2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
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.
11 #ifndef VPX_VP9_ENCODER_VP9_ENCODER_H_
12 #define VPX_VP9_ENCODER_VP9_ENCODER_H_
16 #include "./vpx_config.h"
17 #include "vpx/internal/vpx_codec_internal.h"
18 #include "vpx/vp8cx.h"
19 #if CONFIG_INTERNAL_STATS
20 #include "vpx_dsp/ssim.h"
22 #include "vpx_dsp/variance.h"
23 #include "vpx_dsp/psnr.h"
24 #include "vpx_ports/system_state.h"
25 #include "vpx_util/vpx_thread.h"
26 #include "vpx_util/vpx_timestamp.h"
28 #include "vp9/common/vp9_alloccommon.h"
29 #include "vp9/common/vp9_ppflags.h"
30 #include "vp9/common/vp9_entropymode.h"
31 #include "vp9/common/vp9_thread_common.h"
32 #include "vp9/common/vp9_onyxc_int.h"
34 #if !CONFIG_REALTIME_ONLY
35 #include "vp9/encoder/vp9_alt_ref_aq.h"
37 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
38 #include "vp9/encoder/vp9_context_tree.h"
39 #include "vp9/encoder/vp9_encodemb.h"
40 #include "vp9/encoder/vp9_ethread.h"
41 #include "vp9/encoder/vp9_firstpass.h"
42 #include "vp9/encoder/vp9_job_queue.h"
43 #include "vp9/encoder/vp9_lookahead.h"
44 #include "vp9/encoder/vp9_mbgraph.h"
45 #include "vp9/encoder/vp9_mcomp.h"
46 #include "vp9/encoder/vp9_noise_estimate.h"
47 #include "vp9/encoder/vp9_quantize.h"
48 #include "vp9/encoder/vp9_ratectrl.h"
49 #include "vp9/encoder/vp9_rd.h"
50 #include "vp9/encoder/vp9_speed_features.h"
51 #include "vp9/encoder/vp9_svc_layercontext.h"
52 #include "vp9/encoder/vp9_tokenize.h"
54 #if CONFIG_VP9_TEMPORAL_DENOISING
55 #include "vp9/encoder/vp9_denoiser.h"
62 // vp9 uses 10,000,000 ticks/second as time stamp
63 #define TICKS_PER_SEC 10000000
66 int nmvjointcost[MV_JOINTS];
67 int nmvcosts[2][MV_VALS];
68 int nmvcosts_hp[2][MV_VALS];
70 vpx_prob segment_pred_probs[PREDICTION_PROBS];
72 unsigned char *last_frame_seg_map_copy;
74 // 0 = Intra, Last, GF, ARF
75 signed char last_ref_lf_deltas[MAX_REF_LF_DELTAS];
77 signed char last_mode_lf_deltas[MAX_MODE_LF_DELTAS];
83 // encode_breakout is disabled.
84 ENCODE_BREAKOUT_DISABLED = 0,
85 // encode_breakout is enabled.
86 ENCODE_BREAKOUT_ENABLED = 1,
87 // encode_breakout is enabled with small max_thresh limit.
88 ENCODE_BREAKOUT_LIMITED = 2
89 } ENCODE_BREAKOUT_TYPE;
99 // Good Quality Fast Encoding. The encoder balances quality with the amount of
100 // time it takes to encode the output. Speed setting controls how fast.
103 // The encoder places priority on the quality of the output over encoding
104 // speed. The output is compressed at the highest possible quality. This
105 // option takes the longest amount of time to encode. Speed setting ignored.
108 // Realtime/Live Encoding. This mode is optimized for realtime encoding (for
109 // example, capturing a television signal or feed from a live camera). Speed
110 // setting controls how fast.
115 FRAMEFLAGS_KEY = 1 << 0,
116 FRAMEFLAGS_GOLDEN = 1 << 1,
117 FRAMEFLAGS_ALTREF = 1 << 2,
124 CYCLIC_REFRESH_AQ = 3,
128 // AQ based on lookahead temporal
129 // variance (only valid for altref frames)
131 AQ_MODE_COUNT // This should always be the last member of the enum
135 RESIZE_NONE = 0, // No frame resizing allowed (except for SVC).
136 RESIZE_FIXED = 1, // All frames are coded at the specified dimension.
137 RESIZE_DYNAMIC = 2 // Coded size of each frame is determined by the codec.
142 kLowSadLowSumdiff = 1,
143 kLowSadHighSumdiff = 2,
144 kHighSadLowSumdiff = 3,
145 kHighSadHighSumdiff = 4,
146 kLowVarHighSumdiff = 5,
150 typedef struct VP9EncoderConfig {
151 BITSTREAM_PROFILE profile;
152 vpx_bit_depth_t bit_depth; // Codec bit-depth.
153 int width; // width of data passed to the compressor
154 int height; // height of data passed to the compressor
155 unsigned int input_bit_depth; // Input bit depth.
156 double init_framerate; // set to passed in framerate
157 vpx_rational_t g_timebase; // equivalent to g_timebase in vpx_codec_enc_cfg_t
158 vpx_rational64_t g_timebase_in_ts; // g_timebase * TICKS_PER_SEC
160 int64_t target_bandwidth; // bandwidth to be used in bits per second
162 int noise_sensitivity; // pre processing blur: recommendation 0
163 int sharpness; // sharpening output: recommendation 0:
165 // maximum allowed bitrate for any intra frame in % of bitrate target.
166 unsigned int rc_max_intra_bitrate_pct;
167 // maximum allowed bitrate for any inter frame in % of bitrate target.
168 unsigned int rc_max_inter_bitrate_pct;
169 // percent of rate boost for golden frame in CBR mode.
170 unsigned int gf_cbr_boost_pct;
175 // Key Framing Operations
176 int auto_key; // autodetect cut scenes and set the keyframes
177 int key_freq; // maximum distance to key frame.
179 int lag_in_frames; // how many frames lag before we start encoding
181 // ----------------------------------------------------------------
182 // DATARATE CONTROL OPTIONS
184 // vbr, cbr, constrained quality or constant quality
185 enum vpx_rc_mode rc_mode;
187 // buffer targeting aggressiveness
191 // buffering parameters
192 int64_t starting_buffer_level_ms;
193 int64_t optimal_buffer_level_ms;
194 int64_t maximum_buffer_size_ms;
196 // Frame drop threshold.
197 int drop_frames_water_mark;
199 // controlling quality
204 AQ_MODE aq_mode; // Adaptive Quantization mode
206 // Special handling of Adaptive Quantization for AltRef frames
209 // Internal frame size scaling.
210 RESIZE_TYPE resize_mode;
211 int scaled_frame_width;
212 int scaled_frame_height;
214 // Enable feature to reduce the frame quantization every x frames.
215 int frame_periodic_boost;
217 // two pass datarate control
218 int two_pass_vbrbias; // two pass datarate control tweaks
219 int two_pass_vbrmin_section;
220 int two_pass_vbrmax_section;
221 int vbr_corpus_complexity; // 0 indicates corpus vbr disabled
222 // END DATARATE CONTROL OPTIONS
223 // ----------------------------------------------------------------
225 // Spatial and temporal scalability.
226 int ss_number_layers; // Number of spatial layers.
227 int ts_number_layers; // Number of temporal layers.
228 // Bitrate allocation for spatial layers.
229 int layer_target_bitrate[VPX_MAX_LAYERS];
230 int ss_target_bitrate[VPX_SS_MAX_LAYERS];
231 int ss_enable_auto_arf[VPX_SS_MAX_LAYERS];
232 // Bitrate allocation (CBR mode) and framerate factor, for temporal layers.
233 int ts_rate_decimator[VPX_TS_MAX_LAYERS];
237 int encode_breakout; // early breakout : for video conf recommend 800
239 /* Bitfield defining the error resiliency features to enable.
240 * Can provide decodable frames after losses in previous
241 * frames and decodable partitions after losses in the same frame.
243 unsigned int error_resilient_mode;
245 /* Bitfield defining the parallel decoding mode where the
246 * decoding in successive frames may be conducted in parallel
247 * just by decoding the frame headers.
249 unsigned int frame_parallel_decoding_mode;
260 int enable_tpl_model;
264 unsigned int target_level;
266 vpx_fixed_buf_t two_pass_stats_in;
268 #if CONFIG_FP_MB_STATS
269 vpx_fixed_buf_t firstpass_mb_stats_in;
273 vp9e_tune_content content;
274 #if CONFIG_VP9_HIGHBITDEPTH
275 int use_highbitdepth;
277 vpx_color_space_t color_space;
278 vpx_color_range_t color_range;
281 VP9E_TEMPORAL_LAYERING_MODE temporal_layering_mode;
284 unsigned int motion_vector_unit_test;
288 static INLINE int is_lossless_requested(const VP9EncoderConfig *cfg) {
289 return cfg->best_allowed_q == 0 && cfg->worst_allowed_q == 0;
292 typedef struct TplDepStats {
303 #if CONFIG_NON_GREEDY_MV
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
312 typedef struct TplDepFrame {
314 TplDepStats *tpl_stats_ptr;
321 #if CONFIG_NON_GREEDY_MV
324 double *rd_diff_arr[3];
328 #define TPL_DEP_COST_SCALE_LOG2 4
330 // TODO(jingning) All spatially adaptive variables should go to TileDataEnc.
331 typedef struct TileDataEnc {
333 int thresh_freq_fact[BLOCK_SIZES][MAX_MODES];
334 #if CONFIG_CONSISTENT_RECODE
335 int thresh_freq_fact_prev[BLOCK_SIZES][MAX_MODES];
337 int8_t mode_map[BLOCK_SIZES][MAX_MODES];
338 FIRSTPASS_DATA fp_data;
339 VP9RowMTSync row_mt_sync;
341 // Used for adaptive_rd_thresh with row multithreading
342 int *row_base_thresh_freq_fact;
345 typedef struct RowMTInfo {
346 JobQueueHandle job_queue_hdl;
347 #if CONFIG_MULTITHREAD
348 pthread_mutex_t job_mutex;
358 typedef struct MultiThreadHandle {
359 int allocated_tile_rows;
360 int allocated_tile_cols;
361 int allocated_vert_unit_rows;
363 // Frame level params
364 int num_tile_vert_sbs[MAX_NUM_TILE_ROWS];
366 // Job Queue structure and handles
369 int jobs_per_tile_col;
371 RowMTInfo row_mt_info[MAX_NUM_TILE_COLS];
372 int thread_id_to_tile_id[MAX_NUM_THREADS]; // Mapping of threads to tiles
375 typedef struct RD_COUNTS {
376 vp9_coeff_count coef_counts[TX_SIZES][PLANE_TYPES];
377 int64_t comp_pred_diff[REFERENCE_MODES];
378 int64_t filter_diff[SWITCHABLE_FILTER_CONTEXTS];
381 typedef struct ThreadData {
384 FRAME_COUNTS *counts;
386 PICK_MODE_CONTEXT *leaf_tree;
391 struct EncWorkerData;
393 typedef struct ActiveMap {
399 typedef enum { Y, U, V, ALL } STAT_TYPE;
401 typedef struct IMAGE_STAT {
402 double stat[ALL + 1];
406 // Kf noise filtering currently disabled by default in build.
407 // #define ENABLE_KF_DENOISE 1
409 #define CPB_WINDOW_SIZE 4
410 #define FRAME_WINDOW_SIZE 128
411 #define SAMPLE_RATE_GRACE_P 0.015
412 #define VP9_LEVELS 14
436 uint64_t max_luma_sample_rate;
437 uint32_t max_luma_picture_size;
438 uint32_t max_luma_picture_breadth;
439 double average_bitrate; // in kilobits per second
440 double max_cpb_size; // in kilobits
441 double compression_ratio;
442 uint8_t max_col_tiles;
443 uint32_t min_altref_distance;
444 uint8_t max_ref_frame_buffers;
447 extern const Vp9LevelSpec vp9_level_defs[VP9_LEVELS];
450 int64_t ts; // timestamp
451 uint32_t luma_samples;
452 uint32_t size; // in bytes
456 FrameRecord buf[FRAME_WINDOW_SIZE];
462 uint8_t seen_first_altref;
463 uint32_t frames_since_last_altref;
464 uint64_t total_compressed_size;
465 uint64_t total_uncompressed_size;
466 double time_encoded; // in seconds
467 FrameWindowBuffer frame_window_buffer;
472 Vp9LevelStats level_stats;
473 Vp9LevelSpec level_spec;
477 BITRATE_TOO_LARGE = 0,
478 LUMA_PIC_SIZE_TOO_LARGE,
479 LUMA_PIC_BREADTH_TOO_LARGE,
480 LUMA_SAMPLE_RATE_TOO_LARGE,
482 COMPRESSION_RATIO_TOO_SMALL,
483 TOO_MANY_COLUMN_TILE,
484 ALTREF_DIST_TOO_SMALL,
486 TARGET_LEVEL_FAIL_IDS
487 } TARGET_LEVEL_FAIL_ID;
492 int max_frame_size; // in bits
493 double max_cpb_size; // in bits
496 typedef struct ARNRFilterData {
497 YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS];
501 struct scale_factors sf;
504 typedef struct EncFrameBuf {
507 YV12_BUFFER_CONFIG frame;
510 // Maximum operating frame buffer size needed for a GOP using ARF reference.
511 #define MAX_ARF_GOP_SIZE (2 * MAX_LAG_BUFFERS)
512 #define MAX_KMEANS_GROUPS 8
514 typedef struct KMEANS_DATA {
521 typedef struct ENCODE_COMMAND {
522 int use_external_quantize_index;
523 int external_quantize_index;
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
535 static INLINE void encode_command_init(ENCODE_COMMAND *encode_command) {
536 vp9_zero(*encode_command);
537 encode_command->use_external_quantize_index = 0;
538 encode_command->external_quantize_index = -1;
541 static INLINE void encode_command_set_external_quantize_index(
542 ENCODE_COMMAND *encode_command, int quantize_index) {
543 encode_command->use_external_quantize_index = 1;
544 encode_command->external_quantize_index = quantize_index;
547 static INLINE void encode_command_reset_external_quantize_index(
548 ENCODE_COMMAND *encode_command) {
549 encode_command->use_external_quantize_index = 0;
550 encode_command->external_quantize_index = -1;
553 // Returns number of units in size of 4, if not multiple not a multiple of 4,
554 // round it up. For example, size is 7, return 3.
555 static INLINE int get_num_unit_4x4(int size) { return (size + 3) >> 2; }
556 #endif // CONFIG_RATE_CTRL
558 typedef struct VP9_COMP {
559 FRAME_INFO frame_info;
562 MB_MODE_INFO_EXT *mbmi_ext_base;
563 DECLARE_ALIGNED(16, int16_t, y_dequant[QINDEX_RANGE][8]);
564 DECLARE_ALIGNED(16, int16_t, uv_dequant[QINDEX_RANGE][8]);
566 VP9EncoderConfig oxcf;
567 struct lookahead_ctx *lookahead;
568 struct lookahead_entry *alt_ref_source;
570 YV12_BUFFER_CONFIG *Source;
571 YV12_BUFFER_CONFIG *Last_Source; // NULL for first frame and alt_ref frames
572 YV12_BUFFER_CONFIG *un_scaled_source;
573 YV12_BUFFER_CONFIG scaled_source;
574 YV12_BUFFER_CONFIG *unscaled_last_source;
575 YV12_BUFFER_CONFIG scaled_last_source;
576 #ifdef ENABLE_KF_DENOISE
577 YV12_BUFFER_CONFIG raw_unscaled_source;
578 YV12_BUFFER_CONFIG raw_scaled_source;
580 YV12_BUFFER_CONFIG *raw_source_frame;
582 BLOCK_SIZE tpl_bsize;
583 TplDepFrame tpl_stats[MAX_ARF_GOP_SIZE];
584 YV12_BUFFER_CONFIG *tpl_recon_frames[REF_FRAMES];
585 EncFrameBuf enc_frame_buf[REF_FRAMES];
586 #if CONFIG_MULTITHREAD
587 pthread_mutex_t kmeans_mutex;
589 int kmeans_data_arr_alloc;
590 KMEANS_DATA *kmeans_data_arr;
591 int kmeans_data_size;
592 int kmeans_data_stride;
593 double kmeans_ctr_ls[MAX_KMEANS_GROUPS];
594 double kmeans_boundary_ls[MAX_KMEANS_GROUPS];
595 int kmeans_count_ls[MAX_KMEANS_GROUPS];
597 #if CONFIG_NON_GREEDY_MV
598 MotionFieldInfo motion_field_info;
600 int_mv *select_mv_arr;
603 TileDataEnc *tile_data;
604 int allocated_tiles; // Keep track of memory allocated for tiles.
606 // For a still frame, this flag is set to 1 to skip partition search.
607 int partition_search_skippable_frame;
609 int scaled_ref_idx[REFS_PER_FRAME];
614 int ref_fb_idx[REF_FRAMES];
616 int refresh_last_frame;
617 int refresh_golden_frame;
618 int refresh_alt_ref_frame;
620 int ext_refresh_frame_flags_pending;
621 int ext_refresh_last_frame;
622 int ext_refresh_golden_frame;
623 int ext_refresh_alt_ref_frame;
625 int ext_refresh_frame_context_pending;
626 int ext_refresh_frame_context;
628 int64_t norm_wiener_variance;
629 int64_t *mb_wiener_variance;
630 int mb_wiener_var_rows;
631 int mb_wiener_var_cols;
632 double *mi_ssim_rdmult_scaling_factors;
634 YV12_BUFFER_CONFIG last_frame_uf;
636 TOKENEXTRA *tile_tok[4][1 << 6];
637 TOKENLIST *tplist[4][1 << 6];
639 // Ambient reconstruction err target for force key frames
644 CODING_CONTEXT coding_context;
649 int *nmvsadcosts_hp[2];
651 int64_t last_time_stamp_seen;
652 int64_t last_end_time_stamp_seen;
653 int64_t first_time_stamp_ever;
658 int interp_filter_selected[REF_FRAMES][SWITCHABLE];
660 struct vpx_codec_pkt_list *output_pkt_list;
662 MBGRAPH_FRAME_STATS mbgraph_stats[MAX_LAG_BUFFERS];
663 int mbgraph_n_frames; // number of frames filled in the above
664 int static_mb_pct; // % forced skip mbs by segmentation
669 uint32_t max_mv_magnitude;
672 int allow_comp_inter_inter;
674 // Default value is 1. From first pass stats, encode_breakout may be disabled.
675 ENCODE_BREAKOUT_TYPE allow_encode_breakout;
677 // Get threshold from external input. A suggested threshold is 800 for HD
678 // clips, and 300 for < HD clips.
681 uint8_t *segmentation_map;
685 // segment threashold for encode breakout
686 int segment_encode_breakout[MAX_SEGMENTS];
688 CYCLIC_REFRESH *cyclic_refresh;
689 ActiveMap active_map;
691 fractional_mv_step_fp *find_fractional_mv_step;
692 struct scale_factors me_sf;
693 vp9_diamond_search_fn_t diamond_search_sad;
694 vp9_variance_fn_ptr_t fn_ptr[BLOCK_SIZES];
695 uint64_t time_receive_data;
696 uint64_t time_compress_data;
697 uint64_t time_pick_lpf;
698 uint64_t time_encode_sb_row;
700 #if CONFIG_FP_MB_STATS
706 // Force recalculation of segment_ids for each mode info
707 uint8_t force_update_segmentation;
709 YV12_BUFFER_CONFIG alt_ref_buffer;
711 // class responsible for adaptive
712 // quantization of altref frames
713 struct ALT_REF_AQ *alt_ref_aq;
715 #if CONFIG_INTERNAL_STATS
716 unsigned int mode_chosen_counts[MAX_MODES];
719 uint64_t total_sq_error;
720 uint64_t total_samples;
723 uint64_t totalp_sq_error;
724 uint64_t totalp_samples;
727 double total_blockiness;
728 double worst_blockiness;
731 double summed_quality;
732 double summed_weights;
733 double summedp_quality;
734 double summedp_weights;
735 unsigned int tot_recode_hits;
742 int b_calculate_ssimg;
743 int b_calculate_blockiness;
745 int b_calculate_consistency;
747 double total_inconsistency;
748 double worst_consistency;
752 int b_calculate_psnr;
758 int initial_mbs; // Number of MBs in the full-size frame; to be used to
759 // normalize the firstpass stats. This will differ from the
760 // number of MBs in the current frame when the frame is
767 // Store frame variance info in SOURCE_VAR_BASED_PARTITION search type.
768 diff *source_diff_var;
769 // The threshold used in SOURCE_VAR_BASED_PARTITION search type.
770 unsigned int source_var_thresh;
771 int frames_till_next_var_check;
775 search_site_config ss_cfg;
777 int mbmode_cost[INTRA_MODES];
778 unsigned int inter_mode_cost[INTER_MODE_CONTEXTS][INTER_MODES];
779 int intra_uv_mode_cost[FRAME_TYPES][INTRA_MODES][INTRA_MODES];
780 int y_mode_costs[INTRA_MODES][INTRA_MODES][INTRA_MODES];
781 int switchable_interp_costs[SWITCHABLE_FILTER_CONTEXTS][SWITCHABLE_FILTERS];
782 int partition_cost[PARTITION_CONTEXTS][PARTITION_TYPES];
783 // Indices are: max_tx_size-1, tx_size_ctx, tx_size
784 int tx_size_cost[TX_SIZES - 1][TX_SIZE_CONTEXTS][TX_SIZES];
786 #if CONFIG_VP9_TEMPORAL_DENOISING
787 VP9_DENOISER denoiser;
791 RESIZE_STATE resize_state;
793 int resize_scale_num;
794 int resize_scale_den;
796 int resize_buffer_underflow;
799 int use_skin_detection;
803 NOISE_ESTIMATE noise_estimate;
805 // Count on how many consecutive times a block uses small/zeromv for encoding.
806 uint8_t *consec_zero_mv;
808 // VAR_BASED_PARTITION thresholds
809 // 0 - threshold_64x64; 1 - threshold_32x32;
810 // 2 - threshold_16x16; 3 - vbp_threshold_8x8;
811 int64_t vbp_thresholds[4];
812 int64_t vbp_threshold_minmax;
813 int64_t vbp_threshold_sad;
814 // Threshold used for partition copy
815 int64_t vbp_threshold_copy;
816 BLOCK_SIZE vbp_bsize_min;
821 struct EncWorkerData *tile_thr_data;
822 VP9LfSync lf_row_sync;
823 struct VP9BitstreamWorkerData *vp9_bitstream_worker_data;
825 int keep_level_stats;
826 Vp9LevelInfo level_info;
827 MultiThreadHandle multi_thread_ctxt;
828 void (*row_mt_sync_read_ptr)(VP9RowMTSync *const, int, int);
829 void (*row_mt_sync_write_ptr)(VP9RowMTSync *const, int, int, const int);
830 ARNRFilterData arnr_filter_data;
833 unsigned int row_mt_bit_exact;
835 // Previous Partition Info
836 BLOCK_SIZE *prev_partition;
837 int8_t *prev_segment_id;
838 // Used to save the status of whether a block has a low variance in
839 // choose_partitioning. 0 for 64x64, 1~2 for 64x32, 3~4 for 32x64, 5~8 for
840 // 32x32, 9~24 for 16x16.
841 // This is for the last frame and is copied to the current frame
842 // when partition copy happens.
843 uint8_t *prev_variance_low;
844 uint8_t *copied_frame_cnt;
845 uint8_t max_copied_frame;
846 // If the last frame is dropped, we don't copy partition.
847 uint8_t last_frame_dropped;
849 // For each superblock: keeps track of the last time (in frame distance) the
850 // the superblock did not have low source sad.
851 uint8_t *content_state_sb_fd;
853 int compute_source_sad_onepass;
855 LevelConstraint level_constraint;
857 uint8_t *count_arf_frame_usage;
858 uint8_t *count_lastgolden_frame_usage;
863 ENCODE_COMMAND encode_command;
864 PARTITION_INFO *partition_info;
869 // Allocates memory for the partition information.
870 // The unit size is each 4x4 block.
871 // Only called once in vp9_create_compressor().
872 static INLINE void partition_info_init(struct VP9_COMP *cpi) {
873 VP9_COMMON *const cm = &cpi->common;
874 const int unit_width = get_num_unit_4x4(cpi->frame_info.frame_width);
875 const int unit_height = get_num_unit_4x4(cpi->frame_info.frame_height);
876 CHECK_MEM_ERROR(cm, cpi->partition_info,
877 (PARTITION_INFO *)vpx_calloc(unit_width * unit_height,
878 sizeof(PARTITION_INFO)));
879 memset(cpi->partition_info, 0,
880 unit_width * unit_height * sizeof(PARTITION_INFO));
883 // Frees memory of the partition information.
884 // Only called once in dealloc_compressor_data().
885 static INLINE void free_partition_info(struct VP9_COMP *cpi) {
886 vpx_free(cpi->partition_info);
887 cpi->partition_info = NULL;
889 #endif // CONFIG_RATE_CTRL
891 typedef struct ENCODE_FRAME_RESULT {
893 FRAME_UPDATE_TYPE update_type;
897 FRAME_COUNTS frame_counts;
898 #endif // CONFIG_RATE_CTRL
900 } ENCODE_FRAME_RESULT;
902 void vp9_initialize_enc(void);
904 void vp9_update_compressor_with_img_fmt(VP9_COMP *cpi, vpx_img_fmt_t img_fmt);
905 struct VP9_COMP *vp9_create_compressor(const VP9EncoderConfig *oxcf,
906 BufferPool *const pool);
907 void vp9_remove_compressor(VP9_COMP *cpi);
909 void vp9_change_config(VP9_COMP *cpi, const VP9EncoderConfig *oxcf);
911 // receive a frames worth of data. caller can assume that a copy of this
912 // frame is made and not just a copy of the pointer..
913 int vp9_receive_raw_frame(VP9_COMP *cpi, vpx_enc_frame_flags_t frame_flags,
914 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
917 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
918 size_t *size, uint8_t *dest, int64_t *time_stamp,
919 int64_t *time_end, int flush,
920 ENCODE_FRAME_RESULT *encode_frame_result);
922 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
923 vp9_ppflags_t *flags);
925 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags);
927 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags);
929 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
930 YV12_BUFFER_CONFIG *sd);
932 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
933 YV12_BUFFER_CONFIG *sd);
935 int vp9_update_entropy(VP9_COMP *cpi, int update);
937 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
940 int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
943 int vp9_set_internal_size(VP9_COMP *cpi, VPX_SCALING horiz_mode,
944 VPX_SCALING vert_mode);
946 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
947 unsigned int height);
949 void vp9_set_svc(VP9_COMP *cpi, int use_svc);
951 static INLINE int stack_pop(int *stack, int stack_size) {
953 const int r = stack[0];
954 for (idx = 1; idx < stack_size; ++idx) stack[idx - 1] = stack[idx];
959 static INLINE int stack_top(const int *stack) { return stack[0]; }
961 static INLINE void stack_push(int *stack, int new_item, int stack_size) {
963 for (idx = stack_size; idx > 0; --idx) stack[idx] = stack[idx - 1];
967 static INLINE void stack_init(int *stack, int length) {
969 for (idx = 0; idx < length; ++idx) stack[idx] = -1;
972 int vp9_get_quantizer(const VP9_COMP *cpi);
974 static INLINE int frame_is_kf_gf_arf(const VP9_COMP *cpi) {
975 return frame_is_intra_only(&cpi->common) || cpi->refresh_alt_ref_frame ||
976 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref);
979 static INLINE int get_ref_frame_map_idx(const VP9_COMP *cpi,
980 MV_REFERENCE_FRAME ref_frame) {
981 if (ref_frame == LAST_FRAME) {
982 return cpi->lst_fb_idx;
983 } else if (ref_frame == GOLDEN_FRAME) {
984 return cpi->gld_fb_idx;
986 return cpi->alt_fb_idx;
990 static INLINE int get_ref_frame_buf_idx(const VP9_COMP *const cpi,
992 const VP9_COMMON *const cm = &cpi->common;
993 const int map_idx = get_ref_frame_map_idx(cpi, ref_frame);
994 return (map_idx != INVALID_IDX) ? cm->ref_frame_map[map_idx] : INVALID_IDX;
997 static INLINE RefCntBuffer *get_ref_cnt_buffer(VP9_COMMON *cm, int fb_idx) {
998 return fb_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[fb_idx] : NULL;
1001 static INLINE YV12_BUFFER_CONFIG *get_ref_frame_buffer(
1002 const VP9_COMP *const cpi, MV_REFERENCE_FRAME ref_frame) {
1003 const VP9_COMMON *const cm = &cpi->common;
1004 const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
1005 return buf_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[buf_idx].buf
1009 static INLINE int get_token_alloc(int mb_rows, int mb_cols) {
1010 // TODO(JBB): double check we can't exceed this token count if we have a
1011 // 32x32 transform crossing a boundary at a multiple of 16.
1012 // mb_rows, cols are in units of 16 pixels. We assume 3 planes all at full
1013 // resolution. We assume up to 1 token per pixel, and then allow
1014 // a head room of 4.
1015 return mb_rows * mb_cols * (16 * 16 * 3 + 4);
1018 // Get the allocated token size for a tile. It does the same calculation as in
1019 // the frame token allocation.
1020 static INLINE int allocated_tokens(TileInfo tile) {
1021 int tile_mb_rows = (tile.mi_row_end - tile.mi_row_start + 1) >> 1;
1022 int tile_mb_cols = (tile.mi_col_end - tile.mi_col_start + 1) >> 1;
1024 return get_token_alloc(tile_mb_rows, tile_mb_cols);
1027 static INLINE void get_start_tok(VP9_COMP *cpi, int tile_row, int tile_col,
1028 int mi_row, TOKENEXTRA **tok) {
1029 VP9_COMMON *const cm = &cpi->common;
1030 const int tile_cols = 1 << cm->log2_tile_cols;
1031 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
1032 const TileInfo *const tile_info = &this_tile->tile_info;
1034 int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
1035 const int mb_row = (mi_row - tile_info->mi_row_start) >> 1;
1038 cpi->tile_tok[tile_row][tile_col] + get_token_alloc(mb_row, tile_mb_cols);
1041 int64_t vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b);
1042 #if CONFIG_VP9_HIGHBITDEPTH
1043 int64_t vp9_highbd_get_y_sse(const YV12_BUFFER_CONFIG *a,
1044 const YV12_BUFFER_CONFIG *b);
1045 #endif // CONFIG_VP9_HIGHBITDEPTH
1047 void vp9_scale_references(VP9_COMP *cpi);
1049 void vp9_update_reference_frames(VP9_COMP *cpi);
1051 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv);
1053 YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(
1054 VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
1055 YV12_BUFFER_CONFIG *scaled_temp, INTERP_FILTER filter_type,
1056 int phase_scaler, INTERP_FILTER filter_type2, int phase_scaler2);
1058 YV12_BUFFER_CONFIG *vp9_scale_if_required(
1059 VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
1060 int use_normative_scaler, INTERP_FILTER filter_type, int phase_scaler);
1062 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags);
1064 static INLINE int is_one_pass_cbr_svc(const struct VP9_COMP *const cpi) {
1065 return (cpi->use_svc && cpi->oxcf.pass == 0);
1068 #if CONFIG_VP9_TEMPORAL_DENOISING
1069 static INLINE int denoise_svc(const struct VP9_COMP *const cpi) {
1070 return (!cpi->use_svc || (cpi->use_svc && cpi->svc.spatial_layer_id >=
1071 cpi->svc.first_layer_denoise));
1075 #define MIN_LOOKAHEAD_FOR_ARFS 4
1076 static INLINE int is_altref_enabled(const VP9_COMP *const cpi) {
1077 return !(cpi->oxcf.mode == REALTIME && cpi->oxcf.rc_mode == VPX_CBR) &&
1078 cpi->oxcf.lag_in_frames >= MIN_LOOKAHEAD_FOR_ARFS &&
1079 cpi->oxcf.enable_auto_arf;
1082 static INLINE void set_ref_ptrs(const VP9_COMMON *const cm, MACROBLOCKD *xd,
1083 MV_REFERENCE_FRAME ref0,
1084 MV_REFERENCE_FRAME ref1) {
1086 &cm->frame_refs[ref0 >= LAST_FRAME ? ref0 - LAST_FRAME : 0];
1088 &cm->frame_refs[ref1 >= LAST_FRAME ? ref1 - LAST_FRAME : 0];
1091 static INLINE int get_chessboard_index(const int frame_index) {
1092 return frame_index & 0x1;
1095 static INLINE int *cond_cost_list(const struct VP9_COMP *cpi, int *cost_list) {
1096 return cpi->sf.mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL;
1099 static INLINE int get_num_vert_units(TileInfo tile, int shift) {
1100 int num_vert_units =
1101 (tile.mi_row_end - tile.mi_row_start + (1 << shift) - 1) >> shift;
1102 return num_vert_units;
1105 static INLINE int get_num_cols(TileInfo tile, int shift) {
1107 (tile.mi_col_end - tile.mi_col_start + (1 << shift) - 1) >> shift;
1111 static INLINE int get_level_index(VP9_LEVEL level) {
1113 for (i = 0; i < VP9_LEVELS; ++i) {
1114 if (level == vp9_level_defs[i].level) return i;
1119 // Return the log2 value of max column tiles corresponding to the level that
1120 // the picture size fits into.
1121 static INLINE int log_tile_cols_from_picsize_level(uint32_t width,
1124 const uint32_t pic_size = width * height;
1125 const uint32_t pic_breadth = VPXMAX(width, height);
1126 for (i = LEVEL_1; i < LEVEL_MAX; ++i) {
1127 if (vp9_level_defs[i].max_luma_picture_size >= pic_size &&
1128 vp9_level_defs[i].max_luma_picture_breadth >= pic_breadth) {
1129 return get_msb(vp9_level_defs[i].max_col_tiles);
1135 VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec);
1137 int vp9_set_roi_map(VP9_COMP *cpi, unsigned char *map, unsigned int rows,
1138 unsigned int cols, int delta_q[8], int delta_lf[8],
1139 int skip[8], int ref_frame[8]);
1141 void vp9_new_framerate(VP9_COMP *cpi, double framerate);
1143 void vp9_set_row_mt(VP9_COMP *cpi);
1145 int vp9_get_psnr(const VP9_COMP *cpi, PSNR_STATS *psnr);
1147 #define LAYER_IDS_TO_IDX(sl, tl, num_tl) ((sl) * (num_tl) + (tl))
1153 #endif // VPX_VP9_ENCODER_VP9_ENCODER_H_