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