vp9_firstpass.c 86.6 KB
Newer Older
John Koleszar's avatar
John Koleszar committed
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
John Koleszar's avatar
John Koleszar committed
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5
6
 *  that can be found in the LICENSE file in the root of the source
 *  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.
John Koleszar's avatar
John Koleszar committed
9
10
11
12
 */

#include "math.h"
#include "limits.h"
13
14
15
16
#include "vp9/encoder/vp9_block.h"
#include "vp9/encoder/vp9_onyx_int.h"
#include "vp9/encoder/vp9_variance.h"
#include "vp9/encoder/vp9_encodeintra.h"
17
#include "vp9/common/vp9_setupintrarecon.h"
18
19
#include "vp9/encoder/vp9_mcomp.h"
#include "vp9/encoder/vp9_firstpass.h"
Johann's avatar
Johann committed
20
#include "vpx_scale/vpx_scale.h"
21
#include "vp9/encoder/vp9_encodeframe.h"
22
#include "vp9/encoder/vp9_encodemb.h"
23
24
#include "vp9/common/vp9_extend.h"
#include "vp9/common/vp9_systemdependent.h"
John Koleszar's avatar
John Koleszar committed
25
#include "vpx_mem/vpx_mem.h"
26
#include "vp9/common/vp9_swapyv12buffer.h"
John Koleszar's avatar
John Koleszar committed
27
#include <stdio.h>
28
#include "vp9/encoder/vp9_quantize.h"
29
30
#include "vp9/encoder/vp9_rdopt.h"
#include "vp9/encoder/vp9_ratectrl.h"
31
32
#include "vp9/common/vp9_quant_common.h"
#include "vp9/common/vp9_entropymv.h"
33
#include "vp9/encoder/vp9_encodemv.h"
34
#include "./vpx_scale_rtcd.h"
John Koleszar's avatar
John Koleszar committed
35

36
#define OUTPUT_FPF 0
John Koleszar's avatar
John Koleszar committed
37

38
39
#define IIFACTOR   12.5
#define IIKFACTOR1 12.5
40
41
#define IIKFACTOR2 15.0
#define RMAX       128.0
42
#define GF_RMAX    96.0
Paul Wilkins's avatar
Paul Wilkins committed
43
#define ERR_DIVISOR   150.0
John Koleszar's avatar
John Koleszar committed
44

45
46
#define KF_MB_INTRA_MIN 300
#define GF_MB_INTRA_MIN 200
Paul Wilkins's avatar
CQ Mode    
Paul Wilkins committed
47

John Koleszar's avatar
John Koleszar committed
48
49
50
51
52
#define DOUBLE_DIVIDE_CHECK(X) ((X)<0?(X)-.000001:(X)+.000001)

#define POW1 (double)cpi->oxcf.two_pass_vbrbias/100.0
#define POW2 (double)cpi->oxcf.two_pass_vbrbias/100.0

53
static void find_next_key_frame(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame);
Paul Wilkins's avatar
Paul Wilkins committed
54

John Koleszar's avatar
John Koleszar committed
55
56
57
static int select_cq_level(int qindex) {
  int ret_val = QINDEX_RANGE - 1;
  int i;
Paul Wilkins's avatar
Paul Wilkins committed
58

59
  double target_q = (vp9_convert_qindex_to_q(qindex) * 0.5847) + 1.0;
Paul Wilkins's avatar
Paul Wilkins committed
60

John Koleszar's avatar
John Koleszar committed
61
  for (i = 0; i < QINDEX_RANGE; i++) {
62
    if (target_q <= vp9_convert_qindex_to_q(i)) {
John Koleszar's avatar
John Koleszar committed
63
64
      ret_val = i;
      break;
Paul Wilkins's avatar
Paul Wilkins committed
65
    }
John Koleszar's avatar
John Koleszar committed
66
  }
Paul Wilkins's avatar
Paul Wilkins committed
67

John Koleszar's avatar
John Koleszar committed
68
  return ret_val;
Paul Wilkins's avatar
Paul Wilkins committed
69
}
Paul Wilkins's avatar
CQ Mode    
Paul Wilkins committed
70

John Koleszar's avatar
John Koleszar committed
71
72

// Resets the first pass file to the given position using a relative seek from the current position
73
static void reset_fpf_position(VP9_COMP *cpi, FIRSTPASS_STATS *Position) {
John Koleszar's avatar
John Koleszar committed
74
  cpi->twopass.stats_in = Position;
John Koleszar's avatar
John Koleszar committed
75
76
}

77
static int lookup_next_frame_stats(VP9_COMP *cpi, FIRSTPASS_STATS *next_frame) {
John Koleszar's avatar
John Koleszar committed
78
79
  if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end)
    return EOF;
John Koleszar's avatar
John Koleszar committed
80

John Koleszar's avatar
John Koleszar committed
81
82
  *next_frame = *cpi->twopass.stats_in;
  return 1;
John Koleszar's avatar
John Koleszar committed
83
84
}

85
// Read frame stats at an offset from the current position
86
static int read_frame_stats(VP9_COMP *cpi,
John Koleszar's avatar
John Koleszar committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
                            FIRSTPASS_STATS *frame_stats,
                            int offset) {
  FIRSTPASS_STATS *fps_ptr = cpi->twopass.stats_in;

  // Check legality of offset
  if (offset >= 0) {
    if (&fps_ptr[offset] >= cpi->twopass.stats_in_end)
      return EOF;
  } else if (offset < 0) {
    if (&fps_ptr[offset] < cpi->twopass.stats_in_start)
      return EOF;
  }

  *frame_stats = fps_ptr[offset];
  return 1;
102
103
}

104
static int input_stats(VP9_COMP *cpi, FIRSTPASS_STATS *fps) {
John Koleszar's avatar
John Koleszar committed
105
106
  if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end)
    return EOF;
107

John Koleszar's avatar
John Koleszar committed
108
109
110
111
  *fps = *cpi->twopass.stats_in;
  cpi->twopass.stats_in =
    (void *)((char *)cpi->twopass.stats_in + sizeof(FIRSTPASS_STATS));
  return 1;
112
113
}

114
static void output_stats(const VP9_COMP            *cpi,
115
                         struct vpx_codec_pkt_list *pktlist,
John Koleszar's avatar
John Koleszar committed
116
117
118
119
120
121
                         FIRSTPASS_STATS            *stats) {
  struct vpx_codec_cx_pkt pkt;
  pkt.kind = VPX_CODEC_STATS_PKT;
  pkt.data.twopass_stats.buf = stats;
  pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
  vpx_codec_pkt_list_add(pktlist, &pkt);
122
123
124
125

// TEMP debug code
#if OUTPUT_FPF

John Koleszar's avatar
John Koleszar committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
  {
    FILE *fpfile;
    fpfile = fopen("firstpass.stt", "a");

    fprintf(fpfile, "%12.0f %12.0f %12.0f %12.0f %12.0f %12.4f %12.4f"
            "%12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f"
            "%12.0f %12.0f %12.4f %12.0f %12.0f %12.4f\n",
            stats->frame,
            stats->intra_error,
            stats->coded_error,
            stats->sr_coded_error,
            stats->ssim_weighted_pred_err,
            stats->pcnt_inter,
            stats->pcnt_motion,
            stats->pcnt_second_ref,
            stats->pcnt_neutral,
            stats->MVr,
            stats->mvr_abs,
            stats->MVc,
            stats->mvc_abs,
            stats->MVrv,
            stats->MVcv,
            stats->mv_in_out_count,
            stats->new_mv_count,
            stats->count,
            stats->duration);
    fclose(fpfile);
  }
154
155
156
#endif
}

John Koleszar's avatar
John Koleszar committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
static void zero_stats(FIRSTPASS_STATS *section) {
  section->frame      = 0.0;
  section->intra_error = 0.0;
  section->coded_error = 0.0;
  section->sr_coded_error = 0.0;
  section->ssim_weighted_pred_err = 0.0;
  section->pcnt_inter  = 0.0;
  section->pcnt_motion  = 0.0;
  section->pcnt_second_ref = 0.0;
  section->pcnt_neutral = 0.0;
  section->MVr        = 0.0;
  section->mvr_abs     = 0.0;
  section->MVc        = 0.0;
  section->mvc_abs     = 0.0;
  section->MVrv       = 0.0;
  section->MVcv       = 0.0;
  section->mv_in_out_count  = 0.0;
  section->new_mv_count = 0.0;
  section->count      = 0.0;
  section->duration   = 1.0;
177
178
}

John Koleszar's avatar
John Koleszar committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
static void accumulate_stats(FIRSTPASS_STATS *section, FIRSTPASS_STATS *frame) {
  section->frame += frame->frame;
  section->intra_error += frame->intra_error;
  section->coded_error += frame->coded_error;
  section->sr_coded_error += frame->sr_coded_error;
  section->ssim_weighted_pred_err += frame->ssim_weighted_pred_err;
  section->pcnt_inter  += frame->pcnt_inter;
  section->pcnt_motion += frame->pcnt_motion;
  section->pcnt_second_ref += frame->pcnt_second_ref;
  section->pcnt_neutral += frame->pcnt_neutral;
  section->MVr        += frame->MVr;
  section->mvr_abs     += frame->mvr_abs;
  section->MVc        += frame->MVc;
  section->mvc_abs     += frame->mvc_abs;
  section->MVrv       += frame->MVrv;
  section->MVcv       += frame->MVcv;
  section->mv_in_out_count  += frame->mv_in_out_count;
  section->new_mv_count += frame->new_mv_count;
  section->count      += frame->count;
  section->duration   += frame->duration;
199
200
}

John Koleszar's avatar
John Koleszar committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
static void subtract_stats(FIRSTPASS_STATS *section, FIRSTPASS_STATS *frame) {
  section->frame -= frame->frame;
  section->intra_error -= frame->intra_error;
  section->coded_error -= frame->coded_error;
  section->sr_coded_error -= frame->sr_coded_error;
  section->ssim_weighted_pred_err -= frame->ssim_weighted_pred_err;
  section->pcnt_inter  -= frame->pcnt_inter;
  section->pcnt_motion -= frame->pcnt_motion;
  section->pcnt_second_ref -= frame->pcnt_second_ref;
  section->pcnt_neutral -= frame->pcnt_neutral;
  section->MVr        -= frame->MVr;
  section->mvr_abs     -= frame->mvr_abs;
  section->MVc        -= frame->MVc;
  section->mvc_abs     -= frame->mvc_abs;
  section->MVrv       -= frame->MVrv;
  section->MVcv       -= frame->MVcv;
  section->mv_in_out_count  -= frame->mv_in_out_count;
  section->new_mv_count -= frame->new_mv_count;
  section->count      -= frame->count;
  section->duration   -= frame->duration;
221
222
}

John Koleszar's avatar
John Koleszar committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
static void avg_stats(FIRSTPASS_STATS *section) {
  if (section->count < 1.0)
    return;

  section->intra_error /= section->count;
  section->coded_error /= section->count;
  section->sr_coded_error /= section->count;
  section->ssim_weighted_pred_err /= section->count;
  section->pcnt_inter  /= section->count;
  section->pcnt_second_ref /= section->count;
  section->pcnt_neutral /= section->count;
  section->pcnt_motion /= section->count;
  section->MVr        /= section->count;
  section->mvr_abs     /= section->count;
  section->MVc        /= section->count;
  section->mvc_abs     /= section->count;
  section->MVrv       /= section->count;
  section->MVcv       /= section->count;
  section->mv_in_out_count   /= section->count;
  section->duration   /= section->count;
243
244
}

John Koleszar's avatar
John Koleszar committed
245
// Calculate a modified Error used in distributing bits between easier and harder frames
246
static double calculate_modified_err(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
John Koleszar's avatar
John Koleszar committed
247
248
249
250
251
252
253
254
255
256
257
  double av_err = (cpi->twopass.total_stats->ssim_weighted_pred_err /
                   cpi->twopass.total_stats->count);
  double this_err = this_frame->ssim_weighted_pred_err;
  double modified_err;

  if (this_err > av_err)
    modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW1);
  else
    modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW2);

  return modified_err;
John Koleszar's avatar
John Koleszar committed
258
259
}

260
static const double weight_table[256] = {
John Koleszar's avatar
John Koleszar committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
  0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
  0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
  0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
  0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
  0.020000, 0.031250, 0.062500, 0.093750, 0.125000, 0.156250, 0.187500, 0.218750,
  0.250000, 0.281250, 0.312500, 0.343750, 0.375000, 0.406250, 0.437500, 0.468750,
  0.500000, 0.531250, 0.562500, 0.593750, 0.625000, 0.656250, 0.687500, 0.718750,
  0.750000, 0.781250, 0.812500, 0.843750, 0.875000, 0.906250, 0.937500, 0.968750,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000
293
294
};

John Koleszar's avatar
John Koleszar committed
295
296
297
static double simple_weight(YV12_BUFFER_CONFIG *source) {
  int i, j;

298
  uint8_t *src = source->y_buffer;
John Koleszar's avatar
John Koleszar committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
  double sum_weights = 0.0;

  // Loop throught the Y plane raw examining levels and creating a weight for the image
  i = source->y_height;
  do {
    j = source->y_width;
    do {
      sum_weights += weight_table[ *src];
      src++;
    } while (--j);
    src -= source->y_width;
    src += source->y_stride;
  } while (--i);

  sum_weights /= (source->y_height * source->y_width);

  return sum_weights;
John Koleszar's avatar
John Koleszar committed
316
317
}

318

John Koleszar's avatar
John Koleszar committed
319
// This function returns the current per frame maximum bitrate target
320
static int frame_max_bits(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
321
322
  // Max allocation for a single frame based on the max section guidelines passed in and how many bits are left
  int max_bits;
John Koleszar's avatar
John Koleszar committed
323

John Koleszar's avatar
John Koleszar committed
324
325
  // For VBR base this on the bits and frames left plus the two_pass_vbrmax_section rate passed in by the user
  max_bits = (int)(((double)cpi->twopass.bits_left / (cpi->twopass.total_stats->count - (double)cpi->common.current_video_frame)) * ((double)cpi->oxcf.two_pass_vbrmax_section / 100.0));
John Koleszar's avatar
John Koleszar committed
326

John Koleszar's avatar
John Koleszar committed
327
328
329
  // Trap case where we are out of bits
  if (max_bits < 0)
    max_bits = 0;
John Koleszar's avatar
John Koleszar committed
330

John Koleszar's avatar
John Koleszar committed
331
  return max_bits;
John Koleszar's avatar
John Koleszar committed
332
333
}

334
void vp9_init_first_pass(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
335
  zero_stats(cpi->twopass.total_stats);
John Koleszar's avatar
John Koleszar committed
336
337
}

338
void vp9_end_first_pass(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
339
  output_stats(cpi, cpi->output_pkt_list, cpi->twopass.total_stats);
340
}
John Koleszar's avatar
John Koleszar committed
341

342
static void zz_motion_search(VP9_COMP *cpi, MACROBLOCK *x, YV12_BUFFER_CONFIG *recon_buffer, int *best_motion_err, int recon_yoffset) {
John Koleszar's avatar
John Koleszar committed
343
  MACROBLOCKD *const xd = &x->e_mbd;
John Koleszar's avatar
John Koleszar committed
344
345
  BLOCK *b = &x->block[0];
  BLOCKD *d = &x->e_mbd.block[0];
John Koleszar's avatar
John Koleszar committed
346

347
  uint8_t *src_ptr = (*(b->base_src) + b->src);
John Koleszar's avatar
John Koleszar committed
348
  int src_stride = b->src_stride;
349
  uint8_t *ref_ptr;
John Koleszar's avatar
John Koleszar committed
350
  int ref_stride = d->pre_stride;
John Koleszar's avatar
John Koleszar committed
351

John Koleszar's avatar
John Koleszar committed
352
353
  // Set up pointers for this macro block recon buffer
  xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;
John Koleszar's avatar
John Koleszar committed
354

355
  ref_ptr = (uint8_t *)(*(d->base_pre) + d->pre);
John Koleszar's avatar
John Koleszar committed
356

357
  vp9_mse16x16(src_ptr, src_stride, ref_ptr, ref_stride,
358
               (unsigned int *)(best_motion_err));
John Koleszar's avatar
John Koleszar committed
359
360
}

361
static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
Scott LaVarnway's avatar
Scott LaVarnway committed
362
363
                                     int_mv *ref_mv, MV *best_mv,
                                     YV12_BUFFER_CONFIG *recon_buffer,
John Koleszar's avatar
John Koleszar committed
364
                                     int *best_motion_err, int recon_yoffset) {
John Koleszar's avatar
John Koleszar committed
365
  MACROBLOCKD *const xd = &x->e_mbd;
John Koleszar's avatar
John Koleszar committed
366
367
368
369
370
371
372
373
374
375
376
  BLOCK *b = &x->block[0];
  BLOCKD *d = &x->e_mbd.block[0];
  int num00;

  int_mv tmp_mv;
  int_mv ref_mv_full;

  int tmp_err;
  int step_param = 3;
  int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
  int n;
377
  vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[BLOCK_16X16];
John Koleszar's avatar
John Koleszar committed
378
379
380
  int new_mv_mode_penalty = 256;

  // override the default variance function to use MSE
381
  v_fn_ptr.vf = vp9_mse16x16;
John Koleszar's avatar
John Koleszar committed
382
383
384
385
386
387
388
389
390
391

  // Set up pointers for this macro block recon buffer
  xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;

  // Initial step/diamond search centred on best mv
  tmp_mv.as_int = 0;
  ref_mv_full.as_mv.col = ref_mv->as_mv.col >> 3;
  ref_mv_full.as_mv.row = ref_mv->as_mv.row >> 3;
  tmp_err = cpi->diamond_search_sad(x, b, d, &ref_mv_full, &tmp_mv, step_param,
                                    x->sadperbit16, &num00, &v_fn_ptr,
392
393
                                    x->nmvjointcost,
                                    x->mvcost, ref_mv);
John Koleszar's avatar
John Koleszar committed
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
  if (tmp_err < INT_MAX - new_mv_mode_penalty)
    tmp_err += new_mv_mode_penalty;

  if (tmp_err < *best_motion_err) {
    *best_motion_err = tmp_err;
    best_mv->row = tmp_mv.as_mv.row;
    best_mv->col = tmp_mv.as_mv.col;
  }

  // Further step/diamond searches as necessary
  n = num00;
  num00 = 0;

  while (n < further_steps) {
    n++;

    if (num00)
      num00--;
    else {
      tmp_err = cpi->diamond_search_sad(x, b, d, &ref_mv_full, &tmp_mv,
                                        step_param + n, x->sadperbit16,
                                        &num00, &v_fn_ptr,
416
417
                                        x->nmvjointcost,
                                        x->mvcost, ref_mv);
John Koleszar's avatar
John Koleszar committed
418
      if (tmp_err < INT_MAX - new_mv_mode_penalty)
John Koleszar's avatar
John Koleszar committed
419
420
        tmp_err += new_mv_mode_penalty;

John Koleszar's avatar
John Koleszar committed
421
      if (tmp_err < *best_motion_err) {
John Koleszar's avatar
John Koleszar committed
422
        *best_motion_err = tmp_err;
Scott LaVarnway's avatar
Scott LaVarnway committed
423
424
        best_mv->row = tmp_mv.as_mv.row;
        best_mv->col = tmp_mv.as_mv.col;
John Koleszar's avatar
John Koleszar committed
425
      }
John Koleszar's avatar
John Koleszar committed
426
    }
John Koleszar's avatar
John Koleszar committed
427
  }
John Koleszar's avatar
John Koleszar committed
428
429
}

430
void vp9_first_pass(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
431
  int mb_row, mb_col;
John Koleszar's avatar
John Koleszar committed
432
  MACROBLOCK *const x = &cpi->mb;
433
  VP9_COMMON *const cm = &cpi->common;
John Koleszar's avatar
John Koleszar committed
434
  MACROBLOCKD *const xd = &x->e_mbd;
John Koleszar's avatar
John Koleszar committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461

  int recon_yoffset, recon_uvoffset;
  YV12_BUFFER_CONFIG *lst_yv12 = &cm->yv12_fb[cm->lst_fb_idx];
  YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
  YV12_BUFFER_CONFIG *gld_yv12 = &cm->yv12_fb[cm->gld_fb_idx];
  int recon_y_stride = lst_yv12->y_stride;
  int recon_uv_stride = lst_yv12->uv_stride;
  int64_t intra_error = 0;
  int64_t coded_error = 0;
  int64_t sr_coded_error = 0;

  int sum_mvr = 0, sum_mvc = 0;
  int sum_mvr_abs = 0, sum_mvc_abs = 0;
  int sum_mvrs = 0, sum_mvcs = 0;
  int mvcount = 0;
  int intercount = 0;
  int second_ref_count = 0;
  int intrapenalty = 256;
  int neutral_count = 0;
  int new_mv_count = 0;
  int sum_in_vectors = 0;
  uint32_t lastmv_as_int = 0;

  int_mv zero_ref_mv;

  zero_ref_mv.as_int = 0;

462
  vp9_clear_system_state();  // __asm emms;
John Koleszar's avatar
John Koleszar committed
463
464
465
466
467
468
469
470
471

  x->src = * cpi->Source;
  xd->pre = *lst_yv12;
  xd->dst = *new_yv12;

  x->partition_info = x->pi;

  xd->mode_info_context = cm->mi;

472
  vp9_build_block_offsets(x);
John Koleszar's avatar
John Koleszar committed
473

474
  vp9_setup_block_dptrs(&x->e_mbd);
John Koleszar's avatar
John Koleszar committed
475

476
  vp9_setup_block_ptrs(x);
John Koleszar's avatar
John Koleszar committed
477
478

  // set up frame new frame for intra coded blocks
479
  vp9_setup_intra_recon(new_yv12);
480
  vp9_frame_init_quantizer(cpi);
John Koleszar's avatar
John Koleszar committed
481
482
483
484
485

  // Initialise the MV cost table to the defaults
  // if( cm->current_video_frame == 0)
  // if ( 0 )
  {
486
    vp9_init_mv_probs(cm);
487
    vp9_initialize_rd_consts(cpi, cm->base_qindex + cm->y1dc_delta_q);
John Koleszar's avatar
John Koleszar committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501
  }

  // for each macroblock row in image
  for (mb_row = 0; mb_row < cm->mb_rows; mb_row++) {
    int_mv best_ref_mv;

    best_ref_mv.as_int = 0;

    // reset above block coeffs
    xd->up_available = (mb_row != 0);
    recon_yoffset = (mb_row * recon_y_stride * 16);
    recon_uvoffset = (mb_row * recon_uv_stride * 8);

    // Set up limit values for motion vectors to prevent them extending outside the UMV borders
John Koleszar's avatar
John Koleszar committed
502
503
504
    x->mv_row_min = -((mb_row * 16) + (VP9BORDERINPIXELS - 16));
    x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16)
                    + (VP9BORDERINPIXELS - 16);
John Koleszar's avatar
John Koleszar committed
505
506
507
508
509
510
511
512
513
514
515
516
517


    // for each macroblock col in image
    for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) {
      int this_error;
      int gf_motion_error = INT_MAX;
      int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);

      xd->dst.y_buffer = new_yv12->y_buffer + recon_yoffset;
      xd->dst.u_buffer = new_yv12->u_buffer + recon_uvoffset;
      xd->dst.v_buffer = new_yv12->v_buffer + recon_uvoffset;
      xd->left_available = (mb_col != 0);

518
#if !CONFIG_SUPERBLOCKS
John Koleszar's avatar
John Koleszar committed
519
      // Copy current mb to a buffer
520
      vp9_copy_mem16x16(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
521
#endif
John Koleszar's avatar
John Koleszar committed
522
523

      // do intra 16x16 prediction
524
      this_error = vp9_encode_intra(cpi, x, use_dc_pred);
John Koleszar's avatar
John Koleszar committed
525
526
527
528
529
530
531
532
533
534
535

      // "intrapenalty" below deals with situations where the intra and inter error scores are very low (eg a plain black frame)
      // We do not have special cases in first pass for 0,0 and nearest etc so all inter modes carry an overhead cost estimate fot the mv.
      // When the error score is very low this causes us to pick all or lots of INTRA modes and throw lots of key frames.
      // This penalty adds a cost matching that of a 0,0 mv to the intra case.
      this_error += intrapenalty;

      // Cumulative intra error total
      intra_error += (int64_t)this_error;

      // Set up limit values for motion vectors to prevent them extending outside the UMV borders
John Koleszar's avatar
John Koleszar committed
536
537
538
      x->mv_col_min = -((mb_col * 16) + (VP9BORDERINPIXELS - 16));
      x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16)
                      + (VP9BORDERINPIXELS - 16);
John Koleszar's avatar
John Koleszar committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566

      // Other than for the first frame do a motion search
      if (cm->current_video_frame > 0) {
        int tmp_err;
        int motion_error = INT_MAX;
        int_mv mv, tmp_mv;

        // Simple 0,0 motion with no mv overhead
        zz_motion_search(cpi, x, lst_yv12, &motion_error, recon_yoffset);
        mv.as_int = tmp_mv.as_int = 0;

        // Test last reference frame using the previous best mv as the
        // starting point (best reference) for the search
        first_pass_motion_search(cpi, x, &best_ref_mv,
                                 &mv.as_mv, lst_yv12,
                                 &motion_error, recon_yoffset);

        // If the current best reference mv is not centred on 0,0 then do a 0,0 based search as well
        if (best_ref_mv.as_int) {
          tmp_err = INT_MAX;
          first_pass_motion_search(cpi, x, &zero_ref_mv, &tmp_mv.as_mv,
                                   lst_yv12, &tmp_err, recon_yoffset);

          if (tmp_err < motion_error) {
            motion_error = tmp_err;
            mv.as_int = tmp_mv.as_int;
          }
        }
John Koleszar's avatar
John Koleszar committed
567

John Koleszar's avatar
John Koleszar committed
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
        // Experimental search in an older reference frame
        if (cm->current_video_frame > 1) {
          // Simple 0,0 motion with no mv overhead
          zz_motion_search(cpi, x, gld_yv12,
                           &gf_motion_error, recon_yoffset);

          first_pass_motion_search(cpi, x, &zero_ref_mv,
                                   &tmp_mv.as_mv, gld_yv12,
                                   &gf_motion_error, recon_yoffset);

          if ((gf_motion_error < motion_error) &&
              (gf_motion_error < this_error)) {
            second_ref_count++;
          }

          // Reset to last frame as reference buffer
          xd->pre.y_buffer = lst_yv12->y_buffer + recon_yoffset;
          xd->pre.u_buffer = lst_yv12->u_buffer + recon_uvoffset;
          xd->pre.v_buffer = lst_yv12->v_buffer + recon_uvoffset;

          // In accumulating a score for the older reference frame
          // take the best of the motion predicted score and
          // the intra coded error (just as will be done for)
          // accumulation of "coded_error" for the last frame.
          if (gf_motion_error < this_error)
            sr_coded_error += gf_motion_error;
          else
            sr_coded_error += this_error;
        } else
          sr_coded_error += motion_error;
598

John Koleszar's avatar
John Koleszar committed
599
        /* Intra assumed best */
600
        best_ref_mv.as_int = 0;
John Koleszar's avatar
John Koleszar committed
601

John Koleszar's avatar
John Koleszar committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
        if (motion_error <= this_error) {
          // Keep a count of cases where the inter and intra were
          // very close and very low. This helps with scene cut
          // detection for example in cropped clips with black bars
          // at the sides or top and bottom.
          if ((((this_error - intrapenalty) * 9) <=
               (motion_error * 10)) &&
              (this_error < (2 * intrapenalty))) {
            neutral_count++;
          }

          mv.as_mv.row <<= 3;
          mv.as_mv.col <<= 3;
          this_error = motion_error;
616
          vp9_set_mbmode_and_mvs(x, NEWMV, &mv);
617
          xd->mode_info_context->mbmi.txfm_size = TX_4X4;
618
          vp9_encode_inter16x16y(x);
John Koleszar's avatar
John Koleszar committed
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
          sum_mvr += mv.as_mv.row;
          sum_mvr_abs += abs(mv.as_mv.row);
          sum_mvc += mv.as_mv.col;
          sum_mvc_abs += abs(mv.as_mv.col);
          sum_mvrs += mv.as_mv.row * mv.as_mv.row;
          sum_mvcs += mv.as_mv.col * mv.as_mv.col;
          intercount++;

          best_ref_mv.as_int = mv.as_int;

          // Was the vector non-zero
          if (mv.as_int) {
            mvcount++;

            // Was it different from the last non zero vector
            if (mv.as_int != lastmv_as_int)
              new_mv_count++;
            lastmv_as_int = mv.as_int;

            // Does the Row vector point inwards or outwards
            if (mb_row < cm->mb_rows / 2) {
              if (mv.as_mv.row > 0)
                sum_in_vectors--;
              else if (mv.as_mv.row < 0)
                sum_in_vectors++;
            } else if (mb_row > cm->mb_rows / 2) {
              if (mv.as_mv.row > 0)
                sum_in_vectors++;
              else if (mv.as_mv.row < 0)
                sum_in_vectors--;
John Koleszar's avatar
John Koleszar committed
649
650
            }

John Koleszar's avatar
John Koleszar committed
651
652
653
654
655
656
657
658
659
660
661
662
663
            // Does the Row vector point inwards or outwards
            if (mb_col < cm->mb_cols / 2) {
              if (mv.as_mv.col > 0)
                sum_in_vectors--;
              else if (mv.as_mv.col < 0)
                sum_in_vectors++;
            } else if (mb_col > cm->mb_cols / 2) {
              if (mv.as_mv.col > 0)
                sum_in_vectors++;
              else if (mv.as_mv.col < 0)
                sum_in_vectors--;
            }
          }
John Koleszar's avatar
John Koleszar committed
664
        }
John Koleszar's avatar
John Koleszar committed
665
666
      } else
        sr_coded_error += (int64_t)this_error;
John Koleszar's avatar
John Koleszar committed
667

John Koleszar's avatar
John Koleszar committed
668
      coded_error += (int64_t)this_error;
John Koleszar's avatar
John Koleszar committed
669

John Koleszar's avatar
John Koleszar committed
670
671
672
673
      // adjust to the next column of macroblocks
      x->src.y_buffer += 16;
      x->src.u_buffer += 8;
      x->src.v_buffer += 8;
John Koleszar's avatar
John Koleszar committed
674

John Koleszar's avatar
John Koleszar committed
675
676
      recon_yoffset += 16;
      recon_uvoffset += 8;
John Koleszar's avatar
John Koleszar committed
677
678
    }

John Koleszar's avatar
John Koleszar committed
679
680
681
682
683
684
    // adjust to the next row of mbs
    x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
    x->src.u_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
    x->src.v_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;

    // extend the recon for intra prediction
685
686
    vp9_extend_mb_row(new_yv12, xd->dst.y_buffer + 16,
                      xd->dst.u_buffer + 8, xd->dst.v_buffer + 8);
687
    vp9_clear_system_state();  // __asm emms;
John Koleszar's avatar
John Koleszar committed
688
689
  }

690
  vp9_clear_system_state();  // __asm emms;
John Koleszar's avatar
John Koleszar committed
691
692
693
694
695
696
  {
    double weight = 0.0;

    FIRSTPASS_STATS fps;

    fps.frame      = cm->current_video_frame;
697
698
699
    fps.intra_error = (double)(intra_error >> 8);
    fps.coded_error = (double)(coded_error >> 8);
    fps.sr_coded_error = (double)(sr_coded_error >> 8);
John Koleszar's avatar
John Koleszar committed
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
    weight = simple_weight(cpi->Source);


    if (weight < 0.1)
      weight = 0.1;

    fps.ssim_weighted_pred_err = fps.coded_error * weight;

    fps.pcnt_inter  = 0.0;
    fps.pcnt_motion = 0.0;
    fps.MVr        = 0.0;
    fps.mvr_abs     = 0.0;
    fps.MVc        = 0.0;
    fps.mvc_abs     = 0.0;
    fps.MVrv       = 0.0;
    fps.MVcv       = 0.0;
    fps.mv_in_out_count  = 0.0;
    fps.new_mv_count = 0.0;
    fps.count      = 1.0;

    fps.pcnt_inter   = 1.0 * (double)intercount / cm->MBs;
    fps.pcnt_second_ref = 1.0 * (double)second_ref_count / cm->MBs;
    fps.pcnt_neutral = 1.0 * (double)neutral_count / cm->MBs;

    if (mvcount > 0) {
      fps.MVr = (double)sum_mvr / (double)mvcount;
      fps.mvr_abs = (double)sum_mvr_abs / (double)mvcount;
      fps.MVc = (double)sum_mvc / (double)mvcount;
      fps.mvc_abs = (double)sum_mvc_abs / (double)mvcount;
      fps.MVrv = ((double)sum_mvrs - (fps.MVr * fps.MVr / (double)mvcount)) / (double)mvcount;
      fps.MVcv = ((double)sum_mvcs - (fps.MVc * fps.MVc / (double)mvcount)) / (double)mvcount;
      fps.mv_in_out_count = (double)sum_in_vectors / (double)(mvcount * 2);
      fps.new_mv_count = new_mv_count;

      fps.pcnt_motion = 1.0 * (double)mvcount / cpi->common.MBs;
Paul Wilkins's avatar
Paul Wilkins committed
735
    }
John Koleszar's avatar
John Koleszar committed
736

John Koleszar's avatar
John Koleszar committed
737
738
    // TODO:  handle the case when duration is set to 0, or something less
    // than the full time between subsequent cpi->source_time_stamp s  .
739
740
    fps.duration = (double)(cpi->source->ts_end
                            - cpi->source->ts_start);
John Koleszar's avatar
John Koleszar committed
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756

    // don't want to do output stats with a stack variable!
    memcpy(cpi->twopass.this_frame_stats,
           &fps,
           sizeof(FIRSTPASS_STATS));
    output_stats(cpi, cpi->output_pkt_list, cpi->twopass.this_frame_stats);
    accumulate_stats(cpi->twopass.total_stats, &fps);
  }

  // Copy the previous Last Frame back into gf and and arf buffers if
  // the prediction is good enough... but also dont allow it to lag too far
  if ((cpi->twopass.sr_update_lag > 3) ||
      ((cm->current_video_frame > 0) &&
       (cpi->twopass.this_frame_stats->pcnt_inter > 0.20) &&
       ((cpi->twopass.this_frame_stats->intra_error /
         cpi->twopass.this_frame_stats->coded_error) > 2.0))) {
John Koleszar's avatar
John Koleszar committed
757
    vp8_yv12_copy_frame(lst_yv12, gld_yv12);
John Koleszar's avatar
John Koleszar committed
758
759
760
    cpi->twopass.sr_update_lag = 1;
  } else
    cpi->twopass.sr_update_lag++;
John Koleszar's avatar
John Koleszar committed
761

John Koleszar's avatar
John Koleszar committed
762
  // swap frame pointers so last frame refers to the frame we just compressed
763
  vp9_swap_yv12_buffer(lst_yv12, new_yv12);
John Koleszar's avatar
John Koleszar committed
764
  vp8_yv12_extend_frame_borders(lst_yv12);
John Koleszar's avatar
John Koleszar committed
765

John Koleszar's avatar
John Koleszar committed
766
767
  // Special case for the first frame. Copy into the GF buffer as a second reference.
  if (cm->current_video_frame == 0) {
John Koleszar's avatar
John Koleszar committed
768
    vp8_yv12_copy_frame(lst_yv12, gld_yv12);
John Koleszar's avatar
John Koleszar committed
769
  }
John Koleszar's avatar
John Koleszar committed
770
771


John Koleszar's avatar
John Koleszar committed
772
773
774
775
776
  // use this to see what the first pass reconstruction looks like
  if (0) {
    char filename[512];
    FILE *recon_file;
    sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
John Koleszar's avatar
John Koleszar committed
777

John Koleszar's avatar
John Koleszar committed
778
779
780
781
782
    if (cm->current_video_frame == 0)
      recon_file = fopen(filename, "wb");
    else
      recon_file = fopen(filename, "ab");

Frank Galligan's avatar
Frank Galligan committed
783
    (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
John Koleszar's avatar
John Koleszar committed
784
785
    fclose(recon_file);
  }
John Koleszar's avatar
John Koleszar committed
786

John Koleszar's avatar
John Koleszar committed
787
  cm->current_video_frame++;
John Koleszar's avatar
John Koleszar committed
788
789
790

}

791
792
793
794
795
796
// Estimate a cost per mb attributable to overheads such as the coding of
// modes and motion vectors.
// Currently simplistic in its assumptions for testing.
//


797
static double bitcost(double prob) {
John Koleszar's avatar
John Koleszar committed
798
  return -(log(prob) / log(2.0));
799
}
800

801
static long long estimate_modemvcost(VP9_COMP *cpi,
John Koleszar's avatar
John Koleszar committed
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
                                     FIRSTPASS_STATS *fpstats) {
  int mv_cost;
  int mode_cost;

  double av_pct_inter = fpstats->pcnt_inter / fpstats->count;
  double av_pct_motion = fpstats->pcnt_motion / fpstats->count;
  double av_intra = (1.0 - av_pct_inter);

  double zz_cost;
  double motion_cost;
  double intra_cost;

  zz_cost = bitcost(av_pct_inter - av_pct_motion);
  motion_cost = bitcost(av_pct_motion);
  intra_cost = bitcost(av_intra);

  // Estimate of extra bits per mv overhead for mbs
819
  // << 9 is the normalization to the (bits * 512) used in vp9_bits_per_mb
John Koleszar's avatar
John Koleszar committed
820
821
822
  mv_cost = ((int)(fpstats->new_mv_count / fpstats->count) * 8) << 9;

  // Crude estimate of overhead cost from modes
823
  // << 9 is the normalization to (bits * 512) used in vp9_bits_per_mb
John Koleszar's avatar
John Koleszar committed
824
825
826
827
828
829
830
831
  mode_cost =
    (int)((((av_pct_inter - av_pct_motion) * zz_cost) +
           (av_pct_motion * motion_cost) +
           (av_intra * intra_cost)) * cpi->common.MBs) << 9;

  // return mv_cost + mode_cost;
  // TODO PGW Fix overhead costs for extended Q range
  return 0;
832
833
}

John Koleszar's avatar
John Koleszar committed
834
835
836
837
838
839
840
841
static double calc_correction_factor(double err_per_mb,
                                     double err_divisor,
                                     double pt_low,
                                     double pt_high,
                                     int Q) {
  double power_term;
  double error_term = err_per_mb / err_divisor;
  double correction_factor;
842

John Koleszar's avatar
John Koleszar committed
843
  // Adjustment based on actual quantizer to power term.
844
  power_term = (vp9_convert_qindex_to_q(Q) * 0.01) + pt_low;
John Koleszar's avatar
John Koleszar committed
845
  power_term = (power_term > pt_high) ? pt_high : power_term;
846

John Koleszar's avatar
John Koleszar committed
847
848
  // Adjustments to error term
  // TBD
849

John Koleszar's avatar
John Koleszar committed
850
851
  // Calculate correction factor
  correction_factor = pow(error_term, power_term);
852

John Koleszar's avatar
John Koleszar committed
853
854
855
856
  // Clip range
  correction_factor =
    (correction_factor < 0.05)
    ? 0.05 : (correction_factor > 2.0) ? 2.0 : correction_factor;
Paul Wilkins's avatar
Paul Wilkins committed
857

John Koleszar's avatar
John Koleszar committed
858
  return correction_factor;
859
860
}

Paul Wilkins's avatar
Paul Wilkins committed
861
862
863
864
// Given a current maxQ value sets a range for future values.
// PGW TODO..
// This code removes direct dependency on QIndex to determin the range
// (now uses the actual quantizer) but has not been tuned.
865
static void adjust_maxq_qrange(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
866
867
868
869
870
871
872
873
  int i;
  double q;

  // Set the max corresponding to cpi->avg_q * 2.0
  q = cpi->avg_q * 2.0;
  cpi->twopass.maxq_max_limit = cpi->worst_quality;
  for (i = cpi->best_quality; i <= cpi->worst_quality; i++) {
    cpi->twopass.maxq_max_limit = i;
874
    if (vp9_convert_qindex_to_q(i) >= q)
John Koleszar's avatar
John Koleszar committed
875
876
877
878
879
880
881
882
      break;
  }

  // Set the min corresponding to cpi->avg_q * 0.5
  q = cpi->avg_q * 0.5;
  cpi->twopass.maxq_min_limit = cpi->best_quality;
  for (i = cpi->worst_quality; i >= cpi->best_quality; i--) {
    cpi->twopass.maxq_min_limit = i;
883
    if (vp9_convert_qindex_to_q(i) <= q)
John Koleszar's avatar
John Koleszar committed
884
885
      break;
  }
Paul Wilkins's avatar
Paul Wilkins committed
886
}
Paul Wilkins's avatar
Paul Wilkins committed
887

888
static int estimate_max_q(VP9_COMP *cpi,
John Koleszar's avatar
John Koleszar committed
889
                          FIRSTPASS_STATS *fpstats,
890
                          int section_target_bandwitdh,
John Koleszar's avatar
John Koleszar committed
891
892
893
894
895
896
897
898
899
900
901
                          int overhead_bits) {
  int Q;
  int num_mbs = cpi->common.MBs;
  int target_norm_bits_per_mb;

  double section_err = (fpstats->coded_error / fpstats->count);
  double sr_err_diff;
  double sr_correction;
  double err_per_mb = section_err / num_mbs;
  double err_correction_factor;
  double speed_correction = 1.0;
902
  double overhead_bits_per_mb;
John Koleszar's avatar
John Koleszar committed
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976

  if (section_target_bandwitdh <= 0)
    return cpi->twopass.maxq_max_limit;          // Highest value allowed

  target_norm_bits_per_mb =
    (section_target_bandwitdh < (1 << 20))
    ? (512 * section_target_bandwitdh) / num_mbs
    : 512 * (section_target_bandwitdh / num_mbs);

  // Look at the drop in prediction quality between the last frame
  // and the GF buffer (which contained an older frame).
  sr_err_diff =
    (fpstats->sr_coded_error - fpstats->coded_error) /
    (fpstats->count * cpi->common.MBs);
  sr_correction = (sr_err_diff / 32.0);
  sr_correction = pow(sr_correction, 0.25);
  if (sr_correction < 0.75)
    sr_correction = 0.75;
  else if (sr_correction > 1.25)
    sr_correction = 1.25;

  // Calculate a corrective factor based on a rolling ratio of bits spent
  // vs target bits
  if ((cpi->rolling_target_bits > 0) &&
      (cpi->active_worst_quality < cpi->worst_quality)) {
    double rolling_ratio;

    rolling_ratio = (double)cpi->rolling_actual_bits /
                    (double)cpi->rolling_target_bits;

    if (rolling_ratio < 0.95)
      cpi->twopass.est_max_qcorrection_factor -= 0.005;
    else if (rolling_ratio > 1.05)
      cpi->twopass.est_max_qcorrection_factor += 0.005;

    cpi->twopass.est_max_qcorrection_factor =
      (cpi->twopass.est_max_qcorrection_factor < 0.1)
      ? 0.1
      : (cpi->twopass.est_max_qcorrection_factor > 10.0)
      ? 10.0 : cpi->twopass.est_max_qcorrection_factor;
  }

  // Corrections for higher compression speed settings
  // (reduced compression expected)
  if (cpi->compressor_speed == 1) {
    if (cpi->oxcf.cpu_used <= 5)
      speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
    else
      speed_correction = 1.25;
  }

  // Estimate of overhead bits per mb
  // Correction to overhead bits for min allowed Q.
  // PGW TODO.. This code is broken for the extended Q range
  //            for now overhead set to 0.
  overhead_bits_per_mb = overhead_bits / num_mbs;
  overhead_bits_per_mb *= pow(0.98, (double)cpi->twopass.maxq_min_limit);

  // Try and pick a max Q that will be high enough to encode the
  // content at the given rate.
  for (Q = cpi->twopass.maxq_min_limit; Q < cpi->twopass.maxq_max_limit; Q++) {
    int bits_per_mb_at_this_q;

    err_correction_factor =
      calc_correction_factor(err_per_mb, ERR_DIVISOR, 0.4, 0.90, Q) *
      sr_correction * speed_correction *
      cpi->twopass.est_max_qcorrection_factor;

    if (err_correction_factor < 0.05)
      err_correction_factor = 0.05;
    else if (err_correction_factor > 5.0)
      err_correction_factor = 5.0;

    bits_per_mb_at_this_q =
977
      vp9_bits_per_mb(INTER_FRAME, Q) + (int)overhead_bits_per_mb;
John Koleszar's avatar
John Koleszar committed
978
979
980
981
982
983
984

    bits_per_mb_at_this_q = (int)(.5 + err_correction_factor *
                                  (double)bits_per_mb_at_this_q);

    // Mode and motion overhead
    // As Q rises in real encode loop rd code will force overhead down
    // We make a crude adjustment for this here as *.98 per Q step.
985
    // PGW TODO.. This code is broken for the extended Q range
Paul Wilkins's avatar
Paul Wilkins committed
986
    //            for now overhead set to 0.
John Koleszar's avatar
John Koleszar committed
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
    // overhead_bits_per_mb = (int)((double)overhead_bits_per_mb * 0.98);

    if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
      break;
  }

  // Restriction on active max q for constrained quality mode.
  if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
      (Q < cpi->cq_target_quality)) {
    Q = cpi->cq_target_quality;
  }

  // Adjust maxq_min_limit and maxq_max_limit limits based on
  // averaga q observed in clip for non kf/gf/arf frames
  // Give average a chance to settle though.
  // PGW TODO.. This code is broken for the extended Q range
  if ((cpi->ni_frames >
1004
       ((int)cpi->twopass.total_stats->count >> 8)) &&
John Koleszar's avatar
John Koleszar committed
1005
1006
1007
1008
1009
      (cpi->ni_frames > 150)) {
    adjust_maxq_qrange(cpi);
  }

  return Q;
John Koleszar's avatar
John Koleszar committed
1010
}
1011
1012
1013

// For cq mode estimate a cq level that matches the observed
// complexity and data rate.
1014
static int estimate_cq(VP9_COMP *cpi,
John Koleszar's avatar
John Koleszar committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
                       FIRSTPASS_STATS *fpstats,
                       int section_target_bandwitdh,
                       int overhead_bits) {
  int Q;
  int num_mbs = cpi->common.MBs;
  int target_norm_bits_per_mb;

  double section_err = (fpstats->coded_error / fpstats->count);
  double err_per_mb = section_err / num_mbs;
  double err_correction_factor;
  double sr_err_diff;
  double sr_correction;
  double speed_correction = 1.0;
  double clip_iiratio;
  double clip_iifactor;
1030
  double overhead_bits_per_mb;
John Koleszar's avatar
John Koleszar committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082


  target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20))
                            ? (512 * section_target_bandwitdh) / num_mbs
                            : 512 * (section_target_bandwitdh / num_mbs);

  // Estimate of overhead bits per mb
  overhead_bits_per_mb = overhead_bits / num_mbs;

  // Corrections for higher compression speed settings
  // (reduced compression expected)
  if (cpi->compressor_speed == 1) {
    if (cpi->oxcf.cpu_used <= 5)
      speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
    else
      speed_correction = 1.25;
  }

  // Look at the drop in prediction quality between the last frame
  // and the GF buffer (which contained an older frame).
  sr_err_diff =
    (fpstats->sr_coded_error - fpstats->coded_error) /
    (fpstats->count * cpi->common.MBs);
  sr_correction = (sr_err_diff / 32.0);
  sr_correction = pow(sr_correction, 0.25);
  if (sr_correction < 0.75)
    sr_correction = 0.75;
  else if (sr_correction > 1.25)
    sr_correction = 1.25;

  // II ratio correction factor for clip as a whole
  clip_iiratio = cpi->twopass.total_stats->intra_error /
                 DOUBLE_DIVIDE_CHECK(cpi->twopass.total_stats->coded_error);
  clip_iifactor = 1.0 - ((clip_iiratio - 10.0) * 0.025);
  if (clip_iifactor < 0.80)
    clip_iifactor = 0.80;

  // Try and pick a Q that can encode the content at the given rate.
  for (Q = 0; Q < MAXQ; Q++) {
    int bits_per_mb_at_this_q;

    // Error per MB based correction factor
    err_correction_factor =
      calc_correction_factor(err_per_mb, 100.0, 0.4, 0.90, Q) *
      sr_correction * speed_correction * clip_iifactor;

    if (err_correction_factor < 0.05)
      err_correction_factor = 0.05;
    else if (err_correction_factor > 5.0)
      err_correction_factor = 5.0;

    bits_per_mb_at_this_q =
1083
      vp9_bits_per_mb(INTER_FRAME, Q) + (int)overhead_bits_per_mb;
John Koleszar's avatar
John Koleszar committed
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093

    bits_per_mb_at_this_q = (int)(.5 + err_correction_factor *
                                  (double)bits_per_mb_at_this_q);

    // Mode and motion overhead
    // As Q rises in real encode loop rd code will force overhead down
    // We make a crude adjustment for this here as *.98 per Q step.
    // PGW TODO.. This code is broken for the extended Q range
    //            for now overhead set to 0.
    overhead_bits_per_mb = (int)((double)overhead_bits_per_mb * 0.98);
1094

John Koleszar's avatar
John Koleszar committed
1095
1096
1097
    if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
      break;
  }
1098

John Koleszar's avatar
John Koleszar committed
1099
1100
1101
1102
1103
1104
  // Clip value to range "best allowed to (worst allowed - 1)"
  Q = select_cq_level(Q);
  if (Q >= cpi->worst_quality)
    Q = cpi->worst_quality - 1;
  if (Q < cpi->best_quality)
    Q = cpi->best_quality;
1105

John Koleszar's avatar
John Koleszar committed
1106
  return Q;
1107
1108
}

Paul Wilkins's avatar
CQ Mode    
Paul Wilkins committed
1109

1110
extern void vp9_new_frame_rate(VP9_COMP *cpi, double framerate);
John Koleszar's avatar
John Koleszar committed
1111

1112
void vp9_init_second_pass(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
1113
1114
  FIRSTPASS_STATS this_frame;
  FIRSTPASS_STATS *start_pos;
John Koleszar's avatar
John Koleszar committed
1115

John Koleszar's avatar
John Koleszar committed
1116
1117
1118
  double lower_bounds_min_rate = FRAME_OVERHEAD_BITS * cpi->oxcf.frame_rate;
  double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
                                      * cpi->oxcf.two_pass_vbrmin_section / 100);
1119

John Koleszar's avatar
John Koleszar committed
1120
1121
  if (two_pass_min_rate < lower_bounds_min_rate)
    two_pass_min_rate = lower_bounds_min_rate;
John Koleszar's avatar
John Koleszar committed
1122

John Koleszar's avatar
John Koleszar committed
1123
1124
  zero_stats(cpi->twopass.total_stats);
  zero_stats(cpi->twopass.total_left_stats);
John Koleszar's avatar
John Koleszar committed
1125

John Koleszar's avatar
John Koleszar committed
1126
1127
  if (!cpi->twopass.stats_in_end)
    return;
John Koleszar's avatar
John Koleszar committed
1128

John Koleszar's avatar
John Koleszar committed
1129
1130
  *cpi->twopass.total_stats = *cpi->twopass.stats_in_end;
  *cpi->twopass.total_left_stats = *cpi->twopass.total_stats;
John Koleszar's avatar
John Koleszar committed
1131

John Koleszar's avatar
John Koleszar committed
1132
1133
1134
1135
1136
  // each frame can have a different duration, as the frame rate in the source
  // isn't guaranteed to be constant.   The frame rate prior to the first frame
  // encoded in the second pass is a guess.  However the sum duration is not.
  // Its calculated based on the actual durations of all frames from the first
  // pass.
1137
1138
1139
  vp9_new_frame_rate(cpi,
                     10000000.0 * cpi->twopass.total_stats->count /
                     cpi->twopass.total_stats->duration);
John Koleszar's avatar
John Koleszar committed
1140

John Koleszar's avatar
John Koleszar committed
1141
  cpi->output_frame_rate = cpi->oxcf.frame_rate;
1142
1143
1144
1145
  cpi->twopass.bits_left = (int64_t)(cpi->twopass.total_stats->duration *
                                     cpi->oxcf.target_bandwidth / 10000000.0);
  cpi->twopass.bits_left -= (int64_t)(cpi->twopass.total_stats->duration *
                                      two_pass_min_rate / 10000000.0);
Paul Wilkins's avatar
Paul Wilkins committed
1146

John Koleszar's avatar
John Koleszar committed
1147
1148
1149
1150
1151
1152
  // Calculate a minimum intra value to be used in determining the IIratio
  // scores used in the second pass. We have this minimum to make sure
  // that clips that are static but "low complexity" in the intra domain
  // are still boosted appropriately for KF/GF/ARF
  cpi->twopass.kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
  cpi->twopass.gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
John Koleszar's avatar
John Koleszar committed
1153

John Koleszar's avatar
John Koleszar committed
1154
1155
  // This variable monitors how far behind the second ref update is lagging
  cpi->twopass.sr_update_lag = 1;
John Koleszar's avatar
John Koleszar committed
1156

John Koleszar's avatar
John Koleszar committed
1157
1158
1159
1160
  // Scan the first pass file and calculate an average Intra / Inter error score ratio for the sequence
  {
    double sum_iiratio = 0.0;
    double IIRatio;
John Koleszar's avatar
John Koleszar committed
1161

John Koleszar's avatar
John Koleszar committed
1162
    start_pos = cpi->twopass.stats_in;               // Note starting "file" position
John Koleszar's avatar
John Koleszar committed
1163

John Koleszar's avatar
John Koleszar committed
1164
1165
1166
1167
    while (input_stats(cpi, &this_frame) != EOF) {
      IIRatio = this_frame.intra_error / DOUBLE_DIVIDE_CHECK(this_frame.coded_error);
      IIRatio = (IIRatio < 1.0) ? 1.0 : (IIRatio > 20.0) ? 20.0 : IIRatio;
      sum_iiratio += IIRatio;
John Koleszar's avatar
John Koleszar committed
1168
1169
    }

John Koleszar's avatar
John Koleszar committed
1170
    cpi->twopass.avg_iiratio = sum_iiratio / DOUBLE_DIVIDE_CHECK((double)cpi->twopass.total_stats->count);
John Koleszar's avatar
John Koleszar committed
1171

John Koleszar's avatar
John Koleszar committed
1172
1173
1174
    // Reset file position
    reset_fpf_position(cpi, start_pos);
  }
John Koleszar's avatar
John Koleszar committed
1175

John Koleszar's avatar
John Koleszar committed
1176
1177
1178
1179
  // Scan the first pass file and calculate a modified total error based upon the bias/power function
  // used to allocate bits
  {
    start_pos = cpi->twopass.stats_in;               // Note starting "file" position
John Koleszar's avatar
John Koleszar committed
1180

John Koleszar's avatar
John Koleszar committed
1181
1182
    cpi->twopass.modified_error_total = 0.0;
    cpi->twopass.modified_error_used = 0.0;
John Koleszar's avatar
John Koleszar committed
1183

John Koleszar's avatar
John Koleszar committed
1184
1185
    while (input_stats(cpi, &this_frame) != EOF) {
      cpi->twopass.modified_error_total += calculate_modified_err(cpi, &this_frame);
John Koleszar's avatar
John Koleszar committed
1186
    }
John Koleszar's avatar
John Koleszar committed
1187
1188
1189
1190
1191
    cpi->twopass.modified_error_left = cpi->twopass.modified_error_total;

    reset_fpf_position(cpi, start_pos);            // Reset file position

  }
John Koleszar's avatar
John Koleszar committed
1192
1193
}

1194
void vp9_end_second_pass(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
1195
1196
}

Paul Wilkins's avatar
Paul Wilkins committed
1197
// This function gives and estimate of how badly we believe
Adrian Grange's avatar
Adrian Grange committed
1198
// the prediction quality is decaying from frame to frame.
1199
static double get_prediction_decay_rate(VP9_COMP *cpi,
John Koleszar's avatar
John Koleszar committed
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
                                        FIRSTPASS_STATS *next_frame) {
  double prediction_decay_rate;
  double second_ref_decay;
  double mb_sr_err_diff;

  // Initial basis is the % mbs inter coded
  prediction_decay_rate = next_frame->pcnt_inter;

  // Look at the observed drop in prediction quality between the last frame
  // and the GF buffer (which contains an older frame).
  mb_sr_err_diff =
    (next_frame->sr_coded_error - next_frame->coded_error) /
    (cpi->common.MBs);
  second_ref_decay = 1.0 - (mb_sr_err_diff / 512.0);
  second_ref_decay = pow(second_ref_decay, 0.5);
  if (second_ref_decay < 0.85)
    second_ref_decay = 0.85;
  else if (second_ref_decay > 1.0)
    second_ref_decay = 1.0;

  if (second_ref_decay < prediction_decay_rate)
    prediction_decay_rate = second_ref_decay;

  return prediction_decay_rate;
Paul Wilkins's avatar
Paul Wilkins committed
1224
1225
}

Paul Wilkins's avatar
Paul Wilkins committed
1226
// Function to test for a condition where a complex transition is followed
1227
1228
// by a static section. For example in slide shows where there is a fade
// between slides. This is to help with more optimal kf and gf positioning.
1229
static int detect_transition_to_still(
1230
  VP9_COMP *cpi,
John Koleszar's avatar
John Koleszar committed
1231
1232
1233
1234
  int frame_interval,
  int still_interval,
  double loop_decay_rate,
  double last_decay_rate) {
John Koleszar's avatar
John Koleszar committed
1235
  int trans_to_still = FALSE;
John Koleszar's avatar
John Koleszar committed
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252

  // Break clause to detect very still sections after motion
  // For example a static image after a fade or other transition
  // instead of a clean scene cut.
  if ((frame_interval > MIN_GF_INTERVAL) &&
      (loop_decay_rate >= 0.999) &&
      (last_decay_rate < 0.9)) {
    int j;
    FIRSTPASS_STATS *position = cpi->twopass.stats_in;
    FIRSTPASS_STATS tmp_next_frame;
    double zz_inter;

    // Look ahead a few frames to see if static condition
    // persists...
    for (j = 0; j < still_interval; j++) {
      if (EOF == input_stats(cpi, &tmp_next_frame))
        break;
1253

John Koleszar's avatar
John Koleszar committed
1254
1255
1256
1257
      zz_inter =
        (tmp_next_frame.pcnt_inter - tmp_next_frame.pcnt_motion);
      if (zz_inter < 0.999)
        break;
1258
    }
John Koleszar's avatar
John Koleszar committed
1259
1260
    // Reset file position
    reset_fpf_position(cpi, position);
1261

John Koleszar's avatar
John Koleszar committed
1262
1263
1264
1265
1266
1267
    // Only if it does do we signal a transition to still
    if (j == still_interval)
      trans_to_still = TRUE;
  }

  return trans_to_still;
1268
}
Paul Wilkins's avatar
Paul Wilkins committed
1269

1270
1271
1272
// This function detects a flash through the high relative pcnt_second_ref
// score in the frame following a flash frame. The offset passed in should
// reflect this
John Koleszar's avatar
John Koleszar committed
1273
static int detect_flash(VP9_COMP *cpi, int offset) {
John Koleszar's avatar
John Koleszar committed
1274
1275
  FIRSTPASS_STATS next_frame;

John Koleszar's avatar
John Koleszar committed
1276
  int flash_detected = FALSE;
John Koleszar's avatar
John Koleszar committed
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288

  // Read the frame data.
  // The return is FALSE (no flash detected) if not a valid frame
  if (read_frame_stats(cpi, &next_frame, offset) != EOF) {
    // What we are looking for here is a situation where there is a
    // brief break in prediction (such as a flash) but subsequent frames
    // are reasonably well predicted by an earlier (pre flash) frame.
    // The recovery after a flash is indicated by a high pcnt_second_ref
    // comapred to pcnt_inter.
    if ((next_frame.pcnt_second_ref > next_frame.pcnt_inter) &&
        (next_frame.pcnt_second_ref >= 0.5)) {
      flash_detected = TRUE;
1289
    }
John Koleszar's avatar
John Koleszar committed
1290
  }
1291

John Koleszar's avatar
John Koleszar committed
1292