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 VP9_ENCODER_VP9_ENCODER_H_
12#define VP9_ENCODER_VP9_ENCODER_H_
13
14#include <stdio.h>
15
16#include "./vpx_config.h"
17#include "vpx_ports/mem.h"
18#include "vpx/internal/vpx_codec_internal.h"
19#include "vpx/vp8cx.h"
20
21#include "vp9/common/vp9_ppflags.h"
22#include "vp9/common/vp9_entropy.h"
23#include "vp9/common/vp9_entropymode.h"
24#include "vp9/common/vp9_onyxc_int.h"
25
26#include "vp9/encoder/vp9_aq_cyclicrefresh.h"
27#include "vp9/encoder/vp9_context_tree.h"
28#include "vp9/encoder/vp9_encodemb.h"
29#include "vp9/encoder/vp9_firstpass.h"
30#include "vp9/encoder/vp9_lookahead.h"
31#include "vp9/encoder/vp9_mbgraph.h"
32#include "vp9/encoder/vp9_mcomp.h"
33#include "vp9/encoder/vp9_quantize.h"
34#include "vp9/encoder/vp9_ratectrl.h"
35#include "vp9/encoder/vp9_rd.h"
36#include "vp9/encoder/vp9_speed_features.h"
37#include "vp9/encoder/vp9_svc_layercontext.h"
38#include "vp9/encoder/vp9_tokenize.h"
39#include "vp9/encoder/vp9_variance.h"
40#if CONFIG_VP9_TEMPORAL_DENOISING
41#include "vp9/encoder/vp9_denoiser.h"
42#endif
43
44#ifdef __cplusplus
45extern "C" {
46#endif
47
48#define DEFAULT_GF_INTERVAL         10
49
50typedef struct {
51  int nmvjointcost[MV_JOINTS];
52  int nmvcosts[2][MV_VALS];
53  int nmvcosts_hp[2][MV_VALS];
54
55  vp9_prob segment_pred_probs[PREDICTION_PROBS];
56
57  unsigned char *last_frame_seg_map_copy;
58
59  // 0 = Intra, Last, GF, ARF
60  signed char last_ref_lf_deltas[MAX_REF_LF_DELTAS];
61  // 0 = ZERO_MV, MV
62  signed char last_mode_lf_deltas[MAX_MODE_LF_DELTAS];
63
64  FRAME_CONTEXT fc;
65} CODING_CONTEXT;
66
67
68typedef enum {
69  // encode_breakout is disabled.
70  ENCODE_BREAKOUT_DISABLED = 0,
71  // encode_breakout is enabled.
72  ENCODE_BREAKOUT_ENABLED = 1,
73  // encode_breakout is enabled with small max_thresh limit.
74  ENCODE_BREAKOUT_LIMITED = 2
75} ENCODE_BREAKOUT_TYPE;
76
77typedef enum {
78  NORMAL      = 0,
79  FOURFIVE    = 1,
80  THREEFIVE   = 2,
81  ONETWO      = 3
82} VPX_SCALING;
83
84typedef enum {
85  // Good Quality Fast Encoding. The encoder balances quality with the amount of
86  // time it takes to encode the output. Speed setting controls how fast.
87  GOOD,
88
89  // The encoder places priority on the quality of the output over encoding
90  // speed. The output is compressed at the highest possible quality. This
91  // option takes the longest amount of time to encode. Speed setting ignored.
92  BEST,
93
94  // Realtime/Live Encoding. This mode is optimized for realtime encoding (for
95  // example, capturing a television signal or feed from a live camera). Speed
96  // setting controls how fast.
97  REALTIME
98} MODE;
99
100typedef enum {
101  FRAMEFLAGS_KEY    = 1 << 0,
102  FRAMEFLAGS_GOLDEN = 1 << 1,
103  FRAMEFLAGS_ALTREF = 1 << 2,
104} FRAMETYPE_FLAGS;
105
106typedef enum {
107  NO_AQ = 0,
108  VARIANCE_AQ = 1,
109  COMPLEXITY_AQ = 2,
110  CYCLIC_REFRESH_AQ = 3,
111  AQ_MODE_COUNT  // This should always be the last member of the enum
112} AQ_MODE;
113
114
115typedef struct VP9EncoderConfig {
116  BITSTREAM_PROFILE profile;
117  vpx_bit_depth_t bit_depth;     // Codec bit-depth.
118  int width;  // width of data passed to the compressor
119  int height;  // height of data passed to the compressor
120  unsigned int input_bit_depth;  // Input bit depth.
121  double init_framerate;  // set to passed in framerate
122  int64_t target_bandwidth;  // bandwidth to be used in kilobits per second
123
124  int noise_sensitivity;  // pre processing blur: recommendation 0
125  int sharpness;  // sharpening output: recommendation 0:
126  int speed;
127  unsigned int rc_max_intra_bitrate_pct;
128
129  MODE mode;
130  int pass;
131
132  // Key Framing Operations
133  int auto_key;  // autodetect cut scenes and set the keyframes
134  int key_freq;  // maximum distance to key frame.
135
136  int lag_in_frames;  // how many frames lag before we start encoding
137
138  // ----------------------------------------------------------------
139  // DATARATE CONTROL OPTIONS
140
141  // vbr, cbr, constrained quality or constant quality
142  enum vpx_rc_mode rc_mode;
143
144  // buffer targeting aggressiveness
145  int under_shoot_pct;
146  int over_shoot_pct;
147
148  // buffering parameters
149  int64_t starting_buffer_level_ms;
150  int64_t optimal_buffer_level_ms;
151  int64_t maximum_buffer_size_ms;
152
153  // Frame drop threshold.
154  int drop_frames_water_mark;
155
156  // controlling quality
157  int fixed_q;
158  int worst_allowed_q;
159  int best_allowed_q;
160  int cq_level;
161  AQ_MODE aq_mode;  // Adaptive Quantization mode
162
163  // Internal frame size scaling.
164  int allow_spatial_resampling;
165  int scaled_frame_width;
166  int scaled_frame_height;
167
168  // Enable feature to reduce the frame quantization every x frames.
169  int frame_periodic_boost;
170
171  // two pass datarate control
172  int two_pass_vbrbias;        // two pass datarate control tweaks
173  int two_pass_vbrmin_section;
174  int two_pass_vbrmax_section;
175  // END DATARATE CONTROL OPTIONS
176  // ----------------------------------------------------------------
177
178  // Spatial and temporal scalability.
179  int ss_number_layers;  // Number of spatial layers.
180  int ts_number_layers;  // Number of temporal layers.
181  // Bitrate allocation for spatial layers.
182  int ss_target_bitrate[VPX_SS_MAX_LAYERS];
183  int ss_play_alternate[VPX_SS_MAX_LAYERS];
184  // Bitrate allocation (CBR mode) and framerate factor, for temporal layers.
185  int ts_target_bitrate[VPX_TS_MAX_LAYERS];
186  int ts_rate_decimator[VPX_TS_MAX_LAYERS];
187
188  // these parameters aren't to be used in final build don't use!!!
189  int play_alternate;
190
191  int encode_breakout;  // early breakout : for video conf recommend 800
192
193  /* Bitfield defining the error resiliency features to enable.
194   * Can provide decodable frames after losses in previous
195   * frames and decodable partitions after losses in the same frame.
196   */
197  unsigned int error_resilient_mode;
198
199  /* Bitfield defining the parallel decoding mode where the
200   * decoding in successive frames may be conducted in parallel
201   * just by decoding the frame headers.
202   */
203  unsigned int frame_parallel_decoding_mode;
204
205  int arnr_max_frames;
206  int arnr_strength;
207
208  int tile_columns;
209  int tile_rows;
210
211  vpx_fixed_buf_t two_pass_stats_in;
212  struct vpx_codec_pkt_list *output_pkt_list;
213
214#if CONFIG_FP_MB_STATS
215  vpx_fixed_buf_t firstpass_mb_stats_in;
216#endif
217
218  vp8e_tuning tuning;
219  vp9e_tune_content content;
220#if CONFIG_VP9_HIGHBITDEPTH
221  int use_highbitdepth;
222#endif
223} VP9EncoderConfig;
224
225static INLINE int is_lossless_requested(const VP9EncoderConfig *cfg) {
226  return cfg->best_allowed_q == 0 && cfg->worst_allowed_q == 0;
227}
228
229typedef struct VP9_COMP {
230  QUANTS quants;
231  MACROBLOCK mb;
232  VP9_COMMON common;
233  VP9EncoderConfig oxcf;
234  struct lookahead_ctx    *lookahead;
235  struct lookahead_entry  *alt_ref_source;
236
237  YV12_BUFFER_CONFIG *Source;
238  YV12_BUFFER_CONFIG *Last_Source;  // NULL for first frame and alt_ref frames
239  YV12_BUFFER_CONFIG *un_scaled_source;
240  YV12_BUFFER_CONFIG scaled_source;
241  YV12_BUFFER_CONFIG *unscaled_last_source;
242  YV12_BUFFER_CONFIG scaled_last_source;
243
244  int skippable_frame;
245
246  int scaled_ref_idx[3];
247  int lst_fb_idx;
248  int gld_fb_idx;
249  int alt_fb_idx;
250
251  int refresh_last_frame;
252  int refresh_golden_frame;
253  int refresh_alt_ref_frame;
254
255  int ext_refresh_frame_flags_pending;
256  int ext_refresh_last_frame;
257  int ext_refresh_golden_frame;
258  int ext_refresh_alt_ref_frame;
259
260  int ext_refresh_frame_context_pending;
261  int ext_refresh_frame_context;
262
263  YV12_BUFFER_CONFIG last_frame_uf;
264
265  TOKENEXTRA *tok;
266  unsigned int tok_count[4][1 << 6];
267
268  // Ambient reconstruction err target for force key frames
269  int ambient_err;
270
271  RD_OPT rd;
272
273  CODING_CONTEXT coding_context;
274
275  int *nmvcosts[2];
276  int *nmvcosts_hp[2];
277  int *nmvsadcosts[2];
278  int *nmvsadcosts_hp[2];
279
280  int zbin_mode_boost;
281  int zbin_mode_boost_enabled;
282
283  int64_t last_time_stamp_seen;
284  int64_t last_end_time_stamp_seen;
285  int64_t first_time_stamp_ever;
286
287  RATE_CONTROL rc;
288  double framerate;
289
290  vp9_coeff_count coef_counts[TX_SIZES][PLANE_TYPES];
291  int interp_filter_selected[MAX_REF_FRAMES][SWITCHABLE];
292
293  struct vpx_codec_pkt_list  *output_pkt_list;
294
295  MBGRAPH_FRAME_STATS mbgraph_stats[MAX_LAG_BUFFERS];
296  int mbgraph_n_frames;             // number of frames filled in the above
297  int static_mb_pct;                // % forced skip mbs by segmentation
298  int ref_frame_flags;
299
300  SPEED_FEATURES sf;
301
302  unsigned int max_mv_magnitude;
303  int mv_step_param;
304
305  // Default value is 1. From first pass stats, encode_breakout may be disabled.
306  ENCODE_BREAKOUT_TYPE allow_encode_breakout;
307
308  // Get threshold from external input. A suggested threshold is 800 for HD
309  // clips, and 300 for < HD clips.
310  int encode_breakout;
311
312  unsigned char *segmentation_map;
313
314  // segment threashold for encode breakout
315  int  segment_encode_breakout[MAX_SEGMENTS];
316
317  unsigned char *complexity_map;
318
319  CYCLIC_REFRESH *cyclic_refresh;
320
321  fractional_mv_step_fp *find_fractional_mv_step;
322  vp9_full_search_fn_t full_search_sad;
323  vp9_refining_search_fn_t refining_search_sad;
324  vp9_diamond_search_fn_t diamond_search_sad;
325  vp9_variance_fn_ptr_t fn_ptr[BLOCK_SIZES];
326  uint64_t time_receive_data;
327  uint64_t time_compress_data;
328  uint64_t time_pick_lpf;
329  uint64_t time_encode_sb_row;
330
331#if CONFIG_FP_MB_STATS
332  int use_fp_mb_stats;
333#endif
334
335  TWO_PASS twopass;
336
337  YV12_BUFFER_CONFIG alt_ref_buffer;
338
339
340#if CONFIG_INTERNAL_STATS
341  unsigned int mode_chosen_counts[MAX_MODES];
342
343  int    count;
344  double total_y;
345  double total_u;
346  double total_v;
347  double total;
348  uint64_t total_sq_error;
349  uint64_t total_samples;
350
351  double totalp_y;
352  double totalp_u;
353  double totalp_v;
354  double totalp;
355  uint64_t totalp_sq_error;
356  uint64_t totalp_samples;
357
358  int    bytes;
359  double summed_quality;
360  double summed_weights;
361  double summedp_quality;
362  double summedp_weights;
363  unsigned int tot_recode_hits;
364
365
366  double total_ssimg_y;
367  double total_ssimg_u;
368  double total_ssimg_v;
369  double total_ssimg_all;
370
371  int b_calculate_ssimg;
372#endif
373  int b_calculate_psnr;
374
375  int droppable;
376
377  int initial_width;
378  int initial_height;
379
380  int use_svc;
381
382  SVC svc;
383
384  // Store frame variance info in SOURCE_VAR_BASED_PARTITION search type.
385  diff *source_diff_var;
386  // The threshold used in SOURCE_VAR_BASED_PARTITION search type.
387  unsigned int source_var_thresh;
388  int frames_till_next_var_check;
389
390  int frame_flags;
391
392  search_site_config ss_cfg;
393
394  int mbmode_cost[INTRA_MODES];
395  unsigned int inter_mode_cost[INTER_MODE_CONTEXTS][INTER_MODES];
396  int intra_uv_mode_cost[FRAME_TYPES][INTRA_MODES];
397  int y_mode_costs[INTRA_MODES][INTRA_MODES][INTRA_MODES];
398  int switchable_interp_costs[SWITCHABLE_FILTER_CONTEXTS][SWITCHABLE_FILTERS];
399
400  PICK_MODE_CONTEXT *leaf_tree;
401  PC_TREE *pc_tree;
402  PC_TREE *pc_root;
403  int partition_cost[PARTITION_CONTEXTS][PARTITION_TYPES];
404
405  int multi_arf_allowed;
406  int multi_arf_enabled;
407  int multi_arf_last_grp_enabled;
408
409#if CONFIG_VP9_TEMPORAL_DENOISING
410  VP9_DENOISER denoiser;
411#endif
412} VP9_COMP;
413
414void vp9_initialize_enc();
415
416struct VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf);
417void vp9_remove_compressor(VP9_COMP *cpi);
418
419void vp9_change_config(VP9_COMP *cpi, const VP9EncoderConfig *oxcf);
420
421  // receive a frames worth of data. caller can assume that a copy of this
422  // frame is made and not just a copy of the pointer..
423int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
424                          YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
425                          int64_t end_time_stamp);
426
427int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
428                            size_t *size, uint8_t *dest,
429                            int64_t *time_stamp, int64_t *time_end, int flush);
430
431int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
432                              vp9_ppflags_t *flags);
433
434int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags);
435
436void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags);
437
438int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
439                           YV12_BUFFER_CONFIG *sd);
440
441int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
442                          YV12_BUFFER_CONFIG *sd);
443
444int vp9_update_entropy(VP9_COMP *cpi, int update);
445
446int vp9_set_active_map(VP9_COMP *cpi, unsigned char *map, int rows, int cols);
447
448int vp9_set_internal_size(VP9_COMP *cpi,
449                          VPX_SCALING horiz_mode, VPX_SCALING vert_mode);
450
451int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
452                         unsigned int height);
453
454void vp9_set_svc(VP9_COMP *cpi, int use_svc);
455
456int vp9_get_quantizer(struct VP9_COMP *cpi);
457
458static INLINE int get_ref_frame_idx(const VP9_COMP *cpi,
459                                    MV_REFERENCE_FRAME ref_frame) {
460  if (ref_frame == LAST_FRAME) {
461    return cpi->lst_fb_idx;
462  } else if (ref_frame == GOLDEN_FRAME) {
463    return cpi->gld_fb_idx;
464  } else {
465    return cpi->alt_fb_idx;
466  }
467}
468
469static INLINE YV12_BUFFER_CONFIG *get_ref_frame_buffer(
470    VP9_COMP *cpi, MV_REFERENCE_FRAME ref_frame) {
471  VP9_COMMON * const cm = &cpi->common;
472  return &cm->frame_bufs[cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)]]
473      .buf;
474}
475
476static INLINE int get_token_alloc(int mb_rows, int mb_cols) {
477  // TODO(JBB): double check we can't exceed this token count if we have a
478  // 32x32 transform crossing a boundary at a multiple of 16.
479  // mb_rows, cols are in units of 16 pixels. We assume 3 planes all at full
480  // resolution. We assume up to 1 token per pixel, and then allow
481  // a head room of 4.
482  return mb_rows * mb_cols * (16 * 16 * 3 + 4);
483}
484
485int vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b);
486
487void vp9_alloc_compressor_data(VP9_COMP *cpi);
488
489void vp9_scale_references(VP9_COMP *cpi);
490
491void vp9_update_reference_frames(VP9_COMP *cpi);
492
493void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv);
494
495YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
496                                          YV12_BUFFER_CONFIG *unscaled,
497                                          YV12_BUFFER_CONFIG *scaled);
498
499void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags);
500
501static INLINE int is_two_pass_svc(const struct VP9_COMP *const cpi) {
502  return cpi->use_svc &&
503         (cpi->svc.number_temporal_layers > 1 ||
504          cpi->svc.number_spatial_layers > 1) &&
505         (cpi->oxcf.pass == 1 || cpi->oxcf.pass == 2);
506}
507
508static INLINE int is_altref_enabled(const VP9_COMP *const cpi) {
509  return cpi->oxcf.mode != REALTIME && cpi->oxcf.lag_in_frames > 0 &&
510         (cpi->oxcf.play_alternate &&
511          (!is_two_pass_svc(cpi) ||
512           cpi->oxcf.ss_play_alternate[cpi->svc.spatial_layer_id]));
513}
514
515static INLINE void set_ref_ptrs(VP9_COMMON *cm, MACROBLOCKD *xd,
516                                MV_REFERENCE_FRAME ref0,
517                                MV_REFERENCE_FRAME ref1) {
518  xd->block_refs[0] = &cm->frame_refs[ref0 >= LAST_FRAME ? ref0 - LAST_FRAME
519                                                         : 0];
520  xd->block_refs[1] = &cm->frame_refs[ref1 >= LAST_FRAME ? ref1 - LAST_FRAME
521                                                         : 0];
522}
523
524static INLINE int get_chessboard_index(const int frame_index) {
525  return frame_index & 0x1;
526}
527
528static INLINE int *cond_sad_list(const struct VP9_COMP *cpi, int *sad_list) {
529  return cpi->sf.mv.subpel_search_method != SUBPEL_TREE ? sad_list : NULL;
530}
531
532#ifdef __cplusplus
533}  // extern "C"
534#endif
535
536#endif  // VP9_ENCODER_VP9_ENCODER_H_
537