vp9_encoder.c 187 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 13 14
#include <math.h>
#include <stdio.h>
#include <limits.h>

15
#include "./vp9_rtcd.h"
Zoe Liu's avatar
Zoe Liu committed
16
#include "./vpx_config.h"
Johann's avatar
Johann committed
17
#include "./vpx_dsp_rtcd.h"
18
#include "./vpx_scale_rtcd.h"
19
#include "vpx_dsp/psnr.h"
20
#include "vpx_dsp/vpx_dsp_common.h"
Zoe Liu's avatar
Zoe Liu committed
21
#include "vpx_dsp/vpx_filter.h"
22 23 24
#if CONFIG_INTERNAL_STATS
#include "vpx_dsp/ssim.h"
#endif
25
#include "vpx_ports/mem.h"
26
#include "vpx_ports/system_state.h"
27
#include "vpx_ports/vpx_timer.h"
John Koleszar's avatar
John Koleszar committed
28

29
#include "vp9/common/vp9_alloccommon.h"
30
#include "vp9/common/vp9_filter.h"
31
#include "vp9/common/vp9_idct.h"
32 33 34
#if CONFIG_VP9_POSTPROC
#include "vp9/common/vp9_postproc.h"
#endif
35
#include "vp9/common/vp9_reconinter.h"
36
#include "vp9/common/vp9_reconintra.h"
37
#include "vp9/common/vp9_tile_common.h"
38

39
#include "vp9/encoder/vp9_alt_ref_aq.h"
40
#include "vp9/encoder/vp9_aq_360.h"
41
#include "vp9/encoder/vp9_aq_complexity.h"
42 43
#include "vp9/encoder/vp9_aq_cyclicrefresh.h"
#include "vp9/encoder/vp9_aq_variance.h"
44
#include "vp9/encoder/vp9_bitstream.h"
45
#include "vp9/encoder/vp9_context_tree.h"
46
#include "vp9/encoder/vp9_encodeframe.h"
47
#include "vp9/encoder/vp9_encodemv.h"
48
#include "vp9/encoder/vp9_encoder.h"
49
#include "vp9/encoder/vp9_extend.h"
50
#include "vp9/encoder/vp9_ethread.h"
51
#include "vp9/encoder/vp9_firstpass.h"
52
#include "vp9/encoder/vp9_mbgraph.h"
53
#include "vp9/encoder/vp9_multi_thread.h"
54
#include "vp9/encoder/vp9_noise_estimate.h"
55
#include "vp9/encoder/vp9_picklpf.h"
56
#include "vp9/encoder/vp9_ratectrl.h"
57
#include "vp9/encoder/vp9_rd.h"
58
#include "vp9/encoder/vp9_resize.h"
59
#include "vp9/encoder/vp9_segmentation.h"
60
#include "vp9/encoder/vp9_skin_detection.h"
Yaowu Xu's avatar
Yaowu Xu committed
61
#include "vp9/encoder/vp9_speed_features.h"
62
#include "vp9/encoder/vp9_svc_layercontext.h"
63
#include "vp9/encoder/vp9_temporal_filter.h"
64

65 66
#define AM_SEGMENT_ID_INACTIVE 7
#define AM_SEGMENT_ID_ACTIVE 0
67

68 69 70 71 72 73
#define ALTREF_HIGH_PRECISION_MV 1     // Whether to use high precision mv
                                       //  for altref computation.
#define HIGH_PRECISION_MV_QTHRESH 200  // Q threshold for high precision
                                       // mv. Choose a very high value for
                                       // now so that HIGH_PRECISION is always
                                       // chosen.
John Koleszar's avatar
John Koleszar committed
74
// #define OUTPUT_YUV_REC
John Koleszar's avatar
John Koleszar committed
75

76
#ifdef OUTPUT_YUV_DENOISED
77
FILE *yuv_denoised_file = NULL;
78
#endif
Marco's avatar
Marco committed
79 80 81
#ifdef OUTPUT_YUV_SKINMAP
FILE *yuv_skinmap_file = NULL;
#endif
82 83 84
#ifdef OUTPUT_YUV_REC
FILE *yuv_rec_file;
#endif
John Koleszar's avatar
John Koleszar committed
85 86 87

#if 0
FILE *framepsnr;
Yaowu Xu's avatar
Yaowu Xu committed
88
FILE *kf_list;
John Koleszar's avatar
John Koleszar committed
89 90 91
FILE *keyfile;
#endif

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
#ifdef ENABLE_KF_DENOISE
// Test condition for spatial denoise of source.
static int is_spatial_denoise_enabled(VP9_COMP *cpi) {
  VP9_COMMON *const cm = &cpi->common;
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;

  return (oxcf->pass != 1) && !is_lossless_requested(&cpi->oxcf) &&
         frame_is_intra_only(cm);
}
#endif

// Test for whether to calculate metrics for the frame.
static int is_psnr_calc_enabled(VP9_COMP *cpi) {
  VP9_COMMON *const cm = &cpi->common;
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;

  return cpi->b_calculate_psnr && (oxcf->pass != 1) && cm->show_frame;
}

111
/* clang-format off */
112
const Vp9LevelSpec vp9_level_defs[VP9_LEVELS] = {
113 114 115 116 117 118 119 120 121 122
  { LEVEL_1,   829440,      36864,    200,    400,   2, 1,  4,  8 },
  { LEVEL_1_1, 2764800,     73728,    800,    1000,  2, 1,  4,  8 },
  { LEVEL_2,   4608000,     122880,   1800,   1500,  2, 1,  4,  8 },
  { LEVEL_2_1, 9216000,     245760,   3600,   2800,  2, 2,  4,  8 },
  { LEVEL_3,   20736000,    552960,   7200,   6000,  2, 4,  4,  8 },
  { LEVEL_3_1, 36864000,    983040,   12000,  10000, 2, 4,  4,  8 },
  { LEVEL_4,   83558400,    2228224,  18000,  16000, 4, 4,  4,  8 },
  { LEVEL_4_1, 160432128,   2228224,  30000,  18000, 4, 4,  5,  6 },
  { LEVEL_5,   311951360,   8912896,  60000,  36000, 6, 8,  6,  4 },
  { LEVEL_5_1, 588251136,   8912896,  120000, 46000, 8, 8,  10, 4 },
123 124
  // TODO(huisu): update max_cpb_size for level 5_2 ~ 6_2 when
  // they are finalized (currently TBD).
125 126 127 128
  { LEVEL_5_2, 1176502272,  8912896,  180000, 0,     8, 8,  10, 4 },
  { LEVEL_6,   1176502272,  35651584, 180000, 0,     8, 16, 10, 4 },
  { LEVEL_6_1, 2353004544u, 35651584, 240000, 0,     8, 16, 10, 4 },
  { LEVEL_6_2, 4706009088u, 35651584, 480000, 0,     8, 16, 10, 4 },
129
};
130
/* clang-format on */
131

132 133 134 135 136 137 138 139 140 141
static const char *level_fail_messages[TARGET_LEVEL_FAIL_IDS] =
    { "The average bit-rate is too high.",
      "The picture size is too large.",
      "The luma sample rate is too large.",
      "The CPB size is too large.",
      "The compression ratio is too small",
      "Too many column tiles are used.",
      "The alt-ref distance is too small.",
      "Too many reference buffers are used." };

142
static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
143 144 145 146 147 148 149 150 151 152 153 154
  switch (mode) {
    case NORMAL:
      *hr = 1;
      *hs = 1;
      break;
    case FOURFIVE:
      *hr = 4;
      *hs = 5;
      break;
    case THREEFIVE:
      *hr = 3;
      *hs = 5;
155
      break;
156 157 158
    case ONETWO:
      *hr = 1;
      *hs = 2;
159
      break;
160 161 162
    default:
      *hr = 1;
      *hs = 1;
163
      assert(0);
164 165 166 167
      break;
  }
}

168 169
// Mark all inactive blocks as active. Other segmentation features may be set
// so memset cannot be used, instead only inactive blocks should be reset.
170
static void suppress_active_map(VP9_COMP *cpi) {
171
  unsigned char *const seg_map = cpi->segmentation_map;
172 173 174 175 176 177 178

  if (cpi->active_map.enabled || cpi->active_map.update) {
    const int rows = cpi->common.mi_rows;
    const int cols = cpi->common.mi_cols;
    int i;

    for (i = 0; i < rows * cols; ++i)
179 180
      if (seg_map[i] == AM_SEGMENT_ID_INACTIVE)
        seg_map[i] = AM_SEGMENT_ID_ACTIVE;
181
  }
182 183
}

184
static void apply_active_map(VP9_COMP *cpi) {
185 186 187 188 189 190 191
  struct segmentation *const seg = &cpi->common.seg;
  unsigned char *const seg_map = cpi->segmentation_map;
  const unsigned char *const active_map = cpi->active_map.map;
  int i;

  assert(AM_SEGMENT_ID_ACTIVE == CR_SEGMENT_ID_BASE);

192 193 194 195 196
  if (frame_is_intra_only(&cpi->common)) {
    cpi->active_map.enabled = 0;
    cpi->active_map.update = 1;
  }

197 198 199 200 201 202
  if (cpi->active_map.update) {
    if (cpi->active_map.enabled) {
      for (i = 0; i < cpi->common.mi_rows * cpi->common.mi_cols; ++i)
        if (seg_map[i] == AM_SEGMENT_ID_ACTIVE) seg_map[i] = active_map[i];
      vp9_enable_segmentation(seg);
      vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
203 204 205
      vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
      // Setting the data to -MAX_LOOP_FILTER will result in the computed loop
      // filter level being zero regardless of the value of seg->abs_delta.
206 207
      vp9_set_segdata(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF,
                      -MAX_LOOP_FILTER);
208 209
    } else {
      vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
210
      vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
211 212 213 214 215 216 217 218 219
      if (seg->enabled) {
        seg->update_data = 1;
        seg->update_map = 1;
      }
    }
    cpi->active_map.update = 0;
  }
}

220 221 222 223 224 225 226 227 228 229
static void init_level_info(Vp9LevelInfo *level_info) {
  Vp9LevelStats *const level_stats = &level_info->level_stats;
  Vp9LevelSpec *const level_spec = &level_info->level_spec;

  memset(level_stats, 0, sizeof(*level_stats));
  memset(level_spec, 0, sizeof(*level_spec));
  level_spec->level = LEVEL_UNKNOWN;
  level_spec->min_altref_distance = INT_MAX;
}

230
VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec) {
231 232 233 234 235 236 237
  int i;
  const Vp9LevelSpec *this_level;

  vpx_clear_system_state();

  for (i = 0; i < VP9_LEVELS; ++i) {
    this_level = &vp9_level_defs[i];
238 239 240
    if ((double)level_spec->max_luma_sample_rate >
            (double)this_level->max_luma_sample_rate *
                (1 + SAMPLE_RATE_GRACE_P) ||
241 242 243 244 245 246 247 248 249 250 251 252 253
        level_spec->max_luma_picture_size > this_level->max_luma_picture_size ||
        level_spec->average_bitrate > this_level->average_bitrate ||
        level_spec->max_cpb_size > this_level->max_cpb_size ||
        level_spec->compression_ratio < this_level->compression_ratio ||
        level_spec->max_col_tiles > this_level->max_col_tiles ||
        level_spec->min_altref_distance < this_level->min_altref_distance ||
        level_spec->max_ref_frame_buffers > this_level->max_ref_frame_buffers)
      continue;
    break;
  }
  return (i == VP9_LEVELS) ? LEVEL_UNKNOWN : vp9_level_defs[i].level;
}

254
int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                       int cols) {
  if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
    unsigned char *const active_map_8x8 = cpi->active_map.map;
    const int mi_rows = cpi->common.mi_rows;
    const int mi_cols = cpi->common.mi_cols;
    cpi->active_map.update = 1;
    if (new_map_16x16) {
      int r, c;
      for (r = 0; r < mi_rows; ++r) {
        for (c = 0; c < mi_cols; ++c) {
          active_map_8x8[r * mi_cols + c] =
              new_map_16x16[(r >> 1) * cols + (c >> 1)]
                  ? AM_SEGMENT_ID_ACTIVE
                  : AM_SEGMENT_ID_INACTIVE;
        }
      }
      cpi->active_map.enabled = 1;
    } else {
      cpi->active_map.enabled = 0;
    }
    return 0;
  } else {
    return -1;
  }
}

281
int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
282 283 284
                       int cols) {
  if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols &&
      new_map_16x16) {
285
    unsigned char *const seg_map_8x8 = cpi->segmentation_map;
286 287
    const int mi_rows = cpi->common.mi_rows;
    const int mi_cols = cpi->common.mi_cols;
James Zern's avatar
James Zern committed
288
    memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    if (cpi->active_map.enabled) {
      int r, c;
      for (r = 0; r < mi_rows; ++r) {
        for (c = 0; c < mi_cols; ++c) {
          // Cyclic refresh segments are considered active despite not having
          // AM_SEGMENT_ID_ACTIVE
          new_map_16x16[(r >> 1) * cols + (c >> 1)] |=
              seg_map_8x8[r * mi_cols + c] != AM_SEGMENT_ID_INACTIVE;
        }
      }
    }
    return 0;
  } else {
    return -1;
  }
}

306
void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
307
  MACROBLOCK *const mb = &cpi->td.mb;
308
  cpi->common.allow_high_precision_mv = allow_high_precision_mv;
309
  if (cpi->common.allow_high_precision_mv) {
310 311 312 313 314 315 316
    mb->mvcost = mb->nmvcost_hp;
    mb->mvsadcost = mb->nmvsadcost_hp;
  } else {
    mb->mvcost = mb->nmvcost;
    mb->mvsadcost = mb->nmvsadcost;
  }
}
317

318 319 320 321 322 323 324
static void setup_frame(VP9_COMP *cpi) {
  VP9_COMMON *const cm = &cpi->common;
  // Set up entropy context depending on frame type. The decoder mandates
  // the use of the default context, index 0, for keyframes and inter
  // frames where the error_resilient_mode or intra_only flag is set. For
  // other inter-frames the encoder currently uses only two contexts;
  // context 1 for ALTREF frames and context 0 for the others.
325 326 327
  if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
    vp9_setup_past_independence(cm);
  } else {
328
    if (!cpi->use_svc) cm->frame_context_idx = cpi->refresh_alt_ref_frame;
329 330
  }

331
  if (cm->frame_type == KEY_FRAME) {
332
    if (!is_two_pass_svc(cpi)) cpi->refresh_golden_frame = 1;
333
    cpi->refresh_alt_ref_frame = 1;
334
    vp9_zero(cpi->interp_filter_selected);
335
  } else {
336
    *cm->fc = cm->frame_contexts[cm->frame_context_idx];
337
    vp9_zero(cpi->interp_filter_selected[0]);
338 339 340
  }
}

341 342 343
static void vp9_enc_setup_mi(VP9_COMMON *cm) {
  int i;
  cm->mi = cm->mip + cm->mi_stride + 1;
James Zern's avatar
James Zern committed
344
  memset(cm->mip, 0, cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mip));
345 346
  cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
  // Clear top border row
James Zern's avatar
James Zern committed
347
  memset(cm->prev_mip, 0, sizeof(*cm->prev_mip) * cm->mi_stride);
348 349
  // Clear left border column
  for (i = 1; i < cm->mi_rows + 1; ++i)
James Zern's avatar
James Zern committed
350
    memset(&cm->prev_mip[i * cm->mi_stride], 0, sizeof(*cm->prev_mip));
351 352 353 354

  cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
  cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;

James Zern's avatar
James Zern committed
355 356
  memset(cm->mi_grid_base, 0,
         cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mi_grid_base));
357 358 359 360
}

static int vp9_enc_alloc_mi(VP9_COMMON *cm, int mi_size) {
  cm->mip = vpx_calloc(mi_size, sizeof(*cm->mip));
361
  if (!cm->mip) return 1;
362
  cm->prev_mip = vpx_calloc(mi_size, sizeof(*cm->prev_mip));
363
  if (!cm->prev_mip) return 1;
364
  cm->mi_alloc_size = mi_size;
365

366 367 368 369 370
  cm->mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO *));
  if (!cm->mi_grid_base) return 1;
  cm->prev_mi_grid_base =
      (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO *));
  if (!cm->prev_mi_grid_base) return 1;
371

372 373 374 375 376 377 378 379
  return 0;
}

static void vp9_enc_free_mi(VP9_COMMON *cm) {
  vpx_free(cm->mip);
  cm->mip = NULL;
  vpx_free(cm->prev_mip);
  cm->prev_mip = NULL;
380 381 382 383
  vpx_free(cm->mi_grid_base);
  cm->mi_grid_base = NULL;
  vpx_free(cm->prev_mi_grid_base);
  cm->prev_mi_grid_base = NULL;
384 385 386 387
}

static void vp9_swap_mi_and_prev_mi(VP9_COMMON *cm) {
  // Current mip will be the prev_mip for the next frame.
388
  MODE_INFO **temp_base = cm->prev_mi_grid_base;
389 390 391 392 393 394 395
  MODE_INFO *temp = cm->prev_mip;
  cm->prev_mip = cm->mip;
  cm->mip = temp;

  // Update the upper left visible macroblock ptrs.
  cm->mi = cm->mip + cm->mi_stride + 1;
  cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
396 397 398 399 400

  cm->prev_mi_grid_base = cm->mi_grid_base;
  cm->mi_grid_base = temp_base;
  cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
  cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
401 402
}

403
void vp9_initialize_enc(void) {
404
  static volatile int init_done = 0;
John Koleszar's avatar
John Koleszar committed
405 406

  if (!init_done) {
407
    vp9_rtcd();
Johann's avatar
Johann committed
408
    vpx_dsp_rtcd();
409
    vpx_scale_rtcd();
410
    vp9_init_intra_predictors();
411
    vp9_init_me_luts();
412
    vp9_rc_init_minq_luts();
413
    vp9_entropy_mv_init();
414
    vp9_temporal_filter_init();
John Koleszar's avatar
John Koleszar committed
415 416
    init_done = 1;
  }
John Koleszar's avatar
John Koleszar committed
417 418
}

419
static void dealloc_compressor_data(VP9_COMP *cpi) {
420
  VP9_COMMON *const cm = &cpi->common;
421
  int i;
422

423 424 425
  vpx_free(cpi->mbmi_ext_base);
  cpi->mbmi_ext_base = NULL;

426 427
  vpx_free(cpi->tile_data);
  cpi->tile_data = NULL;
428

John Koleszar's avatar
John Koleszar committed
429
  vpx_free(cpi->segmentation_map);
430
  cpi->segmentation_map = NULL;
John Koleszar's avatar
John Koleszar committed
431
  vpx_free(cpi->coding_context.last_frame_seg_map_copy);
432
  cpi->coding_context.last_frame_seg_map_copy = NULL;
John Koleszar's avatar
John Koleszar committed
433

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
  vpx_free(cpi->nmvcosts[0]);
  vpx_free(cpi->nmvcosts[1]);
  cpi->nmvcosts[0] = NULL;
  cpi->nmvcosts[1] = NULL;

  vpx_free(cpi->nmvcosts_hp[0]);
  vpx_free(cpi->nmvcosts_hp[1]);
  cpi->nmvcosts_hp[0] = NULL;
  cpi->nmvcosts_hp[1] = NULL;

  vpx_free(cpi->nmvsadcosts[0]);
  vpx_free(cpi->nmvsadcosts[1]);
  cpi->nmvsadcosts[0] = NULL;
  cpi->nmvsadcosts[1] = NULL;

  vpx_free(cpi->nmvsadcosts_hp[0]);
  vpx_free(cpi->nmvsadcosts_hp[1]);
  cpi->nmvsadcosts_hp[0] = NULL;
  cpi->nmvsadcosts_hp[1] = NULL;

454 455 456 457 458 459
  vpx_free(cpi->prev_partition);
  cpi->prev_partition = NULL;

  vpx_free(cpi->prev_segment_id);
  cpi->prev_segment_id = NULL;

460 461 462
  vpx_free(cpi->prev_variance_low);
  cpi->prev_variance_low = NULL;

463 464 465
  vpx_free(cpi->copied_frame_cnt);
  cpi->copied_frame_cnt = NULL;

466 467
  vpx_free(cpi->content_state_sb);
  cpi->content_state_sb = NULL;
468

469 470 471
  vp9_cyclic_refresh_free(cpi->cyclic_refresh);
  cpi->cyclic_refresh = NULL;

472 473 474
  vpx_free(cpi->active_map.map);
  cpi->active_map.map = NULL;

475 476 477
  vpx_free(cpi->consec_zero_mv);
  cpi->consec_zero_mv = NULL;

478 479 480 481
  vp9_free_ref_frame_buffers(cm->buffer_pool);
#if CONFIG_VP9_POSTPROC
  vp9_free_postproc_buffers(cm);
#endif
482
  vp9_free_context_buffers(cm);
John Koleszar's avatar
John Koleszar committed
483

484 485 486 487
  vpx_free_frame_buffer(&cpi->last_frame_uf);
  vpx_free_frame_buffer(&cpi->scaled_source);
  vpx_free_frame_buffer(&cpi->scaled_last_source);
  vpx_free_frame_buffer(&cpi->alt_ref_buffer);
488 489 490 491 492
#ifdef ENABLE_KF_DENOISE
  vpx_free_frame_buffer(&cpi->raw_unscaled_source);
  vpx_free_frame_buffer(&cpi->raw_scaled_source);
#endif

493
  vp9_lookahead_destroy(cpi->lookahead);
John Koleszar's avatar
John Koleszar committed
494

495 496
  vpx_free(cpi->tile_tok[0][0]);
  cpi->tile_tok[0][0] = 0;
John Koleszar's avatar
John Koleszar committed
497

498 499 500
  vpx_free(cpi->tplist[0][0]);
  cpi->tplist[0][0] = NULL;

501
  vp9_free_pc_tree(&cpi->td);
502

503 504 505 506 507 508
  for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
    LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
    vpx_free(lc->rc_twopass_stats_in.buf);
    lc->rc_twopass_stats_in.buf = NULL;
    lc->rc_twopass_stats_in.sz = 0;
  }
509 510 511 512 513

  if (cpi->source_diff_var != NULL) {
    vpx_free(cpi->source_diff_var);
    cpi->source_diff_var = NULL;
  }
514

515
  for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
516
    vpx_free_frame_buffer(&cpi->svc.scaled_frames[i]);
517
  }
James Zern's avatar
James Zern committed
518 519
  memset(&cpi->svc.scaled_frames[0], 0,
         MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
520

521 522 523
  vpx_free_frame_buffer(&cpi->svc.scaled_temp);
  memset(&cpi->svc.scaled_temp, 0, sizeof(cpi->svc.scaled_temp));

524
  vpx_free_frame_buffer(&cpi->svc.empty_frame.img);
James Zern's avatar
James Zern committed
525
  memset(&cpi->svc.empty_frame, 0, sizeof(cpi->svc.empty_frame));
526 527

  vp9_free_svc_cyclic_refresh(cpi);
John Koleszar's avatar
John Koleszar committed
528 529
}

530 531 532 533 534 535 536 537
static void save_coding_context(VP9_COMP *cpi) {
  CODING_CONTEXT *const cc = &cpi->coding_context;
  VP9_COMMON *cm = &cpi->common;

  // Stores a snapshot of key state variables which can subsequently be
  // restored with a call to vp9_restore_coding_context. These functions are
  // intended for use in a re-code loop in vp9_compress_frame where the
  // quantizer value is adjusted between loop iterations.
538
  vp9_copy(cc->nmvjointcost, cpi->td.mb.nmvjointcost);
539

James Zern's avatar
James Zern committed
540 541 542 543 544 545 546 547
  memcpy(cc->nmvcosts[0], cpi->nmvcosts[0],
         MV_VALS * sizeof(*cpi->nmvcosts[0]));
  memcpy(cc->nmvcosts[1], cpi->nmvcosts[1],
         MV_VALS * sizeof(*cpi->nmvcosts[1]));
  memcpy(cc->nmvcosts_hp[0], cpi->nmvcosts_hp[0],
         MV_VALS * sizeof(*cpi->nmvcosts_hp[0]));
  memcpy(cc->nmvcosts_hp[1], cpi->nmvcosts_hp[1],
         MV_VALS * sizeof(*cpi->nmvcosts_hp[1]));
548 549 550

  vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);

551 552
  memcpy(cpi->coding_context.last_frame_seg_map_copy, cm->last_frame_seg_map,
         (cm->mi_rows * cm->mi_cols));
553 554 555 556

  vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
  vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);

557
  cc->fc = *cm->fc;
558 559 560 561 562 563 564 565
}

static void restore_coding_context(VP9_COMP *cpi) {
  CODING_CONTEXT *const cc = &cpi->coding_context;
  VP9_COMMON *cm = &cpi->common;

  // Restore key state variables to the snapshot state stored in the
  // previous call to vp9_save_coding_context.
566
  vp9_copy(cpi->td.mb.nmvjointcost, cc->nmvjointcost);
567

James Zern's avatar
James Zern committed
568 569 570 571 572 573
  memcpy(cpi->nmvcosts[0], cc->nmvcosts[0], MV_VALS * sizeof(*cc->nmvcosts[0]));
  memcpy(cpi->nmvcosts[1], cc->nmvcosts[1], MV_VALS * sizeof(*cc->nmvcosts[1]));
  memcpy(cpi->nmvcosts_hp[0], cc->nmvcosts_hp[0],
         MV_VALS * sizeof(*cc->nmvcosts_hp[0]));
  memcpy(cpi->nmvcosts_hp[1], cc->nmvcosts_hp[1],
         MV_VALS * sizeof(*cc->nmvcosts_hp[1]));
574 575 576

  vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);

577
  memcpy(cm->last_frame_seg_map, cpi->coding_context.last_frame_seg_map_copy,
James Zern's avatar
James Zern committed
578
         (cm->mi_rows * cm->mi_cols));
579 580 581 582

  vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
  vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);

583
  *cm->fc = cc->fc;
584 585
}

586
static void configure_static_seg_features(VP9_COMP *cpi) {
587
  VP9_COMMON *const cm = &cpi->common;
588
  const RATE_CONTROL *const rc = &cpi->rc;
589
  struct segmentation *const seg = &cm->seg;
590

591
  int high_q = (int)(rc->avg_q > 48.0);
John Koleszar's avatar
John Koleszar committed
592
  int qi_delta;
593

John Koleszar's avatar
John Koleszar committed
594 595 596
  // Disable and clear down for KF
  if (cm->frame_type == KEY_FRAME) {
    // Clear down the global segmentation map
James Zern's avatar
James Zern committed
597
    memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
598 599
    seg->update_map = 0;
    seg->update_data = 0;
John Koleszar's avatar
John Koleszar committed
600
    cpi->static_mb_pct = 0;
601

John Koleszar's avatar
John Koleszar committed
602
    // Disable segmentation
603
    vp9_disable_segmentation(seg);
Paul Wilkins's avatar
Paul Wilkins committed
604

John Koleszar's avatar
John Koleszar committed
605
    // Clear down the segment features.
606
    vp9_clearall_segfeatures(seg);
607 608
  } else if (cpi->refresh_alt_ref_frame) {
    // If this is an alt ref frame
John Koleszar's avatar
John Koleszar committed
609
    // Clear down the global segmentation map
James Zern's avatar
James Zern committed
610
    memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
611 612
    seg->update_map = 0;
    seg->update_data = 0;
John Koleszar's avatar
John Koleszar committed
613
    cpi->static_mb_pct = 0;
Paul Wilkins's avatar
Paul Wilkins committed
614

John Koleszar's avatar
John Koleszar committed
615
    // Disable segmentation and individual segment features by default
616
    vp9_disable_segmentation(seg);
617
    vp9_clearall_segfeatures(seg);
Paul Wilkins's avatar
Paul Wilkins committed
618

John Koleszar's avatar
John Koleszar committed
619 620
    // Scan frames from current to arf frame.
    // This function re-enables segmentation if appropriate.
621
    vp9_update_mbgraph_stats(cpi);
Paul Wilkins's avatar
Paul Wilkins committed
622

John Koleszar's avatar
John Koleszar committed
623 624
    // If segmentation was enabled set those features needed for the
    // arf itself.
625 626 627
    if (seg->enabled) {
      seg->update_map = 1;
      seg->update_data = 1;
Paul Wilkins's avatar
Paul Wilkins committed
628

629 630
      qi_delta =
          vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875, cm->bit_depth);
631
      vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
632
      vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
Paul Wilkins's avatar
Paul Wilkins committed
633

634 635
      vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
      vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
636

John Koleszar's avatar
John Koleszar committed
637
      // Where relevant assume segment data is delta data
638
      seg->abs_delta = SEGMENT_DELTADATA;
639
    }
640
  } else if (seg->enabled) {
641 642
    // All other frames if segmentation has been enabled

John Koleszar's avatar
John Koleszar committed
643
    // First normal frame in a valid gf or alt ref group
644
    if (rc->frames_since_golden == 0) {
Paul Wilkins's avatar
Paul Wilkins committed
645
      // Set up segment features for normal frames in an arf group
646
      if (rc->source_alt_ref_active) {
647 648 649
        seg->update_map = 0;
        seg->update_data = 1;
        seg->abs_delta = SEGMENT_DELTADATA;
650

651 652
        qi_delta =
            vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125, cm->bit_depth);
653
        vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
654
        vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
Paul Wilkins's avatar
Paul Wilkins committed
655

656 657
        vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
        vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
658

John Koleszar's avatar
John Koleszar committed
659 660
        // Segment coding disabled for compred testing
        if (high_q || (cpi->static_mb_pct == 100)) {
661 662 663
          vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
          vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
          vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
John Koleszar's avatar
John Koleszar committed
664
        }
665 666 667 668
      } else {
        // Disable segmentation and clear down features if alt ref
        // is not active for this group

669
        vp9_disable_segmentation(seg);
Paul Wilkins's avatar
Paul Wilkins committed
670

James Zern's avatar
James Zern committed
671
        memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
Paul Wilkins's avatar
Paul Wilkins committed
672

673 674
        seg->update_map = 0;
        seg->update_data = 0;
Paul Wilkins's avatar
Paul Wilkins committed
675

676
        vp9_clearall_segfeatures(seg);
John Koleszar's avatar
John Koleszar committed
677
      }
678
    } else if (rc->is_src_frame_alt_ref) {
679 680 681
      // Special case where we are coding over the top of a previous
      // alt ref frame.
      // Segment coding disabled for compred testing
John Koleszar's avatar
John Koleszar committed
682

Paul Wilkins's avatar
Paul Wilkins committed
683
      // Enable ref frame features for segment 0 as well
684 685
      vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
      vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
John Koleszar's avatar
John Koleszar committed
686

Paul Wilkins's avatar
Paul Wilkins committed
687
      // All mbs should use ALTREF_FRAME
688 689 690 691
      vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
      vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
      vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
      vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
John Koleszar's avatar
John Koleszar committed
692

Paul Wilkins's avatar
Paul Wilkins committed
693
      // Skip all MBs if high Q (0,0 mv and skip coeffs)
John Koleszar's avatar
John Koleszar committed
694
      if (high_q) {
695 696
        vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
        vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
John Koleszar's avatar
John Koleszar committed
697
      }
698
      // Enable data update
699
      seg->update_data = 1;
700 701 702
    } else {
      // All other frames.

John Koleszar's avatar
John Koleszar committed
703
      // No updates.. leave things as they are.
704 705
      seg->update_map = 0;
      seg->update_data = 0;
John Koleszar's avatar
John Koleszar committed
706 707
    }
  }
708 709
}

710
static void update_reference_segmentation_map(VP9_COMP *cpi) {
711
  VP9_COMMON *const cm = &cpi->common;
712
  MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
713
  uint8_t *cache_ptr = cm->last_frame_seg_map;
714 715
  int row, col;

716
  for (row = 0; row < cm->mi_rows; row++) {
717
    MODE_INFO **mi_8x8 = mi_8x8_ptr;
718
    uint8_t *cache = cache_ptr;
719
    for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
720
      cache[0] = mi_8x8[0]->segment_id;
721
    mi_8x8_ptr += cm->mi_stride;
722
    cache_ptr += cm->mi_cols;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
723 724 725
  }
}

726
static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
727
  VP9_COMMON *cm = &cpi->common;
728
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
729

730 731 732
  if (!cpi->lookahead)
    cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
                                        cm->subsampling_x, cm->subsampling_y,
733
#if CONFIG_VP9_HIGHBITDEPTH
734
                                        cm->use_highbitdepth,
735
#endif
736
                                        oxcf->lag_in_frames);
John Koleszar's avatar
John Koleszar committed
737
  if (!cpi->lookahead)
738
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
John Koleszar's avatar
John Koleszar committed
739
                       "Failed to allocate lag buffers");
John Koleszar's avatar
John Koleszar committed
740

741
  // TODO(agrange) Check if ARF is enabled and skip allocation if not.
742
  if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, oxcf->width, oxcf->height,
743
                               cm->subsampling_x, cm->subsampling_y,
744 745 746
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
747 748
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
749
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
John Koleszar's avatar
John Koleszar committed
750
                       "Failed to allocate altref buffer");
John Koleszar's avatar
John Koleszar committed
751
}
752

753
static void alloc_util_frame_buffers(VP9_COMP *cpi) {
754
  VP9_COMMON *const cm = &cpi->common;
755
  if (vpx_realloc_frame_buffer(&cpi->last_frame_uf, cm->width, cm->height,
756
                               cm->subsampling_x, cm->subsampling_y,
757 758 759
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
760 761
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
762
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
763
                       "Failed to allocate last frame buffer");
764

765
  if (vpx_realloc_frame_buffer(&cpi->scaled_source, cm->width, cm->height,
766
                               cm->subsampling_x, cm->subsampling_y,
767 768 769
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
770 771
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
772
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
773
                       "Failed to allocate scaled source buffer");
774

775 776 777 778 779
  // For 1 pass cbr: allocate scaled_frame that may be used as an intermediate
  // buffer for a 2 stage down-sampling: two stages of 1:2 down-sampling for a
  // target of 1/4x1/4.
  if (is_one_pass_cbr_svc(cpi) && !cpi->svc.scaled_temp_is_alloc) {
    cpi->svc.scaled_temp_is_alloc = 1;
780 781 782
    if (vpx_realloc_frame_buffer(
            &cpi->svc.scaled_temp, cm->width >> 1, cm->height >> 1,
            cm->subsampling_x, cm->subsampling_y,
783
#if CONFIG_VP9_HIGHBITDEPTH
784
            cm->use_highbitdepth,
785
#endif
786
            VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment, NULL, NULL, NULL))
787 788 789 790
      vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
                         "Failed to allocate scaled_frame for svc ");
  }

791
  if (vpx_realloc_frame_buffer(&cpi->scaled_last_source, cm->width, cm->height,
792
                               cm->subsampling_x, cm->subsampling_y,
793 794 795
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
796 797
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
798
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
799
                       "Failed to allocate scaled last source buffer");
800
#ifdef ENABLE_KF_DENOISE
801
  if (vpx_realloc_frame_buffer(&cpi->raw_unscaled_source, cm->width, cm->height,
802 803 804 805 806 807 808 809 810
                               cm->subsampling_x, cm->subsampling_y,
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                       "Failed to allocate unscaled raw source frame buffer");

811
  if (vpx_realloc_frame_buffer(&cpi->raw_scaled_source, cm->width, cm->height,
812 813 814 815 816 817 818 819 820
                               cm->subsampling_x, cm->subsampling_y,
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                       "Failed to allocate scaled raw source frame buffer");
#endif
821
}
822

823 824 825 826 827
static int alloc_context_buffers_ext(VP9_COMP *cpi) {
  VP9_COMMON *cm = &cpi->common;
  int mi_size = cm->mi_cols * cm->mi_rows;

  cpi->mbmi_ext_base = vpx_calloc(mi_size, sizeof(*cpi->mbmi_ext_base));
828
  if (!cpi->mbmi_ext_base) return 1;
829 830 831 832

  return 0;
}

833
static void alloc_compressor_data(VP9_COMP *cpi) {
834
  VP9_COMMON *cm = &cpi->common;
835
  int sb_rows;
836

837 838
  vp9_alloc_context_buffers(cm, cm->width, cm->height);

839 840
  alloc_context_buffers_ext(cpi);

841
  vpx_free(cpi->tile_tok[0][0]);
842 843 844

  {
    unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
845
    CHECK_MEM_ERROR(cm, cpi->tile_tok[0][0],
846
                    vpx_calloc(tokens, sizeof(*cpi->tile_tok[0][0])));
847
  }
848

849 850 851 852 853 854
  sb_rows = mi_cols_aligned_to_sb(cm->mi_rows) >> MI_BLOCK_SIZE_LOG2;
  vpx_free(cpi->tplist[0][0]);
  CHECK_MEM_ERROR(
      cm, cpi->tplist[0][0],
      vpx_calloc(sb_rows * 4 * (1 << 6), sizeof(*cpi->tplist[0][0])));

855
  vp9_setup_pc_tree(&cpi->common, &cpi->td);
856 857
}

858 859 860 861 862 863 864 865 866 867 868
void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
  cpi->framerate = framerate < 0.1 ? 30 : framerate;
  vp9_rc_update_framerate(cpi);
}

static void set_tile_limits(VP9_COMP *cpi) {
  VP9_COMMON *const cm = &cpi->common;

  int min_log2_tile_cols, max_log2_tile_cols;
  vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);

869 870
  if (is_two_pass_svc(cpi) && (cpi->svc.encode_empty_frame_state == ENCODING ||
                               cpi->svc.number_spatial_layers > 1)) {
871 872 873
    cm->log2_tile_cols = 0;
    cm->log2_tile_rows = 0;
  } else {
874 875
    cm->log2_tile_cols =
        clamp(cpi->oxcf.tile_columns, min_log2_tile_cols, max_log2_tile_cols);
876 877 878 879
    cm->log2_tile_rows = cpi->oxcf.tile_rows;
  }
}

880 881
static void update_frame_size(VP9_COMP *cpi) {
  VP9_COMMON *const cm = &cpi->common;
882
  MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
883 884 885

  vp9_set_mb_mi(cm, cm->width, cm->height);
  vp9_init_context_buffers(cm);
886
  vp9_init_macroblockd(cm, xd, NULL);
887 888 889
  cpi->td.mb.mbmi_ext_base = cpi->mbmi_ext_base;
  memset(cpi->mbmi_ext_base, 0,
         cm->mi_rows * cm->mi_cols * sizeof(*cpi->mbmi_ext_base));
890

891 892
  set_tile_limits(cpi);

893
  if (is_two_pass_svc(cpi)) {
894
    if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, cm->width, cm->height,
895
                                 cm->subsampling_x, cm->subsampling_y,
896 897 898
#if CONFIG_VP9_HIGHBITDEPTH
                                 cm->use_highbitdepth,
#endif
899 900
                                 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                                 NULL, NULL, NULL))
901 902 903
      vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                         "Failed to reallocate alt_ref_buffer");
  }
904 905
}

906 907 908 909 910 911
static void init_buffer_indices(VP9_COMP *cpi) {
  cpi->lst_fb_idx = 0;
  cpi->gld_fb_idx = 1;
  cpi->alt_fb_idx = 2;
}

912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
static void init_level_constraint(LevelConstraint *lc) {
  lc->level_index = -1;
  lc->max_cpb_size = INT_MAX;
  lc->max_frame_size = INT_MAX;
  lc->rc_config_updated = 0;
  lc->fail_flag = 0;
}

static void set_level_constraint(LevelConstraint *ls, int8_t level_index) {
  vpx_clear_system_state();
  ls->level_index = level_index;
  if (level_index >= 0) {
    ls->max_cpb_size = vp9_level_defs[level_index].max_cpb_size * (double)1000;
  }
}

928
static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
929
  VP9_COMMON *const cm = &cpi->common;
John Koleszar's avatar
John Koleszar committed
930

John Koleszar's avatar
John Koleszar committed
931
  cpi->oxcf = *oxcf;
932
  cpi->framerate = oxcf->init_framerate;
933 934
  cm->profile = oxcf->profile;
  cm->bit_depth = oxcf->bit_depth;
935 936 937
#if CONFIG_VP9_HIGHBITDEPTH
  cm->use_highbitdepth = oxcf->use_highbitdepth;
#endif
938
  cm->color_space = oxcf->color_space;
939
  cm->color_range = oxcf->color_range;
John Koleszar's avatar
John Koleszar committed
940

941
  cpi->target_level = oxcf->target_level;
942
  cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
943 944
  set_level_constraint(&cpi->level_constraint,
                       get_level_index(cpi->target_level));
945

946 947
  cm->width = oxcf->width;
  cm->height = oxcf->height;
948
  alloc_compressor_data(cpi);
949

950 951
  cpi->svc.temporal_layering_mode = oxcf->temporal_layering_mode;

952 953 954
  // Single thread case: use counts in common.
  cpi->td.counts = &cm->counts;

955 956 957 958 959
  // Spatial scalability.
  cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
  // Temporal scalability.
  cpi->svc.number_temporal_layers = oxcf->ts_number_layers;

960
  if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
961 962
      ((cpi->svc.number_temporal_layers > 1 ||
        cpi->svc.number_spatial_layers > 1) &&
963
       cpi->oxcf.pass != 1)) {
964
    vp9_init_layer_context(cpi);
965 966
  }

John Koleszar's avatar
John Koleszar committed
967
  // change includes all joint functionality
Dmitry Kovalev's avatar
Dmitry Kovalev committed
968
  vp9_change_config(cpi, oxcf);
John Koleszar's avatar
John Koleszar committed
969

John Koleszar's avatar
John Koleszar committed
970
  cpi->static_mb_pct = 0;
971
  cpi->ref_frame_flags = 0;
972

973
  init_buffer_indices(cpi);
974 975

  vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
John Koleszar's avatar
John Koleszar committed
976 977
}

978 979 980 981 982 983 984 985
static void set_rc_buffer_sizes(RATE_CONTROL *rc,
                                const VP9EncoderConfig *oxcf) {
  const int64_t bandwidth = oxcf->target_bandwidth;
  const int64_t starting = oxcf->starting_buffer_level_ms;
  const int64_t optimal = oxcf->optimal_buffer_level_ms;
  const int64_t maximum = oxcf->maximum_buffer_size_ms;

  rc->starting_buffer_level = starting * bandwidth / 1000;
986 987 988 989
  rc->optimal_buffer_level =
      (optimal == 0) ? bandwidth / 8 : optimal * bandwidth / 1000;
  rc->maximum_buffer_size =
      (maximum == 0) ? bandwidth / 8 : maximum * bandwidth / 1000;
990 991
}

992 993
#if CONFIG_VP9_HIGHBITDEPTH
#define HIGHBD_BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF) \
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 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 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
  cpi->fn_ptr[BT].sdf = SDF;                                           \
  cpi->fn_ptr[BT].sdaf = SDAF;                                         \
  cpi->fn_ptr[BT].vf = VF;                                             \
  cpi->fn_ptr[BT].svf = SVF;                                           \
  cpi->fn_ptr[BT].svaf = SVAF;                                         \
  cpi->fn_ptr[BT].sdx3f = SDX3F;                                       \
  cpi->fn_ptr[BT].sdx8f = SDX8F;                                       \
  cpi->fn_ptr[BT].sdx4df = SDX4DF;

#define MAKE_BFP_SAD_WRAPPER(fnname)                                           \
  static unsigned int fnname##_bits8(const uint8_t *src_ptr,                   \
                                     int source_stride,                        \
                                     const uint8_t *ref_ptr, int ref_stride) { \
    return fnname(src_ptr, source_stride, ref_ptr, ref_stride);                \
  }                                                                            \
  static unsigned int fnname##_bits10(                                         \
      const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
      int ref_stride) {                                                        \
    return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 2;           \
  }                                                                            \
  static unsigned int fnname##_bits12(                                         \
      const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
      int ref_stride) {                                                        \
    return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 4;           \
  }

#define MAKE_BFP_SADAVG_WRAPPER(fnname)                                        \
  static unsigned int fnname##_bits8(                                          \
      const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
      int ref_stride, const uint8_t *second_pred) {                            \
    return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred);   \
  }                                                                            \
  static unsigned int fnname##_bits10(                                         \
      const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
      int ref_stride, const uint8_t *second_pred) {                            \
    return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred) >> \
           2;                                                                  \
  }                                                                            \
  static unsigned int fnname##_bits12(                                         \
      const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
      int ref_stride, const uint8_t *second_pred) {                            \
    return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred) >> \
           4;                                                                  \
  }

#define MAKE_BFP_SAD3_WRAPPER(fnname)                                    \
  static void fnname##_bits8(const uint8_t *src_ptr, int source_stride,  \
                             const uint8_t *ref_ptr, int ref_stride,     \
                             unsigned int *sad_array) {                  \
    fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);      \
  }                                                                      \
  static void fnname##_bits10(const uint8_t *src_ptr, int source_stride, \
                              const uint8_t *ref_ptr, int ref_stride,    \
                              unsigned int *sad_array) {                 \
    int i;                                                               \
    fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);      \
    for (i = 0; i < 3; i++) sad_array[i] >>= 2;                          \
  }                                                                      \
  static void fnname##_bits12(const uint8_t *src_ptr, int source_stride, \
                              const uint8_t *ref_ptr, int ref_stride,    \
                              unsigned int *sad_array) {                 \
    int i;                                                               \
    fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);      \
    for (i = 0; i < 3; i++) sad_array[i] >>= 4;                          \
  }

#define MAKE_BFP_SAD8_WRAPPER(fnname)                                    \
  static void fnname##_bits8(const uint8_t *src_ptr, int source_stride,  \
                             const uint8_t *ref_ptr, int ref_stride,     \
                             unsigned int *sad_array) {                  \
    fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);      \
  }                                                                      \
  static void fnname##_bits10(const uint8_t *src_ptr, int source_stride, \
                              const uint8_t *ref_ptr, int ref_stride,    \
                              unsigned int *sad_array) {                 \
    int i;                                                               \
    fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);      \
    for (i = 0; i < 8; i++) sad_array[i] >>= 2;                          \
  }                                                                      \
  static void fnname##_bits12(const uint8_t *src_ptr, int source_stride, \
                              const uint8_t *ref_ptr, int ref_stride,    \
                              unsigned int *sad_array) {                 \
    int i;                                                               \
    fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);      \
    for (i = 0; i < 8; i++) sad_array[i] >>= 4;                          \
  }
#define MAKE_BFP_SAD4D_WRAPPER(fnname)                                        \
  static void fnname##_bits8(const uint8_t *src_ptr, int source_stride,       \
                             const uint8_t *const ref_ptr[], int ref_stride,  \
                             unsigned int *sad_array) {                       \
    fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);           \
  }                                                                           \
  static void fnname##_bits10(const uint8_t *src_ptr, int source_stride,      \
                              const uint8_t *const ref_ptr[], int ref_stride, \
                              unsigned int *sad_array) {                      \
    int i;                                                                    \
    fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);           \
    for (i = 0; i < 4; i++) sad_array[i] >>= 2;                               \
  }                                                                           \
  static void fnname##_bits12(const uint8_t *src_ptr, int source_stride,      \
                              const uint8_t *const ref_ptr[], int ref_stride, \
                              unsigned int *sad_array) {                      \
    int i;                                                                    \
    fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);           \
    for (i = 0; i < 4; i++) sad_array[i] >>= 4;                               \
  }
1100

Johann's avatar
Johann committed
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x16)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x16_avg)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x16x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x32)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x32_avg)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x32x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x32)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x32_avg)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x32x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x64)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x64_avg)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x64x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x32)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x32_avg)
MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad32x32x3)
MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad32x32x8)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x32x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x64)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x64_avg)
MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad64x64x3)
MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad64x64x8)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x64x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x16)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x16_avg)
MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x16x3)
MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x16x8)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x16x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x8)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x8_avg)
MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x8x3)
MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x8x8)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x8x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x16)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x16_avg)
MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x16x3)
MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x16x8)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x16x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x8)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x8_avg)
MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x8x3)
MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x8x8)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x8x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x4)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x4_avg)
MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x4x8)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x4x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x8)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x8_avg)
MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x8x8)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x8x4d)
MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x4)
MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x4_avg)
MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad4x4x3)
MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x4x8)
MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x4x4d)
1156

1157
static void highbd_set_var_fns(VP9_COMP *const cpi) {
1158 1159 1160 1161
  VP9_COMMON *const cm = &cpi->common;
  if (cm->use_highbitdepth) {
    switch (cm->bit_depth) {
      case VPX_BITS_8:
1162 1163
        HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits8,
                   vpx_highbd_sad32x16_avg_bits8, vpx_highbd_8_variance32x16,
1164
                   vpx_highbd_8_sub_pixel_variance32x16,
1165
                   vpx_highbd_8_sub_pixel_avg_variance32x16, NULL, NULL,
Johann's avatar
Johann committed
1166
                   vpx_highbd_sad32x16x4d_bits8)
1167

1168 1169
        HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits8,
                   vpx_highbd_sad16x32_avg_bits8, vpx_highbd_8_variance16x32,
1170
                   vpx_highbd_8_sub_pixel_variance16x32,
1171
                   vpx_highbd_8_sub_pixel_avg_variance16x32, NULL, NULL,
Johann's avatar
Johann committed
1172
                   vpx_highbd_sad16x32x4d_bits8)
1173

1174 1175
        HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits8,
                   vpx_highbd_sad64x32_avg_bits8, vpx_highbd_8_variance64x32,
1176
                   vpx_highbd_8_sub_pixel_variance64x32,
1177
                   vpx_highbd_8_sub_pixel_avg_variance64x32, NULL, NULL,
Johann's avatar
Johann committed
1178
                   vpx_highbd_sad64x32x4d_bits8)
1179

1180 1181
        HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits8,
                   vpx_highbd_sad32x64_avg_bits8, vpx_highbd_8_variance32x64,
1182
                   vpx_highbd_8_sub_pixel_variance32x64,
1183
                   vpx_highbd_8_sub_pixel_avg_variance32x64, NULL, NULL,
Johann's avatar
Johann committed
1184
                   vpx_highbd_sad32x64x4d_bits8)
1185

1186 1187
        HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits8,
                   vpx_highbd_sad32x32_avg_bits8, vpx_highbd_8_variance32x32,
1188 1189
                   vpx_highbd_8_sub_pixel_variance32x32,
                   vpx_highbd_8_sub_pixel_avg_variance32x32,
1190
                   vpx_highbd_sad32x32x3_bits8, vpx_highbd_sad32x32x8_bits8,
Johann's avatar
Johann committed
1191
                   vpx_highbd_sad32x32x4d_bits8)
1192

1193 1194
        HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits8,
                   vpx_highbd_sad64x64_avg_bits8, vpx_highbd_8_variance64x64,
1195 1196
                   vpx_highbd_8_sub_pixel_variance64x64,
                   vpx_highbd_8_sub_pixel_avg_variance64x64,
1197
                   vpx_highbd_sad64x64x3_bits8, vpx_highbd_sad64x64x8_bits8,
Johann's avatar
Johann committed
1198
                   vpx_highbd_sad64x64x4d_bits8)
1199

1200 1201
        HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits8,
                   vpx_highbd_sad16x16_avg_bits8, vpx_highbd_8_variance16x16,
1202 1203
                   vpx_highbd_8_sub_pixel_variance16x16,
                   vpx_highbd_8_sub_pixel_avg_variance16x16,
1204
                   vpx_highbd_sad16x16x3_bits8, vpx_highbd_sad16x16x8_bits8,
Johann's avatar
Johann committed
1205
                   vpx_highbd_sad16x16x4d_bits8)
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
        HIGHBD_BFP(
            BLOCK_16X8, vpx_highbd_sad16x8_bits8, vpx_highbd_sad16x8_avg_bits8,
            vpx_highbd_8_variance16x8, vpx_highbd_8_sub_pixel_variance16x8,
            vpx_highbd_8_sub_pixel_avg_variance16x8, vpx_highbd_sad16x8x3_bits8,
            vpx_highbd_sad16x8x8_bits8, vpx_highbd_sad16x8x4d_bits8)

        HIGHBD_BFP(
            BLOCK_8X16, vpx_highbd_sad8x16_bits8, vpx_highbd_sad8x16_avg_bits8,
            vpx_highbd_8_variance8x16, vpx_highbd_8_sub_pixel_variance8x16,
            vpx_highbd_8_sub_pixel_avg_variance8x16, vpx_highbd_sad8x16x3_bits8,
            vpx_highbd_sad8x16x8_bits8, vpx_highbd_sad8x16x4d_bits8)

        HIGHBD_BFP(
            BLOCK_8X8, vpx_highbd_sad8x8_bits8, vpx_highbd_sad8x8_avg_bits8,
            vpx_highbd_8_variance8x8, vpx_highbd_8_sub_pixel_variance8x8,
            vpx_highbd_8_sub_pixel_avg_variance8x8, vpx_highbd_sad8x8x3_bits8,
            vpx_highbd_sad8x8x8_bits8, vpx_highbd_sad8x8x4d_bits8)

        HIGHBD_BFP(BLOCK_8X4, vpx_highbd_sad8x4_bits8,
                   vpx_highbd_sad8x4_avg_bits8, vpx_highbd_8_variance8x4,
1227
                   vpx_highbd_8_sub_pixel_variance8x4,