Coverage Report

Created: 2025-08-28 07:12

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