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