From 123d76fe0f3d000bb0f6880550e970f2dae63969 Mon Sep 17 00:00:00 2001 From: Macocian Alexandru Victor Date: Thu, 26 Feb 2026 01:26:51 -0800 Subject: [PATCH] Fix stackoverflow risk on ScreenshotService (Closes #1476) (#1481) --- .../Services/Screenshots/ScreenshotService.cs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Daybreak.Core/Services/Screenshots/ScreenshotService.cs b/Daybreak.Core/Services/Screenshots/ScreenshotService.cs index 7a495b54..02f914b8 100644 --- a/Daybreak.Core/Services/Screenshots/ScreenshotService.cs +++ b/Daybreak.Core/Services/Screenshots/ScreenshotService.cs @@ -66,7 +66,7 @@ public sealed class ScreenshotService( { using var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); using var image = Image.Load(fileStream); - + var (dominantColor, isDark) = GetDominantColor(image); var closestAccent = GetClosestAccentColor(dominantColor); var entry = new ScreenshotEntry(path, closestAccent, isDark ? LightDarkMode.Dark : LightDarkMode.Light); @@ -108,13 +108,15 @@ public sealed class ScreenshotService( var sumB = Vector.Zero; int simdPixelCount = 0; + // Gather sampled pixels into arrays for vectorization + Span rValues = stackalloc int[Vector.Count]; + Span gValues = stackalloc int[Vector.Count]; + Span bValues = stackalloc int[Vector.Count]; + // Collect sampled pixels for SIMD processing while (x + (Vector.Count * SampleQuality) <= rowSpan.Length) { - // Gather sampled pixels into arrays for vectorization - Span rValues = stackalloc int[Vector.Count]; - Span gValues = stackalloc int[Vector.Count]; - Span bValues = stackalloc int[Vector.Count]; + for (int i = 0; i < Vector.Count && x < rowSpan.Length; i++, x += SampleQuality) { @@ -146,6 +148,7 @@ public sealed class ScreenshotService( totalG += sumG[i]; totalB += sumB[i]; } + pixelCount += simdPixelCount; } @@ -171,7 +174,7 @@ public sealed class ScreenshotService( var avgB = (byte)(totalB / pixelCount); var color = Color.FromArgb(255, avgR, avgG, avgB); - + // Calculate perceived brightness using standard formula // Values > 128 are generally considered "light" var brightness = (0.299 * avgR) + (0.587 * avgG) + (0.114 * avgB);