using ImageMagick; namespace Heimdall.Agent.Services; /// Compares two nearby frames at low resolution to detect temporal pixel changes. internal static class MotionDetectionAnalyzer { private const int Width = 32; private const int Height = 18; private const double PixelDifferenceThreshold = 0.12; private const double ChangedPixelRatioThreshold = 0.02; public static DetectionResult[] Compare(byte[] previousJpeg, byte[] currentJpeg) { using var previous = Decode(previousJpeg); using var current = Decode(currentJpeg); using var previousPixels = previous.GetPixels(); using var currentPixels = current.GetPixels(); var changed = 0; var minX = Width; var minY = Height; var maxX = -1; var maxY = -1; for (var y = 0; y < Height; y++) for (var x = 0; x < Width; x++) { var before = Luminance(previousPixels.GetPixel(x, y).ToColor()!); var after = Luminance(currentPixels.GetPixel(x, y).ToColor()!); if (Math.Abs(after - before) < PixelDifferenceThreshold) continue; changed++; minX = Math.Min(minX, x); minY = Math.Min(minY, y); maxX = Math.Max(maxX, x); maxY = Math.Max(maxY, y); } var ratio = changed / (double)(Width * Height); if (ratio < ChangedPixelRatioThreshold || maxX < minX || maxY < minY) return []; return [ new DetectionResult("motion", (float)Math.Clamp(ratio, 0, 1), minX / (float)Width, minY / (float)Height, (maxX - minX + 1) / (float)Width, (maxY - minY + 1) / (float)Height) ]; } private static MagickImage Decode(byte[] jpeg) { var image = new MagickImage(jpeg); image.Resize(new MagickGeometry(Width, Height) { IgnoreAspectRatio = true }); image.ColorSpace = ColorSpace.RGB; return image; } private static double Luminance(IMagickColor color) => (0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B) / ushort.MaxValue; }