[v3,4/6] libcamera: simple: Avoid incorrect arithmetic in AWB
diff mbox series

Message ID 20250919173709.220881-5-mzamazal@redhat.com
State New
Headers show
Series
  • Fix stats related problems in software ISP
Related show

Commit Message

Milan Zamazal Sept. 19, 2025, 5:37 p.m. UTC
The R/G/B sums computed in AWB simple IPA may be zero or perhaps even
negative.  Let's make sure the sums are always positive, to prevent
division by zero or completely nonsense results.

Signed-off-by: Milan Zamazal <mzamazal@redhat.com>
---
 src/ipa/simple/algorithms/awb.cpp | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

Comments

Maciej S. Szmigiero Sept. 21, 2025, 12:48 p.m. UTC | #1
On 19.09.2025 19:37, Milan Zamazal wrote:
> The R/G/B sums computed in AWB simple IPA may be zero or perhaps even
> negative.  Let's make sure the sums are always positive, to prevent
> division by zero or completely nonsense results.
> 
> Signed-off-by: Milan Zamazal <mzamazal@redhat.com>
> ---

Reviewed-by: Maciej S. Szmigiero <mail@maciej.szmigiero.name>

Thanks,
Maciej

Patch
diff mbox series

diff --git a/src/ipa/simple/algorithms/awb.cpp b/src/ipa/simple/algorithms/awb.cpp
index cf567e894..8231a4968 100644
--- a/src/ipa/simple/algorithms/awb.cpp
+++ b/src/ipa/simple/algorithms/awb.cpp
@@ -7,6 +7,7 @@ 
 
 #include "awb.h"
 
+#include <algorithm>
 #include <numeric>
 #include <stdint.h>
 
@@ -68,10 +69,11 @@  void Awb::process(IPAContext &context,
 	 */
 	const uint64_t nPixels = std::accumulate(
 		histogram.begin(), histogram.end(), 0);
-	const uint64_t offset = blackLevel * nPixels;
-	const uint64_t sumR = stats->sumR_ - offset / 4;
-	const uint64_t sumG = stats->sumG_ - offset / 2;
-	const uint64_t sumB = stats->sumB_ - offset / 4;
+	const int64_t offset = blackLevel * nPixels;
+	const int64_t minValid = 1;
+	const uint64_t sumR = std::max(static_cast<int64_t>(stats->sumR_) - offset / 4, minValid);
+	const uint64_t sumG = std::max(static_cast<int64_t>(stats->sumG_) - offset / 2, minValid);
+	const uint64_t sumB = std::max(static_cast<int64_t>(stats->sumB_) - offset / 4, minValid);
 
 	/*
 	 * Calculate red and blue gains for AWB.