1 /*
2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include <limits.h>
12 #include <math.h>
13 #include <stdio.h>
14
15 #include "./vpx_dsp_rtcd.h"
16 #include "./vpx_scale_rtcd.h"
17
18 #include "vpx_dsp/vpx_dsp_common.h"
19 #include "vpx_mem/vpx_mem.h"
20 #include "vpx_ports/mem.h"
21 #include "vpx_ports/system_state.h"
22 #include "vpx_scale/vpx_scale.h"
23 #include "vpx_scale/yv12config.h"
24
25 #include "vp9/common/vp9_entropymv.h"
26 #include "vp9/common/vp9_quant_common.h"
27 #include "vp9/common/vp9_reconinter.h" // vp9_setup_dst_planes()
28 #include "vp9/encoder/vp9_aq_variance.h"
29 #include "vp9/encoder/vp9_block.h"
30 #include "vp9/encoder/vp9_encodeframe.h"
31 #include "vp9/encoder/vp9_encodemb.h"
32 #include "vp9/encoder/vp9_encodemv.h"
33 #include "vp9/encoder/vp9_encoder.h"
34 #include "vp9/encoder/vp9_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"
41
42 #define OUTPUT_FPF 0
43 #define ARF_STATS_OUTPUT 0
44 #define COMPLEXITY_STATS_OUTPUT 0
45
46 #define FIRST_PASS_Q 10.0
47 #define NORMAL_BOOST 100
48 #define MIN_ARF_GF_BOOST 250
49 #define MIN_DECAY_FACTOR 0.01
50 #define NEW_MV_MODE_PENALTY 32
51 #define DARK_THRESH 64
52 #define LOW_I_THRESH 24000
53
54 #define NCOUNT_INTRA_THRESH 8192
55 #define NCOUNT_INTRA_FACTOR 3
56
57 #define INTRA_PART 0.005
58 #define DEFAULT_DECAY_LIMIT 0.75
59 #define LOW_SR_DIFF_TRHESH 0.1
60 #define LOW_CODED_ERR_PER_MB 10.0
61 #define NCOUNT_FRAME_II_THRESH 6.0
62 #define BASELINE_ERR_PER_MB 12500.0
63 #define GF_MAX_FRAME_BOOST 96.0
64
65 #ifdef AGGRESSIVE_VBR
66 #define KF_MIN_FRAME_BOOST 40.0
67 #define KF_MAX_FRAME_BOOST 80.0
68 #define MAX_KF_TOT_BOOST 4800
69 #else
70 #define KF_MIN_FRAME_BOOST 40.0
71 #define KF_MAX_FRAME_BOOST 96.0
72 #define MAX_KF_TOT_BOOST 5400
73 #endif
74
75 #define DEFAULT_ZM_FACTOR 0.5
76 #define MINQ_ADJ_LIMIT 48
77 #define MINQ_ADJ_LIMIT_CQ 20
78 #define HIGH_UNDERSHOOT_RATIO 2
79 #define AV_WQ_FACTOR 4.0
80
81 #define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x)-0.000001 : (x) + 0.000001)
82
83 #if ARF_STATS_OUTPUT
84 unsigned int arf_count = 0;
85 #endif
86
87 // Resets the first pass file to the given position using a relative seek from
88 // the current position.
reset_fpf_position(TWO_PASS * p,const FIRSTPASS_STATS * position)89 static void reset_fpf_position(TWO_PASS *p, const FIRSTPASS_STATS *position) {
90 p->stats_in = position;
91 }
92
93 // Read frame stats at an offset from the current position.
read_frame_stats(const TWO_PASS * p,int offset)94 static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
95 if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
96 (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
97 return NULL;
98 }
99
100 return &p->stats_in[offset];
101 }
102
input_stats(TWO_PASS * p,FIRSTPASS_STATS * fps)103 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
104 if (p->stats_in >= p->stats_in_end) return EOF;
105
106 *fps = *p->stats_in;
107 ++p->stats_in;
108 return 1;
109 }
110
output_stats(FIRSTPASS_STATS * stats)111 static void output_stats(FIRSTPASS_STATS *stats) {
112 (void)stats;
113 // TEMP debug code
114 #if OUTPUT_FPF
115 {
116 FILE *fpfile;
117 fpfile = fopen("firstpass.stt", "a");
118
119 fprintf(fpfile,
120 "%12.0lf %12.4lf %12.2lf %12.2lf %12.2lf %12.0lf %12.4lf %12.4lf"
121 "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
122 "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.0lf %12.4lf %12.0lf"
123 "%12.4lf"
124 "\n",
125 stats->frame, stats->weight, stats->intra_error, stats->coded_error,
126 stats->sr_coded_error, stats->frame_noise_energy, stats->pcnt_inter,
127 stats->pcnt_motion, stats->pcnt_second_ref, stats->pcnt_neutral,
128 stats->pcnt_intra_low, stats->pcnt_intra_high,
129 stats->intra_skip_pct, stats->intra_smooth_pct,
130 stats->inactive_zone_rows, stats->inactive_zone_cols, stats->MVr,
131 stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
132 stats->MVcv, stats->mv_in_out_count, stats->count, stats->duration);
133 fclose(fpfile);
134 }
135 #endif
136 }
137
zero_stats(FIRSTPASS_STATS * section)138 static void zero_stats(FIRSTPASS_STATS *section) {
139 section->frame = 0.0;
140 section->weight = 0.0;
141 section->intra_error = 0.0;
142 section->coded_error = 0.0;
143 section->sr_coded_error = 0.0;
144 section->frame_noise_energy = 0.0;
145 section->pcnt_inter = 0.0;
146 section->pcnt_motion = 0.0;
147 section->pcnt_second_ref = 0.0;
148 section->pcnt_neutral = 0.0;
149 section->intra_skip_pct = 0.0;
150 section->intra_smooth_pct = 0.0;
151 section->pcnt_intra_low = 0.0;
152 section->pcnt_intra_high = 0.0;
153 section->inactive_zone_rows = 0.0;
154 section->inactive_zone_cols = 0.0;
155 section->new_mv_count = 0.0;
156 section->MVr = 0.0;
157 section->mvr_abs = 0.0;
158 section->MVc = 0.0;
159 section->mvc_abs = 0.0;
160 section->MVrv = 0.0;
161 section->MVcv = 0.0;
162 section->mv_in_out_count = 0.0;
163 section->count = 0.0;
164 section->duration = 1.0;
165 section->spatial_layer_id = 0;
166 }
167
accumulate_stats(FIRSTPASS_STATS * section,const FIRSTPASS_STATS * frame)168 static void accumulate_stats(FIRSTPASS_STATS *section,
169 const FIRSTPASS_STATS *frame) {
170 section->frame += frame->frame;
171 section->weight += frame->weight;
172 section->spatial_layer_id = frame->spatial_layer_id;
173 section->intra_error += frame->intra_error;
174 section->coded_error += frame->coded_error;
175 section->sr_coded_error += frame->sr_coded_error;
176 section->frame_noise_energy += frame->frame_noise_energy;
177 section->pcnt_inter += frame->pcnt_inter;
178 section->pcnt_motion += frame->pcnt_motion;
179 section->pcnt_second_ref += frame->pcnt_second_ref;
180 section->pcnt_neutral += frame->pcnt_neutral;
181 section->intra_skip_pct += frame->intra_skip_pct;
182 section->intra_smooth_pct += frame->intra_smooth_pct;
183 section->pcnt_intra_low += frame->pcnt_intra_low;
184 section->pcnt_intra_high += frame->pcnt_intra_high;
185 section->inactive_zone_rows += frame->inactive_zone_rows;
186 section->inactive_zone_cols += frame->inactive_zone_cols;
187 section->new_mv_count += frame->new_mv_count;
188 section->MVr += frame->MVr;
189 section->mvr_abs += frame->mvr_abs;
190 section->MVc += frame->MVc;
191 section->mvc_abs += frame->mvc_abs;
192 section->MVrv += frame->MVrv;
193 section->MVcv += frame->MVcv;
194 section->mv_in_out_count += frame->mv_in_out_count;
195 section->count += frame->count;
196 section->duration += frame->duration;
197 }
198
subtract_stats(FIRSTPASS_STATS * section,const FIRSTPASS_STATS * frame)199 static void subtract_stats(FIRSTPASS_STATS *section,
200 const FIRSTPASS_STATS *frame) {
201 section->frame -= frame->frame;
202 section->weight -= frame->weight;
203 section->intra_error -= frame->intra_error;
204 section->coded_error -= frame->coded_error;
205 section->sr_coded_error -= frame->sr_coded_error;
206 section->frame_noise_energy -= frame->frame_noise_energy;
207 section->pcnt_inter -= frame->pcnt_inter;
208 section->pcnt_motion -= frame->pcnt_motion;
209 section->pcnt_second_ref -= frame->pcnt_second_ref;
210 section->pcnt_neutral -= frame->pcnt_neutral;
211 section->intra_skip_pct -= frame->intra_skip_pct;
212 section->intra_smooth_pct -= frame->intra_smooth_pct;
213 section->pcnt_intra_low -= frame->pcnt_intra_low;
214 section->pcnt_intra_high -= frame->pcnt_intra_high;
215 section->inactive_zone_rows -= frame->inactive_zone_rows;
216 section->inactive_zone_cols -= frame->inactive_zone_cols;
217 section->new_mv_count -= frame->new_mv_count;
218 section->MVr -= frame->MVr;
219 section->mvr_abs -= frame->mvr_abs;
220 section->MVc -= frame->MVc;
221 section->mvc_abs -= frame->mvc_abs;
222 section->MVrv -= frame->MVrv;
223 section->MVcv -= frame->MVcv;
224 section->mv_in_out_count -= frame->mv_in_out_count;
225 section->count -= frame->count;
226 section->duration -= frame->duration;
227 }
228
229 // Calculate an active area of the image that discounts formatting
230 // bars and partially discounts other 0 energy areas.
231 #define MIN_ACTIVE_AREA 0.5
232 #define MAX_ACTIVE_AREA 1.0
calculate_active_area(const FRAME_INFO * frame_info,const FIRSTPASS_STATS * this_frame)233 static double calculate_active_area(const FRAME_INFO *frame_info,
234 const FIRSTPASS_STATS *this_frame) {
235 double active_pct;
236
237 active_pct =
238 1.0 -
239 ((this_frame->intra_skip_pct / 2) +
240 ((this_frame->inactive_zone_rows * 2) / (double)frame_info->mb_rows));
241 return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
242 }
243
244 // Get the average weighted error for the clip (or corpus)
get_distribution_av_err(VP9_COMP * cpi,TWO_PASS * const twopass)245 static double get_distribution_av_err(VP9_COMP *cpi, TWO_PASS *const twopass) {
246 const double av_weight =
247 twopass->total_stats.weight / twopass->total_stats.count;
248
249 if (cpi->oxcf.vbr_corpus_complexity)
250 return av_weight * twopass->mean_mod_score;
251 else
252 return (twopass->total_stats.coded_error * av_weight) /
253 twopass->total_stats.count;
254 }
255
256 #define ACT_AREA_CORRECTION 0.5
257 // Calculate a modified Error used in distributing bits between easier and
258 // harder frames.
calculate_mod_frame_score(const VP9_COMP * cpi,const VP9EncoderConfig * oxcf,const FIRSTPASS_STATS * this_frame,const double av_err)259 static double calculate_mod_frame_score(const VP9_COMP *cpi,
260 const VP9EncoderConfig *oxcf,
261 const FIRSTPASS_STATS *this_frame,
262 const double av_err) {
263 double modified_score =
264 av_err * pow(this_frame->coded_error * this_frame->weight /
265 DOUBLE_DIVIDE_CHECK(av_err),
266 oxcf->two_pass_vbrbias / 100.0);
267
268 // Correction for active area. Frames with a reduced active area
269 // (eg due to formatting bars) have a higher error per mb for the
270 // remaining active MBs. The correction here assumes that coding
271 // 0.5N blocks of complexity 2X is a little easier than coding N
272 // blocks of complexity X.
273 modified_score *= pow(calculate_active_area(&cpi->frame_info, this_frame),
274 ACT_AREA_CORRECTION);
275
276 return modified_score;
277 }
278
calc_norm_frame_score(const VP9EncoderConfig * oxcf,const FRAME_INFO * frame_info,const FIRSTPASS_STATS * this_frame,double mean_mod_score,double av_err)279 static double calc_norm_frame_score(const VP9EncoderConfig *oxcf,
280 const FRAME_INFO *frame_info,
281 const FIRSTPASS_STATS *this_frame,
282 double mean_mod_score, double av_err) {
283 double modified_score =
284 av_err * pow(this_frame->coded_error * this_frame->weight /
285 DOUBLE_DIVIDE_CHECK(av_err),
286 oxcf->two_pass_vbrbias / 100.0);
287
288 const double min_score = (double)(oxcf->two_pass_vbrmin_section) / 100.0;
289 const double max_score = (double)(oxcf->two_pass_vbrmax_section) / 100.0;
290
291 // Correction for active area. Frames with a reduced active area
292 // (eg due to formatting bars) have a higher error per mb for the
293 // remaining active MBs. The correction here assumes that coding
294 // 0.5N blocks of complexity 2X is a little easier than coding N
295 // blocks of complexity X.
296 modified_score *=
297 pow(calculate_active_area(frame_info, this_frame), ACT_AREA_CORRECTION);
298
299 // Normalize to a midpoint score.
300 modified_score /= DOUBLE_DIVIDE_CHECK(mean_mod_score);
301 return fclamp(modified_score, min_score, max_score);
302 }
303
calculate_norm_frame_score(const VP9_COMP * cpi,const TWO_PASS * twopass,const VP9EncoderConfig * oxcf,const FIRSTPASS_STATS * this_frame,const double av_err)304 static double calculate_norm_frame_score(const VP9_COMP *cpi,
305 const TWO_PASS *twopass,
306 const VP9EncoderConfig *oxcf,
307 const FIRSTPASS_STATS *this_frame,
308 const double av_err) {
309 return calc_norm_frame_score(oxcf, &cpi->frame_info, this_frame,
310 twopass->mean_mod_score, av_err);
311 }
312
313 // This function returns the maximum target rate per frame.
frame_max_bits(const RATE_CONTROL * rc,const VP9EncoderConfig * oxcf)314 static int frame_max_bits(const RATE_CONTROL *rc,
315 const VP9EncoderConfig *oxcf) {
316 int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
317 (int64_t)oxcf->two_pass_vbrmax_section) /
318 100;
319 if (max_bits < 0)
320 max_bits = 0;
321 else if (max_bits > rc->max_frame_bandwidth)
322 max_bits = rc->max_frame_bandwidth;
323
324 return (int)max_bits;
325 }
326
vp9_init_first_pass(VP9_COMP * cpi)327 void vp9_init_first_pass(VP9_COMP *cpi) {
328 zero_stats(&cpi->twopass.total_stats);
329 }
330
vp9_end_first_pass(VP9_COMP * cpi)331 void vp9_end_first_pass(VP9_COMP *cpi) {
332 output_stats(&cpi->twopass.total_stats);
333 cpi->twopass.first_pass_done = 1;
334 vpx_free(cpi->twopass.fp_mb_float_stats);
335 cpi->twopass.fp_mb_float_stats = NULL;
336 }
337
get_block_variance_fn(BLOCK_SIZE bsize)338 static vpx_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
339 switch (bsize) {
340 case BLOCK_8X8: return vpx_mse8x8;
341 case BLOCK_16X8: return vpx_mse16x8;
342 case BLOCK_8X16: return vpx_mse8x16;
343 default: return vpx_mse16x16;
344 }
345 }
346
get_prediction_error(BLOCK_SIZE bsize,const struct buf_2d * src,const struct buf_2d * ref)347 static unsigned int get_prediction_error(BLOCK_SIZE bsize,
348 const struct buf_2d *src,
349 const struct buf_2d *ref) {
350 unsigned int sse;
351 const vpx_variance_fn_t fn = get_block_variance_fn(bsize);
352 fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
353 return sse;
354 }
355
356 #if CONFIG_VP9_HIGHBITDEPTH
highbd_get_block_variance_fn(BLOCK_SIZE bsize,int bd)357 static vpx_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
358 int bd) {
359 switch (bd) {
360 default:
361 switch (bsize) {
362 case BLOCK_8X8: return vpx_highbd_8_mse8x8;
363 case BLOCK_16X8: return vpx_highbd_8_mse16x8;
364 case BLOCK_8X16: return vpx_highbd_8_mse8x16;
365 default: return vpx_highbd_8_mse16x16;
366 }
367 case 10:
368 switch (bsize) {
369 case BLOCK_8X8: return vpx_highbd_10_mse8x8;
370 case BLOCK_16X8: return vpx_highbd_10_mse16x8;
371 case BLOCK_8X16: return vpx_highbd_10_mse8x16;
372 default: return vpx_highbd_10_mse16x16;
373 }
374 case 12:
375 switch (bsize) {
376 case BLOCK_8X8: return vpx_highbd_12_mse8x8;
377 case BLOCK_16X8: return vpx_highbd_12_mse16x8;
378 case BLOCK_8X16: return vpx_highbd_12_mse8x16;
379 default: return vpx_highbd_12_mse16x16;
380 }
381 }
382 }
383
highbd_get_prediction_error(BLOCK_SIZE bsize,const struct buf_2d * src,const struct buf_2d * ref,int bd)384 static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
385 const struct buf_2d *src,
386 const struct buf_2d *ref,
387 int bd) {
388 unsigned int sse;
389 const vpx_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
390 fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
391 return sse;
392 }
393 #endif // CONFIG_VP9_HIGHBITDEPTH
394
395 // Refine the motion search range according to the frame dimension
396 // for first pass test.
get_search_range(const VP9_COMP * cpi)397 static int get_search_range(const VP9_COMP *cpi) {
398 int sr = 0;
399 const int dim = VPXMIN(cpi->initial_width, cpi->initial_height);
400
401 while ((dim << sr) < MAX_FULL_PEL_VAL) ++sr;
402 return sr;
403 }
404
405 // Reduce limits to keep the motion search within MV_MAX of ref_mv. Not doing
406 // this can be problematic for big videos (8K) and may cause assert failure
407 // (or memory violation) in mv_cost. Limits are only modified if they would
408 // be non-empty. Returns 1 if limits are non-empty.
intersect_limits_with_mv_max(MvLimits * mv_limits,const MV * ref_mv)409 static int intersect_limits_with_mv_max(MvLimits *mv_limits, const MV *ref_mv) {
410 const int row_min =
411 VPXMAX(mv_limits->row_min, (ref_mv->row + 7 - MV_MAX) >> 3);
412 const int row_max =
413 VPXMIN(mv_limits->row_max, (ref_mv->row - 1 + MV_MAX) >> 3);
414 const int col_min =
415 VPXMAX(mv_limits->col_min, (ref_mv->col + 7 - MV_MAX) >> 3);
416 const int col_max =
417 VPXMIN(mv_limits->col_max, (ref_mv->col - 1 + MV_MAX) >> 3);
418 if (row_min > row_max || col_min > col_max) {
419 return 0;
420 }
421 mv_limits->row_min = row_min;
422 mv_limits->row_max = row_max;
423 mv_limits->col_min = col_min;
424 mv_limits->col_max = col_max;
425 return 1;
426 }
427
first_pass_motion_search(VP9_COMP * cpi,MACROBLOCK * x,const MV * ref_mv,MV * best_mv,int * best_motion_err)428 static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
429 const MV *ref_mv, MV *best_mv,
430 int *best_motion_err) {
431 MACROBLOCKD *const xd = &x->e_mbd;
432 MV tmp_mv = { 0, 0 };
433 MV ref_mv_full = { ref_mv->row >> 3, ref_mv->col >> 3 };
434 int num00, tmp_err, n;
435 const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
436 vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
437 const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
438 MV center_mv_full = ref_mv_full;
439 unsigned int start_mv_sad;
440 vp9_sad_fn_ptr_t sad_fn_ptr;
441
442 int step_param = 3;
443 int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
444 const int sr = get_search_range(cpi);
445 const MvLimits tmp_mv_limits = x->mv_limits;
446 step_param += sr;
447 further_steps -= sr;
448
449 if (!intersect_limits_with_mv_max(&x->mv_limits, ref_mv)) {
450 return;
451 }
452
453 // Override the default variance function to use MSE.
454 v_fn_ptr.vf = get_block_variance_fn(bsize);
455 #if CONFIG_VP9_HIGHBITDEPTH
456 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
457 v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, xd->bd);
458 }
459 #endif // CONFIG_VP9_HIGHBITDEPTH
460
461 // Calculate SAD of the start mv
462 clamp_mv(&ref_mv_full, x->mv_limits.col_min, x->mv_limits.col_max,
463 x->mv_limits.row_min, x->mv_limits.row_max);
464 start_mv_sad = get_start_mv_sad(x, &ref_mv_full, ¢er_mv_full,
465 cpi->fn_ptr[bsize].sdf, x->sadperbit16);
466 sad_fn_ptr.sdf = cpi->fn_ptr[bsize].sdf;
467 sad_fn_ptr.sdx4df = cpi->fn_ptr[bsize].sdx4df;
468
469 // Center the initial step/diamond search on best mv.
470 tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, start_mv_sad,
471 &tmp_mv, step_param, x->sadperbit16, &num00,
472 &sad_fn_ptr, ref_mv);
473 if (tmp_err < INT_MAX)
474 tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
475 if (tmp_err < INT_MAX - new_mv_mode_penalty) tmp_err += new_mv_mode_penalty;
476
477 if (tmp_err < *best_motion_err) {
478 *best_motion_err = tmp_err;
479 *best_mv = tmp_mv;
480 }
481
482 // Carry out further step/diamond searches as necessary.
483 n = num00;
484 num00 = 0;
485
486 while (n < further_steps) {
487 ++n;
488
489 if (num00) {
490 --num00;
491 } else {
492 tmp_err = cpi->diamond_search_sad(
493 x, &cpi->ss_cfg, &ref_mv_full, start_mv_sad, &tmp_mv, step_param + n,
494 x->sadperbit16, &num00, &sad_fn_ptr, ref_mv);
495 if (tmp_err < INT_MAX)
496 tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
497 if (tmp_err < INT_MAX - new_mv_mode_penalty)
498 tmp_err += new_mv_mode_penalty;
499
500 if (tmp_err < *best_motion_err) {
501 *best_motion_err = tmp_err;
502 *best_mv = tmp_mv;
503 }
504 }
505 }
506 x->mv_limits = tmp_mv_limits;
507 }
508
get_bsize(const VP9_COMMON * cm,int mb_row,int mb_col)509 static BLOCK_SIZE get_bsize(const VP9_COMMON *cm, int mb_row, int mb_col) {
510 if (2 * mb_col + 1 < cm->mi_cols) {
511 return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_16X16 : BLOCK_16X8;
512 } else {
513 return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_8X16 : BLOCK_8X8;
514 }
515 }
516
find_fp_qindex(vpx_bit_depth_t bit_depth)517 static int find_fp_qindex(vpx_bit_depth_t bit_depth) {
518 int i;
519
520 for (i = 0; i < QINDEX_RANGE; ++i)
521 if (vp9_convert_qindex_to_q(i, bit_depth) >= FIRST_PASS_Q) break;
522
523 if (i == QINDEX_RANGE) i--;
524
525 return i;
526 }
527
set_first_pass_params(VP9_COMP * cpi)528 static void set_first_pass_params(VP9_COMP *cpi) {
529 VP9_COMMON *const cm = &cpi->common;
530 if (!cpi->refresh_alt_ref_frame &&
531 (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY))) {
532 cm->frame_type = KEY_FRAME;
533 } else {
534 cm->frame_type = INTER_FRAME;
535 }
536 // Do not use periodic key frames.
537 cpi->rc.frames_to_key = INT_MAX;
538 }
539
540 // Scale an sse threshold to account for 8/10/12 bit.
scale_sse_threshold(VP9_COMMON * cm,int thresh)541 static int scale_sse_threshold(VP9_COMMON *cm, int thresh) {
542 int ret_val = thresh;
543 #if CONFIG_VP9_HIGHBITDEPTH
544 if (cm->use_highbitdepth) {
545 switch (cm->bit_depth) {
546 case VPX_BITS_8: ret_val = thresh; break;
547 case VPX_BITS_10: ret_val = thresh << 4; break;
548 default:
549 assert(cm->bit_depth == VPX_BITS_12);
550 ret_val = thresh << 8;
551 break;
552 }
553 }
554 #else
555 (void)cm;
556 #endif // CONFIG_VP9_HIGHBITDEPTH
557 return ret_val;
558 }
559
560 // This threshold is used to track blocks where to all intents and purposes
561 // the intra prediction error 0. Though the metric we test against
562 // is technically a sse we are mainly interested in blocks where all the pixels
563 // in the 8 bit domain have an error of <= 1 (where error = sse) so a
564 // linear scaling for 10 and 12 bit gives similar results.
565 #define UL_INTRA_THRESH 50
get_ul_intra_threshold(VP9_COMMON * cm)566 static int get_ul_intra_threshold(VP9_COMMON *cm) {
567 int ret_val = UL_INTRA_THRESH;
568 #if CONFIG_VP9_HIGHBITDEPTH
569 if (cm->use_highbitdepth) {
570 switch (cm->bit_depth) {
571 case VPX_BITS_8: ret_val = UL_INTRA_THRESH; break;
572 case VPX_BITS_10: ret_val = UL_INTRA_THRESH << 2; break;
573 default:
574 assert(cm->bit_depth == VPX_BITS_12);
575 ret_val = UL_INTRA_THRESH << 4;
576 break;
577 }
578 }
579 #else
580 (void)cm;
581 #endif // CONFIG_VP9_HIGHBITDEPTH
582 return ret_val;
583 }
584
585 #define SMOOTH_INTRA_THRESH 4000
get_smooth_intra_threshold(VP9_COMMON * cm)586 static int get_smooth_intra_threshold(VP9_COMMON *cm) {
587 int ret_val = SMOOTH_INTRA_THRESH;
588 #if CONFIG_VP9_HIGHBITDEPTH
589 if (cm->use_highbitdepth) {
590 switch (cm->bit_depth) {
591 case VPX_BITS_8: ret_val = SMOOTH_INTRA_THRESH; break;
592 case VPX_BITS_10: ret_val = SMOOTH_INTRA_THRESH << 4; break;
593 default:
594 assert(cm->bit_depth == VPX_BITS_12);
595 ret_val = SMOOTH_INTRA_THRESH << 8;
596 break;
597 }
598 }
599 #else
600 (void)cm;
601 #endif // CONFIG_VP9_HIGHBITDEPTH
602 return ret_val;
603 }
604
605 #define FP_DN_THRESH 8
606 #define FP_MAX_DN_THRESH 24
607 #define KERNEL_SIZE 3
608
609 // Baseline Kernel weights for first pass noise metric
610 static uint8_t fp_dn_kernel_3[KERNEL_SIZE * KERNEL_SIZE] = { 1, 2, 1, 2, 4,
611 2, 1, 2, 1 };
612
613 // Estimate noise at a single point based on the impact of a spatial kernel
614 // on the point value
fp_estimate_point_noise(uint8_t * src_ptr,const int stride)615 static int fp_estimate_point_noise(uint8_t *src_ptr, const int stride) {
616 int sum_weight = 0;
617 int sum_val = 0;
618 int i, j;
619 int max_diff = 0;
620 int diff;
621 int dn_diff;
622 uint8_t *tmp_ptr;
623 uint8_t *kernel_ptr;
624 uint8_t dn_val;
625 uint8_t centre_val = *src_ptr;
626
627 kernel_ptr = fp_dn_kernel_3;
628
629 // Apply the kernel
630 tmp_ptr = src_ptr - stride - 1;
631 for (i = 0; i < KERNEL_SIZE; ++i) {
632 for (j = 0; j < KERNEL_SIZE; ++j) {
633 diff = abs((int)centre_val - (int)tmp_ptr[j]);
634 max_diff = VPXMAX(max_diff, diff);
635 if (diff <= FP_DN_THRESH) {
636 sum_weight += *kernel_ptr;
637 sum_val += (int)tmp_ptr[j] * (int)*kernel_ptr;
638 }
639 ++kernel_ptr;
640 }
641 tmp_ptr += stride;
642 }
643
644 if (max_diff < FP_MAX_DN_THRESH)
645 // Update the source value with the new filtered value
646 dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
647 else
648 dn_val = *src_ptr;
649
650 // return the noise energy as the square of the difference between the
651 // denoised and raw value.
652 dn_diff = (int)*src_ptr - (int)dn_val;
653 return dn_diff * dn_diff;
654 }
655 #if CONFIG_VP9_HIGHBITDEPTH
fp_highbd_estimate_point_noise(uint8_t * src_ptr,const int stride)656 static int fp_highbd_estimate_point_noise(uint8_t *src_ptr, const int stride) {
657 int sum_weight = 0;
658 int sum_val = 0;
659 int i, j;
660 int max_diff = 0;
661 int diff;
662 int dn_diff;
663 uint8_t *tmp_ptr;
664 uint16_t *tmp_ptr16;
665 uint8_t *kernel_ptr;
666 uint16_t dn_val;
667 uint16_t centre_val = *CONVERT_TO_SHORTPTR(src_ptr);
668
669 kernel_ptr = fp_dn_kernel_3;
670
671 // Apply the kernel
672 tmp_ptr = src_ptr - stride - 1;
673 for (i = 0; i < KERNEL_SIZE; ++i) {
674 tmp_ptr16 = CONVERT_TO_SHORTPTR(tmp_ptr);
675 for (j = 0; j < KERNEL_SIZE; ++j) {
676 diff = abs((int)centre_val - (int)tmp_ptr16[j]);
677 max_diff = VPXMAX(max_diff, diff);
678 if (diff <= FP_DN_THRESH) {
679 sum_weight += *kernel_ptr;
680 sum_val += (int)tmp_ptr16[j] * (int)*kernel_ptr;
681 }
682 ++kernel_ptr;
683 }
684 tmp_ptr += stride;
685 }
686
687 if (max_diff < FP_MAX_DN_THRESH)
688 // Update the source value with the new filtered value
689 dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
690 else
691 dn_val = *CONVERT_TO_SHORTPTR(src_ptr);
692
693 // return the noise energy as the square of the difference between the
694 // denoised and raw value.
695 dn_diff = (int)(*CONVERT_TO_SHORTPTR(src_ptr)) - (int)dn_val;
696 return dn_diff * dn_diff;
697 }
698 #endif
699
700 // Estimate noise for a block.
fp_estimate_block_noise(MACROBLOCK * x,BLOCK_SIZE bsize)701 static int fp_estimate_block_noise(MACROBLOCK *x, BLOCK_SIZE bsize) {
702 #if CONFIG_VP9_HIGHBITDEPTH
703 MACROBLOCKD *xd = &x->e_mbd;
704 #endif
705 uint8_t *src_ptr = &x->plane[0].src.buf[0];
706 const int width = num_4x4_blocks_wide_lookup[bsize] * 4;
707 const int height = num_4x4_blocks_high_lookup[bsize] * 4;
708 int w, h;
709 int stride = x->plane[0].src.stride;
710 int block_noise = 0;
711
712 // Sampled points to reduce cost overhead.
713 for (h = 0; h < height; h += 2) {
714 for (w = 0; w < width; w += 2) {
715 #if CONFIG_VP9_HIGHBITDEPTH
716 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
717 block_noise += fp_highbd_estimate_point_noise(src_ptr, stride);
718 else
719 block_noise += fp_estimate_point_noise(src_ptr, stride);
720 #else
721 block_noise += fp_estimate_point_noise(src_ptr, stride);
722 #endif
723 ++src_ptr;
724 }
725 src_ptr += (stride - width);
726 }
727 return block_noise << 2; // Scale << 2 to account for sampling.
728 }
729
730 // This function is called to test the functionality of row based
731 // multi-threading in unit tests for bit-exactness
accumulate_floating_point_stats(VP9_COMP * cpi,TileDataEnc * first_tile_col)732 static void accumulate_floating_point_stats(VP9_COMP *cpi,
733 TileDataEnc *first_tile_col) {
734 VP9_COMMON *const cm = &cpi->common;
735 int mb_row, mb_col;
736 first_tile_col->fp_data.intra_factor = 0;
737 first_tile_col->fp_data.brightness_factor = 0;
738 first_tile_col->fp_data.neutral_count = 0;
739 for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
740 for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
741 const int mb_index = mb_row * cm->mb_cols + mb_col;
742 first_tile_col->fp_data.intra_factor +=
743 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_intra_factor;
744 first_tile_col->fp_data.brightness_factor +=
745 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_brightness_factor;
746 first_tile_col->fp_data.neutral_count +=
747 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_neutral_count;
748 }
749 }
750 }
751
first_pass_stat_calc(VP9_COMP * cpi,FIRSTPASS_STATS * fps,FIRSTPASS_DATA * fp_acc_data)752 static void first_pass_stat_calc(VP9_COMP *cpi, FIRSTPASS_STATS *fps,
753 FIRSTPASS_DATA *fp_acc_data) {
754 VP9_COMMON *const cm = &cpi->common;
755 // The minimum error here insures some bit allocation to frames even
756 // in static regions. The allocation per MB declines for larger formats
757 // where the typical "real" energy per MB also falls.
758 // Initial estimate here uses sqrt(mbs) to define the min_err, where the
759 // number of mbs is proportional to the image area.
760 const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
761 : cpi->common.MBs;
762 const double min_err = 200 * sqrt(num_mbs);
763
764 // Clamp the image start to rows/2. This number of rows is discarded top
765 // and bottom as dead data so rows / 2 means the frame is blank.
766 if ((fp_acc_data->image_data_start_row > cm->mb_rows / 2) ||
767 (fp_acc_data->image_data_start_row == INVALID_ROW)) {
768 fp_acc_data->image_data_start_row = cm->mb_rows / 2;
769 }
770 // Exclude any image dead zone
771 if (fp_acc_data->image_data_start_row > 0) {
772 fp_acc_data->intra_skip_count =
773 VPXMAX(0, fp_acc_data->intra_skip_count -
774 (fp_acc_data->image_data_start_row * cm->mb_cols * 2));
775 }
776
777 fp_acc_data->intra_factor = fp_acc_data->intra_factor / (double)num_mbs;
778 fp_acc_data->brightness_factor =
779 fp_acc_data->brightness_factor / (double)num_mbs;
780 fps->weight = fp_acc_data->intra_factor * fp_acc_data->brightness_factor;
781
782 fps->frame = cm->current_video_frame;
783 fps->spatial_layer_id = cpi->svc.spatial_layer_id;
784
785 fps->coded_error =
786 ((double)(fp_acc_data->coded_error >> 8) + min_err) / num_mbs;
787 fps->sr_coded_error =
788 ((double)(fp_acc_data->sr_coded_error >> 8) + min_err) / num_mbs;
789 fps->intra_error =
790 ((double)(fp_acc_data->intra_error >> 8) + min_err) / num_mbs;
791
792 fps->frame_noise_energy =
793 (double)(fp_acc_data->frame_noise_energy) / (double)num_mbs;
794 fps->count = 1.0;
795 fps->pcnt_inter = (double)(fp_acc_data->intercount) / num_mbs;
796 fps->pcnt_second_ref = (double)(fp_acc_data->second_ref_count) / num_mbs;
797 fps->pcnt_neutral = (double)(fp_acc_data->neutral_count) / num_mbs;
798 fps->pcnt_intra_low = (double)(fp_acc_data->intra_count_low) / num_mbs;
799 fps->pcnt_intra_high = (double)(fp_acc_data->intra_count_high) / num_mbs;
800 fps->intra_skip_pct = (double)(fp_acc_data->intra_skip_count) / num_mbs;
801 fps->intra_smooth_pct = (double)(fp_acc_data->intra_smooth_count) / num_mbs;
802 fps->inactive_zone_rows = (double)(fp_acc_data->image_data_start_row);
803 // Currently set to 0 as most issues relate to letter boxing.
804 fps->inactive_zone_cols = (double)0;
805
806 if (fp_acc_data->mvcount > 0) {
807 fps->new_mv_count = (double)(fp_acc_data->new_mv_count) / num_mbs;
808 fps->MVr = (double)(fp_acc_data->sum_mvr) / fp_acc_data->mvcount;
809 fps->mvr_abs = (double)(fp_acc_data->sum_mvr_abs) / fp_acc_data->mvcount;
810 fps->MVc = (double)(fp_acc_data->sum_mvc) / fp_acc_data->mvcount;
811 fps->mvc_abs = (double)(fp_acc_data->sum_mvc_abs) / fp_acc_data->mvcount;
812 fps->MVrv = ((double)(fp_acc_data->sum_mvrs) -
813 ((double)(fp_acc_data->sum_mvr) * (fp_acc_data->sum_mvr) /
814 fp_acc_data->mvcount)) /
815 fp_acc_data->mvcount;
816 fps->MVcv = ((double)(fp_acc_data->sum_mvcs) -
817 ((double)(fp_acc_data->sum_mvc) * (fp_acc_data->sum_mvc) /
818 fp_acc_data->mvcount)) /
819 fp_acc_data->mvcount;
820 fps->mv_in_out_count =
821 (double)(fp_acc_data->sum_in_vectors) / (fp_acc_data->mvcount * 2);
822 fps->pcnt_motion = (double)(fp_acc_data->mvcount) / num_mbs;
823 } else {
824 fps->new_mv_count = 0.0;
825 fps->MVr = 0.0;
826 fps->mvr_abs = 0.0;
827 fps->MVc = 0.0;
828 fps->mvc_abs = 0.0;
829 fps->MVrv = 0.0;
830 fps->MVcv = 0.0;
831 fps->mv_in_out_count = 0.0;
832 fps->pcnt_motion = 0.0;
833 }
834 }
835
accumulate_fp_mb_row_stat(TileDataEnc * this_tile,FIRSTPASS_DATA * fp_acc_data)836 static void accumulate_fp_mb_row_stat(TileDataEnc *this_tile,
837 FIRSTPASS_DATA *fp_acc_data) {
838 this_tile->fp_data.intra_factor += fp_acc_data->intra_factor;
839 this_tile->fp_data.brightness_factor += fp_acc_data->brightness_factor;
840 this_tile->fp_data.coded_error += fp_acc_data->coded_error;
841 this_tile->fp_data.sr_coded_error += fp_acc_data->sr_coded_error;
842 this_tile->fp_data.frame_noise_energy += fp_acc_data->frame_noise_energy;
843 this_tile->fp_data.intra_error += fp_acc_data->intra_error;
844 this_tile->fp_data.intercount += fp_acc_data->intercount;
845 this_tile->fp_data.second_ref_count += fp_acc_data->second_ref_count;
846 this_tile->fp_data.neutral_count += fp_acc_data->neutral_count;
847 this_tile->fp_data.intra_count_low += fp_acc_data->intra_count_low;
848 this_tile->fp_data.intra_count_high += fp_acc_data->intra_count_high;
849 this_tile->fp_data.intra_skip_count += fp_acc_data->intra_skip_count;
850 this_tile->fp_data.new_mv_count += fp_acc_data->new_mv_count;
851 this_tile->fp_data.mvcount += fp_acc_data->mvcount;
852 this_tile->fp_data.sum_mvr += fp_acc_data->sum_mvr;
853 this_tile->fp_data.sum_mvr_abs += fp_acc_data->sum_mvr_abs;
854 this_tile->fp_data.sum_mvc += fp_acc_data->sum_mvc;
855 this_tile->fp_data.sum_mvc_abs += fp_acc_data->sum_mvc_abs;
856 this_tile->fp_data.sum_mvrs += fp_acc_data->sum_mvrs;
857 this_tile->fp_data.sum_mvcs += fp_acc_data->sum_mvcs;
858 this_tile->fp_data.sum_in_vectors += fp_acc_data->sum_in_vectors;
859 this_tile->fp_data.intra_smooth_count += fp_acc_data->intra_smooth_count;
860 this_tile->fp_data.image_data_start_row =
861 VPXMIN(this_tile->fp_data.image_data_start_row,
862 fp_acc_data->image_data_start_row) == INVALID_ROW
863 ? VPXMAX(this_tile->fp_data.image_data_start_row,
864 fp_acc_data->image_data_start_row)
865 : VPXMIN(this_tile->fp_data.image_data_start_row,
866 fp_acc_data->image_data_start_row);
867 }
868
869 #if CONFIG_RATE_CTRL
store_fp_motion_vector(VP9_COMP * cpi,const MV * mv,const int mb_row,const int mb_col,MV_REFERENCE_FRAME frame_type,const int mv_idx)870 static void store_fp_motion_vector(VP9_COMP *cpi, const MV *mv,
871 const int mb_row, const int mb_col,
872 MV_REFERENCE_FRAME frame_type,
873 const int mv_idx) {
874 VP9_COMMON *const cm = &cpi->common;
875 const int mb_index = mb_row * cm->mb_cols + mb_col;
876 MOTION_VECTOR_INFO *this_motion_vector_info =
877 &cpi->fp_motion_vector_info[mb_index];
878 this_motion_vector_info->ref_frame[mv_idx] = frame_type;
879 if (frame_type != INTRA_FRAME) {
880 this_motion_vector_info->mv[mv_idx].as_mv = *mv;
881 }
882 }
883 #endif // CONFIG_RATE_CTRL
884
885 #define NZ_MOTION_PENALTY 128
886 #define INTRA_MODE_PENALTY 1024
vp9_first_pass_encode_tile_mb_row(VP9_COMP * cpi,ThreadData * td,FIRSTPASS_DATA * fp_acc_data,TileDataEnc * tile_data,MV * best_ref_mv,int mb_row)887 void vp9_first_pass_encode_tile_mb_row(VP9_COMP *cpi, ThreadData *td,
888 FIRSTPASS_DATA *fp_acc_data,
889 TileDataEnc *tile_data, MV *best_ref_mv,
890 int mb_row) {
891 int mb_col;
892 MACROBLOCK *const x = &td->mb;
893 VP9_COMMON *const cm = &cpi->common;
894 MACROBLOCKD *const xd = &x->e_mbd;
895 TileInfo tile = tile_data->tile_info;
896 const int mb_col_start = ROUND_POWER_OF_TWO(tile.mi_col_start, 1);
897 const int mb_col_end = ROUND_POWER_OF_TWO(tile.mi_col_end, 1);
898 struct macroblock_plane *const p = x->plane;
899 struct macroblockd_plane *const pd = xd->plane;
900 const PICK_MODE_CONTEXT *ctx = &td->pc_root->none;
901 int i, c;
902 int num_mb_cols = get_num_cols(tile_data->tile_info, 1);
903
904 int recon_yoffset, recon_uvoffset;
905 const int intrapenalty = INTRA_MODE_PENALTY;
906 const MV zero_mv = { 0, 0 };
907 int recon_y_stride, recon_uv_stride, uv_mb_height;
908
909 YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
910 YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
911 YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
912 const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
913
914 MODE_INFO mi_above, mi_left;
915
916 double mb_intra_factor;
917 double mb_brightness_factor;
918 double mb_neutral_count;
919 int scaled_low_intra_thresh = scale_sse_threshold(cm, LOW_I_THRESH);
920
921 MV *first_top_mv = &tile_data->firstpass_top_mv;
922 MV last_nonzero_mv = { 0, 0 };
923
924 // First pass code requires valid last and new frame buffers.
925 assert(new_yv12 != NULL);
926 assert(frame_is_intra_only(cm) || (lst_yv12 != NULL));
927
928 xd->mi = cm->mi_grid_visible + xd->mi_stride * (mb_row << 1) + mb_col_start;
929 xd->mi[0] = cm->mi + xd->mi_stride * (mb_row << 1) + mb_col_start;
930
931 for (i = 0; i < MAX_MB_PLANE; ++i) {
932 p[i].coeff = ctx->coeff_pbuf[i][1];
933 p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
934 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
935 p[i].eobs = ctx->eobs_pbuf[i][1];
936 }
937
938 recon_y_stride = new_yv12->y_stride;
939 recon_uv_stride = new_yv12->uv_stride;
940 uv_mb_height = 16 >> (new_yv12->y_height > new_yv12->uv_height);
941
942 // Reset above block coeffs.
943 recon_yoffset = (mb_row * recon_y_stride * 16) + mb_col_start * 16;
944 recon_uvoffset =
945 (mb_row * recon_uv_stride * uv_mb_height) + mb_col_start * uv_mb_height;
946
947 // Set up limit values for motion vectors to prevent them extending
948 // outside the UMV borders.
949 x->mv_limits.row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
950 x->mv_limits.row_max =
951 ((cm->mb_rows - 1 - mb_row) * 16) + BORDER_MV_PIXELS_B16;
952
953 for (mb_col = mb_col_start, c = 0; mb_col < mb_col_end; ++mb_col, c++) {
954 int this_error;
955 int this_intra_error;
956 const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
957 const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
958 double log_intra;
959 int level_sample;
960 const int mb_index = mb_row * cm->mb_cols + mb_col;
961
962 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, mb_row, c);
963
964 if (mb_col == mb_col_start) {
965 last_nonzero_mv = *first_top_mv;
966 }
967
968 // Adjust to the next column of MBs.
969 x->plane[0].src.buf = cpi->Source->y_buffer +
970 mb_row * 16 * x->plane[0].src.stride + mb_col * 16;
971 x->plane[1].src.buf = cpi->Source->u_buffer +
972 mb_row * uv_mb_height * x->plane[1].src.stride +
973 mb_col * uv_mb_height;
974 x->plane[2].src.buf = cpi->Source->v_buffer +
975 mb_row * uv_mb_height * x->plane[1].src.stride +
976 mb_col * uv_mb_height;
977
978 vpx_clear_system_state();
979
980 xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
981 xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
982 xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
983 xd->mi[0]->sb_type = bsize;
984 xd->mi[0]->ref_frame[0] = INTRA_FRAME;
985 set_mi_row_col(xd, &tile, mb_row << 1, num_8x8_blocks_high_lookup[bsize],
986 mb_col << 1, num_8x8_blocks_wide_lookup[bsize], cm->mi_rows,
987 cm->mi_cols);
988 // Are edges available for intra prediction?
989 // Since the firstpass does not populate the mi_grid_visible,
990 // above_mi/left_mi must be overwritten with a nonzero value when edges
991 // are available. Required by vp9_predict_intra_block().
992 xd->above_mi = (mb_row != 0) ? &mi_above : NULL;
993 xd->left_mi = ((mb_col << 1) > tile.mi_col_start) ? &mi_left : NULL;
994
995 // Do intra 16x16 prediction.
996 x->skip_encode = 0;
997 x->fp_src_pred = 0;
998 // Do intra prediction based on source pixels for tile boundaries
999 if (mb_col == mb_col_start && mb_col != 0) {
1000 xd->left_mi = &mi_left;
1001 x->fp_src_pred = 1;
1002 }
1003 xd->mi[0]->mode = DC_PRED;
1004 xd->mi[0]->tx_size =
1005 use_dc_pred ? (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
1006 // Fix - zero the 16x16 block first. This ensures correct this_error for
1007 // block sizes smaller than 16x16.
1008 vp9_zero_array(x->plane[0].src_diff, 256);
1009 vp9_encode_intra_block_plane(x, bsize, 0, 0);
1010 this_error = vpx_get_mb_ss(x->plane[0].src_diff);
1011 this_intra_error = this_error;
1012
1013 // Keep a record of blocks that have very low intra error residual
1014 // (i.e. are in effect completely flat and untextured in the intra
1015 // domain). In natural videos this is uncommon, but it is much more
1016 // common in animations, graphics and screen content, so may be used
1017 // as a signal to detect these types of content.
1018 if (this_error < get_ul_intra_threshold(cm)) {
1019 ++(fp_acc_data->intra_skip_count);
1020 } else if ((mb_col > 0) &&
1021 (fp_acc_data->image_data_start_row == INVALID_ROW)) {
1022 fp_acc_data->image_data_start_row = mb_row;
1023 }
1024
1025 // Blocks that are mainly smooth in the intra domain.
1026 // Some special accounting for CQ but also these are better for testing
1027 // noise levels.
1028 if (this_error < get_smooth_intra_threshold(cm)) {
1029 ++(fp_acc_data->intra_smooth_count);
1030 }
1031
1032 // Special case noise measurement for first frame.
1033 if (cm->current_video_frame == 0) {
1034 if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH)) {
1035 fp_acc_data->frame_noise_energy += fp_estimate_block_noise(x, bsize);
1036 } else {
1037 fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1038 }
1039 }
1040
1041 #if CONFIG_VP9_HIGHBITDEPTH
1042 if (cm->use_highbitdepth) {
1043 switch (cm->bit_depth) {
1044 case VPX_BITS_8: break;
1045 case VPX_BITS_10: this_error >>= 4; break;
1046 default:
1047 assert(cm->bit_depth == VPX_BITS_12);
1048 this_error >>= 8;
1049 break;
1050 }
1051 }
1052 #endif // CONFIG_VP9_HIGHBITDEPTH
1053
1054 vpx_clear_system_state();
1055 log_intra = log(this_error + 1.0);
1056 if (log_intra < 10.0) {
1057 mb_intra_factor = 1.0 + ((10.0 - log_intra) * 0.05);
1058 fp_acc_data->intra_factor += mb_intra_factor;
1059 if (cpi->row_mt_bit_exact)
1060 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_intra_factor =
1061 mb_intra_factor;
1062 } else {
1063 fp_acc_data->intra_factor += 1.0;
1064 if (cpi->row_mt_bit_exact)
1065 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_intra_factor = 1.0;
1066 }
1067
1068 #if CONFIG_VP9_HIGHBITDEPTH
1069 if (cm->use_highbitdepth)
1070 level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
1071 else
1072 level_sample = x->plane[0].src.buf[0];
1073 #else
1074 level_sample = x->plane[0].src.buf[0];
1075 #endif
1076 if ((level_sample < DARK_THRESH) && (log_intra < 9.0)) {
1077 mb_brightness_factor = 1.0 + (0.01 * (DARK_THRESH - level_sample));
1078 fp_acc_data->brightness_factor += mb_brightness_factor;
1079 if (cpi->row_mt_bit_exact)
1080 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_brightness_factor =
1081 mb_brightness_factor;
1082 } else {
1083 fp_acc_data->brightness_factor += 1.0;
1084 if (cpi->row_mt_bit_exact)
1085 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_brightness_factor =
1086 1.0;
1087 }
1088
1089 // Intrapenalty below deals with situations where the intra and inter
1090 // error scores are very low (e.g. a plain black frame).
1091 // We do not have special cases in first pass for 0,0 and nearest etc so
1092 // all inter modes carry an overhead cost estimate for the mv.
1093 // When the error score is very low this causes us to pick all or lots of
1094 // INTRA modes and throw lots of key frames.
1095 // This penalty adds a cost matching that of a 0,0 mv to the intra case.
1096 this_error += intrapenalty;
1097
1098 // Accumulate the intra error.
1099 fp_acc_data->intra_error += (int64_t)this_error;
1100
1101 // Set up limit values for motion vectors to prevent them extending
1102 // outside the UMV borders.
1103 x->mv_limits.col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
1104 x->mv_limits.col_max =
1105 ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
1106
1107 // Other than for intra-only frame do a motion search.
1108 if (!frame_is_intra_only(cm)) {
1109 int tmp_err, motion_error, this_motion_error, raw_motion_error;
1110 // Assume 0,0 motion with no mv overhead.
1111 MV mv = { 0, 0 }, tmp_mv = { 0, 0 };
1112 struct buf_2d unscaled_last_source_buf_2d;
1113 vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
1114
1115 #if CONFIG_RATE_CTRL
1116 if (cpi->oxcf.use_simple_encode_api) {
1117 // Store zero mv as default
1118 store_fp_motion_vector(cpi, &mv, mb_row, mb_col, LAST_FRAME, 0);
1119 }
1120 #endif // CONFIG_RAGE_CTRL
1121
1122 xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
1123 #if CONFIG_VP9_HIGHBITDEPTH
1124 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1125 motion_error = highbd_get_prediction_error(
1126 bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
1127 this_motion_error = highbd_get_prediction_error(
1128 bsize, &x->plane[0].src, &xd->plane[0].pre[0], 8);
1129 } else {
1130 motion_error =
1131 get_prediction_error(bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
1132 this_motion_error = motion_error;
1133 }
1134 #else
1135 motion_error =
1136 get_prediction_error(bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
1137 this_motion_error = motion_error;
1138 #endif // CONFIG_VP9_HIGHBITDEPTH
1139
1140 // Compute the motion error of the 0,0 motion using the last source
1141 // frame as the reference. Skip the further motion search on
1142 // reconstructed frame if this error is very small.
1143 unscaled_last_source_buf_2d.buf =
1144 cpi->unscaled_last_source->y_buffer + recon_yoffset;
1145 unscaled_last_source_buf_2d.stride = cpi->unscaled_last_source->y_stride;
1146 #if CONFIG_VP9_HIGHBITDEPTH
1147 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1148 raw_motion_error = highbd_get_prediction_error(
1149 bsize, &x->plane[0].src, &unscaled_last_source_buf_2d, xd->bd);
1150 } else {
1151 raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1152 &unscaled_last_source_buf_2d);
1153 }
1154 #else
1155 raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1156 &unscaled_last_source_buf_2d);
1157 #endif // CONFIG_VP9_HIGHBITDEPTH
1158
1159 if (raw_motion_error > NZ_MOTION_PENALTY) {
1160 // Test last reference frame using the previous best mv as the
1161 // starting point (best reference) for the search.
1162 first_pass_motion_search(cpi, x, best_ref_mv, &mv, &motion_error);
1163
1164 v_fn_ptr.vf = get_block_variance_fn(bsize);
1165 #if CONFIG_VP9_HIGHBITDEPTH
1166 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1167 v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, 8);
1168 }
1169 #endif // CONFIG_VP9_HIGHBITDEPTH
1170 this_motion_error =
1171 vp9_get_mvpred_var(x, &mv, best_ref_mv, &v_fn_ptr, 0);
1172
1173 // If the current best reference mv is not centered on 0,0 then do a
1174 // 0,0 based search as well.
1175 if (!is_zero_mv(best_ref_mv)) {
1176 tmp_err = INT_MAX;
1177 first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &tmp_err);
1178
1179 if (tmp_err < motion_error) {
1180 motion_error = tmp_err;
1181 mv = tmp_mv;
1182 this_motion_error =
1183 vp9_get_mvpred_var(x, &tmp_mv, &zero_mv, &v_fn_ptr, 0);
1184 }
1185 }
1186 #if CONFIG_RATE_CTRL
1187 if (cpi->oxcf.use_simple_encode_api) {
1188 store_fp_motion_vector(cpi, &mv, mb_row, mb_col, LAST_FRAME, 0);
1189 }
1190 #endif // CONFIG_RAGE_CTRL
1191
1192 // Search in an older reference frame.
1193 if ((cm->current_video_frame > 1) && gld_yv12 != NULL) {
1194 // Assume 0,0 motion with no mv overhead.
1195 int gf_motion_error;
1196
1197 xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
1198 #if CONFIG_VP9_HIGHBITDEPTH
1199 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1200 gf_motion_error = highbd_get_prediction_error(
1201 bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
1202 } else {
1203 gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1204 &xd->plane[0].pre[0]);
1205 }
1206 #else
1207 gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1208 &xd->plane[0].pre[0]);
1209 #endif // CONFIG_VP9_HIGHBITDEPTH
1210
1211 first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &gf_motion_error);
1212 #if CONFIG_RATE_CTRL
1213 if (cpi->oxcf.use_simple_encode_api) {
1214 store_fp_motion_vector(cpi, &tmp_mv, mb_row, mb_col, GOLDEN_FRAME,
1215 1);
1216 }
1217 #endif // CONFIG_RAGE_CTRL
1218
1219 if (gf_motion_error < motion_error && gf_motion_error < this_error)
1220 ++(fp_acc_data->second_ref_count);
1221
1222 // Reset to last frame as reference buffer.
1223 xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
1224 xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
1225 xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
1226
1227 // In accumulating a score for the older reference frame take the
1228 // best of the motion predicted score and the intra coded error
1229 // (just as will be done for) accumulation of "coded_error" for
1230 // the last frame.
1231 if (gf_motion_error < this_error)
1232 fp_acc_data->sr_coded_error += gf_motion_error;
1233 else
1234 fp_acc_data->sr_coded_error += this_error;
1235 } else {
1236 fp_acc_data->sr_coded_error += motion_error;
1237 }
1238 } else {
1239 fp_acc_data->sr_coded_error += motion_error;
1240 }
1241
1242 // Start by assuming that intra mode is best.
1243 best_ref_mv->row = 0;
1244 best_ref_mv->col = 0;
1245
1246 if (motion_error <= this_error) {
1247 vpx_clear_system_state();
1248
1249 // Keep a count of cases where the inter and intra were very close
1250 // and very low. This helps with scene cut detection for example in
1251 // cropped clips with black bars at the sides or top and bottom.
1252 if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
1253 (this_error < (2 * intrapenalty))) {
1254 fp_acc_data->neutral_count += 1.0;
1255 if (cpi->row_mt_bit_exact)
1256 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_neutral_count =
1257 1.0;
1258 // Also track cases where the intra is not much worse than the inter
1259 // and use this in limiting the GF/arf group length.
1260 } else if ((this_error > NCOUNT_INTRA_THRESH) &&
1261 (this_error < (NCOUNT_INTRA_FACTOR * motion_error))) {
1262 mb_neutral_count =
1263 (double)motion_error / DOUBLE_DIVIDE_CHECK((double)this_error);
1264 fp_acc_data->neutral_count += mb_neutral_count;
1265 if (cpi->row_mt_bit_exact)
1266 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_neutral_count =
1267 mb_neutral_count;
1268 }
1269
1270 mv.row *= 8;
1271 mv.col *= 8;
1272 this_error = motion_error;
1273 xd->mi[0]->mode = NEWMV;
1274 xd->mi[0]->mv[0].as_mv = mv;
1275 xd->mi[0]->tx_size = TX_4X4;
1276 xd->mi[0]->ref_frame[0] = LAST_FRAME;
1277 xd->mi[0]->ref_frame[1] = NO_REF_FRAME;
1278 vp9_build_inter_predictors_sby(xd, mb_row << 1, mb_col << 1, bsize);
1279 vp9_encode_sby_pass1(x, bsize);
1280 fp_acc_data->sum_mvr += mv.row;
1281 fp_acc_data->sum_mvr_abs += abs(mv.row);
1282 fp_acc_data->sum_mvc += mv.col;
1283 fp_acc_data->sum_mvc_abs += abs(mv.col);
1284 fp_acc_data->sum_mvrs += mv.row * mv.row;
1285 fp_acc_data->sum_mvcs += mv.col * mv.col;
1286 ++(fp_acc_data->intercount);
1287
1288 *best_ref_mv = mv;
1289
1290 if (!is_zero_mv(&mv)) {
1291 ++(fp_acc_data->mvcount);
1292 if (!is_equal_mv(&mv, &last_nonzero_mv)) {
1293 ++(fp_acc_data->new_mv_count);
1294 }
1295 last_nonzero_mv = mv;
1296
1297 // Does the row vector point inwards or outwards?
1298 if (mb_row < cm->mb_rows / 2) {
1299 if (mv.row > 0)
1300 --(fp_acc_data->sum_in_vectors);
1301 else if (mv.row < 0)
1302 ++(fp_acc_data->sum_in_vectors);
1303 } else if (mb_row > cm->mb_rows / 2) {
1304 if (mv.row > 0)
1305 ++(fp_acc_data->sum_in_vectors);
1306 else if (mv.row < 0)
1307 --(fp_acc_data->sum_in_vectors);
1308 }
1309
1310 // Does the col vector point inwards or outwards?
1311 if (mb_col < cm->mb_cols / 2) {
1312 if (mv.col > 0)
1313 --(fp_acc_data->sum_in_vectors);
1314 else if (mv.col < 0)
1315 ++(fp_acc_data->sum_in_vectors);
1316 } else if (mb_col > cm->mb_cols / 2) {
1317 if (mv.col > 0)
1318 ++(fp_acc_data->sum_in_vectors);
1319 else if (mv.col < 0)
1320 --(fp_acc_data->sum_in_vectors);
1321 }
1322 }
1323 if (this_intra_error < scaled_low_intra_thresh) {
1324 fp_acc_data->frame_noise_energy += fp_estimate_block_noise(x, bsize);
1325 } else {
1326 fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1327 }
1328 } else { // Intra < inter error
1329 if (this_intra_error < scaled_low_intra_thresh) {
1330 fp_acc_data->frame_noise_energy += fp_estimate_block_noise(x, bsize);
1331 if (this_motion_error < scaled_low_intra_thresh) {
1332 fp_acc_data->intra_count_low += 1.0;
1333 } else {
1334 fp_acc_data->intra_count_high += 1.0;
1335 }
1336 } else {
1337 fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1338 fp_acc_data->intra_count_high += 1.0;
1339 }
1340 }
1341 } else {
1342 fp_acc_data->sr_coded_error += (int64_t)this_error;
1343 #if CONFIG_RATE_CTRL
1344 if (cpi->oxcf.use_simple_encode_api) {
1345 store_fp_motion_vector(cpi, NULL, mb_row, mb_col, INTRA_FRAME, 0);
1346 }
1347 #endif // CONFIG_RAGE_CTRL
1348 }
1349 fp_acc_data->coded_error += (int64_t)this_error;
1350
1351 if (mb_col == mb_col_start) {
1352 *first_top_mv = last_nonzero_mv;
1353 }
1354 recon_yoffset += 16;
1355 recon_uvoffset += uv_mb_height;
1356
1357 // Accumulate row level stats to the corresponding tile stats
1358 if (cpi->row_mt && mb_col == mb_col_end - 1)
1359 accumulate_fp_mb_row_stat(tile_data, fp_acc_data);
1360
1361 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, mb_row, c,
1362 num_mb_cols);
1363 }
1364 vpx_clear_system_state();
1365 }
1366
first_pass_encode(VP9_COMP * cpi,FIRSTPASS_DATA * fp_acc_data)1367 static void first_pass_encode(VP9_COMP *cpi, FIRSTPASS_DATA *fp_acc_data) {
1368 VP9_COMMON *const cm = &cpi->common;
1369 int mb_row;
1370 TileDataEnc tile_data;
1371 TileInfo *tile = &tile_data.tile_info;
1372 MV zero_mv = { 0, 0 };
1373 MV best_ref_mv;
1374 // Tiling is ignored in the first pass.
1375 vp9_tile_init(tile, cm, 0, 0);
1376 tile_data.firstpass_top_mv = zero_mv;
1377 #if CONFIG_RATE_CTRL
1378 if (cpi->oxcf.use_simple_encode_api) {
1379 fp_motion_vector_info_reset(cpi->frame_info.frame_width,
1380 cpi->frame_info.frame_height,
1381 cpi->fp_motion_vector_info);
1382 }
1383 #endif
1384
1385 for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
1386 best_ref_mv = zero_mv;
1387 vp9_first_pass_encode_tile_mb_row(cpi, &cpi->td, fp_acc_data, &tile_data,
1388 &best_ref_mv, mb_row);
1389 }
1390 }
1391
vp9_first_pass(VP9_COMP * cpi,const struct lookahead_entry * source)1392 void vp9_first_pass(VP9_COMP *cpi, const struct lookahead_entry *source) {
1393 MACROBLOCK *const x = &cpi->td.mb;
1394 VP9_COMMON *const cm = &cpi->common;
1395 MACROBLOCKD *const xd = &x->e_mbd;
1396 TWO_PASS *twopass = &cpi->twopass;
1397
1398 YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1399 YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1400 YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
1401 const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
1402
1403 BufferPool *const pool = cm->buffer_pool;
1404
1405 FIRSTPASS_DATA fp_temp_data;
1406 FIRSTPASS_DATA *fp_acc_data = &fp_temp_data;
1407
1408 vpx_clear_system_state();
1409 vp9_zero(fp_temp_data);
1410 fp_acc_data->image_data_start_row = INVALID_ROW;
1411
1412 // First pass code requires valid last and new frame buffers.
1413 assert(new_yv12 != NULL);
1414 assert(frame_is_intra_only(cm) || (lst_yv12 != NULL));
1415
1416 set_first_pass_params(cpi);
1417 vp9_set_quantizer(cpi, find_fp_qindex(cm->bit_depth));
1418
1419 vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
1420
1421 vp9_setup_src_planes(x, cpi->Source, 0, 0);
1422 vp9_setup_dst_planes(xd->plane, new_yv12, 0, 0);
1423
1424 if (!frame_is_intra_only(cm)) {
1425 vp9_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL);
1426 }
1427
1428 xd->mi = cm->mi_grid_visible;
1429 xd->mi[0] = cm->mi;
1430
1431 vp9_frame_init_quantizer(cpi);
1432
1433 x->skip_recode = 0;
1434
1435 vp9_init_mv_probs(cm);
1436 vp9_initialize_rd_consts(cpi);
1437
1438 cm->log2_tile_rows = 0;
1439
1440 if (cpi->row_mt_bit_exact && cpi->twopass.fp_mb_float_stats == NULL)
1441 CHECK_MEM_ERROR(
1442 &cm->error, cpi->twopass.fp_mb_float_stats,
1443 vpx_calloc(cm->MBs * sizeof(*cpi->twopass.fp_mb_float_stats), 1));
1444
1445 {
1446 FIRSTPASS_STATS fps;
1447 TileDataEnc *first_tile_col;
1448 if (!cpi->row_mt) {
1449 cm->log2_tile_cols = 0;
1450 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
1451 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
1452 first_pass_encode(cpi, fp_acc_data);
1453 first_pass_stat_calc(cpi, &fps, fp_acc_data);
1454 } else {
1455 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
1456 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
1457 if (cpi->row_mt_bit_exact) {
1458 cm->log2_tile_cols = 0;
1459 vp9_zero_array(cpi->twopass.fp_mb_float_stats, cm->MBs);
1460 }
1461 vp9_encode_fp_row_mt(cpi);
1462 first_tile_col = &cpi->tile_data[0];
1463 if (cpi->row_mt_bit_exact)
1464 accumulate_floating_point_stats(cpi, first_tile_col);
1465 first_pass_stat_calc(cpi, &fps, &(first_tile_col->fp_data));
1466 }
1467
1468 // Don't allow a value of 0 for duration.
1469 // (Section duration is also defaulted to minimum of 1.0).
1470 fps.duration = VPXMAX(1.0, (double)(source->ts_end - source->ts_start));
1471
1472 // Don't want to do output stats with a stack variable!
1473 twopass->this_frame_stats = fps;
1474 output_stats(&twopass->this_frame_stats);
1475 accumulate_stats(&twopass->total_stats, &fps);
1476 }
1477
1478 // Copy the previous Last Frame back into gf and arf buffers if
1479 // the prediction is good enough... but also don't allow it to lag too far.
1480 if ((twopass->sr_update_lag > 3) ||
1481 ((cm->current_video_frame > 0) &&
1482 (twopass->this_frame_stats.pcnt_inter > 0.20) &&
1483 ((twopass->this_frame_stats.intra_error /
1484 DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
1485 if (gld_yv12 != NULL) {
1486 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1487 cm->ref_frame_map[cpi->lst_fb_idx]);
1488 }
1489 twopass->sr_update_lag = 1;
1490 } else {
1491 ++twopass->sr_update_lag;
1492 }
1493
1494 vpx_extend_frame_borders(new_yv12);
1495
1496 // The frame we just compressed now becomes the last frame.
1497 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
1498 cm->new_fb_idx);
1499
1500 // Special case for the first frame. Copy into the GF buffer as a second
1501 // reference.
1502 if (cm->current_video_frame == 0 && cpi->gld_fb_idx != INVALID_IDX) {
1503 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1504 cm->ref_frame_map[cpi->lst_fb_idx]);
1505 }
1506
1507 // In the first pass, every frame is considered as a show frame.
1508 update_frame_indexes(cm, /*show_frame=*/1);
1509 if (cpi->use_svc) vp9_inc_frame_in_layer(cpi);
1510 }
1511
1512 static const double q_pow_term[(QINDEX_RANGE >> 5) + 1] = { 0.65, 0.70, 0.75,
1513 0.85, 0.90, 0.90,
1514 0.90, 1.00, 1.25 };
1515
calc_correction_factor(double err_per_mb,double err_divisor,int q)1516 static double calc_correction_factor(double err_per_mb, double err_divisor,
1517 int q) {
1518 const double error_term = err_per_mb / DOUBLE_DIVIDE_CHECK(err_divisor);
1519 const int index = q >> 5;
1520 double power_term;
1521
1522 assert((index >= 0) && (index < (QINDEX_RANGE >> 5)));
1523
1524 // Adjustment based on quantizer to the power term.
1525 power_term =
1526 q_pow_term[index] +
1527 (((q_pow_term[index + 1] - q_pow_term[index]) * (q % 32)) / 32.0);
1528
1529 // Calculate correction factor.
1530 if (power_term < 1.0) assert(error_term >= 0.0);
1531
1532 return fclamp(pow(error_term, power_term), 0.05, 5.0);
1533 }
1534
wq_err_divisor(VP9_COMP * cpi)1535 static double wq_err_divisor(VP9_COMP *cpi) {
1536 const VP9_COMMON *const cm = &cpi->common;
1537 unsigned int screen_area = (cm->width * cm->height);
1538
1539 // Use a different error per mb factor for calculating boost for
1540 // different formats.
1541 if (screen_area <= 640 * 360) {
1542 return 115.0;
1543 } else if (screen_area < 1280 * 720) {
1544 return 125.0;
1545 } else if (screen_area <= 1920 * 1080) {
1546 return 130.0;
1547 } else if (screen_area < 3840 * 2160) {
1548 return 150.0;
1549 }
1550
1551 // Fall through to here only for 4K and above.
1552 return 200.0;
1553 }
1554
1555 #define NOISE_FACTOR_MIN 0.9
1556 #define NOISE_FACTOR_MAX 1.1
get_twopass_worst_quality(VP9_COMP * cpi,const double section_err,double inactive_zone,double section_noise,int section_target_bandwidth)1557 static int get_twopass_worst_quality(VP9_COMP *cpi, const double section_err,
1558 double inactive_zone, double section_noise,
1559 int section_target_bandwidth) {
1560 const RATE_CONTROL *const rc = &cpi->rc;
1561 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1562 TWO_PASS *const twopass = &cpi->twopass;
1563 double last_group_rate_err;
1564
1565 // Clamp the target rate to VBR min / max limts.
1566 const int target_rate =
1567 vp9_rc_clamp_pframe_target_size(cpi, section_target_bandwidth);
1568 double noise_factor = pow((section_noise / SECTION_NOISE_DEF), 0.5);
1569 noise_factor = fclamp(noise_factor, NOISE_FACTOR_MIN, NOISE_FACTOR_MAX);
1570 inactive_zone = fclamp(inactive_zone, 0.0, 1.0);
1571
1572 // TODO(jimbankoski): remove #if here or below when this has been
1573 // well tested.
1574 #if CONFIG_ALWAYS_ADJUST_BPM
1575 // based on recent history adjust expectations of bits per macroblock.
1576 last_group_rate_err =
1577 (double)twopass->rolling_arf_group_actual_bits /
1578 DOUBLE_DIVIDE_CHECK((double)twopass->rolling_arf_group_target_bits);
1579 last_group_rate_err = VPXMAX(0.25, VPXMIN(4.0, last_group_rate_err));
1580 twopass->bpm_factor *= (3.0 + last_group_rate_err) / 4.0;
1581 twopass->bpm_factor = VPXMAX(0.25, VPXMIN(4.0, twopass->bpm_factor));
1582 #endif
1583
1584 if (target_rate <= 0) {
1585 return rc->worst_quality; // Highest value allowed
1586 } else {
1587 const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1588 ? cpi->initial_mbs
1589 : cpi->common.MBs;
1590 const double active_pct = VPXMAX(0.01, 1.0 - inactive_zone);
1591 const int active_mbs = (int)VPXMAX(1, (double)num_mbs * active_pct);
1592 const double av_err_per_mb = section_err / active_pct;
1593 const double speed_term = 1.0 + 0.04 * oxcf->speed;
1594 const int target_norm_bits_per_mb =
1595 (int)(((uint64_t)target_rate << BPER_MB_NORMBITS) / active_mbs);
1596 int q;
1597
1598 // TODO(jimbankoski): remove #if here or above when this has been
1599 // well tested.
1600 #if !CONFIG_ALWAYS_ADJUST_BPM
1601 // based on recent history adjust expectations of bits per macroblock.
1602 last_group_rate_err =
1603 (double)twopass->rolling_arf_group_actual_bits /
1604 DOUBLE_DIVIDE_CHECK((double)twopass->rolling_arf_group_target_bits);
1605 last_group_rate_err = VPXMAX(0.25, VPXMIN(4.0, last_group_rate_err));
1606 twopass->bpm_factor *= (3.0 + last_group_rate_err) / 4.0;
1607 twopass->bpm_factor = VPXMAX(0.25, VPXMIN(4.0, twopass->bpm_factor));
1608 #endif
1609
1610 // Try and pick a max Q that will be high enough to encode the
1611 // content at the given rate.
1612 for (q = rc->best_quality; q < rc->worst_quality; ++q) {
1613 const double factor =
1614 calc_correction_factor(av_err_per_mb, wq_err_divisor(cpi), q);
1615 const int bits_per_mb = vp9_rc_bits_per_mb(
1616 INTER_FRAME, q,
1617 factor * speed_term * cpi->twopass.bpm_factor * noise_factor,
1618 cpi->common.bit_depth);
1619 if (bits_per_mb <= target_norm_bits_per_mb) break;
1620 }
1621
1622 // Restriction on active max q for constrained quality mode.
1623 if (cpi->oxcf.rc_mode == VPX_CQ) q = VPXMAX(q, oxcf->cq_level);
1624 return q;
1625 }
1626 }
1627
setup_rf_level_maxq(VP9_COMP * cpi)1628 static void setup_rf_level_maxq(VP9_COMP *cpi) {
1629 int i;
1630 RATE_CONTROL *const rc = &cpi->rc;
1631 for (i = INTER_NORMAL; i < RATE_FACTOR_LEVELS; ++i) {
1632 int qdelta = vp9_frame_type_qdelta(cpi, i, rc->worst_quality);
1633 rc->rf_level_maxq[i] = VPXMAX(rc->worst_quality + qdelta, rc->best_quality);
1634 }
1635 }
1636
init_subsampling(VP9_COMP * cpi)1637 static void init_subsampling(VP9_COMP *cpi) {
1638 const VP9_COMMON *const cm = &cpi->common;
1639 RATE_CONTROL *const rc = &cpi->rc;
1640 const int w = cm->width;
1641 const int h = cm->height;
1642 int i;
1643
1644 for (i = 0; i < FRAME_SCALE_STEPS; ++i) {
1645 // Note: Frames with odd-sized dimensions may result from this scaling.
1646 rc->frame_width[i] = (w * 16) / frame_scale_factor[i];
1647 rc->frame_height[i] = (h * 16) / frame_scale_factor[i];
1648 }
1649
1650 setup_rf_level_maxq(cpi);
1651 }
1652
calculate_coded_size(VP9_COMP * cpi,int * scaled_frame_width,int * scaled_frame_height)1653 void calculate_coded_size(VP9_COMP *cpi, int *scaled_frame_width,
1654 int *scaled_frame_height) {
1655 RATE_CONTROL *const rc = &cpi->rc;
1656 *scaled_frame_width = rc->frame_width[rc->frame_size_selector];
1657 *scaled_frame_height = rc->frame_height[rc->frame_size_selector];
1658 }
1659
vp9_init_second_pass(VP9_COMP * cpi)1660 void vp9_init_second_pass(VP9_COMP *cpi) {
1661 VP9EncoderConfig *const oxcf = &cpi->oxcf;
1662 RATE_CONTROL *const rc = &cpi->rc;
1663 TWO_PASS *const twopass = &cpi->twopass;
1664 double frame_rate;
1665 FIRSTPASS_STATS *stats;
1666
1667 zero_stats(&twopass->total_stats);
1668 zero_stats(&twopass->total_left_stats);
1669
1670 if (!twopass->stats_in_end) return;
1671
1672 stats = &twopass->total_stats;
1673
1674 *stats = *twopass->stats_in_end;
1675 twopass->total_left_stats = *stats;
1676
1677 // Scan the first pass file and calculate a modified score for each
1678 // frame that is used to distribute bits. The modified score is assumed
1679 // to provide a linear basis for bit allocation. I.e., a frame A with a score
1680 // that is double that of frame B will be allocated 2x as many bits.
1681 {
1682 double modified_score_total = 0.0;
1683 const FIRSTPASS_STATS *s = twopass->stats_in;
1684 double av_err;
1685
1686 if (oxcf->vbr_corpus_complexity) {
1687 twopass->mean_mod_score = (double)oxcf->vbr_corpus_complexity / 10.0;
1688 av_err = get_distribution_av_err(cpi, twopass);
1689 } else {
1690 av_err = get_distribution_av_err(cpi, twopass);
1691 // The first scan is unclamped and gives a raw average.
1692 while (s < twopass->stats_in_end) {
1693 modified_score_total += calculate_mod_frame_score(cpi, oxcf, s, av_err);
1694 ++s;
1695 }
1696
1697 // The average error from this first scan is used to define the midpoint
1698 // error for the rate distribution function.
1699 twopass->mean_mod_score =
1700 modified_score_total / DOUBLE_DIVIDE_CHECK(stats->count);
1701 }
1702
1703 // Second scan using clamps based on the previous cycle average.
1704 // This may modify the total and average somewhat but we don't bother with
1705 // further iterations.
1706 modified_score_total = 0.0;
1707 s = twopass->stats_in;
1708 while (s < twopass->stats_in_end) {
1709 modified_score_total +=
1710 calculate_norm_frame_score(cpi, twopass, oxcf, s, av_err);
1711 ++s;
1712 }
1713 twopass->normalized_score_left = modified_score_total;
1714
1715 // If using Corpus wide VBR mode then update the clip target bandwidth to
1716 // reflect how the clip compares to the rest of the corpus.
1717 if (oxcf->vbr_corpus_complexity) {
1718 oxcf->target_bandwidth =
1719 (int64_t)((double)oxcf->target_bandwidth *
1720 (twopass->normalized_score_left / stats->count));
1721 }
1722
1723 #if COMPLEXITY_STATS_OUTPUT
1724 {
1725 FILE *compstats;
1726 compstats = fopen("complexity_stats.stt", "a");
1727 fprintf(compstats, "%10.3lf\n",
1728 twopass->normalized_score_left / stats->count);
1729 fclose(compstats);
1730 }
1731 #endif
1732 }
1733
1734 frame_rate = 10000000.0 * stats->count / stats->duration;
1735 // Each frame can have a different duration, as the frame rate in the source
1736 // isn't guaranteed to be constant. The frame rate prior to the first frame
1737 // encoded in the second pass is a guess. However, the sum duration is not.
1738 // It is calculated based on the actual durations of all frames from the
1739 // first pass.
1740 vp9_new_framerate(cpi, frame_rate);
1741 twopass->bits_left =
1742 (int64_t)(stats->duration * oxcf->target_bandwidth / 10000000.0);
1743
1744 // This variable monitors how far behind the second ref update is lagging.
1745 twopass->sr_update_lag = 1;
1746
1747 // Reset the vbr bits off target counters
1748 rc->vbr_bits_off_target = 0;
1749 rc->vbr_bits_off_target_fast = 0;
1750 rc->rate_error_estimate = 0;
1751
1752 // Static sequence monitor variables.
1753 twopass->kf_zeromotion_pct = 100;
1754 twopass->last_kfgroup_zeromotion_pct = 100;
1755
1756 // Initialize bits per macro_block estimate correction factor.
1757 twopass->bpm_factor = 1.0;
1758 // Initialize actual and target bits counters for ARF groups so that
1759 // at the start we have a neutral bpm adjustment.
1760 twopass->rolling_arf_group_target_bits = 1;
1761 twopass->rolling_arf_group_actual_bits = 1;
1762
1763 if (oxcf->resize_mode != RESIZE_NONE) {
1764 init_subsampling(cpi);
1765 }
1766
1767 // Initialize the arnr strangth adjustment to 0
1768 twopass->arnr_strength_adjustment = 0;
1769 }
1770
1771 /* This function considers how the quality of prediction may be deteriorating
1772 * with distance. It compares the coded error for the last frame and the
1773 * second reference frame (usually two frames old) and also applies a factor
1774 * based on the extent of INTRA coding.
1775 *
1776 * The decay factor is then used to reduce the contribution of frames further
1777 * from the alt-ref or golden frame, to the bitrate boost calculation for that
1778 * alt-ref or golden frame.
1779 */
get_sr_decay_rate(const TWO_PASS * const twopass,const FIRSTPASS_STATS * frame)1780 static double get_sr_decay_rate(const TWO_PASS *const twopass,
1781 const FIRSTPASS_STATS *frame) {
1782 double sr_diff = (frame->sr_coded_error - frame->coded_error);
1783 double sr_decay = 1.0;
1784
1785 // Do nothing if the second ref to last frame error difference is
1786 // very small or even negative.
1787 if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
1788 const double sr_diff_part =
1789 twopass->sr_diff_factor * ((sr_diff * 0.25) / frame->intra_error);
1790 double modified_pct_inter = frame->pcnt_inter;
1791 double modified_pcnt_intra;
1792
1793 if ((frame->coded_error > LOW_CODED_ERR_PER_MB) &&
1794 ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
1795 (double)NCOUNT_FRAME_II_THRESH)) {
1796 modified_pct_inter =
1797 frame->pcnt_inter + frame->pcnt_intra_low - frame->pcnt_neutral;
1798 }
1799 modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
1800
1801 sr_decay = 1.0 - sr_diff_part - (INTRA_PART * modified_pcnt_intra);
1802 }
1803 return VPXMAX(sr_decay, twopass->sr_default_decay_limit);
1804 }
1805
1806 // This function gives an estimate of how badly we believe the prediction
1807 // quality is decaying from frame to frame.
get_zero_motion_factor(const TWO_PASS * const twopass,const FIRSTPASS_STATS * frame_stats)1808 static double get_zero_motion_factor(const TWO_PASS *const twopass,
1809 const FIRSTPASS_STATS *frame_stats) {
1810 const double zero_motion_pct =
1811 frame_stats->pcnt_inter - frame_stats->pcnt_motion;
1812 double sr_decay = get_sr_decay_rate(twopass, frame_stats);
1813 return VPXMIN(sr_decay, zero_motion_pct);
1814 }
1815
get_prediction_decay_rate(const TWO_PASS * const twopass,const FIRSTPASS_STATS * frame_stats)1816 static double get_prediction_decay_rate(const TWO_PASS *const twopass,
1817 const FIRSTPASS_STATS *frame_stats) {
1818 const double sr_decay_rate = get_sr_decay_rate(twopass, frame_stats);
1819 double zero_motion_factor =
1820 twopass->zm_factor * (frame_stats->pcnt_inter - frame_stats->pcnt_motion);
1821
1822 // Check that the zero motion factor is valid
1823 assert(zero_motion_factor >= 0.0 && zero_motion_factor <= 1.0);
1824
1825 return VPXMAX(zero_motion_factor,
1826 (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
1827 }
1828
get_show_idx(const TWO_PASS * twopass)1829 static int get_show_idx(const TWO_PASS *twopass) {
1830 return (int)(twopass->stats_in - twopass->stats_in_start);
1831 }
1832 // Function to test for a condition where a complex transition is followed
1833 // by a static section. For example in slide shows where there is a fade
1834 // between slides. This is to help with more optimal kf and gf positioning.
check_transition_to_still(const FIRST_PASS_INFO * first_pass_info,int show_idx,int still_interval)1835 static int check_transition_to_still(const FIRST_PASS_INFO *first_pass_info,
1836 int show_idx, int still_interval) {
1837 int j;
1838 int num_frames = fps_get_num_frames(first_pass_info);
1839 if (show_idx + still_interval > num_frames) {
1840 return 0;
1841 }
1842
1843 // Look ahead a few frames to see if static condition persists...
1844 for (j = 0; j < still_interval; ++j) {
1845 const FIRSTPASS_STATS *stats =
1846 fps_get_frame_stats(first_pass_info, show_idx + j);
1847 if (stats->pcnt_inter - stats->pcnt_motion < 0.999) break;
1848 }
1849
1850 // Only if it does do we signal a transition to still.
1851 return j == still_interval;
1852 }
1853
1854 // This function detects a flash through the high relative pcnt_second_ref
1855 // score in the frame following a flash frame. The offset passed in should
1856 // reflect this.
detect_flash_from_frame_stats(const FIRSTPASS_STATS * frame_stats)1857 static int detect_flash_from_frame_stats(const FIRSTPASS_STATS *frame_stats) {
1858 // What we are looking for here is a situation where there is a
1859 // brief break in prediction (such as a flash) but subsequent frames
1860 // are reasonably well predicted by an earlier (pre flash) frame.
1861 // The recovery after a flash is indicated by a high pcnt_second_ref
1862 // usage or a second ref coded error notabley lower than the last
1863 // frame coded error.
1864 if (frame_stats == NULL) {
1865 return 0;
1866 }
1867 return (frame_stats->sr_coded_error < frame_stats->coded_error) ||
1868 ((frame_stats->pcnt_second_ref > frame_stats->pcnt_inter) &&
1869 (frame_stats->pcnt_second_ref >= 0.5));
1870 }
1871
detect_flash(const TWO_PASS * twopass,int offset)1872 static int detect_flash(const TWO_PASS *twopass, int offset) {
1873 const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
1874 return detect_flash_from_frame_stats(next_frame);
1875 }
1876
1877 // Update the motion related elements to the GF arf boost calculation.
accumulate_frame_motion_stats(const FIRSTPASS_STATS * stats,double * mv_in_out,double * mv_in_out_accumulator,double * abs_mv_in_out_accumulator,double * mv_ratio_accumulator)1878 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
1879 double *mv_in_out,
1880 double *mv_in_out_accumulator,
1881 double *abs_mv_in_out_accumulator,
1882 double *mv_ratio_accumulator) {
1883 const double pct = stats->pcnt_motion;
1884
1885 // Accumulate Motion In/Out of frame stats.
1886 *mv_in_out = stats->mv_in_out_count * pct;
1887 *mv_in_out_accumulator += *mv_in_out;
1888 *abs_mv_in_out_accumulator += fabs(*mv_in_out);
1889
1890 // Accumulate a measure of how uniform (or conversely how random) the motion
1891 // field is (a ratio of abs(mv) / mv).
1892 if (pct > 0.05) {
1893 const double mvr_ratio =
1894 fabs(stats->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
1895 const double mvc_ratio =
1896 fabs(stats->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
1897
1898 *mv_ratio_accumulator +=
1899 pct * (mvr_ratio < stats->mvr_abs ? mvr_ratio : stats->mvr_abs);
1900 *mv_ratio_accumulator +=
1901 pct * (mvc_ratio < stats->mvc_abs ? mvc_ratio : stats->mvc_abs);
1902 }
1903 }
1904
calc_frame_boost(const FRAME_INFO * frame_info,const FIRSTPASS_STATS * this_frame,const TWO_PASS * const twopass,int avg_frame_qindex,double this_frame_mv_in_out)1905 static double calc_frame_boost(const FRAME_INFO *frame_info,
1906 const FIRSTPASS_STATS *this_frame,
1907 const TWO_PASS *const twopass,
1908 int avg_frame_qindex,
1909 double this_frame_mv_in_out) {
1910 double frame_boost;
1911 const double lq =
1912 vp9_convert_qindex_to_q(avg_frame_qindex, frame_info->bit_depth);
1913 const double boost_q_correction = VPXMIN((0.5 + (lq * 0.015)), 1.5);
1914 const double active_area = calculate_active_area(frame_info, this_frame);
1915
1916 // Frame booost is based on inter error.
1917 frame_boost = (twopass->err_per_mb * active_area) /
1918 DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
1919
1920 // Small adjustment for cases where there is a zoom out
1921 if (this_frame_mv_in_out > 0.0)
1922 frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1923
1924 // Q correction and scalling
1925 frame_boost = frame_boost * boost_q_correction;
1926
1927 return VPXMIN(frame_boost, twopass->gf_frame_max_boost * boost_q_correction);
1928 }
1929
calc_kf_frame_boost(VP9_COMP * cpi,const FIRSTPASS_STATS * this_frame,double * sr_accumulator,double this_frame_mv_in_out,double zm_factor)1930 static double calc_kf_frame_boost(VP9_COMP *cpi,
1931 const FIRSTPASS_STATS *this_frame,
1932 double *sr_accumulator,
1933 double this_frame_mv_in_out,
1934 double zm_factor) {
1935 TWO_PASS *const twopass = &cpi->twopass;
1936 double frame_boost;
1937 const double lq = vp9_convert_qindex_to_q(
1938 cpi->rc.avg_frame_qindex[INTER_FRAME], cpi->common.bit_depth);
1939 const double boost_q_correction = VPXMIN((0.50 + (lq * 0.015)), 2.00);
1940 const double active_area =
1941 calculate_active_area(&cpi->frame_info, this_frame);
1942 double max_boost;
1943
1944 // Frame booost is based on inter error.
1945 frame_boost = (twopass->kf_err_per_mb * active_area) /
1946 DOUBLE_DIVIDE_CHECK(this_frame->coded_error + *sr_accumulator);
1947
1948 // Update the accumulator for second ref error difference.
1949 // This is intended to give an indication of how much the coded error is
1950 // increasing over time.
1951 *sr_accumulator += (this_frame->sr_coded_error - this_frame->coded_error);
1952 *sr_accumulator = VPXMAX(0.0, *sr_accumulator);
1953
1954 // Small adjustment for cases where there is a zoom out
1955 if (this_frame_mv_in_out > 0.0)
1956 frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1957
1958 // Q correction and scaling
1959 // The 40.0 value here is an experimentally derived baseline minimum.
1960 // This value is in line with the minimum per frame boost in the alt_ref
1961 // boost calculation.
1962 frame_boost =
1963 (frame_boost + twopass->kf_frame_min_boost) * boost_q_correction;
1964
1965 // Maximum allowed boost this frame. May be different for first vs subsequent
1966 // key frames.
1967 max_boost = (cpi->common.current_video_frame == 0)
1968 ? twopass->kf_frame_max_boost_first
1969 : twopass->kf_frame_max_boost_subs;
1970 max_boost *= zm_factor * boost_q_correction;
1971
1972 return VPXMIN(frame_boost, max_boost);
1973 }
1974
compute_arf_boost(const FRAME_INFO * frame_info,TWO_PASS * const twopass,int arf_show_idx,int f_frames,int b_frames,int avg_frame_qindex)1975 static int compute_arf_boost(const FRAME_INFO *frame_info,
1976 TWO_PASS *const twopass, int arf_show_idx,
1977 int f_frames, int b_frames, int avg_frame_qindex) {
1978 const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
1979 int i;
1980 double boost_score = 0.0;
1981 double mv_ratio_accumulator = 0.0;
1982 double decay_accumulator = 1.0;
1983 double this_frame_mv_in_out = 0.0;
1984 double mv_in_out_accumulator = 0.0;
1985 double abs_mv_in_out_accumulator = 0.0;
1986 int arf_boost;
1987 int flash_detected = 0;
1988
1989 // Search forward from the proposed arf/next gf position.
1990 for (i = 0; i < f_frames; ++i) {
1991 const FIRSTPASS_STATS *this_frame =
1992 fps_get_frame_stats(first_pass_info, arf_show_idx + i);
1993 const FIRSTPASS_STATS *next_frame =
1994 fps_get_frame_stats(first_pass_info, arf_show_idx + i + 1);
1995 if (this_frame == NULL) break;
1996
1997 // Update the motion related elements to the boost calculation.
1998 accumulate_frame_motion_stats(
1999 this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2000 &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2001
2002 // We want to discount the flash frame itself and the recovery
2003 // frame that follows as both will have poor scores.
2004 flash_detected = detect_flash_from_frame_stats(this_frame) ||
2005 detect_flash_from_frame_stats(next_frame);
2006
2007 // Accumulate the effect of prediction quality decay.
2008 if (!flash_detected) {
2009 decay_accumulator *= get_prediction_decay_rate(twopass, this_frame);
2010 decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
2011 ? MIN_DECAY_FACTOR
2012 : decay_accumulator;
2013 }
2014 boost_score += decay_accumulator *
2015 calc_frame_boost(frame_info, this_frame, twopass,
2016 avg_frame_qindex, this_frame_mv_in_out);
2017 }
2018
2019 arf_boost = (int)boost_score;
2020
2021 // Reset for backward looking loop.
2022 boost_score = 0.0;
2023 mv_ratio_accumulator = 0.0;
2024 decay_accumulator = 1.0;
2025 this_frame_mv_in_out = 0.0;
2026 mv_in_out_accumulator = 0.0;
2027 abs_mv_in_out_accumulator = 0.0;
2028
2029 // Search backward towards last gf position.
2030 for (i = -1; i >= -b_frames; --i) {
2031 const FIRSTPASS_STATS *this_frame =
2032 fps_get_frame_stats(first_pass_info, arf_show_idx + i);
2033 const FIRSTPASS_STATS *next_frame =
2034 fps_get_frame_stats(first_pass_info, arf_show_idx + i + 1);
2035 if (this_frame == NULL) break;
2036
2037 // Update the motion related elements to the boost calculation.
2038 accumulate_frame_motion_stats(
2039 this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2040 &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2041
2042 // We want to discount the flash frame itself and the recovery
2043 // frame that follows as both will have poor scores.
2044 flash_detected = detect_flash_from_frame_stats(this_frame) ||
2045 detect_flash_from_frame_stats(next_frame);
2046
2047 // Cumulative effect of prediction quality decay.
2048 if (!flash_detected) {
2049 decay_accumulator *= get_prediction_decay_rate(twopass, this_frame);
2050 decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
2051 ? MIN_DECAY_FACTOR
2052 : decay_accumulator;
2053 }
2054 boost_score += decay_accumulator *
2055 calc_frame_boost(frame_info, this_frame, twopass,
2056 avg_frame_qindex, this_frame_mv_in_out);
2057 }
2058 arf_boost += (int)boost_score;
2059
2060 if (arf_boost < ((b_frames + f_frames) * 40))
2061 arf_boost = ((b_frames + f_frames) * 40);
2062 arf_boost = VPXMAX(arf_boost, MIN_ARF_GF_BOOST);
2063
2064 return arf_boost;
2065 }
2066
calc_arf_boost(VP9_COMP * cpi,int f_frames,int b_frames)2067 static int calc_arf_boost(VP9_COMP *cpi, int f_frames, int b_frames) {
2068 const FRAME_INFO *frame_info = &cpi->frame_info;
2069 TWO_PASS *const twopass = &cpi->twopass;
2070 const int avg_inter_frame_qindex = cpi->rc.avg_frame_qindex[INTER_FRAME];
2071 int arf_show_idx = get_show_idx(twopass);
2072 return compute_arf_boost(frame_info, twopass, arf_show_idx, f_frames,
2073 b_frames, avg_inter_frame_qindex);
2074 }
2075
2076 // Calculate a section intra ratio used in setting max loop filter.
calculate_section_intra_ratio(const FIRSTPASS_STATS * begin,const FIRSTPASS_STATS * end,int section_length)2077 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
2078 const FIRSTPASS_STATS *end,
2079 int section_length) {
2080 const FIRSTPASS_STATS *s = begin;
2081 double intra_error = 0.0;
2082 double coded_error = 0.0;
2083 int i = 0;
2084
2085 while (s < end && i < section_length) {
2086 intra_error += s->intra_error;
2087 coded_error += s->coded_error;
2088 ++s;
2089 ++i;
2090 }
2091
2092 return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
2093 }
2094
2095 // Calculate the total bits to allocate in this GF/ARF group.
calculate_total_gf_group_bits(VP9_COMP * cpi,double gf_group_err)2096 static int64_t calculate_total_gf_group_bits(VP9_COMP *cpi,
2097 double gf_group_err) {
2098 VP9_COMMON *const cm = &cpi->common;
2099 const RATE_CONTROL *const rc = &cpi->rc;
2100 const TWO_PASS *const twopass = &cpi->twopass;
2101 const int max_bits = frame_max_bits(rc, &cpi->oxcf);
2102 int64_t total_group_bits;
2103 const int is_key_frame = frame_is_intra_only(cm);
2104 const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
2105 int gop_frames =
2106 rc->baseline_gf_interval + rc->source_alt_ref_pending - arf_active_or_kf;
2107
2108 // Calculate the bits to be allocated to the group as a whole.
2109 if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0.0)) {
2110 int key_frame_interval = rc->frames_since_key + rc->frames_to_key;
2111 int distance_from_next_key_frame =
2112 rc->frames_to_key -
2113 (rc->baseline_gf_interval + rc->source_alt_ref_pending);
2114 int max_gf_bits_bias = rc->avg_frame_bandwidth;
2115 double gf_interval_bias_bits_normalize_factor =
2116 (double)rc->baseline_gf_interval / 16;
2117 total_group_bits = (int64_t)(twopass->kf_group_bits *
2118 (gf_group_err / twopass->kf_group_error_left));
2119 // TODO(ravi): Experiment with different values of max_gf_bits_bias
2120 total_group_bits +=
2121 (int64_t)((double)distance_from_next_key_frame / key_frame_interval *
2122 max_gf_bits_bias * gf_interval_bias_bits_normalize_factor);
2123 } else {
2124 total_group_bits = 0;
2125 }
2126
2127 // Clamp odd edge cases.
2128 total_group_bits = (total_group_bits < 0) ? 0
2129 : (total_group_bits > twopass->kf_group_bits)
2130 ? twopass->kf_group_bits
2131 : total_group_bits;
2132
2133 // Clip based on user supplied data rate variability limit.
2134 if (total_group_bits > (int64_t)max_bits * gop_frames)
2135 total_group_bits = (int64_t)max_bits * gop_frames;
2136
2137 return total_group_bits;
2138 }
2139
2140 // Calculate the number bits extra to assign to boosted frames in a group.
calculate_boost_bits(int frame_count,int boost,int64_t total_group_bits)2141 static int calculate_boost_bits(int frame_count, int boost,
2142 int64_t total_group_bits) {
2143 int allocation_chunks;
2144
2145 // return 0 for invalid inputs (could arise e.g. through rounding errors)
2146 if (!boost || (total_group_bits <= 0) || (frame_count < 0)) return 0;
2147
2148 allocation_chunks = (frame_count * NORMAL_BOOST) + boost;
2149
2150 // Prevent overflow.
2151 if (boost > 1023) {
2152 int divisor = boost >> 10;
2153 boost /= divisor;
2154 allocation_chunks /= divisor;
2155 }
2156
2157 // Calculate the number of extra bits for use in the boosted frame or frames.
2158 return VPXMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
2159 0);
2160 }
2161
2162 // Used in corpus vbr: Calculates the total normalized group complexity score
2163 // for a given number of frames starting at the current position in the stats
2164 // file.
calculate_group_score(VP9_COMP * cpi,double av_score,int frame_count)2165 static double calculate_group_score(VP9_COMP *cpi, double av_score,
2166 int frame_count) {
2167 VP9EncoderConfig *const oxcf = &cpi->oxcf;
2168 TWO_PASS *const twopass = &cpi->twopass;
2169 const FIRSTPASS_STATS *s = twopass->stats_in;
2170 double score_total = 0.0;
2171 int i = 0;
2172
2173 // We don't ever want to return a 0 score here.
2174 if (frame_count == 0) return 1.0;
2175
2176 while ((i < frame_count) && (s < twopass->stats_in_end)) {
2177 score_total += calculate_norm_frame_score(cpi, twopass, oxcf, s, av_score);
2178 ++s;
2179 ++i;
2180 }
2181
2182 return score_total;
2183 }
2184
find_arf_order(VP9_COMP * cpi,GF_GROUP * gf_group,int * index_counter,int depth,int start,int end)2185 static void find_arf_order(VP9_COMP *cpi, GF_GROUP *gf_group,
2186 int *index_counter, int depth, int start, int end) {
2187 TWO_PASS *twopass = &cpi->twopass;
2188 const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
2189 FIRSTPASS_STATS fpf_frame;
2190 const int mid = (start + end + 1) >> 1;
2191 const int min_frame_interval = 2;
2192 int idx;
2193
2194 // Process regular P frames
2195 if ((end - start < min_frame_interval) ||
2196 (depth > gf_group->allowed_max_layer_depth)) {
2197 for (idx = start; idx <= end; ++idx) {
2198 gf_group->update_type[*index_counter] = LF_UPDATE;
2199 gf_group->arf_src_offset[*index_counter] = 0;
2200 gf_group->frame_gop_index[*index_counter] = idx;
2201 gf_group->rf_level[*index_counter] = INTER_NORMAL;
2202 gf_group->layer_depth[*index_counter] = depth;
2203 gf_group->gfu_boost[*index_counter] = NORMAL_BOOST;
2204 ++(*index_counter);
2205 }
2206 gf_group->max_layer_depth = VPXMAX(gf_group->max_layer_depth, depth);
2207 return;
2208 }
2209
2210 assert(abs(mid - start) >= 1 && abs(mid - end) >= 1);
2211
2212 // Process ARF frame
2213 gf_group->layer_depth[*index_counter] = depth;
2214 gf_group->update_type[*index_counter] = ARF_UPDATE;
2215 gf_group->arf_src_offset[*index_counter] = mid - start;
2216 gf_group->frame_gop_index[*index_counter] = mid;
2217 gf_group->rf_level[*index_counter] = GF_ARF_LOW;
2218
2219 for (idx = 0; idx <= mid; ++idx)
2220 if (EOF == input_stats(twopass, &fpf_frame)) break;
2221
2222 gf_group->gfu_boost[*index_counter] =
2223 VPXMAX(MIN_ARF_GF_BOOST,
2224 calc_arf_boost(cpi, end - mid + 1, mid - start) >> depth);
2225
2226 reset_fpf_position(twopass, start_pos);
2227
2228 ++(*index_counter);
2229
2230 find_arf_order(cpi, gf_group, index_counter, depth + 1, start, mid - 1);
2231
2232 gf_group->update_type[*index_counter] = USE_BUF_FRAME;
2233 gf_group->arf_src_offset[*index_counter] = 0;
2234 gf_group->frame_gop_index[*index_counter] = mid;
2235 gf_group->rf_level[*index_counter] = INTER_NORMAL;
2236 gf_group->layer_depth[*index_counter] = depth;
2237 ++(*index_counter);
2238
2239 find_arf_order(cpi, gf_group, index_counter, depth + 1, mid + 1, end);
2240 }
2241
set_gf_overlay_frame_type(GF_GROUP * gf_group,int frame_index,int source_alt_ref_active)2242 static INLINE void set_gf_overlay_frame_type(GF_GROUP *gf_group,
2243 int frame_index,
2244 int source_alt_ref_active) {
2245 if (source_alt_ref_active) {
2246 gf_group->update_type[frame_index] = OVERLAY_UPDATE;
2247 gf_group->rf_level[frame_index] = INTER_NORMAL;
2248 gf_group->layer_depth[frame_index] = MAX_ARF_LAYERS - 1;
2249 gf_group->gfu_boost[frame_index] = NORMAL_BOOST;
2250 } else {
2251 gf_group->update_type[frame_index] = GF_UPDATE;
2252 gf_group->rf_level[frame_index] = GF_ARF_STD;
2253 gf_group->layer_depth[frame_index] = 0;
2254 }
2255 }
2256
define_gf_group_structure(VP9_COMP * cpi)2257 static void define_gf_group_structure(VP9_COMP *cpi) {
2258 RATE_CONTROL *const rc = &cpi->rc;
2259 TWO_PASS *const twopass = &cpi->twopass;
2260 GF_GROUP *const gf_group = &twopass->gf_group;
2261 int frame_index = 0;
2262 int key_frame = cpi->common.frame_type == KEY_FRAME;
2263 int layer_depth = 1;
2264 int gop_frames =
2265 rc->baseline_gf_interval - (key_frame || rc->source_alt_ref_pending);
2266
2267 gf_group->frame_start = cpi->common.current_video_frame;
2268 gf_group->frame_end = gf_group->frame_start + rc->baseline_gf_interval;
2269 gf_group->max_layer_depth = 0;
2270 gf_group->allowed_max_layer_depth = 0;
2271
2272 // For key frames the frame target rate is already set and it
2273 // is also the golden frame.
2274 // === [frame_index == 0] ===
2275 if (!key_frame)
2276 set_gf_overlay_frame_type(gf_group, frame_index, rc->source_alt_ref_active);
2277
2278 ++frame_index;
2279
2280 // === [frame_index == 1] ===
2281 if (rc->source_alt_ref_pending) {
2282 gf_group->update_type[frame_index] = ARF_UPDATE;
2283 gf_group->rf_level[frame_index] = GF_ARF_STD;
2284 gf_group->layer_depth[frame_index] = layer_depth;
2285 gf_group->arf_src_offset[frame_index] =
2286 (unsigned char)(rc->baseline_gf_interval - 1);
2287 gf_group->frame_gop_index[frame_index] = rc->baseline_gf_interval;
2288 gf_group->max_layer_depth = 1;
2289 ++frame_index;
2290 ++layer_depth;
2291 gf_group->allowed_max_layer_depth = cpi->oxcf.enable_auto_arf;
2292 }
2293
2294 find_arf_order(cpi, gf_group, &frame_index, layer_depth, 1, gop_frames);
2295
2296 set_gf_overlay_frame_type(gf_group, frame_index, rc->source_alt_ref_pending);
2297 gf_group->arf_src_offset[frame_index] = 0;
2298 gf_group->frame_gop_index[frame_index] = rc->baseline_gf_interval;
2299
2300 // Set the frame ops number.
2301 gf_group->gf_group_size = frame_index;
2302 }
2303
allocate_gf_group_bits(VP9_COMP * cpi,int64_t gf_group_bits,int gf_arf_bits)2304 static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
2305 int gf_arf_bits) {
2306 VP9EncoderConfig *const oxcf = &cpi->oxcf;
2307 RATE_CONTROL *const rc = &cpi->rc;
2308 TWO_PASS *const twopass = &cpi->twopass;
2309 GF_GROUP *const gf_group = &twopass->gf_group;
2310 FIRSTPASS_STATS frame_stats;
2311 int i;
2312 int frame_index = 0;
2313 int target_frame_size;
2314 int key_frame;
2315 const int max_bits = frame_max_bits(&cpi->rc, oxcf);
2316 int64_t total_group_bits = gf_group_bits;
2317 int mid_frame_idx;
2318 int normal_frames;
2319 int normal_frame_bits;
2320 int last_frame_reduction = 0;
2321 double av_score = 1.0;
2322 double tot_norm_frame_score = 1.0;
2323 double this_frame_score = 1.0;
2324
2325 // Define the GF structure and specify
2326 int gop_frames = gf_group->gf_group_size;
2327
2328 key_frame = cpi->common.frame_type == KEY_FRAME;
2329
2330 // For key frames the frame target rate is already set and it
2331 // is also the golden frame.
2332 // === [frame_index == 0] ===
2333 if (!key_frame) {
2334 gf_group->bit_allocation[frame_index] =
2335 rc->source_alt_ref_active ? 0 : gf_arf_bits;
2336 }
2337
2338 // Deduct the boost bits for arf (or gf if it is not a key frame)
2339 // from the group total.
2340 if (rc->source_alt_ref_pending || !key_frame) total_group_bits -= gf_arf_bits;
2341
2342 ++frame_index;
2343
2344 // === [frame_index == 1] ===
2345 // Store the bits to spend on the ARF if there is one.
2346 if (rc->source_alt_ref_pending) {
2347 gf_group->bit_allocation[frame_index] = gf_arf_bits;
2348
2349 ++frame_index;
2350 }
2351
2352 // Define middle frame
2353 mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
2354
2355 normal_frames = (rc->baseline_gf_interval - 1);
2356 if (normal_frames > 1)
2357 normal_frame_bits = (int)(total_group_bits / normal_frames);
2358 else
2359 normal_frame_bits = (int)total_group_bits;
2360
2361 gf_group->gfu_boost[1] = rc->gfu_boost;
2362
2363 if (cpi->multi_layer_arf) {
2364 int idx;
2365 int arf_depth_bits[MAX_ARF_LAYERS] = { 0 };
2366 int arf_depth_count[MAX_ARF_LAYERS] = { 0 };
2367 int arf_depth_boost[MAX_ARF_LAYERS] = { 0 };
2368 int total_arfs = 1; // Account for the base layer ARF.
2369
2370 for (idx = 0; idx < gop_frames; ++idx) {
2371 if (gf_group->update_type[idx] == ARF_UPDATE) {
2372 arf_depth_boost[gf_group->layer_depth[idx]] += gf_group->gfu_boost[idx];
2373 ++arf_depth_count[gf_group->layer_depth[idx]];
2374 }
2375 }
2376
2377 for (idx = 2; idx < MAX_ARF_LAYERS; ++idx) {
2378 if (arf_depth_boost[idx] == 0) break;
2379 arf_depth_bits[idx] = calculate_boost_bits(
2380 rc->baseline_gf_interval - total_arfs - arf_depth_count[idx],
2381 arf_depth_boost[idx], total_group_bits);
2382
2383 total_group_bits -= arf_depth_bits[idx];
2384 total_arfs += arf_depth_count[idx];
2385 }
2386
2387 // offset the base layer arf
2388 normal_frames -= (total_arfs - 1);
2389 if (normal_frames > 1)
2390 normal_frame_bits = (int)(total_group_bits / normal_frames);
2391 else
2392 normal_frame_bits = (int)total_group_bits;
2393
2394 target_frame_size = normal_frame_bits;
2395 target_frame_size =
2396 clamp(target_frame_size, 0, VPXMIN(max_bits, (int)total_group_bits));
2397
2398 // The first layer ARF has its bit allocation assigned.
2399 for (idx = frame_index; idx < gop_frames; ++idx) {
2400 switch (gf_group->update_type[idx]) {
2401 case ARF_UPDATE:
2402 gf_group->bit_allocation[idx] =
2403 (int)(((int64_t)arf_depth_bits[gf_group->layer_depth[idx]] *
2404 gf_group->gfu_boost[idx]) /
2405 arf_depth_boost[gf_group->layer_depth[idx]]);
2406 break;
2407 case USE_BUF_FRAME: gf_group->bit_allocation[idx] = 0; break;
2408 default: gf_group->bit_allocation[idx] = target_frame_size; break;
2409 }
2410 }
2411 gf_group->bit_allocation[idx] = 0;
2412
2413 return;
2414 }
2415
2416 if (oxcf->vbr_corpus_complexity) {
2417 av_score = get_distribution_av_err(cpi, twopass);
2418 tot_norm_frame_score = calculate_group_score(cpi, av_score, normal_frames);
2419 }
2420
2421 // Allocate bits to the other frames in the group.
2422 for (i = 0; i < normal_frames; ++i) {
2423 if (EOF == input_stats(twopass, &frame_stats)) break;
2424 if (oxcf->vbr_corpus_complexity) {
2425 this_frame_score = calculate_norm_frame_score(cpi, twopass, oxcf,
2426 &frame_stats, av_score);
2427 normal_frame_bits = (int)((double)total_group_bits *
2428 (this_frame_score / tot_norm_frame_score));
2429 }
2430
2431 target_frame_size = normal_frame_bits;
2432 if ((i == (normal_frames - 1)) && (i >= 1)) {
2433 last_frame_reduction = normal_frame_bits / 16;
2434 target_frame_size -= last_frame_reduction;
2435 }
2436
2437 target_frame_size =
2438 clamp(target_frame_size, 0, VPXMIN(max_bits, (int)total_group_bits));
2439
2440 gf_group->bit_allocation[frame_index] = target_frame_size;
2441 ++frame_index;
2442 }
2443
2444 // Add in some extra bits for the middle frame in the group.
2445 gf_group->bit_allocation[mid_frame_idx] += last_frame_reduction;
2446
2447 // Note:
2448 // We need to configure the frame at the end of the sequence + 1 that will be
2449 // the start frame for the next group. Otherwise prior to the call to
2450 // vp9_rc_get_second_pass_params() the data will be undefined.
2451 }
2452
2453 // Adjusts the ARNF filter for a GF group.
adjust_group_arnr_filter(VP9_COMP * cpi,double section_noise,double section_inter,double section_motion)2454 static void adjust_group_arnr_filter(VP9_COMP *cpi, double section_noise,
2455 double section_inter,
2456 double section_motion) {
2457 TWO_PASS *const twopass = &cpi->twopass;
2458 double section_zeromv = section_inter - section_motion;
2459
2460 twopass->arnr_strength_adjustment = 0;
2461
2462 if (section_noise < 150) {
2463 twopass->arnr_strength_adjustment -= 1;
2464 if (section_noise < 75) twopass->arnr_strength_adjustment -= 1;
2465 } else if (section_noise > 250)
2466 twopass->arnr_strength_adjustment += 1;
2467
2468 if (section_zeromv > 0.50) twopass->arnr_strength_adjustment += 1;
2469 }
2470
2471 // Analyse and define a gf/arf group.
2472 #define ARF_ABS_ZOOM_THRESH 4.0
2473
2474 #define MAX_GF_BOOST 5400
2475
2476 typedef struct RANGE {
2477 int min;
2478 int max;
2479 } RANGE;
2480
2481 /* get_gop_coding_frame_num() depends on several fields in RATE_CONTROL *rc as
2482 * follows.
2483 * Static fields:
2484 * (The following fields will remain unchanged after initialization of encoder.)
2485 * rc->static_scene_max_gf_interval
2486 * rc->min_gf_interval
2487 * twopass->sr_diff_factor
2488 * twopass->sr_default_decay_limit
2489 * twopass->zm_factor
2490 *
2491 * Dynamic fields:
2492 * (The following fields will be updated before or after coding each frame.)
2493 * rc->frames_to_key
2494 * rc->frames_since_key
2495 * rc->source_alt_ref_active
2496 *
2497 * Special case: if CONFIG_RATE_CTRL is true, the external arf indexes will
2498 * determine the arf position.
2499 *
2500 * TODO(angiebird): Separate the dynamic fields and static fields into two
2501 * structs.
2502 */
get_gop_coding_frame_num(int * use_alt_ref,const FRAME_INFO * frame_info,const TWO_PASS * const twopass,const RATE_CONTROL * rc,int gf_start_show_idx,const RANGE * active_gf_interval,double gop_intra_factor,int lag_in_frames,int * end_of_sequence)2503 static int get_gop_coding_frame_num(
2504 int *use_alt_ref, const FRAME_INFO *frame_info,
2505 const TWO_PASS *const twopass, const RATE_CONTROL *rc,
2506 int gf_start_show_idx, const RANGE *active_gf_interval,
2507 double gop_intra_factor, int lag_in_frames, int *end_of_sequence) {
2508 const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
2509 double loop_decay_rate = 1.00;
2510 double mv_ratio_accumulator = 0.0;
2511 double this_frame_mv_in_out = 0.0;
2512 double mv_in_out_accumulator = 0.0;
2513 double abs_mv_in_out_accumulator = 0.0;
2514 double sr_accumulator = 0.0;
2515 // Motion breakout threshold for loop below depends on image size.
2516 double mv_ratio_accumulator_thresh =
2517 (frame_info->frame_height + frame_info->frame_width) / 4.0;
2518 double zero_motion_accumulator = 1.0;
2519 int gop_coding_frames;
2520
2521 *use_alt_ref = 1;
2522 gop_coding_frames = 0;
2523 while (gop_coding_frames < rc->static_scene_max_gf_interval &&
2524 gop_coding_frames < rc->frames_to_key) {
2525 const FIRSTPASS_STATS *next_next_frame;
2526 const FIRSTPASS_STATS *next_frame;
2527 int flash_detected;
2528 ++gop_coding_frames;
2529
2530 next_frame = fps_get_frame_stats(first_pass_info,
2531 gf_start_show_idx + gop_coding_frames);
2532 if (next_frame == NULL) {
2533 *end_of_sequence = gop_coding_frames == 1 && rc->source_alt_ref_active;
2534 break;
2535 }
2536
2537 // Test for the case where there is a brief flash but the prediction
2538 // quality back to an earlier frame is then restored.
2539 next_next_frame = fps_get_frame_stats(
2540 first_pass_info, gf_start_show_idx + gop_coding_frames + 1);
2541 flash_detected = detect_flash_from_frame_stats(next_next_frame);
2542
2543 // Update the motion related elements to the boost calculation.
2544 accumulate_frame_motion_stats(
2545 next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2546 &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2547
2548 // Monitor for static sections.
2549 if ((rc->frames_since_key + gop_coding_frames - 1) > 1) {
2550 zero_motion_accumulator = VPXMIN(
2551 zero_motion_accumulator, get_zero_motion_factor(twopass, next_frame));
2552 }
2553
2554 // Accumulate the effect of prediction quality decay.
2555 if (!flash_detected) {
2556 double last_loop_decay_rate = loop_decay_rate;
2557 loop_decay_rate = get_prediction_decay_rate(twopass, next_frame);
2558
2559 // Break clause to detect very still sections after motion. For example,
2560 // a static image after a fade or other transition.
2561 if (gop_coding_frames > rc->min_gf_interval && loop_decay_rate >= 0.999 &&
2562 last_loop_decay_rate < 0.9) {
2563 int still_interval = 5;
2564 if (check_transition_to_still(first_pass_info,
2565 gf_start_show_idx + gop_coding_frames,
2566 still_interval)) {
2567 *use_alt_ref = 0;
2568 break;
2569 }
2570 }
2571
2572 // Update the accumulator for second ref error difference.
2573 // This is intended to give an indication of how much the coded error is
2574 // increasing over time.
2575 if (gop_coding_frames == 1) {
2576 sr_accumulator += next_frame->coded_error;
2577 } else {
2578 sr_accumulator +=
2579 (next_frame->sr_coded_error - next_frame->coded_error);
2580 }
2581 }
2582
2583 // Break out conditions.
2584 // Break at maximum of active_gf_interval->max unless almost totally
2585 // static.
2586 //
2587 // Note that the addition of a test of rc->source_alt_ref_active is
2588 // deliberate. The effect of this is that after a normal altref group even
2589 // if the material is static there will be one normal length GF group
2590 // before allowing longer GF groups. The reason for this is that in cases
2591 // such as slide shows where slides are separated by a complex transition
2592 // such as a fade, the arf group spanning the transition may not be coded
2593 // at a very high quality and hence this frame (with its overlay) is a
2594 // poor golden frame to use for an extended group.
2595 if ((gop_coding_frames >= active_gf_interval->max) &&
2596 ((zero_motion_accumulator < 0.995) || (rc->source_alt_ref_active))) {
2597 break;
2598 }
2599 if (
2600 // Don't break out with a very short interval.
2601 (gop_coding_frames >= active_gf_interval->min) &&
2602 // If possible don't break very close to a kf
2603 ((rc->frames_to_key - gop_coding_frames) >= rc->min_gf_interval) &&
2604 (gop_coding_frames & 0x01) && (!flash_detected) &&
2605 ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
2606 (abs_mv_in_out_accumulator > ARF_ABS_ZOOM_THRESH) ||
2607 (sr_accumulator > gop_intra_factor * next_frame->intra_error))) {
2608 break;
2609 }
2610 }
2611 *use_alt_ref &= zero_motion_accumulator < 0.995;
2612 *use_alt_ref &= gop_coding_frames < lag_in_frames;
2613 *use_alt_ref &= gop_coding_frames >= rc->min_gf_interval;
2614 return gop_coding_frames;
2615 }
2616
get_active_gf_inverval_range_simple(int min_gf_interval,int arf_active_or_kf,int frames_to_key)2617 static RANGE get_active_gf_inverval_range_simple(int min_gf_interval,
2618 int arf_active_or_kf,
2619 int frames_to_key) {
2620 RANGE active_gf_interval;
2621 active_gf_interval.min = min_gf_interval + arf_active_or_kf + 2;
2622 active_gf_interval.max = 16 + arf_active_or_kf;
2623
2624 if ((active_gf_interval.max <= frames_to_key) &&
2625 (active_gf_interval.max >= (frames_to_key - min_gf_interval))) {
2626 active_gf_interval.min = frames_to_key / 2;
2627 active_gf_interval.max = frames_to_key / 2;
2628 }
2629 return active_gf_interval;
2630 }
2631
get_active_gf_inverval_range(const FRAME_INFO * frame_info,const RATE_CONTROL * rc,int arf_active_or_kf,int gf_start_show_idx,int active_worst_quality,int last_boosted_qindex)2632 static RANGE get_active_gf_inverval_range(
2633 const FRAME_INFO *frame_info, const RATE_CONTROL *rc, int arf_active_or_kf,
2634 int gf_start_show_idx, int active_worst_quality, int last_boosted_qindex) {
2635 RANGE active_gf_interval;
2636 int int_max_q = (int)(vp9_convert_qindex_to_q(active_worst_quality,
2637 frame_info->bit_depth));
2638 int q_term = (gf_start_show_idx == 0)
2639 ? int_max_q / 32
2640 : (int)(vp9_convert_qindex_to_q(last_boosted_qindex,
2641 frame_info->bit_depth) /
2642 6);
2643 active_gf_interval.min =
2644 rc->min_gf_interval + arf_active_or_kf + VPXMIN(2, int_max_q / 200);
2645 active_gf_interval.min =
2646 VPXMIN(active_gf_interval.min, rc->max_gf_interval + arf_active_or_kf);
2647
2648 // The value chosen depends on the active Q range. At low Q we have
2649 // bits to spare and are better with a smaller interval and smaller boost.
2650 // At high Q when there are few bits to spare we are better with a longer
2651 // interval to spread the cost of the GF.
2652 active_gf_interval.max = 11 + arf_active_or_kf + VPXMIN(5, q_term);
2653
2654 // Force max GF interval to be odd.
2655 active_gf_interval.max = active_gf_interval.max | 0x01;
2656
2657 // We have: active_gf_interval.min <=
2658 // rc->max_gf_interval + arf_active_or_kf.
2659 if (active_gf_interval.max < active_gf_interval.min) {
2660 active_gf_interval.max = active_gf_interval.min;
2661 } else {
2662 active_gf_interval.max =
2663 VPXMIN(active_gf_interval.max, rc->max_gf_interval + arf_active_or_kf);
2664 }
2665
2666 // Would the active max drop us out just before the near the next kf?
2667 if ((active_gf_interval.max <= rc->frames_to_key) &&
2668 (active_gf_interval.max >= (rc->frames_to_key - rc->min_gf_interval))) {
2669 active_gf_interval.max = rc->frames_to_key / 2;
2670 }
2671 active_gf_interval.max =
2672 VPXMAX(active_gf_interval.max, active_gf_interval.min);
2673 return active_gf_interval;
2674 }
2675
get_arf_layers(int multi_layer_arf,int max_layers,int coding_frame_num)2676 static int get_arf_layers(int multi_layer_arf, int max_layers,
2677 int coding_frame_num) {
2678 assert(max_layers <= MAX_ARF_LAYERS);
2679 if (multi_layer_arf) {
2680 int layers = 0;
2681 int i;
2682 for (i = coding_frame_num; i > 0; i >>= 1) {
2683 ++layers;
2684 }
2685 layers = VPXMIN(max_layers, layers);
2686 return layers;
2687 } else {
2688 return 1;
2689 }
2690 }
2691
define_gf_group(VP9_COMP * cpi,int gf_start_show_idx)2692 static void define_gf_group(VP9_COMP *cpi, int gf_start_show_idx) {
2693 VP9_COMMON *const cm = &cpi->common;
2694 RATE_CONTROL *const rc = &cpi->rc;
2695 VP9EncoderConfig *const oxcf = &cpi->oxcf;
2696 TWO_PASS *const twopass = &cpi->twopass;
2697 const FRAME_INFO *frame_info = &cpi->frame_info;
2698 const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
2699 const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
2700 int gop_coding_frames;
2701
2702 double gf_group_err = 0.0;
2703 double gf_group_raw_error = 0.0;
2704 double gf_group_noise = 0.0;
2705 double gf_group_skip_pct = 0.0;
2706 double gf_group_inactive_zone_rows = 0.0;
2707 double gf_group_inter = 0.0;
2708 double gf_group_motion = 0.0;
2709
2710 int allow_alt_ref = is_altref_enabled(cpi);
2711 int use_alt_ref;
2712
2713 int64_t gf_group_bits;
2714 int gf_arf_bits;
2715 const int is_key_frame = frame_is_intra_only(cm);
2716 // If this is a key frame or the overlay from a previous arf then
2717 // the error score / cost of this frame has already been accounted for.
2718 const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
2719 int is_alt_ref_flash = 0;
2720
2721 double gop_intra_factor;
2722 int gop_frames;
2723 RANGE active_gf_interval;
2724 // Whether this is at the end of last GOP of this sequence.
2725 int end_of_sequence = 0;
2726
2727 // Reset the GF group data structures unless this is a key
2728 // frame in which case it will already have been done.
2729 if (is_key_frame == 0) {
2730 vp9_zero(twopass->gf_group);
2731 ++rc->gop_global_index;
2732 } else {
2733 rc->gop_global_index = 0;
2734 }
2735
2736 vpx_clear_system_state();
2737
2738 if (oxcf->use_simple_encode_api) {
2739 active_gf_interval = get_active_gf_inverval_range_simple(
2740 rc->min_gf_interval, arf_active_or_kf, rc->frames_to_key);
2741 } else {
2742 active_gf_interval = get_active_gf_inverval_range(
2743 frame_info, rc, arf_active_or_kf, gf_start_show_idx,
2744 twopass->active_worst_quality, rc->last_boosted_qindex);
2745 }
2746
2747 if (cpi->multi_layer_arf) {
2748 int arf_layers = get_arf_layers(cpi->multi_layer_arf, oxcf->enable_auto_arf,
2749 active_gf_interval.max);
2750 gop_intra_factor = 1.0 + 0.25 * arf_layers;
2751 } else {
2752 gop_intra_factor = 1.0;
2753 }
2754
2755 gop_coding_frames = get_gop_coding_frame_num(
2756 &use_alt_ref, frame_info, twopass, rc, gf_start_show_idx,
2757 &active_gf_interval, gop_intra_factor, cpi->oxcf.lag_in_frames,
2758 &end_of_sequence);
2759 use_alt_ref &= allow_alt_ref;
2760 #if CONFIG_RATE_CTRL
2761 // If the external gop_command is on, we will override the decisions
2762 // of gop_coding_frames and use_alt_ref.
2763 if (cpi->oxcf.use_simple_encode_api) {
2764 const GOP_COMMAND *gop_command = &cpi->encode_command.gop_command;
2765 assert(allow_alt_ref == 1);
2766 if (gop_command->use) {
2767 gop_coding_frames = gop_command_coding_frame_count(gop_command);
2768 use_alt_ref = gop_command->use_alt_ref;
2769 }
2770 }
2771 #endif
2772 // If the external rate control model for GOP is used, the gop decisions
2773 // are overwritten. Specifically, |gop_coding_frames| and |use_alt_ref|
2774 // will be overwritten.
2775 if (cpi->ext_ratectrl.ready &&
2776 (cpi->ext_ratectrl.funcs.rc_type & VPX_RC_GOP) != 0 &&
2777 cpi->ext_ratectrl.funcs.get_gop_decision != NULL && !end_of_sequence) {
2778 vpx_codec_err_t codec_status;
2779 vpx_rc_gop_decision_t gop_decision;
2780 vpx_rc_gop_info_t gop_info;
2781 gop_info.min_gf_interval = rc->min_gf_interval;
2782 gop_info.max_gf_interval = rc->max_gf_interval;
2783 gop_info.active_min_gf_interval = active_gf_interval.min;
2784 gop_info.active_max_gf_interval = active_gf_interval.max;
2785 gop_info.allow_alt_ref = allow_alt_ref;
2786 gop_info.is_key_frame = is_key_frame;
2787 gop_info.last_gop_use_alt_ref = rc->source_alt_ref_active;
2788 gop_info.frames_since_key = rc->frames_since_key;
2789 gop_info.frames_to_key = rc->frames_to_key;
2790 gop_info.lag_in_frames = cpi->oxcf.lag_in_frames;
2791 gop_info.show_index = cm->current_video_frame;
2792 gop_info.coding_index = cm->current_frame_coding_index;
2793 gop_info.gop_global_index = rc->gop_global_index;
2794
2795 codec_status = vp9_extrc_get_gop_decision(&cpi->ext_ratectrl, &gop_info,
2796 &gop_decision);
2797 if (codec_status != VPX_CODEC_OK) {
2798 vpx_internal_error(&cm->error, codec_status,
2799 "vp9_extrc_get_gop_decision() failed");
2800 }
2801 gop_coding_frames = gop_decision.gop_coding_frames;
2802 use_alt_ref = gop_decision.use_alt_ref;
2803 }
2804
2805 // Was the group length constrained by the requirement for a new KF?
2806 rc->constrained_gf_group = (gop_coding_frames >= rc->frames_to_key) ? 1 : 0;
2807
2808 // Should we use the alternate reference frame.
2809 if (use_alt_ref) {
2810 const int f_frames =
2811 (rc->frames_to_key - gop_coding_frames >= gop_coding_frames - 1)
2812 ? gop_coding_frames - 1
2813 : VPXMAX(0, rc->frames_to_key - gop_coding_frames);
2814 const int b_frames = gop_coding_frames - 1;
2815 const int avg_inter_frame_qindex = rc->avg_frame_qindex[INTER_FRAME];
2816 // TODO(angiebird): figure out why arf's location is assigned this way
2817 const int arf_show_idx = VPXMIN(gf_start_show_idx + gop_coding_frames + 1,
2818 fps_get_num_frames(first_pass_info));
2819
2820 // Calculate the boost for alt ref.
2821 rc->gfu_boost =
2822 compute_arf_boost(frame_info, twopass, arf_show_idx, f_frames, b_frames,
2823 avg_inter_frame_qindex);
2824 rc->source_alt_ref_pending = 1;
2825 } else {
2826 const int f_frames = gop_coding_frames - 1;
2827 const int b_frames = 0;
2828 const int avg_inter_frame_qindex = rc->avg_frame_qindex[INTER_FRAME];
2829 // TODO(angiebird): figure out why arf's location is assigned this way
2830 const int gld_show_idx =
2831 VPXMIN(gf_start_show_idx + 1, fps_get_num_frames(first_pass_info));
2832 const int arf_boost =
2833 compute_arf_boost(frame_info, twopass, gld_show_idx, f_frames, b_frames,
2834 avg_inter_frame_qindex);
2835 rc->gfu_boost = VPXMIN((int)twopass->gf_max_total_boost, arf_boost);
2836 rc->source_alt_ref_pending = 0;
2837 }
2838
2839 #define LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR 0.2
2840 rc->arf_active_best_quality_adjustment_factor = 1.0;
2841 rc->arf_increase_active_best_quality = 0;
2842
2843 if (!is_lossless_requested(&cpi->oxcf)) {
2844 if (rc->frames_since_key >= rc->frames_to_key) {
2845 // Increase the active best quality in the second half of key frame
2846 // interval.
2847 rc->arf_active_best_quality_adjustment_factor =
2848 LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR +
2849 (1.0 - LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR) *
2850 (rc->frames_to_key - gop_coding_frames) /
2851 (VPXMAX(1, ((rc->frames_to_key + rc->frames_since_key) / 2 -
2852 gop_coding_frames)));
2853 rc->arf_increase_active_best_quality = 1;
2854 } else if ((rc->frames_to_key - gop_coding_frames) > 0) {
2855 // Reduce the active best quality in the first half of key frame interval.
2856 rc->arf_active_best_quality_adjustment_factor =
2857 LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR +
2858 (1.0 - LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR) *
2859 (rc->frames_since_key + gop_coding_frames) /
2860 (VPXMAX(1, (rc->frames_to_key + rc->frames_since_key) / 2 +
2861 gop_coding_frames));
2862 rc->arf_increase_active_best_quality = -1;
2863 }
2864 }
2865
2866 #ifdef AGGRESSIVE_VBR
2867 // Limit maximum boost based on interval length.
2868 rc->gfu_boost = VPXMIN((int)rc->gfu_boost, gop_coding_frames * 140);
2869 #else
2870 rc->gfu_boost = VPXMIN((int)rc->gfu_boost, gop_coding_frames * 200);
2871 #endif
2872
2873 // Cap the ARF boost when perceptual quality AQ mode is enabled. This is
2874 // designed to improve the perceptual quality of high value content and to
2875 // make consistent quality across consecutive frames. It will hurt objective
2876 // quality.
2877 if (oxcf->aq_mode == PERCEPTUAL_AQ)
2878 rc->gfu_boost = VPXMIN(rc->gfu_boost, MIN_ARF_GF_BOOST);
2879
2880 rc->baseline_gf_interval = gop_coding_frames - rc->source_alt_ref_pending;
2881
2882 if (rc->source_alt_ref_pending)
2883 is_alt_ref_flash = detect_flash(twopass, rc->baseline_gf_interval);
2884
2885 {
2886 const double av_err = get_distribution_av_err(cpi, twopass);
2887 const double mean_mod_score = twopass->mean_mod_score;
2888 // If the first frame is a key frame or the overlay from a previous arf then
2889 // the error score / cost of this frame has already been accounted for.
2890 int start_idx = arf_active_or_kf ? 1 : 0;
2891 int j;
2892 for (j = start_idx; j < gop_coding_frames; ++j) {
2893 int show_idx = gf_start_show_idx + j;
2894 const FIRSTPASS_STATS *frame_stats =
2895 fps_get_frame_stats(first_pass_info, show_idx);
2896 // Accumulate error score of frames in this gf group.
2897 gf_group_err += calc_norm_frame_score(oxcf, frame_info, frame_stats,
2898 mean_mod_score, av_err);
2899 gf_group_raw_error += frame_stats->coded_error;
2900 gf_group_noise += frame_stats->frame_noise_energy;
2901 gf_group_skip_pct += frame_stats->intra_skip_pct;
2902 gf_group_inactive_zone_rows += frame_stats->inactive_zone_rows;
2903 gf_group_inter += frame_stats->pcnt_inter;
2904 gf_group_motion += frame_stats->pcnt_motion;
2905 }
2906 }
2907
2908 // Calculate the bits to be allocated to the gf/arf group as a whole
2909 gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
2910
2911 gop_frames =
2912 rc->baseline_gf_interval + rc->source_alt_ref_pending - arf_active_or_kf;
2913
2914 // Store the average moise level measured for the group
2915 // TODO(any): Experiment with removal of else condition (gop_frames = 0) so
2916 // that consumption of group noise energy is based on previous gf group
2917 if (gop_frames > 0)
2918 twopass->gf_group.group_noise_energy = (int)(gf_group_noise / gop_frames);
2919 else
2920 twopass->gf_group.group_noise_energy = 0;
2921
2922 // Calculate an estimate of the maxq needed for the group.
2923 // We are more aggressive about correcting for sections
2924 // where there could be significant overshoot than for easier
2925 // sections where we do not wish to risk creating an overshoot
2926 // of the allocated bit budget.
2927 if ((cpi->oxcf.rc_mode != VPX_Q) && (rc->baseline_gf_interval > 1)) {
2928 const int vbr_group_bits_per_frame = (int)(gf_group_bits / gop_frames);
2929 const double group_av_err = gf_group_raw_error / gop_frames;
2930 const double group_av_noise = gf_group_noise / gop_frames;
2931 const double group_av_skip_pct = gf_group_skip_pct / gop_frames;
2932 const double group_av_inactive_zone = ((gf_group_inactive_zone_rows * 2) /
2933 (gop_frames * (double)cm->mb_rows));
2934 int tmp_q = get_twopass_worst_quality(
2935 cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
2936 group_av_noise, vbr_group_bits_per_frame);
2937 twopass->active_worst_quality =
2938 (int)((tmp_q + (twopass->active_worst_quality *
2939 (twopass->active_wq_factor - 1))) /
2940 twopass->active_wq_factor);
2941
2942 #if CONFIG_ALWAYS_ADJUST_BPM
2943 // Reset rolling actual and target bits counters for ARF groups.
2944 twopass->rolling_arf_group_target_bits = 0;
2945 twopass->rolling_arf_group_actual_bits = 0;
2946 #endif
2947 }
2948
2949 // Context Adjustment of ARNR filter strength
2950 if (rc->baseline_gf_interval > 1) {
2951 adjust_group_arnr_filter(cpi, (gf_group_noise / gop_frames),
2952 (gf_group_inter / gop_frames),
2953 (gf_group_motion / gop_frames));
2954 } else {
2955 twopass->arnr_strength_adjustment = 0;
2956 }
2957
2958 // Calculate the extra bits to be used for boosted frame(s)
2959 gf_arf_bits = calculate_boost_bits((rc->baseline_gf_interval - 1),
2960 rc->gfu_boost, gf_group_bits);
2961
2962 // Adjust KF group bits and error remaining.
2963 twopass->kf_group_error_left -= gf_group_err;
2964
2965 // Decide GOP structure.
2966 define_gf_group_structure(cpi);
2967
2968 // Allocate bits to each of the frames in the GF group.
2969 allocate_gf_group_bits(cpi, gf_group_bits, gf_arf_bits);
2970
2971 // Reset the file position.
2972 reset_fpf_position(twopass, start_pos);
2973
2974 // Calculate a section intra ratio used in setting max loop filter.
2975 twopass->section_intra_rating = calculate_section_intra_ratio(
2976 start_pos, twopass->stats_in_end, rc->baseline_gf_interval);
2977
2978 if (oxcf->resize_mode == RESIZE_DYNAMIC) {
2979 // Default to starting GF groups at normal frame size.
2980 cpi->rc.next_frame_size_selector = UNSCALED;
2981 }
2982 #if !CONFIG_ALWAYS_ADJUST_BPM
2983 // Reset rolling actual and target bits counters for ARF groups.
2984 twopass->rolling_arf_group_target_bits = 0;
2985 twopass->rolling_arf_group_actual_bits = 0;
2986 #endif
2987 rc->preserve_arf_as_gld = rc->preserve_next_arf_as_gld;
2988 rc->preserve_next_arf_as_gld = 0;
2989 // If alt ref frame is flash do not set preserve_arf_as_gld
2990 if (!is_lossless_requested(&cpi->oxcf) && !cpi->use_svc &&
2991 cpi->oxcf.aq_mode == NO_AQ && cpi->multi_layer_arf && !is_alt_ref_flash)
2992 rc->preserve_next_arf_as_gld = 1;
2993 }
2994
2995 // Intra / Inter threshold very low
2996 #define VERY_LOW_II 1.5
2997 // Clean slide transitions we expect a sharp single frame spike in error.
2998 #define ERROR_SPIKE 5.0
2999
3000 // Slide show transition detection.
3001 // Tests for case where there is very low error either side of the current frame
3002 // but much higher just for this frame. This can help detect key frames in
3003 // slide shows even where the slides are pictures of different sizes.
3004 // Also requires that intra and inter errors are very similar to help eliminate
3005 // harmful false positives.
3006 // It will not help if the transition is a fade or other multi-frame effect.
slide_transition(const FIRSTPASS_STATS * this_frame,const FIRSTPASS_STATS * last_frame,const FIRSTPASS_STATS * next_frame)3007 static int slide_transition(const FIRSTPASS_STATS *this_frame,
3008 const FIRSTPASS_STATS *last_frame,
3009 const FIRSTPASS_STATS *next_frame) {
3010 return (this_frame->intra_error < (this_frame->coded_error * VERY_LOW_II)) &&
3011 (this_frame->coded_error > (last_frame->coded_error * ERROR_SPIKE)) &&
3012 (this_frame->coded_error > (next_frame->coded_error * ERROR_SPIKE));
3013 }
3014
3015 // This test looks for anomalous changes in the nature of the intra signal
3016 // related to the previous and next frame as an indicator for coding a key
3017 // frame. This test serves to detect some additional scene cuts,
3018 // especially in lowish motion and low contrast sections, that are missed
3019 // by the other tests.
intra_step_transition(const FIRSTPASS_STATS * this_frame,const FIRSTPASS_STATS * last_frame,const FIRSTPASS_STATS * next_frame)3020 static int intra_step_transition(const FIRSTPASS_STATS *this_frame,
3021 const FIRSTPASS_STATS *last_frame,
3022 const FIRSTPASS_STATS *next_frame) {
3023 double last_ii_ratio;
3024 double this_ii_ratio;
3025 double next_ii_ratio;
3026 double last_pcnt_intra = 1.0 - last_frame->pcnt_inter;
3027 double this_pcnt_intra = 1.0 - this_frame->pcnt_inter;
3028 double next_pcnt_intra = 1.0 - next_frame->pcnt_inter;
3029 double mod_this_intra = this_pcnt_intra + this_frame->pcnt_neutral;
3030
3031 // Calculate ii ratio for this frame last frame and next frame.
3032 last_ii_ratio =
3033 last_frame->intra_error / DOUBLE_DIVIDE_CHECK(last_frame->coded_error);
3034 this_ii_ratio =
3035 this_frame->intra_error / DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
3036 next_ii_ratio =
3037 next_frame->intra_error / DOUBLE_DIVIDE_CHECK(next_frame->coded_error);
3038
3039 // Return true the intra/inter ratio for the current frame is
3040 // low but better in the next and previous frame and the relative usage of
3041 // intra in the current frame is markedly higher than the last and next frame.
3042 if ((this_ii_ratio < 2.0) && (last_ii_ratio > 2.25) &&
3043 (next_ii_ratio > 2.25) && (this_pcnt_intra > (3 * last_pcnt_intra)) &&
3044 (this_pcnt_intra > (3 * next_pcnt_intra)) &&
3045 ((this_pcnt_intra > 0.075) || (mod_this_intra > 0.85))) {
3046 return 1;
3047 // Very low inter intra ratio (i.e. not much gain from inter coding), most
3048 // blocks neutral on coding method and better inter prediction either side
3049 } else if ((this_ii_ratio < 1.25) && (mod_this_intra > 0.85) &&
3050 (this_ii_ratio < last_ii_ratio * 0.9) &&
3051 (this_ii_ratio < next_ii_ratio * 0.9)) {
3052 return 1;
3053 } else {
3054 return 0;
3055 }
3056 }
3057
3058 // Minimum % intra coding observed in first pass (1.0 = 100%)
3059 #define MIN_INTRA_LEVEL 0.25
3060 // Threshold for use of the lagging second reference frame. Scene cuts do not
3061 // usually have a high second ref usage.
3062 #define SECOND_REF_USAGE_THRESH 0.2
3063 // Hard threshold where the first pass chooses intra for almost all blocks.
3064 // In such a case even if the frame is not a scene cut coding a key frame
3065 // may be a good option.
3066 #define VERY_LOW_INTER_THRESH 0.05
3067 // Maximum threshold for the relative ratio of intra error score vs best
3068 // inter error score.
3069 #define KF_II_ERR_THRESHOLD 2.5
3070 #define KF_II_MAX 128.0
3071 #define II_FACTOR 12.5
3072 // Test for very low intra complexity which could cause false key frames
3073 #define V_LOW_INTRA 0.5
3074
test_candidate_kf(const FIRST_PASS_INFO * first_pass_info,int show_idx)3075 static int test_candidate_kf(const FIRST_PASS_INFO *first_pass_info,
3076 int show_idx) {
3077 const FIRSTPASS_STATS *last_frame =
3078 fps_get_frame_stats(first_pass_info, show_idx - 1);
3079 const FIRSTPASS_STATS *this_frame =
3080 fps_get_frame_stats(first_pass_info, show_idx);
3081 const FIRSTPASS_STATS *next_frame =
3082 fps_get_frame_stats(first_pass_info, show_idx + 1);
3083 int is_viable_kf = 0;
3084 double pcnt_intra = 1.0 - this_frame->pcnt_inter;
3085
3086 // Does the frame satisfy the primary criteria of a key frame?
3087 // See above for an explanation of the test criteria.
3088 // If so, then examine how well it predicts subsequent frames.
3089 detect_flash_from_frame_stats(next_frame);
3090 if (!detect_flash_from_frame_stats(this_frame) &&
3091 !detect_flash_from_frame_stats(next_frame) &&
3092 (this_frame->pcnt_second_ref < SECOND_REF_USAGE_THRESH) &&
3093 ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
3094 (slide_transition(this_frame, last_frame, next_frame)) ||
3095 (intra_step_transition(this_frame, last_frame, next_frame)) ||
3096 (((this_frame->coded_error > (next_frame->coded_error * 1.2)) &&
3097 (this_frame->coded_error > (last_frame->coded_error * 1.2))) &&
3098 (pcnt_intra > MIN_INTRA_LEVEL) &&
3099 ((pcnt_intra + this_frame->pcnt_neutral) > 0.5) &&
3100 ((this_frame->intra_error /
3101 DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
3102 KF_II_ERR_THRESHOLD)))) {
3103 int i;
3104 double boost_score = 0.0;
3105 double old_boost_score = 0.0;
3106 double decay_accumulator = 1.0;
3107
3108 // Examine how well the key frame predicts subsequent frames.
3109 for (i = 0; i < 16; ++i) {
3110 const FIRSTPASS_STATS *frame_stats =
3111 fps_get_frame_stats(first_pass_info, show_idx + 1 + i);
3112 double next_iiratio = (II_FACTOR * frame_stats->intra_error /
3113 DOUBLE_DIVIDE_CHECK(frame_stats->coded_error));
3114
3115 if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
3116
3117 // Cumulative effect of decay in prediction quality.
3118 if (frame_stats->pcnt_inter > 0.85)
3119 decay_accumulator *= frame_stats->pcnt_inter;
3120 else
3121 decay_accumulator *= (0.85 + frame_stats->pcnt_inter) / 2.0;
3122
3123 // Keep a running total.
3124 boost_score += (decay_accumulator * next_iiratio);
3125
3126 // Test various breakout clauses.
3127 if ((frame_stats->pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
3128 (((frame_stats->pcnt_inter - frame_stats->pcnt_neutral) < 0.20) &&
3129 (next_iiratio < 3.0)) ||
3130 ((boost_score - old_boost_score) < 3.0) ||
3131 (frame_stats->intra_error < V_LOW_INTRA)) {
3132 break;
3133 }
3134
3135 old_boost_score = boost_score;
3136
3137 // Get the next frame details
3138 if (show_idx + 1 + i == fps_get_num_frames(first_pass_info) - 1) break;
3139 }
3140
3141 // If there is tolerable prediction for at least the next 3 frames then
3142 // break out else discard this potential key frame and move on
3143 if (boost_score > 30.0 && (i > 3)) {
3144 is_viable_kf = 1;
3145 } else {
3146 is_viable_kf = 0;
3147 }
3148 }
3149
3150 return is_viable_kf;
3151 }
3152
3153 #define FRAMES_TO_CHECK_DECAY 8
3154 #define MIN_KF_TOT_BOOST 300
3155 #define DEFAULT_SCAN_FRAMES_FOR_KF_BOOST 32
3156 #define MAX_SCAN_FRAMES_FOR_KF_BOOST 48
3157 #define MIN_SCAN_FRAMES_FOR_KF_BOOST 32
3158 #define KF_ABS_ZOOM_THRESH 6.0
3159
vp9_get_frames_to_next_key(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,int kf_show_idx,int min_gf_interval)3160 int vp9_get_frames_to_next_key(const VP9EncoderConfig *oxcf,
3161 const TWO_PASS *const twopass, int kf_show_idx,
3162 int min_gf_interval) {
3163 const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3164 double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
3165 int j;
3166 int frames_to_key;
3167 int max_frames_to_key = first_pass_info->num_frames - kf_show_idx;
3168 max_frames_to_key = VPXMIN(max_frames_to_key, oxcf->key_freq);
3169
3170 // Initialize the decay rates for the recent frames to check
3171 for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
3172 // Find the next keyframe.
3173 if (!oxcf->auto_key) {
3174 frames_to_key = max_frames_to_key;
3175 } else {
3176 frames_to_key = 1;
3177 while (frames_to_key < max_frames_to_key) {
3178 // Provided that we are not at the end of the file...
3179 if (kf_show_idx + frames_to_key + 1 < first_pass_info->num_frames) {
3180 double loop_decay_rate;
3181 double decay_accumulator;
3182 const FIRSTPASS_STATS *next_frame = fps_get_frame_stats(
3183 first_pass_info, kf_show_idx + frames_to_key + 1);
3184
3185 // Check for a scene cut.
3186 if (test_candidate_kf(first_pass_info, kf_show_idx + frames_to_key))
3187 break;
3188
3189 // How fast is the prediction quality decaying?
3190 loop_decay_rate = get_prediction_decay_rate(twopass, next_frame);
3191
3192 // We want to know something about the recent past... rather than
3193 // as used elsewhere where we are concerned with decay in prediction
3194 // quality since the last GF or KF.
3195 recent_loop_decay[(frames_to_key - 1) % FRAMES_TO_CHECK_DECAY] =
3196 loop_decay_rate;
3197 decay_accumulator = 1.0;
3198 for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
3199 decay_accumulator *= recent_loop_decay[j];
3200
3201 // Special check for transition or high motion followed by a
3202 // static scene.
3203 if ((frames_to_key - 1) > min_gf_interval && loop_decay_rate >= 0.999 &&
3204 decay_accumulator < 0.9) {
3205 int still_interval = oxcf->key_freq - (frames_to_key - 1);
3206 // TODO(angiebird): Figure out why we use "+1" here
3207 int show_idx = kf_show_idx + frames_to_key;
3208 if (check_transition_to_still(first_pass_info, show_idx,
3209 still_interval)) {
3210 break;
3211 }
3212 }
3213 }
3214 ++frames_to_key;
3215 }
3216 }
3217 return frames_to_key;
3218 }
3219
find_next_key_frame(VP9_COMP * cpi,int kf_show_idx)3220 static void find_next_key_frame(VP9_COMP *cpi, int kf_show_idx) {
3221 int i;
3222 RATE_CONTROL *const rc = &cpi->rc;
3223 TWO_PASS *const twopass = &cpi->twopass;
3224 GF_GROUP *const gf_group = &twopass->gf_group;
3225 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3226 const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3227 const FRAME_INFO *frame_info = &cpi->frame_info;
3228 const FIRSTPASS_STATS *const start_position = twopass->stats_in;
3229 const FIRSTPASS_STATS *keyframe_stats =
3230 fps_get_frame_stats(first_pass_info, kf_show_idx);
3231 FIRSTPASS_STATS next_frame;
3232 int kf_bits = 0;
3233 int64_t max_kf_bits;
3234 double zero_motion_accumulator = 1.0;
3235 double zero_motion_sum = 0.0;
3236 double zero_motion_avg;
3237 double motion_compensable_sum = 0.0;
3238 double motion_compensable_avg;
3239 int num_frames = 0;
3240 int kf_boost_scan_frames = DEFAULT_SCAN_FRAMES_FOR_KF_BOOST;
3241 double boost_score = 0.0;
3242 double kf_mod_err = 0.0;
3243 double kf_raw_err = 0.0;
3244 double kf_group_err = 0.0;
3245 double sr_accumulator = 0.0;
3246 double abs_mv_in_out_accumulator = 0.0;
3247 const double av_err = get_distribution_av_err(cpi, twopass);
3248 const double mean_mod_score = twopass->mean_mod_score;
3249 vp9_zero(next_frame);
3250
3251 cpi->common.frame_type = KEY_FRAME;
3252 rc->frames_since_key = 0;
3253
3254 // Reset the GF group data structures.
3255 vp9_zero(*gf_group);
3256
3257 // Is this a forced key frame by interval.
3258 rc->this_key_frame_forced = rc->next_key_frame_forced;
3259
3260 // Clear the alt ref active flag and last group multi arf flags as they
3261 // can never be set for a key frame.
3262 rc->source_alt_ref_active = 0;
3263
3264 // KF is always a GF so clear frames till next gf counter.
3265 rc->frames_till_gf_update_due = 0;
3266
3267 rc->frames_to_key = 1;
3268
3269 twopass->kf_group_bits = 0; // Total bits available to kf group
3270 twopass->kf_group_error_left = 0.0; // Group modified error score.
3271
3272 kf_raw_err = keyframe_stats->intra_error;
3273 kf_mod_err = calc_norm_frame_score(oxcf, frame_info, keyframe_stats,
3274 mean_mod_score, av_err);
3275
3276 rc->frames_to_key = vp9_get_frames_to_next_key(oxcf, twopass, kf_show_idx,
3277 rc->min_gf_interval);
3278
3279 // If there is a max kf interval set by the user we must obey it.
3280 // We already breakout of the loop above at 2x max.
3281 // This code centers the extra kf if the actual natural interval
3282 // is between 1x and 2x.
3283 if (rc->frames_to_key >= cpi->oxcf.key_freq) {
3284 rc->next_key_frame_forced = 1;
3285 } else {
3286 rc->next_key_frame_forced = 0;
3287 }
3288
3289 for (i = 0; i < rc->frames_to_key; ++i) {
3290 const FIRSTPASS_STATS *frame_stats =
3291 fps_get_frame_stats(first_pass_info, kf_show_idx + i);
3292 // Accumulate kf group error.
3293 kf_group_err += calc_norm_frame_score(oxcf, frame_info, frame_stats,
3294 mean_mod_score, av_err);
3295 }
3296
3297 // Calculate the number of bits that should be assigned to the kf group.
3298 if (twopass->bits_left > 0 && twopass->normalized_score_left > 0.0) {
3299 // Maximum number of bits for a single normal frame (not key frame).
3300 const int max_bits = frame_max_bits(rc, &cpi->oxcf);
3301
3302 // Maximum number of bits allocated to the key frame group.
3303 int64_t max_grp_bits;
3304
3305 // Default allocation based on bits left and relative
3306 // complexity of the section.
3307 twopass->kf_group_bits = (int64_t)(
3308 twopass->bits_left * (kf_group_err / twopass->normalized_score_left));
3309
3310 // Clip based on maximum per frame rate defined by the user.
3311 max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
3312 if (twopass->kf_group_bits > max_grp_bits)
3313 twopass->kf_group_bits = max_grp_bits;
3314 } else {
3315 twopass->kf_group_bits = 0;
3316 }
3317 twopass->kf_group_bits = VPXMAX(0, twopass->kf_group_bits);
3318
3319 // Scan through the kf group collating various stats used to determine
3320 // how many bits to spend on it.
3321 boost_score = 0.0;
3322
3323 for (i = 0; i < VPXMIN(MAX_SCAN_FRAMES_FOR_KF_BOOST, (rc->frames_to_key - 1));
3324 ++i) {
3325 if (EOF == input_stats(twopass, &next_frame)) break;
3326
3327 zero_motion_sum += next_frame.pcnt_inter - next_frame.pcnt_motion;
3328 motion_compensable_sum +=
3329 1 - (double)next_frame.coded_error / next_frame.intra_error;
3330 num_frames++;
3331 }
3332
3333 if (num_frames >= MIN_SCAN_FRAMES_FOR_KF_BOOST) {
3334 zero_motion_avg = zero_motion_sum / num_frames;
3335 motion_compensable_avg = motion_compensable_sum / num_frames;
3336 kf_boost_scan_frames = (int)(VPXMAX(64 * zero_motion_avg - 16,
3337 160 * motion_compensable_avg - 112));
3338 kf_boost_scan_frames =
3339 VPXMAX(VPXMIN(kf_boost_scan_frames, MAX_SCAN_FRAMES_FOR_KF_BOOST),
3340 MIN_SCAN_FRAMES_FOR_KF_BOOST);
3341 }
3342 reset_fpf_position(twopass, start_position);
3343
3344 for (i = 0; i < (rc->frames_to_key - 1); ++i) {
3345 if (EOF == input_stats(twopass, &next_frame)) break;
3346
3347 // The zero motion test here insures that if we mark a kf group as static
3348 // it is static throughout not just the first KF_BOOST_SCAN_MAX_FRAMES.
3349 // It also allows for a larger boost on long static groups.
3350 if ((i <= kf_boost_scan_frames) || (zero_motion_accumulator >= 0.99)) {
3351 double frame_boost;
3352 double zm_factor;
3353
3354 // Monitor for static sections.
3355 // First frame in kf group the second ref indicator is invalid.
3356 if (i > 0) {
3357 zero_motion_accumulator =
3358 VPXMIN(zero_motion_accumulator,
3359 get_zero_motion_factor(twopass, &next_frame));
3360 } else {
3361 zero_motion_accumulator =
3362 next_frame.pcnt_inter - next_frame.pcnt_motion;
3363 }
3364
3365 // Factor 0.75-1.25 based on how much of frame is static.
3366 zm_factor = (0.75 + (zero_motion_accumulator / 2.0));
3367
3368 // The second (lagging) ref error is not valid immediately after
3369 // a key frame because either the lag has not built up (in the case of
3370 // the first key frame or it points to a reference before the new key
3371 // frame.
3372 if (i < 2) sr_accumulator = 0.0;
3373 frame_boost =
3374 calc_kf_frame_boost(cpi, &next_frame, &sr_accumulator, 0, zm_factor);
3375
3376 boost_score += frame_boost;
3377
3378 // Measure of zoom. Large zoom tends to indicate reduced boost.
3379 abs_mv_in_out_accumulator +=
3380 fabs(next_frame.mv_in_out_count * next_frame.pcnt_motion);
3381
3382 if ((frame_boost < 25.00) ||
3383 (abs_mv_in_out_accumulator > KF_ABS_ZOOM_THRESH) ||
3384 (sr_accumulator > (kf_raw_err * 1.50)))
3385 break;
3386 } else {
3387 break;
3388 }
3389 }
3390
3391 reset_fpf_position(twopass, start_position);
3392
3393 // Store the zero motion percentage
3394 twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
3395
3396 // Calculate a section intra ratio used in setting max loop filter.
3397 twopass->key_frame_section_intra_rating = calculate_section_intra_ratio(
3398 start_position, twopass->stats_in_end, rc->frames_to_key);
3399
3400 // Special case for static / slide show content but don't apply
3401 // if the kf group is very short.
3402 if ((zero_motion_accumulator > 0.99) && (rc->frames_to_key > 8)) {
3403 rc->kf_boost = (int)(twopass->kf_max_total_boost);
3404 } else {
3405 // Apply various clamps for min and max oost
3406 rc->kf_boost = VPXMAX((int)boost_score, (rc->frames_to_key * 3));
3407 rc->kf_boost = VPXMAX(rc->kf_boost, MIN_KF_TOT_BOOST);
3408 rc->kf_boost = VPXMIN(rc->kf_boost, (int)(twopass->kf_max_total_boost));
3409 }
3410
3411 // Work out how many bits to allocate for the key frame itself.
3412 kf_bits = calculate_boost_bits((rc->frames_to_key - 1), rc->kf_boost,
3413 twopass->kf_group_bits);
3414 // Based on the spatial complexity, increase the bits allocated to key frame.
3415 kf_bits +=
3416 (int)((twopass->kf_group_bits - kf_bits) * (kf_mod_err / kf_group_err));
3417 max_kf_bits =
3418 twopass->kf_group_bits - (rc->frames_to_key - 1) * FRAME_OVERHEAD_BITS;
3419 max_kf_bits = lclamp(max_kf_bits, 0, INT_MAX);
3420 kf_bits = VPXMIN(kf_bits, (int)max_kf_bits);
3421
3422 twopass->kf_group_bits -= kf_bits;
3423
3424 // Save the bits to spend on the key frame.
3425 gf_group->bit_allocation[0] = kf_bits;
3426 gf_group->update_type[0] = KF_UPDATE;
3427 gf_group->rf_level[0] = KF_STD;
3428 gf_group->layer_depth[0] = 0;
3429
3430 // Note the total error score of the kf group minus the key frame itself.
3431 twopass->kf_group_error_left = (kf_group_err - kf_mod_err);
3432
3433 // Adjust the count of total modified error left.
3434 // The count of bits left is adjusted elsewhere based on real coded frame
3435 // sizes.
3436 twopass->normalized_score_left -= kf_group_err;
3437
3438 if (oxcf->resize_mode == RESIZE_DYNAMIC) {
3439 // Default to normal-sized frame on keyframes.
3440 cpi->rc.next_frame_size_selector = UNSCALED;
3441 }
3442 }
3443
3444 // Configure image size specific vizier parameters.
3445 // Later these will be set via additional command line options
vp9_init_vizier_params(TWO_PASS * const twopass,int screen_area)3446 void vp9_init_vizier_params(TWO_PASS *const twopass, int screen_area) {
3447 // When |use_vizier_rc_params| is 1, we expect the rc parameters below to
3448 // have been initialised on the command line as adjustment factors such
3449 // that a factor of 1.0 will match the default behavior when
3450 // |use_vizier_rc_params| is 0
3451 if (twopass->use_vizier_rc_params) {
3452 twopass->active_wq_factor *= AV_WQ_FACTOR;
3453 twopass->err_per_mb *= BASELINE_ERR_PER_MB;
3454 twopass->sr_default_decay_limit *= DEFAULT_DECAY_LIMIT;
3455 if (twopass->sr_default_decay_limit > 1.0) // > 1.0 here makes no sense
3456 twopass->sr_default_decay_limit = 1.0;
3457 twopass->sr_diff_factor *= 1.0;
3458 twopass->gf_frame_max_boost *= GF_MAX_FRAME_BOOST;
3459 twopass->gf_max_total_boost *= MAX_GF_BOOST;
3460 // NOTE: In use max boost has precedence over min boost. So even if min is
3461 // somehow set higher than max the final boost value will be clamped to the
3462 // appropriate maximum.
3463 twopass->kf_frame_min_boost *= KF_MIN_FRAME_BOOST;
3464 twopass->kf_frame_max_boost_first *= KF_MAX_FRAME_BOOST;
3465 twopass->kf_frame_max_boost_subs *= KF_MAX_FRAME_BOOST;
3466 twopass->kf_max_total_boost *= MAX_KF_TOT_BOOST;
3467 twopass->zm_factor *= DEFAULT_ZM_FACTOR;
3468 if (twopass->zm_factor > 1.0) // > 1.0 here makes no sense
3469 twopass->zm_factor = 1.0;
3470
3471 // Correction for the fact that the kf_err_per_mb_factor default is
3472 // already different for different video formats and ensures that a passed
3473 // in value of 1.0 on the vizier command line will still match the current
3474 // default.
3475 if (screen_area < 1280 * 720) {
3476 twopass->kf_err_per_mb *= 2000.0;
3477 } else if (screen_area < 1920 * 1080) {
3478 twopass->kf_err_per_mb *= 500.0;
3479 } else {
3480 twopass->kf_err_per_mb *= 250.0;
3481 }
3482 } else {
3483 // When |use_vizier_rc_params| is 0, use defaults.
3484 twopass->active_wq_factor = AV_WQ_FACTOR;
3485 twopass->err_per_mb = BASELINE_ERR_PER_MB;
3486 twopass->sr_default_decay_limit = DEFAULT_DECAY_LIMIT;
3487 twopass->sr_diff_factor = 1.0;
3488 twopass->gf_frame_max_boost = GF_MAX_FRAME_BOOST;
3489 twopass->gf_max_total_boost = MAX_GF_BOOST;
3490 twopass->kf_frame_min_boost = KF_MIN_FRAME_BOOST;
3491 twopass->kf_frame_max_boost_first = KF_MAX_FRAME_BOOST;
3492 twopass->kf_frame_max_boost_subs = KF_MAX_FRAME_BOOST;
3493 twopass->kf_max_total_boost = MAX_KF_TOT_BOOST;
3494 twopass->zm_factor = DEFAULT_ZM_FACTOR;
3495
3496 if (screen_area < 1280 * 720) {
3497 twopass->kf_err_per_mb = 2000.0;
3498 } else if (screen_area < 1920 * 1080) {
3499 twopass->kf_err_per_mb = 500.0;
3500 } else {
3501 twopass->kf_err_per_mb = 250.0;
3502 }
3503 }
3504 }
3505
vp9_rc_get_second_pass_params(VP9_COMP * cpi)3506 void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
3507 VP9_COMMON *const cm = &cpi->common;
3508 RATE_CONTROL *const rc = &cpi->rc;
3509 TWO_PASS *const twopass = &cpi->twopass;
3510 GF_GROUP *const gf_group = &twopass->gf_group;
3511 FIRSTPASS_STATS this_frame;
3512 const int show_idx = cm->current_video_frame;
3513
3514 if (cpi->common.current_frame_coding_index == 0 &&
3515 cpi->ext_ratectrl.funcs.send_firstpass_stats != NULL) {
3516 const vpx_codec_err_t codec_status = vp9_extrc_send_firstpass_stats(
3517 &cpi->ext_ratectrl, &cpi->twopass.first_pass_info);
3518 if (codec_status != VPX_CODEC_OK) {
3519 vpx_internal_error(&cm->error, codec_status,
3520 "vp9_extrc_send_firstpass_stats() failed");
3521 }
3522 }
3523
3524 if (!twopass->stats_in) return;
3525
3526 // Configure image size specific vizier parameters
3527 if (cm->current_video_frame == 0) {
3528 unsigned int screen_area = (cm->width * cm->height);
3529
3530 vp9_init_vizier_params(twopass, screen_area);
3531 }
3532
3533 // If this is an arf frame then we don't want to read the stats file or
3534 // advance the input pointer as we already have what we need.
3535 if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
3536 int target_rate;
3537
3538 vp9_zero(this_frame);
3539 this_frame =
3540 cpi->twopass.stats_in_start[cm->current_video_frame +
3541 gf_group->arf_src_offset[gf_group->index]];
3542
3543 vp9_configure_buffer_updates(cpi, gf_group->index);
3544
3545 target_rate = gf_group->bit_allocation[gf_group->index];
3546 target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
3547 rc->base_frame_target = target_rate;
3548
3549 cm->frame_type = INTER_FRAME;
3550
3551 // The multiplication by 256 reverses a scaling factor of (>> 8)
3552 // applied when combining MB error values for the frame.
3553 twopass->mb_av_energy = log((this_frame.intra_error * 256.0) + 1.0);
3554 twopass->mb_smooth_pct = this_frame.intra_smooth_pct;
3555
3556 return;
3557 }
3558
3559 vpx_clear_system_state();
3560
3561 if (cpi->oxcf.rc_mode == VPX_Q) {
3562 twopass->active_worst_quality = cpi->oxcf.cq_level;
3563 } else if (cm->current_video_frame == 0) {
3564 const int frames_left =
3565 (int)(twopass->total_stats.count - cm->current_video_frame);
3566 // Special case code for first frame.
3567 const int section_target_bandwidth =
3568 (int)(twopass->bits_left / frames_left);
3569 const double section_length = twopass->total_left_stats.count;
3570 const double section_error =
3571 twopass->total_left_stats.coded_error / section_length;
3572 const double section_intra_skip =
3573 twopass->total_left_stats.intra_skip_pct / section_length;
3574 const double section_inactive_zone =
3575 (twopass->total_left_stats.inactive_zone_rows * 2) /
3576 ((double)cm->mb_rows * section_length);
3577 const double section_noise =
3578 twopass->total_left_stats.frame_noise_energy / section_length;
3579 int tmp_q;
3580
3581 tmp_q = get_twopass_worst_quality(
3582 cpi, section_error, section_intra_skip + section_inactive_zone,
3583 section_noise, section_target_bandwidth);
3584
3585 twopass->active_worst_quality = tmp_q;
3586 twopass->baseline_active_worst_quality = tmp_q;
3587 rc->ni_av_qi = tmp_q;
3588 rc->last_q[INTER_FRAME] = tmp_q;
3589 rc->avg_q = vp9_convert_qindex_to_q(tmp_q, cm->bit_depth);
3590 rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
3591 rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
3592 rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
3593 }
3594 vp9_zero(this_frame);
3595 if (EOF == input_stats(twopass, &this_frame)) return;
3596
3597 // Set the frame content type flag.
3598 if (this_frame.intra_skip_pct >= FC_ANIMATION_THRESH)
3599 twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
3600 else
3601 twopass->fr_content_type = FC_NORMAL;
3602
3603 // Keyframe and section processing.
3604 if (rc->frames_to_key == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY)) {
3605 // Define next KF group and assign bits to it.
3606 find_next_key_frame(cpi, show_idx);
3607 } else {
3608 cm->frame_type = INTER_FRAME;
3609 }
3610
3611 // Define a new GF/ARF group. (Should always enter here for key frames).
3612 if (rc->frames_till_gf_update_due == 0) {
3613 define_gf_group(cpi, show_idx);
3614
3615 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3616
3617 #if ARF_STATS_OUTPUT
3618 {
3619 FILE *fpfile;
3620 fpfile = fopen("arf.stt", "a");
3621 ++arf_count;
3622 fprintf(fpfile, "%10d %10ld %10d %10d %10ld %10ld\n",
3623 cm->current_video_frame, rc->frames_till_gf_update_due,
3624 rc->kf_boost, arf_count, rc->gfu_boost, cm->frame_type);
3625
3626 fclose(fpfile);
3627 }
3628 #endif
3629 }
3630
3631 vp9_configure_buffer_updates(cpi, gf_group->index);
3632
3633 rc->base_frame_target = gf_group->bit_allocation[gf_group->index];
3634
3635 // The multiplication by 256 reverses a scaling factor of (>> 8)
3636 // applied when combining MB error values for the frame.
3637 twopass->mb_av_energy = log((this_frame.intra_error * 256.0) + 1.0);
3638 twopass->mb_smooth_pct = this_frame.intra_smooth_pct;
3639
3640 // Update the total stats remaining structure.
3641 subtract_stats(&twopass->total_left_stats, &this_frame);
3642 }
3643
vp9_twopass_postencode_update(VP9_COMP * cpi)3644 void vp9_twopass_postencode_update(VP9_COMP *cpi) {
3645 TWO_PASS *const twopass = &cpi->twopass;
3646 RATE_CONTROL *const rc = &cpi->rc;
3647 VP9_COMMON *const cm = &cpi->common;
3648 const int bits_used = rc->base_frame_target;
3649
3650 // VBR correction is done through rc->vbr_bits_off_target. Based on the
3651 // sign of this value, a limited % adjustment is made to the target rate
3652 // of subsequent frames, to try and push it back towards 0. This method
3653 // is designed to prevent extreme behaviour at the end of a clip
3654 // or group of frames.
3655 rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
3656 twopass->bits_left = VPXMAX(twopass->bits_left - bits_used, 0);
3657
3658 // Target vs actual bits for this arf group.
3659 twopass->rolling_arf_group_target_bits += rc->this_frame_target;
3660 twopass->rolling_arf_group_actual_bits += rc->projected_frame_size;
3661
3662 // Calculate the pct rc error.
3663 if (rc->total_actual_bits) {
3664 rc->rate_error_estimate =
3665 (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
3666 rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
3667 } else {
3668 rc->rate_error_estimate = 0;
3669 }
3670
3671 if (cpi->common.frame_type != KEY_FRAME) {
3672 twopass->kf_group_bits -= bits_used;
3673 twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
3674 }
3675 twopass->kf_group_bits = VPXMAX(twopass->kf_group_bits, 0);
3676
3677 // Increment the gf group index ready for the next frame.
3678 ++twopass->gf_group.index;
3679
3680 // If the rate control is drifting consider adjustment to min or maxq.
3681 if ((cpi->oxcf.rc_mode != VPX_Q) && !cpi->rc.is_src_frame_alt_ref) {
3682 const int maxq_adj_limit =
3683 rc->worst_quality - twopass->active_worst_quality;
3684 const int minq_adj_limit =
3685 (cpi->oxcf.rc_mode == VPX_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
3686 int aq_extend_min = 0;
3687 int aq_extend_max = 0;
3688
3689 // Extend min or Max Q range to account for imbalance from the base
3690 // value when using AQ.
3691 if (cpi->oxcf.aq_mode != NO_AQ && cpi->oxcf.aq_mode != PSNR_AQ &&
3692 cpi->oxcf.aq_mode != PERCEPTUAL_AQ) {
3693 if (cm->seg.aq_av_offset < 0) {
3694 // The balance of the AQ map tends towarda lowering the average Q.
3695 aq_extend_min = 0;
3696 aq_extend_max = VPXMIN(maxq_adj_limit, -cm->seg.aq_av_offset);
3697 } else {
3698 // The balance of the AQ map tends towards raising the average Q.
3699 aq_extend_min = VPXMIN(minq_adj_limit, cm->seg.aq_av_offset);
3700 aq_extend_max = 0;
3701 }
3702 }
3703
3704 // Undershoot.
3705 if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
3706 --twopass->extend_maxq;
3707 if (rc->rolling_target_bits >= rc->rolling_actual_bits)
3708 ++twopass->extend_minq;
3709 // Overshoot.
3710 } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
3711 --twopass->extend_minq;
3712 if (rc->rolling_target_bits < rc->rolling_actual_bits)
3713 ++twopass->extend_maxq;
3714 } else {
3715 // Adjustment for extreme local overshoot.
3716 if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
3717 rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
3718 ++twopass->extend_maxq;
3719
3720 // Unwind undershoot or overshoot adjustment.
3721 if (rc->rolling_target_bits < rc->rolling_actual_bits)
3722 --twopass->extend_minq;
3723 else if (rc->rolling_target_bits > rc->rolling_actual_bits)
3724 --twopass->extend_maxq;
3725 }
3726
3727 twopass->extend_minq =
3728 clamp(twopass->extend_minq, aq_extend_min, minq_adj_limit);
3729 twopass->extend_maxq =
3730 clamp(twopass->extend_maxq, aq_extend_max, maxq_adj_limit);
3731
3732 // If there is a big and undexpected undershoot then feed the extra
3733 // bits back in quickly. One situation where this may happen is if a
3734 // frame is unexpectedly almost perfectly predicted by the ARF or GF
3735 // but not very well predcited by the previous frame.
3736 if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
3737 int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
3738 if (rc->projected_frame_size < fast_extra_thresh) {
3739 rc->vbr_bits_off_target_fast +=
3740 fast_extra_thresh - rc->projected_frame_size;
3741 rc->vbr_bits_off_target_fast =
3742 VPXMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
3743
3744 // Fast adaptation of minQ if necessary to use up the extra bits.
3745 if (rc->avg_frame_bandwidth) {
3746 twopass->extend_minq_fast =
3747 (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
3748 }
3749 twopass->extend_minq_fast = VPXMIN(
3750 twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3751 } else if (rc->vbr_bits_off_target_fast) {
3752 twopass->extend_minq_fast = VPXMIN(
3753 twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3754 } else {
3755 twopass->extend_minq_fast = 0;
3756 }
3757 }
3758 }
3759 }
3760
3761 #if CONFIG_RATE_CTRL
vp9_get_next_group_of_picture(const VP9_COMP * cpi,int * first_is_key_frame,int * use_alt_ref,int * coding_frame_count,int * first_show_idx,int * last_gop_use_alt_ref)3762 void vp9_get_next_group_of_picture(const VP9_COMP *cpi, int *first_is_key_frame,
3763 int *use_alt_ref, int *coding_frame_count,
3764 int *first_show_idx,
3765 int *last_gop_use_alt_ref) {
3766 const GOP_COMMAND *gop_command = &cpi->encode_command.gop_command;
3767 // We make a copy of rc here because we want to get information from the
3768 // encoder without changing its state.
3769 // TODO(angiebird): Avoid copying rc here.
3770 RATE_CONTROL rc = cpi->rc;
3771 const int multi_layer_arf = 0;
3772 const int allow_alt_ref = 1;
3773 // We assume that current_video_frame is updated to the show index of the
3774 // frame we are about to called. Note that current_video_frame is updated at
3775 // the end of encode_frame_to_data_rate().
3776 // TODO(angiebird): Avoid this kind of fragile style.
3777 *first_show_idx = cpi->common.current_video_frame;
3778 *last_gop_use_alt_ref = rc.source_alt_ref_active;
3779
3780 *first_is_key_frame = 0;
3781 if (rc.frames_to_key == 0) {
3782 rc.frames_to_key = vp9_get_frames_to_next_key(
3783 &cpi->oxcf, &cpi->twopass, *first_show_idx, rc.min_gf_interval);
3784 rc.frames_since_key = 0;
3785 *first_is_key_frame = 1;
3786 }
3787
3788 if (gop_command->use) {
3789 *coding_frame_count = gop_command_coding_frame_count(gop_command);
3790 *use_alt_ref = gop_command->use_alt_ref;
3791 assert(gop_command->show_frame_count <= rc.frames_to_key);
3792 } else {
3793 *coding_frame_count = vp9_get_gop_coding_frame_count(
3794 &cpi->oxcf, &cpi->twopass, &cpi->frame_info, &rc, *first_show_idx,
3795 multi_layer_arf, allow_alt_ref, *first_is_key_frame,
3796 *last_gop_use_alt_ref, use_alt_ref);
3797 }
3798 }
3799
vp9_get_gop_coding_frame_count(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,const FRAME_INFO * frame_info,const RATE_CONTROL * rc,int show_idx,int multi_layer_arf,int allow_alt_ref,int first_is_key_frame,int last_gop_use_alt_ref,int * use_alt_ref)3800 int vp9_get_gop_coding_frame_count(const VP9EncoderConfig *oxcf,
3801 const TWO_PASS *const twopass,
3802 const FRAME_INFO *frame_info,
3803 const RATE_CONTROL *rc, int show_idx,
3804 int multi_layer_arf, int allow_alt_ref,
3805 int first_is_key_frame,
3806 int last_gop_use_alt_ref, int *use_alt_ref) {
3807 int frame_count;
3808 double gop_intra_factor;
3809 const int arf_active_or_kf = last_gop_use_alt_ref || first_is_key_frame;
3810 RANGE active_gf_interval;
3811 int arf_layers;
3812 int end_of_sequence = 0;
3813 if (oxcf->use_simple_encode_api) {
3814 active_gf_interval = get_active_gf_inverval_range_simple(
3815 rc->min_gf_interval, arf_active_or_kf, rc->frames_to_key);
3816 } else {
3817 active_gf_interval = get_active_gf_inverval_range(
3818 frame_info, rc, arf_active_or_kf, show_idx, /*active_worst_quality=*/0,
3819 /*last_boosted_qindex=*/0);
3820 }
3821
3822 arf_layers = get_arf_layers(multi_layer_arf, oxcf->enable_auto_arf,
3823 active_gf_interval.max);
3824 if (multi_layer_arf) {
3825 gop_intra_factor = 1.0 + 0.25 * arf_layers;
3826 } else {
3827 gop_intra_factor = 1.0;
3828 }
3829
3830 frame_count = get_gop_coding_frame_num(
3831 use_alt_ref, frame_info, twopass, rc, show_idx, &active_gf_interval,
3832 gop_intra_factor, oxcf->lag_in_frames, &end_of_sequence);
3833 *use_alt_ref &= allow_alt_ref;
3834 return frame_count;
3835 }
3836
3837 // Under CONFIG_RATE_CTRL, once the first_pass_info is ready, the number of
3838 // coding frames (including show frame and alt ref) can be determined.
vp9_get_coding_frame_num(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,const FRAME_INFO * frame_info,int multi_layer_arf,int allow_alt_ref)3839 int vp9_get_coding_frame_num(const VP9EncoderConfig *oxcf,
3840 const TWO_PASS *const twopass,
3841 const FRAME_INFO *frame_info, int multi_layer_arf,
3842 int allow_alt_ref) {
3843 const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3844 int coding_frame_num = 0;
3845 RATE_CONTROL rc;
3846 int gop_coding_frame_count;
3847 int gop_show_frames;
3848 int show_idx = 0;
3849 int last_gop_use_alt_ref = 0;
3850 vp9_rc_init(oxcf, 1, &rc);
3851
3852 while (show_idx < first_pass_info->num_frames) {
3853 int use_alt_ref;
3854 int first_is_key_frame = 0;
3855 if (rc.frames_to_key == 0) {
3856 rc.frames_to_key = vp9_get_frames_to_next_key(oxcf, twopass, show_idx,
3857 rc.min_gf_interval);
3858 rc.frames_since_key = 0;
3859 first_is_key_frame = 1;
3860 }
3861
3862 gop_coding_frame_count = vp9_get_gop_coding_frame_count(
3863 oxcf, twopass, frame_info, &rc, show_idx, multi_layer_arf,
3864 allow_alt_ref, first_is_key_frame, last_gop_use_alt_ref, &use_alt_ref);
3865
3866 rc.source_alt_ref_active = use_alt_ref;
3867 last_gop_use_alt_ref = use_alt_ref;
3868 gop_show_frames = gop_coding_frame_count - use_alt_ref;
3869 rc.frames_to_key -= gop_show_frames;
3870 rc.frames_since_key += gop_show_frames;
3871 show_idx += gop_show_frames;
3872 coding_frame_num += gop_show_frames + use_alt_ref;
3873 }
3874 return coding_frame_num;
3875 }
3876
vp9_get_key_frame_map(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,int * key_frame_map)3877 void vp9_get_key_frame_map(const VP9EncoderConfig *oxcf,
3878 const TWO_PASS *const twopass, int *key_frame_map) {
3879 const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3880 int show_idx = 0;
3881 RATE_CONTROL rc;
3882 vp9_rc_init(oxcf, 1, &rc);
3883
3884 // key_frame_map points to an int array with size equal to
3885 // first_pass_info->num_frames, which is also the number of show frames in the
3886 // video.
3887 memset(key_frame_map, 0,
3888 sizeof(*key_frame_map) * first_pass_info->num_frames);
3889 while (show_idx < first_pass_info->num_frames) {
3890 int key_frame_group_size;
3891 key_frame_map[show_idx] = 1;
3892 key_frame_group_size =
3893 vp9_get_frames_to_next_key(oxcf, twopass, show_idx, rc.min_gf_interval);
3894 assert(key_frame_group_size > 0);
3895 show_idx += key_frame_group_size;
3896 }
3897 assert(show_idx == first_pass_info->num_frames);
3898 }
3899 #endif // CONFIG_RATE_CTRL
3900
vp9_get_frame_stats(const TWO_PASS * twopass)3901 FIRSTPASS_STATS vp9_get_frame_stats(const TWO_PASS *twopass) {
3902 return twopass->this_frame_stats;
3903 }
vp9_get_total_stats(const TWO_PASS * twopass)3904 FIRSTPASS_STATS vp9_get_total_stats(const TWO_PASS *twopass) {
3905 return twopass->total_stats;
3906 }
3907