Move safe_minmax.h to webrtc namespace

Bug: webrtc:42232595
Change-Id: Ia3d96dfe1b1c25b6cc21bbd99d24ded7461924cd
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/378061
Reviewed-by: Harald Alvestrand <hta@webrtc.org>
Commit-Queue: Evan Shrubsole <eshr@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#43942}
This commit is contained in:
Evan Shrubsole 2025-02-20 09:42:51 +00:00 committed by WebRTC LUCI CQ
parent ad82b6e45b
commit d9dd939d66
43 changed files with 97 additions and 92 deletions

View File

@ -18,7 +18,7 @@
namespace webrtc {
namespace {
bool Limit(float* value, float min, float max) {
float clamped = rtc::SafeClamp(*value, min, max);
float clamped = SafeClamp(*value, min, max);
clamped = std::isfinite(clamped) ? clamped : min;
bool res = *value == clamped;
*value = clamped;
@ -26,14 +26,14 @@ bool Limit(float* value, float min, float max) {
}
bool Limit(size_t* value, size_t min, size_t max) {
size_t clamped = rtc::SafeClamp(*value, min, max);
size_t clamped = SafeClamp(*value, min, max);
bool res = *value == clamped;
*value = clamped;
return res;
}
bool Limit(int* value, int min, int max) {
int clamped = rtc::SafeClamp(*value, min, max);
int clamped = SafeClamp(*value, min, max);
bool res = *value == clamped;
*value = clamped;
return res;

View File

@ -45,7 +45,7 @@ std::optional<AudioEncoderL16::Config> AudioEncoderL16::SdpToConfig(
if (ptime_iter != format.parameters.end()) {
const auto ptime = StringToNumber<int>(ptime_iter->second);
if (ptime && *ptime > 0) {
config.frame_size_ms = rtc::SafeClamp(10 * (*ptime / 10), 10, 60);
config.frame_size_ms = SafeClamp(10 * (*ptime / 10), 10, 60);
}
}
if (absl::EqualsIgnoreCase(format.name, "L16") && config.IsOk()) {

View File

@ -46,7 +46,7 @@ std::optional<AudioEncoderG711::Config> AudioEncoderG711::SdpToConfig(
if (ptime_iter != format.parameters.end()) {
const auto ptime = StringToNumber<int>(ptime_iter->second);
if (ptime && *ptime > 0) {
config.frame_size_ms = rtc::SafeClamp(10 * (*ptime / 10), 10, 60);
config.frame_size_ms = SafeClamp(10 * (*ptime / 10), 10, 60);
}
}
if (!config.IsOk()) {

View File

@ -46,7 +46,7 @@ std::optional<AudioEncoderG722Config> AudioEncoderG722::SdpToConfig(
auto ptime = StringToNumber<int>(ptime_iter->second);
if (ptime && *ptime > 0) {
const int whole_packets = *ptime / 10;
config.frame_size_ms = rtc::SafeClamp<int>(whole_packets * 10, 10, 60);
config.frame_size_ms = SafeClamp<int>(whole_packets * 10, 10, 60);
}
}
if (!config.IsOk()) {

View File

@ -1058,8 +1058,8 @@ bool ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
RTC_DCHECK_RUN_ON(&worker_thread_checker_);
// Limit to range accepted by both VoE and ACM, so we're at least getting as
// close as possible, instead of failing.
delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
kVoiceEngineMaxMinPlayoutDelayMs);
delay_ms = SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
kVoiceEngineMaxMinPlayoutDelayMs);
if (!neteq_->SetMinimumDelay(delay_ms)) {
RTC_DLOG(LS_ERROR)
<< "SetMinimumPlayoutDelay() failed to set min playout delay "

View File

@ -494,7 +494,7 @@ void BitrateAllocator::OnNetworkEstimateChanged(TargetTransferRate msg) {
int loss_ratio_255 = msg.network_estimate.loss_rate_ratio * 255;
last_fraction_loss_ =
rtc::dchecked_cast<uint8_t>(rtc::SafeClamp(loss_ratio_255, 0, 255));
rtc::dchecked_cast<uint8_t>(SafeClamp(loss_ratio_255, 0, 255));
last_rtt_ = msg.network_estimate.round_trip_time.ms();
last_bwe_period_ms_ = msg.network_estimate.bwe_period.ms();

View File

@ -57,7 +57,7 @@ int64_t ReceiveTimeCalculator::ReconcileReceiveTimes(int64_t packet_time_us,
int64_t safe_time_us) {
int64_t stall_time_us = system_time_us - packet_time_us;
if (total_system_time_passed_us_ < config_.stall_threshold->us()) {
stall_time_us = rtc::SafeMin(stall_time_us, config_.max_stall->us());
stall_time_us = SafeMin(stall_time_us, config_.max_stall->us());
}
int64_t corrected_time_us = safe_time_us - stall_time_us;
@ -107,8 +107,8 @@ int64_t ReceiveTimeCalculator::ReconcileReceiveTimes(int64_t packet_time_us,
if (forward_clock_reset || obvious_backward_clock_reset ||
small_reset_during_stall_) {
corrected_time_us = last_corrected_time_us_ +
rtc::SafeClamp(packet_time_delta_us, 0,
config_.max_packet_time_repair->us());
SafeClamp(packet_time_delta_us, 0,
config_.max_packet_time_repair->us());
}
}

View File

@ -235,8 +235,8 @@ void RtcEventLogImpl::ScheduleOutput() {
};
const int64_t now_ms = rtc::TimeMillis();
const int64_t time_since_output_ms = now_ms - last_output_ms_;
const int32_t delay = rtc::SafeClamp(output_period_ms_ - time_since_output_ms,
0, output_period_ms_);
const int32_t delay =
SafeClamp(output_period_ms_ - time_since_output_ms, 0, output_period_ms_);
task_queue_->PostDelayedTask(std::move(output_task),
TimeDelta::Millis(delay));
}

View File

@ -733,9 +733,9 @@ void AudioEncoderOpusImpl::SetProjectedPacketLossRate(float fraction) {
}
void AudioEncoderOpusImpl::SetTargetBitrate(int bits_per_second) {
const int new_bitrate = rtc::SafeClamp<int>(
bits_per_second, AudioEncoderOpusConfig::kMinBitrateBps,
AudioEncoderOpusConfig::kMaxBitrateBps);
const int new_bitrate =
SafeClamp<int>(bits_per_second, AudioEncoderOpusConfig::kMinBitrateBps,
AudioEncoderOpusConfig::kMaxBitrateBps);
if (config_.bitrate_bps && *config_.bitrate_bps != new_bitrate) {
config_.bitrate_bps = new_bitrate;
RTC_DCHECK(config_.IsOk());

View File

@ -100,7 +100,7 @@ void DelayConstraints::UpdateEffectiveMinimumDelay() {
// Clamp `base_minimum_delay_ms_` into the range which can be effectively
// used.
const int base_minimum_delay_ms =
rtc::SafeClamp(base_minimum_delay_ms_, 0, MinimumDelayUpperBound());
SafeClamp(base_minimum_delay_ms_, 0, MinimumDelayUpperBound());
effective_minimum_delay_ms_ =
std::max(minimum_delay_ms_, base_minimum_delay_ms);
}

View File

@ -211,8 +211,8 @@ int16_t Merge::SignalScaling(const int16_t* input,
size_t input_length,
const int16_t* expanded_signal) const {
// Adjust muting factor if new vector is more or less of the BGN energy.
const auto mod_input_length = rtc::SafeMin<size_t>(
64 * rtc::dchecked_cast<size_t>(fs_mult_), input_length);
const auto mod_input_length =
SafeMin<size_t>(64 * rtc::dchecked_cast<size_t>(fs_mult_), input_length);
const int16_t expanded_max =
WebRtcSpl_MaxAbsValueW16(expanded_signal, mod_input_length);
int32_t factor =

View File

@ -566,7 +566,7 @@ TEST_P(AdaptiveFirFilterMultiChannel, FilterAndAdapt) {
e.begin(),
[&](float a, float b) { return a - b * kScale; });
std::for_each(e.begin(), e.end(),
[](float& a) { a = rtc::SafeClamp(a, -32768.f, 32767.f); });
[](float& a) { a = SafeClamp(a, -32768.f, 32767.f); });
fft.ZeroPaddedFft(e, Aec3Fft::Window::kRectangular, &E);
for (auto& o : output) {
for (size_t k = 0; k < kBlockSize; ++k) {

View File

@ -100,7 +100,7 @@ void RunFilterUpdateTest(int num_blocks_to_process,
e_coarse.begin(),
[&](float a, float b) { return a - b * kScale; });
std::for_each(e_coarse.begin(), e_coarse.end(),
[](float& a) { a = rtc::SafeClamp(a, -32768.f, 32767.f); });
[](float& a) { a = SafeClamp(a, -32768.f, 32767.f); });
fft.ZeroPaddedFft(e_coarse, Aec3Fft::Window::kRectangular, &E_coarse);
std::array<float, kFftLengthBy2Plus1> render_power;

View File

@ -149,7 +149,7 @@ int TransformDbMetricForReporting(bool negate,
if (negate) {
new_value = -new_value;
}
return static_cast<int>(rtc::SafeClamp(new_value, min_value, max_value));
return static_cast<int>(SafeClamp(new_value, min_value, max_value));
}
} // namespace aec3

View File

@ -162,7 +162,7 @@ void RunFilterUpdateTest(const Environment& env,
e_refined.begin(),
[&](float a, float b) { return a - b * kScale; });
std::for_each(e_refined.begin(), e_refined.end(),
[](float& a) { a = rtc::SafeClamp(a, -32768.f, 32767.f); });
[](float& a) { a = SafeClamp(a, -32768.f, 32767.f); });
fft.ZeroPaddedFft(e_refined, Aec3Fft::Window::kRectangular, &E_refined);
for (size_t k = 0; k < kBlockSize; ++k) {
s[k] = kScale * s_scratch[k + kFftLengthBy2];
@ -175,7 +175,7 @@ void RunFilterUpdateTest(const Environment& env,
e_coarse.begin(),
[&](float a, float b) { return a - b * kScale; });
std::for_each(e_coarse.begin(), e_coarse.end(),
[](float& a) { a = rtc::SafeClamp(a, -32768.f, 32767.f); });
[](float& a) { a = SafeClamp(a, -32768.f, 32767.f); });
fft.ZeroPaddedFft(e_coarse, Aec3Fft::Window::kRectangular, &E_coarse);
// Compute spectra for future use.

View File

@ -205,12 +205,12 @@ void SignalDependentErleEstimator::Update(
float correction_factor =
correction_factors_[ch][n_active_sections_[ch][k]]
[band_to_subband_[k]];
erle_[ch][k] = rtc::SafeClamp(average_erle[ch][k] * correction_factor,
min_erle_, max_erle_[band_to_subband_[k]]);
erle_[ch][k] = SafeClamp(average_erle[ch][k] * correction_factor,
min_erle_, max_erle_[band_to_subband_[k]]);
if (use_onset_detection_) {
erle_onset_compensated_[ch][k] = rtc::SafeClamp(
average_erle_onset_compensated[ch][k] * correction_factor,
min_erle_, max_erle_[band_to_subband_[k]]);
erle_onset_compensated_[ch][k] =
SafeClamp(average_erle_onset_compensated[ch][k] * correction_factor,
min_erle_, max_erle_[band_to_subband_[k]]);
}
}
}
@ -306,7 +306,7 @@ void SignalDependentErleEstimator::UpdateCorrectionFactors(
alpha = static_cast<float>(is_erle_updated[subband]) * alpha;
erle_estimators_[ch][idx][subband] +=
alpha * (new_erle[subband] - erle_estimators_[ch][idx][subband]);
erle_estimators_[ch][idx][subband] = rtc::SafeClamp(
erle_estimators_[ch][idx][subband] = SafeClamp(
erle_estimators_[ch][idx][subband], min_erle_, max_erle_[subband]);
}
@ -317,8 +317,8 @@ void SignalDependentErleEstimator::UpdateCorrectionFactors(
alpha = static_cast<float>(is_erle_updated[subband]) * alpha;
erle_ref_[ch][subband] +=
alpha * (new_erle[subband] - erle_ref_[ch][subband]);
erle_ref_[ch][subband] = rtc::SafeClamp(erle_ref_[ch][subband],
min_erle_, max_erle_[subband]);
erle_ref_[ch][subband] =
SafeClamp(erle_ref_[ch][subband], min_erle_, max_erle_[subband]);
}
for (size_t subband = 0; subband < kSubbands; ++subband) {

View File

@ -141,7 +141,7 @@ void SubbandErleEstimator::UpdateBands(
if (!use_min_erle_during_onsets_) {
float alpha =
new_erle[k] < erle_during_onsets_[ch][k] ? 0.3f : 0.15f;
erle_during_onsets_[ch][k] = rtc::SafeClamp(
erle_during_onsets_[ch][k] = SafeClamp(
erle_during_onsets_[ch][k] +
alpha * (new_erle[k] - erle_during_onsets_[ch][k]),
min_erle_, max_erle_[k]);
@ -159,8 +159,7 @@ void SubbandErleEstimator::UpdateBands(
if (new_erle < erle) {
alpha = low_render_energy ? 0.f : 0.1f;
}
erle =
rtc::SafeClamp(erle + alpha * (new_erle - erle), min_erle, max_erle);
erle = SafeClamp(erle + alpha * (new_erle - erle), min_erle, max_erle);
};
for (size_t k = 1; k < kFftLengthBy2; ++k) {

View File

@ -171,7 +171,7 @@ void SuppressionFilter::ApplyGain(
for (int b = 0; b < e->NumBands(); ++b) {
auto e_band = e->View(b, ch);
for (size_t i = 0; i < kFftLengthBy2; ++i) {
e_band[i] = rtc::SafeClamp(e_band[i], -32768.f, 32767.f);
e_band[i] = SafeClamp(e_band[i], -32768.f, 32767.f);
}
}
}

View File

@ -152,7 +152,7 @@ int GetSpeechLevelErrorDb(float speech_level_dbfs, float speech_probability) {
return 0;
}
const float speech_level = rtc::SafeClamp<float>(
const float speech_level = SafeClamp<float>(
speech_level_dbfs, kMinSpeechLevelDbfs, kMaxSpeechLevelDbfs);
return std::round(kOverrideTargetSpeechLevelDbfs - speech_level);
@ -376,7 +376,7 @@ void MonoAgc::UpdateGain(int rms_error_db) {
// Handle as much error as possible with the compressor first.
int raw_compression =
rtc::SafeClamp(rms_error, kMinCompressionGain, max_compression_gain_);
SafeClamp(rms_error, kMinCompressionGain, max_compression_gain_);
// Deemphasize the compression gain error. Move halfway between the current
// target and the newly received target. This serves to soften perceptible
@ -397,8 +397,8 @@ void MonoAgc::UpdateGain(int rms_error_db) {
// raw rather than deemphasized compression here as we would otherwise
// shrink the amount of slack the compressor provides.
const int residual_gain =
rtc::SafeClamp(rms_error - raw_compression, -kMaxResidualGainChange,
kMaxResidualGainChange);
SafeClamp(rms_error - raw_compression, -kMaxResidualGainChange,
kMaxResidualGainChange);
RTC_DLOG(LS_INFO) << "[agc] rms_error=" << rms_error
<< ", target_compression=" << target_compression_
<< ", residual_gain=" << residual_gain;

View File

@ -258,8 +258,8 @@ class SpeechSamplesReader {
// Apply gain and copy samples into `audio_buffer_`.
std::transform(buffer_.begin(), buffer_.end(),
audio_buffer_.channels()[0], [gain](int16_t v) -> float {
return rtc::SafeClamp(static_cast<float>(v) * gain,
kMinSample, kMaxSample);
return SafeClamp(static_cast<float>(v) * gain,
kMinSample, kMaxSample);
});
agc.AnalyzePreProcess(audio_buffer_);
@ -292,8 +292,8 @@ class SpeechSamplesReader {
// Apply gain and copy samples into `audio_buffer_`.
std::transform(buffer_.begin(), buffer_.end(),
audio_buffer_.channels()[0], [gain](int16_t v) -> float {
return rtc::SafeClamp(static_cast<float>(v) * gain,
kMinSample, kMaxSample);
return SafeClamp(static_cast<float>(v) * gain,
kMinSample, kMaxSample);
});
agc.AnalyzePreProcess(audio_buffer_);

View File

@ -96,8 +96,8 @@ float ComputeGainChangeThisFrameDb(float target_gain_db,
if (!gain_increase_allowed) {
target_gain_difference_db = std::min(target_gain_difference_db, 0.0f);
}
return rtc::SafeClamp(target_gain_difference_db, -max_gain_decrease_db,
max_gain_increase_db);
return SafeClamp(target_gain_difference_db, -max_gain_decrease_db,
max_gain_increase_db);
}
} // namespace

View File

@ -151,7 +151,7 @@ class ClippingEventPredictor : public ClippingPredictor {
}
if (PredictClippingEvent(channel)) {
const int new_level =
rtc::SafeClamp(level - default_step, min_mic_level, max_mic_level);
SafeClamp(level - default_step, min_mic_level, max_mic_level);
const int step = level - new_level;
if (step > 0) {
return step;
@ -296,15 +296,15 @@ class ClippingPeakPredictor : public ClippingPredictor {
step = default_step;
} else {
const int estimated_gain_change =
rtc::SafeClamp(-static_cast<int>(std::ceil(estimate_db.value())),
-kClippingPredictorMaxGainChange, 0);
SafeClamp(-static_cast<int>(std::ceil(estimate_db.value())),
-kClippingPredictorMaxGainChange, 0);
step =
std::max(level - ComputeVolumeUpdate(estimated_gain_change, level,
min_mic_level, max_mic_level),
default_step);
}
const int new_level =
rtc::SafeClamp(level - step, min_mic_level, max_mic_level);
SafeClamp(level - step, min_mic_level, max_mic_level);
if (level > new_level) {
return level - new_level;
}

View File

@ -28,7 +28,7 @@ void ClipSignal(DeinterleavedView<float> signal) {
for (size_t k = 0; k < signal.num_channels(); ++k) {
MonoView<float> channel_view = signal[k];
for (auto& sample : channel_view) {
sample = rtc::SafeClamp(sample, kMinFloatS16Value, kMaxFloatS16Value);
sample = SafeClamp(sample, kMinFloatS16Value, kMaxFloatS16Value);
}
}
}

View File

@ -116,8 +116,8 @@ int GetSpeechLevelRmsErrorDb(float speech_level_dbfs,
constexpr float kMaxSpeechLevelDbfs = 30.0f;
RTC_DCHECK_GE(speech_level_dbfs, kMinSpeechLevelDbfs);
RTC_DCHECK_LE(speech_level_dbfs, kMaxSpeechLevelDbfs);
speech_level_dbfs = rtc::SafeClamp<float>(
speech_level_dbfs, kMinSpeechLevelDbfs, kMaxSpeechLevelDbfs);
speech_level_dbfs = SafeClamp<float>(speech_level_dbfs, kMinSpeechLevelDbfs,
kMaxSpeechLevelDbfs);
int rms_error_db = 0;
if (speech_level_dbfs > target_range_max_dbfs) {
@ -343,7 +343,7 @@ void MonoInputVolumeController::UpdateInputVolume(int rms_error_db) {
// Prevent too large microphone input volume changes by clamping the RMS
// error.
rms_error_db =
rtc::SafeClamp(rms_error_db, -KMaxAbsRmsErrorDbfs, KMaxAbsRmsErrorDbfs);
SafeClamp(rms_error_db, -KMaxAbsRmsErrorDbfs, KMaxAbsRmsErrorDbfs);
if (rms_error_db == 0) {
return;
}

View File

@ -173,8 +173,8 @@ class SpeechSamplesReader {
// Apply gain and copy samples into `audio_buffer_`.
std::transform(buffer_.begin(), buffer_.end(),
audio_buffer_.channels()[0], [gain](int16_t v) -> float {
return rtc::SafeClamp(static_cast<float>(v) * gain,
kMinSample, kMaxSample);
return SafeClamp(static_cast<float>(v) * gain,
kMinSample, kMaxSample);
});
controller.AnalyzeInputAudio(applied_input_volume, audio_buffer_);
const auto recommended_input_volume = controller.RecommendInputVolume(

View File

@ -79,8 +79,8 @@ void ScaleSamples(MonoView<const float> per_sample_scaling_factors,
for (size_t i = 0; i < signal.num_channels(); ++i) {
MonoView<float> channel = signal[i];
for (int j = 0; j < samples_per_channel; ++j) {
channel[j] = rtc::SafeClamp(channel[j] * per_sample_scaling_factors[j],
kMinFloatS16Value, kMaxFloatS16Value);
channel[j] = SafeClamp(channel[j] * per_sample_scaling_factors[j],
kMinFloatS16Value, kMaxFloatS16Value);
}
}
}

View File

@ -88,7 +88,7 @@ void UpdateSaturationProtectorState(float peak_dbfs,
}
state.headroom_db =
rtc::SafeClamp<float>(state.headroom_db, kMinMarginDb, kMaxMarginDb);
SafeClamp<float>(state.headroom_db, kMinMarginDb, kMaxMarginDb);
}
// Saturation protector which recommends a headroom based on the recent peaks.

View File

@ -20,7 +20,7 @@ namespace webrtc {
namespace {
float ClampLevelEstimateDbfs(float level_estimate_dbfs) {
return rtc::SafeClamp<float>(level_estimate_dbfs, -90.0f, 30.0f);
return SafeClamp<float>(level_estimate_dbfs, -90.0f, 30.0f);
}
// Returns the initial speech level estimate needed to apply the initial gain.

View File

@ -670,13 +670,13 @@ void ApmTest::ProcessDelayVerificationTest(int delay_ms,
// Calculate expected delay estimate and acceptable regions. Further,
// limit them w.r.t. AEC delay estimation support.
const size_t samples_per_ms =
rtc::SafeMin<size_t>(16u, frame_.samples_per_channel() / 10);
SafeMin<size_t>(16u, frame_.samples_per_channel() / 10);
const int expected_median =
rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
const int expected_median_high = rtc::SafeClamp<int>(
SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
const int expected_median_high = SafeClamp<int>(
expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
delay_max);
const int expected_median_low = rtc::SafeClamp<int>(
const int expected_median_low = SafeClamp<int>(
expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
delay_max);
// Verify delay metrics.

View File

@ -84,7 +84,7 @@ void AudioSamplesScaler::Process(AudioBuffer& audio_buffer) {
for (float& sample : channel_view) {
constexpr float kMinFloatS16Value = -32768.f;
constexpr float kMaxFloatS16Value = 32767.f;
sample = rtc::SafeClamp(sample, kMinFloatS16Value, kMaxFloatS16Value);
sample = SafeClamp(sample, kMinFloatS16Value, kMaxFloatS16Value);
}
}
}

View File

@ -80,7 +80,7 @@ void CaptureLevelsAdjuster::SetAnalogMicGainLevel(int level) {
RTC_DCHECK_GE(level, kMinAnalogMicGainLevel);
RTC_DCHECK_LE(level, kMaxAnalogMicGainLevel);
int clamped_level =
rtc::SafeClamp(level, kMinAnalogMicGainLevel, kMaxAnalogMicGainLevel);
SafeClamp(level, kMinAnalogMicGainLevel, kMaxAnalogMicGainLevel);
emulated_analog_mic_gain_level_ = clamped_level;
UpdatePreAdjustmentGain();

View File

@ -87,8 +87,8 @@ class FakeRecordingDeviceLinear final : public FakeRecordingDeviceWorker {
for (size_t c = 0; c < buffer->num_channels(); ++c) {
for (size_t i = 0; i < buffer->num_frames(); ++i) {
buffer->channels()[c][i] =
rtc::SafeClamp(buffer->channels()[c][i] * mic_level_ / divisor,
kFloatSampleMin, kFloatSampleMax);
SafeClamp(buffer->channels()[c][i] * mic_level_ / divisor,
kFloatSampleMin, kFloatSampleMax);
}
}
}
@ -125,8 +125,8 @@ class FakeRecordingDeviceAgc final : public FakeRecordingDeviceWorker {
for (size_t c = 0; c < buffer->num_channels(); ++c) {
for (size_t i = 0; i < buffer->num_frames(); ++i) {
buffer->channels()[c][i] =
rtc::SafeClamp(buffer->channels()[c][i] * scaling_factor,
kFloatSampleMin, kFloatSampleMax);
SafeClamp(buffer->channels()[c][i] * scaling_factor,
kFloatSampleMin, kFloatSampleMax);
}
}
}

View File

@ -325,7 +325,7 @@ void TrendlineEstimator::UpdateThreshold(double modified_trend,
const int64_t kMaxTimeDeltaMs = 100;
int64_t time_delta_ms = std::min(now_ms - last_update_ms_, kMaxTimeDeltaMs);
threshold_ += k * (fabs(modified_trend) - threshold_) * time_delta_ms;
threshold_ = rtc::SafeClamp(threshold_, 6.f, 600.f);
threshold_ = SafeClamp(threshold_, 6.f, 600.f);
last_update_ms_ = now_ms;
}

View File

@ -93,7 +93,7 @@ void OveruseDetector::UpdateThreshold(double modified_offset, int64_t now_ms) {
const int64_t kMaxTimeDeltaMs = 100;
int64_t time_delta_ms = std::min(now_ms - last_update_ms_, kMaxTimeDeltaMs);
threshold_ += k * (fabs(modified_offset) - threshold_) * time_delta_ms;
threshold_ = rtc::SafeClamp(threshold_, 6.f, 600.f);
threshold_ = SafeClamp(threshold_, 6.f, 600.f);
last_update_ms_ = now_ms;
}

View File

@ -420,15 +420,15 @@ std::vector<std::unique_ptr<RtpPacketToSend>> RTPSender::GeneratePadding(
max_packet_size_ - max_padding_fec_packet_header_;
if (audio_configured_) {
// Allow smaller padding packets for audio.
padding_bytes_in_packet = rtc::SafeClamp<size_t>(
bytes_left, kMinAudioPaddingLength,
rtc::SafeMin(max_payload_size, kMaxPaddingLength));
padding_bytes_in_packet =
SafeClamp<size_t>(bytes_left, kMinAudioPaddingLength,
SafeMin(max_payload_size, kMaxPaddingLength));
} else {
// Always send full padding packets. This is accounted for by the
// RtpPacketSender, which will make sure we don't send too much padding even
// if a single packet is larger than requested.
// We do this to avoid frequently sending small packets on higher bitrates.
padding_bytes_in_packet = rtc::SafeMin(max_payload_size, kMaxPaddingLength);
padding_bytes_in_packet = SafeMin(max_payload_size, kMaxPaddingLength);
}
while (bytes_left > 0) {

View File

@ -983,7 +983,7 @@ void Connection::UpdateState(int64_t now) {
return;
// Computes our estimate of the RTT given the current estimate.
int rtt = rtc::SafeClamp(2 * rtt_, MINIMUM_RTT, MAXIMUM_RTT);
int rtt = webrtc::SafeClamp(2 * rtt_, MINIMUM_RTT, MAXIMUM_RTT);
if (RTC_LOG_CHECK_LEVEL(LS_VERBOSE)) {
std::string pings;

View File

@ -713,8 +713,8 @@ bool PseudoTcp::process(Segment& seg) {
m_rx_rttvar = (3 * m_rx_rttvar + abs_err) / 4;
m_rx_srtt = (7 * m_rx_srtt + rtt) / 8;
}
m_rx_rto = rtc::SafeClamp(m_rx_srtt + rtc::SafeMax(1, 4 * m_rx_rttvar),
MIN_RTO, MAX_RTO);
m_rx_rto = webrtc::SafeClamp(
m_rx_srtt + webrtc::SafeMax(1, 4 * m_rx_rttvar), MIN_RTO, MAX_RTO);
#if _DEBUGMSG >= _DBG_VERBOSE
RTC_LOG(LS_INFO) << "rtt: " << rtt << " srtt: " << m_rx_srtt
<< " rto: " << m_rx_rto;

View File

@ -29,10 +29,9 @@ void JitterBufferDelay::Set(std::optional<double> delay_seconds) {
int JitterBufferDelay::GetMs() const {
RTC_DCHECK_RUN_ON(&worker_thread_checker_);
return rtc::SafeClamp(
rtc::saturated_cast<int>(cached_delay_seconds_.value_or(kDefaultDelay) *
1000),
0, kMaximumDelayMs);
return SafeClamp(rtc::saturated_cast<int>(
cached_delay_seconds_.value_or(kDefaultDelay) * 1000),
0, kMaximumDelayMs);
}
} // namespace webrtc

View File

@ -84,7 +84,7 @@
#include "rtc_base/numerics/safe_compare.h"
#include "rtc_base/type_traits.h"
namespace rtc {
namespace webrtc {
namespace safe_minmax_impl {
@ -331,6 +331,14 @@ R2 SafeClamp(T x, L min, H max) {
: static_cast<R2>(x);
}
} // namespace webrtc
// Re-export symbols from the webrtc namespace for backwards compatibility.
// TODO(bugs.webrtc.org/4222596): Remove once all references are updated.
namespace rtc {
using ::webrtc::SafeClamp;
using ::webrtc::SafeMax;
using ::webrtc::SafeMin;
} // namespace rtc
#endif // RTC_BASE_NUMERICS_SAFE_MINMAX_H_

View File

@ -17,7 +17,7 @@
#include "test/gtest.h"
namespace rtc {
namespace webrtc {
namespace {
@ -344,4 +344,4 @@ uint32_t TestClampSafe(uint32_t x, uint32_t a, uint32_t b) {
return SafeClamp(x, a, b);
}
} // namespace rtc
} // namespace webrtc

View File

@ -34,8 +34,7 @@ SimpleStringBuilder& SimpleStringBuilder::operator<<(char ch) {
SimpleStringBuilder& SimpleStringBuilder::operator<<(absl::string_view str) {
RTC_DCHECK_LT(size_ + str.length(), buffer_.size())
<< "Buffer size was insufficient";
const size_t chars_added =
rtc::SafeMin(str.length(), buffer_.size() - size_ - 1);
const size_t chars_added = SafeMin(str.length(), buffer_.size() - size_ - 1);
memcpy(&buffer_[size_], str.data(), chars_added);
size_ += chars_added;
buffer_[size_] = '\0';
@ -97,7 +96,7 @@ SimpleStringBuilder& SimpleStringBuilder::AppendFormat(const char* fmt, ...) {
const int len =
std::vsnprintf(&buffer_[size_], buffer_.size() - size_, fmt, args);
if (len >= 0) {
const size_t chars_added = rtc::SafeMin(len, buffer_.size() - 1 - size_);
const size_t chars_added = SafeMin(len, buffer_.size() - 1 - size_);
size_ += chars_added;
RTC_DCHECK_EQ(len, chars_added) << "Buffer size was insufficient";
} else {

View File

@ -56,7 +56,7 @@ void RandomWalkCrossTraffic::Process(Timestamp at_time) {
if (at_time - last_update_time_ >= config_.update_interval) {
intensity_ += random_.Gaussian(config_.bias, config_.variance) *
sqrt((at_time - last_update_time_).seconds<double>());
intensity_ = rtc::SafeClamp(intensity_, 0.0, 1.0);
intensity_ = SafeClamp(intensity_, 0.0, 1.0);
last_update_time_ = at_time;
}
pending_size_ += TrafficRate() * delta;

View File

@ -137,7 +137,7 @@ double GetFilteredElement(int width,
}
// Take the rounding errors into consideration.
return rtc::SafeClamp(element_sum / total_weight, 0.0, 255.0);
return SafeClamp(element_sum / total_weight, 0.0, 255.0);
}
std::vector<FilteredSample> GetSampleValuesForFrame(