Prevent missing corruption header because of floating point errors.

Sometimes the blurred value gets to be a little above 255 because of
floating point errors. This prevents the header from being sent, losing
1 second of information. This can easily be prevented with the changes
in this CL.

Bug: webrtc:358039777
Change-Id: Ibad1c8f41272260e28fe58557c623e52a6af8294
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/376740
Reviewed-by: Björn Terelius <terelius@webrtc.org>
Reviewed-by: Erik Språng <sprang@webrtc.org>
Commit-Queue: Emil Vardar (xWF) <vardar@google.com>
Cr-Commit-Position: refs/heads/main@{#43906}
diff --git a/video/corruption_detection/BUILD.gn b/video/corruption_detection/BUILD.gn
index 9f98783..51fd216 100644
--- a/video/corruption_detection/BUILD.gn
+++ b/video/corruption_detection/BUILD.gn
@@ -103,6 +103,7 @@
     "../../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 cd88310..643bde0 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 @@
       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<FilteredSample> GetSampleValuesForFrame(
diff --git a/video/corruption_detection/halton_frame_sampler_unittest.cc b/video/corruption_detection/halton_frame_sampler_unittest.cc
index 3475c67..45234ab 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, RoundingErrorsShouldNotHappen) {
+  // These values should force a rounding error.
+  constexpr int kWidth = 128;
+  constexpr int kHeight = 128;
+  constexpr double kStdDev = 40;
+  const std::vector<uint8_t> 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;