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