vp9_encoder.h 26.6 KB
Newer Older
John Koleszar's avatar
John Koleszar committed
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
John Koleszar's avatar
John Koleszar committed
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5 6
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
7
 *  in the file PATENTS.  All contributing project authors may
8
 *  be found in the AUTHORS file in the root of the source tree.
John Koleszar's avatar
John Koleszar committed
9 10
 */

11 12
#ifndef VP9_ENCODER_VP9_ENCODER_H_
#define VP9_ENCODER_VP9_ENCODER_H_
John Koleszar's avatar
John Koleszar committed
13 14

#include <stdio.h>
15

16
#include "./vpx_config.h"
17
#include "vpx/internal/vpx_codec_internal.h"
18
#include "vpx/vp8cx.h"
19 20 21 22
#if CONFIG_INTERNAL_STATS
#include "vpx_dsp/ssim.h"
#endif
#include "vpx_dsp/variance.h"
23
#include "vpx_ports/system_state.h"
24
#include "vpx_util/vpx_thread.h"
25

26
#include "vp9/common/vp9_alloccommon.h"
27
#include "vp9/common/vp9_ppflags.h"
28
#include "vp9/common/vp9_entropymode.h"
29
#include "vp9/common/vp9_thread_common.h"
30
#include "vp9/common/vp9_onyxc_int.h"
31

32
#include "vp9/encoder/vp9_alt_ref_aq.h"
33
#include "vp9/encoder/vp9_aq_cyclicrefresh.h"
34
#include "vp9/encoder/vp9_context_tree.h"
35
#include "vp9/encoder/vp9_encodemb.h"
36
#include "vp9/encoder/vp9_ethread.h"
37
#include "vp9/encoder/vp9_firstpass.h"
38
#include "vp9/encoder/vp9_job_queue.h"
39
#include "vp9/encoder/vp9_lookahead.h"
40
#include "vp9/encoder/vp9_mbgraph.h"
41
#include "vp9/encoder/vp9_mcomp.h"
42
#include "vp9/encoder/vp9_noise_estimate.h"
43 44
#include "vp9/encoder/vp9_quantize.h"
#include "vp9/encoder/vp9_ratectrl.h"
45
#include "vp9/encoder/vp9_rd.h"
46
#include "vp9/encoder/vp9_speed_features.h"
47
#include "vp9/encoder/vp9_svc_layercontext.h"
48
#include "vp9/encoder/vp9_tokenize.h"
49

50
#if CONFIG_VP9_TEMPORAL_DENOISING
51 52
#include "vp9/encoder/vp9_denoiser.h"
#endif
John Koleszar's avatar
John Koleszar committed
53

54 55 56 57
#ifdef __cplusplus
extern "C" {
#endif

58 59 60
// vp9 uses 10,000,000 ticks/second as time stamp
#define TICKS_PER_SEC 10000000

John Koleszar's avatar
John Koleszar committed
61
typedef struct {
62 63 64
  int nmvjointcost[MV_JOINTS];
  int nmvcosts[2][MV_VALS];
  int nmvcosts_hp[2][MV_VALS];
John Koleszar's avatar
John Koleszar committed
65

66
  vpx_prob segment_pred_probs[PREDICTION_PROBS];
John Koleszar's avatar
John Koleszar committed
67

John Koleszar's avatar
John Koleszar committed
68
  unsigned char *last_frame_seg_map_copy;
69

John Koleszar's avatar
John Koleszar committed
70 71
  // 0 = Intra, Last, GF, ARF
  signed char last_ref_lf_deltas[MAX_REF_LF_DELTAS];
72
  // 0 = ZERO_MV, MV
John Koleszar's avatar
John Koleszar committed
73
  signed char last_mode_lf_deltas[MAX_MODE_LF_DELTAS];
John Koleszar's avatar
John Koleszar committed
74

75
  FRAME_CONTEXT fc;
John Koleszar's avatar
John Koleszar committed
76 77
} CODING_CONTEXT;

78 79 80 81 82 83 84 85 86
typedef enum {
  // encode_breakout is disabled.
  ENCODE_BREAKOUT_DISABLED = 0,
  // encode_breakout is enabled.
  ENCODE_BREAKOUT_ENABLED = 1,
  // encode_breakout is enabled with small max_thresh limit.
  ENCODE_BREAKOUT_LIMITED = 2
} ENCODE_BREAKOUT_TYPE;

87
typedef enum {
88 89 90 91
  NORMAL = 0,
  FOURFIVE = 1,
  THREEFIVE = 2,
  ONETWO = 3
92 93 94
} VPX_SCALING;

typedef enum {
95 96 97 98 99 100 101 102 103 104 105 106 107
  // Good Quality Fast Encoding. The encoder balances quality with the amount of
  // time it takes to encode the output. Speed setting controls how fast.
  GOOD,

  // The encoder places priority on the quality of the output over encoding
  // speed. The output is compressed at the highest possible quality. This
  // option takes the longest amount of time to encode. Speed setting ignored.
  BEST,

  // Realtime/Live Encoding. This mode is optimized for realtime encoding (for
  // example, capturing a television signal or feed from a live camera). Speed
  // setting controls how fast.
  REALTIME
108 109 110
} MODE;

typedef enum {
111
  FRAMEFLAGS_KEY = 1 << 0,
112 113
  FRAMEFLAGS_GOLDEN = 1 << 1,
  FRAMEFLAGS_ALTREF = 1 << 2,
114 115 116 117 118 119
} FRAMETYPE_FLAGS;

typedef enum {
  NO_AQ = 0,
  VARIANCE_AQ = 1,
  COMPLEXITY_AQ = 2,
120
  CYCLIC_REFRESH_AQ = 3,
121
  EQUATOR360_AQ = 4,
122 123 124
  // AQ based on lookahead temporal
  // variance (only valid for altref frames)
  LOOKAHEAD_AQ = 5,
125 126
  AQ_MODE_COUNT  // This should always be the last member of the enum
} AQ_MODE;
127

128 129 130 131 132
typedef enum {
  RESIZE_NONE = 0,    // No frame resizing allowed (except for SVC).
  RESIZE_FIXED = 1,   // All frames are coded at the specified dimension.
  RESIZE_DYNAMIC = 2  // Coded size of each frame is determined by the codec.
} RESIZE_TYPE;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
133

134 135 136 137 138 139
typedef enum {
  kInvalid = 0,
  kLowSadLowSumdiff = 1,
  kLowSadHighSumdiff = 2,
  kHighSadLowSumdiff = 3,
  kHighSadHighSumdiff = 4,
140
  kLowVarHighSumdiff = 5,
141
  kVeryHighSad = 6,
142 143
} CONTENT_STATE_SB;

144
typedef struct VP9EncoderConfig {
145
  BITSTREAM_PROFILE profile;
146
  vpx_bit_depth_t bit_depth;     // Codec bit-depth.
147 148
  int width;                     // width of data passed to the compressor
  int height;                    // height of data passed to the compressor
149
  unsigned int input_bit_depth;  // Input bit depth.
150 151
  double init_framerate;         // set to passed in framerate
  int64_t target_bandwidth;      // bandwidth to be used in bits per second
152 153

  int noise_sensitivity;  // pre processing blur: recommendation 0
154
  int sharpness;          // sharpening output: recommendation 0:
155
  int speed;
156
  // maximum allowed bitrate for any intra frame in % of bitrate target.
157
  unsigned int rc_max_intra_bitrate_pct;
158 159
  // maximum allowed bitrate for any inter frame in % of bitrate target.
  unsigned int rc_max_inter_bitrate_pct;
160 161
  // percent of rate boost for golden frame in CBR mode.
  unsigned int gf_cbr_boost_pct;
162

163
  MODE mode;
164
  int pass;
165 166 167 168 169 170 171 172 173 174

  // Key Framing Operations
  int auto_key;  // autodetect cut scenes and set the keyframes
  int key_freq;  // maximum distance to key frame.

  int lag_in_frames;  // how many frames lag before we start encoding

  // ----------------------------------------------------------------
  // DATARATE CONTROL OPTIONS

175 176
  // vbr, cbr, constrained quality or constant quality
  enum vpx_rc_mode rc_mode;
177 178 179 180 181 182

  // buffer targeting aggressiveness
  int under_shoot_pct;
  int over_shoot_pct;

  // buffering parameters
183 184 185
  int64_t starting_buffer_level_ms;
  int64_t optimal_buffer_level_ms;
  int64_t maximum_buffer_size_ms;
186 187 188 189 190 191 192 193 194

  // Frame drop threshold.
  int drop_frames_water_mark;

  // controlling quality
  int fixed_q;
  int worst_allowed_q;
  int best_allowed_q;
  int cq_level;
195
  AQ_MODE aq_mode;  // Adaptive Quantization mode
196

197 198 199
  // Special handling of Adaptive Quantization for AltRef frames
  int alt_ref_aq;

200
  // Internal frame size scaling.
201
  RESIZE_TYPE resize_mode;
202 203 204
  int scaled_frame_width;
  int scaled_frame_height;

205 206 207
  // Enable feature to reduce the frame quantization every x frames.
  int frame_periodic_boost;

208
  // two pass datarate control
209
  int two_pass_vbrbias;  // two pass datarate control tweaks
210 211 212 213 214 215 216 217 218
  int two_pass_vbrmin_section;
  int two_pass_vbrmax_section;
  // END DATARATE CONTROL OPTIONS
  // ----------------------------------------------------------------

  // Spatial and temporal scalability.
  int ss_number_layers;  // Number of spatial layers.
  int ts_number_layers;  // Number of temporal layers.
  // Bitrate allocation for spatial layers.
219
  int layer_target_bitrate[VPX_MAX_LAYERS];
220
  int ss_target_bitrate[VPX_SS_MAX_LAYERS];
221
  int ss_enable_auto_arf[VPX_SS_MAX_LAYERS];
222 223 224
  // Bitrate allocation (CBR mode) and framerate factor, for temporal layers.
  int ts_rate_decimator[VPX_TS_MAX_LAYERS];

225
  int enable_auto_arf;
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

  int encode_breakout;  // early breakout : for video conf recommend 800

  /* Bitfield defining the error resiliency features to enable.
   * Can provide decodable frames after losses in previous
   * frames and decodable partitions after losses in the same frame.
   */
  unsigned int error_resilient_mode;

  /* Bitfield defining the parallel decoding mode where the
   * decoding in successive frames may be conducted in parallel
   * just by decoding the frame headers.
   */
  unsigned int frame_parallel_decoding_mode;

  int arnr_max_frames;
  int arnr_strength;

244 245 246
  int min_gf_interval;
  int max_gf_interval;

247 248 249
  int tile_columns;
  int tile_rows;

250 251
  int max_threads;

252
  unsigned int target_level;
253

254 255
  vpx_fixed_buf_t two_pass_stats_in;
  struct vpx_codec_pkt_list *output_pkt_list;
256

257
#if CONFIG_FP_MB_STATS
258
  vpx_fixed_buf_t firstpass_mb_stats_in;
259 260
#endif

261
  vp8e_tuning tuning;
262
  vp9e_tune_content content;
263 264 265
#if CONFIG_VP9_HIGHBITDEPTH
  int use_highbitdepth;
#endif
266
  vpx_color_space_t color_space;
267
  vpx_color_range_t color_range;
268 269
  int render_width;
  int render_height;
270
  VP9E_TEMPORAL_LAYERING_MODE temporal_layering_mode;
271

272
  int row_mt;
273
  unsigned int motion_vector_unit_test;
274
} VP9EncoderConfig;
275

276 277 278 279
static INLINE int is_lossless_requested(const VP9EncoderConfig *cfg) {
  return cfg->best_allowed_q == 0 && cfg->worst_allowed_q == 0;
}

280 281
// TODO(jingning) All spatially adaptive variables should go to TileDataEnc.
typedef struct TileDataEnc {
282
  TileInfo tile_info;
283 284
  int thresh_freq_fact[BLOCK_SIZES][MAX_MODES];
  int mode_map[BLOCK_SIZES][MAX_MODES];
285 286
  FIRSTPASS_DATA fp_data;
  VP9RowMTSync row_mt_sync;
287 288 289

  // Used for adaptive_rd_thresh with row multithreading
  int *row_base_thresh_freq_fact;
290 291
} TileDataEnc;

292 293 294 295 296 297 298
typedef struct RowMTInfo {
  JobQueueHandle job_queue_hdl;
#if CONFIG_MULTITHREAD
  pthread_mutex_t job_mutex;
#endif
} RowMTInfo;

299 300 301 302 303 304
typedef struct {
  TOKENEXTRA *start;
  TOKENEXTRA *stop;
  unsigned int count;
} TOKENLIST;

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
typedef struct MultiThreadHandle {
  int allocated_tile_rows;
  int allocated_tile_cols;
  int allocated_vert_unit_rows;

  // Frame level params
  int num_tile_vert_sbs[MAX_NUM_TILE_ROWS];

  // Job Queue structure and handles
  JobQueue *job_queue;

  int jobs_per_tile_col;

  RowMTInfo row_mt_info[MAX_NUM_TILE_COLS];
  int thread_id_to_tile_id[MAX_NUM_THREADS];  // Mapping of threads to tiles
} MultiThreadHandle;

322
typedef struct RD_COUNTS {
323 324 325
  vp9_coeff_count coef_counts[TX_SIZES][PLANE_TYPES];
  int64_t comp_pred_diff[REFERENCE_MODES];
  int64_t filter_diff[SWITCHABLE_FILTER_CONTEXTS];
326 327 328 329 330 331 332 333 334 335 336
} RD_COUNTS;

typedef struct ThreadData {
  MACROBLOCK mb;
  RD_COUNTS rd_counts;
  FRAME_COUNTS *counts;

  PICK_MODE_CONTEXT *leaf_tree;
  PC_TREE *pc_tree;
  PC_TREE *pc_root;
} ThreadData;
337

338 339
struct EncWorkerData;

340 341 342 343 344 345
typedef struct ActiveMap {
  int enabled;
  int update;
  unsigned char *map;
} ActiveMap;

346
typedef enum { Y, U, V, ALL } STAT_TYPE;
347 348

typedef struct IMAGE_STAT {
349
  double stat[ALL + 1];
350 351 352
  double worst;
} ImageStat;

353 354 355
// Kf noise filtering currently disabled by default in build.
// #define ENABLE_KF_DENOISE 1

356 357 358 359 360 361 362
#define CPB_WINDOW_SIZE 4
#define FRAME_WINDOW_SIZE 128
#define SAMPLE_RATE_GRACE_P 0.015
#define VP9_LEVELS 14

typedef enum {
  LEVEL_UNKNOWN = 0,
363
  LEVEL_AUTO = 1,
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
  LEVEL_1 = 10,
  LEVEL_1_1 = 11,
  LEVEL_2 = 20,
  LEVEL_2_1 = 21,
  LEVEL_3 = 30,
  LEVEL_3_1 = 31,
  LEVEL_4 = 40,
  LEVEL_4_1 = 41,
  LEVEL_5 = 50,
  LEVEL_5_1 = 51,
  LEVEL_5_2 = 52,
  LEVEL_6 = 60,
  LEVEL_6_1 = 61,
  LEVEL_6_2 = 62,
  LEVEL_MAX = 255
} VP9_LEVEL;

typedef struct {
  VP9_LEVEL level;
  uint64_t max_luma_sample_rate;
  uint32_t max_luma_picture_size;
  double average_bitrate;  // in kilobits per second
386
  double max_cpb_size;     // in kilobits
387 388 389 390 391 392
  double compression_ratio;
  uint8_t max_col_tiles;
  uint32_t min_altref_distance;
  uint8_t max_ref_frame_buffers;
} Vp9LevelSpec;

393 394
extern const Vp9LevelSpec vp9_level_defs[VP9_LEVELS];

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
typedef struct {
  int64_t ts;  // timestamp
  uint32_t luma_samples;
  uint32_t size;  // in bytes
} FrameRecord;

typedef struct {
  FrameRecord buf[FRAME_WINDOW_SIZE];
  uint8_t start;
  uint8_t len;
} FrameWindowBuffer;

typedef struct {
  uint8_t seen_first_altref;
  uint32_t frames_since_last_altref;
  uint64_t total_compressed_size;
  uint64_t total_uncompressed_size;
  double time_encoded;  // in seconds
  FrameWindowBuffer frame_window_buffer;
  int ref_refresh_map;
} Vp9LevelStats;

typedef struct {
  Vp9LevelStats level_stats;
  Vp9LevelSpec level_spec;
} Vp9LevelInfo;

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
typedef enum {
  BITRATE_TOO_LARGE = 0,
  LUMA_PIC_SIZE_TOO_LARGE = 1,
  LUMA_SAMPLE_RATE_TOO_LARGE = 2,
  CPB_TOO_LARGE = 3,
  COMPRESSION_RATIO_TOO_SMALL = 4,
  TOO_MANY_COLUMN_TILE = 5,
  ALTREF_DIST_TOO_SMALL = 6,
  TOO_MANY_REF_BUFFER = 7,
  TARGET_LEVEL_FAIL_IDS = 8
} TARGET_LEVEL_FAIL_ID;

typedef struct {
  int8_t level_index;
  uint8_t rc_config_updated;
  uint8_t fail_flag;
  int max_frame_size;   // in bits
  double max_cpb_size;  // in bits
} LevelConstraint;

442 443 444 445 446 447 448 449
typedef struct ARNRFilterData {
  YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS];
  int strength;
  int frame_count;
  int alt_ref_index;
  struct scale_factors sf;
} ARNRFilterData;

450
typedef struct VP9_COMP {
451
  QUANTS quants;
452
  ThreadData td;
453
  MB_MODE_INFO_EXT *mbmi_ext_base;
454 455
  DECLARE_ALIGNED(16, int16_t, y_dequant[QINDEX_RANGE][8]);
  DECLARE_ALIGNED(16, int16_t, uv_dequant[QINDEX_RANGE][8]);
456
  VP9_COMMON common;
457
  VP9EncoderConfig oxcf;
458 459
  struct lookahead_ctx *lookahead;
  struct lookahead_entry *alt_ref_source;
460

John Koleszar's avatar
John Koleszar committed
461
  YV12_BUFFER_CONFIG *Source;
462
  YV12_BUFFER_CONFIG *Last_Source;  // NULL for first frame and alt_ref frames
John Koleszar's avatar
John Koleszar committed
463 464
  YV12_BUFFER_CONFIG *un_scaled_source;
  YV12_BUFFER_CONFIG scaled_source;
465 466
  YV12_BUFFER_CONFIG *unscaled_last_source;
  YV12_BUFFER_CONFIG scaled_last_source;
467 468 469 470 471
#ifdef ENABLE_KF_DENOISE
  YV12_BUFFER_CONFIG raw_unscaled_source;
  YV12_BUFFER_CONFIG raw_scaled_source;
#endif
  YV12_BUFFER_CONFIG *raw_source_frame;
John Koleszar's avatar
John Koleszar committed
472

473
  TileDataEnc *tile_data;
474
  int allocated_tiles;  // Keep track of memory allocated for tiles.
475

476 477
  // For a still frame, this flag is set to 1 to skip partition search.
  int partition_search_skippable_frame;
478

479
  int scaled_ref_idx[MAX_REF_FRAMES];
480 481 482
  int lst_fb_idx;
  int gld_fb_idx;
  int alt_fb_idx;
483

484 485 486
  int refresh_last_frame;
  int refresh_golden_frame;
  int refresh_alt_ref_frame;
487 488 489 490 491 492 493 494 495

  int ext_refresh_frame_flags_pending;
  int ext_refresh_last_frame;
  int ext_refresh_golden_frame;
  int ext_refresh_alt_ref_frame;

  int ext_refresh_frame_context_pending;
  int ext_refresh_frame_context;

John Koleszar's avatar
John Koleszar committed
496
  YV12_BUFFER_CONFIG last_frame_uf;
John Koleszar's avatar
John Koleszar committed
497

498
  TOKENEXTRA *tile_tok[4][1 << 6];
499
  uint32_t tok_count[4][1 << 6];
500
  TOKENLIST *tplist[4][1 << 6];
John Koleszar's avatar
John Koleszar committed
501

John Koleszar's avatar
John Koleszar committed
502
  // Ambient reconstruction err target for force key frames
503
  int64_t ambient_err;
504

Dmitry Kovalev's avatar
Dmitry Kovalev committed
505
  RD_OPT rd;
John Koleszar's avatar
John Koleszar committed
506

John Koleszar's avatar
John Koleszar committed
507
  CODING_CONTEXT coding_context;
John Koleszar's avatar
John Koleszar committed
508

509 510 511 512 513
  int *nmvcosts[2];
  int *nmvcosts_hp[2];
  int *nmvsadcosts[2];
  int *nmvsadcosts_hp[2];

John Koleszar's avatar
John Koleszar committed
514 515 516
  int64_t last_time_stamp_seen;
  int64_t last_end_time_stamp_seen;
  int64_t first_time_stamp_ever;
John Koleszar's avatar
John Koleszar committed
517

518
  RATE_CONTROL rc;
519
  double framerate;
John Koleszar's avatar
John Koleszar committed
520

521
  int interp_filter_selected[MAX_REF_FRAMES][SWITCHABLE];
522

523
  struct vpx_codec_pkt_list *output_pkt_list;
524

John Koleszar's avatar
John Koleszar committed
525
  MBGRAPH_FRAME_STATS mbgraph_stats[MAX_LAG_BUFFERS];
526 527
  int mbgraph_n_frames;  // number of frames filled in the above
  int static_mb_pct;     // % forced skip mbs by segmentation
John Koleszar's avatar
John Koleszar committed
528
  int ref_frame_flags;
John Koleszar's avatar
John Koleszar committed
529

John Koleszar's avatar
John Koleszar committed
530
  SPEED_FEATURES sf;
John Koleszar's avatar
John Koleszar committed
531

532
  uint32_t max_mv_magnitude;
533
  int mv_step_param;
534

535 536
  int allow_comp_inter_inter;

537 538 539
  // Default value is 1. From first pass stats, encode_breakout may be disabled.
  ENCODE_BREAKOUT_TYPE allow_encode_breakout;

540 541
  // Get threshold from external input. A suggested threshold is 800 for HD
  // clips, and 300 for < HD clips.
542 543
  int encode_breakout;

544
  uint8_t *segmentation_map;
Paul Wilkins's avatar
Paul Wilkins committed
545

546 547
  uint8_t *skin_map;

John Koleszar's avatar
John Koleszar committed
548
  // segment threashold for encode breakout
549
  int segment_encode_breakout[MAX_SEGMENTS];
John Koleszar's avatar
John Koleszar committed
550

551
  CYCLIC_REFRESH *cyclic_refresh;
552
  ActiveMap active_map;
553

John Koleszar's avatar
John Koleszar committed
554
  fractional_mv_step_fp *find_fractional_mv_step;
555
  vp9_diamond_search_fn_t diamond_search_sad;
556
  vp9_variance_fn_ptr_t fn_ptr[BLOCK_SIZES];
557 558 559
  uint64_t time_receive_data;
  uint64_t time_compress_data;
  uint64_t time_pick_lpf;
560
  uint64_t time_encode_sb_row;
John Koleszar's avatar
John Koleszar committed
561

562 563 564 565
#if CONFIG_FP_MB_STATS
  int use_fp_mb_stats;
#endif

Paul Wilkins's avatar
Paul Wilkins committed
566
  TWO_PASS twopass;
John Koleszar's avatar
John Koleszar committed
567

568 569 570
  // Force recalculation of segment_ids for each mode info
  uint8_t force_update_segmentation;

John Koleszar's avatar
John Koleszar committed
571
  YV12_BUFFER_CONFIG alt_ref_buffer;
572

573 574 575 576
  // class responsible for adaptive
  // quantization of altref frames
  struct ALT_REF_AQ *alt_ref_aq;

577
#if CONFIG_INTERNAL_STATS
578 579
  unsigned int mode_chosen_counts[MAX_MODES];

580
  int count;
581 582
  uint64_t total_sq_error;
  uint64_t total_samples;
583
  ImageStat psnr;
584 585 586

  uint64_t totalp_sq_error;
  uint64_t totalp_samples;
587
  ImageStat psnrp;
588

589
  double total_blockiness;
590
  double worst_blockiness;
591

592
  int bytes;
John Koleszar's avatar
John Koleszar committed
593 594
  double summed_quality;
  double summed_weights;
595 596
  double summedp_quality;
  double summedp_weights;
John Koleszar's avatar
John Koleszar committed
597
  unsigned int tot_recode_hits;
598
  double worst_ssim;
John Koleszar's avatar
John Koleszar committed
599

600 601 602
  ImageStat ssimg;
  ImageStat fastssim;
  ImageStat psnrhvs;
603

John Koleszar's avatar
John Koleszar committed
604
  int b_calculate_ssimg;
605
  int b_calculate_blockiness;
606

607
  int b_calculate_consistency;
608

609
  double total_inconsistency;
610
  double worst_consistency;
611 612
  Ssimv *ssim_vars;
  Metrics metrics;
John Koleszar's avatar
John Koleszar committed
613
#endif
John Koleszar's avatar
John Koleszar committed
614
  int b_calculate_psnr;
615

John Koleszar's avatar
John Koleszar committed
616
  int droppable;
617

618 619
  int initial_width;
  int initial_height;
620 621 622 623
  int initial_mbs;  // Number of MBs in the full-size frame; to be used to
                    // normalize the firstpass stats. This will differ from the
                    // number of MBs in the current frame when the frame is
                    // scaled.
624

625 626
  int use_svc;

627
  SVC svc;
628

629 630 631 632 633
  // Store frame variance info in SOURCE_VAR_BASED_PARTITION search type.
  diff *source_diff_var;
  // The threshold used in SOURCE_VAR_BASED_PARTITION search type.
  unsigned int source_var_thresh;
  int frames_till_next_var_check;
634

635 636
  int frame_flags;

637 638
  search_site_config ss_cfg;

639
  int mbmode_cost[INTRA_MODES];
640
  unsigned int inter_mode_cost[INTER_MODE_CONTEXTS][INTER_MODES];
641
  int intra_uv_mode_cost[FRAME_TYPES][INTRA_MODES][INTRA_MODES];
642 643
  int y_mode_costs[INTRA_MODES][INTRA_MODES][INTRA_MODES];
  int switchable_interp_costs[SWITCHABLE_FILTER_CONTEXTS][SWITCHABLE_FILTERS];
644 645
  int partition_cost[PARTITION_CONTEXTS][PARTITION_TYPES];

646
  int multi_arf_allowed;
647
  int multi_arf_enabled;
648
  int multi_arf_last_grp_enabled;
649

650
#if CONFIG_VP9_TEMPORAL_DENOISING
651 652
  VP9_DENOISER denoiser;
#endif
653

654
  int resize_pending;
655
  RESIZE_STATE resize_state;
656
  int external_resize;
657 658 659 660 661
  int resize_scale_num;
  int resize_scale_den;
  int resize_avg_qp;
  int resize_buffer_underflow;
  int resize_count;
662

663 664
  int use_skin_detection;

665 666
  int target_level;

667 668
  NOISE_ESTIMATE noise_estimate;

669 670 671
  // Count on how many consecutive times a block uses small/zeromv for encoding.
  uint8_t *consec_zero_mv;

672
  // VAR_BASED_PARTITION thresholds
673 674 675
  // 0 - threshold_64x64; 1 - threshold_32x32;
  // 2 - threshold_16x16; 3 - vbp_threshold_8x8;
  int64_t vbp_thresholds[4];
676 677
  int64_t vbp_threshold_minmax;
  int64_t vbp_threshold_sad;
678 679
  // Threshold used for partition copy
  int64_t vbp_threshold_copy;
680 681
  BLOCK_SIZE vbp_bsize_min;

682 683
  // Multi-threading
  int num_workers;
684
  VPxWorker *workers;
685 686
  struct EncWorkerData *tile_thr_data;
  VP9LfSync lf_row_sync;
687
  struct VP9BitstreamWorkerData *vp9_bitstream_worker_data;
688 689 690

  int keep_level_stats;
  Vp9LevelInfo level_info;
691 692 693
  MultiThreadHandle multi_thread_ctxt;
  void (*row_mt_sync_read_ptr)(VP9RowMTSync *const, int, int);
  void (*row_mt_sync_write_ptr)(VP9RowMTSync *const, int, int, const int);
694
  ARNRFilterData arnr_filter_data;
695

696
  int row_mt;
697
  unsigned int row_mt_bit_exact;
698 699 700 701

  // Previous Partition Info
  BLOCK_SIZE *prev_partition;
  int8_t *prev_segment_id;
702 703 704 705 706 707
  // Used to save the status of whether a block has a low variance in
  // choose_partitioning. 0 for 64x64, 1~2 for 64x32, 3~4 for 32x64, 5~8 for
  // 32x32, 9~24 for 16x16.
  // This is for the last frame and is copied to the current frame
  // when partition copy happens.
  uint8_t *prev_variance_low;
708 709
  uint8_t *copied_frame_cnt;
  uint8_t max_copied_frame;
710 711
  // If the last frame is dropped, we don't copy partition.
  uint8_t last_frame_dropped;
712

713 714 715
  // For each superblock: keeps track of the last time (in frame distance) the
  // the superblock did not have low source sad.
  uint8_t *content_state_sb_fd;
716

717 718
  int compute_source_sad_onepass;

719
  LevelConstraint level_constraint;
720
} VP9_COMP;
John Koleszar's avatar
John Koleszar committed
721

722
void vp9_initialize_enc(void);
723

724 725
struct VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf,
                                       BufferPool *const pool);
726 727
void vp9_remove_compressor(VP9_COMP *cpi);

728
void vp9_change_config(VP9_COMP *cpi, const VP9EncoderConfig *oxcf);
729

730 731
// receive a frames worth of data. caller can assume that a copy of this
// frame is made and not just a copy of the pointer..
732
int vp9_receive_raw_frame(VP9_COMP *cpi, vpx_enc_frame_flags_t frame_flags,
733 734 735 736
                          YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
                          int64_t end_time_stamp);

int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
737 738
                            size_t *size, uint8_t *dest, int64_t *time_stamp,
                            int64_t *time_end, int flush);
739 740 741 742 743 744

int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
                              vp9_ppflags_t *flags);

int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags);

745
void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags);
746 747 748 749 750 751 752 753 754

int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
                           YV12_BUFFER_CONFIG *sd);

int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
                          YV12_BUFFER_CONFIG *sd);

int vp9_update_entropy(VP9_COMP *cpi, int update);

755
int vp9_set_active_map(VP9_COMP *cpi, unsigned char *map, int rows, int cols);
756

757 758
int vp9_get_active_map(VP9_COMP *cpi, unsigned char *map, int rows, int cols);

759 760
int vp9_set_internal_size(VP9_COMP *cpi, VPX_SCALING horiz_mode,
                          VPX_SCALING vert_mode);
761 762 763 764 765 766 767 768

int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
                         unsigned int height);

void vp9_set_svc(VP9_COMP *cpi, int use_svc);

int vp9_get_quantizer(struct VP9_COMP *cpi);

769
static INLINE int frame_is_kf_gf_arf(const VP9_COMP *cpi) {
770
  return frame_is_intra_only(&cpi->common) || cpi->refresh_alt_ref_frame ||
771 772 773
         (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref);
}

774 775
static INLINE int get_ref_frame_map_idx(const VP9_COMP *cpi,
                                        MV_REFERENCE_FRAME ref_frame) {
776 777 778 779 780 781 782 783 784
  if (ref_frame == LAST_FRAME) {
    return cpi->lst_fb_idx;
  } else if (ref_frame == GOLDEN_FRAME) {
    return cpi->gld_fb_idx;
  } else {
    return cpi->alt_fb_idx;
  }
}

785 786 787 788 789 790 791
static INLINE int get_ref_frame_buf_idx(const VP9_COMP *const cpi,
                                        int ref_frame) {
  const VP9_COMMON *const cm = &cpi->common;
  const int map_idx = get_ref_frame_map_idx(cpi, ref_frame);
  return (map_idx != INVALID_IDX) ? cm->ref_frame_map[map_idx] : INVALID_IDX;
}

792 793
static INLINE YV12_BUFFER_CONFIG *get_ref_frame_buffer(
    VP9_COMP *cpi, MV_REFERENCE_FRAME ref_frame) {
794
  VP9_COMMON *const cm = &cpi->common;
795
  const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
796 797
  return buf_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[buf_idx].buf
                                : NULL;
798 799
}

800
static INLINE int get_token_alloc(int mb_rows, int mb_cols) {
801 802
  // TODO(JBB): double check we can't exceed this token count if we have a
  // 32x32 transform crossing a boundary at a multiple of 16.
803 804 805 806 807 808
  // mb_rows, cols are in units of 16 pixels. We assume 3 planes all at full
  // resolution. We assume up to 1 token per pixel, and then allow
  // a head room of 4.
  return mb_rows * mb_cols * (16 * 16 * 3 + 4);
}

809 810 811 812 813 814 815 816 817
// Get the allocated token size for a tile. It does the same calculation as in
// the frame token allocation.
static INLINE int allocated_tokens(TileInfo tile) {
  int tile_mb_rows = (tile.mi_row_end - tile.mi_row_start + 1) >> 1;
  int tile_mb_cols = (tile.mi_col_end - tile.mi_col_start + 1) >> 1;

  return get_token_alloc(tile_mb_rows, tile_mb_cols);
}

818 819 820 821 822 823 824 825 826 827 828 829 830 831
static INLINE void get_start_tok(VP9_COMP *cpi, int tile_row, int tile_col,
                                 int mi_row, TOKENEXTRA **tok) {
  VP9_COMMON *const cm = &cpi->common;
  const int tile_cols = 1 << cm->log2_tile_cols;
  TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
  const TileInfo *const tile_info = &this_tile->tile_info;

  int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
  const int mb_row = (mi_row - tile_info->mi_row_start) >> 1;

  *tok =
      cpi->tile_tok[tile_row][tile_col] + get_token_alloc(mb_row, tile_mb_cols);
}

832
int64_t vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b);
833
#if CONFIG_VP9_HIGHBITDEPTH
834 835
int64_t vp9_highbd_get_y_sse(const YV12_BUFFER_CONFIG *a,
                             const YV12_BUFFER_CONFIG *b);
836
#endif  // CONFIG_VP9_HIGHBITDEPTH
837

838 839 840 841
void vp9_scale_references(VP9_COMP *cpi);

void vp9_update_reference_frames(VP9_COMP *cpi);

842 843
void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv);

844 845 846 847 848 849 850 851
YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(
    VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
    YV12_BUFFER_CONFIG *scaled_temp, INTERP_FILTER filter_type,
    int phase_scaler, INTERP_FILTER filter_type2, int phase_scaler2);

YV12_BUFFER_CONFIG *vp9_scale_if_required(
    VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
    int use_normative_scaler, INTERP_FILTER filter_type, int phase_scaler);
852

853 854
void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags);

855
static INLINE int is_two_pass_svc(const struct VP9_COMP *const cpi) {
856 857 858 859 860
  return cpi->use_svc && cpi->oxcf.pass != 0;
}

static INLINE int is_one_pass_cbr_svc(const struct VP9_COMP *const cpi) {
  return (cpi->use_svc && cpi->oxcf.pass == 0);
861 862
}

863 864 865 866 867 868 869 870
#if CONFIG_VP9_TEMPORAL_DENOISING
static INLINE int denoise_svc(const struct VP9_COMP *const cpi) {
  return (!cpi->use_svc ||
          (cpi->use_svc &&
           cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1));
}
#endif

871
#define MIN_LOOKAHEAD_FOR_ARFS 4
872
static INLINE int is_altref_enabled(const VP9_COMP *const cpi) {
873
  return !(cpi->oxcf.mode == REALTIME && cpi->oxcf.rc_mode == VPX_CBR) &&
874
         cpi->oxcf.lag_in_frames >= MIN_LOOKAHEAD_FOR_ARFS &&
875
         (cpi->oxcf.enable_auto_arf &&
876
          (!is_two_pass_svc(cpi) ||
877
           cpi->oxcf.ss_enable_auto_arf[cpi->svc.spatial_layer_id]));
878 879
}

880 881 882
static INLINE void set_ref_ptrs(VP9_COMMON *cm, MACROBLOCKD *xd,
                                MV_REFERENCE_FRAME ref0,
                                MV_REFERENCE_FRAME ref1) {
883 884 885 886
  xd->block_refs[0] =
      &cm->frame_refs[ref0 >= LAST_FRAME ? ref0 - LAST_FRAME : 0];
  xd->block_refs[1] =
      &cm->frame_refs[ref1 >= LAST_FRAME ? ref1 - LAST_FRAME : 0];
887 888
}

889 890
static INLINE int get_chessboard_index(const int frame_index) {
  return frame_index & 0x1;
891 892
}

893 894
static INLINE int *cond_cost_list(const struct VP9_COMP *cpi, int *cost_list) {
  return cpi->sf.mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL;
895 896
}

897 898 899 900 901 902 903 904 905 906 907 908
static INLINE int get_num_vert_units(TileInfo tile, int shift) {
  int num_vert_units =
      (tile.mi_row_end - tile.mi_row_start + (1 << shift) - 1) >> shift;
  return num_vert_units;
}

static INLINE int get_num_cols(TileInfo tile, int shift) {
  int num_cols =
      (tile.mi_col_end - tile.mi_col_start + (1 << shift) - 1) >> shift;
  return num_cols;
}

909 910 911 912 913 914 915 916
static INLINE int get_level_index(VP9_LEVEL level) {
  int i;
  for (i = 0; i < VP9_LEVELS; ++i) {
    if (level == vp9_level_defs[i].level) return i;
  }
  return -1;
}

917 918 919 920 921 922 923 924 925 926 927 928
// Return the log2 value of max column tiles corresponding to the level that
// the picture size fits into.
static INLINE int log_tile_cols_from_picsize_level(uint32_t pic_size) {
  int i;
  for (i = LEVEL_1; i < LEVEL_MAX; ++i) {
    if (vp9_level_defs[i].max_luma_picture_size > pic_size) {
      return get_msb(vp9_level_defs[i].max_col_tiles);
    }
  }
  return INT_MAX;
}

929 930
VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec);

931 932
void vp9_new_framerate(VP9_COMP *cpi, double framerate);

933
void vp9_set_row_mt(VP9_COMP *cpi);
934

935 936
#define LAYER_IDS_TO_IDX(sl, tl, num_tl) ((sl) * (num_tl) + (tl))

937 938 939 940
#ifdef __cplusplus
}  // extern "C"
#endif

941
#endif  // VP9_ENCODER_VP9_ENCODER_H_