Coverage Report

Created: 2025-12-31 07:57

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