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