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