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