using Heimdall.Application.DTOs; using ImageMagick; namespace Heimdall.Agent.Services; /// Per-camera pixel difference on a fixed RGB grid; JPEG encoding size is irrelevant. public sealed class FrameMotionDetector { private readonly double _thresholdPercent; private byte[]? _previous; private DetectionProfileDto? _profile; public FrameMotionDetector(double thresholdPercent = 8.0) => _thresholdPercent = thresholdPercent; public bool Detect(byte[] jpegFrame) => Detect(jpegFrame, new DetectionProfileDto { MotionThreshold = _thresholdPercent / 100 }); public bool Detect(byte[] jpegFrame, DetectionProfileDto profile) { profile.Validate(); using var image = new MagickImage(jpegFrame); image.Resize(new MagickGeometry(64, 64) { IgnoreAspectRatio = true }); var pixels = image.GetPixels().ToByteArray(PixelMapping.RGB) ?? throw new InvalidOperationException("RGB conversion failed"); var previous = _previous; _previous = pixels; if (previous is null || profile != _profile) { _profile = profile; return false; } var changed = 0; var total = 0; for (var y = (int)(profile.ZoneY * 64); y < Math.Ceiling((profile.ZoneY + profile.ZoneHeight) * 64); y++) for (var x = (int)(profile.ZoneX * 64); x < Math.Ceiling((profile.ZoneX + profile.ZoneWidth) * 64); x++) { var i = (y * 64 + x) * 3; var delta = (Math.Abs(pixels[i] - previous[i]) + Math.Abs(pixels[i+1] - previous[i+1]) + Math.Abs(pixels[i+2] - previous[i+2])) / (3.0 * 255); if (delta >= profile.MotionPixelThreshold) changed++; total++; } return profile.DetectMotion && changed > 0 && changed / (double)total >= profile.MotionThreshold; } public void Reset() { _previous = null; _profile = null; } }