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