/* * Copyright (c) 2010 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree.
*/
/* Work out the average size of a frame within this layer */ if (layer > 0) {
lc->avg_frame_size_for_layer =
(int)round((cpi->oxcf.target_bitrate[layer] -
cpi->oxcf.target_bitrate[layer - 1]) *
1000 / (lc->framerate - prev_layer_framerate));
}
// Upon a run-time change in temporal layers, reset the layer context parameters // for any "new" layers. For "existing" layers, let them inherit the parameters // from the previous layer state (at the same layer #). In future we may want // to better map the previous layer state(s) to the "new" ones. void vp8_reset_temporal_layer_change(VP8_COMP *cpi, const VP8_CONFIG *oxcf, constint prev_num_layers) { int i; double prev_layer_framerate = 0; constint curr_num_layers = cpi->oxcf.number_of_layers; // If the previous state was 1 layer, get current layer context from cpi. // We need this to set the layer context for the new layers below. if (prev_num_layers == 1) {
cpi->current_layer = 0;
vp8_save_layer_context(cpi);
} for (i = 0; i < curr_num_layers; ++i) {
LAYER_CONTEXT *lc = &cpi->layer_context[i]; if (i >= prev_num_layers) {
vp8_init_temporal_layer_context(cpi, oxcf, i, prev_layer_framerate);
} // The initial buffer levels are set based on their starting levels. // We could set the buffer levels based on the previous state (normalized // properly by the layer bandwidths) but we would need to keep track of // the previous set of layer bandwidths (i.e., target_bitrate[i]) // before the layer change. For now, reset to the starting levels.
lc->buffer_level =
cpi->oxcf.starting_buffer_level_in_ms * cpi->oxcf.target_bitrate[i];
lc->bits_off_target = lc->buffer_level; // TDOD(marpan): Should we set the rate_correction_factor and // active_worst/best_quality to values derived from the previous layer // state (to smooth-out quality dips/rate fluctuation at transition)?
// We need to treat the 1 layer case separately: oxcf.target_bitrate[i] // is not set for 1 layer, and the vp8_restore_layer_context/save_context() // are not called in the encoding loop, so we need to call it here to // pass the layer context state to |cpi|. if (curr_num_layers == 1) {
lc->target_bandwidth = cpi->oxcf.target_bandwidth;
lc->buffer_level =
cpi->oxcf.starting_buffer_level_in_ms * lc->target_bandwidth / 1000;
lc->bits_off_target = lc->buffer_level;
vp8_restore_layer_context(cpi, 0);
}
prev_layer_framerate = cpi->output_framerate / cpi->oxcf.rate_decimator[i];
}
}
staticvoid setup_features(VP8_COMP *cpi) { // If segmentation enabled set the update flags if (cpi->mb.e_mbd.segmentation_enabled) {
cpi->mb.e_mbd.update_mb_segmentation_map = 1;
cpi->mb.e_mbd.update_mb_segmentation_data = 1;
} else {
cpi->mb.e_mbd.update_mb_segmentation_map = 0;
cpi->mb.e_mbd.update_mb_segmentation_data = 0;
}
/* Structure used to monitor GF usage */
vpx_free(cpi->gf_active_flags);
cpi->gf_active_flags = 0;
/* Activity mask based per mb zbin adjustments */
vpx_free(cpi->mb_activity_map);
cpi->mb_activity_map = 0;
vpx_free(cpi->mb.pip);
cpi->mb.pip = 0;
}
staticvoid enable_segmentation(VP8_COMP *cpi) { /* Set the appropriate feature bit */
cpi->mb.e_mbd.segmentation_enabled = 1;
cpi->mb.e_mbd.update_mb_segmentation_map = 1;
cpi->mb.e_mbd.update_mb_segmentation_data = 1;
} staticvoid disable_segmentation(VP8_COMP *cpi) { /* Clear the appropriate feature bit */
cpi->mb.e_mbd.segmentation_enabled = 0;
}
/* Valid values for a segment are 0 to 3 * Segmentation map is arrange as [Rows][Columns]
*/ staticvoid set_segmentation_map(VP8_COMP *cpi, unsignedchar *segmentation_map) { /* Copy in the new segmentation map */
memcpy(cpi->segmentation_map, segmentation_map,
(cpi->common.mb_rows * cpi->common.mb_cols));
/* Signal that the map should be updated. */
cpi->mb.e_mbd.update_mb_segmentation_map = 1;
cpi->mb.e_mbd.update_mb_segmentation_data = 1;
}
/* The values given for each segment can be either deltas (from the default * value chosen for the frame) or absolute values. * * Valid range for abs values is: * (0-127 for MB_LVL_ALT_Q), (0-63 for SEGMENT_ALT_LF) * Valid range for delta values are: * (+/-127 for MB_LVL_ALT_Q), (+/-63 for SEGMENT_ALT_LF) * * abs_delta = SEGMENT_DELTADATA (deltas) * abs_delta = SEGMENT_ABSDATA (use the absolute values given). *
*/ staticvoid set_segment_data(VP8_COMP *cpi, signedchar *feature_data, unsignedchar abs_delta) {
cpi->mb.e_mbd.mb_segment_abs_delta = abs_delta;
memcpy(cpi->segment_feature_data, feature_data, sizeof(cpi->segment_feature_data));
}
/* A simple function to cyclically refresh the background at a lower Q */ staticvoid cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment) { unsignedchar *seg_map = cpi->segmentation_map; signedchar feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS]; int i; int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe; int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
cpi->cyclic_refresh_q = Q / 2;
if (cpi->oxcf.screen_content_mode) { // Modify quality ramp-up based on Q. Above some Q level, increase the // number of blocks to be refreshed, and reduce it below the thredhold. // Turn-off under certain conditions (i.e., away from key frame, and if // we are at good quality (low Q) and most of the blocks were // skipped-encoded // in previous frame. int qp_thresh = (cpi->oxcf.screen_content_mode == 2) ? 80 : 100; if (Q >= qp_thresh) {
cpi->cyclic_refresh_mode_max_mbs_perframe =
(cpi->common.mb_rows * cpi->common.mb_cols) / 10;
} elseif (cpi->frames_since_key > 250 && Q < 20 &&
cpi->mb.skip_true_count > (int)(0.95 * mbs_in_frame)) {
cpi->cyclic_refresh_mode_max_mbs_perframe = 0;
} else {
cpi->cyclic_refresh_mode_max_mbs_perframe =
(cpi->common.mb_rows * cpi->common.mb_cols) / 20;
}
block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
}
// Set every macroblock to be eligible for update. // For key frame this will reset seg map to 0.
memset(cpi->segmentation_map, 0, mbs_in_frame);
if (cpi->common.frame_type != KEY_FRAME && block_count > 0) { /* Cycle through the macro_block rows */ /* MB loop to set local segmentation map */
i = cpi->cyclic_refresh_mode_index;
assert(i < mbs_in_frame); do { /* If the MB is as a candidate for clean up then mark it for * possible boost/refresh (segment 1) The segment id may get * reset to 0 later if the MB gets coded anything other than * last frame 0,0 as only (last frame 0,0) MBs are eligable for * refresh : that is to say Mbs likely to be background blocks.
*/ if (cpi->cyclic_refresh_map[i] == 0) {
seg_map[i] = 1;
block_count--;
} elseif (cpi->cyclic_refresh_map[i] < 0) {
cpi->cyclic_refresh_map[i]++;
}
i++; if (i == mbs_in_frame) i = 0;
} while (block_count && i != cpi->cyclic_refresh_mode_index);
cpi->cyclic_refresh_mode_index = i;
#if CONFIG_TEMPORAL_DENOISING if (cpi->oxcf.noise_sensitivity > 0) { if (cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive &&
Q < (int)cpi->denoiser.denoise_pars.qp_thresh &&
(cpi->frames_since_key >
2 * cpi->denoiser.denoise_pars.consec_zerolast)) { // Under aggressive denoising, use segmentation to turn off loop // filter below some qp thresh. The filter is reduced for all // blocks that have been encoded as ZEROMV LAST x frames in a row, // where x is set by cpi->denoiser.denoise_pars.consec_zerolast. // This is to avoid "dot" artifacts that can occur from repeated // loop filtering on noisy input source.
cpi->cyclic_refresh_q = Q; // lf_adjustment = -MAX_LOOP_FILTER;
lf_adjustment = -40; for (i = 0; i < mbs_in_frame; ++i) {
seg_map[i] = (cpi->consec_zero_last[i] >
cpi->denoiser.denoise_pars.consec_zerolast)
? 1
: 0;
}
}
} #endif
}
/* Set up the quant segment data */
feature_data[MB_LVL_ALT_Q][0] = 0;
feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
feature_data[MB_LVL_ALT_Q][2] = 0;
feature_data[MB_LVL_ALT_Q][3] = 0;
/* Set up the loop segment data */
feature_data[MB_LVL_ALT_LF][0] = 0;
feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
feature_data[MB_LVL_ALT_LF][2] = 0;
feature_data[MB_LVL_ALT_LF][3] = 0;
/* Initialise the feature data structure */
set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
}
void vp8_set_speed_features(VP8_COMP *cpi) {
SPEED_FEATURES *sf = &cpi->sf; int Mode = cpi->compressor_speed; int Speed = cpi->Speed; int Speed2; int i;
VP8_COMMON *cm = &cpi->common; int last_improved_quant = sf->improved_quant; int ref_frames;
/* Initialise default mode frequency sampling variables */ for (i = 0; i < MAX_MODES; ++i) {
cpi->mode_check_freq[i] = 0;
}
// Special case for temporal layers. // Reduce the thresholds for zero/nearest/near for GOLDEN, if GOLDEN is // used as second reference. We don't modify thresholds for ALTREF case // since ALTREF is usually used as long-term reference in temporal layers. if ((cpi->Speed <= 6) && (cpi->oxcf.number_of_layers > 1) &&
(cpi->ref_frame_flags & VP8_LAST_FRAME) &&
(cpi->ref_frame_flags & VP8_GOLD_FRAME)) { if (cpi->closest_reference_frame == GOLDEN_FRAME) {
sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO2] >> 3;
sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST2] >> 3;
sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR2] >> 3;
} else {
sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO2] >> 1;
sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST2] >> 1;
sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR2] >> 1;
}
}
// For real-time mode at speed 10 keep the mode_check_freq threshold // for NEW1 similar to that of speed 9.
Speed2 = Speed; if (cpi->Speed == 10 && Mode == 2) Speed2 = RT(9);
cpi->mode_check_freq[THR_NEW1] = speed_map(Speed2, mode_check_freq_map_new1);
/* Slow quant, dct and trellis not worthwhile for first pass * so make sure they are always turned off.
*/ if (cpi->pass == 1) {
sf->improved_quant = 0;
sf->optimize_coefficients = 0;
sf->improved_dct = 0;
}
if (cpi->sf.improved_dct) {
cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
} else { /* No fast FDCT defined for any platform at this time. */
cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
}
cpi->mb.short_walsh4x4 = vp8_short_walsh4x4;
if (cpi->sf.improved_quant) {
cpi->mb.quantize_b = vp8_regular_quantize_b;
} else {
cpi->mb.quantize_b = vp8_fast_quantize_b;
} if (cpi->sf.improved_quant != last_improved_quant) vp8cx_init_quantizer(cpi);
if (vp8_yv12_alloc_frame_buffer(&cpi->pick_lf_lvl_frame, width, height,
VP8BORDERINPIXELS)) {
vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR, "Failed to allocate last frame buffer");
}
if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source, width, height,
VP8BORDERINPIXELS)) {
vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR, "Failed to allocate scaled source buffer");
}
/* Frame rate is not available on the first frame, as it's derived from * the observed timestamps. The actual value used here doesn't matter * too much, as it will adapt quickly.
*/ if (oxcf->timebase.num > 0) {
cpi->framerate =
(double)(oxcf->timebase.den) / (double)(oxcf->timebase.num);
} else {
cpi->framerate = 30;
}
/* If the reciprocal of the timebase seems like a reasonable framerate, * then use that as a guess, otherwise use 30.
*/ if (cpi->framerate > 180) cpi->framerate = 30;
/* change includes all joint functionality */
vp8_change_config(cpi, oxcf);
/* Initialize active best and worst q and average q values. */
cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
cpi->active_best_quality = cpi->oxcf.best_allowed_q;
cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
vp8_init_temporal_layer_context(cpi, oxcf, i, prev_layer_framerate);
prev_layer_framerate =
cpi->output_framerate / cpi->oxcf.rate_decimator[i];
}
}
#if VP8_TEMPORAL_ALT_REF
{ int i;
cpi->fixed_divide[0] = 0;
for (i = 1; i < 512; ++i) cpi->fixed_divide[i] = 0x80000 / i;
} #endif
}
/* Update snapshots of the layer contexts to reflect new parameters */ if (oxcf->number_of_layers > 1) { unsignedint i; double prev_layer_framerate = 0;
assert(oxcf->number_of_layers <= VPX_TS_MAX_LAYERS); for (i = 0; i < oxcf->number_of_layers && i < VPX_TS_MAX_LAYERS; ++i) {
LAYER_CONTEXT *lc = &cpi->layer_context[i];
/* Work out the average size of a frame within this layer */ if (i > 0) {
lc->avg_frame_size_for_layer =
(int)round((oxcf->target_bitrate[i] - oxcf->target_bitrate[i - 1]) *
1000 / (lc->framerate - prev_layer_framerate));
}
// GF behavior for 1 pass CBR, used when error_resilience is off. if (!cpi->oxcf.error_resilient_mode &&
cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
cpi->oxcf.Mode == MODE_REALTIME)
cpi->baseline_gf_interval = cpi->gf_interval_onepass_cbr;
/* Set or reset optimal and maximum buffer levels. */ if (cpi->oxcf.optimal_buffer_level == 0) {
cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
} else {
cpi->oxcf.optimal_buffer_level = rescale(
(int)cpi->oxcf.optimal_buffer_level, cpi->oxcf.target_bandwidth, 1000);
}
if (cpi->oxcf.maximum_buffer_size == 0) {
cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
} else {
cpi->oxcf.maximum_buffer_size = rescale((int)cpi->oxcf.maximum_buffer_size,
cpi->oxcf.target_bandwidth, 1000);
} // Under a configuration change, where maximum_buffer_size may change, // keep buffer level clipped to the maximum allowed buffer size. if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
cpi->buffer_level = cpi->bits_off_target;
}
/* Set up frame rate and related parameters rate control values. */
vp8_new_framerate(cpi, cpi->framerate);
/* Set absolute upper and lower quality limits */
cpi->worst_quality = cpi->oxcf.worst_allowed_q;
cpi->best_quality = cpi->oxcf.best_allowed_q;
/* active values should only be modified if out of new range */ if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q) {
cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
} /* less likely */ elseif (cpi->active_worst_quality < cpi->oxcf.best_allowed_q) {
cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
} if (cpi->active_best_quality < cpi->oxcf.best_allowed_q) {
cpi->active_best_quality = cpi->oxcf.best_allowed_q;
} /* less likely */ elseif (cpi->active_best_quality > cpi->oxcf.worst_allowed_q) {
cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
}
// Check if the number of temporal layers has changed, and if so reset the // pattern counter and set/initialize the temporal layer context for the // new layer configuration. if (cpi->oxcf.number_of_layers != prev_number_of_layers) { // If the number of temporal layers are changed we must start at the // base of the pattern cycle, so set the layer id to 0 and reset // the temporal pattern counter. if (cpi->temporal_layer_id > 0) {
cpi->temporal_layer_id = 0;
}
cpi->temporal_pattern_counter = 0;
vp8_reset_temporal_layer_change(cpi, oxcf, prev_number_of_layers);
}
if (!cpi->initial_width) {
cpi->initial_width = cpi->oxcf.Width;
cpi->initial_height = cpi->oxcf.Height;
}
/* TODO(jkoleszar): if an internal spatial resampling is active, * and we downsize the input image, maybe we should clear the * internal scale immediately rather than waiting for it to * correct.
*/
/* VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs) */ if (cpi->oxcf.Sharpness > 7) cpi->oxcf.Sharpness = 7;
cm->sharpness_level = cpi->oxcf.Sharpness;
if (cm->horiz_scale != VP8E_NORMAL || cm->vert_scale != VP8E_NORMAL) { int hr, hs, vr, vs;
/* force to allowlag to 0 if lag_in_frames is 0; */ if (cpi->oxcf.lag_in_frames == 0) {
cpi->oxcf.allow_lag = 0;
} /* Limit on lag buffers as these are not currently dynamically allocated */ elseif (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS) {
cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
}
/* Prime the recent reference frame usage counters. * Hereafter they will be maintained as a sort of moving average
*/
cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
/* Set reference frame sign bias for ALTREF frame to 1 (for now) */
cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
/*Initialize the feed-forward activity masking.*/
cpi->activity_avg = 90 << 12;
/* Give a sensible default for the first frame. */
cpi->frames_since_key = 8;
cpi->key_frame_frequency = cpi->oxcf.key_freq;
cpi->this_key_frame_forced = 0;
cpi->next_key_frame_forced = 0;
/* make sure frame 1 is okay */
cpi->mb.error_bins[0] = cpi->common.MBs;
/* vp8cx_init_quantizer() is first called here. Add check in * vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only * called later when needed. This will avoid unnecessary calls of * vp8cx_init_quantizer() for every frame.
*/
vp8cx_init_quantizer(cpi);
vp8_loop_filter_init(cm);
#if CONFIG_MULTI_RES_ENCODING
/* Calculate # of MBs in a row in lower-resolution level image. */ if (cpi->oxcf.mr_encoder_id > 0) vp8_cal_low_res_mb_cols(cpi);
/* Do we need to apply resampling for one pass cbr. * In one pass this is more limited than in two pass cbr. * The test and any change is only made once per key frame sequence.
*/ if (cpi->oxcf.allow_spatial_resampling &&
(cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) { int hr, hs, vr, vs; int new_width, new_height;
/* If we are below the resample DOWN watermark then scale down a * notch.
*/ if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark *
cpi->oxcf.optimal_buffer_level / 100)) {
cm->horiz_scale =
(cm->horiz_scale < VP8E_ONETWO) ? cm->horiz_scale + 1 : VP8E_ONETWO;
cm->vert_scale =
(cm->vert_scale < VP8E_ONETWO) ? cm->vert_scale + 1 : VP8E_ONETWO;
} /* Should we now start scaling back up */ elseif (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark *
cpi->oxcf.optimal_buffer_level / 100)) {
cm->horiz_scale =
(cm->horiz_scale > VP8E_NORMAL) ? cm->horiz_scale - 1 : VP8E_NORMAL;
cm->vert_scale =
(cm->vert_scale > VP8E_NORMAL) ? cm->vert_scale - 1 : VP8E_NORMAL;
}
/* Get the new height and width */
Scale2Ratio(cm->horiz_scale, &hr, &hs);
Scale2Ratio(cm->vert_scale, &vr, &vs);
new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
/* If the image size has changed we need to reallocate the buffers * and resample the source image
*/ if ((cm->Width != new_width) || (cm->Height != new_height)) {
cm->Width = new_width;
cm->Height = new_height;
vp8_alloc_compressor_data(cpi);
scale_and_extend_source(cpi->un_scaled_source, cpi); return 1;
}
}
/* Select an interval before next GF or altref */ if (!cpi->auto_gold) cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
if ((cpi->pass != 2) && cpi->frames_till_gf_update_due) {
cpi->current_gf_interval = cpi->frames_till_gf_update_due;
/* Set the bits per frame that we should try and recover in * subsequent inter frames to account for the extra GF spend... * note that his does not apply for GF updates that occur * coincident with a key frame as the extra cost of key frames is * dealt with elsewhere.
*/
cpi->gf_overspend_bits += cpi->projected_frame_size;
cpi->non_gf_bitrate_adjustment =
cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
}
/* Update data structure that monitors level of reference to last GF */
memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
/* this frame refreshes means next frames don't unless specified by user */
cpi->frames_since_golden = 0;
/* Set the alternate reference frame active flag */
cpi->source_alt_ref_active = 1;
} staticvoid update_golden_frame_stats(VP8_COMP *cpi) {
VP8_COMMON *cm = &cpi->common;
/* Update the Golden frame usage counts. */ if (cm->refresh_golden_frame) { /* Select an interval before next GF */ if (!cpi->auto_gold) cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
/* Set the bits per frame that we should try and recover in * subsequent inter frames to account for the extra GF spend... * note that his does not apply for GF updates that occur * coincident with a key frame as the extra cost of key frames * is dealt with elsewhere.
*/ if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active) { /* Calcluate GF bits to be recovered * Projected size - av frame bits available for inter * frames for clip as a whole
*/
cpi->gf_overspend_bits +=
(cpi->projected_frame_size - cpi->inter_frame_target);
}
/* Update data structure that monitors level of reference to last GF */
memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
/* this frame refreshes means next frames don't unless specified by * user
*/
cm->refresh_golden_frame = 0;
cpi->frames_since_golden = 0;
/* ******** Fixed Q test code only ************ */ /* If we are going to use the ALT reference for the next group of * frames set a flag to say so.
*/ if (cpi->oxcf.fixed_q >= 0 && cpi->oxcf.play_alternate &&
!cpi->common.refresh_alt_ref_frame) {
cpi->source_alt_ref_pending = 1;
cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
}
if (!cpi->source_alt_ref_pending) cpi->source_alt_ref_active = 0;
/* Decrement count down till next gf */ if (cpi->frames_till_gf_update_due > 0) cpi->frames_till_gf_update_due--;
} elseif (!cpi->common.refresh_alt_ref_frame) { /* Decrement count down till next gf */ if (cpi->frames_till_gf_update_due > 0) cpi->frames_till_gf_update_due--;
if (cpi->frames_till_alt_ref_frame) cpi->frames_till_alt_ref_frame--;
/* This function updates the reference frame probability estimates that * will be used during mode selection
*/ staticvoid update_rd_ref_frame_probs(VP8_COMP *cpi) {
VP8_COMMON *cm = &cpi->common;
/* If the following are true we might as well code a key frame */ if (((cpi->this_frame_percent_intra == 100) &&
(cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
((cpi->this_frame_percent_intra > 95) &&
(cpi->this_frame_percent_intra >=
(cpi->last_frame_percent_intra + 5)))) {
code_key_frame = 1;
} /* in addition if the following are true and this is not a golden frame * then code a key frame Note that on golden frames there often seems * to be a pop in intra usage anyway hence this restriction is * designed to prevent spurious key frames. The Intra pop needs to be * investigated.
*/ elseif (((cpi->this_frame_percent_intra > 60) &&
(cpi->this_frame_percent_intra >
(cpi->last_frame_percent_intra * 2))) ||
((cpi->this_frame_percent_intra > 75) &&
(cpi->this_frame_percent_intra >
(cpi->last_frame_percent_intra * 3 / 2))) ||
((cpi->this_frame_percent_intra > 90) &&
(cpi->this_frame_percent_intra >
(cpi->last_frame_percent_intra + 10)))) { if (!cm->refresh_golden_frame) code_key_frame = 1;
}
for (i = 0; i < frame->uv_height; ++i)
fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
fclose(yframe);
} #endif
#if !CONFIG_REALTIME_ONLY /* Function to test for conditions that indeicate we should loop * back and recode a frame.
*/ staticint recode_loop_test(VP8_COMP *cpi, int high_limit, int low_limit, int q, int maxq, int minq) { int force_recode = 0;
VP8_COMMON *cm = &cpi->common;
/* Is frame recode allowed at all * Yes if either recode mode 1 is selected or mode two is selcted * and the frame is a key frame. golden frame or alt_ref_frame
*/ if ((cpi->sf.recode_loop == 1) ||
((cpi->sf.recode_loop == 2) &&
((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame ||
cm->refresh_alt_ref_frame))) { /* General over and under shoot tests */ if (((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
((cpi->projected_frame_size < low_limit) && (q > minq))) {
force_recode = 1;
} /* Special Constrained quality tests */ elseif (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) { /* Undershoot and below auto cq level */ if ((q > cpi->cq_target_quality) &&
(cpi->projected_frame_size < ((cpi->this_frame_target * 7) >> 3))) {
force_recode = 1;
} /* Severe undershoot and between auto and user cq level */ elseif ((q > cpi->oxcf.cq_level) &&
(cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
(cpi->active_best_quality > cpi->oxcf.cq_level)) {
force_recode = 1;
cpi->active_best_quality = cpi->oxcf.cq_level;
}
}
}
#if CONFIG_TEMPORAL_DENOISING if (cpi->oxcf.noise_sensitivity) { /* we shouldn't have to keep multiple copies as we know in advance which * buffer we should start - for now to get something up and running * I've chosen to copy the buffers
*/ if (cm->frame_type == KEY_FRAME) { int i; for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i)
vp8_yv12_copy_frame(cpi->Source, &cpi->denoiser.yv12_running_avg[i]);
} else {
vp8_yv12_extend_frame_borders(
&cpi->denoiser.yv12_running_avg[INTRA_FRAME]);
if (cm->refresh_alt_ref_frame || cm->copy_buffer_to_arf) {
vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
&cpi->denoiser.yv12_running_avg[ALTREF_FRAME]);
} if (cm->refresh_golden_frame || cm->copy_buffer_to_gf) {
vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
&cpi->denoiser.yv12_running_avg[GOLDEN_FRAME]);
} if (cm->refresh_last_frame) {
vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
&cpi->denoiser.yv12_running_avg[LAST_FRAME]);
}
} if (cpi->oxcf.noise_sensitivity == 4)
vp8_yv12_copy_frame(cpi->Source, &cpi->denoiser.yv12_last_source);
} #endif
}
staticint measure_square_diff_partial(YV12_BUFFER_CONFIG *source,
YV12_BUFFER_CONFIG *dest,
VP8_COMP *cpi) { int i, j; int Total = 0; int num_blocks = 0; int skip = 2; int min_consec_zero_last = 10; int tot_num_blocks = (source->y_height * source->y_width) >> 8; unsignedchar *src = source->y_buffer; unsignedchar *dst = dest->y_buffer;
/* Loop through the Y plane, every |skip| blocks along rows and colmumns, * summing the square differences, and only for blocks that have been * zero_last mode at least |x| frames in a row.
*/ for (i = 0; i < source->y_height; i += 16 * skip) { int block_index_row = (i >> 4) * cpi->common.mb_cols; for (j = 0; j < source->y_width; j += 16 * skip) { int index = block_index_row + (j >> 4); if (cpi->consec_zero_last[index] >= min_consec_zero_last) { unsignedint sse;
Total += vpx_mse16x16(src + j, source->y_stride, dst + j,
dest->y_stride, &sse);
num_blocks++;
}
}
src += 16 * skip * source->y_stride;
dst += 16 * skip * dest->y_stride;
} // Only return non-zero if we have at least ~1/16 samples for estimate. if (num_blocks > (tot_num_blocks >> 4)) {
assert(num_blocks != 0); return (Total / num_blocks);
} else { return 0;
}
}
#if CONFIG_TEMPORAL_DENOISING staticvoid process_denoiser_mode_change(VP8_COMP *cpi) { const VP8_COMMON *const cm = &cpi->common; int i, j; int total = 0; int num_blocks = 0; // Number of blocks skipped along row/column in computing the // nmse (normalized mean square error) of source. int skip = 2; // Only select blocks for computing nmse that have been encoded // as ZERO LAST min_consec_zero_last frames in a row. // Scale with number of temporal layers. int min_consec_zero_last = 12 / cpi->oxcf.number_of_layers; // Decision is tested for changing the denoising mode every // num_mode_change times this function is called. Note that this // function called every 8 frames, so (8 * num_mode_change) is number // of frames where denoising mode change is tested for switch. int num_mode_change = 20; // Framerate factor, to compensate for larger mse at lower framerates. // Use ref_framerate, which is full source framerate for temporal layers. // TODO(marpan): Adjust this factor. int fac_framerate = cpi->ref_framerate < 25.0f ? 80 : 100; int tot_num_blocks = cm->mb_rows * cm->mb_cols; int ystride = cpi->Source->y_stride; unsignedchar *src = cpi->Source->y_buffer; unsignedchar *dst = cpi->denoiser.yv12_last_source.y_buffer; staticconstunsignedchar const_source[16] = { 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128,
128, 128, 128, 128 }; int bandwidth = (int)(cpi->target_bandwidth); // For temporal layers, use full bandwidth (top layer). if (cpi->oxcf.number_of_layers > 1) {
LAYER_CONTEXT *lc = &cpi->layer_context[cpi->oxcf.number_of_layers - 1];
bandwidth = (int)(lc->target_bandwidth);
} // Loop through the Y plane, every skip blocks along rows and columns, // summing the normalized mean square error, only for blocks that have // been encoded as ZEROMV LAST at least min_consec_zero_last least frames in // a row and have small sum difference between current and previous frame. // Normalization here is by the contrast of the current frame block. for (i = 0; i < cm->Height; i += 16 * skip) { int block_index_row = (i >> 4) * cm->mb_cols; for (j = 0; j < cm->Width; j += 16 * skip) { int index = block_index_row + (j >> 4); if (cpi->consec_zero_last[index] >= min_consec_zero_last) { unsignedint sse; constunsignedint var =
vpx_variance16x16(src + j, ystride, dst + j, ystride, &sse); // Only consider this block as valid for noise measurement // if the sum_diff average of the current and previous frame // is small (to avoid effects from lighting change). if ((sse - var) < 128) { unsignedint sse2; constunsignedint act =
vpx_variance16x16(src + j, ystride, const_source, 0, &sse2); if (act > 0) total += sse / act;
num_blocks++;
}
}
}
src += 16 * skip * ystride;
dst += 16 * skip * ystride;
}
total = total * fac_framerate / 100;
// Only consider this frame as valid sample if we have computed nmse over // at least ~1/16 blocks, and Total > 0 (Total == 0 can happen if the // application inputs duplicate frames, or contrast is all zero). if (total > 0 && (num_blocks > (tot_num_blocks >> 4))) { // Update the recursive mean square source_diff.
total = (total << 8) / num_blocks; if (cpi->denoiser.nmse_source_diff_count == 0) { // First sample in new interval.
cpi->denoiser.nmse_source_diff = total;
cpi->denoiser.qp_avg = cm->base_qindex;
} else { // For subsequent samples, use average with weight ~1/4 for new sample.
cpi->denoiser.nmse_source_diff =
(int)((total + 3 * cpi->denoiser.nmse_source_diff) >> 2);
cpi->denoiser.qp_avg =
(int)((cm->base_qindex + 3 * cpi->denoiser.qp_avg) >> 2);
}
cpi->denoiser.nmse_source_diff_count++;
} // Check for changing the denoiser mode, when we have obtained #samples = // num_mode_change. Condition the change also on the bitrate and QP. if (cpi->denoiser.nmse_source_diff_count == num_mode_change) { // Check for going up: from normal to aggressive mode. if ((cpi->denoiser.denoiser_mode == kDenoiserOnYUV) &&
(cpi->denoiser.nmse_source_diff >
cpi->denoiser.threshold_aggressive_mode) &&
(cpi->denoiser.qp_avg < cpi->denoiser.qp_threshold_up &&
bandwidth > cpi->denoiser.bitrate_threshold)) {
vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUVAggressive);
} else { // Check for going down: from aggressive to normal mode. if (((cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive) &&
(cpi->denoiser.nmse_source_diff <
cpi->denoiser.threshold_aggressive_mode)) ||
((cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive) &&
(cpi->denoiser.qp_avg > cpi->denoiser.qp_threshold_down ||
bandwidth < cpi->denoiser.bitrate_threshold))) {
vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUV);
}
} // Reset metric and counter for next interval.
cpi->denoiser.nmse_source_diff = 0;
cpi->denoiser.qp_avg = 0;
cpi->denoiser.nmse_source_diff_count = 0;
}
} #endif
vpx_usec_timer_start(&timer); if (cpi->sf.auto_filter == 0) { #if CONFIG_TEMPORAL_DENOISING if (cpi->oxcf.noise_sensitivity && cm->frame_type != KEY_FRAME) { // Use the denoised buffer for selecting base loop filter level. // Denoised signal for current frame is stored in INTRA_FRAME. // No denoising on key frames.
vp8cx_pick_filter_level_fast(
&cpi->denoiser.yv12_running_avg[INTRA_FRAME], cpi);
} else {
vp8cx_pick_filter_level_fast(cpi->Source, cpi);
} #else
vp8cx_pick_filter_level_fast(cpi->Source, cpi); #endif
} else { #if CONFIG_TEMPORAL_DENOISING if (cpi->oxcf.noise_sensitivity && cm->frame_type != KEY_FRAME) { // Use the denoised buffer for selecting base loop filter level. // Denoised signal for current frame is stored in INTRA_FRAME. // No denoising on key frames.
vp8cx_pick_filter_level(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
cpi);
} else {
vp8cx_pick_filter_level(cpi->Source, cpi);
} #else
vp8cx_pick_filter_level(cpi->Source, cpi); #endif
}
if (cm->filter_level > 0) {
vp8cx_set_alt_lf_level(cpi, cm->filter_level);
}
#if CONFIG_MULTITHREAD if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) { /* signal that we have set filter_level */
vp8_sem_post(&cpi->h_event_end_lpf);
} #endif
// No need to apply loop-filter if the encoded frame does not update // any reference buffers. if (cm->filter_level > 0 && update_any_ref_buffers) {
vp8_loop_filter_frame(cm, &cpi->mb.e_mbd, frame_type);
}
vp8_yv12_extend_frame_borders(cm->frame_to_show);
} // Return 1 if frame is to be dropped. Update frame drop decimation // counters. int vp8_check_drop_buffer(VP8_COMP *cpi) {
VP8_COMMON *cm = &cpi->common; int drop_mark = (int)(cpi->oxcf.drop_frames_water_mark *
cpi->oxcf.optimal_buffer_level / 100); int drop_mark75 = drop_mark * 2 / 3; int drop_mark50 = drop_mark / 4; int drop_mark25 = drop_mark / 8; if (cpi->drop_frames_allowed) { /* The reset to decimation 0 is only done here for one pass. * Once it is set two pass leaves decimation on till the next kf.
*/ if (cpi->buffer_level > drop_mark && cpi->decimation_factor > 0) {
cpi->decimation_factor--;
}
/* The following decimates the frame rate according to a regular * pattern (i.e. to 1/2 or 2/3 frame rate) This can be used to help * prevent buffer under-run in CBR mode. Alternatively it might be * desirable in some situations to drop frame rate but throw more bits * at each frame. * * Note that dropping a key frame can be problematic if spatial * resampling is also active
*/ if (cpi->decimation_factor > 0 && cpi->drop_frames_allowed) { switch (cpi->decimation_factor) { case 1:
cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 3 / 2; break; case 2:
cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4; break; case 3:
cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4; break;
}
/* Note that we should not throw out a key frame (especially when * spatial resampling is enabled).
*/ if (cm->frame_type == KEY_FRAME) {
cpi->decimation_count = cpi->decimation_factor;
} elseif (cpi->decimation_count > 0) {
cpi->decimation_count--;
cm->current_video_frame++;
cpi->frames_since_key++;
cpi->ext_refresh_frame_flags_pending = 0; // We advance the temporal pattern for dropped frames.
cpi->temporal_pattern_counter++;
#if CONFIG_INTERNAL_STATS
cpi->count++; #endif
cpi->buffer_level = cpi->bits_off_target;
if (cpi->oxcf.number_of_layers > 1) { unsignedint i;
/* Propagate bits saved by dropping the frame to higher * layers
*/ for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
LAYER_CONTEXT *lc = &cpi->layer_context[i];
lc->bits_off_target += (int)(lc->target_bandwidth / lc->framerate); if (lc->bits_off_target > lc->maximum_buffer_size) {
lc->bits_off_target = lc->maximum_buffer_size;
}
lc->buffer_level = lc->bits_off_target;
}
} return 1;
} else {
cpi->decimation_count = cpi->decimation_factor;
}
} else {
cpi->decimation_count = 0;
} return 0;
}
staticvoid encode_frame_to_data_rate(VP8_COMP *cpi, size_t *size, unsignedchar *dest, unsignedchar *dest_end, unsignedint *frame_flags) { int Q; int frame_over_shoot_limit; int frame_under_shoot_limit;
int Loop = 0;
VP8_COMMON *cm = &cpi->common; int active_worst_qchanged = 0;
#if !CONFIG_REALTIME_ONLY int q_low; int q_high; int zbin_oq_high; int zbin_oq_low = 0; int top_index; int bottom_index; int overshoot_seen = 0; int undershoot_seen = 0; #endif
/* Clear down mmx registers to allow floating point in what follows */
vpx_clear_system_state();
if (cpi->force_next_frame_intra) {
cm->frame_type = KEY_FRAME; /* delayed intra frame */
cpi->force_next_frame_intra = 0;
}
/* For an alt ref frame in 2 pass we skip the call to the second pass * function that sets the target bandwidth
*/ switch (cpi->pass) { #if !CONFIG_REALTIME_ONLY case 2: if (cpi->common.refresh_alt_ref_frame) { /* Per frame bit target for the alt ref frame */
cpi->per_frame_bandwidth = cpi->twopass.gf_bits; /* per second target bitrate */
cpi->target_bandwidth =
(int)(cpi->twopass.gf_bits * cpi->output_framerate);
} break; #endif// !CONFIG_REALTIME_ONLY default: { constdouble per_frame_bandwidth =
round(cpi->target_bandwidth / cpi->output_framerate);
cpi->per_frame_bandwidth = (int)VPXMIN(per_frame_bandwidth, INT_MAX); break;
}
}
/* Default turn off buffer to buffer copying */
cm->copy_buffer_to_gf = 0;
cm->copy_buffer_to_arf = 0;
/* Clear zbin over-quant value and mode boost values. */
cpi->mb.zbin_over_quant = 0;
cpi->mb.zbin_mode_boost = 0;
/* Enable or disable mode based tweaking of the zbin * For 2 Pass Only used where GF/ARF prediction quality * is above a threshold
*/
cpi->mb.zbin_mode_boost_enabled = 1; if (cpi->pass == 2) { if (cpi->gfu_boost <= 400) {
cpi->mb.zbin_mode_boost_enabled = 0;
}
}
/* Current default encoder behaviour for the altref sign bias */ if (cpi->source_alt_ref_active) {
cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
} else {
cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
}
/* Check to see if a key frame is signaled * For two pass with auto key frame enabled cm->frame_type may already * be set, but not for one pass.
*/ if ((cm->current_video_frame == 0) || (cm->frame_flags & FRAMEFLAGS_KEY) ||
(cpi->oxcf.auto_key &&
(cpi->frames_since_key % cpi->key_frame_frequency == 0))) { /* Key frame from VFW/auto-keyframe/first frame */
cm->frame_type = KEY_FRAME; #if CONFIG_TEMPORAL_DENOISING if (cpi->oxcf.noise_sensitivity == 4) { // For adaptive mode, reset denoiser to normal mode on key frame.
vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUV);
} #endif
}
if (cpi->oxcf.mr_encoder_id) { // Check if lower resolution is available for motion vector reuse. if (cm->frame_type != KEY_FRAME) {
cpi->mr_low_res_mv_avail = 1;
cpi->mr_low_res_mv_avail &= !(low_res_frame_info->is_frame_dropped);
if (cpi->ref_frame_flags & VP8_LAST_FRAME)
cpi->mr_low_res_mv_avail &=
(cpi->current_ref_frames[LAST_FRAME] ==
low_res_frame_info->low_res_ref_frames[LAST_FRAME]);
if (cpi->ref_frame_flags & VP8_GOLD_FRAME)
cpi->mr_low_res_mv_avail &=
(cpi->current_ref_frames[GOLDEN_FRAME] ==
low_res_frame_info->low_res_ref_frames[GOLDEN_FRAME]);
// Don't use altref to determine whether low res is available. // TODO (marpan): Should we make this type of condition on a // per-reference frame basis? /* if (cpi->ref_frame_flags & VP8_ALTR_FRAME) cpi->mr_low_res_mv_avail &= (cpi->current_ref_frames[ALTREF_FRAME] == low_res_frame_info->low_res_ref_frames[ALTREF_FRAME]);
*/
} // Disable motion vector reuse (i.e., disable any usage of the low_res) // if the previous lower stream is skipped/disabled. if (low_res_frame_info->skip_encoding_prev_stream) {
cpi->mr_low_res_mv_avail = 0;
}
} // This stream is not skipped (i.e., it's being encoded), so set this skip // flag to 0. This is needed for the next stream (i.e., which is the next // frame to be encoded).
low_res_frame_info->skip_encoding_prev_stream = 0;
// On a key frame: For the lowest resolution, keep track of the key frame // counter value. For the higher resolutions, reset the current video // frame counter to that of the lowest resolution. // This is done to the handle the case where we may stop/start encoding // higher layer(s). The restart-encoding of higher layer is only signaled // by a key frame for now. // TODO (marpan): Add flag to indicate restart-encoding of higher layer. if (cm->frame_type == KEY_FRAME) { if (cpi->oxcf.mr_encoder_id) { // If the initial starting value of the buffer level is zero (this can // happen because we may have not started encoding this higher stream), // then reset it to non-zero value based on |starting_buffer_level|. if (cpi->common.current_video_frame == 0 && cpi->buffer_level == 0) { unsignedint i;
cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
cpi->buffer_level = cpi->oxcf.starting_buffer_level; for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
LAYER_CONTEXT *lc = &cpi->layer_context[i];
lc->bits_off_target = lc->starting_buffer_level;
lc->buffer_level = lc->starting_buffer_level;
}
}
cpi->common.current_video_frame =
low_res_frame_info->key_frame_counter_value;
} else {
low_res_frame_info->key_frame_counter_value =
cpi->common.current_video_frame;
}
}
} #endif
// Find the reference frame closest to the current frame.
cpi->closest_reference_frame = LAST_FRAME; if (cm->frame_type != KEY_FRAME) { int i;
MV_REFERENCE_FRAME closest_ref = INTRA_FRAME; if (cpi->ref_frame_flags & VP8_LAST_FRAME) {
closest_ref = LAST_FRAME;
} elseif (cpi->ref_frame_flags & VP8_GOLD_FRAME) {
closest_ref = GOLDEN_FRAME;
} elseif (cpi->ref_frame_flags & VP8_ALTR_FRAME) {
closest_ref = ALTREF_FRAME;
} for (i = 1; i <= 3; ++i) {
vpx_ref_frame_type_t ref_frame_type =
(vpx_ref_frame_type_t)((i == 3) ? 4 : i); if (cpi->ref_frame_flags & ref_frame_type) { if ((cm->current_video_frame - cpi->current_ref_frames[i]) <
(cm->current_video_frame - cpi->current_ref_frames[closest_ref])) {
closest_ref = i;
}
}
}
cpi->closest_reference_frame = closest_ref;
}
/* Set various flags etc to special state if it is a key frame */ if (cm->frame_type == KEY_FRAME) { int i;
// Set the loop filter deltas and segmentation map update
setup_features(cpi);
/* The alternate reference frame cannot be active for a key frame */
cpi->source_alt_ref_active = 0;
/* Reset the RD threshold multipliers to default of * 1 (128) */ for (i = 0; i < MAX_MODES; ++i) {
cpi->mb.rd_thresh_mult[i] = 128;
}
// Reset the zero_last counter to 0 on key frame.
memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
memset(cpi->consec_zero_last_mvbias, 0,
(cpi->common.mb_rows * cpi->common.mb_cols));
}
#if 0 /* Experimental code for lagged compress and one pass * Initialise one_pass GF frames stats * Update stats used for GF selection
*/
{
cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
/* Decide how big to make the frame */ if (!vp8_pick_frame_size(cpi)) { /*TODO: 2 drop_frame and return code could be put together. */ #if CONFIG_MULTI_RES_ENCODING
vp8_store_drop_frame_info(cpi); #endif
cm->current_video_frame++;
cpi->frames_since_key++;
cpi->ext_refresh_frame_flags_pending = 0; // We advance the temporal pattern for dropped frames.
cpi->temporal_pattern_counter++; return;
}
/* Reduce active_worst_allowed_q for CBR if our buffer is getting too full. * This has a knock on effect on active best quality as well. * For CBR if the buffer reaches its maximum level then we can no longer * save up bits for later frames so we might as well use them up * on the current frame.
*/ if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
(cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) &&
cpi->buffered_mode) { /* Max adjustment is 1/4 */ int Adjustment = cpi->active_worst_quality / 4;
/* Set an active best quality and if necessary active worst quality * There is some odd behavior for one pass here that needs attention.
*/ if ((cpi->pass == 2) || (cpi->ni_frames > 150)) {
vpx_clear_system_state();
Q = cpi->active_worst_quality;
if (cm->frame_type == KEY_FRAME) { if (cpi->pass == 2) { if (cpi->gfu_boost > 600) {
cpi->active_best_quality = kf_low_motion_minq[Q];
} else {
cpi->active_best_quality = kf_high_motion_minq[Q];
}
/* Special case for key frames forced because we have reached * the maximum key frame interval. Here force the Q to a range * based on the ambient Q to reduce the risk of popping
*/ if (cpi->this_key_frame_forced) { if (cpi->active_best_quality > cpi->avg_frame_qindex * 7 / 8) {
cpi->active_best_quality = cpi->avg_frame_qindex * 7 / 8;
} elseif (cpi->active_best_quality < (cpi->avg_frame_qindex >> 2)) {
cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
}
}
} /* One pass more conservative */ else {
cpi->active_best_quality = kf_high_motion_minq[Q];
}
}
elseif (cpi->oxcf.number_of_layers == 1 &&
(cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame)) { /* Use the lower of cpi->active_worst_quality and recent * average Q as basis for GF/ARF Q limit unless last frame was * a key frame.
*/ if ((cpi->frames_since_key > 1) &&
(cpi->avg_frame_qindex < cpi->active_worst_quality)) {
Q = cpi->avg_frame_qindex;
}
/* For constrained quality don't allow Q less than the cq level */ if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
(Q < cpi->cq_target_quality)) {
Q = cpi->cq_target_quality;
}
/* Constrained quality use slightly lower active best. */ if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
cpi->active_best_quality = cpi->active_best_quality * 15 / 16;
}
} /* One pass more conservative */ else {
cpi->active_best_quality = gf_high_motion_minq[Q];
}
} else {
cpi->active_best_quality = inter_minq[Q];
/* For the constant/constrained quality mode we don't want * q to fall below the cq level.
*/ if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
(cpi->active_best_quality < cpi->cq_target_quality)) { /* If we are strongly undershooting the target rate in the last * frames then use the user passed in cq value not the auto * cq value.
*/ if (cpi->rolling_actual_bits < cpi->min_frame_bandwidth) {
cpi->active_best_quality = cpi->oxcf.cq_level;
} else {
cpi->active_best_quality = cpi->cq_target_quality;
}
}
}
/* If CBR and the buffer is as full then it is reasonable to allow * higher quality on the frames to prevent bits just going to waste.
*/ if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) { /* Note that the use of >= here elliminates the risk of a divide * by 0 error in the else if clause
*/ if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size) {
cpi->active_best_quality = cpi->best_quality;
cpi->active_best_quality -= min_qadjustment;
}
}
} /* Make sure constrained quality mode limits are adhered to for the first * few frames of one pass encodes
*/ elseif (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) { if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame ||
cpi->common.refresh_alt_ref_frame) {
cpi->active_best_quality = cpi->best_quality;
} elseif (cpi->active_best_quality < cpi->cq_target_quality) {
cpi->active_best_quality = cpi->cq_target_quality;
}
}
/* Clip the active best and worst quality values to limits */ if (cpi->active_worst_quality > cpi->worst_quality) {
cpi->active_worst_quality = cpi->worst_quality;
}
if (cpi->active_best_quality < cpi->best_quality) {
cpi->active_best_quality = cpi->best_quality;
}
if (cpi->active_worst_quality < cpi->active_best_quality) {
cpi->active_worst_quality = cpi->active_best_quality;
}
/* Set highest allowed value for Zbin over quant */ if (cm->frame_type == KEY_FRAME) {
zbin_oq_high = 0;
} elseif ((cpi->oxcf.number_of_layers == 1) &&
((cm->refresh_alt_ref_frame ||
(cm->refresh_golden_frame && !cpi->source_alt_ref_active)))) {
zbin_oq_high = 16;
} else {
zbin_oq_high = ZBIN_OQ_MAX;
} #endif
compute_skin_map(cpi);
/* Setup background Q adjustment for error resilient mode. * For multi-layer encodes only enable this for the base layer.
*/ if (cpi->cyclic_refresh_mode_enabled) { // Special case for screen_content_mode with golden frame updates. int disable_cr_gf =
(cpi->oxcf.screen_content_mode == 2 && cm->refresh_golden_frame); if (cpi->current_layer == 0 && cpi->force_maxqp == 0 && !disable_cr_gf) {
cyclic_background_refresh(cpi, Q, 0);
} else {
disable_segmentation(cpi);
}
}
if (cpi->oxcf.noise_sensitivity > 0) { unsignedchar *src; int l = 0;
switch (cpi->oxcf.noise_sensitivity) { case 1: l = 20; break; case 2: l = 40; break; case 3: l = 60; break; case 4: l = 80; break; case 5: l = 100; break; case 6: l = 150; break;
}
if (cm->frame_type == KEY_FRAME) { if (resize_key_frame(cpi)) { /* If the frame size has changed, need to reset Q, quantizer, * and background refresh.
*/
Q = vp8_regulate_q(cpi, cpi->this_frame_target); if (cpi->cyclic_refresh_mode_enabled) { if (cpi->current_layer == 0) {
cyclic_background_refresh(cpi, Q, 0);
} else {
disable_segmentation(cpi);
}
} // Reset the zero_last counter to 0 on key frame.
memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
memset(cpi->consec_zero_last_mvbias, 0,
(cpi->common.mb_rows * cpi->common.mb_cols));
vp8_set_quantizer(cpi, Q);
}
vp8_setup_key_frame(cpi);
}
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
{ if (cpi->oxcf.error_resilient_mode) cm->refresh_entropy_probs = 0;
if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) { if (cm->frame_type == KEY_FRAME) cm->refresh_entropy_probs = 1;
}
if (cm->refresh_entropy_probs == 0) { /* save a copy for later refresh */
memcpy(&cm->lfc, &cm->fc, sizeof(cm->fc));
}
/* Limit Q range for the adaptive loop. */
bottom_index = cpi->active_best_quality;
top_index = cpi->active_worst_quality;
q_low = cpi->active_best_quality;
q_high = cpi->active_worst_quality;
Loop = 1;
continue;
} #endif
}
vpx_clear_system_state();
if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
/* Are we are overshooting and up against the limit of active max Q. */ if (!cpi->rt_always_update_correction_factor &&
((cpi->pass != 2) ||
(cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
(Q == cpi->active_worst_quality) &&
(cpi->active_worst_quality < cpi->worst_quality) &&
(cpi->projected_frame_size > frame_over_shoot_limit)) { int over_size_percent =
((cpi->projected_frame_size - frame_over_shoot_limit) * 100) /
frame_over_shoot_limit;
/* If so is there any scope for relaxing it */ while ((cpi->active_worst_quality < cpi->worst_quality) &&
(over_size_percent > 0)) {
cpi->active_worst_quality++; /* Assume 1 qstep = about 4% on frame size. */
over_size_percent = (int)(over_size_percent * 0.96);
} #if !CONFIG_REALTIME_ONLY
top_index = cpi->active_worst_quality; #endif// !CONFIG_REALTIME_ONLY /* If we have updated the active max Q do not call * vp8_update_rate_correction_factors() this loop.
*/
active_worst_qchanged = 1;
} else {
active_worst_qchanged = 0;
}
#if CONFIG_REALTIME_ONLY
Loop = 0; #else /* Special case handling for forced key frames */ if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) { int last_q = Q; int kf_err = vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);
/* The key frame is not good enough */ if (kf_err > ((cpi->ambient_err * 7) >> 3)) { /* Lower q_high */
q_high = (Q > q_low) ? (Q - 1) : q_low;
/* Adjust Q */
Q = (q_high + q_low) >> 1;
} /* The key frame is much better than the previous frame */ elseif (kf_err < (cpi->ambient_err >> 1)) { /* Raise q_low */
q_low = (Q < q_high) ? (Q + 1) : q_high;
/* Adjust Q */
Q = (q_high + q_low + 1) >> 1;
}
/* Clamp Q to upper and lower limits: */ if (Q > q_high) {
Q = q_high;
} elseif (Q < q_low) {
Q = q_low;
}
Loop = Q != last_q;
}
/* Is the projected frame size out of range and are we allowed * to attempt to recode.
*/ elseif (recode_loop_test(cpi, frame_over_shoot_limit,
frame_under_shoot_limit, Q, top_index,
bottom_index)) { int last_q = Q; int Retries = 0;
/* Frame size out of permitted range. Update correction factor * & compute new Q to try...
*/
/* Frame is too large */ if (cpi->projected_frame_size > cpi->this_frame_target) { /* Raise Qlow as to at least the current value */
q_low = (Q < q_high) ? (Q + 1) : q_high;
/* If we are using over quant do the same for zbin_oq_low */ if (cpi->mb.zbin_over_quant > 0) {
zbin_oq_low = (cpi->mb.zbin_over_quant < zbin_oq_high)
? (cpi->mb.zbin_over_quant + 1)
: zbin_oq_high;
}
if (undershoot_seen) { /* Update rate_correction_factor unless * cpi->active_worst_quality has changed.
*/ if (!active_worst_qchanged) {
vp8_update_rate_correction_factors(cpi, 1);
}
overshoot_seen = 1;
} /* Frame is too small */ else { if (cpi->mb.zbin_over_quant == 0) { /* Lower q_high if not using over quant */
q_high = (Q > q_low) ? (Q - 1) : q_low;
} else { /* else lower zbin_oq_high */
zbin_oq_high = (cpi->mb.zbin_over_quant > zbin_oq_low)
? (cpi->mb.zbin_over_quant - 1)
: zbin_oq_low;
}
if (overshoot_seen) { /* Update rate_correction_factor unless * cpi->active_worst_quality has changed.
*/ if (!active_worst_qchanged) {
vp8_update_rate_correction_factors(cpi, 1);
}
Q = (q_high + q_low) / 2;
/* Adjust cpi->zbin_over_quant (only allowed when Q * is max)
*/ if (Q < MAXQ) {
cpi->mb.zbin_over_quant = 0;
} else {
cpi->mb.zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
}
} else { /* Update rate_correction_factor unless * cpi->active_worst_quality has changed.
*/ if (!active_worst_qchanged) {
vp8_update_rate_correction_factors(cpi, 0);
}
Q = vp8_regulate_q(cpi, cpi->this_frame_target);
/* Special case reset for qlow for constrained quality. * This should only trigger where there is very substantial * undershoot on a frame and the auto cq level is above * the user passsed in value.
*/ if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
(Q < q_low)) {
q_low = Q;
}
if (Loop == 1) {
vp8_restore_coding_context(cpi); #if CONFIG_INTERNAL_STATS
cpi->tot_recode_hits++; #endif
}
} while (Loop == 1);
#ifdefined(DROP_UNCODED_FRAMES) /* if there are no coded macroblocks at all drop this frame */ if (cpi->common.MBs == cpi->mb.skip_true_count &&
(cpi->drop_frame_count & 7) != 7 && cm->frame_type != KEY_FRAME) {
cpi->common.current_video_frame++;
cpi->frames_since_key++;
cpi->drop_frame_count++;
cpi->ext_refresh_frame_flags_pending = 0; // We advance the temporal pattern for dropped frames.
cpi->temporal_pattern_counter++; return;
}
cpi->drop_frame_count = 0; #endif
#if 0 /* Experimental code for lagged and one pass * Update stats used for one pass GF selection
*/
{
cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
} #endif
/* Special case code to reduce pulsing when key frames are forced at a * fixed interval. Note the reconstruction error if it is the frame before * the force key frame
*/ if (cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0)) {
cpi->ambient_err =
vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);
}
/* This frame's MVs are saved and will be used in next frame's MV predictor. * Last frame has one more line(add to bottom) and one more column(add to * right) than cm->mip. The edge elements are initialized to 0.
*/ #if CONFIG_MULTI_RES_ENCODING if (!cpi->oxcf.mr_encoder_id && cm->show_frame) #else if (cm->show_frame) /* do not save for altref frame */ #endif
{ int mb_row; int mb_col; /* Point to beginning of allocated MODE_INFO arrays. */
MODE_INFO *tmp = cm->mip;
/* Count last ref frame 0,0 usage on current encoded frame. */
{ int mb_row; int mb_col; /* Point to beginning of MODE_INFO arrays. */
MODE_INFO *tmp = cm->mi;
cpi->zeromv_count = 0;
if (cm->frame_type != KEY_FRAME) { for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) { for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) { if (tmp->mbmi.mode == ZEROMV && tmp->mbmi.ref_frame == LAST_FRAME) {
cpi->zeromv_count++;
}
tmp++;
}
tmp++;
}
}
}
/* Update the GF usage maps. * This is done after completing the compression of a frame when all * modes etc. are finalized but before loop filter
*/ if (cpi->oxcf.number_of_layers == 1) {
vp8_update_gf_usage_maps(cpi, cm, &cpi->mb);
}
if (cm->frame_type == KEY_FRAME) cm->refresh_last_frame = 1;
/* For inter frames the current default behavior is that when * cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer * This is purely an encoder decision at present. * Avoid this behavior when refresh flags are set by the user.
*/ if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame &&
!cpi->ext_refresh_frame_flags_pending) {
cm->copy_buffer_to_arf = 2;
} else {
cm->copy_buffer_to_arf = 0;
}
cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
#if CONFIG_TEMPORAL_DENOISING // Get some measure of the amount of noise, by measuring the (partial) mse // between source and denoised buffer, for y channel. Partial refers to // computing the sse for a sub-sample of the frame (i.e., skip x blocks along // row/column), // and only for blocks in that set that are consecutive ZEROMV_LAST mode. // Do this every ~8 frames, to further reduce complexity. // TODO(marpan): Keep this for now for the case cpi->oxcf.noise_sensitivity < // 4, // should be removed in favor of the process_denoiser_mode_change() function // below. if (cpi->oxcf.noise_sensitivity > 0 && cpi->oxcf.noise_sensitivity < 4 &&
!cpi->oxcf.screen_content_mode && cpi->frames_since_key % 8 == 0 &&
cm->frame_type != KEY_FRAME) {
cpi->mse_source_denoised = measure_square_diff_partial(
&cpi->denoiser.yv12_running_avg[INTRA_FRAME], cpi->Source, cpi);
}
// For the adaptive denoising mode (noise_sensitivity == 4), sample the mse // of source diff (between current and previous frame), and determine if we // should switch the denoiser mode. Sampling refers to computing the mse for // a sub-sample of the frame (i.e., skip x blocks along row/column), and // only for blocks in that set that have used ZEROMV LAST, along with some // constraint on the sum diff between blocks. This process is called every // ~8 frames, to further reduce complexity. if (cpi->oxcf.noise_sensitivity == 4 && !cpi->oxcf.screen_content_mode &&
cpi->frames_since_key % 8 == 0 && cm->frame_type != KEY_FRAME) {
process_denoiser_mode_change(cpi);
} #endif
#if CONFIG_MULTITHREAD if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) { /* start loopfilter in separate thread */
vp8_sem_post(&cpi->h_event_start_lpf);
cpi->b_lpf_running = 1; /* wait for the filter_level to be picked so that we can continue with
* stream packing */
vp8_sem_wait(&cpi->h_event_end_lpf);
} else #endif
{
vp8_loopfilter_frame(cpi, cm);
}
/* build the bitstream */
vp8_pack_bitstream(cpi, dest, dest_end, size);
/* Move storing frame_type out of the above loop since it is also
* needed in motion search besides loopfilter */
cm->last_frame_type = cm->frame_type;
if (cpi->oxcf.number_of_layers > 1) { unsignedint i; for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
cpi->layer_context[i].total_byte_count += (*size);
}
}
if (!active_worst_qchanged) vp8_update_rate_correction_factors(cpi, 2);
cpi->last_q[cm->frame_type] = cm->base_qindex;
if (cm->frame_type == KEY_FRAME) {
vp8_adjust_key_frame_context(cpi);
}
/* Keep a record of ambient average Q. */ if (cm->frame_type != KEY_FRAME) {
cpi->avg_frame_qindex =
(2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
}
/* Keep a record from which we can calculate the average Q excluding * GF updates and key frames
*/ if ((cm->frame_type != KEY_FRAME) &&
((cpi->oxcf.number_of_layers > 1) ||
(!cm->refresh_golden_frame && !cm->refresh_alt_ref_frame))) {
cpi->ni_frames++;
/* Calculate the average Q for normal inter frames (not key or GFU * frames).
*/ if (cpi->pass == 2) {
cpi->ni_tot_qi += Q;
cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
} else { /* Damp value for first few frames */ if (cpi->ni_frames > 150) {
cpi->ni_tot_qi += Q;
cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
} /* For one pass, early in the clip ... average the current frame Q * value with the worstq entered by the user as a dampening measure
*/ else {
cpi->ni_tot_qi += Q;
cpi->ni_av_qi =
((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
}
/* If the average Q is higher than what was used in the last * frame (after going through the recode loop to keep the frame * size within range) then use the last frame value - 1. The -1 * is designed to stop Q and hence the data rate, from * progressively falling away during difficult sections, but at * the same time reduce the number of iterations around the * recode loop.
*/ if (Q > cpi->ni_av_qi) cpi->ni_av_qi = Q - 1;
}
}
/* Update the buffer level variable. */ /* Non-viewable frames are a special case and are treated as pure overhead. */ if (!cm->show_frame) {
cpi->bits_off_target -= cpi->projected_frame_size;
} else {
cpi->bits_off_target +=
cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
}
/* Clip the buffer level to the maximum specified buffer size */ if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
}
// Don't let the buffer level go below some threshold, given here // by -|maximum_buffer_size|. For now we only do this for // screen content input. if (cpi->oxcf.screen_content_mode &&
cpi->bits_off_target < -cpi->oxcf.maximum_buffer_size) {
cpi->bits_off_target = -cpi->oxcf.maximum_buffer_size;
}
/* Rolling monitors of whether we are over or underspending used to * help regulate min and Max Q in two pass.
*/
cpi->rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
(int64_t)cpi->rolling_target_bits * 3 + cpi->this_frame_target, 2);
cpi->rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
(int64_t)cpi->rolling_actual_bits * 3 + cpi->projected_frame_size, 2);
cpi->long_rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
(int64_t)cpi->long_rolling_target_bits * 31 + cpi->this_frame_target, 5);
cpi->long_rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
(int64_t)cpi->long_rolling_actual_bits * 31 + cpi->projected_frame_size,
5);
/* Actual bits spent */
cpi->total_actual_bits += cpi->projected_frame_size;
/* Propagate values to higher temporal layers */ if (cpi->oxcf.number_of_layers > 1) { unsignedint i;
for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
LAYER_CONTEXT *lc = &cpi->layer_context[i]; int bits_off_for_this_layer = (int)round(
lc->target_bandwidth / lc->framerate - cpi->projected_frame_size);
lc->bits_off_target += bits_off_for_this_layer;
/* Clip buffer level to maximum buffer size for the layer */ if (lc->bits_off_target > lc->maximum_buffer_size) {
lc->bits_off_target = lc->maximum_buffer_size;
}
/* Update bits left to the kf and gf groups to account for overshoot * or undershoot on these frames
*/ if (cm->frame_type == KEY_FRAME) {
cpi->twopass.kf_group_bits +=
cpi->this_frame_target - cpi->projected_frame_size;
if (cm->refresh_last_frame & cm->refresh_golden_frame) { /* both refreshed */
cpi->gold_is_last = 1;
} elseif (cm->refresh_last_frame ^ cm->refresh_golden_frame) { /* 1 refreshed but not the other */
cpi->gold_is_last = 0;
}
if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) { /* both refreshed */
cpi->alt_is_last = 1;
} elseif (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) { /* 1 refreshed but not the other */
cpi->alt_is_last = 0;
}
if (cm->refresh_alt_ref_frame &
cm->refresh_golden_frame) { /* both refreshed */
cpi->gold_is_alt = 1;
} elseif (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) { /* 1 refreshed but not the other */
cpi->gold_is_alt = 0;
}
/* Clear the one shot update flags for segmentation map and mode/ref * loop filter deltas.
*/
cpi->mb.e_mbd.update_mb_segmentation_map = 0;
cpi->mb.e_mbd.update_mb_segmentation_data = 0;
cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
/* Don't increment frame counters if this was an altref buffer update * not a real frame
*/ if (cm->show_frame) {
cm->current_video_frame++;
cpi->frames_since_key++;
cpi->temporal_pattern_counter++;
}
if (!cpi->source) { /* Read last frame source if we are encoding first pass. */ if (cpi->pass == 1 && cm->current_video_frame > 0) { if ((cpi->last_source =
vp8_lookahead_peek(cpi->lookahead, 1, PEEK_BACKWARD)) == NULL) { return -1;
}
}
if ((cpi->source = vp8_lookahead_pop(cpi->lookahead, flush))) {
cm->show_frame = 1;
this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
last_duration = cpi->last_end_time_stamp_seen - cpi->last_time_stamp_seen; // Cap this to avoid overflow of (this_duration - last_duration) * 10
this_duration = VPXMIN(this_duration, INT64_MAX / 10); /* do a step update if the duration changes by 10% */ if (last_duration) {
step = (int)(((this_duration - last_duration) * 10 / last_duration));
}
}
if (this_duration) { if (step) {
cpi->ref_framerate = 10000000.0 / this_duration;
} else { double avg_duration, interval;
/* Average this frame's rate into the last second's average * frame rate. If we haven't seen 1 second yet, then average * over the whole interval seen.
*/
interval = (double)(cpi->source->ts_end - cpi->first_time_stamp_ever); if (interval > 10000000.0) interval = 10000000;
cpi->ref_framerate = 10000000.0 / avg_duration;
} #if CONFIG_MULTI_RES_ENCODING if (cpi->oxcf.mr_total_resolutions > 1) {
LOWER_RES_FRAME_INFO *low_res_frame_info =
(LOWER_RES_FRAME_INFO *)cpi->oxcf.mr_low_res_mode_info; // Frame rate should be the same for all spatial layers in // multi-res-encoding (simulcast), so we constrain the frame for // higher layers to be that of lowest resolution. This is needed // as he application may decide to skip encoding a high layer and // then start again, in which case a big jump in time-stamps will // be received for that high layer, which will yield an incorrect // frame rate (from time-stamp adjustment in above calculation). if (cpi->oxcf.mr_encoder_id) { if (!low_res_frame_info->skip_encoding_base_stream)
cpi->ref_framerate = low_res_frame_info->low_res_framerate;
} else { // Keep track of frame rate for lowest resolution.
low_res_frame_info->low_res_framerate = cpi->ref_framerate; // The base stream is being encoded so set skip flag to 0.
low_res_frame_info->skip_encoding_base_stream = 0;
}
} #endif if (cpi->oxcf.number_of_layers > 1) { unsignedint i;
/* Update frame rates for each layer */
assert(cpi->oxcf.number_of_layers <= VPX_TS_MAX_LAYERS); for (i = 0; i < cpi->oxcf.number_of_layers && i < VPX_TS_MAX_LAYERS;
++i) {
LAYER_CONTEXT *lc = &cpi->layer_context[i];
lc->framerate = cpi->ref_framerate / cpi->oxcf.rate_decimator[i];
}
} else {
vp8_new_framerate(cpi, cpi->ref_framerate);
}
}
#endif /* find a free buffer for the new frame */
{ int i = 0; for (; i < NUM_YV12_BUFFERS; ++i) { if (!cm->yv12_fb[i].flags) {
cm->new_fb_idx = i; break;
}
}
if (cm->refresh_entropy_probs == 0) {
memcpy(&cm->fc, &cm->lfc, sizeof(cm->fc));
}
/* Save the contexts separately for alt ref, gold and last. */ /* (TODO jbb -> Optimize this with pointers to avoid extra copies. ) */ if (cm->refresh_alt_ref_frame) memcpy(&cpi->lfc_a, &cm->fc, sizeof(cm->fc));
if (cm->refresh_golden_frame) memcpy(&cpi->lfc_g, &cm->fc, sizeof(cm->fc));
if (cm->refresh_last_frame) memcpy(&cpi->lfc_n, &cm->fc, sizeof(cm->fc));
/* if it's a dropped frame honor the requests on subsequent frames */ if (*size > 0) {
cpi->droppable = !frame_is_reference(cpi);
/* return to normal state */
cm->refresh_entropy_probs = 1;
cm->refresh_alt_ref_frame = 0;
cm->refresh_golden_frame = 0;
cm->refresh_last_frame = 1;
cm->frame_type = INTER_FRAME;
}
/* Save layer specific state */ if (cpi->oxcf.number_of_layers > 1) vp8_save_layer_context(cpi);
if (cpi->common.frame_to_show) {
*dest = *cpi->common.frame_to_show;
dest->y_width = cpi->common.Width;
dest->y_height = cpi->common.Height;
dest->uv_height = cpi->common.Height / 2;
ret = 0;
} else {
ret = -1;
}
#endif
vpx_clear_system_state(); return ret;
}
}
int vp8_set_roimap(VP8_COMP *cpi, unsignedchar *map, unsignedint rows, unsignedint cols, int delta_q[4], int delta_lf[4], unsignedint threshold[4]) { signedchar feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS]; int internal_delta_q[MAX_MB_SEGMENTS]; constint range = 63; int i;
// Check number of rows and columns match if (cpi->common.mb_rows != (int)rows || cpi->common.mb_cols != (int)cols) { return -1;
}
for (i = 0; i < MAX_MB_SEGMENTS; ++i) { // Note abs() alone can't be used as the behavior of abs(INT_MIN) is // undefined. if (delta_q[i] > range || delta_q[i] < -range || delta_lf[i] > range ||
delta_lf[i] < -range) { return -1;
}
}
/* Set up the quant segment data */
feature_data[MB_LVL_ALT_Q][0] = internal_delta_q[0];
feature_data[MB_LVL_ALT_Q][1] = internal_delta_q[1];
feature_data[MB_LVL_ALT_Q][2] = internal_delta_q[2];
feature_data[MB_LVL_ALT_Q][3] = internal_delta_q[3];
/* Set up the loop segment data s */
feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
/* Loop through the Y plane raw and reconstruction data summing * (square differences)
*/ for (i = 0; i < source->y_height; i += 16) { for (j = 0; j < source->y_width; j += 16) { unsignedint sse;
Total += vpx_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride,
&sse);
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.