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