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