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