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