diff --git a/video/corruption_detection/BUILD.gn b/video/corruption_detection/BUILD.gn index 9f9878387c..51fd2162da 100644 --- a/video/corruption_detection/BUILD.gn +++ b/video/corruption_detection/BUILD.gn @@ -103,6 +103,7 @@ rtc_library("halton_frame_sampler") { "../../api/video:video_frame", "../../rtc_base:checks", "../../rtc_base:logging", + "../../rtc_base:safe_minmax", ] } diff --git a/video/corruption_detection/halton_frame_sampler.cc b/video/corruption_detection/halton_frame_sampler.cc index cd88310a10..643bde0132 100644 --- a/video/corruption_detection/halton_frame_sampler.cc +++ b/video/corruption_detection/halton_frame_sampler.cc @@ -20,6 +20,7 @@ #include "api/video/video_frame_buffer.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/numerics/safe_minmax.h" #include "video/corruption_detection/halton_sequence.h" namespace webrtc { @@ -134,7 +135,9 @@ double GetFilteredElement(int width, total_weight += weight; } } - return element_sum / total_weight; + + // Take the rounding errors into consideration. + return rtc::SafeClamp(element_sum / total_weight, 0.0, 255.0); } std::vector GetSampleValuesForFrame( diff --git a/video/corruption_detection/halton_frame_sampler_unittest.cc b/video/corruption_detection/halton_frame_sampler_unittest.cc index 3475c67bf4..45234ab58f 100644 --- a/video/corruption_detection/halton_frame_sampler_unittest.cc +++ b/video/corruption_detection/halton_frame_sampler_unittest.cc @@ -145,6 +145,18 @@ TEST(GaussianFilteringTest, ShouldCrashWhenStdDevIsNegative) { _); } +TEST(GaussianFilteringTest, RoundingErrorsShouldNotHappen) { + // These values should force a rounding error. + constexpr int kWidth = 128; + constexpr int kHeight = 128; + constexpr double kStdDev = 40; + const std::vector data(kWidth * kHeight, 255); + + EXPECT_THAT(GetFilteredElement(kWidth, kHeight, kHeight, data.data(), + kWidth / 2, kHeight / 2, kStdDev), + 255); +} + TEST(HaltonFrameSamplerTest, FrameIsNotSampledWhenTimestampsAreEqual) { HaltonFrameSampler halton_frame_sampler;