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