vp9_firstpass.c 102 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
#include <limits.h>
12
#include <math.h>
13
#include <stdio.h>
14

Johann's avatar
Johann committed
15
#include "./vpx_dsp_rtcd.h"
16 17 18
#include "./vpx_scale_rtcd.h"

#include "vpx_mem/vpx_mem.h"
19
#include "vpx_ports/mem.h"
20 21 22 23 24
#include "vpx_scale/vpx_scale.h"
#include "vpx_scale/yv12config.h"

#include "vp9/common/vp9_entropymv.h"
#include "vp9/common/vp9_quant_common.h"
25
#include "vp9/common/vp9_reconinter.h"  // vp9_setup_dst_planes()
26
#include "vp9/common/vp9_systemdependent.h"
Marco Paniconi's avatar
Marco Paniconi committed
27
#include "vp9/encoder/vp9_aq_variance.h"
28
#include "vp9/encoder/vp9_block.h"
29 30
#include "vp9/encoder/vp9_encodeframe.h"
#include "vp9/encoder/vp9_encodemb.h"
31
#include "vp9/encoder/vp9_encodemv.h"
Dmitry Kovalev's avatar
Dmitry Kovalev committed
32
#include "vp9/encoder/vp9_encoder.h"
33 34 35
#include "vp9/encoder/vp9_extend.h"
#include "vp9/encoder/vp9_firstpass.h"
#include "vp9/encoder/vp9_mcomp.h"
36
#include "vp9/encoder/vp9_quantize.h"
37
#include "vp9/encoder/vp9_rd.h"
Johann's avatar
Johann committed
38
#include "vpx_dsp/variance.h"
John Koleszar's avatar
John Koleszar committed
39

40 41 42
#define OUTPUT_FPF          0
#define ARF_STATS_OUTPUT    0

43
#define GROUP_ADAPTIVE_MAXQ 1
44

Paul Wilkins's avatar
Paul Wilkins committed
45
#define BOOST_BREAKOUT      12.5
46
#define BOOST_FACTOR        12.5
Paul Wilkins's avatar
Paul Wilkins committed
47
#define ERR_DIVISOR         128.0
Paul Wilkins's avatar
Paul Wilkins committed
48 49
#define FACTOR_PT_LOW       0.70
#define FACTOR_PT_HIGH      0.90
50 51 52 53
#define FIRST_PASS_Q        10.0
#define GF_MAX_BOOST        96.0
#define INTRA_MODE_PENALTY  1024
#define KF_MAX_BOOST        128.0
Paul Wilkins's avatar
Paul Wilkins committed
54
#define MIN_ARF_GF_BOOST    240
55 56 57 58
#define MIN_DECAY_FACTOR    0.01
#define MIN_KF_BOOST        300
#define NEW_MV_MODE_PENALTY 32
#define SVC_FACTOR_PT_LOW   0.45
59
#define DARK_THRESH         64
60
#define DEFAULT_GRP_WEIGHT  1.0
61 62
#define RC_FACTOR_MIN       0.75
#define RC_FACTOR_MAX       1.75
Paul Wilkins's avatar
CQ Mode  
Paul Wilkins committed
63

64 65 66 67 68

#define NCOUNT_INTRA_THRESH 8192
#define NCOUNT_INTRA_FACTOR 3
#define NCOUNT_FRAME_II_THRESH 5.0

69
#define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x) - 0.000001 : (x) + 0.000001)
John Koleszar's avatar
John Koleszar committed
70

71 72 73
#if ARF_STATS_OUTPUT
unsigned int arf_count = 0;
#endif
74

75 76
// Resets the first pass file to the given position using a relative seek from
// the current position.
Paul Wilkins's avatar
Paul Wilkins committed
77
static void reset_fpf_position(TWO_PASS *p,
78
                               const FIRSTPASS_STATS *position) {
79
  p->stats_in = position;
John Koleszar's avatar
John Koleszar committed
80 81
}

Adrian Grange's avatar
Adrian Grange committed
82
// Read frame stats at an offset from the current position.
83 84 85 86
static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
  if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
      (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
    return NULL;
John Koleszar's avatar
John Koleszar committed
87 88
  }

89
  return &p->stats_in[offset];
90 91
}

Paul Wilkins's avatar
Paul Wilkins committed
92
static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
93
  if (p->stats_in >= p->stats_in_end)
John Koleszar's avatar
John Koleszar committed
94
    return EOF;
95

96 97
  *fps = *p->stats_in;
  ++p->stats_in;
John Koleszar's avatar
John Koleszar committed
98
  return 1;
99 100
}

101 102
static void output_stats(FIRSTPASS_STATS *stats,
                         struct vpx_codec_pkt_list *pktlist) {
John Koleszar's avatar
John Koleszar committed
103 104 105 106 107
  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);
108 109 110

// TEMP debug code
#if OUTPUT_FPF
John Koleszar's avatar
John Koleszar committed
111 112 113 114
  {
    FILE *fpfile;
    fpfile = fopen("firstpass.stt", "a");

115
    fprintf(fpfile, "%12.0lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf %12.4lf"
116 117
            "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
            "%12.4lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf\n",
John Koleszar's avatar
John Koleszar committed
118
            stats->frame,
119
            stats->weight,
John Koleszar's avatar
John Koleszar committed
120 121 122 123 124 125 126
            stats->intra_error,
            stats->coded_error,
            stats->sr_coded_error,
            stats->pcnt_inter,
            stats->pcnt_motion,
            stats->pcnt_second_ref,
            stats->pcnt_neutral,
127 128
            stats->intra_skip_pct,
            stats->inactive_zone_rows,
129
            stats->inactive_zone_cols,
John Koleszar's avatar
John Koleszar committed
130 131 132 133 134 135 136 137 138 139 140 141
            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);
  }
142 143 144
#endif
}

145 146 147 148 149 150
#if CONFIG_FP_MB_STATS
static void output_fpmb_stats(uint8_t *this_frame_mb_stats, VP9_COMMON *cm,
                         struct vpx_codec_pkt_list *pktlist) {
  struct vpx_codec_cx_pkt pkt;
  pkt.kind = VPX_CODEC_FPMB_STATS_PKT;
  pkt.data.firstpass_mb_stats.buf = this_frame_mb_stats;
151
  pkt.data.firstpass_mb_stats.sz = cm->initial_mbs * sizeof(uint8_t);
152 153 154 155
  vpx_codec_pkt_list_add(pktlist, &pkt);
}
#endif

John Koleszar's avatar
John Koleszar committed
156
static void zero_stats(FIRSTPASS_STATS *section) {
157 158
  section->frame = 0.0;
  section->weight = 0.0;
John Koleszar's avatar
John Koleszar committed
159 160 161 162 163 164 165
  section->intra_error = 0.0;
  section->coded_error = 0.0;
  section->sr_coded_error = 0.0;
  section->pcnt_inter  = 0.0;
  section->pcnt_motion  = 0.0;
  section->pcnt_second_ref = 0.0;
  section->pcnt_neutral = 0.0;
166 167
  section->intra_skip_pct = 0.0;
  section->inactive_zone_rows = 0.0;
168
  section->inactive_zone_cols = 0.0;
169
  section->MVr = 0.0;
John Koleszar's avatar
John Koleszar committed
170 171 172 173 174 175 176 177 178
  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;
179
  section->spatial_layer_id = 0;
180 181
}

Dmitry Kovalev's avatar
Dmitry Kovalev committed
182 183
static void accumulate_stats(FIRSTPASS_STATS *section,
                             const FIRSTPASS_STATS *frame) {
John Koleszar's avatar
John Koleszar committed
184
  section->frame += frame->frame;
185
  section->weight += frame->weight;
186
  section->spatial_layer_id = frame->spatial_layer_id;
John Koleszar's avatar
John Koleszar committed
187 188 189 190 191 192 193
  section->intra_error += frame->intra_error;
  section->coded_error += frame->coded_error;
  section->sr_coded_error += frame->sr_coded_error;
  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;
194 195
  section->intra_skip_pct += frame->intra_skip_pct;
  section->inactive_zone_rows += frame->inactive_zone_rows;
196
  section->inactive_zone_cols += frame->inactive_zone_cols;
197
  section->MVr += frame->MVr;
John Koleszar's avatar
John Koleszar committed
198 199 200 201 202 203 204 205 206
  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;
207 208
}

Dmitry Kovalev's avatar
Dmitry Kovalev committed
209 210
static void subtract_stats(FIRSTPASS_STATS *section,
                           const FIRSTPASS_STATS *frame) {
John Koleszar's avatar
John Koleszar committed
211
  section->frame -= frame->frame;
212
  section->weight -= frame->weight;
John Koleszar's avatar
John Koleszar committed
213 214 215 216 217 218 219
  section->intra_error -= frame->intra_error;
  section->coded_error -= frame->coded_error;
  section->sr_coded_error -= frame->sr_coded_error;
  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;
220 221
  section->intra_skip_pct -= frame->intra_skip_pct;
  section->inactive_zone_rows -= frame->inactive_zone_rows;
222
  section->inactive_zone_cols -= frame->inactive_zone_cols;
223
  section->MVr -= frame->MVr;
John Koleszar's avatar
John Koleszar committed
224 225 226 227 228 229 230 231 232
  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;
233 234
}

235 236 237 238 239
// Calculate an active area of the image that discounts formatting
// bars and partially discounts other 0 energy areas.
#define MIN_ACTIVE_AREA 0.5
#define MAX_ACTIVE_AREA 1.0
static double calculate_active_area(const VP9_COMP *cpi,
Jingning Han's avatar
Jingning Han committed
240
                                    const FIRSTPASS_STATS *this_frame) {
241 242 243 244 245 246 247
  double active_pct;

  active_pct = 1.0 -
    ((this_frame->intra_skip_pct / 2) +
     ((this_frame->inactive_zone_rows * 2) / (double)cpi->common.mb_rows));
  return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
}
248

249 250
// Calculate a modified Error used in distributing bits between easier and
// harder frames.
251 252 253
#define ACT_AREA_CORRECTION 0.5
static double calculate_modified_err(const VP9_COMP *cpi,
                                     const TWO_PASS *twopass,
254
                                     const VP9EncoderConfig *oxcf,
Dmitry Kovalev's avatar
Dmitry Kovalev committed
255
                                     const FIRSTPASS_STATS *this_frame) {
256
  const FIRSTPASS_STATS *const stats = &twopass->total_stats;
257 258
  const double av_weight = stats->weight / stats->count;
  const double av_err = (stats->coded_error * av_weight) / stats->count;
259
  double modified_error =
260 261
    av_err * pow(this_frame->coded_error * this_frame->weight /
                 DOUBLE_DIVIDE_CHECK(av_err), oxcf->two_pass_vbrbias / 100.0);
262 263 264 265 266 267 268 269 270

  // Correction for active area. Frames with a reduced active area
  // (eg due to formatting bars) have a higher error per mb for the
  // remaining active MBs. The correction here assumes that coding
  // 0.5N blocks of complexity 2X is a little easier than coding N
  // blocks of complexity X.
  modified_error *=
    pow(calculate_active_area(cpi, this_frame), ACT_AREA_CORRECTION);

271 272
  return fclamp(modified_error,
                twopass->modified_error_min, twopass->modified_error_max);
John Koleszar's avatar
John Koleszar committed
273 274
}

275
// This function returns the maximum target rate per frame.
276 277
static int frame_max_bits(const RATE_CONTROL *rc,
                          const VP9EncoderConfig *oxcf) {
278
  int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
Dmitry Kovalev's avatar
Dmitry Kovalev committed
279
                          (int64_t)oxcf->two_pass_vbrmax_section) / 100;
Yaowu Xu's avatar
Yaowu Xu committed
280
  if (max_bits < 0)
Paul Wilkins's avatar
Paul Wilkins committed
281
    max_bits = 0;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
282 283
  else if (max_bits > rc->max_frame_bandwidth)
    max_bits = rc->max_frame_bandwidth;
Paul Wilkins's avatar
Paul Wilkins committed
284

Yaowu Xu's avatar
Yaowu Xu committed
285
  return (int)max_bits;
John Koleszar's avatar
John Koleszar committed
286 287
}

288
void vp9_init_first_pass(VP9_COMP *cpi) {
289
  zero_stats(&cpi->twopass.total_stats);
John Koleszar's avatar
John Koleszar committed
290 291
}

292
void vp9_end_first_pass(VP9_COMP *cpi) {
293
  if (is_two_pass_svc(cpi)) {
294 295 296 297 298 299 300 301
    int i;
    for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
      output_stats(&cpi->svc.layer_context[i].twopass.total_stats,
                   cpi->output_pkt_list);
    }
  } else {
    output_stats(&cpi->twopass.total_stats, cpi->output_pkt_list);
  }
302
}
John Koleszar's avatar
John Koleszar committed
303

Johann's avatar
Johann committed
304
static vpx_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
305 306
  switch (bsize) {
    case BLOCK_8X8:
Johann's avatar
Johann committed
307
      return vpx_mse8x8;
308
    case BLOCK_16X8:
Johann's avatar
Johann committed
309
      return vpx_mse16x8;
310
    case BLOCK_8X16:
Johann's avatar
Johann committed
311
      return vpx_mse8x16;
312
    default:
Johann's avatar
Johann committed
313
      return vpx_mse16x16;
314 315 316
  }
}

317 318 319
static unsigned int get_prediction_error(BLOCK_SIZE bsize,
                                         const struct buf_2d *src,
                                         const struct buf_2d *ref) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
320
  unsigned int sse;
Johann's avatar
Johann committed
321
  const vpx_variance_fn_t fn = get_block_variance_fn(bsize);
322
  fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
323
  return sse;
324 325
}

326
#if CONFIG_VP9_HIGHBITDEPTH
Johann's avatar
Johann committed
327
static vpx_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
328 329 330 331 332
                                                      int bd) {
  switch (bd) {
    default:
      switch (bsize) {
        case BLOCK_8X8:
Johann's avatar
Johann committed
333
          return vpx_highbd_8_mse8x8;
334
        case BLOCK_16X8:
Johann's avatar
Johann committed
335
          return vpx_highbd_8_mse16x8;
336
        case BLOCK_8X16:
Johann's avatar
Johann committed
337
          return vpx_highbd_8_mse8x16;
338
        default:
Johann's avatar
Johann committed
339
          return vpx_highbd_8_mse16x16;
340 341 342 343 344
      }
      break;
    case 10:
      switch (bsize) {
        case BLOCK_8X8:
Johann's avatar
Johann committed
345
          return vpx_highbd_10_mse8x8;
346
        case BLOCK_16X8:
Johann's avatar
Johann committed
347
          return vpx_highbd_10_mse16x8;
348
        case BLOCK_8X16:
Johann's avatar
Johann committed
349
          return vpx_highbd_10_mse8x16;
350
        default:
Johann's avatar
Johann committed
351
          return vpx_highbd_10_mse16x16;
352 353 354 355 356
      }
      break;
    case 12:
      switch (bsize) {
        case BLOCK_8X8:
Johann's avatar
Johann committed
357
          return vpx_highbd_12_mse8x8;
358
        case BLOCK_16X8:
Johann's avatar
Johann committed
359
          return vpx_highbd_12_mse16x8;
360
        case BLOCK_8X16:
Johann's avatar
Johann committed
361
          return vpx_highbd_12_mse8x16;
362
        default:
Johann's avatar
Johann committed
363
          return vpx_highbd_12_mse16x16;
364 365 366 367 368 369 370 371 372 373
      }
      break;
  }
}

static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
                                                const struct buf_2d *src,
                                                const struct buf_2d *ref,
                                                int bd) {
  unsigned int sse;
Johann's avatar
Johann committed
374
  const vpx_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
375 376 377 378 379
  fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
  return sse;
}
#endif  // CONFIG_VP9_HIGHBITDEPTH

380 381
// Refine the motion search range according to the frame dimension
// for first pass test.
382
static int get_search_range(const VP9_COMP *cpi) {
383
  int sr = 0;
384
  const int dim = MIN(cpi->initial_width, cpi->initial_height);
385 386 387 388 389 390

  while ((dim << sr) < MAX_FULL_PEL_VAL)
    ++sr;
  return sr;
}

391
static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
392
                                     const MV *ref_mv, MV *best_mv,
393
                                     int *best_motion_err) {
John Koleszar's avatar
John Koleszar committed
394
  MACROBLOCKD *const xd = &x->e_mbd;
395
  MV tmp_mv = {0, 0};
396
  MV ref_mv_full = {ref_mv->row >> 3, ref_mv->col >> 3};
397
  int num00, tmp_err, n;
398
  const BLOCK_SIZE bsize = xd->mi[0]->mbmi.sb_type;
399
  vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
400
  const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
401

402 403
  int step_param = 3;
  int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
404
  const int sr = get_search_range(cpi);
405
  step_param += sr;
406 407
  further_steps -= sr;

Adrian Grange's avatar
Adrian Grange committed
408
  // Override the default variance function to use MSE.
409
  v_fn_ptr.vf = get_block_variance_fn(bsize);
410 411 412 413 414
#if CONFIG_VP9_HIGHBITDEPTH
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
    v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, xd->bd);
  }
#endif  // CONFIG_VP9_HIGHBITDEPTH
John Koleszar's avatar
John Koleszar committed
415

Adrian Grange's avatar
Adrian Grange committed
416
  // Center the initial step/diamond search on best mv.
417
  tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
418
                                    step_param,
419
                                    x->sadperbit16, &num00, &v_fn_ptr, ref_mv);
Deb Mukherjee's avatar
Deb Mukherjee committed
420 421
  if (tmp_err < INT_MAX)
    tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
John Koleszar's avatar
John Koleszar committed
422 423 424 425 426
  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;
427
    *best_mv = tmp_mv;
John Koleszar's avatar
John Koleszar committed
428 429
  }

Adrian Grange's avatar
Adrian Grange committed
430
  // Carry out further step/diamond searches as necessary.
John Koleszar's avatar
John Koleszar committed
431 432 433 434
  n = num00;
  num00 = 0;

  while (n < further_steps) {
Adrian Grange's avatar
Adrian Grange committed
435
    ++n;
John Koleszar's avatar
John Koleszar committed
436

437
    if (num00) {
Adrian Grange's avatar
Adrian Grange committed
438
      --num00;
439
    } else {
440
      tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
John Koleszar's avatar
John Koleszar committed
441
                                        step_param + n, x->sadperbit16,
442
                                        &num00, &v_fn_ptr, ref_mv);
Deb Mukherjee's avatar
Deb Mukherjee committed
443 444
      if (tmp_err < INT_MAX)
        tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
John Koleszar's avatar
John Koleszar committed
445
      if (tmp_err < INT_MAX - new_mv_mode_penalty)
John Koleszar's avatar
John Koleszar committed
446 447
        tmp_err += new_mv_mode_penalty;

John Koleszar's avatar
John Koleszar committed
448
      if (tmp_err < *best_motion_err) {
John Koleszar's avatar
John Koleszar committed
449
        *best_motion_err = tmp_err;
450
        *best_mv = tmp_mv;
John Koleszar's avatar
John Koleszar committed
451
      }
John Koleszar's avatar
John Koleszar committed
452
    }
John Koleszar's avatar
John Koleszar committed
453
  }
John Koleszar's avatar
John Koleszar committed
454 455
}

456 457 458 459 460 461 462 463 464 465
static BLOCK_SIZE get_bsize(const VP9_COMMON *cm, int mb_row, int mb_col) {
  if (2 * mb_col + 1 < cm->mi_cols) {
    return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_16X16
                                        : BLOCK_16X8;
  } else {
    return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_8X16
                                        : BLOCK_8X8;
  }
}

466
static int find_fp_qindex(vpx_bit_depth_t bit_depth) {
467 468 469
  int i;

  for (i = 0; i < QINDEX_RANGE; ++i)
470
    if (vp9_convert_qindex_to_q(i, bit_depth) >= FIRST_PASS_Q)
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
      break;

  if (i == QINDEX_RANGE)
    i--;

  return i;
}

static void set_first_pass_params(VP9_COMP *cpi) {
  VP9_COMMON *const cm = &cpi->common;
  if (!cpi->refresh_alt_ref_frame &&
      (cm->current_video_frame == 0 ||
       (cpi->frame_flags & FRAMEFLAGS_KEY))) {
    cm->frame_type = KEY_FRAME;
  } else {
    cm->frame_type = INTER_FRAME;
  }
  // Do not use periodic key frames.
  cpi->rc.frames_to_key = INT_MAX;
}

492 493
#define UL_INTRA_THRESH 50
#define INVALID_ROW -1
494
void vp9_first_pass(VP9_COMP *cpi, const struct lookahead_entry *source) {
John Koleszar's avatar
John Koleszar committed
495
  int mb_row, mb_col;
496
  MACROBLOCK *const x = &cpi->td.mb;
497
  VP9_COMMON *const cm = &cpi->common;
John Koleszar's avatar
John Koleszar committed
498
  MACROBLOCKD *const xd = &x->e_mbd;
James Zern's avatar
James Zern committed
499
  TileInfo tile;
500 501
  struct macroblock_plane *const p = x->plane;
  struct macroblockd_plane *const pd = xd->plane;
502
  const PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
503
  int i;
John Koleszar's avatar
John Koleszar committed
504 505 506 507 508 509 510 511

  int recon_yoffset, recon_uvoffset;
  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;
512
  int64_t sum_mvrs = 0, sum_mvcs = 0;
John Koleszar's avatar
John Koleszar committed
513 514 515
  int mvcount = 0;
  int intercount = 0;
  int second_ref_count = 0;
516
  const int intrapenalty = INTRA_MODE_PENALTY;
517
  double neutral_count;
518
  int intra_skip_count = 0;
519
  int image_data_start_row = INVALID_ROW;
John Koleszar's avatar
John Koleszar committed
520 521
  int new_mv_count = 0;
  int sum_in_vectors = 0;
522
  MV lastmv = {0, 0};
Paul Wilkins's avatar
Paul Wilkins committed
523
  TWO_PASS *twopass = &cpi->twopass;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
524
  const MV zero_mv = {0, 0};
525 526 527 528 529
  int recon_y_stride, recon_uv_stride, uv_mb_height;

  YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
  YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
  YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
530
  const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
531

532 533
  LAYER_CONTEXT *const lc = is_two_pass_svc(cpi) ?
        &cpi->svc.layer_context[cpi->svc.spatial_layer_id] : NULL;
Paul Wilkins's avatar
Paul Wilkins committed
534 535
  double intra_factor;
  double brightness_factor;
536 537 538 539 540 541
  BufferPool *const pool = cm->buffer_pool;

  // First pass code requires valid last and new frame buffers.
  assert(new_yv12 != NULL);
  assert((lc != NULL) || frame_is_intra_only(cm) || (lst_yv12 != NULL));

542
#if CONFIG_FP_MB_STATS
543
  if (cpi->use_fp_mb_stats) {
544
    vp9_zero_array(cpi->twopass.frame_mb_stats_buf, cm->initial_mbs);
545
  }
546 547
#endif

548
  vp9_clear_system_state();
John Koleszar's avatar
John Koleszar committed
549

Paul Wilkins's avatar
Paul Wilkins committed
550 551
  intra_factor = 0.0;
  brightness_factor = 0.0;
552
  neutral_count = 0.0;
Paul Wilkins's avatar
Paul Wilkins committed
553

554
  set_first_pass_params(cpi);
555
  vp9_set_quantizer(cm, find_fp_qindex(cm->bit_depth));
556

557 558
  if (lc != NULL) {
    twopass = &lc->twopass;
559

560 561 562 563 564 565 566 567 568
    cpi->lst_fb_idx = cpi->svc.spatial_layer_id;
    cpi->ref_frame_flags = VP9_LAST_FLAG;

    if (cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id <
        REF_FRAMES) {
      cpi->gld_fb_idx =
          cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id;
      cpi->ref_frame_flags |= VP9_GOLD_FLAG;
      cpi->refresh_golden_frame = (lc->current_video_frame_in_layer == 0);
569
    } else {
570
      cpi->refresh_golden_frame = 0;
571 572
    }

573 574 575
    if (lc->current_video_frame_in_layer == 0)
      cpi->ref_frame_flags = 0;

576 577 578 579
    vp9_scale_references(cpi);

    // Use either last frame or alt frame for motion search.
    if (cpi->ref_frame_flags & VP9_LAST_FLAG) {
580 581 582
      first_ref_buf = vp9_get_scaled_ref_frame(cpi, LAST_FRAME);
      if (first_ref_buf == NULL)
        first_ref_buf = get_ref_frame_buffer(cpi, LAST_FRAME);
583 584 585
    }

    if (cpi->ref_frame_flags & VP9_GOLD_FLAG) {
586 587 588 589
      gld_yv12 = vp9_get_scaled_ref_frame(cpi, GOLDEN_FRAME);
      if (gld_yv12 == NULL) {
        gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
      }
590 591
    } else {
      gld_yv12 = NULL;
592 593
    }

594 595 596
    set_ref_ptrs(cm, xd,
                 (cpi->ref_frame_flags & VP9_LAST_FLAG) ? LAST_FRAME: NONE,
                 (cpi->ref_frame_flags & VP9_GOLD_FLAG) ? GOLDEN_FRAME : NONE);
597 598 599

    cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
                                        &cpi->scaled_source);
600 601
  }

602 603
  vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);

John Koleszar's avatar
John Koleszar committed
604
  vp9_setup_src_planes(x, cpi->Source, 0, 0);
605
  vp9_setup_dst_planes(xd->plane, new_yv12, 0, 0);
John Koleszar's avatar
John Koleszar committed
606

607 608 609 610
  if (!frame_is_intra_only(cm)) {
    vp9_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL);
  }

611 612
  xd->mi = cm->mi_grid_visible;
  xd->mi[0] = cm->mi;
John Koleszar's avatar
John Koleszar committed
613

614
  vp9_frame_init_quantizer(cpi);
John Koleszar's avatar
John Koleszar committed
615

616 617
  for (i = 0; i < MAX_MB_PLANE; ++i) {
    p[i].coeff = ctx->coeff_pbuf[i][1];
618
    p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
619
    pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
620
    p[i].eobs = ctx->eobs_pbuf[i][1];
621
  }
622
  x->skip_recode = 0;
623

Dmitry Kovalev's avatar
Dmitry Kovalev committed
624 625
  vp9_init_mv_probs(cm);
  vp9_initialize_rd_consts(cpi);
John Koleszar's avatar
John Koleszar committed
626

Adrian Grange's avatar
Adrian Grange committed
627
  // Tiling is ignored in the first pass.
James Zern's avatar
James Zern committed
628 629
  vp9_tile_init(&tile, cm, 0, 0);

630 631 632 633
  recon_y_stride = new_yv12->y_stride;
  recon_uv_stride = new_yv12->uv_stride;
  uv_mb_height = 16 >> (new_yv12->y_height > new_yv12->uv_height);

Adrian Grange's avatar
Adrian Grange committed
634
  for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
635
    MV best_ref_mv = {0, 0};
John Koleszar's avatar
John Koleszar committed
636

Adrian Grange's avatar
Adrian Grange committed
637
    // Reset above block coeffs.
John Koleszar's avatar
John Koleszar committed
638 639
    xd->up_available = (mb_row != 0);
    recon_yoffset = (mb_row * recon_y_stride * 16);
Alex Converse's avatar
Alex Converse committed
640
    recon_uvoffset = (mb_row * recon_uv_stride * uv_mb_height);
John Koleszar's avatar
John Koleszar committed
641

642
    // Set up limit values for motion vectors to prevent them extending
Adrian Grange's avatar
Adrian Grange committed
643
    // outside the UMV borders.
644
    x->mv_row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
John Koleszar's avatar
John Koleszar committed
645
    x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16)
646
                    + BORDER_MV_PIXELS_B16;
John Koleszar's avatar
John Koleszar committed
647

Adrian Grange's avatar
Adrian Grange committed
648
    for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
John Koleszar's avatar
John Koleszar committed
649
      int this_error;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
650
      const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
651
      const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
652 653 654
      double log_intra;
      int level_sample;

655 656 657
#if CONFIG_FP_MB_STATS
      const int mb_index = mb_row * cm->mb_cols + mb_col;
#endif
658

659
      vp9_clear_system_state();
John Koleszar's avatar
John Koleszar committed
660

661 662 663
      xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
      xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
      xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
John Koleszar's avatar
John Koleszar committed
664
      xd->left_available = (mb_col != 0);
665 666
      xd->mi[0]->mbmi.sb_type = bsize;
      xd->mi[0]->mbmi.ref_frame[0] = INTRA_FRAME;
James Zern's avatar
James Zern committed
667
      set_mi_row_col(xd, &tile,
668 669
                     mb_row << 1, num_8x8_blocks_high_lookup[bsize],
                     mb_col << 1, num_8x8_blocks_wide_lookup[bsize],
James Zern's avatar
James Zern committed
670
                     cm->mi_rows, cm->mi_cols);
Jingning Han's avatar
Jingning Han committed
671

Adrian Grange's avatar
Adrian Grange committed
672
      // Do intra 16x16 prediction.
673
      x->skip_encode = 0;
674 675
      xd->mi[0]->mbmi.mode = DC_PRED;
      xd->mi[0]->mbmi.tx_size = use_dc_pred ?
676 677
         (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
      vp9_encode_intra_block_plane(x, bsize, 0);
Johann's avatar
Johann committed
678
      this_error = vpx_get_mb_ss(x->plane[0].src_diff);
679 680 681 682 683 684 685

      // Keep a record of blocks that have almost no intra error residual
      // (i.e. are in effect completely flat and untextured in the intra
      // domain). In natural videos this is uncommon, but it is much more
      // common in animations, graphics and screen content, so may be used
      // as a signal to detect these types of content.
      if (this_error < UL_INTRA_THRESH) {
686
        ++intra_skip_count;
687 688 689 690
      } else if ((mb_col > 0) && (image_data_start_row == INVALID_ROW)) {
        image_data_start_row = mb_row;
      }

691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
#if CONFIG_VP9_HIGHBITDEPTH
      if (cm->use_highbitdepth) {
        switch (cm->bit_depth) {
          case VPX_BITS_8:
            break;
          case VPX_BITS_10:
            this_error >>= 4;
            break;
          case VPX_BITS_12:
            this_error >>= 8;
            break;
          default:
            assert(0 && "cm->bit_depth should be VPX_BITS_8, "
                        "VPX_BITS_10 or VPX_BITS_12");
            return;
        }
      }
#endif  // CONFIG_VP9_HIGHBITDEPTH
709

Paul Wilkins's avatar
Paul Wilkins committed
710
      vp9_clear_system_state();
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
      log_intra = log(this_error + 1.0);
      if (log_intra < 10.0)
        intra_factor += 1.0 + ((10.0 - log_intra) * 0.05);
      else
        intra_factor += 1.0;

#if CONFIG_VP9_HIGHBITDEPTH
      if (cm->use_highbitdepth)
        level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
      else
        level_sample = x->plane[0].src.buf[0];
#else
      level_sample = x->plane[0].src.buf[0];
#endif
      if ((level_sample < DARK_THRESH) && (log_intra < 9.0))
        brightness_factor += 1.0 + (0.01 * (DARK_THRESH - level_sample));
      else
        brightness_factor += 1.0;

Adrian Grange's avatar
Adrian Grange committed
730 731
      // Intrapenalty below deals with situations where the intra and inter
      // error scores are very low (e.g. a plain black frame).
732 733 734 735
      // We do not have special cases in first pass for 0,0 and nearest etc so
      // all inter modes carry an overhead cost estimate for 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.
John Koleszar's avatar
John Koleszar committed
736 737 738
      // This penalty adds a cost matching that of a 0,0 mv to the intra case.
      this_error += intrapenalty;

Adrian Grange's avatar
Adrian Grange committed
739
      // Accumulate the intra error.
John Koleszar's avatar
John Koleszar committed
740 741
      intra_error += (int64_t)this_error;

742 743
#if CONFIG_FP_MB_STATS
      if (cpi->use_fp_mb_stats) {
744
        // initialization
745
        cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
746 747 748
      }
#endif

749 750
      // Set up limit values for motion vectors to prevent them extending
      // outside the UMV borders.
751
      x->mv_col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
752
      x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
John Koleszar's avatar
John Koleszar committed
753

Adrian Grange's avatar
Adrian Grange committed
754
      // Other than for the first frame do a motion search.
755 756
      if ((lc == NULL && cm->current_video_frame > 0) ||
          (lc != NULL && lc->current_video_frame_in_layer > 0)) {
757
        int tmp_err, motion_error, raw_motion_error;
758 759
        // Assume 0,0 motion with no mv overhead.
        MV mv = {0, 0} , tmp_mv = {0, 0};
760
        struct buf_2d unscaled_last_source_buf_2d;
761

762
        xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
763 764 765 766 767 768 769 770 771 772 773 774
#if CONFIG_VP9_HIGHBITDEPTH
        if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
          motion_error = highbd_get_prediction_error(
              bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
        } else {
          motion_error = get_prediction_error(
              bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
        }
#else
        motion_error = get_prediction_error(
            bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
#endif  // CONFIG_VP9_HIGHBITDEPTH
775

776 777 778 779 780 781 782
        // Compute the motion error of the 0,0 motion using the last source
        // frame as the reference. Skip the further motion search on
        // reconstructed frame if this error is small.
        unscaled_last_source_buf_2d.buf =
            cpi->unscaled_last_source->y_buffer + recon_yoffset;
        unscaled_last_source_buf_2d.stride =
            cpi->unscaled_last_source->y_stride;
783 784 785 786 787 788 789 790 791 792 793 794
#if CONFIG_VP9_HIGHBITDEPTH
        if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
          raw_motion_error = highbd_get_prediction_error(
              bsize, &x->plane[0].src, &unscaled_last_source_buf_2d, xd->bd);
        } else {
          raw_motion_error = get_prediction_error(
              bsize, &x->plane[0].src, &unscaled_last_source_buf_2d);
        }
#else
        raw_motion_error = get_prediction_error(
            bsize, &x->plane[0].src, &unscaled_last_source_buf_2d);
#endif  // CONFIG_VP9_HIGHBITDEPTH
795 796

        // TODO(pengchong): Replace the hard-coded threshold
797
        if (raw_motion_error > 25 || lc != NULL) {
798 799
          // Test last reference frame using the previous best mv as the
          // starting point (best reference) for the search.
800
          first_pass_motion_search(cpi, x, &best_ref_mv, &mv, &motion_error);
John Koleszar's avatar
John Koleszar committed
801

802 803
          // If the current best reference mv is not centered on 0,0 then do a
          // 0,0 based search as well.
804
          if (!is_zero_mv(&best_ref_mv)) {
805
            tmp_err = INT_MAX;
806
            first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &tmp_err);
807 808 809

            if (tmp_err < motion_error) {
              motion_error = tmp_err;
810
              mv = tmp_mv;
811
            }
John Koleszar's avatar
John Koleszar committed
812 813
          }

814
          // Search in an older reference frame.