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