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