]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_encoder.h
Merge "vp9-rtc: Fix condition in regulate_q for cyclic_refresh"
[libvpx] / vp9 / encoder / vp9_encoder.h
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  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.
9  */
10
11 #ifndef VPX_VP9_ENCODER_VP9_ENCODER_H_
12 #define VPX_VP9_ENCODER_VP9_ENCODER_H_
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 #if CONFIG_INTERNAL_STATS
20 #include "vpx_dsp/ssim.h"
21 #endif
22 #include "vpx_dsp/variance.h"
23 #include "vpx_dsp/psnr.h"
24 #include "vpx_ports/system_state.h"
25 #include "vpx_util/vpx_thread.h"
26 #include "vpx_util/vpx_timestamp.h"
27
28 #include "vp9/common/vp9_alloccommon.h"
29 #include "vp9/common/vp9_ppflags.h"
30 #include "vp9/common/vp9_entropymode.h"
31 #include "vp9/common/vp9_thread_common.h"
32 #include "vp9/common/vp9_onyxc_int.h"
33
34 #if !CONFIG_REALTIME_ONLY
35 #include "vp9/encoder/vp9_alt_ref_aq.h"
36 #endif
37 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
38 #include "vp9/encoder/vp9_context_tree.h"
39 #include "vp9/encoder/vp9_encodemb.h"
40 #include "vp9/encoder/vp9_ethread.h"
41 #include "vp9/encoder/vp9_firstpass.h"
42 #include "vp9/encoder/vp9_job_queue.h"
43 #include "vp9/encoder/vp9_lookahead.h"
44 #include "vp9/encoder/vp9_mbgraph.h"
45 #include "vp9/encoder/vp9_mcomp.h"
46 #include "vp9/encoder/vp9_noise_estimate.h"
47 #include "vp9/encoder/vp9_quantize.h"
48 #include "vp9/encoder/vp9_ratectrl.h"
49 #include "vp9/encoder/vp9_rd.h"
50 #include "vp9/encoder/vp9_speed_features.h"
51 #include "vp9/encoder/vp9_svc_layercontext.h"
52 #include "vp9/encoder/vp9_tokenize.h"
53
54 #if CONFIG_VP9_TEMPORAL_DENOISING
55 #include "vp9/encoder/vp9_denoiser.h"
56 #endif
57
58 #ifdef __cplusplus
59 extern "C" {
60 #endif
61
62 // vp9 uses 10,000,000 ticks/second as time stamp
63 #define TICKS_PER_SEC 10000000
64
65 typedef struct {
66   int nmvjointcost[MV_JOINTS];
67   int nmvcosts[2][MV_VALS];
68   int nmvcosts_hp[2][MV_VALS];
69
70   vpx_prob segment_pred_probs[PREDICTION_PROBS];
71
72   unsigned char *last_frame_seg_map_copy;
73
74   // 0 = Intra, Last, GF, ARF
75   signed char last_ref_lf_deltas[MAX_REF_LF_DELTAS];
76   // 0 = ZERO_MV, MV
77   signed char last_mode_lf_deltas[MAX_MODE_LF_DELTAS];
78
79   FRAME_CONTEXT fc;
80 } CODING_CONTEXT;
81
82 typedef enum {
83   // encode_breakout is disabled.
84   ENCODE_BREAKOUT_DISABLED = 0,
85   // encode_breakout is enabled.
86   ENCODE_BREAKOUT_ENABLED = 1,
87   // encode_breakout is enabled with small max_thresh limit.
88   ENCODE_BREAKOUT_LIMITED = 2
89 } ENCODE_BREAKOUT_TYPE;
90
91 typedef enum {
92   NORMAL = 0,
93   FOURFIVE = 1,
94   THREEFIVE = 2,
95   ONETWO = 3
96 } VPX_SCALING;
97
98 typedef enum {
99   // Good Quality Fast Encoding. The encoder balances quality with the amount of
100   // time it takes to encode the output. Speed setting controls how fast.
101   GOOD,
102
103   // The encoder places priority on the quality of the output over encoding
104   // speed. The output is compressed at the highest possible quality. This
105   // option takes the longest amount of time to encode. Speed setting ignored.
106   BEST,
107
108   // Realtime/Live Encoding. This mode is optimized for realtime encoding (for
109   // example, capturing a television signal or feed from a live camera). Speed
110   // setting controls how fast.
111   REALTIME
112 } MODE;
113
114 typedef enum {
115   FRAMEFLAGS_KEY = 1 << 0,
116   FRAMEFLAGS_GOLDEN = 1 << 1,
117   FRAMEFLAGS_ALTREF = 1 << 2,
118 } FRAMETYPE_FLAGS;
119
120 typedef enum {
121   NO_AQ = 0,
122   VARIANCE_AQ = 1,
123   COMPLEXITY_AQ = 2,
124   CYCLIC_REFRESH_AQ = 3,
125   EQUATOR360_AQ = 4,
126   PERCEPTUAL_AQ = 5,
127   PSNR_AQ = 6,
128   // AQ based on lookahead temporal
129   // variance (only valid for altref frames)
130   LOOKAHEAD_AQ = 7,
131   AQ_MODE_COUNT  // This should always be the last member of the enum
132 } AQ_MODE;
133
134 typedef enum {
135   RESIZE_NONE = 0,    // No frame resizing allowed (except for SVC).
136   RESIZE_FIXED = 1,   // All frames are coded at the specified dimension.
137   RESIZE_DYNAMIC = 2  // Coded size of each frame is determined by the codec.
138 } RESIZE_TYPE;
139
140 typedef enum {
141   kInvalid = 0,
142   kLowSadLowSumdiff = 1,
143   kLowSadHighSumdiff = 2,
144   kHighSadLowSumdiff = 3,
145   kHighSadHighSumdiff = 4,
146   kLowVarHighSumdiff = 5,
147   kVeryHighSad = 6,
148 } CONTENT_STATE_SB;
149
150 typedef struct VP9EncoderConfig {
151   BITSTREAM_PROFILE profile;
152   vpx_bit_depth_t bit_depth;     // Codec bit-depth.
153   int width;                     // width of data passed to the compressor
154   int height;                    // height of data passed to the compressor
155   unsigned int input_bit_depth;  // Input bit depth.
156   double init_framerate;         // set to passed in framerate
157   vpx_rational_t g_timebase;  // equivalent to g_timebase in vpx_codec_enc_cfg_t
158   vpx_rational64_t g_timebase_in_ts;  // g_timebase * TICKS_PER_SEC
159
160   int64_t target_bandwidth;  // bandwidth to be used in bits per second
161
162   int noise_sensitivity;  // pre processing blur: recommendation 0
163   int sharpness;          // sharpening output: recommendation 0:
164   int speed;
165   // maximum allowed bitrate for any intra frame in % of bitrate target.
166   unsigned int rc_max_intra_bitrate_pct;
167   // maximum allowed bitrate for any inter frame in % of bitrate target.
168   unsigned int rc_max_inter_bitrate_pct;
169   // percent of rate boost for golden frame in CBR mode.
170   unsigned int gf_cbr_boost_pct;
171
172   MODE mode;
173   int pass;
174
175   // Key Framing Operations
176   int auto_key;  // autodetect cut scenes and set the keyframes
177   int key_freq;  // maximum distance to key frame.
178
179   int lag_in_frames;  // how many frames lag before we start encoding
180
181   // ----------------------------------------------------------------
182   // DATARATE CONTROL OPTIONS
183
184   // vbr, cbr, constrained quality or constant quality
185   enum vpx_rc_mode rc_mode;
186
187   // buffer targeting aggressiveness
188   int under_shoot_pct;
189   int over_shoot_pct;
190
191   // buffering parameters
192   int64_t starting_buffer_level_ms;
193   int64_t optimal_buffer_level_ms;
194   int64_t maximum_buffer_size_ms;
195
196   // Frame drop threshold.
197   int drop_frames_water_mark;
198
199   // controlling quality
200   int fixed_q;
201   int worst_allowed_q;
202   int best_allowed_q;
203   int cq_level;
204   AQ_MODE aq_mode;  // Adaptive Quantization mode
205
206   // Special handling of Adaptive Quantization for AltRef frames
207   int alt_ref_aq;
208
209   // Internal frame size scaling.
210   RESIZE_TYPE resize_mode;
211   int scaled_frame_width;
212   int scaled_frame_height;
213
214   // Enable feature to reduce the frame quantization every x frames.
215   int frame_periodic_boost;
216
217   // two pass datarate control
218   int two_pass_vbrbias;  // two pass datarate control tweaks
219   int two_pass_vbrmin_section;
220   int two_pass_vbrmax_section;
221   int vbr_corpus_complexity;  // 0 indicates corpus vbr disabled
222   // END DATARATE CONTROL OPTIONS
223   // ----------------------------------------------------------------
224
225   // Spatial and temporal scalability.
226   int ss_number_layers;  // Number of spatial layers.
227   int ts_number_layers;  // Number of temporal layers.
228   // Bitrate allocation for spatial layers.
229   int layer_target_bitrate[VPX_MAX_LAYERS];
230   int ss_target_bitrate[VPX_SS_MAX_LAYERS];
231   int ss_enable_auto_arf[VPX_SS_MAX_LAYERS];
232   // Bitrate allocation (CBR mode) and framerate factor, for temporal layers.
233   int ts_rate_decimator[VPX_TS_MAX_LAYERS];
234
235   int enable_auto_arf;
236
237   int encode_breakout;  // early breakout : for video conf recommend 800
238
239   /* Bitfield defining the error resiliency features to enable.
240    * Can provide decodable frames after losses in previous
241    * frames and decodable partitions after losses in the same frame.
242    */
243   unsigned int error_resilient_mode;
244
245   /* Bitfield defining the parallel decoding mode where the
246    * decoding in successive frames may be conducted in parallel
247    * just by decoding the frame headers.
248    */
249   unsigned int frame_parallel_decoding_mode;
250
251   int arnr_max_frames;
252   int arnr_strength;
253
254   int min_gf_interval;
255   int max_gf_interval;
256
257   int tile_columns;
258   int tile_rows;
259
260   int enable_tpl_model;
261
262   int max_threads;
263
264   unsigned int target_level;
265
266   vpx_fixed_buf_t two_pass_stats_in;
267
268 #if CONFIG_FP_MB_STATS
269   vpx_fixed_buf_t firstpass_mb_stats_in;
270 #endif
271
272   vp8e_tuning tuning;
273   vp9e_tune_content content;
274 #if CONFIG_VP9_HIGHBITDEPTH
275   int use_highbitdepth;
276 #endif
277   vpx_color_space_t color_space;
278   vpx_color_range_t color_range;
279   int render_width;
280   int render_height;
281   VP9E_TEMPORAL_LAYERING_MODE temporal_layering_mode;
282
283   int row_mt;
284   unsigned int motion_vector_unit_test;
285   int delta_q_uv;
286 } VP9EncoderConfig;
287
288 static INLINE int is_lossless_requested(const VP9EncoderConfig *cfg) {
289   return cfg->best_allowed_q == 0 && cfg->worst_allowed_q == 0;
290 }
291
292 typedef struct TplDepStats {
293   int64_t intra_cost;
294   int64_t inter_cost;
295   int64_t mc_flow;
296   int64_t mc_dep_cost;
297   int64_t mc_ref_cost;
298
299   int ref_frame_index;
300   int_mv mv;
301 } TplDepStats;
302
303 #if CONFIG_NON_GREEDY_MV
304
305 #define ZERO_MV_MODE 0
306 #define NEW_MV_MODE 1
307 #define NEAREST_MV_MODE 2
308 #define NEAR_MV_MODE 3
309 #define MAX_MV_MODE 4
310 #endif
311
312 typedef struct TplDepFrame {
313   uint8_t is_valid;
314   TplDepStats *tpl_stats_ptr;
315   int stride;
316   int width;
317   int height;
318   int mi_rows;
319   int mi_cols;
320   int base_qindex;
321 #if CONFIG_NON_GREEDY_MV
322   int lambda;
323   int *mv_mode_arr[3];
324   double *rd_diff_arr[3];
325 #endif
326 } TplDepFrame;
327
328 #define TPL_DEP_COST_SCALE_LOG2 4
329
330 // TODO(jingning) All spatially adaptive variables should go to TileDataEnc.
331 typedef struct TileDataEnc {
332   TileInfo tile_info;
333   int thresh_freq_fact[BLOCK_SIZES][MAX_MODES];
334 #if CONFIG_CONSISTENT_RECODE
335   int thresh_freq_fact_prev[BLOCK_SIZES][MAX_MODES];
336 #endif
337   int8_t mode_map[BLOCK_SIZES][MAX_MODES];
338   FIRSTPASS_DATA fp_data;
339   VP9RowMTSync row_mt_sync;
340
341   // Used for adaptive_rd_thresh with row multithreading
342   int *row_base_thresh_freq_fact;
343 } TileDataEnc;
344
345 typedef struct RowMTInfo {
346   JobQueueHandle job_queue_hdl;
347 #if CONFIG_MULTITHREAD
348   pthread_mutex_t job_mutex;
349 #endif
350 } RowMTInfo;
351
352 typedef struct {
353   TOKENEXTRA *start;
354   TOKENEXTRA *stop;
355   unsigned int count;
356 } TOKENLIST;
357
358 typedef struct MultiThreadHandle {
359   int allocated_tile_rows;
360   int allocated_tile_cols;
361   int allocated_vert_unit_rows;
362
363   // Frame level params
364   int num_tile_vert_sbs[MAX_NUM_TILE_ROWS];
365
366   // Job Queue structure and handles
367   JobQueue *job_queue;
368
369   int jobs_per_tile_col;
370
371   RowMTInfo row_mt_info[MAX_NUM_TILE_COLS];
372   int thread_id_to_tile_id[MAX_NUM_THREADS];  // Mapping of threads to tiles
373 } MultiThreadHandle;
374
375 typedef struct RD_COUNTS {
376   vp9_coeff_count coef_counts[TX_SIZES][PLANE_TYPES];
377   int64_t comp_pred_diff[REFERENCE_MODES];
378   int64_t filter_diff[SWITCHABLE_FILTER_CONTEXTS];
379 } RD_COUNTS;
380
381 typedef struct ThreadData {
382   MACROBLOCK mb;
383   RD_COUNTS rd_counts;
384   FRAME_COUNTS *counts;
385
386   PICK_MODE_CONTEXT *leaf_tree;
387   PC_TREE *pc_tree;
388   PC_TREE *pc_root;
389 } ThreadData;
390
391 struct EncWorkerData;
392
393 typedef struct ActiveMap {
394   int enabled;
395   int update;
396   unsigned char *map;
397 } ActiveMap;
398
399 typedef enum { Y, U, V, ALL } STAT_TYPE;
400
401 typedef struct IMAGE_STAT {
402   double stat[ALL + 1];
403   double worst;
404 } ImageStat;
405
406 // Kf noise filtering currently disabled by default in build.
407 // #define ENABLE_KF_DENOISE 1
408
409 #define CPB_WINDOW_SIZE 4
410 #define FRAME_WINDOW_SIZE 128
411 #define SAMPLE_RATE_GRACE_P 0.015
412 #define VP9_LEVELS 14
413
414 typedef enum {
415   LEVEL_UNKNOWN = 0,
416   LEVEL_AUTO = 1,
417   LEVEL_1 = 10,
418   LEVEL_1_1 = 11,
419   LEVEL_2 = 20,
420   LEVEL_2_1 = 21,
421   LEVEL_3 = 30,
422   LEVEL_3_1 = 31,
423   LEVEL_4 = 40,
424   LEVEL_4_1 = 41,
425   LEVEL_5 = 50,
426   LEVEL_5_1 = 51,
427   LEVEL_5_2 = 52,
428   LEVEL_6 = 60,
429   LEVEL_6_1 = 61,
430   LEVEL_6_2 = 62,
431   LEVEL_MAX = 255
432 } VP9_LEVEL;
433
434 typedef struct {
435   VP9_LEVEL level;
436   uint64_t max_luma_sample_rate;
437   uint32_t max_luma_picture_size;
438   uint32_t max_luma_picture_breadth;
439   double average_bitrate;  // in kilobits per second
440   double max_cpb_size;     // in kilobits
441   double compression_ratio;
442   uint8_t max_col_tiles;
443   uint32_t min_altref_distance;
444   uint8_t max_ref_frame_buffers;
445 } Vp9LevelSpec;
446
447 extern const Vp9LevelSpec vp9_level_defs[VP9_LEVELS];
448
449 typedef struct {
450   int64_t ts;  // timestamp
451   uint32_t luma_samples;
452   uint32_t size;  // in bytes
453 } FrameRecord;
454
455 typedef struct {
456   FrameRecord buf[FRAME_WINDOW_SIZE];
457   uint8_t start;
458   uint8_t len;
459 } FrameWindowBuffer;
460
461 typedef struct {
462   uint8_t seen_first_altref;
463   uint32_t frames_since_last_altref;
464   uint64_t total_compressed_size;
465   uint64_t total_uncompressed_size;
466   double time_encoded;  // in seconds
467   FrameWindowBuffer frame_window_buffer;
468   int ref_refresh_map;
469 } Vp9LevelStats;
470
471 typedef struct {
472   Vp9LevelStats level_stats;
473   Vp9LevelSpec level_spec;
474 } Vp9LevelInfo;
475
476 typedef enum {
477   BITRATE_TOO_LARGE = 0,
478   LUMA_PIC_SIZE_TOO_LARGE,
479   LUMA_PIC_BREADTH_TOO_LARGE,
480   LUMA_SAMPLE_RATE_TOO_LARGE,
481   CPB_TOO_LARGE,
482   COMPRESSION_RATIO_TOO_SMALL,
483   TOO_MANY_COLUMN_TILE,
484   ALTREF_DIST_TOO_SMALL,
485   TOO_MANY_REF_BUFFER,
486   TARGET_LEVEL_FAIL_IDS
487 } TARGET_LEVEL_FAIL_ID;
488
489 typedef struct {
490   int8_t level_index;
491   uint8_t fail_flag;
492   int max_frame_size;   // in bits
493   double max_cpb_size;  // in bits
494 } LevelConstraint;
495
496 typedef struct ARNRFilterData {
497   YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS];
498   int strength;
499   int frame_count;
500   int alt_ref_index;
501   struct scale_factors sf;
502 } ARNRFilterData;
503
504 typedef struct EncFrameBuf {
505   int mem_valid;
506   int released;
507   YV12_BUFFER_CONFIG frame;
508 } EncFrameBuf;
509
510 // Maximum operating frame buffer size needed for a GOP using ARF reference.
511 #define MAX_ARF_GOP_SIZE (2 * MAX_LAG_BUFFERS)
512 #define MAX_KMEANS_GROUPS 8
513
514 typedef struct KMEANS_DATA {
515   double value;
516   int pos;
517   int group_idx;
518 } KMEANS_DATA;
519
520 #if CONFIG_RATE_CTRL
521 typedef struct ENCODE_COMMAND {
522   int use_external_quantize_index;
523   int external_quantize_index;
524 } ENCODE_COMMAND;
525
526 typedef struct PARTITION_INFO {
527   int row;           // row pixel offset of current 4x4 block
528   int column;        // column pixel offset of current 4x4 block
529   int row_start;     // row pixel offset of the start of the prediction block
530   int column_start;  // column pixel offset of the start of the prediction block
531   int width;         // prediction block width
532   int height;        // prediction block height
533 } PARTITION_INFO;
534
535 static INLINE void encode_command_init(ENCODE_COMMAND *encode_command) {
536   vp9_zero(*encode_command);
537   encode_command->use_external_quantize_index = 0;
538   encode_command->external_quantize_index = -1;
539 }
540
541 static INLINE void encode_command_set_external_quantize_index(
542     ENCODE_COMMAND *encode_command, int quantize_index) {
543   encode_command->use_external_quantize_index = 1;
544   encode_command->external_quantize_index = quantize_index;
545 }
546
547 static INLINE void encode_command_reset_external_quantize_index(
548     ENCODE_COMMAND *encode_command) {
549   encode_command->use_external_quantize_index = 0;
550   encode_command->external_quantize_index = -1;
551 }
552
553 // Returns number of units in size of 4, if not multiple not a multiple of 4,
554 // round it up. For example, size is 7, return 3.
555 static INLINE int get_num_unit_4x4(int size) { return (size + 3) >> 2; }
556 #endif  // CONFIG_RATE_CTRL
557
558 typedef struct VP9_COMP {
559   FRAME_INFO frame_info;
560   QUANTS quants;
561   ThreadData td;
562   MB_MODE_INFO_EXT *mbmi_ext_base;
563   DECLARE_ALIGNED(16, int16_t, y_dequant[QINDEX_RANGE][8]);
564   DECLARE_ALIGNED(16, int16_t, uv_dequant[QINDEX_RANGE][8]);
565   VP9_COMMON common;
566   VP9EncoderConfig oxcf;
567   struct lookahead_ctx *lookahead;
568   struct lookahead_entry *alt_ref_source;
569
570   YV12_BUFFER_CONFIG *Source;
571   YV12_BUFFER_CONFIG *Last_Source;  // NULL for first frame and alt_ref frames
572   YV12_BUFFER_CONFIG *un_scaled_source;
573   YV12_BUFFER_CONFIG scaled_source;
574   YV12_BUFFER_CONFIG *unscaled_last_source;
575   YV12_BUFFER_CONFIG scaled_last_source;
576 #ifdef ENABLE_KF_DENOISE
577   YV12_BUFFER_CONFIG raw_unscaled_source;
578   YV12_BUFFER_CONFIG raw_scaled_source;
579 #endif
580   YV12_BUFFER_CONFIG *raw_source_frame;
581
582   BLOCK_SIZE tpl_bsize;
583   TplDepFrame tpl_stats[MAX_ARF_GOP_SIZE];
584   YV12_BUFFER_CONFIG *tpl_recon_frames[REF_FRAMES];
585   EncFrameBuf enc_frame_buf[REF_FRAMES];
586 #if CONFIG_MULTITHREAD
587   pthread_mutex_t kmeans_mutex;
588 #endif
589   int kmeans_data_arr_alloc;
590   KMEANS_DATA *kmeans_data_arr;
591   int kmeans_data_size;
592   int kmeans_data_stride;
593   double kmeans_ctr_ls[MAX_KMEANS_GROUPS];
594   double kmeans_boundary_ls[MAX_KMEANS_GROUPS];
595   int kmeans_count_ls[MAX_KMEANS_GROUPS];
596   int kmeans_ctr_num;
597 #if CONFIG_NON_GREEDY_MV
598   MotionFieldInfo motion_field_info;
599   int tpl_ready;
600   int_mv *select_mv_arr;
601 #endif
602
603   TileDataEnc *tile_data;
604   int allocated_tiles;  // Keep track of memory allocated for tiles.
605
606   // For a still frame, this flag is set to 1 to skip partition search.
607   int partition_search_skippable_frame;
608
609   int scaled_ref_idx[REFS_PER_FRAME];
610   int lst_fb_idx;
611   int gld_fb_idx;
612   int alt_fb_idx;
613
614   int ref_fb_idx[REF_FRAMES];
615
616   int refresh_last_frame;
617   int refresh_golden_frame;
618   int refresh_alt_ref_frame;
619
620   int ext_refresh_frame_flags_pending;
621   int ext_refresh_last_frame;
622   int ext_refresh_golden_frame;
623   int ext_refresh_alt_ref_frame;
624
625   int ext_refresh_frame_context_pending;
626   int ext_refresh_frame_context;
627
628   int64_t norm_wiener_variance;
629   int64_t *mb_wiener_variance;
630   int mb_wiener_var_rows;
631   int mb_wiener_var_cols;
632   double *mi_ssim_rdmult_scaling_factors;
633
634   YV12_BUFFER_CONFIG last_frame_uf;
635
636   TOKENEXTRA *tile_tok[4][1 << 6];
637   TOKENLIST *tplist[4][1 << 6];
638
639   // Ambient reconstruction err target for force key frames
640   int64_t ambient_err;
641
642   RD_OPT rd;
643
644   CODING_CONTEXT coding_context;
645
646   int *nmvcosts[2];
647   int *nmvcosts_hp[2];
648   int *nmvsadcosts[2];
649   int *nmvsadcosts_hp[2];
650
651   int64_t last_time_stamp_seen;
652   int64_t last_end_time_stamp_seen;
653   int64_t first_time_stamp_ever;
654
655   RATE_CONTROL rc;
656   double framerate;
657
658   int interp_filter_selected[REF_FRAMES][SWITCHABLE];
659
660   struct vpx_codec_pkt_list *output_pkt_list;
661
662   MBGRAPH_FRAME_STATS mbgraph_stats[MAX_LAG_BUFFERS];
663   int mbgraph_n_frames;  // number of frames filled in the above
664   int static_mb_pct;     // % forced skip mbs by segmentation
665   int ref_frame_flags;
666
667   SPEED_FEATURES sf;
668
669   uint32_t max_mv_magnitude;
670   int mv_step_param;
671
672   int allow_comp_inter_inter;
673
674   // Default value is 1. From first pass stats, encode_breakout may be disabled.
675   ENCODE_BREAKOUT_TYPE allow_encode_breakout;
676
677   // Get threshold from external input. A suggested threshold is 800 for HD
678   // clips, and 300 for < HD clips.
679   int encode_breakout;
680
681   uint8_t *segmentation_map;
682
683   uint8_t *skin_map;
684
685   // segment threashold for encode breakout
686   int segment_encode_breakout[MAX_SEGMENTS];
687
688   CYCLIC_REFRESH *cyclic_refresh;
689   ActiveMap active_map;
690
691   fractional_mv_step_fp *find_fractional_mv_step;
692   struct scale_factors me_sf;
693   vp9_diamond_search_fn_t diamond_search_sad;
694   vp9_variance_fn_ptr_t fn_ptr[BLOCK_SIZES];
695   uint64_t time_receive_data;
696   uint64_t time_compress_data;
697   uint64_t time_pick_lpf;
698   uint64_t time_encode_sb_row;
699
700 #if CONFIG_FP_MB_STATS
701   int use_fp_mb_stats;
702 #endif
703
704   TWO_PASS twopass;
705
706   // Force recalculation of segment_ids for each mode info
707   uint8_t force_update_segmentation;
708
709   YV12_BUFFER_CONFIG alt_ref_buffer;
710
711   // class responsible for adaptive
712   // quantization of altref frames
713   struct ALT_REF_AQ *alt_ref_aq;
714
715 #if CONFIG_INTERNAL_STATS
716   unsigned int mode_chosen_counts[MAX_MODES];
717
718   int count;
719   uint64_t total_sq_error;
720   uint64_t total_samples;
721   ImageStat psnr;
722
723   uint64_t totalp_sq_error;
724   uint64_t totalp_samples;
725   ImageStat psnrp;
726
727   double total_blockiness;
728   double worst_blockiness;
729
730   int bytes;
731   double summed_quality;
732   double summed_weights;
733   double summedp_quality;
734   double summedp_weights;
735   unsigned int tot_recode_hits;
736   double worst_ssim;
737
738   ImageStat ssimg;
739   ImageStat fastssim;
740   ImageStat psnrhvs;
741
742   int b_calculate_ssimg;
743   int b_calculate_blockiness;
744
745   int b_calculate_consistency;
746
747   double total_inconsistency;
748   double worst_consistency;
749   Ssimv *ssim_vars;
750   Metrics metrics;
751 #endif
752   int b_calculate_psnr;
753
754   int droppable;
755
756   int initial_width;
757   int initial_height;
758   int initial_mbs;  // Number of MBs in the full-size frame; to be used to
759                     // normalize the firstpass stats. This will differ from the
760                     // number of MBs in the current frame when the frame is
761                     // scaled.
762
763   int use_svc;
764
765   SVC svc;
766
767   // Store frame variance info in SOURCE_VAR_BASED_PARTITION search type.
768   diff *source_diff_var;
769   // The threshold used in SOURCE_VAR_BASED_PARTITION search type.
770   unsigned int source_var_thresh;
771   int frames_till_next_var_check;
772
773   int frame_flags;
774
775   search_site_config ss_cfg;
776
777   int mbmode_cost[INTRA_MODES];
778   unsigned int inter_mode_cost[INTER_MODE_CONTEXTS][INTER_MODES];
779   int intra_uv_mode_cost[FRAME_TYPES][INTRA_MODES][INTRA_MODES];
780   int y_mode_costs[INTRA_MODES][INTRA_MODES][INTRA_MODES];
781   int switchable_interp_costs[SWITCHABLE_FILTER_CONTEXTS][SWITCHABLE_FILTERS];
782   int partition_cost[PARTITION_CONTEXTS][PARTITION_TYPES];
783   // Indices are:  max_tx_size-1,  tx_size_ctx,    tx_size
784   int tx_size_cost[TX_SIZES - 1][TX_SIZE_CONTEXTS][TX_SIZES];
785
786 #if CONFIG_VP9_TEMPORAL_DENOISING
787   VP9_DENOISER denoiser;
788 #endif
789
790   int resize_pending;
791   RESIZE_STATE resize_state;
792   int external_resize;
793   int resize_scale_num;
794   int resize_scale_den;
795   int resize_avg_qp;
796   int resize_buffer_underflow;
797   int resize_count;
798
799   int use_skin_detection;
800
801   int target_level;
802
803   NOISE_ESTIMATE noise_estimate;
804
805   // Count on how many consecutive times a block uses small/zeromv for encoding.
806   uint8_t *consec_zero_mv;
807
808   // VAR_BASED_PARTITION thresholds
809   // 0 - threshold_64x64; 1 - threshold_32x32;
810   // 2 - threshold_16x16; 3 - vbp_threshold_8x8;
811   int64_t vbp_thresholds[4];
812   int64_t vbp_threshold_minmax;
813   int64_t vbp_threshold_sad;
814   // Threshold used for partition copy
815   int64_t vbp_threshold_copy;
816   BLOCK_SIZE vbp_bsize_min;
817
818   // Multi-threading
819   int num_workers;
820   VPxWorker *workers;
821   struct EncWorkerData *tile_thr_data;
822   VP9LfSync lf_row_sync;
823   struct VP9BitstreamWorkerData *vp9_bitstream_worker_data;
824
825   int keep_level_stats;
826   Vp9LevelInfo level_info;
827   MultiThreadHandle multi_thread_ctxt;
828   void (*row_mt_sync_read_ptr)(VP9RowMTSync *const, int, int);
829   void (*row_mt_sync_write_ptr)(VP9RowMTSync *const, int, int, const int);
830   ARNRFilterData arnr_filter_data;
831
832   int row_mt;
833   unsigned int row_mt_bit_exact;
834
835   // Previous Partition Info
836   BLOCK_SIZE *prev_partition;
837   int8_t *prev_segment_id;
838   // Used to save the status of whether a block has a low variance in
839   // choose_partitioning. 0 for 64x64, 1~2 for 64x32, 3~4 for 32x64, 5~8 for
840   // 32x32, 9~24 for 16x16.
841   // This is for the last frame and is copied to the current frame
842   // when partition copy happens.
843   uint8_t *prev_variance_low;
844   uint8_t *copied_frame_cnt;
845   uint8_t max_copied_frame;
846   // If the last frame is dropped, we don't copy partition.
847   uint8_t last_frame_dropped;
848
849   // For each superblock: keeps track of the last time (in frame distance) the
850   // the superblock did not have low source sad.
851   uint8_t *content_state_sb_fd;
852
853   int compute_source_sad_onepass;
854
855   LevelConstraint level_constraint;
856
857   uint8_t *count_arf_frame_usage;
858   uint8_t *count_lastgolden_frame_usage;
859
860   int multi_layer_arf;
861   vpx_roi_map_t roi;
862 #if CONFIG_RATE_CTRL
863   ENCODE_COMMAND encode_command;
864   PARTITION_INFO *partition_info;
865 #endif
866 } VP9_COMP;
867
868 #if CONFIG_RATE_CTRL
869 // Allocates memory for the partition information.
870 // The unit size is each 4x4 block.
871 // Only called once in vp9_create_compressor().
872 static INLINE void partition_info_init(struct VP9_COMP *cpi) {
873   VP9_COMMON *const cm = &cpi->common;
874   const int unit_width = get_num_unit_4x4(cpi->frame_info.frame_width);
875   const int unit_height = get_num_unit_4x4(cpi->frame_info.frame_height);
876   CHECK_MEM_ERROR(cm, cpi->partition_info,
877                   (PARTITION_INFO *)vpx_calloc(unit_width * unit_height,
878                                                sizeof(PARTITION_INFO)));
879   memset(cpi->partition_info, 0,
880          unit_width * unit_height * sizeof(PARTITION_INFO));
881 }
882
883 // Frees memory of the partition information.
884 // Only called once in dealloc_compressor_data().
885 static INLINE void free_partition_info(struct VP9_COMP *cpi) {
886   vpx_free(cpi->partition_info);
887   cpi->partition_info = NULL;
888 }
889 #endif  // CONFIG_RATE_CTRL
890
891 typedef struct ENCODE_FRAME_RESULT {
892   int show_idx;
893   FRAME_UPDATE_TYPE update_type;
894 #if CONFIG_RATE_CTRL
895   double psnr;
896   uint64_t sse;
897   FRAME_COUNTS frame_counts;
898 #endif  // CONFIG_RATE_CTRL
899   int quantize_index;
900 } ENCODE_FRAME_RESULT;
901
902 void vp9_initialize_enc(void);
903
904 void vp9_update_compressor_with_img_fmt(VP9_COMP *cpi, vpx_img_fmt_t img_fmt);
905 struct VP9_COMP *vp9_create_compressor(const VP9EncoderConfig *oxcf,
906                                        BufferPool *const pool);
907 void vp9_remove_compressor(VP9_COMP *cpi);
908
909 void vp9_change_config(VP9_COMP *cpi, const VP9EncoderConfig *oxcf);
910
911 // receive a frames worth of data. caller can assume that a copy of this
912 // frame is made and not just a copy of the pointer..
913 int vp9_receive_raw_frame(VP9_COMP *cpi, vpx_enc_frame_flags_t frame_flags,
914                           YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
915                           int64_t end_time);
916
917 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
918                             size_t *size, uint8_t *dest, int64_t *time_stamp,
919                             int64_t *time_end, int flush,
920                             ENCODE_FRAME_RESULT *encode_frame_result);
921
922 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
923                               vp9_ppflags_t *flags);
924
925 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags);
926
927 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags);
928
929 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
930                            YV12_BUFFER_CONFIG *sd);
931
932 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
933                           YV12_BUFFER_CONFIG *sd);
934
935 int vp9_update_entropy(VP9_COMP *cpi, int update);
936
937 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
938                        int cols);
939
940 int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
941                        int cols);
942
943 int vp9_set_internal_size(VP9_COMP *cpi, VPX_SCALING horiz_mode,
944                           VPX_SCALING vert_mode);
945
946 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
947                          unsigned int height);
948
949 void vp9_set_svc(VP9_COMP *cpi, int use_svc);
950
951 static INLINE int stack_pop(int *stack, int stack_size) {
952   int idx;
953   const int r = stack[0];
954   for (idx = 1; idx < stack_size; ++idx) stack[idx - 1] = stack[idx];
955
956   return r;
957 }
958
959 static INLINE int stack_top(const int *stack) { return stack[0]; }
960
961 static INLINE void stack_push(int *stack, int new_item, int stack_size) {
962   int idx;
963   for (idx = stack_size; idx > 0; --idx) stack[idx] = stack[idx - 1];
964   stack[0] = new_item;
965 }
966
967 static INLINE void stack_init(int *stack, int length) {
968   int idx;
969   for (idx = 0; idx < length; ++idx) stack[idx] = -1;
970 }
971
972 int vp9_get_quantizer(const VP9_COMP *cpi);
973
974 static INLINE int frame_is_kf_gf_arf(const VP9_COMP *cpi) {
975   return frame_is_intra_only(&cpi->common) || cpi->refresh_alt_ref_frame ||
976          (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref);
977 }
978
979 static INLINE int get_ref_frame_map_idx(const VP9_COMP *cpi,
980                                         MV_REFERENCE_FRAME ref_frame) {
981   if (ref_frame == LAST_FRAME) {
982     return cpi->lst_fb_idx;
983   } else if (ref_frame == GOLDEN_FRAME) {
984     return cpi->gld_fb_idx;
985   } else {
986     return cpi->alt_fb_idx;
987   }
988 }
989
990 static INLINE int get_ref_frame_buf_idx(const VP9_COMP *const cpi,
991                                         int ref_frame) {
992   const VP9_COMMON *const cm = &cpi->common;
993   const int map_idx = get_ref_frame_map_idx(cpi, ref_frame);
994   return (map_idx != INVALID_IDX) ? cm->ref_frame_map[map_idx] : INVALID_IDX;
995 }
996
997 static INLINE RefCntBuffer *get_ref_cnt_buffer(VP9_COMMON *cm, int fb_idx) {
998   return fb_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[fb_idx] : NULL;
999 }
1000
1001 static INLINE YV12_BUFFER_CONFIG *get_ref_frame_buffer(
1002     const VP9_COMP *const cpi, MV_REFERENCE_FRAME ref_frame) {
1003   const VP9_COMMON *const cm = &cpi->common;
1004   const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
1005   return buf_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[buf_idx].buf
1006                                 : NULL;
1007 }
1008
1009 static INLINE int get_token_alloc(int mb_rows, int mb_cols) {
1010   // TODO(JBB): double check we can't exceed this token count if we have a
1011   // 32x32 transform crossing a boundary at a multiple of 16.
1012   // mb_rows, cols are in units of 16 pixels. We assume 3 planes all at full
1013   // resolution. We assume up to 1 token per pixel, and then allow
1014   // a head room of 4.
1015   return mb_rows * mb_cols * (16 * 16 * 3 + 4);
1016 }
1017
1018 // Get the allocated token size for a tile. It does the same calculation as in
1019 // the frame token allocation.
1020 static INLINE int allocated_tokens(TileInfo tile) {
1021   int tile_mb_rows = (tile.mi_row_end - tile.mi_row_start + 1) >> 1;
1022   int tile_mb_cols = (tile.mi_col_end - tile.mi_col_start + 1) >> 1;
1023
1024   return get_token_alloc(tile_mb_rows, tile_mb_cols);
1025 }
1026
1027 static INLINE void get_start_tok(VP9_COMP *cpi, int tile_row, int tile_col,
1028                                  int mi_row, TOKENEXTRA **tok) {
1029   VP9_COMMON *const cm = &cpi->common;
1030   const int tile_cols = 1 << cm->log2_tile_cols;
1031   TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
1032   const TileInfo *const tile_info = &this_tile->tile_info;
1033
1034   int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
1035   const int mb_row = (mi_row - tile_info->mi_row_start) >> 1;
1036
1037   *tok =
1038       cpi->tile_tok[tile_row][tile_col] + get_token_alloc(mb_row, tile_mb_cols);
1039 }
1040
1041 int64_t vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b);
1042 #if CONFIG_VP9_HIGHBITDEPTH
1043 int64_t vp9_highbd_get_y_sse(const YV12_BUFFER_CONFIG *a,
1044                              const YV12_BUFFER_CONFIG *b);
1045 #endif  // CONFIG_VP9_HIGHBITDEPTH
1046
1047 void vp9_scale_references(VP9_COMP *cpi);
1048
1049 void vp9_update_reference_frames(VP9_COMP *cpi);
1050
1051 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv);
1052
1053 YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(
1054     VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
1055     YV12_BUFFER_CONFIG *scaled_temp, INTERP_FILTER filter_type,
1056     int phase_scaler, INTERP_FILTER filter_type2, int phase_scaler2);
1057
1058 YV12_BUFFER_CONFIG *vp9_scale_if_required(
1059     VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
1060     int use_normative_scaler, INTERP_FILTER filter_type, int phase_scaler);
1061
1062 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags);
1063
1064 static INLINE int is_one_pass_cbr_svc(const struct VP9_COMP *const cpi) {
1065   return (cpi->use_svc && cpi->oxcf.pass == 0);
1066 }
1067
1068 #if CONFIG_VP9_TEMPORAL_DENOISING
1069 static INLINE int denoise_svc(const struct VP9_COMP *const cpi) {
1070   return (!cpi->use_svc || (cpi->use_svc && cpi->svc.spatial_layer_id >=
1071                                                 cpi->svc.first_layer_denoise));
1072 }
1073 #endif
1074
1075 #define MIN_LOOKAHEAD_FOR_ARFS 4
1076 static INLINE int is_altref_enabled(const VP9_COMP *const cpi) {
1077   return !(cpi->oxcf.mode == REALTIME && cpi->oxcf.rc_mode == VPX_CBR) &&
1078          cpi->oxcf.lag_in_frames >= MIN_LOOKAHEAD_FOR_ARFS &&
1079          cpi->oxcf.enable_auto_arf;
1080 }
1081
1082 static INLINE void set_ref_ptrs(const VP9_COMMON *const cm, MACROBLOCKD *xd,
1083                                 MV_REFERENCE_FRAME ref0,
1084                                 MV_REFERENCE_FRAME ref1) {
1085   xd->block_refs[0] =
1086       &cm->frame_refs[ref0 >= LAST_FRAME ? ref0 - LAST_FRAME : 0];
1087   xd->block_refs[1] =
1088       &cm->frame_refs[ref1 >= LAST_FRAME ? ref1 - LAST_FRAME : 0];
1089 }
1090
1091 static INLINE int get_chessboard_index(const int frame_index) {
1092   return frame_index & 0x1;
1093 }
1094
1095 static INLINE int *cond_cost_list(const struct VP9_COMP *cpi, int *cost_list) {
1096   return cpi->sf.mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL;
1097 }
1098
1099 static INLINE int get_num_vert_units(TileInfo tile, int shift) {
1100   int num_vert_units =
1101       (tile.mi_row_end - tile.mi_row_start + (1 << shift) - 1) >> shift;
1102   return num_vert_units;
1103 }
1104
1105 static INLINE int get_num_cols(TileInfo tile, int shift) {
1106   int num_cols =
1107       (tile.mi_col_end - tile.mi_col_start + (1 << shift) - 1) >> shift;
1108   return num_cols;
1109 }
1110
1111 static INLINE int get_level_index(VP9_LEVEL level) {
1112   int i;
1113   for (i = 0; i < VP9_LEVELS; ++i) {
1114     if (level == vp9_level_defs[i].level) return i;
1115   }
1116   return -1;
1117 }
1118
1119 // Return the log2 value of max column tiles corresponding to the level that
1120 // the picture size fits into.
1121 static INLINE int log_tile_cols_from_picsize_level(uint32_t width,
1122                                                    uint32_t height) {
1123   int i;
1124   const uint32_t pic_size = width * height;
1125   const uint32_t pic_breadth = VPXMAX(width, height);
1126   for (i = LEVEL_1; i < LEVEL_MAX; ++i) {
1127     if (vp9_level_defs[i].max_luma_picture_size >= pic_size &&
1128         vp9_level_defs[i].max_luma_picture_breadth >= pic_breadth) {
1129       return get_msb(vp9_level_defs[i].max_col_tiles);
1130     }
1131   }
1132   return INT_MAX;
1133 }
1134
1135 VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec);
1136
1137 int vp9_set_roi_map(VP9_COMP *cpi, unsigned char *map, unsigned int rows,
1138                     unsigned int cols, int delta_q[8], int delta_lf[8],
1139                     int skip[8], int ref_frame[8]);
1140
1141 void vp9_new_framerate(VP9_COMP *cpi, double framerate);
1142
1143 void vp9_set_row_mt(VP9_COMP *cpi);
1144
1145 int vp9_get_psnr(const VP9_COMP *cpi, PSNR_STATS *psnr);
1146
1147 #define LAYER_IDS_TO_IDX(sl, tl, num_tl) ((sl) * (num_tl) + (tl))
1148
1149 #ifdef __cplusplus
1150 }  // extern "C"
1151 #endif
1152
1153 #endif  // VPX_VP9_ENCODER_VP9_ENCODER_H_