vp9_encoder.c 201 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

75 76 77
#define FRAME_SIZE_FACTOR 128  // empirical params for context model threshold
#define FRAME_RATE_FACTOR 8

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

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

94 95 96 97 98 99 100 101 102 103 104
#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

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
// compute adaptive threshold for skip recoding
static int compute_context_model_thresh(const VP9_COMP *const cpi) {
  const VP9_COMMON *const cm = &cpi->common;
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
  const int frame_size = (cm->width * cm->height) >> 10;
  const int bitrate = (int)(oxcf->target_bandwidth >> 10);
  const int qindex_factor = cm->base_qindex + (MAXQ >> 1);

  // This equation makes the threshold adaptive to frame size.
  // Coding gain obtained by recoding comes from alternate frames of large
  // content change. We skip recoding if the difference of previous and current
  // frame context probability model is less than a certain threshold.
  // The first component is the most critical part to guarantee adaptivity.
  // Other parameters are estimated based on normal setting of hd resolution
  // parameters. e.g frame_size = 1920x1080, bitrate = 8000, qindex_factor < 50
  const int thresh =
      ((FRAME_SIZE_FACTOR * frame_size - FRAME_RATE_FACTOR * bitrate) *
       qindex_factor) >>
      9;

  return thresh;
}

// compute the total cost difference between current
// and previous frame context prob model.
static int compute_context_model_diff(const VP9_COMMON *const cm) {
  const FRAME_CONTEXT *const pre_fc =
      &cm->frame_contexts[cm->frame_context_idx];
  const FRAME_CONTEXT *const cur_fc = cm->fc;
  const FRAME_COUNTS *counts = &cm->counts;
  vpx_prob pre_last_prob, cur_last_prob;
  int diff = 0;
  int i, j, k, l, m, n;

  // y_mode_prob
  for (i = 0; i < BLOCK_SIZE_GROUPS; ++i) {
    for (j = 0; j < INTRA_MODES - 1; ++j) {
      diff += (int)counts->y_mode[i][j] *
              (pre_fc->y_mode_prob[i][j] - cur_fc->y_mode_prob[i][j]);
    }
    pre_last_prob = MAX_PROB - pre_fc->y_mode_prob[i][INTRA_MODES - 2];
    cur_last_prob = MAX_PROB - cur_fc->y_mode_prob[i][INTRA_MODES - 2];

    diff += (int)counts->y_mode[i][INTRA_MODES - 1] *
            (pre_last_prob - cur_last_prob);
  }

  // uv_mode_prob
  for (i = 0; i < INTRA_MODES; ++i) {
    for (j = 0; j < INTRA_MODES - 1; ++j) {
      diff += (int)counts->uv_mode[i][j] *
              (pre_fc->uv_mode_prob[i][j] - cur_fc->uv_mode_prob[i][j]);
    }
    pre_last_prob = MAX_PROB - pre_fc->uv_mode_prob[i][INTRA_MODES - 2];
    cur_last_prob = MAX_PROB - cur_fc->uv_mode_prob[i][INTRA_MODES - 2];

    diff += (int)counts->uv_mode[i][INTRA_MODES - 1] *
            (pre_last_prob - cur_last_prob);
  }

  // partition_prob
  for (i = 0; i < PARTITION_CONTEXTS; ++i) {
    for (j = 0; j < PARTITION_TYPES - 1; ++j) {
      diff += (int)counts->partition[i][j] *
              (pre_fc->partition_prob[i][j] - cur_fc->partition_prob[i][j]);
    }
    pre_last_prob = MAX_PROB - pre_fc->partition_prob[i][PARTITION_TYPES - 2];
    cur_last_prob = MAX_PROB - cur_fc->partition_prob[i][PARTITION_TYPES - 2];

    diff += (int)counts->partition[i][PARTITION_TYPES - 1] *
            (pre_last_prob - cur_last_prob);
  }

  // coef_probs
  for (i = 0; i < TX_SIZES; ++i) {
    for (j = 0; j < PLANE_TYPES; ++j) {
      for (k = 0; k < REF_TYPES; ++k) {
        for (l = 0; l < COEF_BANDS; ++l) {
          for (m = 0; m < BAND_COEFF_CONTEXTS(l); ++m) {
            for (n = 0; n < UNCONSTRAINED_NODES; ++n) {
              diff += (int)counts->coef[i][j][k][l][m][n] *
                      (pre_fc->coef_probs[i][j][k][l][m][n] -
                       cur_fc->coef_probs[i][j][k][l][m][n]);
            }

            pre_last_prob =
                MAX_PROB -
                pre_fc->coef_probs[i][j][k][l][m][UNCONSTRAINED_NODES - 1];
            cur_last_prob =
                MAX_PROB -
                cur_fc->coef_probs[i][j][k][l][m][UNCONSTRAINED_NODES - 1];

            diff += (int)counts->coef[i][j][k][l][m][UNCONSTRAINED_NODES] *
                    (pre_last_prob - cur_last_prob);
          }
        }
      }
    }
  }

  // switchable_interp_prob
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) {
    for (j = 0; j < SWITCHABLE_FILTERS - 1; ++j) {
      diff += (int)counts->switchable_interp[i][j] *
              (pre_fc->switchable_interp_prob[i][j] -
               cur_fc->switchable_interp_prob[i][j]);
    }
    pre_last_prob =
        MAX_PROB - pre_fc->switchable_interp_prob[i][SWITCHABLE_FILTERS - 2];
    cur_last_prob =
        MAX_PROB - cur_fc->switchable_interp_prob[i][SWITCHABLE_FILTERS - 2];

    diff += (int)counts->switchable_interp[i][SWITCHABLE_FILTERS - 1] *
            (pre_last_prob - cur_last_prob);
  }

  // inter_mode_probs
  for (i = 0; i < INTER_MODE_CONTEXTS; ++i) {
    for (j = 0; j < INTER_MODES - 1; ++j) {
      diff += (int)counts->inter_mode[i][j] *
              (pre_fc->inter_mode_probs[i][j] - cur_fc->inter_mode_probs[i][j]);
    }
    pre_last_prob = MAX_PROB - pre_fc->inter_mode_probs[i][INTER_MODES - 2];
    cur_last_prob = MAX_PROB - cur_fc->inter_mode_probs[i][INTER_MODES - 2];

    diff += (int)counts->inter_mode[i][INTER_MODES - 1] *
            (pre_last_prob - cur_last_prob);
  }

  // intra_inter_prob
  for (i = 0; i < INTRA_INTER_CONTEXTS; ++i) {
    diff += (int)counts->intra_inter[i][0] *
            (pre_fc->intra_inter_prob[i] - cur_fc->intra_inter_prob[i]);

    pre_last_prob = MAX_PROB - pre_fc->intra_inter_prob[i];
    cur_last_prob = MAX_PROB - cur_fc->intra_inter_prob[i];

    diff += (int)counts->intra_inter[i][1] * (pre_last_prob - cur_last_prob);
  }

  // comp_inter_prob
  for (i = 0; i < COMP_INTER_CONTEXTS; ++i) {
    diff += (int)counts->comp_inter[i][0] *
            (pre_fc->comp_inter_prob[i] - cur_fc->comp_inter_prob[i]);

    pre_last_prob = MAX_PROB - pre_fc->comp_inter_prob[i];
    cur_last_prob = MAX_PROB - cur_fc->comp_inter_prob[i];

    diff += (int)counts->comp_inter[i][1] * (pre_last_prob - cur_last_prob);
  }

  // single_ref_prob
  for (i = 0; i < REF_CONTEXTS; ++i) {
    for (j = 0; j < 2; ++j) {
      diff += (int)counts->single_ref[i][j][0] *
              (pre_fc->single_ref_prob[i][j] - cur_fc->single_ref_prob[i][j]);

      pre_last_prob = MAX_PROB - pre_fc->single_ref_prob[i][j];
      cur_last_prob = MAX_PROB - cur_fc->single_ref_prob[i][j];

      diff +=
          (int)counts->single_ref[i][j][1] * (pre_last_prob - cur_last_prob);
    }
  }

  // comp_ref_prob
  for (i = 0; i < REF_CONTEXTS; ++i) {
    diff += (int)counts->comp_ref[i][0] *
            (pre_fc->comp_ref_prob[i] - cur_fc->comp_ref_prob[i]);

    pre_last_prob = MAX_PROB - pre_fc->comp_ref_prob[i];
    cur_last_prob = MAX_PROB - cur_fc->comp_ref_prob[i];

    diff += (int)counts->comp_ref[i][1] * (pre_last_prob - cur_last_prob);
  }

  // tx_probs
  for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
    // p32x32
    for (j = 0; j < TX_SIZES - 1; ++j) {
      diff += (int)counts->tx.p32x32[i][j] *
              (pre_fc->tx_probs.p32x32[i][j] - cur_fc->tx_probs.p32x32[i][j]);
    }
    pre_last_prob = MAX_PROB - pre_fc->tx_probs.p32x32[i][TX_SIZES - 2];
    cur_last_prob = MAX_PROB - cur_fc->tx_probs.p32x32[i][TX_SIZES - 2];

    diff += (int)counts->tx.p32x32[i][TX_SIZES - 1] *
            (pre_last_prob - cur_last_prob);

    // p16x16
    for (j = 0; j < TX_SIZES - 2; ++j) {
      diff += (int)counts->tx.p16x16[i][j] *
              (pre_fc->tx_probs.p16x16[i][j] - cur_fc->tx_probs.p16x16[i][j]);
    }
    pre_last_prob = MAX_PROB - pre_fc->tx_probs.p16x16[i][TX_SIZES - 3];
    cur_last_prob = MAX_PROB - cur_fc->tx_probs.p16x16[i][TX_SIZES - 3];

    diff += (int)counts->tx.p16x16[i][TX_SIZES - 2] *
            (pre_last_prob - cur_last_prob);

    // p8x8
    for (j = 0; j < TX_SIZES - 3; ++j) {
      diff += (int)counts->tx.p8x8[i][j] *
              (pre_fc->tx_probs.p8x8[i][j] - cur_fc->tx_probs.p8x8[i][j]);
    }
    pre_last_prob = MAX_PROB - pre_fc->tx_probs.p8x8[i][TX_SIZES - 4];
    cur_last_prob = MAX_PROB - cur_fc->tx_probs.p8x8[i][TX_SIZES - 4];

    diff +=
        (int)counts->tx.p8x8[i][TX_SIZES - 3] * (pre_last_prob - cur_last_prob);
  }

  // skip_probs
  for (i = 0; i < SKIP_CONTEXTS; ++i) {
    diff += (int)counts->skip[i][0] *
            (pre_fc->skip_probs[i] - cur_fc->skip_probs[i]);

    pre_last_prob = MAX_PROB - pre_fc->skip_probs[i];
    cur_last_prob = MAX_PROB - cur_fc->skip_probs[i];

    diff += (int)counts->skip[i][1] * (pre_last_prob - cur_last_prob);
  }

  // mv
  for (i = 0; i < MV_JOINTS - 1; ++i) {
    diff += (int)counts->mv.joints[i] *
            (pre_fc->nmvc.joints[i] - cur_fc->nmvc.joints[i]);
  }
  pre_last_prob = MAX_PROB - pre_fc->nmvc.joints[MV_JOINTS - 2];
  cur_last_prob = MAX_PROB - cur_fc->nmvc.joints[MV_JOINTS - 2];

  diff +=
      (int)counts->mv.joints[MV_JOINTS - 1] * (pre_last_prob - cur_last_prob);

  for (i = 0; i < 2; ++i) {
    const nmv_component_counts *nmv_count = &counts->mv.comps[i];
    const nmv_component *pre_nmv_prob = &pre_fc->nmvc.comps[i];
    const nmv_component *cur_nmv_prob = &cur_fc->nmvc.comps[i];

    // sign
    diff += (int)nmv_count->sign[0] * (pre_nmv_prob->sign - cur_nmv_prob->sign);

    pre_last_prob = MAX_PROB - pre_nmv_prob->sign;
    cur_last_prob = MAX_PROB - cur_nmv_prob->sign;

    diff += (int)nmv_count->sign[1] * (pre_last_prob - cur_last_prob);

    // classes
    for (j = 0; j < MV_CLASSES - 1; ++j) {
      diff += (int)nmv_count->classes[j] *
              (pre_nmv_prob->classes[j] - cur_nmv_prob->classes[j]);
    }
    pre_last_prob = MAX_PROB - pre_nmv_prob->classes[MV_CLASSES - 2];
    cur_last_prob = MAX_PROB - cur_nmv_prob->classes[MV_CLASSES - 2];

    diff += (int)nmv_count->classes[MV_CLASSES - 1] *
            (pre_last_prob - cur_last_prob);

    // class0
    for (j = 0; j < CLASS0_SIZE - 1; ++j) {
      diff += (int)nmv_count->class0[j] *
              (pre_nmv_prob->class0[j] - cur_nmv_prob->class0[j]);
    }
    pre_last_prob = MAX_PROB - pre_nmv_prob->class0[CLASS0_SIZE - 2];
    cur_last_prob = MAX_PROB - cur_nmv_prob->class0[CLASS0_SIZE - 2];

    diff += (int)nmv_count->class0[CLASS0_SIZE - 1] *
            (pre_last_prob - cur_last_prob);

    // bits
    for (j = 0; j < MV_OFFSET_BITS; ++j) {
      diff += (int)nmv_count->bits[j][0] *
              (pre_nmv_prob->bits[j] - cur_nmv_prob->bits[j]);

      pre_last_prob = MAX_PROB - pre_nmv_prob->bits[j];
      cur_last_prob = MAX_PROB - cur_nmv_prob->bits[j];

      diff += (int)nmv_count->bits[j][1] * (pre_last_prob - cur_last_prob);
    }

    // class0_fp
    for (j = 0; j < CLASS0_SIZE; ++j) {
      for (k = 0; k < MV_FP_SIZE - 1; ++k) {
        diff += (int)nmv_count->class0_fp[j][k] *
                (pre_nmv_prob->class0_fp[j][k] - cur_nmv_prob->class0_fp[j][k]);
      }
      pre_last_prob = MAX_PROB - pre_nmv_prob->class0_fp[j][MV_FP_SIZE - 2];
      cur_last_prob = MAX_PROB - cur_nmv_prob->class0_fp[j][MV_FP_SIZE - 2];

      diff += (int)nmv_count->class0_fp[j][MV_FP_SIZE - 1] *
              (pre_last_prob - cur_last_prob);
    }

    // fp
    for (j = 0; j < MV_FP_SIZE - 1; ++j) {
      diff +=
          (int)nmv_count->fp[j] * (pre_nmv_prob->fp[j] - cur_nmv_prob->fp[j]);
    }
    pre_last_prob = MAX_PROB - pre_nmv_prob->fp[MV_FP_SIZE - 2];
    cur_last_prob = MAX_PROB - cur_nmv_prob->fp[MV_FP_SIZE - 2];

    diff +=
        (int)nmv_count->fp[MV_FP_SIZE - 1] * (pre_last_prob - cur_last_prob);

    // class0_hp
    diff += (int)nmv_count->class0_hp[0] *
            (pre_nmv_prob->class0_hp - cur_nmv_prob->class0_hp);

    pre_last_prob = MAX_PROB - pre_nmv_prob->class0_hp;
    cur_last_prob = MAX_PROB - cur_nmv_prob->class0_hp;

    diff += (int)nmv_count->class0_hp[1] * (pre_last_prob - cur_last_prob);

    // hp
    diff += (int)nmv_count->hp[0] * (pre_nmv_prob->hp - cur_nmv_prob->hp);

    pre_last_prob = MAX_PROB - pre_nmv_prob->hp;
    cur_last_prob = MAX_PROB - cur_nmv_prob->hp;

    diff += (int)nmv_count->hp[1] * (pre_last_prob - cur_last_prob);
  }

  return -diff;
}

430 431 432 433 434 435 436 437
// 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;
}

438
/* clang-format off */
439
const Vp9LevelSpec vp9_level_defs[VP9_LEVELS] = {
440 441 442 443 444 445 446 447 448 449 450
  //         sample rate    size   breadth  bitrate  cpb
  { LEVEL_1,   829440,      36864,    512,   200,    400,    2, 1,  4,  8 },
  { LEVEL_1_1, 2764800,     73728,    768,   800,    1000,   2, 1,  4,  8 },
  { LEVEL_2,   4608000,     122880,   960,   1800,   1500,   2, 1,  4,  8 },
  { LEVEL_2_1, 9216000,     245760,   1344,  3600,   2800,   2, 2,  4,  8 },
  { LEVEL_3,   20736000,    552960,   2048,  7200,   6000,   2, 4,  4,  8 },
  { LEVEL_3_1, 36864000,    983040,   2752,  12000,  10000,  2, 4,  4,  8 },
  { LEVEL_4,   83558400,    2228224,  4160,  18000,  16000,  4, 4,  4,  8 },
  { LEVEL_4_1, 160432128,   2228224,  4160,  30000,  18000,  4, 4,  5,  6 },
  { LEVEL_5,   311951360,   8912896,  8384,  60000,  36000,  6, 8,  6,  4 },
  { LEVEL_5_1, 588251136,   8912896,  8384,  120000, 46000,  8, 8,  10, 4 },
451
  // TODO(huisu): update max_cpb_size for level 5_2 ~ 6_2 when
452
  // they are finalized (currently tentative).
453 454 455 456
  { LEVEL_5_2, 1176502272,  8912896,  8384,  180000, 90000,  8, 8,  10, 4 },
  { LEVEL_6,   1176502272,  35651584, 16832, 180000, 90000,  8, 16, 10, 4 },
  { LEVEL_6_1, 2353004544u, 35651584, 16832, 240000, 180000, 8, 16, 10, 4 },
  { LEVEL_6_2, 4706009088u, 35651584, 16832, 480000, 360000, 8, 16, 10, 4 },
457
};
458
/* clang-format on */
459

460 461 462 463 464 465 466 467 468 469 470
static const char *level_fail_messages[TARGET_LEVEL_FAIL_IDS] = {
  "The average bit-rate is too high.",
  "The picture size is too large.",
  "The picture width/height 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."
};
471

472
static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
473 474 475 476 477 478 479 480 481 482 483 484
  switch (mode) {
    case NORMAL:
      *hr = 1;
      *hs = 1;
      break;
    case FOURFIVE:
      *hr = 4;
      *hs = 5;
      break;
    case THREEFIVE:
      *hr = 3;
      *hs = 5;
485
      break;
486 487 488
    case ONETWO:
      *hr = 1;
      *hs = 2;
489
      break;
490 491 492
    default:
      *hr = 1;
      *hs = 1;
493
      assert(0);
494 495 496 497
      break;
  }
}

498 499
// Mark all inactive blocks as active. Other segmentation features may be set
// so memset cannot be used, instead only inactive blocks should be reset.
500
static void suppress_active_map(VP9_COMP *cpi) {
501
  unsigned char *const seg_map = cpi->segmentation_map;
502 503 504 505 506 507 508

  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)
509 510
      if (seg_map[i] == AM_SEGMENT_ID_INACTIVE)
        seg_map[i] = AM_SEGMENT_ID_ACTIVE;
511
  }
512 513
}

514
static void apply_active_map(VP9_COMP *cpi) {
515 516 517 518 519 520 521
  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);

522 523 524 525 526
  if (frame_is_intra_only(&cpi->common)) {
    cpi->active_map.enabled = 0;
    cpi->active_map.update = 1;
  }

527 528 529 530 531 532
  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);
533 534 535
      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.
536 537
      vp9_set_segdata(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF,
                      -MAX_LOOP_FILTER);
538 539
    } else {
      vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
540
      vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
541 542 543 544 545 546 547 548 549
      if (seg->enabled) {
        seg->update_data = 1;
        seg->update_map = 1;
      }
    }
    cpi->active_map.update = 0;
  }
}

550 551 552 553 554 555 556 557 558 559
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;
}

560
VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec) {
561 562 563 564 565 566 567
  int i;
  const Vp9LevelSpec *this_level;

  vpx_clear_system_state();

  for (i = 0; i < VP9_LEVELS; ++i) {
    this_level = &vp9_level_defs[i];
568 569 570
    if ((double)level_spec->max_luma_sample_rate >
            (double)this_level->max_luma_sample_rate *
                (1 + SAMPLE_RATE_GRACE_P) ||
571
        level_spec->max_luma_picture_size > this_level->max_luma_picture_size ||
572 573
        level_spec->max_luma_picture_breadth >
            this_level->max_luma_picture_breadth ||
574 575 576 577 578 579 580 581 582 583 584 585
        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;
}

586
int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
                       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;
  }
}

613
int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
614 615 616
                       int cols) {
  if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols &&
      new_map_16x16) {
617
    unsigned char *const seg_map_8x8 = cpi->segmentation_map;
618 619
    const int mi_rows = cpi->common.mi_rows;
    const int mi_cols = cpi->common.mi_cols;
James Zern's avatar
James Zern committed
620
    memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
    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;
  }
}

638
void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
639
  MACROBLOCK *const mb = &cpi->td.mb;
640
  cpi->common.allow_high_precision_mv = allow_high_precision_mv;
641
  if (cpi->common.allow_high_precision_mv) {
642 643 644 645 646 647 648
    mb->mvcost = mb->nmvcost_hp;
    mb->mvsadcost = mb->nmvsadcost_hp;
  } else {
    mb->mvcost = mb->nmvcost;
    mb->mvsadcost = mb->nmvsadcost;
  }
}
649

650 651 652 653 654 655 656
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.
657 658 659
  if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
    vp9_setup_past_independence(cm);
  } else {
660
    if (!cpi->use_svc) cm->frame_context_idx = cpi->refresh_alt_ref_frame;
661 662
  }

663
  if (cm->frame_type == KEY_FRAME) {
664
    if (!is_two_pass_svc(cpi)) cpi->refresh_golden_frame = 1;
665
    cpi->refresh_alt_ref_frame = 1;
666
    vp9_zero(cpi->interp_filter_selected);
667
  } else {
668
    *cm->fc = cm->frame_contexts[cm->frame_context_idx];
669
    vp9_zero(cpi->interp_filter_selected[0]);
670 671 672
  }
}

673 674 675
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
676
  memset(cm->mip, 0, cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mip));
677 678
  cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
  // Clear top border row
James Zern's avatar
James Zern committed
679
  memset(cm->prev_mip, 0, sizeof(*cm->prev_mip) * cm->mi_stride);
680 681
  // Clear left border column
  for (i = 1; i < cm->mi_rows + 1; ++i)
James Zern's avatar
James Zern committed
682
    memset(&cm->prev_mip[i * cm->mi_stride], 0, sizeof(*cm->prev_mip));
683 684 685 686

  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
687 688
  memset(cm->mi_grid_base, 0,
         cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mi_grid_base));
689 690 691 692
}

static int vp9_enc_alloc_mi(VP9_COMMON *cm, int mi_size) {
  cm->mip = vpx_calloc(mi_size, sizeof(*cm->mip));
693
  if (!cm->mip) return 1;
694
  cm->prev_mip = vpx_calloc(mi_size, sizeof(*cm->prev_mip));
695
  if (!cm->prev_mip) return 1;
696
  cm->mi_alloc_size = mi_size;
697

698 699 700 701 702
  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;
703

704 705 706 707 708 709 710 711
  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;
712 713 714 715
  vpx_free(cm->mi_grid_base);
  cm->mi_grid_base = NULL;
  vpx_free(cm->prev_mi_grid_base);
  cm->prev_mi_grid_base = NULL;
716 717 718 719
}

static void vp9_swap_mi_and_prev_mi(VP9_COMMON *cm) {
  // Current mip will be the prev_mip for the next frame.
720
  MODE_INFO **temp_base = cm->prev_mi_grid_base;
721 722 723 724 725 726 727
  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;
728 729 730 731 732

  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;
733 734
}

735
void vp9_initialize_enc(void) {
736
  static volatile int init_done = 0;
John Koleszar's avatar
John Koleszar committed
737 738

  if (!init_done) {
739
    vp9_rtcd();
Johann's avatar
Johann committed
740
    vpx_dsp_rtcd();
741
    vpx_scale_rtcd();
742
    vp9_init_intra_predictors();
743
    vp9_init_me_luts();
744
    vp9_rc_init_minq_luts();
745
    vp9_entropy_mv_init();
746
#if !CONFIG_REALTIME_ONLY
747
    vp9_temporal_filter_init();
748
#endif
John Koleszar's avatar
John Koleszar committed
749 750
    init_done = 1;
  }
John Koleszar's avatar
John Koleszar committed
751 752
}

753
static void dealloc_compressor_data(VP9_COMP *cpi) {
754
  VP9_COMMON *const cm = &cpi->common;
755
  int i;
756

757 758 759
  vpx_free(cpi->mbmi_ext_base);
  cpi->mbmi_ext_base = NULL;

760 761
  vpx_free(cpi->tile_data);
  cpi->tile_data = NULL;
762

John Koleszar's avatar
John Koleszar committed
763
  vpx_free(cpi->segmentation_map);
764
  cpi->segmentation_map = NULL;
John Koleszar's avatar
John Koleszar committed
765
  vpx_free(cpi->coding_context.last_frame_seg_map_copy);
766
  cpi->coding_context.last_frame_seg_map_copy = NULL;
John Koleszar's avatar
John Koleszar committed
767

768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
  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;

788 789 790
  vpx_free(cpi->skin_map);
  cpi->skin_map = NULL;

791 792 793
  vpx_free(cpi->prev_partition);
  cpi->prev_partition = NULL;

794 795 796
  vpx_free(cpi->svc.prev_partition_svc);
  cpi->svc.prev_partition_svc = NULL;

797 798 799
  vpx_free(cpi->prev_segment_id);
  cpi->prev_segment_id = NULL;

800 801 802
  vpx_free(cpi->prev_variance_low);
  cpi->prev_variance_low = NULL;

803 804 805
  vpx_free(cpi->copied_frame_cnt);
  cpi->copied_frame_cnt = NULL;

806 807 808
  vpx_free(cpi->content_state_sb_fd);
  cpi->content_state_sb_fd = NULL;

809 810 811 812 813
  vpx_free(cpi->count_arf_frame_usage);
  cpi->count_arf_frame_usage = NULL;
  vpx_free(cpi->count_lastgolden_frame_usage);
  cpi->count_lastgolden_frame_usage = NULL;

814 815 816
  vp9_cyclic_refresh_free(cpi->cyclic_refresh);
  cpi->cyclic_refresh = NULL;

817 818 819
  vpx_free(cpi->active_map.map);
  cpi->active_map.map = NULL;

820 821 822
  vpx_free(cpi->consec_zero_mv);
  cpi->consec_zero_mv = NULL;

823 824 825 826
  vp9_free_ref_frame_buffers(cm->buffer_pool);
#if CONFIG_VP9_POSTPROC
  vp9_free_postproc_buffers(cm);
#endif
827
  vp9_free_context_buffers(cm);
John Koleszar's avatar
John Koleszar committed
828

829 830 831 832
  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);
833 834 835 836 837
#ifdef ENABLE_KF_DENOISE
  vpx_free_frame_buffer(&cpi->raw_unscaled_source);
  vpx_free_frame_buffer(&cpi->raw_scaled_source);
#endif

838
  vp9_lookahead_destroy(cpi->lookahead);
John Koleszar's avatar
John Koleszar committed
839

840 841
  vpx_free(cpi->tile_tok[0][0]);
  cpi->tile_tok[0][0] = 0;
John Koleszar's avatar
John Koleszar committed
842

843 844 845
  vpx_free(cpi->tplist[0][0]);
  cpi->tplist[0][0] = NULL;

846
  vp9_free_pc_tree(&cpi->td);
847

848 849 850 851 852 853
  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;
  }
854 855 856 857 858

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

860
  for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
861
    vpx_free_frame_buffer(&cpi->svc.scaled_frames[i]);
862
  }
James Zern's avatar
James Zern committed
863 864
  memset(&cpi->svc.scaled_frames[0], 0,
         MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
865

866 867 868
  vpx_free_frame_buffer(&cpi->svc.scaled_temp);
  memset(&cpi->svc.scaled_temp, 0, sizeof(cpi->svc.scaled_temp));

869
  vpx_free_frame_buffer(&cpi->svc.empty_frame.img);
James Zern's avatar
James Zern committed
870
  memset(&cpi->svc.empty_frame, 0, sizeof(cpi->svc.empty_frame));
871 872

  vp9_free_svc_cyclic_refresh(cpi);
John Koleszar's avatar
John Koleszar committed
873 874
}

875 876 877 878 879 880 881 882
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.
883
  vp9_copy(cc->nmvjointcost, cpi->td.mb.nmvjointcost);
884

James Zern's avatar
James Zern committed
885 886 887 888 889 890 891 892
  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]));
893 894 895

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

896 897
  memcpy(cpi->coding_context.last_frame_seg_map_copy, cm->last_frame_seg_map,
         (cm->mi_rows * cm->mi_cols));
898 899 900 901

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

902
  cc->fc = *cm->fc;
903 904 905 906 907 908 909 910
}

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.
911
  vp9_copy(cpi->td.mb.nmvjointcost, cc->nmvjointcost);
912

James Zern's avatar
James Zern committed
913 914 915 916 917 918
  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]));
919 920 921

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

922
  memcpy(cm->last_frame_seg_map, cpi->coding_context.last_frame_seg_map_copy,
James Zern's avatar
James Zern committed
923
         (cm->mi_rows * cm->mi_cols));
924 925 926 927

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

928
  *cm->fc = cc->fc;
929 930
}

931
#if !CONFIG_REALTIME_ONLY
932
static void configure_static_seg_features(VP9_COMP *cpi) {
933
  VP9_COMMON *const cm = &cpi->common;
934
  const RATE_CONTROL *const rc = &cpi->rc;
935
  struct segmentation *const seg = &cm->seg;
936

937
  int high_q = (int)(rc->avg_q > 48.0);
John Koleszar's avatar
John Koleszar committed
938
  int qi_delta;
939

John Koleszar's avatar
John Koleszar committed
940 941 942
  // 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
943
    memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
944 945
    seg->update_map = 0;
    seg->update_data = 0;
John Koleszar's avatar
John Koleszar committed
946
    cpi->static_mb_pct = 0;
947

John Koleszar's avatar
John Koleszar committed
948
    // Disable segmentation
949
    vp9_disable_segmentation(seg);
Paul Wilkins's avatar
Paul Wilkins committed
950

John Koleszar's avatar
John Koleszar committed
951
    // Clear down the segment features.
952
    vp9_clearall_segfeatures(seg);
953 954
  } else if (cpi->refresh_alt_ref_frame) {
    // If this is an alt ref frame
John Koleszar's avatar
John Koleszar committed
955
    // Clear down the global segmentation map
James Zern's avatar
James Zern committed
956
    memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
957 958
    seg->update_map = 0;
    seg->update_data = 0;
John Koleszar's avatar
John Koleszar committed
959
    cpi->static_mb_pct = 0;
Paul Wilkins's avatar
Paul Wilkins committed
960

John Koleszar's avatar
John Koleszar committed
961
    // Disable segmentation and individual segment features by default
962
    vp9_disable_segmentation(seg);
963
    vp9_clearall_segfeatures(seg);
Paul Wilkins's avatar
Paul Wilkins committed
964

John Koleszar's avatar
John Koleszar committed
965 966
    // Scan frames from current to arf frame.
    // This function re-enables segmentation if appropriate.
967
    vp9_update_mbgraph_stats(cpi);
Paul Wilkins's avatar
Paul Wilkins committed
968

John Koleszar's avatar
John Koleszar committed
969 970
    // If segmentation was enabled set those features needed for the
    // arf itself.
971 972 973
    if (seg->enabled) {
      seg->update_map = 1;
      seg->update_data = 1;
Paul Wilkins's avatar
Paul Wilkins committed
974

975 976
      qi_delta =
          vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875, cm->bit_depth);
977
      vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
978
      vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
Paul Wilkins's avatar
Paul Wilkins committed
979

980 981
      vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
      vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
982

John Koleszar's avatar
John Koleszar committed
983
      // Where relevant assume segment data is delta data
984
      seg->abs_delta = SEGMENT_DELTADATA;
985
    }
986
  } else if (seg->enabled) {
987 988
    // All other frames if segmentation has been enabled

John Koleszar's avatar
John Koleszar committed
989
    // First normal frame in a valid gf or alt ref group
990
    if (rc->frames_since_golden == 0) {
Paul Wilkins's avatar
Paul Wilkins committed
991
      // Set up segment features for normal frames in an arf group
992
      if (rc->source_alt_ref_active) {
993 994 995
        seg->update_map = 0;
        seg->update_data = 1;
        seg->abs_delta = SEGMENT_DELTADATA;
996

997 998
        qi_delta =
            vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125, cm->bit_depth);
999
        vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
1000
        vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
Paul Wilkins's avatar
Paul Wilkins committed
1001

1002 1003
        vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
        vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
1004

John Koleszar's avatar
John Koleszar committed
1005 1006
        // Segment coding disabled for compred testing
        if (high_q || (cpi->static_mb_pct == 100)) {
1007 1008 1009
          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
1010
        }
1011 1012 1013 1014
      } else {
        // Disable segmentation and clear down features if alt ref
        // is not active for this group

1015
        vp9_disable_segmentation(seg);
Paul Wilkins's avatar
Paul Wilkins committed
1016

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

1019 1020
        seg->update_map = 0;
        seg->update_data = 0;
Paul Wilkins's avatar
Paul Wilkins committed
1021

1022
        vp9_clearall_segfeatures(seg);
John Koleszar's avatar
John Koleszar committed
1023
      }
1024
    } else if (rc->is_src_frame_alt_ref) {
1025 1026 1027
      // 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
1028

Paul Wilkins's avatar
Paul Wilkins committed
1029
      // Enable ref frame features for segment 0 as well
1030 1031
      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
1032

Paul Wilkins's avatar
Paul Wilkins committed
1033
      // All mbs should use ALTREF_FRAME
1034 1035 1036 1037
      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
1038

Paul Wilkins's avatar
Paul Wilkins committed
1039
      // Skip all MBs if high Q (0,0 mv and skip coeffs)
John Koleszar's avatar
John Koleszar committed
1040
      if (high_q) {
1041 1042
        vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
        vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
John Koleszar's avatar
John Koleszar committed
1043
      }
1044
      // Enable data update
1045
      seg->update_data = 1;
1046 1047 1048
    } else {
      // All other frames.

John Koleszar's avatar
John Koleszar committed
1049
      // No updates.. leave things as they are.
1050 1051
      seg->update_map = 0;
      seg->update_data = 0;
John Koleszar's avatar
John Koleszar committed
1052 1053
    }
  }
1054
}
1055
#endif  // !CONFIG_REALTIME_ONLY
1056

1057
static void update_reference_segmentation_map(VP9_COMP *cpi) {
1058
  VP9_COMMON *const cm = &cpi->common;
1059
  MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
1060
  uint8_t *cache_ptr = cm->last_frame_seg_map;
1061 1062
  int row, col;

1063
  for (row = 0; row < cm->mi_rows; row++) {
1064
    MODE_INFO **mi_8x8 = mi_8x8_ptr;
1065
    uint8_t *cache = cache_ptr;
1066
    for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
1067
      cache[0] = mi_8x8[0]->segment_id;
1068
    mi_8x8_ptr += cm->mi_stride;
1069
    cache_ptr += cm->mi_cols;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
1070 1071 1072
  }
}

1073
static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
1074
  VP9_COMMON *cm = &cpi->common;
1075
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
1076

1077 1078 1079
  if (!cpi->lookahead)
    cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
                                        cm->subsampling_x, cm->subsampling_y,
1080
#if CONFIG_VP9_HIGHBITDEPTH
1081
                                        cm->use_highbitdepth,
1082
#endif
1083
                                        oxcf->lag_in_frames);
John Koleszar's avatar
John Koleszar committed
1084
  if (!cpi->lookahead)
1085
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
John Koleszar's avatar
John Koleszar committed
1086
                       "Failed to allocate lag buffers");
John Koleszar's avatar
John Koleszar committed
1087

1088
  // TODO(agrange) Check if ARF is enabled and skip allocation if not.
1089
  if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, oxcf->width, oxcf->height,
1090
                               cm->subsampling_x, cm->subsampling_y,
1091 1092 1093
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
1094 1095
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
1096
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
John Koleszar's avatar
John Koleszar committed
1097
                       "Failed to allocate altref buffer");
John Koleszar's avatar
John Koleszar committed
1098
}
1099

1100
static void alloc_util_frame_buffers(VP9_COMP *cpi) {
1101
  VP9_COMMON *const cm = &cpi->common;
1102
  if (vpx_realloc_frame_buffer(&cpi->last_frame_uf, cm->width, cm->height,
1103
                               cm->subsampling_x, cm->subsampling_y,
1104 1105 1106
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
1107 1108
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
1109
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1110
                       "Failed to allocate last frame buffer");
1111

1112
  if (vpx_realloc_frame_buffer(&cpi->scaled_source, cm->width, cm->height,
1113
                               cm->subsampling_x, cm->subsampling_y,
1114 1115 1116
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
1117 1118
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
1119
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1120
                       "Failed to allocate scaled source buffer");
1121

1122 1123 1124 1125 1126
  // 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;
1127 1128 1129
    if (vpx_realloc_frame_buffer(
            &cpi->svc.scaled_temp, cm->width >> 1, cm->height >> 1,
            cm->subsampling_x, cm->subsampling_y,
1130
#if CONFIG_VP9_HIGHBITDEPTH
1131
            cm->use_highbitdepth,
1132
#endif
1133
            VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment, NULL, NULL, NULL))
1134 1135 1136 1137
      vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
                         "Failed to allocate scaled_frame for svc ");
  }

1138
  if (vpx_realloc_frame_buffer(&cpi->scaled_last_source, cm->width, cm->height,
1139
                               cm->subsampling_x, cm->subsampling_y,
1140 1141 1142
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
1143 1144
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
1145
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1146
                       "Failed to allocate scaled last source buffer");
1147
#ifdef ENABLE_KF_DENOISE
1148
  if (vpx_realloc_frame_buffer(&cpi->raw_unscaled_source, cm->width, cm->height,
1149 1150 1151 1152 1153 1154 1155 1156 1157
                               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");

1158
  if (vpx_realloc_frame_buffer(&cpi->raw_scaled_source, cm->width, cm->height,
1159 1160 1161 1162 1163 1164 1165 1166 1167
                               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
1168
}
1169

1170 1171 1172 1173 1174
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));
1175
  if (!cpi->mbmi_ext_base) return 1;
1176 1177 1178 1179

  return 0;
}

1180
static void alloc_compressor_data(VP9_COMP *cpi) {
1181
  VP9_COMMON *cm = &cpi->common;
1182
  int sb_rows;
1183

1184 1185
  vp9_alloc_context_buffers(cm, cm->width, cm->height);

1186 1187
  alloc_context_buffers_ext(cpi);

1188
  vpx_free(cpi->tile_tok[0][0]);
1189 1190 1191

  {
    unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
1192
    CHECK_MEM_ERROR(cm, cpi->tile_tok[0][0],
1193
                    vpx_calloc(tokens, sizeof(*cpi->tile_tok[0][0])));
1194
  }
1195

1196 1197 1198 1199 1200 1201
  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])));

1202
  vp9_setup_pc_tree(&cpi->common, &cpi->td);
1203 1204
}

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
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);

1216 1217
  if (is_two_pass_svc(cpi) && (cpi->svc.encode_empty_frame_state == ENCODING ||
                               cpi->svc.number_spatial_layers > 1)) {
1218 1219 1220
    cm->log2_tile_cols = 0;
    cm->log2_tile_rows = 0;
  } else {
1221 1222
    cm->log2_tile_cols =
        clamp(cpi->oxcf.tile_columns, min_log2_tile_cols, max_log2_tile_cols);
1223 1224
    cm->log2_tile_rows = cpi->oxcf.tile_rows;
  }
1225 1226

  if (cpi->oxcf.target_level == LEVEL_AUTO) {
1227 1228
    const int level_tile_cols =
        log_tile_cols_from_picsize_level(cpi->common.width, cpi->common.height);
1229 1230 1231 1232
    if (cm->log2_tile_cols > level_tile_cols) {
      cm->log2_tile_cols = VPXMAX(level_tile_cols, min_log2_tile_cols);
    }
  }
1233 1234
}

1235 1236
static void update_frame_size(VP9_COMP *cpi) {
  VP9_COMMON *const cm = &cpi->common;
1237
  MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
1238 1239 1240

  vp9_set_mb_mi(cm, cm->width, cm->height);
  vp9_init_context_buffers(cm);
1241
  vp9_init_macroblockd(cm, xd, NULL);
1242 1243 1244
  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));
1245

1246 1247
  set_tile_limits(cpi);

1248
  if (is_two_pass_svc(cpi)) {
1249
    if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, cm->width, cm->height,
1250
                                 cm->subsampling_x, cm->subsampling_y,
1251 1252 1253
#if CONFIG_VP9_HIGHBITDEPTH
                                 cm->use_highbitdepth,
#endif
1254 1255
                                 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                                 NULL, NULL, NULL))
1256 1257 1258
      vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                         "Failed to reallocate alt_ref_buffer");
  }
1259 1260
}

1261 1262 1263 1264 1265 1266
static void init_buffer_indices(VP9_COMP *cpi) {
  cpi->lst_fb_idx = 0;
  cpi->gld_fb_idx = 1;
  cpi->alt_fb_idx = 2;
}

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
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;
  }
}

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

John Koleszar's avatar
John Koleszar committed
1286
  cpi->oxcf = *oxcf;
1287
  cpi->framerate = oxcf->init_framerate;
1288 1289
  cm->profile = oxcf->profile;
  cm->bit_depth = oxcf->bit_depth;
1290 1291 1292
#if CONFIG_VP9_HIGHBITDEPTH
  cm->use_highbitdepth = oxcf->use_highbitdepth;
#endif
1293
  cm->color_space = oxcf->color_space;
1294
  cm->color_range = oxcf->color_range;
John Koleszar's avatar
John Koleszar committed
1295

1296
  cpi->target_level = oxcf->target_level;
1297
  cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
1298 1299
  set_level_constraint(&cpi->level_constraint,
                       get_level_index(cpi->target_level));
hui su's avatar