fix(pipeline): version detection profiles and resync camera configuration #8

Merged
arnaud.dartois merged 4 commits from audit/pipe-profile into main 2026-10-20 07:33:56 +02:00
26 changed files with 492 additions and 171 deletions

No files matched your search

@@ -73,6 +73,9 @@ public sealed class AnalysisJobConsumer : IConsumer<AnalysisJobRequested>
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;
@@ -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)
@@ -10,7 +10,8 @@ public sealed record AgentCameraConfig(
string Name,
string RtspUrl,
string? SubRtspUrl,
bool Enabled)
bool Enabled,
Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null)
{
/// <summary>
/// URL used for AI capture: the low-res sub-stream when available,
@@ -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<string, object>
{
["executionProvider"] = _analyzer?.ExecutionProvider ?? "unknown",
["modelAvailable"] = _analyzer?.ModelAvailable ?? false,
["rejectedFrames"] = _analyzer?.RejectedFrames ?? 0
}));
}
if (level == DegradationLevel.CpuSaturation)
@@ -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<AgentRegistrationService> logger)
ILogger<AgentRegistrationService> logger, FrameAnalyzerService? analyzer = null)
{
_httpClientFactory = httpClientFactory;
_state = state;
@@ -58,6 +59,7 @@ public class AgentRegistrationService : BackgroundService
_gpu = gpu;
_buffer = buffer;
_logger = logger;
_analyzer = analyzer;
}
/// <summary>
@@ -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,
@@ -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;
/// </summary>
public sealed class CameraConfigStore
{
private readonly ConcurrentDictionary<Guid, AgentCameraConfig> _central = new();
private ConcurrentDictionary<Guid, AgentCameraConfig> _central = new();
private IReadOnlyList<AgentCameraConfig> _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();
}
/// <summary>Atomically replace the authoritative snapshot, including removals.</summary>
public void ReplaceCentral(IReadOnlyDictionary<string, string> 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();
}
/// <summary>Effective camera assignments: Central list, or local fallback before that.</summary>
public IReadOnlyList<AgentCameraConfig> 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<DetectionProfileDto>(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";
@@ -29,6 +29,9 @@ public sealed class CameraStreamService : IDisposable
private readonly ConcurrentDictionary<Guid, StreamSession> _sessions = new();
private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg
private readonly ConcurrentDictionary<Guid, Heimdall.Application.DTOs.DetectionProfileDto> _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<Snapshot> SnapshotChannel { get; } = Channel.CreateBounded<Snapshot>(
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));
}
}
@@ -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);
/// <summary>
/// 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<string, string>("SettingChanged", (key, value) =>
_connection.On<string, string>("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(); }
}
}
@@ -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 <see cref="CircuitBreaker"/> and
/// <see cref="PipelineDegradationManager"/> for graceful degradation:
@@ -41,11 +40,17 @@ public sealed record FrameAnalysisResult(
public sealed class FrameAnalyzerService : IDisposable
{
private readonly ILogger<FrameAnalyzerService> _logger;
private readonly Func<byte[], float, DetectionResult[]>? _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<FrameAnalyzerService> logger,
CircuitBreaker? circuitBreaker,
PipelineDegradationManager? degradationManager)
PipelineDegradationManager? degradationManager) : this(logger, circuitBreaker, degradationManager, null) { }
internal FrameAnalyzerService(ILogger<FrameAnalyzerService> logger, CircuitBreaker? circuitBreaker,
PipelineDegradationManager? degradationManager, Func<byte[], float, DetectionResult[]>? 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<FrameJob>(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
/// <summary>
/// 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.
/// </summary>
/// <param name="jpegData">Raw JPEG frame bytes.</param>
@@ -186,15 +199,16 @@ public sealed class FrameAnalyzerService : IDisposable
return null;
}
if (!_modelLoaded)
if (!_modelLoaded || _disposed)
return null;
var tcs = new TaskCompletionSource<FrameAnalysisResult?>();
var tcs = new TaskCompletionSource<FrameAnalysisResult?>(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
/// <param name="minConfidence">Minimum confidence threshold (default 0.4 per spec §16).</param>
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<float>().ToArray();
return ParseYoloOutput(output, (int)image.Width, (int)image.Height, minConfidence);
return ParseYoloOutput(output, originalWidth, originalHeight, minConfidence);
}
}
/// <summary>
/// Convert Magick.NET image to a normalized NCHW tensor [1, 3, 640, 640].
/// YOLOv8 expects RGB channels, each normalized to [0, 1].
/// </summary>
private static DenseTensor<float> PreprocessImage(MagickImage image)
internal static DenseTensor<float> PreprocessImage(MagickImage image)
{
var tensor = new DenseTensor<float>([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<FrameAnalysisResult?> Tcs, float MinConfidence);
@@ -1,39 +1,45 @@
using Heimdall.Application.DTOs;
using ImageMagick;
namespace Heimdall.Agent.Services;
/// <summary>
/// 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.
/// </summary>
/// <summary>Per-camera pixel difference on a fixed RGB grid; JPEG encoding size is irrelevant.</summary>
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;
/// <summary>
/// Feeds the next frame and reports whether the scene changed enough to
/// count as motion. The first frame is always a baseline (no motion).
/// </summary>
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; }
}
@@ -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<SnapshotPipelineService> _logger;
private readonly SemaphoreSlim _syncLock = new(1, 1);
private readonly Dictionary<Guid, string> _streamUrls = new();
private readonly ConcurrentDictionary<Guid, FrameMotionDetector> _motionDetectors = new();
private readonly ConcurrentDictionary<Guid, SceneState> _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(); }
}
/// <summary>
@@ -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)
{
@@ -51,6 +51,10 @@ public class ReportCameraStatusCommandHandler : IRequestHandler<ReportCameraStat
if (camera.SiteId != agent.SiteId)
return ServiceResult.Failure("Camera does not belong to the agent's site");
// Administrative disable wins over an in-flight capture status report.
if (camera.Status == CameraStatus.Disabled && request.Status != CameraStatus.Disabled)
return ServiceResult.Success();
if (camera.Status != request.Status)
{
camera.SetStatus(request.Status);
@@ -4,6 +4,7 @@ using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Cameras.Commands.UpdateCamera;
public record UpdateCameraCommand(
@@ -12,7 +13,8 @@ public record UpdateCameraCommand(
string? RtspUrl,
CameraStatus? Status,
string? Manufacturer = null,
string? Model = null) : IRequest<ServiceResult<CameraResponse>>;
string? Model = null,
DetectionProfileDto? DetectionProfile = null) : IRequest<ServiceResult<CameraResponse>>;
public class UpdateCameraCommandHandler : IRequestHandler<UpdateCameraCommand, ServiceResult<CameraResponse>>
{
@@ -29,6 +31,16 @@ public class UpdateCameraCommandHandler : IRequestHandler<UpdateCameraCommand, S
if (camera is null)
return ServiceResult<CameraResponse>.NotFound("Camera not found");
if (request.DetectionProfile is { } executionProfile)
{
try { executionProfile.Validate(); }
catch (ArgumentException ex) { return ServiceResult<CameraResponse>.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);
+2 -1
View File
@@ -14,7 +14,8 @@ public record UpdateCameraRequest(
string? RtspUrl,
CameraStatus? Status,
string? Manufacturer = null,
string? Model = null);
string? Model = null,
DetectionProfileDto? DetectionProfile = null);
/// <summary>Camera response including all discovery and stream test metadata.</summary>
public record CameraResponse(
@@ -0,0 +1,43 @@
namespace Heimdall.Application.DTOs;
/// <summary>Version 1 supports COCO object detection and a normalized pixel motion gate.</summary>
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
};
}
@@ -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;
@@ -7,6 +7,8 @@ namespace Heimdall.Domain.Entities;
public class CameraDetectionProfile
{
public Guid CameraId { get; private set; }
/// <summary>Optional versioned execution contract; null preserves legacy defaults.</summary>
public string? ExecutionProfileJson { get; set; }
// Object types to detect
public bool DetectPerson { get; set; } = true;
@@ -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<AppUser, AppRole, Guid>, IApplicationDbContext
{
private readonly AuditInterceptor _auditInterceptor;
private readonly IConfigBroadcastService? _configBroadcast;
public AppDbContext(
DbContextOptions<AppDbContext> 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<AppUser, AppRole, Guid>, IApplicat
await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct).ConfigureAwait(false);
}
public override async Task<int> 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);
@@ -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<string>(name: "ExecutionProfileJson", table: "camera_detection_profiles", type: "text", nullable: true);
protected override void Down(MigrationBuilder migrationBuilder) =>
migrationBuilder.DropColumn(name: "ExecutionProfileJson", table: "camera_detection_profiles");
}
@@ -900,6 +900,9 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b =>
{
b.Property<string>("ExecutionProfileJson")
.HasColumnType("text");
b.Property<Guid>("CameraId")
.HasColumnType("uuid");
@@ -74,7 +74,7 @@ public class CamerasController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> 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)
@@ -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<string, string>
{
[$"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<string, string>());
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<ArgumentException>(() => store.ReplaceCentral(new Dictionary<string, string>
{ [$"camera.{id}.profile"] = JsonSerializer.Serialize(new DetectionProfileDto { Version = 2 }) }));
store.Cameras.Single().RtspUrl.ShouldBe("rtsp://old");
}
[Fact]
public void UnsupportedFeatures_AndInvalidThreshold_AreRejected()
{
Should.Throw<ArgumentException>(() => new DetectionProfileDto { MinConfidence = float.NaN }.Validate());
Should.Throw<ArgumentException>(() => new DetectionProfileDto { DetectPackage = true }.Validate());
Should.Throw<ArgumentException>(() => new DetectionProfileDto { ZoneX = .8, ZoneWidth = .5 }.Validate());
}
}
@@ -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<ILogger<FrameAnalyzerService>>(), 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<ILogger<FrameAnalyzerService>>());
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<ILogger<FrameAnalyzerService>>(), 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<ILogger<FrameAnalyzerService>>(), 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]
@@ -46,43 +46,40 @@ public class SceneStateTrackerTests
public class FrameMotionDetectorTests
{
[Fact]
public void FirstFrame_IsBaseline_NoMotion()
private static byte[] Frame(ImageMagick.IMagickColor<ushort> 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();
}
}
@@ -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<string, string>
{
[$"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
@@ -24,7 +24,7 @@ public class ReportCameraStatusCommandTests
_db, _monitoring, NullLogger<ReportCameraStatusCommandHandler>.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");