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