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"
35 #include "vpx_ports/arm.h"
37 #if CONFIG_MULTI_RES_ENCODING
38 #include "mr_dissim.h"
45 extern void vp8cx_pick_filter_level_fast(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
46 extern void vp8cx_set_alt_lf_level(VP8_COMP *cpi, int filt_val);
47 extern void vp8cx_pick_filter_level(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
49 extern void vp8_deblock_frame(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *post, int filt_lvl, int low_var_thresh, int flag);
50 extern void print_parms(VP8_CONFIG *ocf, char *filenam);
51 extern unsigned int vp8_get_processor_freq();
52 extern void print_tree_update_probs();
53 extern void vp8cx_create_encoder_threads(VP8_COMP *cpi);
54 extern void vp8cx_remove_encoder_threads(VP8_COMP *cpi);
56 extern void vp8_yv12_copy_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
57 extern void vp8_yv12_copy_src_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
60 int vp8_estimate_entropy_savings(VP8_COMP *cpi);
62 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest);
64 extern void vp8_temporal_filter_prepare_c(VP8_COMP *cpi, int distance);
66 static void set_default_lf_deltas(VP8_COMP *cpi);
68 extern const int vp8_gf_interval_table[101];
70 #if CONFIG_INTERNAL_STATS
73 extern double vp8_calc_ssim
75 YV12_BUFFER_CONFIG *source,
76 YV12_BUFFER_CONFIG *dest,
82 extern double vp8_calc_ssimg
84 YV12_BUFFER_CONFIG *source,
85 YV12_BUFFER_CONFIG *dest,
106 extern int skip_true_count;
107 extern int skip_false_count;
112 extern int intra_mode_stats[10][10][10];
116 unsigned int frames_at_speed[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
117 unsigned int tot_pm = 0;
118 unsigned int cnt_pm = 0;
119 unsigned int tot_ef = 0;
120 unsigned int cnt_ef = 0;
124 extern unsigned __int64 Sectionbits[50];
125 extern int y_modes[5] ;
126 extern int uv_modes[4] ;
127 extern int b_modes[10] ;
129 extern int inter_y_modes[10] ;
130 extern int inter_uv_modes[4] ;
131 extern unsigned int inter_b_modes[15];
134 extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
136 extern const int qrounding_factors[129];
137 extern const int qzbin_factors[129];
138 extern void vp8cx_init_quantizer(VP8_COMP *cpi);
139 extern const int vp8cx_base_skip_false_prob[128];
141 // Tables relating active max Q to active min Q
142 static const int kf_low_motion_minq[QINDEX_RANGE] =
144 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
145 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
146 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
147 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
148 3,3,3,3,3,3,4,4,4,5,5,5,5,5,6,6,
149 6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
150 11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
151 16,16,17,17,18,18,18,18,19,20,20,21,21,22,23,23
153 static const int kf_high_motion_minq[QINDEX_RANGE] =
155 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
156 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
157 1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,
158 3,3,3,3,4,4,4,4,5,5,5,5,5,5,6,6,
159 6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
160 11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
161 16,16,17,17,18,18,18,18,19,19,20,20,20,20,21,21,
162 21,21,22,22,23,23,24,25,25,26,26,27,28,28,29,30
164 static const int gf_low_motion_minq[QINDEX_RANGE] =
166 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
167 3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,
168 7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,
169 11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,
170 19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,
171 27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,
172 35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,
173 43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58
175 static const int gf_mid_motion_minq[QINDEX_RANGE] =
177 0,0,0,0,1,1,1,1,1,1,2,2,3,3,3,4,
178 4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
179 9,10,10,10,10,11,11,11,12,12,12,12,13,13,13,14,
180 14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,
181 22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,
182 30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,
183 38,39,39,40,40,41,41,42,42,43,43,44,45,46,47,48,
184 49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64
186 static const int gf_high_motion_minq[QINDEX_RANGE] =
188 0,0,0,0,1,1,1,1,1,2,2,2,3,3,3,4,
189 4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
190 9,10,10,10,11,11,12,12,13,13,14,14,15,15,16,16,
191 17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,
192 25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,
193 33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,
194 41,41,42,42,43,44,45,46,47,48,49,50,51,52,53,54,
195 55,56,57,58,59,60,62,64,66,68,70,72,74,76,78,80
197 static const int inter_minq[QINDEX_RANGE] =
199 0,0,1,1,2,3,3,4,4,5,6,6,7,8,8,9,
200 9,10,11,11,12,13,13,14,15,15,16,17,17,18,19,20,
201 20,21,22,22,23,24,24,25,26,27,27,28,29,30,30,31,
202 32,33,33,34,35,36,36,37,38,39,39,40,41,42,42,43,
203 44,45,46,46,47,48,49,50,50,51,52,53,54,55,55,56,
204 57,58,59,60,60,61,62,63,64,65,66,67,67,68,69,70,
205 71,72,73,74,75,75,76,77,78,79,80,81,82,83,84,85,
206 86,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
209 void vp8_initialize()
211 static int init_done = 0;
215 vp8_scale_machine_specific_config();
216 vp8_initialize_common();
217 vp8_tokenize_initialize();
222 #ifdef PACKET_TESTING
223 extern FILE *vpxlogc;
226 static void save_layer_context(VP8_COMP *cpi)
228 LAYER_CONTEXT *lc = &cpi->layer_context[cpi->current_layer];
230 // Save layer dependent coding state
231 lc->target_bandwidth = cpi->target_bandwidth;
232 //lc->target_bandwidth = cpi->oxcf.target_bandwidth;
233 lc->starting_buffer_level = cpi->oxcf.starting_buffer_level;
234 lc->optimal_buffer_level = cpi->oxcf.optimal_buffer_level;
235 lc->maximum_buffer_size = cpi->oxcf.maximum_buffer_size;
236 lc->starting_buffer_level_in_ms = cpi->oxcf.starting_buffer_level_in_ms;
237 lc->optimal_buffer_level_in_ms = cpi->oxcf.optimal_buffer_level_in_ms;
238 lc->maximum_buffer_size_in_ms = cpi->oxcf.maximum_buffer_size_in_ms;
239 lc->buffer_level = cpi->buffer_level;
240 lc->bits_off_target = cpi->bits_off_target;
241 lc->total_actual_bits = cpi->total_actual_bits;
242 lc->worst_quality = cpi->worst_quality;
243 lc->active_worst_quality = cpi->active_worst_quality;
244 lc->best_quality = cpi->best_quality;
245 lc->active_best_quality = cpi->active_best_quality;
246 lc->ni_av_qi = cpi->ni_av_qi;
247 lc->ni_tot_qi = cpi->ni_tot_qi;
248 lc->ni_frames = cpi->ni_frames;
249 lc->avg_frame_qindex = cpi->avg_frame_qindex;
250 lc->rate_correction_factor = cpi->rate_correction_factor;
251 lc->key_frame_rate_correction_factor = cpi->key_frame_rate_correction_factor;
252 lc->gf_rate_correction_factor = cpi->gf_rate_correction_factor;
253 lc->zbin_over_quant = cpi->zbin_over_quant;
254 lc->inter_frame_target = cpi->inter_frame_target;
255 lc->total_byte_count = cpi->total_byte_count;
256 lc->filter_level = cpi->common.filter_level;
258 lc->last_frame_percent_intra = cpi->last_frame_percent_intra;
260 memcpy (lc->count_mb_ref_frame_usage,
261 cpi->count_mb_ref_frame_usage,
262 sizeof(cpi->count_mb_ref_frame_usage));
265 static void restore_layer_context(VP8_COMP *cpi, const int layer)
267 LAYER_CONTEXT *lc = &cpi->layer_context[layer];
269 // Restore layer dependent coding state
270 cpi->current_layer = layer;
271 cpi->target_bandwidth = lc->target_bandwidth;
272 cpi->oxcf.target_bandwidth = lc->target_bandwidth;
273 cpi->oxcf.starting_buffer_level = lc->starting_buffer_level;
274 cpi->oxcf.optimal_buffer_level = lc->optimal_buffer_level;
275 cpi->oxcf.maximum_buffer_size = lc->maximum_buffer_size;
276 cpi->oxcf.starting_buffer_level_in_ms = lc->starting_buffer_level_in_ms;
277 cpi->oxcf.optimal_buffer_level_in_ms = lc->optimal_buffer_level_in_ms;
278 cpi->oxcf.maximum_buffer_size_in_ms = lc->maximum_buffer_size_in_ms;
279 cpi->buffer_level = lc->buffer_level;
280 cpi->bits_off_target = lc->bits_off_target;
281 cpi->total_actual_bits = lc->total_actual_bits;
282 //cpi->worst_quality = lc->worst_quality;
283 cpi->active_worst_quality = lc->active_worst_quality;
284 //cpi->best_quality = lc->best_quality;
285 cpi->active_best_quality = lc->active_best_quality;
286 cpi->ni_av_qi = lc->ni_av_qi;
287 cpi->ni_tot_qi = lc->ni_tot_qi;
288 cpi->ni_frames = lc->ni_frames;
289 cpi->avg_frame_qindex = lc->avg_frame_qindex;
290 cpi->rate_correction_factor = lc->rate_correction_factor;
291 cpi->key_frame_rate_correction_factor = lc->key_frame_rate_correction_factor;
292 cpi->gf_rate_correction_factor = lc->gf_rate_correction_factor;
293 cpi->zbin_over_quant = lc->zbin_over_quant;
294 cpi->inter_frame_target = lc->inter_frame_target;
295 cpi->total_byte_count = lc->total_byte_count;
296 cpi->common.filter_level = lc->filter_level;
298 cpi->last_frame_percent_intra = lc->last_frame_percent_intra;
300 memcpy (cpi->count_mb_ref_frame_usage,
301 lc->count_mb_ref_frame_usage,
302 sizeof(cpi->count_mb_ref_frame_usage));
305 static void setup_features(VP8_COMP *cpi)
307 // Set up default state for MB feature flags
308 cpi->mb.e_mbd.segmentation_enabled = 0;
309 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
310 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
311 vpx_memset(cpi->mb.e_mbd.mb_segment_tree_probs, 255, sizeof(cpi->mb.e_mbd.mb_segment_tree_probs));
312 vpx_memset(cpi->mb.e_mbd.segment_feature_data, 0, sizeof(cpi->mb.e_mbd.segment_feature_data));
314 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 0;
315 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
316 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
317 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
318 vpx_memset(cpi->mb.e_mbd.last_ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
319 vpx_memset(cpi->mb.e_mbd.last_mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
321 set_default_lf_deltas(cpi);
326 static void dealloc_raw_frame_buffers(VP8_COMP *cpi);
329 static void dealloc_compressor_data(VP8_COMP *cpi)
331 vpx_free(cpi->tplist);
334 // Delete last frame MV storage buffers
338 vpx_free(cpi->lf_ref_frame_sign_bias);
339 cpi->lf_ref_frame_sign_bias = 0;
341 vpx_free(cpi->lf_ref_frame);
342 cpi->lf_ref_frame = 0;
344 // Delete sementation map
345 vpx_free(cpi->segmentation_map);
346 cpi->segmentation_map = 0;
348 vpx_free(cpi->active_map);
351 vp8_de_alloc_frame_buffers(&cpi->common);
353 vp8_yv12_de_alloc_frame_buffer(&cpi->pick_lf_lvl_frame);
354 vp8_yv12_de_alloc_frame_buffer(&cpi->scaled_source);
355 dealloc_raw_frame_buffers(cpi);
360 // Structure used to monitor GF usage
361 vpx_free(cpi->gf_active_flags);
362 cpi->gf_active_flags = 0;
364 // Activity mask based per mb zbin adjustments
365 vpx_free(cpi->mb_activity_map);
366 cpi->mb_activity_map = 0;
367 vpx_free(cpi->mb_norm_activity_map);
368 cpi->mb_norm_activity_map = 0;
370 vpx_free(cpi->mb.pip);
374 static void enable_segmentation(VP8_COMP *cpi)
376 // Set the appropriate feature bit
377 cpi->mb.e_mbd.segmentation_enabled = 1;
378 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
379 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
381 static void disable_segmentation(VP8_COMP *cpi)
383 // Clear the appropriate feature bit
384 cpi->mb.e_mbd.segmentation_enabled = 0;
387 // Valid values for a segment are 0 to 3
388 // Segmentation map is arrange as [Rows][Columns]
389 static void set_segmentation_map(VP8_COMP *cpi, unsigned char *segmentation_map)
391 // Copy in the new segmentation map
392 vpx_memcpy(cpi->segmentation_map, segmentation_map, (cpi->common.mb_rows * cpi->common.mb_cols));
394 // Signal that the map should be updated.
395 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
396 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
399 // The values given for each segment can be either deltas (from the default value chosen for the frame) or absolute values.
401 // Valid range for abs values is (0-127 for MB_LVL_ALT_Q) , (0-63 for SEGMENT_ALT_LF)
402 // Valid range for delta values are (+/-127 for MB_LVL_ALT_Q) , (+/-63 for SEGMENT_ALT_LF)
404 // abs_delta = SEGMENT_DELTADATA (deltas) abs_delta = SEGMENT_ABSDATA (use the absolute values given).
407 static void set_segment_data(VP8_COMP *cpi, signed char *feature_data, unsigned char abs_delta)
409 cpi->mb.e_mbd.mb_segement_abs_delta = abs_delta;
410 vpx_memcpy(cpi->segment_feature_data, feature_data, sizeof(cpi->segment_feature_data));
414 static void segmentation_test_function(VP8_COMP *cpi)
416 unsigned char *seg_map;
417 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
419 // Create a temporary map for segmentation data.
420 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
422 // MB loop to set local segmentation map
423 /*for ( i = 0; i < cpi->common.mb_rows; i++ )
425 for ( j = 0; j < cpi->common.mb_cols; j++ )
427 //seg_map[(i*cpi->common.mb_cols) + j] = (j % 2) + ((i%2)* 2);
428 //if ( j < cpi->common.mb_cols/2 )
430 // Segment 1 around the edge else 0
431 if ( (i == 0) || (j == 0) || (i == (cpi->common.mb_rows-1)) || (j == (cpi->common.mb_cols-1)) )
432 seg_map[(i*cpi->common.mb_cols) + j] = 1;
433 //else if ( (i < 2) || (j < 2) || (i > (cpi->common.mb_rows-3)) || (j > (cpi->common.mb_cols-3)) )
434 // seg_map[(i*cpi->common.mb_cols) + j] = 2;
435 //else if ( (i < 5) || (j < 5) || (i > (cpi->common.mb_rows-6)) || (j > (cpi->common.mb_cols-6)) )
436 // seg_map[(i*cpi->common.mb_cols) + j] = 3;
438 seg_map[(i*cpi->common.mb_cols) + j] = 0;
442 // Set the segmentation Map
443 set_segmentation_map(cpi, seg_map);
445 // Activate segmentation.
446 enable_segmentation(cpi);
448 // Set up the quant segment data
449 feature_data[MB_LVL_ALT_Q][0] = 0;
450 feature_data[MB_LVL_ALT_Q][1] = 4;
451 feature_data[MB_LVL_ALT_Q][2] = 0;
452 feature_data[MB_LVL_ALT_Q][3] = 0;
453 // Set up the loop segment data
454 feature_data[MB_LVL_ALT_LF][0] = 0;
455 feature_data[MB_LVL_ALT_LF][1] = 0;
456 feature_data[MB_LVL_ALT_LF][2] = 0;
457 feature_data[MB_LVL_ALT_LF][3] = 0;
459 // Initialise the feature data structure
460 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
461 set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
463 // Delete sementation map
470 // A simple function to cyclically refresh the background at a lower Q
471 static void cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment)
473 unsigned char *seg_map;
474 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
476 int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
477 int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
479 // Create a temporary map for segmentation data.
480 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
482 cpi->cyclic_refresh_q = Q;
484 for (i = Q; i > 0; i--)
486 if (vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*(Q + 128)) / 64))
487 //if ( vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*((2*Q)+96))/64) )
493 cpi->cyclic_refresh_q = i;
495 // Only update for inter frames
496 if (cpi->common.frame_type != KEY_FRAME)
498 // Cycle through the macro_block rows
499 // MB loop to set local segmentation map
500 for (i = cpi->cyclic_refresh_mode_index; i < mbs_in_frame; i++)
502 // If the MB is as a candidate for clean up then mark it for possible boost/refresh (segment 1)
503 // The segment id may get reset to 0 later if the MB gets coded anything other than last frame 0,0
504 // as only (last frame 0,0) MBs are eligable for refresh : that is to say Mbs likely to be background blocks.
505 if (cpi->cyclic_refresh_map[i] == 0)
513 // Skip blocks that have been refreshed recently anyway.
514 if (cpi->cyclic_refresh_map[i] < 0)
515 //cpi->cyclic_refresh_map[i] = cpi->cyclic_refresh_map[i] / 16;
516 cpi->cyclic_refresh_map[i]++;
527 // If we have gone through the frame reset to the start
528 cpi->cyclic_refresh_mode_index = i;
530 if (cpi->cyclic_refresh_mode_index >= mbs_in_frame)
531 cpi->cyclic_refresh_mode_index = 0;
534 // Set the segmentation Map
535 set_segmentation_map(cpi, seg_map);
537 // Activate segmentation.
538 enable_segmentation(cpi);
540 // Set up the quant segment data
541 feature_data[MB_LVL_ALT_Q][0] = 0;
542 feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
543 feature_data[MB_LVL_ALT_Q][2] = 0;
544 feature_data[MB_LVL_ALT_Q][3] = 0;
546 // Set up the loop segment data
547 feature_data[MB_LVL_ALT_LF][0] = 0;
548 feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
549 feature_data[MB_LVL_ALT_LF][2] = 0;
550 feature_data[MB_LVL_ALT_LF][3] = 0;
552 // Initialise the feature data structure
553 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
554 set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
556 // Delete sementation map
563 static void set_default_lf_deltas(VP8_COMP *cpi)
565 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 1;
566 cpi->mb.e_mbd.mode_ref_lf_delta_update = 1;
568 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
569 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
571 // Test of ref frame deltas
572 cpi->mb.e_mbd.ref_lf_deltas[INTRA_FRAME] = 2;
573 cpi->mb.e_mbd.ref_lf_deltas[LAST_FRAME] = 0;
574 cpi->mb.e_mbd.ref_lf_deltas[GOLDEN_FRAME] = -2;
575 cpi->mb.e_mbd.ref_lf_deltas[ALTREF_FRAME] = -2;
577 cpi->mb.e_mbd.mode_lf_deltas[0] = 4; // BPRED
578 cpi->mb.e_mbd.mode_lf_deltas[1] = -2; // Zero
579 cpi->mb.e_mbd.mode_lf_deltas[2] = 2; // New mv
580 cpi->mb.e_mbd.mode_lf_deltas[3] = 4; // Split mv
583 /* Convenience macros for mapping speed and mode into a continuous
586 #define GOOD(x) (x+1)
589 static int speed_map(int speed, int *map)
596 } while(speed >= *map++);
600 static int thresh_mult_map_znn[] = {
601 /* map common to zero, nearest, and near */
602 0, GOOD(2), 1500, GOOD(3), 2000, RT(0), 1000, RT(2), 2000, INT_MAX
605 static int thresh_mult_map_vhpred[] = {
606 1000, GOOD(2), 1500, GOOD(3), 2000, RT(0), 1000, RT(1), 2000,
607 RT(7), INT_MAX, INT_MAX
610 static int thresh_mult_map_bpred[] = {
611 2000, GOOD(0), 2500, GOOD(2), 5000, GOOD(3), 7500, RT(0), 2500, RT(1), 5000,
612 RT(6), INT_MAX, INT_MAX
615 static int thresh_mult_map_tm[] = {
616 1000, GOOD(2), 1500, GOOD(3), 2000, RT(0), 0, RT(1), 1000, RT(2), 2000,
617 RT(7), INT_MAX, INT_MAX
620 static int thresh_mult_map_new1[] = {
621 1000, GOOD(2), 2000, RT(0), 2000, INT_MAX
624 static int thresh_mult_map_new2[] = {
625 1000, GOOD(2), 2000, GOOD(3), 2500, GOOD(5), 4000, RT(0), 2000, RT(2), 2500,
629 static int thresh_mult_map_split1[] = {
630 2500, GOOD(0), 1700, GOOD(2), 10000, GOOD(3), 25000, GOOD(4), INT_MAX,
631 RT(0), 5000, RT(1), 10000, RT(2), 25000, RT(3), INT_MAX, INT_MAX
634 static int thresh_mult_map_split2[] = {
635 5000, GOOD(0), 4500, GOOD(2), 20000, GOOD(3), 50000, GOOD(4), INT_MAX,
636 RT(0), 10000, RT(1), 20000, RT(2), 50000, RT(3), INT_MAX, INT_MAX
639 static int mode_check_freq_map_zn2[] = {
640 /* {zero,nearest}{2,3} */
641 0, RT(10), 1<<1, RT(11), 1<<2, RT(12), 1<<3, INT_MAX
644 static int mode_check_freq_map_vhbpred[] = {
645 0, GOOD(5), 2, RT(0), 0, RT(3), 2, RT(5), 4, INT_MAX
648 static int mode_check_freq_map_near2[] = {
649 0, GOOD(5), 2, RT(0), 0, RT(3), 2, RT(10), 1<<2, RT(11), 1<<3, RT(12), 1<<4,
653 static int mode_check_freq_map_new1[] = {
654 0, RT(10), 1<<1, RT(11), 1<<2, RT(12), 1<<3, INT_MAX
657 static int mode_check_freq_map_new2[] = {
658 0, GOOD(5), 4, RT(0), 0, RT(3), 4, RT(10), 1<<3, RT(11), 1<<4, RT(12), 1<<5,
662 static int mode_check_freq_map_split1[] = {
663 0, GOOD(2), 2, GOOD(3), 7, RT(1), 2, RT(2), 7, INT_MAX
666 static int mode_check_freq_map_split2[] = {
667 0, GOOD(1), 2, GOOD(2), 4, GOOD(3), 15, RT(1), 4, RT(2), 15, INT_MAX
670 void vp8_set_speed_features(VP8_COMP *cpi)
672 SPEED_FEATURES *sf = &cpi->sf;
673 int Mode = cpi->compressor_speed;
674 int Speed = cpi->Speed;
676 VP8_COMMON *cm = &cpi->common;
677 int last_improved_quant = sf->improved_quant;
680 // Initialise default mode frequency sampling variables
681 for (i = 0; i < MAX_MODES; i ++)
683 cpi->mode_check_freq[i] = 0;
684 cpi->mode_test_hit_counts[i] = 0;
685 cpi->mode_chosen_counts[i] = 0;
688 cpi->mbs_tested_so_far = 0;
690 // best quality defaults
692 sf->search_method = NSTEP;
693 sf->improved_quant = 1;
694 sf->improved_dct = 1;
697 sf->quarter_pixel_search = 1;
698 sf->half_pixel_search = 1;
699 sf->iterative_sub_pixel = 1;
700 sf->optimize_coefficients = 1;
701 sf->use_fastquant_for_pick = 0;
702 sf->no_skip_block4x4_search = 1;
705 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
706 sf->improved_mv_pred = 1;
708 // default thresholds to 0
709 for (i = 0; i < MAX_MODES; i++)
710 sf->thresh_mult[i] = 0;
712 /* Count enabled references */
714 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
716 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
718 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
721 /* Convert speed to continuous range, with clamping */
733 sf->thresh_mult[THR_ZERO1] =
734 sf->thresh_mult[THR_NEAREST1] =
735 sf->thresh_mult[THR_NEAR1] =
736 sf->thresh_mult[THR_DC] = 0; /* always */
738 sf->thresh_mult[THR_ZERO2] =
739 sf->thresh_mult[THR_ZERO3] =
740 sf->thresh_mult[THR_NEAREST2] =
741 sf->thresh_mult[THR_NEAREST3] =
742 sf->thresh_mult[THR_NEAR2] =
743 sf->thresh_mult[THR_NEAR3] = speed_map(Speed, thresh_mult_map_znn);
745 sf->thresh_mult[THR_V_PRED] =
746 sf->thresh_mult[THR_H_PRED] = speed_map(Speed, thresh_mult_map_vhpred);
747 sf->thresh_mult[THR_B_PRED] = speed_map(Speed, thresh_mult_map_bpred);
748 sf->thresh_mult[THR_TM] = speed_map(Speed, thresh_mult_map_tm);
749 sf->thresh_mult[THR_NEW1] = speed_map(Speed, thresh_mult_map_new1);
750 sf->thresh_mult[THR_NEW2] =
751 sf->thresh_mult[THR_NEW3] = speed_map(Speed, thresh_mult_map_new2);
752 sf->thresh_mult[THR_SPLIT1] = speed_map(Speed, thresh_mult_map_split1);
753 sf->thresh_mult[THR_SPLIT2] =
754 sf->thresh_mult[THR_SPLIT3] = speed_map(Speed, thresh_mult_map_split2);
756 cpi->mode_check_freq[THR_ZERO1] =
757 cpi->mode_check_freq[THR_NEAREST1] =
758 cpi->mode_check_freq[THR_NEAR1] =
759 cpi->mode_check_freq[THR_TM] =
760 cpi->mode_check_freq[THR_DC] = 0; /* always */
762 cpi->mode_check_freq[THR_ZERO2] =
763 cpi->mode_check_freq[THR_ZERO3] =
764 cpi->mode_check_freq[THR_NEAREST2] =
765 cpi->mode_check_freq[THR_NEAREST3] = speed_map(Speed,
766 mode_check_freq_map_zn2);
768 cpi->mode_check_freq[THR_NEAR2] =
769 cpi->mode_check_freq[THR_NEAR3] = speed_map(Speed,
770 mode_check_freq_map_near2);
772 cpi->mode_check_freq[THR_V_PRED] =
773 cpi->mode_check_freq[THR_H_PRED] =
774 cpi->mode_check_freq[THR_B_PRED] = speed_map(Speed,
775 mode_check_freq_map_vhbpred);
776 cpi->mode_check_freq[THR_NEW1] = speed_map(Speed,
777 mode_check_freq_map_new1);
778 cpi->mode_check_freq[THR_NEW2] =
779 cpi->mode_check_freq[THR_NEW3] = speed_map(Speed,
780 mode_check_freq_map_new2);
781 cpi->mode_check_freq[THR_SPLIT1] = speed_map(Speed,
782 mode_check_freq_map_split1);
783 cpi->mode_check_freq[THR_SPLIT2] =
784 cpi->mode_check_freq[THR_SPLIT3] = speed_map(Speed,
785 mode_check_freq_map_split2);
789 #if !(CONFIG_REALTIME_ONLY)
790 case 0: // best quality mode
792 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
798 /* Disable coefficient optimization above speed 0 */
799 sf->optimize_coefficients = 0;
800 sf->use_fastquant_for_pick = 1;
801 sf->no_skip_block4x4_search = 0;
808 sf->improved_quant = 0;
809 sf->improved_dct = 0;
811 // Only do recode loop on key frames, golden frames and
820 sf->recode_loop = 0; // recode loop off
821 sf->RD = 0; // Turn rd off
827 sf->auto_filter = 0; // Faster selection of loop filter
833 sf->optimize_coefficients = 0;
836 sf->iterative_sub_pixel = 1;
837 sf->search_method = NSTEP;
841 sf->improved_quant = 0;
842 sf->improved_dct = 0;
844 sf->use_fastquant_for_pick = 1;
845 sf->no_skip_block4x4_search = 0;
850 sf->auto_filter = 0; // Faster selection of loop filter
860 sf->auto_filter = 0; // Faster selection of loop filter
861 sf->search_method = HEX;
862 sf->iterative_sub_pixel = 0;
867 unsigned int sum = 0;
868 unsigned int total_mbs = cm->MBs;
870 unsigned int total_skip;
874 if (cpi->oxcf.encode_breakout > 2000)
875 min = cpi->oxcf.encode_breakout;
879 for (i = 0; i < min; i++)
881 sum += cpi->error_bins[i];
887 // i starts from 2 to make sure thresh started from 2048
888 for (; i < 1024; i++)
890 sum += cpi->error_bins[i];
892 if (10 * sum >= (unsigned int)(cpi->Speed - 6)*(total_mbs - total_skip))
904 sf->thresh_mult[THR_NEW1 ] = thresh;
905 sf->thresh_mult[THR_NEAREST1 ] = thresh >> 1;
906 sf->thresh_mult[THR_NEAR1 ] = thresh >> 1;
911 sf->thresh_mult[THR_NEW2] = thresh << 1;
912 sf->thresh_mult[THR_NEAREST2 ] = thresh;
913 sf->thresh_mult[THR_NEAR2 ] = thresh;
918 sf->thresh_mult[THR_NEW3] = thresh << 1;
919 sf->thresh_mult[THR_NEAREST3 ] = thresh;
920 sf->thresh_mult[THR_NEAR3 ] = thresh;
923 sf->improved_mv_pred = 0;
927 sf->quarter_pixel_search = 0;
931 cm->filter_type = NORMAL_LOOPFILTER;
934 cm->filter_type = SIMPLE_LOOPFILTER;
938 cm->filter_type = SIMPLE_LOOPFILTER;
941 // This has a big hit on quality. Last resort
943 sf->half_pixel_search = 0;
945 vpx_memset(cpi->error_bins, 0, sizeof(cpi->error_bins));
949 // Slow quant, dct and trellis not worthwhile for first pass
950 // so make sure they are always turned off.
951 if ( cpi->pass == 1 )
953 sf->improved_quant = 0;
954 sf->optimize_coefficients = 0;
955 sf->improved_dct = 0;
958 if (cpi->sf.search_method == NSTEP)
960 vp8_init3smotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
962 else if (cpi->sf.search_method == DIAMOND)
964 vp8_init_dsmotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
967 if (cpi->sf.improved_dct)
969 cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
970 cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
974 /* No fast FDCT defined for any platform at this time. */
975 cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
976 cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
979 cpi->mb.short_walsh4x4 = vp8_short_walsh4x4;
981 if (cpi->sf.improved_quant)
983 cpi->mb.quantize_b = vp8_regular_quantize_b;
984 cpi->mb.quantize_b_pair = vp8_regular_quantize_b_pair;
988 cpi->mb.quantize_b = vp8_fast_quantize_b;
989 cpi->mb.quantize_b_pair = vp8_fast_quantize_b_pair;
991 if (cpi->sf.improved_quant != last_improved_quant)
992 vp8cx_init_quantizer(cpi);
994 if (cpi->sf.iterative_sub_pixel == 1)
996 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step_iteratively;
998 else if (cpi->sf.quarter_pixel_search)
1000 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step;
1002 else if (cpi->sf.half_pixel_search)
1004 cpi->find_fractional_mv_step = vp8_find_best_half_pixel_step;
1008 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1011 if (cpi->sf.optimize_coefficients == 1 && cpi->pass!=1)
1012 cpi->mb.optimize = 1;
1014 cpi->mb.optimize = 0;
1016 if (cpi->common.full_pixel)
1017 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1020 frames_at_speed[cpi->Speed]++;
1026 static void alloc_raw_frame_buffers(VP8_COMP *cpi)
1028 int width = (cpi->oxcf.Width + 15) & ~15;
1029 int height = (cpi->oxcf.Height + 15) & ~15;
1031 cpi->lookahead = vp8_lookahead_init(cpi->oxcf.Width, cpi->oxcf.Height,
1032 cpi->oxcf.lag_in_frames);
1034 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1035 "Failed to allocate lag buffers");
1037 #if VP8_TEMPORAL_ALT_REF
1039 if (vp8_yv12_alloc_frame_buffer(&cpi->alt_ref_buffer,
1040 width, height, VP8BORDERINPIXELS))
1041 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1042 "Failed to allocate altref buffer");
1048 static void dealloc_raw_frame_buffers(VP8_COMP *cpi)
1050 #if VP8_TEMPORAL_ALT_REF
1051 vp8_yv12_de_alloc_frame_buffer(&cpi->alt_ref_buffer);
1053 vp8_lookahead_destroy(cpi->lookahead);
1057 static int vp8_alloc_partition_data(VP8_COMP *cpi)
1059 vpx_free(cpi->mb.pip);
1061 cpi->mb.pip = vpx_calloc((cpi->common.mb_cols + 1) *
1062 (cpi->common.mb_rows + 1),
1063 sizeof(PARTITION_INFO));
1067 cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
1072 void vp8_alloc_compressor_data(VP8_COMP *cpi)
1074 VP8_COMMON *cm = & cpi->common;
1076 int width = cm->Width;
1077 int height = cm->Height;
1079 if (vp8_alloc_frame_buffers(cm, width, height))
1080 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1081 "Failed to allocate frame buffers");
1083 if (vp8_alloc_partition_data(cpi))
1084 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1085 "Failed to allocate partition data");
1088 if ((width & 0xf) != 0)
1089 width += 16 - (width & 0xf);
1091 if ((height & 0xf) != 0)
1092 height += 16 - (height & 0xf);
1095 if (vp8_yv12_alloc_frame_buffer(&cpi->pick_lf_lvl_frame,
1096 width, height, VP8BORDERINPIXELS))
1097 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1098 "Failed to allocate last frame buffer");
1100 if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source,
1101 width, height, VP8BORDERINPIXELS))
1102 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1103 "Failed to allocate scaled source buffer");
1109 unsigned int tokens = cm->mb_rows * cm->mb_cols * 24 * 16;
1111 CHECK_MEM_ERROR(cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
1114 // Data used for real time vc mode to see if gf needs refreshing
1115 cpi->inter_zz_count = 0;
1116 cpi->gf_bad_count = 0;
1117 cpi->gf_update_recommended = 0;
1120 // Structures used to minitor GF usage
1121 vpx_free(cpi->gf_active_flags);
1122 CHECK_MEM_ERROR(cpi->gf_active_flags,
1123 vpx_calloc(1, cm->mb_rows * cm->mb_cols));
1124 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
1126 vpx_free(cpi->mb_activity_map);
1127 CHECK_MEM_ERROR(cpi->mb_activity_map,
1128 vpx_calloc(sizeof(unsigned int),
1129 cm->mb_rows * cm->mb_cols));
1131 vpx_free(cpi->mb_norm_activity_map);
1132 CHECK_MEM_ERROR(cpi->mb_norm_activity_map,
1133 vpx_calloc(sizeof(unsigned int),
1134 cm->mb_rows * cm->mb_cols));
1136 #if CONFIG_MULTITHREAD
1138 cpi->mt_sync_range = 1;
1139 else if (width <= 1280)
1140 cpi->mt_sync_range = 4;
1141 else if (width <= 2560)
1142 cpi->mt_sync_range = 8;
1144 cpi->mt_sync_range = 16;
1147 vpx_free(cpi->tplist);
1149 CHECK_MEM_ERROR(cpi->tplist, vpx_malloc(sizeof(TOKENLIST) * cpi->common.mb_rows));
1154 static const int q_trans[] =
1156 0, 1, 2, 3, 4, 5, 7, 8,
1157 9, 10, 12, 13, 15, 17, 18, 19,
1158 20, 21, 23, 24, 25, 26, 27, 28,
1159 29, 30, 31, 33, 35, 37, 39, 41,
1160 43, 45, 47, 49, 51, 53, 55, 57,
1161 59, 61, 64, 67, 70, 73, 76, 79,
1162 82, 85, 88, 91, 94, 97, 100, 103,
1163 106, 109, 112, 115, 118, 121, 124, 127,
1166 int vp8_reverse_trans(int x)
1170 for (i = 0; i < 64; i++)
1171 if (q_trans[i] >= x)
1176 void vp8_new_frame_rate(VP8_COMP *cpi, double framerate)
1181 cpi->frame_rate = framerate;
1182 cpi->output_frame_rate = framerate;
1183 cpi->per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth /
1184 cpi->output_frame_rate);
1185 cpi->av_per_frame_bandwidth = cpi->per_frame_bandwidth;
1186 cpi->min_frame_bandwidth = (int)(cpi->av_per_frame_bandwidth *
1187 cpi->oxcf.two_pass_vbrmin_section / 100);
1189 // Set Maximum gf/arf interval
1190 cpi->max_gf_interval = ((int)(cpi->output_frame_rate / 2.0) + 2);
1192 if(cpi->max_gf_interval < 12)
1193 cpi->max_gf_interval = 12;
1195 // Extended interval for genuinely static scenes
1196 cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1198 // Special conditions when altr ref frame enabled in lagged compress mode
1199 if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames)
1201 if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1202 cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1204 if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1205 cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1208 if ( cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval )
1209 cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1214 rescale(int val, int num, int denom)
1216 int64_t llnum = num;
1217 int64_t llden = denom;
1218 int64_t llval = val;
1220 return llval * llnum / llden;
1224 static void init_config(VP8_COMP *cpi, VP8_CONFIG *oxcf)
1226 VP8_COMMON *cm = &cpi->common;
1231 cpi->auto_adjust_gold_quantizer = 1;
1234 cm->version = oxcf->Version;
1235 vp8_setup_version(cm);
1237 /* frame rate is not available on the first frame, as it's derived from
1238 * the observed timestamps. The actual value used here doesn't matter
1239 * too much, as it will adapt quickly. If the reciprocal of the timebase
1240 * seems like a reasonable framerate, then use that as a guess, otherwise
1243 cpi->frame_rate = (double)(oxcf->timebase.den) /
1244 (double)(oxcf->timebase.num);
1246 if (cpi->frame_rate > 180)
1247 cpi->frame_rate = 30;
1249 cpi->ref_frame_rate = cpi->frame_rate;
1251 // change includes all joint functionality
1252 vp8_change_config(cpi, oxcf);
1254 // Initialize active best and worst q and average q values.
1255 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1256 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1257 cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1259 // Initialise the starting buffer levels
1260 cpi->buffer_level = cpi->oxcf.starting_buffer_level;
1261 cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
1263 cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
1264 cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
1265 cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
1266 cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
1268 cpi->total_actual_bits = 0;
1269 cpi->total_target_vs_actual = 0;
1271 // Temporal scalabilty
1272 if (cpi->oxcf.number_of_layers > 1)
1275 double prev_layer_frame_rate=0;
1277 for (i=0; i<cpi->oxcf.number_of_layers; i++)
1279 LAYER_CONTEXT *lc = &cpi->layer_context[i];
1281 // Layer configuration
1283 cpi->output_frame_rate / cpi->oxcf.rate_decimator[i];
1284 lc->target_bandwidth = cpi->oxcf.target_bitrate[i] * 1000;
1286 lc->starting_buffer_level_in_ms = oxcf->starting_buffer_level;
1287 lc->optimal_buffer_level_in_ms = oxcf->optimal_buffer_level;
1288 lc->maximum_buffer_size_in_ms = oxcf->maximum_buffer_size;
1290 lc->starting_buffer_level =
1291 rescale(oxcf->starting_buffer_level,
1292 lc->target_bandwidth, 1000);
1294 if (oxcf->optimal_buffer_level == 0)
1295 lc->optimal_buffer_level = lc->target_bandwidth / 8;
1297 lc->optimal_buffer_level =
1298 rescale(oxcf->optimal_buffer_level,
1299 lc->target_bandwidth, 1000);
1301 if (oxcf->maximum_buffer_size == 0)
1302 lc->maximum_buffer_size = lc->target_bandwidth / 8;
1304 lc->maximum_buffer_size =
1305 rescale(oxcf->maximum_buffer_size,
1306 lc->target_bandwidth, 1000);
1308 // Work out the average size of a frame within this layer
1310 lc->avg_frame_size_for_layer = (cpi->oxcf.target_bitrate[i] -
1311 cpi->oxcf.target_bitrate[i-1]) * 1000 /
1312 (lc->frame_rate - prev_layer_frame_rate);
1314 lc->active_worst_quality = cpi->oxcf.worst_allowed_q;
1315 lc->active_best_quality = cpi->oxcf.best_allowed_q;
1316 lc->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1318 lc->buffer_level = lc->starting_buffer_level;
1319 lc->bits_off_target = lc->starting_buffer_level;
1321 lc->total_actual_bits = 0;
1325 lc->rate_correction_factor = 1.0;
1326 lc->key_frame_rate_correction_factor = 1.0;
1327 lc->gf_rate_correction_factor = 1.0;
1328 lc->inter_frame_target = 0.0;
1330 prev_layer_frame_rate = lc->frame_rate;
1334 #if VP8_TEMPORAL_ALT_REF
1338 cpi->fixed_divide[0] = 0;
1340 for (i = 1; i < 512; i++)
1341 cpi->fixed_divide[i] = 0x80000 / i;
1346 void update_layer_contexts (VP8_COMP *cpi)
1348 VP8_CONFIG *oxcf = &cpi->oxcf;
1350 /* Update snapshots of the layer contexts to reflect new parameters */
1351 if (oxcf->number_of_layers > 1)
1354 double prev_layer_frame_rate=0;
1356 for (i=0; i<oxcf->number_of_layers; i++)
1358 LAYER_CONTEXT *lc = &cpi->layer_context[i];
1361 cpi->ref_frame_rate / oxcf->rate_decimator[i];
1362 lc->target_bandwidth = oxcf->target_bitrate[i] * 1000;
1364 lc->starting_buffer_level = rescale(
1365 oxcf->starting_buffer_level_in_ms,
1366 lc->target_bandwidth, 1000);
1368 if (oxcf->optimal_buffer_level == 0)
1369 lc->optimal_buffer_level = lc->target_bandwidth / 8;
1371 lc->optimal_buffer_level = rescale(
1372 oxcf->optimal_buffer_level_in_ms,
1373 lc->target_bandwidth, 1000);
1375 if (oxcf->maximum_buffer_size == 0)
1376 lc->maximum_buffer_size = lc->target_bandwidth / 8;
1378 lc->maximum_buffer_size = rescale(
1379 oxcf->maximum_buffer_size_in_ms,
1380 lc->target_bandwidth, 1000);
1382 // Work out the average size of a frame within this layer
1384 lc->avg_frame_size_for_layer = (oxcf->target_bitrate[i] -
1385 oxcf->target_bitrate[i-1]) * 1000 /
1386 (lc->frame_rate - prev_layer_frame_rate);
1388 lc->active_worst_quality = oxcf->worst_allowed_q;
1389 lc->active_best_quality = oxcf->best_allowed_q;
1390 lc->avg_frame_qindex = oxcf->worst_allowed_q;
1392 prev_layer_frame_rate = lc->frame_rate;
1397 void vp8_change_config(VP8_COMP *cpi, VP8_CONFIG *oxcf)
1399 VP8_COMMON *cm = &cpi->common;
1408 if (cm->version != oxcf->Version)
1410 cm->version = oxcf->Version;
1411 vp8_setup_version(cm);
1416 switch (cpi->oxcf.Mode)
1421 cpi->compressor_speed = 2;
1423 if (cpi->oxcf.cpu_used < -16)
1425 cpi->oxcf.cpu_used = -16;
1428 if (cpi->oxcf.cpu_used > 16)
1429 cpi->oxcf.cpu_used = 16;
1433 case MODE_GOODQUALITY:
1435 cpi->compressor_speed = 1;
1437 if (cpi->oxcf.cpu_used < -5)
1439 cpi->oxcf.cpu_used = -5;
1442 if (cpi->oxcf.cpu_used > 5)
1443 cpi->oxcf.cpu_used = 5;
1447 case MODE_BESTQUALITY:
1449 cpi->compressor_speed = 0;
1452 case MODE_FIRSTPASS:
1454 cpi->compressor_speed = 1;
1456 case MODE_SECONDPASS:
1458 cpi->compressor_speed = 1;
1460 if (cpi->oxcf.cpu_used < -5)
1462 cpi->oxcf.cpu_used = -5;
1465 if (cpi->oxcf.cpu_used > 5)
1466 cpi->oxcf.cpu_used = 5;
1469 case MODE_SECONDPASS_BEST:
1471 cpi->compressor_speed = 0;
1476 cpi->auto_worst_q = 1;
1478 cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1479 cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1480 cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1482 if (oxcf->fixed_q >= 0)
1484 if (oxcf->worst_allowed_q < 0)
1485 cpi->oxcf.fixed_q = q_trans[0];
1487 cpi->oxcf.fixed_q = q_trans[oxcf->worst_allowed_q];
1489 if (oxcf->alt_q < 0)
1490 cpi->oxcf.alt_q = q_trans[0];
1492 cpi->oxcf.alt_q = q_trans[oxcf->alt_q];
1494 if (oxcf->key_q < 0)
1495 cpi->oxcf.key_q = q_trans[0];
1497 cpi->oxcf.key_q = q_trans[oxcf->key_q];
1499 if (oxcf->gold_q < 0)
1500 cpi->oxcf.gold_q = q_trans[0];
1502 cpi->oxcf.gold_q = q_trans[oxcf->gold_q];
1506 cpi->baseline_gf_interval =
1507 cpi->oxcf.alt_freq ? cpi->oxcf.alt_freq : DEFAULT_GF_INTERVAL;
1509 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
1511 //cpi->use_golden_frame_only = 0;
1512 //cpi->use_last_frame_only = 0;
1513 cm->refresh_golden_frame = 0;
1514 cm->refresh_last_frame = 1;
1515 cm->refresh_entropy_probs = 1;
1517 if (cpi->oxcf.token_partitions >= 0 && cpi->oxcf.token_partitions <= 3)
1518 cm->multi_token_partition =
1519 (TOKEN_PARTITION) cpi->oxcf.token_partitions;
1521 setup_features(cpi);
1526 for (i = 0; i < MAX_MB_SEGMENTS; i++)
1527 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1530 // At the moment the first order values may not be > MAXQ
1531 if (cpi->oxcf.fixed_q > MAXQ)
1532 cpi->oxcf.fixed_q = MAXQ;
1534 // local file playback mode == really big buffer
1535 if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK)
1537 cpi->oxcf.starting_buffer_level = 60000;
1538 cpi->oxcf.optimal_buffer_level = 60000;
1539 cpi->oxcf.maximum_buffer_size = 240000;
1540 cpi->oxcf.starting_buffer_level_in_ms = 60000;
1541 cpi->oxcf.optimal_buffer_level_in_ms = 60000;
1542 cpi->oxcf.maximum_buffer_size_in_ms = 240000;
1545 // Convert target bandwidth from Kbit/s to Bit/s
1546 cpi->oxcf.target_bandwidth *= 1000;
1548 cpi->oxcf.starting_buffer_level =
1549 rescale(cpi->oxcf.starting_buffer_level,
1550 cpi->oxcf.target_bandwidth, 1000);
1552 // Set or reset optimal and maximum buffer levels.
1553 if (cpi->oxcf.optimal_buffer_level == 0)
1554 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1556 cpi->oxcf.optimal_buffer_level =
1557 rescale(cpi->oxcf.optimal_buffer_level,
1558 cpi->oxcf.target_bandwidth, 1000);
1560 if (cpi->oxcf.maximum_buffer_size == 0)
1561 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1563 cpi->oxcf.maximum_buffer_size =
1564 rescale(cpi->oxcf.maximum_buffer_size,
1565 cpi->oxcf.target_bandwidth, 1000);
1567 // Set up frame rate and related parameters rate control values.
1568 vp8_new_frame_rate(cpi, cpi->frame_rate);
1570 // Set absolute upper and lower quality limits
1571 cpi->worst_quality = cpi->oxcf.worst_allowed_q;
1572 cpi->best_quality = cpi->oxcf.best_allowed_q;
1574 // active values should only be modified if out of new range
1575 if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q)
1577 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1580 else if (cpi->active_worst_quality < cpi->oxcf.best_allowed_q)
1582 cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
1584 if (cpi->active_best_quality < cpi->oxcf.best_allowed_q)
1586 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1589 else if (cpi->active_best_quality > cpi->oxcf.worst_allowed_q)
1591 cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
1594 cpi->buffered_mode = cpi->oxcf.optimal_buffer_level > 0;
1596 cpi->cq_target_quality = cpi->oxcf.cq_level;
1598 // Only allow dropped frames in buffered mode
1599 cpi->drop_frames_allowed = cpi->oxcf.allow_df && cpi->buffered_mode;
1601 if (!cm->use_bilinear_mc_filter)
1602 cm->mcomp_filter_type = SIXTAP;
1604 cm->mcomp_filter_type = BILINEAR;
1606 cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1610 last_h = cm->Height;
1612 cm->Width = cpi->oxcf.Width;
1613 cm->Height = cpi->oxcf.Height;
1615 cm->horiz_scale = cpi->horiz_scale;
1616 cm->vert_scale = cpi->vert_scale;
1618 // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1619 if (cpi->oxcf.Sharpness > 7)
1620 cpi->oxcf.Sharpness = 7;
1622 cm->sharpness_level = cpi->oxcf.Sharpness;
1624 if (cm->horiz_scale != NORMAL || cm->vert_scale != NORMAL)
1626 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
1627 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
1629 Scale2Ratio(cm->horiz_scale, &hr, &hs);
1630 Scale2Ratio(cm->vert_scale, &vr, &vs);
1632 // always go to the next whole number
1633 cm->Width = (hs - 1 + cpi->oxcf.Width * hr) / hs;
1634 cm->Height = (vs - 1 + cpi->oxcf.Height * vr) / vs;
1637 if (last_w != cm->Width || last_h != cm->Height)
1638 cpi->force_next_frame_intra = 1;
1640 if (((cm->Width + 15) & 0xfffffff0) !=
1641 cm->yv12_fb[cm->lst_fb_idx].y_width ||
1642 ((cm->Height + 15) & 0xfffffff0) !=
1643 cm->yv12_fb[cm->lst_fb_idx].y_height ||
1644 cm->yv12_fb[cm->lst_fb_idx].y_width == 0)
1646 alloc_raw_frame_buffers(cpi);
1647 vp8_alloc_compressor_data(cpi);
1650 if (cpi->oxcf.fixed_q >= 0)
1652 cpi->last_q[0] = cpi->oxcf.fixed_q;
1653 cpi->last_q[1] = cpi->oxcf.fixed_q;
1656 cpi->Speed = cpi->oxcf.cpu_used;
1658 // force to allowlag to 0 if lag_in_frames is 0;
1659 if (cpi->oxcf.lag_in_frames == 0)
1661 cpi->oxcf.allow_lag = 0;
1663 // Limit on lag buffers as these are not currently dynamically allocated
1664 else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS)
1665 cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1668 cpi->alt_ref_source = NULL;
1669 cpi->is_src_frame_alt_ref = 0;
1673 // Experimental RD Code
1674 cpi->frame_distortion = 0;
1675 cpi->last_frame_distortion = 0;
1680 #define M_LOG2_E 0.693147180559945309417
1681 #define log2f(x) (log (x) / (float) M_LOG2_E)
1682 static void cal_mvsadcosts(int *mvsadcost[2])
1686 mvsadcost [0] [0] = 300;
1687 mvsadcost [1] [0] = 300;
1691 double z = 256 * (2 * (log2f(8 * i) + .6));
1692 mvsadcost [0][i] = (int) z;
1693 mvsadcost [1][i] = (int) z;
1694 mvsadcost [0][-i] = (int) z;
1695 mvsadcost [1][-i] = (int) z;
1697 while (++i <= mvfp_max);
1700 struct VP8_COMP* vp8_create_compressor(VP8_CONFIG *oxcf)
1707 cpi = vpx_memalign(32, sizeof(VP8_COMP));
1708 // Check that the CPI instance is valid
1714 vpx_memset(cpi, 0, sizeof(VP8_COMP));
1716 if (setjmp(cm->error.jmp))
1718 cpi->common.error.setjmp = 0;
1719 vp8_remove_compressor(&cpi);
1723 cpi->common.error.setjmp = 1;
1725 CHECK_MEM_ERROR(cpi->mb.ss, vpx_calloc(sizeof(search_site), (MAX_MVSEARCH_STEPS * 8) + 1));
1727 vp8_create_common(&cpi->common);
1729 init_config(cpi, oxcf);
1731 memcpy(cpi->base_skip_false_prob, vp8cx_base_skip_false_prob, sizeof(vp8cx_base_skip_false_prob));
1732 cpi->common.current_video_frame = 0;
1733 cpi->kf_overspend_bits = 0;
1734 cpi->kf_bitrate_adjustment = 0;
1735 cpi->frames_till_gf_update_due = 0;
1736 cpi->gf_overspend_bits = 0;
1737 cpi->non_gf_bitrate_adjustment = 0;
1738 cpi->prob_last_coded = 128;
1739 cpi->prob_gf_coded = 128;
1740 cpi->prob_intra_coded = 63;
1742 // Prime the recent reference frame usage counters.
1743 // Hereafter they will be maintained as a sort of moving average
1744 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
1745 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
1746 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
1747 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
1749 // Set reference frame sign bias for ALTREF frame to 1 (for now)
1750 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
1752 cpi->twopass.gf_decay_rate = 0;
1753 cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1755 cpi->gold_is_last = 0 ;
1756 cpi->alt_is_last = 0 ;
1757 cpi->gold_is_alt = 0 ;
1759 // allocate memory for storing last frame's MVs for MV prediction.
1760 CHECK_MEM_ERROR(cpi->lfmv, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int_mv)));
1761 CHECK_MEM_ERROR(cpi->lf_ref_frame_sign_bias, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1762 CHECK_MEM_ERROR(cpi->lf_ref_frame, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1764 // Create the encoder segmentation map and set all entries to 0
1765 CHECK_MEM_ERROR(cpi->segmentation_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1766 CHECK_MEM_ERROR(cpi->active_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1767 vpx_memset(cpi->active_map , 1, (cpi->common.mb_rows * cpi->common.mb_cols));
1768 cpi->active_map_enabled = 0;
1771 // Experimental code for lagged and one pass
1772 // Initialise one_pass GF frames stats
1773 // Update stats used for GF selection
1776 cpi->one_pass_frame_index = 0;
1778 for (i = 0; i < MAX_LAG_BUFFERS; i++)
1780 cpi->one_pass_frame_stats[i].frames_so_far = 0;
1781 cpi->one_pass_frame_stats[i].frame_intra_error = 0.0;
1782 cpi->one_pass_frame_stats[i].frame_coded_error = 0.0;
1783 cpi->one_pass_frame_stats[i].frame_pcnt_inter = 0.0;
1784 cpi->one_pass_frame_stats[i].frame_pcnt_motion = 0.0;
1785 cpi->one_pass_frame_stats[i].frame_mvr = 0.0;
1786 cpi->one_pass_frame_stats[i].frame_mvr_abs = 0.0;
1787 cpi->one_pass_frame_stats[i].frame_mvc = 0.0;
1788 cpi->one_pass_frame_stats[i].frame_mvc_abs = 0.0;
1793 // Should we use the cyclic refresh method.
1794 // Currently this is tied to error resilliant mode
1795 cpi->cyclic_refresh_mode_enabled = cpi->oxcf.error_resilient_mode;
1796 cpi->cyclic_refresh_mode_max_mbs_perframe = (cpi->common.mb_rows * cpi->common.mb_cols) / 40;
1797 cpi->cyclic_refresh_mode_index = 0;
1798 cpi->cyclic_refresh_q = 32;
1800 if (cpi->cyclic_refresh_mode_enabled)
1802 CHECK_MEM_ERROR(cpi->cyclic_refresh_map, vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
1805 cpi->cyclic_refresh_map = (signed char *) NULL;
1807 // Test function for segmentation
1808 //segmentation_test_function( cpi);
1810 #ifdef ENTROPY_STATS
1811 init_context_counters();
1814 /*Initialize the feed-forward activity masking.*/
1815 cpi->activity_avg = 90<<12;
1817 cpi->frames_since_key = 8; // Give a sensible default for the first frame.
1818 cpi->key_frame_frequency = cpi->oxcf.key_freq;
1819 cpi->this_key_frame_forced = 0;
1820 cpi->next_key_frame_forced = 0;
1822 cpi->source_alt_ref_pending = 0;
1823 cpi->source_alt_ref_active = 0;
1824 cpi->common.refresh_alt_ref_frame = 0;
1826 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1827 #if CONFIG_INTERNAL_STATS
1828 cpi->b_calculate_ssimg = 0;
1833 if (cpi->b_calculate_psnr)
1835 cpi->total_sq_error = 0.0;
1836 cpi->total_sq_error2 = 0.0;
1841 cpi->totalp_y = 0.0;
1842 cpi->totalp_u = 0.0;
1843 cpi->totalp_v = 0.0;
1845 cpi->tot_recode_hits = 0;
1846 cpi->summed_quality = 0;
1847 cpi->summed_weights = 0;
1850 if (cpi->b_calculate_ssimg)
1852 cpi->total_ssimg_y = 0;
1853 cpi->total_ssimg_u = 0;
1854 cpi->total_ssimg_v = 0;
1855 cpi->total_ssimg_all = 0;
1861 #define LLONG_MAX 9223372036854775807LL
1863 cpi->first_time_stamp_ever = LLONG_MAX;
1865 cpi->frames_till_gf_update_due = 0;
1866 cpi->key_frame_count = 1;
1868 cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
1871 cpi->total_byte_count = 0;
1873 cpi->drop_frame = 0;
1874 cpi->drop_count = 0;
1875 cpi->max_drop_count = 0;
1876 cpi->max_consec_dropped_frames = 4;
1878 cpi->rate_correction_factor = 1.0;
1879 cpi->key_frame_rate_correction_factor = 1.0;
1880 cpi->gf_rate_correction_factor = 1.0;
1881 cpi->twopass.est_max_qcorrection_factor = 1.0;
1883 cpi->mb.mvcost[0] = &cpi->mb.mvcosts[0][mv_max+1];
1884 cpi->mb.mvcost[1] = &cpi->mb.mvcosts[1][mv_max+1];
1885 cpi->mb.mvsadcost[0] = &cpi->mb.mvsadcosts[0][mvfp_max+1];
1886 cpi->mb.mvsadcost[1] = &cpi->mb.mvsadcosts[1][mvfp_max+1];
1888 cal_mvsadcosts(cpi->mb.mvsadcost);
1890 for (i = 0; i < KEY_FRAME_CONTEXT; i++)
1892 cpi->prior_key_frame_distance[i] = (int)cpi->output_frame_rate;
1895 #ifdef OUTPUT_YUV_SRC
1896 yuv_file = fopen("bd.yuv", "ab");
1900 framepsnr = fopen("framepsnr.stt", "a");
1901 kf_list = fopen("kf_list.stt", "w");
1904 cpi->output_pkt_list = oxcf->output_pkt_list;
1906 #if !(CONFIG_REALTIME_ONLY)
1910 vp8_init_first_pass(cpi);
1912 else if (cpi->pass == 2)
1914 size_t packet_sz = sizeof(FIRSTPASS_STATS);
1915 int packets = oxcf->two_pass_stats_in.sz / packet_sz;
1917 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1918 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1919 cpi->twopass.stats_in_end = (void*)((char *)cpi->twopass.stats_in
1920 + (packets - 1) * packet_sz);
1921 vp8_init_second_pass(cpi);
1926 if (cpi->compressor_speed == 2)
1928 cpi->cpu_freq = 0; //vp8_get_processor_freq();
1929 cpi->avg_encode_time = 0;
1930 cpi->avg_pick_mode_time = 0;
1933 vp8_set_speed_features(cpi);
1935 // Set starting values of RD threshold multipliers (128 = *1)
1936 for (i = 0; i < MAX_MODES; i++)
1938 cpi->rd_thresh_mult[i] = 128;
1941 #ifdef ENTROPY_STATS
1942 init_mv_ref_counts();
1945 #if CONFIG_MULTITHREAD
1946 vp8cx_create_encoder_threads(cpi);
1949 cpi->fn_ptr[BLOCK_16X16].sdf = vp8_sad16x16;
1950 cpi->fn_ptr[BLOCK_16X16].vf = vp8_variance16x16;
1951 cpi->fn_ptr[BLOCK_16X16].svf = vp8_sub_pixel_variance16x16;
1952 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_h = vp8_variance_halfpixvar16x16_h;
1953 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_v = vp8_variance_halfpixvar16x16_v;
1954 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_hv = vp8_variance_halfpixvar16x16_hv;
1955 cpi->fn_ptr[BLOCK_16X16].sdx3f = vp8_sad16x16x3;
1956 cpi->fn_ptr[BLOCK_16X16].sdx8f = vp8_sad16x16x8;
1957 cpi->fn_ptr[BLOCK_16X16].sdx4df = vp8_sad16x16x4d;
1959 cpi->fn_ptr[BLOCK_16X8].sdf = vp8_sad16x8;
1960 cpi->fn_ptr[BLOCK_16X8].vf = vp8_variance16x8;
1961 cpi->fn_ptr[BLOCK_16X8].svf = vp8_sub_pixel_variance16x8;
1962 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_h = NULL;
1963 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_v = NULL;
1964 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_hv = NULL;
1965 cpi->fn_ptr[BLOCK_16X8].sdx3f = vp8_sad16x8x3;
1966 cpi->fn_ptr[BLOCK_16X8].sdx8f = vp8_sad16x8x8;
1967 cpi->fn_ptr[BLOCK_16X8].sdx4df = vp8_sad16x8x4d;
1969 cpi->fn_ptr[BLOCK_8X16].sdf = vp8_sad8x16;
1970 cpi->fn_ptr[BLOCK_8X16].vf = vp8_variance8x16;
1971 cpi->fn_ptr[BLOCK_8X16].svf = vp8_sub_pixel_variance8x16;
1972 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_h = NULL;
1973 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_v = NULL;
1974 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_hv = NULL;
1975 cpi->fn_ptr[BLOCK_8X16].sdx3f = vp8_sad8x16x3;
1976 cpi->fn_ptr[BLOCK_8X16].sdx8f = vp8_sad8x16x8;
1977 cpi->fn_ptr[BLOCK_8X16].sdx4df = vp8_sad8x16x4d;
1979 cpi->fn_ptr[BLOCK_8X8].sdf = vp8_sad8x8;
1980 cpi->fn_ptr[BLOCK_8X8].vf = vp8_variance8x8;
1981 cpi->fn_ptr[BLOCK_8X8].svf = vp8_sub_pixel_variance8x8;
1982 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_h = NULL;
1983 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_v = NULL;
1984 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_hv = NULL;
1985 cpi->fn_ptr[BLOCK_8X8].sdx3f = vp8_sad8x8x3;
1986 cpi->fn_ptr[BLOCK_8X8].sdx8f = vp8_sad8x8x8;
1987 cpi->fn_ptr[BLOCK_8X8].sdx4df = vp8_sad8x8x4d;
1989 cpi->fn_ptr[BLOCK_4X4].sdf = vp8_sad4x4;
1990 cpi->fn_ptr[BLOCK_4X4].vf = vp8_variance4x4;
1991 cpi->fn_ptr[BLOCK_4X4].svf = vp8_sub_pixel_variance4x4;
1992 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_h = NULL;
1993 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_v = NULL;
1994 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_hv = NULL;
1995 cpi->fn_ptr[BLOCK_4X4].sdx3f = vp8_sad4x4x3;
1996 cpi->fn_ptr[BLOCK_4X4].sdx8f = vp8_sad4x4x8;
1997 cpi->fn_ptr[BLOCK_4X4].sdx4df = vp8_sad4x4x4d;
1999 #if ARCH_X86 || ARCH_X86_64
2000 cpi->fn_ptr[BLOCK_16X16].copymem = vp8_copy32xn;
2001 cpi->fn_ptr[BLOCK_16X8].copymem = vp8_copy32xn;
2002 cpi->fn_ptr[BLOCK_8X16].copymem = vp8_copy32xn;
2003 cpi->fn_ptr[BLOCK_8X8].copymem = vp8_copy32xn;
2004 cpi->fn_ptr[BLOCK_4X4].copymem = vp8_copy32xn;
2007 cpi->full_search_sad = vp8_full_search_sad;
2008 cpi->diamond_search_sad = vp8_diamond_search_sad;
2009 cpi->refining_search_sad = vp8_refining_search_sad;
2011 // make sure frame 1 is okay
2012 cpi->error_bins[0] = cpi->common.MBs;
2014 //vp8cx_init_quantizer() is first called here. Add check in vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only called later
2015 //when needed. This will avoid unnecessary calls of vp8cx_init_quantizer() for every frame.
2016 vp8cx_init_quantizer(cpi);
2018 vp8_loop_filter_init(cm);
2020 cpi->common.error.setjmp = 0;
2022 #if CONFIG_MULTI_RES_ENCODING
2023 /* Calculate # of MBs in a row in lower-resolution level image. */
2024 if (cpi->oxcf.mr_encoder_id > 0)
2025 vp8_cal_low_res_mb_cols(cpi);
2033 void vp8_remove_compressor(VP8_COMP **ptr)
2035 VP8_COMP *cpi = *ptr;
2040 if (cpi && (cpi->common.current_video_frame > 0))
2042 #if !(CONFIG_REALTIME_ONLY)
2046 vp8_end_second_pass(cpi);
2051 #ifdef ENTROPY_STATS
2052 print_context_counters();
2053 print_tree_update_probs();
2054 print_mode_context();
2057 #if CONFIG_INTERNAL_STATS
2061 FILE *f = fopen("opsnr.stt", "a");
2062 double time_encoded = (cpi->last_end_time_stamp_seen
2063 - cpi->first_time_stamp_ever) / 10000000.000;
2064 double total_encode_time = (cpi->time_receive_data +
2065 cpi->time_compress_data) / 1000.000;
2066 double dr = (double)cpi->bytes * 8.0 / 1000.0 / time_encoded;
2068 if (cpi->b_calculate_psnr)
2070 YV12_BUFFER_CONFIG *lst_yv12 =
2071 &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
2073 if (cpi->oxcf.number_of_layers > 1)
2077 fprintf(f, "Layer\tBitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2078 "GLPsnrP\tVPXSSIM\t\n");
2079 for (i=0; i<cpi->oxcf.number_of_layers; i++)
2081 double dr = (double)cpi->bytes_in_layer[i] *
2082 8.0 / 1000.0 / time_encoded;
2083 double samples = 3.0 / 2 * cpi->frames_in_layer[i] *
2084 lst_yv12->y_width * lst_yv12->y_height;
2085 double total_psnr = vp8_mse2psnr(samples, 255.0,
2086 cpi->total_error2[i]);
2087 double total_psnr2 = vp8_mse2psnr(samples, 255.0,
2088 cpi->total_error2_p[i]);
2089 double total_ssim = 100 * pow(cpi->sum_ssim[i] /
2090 cpi->sum_weights[i], 8.0);
2092 fprintf(f, "%5d\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2095 cpi->sum_psnr[i] / cpi->frames_in_layer[i],
2097 cpi->sum_psnr_p[i] / cpi->frames_in_layer[i],
2098 total_psnr2, total_ssim);
2103 double samples = 3.0 / 2 * cpi->count *
2104 lst_yv12->y_width * lst_yv12->y_height;
2105 double total_psnr = vp8_mse2psnr(samples, 255.0,
2106 cpi->total_sq_error);
2107 double total_psnr2 = vp8_mse2psnr(samples, 255.0,
2108 cpi->total_sq_error2);
2109 double total_ssim = 100 * pow(cpi->summed_quality /
2110 cpi->summed_weights, 8.0);
2112 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2113 "GLPsnrP\tVPXSSIM\t Time(us)\n");
2114 fprintf(f, "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2116 dr, cpi->total / cpi->count, total_psnr,
2117 cpi->totalp / cpi->count, total_psnr2,
2118 total_ssim, total_encode_time);
2122 if (cpi->b_calculate_ssimg)
2124 if (cpi->oxcf.number_of_layers > 1)
2128 fprintf(f, "Layer\tBitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t"
2130 for (i=0; i<cpi->oxcf.number_of_layers; i++)
2132 double dr = (double)cpi->bytes_in_layer[i] *
2133 8.0 / 1000.0 / time_encoded;
2134 fprintf(f, "%5d\t%7.3f\t%6.4f\t"
2135 "%6.4f\t%6.4f\t%6.4f\t%8.0f\n",
2137 cpi->total_ssimg_y_in_layer[i] /
2138 cpi->frames_in_layer[i],
2139 cpi->total_ssimg_u_in_layer[i] /
2140 cpi->frames_in_layer[i],
2141 cpi->total_ssimg_v_in_layer[i] /
2142 cpi->frames_in_layer[i],
2143 cpi->total_ssimg_all_in_layer[i] /
2144 cpi->frames_in_layer[i],
2150 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t"
2152 fprintf(f, "%7.3f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
2153 cpi->total_ssimg_y / cpi->count,
2154 cpi->total_ssimg_u / cpi->count,
2155 cpi->total_ssimg_v / cpi->count,
2156 cpi->total_ssimg_all / cpi->count, total_encode_time);
2162 f = fopen("qskip.stt", "a");
2163 fprintf(f, "minq:%d -maxq:%d skiptrue:skipfalse = %d:%d\n", cpi->oxcf.best_allowed_q, cpi->oxcf.worst_allowed_q, skiptruecount, skipfalsecount);
2174 if (cpi->compressor_speed == 2)
2177 FILE *f = fopen("cxspeed.stt", "a");
2178 cnt_pm /= cpi->common.MBs;
2180 for (i = 0; i < 16; i++)
2181 fprintf(f, "%5d", frames_at_speed[i]);
2184 //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);
2193 extern int count_mb_seg[4];
2194 FILE *f = fopen("modes.stt", "a");
2195 double dr = (double)cpi->frame_rate * (double)bytes * (double)8 / (double)count / (double)1000 ;
2196 fprintf(f, "intra_mode in Intra Frames:\n");
2197 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d\n", y_modes[0], y_modes[1], y_modes[2], y_modes[3], y_modes[4]);
2198 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", uv_modes[0], uv_modes[1], uv_modes[2], uv_modes[3]);
2203 for (i = 0; i < 10; i++)
2204 fprintf(f, "%8d, ", b_modes[i]);
2210 fprintf(f, "Modes in Inter Frames:\n");
2211 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d\n",
2212 inter_y_modes[0], inter_y_modes[1], inter_y_modes[2], inter_y_modes[3], inter_y_modes[4],
2213 inter_y_modes[5], inter_y_modes[6], inter_y_modes[7], inter_y_modes[8], inter_y_modes[9]);
2214 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", inter_uv_modes[0], inter_uv_modes[1], inter_uv_modes[2], inter_uv_modes[3]);
2219 for (i = 0; i < 15; i++)
2220 fprintf(f, "%8d, ", inter_b_modes[i]);
2225 fprintf(f, "P:%8d, %8d, %8d, %8d\n", count_mb_seg[0], count_mb_seg[1], count_mb_seg[2], count_mb_seg[3]);
2226 fprintf(f, "PB:%8d, %8d, %8d, %8d\n", inter_b_modes[LEFT4X4], inter_b_modes[ABOVE4X4], inter_b_modes[ZERO4X4], inter_b_modes[NEW4X4]);
2234 #ifdef ENTROPY_STATS
2237 FILE *fmode = fopen("modecontext.c", "w");
2239 fprintf(fmode, "\n#include \"entropymode.h\"\n\n");
2240 fprintf(fmode, "const unsigned int vp8_kf_default_bmode_counts ");
2241 fprintf(fmode, "[VP8_BINTRAMODES] [VP8_BINTRAMODES] [VP8_BINTRAMODES] =\n{\n");
2243 for (i = 0; i < 10; i++)
2246 fprintf(fmode, " { //Above Mode : %d\n", i);
2248 for (j = 0; j < 10; j++)
2251 fprintf(fmode, " {");
2253 for (k = 0; k < 10; k++)
2255 if (!intra_mode_stats[i][j][k])
2256 fprintf(fmode, " %5d, ", 1);
2258 fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
2261 fprintf(fmode, "}, // left_mode %d\n", j);
2265 fprintf(fmode, " },\n");
2269 fprintf(fmode, "};\n");
2275 #if defined(SECTIONBITS_OUTPUT)
2280 FILE *f = fopen("tokenbits.stt", "a");
2282 for (i = 0; i < 28; i++)
2283 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
2293 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2294 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
2295 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);
2301 #if CONFIG_MULTITHREAD
2302 vp8cx_remove_encoder_threads(cpi);
2305 dealloc_compressor_data(cpi);
2306 vpx_free(cpi->mb.ss);
2308 vpx_free(cpi->cyclic_refresh_map);
2310 vp8_remove_common(&cpi->common);
2314 #ifdef OUTPUT_YUV_SRC
2334 static uint64_t calc_plane_error(unsigned char *orig, int orig_stride,
2335 unsigned char *recon, int recon_stride,
2336 unsigned int cols, unsigned int rows)
2338 unsigned int row, col;
2339 uint64_t total_sse = 0;
2342 for (row = 0; row + 16 <= rows; row += 16)
2344 for (col = 0; col + 16 <= cols; col += 16)
2348 vp8_mse16x16(orig + col, orig_stride,
2349 recon + col, recon_stride,
2354 /* Handle odd-sized width */
2357 unsigned int border_row, border_col;
2358 unsigned char *border_orig = orig;
2359 unsigned char *border_recon = recon;
2361 for (border_row = 0; border_row < 16; border_row++)
2363 for (border_col = col; border_col < cols; border_col++)
2365 diff = border_orig[border_col] - border_recon[border_col];
2366 total_sse += diff * diff;
2369 border_orig += orig_stride;
2370 border_recon += recon_stride;
2374 orig += orig_stride * 16;
2375 recon += recon_stride * 16;
2378 /* Handle odd-sized height */
2379 for (; row < rows; row++)
2381 for (col = 0; col < cols; col++)
2383 diff = orig[col] - recon[col];
2384 total_sse += diff * diff;
2387 orig += orig_stride;
2388 recon += recon_stride;
2391 vp8_clear_system_state();
2396 static void generate_psnr_packet(VP8_COMP *cpi)
2398 YV12_BUFFER_CONFIG *orig = cpi->Source;
2399 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2400 struct vpx_codec_cx_pkt pkt;
2403 unsigned int width = cpi->common.Width;
2404 unsigned int height = cpi->common.Height;
2406 pkt.kind = VPX_CODEC_PSNR_PKT;
2407 sse = calc_plane_error(orig->y_buffer, orig->y_stride,
2408 recon->y_buffer, recon->y_stride,
2410 pkt.data.psnr.sse[0] = sse;
2411 pkt.data.psnr.sse[1] = sse;
2412 pkt.data.psnr.samples[0] = width * height;
2413 pkt.data.psnr.samples[1] = width * height;
2415 width = (width + 1) / 2;
2416 height = (height + 1) / 2;
2418 sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
2419 recon->u_buffer, recon->uv_stride,
2421 pkt.data.psnr.sse[0] += sse;
2422 pkt.data.psnr.sse[2] = sse;
2423 pkt.data.psnr.samples[0] += width * height;
2424 pkt.data.psnr.samples[2] = width * height;
2426 sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2427 recon->v_buffer, recon->uv_stride,
2429 pkt.data.psnr.sse[0] += sse;
2430 pkt.data.psnr.sse[3] = sse;
2431 pkt.data.psnr.samples[0] += width * height;
2432 pkt.data.psnr.samples[3] = width * height;
2434 for (i = 0; i < 4; i++)
2435 pkt.data.psnr.psnr[i] = vp8_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2436 pkt.data.psnr.sse[i]);
2438 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2442 int vp8_use_as_reference(VP8_COMP *cpi, int ref_frame_flags)
2444 if (ref_frame_flags > 7)
2447 cpi->ref_frame_flags = ref_frame_flags;
2450 int vp8_update_reference(VP8_COMP *cpi, int ref_frame_flags)
2452 if (ref_frame_flags > 7)
2455 cpi->common.refresh_golden_frame = 0;
2456 cpi->common.refresh_alt_ref_frame = 0;
2457 cpi->common.refresh_last_frame = 0;
2459 if (ref_frame_flags & VP8_LAST_FLAG)
2460 cpi->common.refresh_last_frame = 1;
2462 if (ref_frame_flags & VP8_GOLD_FLAG)
2463 cpi->common.refresh_golden_frame = 1;
2465 if (ref_frame_flags & VP8_ALT_FLAG)
2466 cpi->common.refresh_alt_ref_frame = 1;
2471 int vp8_get_reference(VP8_COMP *cpi, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2473 VP8_COMMON *cm = &cpi->common;
2476 if (ref_frame_flag == VP8_LAST_FLAG)
2477 ref_fb_idx = cm->lst_fb_idx;
2478 else if (ref_frame_flag == VP8_GOLD_FLAG)
2479 ref_fb_idx = cm->gld_fb_idx;
2480 else if (ref_frame_flag == VP8_ALT_FLAG)
2481 ref_fb_idx = cm->alt_fb_idx;
2485 vp8_yv12_copy_frame_ptr(&cm->yv12_fb[ref_fb_idx], sd);
2489 int vp8_set_reference(VP8_COMP *cpi, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2491 VP8_COMMON *cm = &cpi->common;
2495 if (ref_frame_flag == VP8_LAST_FLAG)
2496 ref_fb_idx = cm->lst_fb_idx;
2497 else if (ref_frame_flag == VP8_GOLD_FLAG)
2498 ref_fb_idx = cm->gld_fb_idx;
2499 else if (ref_frame_flag == VP8_ALT_FLAG)
2500 ref_fb_idx = cm->alt_fb_idx;
2504 vp8_yv12_copy_frame_ptr(sd, &cm->yv12_fb[ref_fb_idx]);
2508 int vp8_update_entropy(VP8_COMP *cpi, int update)
2510 VP8_COMMON *cm = &cpi->common;
2511 cm->refresh_entropy_probs = update;
2518 void vp8_write_yuv_frame(const char *name, YV12_BUFFER_CONFIG *s)
2520 FILE *yuv_file = fopen(name, "ab");
2521 unsigned char *src = s->y_buffer;
2522 int h = s->y_height;
2526 fwrite(src, s->y_width, 1, yuv_file);
2536 fwrite(src, s->uv_width, 1, yuv_file);
2537 src += s->uv_stride;
2546 fwrite(src, s->uv_width, 1, yuv_file);
2547 src += s->uv_stride;
2556 static void scale_and_extend_source(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi)
2558 VP8_COMMON *cm = &cpi->common;
2560 // are we resizing the image
2561 if (cm->horiz_scale != 0 || cm->vert_scale != 0)
2563 #if CONFIG_SPATIAL_RESAMPLING
2564 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2565 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2568 if (cm->vert_scale == 3)
2573 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2574 Scale2Ratio(cm->vert_scale, &vr, &vs);
2576 vp8_scale_frame(sd, &cpi->scaled_source, cm->temp_scale_frame.y_buffer,
2577 tmp_height, hs, hr, vs, vr, 0);
2579 vp8_yv12_extend_frame_borders(&cpi->scaled_source);
2580 cpi->Source = &cpi->scaled_source;
2588 static void resize_key_frame(VP8_COMP *cpi)
2590 #if CONFIG_SPATIAL_RESAMPLING
2591 VP8_COMMON *cm = &cpi->common;
2593 // Do we need to apply resampling for one pass cbr.
2594 // In one pass this is more limited than in two pass cbr
2595 // The test and any change is only made one per key frame sequence
2596 if (cpi->oxcf.allow_spatial_resampling && (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER))
2598 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2599 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2600 int new_width, new_height;
2602 // If we are below the resample DOWN watermark then scale down a notch.
2603 if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2605 cm->horiz_scale = (cm->horiz_scale < ONETWO) ? cm->horiz_scale + 1 : ONETWO;
2606 cm->vert_scale = (cm->vert_scale < ONETWO) ? cm->vert_scale + 1 : ONETWO;
2608 // Should we now start scaling back up
2609 else if (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2611 cm->horiz_scale = (cm->horiz_scale > NORMAL) ? cm->horiz_scale - 1 : NORMAL;
2612 cm->vert_scale = (cm->vert_scale > NORMAL) ? cm->vert_scale - 1 : NORMAL;
2615 // Get the new hieght and width
2616 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2617 Scale2Ratio(cm->vert_scale, &vr, &vs);
2618 new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
2619 new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
2621 // If the image size has changed we need to reallocate the buffers
2622 // and resample the source image
2623 if ((cm->Width != new_width) || (cm->Height != new_height))
2625 cm->Width = new_width;
2626 cm->Height = new_height;
2627 vp8_alloc_compressor_data(cpi);
2628 scale_and_extend_source(cpi->un_scaled_source, cpi);
2636 static void update_alt_ref_frame_stats(VP8_COMP *cpi)
2638 VP8_COMMON *cm = &cpi->common;
2640 // Select an interval before next GF or altref
2641 if (!cpi->auto_gold)
2642 cpi->frames_till_gf_update_due = cpi->goldfreq;
2644 if ((cpi->pass != 2) && cpi->frames_till_gf_update_due)
2646 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2648 // Set the bits per frame that we should try and recover in subsequent inter frames
2649 // to account for the extra GF spend... note that his does not apply for GF updates
2650 // that occur coincident with a key frame as the extra cost of key frames is dealt
2653 cpi->gf_overspend_bits += cpi->projected_frame_size;
2654 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2657 // Update data structure that monitors level of reference to last GF
2658 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2659 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2661 // this frame refreshes means next frames don't unless specified by user
2662 cpi->common.frames_since_golden = 0;
2664 // Clear the alternate reference update pending flag.
2665 cpi->source_alt_ref_pending = 0;
2667 // Set the alternate refernce frame active flag
2668 cpi->source_alt_ref_active = 1;
2672 static void update_golden_frame_stats(VP8_COMP *cpi)
2674 VP8_COMMON *cm = &cpi->common;
2676 // Update the Golden frame usage counts.
2677 if (cm->refresh_golden_frame)
2679 // Select an interval before next GF
2680 if (!cpi->auto_gold)
2681 cpi->frames_till_gf_update_due = cpi->goldfreq;
2683 if ((cpi->pass != 2) && (cpi->frames_till_gf_update_due > 0))
2685 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2687 // Set the bits per frame that we should try and recover in subsequent inter frames
2688 // to account for the extra GF spend... note that his does not apply for GF updates
2689 // that occur coincident with a key frame as the extra cost of key frames is dealt
2691 if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active)
2693 // Calcluate GF bits to be recovered
2694 // Projected size - av frame bits available for inter frames for clip as a whole
2695 cpi->gf_overspend_bits += (cpi->projected_frame_size - cpi->inter_frame_target);
2698 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2702 // Update data structure that monitors level of reference to last GF
2703 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2704 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2706 // this frame refreshes means next frames don't unless specified by user
2707 cm->refresh_golden_frame = 0;
2708 cpi->common.frames_since_golden = 0;
2710 //if ( cm->frame_type == KEY_FRAME )
2712 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
2713 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
2714 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
2715 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
2719 // // Carry a potrtion of count over to begining of next gf sequence
2720 // cpi->recent_ref_frame_usage[INTRA_FRAME] >>= 5;
2721 // cpi->recent_ref_frame_usage[LAST_FRAME] >>= 5;
2722 // cpi->recent_ref_frame_usage[GOLDEN_FRAME] >>= 5;
2723 // cpi->recent_ref_frame_usage[ALTREF_FRAME] >>= 5;
2726 // ******** Fixed Q test code only ************
2727 // If we are going to use the ALT reference for the next group of frames set a flag to say so.
2728 if (cpi->oxcf.fixed_q >= 0 &&
2729 cpi->oxcf.play_alternate && !cpi->common.refresh_alt_ref_frame)
2731 cpi->source_alt_ref_pending = 1;
2732 cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2735 if (!cpi->source_alt_ref_pending)
2736 cpi->source_alt_ref_active = 0;
2738 // Decrement count down till next gf
2739 if (cpi->frames_till_gf_update_due > 0)
2740 cpi->frames_till_gf_update_due--;
2743 else if (!cpi->common.refresh_alt_ref_frame)
2745 // Decrement count down till next gf
2746 if (cpi->frames_till_gf_update_due > 0)
2747 cpi->frames_till_gf_update_due--;
2749 if (cpi->common.frames_till_alt_ref_frame)
2750 cpi->common.frames_till_alt_ref_frame --;
2752 cpi->common.frames_since_golden ++;
2754 if (cpi->common.frames_since_golden > 1)
2756 cpi->recent_ref_frame_usage[INTRA_FRAME] += cpi->count_mb_ref_frame_usage[INTRA_FRAME];
2757 cpi->recent_ref_frame_usage[LAST_FRAME] += cpi->count_mb_ref_frame_usage[LAST_FRAME];
2758 cpi->recent_ref_frame_usage[GOLDEN_FRAME] += cpi->count_mb_ref_frame_usage[GOLDEN_FRAME];
2759 cpi->recent_ref_frame_usage[ALTREF_FRAME] += cpi->count_mb_ref_frame_usage[ALTREF_FRAME];
2764 // This function updates the reference frame probability estimates that
2765 // will be used during mode selection
2766 static void update_rd_ref_frame_probs(VP8_COMP *cpi)
2768 VP8_COMMON *cm = &cpi->common;
2770 const int *const rfct = cpi->count_mb_ref_frame_usage;
2771 const int rf_intra = rfct[INTRA_FRAME];
2772 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
2774 if (cm->frame_type == KEY_FRAME)
2776 cpi->prob_intra_coded = 255;
2777 cpi->prob_last_coded = 128;
2778 cpi->prob_gf_coded = 128;
2780 else if (!(rf_intra + rf_inter))
2782 cpi->prob_intra_coded = 63;
2783 cpi->prob_last_coded = 128;
2784 cpi->prob_gf_coded = 128;
2787 // update reference frame costs since we can do better than what we got last frame.
2788 if (cpi->oxcf.number_of_layers == 1)
2790 if (cpi->common.refresh_alt_ref_frame)
2792 cpi->prob_intra_coded += 40;
2793 cpi->prob_last_coded = 200;
2794 cpi->prob_gf_coded = 1;
2796 else if (cpi->common.frames_since_golden == 0)
2798 cpi->prob_last_coded = 214;
2800 else if (cpi->common.frames_since_golden == 1)
2802 cpi->prob_last_coded = 192;
2803 cpi->prob_gf_coded = 220;
2805 else if (cpi->source_alt_ref_active)
2807 cpi->prob_gf_coded -= 20;
2809 if (cpi->prob_gf_coded < 10)
2810 cpi->prob_gf_coded = 10;
2812 if (!cpi->source_alt_ref_active)
2813 cpi->prob_gf_coded = 255;
2818 // 1 = key, 0 = inter
2819 static int decide_key_frame(VP8_COMP *cpi)
2821 VP8_COMMON *cm = &cpi->common;
2823 int code_key_frame = 0;
2827 if (cpi->Speed > 11)
2830 // Clear down mmx registers
2831 vp8_clear_system_state(); //__asm emms;
2833 if ((cpi->compressor_speed == 2) && (cpi->Speed >= 5) && (cpi->sf.RD == 0))
2835 double change = 1.0 * abs((int)(cpi->intra_error - cpi->last_intra_error)) / (1 + cpi->last_intra_error);
2836 double change2 = 1.0 * abs((int)(cpi->prediction_error - cpi->last_prediction_error)) / (1 + cpi->last_prediction_error);
2837 double minerror = cm->MBs * 256;
2841 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
2842 && cpi->prediction_error > minerror
2843 && (change > .25 || change2 > .25))
2845 FILE *f = fopen("intra_inter.stt", "a");
2847 if (cpi->prediction_error <= 0)
2848 cpi->prediction_error = 1;
2850 fprintf(f, "%d %d %d %d %14.4f\n",
2851 cm->current_video_frame,
2852 (int) cpi->prediction_error,
2853 (int) cpi->intra_error,
2854 (int)((10 * cpi->intra_error) / cpi->prediction_error),
2862 cpi->last_intra_error = cpi->intra_error;
2863 cpi->last_prediction_error = cpi->prediction_error;
2865 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
2866 && cpi->prediction_error > minerror
2867 && (change > .25 || change2 > .25))
2869 /*(change > 1.4 || change < .75)&& cpi->this_frame_percent_intra > cpi->last_frame_percent_intra + 3*/
2877 // If the following are true we might as well code a key frame
2878 if (((cpi->this_frame_percent_intra == 100) &&
2879 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
2880 ((cpi->this_frame_percent_intra > 95) &&
2881 (cpi->this_frame_percent_intra >= (cpi->last_frame_percent_intra + 5))))
2885 // in addition if the following are true and this is not a golden frame then code a key frame
2886 // Note that on golden frames there often seems to be a pop in intra useage anyway hence this
2887 // restriction is designed to prevent spurious key frames. The Intra pop needs to be investigated.
2888 else if (((cpi->this_frame_percent_intra > 60) &&
2889 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 2))) ||
2890 ((cpi->this_frame_percent_intra > 75) &&
2891 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 3 / 2))) ||
2892 ((cpi->this_frame_percent_intra > 90) &&
2893 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 10))))
2895 if (!cm->refresh_golden_frame)
2899 return code_key_frame;
2903 #if !(CONFIG_REALTIME_ONLY)
2904 static void Pass1Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags)
2909 vp8_set_quantizer(cpi, 26);
2911 scale_and_extend_source(cpi->un_scaled_source, cpi);
2912 vp8_first_pass(cpi);
2917 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame)
2925 sprintf(filename, "cx\\y%04d.raw", this_frame);
2926 yframe = fopen(filename, "wb");
2928 for (i = 0; i < frame->y_height; i++)
2929 fwrite(frame->y_buffer + i * frame->y_stride, frame->y_width, 1, yframe);
2932 sprintf(filename, "cx\\u%04d.raw", this_frame);
2933 yframe = fopen(filename, "wb");
2935 for (i = 0; i < frame->uv_height; i++)
2936 fwrite(frame->u_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2939 sprintf(filename, "cx\\v%04d.raw", this_frame);
2940 yframe = fopen(filename, "wb");
2942 for (i = 0; i < frame->uv_height; i++)
2943 fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2948 // return of 0 means drop frame
2950 // Function to test for conditions that indeicate we should loop
2951 // back and recode a frame.
2952 static int recode_loop_test( VP8_COMP *cpi,
2953 int high_limit, int low_limit,
2954 int q, int maxq, int minq )
2956 int force_recode = 0;
2957 VP8_COMMON *cm = &cpi->common;
2959 // Is frame recode allowed at all
2960 // Yes if either recode mode 1 is selected or mode two is selcted
2961 // and the frame is a key frame. golden frame or alt_ref_frame
2962 if ( (cpi->sf.recode_loop == 1) ||
2963 ( (cpi->sf.recode_loop == 2) &&
2964 ( (cm->frame_type == KEY_FRAME) ||
2965 cm->refresh_golden_frame ||
2966 cm->refresh_alt_ref_frame ) ) )
2968 // General over and under shoot tests
2969 if ( ((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
2970 ((cpi->projected_frame_size < low_limit) && (q > minq)) )
2974 // Special Constrained quality tests
2975 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
2977 // Undershoot and below auto cq level
2978 if ( (q > cpi->cq_target_quality) &&
2979 (cpi->projected_frame_size <
2980 ((cpi->this_frame_target * 7) >> 3)))
2984 // Severe undershoot and between auto and user cq level
2985 else if ( (q > cpi->oxcf.cq_level) &&
2986 (cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
2987 (cpi->active_best_quality > cpi->oxcf.cq_level))
2990 cpi->active_best_quality = cpi->oxcf.cq_level;
2995 return force_recode;
2998 void update_reference_frames(VP8_COMMON *cm)
3000 YV12_BUFFER_CONFIG *yv12_fb = cm->yv12_fb;
3002 // At this point the new frame has been encoded.
3003 // If any buffer copy / swapping is signaled it should be done here.
3005 if (cm->frame_type == KEY_FRAME)
3007 yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG | VP8_ALT_FLAG ;
3009 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3010 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3012 cm->alt_fb_idx = cm->gld_fb_idx = cm->new_fb_idx;
3014 else /* For non key frames */
3016 if (cm->refresh_alt_ref_frame)
3018 assert(!cm->copy_buffer_to_arf);
3020 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_ALT_FLAG;
3021 cm->yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3022 cm->alt_fb_idx = cm->new_fb_idx;
3024 else if (cm->copy_buffer_to_arf)
3026 assert(!(cm->copy_buffer_to_arf & ~0x3));
3028 if (cm->copy_buffer_to_arf == 1)
3030 if(cm->alt_fb_idx != cm->lst_fb_idx)
3032 yv12_fb[cm->lst_fb_idx].flags |= VP8_ALT_FLAG;
3033 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3034 cm->alt_fb_idx = cm->lst_fb_idx;
3037 else /* if (cm->copy_buffer_to_arf == 2) */
3039 if(cm->alt_fb_idx != cm->gld_fb_idx)
3041 yv12_fb[cm->gld_fb_idx].flags |= VP8_ALT_FLAG;
3042 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3043 cm->alt_fb_idx = cm->gld_fb_idx;
3048 if (cm->refresh_golden_frame)
3050 assert(!cm->copy_buffer_to_gf);
3052 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG;
3053 cm->yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3054 cm->gld_fb_idx = cm->new_fb_idx;
3056 else if (cm->copy_buffer_to_gf)
3058 assert(!(cm->copy_buffer_to_arf & ~0x3));
3060 if (cm->copy_buffer_to_gf == 1)
3062 if(cm->gld_fb_idx != cm->lst_fb_idx)
3064 yv12_fb[cm->lst_fb_idx].flags |= VP8_GOLD_FLAG;
3065 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3066 cm->gld_fb_idx = cm->lst_fb_idx;
3069 else /* if (cm->copy_buffer_to_gf == 2) */
3071 if(cm->alt_fb_idx != cm->gld_fb_idx)
3073 yv12_fb[cm->alt_fb_idx].flags |= VP8_GOLD_FLAG;
3074 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3075 cm->gld_fb_idx = cm->alt_fb_idx;
3081 if (cm->refresh_last_frame)
3083 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_LAST_FLAG;
3084 cm->yv12_fb[cm->lst_fb_idx].flags &= ~VP8_LAST_FLAG;
3085 cm->lst_fb_idx = cm->new_fb_idx;
3089 void vp8_loopfilter_frame(VP8_COMP *cpi, VP8_COMMON *cm)
3093 cm->filter_level = 0;
3097 struct vpx_usec_timer timer;
3099 vp8_clear_system_state();
3101 vpx_usec_timer_start(&timer);
3102 if (cpi->sf.auto_filter == 0)
3103 vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3106 vp8cx_pick_filter_level(cpi->Source, cpi);
3108 vpx_usec_timer_mark(&timer);
3109 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
3112 #if CONFIG_MULTITHREAD
3113 if (cpi->b_multi_threaded)
3114 sem_post(&cpi->h_event_end_lpf); /* signal that we have set filter_level */
3117 if (cm->filter_level > 0)
3119 vp8cx_set_alt_lf_level(cpi, cm->filter_level);
3120 vp8_loop_filter_frame(cm, &cpi->mb.e_mbd);
3123 vp8_yv12_extend_frame_borders_ptr(cm->frame_to_show);
3127 static void encode_frame_to_data_rate
3130 unsigned long *size,
3131 unsigned char *dest,
3132 unsigned char* dest_end,
3133 unsigned int *frame_flags
3137 int frame_over_shoot_limit;
3138 int frame_under_shoot_limit;
3148 int zbin_oq_low = 0;
3151 VP8_COMMON *cm = &cpi->common;
3152 int active_worst_qchanged = 0;
3154 int overshoot_seen = 0;
3155 int undershoot_seen = 0;
3156 int drop_mark = cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100;
3157 int drop_mark75 = drop_mark * 2 / 3;
3158 int drop_mark50 = drop_mark / 4;
3159 int drop_mark25 = drop_mark / 8;
3162 // Clear down mmx registers to allow floating point in what follows
3163 vp8_clear_system_state();
3165 // Test code for segmentation of gf/arf (0,0)
3166 //segmentation_test_function( cpi);
3168 if(cpi->force_next_frame_intra)
3170 cm->frame_type = KEY_FRAME; /* delayed intra frame */
3171 cpi->force_next_frame_intra = 0;
3174 // For an alt ref frame in 2 pass we skip the call to the second pass function that sets the target bandwidth
3175 #if !(CONFIG_REALTIME_ONLY)
3179 if (cpi->common.refresh_alt_ref_frame)
3181 cpi->per_frame_bandwidth = cpi->twopass.gf_bits; // Per frame bit target for the alt ref frame
3182 cpi->target_bandwidth = cpi->twopass.gf_bits * cpi->output_frame_rate; // per second target bitrate
3187 cpi->per_frame_bandwidth = (int)(cpi->target_bandwidth / cpi->output_frame_rate);
3189 // Default turn off buffer to buffer copying
3190 cm->copy_buffer_to_gf = 0;
3191 cm->copy_buffer_to_arf = 0;
3193 // Clear zbin over-quant value and mode boost values.
3194 cpi->zbin_over_quant = 0;
3195 cpi->zbin_mode_boost = 0;
3197 // Enable or disable mode based tweaking of the zbin
3198 // For 2 Pass Only used where GF/ARF prediction quality
3199 // is above a threshold
3200 cpi->zbin_mode_boost_enabled = 1;
3203 if ( cpi->gfu_boost <= 400 )
3205 cpi->zbin_mode_boost_enabled = 0;
3209 // Current default encoder behaviour for the altref sign bias
3210 if (cpi->source_alt_ref_active)
3211 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
3213 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
3215 // Check to see if a key frame is signalled
3216 // For two pass with auto key frame enabled cm->frame_type may already be set, but not for one pass.
3217 if ((cm->current_video_frame == 0) ||
3218 (cm->frame_flags & FRAMEFLAGS_KEY) ||
3219 (cpi->oxcf.auto_key && (cpi->frames_since_key % cpi->key_frame_frequency == 0)))
3221 // Key frame from VFW/auto-keyframe/first frame
3222 cm->frame_type = KEY_FRAME;
3225 // Set default state for segment and mode based loop filter update flags
3226 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
3227 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
3228 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
3230 // Set various flags etc to special state if it is a key frame
3231 if (cm->frame_type == KEY_FRAME)
3235 // Reset the loop filter deltas and segmentation map
3236 setup_features(cpi);
3238 // If segmentation is enabled force a map update for key frames
3239 if (cpi->mb.e_mbd.segmentation_enabled)
3241 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3242 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3245 // The alternate reference frame cannot be active for a key frame
3246 cpi->source_alt_ref_active = 0;
3248 // Reset the RD threshold multipliers to default of * 1 (128)
3249 for (i = 0; i < MAX_MODES; i++)
3251 cpi->rd_thresh_mult[i] = 128;
3255 // Test code for segmentation
3256 //if ( (cm->frame_type == KEY_FRAME) || ((cm->current_video_frame % 2) == 0))
3257 //if ( (cm->current_video_frame % 2) == 0 )
3258 // enable_segmentation(cpi);
3260 // disable_segmentation(cpi);
3263 // Experimental code for lagged compress and one pass
3264 // Initialise one_pass GF frames stats
3265 // Update stats used for GF selection
3266 //if ( cpi->pass == 0 )
3268 cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
3270 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
3271 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
3272 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
3273 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
3274 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
3275 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
3276 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
3277 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
3278 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
3282 update_rd_ref_frame_probs(cpi);
3284 if (cpi->drop_frames_allowed)
3286 // The reset to decimation 0 is only done here for one pass.
3287 // Once it is set two pass leaves decimation on till the next kf.
3288 if ((cpi->buffer_level > drop_mark) && (cpi->decimation_factor > 0))
3289 cpi->decimation_factor --;
3291 if (cpi->buffer_level > drop_mark75 && cpi->decimation_factor > 0)
3292 cpi->decimation_factor = 1;
3294 else if (cpi->buffer_level < drop_mark25 && (cpi->decimation_factor == 2 || cpi->decimation_factor == 3))
3296 cpi->decimation_factor = 3;
3298 else if (cpi->buffer_level < drop_mark50 && (cpi->decimation_factor == 1 || cpi->decimation_factor == 2))
3300 cpi->decimation_factor = 2;
3302 else if (cpi->buffer_level < drop_mark75 && (cpi->decimation_factor == 0 || cpi->decimation_factor == 1))
3304 cpi->decimation_factor = 1;
3307 //vpx_log("Encoder: Decimation Factor: %d \n",cpi->decimation_factor);
3310 // The following decimates the frame rate according to a regular pattern (i.e. to 1/2 or 2/3 frame rate)
3311 // This can be used to help prevent buffer under-run in CBR mode. Alternatively it might be desirable in
3312 // some situations to drop frame rate but throw more bits at each frame.
3314 // Note that dropping a key frame can be problematic if spatial resampling is also active
3315 if (cpi->decimation_factor > 0)
3317 switch (cpi->decimation_factor)
3320 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 3 / 2;
3323 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3326 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3330 // Note that we should not throw out a key frame (especially when spatial resampling is enabled).
3331 if ((cm->frame_type == KEY_FRAME)) // && cpi->oxcf.allow_spatial_resampling )
3333 cpi->decimation_count = cpi->decimation_factor;
3335 else if (cpi->decimation_count > 0)
3337 cpi->decimation_count --;
3339 cpi->bits_off_target += cpi->av_per_frame_bandwidth;
3340 if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
3341 cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
3343 cm->current_video_frame++;
3344 cpi->frames_since_key++;
3346 #if CONFIG_INTERNAL_STATS
3350 cpi->buffer_level = cpi->bits_off_target;
3352 if (cpi->oxcf.number_of_layers > 1)
3356 // Propagate bits saved by dropping the frame to higher layers
3357 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
3359 LAYER_CONTEXT *lc = &cpi->layer_context[i];
3360 lc->bits_off_target += cpi->av_per_frame_bandwidth;
3361 if (lc->bits_off_target > lc->maximum_buffer_size)
3362 lc->bits_off_target = lc->maximum_buffer_size;
3363 lc->buffer_level = lc->bits_off_target;
3370 cpi->decimation_count = cpi->decimation_factor;
3373 // Decide how big to make the frame
3374 if (!vp8_pick_frame_size(cpi))
3376 cm->current_video_frame++;
3377 cpi->frames_since_key++;
3381 // Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
3382 // This has a knock on effect on active best quality as well.
3383 // For CBR if the buffer reaches its maximum level then we can no longer
3384 // save up bits for later frames so we might as well use them up
3385 // on the current frame.
3386 if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
3387 (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) && cpi->buffered_mode)
3389 int Adjustment = cpi->active_worst_quality / 4; // Max adjustment is 1/4
3395 if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size)
3397 buff_lvl_step = (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level) / Adjustment;
3400 Adjustment = (cpi->buffer_level - cpi->oxcf.optimal_buffer_level) / buff_lvl_step;
3405 cpi->active_worst_quality -= Adjustment;
3407 if(cpi->active_worst_quality < cpi->active_best_quality)
3408 cpi->active_worst_quality = cpi->active_best_quality;
3412 // Set an active best quality and if necessary active worst quality
3413 // There is some odd behavior for one pass here that needs attention.
3414 if ( (cpi->pass == 2) || (cpi->ni_frames > 150))
3416 vp8_clear_system_state();
3418 Q = cpi->active_worst_quality;
3420 if ( cm->frame_type == KEY_FRAME )
3422 if ( cpi->pass == 2 )
3424 if (cpi->gfu_boost > 600)
3425 cpi->active_best_quality = kf_low_motion_minq[Q];
3427 cpi->active_best_quality = kf_high_motion_minq[Q];
3429 // Special case for key frames forced because we have reached
3430 // the maximum key frame interval. Here force the Q to a range
3431 // based on the ambient Q to reduce the risk of popping
3432 if ( cpi->this_key_frame_forced )
3434 if ( cpi->active_best_quality > cpi->avg_frame_qindex * 7/8)
3435 cpi->active_best_quality = cpi->avg_frame_qindex * 7/8;
3436 else if ( cpi->active_best_quality < cpi->avg_frame_qindex >> 2 )
3437 cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
3440 // One pass more conservative
3442 cpi->active_best_quality = kf_high_motion_minq[Q];
3445 else if (cpi->oxcf.number_of_layers==1 &&
3446 (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame))
3448 // Use the lower of cpi->active_worst_quality and recent
3449 // average Q as basis for GF/ARF Q limit unless last frame was
3451 if ( (cpi->frames_since_key > 1) &&
3452 (cpi->avg_frame_qindex < cpi->active_worst_quality) )
3454 Q = cpi->avg_frame_qindex;
3457 // For constrained quality dont allow Q less than the cq level
3458 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3459 (Q < cpi->cq_target_quality) )
3461 Q = cpi->cq_target_quality;
3464 if ( cpi->pass == 2 )
3466 if ( cpi->gfu_boost > 1000 )
3467 cpi->active_best_quality = gf_low_motion_minq[Q];
3468 else if ( cpi->gfu_boost < 400 )
3469 cpi->active_best_quality = gf_high_motion_minq[Q];
3471 cpi->active_best_quality = gf_mid_motion_minq[Q];
3473 // Constrained quality use slightly lower active best.
3474 if ( cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY )
3476 cpi->active_best_quality =
3477 cpi->active_best_quality * 15/16;
3480 // One pass more conservative
3482 cpi->active_best_quality = gf_high_motion_minq[Q];
3486 cpi->active_best_quality = inter_minq[Q];
3488 // For the constant/constrained quality mode we dont want
3489 // q to fall below the cq level.
3490 if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3491 (cpi->active_best_quality < cpi->cq_target_quality) )
3493 // If we are strongly undershooting the target rate in the last
3494 // frames then use the user passed in cq value not the auto
3496 if ( cpi->rolling_actual_bits < cpi->min_frame_bandwidth )
3497 cpi->active_best_quality = cpi->oxcf.cq_level;
3499 cpi->active_best_quality = cpi->cq_target_quality;
3503 // If CBR and the buffer is as full then it is reasonable to allow
3504 // higher quality on the frames to prevent bits just going to waste.
3505 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
3507 // Note that the use of >= here elliminates the risk of a devide
3508 // by 0 error in the else if clause
3509 if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size)
3510 cpi->active_best_quality = cpi->best_quality;
3512 else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level)
3514 int Fraction = ((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) / (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level);
3515 int min_qadjustment = ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;
3517 cpi->active_best_quality -= min_qadjustment;
3521 // Make sure constrained quality mode limits are adhered to for the first
3522 // few frames of one pass encodes
3523 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
3525 if ( (cm->frame_type == KEY_FRAME) ||
3526 cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame )
3528 cpi->active_best_quality = cpi->best_quality;
3530 else if (cpi->active_best_quality < cpi->cq_target_quality)
3532 cpi->active_best_quality = cpi->cq_target_quality;
3536 // Clip the active best and worst quality values to limits
3537 if (cpi->active_worst_quality > cpi->worst_quality)
3538 cpi->active_worst_quality = cpi->worst_quality;
3540 if (cpi->active_best_quality < cpi->best_quality)
3541 cpi->active_best_quality = cpi->best_quality;
3543 if ( cpi->active_worst_quality < cpi->active_best_quality )
3544 cpi->active_worst_quality = cpi->active_best_quality;
3546 // Determine initial Q to try
3547 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3548 last_zbin_oq = cpi->zbin_over_quant;
3550 // Set highest allowed value for Zbin over quant
3551 if (cm->frame_type == KEY_FRAME)
3552 zbin_oq_high = 0; //ZBIN_OQ_MAX/16
3553 else if ((cpi->oxcf.number_of_layers == 1) && ((cm->refresh_alt_ref_frame ||
3554 (cm->refresh_golden_frame && !cpi->source_alt_ref_active))))
3559 zbin_oq_high = ZBIN_OQ_MAX;
3561 // Setup background Q adjustment for error resilient mode.
3562 // For multi-layer encodes only enable this for the base layer.
3563 if (cpi->cyclic_refresh_mode_enabled && (cpi->current_layer==0))
3564 cyclic_background_refresh(cpi, Q, 0);
3566 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3568 // Limit Q range for the adaptive loop.
3569 bottom_index = cpi->active_best_quality;
3570 top_index = cpi->active_worst_quality;
3571 q_low = cpi->active_best_quality;
3572 q_high = cpi->active_worst_quality;
3574 vp8_save_coding_context(cpi);
3579 scale_and_extend_source(cpi->un_scaled_source, cpi);
3580 #if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC
3582 if (cpi->oxcf.noise_sensitivity > 0)
3587 switch (cpi->oxcf.noise_sensitivity)
3610 if (cm->frame_type == KEY_FRAME)
3612 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0);
3616 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0);
3618 src = cpi->Source->y_buffer;
3620 if (cpi->Source->y_stride < 0)
3622 src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
3629 #ifdef OUTPUT_YUV_SRC
3630 vp8_write_yuv_frame(cpi->Source);
3635 vp8_clear_system_state(); //__asm emms;
3638 if(cpi->is_src_frame_alt_ref)
3642 vp8_set_quantizer(cpi, Q);
3645 // setup skip prob for costing in mode/mv decision
3646 if (cpi->common.mb_no_coeff_skip)
3648 cpi->prob_skip_false = cpi->base_skip_false_prob[Q];
3650 if (cm->frame_type != KEY_FRAME)
3652 if (cpi->common.refresh_alt_ref_frame)
3654 if (cpi->last_skip_false_probs[2] != 0)
3655 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3658 if(cpi->last_skip_false_probs[2]!=0 && abs(Q- cpi->last_skip_probs_q[2])<=16 )
3659 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3660 else if (cpi->last_skip_false_probs[2]!=0)
3661 cpi->prob_skip_false = (cpi->last_skip_false_probs[2] + cpi->prob_skip_false ) / 2;
3664 else if (cpi->common.refresh_golden_frame)
3666 if (cpi->last_skip_false_probs[1] != 0)
3667 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3670 if(cpi->last_skip_false_probs[1]!=0 && abs(Q- cpi->last_skip_probs_q[1])<=16 )
3671 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3672 else if (cpi->last_skip_false_probs[1]!=0)
3673 cpi->prob_skip_false = (cpi->last_skip_false_probs[1] + cpi->prob_skip_false ) / 2;
3678 if (cpi->last_skip_false_probs[0] != 0)
3679 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3682 if(cpi->last_skip_false_probs[0]!=0 && abs(Q- cpi->last_skip_probs_q[0])<=16 )
3683 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3684 else if(cpi->last_skip_false_probs[0]!=0)
3685 cpi->prob_skip_false = (cpi->last_skip_false_probs[0] + cpi->prob_skip_false ) / 2;
3689 //as this is for cost estimate, let's make sure it does not go extreme eitehr way
3690 if (cpi->prob_skip_false < 5)
3691 cpi->prob_skip_false = 5;
3693 if (cpi->prob_skip_false > 250)
3694 cpi->prob_skip_false = 250;
3696 if (cpi->oxcf.number_of_layers == 1 && cpi->is_src_frame_alt_ref)
3697 cpi->prob_skip_false = 1;
3704 FILE *f = fopen("skip.stt", "a");
3705 fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
3713 if (cm->frame_type == KEY_FRAME)
3715 resize_key_frame(cpi);
3716 vp8_setup_key_frame(cpi);
3719 #if CONFIG_MULTITHREAD
3720 /* wait for the last picture loopfilter thread done */
3721 if (cpi->b_lpf_running)
3723 sem_wait(&cpi->h_event_end_lpf);
3724 cpi->b_lpf_running = 0;
3728 // transform / motion compensation build reconstruction frame
3729 vp8_encode_frame(cpi);
3731 cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
3732 cpi->projected_frame_size = (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
3734 vp8_clear_system_state(); //__asm emms;
3736 // Test to see if the stats generated for this frame indicate that we should have coded a key frame
3737 // (assuming that we didn't)!
3738 if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3740 int key_frame_decision = decide_key_frame(cpi);
3742 if (cpi->compressor_speed == 2)
3744 /* we don't do re-encoding in realtime mode
3745 * if key frame is decided than we force it on next frame */
3746 cpi->force_next_frame_intra = key_frame_decision;
3748 else if (key_frame_decision)
3750 // Reset all our sizing numbers and recode
3751 cm->frame_type = KEY_FRAME;
3753 vp8_pick_frame_size(cpi);
3755 // Clear the Alt reference frame active flag when we have a key frame
3756 cpi->source_alt_ref_active = 0;
3758 // Reset the loop filter deltas and segmentation map
3759 setup_features(cpi);
3761 // If segmentation is enabled force a map update for key frames
3762 if (cpi->mb.e_mbd.segmentation_enabled)
3764 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3765 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3768 vp8_restore_coding_context(cpi);
3770 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3772 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3774 // Limit Q range for the adaptive loop.
3775 bottom_index = cpi->active_best_quality;
3776 top_index = cpi->active_worst_quality;
3777 q_low = cpi->active_best_quality;
3778 q_high = cpi->active_worst_quality;
3787 vp8_clear_system_state();
3789 if (frame_over_shoot_limit == 0)
3790 frame_over_shoot_limit = 1;
3792 // Are we are overshooting and up against the limit of active max Q.
3793 if (((cpi->pass != 2) || (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
3794 (Q == cpi->active_worst_quality) &&
3795 (cpi->active_worst_quality < cpi->worst_quality) &&
3796 (cpi->projected_frame_size > frame_over_shoot_limit))
3798 int over_size_percent = ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) / frame_over_shoot_limit;
3800 // If so is there any scope for relaxing it
3801 while ((cpi->active_worst_quality < cpi->worst_quality) && (over_size_percent > 0))
3803 cpi->active_worst_quality++;
3804 top_index = cpi->active_worst_quality;
3805 over_size_percent = (int)(over_size_percent * 0.96); // Assume 1 qstep = about 4% on frame size.
3808 // If we have updated the active max Q do not call vp8_update_rate_correction_factors() this loop.
3809 active_worst_qchanged = 1;
3812 active_worst_qchanged = 0;
3814 #if !(CONFIG_REALTIME_ONLY)
3815 // Special case handling for forced key frames
3816 if ( (cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced )
3819 int kf_err = vp8_calc_ss_err(cpi->Source,
3820 &cm->yv12_fb[cm->new_fb_idx]);
3822 // The key frame is not good enough
3823 if ( kf_err > ((cpi->ambient_err * 7) >> 3) )
3826 q_high = (Q > q_low) ? (Q - 1) : q_low;
3829 Q = (q_high + q_low) >> 1;
3831 // The key frame is much better than the previous frame
3832 else if ( kf_err < (cpi->ambient_err >> 1) )
3835 q_low = (Q < q_high) ? (Q + 1) : q_high;
3838 Q = (q_high + q_low + 1) >> 1;
3841 // Clamp Q to upper and lower limits:
3850 // Is the projected frame size out of range and are we allowed to attempt to recode.
3851 else if ( recode_loop_test( cpi,
3852 frame_over_shoot_limit, frame_under_shoot_limit,
3853 Q, top_index, bottom_index ) )
3858 // Frame size out of permitted range:
3859 // Update correction factor & compute new Q to try...
3861 // Frame is too large
3862 if (cpi->projected_frame_size > cpi->this_frame_target)
3864 //if ( cpi->zbin_over_quant == 0 )
3865 q_low = (Q < q_high) ? (Q + 1) : q_high; // Raise Qlow as to at least the current value
3867 if (cpi->zbin_over_quant > 0) // If we are using over quant do the same for zbin_oq_low
3868 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
3870 //if ( undershoot_seen || (Q == MAXQ) )
3871 if (undershoot_seen)
3873 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3874 if (!active_worst_qchanged)
3875 vp8_update_rate_correction_factors(cpi, 1);
3877 Q = (q_high + q_low + 1) / 2;
3879 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
3881 cpi->zbin_over_quant = 0;
3884 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
3885 cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
3890 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3891 if (!active_worst_qchanged)
3892 vp8_update_rate_correction_factors(cpi, 0);
3894 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3896 while (((Q < q_low) || (cpi->zbin_over_quant < zbin_oq_low)) && (Retries < 10))
3898 vp8_update_rate_correction_factors(cpi, 0);
3899 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3906 // Frame is too small
3909 if (cpi->zbin_over_quant == 0)
3910 q_high = (Q > q_low) ? (Q - 1) : q_low; // Lower q_high if not using over quant
3911 else // else lower zbin_oq_high
3912 zbin_oq_high = (cpi->zbin_over_quant > zbin_oq_low) ? (cpi->zbin_over_quant - 1) : zbin_oq_low;
3916 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3917 if (!active_worst_qchanged)
3918 vp8_update_rate_correction_factors(cpi, 1);
3920 Q = (q_high + q_low) / 2;
3922 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
3924 cpi->zbin_over_quant = 0;
3926 cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
3930 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3931 if (!active_worst_qchanged)
3932 vp8_update_rate_correction_factors(cpi, 0);
3934 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3936 // Special case reset for qlow for constrained quality.
3937 // This should only trigger where there is very substantial
3938 // undershoot on a frame and the auto cq level is above
3939 // the user passsed in value.
3940 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3946 while (((Q > q_high) || (cpi->zbin_over_quant > zbin_oq_high)) && (Retries < 10))
3948 vp8_update_rate_correction_factors(cpi, 0);
3949 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3954 undershoot_seen = 1;
3957 // Clamp Q to upper and lower limits:
3963 // Clamp cpi->zbin_over_quant
3964 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;
3966 //Loop = (Q != last_q) || (last_zbin_oq != cpi->zbin_over_quant);
3968 last_zbin_oq = cpi->zbin_over_quant;
3974 if (cpi->is_src_frame_alt_ref)
3979 vp8_restore_coding_context(cpi);
3981 #if CONFIG_INTERNAL_STATS
3982 cpi->tot_recode_hits++;
3989 // Experimental code for lagged and one pass
3990 // Update stats used for one pass GF selection
3994 double frame_intra_error;
3995 double frame_coded_error;
3996 double frame_pcnt_inter;
3997 double frame_pcnt_motion;
3999 double frame_mvr_abs;
4001 double frame_mvc_abs;
4004 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
4005 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
4006 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
4010 // Special case code to reduce pulsing when key frames are forced at a
4011 // fixed interval. Note the reconstruction error if it is the frame before
4012 // the force key frame
4013 if ( cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0) )
4015 cpi->ambient_err = vp8_calc_ss_err(cpi->Source,
4016 &cm->yv12_fb[cm->new_fb_idx]);
4019 /* This frame's MVs are saved and will be used in next frame's MV predictor.
4020 * Last frame has one more line(add to bottom) and one more column(add to
4021 * right) than cm->mip. The edge elements are initialized to 0.
4023 #if CONFIG_MULTI_RES_ENCODING
4024 if(!cpi->oxcf.mr_encoder_id && cm->show_frame)
4026 if(cm->show_frame) /* do not save for altref frame */
4031 /* Point to beginning of allocated MODE_INFO arrays. */
4032 MODE_INFO *tmp = cm->mip;
4034 if(cm->frame_type != KEY_FRAME)
4036 for (mb_row = 0; mb_row < cm->mb_rows+1; mb_row ++)
4038 for (mb_col = 0; mb_col < cm->mb_cols+1; mb_col ++)
4040 if(tmp->mbmi.ref_frame != INTRA_FRAME)
4041 cpi->lfmv[mb_col + mb_row*(cm->mode_info_stride+1)].as_int = tmp->mbmi.mv.as_int;
4043 cpi->lf_ref_frame_sign_bias[mb_col + mb_row*(cm->mode_info_stride+1)] = cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
4044 cpi->lf_ref_frame[mb_col + mb_row*(cm->mode_info_stride+1)] = tmp->mbmi.ref_frame;
4051 #if CONFIG_MULTI_RES_ENCODING
4052 vp8_cal_dissimilarity(cpi);
4055 // Update the GF useage maps.
4056 // This is done after completing the compression of a frame when all
4057 // modes etc. are finalized but before loop filter
4058 if (cpi->oxcf.number_of_layers == 1)
4059 vp8_update_gf_useage_maps(cpi, cm, &cpi->mb);
4061 if (cm->frame_type == KEY_FRAME)
4062 cm->refresh_last_frame = 1;
4066 FILE *f = fopen("gfactive.stt", "a");
4067 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);
4072 // For inter frames the current default behavior is that when
4073 // cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
4074 // This is purely an encoder decision at present.
4075 if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame)
4076 cm->copy_buffer_to_arf = 2;
4078 cm->copy_buffer_to_arf = 0;
4080 cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
4082 #if CONFIG_MULTITHREAD
4083 if (cpi->b_multi_threaded)
4085 sem_post(&cpi->h_event_start_lpf); /* start loopfilter in separate thread */
4086 cpi->b_lpf_running = 1;
4091 vp8_loopfilter_frame(cpi, cm);
4094 update_reference_frames(cm);
4096 if (cpi->oxcf.error_resilient_mode)
4098 cm->refresh_entropy_probs = 0;
4101 #if CONFIG_MULTITHREAD
4102 /* wait that filter_level is picked so that we can continue with stream packing */
4103 if (cpi->b_multi_threaded)
4104 sem_wait(&cpi->h_event_end_lpf);
4107 // build the bitstream
4108 vp8_pack_bitstream(cpi, dest, dest_end, size);
4110 #if CONFIG_MULTITHREAD
4111 /* if PSNR packets are generated we have to wait for the lpf */
4112 if (cpi->b_lpf_running && cpi->b_calculate_psnr)
4114 sem_wait(&cpi->h_event_end_lpf);
4115 cpi->b_lpf_running = 0;
4119 /* Move storing frame_type out of the above loop since it is also
4120 * needed in motion search besides loopfilter */
4121 cm->last_frame_type = cm->frame_type;
4123 // Update rate control heuristics
4124 cpi->total_byte_count += (*size);
4125 cpi->projected_frame_size = (*size) << 3;
4127 if (cpi->oxcf.number_of_layers > 1)
4130 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
4131 cpi->layer_context[i].total_byte_count += (*size);
4134 if (!active_worst_qchanged)
4135 vp8_update_rate_correction_factors(cpi, 2);
4137 cpi->last_q[cm->frame_type] = cm->base_qindex;
4139 if (cm->frame_type == KEY_FRAME)
4141 vp8_adjust_key_frame_context(cpi);
4144 // Keep a record of ambient average Q.
4145 if (cm->frame_type != KEY_FRAME)
4146 cpi->avg_frame_qindex = (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
4148 // Keep a record from which we can calculate the average Q excluding GF updates and key frames
4149 if ((cm->frame_type != KEY_FRAME) && ((cpi->oxcf.number_of_layers > 1) ||
4150 (!cm->refresh_golden_frame && !cm->refresh_alt_ref_frame)))
4154 // Calculate the average Q for normal inter frames (not key or GFU
4156 if ( cpi->pass == 2 )
4158 cpi->ni_tot_qi += Q;
4159 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4163 // Damp value for first few frames
4164 if (cpi->ni_frames > 150 )
4166 cpi->ni_tot_qi += Q;
4167 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4169 // For one pass, early in the clip ... average the current frame Q
4170 // value with the worstq entered by the user as a dampening measure
4173 cpi->ni_tot_qi += Q;
4174 cpi->ni_av_qi = ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
4177 // If the average Q is higher than what was used in the last frame
4178 // (after going through the recode loop to keep the frame size within range)
4179 // then use the last frame value - 1.
4180 // The -1 is designed to stop Q and hence the data rate, from progressively
4181 // falling away during difficult sections, but at the same time reduce the number of
4182 // itterations around the recode loop.
4183 if (Q > cpi->ni_av_qi)
4184 cpi->ni_av_qi = Q - 1;
4190 // If the frame was massively oversize and we are below optimal buffer level drop next frame
4191 if ((cpi->drop_frames_allowed) &&
4192 (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
4193 (cpi->buffer_level < cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100) &&
4194 (cpi->projected_frame_size > (4 * cpi->this_frame_target)))
4196 cpi->drop_frame = 1;
4201 // Set the count for maximum consecutive dropped frames based upon the ratio of
4202 // this frame size to the target average per frame bandwidth.
4203 // (cpi->av_per_frame_bandwidth > 0) is just a sanity check to prevent / 0.
4204 if (cpi->drop_frames_allowed && (cpi->av_per_frame_bandwidth > 0))
4206 cpi->max_drop_count = cpi->projected_frame_size / cpi->av_per_frame_bandwidth;
4208 if (cpi->max_drop_count > cpi->max_consec_dropped_frames)
4209 cpi->max_drop_count = cpi->max_consec_dropped_frames;
4212 // Update the buffer level variable.
4213 // Non-viewable frames are a special case and are treated as pure overhead.
4214 if ( !cm->show_frame )
4215 cpi->bits_off_target -= cpi->projected_frame_size;
4217 cpi->bits_off_target += cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
4219 // Clip the buffer level to the maximum specified buffer size
4220 if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
4221 cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
4223 // Rolling monitors of whether we are over or underspending used to help regulate min and Max Q in two pass.
4224 cpi->rolling_target_bits = ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
4225 cpi->rolling_actual_bits = ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
4226 cpi->long_rolling_target_bits = ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
4227 cpi->long_rolling_actual_bits = ((cpi->long_rolling_actual_bits * 31) + cpi->projected_frame_size + 16) / 32;
4229 // Actual bits spent
4230 cpi->total_actual_bits += cpi->projected_frame_size;
4233 cpi->total_target_vs_actual += (cpi->this_frame_target - cpi->projected_frame_size);
4235 cpi->buffer_level = cpi->bits_off_target;
4237 // Propagate values to higher temporal layers
4238 if (cpi->oxcf.number_of_layers > 1)
4242 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
4244 LAYER_CONTEXT *lc = &cpi->layer_context[i];
4245 int bits_off_for_this_layer = lc->target_bandwidth / lc->frame_rate
4246 - cpi->projected_frame_size;
4248 lc->bits_off_target += bits_off_for_this_layer;
4250 // Clip buffer level to maximum buffer size for the layer
4251 if (lc->bits_off_target > lc->maximum_buffer_size)
4252 lc->bits_off_target = lc->maximum_buffer_size;
4254 lc->total_actual_bits += cpi->projected_frame_size;
4255 lc->total_target_vs_actual += bits_off_for_this_layer;
4256 lc->buffer_level = lc->bits_off_target;
4260 // Update bits left to the kf and gf groups to account for overshoot or undershoot on these frames
4261 if (cm->frame_type == KEY_FRAME)
4263 cpi->twopass.kf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4265 if (cpi->twopass.kf_group_bits < 0)
4266 cpi->twopass.kf_group_bits = 0 ;
4268 else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4270 cpi->twopass.gf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4272 if (cpi->twopass.gf_group_bits < 0)
4273 cpi->twopass.gf_group_bits = 0 ;
4276 if (cm->frame_type != KEY_FRAME)
4278 if (cpi->common.refresh_alt_ref_frame)
4280 cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
4281 cpi->last_skip_probs_q[2] = cm->base_qindex;
4283 else if (cpi->common.refresh_golden_frame)
4285 cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
4286 cpi->last_skip_probs_q[1] = cm->base_qindex;
4290 cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
4291 cpi->last_skip_probs_q[0] = cm->base_qindex;
4293 //update the baseline
4294 cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
4299 #if 0 && CONFIG_INTERNAL_STATS
4301 FILE *f = fopen("tmp.stt", "a");
4303 vp8_clear_system_state(); //__asm emms;
4305 if (cpi->twopass.total_left_stats.coded_error != 0.0)
4306 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4307 "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4309 cpi->common.current_video_frame, cpi->this_frame_target,
4310 cpi->projected_frame_size,
4311 (cpi->projected_frame_size - cpi->this_frame_target),
4312 (int)cpi->total_target_vs_actual,
4314 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4315 (int)cpi->total_actual_bits, cm->base_qindex,
4316 cpi->active_best_quality, cpi->active_worst_quality,
4317 cpi->ni_av_qi, cpi->cq_target_quality,
4318 cpi->zbin_over_quant,
4319 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4320 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4321 cm->frame_type, cpi->gfu_boost,
4322 cpi->twopass.est_max_qcorrection_factor,
4323 (int)cpi->twopass.bits_left,
4324 cpi->twopass.total_left_stats.coded_error,
4325 (double)cpi->twopass.bits_left /
4326 cpi->twopass.total_left_stats.coded_error,
4327 cpi->tot_recode_hits);
4329 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4330 "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4332 cpi->common.current_video_frame,
4333 cpi->this_frame_target, cpi->projected_frame_size,
4334 (cpi->projected_frame_size - cpi->this_frame_target),
4335 (int)cpi->total_target_vs_actual,
4337 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4338 (int)cpi->total_actual_bits, cm->base_qindex,
4339 cpi->active_best_quality, cpi->active_worst_quality,
4340 cpi->ni_av_qi, cpi->cq_target_quality,
4341 cpi->zbin_over_quant,
4342 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4343 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4344 cm->frame_type, cpi->gfu_boost,
4345 cpi->twopass.est_max_qcorrection_factor,
4346 (int)cpi->twopass.bits_left,
4347 cpi->twopass.total_left_stats.coded_error,
4348 cpi->tot_recode_hits);
4353 FILE *fmodes = fopen("Modes.stt", "a");
4356 fprintf(fmodes, "%6d:%1d:%1d:%1d ",
4357 cpi->common.current_video_frame,
4358 cm->frame_type, cm->refresh_golden_frame,
4359 cm->refresh_alt_ref_frame);
4361 for (i = 0; i < MAX_MODES; i++)
4362 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
4364 fprintf(fmodes, "\n");
4372 // If this was a kf or Gf note the Q
4373 if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4374 cm->last_kf_gf_q = cm->base_qindex;
4376 if (cm->refresh_golden_frame == 1)
4377 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
4379 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
4381 if (cm->refresh_alt_ref_frame == 1)
4382 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
4384 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
4387 if (cm->refresh_last_frame & cm->refresh_golden_frame) // both refreshed
4388 cpi->gold_is_last = 1;
4389 else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4390 cpi->gold_is_last = 0;
4392 if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) // both refreshed
4393 cpi->alt_is_last = 1;
4394 else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) // 1 refreshed but not the other
4395 cpi->alt_is_last = 0;
4397 if (cm->refresh_alt_ref_frame & cm->refresh_golden_frame) // both refreshed
4398 cpi->gold_is_alt = 1;
4399 else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4400 cpi->gold_is_alt = 0;
4402 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
4404 if (cpi->gold_is_last)
4405 cpi->ref_frame_flags &= ~VP8_GOLD_FLAG;
4407 if (cpi->alt_is_last)
4408 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4410 if (cpi->gold_is_alt)
4411 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4414 if (!cpi->oxcf.error_resilient_mode)
4416 if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame && (cm->frame_type != KEY_FRAME))
4417 // Update the alternate reference frame stats as appropriate.
4418 update_alt_ref_frame_stats(cpi);
4420 // Update the Golden frame stats as appropriate.
4421 update_golden_frame_stats(cpi);
4424 if (cm->frame_type == KEY_FRAME)
4426 // Tell the caller that the frame was coded as a key frame
4427 *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
4429 // As this frame is a key frame the next defaults to an inter frame.
4430 cm->frame_type = INTER_FRAME;
4432 cpi->last_frame_percent_intra = 100;
4436 *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
4438 cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
4441 // Clear the one shot update flags for segmentation map and mode/ref loop filter deltas.
4442 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
4443 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
4444 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
4447 // Dont increment frame counters if this was an altref buffer update not a real frame
4450 cm->current_video_frame++;
4451 cpi->frames_since_key++;
4454 // reset to normal state now that we are done.
4462 sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
4463 recon_file = fopen(filename, "wb");
4464 fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
4465 cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
4471 //vp8_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show);
4477 static void check_gf_quality(VP8_COMP *cpi)
4479 VP8_COMMON *cm = &cpi->common;
4480 int gf_active_pct = (100 * cpi->gf_active_count) / (cm->mb_rows * cm->mb_cols);
4481 int gf_ref_usage_pct = (cpi->count_mb_ref_frame_usage[GOLDEN_FRAME] * 100) / (cm->mb_rows * cm->mb_cols);
4482 int last_ref_zz_useage = (cpi->inter_zz_count * 100) / (cm->mb_rows * cm->mb_cols);
4484 // Gf refresh is not currently being signalled
4485 if (cpi->gf_update_recommended == 0)
4487 if (cpi->common.frames_since_golden > 7)
4490 if ((gf_active_pct < 10) || ((gf_active_pct + gf_ref_usage_pct) < 15))
4492 // ...but last frame zero zero usage is reasonbable so a new gf might be appropriate
4493 if (last_ref_zz_useage >= 25)
4495 cpi->gf_bad_count ++;
4497 if (cpi->gf_bad_count >= 8) // Check that the condition is stable
4499 cpi->gf_update_recommended = 1;
4500 cpi->gf_bad_count = 0;
4504 cpi->gf_bad_count = 0; // Restart count as the background is not stable enough
4507 cpi->gf_bad_count = 0; // Gf useage has picked up so reset count
4510 // If the signal is set but has not been read should we cancel it.
4511 else if (last_ref_zz_useage < 15)
4513 cpi->gf_update_recommended = 0;
4514 cpi->gf_bad_count = 0;
4519 FILE *f = fopen("gfneeded.stt", "a");
4520 fprintf(f, "%10d %10d %10d %10d %10ld \n",
4521 cm->current_video_frame,
4522 cpi->common.frames_since_golden,
4523 gf_active_pct, gf_ref_usage_pct,
4524 cpi->gf_update_recommended);
4531 #if !(CONFIG_REALTIME_ONLY)
4532 static void Pass2Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned char * dest_end, unsigned int *frame_flags)
4535 if (!cpi->common.refresh_alt_ref_frame)
4536 vp8_second_pass(cpi);
4538 encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
4539 cpi->twopass.bits_left -= 8 * *size;
4541 if (!cpi->common.refresh_alt_ref_frame)
4543 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
4544 *cpi->oxcf.two_pass_vbrmin_section / 100);
4545 cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->frame_rate);
4550 //For ARM NEON, d8-d15 are callee-saved registers, and need to be saved by us.
4552 extern void vp8_push_neon(int64_t *store);
4553 extern void vp8_pop_neon(int64_t *store);
4557 int vp8_receive_raw_frame(VP8_COMP *cpi, unsigned int frame_flags, YV12_BUFFER_CONFIG *sd, int64_t time_stamp, int64_t end_time)
4560 int64_t store_reg[8];
4562 VP8_COMMON *cm = &cpi->common;
4563 struct vpx_usec_timer timer;
4567 #if CONFIG_RUNTIME_CPU_DETECT
4568 if (cm->cpu_caps & HAS_NEON)
4571 vp8_push_neon(store_reg);
4575 vpx_usec_timer_start(&timer);
4577 /* Reinit the lookahead buffer if the frame size changes */
4578 if (sd->y_width != cpi->oxcf.Width || sd->y_height != cpi->oxcf.Height)
4580 assert(cpi->oxcf.lag_in_frames < 2);
4581 dealloc_raw_frame_buffers(cpi);
4582 alloc_raw_frame_buffers(cpi);
4585 if(vp8_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4586 frame_flags, cpi->active_map_enabled ? cpi->active_map : NULL))
4588 cm->clr_type = sd->clrtype;
4589 vpx_usec_timer_mark(&timer);
4590 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4593 #if CONFIG_RUNTIME_CPU_DETECT
4594 if (cm->cpu_caps & HAS_NEON)
4597 vp8_pop_neon(store_reg);
4605 static int frame_is_reference(const VP8_COMP *cpi)
4607 const VP8_COMMON *cm = &cpi->common;
4608 const MACROBLOCKD *xd = &cpi->mb.e_mbd;
4610 return cm->frame_type == KEY_FRAME || cm->refresh_last_frame
4611 || cm->refresh_golden_frame || cm->refresh_alt_ref_frame
4612 || cm->copy_buffer_to_gf || cm->copy_buffer_to_arf
4613 || cm->refresh_entropy_probs
4614 || xd->mode_ref_lf_delta_update
4615 || xd->update_mb_segmentation_map || xd->update_mb_segmentation_data;
4619 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)
4622 int64_t store_reg[8];
4625 struct vpx_usec_timer tsctimer;
4626 struct vpx_usec_timer ticktimer;
4627 struct vpx_usec_timer cmptimer;
4628 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4635 if (setjmp(cpi->common.error.jmp))
4637 cpi->common.error.setjmp = 0;
4638 return VPX_CODEC_CORRUPT_FRAME;
4641 cpi->common.error.setjmp = 1;
4644 #if CONFIG_RUNTIME_CPU_DETECT
4645 if (cm->cpu_caps & HAS_NEON)
4648 vp8_push_neon(store_reg);
4652 vpx_usec_timer_start(&cmptimer);
4656 #if !(CONFIG_REALTIME_ONLY)
4657 // Should we code an alternate reference frame
4658 if (cpi->oxcf.error_resilient_mode == 0 &&
4659 cpi->oxcf.play_alternate &&
4660 cpi->source_alt_ref_pending)
4662 if ((cpi->source = vp8_lookahead_peek(cpi->lookahead,
4663 cpi->frames_till_gf_update_due)))
4665 cpi->alt_ref_source = cpi->source;
4666 if (cpi->oxcf.arnr_max_frames > 0)
4668 vp8_temporal_filter_prepare_c(cpi,
4669 cpi->frames_till_gf_update_due);
4670 force_src_buffer = &cpi->alt_ref_buffer;
4672 cm->frames_till_alt_ref_frame = cpi->frames_till_gf_update_due;
4673 cm->refresh_alt_ref_frame = 1;
4674 cm->refresh_golden_frame = 0;
4675 cm->refresh_last_frame = 0;
4677 cpi->source_alt_ref_pending = 0; // Clear Pending alt Ref flag.
4678 cpi->is_src_frame_alt_ref = 0;
4685 if ((cpi->source = vp8_lookahead_pop(cpi->lookahead, flush)))
4689 cpi->is_src_frame_alt_ref = cpi->alt_ref_source
4690 && (cpi->source == cpi->alt_ref_source);
4692 if(cpi->is_src_frame_alt_ref)
4693 cpi->alt_ref_source = NULL;
4699 cpi->Source = force_src_buffer ? force_src_buffer : &cpi->source->img;
4700 cpi->un_scaled_source = cpi->Source;
4701 *time_stamp = cpi->source->ts_start;
4702 *time_end = cpi->source->ts_end;
4703 *frame_flags = cpi->source->flags;
4708 #if !(CONFIG_REALTIME_ONLY)
4710 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done)
4712 vp8_end_first_pass(cpi); /* get last stats packet */
4713 cpi->twopass.first_pass_done = 1;
4719 #if CONFIG_RUNTIME_CPU_DETECT
4720 if (cm->cpu_caps & HAS_NEON)
4723 vp8_pop_neon(store_reg);
4729 if (cpi->source->ts_start < cpi->first_time_stamp_ever)
4731 cpi->first_time_stamp_ever = cpi->source->ts_start;
4732 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
4735 // adjust frame rates based on timestamps given
4736 if (!cm->refresh_alt_ref_frame || (cpi->oxcf.number_of_layers > 1))
4738 int64_t this_duration;
4741 if (cpi->source->ts_start == cpi->first_time_stamp_ever)
4743 this_duration = cpi->source->ts_end - cpi->source->ts_start;
4748 int64_t last_duration;
4750 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
4751 last_duration = cpi->last_end_time_stamp_seen
4752 - cpi->last_time_stamp_seen;
4753 // do a step update if the duration changes by 10%
4755 step = ((this_duration - last_duration) * 10 / last_duration);
4761 cpi->ref_frame_rate = 10000000.0 / this_duration;
4764 double avg_duration, interval;
4766 /* Average this frame's rate into the last second's average
4767 * frame rate. If we haven't seen 1 second yet, then average
4768 * over the whole interval seen.
4770 interval = cpi->source->ts_end - cpi->first_time_stamp_ever;
4771 if(interval > 10000000.0)
4772 interval = 10000000;
4774 avg_duration = 10000000.0 / cpi->ref_frame_rate;
4775 avg_duration *= (interval - avg_duration + this_duration);
4776 avg_duration /= interval;
4778 cpi->ref_frame_rate = 10000000.0 / avg_duration;
4781 if (cpi->oxcf.number_of_layers > 1)
4785 // Update frame rates for each layer
4786 for (i=0; i<cpi->oxcf.number_of_layers; i++)
4788 LAYER_CONTEXT *lc = &cpi->layer_context[i];
4789 lc->frame_rate = cpi->ref_frame_rate /
4790 cpi->oxcf.rate_decimator[i];
4794 vp8_new_frame_rate(cpi, cpi->ref_frame_rate);
4797 cpi->last_time_stamp_seen = cpi->source->ts_start;
4798 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
4801 if (cpi->oxcf.number_of_layers > 1)
4805 update_layer_contexts (cpi);
4807 // Restore layer specific context & set frame rate
4808 layer = cpi->oxcf.layer_id[
4809 cm->current_video_frame % cpi->oxcf.periodicity];
4810 restore_layer_context (cpi, layer);
4811 vp8_new_frame_rate (cpi, cpi->layer_context[layer].frame_rate);
4814 if (cpi->compressor_speed == 2)
4816 if (cpi->oxcf.number_of_layers == 1)
4817 check_gf_quality(cpi);
4818 vpx_usec_timer_start(&tsctimer);
4819 vpx_usec_timer_start(&ticktimer);
4822 // start with a 0 size frame
4825 // Clear down mmx registers
4826 vp8_clear_system_state(); //__asm emms;
4828 cm->frame_type = INTER_FRAME;
4829 cm->frame_flags = *frame_flags;
4833 if (cm->refresh_alt_ref_frame)
4835 //cm->refresh_golden_frame = 1;
4836 cm->refresh_golden_frame = 0;
4837 cm->refresh_last_frame = 0;
4841 cm->refresh_golden_frame = 0;
4842 cm->refresh_last_frame = 1;
4846 /* find a free buffer for the new frame */
4849 for(; i < NUM_YV12_BUFFERS; i++)
4851 if(!cm->yv12_fb[i].flags)
4858 assert(i < NUM_YV12_BUFFERS );
4860 #if !(CONFIG_REALTIME_ONLY)
4864 Pass1Encode(cpi, size, dest, frame_flags);
4866 else if (cpi->pass == 2)
4868 Pass2Encode(cpi, size, dest, dest_end, frame_flags);
4872 encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
4874 if (cpi->compressor_speed == 2)
4876 unsigned int duration, duration2;
4877 vpx_usec_timer_mark(&tsctimer);
4878 vpx_usec_timer_mark(&ticktimer);
4880 duration = vpx_usec_timer_elapsed(&ticktimer);
4881 duration2 = (unsigned int)((double)duration / 2);
4883 if (cm->frame_type != KEY_FRAME)
4885 if (cpi->avg_encode_time == 0)
4886 cpi->avg_encode_time = duration;
4888 cpi->avg_encode_time = (7 * cpi->avg_encode_time + duration) >> 3;
4893 //if(*frame_flags!=1)
4896 if (cpi->avg_pick_mode_time == 0)
4897 cpi->avg_pick_mode_time = duration2;
4899 cpi->avg_pick_mode_time = (7 * cpi->avg_pick_mode_time + duration2) >> 3;
4905 if (cm->refresh_entropy_probs == 0)
4907 vpx_memcpy(&cm->fc, &cm->lfc, sizeof(cm->fc));
4910 // Save the contexts separately for alt ref, gold and last.
4911 // (TODO jbb -> Optimize this with pointers to avoid extra copies. )
4912 if(cm->refresh_alt_ref_frame)
4913 vpx_memcpy(&cpi->lfc_a, &cm->fc, sizeof(cm->fc));
4915 if(cm->refresh_golden_frame)
4916 vpx_memcpy(&cpi->lfc_g, &cm->fc, sizeof(cm->fc));
4918 if(cm->refresh_last_frame)
4919 vpx_memcpy(&cpi->lfc_n, &cm->fc, sizeof(cm->fc));
4921 // if its a dropped frame honor the requests on subsequent frames
4924 cpi->droppable = !frame_is_reference(cpi);
4926 // return to normal state
4927 cm->refresh_entropy_probs = 1;
4928 cm->refresh_alt_ref_frame = 0;
4929 cm->refresh_golden_frame = 0;
4930 cm->refresh_last_frame = 1;
4931 cm->frame_type = INTER_FRAME;
4935 // Save layer specific state
4936 if (cpi->oxcf.number_of_layers > 1)
4937 save_layer_context (cpi);
4939 vpx_usec_timer_mark(&cmptimer);
4940 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4942 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
4944 generate_psnr_packet(cpi);
4947 #if CONFIG_INTERNAL_STATS
4951 cpi->bytes += *size;
4958 if (cpi->b_calculate_psnr)
4962 YV12_BUFFER_CONFIG *orig = cpi->Source;
4963 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
4964 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
4965 int y_samples = orig->y_height * orig->y_width ;
4966 int uv_samples = orig->uv_height * orig->uv_width ;
4967 int t_samples = y_samples + 2 * uv_samples;
4968 int64_t sq_error, sq_error2;
4970 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
4971 recon->y_buffer, recon->y_stride, orig->y_width, orig->y_height);
4973 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
4974 recon->u_buffer, recon->uv_stride, orig->uv_width, orig->uv_height);
4976 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
4977 recon->v_buffer, recon->uv_stride, orig->uv_width, orig->uv_height);
4979 sq_error = ye + ue + ve;
4981 frame_psnr = vp8_mse2psnr(t_samples, 255.0, sq_error);
4983 cpi->total_y += vp8_mse2psnr(y_samples, 255.0, ye);
4984 cpi->total_u += vp8_mse2psnr(uv_samples, 255.0, ue);
4985 cpi->total_v += vp8_mse2psnr(uv_samples, 255.0, ve);
4986 cpi->total_sq_error += sq_error;
4987 cpi->total += frame_psnr;
4989 double frame_psnr2, frame_ssim2 = 0;
4992 vp8_deblock(cm->frame_to_show, &cm->post_proc_buffer, cm->filter_level * 10 / 6, 1, 0);
4993 vp8_clear_system_state();
4995 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
4996 pp->y_buffer, pp->y_stride, orig->y_width, orig->y_height);
4998 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
4999 pp->u_buffer, pp->uv_stride, orig->uv_width, orig->uv_height);
5001 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
5002 pp->v_buffer, pp->uv_stride, orig->uv_width, orig->uv_height);
5004 sq_error2 = ye + ue + ve;
5006 frame_psnr2 = vp8_mse2psnr(t_samples, 255.0, sq_error2);
5008 cpi->totalp_y += vp8_mse2psnr(y_samples, 255.0, ye);
5009 cpi->totalp_u += vp8_mse2psnr(uv_samples, 255.0, ue);
5010 cpi->totalp_v += vp8_mse2psnr(uv_samples, 255.0, ve);
5011 cpi->total_sq_error2 += sq_error2;
5012 cpi->totalp += frame_psnr2;
5014 frame_ssim2 = vp8_calc_ssim(cpi->Source,
5015 &cm->post_proc_buffer, 1, &weight);
5017 cpi->summed_quality += frame_ssim2 * weight;
5018 cpi->summed_weights += weight;
5020 if (cpi->oxcf.number_of_layers > 1)
5024 for (i=cpi->current_layer;
5025 i<cpi->oxcf.number_of_layers; i++)
5027 cpi->frames_in_layer[i]++;
5029 cpi->bytes_in_layer[i] += *size;
5030 cpi->sum_psnr[i] += frame_psnr;
5031 cpi->sum_psnr_p[i] += frame_psnr2;
5032 cpi->total_error2[i] += sq_error;
5033 cpi->total_error2_p[i] += sq_error2;
5034 cpi->sum_ssim[i] += frame_ssim2 * weight;
5035 cpi->sum_weights[i] += weight;
5041 if (cpi->b_calculate_ssimg)
5043 double y, u, v, frame_all;
5044 frame_all = vp8_calc_ssimg(cpi->Source, cm->frame_to_show,
5047 if (cpi->oxcf.number_of_layers > 1)
5051 for (i=cpi->current_layer;
5052 i<cpi->oxcf.number_of_layers; i++)
5054 if (!cpi->b_calculate_psnr)
5055 cpi->frames_in_layer[i]++;
5057 cpi->total_ssimg_y_in_layer[i] += y;
5058 cpi->total_ssimg_u_in_layer[i] += u;
5059 cpi->total_ssimg_v_in_layer[i] += v;
5060 cpi->total_ssimg_all_in_layer[i] += frame_all;
5065 cpi->total_ssimg_y += y;
5066 cpi->total_ssimg_u += u;
5067 cpi->total_ssimg_v += v;
5068 cpi->total_ssimg_all += frame_all;
5077 if (cpi->common.frame_type != 0 && cpi->common.base_qindex == cpi->oxcf.worst_allowed_q)
5079 skiptruecount += cpi->skip_true_count;
5080 skipfalsecount += cpi->skip_false_count;
5088 FILE *f = fopen("skip.stt", "a");
5089 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);
5091 if (cpi->is_src_frame_alt_ref == 1)
5092 fprintf(f, "skipcount: %4d framesize: %d\n", cpi->skip_true_count , *size);
5101 #if CONFIG_RUNTIME_CPU_DETECT
5102 if (cm->cpu_caps & HAS_NEON)
5105 vp8_pop_neon(store_reg);
5109 cpi->common.error.setjmp = 0;
5114 int vp8_get_preview_raw_frame(VP8_COMP *cpi, YV12_BUFFER_CONFIG *dest, vp8_ppflags_t *flags)
5116 if (cpi->common.refresh_alt_ref_frame)
5122 #if CONFIG_MULTITHREAD
5123 if(cpi->b_lpf_running)
5125 sem_wait(&cpi->h_event_end_lpf);
5126 cpi->b_lpf_running = 0;
5131 ret = vp8_post_proc_frame(&cpi->common, dest, flags);
5134 if (cpi->common.frame_to_show)
5136 *dest = *cpi->common.frame_to_show;
5137 dest->y_width = cpi->common.Width;
5138 dest->y_height = cpi->common.Height;
5139 dest->uv_height = cpi->common.Height / 2;
5147 #endif //!CONFIG_POSTPROC
5148 vp8_clear_system_state();
5153 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])
5155 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
5157 if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
5162 disable_segmentation(cpi);
5166 // Set the segmentation Map
5167 set_segmentation_map(cpi, map);
5169 // Activate segmentation.
5170 enable_segmentation(cpi);
5172 // Set up the quant segment data
5173 feature_data[MB_LVL_ALT_Q][0] = delta_q[0];
5174 feature_data[MB_LVL_ALT_Q][1] = delta_q[1];
5175 feature_data[MB_LVL_ALT_Q][2] = delta_q[2];
5176 feature_data[MB_LVL_ALT_Q][3] = delta_q[3];
5178 // Set up the loop segment data s
5179 feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
5180 feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
5181 feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
5182 feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
5184 cpi->segment_encode_breakout[0] = threshold[0];
5185 cpi->segment_encode_breakout[1] = threshold[1];
5186 cpi->segment_encode_breakout[2] = threshold[2];
5187 cpi->segment_encode_breakout[3] = threshold[3];
5189 // Initialise the feature data structure
5190 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
5191 set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
5196 int vp8_set_active_map(VP8_COMP *cpi, unsigned char *map, unsigned int rows, unsigned int cols)
5198 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols)
5202 vpx_memcpy(cpi->active_map, map, rows * cols);
5203 cpi->active_map_enabled = 1;
5206 cpi->active_map_enabled = 0;
5212 //cpi->active_map_enabled = 0;
5217 int vp8_set_internal_size(VP8_COMP *cpi, VPX_SCALING horiz_mode, VPX_SCALING vert_mode)
5219 if (horiz_mode <= ONETWO)
5220 cpi->common.horiz_scale = horiz_mode;
5224 if (vert_mode <= ONETWO)
5225 cpi->common.vert_scale = vert_mode;
5234 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest)
5239 unsigned char *src = source->y_buffer;
5240 unsigned char *dst = dest->y_buffer;
5242 // Loop through the Y plane raw and reconstruction data summing (square differences)
5243 for (i = 0; i < source->y_height; i += 16)
5245 for (j = 0; j < source->y_width; j += 16)
5248 Total += vp8_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride, &sse);
5251 src += 16 * source->y_stride;
5252 dst += 16 * dest->y_stride;
5259 int vp8_get_quantizer(VP8_COMP *cpi)
5261 return cpi->common.base_qindex;