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 } VP9EncoderConfig;
286 
is_lossless_requested(const VP9EncoderConfig * cfg)287 static INLINE int is_lossless_requested(const VP9EncoderConfig *cfg) {
288   return cfg->best_allowed_q == 0 && cfg->worst_allowed_q == 0;
289 }
290 
291 typedef struct TplDepStats {
292   int64_t intra_cost;
293   int64_t inter_cost;
294   int64_t mc_flow;
295   int64_t mc_dep_cost;
296   int64_t mc_ref_cost;
297 
298   int ref_frame_index;
299   int_mv mv;
300 } TplDepStats;
301 
302 #if CONFIG_NON_GREEDY_MV
303 
304 #define ZERO_MV_MODE 0
305 #define NEW_MV_MODE 1
306 #define NEAREST_MV_MODE 2
307 #define NEAR_MV_MODE 3
308 #define MAX_MV_MODE 4
309 #endif
310 
311 typedef struct TplDepFrame {
312   uint8_t is_valid;
313   TplDepStats *tpl_stats_ptr;
314   int stride;
315   int width;
316   int height;
317   int mi_rows;
318   int mi_cols;
319   int base_qindex;
320 #if CONFIG_NON_GREEDY_MV
321   int lambda;
322   int *mv_mode_arr[3];
323   double *rd_diff_arr[3];
324 #endif
325 } TplDepFrame;
326 
327 #define TPL_DEP_COST_SCALE_LOG2 4
328 
329 // TODO(jingning) All spatially adaptive variables should go to TileDataEnc.
330 typedef struct TileDataEnc {
331   TileInfo tile_info;
332   int thresh_freq_fact[BLOCK_SIZES][MAX_MODES];
333 #if CONFIG_CONSISTENT_RECODE
334   int thresh_freq_fact_prev[BLOCK_SIZES][MAX_MODES];
335 #endif
336   int8_t mode_map[BLOCK_SIZES][MAX_MODES];
337   FIRSTPASS_DATA fp_data;
338   VP9RowMTSync row_mt_sync;
339 
340   // Used for adaptive_rd_thresh with row multithreading
341   int *row_base_thresh_freq_fact;
342 } TileDataEnc;
343 
344 typedef struct RowMTInfo {
345   JobQueueHandle job_queue_hdl;
346 #if CONFIG_MULTITHREAD
347   pthread_mutex_t job_mutex;
348 #endif
349 } RowMTInfo;
350 
351 typedef struct {
352   TOKENEXTRA *start;
353   TOKENEXTRA *stop;
354   unsigned int count;
355 } TOKENLIST;
356 
357 typedef struct MultiThreadHandle {
358   int allocated_tile_rows;
359   int allocated_tile_cols;
360   int allocated_vert_unit_rows;
361 
362   // Frame level params
363   int num_tile_vert_sbs[MAX_NUM_TILE_ROWS];
364 
365   // Job Queue structure and handles
366   JobQueue *job_queue;
367 
368   int jobs_per_tile_col;
369 
370   RowMTInfo row_mt_info[MAX_NUM_TILE_COLS];
371   int thread_id_to_tile_id[MAX_NUM_THREADS];  // Mapping of threads to tiles
372 } MultiThreadHandle;
373 
374 typedef struct RD_COUNTS {
375   vp9_coeff_count coef_counts[TX_SIZES][PLANE_TYPES];
376   int64_t comp_pred_diff[REFERENCE_MODES];
377   int64_t filter_diff[SWITCHABLE_FILTER_CONTEXTS];
378 } RD_COUNTS;
379 
380 typedef struct ThreadData {
381   MACROBLOCK mb;
382   RD_COUNTS rd_counts;
383   FRAME_COUNTS *counts;
384 
385   PICK_MODE_CONTEXT *leaf_tree;
386   PC_TREE *pc_tree;
387   PC_TREE *pc_root;
388 } ThreadData;
389 
390 struct EncWorkerData;
391 
392 typedef struct ActiveMap {
393   int enabled;
394   int update;
395   unsigned char *map;
396 } ActiveMap;
397 
398 typedef enum { Y, U, V, ALL } STAT_TYPE;
399 
400 typedef struct IMAGE_STAT {
401   double stat[ALL + 1];
402   double worst;
403 } ImageStat;
404 
405 // Kf noise filtering currently disabled by default in build.
406 // #define ENABLE_KF_DENOISE 1
407 
408 #define CPB_WINDOW_SIZE 4
409 #define FRAME_WINDOW_SIZE 128
410 #define SAMPLE_RATE_GRACE_P 0.015
411 #define VP9_LEVELS 14
412 
413 typedef enum {
414   LEVEL_UNKNOWN = 0,
415   LEVEL_AUTO = 1,
416   LEVEL_1 = 10,
417   LEVEL_1_1 = 11,
418   LEVEL_2 = 20,
419   LEVEL_2_1 = 21,
420   LEVEL_3 = 30,
421   LEVEL_3_1 = 31,
422   LEVEL_4 = 40,
423   LEVEL_4_1 = 41,
424   LEVEL_5 = 50,
425   LEVEL_5_1 = 51,
426   LEVEL_5_2 = 52,
427   LEVEL_6 = 60,
428   LEVEL_6_1 = 61,
429   LEVEL_6_2 = 62,
430   LEVEL_MAX = 255
431 } VP9_LEVEL;
432 
433 typedef struct {
434   VP9_LEVEL level;
435   uint64_t max_luma_sample_rate;
436   uint32_t max_luma_picture_size;
437   uint32_t max_luma_picture_breadth;
438   double average_bitrate;  // in kilobits per second
439   double max_cpb_size;     // in kilobits
440   double compression_ratio;
441   uint8_t max_col_tiles;
442   uint32_t min_altref_distance;
443   uint8_t max_ref_frame_buffers;
444 } Vp9LevelSpec;
445 
446 extern const Vp9LevelSpec vp9_level_defs[VP9_LEVELS];
447 
448 typedef struct {
449   int64_t ts;  // timestamp
450   uint32_t luma_samples;
451   uint32_t size;  // in bytes
452 } FrameRecord;
453 
454 typedef struct {
455   FrameRecord buf[FRAME_WINDOW_SIZE];
456   uint8_t start;
457   uint8_t len;
458 } FrameWindowBuffer;
459 
460 typedef struct {
461   uint8_t seen_first_altref;
462   uint32_t frames_since_last_altref;
463   uint64_t total_compressed_size;
464   uint64_t total_uncompressed_size;
465   double time_encoded;  // in seconds
466   FrameWindowBuffer frame_window_buffer;
467   int ref_refresh_map;
468 } Vp9LevelStats;
469 
470 typedef struct {
471   Vp9LevelStats level_stats;
472   Vp9LevelSpec level_spec;
473 } Vp9LevelInfo;
474 
475 typedef enum {
476   BITRATE_TOO_LARGE = 0,
477   LUMA_PIC_SIZE_TOO_LARGE,
478   LUMA_PIC_BREADTH_TOO_LARGE,
479   LUMA_SAMPLE_RATE_TOO_LARGE,
480   CPB_TOO_LARGE,
481   COMPRESSION_RATIO_TOO_SMALL,
482   TOO_MANY_COLUMN_TILE,
483   ALTREF_DIST_TOO_SMALL,
484   TOO_MANY_REF_BUFFER,
485   TARGET_LEVEL_FAIL_IDS
486 } TARGET_LEVEL_FAIL_ID;
487 
488 typedef struct {
489   int8_t level_index;
490   uint8_t fail_flag;
491   int max_frame_size;   // in bits
492   double max_cpb_size;  // in bits
493 } LevelConstraint;
494 
495 typedef struct ARNRFilterData {
496   YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS];
497   int strength;
498   int frame_count;
499   int alt_ref_index;
500   struct scale_factors sf;
501 } ARNRFilterData;
502 
503 typedef struct EncFrameBuf {
504   int mem_valid;
505   int released;
506   YV12_BUFFER_CONFIG frame;
507 } EncFrameBuf;
508 
509 // Maximum operating frame buffer size needed for a GOP using ARF reference.
510 #define MAX_ARF_GOP_SIZE (2 * MAX_LAG_BUFFERS)
511 #define MAX_KMEANS_GROUPS 8
512 
513 typedef struct KMEANS_DATA {
514   double value;
515   int pos;
516   int group_idx;
517 } KMEANS_DATA;
518 
519 #if CONFIG_RATE_CTRL
520 typedef struct ENCODE_COMMAND {
521   int use_external_quantize_index;
522   int external_quantize_index;
523 } ENCODE_COMMAND;
524 
encode_command_init(ENCODE_COMMAND * encode_command)525 static INLINE void encode_command_init(ENCODE_COMMAND *encode_command) {
526   vp9_zero(*encode_command);
527   encode_command->use_external_quantize_index = 0;
528   encode_command->external_quantize_index = -1;
529 }
530 
encode_command_set_external_quantize_index(ENCODE_COMMAND * encode_command,int quantize_index)531 static INLINE void encode_command_set_external_quantize_index(
532     ENCODE_COMMAND *encode_command, int quantize_index) {
533   encode_command->use_external_quantize_index = 1;
534   encode_command->external_quantize_index = quantize_index;
535 }
536 
encode_command_reset_external_quantize_index(ENCODE_COMMAND * encode_command)537 static INLINE void encode_command_reset_external_quantize_index(
538     ENCODE_COMMAND *encode_command) {
539   encode_command->use_external_quantize_index = 0;
540   encode_command->external_quantize_index = -1;
541 }
542 #endif  // CONFIG_RATE_CTRL
543 
544 typedef struct VP9_COMP {
545   FRAME_INFO frame_info;
546   QUANTS quants;
547   ThreadData td;
548   MB_MODE_INFO_EXT *mbmi_ext_base;
549   DECLARE_ALIGNED(16, int16_t, y_dequant[QINDEX_RANGE][8]);
550   DECLARE_ALIGNED(16, int16_t, uv_dequant[QINDEX_RANGE][8]);
551   VP9_COMMON common;
552   VP9EncoderConfig oxcf;
553   struct lookahead_ctx *lookahead;
554   struct lookahead_entry *alt_ref_source;
555 
556   YV12_BUFFER_CONFIG *Source;
557   YV12_BUFFER_CONFIG *Last_Source;  // NULL for first frame and alt_ref frames
558   YV12_BUFFER_CONFIG *un_scaled_source;
559   YV12_BUFFER_CONFIG scaled_source;
560   YV12_BUFFER_CONFIG *unscaled_last_source;
561   YV12_BUFFER_CONFIG scaled_last_source;
562 #ifdef ENABLE_KF_DENOISE
563   YV12_BUFFER_CONFIG raw_unscaled_source;
564   YV12_BUFFER_CONFIG raw_scaled_source;
565 #endif
566   YV12_BUFFER_CONFIG *raw_source_frame;
567 
568   BLOCK_SIZE tpl_bsize;
569   TplDepFrame tpl_stats[MAX_ARF_GOP_SIZE];
570   YV12_BUFFER_CONFIG *tpl_recon_frames[REF_FRAMES];
571   EncFrameBuf enc_frame_buf[REF_FRAMES];
572 #if CONFIG_MULTITHREAD
573   pthread_mutex_t kmeans_mutex;
574 #endif
575   int kmeans_data_arr_alloc;
576   KMEANS_DATA *kmeans_data_arr;
577   int kmeans_data_size;
578   int kmeans_data_stride;
579   double kmeans_ctr_ls[MAX_KMEANS_GROUPS];
580   double kmeans_boundary_ls[MAX_KMEANS_GROUPS];
581   int kmeans_count_ls[MAX_KMEANS_GROUPS];
582   int kmeans_ctr_num;
583 #if CONFIG_NON_GREEDY_MV
584   MotionFieldInfo motion_field_info;
585   int tpl_ready;
586   int_mv *select_mv_arr;
587 #endif
588 
589   TileDataEnc *tile_data;
590   int allocated_tiles;  // Keep track of memory allocated for tiles.
591 
592   // For a still frame, this flag is set to 1 to skip partition search.
593   int partition_search_skippable_frame;
594 
595   int scaled_ref_idx[REFS_PER_FRAME];
596   int lst_fb_idx;
597   int gld_fb_idx;
598   int alt_fb_idx;
599 
600   int ref_fb_idx[REF_FRAMES];
601 
602   int refresh_last_frame;
603   int refresh_golden_frame;
604   int refresh_alt_ref_frame;
605 
606   int ext_refresh_frame_flags_pending;
607   int ext_refresh_last_frame;
608   int ext_refresh_golden_frame;
609   int ext_refresh_alt_ref_frame;
610 
611   int ext_refresh_frame_context_pending;
612   int ext_refresh_frame_context;
613 
614   int64_t norm_wiener_variance;
615   int64_t *mb_wiener_variance;
616   int mb_wiener_var_rows;
617   int mb_wiener_var_cols;
618   double *mi_ssim_rdmult_scaling_factors;
619 
620   YV12_BUFFER_CONFIG last_frame_uf;
621 
622   TOKENEXTRA *tile_tok[4][1 << 6];
623   TOKENLIST *tplist[4][1 << 6];
624 
625   // Ambient reconstruction err target for force key frames
626   int64_t ambient_err;
627 
628   RD_OPT rd;
629 
630   CODING_CONTEXT coding_context;
631 
632   int *nmvcosts[2];
633   int *nmvcosts_hp[2];
634   int *nmvsadcosts[2];
635   int *nmvsadcosts_hp[2];
636 
637   int64_t last_time_stamp_seen;
638   int64_t last_end_time_stamp_seen;
639   int64_t first_time_stamp_ever;
640 
641   RATE_CONTROL rc;
642   double framerate;
643 
644   int interp_filter_selected[REF_FRAMES][SWITCHABLE];
645 
646   struct vpx_codec_pkt_list *output_pkt_list;
647 
648   MBGRAPH_FRAME_STATS mbgraph_stats[MAX_LAG_BUFFERS];
649   int mbgraph_n_frames;  // number of frames filled in the above
650   int static_mb_pct;     // % forced skip mbs by segmentation
651   int ref_frame_flags;
652 
653   SPEED_FEATURES sf;
654 
655   uint32_t max_mv_magnitude;
656   int mv_step_param;
657 
658   int allow_comp_inter_inter;
659 
660   // Default value is 1. From first pass stats, encode_breakout may be disabled.
661   ENCODE_BREAKOUT_TYPE allow_encode_breakout;
662 
663   // Get threshold from external input. A suggested threshold is 800 for HD
664   // clips, and 300 for < HD clips.
665   int encode_breakout;
666 
667   uint8_t *segmentation_map;
668 
669   uint8_t *skin_map;
670 
671   // segment threashold for encode breakout
672   int segment_encode_breakout[MAX_SEGMENTS];
673 
674   CYCLIC_REFRESH *cyclic_refresh;
675   ActiveMap active_map;
676 
677   fractional_mv_step_fp *find_fractional_mv_step;
678   struct scale_factors me_sf;
679   vp9_diamond_search_fn_t diamond_search_sad;
680   vp9_variance_fn_ptr_t fn_ptr[BLOCK_SIZES];
681   uint64_t time_receive_data;
682   uint64_t time_compress_data;
683   uint64_t time_pick_lpf;
684   uint64_t time_encode_sb_row;
685 
686 #if CONFIG_FP_MB_STATS
687   int use_fp_mb_stats;
688 #endif
689 
690   TWO_PASS twopass;
691 
692   // Force recalculation of segment_ids for each mode info
693   uint8_t force_update_segmentation;
694 
695   YV12_BUFFER_CONFIG alt_ref_buffer;
696 
697   // class responsible for adaptive
698   // quantization of altref frames
699   struct ALT_REF_AQ *alt_ref_aq;
700 
701 #if CONFIG_INTERNAL_STATS
702   unsigned int mode_chosen_counts[MAX_MODES];
703 
704   int count;
705   uint64_t total_sq_error;
706   uint64_t total_samples;
707   ImageStat psnr;
708 
709   uint64_t totalp_sq_error;
710   uint64_t totalp_samples;
711   ImageStat psnrp;
712 
713   double total_blockiness;
714   double worst_blockiness;
715 
716   int bytes;
717   double summed_quality;
718   double summed_weights;
719   double summedp_quality;
720   double summedp_weights;
721   unsigned int tot_recode_hits;
722   double worst_ssim;
723 
724   ImageStat ssimg;
725   ImageStat fastssim;
726   ImageStat psnrhvs;
727 
728   int b_calculate_ssimg;
729   int b_calculate_blockiness;
730 
731   int b_calculate_consistency;
732 
733   double total_inconsistency;
734   double worst_consistency;
735   Ssimv *ssim_vars;
736   Metrics metrics;
737 #endif
738   int b_calculate_psnr;
739 
740   int droppable;
741 
742   int initial_width;
743   int initial_height;
744   int initial_mbs;  // Number of MBs in the full-size frame; to be used to
745                     // normalize the firstpass stats. This will differ from the
746                     // number of MBs in the current frame when the frame is
747                     // scaled.
748 
749   int use_svc;
750 
751   SVC svc;
752 
753   // Store frame variance info in SOURCE_VAR_BASED_PARTITION search type.
754   diff *source_diff_var;
755   // The threshold used in SOURCE_VAR_BASED_PARTITION search type.
756   unsigned int source_var_thresh;
757   int frames_till_next_var_check;
758 
759   int frame_flags;
760 
761   search_site_config ss_cfg;
762 
763   int mbmode_cost[INTRA_MODES];
764   unsigned int inter_mode_cost[INTER_MODE_CONTEXTS][INTER_MODES];
765   int intra_uv_mode_cost[FRAME_TYPES][INTRA_MODES][INTRA_MODES];
766   int y_mode_costs[INTRA_MODES][INTRA_MODES][INTRA_MODES];
767   int switchable_interp_costs[SWITCHABLE_FILTER_CONTEXTS][SWITCHABLE_FILTERS];
768   int partition_cost[PARTITION_CONTEXTS][PARTITION_TYPES];
769   // Indices are:  max_tx_size-1,  tx_size_ctx,    tx_size
770   int tx_size_cost[TX_SIZES - 1][TX_SIZE_CONTEXTS][TX_SIZES];
771 
772 #if CONFIG_VP9_TEMPORAL_DENOISING
773   VP9_DENOISER denoiser;
774 #endif
775 
776   int resize_pending;
777   RESIZE_STATE resize_state;
778   int external_resize;
779   int resize_scale_num;
780   int resize_scale_den;
781   int resize_avg_qp;
782   int resize_buffer_underflow;
783   int resize_count;
784 
785   int use_skin_detection;
786 
787   int target_level;
788 
789   NOISE_ESTIMATE noise_estimate;
790 
791   // Count on how many consecutive times a block uses small/zeromv for encoding.
792   uint8_t *consec_zero_mv;
793 
794   // VAR_BASED_PARTITION thresholds
795   // 0 - threshold_64x64; 1 - threshold_32x32;
796   // 2 - threshold_16x16; 3 - vbp_threshold_8x8;
797   int64_t vbp_thresholds[4];
798   int64_t vbp_threshold_minmax;
799   int64_t vbp_threshold_sad;
800   // Threshold used for partition copy
801   int64_t vbp_threshold_copy;
802   BLOCK_SIZE vbp_bsize_min;
803 
804   // Multi-threading
805   int num_workers;
806   VPxWorker *workers;
807   struct EncWorkerData *tile_thr_data;
808   VP9LfSync lf_row_sync;
809   struct VP9BitstreamWorkerData *vp9_bitstream_worker_data;
810 
811   int keep_level_stats;
812   Vp9LevelInfo level_info;
813   MultiThreadHandle multi_thread_ctxt;
814   void (*row_mt_sync_read_ptr)(VP9RowMTSync *const, int, int);
815   void (*row_mt_sync_write_ptr)(VP9RowMTSync *const, int, int, const int);
816   ARNRFilterData arnr_filter_data;
817 
818   int row_mt;
819   unsigned int row_mt_bit_exact;
820 
821   // Previous Partition Info
822   BLOCK_SIZE *prev_partition;
823   int8_t *prev_segment_id;
824   // Used to save the status of whether a block has a low variance in
825   // choose_partitioning. 0 for 64x64, 1~2 for 64x32, 3~4 for 32x64, 5~8 for
826   // 32x32, 9~24 for 16x16.
827   // This is for the last frame and is copied to the current frame
828   // when partition copy happens.
829   uint8_t *prev_variance_low;
830   uint8_t *copied_frame_cnt;
831   uint8_t max_copied_frame;
832   // If the last frame is dropped, we don't copy partition.
833   uint8_t last_frame_dropped;
834 
835   // For each superblock: keeps track of the last time (in frame distance) the
836   // the superblock did not have low source sad.
837   uint8_t *content_state_sb_fd;
838 
839   int compute_source_sad_onepass;
840 
841   LevelConstraint level_constraint;
842 
843   uint8_t *count_arf_frame_usage;
844   uint8_t *count_lastgolden_frame_usage;
845 
846   int multi_layer_arf;
847   vpx_roi_map_t roi;
848 #if CONFIG_RATE_CTRL
849   ENCODE_COMMAND encode_command;
850 #endif
851 } VP9_COMP;
852 
853 typedef struct ENCODE_FRAME_RESULT {
854   int show_idx;
855   FRAME_UPDATE_TYPE update_type;
856   double psnr;
857   uint64_t sse;
858   int quantize_index;
859 } ENCODE_FRAME_RESULT;
860 
861 void vp9_initialize_enc(void);
862 
863 void vp9_update_compressor_with_img_fmt(VP9_COMP *cpi, vpx_img_fmt_t img_fmt);
864 struct VP9_COMP *vp9_create_compressor(const VP9EncoderConfig *oxcf,
865                                        BufferPool *const pool);
866 void vp9_remove_compressor(VP9_COMP *cpi);
867 
868 void vp9_change_config(VP9_COMP *cpi, const VP9EncoderConfig *oxcf);
869 
870 // receive a frames worth of data. caller can assume that a copy of this
871 // frame is made and not just a copy of the pointer..
872 int vp9_receive_raw_frame(VP9_COMP *cpi, vpx_enc_frame_flags_t frame_flags,
873                           YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
874                           int64_t end_time);
875 
876 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
877                             size_t *size, uint8_t *dest, int64_t *time_stamp,
878                             int64_t *time_end, int flush,
879                             ENCODE_FRAME_RESULT *encode_frame_result);
880 
881 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
882                               vp9_ppflags_t *flags);
883 
884 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags);
885 
886 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags);
887 
888 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
889                            YV12_BUFFER_CONFIG *sd);
890 
891 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
892                           YV12_BUFFER_CONFIG *sd);
893 
894 int vp9_update_entropy(VP9_COMP *cpi, int update);
895 
896 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
897                        int cols);
898 
899 int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
900                        int cols);
901 
902 int vp9_set_internal_size(VP9_COMP *cpi, VPX_SCALING horiz_mode,
903                           VPX_SCALING vert_mode);
904 
905 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
906                          unsigned int height);
907 
908 void vp9_set_svc(VP9_COMP *cpi, int use_svc);
909 
stack_pop(int * stack,int stack_size)910 static INLINE int stack_pop(int *stack, int stack_size) {
911   int idx;
912   const int r = stack[0];
913   for (idx = 1; idx < stack_size; ++idx) stack[idx - 1] = stack[idx];
914 
915   return r;
916 }
917 
stack_top(const int * stack)918 static INLINE int stack_top(const int *stack) { return stack[0]; }
919 
stack_push(int * stack,int new_item,int stack_size)920 static INLINE void stack_push(int *stack, int new_item, int stack_size) {
921   int idx;
922   for (idx = stack_size; idx > 0; --idx) stack[idx] = stack[idx - 1];
923   stack[0] = new_item;
924 }
925 
stack_init(int * stack,int length)926 static INLINE void stack_init(int *stack, int length) {
927   int idx;
928   for (idx = 0; idx < length; ++idx) stack[idx] = -1;
929 }
930 
931 int vp9_get_quantizer(const VP9_COMP *cpi);
932 
frame_is_kf_gf_arf(const VP9_COMP * cpi)933 static INLINE int frame_is_kf_gf_arf(const VP9_COMP *cpi) {
934   return frame_is_intra_only(&cpi->common) || cpi->refresh_alt_ref_frame ||
935          (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref);
936 }
937 
get_ref_frame_map_idx(const VP9_COMP * cpi,MV_REFERENCE_FRAME ref_frame)938 static INLINE int get_ref_frame_map_idx(const VP9_COMP *cpi,
939                                         MV_REFERENCE_FRAME ref_frame) {
940   if (ref_frame == LAST_FRAME) {
941     return cpi->lst_fb_idx;
942   } else if (ref_frame == GOLDEN_FRAME) {
943     return cpi->gld_fb_idx;
944   } else {
945     return cpi->alt_fb_idx;
946   }
947 }
948 
get_ref_frame_buf_idx(const VP9_COMP * const cpi,int ref_frame)949 static INLINE int get_ref_frame_buf_idx(const VP9_COMP *const cpi,
950                                         int ref_frame) {
951   const VP9_COMMON *const cm = &cpi->common;
952   const int map_idx = get_ref_frame_map_idx(cpi, ref_frame);
953   return (map_idx != INVALID_IDX) ? cm->ref_frame_map[map_idx] : INVALID_IDX;
954 }
955 
get_ref_cnt_buffer(VP9_COMMON * cm,int fb_idx)956 static INLINE RefCntBuffer *get_ref_cnt_buffer(VP9_COMMON *cm, int fb_idx) {
957   return fb_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[fb_idx] : NULL;
958 }
959 
get_ref_frame_buffer(const VP9_COMP * const cpi,MV_REFERENCE_FRAME ref_frame)960 static INLINE YV12_BUFFER_CONFIG *get_ref_frame_buffer(
961     const VP9_COMP *const cpi, MV_REFERENCE_FRAME ref_frame) {
962   const VP9_COMMON *const cm = &cpi->common;
963   const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
964   return buf_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[buf_idx].buf
965                                 : NULL;
966 }
967 
get_token_alloc(int mb_rows,int mb_cols)968 static INLINE int get_token_alloc(int mb_rows, int mb_cols) {
969   // TODO(JBB): double check we can't exceed this token count if we have a
970   // 32x32 transform crossing a boundary at a multiple of 16.
971   // mb_rows, cols are in units of 16 pixels. We assume 3 planes all at full
972   // resolution. We assume up to 1 token per pixel, and then allow
973   // a head room of 4.
974   return mb_rows * mb_cols * (16 * 16 * 3 + 4);
975 }
976 
977 // Get the allocated token size for a tile. It does the same calculation as in
978 // the frame token allocation.
allocated_tokens(TileInfo tile)979 static INLINE int allocated_tokens(TileInfo tile) {
980   int tile_mb_rows = (tile.mi_row_end - tile.mi_row_start + 1) >> 1;
981   int tile_mb_cols = (tile.mi_col_end - tile.mi_col_start + 1) >> 1;
982 
983   return get_token_alloc(tile_mb_rows, tile_mb_cols);
984 }
985 
get_start_tok(VP9_COMP * cpi,int tile_row,int tile_col,int mi_row,TOKENEXTRA ** tok)986 static INLINE void get_start_tok(VP9_COMP *cpi, int tile_row, int tile_col,
987                                  int mi_row, TOKENEXTRA **tok) {
988   VP9_COMMON *const cm = &cpi->common;
989   const int tile_cols = 1 << cm->log2_tile_cols;
990   TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
991   const TileInfo *const tile_info = &this_tile->tile_info;
992 
993   int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
994   const int mb_row = (mi_row - tile_info->mi_row_start) >> 1;
995 
996   *tok =
997       cpi->tile_tok[tile_row][tile_col] + get_token_alloc(mb_row, tile_mb_cols);
998 }
999 
1000 int64_t vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b);
1001 #if CONFIG_VP9_HIGHBITDEPTH
1002 int64_t vp9_highbd_get_y_sse(const YV12_BUFFER_CONFIG *a,
1003                              const YV12_BUFFER_CONFIG *b);
1004 #endif  // CONFIG_VP9_HIGHBITDEPTH
1005 
1006 void vp9_scale_references(VP9_COMP *cpi);
1007 
1008 void vp9_update_reference_frames(VP9_COMP *cpi);
1009 
1010 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv);
1011 
1012 YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(
1013     VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
1014     YV12_BUFFER_CONFIG *scaled_temp, INTERP_FILTER filter_type,
1015     int phase_scaler, INTERP_FILTER filter_type2, int phase_scaler2);
1016 
1017 YV12_BUFFER_CONFIG *vp9_scale_if_required(
1018     VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
1019     int use_normative_scaler, INTERP_FILTER filter_type, int phase_scaler);
1020 
1021 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags);
1022 
is_one_pass_cbr_svc(const struct VP9_COMP * const cpi)1023 static INLINE int is_one_pass_cbr_svc(const struct VP9_COMP *const cpi) {
1024   return (cpi->use_svc && cpi->oxcf.pass == 0);
1025 }
1026 
1027 #if CONFIG_VP9_TEMPORAL_DENOISING
denoise_svc(const struct VP9_COMP * const cpi)1028 static INLINE int denoise_svc(const struct VP9_COMP *const cpi) {
1029   return (!cpi->use_svc || (cpi->use_svc && cpi->svc.spatial_layer_id >=
1030                                                 cpi->svc.first_layer_denoise));
1031 }
1032 #endif
1033 
1034 #define MIN_LOOKAHEAD_FOR_ARFS 4
is_altref_enabled(const VP9_COMP * const cpi)1035 static INLINE int is_altref_enabled(const VP9_COMP *const cpi) {
1036   return !(cpi->oxcf.mode == REALTIME && cpi->oxcf.rc_mode == VPX_CBR) &&
1037          cpi->oxcf.lag_in_frames >= MIN_LOOKAHEAD_FOR_ARFS &&
1038          cpi->oxcf.enable_auto_arf;
1039 }
1040 
set_ref_ptrs(const VP9_COMMON * const cm,MACROBLOCKD * xd,MV_REFERENCE_FRAME ref0,MV_REFERENCE_FRAME ref1)1041 static INLINE void set_ref_ptrs(const VP9_COMMON *const cm, MACROBLOCKD *xd,
1042                                 MV_REFERENCE_FRAME ref0,
1043                                 MV_REFERENCE_FRAME ref1) {
1044   xd->block_refs[0] =
1045       &cm->frame_refs[ref0 >= LAST_FRAME ? ref0 - LAST_FRAME : 0];
1046   xd->block_refs[1] =
1047       &cm->frame_refs[ref1 >= LAST_FRAME ? ref1 - LAST_FRAME : 0];
1048 }
1049 
get_chessboard_index(const int frame_index)1050 static INLINE int get_chessboard_index(const int frame_index) {
1051   return frame_index & 0x1;
1052 }
1053 
cond_cost_list(const struct VP9_COMP * cpi,int * cost_list)1054 static INLINE int *cond_cost_list(const struct VP9_COMP *cpi, int *cost_list) {
1055   return cpi->sf.mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL;
1056 }
1057 
get_num_vert_units(TileInfo tile,int shift)1058 static INLINE int get_num_vert_units(TileInfo tile, int shift) {
1059   int num_vert_units =
1060       (tile.mi_row_end - tile.mi_row_start + (1 << shift) - 1) >> shift;
1061   return num_vert_units;
1062 }
1063 
get_num_cols(TileInfo tile,int shift)1064 static INLINE int get_num_cols(TileInfo tile, int shift) {
1065   int num_cols =
1066       (tile.mi_col_end - tile.mi_col_start + (1 << shift) - 1) >> shift;
1067   return num_cols;
1068 }
1069 
get_level_index(VP9_LEVEL level)1070 static INLINE int get_level_index(VP9_LEVEL level) {
1071   int i;
1072   for (i = 0; i < VP9_LEVELS; ++i) {
1073     if (level == vp9_level_defs[i].level) return i;
1074   }
1075   return -1;
1076 }
1077 
1078 // Return the log2 value of max column tiles corresponding to the level that
1079 // the picture size fits into.
log_tile_cols_from_picsize_level(uint32_t width,uint32_t height)1080 static INLINE int log_tile_cols_from_picsize_level(uint32_t width,
1081                                                    uint32_t height) {
1082   int i;
1083   const uint32_t pic_size = width * height;
1084   const uint32_t pic_breadth = VPXMAX(width, height);
1085   for (i = LEVEL_1; i < LEVEL_MAX; ++i) {
1086     if (vp9_level_defs[i].max_luma_picture_size >= pic_size &&
1087         vp9_level_defs[i].max_luma_picture_breadth >= pic_breadth) {
1088       return get_msb(vp9_level_defs[i].max_col_tiles);
1089     }
1090   }
1091   return INT_MAX;
1092 }
1093 
1094 VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec);
1095 
1096 int vp9_set_roi_map(VP9_COMP *cpi, unsigned char *map, unsigned int rows,
1097                     unsigned int cols, int delta_q[8], int delta_lf[8],
1098                     int skip[8], int ref_frame[8]);
1099 
1100 void vp9_new_framerate(VP9_COMP *cpi, double framerate);
1101 
1102 void vp9_set_row_mt(VP9_COMP *cpi);
1103 
1104 int vp9_get_psnr(const VP9_COMP *cpi, PSNR_STATS *psnr);
1105 
1106 #define LAYER_IDS_TO_IDX(sl, tl, num_tl) ((sl) * (num_tl) + (tl))
1107 
1108 #ifdef __cplusplus
1109 }  // extern "C"
1110 #endif
1111 
1112 #endif  // VPX_VP9_ENCODER_VP9_ENCODER_H_
1113