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