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