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