2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
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.
12 #include "vpx_config.h"
13 #include "vp8/common/onyxc_int.h"
15 #include "vp8/common/systemdependent.h"
17 #include "vp8/common/alloccommon.h"
19 #include "firstpass.h"
21 #include "vpx_scale/vpxscale.h"
22 #include "vp8/common/extend.h"
24 #include "vp8/common/quant_common.h"
25 #include "segmentation.h"
26 #include "vp8/common/g_common.h"
27 #include "vpx_scale/yv12extend.h"
29 #include "vp8/common/postproc.h"
31 #include "vpx_mem/vpx_mem.h"
32 #include "vp8/common/swapyv12buffer.h"
33 #include "vp8/common/threading.h"
34 #include "vpx_ports/vpx_timer.h"
35 #include "temporal_filter.h"
37 #include "vpx_ports/arm.h"
39 #if CONFIG_MULTI_RES_ENCODING
40 #include "mr_dissim.h"
47 #if CONFIG_RUNTIME_CPU_DETECT
48 #define IF_RTCD(x) (x)
49 #define RTCD(x) &cpi->common.rtcd.x
51 #define IF_RTCD(x) NULL
55 extern void vp8cx_pick_filter_level_fast(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
56 extern void vp8cx_set_alt_lf_level(VP8_COMP *cpi, int filt_val);
57 extern void vp8cx_pick_filter_level(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
59 extern void vp8_dmachine_specific_config(VP8_COMP *cpi);
60 extern void vp8_cmachine_specific_config(VP8_COMP *cpi);
61 extern void vp8_deblock_frame(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *post, int filt_lvl, int low_var_thresh, int flag);
62 extern void print_parms(VP8_CONFIG *ocf, char *filenam);
63 extern unsigned int vp8_get_processor_freq();
64 extern void print_tree_update_probs();
65 extern void vp8cx_create_encoder_threads(VP8_COMP *cpi);
66 extern void vp8cx_remove_encoder_threads(VP8_COMP *cpi);
68 extern void vp8_yv12_copy_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
69 extern void vp8_yv12_copy_src_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
72 int vp8_estimate_entropy_savings(VP8_COMP *cpi);
73 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd);
75 extern void vp8_temporal_filter_prepare_c(VP8_COMP *cpi, int distance);
77 static void set_default_lf_deltas(VP8_COMP *cpi);
79 extern const int vp8_gf_interval_table[101];
81 #if CONFIG_INTERNAL_STATS
84 extern double vp8_calc_ssim
86 YV12_BUFFER_CONFIG *source,
87 YV12_BUFFER_CONFIG *dest,
90 const vp8_variance_rtcd_vtable_t *rtcd
94 extern double vp8_calc_ssimg
96 YV12_BUFFER_CONFIG *source,
97 YV12_BUFFER_CONFIG *dest,
101 const vp8_variance_rtcd_vtable_t *rtcd
108 #ifdef OUTPUT_YUV_SRC
119 extern int skip_true_count;
120 extern int skip_false_count;
125 extern int intra_mode_stats[10][10][10];
129 unsigned int frames_at_speed[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
130 unsigned int tot_pm = 0;
131 unsigned int cnt_pm = 0;
132 unsigned int tot_ef = 0;
133 unsigned int cnt_ef = 0;
137 extern unsigned __int64 Sectionbits[50];
138 extern int y_modes[5] ;
139 extern int uv_modes[4] ;
140 extern int b_modes[10] ;
142 extern int inter_y_modes[10] ;
143 extern int inter_uv_modes[4] ;
144 extern unsigned int inter_b_modes[15];
147 extern void (*vp8_short_fdct4x4)(short *input, short *output, int pitch);
148 extern void (*vp8_short_fdct8x4)(short *input, short *output, int pitch);
150 extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
152 extern const int qrounding_factors[129];
153 extern const int qzbin_factors[129];
154 extern void vp8cx_init_quantizer(VP8_COMP *cpi);
155 extern const int vp8cx_base_skip_false_prob[128];
157 // Tables relating active max Q to active min Q
158 static const int kf_low_motion_minq[QINDEX_RANGE] =
160 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
161 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
162 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
163 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
164 3,3,3,3,3,3,4,4,4,5,5,5,5,5,6,6,
165 6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
166 11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
167 16,16,17,17,18,18,18,18,19,20,20,21,21,22,23,23
169 static const int kf_high_motion_minq[QINDEX_RANGE] =
171 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
172 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
173 1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,
174 3,3,3,3,4,4,4,4,5,5,5,5,5,5,6,6,
175 6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
176 11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
177 16,16,17,17,18,18,18,18,19,19,20,20,20,20,21,21,
178 21,21,22,22,23,23,24,25,25,26,26,27,28,28,29,30
180 static const int gf_low_motion_minq[QINDEX_RANGE] =
182 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
183 3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,
184 7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,
185 11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,
186 19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,
187 27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,
188 35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,
189 43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58
191 static const int gf_mid_motion_minq[QINDEX_RANGE] =
193 0,0,0,0,1,1,1,1,1,1,2,2,3,3,3,4,
194 4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
195 9,10,10,10,10,11,11,11,12,12,12,12,13,13,13,14,
196 14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,
197 22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,
198 30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,
199 38,39,39,40,40,41,41,42,42,43,43,44,45,46,47,48,
200 49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64
202 static const int gf_high_motion_minq[QINDEX_RANGE] =
204 0,0,0,0,1,1,1,1,1,2,2,2,3,3,3,4,
205 4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
206 9,10,10,10,11,11,12,12,13,13,14,14,15,15,16,16,
207 17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,
208 25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,
209 33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,
210 41,41,42,42,43,44,45,46,47,48,49,50,51,52,53,54,
211 55,56,57,58,59,60,62,64,66,68,70,72,74,76,78,80
213 static const int inter_minq[QINDEX_RANGE] =
215 0,0,1,1,2,3,3,4,4,5,6,6,7,8,8,9,
216 9,10,11,11,12,13,13,14,15,15,16,17,17,18,19,20,
217 20,21,22,22,23,24,24,25,26,27,27,28,29,30,30,31,
218 32,33,33,34,35,36,36,37,38,39,39,40,41,42,42,43,
219 44,45,46,46,47,48,49,50,50,51,52,53,54,55,55,56,
220 57,58,59,60,60,61,62,63,64,65,66,67,67,68,69,70,
221 71,72,73,74,75,75,76,77,78,79,80,81,82,83,84,85,
222 86,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
225 void vp8_initialize()
227 static int init_done = 0;
231 vp8_scale_machine_specific_config();
232 vp8_initialize_common();
233 //vp8_dmachine_specific_config();
234 vp8_tokenize_initialize();
239 #ifdef PACKET_TESTING
240 extern FILE *vpxlogc;
243 static void save_layer_context(VP8_COMP *cpi)
245 LAYER_CONTEXT *lc = &cpi->layer_context[cpi->current_layer];
247 // Save layer dependent coding state
248 lc->target_bandwidth = cpi->target_bandwidth;
249 //lc->target_bandwidth = cpi->oxcf.target_bandwidth;
250 lc->starting_buffer_level = cpi->oxcf.starting_buffer_level;
251 lc->optimal_buffer_level = cpi->oxcf.optimal_buffer_level;
252 lc->maximum_buffer_size = cpi->oxcf.maximum_buffer_size;
253 lc->buffer_level = cpi->buffer_level;
254 lc->bits_off_target = cpi->bits_off_target;
255 lc->total_actual_bits = cpi->total_actual_bits;
256 lc->worst_quality = cpi->worst_quality;
257 lc->active_worst_quality = cpi->active_worst_quality;
258 lc->best_quality = cpi->best_quality;
259 lc->active_best_quality = cpi->active_best_quality;
260 lc->ni_av_qi = cpi->ni_av_qi;
261 lc->ni_tot_qi = cpi->ni_tot_qi;
262 lc->ni_frames = cpi->ni_frames;
263 lc->avg_frame_qindex = cpi->avg_frame_qindex;
264 lc->rate_correction_factor = cpi->rate_correction_factor;
265 lc->key_frame_rate_correction_factor = cpi->key_frame_rate_correction_factor;
266 lc->gf_rate_correction_factor = cpi->gf_rate_correction_factor;
267 lc->zbin_over_quant = cpi->zbin_over_quant;
268 lc->inter_frame_target = cpi->inter_frame_target;
269 lc->total_byte_count = cpi->total_byte_count;
270 lc->filter_level = cpi->common.filter_level;
272 lc->last_frame_percent_intra = cpi->last_frame_percent_intra;
274 memcpy (lc->count_mb_ref_frame_usage,
275 cpi->count_mb_ref_frame_usage,
276 sizeof(cpi->count_mb_ref_frame_usage));
279 static void restore_layer_context(VP8_COMP *cpi, const int layer)
281 LAYER_CONTEXT *lc = &cpi->layer_context[layer];
283 // Restore layer dependent coding state
284 cpi->current_layer = layer;
285 cpi->target_bandwidth = lc->target_bandwidth;
286 cpi->oxcf.target_bandwidth = lc->target_bandwidth;
287 cpi->oxcf.starting_buffer_level = lc->starting_buffer_level;
288 cpi->oxcf.optimal_buffer_level = lc->optimal_buffer_level;
289 cpi->oxcf.maximum_buffer_size = lc->maximum_buffer_size;
290 cpi->buffer_level = lc->buffer_level;
291 cpi->bits_off_target = lc->bits_off_target;
292 cpi->total_actual_bits = lc->total_actual_bits;
293 //cpi->worst_quality = lc->worst_quality;
294 cpi->active_worst_quality = lc->active_worst_quality;
295 //cpi->best_quality = lc->best_quality;
296 cpi->active_best_quality = lc->active_best_quality;
297 cpi->ni_av_qi = lc->ni_av_qi;
298 cpi->ni_tot_qi = lc->ni_tot_qi;
299 cpi->ni_frames = lc->ni_frames;
300 cpi->avg_frame_qindex = lc->avg_frame_qindex;
301 cpi->rate_correction_factor = lc->rate_correction_factor;
302 cpi->key_frame_rate_correction_factor = lc->key_frame_rate_correction_factor;
303 cpi->gf_rate_correction_factor = lc->gf_rate_correction_factor;
304 cpi->zbin_over_quant = lc->zbin_over_quant;
305 cpi->inter_frame_target = lc->inter_frame_target;
306 cpi->total_byte_count = lc->total_byte_count;
307 cpi->common.filter_level = lc->filter_level;
309 cpi->last_frame_percent_intra = lc->last_frame_percent_intra;
311 memcpy (cpi->count_mb_ref_frame_usage,
312 lc->count_mb_ref_frame_usage,
313 sizeof(cpi->count_mb_ref_frame_usage));
316 static void setup_features(VP8_COMP *cpi)
318 // Set up default state for MB feature flags
319 cpi->mb.e_mbd.segmentation_enabled = 0;
320 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
321 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
322 vpx_memset(cpi->mb.e_mbd.mb_segment_tree_probs, 255, sizeof(cpi->mb.e_mbd.mb_segment_tree_probs));
323 vpx_memset(cpi->mb.e_mbd.segment_feature_data, 0, sizeof(cpi->mb.e_mbd.segment_feature_data));
325 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 0;
326 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
327 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
328 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
329 vpx_memset(cpi->mb.e_mbd.last_ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
330 vpx_memset(cpi->mb.e_mbd.last_mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
332 set_default_lf_deltas(cpi);
337 static void dealloc_compressor_data(VP8_COMP *cpi)
339 vpx_free(cpi->tplist);
342 // Delete last frame MV storage buffers
346 vpx_free(cpi->lf_ref_frame_sign_bias);
347 cpi->lf_ref_frame_sign_bias = 0;
349 vpx_free(cpi->lf_ref_frame);
350 cpi->lf_ref_frame = 0;
352 // Delete sementation map
353 vpx_free(cpi->segmentation_map);
354 cpi->segmentation_map = 0;
356 vpx_free(cpi->active_map);
359 vp8_de_alloc_frame_buffers(&cpi->common);
361 vp8_yv12_de_alloc_frame_buffer(&cpi->pick_lf_lvl_frame);
362 vp8_yv12_de_alloc_frame_buffer(&cpi->scaled_source);
363 #if VP8_TEMPORAL_ALT_REF
364 vp8_yv12_de_alloc_frame_buffer(&cpi->alt_ref_buffer);
366 vp8_lookahead_destroy(cpi->lookahead);
371 // Structure used to monitor GF usage
372 vpx_free(cpi->gf_active_flags);
373 cpi->gf_active_flags = 0;
375 // Activity mask based per mb zbin adjustments
376 vpx_free(cpi->mb_activity_map);
377 cpi->mb_activity_map = 0;
378 vpx_free(cpi->mb_norm_activity_map);
379 cpi->mb_norm_activity_map = 0;
381 vpx_free(cpi->mb.pip);
384 #if !(CONFIG_REALTIME_ONLY)
385 vpx_free(cpi->twopass.total_stats);
386 cpi->twopass.total_stats = 0;
388 vpx_free(cpi->twopass.total_left_stats);
389 cpi->twopass.total_left_stats = 0;
391 vpx_free(cpi->twopass.this_frame_stats);
392 cpi->twopass.this_frame_stats = 0;
396 static void enable_segmentation(VP8_PTR ptr)
398 VP8_COMP *cpi = (VP8_COMP *)(ptr);
400 // Set the appropriate feature bit
401 cpi->mb.e_mbd.segmentation_enabled = 1;
402 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
403 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
405 static void disable_segmentation(VP8_PTR ptr)
407 VP8_COMP *cpi = (VP8_COMP *)(ptr);
409 // Clear the appropriate feature bit
410 cpi->mb.e_mbd.segmentation_enabled = 0;
413 // Valid values for a segment are 0 to 3
414 // Segmentation map is arrange as [Rows][Columns]
415 static void set_segmentation_map(VP8_PTR ptr, unsigned char *segmentation_map)
417 VP8_COMP *cpi = (VP8_COMP *)(ptr);
419 // Copy in the new segmentation map
420 vpx_memcpy(cpi->segmentation_map, segmentation_map, (cpi->common.mb_rows * cpi->common.mb_cols));
422 // Signal that the map should be updated.
423 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
424 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
427 // The values given for each segment can be either deltas (from the default value chosen for the frame) or absolute values.
429 // Valid range for abs values is (0-127 for MB_LVL_ALT_Q) , (0-63 for SEGMENT_ALT_LF)
430 // Valid range for delta values are (+/-127 for MB_LVL_ALT_Q) , (+/-63 for SEGMENT_ALT_LF)
432 // abs_delta = SEGMENT_DELTADATA (deltas) abs_delta = SEGMENT_ABSDATA (use the absolute values given).
435 static void set_segment_data(VP8_PTR ptr, signed char *feature_data, unsigned char abs_delta)
437 VP8_COMP *cpi = (VP8_COMP *)(ptr);
439 cpi->mb.e_mbd.mb_segement_abs_delta = abs_delta;
440 vpx_memcpy(cpi->segment_feature_data, feature_data, sizeof(cpi->segment_feature_data));
444 static void segmentation_test_function(VP8_PTR ptr)
446 VP8_COMP *cpi = (VP8_COMP *)(ptr);
448 unsigned char *seg_map;
449 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
451 // Create a temporary map for segmentation data.
452 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
454 // MB loop to set local segmentation map
455 /*for ( i = 0; i < cpi->common.mb_rows; i++ )
457 for ( j = 0; j < cpi->common.mb_cols; j++ )
459 //seg_map[(i*cpi->common.mb_cols) + j] = (j % 2) + ((i%2)* 2);
460 //if ( j < cpi->common.mb_cols/2 )
462 // Segment 1 around the edge else 0
463 if ( (i == 0) || (j == 0) || (i == (cpi->common.mb_rows-1)) || (j == (cpi->common.mb_cols-1)) )
464 seg_map[(i*cpi->common.mb_cols) + j] = 1;
465 //else if ( (i < 2) || (j < 2) || (i > (cpi->common.mb_rows-3)) || (j > (cpi->common.mb_cols-3)) )
466 // seg_map[(i*cpi->common.mb_cols) + j] = 2;
467 //else if ( (i < 5) || (j < 5) || (i > (cpi->common.mb_rows-6)) || (j > (cpi->common.mb_cols-6)) )
468 // seg_map[(i*cpi->common.mb_cols) + j] = 3;
470 seg_map[(i*cpi->common.mb_cols) + j] = 0;
474 // Set the segmentation Map
475 set_segmentation_map(ptr, seg_map);
477 // Activate segmentation.
478 enable_segmentation(ptr);
480 // Set up the quant segment data
481 feature_data[MB_LVL_ALT_Q][0] = 0;
482 feature_data[MB_LVL_ALT_Q][1] = 4;
483 feature_data[MB_LVL_ALT_Q][2] = 0;
484 feature_data[MB_LVL_ALT_Q][3] = 0;
485 // Set up the loop segment data
486 feature_data[MB_LVL_ALT_LF][0] = 0;
487 feature_data[MB_LVL_ALT_LF][1] = 0;
488 feature_data[MB_LVL_ALT_LF][2] = 0;
489 feature_data[MB_LVL_ALT_LF][3] = 0;
491 // Initialise the feature data structure
492 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
493 set_segment_data(ptr, &feature_data[0][0], SEGMENT_DELTADATA);
495 // Delete sementation map
502 // A simple function to cyclically refresh the background at a lower Q
503 static void cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment)
505 unsigned char *seg_map;
506 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
508 int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
509 int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
511 // Create a temporary map for segmentation data.
512 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
514 cpi->cyclic_refresh_q = Q;
516 for (i = Q; i > 0; i--)
518 if (vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*(Q + 128)) / 64))
519 //if ( vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*((2*Q)+96))/64) )
525 cpi->cyclic_refresh_q = i;
527 // Only update for inter frames
528 if (cpi->common.frame_type != KEY_FRAME)
530 // Cycle through the macro_block rows
531 // MB loop to set local segmentation map
532 for (i = cpi->cyclic_refresh_mode_index; i < mbs_in_frame; i++)
534 // If the MB is as a candidate for clean up then mark it for possible boost/refresh (segment 1)
535 // The segment id may get reset to 0 later if the MB gets coded anything other than last frame 0,0
536 // as only (last frame 0,0) MBs are eligable for refresh : that is to say Mbs likely to be background blocks.
537 if (cpi->cyclic_refresh_map[i] == 0)
545 // Skip blocks that have been refreshed recently anyway.
546 if (cpi->cyclic_refresh_map[i] < 0)
547 //cpi->cyclic_refresh_map[i] = cpi->cyclic_refresh_map[i] / 16;
548 cpi->cyclic_refresh_map[i]++;
559 // If we have gone through the frame reset to the start
560 cpi->cyclic_refresh_mode_index = i;
562 if (cpi->cyclic_refresh_mode_index >= mbs_in_frame)
563 cpi->cyclic_refresh_mode_index = 0;
566 // Set the segmentation Map
567 set_segmentation_map((VP8_PTR)cpi, seg_map);
569 // Activate segmentation.
570 enable_segmentation((VP8_PTR)cpi);
572 // Set up the quant segment data
573 feature_data[MB_LVL_ALT_Q][0] = 0;
574 feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
575 feature_data[MB_LVL_ALT_Q][2] = 0;
576 feature_data[MB_LVL_ALT_Q][3] = 0;
578 // Set up the loop segment data
579 feature_data[MB_LVL_ALT_LF][0] = 0;
580 feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
581 feature_data[MB_LVL_ALT_LF][2] = 0;
582 feature_data[MB_LVL_ALT_LF][3] = 0;
584 // Initialise the feature data structure
585 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
586 set_segment_data((VP8_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
588 // Delete sementation map
595 static void set_default_lf_deltas(VP8_COMP *cpi)
597 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 1;
598 cpi->mb.e_mbd.mode_ref_lf_delta_update = 1;
600 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
601 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
603 // Test of ref frame deltas
604 cpi->mb.e_mbd.ref_lf_deltas[INTRA_FRAME] = 2;
605 cpi->mb.e_mbd.ref_lf_deltas[LAST_FRAME] = 0;
606 cpi->mb.e_mbd.ref_lf_deltas[GOLDEN_FRAME] = -2;
607 cpi->mb.e_mbd.ref_lf_deltas[ALTREF_FRAME] = -2;
609 cpi->mb.e_mbd.mode_lf_deltas[0] = 4; // BPRED
610 cpi->mb.e_mbd.mode_lf_deltas[1] = -2; // Zero
611 cpi->mb.e_mbd.mode_lf_deltas[2] = 2; // New mv
612 cpi->mb.e_mbd.mode_lf_deltas[3] = 4; // Split mv
615 void vp8_set_speed_features(VP8_COMP *cpi)
617 SPEED_FEATURES *sf = &cpi->sf;
618 int Mode = cpi->compressor_speed;
619 int Speed = cpi->Speed;
621 VP8_COMMON *cm = &cpi->common;
622 int last_improved_quant = sf->improved_quant;
625 // Initialise default mode frequency sampling variables
626 for (i = 0; i < MAX_MODES; i ++)
628 cpi->mode_check_freq[i] = 0;
629 cpi->mode_test_hit_counts[i] = 0;
630 cpi->mode_chosen_counts[i] = 0;
633 cpi->mbs_tested_so_far = 0;
635 // best quality defaults
637 sf->search_method = NSTEP;
638 sf->improved_quant = 1;
639 sf->improved_dct = 1;
642 sf->quarter_pixel_search = 1;
643 sf->half_pixel_search = 1;
644 sf->iterative_sub_pixel = 1;
645 sf->optimize_coefficients = 1;
646 sf->use_fastquant_for_pick = 0;
647 sf->no_skip_block4x4_search = 1;
650 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
651 sf->improved_mv_pred = 1;
653 // default thresholds to 0
654 for (i = 0; i < MAX_MODES; i++)
655 sf->thresh_mult[i] = 0;
657 /* Count enabled references */
659 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
661 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
663 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
668 #if !(CONFIG_REALTIME_ONLY)
669 case 0: // best quality mode
670 sf->thresh_mult[THR_ZERO1 ] = 0;
671 sf->thresh_mult[THR_ZERO2 ] = 0;
672 sf->thresh_mult[THR_ZERO3 ] = 0;
673 sf->thresh_mult[THR_NEAREST1 ] = 0;
674 sf->thresh_mult[THR_NEAREST2 ] = 0;
675 sf->thresh_mult[THR_NEAREST3 ] = 0;
676 sf->thresh_mult[THR_NEAR1 ] = 0;
677 sf->thresh_mult[THR_NEAR2 ] = 0;
678 sf->thresh_mult[THR_NEAR3 ] = 0;
680 sf->thresh_mult[THR_DC ] = 0;
682 sf->thresh_mult[THR_V_PRED ] = 1000;
683 sf->thresh_mult[THR_H_PRED ] = 1000;
684 sf->thresh_mult[THR_B_PRED ] = 2000;
685 sf->thresh_mult[THR_TM ] = 1000;
687 sf->thresh_mult[THR_NEW1 ] = 1000;
688 sf->thresh_mult[THR_NEW2 ] = 1000;
689 sf->thresh_mult[THR_NEW3 ] = 1000;
691 sf->thresh_mult[THR_SPLIT1 ] = 2500;
692 sf->thresh_mult[THR_SPLIT2 ] = 5000;
693 sf->thresh_mult[THR_SPLIT3 ] = 5000;
697 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
701 sf->thresh_mult[THR_NEAREST1 ] = 0;
702 sf->thresh_mult[THR_ZERO1 ] = 0;
703 sf->thresh_mult[THR_DC ] = 0;
704 sf->thresh_mult[THR_NEAR1 ] = 0;
705 sf->thresh_mult[THR_V_PRED ] = 1000;
706 sf->thresh_mult[THR_H_PRED ] = 1000;
707 sf->thresh_mult[THR_B_PRED ] = 2500;
708 sf->thresh_mult[THR_TM ] = 1000;
710 sf->thresh_mult[THR_NEAREST2 ] = 1000;
711 sf->thresh_mult[THR_NEAREST3 ] = 1000;
713 sf->thresh_mult[THR_ZERO2 ] = 1000;
714 sf->thresh_mult[THR_ZERO3 ] = 1000;
715 sf->thresh_mult[THR_NEAR2 ] = 1000;
716 sf->thresh_mult[THR_NEAR3 ] = 1000;
719 sf->thresh_mult[THR_ZERO1 ] = 0;
720 sf->thresh_mult[THR_ZERO2 ] = 0;
721 sf->thresh_mult[THR_ZERO3 ] = 0;
722 sf->thresh_mult[THR_NEAREST1 ] = 0;
723 sf->thresh_mult[THR_NEAREST2 ] = 0;
724 sf->thresh_mult[THR_NEAREST3 ] = 0;
725 sf->thresh_mult[THR_NEAR1 ] = 0;
726 sf->thresh_mult[THR_NEAR2 ] = 0;
727 sf->thresh_mult[THR_NEAR3 ] = 0;
729 // sf->thresh_mult[THR_DC ] = 0;
731 // sf->thresh_mult[THR_V_PRED ] = 1000;
732 // sf->thresh_mult[THR_H_PRED ] = 1000;
733 // sf->thresh_mult[THR_B_PRED ] = 2000;
734 // sf->thresh_mult[THR_TM ] = 1000;
736 sf->thresh_mult[THR_NEW1 ] = 1000;
737 sf->thresh_mult[THR_NEW2 ] = 1000;
738 sf->thresh_mult[THR_NEW3 ] = 1000;
740 sf->thresh_mult[THR_SPLIT1 ] = 1700;
741 sf->thresh_mult[THR_SPLIT2 ] = 4500;
742 sf->thresh_mult[THR_SPLIT3 ] = 4500;
744 sf->thresh_mult[THR_NEW1 ] = 1500;
745 sf->thresh_mult[THR_NEW2 ] = 1500;
746 sf->thresh_mult[THR_NEW3 ] = 1500;
748 sf->thresh_mult[THR_SPLIT1 ] = 5000;
749 sf->thresh_mult[THR_SPLIT2 ] = 10000;
750 sf->thresh_mult[THR_SPLIT3 ] = 10000;
755 /* Disable coefficient optimization above speed 0 */
756 sf->optimize_coefficients = 0;
757 sf->use_fastquant_for_pick = 1;
758 sf->no_skip_block4x4_search = 0;
762 cpi->mode_check_freq[THR_SPLIT2] = 2;
763 cpi->mode_check_freq[THR_SPLIT3] = 2;
764 cpi->mode_check_freq[THR_SPLIT1 ] = 0;
769 cpi->mode_check_freq[THR_SPLIT2] = 4;
770 cpi->mode_check_freq[THR_SPLIT3] = 4;
771 cpi->mode_check_freq[THR_SPLIT1 ] = 2;
773 sf->thresh_mult[THR_TM ] = 1500;
774 sf->thresh_mult[THR_V_PRED ] = 1500;
775 sf->thresh_mult[THR_H_PRED ] = 1500;
776 sf->thresh_mult[THR_B_PRED ] = 5000;
780 sf->thresh_mult[THR_NEW1 ] = 2000;
781 sf->thresh_mult[THR_SPLIT1 ] = 10000;
786 sf->thresh_mult[THR_NEAREST2 ] = 1500;
787 sf->thresh_mult[THR_ZERO2 ] = 1500;
788 sf->thresh_mult[THR_NEAR2 ] = 1500;
789 sf->thresh_mult[THR_NEW2 ] = 2000;
790 sf->thresh_mult[THR_SPLIT2 ] = 20000;
795 sf->thresh_mult[THR_NEAREST3 ] = 1500;
796 sf->thresh_mult[THR_ZERO3 ] = 1500;
797 sf->thresh_mult[THR_NEAR3 ] = 1500;
798 sf->thresh_mult[THR_NEW3 ] = 2000;
799 sf->thresh_mult[THR_SPLIT3 ] = 20000;
805 cpi->mode_check_freq[THR_SPLIT2] = 15;
806 cpi->mode_check_freq[THR_SPLIT3] = 15;
807 cpi->mode_check_freq[THR_SPLIT1 ] = 7;
809 sf->thresh_mult[THR_TM ] = 2000;
810 sf->thresh_mult[THR_V_PRED ] = 2000;
811 sf->thresh_mult[THR_H_PRED ] = 2000;
812 sf->thresh_mult[THR_B_PRED ] = 7500;
816 sf->thresh_mult[THR_NEW1 ] = 2000;
817 sf->thresh_mult[THR_SPLIT1 ] = 25000;
822 sf->thresh_mult[THR_NEAREST2 ] = 2000;
823 sf->thresh_mult[THR_ZERO2 ] = 2000;
824 sf->thresh_mult[THR_NEAR2 ] = 2000;
825 sf->thresh_mult[THR_NEW2 ] = 2500;
826 sf->thresh_mult[THR_SPLIT2 ] = 50000;
831 sf->thresh_mult[THR_NEAREST3 ] = 2000;
832 sf->thresh_mult[THR_ZERO3 ] = 2000;
833 sf->thresh_mult[THR_NEAR3 ] = 2000;
834 sf->thresh_mult[THR_NEW3 ] = 2500;
835 sf->thresh_mult[THR_SPLIT3 ] = 50000;
838 sf->improved_quant = 0;
839 sf->improved_dct = 0;
841 // Only do recode loop on key frames, golden frames and
849 sf->thresh_mult[THR_SPLIT3 ] = INT_MAX;
850 sf->thresh_mult[THR_SPLIT2 ] = INT_MAX;
851 sf->thresh_mult[THR_SPLIT1 ] = INT_MAX;
853 cpi->mode_check_freq[THR_V_PRED] = 0;
854 cpi->mode_check_freq[THR_H_PRED] = 0;
855 cpi->mode_check_freq[THR_B_PRED] = 0;
856 cpi->mode_check_freq[THR_NEAR2] = 0;
857 cpi->mode_check_freq[THR_NEW2] = 0;
858 cpi->mode_check_freq[THR_NEAR3] = 0;
859 cpi->mode_check_freq[THR_NEW3] = 0;
862 sf->recode_loop = 0; // recode loop off
863 sf->RD = 0; // Turn rd off
869 sf->auto_filter = 0; // Faster selection of loop filter
871 cpi->mode_check_freq[THR_V_PRED] = 2;
872 cpi->mode_check_freq[THR_H_PRED] = 2;
873 cpi->mode_check_freq[THR_B_PRED] = 2;
877 cpi->mode_check_freq[THR_NEAR2] = 2;
878 cpi->mode_check_freq[THR_NEW2] = 4;
883 cpi->mode_check_freq[THR_NEAR3] = 2;
884 cpi->mode_check_freq[THR_NEW3] = 4;
889 sf->thresh_mult[THR_NEAREST2 ] = 2000;
890 sf->thresh_mult[THR_ZERO2 ] = 2000;
891 sf->thresh_mult[THR_NEAR2 ] = 2000;
892 sf->thresh_mult[THR_NEW2 ] = 4000;
897 sf->thresh_mult[THR_NEAREST3 ] = 2000;
898 sf->thresh_mult[THR_ZERO3 ] = 2000;
899 sf->thresh_mult[THR_NEAR3 ] = 2000;
900 sf->thresh_mult[THR_NEW3 ] = 4000;
907 sf->optimize_coefficients = 0;
910 sf->iterative_sub_pixel = 1;
911 sf->thresh_mult[THR_NEAREST1 ] = 0;
912 sf->thresh_mult[THR_ZERO1 ] = 0;
913 sf->thresh_mult[THR_DC ] = 0;
914 sf->thresh_mult[THR_TM ] = 0;
915 sf->thresh_mult[THR_NEAR1 ] = 0;
916 sf->thresh_mult[THR_V_PRED ] = 1000;
917 sf->thresh_mult[THR_H_PRED ] = 1000;
918 sf->thresh_mult[THR_B_PRED ] = 2500;
919 sf->thresh_mult[THR_NEAREST2 ] = 1000;
920 sf->thresh_mult[THR_ZERO2 ] = 1000;
921 sf->thresh_mult[THR_NEAR2 ] = 1000;
922 sf->thresh_mult[THR_NEAREST3 ] = 1000;
923 sf->thresh_mult[THR_ZERO3 ] = 1000;
924 sf->thresh_mult[THR_NEAR3 ] = 1000;
925 sf->thresh_mult[THR_NEW1 ] = 2000;
926 sf->thresh_mult[THR_NEW2 ] = 2000;
927 sf->thresh_mult[THR_NEW3 ] = 2000;
928 sf->thresh_mult[THR_SPLIT1 ] = 5000;
929 sf->thresh_mult[THR_SPLIT2 ] = 10000;
930 sf->thresh_mult[THR_SPLIT3 ] = 10000;
931 sf->search_method = NSTEP;
935 cpi->mode_check_freq[THR_SPLIT2] = 4;
936 cpi->mode_check_freq[THR_SPLIT3] = 4;
937 cpi->mode_check_freq[THR_SPLIT1 ] = 2;
939 sf->thresh_mult[THR_DC ] = 0;
940 sf->thresh_mult[THR_TM ] = 1000;
941 sf->thresh_mult[THR_V_PRED ] = 2000;
942 sf->thresh_mult[THR_H_PRED ] = 2000;
943 sf->thresh_mult[THR_B_PRED ] = 5000;
947 sf->thresh_mult[THR_NEAREST1 ] = 0;
948 sf->thresh_mult[THR_ZERO1 ] = 0;
949 sf->thresh_mult[THR_NEAR1 ] = 0;
950 sf->thresh_mult[THR_NEW1 ] = 2000;
951 sf->thresh_mult[THR_SPLIT1 ] = 10000;
956 sf->thresh_mult[THR_NEAREST2 ] = 1000;
957 sf->thresh_mult[THR_ZERO2 ] = 1000;
958 sf->thresh_mult[THR_NEAR2 ] = 1000;
959 sf->thresh_mult[THR_NEW2 ] = 2000;
960 sf->thresh_mult[THR_SPLIT2 ] = 20000;
965 sf->thresh_mult[THR_NEAREST3 ] = 1000;
966 sf->thresh_mult[THR_ZERO3 ] = 1000;
967 sf->thresh_mult[THR_NEAR3 ] = 1000;
968 sf->thresh_mult[THR_NEW3 ] = 2000;
969 sf->thresh_mult[THR_SPLIT3 ] = 20000;
972 sf->improved_quant = 0;
973 sf->improved_dct = 0;
975 sf->use_fastquant_for_pick = 1;
976 sf->no_skip_block4x4_search = 0;
982 cpi->mode_check_freq[THR_SPLIT1 ] = 7;
983 cpi->mode_check_freq[THR_SPLIT2] = 15;
984 cpi->mode_check_freq[THR_SPLIT3] = 15;
986 sf->thresh_mult[THR_TM ] = 2000;
987 sf->thresh_mult[THR_V_PRED ] = 2000;
988 sf->thresh_mult[THR_H_PRED ] = 2000;
989 sf->thresh_mult[THR_B_PRED ] = 5000;
993 sf->thresh_mult[THR_NEW1 ] = 2000;
994 sf->thresh_mult[THR_SPLIT1 ] = 25000;
999 sf->thresh_mult[THR_NEAREST2 ] = 2000;
1000 sf->thresh_mult[THR_ZERO2 ] = 2000;
1001 sf->thresh_mult[THR_NEAR2 ] = 2000;
1002 sf->thresh_mult[THR_NEW2 ] = 2500;
1003 sf->thresh_mult[THR_SPLIT2 ] = 50000;
1008 sf->thresh_mult[THR_NEAREST3 ] = 2000;
1009 sf->thresh_mult[THR_ZERO3 ] = 2000;
1010 sf->thresh_mult[THR_NEAR3 ] = 2000;
1011 sf->thresh_mult[THR_NEW3 ] = 2500;
1012 sf->thresh_mult[THR_SPLIT3 ] = 50000;
1019 sf->auto_filter = 0; // Faster selection of loop filter
1021 cpi->mode_check_freq[THR_V_PRED] = 2;
1022 cpi->mode_check_freq[THR_H_PRED] = 2;
1023 cpi->mode_check_freq[THR_B_PRED] = 2;
1027 cpi->mode_check_freq[THR_NEAR2] = 2;
1028 cpi->mode_check_freq[THR_NEW2] = 4;
1033 cpi->mode_check_freq[THR_NEAR3] = 2;
1034 cpi->mode_check_freq[THR_NEW3] = 4;
1037 sf->thresh_mult[THR_SPLIT1 ] = INT_MAX;
1038 sf->thresh_mult[THR_SPLIT2 ] = INT_MAX;
1039 sf->thresh_mult[THR_SPLIT3 ] = INT_MAX;
1047 sf->auto_filter = 1;
1052 sf->auto_filter = 0; // Faster selection of loop filter
1054 sf->search_method = HEX;
1055 //sf->search_method = DIAMOND;
1057 sf->iterative_sub_pixel = 0;
1059 cpi->mode_check_freq[THR_V_PRED] = 4;
1060 cpi->mode_check_freq[THR_H_PRED] = 4;
1061 cpi->mode_check_freq[THR_B_PRED] = 4;
1063 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
1065 cpi->mode_check_freq[THR_NEAR2] = 2;
1066 cpi->mode_check_freq[THR_NEW2] = 4;
1069 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
1071 cpi->mode_check_freq[THR_NEAR3] = 2;
1072 cpi->mode_check_freq[THR_NEW3] = 4;
1075 sf->thresh_mult[THR_TM ] = 2000;
1076 sf->thresh_mult[THR_B_PRED ] = 5000;
1078 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
1080 sf->thresh_mult[THR_NEAREST2 ] = 2000;
1081 sf->thresh_mult[THR_ZERO2 ] = 2000;
1082 sf->thresh_mult[THR_NEAR2 ] = 2000;
1083 sf->thresh_mult[THR_NEW2 ] = 4000;
1086 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
1088 sf->thresh_mult[THR_NEAREST3 ] = 2000;
1089 sf->thresh_mult[THR_ZERO3 ] = 2000;
1090 sf->thresh_mult[THR_NEAR3 ] = 2000;
1091 sf->thresh_mult[THR_NEW3 ] = 4000;
1097 // Disable split MB intra prediction mode
1098 sf->thresh_mult[THR_B_PRED] = INT_MAX;
1103 unsigned int i, sum = 0;
1104 unsigned int total_mbs = cm->MBs;
1110 if (cpi->oxcf.encode_breakout > 2000)
1111 min = cpi->oxcf.encode_breakout;
1115 for (i = 0; i < min; i++)
1117 sum += cpi->error_bins[i];
1123 // i starts from 2 to make sure thresh started from 2048
1124 for (; i < 1024; i++)
1126 sum += cpi->error_bins[i];
1128 if (10 * sum >= (unsigned int)(cpi->Speed - 6)*(total_mbs - total_skip))
1140 sf->thresh_mult[THR_NEW1 ] = thresh;
1141 sf->thresh_mult[THR_NEAREST1 ] = thresh >> 1;
1142 sf->thresh_mult[THR_NEAR1 ] = thresh >> 1;
1147 sf->thresh_mult[THR_NEW2] = thresh << 1;
1148 sf->thresh_mult[THR_NEAREST2 ] = thresh;
1149 sf->thresh_mult[THR_NEAR2 ] = thresh;
1154 sf->thresh_mult[THR_NEW3] = thresh << 1;
1155 sf->thresh_mult[THR_NEAREST3 ] = thresh;
1156 sf->thresh_mult[THR_NEAR3 ] = thresh;
1159 // Disable other intra prediction modes
1160 sf->thresh_mult[THR_TM] = INT_MAX;
1161 sf->thresh_mult[THR_V_PRED] = INT_MAX;
1162 sf->thresh_mult[THR_H_PRED] = INT_MAX;
1164 sf->improved_mv_pred = 0;
1169 sf->quarter_pixel_search = 0;
1174 int Tmp = cpi->Speed - 8;
1179 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
1181 cpi->mode_check_freq[THR_ZERO2] = 1 << (Tmp - 1);
1182 cpi->mode_check_freq[THR_NEAREST2] = 1 << (Tmp - 1);
1183 cpi->mode_check_freq[THR_NEAR2] = 1 << Tmp;
1184 cpi->mode_check_freq[THR_NEW2] = 1 << (Tmp + 1);
1187 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
1189 cpi->mode_check_freq[THR_ZERO3] = 1 << (Tmp - 1);
1190 cpi->mode_check_freq[THR_NEAREST3] = 1 << (Tmp - 1);
1191 cpi->mode_check_freq[THR_NEAR3] = 1 << Tmp;
1192 cpi->mode_check_freq[THR_NEW3] = 1 << (Tmp + 1);
1195 cpi->mode_check_freq[THR_NEW1 ] = 1 << (Tmp - 1);
1198 cm->filter_type = NORMAL_LOOPFILTER;
1201 cm->filter_type = SIMPLE_LOOPFILTER;
1205 sf->half_pixel_search = 0; // This has a big hit on quality. Last resort
1208 vpx_memset(cpi->error_bins, 0, sizeof(cpi->error_bins));
1212 // Slow quant, dct and trellis not worthwhile for first pass
1213 // so make sure they are always turned off.
1214 if ( cpi->pass == 1 )
1216 sf->improved_quant = 0;
1217 sf->optimize_coefficients = 0;
1218 sf->improved_dct = 0;
1221 if (cpi->sf.search_method == NSTEP)
1223 vp8_init3smotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
1225 else if (cpi->sf.search_method == DIAMOND)
1227 vp8_init_dsmotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
1230 if (cpi->sf.improved_dct)
1232 cpi->mb.vp8_short_fdct8x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short8x4);
1233 cpi->mb.vp8_short_fdct4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short4x4);
1237 cpi->mb.vp8_short_fdct8x4 = FDCT_INVOKE(&cpi->rtcd.fdct, fast8x4);
1238 cpi->mb.vp8_short_fdct4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, fast4x4);
1241 cpi->mb.short_walsh4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, walsh_short4x4);
1243 if (cpi->sf.improved_quant)
1245 cpi->mb.quantize_b = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1247 cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1252 cpi->mb.quantize_b = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1254 cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1257 if (cpi->sf.improved_quant != last_improved_quant)
1258 vp8cx_init_quantizer(cpi);
1260 #if CONFIG_RUNTIME_CPU_DETECT
1261 cpi->mb.e_mbd.rtcd = &cpi->common.rtcd;
1264 if (cpi->sf.iterative_sub_pixel == 1)
1266 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step_iteratively;
1268 else if (cpi->sf.quarter_pixel_search)
1270 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step;
1272 else if (cpi->sf.half_pixel_search)
1274 cpi->find_fractional_mv_step = vp8_find_best_half_pixel_step;
1278 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1281 if (cpi->sf.optimize_coefficients == 1 && cpi->pass!=1)
1282 cpi->mb.optimize = 1;
1284 cpi->mb.optimize = 0;
1286 if (cpi->common.full_pixel)
1287 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1290 frames_at_speed[cpi->Speed]++;
1293 static void alloc_raw_frame_buffers(VP8_COMP *cpi)
1295 int width = (cpi->oxcf.Width + 15) & ~15;
1296 int height = (cpi->oxcf.Height + 15) & ~15;
1298 cpi->lookahead = vp8_lookahead_init(cpi->oxcf.Width, cpi->oxcf.Height,
1299 cpi->oxcf.lag_in_frames);
1301 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1302 "Failed to allocate lag buffers");
1304 #if VP8_TEMPORAL_ALT_REF
1306 if (vp8_yv12_alloc_frame_buffer(&cpi->alt_ref_buffer,
1307 width, height, VP8BORDERINPIXELS))
1308 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1309 "Failed to allocate altref buffer");
1314 static int vp8_alloc_partition_data(VP8_COMP *cpi)
1316 vpx_free(cpi->mb.pip);
1318 cpi->mb.pip = vpx_calloc((cpi->common.mb_cols + 1) *
1319 (cpi->common.mb_rows + 1),
1320 sizeof(PARTITION_INFO));
1324 cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
1329 void vp8_alloc_compressor_data(VP8_COMP *cpi)
1331 VP8_COMMON *cm = & cpi->common;
1333 int width = cm->Width;
1334 int height = cm->Height;
1336 if (vp8_alloc_frame_buffers(cm, width, height))
1337 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1338 "Failed to allocate frame buffers");
1340 if (vp8_alloc_partition_data(cpi))
1341 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1342 "Failed to allocate partition data");
1345 if ((width & 0xf) != 0)
1346 width += 16 - (width & 0xf);
1348 if ((height & 0xf) != 0)
1349 height += 16 - (height & 0xf);
1352 if (vp8_yv12_alloc_frame_buffer(&cpi->pick_lf_lvl_frame,
1353 width, height, VP8BORDERINPIXELS))
1354 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1355 "Failed to allocate last frame buffer");
1357 if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source,
1358 width, height, VP8BORDERINPIXELS))
1359 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1360 "Failed to allocate scaled source buffer");
1366 unsigned int tokens = cm->mb_rows * cm->mb_cols * 24 * 16;
1368 CHECK_MEM_ERROR(cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
1371 // Data used for real time vc mode to see if gf needs refreshing
1372 cpi->inter_zz_count = 0;
1373 cpi->gf_bad_count = 0;
1374 cpi->gf_update_recommended = 0;
1377 // Structures used to minitor GF usage
1378 vpx_free(cpi->gf_active_flags);
1379 CHECK_MEM_ERROR(cpi->gf_active_flags,
1380 vpx_calloc(1, cm->mb_rows * cm->mb_cols));
1381 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
1383 vpx_free(cpi->mb_activity_map);
1384 CHECK_MEM_ERROR(cpi->mb_activity_map,
1385 vpx_calloc(sizeof(unsigned int),
1386 cm->mb_rows * cm->mb_cols));
1388 vpx_free(cpi->mb_norm_activity_map);
1389 CHECK_MEM_ERROR(cpi->mb_norm_activity_map,
1390 vpx_calloc(sizeof(unsigned int),
1391 cm->mb_rows * cm->mb_cols));
1393 #if !(CONFIG_REALTIME_ONLY)
1394 vpx_free(cpi->twopass.total_stats);
1396 cpi->twopass.total_stats = vpx_calloc(1, sizeof(FIRSTPASS_STATS));
1398 vpx_free(cpi->twopass.total_left_stats);
1399 cpi->twopass.total_left_stats = vpx_calloc(1, sizeof(FIRSTPASS_STATS));
1401 vpx_free(cpi->twopass.this_frame_stats);
1403 cpi->twopass.this_frame_stats = vpx_calloc(1, sizeof(FIRSTPASS_STATS));
1405 if( !cpi->twopass.total_stats ||
1406 !cpi->twopass.total_left_stats ||
1407 !cpi->twopass.this_frame_stats)
1408 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1409 "Failed to allocate firstpass stats");
1412 #if CONFIG_MULTITHREAD
1414 cpi->mt_sync_range = 1;
1415 else if (width <= 1280)
1416 cpi->mt_sync_range = 4;
1417 else if (width <= 2560)
1418 cpi->mt_sync_range = 8;
1420 cpi->mt_sync_range = 16;
1423 vpx_free(cpi->tplist);
1425 CHECK_MEM_ERROR(cpi->tplist, vpx_malloc(sizeof(TOKENLIST) * cpi->common.mb_rows));
1430 static const int q_trans[] =
1432 0, 1, 2, 3, 4, 5, 7, 8,
1433 9, 10, 12, 13, 15, 17, 18, 19,
1434 20, 21, 23, 24, 25, 26, 27, 28,
1435 29, 30, 31, 33, 35, 37, 39, 41,
1436 43, 45, 47, 49, 51, 53, 55, 57,
1437 59, 61, 64, 67, 70, 73, 76, 79,
1438 82, 85, 88, 91, 94, 97, 100, 103,
1439 106, 109, 112, 115, 118, 121, 124, 127,
1442 int vp8_reverse_trans(int x)
1446 for (i = 0; i < 64; i++)
1447 if (q_trans[i] >= x)
1452 void vp8_new_frame_rate(VP8_COMP *cpi, double framerate)
1457 cpi->frame_rate = framerate;
1458 cpi->output_frame_rate = framerate;
1459 cpi->per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth /
1460 cpi->output_frame_rate);
1461 cpi->av_per_frame_bandwidth = cpi->per_frame_bandwidth;
1462 cpi->min_frame_bandwidth = (int)(cpi->av_per_frame_bandwidth *
1463 cpi->oxcf.two_pass_vbrmin_section / 100);
1465 // Set Maximum gf/arf interval
1466 cpi->max_gf_interval = ((int)(cpi->output_frame_rate / 2.0) + 2);
1468 if(cpi->max_gf_interval < 12)
1469 cpi->max_gf_interval = 12;
1471 // Extended interval for genuinely static scenes
1472 cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1474 // Special conditions when altr ref frame enabled in lagged compress mode
1475 if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames)
1477 if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1478 cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1480 if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1481 cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1484 if ( cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval )
1485 cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1490 rescale(int val, int num, int denom)
1492 int64_t llnum = num;
1493 int64_t llden = denom;
1494 int64_t llval = val;
1496 return llval * llnum / llden;
1500 static void init_config(VP8_PTR ptr, VP8_CONFIG *oxcf)
1502 VP8_COMP *cpi = (VP8_COMP *)(ptr);
1503 VP8_COMMON *cm = &cpi->common;
1508 cpi->auto_adjust_gold_quantizer = 1;
1511 cm->version = oxcf->Version;
1512 vp8_setup_version(cm);
1514 /* frame rate is not available on the first frame, as it's derived from
1515 * the observed timestamps. The actual value used here doesn't matter
1516 * too much, as it will adapt quickly. If the reciprocal of the timebase
1517 * seems like a reasonable framerate, then use that as a guess, otherwise
1520 cpi->frame_rate = (double)(oxcf->timebase.den) /
1521 (double)(oxcf->timebase.num);
1523 if (cpi->frame_rate > 180)
1524 cpi->frame_rate = 30;
1526 // change includes all joint functionality
1527 vp8_change_config(ptr, oxcf);
1529 // Initialize active best and worst q and average q values.
1530 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1531 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1532 cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1534 // Initialise the starting buffer levels
1535 cpi->buffer_level = cpi->oxcf.starting_buffer_level;
1536 cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
1538 cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
1539 cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
1540 cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
1541 cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
1543 cpi->total_actual_bits = 0;
1544 cpi->total_target_vs_actual = 0;
1546 // Temporal scalabilty
1547 if (cpi->oxcf.number_of_layers > 1)
1550 int prev_layer_frame_rate=0;
1552 for (i=0; i<cpi->oxcf.number_of_layers; i++)
1554 LAYER_CONTEXT *lc = &cpi->layer_context[i];
1556 // Layer configuration
1558 cpi->output_frame_rate / cpi->oxcf.rate_decimator[i];
1559 lc->target_bandwidth = cpi->oxcf.target_bitrate[i] * 1000;
1561 lc->starting_buffer_level =
1562 rescale(oxcf->starting_buffer_level,
1563 lc->target_bandwidth, 1000);
1565 if (oxcf->optimal_buffer_level == 0)
1566 lc->optimal_buffer_level = lc->target_bandwidth / 8;
1568 lc->optimal_buffer_level =
1569 rescale(oxcf->optimal_buffer_level,
1570 lc->target_bandwidth, 1000);
1572 if (oxcf->maximum_buffer_size == 0)
1573 lc->maximum_buffer_size = lc->target_bandwidth / 8;
1575 lc->maximum_buffer_size =
1576 rescale(oxcf->maximum_buffer_size,
1577 lc->target_bandwidth, 1000);
1579 // Work out the average size of a frame within this layer
1581 lc->avg_frame_size_for_layer = (cpi->oxcf.target_bitrate[i] -
1582 cpi->oxcf.target_bitrate[i-1]) * 1000 /
1583 (lc->frame_rate - prev_layer_frame_rate);
1585 lc->active_worst_quality = cpi->oxcf.worst_allowed_q;
1586 lc->active_best_quality = cpi->oxcf.best_allowed_q;
1587 lc->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1589 lc->buffer_level = lc->starting_buffer_level;
1590 lc->bits_off_target = lc->starting_buffer_level;
1592 lc->total_actual_bits = 0;
1596 lc->rate_correction_factor = 1.0;
1597 lc->key_frame_rate_correction_factor = 1.0;
1598 lc->gf_rate_correction_factor = 1.0;
1599 lc->inter_frame_target = 0.0;
1601 prev_layer_frame_rate = lc->frame_rate;
1605 #if VP8_TEMPORAL_ALT_REF
1609 cpi->fixed_divide[0] = 0;
1611 for (i = 1; i < 512; i++)
1612 cpi->fixed_divide[i] = 0x80000 / i;
1618 void vp8_change_config(VP8_PTR ptr, VP8_CONFIG *oxcf)
1620 VP8_COMP *cpi = (VP8_COMP *)(ptr);
1621 VP8_COMMON *cm = &cpi->common;
1629 if (cm->version != oxcf->Version)
1631 cm->version = oxcf->Version;
1632 vp8_setup_version(cm);
1637 switch (cpi->oxcf.Mode)
1642 cpi->compressor_speed = 2;
1644 if (cpi->oxcf.cpu_used < -16)
1646 cpi->oxcf.cpu_used = -16;
1649 if (cpi->oxcf.cpu_used > 16)
1650 cpi->oxcf.cpu_used = 16;
1654 case MODE_GOODQUALITY:
1656 cpi->compressor_speed = 1;
1658 if (cpi->oxcf.cpu_used < -5)
1660 cpi->oxcf.cpu_used = -5;
1663 if (cpi->oxcf.cpu_used > 5)
1664 cpi->oxcf.cpu_used = 5;
1668 case MODE_BESTQUALITY:
1670 cpi->compressor_speed = 0;
1673 case MODE_FIRSTPASS:
1675 cpi->compressor_speed = 1;
1677 case MODE_SECONDPASS:
1679 cpi->compressor_speed = 1;
1681 if (cpi->oxcf.cpu_used < -5)
1683 cpi->oxcf.cpu_used = -5;
1686 if (cpi->oxcf.cpu_used > 5)
1687 cpi->oxcf.cpu_used = 5;
1690 case MODE_SECONDPASS_BEST:
1692 cpi->compressor_speed = 0;
1697 cpi->auto_worst_q = 1;
1699 cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1700 cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1701 cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1703 if (oxcf->fixed_q >= 0)
1705 if (oxcf->worst_allowed_q < 0)
1706 cpi->oxcf.fixed_q = q_trans[0];
1708 cpi->oxcf.fixed_q = q_trans[oxcf->worst_allowed_q];
1710 if (oxcf->alt_q < 0)
1711 cpi->oxcf.alt_q = q_trans[0];
1713 cpi->oxcf.alt_q = q_trans[oxcf->alt_q];
1715 if (oxcf->key_q < 0)
1716 cpi->oxcf.key_q = q_trans[0];
1718 cpi->oxcf.key_q = q_trans[oxcf->key_q];
1720 if (oxcf->gold_q < 0)
1721 cpi->oxcf.gold_q = q_trans[0];
1723 cpi->oxcf.gold_q = q_trans[oxcf->gold_q];
1727 cpi->baseline_gf_interval =
1728 cpi->oxcf.alt_freq ? cpi->oxcf.alt_freq : DEFAULT_GF_INTERVAL;
1730 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
1732 //cpi->use_golden_frame_only = 0;
1733 //cpi->use_last_frame_only = 0;
1734 cm->refresh_golden_frame = 0;
1735 cm->refresh_last_frame = 1;
1736 cm->refresh_entropy_probs = 1;
1738 if (cpi->oxcf.token_partitions >= 0 && cpi->oxcf.token_partitions <= 3)
1739 cm->multi_token_partition =
1740 (TOKEN_PARTITION) cpi->oxcf.token_partitions;
1742 setup_features(cpi);
1747 for (i = 0; i < MAX_MB_SEGMENTS; i++)
1748 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1751 // At the moment the first order values may not be > MAXQ
1752 if (cpi->oxcf.fixed_q > MAXQ)
1753 cpi->oxcf.fixed_q = MAXQ;
1755 // local file playback mode == really big buffer
1756 if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK)
1758 cpi->oxcf.starting_buffer_level = 60000;
1759 cpi->oxcf.optimal_buffer_level = 60000;
1760 cpi->oxcf.maximum_buffer_size = 240000;
1763 // Convert target bandwidth from Kbit/s to Bit/s
1764 cpi->oxcf.target_bandwidth *= 1000;
1766 cpi->oxcf.starting_buffer_level =
1767 rescale(cpi->oxcf.starting_buffer_level,
1768 cpi->oxcf.target_bandwidth, 1000);
1770 // Set or reset optimal and maximum buffer levels.
1771 if (cpi->oxcf.optimal_buffer_level == 0)
1772 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1774 cpi->oxcf.optimal_buffer_level =
1775 rescale(cpi->oxcf.optimal_buffer_level,
1776 cpi->oxcf.target_bandwidth, 1000);
1778 if (cpi->oxcf.maximum_buffer_size == 0)
1779 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1781 cpi->oxcf.maximum_buffer_size =
1782 rescale(cpi->oxcf.maximum_buffer_size,
1783 cpi->oxcf.target_bandwidth, 1000);
1785 // Set up frame rate and related parameters rate control values.
1786 vp8_new_frame_rate(cpi, cpi->frame_rate);
1788 // Set absolute upper and lower quality limits
1789 cpi->worst_quality = cpi->oxcf.worst_allowed_q;
1790 cpi->best_quality = cpi->oxcf.best_allowed_q;
1792 // active values should only be modified if out of new range
1793 if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q)
1795 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1798 else if (cpi->active_worst_quality < cpi->oxcf.best_allowed_q)
1800 cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
1802 if (cpi->active_best_quality < cpi->oxcf.best_allowed_q)
1804 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1807 else if (cpi->active_best_quality > cpi->oxcf.worst_allowed_q)
1809 cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
1812 cpi->buffered_mode = (cpi->oxcf.optimal_buffer_level > 0) ? TRUE : FALSE;
1814 cpi->cq_target_quality = cpi->oxcf.cq_level;
1816 // Only allow dropped frames in buffered mode
1817 cpi->drop_frames_allowed = cpi->oxcf.allow_df && cpi->buffered_mode;
1819 if (!cm->use_bilinear_mc_filter)
1820 cm->mcomp_filter_type = SIXTAP;
1822 cm->mcomp_filter_type = BILINEAR;
1824 cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1826 cm->Width = cpi->oxcf.Width;
1827 cm->Height = cpi->oxcf.Height;
1829 cm->horiz_scale = cpi->horiz_scale;
1830 cm->vert_scale = cpi->vert_scale;
1832 // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1833 if (cpi->oxcf.Sharpness > 7)
1834 cpi->oxcf.Sharpness = 7;
1836 cm->sharpness_level = cpi->oxcf.Sharpness;
1838 if (cm->horiz_scale != NORMAL || cm->vert_scale != NORMAL)
1840 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
1841 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
1843 Scale2Ratio(cm->horiz_scale, &hr, &hs);
1844 Scale2Ratio(cm->vert_scale, &vr, &vs);
1846 // always go to the next whole number
1847 cm->Width = (hs - 1 + cpi->oxcf.Width * hr) / hs;
1848 cm->Height = (vs - 1 + cpi->oxcf.Height * vr) / vs;
1851 if (((cm->Width + 15) & 0xfffffff0) !=
1852 cm->yv12_fb[cm->lst_fb_idx].y_width ||
1853 ((cm->Height + 15) & 0xfffffff0) !=
1854 cm->yv12_fb[cm->lst_fb_idx].y_height ||
1855 cm->yv12_fb[cm->lst_fb_idx].y_width == 0)
1857 alloc_raw_frame_buffers(cpi);
1858 vp8_alloc_compressor_data(cpi);
1861 if (cpi->oxcf.fixed_q >= 0)
1863 cpi->last_q[0] = cpi->oxcf.fixed_q;
1864 cpi->last_q[1] = cpi->oxcf.fixed_q;
1867 cpi->Speed = cpi->oxcf.cpu_used;
1869 // force to allowlag to 0 if lag_in_frames is 0;
1870 if (cpi->oxcf.lag_in_frames == 0)
1872 cpi->oxcf.allow_lag = 0;
1874 // Limit on lag buffers as these are not currently dynamically allocated
1875 else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS)
1876 cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1879 cpi->alt_ref_source = NULL;
1880 cpi->is_src_frame_alt_ref = 0;
1884 // Experimental RD Code
1885 cpi->frame_distortion = 0;
1886 cpi->last_frame_distortion = 0;
1891 #define M_LOG2_E 0.693147180559945309417
1892 #define log2f(x) (log (x) / (float) M_LOG2_E)
1893 static void cal_mvsadcosts(int *mvsadcost[2])
1897 mvsadcost [0] [0] = 300;
1898 mvsadcost [1] [0] = 300;
1902 double z = 256 * (2 * (log2f(8 * i) + .6));
1903 mvsadcost [0][i] = (int) z;
1904 mvsadcost [1][i] = (int) z;
1905 mvsadcost [0][-i] = (int) z;
1906 mvsadcost [1][-i] = (int) z;
1908 while (++i <= mvfp_max);
1911 VP8_PTR vp8_create_compressor(VP8_CONFIG *oxcf)
1923 cpi = ctx.cpi = vpx_memalign(32, sizeof(VP8_COMP));
1924 // Check that the CPI instance is valid
1930 vpx_memset(cpi, 0, sizeof(VP8_COMP));
1932 if (setjmp(cm->error.jmp))
1934 VP8_PTR ptr = ctx.ptr;
1936 ctx.cpi->common.error.setjmp = 0;
1937 vp8_remove_compressor(&ptr);
1941 cpi->common.error.setjmp = 1;
1943 CHECK_MEM_ERROR(cpi->mb.ss, vpx_calloc(sizeof(search_site), (MAX_MVSEARCH_STEPS * 8) + 1));
1945 vp8_create_common(&cpi->common);
1946 vp8_cmachine_specific_config(cpi);
1948 init_config((VP8_PTR)cpi, oxcf);
1950 memcpy(cpi->base_skip_false_prob, vp8cx_base_skip_false_prob, sizeof(vp8cx_base_skip_false_prob));
1951 cpi->common.current_video_frame = 0;
1952 cpi->kf_overspend_bits = 0;
1953 cpi->kf_bitrate_adjustment = 0;
1954 cpi->frames_till_gf_update_due = 0;
1955 cpi->gf_overspend_bits = 0;
1956 cpi->non_gf_bitrate_adjustment = 0;
1957 cpi->prob_last_coded = 128;
1958 cpi->prob_gf_coded = 128;
1959 cpi->prob_intra_coded = 63;
1961 // Prime the recent reference frame usage counters.
1962 // Hereafter they will be maintained as a sort of moving average
1963 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
1964 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
1965 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
1966 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
1968 // Set reference frame sign bias for ALTREF frame to 1 (for now)
1969 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
1971 cpi->twopass.gf_decay_rate = 0;
1972 cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1974 cpi->gold_is_last = 0 ;
1975 cpi->alt_is_last = 0 ;
1976 cpi->gold_is_alt = 0 ;
1978 // allocate memory for storing last frame's MVs for MV prediction.
1979 CHECK_MEM_ERROR(cpi->lfmv, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int_mv)));
1980 CHECK_MEM_ERROR(cpi->lf_ref_frame_sign_bias, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1981 CHECK_MEM_ERROR(cpi->lf_ref_frame, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1983 // Create the encoder segmentation map and set all entries to 0
1984 CHECK_MEM_ERROR(cpi->segmentation_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1985 CHECK_MEM_ERROR(cpi->active_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1986 vpx_memset(cpi->active_map , 1, (cpi->common.mb_rows * cpi->common.mb_cols));
1987 cpi->active_map_enabled = 0;
1990 // Experimental code for lagged and one pass
1991 // Initialise one_pass GF frames stats
1992 // Update stats used for GF selection
1995 cpi->one_pass_frame_index = 0;
1997 for (i = 0; i < MAX_LAG_BUFFERS; i++)
1999 cpi->one_pass_frame_stats[i].frames_so_far = 0;
2000 cpi->one_pass_frame_stats[i].frame_intra_error = 0.0;
2001 cpi->one_pass_frame_stats[i].frame_coded_error = 0.0;
2002 cpi->one_pass_frame_stats[i].frame_pcnt_inter = 0.0;
2003 cpi->one_pass_frame_stats[i].frame_pcnt_motion = 0.0;
2004 cpi->one_pass_frame_stats[i].frame_mvr = 0.0;
2005 cpi->one_pass_frame_stats[i].frame_mvr_abs = 0.0;
2006 cpi->one_pass_frame_stats[i].frame_mvc = 0.0;
2007 cpi->one_pass_frame_stats[i].frame_mvc_abs = 0.0;
2012 // Should we use the cyclic refresh method.
2013 // Currently this is tied to error resilliant mode
2014 cpi->cyclic_refresh_mode_enabled = cpi->oxcf.error_resilient_mode;
2015 cpi->cyclic_refresh_mode_max_mbs_perframe = (cpi->common.mb_rows * cpi->common.mb_cols) / 40;
2016 cpi->cyclic_refresh_mode_index = 0;
2017 cpi->cyclic_refresh_q = 32;
2019 if (cpi->cyclic_refresh_mode_enabled)
2021 CHECK_MEM_ERROR(cpi->cyclic_refresh_map, vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
2024 cpi->cyclic_refresh_map = (signed char *) NULL;
2026 // Test function for segmentation
2027 //segmentation_test_function((VP8_PTR) cpi);
2029 #ifdef ENTROPY_STATS
2030 init_context_counters();
2033 /*Initialize the feed-forward activity masking.*/
2034 cpi->activity_avg = 90<<12;
2036 cpi->frames_since_key = 8; // Give a sensible default for the first frame.
2037 cpi->key_frame_frequency = cpi->oxcf.key_freq;
2038 cpi->this_key_frame_forced = FALSE;
2039 cpi->next_key_frame_forced = FALSE;
2041 cpi->source_alt_ref_pending = FALSE;
2042 cpi->source_alt_ref_active = FALSE;
2043 cpi->common.refresh_alt_ref_frame = 0;
2045 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
2046 #if CONFIG_INTERNAL_STATS
2047 cpi->b_calculate_ssimg = 0;
2052 if (cpi->b_calculate_psnr)
2054 cpi->total_sq_error = 0.0;
2055 cpi->total_sq_error2 = 0.0;
2060 cpi->totalp_y = 0.0;
2061 cpi->totalp_u = 0.0;
2062 cpi->totalp_v = 0.0;
2064 cpi->tot_recode_hits = 0;
2065 cpi->summed_quality = 0;
2066 cpi->summed_weights = 0;
2069 if (cpi->b_calculate_ssimg)
2071 cpi->total_ssimg_y = 0;
2072 cpi->total_ssimg_u = 0;
2073 cpi->total_ssimg_v = 0;
2074 cpi->total_ssimg_all = 0;
2080 #define LLONG_MAX 9223372036854775807LL
2082 cpi->first_time_stamp_ever = LLONG_MAX;
2084 cpi->frames_till_gf_update_due = 0;
2085 cpi->key_frame_count = 1;
2087 cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
2090 cpi->total_byte_count = 0;
2092 cpi->drop_frame = 0;
2093 cpi->drop_count = 0;
2094 cpi->max_drop_count = 0;
2095 cpi->max_consec_dropped_frames = 4;
2097 cpi->rate_correction_factor = 1.0;
2098 cpi->key_frame_rate_correction_factor = 1.0;
2099 cpi->gf_rate_correction_factor = 1.0;
2100 cpi->twopass.est_max_qcorrection_factor = 1.0;
2102 cpi->mb.mvcost[0] = &cpi->mb.mvcosts[0][mv_max+1];
2103 cpi->mb.mvcost[1] = &cpi->mb.mvcosts[1][mv_max+1];
2104 cpi->mb.mvsadcost[0] = &cpi->mb.mvsadcosts[0][mvfp_max+1];
2105 cpi->mb.mvsadcost[1] = &cpi->mb.mvsadcosts[1][mvfp_max+1];
2107 cal_mvsadcosts(cpi->mb.mvsadcost);
2109 for (i = 0; i < KEY_FRAME_CONTEXT; i++)
2111 cpi->prior_key_frame_distance[i] = (int)cpi->output_frame_rate;
2114 #ifdef OUTPUT_YUV_SRC
2115 yuv_file = fopen("bd.yuv", "ab");
2119 framepsnr = fopen("framepsnr.stt", "a");
2120 kf_list = fopen("kf_list.stt", "w");
2123 cpi->output_pkt_list = oxcf->output_pkt_list;
2125 #if !(CONFIG_REALTIME_ONLY)
2129 vp8_init_first_pass(cpi);
2131 else if (cpi->pass == 2)
2133 size_t packet_sz = sizeof(FIRSTPASS_STATS);
2134 int packets = oxcf->two_pass_stats_in.sz / packet_sz;
2136 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
2137 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
2138 cpi->twopass.stats_in_end = (void*)((char *)cpi->twopass.stats_in
2139 + (packets - 1) * packet_sz);
2140 vp8_init_second_pass(cpi);
2145 if (cpi->compressor_speed == 2)
2147 cpi->cpu_freq = 0; //vp8_get_processor_freq();
2148 cpi->avg_encode_time = 0;
2149 cpi->avg_pick_mode_time = 0;
2152 vp8_set_speed_features(cpi);
2154 // Set starting values of RD threshold multipliers (128 = *1)
2155 for (i = 0; i < MAX_MODES; i++)
2157 cpi->rd_thresh_mult[i] = 128;
2160 #ifdef ENTROPY_STATS
2161 init_mv_ref_counts();
2164 #if CONFIG_MULTITHREAD
2165 vp8cx_create_encoder_threads(cpi);
2168 cpi->fn_ptr[BLOCK_16X16].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16);
2169 cpi->fn_ptr[BLOCK_16X16].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x16);
2170 cpi->fn_ptr[BLOCK_16X16].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x16);
2171 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_h = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_h);
2172 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_v = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_v);
2173 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_hv = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_hv);
2174 cpi->fn_ptr[BLOCK_16X16].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x3);
2175 cpi->fn_ptr[BLOCK_16X16].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x8);
2176 cpi->fn_ptr[BLOCK_16X16].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x4d);
2178 cpi->fn_ptr[BLOCK_16X8].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8);
2179 cpi->fn_ptr[BLOCK_16X8].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x8);
2180 cpi->fn_ptr[BLOCK_16X8].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x8);
2181 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_h = NULL;
2182 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_v = NULL;
2183 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_hv = NULL;
2184 cpi->fn_ptr[BLOCK_16X8].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x3);
2185 cpi->fn_ptr[BLOCK_16X8].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x8);
2186 cpi->fn_ptr[BLOCK_16X8].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x4d);
2188 cpi->fn_ptr[BLOCK_8X16].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16);
2189 cpi->fn_ptr[BLOCK_8X16].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x16);
2190 cpi->fn_ptr[BLOCK_8X16].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x16);
2191 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_h = NULL;
2192 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_v = NULL;
2193 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_hv = NULL;
2194 cpi->fn_ptr[BLOCK_8X16].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x3);
2195 cpi->fn_ptr[BLOCK_8X16].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x8);
2196 cpi->fn_ptr[BLOCK_8X16].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x4d);
2198 cpi->fn_ptr[BLOCK_8X8].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8);
2199 cpi->fn_ptr[BLOCK_8X8].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x8);
2200 cpi->fn_ptr[BLOCK_8X8].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x8);
2201 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_h = NULL;
2202 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_v = NULL;
2203 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_hv = NULL;
2204 cpi->fn_ptr[BLOCK_8X8].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x3);
2205 cpi->fn_ptr[BLOCK_8X8].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x8);
2206 cpi->fn_ptr[BLOCK_8X8].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x4d);
2208 cpi->fn_ptr[BLOCK_4X4].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4);
2209 cpi->fn_ptr[BLOCK_4X4].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var4x4);
2210 cpi->fn_ptr[BLOCK_4X4].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar4x4);
2211 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_h = NULL;
2212 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_v = NULL;
2213 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_hv = NULL;
2214 cpi->fn_ptr[BLOCK_4X4].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x3);
2215 cpi->fn_ptr[BLOCK_4X4].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x8);
2216 cpi->fn_ptr[BLOCK_4X4].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x4d);
2218 #if ARCH_X86 || ARCH_X86_64
2219 cpi->fn_ptr[BLOCK_16X16].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2220 cpi->fn_ptr[BLOCK_16X8].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2221 cpi->fn_ptr[BLOCK_8X16].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2222 cpi->fn_ptr[BLOCK_8X8].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2223 cpi->fn_ptr[BLOCK_4X4].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2226 cpi->full_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, full_search);
2227 cpi->diamond_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, diamond_search);
2228 cpi->refining_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, refining_search);
2230 // make sure frame 1 is okay
2231 cpi->error_bins[0] = cpi->common.MBs;
2233 //vp8cx_init_quantizer() is first called here. Add check in vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only called later
2234 //when needed. This will avoid unnecessary calls of vp8cx_init_quantizer() for every frame.
2235 vp8cx_init_quantizer(cpi);
2237 vp8_loop_filter_init(cm);
2239 cpi->common.error.setjmp = 0;
2241 #if CONFIG_MULTI_RES_ENCODING
2242 /* Calculate # of MBs in a row in lower-resolution level image. */
2243 if (cpi->oxcf.mr_encoder_id > 0)
2244 vp8_cal_low_res_mb_cols(cpi);
2247 return (VP8_PTR) cpi;
2252 void vp8_remove_compressor(VP8_PTR *ptr)
2254 VP8_COMP *cpi = (VP8_COMP *)(*ptr);
2259 if (cpi && (cpi->common.current_video_frame > 0))
2261 #if !(CONFIG_REALTIME_ONLY)
2265 vp8_end_second_pass(cpi);
2270 #ifdef ENTROPY_STATS
2271 print_context_counters();
2272 print_tree_update_probs();
2273 print_mode_context();
2276 #if CONFIG_INTERNAL_STATS
2280 FILE *f = fopen("opsnr.stt", "a");
2281 double time_encoded = (cpi->last_end_time_stamp_seen
2282 - cpi->first_time_stamp_ever) / 10000000.000;
2283 double total_encode_time = (cpi->time_receive_data +
2284 cpi->time_compress_data) / 1000.000;
2285 double dr = (double)cpi->bytes * 8.0 / 1000.0 / time_encoded;
2287 if (cpi->b_calculate_psnr)
2289 YV12_BUFFER_CONFIG *lst_yv12 =
2290 &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
2292 if (cpi->oxcf.number_of_layers > 1)
2296 fprintf(f, "Layer\tBitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2297 "GLPsnrP\tVPXSSIM\t\n");
2298 for (i=0; i<cpi->oxcf.number_of_layers; i++)
2300 double dr = (double)cpi->bytes_in_layer[i] *
2301 8.0 / 1000.0 / time_encoded;
2302 double samples = 3.0 / 2 * cpi->frames_in_layer[i] *
2303 lst_yv12->y_width * lst_yv12->y_height;
2304 double total_psnr = vp8_mse2psnr(samples, 255.0,
2305 cpi->total_error2[i]);
2306 double total_psnr2 = vp8_mse2psnr(samples, 255.0,
2307 cpi->total_error2_p[i]);
2308 double total_ssim = 100 * pow(cpi->sum_ssim[i] /
2309 cpi->sum_weights[i], 8.0);
2311 fprintf(f, "%5d\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2314 cpi->sum_psnr[i] / cpi->frames_in_layer[i],
2316 cpi->sum_psnr_p[i] / cpi->frames_in_layer[i],
2317 total_psnr2, total_ssim);
2322 double samples = 3.0 / 2 * cpi->count *
2323 lst_yv12->y_width * lst_yv12->y_height;
2324 double total_psnr = vp8_mse2psnr(samples, 255.0,
2325 cpi->total_sq_error);
2326 double total_psnr2 = vp8_mse2psnr(samples, 255.0,
2327 cpi->total_sq_error2);
2328 double total_ssim = 100 * pow(cpi->summed_quality /
2329 cpi->summed_weights, 8.0);
2331 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2332 "GLPsnrP\tVPXSSIM\t Time(us)\n");
2333 fprintf(f, "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2335 dr, cpi->total / cpi->count, total_psnr,
2336 cpi->totalp / cpi->count, total_psnr2,
2337 total_ssim, total_encode_time);
2341 if (cpi->b_calculate_ssimg)
2343 if (cpi->oxcf.number_of_layers > 1)
2347 fprintf(f, "Layer\tBitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t"
2349 for (i=0; i<cpi->oxcf.number_of_layers; i++)
2351 double dr = (double)cpi->bytes_in_layer[i] *
2352 8.0 / 1000.0 / time_encoded;
2353 fprintf(f, "%5d\t%7.3f\t%6.4f\t"
2354 "%6.4f\t%6.4f\t%6.4f\t%8.0f\n",
2356 cpi->total_ssimg_y_in_layer[i] /
2357 cpi->frames_in_layer[i],
2358 cpi->total_ssimg_u_in_layer[i] /
2359 cpi->frames_in_layer[i],
2360 cpi->total_ssimg_v_in_layer[i] /
2361 cpi->frames_in_layer[i],
2362 cpi->total_ssimg_all_in_layer[i] /
2363 cpi->frames_in_layer[i],
2369 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t"
2371 fprintf(f, "%7.3f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
2372 cpi->total_ssimg_y / cpi->count,
2373 cpi->total_ssimg_u / cpi->count,
2374 cpi->total_ssimg_v / cpi->count,
2375 cpi->total_ssimg_all / cpi->count, total_encode_time);
2381 f = fopen("qskip.stt", "a");
2382 fprintf(f, "minq:%d -maxq:%d skiptrue:skipfalse = %d:%d\n", cpi->oxcf.best_allowed_q, cpi->oxcf.worst_allowed_q, skiptruecount, skipfalsecount);
2393 if (cpi->compressor_speed == 2)
2396 FILE *f = fopen("cxspeed.stt", "a");
2397 cnt_pm /= cpi->common.MBs;
2399 for (i = 0; i < 16; i++)
2400 fprintf(f, "%5d", frames_at_speed[i]);
2403 //fprintf(f, "%10d PM %10d %10d %10d EF %10d %10d %10d\n", cpi->Speed, cpi->avg_pick_mode_time, (tot_pm/cnt_pm), cnt_pm, cpi->avg_encode_time, 0, 0);
2412 extern int count_mb_seg[4];
2413 FILE *f = fopen("modes.stt", "a");
2414 double dr = (double)cpi->frame_rate * (double)bytes * (double)8 / (double)count / (double)1000 ;
2415 fprintf(f, "intra_mode in Intra Frames:\n");
2416 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d\n", y_modes[0], y_modes[1], y_modes[2], y_modes[3], y_modes[4]);
2417 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", uv_modes[0], uv_modes[1], uv_modes[2], uv_modes[3]);
2422 for (i = 0; i < 10; i++)
2423 fprintf(f, "%8d, ", b_modes[i]);
2429 fprintf(f, "Modes in Inter Frames:\n");
2430 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d\n",
2431 inter_y_modes[0], inter_y_modes[1], inter_y_modes[2], inter_y_modes[3], inter_y_modes[4],
2432 inter_y_modes[5], inter_y_modes[6], inter_y_modes[7], inter_y_modes[8], inter_y_modes[9]);
2433 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", inter_uv_modes[0], inter_uv_modes[1], inter_uv_modes[2], inter_uv_modes[3]);
2438 for (i = 0; i < 15; i++)
2439 fprintf(f, "%8d, ", inter_b_modes[i]);
2444 fprintf(f, "P:%8d, %8d, %8d, %8d\n", count_mb_seg[0], count_mb_seg[1], count_mb_seg[2], count_mb_seg[3]);
2445 fprintf(f, "PB:%8d, %8d, %8d, %8d\n", inter_b_modes[LEFT4X4], inter_b_modes[ABOVE4X4], inter_b_modes[ZERO4X4], inter_b_modes[NEW4X4]);
2453 #ifdef ENTROPY_STATS
2456 FILE *fmode = fopen("modecontext.c", "w");
2458 fprintf(fmode, "\n#include \"entropymode.h\"\n\n");
2459 fprintf(fmode, "const unsigned int vp8_kf_default_bmode_counts ");
2460 fprintf(fmode, "[VP8_BINTRAMODES] [VP8_BINTRAMODES] [VP8_BINTRAMODES] =\n{\n");
2462 for (i = 0; i < 10; i++)
2465 fprintf(fmode, " { //Above Mode : %d\n", i);
2467 for (j = 0; j < 10; j++)
2470 fprintf(fmode, " {");
2472 for (k = 0; k < 10; k++)
2474 if (!intra_mode_stats[i][j][k])
2475 fprintf(fmode, " %5d, ", 1);
2477 fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
2480 fprintf(fmode, "}, // left_mode %d\n", j);
2484 fprintf(fmode, " },\n");
2488 fprintf(fmode, "};\n");
2494 #if defined(SECTIONBITS_OUTPUT)
2499 FILE *f = fopen("tokenbits.stt", "a");
2501 for (i = 0; i < 28; i++)
2502 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
2512 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2513 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
2514 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame, cpi->time_receive_data / 1000, cpi->time_encode_mb_row / 1000, cpi->time_compress_data / 1000, (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2520 #if CONFIG_MULTITHREAD
2521 vp8cx_remove_encoder_threads(cpi);
2524 dealloc_compressor_data(cpi);
2525 vpx_free(cpi->mb.ss);
2527 vpx_free(cpi->cyclic_refresh_map);
2529 vp8_remove_common(&cpi->common);
2533 #ifdef OUTPUT_YUV_SRC
2553 static uint64_t calc_plane_error(unsigned char *orig, int orig_stride,
2554 unsigned char *recon, int recon_stride,
2555 unsigned int cols, unsigned int rows,
2556 vp8_variance_rtcd_vtable_t *rtcd)
2558 unsigned int row, col;
2559 uint64_t total_sse = 0;
2562 for (row = 0; row + 16 <= rows; row += 16)
2564 for (col = 0; col + 16 <= cols; col += 16)
2568 VARIANCE_INVOKE(rtcd, mse16x16)(orig + col, orig_stride,
2569 recon + col, recon_stride,
2574 /* Handle odd-sized width */
2577 unsigned int border_row, border_col;
2578 unsigned char *border_orig = orig;
2579 unsigned char *border_recon = recon;
2581 for (border_row = 0; border_row < 16; border_row++)
2583 for (border_col = col; border_col < cols; border_col++)
2585 diff = border_orig[border_col] - border_recon[border_col];
2586 total_sse += diff * diff;
2589 border_orig += orig_stride;
2590 border_recon += recon_stride;
2594 orig += orig_stride * 16;
2595 recon += recon_stride * 16;
2598 /* Handle odd-sized height */
2599 for (; row < rows; row++)
2601 for (col = 0; col < cols; col++)
2603 diff = orig[col] - recon[col];
2604 total_sse += diff * diff;
2607 orig += orig_stride;
2608 recon += recon_stride;
2611 vp8_clear_system_state();
2616 static void generate_psnr_packet(VP8_COMP *cpi)
2618 YV12_BUFFER_CONFIG *orig = cpi->Source;
2619 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2620 struct vpx_codec_cx_pkt pkt;
2623 unsigned int width = cpi->common.Width;
2624 unsigned int height = cpi->common.Height;
2626 pkt.kind = VPX_CODEC_PSNR_PKT;
2627 sse = calc_plane_error(orig->y_buffer, orig->y_stride,
2628 recon->y_buffer, recon->y_stride,
2630 IF_RTCD(&cpi->rtcd.variance));
2631 pkt.data.psnr.sse[0] = sse;
2632 pkt.data.psnr.sse[1] = sse;
2633 pkt.data.psnr.samples[0] = width * height;
2634 pkt.data.psnr.samples[1] = width * height;
2636 width = (width + 1) / 2;
2637 height = (height + 1) / 2;
2639 sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
2640 recon->u_buffer, recon->uv_stride,
2642 IF_RTCD(&cpi->rtcd.variance));
2643 pkt.data.psnr.sse[0] += sse;
2644 pkt.data.psnr.sse[2] = sse;
2645 pkt.data.psnr.samples[0] += width * height;
2646 pkt.data.psnr.samples[2] = width * height;
2648 sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2649 recon->v_buffer, recon->uv_stride,
2651 IF_RTCD(&cpi->rtcd.variance));
2652 pkt.data.psnr.sse[0] += sse;
2653 pkt.data.psnr.sse[3] = sse;
2654 pkt.data.psnr.samples[0] += width * height;
2655 pkt.data.psnr.samples[3] = width * height;
2657 for (i = 0; i < 4; i++)
2658 pkt.data.psnr.psnr[i] = vp8_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2659 pkt.data.psnr.sse[i]);
2661 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2665 int vp8_use_as_reference(VP8_PTR ptr, int ref_frame_flags)
2667 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2669 if (ref_frame_flags > 7)
2672 cpi->ref_frame_flags = ref_frame_flags;
2675 int vp8_update_reference(VP8_PTR ptr, int ref_frame_flags)
2677 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2679 if (ref_frame_flags > 7)
2682 cpi->common.refresh_golden_frame = 0;
2683 cpi->common.refresh_alt_ref_frame = 0;
2684 cpi->common.refresh_last_frame = 0;
2686 if (ref_frame_flags & VP8_LAST_FLAG)
2687 cpi->common.refresh_last_frame = 1;
2689 if (ref_frame_flags & VP8_GOLD_FLAG)
2690 cpi->common.refresh_golden_frame = 1;
2692 if (ref_frame_flags & VP8_ALT_FLAG)
2693 cpi->common.refresh_alt_ref_frame = 1;
2698 int vp8_get_reference(VP8_PTR ptr, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2700 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2701 VP8_COMMON *cm = &cpi->common;
2704 if (ref_frame_flag == VP8_LAST_FLAG)
2705 ref_fb_idx = cm->lst_fb_idx;
2706 else if (ref_frame_flag == VP8_GOLD_FLAG)
2707 ref_fb_idx = cm->gld_fb_idx;
2708 else if (ref_frame_flag == VP8_ALT_FLAG)
2709 ref_fb_idx = cm->alt_fb_idx;
2713 vp8_yv12_copy_frame_ptr(&cm->yv12_fb[ref_fb_idx], sd);
2717 int vp8_set_reference(VP8_PTR ptr, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2719 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2720 VP8_COMMON *cm = &cpi->common;
2724 if (ref_frame_flag == VP8_LAST_FLAG)
2725 ref_fb_idx = cm->lst_fb_idx;
2726 else if (ref_frame_flag == VP8_GOLD_FLAG)
2727 ref_fb_idx = cm->gld_fb_idx;
2728 else if (ref_frame_flag == VP8_ALT_FLAG)
2729 ref_fb_idx = cm->alt_fb_idx;
2733 vp8_yv12_copy_frame_ptr(sd, &cm->yv12_fb[ref_fb_idx]);
2737 int vp8_update_entropy(VP8_PTR comp, int update)
2739 VP8_COMP *cpi = (VP8_COMP *) comp;
2740 VP8_COMMON *cm = &cpi->common;
2741 cm->refresh_entropy_probs = update;
2748 void vp8_write_yuv_frame(const char *name, YV12_BUFFER_CONFIG *s)
2750 FILE *yuv_file = fopen(name, "ab");
2751 unsigned char *src = s->y_buffer;
2752 int h = s->y_height;
2756 fwrite(src, s->y_width, 1, yuv_file);
2766 fwrite(src, s->uv_width, 1, yuv_file);
2767 src += s->uv_stride;
2776 fwrite(src, s->uv_width, 1, yuv_file);
2777 src += s->uv_stride;
2786 static void scale_and_extend_source(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi)
2788 VP8_COMMON *cm = &cpi->common;
2790 // are we resizing the image
2791 if (cm->horiz_scale != 0 || cm->vert_scale != 0)
2793 #if CONFIG_SPATIAL_RESAMPLING
2794 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2795 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2798 if (cm->vert_scale == 3)
2803 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2804 Scale2Ratio(cm->vert_scale, &vr, &vs);
2806 vp8_scale_frame(sd, &cpi->scaled_source, cm->temp_scale_frame.y_buffer,
2807 tmp_height, hs, hr, vs, vr, 0);
2809 vp8_yv12_extend_frame_borders(&cpi->scaled_source);
2810 cpi->Source = &cpi->scaled_source;
2818 static void resize_key_frame(VP8_COMP *cpi)
2820 #if CONFIG_SPATIAL_RESAMPLING
2821 VP8_COMMON *cm = &cpi->common;
2823 // Do we need to apply resampling for one pass cbr.
2824 // In one pass this is more limited than in two pass cbr
2825 // The test and any change is only made one per key frame sequence
2826 if (cpi->oxcf.allow_spatial_resampling && (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER))
2828 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2829 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2830 int new_width, new_height;
2832 // If we are below the resample DOWN watermark then scale down a notch.
2833 if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2835 cm->horiz_scale = (cm->horiz_scale < ONETWO) ? cm->horiz_scale + 1 : ONETWO;
2836 cm->vert_scale = (cm->vert_scale < ONETWO) ? cm->vert_scale + 1 : ONETWO;
2838 // Should we now start scaling back up
2839 else if (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2841 cm->horiz_scale = (cm->horiz_scale > NORMAL) ? cm->horiz_scale - 1 : NORMAL;
2842 cm->vert_scale = (cm->vert_scale > NORMAL) ? cm->vert_scale - 1 : NORMAL;
2845 // Get the new hieght and width
2846 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2847 Scale2Ratio(cm->vert_scale, &vr, &vs);
2848 new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
2849 new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
2851 // If the image size has changed we need to reallocate the buffers
2852 // and resample the source image
2853 if ((cm->Width != new_width) || (cm->Height != new_height))
2855 cm->Width = new_width;
2856 cm->Height = new_height;
2857 vp8_alloc_compressor_data(cpi);
2858 scale_and_extend_source(cpi->un_scaled_source, cpi);
2866 static void update_alt_ref_frame_stats(VP8_COMP *cpi)
2868 VP8_COMMON *cm = &cpi->common;
2870 // Select an interval before next GF or altref
2871 if (!cpi->auto_gold)
2872 cpi->frames_till_gf_update_due = cpi->goldfreq;
2874 if ((cpi->pass != 2) && cpi->frames_till_gf_update_due)
2876 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2878 // Set the bits per frame that we should try and recover in subsequent inter frames
2879 // to account for the extra GF spend... note that his does not apply for GF updates
2880 // that occur coincident with a key frame as the extra cost of key frames is dealt
2883 cpi->gf_overspend_bits += cpi->projected_frame_size;
2884 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2887 // Update data structure that monitors level of reference to last GF
2888 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2889 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2891 // this frame refreshes means next frames don't unless specified by user
2892 cpi->common.frames_since_golden = 0;
2894 // Clear the alternate reference update pending flag.
2895 cpi->source_alt_ref_pending = FALSE;
2897 // Set the alternate refernce frame active flag
2898 cpi->source_alt_ref_active = TRUE;
2902 static void update_golden_frame_stats(VP8_COMP *cpi)
2904 VP8_COMMON *cm = &cpi->common;
2906 // Update the Golden frame usage counts.
2907 if (cm->refresh_golden_frame)
2909 // Select an interval before next GF
2910 if (!cpi->auto_gold)
2911 cpi->frames_till_gf_update_due = cpi->goldfreq;
2913 if ((cpi->pass != 2) && (cpi->frames_till_gf_update_due > 0))
2915 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2917 // Set the bits per frame that we should try and recover in subsequent inter frames
2918 // to account for the extra GF spend... note that his does not apply for GF updates
2919 // that occur coincident with a key frame as the extra cost of key frames is dealt
2921 if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active)
2923 // Calcluate GF bits to be recovered
2924 // Projected size - av frame bits available for inter frames for clip as a whole
2925 cpi->gf_overspend_bits += (cpi->projected_frame_size - cpi->inter_frame_target);
2928 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2932 // Update data structure that monitors level of reference to last GF
2933 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2934 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2936 // this frame refreshes means next frames don't unless specified by user
2937 cm->refresh_golden_frame = 0;
2938 cpi->common.frames_since_golden = 0;
2940 //if ( cm->frame_type == KEY_FRAME )
2942 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
2943 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
2944 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
2945 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
2949 // // Carry a potrtion of count over to begining of next gf sequence
2950 // cpi->recent_ref_frame_usage[INTRA_FRAME] >>= 5;
2951 // cpi->recent_ref_frame_usage[LAST_FRAME] >>= 5;
2952 // cpi->recent_ref_frame_usage[GOLDEN_FRAME] >>= 5;
2953 // cpi->recent_ref_frame_usage[ALTREF_FRAME] >>= 5;
2956 // ******** Fixed Q test code only ************
2957 // If we are going to use the ALT reference for the next group of frames set a flag to say so.
2958 if (cpi->oxcf.fixed_q >= 0 &&
2959 cpi->oxcf.play_alternate && !cpi->common.refresh_alt_ref_frame)
2961 cpi->source_alt_ref_pending = TRUE;
2962 cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2965 if (!cpi->source_alt_ref_pending)
2966 cpi->source_alt_ref_active = FALSE;
2968 // Decrement count down till next gf
2969 if (cpi->frames_till_gf_update_due > 0)
2970 cpi->frames_till_gf_update_due--;
2973 else if (!cpi->common.refresh_alt_ref_frame)
2975 // Decrement count down till next gf
2976 if (cpi->frames_till_gf_update_due > 0)
2977 cpi->frames_till_gf_update_due--;
2979 if (cpi->common.frames_till_alt_ref_frame)
2980 cpi->common.frames_till_alt_ref_frame --;
2982 cpi->common.frames_since_golden ++;
2984 if (cpi->common.frames_since_golden > 1)
2986 cpi->recent_ref_frame_usage[INTRA_FRAME] += cpi->count_mb_ref_frame_usage[INTRA_FRAME];
2987 cpi->recent_ref_frame_usage[LAST_FRAME] += cpi->count_mb_ref_frame_usage[LAST_FRAME];
2988 cpi->recent_ref_frame_usage[GOLDEN_FRAME] += cpi->count_mb_ref_frame_usage[GOLDEN_FRAME];
2989 cpi->recent_ref_frame_usage[ALTREF_FRAME] += cpi->count_mb_ref_frame_usage[ALTREF_FRAME];
2994 // This function updates the reference frame probability estimates that
2995 // will be used during mode selection
2996 static void update_rd_ref_frame_probs(VP8_COMP *cpi)
2998 VP8_COMMON *cm = &cpi->common;
3001 const int *const rfct = cpi->recent_ref_frame_usage;
3002 const int rf_intra = rfct[INTRA_FRAME];
3003 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
3005 if (cm->frame_type == KEY_FRAME)
3007 cpi->prob_intra_coded = 255;
3008 cpi->prob_last_coded = 128;
3009 cpi->prob_gf_coded = 128;
3011 else if (!(rf_intra + rf_inter))
3013 // This is a trap in case this function is called with cpi->recent_ref_frame_usage[] blank.
3014 cpi->prob_intra_coded = 63;
3015 cpi->prob_last_coded = 128;
3016 cpi->prob_gf_coded = 128;
3020 cpi->prob_intra_coded = (rf_intra * 255) / (rf_intra + rf_inter);
3022 if (cpi->prob_intra_coded < 1)
3023 cpi->prob_intra_coded = 1;
3025 if ((cm->frames_since_golden > 0) || cpi->source_alt_ref_active)
3027 cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
3029 if (cpi->prob_last_coded < 1)
3030 cpi->prob_last_coded = 1;
3032 cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
3033 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
3035 if (cpi->prob_gf_coded < 1)
3036 cpi->prob_gf_coded = 1;
3041 const int *const rfct = cpi->count_mb_ref_frame_usage;
3042 const int rf_intra = rfct[INTRA_FRAME];
3043 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
3045 if (cm->frame_type == KEY_FRAME)
3047 cpi->prob_intra_coded = 255;
3048 cpi->prob_last_coded = 128;
3049 cpi->prob_gf_coded = 128;
3051 else if (!(rf_intra + rf_inter))
3053 if (cpi->oxcf.number_of_layers > 1)
3055 if (cpi->ref_frame_flags == VP8_LAST_FLAG)
3057 cpi->prob_intra_coded = 63;
3058 cpi->prob_last_coded = 255;
3059 cpi->prob_gf_coded = 128;
3061 else if (cpi->ref_frame_flags == VP8_GOLD_FLAG)
3063 cpi->prob_intra_coded = 63;
3064 cpi->prob_last_coded = 1;
3065 cpi->prob_gf_coded = 255;
3067 else if (cpi->ref_frame_flags == VP8_ALT_FLAG)
3069 cpi->prob_intra_coded = 63;
3070 cpi->prob_last_coded = 1;
3071 cpi->prob_gf_coded = 1;
3075 cpi->prob_intra_coded = 63;
3076 cpi->prob_last_coded = 128;
3077 cpi->prob_gf_coded = 128;
3082 // This is a trap in case this function is called with
3083 // cpi->recent_ref_frame_usage[] blank.
3084 cpi->prob_intra_coded = 63;
3085 cpi->prob_last_coded = 128;
3086 cpi->prob_gf_coded = 128;
3091 cpi->prob_intra_coded = (rf_intra * 255) / (rf_intra + rf_inter);
3093 if (cpi->prob_intra_coded < 1)
3094 cpi->prob_intra_coded = 1;
3096 cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
3098 if (cpi->prob_last_coded < 1)
3099 cpi->prob_last_coded = 1;
3101 cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
3102 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
3104 if (cpi->prob_gf_coded < 1)
3105 cpi->prob_gf_coded = 1;
3108 // update reference frame costs since we can do better than what we got last frame.
3109 if (cpi->oxcf.number_of_layers == 1)
3111 if (cpi->common.refresh_alt_ref_frame)
3113 cpi->prob_intra_coded += 40;
3114 cpi->prob_last_coded = 200;
3115 cpi->prob_gf_coded = 1;
3117 else if (cpi->common.frames_since_golden == 0)
3119 cpi->prob_last_coded = 214;
3120 cpi->prob_gf_coded = 1;
3122 else if (cpi->common.frames_since_golden == 1)
3124 cpi->prob_last_coded = 192;
3125 cpi->prob_gf_coded = 220;
3127 else if (cpi->source_alt_ref_active)
3129 //int dist = cpi->common.frames_till_alt_ref_frame + cpi->common.frames_since_golden;
3130 cpi->prob_gf_coded -= 20;
3132 if (cpi->prob_gf_coded < 10)
3133 cpi->prob_gf_coded = 10;
3140 // 1 = key, 0 = inter
3141 static int decide_key_frame(VP8_COMP *cpi)
3143 VP8_COMMON *cm = &cpi->common;
3145 int code_key_frame = FALSE;
3149 if (cpi->Speed > 11)
3152 // Clear down mmx registers
3153 vp8_clear_system_state(); //__asm emms;
3155 if ((cpi->compressor_speed == 2) && (cpi->Speed >= 5) && (cpi->sf.RD == 0))
3157 double change = 1.0 * abs((int)(cpi->intra_error - cpi->last_intra_error)) / (1 + cpi->last_intra_error);
3158 double change2 = 1.0 * abs((int)(cpi->prediction_error - cpi->last_prediction_error)) / (1 + cpi->last_prediction_error);
3159 double minerror = cm->MBs * 256;
3163 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
3164 && cpi->prediction_error > minerror
3165 && (change > .25 || change2 > .25))
3167 FILE *f = fopen("intra_inter.stt", "a");
3169 if (cpi->prediction_error <= 0)
3170 cpi->prediction_error = 1;
3172 fprintf(f, "%d %d %d %d %14.4f\n",
3173 cm->current_video_frame,
3174 (int) cpi->prediction_error,
3175 (int) cpi->intra_error,
3176 (int)((10 * cpi->intra_error) / cpi->prediction_error),
3184 cpi->last_intra_error = cpi->intra_error;
3185 cpi->last_prediction_error = cpi->prediction_error;
3187 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
3188 && cpi->prediction_error > minerror
3189 && (change > .25 || change2 > .25))
3191 /*(change > 1.4 || change < .75)&& cpi->this_frame_percent_intra > cpi->last_frame_percent_intra + 3*/
3199 // If the following are true we might as well code a key frame
3200 if (((cpi->this_frame_percent_intra == 100) &&
3201 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
3202 ((cpi->this_frame_percent_intra > 95) &&
3203 (cpi->this_frame_percent_intra >= (cpi->last_frame_percent_intra + 5))))
3205 code_key_frame = TRUE;
3207 // in addition if the following are true and this is not a golden frame then code a key frame
3208 // Note that on golden frames there often seems to be a pop in intra useage anyway hence this
3209 // restriction is designed to prevent spurious key frames. The Intra pop needs to be investigated.
3210 else if (((cpi->this_frame_percent_intra > 60) &&
3211 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 2))) ||
3212 ((cpi->this_frame_percent_intra > 75) &&
3213 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 3 / 2))) ||
3214 ((cpi->this_frame_percent_intra > 90) &&
3215 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 10))))
3217 if (!cm->refresh_golden_frame)
3218 code_key_frame = TRUE;
3221 return code_key_frame;
3225 #if !(CONFIG_REALTIME_ONLY)
3226 static void Pass1Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags)
3231 vp8_set_quantizer(cpi, 26);
3233 scale_and_extend_source(cpi->un_scaled_source, cpi);
3234 vp8_first_pass(cpi);
3239 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame)
3247 sprintf(filename, "cx\\y%04d.raw", this_frame);
3248 yframe = fopen(filename, "wb");
3250 for (i = 0; i < frame->y_height; i++)
3251 fwrite(frame->y_buffer + i * frame->y_stride, frame->y_width, 1, yframe);
3254 sprintf(filename, "cx\\u%04d.raw", this_frame);
3255 yframe = fopen(filename, "wb");
3257 for (i = 0; i < frame->uv_height; i++)
3258 fwrite(frame->u_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
3261 sprintf(filename, "cx\\v%04d.raw", this_frame);
3262 yframe = fopen(filename, "wb");
3264 for (i = 0; i < frame->uv_height; i++)
3265 fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
3270 // return of 0 means drop frame
3272 // Function to test for conditions that indeicate we should loop
3273 // back and recode a frame.
3274 static BOOL recode_loop_test( VP8_COMP *cpi,
3275 int high_limit, int low_limit,
3276 int q, int maxq, int minq )
3278 BOOL force_recode = FALSE;
3279 VP8_COMMON *cm = &cpi->common;
3281 // Is frame recode allowed at all
3282 // Yes if either recode mode 1 is selected or mode two is selcted
3283 // and the frame is a key frame. golden frame or alt_ref_frame
3284 if ( (cpi->sf.recode_loop == 1) ||
3285 ( (cpi->sf.recode_loop == 2) &&
3286 ( (cm->frame_type == KEY_FRAME) ||
3287 cm->refresh_golden_frame ||
3288 cm->refresh_alt_ref_frame ) ) )
3290 // General over and under shoot tests
3291 if ( ((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
3292 ((cpi->projected_frame_size < low_limit) && (q > minq)) )
3294 force_recode = TRUE;
3296 // Special Constrained quality tests
3297 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
3299 // Undershoot and below auto cq level
3300 if ( (q > cpi->cq_target_quality) &&
3301 (cpi->projected_frame_size <
3302 ((cpi->this_frame_target * 7) >> 3)))
3304 force_recode = TRUE;
3306 // Severe undershoot and between auto and user cq level
3307 else if ( (q > cpi->oxcf.cq_level) &&
3308 (cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
3309 (cpi->active_best_quality > cpi->oxcf.cq_level))
3311 force_recode = TRUE;
3312 cpi->active_best_quality = cpi->oxcf.cq_level;
3317 return force_recode;
3320 void update_reference_frames(VP8_COMMON *cm)
3322 YV12_BUFFER_CONFIG *yv12_fb = cm->yv12_fb;
3324 // At this point the new frame has been encoded.
3325 // If any buffer copy / swapping is signaled it should be done here.
3327 if (cm->frame_type == KEY_FRAME)
3329 yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG | VP8_ALT_FLAG ;
3331 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3332 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3334 cm->alt_fb_idx = cm->gld_fb_idx = cm->new_fb_idx;
3336 else /* For non key frames */
3338 if (cm->refresh_alt_ref_frame)
3340 assert(!cm->copy_buffer_to_arf);
3342 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_ALT_FLAG;
3343 cm->yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3344 cm->alt_fb_idx = cm->new_fb_idx;
3346 else if (cm->copy_buffer_to_arf)
3348 assert(!(cm->copy_buffer_to_arf & ~0x3));
3350 if (cm->copy_buffer_to_arf == 1)
3352 if(cm->alt_fb_idx != cm->lst_fb_idx)
3354 yv12_fb[cm->lst_fb_idx].flags |= VP8_ALT_FLAG;
3355 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3356 cm->alt_fb_idx = cm->lst_fb_idx;
3359 else /* if (cm->copy_buffer_to_arf == 2) */
3361 if(cm->alt_fb_idx != cm->gld_fb_idx)
3363 yv12_fb[cm->gld_fb_idx].flags |= VP8_ALT_FLAG;
3364 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3365 cm->alt_fb_idx = cm->gld_fb_idx;
3370 if (cm->refresh_golden_frame)
3372 assert(!cm->copy_buffer_to_gf);
3374 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG;
3375 cm->yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3376 cm->gld_fb_idx = cm->new_fb_idx;
3378 else if (cm->copy_buffer_to_gf)
3380 assert(!(cm->copy_buffer_to_arf & ~0x3));
3382 if (cm->copy_buffer_to_gf == 1)
3384 if(cm->gld_fb_idx != cm->lst_fb_idx)
3386 yv12_fb[cm->lst_fb_idx].flags |= VP8_GOLD_FLAG;
3387 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3388 cm->gld_fb_idx = cm->lst_fb_idx;
3391 else /* if (cm->copy_buffer_to_gf == 2) */
3393 if(cm->alt_fb_idx != cm->gld_fb_idx)
3395 yv12_fb[cm->alt_fb_idx].flags |= VP8_GOLD_FLAG;
3396 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3397 cm->gld_fb_idx = cm->alt_fb_idx;
3403 if (cm->refresh_last_frame)
3405 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_LAST_FLAG;
3406 cm->yv12_fb[cm->lst_fb_idx].flags &= ~VP8_LAST_FLAG;
3407 cm->lst_fb_idx = cm->new_fb_idx;
3411 void loopfilter_frame(VP8_COMP *cpi, VP8_COMMON *cm)
3415 cm->filter_level = 0;
3419 struct vpx_usec_timer timer;
3421 vp8_clear_system_state();
3423 vpx_usec_timer_start(&timer);
3424 if (cpi->sf.auto_filter == 0)
3425 vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3428 vp8cx_pick_filter_level(cpi->Source, cpi);
3430 vpx_usec_timer_mark(&timer);
3431 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
3434 #if CONFIG_MULTITHREAD
3435 if (cpi->b_multi_threaded)
3436 sem_post(&cpi->h_event_end_lpf); /* signal that we have set filter_level */
3439 if (cm->filter_level > 0)
3441 vp8cx_set_alt_lf_level(cpi, cm->filter_level);
3442 vp8_loop_filter_frame(cm, &cpi->mb.e_mbd);
3445 vp8_yv12_extend_frame_borders_ptr(cm->frame_to_show);
3449 static void encode_frame_to_data_rate
3452 unsigned long *size,
3453 unsigned char *dest,
3454 unsigned char* dest_end,
3455 unsigned int *frame_flags
3459 int frame_over_shoot_limit;
3460 int frame_under_shoot_limit;
3470 int zbin_oq_low = 0;
3473 VP8_COMMON *cm = &cpi->common;
3474 int active_worst_qchanged = FALSE;
3476 int overshoot_seen = FALSE;
3477 int undershoot_seen = FALSE;
3478 int drop_mark = cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100;
3479 int drop_mark75 = drop_mark * 2 / 3;
3480 int drop_mark50 = drop_mark / 4;
3481 int drop_mark25 = drop_mark / 8;
3484 // Clear down mmx registers to allow floating point in what follows
3485 vp8_clear_system_state();
3487 // Test code for segmentation of gf/arf (0,0)
3488 //segmentation_test_function((VP8_PTR) cpi);
3490 if (cpi->compressor_speed == 2)
3492 if(cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3494 if(cpi->force_next_frame_intra)
3496 cm->frame_type = KEY_FRAME; /* delayed intra frame */
3499 cpi->force_next_frame_intra = 0;
3502 // For an alt ref frame in 2 pass we skip the call to the second pass function that sets the target bandwidth
3503 #if !(CONFIG_REALTIME_ONLY)
3507 if (cpi->common.refresh_alt_ref_frame)
3509 cpi->per_frame_bandwidth = cpi->twopass.gf_bits; // Per frame bit target for the alt ref frame
3510 cpi->target_bandwidth = cpi->twopass.gf_bits * cpi->output_frame_rate; // per second target bitrate
3515 cpi->per_frame_bandwidth = (int)(cpi->target_bandwidth / cpi->output_frame_rate);
3517 // Default turn off buffer to buffer copying
3518 cm->copy_buffer_to_gf = 0;
3519 cm->copy_buffer_to_arf = 0;
3521 // Clear zbin over-quant value and mode boost values.
3522 cpi->zbin_over_quant = 0;
3523 cpi->zbin_mode_boost = 0;
3525 // Enable or disable mode based tweaking of the zbin
3526 // For 2 Pass Only used where GF/ARF prediction quality
3527 // is above a threshold
3528 cpi->zbin_mode_boost_enabled = TRUE;
3531 if ( cpi->gfu_boost <= 400 )
3533 cpi->zbin_mode_boost_enabled = FALSE;
3537 // Current default encoder behaviour for the altref sign bias
3538 if (cpi->source_alt_ref_active)
3539 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
3541 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
3543 // Check to see if a key frame is signalled
3544 // For two pass with auto key frame enabled cm->frame_type may already be set, but not for one pass.
3545 if ((cm->current_video_frame == 0) ||
3546 (cm->frame_flags & FRAMEFLAGS_KEY) ||
3547 (cpi->oxcf.auto_key && (cpi->frames_since_key % cpi->key_frame_frequency == 0)))
3549 // Key frame from VFW/auto-keyframe/first frame
3550 cm->frame_type = KEY_FRAME;
3553 // Set default state for segment and mode based loop filter update flags
3554 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
3555 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
3556 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
3558 // Set various flags etc to special state if it is a key frame
3559 if (cm->frame_type == KEY_FRAME)
3563 // Reset the loop filter deltas and segmentation map
3564 setup_features(cpi);
3566 // If segmentation is enabled force a map update for key frames
3567 if (cpi->mb.e_mbd.segmentation_enabled)
3569 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3570 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3573 // The alternate reference frame cannot be active for a key frame
3574 cpi->source_alt_ref_active = FALSE;
3576 // Reset the RD threshold multipliers to default of * 1 (128)
3577 for (i = 0; i < MAX_MODES; i++)
3579 cpi->rd_thresh_mult[i] = 128;
3583 // Test code for segmentation
3584 //if ( (cm->frame_type == KEY_FRAME) || ((cm->current_video_frame % 2) == 0))
3585 //if ( (cm->current_video_frame % 2) == 0 )
3586 // enable_segmentation((VP8_PTR)cpi);
3588 // disable_segmentation((VP8_PTR)cpi);
3591 // Experimental code for lagged compress and one pass
3592 // Initialise one_pass GF frames stats
3593 // Update stats used for GF selection
3594 //if ( cpi->pass == 0 )
3596 cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
3598 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
3599 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
3600 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
3601 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
3602 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
3603 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
3604 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
3605 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
3606 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
3610 update_rd_ref_frame_probs(cpi);
3612 if (cpi->drop_frames_allowed)
3614 // The reset to decimation 0 is only done here for one pass.
3615 // Once it is set two pass leaves decimation on till the next kf.
3616 if ((cpi->buffer_level > drop_mark) && (cpi->decimation_factor > 0))
3617 cpi->decimation_factor --;
3619 if (cpi->buffer_level > drop_mark75 && cpi->decimation_factor > 0)
3620 cpi->decimation_factor = 1;
3622 else if (cpi->buffer_level < drop_mark25 && (cpi->decimation_factor == 2 || cpi->decimation_factor == 3))
3624 cpi->decimation_factor = 3;
3626 else if (cpi->buffer_level < drop_mark50 && (cpi->decimation_factor == 1 || cpi->decimation_factor == 2))
3628 cpi->decimation_factor = 2;
3630 else if (cpi->buffer_level < drop_mark75 && (cpi->decimation_factor == 0 || cpi->decimation_factor == 1))
3632 cpi->decimation_factor = 1;
3635 //vpx_log("Encoder: Decimation Factor: %d \n",cpi->decimation_factor);
3638 // The following decimates the frame rate according to a regular pattern (i.e. to 1/2 or 2/3 frame rate)
3639 // This can be used to help prevent buffer under-run in CBR mode. Alternatively it might be desirable in
3640 // some situations to drop frame rate but throw more bits at each frame.
3642 // Note that dropping a key frame can be problematic if spatial resampling is also active
3643 if (cpi->decimation_factor > 0)
3645 switch (cpi->decimation_factor)
3648 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 3 / 2;
3651 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3654 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3658 // Note that we should not throw out a key frame (especially when spatial resampling is enabled).
3659 if ((cm->frame_type == KEY_FRAME)) // && cpi->oxcf.allow_spatial_resampling )
3661 cpi->decimation_count = cpi->decimation_factor;
3663 else if (cpi->decimation_count > 0)
3665 cpi->decimation_count --;
3667 cpi->bits_off_target += cpi->av_per_frame_bandwidth;
3668 if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
3669 cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
3671 cm->current_video_frame++;
3672 cpi->frames_since_key++;
3674 #if CONFIG_INTERNAL_STATS
3678 cpi->buffer_level = cpi->bits_off_target;
3680 if (cpi->oxcf.number_of_layers > 1)
3684 // Propagate bits saved by dropping the frame to higher layers
3685 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
3687 LAYER_CONTEXT *lc = &cpi->layer_context[i];
3688 lc->bits_off_target += cpi->av_per_frame_bandwidth;
3689 if (lc->bits_off_target > lc->maximum_buffer_size)
3690 lc->bits_off_target = lc->maximum_buffer_size;
3691 lc->buffer_level = lc->bits_off_target;
3698 cpi->decimation_count = cpi->decimation_factor;
3701 // Decide how big to make the frame
3702 if (!vp8_pick_frame_size(cpi))
3704 cm->current_video_frame++;
3705 cpi->frames_since_key++;
3709 // Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
3710 // This has a knock on effect on active best quality as well.
3711 // For CBR if the buffer reaches its maximum level then we can no longer
3712 // save up bits for later frames so we might as well use them up
3713 // on the current frame.
3714 if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
3715 (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) && cpi->buffered_mode)
3717 int Adjustment = cpi->active_worst_quality / 4; // Max adjustment is 1/4
3723 if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size)
3725 buff_lvl_step = (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level) / Adjustment;
3728 Adjustment = (cpi->buffer_level - cpi->oxcf.optimal_buffer_level) / buff_lvl_step;
3733 cpi->active_worst_quality -= Adjustment;
3735 if(cpi->active_worst_quality < cpi->active_best_quality)
3736 cpi->active_worst_quality = cpi->active_best_quality;
3740 // Set an active best quality and if necessary active worst quality
3741 // There is some odd behavior for one pass here that needs attention.
3742 if ( (cpi->pass == 2) || (cpi->ni_frames > 150))
3744 vp8_clear_system_state();
3746 Q = cpi->active_worst_quality;
3748 if ( cm->frame_type == KEY_FRAME )
3750 if ( cpi->pass == 2 )
3752 if (cpi->gfu_boost > 600)
3753 cpi->active_best_quality = kf_low_motion_minq[Q];
3755 cpi->active_best_quality = kf_high_motion_minq[Q];
3757 // Special case for key frames forced because we have reached
3758 // the maximum key frame interval. Here force the Q to a range
3759 // based on the ambient Q to reduce the risk of popping
3760 if ( cpi->this_key_frame_forced )
3762 if ( cpi->active_best_quality > cpi->avg_frame_qindex * 7/8)
3763 cpi->active_best_quality = cpi->avg_frame_qindex * 7/8;
3764 else if ( cpi->active_best_quality < cpi->avg_frame_qindex >> 2 )
3765 cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
3768 // One pass more conservative
3770 cpi->active_best_quality = kf_high_motion_minq[Q];
3773 else if (cpi->oxcf.number_of_layers==1 &&
3774 (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame))
3776 // Use the lower of cpi->active_worst_quality and recent
3777 // average Q as basis for GF/ARF Q limit unless last frame was
3779 if ( (cpi->frames_since_key > 1) &&
3780 (cpi->avg_frame_qindex < cpi->active_worst_quality) )
3782 Q = cpi->avg_frame_qindex;
3785 // For constrained quality dont allow Q less than the cq level
3786 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3787 (Q < cpi->cq_target_quality) )
3789 Q = cpi->cq_target_quality;
3792 if ( cpi->pass == 2 )
3794 if ( cpi->gfu_boost > 1000 )
3795 cpi->active_best_quality = gf_low_motion_minq[Q];
3796 else if ( cpi->gfu_boost < 400 )
3797 cpi->active_best_quality = gf_high_motion_minq[Q];
3799 cpi->active_best_quality = gf_mid_motion_minq[Q];
3801 // Constrained quality use slightly lower active best.
3802 if ( cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY )
3804 cpi->active_best_quality =
3805 cpi->active_best_quality * 15/16;
3808 // One pass more conservative
3810 cpi->active_best_quality = gf_high_motion_minq[Q];
3814 cpi->active_best_quality = inter_minq[Q];
3816 // For the constant/constrained quality mode we dont want
3817 // q to fall below the cq level.
3818 if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3819 (cpi->active_best_quality < cpi->cq_target_quality) )
3821 // If we are strongly undershooting the target rate in the last
3822 // frames then use the user passed in cq value not the auto
3824 if ( cpi->rolling_actual_bits < cpi->min_frame_bandwidth )
3825 cpi->active_best_quality = cpi->oxcf.cq_level;
3827 cpi->active_best_quality = cpi->cq_target_quality;
3831 // If CBR and the buffer is as full then it is reasonable to allow
3832 // higher quality on the frames to prevent bits just going to waste.
3833 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
3835 // Note that the use of >= here elliminates the risk of a devide
3836 // by 0 error in the else if clause
3837 if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size)
3838 cpi->active_best_quality = cpi->best_quality;
3840 else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level)
3842 int Fraction = ((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) / (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level);
3843 int min_qadjustment = ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;
3845 cpi->active_best_quality -= min_qadjustment;
3849 // Make sure constrained quality mode limits are adhered to for the first
3850 // few frames of one pass encodes
3851 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
3853 if ( (cm->frame_type == KEY_FRAME) ||
3854 cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame )
3856 cpi->active_best_quality = cpi->best_quality;
3858 else if (cpi->active_best_quality < cpi->cq_target_quality)
3860 cpi->active_best_quality = cpi->cq_target_quality;
3864 // Clip the active best and worst quality values to limits
3865 if (cpi->active_worst_quality > cpi->worst_quality)
3866 cpi->active_worst_quality = cpi->worst_quality;
3868 if (cpi->active_best_quality < cpi->best_quality)
3869 cpi->active_best_quality = cpi->best_quality;
3871 if ( cpi->active_worst_quality < cpi->active_best_quality )
3872 cpi->active_worst_quality = cpi->active_best_quality;
3874 // Determine initial Q to try
3875 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3876 last_zbin_oq = cpi->zbin_over_quant;
3878 // Set highest allowed value for Zbin over quant
3879 if (cm->frame_type == KEY_FRAME)
3880 zbin_oq_high = 0; //ZBIN_OQ_MAX/16
3881 else if ((cpi->oxcf.number_of_layers == 1) && ((cm->refresh_alt_ref_frame ||
3882 (cm->refresh_golden_frame && !cpi->source_alt_ref_active))))
3887 zbin_oq_high = ZBIN_OQ_MAX;
3889 // Setup background Q adjustment for error resilient mode.
3890 // For multi-layer encodes only enable this for the base layer.
3891 if (cpi->cyclic_refresh_mode_enabled && (cpi->current_layer==0))
3892 cyclic_background_refresh(cpi, Q, 0);
3894 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3896 // Limit Q range for the adaptive loop.
3897 bottom_index = cpi->active_best_quality;
3898 top_index = cpi->active_worst_quality;
3899 q_low = cpi->active_best_quality;
3900 q_high = cpi->active_worst_quality;
3902 vp8_save_coding_context(cpi);
3907 scale_and_extend_source(cpi->un_scaled_source, cpi);
3908 #if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC
3910 if (cpi->oxcf.noise_sensitivity > 0)
3915 switch (cpi->oxcf.noise_sensitivity)
3938 if (cm->frame_type == KEY_FRAME)
3940 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0, RTCD(postproc));
3944 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0, RTCD(postproc));
3946 src = cpi->Source->y_buffer;
3948 if (cpi->Source->y_stride < 0)
3950 src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
3957 #ifdef OUTPUT_YUV_SRC
3958 vp8_write_yuv_frame(cpi->Source);
3963 vp8_clear_system_state(); //__asm emms;
3966 if(cpi->is_src_frame_alt_ref)
3970 vp8_set_quantizer(cpi, Q);
3973 // setup skip prob for costing in mode/mv decision
3974 if (cpi->common.mb_no_coeff_skip)
3976 cpi->prob_skip_false = cpi->base_skip_false_prob[Q];
3978 if (cm->frame_type != KEY_FRAME)
3980 if (cpi->common.refresh_alt_ref_frame)
3982 if (cpi->last_skip_false_probs[2] != 0)
3983 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3986 if(cpi->last_skip_false_probs[2]!=0 && abs(Q- cpi->last_skip_probs_q[2])<=16 )
3987 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3988 else if (cpi->last_skip_false_probs[2]!=0)
3989 cpi->prob_skip_false = (cpi->last_skip_false_probs[2] + cpi->prob_skip_false ) / 2;
3992 else if (cpi->common.refresh_golden_frame)
3994 if (cpi->last_skip_false_probs[1] != 0)
3995 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3998 if(cpi->last_skip_false_probs[1]!=0 && abs(Q- cpi->last_skip_probs_q[1])<=16 )
3999 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
4000 else if (cpi->last_skip_false_probs[1]!=0)
4001 cpi->prob_skip_false = (cpi->last_skip_false_probs[1] + cpi->prob_skip_false ) / 2;
4006 if (cpi->last_skip_false_probs[0] != 0)
4007 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
4010 if(cpi->last_skip_false_probs[0]!=0 && abs(Q- cpi->last_skip_probs_q[0])<=16 )
4011 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
4012 else if(cpi->last_skip_false_probs[0]!=0)
4013 cpi->prob_skip_false = (cpi->last_skip_false_probs[0] + cpi->prob_skip_false ) / 2;
4017 //as this is for cost estimate, let's make sure it does not go extreme eitehr way
4018 if (cpi->prob_skip_false < 5)
4019 cpi->prob_skip_false = 5;
4021 if (cpi->prob_skip_false > 250)
4022 cpi->prob_skip_false = 250;
4024 if (cpi->oxcf.number_of_layers == 1 && cpi->is_src_frame_alt_ref)
4025 cpi->prob_skip_false = 1;
4032 FILE *f = fopen("skip.stt", "a");
4033 fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
4041 if (cm->frame_type == KEY_FRAME)
4043 resize_key_frame(cpi);
4044 vp8_setup_key_frame(cpi);
4047 #if CONFIG_MULTITHREAD
4048 /* wait for loopfilter thread done (for last picture)
4049 * don't do it for first frame, re-code and when PSNR is calculated
4051 if (cpi->b_multi_threaded && cm->current_video_frame && (!Loop) &&
4052 (!cpi->b_calculate_psnr))
4054 sem_wait(&cpi->h_event_end_lpf);
4058 // transform / motion compensation build reconstruction frame
4059 vp8_encode_frame(cpi);
4061 cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
4062 cpi->projected_frame_size = (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
4064 vp8_clear_system_state(); //__asm emms;
4066 // Test to see if the stats generated for this frame indicate that we should have coded a key frame
4067 // (assuming that we didn't)!
4068 if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
4070 int key_frame_decision = decide_key_frame(cpi);
4072 if (cpi->compressor_speed == 2)
4074 /* we don't do re-encoding in realtime mode
4075 * if key frame is decided than we force it on next frame */
4076 cpi->force_next_frame_intra = key_frame_decision;
4078 else if (key_frame_decision)
4080 // Reset all our sizing numbers and recode
4081 cm->frame_type = KEY_FRAME;
4083 vp8_pick_frame_size(cpi);
4085 // Clear the Alt reference frame active flag when we have a key frame
4086 cpi->source_alt_ref_active = FALSE;
4088 // Reset the loop filter deltas and segmentation map
4089 setup_features(cpi);
4091 // If segmentation is enabled force a map update for key frames
4092 if (cpi->mb.e_mbd.segmentation_enabled)
4094 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
4095 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
4098 vp8_restore_coding_context(cpi);
4100 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4102 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
4104 // Limit Q range for the adaptive loop.
4105 bottom_index = cpi->active_best_quality;
4106 top_index = cpi->active_worst_quality;
4107 q_low = cpi->active_best_quality;
4108 q_high = cpi->active_worst_quality;
4117 vp8_clear_system_state();
4119 if (frame_over_shoot_limit == 0)
4120 frame_over_shoot_limit = 1;
4122 // Are we are overshooting and up against the limit of active max Q.
4123 if (((cpi->pass != 2) || (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
4124 (Q == cpi->active_worst_quality) &&
4125 (cpi->active_worst_quality < cpi->worst_quality) &&
4126 (cpi->projected_frame_size > frame_over_shoot_limit))
4128 int over_size_percent = ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) / frame_over_shoot_limit;
4130 // If so is there any scope for relaxing it
4131 while ((cpi->active_worst_quality < cpi->worst_quality) && (over_size_percent > 0))
4133 cpi->active_worst_quality++;
4134 top_index = cpi->active_worst_quality;
4135 over_size_percent = (int)(over_size_percent * 0.96); // Assume 1 qstep = about 4% on frame size.
4138 // If we have updated the active max Q do not call vp8_update_rate_correction_factors() this loop.
4139 active_worst_qchanged = TRUE;
4142 active_worst_qchanged = FALSE;
4144 #if !(CONFIG_REALTIME_ONLY)
4145 // Special case handling for forced key frames
4146 if ( (cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced )
4149 int kf_err = vp8_calc_ss_err(cpi->Source,
4150 &cm->yv12_fb[cm->new_fb_idx],
4151 IF_RTCD(&cpi->rtcd.variance));
4153 // The key frame is not good enough
4154 if ( kf_err > ((cpi->ambient_err * 7) >> 3) )
4157 q_high = (Q > q_low) ? (Q - 1) : q_low;
4160 Q = (q_high + q_low) >> 1;
4162 // The key frame is much better than the previous frame
4163 else if ( kf_err < (cpi->ambient_err >> 1) )
4166 q_low = (Q < q_high) ? (Q + 1) : q_high;
4169 Q = (q_high + q_low + 1) >> 1;
4172 // Clamp Q to upper and lower limits:
4178 Loop = ((Q != last_q)) ? TRUE : FALSE;
4181 // Is the projected frame size out of range and are we allowed to attempt to recode.
4182 else if ( recode_loop_test( cpi,
4183 frame_over_shoot_limit, frame_under_shoot_limit,
4184 Q, top_index, bottom_index ) )
4189 // Frame size out of permitted range:
4190 // Update correction factor & compute new Q to try...
4192 // Frame is too large
4193 if (cpi->projected_frame_size > cpi->this_frame_target)
4195 //if ( cpi->zbin_over_quant == 0 )
4196 q_low = (Q < q_high) ? (Q + 1) : q_high; // Raise Qlow as to at least the current value
4198 if (cpi->zbin_over_quant > 0) // If we are using over quant do the same for zbin_oq_low
4199 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
4201 //if ( undershoot_seen || (Q == MAXQ) )
4202 if (undershoot_seen)
4204 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
4205 if (!active_worst_qchanged)
4206 vp8_update_rate_correction_factors(cpi, 1);
4208 Q = (q_high + q_low + 1) / 2;
4210 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
4212 cpi->zbin_over_quant = 0;
4215 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
4216 cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
4221 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
4222 if (!active_worst_qchanged)
4223 vp8_update_rate_correction_factors(cpi, 0);
4225 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4227 while (((Q < q_low) || (cpi->zbin_over_quant < zbin_oq_low)) && (Retries < 10))
4229 vp8_update_rate_correction_factors(cpi, 0);
4230 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4235 overshoot_seen = TRUE;
4237 // Frame is too small
4240 if (cpi->zbin_over_quant == 0)
4241 q_high = (Q > q_low) ? (Q - 1) : q_low; // Lower q_high if not using over quant
4242 else // else lower zbin_oq_high
4243 zbin_oq_high = (cpi->zbin_over_quant > zbin_oq_low) ? (cpi->zbin_over_quant - 1) : zbin_oq_low;
4247 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
4248 if (!active_worst_qchanged)
4249 vp8_update_rate_correction_factors(cpi, 1);
4251 Q = (q_high + q_low) / 2;
4253 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
4255 cpi->zbin_over_quant = 0;
4257 cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
4261 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
4262 if (!active_worst_qchanged)
4263 vp8_update_rate_correction_factors(cpi, 0);
4265 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4267 // Special case reset for qlow for constrained quality.
4268 // This should only trigger where there is very substantial
4269 // undershoot on a frame and the auto cq level is above
4270 // the user passsed in value.
4271 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
4277 while (((Q > q_high) || (cpi->zbin_over_quant > zbin_oq_high)) && (Retries < 10))
4279 vp8_update_rate_correction_factors(cpi, 0);
4280 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4285 undershoot_seen = TRUE;
4288 // Clamp Q to upper and lower limits:
4294 // Clamp cpi->zbin_over_quant
4295 cpi->zbin_over_quant = (cpi->zbin_over_quant < zbin_oq_low) ? zbin_oq_low : (cpi->zbin_over_quant > zbin_oq_high) ? zbin_oq_high : cpi->zbin_over_quant;
4297 //Loop = ((Q != last_q) || (last_zbin_oq != cpi->zbin_over_quant)) ? TRUE : FALSE;
4298 Loop = ((Q != last_q)) ? TRUE : FALSE;
4299 last_zbin_oq = cpi->zbin_over_quant;
4305 if (cpi->is_src_frame_alt_ref)
4310 vp8_restore_coding_context(cpi);
4312 #if CONFIG_INTERNAL_STATS
4313 cpi->tot_recode_hits++;
4317 while (Loop == TRUE);
4320 // Experimental code for lagged and one pass
4321 // Update stats used for one pass GF selection
4325 double frame_intra_error;
4326 double frame_coded_error;
4327 double frame_pcnt_inter;
4328 double frame_pcnt_motion;
4330 double frame_mvr_abs;
4332 double frame_mvc_abs;
4335 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
4336 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
4337 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
4341 // Special case code to reduce pulsing when key frames are forced at a
4342 // fixed interval. Note the reconstruction error if it is the frame before
4343 // the force key frame
4344 if ( cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0) )
4346 cpi->ambient_err = vp8_calc_ss_err(cpi->Source,
4347 &cm->yv12_fb[cm->new_fb_idx],
4348 IF_RTCD(&cpi->rtcd.variance));
4351 /* This frame's MVs are saved and will be used in next frame's MV predictor.
4352 * Last frame has one more line(add to bottom) and one more column(add to
4353 * right) than cm->mip. The edge elements are initialized to 0.
4355 #if CONFIG_MULTI_RES_ENCODING
4356 if(!cpi->oxcf.mr_encoder_id && cm->show_frame)
4358 if(cm->show_frame) /* do not save for altref frame */
4363 /* Point to beginning of allocated MODE_INFO arrays. */
4364 MODE_INFO *tmp = cm->mip;
4366 if(cm->frame_type != KEY_FRAME)
4368 for (mb_row = 0; mb_row < cm->mb_rows+1; mb_row ++)
4370 for (mb_col = 0; mb_col < cm->mb_cols+1; mb_col ++)
4372 if(tmp->mbmi.ref_frame != INTRA_FRAME)
4373 cpi->lfmv[mb_col + mb_row*(cm->mode_info_stride+1)].as_int = tmp->mbmi.mv.as_int;
4375 cpi->lf_ref_frame_sign_bias[mb_col + mb_row*(cm->mode_info_stride+1)] = cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
4376 cpi->lf_ref_frame[mb_col + mb_row*(cm->mode_info_stride+1)] = tmp->mbmi.ref_frame;
4383 #if CONFIG_MULTI_RES_ENCODING
4384 vp8_cal_dissimilarity(cpi);
4387 // Update the GF useage maps.
4388 // This is done after completing the compression of a frame when all
4389 // modes etc. are finalized but before loop filter
4390 if (cpi->oxcf.number_of_layers == 1)
4391 vp8_update_gf_useage_maps(cpi, cm, &cpi->mb);
4393 if (cm->frame_type == KEY_FRAME)
4394 cm->refresh_last_frame = 1;
4398 FILE *f = fopen("gfactive.stt", "a");
4399 fprintf(f, "%8d %8d %8d %8d %8d\n", cm->current_video_frame, (100 * cpi->gf_active_count) / (cpi->common.mb_rows * cpi->common.mb_cols), cpi->this_iiratio, cpi->next_iiratio, cm->refresh_golden_frame);
4404 // For inter frames the current default behavior is that when
4405 // cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
4406 // This is purely an encoder decision at present.
4407 if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame)
4408 cm->copy_buffer_to_arf = 2;
4410 cm->copy_buffer_to_arf = 0;
4412 cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
4414 #if CONFIG_MULTITHREAD
4415 if (cpi->b_multi_threaded)
4417 sem_post(&cpi->h_event_start_lpf); /* start loopfilter in separate thread */
4422 loopfilter_frame(cpi, cm);
4425 update_reference_frames(cm);
4427 if (cpi->oxcf.error_resilient_mode)
4429 cm->refresh_entropy_probs = 0;
4432 #if CONFIG_MULTITHREAD
4433 /* wait that filter_level is picked so that we can continue with stream packing */
4434 if (cpi->b_multi_threaded)
4435 sem_wait(&cpi->h_event_end_lpf);
4438 // build the bitstream
4439 vp8_pack_bitstream(cpi, dest, dest_end, size);
4441 #if CONFIG_MULTITHREAD
4442 /* if PSNR packets are generated we have to wait for the lpf */
4443 if (cpi->b_multi_threaded && cpi->b_calculate_psnr)
4445 sem_wait(&cpi->h_event_end_lpf);
4449 /* Move storing frame_type out of the above loop since it is also
4450 * needed in motion search besides loopfilter */
4451 cm->last_frame_type = cm->frame_type;
4453 // Update rate control heuristics
4454 cpi->total_byte_count += (*size);
4455 cpi->projected_frame_size = (*size) << 3;
4457 if (cpi->oxcf.number_of_layers > 1)
4460 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
4461 cpi->layer_context[i].total_byte_count += (*size);
4464 if (!active_worst_qchanged)
4465 vp8_update_rate_correction_factors(cpi, 2);
4467 cpi->last_q[cm->frame_type] = cm->base_qindex;
4469 if (cm->frame_type == KEY_FRAME)
4471 vp8_adjust_key_frame_context(cpi);
4474 // Keep a record of ambient average Q.
4475 if (cm->frame_type != KEY_FRAME)
4476 cpi->avg_frame_qindex = (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
4478 // Keep a record from which we can calculate the average Q excluding GF updates and key frames
4479 if ((cm->frame_type != KEY_FRAME) && ((cpi->oxcf.number_of_layers > 1) ||
4480 (!cm->refresh_golden_frame && !cm->refresh_alt_ref_frame)))
4484 // Calculate the average Q for normal inter frames (not key or GFU
4486 if ( cpi->pass == 2 )
4488 cpi->ni_tot_qi += Q;
4489 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4493 // Damp value for first few frames
4494 if (cpi->ni_frames > 150 )
4496 cpi->ni_tot_qi += Q;
4497 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4499 // For one pass, early in the clip ... average the current frame Q
4500 // value with the worstq entered by the user as a dampening measure
4503 cpi->ni_tot_qi += Q;
4504 cpi->ni_av_qi = ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
4507 // If the average Q is higher than what was used in the last frame
4508 // (after going through the recode loop to keep the frame size within range)
4509 // then use the last frame value - 1.
4510 // The -1 is designed to stop Q and hence the data rate, from progressively
4511 // falling away during difficult sections, but at the same time reduce the number of
4512 // itterations around the recode loop.
4513 if (Q > cpi->ni_av_qi)
4514 cpi->ni_av_qi = Q - 1;
4520 // If the frame was massively oversize and we are below optimal buffer level drop next frame
4521 if ((cpi->drop_frames_allowed) &&
4522 (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
4523 (cpi->buffer_level < cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100) &&
4524 (cpi->projected_frame_size > (4 * cpi->this_frame_target)))
4526 cpi->drop_frame = TRUE;
4531 // Set the count for maximum consecutive dropped frames based upon the ratio of
4532 // this frame size to the target average per frame bandwidth.
4533 // (cpi->av_per_frame_bandwidth > 0) is just a sanity check to prevent / 0.
4534 if (cpi->drop_frames_allowed && (cpi->av_per_frame_bandwidth > 0))
4536 cpi->max_drop_count = cpi->projected_frame_size / cpi->av_per_frame_bandwidth;
4538 if (cpi->max_drop_count > cpi->max_consec_dropped_frames)
4539 cpi->max_drop_count = cpi->max_consec_dropped_frames;
4542 // Update the buffer level variable.
4543 // Non-viewable frames are a special case and are treated as pure overhead.
4544 if ( !cm->show_frame )
4545 cpi->bits_off_target -= cpi->projected_frame_size;
4547 cpi->bits_off_target += cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
4549 // Clip the buffer level to the maximum specified buffer size
4550 if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
4551 cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
4553 // Rolling monitors of whether we are over or underspending used to help regulate min and Max Q in two pass.
4554 cpi->rolling_target_bits = ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
4555 cpi->rolling_actual_bits = ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
4556 cpi->long_rolling_target_bits = ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
4557 cpi->long_rolling_actual_bits = ((cpi->long_rolling_actual_bits * 31) + cpi->projected_frame_size + 16) / 32;
4559 // Actual bits spent
4560 cpi->total_actual_bits += cpi->projected_frame_size;
4563 cpi->total_target_vs_actual += (cpi->this_frame_target - cpi->projected_frame_size);
4565 cpi->buffer_level = cpi->bits_off_target;
4567 // Propagate values to higher temporal layers
4568 if (cpi->oxcf.number_of_layers > 1)
4572 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
4574 LAYER_CONTEXT *lc = &cpi->layer_context[i];
4575 int bits_off_for_this_layer = lc->target_bandwidth / lc->frame_rate
4576 - cpi->projected_frame_size;
4578 lc->bits_off_target += bits_off_for_this_layer;
4580 // Clip buffer level to maximum buffer size for the layer
4581 if (lc->bits_off_target > lc->maximum_buffer_size)
4582 lc->bits_off_target = lc->maximum_buffer_size;
4584 lc->total_actual_bits += cpi->projected_frame_size;
4585 lc->total_target_vs_actual += bits_off_for_this_layer;
4586 lc->buffer_level = lc->bits_off_target;
4590 // Update bits left to the kf and gf groups to account for overshoot or undershoot on these frames
4591 if (cm->frame_type == KEY_FRAME)
4593 cpi->twopass.kf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4595 if (cpi->twopass.kf_group_bits < 0)
4596 cpi->twopass.kf_group_bits = 0 ;
4598 else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4600 cpi->twopass.gf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4602 if (cpi->twopass.gf_group_bits < 0)
4603 cpi->twopass.gf_group_bits = 0 ;
4606 if (cm->frame_type != KEY_FRAME)
4608 if (cpi->common.refresh_alt_ref_frame)
4610 cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
4611 cpi->last_skip_probs_q[2] = cm->base_qindex;
4613 else if (cpi->common.refresh_golden_frame)
4615 cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
4616 cpi->last_skip_probs_q[1] = cm->base_qindex;
4620 cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
4621 cpi->last_skip_probs_q[0] = cm->base_qindex;
4623 //update the baseline
4624 cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
4629 #if 0 && CONFIG_INTERNAL_STATS
4631 FILE *f = fopen("tmp.stt", "a");
4633 vp8_clear_system_state(); //__asm emms;
4635 if (cpi->twopass.total_left_stats->coded_error != 0.0)
4636 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4637 "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4639 cpi->common.current_video_frame, cpi->this_frame_target,
4640 cpi->projected_frame_size,
4641 (cpi->projected_frame_size - cpi->this_frame_target),
4642 (int)cpi->total_target_vs_actual,
4643 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4644 (int)cpi->total_actual_bits, cm->base_qindex,
4645 cpi->active_best_quality, cpi->active_worst_quality,
4646 cpi->ni_av_qi, cpi->cq_target_quality,
4647 cpi->zbin_over_quant,
4648 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4649 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4650 cm->frame_type, cpi->gfu_boost,
4651 cpi->twopass.est_max_qcorrection_factor,
4652 (int)cpi->twopass.bits_left,
4653 cpi->twopass.total_left_stats->coded_error,
4654 (double)cpi->twopass.bits_left /
4655 cpi->twopass.total_left_stats->coded_error,
4656 cpi->tot_recode_hits);
4658 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4659 "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4661 cpi->common.current_video_frame,
4662 cpi->this_frame_target, cpi->projected_frame_size,
4663 (cpi->projected_frame_size - cpi->this_frame_target),
4664 (int)cpi->total_target_vs_actual,
4665 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4666 (int)cpi->total_actual_bits, cm->base_qindex,
4667 cpi->active_best_quality, cpi->active_worst_quality,
4668 cpi->ni_av_qi, cpi->cq_target_quality,
4669 cpi->zbin_over_quant,
4670 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4671 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4672 cm->frame_type, cpi->gfu_boost,
4673 cpi->twopass.est_max_qcorrection_factor,
4674 (int)cpi->twopass.bits_left,
4675 cpi->twopass.total_left_stats->coded_error,
4676 cpi->tot_recode_hits);
4681 FILE *fmodes = fopen("Modes.stt", "a");
4684 fprintf(fmodes, "%6d:%1d:%1d:%1d ",
4685 cpi->common.current_video_frame,
4686 cm->frame_type, cm->refresh_golden_frame,
4687 cm->refresh_alt_ref_frame);
4689 for (i = 0; i < MAX_MODES; i++)
4690 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
4692 fprintf(fmodes, "\n");
4700 // If this was a kf or Gf note the Q
4701 if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4702 cm->last_kf_gf_q = cm->base_qindex;
4704 if (cm->refresh_golden_frame == 1)
4705 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
4707 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
4709 if (cm->refresh_alt_ref_frame == 1)
4710 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
4712 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
4715 if (cm->refresh_last_frame & cm->refresh_golden_frame) // both refreshed
4716 cpi->gold_is_last = 1;
4717 else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4718 cpi->gold_is_last = 0;
4720 if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) // both refreshed
4721 cpi->alt_is_last = 1;
4722 else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) // 1 refreshed but not the other
4723 cpi->alt_is_last = 0;
4725 if (cm->refresh_alt_ref_frame & cm->refresh_golden_frame) // both refreshed
4726 cpi->gold_is_alt = 1;
4727 else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4728 cpi->gold_is_alt = 0;
4730 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
4732 if (cpi->gold_is_last)
4733 cpi->ref_frame_flags &= ~VP8_GOLD_FLAG;
4735 if (cpi->alt_is_last)
4736 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4738 if (cpi->gold_is_alt)
4739 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4742 if (!cpi->oxcf.error_resilient_mode)
4744 if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame && (cm->frame_type != KEY_FRAME))
4745 // Update the alternate reference frame stats as appropriate.
4746 update_alt_ref_frame_stats(cpi);
4748 // Update the Golden frame stats as appropriate.
4749 update_golden_frame_stats(cpi);
4752 if (cm->frame_type == KEY_FRAME)
4754 // Tell the caller that the frame was coded as a key frame
4755 *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
4757 // As this frame is a key frame the next defaults to an inter frame.
4758 cm->frame_type = INTER_FRAME;
4760 cpi->last_frame_percent_intra = 100;
4764 *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
4766 cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
4769 // Clear the one shot update flags for segmentation map and mode/ref loop filter deltas.
4770 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
4771 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
4772 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
4775 // Dont increment frame counters if this was an altref buffer update not a real frame
4778 cm->current_video_frame++;
4779 cpi->frames_since_key++;
4782 // reset to normal state now that we are done.
4790 sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
4791 recon_file = fopen(filename, "wb");
4792 fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
4793 cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
4799 //vp8_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show);
4805 static void check_gf_quality(VP8_COMP *cpi)
4807 VP8_COMMON *cm = &cpi->common;
4808 int gf_active_pct = (100 * cpi->gf_active_count) / (cm->mb_rows * cm->mb_cols);
4809 int gf_ref_usage_pct = (cpi->count_mb_ref_frame_usage[GOLDEN_FRAME] * 100) / (cm->mb_rows * cm->mb_cols);
4810 int last_ref_zz_useage = (cpi->inter_zz_count * 100) / (cm->mb_rows * cm->mb_cols);
4812 // Gf refresh is not currently being signalled
4813 if (cpi->gf_update_recommended == 0)
4815 if (cpi->common.frames_since_golden > 7)
4818 if ((gf_active_pct < 10) || ((gf_active_pct + gf_ref_usage_pct) < 15))
4820 // ...but last frame zero zero usage is reasonbable so a new gf might be appropriate
4821 if (last_ref_zz_useage >= 25)
4823 cpi->gf_bad_count ++;
4825 if (cpi->gf_bad_count >= 8) // Check that the condition is stable
4827 cpi->gf_update_recommended = 1;
4828 cpi->gf_bad_count = 0;
4832 cpi->gf_bad_count = 0; // Restart count as the background is not stable enough
4835 cpi->gf_bad_count = 0; // Gf useage has picked up so reset count
4838 // If the signal is set but has not been read should we cancel it.
4839 else if (last_ref_zz_useage < 15)
4841 cpi->gf_update_recommended = 0;
4842 cpi->gf_bad_count = 0;
4847 FILE *f = fopen("gfneeded.stt", "a");
4848 fprintf(f, "%10d %10d %10d %10d %10ld \n",
4849 cm->current_video_frame,
4850 cpi->common.frames_since_golden,
4851 gf_active_pct, gf_ref_usage_pct,
4852 cpi->gf_update_recommended);
4859 #if !(CONFIG_REALTIME_ONLY)
4860 static void Pass2Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned char * dest_end, unsigned int *frame_flags)
4863 if (!cpi->common.refresh_alt_ref_frame)
4864 vp8_second_pass(cpi);
4866 encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
4867 cpi->twopass.bits_left -= 8 * *size;
4869 if (!cpi->common.refresh_alt_ref_frame)
4871 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
4872 *cpi->oxcf.two_pass_vbrmin_section / 100);
4873 cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->frame_rate);
4878 //For ARM NEON, d8-d15 are callee-saved registers, and need to be saved by us.
4880 extern void vp8_push_neon(int64_t *store);
4881 extern void vp8_pop_neon(int64_t *store);
4885 int vp8_receive_raw_frame(VP8_PTR ptr, unsigned int frame_flags, YV12_BUFFER_CONFIG *sd, int64_t time_stamp, int64_t end_time)
4888 int64_t store_reg[8];
4890 VP8_COMP *cpi = (VP8_COMP *) ptr;
4891 VP8_COMMON *cm = &cpi->common;
4892 struct vpx_usec_timer timer;
4896 #if CONFIG_RUNTIME_CPU_DETECT
4897 if (cm->rtcd.flags & HAS_NEON)
4900 vp8_push_neon(store_reg);
4904 vpx_usec_timer_start(&timer);
4905 if(vp8_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4906 frame_flags, cpi->active_map_enabled ? cpi->active_map : NULL))
4908 cm->clr_type = sd->clrtype;
4909 vpx_usec_timer_mark(&timer);
4910 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4913 #if CONFIG_RUNTIME_CPU_DETECT
4914 if (cm->rtcd.flags & HAS_NEON)
4917 vp8_pop_neon(store_reg);
4925 static int frame_is_reference(const VP8_COMP *cpi)
4927 const VP8_COMMON *cm = &cpi->common;
4928 const MACROBLOCKD *xd = &cpi->mb.e_mbd;
4930 return cm->frame_type == KEY_FRAME || cm->refresh_last_frame
4931 || cm->refresh_golden_frame || cm->refresh_alt_ref_frame
4932 || cm->copy_buffer_to_gf || cm->copy_buffer_to_arf
4933 || cm->refresh_entropy_probs
4934 || xd->mode_ref_lf_delta_update
4935 || xd->update_mb_segmentation_map || xd->update_mb_segmentation_data;
4939 int vp8_get_compressed_data(VP8_PTR ptr, unsigned int *frame_flags, unsigned long *size, unsigned char *dest, unsigned char *dest_end, int64_t *time_stamp, int64_t *time_end, int flush)
4942 int64_t store_reg[8];
4944 VP8_COMP *cpi = (VP8_COMP *) ptr;
4946 struct vpx_usec_timer tsctimer;
4947 struct vpx_usec_timer ticktimer;
4948 struct vpx_usec_timer cmptimer;
4949 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4956 if (setjmp(cpi->common.error.jmp))
4958 cpi->common.error.setjmp = 0;
4959 return VPX_CODEC_CORRUPT_FRAME;
4962 cpi->common.error.setjmp = 1;
4965 #if CONFIG_RUNTIME_CPU_DETECT
4966 if (cm->rtcd.flags & HAS_NEON)
4969 vp8_push_neon(store_reg);
4973 vpx_usec_timer_start(&cmptimer);
4977 #if !(CONFIG_REALTIME_ONLY)
4978 // Should we code an alternate reference frame
4979 if (cpi->oxcf.error_resilient_mode == 0 &&
4980 cpi->oxcf.play_alternate &&
4981 cpi->source_alt_ref_pending)
4983 if ((cpi->source = vp8_lookahead_peek(cpi->lookahead,
4984 cpi->frames_till_gf_update_due)))
4986 cpi->alt_ref_source = cpi->source;
4987 if (cpi->oxcf.arnr_max_frames > 0)
4989 vp8_temporal_filter_prepare_c(cpi,
4990 cpi->frames_till_gf_update_due);
4991 force_src_buffer = &cpi->alt_ref_buffer;
4993 cm->frames_till_alt_ref_frame = cpi->frames_till_gf_update_due;
4994 cm->refresh_alt_ref_frame = 1;
4995 cm->refresh_golden_frame = 0;
4996 cm->refresh_last_frame = 0;
4998 cpi->source_alt_ref_pending = FALSE; // Clear Pending alt Ref flag.
4999 cpi->is_src_frame_alt_ref = 0;
5006 if ((cpi->source = vp8_lookahead_pop(cpi->lookahead, flush)))
5010 cpi->is_src_frame_alt_ref = cpi->alt_ref_source
5011 && (cpi->source == cpi->alt_ref_source);
5013 if(cpi->is_src_frame_alt_ref)
5014 cpi->alt_ref_source = NULL;
5020 cpi->un_scaled_source =
5021 cpi->Source = force_src_buffer ? force_src_buffer : &cpi->source->img;
5022 *time_stamp = cpi->source->ts_start;
5023 *time_end = cpi->source->ts_end;
5024 *frame_flags = cpi->source->flags;
5029 #if !(CONFIG_REALTIME_ONLY)
5031 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done)
5033 vp8_end_first_pass(cpi); /* get last stats packet */
5034 cpi->twopass.first_pass_done = 1;
5040 #if CONFIG_RUNTIME_CPU_DETECT
5041 if (cm->rtcd.flags & HAS_NEON)
5044 vp8_pop_neon(store_reg);
5050 // Restore layer specific context if necessary
5051 if (cpi->oxcf.number_of_layers > 1)
5053 restore_layer_context (cpi,
5054 cpi->oxcf.layer_id[cm->current_video_frame % cpi->oxcf.periodicity]);
5057 if (cpi->source->ts_start < cpi->first_time_stamp_ever)
5059 cpi->first_time_stamp_ever = cpi->source->ts_start;
5060 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
5063 // adjust frame rates based on timestamps given
5064 if (cpi->oxcf.number_of_layers > 1 )
5066 vp8_new_frame_rate (
5067 cpi, cpi->layer_context[cpi->current_layer].frame_rate);
5069 cpi->last_time_stamp_seen = cpi->source->ts_start;
5070 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
5073 else if (!cm->refresh_alt_ref_frame)
5075 int64_t this_duration;
5078 if (cpi->source->ts_start == cpi->first_time_stamp_ever)
5080 this_duration = cpi->source->ts_end - cpi->source->ts_start;
5085 int64_t last_duration;
5087 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
5088 last_duration = cpi->last_end_time_stamp_seen
5089 - cpi->last_time_stamp_seen;
5090 // do a step update if the duration changes by 10%
5092 step = ((this_duration - last_duration) * 10 / last_duration);
5098 vp8_new_frame_rate(cpi, 10000000.0 / this_duration);
5101 double avg_duration, interval;
5103 /* Average this frame's rate into the last second's average
5104 * frame rate. If we haven't seen 1 second yet, then average
5105 * over the whole interval seen.
5107 interval = cpi->source->ts_end - cpi->first_time_stamp_ever;
5108 if(interval > 10000000.0)
5109 interval = 10000000;
5111 avg_duration = 10000000.0 / cpi->frame_rate;
5112 avg_duration *= (interval - avg_duration + this_duration);
5113 avg_duration /= interval;
5115 vp8_new_frame_rate(cpi, 10000000.0 / avg_duration);
5119 cpi->last_time_stamp_seen = cpi->source->ts_start;
5120 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
5123 if (cpi->compressor_speed == 2)
5125 if (cpi->oxcf.number_of_layers == 1)
5126 check_gf_quality(cpi);
5127 vpx_usec_timer_start(&tsctimer);
5128 vpx_usec_timer_start(&ticktimer);
5131 // start with a 0 size frame
5134 // Clear down mmx registers
5135 vp8_clear_system_state(); //__asm emms;
5137 cm->frame_type = INTER_FRAME;
5138 cm->frame_flags = *frame_flags;
5142 if (cm->refresh_alt_ref_frame)
5144 //cm->refresh_golden_frame = 1;
5145 cm->refresh_golden_frame = 0;
5146 cm->refresh_last_frame = 0;
5150 cm->refresh_golden_frame = 0;
5151 cm->refresh_last_frame = 1;
5155 /* find a free buffer for the new frame */
5158 for(; i < NUM_YV12_BUFFERS; i++)
5160 if(!cm->yv12_fb[i].flags)
5167 assert(i < NUM_YV12_BUFFERS );
5169 #if !(CONFIG_REALTIME_ONLY)
5173 Pass1Encode(cpi, size, dest, frame_flags);
5175 else if (cpi->pass == 2)
5177 Pass2Encode(cpi, size, dest, dest_end, frame_flags);
5181 encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
5183 if (cpi->compressor_speed == 2)
5185 unsigned int duration, duration2;
5186 vpx_usec_timer_mark(&tsctimer);
5187 vpx_usec_timer_mark(&ticktimer);
5189 duration = vpx_usec_timer_elapsed(&ticktimer);
5190 duration2 = (unsigned int)((double)duration / 2);
5192 if (cm->frame_type != KEY_FRAME)
5194 if (cpi->avg_encode_time == 0)
5195 cpi->avg_encode_time = duration;
5197 cpi->avg_encode_time = (7 * cpi->avg_encode_time + duration) >> 3;
5202 //if(*frame_flags!=1)
5205 if (cpi->avg_pick_mode_time == 0)
5206 cpi->avg_pick_mode_time = duration2;
5208 cpi->avg_pick_mode_time = (7 * cpi->avg_pick_mode_time + duration2) >> 3;
5214 if (cm->refresh_entropy_probs == 0)
5216 vpx_memcpy(&cm->fc, &cm->lfc, sizeof(cm->fc));
5219 // if its a dropped frame honor the requests on subsequent frames
5222 cpi->droppable = !frame_is_reference(cpi);
5224 // return to normal state
5225 cm->refresh_entropy_probs = 1;
5226 cm->refresh_alt_ref_frame = 0;
5227 cm->refresh_golden_frame = 0;
5228 cm->refresh_last_frame = 1;
5229 cm->frame_type = INTER_FRAME;
5233 // Save layer specific state
5234 if (cpi->oxcf.number_of_layers > 1)
5235 save_layer_context (cpi);
5237 vpx_usec_timer_mark(&cmptimer);
5238 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
5240 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
5242 generate_psnr_packet(cpi);
5245 #if CONFIG_INTERNAL_STATS
5249 cpi->bytes += *size;
5256 if (cpi->b_calculate_psnr)
5260 YV12_BUFFER_CONFIG *orig = cpi->Source;
5261 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
5262 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
5263 int y_samples = orig->y_height * orig->y_width ;
5264 int uv_samples = orig->uv_height * orig->uv_width ;
5265 int t_samples = y_samples + 2 * uv_samples;
5266 int64_t sq_error, sq_error2;
5268 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
5269 recon->y_buffer, recon->y_stride, orig->y_width, orig->y_height,
5270 IF_RTCD(&cpi->rtcd.variance));
5272 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
5273 recon->u_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
5274 IF_RTCD(&cpi->rtcd.variance));
5276 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
5277 recon->v_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
5278 IF_RTCD(&cpi->rtcd.variance));
5280 sq_error = ye + ue + ve;
5282 frame_psnr = vp8_mse2psnr(t_samples, 255.0, sq_error);
5284 cpi->total_y += vp8_mse2psnr(y_samples, 255.0, ye);
5285 cpi->total_u += vp8_mse2psnr(uv_samples, 255.0, ue);
5286 cpi->total_v += vp8_mse2psnr(uv_samples, 255.0, ve);
5287 cpi->total_sq_error += sq_error;
5288 cpi->total += frame_psnr;
5290 double frame_psnr2, frame_ssim2 = 0;
5293 vp8_deblock(cm->frame_to_show, &cm->post_proc_buffer, cm->filter_level * 10 / 6, 1, 0, IF_RTCD(&cm->rtcd.postproc));
5294 vp8_clear_system_state();
5296 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
5297 pp->y_buffer, pp->y_stride, orig->y_width, orig->y_height,
5298 IF_RTCD(&cpi->rtcd.variance));
5300 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
5301 pp->u_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
5302 IF_RTCD(&cpi->rtcd.variance));
5304 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
5305 pp->v_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
5306 IF_RTCD(&cpi->rtcd.variance));
5308 sq_error2 = ye + ue + ve;
5310 frame_psnr2 = vp8_mse2psnr(t_samples, 255.0, sq_error2);
5312 cpi->totalp_y += vp8_mse2psnr(y_samples, 255.0, ye);
5313 cpi->totalp_u += vp8_mse2psnr(uv_samples, 255.0, ue);
5314 cpi->totalp_v += vp8_mse2psnr(uv_samples, 255.0, ve);
5315 cpi->total_sq_error2 += sq_error2;
5316 cpi->totalp += frame_psnr2;
5318 frame_ssim2 = vp8_calc_ssim(cpi->Source,
5319 &cm->post_proc_buffer, 1, &weight,
5320 IF_RTCD(&cpi->rtcd.variance));
5322 cpi->summed_quality += frame_ssim2 * weight;
5323 cpi->summed_weights += weight;
5325 if (cpi->oxcf.number_of_layers > 1)
5329 for (i=cpi->current_layer;
5330 i<cpi->oxcf.number_of_layers; i++)
5332 cpi->frames_in_layer[i]++;
5334 cpi->bytes_in_layer[i] += *size;
5335 cpi->sum_psnr[i] += frame_psnr;
5336 cpi->sum_psnr_p[i] += frame_psnr2;
5337 cpi->total_error2[i] += sq_error;
5338 cpi->total_error2_p[i] += sq_error2;
5339 cpi->sum_ssim[i] += frame_ssim2 * weight;
5340 cpi->sum_weights[i] += weight;
5346 if (cpi->b_calculate_ssimg)
5348 double y, u, v, frame_all;
5349 frame_all = vp8_calc_ssimg(cpi->Source, cm->frame_to_show,
5350 &y, &u, &v, IF_RTCD(&cpi->rtcd.variance));
5352 if (cpi->oxcf.number_of_layers > 1)
5356 for (i=cpi->current_layer;
5357 i<cpi->oxcf.number_of_layers; i++)
5359 if (!cpi->b_calculate_psnr)
5360 cpi->frames_in_layer[i]++;
5362 cpi->total_ssimg_y_in_layer[i] += y;
5363 cpi->total_ssimg_u_in_layer[i] += u;
5364 cpi->total_ssimg_v_in_layer[i] += v;
5365 cpi->total_ssimg_all_in_layer[i] += frame_all;
5370 cpi->total_ssimg_y += y;
5371 cpi->total_ssimg_u += u;
5372 cpi->total_ssimg_v += v;
5373 cpi->total_ssimg_all += frame_all;
5382 if (cpi->common.frame_type != 0 && cpi->common.base_qindex == cpi->oxcf.worst_allowed_q)
5384 skiptruecount += cpi->skip_true_count;
5385 skipfalsecount += cpi->skip_false_count;
5393 FILE *f = fopen("skip.stt", "a");
5394 fprintf(f, "frame:%4d flags:%4x Q:%4d P:%4d Size:%5d\n", cpi->common.current_video_frame, *frame_flags, cpi->common.base_qindex, cpi->prob_skip_false, *size);
5396 if (cpi->is_src_frame_alt_ref == 1)
5397 fprintf(f, "skipcount: %4d framesize: %d\n", cpi->skip_true_count , *size);
5406 #if CONFIG_RUNTIME_CPU_DETECT
5407 if (cm->rtcd.flags & HAS_NEON)
5410 vp8_pop_neon(store_reg);
5414 cpi->common.error.setjmp = 0;
5419 int vp8_get_preview_raw_frame(VP8_PTR comp, YV12_BUFFER_CONFIG *dest, vp8_ppflags_t *flags)
5421 VP8_COMP *cpi = (VP8_COMP *) comp;
5423 if (cpi->common.refresh_alt_ref_frame)
5429 ret = vp8_post_proc_frame(&cpi->common, dest, flags);
5432 if (cpi->common.frame_to_show)
5434 *dest = *cpi->common.frame_to_show;
5435 dest->y_width = cpi->common.Width;
5436 dest->y_height = cpi->common.Height;
5437 dest->uv_height = cpi->common.Height / 2;
5445 #endif //!CONFIG_POSTPROC
5446 vp8_clear_system_state();
5451 int vp8_set_roimap(VP8_PTR comp, unsigned char *map, unsigned int rows, unsigned int cols, int delta_q[4], int delta_lf[4], unsigned int threshold[4])
5453 VP8_COMP *cpi = (VP8_COMP *) comp;
5454 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
5456 if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
5461 disable_segmentation((VP8_PTR)cpi);
5465 // Set the segmentation Map
5466 set_segmentation_map((VP8_PTR)cpi, map);
5468 // Activate segmentation.
5469 enable_segmentation((VP8_PTR)cpi);
5471 // Set up the quant segment data
5472 feature_data[MB_LVL_ALT_Q][0] = delta_q[0];
5473 feature_data[MB_LVL_ALT_Q][1] = delta_q[1];
5474 feature_data[MB_LVL_ALT_Q][2] = delta_q[2];
5475 feature_data[MB_LVL_ALT_Q][3] = delta_q[3];
5477 // Set up the loop segment data s
5478 feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
5479 feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
5480 feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
5481 feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
5483 cpi->segment_encode_breakout[0] = threshold[0];
5484 cpi->segment_encode_breakout[1] = threshold[1];
5485 cpi->segment_encode_breakout[2] = threshold[2];
5486 cpi->segment_encode_breakout[3] = threshold[3];
5488 // Initialise the feature data structure
5489 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
5490 set_segment_data((VP8_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
5495 int vp8_set_active_map(VP8_PTR comp, unsigned char *map, unsigned int rows, unsigned int cols)
5497 VP8_COMP *cpi = (VP8_COMP *) comp;
5499 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols)
5503 vpx_memcpy(cpi->active_map, map, rows * cols);
5504 cpi->active_map_enabled = 1;
5507 cpi->active_map_enabled = 0;
5513 //cpi->active_map_enabled = 0;
5518 int vp8_set_internal_size(VP8_PTR comp, VPX_SCALING horiz_mode, VPX_SCALING vert_mode)
5520 VP8_COMP *cpi = (VP8_COMP *) comp;
5522 if (horiz_mode <= ONETWO)
5523 cpi->common.horiz_scale = horiz_mode;
5527 if (vert_mode <= ONETWO)
5528 cpi->common.vert_scale = vert_mode;
5537 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd)
5542 unsigned char *src = source->y_buffer;
5543 unsigned char *dst = dest->y_buffer;
5546 // Loop through the Y plane raw and reconstruction data summing (square differences)
5547 for (i = 0; i < source->y_height; i += 16)
5549 for (j = 0; j < source->y_width; j += 16)
5552 Total += VARIANCE_INVOKE(rtcd, mse16x16)(src + j, source->y_stride, dst + j, dest->y_stride, &sse);
5555 src += 16 * source->y_stride;
5556 dst += 16 * dest->y_stride;
5563 int vp8_get_quantizer(VP8_PTR c)
5565 VP8_COMP *cpi = (VP8_COMP *) c;
5566 return cpi->common.base_qindex;