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 "vpx_scale/yv12extend.h"
28 #include "vp8/common/postproc.h"
30 #include "vpx_mem/vpx_mem.h"
31 #include "vp8/common/swapyv12buffer.h"
32 #include "vp8/common/threading.h"
33 #include "vpx_ports/vpx_timer.h"
34 #include "temporal_filter.h"
36 #include "vpx_ports/arm.h"
38 #if CONFIG_MULTI_RES_ENCODING
39 #include "mr_dissim.h"
46 #if CONFIG_RUNTIME_CPU_DETECT
47 #define IF_RTCD(x) (x)
48 #define RTCD(x) &cpi->common.rtcd.x
50 #define IF_RTCD(x) NULL
54 extern void vp8cx_pick_filter_level_fast(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
55 extern void vp8cx_set_alt_lf_level(VP8_COMP *cpi, int filt_val);
56 extern void vp8cx_pick_filter_level(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
58 extern void vp8_dmachine_specific_config(VP8_COMP *cpi);
59 extern void vp8_cmachine_specific_config(VP8_COMP *cpi);
60 extern void vp8_deblock_frame(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *post, int filt_lvl, int low_var_thresh, int flag);
61 extern void print_parms(VP8_CONFIG *ocf, char *filenam);
62 extern unsigned int vp8_get_processor_freq();
63 extern void print_tree_update_probs();
64 extern void vp8cx_create_encoder_threads(VP8_COMP *cpi);
65 extern void vp8cx_remove_encoder_threads(VP8_COMP *cpi);
67 extern void vp8_yv12_copy_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
68 extern void vp8_yv12_copy_src_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
71 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->starting_buffer_level_in_ms = cpi->oxcf.starting_buffer_level_in_ms;
254 lc->optimal_buffer_level_in_ms = cpi->oxcf.optimal_buffer_level_in_ms;
255 lc->maximum_buffer_size_in_ms = cpi->oxcf.maximum_buffer_size_in_ms;
256 lc->buffer_level = cpi->buffer_level;
257 lc->bits_off_target = cpi->bits_off_target;
258 lc->total_actual_bits = cpi->total_actual_bits;
259 lc->worst_quality = cpi->worst_quality;
260 lc->active_worst_quality = cpi->active_worst_quality;
261 lc->best_quality = cpi->best_quality;
262 lc->active_best_quality = cpi->active_best_quality;
263 lc->ni_av_qi = cpi->ni_av_qi;
264 lc->ni_tot_qi = cpi->ni_tot_qi;
265 lc->ni_frames = cpi->ni_frames;
266 lc->avg_frame_qindex = cpi->avg_frame_qindex;
267 lc->rate_correction_factor = cpi->rate_correction_factor;
268 lc->key_frame_rate_correction_factor = cpi->key_frame_rate_correction_factor;
269 lc->gf_rate_correction_factor = cpi->gf_rate_correction_factor;
270 lc->zbin_over_quant = cpi->zbin_over_quant;
271 lc->inter_frame_target = cpi->inter_frame_target;
272 lc->total_byte_count = cpi->total_byte_count;
273 lc->filter_level = cpi->common.filter_level;
275 lc->last_frame_percent_intra = cpi->last_frame_percent_intra;
277 memcpy (lc->count_mb_ref_frame_usage,
278 cpi->count_mb_ref_frame_usage,
279 sizeof(cpi->count_mb_ref_frame_usage));
282 static void restore_layer_context(VP8_COMP *cpi, const int layer)
284 LAYER_CONTEXT *lc = &cpi->layer_context[layer];
286 // Restore layer dependent coding state
287 cpi->current_layer = layer;
288 cpi->target_bandwidth = lc->target_bandwidth;
289 cpi->oxcf.target_bandwidth = lc->target_bandwidth;
290 cpi->oxcf.starting_buffer_level = lc->starting_buffer_level;
291 cpi->oxcf.optimal_buffer_level = lc->optimal_buffer_level;
292 cpi->oxcf.maximum_buffer_size = lc->maximum_buffer_size;
293 cpi->oxcf.starting_buffer_level_in_ms = lc->starting_buffer_level_in_ms;
294 cpi->oxcf.optimal_buffer_level_in_ms = lc->optimal_buffer_level_in_ms;
295 cpi->oxcf.maximum_buffer_size_in_ms = lc->maximum_buffer_size_in_ms;
296 cpi->buffer_level = lc->buffer_level;
297 cpi->bits_off_target = lc->bits_off_target;
298 cpi->total_actual_bits = lc->total_actual_bits;
299 //cpi->worst_quality = lc->worst_quality;
300 cpi->active_worst_quality = lc->active_worst_quality;
301 //cpi->best_quality = lc->best_quality;
302 cpi->active_best_quality = lc->active_best_quality;
303 cpi->ni_av_qi = lc->ni_av_qi;
304 cpi->ni_tot_qi = lc->ni_tot_qi;
305 cpi->ni_frames = lc->ni_frames;
306 cpi->avg_frame_qindex = lc->avg_frame_qindex;
307 cpi->rate_correction_factor = lc->rate_correction_factor;
308 cpi->key_frame_rate_correction_factor = lc->key_frame_rate_correction_factor;
309 cpi->gf_rate_correction_factor = lc->gf_rate_correction_factor;
310 cpi->zbin_over_quant = lc->zbin_over_quant;
311 cpi->inter_frame_target = lc->inter_frame_target;
312 cpi->total_byte_count = lc->total_byte_count;
313 cpi->common.filter_level = lc->filter_level;
315 cpi->last_frame_percent_intra = lc->last_frame_percent_intra;
317 memcpy (cpi->count_mb_ref_frame_usage,
318 lc->count_mb_ref_frame_usage,
319 sizeof(cpi->count_mb_ref_frame_usage));
322 static void setup_features(VP8_COMP *cpi)
324 // Set up default state for MB feature flags
325 cpi->mb.e_mbd.segmentation_enabled = 0;
326 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
327 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
328 vpx_memset(cpi->mb.e_mbd.mb_segment_tree_probs, 255, sizeof(cpi->mb.e_mbd.mb_segment_tree_probs));
329 vpx_memset(cpi->mb.e_mbd.segment_feature_data, 0, sizeof(cpi->mb.e_mbd.segment_feature_data));
331 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 0;
332 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
333 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
334 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
335 vpx_memset(cpi->mb.e_mbd.last_ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
336 vpx_memset(cpi->mb.e_mbd.last_mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
338 set_default_lf_deltas(cpi);
343 static void dealloc_compressor_data(VP8_COMP *cpi)
345 vpx_free(cpi->tplist);
348 // Delete last frame MV storage buffers
352 vpx_free(cpi->lf_ref_frame_sign_bias);
353 cpi->lf_ref_frame_sign_bias = 0;
355 vpx_free(cpi->lf_ref_frame);
356 cpi->lf_ref_frame = 0;
358 // Delete sementation map
359 vpx_free(cpi->segmentation_map);
360 cpi->segmentation_map = 0;
362 vpx_free(cpi->active_map);
365 vp8_de_alloc_frame_buffers(&cpi->common);
367 vp8_yv12_de_alloc_frame_buffer(&cpi->pick_lf_lvl_frame);
368 vp8_yv12_de_alloc_frame_buffer(&cpi->scaled_source);
369 #if VP8_TEMPORAL_ALT_REF
370 vp8_yv12_de_alloc_frame_buffer(&cpi->alt_ref_buffer);
372 vp8_lookahead_destroy(cpi->lookahead);
377 // Structure used to monitor GF usage
378 vpx_free(cpi->gf_active_flags);
379 cpi->gf_active_flags = 0;
381 // Activity mask based per mb zbin adjustments
382 vpx_free(cpi->mb_activity_map);
383 cpi->mb_activity_map = 0;
384 vpx_free(cpi->mb_norm_activity_map);
385 cpi->mb_norm_activity_map = 0;
387 vpx_free(cpi->mb.pip);
391 static void enable_segmentation(VP8_COMP *cpi)
393 // Set the appropriate feature bit
394 cpi->mb.e_mbd.segmentation_enabled = 1;
395 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
396 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
398 static void disable_segmentation(VP8_COMP *cpi)
400 // Clear the appropriate feature bit
401 cpi->mb.e_mbd.segmentation_enabled = 0;
404 // Valid values for a segment are 0 to 3
405 // Segmentation map is arrange as [Rows][Columns]
406 static void set_segmentation_map(VP8_COMP *cpi, unsigned char *segmentation_map)
408 // Copy in the new segmentation map
409 vpx_memcpy(cpi->segmentation_map, segmentation_map, (cpi->common.mb_rows * cpi->common.mb_cols));
411 // Signal that the map should be updated.
412 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
413 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
416 // The values given for each segment can be either deltas (from the default value chosen for the frame) or absolute values.
418 // Valid range for abs values is (0-127 for MB_LVL_ALT_Q) , (0-63 for SEGMENT_ALT_LF)
419 // Valid range for delta values are (+/-127 for MB_LVL_ALT_Q) , (+/-63 for SEGMENT_ALT_LF)
421 // abs_delta = SEGMENT_DELTADATA (deltas) abs_delta = SEGMENT_ABSDATA (use the absolute values given).
424 static void set_segment_data(VP8_COMP *cpi, signed char *feature_data, unsigned char abs_delta)
426 cpi->mb.e_mbd.mb_segement_abs_delta = abs_delta;
427 vpx_memcpy(cpi->segment_feature_data, feature_data, sizeof(cpi->segment_feature_data));
431 static void segmentation_test_function(VP8_COMP *cpi)
433 unsigned char *seg_map;
434 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
436 // Create a temporary map for segmentation data.
437 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
439 // MB loop to set local segmentation map
440 /*for ( i = 0; i < cpi->common.mb_rows; i++ )
442 for ( j = 0; j < cpi->common.mb_cols; j++ )
444 //seg_map[(i*cpi->common.mb_cols) + j] = (j % 2) + ((i%2)* 2);
445 //if ( j < cpi->common.mb_cols/2 )
447 // Segment 1 around the edge else 0
448 if ( (i == 0) || (j == 0) || (i == (cpi->common.mb_rows-1)) || (j == (cpi->common.mb_cols-1)) )
449 seg_map[(i*cpi->common.mb_cols) + j] = 1;
450 //else if ( (i < 2) || (j < 2) || (i > (cpi->common.mb_rows-3)) || (j > (cpi->common.mb_cols-3)) )
451 // seg_map[(i*cpi->common.mb_cols) + j] = 2;
452 //else if ( (i < 5) || (j < 5) || (i > (cpi->common.mb_rows-6)) || (j > (cpi->common.mb_cols-6)) )
453 // seg_map[(i*cpi->common.mb_cols) + j] = 3;
455 seg_map[(i*cpi->common.mb_cols) + j] = 0;
459 // Set the segmentation Map
460 set_segmentation_map(cpi, seg_map);
462 // Activate segmentation.
463 enable_segmentation(cpi);
465 // Set up the quant segment data
466 feature_data[MB_LVL_ALT_Q][0] = 0;
467 feature_data[MB_LVL_ALT_Q][1] = 4;
468 feature_data[MB_LVL_ALT_Q][2] = 0;
469 feature_data[MB_LVL_ALT_Q][3] = 0;
470 // Set up the loop segment data
471 feature_data[MB_LVL_ALT_LF][0] = 0;
472 feature_data[MB_LVL_ALT_LF][1] = 0;
473 feature_data[MB_LVL_ALT_LF][2] = 0;
474 feature_data[MB_LVL_ALT_LF][3] = 0;
476 // Initialise the feature data structure
477 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
478 set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
480 // Delete sementation map
487 // A simple function to cyclically refresh the background at a lower Q
488 static void cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment)
490 unsigned char *seg_map;
491 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
493 int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
494 int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
496 // Create a temporary map for segmentation data.
497 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
499 cpi->cyclic_refresh_q = Q;
501 for (i = Q; i > 0; i--)
503 if (vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*(Q + 128)) / 64))
504 //if ( vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*((2*Q)+96))/64) )
510 cpi->cyclic_refresh_q = i;
512 // Only update for inter frames
513 if (cpi->common.frame_type != KEY_FRAME)
515 // Cycle through the macro_block rows
516 // MB loop to set local segmentation map
517 for (i = cpi->cyclic_refresh_mode_index; i < mbs_in_frame; i++)
519 // If the MB is as a candidate for clean up then mark it for possible boost/refresh (segment 1)
520 // The segment id may get reset to 0 later if the MB gets coded anything other than last frame 0,0
521 // as only (last frame 0,0) MBs are eligable for refresh : that is to say Mbs likely to be background blocks.
522 if (cpi->cyclic_refresh_map[i] == 0)
530 // Skip blocks that have been refreshed recently anyway.
531 if (cpi->cyclic_refresh_map[i] < 0)
532 //cpi->cyclic_refresh_map[i] = cpi->cyclic_refresh_map[i] / 16;
533 cpi->cyclic_refresh_map[i]++;
544 // If we have gone through the frame reset to the start
545 cpi->cyclic_refresh_mode_index = i;
547 if (cpi->cyclic_refresh_mode_index >= mbs_in_frame)
548 cpi->cyclic_refresh_mode_index = 0;
551 // Set the segmentation Map
552 set_segmentation_map(cpi, seg_map);
554 // Activate segmentation.
555 enable_segmentation(cpi);
557 // Set up the quant segment data
558 feature_data[MB_LVL_ALT_Q][0] = 0;
559 feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
560 feature_data[MB_LVL_ALT_Q][2] = 0;
561 feature_data[MB_LVL_ALT_Q][3] = 0;
563 // Set up the loop segment data
564 feature_data[MB_LVL_ALT_LF][0] = 0;
565 feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
566 feature_data[MB_LVL_ALT_LF][2] = 0;
567 feature_data[MB_LVL_ALT_LF][3] = 0;
569 // Initialise the feature data structure
570 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
571 set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
573 // Delete sementation map
580 static void set_default_lf_deltas(VP8_COMP *cpi)
582 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 1;
583 cpi->mb.e_mbd.mode_ref_lf_delta_update = 1;
585 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
586 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
588 // Test of ref frame deltas
589 cpi->mb.e_mbd.ref_lf_deltas[INTRA_FRAME] = 2;
590 cpi->mb.e_mbd.ref_lf_deltas[LAST_FRAME] = 0;
591 cpi->mb.e_mbd.ref_lf_deltas[GOLDEN_FRAME] = -2;
592 cpi->mb.e_mbd.ref_lf_deltas[ALTREF_FRAME] = -2;
594 cpi->mb.e_mbd.mode_lf_deltas[0] = 4; // BPRED
595 cpi->mb.e_mbd.mode_lf_deltas[1] = -2; // Zero
596 cpi->mb.e_mbd.mode_lf_deltas[2] = 2; // New mv
597 cpi->mb.e_mbd.mode_lf_deltas[3] = 4; // Split mv
600 /* Convenience macros for mapping speed and mode into a continuous
603 #define GOOD(x) (x+1)
606 static int speed_map(int speed, int *map)
613 } while(speed >= *map++);
617 static int thresh_mult_map_znn[] = {
618 /* map common to zero, nearest, and near */
619 0, GOOD(2), 1500, GOOD(3), 2000, RT(0), 1000, RT(2), 2000, INT_MAX
622 static int thresh_mult_map_vhpred[] = {
623 1000, GOOD(2), 1500, GOOD(3), 2000, RT(0), 1000, RT(1), 2000,
624 RT(7), INT_MAX, INT_MAX
627 static int thresh_mult_map_bpred[] = {
628 2000, GOOD(0), 2500, GOOD(2), 5000, GOOD(3), 7500, RT(0), 2500, RT(1), 5000,
629 RT(6), INT_MAX, INT_MAX
632 static int thresh_mult_map_tm[] = {
633 1000, GOOD(2), 1500, GOOD(3), 2000, RT(0), 0, RT(1), 1000, RT(2), 2000,
634 RT(7), INT_MAX, INT_MAX
637 static int thresh_mult_map_new1[] = {
638 1000, GOOD(2), 2000, RT(0), 2000, INT_MAX
641 static int thresh_mult_map_new2[] = {
642 1000, GOOD(2), 2000, GOOD(3), 2500, GOOD(5), 4000, RT(0), 2000, RT(2), 2500,
646 static int thresh_mult_map_split1[] = {
647 2500, GOOD(0), 1700, GOOD(2), 10000, GOOD(3), 25000, GOOD(4), INT_MAX,
648 RT(0), 5000, RT(1), 10000, RT(2), 25000, RT(3), INT_MAX, INT_MAX
651 static int thresh_mult_map_split2[] = {
652 5000, GOOD(0), 4500, GOOD(2), 20000, GOOD(3), 50000, GOOD(4), INT_MAX,
653 RT(0), 10000, RT(1), 20000, RT(2), 50000, RT(3), INT_MAX, INT_MAX
656 static int mode_check_freq_map_zn2[] = {
657 /* {zero,nearest}{2,3} */
658 0, RT(10), 1<<1, RT(11), 1<<2, RT(12), 1<<3, INT_MAX
661 static int mode_check_freq_map_vhbpred[] = {
662 0, GOOD(5), 2, RT(0), 0, RT(3), 2, RT(5), 4, INT_MAX
665 static int mode_check_freq_map_near2[] = {
666 0, GOOD(5), 2, RT(0), 0, RT(3), 2, RT(10), 1<<2, RT(11), 1<<3, RT(12), 1<<4,
670 static int mode_check_freq_map_new1[] = {
671 0, RT(10), 1<<1, RT(11), 1<<2, RT(12), 1<<3, INT_MAX
674 static int mode_check_freq_map_new2[] = {
675 0, GOOD(5), 4, RT(0), 0, RT(3), 4, RT(10), 1<<3, RT(11), 1<<4, RT(12), 1<<5,
679 static int mode_check_freq_map_split1[] = {
680 0, GOOD(2), 2, GOOD(3), 7, RT(1), 2, RT(2), 7, INT_MAX
683 static int mode_check_freq_map_split2[] = {
684 0, GOOD(1), 2, GOOD(2), 4, GOOD(3), 15, RT(1), 4, RT(2), 15, INT_MAX
687 void vp8_set_speed_features(VP8_COMP *cpi)
689 SPEED_FEATURES *sf = &cpi->sf;
690 int Mode = cpi->compressor_speed;
691 int Speed = cpi->Speed;
693 VP8_COMMON *cm = &cpi->common;
694 int last_improved_quant = sf->improved_quant;
697 // Initialise default mode frequency sampling variables
698 for (i = 0; i < MAX_MODES; i ++)
700 cpi->mode_check_freq[i] = 0;
701 cpi->mode_test_hit_counts[i] = 0;
702 cpi->mode_chosen_counts[i] = 0;
705 cpi->mbs_tested_so_far = 0;
707 // best quality defaults
709 sf->search_method = NSTEP;
710 sf->improved_quant = 1;
711 sf->improved_dct = 1;
714 sf->quarter_pixel_search = 1;
715 sf->half_pixel_search = 1;
716 sf->iterative_sub_pixel = 1;
717 sf->optimize_coefficients = 1;
718 sf->use_fastquant_for_pick = 0;
719 sf->no_skip_block4x4_search = 1;
722 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
723 sf->improved_mv_pred = 1;
725 // default thresholds to 0
726 for (i = 0; i < MAX_MODES; i++)
727 sf->thresh_mult[i] = 0;
729 /* Count enabled references */
731 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
733 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
735 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
738 /* Convert speed to continuous range, with clamping */
750 sf->thresh_mult[THR_ZERO1] =
751 sf->thresh_mult[THR_NEAREST1] =
752 sf->thresh_mult[THR_NEAR1] =
753 sf->thresh_mult[THR_DC] = 0; /* always */
755 sf->thresh_mult[THR_ZERO2] =
756 sf->thresh_mult[THR_ZERO3] =
757 sf->thresh_mult[THR_NEAREST2] =
758 sf->thresh_mult[THR_NEAREST3] =
759 sf->thresh_mult[THR_NEAR2] =
760 sf->thresh_mult[THR_NEAR3] = speed_map(Speed, thresh_mult_map_znn);
762 sf->thresh_mult[THR_V_PRED] =
763 sf->thresh_mult[THR_H_PRED] = speed_map(Speed, thresh_mult_map_vhpred);
764 sf->thresh_mult[THR_B_PRED] = speed_map(Speed, thresh_mult_map_bpred);
765 sf->thresh_mult[THR_TM] = speed_map(Speed, thresh_mult_map_tm);
766 sf->thresh_mult[THR_NEW1] = speed_map(Speed, thresh_mult_map_new1);
767 sf->thresh_mult[THR_NEW2] =
768 sf->thresh_mult[THR_NEW3] = speed_map(Speed, thresh_mult_map_new2);
769 sf->thresh_mult[THR_SPLIT1] = speed_map(Speed, thresh_mult_map_split1);
770 sf->thresh_mult[THR_SPLIT2] =
771 sf->thresh_mult[THR_SPLIT3] = speed_map(Speed, thresh_mult_map_split2);
773 cpi->mode_check_freq[THR_ZERO1] =
774 cpi->mode_check_freq[THR_NEAREST1] =
775 cpi->mode_check_freq[THR_NEAR1] =
776 cpi->mode_check_freq[THR_TM] =
777 cpi->mode_check_freq[THR_DC] = 0; /* always */
779 cpi->mode_check_freq[THR_ZERO2] =
780 cpi->mode_check_freq[THR_ZERO3] =
781 cpi->mode_check_freq[THR_NEAREST2] =
782 cpi->mode_check_freq[THR_NEAREST3] = speed_map(Speed,
783 mode_check_freq_map_zn2);
785 cpi->mode_check_freq[THR_NEAR2] =
786 cpi->mode_check_freq[THR_NEAR3] = speed_map(Speed,
787 mode_check_freq_map_near2);
789 cpi->mode_check_freq[THR_V_PRED] =
790 cpi->mode_check_freq[THR_H_PRED] =
791 cpi->mode_check_freq[THR_B_PRED] = speed_map(Speed,
792 mode_check_freq_map_vhbpred);
793 cpi->mode_check_freq[THR_NEW1] = speed_map(Speed,
794 mode_check_freq_map_new1);
795 cpi->mode_check_freq[THR_NEW2] =
796 cpi->mode_check_freq[THR_NEW3] = speed_map(Speed,
797 mode_check_freq_map_new2);
798 cpi->mode_check_freq[THR_SPLIT1] = speed_map(Speed,
799 mode_check_freq_map_split1);
800 cpi->mode_check_freq[THR_SPLIT2] =
801 cpi->mode_check_freq[THR_SPLIT3] = speed_map(Speed,
802 mode_check_freq_map_split2);
806 #if !(CONFIG_REALTIME_ONLY)
807 case 0: // best quality mode
809 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
815 /* Disable coefficient optimization above speed 0 */
816 sf->optimize_coefficients = 0;
817 sf->use_fastquant_for_pick = 1;
818 sf->no_skip_block4x4_search = 0;
825 sf->improved_quant = 0;
826 sf->improved_dct = 0;
828 // Only do recode loop on key frames, golden frames and
837 sf->recode_loop = 0; // recode loop off
838 sf->RD = 0; // Turn rd off
844 sf->auto_filter = 0; // Faster selection of loop filter
850 sf->optimize_coefficients = 0;
853 sf->iterative_sub_pixel = 1;
854 sf->search_method = NSTEP;
858 sf->improved_quant = 0;
859 sf->improved_dct = 0;
861 sf->use_fastquant_for_pick = 1;
862 sf->no_skip_block4x4_search = 0;
867 sf->auto_filter = 0; // Faster selection of loop filter
877 sf->auto_filter = 0; // Faster selection of loop filter
878 sf->search_method = HEX;
879 sf->iterative_sub_pixel = 0;
884 unsigned int sum = 0;
885 unsigned int total_mbs = cm->MBs;
887 unsigned int total_skip;
891 if (cpi->oxcf.encode_breakout > 2000)
892 min = cpi->oxcf.encode_breakout;
896 for (i = 0; i < min; i++)
898 sum += cpi->error_bins[i];
904 // i starts from 2 to make sure thresh started from 2048
905 for (; i < 1024; i++)
907 sum += cpi->error_bins[i];
909 if (10 * sum >= (unsigned int)(cpi->Speed - 6)*(total_mbs - total_skip))
921 sf->thresh_mult[THR_NEW1 ] = thresh;
922 sf->thresh_mult[THR_NEAREST1 ] = thresh >> 1;
923 sf->thresh_mult[THR_NEAR1 ] = thresh >> 1;
928 sf->thresh_mult[THR_NEW2] = thresh << 1;
929 sf->thresh_mult[THR_NEAREST2 ] = thresh;
930 sf->thresh_mult[THR_NEAR2 ] = thresh;
935 sf->thresh_mult[THR_NEW3] = thresh << 1;
936 sf->thresh_mult[THR_NEAREST3 ] = thresh;
937 sf->thresh_mult[THR_NEAR3 ] = thresh;
940 sf->improved_mv_pred = 0;
944 sf->quarter_pixel_search = 0;
948 cm->filter_type = NORMAL_LOOPFILTER;
951 cm->filter_type = SIMPLE_LOOPFILTER;
955 cm->filter_type = SIMPLE_LOOPFILTER;
958 // This has a big hit on quality. Last resort
960 sf->half_pixel_search = 0;
962 vpx_memset(cpi->error_bins, 0, sizeof(cpi->error_bins));
966 // Slow quant, dct and trellis not worthwhile for first pass
967 // so make sure they are always turned off.
968 if ( cpi->pass == 1 )
970 sf->improved_quant = 0;
971 sf->optimize_coefficients = 0;
972 sf->improved_dct = 0;
975 if (cpi->sf.search_method == NSTEP)
977 vp8_init3smotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
979 else if (cpi->sf.search_method == DIAMOND)
981 vp8_init_dsmotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
984 if (cpi->sf.improved_dct)
986 cpi->mb.vp8_short_fdct8x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short8x4);
987 cpi->mb.vp8_short_fdct4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short4x4);
991 cpi->mb.vp8_short_fdct8x4 = FDCT_INVOKE(&cpi->rtcd.fdct, fast8x4);
992 cpi->mb.vp8_short_fdct4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, fast4x4);
995 cpi->mb.short_walsh4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, walsh_short4x4);
997 if (cpi->sf.improved_quant)
999 cpi->mb.quantize_b = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1001 cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1006 cpi->mb.quantize_b = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1008 cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1011 if (cpi->sf.improved_quant != last_improved_quant)
1012 vp8cx_init_quantizer(cpi);
1014 #if CONFIG_RUNTIME_CPU_DETECT
1015 cpi->mb.e_mbd.rtcd = &cpi->common.rtcd;
1018 if (cpi->sf.iterative_sub_pixel == 1)
1020 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step_iteratively;
1022 else if (cpi->sf.quarter_pixel_search)
1024 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step;
1026 else if (cpi->sf.half_pixel_search)
1028 cpi->find_fractional_mv_step = vp8_find_best_half_pixel_step;
1032 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1035 if (cpi->sf.optimize_coefficients == 1 && cpi->pass!=1)
1036 cpi->mb.optimize = 1;
1038 cpi->mb.optimize = 0;
1040 if (cpi->common.full_pixel)
1041 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1044 frames_at_speed[cpi->Speed]++;
1050 static void alloc_raw_frame_buffers(VP8_COMP *cpi)
1052 int width = (cpi->oxcf.Width + 15) & ~15;
1053 int height = (cpi->oxcf.Height + 15) & ~15;
1055 cpi->lookahead = vp8_lookahead_init(cpi->oxcf.Width, cpi->oxcf.Height,
1056 cpi->oxcf.lag_in_frames);
1058 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1059 "Failed to allocate lag buffers");
1061 #if VP8_TEMPORAL_ALT_REF
1063 if (vp8_yv12_alloc_frame_buffer(&cpi->alt_ref_buffer,
1064 width, height, VP8BORDERINPIXELS))
1065 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1066 "Failed to allocate altref buffer");
1071 static int vp8_alloc_partition_data(VP8_COMP *cpi)
1073 vpx_free(cpi->mb.pip);
1075 cpi->mb.pip = vpx_calloc((cpi->common.mb_cols + 1) *
1076 (cpi->common.mb_rows + 1),
1077 sizeof(PARTITION_INFO));
1081 cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
1086 void vp8_alloc_compressor_data(VP8_COMP *cpi)
1088 VP8_COMMON *cm = & cpi->common;
1090 int width = cm->Width;
1091 int height = cm->Height;
1093 if (vp8_alloc_frame_buffers(cm, width, height))
1094 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1095 "Failed to allocate frame buffers");
1097 if (vp8_alloc_partition_data(cpi))
1098 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1099 "Failed to allocate partition data");
1102 if ((width & 0xf) != 0)
1103 width += 16 - (width & 0xf);
1105 if ((height & 0xf) != 0)
1106 height += 16 - (height & 0xf);
1109 if (vp8_yv12_alloc_frame_buffer(&cpi->pick_lf_lvl_frame,
1110 width, height, VP8BORDERINPIXELS))
1111 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1112 "Failed to allocate last frame buffer");
1114 if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source,
1115 width, height, VP8BORDERINPIXELS))
1116 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1117 "Failed to allocate scaled source buffer");
1123 unsigned int tokens = cm->mb_rows * cm->mb_cols * 24 * 16;
1125 CHECK_MEM_ERROR(cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
1128 // Data used for real time vc mode to see if gf needs refreshing
1129 cpi->inter_zz_count = 0;
1130 cpi->gf_bad_count = 0;
1131 cpi->gf_update_recommended = 0;
1134 // Structures used to minitor GF usage
1135 vpx_free(cpi->gf_active_flags);
1136 CHECK_MEM_ERROR(cpi->gf_active_flags,
1137 vpx_calloc(1, cm->mb_rows * cm->mb_cols));
1138 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
1140 vpx_free(cpi->mb_activity_map);
1141 CHECK_MEM_ERROR(cpi->mb_activity_map,
1142 vpx_calloc(sizeof(unsigned int),
1143 cm->mb_rows * cm->mb_cols));
1145 vpx_free(cpi->mb_norm_activity_map);
1146 CHECK_MEM_ERROR(cpi->mb_norm_activity_map,
1147 vpx_calloc(sizeof(unsigned int),
1148 cm->mb_rows * cm->mb_cols));
1150 #if CONFIG_MULTITHREAD
1152 cpi->mt_sync_range = 1;
1153 else if (width <= 1280)
1154 cpi->mt_sync_range = 4;
1155 else if (width <= 2560)
1156 cpi->mt_sync_range = 8;
1158 cpi->mt_sync_range = 16;
1161 vpx_free(cpi->tplist);
1163 CHECK_MEM_ERROR(cpi->tplist, vpx_malloc(sizeof(TOKENLIST) * cpi->common.mb_rows));
1168 static const int q_trans[] =
1170 0, 1, 2, 3, 4, 5, 7, 8,
1171 9, 10, 12, 13, 15, 17, 18, 19,
1172 20, 21, 23, 24, 25, 26, 27, 28,
1173 29, 30, 31, 33, 35, 37, 39, 41,
1174 43, 45, 47, 49, 51, 53, 55, 57,
1175 59, 61, 64, 67, 70, 73, 76, 79,
1176 82, 85, 88, 91, 94, 97, 100, 103,
1177 106, 109, 112, 115, 118, 121, 124, 127,
1180 int vp8_reverse_trans(int x)
1184 for (i = 0; i < 64; i++)
1185 if (q_trans[i] >= x)
1190 void vp8_new_frame_rate(VP8_COMP *cpi, double framerate)
1195 cpi->frame_rate = framerate;
1196 cpi->output_frame_rate = framerate;
1197 cpi->per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth /
1198 cpi->output_frame_rate);
1199 cpi->av_per_frame_bandwidth = cpi->per_frame_bandwidth;
1200 cpi->min_frame_bandwidth = (int)(cpi->av_per_frame_bandwidth *
1201 cpi->oxcf.two_pass_vbrmin_section / 100);
1203 // Set Maximum gf/arf interval
1204 cpi->max_gf_interval = ((int)(cpi->output_frame_rate / 2.0) + 2);
1206 if(cpi->max_gf_interval < 12)
1207 cpi->max_gf_interval = 12;
1209 // Extended interval for genuinely static scenes
1210 cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1212 // Special conditions when altr ref frame enabled in lagged compress mode
1213 if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames)
1215 if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1216 cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1218 if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1219 cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1222 if ( cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval )
1223 cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1228 rescale(int val, int num, int denom)
1230 int64_t llnum = num;
1231 int64_t llden = denom;
1232 int64_t llval = val;
1234 return llval * llnum / llden;
1238 static void init_config(VP8_COMP *cpi, VP8_CONFIG *oxcf)
1240 VP8_COMMON *cm = &cpi->common;
1245 cpi->auto_adjust_gold_quantizer = 1;
1248 cm->version = oxcf->Version;
1249 vp8_setup_version(cm);
1251 /* frame rate is not available on the first frame, as it's derived from
1252 * the observed timestamps. The actual value used here doesn't matter
1253 * too much, as it will adapt quickly. If the reciprocal of the timebase
1254 * seems like a reasonable framerate, then use that as a guess, otherwise
1257 cpi->frame_rate = (double)(oxcf->timebase.den) /
1258 (double)(oxcf->timebase.num);
1260 if (cpi->frame_rate > 180)
1261 cpi->frame_rate = 30;
1263 cpi->ref_frame_rate = cpi->frame_rate;
1265 // change includes all joint functionality
1266 vp8_change_config(cpi, oxcf);
1268 // Initialize active best and worst q and average q values.
1269 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1270 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1271 cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1273 // Initialise the starting buffer levels
1274 cpi->buffer_level = cpi->oxcf.starting_buffer_level;
1275 cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
1277 cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
1278 cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
1279 cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
1280 cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
1282 cpi->total_actual_bits = 0;
1283 cpi->total_target_vs_actual = 0;
1285 // Temporal scalabilty
1286 if (cpi->oxcf.number_of_layers > 1)
1289 double prev_layer_frame_rate=0;
1291 for (i=0; i<cpi->oxcf.number_of_layers; i++)
1293 LAYER_CONTEXT *lc = &cpi->layer_context[i];
1295 // Layer configuration
1297 cpi->output_frame_rate / cpi->oxcf.rate_decimator[i];
1298 lc->target_bandwidth = cpi->oxcf.target_bitrate[i] * 1000;
1300 lc->starting_buffer_level_in_ms = oxcf->starting_buffer_level;
1301 lc->optimal_buffer_level_in_ms = oxcf->optimal_buffer_level;
1302 lc->maximum_buffer_size_in_ms = oxcf->maximum_buffer_size;
1304 lc->starting_buffer_level =
1305 rescale(oxcf->starting_buffer_level,
1306 lc->target_bandwidth, 1000);
1308 if (oxcf->optimal_buffer_level == 0)
1309 lc->optimal_buffer_level = lc->target_bandwidth / 8;
1311 lc->optimal_buffer_level =
1312 rescale(oxcf->optimal_buffer_level,
1313 lc->target_bandwidth, 1000);
1315 if (oxcf->maximum_buffer_size == 0)
1316 lc->maximum_buffer_size = lc->target_bandwidth / 8;
1318 lc->maximum_buffer_size =
1319 rescale(oxcf->maximum_buffer_size,
1320 lc->target_bandwidth, 1000);
1322 // Work out the average size of a frame within this layer
1324 lc->avg_frame_size_for_layer = (cpi->oxcf.target_bitrate[i] -
1325 cpi->oxcf.target_bitrate[i-1]) * 1000 /
1326 (lc->frame_rate - prev_layer_frame_rate);
1328 lc->active_worst_quality = cpi->oxcf.worst_allowed_q;
1329 lc->active_best_quality = cpi->oxcf.best_allowed_q;
1330 lc->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1332 lc->buffer_level = lc->starting_buffer_level;
1333 lc->bits_off_target = lc->starting_buffer_level;
1335 lc->total_actual_bits = 0;
1339 lc->rate_correction_factor = 1.0;
1340 lc->key_frame_rate_correction_factor = 1.0;
1341 lc->gf_rate_correction_factor = 1.0;
1342 lc->inter_frame_target = 0.0;
1344 prev_layer_frame_rate = lc->frame_rate;
1348 #if VP8_TEMPORAL_ALT_REF
1352 cpi->fixed_divide[0] = 0;
1354 for (i = 1; i < 512; i++)
1355 cpi->fixed_divide[i] = 0x80000 / i;
1360 void update_layer_contexts (VP8_COMP *cpi)
1362 VP8_CONFIG *oxcf = &cpi->oxcf;
1364 /* Update snapshots of the layer contexts to reflect new parameters */
1365 if (oxcf->number_of_layers > 1)
1368 double prev_layer_frame_rate=0;
1370 for (i=0; i<oxcf->number_of_layers; i++)
1372 LAYER_CONTEXT *lc = &cpi->layer_context[i];
1375 cpi->ref_frame_rate / oxcf->rate_decimator[i];
1376 lc->target_bandwidth = oxcf->target_bitrate[i] * 1000;
1378 lc->starting_buffer_level = rescale(
1379 oxcf->starting_buffer_level_in_ms,
1380 lc->target_bandwidth, 1000);
1382 if (oxcf->optimal_buffer_level == 0)
1383 lc->optimal_buffer_level = lc->target_bandwidth / 8;
1385 lc->optimal_buffer_level = rescale(
1386 oxcf->optimal_buffer_level_in_ms,
1387 lc->target_bandwidth, 1000);
1389 if (oxcf->maximum_buffer_size == 0)
1390 lc->maximum_buffer_size = lc->target_bandwidth / 8;
1392 lc->maximum_buffer_size = rescale(
1393 oxcf->maximum_buffer_size_in_ms,
1394 lc->target_bandwidth, 1000);
1396 // Work out the average size of a frame within this layer
1398 lc->avg_frame_size_for_layer = (oxcf->target_bitrate[i] -
1399 oxcf->target_bitrate[i-1]) * 1000 /
1400 (lc->frame_rate - prev_layer_frame_rate);
1402 lc->active_worst_quality = oxcf->worst_allowed_q;
1403 lc->active_best_quality = oxcf->best_allowed_q;
1404 lc->avg_frame_qindex = oxcf->worst_allowed_q;
1406 prev_layer_frame_rate = lc->frame_rate;
1411 void vp8_change_config(VP8_COMP *cpi, VP8_CONFIG *oxcf)
1413 VP8_COMMON *cm = &cpi->common;
1421 if (cm->version != oxcf->Version)
1423 cm->version = oxcf->Version;
1424 vp8_setup_version(cm);
1429 switch (cpi->oxcf.Mode)
1434 cpi->compressor_speed = 2;
1436 if (cpi->oxcf.cpu_used < -16)
1438 cpi->oxcf.cpu_used = -16;
1441 if (cpi->oxcf.cpu_used > 16)
1442 cpi->oxcf.cpu_used = 16;
1446 case MODE_GOODQUALITY:
1448 cpi->compressor_speed = 1;
1450 if (cpi->oxcf.cpu_used < -5)
1452 cpi->oxcf.cpu_used = -5;
1455 if (cpi->oxcf.cpu_used > 5)
1456 cpi->oxcf.cpu_used = 5;
1460 case MODE_BESTQUALITY:
1462 cpi->compressor_speed = 0;
1465 case MODE_FIRSTPASS:
1467 cpi->compressor_speed = 1;
1469 case MODE_SECONDPASS:
1471 cpi->compressor_speed = 1;
1473 if (cpi->oxcf.cpu_used < -5)
1475 cpi->oxcf.cpu_used = -5;
1478 if (cpi->oxcf.cpu_used > 5)
1479 cpi->oxcf.cpu_used = 5;
1482 case MODE_SECONDPASS_BEST:
1484 cpi->compressor_speed = 0;
1489 cpi->auto_worst_q = 1;
1491 cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1492 cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1493 cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1495 if (oxcf->fixed_q >= 0)
1497 if (oxcf->worst_allowed_q < 0)
1498 cpi->oxcf.fixed_q = q_trans[0];
1500 cpi->oxcf.fixed_q = q_trans[oxcf->worst_allowed_q];
1502 if (oxcf->alt_q < 0)
1503 cpi->oxcf.alt_q = q_trans[0];
1505 cpi->oxcf.alt_q = q_trans[oxcf->alt_q];
1507 if (oxcf->key_q < 0)
1508 cpi->oxcf.key_q = q_trans[0];
1510 cpi->oxcf.key_q = q_trans[oxcf->key_q];
1512 if (oxcf->gold_q < 0)
1513 cpi->oxcf.gold_q = q_trans[0];
1515 cpi->oxcf.gold_q = q_trans[oxcf->gold_q];
1519 cpi->baseline_gf_interval =
1520 cpi->oxcf.alt_freq ? cpi->oxcf.alt_freq : DEFAULT_GF_INTERVAL;
1522 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
1524 //cpi->use_golden_frame_only = 0;
1525 //cpi->use_last_frame_only = 0;
1526 cm->refresh_golden_frame = 0;
1527 cm->refresh_last_frame = 1;
1528 cm->refresh_entropy_probs = 1;
1530 if (cpi->oxcf.token_partitions >= 0 && cpi->oxcf.token_partitions <= 3)
1531 cm->multi_token_partition =
1532 (TOKEN_PARTITION) cpi->oxcf.token_partitions;
1534 setup_features(cpi);
1539 for (i = 0; i < MAX_MB_SEGMENTS; i++)
1540 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1543 // At the moment the first order values may not be > MAXQ
1544 if (cpi->oxcf.fixed_q > MAXQ)
1545 cpi->oxcf.fixed_q = MAXQ;
1547 // local file playback mode == really big buffer
1548 if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK)
1550 cpi->oxcf.starting_buffer_level = 60000;
1551 cpi->oxcf.optimal_buffer_level = 60000;
1552 cpi->oxcf.maximum_buffer_size = 240000;
1553 cpi->oxcf.starting_buffer_level_in_ms = 60000;
1554 cpi->oxcf.optimal_buffer_level_in_ms = 60000;
1555 cpi->oxcf.maximum_buffer_size_in_ms = 240000;
1558 // Convert target bandwidth from Kbit/s to Bit/s
1559 cpi->oxcf.target_bandwidth *= 1000;
1561 cpi->oxcf.starting_buffer_level =
1562 rescale(cpi->oxcf.starting_buffer_level,
1563 cpi->oxcf.target_bandwidth, 1000);
1565 // Set or reset optimal and maximum buffer levels.
1566 if (cpi->oxcf.optimal_buffer_level == 0)
1567 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1569 cpi->oxcf.optimal_buffer_level =
1570 rescale(cpi->oxcf.optimal_buffer_level,
1571 cpi->oxcf.target_bandwidth, 1000);
1573 if (cpi->oxcf.maximum_buffer_size == 0)
1574 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1576 cpi->oxcf.maximum_buffer_size =
1577 rescale(cpi->oxcf.maximum_buffer_size,
1578 cpi->oxcf.target_bandwidth, 1000);
1580 // Set up frame rate and related parameters rate control values.
1581 vp8_new_frame_rate(cpi, cpi->frame_rate);
1583 // Set absolute upper and lower quality limits
1584 cpi->worst_quality = cpi->oxcf.worst_allowed_q;
1585 cpi->best_quality = cpi->oxcf.best_allowed_q;
1587 // active values should only be modified if out of new range
1588 if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q)
1590 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1593 else if (cpi->active_worst_quality < cpi->oxcf.best_allowed_q)
1595 cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
1597 if (cpi->active_best_quality < cpi->oxcf.best_allowed_q)
1599 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1602 else if (cpi->active_best_quality > cpi->oxcf.worst_allowed_q)
1604 cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
1607 cpi->buffered_mode = cpi->oxcf.optimal_buffer_level > 0;
1609 cpi->cq_target_quality = cpi->oxcf.cq_level;
1611 // Only allow dropped frames in buffered mode
1612 cpi->drop_frames_allowed = cpi->oxcf.allow_df && cpi->buffered_mode;
1614 if (!cm->use_bilinear_mc_filter)
1615 cm->mcomp_filter_type = SIXTAP;
1617 cm->mcomp_filter_type = BILINEAR;
1619 cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1621 cm->Width = cpi->oxcf.Width;
1622 cm->Height = cpi->oxcf.Height;
1624 cm->horiz_scale = cpi->horiz_scale;
1625 cm->vert_scale = cpi->vert_scale;
1627 // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1628 if (cpi->oxcf.Sharpness > 7)
1629 cpi->oxcf.Sharpness = 7;
1631 cm->sharpness_level = cpi->oxcf.Sharpness;
1633 if (cm->horiz_scale != NORMAL || cm->vert_scale != NORMAL)
1635 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
1636 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
1638 Scale2Ratio(cm->horiz_scale, &hr, &hs);
1639 Scale2Ratio(cm->vert_scale, &vr, &vs);
1641 // always go to the next whole number
1642 cm->Width = (hs - 1 + cpi->oxcf.Width * hr) / hs;
1643 cm->Height = (vs - 1 + cpi->oxcf.Height * vr) / vs;
1646 if (((cm->Width + 15) & 0xfffffff0) !=
1647 cm->yv12_fb[cm->lst_fb_idx].y_width ||
1648 ((cm->Height + 15) & 0xfffffff0) !=
1649 cm->yv12_fb[cm->lst_fb_idx].y_height ||
1650 cm->yv12_fb[cm->lst_fb_idx].y_width == 0)
1652 alloc_raw_frame_buffers(cpi);
1653 vp8_alloc_compressor_data(cpi);
1656 if (cpi->oxcf.fixed_q >= 0)
1658 cpi->last_q[0] = cpi->oxcf.fixed_q;
1659 cpi->last_q[1] = cpi->oxcf.fixed_q;
1662 cpi->Speed = cpi->oxcf.cpu_used;
1664 // force to allowlag to 0 if lag_in_frames is 0;
1665 if (cpi->oxcf.lag_in_frames == 0)
1667 cpi->oxcf.allow_lag = 0;
1669 // Limit on lag buffers as these are not currently dynamically allocated
1670 else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS)
1671 cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1674 cpi->alt_ref_source = NULL;
1675 cpi->is_src_frame_alt_ref = 0;
1679 // Experimental RD Code
1680 cpi->frame_distortion = 0;
1681 cpi->last_frame_distortion = 0;
1686 #define M_LOG2_E 0.693147180559945309417
1687 #define log2f(x) (log (x) / (float) M_LOG2_E)
1688 static void cal_mvsadcosts(int *mvsadcost[2])
1692 mvsadcost [0] [0] = 300;
1693 mvsadcost [1] [0] = 300;
1697 double z = 256 * (2 * (log2f(8 * i) + .6));
1698 mvsadcost [0][i] = (int) z;
1699 mvsadcost [1][i] = (int) z;
1700 mvsadcost [0][-i] = (int) z;
1701 mvsadcost [1][-i] = (int) z;
1703 while (++i <= mvfp_max);
1706 struct VP8_COMP* vp8_create_compressor(VP8_CONFIG *oxcf)
1713 cpi = vpx_memalign(32, sizeof(VP8_COMP));
1714 // Check that the CPI instance is valid
1720 vpx_memset(cpi, 0, sizeof(VP8_COMP));
1722 if (setjmp(cm->error.jmp))
1724 cpi->common.error.setjmp = 0;
1725 vp8_remove_compressor(&cpi);
1729 cpi->common.error.setjmp = 1;
1731 CHECK_MEM_ERROR(cpi->mb.ss, vpx_calloc(sizeof(search_site), (MAX_MVSEARCH_STEPS * 8) + 1));
1733 vp8_create_common(&cpi->common);
1734 vp8_cmachine_specific_config(cpi);
1736 init_config(cpi, oxcf);
1738 memcpy(cpi->base_skip_false_prob, vp8cx_base_skip_false_prob, sizeof(vp8cx_base_skip_false_prob));
1739 cpi->common.current_video_frame = 0;
1740 cpi->kf_overspend_bits = 0;
1741 cpi->kf_bitrate_adjustment = 0;
1742 cpi->frames_till_gf_update_due = 0;
1743 cpi->gf_overspend_bits = 0;
1744 cpi->non_gf_bitrate_adjustment = 0;
1745 cpi->prob_last_coded = 128;
1746 cpi->prob_gf_coded = 128;
1747 cpi->prob_intra_coded = 63;
1749 // Prime the recent reference frame usage counters.
1750 // Hereafter they will be maintained as a sort of moving average
1751 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
1752 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
1753 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
1754 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
1756 // Set reference frame sign bias for ALTREF frame to 1 (for now)
1757 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
1759 cpi->twopass.gf_decay_rate = 0;
1760 cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1762 cpi->gold_is_last = 0 ;
1763 cpi->alt_is_last = 0 ;
1764 cpi->gold_is_alt = 0 ;
1766 // allocate memory for storing last frame's MVs for MV prediction.
1767 CHECK_MEM_ERROR(cpi->lfmv, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int_mv)));
1768 CHECK_MEM_ERROR(cpi->lf_ref_frame_sign_bias, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1769 CHECK_MEM_ERROR(cpi->lf_ref_frame, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1771 // Create the encoder segmentation map and set all entries to 0
1772 CHECK_MEM_ERROR(cpi->segmentation_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1773 CHECK_MEM_ERROR(cpi->active_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1774 vpx_memset(cpi->active_map , 1, (cpi->common.mb_rows * cpi->common.mb_cols));
1775 cpi->active_map_enabled = 0;
1778 // Experimental code for lagged and one pass
1779 // Initialise one_pass GF frames stats
1780 // Update stats used for GF selection
1783 cpi->one_pass_frame_index = 0;
1785 for (i = 0; i < MAX_LAG_BUFFERS; i++)
1787 cpi->one_pass_frame_stats[i].frames_so_far = 0;
1788 cpi->one_pass_frame_stats[i].frame_intra_error = 0.0;
1789 cpi->one_pass_frame_stats[i].frame_coded_error = 0.0;
1790 cpi->one_pass_frame_stats[i].frame_pcnt_inter = 0.0;
1791 cpi->one_pass_frame_stats[i].frame_pcnt_motion = 0.0;
1792 cpi->one_pass_frame_stats[i].frame_mvr = 0.0;
1793 cpi->one_pass_frame_stats[i].frame_mvr_abs = 0.0;
1794 cpi->one_pass_frame_stats[i].frame_mvc = 0.0;
1795 cpi->one_pass_frame_stats[i].frame_mvc_abs = 0.0;
1800 // Should we use the cyclic refresh method.
1801 // Currently this is tied to error resilliant mode
1802 cpi->cyclic_refresh_mode_enabled = cpi->oxcf.error_resilient_mode;
1803 cpi->cyclic_refresh_mode_max_mbs_perframe = (cpi->common.mb_rows * cpi->common.mb_cols) / 40;
1804 cpi->cyclic_refresh_mode_index = 0;
1805 cpi->cyclic_refresh_q = 32;
1807 if (cpi->cyclic_refresh_mode_enabled)
1809 CHECK_MEM_ERROR(cpi->cyclic_refresh_map, vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
1812 cpi->cyclic_refresh_map = (signed char *) NULL;
1814 // Test function for segmentation
1815 //segmentation_test_function( cpi);
1817 #ifdef ENTROPY_STATS
1818 init_context_counters();
1821 /*Initialize the feed-forward activity masking.*/
1822 cpi->activity_avg = 90<<12;
1824 cpi->frames_since_key = 8; // Give a sensible default for the first frame.
1825 cpi->key_frame_frequency = cpi->oxcf.key_freq;
1826 cpi->this_key_frame_forced = 0;
1827 cpi->next_key_frame_forced = 0;
1829 cpi->source_alt_ref_pending = 0;
1830 cpi->source_alt_ref_active = 0;
1831 cpi->common.refresh_alt_ref_frame = 0;
1833 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1834 #if CONFIG_INTERNAL_STATS
1835 cpi->b_calculate_ssimg = 0;
1840 if (cpi->b_calculate_psnr)
1842 cpi->total_sq_error = 0.0;
1843 cpi->total_sq_error2 = 0.0;
1848 cpi->totalp_y = 0.0;
1849 cpi->totalp_u = 0.0;
1850 cpi->totalp_v = 0.0;
1852 cpi->tot_recode_hits = 0;
1853 cpi->summed_quality = 0;
1854 cpi->summed_weights = 0;
1857 if (cpi->b_calculate_ssimg)
1859 cpi->total_ssimg_y = 0;
1860 cpi->total_ssimg_u = 0;
1861 cpi->total_ssimg_v = 0;
1862 cpi->total_ssimg_all = 0;
1868 #define LLONG_MAX 9223372036854775807LL
1870 cpi->first_time_stamp_ever = LLONG_MAX;
1872 cpi->frames_till_gf_update_due = 0;
1873 cpi->key_frame_count = 1;
1875 cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
1878 cpi->total_byte_count = 0;
1880 cpi->drop_frame = 0;
1881 cpi->drop_count = 0;
1882 cpi->max_drop_count = 0;
1883 cpi->max_consec_dropped_frames = 4;
1885 cpi->rate_correction_factor = 1.0;
1886 cpi->key_frame_rate_correction_factor = 1.0;
1887 cpi->gf_rate_correction_factor = 1.0;
1888 cpi->twopass.est_max_qcorrection_factor = 1.0;
1890 cpi->mb.mvcost[0] = &cpi->mb.mvcosts[0][mv_max+1];
1891 cpi->mb.mvcost[1] = &cpi->mb.mvcosts[1][mv_max+1];
1892 cpi->mb.mvsadcost[0] = &cpi->mb.mvsadcosts[0][mvfp_max+1];
1893 cpi->mb.mvsadcost[1] = &cpi->mb.mvsadcosts[1][mvfp_max+1];
1895 cal_mvsadcosts(cpi->mb.mvsadcost);
1897 for (i = 0; i < KEY_FRAME_CONTEXT; i++)
1899 cpi->prior_key_frame_distance[i] = (int)cpi->output_frame_rate;
1902 #ifdef OUTPUT_YUV_SRC
1903 yuv_file = fopen("bd.yuv", "ab");
1907 framepsnr = fopen("framepsnr.stt", "a");
1908 kf_list = fopen("kf_list.stt", "w");
1911 cpi->output_pkt_list = oxcf->output_pkt_list;
1913 #if !(CONFIG_REALTIME_ONLY)
1917 vp8_init_first_pass(cpi);
1919 else if (cpi->pass == 2)
1921 size_t packet_sz = sizeof(FIRSTPASS_STATS);
1922 int packets = oxcf->two_pass_stats_in.sz / packet_sz;
1924 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1925 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1926 cpi->twopass.stats_in_end = (void*)((char *)cpi->twopass.stats_in
1927 + (packets - 1) * packet_sz);
1928 vp8_init_second_pass(cpi);
1933 if (cpi->compressor_speed == 2)
1935 cpi->cpu_freq = 0; //vp8_get_processor_freq();
1936 cpi->avg_encode_time = 0;
1937 cpi->avg_pick_mode_time = 0;
1940 vp8_set_speed_features(cpi);
1942 // Set starting values of RD threshold multipliers (128 = *1)
1943 for (i = 0; i < MAX_MODES; i++)
1945 cpi->rd_thresh_mult[i] = 128;
1948 #ifdef ENTROPY_STATS
1949 init_mv_ref_counts();
1952 #if CONFIG_MULTITHREAD
1953 vp8cx_create_encoder_threads(cpi);
1956 cpi->fn_ptr[BLOCK_16X16].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16);
1957 cpi->fn_ptr[BLOCK_16X16].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x16);
1958 cpi->fn_ptr[BLOCK_16X16].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x16);
1959 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_h = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_h);
1960 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_v = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_v);
1961 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_hv = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_hv);
1962 cpi->fn_ptr[BLOCK_16X16].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x3);
1963 cpi->fn_ptr[BLOCK_16X16].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x8);
1964 cpi->fn_ptr[BLOCK_16X16].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x4d);
1966 cpi->fn_ptr[BLOCK_16X8].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8);
1967 cpi->fn_ptr[BLOCK_16X8].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x8);
1968 cpi->fn_ptr[BLOCK_16X8].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x8);
1969 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_h = NULL;
1970 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_v = NULL;
1971 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_hv = NULL;
1972 cpi->fn_ptr[BLOCK_16X8].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x3);
1973 cpi->fn_ptr[BLOCK_16X8].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x8);
1974 cpi->fn_ptr[BLOCK_16X8].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x4d);
1976 cpi->fn_ptr[BLOCK_8X16].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16);
1977 cpi->fn_ptr[BLOCK_8X16].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x16);
1978 cpi->fn_ptr[BLOCK_8X16].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x16);
1979 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_h = NULL;
1980 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_v = NULL;
1981 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_hv = NULL;
1982 cpi->fn_ptr[BLOCK_8X16].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x3);
1983 cpi->fn_ptr[BLOCK_8X16].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x8);
1984 cpi->fn_ptr[BLOCK_8X16].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x4d);
1986 cpi->fn_ptr[BLOCK_8X8].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8);
1987 cpi->fn_ptr[BLOCK_8X8].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x8);
1988 cpi->fn_ptr[BLOCK_8X8].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x8);
1989 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_h = NULL;
1990 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_v = NULL;
1991 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_hv = NULL;
1992 cpi->fn_ptr[BLOCK_8X8].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x3);
1993 cpi->fn_ptr[BLOCK_8X8].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x8);
1994 cpi->fn_ptr[BLOCK_8X8].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x4d);
1996 cpi->fn_ptr[BLOCK_4X4].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4);
1997 cpi->fn_ptr[BLOCK_4X4].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var4x4);
1998 cpi->fn_ptr[BLOCK_4X4].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar4x4);
1999 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_h = NULL;
2000 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_v = NULL;
2001 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_hv = NULL;
2002 cpi->fn_ptr[BLOCK_4X4].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x3);
2003 cpi->fn_ptr[BLOCK_4X4].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x8);
2004 cpi->fn_ptr[BLOCK_4X4].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x4d);
2006 #if ARCH_X86 || ARCH_X86_64
2007 cpi->fn_ptr[BLOCK_16X16].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2008 cpi->fn_ptr[BLOCK_16X8].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2009 cpi->fn_ptr[BLOCK_8X16].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2010 cpi->fn_ptr[BLOCK_8X8].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2011 cpi->fn_ptr[BLOCK_4X4].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2014 cpi->full_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, full_search);
2015 cpi->diamond_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, diamond_search);
2016 cpi->refining_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, refining_search);
2018 // make sure frame 1 is okay
2019 cpi->error_bins[0] = cpi->common.MBs;
2021 //vp8cx_init_quantizer() is first called here. Add check in vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only called later
2022 //when needed. This will avoid unnecessary calls of vp8cx_init_quantizer() for every frame.
2023 vp8cx_init_quantizer(cpi);
2025 vp8_loop_filter_init(cm);
2027 cpi->common.error.setjmp = 0;
2029 #if CONFIG_MULTI_RES_ENCODING
2030 /* Calculate # of MBs in a row in lower-resolution level image. */
2031 if (cpi->oxcf.mr_encoder_id > 0)
2032 vp8_cal_low_res_mb_cols(cpi);
2040 void vp8_remove_compressor(VP8_COMP **ptr)
2042 VP8_COMP *cpi = *ptr;
2047 if (cpi && (cpi->common.current_video_frame > 0))
2049 #if !(CONFIG_REALTIME_ONLY)
2053 vp8_end_second_pass(cpi);
2058 #ifdef ENTROPY_STATS
2059 print_context_counters();
2060 print_tree_update_probs();
2061 print_mode_context();
2064 #if CONFIG_INTERNAL_STATS
2068 FILE *f = fopen("opsnr.stt", "a");
2069 double time_encoded = (cpi->last_end_time_stamp_seen
2070 - cpi->first_time_stamp_ever) / 10000000.000;
2071 double total_encode_time = (cpi->time_receive_data +
2072 cpi->time_compress_data) / 1000.000;
2073 double dr = (double)cpi->bytes * 8.0 / 1000.0 / time_encoded;
2075 if (cpi->b_calculate_psnr)
2077 YV12_BUFFER_CONFIG *lst_yv12 =
2078 &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
2080 if (cpi->oxcf.number_of_layers > 1)
2084 fprintf(f, "Layer\tBitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2085 "GLPsnrP\tVPXSSIM\t\n");
2086 for (i=0; i<cpi->oxcf.number_of_layers; i++)
2088 double dr = (double)cpi->bytes_in_layer[i] *
2089 8.0 / 1000.0 / time_encoded;
2090 double samples = 3.0 / 2 * cpi->frames_in_layer[i] *
2091 lst_yv12->y_width * lst_yv12->y_height;
2092 double total_psnr = vp8_mse2psnr(samples, 255.0,
2093 cpi->total_error2[i]);
2094 double total_psnr2 = vp8_mse2psnr(samples, 255.0,
2095 cpi->total_error2_p[i]);
2096 double total_ssim = 100 * pow(cpi->sum_ssim[i] /
2097 cpi->sum_weights[i], 8.0);
2099 fprintf(f, "%5d\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2102 cpi->sum_psnr[i] / cpi->frames_in_layer[i],
2104 cpi->sum_psnr_p[i] / cpi->frames_in_layer[i],
2105 total_psnr2, total_ssim);
2110 double samples = 3.0 / 2 * cpi->count *
2111 lst_yv12->y_width * lst_yv12->y_height;
2112 double total_psnr = vp8_mse2psnr(samples, 255.0,
2113 cpi->total_sq_error);
2114 double total_psnr2 = vp8_mse2psnr(samples, 255.0,
2115 cpi->total_sq_error2);
2116 double total_ssim = 100 * pow(cpi->summed_quality /
2117 cpi->summed_weights, 8.0);
2119 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2120 "GLPsnrP\tVPXSSIM\t Time(us)\n");
2121 fprintf(f, "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2123 dr, cpi->total / cpi->count, total_psnr,
2124 cpi->totalp / cpi->count, total_psnr2,
2125 total_ssim, total_encode_time);
2129 if (cpi->b_calculate_ssimg)
2131 if (cpi->oxcf.number_of_layers > 1)
2135 fprintf(f, "Layer\tBitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t"
2137 for (i=0; i<cpi->oxcf.number_of_layers; i++)
2139 double dr = (double)cpi->bytes_in_layer[i] *
2140 8.0 / 1000.0 / time_encoded;
2141 fprintf(f, "%5d\t%7.3f\t%6.4f\t"
2142 "%6.4f\t%6.4f\t%6.4f\t%8.0f\n",
2144 cpi->total_ssimg_y_in_layer[i] /
2145 cpi->frames_in_layer[i],
2146 cpi->total_ssimg_u_in_layer[i] /
2147 cpi->frames_in_layer[i],
2148 cpi->total_ssimg_v_in_layer[i] /
2149 cpi->frames_in_layer[i],
2150 cpi->total_ssimg_all_in_layer[i] /
2151 cpi->frames_in_layer[i],
2157 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t"
2159 fprintf(f, "%7.3f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
2160 cpi->total_ssimg_y / cpi->count,
2161 cpi->total_ssimg_u / cpi->count,
2162 cpi->total_ssimg_v / cpi->count,
2163 cpi->total_ssimg_all / cpi->count, total_encode_time);
2169 f = fopen("qskip.stt", "a");
2170 fprintf(f, "minq:%d -maxq:%d skiptrue:skipfalse = %d:%d\n", cpi->oxcf.best_allowed_q, cpi->oxcf.worst_allowed_q, skiptruecount, skipfalsecount);
2181 if (cpi->compressor_speed == 2)
2184 FILE *f = fopen("cxspeed.stt", "a");
2185 cnt_pm /= cpi->common.MBs;
2187 for (i = 0; i < 16; i++)
2188 fprintf(f, "%5d", frames_at_speed[i]);
2191 //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);
2200 extern int count_mb_seg[4];
2201 FILE *f = fopen("modes.stt", "a");
2202 double dr = (double)cpi->frame_rate * (double)bytes * (double)8 / (double)count / (double)1000 ;
2203 fprintf(f, "intra_mode in Intra Frames:\n");
2204 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d\n", y_modes[0], y_modes[1], y_modes[2], y_modes[3], y_modes[4]);
2205 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", uv_modes[0], uv_modes[1], uv_modes[2], uv_modes[3]);
2210 for (i = 0; i < 10; i++)
2211 fprintf(f, "%8d, ", b_modes[i]);
2217 fprintf(f, "Modes in Inter Frames:\n");
2218 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d\n",
2219 inter_y_modes[0], inter_y_modes[1], inter_y_modes[2], inter_y_modes[3], inter_y_modes[4],
2220 inter_y_modes[5], inter_y_modes[6], inter_y_modes[7], inter_y_modes[8], inter_y_modes[9]);
2221 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", inter_uv_modes[0], inter_uv_modes[1], inter_uv_modes[2], inter_uv_modes[3]);
2226 for (i = 0; i < 15; i++)
2227 fprintf(f, "%8d, ", inter_b_modes[i]);
2232 fprintf(f, "P:%8d, %8d, %8d, %8d\n", count_mb_seg[0], count_mb_seg[1], count_mb_seg[2], count_mb_seg[3]);
2233 fprintf(f, "PB:%8d, %8d, %8d, %8d\n", inter_b_modes[LEFT4X4], inter_b_modes[ABOVE4X4], inter_b_modes[ZERO4X4], inter_b_modes[NEW4X4]);
2241 #ifdef ENTROPY_STATS
2244 FILE *fmode = fopen("modecontext.c", "w");
2246 fprintf(fmode, "\n#include \"entropymode.h\"\n\n");
2247 fprintf(fmode, "const unsigned int vp8_kf_default_bmode_counts ");
2248 fprintf(fmode, "[VP8_BINTRAMODES] [VP8_BINTRAMODES] [VP8_BINTRAMODES] =\n{\n");
2250 for (i = 0; i < 10; i++)
2253 fprintf(fmode, " { //Above Mode : %d\n", i);
2255 for (j = 0; j < 10; j++)
2258 fprintf(fmode, " {");
2260 for (k = 0; k < 10; k++)
2262 if (!intra_mode_stats[i][j][k])
2263 fprintf(fmode, " %5d, ", 1);
2265 fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
2268 fprintf(fmode, "}, // left_mode %d\n", j);
2272 fprintf(fmode, " },\n");
2276 fprintf(fmode, "};\n");
2282 #if defined(SECTIONBITS_OUTPUT)
2287 FILE *f = fopen("tokenbits.stt", "a");
2289 for (i = 0; i < 28; i++)
2290 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
2300 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2301 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
2302 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);
2308 #if CONFIG_MULTITHREAD
2309 vp8cx_remove_encoder_threads(cpi);
2312 dealloc_compressor_data(cpi);
2313 vpx_free(cpi->mb.ss);
2315 vpx_free(cpi->cyclic_refresh_map);
2317 vp8_remove_common(&cpi->common);
2321 #ifdef OUTPUT_YUV_SRC
2341 static uint64_t calc_plane_error(unsigned char *orig, int orig_stride,
2342 unsigned char *recon, int recon_stride,
2343 unsigned int cols, unsigned int rows,
2344 vp8_variance_rtcd_vtable_t *rtcd)
2346 unsigned int row, col;
2347 uint64_t total_sse = 0;
2350 for (row = 0; row + 16 <= rows; row += 16)
2352 for (col = 0; col + 16 <= cols; col += 16)
2356 VARIANCE_INVOKE(rtcd, mse16x16)(orig + col, orig_stride,
2357 recon + col, recon_stride,
2362 /* Handle odd-sized width */
2365 unsigned int border_row, border_col;
2366 unsigned char *border_orig = orig;
2367 unsigned char *border_recon = recon;
2369 for (border_row = 0; border_row < 16; border_row++)
2371 for (border_col = col; border_col < cols; border_col++)
2373 diff = border_orig[border_col] - border_recon[border_col];
2374 total_sse += diff * diff;
2377 border_orig += orig_stride;
2378 border_recon += recon_stride;
2382 orig += orig_stride * 16;
2383 recon += recon_stride * 16;
2386 /* Handle odd-sized height */
2387 for (; row < rows; row++)
2389 for (col = 0; col < cols; col++)
2391 diff = orig[col] - recon[col];
2392 total_sse += diff * diff;
2395 orig += orig_stride;
2396 recon += recon_stride;
2399 vp8_clear_system_state();
2404 static void generate_psnr_packet(VP8_COMP *cpi)
2406 YV12_BUFFER_CONFIG *orig = cpi->Source;
2407 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2408 struct vpx_codec_cx_pkt pkt;
2411 unsigned int width = cpi->common.Width;
2412 unsigned int height = cpi->common.Height;
2414 pkt.kind = VPX_CODEC_PSNR_PKT;
2415 sse = calc_plane_error(orig->y_buffer, orig->y_stride,
2416 recon->y_buffer, recon->y_stride,
2418 IF_RTCD(&cpi->rtcd.variance));
2419 pkt.data.psnr.sse[0] = sse;
2420 pkt.data.psnr.sse[1] = sse;
2421 pkt.data.psnr.samples[0] = width * height;
2422 pkt.data.psnr.samples[1] = width * height;
2424 width = (width + 1) / 2;
2425 height = (height + 1) / 2;
2427 sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
2428 recon->u_buffer, recon->uv_stride,
2430 IF_RTCD(&cpi->rtcd.variance));
2431 pkt.data.psnr.sse[0] += sse;
2432 pkt.data.psnr.sse[2] = sse;
2433 pkt.data.psnr.samples[0] += width * height;
2434 pkt.data.psnr.samples[2] = width * height;
2436 sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2437 recon->v_buffer, recon->uv_stride,
2439 IF_RTCD(&cpi->rtcd.variance));
2440 pkt.data.psnr.sse[0] += sse;
2441 pkt.data.psnr.sse[3] = sse;
2442 pkt.data.psnr.samples[0] += width * height;
2443 pkt.data.psnr.samples[3] = width * height;
2445 for (i = 0; i < 4; i++)
2446 pkt.data.psnr.psnr[i] = vp8_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2447 pkt.data.psnr.sse[i]);
2449 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2453 int vp8_use_as_reference(VP8_COMP *cpi, int ref_frame_flags)
2455 if (ref_frame_flags > 7)
2458 cpi->ref_frame_flags = ref_frame_flags;
2461 int vp8_update_reference(VP8_COMP *cpi, int ref_frame_flags)
2463 if (ref_frame_flags > 7)
2466 cpi->common.refresh_golden_frame = 0;
2467 cpi->common.refresh_alt_ref_frame = 0;
2468 cpi->common.refresh_last_frame = 0;
2470 if (ref_frame_flags & VP8_LAST_FLAG)
2471 cpi->common.refresh_last_frame = 1;
2473 if (ref_frame_flags & VP8_GOLD_FLAG)
2474 cpi->common.refresh_golden_frame = 1;
2476 if (ref_frame_flags & VP8_ALT_FLAG)
2477 cpi->common.refresh_alt_ref_frame = 1;
2482 int vp8_get_reference(VP8_COMP *cpi, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2484 VP8_COMMON *cm = &cpi->common;
2487 if (ref_frame_flag == VP8_LAST_FLAG)
2488 ref_fb_idx = cm->lst_fb_idx;
2489 else if (ref_frame_flag == VP8_GOLD_FLAG)
2490 ref_fb_idx = cm->gld_fb_idx;
2491 else if (ref_frame_flag == VP8_ALT_FLAG)
2492 ref_fb_idx = cm->alt_fb_idx;
2496 vp8_yv12_copy_frame_ptr(&cm->yv12_fb[ref_fb_idx], sd);
2500 int vp8_set_reference(VP8_COMP *cpi, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2502 VP8_COMMON *cm = &cpi->common;
2506 if (ref_frame_flag == VP8_LAST_FLAG)
2507 ref_fb_idx = cm->lst_fb_idx;
2508 else if (ref_frame_flag == VP8_GOLD_FLAG)
2509 ref_fb_idx = cm->gld_fb_idx;
2510 else if (ref_frame_flag == VP8_ALT_FLAG)
2511 ref_fb_idx = cm->alt_fb_idx;
2515 vp8_yv12_copy_frame_ptr(sd, &cm->yv12_fb[ref_fb_idx]);
2519 int vp8_update_entropy(VP8_COMP *cpi, int update)
2521 VP8_COMMON *cm = &cpi->common;
2522 cm->refresh_entropy_probs = update;
2529 void vp8_write_yuv_frame(const char *name, YV12_BUFFER_CONFIG *s)
2531 FILE *yuv_file = fopen(name, "ab");
2532 unsigned char *src = s->y_buffer;
2533 int h = s->y_height;
2537 fwrite(src, s->y_width, 1, yuv_file);
2547 fwrite(src, s->uv_width, 1, yuv_file);
2548 src += s->uv_stride;
2557 fwrite(src, s->uv_width, 1, yuv_file);
2558 src += s->uv_stride;
2567 static void scale_and_extend_source(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi)
2569 VP8_COMMON *cm = &cpi->common;
2571 // are we resizing the image
2572 if (cm->horiz_scale != 0 || cm->vert_scale != 0)
2574 #if CONFIG_SPATIAL_RESAMPLING
2575 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2576 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2579 if (cm->vert_scale == 3)
2584 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2585 Scale2Ratio(cm->vert_scale, &vr, &vs);
2587 vp8_scale_frame(sd, &cpi->scaled_source, cm->temp_scale_frame.y_buffer,
2588 tmp_height, hs, hr, vs, vr, 0);
2590 vp8_yv12_extend_frame_borders(&cpi->scaled_source);
2591 cpi->Source = &cpi->scaled_source;
2599 static void resize_key_frame(VP8_COMP *cpi)
2601 #if CONFIG_SPATIAL_RESAMPLING
2602 VP8_COMMON *cm = &cpi->common;
2604 // Do we need to apply resampling for one pass cbr.
2605 // In one pass this is more limited than in two pass cbr
2606 // The test and any change is only made one per key frame sequence
2607 if (cpi->oxcf.allow_spatial_resampling && (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER))
2609 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2610 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2611 int new_width, new_height;
2613 // If we are below the resample DOWN watermark then scale down a notch.
2614 if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2616 cm->horiz_scale = (cm->horiz_scale < ONETWO) ? cm->horiz_scale + 1 : ONETWO;
2617 cm->vert_scale = (cm->vert_scale < ONETWO) ? cm->vert_scale + 1 : ONETWO;
2619 // Should we now start scaling back up
2620 else if (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2622 cm->horiz_scale = (cm->horiz_scale > NORMAL) ? cm->horiz_scale - 1 : NORMAL;
2623 cm->vert_scale = (cm->vert_scale > NORMAL) ? cm->vert_scale - 1 : NORMAL;
2626 // Get the new hieght and width
2627 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2628 Scale2Ratio(cm->vert_scale, &vr, &vs);
2629 new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
2630 new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
2632 // If the image size has changed we need to reallocate the buffers
2633 // and resample the source image
2634 if ((cm->Width != new_width) || (cm->Height != new_height))
2636 cm->Width = new_width;
2637 cm->Height = new_height;
2638 vp8_alloc_compressor_data(cpi);
2639 scale_and_extend_source(cpi->un_scaled_source, cpi);
2647 static void update_alt_ref_frame_stats(VP8_COMP *cpi)
2649 VP8_COMMON *cm = &cpi->common;
2651 // Select an interval before next GF or altref
2652 if (!cpi->auto_gold)
2653 cpi->frames_till_gf_update_due = cpi->goldfreq;
2655 if ((cpi->pass != 2) && cpi->frames_till_gf_update_due)
2657 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2659 // Set the bits per frame that we should try and recover in subsequent inter frames
2660 // to account for the extra GF spend... note that his does not apply for GF updates
2661 // that occur coincident with a key frame as the extra cost of key frames is dealt
2664 cpi->gf_overspend_bits += cpi->projected_frame_size;
2665 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2668 // Update data structure that monitors level of reference to last GF
2669 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2670 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2672 // this frame refreshes means next frames don't unless specified by user
2673 cpi->common.frames_since_golden = 0;
2675 // Clear the alternate reference update pending flag.
2676 cpi->source_alt_ref_pending = 0;
2678 // Set the alternate refernce frame active flag
2679 cpi->source_alt_ref_active = 1;
2683 static void update_golden_frame_stats(VP8_COMP *cpi)
2685 VP8_COMMON *cm = &cpi->common;
2687 // Update the Golden frame usage counts.
2688 if (cm->refresh_golden_frame)
2690 // Select an interval before next GF
2691 if (!cpi->auto_gold)
2692 cpi->frames_till_gf_update_due = cpi->goldfreq;
2694 if ((cpi->pass != 2) && (cpi->frames_till_gf_update_due > 0))
2696 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2698 // Set the bits per frame that we should try and recover in subsequent inter frames
2699 // to account for the extra GF spend... note that his does not apply for GF updates
2700 // that occur coincident with a key frame as the extra cost of key frames is dealt
2702 if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active)
2704 // Calcluate GF bits to be recovered
2705 // Projected size - av frame bits available for inter frames for clip as a whole
2706 cpi->gf_overspend_bits += (cpi->projected_frame_size - cpi->inter_frame_target);
2709 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2713 // Update data structure that monitors level of reference to last GF
2714 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2715 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2717 // this frame refreshes means next frames don't unless specified by user
2718 cm->refresh_golden_frame = 0;
2719 cpi->common.frames_since_golden = 0;
2721 //if ( cm->frame_type == KEY_FRAME )
2723 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
2724 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
2725 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
2726 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
2730 // // Carry a potrtion of count over to begining of next gf sequence
2731 // cpi->recent_ref_frame_usage[INTRA_FRAME] >>= 5;
2732 // cpi->recent_ref_frame_usage[LAST_FRAME] >>= 5;
2733 // cpi->recent_ref_frame_usage[GOLDEN_FRAME] >>= 5;
2734 // cpi->recent_ref_frame_usage[ALTREF_FRAME] >>= 5;
2737 // ******** Fixed Q test code only ************
2738 // If we are going to use the ALT reference for the next group of frames set a flag to say so.
2739 if (cpi->oxcf.fixed_q >= 0 &&
2740 cpi->oxcf.play_alternate && !cpi->common.refresh_alt_ref_frame)
2742 cpi->source_alt_ref_pending = 1;
2743 cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2746 if (!cpi->source_alt_ref_pending)
2747 cpi->source_alt_ref_active = 0;
2749 // Decrement count down till next gf
2750 if (cpi->frames_till_gf_update_due > 0)
2751 cpi->frames_till_gf_update_due--;
2754 else if (!cpi->common.refresh_alt_ref_frame)
2756 // Decrement count down till next gf
2757 if (cpi->frames_till_gf_update_due > 0)
2758 cpi->frames_till_gf_update_due--;
2760 if (cpi->common.frames_till_alt_ref_frame)
2761 cpi->common.frames_till_alt_ref_frame --;
2763 cpi->common.frames_since_golden ++;
2765 if (cpi->common.frames_since_golden > 1)
2767 cpi->recent_ref_frame_usage[INTRA_FRAME] += cpi->count_mb_ref_frame_usage[INTRA_FRAME];
2768 cpi->recent_ref_frame_usage[LAST_FRAME] += cpi->count_mb_ref_frame_usage[LAST_FRAME];
2769 cpi->recent_ref_frame_usage[GOLDEN_FRAME] += cpi->count_mb_ref_frame_usage[GOLDEN_FRAME];
2770 cpi->recent_ref_frame_usage[ALTREF_FRAME] += cpi->count_mb_ref_frame_usage[ALTREF_FRAME];
2775 // This function updates the reference frame probability estimates that
2776 // will be used during mode selection
2777 static void update_rd_ref_frame_probs(VP8_COMP *cpi)
2779 VP8_COMMON *cm = &cpi->common;
2781 const int *const rfct = cpi->count_mb_ref_frame_usage;
2782 const int rf_intra = rfct[INTRA_FRAME];
2783 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
2785 if (cm->frame_type == KEY_FRAME)
2787 cpi->prob_intra_coded = 255;
2788 cpi->prob_last_coded = 128;
2789 cpi->prob_gf_coded = 128;
2791 else if (!(rf_intra + rf_inter))
2793 cpi->prob_intra_coded = 63;
2794 cpi->prob_last_coded = 128;
2795 cpi->prob_gf_coded = 128;
2798 // update reference frame costs since we can do better than what we got last frame.
2799 if (cpi->oxcf.number_of_layers == 1)
2801 if (cpi->common.refresh_alt_ref_frame)
2803 cpi->prob_intra_coded += 40;
2804 cpi->prob_last_coded = 200;
2805 cpi->prob_gf_coded = 1;
2807 else if (cpi->common.frames_since_golden == 0)
2809 cpi->prob_last_coded = 214;
2811 else if (cpi->common.frames_since_golden == 1)
2813 cpi->prob_last_coded = 192;
2814 cpi->prob_gf_coded = 220;
2816 else if (cpi->source_alt_ref_active)
2818 cpi->prob_gf_coded -= 20;
2820 if (cpi->prob_gf_coded < 10)
2821 cpi->prob_gf_coded = 10;
2823 if (!cpi->source_alt_ref_active)
2824 cpi->prob_gf_coded = 255;
2829 // 1 = key, 0 = inter
2830 static int decide_key_frame(VP8_COMP *cpi)
2832 VP8_COMMON *cm = &cpi->common;
2834 int code_key_frame = 0;
2838 if (cpi->Speed > 11)
2841 // Clear down mmx registers
2842 vp8_clear_system_state(); //__asm emms;
2844 if ((cpi->compressor_speed == 2) && (cpi->Speed >= 5) && (cpi->sf.RD == 0))
2846 double change = 1.0 * abs((int)(cpi->intra_error - cpi->last_intra_error)) / (1 + cpi->last_intra_error);
2847 double change2 = 1.0 * abs((int)(cpi->prediction_error - cpi->last_prediction_error)) / (1 + cpi->last_prediction_error);
2848 double minerror = cm->MBs * 256;
2852 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
2853 && cpi->prediction_error > minerror
2854 && (change > .25 || change2 > .25))
2856 FILE *f = fopen("intra_inter.stt", "a");
2858 if (cpi->prediction_error <= 0)
2859 cpi->prediction_error = 1;
2861 fprintf(f, "%d %d %d %d %14.4f\n",
2862 cm->current_video_frame,
2863 (int) cpi->prediction_error,
2864 (int) cpi->intra_error,
2865 (int)((10 * cpi->intra_error) / cpi->prediction_error),
2873 cpi->last_intra_error = cpi->intra_error;
2874 cpi->last_prediction_error = cpi->prediction_error;
2876 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
2877 && cpi->prediction_error > minerror
2878 && (change > .25 || change2 > .25))
2880 /*(change > 1.4 || change < .75)&& cpi->this_frame_percent_intra > cpi->last_frame_percent_intra + 3*/
2888 // If the following are true we might as well code a key frame
2889 if (((cpi->this_frame_percent_intra == 100) &&
2890 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
2891 ((cpi->this_frame_percent_intra > 95) &&
2892 (cpi->this_frame_percent_intra >= (cpi->last_frame_percent_intra + 5))))
2896 // in addition if the following are true and this is not a golden frame then code a key frame
2897 // Note that on golden frames there often seems to be a pop in intra useage anyway hence this
2898 // restriction is designed to prevent spurious key frames. The Intra pop needs to be investigated.
2899 else if (((cpi->this_frame_percent_intra > 60) &&
2900 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 2))) ||
2901 ((cpi->this_frame_percent_intra > 75) &&
2902 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 3 / 2))) ||
2903 ((cpi->this_frame_percent_intra > 90) &&
2904 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 10))))
2906 if (!cm->refresh_golden_frame)
2910 return code_key_frame;
2914 #if !(CONFIG_REALTIME_ONLY)
2915 static void Pass1Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags)
2920 vp8_set_quantizer(cpi, 26);
2922 scale_and_extend_source(cpi->un_scaled_source, cpi);
2923 vp8_first_pass(cpi);
2928 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame)
2936 sprintf(filename, "cx\\y%04d.raw", this_frame);
2937 yframe = fopen(filename, "wb");
2939 for (i = 0; i < frame->y_height; i++)
2940 fwrite(frame->y_buffer + i * frame->y_stride, frame->y_width, 1, yframe);
2943 sprintf(filename, "cx\\u%04d.raw", this_frame);
2944 yframe = fopen(filename, "wb");
2946 for (i = 0; i < frame->uv_height; i++)
2947 fwrite(frame->u_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2950 sprintf(filename, "cx\\v%04d.raw", this_frame);
2951 yframe = fopen(filename, "wb");
2953 for (i = 0; i < frame->uv_height; i++)
2954 fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2959 // return of 0 means drop frame
2961 // Function to test for conditions that indeicate we should loop
2962 // back and recode a frame.
2963 static int recode_loop_test( VP8_COMP *cpi,
2964 int high_limit, int low_limit,
2965 int q, int maxq, int minq )
2967 int force_recode = 0;
2968 VP8_COMMON *cm = &cpi->common;
2970 // Is frame recode allowed at all
2971 // Yes if either recode mode 1 is selected or mode two is selcted
2972 // and the frame is a key frame. golden frame or alt_ref_frame
2973 if ( (cpi->sf.recode_loop == 1) ||
2974 ( (cpi->sf.recode_loop == 2) &&
2975 ( (cm->frame_type == KEY_FRAME) ||
2976 cm->refresh_golden_frame ||
2977 cm->refresh_alt_ref_frame ) ) )
2979 // General over and under shoot tests
2980 if ( ((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
2981 ((cpi->projected_frame_size < low_limit) && (q > minq)) )
2985 // Special Constrained quality tests
2986 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
2988 // Undershoot and below auto cq level
2989 if ( (q > cpi->cq_target_quality) &&
2990 (cpi->projected_frame_size <
2991 ((cpi->this_frame_target * 7) >> 3)))
2995 // Severe undershoot and between auto and user cq level
2996 else if ( (q > cpi->oxcf.cq_level) &&
2997 (cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
2998 (cpi->active_best_quality > cpi->oxcf.cq_level))
3001 cpi->active_best_quality = cpi->oxcf.cq_level;
3006 return force_recode;
3009 void update_reference_frames(VP8_COMMON *cm)
3011 YV12_BUFFER_CONFIG *yv12_fb = cm->yv12_fb;
3013 // At this point the new frame has been encoded.
3014 // If any buffer copy / swapping is signaled it should be done here.
3016 if (cm->frame_type == KEY_FRAME)
3018 yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG | VP8_ALT_FLAG ;
3020 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3021 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3023 cm->alt_fb_idx = cm->gld_fb_idx = cm->new_fb_idx;
3025 else /* For non key frames */
3027 if (cm->refresh_alt_ref_frame)
3029 assert(!cm->copy_buffer_to_arf);
3031 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_ALT_FLAG;
3032 cm->yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3033 cm->alt_fb_idx = cm->new_fb_idx;
3035 else if (cm->copy_buffer_to_arf)
3037 assert(!(cm->copy_buffer_to_arf & ~0x3));
3039 if (cm->copy_buffer_to_arf == 1)
3041 if(cm->alt_fb_idx != cm->lst_fb_idx)
3043 yv12_fb[cm->lst_fb_idx].flags |= VP8_ALT_FLAG;
3044 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3045 cm->alt_fb_idx = cm->lst_fb_idx;
3048 else /* if (cm->copy_buffer_to_arf == 2) */
3050 if(cm->alt_fb_idx != cm->gld_fb_idx)
3052 yv12_fb[cm->gld_fb_idx].flags |= VP8_ALT_FLAG;
3053 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3054 cm->alt_fb_idx = cm->gld_fb_idx;
3059 if (cm->refresh_golden_frame)
3061 assert(!cm->copy_buffer_to_gf);
3063 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG;
3064 cm->yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3065 cm->gld_fb_idx = cm->new_fb_idx;
3067 else if (cm->copy_buffer_to_gf)
3069 assert(!(cm->copy_buffer_to_arf & ~0x3));
3071 if (cm->copy_buffer_to_gf == 1)
3073 if(cm->gld_fb_idx != cm->lst_fb_idx)
3075 yv12_fb[cm->lst_fb_idx].flags |= VP8_GOLD_FLAG;
3076 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3077 cm->gld_fb_idx = cm->lst_fb_idx;
3080 else /* if (cm->copy_buffer_to_gf == 2) */
3082 if(cm->alt_fb_idx != cm->gld_fb_idx)
3084 yv12_fb[cm->alt_fb_idx].flags |= VP8_GOLD_FLAG;
3085 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3086 cm->gld_fb_idx = cm->alt_fb_idx;
3092 if (cm->refresh_last_frame)
3094 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_LAST_FLAG;
3095 cm->yv12_fb[cm->lst_fb_idx].flags &= ~VP8_LAST_FLAG;
3096 cm->lst_fb_idx = cm->new_fb_idx;
3100 void loopfilter_frame(VP8_COMP *cpi, VP8_COMMON *cm)
3104 cm->filter_level = 0;
3108 struct vpx_usec_timer timer;
3110 vp8_clear_system_state();
3112 vpx_usec_timer_start(&timer);
3113 if (cpi->sf.auto_filter == 0)
3114 vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3117 vp8cx_pick_filter_level(cpi->Source, cpi);
3119 vpx_usec_timer_mark(&timer);
3120 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
3123 #if CONFIG_MULTITHREAD
3124 if (cpi->b_multi_threaded)
3125 sem_post(&cpi->h_event_end_lpf); /* signal that we have set filter_level */
3128 if (cm->filter_level > 0)
3130 vp8cx_set_alt_lf_level(cpi, cm->filter_level);
3131 vp8_loop_filter_frame(cm, &cpi->mb.e_mbd);
3134 vp8_yv12_extend_frame_borders_ptr(cm->frame_to_show);
3138 static void encode_frame_to_data_rate
3141 unsigned long *size,
3142 unsigned char *dest,
3143 unsigned char* dest_end,
3144 unsigned int *frame_flags
3148 int frame_over_shoot_limit;
3149 int frame_under_shoot_limit;
3159 int zbin_oq_low = 0;
3162 VP8_COMMON *cm = &cpi->common;
3163 int active_worst_qchanged = 0;
3165 int overshoot_seen = 0;
3166 int undershoot_seen = 0;
3167 int drop_mark = cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100;
3168 int drop_mark75 = drop_mark * 2 / 3;
3169 int drop_mark50 = drop_mark / 4;
3170 int drop_mark25 = drop_mark / 8;
3173 // Clear down mmx registers to allow floating point in what follows
3174 vp8_clear_system_state();
3176 // Test code for segmentation of gf/arf (0,0)
3177 //segmentation_test_function( cpi);
3179 if (cpi->compressor_speed == 2)
3181 if(cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3183 if(cpi->force_next_frame_intra)
3185 cm->frame_type = KEY_FRAME; /* delayed intra frame */
3188 cpi->force_next_frame_intra = 0;
3191 // For an alt ref frame in 2 pass we skip the call to the second pass function that sets the target bandwidth
3192 #if !(CONFIG_REALTIME_ONLY)
3196 if (cpi->common.refresh_alt_ref_frame)
3198 cpi->per_frame_bandwidth = cpi->twopass.gf_bits; // Per frame bit target for the alt ref frame
3199 cpi->target_bandwidth = cpi->twopass.gf_bits * cpi->output_frame_rate; // per second target bitrate
3204 cpi->per_frame_bandwidth = (int)(cpi->target_bandwidth / cpi->output_frame_rate);
3206 // Default turn off buffer to buffer copying
3207 cm->copy_buffer_to_gf = 0;
3208 cm->copy_buffer_to_arf = 0;
3210 // Clear zbin over-quant value and mode boost values.
3211 cpi->zbin_over_quant = 0;
3212 cpi->zbin_mode_boost = 0;
3214 // Enable or disable mode based tweaking of the zbin
3215 // For 2 Pass Only used where GF/ARF prediction quality
3216 // is above a threshold
3217 cpi->zbin_mode_boost_enabled = 1;
3220 if ( cpi->gfu_boost <= 400 )
3222 cpi->zbin_mode_boost_enabled = 0;
3226 // Current default encoder behaviour for the altref sign bias
3227 if (cpi->source_alt_ref_active)
3228 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
3230 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
3232 // Check to see if a key frame is signalled
3233 // For two pass with auto key frame enabled cm->frame_type may already be set, but not for one pass.
3234 if ((cm->current_video_frame == 0) ||
3235 (cm->frame_flags & FRAMEFLAGS_KEY) ||
3236 (cpi->oxcf.auto_key && (cpi->frames_since_key % cpi->key_frame_frequency == 0)))
3238 // Key frame from VFW/auto-keyframe/first frame
3239 cm->frame_type = KEY_FRAME;
3242 // Set default state for segment and mode based loop filter update flags
3243 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
3244 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
3245 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
3247 // Set various flags etc to special state if it is a key frame
3248 if (cm->frame_type == KEY_FRAME)
3252 // Reset the loop filter deltas and segmentation map
3253 setup_features(cpi);
3255 // If segmentation is enabled force a map update for key frames
3256 if (cpi->mb.e_mbd.segmentation_enabled)
3258 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3259 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3262 // The alternate reference frame cannot be active for a key frame
3263 cpi->source_alt_ref_active = 0;
3265 // Reset the RD threshold multipliers to default of * 1 (128)
3266 for (i = 0; i < MAX_MODES; i++)
3268 cpi->rd_thresh_mult[i] = 128;
3272 // Test code for segmentation
3273 //if ( (cm->frame_type == KEY_FRAME) || ((cm->current_video_frame % 2) == 0))
3274 //if ( (cm->current_video_frame % 2) == 0 )
3275 // enable_segmentation(cpi);
3277 // disable_segmentation(cpi);
3280 // Experimental code for lagged compress and one pass
3281 // Initialise one_pass GF frames stats
3282 // Update stats used for GF selection
3283 //if ( cpi->pass == 0 )
3285 cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
3287 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
3288 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
3289 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
3290 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
3291 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
3292 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
3293 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
3294 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
3295 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
3299 update_rd_ref_frame_probs(cpi);
3301 if (cpi->drop_frames_allowed)
3303 // The reset to decimation 0 is only done here for one pass.
3304 // Once it is set two pass leaves decimation on till the next kf.
3305 if ((cpi->buffer_level > drop_mark) && (cpi->decimation_factor > 0))
3306 cpi->decimation_factor --;
3308 if (cpi->buffer_level > drop_mark75 && cpi->decimation_factor > 0)
3309 cpi->decimation_factor = 1;
3311 else if (cpi->buffer_level < drop_mark25 && (cpi->decimation_factor == 2 || cpi->decimation_factor == 3))
3313 cpi->decimation_factor = 3;
3315 else if (cpi->buffer_level < drop_mark50 && (cpi->decimation_factor == 1 || cpi->decimation_factor == 2))
3317 cpi->decimation_factor = 2;
3319 else if (cpi->buffer_level < drop_mark75 && (cpi->decimation_factor == 0 || cpi->decimation_factor == 1))
3321 cpi->decimation_factor = 1;
3324 //vpx_log("Encoder: Decimation Factor: %d \n",cpi->decimation_factor);
3327 // The following decimates the frame rate according to a regular pattern (i.e. to 1/2 or 2/3 frame rate)
3328 // This can be used to help prevent buffer under-run in CBR mode. Alternatively it might be desirable in
3329 // some situations to drop frame rate but throw more bits at each frame.
3331 // Note that dropping a key frame can be problematic if spatial resampling is also active
3332 if (cpi->decimation_factor > 0)
3334 switch (cpi->decimation_factor)
3337 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 3 / 2;
3340 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3343 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3347 // Note that we should not throw out a key frame (especially when spatial resampling is enabled).
3348 if ((cm->frame_type == KEY_FRAME)) // && cpi->oxcf.allow_spatial_resampling )
3350 cpi->decimation_count = cpi->decimation_factor;
3352 else if (cpi->decimation_count > 0)
3354 cpi->decimation_count --;
3356 cpi->bits_off_target += cpi->av_per_frame_bandwidth;
3357 if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
3358 cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
3360 cm->current_video_frame++;
3361 cpi->frames_since_key++;
3363 #if CONFIG_INTERNAL_STATS
3367 cpi->buffer_level = cpi->bits_off_target;
3369 if (cpi->oxcf.number_of_layers > 1)
3373 // Propagate bits saved by dropping the frame to higher layers
3374 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
3376 LAYER_CONTEXT *lc = &cpi->layer_context[i];
3377 lc->bits_off_target += cpi->av_per_frame_bandwidth;
3378 if (lc->bits_off_target > lc->maximum_buffer_size)
3379 lc->bits_off_target = lc->maximum_buffer_size;
3380 lc->buffer_level = lc->bits_off_target;
3387 cpi->decimation_count = cpi->decimation_factor;
3390 // Decide how big to make the frame
3391 if (!vp8_pick_frame_size(cpi))
3393 cm->current_video_frame++;
3394 cpi->frames_since_key++;
3398 // Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
3399 // This has a knock on effect on active best quality as well.
3400 // For CBR if the buffer reaches its maximum level then we can no longer
3401 // save up bits for later frames so we might as well use them up
3402 // on the current frame.
3403 if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
3404 (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) && cpi->buffered_mode)
3406 int Adjustment = cpi->active_worst_quality / 4; // Max adjustment is 1/4
3412 if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size)
3414 buff_lvl_step = (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level) / Adjustment;
3417 Adjustment = (cpi->buffer_level - cpi->oxcf.optimal_buffer_level) / buff_lvl_step;
3422 cpi->active_worst_quality -= Adjustment;
3424 if(cpi->active_worst_quality < cpi->active_best_quality)
3425 cpi->active_worst_quality = cpi->active_best_quality;
3429 // Set an active best quality and if necessary active worst quality
3430 // There is some odd behavior for one pass here that needs attention.
3431 if ( (cpi->pass == 2) || (cpi->ni_frames > 150))
3433 vp8_clear_system_state();
3435 Q = cpi->active_worst_quality;
3437 if ( cm->frame_type == KEY_FRAME )
3439 if ( cpi->pass == 2 )
3441 if (cpi->gfu_boost > 600)
3442 cpi->active_best_quality = kf_low_motion_minq[Q];
3444 cpi->active_best_quality = kf_high_motion_minq[Q];
3446 // Special case for key frames forced because we have reached
3447 // the maximum key frame interval. Here force the Q to a range
3448 // based on the ambient Q to reduce the risk of popping
3449 if ( cpi->this_key_frame_forced )
3451 if ( cpi->active_best_quality > cpi->avg_frame_qindex * 7/8)
3452 cpi->active_best_quality = cpi->avg_frame_qindex * 7/8;
3453 else if ( cpi->active_best_quality < cpi->avg_frame_qindex >> 2 )
3454 cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
3457 // One pass more conservative
3459 cpi->active_best_quality = kf_high_motion_minq[Q];
3462 else if (cpi->oxcf.number_of_layers==1 &&
3463 (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame))
3465 // Use the lower of cpi->active_worst_quality and recent
3466 // average Q as basis for GF/ARF Q limit unless last frame was
3468 if ( (cpi->frames_since_key > 1) &&
3469 (cpi->avg_frame_qindex < cpi->active_worst_quality) )
3471 Q = cpi->avg_frame_qindex;
3474 // For constrained quality dont allow Q less than the cq level
3475 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3476 (Q < cpi->cq_target_quality) )
3478 Q = cpi->cq_target_quality;
3481 if ( cpi->pass == 2 )
3483 if ( cpi->gfu_boost > 1000 )
3484 cpi->active_best_quality = gf_low_motion_minq[Q];
3485 else if ( cpi->gfu_boost < 400 )
3486 cpi->active_best_quality = gf_high_motion_minq[Q];
3488 cpi->active_best_quality = gf_mid_motion_minq[Q];
3490 // Constrained quality use slightly lower active best.
3491 if ( cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY )
3493 cpi->active_best_quality =
3494 cpi->active_best_quality * 15/16;
3497 // One pass more conservative
3499 cpi->active_best_quality = gf_high_motion_minq[Q];
3503 cpi->active_best_quality = inter_minq[Q];
3505 // For the constant/constrained quality mode we dont want
3506 // q to fall below the cq level.
3507 if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3508 (cpi->active_best_quality < cpi->cq_target_quality) )
3510 // If we are strongly undershooting the target rate in the last
3511 // frames then use the user passed in cq value not the auto
3513 if ( cpi->rolling_actual_bits < cpi->min_frame_bandwidth )
3514 cpi->active_best_quality = cpi->oxcf.cq_level;
3516 cpi->active_best_quality = cpi->cq_target_quality;
3520 // If CBR and the buffer is as full then it is reasonable to allow
3521 // higher quality on the frames to prevent bits just going to waste.
3522 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
3524 // Note that the use of >= here elliminates the risk of a devide
3525 // by 0 error in the else if clause
3526 if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size)
3527 cpi->active_best_quality = cpi->best_quality;
3529 else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level)
3531 int Fraction = ((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) / (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level);
3532 int min_qadjustment = ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;
3534 cpi->active_best_quality -= min_qadjustment;
3538 // Make sure constrained quality mode limits are adhered to for the first
3539 // few frames of one pass encodes
3540 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
3542 if ( (cm->frame_type == KEY_FRAME) ||
3543 cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame )
3545 cpi->active_best_quality = cpi->best_quality;
3547 else if (cpi->active_best_quality < cpi->cq_target_quality)
3549 cpi->active_best_quality = cpi->cq_target_quality;
3553 // Clip the active best and worst quality values to limits
3554 if (cpi->active_worst_quality > cpi->worst_quality)
3555 cpi->active_worst_quality = cpi->worst_quality;
3557 if (cpi->active_best_quality < cpi->best_quality)
3558 cpi->active_best_quality = cpi->best_quality;
3560 if ( cpi->active_worst_quality < cpi->active_best_quality )
3561 cpi->active_worst_quality = cpi->active_best_quality;
3563 // Determine initial Q to try
3564 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3565 last_zbin_oq = cpi->zbin_over_quant;
3567 // Set highest allowed value for Zbin over quant
3568 if (cm->frame_type == KEY_FRAME)
3569 zbin_oq_high = 0; //ZBIN_OQ_MAX/16
3570 else if ((cpi->oxcf.number_of_layers == 1) && ((cm->refresh_alt_ref_frame ||
3571 (cm->refresh_golden_frame && !cpi->source_alt_ref_active))))
3576 zbin_oq_high = ZBIN_OQ_MAX;
3578 // Setup background Q adjustment for error resilient mode.
3579 // For multi-layer encodes only enable this for the base layer.
3580 if (cpi->cyclic_refresh_mode_enabled && (cpi->current_layer==0))
3581 cyclic_background_refresh(cpi, Q, 0);
3583 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3585 // Limit Q range for the adaptive loop.
3586 bottom_index = cpi->active_best_quality;
3587 top_index = cpi->active_worst_quality;
3588 q_low = cpi->active_best_quality;
3589 q_high = cpi->active_worst_quality;
3591 vp8_save_coding_context(cpi);
3596 scale_and_extend_source(cpi->un_scaled_source, cpi);
3597 #if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC
3599 if (cpi->oxcf.noise_sensitivity > 0)
3604 switch (cpi->oxcf.noise_sensitivity)
3627 if (cm->frame_type == KEY_FRAME)
3629 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0, RTCD(postproc));
3633 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0, RTCD(postproc));
3635 src = cpi->Source->y_buffer;
3637 if (cpi->Source->y_stride < 0)
3639 src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
3646 #ifdef OUTPUT_YUV_SRC
3647 vp8_write_yuv_frame(cpi->Source);
3652 vp8_clear_system_state(); //__asm emms;
3655 if(cpi->is_src_frame_alt_ref)
3659 vp8_set_quantizer(cpi, Q);
3662 // setup skip prob for costing in mode/mv decision
3663 if (cpi->common.mb_no_coeff_skip)
3665 cpi->prob_skip_false = cpi->base_skip_false_prob[Q];
3667 if (cm->frame_type != KEY_FRAME)
3669 if (cpi->common.refresh_alt_ref_frame)
3671 if (cpi->last_skip_false_probs[2] != 0)
3672 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3675 if(cpi->last_skip_false_probs[2]!=0 && abs(Q- cpi->last_skip_probs_q[2])<=16 )
3676 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3677 else if (cpi->last_skip_false_probs[2]!=0)
3678 cpi->prob_skip_false = (cpi->last_skip_false_probs[2] + cpi->prob_skip_false ) / 2;
3681 else if (cpi->common.refresh_golden_frame)
3683 if (cpi->last_skip_false_probs[1] != 0)
3684 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3687 if(cpi->last_skip_false_probs[1]!=0 && abs(Q- cpi->last_skip_probs_q[1])<=16 )
3688 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3689 else if (cpi->last_skip_false_probs[1]!=0)
3690 cpi->prob_skip_false = (cpi->last_skip_false_probs[1] + cpi->prob_skip_false ) / 2;
3695 if (cpi->last_skip_false_probs[0] != 0)
3696 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3699 if(cpi->last_skip_false_probs[0]!=0 && abs(Q- cpi->last_skip_probs_q[0])<=16 )
3700 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3701 else if(cpi->last_skip_false_probs[0]!=0)
3702 cpi->prob_skip_false = (cpi->last_skip_false_probs[0] + cpi->prob_skip_false ) / 2;
3706 //as this is for cost estimate, let's make sure it does not go extreme eitehr way
3707 if (cpi->prob_skip_false < 5)
3708 cpi->prob_skip_false = 5;
3710 if (cpi->prob_skip_false > 250)
3711 cpi->prob_skip_false = 250;
3713 if (cpi->oxcf.number_of_layers == 1 && cpi->is_src_frame_alt_ref)
3714 cpi->prob_skip_false = 1;
3721 FILE *f = fopen("skip.stt", "a");
3722 fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
3730 if (cm->frame_type == KEY_FRAME)
3732 resize_key_frame(cpi);
3733 vp8_setup_key_frame(cpi);
3736 #if CONFIG_MULTITHREAD
3737 /* wait for loopfilter thread done (for last picture)
3738 * don't do it for first frame, re-code and when PSNR is calculated
3740 if (cpi->b_multi_threaded && cm->current_video_frame && (!Loop) &&
3741 (!cpi->b_calculate_psnr))
3743 sem_wait(&cpi->h_event_end_lpf);
3747 // transform / motion compensation build reconstruction frame
3748 vp8_encode_frame(cpi);
3750 cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
3751 cpi->projected_frame_size = (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
3753 vp8_clear_system_state(); //__asm emms;
3755 // Test to see if the stats generated for this frame indicate that we should have coded a key frame
3756 // (assuming that we didn't)!
3757 if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3759 int key_frame_decision = decide_key_frame(cpi);
3761 if (cpi->compressor_speed == 2)
3763 /* we don't do re-encoding in realtime mode
3764 * if key frame is decided than we force it on next frame */
3765 cpi->force_next_frame_intra = key_frame_decision;
3767 else if (key_frame_decision)
3769 // Reset all our sizing numbers and recode
3770 cm->frame_type = KEY_FRAME;
3772 vp8_pick_frame_size(cpi);
3774 // Clear the Alt reference frame active flag when we have a key frame
3775 cpi->source_alt_ref_active = 0;
3777 // Reset the loop filter deltas and segmentation map
3778 setup_features(cpi);
3780 // If segmentation is enabled force a map update for key frames
3781 if (cpi->mb.e_mbd.segmentation_enabled)
3783 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3784 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3787 vp8_restore_coding_context(cpi);
3789 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3791 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3793 // Limit Q range for the adaptive loop.
3794 bottom_index = cpi->active_best_quality;
3795 top_index = cpi->active_worst_quality;
3796 q_low = cpi->active_best_quality;
3797 q_high = cpi->active_worst_quality;
3806 vp8_clear_system_state();
3808 if (frame_over_shoot_limit == 0)
3809 frame_over_shoot_limit = 1;
3811 // Are we are overshooting and up against the limit of active max Q.
3812 if (((cpi->pass != 2) || (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
3813 (Q == cpi->active_worst_quality) &&
3814 (cpi->active_worst_quality < cpi->worst_quality) &&
3815 (cpi->projected_frame_size > frame_over_shoot_limit))
3817 int over_size_percent = ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) / frame_over_shoot_limit;
3819 // If so is there any scope for relaxing it
3820 while ((cpi->active_worst_quality < cpi->worst_quality) && (over_size_percent > 0))
3822 cpi->active_worst_quality++;
3823 top_index = cpi->active_worst_quality;
3824 over_size_percent = (int)(over_size_percent * 0.96); // Assume 1 qstep = about 4% on frame size.
3827 // If we have updated the active max Q do not call vp8_update_rate_correction_factors() this loop.
3828 active_worst_qchanged = 1;
3831 active_worst_qchanged = 0;
3833 #if !(CONFIG_REALTIME_ONLY)
3834 // Special case handling for forced key frames
3835 if ( (cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced )
3838 int kf_err = vp8_calc_ss_err(cpi->Source,
3839 &cm->yv12_fb[cm->new_fb_idx],
3840 IF_RTCD(&cpi->rtcd.variance));
3842 // The key frame is not good enough
3843 if ( kf_err > ((cpi->ambient_err * 7) >> 3) )
3846 q_high = (Q > q_low) ? (Q - 1) : q_low;
3849 Q = (q_high + q_low) >> 1;
3851 // The key frame is much better than the previous frame
3852 else if ( kf_err < (cpi->ambient_err >> 1) )
3855 q_low = (Q < q_high) ? (Q + 1) : q_high;
3858 Q = (q_high + q_low + 1) >> 1;
3861 // Clamp Q to upper and lower limits:
3870 // Is the projected frame size out of range and are we allowed to attempt to recode.
3871 else if ( recode_loop_test( cpi,
3872 frame_over_shoot_limit, frame_under_shoot_limit,
3873 Q, top_index, bottom_index ) )
3878 // Frame size out of permitted range:
3879 // Update correction factor & compute new Q to try...
3881 // Frame is too large
3882 if (cpi->projected_frame_size > cpi->this_frame_target)
3884 //if ( cpi->zbin_over_quant == 0 )
3885 q_low = (Q < q_high) ? (Q + 1) : q_high; // Raise Qlow as to at least the current value
3887 if (cpi->zbin_over_quant > 0) // If we are using over quant do the same for zbin_oq_low
3888 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
3890 //if ( undershoot_seen || (Q == MAXQ) )
3891 if (undershoot_seen)
3893 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3894 if (!active_worst_qchanged)
3895 vp8_update_rate_correction_factors(cpi, 1);
3897 Q = (q_high + q_low + 1) / 2;
3899 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
3901 cpi->zbin_over_quant = 0;
3904 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
3905 cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
3910 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3911 if (!active_worst_qchanged)
3912 vp8_update_rate_correction_factors(cpi, 0);
3914 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3916 while (((Q < q_low) || (cpi->zbin_over_quant < zbin_oq_low)) && (Retries < 10))
3918 vp8_update_rate_correction_factors(cpi, 0);
3919 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3926 // Frame is too small
3929 if (cpi->zbin_over_quant == 0)
3930 q_high = (Q > q_low) ? (Q - 1) : q_low; // Lower q_high if not using over quant
3931 else // else lower zbin_oq_high
3932 zbin_oq_high = (cpi->zbin_over_quant > zbin_oq_low) ? (cpi->zbin_over_quant - 1) : zbin_oq_low;
3936 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3937 if (!active_worst_qchanged)
3938 vp8_update_rate_correction_factors(cpi, 1);
3940 Q = (q_high + q_low) / 2;
3942 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
3944 cpi->zbin_over_quant = 0;
3946 cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
3950 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3951 if (!active_worst_qchanged)
3952 vp8_update_rate_correction_factors(cpi, 0);
3954 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3956 // Special case reset for qlow for constrained quality.
3957 // This should only trigger where there is very substantial
3958 // undershoot on a frame and the auto cq level is above
3959 // the user passsed in value.
3960 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3966 while (((Q > q_high) || (cpi->zbin_over_quant > zbin_oq_high)) && (Retries < 10))
3968 vp8_update_rate_correction_factors(cpi, 0);
3969 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3974 undershoot_seen = 1;
3977 // Clamp Q to upper and lower limits:
3983 // Clamp cpi->zbin_over_quant
3984 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;
3986 //Loop = (Q != last_q) || (last_zbin_oq != cpi->zbin_over_quant);
3988 last_zbin_oq = cpi->zbin_over_quant;
3994 if (cpi->is_src_frame_alt_ref)
3999 vp8_restore_coding_context(cpi);
4001 #if CONFIG_INTERNAL_STATS
4002 cpi->tot_recode_hits++;
4009 // Experimental code for lagged and one pass
4010 // Update stats used for one pass GF selection
4014 double frame_intra_error;
4015 double frame_coded_error;
4016 double frame_pcnt_inter;
4017 double frame_pcnt_motion;
4019 double frame_mvr_abs;
4021 double frame_mvc_abs;
4024 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
4025 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
4026 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
4030 // Special case code to reduce pulsing when key frames are forced at a
4031 // fixed interval. Note the reconstruction error if it is the frame before
4032 // the force key frame
4033 if ( cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0) )
4035 cpi->ambient_err = vp8_calc_ss_err(cpi->Source,
4036 &cm->yv12_fb[cm->new_fb_idx],
4037 IF_RTCD(&cpi->rtcd.variance));
4040 /* This frame's MVs are saved and will be used in next frame's MV predictor.
4041 * Last frame has one more line(add to bottom) and one more column(add to
4042 * right) than cm->mip. The edge elements are initialized to 0.
4044 #if CONFIG_MULTI_RES_ENCODING
4045 if(!cpi->oxcf.mr_encoder_id && cm->show_frame)
4047 if(cm->show_frame) /* do not save for altref frame */
4052 /* Point to beginning of allocated MODE_INFO arrays. */
4053 MODE_INFO *tmp = cm->mip;
4055 if(cm->frame_type != KEY_FRAME)
4057 for (mb_row = 0; mb_row < cm->mb_rows+1; mb_row ++)
4059 for (mb_col = 0; mb_col < cm->mb_cols+1; mb_col ++)
4061 if(tmp->mbmi.ref_frame != INTRA_FRAME)
4062 cpi->lfmv[mb_col + mb_row*(cm->mode_info_stride+1)].as_int = tmp->mbmi.mv.as_int;
4064 cpi->lf_ref_frame_sign_bias[mb_col + mb_row*(cm->mode_info_stride+1)] = cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
4065 cpi->lf_ref_frame[mb_col + mb_row*(cm->mode_info_stride+1)] = tmp->mbmi.ref_frame;
4072 #if CONFIG_MULTI_RES_ENCODING
4073 vp8_cal_dissimilarity(cpi);
4076 // Update the GF useage maps.
4077 // This is done after completing the compression of a frame when all
4078 // modes etc. are finalized but before loop filter
4079 if (cpi->oxcf.number_of_layers == 1)
4080 vp8_update_gf_useage_maps(cpi, cm, &cpi->mb);
4082 if (cm->frame_type == KEY_FRAME)
4083 cm->refresh_last_frame = 1;
4087 FILE *f = fopen("gfactive.stt", "a");
4088 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);
4093 // For inter frames the current default behavior is that when
4094 // cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
4095 // This is purely an encoder decision at present.
4096 if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame)
4097 cm->copy_buffer_to_arf = 2;
4099 cm->copy_buffer_to_arf = 0;
4101 cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
4103 #if CONFIG_MULTITHREAD
4104 if (cpi->b_multi_threaded)
4106 sem_post(&cpi->h_event_start_lpf); /* start loopfilter in separate thread */
4111 loopfilter_frame(cpi, cm);
4114 update_reference_frames(cm);
4116 if (cpi->oxcf.error_resilient_mode)
4118 cm->refresh_entropy_probs = 0;
4121 #if CONFIG_MULTITHREAD
4122 /* wait that filter_level is picked so that we can continue with stream packing */
4123 if (cpi->b_multi_threaded)
4124 sem_wait(&cpi->h_event_end_lpf);
4127 // build the bitstream
4128 vp8_pack_bitstream(cpi, dest, dest_end, size);
4130 #if CONFIG_MULTITHREAD
4131 /* if PSNR packets are generated we have to wait for the lpf */
4132 if (cpi->b_multi_threaded && cpi->b_calculate_psnr)
4134 sem_wait(&cpi->h_event_end_lpf);
4138 /* Move storing frame_type out of the above loop since it is also
4139 * needed in motion search besides loopfilter */
4140 cm->last_frame_type = cm->frame_type;
4142 // Update rate control heuristics
4143 cpi->total_byte_count += (*size);
4144 cpi->projected_frame_size = (*size) << 3;
4146 if (cpi->oxcf.number_of_layers > 1)
4149 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
4150 cpi->layer_context[i].total_byte_count += (*size);
4153 if (!active_worst_qchanged)
4154 vp8_update_rate_correction_factors(cpi, 2);
4156 cpi->last_q[cm->frame_type] = cm->base_qindex;
4158 if (cm->frame_type == KEY_FRAME)
4160 vp8_adjust_key_frame_context(cpi);
4163 // Keep a record of ambient average Q.
4164 if (cm->frame_type != KEY_FRAME)
4165 cpi->avg_frame_qindex = (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
4167 // Keep a record from which we can calculate the average Q excluding GF updates and key frames
4168 if ((cm->frame_type != KEY_FRAME) && ((cpi->oxcf.number_of_layers > 1) ||
4169 (!cm->refresh_golden_frame && !cm->refresh_alt_ref_frame)))
4173 // Calculate the average Q for normal inter frames (not key or GFU
4175 if ( cpi->pass == 2 )
4177 cpi->ni_tot_qi += Q;
4178 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4182 // Damp value for first few frames
4183 if (cpi->ni_frames > 150 )
4185 cpi->ni_tot_qi += Q;
4186 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4188 // For one pass, early in the clip ... average the current frame Q
4189 // value with the worstq entered by the user as a dampening measure
4192 cpi->ni_tot_qi += Q;
4193 cpi->ni_av_qi = ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
4196 // If the average Q is higher than what was used in the last frame
4197 // (after going through the recode loop to keep the frame size within range)
4198 // then use the last frame value - 1.
4199 // The -1 is designed to stop Q and hence the data rate, from progressively
4200 // falling away during difficult sections, but at the same time reduce the number of
4201 // itterations around the recode loop.
4202 if (Q > cpi->ni_av_qi)
4203 cpi->ni_av_qi = Q - 1;
4209 // If the frame was massively oversize and we are below optimal buffer level drop next frame
4210 if ((cpi->drop_frames_allowed) &&
4211 (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
4212 (cpi->buffer_level < cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100) &&
4213 (cpi->projected_frame_size > (4 * cpi->this_frame_target)))
4215 cpi->drop_frame = 1;
4220 // Set the count for maximum consecutive dropped frames based upon the ratio of
4221 // this frame size to the target average per frame bandwidth.
4222 // (cpi->av_per_frame_bandwidth > 0) is just a sanity check to prevent / 0.
4223 if (cpi->drop_frames_allowed && (cpi->av_per_frame_bandwidth > 0))
4225 cpi->max_drop_count = cpi->projected_frame_size / cpi->av_per_frame_bandwidth;
4227 if (cpi->max_drop_count > cpi->max_consec_dropped_frames)
4228 cpi->max_drop_count = cpi->max_consec_dropped_frames;
4231 // Update the buffer level variable.
4232 // Non-viewable frames are a special case and are treated as pure overhead.
4233 if ( !cm->show_frame )
4234 cpi->bits_off_target -= cpi->projected_frame_size;
4236 cpi->bits_off_target += cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
4238 // Clip the buffer level to the maximum specified buffer size
4239 if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
4240 cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
4242 // Rolling monitors of whether we are over or underspending used to help regulate min and Max Q in two pass.
4243 cpi->rolling_target_bits = ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
4244 cpi->rolling_actual_bits = ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
4245 cpi->long_rolling_target_bits = ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
4246 cpi->long_rolling_actual_bits = ((cpi->long_rolling_actual_bits * 31) + cpi->projected_frame_size + 16) / 32;
4248 // Actual bits spent
4249 cpi->total_actual_bits += cpi->projected_frame_size;
4252 cpi->total_target_vs_actual += (cpi->this_frame_target - cpi->projected_frame_size);
4254 cpi->buffer_level = cpi->bits_off_target;
4256 // Propagate values to higher temporal layers
4257 if (cpi->oxcf.number_of_layers > 1)
4261 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
4263 LAYER_CONTEXT *lc = &cpi->layer_context[i];
4264 int bits_off_for_this_layer = lc->target_bandwidth / lc->frame_rate
4265 - cpi->projected_frame_size;
4267 lc->bits_off_target += bits_off_for_this_layer;
4269 // Clip buffer level to maximum buffer size for the layer
4270 if (lc->bits_off_target > lc->maximum_buffer_size)
4271 lc->bits_off_target = lc->maximum_buffer_size;
4273 lc->total_actual_bits += cpi->projected_frame_size;
4274 lc->total_target_vs_actual += bits_off_for_this_layer;
4275 lc->buffer_level = lc->bits_off_target;
4279 // Update bits left to the kf and gf groups to account for overshoot or undershoot on these frames
4280 if (cm->frame_type == KEY_FRAME)
4282 cpi->twopass.kf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4284 if (cpi->twopass.kf_group_bits < 0)
4285 cpi->twopass.kf_group_bits = 0 ;
4287 else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4289 cpi->twopass.gf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4291 if (cpi->twopass.gf_group_bits < 0)
4292 cpi->twopass.gf_group_bits = 0 ;
4295 if (cm->frame_type != KEY_FRAME)
4297 if (cpi->common.refresh_alt_ref_frame)
4299 cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
4300 cpi->last_skip_probs_q[2] = cm->base_qindex;
4302 else if (cpi->common.refresh_golden_frame)
4304 cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
4305 cpi->last_skip_probs_q[1] = cm->base_qindex;
4309 cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
4310 cpi->last_skip_probs_q[0] = cm->base_qindex;
4312 //update the baseline
4313 cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
4318 #if 0 && CONFIG_INTERNAL_STATS
4320 FILE *f = fopen("tmp.stt", "a");
4322 vp8_clear_system_state(); //__asm emms;
4324 if (cpi->twopass.total_left_stats.coded_error != 0.0)
4325 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4326 "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4328 cpi->common.current_video_frame, cpi->this_frame_target,
4329 cpi->projected_frame_size,
4330 (cpi->projected_frame_size - cpi->this_frame_target),
4331 (int)cpi->total_target_vs_actual,
4333 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4334 (int)cpi->total_actual_bits, cm->base_qindex,
4335 cpi->active_best_quality, cpi->active_worst_quality,
4336 cpi->ni_av_qi, cpi->cq_target_quality,
4337 cpi->zbin_over_quant,
4338 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4339 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4340 cm->frame_type, cpi->gfu_boost,
4341 cpi->twopass.est_max_qcorrection_factor,
4342 (int)cpi->twopass.bits_left,
4343 cpi->twopass.total_left_stats.coded_error,
4344 (double)cpi->twopass.bits_left /
4345 cpi->twopass.total_left_stats.coded_error,
4346 cpi->tot_recode_hits);
4348 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4349 "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4351 cpi->common.current_video_frame,
4352 cpi->this_frame_target, cpi->projected_frame_size,
4353 (cpi->projected_frame_size - cpi->this_frame_target),
4354 (int)cpi->total_target_vs_actual,
4356 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4357 (int)cpi->total_actual_bits, cm->base_qindex,
4358 cpi->active_best_quality, cpi->active_worst_quality,
4359 cpi->ni_av_qi, cpi->cq_target_quality,
4360 cpi->zbin_over_quant,
4361 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4362 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4363 cm->frame_type, cpi->gfu_boost,
4364 cpi->twopass.est_max_qcorrection_factor,
4365 (int)cpi->twopass.bits_left,
4366 cpi->twopass.total_left_stats.coded_error,
4367 cpi->tot_recode_hits);
4372 FILE *fmodes = fopen("Modes.stt", "a");
4375 fprintf(fmodes, "%6d:%1d:%1d:%1d ",
4376 cpi->common.current_video_frame,
4377 cm->frame_type, cm->refresh_golden_frame,
4378 cm->refresh_alt_ref_frame);
4380 for (i = 0; i < MAX_MODES; i++)
4381 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
4383 fprintf(fmodes, "\n");
4391 // If this was a kf or Gf note the Q
4392 if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4393 cm->last_kf_gf_q = cm->base_qindex;
4395 if (cm->refresh_golden_frame == 1)
4396 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
4398 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
4400 if (cm->refresh_alt_ref_frame == 1)
4401 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
4403 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
4406 if (cm->refresh_last_frame & cm->refresh_golden_frame) // both refreshed
4407 cpi->gold_is_last = 1;
4408 else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4409 cpi->gold_is_last = 0;
4411 if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) // both refreshed
4412 cpi->alt_is_last = 1;
4413 else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) // 1 refreshed but not the other
4414 cpi->alt_is_last = 0;
4416 if (cm->refresh_alt_ref_frame & cm->refresh_golden_frame) // both refreshed
4417 cpi->gold_is_alt = 1;
4418 else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4419 cpi->gold_is_alt = 0;
4421 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
4423 if (cpi->gold_is_last)
4424 cpi->ref_frame_flags &= ~VP8_GOLD_FLAG;
4426 if (cpi->alt_is_last)
4427 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4429 if (cpi->gold_is_alt)
4430 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4433 if (!cpi->oxcf.error_resilient_mode)
4435 if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame && (cm->frame_type != KEY_FRAME))
4436 // Update the alternate reference frame stats as appropriate.
4437 update_alt_ref_frame_stats(cpi);
4439 // Update the Golden frame stats as appropriate.
4440 update_golden_frame_stats(cpi);
4443 if (cm->frame_type == KEY_FRAME)
4445 // Tell the caller that the frame was coded as a key frame
4446 *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
4448 // As this frame is a key frame the next defaults to an inter frame.
4449 cm->frame_type = INTER_FRAME;
4451 cpi->last_frame_percent_intra = 100;
4455 *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
4457 cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
4460 // Clear the one shot update flags for segmentation map and mode/ref loop filter deltas.
4461 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
4462 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
4463 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
4466 // Dont increment frame counters if this was an altref buffer update not a real frame
4469 cm->current_video_frame++;
4470 cpi->frames_since_key++;
4473 // reset to normal state now that we are done.
4481 sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
4482 recon_file = fopen(filename, "wb");
4483 fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
4484 cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
4490 //vp8_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show);
4496 static void check_gf_quality(VP8_COMP *cpi)
4498 VP8_COMMON *cm = &cpi->common;
4499 int gf_active_pct = (100 * cpi->gf_active_count) / (cm->mb_rows * cm->mb_cols);
4500 int gf_ref_usage_pct = (cpi->count_mb_ref_frame_usage[GOLDEN_FRAME] * 100) / (cm->mb_rows * cm->mb_cols);
4501 int last_ref_zz_useage = (cpi->inter_zz_count * 100) / (cm->mb_rows * cm->mb_cols);
4503 // Gf refresh is not currently being signalled
4504 if (cpi->gf_update_recommended == 0)
4506 if (cpi->common.frames_since_golden > 7)
4509 if ((gf_active_pct < 10) || ((gf_active_pct + gf_ref_usage_pct) < 15))
4511 // ...but last frame zero zero usage is reasonbable so a new gf might be appropriate
4512 if (last_ref_zz_useage >= 25)
4514 cpi->gf_bad_count ++;
4516 if (cpi->gf_bad_count >= 8) // Check that the condition is stable
4518 cpi->gf_update_recommended = 1;
4519 cpi->gf_bad_count = 0;
4523 cpi->gf_bad_count = 0; // Restart count as the background is not stable enough
4526 cpi->gf_bad_count = 0; // Gf useage has picked up so reset count
4529 // If the signal is set but has not been read should we cancel it.
4530 else if (last_ref_zz_useage < 15)
4532 cpi->gf_update_recommended = 0;
4533 cpi->gf_bad_count = 0;
4538 FILE *f = fopen("gfneeded.stt", "a");
4539 fprintf(f, "%10d %10d %10d %10d %10ld \n",
4540 cm->current_video_frame,
4541 cpi->common.frames_since_golden,
4542 gf_active_pct, gf_ref_usage_pct,
4543 cpi->gf_update_recommended);
4550 #if !(CONFIG_REALTIME_ONLY)
4551 static void Pass2Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned char * dest_end, unsigned int *frame_flags)
4554 if (!cpi->common.refresh_alt_ref_frame)
4555 vp8_second_pass(cpi);
4557 encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
4558 cpi->twopass.bits_left -= 8 * *size;
4560 if (!cpi->common.refresh_alt_ref_frame)
4562 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
4563 *cpi->oxcf.two_pass_vbrmin_section / 100);
4564 cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->frame_rate);
4569 //For ARM NEON, d8-d15 are callee-saved registers, and need to be saved by us.
4571 extern void vp8_push_neon(int64_t *store);
4572 extern void vp8_pop_neon(int64_t *store);
4576 int vp8_receive_raw_frame(VP8_COMP *cpi, unsigned int frame_flags, YV12_BUFFER_CONFIG *sd, int64_t time_stamp, int64_t end_time)
4579 int64_t store_reg[8];
4581 VP8_COMMON *cm = &cpi->common;
4582 struct vpx_usec_timer timer;
4586 #if CONFIG_RUNTIME_CPU_DETECT
4587 if (cm->rtcd.flags & HAS_NEON)
4590 vp8_push_neon(store_reg);
4594 vpx_usec_timer_start(&timer);
4595 if(vp8_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4596 frame_flags, cpi->active_map_enabled ? cpi->active_map : NULL))
4598 cm->clr_type = sd->clrtype;
4599 vpx_usec_timer_mark(&timer);
4600 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4603 #if CONFIG_RUNTIME_CPU_DETECT
4604 if (cm->rtcd.flags & HAS_NEON)
4607 vp8_pop_neon(store_reg);
4615 static int frame_is_reference(const VP8_COMP *cpi)
4617 const VP8_COMMON *cm = &cpi->common;
4618 const MACROBLOCKD *xd = &cpi->mb.e_mbd;
4620 return cm->frame_type == KEY_FRAME || cm->refresh_last_frame
4621 || cm->refresh_golden_frame || cm->refresh_alt_ref_frame
4622 || cm->copy_buffer_to_gf || cm->copy_buffer_to_arf
4623 || cm->refresh_entropy_probs
4624 || xd->mode_ref_lf_delta_update
4625 || xd->update_mb_segmentation_map || xd->update_mb_segmentation_data;
4629 int vp8_get_compressed_data(VP8_COMP *cpi, unsigned int *frame_flags, unsigned long *size, unsigned char *dest, unsigned char *dest_end, int64_t *time_stamp, int64_t *time_end, int flush)
4632 int64_t store_reg[8];
4635 struct vpx_usec_timer tsctimer;
4636 struct vpx_usec_timer ticktimer;
4637 struct vpx_usec_timer cmptimer;
4638 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4645 if (setjmp(cpi->common.error.jmp))
4647 cpi->common.error.setjmp = 0;
4648 return VPX_CODEC_CORRUPT_FRAME;
4651 cpi->common.error.setjmp = 1;
4654 #if CONFIG_RUNTIME_CPU_DETECT
4655 if (cm->rtcd.flags & HAS_NEON)
4658 vp8_push_neon(store_reg);
4662 vpx_usec_timer_start(&cmptimer);
4666 #if !(CONFIG_REALTIME_ONLY)
4667 // Should we code an alternate reference frame
4668 if (cpi->oxcf.error_resilient_mode == 0 &&
4669 cpi->oxcf.play_alternate &&
4670 cpi->source_alt_ref_pending)
4672 if ((cpi->source = vp8_lookahead_peek(cpi->lookahead,
4673 cpi->frames_till_gf_update_due)))
4675 cpi->alt_ref_source = cpi->source;
4676 if (cpi->oxcf.arnr_max_frames > 0)
4678 vp8_temporal_filter_prepare_c(cpi,
4679 cpi->frames_till_gf_update_due);
4680 force_src_buffer = &cpi->alt_ref_buffer;
4682 cm->frames_till_alt_ref_frame = cpi->frames_till_gf_update_due;
4683 cm->refresh_alt_ref_frame = 1;
4684 cm->refresh_golden_frame = 0;
4685 cm->refresh_last_frame = 0;
4687 cpi->source_alt_ref_pending = 0; // Clear Pending alt Ref flag.
4688 cpi->is_src_frame_alt_ref = 0;
4695 if ((cpi->source = vp8_lookahead_pop(cpi->lookahead, flush)))
4699 cpi->is_src_frame_alt_ref = cpi->alt_ref_source
4700 && (cpi->source == cpi->alt_ref_source);
4702 if(cpi->is_src_frame_alt_ref)
4703 cpi->alt_ref_source = NULL;
4709 cpi->un_scaled_source =
4710 cpi->Source = force_src_buffer ? force_src_buffer : &cpi->source->img;
4711 *time_stamp = cpi->source->ts_start;
4712 *time_end = cpi->source->ts_end;
4713 *frame_flags = cpi->source->flags;
4718 #if !(CONFIG_REALTIME_ONLY)
4720 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done)
4722 vp8_end_first_pass(cpi); /* get last stats packet */
4723 cpi->twopass.first_pass_done = 1;
4729 #if CONFIG_RUNTIME_CPU_DETECT
4730 if (cm->rtcd.flags & HAS_NEON)
4733 vp8_pop_neon(store_reg);
4739 if (cpi->source->ts_start < cpi->first_time_stamp_ever)
4741 cpi->first_time_stamp_ever = cpi->source->ts_start;
4742 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
4745 // adjust frame rates based on timestamps given
4746 if (!cm->refresh_alt_ref_frame || (cpi->oxcf.number_of_layers > 1))
4748 int64_t this_duration;
4751 if (cpi->source->ts_start == cpi->first_time_stamp_ever)
4753 this_duration = cpi->source->ts_end - cpi->source->ts_start;
4758 int64_t last_duration;
4760 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
4761 last_duration = cpi->last_end_time_stamp_seen
4762 - cpi->last_time_stamp_seen;
4763 // do a step update if the duration changes by 10%
4765 step = ((this_duration - last_duration) * 10 / last_duration);
4771 cpi->ref_frame_rate = 10000000.0 / this_duration;
4774 double avg_duration, interval;
4776 /* Average this frame's rate into the last second's average
4777 * frame rate. If we haven't seen 1 second yet, then average
4778 * over the whole interval seen.
4780 interval = cpi->source->ts_end - cpi->first_time_stamp_ever;
4781 if(interval > 10000000.0)
4782 interval = 10000000;
4784 avg_duration = 10000000.0 / cpi->ref_frame_rate;
4785 avg_duration *= (interval - avg_duration + this_duration);
4786 avg_duration /= interval;
4788 cpi->ref_frame_rate = 10000000.0 / avg_duration;
4791 if (cpi->oxcf.number_of_layers > 1)
4795 // Update frame rates for each layer
4796 for (i=0; i<cpi->oxcf.number_of_layers; i++)
4798 LAYER_CONTEXT *lc = &cpi->layer_context[i];
4799 lc->frame_rate = cpi->ref_frame_rate /
4800 cpi->oxcf.rate_decimator[i];
4804 vp8_new_frame_rate(cpi, cpi->ref_frame_rate);
4807 cpi->last_time_stamp_seen = cpi->source->ts_start;
4808 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
4811 if (cpi->oxcf.number_of_layers > 1)
4815 update_layer_contexts (cpi);
4817 // Restore layer specific context & set frame rate
4818 layer = cpi->oxcf.layer_id[
4819 cm->current_video_frame % cpi->oxcf.periodicity];
4820 restore_layer_context (cpi, layer);
4821 vp8_new_frame_rate (cpi, cpi->layer_context[layer].frame_rate);
4824 if (cpi->compressor_speed == 2)
4826 if (cpi->oxcf.number_of_layers == 1)
4827 check_gf_quality(cpi);
4828 vpx_usec_timer_start(&tsctimer);
4829 vpx_usec_timer_start(&ticktimer);
4832 // start with a 0 size frame
4835 // Clear down mmx registers
4836 vp8_clear_system_state(); //__asm emms;
4838 cm->frame_type = INTER_FRAME;
4839 cm->frame_flags = *frame_flags;
4843 if (cm->refresh_alt_ref_frame)
4845 //cm->refresh_golden_frame = 1;
4846 cm->refresh_golden_frame = 0;
4847 cm->refresh_last_frame = 0;
4851 cm->refresh_golden_frame = 0;
4852 cm->refresh_last_frame = 1;
4856 /* find a free buffer for the new frame */
4859 for(; i < NUM_YV12_BUFFERS; i++)
4861 if(!cm->yv12_fb[i].flags)
4868 assert(i < NUM_YV12_BUFFERS );
4870 #if !(CONFIG_REALTIME_ONLY)
4874 Pass1Encode(cpi, size, dest, frame_flags);
4876 else if (cpi->pass == 2)
4878 Pass2Encode(cpi, size, dest, dest_end, frame_flags);
4882 encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
4884 if (cpi->compressor_speed == 2)
4886 unsigned int duration, duration2;
4887 vpx_usec_timer_mark(&tsctimer);
4888 vpx_usec_timer_mark(&ticktimer);
4890 duration = vpx_usec_timer_elapsed(&ticktimer);
4891 duration2 = (unsigned int)((double)duration / 2);
4893 if (cm->frame_type != KEY_FRAME)
4895 if (cpi->avg_encode_time == 0)
4896 cpi->avg_encode_time = duration;
4898 cpi->avg_encode_time = (7 * cpi->avg_encode_time + duration) >> 3;
4903 //if(*frame_flags!=1)
4906 if (cpi->avg_pick_mode_time == 0)
4907 cpi->avg_pick_mode_time = duration2;
4909 cpi->avg_pick_mode_time = (7 * cpi->avg_pick_mode_time + duration2) >> 3;
4915 if (cm->refresh_entropy_probs == 0)
4917 vpx_memcpy(&cm->fc, &cm->lfc, sizeof(cm->fc));
4920 // Save the contexts separately for alt ref, gold and last.
4921 // (TODO jbb -> Optimize this with pointers to avoid extra copies. )
4922 if(cm->refresh_alt_ref_frame)
4923 vpx_memcpy(&cpi->lfc_a, &cm->fc, sizeof(cm->fc));
4925 if(cm->refresh_golden_frame)
4926 vpx_memcpy(&cpi->lfc_g, &cm->fc, sizeof(cm->fc));
4928 if(cm->refresh_last_frame)
4929 vpx_memcpy(&cpi->lfc_n, &cm->fc, sizeof(cm->fc));
4931 // if its a dropped frame honor the requests on subsequent frames
4934 cpi->droppable = !frame_is_reference(cpi);
4936 // return to normal state
4937 cm->refresh_entropy_probs = 1;
4938 cm->refresh_alt_ref_frame = 0;
4939 cm->refresh_golden_frame = 0;
4940 cm->refresh_last_frame = 1;
4941 cm->frame_type = INTER_FRAME;
4945 // Save layer specific state
4946 if (cpi->oxcf.number_of_layers > 1)
4947 save_layer_context (cpi);
4949 vpx_usec_timer_mark(&cmptimer);
4950 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4952 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
4954 generate_psnr_packet(cpi);
4957 #if CONFIG_INTERNAL_STATS
4961 cpi->bytes += *size;
4968 if (cpi->b_calculate_psnr)
4972 YV12_BUFFER_CONFIG *orig = cpi->Source;
4973 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
4974 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
4975 int y_samples = orig->y_height * orig->y_width ;
4976 int uv_samples = orig->uv_height * orig->uv_width ;
4977 int t_samples = y_samples + 2 * uv_samples;
4978 int64_t sq_error, sq_error2;
4980 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
4981 recon->y_buffer, recon->y_stride, orig->y_width, orig->y_height,
4982 IF_RTCD(&cpi->rtcd.variance));
4984 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
4985 recon->u_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
4986 IF_RTCD(&cpi->rtcd.variance));
4988 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
4989 recon->v_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
4990 IF_RTCD(&cpi->rtcd.variance));
4992 sq_error = ye + ue + ve;
4994 frame_psnr = vp8_mse2psnr(t_samples, 255.0, sq_error);
4996 cpi->total_y += vp8_mse2psnr(y_samples, 255.0, ye);
4997 cpi->total_u += vp8_mse2psnr(uv_samples, 255.0, ue);
4998 cpi->total_v += vp8_mse2psnr(uv_samples, 255.0, ve);
4999 cpi->total_sq_error += sq_error;
5000 cpi->total += frame_psnr;
5002 double frame_psnr2, frame_ssim2 = 0;
5005 vp8_deblock(cm->frame_to_show, &cm->post_proc_buffer, cm->filter_level * 10 / 6, 1, 0, IF_RTCD(&cm->rtcd.postproc));
5006 vp8_clear_system_state();
5008 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
5009 pp->y_buffer, pp->y_stride, orig->y_width, orig->y_height,
5010 IF_RTCD(&cpi->rtcd.variance));
5012 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
5013 pp->u_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
5014 IF_RTCD(&cpi->rtcd.variance));
5016 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
5017 pp->v_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
5018 IF_RTCD(&cpi->rtcd.variance));
5020 sq_error2 = ye + ue + ve;
5022 frame_psnr2 = vp8_mse2psnr(t_samples, 255.0, sq_error2);
5024 cpi->totalp_y += vp8_mse2psnr(y_samples, 255.0, ye);
5025 cpi->totalp_u += vp8_mse2psnr(uv_samples, 255.0, ue);
5026 cpi->totalp_v += vp8_mse2psnr(uv_samples, 255.0, ve);
5027 cpi->total_sq_error2 += sq_error2;
5028 cpi->totalp += frame_psnr2;
5030 frame_ssim2 = vp8_calc_ssim(cpi->Source,
5031 &cm->post_proc_buffer, 1, &weight,
5032 IF_RTCD(&cpi->rtcd.variance));
5034 cpi->summed_quality += frame_ssim2 * weight;
5035 cpi->summed_weights += weight;
5037 if (cpi->oxcf.number_of_layers > 1)
5041 for (i=cpi->current_layer;
5042 i<cpi->oxcf.number_of_layers; i++)
5044 cpi->frames_in_layer[i]++;
5046 cpi->bytes_in_layer[i] += *size;
5047 cpi->sum_psnr[i] += frame_psnr;
5048 cpi->sum_psnr_p[i] += frame_psnr2;
5049 cpi->total_error2[i] += sq_error;
5050 cpi->total_error2_p[i] += sq_error2;
5051 cpi->sum_ssim[i] += frame_ssim2 * weight;
5052 cpi->sum_weights[i] += weight;
5058 if (cpi->b_calculate_ssimg)
5060 double y, u, v, frame_all;
5061 frame_all = vp8_calc_ssimg(cpi->Source, cm->frame_to_show,
5062 &y, &u, &v, IF_RTCD(&cpi->rtcd.variance));
5064 if (cpi->oxcf.number_of_layers > 1)
5068 for (i=cpi->current_layer;
5069 i<cpi->oxcf.number_of_layers; i++)
5071 if (!cpi->b_calculate_psnr)
5072 cpi->frames_in_layer[i]++;
5074 cpi->total_ssimg_y_in_layer[i] += y;
5075 cpi->total_ssimg_u_in_layer[i] += u;
5076 cpi->total_ssimg_v_in_layer[i] += v;
5077 cpi->total_ssimg_all_in_layer[i] += frame_all;
5082 cpi->total_ssimg_y += y;
5083 cpi->total_ssimg_u += u;
5084 cpi->total_ssimg_v += v;
5085 cpi->total_ssimg_all += frame_all;
5094 if (cpi->common.frame_type != 0 && cpi->common.base_qindex == cpi->oxcf.worst_allowed_q)
5096 skiptruecount += cpi->skip_true_count;
5097 skipfalsecount += cpi->skip_false_count;
5105 FILE *f = fopen("skip.stt", "a");
5106 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);
5108 if (cpi->is_src_frame_alt_ref == 1)
5109 fprintf(f, "skipcount: %4d framesize: %d\n", cpi->skip_true_count , *size);
5118 #if CONFIG_RUNTIME_CPU_DETECT
5119 if (cm->rtcd.flags & HAS_NEON)
5122 vp8_pop_neon(store_reg);
5126 cpi->common.error.setjmp = 0;
5131 int vp8_get_preview_raw_frame(VP8_COMP *cpi, YV12_BUFFER_CONFIG *dest, vp8_ppflags_t *flags)
5133 if (cpi->common.refresh_alt_ref_frame)
5139 ret = vp8_post_proc_frame(&cpi->common, dest, flags);
5142 if (cpi->common.frame_to_show)
5144 *dest = *cpi->common.frame_to_show;
5145 dest->y_width = cpi->common.Width;
5146 dest->y_height = cpi->common.Height;
5147 dest->uv_height = cpi->common.Height / 2;
5155 #endif //!CONFIG_POSTPROC
5156 vp8_clear_system_state();
5161 int vp8_set_roimap(VP8_COMP *cpi, unsigned char *map, unsigned int rows, unsigned int cols, int delta_q[4], int delta_lf[4], unsigned int threshold[4])
5163 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
5165 if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
5170 disable_segmentation(cpi);
5174 // Set the segmentation Map
5175 set_segmentation_map(cpi, map);
5177 // Activate segmentation.
5178 enable_segmentation(cpi);
5180 // Set up the quant segment data
5181 feature_data[MB_LVL_ALT_Q][0] = delta_q[0];
5182 feature_data[MB_LVL_ALT_Q][1] = delta_q[1];
5183 feature_data[MB_LVL_ALT_Q][2] = delta_q[2];
5184 feature_data[MB_LVL_ALT_Q][3] = delta_q[3];
5186 // Set up the loop segment data s
5187 feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
5188 feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
5189 feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
5190 feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
5192 cpi->segment_encode_breakout[0] = threshold[0];
5193 cpi->segment_encode_breakout[1] = threshold[1];
5194 cpi->segment_encode_breakout[2] = threshold[2];
5195 cpi->segment_encode_breakout[3] = threshold[3];
5197 // Initialise the feature data structure
5198 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
5199 set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
5204 int vp8_set_active_map(VP8_COMP *cpi, unsigned char *map, unsigned int rows, unsigned int cols)
5206 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols)
5210 vpx_memcpy(cpi->active_map, map, rows * cols);
5211 cpi->active_map_enabled = 1;
5214 cpi->active_map_enabled = 0;
5220 //cpi->active_map_enabled = 0;
5225 int vp8_set_internal_size(VP8_COMP *cpi, VPX_SCALING horiz_mode, VPX_SCALING vert_mode)
5227 if (horiz_mode <= ONETWO)
5228 cpi->common.horiz_scale = horiz_mode;
5232 if (vert_mode <= ONETWO)
5233 cpi->common.vert_scale = vert_mode;
5242 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd)
5247 unsigned char *src = source->y_buffer;
5248 unsigned char *dst = dest->y_buffer;
5251 // Loop through the Y plane raw and reconstruction data summing (square differences)
5252 for (i = 0; i < source->y_height; i += 16)
5254 for (j = 0; j < source->y_width; j += 16)
5257 Total += VARIANCE_INVOKE(rtcd, mse16x16)(src + j, source->y_stride, dst + j, dest->y_stride, &sse);
5260 src += 16 * source->y_stride;
5261 dst += 16 * dest->y_stride;
5268 int vp8_get_quantizer(VP8_COMP *cpi)
5270 return cpi->common.base_qindex;