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 webrtc {
namespace { namespace {
bool Limit(float* value, float min, float max) { 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; clamped = std::isfinite(clamped) ? clamped : min;
bool res = *value == clamped; bool res = *value == clamped;
*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) { 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; bool res = *value == clamped;
*value = clamped; *value = clamped;
return res; return res;
} }
bool Limit(int* value, int min, int max) { 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; bool res = *value == clamped;
*value = clamped; *value = clamped;
return res; return res;

View File

@ -45,7 +45,7 @@ std::optional<AudioEncoderL16::Config> AudioEncoderL16::SdpToConfig(
if (ptime_iter != format.parameters.end()) { if (ptime_iter != format.parameters.end()) {
const auto ptime = StringToNumber<int>(ptime_iter->second); const auto ptime = StringToNumber<int>(ptime_iter->second);
if (ptime && *ptime > 0) { 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()) { 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()) { if (ptime_iter != format.parameters.end()) {
const auto ptime = StringToNumber<int>(ptime_iter->second); const auto ptime = StringToNumber<int>(ptime_iter->second);
if (ptime && *ptime > 0) { 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()) { if (!config.IsOk()) {

View File

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

View File

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

View File

@ -494,7 +494,7 @@ void BitrateAllocator::OnNetworkEstimateChanged(TargetTransferRate msg) {
int loss_ratio_255 = msg.network_estimate.loss_rate_ratio * 255; int loss_ratio_255 = msg.network_estimate.loss_rate_ratio * 255;
last_fraction_loss_ = 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_rtt_ = msg.network_estimate.round_trip_time.ms();
last_bwe_period_ms_ = msg.network_estimate.bwe_period.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 safe_time_us) {
int64_t stall_time_us = system_time_us - packet_time_us; int64_t stall_time_us = system_time_us - packet_time_us;
if (total_system_time_passed_us_ < config_.stall_threshold->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; int64_t corrected_time_us = safe_time_us - stall_time_us;
@ -107,7 +107,7 @@ int64_t ReceiveTimeCalculator::ReconcileReceiveTimes(int64_t packet_time_us,
if (forward_clock_reset || obvious_backward_clock_reset || if (forward_clock_reset || obvious_backward_clock_reset ||
small_reset_during_stall_) { small_reset_during_stall_) {
corrected_time_us = last_corrected_time_us_ + corrected_time_us = last_corrected_time_us_ +
rtc::SafeClamp(packet_time_delta_us, 0, SafeClamp(packet_time_delta_us, 0,
config_.max_packet_time_repair->us()); 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 now_ms = rtc::TimeMillis();
const int64_t time_since_output_ms = now_ms - last_output_ms_; 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, const int32_t delay =
0, output_period_ms_); SafeClamp(output_period_ms_ - time_since_output_ms, 0, output_period_ms_);
task_queue_->PostDelayedTask(std::move(output_task), task_queue_->PostDelayedTask(std::move(output_task),
TimeDelta::Millis(delay)); TimeDelta::Millis(delay));
} }

View File

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

View File

@ -100,7 +100,7 @@ void DelayConstraints::UpdateEffectiveMinimumDelay() {
// Clamp `base_minimum_delay_ms_` into the range which can be effectively // Clamp `base_minimum_delay_ms_` into the range which can be effectively
// used. // used.
const int base_minimum_delay_ms = 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_ = effective_minimum_delay_ms_ =
std::max(minimum_delay_ms_, base_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, size_t input_length,
const int16_t* expanded_signal) const { const int16_t* expanded_signal) const {
// Adjust muting factor if new vector is more or less of the BGN energy. // Adjust muting factor if new vector is more or less of the BGN energy.
const auto mod_input_length = rtc::SafeMin<size_t>( const auto mod_input_length =
64 * rtc::dchecked_cast<size_t>(fs_mult_), input_length); SafeMin<size_t>(64 * rtc::dchecked_cast<size_t>(fs_mult_), input_length);
const int16_t expanded_max = const int16_t expanded_max =
WebRtcSpl_MaxAbsValueW16(expanded_signal, mod_input_length); WebRtcSpl_MaxAbsValueW16(expanded_signal, mod_input_length);
int32_t factor = int32_t factor =

View File

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

View File

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

View File

@ -149,7 +149,7 @@ int TransformDbMetricForReporting(bool negate,
if (negate) { if (negate) {
new_value = -new_value; 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 } // namespace aec3

View File

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

View File

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

View File

@ -141,7 +141,7 @@ void SubbandErleEstimator::UpdateBands(
if (!use_min_erle_during_onsets_) { if (!use_min_erle_during_onsets_) {
float alpha = float alpha =
new_erle[k] < erle_during_onsets_[ch][k] ? 0.3f : 0.15f; 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] + erle_during_onsets_[ch][k] +
alpha * (new_erle[k] - erle_during_onsets_[ch][k]), alpha * (new_erle[k] - erle_during_onsets_[ch][k]),
min_erle_, max_erle_[k]); min_erle_, max_erle_[k]);
@ -159,8 +159,7 @@ void SubbandErleEstimator::UpdateBands(
if (new_erle < erle) { if (new_erle < erle) {
alpha = low_render_energy ? 0.f : 0.1f; alpha = low_render_energy ? 0.f : 0.1f;
} }
erle = erle = SafeClamp(erle + alpha * (new_erle - erle), min_erle, max_erle);
rtc::SafeClamp(erle + alpha * (new_erle - erle), min_erle, max_erle);
}; };
for (size_t k = 1; k < kFftLengthBy2; ++k) { 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) { for (int b = 0; b < e->NumBands(); ++b) {
auto e_band = e->View(b, ch); auto e_band = e->View(b, ch);
for (size_t i = 0; i < kFftLengthBy2; ++i) { 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; return 0;
} }
const float speech_level = rtc::SafeClamp<float>( const float speech_level = SafeClamp<float>(
speech_level_dbfs, kMinSpeechLevelDbfs, kMaxSpeechLevelDbfs); speech_level_dbfs, kMinSpeechLevelDbfs, kMaxSpeechLevelDbfs);
return std::round(kOverrideTargetSpeechLevelDbfs - speech_level); 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. // Handle as much error as possible with the compressor first.
int raw_compression = 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 // Deemphasize the compression gain error. Move halfway between the current
// target and the newly received target. This serves to soften perceptible // target and the newly received target. This serves to soften perceptible
@ -397,7 +397,7 @@ void MonoAgc::UpdateGain(int rms_error_db) {
// raw rather than deemphasized compression here as we would otherwise // raw rather than deemphasized compression here as we would otherwise
// shrink the amount of slack the compressor provides. // shrink the amount of slack the compressor provides.
const int residual_gain = const int residual_gain =
rtc::SafeClamp(rms_error - raw_compression, -kMaxResidualGainChange, SafeClamp(rms_error - raw_compression, -kMaxResidualGainChange,
kMaxResidualGainChange); kMaxResidualGainChange);
RTC_DLOG(LS_INFO) << "[agc] rms_error=" << rms_error RTC_DLOG(LS_INFO) << "[agc] rms_error=" << rms_error
<< ", target_compression=" << target_compression_ << ", target_compression=" << target_compression_

View File

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

View File

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

View File

@ -151,7 +151,7 @@ class ClippingEventPredictor : public ClippingPredictor {
} }
if (PredictClippingEvent(channel)) { if (PredictClippingEvent(channel)) {
const int new_level = 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; const int step = level - new_level;
if (step > 0) { if (step > 0) {
return step; return step;
@ -296,7 +296,7 @@ class ClippingPeakPredictor : public ClippingPredictor {
step = default_step; step = default_step;
} else { } else {
const int estimated_gain_change = const int estimated_gain_change =
rtc::SafeClamp(-static_cast<int>(std::ceil(estimate_db.value())), SafeClamp(-static_cast<int>(std::ceil(estimate_db.value())),
-kClippingPredictorMaxGainChange, 0); -kClippingPredictorMaxGainChange, 0);
step = step =
std::max(level - ComputeVolumeUpdate(estimated_gain_change, level, std::max(level - ComputeVolumeUpdate(estimated_gain_change, level,
@ -304,7 +304,7 @@ class ClippingPeakPredictor : public ClippingPredictor {
default_step); default_step);
} }
const int new_level = 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) { if (level > new_level) {
return 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) { for (size_t k = 0; k < signal.num_channels(); ++k) {
MonoView<float> channel_view = signal[k]; MonoView<float> channel_view = signal[k];
for (auto& sample : channel_view) { 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; constexpr float kMaxSpeechLevelDbfs = 30.0f;
RTC_DCHECK_GE(speech_level_dbfs, kMinSpeechLevelDbfs); RTC_DCHECK_GE(speech_level_dbfs, kMinSpeechLevelDbfs);
RTC_DCHECK_LE(speech_level_dbfs, kMaxSpeechLevelDbfs); RTC_DCHECK_LE(speech_level_dbfs, kMaxSpeechLevelDbfs);
speech_level_dbfs = rtc::SafeClamp<float>( speech_level_dbfs = SafeClamp<float>(speech_level_dbfs, kMinSpeechLevelDbfs,
speech_level_dbfs, kMinSpeechLevelDbfs, kMaxSpeechLevelDbfs); kMaxSpeechLevelDbfs);
int rms_error_db = 0; int rms_error_db = 0;
if (speech_level_dbfs > target_range_max_dbfs) { 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 // Prevent too large microphone input volume changes by clamping the RMS
// error. // error.
rms_error_db = rms_error_db =
rtc::SafeClamp(rms_error_db, -KMaxAbsRmsErrorDbfs, KMaxAbsRmsErrorDbfs); SafeClamp(rms_error_db, -KMaxAbsRmsErrorDbfs, KMaxAbsRmsErrorDbfs);
if (rms_error_db == 0) { if (rms_error_db == 0) {
return; return;
} }

View File

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

View File

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

View File

@ -88,7 +88,7 @@ void UpdateSaturationProtectorState(float peak_dbfs,
} }
state.headroom_db = 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. // Saturation protector which recommends a headroom based on the recent peaks.

View File

@ -20,7 +20,7 @@ namespace webrtc {
namespace { namespace {
float ClampLevelEstimateDbfs(float level_estimate_dbfs) { 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. // 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, // Calculate expected delay estimate and acceptable regions. Further,
// limit them w.r.t. AEC delay estimation support. // limit them w.r.t. AEC delay estimation support.
const size_t samples_per_ms = 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 = const int expected_median =
rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max); SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
const int expected_median_high = rtc::SafeClamp<int>( const int expected_median_high = SafeClamp<int>(
expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min, expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
delay_max); 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, expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
delay_max); delay_max);
// Verify delay metrics. // Verify delay metrics.

View File

@ -84,7 +84,7 @@ void AudioSamplesScaler::Process(AudioBuffer& audio_buffer) {
for (float& sample : channel_view) { for (float& sample : channel_view) {
constexpr float kMinFloatS16Value = -32768.f; constexpr float kMinFloatS16Value = -32768.f;
constexpr float kMaxFloatS16Value = 32767.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_GE(level, kMinAnalogMicGainLevel);
RTC_DCHECK_LE(level, kMaxAnalogMicGainLevel); RTC_DCHECK_LE(level, kMaxAnalogMicGainLevel);
int clamped_level = int clamped_level =
rtc::SafeClamp(level, kMinAnalogMicGainLevel, kMaxAnalogMicGainLevel); SafeClamp(level, kMinAnalogMicGainLevel, kMaxAnalogMicGainLevel);
emulated_analog_mic_gain_level_ = clamped_level; emulated_analog_mic_gain_level_ = clamped_level;
UpdatePreAdjustmentGain(); UpdatePreAdjustmentGain();

View File

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

View File

@ -325,7 +325,7 @@ void TrendlineEstimator::UpdateThreshold(double modified_trend,
const int64_t kMaxTimeDeltaMs = 100; const int64_t kMaxTimeDeltaMs = 100;
int64_t time_delta_ms = std::min(now_ms - last_update_ms_, kMaxTimeDeltaMs); int64_t time_delta_ms = std::min(now_ms - last_update_ms_, kMaxTimeDeltaMs);
threshold_ += k * (fabs(modified_trend) - threshold_) * time_delta_ms; 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; 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; const int64_t kMaxTimeDeltaMs = 100;
int64_t time_delta_ms = std::min(now_ms - last_update_ms_, kMaxTimeDeltaMs); int64_t time_delta_ms = std::min(now_ms - last_update_ms_, kMaxTimeDeltaMs);
threshold_ += k * (fabs(modified_offset) - threshold_) * time_delta_ms; 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; 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_; max_packet_size_ - max_padding_fec_packet_header_;
if (audio_configured_) { if (audio_configured_) {
// Allow smaller padding packets for audio. // Allow smaller padding packets for audio.
padding_bytes_in_packet = rtc::SafeClamp<size_t>( padding_bytes_in_packet =
bytes_left, kMinAudioPaddingLength, SafeClamp<size_t>(bytes_left, kMinAudioPaddingLength,
rtc::SafeMin(max_payload_size, kMaxPaddingLength)); SafeMin(max_payload_size, kMaxPaddingLength));
} else { } else {
// Always send full padding packets. This is accounted for by the // Always send full padding packets. This is accounted for by the
// RtpPacketSender, which will make sure we don't send too much padding even // RtpPacketSender, which will make sure we don't send too much padding even
// if a single packet is larger than requested. // if a single packet is larger than requested.
// We do this to avoid frequently sending small packets on higher bitrates. // 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) { while (bytes_left > 0) {

View File

@ -983,7 +983,7 @@ void Connection::UpdateState(int64_t now) {
return; return;
// Computes our estimate of the RTT given the current estimate. // 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)) { if (RTC_LOG_CHECK_LEVEL(LS_VERBOSE)) {
std::string pings; 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_rttvar = (3 * m_rx_rttvar + abs_err) / 4;
m_rx_srtt = (7 * m_rx_srtt + rtt) / 8; m_rx_srtt = (7 * m_rx_srtt + rtt) / 8;
} }
m_rx_rto = rtc::SafeClamp(m_rx_srtt + rtc::SafeMax(1, 4 * m_rx_rttvar), m_rx_rto = webrtc::SafeClamp(
MIN_RTO, MAX_RTO); m_rx_srtt + webrtc::SafeMax(1, 4 * m_rx_rttvar), MIN_RTO, MAX_RTO);
#if _DEBUGMSG >= _DBG_VERBOSE #if _DEBUGMSG >= _DBG_VERBOSE
RTC_LOG(LS_INFO) << "rtt: " << rtt << " srtt: " << m_rx_srtt RTC_LOG(LS_INFO) << "rtt: " << rtt << " srtt: " << m_rx_srtt
<< " rto: " << m_rx_rto; << " rto: " << m_rx_rto;

View File

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

View File

@ -84,7 +84,7 @@
#include "rtc_base/numerics/safe_compare.h" #include "rtc_base/numerics/safe_compare.h"
#include "rtc_base/type_traits.h" #include "rtc_base/type_traits.h"
namespace rtc { namespace webrtc {
namespace safe_minmax_impl { namespace safe_minmax_impl {
@ -331,6 +331,14 @@ R2 SafeClamp(T x, L min, H max) {
: static_cast<R2>(x); : 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 } // namespace rtc
#endif // RTC_BASE_NUMERICS_SAFE_MINMAX_H_ #endif // RTC_BASE_NUMERICS_SAFE_MINMAX_H_

View File

@ -17,7 +17,7 @@
#include "test/gtest.h" #include "test/gtest.h"
namespace rtc { namespace webrtc {
namespace { namespace {
@ -344,4 +344,4 @@ uint32_t TestClampSafe(uint32_t x, uint32_t a, uint32_t b) {
return SafeClamp(x, a, 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) { SimpleStringBuilder& SimpleStringBuilder::operator<<(absl::string_view str) {
RTC_DCHECK_LT(size_ + str.length(), buffer_.size()) RTC_DCHECK_LT(size_ + str.length(), buffer_.size())
<< "Buffer size was insufficient"; << "Buffer size was insufficient";
const size_t chars_added = const size_t chars_added = SafeMin(str.length(), buffer_.size() - size_ - 1);
rtc::SafeMin(str.length(), buffer_.size() - size_ - 1);
memcpy(&buffer_[size_], str.data(), chars_added); memcpy(&buffer_[size_], str.data(), chars_added);
size_ += chars_added; size_ += chars_added;
buffer_[size_] = '\0'; buffer_[size_] = '\0';
@ -97,7 +96,7 @@ SimpleStringBuilder& SimpleStringBuilder::AppendFormat(const char* fmt, ...) {
const int len = const int len =
std::vsnprintf(&buffer_[size_], buffer_.size() - size_, fmt, args); std::vsnprintf(&buffer_[size_], buffer_.size() - size_, fmt, args);
if (len >= 0) { 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; size_ += chars_added;
RTC_DCHECK_EQ(len, chars_added) << "Buffer size was insufficient"; RTC_DCHECK_EQ(len, chars_added) << "Buffer size was insufficient";
} else { } else {

View File

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

View File

@ -137,7 +137,7 @@ double GetFilteredElement(int width,
} }
// Take the rounding errors into consideration. // 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( std::vector<FilteredSample> GetSampleValuesForFrame(