Use consistent delimiters.
[libvpx.git] / vp8 / encoder / onyx_if.c
blob476bf30f8681738fd70079270d0c1b061e8aed8c
1 /*
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.
9 */
12 #include "vp8/common/onyxc_int.h"
13 #include "onyx_int.h"
14 #include "vp8/common/systemdependent.h"
15 #include "quantize.h"
16 #include "vp8/common/alloccommon.h"
17 #include "mcomp.h"
18 #include "firstpass.h"
19 #include "psnr.h"
20 #include "vpx_scale/vpxscale.h"
21 #include "vp8/common/extend.h"
22 #include "ratectrl.h"
23 #include "vp8/common/quant_common.h"
24 #include "segmentation.h"
25 #include "vp8/common/g_common.h"
26 #include "vpx_scale/yv12extend.h"
27 #include "vp8/common/postproc.h"
28 #include "vpx_mem/vpx_mem.h"
29 #include "vp8/common/swapyv12buffer.h"
30 #include "vp8/common/threading.h"
31 #include "vpx_ports/vpx_timer.h"
32 #include "temporal_filter.h"
33 #if ARCH_ARM
34 #include "vpx_ports/arm.h"
35 #endif
37 #include <math.h>
38 #include <stdio.h>
39 #include <limits.h>
41 #if CONFIG_RUNTIME_CPU_DETECT
42 #define IF_RTCD(x) (x)
43 #define RTCD(x) &cpi->common.rtcd.x
44 #else
45 #define IF_RTCD(x) NULL
46 #define RTCD(x) NULL
47 #endif
49 extern void vp8cx_init_mv_bits_sadcost();
50 extern void vp8cx_pick_filter_level_fast(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
51 extern void vp8cx_set_alt_lf_level(VP8_COMP *cpi, int filt_val);
52 extern void vp8cx_pick_filter_level(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
54 extern void vp8_init_loop_filter(VP8_COMMON *cm);
55 extern void vp8_loop_filter_frame(VP8_COMMON *cm, MACROBLOCKD *mbd, int filt_val);
56 extern void vp8_loop_filter_frame_yonly(VP8_COMMON *cm, MACROBLOCKD *mbd, int filt_val, int sharpness_lvl);
57 extern void vp8_dmachine_specific_config(VP8_COMP *cpi);
58 extern void vp8_cmachine_specific_config(VP8_COMP *cpi);
59 extern void vp8_calc_auto_iframe_target_size(VP8_COMP *cpi);
60 extern void vp8_deblock_frame(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *post, int filt_lvl, int low_var_thresh, int flag);
61 extern void print_parms(VP8_CONFIG *ocf, char *filenam);
62 extern unsigned int vp8_get_processor_freq();
63 extern void print_tree_update_probs();
64 extern void vp8cx_create_encoder_threads(VP8_COMP *cpi);
65 extern void vp8cx_remove_encoder_threads(VP8_COMP *cpi);
66 #if HAVE_ARMV7
67 extern void vp8_yv12_copy_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
68 extern void vp8_yv12_copy_src_frame_func_neon(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
69 #endif
71 int vp8_estimate_entropy_savings(VP8_COMP *cpi);
72 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd);
74 extern void vp8_temporal_filter_prepare_c(VP8_COMP *cpi);
76 static void set_default_lf_deltas(VP8_COMP *cpi);
78 extern const int vp8_gf_interval_table[101];
80 #if CONFIG_PSNR
81 #include "math.h"
83 extern double vp8_calc_ssim
85 YV12_BUFFER_CONFIG *source,
86 YV12_BUFFER_CONFIG *dest,
87 int lumamask,
88 double *weight,
89 const vp8_variance_rtcd_vtable_t *rtcd
93 extern double vp8_calc_ssimg
95 YV12_BUFFER_CONFIG *source,
96 YV12_BUFFER_CONFIG *dest,
97 double *ssim_y,
98 double *ssim_u,
99 double *ssim_v
103 #endif
106 #ifdef OUTPUT_YUV_SRC
107 FILE *yuv_file;
108 #endif
110 #if 0
111 FILE *framepsnr;
112 FILE *kf_list;
113 FILE *keyfile;
114 #endif
116 #if 0
117 extern int skip_true_count;
118 extern int skip_false_count;
119 #endif
122 #ifdef ENTROPY_STATS
123 extern int intra_mode_stats[10][10][10];
124 #endif
126 #ifdef SPEEDSTATS
127 unsigned int frames_at_speed[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
128 unsigned int tot_pm = 0;
129 unsigned int cnt_pm = 0;
130 unsigned int tot_ef = 0;
131 unsigned int cnt_ef = 0;
132 #endif
134 #ifdef MODE_STATS
135 extern unsigned __int64 Sectionbits[50];
136 extern int y_modes[5] ;
137 extern int uv_modes[4] ;
138 extern int b_modes[10] ;
140 extern int inter_y_modes[10] ;
141 extern int inter_uv_modes[4] ;
142 extern unsigned int inter_b_modes[15];
143 #endif
145 extern void (*vp8_short_fdct4x4)(short *input, short *output, int pitch);
146 extern void (*vp8_short_fdct8x4)(short *input, short *output, int pitch);
148 extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
150 extern const int qrounding_factors[129];
151 extern const int qzbin_factors[129];
152 extern void vp8cx_init_quantizer(VP8_COMP *cpi);
153 extern const int vp8cx_base_skip_false_prob[128];
155 // Tables relating active max Q to active min Q
156 static const int kf_low_motion_minq[QINDEX_RANGE] =
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,0,0,0,0,0,0,0,0,0,0,0,0,
161 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
162 3,3,3,3,3,3,4,4,4,5,5,5,5,5,6,6,
163 6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
164 11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
165 16,16,17,17,18,18,18,18,19,20,20,21,21,22,23,23
167 static const int kf_high_motion_minq[QINDEX_RANGE] =
169 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
170 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
171 1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,
172 3,3,3,3,4,4,4,4,5,5,5,5,5,5,6,6,
173 6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
174 11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
175 16,16,17,17,18,18,18,18,19,19,20,20,20,20,21,21,
176 21,21,22,22,23,23,24,25,25,26,26,27,28,28,29,30
178 static const int gf_low_motion_minq[QINDEX_RANGE] =
180 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
181 3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,
182 7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,
183 11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,
184 19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,
185 27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,
186 35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,
187 43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58
189 static const int gf_mid_motion_minq[QINDEX_RANGE] =
191 0,0,0,0,1,1,1,1,1,1,2,2,3,3,3,4,
192 4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
193 9,10,10,10,10,11,11,11,12,12,12,12,13,13,13,14,
194 14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,
195 22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,
196 30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,
197 38,39,39,40,40,41,41,42,42,43,43,44,45,46,47,48,
198 49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64
200 static const int gf_high_motion_minq[QINDEX_RANGE] =
202 0,0,0,0,1,1,1,1,1,2,2,2,3,3,3,4,
203 4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
204 9,10,10,10,11,11,12,12,13,13,14,14,15,15,16,16,
205 17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,
206 25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,
207 33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,
208 41,41,42,42,43,44,45,46,47,48,49,50,51,52,53,54,
209 55,56,57,58,59,60,62,64,66,68,70,72,74,76,78,80
211 static const int inter_minq[QINDEX_RANGE] =
213 0,0,1,1,2,3,3,4,4,5,6,6,7,8,8,9,
214 9,10,11,11,12,13,13,14,15,15,16,17,17,18,19,20,
215 20,21,22,22,23,24,24,25,26,27,27,28,29,30,30,31,
216 32,33,33,34,35,36,36,37,38,39,39,40,41,42,42,43,
217 44,45,46,46,47,48,49,50,50,51,52,53,54,55,55,56,
218 57,58,59,60,60,61,62,63,64,65,66,67,67,68,69,70,
219 71,72,73,74,75,75,76,77,78,79,80,81,82,83,84,85,
220 86,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
223 void vp8_initialize()
225 static int init_done = 0;
227 if (!init_done)
229 vp8_scale_machine_specific_config();
230 vp8_initialize_common();
231 //vp8_dmachine_specific_config();
232 vp8_tokenize_initialize();
234 vp8cx_init_mv_bits_sadcost();
235 init_done = 1;
238 #ifdef PACKET_TESTING
239 extern FILE *vpxlogc;
240 #endif
242 static void setup_features(VP8_COMP *cpi)
244 // Set up default state for MB feature flags
245 cpi->mb.e_mbd.segmentation_enabled = 0;
246 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
247 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
248 vpx_memset(cpi->mb.e_mbd.mb_segment_tree_probs, 255, sizeof(cpi->mb.e_mbd.mb_segment_tree_probs));
249 vpx_memset(cpi->mb.e_mbd.segment_feature_data, 0, sizeof(cpi->mb.e_mbd.segment_feature_data));
251 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 0;
252 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
253 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
254 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
255 vpx_memset(cpi->mb.e_mbd.last_ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
256 vpx_memset(cpi->mb.e_mbd.last_mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
258 set_default_lf_deltas(cpi);
263 static void dealloc_compressor_data(VP8_COMP *cpi)
265 vpx_free(cpi->tplist);
266 cpi->tplist = NULL;
268 // Delete last frame MV storage buffers
269 vpx_free(cpi->lfmv);
270 cpi->lfmv = 0;
272 vpx_free(cpi->lf_ref_frame_sign_bias);
273 cpi->lf_ref_frame_sign_bias = 0;
275 vpx_free(cpi->lf_ref_frame);
276 cpi->lf_ref_frame = 0;
278 // Delete sementation map
279 vpx_free(cpi->segmentation_map);
280 cpi->segmentation_map = 0;
282 vpx_free(cpi->active_map);
283 cpi->active_map = 0;
285 vp8_de_alloc_frame_buffers(&cpi->common);
287 vp8_yv12_de_alloc_frame_buffer(&cpi->last_frame_uf);
288 vp8_yv12_de_alloc_frame_buffer(&cpi->scaled_source);
289 #if VP8_TEMPORAL_ALT_REF
290 vp8_yv12_de_alloc_frame_buffer(&cpi->alt_ref_buffer.source_buffer);
291 #endif
293 int i;
295 for (i = 0; i < MAX_LAG_BUFFERS; i++)
296 vp8_yv12_de_alloc_frame_buffer(&cpi->src_buffer[i].source_buffer);
298 cpi->source_buffer_count = 0;
301 vpx_free(cpi->tok);
302 cpi->tok = 0;
304 // Structure used to monitor GF usage
305 vpx_free(cpi->gf_active_flags);
306 cpi->gf_active_flags = 0;
308 vpx_free(cpi->mb.pip);
309 cpi->mb.pip = 0;
311 #if !(CONFIG_REALTIME_ONLY)
312 vpx_free(cpi->total_stats);
313 cpi->total_stats = 0;
315 vpx_free(cpi->this_frame_stats);
316 cpi->this_frame_stats = 0;
317 #endif
320 static void enable_segmentation(VP8_PTR ptr)
322 VP8_COMP *cpi = (VP8_COMP *)(ptr);
324 // Set the appropriate feature bit
325 cpi->mb.e_mbd.segmentation_enabled = 1;
326 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
327 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
329 static void disable_segmentation(VP8_PTR ptr)
331 VP8_COMP *cpi = (VP8_COMP *)(ptr);
333 // Clear the appropriate feature bit
334 cpi->mb.e_mbd.segmentation_enabled = 0;
337 // Valid values for a segment are 0 to 3
338 // Segmentation map is arrange as [Rows][Columns]
339 static void set_segmentation_map(VP8_PTR ptr, unsigned char *segmentation_map)
341 VP8_COMP *cpi = (VP8_COMP *)(ptr);
343 // Copy in the new segmentation map
344 vpx_memcpy(cpi->segmentation_map, segmentation_map, (cpi->common.mb_rows * cpi->common.mb_cols));
346 // Signal that the map should be updated.
347 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
348 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
351 // The values given for each segment can be either deltas (from the default value chosen for the frame) or absolute values.
353 // Valid range for abs values is (0-127 for MB_LVL_ALT_Q) , (0-63 for SEGMENT_ALT_LF)
354 // Valid range for delta values are (+/-127 for MB_LVL_ALT_Q) , (+/-63 for SEGMENT_ALT_LF)
356 // abs_delta = SEGMENT_DELTADATA (deltas) abs_delta = SEGMENT_ABSDATA (use the absolute values given).
359 static void set_segment_data(VP8_PTR ptr, signed char *feature_data, unsigned char abs_delta)
361 VP8_COMP *cpi = (VP8_COMP *)(ptr);
363 cpi->mb.e_mbd.mb_segement_abs_delta = abs_delta;
364 vpx_memcpy(cpi->segment_feature_data, feature_data, sizeof(cpi->segment_feature_data));
368 static void segmentation_test_function(VP8_PTR ptr)
370 VP8_COMP *cpi = (VP8_COMP *)(ptr);
372 unsigned char *seg_map;
373 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
375 // Create a temporary map for segmentation data.
376 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
378 // MB loop to set local segmentation map
379 /*for ( i = 0; i < cpi->common.mb_rows; i++ )
381 for ( j = 0; j < cpi->common.mb_cols; j++ )
383 //seg_map[(i*cpi->common.mb_cols) + j] = (j % 2) + ((i%2)* 2);
384 //if ( j < cpi->common.mb_cols/2 )
386 // Segment 1 around the edge else 0
387 if ( (i == 0) || (j == 0) || (i == (cpi->common.mb_rows-1)) || (j == (cpi->common.mb_cols-1)) )
388 seg_map[(i*cpi->common.mb_cols) + j] = 1;
389 //else if ( (i < 2) || (j < 2) || (i > (cpi->common.mb_rows-3)) || (j > (cpi->common.mb_cols-3)) )
390 // seg_map[(i*cpi->common.mb_cols) + j] = 2;
391 //else if ( (i < 5) || (j < 5) || (i > (cpi->common.mb_rows-6)) || (j > (cpi->common.mb_cols-6)) )
392 // seg_map[(i*cpi->common.mb_cols) + j] = 3;
393 else
394 seg_map[(i*cpi->common.mb_cols) + j] = 0;
398 // Set the segmentation Map
399 set_segmentation_map(ptr, seg_map);
401 // Activate segmentation.
402 enable_segmentation(ptr);
404 // Set up the quant segment data
405 feature_data[MB_LVL_ALT_Q][0] = 0;
406 feature_data[MB_LVL_ALT_Q][1] = 4;
407 feature_data[MB_LVL_ALT_Q][2] = 0;
408 feature_data[MB_LVL_ALT_Q][3] = 0;
409 // Set up the loop segment data
410 feature_data[MB_LVL_ALT_LF][0] = 0;
411 feature_data[MB_LVL_ALT_LF][1] = 0;
412 feature_data[MB_LVL_ALT_LF][2] = 0;
413 feature_data[MB_LVL_ALT_LF][3] = 0;
415 // Initialise the feature data structure
416 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
417 set_segment_data(ptr, &feature_data[0][0], SEGMENT_DELTADATA);
419 // Delete sementation map
420 vpx_free(seg_map);
422 seg_map = 0;
426 // A simple function to cyclically refresh the background at a lower Q
427 static void cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment)
429 unsigned char *seg_map;
430 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
431 int i;
432 int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
433 int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
435 // Create a temporary map for segmentation data.
436 CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
438 cpi->cyclic_refresh_q = Q;
440 for (i = Q; i > 0; i--)
442 if (vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*(Q + 128)) / 64))
443 //if ( vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*((2*Q)+96))/64) )
445 break;
449 cpi->cyclic_refresh_q = i;
451 // Only update for inter frames
452 if (cpi->common.frame_type != KEY_FRAME)
454 // Cycle through the macro_block rows
455 // MB loop to set local segmentation map
456 for (i = cpi->cyclic_refresh_mode_index; i < mbs_in_frame; i++)
458 // If the MB is as a candidate for clean up then mark it for possible boost/refresh (segment 1)
459 // The segment id may get reset to 0 later if the MB gets coded anything other than last frame 0,0
460 // as only (last frame 0,0) MBs are eligable for refresh : that is to say Mbs likely to be background blocks.
461 if (cpi->cyclic_refresh_map[i] == 0)
463 seg_map[i] = 1;
465 else
467 seg_map[i] = 0;
469 // Skip blocks that have been refreshed recently anyway.
470 if (cpi->cyclic_refresh_map[i] < 0)
471 //cpi->cyclic_refresh_map[i] = cpi->cyclic_refresh_map[i] / 16;
472 cpi->cyclic_refresh_map[i]++;
476 if (block_count > 0)
477 block_count--;
478 else
479 break;
483 // If we have gone through the frame reset to the start
484 cpi->cyclic_refresh_mode_index = i;
486 if (cpi->cyclic_refresh_mode_index >= mbs_in_frame)
487 cpi->cyclic_refresh_mode_index = 0;
490 // Set the segmentation Map
491 set_segmentation_map((VP8_PTR)cpi, seg_map);
493 // Activate segmentation.
494 enable_segmentation((VP8_PTR)cpi);
496 // Set up the quant segment data
497 feature_data[MB_LVL_ALT_Q][0] = 0;
498 feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
499 feature_data[MB_LVL_ALT_Q][2] = 0;
500 feature_data[MB_LVL_ALT_Q][3] = 0;
502 // Set up the loop segment data
503 feature_data[MB_LVL_ALT_LF][0] = 0;
504 feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
505 feature_data[MB_LVL_ALT_LF][2] = 0;
506 feature_data[MB_LVL_ALT_LF][3] = 0;
508 // Initialise the feature data structure
509 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
510 set_segment_data((VP8_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
512 // Delete sementation map
513 vpx_free(seg_map);
515 seg_map = 0;
519 static void set_default_lf_deltas(VP8_COMP *cpi)
521 cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 1;
522 cpi->mb.e_mbd.mode_ref_lf_delta_update = 1;
524 vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
525 vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
527 // Test of ref frame deltas
528 cpi->mb.e_mbd.ref_lf_deltas[INTRA_FRAME] = 2;
529 cpi->mb.e_mbd.ref_lf_deltas[LAST_FRAME] = 0;
530 cpi->mb.e_mbd.ref_lf_deltas[GOLDEN_FRAME] = -2;
531 cpi->mb.e_mbd.ref_lf_deltas[ALTREF_FRAME] = -2;
533 cpi->mb.e_mbd.mode_lf_deltas[0] = 4; // BPRED
534 cpi->mb.e_mbd.mode_lf_deltas[1] = -2; // Zero
535 cpi->mb.e_mbd.mode_lf_deltas[2] = 2; // New mv
536 cpi->mb.e_mbd.mode_lf_deltas[3] = 4; // Split mv
539 void vp8_set_speed_features(VP8_COMP *cpi)
541 SPEED_FEATURES *sf = &cpi->sf;
542 int Mode = cpi->compressor_speed;
543 int Speed = cpi->Speed;
544 int i;
545 VP8_COMMON *cm = &cpi->common;
546 int last_improved_quant = sf->improved_quant;
548 // Initialise default mode frequency sampling variables
549 for (i = 0; i < MAX_MODES; i ++)
551 cpi->mode_check_freq[i] = 0;
552 cpi->mode_test_hit_counts[i] = 0;
553 cpi->mode_chosen_counts[i] = 0;
556 cpi->mbs_tested_so_far = 0;
558 // best quality defaults
559 sf->RD = 1;
560 sf->search_method = NSTEP;
561 sf->improved_quant = 1;
562 sf->improved_dct = 1;
563 sf->auto_filter = 1;
564 sf->recode_loop = 1;
565 sf->quarter_pixel_search = 1;
566 sf->half_pixel_search = 1;
567 sf->full_freq[0] = 7;
568 sf->full_freq[1] = 7;
569 sf->min_fs_radius = 8;
570 sf->max_fs_radius = 32;
571 sf->iterative_sub_pixel = 1;
572 sf->optimize_coefficients = 1;
573 sf->use_fastquant_for_pick = 0;
574 sf->no_skip_block4x4_search = 1;
576 sf->first_step = 0;
577 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
578 sf->improved_mv_pred = 1;
580 cpi->do_full[0] = 0;
581 cpi->do_full[1] = 0;
583 // default thresholds to 0
584 for (i = 0; i < MAX_MODES; i++)
585 sf->thresh_mult[i] = 0;
587 switch (Mode)
589 #if !(CONFIG_REALTIME_ONLY)
590 case 0: // best quality mode
591 sf->thresh_mult[THR_ZEROMV ] = 0;
592 sf->thresh_mult[THR_ZEROG ] = 0;
593 sf->thresh_mult[THR_ZEROA ] = 0;
594 sf->thresh_mult[THR_NEARESTMV] = 0;
595 sf->thresh_mult[THR_NEARESTG ] = 0;
596 sf->thresh_mult[THR_NEARESTA ] = 0;
597 sf->thresh_mult[THR_NEARMV ] = 0;
598 sf->thresh_mult[THR_NEARG ] = 0;
599 sf->thresh_mult[THR_NEARA ] = 0;
601 sf->thresh_mult[THR_DC ] = 0;
603 sf->thresh_mult[THR_V_PRED ] = 1000;
604 sf->thresh_mult[THR_H_PRED ] = 1000;
605 sf->thresh_mult[THR_B_PRED ] = 2000;
606 sf->thresh_mult[THR_TM ] = 1000;
608 sf->thresh_mult[THR_NEWMV ] = 1000;
609 sf->thresh_mult[THR_NEWG ] = 1000;
610 sf->thresh_mult[THR_NEWA ] = 1000;
612 sf->thresh_mult[THR_SPLITMV ] = 2500;
613 sf->thresh_mult[THR_SPLITG ] = 5000;
614 sf->thresh_mult[THR_SPLITA ] = 5000;
616 sf->full_freq[0] = 7;
617 sf->full_freq[1] = 15;
619 sf->first_step = 0;
620 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
621 break;
622 case 1:
623 case 3:
624 sf->thresh_mult[THR_NEARESTMV] = 0;
625 sf->thresh_mult[THR_ZEROMV ] = 0;
626 sf->thresh_mult[THR_DC ] = 0;
627 sf->thresh_mult[THR_NEARMV ] = 0;
628 sf->thresh_mult[THR_V_PRED ] = 1000;
629 sf->thresh_mult[THR_H_PRED ] = 1000;
630 sf->thresh_mult[THR_B_PRED ] = 2500;
631 sf->thresh_mult[THR_TM ] = 1000;
633 sf->thresh_mult[THR_NEARESTG ] = 1000;
634 sf->thresh_mult[THR_NEARESTA ] = 1000;
636 sf->thresh_mult[THR_ZEROG ] = 1000;
637 sf->thresh_mult[THR_ZEROA ] = 1000;
638 sf->thresh_mult[THR_NEARG ] = 1000;
639 sf->thresh_mult[THR_NEARA ] = 1000;
641 #if 1
642 sf->thresh_mult[THR_ZEROMV ] = 0;
643 sf->thresh_mult[THR_ZEROG ] = 0;
644 sf->thresh_mult[THR_ZEROA ] = 0;
645 sf->thresh_mult[THR_NEARESTMV] = 0;
646 sf->thresh_mult[THR_NEARESTG ] = 0;
647 sf->thresh_mult[THR_NEARESTA ] = 0;
648 sf->thresh_mult[THR_NEARMV ] = 0;
649 sf->thresh_mult[THR_NEARG ] = 0;
650 sf->thresh_mult[THR_NEARA ] = 0;
652 // sf->thresh_mult[THR_DC ] = 0;
654 // sf->thresh_mult[THR_V_PRED ] = 1000;
655 // sf->thresh_mult[THR_H_PRED ] = 1000;
656 // sf->thresh_mult[THR_B_PRED ] = 2000;
657 // sf->thresh_mult[THR_TM ] = 1000;
659 sf->thresh_mult[THR_NEWMV ] = 1000;
660 sf->thresh_mult[THR_NEWG ] = 1000;
661 sf->thresh_mult[THR_NEWA ] = 1000;
663 sf->thresh_mult[THR_SPLITMV ] = 1700;
664 sf->thresh_mult[THR_SPLITG ] = 4500;
665 sf->thresh_mult[THR_SPLITA ] = 4500;
666 #else
667 sf->thresh_mult[THR_NEWMV ] = 1500;
668 sf->thresh_mult[THR_NEWG ] = 1500;
669 sf->thresh_mult[THR_NEWA ] = 1500;
671 sf->thresh_mult[THR_SPLITMV ] = 5000;
672 sf->thresh_mult[THR_SPLITG ] = 10000;
673 sf->thresh_mult[THR_SPLITA ] = 10000;
674 #endif
675 sf->full_freq[0] = 15;
676 sf->full_freq[1] = 31;
678 if (Speed > 0)
680 /* Disable coefficient optimization above speed 0 */
681 sf->optimize_coefficients = 0;
682 sf->use_fastquant_for_pick = 1;
683 sf->no_skip_block4x4_search = 0;
685 sf->first_step = 1;
687 cpi->mode_check_freq[THR_SPLITG] = 2;
688 cpi->mode_check_freq[THR_SPLITA] = 2;
689 cpi->mode_check_freq[THR_SPLITMV] = 0;
692 if (Speed > 1)
694 cpi->mode_check_freq[THR_SPLITG] = 4;
695 cpi->mode_check_freq[THR_SPLITA] = 4;
696 cpi->mode_check_freq[THR_SPLITMV] = 2;
698 sf->thresh_mult[THR_TM ] = 1500;
699 sf->thresh_mult[THR_V_PRED ] = 1500;
700 sf->thresh_mult[THR_H_PRED ] = 1500;
701 sf->thresh_mult[THR_B_PRED ] = 5000;
703 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
705 sf->thresh_mult[THR_NEWMV ] = 2000;
706 sf->thresh_mult[THR_SPLITMV ] = 10000;
709 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
711 sf->thresh_mult[THR_NEARESTG ] = 1500;
712 sf->thresh_mult[THR_ZEROG ] = 1500;
713 sf->thresh_mult[THR_NEARG ] = 1500;
714 sf->thresh_mult[THR_NEWG ] = 2000;
715 sf->thresh_mult[THR_SPLITG ] = 20000;
718 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
720 sf->thresh_mult[THR_NEARESTA ] = 1500;
721 sf->thresh_mult[THR_ZEROA ] = 1500;
722 sf->thresh_mult[THR_NEARA ] = 1500;
723 sf->thresh_mult[THR_NEWA ] = 2000;
724 sf->thresh_mult[THR_SPLITA ] = 20000;
728 if (Speed > 2)
730 cpi->mode_check_freq[THR_SPLITG] = 15;
731 cpi->mode_check_freq[THR_SPLITA] = 15;
732 cpi->mode_check_freq[THR_SPLITMV] = 7;
734 sf->thresh_mult[THR_TM ] = 2000;
735 sf->thresh_mult[THR_V_PRED ] = 2000;
736 sf->thresh_mult[THR_H_PRED ] = 2000;
737 sf->thresh_mult[THR_B_PRED ] = 7500;
739 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
741 sf->thresh_mult[THR_NEWMV ] = 2000;
742 sf->thresh_mult[THR_SPLITMV ] = 25000;
745 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
747 sf->thresh_mult[THR_NEARESTG ] = 2000;
748 sf->thresh_mult[THR_ZEROG ] = 2000;
749 sf->thresh_mult[THR_NEARG ] = 2000;
750 sf->thresh_mult[THR_NEWG ] = 2500;
751 sf->thresh_mult[THR_SPLITG ] = 50000;
754 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
756 sf->thresh_mult[THR_NEARESTA ] = 2000;
757 sf->thresh_mult[THR_ZEROA ] = 2000;
758 sf->thresh_mult[THR_NEARA ] = 2000;
759 sf->thresh_mult[THR_NEWA ] = 2500;
760 sf->thresh_mult[THR_SPLITA ] = 50000;
763 sf->improved_quant = 0;
764 sf->improved_dct = 0;
766 // Only do recode loop on key frames, golden frames and
767 // alt ref frames
768 sf->recode_loop = 2;
770 sf->full_freq[0] = 31;
771 sf->full_freq[1] = 63;
774 if (Speed > 3)
776 sf->thresh_mult[THR_SPLITA ] = INT_MAX;
777 sf->thresh_mult[THR_SPLITG ] = INT_MAX;
778 sf->thresh_mult[THR_SPLITMV ] = INT_MAX;
780 cpi->mode_check_freq[THR_V_PRED] = 0;
781 cpi->mode_check_freq[THR_H_PRED] = 0;
782 cpi->mode_check_freq[THR_B_PRED] = 0;
783 cpi->mode_check_freq[THR_NEARG] = 0;
784 cpi->mode_check_freq[THR_NEWG] = 0;
785 cpi->mode_check_freq[THR_NEARA] = 0;
786 cpi->mode_check_freq[THR_NEWA] = 0;
788 sf->auto_filter = 1;
789 sf->recode_loop = 0; // recode loop off
790 sf->RD = 0; // Turn rd off
792 sf->full_freq[0] = 63;
793 sf->full_freq[1] = 127;
796 if (Speed > 4)
798 sf->auto_filter = 0; // Faster selection of loop filter
799 sf->full_freq[0] = INT_MAX;
800 sf->full_freq[1] = INT_MAX;
802 cpi->mode_check_freq[THR_V_PRED] = 2;
803 cpi->mode_check_freq[THR_H_PRED] = 2;
804 cpi->mode_check_freq[THR_B_PRED] = 2;
806 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
808 cpi->mode_check_freq[THR_NEARG] = 2;
809 cpi->mode_check_freq[THR_NEWG] = 4;
812 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
814 cpi->mode_check_freq[THR_NEARA] = 2;
815 cpi->mode_check_freq[THR_NEWA] = 4;
818 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
820 sf->thresh_mult[THR_NEARESTG ] = 2000;
821 sf->thresh_mult[THR_ZEROG ] = 2000;
822 sf->thresh_mult[THR_NEARG ] = 2000;
823 sf->thresh_mult[THR_NEWG ] = 4000;
826 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
828 sf->thresh_mult[THR_NEARESTA ] = 2000;
829 sf->thresh_mult[THR_ZEROA ] = 2000;
830 sf->thresh_mult[THR_NEARA ] = 2000;
831 sf->thresh_mult[THR_NEWA ] = 4000;
835 break;
836 #endif
837 case 2:
838 sf->optimize_coefficients = 0;
839 sf->recode_loop = 0;
840 sf->auto_filter = 1;
841 sf->iterative_sub_pixel = 1;
842 sf->thresh_mult[THR_NEARESTMV] = 0;
843 sf->thresh_mult[THR_ZEROMV ] = 0;
844 sf->thresh_mult[THR_DC ] = 0;
845 sf->thresh_mult[THR_TM ] = 0;
846 sf->thresh_mult[THR_NEARMV ] = 0;
847 sf->thresh_mult[THR_V_PRED ] = 1000;
848 sf->thresh_mult[THR_H_PRED ] = 1000;
849 sf->thresh_mult[THR_B_PRED ] = 2500;
850 sf->thresh_mult[THR_NEARESTG ] = 1000;
851 sf->thresh_mult[THR_ZEROG ] = 1000;
852 sf->thresh_mult[THR_NEARG ] = 1000;
853 sf->thresh_mult[THR_NEARESTA ] = 1000;
854 sf->thresh_mult[THR_ZEROA ] = 1000;
855 sf->thresh_mult[THR_NEARA ] = 1000;
856 sf->thresh_mult[THR_NEWMV ] = 2000;
857 sf->thresh_mult[THR_NEWG ] = 2000;
858 sf->thresh_mult[THR_NEWA ] = 2000;
859 sf->thresh_mult[THR_SPLITMV ] = 5000;
860 sf->thresh_mult[THR_SPLITG ] = 10000;
861 sf->thresh_mult[THR_SPLITA ] = 10000;
862 sf->full_freq[0] = 15;
863 sf->full_freq[1] = 31;
864 sf->search_method = NSTEP;
866 if (Speed > 0)
868 cpi->mode_check_freq[THR_SPLITG] = 4;
869 cpi->mode_check_freq[THR_SPLITA] = 4;
870 cpi->mode_check_freq[THR_SPLITMV] = 2;
872 sf->thresh_mult[THR_DC ] = 0;
873 sf->thresh_mult[THR_TM ] = 1000;
874 sf->thresh_mult[THR_V_PRED ] = 2000;
875 sf->thresh_mult[THR_H_PRED ] = 2000;
876 sf->thresh_mult[THR_B_PRED ] = 5000;
878 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
880 sf->thresh_mult[THR_NEARESTMV] = 0;
881 sf->thresh_mult[THR_ZEROMV ] = 0;
882 sf->thresh_mult[THR_NEARMV ] = 0;
883 sf->thresh_mult[THR_NEWMV ] = 2000;
884 sf->thresh_mult[THR_SPLITMV ] = 10000;
887 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
889 sf->thresh_mult[THR_NEARESTG ] = 1000;
890 sf->thresh_mult[THR_ZEROG ] = 1000;
891 sf->thresh_mult[THR_NEARG ] = 1000;
892 sf->thresh_mult[THR_NEWG ] = 2000;
893 sf->thresh_mult[THR_SPLITG ] = 20000;
896 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
898 sf->thresh_mult[THR_NEARESTA ] = 1000;
899 sf->thresh_mult[THR_ZEROA ] = 1000;
900 sf->thresh_mult[THR_NEARA ] = 1000;
901 sf->thresh_mult[THR_NEWA ] = 2000;
902 sf->thresh_mult[THR_SPLITA ] = 20000;
905 sf->improved_quant = 0;
906 sf->improved_dct = 0;
909 if (Speed > 1)
911 cpi->mode_check_freq[THR_SPLITMV] = 7;
912 cpi->mode_check_freq[THR_SPLITG] = 15;
913 cpi->mode_check_freq[THR_SPLITA] = 15;
915 sf->thresh_mult[THR_TM ] = 2000;
916 sf->thresh_mult[THR_V_PRED ] = 2000;
917 sf->thresh_mult[THR_H_PRED ] = 2000;
918 sf->thresh_mult[THR_B_PRED ] = 5000;
920 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
922 sf->thresh_mult[THR_NEWMV ] = 2000;
923 sf->thresh_mult[THR_SPLITMV ] = 25000;
926 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
928 sf->thresh_mult[THR_NEARESTG ] = 2000;
929 sf->thresh_mult[THR_ZEROG ] = 2000;
930 sf->thresh_mult[THR_NEARG ] = 2000;
931 sf->thresh_mult[THR_NEWG ] = 2500;
932 sf->thresh_mult[THR_SPLITG ] = 50000;
935 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
937 sf->thresh_mult[THR_NEARESTA ] = 2000;
938 sf->thresh_mult[THR_ZEROA ] = 2000;
939 sf->thresh_mult[THR_NEARA ] = 2000;
940 sf->thresh_mult[THR_NEWA ] = 2500;
941 sf->thresh_mult[THR_SPLITA ] = 50000;
944 sf->full_freq[0] = 31;
945 sf->full_freq[1] = 63;
948 if (Speed > 2)
950 sf->auto_filter = 0; // Faster selection of loop filter
952 cpi->mode_check_freq[THR_V_PRED] = 2;
953 cpi->mode_check_freq[THR_H_PRED] = 2;
954 cpi->mode_check_freq[THR_B_PRED] = 2;
956 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
958 cpi->mode_check_freq[THR_NEARG] = 2;
959 cpi->mode_check_freq[THR_NEWG] = 4;
962 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
964 cpi->mode_check_freq[THR_NEARA] = 2;
965 cpi->mode_check_freq[THR_NEWA] = 4;
968 sf->thresh_mult[THR_SPLITMV ] = INT_MAX;
969 sf->thresh_mult[THR_SPLITG ] = INT_MAX;
970 sf->thresh_mult[THR_SPLITA ] = INT_MAX;
972 sf->full_freq[0] = 63;
973 sf->full_freq[1] = 127;
976 if (Speed > 3)
978 sf->RD = 0;
979 sf->full_freq[0] = INT_MAX;
980 sf->full_freq[1] = INT_MAX;
982 sf->auto_filter = 1;
985 if (Speed > 4)
987 sf->auto_filter = 0; // Faster selection of loop filter
989 #if CONFIG_REALTIME_ONLY
990 sf->search_method = HEX;
991 #else
992 sf->search_method = DIAMOND;
993 #endif
994 sf->iterative_sub_pixel = 0;
996 cpi->mode_check_freq[THR_V_PRED] = 4;
997 cpi->mode_check_freq[THR_H_PRED] = 4;
998 cpi->mode_check_freq[THR_B_PRED] = 4;
1000 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
1002 cpi->mode_check_freq[THR_NEARG] = 2;
1003 cpi->mode_check_freq[THR_NEWG] = 4;
1006 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
1008 cpi->mode_check_freq[THR_NEARA] = 2;
1009 cpi->mode_check_freq[THR_NEWA] = 4;
1012 sf->thresh_mult[THR_TM ] = 2000;
1013 sf->thresh_mult[THR_B_PRED ] = 5000;
1015 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
1017 sf->thresh_mult[THR_NEARESTG ] = 2000;
1018 sf->thresh_mult[THR_ZEROG ] = 2000;
1019 sf->thresh_mult[THR_NEARG ] = 2000;
1020 sf->thresh_mult[THR_NEWG ] = 4000;
1023 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
1025 sf->thresh_mult[THR_NEARESTA ] = 2000;
1026 sf->thresh_mult[THR_ZEROA ] = 2000;
1027 sf->thresh_mult[THR_NEARA ] = 2000;
1028 sf->thresh_mult[THR_NEWA ] = 4000;
1032 if (Speed > 5)
1034 // Disable split MB intra prediction mode
1035 sf->thresh_mult[THR_B_PRED] = INT_MAX;
1038 if (Speed > 6)
1040 unsigned int i, sum = 0;
1041 unsigned int total_mbs = cm->MBs;
1042 int thresh;
1043 int total_skip;
1045 int min = 2000;
1047 if (cpi->oxcf.encode_breakout > 2000)
1048 min = cpi->oxcf.encode_breakout;
1050 min >>= 7;
1052 for (i = 0; i < min; i++)
1054 sum += cpi->error_bins[i];
1057 total_skip = sum;
1058 sum = 0;
1060 // i starts from 2 to make sure thresh started from 2048
1061 for (; i < 1024; i++)
1063 sum += cpi->error_bins[i];
1065 if (10 * sum >= (unsigned int)(cpi->Speed - 6)*(total_mbs - total_skip))
1066 break;
1069 i--;
1070 thresh = (i << 7);
1072 if (thresh < 2000)
1073 thresh = 2000;
1075 if (cpi->ref_frame_flags & VP8_LAST_FLAG)
1077 sf->thresh_mult[THR_NEWMV] = thresh;
1078 sf->thresh_mult[THR_NEARESTMV ] = thresh >> 1;
1079 sf->thresh_mult[THR_NEARMV ] = thresh >> 1;
1082 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
1084 sf->thresh_mult[THR_NEWG] = thresh << 1;
1085 sf->thresh_mult[THR_NEARESTG ] = thresh;
1086 sf->thresh_mult[THR_NEARG ] = thresh;
1089 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
1091 sf->thresh_mult[THR_NEWA] = thresh << 1;
1092 sf->thresh_mult[THR_NEARESTA ] = thresh;
1093 sf->thresh_mult[THR_NEARA ] = thresh;
1096 // Disable other intra prediction modes
1097 sf->thresh_mult[THR_TM] = INT_MAX;
1098 sf->thresh_mult[THR_V_PRED] = INT_MAX;
1099 sf->thresh_mult[THR_H_PRED] = INT_MAX;
1101 sf->improved_mv_pred = 0;
1104 if (Speed > 8)
1106 sf->quarter_pixel_search = 0;
1109 if (Speed > 9)
1111 int Tmp = cpi->Speed - 8;
1113 if (Tmp > 4)
1114 Tmp = 4;
1116 if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
1118 cpi->mode_check_freq[THR_ZEROG] = 1 << (Tmp - 1);
1119 cpi->mode_check_freq[THR_NEARESTG] = 1 << (Tmp - 1);
1120 cpi->mode_check_freq[THR_NEARG] = 1 << Tmp;
1121 cpi->mode_check_freq[THR_NEWG] = 1 << (Tmp + 1);
1124 if (cpi->ref_frame_flags & VP8_ALT_FLAG)
1126 cpi->mode_check_freq[THR_ZEROA] = 1 << (Tmp - 1);
1127 cpi->mode_check_freq[THR_NEARESTA] = 1 << (Tmp - 1);
1128 cpi->mode_check_freq[THR_NEARA] = 1 << Tmp;
1129 cpi->mode_check_freq[THR_NEWA] = 1 << (Tmp + 1);
1132 cpi->mode_check_freq[THR_NEWMV] = 1 << (Tmp - 1);
1135 cm->filter_type = NORMAL_LOOPFILTER;
1137 if (Speed >= 14)
1138 cm->filter_type = SIMPLE_LOOPFILTER;
1140 if (Speed >= 15)
1142 sf->half_pixel_search = 0; // This has a big hit on quality. Last resort
1145 vpx_memset(cpi->error_bins, 0, sizeof(cpi->error_bins));
1147 }; /* switch */
1149 /* disable frame modes if flags not set */
1150 if (!(cpi->ref_frame_flags & VP8_LAST_FLAG))
1152 sf->thresh_mult[THR_NEWMV ] = INT_MAX;
1153 sf->thresh_mult[THR_NEARESTMV] = INT_MAX;
1154 sf->thresh_mult[THR_ZEROMV ] = INT_MAX;
1155 sf->thresh_mult[THR_NEARMV ] = INT_MAX;
1156 sf->thresh_mult[THR_SPLITMV ] = INT_MAX;
1159 if (!(cpi->ref_frame_flags & VP8_GOLD_FLAG))
1161 sf->thresh_mult[THR_NEARESTG ] = INT_MAX;
1162 sf->thresh_mult[THR_ZEROG ] = INT_MAX;
1163 sf->thresh_mult[THR_NEARG ] = INT_MAX;
1164 sf->thresh_mult[THR_NEWG ] = INT_MAX;
1165 sf->thresh_mult[THR_SPLITG ] = INT_MAX;
1168 if (!(cpi->ref_frame_flags & VP8_ALT_FLAG))
1170 sf->thresh_mult[THR_NEARESTA ] = INT_MAX;
1171 sf->thresh_mult[THR_ZEROA ] = INT_MAX;
1172 sf->thresh_mult[THR_NEARA ] = INT_MAX;
1173 sf->thresh_mult[THR_NEWA ] = INT_MAX;
1174 sf->thresh_mult[THR_SPLITA ] = INT_MAX;
1178 // Slow quant, dct and trellis not worthwhile for first pass
1179 // so make sure they are always turned off.
1180 if ( cpi->pass == 1 )
1182 sf->improved_quant = 0;
1183 sf->optimize_coefficients = 0;
1184 sf->improved_dct = 0;
1187 if (cpi->sf.search_method == NSTEP)
1189 vp8_init3smotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
1191 else if (cpi->sf.search_method == DIAMOND)
1193 vp8_init_dsmotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
1196 if (cpi->sf.improved_dct)
1198 cpi->mb.vp8_short_fdct8x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short8x4);
1199 cpi->mb.vp8_short_fdct4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short4x4);
1201 else
1203 cpi->mb.vp8_short_fdct8x4 = FDCT_INVOKE(&cpi->rtcd.fdct, fast8x4);
1204 cpi->mb.vp8_short_fdct4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, fast4x4);
1207 cpi->mb.short_walsh4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, walsh_short4x4);
1209 if (cpi->sf.improved_quant)
1211 cpi->mb.quantize_b = QUANTIZE_INVOKE(&cpi->rtcd.quantize, quantb);
1213 else
1215 cpi->mb.quantize_b = QUANTIZE_INVOKE(&cpi->rtcd.quantize, fastquantb);
1217 if (cpi->sf.improved_quant != last_improved_quant)
1218 vp8cx_init_quantizer(cpi);
1220 #if CONFIG_RUNTIME_CPU_DETECT
1221 cpi->mb.e_mbd.rtcd = &cpi->common.rtcd;
1222 #endif
1224 if (cpi->sf.iterative_sub_pixel == 1)
1226 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step_iteratively;
1228 else if (cpi->sf.quarter_pixel_search)
1230 cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step;
1232 else if (cpi->sf.half_pixel_search)
1234 cpi->find_fractional_mv_step = vp8_find_best_half_pixel_step;
1236 else
1238 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1241 if (cpi->sf.optimize_coefficients == 1)
1242 cpi->mb.optimize = 1 + cpi->is_next_src_alt_ref;
1243 else
1244 cpi->mb.optimize = 0;
1246 if (cpi->common.full_pixel)
1247 cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1249 #ifdef SPEEDSTATS
1250 frames_at_speed[cpi->Speed]++;
1251 #endif
1253 static void alloc_raw_frame_buffers(VP8_COMP *cpi)
1255 int i, buffers;
1256 /* allocate source_buffer to be multiples of 16 */
1257 int width = (cpi->oxcf.Width + 15) & ~15;
1259 buffers = cpi->oxcf.lag_in_frames;
1261 if (buffers > MAX_LAG_BUFFERS)
1262 buffers = MAX_LAG_BUFFERS;
1264 if (buffers < 1)
1265 buffers = 1;
1267 for (i = 0; i < buffers; i++)
1268 if (vp8_yv12_alloc_frame_buffer(&cpi->src_buffer[i].source_buffer,
1269 width, cpi->oxcf.Height,
1270 16))
1271 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1272 "Failed to allocate lag buffer");
1274 #if VP8_TEMPORAL_ALT_REF
1276 if (vp8_yv12_alloc_frame_buffer(&cpi->alt_ref_buffer.source_buffer,
1277 width, cpi->oxcf.Height, 16))
1278 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1279 "Failed to allocate altref buffer");
1281 #endif
1283 cpi->source_buffer_count = 0;
1286 static int vp8_alloc_partition_data(VP8_COMP *cpi)
1288 vpx_free(cpi->mb.pip);
1290 cpi->mb.pip = vpx_calloc((cpi->common.mb_cols + 1) *
1291 (cpi->common.mb_rows + 1),
1292 sizeof(PARTITION_INFO));
1293 if(!cpi->mb.pip)
1294 return 1;
1296 cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
1298 return 0;
1301 void vp8_alloc_compressor_data(VP8_COMP *cpi)
1303 VP8_COMMON *cm = & cpi->common;
1305 int width = cm->Width;
1306 int height = cm->Height;
1308 if (vp8_alloc_frame_buffers(cm, width, height))
1309 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1310 "Failed to allocate frame buffers");
1312 if (vp8_alloc_partition_data(cpi))
1313 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1314 "Failed to allocate partition data");
1317 if ((width & 0xf) != 0)
1318 width += 16 - (width & 0xf);
1320 if ((height & 0xf) != 0)
1321 height += 16 - (height & 0xf);
1324 if (vp8_yv12_alloc_frame_buffer(&cpi->last_frame_uf,
1325 width, height, VP8BORDERINPIXELS))
1326 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1327 "Failed to allocate last frame buffer");
1329 if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source, width, height, 16))
1330 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1331 "Failed to allocate scaled source buffer");
1334 vpx_free(cpi->tok);
1337 unsigned int tokens = cm->mb_rows * cm->mb_cols * 24 * 16;
1339 CHECK_MEM_ERROR(cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
1342 // Data used for real time vc mode to see if gf needs refreshing
1343 cpi->inter_zz_count = 0;
1344 cpi->gf_bad_count = 0;
1345 cpi->gf_update_recommended = 0;
1348 // Structures used to minitor GF usage
1349 vpx_free(cpi->gf_active_flags);
1351 CHECK_MEM_ERROR(cpi->gf_active_flags, vpx_calloc(1, cm->mb_rows * cm->mb_cols));
1353 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
1355 #if !(CONFIG_REALTIME_ONLY)
1356 vpx_free(cpi->total_stats);
1358 cpi->total_stats = vpx_calloc(1, sizeof(FIRSTPASS_STATS));
1360 vpx_free(cpi->this_frame_stats);
1362 cpi->this_frame_stats = vpx_calloc(1, sizeof(FIRSTPASS_STATS));
1364 if(!cpi->total_stats || !cpi->this_frame_stats)
1365 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1366 "Failed to allocate firstpass stats");
1367 #endif
1369 #if CONFIG_MULTITHREAD
1370 if (width < 640)
1371 cpi->mt_sync_range = 1;
1372 else if (width <= 1280)
1373 cpi->mt_sync_range = 4;
1374 else if (width <= 2560)
1375 cpi->mt_sync_range = 8;
1376 else
1377 cpi->mt_sync_range = 16;
1378 #endif
1380 vpx_free(cpi->tplist);
1382 CHECK_MEM_ERROR(cpi->tplist, vpx_malloc(sizeof(TOKENLIST) * cpi->common.mb_rows));
1386 // Quant MOD
1387 static const int q_trans[] =
1389 0, 1, 2, 3, 4, 5, 7, 8,
1390 9, 10, 12, 13, 15, 17, 18, 19,
1391 20, 21, 23, 24, 25, 26, 27, 28,
1392 29, 30, 31, 33, 35, 37, 39, 41,
1393 43, 45, 47, 49, 51, 53, 55, 57,
1394 59, 61, 64, 67, 70, 73, 76, 79,
1395 82, 85, 88, 91, 94, 97, 100, 103,
1396 106, 109, 112, 115, 118, 121, 124, 127,
1399 int vp8_reverse_trans(int x)
1401 int i;
1403 for (i = 0; i < 64; i++)
1404 if (q_trans[i] >= x)
1405 return i;
1407 return 63;
1409 void vp8_new_frame_rate(VP8_COMP *cpi, double framerate)
1411 if(framerate < .1)
1412 framerate = 30;
1414 cpi->oxcf.frame_rate = framerate;
1415 cpi->output_frame_rate = cpi->oxcf.frame_rate;
1416 cpi->per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth / cpi->output_frame_rate);
1417 cpi->av_per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth / cpi->output_frame_rate);
1418 cpi->min_frame_bandwidth = (int)(cpi->av_per_frame_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100);
1420 // Set Maximum gf/arf interval
1421 cpi->max_gf_interval = ((int)(cpi->output_frame_rate / 2.0) + 2);
1423 if(cpi->max_gf_interval < 12)
1424 cpi->max_gf_interval = 12;
1426 // Extended interval for genuinely static scenes
1427 cpi->static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1429 // Special conditions when altr ref frame enabled in lagged compress mode
1430 if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames)
1432 if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1433 cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1435 if (cpi->static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1436 cpi->static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1439 if ( cpi->max_gf_interval > cpi->static_scene_max_gf_interval )
1440 cpi->max_gf_interval = cpi->static_scene_max_gf_interval;
1444 static int
1445 rescale(int val, int num, int denom)
1447 int64_t llnum = num;
1448 int64_t llden = denom;
1449 int64_t llval = val;
1451 return llval * llnum / llden;
1455 static void init_config(VP8_PTR ptr, VP8_CONFIG *oxcf)
1457 VP8_COMP *cpi = (VP8_COMP *)(ptr);
1458 VP8_COMMON *cm = &cpi->common;
1460 cpi->oxcf = *oxcf;
1462 cpi->auto_gold = 1;
1463 cpi->auto_adjust_gold_quantizer = 1;
1464 cpi->goldquantizer = 1;
1465 cpi->goldfreq = 7;
1466 cpi->auto_adjust_key_quantizer = 1;
1467 cpi->keyquantizer = 1;
1469 cm->version = oxcf->Version;
1470 vp8_setup_version(cm);
1472 // change includes all joint functionality
1473 vp8_change_config(ptr, oxcf);
1475 // Initialize active best and worst q and average q values.
1476 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1477 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1478 cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1480 // Initialise the starting buffer levels
1481 cpi->oxcf.starting_buffer_level =
1482 rescale(cpi->oxcf.starting_buffer_level,
1483 cpi->oxcf.target_bandwidth, 1000);
1485 cpi->buffer_level = cpi->oxcf.starting_buffer_level;
1486 cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
1488 cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
1489 cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
1490 cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
1491 cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
1493 cpi->total_actual_bits = 0;
1494 cpi->total_target_vs_actual = 0;
1496 #if VP8_TEMPORAL_ALT_REF
1498 int i;
1500 cpi->fixed_divide[0] = 0;
1502 for (i = 1; i < 512; i++)
1503 cpi->fixed_divide[i] = 0x80000 / i;
1505 #endif
1509 void vp8_change_config(VP8_PTR ptr, VP8_CONFIG *oxcf)
1511 VP8_COMP *cpi = (VP8_COMP *)(ptr);
1512 VP8_COMMON *cm = &cpi->common;
1514 if (!cpi)
1515 return;
1517 if (!oxcf)
1518 return;
1520 if (cm->version != oxcf->Version)
1522 cm->version = oxcf->Version;
1523 vp8_setup_version(cm);
1526 cpi->oxcf = *oxcf;
1528 switch (cpi->oxcf.Mode)
1531 case MODE_REALTIME:
1532 cpi->pass = 0;
1533 cpi->compressor_speed = 2;
1535 if (cpi->oxcf.cpu_used < -16)
1537 cpi->oxcf.cpu_used = -16;
1540 if (cpi->oxcf.cpu_used > 16)
1541 cpi->oxcf.cpu_used = 16;
1543 break;
1545 case MODE_GOODQUALITY:
1546 cpi->pass = 0;
1547 cpi->compressor_speed = 1;
1549 if (cpi->oxcf.cpu_used < -5)
1551 cpi->oxcf.cpu_used = -5;
1554 if (cpi->oxcf.cpu_used > 5)
1555 cpi->oxcf.cpu_used = 5;
1557 break;
1559 case MODE_BESTQUALITY:
1560 cpi->pass = 0;
1561 cpi->compressor_speed = 0;
1562 break;
1564 case MODE_FIRSTPASS:
1565 cpi->pass = 1;
1566 cpi->compressor_speed = 1;
1567 break;
1568 case MODE_SECONDPASS:
1569 cpi->pass = 2;
1570 cpi->compressor_speed = 1;
1572 if (cpi->oxcf.cpu_used < -5)
1574 cpi->oxcf.cpu_used = -5;
1577 if (cpi->oxcf.cpu_used > 5)
1578 cpi->oxcf.cpu_used = 5;
1580 break;
1581 case MODE_SECONDPASS_BEST:
1582 cpi->pass = 2;
1583 cpi->compressor_speed = 0;
1584 break;
1587 if (cpi->pass == 0)
1588 cpi->auto_worst_q = 1;
1590 cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1591 cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1592 cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1594 if (oxcf->fixed_q >= 0)
1596 if (oxcf->worst_allowed_q < 0)
1597 cpi->oxcf.fixed_q = q_trans[0];
1598 else
1599 cpi->oxcf.fixed_q = q_trans[oxcf->worst_allowed_q];
1601 if (oxcf->alt_q < 0)
1602 cpi->oxcf.alt_q = q_trans[0];
1603 else
1604 cpi->oxcf.alt_q = q_trans[oxcf->alt_q];
1606 if (oxcf->key_q < 0)
1607 cpi->oxcf.key_q = q_trans[0];
1608 else
1609 cpi->oxcf.key_q = q_trans[oxcf->key_q];
1611 if (oxcf->gold_q < 0)
1612 cpi->oxcf.gold_q = q_trans[0];
1613 else
1614 cpi->oxcf.gold_q = q_trans[oxcf->gold_q];
1618 cpi->baseline_gf_interval =
1619 cpi->oxcf.alt_freq ? cpi->oxcf.alt_freq : DEFAULT_GF_INTERVAL;
1621 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
1623 //cpi->use_golden_frame_only = 0;
1624 //cpi->use_last_frame_only = 0;
1625 cm->refresh_golden_frame = 0;
1626 cm->refresh_last_frame = 1;
1627 cm->refresh_entropy_probs = 1;
1629 if (cpi->oxcf.token_partitions >= 0 && cpi->oxcf.token_partitions <= 3)
1630 cm->multi_token_partition =
1631 (TOKEN_PARTITION) cpi->oxcf.token_partitions;
1633 setup_features(cpi);
1636 int i;
1638 for (i = 0; i < MAX_MB_SEGMENTS; i++)
1639 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1642 // At the moment the first order values may not be > MAXQ
1643 if (cpi->oxcf.fixed_q > MAXQ)
1644 cpi->oxcf.fixed_q = MAXQ;
1646 // local file playback mode == really big buffer
1647 if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK)
1649 cpi->oxcf.starting_buffer_level = 60000;
1650 cpi->oxcf.optimal_buffer_level = 60000;
1651 cpi->oxcf.maximum_buffer_size = 240000;
1654 // Convert target bandwidth from Kbit/s to Bit/s
1655 cpi->oxcf.target_bandwidth *= 1000;
1657 // Set or reset optimal and maximum buffer levels.
1658 if (cpi->oxcf.optimal_buffer_level == 0)
1659 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1660 else
1661 cpi->oxcf.optimal_buffer_level =
1662 rescale(cpi->oxcf.optimal_buffer_level,
1663 cpi->oxcf.target_bandwidth, 1000);
1665 if (cpi->oxcf.maximum_buffer_size == 0)
1666 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1667 else
1668 cpi->oxcf.maximum_buffer_size =
1669 rescale(cpi->oxcf.maximum_buffer_size,
1670 cpi->oxcf.target_bandwidth, 1000);
1672 // Set up frame rate and related parameters rate control values.
1673 vp8_new_frame_rate(cpi, cpi->oxcf.frame_rate);
1675 // Set absolute upper and lower quality limits
1676 cpi->worst_quality = cpi->oxcf.worst_allowed_q;
1677 cpi->best_quality = cpi->oxcf.best_allowed_q;
1679 // active values should only be modified if out of new range
1680 if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q)
1682 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1684 // less likely
1685 else if (cpi->active_worst_quality < cpi->oxcf.best_allowed_q)
1687 cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
1689 if (cpi->active_best_quality < cpi->oxcf.best_allowed_q)
1691 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1693 // less likely
1694 else if (cpi->active_best_quality > cpi->oxcf.worst_allowed_q)
1696 cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
1699 cpi->buffered_mode = (cpi->oxcf.optimal_buffer_level > 0) ? TRUE : FALSE;
1701 cpi->cq_target_quality = cpi->oxcf.cq_level;
1703 // Only allow dropped frames in buffered mode
1704 cpi->drop_frames_allowed = cpi->oxcf.allow_df && cpi->buffered_mode;
1706 cm->filter_type = (LOOPFILTERTYPE) cpi->filter_type;
1708 if (!cm->use_bilinear_mc_filter)
1709 cm->mcomp_filter_type = SIXTAP;
1710 else
1711 cm->mcomp_filter_type = BILINEAR;
1713 cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1715 cm->Width = cpi->oxcf.Width ;
1716 cm->Height = cpi->oxcf.Height ;
1718 cm->horiz_scale = cpi->horiz_scale;
1719 cm->vert_scale = cpi->vert_scale ;
1721 // As per VP8
1722 cpi->intra_frame_target = (4 * (cm->Width + cm->Height) / 15) * 1000;
1724 // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1725 if (cpi->oxcf.Sharpness > 7)
1726 cpi->oxcf.Sharpness = 7;
1728 cm->sharpness_level = cpi->oxcf.Sharpness;
1730 if (cm->horiz_scale != NORMAL || cm->vert_scale != NORMAL)
1732 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
1733 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
1735 Scale2Ratio(cm->horiz_scale, &hr, &hs);
1736 Scale2Ratio(cm->vert_scale, &vr, &vs);
1738 // always go to the next whole number
1739 cm->Width = (hs - 1 + cpi->oxcf.Width * hr) / hs;
1740 cm->Height = (vs - 1 + cpi->oxcf.Height * vr) / vs;
1743 if (((cm->Width + 15) & 0xfffffff0) !=
1744 cm->yv12_fb[cm->lst_fb_idx].y_width ||
1745 ((cm->Height + 15) & 0xfffffff0) !=
1746 cm->yv12_fb[cm->lst_fb_idx].y_height ||
1747 cm->yv12_fb[cm->lst_fb_idx].y_width == 0)
1749 alloc_raw_frame_buffers(cpi);
1750 vp8_alloc_compressor_data(cpi);
1753 // Clamp KF frame size to quarter of data rate
1754 if (cpi->intra_frame_target > cpi->target_bandwidth >> 2)
1755 cpi->intra_frame_target = cpi->target_bandwidth >> 2;
1757 if (cpi->oxcf.fixed_q >= 0)
1759 cpi->last_q[0] = cpi->oxcf.fixed_q;
1760 cpi->last_q[1] = cpi->oxcf.fixed_q;
1763 cpi->Speed = cpi->oxcf.cpu_used;
1765 // force to allowlag to 0 if lag_in_frames is 0;
1766 if (cpi->oxcf.lag_in_frames == 0)
1768 cpi->oxcf.allow_lag = 0;
1770 // Limit on lag buffers as these are not currently dynamically allocated
1771 else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS)
1772 cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1774 // YX Temp
1775 cpi->last_alt_ref_sei = -1;
1776 cpi->is_src_frame_alt_ref = 0;
1777 cpi->is_next_src_alt_ref = 0;
1779 #if 0
1780 // Experimental RD Code
1781 cpi->frame_distortion = 0;
1782 cpi->last_frame_distortion = 0;
1783 #endif
1787 #define M_LOG2_E 0.693147180559945309417
1788 #define log2f(x) (log (x) / (float) M_LOG2_E)
1789 static void cal_mvsadcosts(int *mvsadcost[2])
1791 int i = 1;
1793 mvsadcost [0] [0] = 300;
1794 mvsadcost [1] [0] = 300;
1798 double z = 256 * (2 * (log2f(8 * i) + .6));
1799 mvsadcost [0][i] = (int) z;
1800 mvsadcost [1][i] = (int) z;
1801 mvsadcost [0][-i] = (int) z;
1802 mvsadcost [1][-i] = (int) z;
1804 while (++i <= mvfp_max);
1807 VP8_PTR vp8_create_compressor(VP8_CONFIG *oxcf)
1809 int i;
1810 volatile union
1812 VP8_COMP *cpi;
1813 VP8_PTR ptr;
1814 } ctx;
1816 VP8_COMP *cpi;
1817 VP8_COMMON *cm;
1819 cpi = ctx.cpi = vpx_memalign(32, sizeof(VP8_COMP));
1820 // Check that the CPI instance is valid
1821 if (!cpi)
1822 return 0;
1824 cm = &cpi->common;
1826 vpx_memset(cpi, 0, sizeof(VP8_COMP));
1828 if (setjmp(cm->error.jmp))
1830 VP8_PTR ptr = ctx.ptr;
1832 ctx.cpi->common.error.setjmp = 0;
1833 vp8_remove_compressor(&ptr);
1834 return 0;
1837 cpi->common.error.setjmp = 1;
1839 CHECK_MEM_ERROR(cpi->mb.ss, vpx_calloc(sizeof(search_site), (MAX_MVSEARCH_STEPS * 8) + 1));
1841 vp8_create_common(&cpi->common);
1842 vp8_cmachine_specific_config(cpi);
1844 init_config((VP8_PTR)cpi, oxcf);
1846 memcpy(cpi->base_skip_false_prob, vp8cx_base_skip_false_prob, sizeof(vp8cx_base_skip_false_prob));
1847 cpi->common.current_video_frame = 0;
1848 cpi->kf_overspend_bits = 0;
1849 cpi->kf_bitrate_adjustment = 0;
1850 cpi->frames_till_gf_update_due = 0;
1851 cpi->gf_overspend_bits = 0;
1852 cpi->non_gf_bitrate_adjustment = 0;
1853 cpi->prob_last_coded = 128;
1854 cpi->prob_gf_coded = 128;
1855 cpi->prob_intra_coded = 63;
1857 // Prime the recent reference frame useage counters.
1858 // Hereafter they will be maintained as a sort of moving average
1859 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
1860 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
1861 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
1862 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
1864 // Set reference frame sign bias for ALTREF frame to 1 (for now)
1865 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
1867 cpi->gf_decay_rate = 0;
1868 cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1870 cpi->gold_is_last = 0 ;
1871 cpi->alt_is_last = 0 ;
1872 cpi->gold_is_alt = 0 ;
1874 // allocate memory for storing last frame's MVs for MV prediction.
1875 CHECK_MEM_ERROR(cpi->lfmv, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int_mv)));
1876 CHECK_MEM_ERROR(cpi->lf_ref_frame_sign_bias, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1877 CHECK_MEM_ERROR(cpi->lf_ref_frame, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1879 // Create the encoder segmentation map and set all entries to 0
1880 CHECK_MEM_ERROR(cpi->segmentation_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1881 CHECK_MEM_ERROR(cpi->active_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1882 vpx_memset(cpi->active_map , 1, (cpi->common.mb_rows * cpi->common.mb_cols));
1883 cpi->active_map_enabled = 0;
1885 #if 0
1886 // Experimental code for lagged and one pass
1887 // Initialise one_pass GF frames stats
1888 // Update stats used for GF selection
1889 if (cpi->pass == 0)
1891 cpi->one_pass_frame_index = 0;
1893 for (i = 0; i < MAX_LAG_BUFFERS; i++)
1895 cpi->one_pass_frame_stats[i].frames_so_far = 0;
1896 cpi->one_pass_frame_stats[i].frame_intra_error = 0.0;
1897 cpi->one_pass_frame_stats[i].frame_coded_error = 0.0;
1898 cpi->one_pass_frame_stats[i].frame_pcnt_inter = 0.0;
1899 cpi->one_pass_frame_stats[i].frame_pcnt_motion = 0.0;
1900 cpi->one_pass_frame_stats[i].frame_mvr = 0.0;
1901 cpi->one_pass_frame_stats[i].frame_mvr_abs = 0.0;
1902 cpi->one_pass_frame_stats[i].frame_mvc = 0.0;
1903 cpi->one_pass_frame_stats[i].frame_mvc_abs = 0.0;
1906 #endif
1908 // Should we use the cyclic refresh method.
1909 // Currently this is tied to error resilliant mode
1910 cpi->cyclic_refresh_mode_enabled = cpi->oxcf.error_resilient_mode;
1911 cpi->cyclic_refresh_mode_max_mbs_perframe = (cpi->common.mb_rows * cpi->common.mb_cols) / 40;
1912 cpi->cyclic_refresh_mode_index = 0;
1913 cpi->cyclic_refresh_q = 32;
1915 if (cpi->cyclic_refresh_mode_enabled)
1917 CHECK_MEM_ERROR(cpi->cyclic_refresh_map, vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
1919 else
1920 cpi->cyclic_refresh_map = (signed char *) NULL;
1922 // Test function for segmentation
1923 //segmentation_test_function((VP8_PTR) cpi);
1925 #ifdef ENTROPY_STATS
1926 init_context_counters();
1927 #endif
1929 /*Initialize the feed-forward activity masking.*/
1930 cpi->activity_avg = 90<<12;
1932 cpi->frames_since_key = 8; // Give a sensible default for the first frame.
1933 cpi->key_frame_frequency = cpi->oxcf.key_freq;
1934 cpi->this_key_frame_forced = FALSE;
1935 cpi->next_key_frame_forced = FALSE;
1937 cpi->source_alt_ref_pending = FALSE;
1938 cpi->source_alt_ref_active = FALSE;
1939 cpi->common.refresh_alt_ref_frame = 0;
1941 cpi->b_calculate_psnr = CONFIG_PSNR;
1942 #if CONFIG_PSNR
1943 cpi->b_calculate_ssimg = 0;
1945 cpi->count = 0;
1946 cpi->bytes = 0;
1948 if (cpi->b_calculate_psnr)
1950 cpi->total_sq_error = 0.0;
1951 cpi->total_sq_error2 = 0.0;
1952 cpi->total_y = 0.0;
1953 cpi->total_u = 0.0;
1954 cpi->total_v = 0.0;
1955 cpi->total = 0.0;
1956 cpi->totalp_y = 0.0;
1957 cpi->totalp_u = 0.0;
1958 cpi->totalp_v = 0.0;
1959 cpi->totalp = 0.0;
1960 cpi->tot_recode_hits = 0;
1961 cpi->summed_quality = 0;
1962 cpi->summed_weights = 0;
1965 if (cpi->b_calculate_ssimg)
1967 cpi->total_ssimg_y = 0;
1968 cpi->total_ssimg_u = 0;
1969 cpi->total_ssimg_v = 0;
1970 cpi->total_ssimg_all = 0;
1973 #ifndef LLONG_MAX
1974 #define LLONG_MAX 9223372036854775807LL
1975 #endif
1976 cpi->first_time_stamp_ever = LLONG_MAX;
1978 #endif
1980 cpi->frames_till_gf_update_due = 0;
1981 cpi->key_frame_count = 1;
1982 cpi->tot_key_frame_bits = 0;
1984 cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
1985 cpi->ni_tot_qi = 0;
1986 cpi->ni_frames = 0;
1987 cpi->total_byte_count = 0;
1989 cpi->drop_frame = 0;
1990 cpi->drop_count = 0;
1991 cpi->max_drop_count = 0;
1992 cpi->max_consec_dropped_frames = 4;
1994 cpi->rate_correction_factor = 1.0;
1995 cpi->key_frame_rate_correction_factor = 1.0;
1996 cpi->gf_rate_correction_factor = 1.0;
1997 cpi->est_max_qcorrection_factor = 1.0;
1999 cpi->mb.mvcost[0] = &cpi->mb.mvcosts[0][mv_max+1];
2000 cpi->mb.mvcost[1] = &cpi->mb.mvcosts[1][mv_max+1];
2001 cpi->mb.mvsadcost[0] = &cpi->mb.mvsadcosts[0][mvfp_max+1];
2002 cpi->mb.mvsadcost[1] = &cpi->mb.mvsadcosts[1][mvfp_max+1];
2004 cal_mvsadcosts(cpi->mb.mvsadcost);
2006 for (i = 0; i < KEY_FRAME_CONTEXT; i++)
2008 cpi->prior_key_frame_size[i] = cpi->intra_frame_target;
2009 cpi->prior_key_frame_distance[i] = (int)cpi->output_frame_rate;
2012 cpi->check_freq[0] = 15;
2013 cpi->check_freq[1] = 15;
2015 #ifdef OUTPUT_YUV_SRC
2016 yuv_file = fopen("bd.yuv", "ab");
2017 #endif
2019 #if 0
2020 framepsnr = fopen("framepsnr.stt", "a");
2021 kf_list = fopen("kf_list.stt", "w");
2022 #endif
2024 cpi->output_pkt_list = oxcf->output_pkt_list;
2026 #if !(CONFIG_REALTIME_ONLY)
2028 if (cpi->pass == 1)
2030 vp8_init_first_pass(cpi);
2032 else if (cpi->pass == 2)
2034 size_t packet_sz = sizeof(FIRSTPASS_STATS);
2035 int packets = oxcf->two_pass_stats_in.sz / packet_sz;
2037 cpi->stats_in = oxcf->two_pass_stats_in.buf;
2038 cpi->stats_in_end = (void*)((char *)cpi->stats_in
2039 + (packets - 1) * packet_sz);
2040 vp8_init_second_pass(cpi);
2043 #endif
2045 if (cpi->compressor_speed == 2)
2047 cpi->cpu_freq = 0; //vp8_get_processor_freq();
2048 cpi->avg_encode_time = 0;
2049 cpi->avg_pick_mode_time = 0;
2052 vp8_set_speed_features(cpi);
2054 // Set starting values of RD threshold multipliers (128 = *1)
2055 for (i = 0; i < MAX_MODES; i++)
2057 cpi->rd_thresh_mult[i] = 128;
2060 #ifdef ENTROPY_STATS
2061 init_mv_ref_counts();
2062 #endif
2064 #if CONFIG_MULTITHREAD
2065 vp8cx_create_encoder_threads(cpi);
2066 #endif
2068 cpi->fn_ptr[BLOCK_16X16].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16);
2069 cpi->fn_ptr[BLOCK_16X16].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x16);
2070 cpi->fn_ptr[BLOCK_16X16].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x16);
2071 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_h = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_h);
2072 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_v = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_v);
2073 cpi->fn_ptr[BLOCK_16X16].svf_halfpix_hv = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_hv);
2074 cpi->fn_ptr[BLOCK_16X16].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x3);
2075 cpi->fn_ptr[BLOCK_16X16].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x8);
2076 cpi->fn_ptr[BLOCK_16X16].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x4d);
2078 cpi->fn_ptr[BLOCK_16X8].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8);
2079 cpi->fn_ptr[BLOCK_16X8].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x8);
2080 cpi->fn_ptr[BLOCK_16X8].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x8);
2081 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_h = NULL;
2082 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_v = NULL;
2083 cpi->fn_ptr[BLOCK_16X8].svf_halfpix_hv = NULL;
2084 cpi->fn_ptr[BLOCK_16X8].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x3);
2085 cpi->fn_ptr[BLOCK_16X8].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x8);
2086 cpi->fn_ptr[BLOCK_16X8].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x4d);
2088 cpi->fn_ptr[BLOCK_8X16].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16);
2089 cpi->fn_ptr[BLOCK_8X16].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x16);
2090 cpi->fn_ptr[BLOCK_8X16].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x16);
2091 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_h = NULL;
2092 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_v = NULL;
2093 cpi->fn_ptr[BLOCK_8X16].svf_halfpix_hv = NULL;
2094 cpi->fn_ptr[BLOCK_8X16].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x3);
2095 cpi->fn_ptr[BLOCK_8X16].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x8);
2096 cpi->fn_ptr[BLOCK_8X16].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x4d);
2098 cpi->fn_ptr[BLOCK_8X8].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8);
2099 cpi->fn_ptr[BLOCK_8X8].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x8);
2100 cpi->fn_ptr[BLOCK_8X8].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x8);
2101 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_h = NULL;
2102 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_v = NULL;
2103 cpi->fn_ptr[BLOCK_8X8].svf_halfpix_hv = NULL;
2104 cpi->fn_ptr[BLOCK_8X8].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x3);
2105 cpi->fn_ptr[BLOCK_8X8].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x8);
2106 cpi->fn_ptr[BLOCK_8X8].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x4d);
2108 cpi->fn_ptr[BLOCK_4X4].sdf = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4);
2109 cpi->fn_ptr[BLOCK_4X4].vf = VARIANCE_INVOKE(&cpi->rtcd.variance, var4x4);
2110 cpi->fn_ptr[BLOCK_4X4].svf = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar4x4);
2111 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_h = NULL;
2112 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_v = NULL;
2113 cpi->fn_ptr[BLOCK_4X4].svf_halfpix_hv = NULL;
2114 cpi->fn_ptr[BLOCK_4X4].sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x3);
2115 cpi->fn_ptr[BLOCK_4X4].sdx8f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x8);
2116 cpi->fn_ptr[BLOCK_4X4].sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x4d);
2118 cpi->full_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, full_search);
2119 cpi->diamond_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, diamond_search);
2121 cpi->ready_for_new_frame = 1;
2123 cpi->source_encode_index = 0;
2125 // make sure frame 1 is okay
2126 cpi->error_bins[0] = cpi->common.MBs;
2128 //vp8cx_init_quantizer() is first called here. Add check in vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only called later
2129 //when needed. This will avoid unnecessary calls of vp8cx_init_quantizer() for every frame.
2130 vp8cx_init_quantizer(cpi);
2132 vp8_init_loop_filter(cm);
2133 cm->last_frame_type = KEY_FRAME;
2134 cm->last_filter_type = cm->filter_type;
2135 cm->last_sharpness_level = cm->sharpness_level;
2137 cpi->common.error.setjmp = 0;
2138 return (VP8_PTR) cpi;
2143 void vp8_remove_compressor(VP8_PTR *ptr)
2145 VP8_COMP *cpi = (VP8_COMP *)(*ptr);
2147 if (!cpi)
2148 return;
2150 if (cpi && (cpi->common.current_video_frame > 0))
2152 #if !(CONFIG_REALTIME_ONLY)
2154 if (cpi->pass == 2)
2156 vp8_end_second_pass(cpi);
2159 #endif
2161 #ifdef ENTROPY_STATS
2162 print_context_counters();
2163 print_tree_update_probs();
2164 print_mode_context();
2165 #endif
2167 #if CONFIG_PSNR
2169 if (cpi->pass != 1)
2171 FILE *f = fopen("opsnr.stt", "a");
2172 double time_encoded = (cpi->source_end_time_stamp - cpi->first_time_stamp_ever) / 10000000.000;
2173 double total_encode_time = (cpi->time_receive_data + cpi->time_compress_data) / 1000.000;
2174 double dr = (double)cpi->bytes * (double) 8 / (double)1000 / time_encoded;
2176 if (cpi->b_calculate_psnr)
2178 YV12_BUFFER_CONFIG *lst_yv12 = &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
2179 double samples = 3.0 / 2 * cpi->count * lst_yv12->y_width * lst_yv12->y_height;
2180 double total_psnr = vp8_mse2psnr(samples, 255.0, cpi->total_sq_error);
2181 double total_psnr2 = vp8_mse2psnr(samples, 255.0, cpi->total_sq_error2);
2182 double total_ssim = 100 * pow(cpi->summed_quality / cpi->summed_weights, 8.0);
2184 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\tVPXSSIM\t Time(us)\n");
2185 fprintf(f, "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%8.0f\n",
2186 dr, cpi->total / cpi->count, total_psnr, cpi->totalp / cpi->count, total_psnr2, total_ssim,
2187 total_encode_time);
2190 if (cpi->b_calculate_ssimg)
2192 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t Time(us)\n");
2193 fprintf(f, "%7.3f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
2194 cpi->total_ssimg_y / cpi->count, cpi->total_ssimg_u / cpi->count,
2195 cpi->total_ssimg_v / cpi->count, cpi->total_ssimg_all / cpi->count, total_encode_time);
2198 fclose(f);
2199 #if 0
2200 f = fopen("qskip.stt", "a");
2201 fprintf(f, "minq:%d -maxq:%d skipture:skipfalse = %d:%d\n", cpi->oxcf.best_allowed_q, cpi->oxcf.worst_allowed_q, skiptruecount, skipfalsecount);
2202 fclose(f);
2203 #endif
2207 #endif
2210 #ifdef SPEEDSTATS
2212 if (cpi->compressor_speed == 2)
2214 int i;
2215 FILE *f = fopen("cxspeed.stt", "a");
2216 cnt_pm /= cpi->common.MBs;
2218 for (i = 0; i < 16; i++)
2219 fprintf(f, "%5d", frames_at_speed[i]);
2221 fprintf(f, "\n");
2222 //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);
2223 fclose(f);
2226 #endif
2229 #ifdef MODE_STATS
2231 extern int count_mb_seg[4];
2232 FILE *f = fopen("modes.stt", "a");
2233 double dr = (double)cpi->oxcf.frame_rate * (double)bytes * (double)8 / (double)count / (double)1000 ;
2234 fprintf(f, "intra_mode in Intra Frames:\n");
2235 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d\n", y_modes[0], y_modes[1], y_modes[2], y_modes[3], y_modes[4]);
2236 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", uv_modes[0], uv_modes[1], uv_modes[2], uv_modes[3]);
2237 fprintf(f, "B: ");
2239 int i;
2241 for (i = 0; i < 10; i++)
2242 fprintf(f, "%8d, ", b_modes[i]);
2244 fprintf(f, "\n");
2248 fprintf(f, "Modes in Inter Frames:\n");
2249 fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d\n",
2250 inter_y_modes[0], inter_y_modes[1], inter_y_modes[2], inter_y_modes[3], inter_y_modes[4],
2251 inter_y_modes[5], inter_y_modes[6], inter_y_modes[7], inter_y_modes[8], inter_y_modes[9]);
2252 fprintf(f, "UV:%8d, %8d, %8d, %8d\n", inter_uv_modes[0], inter_uv_modes[1], inter_uv_modes[2], inter_uv_modes[3]);
2253 fprintf(f, "B: ");
2255 int i;
2257 for (i = 0; i < 15; i++)
2258 fprintf(f, "%8d, ", inter_b_modes[i]);
2260 fprintf(f, "\n");
2263 fprintf(f, "P:%8d, %8d, %8d, %8d\n", count_mb_seg[0], count_mb_seg[1], count_mb_seg[2], count_mb_seg[3]);
2264 fprintf(f, "PB:%8d, %8d, %8d, %8d\n", inter_b_modes[LEFT4X4], inter_b_modes[ABOVE4X4], inter_b_modes[ZERO4X4], inter_b_modes[NEW4X4]);
2268 fclose(f);
2270 #endif
2272 #ifdef ENTROPY_STATS
2274 int i, j, k;
2275 FILE *fmode = fopen("modecontext.c", "w");
2277 fprintf(fmode, "\n#include \"entropymode.h\"\n\n");
2278 fprintf(fmode, "const unsigned int vp8_kf_default_bmode_counts ");
2279 fprintf(fmode, "[VP8_BINTRAMODES] [VP8_BINTRAMODES] [VP8_BINTRAMODES] =\n{\n");
2281 for (i = 0; i < 10; i++)
2284 fprintf(fmode, " { //Above Mode : %d\n", i);
2286 for (j = 0; j < 10; j++)
2289 fprintf(fmode, " {");
2291 for (k = 0; k < 10; k++)
2293 if (!intra_mode_stats[i][j][k])
2294 fprintf(fmode, " %5d, ", 1);
2295 else
2296 fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
2299 fprintf(fmode, "}, // left_mode %d\n", j);
2303 fprintf(fmode, " },\n");
2307 fprintf(fmode, "};\n");
2308 fclose(fmode);
2310 #endif
2313 #if defined(SECTIONBITS_OUTPUT)
2315 if (0)
2317 int i;
2318 FILE *f = fopen("tokenbits.stt", "a");
2320 for (i = 0; i < 28; i++)
2321 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
2323 fprintf(f, "\n");
2324 fclose(f);
2327 #endif
2329 #if 0
2331 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2332 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
2333 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);
2335 #endif
2339 #if CONFIG_MULTITHREAD
2340 vp8cx_remove_encoder_threads(cpi);
2341 #endif
2343 dealloc_compressor_data(cpi);
2344 vpx_free(cpi->mb.ss);
2345 vpx_free(cpi->tok);
2346 vpx_free(cpi->cyclic_refresh_map);
2348 vp8_remove_common(&cpi->common);
2349 vpx_free(cpi);
2350 *ptr = 0;
2352 #ifdef OUTPUT_YUV_SRC
2353 fclose(yuv_file);
2354 #endif
2356 #if 0
2358 if (keyfile)
2359 fclose(keyfile);
2361 if (framepsnr)
2362 fclose(framepsnr);
2364 if (kf_list)
2365 fclose(kf_list);
2367 #endif
2372 static uint64_t calc_plane_error(unsigned char *orig, int orig_stride,
2373 unsigned char *recon, int recon_stride,
2374 unsigned int cols, unsigned int rows,
2375 vp8_variance_rtcd_vtable_t *rtcd)
2377 unsigned int row, col;
2378 uint64_t total_sse = 0;
2379 int diff;
2381 for (row = 0; row + 16 <= rows; row += 16)
2383 for (col = 0; col + 16 <= cols; col += 16)
2385 unsigned int sse;
2387 VARIANCE_INVOKE(rtcd, mse16x16)(orig + col, orig_stride,
2388 recon + col, recon_stride,
2389 &sse);
2390 total_sse += sse;
2393 /* Handle odd-sized width */
2394 if (col < cols)
2396 unsigned int border_row, border_col;
2397 unsigned char *border_orig = orig;
2398 unsigned char *border_recon = recon;
2400 for (border_row = 0; border_row < 16; border_row++)
2402 for (border_col = col; border_col < cols; border_col++)
2404 diff = border_orig[border_col] - border_recon[border_col];
2405 total_sse += diff * diff;
2408 border_orig += orig_stride;
2409 border_recon += recon_stride;
2413 orig += orig_stride * 16;
2414 recon += recon_stride * 16;
2417 /* Handle odd-sized height */
2418 for (; row < rows; row++)
2420 for (col = 0; col < cols; col++)
2422 diff = orig[col] - recon[col];
2423 total_sse += diff * diff;
2426 orig += orig_stride;
2427 recon += recon_stride;
2430 return total_sse;
2434 static void generate_psnr_packet(VP8_COMP *cpi)
2436 YV12_BUFFER_CONFIG *orig = cpi->Source;
2437 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2438 struct vpx_codec_cx_pkt pkt;
2439 uint64_t sse;
2440 int i;
2441 unsigned int width = cpi->common.Width;
2442 unsigned int height = cpi->common.Height;
2444 pkt.kind = VPX_CODEC_PSNR_PKT;
2445 sse = calc_plane_error(orig->y_buffer, orig->y_stride,
2446 recon->y_buffer, recon->y_stride,
2447 width, height,
2448 IF_RTCD(&cpi->rtcd.variance));
2449 pkt.data.psnr.sse[0] = sse;
2450 pkt.data.psnr.sse[1] = sse;
2451 pkt.data.psnr.samples[0] = width * height;
2452 pkt.data.psnr.samples[1] = width * height;
2454 width = (width + 1) / 2;
2455 height = (height + 1) / 2;
2457 sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
2458 recon->u_buffer, recon->uv_stride,
2459 width, height,
2460 IF_RTCD(&cpi->rtcd.variance));
2461 pkt.data.psnr.sse[0] += sse;
2462 pkt.data.psnr.sse[2] = sse;
2463 pkt.data.psnr.samples[0] += width * height;
2464 pkt.data.psnr.samples[2] = width * height;
2466 sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2467 recon->v_buffer, recon->uv_stride,
2468 width, height,
2469 IF_RTCD(&cpi->rtcd.variance));
2470 pkt.data.psnr.sse[0] += sse;
2471 pkt.data.psnr.sse[3] = sse;
2472 pkt.data.psnr.samples[0] += width * height;
2473 pkt.data.psnr.samples[3] = width * height;
2475 for (i = 0; i < 4; i++)
2476 pkt.data.psnr.psnr[i] = vp8_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2477 pkt.data.psnr.sse[i]);
2479 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2483 int vp8_use_as_reference(VP8_PTR ptr, int ref_frame_flags)
2485 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2487 if (ref_frame_flags > 7)
2488 return -1 ;
2490 cpi->ref_frame_flags = ref_frame_flags;
2491 return 0;
2493 int vp8_update_reference(VP8_PTR ptr, int ref_frame_flags)
2495 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2497 if (ref_frame_flags > 7)
2498 return -1 ;
2500 cpi->common.refresh_golden_frame = 0;
2501 cpi->common.refresh_alt_ref_frame = 0;
2502 cpi->common.refresh_last_frame = 0;
2504 if (ref_frame_flags & VP8_LAST_FLAG)
2505 cpi->common.refresh_last_frame = 1;
2507 if (ref_frame_flags & VP8_GOLD_FLAG)
2508 cpi->common.refresh_golden_frame = 1;
2510 if (ref_frame_flags & VP8_ALT_FLAG)
2511 cpi->common.refresh_alt_ref_frame = 1;
2513 return 0;
2516 int vp8_get_reference(VP8_PTR ptr, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2518 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2519 VP8_COMMON *cm = &cpi->common;
2520 int ref_fb_idx;
2522 if (ref_frame_flag == VP8_LAST_FLAG)
2523 ref_fb_idx = cm->lst_fb_idx;
2524 else if (ref_frame_flag == VP8_GOLD_FLAG)
2525 ref_fb_idx = cm->gld_fb_idx;
2526 else if (ref_frame_flag == VP8_ALT_FLAG)
2527 ref_fb_idx = cm->alt_fb_idx;
2528 else
2529 return -1;
2531 vp8_yv12_copy_frame_ptr(&cm->yv12_fb[ref_fb_idx], sd);
2533 return 0;
2535 int vp8_set_reference(VP8_PTR ptr, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2537 VP8_COMP *cpi = (VP8_COMP *)(ptr);
2538 VP8_COMMON *cm = &cpi->common;
2540 int ref_fb_idx;
2542 if (ref_frame_flag == VP8_LAST_FLAG)
2543 ref_fb_idx = cm->lst_fb_idx;
2544 else if (ref_frame_flag == VP8_GOLD_FLAG)
2545 ref_fb_idx = cm->gld_fb_idx;
2546 else if (ref_frame_flag == VP8_ALT_FLAG)
2547 ref_fb_idx = cm->alt_fb_idx;
2548 else
2549 return -1;
2551 vp8_yv12_copy_frame_ptr(sd, &cm->yv12_fb[ref_fb_idx]);
2553 return 0;
2555 int vp8_update_entropy(VP8_PTR comp, int update)
2557 VP8_COMP *cpi = (VP8_COMP *) comp;
2558 VP8_COMMON *cm = &cpi->common;
2559 cm->refresh_entropy_probs = update;
2561 return 0;
2565 #if OUTPUT_YUV_SRC
2566 void vp8_write_yuv_frame(const char *name, YV12_BUFFER_CONFIG *s)
2568 FILE *yuv_file = fopen(name, "ab");
2569 unsigned char *src = s->y_buffer;
2570 int h = s->y_height;
2574 fwrite(src, s->y_width, 1, yuv_file);
2575 src += s->y_stride;
2577 while (--h);
2579 src = s->u_buffer;
2580 h = s->uv_height;
2584 fwrite(src, s->uv_width, 1, yuv_file);
2585 src += s->uv_stride;
2587 while (--h);
2589 src = s->v_buffer;
2590 h = s->uv_height;
2594 fwrite(src, s->uv_width, 1, yuv_file);
2595 src += s->uv_stride;
2597 while (--h);
2599 fclose(yuv_file);
2601 #endif
2604 static void scale_and_extend_source(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi)
2606 VP8_COMMON *cm = &cpi->common;
2608 // are we resizing the image
2609 if (cm->horiz_scale != 0 || cm->vert_scale != 0)
2611 #if CONFIG_SPATIAL_RESAMPLING
2612 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2613 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2614 int tmp_height;
2616 if (cm->vert_scale == 3)
2617 tmp_height = 9;
2618 else
2619 tmp_height = 11;
2621 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2622 Scale2Ratio(cm->vert_scale, &vr, &vs);
2624 vp8_scale_frame(sd, &cpi->scaled_source, cm->temp_scale_frame.y_buffer,
2625 tmp_height, hs, hr, vs, vr, 0);
2627 cpi->Source = &cpi->scaled_source;
2628 #endif
2630 // we may need to copy to a buffer so we can extend the image...
2631 else if (cm->Width != cm->yv12_fb[cm->lst_fb_idx].y_width ||
2632 cm->Height != cm->yv12_fb[cm->lst_fb_idx].y_height)
2634 //vp8_yv12_copy_frame_ptr(sd, &cpi->scaled_source);
2635 #if HAVE_ARMV7
2636 #if CONFIG_RUNTIME_CPU_DETECT
2637 if (cm->rtcd.flags & HAS_NEON)
2638 #endif
2640 vp8_yv12_copy_src_frame_func_neon(sd, &cpi->scaled_source);
2642 #if CONFIG_RUNTIME_CPU_DETECT
2643 else
2644 #endif
2645 #endif
2646 #if !HAVE_ARMV7 || CONFIG_RUNTIME_CPU_DETECT
2648 vp8_yv12_copy_frame_ptr(sd, &cpi->scaled_source);
2650 #endif
2652 cpi->Source = &cpi->scaled_source;
2655 vp8_extend_to_multiple_of16(cpi->Source, cm->Width, cm->Height);
2658 static void resize_key_frame(VP8_COMP *cpi)
2660 #if CONFIG_SPATIAL_RESAMPLING
2661 VP8_COMMON *cm = &cpi->common;
2663 // Do we need to apply resampling for one pass cbr.
2664 // In one pass this is more limited than in two pass cbr
2665 // The test and any change is only made one per key frame sequence
2666 if (cpi->oxcf.allow_spatial_resampling && (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER))
2668 int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2669 int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2670 int new_width, new_height;
2672 // If we are below the resample DOWN watermark then scale down a notch.
2673 if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2675 cm->horiz_scale = (cm->horiz_scale < ONETWO) ? cm->horiz_scale + 1 : ONETWO;
2676 cm->vert_scale = (cm->vert_scale < ONETWO) ? cm->vert_scale + 1 : ONETWO;
2678 // Should we now start scaling back up
2679 else if (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2681 cm->horiz_scale = (cm->horiz_scale > NORMAL) ? cm->horiz_scale - 1 : NORMAL;
2682 cm->vert_scale = (cm->vert_scale > NORMAL) ? cm->vert_scale - 1 : NORMAL;
2685 // Get the new hieght and width
2686 Scale2Ratio(cm->horiz_scale, &hr, &hs);
2687 Scale2Ratio(cm->vert_scale, &vr, &vs);
2688 new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
2689 new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
2691 // If the image size has changed we need to reallocate the buffers
2692 // and resample the source image
2693 if ((cm->Width != new_width) || (cm->Height != new_height))
2695 cm->Width = new_width;
2696 cm->Height = new_height;
2697 vp8_alloc_compressor_data(cpi);
2698 scale_and_extend_source(cpi->un_scaled_source, cpi);
2702 #endif
2704 // return of 0 means drop frame
2705 static int pick_frame_size(VP8_COMP *cpi)
2707 VP8_COMMON *cm = &cpi->common;
2709 // First Frame is a special case
2710 if (cm->current_video_frame == 0)
2712 #if !(CONFIG_REALTIME_ONLY)
2714 if (cpi->pass == 2)
2715 vp8_calc_auto_iframe_target_size(cpi);
2717 // 1 Pass there is no information on which to base size so use bandwidth per second * fixed fraction
2718 else
2719 #endif
2720 cpi->this_frame_target = cpi->oxcf.target_bandwidth / 2;
2722 // in error resilient mode the first frame is bigger since it likely contains
2723 // all the static background
2724 if (cpi->oxcf.error_resilient_mode == 1 || (cpi->compressor_speed == 2))
2726 cpi->this_frame_target *= 3; // 5;
2729 // Key frame from VFW/auto-keyframe/first frame
2730 cm->frame_type = KEY_FRAME;
2733 // Special case for forced key frames
2734 // The frame sizing here is still far from ideal for 2 pass.
2735 else if (cm->frame_flags & FRAMEFLAGS_KEY)
2737 cm->frame_type = KEY_FRAME;
2738 resize_key_frame(cpi);
2739 vp8_calc_iframe_target_size(cpi);
2741 else if (cm->frame_type == KEY_FRAME)
2743 vp8_calc_auto_iframe_target_size(cpi);
2745 else
2747 // INTER frame: compute target frame size
2748 cm->frame_type = INTER_FRAME;
2749 vp8_calc_pframe_target_size(cpi);
2751 // Check if we're dropping the frame:
2752 if (cpi->drop_frame)
2754 cpi->drop_frame = FALSE;
2755 cpi->drop_count++;
2756 return 0;
2760 return 1;
2763 static void set_quantizer(VP8_COMP *cpi, int Q)
2765 VP8_COMMON *cm = &cpi->common;
2766 MACROBLOCKD *mbd = &cpi->mb.e_mbd;
2767 int update = 0;
2768 int new_delta_q;
2769 cm->base_qindex = Q;
2771 /* if any of the delta_q values are changing update flag has to be set */
2772 /* currently only y2dc_delta_q may change */
2774 cm->y1dc_delta_q = 0;
2775 cm->y2ac_delta_q = 0;
2776 cm->uvdc_delta_q = 0;
2777 cm->uvac_delta_q = 0;
2779 if (Q < 4)
2781 new_delta_q = 4-Q;
2783 else
2784 new_delta_q = 0;
2786 update |= cm->y2dc_delta_q != new_delta_q;
2787 cm->y2dc_delta_q = new_delta_q;
2790 // Set Segment specific quatizers
2791 mbd->segment_feature_data[MB_LVL_ALT_Q][0] = cpi->segment_feature_data[MB_LVL_ALT_Q][0];
2792 mbd->segment_feature_data[MB_LVL_ALT_Q][1] = cpi->segment_feature_data[MB_LVL_ALT_Q][1];
2793 mbd->segment_feature_data[MB_LVL_ALT_Q][2] = cpi->segment_feature_data[MB_LVL_ALT_Q][2];
2794 mbd->segment_feature_data[MB_LVL_ALT_Q][3] = cpi->segment_feature_data[MB_LVL_ALT_Q][3];
2796 /* quantizer has to be reinitialized for any delta_q changes */
2797 if(update)
2798 vp8cx_init_quantizer(cpi);
2802 static void update_alt_ref_frame_and_stats(VP8_COMP *cpi)
2804 VP8_COMMON *cm = &cpi->common;
2806 // Update the golden frame buffer
2807 vp8_yv12_copy_frame_ptr(cm->frame_to_show, &cm->yv12_fb[cm->alt_fb_idx]);
2809 // Select an interval before next GF or altref
2810 if (!cpi->auto_gold)
2811 cpi->frames_till_gf_update_due = cpi->goldfreq;
2813 if ((cpi->pass != 2) && cpi->frames_till_gf_update_due)
2815 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2817 // Set the bits per frame that we should try and recover in subsequent inter frames
2818 // to account for the extra GF spend... note that his does not apply for GF updates
2819 // that occur coincident with a key frame as the extra cost of key frames is dealt
2820 // with elsewhere.
2822 cpi->gf_overspend_bits += cpi->projected_frame_size;
2823 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2826 // Update data structure that monitors level of reference to last GF
2827 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2828 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2830 // this frame refreshes means next frames don't unless specified by user
2831 cpi->common.frames_since_golden = 0;
2833 // Clear the alternate reference update pending flag.
2834 cpi->source_alt_ref_pending = FALSE;
2836 // Set the alternate refernce frame active flag
2837 cpi->source_alt_ref_active = TRUE;
2841 static void update_golden_frame_and_stats(VP8_COMP *cpi)
2843 VP8_COMMON *cm = &cpi->common;
2845 // Update the Golden frame reconstruction buffer if signalled and the GF usage counts.
2846 if (cm->refresh_golden_frame)
2848 if (cm->frame_type != KEY_FRAME)
2850 // Update the golden frame buffer
2851 vp8_yv12_copy_frame_ptr(cm->frame_to_show, &cm->yv12_fb[cm->gld_fb_idx]);
2854 // Select an interval before next GF
2855 if (!cpi->auto_gold)
2856 cpi->frames_till_gf_update_due = cpi->goldfreq;
2858 if ((cpi->pass != 2) && (cpi->frames_till_gf_update_due > 0))
2860 cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2862 // Set the bits per frame that we should try and recover in subsequent inter frames
2863 // to account for the extra GF spend... note that his does not apply for GF updates
2864 // that occur coincident with a key frame as the extra cost of key frames is dealt
2865 // with elsewhere.
2866 if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active)
2868 // Calcluate GF bits to be recovered
2869 // Projected size - av frame bits available for inter frames for clip as a whole
2870 cpi->gf_overspend_bits += (cpi->projected_frame_size - cpi->inter_frame_target);
2873 cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2877 // Update data structure that monitors level of reference to last GF
2878 vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2879 cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2881 // this frame refreshes means next frames don't unless specified by user
2882 cm->refresh_golden_frame = 0;
2883 cpi->common.frames_since_golden = 0;
2885 //if ( cm->frame_type == KEY_FRAME )
2887 cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
2888 cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
2889 cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
2890 cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
2892 //else
2894 // // Carry a potrtion of count over to begining of next gf sequence
2895 // cpi->recent_ref_frame_usage[INTRA_FRAME] >>= 5;
2896 // cpi->recent_ref_frame_usage[LAST_FRAME] >>= 5;
2897 // cpi->recent_ref_frame_usage[GOLDEN_FRAME] >>= 5;
2898 // cpi->recent_ref_frame_usage[ALTREF_FRAME] >>= 5;
2901 // ******** Fixed Q test code only ************
2902 // If we are going to use the ALT reference for the next group of frames set a flag to say so.
2903 if (cpi->oxcf.fixed_q >= 0 &&
2904 cpi->oxcf.play_alternate && !cpi->common.refresh_alt_ref_frame)
2906 cpi->source_alt_ref_pending = TRUE;
2907 cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2910 if (!cpi->source_alt_ref_pending)
2911 cpi->source_alt_ref_active = FALSE;
2913 // Decrement count down till next gf
2914 if (cpi->frames_till_gf_update_due > 0)
2915 cpi->frames_till_gf_update_due--;
2918 else if (!cpi->common.refresh_alt_ref_frame)
2920 // Decrement count down till next gf
2921 if (cpi->frames_till_gf_update_due > 0)
2922 cpi->frames_till_gf_update_due--;
2924 if (cpi->common.frames_till_alt_ref_frame)
2925 cpi->common.frames_till_alt_ref_frame --;
2927 cpi->common.frames_since_golden ++;
2929 if (cpi->common.frames_since_golden > 1)
2931 cpi->recent_ref_frame_usage[INTRA_FRAME] += cpi->count_mb_ref_frame_usage[INTRA_FRAME];
2932 cpi->recent_ref_frame_usage[LAST_FRAME] += cpi->count_mb_ref_frame_usage[LAST_FRAME];
2933 cpi->recent_ref_frame_usage[GOLDEN_FRAME] += cpi->count_mb_ref_frame_usage[GOLDEN_FRAME];
2934 cpi->recent_ref_frame_usage[ALTREF_FRAME] += cpi->count_mb_ref_frame_usage[ALTREF_FRAME];
2939 // This function updates the reference frame probability estimates that
2940 // will be used during mode selection
2941 static void update_rd_ref_frame_probs(VP8_COMP *cpi)
2943 VP8_COMMON *cm = &cpi->common;
2945 #if 0
2946 const int *const rfct = cpi->recent_ref_frame_usage;
2947 const int rf_intra = rfct[INTRA_FRAME];
2948 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
2950 if (cm->frame_type == KEY_FRAME)
2952 cpi->prob_intra_coded = 255;
2953 cpi->prob_last_coded = 128;
2954 cpi->prob_gf_coded = 128;
2956 else if (!(rf_intra + rf_inter))
2958 // This is a trap in case this function is called with cpi->recent_ref_frame_usage[] blank.
2959 cpi->prob_intra_coded = 63;
2960 cpi->prob_last_coded = 128;
2961 cpi->prob_gf_coded = 128;
2963 else
2965 cpi->prob_intra_coded = (rf_intra * 255) / (rf_intra + rf_inter);
2967 if (cpi->prob_intra_coded < 1)
2968 cpi->prob_intra_coded = 1;
2970 if ((cm->frames_since_golden > 0) || cpi->source_alt_ref_active)
2972 cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
2974 if (cpi->prob_last_coded < 1)
2975 cpi->prob_last_coded = 1;
2977 cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
2978 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
2980 if (cpi->prob_gf_coded < 1)
2981 cpi->prob_gf_coded = 1;
2985 #else
2986 const int *const rfct = cpi->count_mb_ref_frame_usage;
2987 const int rf_intra = rfct[INTRA_FRAME];
2988 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
2990 if (cm->frame_type == KEY_FRAME)
2992 cpi->prob_intra_coded = 255;
2993 cpi->prob_last_coded = 128;
2994 cpi->prob_gf_coded = 128;
2996 else if (!(rf_intra + rf_inter))
2998 // This is a trap in case this function is called with cpi->recent_ref_frame_usage[] blank.
2999 cpi->prob_intra_coded = 63;
3000 cpi->prob_last_coded = 128;
3001 cpi->prob_gf_coded = 128;
3003 else
3005 cpi->prob_intra_coded = (rf_intra * 255) / (rf_intra + rf_inter);
3007 if (cpi->prob_intra_coded < 1)
3008 cpi->prob_intra_coded = 1;
3010 cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
3012 if (cpi->prob_last_coded < 1)
3013 cpi->prob_last_coded = 1;
3015 cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
3016 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
3018 if (cpi->prob_gf_coded < 1)
3019 cpi->prob_gf_coded = 1;
3022 // update reference frame costs since we can do better than what we got last frame.
3024 if (cpi->common.refresh_alt_ref_frame)
3026 cpi->prob_intra_coded += 40;
3027 cpi->prob_last_coded = 200;
3028 cpi->prob_gf_coded = 1;
3030 else if (cpi->common.frames_since_golden == 0)
3032 cpi->prob_last_coded = 214;
3033 cpi->prob_gf_coded = 1;
3035 else if (cpi->common.frames_since_golden == 1)
3037 cpi->prob_last_coded = 192;
3038 cpi->prob_gf_coded = 220;
3040 else if (cpi->source_alt_ref_active)
3042 //int dist = cpi->common.frames_till_alt_ref_frame + cpi->common.frames_since_golden;
3043 cpi->prob_gf_coded -= 20;
3045 if (cpi->prob_gf_coded < 10)
3046 cpi->prob_gf_coded = 10;
3049 #endif
3053 // 1 = key, 0 = inter
3054 static int decide_key_frame(VP8_COMP *cpi)
3056 VP8_COMMON *cm = &cpi->common;
3058 int code_key_frame = FALSE;
3060 cpi->kf_boost = 0;
3062 if (cpi->Speed > 11)
3063 return FALSE;
3065 // Clear down mmx registers
3066 vp8_clear_system_state(); //__asm emms;
3068 if ((cpi->compressor_speed == 2) && (cpi->Speed >= 5) && (cpi->sf.RD == 0))
3070 double change = 1.0 * abs((int)(cpi->intra_error - cpi->last_intra_error)) / (1 + cpi->last_intra_error);
3071 double change2 = 1.0 * abs((int)(cpi->prediction_error - cpi->last_prediction_error)) / (1 + cpi->last_prediction_error);
3072 double minerror = cm->MBs * 256;
3074 #if 0
3076 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
3077 && cpi->prediction_error > minerror
3078 && (change > .25 || change2 > .25))
3080 FILE *f = fopen("intra_inter.stt", "a");
3082 if (cpi->prediction_error <= 0)
3083 cpi->prediction_error = 1;
3085 fprintf(f, "%d %d %d %d %14.4f\n",
3086 cm->current_video_frame,
3087 (int) cpi->prediction_error,
3088 (int) cpi->intra_error,
3089 (int)((10 * cpi->intra_error) / cpi->prediction_error),
3090 change);
3092 fclose(f);
3095 #endif
3097 cpi->last_intra_error = cpi->intra_error;
3098 cpi->last_prediction_error = cpi->prediction_error;
3100 if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
3101 && cpi->prediction_error > minerror
3102 && (change > .25 || change2 > .25))
3104 /*(change > 1.4 || change < .75)&& cpi->this_frame_percent_intra > cpi->last_frame_percent_intra + 3*/
3105 return TRUE;
3108 return FALSE;
3112 // If the following are true we might as well code a key frame
3113 if (((cpi->this_frame_percent_intra == 100) &&
3114 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
3115 ((cpi->this_frame_percent_intra > 95) &&
3116 (cpi->this_frame_percent_intra >= (cpi->last_frame_percent_intra + 5))))
3118 code_key_frame = TRUE;
3120 // in addition if the following are true and this is not a golden frame then code a key frame
3121 // Note that on golden frames there often seems to be a pop in intra useage anyway hence this
3122 // restriction is designed to prevent spurious key frames. The Intra pop needs to be investigated.
3123 else if (((cpi->this_frame_percent_intra > 60) &&
3124 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 2))) ||
3125 ((cpi->this_frame_percent_intra > 75) &&
3126 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 3 / 2))) ||
3127 ((cpi->this_frame_percent_intra > 90) &&
3128 (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 10))))
3130 if (!cm->refresh_golden_frame)
3131 code_key_frame = TRUE;
3134 return code_key_frame;
3138 #if !(CONFIG_REALTIME_ONLY)
3139 static void Pass1Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags)
3141 (void) size;
3142 (void) dest;
3143 (void) frame_flags;
3144 set_quantizer(cpi, 26);
3146 scale_and_extend_source(cpi->un_scaled_source, cpi);
3147 vp8_first_pass(cpi);
3149 #endif
3151 #if 0
3152 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame)
3155 // write the frame
3156 FILE *yframe;
3157 int i;
3158 char filename[255];
3160 sprintf(filename, "cx\\y%04d.raw", this_frame);
3161 yframe = fopen(filename, "wb");
3163 for (i = 0; i < frame->y_height; i++)
3164 fwrite(frame->y_buffer + i * frame->y_stride, frame->y_width, 1, yframe);
3166 fclose(yframe);
3167 sprintf(filename, "cx\\u%04d.raw", this_frame);
3168 yframe = fopen(filename, "wb");
3170 for (i = 0; i < frame->uv_height; i++)
3171 fwrite(frame->u_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
3173 fclose(yframe);
3174 sprintf(filename, "cx\\v%04d.raw", this_frame);
3175 yframe = fopen(filename, "wb");
3177 for (i = 0; i < frame->uv_height; i++)
3178 fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
3180 fclose(yframe);
3182 #endif
3183 // return of 0 means drop frame
3185 // Function to test for conditions that indeicate we should loop
3186 // back and recode a frame.
3187 static BOOL recode_loop_test( VP8_COMP *cpi,
3188 int high_limit, int low_limit,
3189 int q, int maxq, int minq )
3191 BOOL force_recode = FALSE;
3192 VP8_COMMON *cm = &cpi->common;
3194 // Is frame recode allowed at all
3195 // Yes if either recode mode 1 is selected or mode two is selcted
3196 // and the frame is a key frame. golden frame or alt_ref_frame
3197 if ( (cpi->sf.recode_loop == 1) ||
3198 ( (cpi->sf.recode_loop == 2) &&
3199 ( (cm->frame_type == KEY_FRAME) ||
3200 cm->refresh_golden_frame ||
3201 cm->refresh_alt_ref_frame ) ) )
3203 // General over and under shoot tests
3204 if ( ((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
3205 ((cpi->projected_frame_size < low_limit) && (q > minq)) )
3207 force_recode = TRUE;
3209 // Special Constrained quality tests
3210 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
3212 // Undershoot and below auto cq level
3213 if ( (q > cpi->cq_target_quality) &&
3214 (cpi->projected_frame_size <
3215 ((cpi->this_frame_target * 7) >> 3)))
3217 force_recode = TRUE;
3219 // Severe undershoot and between auto and user cq level
3220 else if ( (q > cpi->oxcf.cq_level) &&
3221 (cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
3222 (cpi->active_best_quality > cpi->oxcf.cq_level))
3224 force_recode = TRUE;
3225 cpi->active_best_quality = cpi->oxcf.cq_level;
3230 return force_recode;
3233 void loopfilter_frame(VP8_COMP *cpi, VP8_COMMON *cm)
3235 if (cm->no_lpf)
3237 cm->filter_level = 0;
3239 else
3241 struct vpx_usec_timer timer;
3243 vp8_clear_system_state();
3245 vpx_usec_timer_start(&timer);
3246 if (cpi->sf.auto_filter == 0)
3247 vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3249 else
3250 vp8cx_pick_filter_level(cpi->Source, cpi);
3252 vpx_usec_timer_mark(&timer);
3253 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
3256 #if CONFIG_MULTITHREAD
3257 if (cpi->b_multi_threaded)
3258 sem_post(&cpi->h_event_end_lpf); /* signal that we have set filter_level */
3259 #endif
3261 if (cm->filter_level > 0)
3263 vp8cx_set_alt_lf_level(cpi, cm->filter_level);
3264 vp8_loop_filter_frame(cm, &cpi->mb.e_mbd, cm->filter_level);
3265 cm->last_filter_type = cm->filter_type;
3266 cm->last_sharpness_level = cm->sharpness_level;
3269 vp8_yv12_extend_frame_borders_ptr(cm->frame_to_show);
3272 YV12_BUFFER_CONFIG *lst_yv12 = &cm->yv12_fb[cm->lst_fb_idx];
3273 YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
3274 YV12_BUFFER_CONFIG *gld_yv12 = &cm->yv12_fb[cm->gld_fb_idx];
3275 YV12_BUFFER_CONFIG *alt_yv12 = &cm->yv12_fb[cm->alt_fb_idx];
3276 // At this point the new frame has been encoded.
3277 // If any buffer copy / swapping is signaled it should be done here.
3278 if (cm->frame_type == KEY_FRAME)
3280 vp8_yv12_copy_frame_ptr(cm->frame_to_show, gld_yv12);
3281 vp8_yv12_copy_frame_ptr(cm->frame_to_show, alt_yv12);
3283 else // For non key frames
3285 // Code to copy between reference buffers
3286 if (cm->copy_buffer_to_arf)
3288 if (cm->copy_buffer_to_arf == 1)
3290 if (cm->refresh_last_frame)
3291 // We copy new_frame here because last and new buffers will already have been swapped if cm->refresh_last_frame is set.
3292 vp8_yv12_copy_frame_ptr(new_yv12, alt_yv12);
3293 else
3294 vp8_yv12_copy_frame_ptr(lst_yv12, alt_yv12);
3296 else if (cm->copy_buffer_to_arf == 2)
3297 vp8_yv12_copy_frame_ptr(gld_yv12, alt_yv12);
3300 if (cm->copy_buffer_to_gf)
3302 if (cm->copy_buffer_to_gf == 1)
3304 if (cm->refresh_last_frame)
3305 // We copy new_frame here because last and new buffers will already have been swapped if cm->refresh_last_frame is set.
3306 vp8_yv12_copy_frame_ptr(new_yv12, gld_yv12);
3307 else
3308 vp8_yv12_copy_frame_ptr(lst_yv12, gld_yv12);
3310 else if (cm->copy_buffer_to_gf == 2)
3311 vp8_yv12_copy_frame_ptr(alt_yv12, gld_yv12);
3317 static void encode_frame_to_data_rate
3319 VP8_COMP *cpi,
3320 unsigned long *size,
3321 unsigned char *dest,
3322 unsigned int *frame_flags
3325 int Q;
3326 int frame_over_shoot_limit;
3327 int frame_under_shoot_limit;
3329 int Loop = FALSE;
3330 int loop_count;
3331 int this_q;
3332 int last_zbin_oq;
3334 int q_low;
3335 int q_high;
3336 int zbin_oq_high;
3337 int zbin_oq_low = 0;
3338 int top_index;
3339 int bottom_index;
3340 VP8_COMMON *cm = &cpi->common;
3341 int active_worst_qchanged = FALSE;
3343 int overshoot_seen = FALSE;
3344 int undershoot_seen = FALSE;
3345 int drop_mark = cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100;
3346 int drop_mark75 = drop_mark * 2 / 3;
3347 int drop_mark50 = drop_mark / 4;
3348 int drop_mark25 = drop_mark / 8;
3351 // Clear down mmx registers to allow floating point in what follows
3352 vp8_clear_system_state();
3354 // Test code for segmentation of gf/arf (0,0)
3355 //segmentation_test_function((VP8_PTR) cpi);
3357 #if CONFIG_REALTIME_ONLY
3358 if(cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3360 if(cpi->force_next_frame_intra)
3362 cm->frame_type = KEY_FRAME; /* delayed intra frame */
3365 cpi->force_next_frame_intra = 0;
3366 #endif
3368 // For an alt ref frame in 2 pass we skip the call to the second pass function that sets the target bandwidth
3369 #if !(CONFIG_REALTIME_ONLY)
3371 if (cpi->pass == 2)
3373 if (cpi->common.refresh_alt_ref_frame)
3375 cpi->per_frame_bandwidth = cpi->gf_bits; // Per frame bit target for the alt ref frame
3376 cpi->target_bandwidth = cpi->gf_bits * cpi->output_frame_rate; // per second target bitrate
3379 else
3380 #endif
3381 cpi->per_frame_bandwidth = (int)(cpi->target_bandwidth / cpi->output_frame_rate);
3383 // Default turn off buffer to buffer copying
3384 cm->copy_buffer_to_gf = 0;
3385 cm->copy_buffer_to_arf = 0;
3387 // Clear zbin over-quant value and mode boost values.
3388 cpi->zbin_over_quant = 0;
3389 cpi->zbin_mode_boost = 0;
3391 // Enable or disable mode based tweaking of the zbin
3392 // For 2 Pass Only used where GF/ARF prediction quality
3393 // is above a threshold
3394 cpi->zbin_mode_boost = 0;
3395 cpi->zbin_mode_boost_enabled = TRUE;
3396 if (cpi->pass == 2)
3398 if ( cpi->gfu_boost <= 400 )
3400 cpi->zbin_mode_boost_enabled = FALSE;
3404 // Current default encoder behaviour for the altref sign bias
3405 if (cpi->source_alt_ref_active)
3406 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
3407 else
3408 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
3410 // Check to see if a key frame is signalled
3411 // For two pass with auto key frame enabled cm->frame_type may already be set, but not for one pass.
3412 if ((cm->current_video_frame == 0) ||
3413 (cm->frame_flags & FRAMEFLAGS_KEY) ||
3414 (cpi->oxcf.auto_key && (cpi->frames_since_key % cpi->key_frame_frequency == 0)))
3416 // Key frame from VFW/auto-keyframe/first frame
3417 cm->frame_type = KEY_FRAME;
3420 // Set default state for segment and mode based loop filter update flags
3421 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
3422 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
3423 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
3425 // Set various flags etc to special state if it is a key frame
3426 if (cm->frame_type == KEY_FRAME)
3428 int i;
3430 // Reset the loop filter deltas and segmentation map
3431 setup_features(cpi);
3433 // If segmentation is enabled force a map update for key frames
3434 if (cpi->mb.e_mbd.segmentation_enabled)
3436 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3437 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3440 // The alternate reference frame cannot be active for a key frame
3441 cpi->source_alt_ref_active = FALSE;
3443 // Reset the RD threshold multipliers to default of * 1 (128)
3444 for (i = 0; i < MAX_MODES; i++)
3446 cpi->rd_thresh_mult[i] = 128;
3450 // Test code for segmentation
3451 //if ( (cm->frame_type == KEY_FRAME) || ((cm->current_video_frame % 2) == 0))
3452 //if ( (cm->current_video_frame % 2) == 0 )
3453 // enable_segmentation((VP8_PTR)cpi);
3454 //else
3455 // disable_segmentation((VP8_PTR)cpi);
3457 #if 0
3458 // Experimental code for lagged compress and one pass
3459 // Initialise one_pass GF frames stats
3460 // Update stats used for GF selection
3461 //if ( cpi->pass == 0 )
3463 cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
3465 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
3466 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
3467 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
3468 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
3469 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
3470 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
3471 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
3472 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
3473 cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
3475 #endif
3477 update_rd_ref_frame_probs(cpi);
3479 if (cpi->drop_frames_allowed)
3481 // The reset to decimation 0 is only done here for one pass.
3482 // Once it is set two pass leaves decimation on till the next kf.
3483 if ((cpi->buffer_level > drop_mark) && (cpi->decimation_factor > 0))
3484 cpi->decimation_factor --;
3486 if (cpi->buffer_level > drop_mark75 && cpi->decimation_factor > 0)
3487 cpi->decimation_factor = 1;
3489 else if (cpi->buffer_level < drop_mark25 && (cpi->decimation_factor == 2 || cpi->decimation_factor == 3))
3491 cpi->decimation_factor = 3;
3493 else if (cpi->buffer_level < drop_mark50 && (cpi->decimation_factor == 1 || cpi->decimation_factor == 2))
3495 cpi->decimation_factor = 2;
3497 else if (cpi->buffer_level < drop_mark75 && (cpi->decimation_factor == 0 || cpi->decimation_factor == 1))
3499 cpi->decimation_factor = 1;
3502 //vpx_log("Encoder: Decimation Factor: %d \n",cpi->decimation_factor);
3505 // The following decimates the frame rate according to a regular pattern (i.e. to 1/2 or 2/3 frame rate)
3506 // This can be used to help prevent buffer under-run in CBR mode. Alternatively it might be desirable in
3507 // some situations to drop frame rate but throw more bits at each frame.
3509 // Note that dropping a key frame can be problematic if spatial resampling is also active
3510 if (cpi->decimation_factor > 0)
3512 switch (cpi->decimation_factor)
3514 case 1:
3515 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 3 / 2;
3516 break;
3517 case 2:
3518 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3519 break;
3520 case 3:
3521 cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3522 break;
3525 // Note that we should not throw out a key frame (especially when spatial resampling is enabled).
3526 if ((cm->frame_type == KEY_FRAME)) // && cpi->oxcf.allow_spatial_resampling )
3528 cpi->decimation_count = cpi->decimation_factor;
3530 else if (cpi->decimation_count > 0)
3532 cpi->decimation_count --;
3533 cpi->bits_off_target += cpi->av_per_frame_bandwidth;
3534 cm->current_video_frame++;
3535 cpi->frames_since_key++;
3537 #if CONFIG_PSNR
3538 cpi->count ++;
3539 #endif
3541 cpi->buffer_level = cpi->bits_off_target;
3543 return;
3545 else
3546 cpi->decimation_count = cpi->decimation_factor;
3549 // Decide how big to make the frame
3550 if (!pick_frame_size(cpi))
3552 cm->current_video_frame++;
3553 cpi->frames_since_key++;
3554 return;
3557 // Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
3558 // This has a knock on effect on active best quality as well.
3559 // For CBR if the buffer reaches its maximum level then we can no longer
3560 // save up bits for later frames so we might as well use them up
3561 // on the current frame.
3562 if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
3563 (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) && cpi->buffered_mode)
3565 int Adjustment = cpi->active_worst_quality / 4; // Max adjustment is 1/4
3567 if (Adjustment)
3569 int buff_lvl_step;
3570 int tmp_lvl = cpi->buffer_level;
3572 if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size)
3574 buff_lvl_step = (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level) / Adjustment;
3576 if (buff_lvl_step)
3578 Adjustment = (cpi->buffer_level - cpi->oxcf.optimal_buffer_level) / buff_lvl_step;
3579 cpi->active_worst_quality -= Adjustment;
3582 else
3584 cpi->active_worst_quality -= Adjustment;
3589 // Set an active best quality and if necessary active worst quality
3590 // There is some odd behaviour for one pass here that needs attention.
3591 if ( (cpi->pass == 2) || (cpi->ni_frames > 150))
3593 vp8_clear_system_state();
3595 Q = cpi->active_worst_quality;
3597 if ( cm->frame_type == KEY_FRAME )
3599 if ( cpi->pass == 2 )
3601 if (cpi->gfu_boost > 600)
3602 cpi->active_best_quality = kf_low_motion_minq[Q];
3603 else
3604 cpi->active_best_quality = kf_high_motion_minq[Q];
3606 // Special case for key frames forced because we have reached
3607 // the maximum key frame interval. Here force the Q to a range
3608 // based on the ambient Q to reduce the risk of popping
3609 if ( cpi->this_key_frame_forced )
3611 if ( cpi->active_best_quality > cpi->avg_frame_qindex * 7/8)
3612 cpi->active_best_quality = cpi->avg_frame_qindex * 7/8;
3613 else if ( cpi->active_best_quality < cpi->avg_frame_qindex >> 2 )
3614 cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
3617 // One pass more conservative
3618 else
3619 cpi->active_best_quality = kf_high_motion_minq[Q];
3622 else if (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame)
3624 // Use the lower of cpi->active_worst_quality and recent
3625 // average Q as basis for GF/ARF Q limit unless last frame was
3626 // a key frame.
3627 if ( (cpi->frames_since_key > 1) &&
3628 (cpi->avg_frame_qindex < cpi->active_worst_quality) )
3630 Q = cpi->avg_frame_qindex;
3632 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3633 (Q < cpi->oxcf.cq_level) )
3635 Q = cpi->oxcf.cq_level;
3639 if ( cpi->pass == 2 )
3641 if ( cpi->gfu_boost > 1000 )
3642 cpi->active_best_quality = gf_low_motion_minq[Q];
3643 else if ( cpi->gfu_boost < 400 )
3644 cpi->active_best_quality = gf_high_motion_minq[Q];
3645 else
3646 cpi->active_best_quality = gf_mid_motion_minq[Q];
3648 // One pass more conservative
3649 else
3650 cpi->active_best_quality = gf_high_motion_minq[Q];
3652 else
3654 cpi->active_best_quality = inter_minq[Q];
3656 // For the constant/constrained quality mode we dont want
3657 // the quality to rise above the cq level.
3658 if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3659 (cpi->active_best_quality < cpi->cq_target_quality) )
3661 // If we are strongly undershooting the target rate in the last
3662 // frames then use the user passed in cq value not the auto
3663 // cq value.
3664 if ( cpi->rolling_actual_bits < cpi->min_frame_bandwidth )
3665 cpi->active_best_quality = cpi->oxcf.cq_level;
3666 else
3667 cpi->active_best_quality = cpi->cq_target_quality;
3671 // If CBR and the buffer is as full then it is reasonable to allow
3672 // higher quality on the frames to prevent bits just going to waste.
3673 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
3675 // Note that the use of >= here elliminates the risk of a devide
3676 // by 0 error in the else if clause
3677 if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size)
3678 cpi->active_best_quality = cpi->best_quality;
3680 else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level)
3682 int Fraction = ((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) / (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level);
3683 int min_qadjustment = ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;
3685 cpi->active_best_quality -= min_qadjustment;
3689 // Make sure constrained quality mode limits are adhered to for the first
3690 // few frames of one pass encodes
3691 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
3693 if ( (cm->frame_type == KEY_FRAME) ||
3694 cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame )
3696 cpi->active_best_quality = cpi->best_quality;
3698 else if (cpi->active_best_quality < cpi->cq_target_quality)
3700 cpi->active_best_quality = cpi->cq_target_quality;
3704 // Clip the active best and worst quality values to limits
3705 if (cpi->active_worst_quality > cpi->worst_quality)
3706 cpi->active_worst_quality = cpi->worst_quality;
3708 if (cpi->active_best_quality < cpi->best_quality)
3709 cpi->active_best_quality = cpi->best_quality;
3710 else if (cpi->active_best_quality > cpi->active_worst_quality)
3711 cpi->active_best_quality = cpi->active_worst_quality;
3713 // Determine initial Q to try
3714 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3715 last_zbin_oq = cpi->zbin_over_quant;
3717 // Set highest allowed value for Zbin over quant
3718 if (cm->frame_type == KEY_FRAME)
3719 zbin_oq_high = 0; //ZBIN_OQ_MAX/16
3720 else if (cm->refresh_alt_ref_frame || (cm->refresh_golden_frame && !cpi->source_alt_ref_active))
3721 zbin_oq_high = 16;
3722 else
3723 zbin_oq_high = ZBIN_OQ_MAX;
3725 // Setup background Q adjustment for error resilliant mode
3726 if (cpi->cyclic_refresh_mode_enabled)
3727 cyclic_background_refresh(cpi, Q, 0);
3729 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3731 // Limit Q range for the adaptive loop.
3732 bottom_index = cpi->active_best_quality;
3733 top_index = cpi->active_worst_quality;
3734 q_low = cpi->active_best_quality;
3735 q_high = cpi->active_worst_quality;
3737 vp8_save_coding_context(cpi);
3739 loop_count = 0;
3742 scale_and_extend_source(cpi->un_scaled_source, cpi);
3743 #if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC
3745 if (cpi->oxcf.noise_sensitivity > 0)
3747 unsigned char *src;
3748 int l = 0;
3750 switch (cpi->oxcf.noise_sensitivity)
3752 case 1:
3753 l = 20;
3754 break;
3755 case 2:
3756 l = 40;
3757 break;
3758 case 3:
3759 l = 60;
3760 break;
3761 case 4:
3762 l = 80;
3763 break;
3764 case 5:
3765 l = 100;
3766 break;
3767 case 6:
3768 l = 150;
3769 break;
3773 if (cm->frame_type == KEY_FRAME)
3775 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0, RTCD(postproc));
3777 else
3779 vp8_de_noise(cpi->Source, cpi->Source, l , 1, 0, RTCD(postproc));
3781 src = cpi->Source->y_buffer;
3783 if (cpi->Source->y_stride < 0)
3785 src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
3790 #endif
3792 #ifdef OUTPUT_YUV_SRC
3793 vp8_write_yuv_frame(cpi->Source);
3794 #endif
3798 vp8_clear_system_state(); //__asm emms;
3801 if(cpi->is_src_frame_alt_ref)
3802 Q = 127;
3805 set_quantizer(cpi, Q);
3806 this_q = Q;
3808 // setup skip prob for costing in mode/mv decision
3809 if (cpi->common.mb_no_coeff_skip)
3811 cpi->prob_skip_false = cpi->base_skip_false_prob[Q];
3813 if (cm->frame_type != KEY_FRAME)
3815 if (cpi->common.refresh_alt_ref_frame)
3817 if (cpi->last_skip_false_probs[2] != 0)
3818 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3821 if(cpi->last_skip_false_probs[2]!=0 && abs(Q- cpi->last_skip_probs_q[2])<=16 )
3822 cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3823 else if (cpi->last_skip_false_probs[2]!=0)
3824 cpi->prob_skip_false = (cpi->last_skip_false_probs[2] + cpi->prob_skip_false ) / 2;
3827 else if (cpi->common.refresh_golden_frame)
3829 if (cpi->last_skip_false_probs[1] != 0)
3830 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3833 if(cpi->last_skip_false_probs[1]!=0 && abs(Q- cpi->last_skip_probs_q[1])<=16 )
3834 cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3835 else if (cpi->last_skip_false_probs[1]!=0)
3836 cpi->prob_skip_false = (cpi->last_skip_false_probs[1] + cpi->prob_skip_false ) / 2;
3839 else
3841 if (cpi->last_skip_false_probs[0] != 0)
3842 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3845 if(cpi->last_skip_false_probs[0]!=0 && abs(Q- cpi->last_skip_probs_q[0])<=16 )
3846 cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3847 else if(cpi->last_skip_false_probs[0]!=0)
3848 cpi->prob_skip_false = (cpi->last_skip_false_probs[0] + cpi->prob_skip_false ) / 2;
3852 //as this is for cost estimate, let's make sure it does not go extreme eitehr way
3853 if (cpi->prob_skip_false < 5)
3854 cpi->prob_skip_false = 5;
3856 if (cpi->prob_skip_false > 250)
3857 cpi->prob_skip_false = 250;
3859 if (cpi->is_src_frame_alt_ref)
3860 cpi->prob_skip_false = 1;
3865 #if 0
3867 if (cpi->pass != 1)
3869 FILE *f = fopen("skip.stt", "a");
3870 fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
3871 fclose(f);
3874 #endif
3878 if (cm->frame_type == KEY_FRAME)
3879 vp8_setup_key_frame(cpi);
3881 // transform / motion compensation build reconstruction frame
3882 vp8_encode_frame(cpi);
3884 cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
3885 cpi->projected_frame_size = (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
3887 vp8_clear_system_state(); //__asm emms;
3889 // Test to see if the stats generated for this frame indicate that we should have coded a key frame
3890 // (assuming that we didn't)!
3891 if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3894 #if CONFIG_REALTIME_ONLY
3896 /* we don't do re-encoding in realtime mode
3897 * if key frame is decided than we force it on next frame */
3898 cpi->force_next_frame_intra = decide_key_frame(cpi);
3900 #else
3901 if (decide_key_frame(cpi))
3903 vp8_calc_auto_iframe_target_size(cpi);
3905 // Reset all our sizing numbers and recode
3906 cm->frame_type = KEY_FRAME;
3908 // Clear the Alt reference frame active flag when we have a key frame
3909 cpi->source_alt_ref_active = FALSE;
3911 // Reset the loop filter deltas and segmentation map
3912 setup_features(cpi);
3914 // If segmentation is enabled force a map update for key frames
3915 if (cpi->mb.e_mbd.segmentation_enabled)
3917 cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3918 cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3921 vp8_restore_coding_context(cpi);
3923 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3925 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3927 // Limit Q range for the adaptive loop.
3928 bottom_index = cpi->active_best_quality;
3929 top_index = cpi->active_worst_quality;
3930 q_low = cpi->active_best_quality;
3931 q_high = cpi->active_worst_quality;
3933 loop_count++;
3934 Loop = TRUE;
3936 resize_key_frame(cpi);
3937 continue;
3939 #endif
3942 vp8_clear_system_state();
3944 if (frame_over_shoot_limit == 0)
3945 frame_over_shoot_limit = 1;
3947 // Are we are overshooting and up against the limit of active max Q.
3948 if (((cpi->pass != 2) || (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
3949 (Q == cpi->active_worst_quality) &&
3950 (cpi->active_worst_quality < cpi->worst_quality) &&
3951 (cpi->projected_frame_size > frame_over_shoot_limit))
3953 int over_size_percent = ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) / frame_over_shoot_limit;
3955 // If so is there any scope for relaxing it
3956 while ((cpi->active_worst_quality < cpi->worst_quality) && (over_size_percent > 0))
3958 cpi->active_worst_quality++;
3959 top_index = cpi->active_worst_quality;
3960 over_size_percent = (int)(over_size_percent * 0.96); // Assume 1 qstep = about 4% on frame size.
3963 // If we have updated the active max Q do not call vp8_update_rate_correction_factors() this loop.
3964 active_worst_qchanged = TRUE;
3966 else
3967 active_worst_qchanged = FALSE;
3969 #if !(CONFIG_REALTIME_ONLY)
3970 // Special case handling for forced key frames
3971 if ( (cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced )
3973 int last_q = Q;
3974 int kf_err = vp8_calc_ss_err(cpi->Source,
3975 &cm->yv12_fb[cm->new_fb_idx],
3976 IF_RTCD(&cpi->rtcd.variance));
3978 // The key frame is not good enough
3979 if ( kf_err > ((cpi->ambient_err * 7) >> 3) )
3981 // Lower q_high
3982 q_high = (Q > q_low) ? (Q - 1) : q_low;
3984 // Adjust Q
3985 Q = (q_high + q_low) >> 1;
3987 // The key frame is much better than the previous frame
3988 else if ( kf_err < (cpi->ambient_err >> 1) )
3990 // Raise q_low
3991 q_low = (Q < q_high) ? (Q + 1) : q_high;
3993 // Adjust Q
3994 Q = (q_high + q_low + 1) >> 1;
3997 // Clamp Q to upper and lower limits:
3998 if (Q > q_high)
3999 Q = q_high;
4000 else if (Q < q_low)
4001 Q = q_low;
4003 Loop = ((Q != last_q)) ? TRUE : FALSE;
4006 // Is the projected frame size out of range and are we allowed to attempt to recode.
4007 else if ( recode_loop_test( cpi,
4008 frame_over_shoot_limit, frame_under_shoot_limit,
4009 Q, top_index, bottom_index ) )
4011 int last_q = Q;
4012 int Retries = 0;
4014 // Frame size out of permitted range:
4015 // Update correction factor & compute new Q to try...
4017 // Frame is too large
4018 if (cpi->projected_frame_size > cpi->this_frame_target)
4020 //if ( cpi->zbin_over_quant == 0 )
4021 q_low = (Q < q_high) ? (Q + 1) : q_high; // Raise Qlow as to at least the current value
4023 if (cpi->zbin_over_quant > 0) // If we are using over quant do the same for zbin_oq_low
4024 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
4026 //if ( undershoot_seen || (Q == MAXQ) )
4027 if (undershoot_seen)
4029 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
4030 if (!active_worst_qchanged)
4031 vp8_update_rate_correction_factors(cpi, 1);
4033 Q = (q_high + q_low + 1) / 2;
4035 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
4036 if (Q < MAXQ)
4037 cpi->zbin_over_quant = 0;
4038 else
4040 zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
4041 cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
4044 else
4046 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
4047 if (!active_worst_qchanged)
4048 vp8_update_rate_correction_factors(cpi, 0);
4050 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4052 while (((Q < q_low) || (cpi->zbin_over_quant < zbin_oq_low)) && (Retries < 10))
4054 vp8_update_rate_correction_factors(cpi, 0);
4055 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4056 Retries ++;
4060 overshoot_seen = TRUE;
4062 // Frame is too small
4063 else
4065 if (cpi->zbin_over_quant == 0)
4066 q_high = (Q > q_low) ? (Q - 1) : q_low; // Lower q_high if not using over quant
4067 else // else lower zbin_oq_high
4068 zbin_oq_high = (cpi->zbin_over_quant > zbin_oq_low) ? (cpi->zbin_over_quant - 1) : zbin_oq_low;
4070 if (overshoot_seen)
4072 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
4073 if (!active_worst_qchanged)
4074 vp8_update_rate_correction_factors(cpi, 1);
4076 Q = (q_high + q_low) / 2;
4078 // Adjust cpi->zbin_over_quant (only allowed when Q is max)
4079 if (Q < MAXQ)
4080 cpi->zbin_over_quant = 0;
4081 else
4082 cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
4084 else
4086 // Update rate_correction_factor unless cpi->active_worst_quality has changed.
4087 if (!active_worst_qchanged)
4088 vp8_update_rate_correction_factors(cpi, 0);
4090 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4092 // Special case reset for qlow for constrained quality.
4093 // This should only trigger where there is very substantial
4094 // undershoot on a frame and the auto cq level is above
4095 // the user passsed in value.
4096 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
4097 (Q < q_low) )
4099 q_low = Q;
4102 while (((Q > q_high) || (cpi->zbin_over_quant > zbin_oq_high)) && (Retries < 10))
4104 vp8_update_rate_correction_factors(cpi, 0);
4105 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4106 Retries ++;
4110 undershoot_seen = TRUE;
4113 // Clamp Q to upper and lower limits:
4114 if (Q > q_high)
4115 Q = q_high;
4116 else if (Q < q_low)
4117 Q = q_low;
4119 // Clamp cpi->zbin_over_quant
4120 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;
4122 //Loop = ((Q != last_q) || (last_zbin_oq != cpi->zbin_over_quant)) ? TRUE : FALSE;
4123 Loop = ((Q != last_q)) ? TRUE : FALSE;
4124 last_zbin_oq = cpi->zbin_over_quant;
4126 else
4127 #endif
4128 Loop = FALSE;
4130 if (cpi->is_src_frame_alt_ref)
4131 Loop = FALSE;
4133 if (Loop == TRUE)
4135 vp8_restore_coding_context(cpi);
4136 loop_count++;
4137 #if CONFIG_PSNR
4138 cpi->tot_recode_hits++;
4139 #endif
4142 while (Loop == TRUE);
4144 #if 0
4145 // Experimental code for lagged and one pass
4146 // Update stats used for one pass GF selection
4149 int frames_so_far;
4150 double frame_intra_error;
4151 double frame_coded_error;
4152 double frame_pcnt_inter;
4153 double frame_pcnt_motion;
4154 double frame_mvr;
4155 double frame_mvr_abs;
4156 double frame_mvc;
4157 double frame_mvc_abs;
4160 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
4161 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
4162 cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
4164 #endif
4166 // Special case code to reduce pulsing when key frames are forced at a
4167 // fixed interval. Note the reconstruction error if it is the frame before
4168 // the force key frame
4169 if ( cpi->next_key_frame_forced && (cpi->frames_to_key == 0) )
4171 cpi->ambient_err = vp8_calc_ss_err(cpi->Source,
4172 &cm->yv12_fb[cm->new_fb_idx],
4173 IF_RTCD(&cpi->rtcd.variance));
4176 // This frame's MVs are saved and will be used in next frame's MV prediction.
4177 // 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.
4178 if(cm->show_frame) //do not save for altref frame
4180 int mb_row;
4181 int mb_col;
4182 MODE_INFO *tmp = cm->mip; //point to beginning of allocated MODE_INFO arrays.
4184 if(cm->frame_type != KEY_FRAME)
4186 for (mb_row = 0; mb_row < cm->mb_rows+1; mb_row ++)
4188 for (mb_col = 0; mb_col < cm->mb_cols+1; mb_col ++)
4190 if(tmp->mbmi.ref_frame != INTRA_FRAME)
4191 cpi->lfmv[mb_col + mb_row*(cm->mode_info_stride+1)].as_int = tmp->mbmi.mv.as_int;
4193 cpi->lf_ref_frame_sign_bias[mb_col + mb_row*(cm->mode_info_stride+1)] = cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
4194 cpi->lf_ref_frame[mb_col + mb_row*(cm->mode_info_stride+1)] = tmp->mbmi.ref_frame;
4195 tmp++;
4201 // Update the GF useage maps.
4202 // This is done after completing the compression of a frame when all modes etc. are finalized but before loop filter
4203 // This is done after completing the compression of a frame when all modes etc. are finalized but before loop filter
4204 vp8_update_gf_useage_maps(cpi, cm, &cpi->mb);
4206 if (cm->frame_type == KEY_FRAME)
4207 cm->refresh_last_frame = 1;
4209 #if 0
4211 FILE *f = fopen("gfactive.stt", "a");
4212 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);
4213 fclose(f);
4215 #endif
4217 // For inter frames the current default behaviour is that when cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
4218 // This is purely an encoder descision at present.
4219 if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame)
4220 cm->copy_buffer_to_arf = 2;
4221 else
4222 cm->copy_buffer_to_arf = 0;
4224 if (cm->refresh_last_frame)
4226 vp8_swap_yv12_buffer(&cm->yv12_fb[cm->lst_fb_idx], &cm->yv12_fb[cm->new_fb_idx]);
4227 cm->frame_to_show = &cm->yv12_fb[cm->lst_fb_idx];
4229 else
4230 cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
4233 #if CONFIG_MULTITHREAD
4234 if (cpi->b_multi_threaded)
4236 sem_post(&cpi->h_event_start_lpf); /* start loopfilter in separate thread */
4238 else
4239 #endif
4241 loopfilter_frame(cpi, cm);
4244 if (cpi->oxcf.error_resilient_mode == 1)
4246 cm->refresh_entropy_probs = 0;
4249 #if CONFIG_MULTITHREAD
4250 /* wait that filter_level is picked so that we can continue with stream packing */
4251 if (cpi->b_multi_threaded)
4252 sem_wait(&cpi->h_event_end_lpf);
4253 #endif
4255 // build the bitstream
4256 vp8_pack_bitstream(cpi, dest, size);
4258 #if CONFIG_MULTITHREAD
4259 /* wait for loopfilter thread done */
4260 if (cpi->b_multi_threaded)
4262 sem_wait(&cpi->h_event_end_lpf);
4264 #endif
4266 /* Move storing frame_type out of the above loop since it is also
4267 * needed in motion search besides loopfilter */
4268 cm->last_frame_type = cm->frame_type;
4270 // Update rate control heuristics
4271 cpi->total_byte_count += (*size);
4272 cpi->projected_frame_size = (*size) << 3;
4274 if (!active_worst_qchanged)
4275 vp8_update_rate_correction_factors(cpi, 2);
4277 cpi->last_q[cm->frame_type] = cm->base_qindex;
4279 if (cm->frame_type == KEY_FRAME)
4281 vp8_adjust_key_frame_context(cpi);
4284 // Keep a record of ambient average Q.
4285 if (cm->frame_type != KEY_FRAME)
4286 cpi->avg_frame_qindex = (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
4288 // Keep a record from which we can calculate the average Q excluding GF updates and key frames
4289 if ((cm->frame_type != KEY_FRAME) && !cm->refresh_golden_frame && !cm->refresh_alt_ref_frame)
4291 cpi->ni_frames++;
4293 // Calculate the average Q for normal inter frames (not key or GFU
4294 // frames).
4295 if ( cpi->pass == 2 )
4297 cpi->ni_tot_qi += Q;
4298 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4300 else
4302 // Damp value for first few frames
4303 if (cpi->ni_frames > 150 )
4305 cpi->ni_tot_qi += Q;
4306 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4308 // For one pass, early in the clip ... average the current frame Q
4309 // value with the worstq entered by the user as a dampening measure
4310 else
4312 cpi->ni_tot_qi += Q;
4313 cpi->ni_av_qi = ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
4316 // If the average Q is higher than what was used in the last frame
4317 // (after going through the recode loop to keep the frame size within range)
4318 // then use the last frame value - 1.
4319 // The -1 is designed to stop Q and hence the data rate, from progressively
4320 // falling away during difficult sections, but at the same time reduce the number of
4321 // itterations around the recode loop.
4322 if (Q > cpi->ni_av_qi)
4323 cpi->ni_av_qi = Q - 1;
4327 #if 0
4329 // If the frame was massively oversize and we are below optimal buffer level drop next frame
4330 if ((cpi->drop_frames_allowed) &&
4331 (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
4332 (cpi->buffer_level < cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100) &&
4333 (cpi->projected_frame_size > (4 * cpi->this_frame_target)))
4335 cpi->drop_frame = TRUE;
4338 #endif
4340 // Set the count for maximum consequative dropped frames based upon the ratio of
4341 // this frame size to the target average per frame bandwidth.
4342 // (cpi->av_per_frame_bandwidth > 0) is just a sanity check to prevent / 0.
4343 if (cpi->drop_frames_allowed && (cpi->av_per_frame_bandwidth > 0))
4345 cpi->max_drop_count = cpi->projected_frame_size / cpi->av_per_frame_bandwidth;
4347 if (cpi->max_drop_count > cpi->max_consec_dropped_frames)
4348 cpi->max_drop_count = cpi->max_consec_dropped_frames;
4351 // Update the buffer level variable.
4352 // Non-viewable frames are a special case and are treated as pure overhead.
4353 if ( !cm->show_frame )
4354 cpi->bits_off_target -= cpi->projected_frame_size;
4355 else
4356 cpi->bits_off_target += cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
4358 // Rolling monitors of whether we are over or underspending used to help regulate min and Max Q in two pass.
4359 cpi->rolling_target_bits = ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
4360 cpi->rolling_actual_bits = ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
4361 cpi->long_rolling_target_bits = ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
4362 cpi->long_rolling_actual_bits = ((cpi->long_rolling_actual_bits * 31) + cpi->projected_frame_size + 16) / 32;
4364 // Actual bits spent
4365 cpi->total_actual_bits += cpi->projected_frame_size;
4367 // Debug stats
4368 cpi->total_target_vs_actual += (cpi->this_frame_target - cpi->projected_frame_size);
4370 cpi->buffer_level = cpi->bits_off_target;
4372 // Update bits left to the kf and gf groups to account for overshoot or undershoot on these frames
4373 if (cm->frame_type == KEY_FRAME)
4375 cpi->kf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4377 if (cpi->kf_group_bits < 0)
4378 cpi->kf_group_bits = 0 ;
4380 else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4382 cpi->gf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4384 if (cpi->gf_group_bits < 0)
4385 cpi->gf_group_bits = 0 ;
4388 if (cm->frame_type != KEY_FRAME)
4390 if (cpi->common.refresh_alt_ref_frame)
4392 cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
4393 cpi->last_skip_probs_q[2] = cm->base_qindex;
4395 else if (cpi->common.refresh_golden_frame)
4397 cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
4398 cpi->last_skip_probs_q[1] = cm->base_qindex;
4400 else
4402 cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
4403 cpi->last_skip_probs_q[0] = cm->base_qindex;
4405 //update the baseline
4406 cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
4411 #if 0 && CONFIG_PSNR
4413 FILE *f = fopen("tmp.stt", "a");
4415 vp8_clear_system_state(); //__asm emms;
4417 if (cpi->total_coded_error_left != 0.0)
4418 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %6ld %6ld"
4419 "%6ld %6ld %6ld %5ld %5ld %5ld %8ld %8.2f %10d %10.3f"
4420 "%10.3f %8ld\n",
4421 cpi->common.current_video_frame, cpi->this_frame_target,
4422 cpi->projected_frame_size,
4423 (cpi->projected_frame_size - cpi->this_frame_target),
4424 (int)cpi->total_target_vs_actual,
4425 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4426 (int)cpi->total_actual_bits, cm->base_qindex,
4427 cpi->active_best_quality, cpi->active_worst_quality,
4428 cpi->ni_av_qi, cpi->cq_target_quality, cpi->zbin_over_quant,
4429 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4430 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4431 cm->frame_type, cpi->gfu_boost,
4432 cpi->est_max_qcorrection_factor, (int)cpi->bits_left,
4433 cpi->total_coded_error_left,
4434 (double)cpi->bits_left / cpi->total_coded_error_left,
4435 cpi->tot_recode_hits);
4436 else
4437 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %6ld %6ld"
4438 "%6ld %6ld %6ld %5ld %5ld %5ld %8ld %8.2f %10d %10.3f"
4439 "%8ld\n",
4440 cpi->common.current_video_frame,
4441 cpi->this_frame_target, cpi->projected_frame_size,
4442 (cpi->projected_frame_size - cpi->this_frame_target),
4443 (int)cpi->total_target_vs_actual,
4444 (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4445 (int)cpi->total_actual_bits, cm->base_qindex,
4446 cpi->active_best_quality, cpi->active_worst_quality,
4447 cpi->ni_av_qi, cpi->cq_target_quality, cpi->zbin_over_quant,
4448 //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4449 cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4450 cm->frame_type, cpi->gfu_boost,
4451 cpi->est_max_qcorrection_factor, (int)cpi->bits_left,
4452 cpi->total_coded_error_left, cpi->tot_recode_hits);
4454 fclose(f);
4457 FILE *fmodes = fopen("Modes.stt", "a");
4458 int i;
4460 fprintf(fmodes, "%6d:%1d:%1d:%1d ",
4461 cpi->common.current_video_frame,
4462 cm->frame_type, cm->refresh_golden_frame,
4463 cm->refresh_alt_ref_frame);
4465 for (i = 0; i < MAX_MODES; i++)
4466 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
4468 fprintf(fmodes, "\n");
4470 fclose(fmodes);
4474 #endif
4476 // If this was a kf or Gf note the Q
4477 if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4478 cm->last_kf_gf_q = cm->base_qindex;
4480 if (cm->refresh_golden_frame == 1)
4481 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
4482 else
4483 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
4485 if (cm->refresh_alt_ref_frame == 1)
4486 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
4487 else
4488 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
4491 if (cm->refresh_last_frame & cm->refresh_golden_frame) // both refreshed
4492 cpi->gold_is_last = 1;
4493 else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4494 cpi->gold_is_last = 0;
4496 if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) // both refreshed
4497 cpi->alt_is_last = 1;
4498 else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) // 1 refreshed but not the other
4499 cpi->alt_is_last = 0;
4501 if (cm->refresh_alt_ref_frame & cm->refresh_golden_frame) // both refreshed
4502 cpi->gold_is_alt = 1;
4503 else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4504 cpi->gold_is_alt = 0;
4506 cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
4508 if (cpi->gold_is_last)
4509 cpi->ref_frame_flags &= ~VP8_GOLD_FLAG;
4511 if (cpi->alt_is_last)
4512 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4514 if (cpi->gold_is_alt)
4515 cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4518 if (cpi->oxcf.error_resilient_mode)
4520 if (cm->frame_type != KEY_FRAME)
4522 // Is this an alternate reference update
4523 if (cm->refresh_alt_ref_frame)
4524 vp8_yv12_copy_frame_ptr(cm->frame_to_show, &cm->yv12_fb[cm->alt_fb_idx]);
4526 if (cm->refresh_golden_frame)
4527 vp8_yv12_copy_frame_ptr(cm->frame_to_show, &cm->yv12_fb[cm->gld_fb_idx]);
4530 else
4532 if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame && (cm->frame_type != KEY_FRAME))
4533 // Update the alternate reference frame and stats as appropriate.
4534 update_alt_ref_frame_and_stats(cpi);
4535 else
4536 // Update the Golden frame and golden frame and stats as appropriate.
4537 update_golden_frame_and_stats(cpi);
4540 if (cm->frame_type == KEY_FRAME)
4542 // Tell the caller that the frame was coded as a key frame
4543 *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
4545 // As this frame is a key frame the next defaults to an inter frame.
4546 cm->frame_type = INTER_FRAME;
4548 cpi->last_frame_percent_intra = 100;
4550 else
4552 *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
4554 cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
4557 // Clear the one shot update flags for segmentation map and mode/ref loop filter deltas.
4558 cpi->mb.e_mbd.update_mb_segmentation_map = 0;
4559 cpi->mb.e_mbd.update_mb_segmentation_data = 0;
4560 cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
4563 // Dont increment frame counters if this was an altref buffer update not a real frame
4564 if (cm->show_frame)
4566 cm->current_video_frame++;
4567 cpi->frames_since_key++;
4570 // reset to normal state now that we are done.
4574 #if 0
4576 char filename[512];
4577 FILE *recon_file;
4578 sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
4579 recon_file = fopen(filename, "wb");
4580 fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
4581 cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
4582 fclose(recon_file);
4584 #endif
4586 // DEBUG
4587 //vp8_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show);
4593 static void check_gf_quality(VP8_COMP *cpi)
4595 VP8_COMMON *cm = &cpi->common;
4596 int gf_active_pct = (100 * cpi->gf_active_count) / (cm->mb_rows * cm->mb_cols);
4597 int gf_ref_usage_pct = (cpi->count_mb_ref_frame_usage[GOLDEN_FRAME] * 100) / (cm->mb_rows * cm->mb_cols);
4598 int last_ref_zz_useage = (cpi->inter_zz_count * 100) / (cm->mb_rows * cm->mb_cols);
4600 // Gf refresh is not currently being signalled
4601 if (cpi->gf_update_recommended == 0)
4603 if (cpi->common.frames_since_golden > 7)
4605 // Low use of gf
4606 if ((gf_active_pct < 10) || ((gf_active_pct + gf_ref_usage_pct) < 15))
4608 // ...but last frame zero zero usage is reasonbable so a new gf might be appropriate
4609 if (last_ref_zz_useage >= 25)
4611 cpi->gf_bad_count ++;
4613 if (cpi->gf_bad_count >= 8) // Check that the condition is stable
4615 cpi->gf_update_recommended = 1;
4616 cpi->gf_bad_count = 0;
4619 else
4620 cpi->gf_bad_count = 0; // Restart count as the background is not stable enough
4622 else
4623 cpi->gf_bad_count = 0; // Gf useage has picked up so reset count
4626 // If the signal is set but has not been read should we cancel it.
4627 else if (last_ref_zz_useage < 15)
4629 cpi->gf_update_recommended = 0;
4630 cpi->gf_bad_count = 0;
4633 #if 0
4635 FILE *f = fopen("gfneeded.stt", "a");
4636 fprintf(f, "%10d %10d %10d %10d %10ld \n",
4637 cm->current_video_frame,
4638 cpi->common.frames_since_golden,
4639 gf_active_pct, gf_ref_usage_pct,
4640 cpi->gf_update_recommended);
4641 fclose(f);
4644 #endif
4647 #if !(CONFIG_REALTIME_ONLY)
4648 static void Pass2Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags)
4651 if (!cpi->common.refresh_alt_ref_frame)
4652 vp8_second_pass(cpi);
4654 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4655 cpi->bits_left -= 8 * *size;
4657 if (!cpi->common.refresh_alt_ref_frame)
4659 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
4660 *cpi->oxcf.two_pass_vbrmin_section / 100);
4661 cpi->bits_left += (long long)(two_pass_min_rate / cpi->oxcf.frame_rate);
4664 #endif
4666 //For ARM NEON, d8-d15 are callee-saved registers, and need to be saved by us.
4667 #if HAVE_ARMV7
4668 extern void vp8_push_neon(INT64 *store);
4669 extern void vp8_pop_neon(INT64 *store);
4670 #endif
4671 int vp8_receive_raw_frame(VP8_PTR ptr, unsigned int frame_flags, YV12_BUFFER_CONFIG *sd, INT64 time_stamp, INT64 end_time)
4673 #if HAVE_ARMV7
4674 INT64 store_reg[8];
4675 #endif
4676 VP8_COMP *cpi = (VP8_COMP *) ptr;
4677 VP8_COMMON *cm = &cpi->common;
4678 struct vpx_usec_timer timer;
4680 if (!cpi)
4681 return -1;
4683 #if HAVE_ARMV7
4684 #if CONFIG_RUNTIME_CPU_DETECT
4685 if (cm->rtcd.flags & HAS_NEON)
4686 #endif
4688 vp8_push_neon(store_reg);
4690 #endif
4692 vpx_usec_timer_start(&timer);
4694 // no more room for frames;
4695 if (cpi->source_buffer_count != 0 && cpi->source_buffer_count >= cpi->oxcf.lag_in_frames)
4697 #if HAVE_ARMV7
4698 #if CONFIG_RUNTIME_CPU_DETECT
4699 if (cm->rtcd.flags & HAS_NEON)
4700 #endif
4702 vp8_pop_neon(store_reg);
4704 #endif
4705 return -1;
4708 //printf("in-cpi->source_buffer_count: %d\n", cpi->source_buffer_count);
4710 cm->clr_type = sd->clrtype;
4712 // make a copy of the frame for use later...
4713 #if !(CONFIG_REALTIME_ONLY)
4715 if (cpi->oxcf.allow_lag)
4717 int which_buffer = cpi->source_encode_index - 1;
4718 SOURCE_SAMPLE *s;
4720 if (which_buffer == -1)
4721 which_buffer = cpi->oxcf.lag_in_frames - 1;
4723 if (cpi->source_buffer_count < cpi->oxcf.lag_in_frames - 1)
4724 which_buffer = cpi->source_buffer_count;
4726 s = &cpi->src_buffer[which_buffer];
4728 s->source_time_stamp = time_stamp;
4729 s->source_end_time_stamp = end_time;
4730 s->source_frame_flags = frame_flags;
4731 vp8_yv12_copy_frame_ptr(sd, &s->source_buffer);
4733 cpi->source_buffer_count ++;
4735 else
4736 #endif
4738 SOURCE_SAMPLE *s;
4739 s = &cpi->src_buffer[0];
4740 s->source_end_time_stamp = end_time;
4741 s->source_time_stamp = time_stamp;
4742 s->source_frame_flags = frame_flags;
4743 #if HAVE_ARMV7
4744 #if CONFIG_RUNTIME_CPU_DETECT
4745 if (cm->rtcd.flags & HAS_NEON)
4746 #endif
4748 vp8_yv12_copy_src_frame_func_neon(sd, &s->source_buffer);
4750 #if CONFIG_RUNTIME_CPU_DETECT
4751 else
4752 #endif
4753 #endif
4754 #if !HAVE_ARMV7 || CONFIG_RUNTIME_CPU_DETECT
4756 vp8_yv12_copy_frame_ptr(sd, &s->source_buffer);
4758 #endif
4759 cpi->source_buffer_count = 1;
4762 vpx_usec_timer_mark(&timer);
4763 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4765 #if HAVE_ARMV7
4766 #if CONFIG_RUNTIME_CPU_DETECT
4767 if (cm->rtcd.flags & HAS_NEON)
4768 #endif
4770 vp8_pop_neon(store_reg);
4772 #endif
4774 return 0;
4776 int vp8_get_compressed_data(VP8_PTR ptr, unsigned int *frame_flags, unsigned long *size, unsigned char *dest, INT64 *time_stamp, INT64 *time_end, int flush)
4778 #if HAVE_ARMV7
4779 INT64 store_reg[8];
4780 #endif
4781 VP8_COMP *cpi = (VP8_COMP *) ptr;
4782 VP8_COMMON *cm = &cpi->common;
4783 struct vpx_usec_timer tsctimer;
4784 struct vpx_usec_timer ticktimer;
4785 struct vpx_usec_timer cmptimer;
4787 if (!cpi)
4788 return -1;
4790 #if HAVE_ARMV7
4791 #if CONFIG_RUNTIME_CPU_DETECT
4792 if (cm->rtcd.flags & HAS_NEON)
4793 #endif
4795 vp8_push_neon(store_reg);
4797 #endif
4799 vpx_usec_timer_start(&cmptimer);
4802 // flush variable tells us that even though we have less than 10 frames
4803 // in our buffer we need to start producing compressed frames.
4804 // Probably because we are at the end of a file....
4805 if ((cpi->source_buffer_count == cpi->oxcf.lag_in_frames && cpi->oxcf.lag_in_frames > 0)
4806 || (!cpi->oxcf.allow_lag && cpi->source_buffer_count > 0)
4807 || (flush && cpi->source_buffer_count > 0))
4810 SOURCE_SAMPLE *s;
4812 s = &cpi->src_buffer[cpi->source_encode_index];
4813 cpi->source_time_stamp = s->source_time_stamp;
4814 cpi->source_end_time_stamp = s->source_end_time_stamp;
4816 #if !(CONFIG_REALTIME_ONLY)
4818 // Should we code an alternate reference frame
4819 if (cpi->oxcf.error_resilient_mode == 0 &&
4820 cpi->oxcf.play_alternate &&
4821 cpi->source_alt_ref_pending &&
4822 (cpi->frames_till_gf_update_due < cpi->source_buffer_count) &&
4823 cpi->oxcf.lag_in_frames != 0)
4825 cpi->last_alt_ref_sei = (cpi->source_encode_index + cpi->frames_till_gf_update_due) % cpi->oxcf.lag_in_frames;
4827 #if VP8_TEMPORAL_ALT_REF
4829 if (cpi->oxcf.arnr_max_frames > 0)
4831 #if 0
4832 // my attempt at a loop that tests the results of strength filter.
4833 int start_frame = cpi->last_alt_ref_sei - 3;
4835 int i, besti = -1, pastin = cpi->oxcf.arnr_strength;
4837 int besterr;
4839 if (start_frame < 0)
4840 start_frame += cpi->oxcf.lag_in_frames;
4842 besterr = calc_low_ss_err(&cpi->src_buffer[cpi->last_alt_ref_sei].source_buffer,
4843 &cpi->src_buffer[start_frame].source_buffer, IF_RTCD(&cpi->rtcd.variance));
4845 for (i = 0; i < 7; i++)
4847 int thiserr;
4848 cpi->oxcf.arnr_strength = i;
4849 vp8_temporal_filter_prepare_c(cpi);
4851 thiserr = calc_low_ss_err(&cpi->alt_ref_buffer.source_buffer,
4852 &cpi->src_buffer[start_frame].source_buffer, IF_RTCD(&cpi->rtcd.variance));
4854 if (10 * thiserr < besterr * 8)
4856 besterr = thiserr;
4857 besti = i;
4861 if (besti != -1)
4863 cpi->oxcf.arnr_strength = besti;
4864 vp8_temporal_filter_prepare_c(cpi);
4865 s = &cpi->alt_ref_buffer;
4867 // FWG not sure if I need to copy this data for the Alt Ref frame
4868 s->source_time_stamp = cpi->src_buffer[cpi->last_alt_ref_sei].source_time_stamp;
4869 s->source_end_time_stamp = cpi->src_buffer[cpi->last_alt_ref_sei].source_end_time_stamp;
4870 s->source_frame_flags = cpi->src_buffer[cpi->last_alt_ref_sei].source_frame_flags;
4872 else
4873 s = &cpi->src_buffer[cpi->last_alt_ref_sei];
4875 #else
4876 vp8_temporal_filter_prepare_c(cpi);
4877 s = &cpi->alt_ref_buffer;
4879 // FWG not sure if I need to copy this data for the Alt Ref frame
4880 s->source_time_stamp = cpi->src_buffer[cpi->last_alt_ref_sei].source_time_stamp;
4881 s->source_end_time_stamp = cpi->src_buffer[cpi->last_alt_ref_sei].source_end_time_stamp;
4882 s->source_frame_flags = cpi->src_buffer[cpi->last_alt_ref_sei].source_frame_flags;
4884 #endif
4886 else
4887 #endif
4888 s = &cpi->src_buffer[cpi->last_alt_ref_sei];
4890 cm->frames_till_alt_ref_frame = cpi->frames_till_gf_update_due;
4891 cm->refresh_alt_ref_frame = 1;
4892 cm->refresh_golden_frame = 0;
4893 cm->refresh_last_frame = 0;
4894 cm->show_frame = 0;
4895 cpi->source_alt_ref_pending = FALSE; // Clear Pending altf Ref flag.
4896 cpi->is_src_frame_alt_ref = 0;
4897 cpi->is_next_src_alt_ref = 0;
4899 else
4900 #endif
4902 cm->show_frame = 1;
4903 #if !(CONFIG_REALTIME_ONLY)
4905 if (cpi->oxcf.allow_lag)
4907 if (cpi->source_encode_index == cpi->last_alt_ref_sei)
4909 cpi->is_src_frame_alt_ref = 1;
4910 cpi->last_alt_ref_sei = -1;
4912 else
4913 cpi->is_src_frame_alt_ref = 0;
4915 cpi->source_encode_index = (cpi->source_encode_index + 1) % cpi->oxcf.lag_in_frames;
4917 if(cpi->source_encode_index == cpi->last_alt_ref_sei)
4918 cpi->is_next_src_alt_ref = 1;
4919 else
4920 cpi->is_next_src_alt_ref = 0;
4923 #endif
4924 cpi->source_buffer_count--;
4927 cpi->un_scaled_source = &s->source_buffer;
4928 cpi->Source = &s->source_buffer;
4929 cpi->source_frame_flags = s->source_frame_flags;
4931 *time_stamp = cpi->source_time_stamp;
4932 *time_end = cpi->source_end_time_stamp;
4934 else
4936 *size = 0;
4937 #if !(CONFIG_REALTIME_ONLY)
4939 if (flush && cpi->pass == 1 && !cpi->first_pass_done)
4941 vp8_end_first_pass(cpi); /* get last stats packet */
4942 cpi->first_pass_done = 1;
4945 #endif
4947 #if HAVE_ARMV7
4948 #if CONFIG_RUNTIME_CPU_DETECT
4949 if (cm->rtcd.flags & HAS_NEON)
4950 #endif
4952 vp8_pop_neon(store_reg);
4954 #endif
4955 return -1;
4958 *frame_flags = cpi->source_frame_flags;
4960 if (cpi->source_time_stamp < cpi->first_time_stamp_ever)
4962 cpi->first_time_stamp_ever = cpi->source_time_stamp;
4963 cpi->last_end_time_stamp_seen = cpi->source_time_stamp;
4966 // adjust frame rates based on timestamps given
4967 if (!cm->refresh_alt_ref_frame)
4969 if (cpi->source_time_stamp == cpi->first_time_stamp_ever)
4971 double this_fps = 10000000.000 / (cpi->source_end_time_stamp - cpi->source_time_stamp);
4973 vp8_new_frame_rate(cpi, this_fps);
4975 else
4977 long long nanosecs = cpi->source_end_time_stamp
4978 - cpi->last_end_time_stamp_seen;
4980 if (nanosecs > 0)
4982 double this_fps = 10000000.000 / nanosecs;
4983 vp8_new_frame_rate(cpi, (7 * cpi->oxcf.frame_rate + this_fps) / 8);
4988 cpi->last_time_stamp_seen = cpi->source_time_stamp;
4989 cpi->last_end_time_stamp_seen = cpi->source_end_time_stamp;
4992 if (cpi->compressor_speed == 2)
4994 check_gf_quality(cpi);
4995 vpx_usec_timer_start(&tsctimer);
4996 vpx_usec_timer_start(&ticktimer);
4999 // start with a 0 size frame
5000 *size = 0;
5002 // Clear down mmx registers
5003 vp8_clear_system_state(); //__asm emms;
5005 cm->frame_type = INTER_FRAME;
5006 cm->frame_flags = *frame_flags;
5008 #if 0
5010 if (cm->refresh_alt_ref_frame)
5012 //cm->refresh_golden_frame = 1;
5013 cm->refresh_golden_frame = 0;
5014 cm->refresh_last_frame = 0;
5016 else
5018 cm->refresh_golden_frame = 0;
5019 cm->refresh_last_frame = 1;
5022 #endif
5024 #if !(CONFIG_REALTIME_ONLY)
5026 if (cpi->pass == 1)
5028 Pass1Encode(cpi, size, dest, frame_flags);
5030 else if (cpi->pass == 2)
5032 Pass2Encode(cpi, size, dest, frame_flags);
5034 else
5035 #endif
5036 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
5038 if (cpi->compressor_speed == 2)
5040 unsigned int duration, duration2;
5041 vpx_usec_timer_mark(&tsctimer);
5042 vpx_usec_timer_mark(&ticktimer);
5044 duration = vpx_usec_timer_elapsed(&ticktimer);
5045 duration2 = (unsigned int)((double)duration / 2);
5047 if (cm->frame_type != KEY_FRAME)
5049 if (cpi->avg_encode_time == 0)
5050 cpi->avg_encode_time = duration;
5051 else
5052 cpi->avg_encode_time = (7 * cpi->avg_encode_time + duration) >> 3;
5055 if (duration2)
5057 //if(*frame_flags!=1)
5060 if (cpi->avg_pick_mode_time == 0)
5061 cpi->avg_pick_mode_time = duration2;
5062 else
5063 cpi->avg_pick_mode_time = (7 * cpi->avg_pick_mode_time + duration2) >> 3;
5069 if (cm->refresh_entropy_probs == 0)
5071 vpx_memcpy(&cm->fc, &cm->lfc, sizeof(cm->fc));
5074 // if its a dropped frame honor the requests on subsequent frames
5075 if (*size > 0)
5078 // return to normal state
5079 cm->refresh_entropy_probs = 1;
5080 cm->refresh_alt_ref_frame = 0;
5081 cm->refresh_golden_frame = 0;
5082 cm->refresh_last_frame = 1;
5083 cm->frame_type = INTER_FRAME;
5087 cpi->ready_for_new_frame = 1;
5089 vpx_usec_timer_mark(&cmptimer);
5090 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
5092 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
5094 generate_psnr_packet(cpi);
5097 #if CONFIG_PSNR
5099 if (cpi->pass != 1)
5101 cpi->bytes += *size;
5103 if (cm->show_frame)
5106 cpi->count ++;
5108 if (cpi->b_calculate_psnr)
5110 double y, u, v;
5111 double ye,ue,ve;
5112 double frame_psnr;
5113 YV12_BUFFER_CONFIG *orig = cpi->Source;
5114 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
5115 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
5116 int y_samples = orig->y_height * orig->y_width ;
5117 int uv_samples = orig->uv_height * orig->uv_width ;
5118 int t_samples = y_samples + 2 * uv_samples;
5119 long long sq_error;
5121 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
5122 recon->y_buffer, recon->y_stride, orig->y_width, orig->y_height,
5123 IF_RTCD(&cpi->rtcd.variance));
5125 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
5126 recon->u_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
5127 IF_RTCD(&cpi->rtcd.variance));
5129 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
5130 recon->v_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
5131 IF_RTCD(&cpi->rtcd.variance));
5133 sq_error = ye + ue + ve;
5135 frame_psnr = vp8_mse2psnr(t_samples, 255.0, sq_error);
5137 cpi->total_y += vp8_mse2psnr(y_samples, 255.0, ye);
5138 cpi->total_u += vp8_mse2psnr(uv_samples, 255.0, ue);
5139 cpi->total_v += vp8_mse2psnr(uv_samples, 255.0, ve);
5140 cpi->total_sq_error += sq_error;
5141 cpi->total += frame_psnr;
5143 double y2, u2, v2, frame_psnr2, frame_ssim2 = 0;
5144 double weight = 0;
5146 vp8_deblock(cm->frame_to_show, &cm->post_proc_buffer, cm->filter_level * 10 / 6, 1, 0, IF_RTCD(&cm->rtcd.postproc));
5147 vp8_clear_system_state();
5149 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
5150 pp->y_buffer, pp->y_stride, orig->y_width, orig->y_height,
5151 IF_RTCD(&cpi->rtcd.variance));
5153 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
5154 pp->u_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
5155 IF_RTCD(&cpi->rtcd.variance));
5157 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
5158 pp->v_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
5159 IF_RTCD(&cpi->rtcd.variance));
5161 sq_error = ye + ue + ve;
5163 frame_psnr2 = vp8_mse2psnr(t_samples, 255.0, sq_error);
5165 cpi->totalp_y += vp8_mse2psnr(y_samples, 255.0, ye);
5166 cpi->totalp_u += vp8_mse2psnr(uv_samples, 255.0, ue);
5167 cpi->totalp_v += vp8_mse2psnr(uv_samples, 255.0, ve);
5168 cpi->total_sq_error2 += sq_error;
5169 cpi->totalp += frame_psnr2;
5171 frame_ssim2 = vp8_calc_ssim(cpi->Source,
5172 &cm->post_proc_buffer, 1, &weight,
5173 IF_RTCD(&cpi->rtcd.variance));
5175 cpi->summed_quality += frame_ssim2 * weight;
5176 cpi->summed_weights += weight;
5181 if (cpi->b_calculate_ssimg)
5183 double y, u, v, frame_all;
5184 frame_all = vp8_calc_ssimg(cpi->Source, cm->frame_to_show, &y, &u, &v);
5185 cpi->total_ssimg_y += y;
5186 cpi->total_ssimg_u += u;
5187 cpi->total_ssimg_v += v;
5188 cpi->total_ssimg_all += frame_all;
5194 #if 0
5196 if (cpi->common.frame_type != 0 && cpi->common.base_qindex == cpi->oxcf.worst_allowed_q)
5198 skiptruecount += cpi->skip_true_count;
5199 skipfalsecount += cpi->skip_false_count;
5202 #endif
5203 #if 0
5205 if (cpi->pass != 1)
5207 FILE *f = fopen("skip.stt", "a");
5208 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);
5210 if (cpi->is_src_frame_alt_ref == 1)
5211 fprintf(f, "skipcount: %4d framesize: %d\n", cpi->skip_true_count , *size);
5213 fclose(f);
5216 #endif
5217 #endif
5219 #if HAVE_ARMV7
5220 #if CONFIG_RUNTIME_CPU_DETECT
5221 if (cm->rtcd.flags & HAS_NEON)
5222 #endif
5224 vp8_pop_neon(store_reg);
5226 #endif
5228 return 0;
5231 int vp8_get_preview_raw_frame(VP8_PTR comp, YV12_BUFFER_CONFIG *dest, vp8_ppflags_t *flags)
5233 VP8_COMP *cpi = (VP8_COMP *) comp;
5235 if (cpi->common.refresh_alt_ref_frame)
5236 return -1;
5237 else
5239 int ret;
5240 #if CONFIG_POSTPROC
5241 ret = vp8_post_proc_frame(&cpi->common, dest, flags);
5242 #else
5244 if (cpi->common.frame_to_show)
5246 *dest = *cpi->common.frame_to_show;
5247 dest->y_width = cpi->common.Width;
5248 dest->y_height = cpi->common.Height;
5249 dest->uv_height = cpi->common.Height / 2;
5250 ret = 0;
5252 else
5254 ret = -1;
5257 #endif //!CONFIG_POSTPROC
5258 vp8_clear_system_state();
5259 return ret;
5263 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])
5265 VP8_COMP *cpi = (VP8_COMP *) comp;
5266 signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
5268 if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
5269 return -1;
5271 if (!map)
5273 disable_segmentation((VP8_PTR)cpi);
5274 return 0;
5277 // Set the segmentation Map
5278 set_segmentation_map((VP8_PTR)cpi, map);
5280 // Activate segmentation.
5281 enable_segmentation((VP8_PTR)cpi);
5283 // Set up the quant segment data
5284 feature_data[MB_LVL_ALT_Q][0] = delta_q[0];
5285 feature_data[MB_LVL_ALT_Q][1] = delta_q[1];
5286 feature_data[MB_LVL_ALT_Q][2] = delta_q[2];
5287 feature_data[MB_LVL_ALT_Q][3] = delta_q[3];
5289 // Set up the loop segment data s
5290 feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
5291 feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
5292 feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
5293 feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
5295 cpi->segment_encode_breakout[0] = threshold[0];
5296 cpi->segment_encode_breakout[1] = threshold[1];
5297 cpi->segment_encode_breakout[2] = threshold[2];
5298 cpi->segment_encode_breakout[3] = threshold[3];
5300 // Initialise the feature data structure
5301 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
5302 set_segment_data((VP8_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
5304 return 0;
5307 int vp8_set_active_map(VP8_PTR comp, unsigned char *map, unsigned int rows, unsigned int cols)
5309 VP8_COMP *cpi = (VP8_COMP *) comp;
5311 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols)
5313 if (map)
5315 vpx_memcpy(cpi->active_map, map, rows * cols);
5316 cpi->active_map_enabled = 1;
5318 else
5319 cpi->active_map_enabled = 0;
5321 return 0;
5323 else
5325 //cpi->active_map_enabled = 0;
5326 return -1 ;
5330 int vp8_set_internal_size(VP8_PTR comp, VPX_SCALING horiz_mode, VPX_SCALING vert_mode)
5332 VP8_COMP *cpi = (VP8_COMP *) comp;
5334 if (horiz_mode <= ONETWO)
5335 cpi->common.horiz_scale = horiz_mode;
5336 else
5337 return -1;
5339 if (vert_mode <= ONETWO)
5340 cpi->common.vert_scale = vert_mode;
5341 else
5342 return -1;
5344 return 0;
5349 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd)
5351 int i, j;
5352 int Total = 0;
5354 unsigned char *src = source->y_buffer;
5355 unsigned char *dst = dest->y_buffer;
5356 (void)rtcd;
5358 // Loop through the Y plane raw and reconstruction data summing (square differences)
5359 for (i = 0; i < source->y_height; i += 16)
5361 for (j = 0; j < source->y_width; j += 16)
5363 unsigned int sse;
5364 Total += VARIANCE_INVOKE(rtcd, mse16x16)(src + j, source->y_stride, dst + j, dest->y_stride, &sse);
5367 src += 16 * source->y_stride;
5368 dst += 16 * dest->y_stride;
5371 return Total;
5375 static int calc_low_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd)
5377 int i, j;
5378 int Total = 0;
5380 unsigned char *src = source->y_buffer;
5381 unsigned char *dst = dest->y_buffer;
5382 (void)rtcd;
5384 // Loop through the Y plane raw and reconstruction data summing (square differences)
5385 for (i = 0; i < source->y_height; i += 16)
5387 for (j = 0; j < source->y_width; j += 16)
5389 unsigned int sse;
5390 VARIANCE_INVOKE(rtcd, mse16x16)(src + j, source->y_stride, dst + j, dest->y_stride, &sse);
5392 if (sse < 8096)
5393 Total += sse;
5396 src += 16 * source->y_stride;
5397 dst += 16 * dest->y_stride;
5400 return Total;
5404 int vp8_get_quantizer(VP8_PTR c)
5406 VP8_COMP *cpi = (VP8_COMP *) c;
5407 return cpi->common.base_qindex;