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