diff --git a/src/Heimdall.Agent/AnalysisJobConsumer.cs b/src/Heimdall.Agent/AnalysisJobConsumer.cs index e5b331e..14071ab 100644 --- a/src/Heimdall.Agent/AnalysisJobConsumer.cs +++ b/src/Heimdall.Agent/AnalysisJobConsumer.cs @@ -73,6 +73,9 @@ public sealed class AnalysisJobConsumer : IConsumer var result = await _frameAnalyzer.AnalyzeFrameAsync( frameData, ct: context.CancellationToken); + if (result is null) + throw new InvalidOperationException("Inference unavailable, skipped or saturated; no detection result produced"); + stopwatch.Stop(); var detections = result?.Detections; diff --git a/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs b/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs index 4d6f710..76a7c22 100644 --- a/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs +++ b/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs @@ -12,13 +12,13 @@ public sealed class AdaptiveSnapshotInterval public const int ObjectDetectedMs = 200; public const double CpuThrottlePercent = 80.0; - public TimeSpan GetInterval(SceneState state, double? cpuPercent) + public TimeSpan GetInterval(SceneState state, double? cpuPercent, Heimdall.Application.DTOs.DetectionProfileDto? profile = null) { var ms = state switch { - SceneState.ObjectDetected => ObjectDetectedMs, - SceneState.Motion => MotionMs, - _ => IdleMs, + SceneState.ObjectDetected => profile?.ActiveIntervalMs ?? ObjectDetectedMs, + SceneState.Motion => profile?.MotionIntervalMs ?? MotionMs, + _ => profile?.IdleIntervalMs ?? IdleMs, }; if (cpuPercent is >= CpuThrottlePercent) diff --git a/src/Heimdall.Agent/Services/AgentCameraConfig.cs b/src/Heimdall.Agent/Services/AgentCameraConfig.cs index 13dc713..e2fb29b 100644 --- a/src/Heimdall.Agent/Services/AgentCameraConfig.cs +++ b/src/Heimdall.Agent/Services/AgentCameraConfig.cs @@ -10,7 +10,8 @@ public sealed record AgentCameraConfig( string Name, string RtspUrl, string? SubRtspUrl, - bool Enabled) + bool Enabled, + Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null) { /// /// URL used for AI capture: the low-res sub-stream when available, diff --git a/src/Heimdall.Agent/Services/AgentHealthCheck.cs b/src/Heimdall.Agent/Services/AgentHealthCheck.cs index 40163ec..9a8ec8c 100644 --- a/src/Heimdall.Agent/Services/AgentHealthCheck.cs +++ b/src/Heimdall.Agent/Services/AgentHealthCheck.cs @@ -10,11 +10,13 @@ namespace Heimdall.Agent.Services; public sealed class AgentHealthCheck : IHealthCheck { private readonly AgentState _state; + private readonly FrameAnalyzerService? _analyzer; private readonly PipelineDegradationManager _degradationManager; - public AgentHealthCheck(AgentState state, PipelineDegradationManager degradationManager) + public AgentHealthCheck(AgentState state, PipelineDegradationManager degradationManager, FrameAnalyzerService? analyzer = null) { _state = state; + _analyzer = analyzer; _degradationManager = degradationManager; } @@ -34,11 +36,18 @@ public sealed class AgentHealthCheck : IHealthCheck "Agent registered but has no API key configured")); } + if (_analyzer is { ModelAvailable: false }) + return Task.FromResult(HealthCheckResult.Unhealthy("Detection model unavailable; CPU inference cannot run")); var level = _degradationManager.Level; if (level == DegradationLevel.Normal) { return Task.FromResult(HealthCheckResult.Healthy( - "Agent is registered and operational")); + "Agent is registered and operational", data: new Dictionary + { + ["executionProvider"] = _analyzer?.ExecutionProvider ?? "unknown", + ["modelAvailable"] = _analyzer?.ModelAvailable ?? false, + ["rejectedFrames"] = _analyzer?.RejectedFrames ?? 0 + })); } if (level == DegradationLevel.CpuSaturation) diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs index ee275fc..2429ca1 100644 --- a/src/Heimdall.Agent/Services/AgentRegistrationService.cs +++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs @@ -32,6 +32,7 @@ public class AgentRegistrationService : BackgroundService private readonly SystemMetricsProvider _metrics; private readonly InventoryProviders _providers; private readonly GpuDetectorService _gpu; + private readonly FrameAnalyzerService? _analyzer; private readonly Logging.LogBufferService _buffer; private HttpClient? _client; @@ -48,7 +49,7 @@ public class AgentRegistrationService : BackgroundService InventoryProviders providers, GpuDetectorService gpu, Logging.LogBufferService buffer, - ILogger logger) + ILogger logger, FrameAnalyzerService? analyzer = null) { _httpClientFactory = httpClientFactory; _state = state; @@ -58,6 +59,7 @@ public class AgentRegistrationService : BackgroundService _gpu = gpu; _buffer = buffer; _logger = logger; + _analyzer = analyzer; } /// @@ -236,6 +238,9 @@ public class AgentRegistrationService : BackgroundService return new HeartbeatRequest( _state.PublicIp, + HasGpu: false, // The shipped ONNX package executes on CPU; hardware inventory is separate. + CpuCores: _analyzer is { ModelAvailable: false } ? 0 : Environment.ProcessorCount, + MemoryMb: totalMemoryMb, CpuUsagePercent: metrics.CpuUsagePercent, MemoryUsageBytes: metrics.MemoryUsageBytes, DiskUsagePercent: metrics.DiskUsagePercent, @@ -348,6 +353,9 @@ internal sealed record HeartbeatRequest( [property: JsonPropertyName("diskUsagePercent")] double? DiskUsagePercent = null, [property: JsonPropertyName("uptimeSeconds")] long? UptimeSeconds = null, [property: JsonPropertyName("machineUptimeSeconds")] long? MachineUptimeSeconds = null, + [property: JsonPropertyName("hasGpu")] bool? HasGpu = null, + [property: JsonPropertyName("cpuCores")] int? CpuCores = null, + [property: JsonPropertyName("memoryMb")] long? MemoryMb = null, // CPU inventory [property: JsonPropertyName("cpuVendor")] string? CpuVendor = null, [property: JsonPropertyName("cpuModel")] string? CpuModel = null, diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs index d093e7a..e5a4ec8 100644 --- a/src/Heimdall.Agent/Services/CameraConfigStore.cs +++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs @@ -1,4 +1,6 @@ using System.Collections.Concurrent; +using System.Text.Json; +using Heimdall.Application.DTOs; namespace Heimdall.Agent.Services; @@ -11,7 +13,7 @@ namespace Heimdall.Agent.Services; /// public sealed class CameraConfigStore { - private readonly ConcurrentDictionary _central = new(); + private ConcurrentDictionary _central = new(); private IReadOnlyList _localFallback = []; private volatile bool _centralReceived; @@ -43,6 +45,7 @@ public sealed class CameraConfigStore _ => BuildConfig(cameraId, parts[2], value), (_, existing) => existing with { + DetectionProfile = parts[2] == "profile" ? ParseProfile(value) : existing.DetectionProfile, Name = parts[2] == "name" ? value : existing.Name, RtspUrl = parts[2] == "rtsp" ? value : existing.RtspUrl, SubRtspUrl = parts[2] == "sub_rtsp" ? value : existing.SubRtspUrl, @@ -64,6 +67,17 @@ public sealed class CameraConfigStore RaiseChanged(); } + /// Atomically replace the authoritative snapshot, including removals. + public void ReplaceCentral(IReadOnlyDictionary settings) + { + var replacement = new CameraConfigStore(); + foreach (var setting in settings.Where(s => s.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))) + replacement.ApplyCameraSetting(setting.Key, setting.Value); + Interlocked.Exchange(ref _central, replacement._central); + _centralReceived = true; + RaiseChanged(); + } + /// Effective camera assignments: Central list, or local fallback before that. public IReadOnlyList Cameras => _centralReceived ? _central.Values.ToArray() : _localFallback; @@ -73,7 +87,15 @@ public sealed class CameraConfigStore field == "name" ? value : string.Empty, field == "rtsp" ? value : string.Empty, field == "sub_rtsp" ? value : null, - field == "enabled" ? ParseBool(value) : true); + field == "enabled" ? ParseBool(value) : true, + field == "profile" ? ParseProfile(value) : null); + + private static DetectionProfileDto ParseProfile(string value) + { + var profile = JsonSerializer.Deserialize(value) ?? throw new ArgumentException("Empty detection profile"); + profile.Validate(); + return profile; + } private static bool ParseBool(string value) => bool.TryParse(value, out var parsed) ? parsed : value is "1" or "true" or "True"; diff --git a/src/Heimdall.Agent/Services/CameraStreamService.cs b/src/Heimdall.Agent/Services/CameraStreamService.cs index d018874..ec5d04a 100644 --- a/src/Heimdall.Agent/Services/CameraStreamService.cs +++ b/src/Heimdall.Agent/Services/CameraStreamService.cs @@ -29,6 +29,9 @@ public sealed class CameraStreamService : IDisposable private readonly ConcurrentDictionary _sessions = new(); private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg + private readonly ConcurrentDictionary _profiles = new(); + public void SetDetectionProfile(Guid cameraId, Heimdall.Application.DTOs.DetectionProfileDto profile) => _profiles[cameraId] = profile; + private long _droppedSnapshots; private DateTime _lastDropLogAt; private DateTime _cpuSampleAt; @@ -41,7 +44,7 @@ public sealed class CameraStreamService : IDisposable public Channel SnapshotChannel { get; } = Channel.CreateBounded( new BoundedChannelOptions(MaxQueueSize) { - FullMode = BoundedChannelFullMode.DropOldest, + FullMode = BoundedChannelFullMode.Wait, SingleReader = true, SingleWriter = false, }); @@ -201,7 +204,7 @@ public sealed class CameraStreamService : IDisposable private void MaybeEmitSnapshot(Guid cameraId, StreamSession session, byte[] frame) { var now = DateTime.UtcNow; - var interval = _snapshotInterval.GetInterval(_sceneState.State, GetCpuPercent()); + var interval = _snapshotInterval.GetInterval(_sceneState.State, GetCpuPercent(), _profiles.GetValueOrDefault(cameraId)); // Update snapshot interval metric (spec 13.1) HeimdallMetrics.SetSnapshotInterval(interval); @@ -218,7 +221,7 @@ public sealed class CameraStreamService : IDisposable { _lastDropLogAt = now; _logger.LogWarning( - "Snapshot queue full for camera {CameraId} — oldest frame dropped (total: {Dropped})", + "Snapshot queue full for camera {CameraId} — new frame rejected (total: {Dropped})", cameraId, Interlocked.Read(ref _droppedSnapshots)); } } diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index f3c4e6c..a0e51e7 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -22,6 +22,7 @@ public sealed class ConfigReceiverService : BackgroundService private readonly RuntimeLogLevel _runtimeLogLevel; private readonly CameraConfigStore _cameraStore; private HubConnection? _connection; + private readonly SemaphoreSlim _reloadLock = new(1, 1); /// /// Settings that are known but cannot be applied without an agent restart @@ -82,17 +83,19 @@ public sealed class ConfigReceiverService : BackgroundService _connection.On("DiscoveryScanRequested", () => _scanTrigger.Trigger()); // Listen for setting changes - _connection.On("SettingChanged", (key, value) => + _connection.On("SettingChanged", async (key, value) => { + // Keys may identify secret settings; never log their values. _logger.LogInformation("Config update received: {Key}", key); - ApplySetting(key, value); + if (key == "config.invalidated") await FetchFullConfigAsync(stoppingToken); + else ApplySetting(key, value); }); // Listen for full reload signal - _connection.On("ConfigReload", () => + _connection.On("ConfigReload", async () => { _logger.LogInformation("Full config reload requested, fetching from API..."); - _ = FetchFullConfigAsync(CancellationToken.None); + await FetchFullConfigAsync(stoppingToken); }); // Reconnection events @@ -108,6 +111,7 @@ public sealed class ConfigReceiverService : BackgroundService try { await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken); + await FetchFullConfigAsync(stoppingToken); } catch (Exception ex) { @@ -130,7 +134,11 @@ public sealed class ConfigReceiverService : BackgroundService await FetchFullConfigAsync(stoppingToken); // Keep service alive until cancellation — auto-reconnect handles reconnection - await Task.Delay(Timeout.Infinite, stoppingToken); + while (!stoppingToken.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); + await FetchFullConfigAsync(stoppingToken); + } } catch (OperationCanceledException) { @@ -251,6 +259,7 @@ public sealed class ConfigReceiverService : BackgroundService private async Task FetchFullConfigAsync(CancellationToken ct) { + await _reloadLock.WaitAsync(ct); try { using var http = _httpClientFactory.CreateClient("Central"); @@ -280,8 +289,9 @@ public sealed class ConfigReceiverService : BackgroundService // Apply every key through the same pipeline as live SettingChanged // events — heartbeat interval, log level, credentials, restart-required // documentation, everything. - foreach (var kvp in config) + foreach (var kvp in config.Where(kvp => !kvp.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))) ApplySetting(kvp.Key, kvp.Value); + _cameraStore.ReplaceCentral(config); // The Central camera list is authoritative once the full config // arrives — even if it is empty, drop the local fallback. @@ -291,6 +301,7 @@ public sealed class ConfigReceiverService : BackgroundService { _logger.LogWarning("Failed to fetch full configuration (error type {ErrorType})", ex.GetType().Name); } + finally { _reloadLock.Release(); } } } diff --git a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs index 65e9772..3695d01 100644 --- a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs +++ b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs @@ -29,8 +29,7 @@ public sealed record FrameAnalysisResult( /// Model file expected at: models/yolov8n.onnx (relative to app root) /// or configured via MODEL_PATH environment variable. /// -/// If no model file is found, runs in "passthrough" mode — returns -/// empty detections without crashing. +/// If no compatible model is found, analysis is unavailable (null), never a negative detection. /// /// Integrates with and /// for graceful degradation: @@ -41,11 +40,17 @@ public sealed record FrameAnalysisResult( public sealed class FrameAnalyzerService : IDisposable { private readonly ILogger _logger; + private readonly Func? _testInference; private readonly string _modelPath; private readonly bool _modelLoaded; private readonly InferenceSession? _session; private readonly string _inputName = ""; - private readonly int _numClasses; + private readonly int _numClasses = 80; + private readonly object _inferenceLock = new(); + private long _rejectedFrames; + public long RejectedFrames => Interlocked.Read(ref _rejectedFrames); + public bool ModelAvailable => _modelLoaded; + public string ExecutionProvider => "CPUExecutionProvider"; private readonly CircuitBreaker? _circuitBreaker; private readonly PipelineDegradationManager? _degradationManager; @@ -98,26 +103,36 @@ public sealed class FrameAnalyzerService : IDisposable public FrameAnalyzerService( ILogger logger, CircuitBreaker? circuitBreaker, - PipelineDegradationManager? degradationManager) + PipelineDegradationManager? degradationManager) : this(logger, circuitBreaker, degradationManager, null) { } + + internal FrameAnalyzerService(ILogger logger, CircuitBreaker? circuitBreaker, + PipelineDegradationManager? degradationManager, Func? inference, string? modelPath = null) { + _testInference = inference; _logger = logger; _circuitBreaker = circuitBreaker; _degradationManager = degradationManager; - _modelPath = Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8n.onnx"; - _modelLoaded = File.Exists(_modelPath); + _modelPath = modelPath ?? Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8n.onnx"; + _modelLoaded = inference is not null || File.Exists(_modelPath); - if (_modelLoaded) + if (_modelLoaded && inference is null) { try { - var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions + using var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions { InterOpNumThreads = 1, IntraOpNumThreads = 2, // spec §16: limit CPU threads for agent GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL, }; _session = new InferenceSession(_modelPath, sessionOptions); - _inputName = _session.InputMetadata.Keys.ToArray()[0]; + _inputName = _session.InputMetadata.Keys.Single(); + var input = _session.InputMetadata[_inputName]; + var output = _session.OutputMetadata.Values.Single(); + if (input.ElementType != typeof(float) || !input.Dimensions.SequenceEqual(new[] { 1, 3, InputSize, InputSize }) || + output.ElementType != typeof(float) || output.Dimensions.Length != 3 || output.Dimensions[0] != 1 || + output.Dimensions[1] != 84 || output.Dimensions[2] <= 0) + throw new InvalidOperationException("Expected COCO YOLOv8 float NCHW [1,3,640,640] -> [1,84,N]"); // Determine number of classes from output shape [1, 4+C, 8400] var outputMeta = _session.OutputMetadata.Values.ToArray()[0]; @@ -135,17 +150,15 @@ public sealed class FrameAnalyzerService : IDisposable _modelLoaded = false; } } - else + else if (!_modelLoaded) { - _logger.LogWarning("FrameAnalyzer in passthrough mode — model not found at {ModelPath}", _modelPath); + _logger.LogWarning("FrameAnalyzer unavailable — model not found at {ModelPath}", _modelPath); } _frameQueue = Channel.CreateBounded(new BoundedChannelOptions(MaxQueueSize) { - // DropWrite rejects new writes when full with TryWrite=false, - // allowing the caller to gracefully complete the TCS with null. - // DropOldest would orphan the oldest job's TaskCompletionSource. - FullMode = BoundedChannelFullMode.DropWrite, + // Wait mode makes TryWrite return false on saturation; no accepted job is dropped. + FullMode = BoundedChannelFullMode.Wait, SingleReader = true, SingleWriter = false }); @@ -155,8 +168,8 @@ public sealed class FrameAnalyzerService : IDisposable /// /// Submit a JPEG frame for analysis. Returns a task that completes when - /// analysis is done. If the queue is full, drops the oldest frame. - /// Returns empty detections if model not loaded (passthrough mode). + /// analysis is done. If the queue is full, explicitly rejects the new frame. + /// Returns null when inference is unavailable. /// Respects circuit breaker and degradation level. /// /// Raw JPEG frame bytes. @@ -186,15 +199,16 @@ public sealed class FrameAnalyzerService : IDisposable return null; } - if (!_modelLoaded) + if (!_modelLoaded || _disposed) return null; - var tcs = new TaskCompletionSource(); + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var job = new FrameJob(jpegData, tcs, minConfidence); - // If queue is full (DropWrite rejected our write), complete TCS with fallback + // Wait mode rejects TryWrite when full; every accepted job is completed by the reader. if (!_frameQueue.Writer.TryWrite(job)) { + Interlocked.Increment(ref _rejectedFrames); tcs.TrySetResult(null); return null; } @@ -211,33 +225,7 @@ public sealed class FrameAnalyzerService : IDisposable byte[] jpegData, float minConfidence = DefaultMinConfidence) { - Interlocked.Increment(ref _analyzedFrameCount); - if (!_modelLoaded) return null; - - // Circuit breaker: skip if open - if (_circuitBreaker is not null && !_circuitBreaker.ShouldAllowCall()) - { - Interlocked.Increment(ref _skippedByCircuitBreaker); - return null; - } - - // Degradation: skip if level >= ExecutorDown - if (_degradationManager is not null && !_degradationManager.ShouldUseInference()) - { - Interlocked.Increment(ref _skippedByDegradation); - return null; - } - - var sw = Stopwatch.StartNew(); - var detections = RunInference(jpegData, minConfidence); - sw.Stop(); - - ReportInferenceResult(sw.ElapsedMilliseconds); - - return new FrameAnalysisResult( - Convert.ToBase64String(jpegData), - detections, - sw.ElapsedMilliseconds); + return AnalyzeFrameAsync(jpegData, minConfidence).GetAwaiter().GetResult(); } private async Task ProcessingLoopAsync(CancellationToken ct) @@ -299,10 +287,15 @@ public sealed class FrameAnalyzerService : IDisposable /// Minimum confidence threshold (default 0.4 per spec §16). internal DetectionResult[] RunInference(byte[] jpegData, float minConfidence = DefaultMinConfidence) { + if (_testInference is not null) return _testInference(jpegData, minConfidence); if (_session is null) return []; + lock (_inferenceLock) + { using var image = new MagickImage(jpegData); + var originalWidth = (int)image.Width; + var originalHeight = (int)image.Height; image.Format = MagickFormat.Jpeg; // Resize to model input size (640×640), ignoring aspect ratio (like ImageSharp Resize(640,640)) @@ -315,22 +308,25 @@ public sealed class FrameAnalyzerService : IDisposable NamedOnnxValue.CreateFromTensor(_inputName, inputTensor) }; - using var results = _session.Run(inputs); + using var runOptions = new RunOptions(); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + using var timeoutRegistration = timeout.Token.Register(() => runOptions.Terminate = true); + using var results = _session.Run(inputs, _session.OutputNames, runOptions); var output = results[0].AsTensor().ToArray(); - return ParseYoloOutput(output, (int)image.Width, (int)image.Height, minConfidence); + return ParseYoloOutput(output, originalWidth, originalHeight, minConfidence); + } } /// /// Convert Magick.NET image to a normalized NCHW tensor [1, 3, 640, 640]. /// YOLOv8 expects RGB channels, each normalized to [0, 1]. /// - private static DenseTensor PreprocessImage(MagickImage image) + internal static DenseTensor PreprocessImage(MagickImage image) { var tensor = new DenseTensor([1, 3, InputSize, InputSize]); - // GetPixels().ToArray() returns contiguous interleaved RGB channel values - // (Q16 build => ushort ranging 0..65535), row-major. - var rgb = image.GetPixels()?.ToArray() ?? []; + // Explicit RGB mapping handles grayscale, CMYK and alpha; byte export normalizes Q16 to 8 bits. + var rgb = image.GetPixels().ToByteArray(PixelMapping.RGB) ?? throw new InvalidOperationException("RGB conversion failed"); var idx = 0; for (var y = 0; y < InputSize; y++) @@ -338,7 +334,7 @@ public sealed class FrameAnalyzerService : IDisposable for (var x = 0; x < InputSize; x++) { for (var c = 0; c < 3; c++) - tensor[0, c, y, x] = rgb[idx++] / 65535f; + tensor[0, c, y, x] = rgb[idx++] / 255f; } } @@ -473,23 +469,22 @@ public sealed class FrameAnalyzerService : IDisposable float X1, float Y1, float X2, float Y2, float Score, int ClassIdx); - private bool _disposed; + private volatile bool _disposed; + private readonly object _disposeLock = new(); public void Dispose() { + lock (_disposeLock) + { if (_disposed) return; _disposed = true; - _cts.Cancel(); - _cts.Dispose(); _frameQueue.Writer.TryComplete(); - _session?.Dispose(); - - // Log unobserved exceptions from the processing loop - _processingLoop.ContinueWith(t => - { - if (t.IsFaulted) - _logger.LogCritical(t.Exception, "FrameAnalyzer processing loop crashed"); - }, TaskContinuationOptions.OnlyOnFaulted); + // Drain accepted work before releasing the native session. + _processingLoop.GetAwaiter().GetResult(); + lock (_inferenceLock) + _session?.Dispose(); + _cts.Dispose(); + } } private sealed record FrameJob(byte[] ImageData, TaskCompletionSource Tcs, float MinConfidence); diff --git a/src/Heimdall.Agent/Services/FrameMotionDetector.cs b/src/Heimdall.Agent/Services/FrameMotionDetector.cs index 61bc72a..fedb692 100644 --- a/src/Heimdall.Agent/Services/FrameMotionDetector.cs +++ b/src/Heimdall.Agent/Services/FrameMotionDetector.cs @@ -1,39 +1,45 @@ +using Heimdall.Application.DTOs; +using ImageMagick; + namespace Heimdall.Agent.Services; -/// -/// Lightweight frame-level motion proxy: compares the compressed size of -/// consecutive JPEG frames — a large relative change usually means scene -/// activity. Deliberately cheap (no JPEG decoding) and clearly documented as -/// a placeholder for the real pixel-diff Motion Gate of Phase 16 -/// (MASTER_SPECIFICATION). One instance per camera. -/// +/// Per-camera pixel difference on a fixed RGB grid; JPEG encoding size is irrelevant. public sealed class FrameMotionDetector { private readonly double _thresholdPercent; - private long _lastFrameLength; + private byte[]? _previous; + private DetectionProfileDto? _profile; - public FrameMotionDetector(double thresholdPercent = 8.0) - { - _thresholdPercent = thresholdPercent; - } + public FrameMotionDetector(double thresholdPercent = 8.0) => _thresholdPercent = thresholdPercent; - /// - /// Feeds the next frame and reports whether the scene changed enough to - /// count as motion. The first frame is always a baseline (no motion). - /// - public bool Detect(byte[] jpegFrame) + public bool Detect(byte[] jpegFrame) => Detect(jpegFrame, + new DetectionProfileDto { MotionThreshold = _thresholdPercent / 100 }); + + public bool Detect(byte[] jpegFrame, DetectionProfileDto profile) { - var length = jpegFrame.Length; - if (_lastFrameLength == 0) + 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) { - _lastFrameLength = length; + _profile = profile; return false; } - - var change = Math.Abs(length - _lastFrameLength) / (double)_lastFrameLength * 100.0; - _lastFrameLength = length; - return change >= _thresholdPercent; + 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() => _lastFrameLength = 0; + public void Reset() { _previous = null; _profile = null; } } diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs index eb95efb..4501653 100644 --- a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs +++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs @@ -1,3 +1,4 @@ +using Heimdall.Application.DTOs; using System.Collections.Concurrent; using Heimdall.Application.Metrics; using Microsoft.Extensions.Options; @@ -51,6 +52,8 @@ public sealed class SnapshotPipelineService : BackgroundService private readonly IRemoteFrameBroker? _broker; private readonly FrameResizer? _resizer; private readonly ILogger _logger; + private readonly SemaphoreSlim _syncLock = new(1, 1); + private readonly Dictionary _streamUrls = new(); private readonly ConcurrentDictionary _motionDetectors = new(); private readonly ConcurrentDictionary _reportedSceneState = new(); @@ -60,6 +63,7 @@ public sealed class SnapshotPipelineService : BackgroundService private long _remoteSubmissions; private long _remoteFallbacks; private bool _storeSubscribed; + private int _configDirty; private DateTime _lastCpuCheckAt = DateTime.MinValue; private static readonly TimeSpan CpuCheckInterval = TimeSpan.FromSeconds(10); @@ -139,8 +143,9 @@ public sealed class SnapshotPipelineService : BackgroundService // (e.g. camera settings applied before we subscribed). while (!stoppingToken.IsCancellationRequested) { - await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); - await SyncStreamsAsync(stoppingToken); + await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken); + if (Interlocked.Exchange(ref _configDirty, 0) != 0 || DateTime.UtcNow.Second % 30 == 0) + await SyncStreamsAsync(stoppingToken); } } finally @@ -158,36 +163,39 @@ public sealed class SnapshotPipelineService : BackgroundService public override async Task StopAsync(CancellationToken cancellationToken) { - await _streams.StopAllAsync(); await base.StopAsync(cancellationToken); + await _streams.StopAllAsync(); } private void OnCameraConfigChanged(object? sender, EventArgs e) { - // Fire-and-forget resync; SyncStreamsAsync is idempotent and cheap. - _ = Task.Run(() => SyncStreamsAsync(CancellationToken.None)); + Interlocked.Exchange(ref _configDirty, 1); } private async Task SyncStreamsAsync(CancellationToken ct) { + await _syncLock.WaitAsync(ct); + try + { var desired = _cameraStore.Cameras .Where(c => c.Enabled && !string.IsNullOrWhiteSpace(c.EffectiveRtspUrl)) .ToList(); // Stop streams for cameras no longer assigned/disabled. var toStop = _streams.ActiveCameraIds - .Where(activeId => !desired.Any(c => c.CameraId == activeId)) + .Where(activeId => !desired.Any(c => c.CameraId == activeId && (!_streamUrls.TryGetValue(activeId, out var url) || url == c.EffectiveRtspUrl))) .ToList(); foreach (var activeId in toStop) { await _streams.StopStreamAsync(activeId); - // Camera removed/disabled → Disabled status at the Central. - await _statusReporter.ReportAsync(activeId, "Disabled", ct); + _streamUrls.Remove(activeId); + _motionDetectors.TryRemove(activeId, out _); } // Start streams for newly assigned cameras. foreach (var camera in desired) { + _streams.SetDetectionProfile(camera.CameraId, camera.DetectionProfile ?? new DetectionProfileDto()); if (_streams.IsStreamActive(camera.CameraId)) { // Capture already running → Online. @@ -198,6 +206,7 @@ public sealed class SnapshotPipelineService : BackgroundService var started = await _streams.StartStreamAsync(camera.CameraId, camera.EffectiveRtspUrl, ct); if (started) { + _streamUrls[camera.CameraId] = camera.EffectiveRtspUrl; _logger.LogInformation("Capture started for camera {CameraId} ({Name})", camera.CameraId, camera.Name); await _statusReporter.ReportAsync(camera.CameraId, "Online", ct); } @@ -210,6 +219,8 @@ public sealed class SnapshotPipelineService : BackgroundService await _statusReporter.ReportAsync(camera.CameraId, "Error", ct); } } + } + finally { _syncLock.Release(); } } /// @@ -257,7 +268,24 @@ public sealed class SnapshotPipelineService : BackgroundService // Motion detection runs in both modes — it gates remote submission. var detector = _motionDetectors.GetOrAdd(snapshot.CameraId, _ => new FrameMotionDetector()); - var motion = detector.Detect(snapshot.JpegData); + var camera = _cameraStore.Cameras.FirstOrDefault(c => c.CameraId == snapshot.CameraId); + if (camera is null || !camera.Enabled) continue; + var profile = camera.DetectionProfile ?? new DetectionProfileDto(); + profile.Validate(); + var motion = detector.Detect(snapshot.JpegData, profile); + if (profile.RequireMotionForAI && !motion) + { + _sceneState.UpdateFromAnalysis(false, false); + await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + continue; + } + if (level >= DegradationLevel.ExecutorDown) + { + _sceneState.UpdateFromAnalysis(false, motion); + Interlocked.Increment(ref _snapshotsSkippedByDegradation); + await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + continue; + } FrameAnalysisResult? result = null; @@ -271,27 +299,20 @@ public sealed class SnapshotPipelineService : BackgroundService { // Local analysis: either Local mode, or Remote mode with broker fallback, // or Remote mode but no motion (still run local for detection coverage). - result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, ct: ct); + result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, profile.MinConfidence, ct: ct); } + if (result is null) + throw new InvalidOperationException("Inference unavailable, skipped or saturated"); + result = result with { Detections = result.Detections.Where(d => d.Confidence >= profile.MinConfidence && profile.AllowsClass(d.ClassIndex)).ToArray() }; Interlocked.Increment(ref _snapshotsProcessed); _sceneState.UpdateFromAnalysis( result?.Detections.Count > 0, motion); - if (level >= DegradationLevel.ExecutorDown) - { - // Motion-only mode: skip IA inference reporting - Interlocked.Increment(ref _snapshotsSkippedByDegradation); - await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); - } - else - { - // Normal or SlowExecutor: report full analysis - await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); - await ReportDetectionsAsync(snapshot.CameraId, result, ct).ConfigureAwait(false); - } + await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + await ReportDetectionsAsync(snapshot.CameraId, result, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { diff --git a/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs b/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs index e8cb596..0afa644 100644 --- a/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs @@ -51,6 +51,10 @@ public class ReportCameraStatusCommandHandler : IRequestHandler>; + string? Model = null, + DetectionProfileDto? DetectionProfile = null) : IRequest>; public class UpdateCameraCommandHandler : IRequestHandler> { @@ -29,6 +31,16 @@ public class UpdateCameraCommandHandler : IRequestHandler.NotFound("Camera not found"); + if (request.DetectionProfile is { } executionProfile) + { + try { executionProfile.Validate(); } + catch (ArgumentException ex) { return ServiceResult.Failure(ex.Message, 400); } + var profile = await _db.CameraDetectionProfiles.FirstOrDefaultAsync(p => p.CameraId == camera.Id, ct) + ?? new CameraDetectionProfile(camera.Id); + profile.ExecutionProfileJson = JsonSerializer.Serialize(executionProfile); + if (camera.DetectionProfile is null) camera.SetDetectionProfile(profile); + } + var oldName = camera.Name; var oldManufacturer = camera.Manufacturer; var oldModel = camera.Model; camera.Update(request.Name, request.Manufacturer, request.Model, request.RtspUrl); diff --git a/src/Heimdall.Application/DTOs/CameraDto.cs b/src/Heimdall.Application/DTOs/CameraDto.cs index 43a6291..46bbc52 100644 --- a/src/Heimdall.Application/DTOs/CameraDto.cs +++ b/src/Heimdall.Application/DTOs/CameraDto.cs @@ -14,7 +14,8 @@ public record UpdateCameraRequest( string? RtspUrl, CameraStatus? Status, string? Manufacturer = null, - string? Model = null); + string? Model = null, + DetectionProfileDto? DetectionProfile = null); /// Camera response including all discovery and stream test metadata. public record CameraResponse( diff --git a/src/Heimdall.Application/DTOs/DetectionProfileDto.cs b/src/Heimdall.Application/DTOs/DetectionProfileDto.cs new file mode 100644 index 0000000..6eafacb --- /dev/null +++ b/src/Heimdall.Application/DTOs/DetectionProfileDto.cs @@ -0,0 +1,43 @@ +namespace Heimdall.Application.DTOs; + +/// Version 1 supports COCO object detection and a normalized pixel motion gate. +public sealed record DetectionProfileDto +{ + public int Version { get; init; } = 1; + public int IdleIntervalMs { get; init; } = 1000; + public int MotionIntervalMs { get; init; } = 500; + public int ActiveIntervalMs { get; init; } = 200; + public float MinConfidence { get; init; } = .4f; + public bool DetectPerson { get; init; } = true; + public bool DetectVehicle { get; init; } = true; + public bool DetectAnimal { get; init; } + public bool DetectPackage { get; init; } + public bool DetectMotion { get; init; } = true; + public bool RequireMotionForAI { get; init; } = true; + public double MotionThreshold { get; init; } = .3; + public double MotionPixelThreshold { get; init; } = .08; + public double ZoneX { get; init; } + public double ZoneY { get; init; } + public double ZoneWidth { get; init; } = 1; + public double ZoneHeight { get; init; } = 1; + public string YoloModel { get; init; } = "yolov8n"; + + public void Validate() + { + if (IdleIntervalMs is < 50 or > 60000 || MotionIntervalMs is < 50 or > 60000 || ActiveIntervalMs is < 50 or > 60000 || Version != 1 || !float.IsFinite(MinConfidence) || MinConfidence is < 0 or > 1 || + !double.IsFinite(MotionThreshold) || MotionThreshold is < 0 or > 1 || + !double.IsFinite(MotionPixelThreshold) || MotionPixelThreshold is <= 0 or > 1 || + !double.IsFinite(ZoneX + ZoneY + ZoneWidth + ZoneHeight) || ZoneX < 0 || ZoneY < 0 || + ZoneWidth <= 0 || ZoneHeight <= 0 || ZoneX + ZoneWidth > 1 || ZoneY + ZoneHeight > 1 || + YoloModel != "yolov8n" || DetectPackage) + throw new ArgumentException("Unsupported or invalid detection profile; only COCO yolov8n is available (package detection requires another model)"); + } + + public bool AllowsClass(int? index) => index switch + { + 0 => DetectPerson, + 1 or 2 or 3 or 5 or 7 => DetectVehicle, + >= 14 and <= 23 => DetectAnimal, + _ => false + }; +} diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs index b7ebf38..283f4d9 100644 --- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs +++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs @@ -1,4 +1,5 @@ using Heimdall.Application.Common; +using System.Text.Json; using Heimdall.Application.DTOs; using Heimdall.Application.Security; using Heimdall.Domain.Enums; @@ -81,6 +82,7 @@ public class GetEffectiveAgentConfigQueryHandler // carries them to the agent without a new API surface. var cameras = await _db.Cameras .AsNoTracking() + .Include(c => c.DetectionProfile) .Where(c => c.AgentId == request.AgentId && !c.IsDeleted) .ToListAsync(ct) .ConfigureAwait(false); @@ -88,6 +90,16 @@ public class GetEffectiveAgentConfigQueryHandler foreach (var camera in cameras) { var prefix = $"camera.{camera.Id}"; + var p = camera.DetectionProfile; + var profile = p is null ? new DetectionProfileDto() : new DetectionProfileDto + { + IdleIntervalMs = p.IdleIntervalMs, MotionIntervalMs = p.MotionIntervalMs, ActiveIntervalMs = p.ActiveIntervalMs, + MinConfidence = (float)p.MinConfidence, DetectPerson = p.DetectPerson, + DetectVehicle = p.DetectVehicle, DetectAnimal = p.DetectAnimal, DetectPackage = p.DetectPackage, + DetectMotion = p.DetectMotion, RequireMotionForAI = p.RequireMotionForAI, + MotionThreshold = p.MotionThreshold, YoloModel = p.YoloModel + }; + config[$"{prefix}.profile"] = p?.ExecutionProfileJson ?? JsonSerializer.Serialize(profile); config[$"{prefix}.name"] = camera.Name; if (!string.IsNullOrWhiteSpace(camera.RtspUrl)) config[$"{prefix}.rtsp"] = camera.RtspUrl; diff --git a/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs b/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs index 9aec226..cadd36c 100644 --- a/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs +++ b/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs @@ -7,6 +7,8 @@ namespace Heimdall.Domain.Entities; public class CameraDetectionProfile { public Guid CameraId { get; private set; } + /// Optional versioned execution contract; null preserves legacy defaults. + public string? ExecutionProfileJson { get; set; } // Object types to detect public bool DetectPerson { get; set; } = true; diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 967ef91..223ca46 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -1,4 +1,5 @@ using Heimdall.Application.Common; +using Heimdall.Application.Services; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data.Interceptors; using Microsoft.AspNetCore.Identity; @@ -11,12 +12,14 @@ namespace Heimdall.Infrastructure.Data; public class AppDbContext : IdentityDbContext, IApplicationDbContext { private readonly AuditInterceptor _auditInterceptor; + private readonly IConfigBroadcastService? _configBroadcast; public AppDbContext( DbContextOptions options, - AuditInterceptor auditInterceptor) : base(options) + AuditInterceptor auditInterceptor, IConfigBroadcastService? configBroadcast = null) : base(options) { _auditInterceptor = auditInterceptor; + _configBroadcast = configBroadcast; } // Domain entities @@ -87,6 +90,23 @@ public class AppDbContext : IdentityDbContext, IApplicat await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct).ConfigureAwait(false); } + public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + ChangeTracker.DetectChanges(); + var invalidate = ChangeTracker.Entries().Any(e => + e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted && + e.Entity is Camera or CameraAssignment or CameraDetectionProfile); + var result = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (invalidate && _configBroadcast is not null) + { + // Payload-free invalidation: each agent refetches its authorized full snapshot. + // Delivery is best effort; reconnect and periodic resync recover a missed notification. + try { await _configBroadcast.NotifyAllAgentsReload(cancellationToken).ConfigureAwait(false); } + catch (Exception ex) when (ex is not OutOfMemoryException) { System.Diagnostics.Trace.TraceError("Config invalidation delivery failed: {0}", ex.GetType().Name); } + } + return result; + } + protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); diff --git a/src/Heimdall.Infrastructure/Migrations/20261020030000_AddDetectionExecutionProfile.cs b/src/Heimdall.Infrastructure/Migrations/20261020030000_AddDetectionExecutionProfile.cs new file mode 100644 index 0000000..2ad3bc6 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261020030000_AddDetectionExecutionProfile.cs @@ -0,0 +1,16 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261020030000_AddDetectionExecutionProfile")] +public sealed class AddDetectionExecutionProfile : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => + migrationBuilder.AddColumn(name: "ExecutionProfileJson", table: "camera_detection_profiles", type: "text", nullable: true); + + protected override void Down(MigrationBuilder migrationBuilder) => + migrationBuilder.DropColumn(name: "ExecutionProfileJson", table: "camera_detection_profiles"); +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 06d9c53..4d649c4 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -900,6 +900,9 @@ namespace Heimdall.Infrastructure.Migrations modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => { + b.Property("ExecutionProfileJson") + .HasColumnType("text"); + b.Property("CameraId") .HasColumnType("uuid"); diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs index 2f9408b..ccf2973 100644 --- a/src/Heimdall.Web/Controllers/CamerasController.cs +++ b/src/Heimdall.Web/Controllers/CamerasController.cs @@ -74,7 +74,7 @@ public class CamerasController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Update(Guid id, [FromBody] UpdateCameraRequest request, CancellationToken ct) { - var command = new UpdateCameraCommand(id, request.Name, request.RtspUrl, request.Status, request.Manufacturer, request.Model); + var command = new UpdateCameraCommand(id, request.Name, request.RtspUrl, request.Status, request.Manufacturer, request.Model, request.DetectionProfile); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) diff --git a/tests/Heimdall.Agent.Tests/DetectionProfileTests.cs b/tests/Heimdall.Agent.Tests/DetectionProfileTests.cs new file mode 100644 index 0000000..47e627b --- /dev/null +++ b/tests/Heimdall.Agent.Tests/DetectionProfileTests.cs @@ -0,0 +1,53 @@ +using System.Text.Json; +using Heimdall.Agent.Services; +using Heimdall.Application.DTOs; + +namespace Heimdall.Agent.Tests; + +public class DetectionProfileTests +{ + [Fact] + public void FullResync_RemovesOldCamera_AndAppliesProfileInOneNotification() + { + var store = new CameraConfigStore(); + var oldId = Guid.NewGuid(); + var newId = Guid.NewGuid(); + store.ApplyCameraSetting($"camera.{oldId}.rtsp", "rtsp://old"); + var changes = 0; + store.Changed += (_, _) => changes++; + store.ReplaceCentral(new Dictionary + { + [$"camera.{newId}.rtsp"] = "rtsp://new", + [$"camera.{newId}.enabled"] = "false", + [$"camera.{newId}.profile"] = JsonSerializer.Serialize(new DetectionProfileDto { MinConfidence = .8f, DetectVehicle = false }) + }); + changes.ShouldBe(1); + var camera = store.Cameras.Single(); + camera.CameraId.ShouldBe(newId); + camera.Enabled.ShouldBeFalse(); + camera.DetectionProfile!.MinConfidence.ShouldBe(.8f); + camera.DetectionProfile.AllowsClass(2).ShouldBeFalse(); + camera.DetectionProfile.AllowsClass(0).ShouldBeTrue(); + store.ReplaceCentral(new Dictionary()); + store.Cameras.ShouldBeEmpty(); + } + + [Fact] + public void InvalidSnapshot_KeepsPreviousConfiguration() + { + var store = new CameraConfigStore(); + var id = Guid.NewGuid(); + store.ApplyCameraSetting($"camera.{id}.rtsp", "rtsp://old"); + Should.Throw(() => store.ReplaceCentral(new Dictionary + { [$"camera.{id}.profile"] = JsonSerializer.Serialize(new DetectionProfileDto { Version = 2 }) })); + store.Cameras.Single().RtspUrl.ShouldBe("rtsp://old"); + } + + [Fact] + public void UnsupportedFeatures_AndInvalidThreshold_AreRejected() + { + Should.Throw(() => new DetectionProfileDto { MinConfidence = float.NaN }.Validate()); + Should.Throw(() => new DetectionProfileDto { DetectPackage = true }.Validate()); + Should.Throw(() => new DetectionProfileDto { ZoneX = .8, ZoneWidth = .5 }.Validate()); + } +} diff --git a/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs b/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs index 7389526..3239f16 100644 --- a/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs @@ -73,6 +73,76 @@ public class FrameAnalyzerServiceTests results.ShouldAllBe(r => r == null); } + [Fact] + public async Task Saturation_RejectsNewWork_AndShutdownDrainsAcceptedJobs() + { + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var service = new FrameAnalyzerService(Substitute.For>(), null, null, + (_, _) => { entered.Set(); release.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); return []; }); + var first = service.AnalyzeFrameAsync([1]); + entered.Wait(TimeSpan.FromSeconds(5)).ShouldBeTrue(); + var queued = Enumerable.Range(0, 16).Select(_ => service.AnalyzeFrameAsync([1])).ToArray(); + (await service.AnalyzeFrameAsync([1]).WaitAsync(TimeSpan.FromSeconds(2))).ShouldBeNull(); + service.RejectedFrames.ShouldBe(1); + var shutdown = Task.Run(service.Dispose); + try { shutdown.IsCompleted.ShouldBeFalse(); } + finally { release.Set(); } + await shutdown.WaitAsync(TimeSpan.FromSeconds(10)); + var results = await Task.WhenAll(queued.Append(first)).WaitAsync(TimeSpan.FromSeconds(5)); + results.ShouldAllBe(r => r != null); + (await service.AnalyzeFrameAsync([1])).ShouldBeNull(); + } + + [Fact] + public void YoloCoordinates_UseOriginalFullHdDimensions() + { + using var service = new FrameAnalyzerService(Substitute.For>()); + var output = new float[84]; + output[0] = 320; output[1] = 320; output[2] = 320; output[3] = 320; output[4] = .9f; + var box = service.ParseYoloOutput(output, 1920, 1080).Single(); + box.X.ShouldBe(480); box.Y.ShouldBe(270); box.Width.ShouldBe(960); box.Height.ShouldBe(540); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Preprocess_NormalizesExplicitRgbChannels(bool grayscale) + { + using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Red, 640, 640); + if (grayscale) image.ColorType = ImageMagick.ColorType.Grayscale; + else image.Alpha(ImageMagick.AlphaOption.On); + var tensor = FrameAnalyzerService.PreprocessImage(image); + tensor.Dimensions.ToArray().ShouldBe(new[] { 1, 3, 640, 640 }); + tensor.ToArray().ShouldAllBe(v => v >= 0 && v <= 1); + if (!grayscale) { tensor[0, 0, 0, 0].ShouldBe(1); tensor[0, 1, 0, 0].ShouldBe(0); } + } + + [Fact] + public async Task RealOnnx_CpuModel_ProcessesFullHdImage() + { + var root = new DirectoryInfo(AppContext.BaseDirectory); + while (root is not null && !File.Exists(Path.Combine(root.FullName, "models/yolov8n.onnx"))) root = root.Parent; + root.ShouldNotBeNull("The repository YOLO fixture must be present"); + using var analyzer = new FrameAnalyzerService(Substitute.For>(), null, null, null, + Path.Combine(root.FullName, "models/yolov8n.onnx")); + analyzer.ModelAvailable.ShouldBeTrue(); + analyzer.ExecutionProvider.ShouldBe("CPUExecutionProvider"); + using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Black, 1920, 1080); + var result = await analyzer.AnalyzeFrameAsync(image.ToByteArray(ImageMagick.MagickFormat.Jpeg)).WaitAsync(TimeSpan.FromSeconds(30)); + result.ShouldNotBeNull(); + result.Detections.ShouldBeEmpty(); + } + + [Fact] + public async Task FaultedInference_CompletesJob_AndNextJobStillRuns() + { + using var analyzer = new FrameAnalyzerService(Substitute.For>(), null, null, + (data, _) => data[0] == 0 ? throw new InvalidOperationException("fixture") : []); + (await analyzer.AnalyzeFrameAsync([0]).WaitAsync(TimeSpan.FromSeconds(5))).ShouldBeNull(); + (await analyzer.AnalyzeFrameAsync([1]).WaitAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull(); + } + // ── NMS unit tests ────────────────────────────────────────────── [Fact] diff --git a/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs b/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs index cb8b675..78ee120 100644 --- a/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs +++ b/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs @@ -46,43 +46,40 @@ public class SceneStateTrackerTests public class FrameMotionDetectorTests { - [Fact] - public void FirstFrame_IsBaseline_NoMotion() + private static byte[] Frame(ImageMagick.IMagickColor color, uint quality = 90) { - var detector = new FrameMotionDetector(); - detector.Detect([1, 2, 3, 4]).ShouldBeFalse(); + using var image = new ImageMagick.MagickImage(color, 64, 64); + image.Quality = quality; + return image.ToByteArray(ImageMagick.MagickFormat.Jpeg); } [Fact] - public void IdenticalFrames_NoMotion() + public void PixelChange_TriggersMotion_AndResetCreatesBaseline() { var detector = new FrameMotionDetector(); - detector.Detect([1, 2, 3, 4]); - detector.Detect([1, 2, 3, 4]).ShouldBeFalse(); - } - - [Fact] - public void MuchLargerFrame_Motion() - { - var detector = new FrameMotionDetector(); - detector.Detect(new byte[100]); - detector.Detect(new byte[200]).ShouldBeTrue(); // +100% size - } - - [Fact] - public void SmallChange_BelowThreshold_NoMotion() - { - var detector = new FrameMotionDetector(thresholdPercent: 20.0); - detector.Detect(new byte[1000]); - detector.Detect(new byte[1100]).ShouldBeFalse(); // +10% < 20% - } - - [Fact] - public void Reset_StartsNewBaseline() - { - var detector = new FrameMotionDetector(); - detector.Detect(new byte[100]); + detector.Detect(Frame(ImageMagick.MagickColors.Black)).ShouldBeFalse(); + detector.Detect(Frame(ImageMagick.MagickColors.White)).ShouldBeTrue(); detector.Reset(); - detector.Detect(new byte[500]).ShouldBeFalse(); // baseline again + detector.Detect(Frame(ImageMagick.MagickColors.Black)).ShouldBeFalse(); + } + + [Fact] + public void EncodingChange_DoesNotTriggerMotion() + { + var detector = new FrameMotionDetector(); + detector.Detect(Frame(ImageMagick.MagickColors.Red, 40)); + detector.Detect(Frame(ImageMagick.MagickColors.Red, 100)).ShouldBeFalse(); + } + + [Fact] + public void Zone_IgnoresChangesOutsideRegion() + { + var detector = new FrameMotionDetector(); + var profile = new Heimdall.Application.DTOs.DetectionProfileDto { ZoneWidth = .5 }; + using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Black, 64, 64); + detector.Detect(image.ToByteArray(ImageMagick.MagickFormat.Png), profile); + using var patch = new ImageMagick.MagickImage(ImageMagick.MagickColors.White, 32, 64); + image.Composite(patch, 32, 0, ImageMagick.CompositeOperator.Over); + detector.Detect(image.ToByteArray(ImageMagick.MagickFormat.Png), profile).ShouldBeFalse(); } } diff --git a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs index 50167b9..82d8051 100644 --- a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs @@ -94,18 +94,27 @@ public class SnapshotPipelineServiceTests [Fact] public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer() { - var (service, _, _, streams, analyzer) = CreatePipeline(); + var (service, _, store, streams, analyzer) = CreatePipeline(); + var id = Guid.NewGuid(); + store.ReplaceCentral(new Dictionary + { + [$"camera.{id}.enabled"] = "true", + [$"camera.{id}.profile"] = System.Text.Json.JsonSerializer.Serialize(new Heimdall.Application.DTOs.DetectionProfileDto { RequireMotionForAI = false }) + }); + using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Black, 64, 64); await service.StartAsync(CancellationToken.None); try { await streams.SnapshotChannel.Writer.WriteAsync( - new Snapshot(Guid.NewGuid(), DateTime.UtcNow, [1, 2, 3])); + new Snapshot(id, DateTime.UtcNow, image.ToByteArray(ImageMagick.MagickFormat.Jpeg))); var deadline = DateTime.UtcNow.AddSeconds(5); - while (service.SnapshotsProcessed == 0 && DateTime.UtcNow < deadline) + while (analyzer.AnalyzedFrameCount == 0 && DateTime.UtcNow < deadline) await Task.Delay(50); // The frame reached the analyzer — real call, not just a counter. - service.SnapshotsProcessed.ShouldBe(1); + // An unavailable model is never counted as a successful negative analysis. + service.SnapshotsProcessed.ShouldBe(0); + service.AnalysisFailures.ShouldBe(1); analyzer.AnalyzedFrameCount.ShouldBe(1); } finally diff --git a/tests/Heimdall.Application.Tests/Cameras/Commands/ReportCameraStatusCommandTests.cs b/tests/Heimdall.Application.Tests/Cameras/Commands/ReportCameraStatusCommandTests.cs index 70c9a36..2bf6e63 100644 --- a/tests/Heimdall.Application.Tests/Cameras/Commands/ReportCameraStatusCommandTests.cs +++ b/tests/Heimdall.Application.Tests/Cameras/Commands/ReportCameraStatusCommandTests.cs @@ -24,7 +24,7 @@ public class ReportCameraStatusCommandTests _db, _monitoring, NullLogger.Instance); } - private (Agent Agent, Camera Camera) Seed(Guid siteId, CameraStatus initialStatus = CameraStatus.Disabled) + private (Agent Agent, Camera Camera) Seed(Guid siteId, CameraStatus initialStatus = CameraStatus.Offline) { var agent = new Agent(siteId, "Agent 1", "host1", "1.0.0"); var camera = new Camera(siteId, "Cam 1", "rtsp://cam/stream");