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