Fixed bugs in multi-layer code related to changing params
[profile/ivi/libvpx.git] / vp8 / encoder / onyx_if.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
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  */
10
11
12 #include "vpx_config.h"
13 #include "vp8/common/onyxc_int.h"
14 #include "onyx_int.h"
15 #include "vp8/common/systemdependent.h"
16 #include "quantize.h"
17 #include "vp8/common/alloccommon.h"
18 #include "mcomp.h"
19 #include "firstpass.h"
20 #include "psnr.h"
21 #include "vpx_scale/vpxscale.h"
22 #include "vp8/common/extend.h"
23 #include "ratectrl.h"
24 #include "vp8/common/quant_common.h"
25 #include "segmentation.h"
26 #include "vpx_scale/yv12extend.h"
27 #if CONFIG_POSTPROC
28 #include "vp8/common/postproc.h"
29 #endif
30 #include "vpx_mem/vpx_mem.h"
31 #include "vp8/common/swapyv12buffer.h"
32 #include "vp8/common/threading.h"
33 #include "vpx_ports/vpx_timer.h"
34 #include "temporal_filter.h"
35 #if ARCH_ARM
36 #include "vpx_ports/arm.h"
37 #endif
38 #if CONFIG_MULTI_RES_ENCODING
39 #include "mr_dissim.h"
40 #endif
41
42 #include <math.h>
43 #include <stdio.h>
44 #include <limits.h>
45
46 #if CONFIG_RUNTIME_CPU_DETECT
47 #define IF_RTCD(x) (x)
48 #define RTCD(x) &cpi->common.rtcd.x
49 #else
50 #define IF_RTCD(x) NULL
51 #define RTCD(x) NULL
52 #endif
53
54 extern void vp8cx_pick_filter_level_fast(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
55 extern void vp8cx_set_alt_lf_level(VP8_COMP *cpi, int filt_val);
56 extern void vp8cx_pick_filter_level(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
57
58 extern void vp8_dmachine_specific_config(VP8_COMP *cpi);
59 extern void vp8_cmachine_specific_config(VP8_COMP *cpi);
60 extern void vp8_deblock_frame(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *post, int filt_lvl, int low_var_thresh, int flag);
61 extern void print_parms(VP8_CONFIG *ocf, char *filenam);
62 extern unsigned int vp8_get_processor_freq();
63 extern void print_tree_update_probs();
64 extern void vp8cx_create_encoder_threads(VP8_COMP *cpi);
65 extern void vp8cx_remove_encoder_threads(VP8_COMP *cpi);
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
70
71 int vp8_estimate_entropy_savings(VP8_COMP *cpi);
72
73 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd);
74
75 extern void vp8_temporal_filter_prepare_c(VP8_COMP *cpi, int distance);
76
77 static void set_default_lf_deltas(VP8_COMP *cpi);
78
79 extern const int vp8_gf_interval_table[101];
80
81 #if CONFIG_INTERNAL_STATS
82 #include "math.h"
83
84 extern double vp8_calc_ssim
85 (
86     YV12_BUFFER_CONFIG *source,
87     YV12_BUFFER_CONFIG *dest,
88     int lumamask,
89     double *weight,
90     const vp8_variance_rtcd_vtable_t *rtcd
91 );
92
93
94 extern double vp8_calc_ssimg
95 (
96     YV12_BUFFER_CONFIG *source,
97     YV12_BUFFER_CONFIG *dest,
98     double *ssim_y,
99     double *ssim_u,
100     double *ssim_v,
101     const vp8_variance_rtcd_vtable_t *rtcd
102 );
103
104
105 #endif
106
107
108 #ifdef OUTPUT_YUV_SRC
109 FILE *yuv_file;
110 #endif
111
112 #if 0
113 FILE *framepsnr;
114 FILE *kf_list;
115 FILE *keyfile;
116 #endif
117
118 #if 0
119 extern int skip_true_count;
120 extern int skip_false_count;
121 #endif
122
123
124 #ifdef ENTROPY_STATS
125 extern int intra_mode_stats[10][10][10];
126 #endif
127
128 #ifdef SPEEDSTATS
129 unsigned int frames_at_speed[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
130 unsigned int tot_pm = 0;
131 unsigned int cnt_pm = 0;
132 unsigned int tot_ef = 0;
133 unsigned int cnt_ef = 0;
134 #endif
135
136 #ifdef MODE_STATS
137 extern unsigned __int64 Sectionbits[50];
138 extern int y_modes[5]  ;
139 extern int uv_modes[4] ;
140 extern int b_modes[10]  ;
141
142 extern int inter_y_modes[10] ;
143 extern int inter_uv_modes[4] ;
144 extern unsigned int inter_b_modes[15];
145 #endif
146
147 extern void (*vp8_short_fdct4x4)(short *input, short *output, int pitch);
148 extern void (*vp8_short_fdct8x4)(short *input, short *output, int pitch);
149
150 extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
151
152 extern const int qrounding_factors[129];
153 extern const int qzbin_factors[129];
154 extern void vp8cx_init_quantizer(VP8_COMP *cpi);
155 extern const int vp8cx_base_skip_false_prob[128];
156
157 // Tables relating active max Q to active min Q
158 static const int kf_low_motion_minq[QINDEX_RANGE] =
159 {
160     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
161     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
162     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
163     0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
164     3,3,3,3,3,3,4,4,4,5,5,5,5,5,6,6,
165     6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
166     11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
167     16,16,17,17,18,18,18,18,19,20,20,21,21,22,23,23
168 };
169 static const int kf_high_motion_minq[QINDEX_RANGE] =
170 {
171     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
172     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
173     1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,
174     3,3,3,3,4,4,4,4,5,5,5,5,5,5,6,6,
175     6,6,7,7,8,8,8,8,9,9,10,10,10,10,11,11,
176     11,11,12,12,13,13,13,13,14,14,15,15,15,15,16,16,
177     16,16,17,17,18,18,18,18,19,19,20,20,20,20,21,21,
178     21,21,22,22,23,23,24,25,25,26,26,27,28,28,29,30
179 };
180 static const int gf_low_motion_minq[QINDEX_RANGE] =
181 {
182     0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,
183     3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,
184     7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,
185     11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,
186     19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,
187     27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,
188     35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,
189     43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58
190 };
191 static const int gf_mid_motion_minq[QINDEX_RANGE] =
192 {
193     0,0,0,0,1,1,1,1,1,1,2,2,3,3,3,4,
194     4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
195     9,10,10,10,10,11,11,11,12,12,12,12,13,13,13,14,
196     14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,
197     22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,
198     30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,
199     38,39,39,40,40,41,41,42,42,43,43,44,45,46,47,48,
200     49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64
201 };
202 static const int gf_high_motion_minq[QINDEX_RANGE] =
203 {
204     0,0,0,0,1,1,1,1,1,2,2,2,3,3,3,4,
205     4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,
206     9,10,10,10,11,11,12,12,13,13,14,14,15,15,16,16,
207     17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,
208     25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,
209     33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,
210     41,41,42,42,43,44,45,46,47,48,49,50,51,52,53,54,
211     55,56,57,58,59,60,62,64,66,68,70,72,74,76,78,80
212 };
213 static const int inter_minq[QINDEX_RANGE] =
214 {
215     0,0,1,1,2,3,3,4,4,5,6,6,7,8,8,9,
216     9,10,11,11,12,13,13,14,15,15,16,17,17,18,19,20,
217     20,21,22,22,23,24,24,25,26,27,27,28,29,30,30,31,
218     32,33,33,34,35,36,36,37,38,39,39,40,41,42,42,43,
219     44,45,46,46,47,48,49,50,50,51,52,53,54,55,55,56,
220     57,58,59,60,60,61,62,63,64,65,66,67,67,68,69,70,
221     71,72,73,74,75,75,76,77,78,79,80,81,82,83,84,85,
222     86,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
223 };
224
225 void vp8_initialize()
226 {
227     static int init_done = 0;
228
229     if (!init_done)
230     {
231         vp8_scale_machine_specific_config();
232         vp8_initialize_common();
233         //vp8_dmachine_specific_config();
234         vp8_tokenize_initialize();
235
236         init_done = 1;
237     }
238 }
239 #ifdef PACKET_TESTING
240 extern FILE *vpxlogc;
241 #endif
242
243 static void save_layer_context(VP8_COMP *cpi)
244 {
245     LAYER_CONTEXT *lc = &cpi->layer_context[cpi->current_layer];
246
247     // Save layer dependent coding state
248     lc->target_bandwidth                 = cpi->target_bandwidth;
249     //lc->target_bandwidth                 = cpi->oxcf.target_bandwidth;
250     lc->starting_buffer_level            = cpi->oxcf.starting_buffer_level;
251     lc->optimal_buffer_level             = cpi->oxcf.optimal_buffer_level;
252     lc->maximum_buffer_size              = cpi->oxcf.maximum_buffer_size;
253     lc->starting_buffer_level_in_ms      = cpi->oxcf.starting_buffer_level_in_ms;
254     lc->optimal_buffer_level_in_ms       = cpi->oxcf.optimal_buffer_level_in_ms;
255     lc->maximum_buffer_size_in_ms        = cpi->oxcf.maximum_buffer_size_in_ms;
256     lc->buffer_level                     = cpi->buffer_level;
257     lc->bits_off_target                  = cpi->bits_off_target;
258     lc->total_actual_bits                = cpi->total_actual_bits;
259     lc->worst_quality                    = cpi->worst_quality;
260     lc->active_worst_quality             = cpi->active_worst_quality;
261     lc->best_quality                     = cpi->best_quality;
262     lc->active_best_quality              = cpi->active_best_quality;
263     lc->ni_av_qi                         = cpi->ni_av_qi;
264     lc->ni_tot_qi                        = cpi->ni_tot_qi;
265     lc->ni_frames                        = cpi->ni_frames;
266     lc->avg_frame_qindex                 = cpi->avg_frame_qindex;
267     lc->rate_correction_factor           = cpi->rate_correction_factor;
268     lc->key_frame_rate_correction_factor = cpi->key_frame_rate_correction_factor;
269     lc->gf_rate_correction_factor        = cpi->gf_rate_correction_factor;
270     lc->zbin_over_quant                  = cpi->zbin_over_quant;
271     lc->inter_frame_target               = cpi->inter_frame_target;
272     lc->total_byte_count                 = cpi->total_byte_count;
273     lc->filter_level                     = cpi->common.filter_level;
274
275     lc->last_frame_percent_intra         = cpi->last_frame_percent_intra;
276
277     memcpy (lc->count_mb_ref_frame_usage,
278             cpi->count_mb_ref_frame_usage,
279             sizeof(cpi->count_mb_ref_frame_usage));
280 }
281
282 static void restore_layer_context(VP8_COMP *cpi, const int layer)
283 {
284     LAYER_CONTEXT *lc = &cpi->layer_context[layer];
285
286     // Restore layer dependent coding state
287     cpi->current_layer                    = layer;
288     cpi->target_bandwidth                 = lc->target_bandwidth;
289     cpi->oxcf.target_bandwidth            = lc->target_bandwidth;
290     cpi->oxcf.starting_buffer_level       = lc->starting_buffer_level;
291     cpi->oxcf.optimal_buffer_level        = lc->optimal_buffer_level;
292     cpi->oxcf.maximum_buffer_size         = lc->maximum_buffer_size;
293     cpi->oxcf.starting_buffer_level_in_ms = lc->starting_buffer_level_in_ms;
294     cpi->oxcf.optimal_buffer_level_in_ms  = lc->optimal_buffer_level_in_ms;
295     cpi->oxcf.maximum_buffer_size_in_ms   = lc->maximum_buffer_size_in_ms;
296     cpi->buffer_level                     = lc->buffer_level;
297     cpi->bits_off_target                  = lc->bits_off_target;
298     cpi->total_actual_bits                = lc->total_actual_bits;
299     //cpi->worst_quality                    = lc->worst_quality;
300     cpi->active_worst_quality             = lc->active_worst_quality;
301     //cpi->best_quality                     = lc->best_quality;
302     cpi->active_best_quality              = lc->active_best_quality;
303     cpi->ni_av_qi                         = lc->ni_av_qi;
304     cpi->ni_tot_qi                        = lc->ni_tot_qi;
305     cpi->ni_frames                        = lc->ni_frames;
306     cpi->avg_frame_qindex                 = lc->avg_frame_qindex;
307     cpi->rate_correction_factor           = lc->rate_correction_factor;
308     cpi->key_frame_rate_correction_factor = lc->key_frame_rate_correction_factor;
309     cpi->gf_rate_correction_factor        = lc->gf_rate_correction_factor;
310     cpi->zbin_over_quant                  = lc->zbin_over_quant;
311     cpi->inter_frame_target               = lc->inter_frame_target;
312     cpi->total_byte_count                 = lc->total_byte_count;
313     cpi->common.filter_level              = lc->filter_level;
314
315     cpi->last_frame_percent_intra         = lc->last_frame_percent_intra;
316
317     memcpy (cpi->count_mb_ref_frame_usage,
318             lc->count_mb_ref_frame_usage,
319             sizeof(cpi->count_mb_ref_frame_usage));
320 }
321
322 static void setup_features(VP8_COMP *cpi)
323 {
324     // Set up default state for MB feature flags
325     cpi->mb.e_mbd.segmentation_enabled = 0;
326     cpi->mb.e_mbd.update_mb_segmentation_map = 0;
327     cpi->mb.e_mbd.update_mb_segmentation_data = 0;
328     vpx_memset(cpi->mb.e_mbd.mb_segment_tree_probs, 255, sizeof(cpi->mb.e_mbd.mb_segment_tree_probs));
329     vpx_memset(cpi->mb.e_mbd.segment_feature_data, 0, sizeof(cpi->mb.e_mbd.segment_feature_data));
330
331     cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 0;
332     cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
333     vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
334     vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
335     vpx_memset(cpi->mb.e_mbd.last_ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
336     vpx_memset(cpi->mb.e_mbd.last_mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
337
338     set_default_lf_deltas(cpi);
339
340 }
341
342
343 static void dealloc_compressor_data(VP8_COMP *cpi)
344 {
345     vpx_free(cpi->tplist);
346     cpi->tplist = NULL;
347
348     // Delete last frame MV storage buffers
349     vpx_free(cpi->lfmv);
350     cpi->lfmv = 0;
351
352     vpx_free(cpi->lf_ref_frame_sign_bias);
353     cpi->lf_ref_frame_sign_bias = 0;
354
355     vpx_free(cpi->lf_ref_frame);
356     cpi->lf_ref_frame = 0;
357
358     // Delete sementation map
359     vpx_free(cpi->segmentation_map);
360     cpi->segmentation_map = 0;
361
362     vpx_free(cpi->active_map);
363     cpi->active_map = 0;
364
365     vp8_de_alloc_frame_buffers(&cpi->common);
366
367     vp8_yv12_de_alloc_frame_buffer(&cpi->pick_lf_lvl_frame);
368     vp8_yv12_de_alloc_frame_buffer(&cpi->scaled_source);
369 #if VP8_TEMPORAL_ALT_REF
370     vp8_yv12_de_alloc_frame_buffer(&cpi->alt_ref_buffer);
371 #endif
372     vp8_lookahead_destroy(cpi->lookahead);
373
374     vpx_free(cpi->tok);
375     cpi->tok = 0;
376
377     // Structure used to monitor GF usage
378     vpx_free(cpi->gf_active_flags);
379     cpi->gf_active_flags = 0;
380
381     // Activity mask based per mb zbin adjustments
382     vpx_free(cpi->mb_activity_map);
383     cpi->mb_activity_map = 0;
384     vpx_free(cpi->mb_norm_activity_map);
385     cpi->mb_norm_activity_map = 0;
386
387     vpx_free(cpi->mb.pip);
388     cpi->mb.pip = 0;
389 }
390
391 static void enable_segmentation(VP8_COMP *cpi)
392 {
393     // Set the appropriate feature bit
394     cpi->mb.e_mbd.segmentation_enabled = 1;
395     cpi->mb.e_mbd.update_mb_segmentation_map = 1;
396     cpi->mb.e_mbd.update_mb_segmentation_data = 1;
397 }
398 static void disable_segmentation(VP8_COMP *cpi)
399 {
400     // Clear the appropriate feature bit
401     cpi->mb.e_mbd.segmentation_enabled = 0;
402 }
403
404 // Valid values for a segment are 0 to 3
405 // Segmentation map is arrange as [Rows][Columns]
406 static void set_segmentation_map(VP8_COMP *cpi, unsigned char *segmentation_map)
407 {
408     // Copy in the new segmentation map
409     vpx_memcpy(cpi->segmentation_map, segmentation_map, (cpi->common.mb_rows * cpi->common.mb_cols));
410
411     // Signal that the map should be updated.
412     cpi->mb.e_mbd.update_mb_segmentation_map = 1;
413     cpi->mb.e_mbd.update_mb_segmentation_data = 1;
414 }
415
416 // The values given for each segment can be either deltas (from the default value chosen for the frame) or absolute values.
417 //
418 // Valid range for abs values is (0-127 for MB_LVL_ALT_Q) , (0-63 for SEGMENT_ALT_LF)
419 // Valid range for delta values are (+/-127 for MB_LVL_ALT_Q) , (+/-63 for SEGMENT_ALT_LF)
420 //
421 // abs_delta = SEGMENT_DELTADATA (deltas) abs_delta = SEGMENT_ABSDATA (use the absolute values given).
422 //
423 //
424 static void set_segment_data(VP8_COMP *cpi, signed char *feature_data, unsigned char abs_delta)
425 {
426     cpi->mb.e_mbd.mb_segement_abs_delta = abs_delta;
427     vpx_memcpy(cpi->segment_feature_data, feature_data, sizeof(cpi->segment_feature_data));
428 }
429
430
431 static void segmentation_test_function(VP8_COMP *cpi)
432 {
433     unsigned char *seg_map;
434     signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
435
436     // Create a temporary map for segmentation data.
437     CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
438
439     // MB loop to set local segmentation map
440     /*for ( i = 0; i < cpi->common.mb_rows; i++ )
441     {
442         for ( j = 0; j < cpi->common.mb_cols; j++ )
443         {
444             //seg_map[(i*cpi->common.mb_cols) + j] = (j % 2) + ((i%2)* 2);
445             //if ( j < cpi->common.mb_cols/2 )
446
447             // Segment 1 around the edge else 0
448             if ( (i == 0) || (j == 0) || (i == (cpi->common.mb_rows-1)) || (j == (cpi->common.mb_cols-1)) )
449                 seg_map[(i*cpi->common.mb_cols) + j] = 1;
450             //else if ( (i < 2) || (j < 2) || (i > (cpi->common.mb_rows-3)) || (j > (cpi->common.mb_cols-3)) )
451             //  seg_map[(i*cpi->common.mb_cols) + j] = 2;
452             //else if ( (i < 5) || (j < 5) || (i > (cpi->common.mb_rows-6)) || (j > (cpi->common.mb_cols-6)) )
453             //  seg_map[(i*cpi->common.mb_cols) + j] = 3;
454             else
455                 seg_map[(i*cpi->common.mb_cols) + j] = 0;
456         }
457     }*/
458
459     // Set the segmentation Map
460     set_segmentation_map(cpi, seg_map);
461
462     // Activate segmentation.
463     enable_segmentation(cpi);
464
465     // Set up the quant segment data
466     feature_data[MB_LVL_ALT_Q][0] = 0;
467     feature_data[MB_LVL_ALT_Q][1] = 4;
468     feature_data[MB_LVL_ALT_Q][2] = 0;
469     feature_data[MB_LVL_ALT_Q][3] = 0;
470     // Set up the loop segment data
471     feature_data[MB_LVL_ALT_LF][0] = 0;
472     feature_data[MB_LVL_ALT_LF][1] = 0;
473     feature_data[MB_LVL_ALT_LF][2] = 0;
474     feature_data[MB_LVL_ALT_LF][3] = 0;
475
476     // Initialise the feature data structure
477     // SEGMENT_DELTADATA    0, SEGMENT_ABSDATA      1
478     set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
479
480     // Delete sementation map
481         vpx_free(seg_map);
482
483     seg_map = 0;
484
485 }
486
487 // A simple function to cyclically refresh the background at a lower Q
488 static void cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment)
489 {
490     unsigned char *seg_map;
491     signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
492     int i;
493     int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
494     int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
495
496     // Create a temporary map for segmentation data.
497     CHECK_MEM_ERROR(seg_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
498
499     cpi->cyclic_refresh_q = Q;
500
501     for (i = Q; i > 0; i--)
502     {
503         if (vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*(Q + 128)) / 64))
504             //if ( vp8_bits_per_mb[cpi->common.frame_type][i] >= ((vp8_bits_per_mb[cpi->common.frame_type][Q]*((2*Q)+96))/64) )
505         {
506             break;
507         }
508     }
509
510     cpi->cyclic_refresh_q = i;
511
512     // Only update for inter frames
513     if (cpi->common.frame_type != KEY_FRAME)
514     {
515         // Cycle through the macro_block rows
516         // MB loop to set local segmentation map
517         for (i = cpi->cyclic_refresh_mode_index; i < mbs_in_frame; i++)
518         {
519             // If the MB is as a candidate for clean up then mark it for possible boost/refresh (segment 1)
520             // The segment id may get reset to 0 later if the MB gets coded anything other than last frame 0,0
521             // as only (last frame 0,0) MBs are eligable for refresh : that is to say Mbs likely to be background blocks.
522             if (cpi->cyclic_refresh_map[i] == 0)
523             {
524                 seg_map[i] = 1;
525             }
526             else
527             {
528                 seg_map[i] = 0;
529
530                 // Skip blocks that have been refreshed recently anyway.
531                 if (cpi->cyclic_refresh_map[i] < 0)
532                     //cpi->cyclic_refresh_map[i] = cpi->cyclic_refresh_map[i] / 16;
533                     cpi->cyclic_refresh_map[i]++;
534             }
535
536
537             if (block_count > 0)
538                 block_count--;
539             else
540                 break;
541
542         }
543
544         // If we have gone through the frame reset to the start
545         cpi->cyclic_refresh_mode_index = i;
546
547         if (cpi->cyclic_refresh_mode_index >= mbs_in_frame)
548             cpi->cyclic_refresh_mode_index = 0;
549     }
550
551     // Set the segmentation Map
552     set_segmentation_map(cpi, seg_map);
553
554     // Activate segmentation.
555     enable_segmentation(cpi);
556
557     // Set up the quant segment data
558     feature_data[MB_LVL_ALT_Q][0] = 0;
559     feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
560     feature_data[MB_LVL_ALT_Q][2] = 0;
561     feature_data[MB_LVL_ALT_Q][3] = 0;
562
563     // Set up the loop segment data
564     feature_data[MB_LVL_ALT_LF][0] = 0;
565     feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
566     feature_data[MB_LVL_ALT_LF][2] = 0;
567     feature_data[MB_LVL_ALT_LF][3] = 0;
568
569     // Initialise the feature data structure
570     // SEGMENT_DELTADATA    0, SEGMENT_ABSDATA      1
571     set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
572
573     // Delete sementation map
574     vpx_free(seg_map);
575
576     seg_map = 0;
577
578 }
579
580 static void set_default_lf_deltas(VP8_COMP *cpi)
581 {
582     cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 1;
583     cpi->mb.e_mbd.mode_ref_lf_delta_update = 1;
584
585     vpx_memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
586     vpx_memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
587
588     // Test of ref frame deltas
589     cpi->mb.e_mbd.ref_lf_deltas[INTRA_FRAME] = 2;
590     cpi->mb.e_mbd.ref_lf_deltas[LAST_FRAME] = 0;
591     cpi->mb.e_mbd.ref_lf_deltas[GOLDEN_FRAME] = -2;
592     cpi->mb.e_mbd.ref_lf_deltas[ALTREF_FRAME] = -2;
593
594     cpi->mb.e_mbd.mode_lf_deltas[0] = 4;               // BPRED
595     cpi->mb.e_mbd.mode_lf_deltas[1] = -2;              // Zero
596     cpi->mb.e_mbd.mode_lf_deltas[2] = 2;               // New mv
597     cpi->mb.e_mbd.mode_lf_deltas[3] = 4;               // Split mv
598 }
599
600 /* Convenience macros for mapping speed and mode into a continuous
601  * range
602  */
603 #define GOOD(x) (x+1)
604 #define RT(x) (x+7)
605
606 static int speed_map(int speed, int *map)
607 {
608     int res;
609
610     do
611     {
612         res = *map++;
613     } while(speed >= *map++);
614     return res;
615 }
616
617 static int thresh_mult_map_znn[] = {
618     /* map common to zero, nearest, and near */
619     0, GOOD(2), 1500, GOOD(3), 2000, RT(0), 1000, RT(2), 2000, INT_MAX
620 };
621
622 static int thresh_mult_map_vhpred[] = {
623     1000, GOOD(2), 1500, GOOD(3), 2000, RT(0), 1000, RT(1), 2000,
624     RT(7), INT_MAX, INT_MAX
625 };
626
627 static int thresh_mult_map_bpred[] = {
628     2000, GOOD(0), 2500, GOOD(2), 5000, GOOD(3), 7500, RT(0), 2500, RT(1), 5000,
629     RT(6), INT_MAX, INT_MAX
630 };
631
632 static int thresh_mult_map_tm[] = {
633     1000, GOOD(2), 1500, GOOD(3), 2000, RT(0), 0, RT(1), 1000, RT(2), 2000,
634     RT(7), INT_MAX, INT_MAX
635 };
636
637 static int thresh_mult_map_new1[] = {
638     1000, GOOD(2), 2000, RT(0), 2000, INT_MAX
639 };
640
641 static int thresh_mult_map_new2[] = {
642     1000, GOOD(2), 2000, GOOD(3), 2500, GOOD(5), 4000, RT(0), 2000, RT(2), 2500,
643     RT(5), 4000, INT_MAX
644 };
645
646 static int thresh_mult_map_split1[] = {
647     2500, GOOD(0), 1700, GOOD(2), 10000, GOOD(3), 25000, GOOD(4), INT_MAX,
648     RT(0), 5000, RT(1), 10000, RT(2), 25000, RT(3), INT_MAX, INT_MAX
649 };
650
651 static int thresh_mult_map_split2[] = {
652     5000, GOOD(0), 4500, GOOD(2), 20000, GOOD(3), 50000, GOOD(4), INT_MAX,
653     RT(0), 10000, RT(1), 20000, RT(2), 50000, RT(3), INT_MAX, INT_MAX
654 };
655
656 static int mode_check_freq_map_zn2[] = {
657     /* {zero,nearest}{2,3} */
658     0, RT(10), 1<<1, RT(11), 1<<2, RT(12), 1<<3, INT_MAX
659 };
660
661 static int mode_check_freq_map_vhbpred[] = {
662     0, GOOD(5), 2, RT(0), 0, RT(3), 2, RT(5), 4, INT_MAX
663 };
664
665 static int mode_check_freq_map_near2[] = {
666     0, GOOD(5), 2, RT(0), 0, RT(3), 2, RT(10), 1<<2, RT(11), 1<<3, RT(12), 1<<4,
667     INT_MAX
668 };
669
670 static int mode_check_freq_map_new1[] = {
671     0, RT(10), 1<<1, RT(11), 1<<2, RT(12), 1<<3, INT_MAX
672 };
673
674 static int mode_check_freq_map_new2[] = {
675     0, GOOD(5), 4, RT(0), 0, RT(3), 4, RT(10), 1<<3, RT(11), 1<<4, RT(12), 1<<5,
676     INT_MAX
677 };
678
679 static int mode_check_freq_map_split1[] = {
680     0, GOOD(2), 2, GOOD(3), 7, RT(1), 2, RT(2), 7, INT_MAX
681 };
682
683 static int mode_check_freq_map_split2[] = {
684     0, GOOD(1), 2, GOOD(2), 4, GOOD(3), 15, RT(1), 4, RT(2), 15, INT_MAX
685 };
686
687 void vp8_set_speed_features(VP8_COMP *cpi)
688 {
689     SPEED_FEATURES *sf = &cpi->sf;
690     int Mode = cpi->compressor_speed;
691     int Speed = cpi->Speed;
692     int i;
693     VP8_COMMON *cm = &cpi->common;
694     int last_improved_quant = sf->improved_quant;
695     int ref_frames;
696
697     // Initialise default mode frequency sampling variables
698     for (i = 0; i < MAX_MODES; i ++)
699     {
700         cpi->mode_check_freq[i] = 0;
701         cpi->mode_test_hit_counts[i] = 0;
702         cpi->mode_chosen_counts[i] = 0;
703     }
704
705     cpi->mbs_tested_so_far = 0;
706
707     // best quality defaults
708     sf->RD = 1;
709     sf->search_method = NSTEP;
710     sf->improved_quant = 1;
711     sf->improved_dct = 1;
712     sf->auto_filter = 1;
713     sf->recode_loop = 1;
714     sf->quarter_pixel_search = 1;
715     sf->half_pixel_search = 1;
716     sf->iterative_sub_pixel = 1;
717     sf->optimize_coefficients = 1;
718     sf->use_fastquant_for_pick = 0;
719     sf->no_skip_block4x4_search = 1;
720
721     sf->first_step = 0;
722     sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
723     sf->improved_mv_pred = 1;
724
725     // default thresholds to 0
726     for (i = 0; i < MAX_MODES; i++)
727         sf->thresh_mult[i] = 0;
728
729     /* Count enabled references */
730     ref_frames = 1;
731     if (cpi->ref_frame_flags & VP8_LAST_FLAG)
732         ref_frames++;
733     if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
734         ref_frames++;
735     if (cpi->ref_frame_flags & VP8_ALT_FLAG)
736         ref_frames++;
737
738     /* Convert speed to continuous range, with clamping */
739     if (Mode == 0)
740         Speed = 0;
741     else if (Mode == 2)
742         Speed = RT(Speed);
743     else
744     {
745         if (Speed > 5)
746             Speed = 5;
747         Speed = GOOD(Speed);
748     }
749
750     sf->thresh_mult[THR_ZERO1] =
751     sf->thresh_mult[THR_NEAREST1] =
752     sf->thresh_mult[THR_NEAR1] =
753     sf->thresh_mult[THR_DC] = 0; /* always */
754
755     sf->thresh_mult[THR_ZERO2] =
756     sf->thresh_mult[THR_ZERO3] =
757     sf->thresh_mult[THR_NEAREST2] =
758     sf->thresh_mult[THR_NEAREST3] =
759     sf->thresh_mult[THR_NEAR2]  =
760     sf->thresh_mult[THR_NEAR3]  = speed_map(Speed, thresh_mult_map_znn);
761
762     sf->thresh_mult[THR_V_PRED] =
763     sf->thresh_mult[THR_H_PRED] = speed_map(Speed, thresh_mult_map_vhpred);
764     sf->thresh_mult[THR_B_PRED] = speed_map(Speed, thresh_mult_map_bpred);
765     sf->thresh_mult[THR_TM]     = speed_map(Speed, thresh_mult_map_tm);
766     sf->thresh_mult[THR_NEW1]   = speed_map(Speed, thresh_mult_map_new1);
767     sf->thresh_mult[THR_NEW2]   =
768     sf->thresh_mult[THR_NEW3]   = speed_map(Speed, thresh_mult_map_new2);
769     sf->thresh_mult[THR_SPLIT1] = speed_map(Speed, thresh_mult_map_split1);
770     sf->thresh_mult[THR_SPLIT2] =
771     sf->thresh_mult[THR_SPLIT3] = speed_map(Speed, thresh_mult_map_split2);
772
773     cpi->mode_check_freq[THR_ZERO1] =
774     cpi->mode_check_freq[THR_NEAREST1] =
775     cpi->mode_check_freq[THR_NEAR1] =
776     cpi->mode_check_freq[THR_TM]     =
777     cpi->mode_check_freq[THR_DC] = 0; /* always */
778
779     cpi->mode_check_freq[THR_ZERO2] =
780     cpi->mode_check_freq[THR_ZERO3] =
781     cpi->mode_check_freq[THR_NEAREST2] =
782     cpi->mode_check_freq[THR_NEAREST3] = speed_map(Speed,
783                                                    mode_check_freq_map_zn2);
784
785     cpi->mode_check_freq[THR_NEAR2]  =
786     cpi->mode_check_freq[THR_NEAR3]  = speed_map(Speed,
787                                                  mode_check_freq_map_near2);
788
789     cpi->mode_check_freq[THR_V_PRED] =
790     cpi->mode_check_freq[THR_H_PRED] =
791     cpi->mode_check_freq[THR_B_PRED] = speed_map(Speed,
792                                                  mode_check_freq_map_vhbpred);
793     cpi->mode_check_freq[THR_NEW1]   = speed_map(Speed,
794                                                  mode_check_freq_map_new1);
795     cpi->mode_check_freq[THR_NEW2]   =
796     cpi->mode_check_freq[THR_NEW3]   = speed_map(Speed,
797                                                  mode_check_freq_map_new2);
798     cpi->mode_check_freq[THR_SPLIT1] = speed_map(Speed,
799                                                  mode_check_freq_map_split1);
800     cpi->mode_check_freq[THR_SPLIT2] =
801     cpi->mode_check_freq[THR_SPLIT3] = speed_map(Speed,
802                                                  mode_check_freq_map_split2);
803     Speed = cpi->Speed;
804     switch (Mode)
805     {
806 #if !(CONFIG_REALTIME_ONLY)
807     case 0: // best quality mode
808         sf->first_step = 0;
809         sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
810         break;
811     case 1:
812     case 3:
813         if (Speed > 0)
814         {
815             /* Disable coefficient optimization above speed 0 */
816             sf->optimize_coefficients = 0;
817             sf->use_fastquant_for_pick = 1;
818             sf->no_skip_block4x4_search = 0;
819
820             sf->first_step = 1;
821         }
822
823         if (Speed > 2)
824         {
825             sf->improved_quant = 0;
826             sf->improved_dct = 0;
827
828             // Only do recode loop on key frames, golden frames and
829             // alt ref frames
830             sf->recode_loop = 2;
831
832         }
833
834         if (Speed > 3)
835         {
836             sf->auto_filter = 1;
837             sf->recode_loop = 0; // recode loop off
838             sf->RD = 0;         // Turn rd off
839
840         }
841
842         if (Speed > 4)
843         {
844             sf->auto_filter = 0;                     // Faster selection of loop filter
845         }
846
847         break;
848 #endif
849     case 2:
850         sf->optimize_coefficients = 0;
851         sf->recode_loop = 0;
852         sf->auto_filter = 1;
853         sf->iterative_sub_pixel = 1;
854         sf->search_method = NSTEP;
855
856         if (Speed > 0)
857         {
858             sf->improved_quant = 0;
859             sf->improved_dct = 0;
860
861             sf->use_fastquant_for_pick = 1;
862             sf->no_skip_block4x4_search = 0;
863             sf->first_step = 1;
864         }
865
866         if (Speed > 2)
867             sf->auto_filter = 0;                     // Faster selection of loop filter
868
869         if (Speed > 3)
870         {
871             sf->RD = 0;
872             sf->auto_filter = 1;
873         }
874
875         if (Speed > 4)
876         {
877             sf->auto_filter = 0;                     // Faster selection of loop filter
878             sf->search_method = HEX;
879             sf->iterative_sub_pixel = 0;
880         }
881
882         if (Speed > 6)
883         {
884             unsigned int sum = 0;
885             unsigned int total_mbs = cm->MBs;
886             int i, thresh;
887             unsigned int total_skip;
888
889             int min = 2000;
890
891             if (cpi->oxcf.encode_breakout > 2000)
892                 min = cpi->oxcf.encode_breakout;
893
894             min >>= 7;
895
896             for (i = 0; i < min; i++)
897             {
898                 sum += cpi->error_bins[i];
899             }
900
901             total_skip = sum;
902             sum = 0;
903
904             // i starts from 2 to make sure thresh started from 2048
905             for (; i < 1024; i++)
906             {
907                 sum += cpi->error_bins[i];
908
909                 if (10 * sum >= (unsigned int)(cpi->Speed - 6)*(total_mbs - total_skip))
910                     break;
911             }
912
913             i--;
914             thresh = (i << 7);
915
916             if (thresh < 2000)
917                 thresh = 2000;
918
919             if (ref_frames > 1)
920             {
921                 sf->thresh_mult[THR_NEW1 ] = thresh;
922                 sf->thresh_mult[THR_NEAREST1  ] = thresh >> 1;
923                 sf->thresh_mult[THR_NEAR1     ] = thresh >> 1;
924             }
925
926             if (ref_frames > 2)
927             {
928                 sf->thresh_mult[THR_NEW2] = thresh << 1;
929                 sf->thresh_mult[THR_NEAREST2 ] = thresh;
930                 sf->thresh_mult[THR_NEAR2    ] = thresh;
931             }
932
933             if (ref_frames > 3)
934             {
935                 sf->thresh_mult[THR_NEW3] = thresh << 1;
936                 sf->thresh_mult[THR_NEAREST3 ] = thresh;
937                 sf->thresh_mult[THR_NEAR3    ] = thresh;
938             }
939
940             sf->improved_mv_pred = 0;
941         }
942
943         if (Speed > 8)
944             sf->quarter_pixel_search = 0;
945
946         if(cm->version == 0)
947         {
948             cm->filter_type = NORMAL_LOOPFILTER;
949
950             if (Speed >= 14)
951                 cm->filter_type = SIMPLE_LOOPFILTER;
952         }
953         else
954         {
955             cm->filter_type = SIMPLE_LOOPFILTER;
956         }
957
958         // This has a big hit on quality. Last resort
959         if (Speed >= 15)
960             sf->half_pixel_search = 0;
961
962         vpx_memset(cpi->error_bins, 0, sizeof(cpi->error_bins));
963
964     }; /* switch */
965
966     // Slow quant, dct and trellis not worthwhile for first pass
967     // so make sure they are always turned off.
968     if ( cpi->pass == 1 )
969     {
970         sf->improved_quant = 0;
971         sf->optimize_coefficients = 0;
972         sf->improved_dct = 0;
973     }
974
975     if (cpi->sf.search_method == NSTEP)
976     {
977         vp8_init3smotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
978     }
979     else if (cpi->sf.search_method == DIAMOND)
980     {
981         vp8_init_dsmotion_compensation(&cpi->mb, cm->yv12_fb[cm->lst_fb_idx].y_stride);
982     }
983
984     if (cpi->sf.improved_dct)
985     {
986         cpi->mb.vp8_short_fdct8x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short8x4);
987         cpi->mb.vp8_short_fdct4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, short4x4);
988     }
989     else
990     {
991         cpi->mb.vp8_short_fdct8x4   = FDCT_INVOKE(&cpi->rtcd.fdct, fast8x4);
992         cpi->mb.vp8_short_fdct4x4   = FDCT_INVOKE(&cpi->rtcd.fdct, fast4x4);
993     }
994
995     cpi->mb.short_walsh4x4 = FDCT_INVOKE(&cpi->rtcd.fdct, walsh_short4x4);
996
997     if (cpi->sf.improved_quant)
998     {
999         cpi->mb.quantize_b      = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1000                                                   quantb);
1001         cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1002                                                   quantb_pair);
1003     }
1004     else
1005     {
1006         cpi->mb.quantize_b      = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1007                                                   fastquantb);
1008         cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1009                                                   fastquantb_pair);
1010     }
1011     if (cpi->sf.improved_quant != last_improved_quant)
1012         vp8cx_init_quantizer(cpi);
1013
1014 #if CONFIG_RUNTIME_CPU_DETECT
1015     cpi->mb.e_mbd.rtcd = &cpi->common.rtcd;
1016 #endif
1017
1018     if (cpi->sf.iterative_sub_pixel == 1)
1019     {
1020         cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step_iteratively;
1021     }
1022     else if (cpi->sf.quarter_pixel_search)
1023     {
1024         cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step;
1025     }
1026     else if (cpi->sf.half_pixel_search)
1027     {
1028         cpi->find_fractional_mv_step = vp8_find_best_half_pixel_step;
1029     }
1030     else
1031     {
1032         cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1033     }
1034
1035     if (cpi->sf.optimize_coefficients == 1 && cpi->pass!=1)
1036         cpi->mb.optimize = 1;
1037     else
1038         cpi->mb.optimize = 0;
1039
1040     if (cpi->common.full_pixel)
1041         cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1042
1043 #ifdef SPEEDSTATS
1044     frames_at_speed[cpi->Speed]++;
1045 #endif
1046 }
1047 #undef GOOD
1048 #undef RT
1049
1050 static void alloc_raw_frame_buffers(VP8_COMP *cpi)
1051 {
1052     int width = (cpi->oxcf.Width + 15) & ~15;
1053     int height = (cpi->oxcf.Height + 15) & ~15;
1054
1055     cpi->lookahead = vp8_lookahead_init(cpi->oxcf.Width, cpi->oxcf.Height,
1056                                         cpi->oxcf.lag_in_frames);
1057     if(!cpi->lookahead)
1058         vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1059                            "Failed to allocate lag buffers");
1060
1061 #if VP8_TEMPORAL_ALT_REF
1062
1063     if (vp8_yv12_alloc_frame_buffer(&cpi->alt_ref_buffer,
1064                                     width, height, VP8BORDERINPIXELS))
1065         vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1066                            "Failed to allocate altref buffer");
1067
1068 #endif
1069 }
1070
1071 static int vp8_alloc_partition_data(VP8_COMP *cpi)
1072 {
1073         vpx_free(cpi->mb.pip);
1074
1075     cpi->mb.pip = vpx_calloc((cpi->common.mb_cols + 1) *
1076                                 (cpi->common.mb_rows + 1),
1077                                 sizeof(PARTITION_INFO));
1078     if(!cpi->mb.pip)
1079         return 1;
1080
1081     cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
1082
1083     return 0;
1084 }
1085
1086 void vp8_alloc_compressor_data(VP8_COMP *cpi)
1087 {
1088     VP8_COMMON *cm = & cpi->common;
1089
1090     int width = cm->Width;
1091     int height = cm->Height;
1092
1093     if (vp8_alloc_frame_buffers(cm, width, height))
1094         vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1095                            "Failed to allocate frame buffers");
1096
1097     if (vp8_alloc_partition_data(cpi))
1098         vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1099                            "Failed to allocate partition data");
1100
1101
1102     if ((width & 0xf) != 0)
1103         width += 16 - (width & 0xf);
1104
1105     if ((height & 0xf) != 0)
1106         height += 16 - (height & 0xf);
1107
1108
1109     if (vp8_yv12_alloc_frame_buffer(&cpi->pick_lf_lvl_frame,
1110                                     width, height, VP8BORDERINPIXELS))
1111         vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1112                            "Failed to allocate last frame buffer");
1113
1114     if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source,
1115                                     width, height, VP8BORDERINPIXELS))
1116         vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1117                            "Failed to allocate scaled source buffer");
1118
1119
1120         vpx_free(cpi->tok);
1121
1122     {
1123         unsigned int tokens = cm->mb_rows * cm->mb_cols * 24 * 16;
1124
1125         CHECK_MEM_ERROR(cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
1126     }
1127
1128     // Data used for real time vc mode to see if gf needs refreshing
1129     cpi->inter_zz_count = 0;
1130     cpi->gf_bad_count = 0;
1131     cpi->gf_update_recommended = 0;
1132
1133
1134     // Structures used to minitor GF usage
1135     vpx_free(cpi->gf_active_flags);
1136     CHECK_MEM_ERROR(cpi->gf_active_flags,
1137                     vpx_calloc(1, cm->mb_rows * cm->mb_cols));
1138     cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
1139
1140     vpx_free(cpi->mb_activity_map);
1141     CHECK_MEM_ERROR(cpi->mb_activity_map,
1142                     vpx_calloc(sizeof(unsigned int),
1143                     cm->mb_rows * cm->mb_cols));
1144
1145     vpx_free(cpi->mb_norm_activity_map);
1146     CHECK_MEM_ERROR(cpi->mb_norm_activity_map,
1147                     vpx_calloc(sizeof(unsigned int),
1148                     cm->mb_rows * cm->mb_cols));
1149
1150 #if CONFIG_MULTITHREAD
1151     if (width < 640)
1152         cpi->mt_sync_range = 1;
1153     else if (width <= 1280)
1154         cpi->mt_sync_range = 4;
1155     else if (width <= 2560)
1156         cpi->mt_sync_range = 8;
1157     else
1158         cpi->mt_sync_range = 16;
1159 #endif
1160
1161     vpx_free(cpi->tplist);
1162
1163     CHECK_MEM_ERROR(cpi->tplist, vpx_malloc(sizeof(TOKENLIST) * cpi->common.mb_rows));
1164 }
1165
1166
1167 // Quant MOD
1168 static const int q_trans[] =
1169 {
1170     0,   1,  2,  3,  4,  5,  7,  8,
1171     9,  10, 12, 13, 15, 17, 18, 19,
1172     20,  21, 23, 24, 25, 26, 27, 28,
1173     29,  30, 31, 33, 35, 37, 39, 41,
1174     43,  45, 47, 49, 51, 53, 55, 57,
1175     59,  61, 64, 67, 70, 73, 76, 79,
1176     82,  85, 88, 91, 94, 97, 100, 103,
1177     106, 109, 112, 115, 118, 121, 124, 127,
1178 };
1179
1180 int vp8_reverse_trans(int x)
1181 {
1182     int i;
1183
1184     for (i = 0; i < 64; i++)
1185         if (q_trans[i] >= x)
1186             return i;
1187
1188     return 63;
1189 };
1190 void vp8_new_frame_rate(VP8_COMP *cpi, double framerate)
1191 {
1192     if(framerate < .1)
1193         framerate = 30;
1194
1195     cpi->frame_rate             = framerate;
1196     cpi->output_frame_rate      = framerate;
1197     cpi->per_frame_bandwidth    = (int)(cpi->oxcf.target_bandwidth /
1198                                   cpi->output_frame_rate);
1199     cpi->av_per_frame_bandwidth = cpi->per_frame_bandwidth;
1200     cpi->min_frame_bandwidth    = (int)(cpi->av_per_frame_bandwidth *
1201                                   cpi->oxcf.two_pass_vbrmin_section / 100);
1202
1203     // Set Maximum gf/arf interval
1204     cpi->max_gf_interval = ((int)(cpi->output_frame_rate / 2.0) + 2);
1205
1206     if(cpi->max_gf_interval < 12)
1207         cpi->max_gf_interval = 12;
1208
1209     // Extended interval for genuinely static scenes
1210     cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1211
1212      // Special conditions when altr ref frame enabled in lagged compress mode
1213     if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames)
1214     {
1215         if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1216             cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1217
1218         if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1219             cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1220     }
1221
1222     if ( cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval )
1223         cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1224 }
1225
1226
1227 static int
1228 rescale(int val, int num, int denom)
1229 {
1230     int64_t llnum = num;
1231     int64_t llden = denom;
1232     int64_t llval = val;
1233
1234     return llval * llnum / llden;
1235 }
1236
1237
1238 static void init_config(VP8_COMP *cpi, VP8_CONFIG *oxcf)
1239 {
1240     VP8_COMMON *cm = &cpi->common;
1241
1242     cpi->oxcf = *oxcf;
1243
1244     cpi->auto_gold = 1;
1245     cpi->auto_adjust_gold_quantizer = 1;
1246     cpi->goldfreq = 7;
1247
1248     cm->version = oxcf->Version;
1249     vp8_setup_version(cm);
1250
1251     /* frame rate is not available on the first frame, as it's derived from
1252      * the observed timestamps. The actual value used here doesn't matter
1253      * too much, as it will adapt quickly. If the reciprocal of the timebase
1254      * seems like a reasonable framerate, then use that as a guess, otherwise
1255      * use 30.
1256      */
1257     cpi->frame_rate = (double)(oxcf->timebase.den) /
1258                       (double)(oxcf->timebase.num);
1259
1260     if (cpi->frame_rate > 180)
1261         cpi->frame_rate = 30;
1262
1263     cpi->ref_frame_rate = cpi->frame_rate;
1264
1265     // change includes all joint functionality
1266     vp8_change_config(cpi, oxcf);
1267
1268     // Initialize active best and worst q and average q values.
1269     cpi->active_worst_quality         = cpi->oxcf.worst_allowed_q;
1270     cpi->active_best_quality          = cpi->oxcf.best_allowed_q;
1271     cpi->avg_frame_qindex             = cpi->oxcf.worst_allowed_q;
1272
1273     // Initialise the starting buffer levels
1274     cpi->buffer_level                 = cpi->oxcf.starting_buffer_level;
1275     cpi->bits_off_target              = cpi->oxcf.starting_buffer_level;
1276
1277     cpi->rolling_target_bits          = cpi->av_per_frame_bandwidth;
1278     cpi->rolling_actual_bits          = cpi->av_per_frame_bandwidth;
1279     cpi->long_rolling_target_bits     = cpi->av_per_frame_bandwidth;
1280     cpi->long_rolling_actual_bits     = cpi->av_per_frame_bandwidth;
1281
1282     cpi->total_actual_bits            = 0;
1283     cpi->total_target_vs_actual       = 0;
1284
1285     // Temporal scalabilty
1286     if (cpi->oxcf.number_of_layers > 1)
1287     {
1288         unsigned int i;
1289         double prev_layer_frame_rate=0;
1290
1291         for (i=0; i<cpi->oxcf.number_of_layers; i++)
1292         {
1293             LAYER_CONTEXT *lc = &cpi->layer_context[i];
1294
1295             // Layer configuration
1296             lc->frame_rate =
1297                         cpi->output_frame_rate / cpi->oxcf.rate_decimator[i];
1298             lc->target_bandwidth = cpi->oxcf.target_bitrate[i] * 1000;
1299
1300             lc->starting_buffer_level_in_ms = oxcf->starting_buffer_level;
1301             lc->optimal_buffer_level_in_ms  = oxcf->optimal_buffer_level;
1302             lc->maximum_buffer_size_in_ms   = oxcf->maximum_buffer_size;
1303
1304             lc->starting_buffer_level =
1305               rescale(oxcf->starting_buffer_level,
1306                           lc->target_bandwidth, 1000);
1307
1308             if (oxcf->optimal_buffer_level == 0)
1309                 lc->optimal_buffer_level = lc->target_bandwidth / 8;
1310             else
1311                 lc->optimal_buffer_level =
1312                   rescale(oxcf->optimal_buffer_level,
1313                           lc->target_bandwidth, 1000);
1314
1315             if (oxcf->maximum_buffer_size == 0)
1316                 lc->maximum_buffer_size = lc->target_bandwidth / 8;
1317             else
1318                 lc->maximum_buffer_size =
1319                   rescale(oxcf->maximum_buffer_size,
1320                           lc->target_bandwidth, 1000);
1321
1322             // Work out the average size of a frame within this layer
1323             if (i > 0)
1324                 lc->avg_frame_size_for_layer = (cpi->oxcf.target_bitrate[i] -
1325                     cpi->oxcf.target_bitrate[i-1]) * 1000 /
1326                     (lc->frame_rate - prev_layer_frame_rate);
1327
1328             lc->active_worst_quality         = cpi->oxcf.worst_allowed_q;
1329             lc->active_best_quality          = cpi->oxcf.best_allowed_q;
1330             lc->avg_frame_qindex             = cpi->oxcf.worst_allowed_q;
1331
1332             lc->buffer_level                 = lc->starting_buffer_level;
1333             lc->bits_off_target              = lc->starting_buffer_level;
1334
1335             lc->total_actual_bits                 = 0;
1336             lc->ni_av_qi                          = 0;
1337             lc->ni_tot_qi                         = 0;
1338             lc->ni_frames                         = 0;
1339             lc->rate_correction_factor            = 1.0;
1340             lc->key_frame_rate_correction_factor  = 1.0;
1341             lc->gf_rate_correction_factor         = 1.0;
1342             lc->inter_frame_target                = 0.0;
1343
1344             prev_layer_frame_rate = lc->frame_rate;
1345         }
1346     }
1347
1348 #if VP8_TEMPORAL_ALT_REF
1349     {
1350         int i;
1351
1352         cpi->fixed_divide[0] = 0;
1353
1354         for (i = 1; i < 512; i++)
1355             cpi->fixed_divide[i] = 0x80000 / i;
1356     }
1357 #endif
1358 }
1359
1360 void update_layer_contexts (VP8_COMP *cpi)
1361 {
1362     VP8_CONFIG *oxcf = &cpi->oxcf;
1363
1364     /* Update snapshots of the layer contexts to reflect new parameters */
1365     if (oxcf->number_of_layers > 1)
1366     {
1367         unsigned int i;
1368         double prev_layer_frame_rate=0;
1369
1370         for (i=0; i<oxcf->number_of_layers; i++)
1371         {
1372             LAYER_CONTEXT *lc = &cpi->layer_context[i];
1373
1374             lc->frame_rate =
1375                 cpi->ref_frame_rate / oxcf->rate_decimator[i];
1376             lc->target_bandwidth = oxcf->target_bitrate[i] * 1000;
1377
1378             lc->starting_buffer_level = rescale(
1379                           oxcf->starting_buffer_level_in_ms,
1380                           lc->target_bandwidth, 1000);
1381
1382             if (oxcf->optimal_buffer_level == 0)
1383                 lc->optimal_buffer_level = lc->target_bandwidth / 8;
1384             else
1385                 lc->optimal_buffer_level = rescale(
1386                           oxcf->optimal_buffer_level_in_ms,
1387                           lc->target_bandwidth, 1000);
1388
1389             if (oxcf->maximum_buffer_size == 0)
1390                 lc->maximum_buffer_size = lc->target_bandwidth / 8;
1391             else
1392                 lc->maximum_buffer_size = rescale(
1393                           oxcf->maximum_buffer_size_in_ms,
1394                           lc->target_bandwidth, 1000);
1395
1396             // Work out the average size of a frame within this layer
1397             if (i > 0)
1398                 lc->avg_frame_size_for_layer = (oxcf->target_bitrate[i] -
1399                     oxcf->target_bitrate[i-1]) * 1000 /
1400                     (lc->frame_rate - prev_layer_frame_rate);
1401
1402             lc->active_worst_quality         = oxcf->worst_allowed_q;
1403             lc->active_best_quality          = oxcf->best_allowed_q;
1404             lc->avg_frame_qindex             = oxcf->worst_allowed_q;
1405
1406             prev_layer_frame_rate = lc->frame_rate;
1407         }
1408     }
1409 }
1410
1411 void vp8_change_config(VP8_COMP *cpi, VP8_CONFIG *oxcf)
1412 {
1413     VP8_COMMON *cm = &cpi->common;
1414
1415     if (!cpi)
1416         return;
1417
1418     if (!oxcf)
1419         return;
1420
1421     if (cm->version != oxcf->Version)
1422     {
1423         cm->version = oxcf->Version;
1424         vp8_setup_version(cm);
1425     }
1426
1427     cpi->oxcf = *oxcf;
1428
1429     switch (cpi->oxcf.Mode)
1430     {
1431
1432     case MODE_REALTIME:
1433         cpi->pass = 0;
1434         cpi->compressor_speed = 2;
1435
1436         if (cpi->oxcf.cpu_used < -16)
1437         {
1438             cpi->oxcf.cpu_used = -16;
1439         }
1440
1441         if (cpi->oxcf.cpu_used > 16)
1442             cpi->oxcf.cpu_used = 16;
1443
1444         break;
1445
1446     case MODE_GOODQUALITY:
1447         cpi->pass = 0;
1448         cpi->compressor_speed = 1;
1449
1450         if (cpi->oxcf.cpu_used < -5)
1451         {
1452             cpi->oxcf.cpu_used = -5;
1453         }
1454
1455         if (cpi->oxcf.cpu_used > 5)
1456             cpi->oxcf.cpu_used = 5;
1457
1458         break;
1459
1460     case MODE_BESTQUALITY:
1461         cpi->pass = 0;
1462         cpi->compressor_speed = 0;
1463         break;
1464
1465     case MODE_FIRSTPASS:
1466         cpi->pass = 1;
1467         cpi->compressor_speed = 1;
1468         break;
1469     case MODE_SECONDPASS:
1470         cpi->pass = 2;
1471         cpi->compressor_speed = 1;
1472
1473         if (cpi->oxcf.cpu_used < -5)
1474         {
1475             cpi->oxcf.cpu_used = -5;
1476         }
1477
1478         if (cpi->oxcf.cpu_used > 5)
1479             cpi->oxcf.cpu_used = 5;
1480
1481         break;
1482     case MODE_SECONDPASS_BEST:
1483         cpi->pass = 2;
1484         cpi->compressor_speed = 0;
1485         break;
1486     }
1487
1488     if (cpi->pass == 0)
1489         cpi->auto_worst_q = 1;
1490
1491     cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1492     cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1493     cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1494
1495     if (oxcf->fixed_q >= 0)
1496     {
1497         if (oxcf->worst_allowed_q < 0)
1498             cpi->oxcf.fixed_q = q_trans[0];
1499         else
1500             cpi->oxcf.fixed_q = q_trans[oxcf->worst_allowed_q];
1501
1502         if (oxcf->alt_q < 0)
1503             cpi->oxcf.alt_q = q_trans[0];
1504         else
1505             cpi->oxcf.alt_q = q_trans[oxcf->alt_q];
1506
1507         if (oxcf->key_q < 0)
1508             cpi->oxcf.key_q = q_trans[0];
1509         else
1510             cpi->oxcf.key_q = q_trans[oxcf->key_q];
1511
1512         if (oxcf->gold_q < 0)
1513             cpi->oxcf.gold_q = q_trans[0];
1514         else
1515             cpi->oxcf.gold_q = q_trans[oxcf->gold_q];
1516
1517     }
1518
1519     cpi->baseline_gf_interval =
1520         cpi->oxcf.alt_freq ? cpi->oxcf.alt_freq : DEFAULT_GF_INTERVAL;
1521
1522     cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
1523
1524     //cpi->use_golden_frame_only = 0;
1525     //cpi->use_last_frame_only = 0;
1526     cm->refresh_golden_frame = 0;
1527     cm->refresh_last_frame = 1;
1528     cm->refresh_entropy_probs = 1;
1529
1530     if (cpi->oxcf.token_partitions >= 0 && cpi->oxcf.token_partitions <= 3)
1531         cm->multi_token_partition =
1532             (TOKEN_PARTITION) cpi->oxcf.token_partitions;
1533
1534     setup_features(cpi);
1535
1536     {
1537         int i;
1538
1539         for (i = 0; i < MAX_MB_SEGMENTS; i++)
1540             cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1541     }
1542
1543     // At the moment the first order values may not be > MAXQ
1544     if (cpi->oxcf.fixed_q > MAXQ)
1545         cpi->oxcf.fixed_q = MAXQ;
1546
1547     // local file playback mode == really big buffer
1548     if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK)
1549     {
1550         cpi->oxcf.starting_buffer_level       = 60000;
1551         cpi->oxcf.optimal_buffer_level        = 60000;
1552         cpi->oxcf.maximum_buffer_size         = 240000;
1553         cpi->oxcf.starting_buffer_level_in_ms = 60000;
1554         cpi->oxcf.optimal_buffer_level_in_ms  = 60000;
1555         cpi->oxcf.maximum_buffer_size_in_ms   = 240000;
1556     }
1557
1558     // Convert target bandwidth from Kbit/s to Bit/s
1559     cpi->oxcf.target_bandwidth       *= 1000;
1560
1561     cpi->oxcf.starting_buffer_level =
1562         rescale(cpi->oxcf.starting_buffer_level,
1563                 cpi->oxcf.target_bandwidth, 1000);
1564
1565     // Set or reset optimal and maximum buffer levels.
1566     if (cpi->oxcf.optimal_buffer_level == 0)
1567         cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1568     else
1569         cpi->oxcf.optimal_buffer_level =
1570             rescale(cpi->oxcf.optimal_buffer_level,
1571                     cpi->oxcf.target_bandwidth, 1000);
1572
1573     if (cpi->oxcf.maximum_buffer_size == 0)
1574         cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1575     else
1576         cpi->oxcf.maximum_buffer_size =
1577             rescale(cpi->oxcf.maximum_buffer_size,
1578                     cpi->oxcf.target_bandwidth, 1000);
1579
1580     // Set up frame rate and related parameters rate control values.
1581     vp8_new_frame_rate(cpi, cpi->frame_rate);
1582
1583     // Set absolute upper and lower quality limits
1584     cpi->worst_quality               = cpi->oxcf.worst_allowed_q;
1585     cpi->best_quality                = cpi->oxcf.best_allowed_q;
1586
1587     // active values should only be modified if out of new range
1588     if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q)
1589     {
1590       cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1591     }
1592     // less likely
1593     else if (cpi->active_worst_quality < cpi->oxcf.best_allowed_q)
1594     {
1595       cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
1596     }
1597     if (cpi->active_best_quality < cpi->oxcf.best_allowed_q)
1598     {
1599       cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1600     }
1601     // less likely
1602     else if (cpi->active_best_quality > cpi->oxcf.worst_allowed_q)
1603     {
1604       cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
1605     }
1606
1607     cpi->buffered_mode = cpi->oxcf.optimal_buffer_level > 0;
1608
1609     cpi->cq_target_quality = cpi->oxcf.cq_level;
1610
1611     // Only allow dropped frames in buffered mode
1612     cpi->drop_frames_allowed = cpi->oxcf.allow_df && cpi->buffered_mode;
1613
1614     if (!cm->use_bilinear_mc_filter)
1615         cm->mcomp_filter_type = SIXTAP;
1616     else
1617         cm->mcomp_filter_type = BILINEAR;
1618
1619     cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1620
1621     cm->Width       = cpi->oxcf.Width;
1622     cm->Height      = cpi->oxcf.Height;
1623
1624     cm->horiz_scale  = cpi->horiz_scale;
1625     cm->vert_scale   = cpi->vert_scale;
1626
1627     // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1628     if (cpi->oxcf.Sharpness > 7)
1629         cpi->oxcf.Sharpness = 7;
1630
1631     cm->sharpness_level = cpi->oxcf.Sharpness;
1632
1633     if (cm->horiz_scale != NORMAL || cm->vert_scale != NORMAL)
1634     {
1635         int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
1636         int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
1637
1638         Scale2Ratio(cm->horiz_scale, &hr, &hs);
1639         Scale2Ratio(cm->vert_scale, &vr, &vs);
1640
1641         // always go to the next whole number
1642         cm->Width = (hs - 1 + cpi->oxcf.Width * hr) / hs;
1643         cm->Height = (vs - 1 + cpi->oxcf.Height * vr) / vs;
1644     }
1645
1646     if (((cm->Width + 15) & 0xfffffff0) !=
1647           cm->yv12_fb[cm->lst_fb_idx].y_width ||
1648         ((cm->Height + 15) & 0xfffffff0) !=
1649           cm->yv12_fb[cm->lst_fb_idx].y_height ||
1650         cm->yv12_fb[cm->lst_fb_idx].y_width == 0)
1651     {
1652         alloc_raw_frame_buffers(cpi);
1653         vp8_alloc_compressor_data(cpi);
1654     }
1655
1656     if (cpi->oxcf.fixed_q >= 0)
1657     {
1658         cpi->last_q[0] = cpi->oxcf.fixed_q;
1659         cpi->last_q[1] = cpi->oxcf.fixed_q;
1660     }
1661
1662     cpi->Speed = cpi->oxcf.cpu_used;
1663
1664     // force to allowlag to 0 if lag_in_frames is 0;
1665     if (cpi->oxcf.lag_in_frames == 0)
1666     {
1667         cpi->oxcf.allow_lag = 0;
1668     }
1669     // Limit on lag buffers as these are not currently dynamically allocated
1670     else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS)
1671         cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1672
1673     // YX Temp
1674     cpi->alt_ref_source = NULL;
1675     cpi->is_src_frame_alt_ref = 0;
1676
1677
1678 #if 0
1679     // Experimental RD Code
1680     cpi->frame_distortion = 0;
1681     cpi->last_frame_distortion = 0;
1682 #endif
1683
1684 }
1685
1686 #define M_LOG2_E 0.693147180559945309417
1687 #define log2f(x) (log (x) / (float) M_LOG2_E)
1688 static void cal_mvsadcosts(int *mvsadcost[2])
1689 {
1690     int i = 1;
1691
1692     mvsadcost [0] [0] = 300;
1693     mvsadcost [1] [0] = 300;
1694
1695     do
1696     {
1697         double z = 256 * (2 * (log2f(8 * i) + .6));
1698         mvsadcost [0][i] = (int) z;
1699         mvsadcost [1][i] = (int) z;
1700         mvsadcost [0][-i] = (int) z;
1701         mvsadcost [1][-i] = (int) z;
1702     }
1703     while (++i <= mvfp_max);
1704 }
1705
1706 struct VP8_COMP* vp8_create_compressor(VP8_CONFIG *oxcf)
1707 {
1708     int i;
1709
1710     VP8_COMP *cpi;
1711     VP8_COMMON *cm;
1712
1713     cpi = vpx_memalign(32, sizeof(VP8_COMP));
1714     // Check that the CPI instance is valid
1715     if (!cpi)
1716         return 0;
1717
1718     cm = &cpi->common;
1719
1720     vpx_memset(cpi, 0, sizeof(VP8_COMP));
1721
1722     if (setjmp(cm->error.jmp))
1723     {
1724         cpi->common.error.setjmp = 0;
1725         vp8_remove_compressor(&cpi);
1726         return 0;
1727     }
1728
1729     cpi->common.error.setjmp = 1;
1730
1731     CHECK_MEM_ERROR(cpi->mb.ss, vpx_calloc(sizeof(search_site), (MAX_MVSEARCH_STEPS * 8) + 1));
1732
1733     vp8_create_common(&cpi->common);
1734     vp8_cmachine_specific_config(cpi);
1735
1736     init_config(cpi, oxcf);
1737
1738     memcpy(cpi->base_skip_false_prob, vp8cx_base_skip_false_prob, sizeof(vp8cx_base_skip_false_prob));
1739     cpi->common.current_video_frame   = 0;
1740     cpi->kf_overspend_bits            = 0;
1741     cpi->kf_bitrate_adjustment        = 0;
1742     cpi->frames_till_gf_update_due      = 0;
1743     cpi->gf_overspend_bits            = 0;
1744     cpi->non_gf_bitrate_adjustment     = 0;
1745     cpi->prob_last_coded              = 128;
1746     cpi->prob_gf_coded                = 128;
1747     cpi->prob_intra_coded             = 63;
1748
1749     // Prime the recent reference frame usage counters.
1750     // Hereafter they will be maintained as a sort of moving average
1751     cpi->recent_ref_frame_usage[INTRA_FRAME]  = 1;
1752     cpi->recent_ref_frame_usage[LAST_FRAME]   = 1;
1753     cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
1754     cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
1755
1756     // Set reference frame sign bias for ALTREF frame to 1 (for now)
1757     cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
1758
1759     cpi->twopass.gf_decay_rate = 0;
1760     cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1761
1762     cpi->gold_is_last = 0 ;
1763     cpi->alt_is_last  = 0 ;
1764     cpi->gold_is_alt  = 0 ;
1765
1766     // allocate memory for storing last frame's MVs for MV prediction.
1767     CHECK_MEM_ERROR(cpi->lfmv, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int_mv)));
1768     CHECK_MEM_ERROR(cpi->lf_ref_frame_sign_bias, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1769     CHECK_MEM_ERROR(cpi->lf_ref_frame, vpx_calloc((cpi->common.mb_rows+2) * (cpi->common.mb_cols+2), sizeof(int)));
1770
1771     // Create the encoder segmentation map and set all entries to 0
1772     CHECK_MEM_ERROR(cpi->segmentation_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1773     CHECK_MEM_ERROR(cpi->active_map, vpx_calloc(cpi->common.mb_rows * cpi->common.mb_cols, 1));
1774     vpx_memset(cpi->active_map , 1, (cpi->common.mb_rows * cpi->common.mb_cols));
1775     cpi->active_map_enabled = 0;
1776
1777 #if 0
1778     // Experimental code for lagged and one pass
1779     // Initialise one_pass GF frames stats
1780     // Update stats used for GF selection
1781     if (cpi->pass == 0)
1782     {
1783         cpi->one_pass_frame_index = 0;
1784
1785         for (i = 0; i < MAX_LAG_BUFFERS; i++)
1786         {
1787             cpi->one_pass_frame_stats[i].frames_so_far = 0;
1788             cpi->one_pass_frame_stats[i].frame_intra_error = 0.0;
1789             cpi->one_pass_frame_stats[i].frame_coded_error = 0.0;
1790             cpi->one_pass_frame_stats[i].frame_pcnt_inter = 0.0;
1791             cpi->one_pass_frame_stats[i].frame_pcnt_motion = 0.0;
1792             cpi->one_pass_frame_stats[i].frame_mvr = 0.0;
1793             cpi->one_pass_frame_stats[i].frame_mvr_abs = 0.0;
1794             cpi->one_pass_frame_stats[i].frame_mvc = 0.0;
1795             cpi->one_pass_frame_stats[i].frame_mvc_abs = 0.0;
1796         }
1797     }
1798 #endif
1799
1800     // Should we use the cyclic refresh method.
1801     // Currently this is tied to error resilliant mode
1802     cpi->cyclic_refresh_mode_enabled = cpi->oxcf.error_resilient_mode;
1803     cpi->cyclic_refresh_mode_max_mbs_perframe = (cpi->common.mb_rows * cpi->common.mb_cols) / 40;
1804     cpi->cyclic_refresh_mode_index = 0;
1805     cpi->cyclic_refresh_q = 32;
1806
1807     if (cpi->cyclic_refresh_mode_enabled)
1808     {
1809         CHECK_MEM_ERROR(cpi->cyclic_refresh_map, vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
1810     }
1811     else
1812         cpi->cyclic_refresh_map = (signed char *) NULL;
1813
1814     // Test function for segmentation
1815     //segmentation_test_function( cpi);
1816
1817 #ifdef ENTROPY_STATS
1818     init_context_counters();
1819 #endif
1820
1821     /*Initialize the feed-forward activity masking.*/
1822     cpi->activity_avg = 90<<12;
1823
1824     cpi->frames_since_key = 8;        // Give a sensible default for the first frame.
1825     cpi->key_frame_frequency = cpi->oxcf.key_freq;
1826     cpi->this_key_frame_forced = 0;
1827     cpi->next_key_frame_forced = 0;
1828
1829     cpi->source_alt_ref_pending = 0;
1830     cpi->source_alt_ref_active = 0;
1831     cpi->common.refresh_alt_ref_frame = 0;
1832
1833     cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1834 #if CONFIG_INTERNAL_STATS
1835     cpi->b_calculate_ssimg = 0;
1836
1837     cpi->count = 0;
1838     cpi->bytes = 0;
1839
1840     if (cpi->b_calculate_psnr)
1841     {
1842         cpi->total_sq_error = 0.0;
1843         cpi->total_sq_error2 = 0.0;
1844         cpi->total_y = 0.0;
1845         cpi->total_u = 0.0;
1846         cpi->total_v = 0.0;
1847         cpi->total = 0.0;
1848         cpi->totalp_y = 0.0;
1849         cpi->totalp_u = 0.0;
1850         cpi->totalp_v = 0.0;
1851         cpi->totalp = 0.0;
1852         cpi->tot_recode_hits = 0;
1853         cpi->summed_quality = 0;
1854         cpi->summed_weights = 0;
1855     }
1856
1857     if (cpi->b_calculate_ssimg)
1858     {
1859         cpi->total_ssimg_y = 0;
1860         cpi->total_ssimg_u = 0;
1861         cpi->total_ssimg_v = 0;
1862         cpi->total_ssimg_all = 0;
1863     }
1864
1865 #endif
1866
1867 #ifndef LLONG_MAX
1868 #define LLONG_MAX  9223372036854775807LL
1869 #endif
1870     cpi->first_time_stamp_ever = LLONG_MAX;
1871
1872     cpi->frames_till_gf_update_due      = 0;
1873     cpi->key_frame_count              = 1;
1874
1875     cpi->ni_av_qi                     = cpi->oxcf.worst_allowed_q;
1876     cpi->ni_tot_qi                    = 0;
1877     cpi->ni_frames                   = 0;
1878     cpi->total_byte_count             = 0;
1879
1880     cpi->drop_frame                  = 0;
1881     cpi->drop_count                  = 0;
1882     cpi->max_drop_count               = 0;
1883     cpi->max_consec_dropped_frames     = 4;
1884
1885     cpi->rate_correction_factor         = 1.0;
1886     cpi->key_frame_rate_correction_factor = 1.0;
1887     cpi->gf_rate_correction_factor  = 1.0;
1888     cpi->twopass.est_max_qcorrection_factor  = 1.0;
1889
1890     cpi->mb.mvcost[0] = &cpi->mb.mvcosts[0][mv_max+1];
1891     cpi->mb.mvcost[1] = &cpi->mb.mvcosts[1][mv_max+1];
1892     cpi->mb.mvsadcost[0] = &cpi->mb.mvsadcosts[0][mvfp_max+1];
1893     cpi->mb.mvsadcost[1] = &cpi->mb.mvsadcosts[1][mvfp_max+1];
1894
1895     cal_mvsadcosts(cpi->mb.mvsadcost);
1896
1897     for (i = 0; i < KEY_FRAME_CONTEXT; i++)
1898     {
1899         cpi->prior_key_frame_distance[i] = (int)cpi->output_frame_rate;
1900     }
1901
1902 #ifdef OUTPUT_YUV_SRC
1903     yuv_file = fopen("bd.yuv", "ab");
1904 #endif
1905
1906 #if 0
1907     framepsnr = fopen("framepsnr.stt", "a");
1908     kf_list = fopen("kf_list.stt", "w");
1909 #endif
1910
1911     cpi->output_pkt_list = oxcf->output_pkt_list;
1912
1913 #if !(CONFIG_REALTIME_ONLY)
1914
1915     if (cpi->pass == 1)
1916     {
1917         vp8_init_first_pass(cpi);
1918     }
1919     else if (cpi->pass == 2)
1920     {
1921         size_t packet_sz = sizeof(FIRSTPASS_STATS);
1922         int packets = oxcf->two_pass_stats_in.sz / packet_sz;
1923
1924         cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1925         cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1926         cpi->twopass.stats_in_end = (void*)((char *)cpi->twopass.stats_in
1927                             + (packets - 1) * packet_sz);
1928         vp8_init_second_pass(cpi);
1929     }
1930
1931 #endif
1932
1933     if (cpi->compressor_speed == 2)
1934     {
1935         cpi->cpu_freq            = 0; //vp8_get_processor_freq();
1936         cpi->avg_encode_time      = 0;
1937         cpi->avg_pick_mode_time    = 0;
1938     }
1939
1940     vp8_set_speed_features(cpi);
1941
1942     // Set starting values of RD threshold multipliers (128 = *1)
1943     for (i = 0; i < MAX_MODES; i++)
1944     {
1945         cpi->rd_thresh_mult[i] = 128;
1946     }
1947
1948 #ifdef ENTROPY_STATS
1949     init_mv_ref_counts();
1950 #endif
1951
1952 #if CONFIG_MULTITHREAD
1953     vp8cx_create_encoder_threads(cpi);
1954 #endif
1955
1956     cpi->fn_ptr[BLOCK_16X16].sdf            = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16);
1957     cpi->fn_ptr[BLOCK_16X16].vf             = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x16);
1958     cpi->fn_ptr[BLOCK_16X16].svf            = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x16);
1959     cpi->fn_ptr[BLOCK_16X16].svf_halfpix_h  = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_h);
1960     cpi->fn_ptr[BLOCK_16X16].svf_halfpix_v  = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_v);
1961     cpi->fn_ptr[BLOCK_16X16].svf_halfpix_hv = VARIANCE_INVOKE(&cpi->rtcd.variance, halfpixvar16x16_hv);
1962     cpi->fn_ptr[BLOCK_16X16].sdx3f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x3);
1963     cpi->fn_ptr[BLOCK_16X16].sdx8f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x8);
1964     cpi->fn_ptr[BLOCK_16X16].sdx4df         = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x16x4d);
1965
1966     cpi->fn_ptr[BLOCK_16X8].sdf            = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8);
1967     cpi->fn_ptr[BLOCK_16X8].vf             = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x8);
1968     cpi->fn_ptr[BLOCK_16X8].svf            = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x8);
1969     cpi->fn_ptr[BLOCK_16X8].svf_halfpix_h  = NULL;
1970     cpi->fn_ptr[BLOCK_16X8].svf_halfpix_v  = NULL;
1971     cpi->fn_ptr[BLOCK_16X8].svf_halfpix_hv = NULL;
1972     cpi->fn_ptr[BLOCK_16X8].sdx3f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x3);
1973     cpi->fn_ptr[BLOCK_16X8].sdx8f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x8);
1974     cpi->fn_ptr[BLOCK_16X8].sdx4df         = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x4d);
1975
1976     cpi->fn_ptr[BLOCK_8X16].sdf            = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16);
1977     cpi->fn_ptr[BLOCK_8X16].vf             = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x16);
1978     cpi->fn_ptr[BLOCK_8X16].svf            = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x16);
1979     cpi->fn_ptr[BLOCK_8X16].svf_halfpix_h  = NULL;
1980     cpi->fn_ptr[BLOCK_8X16].svf_halfpix_v  = NULL;
1981     cpi->fn_ptr[BLOCK_8X16].svf_halfpix_hv = NULL;
1982     cpi->fn_ptr[BLOCK_8X16].sdx3f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x3);
1983     cpi->fn_ptr[BLOCK_8X16].sdx8f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x8);
1984     cpi->fn_ptr[BLOCK_8X16].sdx4df         = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x4d);
1985
1986     cpi->fn_ptr[BLOCK_8X8].sdf            = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8);
1987     cpi->fn_ptr[BLOCK_8X8].vf             = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x8);
1988     cpi->fn_ptr[BLOCK_8X8].svf            = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x8);
1989     cpi->fn_ptr[BLOCK_8X8].svf_halfpix_h  = NULL;
1990     cpi->fn_ptr[BLOCK_8X8].svf_halfpix_v  = NULL;
1991     cpi->fn_ptr[BLOCK_8X8].svf_halfpix_hv = NULL;
1992     cpi->fn_ptr[BLOCK_8X8].sdx3f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x3);
1993     cpi->fn_ptr[BLOCK_8X8].sdx8f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x8);
1994     cpi->fn_ptr[BLOCK_8X8].sdx4df         = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x4d);
1995
1996     cpi->fn_ptr[BLOCK_4X4].sdf            = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4);
1997     cpi->fn_ptr[BLOCK_4X4].vf             = VARIANCE_INVOKE(&cpi->rtcd.variance, var4x4);
1998     cpi->fn_ptr[BLOCK_4X4].svf            = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar4x4);
1999     cpi->fn_ptr[BLOCK_4X4].svf_halfpix_h  = NULL;
2000     cpi->fn_ptr[BLOCK_4X4].svf_halfpix_v  = NULL;
2001     cpi->fn_ptr[BLOCK_4X4].svf_halfpix_hv = NULL;
2002     cpi->fn_ptr[BLOCK_4X4].sdx3f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x3);
2003     cpi->fn_ptr[BLOCK_4X4].sdx8f          = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x8);
2004     cpi->fn_ptr[BLOCK_4X4].sdx4df         = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x4d);
2005
2006 #if ARCH_X86 || ARCH_X86_64
2007     cpi->fn_ptr[BLOCK_16X16].copymem        = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2008     cpi->fn_ptr[BLOCK_16X8].copymem        = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2009     cpi->fn_ptr[BLOCK_8X16].copymem        = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2010     cpi->fn_ptr[BLOCK_8X8].copymem        = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2011     cpi->fn_ptr[BLOCK_4X4].copymem        = VARIANCE_INVOKE(&cpi->rtcd.variance, copy32xn);
2012 #endif
2013
2014     cpi->full_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, full_search);
2015     cpi->diamond_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, diamond_search);
2016     cpi->refining_search_sad = SEARCH_INVOKE(&cpi->rtcd.search, refining_search);
2017
2018     // make sure frame 1 is okay
2019     cpi->error_bins[0] = cpi->common.MBs;
2020
2021     //vp8cx_init_quantizer() is first called here. Add check in vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only called later
2022     //when needed. This will avoid unnecessary calls of vp8cx_init_quantizer() for every frame.
2023     vp8cx_init_quantizer(cpi);
2024
2025     vp8_loop_filter_init(cm);
2026
2027     cpi->common.error.setjmp = 0;
2028
2029 #if CONFIG_MULTI_RES_ENCODING
2030     /* Calculate # of MBs in a row in lower-resolution level image. */
2031     if (cpi->oxcf.mr_encoder_id > 0)
2032         vp8_cal_low_res_mb_cols(cpi);
2033 #endif
2034
2035     return  cpi;
2036
2037 }
2038
2039
2040 void vp8_remove_compressor(VP8_COMP **ptr)
2041 {
2042     VP8_COMP *cpi = *ptr;
2043
2044     if (!cpi)
2045         return;
2046
2047     if (cpi && (cpi->common.current_video_frame > 0))
2048     {
2049 #if !(CONFIG_REALTIME_ONLY)
2050
2051         if (cpi->pass == 2)
2052         {
2053             vp8_end_second_pass(cpi);
2054         }
2055
2056 #endif
2057
2058 #ifdef ENTROPY_STATS
2059         print_context_counters();
2060         print_tree_update_probs();
2061         print_mode_context();
2062 #endif
2063
2064 #if CONFIG_INTERNAL_STATS
2065
2066         if (cpi->pass != 1)
2067         {
2068             FILE *f = fopen("opsnr.stt", "a");
2069             double time_encoded = (cpi->last_end_time_stamp_seen
2070                                    - cpi->first_time_stamp_ever) / 10000000.000;
2071             double total_encode_time = (cpi->time_receive_data +
2072                                             cpi->time_compress_data) / 1000.000;
2073             double dr = (double)cpi->bytes * 8.0 / 1000.0 / time_encoded;
2074
2075             if (cpi->b_calculate_psnr)
2076             {
2077                 YV12_BUFFER_CONFIG *lst_yv12 =
2078                               &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
2079
2080                 if (cpi->oxcf.number_of_layers > 1)
2081                 {
2082                     int i;
2083
2084                     fprintf(f, "Layer\tBitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2085                                "GLPsnrP\tVPXSSIM\t\n");
2086                     for (i=0; i<cpi->oxcf.number_of_layers; i++)
2087                     {
2088                         double dr = (double)cpi->bytes_in_layer[i] *
2089                                               8.0 / 1000.0  / time_encoded;
2090                         double samples = 3.0 / 2 * cpi->frames_in_layer[i] *
2091                                          lst_yv12->y_width * lst_yv12->y_height;
2092                         double total_psnr = vp8_mse2psnr(samples, 255.0,
2093                                                   cpi->total_error2[i]);
2094                         double total_psnr2 = vp8_mse2psnr(samples, 255.0,
2095                                                   cpi->total_error2_p[i]);
2096                         double total_ssim = 100 * pow(cpi->sum_ssim[i] /
2097                                                       cpi->sum_weights[i], 8.0);
2098
2099                         fprintf(f, "%5d\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2100                                    "%7.3f\t%7.3f\n",
2101                                    i, dr,
2102                                    cpi->sum_psnr[i] / cpi->frames_in_layer[i],
2103                                    total_psnr,
2104                                    cpi->sum_psnr_p[i] / cpi->frames_in_layer[i],
2105                                    total_psnr2, total_ssim);
2106                     }
2107                 }
2108                 else
2109                 {
2110                     double samples = 3.0 / 2 * cpi->count *
2111                                         lst_yv12->y_width * lst_yv12->y_height;
2112                     double total_psnr = vp8_mse2psnr(samples, 255.0,
2113                                                          cpi->total_sq_error);
2114                     double total_psnr2 = vp8_mse2psnr(samples, 255.0,
2115                                                          cpi->total_sq_error2);
2116                     double total_ssim = 100 * pow(cpi->summed_quality /
2117                                                       cpi->summed_weights, 8.0);
2118
2119                     fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2120                                "GLPsnrP\tVPXSSIM\t  Time(us)\n");
2121                     fprintf(f, "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2122                                "%7.3f\t%8.0f\n",
2123                                dr, cpi->total / cpi->count, total_psnr,
2124                                cpi->totalp / cpi->count, total_psnr2,
2125                                total_ssim, total_encode_time);
2126                 }
2127             }
2128
2129             if (cpi->b_calculate_ssimg)
2130             {
2131                 if (cpi->oxcf.number_of_layers > 1)
2132                 {
2133                     int i;
2134
2135                     fprintf(f, "Layer\tBitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t"
2136                                "Time(us)\n");
2137                     for (i=0; i<cpi->oxcf.number_of_layers; i++)
2138                     {
2139                         double dr = (double)cpi->bytes_in_layer[i] *
2140                                     8.0 / 1000.0  / time_encoded;
2141                         fprintf(f, "%5d\t%7.3f\t%6.4f\t"
2142                                 "%6.4f\t%6.4f\t%6.4f\t%8.0f\n",
2143                                 i, dr,
2144                                 cpi->total_ssimg_y_in_layer[i] /
2145                                      cpi->frames_in_layer[i],
2146                                 cpi->total_ssimg_u_in_layer[i] /
2147                                      cpi->frames_in_layer[i],
2148                                 cpi->total_ssimg_v_in_layer[i] /
2149                                      cpi->frames_in_layer[i],
2150                                 cpi->total_ssimg_all_in_layer[i] /
2151                                      cpi->frames_in_layer[i],
2152                                 total_encode_time);
2153                     }
2154                 }
2155                 else
2156                 {
2157                     fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t"
2158                                "Time(us)\n");
2159                     fprintf(f, "%7.3f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
2160                             cpi->total_ssimg_y / cpi->count,
2161                             cpi->total_ssimg_u / cpi->count,
2162                             cpi->total_ssimg_v / cpi->count,
2163                             cpi->total_ssimg_all / cpi->count, total_encode_time);
2164                 }
2165             }
2166
2167             fclose(f);
2168 #if 0
2169             f = fopen("qskip.stt", "a");
2170             fprintf(f, "minq:%d -maxq:%d skiptrue:skipfalse = %d:%d\n", cpi->oxcf.best_allowed_q, cpi->oxcf.worst_allowed_q, skiptruecount, skipfalsecount);
2171             fclose(f);
2172 #endif
2173
2174         }
2175
2176 #endif
2177
2178
2179 #ifdef SPEEDSTATS
2180
2181         if (cpi->compressor_speed == 2)
2182         {
2183             int i;
2184             FILE *f = fopen("cxspeed.stt", "a");
2185             cnt_pm /= cpi->common.MBs;
2186
2187             for (i = 0; i < 16; i++)
2188                 fprintf(f, "%5d", frames_at_speed[i]);
2189
2190             fprintf(f, "\n");
2191             //fprintf(f, "%10d PM %10d %10d %10d EF %10d %10d %10d\n", cpi->Speed, cpi->avg_pick_mode_time, (tot_pm/cnt_pm), cnt_pm,  cpi->avg_encode_time, 0, 0);
2192             fclose(f);
2193         }
2194
2195 #endif
2196
2197
2198 #ifdef MODE_STATS
2199         {
2200             extern int count_mb_seg[4];
2201             FILE *f = fopen("modes.stt", "a");
2202             double dr = (double)cpi->frame_rate * (double)bytes * (double)8 / (double)count / (double)1000 ;
2203             fprintf(f, "intra_mode in Intra Frames:\n");
2204             fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d\n", y_modes[0], y_modes[1], y_modes[2], y_modes[3], y_modes[4]);
2205             fprintf(f, "UV:%8d, %8d, %8d, %8d\n", uv_modes[0], uv_modes[1], uv_modes[2], uv_modes[3]);
2206             fprintf(f, "B: ");
2207             {
2208                 int i;
2209
2210                 for (i = 0; i < 10; i++)
2211                     fprintf(f, "%8d, ", b_modes[i]);
2212
2213                 fprintf(f, "\n");
2214
2215             }
2216
2217             fprintf(f, "Modes in Inter Frames:\n");
2218             fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d\n",
2219                     inter_y_modes[0], inter_y_modes[1], inter_y_modes[2], inter_y_modes[3], inter_y_modes[4],
2220                     inter_y_modes[5], inter_y_modes[6], inter_y_modes[7], inter_y_modes[8], inter_y_modes[9]);
2221             fprintf(f, "UV:%8d, %8d, %8d, %8d\n", inter_uv_modes[0], inter_uv_modes[1], inter_uv_modes[2], inter_uv_modes[3]);
2222             fprintf(f, "B: ");
2223             {
2224                 int i;
2225
2226                 for (i = 0; i < 15; i++)
2227                     fprintf(f, "%8d, ", inter_b_modes[i]);
2228
2229                 fprintf(f, "\n");
2230
2231             }
2232             fprintf(f, "P:%8d, %8d, %8d, %8d\n", count_mb_seg[0], count_mb_seg[1], count_mb_seg[2], count_mb_seg[3]);
2233             fprintf(f, "PB:%8d, %8d, %8d, %8d\n", inter_b_modes[LEFT4X4], inter_b_modes[ABOVE4X4], inter_b_modes[ZERO4X4], inter_b_modes[NEW4X4]);
2234
2235
2236
2237             fclose(f);
2238         }
2239 #endif
2240
2241 #ifdef ENTROPY_STATS
2242         {
2243             int i, j, k;
2244             FILE *fmode = fopen("modecontext.c", "w");
2245
2246             fprintf(fmode, "\n#include \"entropymode.h\"\n\n");
2247             fprintf(fmode, "const unsigned int vp8_kf_default_bmode_counts ");
2248             fprintf(fmode, "[VP8_BINTRAMODES] [VP8_BINTRAMODES] [VP8_BINTRAMODES] =\n{\n");
2249
2250             for (i = 0; i < 10; i++)
2251             {
2252
2253                 fprintf(fmode, "    { //Above Mode :  %d\n", i);
2254
2255                 for (j = 0; j < 10; j++)
2256                 {
2257
2258                     fprintf(fmode, "        {");
2259
2260                     for (k = 0; k < 10; k++)
2261                     {
2262                         if (!intra_mode_stats[i][j][k])
2263                             fprintf(fmode, " %5d, ", 1);
2264                         else
2265                             fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
2266                     }
2267
2268                     fprintf(fmode, "}, // left_mode %d\n", j);
2269
2270                 }
2271
2272                 fprintf(fmode, "    },\n");
2273
2274             }
2275
2276             fprintf(fmode, "};\n");
2277             fclose(fmode);
2278         }
2279 #endif
2280
2281
2282 #if defined(SECTIONBITS_OUTPUT)
2283
2284         if (0)
2285         {
2286             int i;
2287             FILE *f = fopen("tokenbits.stt", "a");
2288
2289             for (i = 0; i < 28; i++)
2290                 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
2291
2292             fprintf(f, "\n");
2293             fclose(f);
2294         }
2295
2296 #endif
2297
2298 #if 0
2299         {
2300             printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2301             printf("\n_frames recive_data encod_mb_row compress_frame  Total\n");
2302             printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame, cpi->time_receive_data / 1000, cpi->time_encode_mb_row / 1000, cpi->time_compress_data / 1000, (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2303         }
2304 #endif
2305
2306     }
2307
2308 #if CONFIG_MULTITHREAD
2309     vp8cx_remove_encoder_threads(cpi);
2310 #endif
2311
2312     dealloc_compressor_data(cpi);
2313     vpx_free(cpi->mb.ss);
2314     vpx_free(cpi->tok);
2315     vpx_free(cpi->cyclic_refresh_map);
2316
2317     vp8_remove_common(&cpi->common);
2318     vpx_free(cpi);
2319     *ptr = 0;
2320
2321 #ifdef OUTPUT_YUV_SRC
2322     fclose(yuv_file);
2323 #endif
2324
2325 #if 0
2326
2327     if (keyfile)
2328         fclose(keyfile);
2329
2330     if (framepsnr)
2331         fclose(framepsnr);
2332
2333     if (kf_list)
2334         fclose(kf_list);
2335
2336 #endif
2337
2338 }
2339
2340
2341 static uint64_t calc_plane_error(unsigned char *orig, int orig_stride,
2342                                  unsigned char *recon, int recon_stride,
2343                                  unsigned int cols, unsigned int rows,
2344                                  vp8_variance_rtcd_vtable_t *rtcd)
2345 {
2346     unsigned int row, col;
2347     uint64_t total_sse = 0;
2348     int diff;
2349
2350     for (row = 0; row + 16 <= rows; row += 16)
2351     {
2352         for (col = 0; col + 16 <= cols; col += 16)
2353         {
2354             unsigned int sse;
2355
2356             VARIANCE_INVOKE(rtcd, mse16x16)(orig + col, orig_stride,
2357                                             recon + col, recon_stride,
2358                                             &sse);
2359             total_sse += sse;
2360         }
2361
2362         /* Handle odd-sized width */
2363         if (col < cols)
2364         {
2365             unsigned int   border_row, border_col;
2366             unsigned char *border_orig = orig;
2367             unsigned char *border_recon = recon;
2368
2369             for (border_row = 0; border_row < 16; border_row++)
2370             {
2371                 for (border_col = col; border_col < cols; border_col++)
2372                 {
2373                     diff = border_orig[border_col] - border_recon[border_col];
2374                     total_sse += diff * diff;
2375                 }
2376
2377                 border_orig += orig_stride;
2378                 border_recon += recon_stride;
2379             }
2380         }
2381
2382         orig += orig_stride * 16;
2383         recon += recon_stride * 16;
2384     }
2385
2386     /* Handle odd-sized height */
2387     for (; row < rows; row++)
2388     {
2389         for (col = 0; col < cols; col++)
2390         {
2391             diff = orig[col] - recon[col];
2392             total_sse += diff * diff;
2393         }
2394
2395         orig += orig_stride;
2396         recon += recon_stride;
2397     }
2398
2399     vp8_clear_system_state();
2400     return total_sse;
2401 }
2402
2403
2404 static void generate_psnr_packet(VP8_COMP *cpi)
2405 {
2406     YV12_BUFFER_CONFIG      *orig = cpi->Source;
2407     YV12_BUFFER_CONFIG      *recon = cpi->common.frame_to_show;
2408     struct vpx_codec_cx_pkt  pkt;
2409     uint64_t                 sse;
2410     int                      i;
2411     unsigned int             width = cpi->common.Width;
2412     unsigned int             height = cpi->common.Height;
2413
2414     pkt.kind = VPX_CODEC_PSNR_PKT;
2415     sse = calc_plane_error(orig->y_buffer, orig->y_stride,
2416                            recon->y_buffer, recon->y_stride,
2417                            width, height,
2418                            IF_RTCD(&cpi->rtcd.variance));
2419     pkt.data.psnr.sse[0] = sse;
2420     pkt.data.psnr.sse[1] = sse;
2421     pkt.data.psnr.samples[0] = width * height;
2422     pkt.data.psnr.samples[1] = width * height;
2423
2424     width = (width + 1) / 2;
2425     height = (height + 1) / 2;
2426
2427     sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
2428                            recon->u_buffer, recon->uv_stride,
2429                            width, height,
2430                            IF_RTCD(&cpi->rtcd.variance));
2431     pkt.data.psnr.sse[0] += sse;
2432     pkt.data.psnr.sse[2] = sse;
2433     pkt.data.psnr.samples[0] += width * height;
2434     pkt.data.psnr.samples[2] = width * height;
2435
2436     sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2437                            recon->v_buffer, recon->uv_stride,
2438                            width, height,
2439                            IF_RTCD(&cpi->rtcd.variance));
2440     pkt.data.psnr.sse[0] += sse;
2441     pkt.data.psnr.sse[3] = sse;
2442     pkt.data.psnr.samples[0] += width * height;
2443     pkt.data.psnr.samples[3] = width * height;
2444
2445     for (i = 0; i < 4; i++)
2446         pkt.data.psnr.psnr[i] = vp8_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2447                                              pkt.data.psnr.sse[i]);
2448
2449     vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2450 }
2451
2452
2453 int vp8_use_as_reference(VP8_COMP *cpi, int ref_frame_flags)
2454 {
2455     if (ref_frame_flags > 7)
2456         return -1 ;
2457
2458     cpi->ref_frame_flags = ref_frame_flags;
2459     return 0;
2460 }
2461 int vp8_update_reference(VP8_COMP *cpi, int ref_frame_flags)
2462 {
2463     if (ref_frame_flags > 7)
2464         return -1 ;
2465
2466     cpi->common.refresh_golden_frame = 0;
2467     cpi->common.refresh_alt_ref_frame = 0;
2468     cpi->common.refresh_last_frame   = 0;
2469
2470     if (ref_frame_flags & VP8_LAST_FLAG)
2471         cpi->common.refresh_last_frame = 1;
2472
2473     if (ref_frame_flags & VP8_GOLD_FLAG)
2474         cpi->common.refresh_golden_frame = 1;
2475
2476     if (ref_frame_flags & VP8_ALT_FLAG)
2477         cpi->common.refresh_alt_ref_frame = 1;
2478
2479     return 0;
2480 }
2481
2482 int vp8_get_reference(VP8_COMP *cpi, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2483 {
2484     VP8_COMMON *cm = &cpi->common;
2485     int ref_fb_idx;
2486
2487     if (ref_frame_flag == VP8_LAST_FLAG)
2488         ref_fb_idx = cm->lst_fb_idx;
2489     else if (ref_frame_flag == VP8_GOLD_FLAG)
2490         ref_fb_idx = cm->gld_fb_idx;
2491     else if (ref_frame_flag == VP8_ALT_FLAG)
2492         ref_fb_idx = cm->alt_fb_idx;
2493     else
2494         return -1;
2495
2496     vp8_yv12_copy_frame_ptr(&cm->yv12_fb[ref_fb_idx], sd);
2497
2498     return 0;
2499 }
2500 int vp8_set_reference(VP8_COMP *cpi, VP8_REFFRAME ref_frame_flag, YV12_BUFFER_CONFIG *sd)
2501 {
2502     VP8_COMMON *cm = &cpi->common;
2503
2504     int ref_fb_idx;
2505
2506     if (ref_frame_flag == VP8_LAST_FLAG)
2507         ref_fb_idx = cm->lst_fb_idx;
2508     else if (ref_frame_flag == VP8_GOLD_FLAG)
2509         ref_fb_idx = cm->gld_fb_idx;
2510     else if (ref_frame_flag == VP8_ALT_FLAG)
2511         ref_fb_idx = cm->alt_fb_idx;
2512     else
2513         return -1;
2514
2515     vp8_yv12_copy_frame_ptr(sd, &cm->yv12_fb[ref_fb_idx]);
2516
2517     return 0;
2518 }
2519 int vp8_update_entropy(VP8_COMP *cpi, int update)
2520 {
2521     VP8_COMMON *cm = &cpi->common;
2522     cm->refresh_entropy_probs = update;
2523
2524     return 0;
2525 }
2526
2527
2528 #if OUTPUT_YUV_SRC
2529 void vp8_write_yuv_frame(const char *name, YV12_BUFFER_CONFIG *s)
2530 {
2531     FILE *yuv_file = fopen(name, "ab");
2532     unsigned char *src = s->y_buffer;
2533     int h = s->y_height;
2534
2535     do
2536     {
2537         fwrite(src, s->y_width, 1,  yuv_file);
2538         src += s->y_stride;
2539     }
2540     while (--h);
2541
2542     src = s->u_buffer;
2543     h = s->uv_height;
2544
2545     do
2546     {
2547         fwrite(src, s->uv_width, 1,  yuv_file);
2548         src += s->uv_stride;
2549     }
2550     while (--h);
2551
2552     src = s->v_buffer;
2553     h = s->uv_height;
2554
2555     do
2556     {
2557         fwrite(src, s->uv_width, 1, yuv_file);
2558         src += s->uv_stride;
2559     }
2560     while (--h);
2561
2562     fclose(yuv_file);
2563 }
2564 #endif
2565
2566
2567 static void scale_and_extend_source(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi)
2568 {
2569     VP8_COMMON *cm = &cpi->common;
2570
2571     // are we resizing the image
2572     if (cm->horiz_scale != 0 || cm->vert_scale != 0)
2573     {
2574 #if CONFIG_SPATIAL_RESAMPLING
2575         int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2576         int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2577         int tmp_height;
2578
2579         if (cm->vert_scale == 3)
2580             tmp_height = 9;
2581         else
2582             tmp_height = 11;
2583
2584         Scale2Ratio(cm->horiz_scale, &hr, &hs);
2585         Scale2Ratio(cm->vert_scale, &vr, &vs);
2586
2587         vp8_scale_frame(sd, &cpi->scaled_source, cm->temp_scale_frame.y_buffer,
2588                         tmp_height, hs, hr, vs, vr, 0);
2589
2590         vp8_yv12_extend_frame_borders(&cpi->scaled_source);
2591         cpi->Source = &cpi->scaled_source;
2592 #endif
2593     }
2594     else
2595         cpi->Source = sd;
2596 }
2597
2598
2599 static void resize_key_frame(VP8_COMP *cpi)
2600 {
2601 #if CONFIG_SPATIAL_RESAMPLING
2602     VP8_COMMON *cm = &cpi->common;
2603
2604     // Do we need to apply resampling for one pass cbr.
2605     // In one pass this is more limited than in two pass cbr
2606     // The test and any change is only made one per key frame sequence
2607     if (cpi->oxcf.allow_spatial_resampling && (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER))
2608     {
2609         int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2610         int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2611         int new_width, new_height;
2612
2613         // If we are below the resample DOWN watermark then scale down a notch.
2614         if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2615         {
2616             cm->horiz_scale = (cm->horiz_scale < ONETWO) ? cm->horiz_scale + 1 : ONETWO;
2617             cm->vert_scale = (cm->vert_scale < ONETWO) ? cm->vert_scale + 1 : ONETWO;
2618         }
2619         // Should we now start scaling back up
2620         else if (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))
2621         {
2622             cm->horiz_scale = (cm->horiz_scale > NORMAL) ? cm->horiz_scale - 1 : NORMAL;
2623             cm->vert_scale = (cm->vert_scale > NORMAL) ? cm->vert_scale - 1 : NORMAL;
2624         }
2625
2626         // Get the new hieght and width
2627         Scale2Ratio(cm->horiz_scale, &hr, &hs);
2628         Scale2Ratio(cm->vert_scale, &vr, &vs);
2629         new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
2630         new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
2631
2632         // If the image size has changed we need to reallocate the buffers
2633         // and resample the source image
2634         if ((cm->Width != new_width) || (cm->Height != new_height))
2635         {
2636             cm->Width = new_width;
2637             cm->Height = new_height;
2638             vp8_alloc_compressor_data(cpi);
2639             scale_and_extend_source(cpi->un_scaled_source, cpi);
2640         }
2641     }
2642
2643 #endif
2644 }
2645
2646
2647 static void update_alt_ref_frame_stats(VP8_COMP *cpi)
2648 {
2649     VP8_COMMON *cm = &cpi->common;
2650
2651     // Select an interval before next GF or altref
2652     if (!cpi->auto_gold)
2653         cpi->frames_till_gf_update_due = cpi->goldfreq;
2654
2655     if ((cpi->pass != 2) && cpi->frames_till_gf_update_due)
2656     {
2657         cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2658
2659         // Set the bits per frame that we should try and recover in subsequent inter frames
2660         // to account for the extra GF spend... note that his does not apply for GF updates
2661         // that occur coincident with a key frame as the extra cost of key frames is dealt
2662         // with elsewhere.
2663
2664         cpi->gf_overspend_bits += cpi->projected_frame_size;
2665         cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2666     }
2667
2668     // Update data structure that monitors level of reference to last GF
2669     vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2670     cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2671
2672     // this frame refreshes means next frames don't unless specified by user
2673     cpi->common.frames_since_golden = 0;
2674
2675     // Clear the alternate reference update pending flag.
2676     cpi->source_alt_ref_pending = 0;
2677
2678     // Set the alternate refernce frame active flag
2679     cpi->source_alt_ref_active = 1;
2680
2681
2682 }
2683 static void update_golden_frame_stats(VP8_COMP *cpi)
2684 {
2685     VP8_COMMON *cm = &cpi->common;
2686
2687     // Update the Golden frame usage counts.
2688     if (cm->refresh_golden_frame)
2689     {
2690         // Select an interval before next GF
2691         if (!cpi->auto_gold)
2692             cpi->frames_till_gf_update_due = cpi->goldfreq;
2693
2694         if ((cpi->pass != 2) && (cpi->frames_till_gf_update_due > 0))
2695         {
2696             cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2697
2698             // Set the bits per frame that we should try and recover in subsequent inter frames
2699             // to account for the extra GF spend... note that his does not apply for GF updates
2700             // that occur coincident with a key frame as the extra cost of key frames is dealt
2701             // with elsewhere.
2702             if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active)
2703             {
2704                 // Calcluate GF bits to be recovered
2705                 // Projected size - av frame bits available for inter frames for clip as a whole
2706                 cpi->gf_overspend_bits += (cpi->projected_frame_size - cpi->inter_frame_target);
2707             }
2708
2709             cpi->non_gf_bitrate_adjustment = cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2710
2711         }
2712
2713         // Update data structure that monitors level of reference to last GF
2714         vpx_memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2715         cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2716
2717         // this frame refreshes means next frames don't unless specified by user
2718         cm->refresh_golden_frame = 0;
2719         cpi->common.frames_since_golden = 0;
2720
2721         //if ( cm->frame_type == KEY_FRAME )
2722         //{
2723         cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
2724         cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
2725         cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
2726         cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
2727         //}
2728         //else
2729         //{
2730         //  // Carry a potrtion of count over to begining of next gf sequence
2731         //  cpi->recent_ref_frame_usage[INTRA_FRAME] >>= 5;
2732         //  cpi->recent_ref_frame_usage[LAST_FRAME] >>= 5;
2733         //  cpi->recent_ref_frame_usage[GOLDEN_FRAME] >>= 5;
2734         //  cpi->recent_ref_frame_usage[ALTREF_FRAME] >>= 5;
2735         //}
2736
2737         // ******** Fixed Q test code only ************
2738         // If we are going to use the ALT reference for the next group of frames set a flag to say so.
2739         if (cpi->oxcf.fixed_q >= 0 &&
2740             cpi->oxcf.play_alternate && !cpi->common.refresh_alt_ref_frame)
2741         {
2742             cpi->source_alt_ref_pending = 1;
2743             cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2744         }
2745
2746         if (!cpi->source_alt_ref_pending)
2747             cpi->source_alt_ref_active = 0;
2748
2749         // Decrement count down till next gf
2750         if (cpi->frames_till_gf_update_due > 0)
2751             cpi->frames_till_gf_update_due--;
2752
2753     }
2754     else if (!cpi->common.refresh_alt_ref_frame)
2755     {
2756         // Decrement count down till next gf
2757         if (cpi->frames_till_gf_update_due > 0)
2758             cpi->frames_till_gf_update_due--;
2759
2760         if (cpi->common.frames_till_alt_ref_frame)
2761             cpi->common.frames_till_alt_ref_frame --;
2762
2763         cpi->common.frames_since_golden ++;
2764
2765         if (cpi->common.frames_since_golden > 1)
2766         {
2767             cpi->recent_ref_frame_usage[INTRA_FRAME] += cpi->count_mb_ref_frame_usage[INTRA_FRAME];
2768             cpi->recent_ref_frame_usage[LAST_FRAME] += cpi->count_mb_ref_frame_usage[LAST_FRAME];
2769             cpi->recent_ref_frame_usage[GOLDEN_FRAME] += cpi->count_mb_ref_frame_usage[GOLDEN_FRAME];
2770             cpi->recent_ref_frame_usage[ALTREF_FRAME] += cpi->count_mb_ref_frame_usage[ALTREF_FRAME];
2771         }
2772     }
2773 }
2774
2775 // This function updates the reference frame probability estimates that
2776 // will be used during mode selection
2777 static void update_rd_ref_frame_probs(VP8_COMP *cpi)
2778 {
2779     VP8_COMMON *cm = &cpi->common;
2780
2781     const int *const rfct = cpi->count_mb_ref_frame_usage;
2782     const int rf_intra = rfct[INTRA_FRAME];
2783     const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
2784
2785     if (cm->frame_type == KEY_FRAME)
2786     {
2787         cpi->prob_intra_coded = 255;
2788         cpi->prob_last_coded  = 128;
2789         cpi->prob_gf_coded  = 128;
2790     }
2791     else if (!(rf_intra + rf_inter))
2792     {
2793         cpi->prob_intra_coded = 63;
2794         cpi->prob_last_coded  = 128;
2795         cpi->prob_gf_coded    = 128;
2796     }
2797
2798     // update reference frame costs since we can do better than what we got last frame.
2799     if (cpi->oxcf.number_of_layers == 1)
2800     {
2801         if (cpi->common.refresh_alt_ref_frame)
2802         {
2803             cpi->prob_intra_coded += 40;
2804             cpi->prob_last_coded = 200;
2805             cpi->prob_gf_coded = 1;
2806         }
2807         else if (cpi->common.frames_since_golden == 0)
2808         {
2809             cpi->prob_last_coded = 214;
2810         }
2811         else if (cpi->common.frames_since_golden == 1)
2812         {
2813             cpi->prob_last_coded = 192;
2814             cpi->prob_gf_coded = 220;
2815         }
2816         else if (cpi->source_alt_ref_active)
2817         {
2818             cpi->prob_gf_coded -= 20;
2819
2820             if (cpi->prob_gf_coded < 10)
2821                 cpi->prob_gf_coded = 10;
2822         }
2823         if (!cpi->source_alt_ref_active)
2824             cpi->prob_gf_coded = 255;
2825     }
2826 }
2827
2828
2829 // 1 = key, 0 = inter
2830 static int decide_key_frame(VP8_COMP *cpi)
2831 {
2832     VP8_COMMON *cm = &cpi->common;
2833
2834     int code_key_frame = 0;
2835
2836     cpi->kf_boost = 0;
2837
2838     if (cpi->Speed > 11)
2839         return 0;
2840
2841     // Clear down mmx registers
2842     vp8_clear_system_state();  //__asm emms;
2843
2844     if ((cpi->compressor_speed == 2) && (cpi->Speed >= 5) && (cpi->sf.RD == 0))
2845     {
2846         double change = 1.0 * abs((int)(cpi->intra_error - cpi->last_intra_error)) / (1 + cpi->last_intra_error);
2847         double change2 = 1.0 * abs((int)(cpi->prediction_error - cpi->last_prediction_error)) / (1 + cpi->last_prediction_error);
2848         double minerror = cm->MBs * 256;
2849
2850 #if 0
2851
2852         if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
2853             && cpi->prediction_error > minerror
2854             && (change > .25 || change2 > .25))
2855         {
2856             FILE *f = fopen("intra_inter.stt", "a");
2857
2858             if (cpi->prediction_error <= 0)
2859                 cpi->prediction_error = 1;
2860
2861             fprintf(f, "%d %d %d %d %14.4f\n",
2862                     cm->current_video_frame,
2863                     (int) cpi->prediction_error,
2864                     (int) cpi->intra_error,
2865                     (int)((10 * cpi->intra_error) / cpi->prediction_error),
2866                     change);
2867
2868             fclose(f);
2869         }
2870
2871 #endif
2872
2873         cpi->last_intra_error = cpi->intra_error;
2874         cpi->last_prediction_error = cpi->prediction_error;
2875
2876         if (10 * cpi->intra_error / (1 + cpi->prediction_error) < 15
2877             && cpi->prediction_error > minerror
2878             && (change > .25 || change2 > .25))
2879         {
2880             /*(change > 1.4 || change < .75)&& cpi->this_frame_percent_intra > cpi->last_frame_percent_intra + 3*/
2881             return 1;
2882         }
2883
2884         return 0;
2885
2886     }
2887
2888     // If the following are true we might as well code a key frame
2889     if (((cpi->this_frame_percent_intra == 100) &&
2890          (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
2891         ((cpi->this_frame_percent_intra > 95) &&
2892          (cpi->this_frame_percent_intra >= (cpi->last_frame_percent_intra + 5))))
2893     {
2894         code_key_frame = 1;
2895     }
2896     // in addition if the following are true and this is not a golden frame then code a key frame
2897     // Note that on golden frames there often seems to be a pop in intra useage anyway hence this
2898     // restriction is designed to prevent spurious key frames. The Intra pop needs to be investigated.
2899     else if (((cpi->this_frame_percent_intra > 60) &&
2900               (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 2))) ||
2901              ((cpi->this_frame_percent_intra > 75) &&
2902               (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra * 3 / 2))) ||
2903              ((cpi->this_frame_percent_intra > 90) &&
2904               (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 10))))
2905     {
2906         if (!cm->refresh_golden_frame)
2907             code_key_frame = 1;
2908     }
2909
2910     return code_key_frame;
2911
2912 }
2913
2914 #if !(CONFIG_REALTIME_ONLY)
2915 static void Pass1Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags)
2916 {
2917     (void) size;
2918     (void) dest;
2919     (void) frame_flags;
2920     vp8_set_quantizer(cpi, 26);
2921
2922     scale_and_extend_source(cpi->un_scaled_source, cpi);
2923     vp8_first_pass(cpi);
2924 }
2925 #endif
2926
2927 #if 0
2928 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame)
2929 {
2930
2931     // write the frame
2932     FILE *yframe;
2933     int i;
2934     char filename[255];
2935
2936     sprintf(filename, "cx\\y%04d.raw", this_frame);
2937     yframe = fopen(filename, "wb");
2938
2939     for (i = 0; i < frame->y_height; i++)
2940         fwrite(frame->y_buffer + i * frame->y_stride, frame->y_width, 1, yframe);
2941
2942     fclose(yframe);
2943     sprintf(filename, "cx\\u%04d.raw", this_frame);
2944     yframe = fopen(filename, "wb");
2945
2946     for (i = 0; i < frame->uv_height; i++)
2947         fwrite(frame->u_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2948
2949     fclose(yframe);
2950     sprintf(filename, "cx\\v%04d.raw", this_frame);
2951     yframe = fopen(filename, "wb");
2952
2953     for (i = 0; i < frame->uv_height; i++)
2954         fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2955
2956     fclose(yframe);
2957 }
2958 #endif
2959 // return of 0 means drop frame
2960
2961 // Function to test for conditions that indeicate we should loop
2962 // back and recode a frame.
2963 static int recode_loop_test( VP8_COMP *cpi,
2964                               int high_limit, int low_limit,
2965                               int q, int maxq, int minq )
2966 {
2967     int force_recode = 0;
2968     VP8_COMMON *cm = &cpi->common;
2969
2970     // Is frame recode allowed at all
2971     // Yes if either recode mode 1 is selected or mode two is selcted
2972     // and the frame is a key frame. golden frame or alt_ref_frame
2973     if ( (cpi->sf.recode_loop == 1) ||
2974          ( (cpi->sf.recode_loop == 2) &&
2975            ( (cm->frame_type == KEY_FRAME) ||
2976              cm->refresh_golden_frame ||
2977              cm->refresh_alt_ref_frame ) ) )
2978     {
2979         // General over and under shoot tests
2980         if ( ((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
2981              ((cpi->projected_frame_size < low_limit) && (q > minq)) )
2982         {
2983             force_recode = 1;
2984         }
2985         // Special Constrained quality tests
2986         else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
2987         {
2988             // Undershoot and below auto cq level
2989             if ( (q > cpi->cq_target_quality) &&
2990                  (cpi->projected_frame_size <
2991                      ((cpi->this_frame_target * 7) >> 3)))
2992             {
2993                 force_recode = 1;
2994             }
2995             // Severe undershoot and between auto and user cq level
2996             else if ( (q > cpi->oxcf.cq_level) &&
2997                       (cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
2998                       (cpi->active_best_quality > cpi->oxcf.cq_level))
2999             {
3000                 force_recode = 1;
3001                 cpi->active_best_quality = cpi->oxcf.cq_level;
3002             }
3003         }
3004     }
3005
3006     return force_recode;
3007 }
3008
3009 void update_reference_frames(VP8_COMMON *cm)
3010 {
3011     YV12_BUFFER_CONFIG *yv12_fb = cm->yv12_fb;
3012
3013     // At this point the new frame has been encoded.
3014     // If any buffer copy / swapping is signaled it should be done here.
3015
3016     if (cm->frame_type == KEY_FRAME)
3017     {
3018         yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG | VP8_ALT_FLAG ;
3019
3020         yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3021         yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3022
3023         cm->alt_fb_idx = cm->gld_fb_idx = cm->new_fb_idx;
3024     }
3025     else    /* For non key frames */
3026     {
3027         if (cm->refresh_alt_ref_frame)
3028         {
3029             assert(!cm->copy_buffer_to_arf);
3030
3031             cm->yv12_fb[cm->new_fb_idx].flags |= VP8_ALT_FLAG;
3032             cm->yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3033             cm->alt_fb_idx = cm->new_fb_idx;
3034         }
3035         else if (cm->copy_buffer_to_arf)
3036         {
3037             assert(!(cm->copy_buffer_to_arf & ~0x3));
3038
3039             if (cm->copy_buffer_to_arf == 1)
3040             {
3041                 if(cm->alt_fb_idx != cm->lst_fb_idx)
3042                 {
3043                     yv12_fb[cm->lst_fb_idx].flags |= VP8_ALT_FLAG;
3044                     yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3045                     cm->alt_fb_idx = cm->lst_fb_idx;
3046                 }
3047             }
3048             else /* if (cm->copy_buffer_to_arf == 2) */
3049             {
3050                 if(cm->alt_fb_idx != cm->gld_fb_idx)
3051                 {
3052                     yv12_fb[cm->gld_fb_idx].flags |= VP8_ALT_FLAG;
3053                     yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALT_FLAG;
3054                     cm->alt_fb_idx = cm->gld_fb_idx;
3055                 }
3056             }
3057         }
3058
3059         if (cm->refresh_golden_frame)
3060         {
3061             assert(!cm->copy_buffer_to_gf);
3062
3063             cm->yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FLAG;
3064             cm->yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3065             cm->gld_fb_idx = cm->new_fb_idx;
3066         }
3067         else if (cm->copy_buffer_to_gf)
3068         {
3069             assert(!(cm->copy_buffer_to_arf & ~0x3));
3070
3071             if (cm->copy_buffer_to_gf == 1)
3072             {
3073                 if(cm->gld_fb_idx != cm->lst_fb_idx)
3074                 {
3075                     yv12_fb[cm->lst_fb_idx].flags |= VP8_GOLD_FLAG;
3076                     yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3077                     cm->gld_fb_idx = cm->lst_fb_idx;
3078                 }
3079             }
3080             else /* if (cm->copy_buffer_to_gf == 2) */
3081             {
3082                 if(cm->alt_fb_idx != cm->gld_fb_idx)
3083                 {
3084                     yv12_fb[cm->alt_fb_idx].flags |= VP8_GOLD_FLAG;
3085                     yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FLAG;
3086                     cm->gld_fb_idx = cm->alt_fb_idx;
3087                 }
3088             }
3089         }
3090     }
3091
3092     if (cm->refresh_last_frame)
3093     {
3094         cm->yv12_fb[cm->new_fb_idx].flags |= VP8_LAST_FLAG;
3095         cm->yv12_fb[cm->lst_fb_idx].flags &= ~VP8_LAST_FLAG;
3096         cm->lst_fb_idx = cm->new_fb_idx;
3097     }
3098 }
3099
3100 void loopfilter_frame(VP8_COMP *cpi, VP8_COMMON *cm)
3101 {
3102     if (cm->no_lpf)
3103     {
3104         cm->filter_level = 0;
3105     }
3106     else
3107     {
3108         struct vpx_usec_timer timer;
3109
3110         vp8_clear_system_state();
3111
3112         vpx_usec_timer_start(&timer);
3113         if (cpi->sf.auto_filter == 0)
3114             vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3115
3116         else
3117             vp8cx_pick_filter_level(cpi->Source, cpi);
3118
3119         vpx_usec_timer_mark(&timer);
3120         cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
3121     }
3122
3123 #if CONFIG_MULTITHREAD
3124     if (cpi->b_multi_threaded)
3125         sem_post(&cpi->h_event_end_lpf); /* signal that we have set filter_level */
3126 #endif
3127
3128     if (cm->filter_level > 0)
3129     {
3130         vp8cx_set_alt_lf_level(cpi, cm->filter_level);
3131         vp8_loop_filter_frame(cm, &cpi->mb.e_mbd);
3132     }
3133
3134     vp8_yv12_extend_frame_borders_ptr(cm->frame_to_show);
3135
3136 }
3137
3138 static void encode_frame_to_data_rate
3139 (
3140     VP8_COMP *cpi,
3141     unsigned long *size,
3142     unsigned char *dest,
3143     unsigned char* dest_end,
3144     unsigned int *frame_flags
3145 )
3146 {
3147     int Q;
3148     int frame_over_shoot_limit;
3149     int frame_under_shoot_limit;
3150
3151     int Loop = 0;
3152     int loop_count;
3153     int this_q;
3154     int last_zbin_oq;
3155
3156     int q_low;
3157     int q_high;
3158     int zbin_oq_high;
3159     int zbin_oq_low = 0;
3160     int top_index;
3161     int bottom_index;
3162     VP8_COMMON *cm = &cpi->common;
3163     int active_worst_qchanged = 0;
3164
3165     int overshoot_seen = 0;
3166     int undershoot_seen = 0;
3167     int drop_mark = cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100;
3168     int drop_mark75 = drop_mark * 2 / 3;
3169     int drop_mark50 = drop_mark / 4;
3170     int drop_mark25 = drop_mark / 8;
3171
3172
3173     // Clear down mmx registers to allow floating point in what follows
3174     vp8_clear_system_state();
3175
3176     // Test code for segmentation of gf/arf (0,0)
3177     //segmentation_test_function( cpi);
3178
3179     if (cpi->compressor_speed == 2)
3180     {
3181         if(cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3182         {
3183             if(cpi->force_next_frame_intra)
3184             {
3185                 cm->frame_type = KEY_FRAME;  /* delayed intra frame */
3186             }
3187         }
3188         cpi->force_next_frame_intra = 0;
3189     }
3190
3191     // For an alt ref frame in 2 pass we skip the call to the second pass function that sets the target bandwidth
3192 #if !(CONFIG_REALTIME_ONLY)
3193
3194     if (cpi->pass == 2)
3195     {
3196         if (cpi->common.refresh_alt_ref_frame)
3197         {
3198             cpi->per_frame_bandwidth = cpi->twopass.gf_bits;                           // Per frame bit target for the alt ref frame
3199             cpi->target_bandwidth = cpi->twopass.gf_bits * cpi->output_frame_rate;      // per second target bitrate
3200         }
3201     }
3202     else
3203 #endif
3204         cpi->per_frame_bandwidth  = (int)(cpi->target_bandwidth / cpi->output_frame_rate);
3205
3206     // Default turn off buffer to buffer copying
3207     cm->copy_buffer_to_gf = 0;
3208     cm->copy_buffer_to_arf = 0;
3209
3210     // Clear zbin over-quant value and mode boost values.
3211     cpi->zbin_over_quant = 0;
3212     cpi->zbin_mode_boost = 0;
3213
3214     // Enable or disable mode based tweaking of the zbin
3215     // For 2 Pass Only used where GF/ARF prediction quality
3216     // is above a threshold
3217     cpi->zbin_mode_boost_enabled = 1;
3218     if (cpi->pass == 2)
3219     {
3220         if ( cpi->gfu_boost <= 400 )
3221         {
3222             cpi->zbin_mode_boost_enabled = 0;
3223         }
3224     }
3225
3226     // Current default encoder behaviour for the altref sign bias
3227     if (cpi->source_alt_ref_active)
3228         cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
3229     else
3230         cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
3231
3232     // Check to see if a key frame is signalled
3233     // For two pass with auto key frame enabled cm->frame_type may already be set, but not for one pass.
3234     if ((cm->current_video_frame == 0) ||
3235         (cm->frame_flags & FRAMEFLAGS_KEY) ||
3236         (cpi->oxcf.auto_key && (cpi->frames_since_key % cpi->key_frame_frequency == 0)))
3237     {
3238         // Key frame from VFW/auto-keyframe/first frame
3239         cm->frame_type = KEY_FRAME;
3240     }
3241
3242     // Set default state for segment and mode based loop filter update flags
3243     cpi->mb.e_mbd.update_mb_segmentation_map = 0;
3244     cpi->mb.e_mbd.update_mb_segmentation_data = 0;
3245     cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
3246
3247     // Set various flags etc to special state if it is a key frame
3248     if (cm->frame_type == KEY_FRAME)
3249     {
3250         int i;
3251
3252         // Reset the loop filter deltas and segmentation map
3253         setup_features(cpi);
3254
3255         // If segmentation is enabled force a map update for key frames
3256         if (cpi->mb.e_mbd.segmentation_enabled)
3257         {
3258             cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3259             cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3260         }
3261
3262         // The alternate reference frame cannot be active for a key frame
3263         cpi->source_alt_ref_active = 0;
3264
3265         // Reset the RD threshold multipliers to default of * 1 (128)
3266         for (i = 0; i < MAX_MODES; i++)
3267         {
3268             cpi->rd_thresh_mult[i] = 128;
3269         }
3270     }
3271
3272     // Test code for segmentation
3273     //if ( (cm->frame_type == KEY_FRAME) || ((cm->current_video_frame % 2) == 0))
3274     //if ( (cm->current_video_frame % 2) == 0 )
3275     //  enable_segmentation(cpi);
3276     //else
3277     //  disable_segmentation(cpi);
3278
3279 #if 0
3280     // Experimental code for lagged compress and one pass
3281     // Initialise one_pass GF frames stats
3282     // Update stats used for GF selection
3283     //if ( cpi->pass == 0 )
3284     {
3285         cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
3286
3287         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
3288         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
3289         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
3290         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
3291         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
3292         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
3293         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
3294         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
3295         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
3296     }
3297 #endif
3298
3299     update_rd_ref_frame_probs(cpi);
3300
3301     if (cpi->drop_frames_allowed)
3302     {
3303         // The reset to decimation 0 is only done here for one pass.
3304         // Once it is set two pass leaves decimation on till the next kf.
3305         if ((cpi->buffer_level > drop_mark) && (cpi->decimation_factor > 0))
3306             cpi->decimation_factor --;
3307
3308         if (cpi->buffer_level > drop_mark75 && cpi->decimation_factor > 0)
3309             cpi->decimation_factor = 1;
3310
3311         else if (cpi->buffer_level < drop_mark25 && (cpi->decimation_factor == 2 || cpi->decimation_factor == 3))
3312         {
3313             cpi->decimation_factor = 3;
3314         }
3315         else if (cpi->buffer_level < drop_mark50 && (cpi->decimation_factor == 1 || cpi->decimation_factor == 2))
3316         {
3317             cpi->decimation_factor = 2;
3318         }
3319         else if (cpi->buffer_level < drop_mark75 && (cpi->decimation_factor == 0 || cpi->decimation_factor == 1))
3320         {
3321             cpi->decimation_factor = 1;
3322         }
3323
3324         //vpx_log("Encoder: Decimation Factor: %d \n",cpi->decimation_factor);
3325     }
3326
3327     // The following decimates the frame rate according to a regular pattern (i.e. to 1/2 or 2/3 frame rate)
3328     // This can be used to help prevent buffer under-run in CBR mode. Alternatively it might be desirable in
3329     // some situations to drop frame rate but throw more bits at each frame.
3330     //
3331     // Note that dropping a key frame can be problematic if spatial resampling is also active
3332     if (cpi->decimation_factor > 0)
3333     {
3334         switch (cpi->decimation_factor)
3335         {
3336         case 1:
3337             cpi->per_frame_bandwidth  = cpi->per_frame_bandwidth * 3 / 2;
3338             break;
3339         case 2:
3340             cpi->per_frame_bandwidth  = cpi->per_frame_bandwidth * 5 / 4;
3341             break;
3342         case 3:
3343             cpi->per_frame_bandwidth  = cpi->per_frame_bandwidth * 5 / 4;
3344             break;
3345         }
3346
3347         // Note that we should not throw out a key frame (especially when spatial resampling is enabled).
3348         if ((cm->frame_type == KEY_FRAME)) // && cpi->oxcf.allow_spatial_resampling )
3349         {
3350             cpi->decimation_count = cpi->decimation_factor;
3351         }
3352         else if (cpi->decimation_count > 0)
3353         {
3354             cpi->decimation_count --;
3355
3356             cpi->bits_off_target += cpi->av_per_frame_bandwidth;
3357             if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
3358                 cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
3359
3360             cm->current_video_frame++;
3361             cpi->frames_since_key++;
3362
3363 #if CONFIG_INTERNAL_STATS
3364             cpi->count ++;
3365 #endif
3366
3367             cpi->buffer_level = cpi->bits_off_target;
3368
3369             if (cpi->oxcf.number_of_layers > 1)
3370             {
3371                 unsigned int i;
3372
3373                 // Propagate bits saved by dropping the frame to higher layers
3374                 for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
3375                 {
3376                     LAYER_CONTEXT *lc = &cpi->layer_context[i];
3377                     lc->bits_off_target += cpi->av_per_frame_bandwidth;
3378                     if (lc->bits_off_target > lc->maximum_buffer_size)
3379                         lc->bits_off_target = lc->maximum_buffer_size;
3380                     lc->buffer_level = lc->bits_off_target;
3381                 }
3382             }
3383
3384             return;
3385         }
3386         else
3387             cpi->decimation_count = cpi->decimation_factor;
3388     }
3389
3390     // Decide how big to make the frame
3391     if (!vp8_pick_frame_size(cpi))
3392     {
3393         cm->current_video_frame++;
3394         cpi->frames_since_key++;
3395         return;
3396     }
3397
3398     // Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
3399     // This has a knock on effect on active best quality as well.
3400     // For CBR if the buffer reaches its maximum level then we can no longer
3401     // save up bits for later frames so we might as well use them up
3402     // on the current frame.
3403     if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
3404         (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) && cpi->buffered_mode)
3405     {
3406         int Adjustment = cpi->active_worst_quality / 4;       // Max adjustment is 1/4
3407
3408         if (Adjustment)
3409         {
3410             int buff_lvl_step;
3411
3412             if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size)
3413             {
3414                 buff_lvl_step = (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level) / Adjustment;
3415
3416                 if (buff_lvl_step)
3417                     Adjustment = (cpi->buffer_level - cpi->oxcf.optimal_buffer_level) / buff_lvl_step;
3418                 else
3419                     Adjustment = 0;
3420             }
3421
3422             cpi->active_worst_quality -= Adjustment;
3423
3424             if(cpi->active_worst_quality < cpi->active_best_quality)
3425                 cpi->active_worst_quality = cpi->active_best_quality;
3426         }
3427     }
3428
3429     // Set an active best quality and if necessary active worst quality
3430     // There is some odd behavior for one pass here that needs attention.
3431     if ( (cpi->pass == 2) || (cpi->ni_frames > 150))
3432     {
3433         vp8_clear_system_state();
3434
3435         Q = cpi->active_worst_quality;
3436
3437         if ( cm->frame_type == KEY_FRAME )
3438         {
3439             if ( cpi->pass == 2 )
3440             {
3441                 if (cpi->gfu_boost > 600)
3442                    cpi->active_best_quality = kf_low_motion_minq[Q];
3443                 else
3444                    cpi->active_best_quality = kf_high_motion_minq[Q];
3445
3446                 // Special case for key frames forced because we have reached
3447                 // the maximum key frame interval. Here force the Q to a range
3448                 // based on the ambient Q to reduce the risk of popping
3449                 if ( cpi->this_key_frame_forced )
3450                 {
3451                     if ( cpi->active_best_quality > cpi->avg_frame_qindex * 7/8)
3452                         cpi->active_best_quality = cpi->avg_frame_qindex * 7/8;
3453                     else if ( cpi->active_best_quality < cpi->avg_frame_qindex >> 2 )
3454                         cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
3455                 }
3456             }
3457             // One pass more conservative
3458             else
3459                cpi->active_best_quality = kf_high_motion_minq[Q];
3460         }
3461
3462         else if (cpi->oxcf.number_of_layers==1 &&
3463                 (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame))
3464         {
3465             // Use the lower of cpi->active_worst_quality and recent
3466             // average Q as basis for GF/ARF Q limit unless last frame was
3467             // a key frame.
3468             if ( (cpi->frames_since_key > 1) &&
3469                (cpi->avg_frame_qindex < cpi->active_worst_quality) )
3470             {
3471                 Q = cpi->avg_frame_qindex;
3472             }
3473
3474             // For constrained quality dont allow Q less than the cq level
3475             if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3476                  (Q < cpi->cq_target_quality) )
3477             {
3478                 Q = cpi->cq_target_quality;
3479             }
3480
3481             if ( cpi->pass == 2 )
3482             {
3483                 if ( cpi->gfu_boost > 1000 )
3484                     cpi->active_best_quality = gf_low_motion_minq[Q];
3485                 else if ( cpi->gfu_boost < 400 )
3486                     cpi->active_best_quality = gf_high_motion_minq[Q];
3487                 else
3488                     cpi->active_best_quality = gf_mid_motion_minq[Q];
3489
3490                 // Constrained quality use slightly lower active best.
3491                 if ( cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY )
3492                 {
3493                     cpi->active_best_quality =
3494                         cpi->active_best_quality * 15/16;
3495                 }
3496             }
3497             // One pass more conservative
3498             else
3499                 cpi->active_best_quality = gf_high_motion_minq[Q];
3500         }
3501         else
3502         {
3503             cpi->active_best_quality = inter_minq[Q];
3504
3505             // For the constant/constrained quality mode we dont want
3506             // q to fall below the cq level.
3507             if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3508                 (cpi->active_best_quality < cpi->cq_target_quality) )
3509             {
3510                 // If we are strongly undershooting the target rate in the last
3511                 // frames then use the user passed in cq value not the auto
3512                 // cq value.
3513                 if ( cpi->rolling_actual_bits < cpi->min_frame_bandwidth )
3514                     cpi->active_best_quality = cpi->oxcf.cq_level;
3515                 else
3516                     cpi->active_best_quality = cpi->cq_target_quality;
3517             }
3518         }
3519
3520         // If CBR and the buffer is as full then it is reasonable to allow
3521         // higher quality on the frames to prevent bits just going to waste.
3522         if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
3523         {
3524             // Note that the use of >= here elliminates the risk of a devide
3525             // by 0 error in the else if clause
3526             if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size)
3527                 cpi->active_best_quality = cpi->best_quality;
3528
3529             else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level)
3530             {
3531                 int Fraction = ((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) / (cpi->oxcf.maximum_buffer_size - cpi->oxcf.optimal_buffer_level);
3532                 int min_qadjustment = ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;
3533
3534                 cpi->active_best_quality -= min_qadjustment;
3535             }
3536         }
3537     }
3538     // Make sure constrained quality mode limits are adhered to for the first
3539     // few frames of one pass encodes
3540     else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
3541     {
3542         if ( (cm->frame_type == KEY_FRAME) ||
3543              cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame )
3544         {
3545              cpi->active_best_quality = cpi->best_quality;
3546         }
3547         else if (cpi->active_best_quality < cpi->cq_target_quality)
3548         {
3549             cpi->active_best_quality = cpi->cq_target_quality;
3550         }
3551     }
3552
3553     // Clip the active best and worst quality values to limits
3554     if (cpi->active_worst_quality > cpi->worst_quality)
3555         cpi->active_worst_quality = cpi->worst_quality;
3556
3557     if (cpi->active_best_quality < cpi->best_quality)
3558         cpi->active_best_quality = cpi->best_quality;
3559
3560     if ( cpi->active_worst_quality < cpi->active_best_quality )
3561         cpi->active_worst_quality = cpi->active_best_quality;
3562
3563     // Determine initial Q to try
3564     Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3565     last_zbin_oq = cpi->zbin_over_quant;
3566
3567     // Set highest allowed value for Zbin over quant
3568     if (cm->frame_type == KEY_FRAME)
3569         zbin_oq_high = 0; //ZBIN_OQ_MAX/16
3570     else if ((cpi->oxcf.number_of_layers == 1) && ((cm->refresh_alt_ref_frame ||
3571               (cm->refresh_golden_frame && !cpi->source_alt_ref_active))))
3572     {
3573           zbin_oq_high = 16;
3574     }
3575     else
3576         zbin_oq_high = ZBIN_OQ_MAX;
3577
3578     // Setup background Q adjustment for error resilient mode.
3579     // For multi-layer encodes only enable this for the base layer.
3580     if (cpi->cyclic_refresh_mode_enabled && (cpi->current_layer==0))
3581         cyclic_background_refresh(cpi, Q, 0);
3582
3583     vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3584
3585     // Limit Q range for the adaptive loop.
3586     bottom_index = cpi->active_best_quality;
3587     top_index    = cpi->active_worst_quality;
3588     q_low  = cpi->active_best_quality;
3589     q_high = cpi->active_worst_quality;
3590
3591     vp8_save_coding_context(cpi);
3592
3593     loop_count = 0;
3594
3595
3596     scale_and_extend_source(cpi->un_scaled_source, cpi);
3597 #if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC
3598
3599     if (cpi->oxcf.noise_sensitivity > 0)
3600     {
3601         unsigned char *src;
3602         int l = 0;
3603
3604         switch (cpi->oxcf.noise_sensitivity)
3605         {
3606         case 1:
3607             l = 20;
3608             break;
3609         case 2:
3610             l = 40;
3611             break;
3612         case 3:
3613             l = 60;
3614             break;
3615         case 4:
3616             l = 80;
3617             break;
3618         case 5:
3619             l = 100;
3620             break;
3621         case 6:
3622             l = 150;
3623             break;
3624         }
3625
3626
3627         if (cm->frame_type == KEY_FRAME)
3628         {
3629             vp8_de_noise(cpi->Source, cpi->Source, l , 1,  0, RTCD(postproc));
3630         }
3631         else
3632         {
3633             vp8_de_noise(cpi->Source, cpi->Source, l , 1,  0, RTCD(postproc));
3634
3635             src = cpi->Source->y_buffer;
3636
3637             if (cpi->Source->y_stride < 0)
3638             {
3639                 src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
3640             }
3641         }
3642     }
3643
3644 #endif
3645
3646 #ifdef OUTPUT_YUV_SRC
3647     vp8_write_yuv_frame(cpi->Source);
3648 #endif
3649
3650     do
3651     {
3652         vp8_clear_system_state();  //__asm emms;
3653
3654         /*
3655         if(cpi->is_src_frame_alt_ref)
3656             Q = 127;
3657             */
3658
3659         vp8_set_quantizer(cpi, Q);
3660         this_q = Q;
3661
3662         // setup skip prob for costing in mode/mv decision
3663         if (cpi->common.mb_no_coeff_skip)
3664         {
3665             cpi->prob_skip_false = cpi->base_skip_false_prob[Q];
3666
3667             if (cm->frame_type != KEY_FRAME)
3668             {
3669                 if (cpi->common.refresh_alt_ref_frame)
3670                 {
3671                     if (cpi->last_skip_false_probs[2] != 0)
3672                         cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3673
3674                     /*
3675                                         if(cpi->last_skip_false_probs[2]!=0 && abs(Q- cpi->last_skip_probs_q[2])<=16 )
3676                        cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3677                                         else if (cpi->last_skip_false_probs[2]!=0)
3678                        cpi->prob_skip_false = (cpi->last_skip_false_probs[2]  + cpi->prob_skip_false ) / 2;
3679                        */
3680                 }
3681                 else if (cpi->common.refresh_golden_frame)
3682                 {
3683                     if (cpi->last_skip_false_probs[1] != 0)
3684                         cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3685
3686                     /*
3687                                         if(cpi->last_skip_false_probs[1]!=0 && abs(Q- cpi->last_skip_probs_q[1])<=16 )
3688                        cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3689                                         else if (cpi->last_skip_false_probs[1]!=0)
3690                        cpi->prob_skip_false = (cpi->last_skip_false_probs[1]  + cpi->prob_skip_false ) / 2;
3691                        */
3692                 }
3693                 else
3694                 {
3695                     if (cpi->last_skip_false_probs[0] != 0)
3696                         cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3697
3698                     /*
3699                     if(cpi->last_skip_false_probs[0]!=0 && abs(Q- cpi->last_skip_probs_q[0])<=16 )
3700                         cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3701                     else if(cpi->last_skip_false_probs[0]!=0)
3702                         cpi->prob_skip_false = (cpi->last_skip_false_probs[0]  + cpi->prob_skip_false ) / 2;
3703                         */
3704                 }
3705
3706                 //as this is for cost estimate, let's make sure it does not go extreme eitehr way
3707                 if (cpi->prob_skip_false < 5)
3708                     cpi->prob_skip_false = 5;
3709
3710                 if (cpi->prob_skip_false > 250)
3711                     cpi->prob_skip_false = 250;
3712
3713                 if (cpi->oxcf.number_of_layers == 1 && cpi->is_src_frame_alt_ref)
3714                     cpi->prob_skip_false = 1;
3715             }
3716
3717 #if 0
3718
3719             if (cpi->pass != 1)
3720             {
3721                 FILE *f = fopen("skip.stt", "a");
3722                 fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
3723                 fclose(f);
3724             }
3725
3726 #endif
3727
3728         }
3729
3730         if (cm->frame_type == KEY_FRAME)
3731         {
3732             resize_key_frame(cpi);
3733             vp8_setup_key_frame(cpi);
3734         }
3735
3736 #if CONFIG_MULTITHREAD
3737         /*  wait for loopfilter thread done (for last picture)
3738          *  don't do it for first frame, re-code and when PSNR is calculated
3739          */
3740         if (cpi->b_multi_threaded && cm->current_video_frame && (!Loop) &&
3741                 (!cpi->b_calculate_psnr))
3742         {
3743             sem_wait(&cpi->h_event_end_lpf);
3744         }
3745 #endif
3746
3747         // transform / motion compensation build reconstruction frame
3748         vp8_encode_frame(cpi);
3749
3750         cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
3751         cpi->projected_frame_size = (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
3752
3753         vp8_clear_system_state();  //__asm emms;
3754
3755         // Test to see if the stats generated for this frame indicate that we should have coded a key frame
3756         // (assuming that we didn't)!
3757         if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME)
3758         {
3759             int key_frame_decision = decide_key_frame(cpi);
3760
3761             if (cpi->compressor_speed == 2)
3762             {
3763                 /* we don't do re-encoding in realtime mode
3764                  * if key frame is decided than we force it on next frame */
3765                 cpi->force_next_frame_intra = key_frame_decision;
3766             }
3767             else if (key_frame_decision)
3768             {
3769                 // Reset all our sizing numbers and recode
3770                 cm->frame_type = KEY_FRAME;
3771
3772                 vp8_pick_frame_size(cpi);
3773
3774                 // Clear the Alt reference frame active flag when we have a key frame
3775                 cpi->source_alt_ref_active = 0;
3776
3777                 // Reset the loop filter deltas and segmentation map
3778                 setup_features(cpi);
3779
3780                 // If segmentation is enabled force a map update for key frames
3781                 if (cpi->mb.e_mbd.segmentation_enabled)
3782                 {
3783                     cpi->mb.e_mbd.update_mb_segmentation_map = 1;
3784                     cpi->mb.e_mbd.update_mb_segmentation_data = 1;
3785                 }
3786
3787                 vp8_restore_coding_context(cpi);
3788
3789                 Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3790
3791                 vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit, &frame_over_shoot_limit);
3792
3793                 // Limit Q range for the adaptive loop.
3794                 bottom_index = cpi->active_best_quality;
3795                 top_index    = cpi->active_worst_quality;
3796                 q_low  = cpi->active_best_quality;
3797                 q_high = cpi->active_worst_quality;
3798
3799                 loop_count++;
3800                 Loop = 1;
3801
3802                 continue;
3803             }
3804         }
3805
3806         vp8_clear_system_state();
3807
3808         if (frame_over_shoot_limit == 0)
3809             frame_over_shoot_limit = 1;
3810
3811         // Are we are overshooting and up against the limit of active max Q.
3812         if (((cpi->pass != 2) || (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
3813             (Q == cpi->active_worst_quality)                     &&
3814             (cpi->active_worst_quality < cpi->worst_quality)      &&
3815             (cpi->projected_frame_size > frame_over_shoot_limit))
3816         {
3817             int over_size_percent = ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) / frame_over_shoot_limit;
3818
3819             // If so is there any scope for relaxing it
3820             while ((cpi->active_worst_quality < cpi->worst_quality) && (over_size_percent > 0))
3821             {
3822                 cpi->active_worst_quality++;
3823                 top_index = cpi->active_worst_quality;
3824                 over_size_percent = (int)(over_size_percent * 0.96);        // Assume 1 qstep = about 4% on frame size.
3825             }
3826
3827             // If we have updated the active max Q do not call vp8_update_rate_correction_factors() this loop.
3828             active_worst_qchanged = 1;
3829         }
3830         else
3831             active_worst_qchanged = 0;
3832
3833 #if !(CONFIG_REALTIME_ONLY)
3834         // Special case handling for forced key frames
3835         if ( (cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced )
3836         {
3837             int last_q = Q;
3838             int kf_err = vp8_calc_ss_err(cpi->Source,
3839                                          &cm->yv12_fb[cm->new_fb_idx],
3840                                          IF_RTCD(&cpi->rtcd.variance));
3841
3842             // The key frame is not good enough
3843             if ( kf_err > ((cpi->ambient_err * 7) >> 3) )
3844             {
3845                 // Lower q_high
3846                 q_high = (Q > q_low) ? (Q - 1) : q_low;
3847
3848                 // Adjust Q
3849                 Q = (q_high + q_low) >> 1;
3850             }
3851             // The key frame is much better than the previous frame
3852             else if ( kf_err < (cpi->ambient_err >> 1) )
3853             {
3854                 // Raise q_low
3855                 q_low = (Q < q_high) ? (Q + 1) : q_high;
3856
3857                 // Adjust Q
3858                 Q = (q_high + q_low + 1) >> 1;
3859             }
3860
3861             // Clamp Q to upper and lower limits:
3862             if (Q > q_high)
3863                 Q = q_high;
3864             else if (Q < q_low)
3865                 Q = q_low;
3866
3867             Loop = Q != last_q;
3868         }
3869
3870         // Is the projected frame size out of range and are we allowed to attempt to recode.
3871         else if ( recode_loop_test( cpi,
3872                                frame_over_shoot_limit, frame_under_shoot_limit,
3873                                Q, top_index, bottom_index ) )
3874         {
3875             int last_q = Q;
3876             int Retries = 0;
3877
3878             // Frame size out of permitted range:
3879             // Update correction factor & compute new Q to try...
3880
3881             // Frame is too large
3882             if (cpi->projected_frame_size > cpi->this_frame_target)
3883             {
3884                 //if ( cpi->zbin_over_quant == 0 )
3885                 q_low = (Q < q_high) ? (Q + 1) : q_high; // Raise Qlow as to at least the current value
3886
3887                 if (cpi->zbin_over_quant > 0)            // If we are using over quant do the same for zbin_oq_low
3888                     zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
3889
3890                 //if ( undershoot_seen || (Q == MAXQ) )
3891                 if (undershoot_seen)
3892                 {
3893                     // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3894                     if (!active_worst_qchanged)
3895                         vp8_update_rate_correction_factors(cpi, 1);
3896
3897                     Q = (q_high + q_low + 1) / 2;
3898
3899                     // Adjust cpi->zbin_over_quant (only allowed when Q is max)
3900                     if (Q < MAXQ)
3901                         cpi->zbin_over_quant = 0;
3902                     else
3903                     {
3904                         zbin_oq_low = (cpi->zbin_over_quant < zbin_oq_high) ? (cpi->zbin_over_quant + 1) : zbin_oq_high;
3905                         cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
3906                     }
3907                 }
3908                 else
3909                 {
3910                     // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3911                     if (!active_worst_qchanged)
3912                         vp8_update_rate_correction_factors(cpi, 0);
3913
3914                     Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3915
3916                     while (((Q < q_low) || (cpi->zbin_over_quant < zbin_oq_low)) && (Retries < 10))
3917                     {
3918                         vp8_update_rate_correction_factors(cpi, 0);
3919                         Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3920                         Retries ++;
3921                     }
3922                 }
3923
3924                 overshoot_seen = 1;
3925             }
3926             // Frame is too small
3927             else
3928             {
3929                 if (cpi->zbin_over_quant == 0)
3930                     q_high = (Q > q_low) ? (Q - 1) : q_low; // Lower q_high if not using over quant
3931                 else                                    // else lower zbin_oq_high
3932                     zbin_oq_high = (cpi->zbin_over_quant > zbin_oq_low) ? (cpi->zbin_over_quant - 1) : zbin_oq_low;
3933
3934                 if (overshoot_seen)
3935                 {
3936                     // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3937                     if (!active_worst_qchanged)
3938                         vp8_update_rate_correction_factors(cpi, 1);
3939
3940                     Q = (q_high + q_low) / 2;
3941
3942                     // Adjust cpi->zbin_over_quant (only allowed when Q is max)
3943                     if (Q < MAXQ)
3944                         cpi->zbin_over_quant = 0;
3945                     else
3946                         cpi->zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
3947                 }
3948                 else
3949                 {
3950                     // Update rate_correction_factor unless cpi->active_worst_quality has changed.
3951                     if (!active_worst_qchanged)
3952                         vp8_update_rate_correction_factors(cpi, 0);
3953
3954                     Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3955
3956                     // Special case reset for qlow for constrained quality.
3957                     // This should only trigger where there is very substantial
3958                     // undershoot on a frame and the auto cq level is above
3959                     // the user passsed in value.
3960                     if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3961                          (Q < q_low) )
3962                     {
3963                         q_low = Q;
3964                     }
3965
3966                     while (((Q > q_high) || (cpi->zbin_over_quant > zbin_oq_high)) && (Retries < 10))
3967                     {
3968                         vp8_update_rate_correction_factors(cpi, 0);
3969                         Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3970                         Retries ++;
3971                     }
3972                 }
3973
3974                 undershoot_seen = 1;
3975             }
3976
3977             // Clamp Q to upper and lower limits:
3978             if (Q > q_high)
3979                 Q = q_high;
3980             else if (Q < q_low)
3981                 Q = q_low;
3982
3983             // Clamp cpi->zbin_over_quant
3984             cpi->zbin_over_quant = (cpi->zbin_over_quant < zbin_oq_low) ? zbin_oq_low : (cpi->zbin_over_quant > zbin_oq_high) ? zbin_oq_high : cpi->zbin_over_quant;
3985
3986             //Loop = (Q != last_q) || (last_zbin_oq != cpi->zbin_over_quant);
3987             Loop = Q != last_q;
3988             last_zbin_oq = cpi->zbin_over_quant;
3989         }
3990         else
3991 #endif
3992             Loop = 0;
3993
3994         if (cpi->is_src_frame_alt_ref)
3995             Loop = 0;
3996
3997         if (Loop == 1)
3998         {
3999             vp8_restore_coding_context(cpi);
4000             loop_count++;
4001 #if CONFIG_INTERNAL_STATS
4002             cpi->tot_recode_hits++;
4003 #endif
4004         }
4005     }
4006     while (Loop == 1);
4007
4008 #if 0
4009     // Experimental code for lagged and one pass
4010     // Update stats used for one pass GF selection
4011     {
4012         /*
4013             int frames_so_far;
4014             double frame_intra_error;
4015             double frame_coded_error;
4016             double frame_pcnt_inter;
4017             double frame_pcnt_motion;
4018             double frame_mvr;
4019             double frame_mvr_abs;
4020             double frame_mvc;
4021             double frame_mvc_abs;
4022         */
4023
4024         cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
4025         cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
4026         cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
4027     }
4028 #endif
4029
4030     // Special case code to reduce pulsing when key frames are forced at a
4031     // fixed interval. Note the reconstruction error if it is the frame before
4032     // the force key frame
4033     if ( cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0) )
4034     {
4035         cpi->ambient_err = vp8_calc_ss_err(cpi->Source,
4036                                            &cm->yv12_fb[cm->new_fb_idx],
4037                                            IF_RTCD(&cpi->rtcd.variance));
4038     }
4039
4040     /* This frame's MVs are saved and will be used in next frame's MV predictor.
4041      * Last frame has one more line(add to bottom) and one more column(add to
4042      * right) than cm->mip. The edge elements are initialized to 0.
4043      */
4044 #if CONFIG_MULTI_RES_ENCODING
4045     if(!cpi->oxcf.mr_encoder_id && cm->show_frame)
4046 #else
4047     if(cm->show_frame)   /* do not save for altref frame */
4048 #endif
4049     {
4050         int mb_row;
4051         int mb_col;
4052         /* Point to beginning of allocated MODE_INFO arrays. */
4053         MODE_INFO *tmp = cm->mip;
4054
4055         if(cm->frame_type != KEY_FRAME)
4056         {
4057             for (mb_row = 0; mb_row < cm->mb_rows+1; mb_row ++)
4058             {
4059                 for (mb_col = 0; mb_col < cm->mb_cols+1; mb_col ++)
4060                 {
4061                     if(tmp->mbmi.ref_frame != INTRA_FRAME)
4062                         cpi->lfmv[mb_col + mb_row*(cm->mode_info_stride+1)].as_int = tmp->mbmi.mv.as_int;
4063
4064                     cpi->lf_ref_frame_sign_bias[mb_col + mb_row*(cm->mode_info_stride+1)] = cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
4065                     cpi->lf_ref_frame[mb_col + mb_row*(cm->mode_info_stride+1)] = tmp->mbmi.ref_frame;
4066                     tmp++;
4067                 }
4068             }
4069         }
4070     }
4071
4072 #if CONFIG_MULTI_RES_ENCODING
4073     vp8_cal_dissimilarity(cpi);
4074 #endif
4075
4076     // Update the GF useage maps.
4077     // This is done after completing the compression of a frame when all
4078     // modes etc. are finalized but before loop filter
4079     if (cpi->oxcf.number_of_layers == 1)
4080         vp8_update_gf_useage_maps(cpi, cm, &cpi->mb);
4081
4082     if (cm->frame_type == KEY_FRAME)
4083         cm->refresh_last_frame = 1;
4084
4085 #if 0
4086     {
4087         FILE *f = fopen("gfactive.stt", "a");
4088         fprintf(f, "%8d %8d %8d %8d %8d\n", cm->current_video_frame, (100 * cpi->gf_active_count) / (cpi->common.mb_rows * cpi->common.mb_cols), cpi->this_iiratio, cpi->next_iiratio, cm->refresh_golden_frame);
4089         fclose(f);
4090     }
4091 #endif
4092
4093     // For inter frames the current default behavior is that when
4094     // cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
4095     // This is purely an encoder decision at present.
4096     if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame)
4097         cm->copy_buffer_to_arf  = 2;
4098     else
4099         cm->copy_buffer_to_arf  = 0;
4100
4101     cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
4102
4103 #if CONFIG_MULTITHREAD
4104     if (cpi->b_multi_threaded)
4105     {
4106         sem_post(&cpi->h_event_start_lpf); /* start loopfilter in separate thread */
4107     }
4108     else
4109 #endif
4110     {
4111         loopfilter_frame(cpi, cm);
4112     }
4113
4114     update_reference_frames(cm);
4115
4116     if (cpi->oxcf.error_resilient_mode)
4117     {
4118         cm->refresh_entropy_probs = 0;
4119     }
4120
4121 #if CONFIG_MULTITHREAD
4122     /* wait that filter_level is picked so that we can continue with stream packing */
4123     if (cpi->b_multi_threaded)
4124         sem_wait(&cpi->h_event_end_lpf);
4125 #endif
4126
4127     // build the bitstream
4128     vp8_pack_bitstream(cpi, dest, dest_end, size);
4129
4130 #if CONFIG_MULTITHREAD
4131     /* if PSNR packets are generated we have to wait for the lpf */
4132     if (cpi->b_multi_threaded && cpi->b_calculate_psnr)
4133     {
4134         sem_wait(&cpi->h_event_end_lpf);
4135     }
4136 #endif
4137
4138     /* Move storing frame_type out of the above loop since it is also
4139      * needed in motion search besides loopfilter */
4140     cm->last_frame_type = cm->frame_type;
4141
4142     // Update rate control heuristics
4143     cpi->total_byte_count += (*size);
4144     cpi->projected_frame_size = (*size) << 3;
4145
4146     if (cpi->oxcf.number_of_layers > 1)
4147     {
4148         unsigned int i;
4149         for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
4150           cpi->layer_context[i].total_byte_count += (*size);
4151     }
4152
4153     if (!active_worst_qchanged)
4154         vp8_update_rate_correction_factors(cpi, 2);
4155
4156     cpi->last_q[cm->frame_type] = cm->base_qindex;
4157
4158     if (cm->frame_type == KEY_FRAME)
4159     {
4160         vp8_adjust_key_frame_context(cpi);
4161     }
4162
4163     // Keep a record of ambient average Q.
4164     if (cm->frame_type != KEY_FRAME)
4165         cpi->avg_frame_qindex = (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
4166
4167     // Keep a record from which we can calculate the average Q excluding GF updates and key frames
4168     if ((cm->frame_type != KEY_FRAME) && ((cpi->oxcf.number_of_layers > 1) ||
4169         (!cm->refresh_golden_frame && !cm->refresh_alt_ref_frame)))
4170     {
4171         cpi->ni_frames++;
4172
4173         // Calculate the average Q for normal inter frames (not key or GFU
4174         // frames).
4175         if ( cpi->pass == 2 )
4176         {
4177             cpi->ni_tot_qi += Q;
4178             cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4179         }
4180         else
4181         {
4182             // Damp value for first few frames
4183             if (cpi->ni_frames > 150 )
4184             {
4185                 cpi->ni_tot_qi += Q;
4186                 cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4187             }
4188             // For one pass, early in the clip ... average the current frame Q
4189             // value with the worstq entered by the user as a dampening measure
4190             else
4191             {
4192                 cpi->ni_tot_qi += Q;
4193                 cpi->ni_av_qi = ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
4194             }
4195
4196             // If the average Q is higher than what was used in the last frame
4197             // (after going through the recode loop to keep the frame size within range)
4198             // then use the last frame value - 1.
4199             // The -1 is designed to stop Q and hence the data rate, from progressively
4200             // falling away during difficult sections, but at the same time reduce the number of
4201             // itterations around the recode loop.
4202             if (Q > cpi->ni_av_qi)
4203                 cpi->ni_av_qi = Q - 1;
4204         }
4205     }
4206
4207 #if 0
4208
4209     // If the frame was massively oversize and we are below optimal buffer level drop next frame
4210     if ((cpi->drop_frames_allowed) &&
4211         (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
4212         (cpi->buffer_level < cpi->oxcf.drop_frames_water_mark * cpi->oxcf.optimal_buffer_level / 100) &&
4213         (cpi->projected_frame_size > (4 * cpi->this_frame_target)))
4214     {
4215         cpi->drop_frame = 1;
4216     }
4217
4218 #endif
4219
4220     // Set the count for maximum consecutive dropped frames based upon the ratio of
4221     // this frame size to the target average per frame bandwidth.
4222     // (cpi->av_per_frame_bandwidth > 0) is just a sanity check to prevent / 0.
4223     if (cpi->drop_frames_allowed && (cpi->av_per_frame_bandwidth > 0))
4224     {
4225         cpi->max_drop_count = cpi->projected_frame_size / cpi->av_per_frame_bandwidth;
4226
4227         if (cpi->max_drop_count > cpi->max_consec_dropped_frames)
4228             cpi->max_drop_count = cpi->max_consec_dropped_frames;
4229     }
4230
4231     // Update the buffer level variable.
4232     // Non-viewable frames are a special case and are treated as pure overhead.
4233     if ( !cm->show_frame )
4234         cpi->bits_off_target -= cpi->projected_frame_size;
4235     else
4236         cpi->bits_off_target += cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
4237
4238     // Clip the buffer level to the maximum specified buffer size
4239     if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
4240         cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
4241
4242     // Rolling monitors of whether we are over or underspending used to help regulate min and Max Q in two pass.
4243     cpi->rolling_target_bits = ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
4244     cpi->rolling_actual_bits = ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
4245     cpi->long_rolling_target_bits = ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
4246     cpi->long_rolling_actual_bits = ((cpi->long_rolling_actual_bits * 31) + cpi->projected_frame_size + 16) / 32;
4247
4248     // Actual bits spent
4249     cpi->total_actual_bits += cpi->projected_frame_size;
4250
4251     // Debug stats
4252     cpi->total_target_vs_actual += (cpi->this_frame_target - cpi->projected_frame_size);
4253
4254     cpi->buffer_level = cpi->bits_off_target;
4255
4256     // Propagate values to higher temporal layers
4257     if (cpi->oxcf.number_of_layers > 1)
4258     {
4259         unsigned int i;
4260
4261         for (i=cpi->current_layer+1; i<cpi->oxcf.number_of_layers; i++)
4262         {
4263             LAYER_CONTEXT *lc = &cpi->layer_context[i];
4264             int bits_off_for_this_layer = lc->target_bandwidth / lc->frame_rate
4265                                                 - cpi->projected_frame_size;
4266
4267             lc->bits_off_target += bits_off_for_this_layer;
4268
4269             // Clip buffer level to maximum buffer size for the layer
4270             if (lc->bits_off_target > lc->maximum_buffer_size)
4271                 lc->bits_off_target = lc->maximum_buffer_size;
4272
4273             lc->total_actual_bits += cpi->projected_frame_size;
4274             lc->total_target_vs_actual += bits_off_for_this_layer;
4275             lc->buffer_level = lc->bits_off_target;
4276         }
4277     }
4278
4279     // Update bits left to the kf and gf groups to account for overshoot or undershoot on these frames
4280     if (cm->frame_type == KEY_FRAME)
4281     {
4282         cpi->twopass.kf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4283
4284         if (cpi->twopass.kf_group_bits < 0)
4285             cpi->twopass.kf_group_bits = 0 ;
4286     }
4287     else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4288     {
4289         cpi->twopass.gf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
4290
4291         if (cpi->twopass.gf_group_bits < 0)
4292             cpi->twopass.gf_group_bits = 0 ;
4293     }
4294
4295     if (cm->frame_type != KEY_FRAME)
4296     {
4297         if (cpi->common.refresh_alt_ref_frame)
4298         {
4299             cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
4300             cpi->last_skip_probs_q[2] = cm->base_qindex;
4301         }
4302         else if (cpi->common.refresh_golden_frame)
4303         {
4304             cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
4305             cpi->last_skip_probs_q[1] = cm->base_qindex;
4306         }
4307         else
4308         {
4309             cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
4310             cpi->last_skip_probs_q[0] = cm->base_qindex;
4311
4312             //update the baseline
4313             cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
4314
4315         }
4316     }
4317
4318 #if 0 && CONFIG_INTERNAL_STATS
4319     {
4320         FILE *f = fopen("tmp.stt", "a");
4321
4322         vp8_clear_system_state();  //__asm emms;
4323
4324         if (cpi->twopass.total_left_stats.coded_error != 0.0)
4325             fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4326                        "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4327                        "%10.3f %8d\n",
4328                        cpi->common.current_video_frame, cpi->this_frame_target,
4329                        cpi->projected_frame_size,
4330                        (cpi->projected_frame_size - cpi->this_frame_target),
4331                        (int)cpi->total_target_vs_actual,
4332                        cpi->buffer_level,
4333                        (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4334                        (int)cpi->total_actual_bits, cm->base_qindex,
4335                        cpi->active_best_quality, cpi->active_worst_quality,
4336                        cpi->ni_av_qi, cpi->cq_target_quality,
4337                        cpi->zbin_over_quant,
4338                        //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4339                        cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4340                        cm->frame_type, cpi->gfu_boost,
4341                        cpi->twopass.est_max_qcorrection_factor,
4342                        (int)cpi->twopass.bits_left,
4343                        cpi->twopass.total_left_stats.coded_error,
4344                        (double)cpi->twopass.bits_left /
4345                            cpi->twopass.total_left_stats.coded_error,
4346                        cpi->tot_recode_hits);
4347         else
4348             fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d %6d %6d"
4349                        "%6d %6d %6d %5d %5d %5d %8d %8.2f %10d %10.3f"
4350                        "%8d\n",
4351                        cpi->common.current_video_frame,
4352                        cpi->this_frame_target, cpi->projected_frame_size,
4353                        (cpi->projected_frame_size - cpi->this_frame_target),
4354                        (int)cpi->total_target_vs_actual,
4355                        cpi->buffer_level,
4356                        (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4357                        (int)cpi->total_actual_bits, cm->base_qindex,
4358                        cpi->active_best_quality, cpi->active_worst_quality,
4359                        cpi->ni_av_qi, cpi->cq_target_quality,
4360                        cpi->zbin_over_quant,
4361                        //cpi->avg_frame_qindex, cpi->zbin_over_quant,
4362                        cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4363                        cm->frame_type, cpi->gfu_boost,
4364                        cpi->twopass.est_max_qcorrection_factor,
4365                        (int)cpi->twopass.bits_left,
4366                        cpi->twopass.total_left_stats.coded_error,
4367                        cpi->tot_recode_hits);
4368
4369         fclose(f);
4370
4371         {
4372             FILE *fmodes = fopen("Modes.stt", "a");
4373             int i;
4374
4375             fprintf(fmodes, "%6d:%1d:%1d:%1d ",
4376                         cpi->common.current_video_frame,
4377                         cm->frame_type, cm->refresh_golden_frame,
4378                         cm->refresh_alt_ref_frame);
4379
4380             for (i = 0; i < MAX_MODES; i++)
4381                 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
4382
4383             fprintf(fmodes, "\n");
4384
4385             fclose(fmodes);
4386         }
4387     }
4388
4389 #endif
4390
4391     // If this was a kf or Gf note the Q
4392     if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame || cm->refresh_alt_ref_frame)
4393         cm->last_kf_gf_q = cm->base_qindex;
4394
4395     if (cm->refresh_golden_frame == 1)
4396         cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
4397     else
4398         cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
4399
4400     if (cm->refresh_alt_ref_frame == 1)
4401         cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
4402     else
4403         cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
4404
4405
4406     if (cm->refresh_last_frame & cm->refresh_golden_frame) // both refreshed
4407         cpi->gold_is_last = 1;
4408     else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4409         cpi->gold_is_last = 0;
4410
4411     if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) // both refreshed
4412         cpi->alt_is_last = 1;
4413     else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) // 1 refreshed but not the other
4414         cpi->alt_is_last = 0;
4415
4416     if (cm->refresh_alt_ref_frame & cm->refresh_golden_frame) // both refreshed
4417         cpi->gold_is_alt = 1;
4418     else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) // 1 refreshed but not the other
4419         cpi->gold_is_alt = 0;
4420
4421     cpi->ref_frame_flags = VP8_ALT_FLAG | VP8_GOLD_FLAG | VP8_LAST_FLAG;
4422
4423     if (cpi->gold_is_last)
4424         cpi->ref_frame_flags &= ~VP8_GOLD_FLAG;
4425
4426     if (cpi->alt_is_last)
4427         cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4428
4429     if (cpi->gold_is_alt)
4430         cpi->ref_frame_flags &= ~VP8_ALT_FLAG;
4431
4432
4433     if (!cpi->oxcf.error_resilient_mode)
4434     {
4435         if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame && (cm->frame_type != KEY_FRAME))
4436             // Update the alternate reference frame stats as appropriate.
4437             update_alt_ref_frame_stats(cpi);
4438         else
4439             // Update the Golden frame stats as appropriate.
4440             update_golden_frame_stats(cpi);
4441     }
4442
4443     if (cm->frame_type == KEY_FRAME)
4444     {
4445         // Tell the caller that the frame was coded as a key frame
4446         *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
4447
4448         // As this frame is a key frame  the next defaults to an inter frame.
4449         cm->frame_type = INTER_FRAME;
4450
4451         cpi->last_frame_percent_intra = 100;
4452     }
4453     else
4454     {
4455         *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
4456
4457         cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
4458     }
4459
4460     // Clear the one shot update flags for segmentation map and mode/ref loop filter deltas.
4461     cpi->mb.e_mbd.update_mb_segmentation_map = 0;
4462     cpi->mb.e_mbd.update_mb_segmentation_data = 0;
4463     cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
4464
4465
4466     // Dont increment frame counters if this was an altref buffer update not a real frame
4467     if (cm->show_frame)
4468     {
4469         cm->current_video_frame++;
4470         cpi->frames_since_key++;
4471     }
4472
4473     // reset to normal state now that we are done.
4474
4475
4476
4477 #if 0
4478     {
4479         char filename[512];
4480         FILE *recon_file;
4481         sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
4482         recon_file = fopen(filename, "wb");
4483         fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
4484                cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
4485         fclose(recon_file);
4486     }
4487 #endif
4488
4489     // DEBUG
4490     //vp8_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show);
4491
4492
4493 }
4494
4495
4496 static void check_gf_quality(VP8_COMP *cpi)
4497 {
4498     VP8_COMMON *cm = &cpi->common;
4499     int gf_active_pct = (100 * cpi->gf_active_count) / (cm->mb_rows * cm->mb_cols);
4500     int gf_ref_usage_pct = (cpi->count_mb_ref_frame_usage[GOLDEN_FRAME] * 100) / (cm->mb_rows * cm->mb_cols);
4501     int last_ref_zz_useage = (cpi->inter_zz_count * 100) / (cm->mb_rows * cm->mb_cols);
4502
4503     // Gf refresh is not currently being signalled
4504     if (cpi->gf_update_recommended == 0)
4505     {
4506         if (cpi->common.frames_since_golden > 7)
4507         {
4508             // Low use of gf
4509             if ((gf_active_pct < 10) || ((gf_active_pct + gf_ref_usage_pct) < 15))
4510             {
4511                 // ...but last frame zero zero usage is reasonbable so a new gf might be appropriate
4512                 if (last_ref_zz_useage >= 25)
4513                 {
4514                     cpi->gf_bad_count ++;
4515
4516                     if (cpi->gf_bad_count >= 8)   // Check that the condition is stable
4517                     {
4518                         cpi->gf_update_recommended = 1;
4519                         cpi->gf_bad_count = 0;
4520                     }
4521                 }
4522                 else
4523                     cpi->gf_bad_count = 0;        // Restart count as the background is not stable enough
4524             }
4525             else
4526                 cpi->gf_bad_count = 0;            // Gf useage has picked up so reset count
4527         }
4528     }
4529     // If the signal is set but has not been read should we cancel it.
4530     else if (last_ref_zz_useage < 15)
4531     {
4532         cpi->gf_update_recommended = 0;
4533         cpi->gf_bad_count = 0;
4534     }
4535
4536 #if 0
4537     {
4538         FILE *f = fopen("gfneeded.stt", "a");
4539         fprintf(f, "%10d %10d %10d %10d %10ld \n",
4540                 cm->current_video_frame,
4541                 cpi->common.frames_since_golden,
4542                 gf_active_pct, gf_ref_usage_pct,
4543                 cpi->gf_update_recommended);
4544         fclose(f);
4545     }
4546
4547 #endif
4548 }
4549
4550 #if !(CONFIG_REALTIME_ONLY)
4551 static void Pass2Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned char * dest_end, unsigned int *frame_flags)
4552 {
4553
4554     if (!cpi->common.refresh_alt_ref_frame)
4555         vp8_second_pass(cpi);
4556
4557     encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
4558     cpi->twopass.bits_left -= 8 * *size;
4559
4560     if (!cpi->common.refresh_alt_ref_frame)
4561     {
4562         double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
4563             *cpi->oxcf.two_pass_vbrmin_section / 100);
4564         cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->frame_rate);
4565     }
4566 }
4567 #endif
4568
4569 //For ARM NEON, d8-d15 are callee-saved registers, and need to be saved by us.
4570 #if HAVE_ARMV7
4571 extern void vp8_push_neon(int64_t *store);
4572 extern void vp8_pop_neon(int64_t *store);
4573 #endif
4574
4575
4576 int vp8_receive_raw_frame(VP8_COMP *cpi, unsigned int frame_flags, YV12_BUFFER_CONFIG *sd, int64_t time_stamp, int64_t end_time)
4577 {
4578 #if HAVE_ARMV7
4579     int64_t store_reg[8];
4580 #endif
4581     VP8_COMMON            *cm = &cpi->common;
4582     struct vpx_usec_timer  timer;
4583     int                    res = 0;
4584
4585 #if HAVE_ARMV7
4586 #if CONFIG_RUNTIME_CPU_DETECT
4587     if (cm->rtcd.flags & HAS_NEON)
4588 #endif
4589     {
4590         vp8_push_neon(store_reg);
4591     }
4592 #endif
4593
4594     vpx_usec_timer_start(&timer);
4595     if(vp8_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4596                           frame_flags, cpi->active_map_enabled ? cpi->active_map : NULL))
4597         res = -1;
4598     cm->clr_type = sd->clrtype;
4599     vpx_usec_timer_mark(&timer);
4600     cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4601
4602 #if HAVE_ARMV7
4603 #if CONFIG_RUNTIME_CPU_DETECT
4604     if (cm->rtcd.flags & HAS_NEON)
4605 #endif
4606     {
4607         vp8_pop_neon(store_reg);
4608     }
4609 #endif
4610
4611     return res;
4612 }
4613
4614
4615 static int frame_is_reference(const VP8_COMP *cpi)
4616 {
4617     const VP8_COMMON *cm = &cpi->common;
4618     const MACROBLOCKD *xd = &cpi->mb.e_mbd;
4619
4620     return cm->frame_type == KEY_FRAME || cm->refresh_last_frame
4621            || cm->refresh_golden_frame || cm->refresh_alt_ref_frame
4622            || cm->copy_buffer_to_gf || cm->copy_buffer_to_arf
4623            || cm->refresh_entropy_probs
4624            || xd->mode_ref_lf_delta_update
4625            || xd->update_mb_segmentation_map || xd->update_mb_segmentation_data;
4626 }
4627
4628
4629 int vp8_get_compressed_data(VP8_COMP *cpi, unsigned int *frame_flags, unsigned long *size, unsigned char *dest, unsigned char *dest_end, int64_t *time_stamp, int64_t *time_end, int flush)
4630 {
4631 #if HAVE_ARMV7
4632     int64_t store_reg[8];
4633 #endif
4634     VP8_COMMON *cm;
4635     struct vpx_usec_timer  tsctimer;
4636     struct vpx_usec_timer  ticktimer;
4637     struct vpx_usec_timer  cmptimer;
4638     YV12_BUFFER_CONFIG    *force_src_buffer = NULL;
4639
4640     if (!cpi)
4641         return -1;
4642
4643     cm = &cpi->common;
4644
4645     if (setjmp(cpi->common.error.jmp))
4646     {
4647         cpi->common.error.setjmp = 0;
4648         return VPX_CODEC_CORRUPT_FRAME;
4649     }
4650
4651     cpi->common.error.setjmp = 1;
4652
4653 #if HAVE_ARMV7
4654 #if CONFIG_RUNTIME_CPU_DETECT
4655     if (cm->rtcd.flags & HAS_NEON)
4656 #endif
4657     {
4658         vp8_push_neon(store_reg);
4659     }
4660 #endif
4661
4662     vpx_usec_timer_start(&cmptimer);
4663
4664     cpi->source = NULL;
4665
4666 #if !(CONFIG_REALTIME_ONLY)
4667     // Should we code an alternate reference frame
4668     if (cpi->oxcf.error_resilient_mode == 0 &&
4669         cpi->oxcf.play_alternate &&
4670         cpi->source_alt_ref_pending)
4671     {
4672         if ((cpi->source = vp8_lookahead_peek(cpi->lookahead,
4673                                               cpi->frames_till_gf_update_due)))
4674         {
4675             cpi->alt_ref_source = cpi->source;
4676             if (cpi->oxcf.arnr_max_frames > 0)
4677             {
4678                 vp8_temporal_filter_prepare_c(cpi,
4679                                               cpi->frames_till_gf_update_due);
4680                 force_src_buffer = &cpi->alt_ref_buffer;
4681             }
4682             cm->frames_till_alt_ref_frame = cpi->frames_till_gf_update_due;
4683             cm->refresh_alt_ref_frame = 1;
4684             cm->refresh_golden_frame = 0;
4685             cm->refresh_last_frame = 0;
4686             cm->show_frame = 0;
4687             cpi->source_alt_ref_pending = 0;  // Clear Pending alt Ref flag.
4688             cpi->is_src_frame_alt_ref = 0;
4689         }
4690     }
4691 #endif
4692
4693     if (!cpi->source)
4694     {
4695         if ((cpi->source = vp8_lookahead_pop(cpi->lookahead, flush)))
4696         {
4697             cm->show_frame = 1;
4698
4699             cpi->is_src_frame_alt_ref = cpi->alt_ref_source
4700                                         && (cpi->source == cpi->alt_ref_source);
4701
4702             if(cpi->is_src_frame_alt_ref)
4703                 cpi->alt_ref_source = NULL;
4704         }
4705     }
4706
4707     if (cpi->source)
4708     {
4709         cpi->un_scaled_source =
4710         cpi->Source = force_src_buffer ? force_src_buffer : &cpi->source->img;
4711         *time_stamp = cpi->source->ts_start;
4712         *time_end = cpi->source->ts_end;
4713         *frame_flags = cpi->source->flags;
4714     }
4715     else
4716     {
4717         *size = 0;
4718 #if !(CONFIG_REALTIME_ONLY)
4719
4720         if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done)
4721         {
4722             vp8_end_first_pass(cpi);    /* get last stats packet */
4723             cpi->twopass.first_pass_done = 1;
4724         }
4725
4726 #endif
4727
4728 #if HAVE_ARMV7
4729 #if CONFIG_RUNTIME_CPU_DETECT
4730         if (cm->rtcd.flags & HAS_NEON)
4731 #endif
4732         {
4733             vp8_pop_neon(store_reg);
4734         }
4735 #endif
4736         return -1;
4737     }
4738
4739     if (cpi->source->ts_start < cpi->first_time_stamp_ever)
4740     {
4741         cpi->first_time_stamp_ever = cpi->source->ts_start;
4742         cpi->last_end_time_stamp_seen = cpi->source->ts_start;
4743     }
4744
4745     // adjust frame rates based on timestamps given
4746     if (!cm->refresh_alt_ref_frame || (cpi->oxcf.number_of_layers > 1))
4747     {
4748         int64_t this_duration;
4749         int step = 0;
4750
4751         if (cpi->source->ts_start == cpi->first_time_stamp_ever)
4752         {
4753             this_duration = cpi->source->ts_end - cpi->source->ts_start;
4754             step = 1;
4755         }
4756         else
4757         {
4758             int64_t last_duration;
4759
4760             this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
4761             last_duration = cpi->last_end_time_stamp_seen
4762                             - cpi->last_time_stamp_seen;
4763             // do a step update if the duration changes by 10%
4764             if (last_duration)
4765                 step = ((this_duration - last_duration) * 10 / last_duration);
4766         }
4767
4768         if (this_duration)
4769         {
4770             if (step)
4771                 cpi->ref_frame_rate = 10000000.0 / this_duration;
4772             else
4773             {
4774                 double avg_duration, interval;
4775
4776                 /* Average this frame's rate into the last second's average
4777                  * frame rate. If we haven't seen 1 second yet, then average
4778                  * over the whole interval seen.
4779                  */
4780                 interval = cpi->source->ts_end - cpi->first_time_stamp_ever;
4781                 if(interval > 10000000.0)
4782                     interval = 10000000;
4783
4784                 avg_duration = 10000000.0 / cpi->ref_frame_rate;
4785                 avg_duration *= (interval - avg_duration + this_duration);
4786                 avg_duration /= interval;
4787
4788                 cpi->ref_frame_rate = 10000000.0 / avg_duration;
4789             }
4790
4791             if (cpi->oxcf.number_of_layers > 1)
4792             {
4793                 int i;
4794
4795                 // Update frame rates for each layer
4796                 for (i=0; i<cpi->oxcf.number_of_layers; i++)
4797                 {
4798                     LAYER_CONTEXT *lc = &cpi->layer_context[i];
4799                     lc->frame_rate = cpi->ref_frame_rate /
4800                                   cpi->oxcf.rate_decimator[i];
4801                 }
4802             }
4803             else
4804                 vp8_new_frame_rate(cpi, cpi->ref_frame_rate);
4805         }
4806
4807         cpi->last_time_stamp_seen = cpi->source->ts_start;
4808         cpi->last_end_time_stamp_seen = cpi->source->ts_end;
4809     }
4810
4811     if (cpi->oxcf.number_of_layers > 1)
4812     {
4813         int layer;
4814
4815         update_layer_contexts (cpi);
4816
4817         // Restore layer specific context & set frame rate
4818         layer = cpi->oxcf.layer_id[
4819                             cm->current_video_frame % cpi->oxcf.periodicity];
4820         restore_layer_context (cpi, layer);
4821         vp8_new_frame_rate (cpi, cpi->layer_context[layer].frame_rate);
4822     }
4823
4824     if (cpi->compressor_speed == 2)
4825     {
4826         if (cpi->oxcf.number_of_layers == 1)
4827             check_gf_quality(cpi);
4828         vpx_usec_timer_start(&tsctimer);
4829         vpx_usec_timer_start(&ticktimer);
4830     }
4831
4832     // start with a 0 size frame
4833     *size = 0;
4834
4835     // Clear down mmx registers
4836     vp8_clear_system_state();  //__asm emms;
4837
4838     cm->frame_type = INTER_FRAME;
4839     cm->frame_flags = *frame_flags;
4840
4841 #if 0
4842
4843     if (cm->refresh_alt_ref_frame)
4844     {
4845         //cm->refresh_golden_frame = 1;
4846         cm->refresh_golden_frame = 0;
4847         cm->refresh_last_frame = 0;
4848     }
4849     else
4850     {
4851         cm->refresh_golden_frame = 0;
4852         cm->refresh_last_frame = 1;
4853     }
4854
4855 #endif
4856     /* find a free buffer for the new frame */
4857     {
4858         int i = 0;
4859         for(; i < NUM_YV12_BUFFERS; i++)
4860         {
4861             if(!cm->yv12_fb[i].flags)
4862             {
4863                 cm->new_fb_idx = i;
4864                 break;
4865             }
4866         }
4867
4868         assert(i < NUM_YV12_BUFFERS );
4869     }
4870 #if !(CONFIG_REALTIME_ONLY)
4871
4872     if (cpi->pass == 1)
4873     {
4874         Pass1Encode(cpi, size, dest, frame_flags);
4875     }
4876     else if (cpi->pass == 2)
4877     {
4878         Pass2Encode(cpi, size, dest, dest_end, frame_flags);
4879     }
4880     else
4881 #endif
4882         encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
4883
4884     if (cpi->compressor_speed == 2)
4885     {
4886         unsigned int duration, duration2;
4887         vpx_usec_timer_mark(&tsctimer);
4888         vpx_usec_timer_mark(&ticktimer);
4889
4890         duration = vpx_usec_timer_elapsed(&ticktimer);
4891         duration2 = (unsigned int)((double)duration / 2);
4892
4893         if (cm->frame_type != KEY_FRAME)
4894         {
4895             if (cpi->avg_encode_time == 0)
4896                 cpi->avg_encode_time = duration;
4897             else
4898                 cpi->avg_encode_time = (7 * cpi->avg_encode_time + duration) >> 3;
4899         }
4900
4901         if (duration2)
4902         {
4903             //if(*frame_flags!=1)
4904             {
4905
4906                 if (cpi->avg_pick_mode_time == 0)
4907                     cpi->avg_pick_mode_time = duration2;
4908                 else
4909                     cpi->avg_pick_mode_time = (7 * cpi->avg_pick_mode_time + duration2) >> 3;
4910             }
4911         }
4912
4913     }
4914
4915     if (cm->refresh_entropy_probs == 0)
4916     {
4917         vpx_memcpy(&cm->fc, &cm->lfc, sizeof(cm->fc));
4918     }
4919
4920     // Save the contexts separately for alt ref, gold and last.
4921     // (TODO jbb -> Optimize this with pointers to avoid extra copies. )
4922     if(cm->refresh_alt_ref_frame)
4923         vpx_memcpy(&cpi->lfc_a, &cm->fc, sizeof(cm->fc));
4924
4925     if(cm->refresh_golden_frame)
4926         vpx_memcpy(&cpi->lfc_g, &cm->fc, sizeof(cm->fc));
4927
4928     if(cm->refresh_last_frame)
4929         vpx_memcpy(&cpi->lfc_n, &cm->fc, sizeof(cm->fc));
4930
4931     // if its a dropped frame honor the requests on subsequent frames
4932     if (*size > 0)
4933     {
4934         cpi->droppable = !frame_is_reference(cpi);
4935
4936         // return to normal state
4937         cm->refresh_entropy_probs = 1;
4938         cm->refresh_alt_ref_frame = 0;
4939         cm->refresh_golden_frame = 0;
4940         cm->refresh_last_frame = 1;
4941         cm->frame_type = INTER_FRAME;
4942
4943     }
4944
4945     // Save layer specific state
4946     if (cpi->oxcf.number_of_layers > 1)
4947         save_layer_context (cpi);
4948
4949     vpx_usec_timer_mark(&cmptimer);
4950     cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4951
4952     if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
4953     {
4954         generate_psnr_packet(cpi);
4955     }
4956
4957 #if CONFIG_INTERNAL_STATS
4958
4959     if (cpi->pass != 1)
4960     {
4961         cpi->bytes += *size;
4962
4963         if (cm->show_frame)
4964         {
4965
4966             cpi->count ++;
4967
4968             if (cpi->b_calculate_psnr)
4969             {
4970                 double ye,ue,ve;
4971                 double frame_psnr;
4972                 YV12_BUFFER_CONFIG      *orig = cpi->Source;
4973                 YV12_BUFFER_CONFIG      *recon = cpi->common.frame_to_show;
4974                 YV12_BUFFER_CONFIG      *pp = &cm->post_proc_buffer;
4975                 int y_samples = orig->y_height * orig->y_width ;
4976                 int uv_samples = orig->uv_height * orig->uv_width ;
4977                 int t_samples = y_samples + 2 * uv_samples;
4978                 int64_t sq_error, sq_error2;
4979
4980                 ye = calc_plane_error(orig->y_buffer, orig->y_stride,
4981                   recon->y_buffer, recon->y_stride, orig->y_width, orig->y_height,
4982                   IF_RTCD(&cpi->rtcd.variance));
4983
4984                 ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
4985                   recon->u_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
4986                   IF_RTCD(&cpi->rtcd.variance));
4987
4988                 ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
4989                   recon->v_buffer, recon->uv_stride, orig->uv_width, orig->uv_height,
4990                   IF_RTCD(&cpi->rtcd.variance));
4991
4992                 sq_error = ye + ue + ve;
4993
4994                 frame_psnr = vp8_mse2psnr(t_samples, 255.0, sq_error);
4995
4996                 cpi->total_y += vp8_mse2psnr(y_samples, 255.0, ye);
4997                 cpi->total_u += vp8_mse2psnr(uv_samples, 255.0, ue);
4998                 cpi->total_v += vp8_mse2psnr(uv_samples, 255.0, ve);
4999                 cpi->total_sq_error += sq_error;
5000                 cpi->total  += frame_psnr;
5001                 {
5002                     double frame_psnr2, frame_ssim2 = 0;
5003                     double weight = 0;
5004
5005                     vp8_deblock(cm->frame_to_show, &cm->post_proc_buffer, cm->filter_level * 10 / 6, 1, 0, IF_RTCD(&cm->rtcd.postproc));
5006                     vp8_clear_system_state();
5007
5008                     ye = calc_plane_error(orig->y_buffer, orig->y_stride,
5009                       pp->y_buffer, pp->y_stride, orig->y_width, orig->y_height,
5010                       IF_RTCD(&cpi->rtcd.variance));
5011
5012                     ue = calc_plane_error(orig->u_buffer, orig->uv_stride,
5013                       pp->u_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
5014                       IF_RTCD(&cpi->rtcd.variance));
5015
5016                     ve = calc_plane_error(orig->v_buffer, orig->uv_stride,
5017                       pp->v_buffer, pp->uv_stride, orig->uv_width, orig->uv_height,
5018                       IF_RTCD(&cpi->rtcd.variance));
5019
5020                     sq_error2 = ye + ue + ve;
5021
5022                     frame_psnr2 = vp8_mse2psnr(t_samples, 255.0, sq_error2);
5023
5024                     cpi->totalp_y += vp8_mse2psnr(y_samples, 255.0, ye);
5025                     cpi->totalp_u += vp8_mse2psnr(uv_samples, 255.0, ue);
5026                     cpi->totalp_v += vp8_mse2psnr(uv_samples, 255.0, ve);
5027                     cpi->total_sq_error2 += sq_error2;
5028                     cpi->totalp  += frame_psnr2;
5029
5030                     frame_ssim2 = vp8_calc_ssim(cpi->Source,
5031                       &cm->post_proc_buffer, 1, &weight,
5032                       IF_RTCD(&cpi->rtcd.variance));
5033
5034                     cpi->summed_quality += frame_ssim2 * weight;
5035                     cpi->summed_weights += weight;
5036
5037                     if (cpi->oxcf.number_of_layers > 1)
5038                     {
5039                          int i;
5040
5041                          for (i=cpi->current_layer;
5042                                        i<cpi->oxcf.number_of_layers; i++)
5043                          {
5044                              cpi->frames_in_layer[i]++;
5045
5046                              cpi->bytes_in_layer[i] += *size;
5047                              cpi->sum_psnr[i]       += frame_psnr;
5048                              cpi->sum_psnr_p[i]     += frame_psnr2;
5049                              cpi->total_error2[i]   += sq_error;
5050                              cpi->total_error2_p[i] += sq_error2;
5051                              cpi->sum_ssim[i]       += frame_ssim2 * weight;
5052                              cpi->sum_weights[i]    += weight;
5053                          }
5054                     }
5055                 }
5056             }
5057
5058             if (cpi->b_calculate_ssimg)
5059             {
5060                 double y, u, v, frame_all;
5061                 frame_all =  vp8_calc_ssimg(cpi->Source, cm->frame_to_show,
5062                     &y, &u, &v, IF_RTCD(&cpi->rtcd.variance));
5063
5064                 if (cpi->oxcf.number_of_layers > 1)
5065                 {
5066                     int i;
5067
5068                     for (i=cpi->current_layer;
5069                          i<cpi->oxcf.number_of_layers; i++)
5070                     {
5071                         if (!cpi->b_calculate_psnr)
5072                             cpi->frames_in_layer[i]++;
5073
5074                         cpi->total_ssimg_y_in_layer[i] += y;
5075                         cpi->total_ssimg_u_in_layer[i] += u;
5076                         cpi->total_ssimg_v_in_layer[i] += v;
5077                         cpi->total_ssimg_all_in_layer[i] += frame_all;
5078                     }
5079                 }
5080                 else
5081                 {
5082                     cpi->total_ssimg_y += y;
5083                     cpi->total_ssimg_u += u;
5084                     cpi->total_ssimg_v += v;
5085                     cpi->total_ssimg_all += frame_all;
5086                 }
5087             }
5088
5089         }
5090     }
5091
5092 #if 0
5093
5094     if (cpi->common.frame_type != 0 && cpi->common.base_qindex == cpi->oxcf.worst_allowed_q)
5095     {
5096         skiptruecount += cpi->skip_true_count;
5097         skipfalsecount += cpi->skip_false_count;
5098     }
5099
5100 #endif
5101 #if 0
5102
5103     if (cpi->pass != 1)
5104     {
5105         FILE *f = fopen("skip.stt", "a");
5106         fprintf(f, "frame:%4d flags:%4x Q:%4d P:%4d Size:%5d\n", cpi->common.current_video_frame, *frame_flags, cpi->common.base_qindex, cpi->prob_skip_false, *size);
5107
5108         if (cpi->is_src_frame_alt_ref == 1)
5109             fprintf(f, "skipcount: %4d framesize: %d\n", cpi->skip_true_count , *size);
5110
5111         fclose(f);
5112     }
5113
5114 #endif
5115 #endif
5116
5117 #if HAVE_ARMV7
5118 #if CONFIG_RUNTIME_CPU_DETECT
5119     if (cm->rtcd.flags & HAS_NEON)
5120 #endif
5121     {
5122         vp8_pop_neon(store_reg);
5123     }
5124 #endif
5125
5126     cpi->common.error.setjmp = 0;
5127
5128     return 0;
5129 }
5130
5131 int vp8_get_preview_raw_frame(VP8_COMP *cpi, YV12_BUFFER_CONFIG *dest, vp8_ppflags_t *flags)
5132 {
5133     if (cpi->common.refresh_alt_ref_frame)
5134         return -1;
5135     else
5136     {
5137         int ret;
5138 #if CONFIG_POSTPROC
5139         ret = vp8_post_proc_frame(&cpi->common, dest, flags);
5140 #else
5141
5142         if (cpi->common.frame_to_show)
5143         {
5144             *dest = *cpi->common.frame_to_show;
5145             dest->y_width = cpi->common.Width;
5146             dest->y_height = cpi->common.Height;
5147             dest->uv_height = cpi->common.Height / 2;
5148             ret = 0;
5149         }
5150         else
5151         {
5152             ret = -1;
5153         }
5154
5155 #endif //!CONFIG_POSTPROC
5156         vp8_clear_system_state();
5157         return ret;
5158     }
5159 }
5160
5161 int vp8_set_roimap(VP8_COMP *cpi, unsigned char *map, unsigned int rows, unsigned int cols, int delta_q[4], int delta_lf[4], unsigned int threshold[4])
5162 {
5163     signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
5164
5165     if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
5166         return -1;
5167
5168     if (!map)
5169     {
5170         disable_segmentation(cpi);
5171         return 0;
5172     }
5173
5174     // Set the segmentation Map
5175     set_segmentation_map(cpi, map);
5176
5177     // Activate segmentation.
5178     enable_segmentation(cpi);
5179
5180     // Set up the quant segment data
5181     feature_data[MB_LVL_ALT_Q][0] = delta_q[0];
5182     feature_data[MB_LVL_ALT_Q][1] = delta_q[1];
5183     feature_data[MB_LVL_ALT_Q][2] = delta_q[2];
5184     feature_data[MB_LVL_ALT_Q][3] = delta_q[3];
5185
5186     // Set up the loop segment data s
5187     feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
5188     feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
5189     feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
5190     feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
5191
5192     cpi->segment_encode_breakout[0] = threshold[0];
5193     cpi->segment_encode_breakout[1] = threshold[1];
5194     cpi->segment_encode_breakout[2] = threshold[2];
5195     cpi->segment_encode_breakout[3] = threshold[3];
5196
5197     // Initialise the feature data structure
5198     // SEGMENT_DELTADATA    0, SEGMENT_ABSDATA      1
5199     set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
5200
5201     return 0;
5202 }
5203
5204 int vp8_set_active_map(VP8_COMP *cpi, unsigned char *map, unsigned int rows, unsigned int cols)
5205 {
5206     if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols)
5207     {
5208         if (map)
5209         {
5210             vpx_memcpy(cpi->active_map, map, rows * cols);
5211             cpi->active_map_enabled = 1;
5212         }
5213         else
5214             cpi->active_map_enabled = 0;
5215
5216         return 0;
5217     }
5218     else
5219     {
5220         //cpi->active_map_enabled = 0;
5221         return -1 ;
5222     }
5223 }
5224
5225 int vp8_set_internal_size(VP8_COMP *cpi, VPX_SCALING horiz_mode, VPX_SCALING vert_mode)
5226 {
5227     if (horiz_mode <= ONETWO)
5228         cpi->common.horiz_scale = horiz_mode;
5229     else
5230         return -1;
5231
5232     if (vert_mode <= ONETWO)
5233         cpi->common.vert_scale  = vert_mode;
5234     else
5235         return -1;
5236
5237     return 0;
5238 }
5239
5240
5241
5242 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest, const vp8_variance_rtcd_vtable_t *rtcd)
5243 {
5244     int i, j;
5245     int Total = 0;
5246
5247     unsigned char *src = source->y_buffer;
5248     unsigned char *dst = dest->y_buffer;
5249     (void)rtcd;
5250
5251     // Loop through the Y plane raw and reconstruction data summing (square differences)
5252     for (i = 0; i < source->y_height; i += 16)
5253     {
5254         for (j = 0; j < source->y_width; j += 16)
5255         {
5256             unsigned int sse;
5257             Total += VARIANCE_INVOKE(rtcd, mse16x16)(src + j, source->y_stride, dst + j, dest->y_stride, &sse);
5258         }
5259
5260         src += 16 * source->y_stride;
5261         dst += 16 * dest->y_stride;
5262     }
5263
5264     return Total;
5265 }
5266
5267
5268 int vp8_get_quantizer(VP8_COMP *cpi)
5269 {
5270     return cpi->common.base_qindex;
5271 }