vp9_encoder.c 184 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
 */

Jim Bankoski's avatar
Jim Bankoski committed
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"
Jim Bankoski's avatar
Jim Bankoski committed
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

Jim Bankoski's avatar
Jim Bankoski committed
29
#include "vp9/common/vp9_alloccommon.h"
30
#include "vp9/common/vp9_filter.h"
31
#include "vp9/common/vp9_idct.h"
Jim Bankoski's avatar
Jim Bankoski committed
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"
Jim Bankoski's avatar
Jim Bankoski committed
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"
Marco Paniconi's avatar
Marco Paniconi committed
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"
Jim Bankoski's avatar
Jim Bankoski committed
52
#include "vp9/encoder/vp9_mbgraph.h"
53
#include "vp9/encoder/vp9_noise_estimate.h"
Jim Bankoski's avatar
Jim Bankoski committed
54
#include "vp9/encoder/vp9_picklpf.h"
55
#include "vp9/encoder/vp9_ratectrl.h"
56
#include "vp9/encoder/vp9_rd.h"
57
#include "vp9/encoder/vp9_resize.h"
Jim Bankoski's avatar
Jim Bankoski committed
58
#include "vp9/encoder/vp9_segmentation.h"
59
#include "vp9/encoder/vp9_skin_detection.h"
Yaowu Xu's avatar
Yaowu Xu committed
60
#include "vp9/encoder/vp9_speed_features.h"
61
#include "vp9/encoder/vp9_svc_layercontext.h"
62
#include "vp9/encoder/vp9_temporal_filter.h"
Paul Wilkins's avatar
Paul Wilkins committed
63

64 65
#define AM_SEGMENT_ID_INACTIVE 7
#define AM_SEGMENT_ID_ACTIVE 0
66

clang-format's avatar
clang-format committed
67 68 69 70 71 72
#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
73
// #define OUTPUT_YUV_REC
John Koleszar's avatar
John Koleszar committed
74

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

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

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
#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;
}

clang-format's avatar
clang-format committed
110
/* clang-format off */
hui su's avatar
hui su committed
111
const Vp9LevelSpec vp9_level_defs[VP9_LEVELS] = {
clang-format's avatar
clang-format committed
112 113 114 115 116 117 118 119 120 121
  { 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 },
122 123
  // TODO(huisu): update max_cpb_size for level 5_2 ~ 6_2 when
  // they are finalized (currently TBD).
clang-format's avatar
clang-format committed
124 125 126 127
  { 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 },
128
};
clang-format's avatar
clang-format committed
129
/* clang-format on */
130

hui su's avatar
hui su committed
131 132 133 134 135 136 137 138 139 140
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." };

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

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

  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)
178 179
      if (seg_map[i] == AM_SEGMENT_ID_INACTIVE)
        seg_map[i] = AM_SEGMENT_ID_ACTIVE;
180
  }
181 182
}

183
static void apply_active_map(VP9_COMP *cpi) {
184 185 186 187 188 189 190
  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);

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

196 197 198 199 200 201
  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);
202 203 204
      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.
clang-format's avatar
clang-format committed
205 206
      vp9_set_segdata(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF,
                      -MAX_LOOP_FILTER);
207 208
    } else {
      vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
209
      vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
210 211 212 213 214 215 216 217 218
      if (seg->enabled) {
        seg->update_data = 1;
        seg->update_map = 1;
      }
    }
    cpi->active_map.update = 0;
  }
}

219 220 221 222 223 224 225 226 227 228
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;
}

clang-format's avatar
clang-format committed
229
VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec) {
230 231 232 233 234 235 236
  int i;
  const Vp9LevelSpec *this_level;

  vpx_clear_system_state();

  for (i = 0; i < VP9_LEVELS; ++i) {
    this_level = &vp9_level_defs[i];
hui su's avatar
hui su committed
237 238 239
    if ((double)level_spec->max_luma_sample_rate >
            (double)this_level->max_luma_sample_rate *
                (1 + SAMPLE_RATE_GRACE_P) ||
240 241 242 243 244 245 246 247 248 249 250 251 252
        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;
}

clang-format's avatar
clang-format committed
253
int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
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
                       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;
  }
}

clang-format's avatar
clang-format committed
280
int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
281 282 283
                       int cols) {
  if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols &&
      new_map_16x16) {
clang-format's avatar
clang-format committed
284
    unsigned char *const seg_map_8x8 = cpi->segmentation_map;
285 286
    const int mi_rows = cpi->common.mi_rows;
    const int mi_cols = cpi->common.mi_cols;
James Zern's avatar
James Zern committed
287
    memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    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;
  }
}

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

317 318 319 320 321 322 323
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.
324 325 326
  if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
    vp9_setup_past_independence(cm);
  } else {
clang-format's avatar
clang-format committed
327
    if (!cpi->use_svc) cm->frame_context_idx = cpi->refresh_alt_ref_frame;
328 329
  }

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

340 341 342
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
343
  memset(cm->mip, 0, cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mip));
344 345
  cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
  // Clear top border row
James Zern's avatar
James Zern committed
346
  memset(cm->prev_mip, 0, sizeof(*cm->prev_mip) * cm->mi_stride);
347 348
  // Clear left border column
  for (i = 1; i < cm->mi_rows + 1; ++i)
James Zern's avatar
James Zern committed
349
    memset(&cm->prev_mip[i * cm->mi_stride], 0, sizeof(*cm->prev_mip));
350 351 352 353

  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
354 355
  memset(cm->mi_grid_base, 0,
         cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mi_grid_base));
356 357 358 359
}

static int vp9_enc_alloc_mi(VP9_COMMON *cm, int mi_size) {
  cm->mip = vpx_calloc(mi_size, sizeof(*cm->mip));
clang-format's avatar
clang-format committed
360
  if (!cm->mip) return 1;
361
  cm->prev_mip = vpx_calloc(mi_size, sizeof(*cm->prev_mip));
clang-format's avatar
clang-format committed
362
  if (!cm->prev_mip) return 1;
363
  cm->mi_alloc_size = mi_size;
364

clang-format's avatar
clang-format committed
365 366 367 368 369
  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;
370

371 372 373 374 375 376 377 378
  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;
379 380 381 382
  vpx_free(cm->mi_grid_base);
  cm->mi_grid_base = NULL;
  vpx_free(cm->prev_mi_grid_base);
  cm->prev_mi_grid_base = NULL;
383 384 385 386
}

static void vp9_swap_mi_and_prev_mi(VP9_COMMON *cm) {
  // Current mip will be the prev_mip for the next frame.
387
  MODE_INFO **temp_base = cm->prev_mi_grid_base;
388 389 390 391 392 393 394
  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;
395 396 397 398 399

  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;
400 401
}

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

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

418
static void dealloc_compressor_data(VP9_COMP *cpi) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
419
  VP9_COMMON *const cm = &cpi->common;
420
  int i;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
421

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

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

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

Jingning Han's avatar
Jingning Han committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
  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;

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

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

459 460 461
  vp9_cyclic_refresh_free(cpi->cyclic_refresh);
  cpi->cyclic_refresh = NULL;

462 463 464
  vpx_free(cpi->active_map.map);
  cpi->active_map.map = NULL;

465 466 467
  vpx_free(cpi->consec_zero_mv);
  cpi->consec_zero_mv = NULL;

468 469 470 471
  vp9_free_ref_frame_buffers(cm->buffer_pool);
#if CONFIG_VP9_POSTPROC
  vp9_free_postproc_buffers(cm);
#endif
472
  vp9_free_context_buffers(cm);
John Koleszar's avatar
John Koleszar committed
473

474 475 476 477
  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);
478 479 480 481 482
#ifdef ENABLE_KF_DENOISE
  vpx_free_frame_buffer(&cpi->raw_unscaled_source);
  vpx_free_frame_buffer(&cpi->raw_scaled_source);
#endif

483
  vp9_lookahead_destroy(cpi->lookahead);
John Koleszar's avatar
John Koleszar committed
484

485 486
  vpx_free(cpi->tile_tok[0][0]);
  cpi->tile_tok[0][0] = 0;
John Koleszar's avatar
John Koleszar committed
487

488
  vp9_free_pc_tree(&cpi->td);
489

490 491 492 493 494 495
  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;
  }
496 497 498 499 500

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

502
  for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
503
    vpx_free_frame_buffer(&cpi->svc.scaled_frames[i]);
504
  }
James Zern's avatar
James Zern committed
505 506
  memset(&cpi->svc.scaled_frames[0], 0,
         MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
507

508 509 510
  vpx_free_frame_buffer(&cpi->svc.scaled_temp);
  memset(&cpi->svc.scaled_temp, 0, sizeof(cpi->svc.scaled_temp));

511
  vpx_free_frame_buffer(&cpi->svc.empty_frame.img);
James Zern's avatar
James Zern committed
512
  memset(&cpi->svc.empty_frame, 0, sizeof(cpi->svc.empty_frame));
513 514

  vp9_free_svc_cyclic_refresh(cpi);
John Koleszar's avatar
John Koleszar committed
515 516
}

517 518 519 520 521 522 523 524
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.
clang-format's avatar
clang-format committed
525
  vp9_copy(cc->nmvjointcost, cpi->td.mb.nmvjointcost);
Jingning Han's avatar
Jingning Han committed
526

James Zern's avatar
James Zern committed
527 528 529 530 531 532 533 534
  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]));
535 536 537

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

clang-format's avatar
clang-format committed
538 539
  memcpy(cpi->coding_context.last_frame_seg_map_copy, cm->last_frame_seg_map,
         (cm->mi_rows * cm->mi_cols));
540 541 542 543

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

544
  cc->fc = *cm->fc;
545 546 547 548 549 550 551 552
}

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.
553
  vp9_copy(cpi->td.mb.nmvjointcost, cc->nmvjointcost);
Jingning Han's avatar
Jingning Han committed
554

James Zern's avatar
James Zern committed
555 556 557 558 559 560
  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]));
561 562 563

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

clang-format's avatar
clang-format committed
564
  memcpy(cm->last_frame_seg_map, cpi->coding_context.last_frame_seg_map_copy,
James Zern's avatar
James Zern committed
565
         (cm->mi_rows * cm->mi_cols));
566 567 568 569

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

570
  *cm->fc = cc->fc;
571 572
}

573
static void configure_static_seg_features(VP9_COMP *cpi) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
574
  VP9_COMMON *const cm = &cpi->common;
575
  const RATE_CONTROL *const rc = &cpi->rc;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
576
  struct segmentation *const seg = &cm->seg;
577

578
  int high_q = (int)(rc->avg_q > 48.0);
John Koleszar's avatar
John Koleszar committed
579
  int qi_delta;
580

John Koleszar's avatar
John Koleszar committed
581 582 583
  // 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
584
    memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
585 586
    seg->update_map = 0;
    seg->update_data = 0;
John Koleszar's avatar
John Koleszar committed
587
    cpi->static_mb_pct = 0;
588

John Koleszar's avatar
John Koleszar committed
589
    // Disable segmentation
590
    vp9_disable_segmentation(seg);
Paul Wilkins's avatar
Paul Wilkins committed
591

John Koleszar's avatar
John Koleszar committed
592
    // Clear down the segment features.
593
    vp9_clearall_segfeatures(seg);
594 595
  } else if (cpi->refresh_alt_ref_frame) {
    // If this is an alt ref frame
John Koleszar's avatar
John Koleszar committed
596
    // 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;
Paul Wilkins's avatar
Paul Wilkins committed
601

John Koleszar's avatar
John Koleszar committed
602
    // Disable segmentation and individual segment features by default
603
    vp9_disable_segmentation(seg);
604
    vp9_clearall_segfeatures(seg);
Paul Wilkins's avatar
Paul Wilkins committed
605

John Koleszar's avatar
John Koleszar committed
606 607
    // Scan frames from current to arf frame.
    // This function re-enables segmentation if appropriate.
608
    vp9_update_mbgraph_stats(cpi);
Paul Wilkins's avatar
Paul Wilkins committed
609

John Koleszar's avatar
John Koleszar committed
610 611
    // If segmentation was enabled set those features needed for the
    // arf itself.
612 613 614
    if (seg->enabled) {
      seg->update_map = 1;
      seg->update_data = 1;
Paul Wilkins's avatar
Paul Wilkins committed
615

clang-format's avatar
clang-format committed
616 617
      qi_delta =
          vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875, cm->bit_depth);
618
      vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
619
      vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
Paul Wilkins's avatar
Paul Wilkins committed
620

621 622
      vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
      vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
623

John Koleszar's avatar
John Koleszar committed
624
      // Where relevant assume segment data is delta data
625
      seg->abs_delta = SEGMENT_DELTADATA;
626
    }
627
  } else if (seg->enabled) {
628 629
    // All other frames if segmentation has been enabled

John Koleszar's avatar
John Koleszar committed
630
    // First normal frame in a valid gf or alt ref group
631
    if (rc->frames_since_golden == 0) {
Paul Wilkins's avatar
Paul Wilkins committed
632
      // Set up segment features for normal frames in an arf group
633
      if (rc->source_alt_ref_active) {
634 635 636
        seg->update_map = 0;
        seg->update_data = 1;
        seg->abs_delta = SEGMENT_DELTADATA;
Paul Wilkins's avatar
Paul Wilkins committed
637

clang-format's avatar
clang-format committed
638 639
        qi_delta =
            vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125, cm->bit_depth);
640
        vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
641
        vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
Paul Wilkins's avatar
Paul Wilkins committed
642

643 644
        vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
        vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
Paul Wilkins's avatar
Paul Wilkins committed
645

John Koleszar's avatar
John Koleszar committed
646 647
        // Segment coding disabled for compred testing
        if (high_q || (cpi->static_mb_pct == 100)) {
648 649 650
          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
651
        }
652 653 654 655
      } else {
        // Disable segmentation and clear down features if alt ref
        // is not active for this group

656
        vp9_disable_segmentation(seg);
Paul Wilkins's avatar
Paul Wilkins committed
657

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

660 661
        seg->update_map = 0;
        seg->update_data = 0;
Paul Wilkins's avatar
Paul Wilkins committed
662

663
        vp9_clearall_segfeatures(seg);
John Koleszar's avatar
John Koleszar committed
664
      }
665
    } else if (rc->is_src_frame_alt_ref) {
666 667 668
      // 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
669

Paul Wilkins's avatar
Paul Wilkins committed
670
      // Enable ref frame features for segment 0 as well
671 672
      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
673

Paul Wilkins's avatar
Paul Wilkins committed
674
      // All mbs should use ALTREF_FRAME
675 676 677 678
      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
679

Paul Wilkins's avatar
Paul Wilkins committed
680
      // Skip all MBs if high Q (0,0 mv and skip coeffs)
John Koleszar's avatar
John Koleszar committed
681
      if (high_q) {
682 683
        vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
        vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
John Koleszar's avatar
John Koleszar committed
684
      }
Adrian Grange's avatar
Adrian Grange committed
685
      // Enable data update
686
      seg->update_data = 1;
687 688 689
    } else {
      // All other frames.

John Koleszar's avatar
John Koleszar committed
690
      // No updates.. leave things as they are.
691 692
      seg->update_map = 0;
      seg->update_data = 0;
John Koleszar's avatar
John Koleszar committed
693 694
    }
  }
695 696
}

697
static void update_reference_segmentation_map(VP9_COMP *cpi) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
698
  VP9_COMMON *const cm = &cpi->common;
699
  MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
700
  uint8_t *cache_ptr = cm->last_frame_seg_map;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
701 702
  int row, col;

703
  for (row = 0; row < cm->mi_rows; row++) {
704
    MODE_INFO **mi_8x8 = mi_8x8_ptr;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
705
    uint8_t *cache = cache_ptr;
706
    for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
Scott LaVarnway's avatar
Scott LaVarnway committed
707
      cache[0] = mi_8x8[0]->segment_id;
708
    mi_8x8_ptr += cm->mi_stride;
709
    cache_ptr += cm->mi_cols;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
710 711 712
  }
}

713
static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
714
  VP9_COMMON *cm = &cpi->common;
715
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
716

717 718 719
  if (!cpi->lookahead)
    cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
                                        cm->subsampling_x, cm->subsampling_y,
720
#if CONFIG_VP9_HIGHBITDEPTH
clang-format's avatar
clang-format committed
721
                                        cm->use_highbitdepth,
722
#endif
clang-format's avatar
clang-format committed
723
                                        oxcf->lag_in_frames);
John Koleszar's avatar
John Koleszar committed
724
  if (!cpi->lookahead)
725
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
John Koleszar's avatar
John Koleszar committed
726
                       "Failed to allocate lag buffers");
John Koleszar's avatar
John Koleszar committed
727

728
  // TODO(agrange) Check if ARF is enabled and skip allocation if not.
clang-format's avatar
clang-format committed
729
  if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, oxcf->width, oxcf->height,
730
                               cm->subsampling_x, cm->subsampling_y,
731 732 733
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
734 735
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
736
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
John Koleszar's avatar
John Koleszar committed
737
                       "Failed to allocate altref buffer");
John Koleszar's avatar
John Koleszar committed
738
}
739

740
static void alloc_util_frame_buffers(VP9_COMP *cpi) {
741
  VP9_COMMON *const cm = &cpi->common;
clang-format's avatar
clang-format committed
742
  if (vpx_realloc_frame_buffer(&cpi->last_frame_uf, cm->width, cm->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,
750
                       "Failed to allocate last frame buffer");
751

clang-format's avatar
clang-format committed
752
  if (vpx_realloc_frame_buffer(&cpi->scaled_source, cm->width, cm->height,
753
                               cm->subsampling_x, cm->subsampling_y,
754 755 756
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
757 758
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
759
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
760
                       "Failed to allocate scaled source buffer");
761

762 763 764 765 766
  // 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;
clang-format's avatar
clang-format committed
767 768 769
    if (vpx_realloc_frame_buffer(
            &cpi->svc.scaled_temp, cm->width >> 1, cm->height >> 1,
            cm->subsampling_x, cm->subsampling_y,
770
#if CONFIG_VP9_HIGHBITDEPTH
clang-format's avatar
clang-format committed
771
            cm->use_highbitdepth,
772
#endif
clang-format's avatar
clang-format committed
773
            VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment, NULL, NULL, NULL))
774 775 776 777
      vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
                         "Failed to allocate scaled_frame for svc ");
  }

clang-format's avatar
clang-format committed
778
  if (vpx_realloc_frame_buffer(&cpi->scaled_last_source, cm->width, cm->height,
779
                               cm->subsampling_x, cm->subsampling_y,
780 781 782
#if CONFIG_VP9_HIGHBITDEPTH
                               cm->use_highbitdepth,
#endif
783 784
                               VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
                               NULL, NULL, NULL))
785
    vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
786
                       "Failed to allocate scaled last source buffer");
787
#ifdef ENABLE_KF_DENOISE
clang-format's avatar
clang-format committed
788
  if (vpx_realloc_frame_buffer(&cpi->raw_unscaled_source, cm->width, cm->height,
789 790 791 792 793 794 795 796 797
                               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");

clang-format's avatar
clang-format committed
798
  if (vpx_realloc_frame_buffer(&cpi->raw_scaled_source, cm->width, cm->height,