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