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