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