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