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 VP10_ENCODER_ENCODER_H_
12 #define VP10_ENCODER_ENCODER_H_
16 #include "./vpx_config.h"
17 #include "vpx/vp8cx.h"
19 #include "vp10/common/alloccommon.h"
20 #include "vp10/common/ppflags.h"
21 #include "vp10/common/entropymode.h"
22 #include "vp10/common/thread_common.h"
23 #include "vp10/common/onyxc_int.h"
25 #include "vp10/encoder/aq_cyclicrefresh.h"
26 #include "vp10/encoder/context_tree.h"
27 #include "vp10/encoder/encodemb.h"
28 #include "vp10/encoder/firstpass.h"
29 #include "vp10/encoder/lookahead.h"
30 #include "vp10/encoder/mbgraph.h"
31 #include "vp10/encoder/mcomp.h"
32 #include "vp10/encoder/quantize.h"
33 #include "vp10/encoder/ratectrl.h"
34 #include "vp10/encoder/rd.h"
35 #include "vp10/encoder/speed_features.h"
36 #include "vp10/encoder/tokenize.h"
38 #if CONFIG_VP9_TEMPORAL_DENOISING
39 #include "vp10/encoder/denoiser.h"
42 #if CONFIG_INTERNAL_STATS
43 #include "vpx_dsp/ssim.h"
45 #include "vpx_dsp/variance.h"
46 #include "vpx/internal/vpx_codec_internal.h"
47 #include "vpx_util/vpx_thread.h"
54 int nmvjointcost[MV_JOINTS];
55 int nmvcosts[2][MV_VALS];
56 int nmvcosts_hp[2][MV_VALS];
58 #if !CONFIG_MISC_FIXES
59 vpx_prob segment_pred_probs[PREDICTION_PROBS];
62 unsigned char *last_frame_seg_map_copy;
64 // 0 = Intra, Last, GF, ARF
65 signed char last_ref_lf_deltas[MAX_REF_FRAMES];
67 signed char last_mode_lf_deltas[MAX_MODE_LF_DELTAS];
74 // encode_breakout is disabled.
75 ENCODE_BREAKOUT_DISABLED = 0,
76 // encode_breakout is enabled.
77 ENCODE_BREAKOUT_ENABLED = 1,
78 // encode_breakout is enabled with small max_thresh limit.
79 ENCODE_BREAKOUT_LIMITED = 2
80 } ENCODE_BREAKOUT_TYPE;
90 // Good Quality Fast Encoding. The encoder balances quality with the amount of
91 // time it takes to encode the output. Speed setting controls how fast.
94 // The encoder places priority on the quality of the output over encoding
95 // speed. The output is compressed at the highest possible quality. This
96 // option takes the longest amount of time to encode. Speed setting ignored.
99 // Realtime/Live Encoding. This mode is optimized for realtime encoding (for
100 // example, capturing a television signal or feed from a live camera). Speed
101 // setting controls how fast.
106 FRAMEFLAGS_KEY = 1 << 0,
107 FRAMEFLAGS_GOLDEN = 1 << 1,
108 FRAMEFLAGS_ALTREF = 1 << 2,
115 CYCLIC_REFRESH_AQ = 3,
116 AQ_MODE_COUNT // This should always be the last member of the enum
120 RESIZE_NONE = 0, // No frame resizing allowed.
121 RESIZE_FIXED = 1, // All frames are coded at the specified dimension.
122 RESIZE_DYNAMIC = 2 // Coded size of each frame is determined by the codec.
125 typedef struct VP10EncoderConfig {
126 BITSTREAM_PROFILE profile;
127 vpx_bit_depth_t bit_depth; // Codec bit-depth.
128 int width; // width of data passed to the compressor
129 int height; // height of data passed to the compressor
130 unsigned int input_bit_depth; // Input bit depth.
131 double init_framerate; // set to passed in framerate
132 int64_t target_bandwidth; // bandwidth to be used in kilobits per second
134 int noise_sensitivity; // pre processing blur: recommendation 0
135 int sharpness; // sharpening output: recommendation 0:
137 // maximum allowed bitrate for any intra frame in % of bitrate target.
138 unsigned int rc_max_intra_bitrate_pct;
139 // maximum allowed bitrate for any inter frame in % of bitrate target.
140 unsigned int rc_max_inter_bitrate_pct;
141 // percent of rate boost for golden frame in CBR mode.
142 unsigned int gf_cbr_boost_pct;
147 // Key Framing Operations
148 int auto_key; // autodetect cut scenes and set the keyframes
149 int key_freq; // maximum distance to key frame.
151 int lag_in_frames; // how many frames lag before we start encoding
153 // ----------------------------------------------------------------
154 // DATARATE CONTROL OPTIONS
156 // vbr, cbr, constrained quality or constant quality
157 enum vpx_rc_mode rc_mode;
159 // buffer targeting aggressiveness
163 // buffering parameters
164 int64_t starting_buffer_level_ms;
165 int64_t optimal_buffer_level_ms;
166 int64_t maximum_buffer_size_ms;
168 // Frame drop threshold.
169 int drop_frames_water_mark;
171 // controlling quality
176 AQ_MODE aq_mode; // Adaptive Quantization mode
178 // Internal frame size scaling.
179 RESIZE_TYPE resize_mode;
180 int scaled_frame_width;
181 int scaled_frame_height;
183 // Enable feature to reduce the frame quantization every x frames.
184 int frame_periodic_boost;
186 // two pass datarate control
187 int two_pass_vbrbias; // two pass datarate control tweaks
188 int two_pass_vbrmin_section;
189 int two_pass_vbrmax_section;
190 // END DATARATE CONTROL OPTIONS
191 // ----------------------------------------------------------------
195 int encode_breakout; // early breakout : for video conf recommend 800
197 /* Bitfield defining the error resiliency features to enable.
198 * Can provide decodable frames after losses in previous
199 * frames and decodable partitions after losses in the same frame.
201 unsigned int error_resilient_mode;
203 /* Bitfield defining the parallel decoding mode where the
204 * decoding in successive frames may be conducted in parallel
205 * just by decoding the frame headers.
207 unsigned int frame_parallel_decoding_mode;
220 vpx_fixed_buf_t two_pass_stats_in;
221 struct vpx_codec_pkt_list *output_pkt_list;
223 #if CONFIG_FP_MB_STATS
224 vpx_fixed_buf_t firstpass_mb_stats_in;
228 vp9e_tune_content content;
229 #if CONFIG_VP9_HIGHBITDEPTH
230 int use_highbitdepth;
232 vpx_color_space_t color_space;
238 static INLINE int is_lossless_requested(const VP10EncoderConfig *cfg) {
239 return cfg->best_allowed_q == 0 && cfg->worst_allowed_q == 0;
242 // TODO(jingning) All spatially adaptive variables should go to TileDataEnc.
243 typedef struct TileDataEnc {
245 int thresh_freq_fact[BLOCK_SIZES][MAX_MODES];
246 int mode_map[BLOCK_SIZES][MAX_MODES];
249 typedef struct RD_COUNTS {
250 vp10_coeff_count coef_counts[TX_SIZES][PLANE_TYPES];
251 int64_t comp_pred_diff[REFERENCE_MODES];
252 int64_t filter_diff[SWITCHABLE_FILTER_CONTEXTS];
255 typedef struct ThreadData {
258 FRAME_COUNTS *counts;
260 PICK_MODE_CONTEXT *leaf_tree;
265 struct EncWorkerData;
267 typedef struct ActiveMap {
280 typedef struct IMAGE_STAT {
285 typedef struct VP10_COMP {
288 MB_MODE_INFO_EXT *mbmi_ext_base;
289 DECLARE_ALIGNED(16, int16_t, y_dequant[QINDEX_RANGE][8]);
290 DECLARE_ALIGNED(16, int16_t, uv_dequant[QINDEX_RANGE][8]);
292 VP10EncoderConfig oxcf;
293 struct lookahead_ctx *lookahead;
294 struct lookahead_entry *alt_ref_source;
296 YV12_BUFFER_CONFIG *Source;
297 YV12_BUFFER_CONFIG *Last_Source; // NULL for first frame and alt_ref frames
298 YV12_BUFFER_CONFIG *un_scaled_source;
299 YV12_BUFFER_CONFIG scaled_source;
300 YV12_BUFFER_CONFIG *unscaled_last_source;
301 YV12_BUFFER_CONFIG scaled_last_source;
303 TileDataEnc *tile_data;
304 int allocated_tiles; // Keep track of memory allocated for tiles.
306 // For a still frame, this flag is set to 1 to skip partition search.
307 int partition_search_skippable_frame;
309 int scaled_ref_idx[MAX_REF_FRAMES];
314 int refresh_last_frame;
315 int refresh_golden_frame;
316 int refresh_alt_ref_frame;
318 int ext_refresh_frame_flags_pending;
319 int ext_refresh_last_frame;
320 int ext_refresh_golden_frame;
321 int ext_refresh_alt_ref_frame;
323 int ext_refresh_frame_context_pending;
324 int ext_refresh_frame_context;
326 YV12_BUFFER_CONFIG last_frame_uf;
328 TOKENEXTRA *tile_tok[4][1 << 6];
329 unsigned int tok_count[4][1 << 6];
331 // Ambient reconstruction err target for force key frames
336 CODING_CONTEXT coding_context;
341 int *nmvsadcosts_hp[2];
343 int64_t last_time_stamp_seen;
344 int64_t last_end_time_stamp_seen;
345 int64_t first_time_stamp_ever;
350 int interp_filter_selected[MAX_REF_FRAMES][SWITCHABLE];
352 struct vpx_codec_pkt_list *output_pkt_list;
354 MBGRAPH_FRAME_STATS mbgraph_stats[MAX_LAG_BUFFERS];
355 int mbgraph_n_frames; // number of frames filled in the above
356 int static_mb_pct; // % forced skip mbs by segmentation
361 unsigned int max_mv_magnitude;
364 int allow_comp_inter_inter;
366 // Default value is 1. From first pass stats, encode_breakout may be disabled.
367 ENCODE_BREAKOUT_TYPE allow_encode_breakout;
369 // Get threshold from external input. A suggested threshold is 800 for HD
370 // clips, and 300 for < HD clips.
373 unsigned char *segmentation_map;
375 // segment threashold for encode breakout
376 int segment_encode_breakout[MAX_SEGMENTS];
378 CYCLIC_REFRESH *cyclic_refresh;
379 ActiveMap active_map;
381 fractional_mv_step_fp *find_fractional_mv_step;
382 vp10_full_search_fn_t full_search_sad;
383 vp10_diamond_search_fn_t diamond_search_sad;
384 vp9_variance_fn_ptr_t fn_ptr[BLOCK_SIZES];
385 uint64_t time_receive_data;
386 uint64_t time_compress_data;
387 uint64_t time_pick_lpf;
388 uint64_t time_encode_sb_row;
390 #if CONFIG_FP_MB_STATS
396 YV12_BUFFER_CONFIG alt_ref_buffer;
399 #if CONFIG_INTERNAL_STATS
400 unsigned int mode_chosen_counts[MAX_MODES];
403 uint64_t total_sq_error;
404 uint64_t total_samples;
407 uint64_t totalp_sq_error;
408 uint64_t totalp_samples;
411 double total_blockiness;
412 double worst_blockiness;
415 double summed_quality;
416 double summed_weights;
417 double summedp_quality;
418 double summedp_weights;
419 unsigned int tot_recode_hits;
426 int b_calculate_ssimg;
427 int b_calculate_blockiness;
429 int b_calculate_consistency;
431 double total_inconsistency;
432 double worst_consistency;
436 int b_calculate_psnr;
442 int initial_mbs; // Number of MBs in the full-size frame; to be used to
443 // normalize the firstpass stats. This will differ from the
444 // number of MBs in the current frame when the frame is
447 // Store frame variance info in SOURCE_VAR_BASED_PARTITION search type.
448 diff *source_diff_var;
449 // The threshold used in SOURCE_VAR_BASED_PARTITION search type.
450 unsigned int source_var_thresh;
451 int frames_till_next_var_check;
455 search_site_config ss_cfg;
457 int mbmode_cost[INTRA_MODES];
458 unsigned int inter_mode_cost[INTER_MODE_CONTEXTS][INTER_MODES];
459 int intra_uv_mode_cost[FRAME_TYPES][INTRA_MODES];
460 int y_mode_costs[INTRA_MODES][INTRA_MODES][INTRA_MODES];
461 int switchable_interp_costs[SWITCHABLE_FILTER_CONTEXTS][SWITCHABLE_FILTERS];
462 int partition_cost[PARTITION_CONTEXTS][PARTITION_TYPES];
463 int palette_y_size_cost[10][PALETTE_SIZES];
464 int palette_uv_size_cost[10][PALETTE_SIZES];
465 int palette_y_color_cost[PALETTE_MAX_SIZE - 1][PALETTE_COLOR_CONTEXTS]
467 int palette_uv_color_cost[PALETTE_MAX_SIZE - 1][PALETTE_COLOR_CONTEXTS]
470 int multi_arf_allowed;
471 int multi_arf_enabled;
472 int multi_arf_last_grp_enabled;
474 #if CONFIG_VP9_TEMPORAL_DENOISING
475 VP9_DENOISER denoiser;
480 int resize_scale_num;
481 int resize_scale_den;
483 int resize_buffer_underflow;
486 // VAR_BASED_PARTITION thresholds
487 // 0 - threshold_64x64; 1 - threshold_32x32;
488 // 2 - threshold_16x16; 3 - vbp_threshold_8x8;
489 int64_t vbp_thresholds[4];
490 int64_t vbp_threshold_minmax;
491 int64_t vbp_threshold_sad;
492 BLOCK_SIZE vbp_bsize_min;
497 struct EncWorkerData *tile_thr_data;
498 VP9LfSync lf_row_sync;
501 void vp10_initialize_enc(void);
503 struct VP10_COMP *vp10_create_compressor(VP10EncoderConfig *oxcf,
504 BufferPool *const pool);
505 void vp10_remove_compressor(VP10_COMP *cpi);
507 void vp10_change_config(VP10_COMP *cpi, const VP10EncoderConfig *oxcf);
509 // receive a frames worth of data. caller can assume that a copy of this
510 // frame is made and not just a copy of the pointer..
511 int vp10_receive_raw_frame(VP10_COMP *cpi, unsigned int frame_flags,
512 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
513 int64_t end_time_stamp);
515 int vp10_get_compressed_data(VP10_COMP *cpi, unsigned int *frame_flags,
516 size_t *size, uint8_t *dest,
517 int64_t *time_stamp, int64_t *time_end, int flush);
519 int vp10_get_preview_raw_frame(VP10_COMP *cpi, YV12_BUFFER_CONFIG *dest,
520 vp10_ppflags_t *flags);
522 int vp10_use_as_reference(VP10_COMP *cpi, int ref_frame_flags);
524 void vp10_update_reference(VP10_COMP *cpi, int ref_frame_flags);
526 int vp10_copy_reference_enc(VP10_COMP *cpi, VP9_REFFRAME ref_frame_flag,
527 YV12_BUFFER_CONFIG *sd);
529 int vp10_set_reference_enc(VP10_COMP *cpi, VP9_REFFRAME ref_frame_flag,
530 YV12_BUFFER_CONFIG *sd);
532 int vp10_update_entropy(VP10_COMP *cpi, int update);
534 int vp10_set_active_map(VP10_COMP *cpi, unsigned char *map, int rows, int cols);
536 int vp10_get_active_map(VP10_COMP *cpi, unsigned char *map, int rows, int cols);
538 int vp10_set_internal_size(VP10_COMP *cpi,
539 VPX_SCALING horiz_mode, VPX_SCALING vert_mode);
541 int vp10_set_size_literal(VP10_COMP *cpi, unsigned int width,
542 unsigned int height);
544 int vp10_get_quantizer(struct VP10_COMP *cpi);
546 static INLINE int frame_is_kf_gf_arf(const VP10_COMP *cpi) {
547 return frame_is_intra_only(&cpi->common) ||
548 cpi->refresh_alt_ref_frame ||
549 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref);
552 static INLINE int get_ref_frame_map_idx(const VP10_COMP *cpi,
553 MV_REFERENCE_FRAME ref_frame) {
554 if (ref_frame == LAST_FRAME) {
555 return cpi->lst_fb_idx;
556 } else if (ref_frame == GOLDEN_FRAME) {
557 return cpi->gld_fb_idx;
559 return cpi->alt_fb_idx;
563 static INLINE int get_ref_frame_buf_idx(const VP10_COMP *const cpi,
565 const VP10_COMMON *const cm = &cpi->common;
566 const int map_idx = get_ref_frame_map_idx(cpi, ref_frame);
567 return (map_idx != INVALID_IDX) ? cm->ref_frame_map[map_idx] : INVALID_IDX;
570 static INLINE YV12_BUFFER_CONFIG *get_ref_frame_buffer(
571 VP10_COMP *cpi, MV_REFERENCE_FRAME ref_frame) {
572 VP10_COMMON *const cm = &cpi->common;
573 const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
575 buf_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[buf_idx].buf : NULL;
578 static INLINE int get_token_alloc(int mb_rows, int mb_cols) {
579 // TODO(JBB): double check we can't exceed this token count if we have a
580 // 32x32 transform crossing a boundary at a multiple of 16.
581 // mb_rows, cols are in units of 16 pixels. We assume 3 planes all at full
582 // resolution. We assume up to 1 token per pixel, and then allow
583 // a head room of 1 EOSB token per 8x8 block per plane.
584 return mb_rows * mb_cols * (16 * 16 + 4) * 3;
587 // Get the allocated token size for a tile. It does the same calculation as in
588 // the frame token allocation.
589 static INLINE int allocated_tokens(TileInfo tile) {
590 int tile_mb_rows = (tile.mi_row_end - tile.mi_row_start + 1) >> 1;
591 int tile_mb_cols = (tile.mi_col_end - tile.mi_col_start + 1) >> 1;
593 return get_token_alloc(tile_mb_rows, tile_mb_cols);
596 int64_t vp10_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b);
597 #if CONFIG_VP9_HIGHBITDEPTH
598 int64_t vp10_highbd_get_y_sse(const YV12_BUFFER_CONFIG *a,
599 const YV12_BUFFER_CONFIG *b);
600 #endif // CONFIG_VP9_HIGHBITDEPTH
602 void vp10_alloc_compressor_data(VP10_COMP *cpi);
604 void vp10_scale_references(VP10_COMP *cpi);
606 void vp10_update_reference_frames(VP10_COMP *cpi);
608 void vp10_set_high_precision_mv(VP10_COMP *cpi, int allow_high_precision_mv);
610 YV12_BUFFER_CONFIG *vp10_scale_if_required_fast(VP10_COMMON *cm,
611 YV12_BUFFER_CONFIG *unscaled,
612 YV12_BUFFER_CONFIG *scaled);
614 YV12_BUFFER_CONFIG *vp10_scale_if_required(VP10_COMMON *cm,
615 YV12_BUFFER_CONFIG *unscaled,
616 YV12_BUFFER_CONFIG *scaled);
618 void vp10_apply_encoding_flags(VP10_COMP *cpi, vpx_enc_frame_flags_t flags);
620 static INLINE int is_altref_enabled(const VP10_COMP *const cpi) {
621 return cpi->oxcf.mode != REALTIME && cpi->oxcf.lag_in_frames > 0 &&
622 cpi->oxcf.enable_auto_arf;
625 static INLINE void set_ref_ptrs(VP10_COMMON *cm, MACROBLOCKD *xd,
626 MV_REFERENCE_FRAME ref0,
627 MV_REFERENCE_FRAME ref1) {
628 xd->block_refs[0] = &cm->frame_refs[ref0 >= LAST_FRAME ? ref0 - LAST_FRAME
630 xd->block_refs[1] = &cm->frame_refs[ref1 >= LAST_FRAME ? ref1 - LAST_FRAME
634 static INLINE int get_chessboard_index(const int frame_index) {
635 return frame_index & 0x1;
638 static INLINE int *cond_cost_list(const struct VP10_COMP *cpi, int *cost_list) {
639 return cpi->sf.mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL;
642 void vp10_new_framerate(VP10_COMP *cpi, double framerate);
644 #define LAYER_IDS_TO_IDX(sl, tl, num_tl) ((sl) * (num_tl) + (tl))
650 #endif // VP10_ENCODER_ENCODER_H_