Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/media/libvpx/libvpx/vp8/encoder/firstpass.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5
 *  that can be found in the LICENSE file in the root of the source
6
 *  tree. An additional intellectual property rights grant can be found
7
 *  in the file PATENTS.  All contributing project authors may
8
 *  be found in the AUTHORS file in the root of the source tree.
9
 */
10
11
#include <math.h>
12
#include <limits.h>
13
#include <stdio.h>
14
15
#include "./vpx_dsp_rtcd.h"
16
#include "./vpx_scale_rtcd.h"
17
#include "block.h"
18
#include "onyx_int.h"
19
#include "vpx_dsp/variance.h"
20
#include "encodeintra.h"
21
#include "vp8/common/common.h"
22
#include "vp8/common/setupintrarecon.h"
23
#include "vp8/common/systemdependent.h"
24
#include "mcomp.h"
25
#include "firstpass.h"
26
#include "vpx_scale/vpx_scale.h"
27
#include "encodemb.h"
28
#include "vp8/common/extend.h"
29
#include "vpx_ports/system_state.h"
30
#include "vpx_mem/vpx_mem.h"
31
#include "vp8/common/swapyv12buffer.h"
32
#include "rdopt.h"
33
#include "vp8/common/quant_common.h"
34
#include "encodemv.h"
35
#include "encodeframe.h"
36
37
#define OUTPUT_FPF 0
38
39
extern void vp8cx_frame_init_quantizer(VP8_COMP *cpi);
40
41
0
#define GFQ_ADJUSTMENT vp8_gf_boost_qadjustment[Q]
42
extern int vp8_kf_boost_qadjustment[QINDEX_RANGE];
43
44
extern const int vp8_gf_boost_qadjustment[QINDEX_RANGE];
45
46
0
#define IIFACTOR 1.5
47
0
#define IIKFACTOR1 1.40
48
0
#define IIKFACTOR2 1.5
49
0
#define RMAX 14.0
50
0
#define GF_RMAX 48.0
51
52
0
#define KF_MB_INTRA_MIN 300
53
0
#define GF_MB_INTRA_MIN 200
54
55
0
#define DOUBLE_DIVIDE_CHECK(X) ((X) < 0 ? (X)-.000001 : (X) + .000001)
56
57
0
#define POW1 (double)cpi->oxcf.two_pass_vbrbias / 100.0
58
0
#define POW2 (double)cpi->oxcf.two_pass_vbrbias / 100.0
59
60
#define NEW_BOOST 1
61
62
static int vscale_lookup[7] = { 0, 1, 1, 2, 2, 3, 3 };
63
static int hscale_lookup[7] = { 0, 0, 1, 1, 2, 2, 3 };
64
65
static const int cq_level[QINDEX_RANGE] = {
66
  0,  0,  1,  1,  2,  3,  3,  4,  4,  5,  6,  6,  7,  8,  8,  9,  9,  10, 11,
67
  11, 12, 13, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23, 24,
68
  24, 25, 26, 27, 27, 28, 29, 30, 30, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
69
  39, 39, 40, 41, 42, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 50, 51, 52, 53,
70
  54, 55, 55, 56, 57, 58, 59, 60, 60, 61, 62, 63, 64, 65, 66, 67, 67, 68, 69,
71
  70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 86,
72
  87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100
73
};
74
75
static void find_next_key_frame(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame);
76
77
/* Resets the first pass file to the given position using a relative seek
78
 * from the current position
79
 */
80
0
static void reset_fpf_position(VP8_COMP *cpi, FIRSTPASS_STATS *Position) {
81
0
  cpi->twopass.stats_in = Position;
82
0
}
83
84
0
static int lookup_next_frame_stats(VP8_COMP *cpi, FIRSTPASS_STATS *next_frame) {
85
0
  if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end) return EOF;
86
0
87
0
  *next_frame = *cpi->twopass.stats_in;
88
0
  return 1;
89
0
}
90
91
/* Read frame stats at an offset from the current position */
92
static int read_frame_stats(VP8_COMP *cpi, FIRSTPASS_STATS *frame_stats,
93
0
                            int offset) {
94
0
  FIRSTPASS_STATS *fps_ptr = cpi->twopass.stats_in;
95
0
96
0
  /* Check legality of offset */
97
0
  if (offset >= 0) {
98
0
    if (&fps_ptr[offset] >= cpi->twopass.stats_in_end) return EOF;
99
0
  } else if (offset < 0) {
100
0
    if (&fps_ptr[offset] < cpi->twopass.stats_in_start) return EOF;
101
0
  }
102
0
103
0
  *frame_stats = fps_ptr[offset];
104
0
  return 1;
105
0
}
106
107
0
static int input_stats(VP8_COMP *cpi, FIRSTPASS_STATS *fps) {
108
0
  if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end) return EOF;
109
0
110
0
  *fps = *cpi->twopass.stats_in;
111
0
  cpi->twopass.stats_in =
112
0
      (void *)((char *)cpi->twopass.stats_in + sizeof(FIRSTPASS_STATS));
113
0
  return 1;
114
0
}
115
116
static void output_stats(const VP8_COMP *cpi,
117
                         struct vpx_codec_pkt_list *pktlist,
118
0
                         FIRSTPASS_STATS *stats) {
119
0
  struct vpx_codec_cx_pkt pkt;
120
0
  (void)cpi;
121
0
  pkt.kind = VPX_CODEC_STATS_PKT;
122
0
  pkt.data.twopass_stats.buf = stats;
123
0
  pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
124
0
  vpx_codec_pkt_list_add(pktlist, &pkt);
125
0
126
0
/* TEMP debug code */
127
#if OUTPUT_FPF
128
129
  {
130
    FILE *fpfile;
131
    fpfile = fopen("firstpass.stt", "a");
132
133
    fprintf(fpfile,
134
            "%12.0f %12.0f %12.0f %12.4f %12.4f %12.4f %12.4f"
135
            " %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f"
136
            " %12.0f %12.0f %12.4f\n",
137
            stats->frame, stats->intra_error, stats->coded_error,
138
            stats->ssim_weighted_pred_err, stats->pcnt_inter,
139
            stats->pcnt_motion, stats->pcnt_second_ref, stats->pcnt_neutral,
140
            stats->MVr, stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
141
            stats->MVcv, stats->mv_in_out_count, stats->new_mv_count,
142
            stats->count, stats->duration);
143
    fclose(fpfile);
144
  }
145
#endif
146
}
147
148
0
static void zero_stats(FIRSTPASS_STATS *section) {
149
0
  section->frame = 0.0;
150
0
  section->intra_error = 0.0;
151
0
  section->coded_error = 0.0;
152
0
  section->ssim_weighted_pred_err = 0.0;
153
0
  section->pcnt_inter = 0.0;
154
0
  section->pcnt_motion = 0.0;
155
0
  section->pcnt_second_ref = 0.0;
156
0
  section->pcnt_neutral = 0.0;
157
0
  section->MVr = 0.0;
158
0
  section->mvr_abs = 0.0;
159
0
  section->MVc = 0.0;
160
0
  section->mvc_abs = 0.0;
161
0
  section->MVrv = 0.0;
162
0
  section->MVcv = 0.0;
163
0
  section->mv_in_out_count = 0.0;
164
0
  section->new_mv_count = 0.0;
165
0
  section->count = 0.0;
166
0
  section->duration = 1.0;
167
0
}
168
169
0
static void accumulate_stats(FIRSTPASS_STATS *section, FIRSTPASS_STATS *frame) {
170
0
  section->frame += frame->frame;
171
0
  section->intra_error += frame->intra_error;
172
0
  section->coded_error += frame->coded_error;
173
0
  section->ssim_weighted_pred_err += frame->ssim_weighted_pred_err;
174
0
  section->pcnt_inter += frame->pcnt_inter;
175
0
  section->pcnt_motion += frame->pcnt_motion;
176
0
  section->pcnt_second_ref += frame->pcnt_second_ref;
177
0
  section->pcnt_neutral += frame->pcnt_neutral;
178
0
  section->MVr += frame->MVr;
179
0
  section->mvr_abs += frame->mvr_abs;
180
0
  section->MVc += frame->MVc;
181
0
  section->mvc_abs += frame->mvc_abs;
182
0
  section->MVrv += frame->MVrv;
183
0
  section->MVcv += frame->MVcv;
184
0
  section->mv_in_out_count += frame->mv_in_out_count;
185
0
  section->new_mv_count += frame->new_mv_count;
186
0
  section->count += frame->count;
187
0
  section->duration += frame->duration;
188
0
}
189
190
0
static void subtract_stats(FIRSTPASS_STATS *section, FIRSTPASS_STATS *frame) {
191
0
  section->frame -= frame->frame;
192
0
  section->intra_error -= frame->intra_error;
193
0
  section->coded_error -= frame->coded_error;
194
0
  section->ssim_weighted_pred_err -= frame->ssim_weighted_pred_err;
195
0
  section->pcnt_inter -= frame->pcnt_inter;
196
0
  section->pcnt_motion -= frame->pcnt_motion;
197
0
  section->pcnt_second_ref -= frame->pcnt_second_ref;
198
0
  section->pcnt_neutral -= frame->pcnt_neutral;
199
0
  section->MVr -= frame->MVr;
200
0
  section->mvr_abs -= frame->mvr_abs;
201
0
  section->MVc -= frame->MVc;
202
0
  section->mvc_abs -= frame->mvc_abs;
203
0
  section->MVrv -= frame->MVrv;
204
0
  section->MVcv -= frame->MVcv;
205
0
  section->mv_in_out_count -= frame->mv_in_out_count;
206
0
  section->new_mv_count -= frame->new_mv_count;
207
0
  section->count -= frame->count;
208
0
  section->duration -= frame->duration;
209
0
}
210
211
0
static void avg_stats(FIRSTPASS_STATS *section) {
212
0
  if (section->count < 1.0) return;
213
0
214
0
  section->intra_error /= section->count;
215
0
  section->coded_error /= section->count;
216
0
  section->ssim_weighted_pred_err /= section->count;
217
0
  section->pcnt_inter /= section->count;
218
0
  section->pcnt_second_ref /= section->count;
219
0
  section->pcnt_neutral /= section->count;
220
0
  section->pcnt_motion /= section->count;
221
0
  section->MVr /= section->count;
222
0
  section->mvr_abs /= section->count;
223
0
  section->MVc /= section->count;
224
0
  section->mvc_abs /= section->count;
225
0
  section->MVrv /= section->count;
226
0
  section->MVcv /= section->count;
227
0
  section->mv_in_out_count /= section->count;
228
0
  section->duration /= section->count;
229
0
}
230
231
/* Calculate a modified Error used in distributing bits between easier
232
 * and harder frames
233
 */
234
static double calculate_modified_err(VP8_COMP *cpi,
235
0
                                     FIRSTPASS_STATS *this_frame) {
236
0
  double av_err = (cpi->twopass.total_stats.ssim_weighted_pred_err /
237
0
                   cpi->twopass.total_stats.count);
238
0
  double this_err = this_frame->ssim_weighted_pred_err;
239
0
  double modified_err;
240
0
241
0
  if (this_err > av_err) {
242
0
    modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW1);
243
0
  } else {
244
0
    modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW2);
245
0
  }
246
0
247
0
  return modified_err;
248
0
}
249
250
static const double weight_table[256] = {
251
  0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
252
  0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
253
  0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
254
  0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
255
  0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.031250, 0.062500,
256
  0.093750, 0.125000, 0.156250, 0.187500, 0.218750, 0.250000, 0.281250,
257
  0.312500, 0.343750, 0.375000, 0.406250, 0.437500, 0.468750, 0.500000,
258
  0.531250, 0.562500, 0.593750, 0.625000, 0.656250, 0.687500, 0.718750,
259
  0.750000, 0.781250, 0.812500, 0.843750, 0.875000, 0.906250, 0.937500,
260
  0.968750, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
261
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
262
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
263
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
264
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
265
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
266
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
267
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
268
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
269
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
270
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
271
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
272
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
273
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
274
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
275
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
276
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
277
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
278
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
279
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
280
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
281
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
282
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
283
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
284
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
285
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
286
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
287
  1.000000, 1.000000, 1.000000, 1.000000
288
};
289
290
0
static double simple_weight(YV12_BUFFER_CONFIG *source) {
291
0
  int i, j;
292
0
293
0
  unsigned char *src = source->y_buffer;
294
0
  double sum_weights = 0.0;
295
0
296
0
  /* Loop throught the Y plane raw examining levels and creating a weight
297
0
   * for the image
298
0
   */
299
0
  i = source->y_height;
300
0
  do {
301
0
    j = source->y_width;
302
0
    do {
303
0
      sum_weights += weight_table[*src];
304
0
      src++;
305
0
    } while (--j);
306
0
    src -= source->y_width;
307
0
    src += source->y_stride;
308
0
  } while (--i);
309
0
310
0
  sum_weights /= (source->y_height * source->y_width);
311
0
312
0
  return sum_weights;
313
0
}
314
315
/* This function returns the current per frame maximum bitrate target */
316
0
static int frame_max_bits(VP8_COMP *cpi) {
317
0
  /* Max allocation for a single frame based on the max section guidelines
318
0
   * passed in and how many bits are left
319
0
   */
320
0
  int max_bits;
321
0
322
0
  /* For CBR we need to also consider buffer fullness.
323
0
   * If we are running below the optimal level then we need to gradually
324
0
   * tighten up on max_bits.
325
0
   */
326
0
  if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
327
0
    double buffer_fullness_ratio =
328
0
        (double)cpi->buffer_level /
329
0
        DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.optimal_buffer_level);
330
0
331
0
    /* For CBR base this on the target average bits per frame plus the
332
0
     * maximum sedction rate passed in by the user
333
0
     */
334
0
    max_bits = (int)(cpi->av_per_frame_bandwidth *
335
0
                     ((double)cpi->oxcf.two_pass_vbrmax_section / 100.0));
336
0
337
0
    /* If our buffer is below the optimum level */
338
0
    if (buffer_fullness_ratio < 1.0) {
339
0
      /* The lower of max_bits / 4 or cpi->av_per_frame_bandwidth / 4. */
340
0
      int min_max_bits = ((cpi->av_per_frame_bandwidth >> 2) < (max_bits >> 2))
341
0
                             ? cpi->av_per_frame_bandwidth >> 2
342
0
                             : max_bits >> 2;
343
0
344
0
      max_bits = (int)(max_bits * buffer_fullness_ratio);
345
0
346
0
      /* Lowest value we will set ... which should allow the buffer to
347
0
       * refill.
348
0
       */
349
0
      if (max_bits < min_max_bits) max_bits = min_max_bits;
350
0
    }
351
0
  }
352
0
  /* VBR */
353
0
  else {
354
0
    /* For VBR base this on the bits and frames left plus the
355
0
     * two_pass_vbrmax_section rate passed in by the user
356
0
     */
357
0
    max_bits = (int)(((double)cpi->twopass.bits_left /
358
0
                      (cpi->twopass.total_stats.count -
359
0
                       (double)cpi->common.current_video_frame)) *
360
0
                     ((double)cpi->oxcf.two_pass_vbrmax_section / 100.0));
361
0
  }
362
0
363
0
  /* Trap case where we are out of bits */
364
0
  if (max_bits < 0) max_bits = 0;
365
0
366
0
  return max_bits;
367
0
}
368
369
0
void vp8_init_first_pass(VP8_COMP *cpi) {
370
0
  zero_stats(&cpi->twopass.total_stats);
371
0
}
372
373
0
void vp8_end_first_pass(VP8_COMP *cpi) {
374
0
  output_stats(cpi, cpi->output_pkt_list, &cpi->twopass.total_stats);
375
0
}
376
377
static void zz_motion_search(VP8_COMP *cpi, MACROBLOCK *x,
378
                             YV12_BUFFER_CONFIG *raw_buffer,
379
                             int *raw_motion_err,
380
                             YV12_BUFFER_CONFIG *recon_buffer,
381
0
                             int *best_motion_err, int recon_yoffset) {
382
0
  MACROBLOCKD *const xd = &x->e_mbd;
383
0
  BLOCK *b = &x->block[0];
384
0
  BLOCKD *d = &x->e_mbd.block[0];
385
0
386
0
  unsigned char *src_ptr = (*(b->base_src) + b->src);
387
0
  int src_stride = b->src_stride;
388
0
  unsigned char *raw_ptr;
389
0
  int raw_stride = raw_buffer->y_stride;
390
0
  unsigned char *ref_ptr;
391
0
  int ref_stride = x->e_mbd.pre.y_stride;
392
0
  (void)cpi;
393
0
394
0
  /* Set up pointers for this macro block raw buffer */
395
0
  raw_ptr = (unsigned char *)(raw_buffer->y_buffer + recon_yoffset + d->offset);
396
0
  vpx_mse16x16(src_ptr, src_stride, raw_ptr, raw_stride,
397
0
               (unsigned int *)(raw_motion_err));
398
0
399
0
  /* Set up pointers for this macro block recon buffer */
400
0
  xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;
401
0
  ref_ptr = (unsigned char *)(xd->pre.y_buffer + d->offset);
402
0
  vpx_mse16x16(src_ptr, src_stride, ref_ptr, ref_stride,
403
0
               (unsigned int *)(best_motion_err));
404
0
}
405
406
static void first_pass_motion_search(VP8_COMP *cpi, MACROBLOCK *x,
407
                                     int_mv *ref_mv, MV *best_mv,
408
                                     YV12_BUFFER_CONFIG *recon_buffer,
409
0
                                     int *best_motion_err, int recon_yoffset) {
410
0
  MACROBLOCKD *const xd = &x->e_mbd;
411
0
  BLOCK *b = &x->block[0];
412
0
  BLOCKD *d = &x->e_mbd.block[0];
413
0
  int num00;
414
0
415
0
  int_mv tmp_mv;
416
0
  int_mv ref_mv_full;
417
0
418
0
  int tmp_err;
419
0
  int step_param = 3; /* Dont search over full range for first pass */
420
0
  int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
421
0
  int n;
422
0
  vp8_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[BLOCK_16X16];
423
0
  int new_mv_mode_penalty = 256;
424
0
425
0
  /* override the default variance function to use MSE */
426
0
  v_fn_ptr.vf = vpx_mse16x16;
427
0
428
0
  /* Set up pointers for this macro block recon buffer */
429
0
  xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;
430
0
431
0
  /* Initial step/diamond search centred on best mv */
432
0
  tmp_mv.as_int = 0;
433
0
  ref_mv_full.as_mv.col = ref_mv->as_mv.col >> 3;
434
0
  ref_mv_full.as_mv.row = ref_mv->as_mv.row >> 3;
435
0
  tmp_err = cpi->diamond_search_sad(x, b, d, &ref_mv_full, &tmp_mv, step_param,
436
0
                                    x->sadperbit16, &num00, &v_fn_ptr,
437
0
                                    x->mvcost, ref_mv);
438
0
  if (tmp_err < INT_MAX - new_mv_mode_penalty) tmp_err += new_mv_mode_penalty;
439
0
440
0
  if (tmp_err < *best_motion_err) {
441
0
    *best_motion_err = tmp_err;
442
0
    best_mv->row = tmp_mv.as_mv.row;
443
0
    best_mv->col = tmp_mv.as_mv.col;
444
0
  }
445
0
446
0
  /* Further step/diamond searches as necessary */
447
0
  n = num00;
448
0
  num00 = 0;
449
0
450
0
  while (n < further_steps) {
451
0
    n++;
452
0
453
0
    if (num00) {
454
0
      num00--;
455
0
    } else {
456
0
      tmp_err = cpi->diamond_search_sad(x, b, d, &ref_mv_full, &tmp_mv,
457
0
                                        step_param + n, x->sadperbit16, &num00,
458
0
                                        &v_fn_ptr, x->mvcost, ref_mv);
459
0
      if (tmp_err < INT_MAX - new_mv_mode_penalty) {
460
0
        tmp_err += new_mv_mode_penalty;
461
0
      }
462
0
463
0
      if (tmp_err < *best_motion_err) {
464
0
        *best_motion_err = tmp_err;
465
0
        best_mv->row = tmp_mv.as_mv.row;
466
0
        best_mv->col = tmp_mv.as_mv.col;
467
0
      }
468
0
    }
469
0
  }
470
0
}
471
472
0
void vp8_first_pass(VP8_COMP *cpi) {
473
0
  int mb_row, mb_col;
474
0
  MACROBLOCK *const x = &cpi->mb;
475
0
  VP8_COMMON *const cm = &cpi->common;
476
0
  MACROBLOCKD *const xd = &x->e_mbd;
477
0
478
0
  int recon_yoffset, recon_uvoffset;
479
0
  YV12_BUFFER_CONFIG *lst_yv12 = &cm->yv12_fb[cm->lst_fb_idx];
480
0
  YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
481
0
  YV12_BUFFER_CONFIG *gld_yv12 = &cm->yv12_fb[cm->gld_fb_idx];
482
0
  int recon_y_stride = lst_yv12->y_stride;
483
0
  int recon_uv_stride = lst_yv12->uv_stride;
484
0
  int64_t intra_error = 0;
485
0
  int64_t coded_error = 0;
486
0
487
0
  int sum_mvr = 0, sum_mvc = 0;
488
0
  int sum_mvr_abs = 0, sum_mvc_abs = 0;
489
0
  int sum_mvrs = 0, sum_mvcs = 0;
490
0
  int mvcount = 0;
491
0
  int intercount = 0;
492
0
  int second_ref_count = 0;
493
0
  int intrapenalty = 256;
494
0
  int neutral_count = 0;
495
0
  int new_mv_count = 0;
496
0
  int sum_in_vectors = 0;
497
0
  uint32_t lastmv_as_int = 0;
498
0
499
0
  int_mv zero_ref_mv;
500
0
501
0
  zero_ref_mv.as_int = 0;
502
0
503
0
  vpx_clear_system_state();
504
0
505
0
  x->src = *cpi->Source;
506
0
  xd->pre = *lst_yv12;
507
0
  xd->dst = *new_yv12;
508
0
509
0
  x->partition_info = x->pi;
510
0
511
0
  xd->mode_info_context = cm->mi;
512
0
513
0
  if (!cm->use_bilinear_mc_filter) {
514
0
    xd->subpixel_predict = vp8_sixtap_predict4x4;
515
0
    xd->subpixel_predict8x4 = vp8_sixtap_predict8x4;
516
0
    xd->subpixel_predict8x8 = vp8_sixtap_predict8x8;
517
0
    xd->subpixel_predict16x16 = vp8_sixtap_predict16x16;
518
0
  } else {
519
0
    xd->subpixel_predict = vp8_bilinear_predict4x4;
520
0
    xd->subpixel_predict8x4 = vp8_bilinear_predict8x4;
521
0
    xd->subpixel_predict8x8 = vp8_bilinear_predict8x8;
522
0
    xd->subpixel_predict16x16 = vp8_bilinear_predict16x16;
523
0
  }
524
0
525
0
  vp8_build_block_offsets(x);
526
0
527
0
  /* set up frame new frame for intra coded blocks */
528
0
  vp8_setup_intra_recon(new_yv12);
529
0
  vp8cx_frame_init_quantizer(cpi);
530
0
531
0
  /* Initialise the MV cost table to the defaults */
532
0
  {
533
0
    int flag[2] = { 1, 1 };
534
0
    vp8_initialize_rd_consts(cpi, x,
535
0
                             vp8_dc_quant(cm->base_qindex, cm->y1dc_delta_q));
536
0
    memcpy(cm->fc.mvc, vp8_default_mv_context, sizeof(vp8_default_mv_context));
537
0
    vp8_build_component_cost_table(cpi->mb.mvcost,
538
0
                                   (const MV_CONTEXT *)cm->fc.mvc, flag);
539
0
  }
540
0
541
0
  /* for each macroblock row in image */
542
0
  for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
543
0
    int_mv best_ref_mv;
544
0
545
0
    best_ref_mv.as_int = 0;
546
0
547
0
    /* reset above block coeffs */
548
0
    xd->up_available = (mb_row != 0);
549
0
    recon_yoffset = (mb_row * recon_y_stride * 16);
550
0
    recon_uvoffset = (mb_row * recon_uv_stride * 8);
551
0
552
0
    /* Set up limit values for motion vectors to prevent them extending
553
0
     * outside the UMV borders
554
0
     */
555
0
    x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16));
556
0
    x->mv_row_max =
557
0
        ((cm->mb_rows - 1 - mb_row) * 16) + (VP8BORDERINPIXELS - 16);
558
0
559
0
    /* for each macroblock col in image */
560
0
    for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
561
0
      int this_error;
562
0
      int gf_motion_error = INT_MAX;
563
0
      int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
564
0
565
0
      xd->dst.y_buffer = new_yv12->y_buffer + recon_yoffset;
566
0
      xd->dst.u_buffer = new_yv12->u_buffer + recon_uvoffset;
567
0
      xd->dst.v_buffer = new_yv12->v_buffer + recon_uvoffset;
568
0
      xd->left_available = (mb_col != 0);
569
0
570
0
      /* Copy current mb to a buffer */
571
0
      vp8_copy_mem16x16(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
572
0
573
0
      /* do intra 16x16 prediction */
574
0
      this_error = vp8_encode_intra(cpi, x, use_dc_pred);
575
0
576
0
      /* "intrapenalty" below deals with situations where the intra
577
0
       * and inter error scores are very low (eg a plain black frame)
578
0
       * We do not have special cases in first pass for 0,0 and
579
0
       * nearest etc so all inter modes carry an overhead cost
580
0
       * estimate fot the mv. When the error score is very low this
581
0
       * causes us to pick all or lots of INTRA modes and throw lots
582
0
       * of key frames. This penalty adds a cost matching that of a
583
0
       * 0,0 mv to the intra case.
584
0
       */
585
0
      this_error += intrapenalty;
586
0
587
0
      /* Cumulative intra error total */
588
0
      intra_error += (int64_t)this_error;
589
0
590
0
      /* Set up limit values for motion vectors to prevent them
591
0
       * extending outside the UMV borders
592
0
       */
593
0
      x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16));
594
0
      x->mv_col_max =
595
0
          ((cm->mb_cols - 1 - mb_col) * 16) + (VP8BORDERINPIXELS - 16);
596
0
597
0
      /* Other than for the first frame do a motion search */
598
0
      if (cm->current_video_frame > 0) {
599
0
        BLOCKD *d = &x->e_mbd.block[0];
600
0
        MV tmp_mv = { 0, 0 };
601
0
        int tmp_err;
602
0
        int motion_error = INT_MAX;
603
0
        int raw_motion_error = INT_MAX;
604
0
605
0
        /* Simple 0,0 motion with no mv overhead */
606
0
        zz_motion_search(cpi, x, cpi->last_frame_unscaled_source,
607
0
                         &raw_motion_error, lst_yv12, &motion_error,
608
0
                         recon_yoffset);
609
0
        d->bmi.mv.as_mv.row = 0;
610
0
        d->bmi.mv.as_mv.col = 0;
611
0
612
0
        if (raw_motion_error < cpi->oxcf.encode_breakout) {
613
0
          goto skip_motion_search;
614
0
        }
615
0
616
0
        /* Test last reference frame using the previous best mv as the
617
0
         * starting point (best reference) for the search
618
0
         */
619
0
        first_pass_motion_search(cpi, x, &best_ref_mv, &d->bmi.mv.as_mv,
620
0
                                 lst_yv12, &motion_error, recon_yoffset);
621
0
622
0
        /* If the current best reference mv is not centred on 0,0
623
0
         * then do a 0,0 based search as well
624
0
         */
625
0
        if (best_ref_mv.as_int) {
626
0
          tmp_err = INT_MAX;
627
0
          first_pass_motion_search(cpi, x, &zero_ref_mv, &tmp_mv, lst_yv12,
628
0
                                   &tmp_err, recon_yoffset);
629
0
630
0
          if (tmp_err < motion_error) {
631
0
            motion_error = tmp_err;
632
0
            d->bmi.mv.as_mv.row = tmp_mv.row;
633
0
            d->bmi.mv.as_mv.col = tmp_mv.col;
634
0
          }
635
0
        }
636
0
637
0
        /* Experimental search in a second reference frame ((0,0)
638
0
         * based only)
639
0
         */
640
0
        if (cm->current_video_frame > 1) {
641
0
          first_pass_motion_search(cpi, x, &zero_ref_mv, &tmp_mv, gld_yv12,
642
0
                                   &gf_motion_error, recon_yoffset);
643
0
644
0
          if ((gf_motion_error < motion_error) &&
645
0
              (gf_motion_error < this_error)) {
646
0
            second_ref_count++;
647
0
          }
648
0
649
0
          /* Reset to last frame as reference buffer */
650
0
          xd->pre.y_buffer = lst_yv12->y_buffer + recon_yoffset;
651
0
          xd->pre.u_buffer = lst_yv12->u_buffer + recon_uvoffset;
652
0
          xd->pre.v_buffer = lst_yv12->v_buffer + recon_uvoffset;
653
0
        }
654
0
655
0
      skip_motion_search:
656
0
        /* Intra assumed best */
657
0
        best_ref_mv.as_int = 0;
658
0
659
0
        if (motion_error <= this_error) {
660
0
          /* Keep a count of cases where the inter and intra were
661
0
           * very close and very low. This helps with scene cut
662
0
           * detection for example in cropped clips with black bars
663
0
           * at the sides or top and bottom.
664
0
           */
665
0
          if ((((this_error - intrapenalty) * 9) <= (motion_error * 10)) &&
666
0
              (this_error < (2 * intrapenalty))) {
667
0
            neutral_count++;
668
0
          }
669
0
670
0
          d->bmi.mv.as_mv.row *= 8;
671
0
          d->bmi.mv.as_mv.col *= 8;
672
0
          this_error = motion_error;
673
0
          vp8_set_mbmode_and_mvs(x, NEWMV, &d->bmi.mv);
674
0
          vp8_encode_inter16x16y(x);
675
0
          sum_mvr += d->bmi.mv.as_mv.row;
676
0
          sum_mvr_abs += abs(d->bmi.mv.as_mv.row);
677
0
          sum_mvc += d->bmi.mv.as_mv.col;
678
0
          sum_mvc_abs += abs(d->bmi.mv.as_mv.col);
679
0
          sum_mvrs += d->bmi.mv.as_mv.row * d->bmi.mv.as_mv.row;
680
0
          sum_mvcs += d->bmi.mv.as_mv.col * d->bmi.mv.as_mv.col;
681
0
          intercount++;
682
0
683
0
          best_ref_mv.as_int = d->bmi.mv.as_int;
684
0
685
0
          /* Was the vector non-zero */
686
0
          if (d->bmi.mv.as_int) {
687
0
            mvcount++;
688
0
689
0
            /* Was it different from the last non zero vector */
690
0
            if (d->bmi.mv.as_int != lastmv_as_int) new_mv_count++;
691
0
            lastmv_as_int = d->bmi.mv.as_int;
692
0
693
0
            /* Does the Row vector point inwards or outwards */
694
0
            if (mb_row < cm->mb_rows / 2) {
695
0
              if (d->bmi.mv.as_mv.row > 0) {
696
0
                sum_in_vectors--;
697
0
              } else if (d->bmi.mv.as_mv.row < 0) {
698
0
                sum_in_vectors++;
699
0
              }
700
0
            } else if (mb_row > cm->mb_rows / 2) {
701
0
              if (d->bmi.mv.as_mv.row > 0) {
702
0
                sum_in_vectors++;
703
0
              } else if (d->bmi.mv.as_mv.row < 0) {
704
0
                sum_in_vectors--;
705
0
              }
706
0
            }
707
0
708
0
            /* Does the Row vector point inwards or outwards */
709
0
            if (mb_col < cm->mb_cols / 2) {
710
0
              if (d->bmi.mv.as_mv.col > 0) {
711
0
                sum_in_vectors--;
712
0
              } else if (d->bmi.mv.as_mv.col < 0) {
713
0
                sum_in_vectors++;
714
0
              }
715
0
            } else if (mb_col > cm->mb_cols / 2) {
716
0
              if (d->bmi.mv.as_mv.col > 0) {
717
0
                sum_in_vectors++;
718
0
              } else if (d->bmi.mv.as_mv.col < 0) {
719
0
                sum_in_vectors--;
720
0
              }
721
0
            }
722
0
          }
723
0
        }
724
0
      }
725
0
726
0
      coded_error += (int64_t)this_error;
727
0
728
0
      /* adjust to the next column of macroblocks */
729
0
      x->src.y_buffer += 16;
730
0
      x->src.u_buffer += 8;
731
0
      x->src.v_buffer += 8;
732
0
733
0
      recon_yoffset += 16;
734
0
      recon_uvoffset += 8;
735
0
    }
736
0
737
0
    /* adjust to the next row of mbs */
738
0
    x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
739
0
    x->src.u_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
740
0
    x->src.v_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
741
0
742
0
    /* extend the recon for intra prediction */
743
0
    vp8_extend_mb_row(new_yv12, xd->dst.y_buffer + 16, xd->dst.u_buffer + 8,
744
0
                      xd->dst.v_buffer + 8);
745
0
    vpx_clear_system_state();
746
0
  }
747
0
748
0
  vpx_clear_system_state();
749
0
  {
750
0
    double weight = 0.0;
751
0
752
0
    FIRSTPASS_STATS fps;
753
0
754
0
    fps.frame = cm->current_video_frame;
755
0
    fps.intra_error = (double)(intra_error >> 8);
756
0
    fps.coded_error = (double)(coded_error >> 8);
757
0
    weight = simple_weight(cpi->Source);
758
0
759
0
    if (weight < 0.1) weight = 0.1;
760
0
761
0
    fps.ssim_weighted_pred_err = fps.coded_error * weight;
762
0
763
0
    fps.pcnt_inter = 0.0;
764
0
    fps.pcnt_motion = 0.0;
765
0
    fps.MVr = 0.0;
766
0
    fps.mvr_abs = 0.0;
767
0
    fps.MVc = 0.0;
768
0
    fps.mvc_abs = 0.0;
769
0
    fps.MVrv = 0.0;
770
0
    fps.MVcv = 0.0;
771
0
    fps.mv_in_out_count = 0.0;
772
0
    fps.new_mv_count = 0.0;
773
0
    fps.count = 1.0;
774
0
775
0
    fps.pcnt_inter = 1.0 * (double)intercount / cm->MBs;
776
0
    fps.pcnt_second_ref = 1.0 * (double)second_ref_count / cm->MBs;
777
0
    fps.pcnt_neutral = 1.0 * (double)neutral_count / cm->MBs;
778
0
779
0
    if (mvcount > 0) {
780
0
      fps.MVr = (double)sum_mvr / (double)mvcount;
781
0
      fps.mvr_abs = (double)sum_mvr_abs / (double)mvcount;
782
0
      fps.MVc = (double)sum_mvc / (double)mvcount;
783
0
      fps.mvc_abs = (double)sum_mvc_abs / (double)mvcount;
784
0
      fps.MVrv = ((double)sum_mvrs - (fps.MVr * fps.MVr / (double)mvcount)) /
785
0
                 (double)mvcount;
786
0
      fps.MVcv = ((double)sum_mvcs - (fps.MVc * fps.MVc / (double)mvcount)) /
787
0
                 (double)mvcount;
788
0
      fps.mv_in_out_count = (double)sum_in_vectors / (double)(mvcount * 2);
789
0
      fps.new_mv_count = new_mv_count;
790
0
791
0
      fps.pcnt_motion = 1.0 * (double)mvcount / cpi->common.MBs;
792
0
    }
793
0
794
0
    /* TODO:  handle the case when duration is set to 0, or something less
795
0
     * than the full time between subsequent cpi->source_time_stamps
796
0
     */
797
0
    fps.duration = (double)(cpi->source->ts_end - cpi->source->ts_start);
798
0
799
0
    /* don't want to do output stats with a stack variable! */
800
0
    memcpy(&cpi->twopass.this_frame_stats, &fps, sizeof(FIRSTPASS_STATS));
801
0
    output_stats(cpi, cpi->output_pkt_list, &cpi->twopass.this_frame_stats);
802
0
    accumulate_stats(&cpi->twopass.total_stats, &fps);
803
0
  }
804
0
805
0
  /* Copy the previous Last Frame into the GF buffer if specific
806
0
   * conditions for doing so are met
807
0
   */
808
0
  if ((cm->current_video_frame > 0) &&
809
0
      (cpi->twopass.this_frame_stats.pcnt_inter > 0.20) &&
810
0
      ((cpi->twopass.this_frame_stats.intra_error /
811
0
        DOUBLE_DIVIDE_CHECK(cpi->twopass.this_frame_stats.coded_error)) >
812
0
       2.0)) {
813
0
    vp8_yv12_copy_frame(lst_yv12, gld_yv12);
814
0
  }
815
0
816
0
  /* swap frame pointers so last frame refers to the frame we just
817
0
   * compressed
818
0
   */
819
0
  vp8_swap_yv12_buffer(lst_yv12, new_yv12);
820
0
  vp8_yv12_extend_frame_borders(lst_yv12);
821
0
822
0
  /* Special case for the first frame. Copy into the GF buffer as a
823
0
   * second reference.
824
0
   */
825
0
  if (cm->current_video_frame == 0) {
826
0
    vp8_yv12_copy_frame(lst_yv12, gld_yv12);
827
0
  }
828
0
829
0
  /* use this to see what the first pass reconstruction looks like */
830
0
  if (0) {
831
0
    char filename[512];
832
0
    FILE *recon_file;
833
0
    sprintf(filename, "enc%04d.yuv", (int)cm->current_video_frame);
834
0
835
0
    if (cm->current_video_frame == 0) {
836
0
      recon_file = fopen(filename, "wb");
837
0
    } else {
838
0
      recon_file = fopen(filename, "ab");
839
0
    }
840
0
841
0
    (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
842
0
    fclose(recon_file);
843
0
  }
844
0
845
0
  cm->current_video_frame++;
846
0
}
847
extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
848
849
/* Estimate a cost per mb attributable to overheads such as the coding of
850
 * modes and motion vectors.
851
 * Currently simplistic in its assumptions for testing.
852
 */
853
854
0
static double bitcost(double prob) {
855
0
  if (prob > 0.000122) {
856
0
    return -log(prob) / log(2.0);
857
0
  } else {
858
0
    return 13.0;
859
0
  }
860
0
}
861
0
static int64_t estimate_modemvcost(VP8_COMP *cpi, FIRSTPASS_STATS *fpstats) {
862
0
  int mv_cost;
863
0
  int64_t mode_cost;
864
0
865
0
  double av_pct_inter = fpstats->pcnt_inter / fpstats->count;
866
0
  double av_pct_motion = fpstats->pcnt_motion / fpstats->count;
867
0
  double av_intra = (1.0 - av_pct_inter);
868
0
869
0
  double zz_cost;
870
0
  double motion_cost;
871
0
  double intra_cost;
872
0
873
0
  zz_cost = bitcost(av_pct_inter - av_pct_motion);
874
0
  motion_cost = bitcost(av_pct_motion);
875
0
  intra_cost = bitcost(av_intra);
876
0
877
0
  /* Estimate of extra bits per mv overhead for mbs
878
0
   * << 9 is the normalization to the (bits * 512) used in vp8_bits_per_mb
879
0
   */
880
0
  mv_cost = ((int)(fpstats->new_mv_count / fpstats->count) * 8) << 9;
881
0
882
0
  /* Crude estimate of overhead cost from modes
883
0
   * << 9 is the normalization to (bits * 512) used in vp8_bits_per_mb
884
0
   */
885
0
  mode_cost =
886
0
      (int64_t)((((av_pct_inter - av_pct_motion) * zz_cost) +
887
0
                 (av_pct_motion * motion_cost) + (av_intra * intra_cost)) *
888
0
                cpi->common.MBs) *
889
0
      512;
890
0
891
0
  return mv_cost + mode_cost;
892
0
}
893
894
static double calc_correction_factor(double err_per_mb, double err_devisor,
895
0
                                     double pt_low, double pt_high, int Q) {
896
0
  double power_term;
897
0
  double error_term = err_per_mb / err_devisor;
898
0
  double correction_factor;
899
0
900
0
  /* Adjustment based on Q to power term. */
901
0
  power_term = pt_low + (Q * 0.01);
902
0
  power_term = (power_term > pt_high) ? pt_high : power_term;
903
0
904
0
  /* Adjustments to error term */
905
0
  /* TBD */
906
0
907
0
  /* Calculate correction factor */
908
0
  correction_factor = pow(error_term, power_term);
909
0
910
0
  /* Clip range */
911
0
  correction_factor = (correction_factor < 0.05)
912
0
                          ? 0.05
913
0
                          : (correction_factor > 5.0) ? 5.0 : correction_factor;
914
0
915
0
  return correction_factor;
916
0
}
917
918
static int estimate_max_q(VP8_COMP *cpi, FIRSTPASS_STATS *fpstats,
919
0
                          int section_target_bandwitdh, int overhead_bits) {
920
0
  int Q;
921
0
  int num_mbs = cpi->common.MBs;
922
0
  int target_norm_bits_per_mb;
923
0
924
0
  double section_err = (fpstats->coded_error / fpstats->count);
925
0
  double err_per_mb = section_err / num_mbs;
926
0
  double err_correction_factor;
927
0
  double speed_correction = 1.0;
928
0
  int overhead_bits_per_mb;
929
0
930
0
  if (section_target_bandwitdh <= 0) {
931
0
    return cpi->twopass.maxq_max_limit; /* Highest value allowed */
932
0
  }
933
0
934
0
  target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20))
935
0
                                ? (512 * section_target_bandwitdh) / num_mbs
936
0
                                : 512 * (section_target_bandwitdh / num_mbs);
937
0
938
0
  /* Calculate a corrective factor based on a rolling ratio of bits spent
939
0
   * vs target bits
940
0
   */
941
0
  if ((cpi->rolling_target_bits > 0) &&
942
0
      (cpi->active_worst_quality < cpi->worst_quality)) {
943
0
    double rolling_ratio;
944
0
945
0
    rolling_ratio =
946
0
        (double)cpi->rolling_actual_bits / (double)cpi->rolling_target_bits;
947
0
948
0
    if (rolling_ratio < 0.95) {
949
0
      cpi->twopass.est_max_qcorrection_factor -= 0.005;
950
0
    } else if (rolling_ratio > 1.05) {
951
0
      cpi->twopass.est_max_qcorrection_factor += 0.005;
952
0
    }
953
0
954
0
    cpi->twopass.est_max_qcorrection_factor =
955
0
        (cpi->twopass.est_max_qcorrection_factor < 0.1)
956
0
            ? 0.1
957
0
            : (cpi->twopass.est_max_qcorrection_factor > 10.0)
958
0
                  ? 10.0
959
0
                  : cpi->twopass.est_max_qcorrection_factor;
960
0
  }
961
0
962
0
  /* Corrections for higher compression speed settings
963
0
   * (reduced compression expected)
964
0
   */
965
0
  if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1)) {
966
0
    if (cpi->oxcf.cpu_used <= 5) {
967
0
      speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
968
0
    } else {
969
0
      speed_correction = 1.25;
970
0
    }
971
0
  }
972
0
973
0
  /* Estimate of overhead bits per mb */
974
0
  /* Correction to overhead bits for min allowed Q. */
975
0
  overhead_bits_per_mb = overhead_bits / num_mbs;
976
0
  overhead_bits_per_mb = (int)(overhead_bits_per_mb *
977
0
                               pow(0.98, (double)cpi->twopass.maxq_min_limit));
978
0
979
0
  /* Try and pick a max Q that will be high enough to encode the
980
0
   * content at the given rate.
981
0
   */
982
0
  for (Q = cpi->twopass.maxq_min_limit; Q < cpi->twopass.maxq_max_limit; ++Q) {
983
0
    int bits_per_mb_at_this_q;
984
0
985
0
    /* Error per MB based correction factor */
986
0
    err_correction_factor =
987
0
        calc_correction_factor(err_per_mb, 150.0, 0.40, 0.90, Q);
988
0
989
0
    bits_per_mb_at_this_q =
990
0
        vp8_bits_per_mb[INTER_FRAME][Q] + overhead_bits_per_mb;
991
0
992
0
    bits_per_mb_at_this_q = (int)(.5 +
993
0
                                  err_correction_factor * speed_correction *
994
0
                                      cpi->twopass.est_max_qcorrection_factor *
995
0
                                      cpi->twopass.section_max_qfactor *
996
0
                                      (double)bits_per_mb_at_this_q);
997
0
998
0
    /* Mode and motion overhead */
999
0
    /* As Q rises in real encode loop rd code will force overhead down
1000
0
     * We make a crude adjustment for this here as *.98 per Q step.
1001
0
     */
1002
0
    overhead_bits_per_mb = (int)((double)overhead_bits_per_mb * 0.98);
1003
0
1004
0
    if (bits_per_mb_at_this_q <= target_norm_bits_per_mb) break;
1005
0
  }
1006
0
1007
0
  /* Restriction on active max q for constrained quality mode. */
1008
0
  if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
1009
0
      (Q < cpi->cq_target_quality)) {
1010
0
    Q = cpi->cq_target_quality;
1011
0
  }
1012
0
1013
0
  /* Adjust maxq_min_limit and maxq_max_limit limits based on
1014
0
   * average q observed in clip for non kf/gf.arf frames
1015
0
   * Give average a chance to settle though.
1016
0
   */
1017
0
  if ((cpi->ni_frames > ((int)cpi->twopass.total_stats.count >> 8)) &&
1018
0
      (cpi->ni_frames > 150)) {
1019
0
    cpi->twopass.maxq_max_limit = ((cpi->ni_av_qi + 32) < cpi->worst_quality)
1020
0
                                      ? (cpi->ni_av_qi + 32)
1021
0
                                      : cpi->worst_quality;
1022
0
    cpi->twopass.maxq_min_limit = ((cpi->ni_av_qi - 32) > cpi->best_quality)
1023
0
                                      ? (cpi->ni_av_qi - 32)
1024
0
                                      : cpi->best_quality;
1025
0
  }
1026
0
1027
0
  return Q;
1028
0
}
1029
1030
/* For cq mode estimate a cq level that matches the observed
1031
 * complexity and data rate.
1032
 */
1033
static int estimate_cq(VP8_COMP *cpi, FIRSTPASS_STATS *fpstats,
1034
0
                       int section_target_bandwitdh, int overhead_bits) {
1035
0
  int Q;
1036
0
  int num_mbs = cpi->common.MBs;
1037
0
  int target_norm_bits_per_mb;
1038
0
1039
0
  double section_err = (fpstats->coded_error / fpstats->count);
1040
0
  double err_per_mb = section_err / num_mbs;
1041
0
  double err_correction_factor;
1042
0
  double speed_correction = 1.0;
1043
0
  double clip_iiratio;
1044
0
  double clip_iifactor;
1045
0
  int overhead_bits_per_mb;
1046
0
1047
0
  if (0) {
1048
0
    FILE *f = fopen("epmp.stt", "a");
1049
0
    fprintf(f, "%10.2f\n", err_per_mb);
1050
0
    fclose(f);
1051
0
  }
1052
0
1053
0
  target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20))
1054
0
                                ? (512 * section_target_bandwitdh) / num_mbs
1055
0
                                : 512 * (section_target_bandwitdh / num_mbs);
1056
0
1057
0
  /* Estimate of overhead bits per mb */
1058
0
  overhead_bits_per_mb = overhead_bits / num_mbs;
1059
0
1060
0
  /* Corrections for higher compression speed settings
1061
0
   * (reduced compression expected)
1062
0
   */
1063
0
  if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1)) {
1064
0
    if (cpi->oxcf.cpu_used <= 5) {
1065
0
      speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
1066
0
    } else {
1067
0
      speed_correction = 1.25;
1068
0
    }
1069
0
  }
1070
0
1071
0
  /* II ratio correction factor for clip as a whole */
1072
0
  clip_iiratio = cpi->twopass.total_stats.intra_error /
1073
0
                 DOUBLE_DIVIDE_CHECK(cpi->twopass.total_stats.coded_error);
1074
0
  clip_iifactor = 1.0 - ((clip_iiratio - 10.0) * 0.025);
1075
0
  if (clip_iifactor < 0.80) clip_iifactor = 0.80;
1076
0
1077
0
  /* Try and pick a Q that can encode the content at the given rate. */
1078
0
  for (Q = 0; Q < MAXQ; ++Q) {
1079
0
    int bits_per_mb_at_this_q;
1080
0
1081
0
    /* Error per MB based correction factor */
1082
0
    err_correction_factor =
1083
0
        calc_correction_factor(err_per_mb, 100.0, 0.40, 0.90, Q);
1084
0
1085
0
    bits_per_mb_at_this_q =
1086
0
        vp8_bits_per_mb[INTER_FRAME][Q] + overhead_bits_per_mb;
1087
0
1088
0
    bits_per_mb_at_this_q =
1089
0
        (int)(.5 +
1090
0
              err_correction_factor * speed_correction * clip_iifactor *
1091
0
                  (double)bits_per_mb_at_this_q);
1092
0
1093
0
    /* Mode and motion overhead */
1094
0
    /* As Q rises in real encode loop rd code will force overhead down
1095
0
     * We make a crude adjustment for this here as *.98 per Q step.
1096
0
     */
1097
0
    overhead_bits_per_mb = (int)((double)overhead_bits_per_mb * 0.98);
1098
0
1099
0
    if (bits_per_mb_at_this_q <= target_norm_bits_per_mb) break;
1100
0
  }
1101
0
1102
0
  /* Clip value to range "best allowed to (worst allowed - 1)" */
1103
0
  Q = cq_level[Q];
1104
0
  if (Q >= cpi->worst_quality) Q = cpi->worst_quality - 1;
1105
0
  if (Q < cpi->best_quality) Q = cpi->best_quality;
1106
0
1107
0
  return Q;
1108
0
}
1109
1110
static int estimate_q(VP8_COMP *cpi, double section_err,
1111
0
                      int section_target_bandwitdh) {
1112
0
  int Q;
1113
0
  int num_mbs = cpi->common.MBs;
1114
0
  int target_norm_bits_per_mb;
1115
0
1116
0
  double err_per_mb = section_err / num_mbs;
1117
0
  double err_correction_factor;
1118
0
  double speed_correction = 1.0;
1119
0
1120
0
  target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20))
1121
0
                                ? (512 * section_target_bandwitdh) / num_mbs
1122
0
                                : 512 * (section_target_bandwitdh / num_mbs);
1123
0
1124
0
  /* Corrections for higher compression speed settings
1125
0
   * (reduced compression expected)
1126
0
   */
1127
0
  if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1)) {
1128
0
    if (cpi->oxcf.cpu_used <= 5) {
1129
0
      speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
1130
0
    } else {
1131
0
      speed_correction = 1.25;
1132
0
    }
1133
0
  }
1134
0
1135
0
  /* Try and pick a Q that can encode the content at the given rate. */
1136
0
  for (Q = 0; Q < MAXQ; ++Q) {
1137
0
    int bits_per_mb_at_this_q;
1138
0
1139
0
    /* Error per MB based correction factor */
1140
0
    err_correction_factor =
1141
0
        calc_correction_factor(err_per_mb, 150.0, 0.40, 0.90, Q);
1142
0
1143
0
    bits_per_mb_at_this_q =
1144
0
        (int)(.5 + (err_correction_factor * speed_correction *
1145
0
                    cpi->twopass.est_max_qcorrection_factor *
1146
0
                    (double)vp8_bits_per_mb[INTER_FRAME][Q] / 1.0));
1147
0
1148
0
    if (bits_per_mb_at_this_q <= target_norm_bits_per_mb) break;
1149
0
  }
1150
0
1151
0
  return Q;
1152
0
}
1153
1154
/* Estimate a worst case Q for a KF group */
1155
static int estimate_kf_group_q(VP8_COMP *cpi, double section_err,
1156
                               int section_target_bandwitdh,
1157
0
                               double group_iiratio) {
1158
0
  int Q;
1159
0
  int num_mbs = cpi->common.MBs;
1160
0
  int target_norm_bits_per_mb = (512 * section_target_bandwitdh) / num_mbs;
1161
0
  int bits_per_mb_at_this_q;
1162
0
1163
0
  double err_per_mb = section_err / num_mbs;
1164
0
  double err_correction_factor;
1165
0
  double speed_correction = 1.0;
1166
0
  double current_spend_ratio = 1.0;
1167
0
1168
0
  double pow_highq = (POW1 < 0.6) ? POW1 + 0.3 : 0.90;
1169
0
  double pow_lowq = (POW1 < 0.7) ? POW1 + 0.1 : 0.80;
1170
0
1171
0
  double iiratio_correction_factor = 1.0;
1172
0
1173
0
  double combined_correction_factor;
1174
0
1175
0
  /* Trap special case where the target is <= 0 */
1176
0
  if (target_norm_bits_per_mb <= 0) return MAXQ * 2;
1177
0
1178
0
  /* Calculate a corrective factor based on a rolling ratio of bits spent
1179
0
   *  vs target bits
1180
0
   * This is clamped to the range 0.1 to 10.0
1181
0
   */
1182
0
  if (cpi->long_rolling_target_bits <= 0) {
1183
0
    current_spend_ratio = 10.0;
1184
0
  } else {
1185
0
    current_spend_ratio = (double)cpi->long_rolling_actual_bits /
1186
0
                          (double)cpi->long_rolling_target_bits;
1187
0
    current_spend_ratio =
1188
0
        (current_spend_ratio > 10.0)
1189
0
            ? 10.0
1190
0
            : (current_spend_ratio < 0.1) ? 0.1 : current_spend_ratio;
1191
0
  }
1192
0
1193
0
  /* Calculate a correction factor based on the quality of prediction in
1194
0
   * the sequence as indicated by intra_inter error score ratio (IIRatio)
1195
0
   * The idea here is to favour subsampling in the hardest sections vs
1196
0
   * the easyest.
1197
0
   */
1198
0
  iiratio_correction_factor = 1.0 - ((group_iiratio - 6.0) * 0.1);
1199
0
1200
0
  if (iiratio_correction_factor < 0.5) iiratio_correction_factor = 0.5;
1201
0
1202
0
  /* Corrections for higher compression speed settings
1203
0
   * (reduced compression expected)
1204
0
   */
1205
0
  if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1)) {
1206
0
    if (cpi->oxcf.cpu_used <= 5) {
1207
0
      speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
1208
0
    } else {
1209
0
      speed_correction = 1.25;
1210
0
    }
1211
0
  }
1212
0
1213
0
  /* Combine the various factors calculated above */
1214
0
  combined_correction_factor =
1215
0
      speed_correction * iiratio_correction_factor * current_spend_ratio;
1216
0
1217
0
  /* Try and pick a Q that should be high enough to encode the content at
1218
0
   * the given rate.
1219
0
   */
1220
0
  for (Q = 0; Q < MAXQ; ++Q) {
1221
0
    /* Error per MB based correction factor */
1222
0
    err_correction_factor =
1223
0
        calc_correction_factor(err_per_mb, 150.0, pow_lowq, pow_highq, Q);
1224
0
1225
0
    bits_per_mb_at_this_q =
1226
0
        (int)(.5 + (err_correction_factor * combined_correction_factor *
1227
0
                    (double)vp8_bits_per_mb[INTER_FRAME][Q]));
1228
0
1229
0
    if (bits_per_mb_at_this_q <= target_norm_bits_per_mb) break;
1230
0
  }
1231
0
1232
0
  /* If we could not hit the target even at Max Q then estimate what Q
1233
0
   * would have been required
1234
0
   */
1235
0
  while ((bits_per_mb_at_this_q > target_norm_bits_per_mb) &&
1236
0
         (Q < (MAXQ * 2))) {
1237
0
    bits_per_mb_at_this_q = (int)(0.96 * bits_per_mb_at_this_q);
1238
0
    Q++;
1239
0
  }
1240
0
1241
0
  if (0) {
1242
0
    FILE *f = fopen("estkf_q.stt", "a");
1243
0
    fprintf(f, "%8d %8d %8d %8.2f %8.3f %8.2f %8.3f %8.3f %8.3f %8d\n",
1244
0
            cpi->common.current_video_frame, bits_per_mb_at_this_q,
1245
0
            target_norm_bits_per_mb, err_per_mb, err_correction_factor,
1246
0
            current_spend_ratio, group_iiratio, iiratio_correction_factor,
1247
0
            (double)cpi->buffer_level / (double)cpi->oxcf.optimal_buffer_level,
1248
0
            Q);
1249
0
    fclose(f);
1250
0
  }
1251
0
1252
0
  return Q;
1253
0
}
1254
1255
0
void vp8_init_second_pass(VP8_COMP *cpi) {
1256
0
  FIRSTPASS_STATS this_frame;
1257
0
  FIRSTPASS_STATS *start_pos;
1258
0
1259
0
  double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth *
1260
0
                                      cpi->oxcf.two_pass_vbrmin_section / 100);
1261
0
1262
0
  zero_stats(&cpi->twopass.total_stats);
1263
0
  zero_stats(&cpi->twopass.total_left_stats);
1264
0
1265
0
  if (!cpi->twopass.stats_in_end) return;
1266
0
1267
0
  cpi->twopass.total_stats = *cpi->twopass.stats_in_end;
1268
0
  cpi->twopass.total_left_stats = cpi->twopass.total_stats;
1269
0
1270
0
  /* each frame can have a different duration, as the frame rate in the
1271
0
   * source isn't guaranteed to be constant.   The frame rate prior to
1272
0
   * the first frame encoded in the second pass is a guess.  However the
1273
0
   * sum duration is not. Its calculated based on the actual durations of
1274
0
   * all frames from the first pass.
1275
0
   */
1276
0
  vp8_new_framerate(cpi,
1277
0
                    10000000.0 * cpi->twopass.total_stats.count /
1278
0
                        cpi->twopass.total_stats.duration);
1279
0
1280
0
  cpi->output_framerate = cpi->framerate;
1281
0
  cpi->twopass.bits_left = (int64_t)(cpi->twopass.total_stats.duration *
1282
0
                                     cpi->oxcf.target_bandwidth / 10000000.0);
1283
0
  cpi->twopass.bits_left -= (int64_t)(cpi->twopass.total_stats.duration *
1284
0
                                      two_pass_min_rate / 10000000.0);
1285
0
1286
0
  /* Calculate a minimum intra value to be used in determining the IIratio
1287
0
   * scores used in the second pass. We have this minimum to make sure
1288
0
   * that clips that are static but "low complexity" in the intra domain
1289
0
   * are still boosted appropriately for KF/GF/ARF
1290
0
   */
1291
0
  cpi->twopass.kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
1292
0
  cpi->twopass.gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
1293
0
1294
0
  /* Scan the first pass file and calculate an average Intra / Inter error
1295
0
   * score ratio for the sequence
1296
0
   */
1297
0
  {
1298
0
    double sum_iiratio = 0.0;
1299
0
    double IIRatio;
1300
0
1301
0
    start_pos = cpi->twopass.stats_in; /* Note starting "file" position */
1302
0
1303
0
    while (input_stats(cpi, &this_frame) != EOF) {
1304
0
      IIRatio =
1305
0
          this_frame.intra_error / DOUBLE_DIVIDE_CHECK(this_frame.coded_error);
1306
0
      IIRatio = (IIRatio < 1.0) ? 1.0 : (IIRatio > 20.0) ? 20.0 : IIRatio;
1307
0
      sum_iiratio += IIRatio;
1308
0
    }
1309
0
1310
0
    cpi->twopass.avg_iiratio =
1311
0
        sum_iiratio /
1312
0
        DOUBLE_DIVIDE_CHECK((double)cpi->twopass.total_stats.count);
1313
0
1314
0
    /* Reset file position */
1315
0
    reset_fpf_position(cpi, start_pos);
1316
0
  }
1317
0
1318
0
  /* Scan the first pass file and calculate a modified total error based
1319
0
   * upon the bias/power function used to allocate bits
1320
0
   */
1321
0
  {
1322
0
    start_pos = cpi->twopass.stats_in; /* Note starting "file" position */
1323
0
1324
0
    cpi->twopass.modified_error_total = 0.0;
1325
0
    cpi->twopass.modified_error_used = 0.0;
1326
0
1327
0
    while (input_stats(cpi, &this_frame) != EOF) {
1328
0
      cpi->twopass.modified_error_total +=
1329
0
          calculate_modified_err(cpi, &this_frame);
1330
0
    }
1331
0
    cpi->twopass.modified_error_left = cpi->twopass.modified_error_total;
1332
0
1333
0
    reset_fpf_position(cpi, start_pos); /* Reset file position */
1334
0
  }
1335
0
}
1336
1337
0
void vp8_end_second_pass(VP8_COMP *cpi) { (void)cpi; }
1338
1339
/* This function gives and estimate of how badly we believe the prediction
1340
 * quality is decaying from frame to frame.
1341
 */
1342
static double get_prediction_decay_rate(VP8_COMP *cpi,
1343
0
                                        FIRSTPASS_STATS *next_frame) {
1344
0
  double prediction_decay_rate;
1345
0
  double motion_decay;
1346
0
  double motion_pct = next_frame->pcnt_motion;
1347
0
  (void)cpi;
1348
0
1349
0
  /* Initial basis is the % mbs inter coded */
1350
0
  prediction_decay_rate = next_frame->pcnt_inter;
1351
0
1352
0
  /* High % motion -> somewhat higher decay rate */
1353
0
  motion_decay = (1.0 - (motion_pct / 20.0));
1354
0
  if (motion_decay < prediction_decay_rate) {
1355
0
    prediction_decay_rate = motion_decay;
1356
0
  }
1357
0
1358
0
  /* Adjustment to decay rate based on speed of motion */
1359
0
  {
1360
0
    double this_mv_rabs;
1361
0
    double this_mv_cabs;
1362
0
    double distance_factor;
1363
0
1364
0
    this_mv_rabs = fabs(next_frame->mvr_abs * motion_pct);
1365
0
    this_mv_cabs = fabs(next_frame->mvc_abs * motion_pct);
1366
0
1367
0
    distance_factor =
1368
0
        sqrt((this_mv_rabs * this_mv_rabs) + (this_mv_cabs * this_mv_cabs)) /
1369
0
        250.0;
1370
0
    distance_factor = ((distance_factor > 1.0) ? 0.0 : (1.0 - distance_factor));
1371
0
    if (distance_factor < prediction_decay_rate) {
1372
0
      prediction_decay_rate = distance_factor;
1373
0
    }
1374
0
  }
1375
0
1376
0
  return prediction_decay_rate;
1377
0
}
1378
1379
/* Function to test for a condition where a complex transition is followed
1380
 * by a static section. For example in slide shows where there is a fade
1381
 * between slides. This is to help with more optimal kf and gf positioning.
1382
 */
1383
static int detect_transition_to_still(VP8_COMP *cpi, int frame_interval,
1384
                                      int still_interval,
1385
                                      double loop_decay_rate,
1386
0
                                      double decay_accumulator) {
1387
0
  int trans_to_still = 0;
1388
0
1389
0
  /* Break clause to detect very still sections after motion
1390
0
   * For example a static image after a fade or other transition
1391
0
   * instead of a clean scene cut.
1392
0
   */
1393
0
  if ((frame_interval > MIN_GF_INTERVAL) && (loop_decay_rate >= 0.999) &&
1394
0
      (decay_accumulator < 0.9)) {
1395
0
    int j;
1396
0
    FIRSTPASS_STATS *position = cpi->twopass.stats_in;
1397
0
    FIRSTPASS_STATS tmp_next_frame;
1398
0
    double decay_rate;
1399
0
1400
0
    /* Look ahead a few frames to see if static condition persists... */
1401
0
    for (j = 0; j < still_interval; ++j) {
1402
0
      if (EOF == input_stats(cpi, &tmp_next_frame)) break;
1403
0
1404
0
      decay_rate = get_prediction_decay_rate(cpi, &tmp_next_frame);
1405
0
      if (decay_rate < 0.999) break;
1406
0
    }
1407
0
    /* Reset file position */
1408
0
    reset_fpf_position(cpi, position);
1409
0
1410
0
    /* Only if it does do we signal a transition to still */
1411
0
    if (j == still_interval) trans_to_still = 1;
1412
0
  }
1413
0
1414
0
  return trans_to_still;
1415
0
}
1416
1417
/* This function detects a flash through the high relative pcnt_second_ref
1418
 * score in the frame following a flash frame. The offset passed in should
1419
 * reflect this
1420
 */
1421
0
static int detect_flash(VP8_COMP *cpi, int offset) {
1422
0
  FIRSTPASS_STATS next_frame;
1423
0
1424
0
  int flash_detected = 0;
1425
0
1426
0
  /* Read the frame data. */
1427
0
  /* The return is 0 (no flash detected) if not a valid frame */
1428
0
  if (read_frame_stats(cpi, &next_frame, offset) != EOF) {
1429
0
    /* What we are looking for here is a situation where there is a
1430
0
     * brief break in prediction (such as a flash) but subsequent frames
1431
0
     * are reasonably well predicted by an earlier (pre flash) frame.
1432
0
     * The recovery after a flash is indicated by a high pcnt_second_ref
1433
0
     * comapred to pcnt_inter.
1434
0
     */
1435
0
    if ((next_frame.pcnt_second_ref > next_frame.pcnt_inter) &&
1436
0
        (next_frame.pcnt_second_ref >= 0.5)) {
1437
0
      flash_detected = 1;
1438
0
1439
0
      /*if (1)
1440
0
      {
1441
0
          FILE *f = fopen("flash.stt", "a");
1442
0
          fprintf(f, "%8.0f %6.2f %6.2f\n",
1443
0
              next_frame.frame,
1444
0
              next_frame.pcnt_inter,
1445
0
              next_frame.pcnt_second_ref);
1446
0
          fclose(f);
1447
0
      }*/
1448
0
    }
1449
0
  }
1450
0
1451
0
  return flash_detected;
1452
0
}
1453
1454
/* Update the motion related elements to the GF arf boost calculation */
1455
static void accumulate_frame_motion_stats(VP8_COMP *cpi,
1456
                                          FIRSTPASS_STATS *this_frame,
1457
                                          double *this_frame_mv_in_out,
1458
                                          double *mv_in_out_accumulator,
1459
                                          double *abs_mv_in_out_accumulator,
1460
0
                                          double *mv_ratio_accumulator) {
1461
0
  double this_frame_mvr_ratio;
1462
0
  double this_frame_mvc_ratio;
1463
0
  double motion_pct;
1464
0
  (void)cpi;
1465
0
1466
0
  /* Accumulate motion stats. */
1467
0
  motion_pct = this_frame->pcnt_motion;
1468
0
1469
0
  /* Accumulate Motion In/Out of frame stats */
1470
0
  *this_frame_mv_in_out = this_frame->mv_in_out_count * motion_pct;
1471
0
  *mv_in_out_accumulator += this_frame->mv_in_out_count * motion_pct;
1472
0
  *abs_mv_in_out_accumulator += fabs(this_frame->mv_in_out_count * motion_pct);
1473
0
1474
0
  /* Accumulate a measure of how uniform (or conversely how random)
1475
0
   * the motion field is. (A ratio of absmv / mv)
1476
0
   */
1477
0
  if (motion_pct > 0.05) {
1478
0
    this_frame_mvr_ratio =
1479
0
        fabs(this_frame->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(this_frame->MVr));
1480
0
1481
0
    this_frame_mvc_ratio =
1482
0
        fabs(this_frame->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(this_frame->MVc));
1483
0
1484
0
    *mv_ratio_accumulator += (this_frame_mvr_ratio < this_frame->mvr_abs)
1485
0
                                 ? (this_frame_mvr_ratio * motion_pct)
1486
0
                                 : this_frame->mvr_abs * motion_pct;
1487
0
1488
0
    *mv_ratio_accumulator += (this_frame_mvc_ratio < this_frame->mvc_abs)
1489
0
                                 ? (this_frame_mvc_ratio * motion_pct)
1490
0
                                 : this_frame->mvc_abs * motion_pct;
1491
0
  }
1492
0
}
1493
1494
/* Calculate a baseline boost number for the current frame. */
1495
static double calc_frame_boost(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame,
1496
0
                               double this_frame_mv_in_out) {
1497
0
  double frame_boost;
1498
0
1499
0
  /* Underlying boost factor is based on inter intra error ratio */
1500
0
  if (this_frame->intra_error > cpi->twopass.gf_intra_err_min) {
1501
0
    frame_boost = (IIFACTOR * this_frame->intra_error /
1502
0
                   DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1503
0
  } else {
1504
0
    frame_boost = (IIFACTOR * cpi->twopass.gf_intra_err_min /
1505
0
                   DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1506
0
  }
1507
0
1508
0
  /* Increase boost for frames where new data coming into frame
1509
0
   * (eg zoom out). Slightly reduce boost if there is a net balance
1510
0
   * of motion out of the frame (zoom in).
1511
0
   * The range for this_frame_mv_in_out is -1.0 to +1.0
1512
0
   */
1513
0
  if (this_frame_mv_in_out > 0.0) {
1514
0
    frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1515
0
    /* In extreme case boost is halved */
1516
0
  } else {
1517
0
    frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
1518
0
  }
1519
0
1520
0
  /* Clip to maximum */
1521
0
  if (frame_boost > GF_RMAX) frame_boost = GF_RMAX;
1522
0
1523
0
  return frame_boost;
1524
0
}
1525
1526
#if NEW_BOOST
1527
static int calc_arf_boost(VP8_COMP *cpi, int offset, int f_frames, int b_frames,
1528
0
                          int *f_boost, int *b_boost) {
1529
0
  FIRSTPASS_STATS this_frame;
1530
0
1531
0
  int i;
1532
0
  double boost_score = 0.0;
1533
0
  double mv_ratio_accumulator = 0.0;
1534
0
  double decay_accumulator = 1.0;
1535
0
  double this_frame_mv_in_out = 0.0;
1536
0
  double mv_in_out_accumulator = 0.0;
1537
0
  double abs_mv_in_out_accumulator = 0.0;
1538
0
  double r;
1539
0
  int flash_detected = 0;
1540
0
1541
0
  /* Search forward from the proposed arf/next gf position */
1542
0
  for (i = 0; i < f_frames; ++i) {
1543
0
    if (read_frame_stats(cpi, &this_frame, (i + offset)) == EOF) break;
1544
0
1545
0
    /* Update the motion related elements to the boost calculation */
1546
0
    accumulate_frame_motion_stats(
1547
0
        cpi, &this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
1548
0
        &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
1549
0
1550
0
    /* Calculate the baseline boost number for this frame */
1551
0
    r = calc_frame_boost(cpi, &this_frame, this_frame_mv_in_out);
1552
0
1553
0
    /* We want to discount the the flash frame itself and the recovery
1554
0
     * frame that follows as both will have poor scores.
1555
0
     */
1556
0
    flash_detected =
1557
0
        detect_flash(cpi, (i + offset)) || detect_flash(cpi, (i + offset + 1));
1558
0
1559
0
    /* Cumulative effect of prediction quality decay */
1560
0
    if (!flash_detected) {
1561
0
      decay_accumulator =
1562
0
          decay_accumulator * get_prediction_decay_rate(cpi, &this_frame);
1563
0
      decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
1564
0
    }
1565
0
    boost_score += (decay_accumulator * r);
1566
0
1567
0
    /* Break out conditions. */
1568
0
    if ((!flash_detected) &&
1569
0
        ((mv_ratio_accumulator > 100.0) || (abs_mv_in_out_accumulator > 3.0) ||
1570
0
         (mv_in_out_accumulator < -2.0))) {
1571
0
      break;
1572
0
    }
1573
0
  }
1574
0
1575
0
  *f_boost = (int)(boost_score * 100.0) >> 4;
1576
0
1577
0
  /* Reset for backward looking loop */
1578
0
  boost_score = 0.0;
1579
0
  mv_ratio_accumulator = 0.0;
1580
0
  decay_accumulator = 1.0;
1581
0
  this_frame_mv_in_out = 0.0;
1582
0
  mv_in_out_accumulator = 0.0;
1583
0
  abs_mv_in_out_accumulator = 0.0;
1584
0
1585
0
  /* Search forward from the proposed arf/next gf position */
1586
0
  for (i = -1; i >= -b_frames; i--) {
1587
0
    if (read_frame_stats(cpi, &this_frame, (i + offset)) == EOF) break;
1588
0
1589
0
    /* Update the motion related elements to the boost calculation */
1590
0
    accumulate_frame_motion_stats(
1591
0
        cpi, &this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
1592
0
        &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
1593
0
1594
0
    /* Calculate the baseline boost number for this frame */
1595
0
    r = calc_frame_boost(cpi, &this_frame, this_frame_mv_in_out);
1596
0
1597
0
    /* We want to discount the the flash frame itself and the recovery
1598
0
     * frame that follows as both will have poor scores.
1599
0
     */
1600
0
    flash_detected =
1601
0
        detect_flash(cpi, (i + offset)) || detect_flash(cpi, (i + offset + 1));
1602
0
1603
0
    /* Cumulative effect of prediction quality decay */
1604
0
    if (!flash_detected) {
1605
0
      decay_accumulator =
1606
0
          decay_accumulator * get_prediction_decay_rate(cpi, &this_frame);
1607
0
      decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
1608
0
    }
1609
0
1610
0
    boost_score += (decay_accumulator * r);
1611
0
1612
0
    /* Break out conditions. */
1613
0
    if ((!flash_detected) &&
1614
0
        ((mv_ratio_accumulator > 100.0) || (abs_mv_in_out_accumulator > 3.0) ||
1615
0
         (mv_in_out_accumulator < -2.0))) {
1616
0
      break;
1617
0
    }
1618
0
  }
1619
0
  *b_boost = (int)(boost_score * 100.0) >> 4;
1620
0
1621
0
  return (*f_boost + *b_boost);
1622
0
}
1623
#endif
1624
1625
/* Analyse and define a gf/arf group . */
1626
0
static void define_gf_group(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame) {
1627
0
  FIRSTPASS_STATS next_frame;
1628
0
  FIRSTPASS_STATS *start_pos;
1629
0
  int i;
1630
0
  double r;
1631
0
  double boost_score = 0.0;
1632
0
  double old_boost_score = 0.0;
1633
0
  double gf_group_err = 0.0;
1634
0
  double gf_first_frame_err = 0.0;
1635
0
  double mod_frame_err = 0.0;
1636
0
1637
0
  double mv_ratio_accumulator = 0.0;
1638
0
  double decay_accumulator = 1.0;
1639
0
1640
0
  double loop_decay_rate = 1.00; /* Starting decay rate */
1641
0
1642
0
  double this_frame_mv_in_out = 0.0;
1643
0
  double mv_in_out_accumulator = 0.0;
1644
0
  double abs_mv_in_out_accumulator = 0.0;
1645
0
  double mod_err_per_mb_accumulator = 0.0;
1646
0
1647
0
  int max_bits = frame_max_bits(cpi); /* Max for a single frame */
1648
0
1649
0
  unsigned int allow_alt_ref =
1650
0
      cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames;
1651
0
1652
0
  int alt_boost = 0;
1653
0
  int f_boost = 0;
1654
0
  int b_boost = 0;
1655
0
  int flash_detected;
1656
0
1657
0
  cpi->twopass.gf_group_bits = 0;
1658
0
  cpi->twopass.gf_decay_rate = 0;
1659
0
1660
0
  vpx_clear_system_state();
1661
0
1662
0
  start_pos = cpi->twopass.stats_in;
1663
0
1664
0
  memset(&next_frame, 0, sizeof(next_frame)); /* assure clean */
1665
0
1666
0
  /* Load stats for the current frame. */
1667
0
  mod_frame_err = calculate_modified_err(cpi, this_frame);
1668
0
1669
0
  /* Note the error of the frame at the start of the group (this will be
1670
0
   * the GF frame error if we code a normal gf
1671
0
   */
1672
0
  gf_first_frame_err = mod_frame_err;
1673
0
1674
0
  /* Special treatment if the current frame is a key frame (which is also
1675
0
   * a gf). If it is then its error score (and hence bit allocation) need
1676
0
   * to be subtracted out from the calculation for the GF group
1677
0
   */
1678
0
  if (cpi->common.frame_type == KEY_FRAME) gf_group_err -= gf_first_frame_err;
1679
0
1680
0
  /* Scan forward to try and work out how many frames the next gf group
1681
0
   * should contain and what level of boost is appropriate for the GF
1682
0
   * or ARF that will be coded with the group
1683
0
   */
1684
0
  i = 0;
1685
0
1686
0
  while (((i < cpi->twopass.static_scene_max_gf_interval) ||
1687
0
          ((cpi->twopass.frames_to_key - i) < MIN_GF_INTERVAL)) &&
1688
0
         (i < cpi->twopass.frames_to_key)) {
1689
0
    i++;
1690
0
1691
0
    /* Accumulate error score of frames in this gf group */
1692
0
    mod_frame_err = calculate_modified_err(cpi, this_frame);
1693
0
1694
0
    gf_group_err += mod_frame_err;
1695
0
1696
0
    mod_err_per_mb_accumulator +=
1697
0
        mod_frame_err / DOUBLE_DIVIDE_CHECK((double)cpi->common.MBs);
1698
0
1699
0
    if (EOF == input_stats(cpi, &next_frame)) break;
1700
0
1701
0
    /* Test for the case where there is a brief flash but the prediction
1702
0
     * quality back to an earlier frame is then restored.
1703
0
     */
1704
0
    flash_detected = detect_flash(cpi, 0);
1705
0
1706
0
    /* Update the motion related elements to the boost calculation */
1707
0
    accumulate_frame_motion_stats(
1708
0
        cpi, &next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
1709
0
        &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
1710
0
1711
0
    /* Calculate a baseline boost number for this frame */
1712
0
    r = calc_frame_boost(cpi, &next_frame, this_frame_mv_in_out);
1713
0
1714
0
    /* Cumulative effect of prediction quality decay */
1715
0
    if (!flash_detected) {
1716
0
      loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
1717
0
      decay_accumulator = decay_accumulator * loop_decay_rate;
1718
0
      decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
1719
0
    }
1720
0
    boost_score += (decay_accumulator * r);
1721
0
1722
0
    /* Break clause to detect very still sections after motion
1723
0
     * For example a staic image after a fade or other transition.
1724
0
     */
1725
0
    if (detect_transition_to_still(cpi, i, 5, loop_decay_rate,
1726
0
                                   decay_accumulator)) {
1727
0
      allow_alt_ref = 0;
1728
0
      boost_score = old_boost_score;
1729
0
      break;
1730
0
    }
1731
0
1732
0
    /* Break out conditions. */
1733
0
    if (
1734
0
        /* Break at cpi->max_gf_interval unless almost totally static */
1735
0
        (i >= cpi->max_gf_interval && (decay_accumulator < 0.995)) ||
1736
0
        (
1737
0
            /* Dont break out with a very short interval */
1738
0
            (i > MIN_GF_INTERVAL) &&
1739
0
            /* Dont break out very close to a key frame */
1740
0
            ((cpi->twopass.frames_to_key - i) >= MIN_GF_INTERVAL) &&
1741
0
            ((boost_score > 20.0) || (next_frame.pcnt_inter < 0.75)) &&
1742
0
            (!flash_detected) && ((mv_ratio_accumulator > 100.0) ||
1743
0
                                  (abs_mv_in_out_accumulator > 3.0) ||
1744
0
                                  (mv_in_out_accumulator < -2.0) ||
1745
0
                                  ((boost_score - old_boost_score) < 2.0)))) {
1746
0
      boost_score = old_boost_score;
1747
0
      break;
1748
0
    }
1749
0
1750
0
    memcpy(this_frame, &next_frame, sizeof(*this_frame));
1751
0
1752
0
    old_boost_score = boost_score;
1753
0
  }
1754
0
1755
0
  cpi->twopass.gf_decay_rate =
1756
0
      (i > 0) ? (int)(100.0 * (1.0 - decay_accumulator)) / i : 0;
1757
0
1758
0
  /* When using CBR apply additional buffer related upper limits */
1759
0
  if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
1760
0
    double max_boost;
1761
0
1762
0
    /* For cbr apply buffer related limits */
1763
0
    if (cpi->drop_frames_allowed) {
1764
0
      int64_t df_buffer_level = cpi->oxcf.drop_frames_water_mark *
1765
0
                                (cpi->oxcf.optimal_buffer_level / 100);
1766
0
1767
0
      if (cpi->buffer_level > df_buffer_level) {
1768
0
        max_boost =
1769
0
            ((double)((cpi->buffer_level - df_buffer_level) * 2 / 3) * 16.0) /
1770
0
            DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
1771
0
      } else {
1772
0
        max_boost = 0.0;
1773
0
      }
1774
0
    } else if (cpi->buffer_level > 0) {
1775
0
      max_boost = ((double)(cpi->buffer_level * 2 / 3) * 16.0) /
1776
0
                  DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
1777
0
    } else {
1778
0
      max_boost = 0.0;
1779
0
    }
1780
0
1781
0
    if (boost_score > max_boost) boost_score = max_boost;
1782
0
  }
1783
0
1784
0
  /* Dont allow conventional gf too near the next kf */
1785
0
  if ((cpi->twopass.frames_to_key - i) < MIN_GF_INTERVAL) {
1786
0
    while (i < cpi->twopass.frames_to_key) {
1787
0
      i++;
1788
0
1789
0
      if (EOF == input_stats(cpi, this_frame)) break;
1790
0
1791
0
      if (i < cpi->twopass.frames_to_key) {
1792
0
        mod_frame_err = calculate_modified_err(cpi, this_frame);
1793
0
        gf_group_err += mod_frame_err;
1794
0
      }
1795
0
    }
1796
0
  }
1797
0
1798
0
  cpi->gfu_boost = (int)(boost_score * 100.0) >> 4;
1799
0
1800
0
#if NEW_BOOST
1801
0
  /* Alterrnative boost calculation for alt ref */
1802
0
  alt_boost = calc_arf_boost(cpi, 0, (i - 1), (i - 1), &f_boost, &b_boost);
1803
0
#endif
1804
0
1805
0
  /* Should we use the alternate refernce frame */
1806
0
  if (allow_alt_ref && (i >= MIN_GF_INTERVAL) &&
1807
0
      /* dont use ARF very near next kf */
1808
0
      (i <= (cpi->twopass.frames_to_key - MIN_GF_INTERVAL)) &&
1809
0
#if NEW_BOOST
1810
0
      ((next_frame.pcnt_inter > 0.75) || (next_frame.pcnt_second_ref > 0.5)) &&
1811
0
      ((mv_in_out_accumulator / (double)i > -0.2) ||
1812
0
       (mv_in_out_accumulator > -2.0)) &&
1813
0
      (b_boost > 100) && (f_boost > 100))
1814
#else
1815
      (next_frame.pcnt_inter > 0.75) &&
1816
      ((mv_in_out_accumulator / (double)i > -0.2) ||
1817
       (mv_in_out_accumulator > -2.0)) &&
1818
      (cpi->gfu_boost > 100) && (cpi->twopass.gf_decay_rate <=
1819
                                 (ARF_DECAY_THRESH + (cpi->gfu_boost / 200))))
1820
#endif
1821
0
  {
1822
0
    int Boost;
1823
0
    int allocation_chunks;
1824
0
    int Q =
1825
0
        (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
1826
0
    int tmp_q;
1827
0
    int arf_frame_bits = 0;
1828
0
    int group_bits;
1829
0
1830
0
#if NEW_BOOST
1831
0
    cpi->gfu_boost = alt_boost;
1832
0
#endif
1833
0
1834
0
    /* Estimate the bits to be allocated to the group as a whole */
1835
0
    if ((cpi->twopass.kf_group_bits > 0) &&
1836
0
        (cpi->twopass.kf_group_error_left > 0)) {
1837
0
      group_bits =
1838
0
          (int)((double)cpi->twopass.kf_group_bits *
1839
0
                (gf_group_err / (double)cpi->twopass.kf_group_error_left));
1840
0
    } else {
1841
0
      group_bits = 0;
1842
0
    }
1843
0
1844
0
/* Boost for arf frame */
1845
0
#if NEW_BOOST
1846
0
    Boost = (alt_boost * GFQ_ADJUSTMENT) / 100;
1847
#else
1848
    Boost = (cpi->gfu_boost * 3 * GFQ_ADJUSTMENT) / (2 * 100);
1849
#endif
1850
    Boost += (i * 50);
1851
0
1852
0
    /* Set max and minimum boost and hence minimum allocation */
1853
0
    if (Boost > ((cpi->baseline_gf_interval + 1) * 200)) {
1854
0
      Boost = ((cpi->baseline_gf_interval + 1) * 200);
1855
0
    } else if (Boost < 125) {
1856
0
      Boost = 125;
1857
0
    }
1858
0
1859
0
    allocation_chunks = (i * 100) + Boost;
1860
0
1861
0
    /* Normalize Altboost and allocations chunck down to prevent overflow */
1862
0
    while (Boost > 1000) {
1863
0
      Boost /= 2;
1864
0
      allocation_chunks /= 2;
1865
0
    }
1866
0
1867
0
    /* Calculate the number of bits to be spent on the arf based on the
1868
0
     * boost number
1869
0
     */
1870
0
    arf_frame_bits =
1871
0
        (int)((double)Boost * (group_bits / (double)allocation_chunks));
1872
0
1873
0
    /* Estimate if there are enough bits available to make worthwhile use
1874
0
     * of an arf.
1875
0
     */
1876
0
    tmp_q = estimate_q(cpi, mod_frame_err, (int)arf_frame_bits);
1877
0
1878
0
    /* Only use an arf if it is likely we will be able to code
1879
0
     * it at a lower Q than the surrounding frames.
1880
0
     */
1881
0
    if (tmp_q < cpi->worst_quality) {
1882
0
      int half_gf_int;
1883
0
      int frames_after_arf;
1884
0
      int frames_bwd = cpi->oxcf.arnr_max_frames - 1;
1885
0
      int frames_fwd = cpi->oxcf.arnr_max_frames - 1;
1886
0
1887
0
      cpi->source_alt_ref_pending = 1;
1888
0
1889
0
      /*
1890
0
       * For alt ref frames the error score for the end frame of the
1891
0
       * group (the alt ref frame) should not contribute to the group
1892
0
       * total and hence the number of bit allocated to the group.
1893
0
       * Rather it forms part of the next group (it is the GF at the
1894
0
       * start of the next group)
1895
0
       * gf_group_err -= mod_frame_err;
1896
0
       *
1897
0
       * For alt ref frames alt ref frame is technically part of the
1898
0
       * GF frame for the next group but we always base the error
1899
0
       * calculation and bit allocation on the current group of frames.
1900
0
       *
1901
0
       * Set the interval till the next gf or arf.
1902
0
       * For ARFs this is the number of frames to be coded before the
1903
0
       * future frame that is coded as an ARF.
1904
0
       * The future frame itself is part of the next group
1905
0
       */
1906
0
      cpi->baseline_gf_interval = i;
1907
0
1908
0
      /*
1909
0
       * Define the arnr filter width for this group of frames:
1910
0
       * We only filter frames that lie within a distance of half
1911
0
       * the GF interval from the ARF frame. We also have to trap
1912
0
       * cases where the filter extends beyond the end of clip.
1913
0
       * Note: this_frame->frame has been updated in the loop
1914
0
       * so it now points at the ARF frame.
1915
0
       */
1916
0
      half_gf_int = cpi->baseline_gf_interval >> 1;
1917
0
      frames_after_arf =
1918
0
          (int)(cpi->twopass.total_stats.count - this_frame->frame - 1);
1919
0
1920
0
      switch (cpi->oxcf.arnr_type) {
1921
0
        case 1: /* Backward filter */
1922
0
          frames_fwd = 0;
1923
0
          if (frames_bwd > half_gf_int) frames_bwd = half_gf_int;
1924
0
          break;
1925
0
1926
0
        case 2: /* Forward filter */
1927
0
          if (frames_fwd > half_gf_int) frames_fwd = half_gf_int;
1928
0
          if (frames_fwd > frames_after_arf) frames_fwd = frames_after_arf;
1929
0
          frames_bwd = 0;
1930
0
          break;
1931
0
1932
0
        case 3: /* Centered filter */
1933
0
        default:
1934
0
          frames_fwd >>= 1;
1935
0
          if (frames_fwd > frames_after_arf) frames_fwd = frames_after_arf;
1936
0
          if (frames_fwd > half_gf_int) frames_fwd = half_gf_int;
1937
0
1938
0
          frames_bwd = frames_fwd;
1939
0
1940
0
          /* For even length filter there is one more frame backward
1941
0
           * than forward: e.g. len=6 ==> bbbAff, len=7 ==> bbbAfff.
1942
0
           */
1943
0
          if (frames_bwd < half_gf_int) {
1944
0
            frames_bwd += (cpi->oxcf.arnr_max_frames + 1) & 0x1;
1945
0
          }
1946
0
          break;
1947
0
      }
1948
0
1949
0
      cpi->active_arnr_frames = frames_bwd + 1 + frames_fwd;
1950
0
    } else {
1951
0
      cpi->source_alt_ref_pending = 0;
1952
0
      cpi->baseline_gf_interval = i;
1953
0
    }
1954
0
  } else {
1955
0
    cpi->source_alt_ref_pending = 0;
1956
0
    cpi->baseline_gf_interval = i;
1957
0
  }
1958
0
1959
0
  /*
1960
0
   * Now decide how many bits should be allocated to the GF group as  a
1961
0
   * proportion of those remaining in the kf group.
1962
0
   * The final key frame group in the clip is treated as a special case
1963
0
   * where cpi->twopass.kf_group_bits is tied to cpi->twopass.bits_left.
1964
0
   * This is also important for short clips where there may only be one
1965
0
   * key frame.
1966
0
   */
1967
0
  if (cpi->twopass.frames_to_key >=
1968
0
      (int)(cpi->twopass.total_stats.count - cpi->common.current_video_frame)) {
1969
0
    cpi->twopass.kf_group_bits =
1970
0
        (cpi->twopass.bits_left > 0) ? cpi->twopass.bits_left : 0;
1971
0
  }
1972
0
1973
0
  /* Calculate the bits to be allocated to the group as a whole */
1974
0
  if ((cpi->twopass.kf_group_bits > 0) &&
1975
0
      (cpi->twopass.kf_group_error_left > 0)) {
1976
0
    cpi->twopass.gf_group_bits =
1977
0
        (int64_t)(cpi->twopass.kf_group_bits *
1978
0
                  (gf_group_err / cpi->twopass.kf_group_error_left));
1979
0
  } else {
1980
0
    cpi->twopass.gf_group_bits = 0;
1981
0
  }
1982
0
1983
0
  cpi->twopass.gf_group_bits =
1984
0
      (cpi->twopass.gf_group_bits < 0)
1985
0
          ? 0
1986
0
          : (cpi->twopass.gf_group_bits > cpi->twopass.kf_group_bits)
1987
0
                ? cpi->twopass.kf_group_bits
1988
0
                : cpi->twopass.gf_group_bits;
1989
0
1990
0
  /* Clip cpi->twopass.gf_group_bits based on user supplied data rate
1991
0
   * variability limit (cpi->oxcf.two_pass_vbrmax_section)
1992
0
   */
1993
0
  if (cpi->twopass.gf_group_bits >
1994
0
      (int64_t)max_bits * cpi->baseline_gf_interval) {
1995
0
    cpi->twopass.gf_group_bits = (int64_t)max_bits * cpi->baseline_gf_interval;
1996
0
  }
1997
0
1998
0
  /* Reset the file position */
1999
0
  reset_fpf_position(cpi, start_pos);
2000
0
2001
0
  /* Update the record of error used so far (only done once per gf group) */
2002
0
  cpi->twopass.modified_error_used += gf_group_err;
2003
0
2004
0
  /* Assign  bits to the arf or gf. */
2005
0
  for (i = 0; i <= (cpi->source_alt_ref_pending &&
2006
0
                    cpi->common.frame_type != KEY_FRAME);
2007
0
       i++) {
2008
0
    int Boost;
2009
0
    int allocation_chunks;
2010
0
    int Q =
2011
0
        (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
2012
0
    int gf_bits;
2013
0
2014
0
    /* For ARF frames */
2015
0
    if (cpi->source_alt_ref_pending && i == 0) {
2016
0
#if NEW_BOOST
2017
0
      Boost = (alt_boost * GFQ_ADJUSTMENT) / 100;
2018
#else
2019
      Boost = (cpi->gfu_boost * 3 * GFQ_ADJUSTMENT) / (2 * 100);
2020
#endif
2021
      Boost += (cpi->baseline_gf_interval * 50);
2022
0
2023
0
      /* Set max and minimum boost and hence minimum allocation */
2024
0
      if (Boost > ((cpi->baseline_gf_interval + 1) * 200)) {
2025
0
        Boost = ((cpi->baseline_gf_interval + 1) * 200);
2026
0
      } else if (Boost < 125) {
2027
0
        Boost = 125;
2028
0
      }
2029
0
2030
0
      allocation_chunks = ((cpi->baseline_gf_interval + 1) * 100) + Boost;
2031
0
    }
2032
0
    /* Else for standard golden frames */
2033
0
    else {
2034
0
      /* boost based on inter / intra ratio of subsequent frames */
2035
0
      Boost = (cpi->gfu_boost * GFQ_ADJUSTMENT) / 100;
2036
0
2037
0
      /* Set max and minimum boost and hence minimum allocation */
2038
0
      if (Boost > (cpi->baseline_gf_interval * 150)) {
2039
0
        Boost = (cpi->baseline_gf_interval * 150);
2040
0
      } else if (Boost < 125) {
2041
0
        Boost = 125;
2042
0
      }
2043
0
2044
0
      allocation_chunks = (cpi->baseline_gf_interval * 100) + (Boost - 100);
2045
0
    }
2046
0
2047
0
    /* Normalize Altboost and allocations chunck down to prevent overflow */
2048
0
    while (Boost > 1000) {
2049
0
      Boost /= 2;
2050
0
      allocation_chunks /= 2;
2051
0
    }
2052
0
2053
0
    /* Calculate the number of bits to be spent on the gf or arf based on
2054
0
     * the boost number
2055
0
     */
2056
0
    gf_bits = (int)((double)Boost *
2057
0
                    (cpi->twopass.gf_group_bits / (double)allocation_chunks));
2058
0
2059
0
    /* If the frame that is to be boosted is simpler than the average for
2060
0
     * the gf/arf group then use an alternative calculation
2061
0
     * based on the error score of the frame itself
2062
0
     */
2063
0
    if (mod_frame_err < gf_group_err / (double)cpi->baseline_gf_interval) {
2064
0
      double alt_gf_grp_bits;
2065
0
      int alt_gf_bits;
2066
0
2067
0
      alt_gf_grp_bits =
2068
0
          (double)cpi->twopass.kf_group_bits *
2069
0
          (mod_frame_err * (double)cpi->baseline_gf_interval) /
2070
0
          DOUBLE_DIVIDE_CHECK((double)cpi->twopass.kf_group_error_left);
2071
0
2072
0
      alt_gf_bits =
2073
0
          (int)((double)Boost * (alt_gf_grp_bits / (double)allocation_chunks));
2074
0
2075
0
      if (gf_bits > alt_gf_bits) {
2076
0
        gf_bits = alt_gf_bits;
2077
0
      }
2078
0
    }
2079
0
    /* Else if it is harder than other frames in the group make sure it at
2080
0
     * least receives an allocation in keeping with its relative error
2081
0
     * score, otherwise it may be worse off than an "un-boosted" frame
2082
0
     */
2083
0
    else {
2084
0
      int alt_gf_bits =
2085
0
          (int)((double)cpi->twopass.kf_group_bits * mod_frame_err /
2086
0
                DOUBLE_DIVIDE_CHECK((double)cpi->twopass.kf_group_error_left));
2087
0
2088
0
      if (alt_gf_bits > gf_bits) {
2089
0
        gf_bits = alt_gf_bits;
2090
0
      }
2091
0
    }
2092
0
2093
0
    /* Apply an additional limit for CBR */
2094
0
    if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
2095
0
      if (cpi->twopass.gf_bits > (int)(cpi->buffer_level >> 1)) {
2096
0
        cpi->twopass.gf_bits = (int)(cpi->buffer_level >> 1);
2097
0
      }
2098
0
    }
2099
0
2100
0
    /* Dont allow a negative value for gf_bits */
2101
0
    if (gf_bits < 0) gf_bits = 0;
2102
0
2103
0
    /* Add in minimum for a frame */
2104
0
    gf_bits += cpi->min_frame_bandwidth;
2105
0
2106
0
    if (i == 0) {
2107
0
      cpi->twopass.gf_bits = gf_bits;
2108
0
    }
2109
0
    if (i == 1 || (!cpi->source_alt_ref_pending &&
2110
0
                   (cpi->common.frame_type != KEY_FRAME))) {
2111
0
      /* Per frame bit target for this frame */
2112
0
      cpi->per_frame_bandwidth = gf_bits;
2113
0
    }
2114
0
  }
2115
0
2116
0
  {
2117
0
    /* Adjust KF group bits and error remainin */
2118
0
    cpi->twopass.kf_group_error_left -= (int64_t)gf_group_err;
2119
0
    cpi->twopass.kf_group_bits -= cpi->twopass.gf_group_bits;
2120
0
2121
0
    if (cpi->twopass.kf_group_bits < 0) cpi->twopass.kf_group_bits = 0;
2122
0
2123
0
    /* Note the error score left in the remaining frames of the group.
2124
0
     * For normal GFs we want to remove the error score for the first
2125
0
     * frame of the group (except in Key frame case where this has
2126
0
     * already happened)
2127
0
     */
2128
0
    if (!cpi->source_alt_ref_pending && cpi->common.frame_type != KEY_FRAME) {
2129
0
      cpi->twopass.gf_group_error_left =
2130
0
          (int)(gf_group_err - gf_first_frame_err);
2131
0
    } else {
2132
0
      cpi->twopass.gf_group_error_left = (int)gf_group_err;
2133
0
    }
2134
0
2135
0
    cpi->twopass.gf_group_bits -=
2136
0
        cpi->twopass.gf_bits - cpi->min_frame_bandwidth;
2137
0
2138
0
    if (cpi->twopass.gf_group_bits < 0) cpi->twopass.gf_group_bits = 0;
2139
0
2140
0
    /* This condition could fail if there are two kfs very close together
2141
0
     * despite (MIN_GF_INTERVAL) and would cause a devide by 0 in the
2142
0
     * calculation of cpi->twopass.alt_extra_bits.
2143
0
     */
2144
0
    if (cpi->baseline_gf_interval >= 3) {
2145
0
#if NEW_BOOST
2146
0
      int boost = (cpi->source_alt_ref_pending) ? b_boost : cpi->gfu_boost;
2147
#else
2148
      int boost = cpi->gfu_boost;
2149
#endif
2150
0
      if (boost >= 150) {
2151
0
        int pct_extra;
2152
0
2153
0
        pct_extra = (boost - 100) / 50;
2154
0
        pct_extra = (pct_extra > 20) ? 20 : pct_extra;
2155
0
2156
0
        cpi->twopass.alt_extra_bits =
2157
0
            (int)(cpi->twopass.gf_group_bits * pct_extra) / 100;
2158
0
        cpi->twopass.gf_group_bits -= cpi->twopass.alt_extra_bits;
2159
0
        cpi->twopass.alt_extra_bits /= ((cpi->baseline_gf_interval - 1) >> 1);
2160
0
      } else {
2161
0
        cpi->twopass.alt_extra_bits = 0;
2162
0
      }
2163
0
    } else {
2164
0
      cpi->twopass.alt_extra_bits = 0;
2165
0
    }
2166
0
  }
2167
0
2168
0
  /* Adjustments based on a measure of complexity of the section */
2169
0
  if (cpi->common.frame_type != KEY_FRAME) {
2170
0
    FIRSTPASS_STATS sectionstats;
2171
0
    double Ratio;
2172
0
2173
0
    zero_stats(&sectionstats);
2174
0
    reset_fpf_position(cpi, start_pos);
2175
0
2176
0
    for (i = 0; i < cpi->baseline_gf_interval; ++i) {
2177
0
      input_stats(cpi, &next_frame);
2178
0
      accumulate_stats(&sectionstats, &next_frame);
2179
0
    }
2180
0
2181
0
    avg_stats(&sectionstats);
2182
0
2183
0
    cpi->twopass.section_intra_rating =
2184
0
        (unsigned int)(sectionstats.intra_error /
2185
0
                       DOUBLE_DIVIDE_CHECK(sectionstats.coded_error));
2186
0
2187
0
    Ratio = sectionstats.intra_error /
2188
0
            DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
2189
0
    cpi->twopass.section_max_qfactor = 1.0 - ((Ratio - 10.0) * 0.025);
2190
0
2191
0
    if (cpi->twopass.section_max_qfactor < 0.80) {
2192
0
      cpi->twopass.section_max_qfactor = 0.80;
2193
0
    }
2194
0
2195
0
    reset_fpf_position(cpi, start_pos);
2196
0
  }
2197
0
}
2198
2199
/* Allocate bits to a normal frame that is neither a gf an arf or a key frame.
2200
 */
2201
0
static void assign_std_frame_bits(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2202
0
  int target_frame_size;
2203
0
2204
0
  double modified_err;
2205
0
  double err_fraction;
2206
0
2207
0
  int max_bits = frame_max_bits(cpi); /* Max for a single frame */
2208
0
2209
0
  /* Calculate modified prediction error used in bit allocation */
2210
0
  modified_err = calculate_modified_err(cpi, this_frame);
2211
0
2212
0
  /* What portion of the remaining GF group error is used by this frame */
2213
0
  if (cpi->twopass.gf_group_error_left > 0) {
2214
0
    err_fraction = modified_err / cpi->twopass.gf_group_error_left;
2215
0
  } else {
2216
0
    err_fraction = 0.0;
2217
0
  }
2218
0
2219
0
  /* How many of those bits available for allocation should we give it? */
2220
0
  target_frame_size = (int)((double)cpi->twopass.gf_group_bits * err_fraction);
2221
0
2222
0
  /* Clip to target size to 0 - max_bits (or cpi->twopass.gf_group_bits)
2223
0
   * at the top end.
2224
0
   */
2225
0
  if (target_frame_size < 0) {
2226
0
    target_frame_size = 0;
2227
0
  } else {
2228
0
    if (target_frame_size > max_bits) target_frame_size = max_bits;
2229
0
2230
0
    if (target_frame_size > cpi->twopass.gf_group_bits) {
2231
0
      target_frame_size = (int)cpi->twopass.gf_group_bits;
2232
0
    }
2233
0
  }
2234
0
2235
0
  /* Adjust error and bits remaining */
2236
0
  cpi->twopass.gf_group_error_left -= (int)modified_err;
2237
0
  cpi->twopass.gf_group_bits -= target_frame_size;
2238
0
2239
0
  if (cpi->twopass.gf_group_bits < 0) cpi->twopass.gf_group_bits = 0;
2240
0
2241
0
  /* Add in the minimum number of bits that is set aside for every frame. */
2242
0
  target_frame_size += cpi->min_frame_bandwidth;
2243
0
2244
0
  /* Every other frame gets a few extra bits */
2245
0
  if ((cpi->frames_since_golden & 0x01) &&
2246
0
      (cpi->frames_till_gf_update_due > 0)) {
2247
0
    target_frame_size += cpi->twopass.alt_extra_bits;
2248
0
  }
2249
0
2250
0
  /* Per frame bit target for this frame */
2251
0
  cpi->per_frame_bandwidth = target_frame_size;
2252
0
}
2253
2254
0
void vp8_second_pass(VP8_COMP *cpi) {
2255
0
  int tmp_q;
2256
0
  int frames_left =
2257
0
      (int)(cpi->twopass.total_stats.count - cpi->common.current_video_frame);
2258
0
2259
0
  FIRSTPASS_STATS this_frame;
2260
0
  FIRSTPASS_STATS this_frame_copy;
2261
0
2262
0
  double this_frame_intra_error;
2263
0
  double this_frame_coded_error;
2264
0
2265
0
  int overhead_bits;
2266
0
2267
0
  vp8_zero(this_frame);
2268
0
2269
0
  if (!cpi->twopass.stats_in) {
2270
0
    return;
2271
0
  }
2272
0
2273
0
  vpx_clear_system_state();
2274
0
2275
0
  if (EOF == input_stats(cpi, &this_frame)) return;
2276
0
2277
0
  this_frame_intra_error = this_frame.intra_error;
2278
0
  this_frame_coded_error = this_frame.coded_error;
2279
0
2280
0
  /* keyframe and section processing ! */
2281
0
  if (cpi->twopass.frames_to_key == 0) {
2282
0
    /* Define next KF group and assign bits to it */
2283
0
    memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2284
0
    find_next_key_frame(cpi, &this_frame_copy);
2285
0
2286
0
    /* Special case: Error error_resilient_mode mode does not make much
2287
0
     * sense for two pass but with its current meaning this code is
2288
0
     * designed to stop outlandish behaviour if someone does set it when
2289
0
     * using two pass. It effectively disables GF groups. This is
2290
0
     * temporary code until we decide what should really happen in this
2291
0
     * case.
2292
0
     */
2293
0
    if (cpi->oxcf.error_resilient_mode) {
2294
0
      cpi->twopass.gf_group_bits = cpi->twopass.kf_group_bits;
2295
0
      cpi->twopass.gf_group_error_left = (int)cpi->twopass.kf_group_error_left;
2296
0
      cpi->baseline_gf_interval = cpi->twopass.frames_to_key;
2297
0
      cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2298
0
      cpi->source_alt_ref_pending = 0;
2299
0
    }
2300
0
  }
2301
0
2302
0
  /* Is this a GF / ARF (Note that a KF is always also a GF) */
2303
0
  if (cpi->frames_till_gf_update_due == 0) {
2304
0
    /* Define next gf group and assign bits to it */
2305
0
    memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2306
0
    define_gf_group(cpi, &this_frame_copy);
2307
0
2308
0
    /* If we are going to code an altref frame at the end of the group
2309
0
     * and the current frame is not a key frame.... If the previous
2310
0
     * group used an arf this frame has already benefited from that arf
2311
0
     * boost and it should not be given extra bits If the previous
2312
0
     * group was NOT coded using arf we may want to apply some boost to
2313
0
     * this GF as well
2314
0
     */
2315
0
    if (cpi->source_alt_ref_pending && (cpi->common.frame_type != KEY_FRAME)) {
2316
0
      /* Assign a standard frames worth of bits from those allocated
2317
0
       * to the GF group
2318
0
       */
2319
0
      int bak = cpi->per_frame_bandwidth;
2320
0
      memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2321
0
      assign_std_frame_bits(cpi, &this_frame_copy);
2322
0
      cpi->per_frame_bandwidth = bak;
2323
0
    }
2324
0
  }
2325
0
2326
0
  /* Otherwise this is an ordinary frame */
2327
0
  else {
2328
0
    /* Special case: Error error_resilient_mode mode does not make much
2329
0
     * sense for two pass but with its current meaning but this code is
2330
0
     * designed to stop outlandish behaviour if someone does set it
2331
0
     * when using two pass. It effectively disables GF groups. This is
2332
0
     * temporary code till we decide what should really happen in this
2333
0
     * case.
2334
0
     */
2335
0
    if (cpi->oxcf.error_resilient_mode) {
2336
0
      cpi->frames_till_gf_update_due = cpi->twopass.frames_to_key;
2337
0
2338
0
      if (cpi->common.frame_type != KEY_FRAME) {
2339
0
        /* Assign bits from those allocated to the GF group */
2340
0
        memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2341
0
        assign_std_frame_bits(cpi, &this_frame_copy);
2342
0
      }
2343
0
    } else {
2344
0
      /* Assign bits from those allocated to the GF group */
2345
0
      memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2346
0
      assign_std_frame_bits(cpi, &this_frame_copy);
2347
0
    }
2348
0
  }
2349
0
2350
0
  /* Keep a globally available copy of this and the next frame's iiratio. */
2351
0
  cpi->twopass.this_iiratio =
2352
0
      (unsigned int)(this_frame_intra_error /
2353
0
                     DOUBLE_DIVIDE_CHECK(this_frame_coded_error));
2354
0
  {
2355
0
    FIRSTPASS_STATS next_frame;
2356
0
    if (lookup_next_frame_stats(cpi, &next_frame) != EOF) {
2357
0
      cpi->twopass.next_iiratio =
2358
0
          (unsigned int)(next_frame.intra_error /
2359
0
                         DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
2360
0
    }
2361
0
  }
2362
0
2363
0
  /* Set nominal per second bandwidth for this frame */
2364
0
  cpi->target_bandwidth =
2365
0
      (int)(cpi->per_frame_bandwidth * cpi->output_framerate);
2366
0
  if (cpi->target_bandwidth < 0) cpi->target_bandwidth = 0;
2367
0
2368
0
  /* Account for mv, mode and other overheads. */
2369
0
  overhead_bits = (int)estimate_modemvcost(cpi, &cpi->twopass.total_left_stats);
2370
0
2371
0
  /* Special case code for first frame. */
2372
0
  if (cpi->common.current_video_frame == 0) {
2373
0
    cpi->twopass.est_max_qcorrection_factor = 1.0;
2374
0
2375
0
    /* Set a cq_level in constrained quality mode. */
2376
0
    if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
2377
0
      int est_cq;
2378
0
2379
0
      est_cq = estimate_cq(cpi, &cpi->twopass.total_left_stats,
2380
0
                           (int)(cpi->twopass.bits_left / frames_left),
2381
0
                           overhead_bits);
2382
0
2383
0
      cpi->cq_target_quality = cpi->oxcf.cq_level;
2384
0
      if (est_cq > cpi->cq_target_quality) cpi->cq_target_quality = est_cq;
2385
0
    }
2386
0
2387
0
    /* guess at maxq needed in 2nd pass */
2388
0
    cpi->twopass.maxq_max_limit = cpi->worst_quality;
2389
0
    cpi->twopass.maxq_min_limit = cpi->best_quality;
2390
0
2391
0
    tmp_q = estimate_max_q(cpi, &cpi->twopass.total_left_stats,
2392
0
                           (int)(cpi->twopass.bits_left / frames_left),
2393
0
                           overhead_bits);
2394
0
2395
0
    /* Limit the maxq value returned subsequently.
2396
0
     * This increases the risk of overspend or underspend if the initial
2397
0
     * estimate for the clip is bad, but helps prevent excessive
2398
0
     * variation in Q, especially near the end of a clip
2399
0
     * where for example a small overspend may cause Q to crash
2400
0
     */
2401
0
    cpi->twopass.maxq_max_limit =
2402
0
        ((tmp_q + 32) < cpi->worst_quality) ? (tmp_q + 32) : cpi->worst_quality;
2403
0
    cpi->twopass.maxq_min_limit =
2404
0
        ((tmp_q - 32) > cpi->best_quality) ? (tmp_q - 32) : cpi->best_quality;
2405
0
2406
0
    cpi->active_worst_quality = tmp_q;
2407
0
    cpi->ni_av_qi = tmp_q;
2408
0
  }
2409
0
2410
0
  /* The last few frames of a clip almost always have to few or too many
2411
0
   * bits and for the sake of over exact rate control we dont want to make
2412
0
   * radical adjustments to the allowed quantizer range just to use up a
2413
0
   * few surplus bits or get beneath the target rate.
2414
0
   */
2415
0
  else if ((cpi->common.current_video_frame <
2416
0
            (((unsigned int)cpi->twopass.total_stats.count * 255) >> 8)) &&
2417
0
           ((cpi->common.current_video_frame + cpi->baseline_gf_interval) <
2418
0
            (unsigned int)cpi->twopass.total_stats.count)) {
2419
0
    if (frames_left < 1) frames_left = 1;
2420
0
2421
0
    tmp_q = estimate_max_q(cpi, &cpi->twopass.total_left_stats,
2422
0
                           (int)(cpi->twopass.bits_left / frames_left),
2423
0
                           overhead_bits);
2424
0
2425
0
    /* Move active_worst_quality but in a damped way */
2426
0
    if (tmp_q > cpi->active_worst_quality) {
2427
0
      cpi->active_worst_quality++;
2428
0
    } else if (tmp_q < cpi->active_worst_quality) {
2429
0
      cpi->active_worst_quality--;
2430
0
    }
2431
0
2432
0
    cpi->active_worst_quality =
2433
0
        ((cpi->active_worst_quality * 3) + tmp_q + 2) / 4;
2434
0
  }
2435
0
2436
0
  cpi->twopass.frames_to_key--;
2437
0
2438
0
  /* Update the total stats remaining sturcture */
2439
0
  subtract_stats(&cpi->twopass.total_left_stats, &this_frame);
2440
0
}
2441
2442
static int test_candidate_kf(VP8_COMP *cpi, FIRSTPASS_STATS *last_frame,
2443
                             FIRSTPASS_STATS *this_frame,
2444
0
                             FIRSTPASS_STATS *next_frame) {
2445
0
  int is_viable_kf = 0;
2446
0
2447
0
  /* Does the frame satisfy the primary criteria of a key frame
2448
0
   *      If so, then examine how well it predicts subsequent frames
2449
0
   */
2450
0
  if ((this_frame->pcnt_second_ref < 0.10) &&
2451
0
      (next_frame->pcnt_second_ref < 0.10) &&
2452
0
      ((this_frame->pcnt_inter < 0.05) ||
2453
0
       (((this_frame->pcnt_inter - this_frame->pcnt_neutral) < .25) &&
2454
0
        ((this_frame->intra_error /
2455
0
          DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) < 2.5) &&
2456
0
        ((fabs(last_frame->coded_error - this_frame->coded_error) /
2457
0
              DOUBLE_DIVIDE_CHECK(this_frame->coded_error) >
2458
0
          .40) ||
2459
0
         (fabs(last_frame->intra_error - this_frame->intra_error) /
2460
0
              DOUBLE_DIVIDE_CHECK(this_frame->intra_error) >
2461
0
          .40) ||
2462
0
         ((next_frame->intra_error /
2463
0
           DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) > 3.5))))) {
2464
0
    int i;
2465
0
    FIRSTPASS_STATS *start_pos;
2466
0
2467
0
    FIRSTPASS_STATS local_next_frame;
2468
0
2469
0
    double boost_score = 0.0;
2470
0
    double old_boost_score = 0.0;
2471
0
    double decay_accumulator = 1.0;
2472
0
    double next_iiratio;
2473
0
2474
0
    memcpy(&local_next_frame, next_frame, sizeof(*next_frame));
2475
0
2476
0
    /* Note the starting file position so we can reset to it */
2477
0
    start_pos = cpi->twopass.stats_in;
2478
0
2479
0
    /* Examine how well the key frame predicts subsequent frames */
2480
0
    for (i = 0; i < 16; ++i) {
2481
0
      next_iiratio = (IIKFACTOR1 * local_next_frame.intra_error /
2482
0
                      DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
2483
0
2484
0
      if (next_iiratio > RMAX) next_iiratio = RMAX;
2485
0
2486
0
      /* Cumulative effect of decay in prediction quality */
2487
0
      if (local_next_frame.pcnt_inter > 0.85) {
2488
0
        decay_accumulator = decay_accumulator * local_next_frame.pcnt_inter;
2489
0
      } else {
2490
0
        decay_accumulator =
2491
0
            decay_accumulator * ((0.85 + local_next_frame.pcnt_inter) / 2.0);
2492
0
      }
2493
0
2494
0
      /* Keep a running total */
2495
0
      boost_score += (decay_accumulator * next_iiratio);
2496
0
2497
0
      /* Test various breakout clauses */
2498
0
      if ((local_next_frame.pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
2499
0
          (((local_next_frame.pcnt_inter - local_next_frame.pcnt_neutral) <
2500
0
            0.20) &&
2501
0
           (next_iiratio < 3.0)) ||
2502
0
          ((boost_score - old_boost_score) < 0.5) ||
2503
0
          (local_next_frame.intra_error < 200)) {
2504
0
        break;
2505
0
      }
2506
0
2507
0
      old_boost_score = boost_score;
2508
0
2509
0
      /* Get the next frame details */
2510
0
      if (EOF == input_stats(cpi, &local_next_frame)) break;
2511
0
    }
2512
0
2513
0
    /* If there is tolerable prediction for at least the next 3 frames
2514
0
     * then break out else discard this pottential key frame and move on
2515
0
     */
2516
0
    if (boost_score > 5.0 && (i > 3)) {
2517
0
      is_viable_kf = 1;
2518
0
    } else {
2519
0
      /* Reset the file position */
2520
0
      reset_fpf_position(cpi, start_pos);
2521
0
2522
0
      is_viable_kf = 0;
2523
0
    }
2524
0
  }
2525
0
2526
0
  return is_viable_kf;
2527
0
}
2528
0
static void find_next_key_frame(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2529
0
  int i, j;
2530
0
  FIRSTPASS_STATS last_frame;
2531
0
  FIRSTPASS_STATS first_frame;
2532
0
  FIRSTPASS_STATS next_frame;
2533
0
  FIRSTPASS_STATS *start_position;
2534
0
2535
0
  double decay_accumulator = 1.0;
2536
0
  double boost_score = 0;
2537
0
  double old_boost_score = 0.0;
2538
0
  double loop_decay_rate;
2539
0
2540
0
  double kf_mod_err = 0.0;
2541
0
  double kf_group_err = 0.0;
2542
0
  double kf_group_intra_err = 0.0;
2543
0
  double kf_group_coded_err = 0.0;
2544
0
  double recent_loop_decay[8] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
2545
0
2546
0
  memset(&next_frame, 0, sizeof(next_frame));
2547
0
2548
0
  vpx_clear_system_state();
2549
0
  start_position = cpi->twopass.stats_in;
2550
0
2551
0
  cpi->common.frame_type = KEY_FRAME;
2552
0
2553
0
  /* is this a forced key frame by interval */
2554
0
  cpi->this_key_frame_forced = cpi->next_key_frame_forced;
2555
0
2556
0
  /* Clear the alt ref active flag as this can never be active on a key
2557
0
   * frame
2558
0
   */
2559
0
  cpi->source_alt_ref_active = 0;
2560
0
2561
0
  /* Kf is always a gf so clear frames till next gf counter */
2562
0
  cpi->frames_till_gf_update_due = 0;
2563
0
2564
0
  cpi->twopass.frames_to_key = 1;
2565
0
2566
0
  /* Take a copy of the initial frame details */
2567
0
  memcpy(&first_frame, this_frame, sizeof(*this_frame));
2568
0
2569
0
  cpi->twopass.kf_group_bits = 0;
2570
0
  cpi->twopass.kf_group_error_left = 0;
2571
0
2572
0
  kf_mod_err = calculate_modified_err(cpi, this_frame);
2573
0
2574
0
  /* find the next keyframe */
2575
0
  i = 0;
2576
0
  while (cpi->twopass.stats_in < cpi->twopass.stats_in_end) {
2577
0
    /* Accumulate kf group error */
2578
0
    kf_group_err += calculate_modified_err(cpi, this_frame);
2579
0
2580
0
    /* These figures keep intra and coded error counts for all frames
2581
0
     * including key frames in the group. The effect of the key frame
2582
0
     * itself can be subtracted out using the first_frame data
2583
0
     * collected above
2584
0
     */
2585
0
    kf_group_intra_err += this_frame->intra_error;
2586
0
    kf_group_coded_err += this_frame->coded_error;
2587
0
2588
0
    /* Load the next frame's stats. */
2589
0
    memcpy(&last_frame, this_frame, sizeof(*this_frame));
2590
0
    input_stats(cpi, this_frame);
2591
0
2592
0
    /* Provided that we are not at the end of the file... */
2593
0
    if (cpi->oxcf.auto_key &&
2594
0
        lookup_next_frame_stats(cpi, &next_frame) != EOF) {
2595
0
      /* Normal scene cut check */
2596
0
      if ((i >= MIN_GF_INTERVAL) &&
2597
0
          test_candidate_kf(cpi, &last_frame, this_frame, &next_frame)) {
2598
0
        break;
2599
0
      }
2600
0
2601
0
      /* How fast is prediction quality decaying */
2602
0
      loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
2603
0
2604
0
      /* We want to know something about the recent past... rather than
2605
0
       * as used elsewhere where we are concened with decay in prediction
2606
0
       * quality since the last GF or KF.
2607
0
       */
2608
0
      recent_loop_decay[i % 8] = loop_decay_rate;
2609
0
      decay_accumulator = 1.0;
2610
0
      for (j = 0; j < 8; ++j) {
2611
0
        decay_accumulator = decay_accumulator * recent_loop_decay[j];
2612
0
      }
2613
0
2614
0
      /* Special check for transition or high motion followed by a
2615
0
       * static scene.
2616
0
       */
2617
0
      if (detect_transition_to_still(cpi, i,
2618
0
                                     ((int)(cpi->key_frame_frequency) - (int)i),
2619
0
                                     loop_decay_rate, decay_accumulator)) {
2620
0
        break;
2621
0
      }
2622
0
2623
0
      /* Step on to the next frame */
2624
0
      cpi->twopass.frames_to_key++;
2625
0
2626
0
      /* If we don't have a real key frame within the next two
2627
0
       * forcekeyframeevery intervals then break out of the loop.
2628
0
       */
2629
0
      if (cpi->twopass.frames_to_key >= 2 * (int)cpi->key_frame_frequency) {
2630
0
        break;
2631
0
      }
2632
0
    } else {
2633
0
      cpi->twopass.frames_to_key++;
2634
0
    }
2635
0
2636
0
    i++;
2637
0
  }
2638
0
2639
0
  /* If there is a max kf interval set by the user we must obey it.
2640
0
   * We already breakout of the loop above at 2x max.
2641
0
   * This code centers the extra kf if the actual natural
2642
0
   * interval is between 1x and 2x
2643
0
   */
2644
0
  if (cpi->oxcf.auto_key &&
2645
0
      cpi->twopass.frames_to_key > (int)cpi->key_frame_frequency) {
2646
0
    FIRSTPASS_STATS *current_pos = cpi->twopass.stats_in;
2647
0
    FIRSTPASS_STATS tmp_frame;
2648
0
2649
0
    cpi->twopass.frames_to_key /= 2;
2650
0
2651
0
    /* Copy first frame details */
2652
0
    memcpy(&tmp_frame, &first_frame, sizeof(first_frame));
2653
0
2654
0
    /* Reset to the start of the group */
2655
0
    reset_fpf_position(cpi, start_position);
2656
0
2657
0
    kf_group_err = 0;
2658
0
    kf_group_intra_err = 0;
2659
0
    kf_group_coded_err = 0;
2660
0
2661
0
    /* Rescan to get the correct error data for the forced kf group */
2662
0
    for (i = 0; i < cpi->twopass.frames_to_key; ++i) {
2663
0
      /* Accumulate kf group errors */
2664
0
      kf_group_err += calculate_modified_err(cpi, &tmp_frame);
2665
0
      kf_group_intra_err += tmp_frame.intra_error;
2666
0
      kf_group_coded_err += tmp_frame.coded_error;
2667
0
2668
0
      /* Load a the next frame's stats */
2669
0
      input_stats(cpi, &tmp_frame);
2670
0
    }
2671
0
2672
0
    /* Reset to the start of the group */
2673
0
    reset_fpf_position(cpi, current_pos);
2674
0
2675
0
    cpi->next_key_frame_forced = 1;
2676
0
  } else {
2677
0
    cpi->next_key_frame_forced = 0;
2678
0
  }
2679
0
2680
0
  /* Special case for the last frame of the file */
2681
0
  if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end) {
2682
0
    /* Accumulate kf group error */
2683
0
    kf_group_err += calculate_modified_err(cpi, this_frame);
2684
0
2685
0
    /* These figures keep intra and coded error counts for all frames
2686
0
     * including key frames in the group. The effect of the key frame
2687
0
     * itself can be subtracted out using the first_frame data
2688
0
     * collected above
2689
0
     */
2690
0
    kf_group_intra_err += this_frame->intra_error;
2691
0
    kf_group_coded_err += this_frame->coded_error;
2692
0
  }
2693
0
2694
0
  /* Calculate the number of bits that should be assigned to the kf group. */
2695
0
  if ((cpi->twopass.bits_left > 0) &&
2696
0
      (cpi->twopass.modified_error_left > 0.0)) {
2697
0
    /* Max for a single normal frame (not key frame) */
2698
0
    int max_bits = frame_max_bits(cpi);
2699
0
2700
0
    /* Maximum bits for the kf group */
2701
0
    int64_t max_grp_bits;
2702
0
2703
0
    /* Default allocation based on bits left and relative
2704
0
     * complexity of the section
2705
0
     */
2706
0
    cpi->twopass.kf_group_bits =
2707
0
        (int64_t)(cpi->twopass.bits_left *
2708
0
                  (kf_group_err / cpi->twopass.modified_error_left));
2709
0
2710
0
    /* Clip based on maximum per frame rate defined by the user. */
2711
0
    max_grp_bits = (int64_t)max_bits * (int64_t)cpi->twopass.frames_to_key;
2712
0
    if (cpi->twopass.kf_group_bits > max_grp_bits) {
2713
0
      cpi->twopass.kf_group_bits = max_grp_bits;
2714
0
    }
2715
0
2716
0
    /* Additional special case for CBR if buffer is getting full. */
2717
0
    if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
2718
0
      int64_t opt_buffer_lvl = cpi->oxcf.optimal_buffer_level;
2719
0
      int64_t buffer_lvl = cpi->buffer_level;
2720
0
2721
0
      /* If the buffer is near or above the optimal and this kf group is
2722
0
       * not being allocated much then increase the allocation a bit.
2723
0
       */
2724
0
      if (buffer_lvl >= opt_buffer_lvl) {
2725
0
        int64_t high_water_mark =
2726
0
            (opt_buffer_lvl + cpi->oxcf.maximum_buffer_size) >> 1;
2727
0
2728
0
        int64_t av_group_bits;
2729
0
2730
0
        /* Av bits per frame * number of frames */
2731
0
        av_group_bits = (int64_t)cpi->av_per_frame_bandwidth *
2732
0
                        (int64_t)cpi->twopass.frames_to_key;
2733
0
2734
0
        /* We are at or above the maximum. */
2735
0
        if (cpi->buffer_level >= high_water_mark) {
2736
0
          int64_t min_group_bits;
2737
0
2738
0
          min_group_bits =
2739
0
              av_group_bits + (int64_t)(buffer_lvl - high_water_mark);
2740
0
2741
0
          if (cpi->twopass.kf_group_bits < min_group_bits) {
2742
0
            cpi->twopass.kf_group_bits = min_group_bits;
2743
0
          }
2744
0
        }
2745
0
        /* We are above optimal but below the maximum */
2746
0
        else if (cpi->twopass.kf_group_bits < av_group_bits) {
2747
0
          int64_t bits_below_av = av_group_bits - cpi->twopass.kf_group_bits;
2748
0
2749
0
          cpi->twopass.kf_group_bits += (int64_t)(
2750
0
              (double)bits_below_av * (double)(buffer_lvl - opt_buffer_lvl) /
2751
0
              (double)(high_water_mark - opt_buffer_lvl));
2752
0
        }
2753
0
      }
2754
0
    }
2755
0
  } else {
2756
0
    cpi->twopass.kf_group_bits = 0;
2757
0
  }
2758
0
2759
0
  /* Reset the first pass file position */
2760
0
  reset_fpf_position(cpi, start_position);
2761
0
2762
0
  /* determine how big to make this keyframe based on how well the
2763
0
   * subsequent frames use inter blocks
2764
0
   */
2765
0
  decay_accumulator = 1.0;
2766
0
  boost_score = 0.0;
2767
0
2768
0
  for (i = 0; i < cpi->twopass.frames_to_key; ++i) {
2769
0
    double r;
2770
0
2771
0
    if (EOF == input_stats(cpi, &next_frame)) break;
2772
0
2773
0
    if (next_frame.intra_error > cpi->twopass.kf_intra_err_min) {
2774
0
      r = (IIKFACTOR2 * next_frame.intra_error /
2775
0
           DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
2776
0
    } else {
2777
0
      r = (IIKFACTOR2 * cpi->twopass.kf_intra_err_min /
2778
0
           DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
2779
0
    }
2780
0
2781
0
    if (r > RMAX) r = RMAX;
2782
0
2783
0
    /* How fast is prediction quality decaying */
2784
0
    loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
2785
0
2786
0
    decay_accumulator = decay_accumulator * loop_decay_rate;
2787
0
    decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
2788
0
2789
0
    boost_score += (decay_accumulator * r);
2790
0
2791
0
    if ((i > MIN_GF_INTERVAL) && ((boost_score - old_boost_score) < 1.0)) {
2792
0
      break;
2793
0
    }
2794
0
2795
0
    old_boost_score = boost_score;
2796
0
  }
2797
0
2798
0
  if (1) {
2799
0
    FIRSTPASS_STATS sectionstats;
2800
0
    double Ratio;
2801
0
2802
0
    zero_stats(&sectionstats);
2803
0
    reset_fpf_position(cpi, start_position);
2804
0
2805
0
    for (i = 0; i < cpi->twopass.frames_to_key; ++i) {
2806
0
      input_stats(cpi, &next_frame);
2807
0
      accumulate_stats(&sectionstats, &next_frame);
2808
0
    }
2809
0
2810
0
    avg_stats(&sectionstats);
2811
0
2812
0
    cpi->twopass.section_intra_rating =
2813
0
        (unsigned int)(sectionstats.intra_error /
2814
0
                       DOUBLE_DIVIDE_CHECK(sectionstats.coded_error));
2815
0
2816
0
    Ratio = sectionstats.intra_error /
2817
0
            DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
2818
0
    cpi->twopass.section_max_qfactor = 1.0 - ((Ratio - 10.0) * 0.025);
2819
0
2820
0
    if (cpi->twopass.section_max_qfactor < 0.80) {
2821
0
      cpi->twopass.section_max_qfactor = 0.80;
2822
0
    }
2823
0
  }
2824
0
2825
0
  /* When using CBR apply additional buffer fullness related upper limits */
2826
0
  if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
2827
0
    double max_boost;
2828
0
2829
0
    if (cpi->drop_frames_allowed) {
2830
0
      int df_buffer_level = (int)(cpi->oxcf.drop_frames_water_mark *
2831
0
                                  (cpi->oxcf.optimal_buffer_level / 100));
2832
0
2833
0
      if (cpi->buffer_level > df_buffer_level) {
2834
0
        max_boost =
2835
0
            ((double)((cpi->buffer_level - df_buffer_level) * 2 / 3) * 16.0) /
2836
0
            DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
2837
0
      } else {
2838
0
        max_boost = 0.0;
2839
0
      }
2840
0
    } else if (cpi->buffer_level > 0) {
2841
0
      max_boost = ((double)(cpi->buffer_level * 2 / 3) * 16.0) /
2842
0
                  DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
2843
0
    } else {
2844
0
      max_boost = 0.0;
2845
0
    }
2846
0
2847
0
    if (boost_score > max_boost) boost_score = max_boost;
2848
0
  }
2849
0
2850
0
  /* Reset the first pass file position */
2851
0
  reset_fpf_position(cpi, start_position);
2852
0
2853
0
  /* Work out how many bits to allocate for the key frame itself */
2854
0
  if (1) {
2855
0
    int kf_boost = (int)boost_score;
2856
0
    int allocation_chunks;
2857
0
    int Counter = cpi->twopass.frames_to_key;
2858
0
    int alt_kf_bits;
2859
0
    YV12_BUFFER_CONFIG *lst_yv12 = &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
2860
0
/* Min boost based on kf interval */
2861
#if 0
2862
2863
        while ((kf_boost < 48) && (Counter > 0))
2864
        {
2865
            Counter -= 2;
2866
            kf_boost ++;
2867
        }
2868
2869
#endif
2870
2871
0
    if (kf_boost < 48) {
2872
0
      kf_boost += ((Counter + 1) >> 1);
2873
0
2874
0
      if (kf_boost > 48) kf_boost = 48;
2875
0
    }
2876
0
2877
0
    /* bigger frame sizes need larger kf boosts, smaller frames smaller
2878
0
     * boosts...
2879
0
     */
2880
0
    if ((lst_yv12->y_width * lst_yv12->y_height) > (320 * 240)) {
2881
0
      kf_boost += 2 * (lst_yv12->y_width * lst_yv12->y_height) / (320 * 240);
2882
0
    } else if ((lst_yv12->y_width * lst_yv12->y_height) < (320 * 240)) {
2883
0
      kf_boost -= 4 * (320 * 240) / (lst_yv12->y_width * lst_yv12->y_height);
2884
0
    }
2885
0
2886
0
    /* Min KF boost */
2887
0
    kf_boost = (int)((double)kf_boost * 100.0) >> 4; /* Scale 16 to 100 */
2888
0
    if (kf_boost < 250) kf_boost = 250;
2889
0
2890
0
    /*
2891
0
     * We do three calculations for kf size.
2892
0
     * The first is based on the error score for the whole kf group.
2893
0
     * The second (optionaly) on the key frames own error if this is
2894
0
     * smaller than the average for the group.
2895
0
     * The final one insures that the frame receives at least the
2896
0
     * allocation it would have received based on its own error score vs
2897
0
     * the error score remaining
2898
0
     * Special case if the sequence appears almost totaly static
2899
0
     * as measured by the decay accumulator. In this case we want to
2900
0
     * spend almost all of the bits on the key frame.
2901
0
     * cpi->twopass.frames_to_key-1 because key frame itself is taken
2902
0
     * care of by kf_boost.
2903
0
     */
2904
0
    if (decay_accumulator >= 0.99) {
2905
0
      allocation_chunks = ((cpi->twopass.frames_to_key - 1) * 10) + kf_boost;
2906
0
    } else {
2907
0
      allocation_chunks = ((cpi->twopass.frames_to_key - 1) * 100) + kf_boost;
2908
0
    }
2909
0
2910
0
    /* Normalize Altboost and allocations chunck down to prevent overflow */
2911
0
    while (kf_boost > 1000) {
2912
0
      kf_boost /= 2;
2913
0
      allocation_chunks /= 2;
2914
0
    }
2915
0
2916
0
    cpi->twopass.kf_group_bits =
2917
0
        (cpi->twopass.kf_group_bits < 0) ? 0 : cpi->twopass.kf_group_bits;
2918
0
2919
0
    /* Calculate the number of bits to be spent on the key frame */
2920
0
    cpi->twopass.kf_bits =
2921
0
        (int)((double)kf_boost *
2922
0
              ((double)cpi->twopass.kf_group_bits / (double)allocation_chunks));
2923
0
2924
0
    /* Apply an additional limit for CBR */
2925
0
    if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
2926
0
      if (cpi->twopass.kf_bits > (int)((3 * cpi->buffer_level) >> 2)) {
2927
0
        cpi->twopass.kf_bits = (int)((3 * cpi->buffer_level) >> 2);
2928
0
      }
2929
0
    }
2930
0
2931
0
    /* If the key frame is actually easier than the average for the
2932
0
     * kf group (which does sometimes happen... eg a blank intro frame)
2933
0
     * Then use an alternate calculation based on the kf error score
2934
0
     * which should give a smaller key frame.
2935
0
     */
2936
0
    if (kf_mod_err < kf_group_err / cpi->twopass.frames_to_key) {
2937
0
      double alt_kf_grp_bits =
2938
0
          ((double)cpi->twopass.bits_left *
2939
0
           (kf_mod_err * (double)cpi->twopass.frames_to_key) /
2940
0
           DOUBLE_DIVIDE_CHECK(cpi->twopass.modified_error_left));
2941
0
2942
0
      alt_kf_bits = (int)((double)kf_boost *
2943
0
                          (alt_kf_grp_bits / (double)allocation_chunks));
2944
0
2945
0
      if (cpi->twopass.kf_bits > alt_kf_bits) {
2946
0
        cpi->twopass.kf_bits = alt_kf_bits;
2947
0
      }
2948
0
    }
2949
0
    /* Else if it is much harder than other frames in the group make sure
2950
0
     * it at least receives an allocation in keeping with its relative
2951
0
     * error score
2952
0
     */
2953
0
    else {
2954
0
      alt_kf_bits = (int)((double)cpi->twopass.bits_left *
2955
0
                          (kf_mod_err / DOUBLE_DIVIDE_CHECK(
2956
0
                                            cpi->twopass.modified_error_left)));
2957
0
2958
0
      if (alt_kf_bits > cpi->twopass.kf_bits) {
2959
0
        cpi->twopass.kf_bits = alt_kf_bits;
2960
0
      }
2961
0
    }
2962
0
2963
0
    cpi->twopass.kf_group_bits -= cpi->twopass.kf_bits;
2964
0
    /* Add in the minimum frame allowance */
2965
0
    cpi->twopass.kf_bits += cpi->min_frame_bandwidth;
2966
0
2967
0
    /* Peer frame bit target for this frame */
2968
0
    cpi->per_frame_bandwidth = cpi->twopass.kf_bits;
2969
0
2970
0
    /* Convert to a per second bitrate */
2971
0
    cpi->target_bandwidth = (int)(cpi->twopass.kf_bits * cpi->output_framerate);
2972
0
  }
2973
0
2974
0
  /* Note the total error score of the kf group minus the key frame itself */
2975
0
  cpi->twopass.kf_group_error_left = (int)(kf_group_err - kf_mod_err);
2976
0
2977
0
  /* Adjust the count of total modified error left. The count of bits left
2978
0
   * is adjusted elsewhere based on real coded frame sizes
2979
0
   */
2980
0
  cpi->twopass.modified_error_left -= kf_group_err;
2981
0
2982
0
  if (cpi->oxcf.allow_spatial_resampling) {
2983
0
    int resample_trigger = 0;
2984
0
    int last_kf_resampled = 0;
2985
0
    int kf_q;
2986
0
    int scale_val = 0;
2987
0
    int hr, hs, vr, vs;
2988
0
    int new_width = cpi->oxcf.Width;
2989
0
    int new_height = cpi->oxcf.Height;
2990
0
2991
0
    int projected_buffer_level;
2992
0
    int tmp_q;
2993
0
2994
0
    double projected_bits_perframe;
2995
0
    double group_iiratio = (kf_group_intra_err - first_frame.intra_error) /
2996
0
                           (kf_group_coded_err - first_frame.coded_error);
2997
0
    double err_per_frame = kf_group_err / cpi->twopass.frames_to_key;
2998
0
    double bits_per_frame;
2999
0
    double av_bits_per_frame;
3000
0
    double effective_size_ratio;
3001
0
3002
0
    if ((cpi->common.Width != cpi->oxcf.Width) ||
3003
0
        (cpi->common.Height != cpi->oxcf.Height)) {
3004
0
      last_kf_resampled = 1;
3005
0
    }
3006
0
3007
0
    /* Set back to unscaled by defaults */
3008
0
    cpi->common.horiz_scale = NORMAL;
3009
0
    cpi->common.vert_scale = NORMAL;
3010
0
3011
0
    /* Calculate Average bits per frame. */
3012
0
    av_bits_per_frame = cpi->oxcf.target_bandwidth /
3013
0
                        DOUBLE_DIVIDE_CHECK((double)cpi->framerate);
3014
0
3015
0
    /* CBR... Use the clip average as the target for deciding resample */
3016
0
    if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
3017
0
      bits_per_frame = av_bits_per_frame;
3018
0
    }
3019
0
3020
0
    /* In VBR we want to avoid downsampling in easy section unless we
3021
0
     * are under extreme pressure So use the larger of target bitrate
3022
0
     * for this section or average bitrate for sequence
3023
0
     */
3024
0
    else {
3025
0
      /* This accounts for how hard the section is... */
3026
0
      bits_per_frame =
3027
0
          (double)(cpi->twopass.kf_group_bits / cpi->twopass.frames_to_key);
3028
0
3029
0
      /* Dont turn to resampling in easy sections just because they
3030
0
       * have been assigned a small number of bits
3031
0
       */
3032
0
      if (bits_per_frame < av_bits_per_frame) {
3033
0
        bits_per_frame = av_bits_per_frame;
3034
0
      }
3035
0
    }
3036
0
3037
0
    /* bits_per_frame should comply with our minimum */
3038
0
    if (bits_per_frame < (cpi->oxcf.target_bandwidth *
3039
0
                          cpi->oxcf.two_pass_vbrmin_section / 100)) {
3040
0
      bits_per_frame = (cpi->oxcf.target_bandwidth *
3041
0
                        cpi->oxcf.two_pass_vbrmin_section / 100);
3042
0
    }
3043
0
3044
0
    /* Work out if spatial resampling is necessary */
3045
0
    kf_q = estimate_kf_group_q(cpi, err_per_frame, (int)bits_per_frame,
3046
0
                               group_iiratio);
3047
0
3048
0
    /* If we project a required Q higher than the maximum allowed Q then
3049
0
     * make a guess at the actual size of frames in this section
3050
0
     */
3051
0
    projected_bits_perframe = bits_per_frame;
3052
0
    tmp_q = kf_q;
3053
0
3054
0
    while (tmp_q > cpi->worst_quality) {
3055
0
      projected_bits_perframe *= 1.04;
3056
0
      tmp_q--;
3057
0
    }
3058
0
3059
0
    /* Guess at buffer level at the end of the section */
3060
0
    projected_buffer_level =
3061
0
        (int)(cpi->buffer_level -
3062
0
              (int)((projected_bits_perframe - av_bits_per_frame) *
3063
0
                    cpi->twopass.frames_to_key));
3064
0
3065
0
    if (0) {
3066
0
      FILE *f = fopen("Subsamle.stt", "a");
3067
0
      fprintf(f, " %8d %8d %8d %8d %12.0f %8d %8d %8d\n",
3068
0
              cpi->common.current_video_frame, kf_q, cpi->common.horiz_scale,
3069
0
              cpi->common.vert_scale, kf_group_err / cpi->twopass.frames_to_key,
3070
0
              (int)(cpi->twopass.kf_group_bits / cpi->twopass.frames_to_key),
3071
0
              new_height, new_width);
3072
0
      fclose(f);
3073
0
    }
3074
0
3075
0
    /* The trigger for spatial resampling depends on the various
3076
0
     * parameters such as whether we are streaming (CBR) or VBR.
3077
0
     */
3078
0
    if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
3079
0
      /* Trigger resample if we are projected to fall below down
3080
0
       * sample level or resampled last time and are projected to
3081
0
       * remain below the up sample level
3082
0
       */
3083
0
      if ((projected_buffer_level < (cpi->oxcf.resample_down_water_mark *
3084
0
                                     cpi->oxcf.optimal_buffer_level / 100)) ||
3085
0
          (last_kf_resampled &&
3086
0
           (projected_buffer_level < (cpi->oxcf.resample_up_water_mark *
3087
0
                                      cpi->oxcf.optimal_buffer_level / 100)))) {
3088
0
        resample_trigger = 1;
3089
0
      } else {
3090
0
        resample_trigger = 0;
3091
0
      }
3092
0
    } else {
3093
0
      int64_t clip_bits = (int64_t)(
3094
0
          cpi->twopass.total_stats.count * cpi->oxcf.target_bandwidth /
3095
0
          DOUBLE_DIVIDE_CHECK((double)cpi->framerate));
3096
0
      int64_t over_spend = cpi->oxcf.starting_buffer_level - cpi->buffer_level;
3097
0
3098
0
      /* If triggered last time the threshold for triggering again is
3099
0
       * reduced:
3100
0
       *
3101
0
       * Projected Q higher than allowed and Overspend > 5% of total
3102
0
       * bits
3103
0
       */
3104
0
      if ((last_kf_resampled && (kf_q > cpi->worst_quality)) ||
3105
0
          ((kf_q > cpi->worst_quality) && (over_spend > clip_bits / 20))) {
3106
0
        resample_trigger = 1;
3107
0
      } else {
3108
0
        resample_trigger = 0;
3109
0
      }
3110
0
    }
3111
0
3112
0
    if (resample_trigger) {
3113
0
      while ((kf_q >= cpi->worst_quality) && (scale_val < 6)) {
3114
0
        scale_val++;
3115
0
3116
0
        cpi->common.vert_scale = vscale_lookup[scale_val];
3117
0
        cpi->common.horiz_scale = hscale_lookup[scale_val];
3118
0
3119
0
        Scale2Ratio(cpi->common.horiz_scale, &hr, &hs);
3120
0
        Scale2Ratio(cpi->common.vert_scale, &vr, &vs);
3121
0
3122
0
        new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
3123
0
        new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
3124
0
3125
0
        /* Reducing the area to 1/4 does not reduce the complexity
3126
0
         * (err_per_frame) to 1/4... effective_sizeratio attempts
3127
0
         * to provide a crude correction for this
3128
0
         */
3129
0
        effective_size_ratio = (double)(new_width * new_height) /
3130
0
                               (double)(cpi->oxcf.Width * cpi->oxcf.Height);
3131
0
        effective_size_ratio = (1.0 + (3.0 * effective_size_ratio)) / 4.0;
3132
0
3133
0
        /* Now try again and see what Q we get with the smaller
3134
0
         * image size
3135
0
         */
3136
0
        kf_q = estimate_kf_group_q(cpi, err_per_frame * effective_size_ratio,
3137
0
                                   (int)bits_per_frame, group_iiratio);
3138
0
3139
0
        if (0) {
3140
0
          FILE *f = fopen("Subsamle.stt", "a");
3141
0
          fprintf(
3142
0
              f, "******** %8d %8d %8d %12.0f %8d %8d %8d\n", kf_q,
3143
0
              cpi->common.horiz_scale, cpi->common.vert_scale,
3144
0
              kf_group_err / cpi->twopass.frames_to_key,
3145
0
              (int)(cpi->twopass.kf_group_bits / cpi->twopass.frames_to_key),
3146
0
              new_height, new_width);
3147
0
          fclose(f);
3148
0
        }
3149
0
      }
3150
0
    }
3151
0
3152
0
    if ((cpi->common.Width != new_width) ||
3153
0
        (cpi->common.Height != new_height)) {
3154
0
      cpi->common.Width = new_width;
3155
0
      cpi->common.Height = new_height;
3156
0
      vp8_alloc_compressor_data(cpi);
3157
0
    }
3158
0
  }
3159
0
}