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