vp9_encoder.h 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  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. #ifndef VPX_VP9_ENCODER_VP9_ENCODER_H_
  11. #define VPX_VP9_ENCODER_VP9_ENCODER_H_
  12. #include <stdio.h>
  13. #include "./vpx_config.h"
  14. #include "vpx/internal/vpx_codec_internal.h"
  15. #include "vpx/vp8cx.h"
  16. #if CONFIG_INTERNAL_STATS
  17. #include "vpx_dsp/ssim.h"
  18. #endif
  19. #include "vpx_dsp/variance.h"
  20. #include "vpx_ports/system_state.h"
  21. #include "vpx_util/vpx_thread.h"
  22. #include "vp9/common/vp9_alloccommon.h"
  23. #include "vp9/common/vp9_ppflags.h"
  24. #include "vp9/common/vp9_entropymode.h"
  25. #include "vp9/common/vp9_thread_common.h"
  26. #include "vp9/common/vp9_onyxc_int.h"
  27. #if !CONFIG_REALTIME_ONLY
  28. #include "vp9/encoder/vp9_alt_ref_aq.h"
  29. #endif
  30. #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
  31. #include "vp9/encoder/vp9_context_tree.h"
  32. #include "vp9/encoder/vp9_encodemb.h"
  33. #include "vp9/encoder/vp9_ethread.h"
  34. #include "vp9/encoder/vp9_firstpass.h"
  35. #include "vp9/encoder/vp9_job_queue.h"
  36. #include "vp9/encoder/vp9_lookahead.h"
  37. #include "vp9/encoder/vp9_mbgraph.h"
  38. #include "vp9/encoder/vp9_mcomp.h"
  39. #include "vp9/encoder/vp9_noise_estimate.h"
  40. #include "vp9/encoder/vp9_quantize.h"
  41. #include "vp9/encoder/vp9_ratectrl.h"
  42. #include "vp9/encoder/vp9_rd.h"
  43. #include "vp9/encoder/vp9_speed_features.h"
  44. #include "vp9/encoder/vp9_svc_layercontext.h"
  45. #include "vp9/encoder/vp9_tokenize.h"
  46. #if CONFIG_VP9_TEMPORAL_DENOISING
  47. #include "vp9/encoder/vp9_denoiser.h"
  48. #endif
  49. #ifdef __cplusplus
  50. extern "C" {
  51. #endif
  52. // vp9 uses 10,000,000 ticks/second as time stamp
  53. #define TICKS_PER_SEC 10000000
  54. typedef struct {
  55. int nmvjointcost[MV_JOINTS];
  56. int nmvcosts[2][MV_VALS];
  57. int nmvcosts_hp[2][MV_VALS];
  58. vpx_prob segment_pred_probs[PREDICTION_PROBS];
  59. unsigned char *last_frame_seg_map_copy;
  60. // 0 = Intra, Last, GF, ARF
  61. signed char last_ref_lf_deltas[MAX_REF_LF_DELTAS];
  62. // 0 = ZERO_MV, MV
  63. signed char last_mode_lf_deltas[MAX_MODE_LF_DELTAS];
  64. FRAME_CONTEXT fc;
  65. } CODING_CONTEXT;
  66. typedef enum {
  67. // encode_breakout is disabled.
  68. ENCODE_BREAKOUT_DISABLED = 0,
  69. // encode_breakout is enabled.
  70. ENCODE_BREAKOUT_ENABLED = 1,
  71. // encode_breakout is enabled with small max_thresh limit.
  72. ENCODE_BREAKOUT_LIMITED = 2
  73. } ENCODE_BREAKOUT_TYPE;
  74. typedef enum {
  75. NORMAL = 0,
  76. FOURFIVE = 1,
  77. THREEFIVE = 2,
  78. ONETWO = 3
  79. } VPX_SCALING;
  80. typedef enum {
  81. // Good Quality Fast Encoding. The encoder balances quality with the amount of
  82. // time it takes to encode the output. Speed setting controls how fast.
  83. GOOD,
  84. // The encoder places priority on the quality of the output over encoding
  85. // speed. The output is compressed at the highest possible quality. This
  86. // option takes the longest amount of time to encode. Speed setting ignored.
  87. BEST,
  88. // Realtime/Live Encoding. This mode is optimized for realtime encoding (for
  89. // example, capturing a television signal or feed from a live camera). Speed
  90. // setting controls how fast.
  91. REALTIME
  92. } MODE;
  93. typedef enum {
  94. FRAMEFLAGS_KEY = 1 << 0,
  95. FRAMEFLAGS_GOLDEN = 1 << 1,
  96. FRAMEFLAGS_ALTREF = 1 << 2,
  97. } FRAMETYPE_FLAGS;
  98. typedef enum {
  99. NO_AQ = 0,
  100. VARIANCE_AQ = 1,
  101. COMPLEXITY_AQ = 2,
  102. CYCLIC_REFRESH_AQ = 3,
  103. EQUATOR360_AQ = 4,
  104. PERCEPTUAL_AQ = 5,
  105. PSNR_AQ = 6,
  106. // AQ based on lookahead temporal
  107. // variance (only valid for altref frames)
  108. LOOKAHEAD_AQ = 7,
  109. AQ_MODE_COUNT // This should always be the last member of the enum
  110. } AQ_MODE;
  111. typedef enum {
  112. RESIZE_NONE = 0, // No frame resizing allowed (except for SVC).
  113. RESIZE_FIXED = 1, // All frames are coded at the specified dimension.
  114. RESIZE_DYNAMIC = 2 // Coded size of each frame is determined by the codec.
  115. } RESIZE_TYPE;
  116. typedef enum {
  117. kInvalid = 0,
  118. kLowSadLowSumdiff = 1,
  119. kLowSadHighSumdiff = 2,
  120. kHighSadLowSumdiff = 3,
  121. kHighSadHighSumdiff = 4,
  122. kLowVarHighSumdiff = 5,
  123. kVeryHighSad = 6,
  124. } CONTENT_STATE_SB;
  125. typedef struct VP9EncoderConfig {
  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 bits per second
  133. int noise_sensitivity; // pre processing blur: recommendation 0
  134. int sharpness; // sharpening output: recommendation 0:
  135. int speed;
  136. // maximum allowed bitrate for any intra frame in % of bitrate target.
  137. unsigned int rc_max_intra_bitrate_pct;
  138. // maximum allowed bitrate for any inter frame in % of bitrate target.
  139. unsigned int rc_max_inter_bitrate_pct;
  140. // percent of rate boost for golden frame in CBR mode.
  141. unsigned int gf_cbr_boost_pct;
  142. MODE mode;
  143. int pass;
  144. // Key Framing Operations
  145. int auto_key; // autodetect cut scenes and set the keyframes
  146. int key_freq; // maximum distance to key frame.
  147. int lag_in_frames; // how many frames lag before we start encoding
  148. // ----------------------------------------------------------------
  149. // DATARATE CONTROL OPTIONS
  150. // vbr, cbr, constrained quality or constant quality
  151. enum vpx_rc_mode rc_mode;
  152. // buffer targeting aggressiveness
  153. int under_shoot_pct;
  154. int over_shoot_pct;
  155. // buffering parameters
  156. int64_t starting_buffer_level_ms;
  157. int64_t optimal_buffer_level_ms;
  158. int64_t maximum_buffer_size_ms;
  159. // Frame drop threshold.
  160. int drop_frames_water_mark;
  161. // controlling quality
  162. int fixed_q;
  163. int worst_allowed_q;
  164. int best_allowed_q;
  165. int cq_level;
  166. AQ_MODE aq_mode; // Adaptive Quantization mode
  167. // Special handling of Adaptive Quantization for AltRef frames
  168. int alt_ref_aq;
  169. // Internal frame size scaling.
  170. RESIZE_TYPE resize_mode;
  171. int scaled_frame_width;
  172. int scaled_frame_height;
  173. // Enable feature to reduce the frame quantization every x frames.
  174. int frame_periodic_boost;
  175. // two pass datarate control
  176. int two_pass_vbrbias; // two pass datarate control tweaks
  177. int two_pass_vbrmin_section;
  178. int two_pass_vbrmax_section;
  179. int vbr_corpus_complexity; // 0 indicates corpus vbr disabled
  180. // END DATARATE CONTROL OPTIONS
  181. // ----------------------------------------------------------------
  182. // Spatial and temporal scalability.
  183. int ss_number_layers; // Number of spatial layers.
  184. int ts_number_layers; // Number of temporal layers.
  185. // Bitrate allocation for spatial layers.
  186. int layer_target_bitrate[VPX_MAX_LAYERS];
  187. int ss_target_bitrate[VPX_SS_MAX_LAYERS];
  188. int ss_enable_auto_arf[VPX_SS_MAX_LAYERS];
  189. // Bitrate allocation (CBR mode) and framerate factor, for temporal layers.
  190. int ts_rate_decimator[VPX_TS_MAX_LAYERS];
  191. int enable_auto_arf;
  192. int encode_breakout; // early breakout : for video conf recommend 800
  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. /* Bitfield defining the parallel decoding mode where the
  199. * decoding in successive frames may be conducted in parallel
  200. * just by decoding the frame headers.
  201. */
  202. unsigned int frame_parallel_decoding_mode;
  203. int arnr_max_frames;
  204. int arnr_strength;
  205. int min_gf_interval;
  206. int max_gf_interval;
  207. int tile_columns;
  208. int tile_rows;
  209. int enable_tpl_model;
  210. int max_threads;
  211. unsigned int target_level;
  212. vpx_fixed_buf_t two_pass_stats_in;
  213. struct vpx_codec_pkt_list *output_pkt_list;
  214. #if CONFIG_FP_MB_STATS
  215. vpx_fixed_buf_t firstpass_mb_stats_in;
  216. #endif
  217. vp8e_tuning tuning;
  218. vp9e_tune_content content;
  219. #if CONFIG_VP9_HIGHBITDEPTH
  220. int use_highbitdepth;
  221. #endif
  222. vpx_color_space_t color_space;
  223. vpx_color_range_t color_range;
  224. int render_width;
  225. int render_height;
  226. VP9E_TEMPORAL_LAYERING_MODE temporal_layering_mode;
  227. int row_mt;
  228. unsigned int motion_vector_unit_test;
  229. } VP9EncoderConfig;
  230. static INLINE int is_lossless_requested(const VP9EncoderConfig *cfg) {
  231. return cfg->best_allowed_q == 0 && cfg->worst_allowed_q == 0;
  232. }
  233. typedef struct TplDepStats {
  234. int64_t intra_cost;
  235. int64_t inter_cost;
  236. int64_t mc_flow;
  237. int64_t mc_dep_cost;
  238. int64_t mc_ref_cost;
  239. int ref_frame_index;
  240. int_mv mv;
  241. #if CONFIG_NON_GREEDY_MV
  242. int ready[3];
  243. int64_t sse_arr[3];
  244. double feature_score;
  245. #endif
  246. } TplDepStats;
  247. #if CONFIG_NON_GREEDY_MV
  248. #define SQUARE_BLOCK_SIZES 4
  249. #define ZERO_MV_MODE 0
  250. #define NEW_MV_MODE 1
  251. #define NEAREST_MV_MODE 2
  252. #define NEAR_MV_MODE 3
  253. #define MAX_MV_MODE 4
  254. #endif
  255. typedef struct TplDepFrame {
  256. uint8_t is_valid;
  257. TplDepStats *tpl_stats_ptr;
  258. int stride;
  259. int width;
  260. int height;
  261. int mi_rows;
  262. int mi_cols;
  263. int base_qindex;
  264. #if CONFIG_NON_GREEDY_MV
  265. int lambda;
  266. int_mv *pyramid_mv_arr[3][SQUARE_BLOCK_SIZES];
  267. int *mv_mode_arr[3];
  268. double *rd_diff_arr[3];
  269. #endif
  270. } TplDepFrame;
  271. #if CONFIG_NON_GREEDY_MV
  272. static INLINE int get_square_block_idx(BLOCK_SIZE bsize) {
  273. if (bsize == BLOCK_4X4) {
  274. return 0;
  275. }
  276. if (bsize == BLOCK_8X8) {
  277. return 1;
  278. }
  279. if (bsize == BLOCK_16X16) {
  280. return 2;
  281. }
  282. if (bsize == BLOCK_32X32) {
  283. return 3;
  284. }
  285. assert(0 && "ERROR: non-square block size");
  286. return -1;
  287. }
  288. static INLINE BLOCK_SIZE square_block_idx_to_bsize(int square_block_idx) {
  289. if (square_block_idx == 0) {
  290. return BLOCK_4X4;
  291. }
  292. if (square_block_idx == 1) {
  293. return BLOCK_8X8;
  294. }
  295. if (square_block_idx == 2) {
  296. return BLOCK_16X16;
  297. }
  298. if (square_block_idx == 3) {
  299. return BLOCK_32X32;
  300. }
  301. assert(0 && "ERROR: invalid square_block_idx");
  302. return BLOCK_INVALID;
  303. }
  304. static INLINE int_mv *get_pyramid_mv(const TplDepFrame *tpl_frame, int rf_idx,
  305. BLOCK_SIZE bsize, int mi_row, int mi_col) {
  306. return &tpl_frame->pyramid_mv_arr[rf_idx][get_square_block_idx(bsize)]
  307. [mi_row * tpl_frame->stride + mi_col];
  308. }
  309. #endif
  310. #define TPL_DEP_COST_SCALE_LOG2 4
  311. // TODO(jingning) All spatially adaptive variables should go to TileDataEnc.
  312. typedef struct TileDataEnc {
  313. TileInfo tile_info;
  314. int thresh_freq_fact[BLOCK_SIZES][MAX_MODES];
  315. #if CONFIG_CONSISTENT_RECODE
  316. int thresh_freq_fact_prev[BLOCK_SIZES][MAX_MODES];
  317. #endif
  318. int8_t mode_map[BLOCK_SIZES][MAX_MODES];
  319. FIRSTPASS_DATA fp_data;
  320. VP9RowMTSync row_mt_sync;
  321. // Used for adaptive_rd_thresh with row multithreading
  322. int *row_base_thresh_freq_fact;
  323. } TileDataEnc;
  324. typedef struct RowMTInfo {
  325. JobQueueHandle job_queue_hdl;
  326. #if CONFIG_MULTITHREAD
  327. pthread_mutex_t job_mutex;
  328. #endif
  329. } RowMTInfo;
  330. typedef struct {
  331. TOKENEXTRA *start;
  332. TOKENEXTRA *stop;
  333. unsigned int count;
  334. } TOKENLIST;
  335. typedef struct MultiThreadHandle {
  336. int allocated_tile_rows;
  337. int allocated_tile_cols;
  338. int allocated_vert_unit_rows;
  339. // Frame level params
  340. int num_tile_vert_sbs[MAX_NUM_TILE_ROWS];
  341. // Job Queue structure and handles
  342. JobQueue *job_queue;
  343. int jobs_per_tile_col;
  344. RowMTInfo row_mt_info[MAX_NUM_TILE_COLS];
  345. int thread_id_to_tile_id[MAX_NUM_THREADS]; // Mapping of threads to tiles
  346. } MultiThreadHandle;
  347. typedef struct RD_COUNTS {
  348. vp9_coeff_count coef_counts[TX_SIZES][PLANE_TYPES];
  349. int64_t comp_pred_diff[REFERENCE_MODES];
  350. int64_t filter_diff[SWITCHABLE_FILTER_CONTEXTS];
  351. } RD_COUNTS;
  352. typedef struct ThreadData {
  353. MACROBLOCK mb;
  354. RD_COUNTS rd_counts;
  355. FRAME_COUNTS *counts;
  356. PICK_MODE_CONTEXT *leaf_tree;
  357. PC_TREE *pc_tree;
  358. PC_TREE *pc_root;
  359. } ThreadData;
  360. struct EncWorkerData;
  361. typedef struct ActiveMap {
  362. int enabled;
  363. int update;
  364. unsigned char *map;
  365. } ActiveMap;
  366. typedef enum { Y, U, V, ALL } STAT_TYPE;
  367. typedef struct IMAGE_STAT {
  368. double stat[ALL + 1];
  369. double worst;
  370. } ImageStat;
  371. // Kf noise filtering currently disabled by default in build.
  372. // #define ENABLE_KF_DENOISE 1
  373. #define CPB_WINDOW_SIZE 4
  374. #define FRAME_WINDOW_SIZE 128
  375. #define SAMPLE_RATE_GRACE_P 0.015
  376. #define VP9_LEVELS 14
  377. typedef enum {
  378. LEVEL_UNKNOWN = 0,
  379. LEVEL_AUTO = 1,
  380. LEVEL_1 = 10,
  381. LEVEL_1_1 = 11,
  382. LEVEL_2 = 20,
  383. LEVEL_2_1 = 21,
  384. LEVEL_3 = 30,
  385. LEVEL_3_1 = 31,
  386. LEVEL_4 = 40,
  387. LEVEL_4_1 = 41,
  388. LEVEL_5 = 50,
  389. LEVEL_5_1 = 51,
  390. LEVEL_5_2 = 52,
  391. LEVEL_6 = 60,
  392. LEVEL_6_1 = 61,
  393. LEVEL_6_2 = 62,
  394. LEVEL_MAX = 255
  395. } VP9_LEVEL;
  396. typedef struct {
  397. VP9_LEVEL level;
  398. uint64_t max_luma_sample_rate;
  399. uint32_t max_luma_picture_size;
  400. uint32_t max_luma_picture_breadth;
  401. double average_bitrate; // in kilobits per second
  402. double max_cpb_size; // in kilobits
  403. double compression_ratio;
  404. uint8_t max_col_tiles;
  405. uint32_t min_altref_distance;
  406. uint8_t max_ref_frame_buffers;
  407. } Vp9LevelSpec;
  408. extern const Vp9LevelSpec vp9_level_defs[VP9_LEVELS];
  409. typedef struct {
  410. int64_t ts; // timestamp
  411. uint32_t luma_samples;
  412. uint32_t size; // in bytes
  413. } FrameRecord;
  414. typedef struct {
  415. FrameRecord buf[FRAME_WINDOW_SIZE];
  416. uint8_t start;
  417. uint8_t len;
  418. } FrameWindowBuffer;
  419. typedef struct {
  420. uint8_t seen_first_altref;
  421. uint32_t frames_since_last_altref;
  422. uint64_t total_compressed_size;
  423. uint64_t total_uncompressed_size;
  424. double time_encoded; // in seconds
  425. FrameWindowBuffer frame_window_buffer;
  426. int ref_refresh_map;
  427. } Vp9LevelStats;
  428. typedef struct {
  429. Vp9LevelStats level_stats;
  430. Vp9LevelSpec level_spec;
  431. } Vp9LevelInfo;
  432. typedef enum {
  433. BITRATE_TOO_LARGE = 0,
  434. LUMA_PIC_SIZE_TOO_LARGE,
  435. LUMA_PIC_BREADTH_TOO_LARGE,
  436. LUMA_SAMPLE_RATE_TOO_LARGE,
  437. CPB_TOO_LARGE,
  438. COMPRESSION_RATIO_TOO_SMALL,
  439. TOO_MANY_COLUMN_TILE,
  440. ALTREF_DIST_TOO_SMALL,
  441. TOO_MANY_REF_BUFFER,
  442. TARGET_LEVEL_FAIL_IDS
  443. } TARGET_LEVEL_FAIL_ID;
  444. typedef struct {
  445. int8_t level_index;
  446. uint8_t rc_config_updated;
  447. uint8_t fail_flag;
  448. int max_frame_size; // in bits
  449. double max_cpb_size; // in bits
  450. } LevelConstraint;
  451. typedef struct ARNRFilterData {
  452. YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS];
  453. int strength;
  454. int frame_count;
  455. int alt_ref_index;
  456. struct scale_factors sf;
  457. } ARNRFilterData;
  458. typedef struct EncFrameBuf {
  459. int mem_valid;
  460. int released;
  461. YV12_BUFFER_CONFIG frame;
  462. } EncFrameBuf;
  463. // Maximum operating frame buffer size needed for a GOP using ARF reference.
  464. #define MAX_ARF_GOP_SIZE (2 * MAX_LAG_BUFFERS)
  465. #if CONFIG_NON_GREEDY_MV
  466. typedef struct FEATURE_SCORE_LOC {
  467. int visited;
  468. double feature_score;
  469. int mi_row;
  470. int mi_col;
  471. } FEATURE_SCORE_LOC;
  472. #endif
  473. #define MAX_KMEANS_GROUPS 8
  474. typedef struct KMEANS_DATA {
  475. double value;
  476. int pos;
  477. int group_idx;
  478. } KMEANS_DATA;
  479. typedef struct VP9_COMP {
  480. QUANTS quants;
  481. ThreadData td;
  482. MB_MODE_INFO_EXT *mbmi_ext_base;
  483. DECLARE_ALIGNED(16, int16_t, y_dequant[QINDEX_RANGE][8]);
  484. DECLARE_ALIGNED(16, int16_t, uv_dequant[QINDEX_RANGE][8]);
  485. VP9_COMMON common;
  486. VP9EncoderConfig oxcf;
  487. struct lookahead_ctx *lookahead;
  488. struct lookahead_entry *alt_ref_source;
  489. YV12_BUFFER_CONFIG *Source;
  490. YV12_BUFFER_CONFIG *Last_Source; // NULL for first frame and alt_ref frames
  491. YV12_BUFFER_CONFIG *un_scaled_source;
  492. YV12_BUFFER_CONFIG scaled_source;
  493. YV12_BUFFER_CONFIG *unscaled_last_source;
  494. YV12_BUFFER_CONFIG scaled_last_source;
  495. #ifdef ENABLE_KF_DENOISE
  496. YV12_BUFFER_CONFIG raw_unscaled_source;
  497. YV12_BUFFER_CONFIG raw_scaled_source;
  498. #endif
  499. YV12_BUFFER_CONFIG *raw_source_frame;
  500. BLOCK_SIZE tpl_bsize;
  501. TplDepFrame tpl_stats[MAX_ARF_GOP_SIZE];
  502. YV12_BUFFER_CONFIG *tpl_recon_frames[REF_FRAMES];
  503. EncFrameBuf enc_frame_buf[REF_FRAMES];
  504. #if CONFIG_MULTITHREAD
  505. pthread_mutex_t kmeans_mutex;
  506. #endif
  507. int kmeans_data_arr_alloc;
  508. KMEANS_DATA *kmeans_data_arr;
  509. int kmeans_data_size;
  510. int kmeans_data_stride;
  511. double kmeans_ctr_ls[MAX_KMEANS_GROUPS];
  512. double kmeans_boundary_ls[MAX_KMEANS_GROUPS];
  513. int kmeans_count_ls[MAX_KMEANS_GROUPS];
  514. int kmeans_ctr_num;
  515. #if CONFIG_NON_GREEDY_MV
  516. int tpl_ready;
  517. int feature_score_loc_alloc;
  518. FEATURE_SCORE_LOC *feature_score_loc_arr;
  519. FEATURE_SCORE_LOC **feature_score_loc_sort;
  520. FEATURE_SCORE_LOC **feature_score_loc_heap;
  521. int_mv *select_mv_arr;
  522. #endif
  523. TileDataEnc *tile_data;
  524. int allocated_tiles; // Keep track of memory allocated for tiles.
  525. // For a still frame, this flag is set to 1 to skip partition search.
  526. int partition_search_skippable_frame;
  527. int scaled_ref_idx[REFS_PER_FRAME];
  528. int lst_fb_idx;
  529. int gld_fb_idx;
  530. int alt_fb_idx;
  531. int ref_fb_idx[REF_FRAMES];
  532. int refresh_last_frame;
  533. int refresh_golden_frame;
  534. int refresh_alt_ref_frame;
  535. int ext_refresh_frame_flags_pending;
  536. int ext_refresh_last_frame;
  537. int ext_refresh_golden_frame;
  538. int ext_refresh_alt_ref_frame;
  539. int ext_refresh_frame_context_pending;
  540. int ext_refresh_frame_context;
  541. int64_t norm_wiener_variance;
  542. int64_t *mb_wiener_variance;
  543. int mb_wiener_var_rows;
  544. int mb_wiener_var_cols;
  545. double *mi_ssim_rdmult_scaling_factors;
  546. YV12_BUFFER_CONFIG last_frame_uf;
  547. TOKENEXTRA *tile_tok[4][1 << 6];
  548. TOKENLIST *tplist[4][1 << 6];
  549. // Ambient reconstruction err target for force key frames
  550. int64_t ambient_err;
  551. RD_OPT rd;
  552. CODING_CONTEXT coding_context;
  553. int *nmvcosts[2];
  554. int *nmvcosts_hp[2];
  555. int *nmvsadcosts[2];
  556. int *nmvsadcosts_hp[2];
  557. int64_t last_time_stamp_seen;
  558. int64_t last_end_time_stamp_seen;
  559. int64_t first_time_stamp_ever;
  560. RATE_CONTROL rc;
  561. double framerate;
  562. int interp_filter_selected[REF_FRAMES][SWITCHABLE];
  563. struct vpx_codec_pkt_list *output_pkt_list;
  564. MBGRAPH_FRAME_STATS mbgraph_stats[MAX_LAG_BUFFERS];
  565. int mbgraph_n_frames; // number of frames filled in the above
  566. int static_mb_pct; // % forced skip mbs by segmentation
  567. int ref_frame_flags;
  568. SPEED_FEATURES sf;
  569. uint32_t max_mv_magnitude;
  570. int mv_step_param;
  571. int allow_comp_inter_inter;
  572. // Default value is 1. From first pass stats, encode_breakout may be disabled.
  573. ENCODE_BREAKOUT_TYPE allow_encode_breakout;
  574. // Get threshold from external input. A suggested threshold is 800 for HD
  575. // clips, and 300 for < HD clips.
  576. int encode_breakout;
  577. uint8_t *segmentation_map;
  578. uint8_t *skin_map;
  579. // segment threashold for encode breakout
  580. int segment_encode_breakout[MAX_SEGMENTS];
  581. CYCLIC_REFRESH *cyclic_refresh;
  582. ActiveMap active_map;
  583. fractional_mv_step_fp *find_fractional_mv_step;
  584. struct scale_factors me_sf;
  585. vp9_diamond_search_fn_t diamond_search_sad;
  586. vp9_variance_fn_ptr_t fn_ptr[BLOCK_SIZES];
  587. uint64_t time_receive_data;
  588. uint64_t time_compress_data;
  589. uint64_t time_pick_lpf;
  590. uint64_t time_encode_sb_row;
  591. #if CONFIG_FP_MB_STATS
  592. int use_fp_mb_stats;
  593. #endif
  594. TWO_PASS twopass;
  595. // Force recalculation of segment_ids for each mode info
  596. uint8_t force_update_segmentation;
  597. YV12_BUFFER_CONFIG alt_ref_buffer;
  598. // class responsible for adaptive
  599. // quantization of altref frames
  600. struct ALT_REF_AQ *alt_ref_aq;
  601. #if CONFIG_INTERNAL_STATS
  602. unsigned int mode_chosen_counts[MAX_MODES];
  603. int count;
  604. uint64_t total_sq_error;
  605. uint64_t total_samples;
  606. ImageStat psnr;
  607. uint64_t totalp_sq_error;
  608. uint64_t totalp_samples;
  609. ImageStat psnrp;
  610. double total_blockiness;
  611. double worst_blockiness;
  612. int bytes;
  613. double summed_quality;
  614. double summed_weights;
  615. double summedp_quality;
  616. double summedp_weights;
  617. unsigned int tot_recode_hits;
  618. double worst_ssim;
  619. ImageStat ssimg;
  620. ImageStat fastssim;
  621. ImageStat psnrhvs;
  622. int b_calculate_ssimg;
  623. int b_calculate_blockiness;
  624. int b_calculate_consistency;
  625. double total_inconsistency;
  626. double worst_consistency;
  627. Ssimv *ssim_vars;
  628. Metrics metrics;
  629. #endif
  630. int b_calculate_psnr;
  631. int droppable;
  632. int initial_width;
  633. int initial_height;
  634. int initial_mbs; // Number of MBs in the full-size frame; to be used to
  635. // normalize the firstpass stats. This will differ from the
  636. // number of MBs in the current frame when the frame is
  637. // scaled.
  638. int use_svc;
  639. SVC svc;
  640. // Store frame variance info in SOURCE_VAR_BASED_PARTITION search type.
  641. diff *source_diff_var;
  642. // The threshold used in SOURCE_VAR_BASED_PARTITION search type.
  643. unsigned int source_var_thresh;
  644. int frames_till_next_var_check;
  645. int frame_flags;
  646. search_site_config ss_cfg;
  647. int mbmode_cost[INTRA_MODES];
  648. unsigned int inter_mode_cost[INTER_MODE_CONTEXTS][INTER_MODES];
  649. int intra_uv_mode_cost[FRAME_TYPES][INTRA_MODES][INTRA_MODES];
  650. int y_mode_costs[INTRA_MODES][INTRA_MODES][INTRA_MODES];
  651. int switchable_interp_costs[SWITCHABLE_FILTER_CONTEXTS][SWITCHABLE_FILTERS];
  652. int partition_cost[PARTITION_CONTEXTS][PARTITION_TYPES];
  653. // Indices are: max_tx_size-1, tx_size_ctx, tx_size
  654. int tx_size_cost[TX_SIZES - 1][TX_SIZE_CONTEXTS][TX_SIZES];
  655. #if CONFIG_VP9_TEMPORAL_DENOISING
  656. VP9_DENOISER denoiser;
  657. #endif
  658. int resize_pending;
  659. RESIZE_STATE resize_state;
  660. int external_resize;
  661. int resize_scale_num;
  662. int resize_scale_den;
  663. int resize_avg_qp;
  664. int resize_buffer_underflow;
  665. int resize_count;
  666. int use_skin_detection;
  667. int target_level;
  668. NOISE_ESTIMATE noise_estimate;
  669. // Count on how many consecutive times a block uses small/zeromv for encoding.
  670. uint8_t *consec_zero_mv;
  671. // VAR_BASED_PARTITION thresholds
  672. // 0 - threshold_64x64; 1 - threshold_32x32;
  673. // 2 - threshold_16x16; 3 - vbp_threshold_8x8;
  674. int64_t vbp_thresholds[4];
  675. int64_t vbp_threshold_minmax;
  676. int64_t vbp_threshold_sad;
  677. // Threshold used for partition copy
  678. int64_t vbp_threshold_copy;
  679. BLOCK_SIZE vbp_bsize_min;
  680. // Multi-threading
  681. int num_workers;
  682. VPxWorker *workers;
  683. struct EncWorkerData *tile_thr_data;
  684. VP9LfSync lf_row_sync;
  685. struct VP9BitstreamWorkerData *vp9_bitstream_worker_data;
  686. int keep_level_stats;
  687. Vp9LevelInfo level_info;
  688. MultiThreadHandle multi_thread_ctxt;
  689. void (*row_mt_sync_read_ptr)(VP9RowMTSync *const, int, int);
  690. void (*row_mt_sync_write_ptr)(VP9RowMTSync *const, int, int, const int);
  691. ARNRFilterData arnr_filter_data;
  692. int row_mt;
  693. unsigned int row_mt_bit_exact;
  694. // Previous Partition Info
  695. BLOCK_SIZE *prev_partition;
  696. int8_t *prev_segment_id;
  697. // Used to save the status of whether a block has a low variance in
  698. // choose_partitioning. 0 for 64x64, 1~2 for 64x32, 3~4 for 32x64, 5~8 for
  699. // 32x32, 9~24 for 16x16.
  700. // This is for the last frame and is copied to the current frame
  701. // when partition copy happens.
  702. uint8_t *prev_variance_low;
  703. uint8_t *copied_frame_cnt;
  704. uint8_t max_copied_frame;
  705. // If the last frame is dropped, we don't copy partition.
  706. uint8_t last_frame_dropped;
  707. // For each superblock: keeps track of the last time (in frame distance) the
  708. // the superblock did not have low source sad.
  709. uint8_t *content_state_sb_fd;
  710. int compute_source_sad_onepass;
  711. LevelConstraint level_constraint;
  712. uint8_t *count_arf_frame_usage;
  713. uint8_t *count_lastgolden_frame_usage;
  714. int multi_layer_arf;
  715. vpx_roi_map_t roi;
  716. } VP9_COMP;
  717. void vp9_initialize_enc(void);
  718. struct VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf,
  719. BufferPool *const pool);
  720. void vp9_remove_compressor(VP9_COMP *cpi);
  721. void vp9_change_config(VP9_COMP *cpi, const VP9EncoderConfig *oxcf);
  722. // receive a frames worth of data. caller can assume that a copy of this
  723. // frame is made and not just a copy of the pointer..
  724. int vp9_receive_raw_frame(VP9_COMP *cpi, vpx_enc_frame_flags_t frame_flags,
  725. YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
  726. int64_t end_time);
  727. int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
  728. size_t *size, uint8_t *dest, int64_t *time_stamp,
  729. int64_t *time_end, int flush);
  730. int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
  731. vp9_ppflags_t *flags);
  732. int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags);
  733. void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags);
  734. int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
  735. YV12_BUFFER_CONFIG *sd);
  736. int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
  737. YV12_BUFFER_CONFIG *sd);
  738. int vp9_update_entropy(VP9_COMP *cpi, int update);
  739. int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
  740. int cols);
  741. int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
  742. int cols);
  743. int vp9_set_internal_size(VP9_COMP *cpi, VPX_SCALING horiz_mode,
  744. VPX_SCALING vert_mode);
  745. int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
  746. unsigned int height);
  747. void vp9_set_svc(VP9_COMP *cpi, int use_svc);
  748. static INLINE int stack_pop(int *stack, int stack_size) {
  749. int idx;
  750. const int r = stack[0];
  751. for (idx = 1; idx < stack_size; ++idx) stack[idx - 1] = stack[idx];
  752. return r;
  753. }
  754. static INLINE int stack_top(const int *stack) { return stack[0]; }
  755. static INLINE void stack_push(int *stack, int new_item, int stack_size) {
  756. int idx;
  757. for (idx = stack_size; idx > 0; --idx) stack[idx] = stack[idx - 1];
  758. stack[0] = new_item;
  759. }
  760. static INLINE void stack_init(int *stack, int length) {
  761. int idx;
  762. for (idx = 0; idx < length; ++idx) stack[idx] = -1;
  763. }
  764. int vp9_get_quantizer(struct VP9_COMP *cpi);
  765. static INLINE int frame_is_kf_gf_arf(const VP9_COMP *cpi) {
  766. return frame_is_intra_only(&cpi->common) || cpi->refresh_alt_ref_frame ||
  767. (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref);
  768. }
  769. static INLINE int get_ref_frame_map_idx(const VP9_COMP *cpi,
  770. MV_REFERENCE_FRAME ref_frame) {
  771. if (ref_frame == LAST_FRAME) {
  772. return cpi->lst_fb_idx;
  773. } else if (ref_frame == GOLDEN_FRAME) {
  774. return cpi->gld_fb_idx;
  775. } else {
  776. return cpi->alt_fb_idx;
  777. }
  778. }
  779. static INLINE int get_ref_frame_buf_idx(const VP9_COMP *const cpi,
  780. int ref_frame) {
  781. const VP9_COMMON *const cm = &cpi->common;
  782. const int map_idx = get_ref_frame_map_idx(cpi, ref_frame);
  783. return (map_idx != INVALID_IDX) ? cm->ref_frame_map[map_idx] : INVALID_IDX;
  784. }
  785. static INLINE RefCntBuffer *get_ref_cnt_buffer(VP9_COMMON *cm, int fb_idx) {
  786. return fb_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[fb_idx] : NULL;
  787. }
  788. static INLINE YV12_BUFFER_CONFIG *get_ref_frame_buffer(
  789. const VP9_COMP *const cpi, MV_REFERENCE_FRAME ref_frame) {
  790. const VP9_COMMON *const cm = &cpi->common;
  791. const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
  792. return buf_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[buf_idx].buf
  793. : NULL;
  794. }
  795. static INLINE int get_token_alloc(int mb_rows, int mb_cols) {
  796. // TODO(JBB): double check we can't exceed this token count if we have a
  797. // 32x32 transform crossing a boundary at a multiple of 16.
  798. // mb_rows, cols are in units of 16 pixels. We assume 3 planes all at full
  799. // resolution. We assume up to 1 token per pixel, and then allow
  800. // a head room of 4.
  801. return mb_rows * mb_cols * (16 * 16 * 3 + 4);
  802. }
  803. // Get the allocated token size for a tile. It does the same calculation as in
  804. // the frame token allocation.
  805. static INLINE int allocated_tokens(TileInfo tile) {
  806. int tile_mb_rows = (tile.mi_row_end - tile.mi_row_start + 1) >> 1;
  807. int tile_mb_cols = (tile.mi_col_end - tile.mi_col_start + 1) >> 1;
  808. return get_token_alloc(tile_mb_rows, tile_mb_cols);
  809. }
  810. static INLINE void get_start_tok(VP9_COMP *cpi, int tile_row, int tile_col,
  811. int mi_row, TOKENEXTRA **tok) {
  812. VP9_COMMON *const cm = &cpi->common;
  813. const int tile_cols = 1 << cm->log2_tile_cols;
  814. TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
  815. const TileInfo *const tile_info = &this_tile->tile_info;
  816. int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
  817. const int mb_row = (mi_row - tile_info->mi_row_start) >> 1;
  818. *tok =
  819. cpi->tile_tok[tile_row][tile_col] + get_token_alloc(mb_row, tile_mb_cols);
  820. }
  821. int64_t vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b);
  822. #if CONFIG_VP9_HIGHBITDEPTH
  823. int64_t vp9_highbd_get_y_sse(const YV12_BUFFER_CONFIG *a,
  824. const YV12_BUFFER_CONFIG *b);
  825. #endif // CONFIG_VP9_HIGHBITDEPTH
  826. void vp9_scale_references(VP9_COMP *cpi);
  827. void vp9_update_reference_frames(VP9_COMP *cpi);
  828. void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv);
  829. YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(
  830. VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
  831. YV12_BUFFER_CONFIG *scaled_temp, INTERP_FILTER filter_type,
  832. int phase_scaler, INTERP_FILTER filter_type2, int phase_scaler2);
  833. YV12_BUFFER_CONFIG *vp9_scale_if_required(
  834. VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
  835. int use_normative_scaler, INTERP_FILTER filter_type, int phase_scaler);
  836. void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags);
  837. static INLINE int is_one_pass_cbr_svc(const struct VP9_COMP *const cpi) {
  838. return (cpi->use_svc && cpi->oxcf.pass == 0);
  839. }
  840. #if CONFIG_VP9_TEMPORAL_DENOISING
  841. static INLINE int denoise_svc(const struct VP9_COMP *const cpi) {
  842. return (!cpi->use_svc || (cpi->use_svc && cpi->svc.spatial_layer_id >=
  843. cpi->svc.first_layer_denoise));
  844. }
  845. #endif
  846. #define MIN_LOOKAHEAD_FOR_ARFS 4
  847. static INLINE int is_altref_enabled(const VP9_COMP *const cpi) {
  848. return !(cpi->oxcf.mode == REALTIME && cpi->oxcf.rc_mode == VPX_CBR) &&
  849. cpi->oxcf.lag_in_frames >= MIN_LOOKAHEAD_FOR_ARFS &&
  850. cpi->oxcf.enable_auto_arf;
  851. }
  852. static INLINE void set_ref_ptrs(const VP9_COMMON *const cm, MACROBLOCKD *xd,
  853. MV_REFERENCE_FRAME ref0,
  854. MV_REFERENCE_FRAME ref1) {
  855. xd->block_refs[0] =
  856. &cm->frame_refs[ref0 >= LAST_FRAME ? ref0 - LAST_FRAME : 0];
  857. xd->block_refs[1] =
  858. &cm->frame_refs[ref1 >= LAST_FRAME ? ref1 - LAST_FRAME : 0];
  859. }
  860. static INLINE int get_chessboard_index(const int frame_index) {
  861. return frame_index & 0x1;
  862. }
  863. static INLINE int *cond_cost_list(const struct VP9_COMP *cpi, int *cost_list) {
  864. return cpi->sf.mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL;
  865. }
  866. static INLINE int get_num_vert_units(TileInfo tile, int shift) {
  867. int num_vert_units =
  868. (tile.mi_row_end - tile.mi_row_start + (1 << shift) - 1) >> shift;
  869. return num_vert_units;
  870. }
  871. static INLINE int get_num_cols(TileInfo tile, int shift) {
  872. int num_cols =
  873. (tile.mi_col_end - tile.mi_col_start + (1 << shift) - 1) >> shift;
  874. return num_cols;
  875. }
  876. static INLINE int get_level_index(VP9_LEVEL level) {
  877. int i;
  878. for (i = 0; i < VP9_LEVELS; ++i) {
  879. if (level == vp9_level_defs[i].level) return i;
  880. }
  881. return -1;
  882. }
  883. // Return the log2 value of max column tiles corresponding to the level that
  884. // the picture size fits into.
  885. static INLINE int log_tile_cols_from_picsize_level(uint32_t width,
  886. uint32_t height) {
  887. int i;
  888. const uint32_t pic_size = width * height;
  889. const uint32_t pic_breadth = VPXMAX(width, height);
  890. for (i = LEVEL_1; i < LEVEL_MAX; ++i) {
  891. if (vp9_level_defs[i].max_luma_picture_size >= pic_size &&
  892. vp9_level_defs[i].max_luma_picture_breadth >= pic_breadth) {
  893. return get_msb(vp9_level_defs[i].max_col_tiles);
  894. }
  895. }
  896. return INT_MAX;
  897. }
  898. VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec);
  899. int vp9_set_roi_map(VP9_COMP *cpi, unsigned char *map, unsigned int rows,
  900. unsigned int cols, int delta_q[8], int delta_lf[8],
  901. int skip[8], int ref_frame[8]);
  902. void vp9_new_framerate(VP9_COMP *cpi, double framerate);
  903. void vp9_set_row_mt(VP9_COMP *cpi);
  904. #define LAYER_IDS_TO_IDX(sl, tl, num_tl) ((sl) * (num_tl) + (tl))
  905. #ifdef __cplusplus
  906. } // extern "C"
  907. #endif
  908. #endif // VPX_VP9_ENCODER_VP9_ENCODER_H_