2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
12 #include "vpx_config.h"
13 #include "vp8/common/onyxc_int.h"
15 #include "vp8/common/systemdependent.h"
17 #include "vp8/common/alloccommon.h"
19 #include "firstpass.h"
21 #include "vpx_scale/vpxscale.h"
22 #include "vp8/common/extend.h"
24 #include "vp8/common/quant_common.h"
25 #include "segmentation.h"
26 #include "vp8/common/g_common.h"
27 #include "vpx_scale/yv12extend.h"
29 #include "vp8/common/postproc.h"
31 #include "vpx_mem/vpx_mem.h"
32 #include "vp8/common/swapyv12buffer.h"
33 #include "vp8/common/threading.h"
34 #include "vpx_ports/vpx_timer.h"
35 #include "temporal_filter.h"
37 #include "vpx_ports/arm.h"
44 #if CONFIG_RUNTIME_CPU_DETECT
45 #define IF_RTCD(x) (x)
46 #define RTCD(x) &cpi->common.rtcd.x
48 #define IF_RTCD(x) NULL
52 extern void vp8cx_pick_filter_level_fast(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
53 extern void vp8cx_set_alt_lf_level(VP8_COMP *cpi, int filt_val);
54 extern void vp8cx_pick_filter_level(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
56 extern void vp8_dmachine_specific_config(VP8_COMP *cpi);
57 extern void vp8_cmachine_specific_config(VP8_COMP *cpi);
58 extern void vp8_deblock_frame(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *post, int filt_lvl, int low_var_thresh, int flag);
59 extern void print_parms(VP8_CONFIG *ocf, char *filenam);
60 extern unsigned int vp8_get_processor_freq();
61 extern void print_tree_update_probs();
62 extern void vp8cx_create_encoder_threads(VP8_COMP *cpi);
63 extern void vp8cx_remove_encoder_threads(VP8_COMP *cpi);
65 extern void vp8_yv12_copy_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
66 extern void vp8_yv12_copy_src_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
69 int vp8_estimate_entropy_savings(VP8_COMP *cpi);
70 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd);
72 extern void vp8_temporal_filter_prepare_c(VP8_COMP *cpi, int distance);
74 static void set_default_lf_deltas(VP8_COMP *cpi);
76 extern const int vp8_gf_interval_table[101];
78 #if CONFIG_INTERNAL_STATS
81 extern double vp8_calc_ssim
83 YV12_BUFFER_CONFIG *source,
84 YV12_BUFFER_CONFIG *dest,
87 const vp8_variance_rtcd_vtable_t *rtcd
91 extern double vp8_calc_ssimg
93 YV12_BUFFER_CONFIG *source,
94 YV12_BUFFER_CONFIG *dest,
98 const vp8_variance_rtcd_vtable_t *rtcd
105 #ifdef OUTPUT_YUV_SRC
116 extern int skip_true_count;
117 extern int skip_false_count;
122 extern int intra_mode_stats[10][10][10];
126 unsigned int frames_at_speed[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
127 unsigned int tot_pm = 0;
128 unsigned int cnt_pm = 0;
129 unsigned int tot_ef = 0;
130 unsigned int cnt_ef = 0;
134 extern unsigned __int64 Sectionbits[50];
135 extern int y_modes[5] ;
136 extern int uv_modes[4] ;
137 extern int b_modes[10] ;
139 extern int inter_y_modes[10] ;
140 extern int inter_uv_modes[4] ;
141 extern unsigned int inter_b_modes[15];
144 extern void (*vp8_short_fdct4x4)(short *input, short *output, int pitch);
145 extern void (*vp8_short_fdct8x4)(short *input, short *output, int pitch);
147 extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
149 extern const int qrounding_factors[129];
150 extern const int qzbin_factors[129];
151 extern void vp8cx_init_quantizer(VP8_COMP *cpi);
152 extern const int vp8cx_base_skip_false_prob[128];
154 // Tables relating active max Q to active min Q
155 static const int kf_low_motion_minq[QINDEX_RANGE] =
157 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
158 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
159 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
160 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
161 3,3,3,3,3,3,4,4,4,5,5,5,5,5,6,6,
162 6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
163 11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
164 16,16,17,17,18,18,18,18,19,20,20,21,21,22,23,23
166 static const int kf_high_motion_minq[QINDEX_RANGE] =
168 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
169 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
170 1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,
171 3,3,3,3,4,4,4,4,5,5,5,5,5,5,6,6,
172 6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
173 11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
174 16,16,17,17,18,18,18,18,19,19,20,20,20,20,21,21,
175 21,21,22,22,23,23,24,25,25,26,26,27,28,28,29,30
177 static const int gf_low_motion_minq[QINDEX_RANGE] =
179 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
180 3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,
181 7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,
182 11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,
183 19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,
184 27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,
185 35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,
186 43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58
188 static const int gf_mid_motion_minq[QINDEX_RANGE] =
190 0,0,0,0,1,1,1,1,1,1,2,2,3,3,3,4,
191 4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
192 9,10,10,10,10,11,11,11,12,12,12,12,13,13,13,14,
193 14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,
194 22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,
195 30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,
196 38,39,39,40,40,41,41,42,42,43,43,44,45,46,47,48,
197 49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64
199 static const int gf_high_motion_minq[QINDEX_RANGE] =
201 0,0,0,0,1,1,1,1,1,2,2,2,3,3,3,4,
202 4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
203 9,10,10,10,11,11,12,12,13,13,14,14,15,15,16,16,
204 17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,
205 25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,
206 33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,
207 41,41,42,42,43,44,45,46,47,48,49,50,51,52,53,54,
208 55,56,57,58,59,60,62,64,66,68,70,72,74,76,78,80
210 static const int inter_minq[QINDEX_RANGE] =
212 0,0,1,1,2,3,3,4,4,5,6,6,7,8,8,9,
213 9,10,11,11,12,13,13,14,15,15,16,17,17,18,19,20,
214 20,21,22,22,23,24,24,25,26,27,27,28,29,30,30,31,
215 32,33,33,34,35,36,36,37,38,39,39,40,41,42,42,43,
216 44,45,46,46,47,48,49,50,50,51,52,53,54,55,55,56,
217 57,58,59,60,60,61,62,63,64,65,66,67,67,68,69,70,
218 71,72,73,74,75,75,76,77,78,79,80,81,82,83,84,85,
219 86,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
222 void vp8_initialize()
224 static int init_done = 0;
228 vp8_scale_machine_specific_config();
229 vp8_initialize_common();
230 //vp8_dmachine_specific_config();
231 vp8_tokenize_initialize();
236 #ifdef PACKET_TESTING
237 extern FILE *vpxlogc;
240 static void setup_features(VP8_COMP *cpi)
242 // Set up default state for MB feature flags
243 cpi->mb.e_mbd.segmentation_enabled = 0;
244 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
245 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
246 vpx_memset(cpi->mb.e_mbd.mb_segment_tree_probs, 255, sizeof(cpi->mb.e_mbd.mb_segment_tree_probs));
247 vpx_memset(cpi->mb.e_mbd.segment_feature_data, 0, sizeof(cpi->mb.e_mbd.segment_feature_data));
249 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 0;
250 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
251 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
252 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
253 vpx_memset(cpi->mb.e_mbd.last_ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
254 vpx_memset(cpi->mb.e_mbd.last_mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
256 set_default_lf_deltas(cpi);
261 static void dealloc_compressor_data(VP8_COMP *cpi)
263 vpx_free(cpi->tplist);
266 // Delete last frame MV storage buffers
270 vpx_free(cpi->lf_ref_frame_sign_bias);
271 cpi->lf_ref_frame_sign_bias = 0;
273 vpx_free(cpi->lf_ref_frame);
274 cpi->lf_ref_frame = 0;
276 // Delete sementation map
277 vpx_free(cpi->segmentation_map);
278 cpi->segmentation_map = 0;
280 vpx_free(cpi->active_map);
283 vp8_de_alloc_frame_buffers(&cpi->common);
285 vp8_yv12_de_alloc_frame_buffer(&cpi->last_frame_uf);
286 vp8_yv12_de_alloc_frame_buffer(&cpi->scaled_source);
287 #if VP8_TEMPORAL_ALT_REF
288 vp8_yv12_de_alloc_frame_buffer(&cpi->alt_ref_buffer);
290 vp8_lookahead_destroy(cpi->lookahead);
295 // Structure used to monitor GF usage
296 vpx_free(cpi->gf_active_flags);
297 cpi->gf_active_flags = 0;
299 // Activity mask based per mb zbin adjustments
300 vpx_free(cpi->mb_activity_map);
301 cpi->mb_activity_map = 0;
302 vpx_free(cpi->mb_norm_activity_map);
303 cpi->mb_norm_activity_map = 0;
305 vpx_free(cpi->mb.pip);
308 #if !(CONFIG_REALTIME_ONLY)
309 vpx_free(cpi->twopass.total_stats);
310 cpi->twopass.total_stats = 0;
312 vpx_free(cpi->twopass.this_frame_stats);
313 cpi->twopass.this_frame_stats = 0;
317 static void enable_segmentation(VP8_PTR ptr)
319 VP8_COMP *cpi = (VP8_COMP *)(ptr);
321 // Set the appropriate feature bit
322 cpi->mb.e_mbd.segmentation_enabled = 1;
323 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
324 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
326 static void disable_segmentation(VP8_PTR ptr)
328 VP8_COMP *cpi = (VP8_COMP *)(ptr);
330 // Clear the appropriate feature bit
331 cpi->mb.e_mbd.segmentation_enabled = 0;
334 // Valid values for a segment are 0 to 3
335 // Segmentation map is arrange as [Rows][Columns]
336 static void set_segmentation_map(VP8_PTR ptr, unsigned char *segmentation_map)
338 VP8_COMP *cpi = (VP8_COMP *)(ptr);
340 // Copy in the new segmentation map
341 vpx_memcpy(cpi->segmentation_map, segmentation_map, (cpi->common.mb_rows * cpi->common.mb_cols));
343 // Signal that the map should be updated.
344 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
345 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
348 // The values given for each segment can be either deltas (from the default value chosen for the frame) or absolute values.
350 // Valid range for abs values is (0-127 for MB_LVL_ALT_Q) , (0-63 for SEGMENT_ALT_LF)
351 // Valid range for delta values are (+/-127 for MB_LVL_ALT_Q) , (+/-63 for SEGMENT_ALT_LF)
353 // abs_delta = SEGMENT_DELTADATA (deltas) abs_delta = SEGMENT_ABSDATA (use the absolute values given).
356 static void set_segment_data(VP8_PTR ptr, signed char *feature_data, unsigned char abs_delta)
358 VP8_COMP *cpi = (VP8_COMP *)(ptr);
360 cpi->mb.e_mbd.mb_segement_abs_delta = abs_delta;
361 vpx_memcpy(cpi->segment_feature_data, feature_data, sizeof(cpi->segment_feature_data));
365 static void segmentation_test_function(VP8_PTR ptr)
367 VP8_COMP *cpi = (VP8_COMP *)(ptr);
369 unsigned char *seg_map;
370 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
372 // Create a temporary map for segmentation data.
373 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
375 // MB loop to set local segmentation map
376 /*for ( i = 0; i < cpi->common.mb_rows; i++ )
378 for ( j = 0; j < cpi->common.mb_cols; j++ )
380 //seg_map[(i*cpi->common.mb_cols) + j] = (j % 2) + ((i%2)* 2);
381 //if ( j < cpi->common.mb_cols/2 )
383 // Segment 1 around the edge else 0
384 if ( (i == 0) || (j == 0) || (i == (cpi->common.mb_rows-1)) || (j == (cpi->common.mb_cols-1)) )
385 seg_map[(i*cpi->common.mb_cols) + j] = 1;
386 //else if ( (i < 2) || (j < 2) || (i > (cpi->common.mb_rows-3)) || (j > (cpi->common.mb_cols-3)) )
387 // seg_map[(i*cpi->common.mb_cols) + j] = 2;
388 //else if ( (i < 5) || (j < 5) || (i > (cpi->common.mb_rows-6)) || (j > (cpi->common.mb_cols-6)) )
389 // seg_map[(i*cpi->common.mb_cols) + j] = 3;
391 seg_map[(i*cpi->common.mb_cols) + j] = 0;
395 // Set the segmentation Map
396 set_segmentation_map(ptr, seg_map);
398 // Activate segmentation.
399 enable_segmentation(ptr);
401 // Set up the quant segment data
402 feature_data[MB_LVL_ALT_Q][0] = 0;
403 feature_data[MB_LVL_ALT_Q][1] = 4;
404 feature_data[MB_LVL_ALT_Q][2] = 0;
405 feature_data[MB_LVL_ALT_Q][3] = 0;
406 // Set up the loop segment data
407 feature_data[MB_LVL_ALT_LF][0] = 0;
408 feature_data[MB_LVL_ALT_LF][1] = 0;
409 feature_data[MB_LVL_ALT_LF][2] = 0;
410 feature_data[MB_LVL_ALT_LF][3] = 0;
412 // Initialise the feature data structure
413 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
414 set_segment_data(ptr, &feature_data[0][0], SEGMENT_DELTADATA);
416 // Delete sementation map
423 // A simple function to cyclically refresh the background at a lower Q
424 static void cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment)
426 unsigned char *seg_map;
427 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
429 int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
430 int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
432 // Create a temporary map for segmentation data.
433 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
435 cpi->cyclic_refresh_q = Q;
437 for (i = Q; i > 0; i--)
439 if (vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*(Q + 128)) / 64))
440 //if ( vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*((2*Q)+96))/64) )
446 cpi->cyclic_refresh_q = i;
448 // Only update for inter frames
449 if (cpi->common.frame_type != KEY_FRAME)
451 // Cycle through the macro_block rows
452 // MB loop to set local segmentation map
453 for (i = cpi->cyclic_refresh_mode_index; i < mbs_in_frame; i++)
455 // If the MB is as a candidate for clean up then mark it for possible boost/refresh (segment 1)
456 // The segment id may get reset to 0 later if the MB gets coded anything other than last frame 0,0
457 // as only (last frame 0,0) MBs are eligable for refresh : that is to say Mbs likely to be background blocks.
458 if (cpi->cyclic_refresh_map[i] == 0)
466 // Skip blocks that have been refreshed recently anyway.
467 if (cpi->cyclic_refresh_map[i] < 0)
468 //cpi->cyclic_refresh_map[i] = cpi->cyclic_refresh_map[i] / 16;
469 cpi->cyclic_refresh_map[i]++;
480 // If we have gone through the frame reset to the start
481 cpi->cyclic_refresh_mode_index = i;
483 if (cpi->cyclic_refresh_mode_index >= mbs_in_frame)
484 cpi->cyclic_refresh_mode_index = 0;
487 // Set the segmentation Map
488 set_segmentation_map((VP8_PTR)cpi, seg_map);
490 // Activate segmentation.
491 enable_segmentation((VP8_PTR)cpi);
493 // Set up the quant segment data
494 feature_data[MB_LVL_ALT_Q][0] = 0;
495 feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
496 feature_data[MB_LVL_ALT_Q][2] = 0;
497 feature_data[MB_LVL_ALT_Q][3] = 0;
499 // Set up the loop segment data
500 feature_data[MB_LVL_ALT_LF][0] = 0;
501 feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
502 feature_data[MB_LVL_ALT_LF][2] = 0;
503 feature_data[MB_LVL_ALT_LF][3] = 0;
505 // Initialise the feature data structure
506 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
507 set_segment_data((VP8_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
509 // Delete sementation map
516 static void set_default_lf_deltas(VP8_COMP *cpi)
518 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 1;
519 cpi->mb.e_mbd.mode_ref_lf_delta_update = 1;
521 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
522 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
524 // Test of ref frame deltas
525 cpi->mb.e_mbd.ref_lf_deltas[INTRA_FRAME] = 2;
526 cpi->mb.e_mbd.ref_lf_deltas[LAST_FRAME] = 0;
527 cpi->mb.e_mbd.ref_lf_deltas[GOLDEN_FRAME] = -2;
528 cpi->mb.e_mbd.ref_lf_deltas[ALTREF_FRAME] = -2;
530 cpi->mb.e_mbd.mode_lf_deltas[0] = 4; // BPRED
531 cpi->mb.e_mbd.mode_lf_deltas[1] = -2; // Zero
532 cpi->mb.e_mbd.mode_lf_deltas[2] = 2; // New mv
533 cpi->mb.e_mbd.mode_lf_deltas[3] = 4; // Split mv
536 void vp8_set_speed_features(VP8_COMP *cpi)
538 SPEED_FEATURES *sf = &cpi->sf;
539 int Mode = cpi->compressor_speed;
540 int Speed = cpi->Speed;
542 VP8_COMMON *cm = &cpi->common;
543 int last_improved_quant = sf->improved_quant;
545 // Initialise default mode frequency sampling variables
546 for (i = 0; i < MAX_MODES; i ++)
548 cpi->mode_check_freq[i] = 0;
549 cpi->mode_test_hit_counts[i] = 0;
550 cpi->mode_chosen_counts[i] = 0;
553 cpi->mbs_tested_so_far = 0;
555 // best quality defaults
557 sf->search_method = NSTEP;
558 sf->improved_quant = 1;
559 sf->improved_dct = 1;
562 sf->quarter_pixel_search = 1;
563 sf->half_pixel_search = 1;
564 sf->iterative_sub_pixel = 1;
565 sf->optimize_coefficients = 1;
566 sf->use_fastquant_for_pick = 0;
567 sf->no_skip_block4x4_search = 1;
570 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
571 sf->improved_mv_pred = 1;
573 // default thresholds to 0
574 for (i = 0; i < MAX_MODES; i++)
575 sf->thresh_mult[i] = 0;
579 #if !(CONFIG_REALTIME_ONLY)
580 case 0: // best quality mode
581 sf->thresh_mult[THR_ZEROMV ] = 0;
582 sf->thresh_mult[THR_ZEROG ] = 0;
583 sf->thresh_mult[THR_ZEROA ] = 0;
584 sf->thresh_mult[THR_NEARESTMV] = 0;
585 sf->thresh_mult[THR_NEARESTG ] = 0;
586 sf->thresh_mult[THR_NEARESTA ] = 0;
587 sf->thresh_mult[THR_NEARMV ] = 0;
588 sf->thresh_mult[THR_NEARG ] = 0;
589 sf->thresh_mult[THR_NEARA ] = 0;
591 sf->thresh_mult[THR_DC ] = 0;
593 sf->thresh_mult[THR_V_PRED ] = 1000;
594 sf->thresh_mult[THR_H_PRED ] = 1000;
595 sf->thresh_mult[THR_B_PRED ] = 2000;
596 sf->thresh_mult[THR_TM ] = 1000;
598 sf->thresh_mult[THR_NEWMV ] = 1000;
599 sf->thresh_mult[THR_NEWG ] = 1000;
600 sf->thresh_mult[THR_NEWA ] = 1000;
602 sf->thresh_mult[THR_SPLITMV ] = 2500;
603 sf->thresh_mult[THR_SPLITG ] = 5000;
604 sf->thresh_mult[THR_SPLITA ] = 5000;
608 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
612 sf->thresh_mult[THR_NEARESTMV] = 0;
613 sf->thresh_mult[THR_ZEROMV ] = 0;
614 sf->thresh_mult[THR_DC ] = 0;
615 sf->thresh_mult[THR_NEARMV ] = 0;
616 sf->thresh_mult[THR_V_PRED ] = 1000;
617 sf->thresh_mult[THR_H_PRED ] = 1000;
618 sf->thresh_mult[THR_B_PRED ] = 2500;
619 sf->thresh_mult[THR_TM ] = 1000;
621 sf->thresh_mult[THR_NEARESTG ] = 1000;
622 sf->thresh_mult[THR_NEARESTA ] = 1000;
624 sf->thresh_mult[THR_ZEROG ] = 1000;
625 sf->thresh_mult[THR_ZEROA ] = 1000;
626 sf->thresh_mult[THR_NEARG ] = 1000;
627 sf->thresh_mult[THR_NEARA ] = 1000;
630 sf->thresh_mult[THR_ZEROMV ] = 0;
631 sf->thresh_mult[THR_ZEROG ] = 0;
632 sf->thresh_mult[THR_ZEROA ] = 0;
633 sf->thresh_mult[THR_NEARESTMV] = 0;
634 sf->thresh_mult[THR_NEARESTG ] = 0;
635 sf->thresh_mult[THR_NEARESTA ] = 0;
636 sf->thresh_mult[THR_NEARMV ] = 0;
637 sf->thresh_mult[THR_NEARG ] = 0;
638 sf->thresh_mult[THR_NEARA ] = 0;
640 // sf->thresh_mult[THR_DC ] = 0;
642 // sf->thresh_mult[THR_V_PRED ] = 1000;
643 // sf->thresh_mult[THR_H_PRED ] = 1000;
644 // sf->thresh_mult[THR_B_PRED ] = 2000;
645 // sf->thresh_mult[THR_TM ] = 1000;
647 sf->thresh_mult[THR_NEWMV ] = 1000;
648 sf->thresh_mult[THR_NEWG ] = 1000;
649 sf->thresh_mult[THR_NEWA ] = 1000;
651 sf->thresh_mult[THR_SPLITMV ] = 1700;
652 sf->thresh_mult[THR_SPLITG ] = 4500;
653 sf->thresh_mult[THR_SPLITA ] = 4500;
655 sf->thresh_mult[THR_NEWMV ] = 1500;
656 sf->thresh_mult[THR_NEWG ] = 1500;
657 sf->thresh_mult[THR_NEWA ] = 1500;
659 sf->thresh_mult[THR_SPLITMV ] = 5000;
660 sf->thresh_mult[THR_SPLITG ] = 10000;
661 sf->thresh_mult[THR_SPLITA ] = 10000;
666 /* Disable coefficient optimization above speed 0 */
667 sf->optimize_coefficients = 0;
668 sf->use_fastquant_for_pick = 1;
669 sf->no_skip_block4x4_search = 0;
673 cpi->mode_check_freq[THR_SPLITG] = 2;
674 cpi->mode_check_freq[THR_SPLITA] = 2;
675 cpi->mode_check_freq[THR_SPLITMV] = 0;
680 cpi->mode_check_freq[THR_SPLITG] = 4;
681 cpi->mode_check_freq[THR_SPLITA] = 4;
682 cpi->mode_check_freq[THR_SPLITMV] = 2;
684 sf->thresh_mult[THR_TM ] = 1500;
685 sf->thresh_mult[THR_V_PRED ] = 1500;
686 sf->thresh_mult[THR_H_PRED ] = 1500;
687 sf->thresh_mult[THR_B_PRED ] = 5000;
689 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
691 sf->thresh_mult[THR_NEWMV ] = 2000;
692 sf->thresh_mult[THR_SPLITMV ] = 10000;
695 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
697 sf->thresh_mult[THR_NEARESTG ] = 1500;
698 sf->thresh_mult[THR_ZEROG ] = 1500;
699 sf->thresh_mult[THR_NEARG ] = 1500;
700 sf->thresh_mult[THR_NEWG ] = 2000;
701 sf->thresh_mult[THR_SPLITG ] = 20000;
704 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
706 sf->thresh_mult[THR_NEARESTA ] = 1500;
707 sf->thresh_mult[THR_ZEROA ] = 1500;
708 sf->thresh_mult[THR_NEARA ] = 1500;
709 sf->thresh_mult[THR_NEWA ] = 2000;
710 sf->thresh_mult[THR_SPLITA ] = 20000;
716 cpi->mode_check_freq[THR_SPLITG] = 15;
717 cpi->mode_check_freq[THR_SPLITA] = 15;
718 cpi->mode_check_freq[THR_SPLITMV] = 7;
720 sf->thresh_mult[THR_TM ] = 2000;
721 sf->thresh_mult[THR_V_PRED ] = 2000;
722 sf->thresh_mult[THR_H_PRED ] = 2000;
723 sf->thresh_mult[THR_B_PRED ] = 7500;
725 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
727 sf->thresh_mult[THR_NEWMV ] = 2000;
728 sf->thresh_mult[THR_SPLITMV ] = 25000;
731 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
733 sf->thresh_mult[THR_NEARESTG ] = 2000;
734 sf->thresh_mult[THR_ZEROG ] = 2000;
735 sf->thresh_mult[THR_NEARG ] = 2000;
736 sf->thresh_mult[THR_NEWG ] = 2500;
737 sf->thresh_mult[THR_SPLITG ] = 50000;
740 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
742 sf->thresh_mult[THR_NEARESTA ] = 2000;
743 sf->thresh_mult[THR_ZEROA ] = 2000;
744 sf->thresh_mult[THR_NEARA ] = 2000;
745 sf->thresh_mult[THR_NEWA ] = 2500;
746 sf->thresh_mult[THR_SPLITA ] = 50000;
749 sf->improved_quant = 0;
750 sf->improved_dct = 0;
752 // Only do recode loop on key frames, golden frames and
760 sf->thresh_mult[THR_SPLITA ] = INT_MAX;
761 sf->thresh_mult[THR_SPLITG ] = INT_MAX;
762 sf->thresh_mult[THR_SPLITMV ] = INT_MAX;
764 cpi->mode_check_freq[THR_V_PRED] = 0;
765 cpi->mode_check_freq[THR_H_PRED] = 0;
766 cpi->mode_check_freq[THR_B_PRED] = 0;
767 cpi->mode_check_freq[THR_NEARG] = 0;
768 cpi->mode_check_freq[THR_NEWG] = 0;
769 cpi->mode_check_freq[THR_NEARA] = 0;
770 cpi->mode_check_freq[THR_NEWA] = 0;
773 sf->recode_loop = 0; // recode loop off
774 sf->RD = 0; // Turn rd off
780 sf->auto_filter = 0; // Faster selection of loop filter
782 cpi->mode_check_freq[THR_V_PRED] = 2;
783 cpi->mode_check_freq[THR_H_PRED] = 2;
784 cpi->mode_check_freq[THR_B_PRED] = 2;
786 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
788 cpi->mode_check_freq[THR_NEARG] = 2;
789 cpi->mode_check_freq[THR_NEWG] = 4;
792 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
794 cpi->mode_check_freq[THR_NEARA] = 2;
795 cpi->mode_check_freq[THR_NEWA] = 4;
798 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
800 sf->thresh_mult[THR_NEARESTG ] = 2000;
801 sf->thresh_mult[THR_ZEROG ] = 2000;
802 sf->thresh_mult[THR_NEARG ] = 2000;
803 sf->thresh_mult[THR_NEWG ] = 4000;
806 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
808 sf->thresh_mult[THR_NEARESTA ] = 2000;
809 sf->thresh_mult[THR_ZEROA ] = 2000;
810 sf->thresh_mult[THR_NEARA ] = 2000;
811 sf->thresh_mult[THR_NEWA ] = 4000;
818 sf->optimize_coefficients = 0;
821 sf->iterative_sub_pixel = 1;
822 sf->thresh_mult[THR_NEARESTMV] = 0;
823 sf->thresh_mult[THR_ZEROMV ] = 0;
824 sf->thresh_mult[THR_DC ] = 0;
825 sf->thresh_mult[THR_TM ] = 0;
826 sf->thresh_mult[THR_NEARMV ] = 0;
827 sf->thresh_mult[THR_V_PRED ] = 1000;
828 sf->thresh_mult[THR_H_PRED ] = 1000;
829 sf->thresh_mult[THR_B_PRED ] = 2500;
830 sf->thresh_mult[THR_NEARESTG ] = 1000;
831 sf->thresh_mult[THR_ZEROG ] = 1000;
832 sf->thresh_mult[THR_NEARG ] = 1000;
833 sf->thresh_mult[THR_NEARESTA ] = 1000;
834 sf->thresh_mult[THR_ZEROA ] = 1000;
835 sf->thresh_mult[THR_NEARA ] = 1000;
836 sf->thresh_mult[THR_NEWMV ] = 2000;
837 sf->thresh_mult[THR_NEWG ] = 2000;
838 sf->thresh_mult[THR_NEWA ] = 2000;
839 sf->thresh_mult[THR_SPLITMV ] = 5000;
840 sf->thresh_mult[THR_SPLITG ] = 10000;
841 sf->thresh_mult[THR_SPLITA ] = 10000;
842 sf->search_method = NSTEP;
846 cpi->mode_check_freq[THR_SPLITG] = 4;
847 cpi->mode_check_freq[THR_SPLITA] = 4;
848 cpi->mode_check_freq[THR_SPLITMV] = 2;
850 sf->thresh_mult[THR_DC ] = 0;
851 sf->thresh_mult[THR_TM ] = 1000;
852 sf->thresh_mult[THR_V_PRED ] = 2000;
853 sf->thresh_mult[THR_H_PRED ] = 2000;
854 sf->thresh_mult[THR_B_PRED ] = 5000;
856 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
858 sf->thresh_mult[THR_NEARESTMV] = 0;
859 sf->thresh_mult[THR_ZEROMV ] = 0;
860 sf->thresh_mult[THR_NEARMV ] = 0;
861 sf->thresh_mult[THR_NEWMV ] = 2000;
862 sf->thresh_mult[THR_SPLITMV ] = 10000;
865 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
867 sf->thresh_mult[THR_NEARESTG ] = 1000;
868 sf->thresh_mult[THR_ZEROG ] = 1000;
869 sf->thresh_mult[THR_NEARG ] = 1000;
870 sf->thresh_mult[THR_NEWG ] = 2000;
871 sf->thresh_mult[THR_SPLITG ] = 20000;
874 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
876 sf->thresh_mult[THR_NEARESTA ] = 1000;
877 sf->thresh_mult[THR_ZEROA ] = 1000;
878 sf->thresh_mult[THR_NEARA ] = 1000;
879 sf->thresh_mult[THR_NEWA ] = 2000;
880 sf->thresh_mult[THR_SPLITA ] = 20000;
883 sf->improved_quant = 0;
884 sf->improved_dct = 0;
886 sf->use_fastquant_for_pick = 1;
887 sf->no_skip_block4x4_search = 0;
893 cpi->mode_check_freq[THR_SPLITMV] = 7;
894 cpi->mode_check_freq[THR_SPLITG] = 15;
895 cpi->mode_check_freq[THR_SPLITA] = 15;
897 sf->thresh_mult[THR_TM ] = 2000;
898 sf->thresh_mult[THR_V_PRED ] = 2000;
899 sf->thresh_mult[THR_H_PRED ] = 2000;
900 sf->thresh_mult[THR_B_PRED ] = 5000;
902 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
904 sf->thresh_mult[THR_NEWMV ] = 2000;
905 sf->thresh_mult[THR_SPLITMV ] = 25000;
908 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
910 sf->thresh_mult[THR_NEARESTG ] = 2000;
911 sf->thresh_mult[THR_ZEROG ] = 2000;
912 sf->thresh_mult[THR_NEARG ] = 2000;
913 sf->thresh_mult[THR_NEWG ] = 2500;
914 sf->thresh_mult[THR_SPLITG ] = 50000;
917 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
919 sf->thresh_mult[THR_NEARESTA ] = 2000;
920 sf->thresh_mult[THR_ZEROA ] = 2000;
921 sf->thresh_mult[THR_NEARA ] = 2000;
922 sf->thresh_mult[THR_NEWA ] = 2500;
923 sf->thresh_mult[THR_SPLITA ] = 50000;
930 sf->auto_filter = 0; // Faster selection of loop filter
932 cpi->mode_check_freq[THR_V_PRED] = 2;
933 cpi->mode_check_freq[THR_H_PRED] = 2;
934 cpi->mode_check_freq[THR_B_PRED] = 2;
936 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
938 cpi->mode_check_freq[THR_NEARG] = 2;
939 cpi->mode_check_freq[THR_NEWG] = 4;
942 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
944 cpi->mode_check_freq[THR_NEARA] = 2;
945 cpi->mode_check_freq[THR_NEWA] = 4;
948 sf->thresh_mult[THR_SPLITMV ] = INT_MAX;
949 sf->thresh_mult[THR_SPLITG ] = INT_MAX;
950 sf->thresh_mult[THR_SPLITA ] = INT_MAX;
963 sf->auto_filter = 0; // Faster selection of loop filter
965 sf->search_method = HEX;
966 //sf->search_method = DIAMOND;
968 sf->iterative_sub_pixel = 0;
970 cpi->mode_check_freq[THR_V_PRED] = 4;
971 cpi->mode_check_freq[THR_H_PRED] = 4;
972 cpi->mode_check_freq[THR_B_PRED] = 4;
974 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
976 cpi->mode_check_freq[THR_NEARG] = 2;
977 cpi->mode_check_freq[THR_NEWG] = 4;
980 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
982 cpi->mode_check_freq[THR_NEARA] = 2;
983 cpi->mode_check_freq[THR_NEWA] = 4;
986 sf->thresh_mult[THR_TM ] = 2000;
987 sf->thresh_mult[THR_B_PRED ] = 5000;
989 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
991 sf->thresh_mult[THR_NEARESTG ] = 2000;
992 sf->thresh_mult[THR_ZEROG ] = 2000;
993 sf->thresh_mult[THR_NEARG ] = 2000;
994 sf->thresh_mult[THR_NEWG ] = 4000;
997 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
999 sf->thresh_mult[THR_NEARESTA ] = 2000;
1000 sf->thresh_mult[THR_ZEROA ] = 2000;
1001 sf->thresh_mult[THR_NEARA ] = 2000;
1002 sf->thresh_mult[THR_NEWA ] = 4000;
1008 // Disable split MB intra prediction mode
1009 sf->thresh_mult[THR_B_PRED] = INT_MAX;
1014 unsigned int i, sum = 0;
1015 unsigned int total_mbs = cm->MBs;
1021 if (cpi->oxcf.encode_breakout > 2000)
1022 min = cpi->oxcf.encode_breakout;
1026 for (i = 0; i < min; i++)
1028 sum += cpi->error_bins[i];
1034 // i starts from 2 to make sure thresh started from 2048
1035 for (; i < 1024; i++)
1037 sum += cpi->error_bins[i];
1039 if (10 * sum >= (unsigned int)(cpi->Speed - 6)*(total_mbs - total_skip))
1049 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
1051 sf->thresh_mult[THR_NEWMV] = thresh;
1052 sf->thresh_mult[THR_NEARESTMV ] = thresh >> 1;
1053 sf->thresh_mult[THR_NEARMV ] = thresh >> 1;
1056 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
1058 sf->thresh_mult[THR_NEWG] = thresh << 1;
1059 sf->thresh_mult[THR_NEARESTG ] = thresh;
1060 sf->thresh_mult[THR_NEARG ] = thresh;
1063 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
1065 sf->thresh_mult[THR_NEWA] = thresh << 1;
1066 sf->thresh_mult[THR_NEARESTA ] = thresh;
1067 sf->thresh_mult[THR_NEARA ] = thresh;
1070 // Disable other intra prediction modes
1071 sf->thresh_mult[THR_TM] = INT_MAX;
1072 sf->thresh_mult[THR_V_PRED] = INT_MAX;
1073 sf->thresh_mult[THR_H_PRED] = INT_MAX;
1075 sf->improved_mv_pred = 0;
1080 sf->quarter_pixel_search = 0;
1085 int Tmp = cpi->Speed - 8;
1090 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
1092 cpi->mode_check_freq[THR_ZEROG] = 1 << (Tmp - 1);
1093 cpi->mode_check_freq[THR_NEARESTG] = 1 << (Tmp - 1);
1094 cpi->mode_check_freq[THR_NEARG] = 1 << Tmp;
1095 cpi->mode_check_freq[THR_NEWG] = 1 << (Tmp + 1);
1098 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
1100 cpi->mode_check_freq[THR_ZEROA] = 1 << (Tmp - 1);
1101 cpi->mode_check_freq[THR_NEARESTA] = 1 << (Tmp - 1);
1102 cpi->mode_check_freq[THR_NEARA] = 1 << Tmp;
1103 cpi->mode_check_freq[THR_NEWA] = 1 << (Tmp + 1);
1106 cpi->mode_check_freq[THR_NEWMV] = 1 << (Tmp - 1);
1109 cm->filter_type = NORMAL_LOOPFILTER;
1112 cm->filter_type = SIMPLE_LOOPFILTER;
1116 sf->half_pixel_search = 0; // This has a big hit on quality. Last resort
1119 vpx_memset(cpi->error_bins, 0, sizeof(cpi->error_bins));
1123 /* disable frame modes if flags not set */
1124 if (!(cpi->ref_frame_flags & VP8_LAST_FLAG))
1126 sf->thresh_mult[THR_NEWMV ] = INT_MAX;
1127 sf->thresh_mult[THR_NEARESTMV] = INT_MAX;
1128 sf->thresh_mult[THR_ZEROMV ] = INT_MAX;
1129 sf->thresh_mult[THR_NEARMV ] = INT_MAX;
1130 sf->thresh_mult[THR_SPLITMV ] = INT_MAX;
1133 if (!(cpi->ref_frame_flags & VP8_GOLD_FLAG))
1135 sf->thresh_mult[THR_NEARESTG ] = INT_MAX;
1136 sf->thresh_mult[THR_ZEROG ] = INT_MAX;
1137 sf->thresh_mult[THR_NEARG ] = INT_MAX;
1138 sf->thresh_mult[THR_NEWG ] = INT_MAX;
1139 sf->thresh_mult[THR_SPLITG ] = INT_MAX;
1142 if (!(cpi->ref_frame_flags & VP8_ALT_FLAG))
1144 sf->thresh_mult[THR_NEARESTA ] = INT_MAX;
1145 sf->thresh_mult[THR_ZEROA ] = INT_MAX;
1146 sf->thresh_mult[THR_NEARA ] = INT_MAX;
1147 sf->thresh_mult[THR_NEWA ] = INT_MAX;
1148 sf->thresh_mult[THR_SPLITA ] = INT_MAX;
1152 // Slow quant, dct and trellis not worthwhile for first pass
1153 // so make sure they are always turned off.
1154 if ( cpi->pass == 1 )
1156 sf->improved_quant = 0;
1157 sf->optimize_coefficients = 0;
1158 sf->improved_dct = 0;
1161 if (cpi->sf.search_method == NSTEP)
1163 vp8_init3smotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
1165 else if (cpi->sf.search_method == DIAMOND)
1167 vp8_init_dsmotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
1170 if (cpi->sf.improved_dct)
1172 cpi->mb.vp8_short_fdct8x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short8x4);
1173 cpi->mb.vp8_short_fdct4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short4x4);
1177 cpi->mb.vp8_short_fdct8x4 = FDCT_INVOKE(&cpi->rtcd.fdct, fast8x4);
1178 cpi->mb.vp8_short_fdct4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, fast4x4);
1181 cpi->mb.short_walsh4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, walsh_short4x4);
1183 if (cpi->sf.improved_quant)
1185 cpi->mb.quantize_b = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1187 cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1192 cpi->mb.quantize_b = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1194 cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1197 if (cpi->sf.improved_quant != last_improved_quant)
1198 vp8cx_init_quantizer(cpi);
1200 #if CONFIG_RUNTIME_CPU_DETECT
1201 cpi->mb.e_mbd.rtcd = &cpi->common.rtcd;
1204 if (cpi->sf.iterative_sub_pixel == 1)
1206 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step_iteratively;
1208 else if (cpi->sf.quarter_pixel_search)
1210 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step;
1212 else if (cpi->sf.half_pixel_search)
1214 cpi->find_fractional_mv_step = vp8_find_best_half_pixel_step;
1218 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1221 if (cpi->sf.optimize_coefficients == 1 && cpi->pass!=1)
1222 cpi->mb.optimize = 1;
1224 cpi->mb.optimize = 0;
1226 if (cpi->common.full_pixel)
1227 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1230 frames_at_speed[cpi->Speed]++;
1233 static void alloc_raw_frame_buffers(VP8_COMP *cpi)
1235 int width = (cpi->oxcf.Width + 15) & ~15;
1236 int height = (cpi->oxcf.Height + 15) & ~15;
1238 cpi->lookahead = vp8_lookahead_init(cpi->oxcf.Width, cpi->oxcf.Height,
1239 cpi->oxcf.lag_in_frames);
1241 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1242 "Failed to allocate lag buffers");
1244 #if VP8_TEMPORAL_ALT_REF
1246 if (vp8_yv12_alloc_frame_buffer(&cpi->alt_ref_buffer,
1247 width, height, VP8BORDERINPIXELS))
1248 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1249 "Failed to allocate altref buffer");
1254 static int vp8_alloc_partition_data(VP8_COMP *cpi)
1256 vpx_free(cpi->mb.pip);
1258 cpi->mb.pip = vpx_calloc((cpi->common.mb_cols + 1) *
1259 (cpi->common.mb_rows + 1),
1260 sizeof(PARTITION_INFO));
1264 cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
1269 void vp8_alloc_compressor_data(VP8_COMP *cpi)
1271 VP8_COMMON *cm = & cpi->common;
1273 int width = cm->Width;
1274 int height = cm->Height;
1276 if (vp8_alloc_frame_buffers(cm, width, height))
1277 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1278 "Failed to allocate frame buffers");
1280 if (vp8_alloc_partition_data(cpi))
1281 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1282 "Failed to allocate partition data");
1285 if ((width & 0xf) != 0)
1286 width += 16 - (width & 0xf);
1288 if ((height & 0xf) != 0)
1289 height += 16 - (height & 0xf);
1292 if (vp8_yv12_alloc_frame_buffer(&cpi->last_frame_uf,
1293 width, height, VP8BORDERINPIXELS))
1294 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1295 "Failed to allocate last frame buffer");
1297 if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source,
1298 width, height, VP8BORDERINPIXELS))
1299 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1300 "Failed to allocate scaled source buffer");
1306 unsigned int tokens = cm->mb_rows * cm->mb_cols * 24 * 16;
1308 CHECK_MEM_ERROR(cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
1311 // Data used for real time vc mode to see if gf needs refreshing
1312 cpi->inter_zz_count = 0;
1313 cpi->gf_bad_count = 0;
1314 cpi->gf_update_recommended = 0;
1317 // Structures used to minitor GF usage
1318 vpx_free(cpi->gf_active_flags);
1319 CHECK_MEM_ERROR(cpi->gf_active_flags,
1320 vpx_calloc(1, cm->mb_rows * cm->mb_cols));
1321 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
1323 vpx_free(cpi->mb_activity_map);
1324 CHECK_MEM_ERROR(cpi->mb_activity_map,
1325 vpx_calloc(sizeof(unsigned int),
1326 cm->mb_rows * cm->mb_cols));
1328 vpx_free(cpi->mb_norm_activity_map);
1329 CHECK_MEM_ERROR(cpi->mb_norm_activity_map,
1330 vpx_calloc(sizeof(unsigned int),
1331 cm->mb_rows * cm->mb_cols));
1333 #if !(CONFIG_REALTIME_ONLY)
1334 vpx_free(cpi->twopass.total_stats);
1336 cpi->twopass.total_stats = vpx_calloc(1, sizeof(FIRSTPASS_STATS));
1338 vpx_free(cpi->twopass.this_frame_stats);
1340 cpi->twopass.this_frame_stats = vpx_calloc(1, sizeof(FIRSTPASS_STATS));
1342 if(!cpi->twopass.total_stats || !cpi->twopass.this_frame_stats)
1343 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1344 "Failed to allocate firstpass stats");
1347 #if CONFIG_MULTITHREAD
1349 cpi->mt_sync_range = 1;
1350 else if (width <= 1280)
1351 cpi->mt_sync_range = 4;
1352 else if (width <= 2560)
1353 cpi->mt_sync_range = 8;
1355 cpi->mt_sync_range = 16;
1358 vpx_free(cpi->tplist);
1360 CHECK_MEM_ERROR(cpi->tplist, vpx_malloc(sizeof(TOKENLIST) * cpi->common.mb_rows));
1365 static const int q_trans[] =
1367 0, 1, 2, 3, 4, 5, 7, 8,
1368 9, 10, 12, 13, 15, 17, 18, 19,
1369 20, 21, 23, 24, 25, 26, 27, 28,
1370 29, 30, 31, 33, 35, 37, 39, 41,
1371 43, 45, 47, 49, 51, 53, 55, 57,
1372 59, 61, 64, 67, 70, 73, 76, 79,
1373 82, 85, 88, 91, 94, 97, 100, 103,
1374 106, 109, 112, 115, 118, 121, 124, 127,
1377 int vp8_reverse_trans(int x)
1381 for (i = 0; i < 64; i++)
1382 if (q_trans[i] >= x)
1387 void vp8_new_frame_rate(VP8_COMP *cpi, double framerate)
1392 cpi->oxcf.frame_rate = framerate;
1393 cpi->output_frame_rate = cpi->oxcf.frame_rate;
1394 cpi->per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth / cpi->output_frame_rate);
1395 cpi->av_per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth / cpi->output_frame_rate);
1396 cpi->min_frame_bandwidth = (int)(cpi->av_per_frame_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100);
1398 // Set Maximum gf/arf interval
1399 cpi->max_gf_interval = ((int)(cpi->output_frame_rate / 2.0) + 2);
1401 if(cpi->max_gf_interval < 12)
1402 cpi->max_gf_interval = 12;
1404 // Extended interval for genuinely static scenes
1405 cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1407 // Special conditions when altr ref frame enabled in lagged compress mode
1408 if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames)
1410 if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1411 cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1413 if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1414 cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1417 if ( cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval )
1418 cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1423 rescale(int val, int num, int denom)
1425 int64_t llnum = num;
1426 int64_t llden = denom;
1427 int64_t llval = val;
1429 return llval * llnum / llden;
1433 static void init_config(VP8_PTR ptr, VP8_CONFIG *oxcf)
1435 VP8_COMP *cpi = (VP8_COMP *)(ptr);
1436 VP8_COMMON *cm = &cpi->common;
1441 cpi->auto_adjust_gold_quantizer = 1;
1444 cm->version = oxcf->Version;
1445 vp8_setup_version(cm);
1447 // change includes all joint functionality
1448 vp8_change_config(ptr, oxcf);
1450 // Initialize active best and worst q and average q values.
1451 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1452 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1453 cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1455 // Initialise the starting buffer levels
1456 cpi->buffer_level = cpi->oxcf.starting_buffer_level;
1457 cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
1459 cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
1460 cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
1461 cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
1462 cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
1464 cpi->total_actual_bits = 0;
1465 cpi->total_target_vs_actual = 0;
1467 #if VP8_TEMPORAL_ALT_REF
1471 cpi->fixed_divide[0] = 0;
1473 for (i = 1; i < 512; i++)
1474 cpi->fixed_divide[i] = 0x80000 / i;
1480 void vp8_change_config(VP8_PTR ptr, VP8_CONFIG *oxcf)
1482 VP8_COMP *cpi = (VP8_COMP *)(ptr);
1483 VP8_COMMON *cm = &cpi->common;
1491 if (cm->version != oxcf->Version)
1493 cm->version = oxcf->Version;
1494 vp8_setup_version(cm);
1499 switch (cpi->oxcf.Mode)
1504 cpi->compressor_speed = 2;
1506 if (cpi->oxcf.cpu_used < -16)
1508 cpi->oxcf.cpu_used = -16;
1511 if (cpi->oxcf.cpu_used > 16)
1512 cpi->oxcf.cpu_used = 16;
1516 case MODE_GOODQUALITY:
1518 cpi->compressor_speed = 1;
1520 if (cpi->oxcf.cpu_used < -5)
1522 cpi->oxcf.cpu_used = -5;
1525 if (cpi->oxcf.cpu_used > 5)
1526 cpi->oxcf.cpu_used = 5;
1530 case MODE_BESTQUALITY:
1532 cpi->compressor_speed = 0;
1535 case MODE_FIRSTPASS:
1537 cpi->compressor_speed = 1;
1539 case MODE_SECONDPASS:
1541 cpi->compressor_speed = 1;
1543 if (cpi->oxcf.cpu_used < -5)
1545 cpi->oxcf.cpu_used = -5;
1548 if (cpi->oxcf.cpu_used > 5)
1549 cpi->oxcf.cpu_used = 5;
1552 case MODE_SECONDPASS_BEST:
1554 cpi->compressor_speed = 0;
1559 cpi->auto_worst_q = 1;
1561 cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1562 cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1563 cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1565 if (oxcf->fixed_q >= 0)
1567 if (oxcf->worst_allowed_q < 0)
1568 cpi->oxcf.fixed_q = q_trans[0];
1570 cpi->oxcf.fixed_q = q_trans[oxcf->worst_allowed_q];
1572 if (oxcf->alt_q < 0)
1573 cpi->oxcf.alt_q = q_trans[0];
1575 cpi->oxcf.alt_q = q_trans[oxcf->alt_q];
1577 if (oxcf->key_q < 0)
1578 cpi->oxcf.key_q = q_trans[0];
1580 cpi->oxcf.key_q = q_trans[oxcf->key_q];
1582 if (oxcf->gold_q < 0)
1583 cpi->oxcf.gold_q = q_trans[0];
1585 cpi->oxcf.gold_q = q_trans[oxcf->gold_q];
1589 cpi->baseline_gf_interval =
1590 cpi->oxcf.alt_freq ? cpi->oxcf.alt_freq : DEFAULT_GF_INTERVAL;
1592 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
1594 //cpi->use_golden_frame_only = 0;
1595 //cpi->use_last_frame_only = 0;
1596 cm->refresh_golden_frame = 0;
1597 cm->refresh_last_frame = 1;
1598 cm->refresh_entropy_probs = 1;
1600 if (cpi->oxcf.token_partitions >= 0 && cpi->oxcf.token_partitions <= 3)
1601 cm->multi_token_partition =
1602 (TOKEN_PARTITION) cpi->oxcf.token_partitions;
1604 setup_features(cpi);
1609 for (i = 0; i < MAX_MB_SEGMENTS; i++)
1610 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1613 // At the moment the first order values may not be > MAXQ
1614 if (cpi->oxcf.fixed_q > MAXQ)
1615 cpi->oxcf.fixed_q = MAXQ;
1617 // local file playback mode == really big buffer
1618 if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK)
1620 cpi->oxcf.starting_buffer_level = 60000;
1621 cpi->oxcf.optimal_buffer_level = 60000;
1622 cpi->oxcf.maximum_buffer_size = 240000;
1625 // Convert target bandwidth from Kbit/s to Bit/s
1626 cpi->oxcf.target_bandwidth *= 1000;
1628 cpi->oxcf.starting_buffer_level =
1629 rescale(cpi->oxcf.starting_buffer_level,
1630 cpi->oxcf.target_bandwidth, 1000);
1632 // Set or reset optimal and maximum buffer levels.
1633 if (cpi->oxcf.optimal_buffer_level == 0)
1634 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1636 cpi->oxcf.optimal_buffer_level =
1637 rescale(cpi->oxcf.optimal_buffer_level,
1638 cpi->oxcf.target_bandwidth, 1000);
1640 if (cpi->oxcf.maximum_buffer_size == 0)
1641 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1643 cpi->oxcf.maximum_buffer_size =
1644 rescale(cpi->oxcf.maximum_buffer_size,
1645 cpi->oxcf.target_bandwidth, 1000);
1647 // Set up frame rate and related parameters rate control values.
1648 vp8_new_frame_rate(cpi, cpi->oxcf.frame_rate);
1650 // Set absolute upper and lower quality limits
1651 cpi->worst_quality = cpi->oxcf.worst_allowed_q;
1652 cpi->best_quality = cpi->oxcf.best_allowed_q;
1654 // active values should only be modified if out of new range
1655 if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q)
1657 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1660 else if (cpi->active_worst_quality < cpi->oxcf.best_allowed_q)
1662 cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
1664 if (cpi->active_best_quality < cpi->oxcf.best_allowed_q)
1666 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1669 else if (cpi->active_best_quality > cpi->oxcf.worst_allowed_q)
1671 cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
1674 cpi->buffered_mode = (cpi->oxcf.optimal_buffer_level > 0) ? TRUE : FALSE;
1676 cpi->cq_target_quality = cpi->oxcf.cq_level;
1678 // Only allow dropped frames in buffered mode
1679 cpi->drop_frames_allowed = cpi->oxcf.allow_df && cpi->buffered_mode;
1681 if (!cm->use_bilinear_mc_filter)
1682 cm->mcomp_filter_type = SIXTAP;
1684 cm->mcomp_filter_type = BILINEAR;
1686 cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1688 cm->Width = cpi->oxcf.Width ;
1689 cm->Height = cpi->oxcf.Height ;
1691 cm->horiz_scale = cpi->horiz_scale;
1692 cm->vert_scale = cpi->vert_scale ;
1694 // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1695 if (cpi->oxcf.Sharpness > 7)
1696 cpi->oxcf.Sharpness = 7;
1698 cm->sharpness_level = cpi->oxcf.Sharpness;
1700 if (cm->horiz_scale != NORMAL || cm->vert_scale != NORMAL)
1702 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
1703 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
1705 Scale2Ratio(cm->horiz_scale, &hr, &hs);
1706 Scale2Ratio(cm->vert_scale, &vr, &vs);
1708 // always go to the next whole number
1709 cm->Width = (hs - 1 + cpi->oxcf.Width * hr) / hs;
1710 cm->Height = (vs - 1 + cpi->oxcf.Height * vr) / vs;
1713 if (((cm->Width + 15) & 0xfffffff0) !=
1714 cm->yv12_fb[cm->lst_fb_idx].y_width ||
1715 ((cm->Height + 15) & 0xfffffff0) !=
1716 cm->yv12_fb[cm->lst_fb_idx].y_height ||
1717 cm->yv12_fb[cm->lst_fb_idx].y_width == 0)
1719 alloc_raw_frame_buffers(cpi);
1720 vp8_alloc_compressor_data(cpi);
1723 if (cpi->oxcf.fixed_q >= 0)
1725 cpi->last_q[0] = cpi->oxcf.fixed_q;
1726 cpi->last_q[1] = cpi->oxcf.fixed_q;
1729 cpi->Speed = cpi->oxcf.cpu_used;
1731 // force to allowlag to 0 if lag_in_frames is 0;
1732 if (cpi->oxcf.lag_in_frames == 0)
1734 cpi->oxcf.allow_lag = 0;
1736 // Limit on lag buffers as these are not currently dynamically allocated
1737 else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS)
1738 cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1741 cpi->alt_ref_source = NULL;
1742 cpi->is_src_frame_alt_ref = 0;
1746 // Experimental RD Code
1747 cpi->frame_distortion = 0;
1748 cpi->last_frame_distortion = 0;
1753 #define M_LOG2_E 0.693147180559945309417
1754 #define log2f(x) (log (x) / (float) M_LOG2_E)
1755 static void cal_mvsadcosts(int *mvsadcost[2])
1759 mvsadcost [0] [0] = 300;
1760 mvsadcost [1] [0] = 300;
1764 double z = 256 * (2 * (log2f(8 * i) + .6));
1765 mvsadcost [0][i] = (int) z;
1766 mvsadcost [1][i] = (int) z;
1767 mvsadcost [0][-i] = (int) z;
1768 mvsadcost [1][-i] = (int) z;
1770 while (++i <= mvfp_max);
1773 VP8_PTR vp8_create_compressor(VP8_CONFIG *oxcf)
1785 cpi = ctx.cpi = vpx_memalign(32, sizeof(VP8_COMP));
1786 // Check that the CPI instance is valid
1792 vpx_memset(cpi, 0, sizeof(VP8_COMP));
1794 if (setjmp(cm->error.jmp))
1796 VP8_PTR ptr = ctx.ptr;
1798 ctx.cpi->common.error.setjmp = 0;
1799 vp8_remove_compressor(&ptr);
1803 cpi->common.error.setjmp = 1;
1805 CHECK_MEM_ERROR(cpi->mb.ss, vpx_calloc(sizeof(search_site), (MAX_MVSEARCH_STEPS * 8) + 1));
1807 vp8_create_common(&cpi->common);
1808 vp8_cmachine_specific_config(cpi);
1810 init_config((VP8_PTR)cpi, oxcf);
1812 memcpy(cpi->base_skip_false_prob, vp8cx_base_skip_false_prob, sizeof(vp8cx_base_skip_false_prob));
1813 cpi->common.current_video_frame = 0;
1814 cpi->kf_overspend_bits = 0;
1815 cpi->kf_bitrate_adjustment = 0;
1816 cpi->frames_till_gf_update_due = 0;
1817 cpi->gf_overspend_bits = 0;
1818 cpi->non_gf_bitrate_adjustment = 0;
1819 cpi->prob_last_coded = 128;
1820 cpi->prob_gf_coded = 128;
1821 cpi->prob_intra_coded = 63;
1823 // Prime the recent reference frame useage counters.
1824 // Hereafter they will be maintained as a sort of moving average
1825 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
1826 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
1827 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
1828 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
1830 // Set reference frame sign bias for ALTREF frame to 1 (for now)
1831 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
1833 cpi->twopass.gf_decay_rate = 0;
1834 cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1836 cpi->gold_is_last = 0 ;
1837 cpi->alt_is_last = 0 ;
1838 cpi->gold_is_alt = 0 ;
1840 // allocate memory for storing last frame's MVs for MV prediction.
1841 CHECK_MEM_ERROR(cpi->lfmv, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int_mv)));
1842 CHECK_MEM_ERROR(cpi->lf_ref_frame_sign_bias, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1843 CHECK_MEM_ERROR(cpi->lf_ref_frame, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1845 // Create the encoder segmentation map and set all entries to 0
1846 CHECK_MEM_ERROR(cpi->segmentation_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1847 CHECK_MEM_ERROR(cpi->active_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1848 vpx_memset(cpi->active_map , 1, (cpi->common.mb_rows * cpi->common.mb_cols));
1849 cpi->active_map_enabled = 0;
1852 // Experimental code for lagged and one pass
1853 // Initialise one_pass GF frames stats
1854 // Update stats used for GF selection
1857 cpi->one_pass_frame_index = 0;
1859 for (i = 0; i < MAX_LAG_BUFFERS; i++)
1861 cpi->one_pass_frame_stats[i].frames_so_far = 0;
1862 cpi->one_pass_frame_stats[i].frame_intra_error = 0.0;
1863 cpi->one_pass_frame_stats[i].frame_coded_error = 0.0;
1864 cpi->one_pass_frame_stats[i].frame_pcnt_inter = 0.0;
1865 cpi->one_pass_frame_stats[i].frame_pcnt_motion = 0.0;
1866 cpi->one_pass_frame_stats[i].frame_mvr = 0.0;
1867 cpi->one_pass_frame_stats[i].frame_mvr_abs = 0.0;
1868 cpi->one_pass_frame_stats[i].frame_mvc = 0.0;
1869 cpi->one_pass_frame_stats[i].frame_mvc_abs = 0.0;
1874 // Should we use the cyclic refresh method.
1875 // Currently this is tied to error resilliant mode
1876 cpi->cyclic_refresh_mode_enabled = cpi->oxcf.error_resilient_mode;
1877 cpi->cyclic_refresh_mode_max_mbs_perframe = (cpi->common.mb_rows * cpi->common.mb_cols) / 40;
1878 cpi->cyclic_refresh_mode_index = 0;
1879 cpi->cyclic_refresh_q = 32;
1881 if (cpi->cyclic_refresh_mode_enabled)
1883 CHECK_MEM_ERROR(cpi->cyclic_refresh_map, vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
1886 cpi->cyclic_refresh_map = (signed char *) NULL;
1888 // Test function for segmentation
1889 //segmentation_test_function((VP8_PTR) cpi);
1891 #ifdef ENTROPY_STATS
1892 init_context_counters();
1895 /*Initialize the feed-forward activity masking.*/
1896 cpi->activity_avg = 90<<12;
1898 cpi->frames_since_key = 8; // Give a sensible default for the first frame.
1899 cpi->key_frame_frequency = cpi->oxcf.key_freq;
1900 cpi->this_key_frame_forced = FALSE;
1901 cpi->next_key_frame_forced = FALSE;
1903 cpi->source_alt_ref_pending = FALSE;
1904 cpi->source_alt_ref_active = FALSE;
1905 cpi->common.refresh_alt_ref_frame = 0;
1907 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1908 #if CONFIG_INTERNAL_STATS
1909 cpi->b_calculate_ssimg = 0;
1914 if (cpi->b_calculate_psnr)
1916 cpi->total_sq_error = 0.0;
1917 cpi->total_sq_error2 = 0.0;
1922 cpi->totalp_y = 0.0;
1923 cpi->totalp_u = 0.0;
1924 cpi->totalp_v = 0.0;
1926 cpi->tot_recode_hits = 0;
1927 cpi->summed_quality = 0;
1928 cpi->summed_weights = 0;
1931 if (cpi->b_calculate_ssimg)
1933 cpi->total_ssimg_y = 0;
1934 cpi->total_ssimg_u = 0;
1935 cpi->total_ssimg_v = 0;
1936 cpi->total_ssimg_all = 0;
1942 #define LLONG_MAX 9223372036854775807LL
1944 cpi->first_time_stamp_ever = LLONG_MAX;
1946 cpi->frames_till_gf_update_due = 0;
1947 cpi->key_frame_count = 1;
1949 cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
1952 cpi->total_byte_count = 0;
1954 cpi->drop_frame = 0;
1955 cpi->drop_count = 0;
1956 cpi->max_drop_count = 0;
1957 cpi->max_consec_dropped_frames = 4;
1959 cpi->rate_correction_factor = 1.0;
1960 cpi->key_frame_rate_correction_factor = 1.0;
1961 cpi->gf_rate_correction_factor = 1.0;
1962 cpi->twopass.est_max_qcorrection_factor = 1.0;
1964 cpi->mb.mvcost[0] = &cpi->mb.mvcosts[0][mv_max+1];
1965 cpi->mb.mvcost[1] = &cpi->mb.mvcosts[1][mv_max+1];
1966 cpi->mb.mvsadcost[0] = &cpi->mb.mvsadcosts[0][mvfp_max+1];
1967 cpi->mb.mvsadcost[1] = &cpi->mb.mvsadcosts[1][mvfp_max+1];
1969 cal_mvsadcosts(cpi->mb.mvsadcost);
1971 for (i = 0; i < KEY_FRAME_CONTEXT; i++)
1973 cpi->prior_key_frame_distance[i] = (int)cpi->output_frame_rate;
1976 #ifdef OUTPUT_YUV_SRC
1977 yuv_file = fopen("bd.yuv", "ab");
1981 framepsnr = fopen("framepsnr.stt", "a");
1982 kf_list = fopen("kf_list.stt", "w");
1985 cpi->output_pkt_list = oxcf->output_pkt_list;
1987 #if !(CONFIG_REALTIME_ONLY)
1991 vp8_init_first_pass(cpi);
1993 else if (cpi->pass == 2)
1995 size_t packet_sz = sizeof(FIRSTPASS_STATS);
1996 int packets = oxcf->two_pass_stats_in.sz / packet_sz;
1998 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1999 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
2000 cpi->twopass.stats_in_end = (void*)((char *)cpi->twopass.stats_in
2001 + (packets - 1) * packet_sz);
2002 vp8_init_second_pass(cpi);
2007 if (cpi->compressor_speed == 2)
2009 cpi->cpu_freq = 0; //vp8_get_processor_freq();
2010 cpi->avg_encode_time = 0;
2011 cpi->avg_pick_mode_time = 0;
2014 vp8_set_speed_features(cpi);
2016 // Set starting values of RD threshold multipliers (128 = *1)
2017 for (i = 0; i < MAX_MODES; i++)
2019 cpi->rd_thresh_mult[i] = 128;
2022 #ifdef ENTROPY_STATS
2023 init_mv_ref_counts();
2026 #if CONFIG_MULTITHREAD
2027 vp8cx_create_encoder_threads(cpi);
2030 cpi->fn_ptr[BLOCK_16X16].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16);
2031 cpi->fn_ptr[BLOCK_16X16].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x16);
2032 cpi->fn_ptr[BLOCK_16X16].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x16);
2033 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_h = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_h);
2034 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_v = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_v);
2035 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_hv = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_hv);
2036 cpi->fn_ptr[BLOCK_16X16].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x3);
2037 cpi->fn_ptr[BLOCK_16X16].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x8);
2038 cpi->fn_ptr[BLOCK_16X16].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x4d);
2040 cpi->fn_ptr[BLOCK_16X8].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8);
2041 cpi->fn_ptr[BLOCK_16X8].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x8);
2042 cpi->fn_ptr[BLOCK_16X8].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x8);
2043 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_h = NULL;
2044 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_v = NULL;
2045 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_hv = NULL;
2046 cpi->fn_ptr[BLOCK_16X8].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x3);
2047 cpi->fn_ptr[BLOCK_16X8].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x8);
2048 cpi->fn_ptr[BLOCK_16X8].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x4d);
2050 cpi->fn_ptr[BLOCK_8X16].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16);
2051 cpi->fn_ptr[BLOCK_8X16].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x16);
2052 cpi->fn_ptr[BLOCK_8X16].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x16);
2053 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_h = NULL;
2054 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_v = NULL;
2055 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_hv = NULL;
2056 cpi->fn_ptr[BLOCK_8X16].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x3);
2057 cpi->fn_ptr[BLOCK_8X16].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x8);
2058 cpi->fn_ptr[BLOCK_8X16].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x4d);
2060 cpi->fn_ptr[BLOCK_8X8].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8);
2061 cpi->fn_ptr[BLOCK_8X8].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x8);
2062 cpi->fn_ptr[BLOCK_8X8].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x8);
2063 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_h = NULL;
2064 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_v = NULL;
2065 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_hv = NULL;
2066 cpi->fn_ptr[BLOCK_8X8].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x3);
2067 cpi->fn_ptr[BLOCK_8X8].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x8);
2068 cpi->fn_ptr[BLOCK_8X8].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x4d);
2070 cpi->fn_ptr[BLOCK_4X4].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4);
2071 cpi->fn_ptr[BLOCK_4X4].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var4x4);
2072 cpi->fn_ptr[BLOCK_4X4].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar4x4);
2073 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_h = NULL;
2074 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_v = NULL;
2075 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_hv = NULL;
2076 cpi->fn_ptr[BLOCK_4X4].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x3);
2077 cpi->fn_ptr[BLOCK_4X4].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x8);
2078 cpi->fn_ptr[BLOCK_4X4].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x4d);
2080 #if ARCH_X86 || ARCH_X86_64
2081 cpi->fn_ptr[BLOCK_16X16].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2082 cpi->fn_ptr[BLOCK_16X8].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2083 cpi->fn_ptr[BLOCK_8X16].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2084 cpi->fn_ptr[BLOCK_8X8].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2085 cpi->fn_ptr[BLOCK_4X4].copymem = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2088 cpi->full_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, full_search);
2089 cpi->diamond_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, diamond_search);
2090 cpi->refining_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, refining_search);
2092 // make sure frame 1 is okay
2093 cpi->error_bins[0] = cpi->common.MBs;
2095 //vp8cx_init_quantizer() is first called here. Add check in vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only called later
2096 //when needed. This will avoid unnecessary calls of vp8cx_init_quantizer() for every frame.
2097 vp8cx_init_quantizer(cpi);
2099 vp8_loop_filter_init(cm);
2101 cpi->common.error.setjmp = 0;
2102 return (VP8_PTR) cpi;
2107 void vp8_remove_compressor(VP8_PTR *ptr)
2109 VP8_COMP *cpi = (VP8_COMP *)(*ptr);
2114 if (cpi && (cpi->common.current_video_frame > 0))
2116 #if !(CONFIG_REALTIME_ONLY)
2120 vp8_end_second_pass(cpi);
2125 #ifdef ENTROPY_STATS
2126 print_context_counters();
2127 print_tree_update_probs();
2128 print_mode_context();
2131 #if CONFIG_INTERNAL_STATS
2135 FILE *f = fopen("opsnr.stt", "a");
2136 double time_encoded = (cpi->last_end_time_stamp_seen
2137 - cpi->first_time_stamp_ever) / 10000000.000;
2138 double total_encode_time = (cpi->time_receive_data + cpi->time_compress_data) / 1000.000;
2139 double dr = (double)cpi->bytes * (double) 8 / (double)1000 / time_encoded;
2141 if (cpi->b_calculate_psnr)
2143 YV12_BUFFER_CONFIG *lst_yv12 = &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
2144 double samples = 3.0 / 2 * cpi->count * lst_yv12->y_width * lst_yv12->y_height;
2145 double total_psnr = vp8_mse2psnr(samples, 255.0, cpi->total_sq_error);
2146 double total_psnr2 = vp8_mse2psnr(samples, 255.0, cpi->total_sq_error2);
2147 double total_ssim = 100 * pow(cpi->summed_quality / cpi->summed_weights, 8.0);
2149 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\tVPXSSIM\t Time(us)\n");
2150 fprintf(f, "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%8.0f\n",
2151 dr, cpi->total / cpi->count, total_psnr, cpi->totalp / cpi->count, total_psnr2, total_ssim,
2155 if (cpi->b_calculate_ssimg)
2157 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t Time(us)\n");
2158 fprintf(f, "%7.3f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
2159 cpi->total_ssimg_y / cpi->count, cpi->total_ssimg_u / cpi->count,
2160 cpi->total_ssimg_v / cpi->count, cpi->total_ssimg_all / cpi->count, total_encode_time);
2165 f = fopen("qskip.stt", "a");
2166 fprintf(f, "minq:%d -maxq:%d skipture:skipfalse = %d:%d\n", cpi->oxcf.best_allowed_q, cpi->oxcf.worst_allowed_q, skiptruecount, skipfalsecount);
2177 if (cpi->compressor_speed == 2)
2180 FILE *f = fopen("cxspeed.stt", "a");
2181 cnt_pm /= cpi->common.MBs;
2183 for (i = 0; i < 16; i++)
2184 fprintf(f, "%5d", frames_at_speed[i]);
2187 //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);
2196 extern int count_mb_seg[4];
2197 FILE *f = fopen("modes.stt", "a");
2198 double dr = (double)cpi->oxcf.frame_rate * (double)bytes * (double)8 / (double)count / (double)1000 ;
2199 fprintf(f, "intra_mode in Intra Frames:\n");
2200 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d\n", y_modes[0], y_modes[1], y_modes[2], y_modes[3], y_modes[4]);
2201 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", uv_modes[0], uv_modes[1], uv_modes[2], uv_modes[3]);
2206 for (i = 0; i < 10; i++)
2207 fprintf(f, "%8d, ", b_modes[i]);
2213 fprintf(f, "Modes in Inter Frames:\n");
2214 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d\n",
2215 inter_y_modes[0], inter_y_modes[1], inter_y_modes[2], inter_y_modes[3], inter_y_modes[4],
2216 inter_y_modes[5], inter_y_modes[6], inter_y_modes[7], inter_y_modes[8], inter_y_modes[9]);
2217 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", inter_uv_modes[0], inter_uv_modes[1], inter_uv_modes[2], inter_uv_modes[3]);
2222 for (i = 0; i < 15; i++)
2223 fprintf(f, "%8d, ", inter_b_modes[i]);
2228 fprintf(f, "P:%8d, %8d, %8d, %8d\n", count_mb_seg[0], count_mb_seg[1], count_mb_seg[2], count_mb_seg[3]);
2229 fprintf(f, "PB:%8d, %8d, %8d, %8d\n", inter_b_modes[LEFT4X4], inter_b_modes[ABOVE4X4], inter_b_modes[ZERO4X4], inter_b_modes[NEW4X4]);
2237 #ifdef ENTROPY_STATS
2240 FILE *fmode = fopen("modecontext.c", "w");
2242 fprintf(fmode, "\n#include \"entropymode.h\"\n\n");
2243 fprintf(fmode, "const unsigned int vp8_kf_default_bmode_counts ");
2244 fprintf(fmode, "[VP8_BINTRAMODES] [VP8_BINTRAMODES] [VP8_BINTRAMODES] =\n{\n");
2246 for (i = 0; i < 10; i++)
2249 fprintf(fmode, " { //Above Mode : %d\n", i);
2251 for (j = 0; j < 10; j++)
2254 fprintf(fmode, " {");
2256 for (k = 0; k < 10; k++)
2258 if (!intra_mode_stats[i][j][k])
2259 fprintf(fmode, " %5d, ", 1);
2261 fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
2264 fprintf(fmode, "}, // left_mode %d\n", j);
2268 fprintf(fmode, " },\n");
2272 fprintf(fmode, "};\n");
2278 #if defined(SECTIONBITS_OUTPUT)
2283 FILE *f = fopen("tokenbits.stt", "a");
2285 for (i = 0; i < 28; i++)
2286 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
2296 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2297 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
2298 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);
2304 #if CONFIG_MULTITHREAD
2305 vp8cx_remove_encoder_threads(cpi);
2308 dealloc_compressor_data(cpi);
2309 vpx_free(cpi->mb.ss);
2311 vpx_free(cpi->cyclic_refresh_map);
2313 vp8_remove_common(&cpi->common);
2317 #ifdef OUTPUT_YUV_SRC
2337 static uint64_t calc_plane_error(unsigned char *orig, int orig_stride,
2338 unsigned char *recon, int recon_stride,
2339 unsigned int cols, unsigned int rows,
2340 vp8_variance_rtcd_vtable_t *rtcd)
2342 unsigned int row, col;
2343 uint64_t total_sse = 0;
2346 for (row = 0; row + 16 <= rows; row += 16)
2348 for (col = 0; col + 16 <= cols; col += 16)
2352 VARIANCE_INVOKE(rtcd, mse16x16)(orig + col, orig_stride,
2353 recon + col, recon_stride,
2358 /* Handle odd-sized width */
2361 unsigned int border_row, border_col;
2362 unsigned char *border_orig = orig;
2363 unsigned char *border_recon = recon;
2365 for (border_row = 0; border_row < 16; border_row++)
2367 for (border_col = col; border_col < cols; border_col++)
2369 diff = border_orig[border_col] - border_recon[border_col];
2370 total_sse += diff * diff;
2373 border_orig += orig_stride;
2374 border_recon += recon_stride;
2378 orig += orig_stride * 16;
2379 recon += recon_stride * 16;
2382 /* Handle odd-sized height */
2383 for (; row < rows; row++)
2385 for (col = 0; col < cols; col++)
2387 diff = orig[col] - recon[col];
2388 total_sse += diff * diff;
2391 orig += orig_stride;
2392 recon += recon_stride;
2399 static void generate_psnr_packet(VP8_COMP *cpi)
2401 YV12_BUFFER_CONFIG *orig = cpi->Source;
2402 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2403 struct vpx_codec_cx_pkt pkt;
2406 unsigned int width = cpi->common.Width;
2407 unsigned int height = cpi->common.Height;
2409 pkt.kind = VPX_CODEC_PSNR_PKT;
2410 sse = calc_plane_error(orig->y_buffer, orig->y_stride,
2411 recon->y_buffer, recon->y_stride,
2413 IF_RTCD(&cpi->rtcd.variance));
2414 pkt.data.psnr.sse[0] = sse;
2415 pkt.data.psnr.sse[1] = sse;
2416 pkt.data.psnr.samples[0] = width * height;
2417 pkt.data.psnr.samples[1] = width * height;
2419 width = (width + 1) / 2;
2420 height = (height + 1) / 2;
2422 sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
2423 recon->u_buffer, recon->uv_stride,
2425 IF_RTCD(&cpi->rtcd.variance));
2426 pkt.data.psnr.sse[0] += sse;
2427 pkt.data.psnr.sse[2] = sse;
2428 pkt.data.psnr.samples[0] += width * height;
2429 pkt.data.psnr.samples[2] = width * height;
2431 sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2432 recon->v_buffer, recon->uv_stride,
2434 IF_RTCD(&cpi->rtcd.variance));
2435 pkt.data.psnr.sse[0] += sse;
2436 pkt.data.psnr.sse[3] = sse;
2437 pkt.data.psnr.samples[0] += width * height;
2438 pkt.data.psnr.samples[3] = width * height;
2440 for (i = 0; i < 4; i++)
2441 pkt.data.psnr.psnr[i] = vp8_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2442 pkt.data.psnr.sse[i]);
2444 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2448 int vp8_use_as_reference(VP8_PTR ptr, int ref_frame_flags)
2450 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2452 if (ref_frame_flags > 7)
2455 cpi->ref_frame_flags = ref_frame_flags;
2458 int vp8_update_reference(VP8_PTR ptr, int ref_frame_flags)
2460 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2462 if (ref_frame_flags > 7)
2465 cpi->common.refresh_golden_frame = 0;
2466 cpi->common.refresh_alt_ref_frame = 0;
2467 cpi->common.refresh_last_frame = 0;
2469 if (ref_frame_flags & VP8_LAST_FLAG)
2470 cpi->common.refresh_last_frame = 1;
2472 if (ref_frame_flags & VP8_GOLD_FLAG)
2473 cpi->common.refresh_golden_frame = 1;
2475 if (ref_frame_flags & VP8_ALT_FLAG)
2476 cpi->common.refresh_alt_ref_frame = 1;
2481 int vp8_get_reference(VP8_PTR ptr, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2483 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2484 VP8_COMMON *cm = &cpi->common;
2487 if (ref_frame_flag == VP8_LAST_FLAG)
2488 ref_fb_idx = cm->lst_fb_idx;
2489 else if (ref_frame_flag == VP8_GOLD_FLAG)
2490 ref_fb_idx = cm->gld_fb_idx;
2491 else if (ref_frame_flag == VP8_ALT_FLAG)
2492 ref_fb_idx = cm->alt_fb_idx;
2496 vp8_yv12_copy_frame_ptr(&cm->yv12_fb[ref_fb_idx], sd);
2500 int vp8_set_reference(VP8_PTR ptr, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2502 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2503 VP8_COMMON *cm = &cpi->common;
2507 if (ref_frame_flag == VP8_LAST_FLAG)
2508 ref_fb_idx = cm->lst_fb_idx;
2509 else if (ref_frame_flag == VP8_GOLD_FLAG)
2510 ref_fb_idx = cm->gld_fb_idx;
2511 else if (ref_frame_flag == VP8_ALT_FLAG)
2512 ref_fb_idx = cm->alt_fb_idx;
2516 vp8_yv12_copy_frame_ptr(sd, &cm->yv12_fb[ref_fb_idx]);
2520 int vp8_update_entropy(VP8_PTR comp, int update)
2522 VP8_COMP *cpi = (VP8_COMP *) comp;
2523 VP8_COMMON *cm = &cpi->common;
2524 cm->refresh_entropy_probs = update;
2531 void vp8_write_yuv_frame(const char *name, YV12_BUFFER_CONFIG *s)
2533 FILE *yuv_file = fopen(name, "ab");
2534 unsigned char *src = s->y_buffer;
2535 int h = s->y_height;
2539 fwrite(src, s->y_width, 1, yuv_file);
2549 fwrite(src, s->uv_width, 1, yuv_file);
2550 src += s->uv_stride;
2559 fwrite(src, s->uv_width, 1, yuv_file);
2560 src += s->uv_stride;
2569 static void scale_and_extend_source(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi)
2571 VP8_COMMON *cm = &cpi->common;
2573 // are we resizing the image
2574 if (cm->horiz_scale != 0 || cm->vert_scale != 0)
2576 #if CONFIG_SPATIAL_RESAMPLING
2577 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2578 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2581 if (cm->vert_scale == 3)
2586 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2587 Scale2Ratio(cm->vert_scale, &vr, &vs);
2589 vp8_scale_frame(sd, &cpi->scaled_source, cm->temp_scale_frame.y_buffer,
2590 tmp_height, hs, hr, vs, vr, 0);
2592 vp8_yv12_extend_frame_borders(&cpi->scaled_source);
2593 cpi->Source = &cpi->scaled_source;
2601 static void resize_key_frame(VP8_COMP *cpi)
2603 #if CONFIG_SPATIAL_RESAMPLING
2604 VP8_COMMON *cm = &cpi->common;
2606 // Do we need to apply resampling for one pass cbr.
2607 // In one pass this is more limited than in two pass cbr
2608 // The test and any change is only made one per key frame sequence
2609 if (cpi->oxcf.allow_spatial_resampling && (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER))
2611 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2612 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2613 int new_width, new_height;
2615 // If we are below the resample DOWN watermark then scale down a notch.
2616 if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2618 cm->horiz_scale = (cm->horiz_scale < ONETWO) ? cm->horiz_scale + 1 : ONETWO;
2619 cm->vert_scale = (cm->vert_scale < ONETWO) ? cm->vert_scale + 1 : ONETWO;
2621 // Should we now start scaling back up
2622 else if (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2624 cm->horiz_scale = (cm->horiz_scale > NORMAL) ? cm->horiz_scale - 1 : NORMAL;
2625 cm->vert_scale = (cm->vert_scale > NORMAL) ? cm->vert_scale - 1 : NORMAL;
2628 // Get the new hieght and width
2629 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2630 Scale2Ratio(cm->vert_scale, &vr, &vs);
2631 new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
2632 new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
2634 // If the image size has changed we need to reallocate the buffers
2635 // and resample the source image
2636 if ((cm->Width != new_width) || (cm->Height != new_height))
2638 cm->Width = new_width;
2639 cm->Height = new_height;
2640 vp8_alloc_compressor_data(cpi);
2641 scale_and_extend_source(cpi->un_scaled_source, cpi);
2649 static void update_alt_ref_frame_stats(VP8_COMP *cpi)
2651 VP8_COMMON *cm = &cpi->common;
2653 // Select an interval before next GF or altref
2654 if (!cpi->auto_gold)
2655 cpi->frames_till_gf_update_due = cpi->goldfreq;
2657 if ((cpi->pass != 2) && cpi->frames_till_gf_update_due)
2659 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2661 // Set the bits per frame that we should try and recover in subsequent inter frames
2662 // to account for the extra GF spend... note that his does not apply for GF updates
2663 // that occur coincident with a key frame as the extra cost of key frames is dealt
2666 cpi->gf_overspend_bits += cpi->projected_frame_size;
2667 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2670 // Update data structure that monitors level of reference to last GF
2671 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2672 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2674 // this frame refreshes means next frames don't unless specified by user
2675 cpi->common.frames_since_golden = 0;
2677 // Clear the alternate reference update pending flag.
2678 cpi->source_alt_ref_pending = FALSE;
2680 // Set the alternate refernce frame active flag
2681 cpi->source_alt_ref_active = TRUE;
2685 static void update_golden_frame_stats(VP8_COMP *cpi)
2687 VP8_COMMON *cm = &cpi->common;
2689 // Update the Golden frame usage counts.
2690 if (cm->refresh_golden_frame)
2692 // Select an interval before next GF
2693 if (!cpi->auto_gold)
2694 cpi->frames_till_gf_update_due = cpi->goldfreq;
2696 if ((cpi->pass != 2) && (cpi->frames_till_gf_update_due > 0))
2698 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2700 // Set the bits per frame that we should try and recover in subsequent inter frames
2701 // to account for the extra GF spend... note that his does not apply for GF updates
2702 // that occur coincident with a key frame as the extra cost of key frames is dealt
2704 if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active)
2706 // Calcluate GF bits to be recovered
2707 // Projected size - av frame bits available for inter frames for clip as a whole
2708 cpi->gf_overspend_bits += (cpi->projected_frame_size - cpi->inter_frame_target);
2711 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2715 // Update data structure that monitors level of reference to last GF
2716 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2717 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2719 // this frame refreshes means next frames don't unless specified by user
2720 cm->refresh_golden_frame = 0;
2721 cpi->common.frames_since_golden = 0;
2723 //if ( cm->frame_type == KEY_FRAME )
2725 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
2726 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
2727 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
2728 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
2732 // // Carry a potrtion of count over to begining of next gf sequence
2733 // cpi->recent_ref_frame_usage[INTRA_FRAME] >>= 5;
2734 // cpi->recent_ref_frame_usage[LAST_FRAME] >>= 5;
2735 // cpi->recent_ref_frame_usage[GOLDEN_FRAME] >>= 5;
2736 // cpi->recent_ref_frame_usage[ALTREF_FRAME] >>= 5;
2739 // ******** Fixed Q test code only ************
2740 // If we are going to use the ALT reference for the next group of frames set a flag to say so.
2741 if (cpi->oxcf.fixed_q >= 0 &&
2742 cpi->oxcf.play_alternate && !cpi->common.refresh_alt_ref_frame)
2744 cpi->source_alt_ref_pending = TRUE;
2745 cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2748 if (!cpi->source_alt_ref_pending)
2749 cpi->source_alt_ref_active = FALSE;
2751 // Decrement count down till next gf
2752 if (cpi->frames_till_gf_update_due > 0)
2753 cpi->frames_till_gf_update_due--;
2756 else if (!cpi->common.refresh_alt_ref_frame)
2758 // Decrement count down till next gf
2759 if (cpi->frames_till_gf_update_due > 0)
2760 cpi->frames_till_gf_update_due--;
2762 if (cpi->common.frames_till_alt_ref_frame)
2763 cpi->common.frames_till_alt_ref_frame --;
2765 cpi->common.frames_since_golden ++;
2767 if (cpi->common.frames_since_golden > 1)
2769 cpi->recent_ref_frame_usage[INTRA_FRAME] += cpi->count_mb_ref_frame_usage[INTRA_FRAME];
2770 cpi->recent_ref_frame_usage[LAST_FRAME] += cpi->count_mb_ref_frame_usage[LAST_FRAME];
2771 cpi->recent_ref_frame_usage[GOLDEN_FRAME] += cpi->count_mb_ref_frame_usage[GOLDEN_FRAME];
2772 cpi->recent_ref_frame_usage[ALTREF_FRAME] += cpi->count_mb_ref_frame_usage[ALTREF_FRAME];
2777 // This function updates the reference frame probability estimates that
2778 // will be used during mode selection
2779 static void update_rd_ref_frame_probs(VP8_COMP *cpi)
2781 VP8_COMMON *cm = &cpi->common;
2784 const int *const rfct = cpi->recent_ref_frame_usage;
2785 const int rf_intra = rfct[INTRA_FRAME];
2786 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
2788 if (cm->frame_type == KEY_FRAME)
2790 cpi->prob_intra_coded = 255;
2791 cpi->prob_last_coded = 128;
2792 cpi->prob_gf_coded = 128;
2794 else if (!(rf_intra + rf_inter))
2796 // This is a trap in case this function is called with cpi->recent_ref_frame_usage[] blank.
2797 cpi->prob_intra_coded = 63;
2798 cpi->prob_last_coded = 128;
2799 cpi->prob_gf_coded = 128;
2803 cpi->prob_intra_coded = (rf_intra * 255) / (rf_intra + rf_inter);
2805 if (cpi->prob_intra_coded < 1)
2806 cpi->prob_intra_coded = 1;
2808 if ((cm->frames_since_golden > 0) || cpi->source_alt_ref_active)
2810 cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
2812 if (cpi->prob_last_coded < 1)
2813 cpi->prob_last_coded = 1;
2815 cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
2816 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
2818 if (cpi->prob_gf_coded < 1)
2819 cpi->prob_gf_coded = 1;
2824 const int *const rfct = cpi->count_mb_ref_frame_usage;
2825 const int rf_intra = rfct[INTRA_FRAME];
2826 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
2828 if (cm->frame_type == KEY_FRAME)
2830 cpi->prob_intra_coded = 255;
2831 cpi->prob_last_coded = 128;
2832 cpi->prob_gf_coded = 128;
2834 else if (!(rf_intra + rf_inter))
2836 // This is a trap in case this function is called with cpi->recent_ref_frame_usage[] blank.
2837 cpi->prob_intra_coded = 63;
2838 cpi->prob_last_coded = 128;
2839 cpi->prob_gf_coded = 128;
2843 cpi->prob_intra_coded = (rf_intra * 255) / (rf_intra + rf_inter);
2845 if (cpi->prob_intra_coded < 1)
2846 cpi->prob_intra_coded = 1;
2848 cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
2850 if (cpi->prob_last_coded < 1)
2851 cpi->prob_last_coded = 1;
2853 cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
2854 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
2856 if (cpi->prob_gf_coded < 1)
2857 cpi->prob_gf_coded = 1;
2860 // update reference frame costs since we can do better than what we got last frame.
2862 if (cpi->common.refresh_alt_ref_frame)
2864 cpi->prob_intra_coded += 40;
2865 cpi->prob_last_coded = 200;
2866 cpi->prob_gf_coded = 1;
2868 else if (cpi->common.frames_since_golden == 0)
2870 cpi->prob_last_coded = 214;
2871 cpi->prob_gf_coded = 1;
2873 else if (cpi->common.frames_since_golden == 1)
2875 cpi->prob_last_coded = 192;
2876 cpi->prob_gf_coded = 220;
2878 else if (cpi->source_alt_ref_active)
2880 //int dist = cpi->common.frames_till_alt_ref_frame + cpi->common.frames_since_golden;
2881 cpi->prob_gf_coded -= 20;
2883 if (cpi->prob_gf_coded < 10)
2884 cpi->prob_gf_coded = 10;
2891 // 1 = key, 0 = inter
2892 static int decide_key_frame(VP8_COMP *cpi)
2894 VP8_COMMON *cm = &cpi->common;
2896 int code_key_frame = FALSE;
2900 if (cpi->Speed > 11)
2903 // Clear down mmx registers
2904 vp8_clear_system_state(); //__asm emms;
2906 if ((cpi->compressor_speed == 2) && (cpi->Speed >= 5) && (cpi->sf.RD == 0))
2908 double change = 1.0 * abs((int)(cpi->intra_error - cpi->last_intra_error)) / (1 + cpi->last_intra_error);
2909 double change2 = 1.0 * abs((int)(cpi->prediction_error - cpi->last_prediction_error)) / (1 + cpi->last_prediction_error);
2910 double minerror = cm->MBs * 256;
2914 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
2915 && cpi->prediction_error > minerror
2916 && (change > .25 || change2 > .25))
2918 FILE *f = fopen("intra_inter.stt", "a");
2920 if (cpi->prediction_error <= 0)
2921 cpi->prediction_error = 1;
2923 fprintf(f, "%d %d %d %d %14.4f\n",
2924 cm->current_video_frame,
2925 (int) cpi->prediction_error,
2926 (int) cpi->intra_error,
2927 (int)((10 * cpi->intra_error) / cpi->prediction_error),
2935 cpi->last_intra_error = cpi->intra_error;
2936 cpi->last_prediction_error = cpi->prediction_error;
2938 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
2939 && cpi->prediction_error > minerror
2940 && (change > .25 || change2 > .25))
2942 /*(change > 1.4 || change < .75)&& cpi->this_frame_percent_intra > cpi->last_frame_percent_intra + 3*/
2950 // If the following are true we might as well code a key frame
2951 if (((cpi->this_frame_percent_intra == 100) &&
2952 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
2953 ((cpi->this_frame_percent_intra > 95) &&
2954 (cpi->this_frame_percent_intra >= (cpi->last_frame_percent_intra + 5))))
2956 code_key_frame = TRUE;
2958 // in addition if the following are true and this is not a golden frame then code a key frame
2959 // Note that on golden frames there often seems to be a pop in intra useage anyway hence this
2960 // restriction is designed to prevent spurious key frames. The Intra pop needs to be investigated.
2961 else if (((cpi->this_frame_percent_intra > 60) &&
2962 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 2))) ||
2963 ((cpi->this_frame_percent_intra > 75) &&
2964 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 3 / 2))) ||
2965 ((cpi->this_frame_percent_intra > 90) &&
2966 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 10))))
2968 if (!cm->refresh_golden_frame)
2969 code_key_frame = TRUE;
2972 return code_key_frame;
2976 #if !(CONFIG_REALTIME_ONLY)
2977 static void Pass1Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags)
2982 vp8_set_quantizer(cpi, 26);
2984 scale_and_extend_source(cpi->un_scaled_source, cpi);
2985 vp8_first_pass(cpi);
2990 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame)
2998 sprintf(filename, "cx\\y%04d.raw", this_frame);
2999 yframe = fopen(filename, "wb");
3001 for (i = 0; i < frame->y_height; i++)
3002 fwrite(frame->y_buffer + i * frame->y_stride, frame->y_width, 1, yframe);
3005 sprintf(filename, "cx\\u%04d.raw", this_frame);
3006 yframe = fopen(filename, "wb");
3008 for (i = 0; i < frame->uv_height; i++)
3009 fwrite(frame->u_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
3012 sprintf(filename, "cx\\v%04d.raw", this_frame);
3013 yframe = fopen(filename, "wb");
3015 for (i = 0; i < frame->uv_height; i++)
3016 fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
3021 // return of 0 means drop frame
3023 // Function to test for conditions that indeicate we should loop
3024 // back and recode a frame.
3025 static BOOL recode_loop_test( VP8_COMP *cpi,
3026 int high_limit, int low_limit,
3027 int q, int maxq, int minq )
3029 BOOL force_recode = FALSE;
3030 VP8_COMMON *cm = &cpi->common;
3032 // Is frame recode allowed at all
3033 // Yes if either recode mode 1 is selected or mode two is selcted
3034 // and the frame is a key frame. golden frame or alt_ref_frame
3035 if ( (cpi->sf.recode_loop == 1) ||
3036 ( (cpi->sf.recode_loop == 2) &&
3037 ( (cm->frame_type == KEY_FRAME) ||
3038 cm->refresh_golden_frame ||
3039 cm->refresh_alt_ref_frame ) ) )
3041 // General over and under shoot tests
3042 if ( ((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
3043 ((cpi->projected_frame_size < low_limit) && (q > minq)) )
3045 force_recode = TRUE;
3047 // Special Constrained quality tests
3048 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
3050 // Undershoot and below auto cq level
3051 if ( (q > cpi->cq_target_quality) &&
3052 (cpi->projected_frame_size <
3053 ((cpi->this_frame_target * 7) >> 3)))
3055 force_recode = TRUE;
3057 // Severe undershoot and between auto and user cq level
3058 else if ( (q > cpi->oxcf.cq_level) &&
3059 (cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
3060 (cpi->active_best_quality > cpi->oxcf.cq_level))
3062 force_recode = TRUE;
3063 cpi->active_best_quality = cpi->oxcf.cq_level;
3068 return force_recode;
3071 void update_reference_frames(VP8_COMMON *cm)
3073 YV12_BUFFER_CONFIG *yv12_fb = cm->yv12_fb;
3075 // At this point the new frame has been encoded.
3076 // If any buffer copy / swapping is signaled it should be done here.
3078 if (cm->frame_type == KEY_FRAME)
3080 yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG | VP8_ALT_FLAG ;
3082 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3083 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3085 cm->alt_fb_idx = cm->gld_fb_idx = cm->new_fb_idx;
3087 else /* For non key frames */
3089 if (cm->refresh_alt_ref_frame)
3091 assert(!cm->copy_buffer_to_arf);
3093 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_ALT_FLAG;
3094 cm->yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3095 cm->alt_fb_idx = cm->new_fb_idx;
3097 else if (cm->copy_buffer_to_arf)
3099 assert(!(cm->copy_buffer_to_arf & ~0x3));
3101 if (cm->copy_buffer_to_arf == 1)
3103 if(cm->alt_fb_idx != cm->lst_fb_idx)
3105 yv12_fb[cm->lst_fb_idx].flags |= VP8_ALT_FLAG;
3106 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3107 cm->alt_fb_idx = cm->lst_fb_idx;
3110 else /* if (cm->copy_buffer_to_arf == 2) */
3112 if(cm->alt_fb_idx != cm->gld_fb_idx)
3114 yv12_fb[cm->gld_fb_idx].flags |= VP8_ALT_FLAG;
3115 yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3116 cm->alt_fb_idx = cm->gld_fb_idx;
3121 if (cm->refresh_golden_frame)
3123 assert(!cm->copy_buffer_to_gf);
3125 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG;
3126 cm->yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3127 cm->gld_fb_idx = cm->new_fb_idx;
3129 else if (cm->copy_buffer_to_gf)
3131 assert(!(cm->copy_buffer_to_arf & ~0x3));
3133 if (cm->copy_buffer_to_gf == 1)
3135 if(cm->gld_fb_idx != cm->lst_fb_idx)
3137 yv12_fb[cm->lst_fb_idx].flags |= VP8_GOLD_FLAG;
3138 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3139 cm->gld_fb_idx = cm->lst_fb_idx;
3142 else /* if (cm->copy_buffer_to_gf == 2) */
3144 if(cm->alt_fb_idx != cm->gld_fb_idx)
3146 yv12_fb[cm->alt_fb_idx].flags |= VP8_GOLD_FLAG;
3147 yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3148 cm->gld_fb_idx = cm->alt_fb_idx;
3154 if (cm->refresh_last_frame)
3156 cm->yv12_fb[cm->new_fb_idx].flags |= VP8_LAST_FLAG;
3157 cm->yv12_fb[cm->lst_fb_idx].flags &= ~VP8_LAST_FLAG;
3158 cm->lst_fb_idx = cm->new_fb_idx;
3162 void loopfilter_frame(VP8_COMP *cpi, VP8_COMMON *cm)
3166 cm->filter_level = 0;
3170 struct vpx_usec_timer timer;
3172 vp8_clear_system_state();
3174 vpx_usec_timer_start(&timer);
3175 if (cpi->sf.auto_filter == 0)
3176 vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3179 vp8cx_pick_filter_level(cpi->Source, cpi);
3181 vpx_usec_timer_mark(&timer);
3182 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
3185 #if CONFIG_MULTITHREAD
3186 if (cpi->b_multi_threaded)
3187 sem_post(&cpi->h_event_end_lpf); /* signal that we have set filter_level */
3190 if (cm->filter_level > 0)
3192 vp8cx_set_alt_lf_level(cpi, cm->filter_level);
3193 vp8_loop_filter_frame(cm, &cpi->mb.e_mbd);
3196 vp8_yv12_extend_frame_borders_ptr(cm->frame_to_show);
3200 static void encode_frame_to_data_rate
3203 unsigned long *size,
3204 unsigned char *dest,
3205 unsigned int *frame_flags
3209 int frame_over_shoot_limit;
3210 int frame_under_shoot_limit;
3220 int zbin_oq_low = 0;
3223 VP8_COMMON *cm = &cpi->common;
3224 int active_worst_qchanged = FALSE;
3226 int overshoot_seen = FALSE;
3227 int undershoot_seen = FALSE;
3228 int drop_mark = cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100;
3229 int drop_mark75 = drop_mark * 2 / 3;
3230 int drop_mark50 = drop_mark / 4;
3231 int drop_mark25 = drop_mark / 8;
3234 // Clear down mmx registers to allow floating point in what follows
3235 vp8_clear_system_state();
3237 // Test code for segmentation of gf/arf (0,0)
3238 //segmentation_test_function((VP8_PTR) cpi);
3240 if (cpi->compressor_speed == 2)
3242 if(cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3244 if(cpi->force_next_frame_intra)
3246 cm->frame_type = KEY_FRAME; /* delayed intra frame */
3249 cpi->force_next_frame_intra = 0;
3252 // For an alt ref frame in 2 pass we skip the call to the second pass function that sets the target bandwidth
3253 #if !(CONFIG_REALTIME_ONLY)
3257 if (cpi->common.refresh_alt_ref_frame)
3259 cpi->per_frame_bandwidth = cpi->twopass.gf_bits; // Per frame bit target for the alt ref frame
3260 cpi->target_bandwidth = cpi->twopass.gf_bits * cpi->output_frame_rate; // per second target bitrate
3265 cpi->per_frame_bandwidth = (int)(cpi->target_bandwidth / cpi->output_frame_rate);
3267 // Default turn off buffer to buffer copying
3268 cm->copy_buffer_to_gf = 0;
3269 cm->copy_buffer_to_arf = 0;
3271 // Clear zbin over-quant value and mode boost values.
3272 cpi->zbin_over_quant = 0;
3273 cpi->zbin_mode_boost = 0;
3275 // Enable or disable mode based tweaking of the zbin
3276 // For 2 Pass Only used where GF/ARF prediction quality
3277 // is above a threshold
3278 cpi->zbin_mode_boost = 0;
3279 cpi->zbin_mode_boost_enabled = TRUE;
3282 if ( cpi->gfu_boost <= 400 )
3284 cpi->zbin_mode_boost_enabled = FALSE;
3288 // Current default encoder behaviour for the altref sign bias
3289 if (cpi->source_alt_ref_active)
3290 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
3292 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
3294 // Check to see if a key frame is signalled
3295 // For two pass with auto key frame enabled cm->frame_type may already be set, but not for one pass.
3296 if ((cm->current_video_frame == 0) ||
3297 (cm->frame_flags & FRAMEFLAGS_KEY) ||
3298 (cpi->oxcf.auto_key && (cpi->frames_since_key % cpi->key_frame_frequency == 0)))
3300 // Key frame from VFW/auto-keyframe/first frame
3301 cm->frame_type = KEY_FRAME;
3304 // Set default state for segment and mode based loop filter update flags
3305 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
3306 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
3307 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
3309 // Set various flags etc to special state if it is a key frame
3310 if (cm->frame_type == KEY_FRAME)
3314 // Reset the loop filter deltas and segmentation map
3315 setup_features(cpi);
3317 // If segmentation is enabled force a map update for key frames
3318 if (cpi->mb.e_mbd.segmentation_enabled)
3320 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3321 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3324 // The alternate reference frame cannot be active for a key frame
3325 cpi->source_alt_ref_active = FALSE;
3327 // Reset the RD threshold multipliers to default of * 1 (128)
3328 for (i = 0; i < MAX_MODES; i++)
3330 cpi->rd_thresh_mult[i] = 128;
3334 // Test code for segmentation
3335 //if ( (cm->frame_type == KEY_FRAME) || ((cm->current_video_frame % 2) == 0))
3336 //if ( (cm->current_video_frame % 2) == 0 )
3337 // enable_segmentation((VP8_PTR)cpi);
3339 // disable_segmentation((VP8_PTR)cpi);
3342 // Experimental code for lagged compress and one pass
3343 // Initialise one_pass GF frames stats
3344 // Update stats used for GF selection
3345 //if ( cpi->pass == 0 )
3347 cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
3349 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
3350 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
3351 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
3352 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
3353 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
3354 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
3355 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
3356 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
3357 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
3361 update_rd_ref_frame_probs(cpi);
3363 if (cpi->drop_frames_allowed)
3365 // The reset to decimation 0 is only done here for one pass.
3366 // Once it is set two pass leaves decimation on till the next kf.
3367 if ((cpi->buffer_level > drop_mark) && (cpi->decimation_factor > 0))
3368 cpi->decimation_factor --;
3370 if (cpi->buffer_level > drop_mark75 && cpi->decimation_factor > 0)
3371 cpi->decimation_factor = 1;
3373 else if (cpi->buffer_level < drop_mark25 && (cpi->decimation_factor == 2 || cpi->decimation_factor == 3))
3375 cpi->decimation_factor = 3;
3377 else if (cpi->buffer_level < drop_mark50 && (cpi->decimation_factor == 1 || cpi->decimation_factor == 2))
3379 cpi->decimation_factor = 2;
3381 else if (cpi->buffer_level < drop_mark75 && (cpi->decimation_factor == 0 || cpi->decimation_factor == 1))
3383 cpi->decimation_factor = 1;
3386 //vpx_log("Encoder: Decimation Factor: %d \n",cpi->decimation_factor);
3389 // The following decimates the frame rate according to a regular pattern (i.e. to 1/2 or 2/3 frame rate)
3390 // This can be used to help prevent buffer under-run in CBR mode. Alternatively it might be desirable in
3391 // some situations to drop frame rate but throw more bits at each frame.
3393 // Note that dropping a key frame can be problematic if spatial resampling is also active
3394 if (cpi->decimation_factor > 0)
3396 switch (cpi->decimation_factor)
3399 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 3 / 2;
3402 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3405 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3409 // Note that we should not throw out a key frame (especially when spatial resampling is enabled).
3410 if ((cm->frame_type == KEY_FRAME)) // && cpi->oxcf.allow_spatial_resampling )
3412 cpi->decimation_count = cpi->decimation_factor;
3414 else if (cpi->decimation_count > 0)
3416 cpi->decimation_count --;
3417 cpi->bits_off_target += cpi->av_per_frame_bandwidth;
3418 cm->current_video_frame++;
3419 cpi->frames_since_key++;
3421 #if CONFIG_INTERNAL_STATS
3425 cpi->buffer_level = cpi->bits_off_target;
3430 cpi->decimation_count = cpi->decimation_factor;
3433 // Decide how big to make the frame
3434 if (!vp8_pick_frame_size(cpi))
3436 cm->current_video_frame++;
3437 cpi->frames_since_key++;
3441 // Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
3442 // This has a knock on effect on active best quality as well.
3443 // For CBR if the buffer reaches its maximum level then we can no longer
3444 // save up bits for later frames so we might as well use them up
3445 // on the current frame.
3446 if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
3447 (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) && cpi->buffered_mode)
3449 int Adjustment = cpi->active_worst_quality / 4; // Max adjustment is 1/4
3455 if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size)
3457 buff_lvl_step = (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level) / Adjustment;
3460 Adjustment = (cpi->buffer_level - cpi->oxcf.optimal_buffer_level) / buff_lvl_step;
3465 cpi->active_worst_quality -= Adjustment;
3467 if(cpi->active_worst_quality < cpi->active_best_quality)
3468 cpi->active_worst_quality = cpi->active_best_quality;
3472 // Set an active best quality and if necessary active worst quality
3473 // There is some odd behaviour for one pass here that needs attention.
3474 if ( (cpi->pass == 2) || (cpi->ni_frames > 150))
3476 vp8_clear_system_state();
3478 Q = cpi->active_worst_quality;
3480 if ( cm->frame_type == KEY_FRAME )
3482 if ( cpi->pass == 2 )
3484 if (cpi->gfu_boost > 600)
3485 cpi->active_best_quality = kf_low_motion_minq[Q];
3487 cpi->active_best_quality = kf_high_motion_minq[Q];
3489 // Special case for key frames forced because we have reached
3490 // the maximum key frame interval. Here force the Q to a range
3491 // based on the ambient Q to reduce the risk of popping
3492 if ( cpi->this_key_frame_forced )
3494 if ( cpi->active_best_quality > cpi->avg_frame_qindex * 7/8)
3495 cpi->active_best_quality = cpi->avg_frame_qindex * 7/8;
3496 else if ( cpi->active_best_quality < cpi->avg_frame_qindex >> 2 )
3497 cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
3500 // One pass more conservative
3502 cpi->active_best_quality = kf_high_motion_minq[Q];
3505 else if (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame)
3507 // Use the lower of cpi->active_worst_quality and recent
3508 // average Q as basis for GF/ARF Q limit unless last frame was
3510 if ( (cpi->frames_since_key > 1) &&
3511 (cpi->avg_frame_qindex < cpi->active_worst_quality) )
3513 Q = cpi->avg_frame_qindex;
3515 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3516 (Q < cpi->oxcf.cq_level) )
3518 Q = cpi->oxcf.cq_level;
3522 if ( cpi->pass == 2 )
3524 if ( cpi->gfu_boost > 1000 )
3525 cpi->active_best_quality = gf_low_motion_minq[Q];
3526 else if ( cpi->gfu_boost < 400 )
3527 cpi->active_best_quality = gf_high_motion_minq[Q];
3529 cpi->active_best_quality = gf_mid_motion_minq[Q];
3531 // One pass more conservative
3533 cpi->active_best_quality = gf_high_motion_minq[Q];
3537 cpi->active_best_quality = inter_minq[Q];
3539 // For the constant/constrained quality mode we dont want
3540 // the quality to rise above the cq level.
3541 if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3542 (cpi->active_best_quality < cpi->cq_target_quality) )
3544 // If we are strongly undershooting the target rate in the last
3545 // frames then use the user passed in cq value not the auto
3547 if ( cpi->rolling_actual_bits < cpi->min_frame_bandwidth )
3548 cpi->active_best_quality = cpi->oxcf.cq_level;
3550 cpi->active_best_quality = cpi->cq_target_quality;
3554 // If CBR and the buffer is as full then it is reasonable to allow
3555 // higher quality on the frames to prevent bits just going to waste.
3556 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
3558 // Note that the use of >= here elliminates the risk of a devide
3559 // by 0 error in the else if clause
3560 if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size)
3561 cpi->active_best_quality = cpi->best_quality;
3563 else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level)
3565 int Fraction = ((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) / (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level);
3566 int min_qadjustment = ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;
3568 cpi->active_best_quality -= min_qadjustment;
3572 // Make sure constrained quality mode limits are adhered to for the first
3573 // few frames of one pass encodes
3574 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
3576 if ( (cm->frame_type == KEY_FRAME) ||
3577 cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame )
3579 cpi->active_best_quality = cpi->best_quality;
3581 else if (cpi->active_best_quality < cpi->cq_target_quality)
3583 cpi->active_best_quality = cpi->cq_target_quality;
3587 // Clip the active best and worst quality values to limits
3588 if (cpi->active_worst_quality > cpi->worst_quality)
3589 cpi->active_worst_quality = cpi->worst_quality;
3591 if (cpi->active_best_quality < cpi->best_quality)
3592 cpi->active_best_quality = cpi->best_quality;
3593 else if (cpi->active_best_quality > cpi->active_worst_quality)
3594 cpi->active_best_quality = cpi->active_worst_quality;
3596 // Determine initial Q to try
3597 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3598 last_zbin_oq = cpi->zbin_over_quant;
3600 // Set highest allowed value for Zbin over quant
3601 if (cm->frame_type == KEY_FRAME)
3602 zbin_oq_high = 0; //ZBIN_OQ_MAX/16
3603 else if (cm->refresh_alt_ref_frame || (cm->refresh_golden_frame && !cpi->source_alt_ref_active))
3606 zbin_oq_high = ZBIN_OQ_MAX;
3608 // Setup background Q adjustment for error resilliant mode
3609 if (cpi->cyclic_refresh_mode_enabled)
3610 cyclic_background_refresh(cpi, Q, 0);
3612 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3614 // Limit Q range for the adaptive loop.
3615 bottom_index = cpi->active_best_quality;
3616 top_index = cpi->active_worst_quality;
3617 q_low = cpi->active_best_quality;
3618 q_high = cpi->active_worst_quality;
3620 vp8_save_coding_context(cpi);
3625 scale_and_extend_source(cpi->un_scaled_source, cpi);
3626 #if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC
3628 if (cpi->oxcf.noise_sensitivity > 0)
3633 switch (cpi->oxcf.noise_sensitivity)
3656 if (cm->frame_type == KEY_FRAME)
3658 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0, RTCD(postproc));
3662 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0, RTCD(postproc));
3664 src = cpi->Source->y_buffer;
3666 if (cpi->Source->y_stride < 0)
3668 src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
3675 #ifdef OUTPUT_YUV_SRC
3676 vp8_write_yuv_frame(cpi->Source);
3681 vp8_clear_system_state(); //__asm emms;
3684 if(cpi->is_src_frame_alt_ref)
3688 vp8_set_quantizer(cpi, Q);
3691 // setup skip prob for costing in mode/mv decision
3692 if (cpi->common.mb_no_coeff_skip)
3694 cpi->prob_skip_false = cpi->base_skip_false_prob[Q];
3696 if (cm->frame_type != KEY_FRAME)
3698 if (cpi->common.refresh_alt_ref_frame)
3700 if (cpi->last_skip_false_probs[2] != 0)
3701 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3704 if(cpi->last_skip_false_probs[2]!=0 && abs(Q- cpi->last_skip_probs_q[2])<=16 )
3705 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3706 else if (cpi->last_skip_false_probs[2]!=0)
3707 cpi->prob_skip_false = (cpi->last_skip_false_probs[2] + cpi->prob_skip_false ) / 2;
3710 else if (cpi->common.refresh_golden_frame)
3712 if (cpi->last_skip_false_probs[1] != 0)
3713 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3716 if(cpi->last_skip_false_probs[1]!=0 && abs(Q- cpi->last_skip_probs_q[1])<=16 )
3717 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3718 else if (cpi->last_skip_false_probs[1]!=0)
3719 cpi->prob_skip_false = (cpi->last_skip_false_probs[1] + cpi->prob_skip_false ) / 2;
3724 if (cpi->last_skip_false_probs[0] != 0)
3725 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3728 if(cpi->last_skip_false_probs[0]!=0 && abs(Q- cpi->last_skip_probs_q[0])<=16 )
3729 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3730 else if(cpi->last_skip_false_probs[0]!=0)
3731 cpi->prob_skip_false = (cpi->last_skip_false_probs[0] + cpi->prob_skip_false ) / 2;
3735 //as this is for cost estimate, let's make sure it does not go extreme eitehr way
3736 if (cpi->prob_skip_false < 5)
3737 cpi->prob_skip_false = 5;
3739 if (cpi->prob_skip_false > 250)
3740 cpi->prob_skip_false = 250;
3742 if (cpi->is_src_frame_alt_ref)
3743 cpi->prob_skip_false = 1;
3752 FILE *f = fopen("skip.stt", "a");
3753 fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
3761 if (cm->frame_type == KEY_FRAME)
3763 resize_key_frame(cpi);
3764 vp8_setup_key_frame(cpi);
3767 // transform / motion compensation build reconstruction frame
3768 vp8_encode_frame(cpi);
3770 cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
3771 cpi->projected_frame_size = (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
3773 vp8_clear_system_state(); //__asm emms;
3775 // Test to see if the stats generated for this frame indicate that we should have coded a key frame
3776 // (assuming that we didn't)!
3777 if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3779 int key_frame_decision = decide_key_frame(cpi);
3781 if (cpi->compressor_speed == 2)
3783 /* we don't do re-encoding in realtime mode
3784 * if key frame is decided than we force it on next frame */
3785 cpi->force_next_frame_intra = key_frame_decision;
3787 else if (key_frame_decision)
3789 // Reset all our sizing numbers and recode
3790 cm->frame_type = KEY_FRAME;
3792 vp8_pick_frame_size(cpi);
3794 // Clear the Alt reference frame active flag when we have a key frame
3795 cpi->source_alt_ref_active = FALSE;
3797 // Reset the loop filter deltas and segmentation map
3798 setup_features(cpi);
3800 // If segmentation is enabled force a map update for key frames
3801 if (cpi->mb.e_mbd.segmentation_enabled)
3803 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3804 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3807 vp8_restore_coding_context(cpi);
3809 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3811 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3813 // Limit Q range for the adaptive loop.
3814 bottom_index = cpi->active_best_quality;
3815 top_index = cpi->active_worst_quality;
3816 q_low = cpi->active_best_quality;
3817 q_high = cpi->active_worst_quality;
3826 vp8_clear_system_state();
3828 if (frame_over_shoot_limit == 0)
3829 frame_over_shoot_limit = 1;
3831 // Are we are overshooting and up against the limit of active max Q.
3832 if (((cpi->pass != 2) || (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
3833 (Q == cpi->active_worst_quality) &&
3834 (cpi->active_worst_quality < cpi->worst_quality) &&
3835 (cpi->projected_frame_size > frame_over_shoot_limit))
3837 int over_size_percent = ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) / frame_over_shoot_limit;
3839 // If so is there any scope for relaxing it
3840 while ((cpi->active_worst_quality < cpi->worst_quality) && (over_size_percent > 0))
3842 cpi->active_worst_quality++;
3843 top_index = cpi->active_worst_quality;
3844 over_size_percent = (int)(over_size_percent * 0.96); // Assume 1 qstep = about 4% on frame size.
3847 // If we have updated the active max Q do not call vp8_update_rate_correction_factors() this loop.
3848 active_worst_qchanged = TRUE;
3851 active_worst_qchanged = FALSE;
3853 #if !(CONFIG_REALTIME_ONLY)
3854 // Special case handling for forced key frames
3855 if ( (cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced )
3858 int kf_err = vp8_calc_ss_err(cpi->Source,
3859 &cm->yv12_fb[cm->new_fb_idx],
3860 IF_RTCD(&cpi->rtcd.variance));
3862 // The key frame is not good enough
3863 if ( kf_err > ((cpi->ambient_err * 7) >> 3) )
3866 q_high = (Q > q_low) ? (Q - 1) : q_low;
3869 Q = (q_high + q_low) >> 1;
3871 // The key frame is much better than the previous frame
3872 else if ( kf_err < (cpi->ambient_err >> 1) )
3875 q_low = (Q < q_high) ? (Q + 1) : q_high;
3878 Q = (q_high + q_low + 1) >> 1;
3881 // Clamp Q to upper and lower limits:
3887 Loop = ((Q != last_q)) ? TRUE : FALSE;
3890 // Is the projected frame size out of range and are we allowed to attempt to recode.
3891 else if ( recode_loop_test( cpi,
3892 frame_over_shoot_limit, frame_under_shoot_limit,
3893 Q, top_index, bottom_index ) )
3898 // Frame size out of permitted range:
3899 // Update correction factor & compute new Q to try...
3901 // Frame is too large
3902 if (cpi->projected_frame_size > cpi->this_frame_target)
3904 //if ( cpi->zbin_over_quant == 0 )
3905 q_low = (Q < q_high) ? (Q + 1) : q_high; // Raise Qlow as to at least the current value
3907 if (cpi->zbin_over_quant > 0) // If we are using over quant do the same for zbin_oq_low
3908 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
3910 //if ( undershoot_seen || (Q == MAXQ) )
3911 if (undershoot_seen)
3913 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3914 if (!active_worst_qchanged)
3915 vp8_update_rate_correction_factors(cpi, 1);
3917 Q = (q_high + q_low + 1) / 2;
3919 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
3921 cpi->zbin_over_quant = 0;
3924 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
3925 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 while (((Q < q_low) || (cpi->zbin_over_quant < zbin_oq_low)) && (Retries < 10))
3938 vp8_update_rate_correction_factors(cpi, 0);
3939 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3944 overshoot_seen = TRUE;
3946 // Frame is too small
3949 if (cpi->zbin_over_quant == 0)
3950 q_high = (Q > q_low) ? (Q - 1) : q_low; // Lower q_high if not using over quant
3951 else // else lower zbin_oq_high
3952 zbin_oq_high = (cpi->zbin_over_quant > zbin_oq_low) ? (cpi->zbin_over_quant - 1) : zbin_oq_low;
3956 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3957 if (!active_worst_qchanged)
3958 vp8_update_rate_correction_factors(cpi, 1);
3960 Q = (q_high + q_low) / 2;
3962 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
3964 cpi->zbin_over_quant = 0;
3966 cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
3970 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3971 if (!active_worst_qchanged)
3972 vp8_update_rate_correction_factors(cpi, 0);
3974 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3976 // Special case reset for qlow for constrained quality.
3977 // This should only trigger where there is very substantial
3978 // undershoot on a frame and the auto cq level is above
3979 // the user passsed in value.
3980 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3986 while (((Q > q_high) || (cpi->zbin_over_quant > zbin_oq_high)) && (Retries < 10))
3988 vp8_update_rate_correction_factors(cpi, 0);
3989 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3994 undershoot_seen = TRUE;
3997 // Clamp Q to upper and lower limits:
4003 // Clamp cpi->zbin_over_quant
4004 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;
4006 //Loop = ((Q != last_q) || (last_zbin_oq != cpi->zbin_over_quant)) ? TRUE : FALSE;
4007 Loop = ((Q != last_q)) ? TRUE : FALSE;
4008 last_zbin_oq = cpi->zbin_over_quant;
4014 if (cpi->is_src_frame_alt_ref)
4019 vp8_restore_coding_context(cpi);
4021 #if CONFIG_INTERNAL_STATS
4022 cpi->tot_recode_hits++;
4026 while (Loop == TRUE);
4029 // Experimental code for lagged and one pass
4030 // Update stats used for one pass GF selection
4034 double frame_intra_error;
4035 double frame_coded_error;
4036 double frame_pcnt_inter;
4037 double frame_pcnt_motion;
4039 double frame_mvr_abs;
4041 double frame_mvc_abs;
4044 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
4045 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
4046 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
4050 // Special case code to reduce pulsing when key frames are forced at a
4051 // fixed interval. Note the reconstruction error if it is the frame before
4052 // the force key frame
4053 if ( cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0) )
4055 cpi->ambient_err = vp8_calc_ss_err(cpi->Source,
4056 &cm->yv12_fb[cm->new_fb_idx],
4057 IF_RTCD(&cpi->rtcd.variance));
4060 // This frame's MVs are saved and will be used in next frame's MV prediction.
4061 // Last frame has one more line(add to bottom) and one more column(add to right) than cm->mip. The edge elements are initialized to 0.
4062 if(cm->show_frame) //do not save for altref frame
4066 MODE_INFO *tmp = cm->mip; //point to beginning of allocated MODE_INFO arrays.
4068 if(cm->frame_type != KEY_FRAME)
4070 for (mb_row = 0; mb_row < cm->mb_rows+1; mb_row ++)
4072 for (mb_col = 0; mb_col < cm->mb_cols+1; mb_col ++)
4074 if(tmp->mbmi.ref_frame != INTRA_FRAME)
4075 cpi->lfmv[mb_col + mb_row*(cm->mode_info_stride+1)].as_int = tmp->mbmi.mv.as_int;
4077 cpi->lf_ref_frame_sign_bias[mb_col + mb_row*(cm->mode_info_stride+1)] = cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
4078 cpi->lf_ref_frame[mb_col + mb_row*(cm->mode_info_stride+1)] = tmp->mbmi.ref_frame;
4085 // Update the GF useage maps.
4086 // This is done after completing the compression of a frame when all modes etc. are finalized but before loop filter
4087 // This is done after completing the compression of a frame when all modes etc. are finalized but before loop filter
4088 vp8_update_gf_useage_maps(cpi, cm, &cpi->mb);
4090 if (cm->frame_type == KEY_FRAME)
4091 cm->refresh_last_frame = 1;
4095 FILE *f = fopen("gfactive.stt", "a");
4096 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);
4101 // For inter frames the current default behavior is that when
4102 // cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
4103 // This is purely an encoder decision at present.
4104 if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame)
4105 cm->copy_buffer_to_arf = 2;
4107 cm->copy_buffer_to_arf = 0;
4109 cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
4111 #if CONFIG_MULTITHREAD
4112 if (cpi->b_multi_threaded)
4114 sem_post(&cpi->h_event_start_lpf); /* start loopfilter in separate thread */
4119 loopfilter_frame(cpi, cm);
4122 update_reference_frames(cm);
4124 if (cpi->oxcf.error_resilient_mode)
4126 cm->refresh_entropy_probs = 0;
4129 #if CONFIG_MULTITHREAD
4130 /* wait that filter_level is picked so that we can continue with stream packing */
4131 if (cpi->b_multi_threaded)
4132 sem_wait(&cpi->h_event_end_lpf);
4135 // build the bitstream
4136 vp8_pack_bitstream(cpi, dest, size);
4138 #if CONFIG_MULTITHREAD
4139 /* wait for loopfilter thread done */
4140 if (cpi->b_multi_threaded)
4142 sem_wait(&cpi->h_event_end_lpf);
4146 /* Move storing frame_type out of the above loop since it is also
4147 * needed in motion search besides loopfilter */
4148 cm->last_frame_type = cm->frame_type;
4150 // Update rate control heuristics
4151 cpi->total_byte_count += (*size);
4152 cpi->projected_frame_size = (*size) << 3;
4154 if (!active_worst_qchanged)
4155 vp8_update_rate_correction_factors(cpi, 2);
4157 cpi->last_q[cm->frame_type] = cm->base_qindex;
4159 if (cm->frame_type == KEY_FRAME)
4161 vp8_adjust_key_frame_context(cpi);
4164 // Keep a record of ambient average Q.
4165 if (cm->frame_type != KEY_FRAME)
4166 cpi->avg_frame_qindex = (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
4168 // Keep a record from which we can calculate the average Q excluding GF updates and key frames
4169 if ((cm->frame_type != KEY_FRAME) && !cm->refresh_golden_frame && !cm->refresh_alt_ref_frame)
4173 // Calculate the average Q for normal inter frames (not key or GFU
4175 if ( cpi->pass == 2 )
4177 cpi->ni_tot_qi += Q;
4178 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4182 // Damp value for first few frames
4183 if (cpi->ni_frames > 150 )
4185 cpi->ni_tot_qi += Q;
4186 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4188 // For one pass, early in the clip ... average the current frame Q
4189 // value with the worstq entered by the user as a dampening measure
4192 cpi->ni_tot_qi += Q;
4193 cpi->ni_av_qi = ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
4196 // If the average Q is higher than what was used in the last frame
4197 // (after going through the recode loop to keep the frame size within range)
4198 // then use the last frame value - 1.
4199 // The -1 is designed to stop Q and hence the data rate, from progressively
4200 // falling away during difficult sections, but at the same time reduce the number of
4201 // itterations around the recode loop.
4202 if (Q > cpi->ni_av_qi)
4203 cpi->ni_av_qi = Q - 1;
4209 // If the frame was massively oversize and we are below optimal buffer level drop next frame
4210 if ((cpi->drop_frames_allowed) &&
4211 (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
4212 (cpi->buffer_level < cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100) &&
4213 (cpi->projected_frame_size > (4 * cpi->this_frame_target)))
4215 cpi->drop_frame = TRUE;
4220 // Set the count for maximum consequative dropped frames based upon the ratio of
4221 // this frame size to the target average per frame bandwidth.
4222 // (cpi->av_per_frame_bandwidth > 0) is just a sanity check to prevent / 0.
4223 if (cpi->drop_frames_allowed && (cpi->av_per_frame_bandwidth > 0))
4225 cpi->max_drop_count = cpi->projected_frame_size / cpi->av_per_frame_bandwidth;
4227 if (cpi->max_drop_count > cpi->max_consec_dropped_frames)
4228 cpi->max_drop_count = cpi->max_consec_dropped_frames;
4231 // Update the buffer level variable.
4232 // Non-viewable frames are a special case and are treated as pure overhead.
4233 if ( !cm->show_frame )
4234 cpi->bits_off_target -= cpi->projected_frame_size;
4236 cpi->bits_off_target += cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
4238 // Rolling monitors of whether we are over or underspending used to help regulate min and Max Q in two pass.
4239 cpi->rolling_target_bits = ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
4240 cpi->rolling_actual_bits = ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
4241 cpi->long_rolling_target_bits = ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
4242 cpi->long_rolling_actual_bits = ((cpi->long_rolling_actual_bits * 31) + cpi->projected_frame_size + 16) / 32;
4244 // Actual bits spent
4245 cpi->total_actual_bits += cpi->projected_frame_size;
4248 cpi->total_target_vs_actual += (cpi->this_frame_target - cpi->projected_frame_size);
4250 cpi->buffer_level = cpi->bits_off_target;
4252 // Update bits left to the kf and gf groups to account for overshoot or undershoot on these frames
4253 if (cm->frame_type == KEY_FRAME)
4255 cpi->twopass.kf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4257 if (cpi->twopass.kf_group_bits < 0)
4258 cpi->twopass.kf_group_bits = 0 ;
4260 else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4262 cpi->twopass.gf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4264 if (cpi->twopass.gf_group_bits < 0)
4265 cpi->twopass.gf_group_bits = 0 ;
4268 if (cm->frame_type != KEY_FRAME)
4270 if (cpi->common.refresh_alt_ref_frame)
4272 cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
4273 cpi->last_skip_probs_q[2] = cm->base_qindex;
4275 else if (cpi->common.refresh_golden_frame)
4277 cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
4278 cpi->last_skip_probs_q[1] = cm->base_qindex;
4282 cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
4283 cpi->last_skip_probs_q[0] = cm->base_qindex;
4285 //update the baseline
4286 cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
4291 #if 0 && CONFIG_INTERNAL_STATS
4293 FILE *f = fopen("tmp.stt", "a");
4295 vp8_clear_system_state(); //__asm emms;
4297 if (cpi->twopass.total_coded_error_left != 0.0)
4298 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4299 "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4301 cpi->common.current_video_frame, cpi->this_frame_target,
4302 cpi->projected_frame_size,
4303 (cpi->projected_frame_size - cpi->this_frame_target),
4304 (int)cpi->total_target_vs_actual,
4305 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4306 (int)cpi->total_actual_bits, cm->base_qindex,
4307 cpi->active_best_quality, cpi->active_worst_quality,
4308 cpi->ni_av_qi, cpi->cq_target_quality, cpi->zbin_over_quant,
4309 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4310 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4311 cm->frame_type, cpi->gfu_boost,
4312 cpi->twopass.est_max_qcorrection_factor, (int)cpi->twopass.bits_left,
4313 cpi->twopass.total_coded_error_left,
4314 (double)cpi->twopass.bits_left / cpi->twopass.total_coded_error_left,
4315 cpi->tot_recode_hits);
4317 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4318 "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4320 cpi->common.current_video_frame,
4321 cpi->this_frame_target, cpi->projected_frame_size,
4322 (cpi->projected_frame_size - cpi->this_frame_target),
4323 (int)cpi->total_target_vs_actual,
4324 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4325 (int)cpi->total_actual_bits, cm->base_qindex,
4326 cpi->active_best_quality, cpi->active_worst_quality,
4327 cpi->ni_av_qi, cpi->cq_target_quality, cpi->zbin_over_quant,
4328 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4329 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4330 cm->frame_type, cpi->gfu_boost,
4331 cpi->twopass.est_max_qcorrection_factor, (int)cpi->twopass.bits_left,
4332 cpi->twopass.total_coded_error_left, cpi->tot_recode_hits);
4337 FILE *fmodes = fopen("Modes.stt", "a");
4340 fprintf(fmodes, "%6d:%1d:%1d:%1d ",
4341 cpi->common.current_video_frame,
4342 cm->frame_type, cm->refresh_golden_frame,
4343 cm->refresh_alt_ref_frame);
4345 for (i = 0; i < MAX_MODES; i++)
4346 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
4348 fprintf(fmodes, "\n");
4356 // If this was a kf or Gf note the Q
4357 if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4358 cm->last_kf_gf_q = cm->base_qindex;
4360 if (cm->refresh_golden_frame == 1)
4361 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
4363 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
4365 if (cm->refresh_alt_ref_frame == 1)
4366 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
4368 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
4371 if (cm->refresh_last_frame & cm->refresh_golden_frame) // both refreshed
4372 cpi->gold_is_last = 1;
4373 else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4374 cpi->gold_is_last = 0;
4376 if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) // both refreshed
4377 cpi->alt_is_last = 1;
4378 else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) // 1 refreshed but not the other
4379 cpi->alt_is_last = 0;
4381 if (cm->refresh_alt_ref_frame & cm->refresh_golden_frame) // both refreshed
4382 cpi->gold_is_alt = 1;
4383 else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4384 cpi->gold_is_alt = 0;
4386 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
4388 if (cpi->gold_is_last)
4389 cpi->ref_frame_flags &= ~VP8_GOLD_FLAG;
4391 if (cpi->alt_is_last)
4392 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4394 if (cpi->gold_is_alt)
4395 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4398 if (!cpi->oxcf.error_resilient_mode)
4400 if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame && (cm->frame_type != KEY_FRAME))
4401 // Update the alternate reference frame stats as appropriate.
4402 update_alt_ref_frame_stats(cpi);
4404 // Update the Golden frame stats as appropriate.
4405 update_golden_frame_stats(cpi);
4408 if (cm->frame_type == KEY_FRAME)
4410 // Tell the caller that the frame was coded as a key frame
4411 *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
4413 // As this frame is a key frame the next defaults to an inter frame.
4414 cm->frame_type = INTER_FRAME;
4416 cpi->last_frame_percent_intra = 100;
4420 *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
4422 cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
4425 // Clear the one shot update flags for segmentation map and mode/ref loop filter deltas.
4426 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
4427 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
4428 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
4431 // Dont increment frame counters if this was an altref buffer update not a real frame
4434 cm->current_video_frame++;
4435 cpi->frames_since_key++;
4438 // reset to normal state now that we are done.
4446 sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
4447 recon_file = fopen(filename, "wb");
4448 fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
4449 cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
4455 //vp8_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show);
4461 static void check_gf_quality(VP8_COMP *cpi)
4463 VP8_COMMON *cm = &cpi->common;
4464 int gf_active_pct = (100 * cpi->gf_active_count) / (cm->mb_rows * cm->mb_cols);
4465 int gf_ref_usage_pct = (cpi->count_mb_ref_frame_usage[GOLDEN_FRAME] * 100) / (cm->mb_rows * cm->mb_cols);
4466 int last_ref_zz_useage = (cpi->inter_zz_count * 100) / (cm->mb_rows * cm->mb_cols);
4468 // Gf refresh is not currently being signalled
4469 if (cpi->gf_update_recommended == 0)
4471 if (cpi->common.frames_since_golden > 7)
4474 if ((gf_active_pct < 10) || ((gf_active_pct + gf_ref_usage_pct) < 15))
4476 // ...but last frame zero zero usage is reasonbable so a new gf might be appropriate
4477 if (last_ref_zz_useage >= 25)
4479 cpi->gf_bad_count ++;
4481 if (cpi->gf_bad_count >= 8) // Check that the condition is stable
4483 cpi->gf_update_recommended = 1;
4484 cpi->gf_bad_count = 0;
4488 cpi->gf_bad_count = 0; // Restart count as the background is not stable enough
4491 cpi->gf_bad_count = 0; // Gf useage has picked up so reset count
4494 // If the signal is set but has not been read should we cancel it.
4495 else if (last_ref_zz_useage < 15)
4497 cpi->gf_update_recommended = 0;
4498 cpi->gf_bad_count = 0;
4503 FILE *f = fopen("gfneeded.stt", "a");
4504 fprintf(f, "%10d %10d %10d %10d %10ld \n",
4505 cm->current_video_frame,
4506 cpi->common.frames_since_golden,
4507 gf_active_pct, gf_ref_usage_pct,
4508 cpi->gf_update_recommended);
4515 #if !(CONFIG_REALTIME_ONLY)
4516 static void Pass2Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags)
4519 if (!cpi->common.refresh_alt_ref_frame)
4520 vp8_second_pass(cpi);
4522 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4523 cpi->twopass.bits_left -= 8 * *size;
4525 if (!cpi->common.refresh_alt_ref_frame)
4527 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
4528 *cpi->oxcf.two_pass_vbrmin_section / 100);
4529 cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->oxcf.frame_rate);
4534 //For ARM NEON, d8-d15 are callee-saved registers, and need to be saved by us.
4536 extern void vp8_push_neon(int64_t *store);
4537 extern void vp8_pop_neon(int64_t *store);
4541 int vp8_receive_raw_frame(VP8_PTR ptr, unsigned int frame_flags, YV12_BUFFER_CONFIG *sd, int64_t time_stamp, int64_t end_time)
4544 int64_t store_reg[8];
4546 VP8_COMP *cpi = (VP8_COMP *) ptr;
4547 VP8_COMMON *cm = &cpi->common;
4548 struct vpx_usec_timer timer;
4552 #if CONFIG_RUNTIME_CPU_DETECT
4553 if (cm->rtcd.flags & HAS_NEON)
4556 vp8_push_neon(store_reg);
4560 vpx_usec_timer_start(&timer);
4561 if(vp8_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4562 frame_flags, cpi->active_map_enabled ? cpi->active_map : NULL))
4564 cm->clr_type = sd->clrtype;
4565 vpx_usec_timer_mark(&timer);
4566 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4569 #if CONFIG_RUNTIME_CPU_DETECT
4570 if (cm->rtcd.flags & HAS_NEON)
4573 vp8_pop_neon(store_reg);
4581 static int frame_is_reference(const VP8_COMP *cpi)
4583 const VP8_COMMON *cm = &cpi->common;
4584 const MACROBLOCKD *xd = &cpi->mb.e_mbd;
4586 return cm->frame_type == KEY_FRAME || cm->refresh_last_frame
4587 || cm->refresh_golden_frame || cm->refresh_alt_ref_frame
4588 || cm->copy_buffer_to_gf || cm->copy_buffer_to_arf
4589 || cm->refresh_entropy_probs
4590 || xd->mode_ref_lf_delta_update
4591 || xd->update_mb_segmentation_map || xd->update_mb_segmentation_data;
4595 int vp8_get_compressed_data(VP8_PTR ptr, unsigned int *frame_flags, unsigned long *size, unsigned char *dest, int64_t *time_stamp, int64_t *time_end, int flush)
4598 int64_t store_reg[8];
4600 VP8_COMP *cpi = (VP8_COMP *) ptr;
4601 VP8_COMMON *cm = &cpi->common;
4602 struct vpx_usec_timer tsctimer;
4603 struct vpx_usec_timer ticktimer;
4604 struct vpx_usec_timer cmptimer;
4605 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4611 #if CONFIG_RUNTIME_CPU_DETECT
4612 if (cm->rtcd.flags & HAS_NEON)
4615 vp8_push_neon(store_reg);
4619 vpx_usec_timer_start(&cmptimer);
4623 #if !(CONFIG_REALTIME_ONLY)
4624 // Should we code an alternate reference frame
4625 if (cpi->oxcf.error_resilient_mode == 0 &&
4626 cpi->oxcf.play_alternate &&
4627 cpi->source_alt_ref_pending)
4629 if ((cpi->source = vp8_lookahead_peek(cpi->lookahead,
4630 cpi->frames_till_gf_update_due)))
4632 cpi->alt_ref_source = cpi->source;
4633 if (cpi->oxcf.arnr_max_frames > 0)
4635 vp8_temporal_filter_prepare_c(cpi,
4636 cpi->frames_till_gf_update_due);
4637 force_src_buffer = &cpi->alt_ref_buffer;
4639 cm->frames_till_alt_ref_frame = cpi->frames_till_gf_update_due;
4640 cm->refresh_alt_ref_frame = 1;
4641 cm->refresh_golden_frame = 0;
4642 cm->refresh_last_frame = 0;
4644 cpi->source_alt_ref_pending = FALSE; // Clear Pending altf Ref flag.
4645 cpi->is_src_frame_alt_ref = 0;
4652 if ((cpi->source = vp8_lookahead_pop(cpi->lookahead, flush)))
4656 cpi->is_src_frame_alt_ref = cpi->alt_ref_source
4657 && (cpi->source == cpi->alt_ref_source);
4659 if(cpi->is_src_frame_alt_ref)
4660 cpi->alt_ref_source = NULL;
4666 cpi->un_scaled_source =
4667 cpi->Source = force_src_buffer ? force_src_buffer : &cpi->source->img;
4668 *time_stamp = cpi->source->ts_start;
4669 *time_end = cpi->source->ts_end;
4670 *frame_flags = cpi->source->flags;
4675 #if !(CONFIG_REALTIME_ONLY)
4677 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done)
4679 vp8_end_first_pass(cpi); /* get last stats packet */
4680 cpi->twopass.first_pass_done = 1;
4686 #if CONFIG_RUNTIME_CPU_DETECT
4687 if (cm->rtcd.flags & HAS_NEON)
4690 vp8_pop_neon(store_reg);
4696 if (cpi->source->ts_start < cpi->first_time_stamp_ever)
4698 cpi->first_time_stamp_ever = cpi->source->ts_start;
4699 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
4702 // adjust frame rates based on timestamps given
4703 if (!cm->refresh_alt_ref_frame)
4705 int64_t this_duration;
4708 if (cpi->source->ts_start == cpi->first_time_stamp_ever)
4710 this_duration = cpi->source->ts_end - cpi->source->ts_start;
4715 int64_t last_duration;
4717 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
4718 last_duration = cpi->last_end_time_stamp_seen
4719 - cpi->last_time_stamp_seen;
4720 // do a step update if the duration changes by 10%
4722 step = ((this_duration - last_duration) * 10 / last_duration);
4728 vp8_new_frame_rate(cpi, 10000000.0 / this_duration);
4731 double avg_duration, interval;
4733 /* Average this frame's rate into the last second's average
4734 * frame rate. If we haven't seen 1 second yet, then average
4735 * over the whole interval seen.
4737 interval = cpi->source->ts_end - cpi->first_time_stamp_ever;
4738 if(interval > 10000000.0)
4739 interval = 10000000;
4741 avg_duration = 10000000.0 / cpi->oxcf.frame_rate;
4742 avg_duration *= (interval - avg_duration + this_duration);
4743 avg_duration /= interval;
4745 vp8_new_frame_rate(cpi, 10000000.0 / avg_duration);
4749 cpi->last_time_stamp_seen = cpi->source->ts_start;
4750 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
4753 if (cpi->compressor_speed == 2)
4755 check_gf_quality(cpi);
4756 vpx_usec_timer_start(&tsctimer);
4757 vpx_usec_timer_start(&ticktimer);
4760 // start with a 0 size frame
4763 // Clear down mmx registers
4764 vp8_clear_system_state(); //__asm emms;
4766 cm->frame_type = INTER_FRAME;
4767 cm->frame_flags = *frame_flags;
4771 if (cm->refresh_alt_ref_frame)
4773 //cm->refresh_golden_frame = 1;
4774 cm->refresh_golden_frame = 0;
4775 cm->refresh_last_frame = 0;
4779 cm->refresh_golden_frame = 0;
4780 cm->refresh_last_frame = 1;
4784 /* find a free buffer for the new frame */
4787 for(; i < NUM_YV12_BUFFERS; i++)
4789 if(!cm->yv12_fb[i].flags)
4796 assert(i < NUM_YV12_BUFFERS );
4798 #if !(CONFIG_REALTIME_ONLY)
4802 Pass1Encode(cpi, size, dest, frame_flags);
4804 else if (cpi->pass == 2)
4806 Pass2Encode(cpi, size, dest, frame_flags);
4810 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4812 if (cpi->compressor_speed == 2)
4814 unsigned int duration, duration2;
4815 vpx_usec_timer_mark(&tsctimer);
4816 vpx_usec_timer_mark(&ticktimer);
4818 duration = vpx_usec_timer_elapsed(&ticktimer);
4819 duration2 = (unsigned int)((double)duration / 2);
4821 if (cm->frame_type != KEY_FRAME)
4823 if (cpi->avg_encode_time == 0)
4824 cpi->avg_encode_time = duration;
4826 cpi->avg_encode_time = (7 * cpi->avg_encode_time + duration) >> 3;
4831 //if(*frame_flags!=1)
4834 if (cpi->avg_pick_mode_time == 0)
4835 cpi->avg_pick_mode_time = duration2;
4837 cpi->avg_pick_mode_time = (7 * cpi->avg_pick_mode_time + duration2) >> 3;
4843 if (cm->refresh_entropy_probs == 0)
4845 vpx_memcpy(&cm->fc, &cm->lfc, sizeof(cm->fc));
4848 // if its a dropped frame honor the requests on subsequent frames
4851 cpi->droppable = !frame_is_reference(cpi);
4853 // return to normal state
4854 cm->refresh_entropy_probs = 1;
4855 cm->refresh_alt_ref_frame = 0;
4856 cm->refresh_golden_frame = 0;
4857 cm->refresh_last_frame = 1;
4858 cm->frame_type = INTER_FRAME;
4862 vpx_usec_timer_mark(&cmptimer);
4863 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4865 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
4867 generate_psnr_packet(cpi);
4870 #if CONFIG_INTERNAL_STATS
4874 cpi->bytes += *size;
4881 if (cpi->b_calculate_psnr)
4885 YV12_BUFFER_CONFIG *orig = cpi->Source;
4886 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
4887 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
4888 int y_samples = orig->y_height * orig->y_width ;
4889 int uv_samples = orig->uv_height * orig->uv_width ;
4890 int t_samples = y_samples + 2 * uv_samples;
4893 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
4894 recon->y_buffer, recon->y_stride, orig->y_width, orig->y_height,
4895 IF_RTCD(&cpi->rtcd.variance));
4897 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
4898 recon->u_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
4899 IF_RTCD(&cpi->rtcd.variance));
4901 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
4902 recon->v_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
4903 IF_RTCD(&cpi->rtcd.variance));
4905 sq_error = ye + ue + ve;
4907 frame_psnr = vp8_mse2psnr(t_samples, 255.0, sq_error);
4909 cpi->total_y += vp8_mse2psnr(y_samples, 255.0, ye);
4910 cpi->total_u += vp8_mse2psnr(uv_samples, 255.0, ue);
4911 cpi->total_v += vp8_mse2psnr(uv_samples, 255.0, ve);
4912 cpi->total_sq_error += sq_error;
4913 cpi->total += frame_psnr;
4915 double frame_psnr2, frame_ssim2 = 0;
4918 vp8_deblock(cm->frame_to_show, &cm->post_proc_buffer, cm->filter_level * 10 / 6, 1, 0, IF_RTCD(&cm->rtcd.postproc));
4919 vp8_clear_system_state();
4921 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
4922 pp->y_buffer, pp->y_stride, orig->y_width, orig->y_height,
4923 IF_RTCD(&cpi->rtcd.variance));
4925 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
4926 pp->u_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
4927 IF_RTCD(&cpi->rtcd.variance));
4929 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
4930 pp->v_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
4931 IF_RTCD(&cpi->rtcd.variance));
4933 sq_error = ye + ue + ve;
4935 frame_psnr2 = vp8_mse2psnr(t_samples, 255.0, sq_error);
4937 cpi->totalp_y += vp8_mse2psnr(y_samples, 255.0, ye);
4938 cpi->totalp_u += vp8_mse2psnr(uv_samples, 255.0, ue);
4939 cpi->totalp_v += vp8_mse2psnr(uv_samples, 255.0, ve);
4940 cpi->total_sq_error2 += sq_error;
4941 cpi->totalp += frame_psnr2;
4943 frame_ssim2 = vp8_calc_ssim(cpi->Source,
4944 &cm->post_proc_buffer, 1, &weight,
4945 IF_RTCD(&cpi->rtcd.variance));
4947 cpi->summed_quality += frame_ssim2 * weight;
4948 cpi->summed_weights += weight;
4953 if (cpi->b_calculate_ssimg)
4955 double y, u, v, frame_all;
4956 frame_all = vp8_calc_ssimg(cpi->Source, cm->frame_to_show,
4957 &y, &u, &v, IF_RTCD(&cpi->rtcd.variance));
4958 cpi->total_ssimg_y += y;
4959 cpi->total_ssimg_u += u;
4960 cpi->total_ssimg_v += v;
4961 cpi->total_ssimg_all += frame_all;
4969 if (cpi->common.frame_type != 0 && cpi->common.base_qindex == cpi->oxcf.worst_allowed_q)
4971 skiptruecount += cpi->skip_true_count;
4972 skipfalsecount += cpi->skip_false_count;
4980 FILE *f = fopen("skip.stt", "a");
4981 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);
4983 if (cpi->is_src_frame_alt_ref == 1)
4984 fprintf(f, "skipcount: %4d framesize: %d\n", cpi->skip_true_count , *size);
4993 #if CONFIG_RUNTIME_CPU_DETECT
4994 if (cm->rtcd.flags & HAS_NEON)
4997 vp8_pop_neon(store_reg);
5004 int vp8_get_preview_raw_frame(VP8_PTR comp, YV12_BUFFER_CONFIG *dest, vp8_ppflags_t *flags)
5006 VP8_COMP *cpi = (VP8_COMP *) comp;
5008 if (cpi->common.refresh_alt_ref_frame)
5014 ret = vp8_post_proc_frame(&cpi->common, dest, flags);
5017 if (cpi->common.frame_to_show)
5019 *dest = *cpi->common.frame_to_show;
5020 dest->y_width = cpi->common.Width;
5021 dest->y_height = cpi->common.Height;
5022 dest->uv_height = cpi->common.Height / 2;
5030 #endif //!CONFIG_POSTPROC
5031 vp8_clear_system_state();
5036 int vp8_set_roimap(VP8_PTR comp, unsigned char *map, unsigned int rows, unsigned int cols, int delta_q[4], int delta_lf[4], unsigned int threshold[4])
5038 VP8_COMP *cpi = (VP8_COMP *) comp;
5039 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
5041 if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
5046 disable_segmentation((VP8_PTR)cpi);
5050 // Set the segmentation Map
5051 set_segmentation_map((VP8_PTR)cpi, map);
5053 // Activate segmentation.
5054 enable_segmentation((VP8_PTR)cpi);
5056 // Set up the quant segment data
5057 feature_data[MB_LVL_ALT_Q][0] = delta_q[0];
5058 feature_data[MB_LVL_ALT_Q][1] = delta_q[1];
5059 feature_data[MB_LVL_ALT_Q][2] = delta_q[2];
5060 feature_data[MB_LVL_ALT_Q][3] = delta_q[3];
5062 // Set up the loop segment data s
5063 feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
5064 feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
5065 feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
5066 feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
5068 cpi->segment_encode_breakout[0] = threshold[0];
5069 cpi->segment_encode_breakout[1] = threshold[1];
5070 cpi->segment_encode_breakout[2] = threshold[2];
5071 cpi->segment_encode_breakout[3] = threshold[3];
5073 // Initialise the feature data structure
5074 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
5075 set_segment_data((VP8_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
5080 int vp8_set_active_map(VP8_PTR comp, unsigned char *map, unsigned int rows, unsigned int cols)
5082 VP8_COMP *cpi = (VP8_COMP *) comp;
5084 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols)
5088 vpx_memcpy(cpi->active_map, map, rows * cols);
5089 cpi->active_map_enabled = 1;
5092 cpi->active_map_enabled = 0;
5098 //cpi->active_map_enabled = 0;
5103 int vp8_set_internal_size(VP8_PTR comp, VPX_SCALING horiz_mode, VPX_SCALING vert_mode)
5105 VP8_COMP *cpi = (VP8_COMP *) comp;
5107 if (horiz_mode <= ONETWO)
5108 cpi->common.horiz_scale = horiz_mode;
5112 if (vert_mode <= ONETWO)
5113 cpi->common.vert_scale = vert_mode;
5122 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd)
5127 unsigned char *src = source->y_buffer;
5128 unsigned char *dst = dest->y_buffer;
5131 // Loop through the Y plane raw and reconstruction data summing (square differences)
5132 for (i = 0; i < source->y_height; i += 16)
5134 for (j = 0; j < source->y_width; j += 16)
5137 Total += VARIANCE_INVOKE(rtcd, mse16x16)(src + j, source->y_stride, dst + j, dest->y_stride, &sse);
5140 src += 16 * source->y_stride;
5141 dst += 16 * dest->y_stride;
5148 int vp8_get_quantizer(VP8_PTR c)
5150 VP8_COMP *cpi = (VP8_COMP *) c;
5151 return cpi->common.base_qindex;