]> granicus.if.org Git - libvpx/blob - vp8/encoder/onyx_int.h
Merge commit 'refs/changes/09/809/1' of https://review.webmproject.org/p/libvpx
[libvpx] / vp8 / encoder / onyx_int.h
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
12 #ifndef __INC_VP8_INT_H
13 #define __INC_VP8_INT_H
14
15 #include <stdio.h>
16 #include "vpx_ports/config.h"
17 #include "onyx.h"
18 #include "treewriter.h"
19 #include "tokenize.h"
20 #include "onyxc_int.h"
21 #include "preproc.h"
22 #include "variance.h"
23 #include "dct.h"
24 #include "encodemb.h"
25 #include "quantize.h"
26 #include "entropy.h"
27 #include "threading.h"
28 #include "vpx_ports/mem.h"
29 #include "vpx/internal/vpx_codec_internal.h"
30 #include "mcomp.h"
31
32 //#define SPEEDSTATS 1
33 #define MIN_GF_INTERVAL             4
34 #define DEFAULT_GF_INTERVAL         7
35
36 #define KEY_FRAME_CONTEXT 5
37
38 #define MAX_LAG_BUFFERS (CONFIG_REALTIME_ONLY? 1 : 25)
39
40 #define AF_THRESH   25
41 #define AF_THRESH2  100
42 #define ARF_DECAY_THRESH 12
43 #define MAX_MODES 20
44
45 #define MIN_THRESHMULT  32
46 #define MAX_THRESHMULT  512
47
48 #define GF_ZEROMV_ZBIN_BOOST 24
49 #define ZBIN_OQ_MAX 192
50
51 #define VP8_TEMPORAL_ALT_REF 1
52
53 typedef struct
54 {
55     int kf_indicated;
56     unsigned int frames_since_key;
57     unsigned int frames_since_golden;
58     int filter_level;
59     int frames_till_gf_update_due;
60     int recent_ref_frame_usage[MAX_REF_FRAMES];
61
62     MV_CONTEXT mvc[2];
63     int mvcosts[2][MVvals+1];
64
65 #ifdef MODE_STATS
66     // Stats
67     int y_modes[5];
68     int uv_modes[4];
69     int b_modes[10];
70     int inter_y_modes[10];
71     int inter_uv_modes[4];
72     int inter_b_modes[10];
73 #endif
74
75     vp8_prob ymode_prob[4], uv_mode_prob[3];   /* interframe intra mode probs */
76     vp8_prob kf_ymode_prob[4], kf_uv_mode_prob[3];   /* keyframe "" */
77
78     int ymode_count[5], uv_mode_count[4];  /* intra MB type cts this frame */
79
80     int count_mb_ref_frame_usage[MAX_REF_FRAMES];
81
82     int this_frame_percent_intra;
83     int last_frame_percent_intra;
84
85
86 } CODING_CONTEXT;
87
88 typedef struct
89 {
90     double frame;
91     double intra_error;
92     double coded_error;
93     double ssim_weighted_pred_err;
94     double pcnt_inter;
95     double pcnt_motion;
96     double pcnt_second_ref;
97     double MVr;
98     double mvr_abs;
99     double MVc;
100     double mvc_abs;
101     double MVrv;
102     double MVcv;
103     double mv_in_out_count;
104     double duration;
105     double count;
106 }
107 FIRSTPASS_STATS;
108
109 typedef struct
110 {
111     int frames_so_far;
112     double frame_intra_error;
113     double frame_coded_error;
114     double frame_pcnt_inter;
115     double frame_pcnt_motion;
116     double frame_mvr;
117     double frame_mvr_abs;
118     double frame_mvc;
119     double frame_mvc_abs;
120
121 } ONEPASS_FRAMESTATS;
122
123
124 typedef enum
125 {
126     THR_ZEROMV         = 0,
127     THR_DC             = 1,
128
129     THR_NEARESTMV      = 2,
130     THR_NEARMV         = 3,
131
132     THR_ZEROG          = 4,
133     THR_NEARESTG       = 5,
134
135     THR_ZEROA          = 6,
136     THR_NEARESTA       = 7,
137
138     THR_NEARG          = 8,
139     THR_NEARA          = 9,
140
141     THR_V_PRED         = 10,
142     THR_H_PRED         = 11,
143     THR_TM             = 12,
144
145     THR_NEWMV          = 13,
146     THR_NEWG           = 14,
147     THR_NEWA           = 15,
148
149     THR_SPLITMV        = 16,
150     THR_SPLITG         = 17,
151     THR_SPLITA         = 18,
152
153     THR_B_PRED         = 19,
154 }
155 THR_MODES;
156
157 typedef enum
158 {
159     DIAMOND = 0,
160     NSTEP = 1,
161     HEX = 2
162 } SEARCH_METHODS;
163
164 typedef struct
165 {
166     int RD;
167     SEARCH_METHODS search_method;
168     int improved_quant;
169     int improved_dct;
170     int auto_filter;
171     int recode_loop;
172     int iterative_sub_pixel;
173     int half_pixel_search;
174     int quarter_pixel_search;
175     int thresh_mult[MAX_MODES];
176     int full_freq[2];
177     int min_fs_radius;
178     int max_fs_radius;
179     int max_step_search_steps;
180     int first_step;
181     int optimize_coefficients;
182
183 } SPEED_FEATURES;
184
185 typedef struct
186 {
187     MACROBLOCK  mb;
188     int mb_row;
189     TOKENEXTRA *tp;
190     int segment_counts[MAX_MB_SEGMENTS];
191     int totalrate;
192     int current_mb_col;
193 } MB_ROW_COMP;
194
195 typedef struct
196 {
197     TOKENEXTRA *start;
198     TOKENEXTRA *stop;
199 } TOKENLIST;
200
201 typedef struct
202 {
203     int ithread;
204     void *ptr1;
205     void *ptr2;
206 } ENCODETHREAD_DATA;
207 typedef struct
208 {
209     int ithread;
210     void *ptr1;
211 } LPFTHREAD_DATA;
212
213 typedef struct
214 {
215     INT64  source_time_stamp;
216     INT64  source_end_time_stamp;
217
218     DECLARE_ALIGNED(16, YV12_BUFFER_CONFIG, source_buffer);
219     unsigned int source_frame_flags;
220 } SOURCE_SAMPLE;
221
222 typedef struct VP8_ENCODER_RTCD
223 {
224     VP8_COMMON_RTCD            *common;
225     vp8_variance_rtcd_vtable_t  variance;
226     vp8_fdct_rtcd_vtable_t      fdct;
227     vp8_encodemb_rtcd_vtable_t  encodemb;
228     vp8_quantize_rtcd_vtable_t  quantize;
229     vp8_search_rtcd_vtable_t    search;
230 } VP8_ENCODER_RTCD;
231
232 typedef struct
233 {
234
235     DECLARE_ALIGNED(16, short, Y1quant[QINDEX_RANGE][16]);
236     DECLARE_ALIGNED(16, short, Y1quant_shift[QINDEX_RANGE][16]);
237     DECLARE_ALIGNED(16, short, Y1zbin[QINDEX_RANGE][16]);
238     DECLARE_ALIGNED(16, short, Y1round[QINDEX_RANGE][16]);
239
240     DECLARE_ALIGNED(16, short, Y2quant[QINDEX_RANGE][16]);
241     DECLARE_ALIGNED(16, short, Y2quant_shift[QINDEX_RANGE][16]);
242     DECLARE_ALIGNED(16, short, Y2zbin[QINDEX_RANGE][16]);
243     DECLARE_ALIGNED(16, short, Y2round[QINDEX_RANGE][16]);
244
245     DECLARE_ALIGNED(16, short, UVquant[QINDEX_RANGE][16]);
246     DECLARE_ALIGNED(16, short, UVquant_shift[QINDEX_RANGE][16]);
247     DECLARE_ALIGNED(16, short, UVzbin[QINDEX_RANGE][16]);
248     DECLARE_ALIGNED(16, short, UVround[QINDEX_RANGE][16]);
249
250     DECLARE_ALIGNED(16, short, zrun_zbin_boost_y1[QINDEX_RANGE][16]);
251     DECLARE_ALIGNED(16, short, zrun_zbin_boost_y2[QINDEX_RANGE][16]);
252     DECLARE_ALIGNED(16, short, zrun_zbin_boost_uv[QINDEX_RANGE][16]);
253
254
255     MACROBLOCK mb;
256     VP8_COMMON common;
257     vp8_writer bc, bc2;
258     // bool_writer *bc2;
259
260     VP8_CONFIG oxcf;
261
262     YV12_BUFFER_CONFIG *Source;
263     YV12_BUFFER_CONFIG *un_scaled_source;
264     INT64 source_time_stamp;
265     INT64 source_end_time_stamp;
266     unsigned int source_frame_flags;
267     YV12_BUFFER_CONFIG scaled_source;
268
269     int source_buffer_count;
270     int source_encode_index;
271     int source_alt_ref_pending;
272     int source_alt_ref_active;
273
274     int last_alt_ref_sei;
275     int is_src_frame_alt_ref;
276     int is_next_src_alt_ref;
277
278     int gold_is_last; // golden frame same as last frame ( short circuit gold searches)
279     int alt_is_last;  // Alt reference frame same as last ( short circuit altref search)
280     int gold_is_alt;  // don't do both alt and gold search ( just do gold).
281
282     //int refresh_alt_ref_frame;
283     SOURCE_SAMPLE src_buffer[MAX_LAG_BUFFERS];
284
285     YV12_BUFFER_CONFIG last_frame_uf;
286
287     char *Dest;
288
289     TOKENEXTRA *tok;
290     unsigned int tok_count;
291
292
293     unsigned int frames_since_key;
294     unsigned int key_frame_frequency;
295     unsigned int next_key;
296
297     unsigned int mode_check_freq[MAX_MODES];
298     unsigned int mode_test_hit_counts[MAX_MODES];
299     unsigned int mode_chosen_counts[MAX_MODES];
300     unsigned int mbs_tested_so_far;
301
302     unsigned int check_freq[2];
303     unsigned int do_full[2];
304
305     int rd_thresh_mult[MAX_MODES];
306     int rd_baseline_thresh[MAX_MODES];
307     int rd_threshes[MAX_MODES];
308     int mvcostbase;
309     int mvcostmultiplier;
310     int subseqblockweight;
311     int errthresh;
312
313     int RDMULT;
314     int RDDIV ;
315
316     TOKENEXTRA *rdtok;
317     vp8_writer rdbc;
318     int intra_mode_costs[10];
319
320
321     CODING_CONTEXT coding_context;
322
323     // Rate targetting variables
324     long long prediction_error;
325     long long last_prediction_error;
326     long long intra_error;
327     long long last_intra_error;
328     long long last_auto_filter_prediction_error;
329
330 #if 0
331     // Experimental RD code
332     long long frame_distortion;
333     long long last_frame_distortion;
334 #endif
335
336     int last_mb_distortion;
337
338     int frames_since_auto_filter;
339
340     int this_frame_target;
341     int projected_frame_size;
342     int last_q[2];                   // Separate values for Intra/Inter
343     int target_bits_per_mb;
344
345     double rate_correction_factor;
346     double key_frame_rate_correction_factor;
347     double gf_rate_correction_factor;
348     double est_max_qcorrection_factor;
349
350     int frames_till_gf_update_due;      // Count down till next GF
351     int current_gf_interval;          // GF interval chosen when we coded the last GF
352
353     int gf_overspend_bits;            // Total bits overspent becasue of GF boost (cumulative)
354
355     int gf_group_bits;                // Projected Bits available for a group of frames including 1 GF or ARF
356     int gf_bits;                     // Bits for the golden frame or ARF - 2 pass only
357     int mid_gf_extra_bits;             // A few extra bits for the frame half way between two gfs.
358
359     // Projected total bits available for a key frame group of frames
360     long long kf_group_bits;
361
362     // Error score of frames still to be coded in kf group
363     long long kf_group_error_left;
364
365     // Bits for the key frame in a key frame group - 2 pass only
366     int kf_bits;
367
368     int non_gf_bitrate_adjustment;     // Used in the few frames following a GF to recover the extra bits spent in that GF
369     int initial_gf_use;               // percentage use of gf 2 frames after gf
370
371     int gf_group_error_left;           // Remaining error from uncoded frames in a gf group. Two pass use only
372
373     int kf_overspend_bits;            // Extra bits spent on key frames that need to be recovered on inter frames
374     int kf_bitrate_adjustment;        // Current number of bit s to try and recover on each inter frame.
375     int max_gf_interval;
376     int baseline_gf_interval;
377     int gf_decay_rate;
378     int active_arnr_frames;           // <= cpi->oxcf.arnr_max_frames
379
380     INT64 key_frame_count;
381     INT64 tot_key_frame_bits;
382     int prior_key_frame_size[KEY_FRAME_CONTEXT];
383     int prior_key_frame_distance[KEY_FRAME_CONTEXT];
384     int per_frame_bandwidth;          // Current section per frame bandwidth target
385     int av_per_frame_bandwidth;        // Average frame size target for clip
386     int min_frame_bandwidth;          // Minimum allocation that should be used for any frame
387     int last_key_frame_size;
388     int intra_frame_target;
389     int inter_frame_target;
390     double output_frame_rate;
391     long long last_time_stamp_seen;
392     long long first_time_stamp_ever;
393
394     int ni_av_qi;
395     int ni_tot_qi;
396     int ni_frames;
397     int avg_frame_qindex;
398
399     int zbin_over_quant;
400     int zbin_mode_boost;
401     int zbin_mode_boost_enabled;
402
403     INT64 total_byte_count;
404
405     int buffered_mode;
406
407     int buffer_level;
408     int bits_off_target;
409
410     int rolling_target_bits;
411     int rolling_actual_bits;
412
413     int long_rolling_target_bits;
414     int long_rolling_actual_bits;
415
416     long long total_actual_bits;
417     int total_target_vs_actual;        // debug stats
418
419     int worst_quality;
420     int active_worst_quality;
421     int best_quality;
422     int active_best_quality;
423
424     int drop_frames_allowed;          // Are we permitted to drop frames?
425     int drop_frame;                  // Drop this frame?
426     int drop_count;                  // How many frames have we dropped?
427     int max_drop_count;               // How many frames should we drop?
428     int max_consec_dropped_frames;     // Limit number of consecutive frames that can be dropped.
429
430
431     int ymode_count [VP8_YMODES];        /* intra MB type cts this frame */
432     int uv_mode_count[VP8_UV_MODES];       /* intra MB type cts this frame */
433
434     unsigned int MVcount [2] [MVvals];  /* (row,col) MV cts this frame */
435
436     unsigned int coef_counts [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens];  /* for this frame */
437     //DECLARE_ALIGNED(16, int, coef_counts_backup [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens]);   //not used any more
438     //save vp8_tree_probs_from_distribution result for each frame to avoid repeat calculation
439     vp8_prob frame_coef_probs [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens-1];
440     unsigned int frame_branch_ct [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens-1][2];
441
442     /* Second compressed data partition contains coefficient data. */
443
444     unsigned char *output_partition2;
445     size_t output_partition2size;
446
447     pre_proc_instance ppi;
448
449     int frames_to_key;
450     int gfu_boost;
451     int kf_boost;
452     int last_boost;
453     double total_error_left;
454     double total_intra_error_left;
455     double total_coded_error_left;
456     double start_tot_err_left;
457     double min_error;
458
459     double modified_total_error_left;
460     double avg_iiratio;
461
462     int target_bandwidth;
463     long long bits_left;
464     FIRSTPASS_STATS *total_stats;
465     FIRSTPASS_STATS *this_frame_stats;
466     FIRSTPASS_STATS *stats_in, *stats_in_end;
467     struct vpx_codec_pkt_list  *output_pkt_list;
468     int                          first_pass_done;
469     unsigned char *fp_motion_map;
470
471     unsigned char *fp_motion_map_stats, *fp_motion_map_stats_save;
472
473 #if 0
474     // Experimental code for lagged and one pass
475     ONEPASS_FRAMESTATS one_pass_frame_stats[MAX_LAG_BUFFERS];
476     int one_pass_frame_index;
477 #endif
478
479     int decimation_factor;
480     int decimation_count;
481
482     // for real time encoding
483     int avg_encode_time;              //microsecond
484     int avg_pick_mode_time;            //microsecond
485     int Speed;
486     unsigned int cpu_freq;           //Mhz
487     int compressor_speed;
488
489     int interquantizer;
490     int auto_gold;
491     int auto_adjust_gold_quantizer;
492     int goldquantizer;
493     int goldfreq;
494     int auto_adjust_key_quantizer;
495     int keyquantizer;
496     int auto_worst_q;
497     int filter_type;
498     int cpu_used;
499     int chroma_boost;
500     int horiz_scale;
501     int vert_scale;
502     int pass;
503
504
505     int prob_intra_coded;
506     int prob_last_coded;
507     int prob_gf_coded;
508     int prob_skip_false;
509     int last_skip_false_probs[3];
510     int last_skip_probs_q[3];
511     int recent_ref_frame_usage[MAX_REF_FRAMES];
512
513     int count_mb_ref_frame_usage[MAX_REF_FRAMES];
514     int this_frame_percent_intra;
515     int last_frame_percent_intra;
516
517     int last_key_frame_q;
518     int last_kffilt_lvl;
519
520     int ref_frame_flags;
521
522     int exp[512];
523
524     SPEED_FEATURES sf;
525     int error_bins[1024];
526
527     int inter_lvl;
528     int intra_lvl;
529     int motion_lvl;
530     int motion_speed;
531     int motion_var;
532     unsigned int next_iiratio;
533     unsigned int this_iiratio;
534     int this_frame_modified_error;
535
536     double norm_intra_err_per_mb;
537     double norm_inter_err_per_mb;
538     double norm_iidiff_per_mb;
539
540     int last_best_mode_index;          // Record of mode index chosen for previous macro block.
541     int last_auto_filt_val;
542     int last_auto_filt_q;
543
544     // Data used for real time conferencing mode to help determine if it would be good to update the gf
545     int inter_zz_count;
546     int gf_bad_count;
547     int gf_update_recommended;
548     int skip_true_count;
549     int skip_false_count;
550
551     int alt_qcount;
552
553     int ready_for_new_frame;
554
555     unsigned char *segmentation_map;
556     signed char segment_feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];            // Segment data (can be deltas or absolute values)
557     int  segment_encode_breakout[MAX_MB_SEGMENTS];                    // segment threashold for encode breakout
558
559     unsigned char *active_map;
560     unsigned int active_map_enabled;
561     // Video conferencing cyclic refresh mode flags etc
562     // This is a mode designed to clean up the background over time in live encoding scenarious. It uses segmentation
563     int cyclic_refresh_mode_enabled;
564     int cyclic_refresh_mode_max_mbs_perframe;
565     int cyclic_refresh_mode_index;
566     int cyclic_refresh_q;
567     signed char *cyclic_refresh_map;
568
569     // multithread data
570     int current_mb_col_main;
571     int processor_core_count;
572     int b_multi_threaded;
573     int encoding_thread_count;
574
575 #if CONFIG_MULTITHREAD
576     pthread_t *h_encoding_thread;
577 #endif
578     MB_ROW_COMP *mb_row_ei;
579     ENCODETHREAD_DATA *en_thread_data;
580
581 #if CONFIG_MULTITHREAD
582     //events
583     sem_t *h_event_mbrencoding;
584     sem_t h_event_main;
585 #endif
586
587     TOKENLIST *tplist;
588     // end of multithread data
589
590
591     fractional_mv_step_fp *find_fractional_mv_step;
592     vp8_full_search_fn_t full_search_sad;
593     vp8_diamond_search_fn_t diamond_search_sad;
594     vp8_variance_fn_ptr_t fn_ptr;
595     unsigned int time_receive_data;
596     unsigned int time_compress_data;
597     unsigned int time_pick_lpf;
598     unsigned int time_encode_mb_row;
599
600     unsigned int tempdata1;
601     unsigned int tempdata2;
602
603     int base_skip_false_prob[128];
604     unsigned int section_is_low_motion;
605     unsigned int section_benefits_from_aggresive_q;
606     unsigned int section_is_fast_motion;
607     unsigned int section_intra_rating;
608
609     double section_max_qfactor;
610
611
612 #if CONFIG_RUNTIME_CPU_DETECT
613     VP8_ENCODER_RTCD            rtcd;
614 #endif
615 #if VP8_TEMPORAL_ALT_REF
616     SOURCE_SAMPLE alt_ref_buffer;
617     YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS];
618     int fixed_divide[512];
619 #endif
620     // Flag to indicate temporal filter method
621     int use_weighted_temporal_filter;
622
623 #if CONFIG_PSNR
624     int    count;
625     double total_y;
626     double total_u;
627     double total_v;
628     double total ;
629     double total_sq_error;
630     double totalp_y;
631     double totalp_u;
632     double totalp_v;
633     double totalp;
634     double total_sq_error2;
635     int    bytes;
636     double summed_quality;
637     double summed_weights;
638     unsigned int tot_recode_hits;
639
640
641     double total_ssimg_y;
642     double total_ssimg_u;
643     double total_ssimg_v;
644     double total_ssimg_all;
645
646     int b_calculate_ssimg;
647 #endif
648     int b_calculate_psnr;
649
650
651     unsigned char *gf_active_flags;   // Record of which MBs still refer to last golden frame either directly or through 0,0
652     int gf_active_count;
653
654
655 } VP8_COMP;
656
657 void control_data_rate(VP8_COMP *cpi);
658
659 void vp8_encode_frame(VP8_COMP *cpi);
660
661 void vp8_pack_bitstream(VP8_COMP *cpi, unsigned char *dest, unsigned long *size);
662
663 int rd_cost_intra_mb(MACROBLOCKD *x);
664
665 void vp8_tokenize_mb(VP8_COMP *, MACROBLOCKD *, TOKENEXTRA **);
666
667 void vp8_set_speed_features(VP8_COMP *cpi);
668
669 #if CONFIG_DEBUG
670 #define CHECK_MEM_ERROR(lval,expr) do {\
671         lval = (expr); \
672         if(!lval) \
673             vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,\
674                                "Failed to allocate "#lval" at %s:%d", \
675                                __FILE__,__LINE__);\
676     } while(0)
677 #else
678 #define CHECK_MEM_ERROR(lval,expr) do {\
679         lval = (expr); \
680         if(!lval) \
681             vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,\
682                                "Failed to allocate "#lval);\
683     } while(0)
684 #endif
685 #endif