Comments for alt ref flags.
[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 struct
245 {
246
247     DECLARE_ALIGNED(16, short, Y1quant[QINDEX_RANGE][16]);
248     DECLARE_ALIGNED(16, short, Y1quant_shift[QINDEX_RANGE][16]);
249     DECLARE_ALIGNED(16, short, Y1zbin[QINDEX_RANGE][16]);
250     DECLARE_ALIGNED(16, short, Y1round[QINDEX_RANGE][16]);
251
252     DECLARE_ALIGNED(16, short, Y2quant[QINDEX_RANGE][16]);
253     DECLARE_ALIGNED(16, short, Y2quant_shift[QINDEX_RANGE][16]);
254     DECLARE_ALIGNED(16, short, Y2zbin[QINDEX_RANGE][16]);
255     DECLARE_ALIGNED(16, short, Y2round[QINDEX_RANGE][16]);
256
257     DECLARE_ALIGNED(16, short, UVquant[QINDEX_RANGE][16]);
258     DECLARE_ALIGNED(16, short, UVquant_shift[QINDEX_RANGE][16]);
259     DECLARE_ALIGNED(16, short, UVzbin[QINDEX_RANGE][16]);
260     DECLARE_ALIGNED(16, short, UVround[QINDEX_RANGE][16]);
261
262     DECLARE_ALIGNED(16, short, zrun_zbin_boost_y1[QINDEX_RANGE][16]);
263     DECLARE_ALIGNED(16, short, zrun_zbin_boost_y2[QINDEX_RANGE][16]);
264     DECLARE_ALIGNED(16, short, zrun_zbin_boost_uv[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     YV12_BUFFER_CONFIG *Source;
275     YV12_BUFFER_CONFIG *un_scaled_source;
276     INT64 source_time_stamp;
277     INT64 source_end_time_stamp;
278     unsigned int source_frame_flags;
279     YV12_BUFFER_CONFIG scaled_source;
280
281     int source_buffer_count;    // number of src_buffers in use for lagged encoding
282     int source_encode_index;    // index of buffer in src_buffer to encode
283     int source_alt_ref_pending; // frame in src_buffers has been identified to be encoded as an alt ref
284     int source_alt_ref_active;  // an alt ref frame has been encoded and is usable
285
286     int last_alt_ref_sei;       // index into src_buffers of frame used as alt reference
287     int is_src_frame_alt_ref;   // source of frame to encode is an exact copy of an alt ref frame
288     int is_next_src_alt_ref;    // source of next frame to encode is an exact copy of an alt ref frame
289
290     int gold_is_last; // golden frame same as last frame ( short circuit gold searches)
291     int alt_is_last;  // Alt reference frame same as last ( short circuit altref search)
292     int gold_is_alt;  // don't do both alt and gold search ( just do gold).
293
294     //int refresh_alt_ref_frame;
295     SOURCE_SAMPLE src_buffer[MAX_LAG_BUFFERS];
296
297     YV12_BUFFER_CONFIG last_frame_uf;
298
299     char *Dest;
300
301     TOKENEXTRA *tok;
302     unsigned int tok_count;
303
304
305     unsigned int frames_since_key;
306     unsigned int key_frame_frequency;
307     unsigned int next_key;
308
309     unsigned int mode_check_freq[MAX_MODES];
310     unsigned int mode_test_hit_counts[MAX_MODES];
311     unsigned int mode_chosen_counts[MAX_MODES];
312     unsigned int mbs_tested_so_far;
313
314     unsigned int check_freq[2];
315     unsigned int do_full[2];
316
317     int rd_thresh_mult[MAX_MODES];
318     int rd_baseline_thresh[MAX_MODES];
319     int rd_threshes[MAX_MODES];
320     int mvcostbase;
321     int mvcostmultiplier;
322     int subseqblockweight;
323     int errthresh;
324
325     int RDMULT;
326     int RDDIV ;
327
328     TOKENEXTRA *rdtok;
329     vp8_writer rdbc;
330     int intra_mode_costs[10];
331
332
333     CODING_CONTEXT coding_context;
334
335     // Rate targetting variables
336     long long prediction_error;
337     long long last_prediction_error;
338     long long intra_error;
339     long long last_intra_error;
340     long long last_auto_filter_prediction_error;
341
342 #if 0
343     // Experimental RD code
344     long long frame_distortion;
345     long long last_frame_distortion;
346 #endif
347
348     int last_mb_distortion;
349
350     int frames_since_auto_filter;
351
352     int this_frame_target;
353     int projected_frame_size;
354     int last_q[2];                   // Separate values for Intra/Inter
355     int target_bits_per_mb;
356
357     double rate_correction_factor;
358     double key_frame_rate_correction_factor;
359     double gf_rate_correction_factor;
360     double est_max_qcorrection_factor;
361
362     int frames_till_gf_update_due;      // Count down till next GF
363     int current_gf_interval;          // GF interval chosen when we coded the last GF
364
365     int gf_overspend_bits;            // Total bits overspent becasue of GF boost (cumulative)
366
367     int gf_group_bits;                // Projected Bits available for a group of frames including 1 GF or ARF
368     int gf_bits;                     // Bits for the golden frame or ARF - 2 pass only
369     int mid_gf_extra_bits;             // A few extra bits for the frame half way between two gfs.
370
371     // Projected total bits available for a key frame group of frames
372     long long kf_group_bits;
373
374     // Error score of frames still to be coded in kf group
375     long long kf_group_error_left;
376
377     // Bits for the key frame in a key frame group - 2 pass only
378     int kf_bits;
379
380     int non_gf_bitrate_adjustment;     // Used in the few frames following a GF to recover the extra bits spent in that GF
381     int initial_gf_use;               // percentage use of gf 2 frames after gf
382
383     int gf_group_error_left;           // Remaining error from uncoded frames in a gf group. Two pass use only
384
385     int kf_overspend_bits;            // Extra bits spent on key frames that need to be recovered on inter frames
386     int kf_bitrate_adjustment;        // Current number of bit s to try and recover on each inter frame.
387     int max_gf_interval;
388     int baseline_gf_interval;
389     int gf_decay_rate;
390     int active_arnr_frames;           // <= cpi->oxcf.arnr_max_frames
391
392     INT64 key_frame_count;
393     INT64 tot_key_frame_bits;
394     int prior_key_frame_size[KEY_FRAME_CONTEXT];
395     int prior_key_frame_distance[KEY_FRAME_CONTEXT];
396     int per_frame_bandwidth;          // Current section per frame bandwidth target
397     int av_per_frame_bandwidth;        // Average frame size target for clip
398     int min_frame_bandwidth;          // Minimum allocation that should be used for any frame
399     int last_key_frame_size;
400     int intra_frame_target;
401     int inter_frame_target;
402     double output_frame_rate;
403     long long last_time_stamp_seen;
404     long long last_end_time_stamp_seen;
405     long long first_time_stamp_ever;
406
407     int ni_av_qi;
408     int ni_tot_qi;
409     int ni_frames;
410     int avg_frame_qindex;
411
412     int zbin_over_quant;
413     int zbin_mode_boost;
414     int zbin_mode_boost_enabled;
415
416     INT64 total_byte_count;
417
418     int buffered_mode;
419
420     int buffer_level;
421     int bits_off_target;
422
423     int rolling_target_bits;
424     int rolling_actual_bits;
425
426     int long_rolling_target_bits;
427     int long_rolling_actual_bits;
428
429     long long total_actual_bits;
430     int total_target_vs_actual;        // debug stats
431
432     int worst_quality;
433     int active_worst_quality;
434     int best_quality;
435     int active_best_quality;
436
437     int drop_frames_allowed;          // Are we permitted to drop frames?
438     int drop_frame;                  // Drop this frame?
439     int drop_count;                  // How many frames have we dropped?
440     int max_drop_count;               // How many frames should we drop?
441     int max_consec_dropped_frames;     // Limit number of consecutive frames that can be dropped.
442
443
444     int ymode_count [VP8_YMODES];        /* intra MB type cts this frame */
445     int uv_mode_count[VP8_UV_MODES];       /* intra MB type cts this frame */
446
447     unsigned int MVcount [2] [MVvals];  /* (row,col) MV cts this frame */
448
449     unsigned int coef_counts [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens];  /* for this frame */
450     //DECLARE_ALIGNED(16, int, coef_counts_backup [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens]);   //not used any more
451     //save vp8_tree_probs_from_distribution result for each frame to avoid repeat calculation
452     vp8_prob frame_coef_probs [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens-1];
453     unsigned int frame_branch_ct [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens-1][2];
454
455     /* Second compressed data partition contains coefficient data. */
456
457     unsigned char *output_partition2;
458     size_t output_partition2size;
459
460     pre_proc_instance ppi;
461
462     int frames_to_key;
463     int gfu_boost;
464     int kf_boost;
465     int last_boost;
466     double total_error_left;
467     double total_intra_error_left;
468     double total_coded_error_left;
469     double start_tot_err_left;
470     double min_error;
471
472     double modified_total_error_left;
473     double avg_iiratio;
474
475     int target_bandwidth;
476     long long bits_left;
477     FIRSTPASS_STATS *total_stats;
478     FIRSTPASS_STATS *this_frame_stats;
479     FIRSTPASS_STATS *stats_in, *stats_in_end;
480     struct vpx_codec_pkt_list  *output_pkt_list;
481     int                          first_pass_done;
482     unsigned char *fp_motion_map;
483
484     unsigned char *fp_motion_map_stats, *fp_motion_map_stats_save;
485
486 #if 0
487     // Experimental code for lagged and one pass
488     ONEPASS_FRAMESTATS one_pass_frame_stats[MAX_LAG_BUFFERS];
489     int one_pass_frame_index;
490 #endif
491
492     int decimation_factor;
493     int decimation_count;
494
495     // for real time encoding
496     int avg_encode_time;              //microsecond
497     int avg_pick_mode_time;            //microsecond
498     int Speed;
499     unsigned int cpu_freq;           //Mhz
500     int compressor_speed;
501
502     int interquantizer;
503     int auto_gold;
504     int auto_adjust_gold_quantizer;
505     int goldquantizer;
506     int goldfreq;
507     int auto_adjust_key_quantizer;
508     int keyquantizer;
509     int auto_worst_q;
510     int filter_type;
511     int cpu_used;
512     int chroma_boost;
513     int horiz_scale;
514     int vert_scale;
515     int pass;
516
517
518     int prob_intra_coded;
519     int prob_last_coded;
520     int prob_gf_coded;
521     int prob_skip_false;
522     int last_skip_false_probs[3];
523     int last_skip_probs_q[3];
524     int recent_ref_frame_usage[MAX_REF_FRAMES];
525
526     int count_mb_ref_frame_usage[MAX_REF_FRAMES];
527     int this_frame_percent_intra;
528     int last_frame_percent_intra;
529
530     int last_key_frame_q;
531     int last_kffilt_lvl;
532
533     int ref_frame_flags;
534
535     int exp[512];
536
537     SPEED_FEATURES sf;
538     int error_bins[1024];
539
540     int inter_lvl;
541     int intra_lvl;
542     int motion_lvl;
543     int motion_speed;
544     int motion_var;
545     unsigned int next_iiratio;
546     unsigned int this_iiratio;
547     int this_frame_modified_error;
548
549     double norm_intra_err_per_mb;
550     double norm_inter_err_per_mb;
551     double norm_iidiff_per_mb;
552
553     int last_best_mode_index;          // Record of mode index chosen for previous macro block.
554     int last_auto_filt_val;
555     int last_auto_filt_q;
556
557     // Data used for real time conferencing mode to help determine if it would be good to update the gf
558     int inter_zz_count;
559     int gf_bad_count;
560     int gf_update_recommended;
561     int skip_true_count;
562     int skip_false_count;
563
564     int alt_qcount;
565
566     int ready_for_new_frame;
567
568     unsigned char *segmentation_map;
569     signed char segment_feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];            // Segment data (can be deltas or absolute values)
570     int  segment_encode_breakout[MAX_MB_SEGMENTS];                    // segment threashold for encode breakout
571
572     unsigned char *active_map;
573     unsigned int active_map_enabled;
574     // Video conferencing cyclic refresh mode flags etc
575     // This is a mode designed to clean up the background over time in live encoding scenarious. It uses segmentation
576     int cyclic_refresh_mode_enabled;
577     int cyclic_refresh_mode_max_mbs_perframe;
578     int cyclic_refresh_mode_index;
579     int cyclic_refresh_q;
580     signed char *cyclic_refresh_map;
581
582     // multithread data
583     int current_mb_col_main;
584     int processor_core_count;
585     int b_multi_threaded;
586     int encoding_thread_count;
587
588 #if CONFIG_MULTITHREAD
589     pthread_t *h_encoding_thread;
590 #endif
591     MB_ROW_COMP *mb_row_ei;
592     ENCODETHREAD_DATA *en_thread_data;
593
594 #if CONFIG_MULTITHREAD
595     //events
596     sem_t *h_event_mbrencoding;
597     sem_t h_event_main;
598 #endif
599
600     TOKENLIST *tplist;
601     // end of multithread data
602
603
604     fractional_mv_step_fp *find_fractional_mv_step;
605     vp8_full_search_fn_t full_search_sad;
606     vp8_diamond_search_fn_t diamond_search_sad;
607     vp8_variance_fn_ptr_t fn_ptr[BLOCK_MAX_SEGMENTS];
608     unsigned int time_receive_data;
609     unsigned int time_compress_data;
610     unsigned int time_pick_lpf;
611     unsigned int time_encode_mb_row;
612
613     unsigned int tempdata1;
614     unsigned int tempdata2;
615
616     int base_skip_false_prob[128];
617     unsigned int section_intra_rating;
618
619     double section_max_qfactor;
620
621
622 #if CONFIG_RUNTIME_CPU_DETECT
623     VP8_ENCODER_RTCD            rtcd;
624 #endif
625 #if VP8_TEMPORAL_ALT_REF
626     SOURCE_SAMPLE alt_ref_buffer;
627     YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS];
628     int fixed_divide[512];
629 #endif
630     // Flag to indicate temporal filter method
631     int use_weighted_temporal_filter;
632
633 #if CONFIG_PSNR
634     int    count;
635     double total_y;
636     double total_u;
637     double total_v;
638     double total ;
639     double total_sq_error;
640     double totalp_y;
641     double totalp_u;
642     double totalp_v;
643     double totalp;
644     double total_sq_error2;
645     int    bytes;
646     double summed_quality;
647     double summed_weights;
648     unsigned int tot_recode_hits;
649
650
651     double total_ssimg_y;
652     double total_ssimg_u;
653     double total_ssimg_v;
654     double total_ssimg_all;
655
656     int b_calculate_ssimg;
657 #endif
658     int b_calculate_psnr;
659
660
661     unsigned char *gf_active_flags;   // Record of which MBs still refer to last golden frame either directly or through 0,0
662     int gf_active_count;
663
664
665 } VP8_COMP;
666
667 void control_data_rate(VP8_COMP *cpi);
668
669 void vp8_encode_frame(VP8_COMP *cpi);
670
671 void vp8_pack_bitstream(VP8_COMP *cpi, unsigned char *dest, unsigned long *size);
672
673 int rd_cost_intra_mb(MACROBLOCKD *x);
674
675 void vp8_tokenize_mb(VP8_COMP *, MACROBLOCKD *, TOKENEXTRA **);
676
677 void vp8_set_speed_features(VP8_COMP *cpi);
678
679 #if CONFIG_DEBUG
680 #define CHECK_MEM_ERROR(lval,expr) do {\
681         lval = (expr); \
682         if(!lval) \
683             vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,\
684                                "Failed to allocate "#lval" at %s:%d", \
685                                __FILE__,__LINE__);\
686     } while(0)
687 #else
688 #define CHECK_MEM_ERROR(lval,expr) do {\
689         lval = (expr); \
690         if(!lval) \
691             vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,\
692                                "Failed to allocate "#lval);\
693     } while(0)
694 #endif
695 #endif