feat(agent): pipeline capture vidéo — FFmpeg par caméra, snapshots adaptatifs, frames → analyseur (Fixes #1)

- CameraStreamService enregistré dans le DI + hosted SnapshotPipelineService
  qui synchronise les captures avec les caméras assignées (Central = source de
  vérité via clés camera.<id>.* dans la config agent ; fallback local Agent:Cameras)
- Découpage du flux MJPEG en frames JPEG (JpegFrameSplitter, marqueurs SOI/EOI)
- Intervalle adaptatif (spec Phase 15) : scène vide 1000ms / mouvement 500ms /
  objet détecté 200ms, doublé si CPU > 80% ; état de scène piloté par les
  résultats de l'analyseur + proxy de mouvement (FrameMotionDetector, pixel diff
  réel en Phase 16)
- Channel borné 100 snapshots (DropOldest) — backpressure + compteur de drops
  et log rate-limité (alerte admin via remontée des logs agent)
- Frames réellement transmises à FrameAnalyzerService (compteur AnalyzedFrameCount)
- Central : GET /api/settings/agent/{id} embarque les caméras assignées
  (name/rtsp/sub_rtsp/enabled) ; ConfigReceiverService les applique à chaud
- Tests : JpegFrameSplitter, intervalle adaptatif, tracker de scène, motion
  detector, CameraConfigStore, pipeline (snapshot → analyseur), handler config
This commit is contained in:
Arnaud Dartois committed 2026-08-11 21:16:28 +02:00
1 parent ea773b17a1
commit c38d69a1e5
24 files changed
+1365 -12

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations;
namespace Heimdall.Agent;
/// <summary>
/// A camera assignment declared in the local agent configuration
/// (<c>Agent:Cameras</c>). Used only as a fallback before the Central camera
/// list is received through the settings pipeline.
/// </summary>
public sealed class AgentCameraOptions
{
/// <summary>Display name of the camera.</summary>
public string Name { get; init; } = string.Empty;
/// <summary>Primary RTSP URL of the camera.</summary>
[Required, Url]
public string RtspUrl { get; init; } = string.Empty;
/// <summary>Secondary / sub-stream RTSP URL (lower resolution, preferred for AI).</summary>
[Url]
public string? SubRtspUrl { get; init; }
}
+8
View File
@@ -44,4 +44,12 @@ public sealed class AgentOptions
/// <summary>Agent software version reported to Central.</summary>
public string Version { get; init; } = "1.0.0";
/// <summary>
/// Local camera assignments used as a fallback until the Central ships its
/// camera list (per-agent settings pipeline). Useful for development or
/// agents that cannot reach the Central camera registry. When the Central
/// config arrives, it replaces this list entirely.
/// </summary>
public List<AgentCameraOptions> Cameras { get; init; } = [];
}
+8
View File
@@ -71,6 +71,14 @@ builder.Services.AddHostedService<AgentRegistrationService>();
builder.Services.AddHostedService<ConfigReceiverService>();
builder.Services.AddHostedService<AgentDiscoveryService>();
// Video capture pipeline (ticket #1): FFmpeg capture per assigned camera,
// bounded snapshot channel, adaptive interval, frames → FrameAnalyzerService.
builder.Services.AddSingleton<SceneStateTracker>();
builder.Services.AddSingleton<CameraConfigStore>();
builder.Services.AddSingleton<FrameAnalyzerService>();
builder.Services.AddSingleton<CameraStreamService>();
builder.Services.AddHostedService<SnapshotPipelineService>();
// Log capture & upload to Central (ticket #50)
builder.Services.AddSingleton<LogBufferService>();
builder.Services.AddSingleton<AgentLoggingProvider>();
@@ -0,0 +1,29 @@
namespace Heimdall.Agent.Services;
/// <summary>
/// Computes the snapshot interval from the scene state and CPU load, per
/// MASTER_SPECIFICATION Phase 15: idle 1000ms, motion 500ms, object detected
/// 200ms, and the interval is doubled while CPU usage exceeds 80%.
/// </summary>
public sealed class AdaptiveSnapshotInterval
{
public const int IdleMs = 1000;
public const int MotionMs = 500;
public const int ObjectDetectedMs = 200;
public const double CpuThrottlePercent = 80.0;
public TimeSpan GetInterval(SceneState state, double? cpuPercent)
{
var ms = state switch
{
SceneState.ObjectDetected => ObjectDetectedMs,
SceneState.Motion => MotionMs,
_ => IdleMs,
};
if (cpuPercent is >= CpuThrottlePercent)
ms *= 2;
return TimeSpan.FromMilliseconds(ms);
}
}
@@ -0,0 +1,20 @@
namespace Heimdall.Agent.Services;
/// <summary>
/// Immutable camera assignment consumed by the capture pipeline. Built either
/// from the Central settings keys (<c>camera.&lt;id&gt;.name|rtsp|sub_rtsp|enabled</c>)
/// or from the local <c>Agent:Cameras</c> fallback.
/// </summary>
public sealed record AgentCameraConfig(
Guid CameraId,
string Name,
string RtspUrl,
string? SubRtspUrl,
bool Enabled)
{
/// <summary>
/// URL used for AI capture: the low-res sub-stream when available,
/// otherwise the primary stream.
/// </summary>
public string EffectiveRtspUrl => !string.IsNullOrWhiteSpace(SubRtspUrl) ? SubRtspUrl : RtspUrl;
}
@@ -0,0 +1,82 @@
using System.Collections.Concurrent;
namespace Heimdall.Agent.Services;
/// <summary>
/// Holds the camera assignments the agent must capture. The Central is the
/// source of truth: cameras are shipped as flat <c>camera.&lt;id&gt;.name|rtsp|sub_rtsp|enabled</c>
/// keys through the settings pipeline (full reload + live SettingChanged).
/// A local list from <c>AgentOptions.Cameras</c> serves as a fallback until
/// the first Central config is received.
/// </summary>
public sealed class CameraConfigStore
{
private readonly ConcurrentDictionary<Guid, AgentCameraConfig> _central = new();
private IReadOnlyList<AgentCameraConfig> _localFallback = [];
private volatile bool _centralReceived;
/// <summary>Raised whenever the effective camera list may have changed.</summary>
public event EventHandler? Changed;
/// <summary>Sets the local fallback list (used until Central config arrives).</summary>
public void SetLocalFallback(IReadOnlyList<AgentCameraConfig> cameras)
{
_localFallback = cameras;
RaiseChanged();
}
/// <summary>
/// Applies a single <c>camera.&lt;id&gt;.&lt;field&gt;</c> setting key received from
/// the Central. Any such key marks the Central list as authoritative.
/// </summary>
public void ApplyCameraSetting(string key, string value)
{
// camera.<id>.<field>
var parts = key.Split('.', 3);
if (parts.Length != 3 || !Guid.TryParse(parts[1], out var cameraId))
return;
_centralReceived = true;
_central.AddOrUpdate(
cameraId,
_ => BuildConfig(cameraId, parts[2], value),
(_, existing) => existing with
{
Name = parts[2] == "name" ? value : existing.Name,
RtspUrl = parts[2] == "rtsp" ? value : existing.RtspUrl,
SubRtspUrl = parts[2] == "sub_rtsp" ? value : existing.SubRtspUrl,
Enabled = parts[2] == "enabled" ? ParseBool(value) : existing.Enabled,
});
RaiseChanged();
}
/// <summary>
/// Marks the Central config as received; the local fallback is no longer
/// used, even if the Central list is empty.
/// </summary>
public void MarkCentralReceived()
{
if (_centralReceived)
return;
_centralReceived = true;
RaiseChanged();
}
/// <summary>Effective camera assignments: Central list, or local fallback before that.</summary>
public IReadOnlyList<AgentCameraConfig> Cameras =>
_centralReceived ? _central.Values.ToArray() : _localFallback;
private static AgentCameraConfig BuildConfig(Guid cameraId, string field, string value) => new(
cameraId,
field == "name" ? value : string.Empty,
field == "rtsp" ? value : string.Empty,
field == "sub_rtsp" ? value : null,
field == "enabled" ? ParseBool(value) : true);
private static bool ParseBool(string value) =>
bool.TryParse(value, out var parsed) ? parsed : value is "1" or "true" or "True";
private void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty);
}
@@ -1,21 +1,53 @@
using System.Buffers;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
namespace Heimdall.Agent.Services;
/// <summary>
/// Manages RTSP stream connections for each assigned camera.
/// Launches FFmpeg processes to capture frames and feeds them to
/// the detection pipeline for analysis.
/// Launches FFmpeg processes to capture MJPEG frames, splits the pipe into
/// complete JPEG frames, samples them at the adaptive snapshot interval
/// (idle 1000ms / motion 500ms / object detected 200ms, doubled while
/// CPU &gt; 80%) and queues them on a bounded channel for the analysis
/// pipeline. Queue overflow drops the oldest frame (backpressure) and is
/// surfaced through <see cref="DroppedSnapshotCount"/> and a rate-limited log.
/// </summary>
public sealed class CameraStreamService : IDisposable
{
/// <summary>Max queued snapshots before oldest frames are dropped (MASTER_SPEC Phase 15: &gt;100).</summary>
public const int MaxQueueSize = 100;
private readonly ILogger<CameraStreamService> _logger;
private readonly string _ffmpegPath;
private readonly SceneStateTracker _sceneState;
private readonly SystemMetricsProvider _metrics;
private readonly AdaptiveSnapshotInterval _snapshotInterval;
private readonly ConcurrentDictionary<Guid, StreamSession> _sessions = new();
private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg
private long _droppedSnapshots;
private DateTime _lastDropLogAt;
private DateTime _cpuSampleAt;
private double? _cpuPercent;
/// <summary>
/// Bounded channel receiving sampled snapshots. Full mode DropOldest —
/// when the queue is full the oldest frame is dropped (backpressure).
/// </summary>
public Channel<Snapshot> SnapshotChannel { get; } = Channel.CreateBounded<Snapshot>(
new BoundedChannelOptions(MaxQueueSize)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
SingleWriter = false,
});
/// <summary>Total number of frames dropped because the queue was full.</summary>
public long DroppedSnapshotCount => Interlocked.Read(ref _droppedSnapshots);
/// <summary>
/// Creates a new CameraStreamService.
/// </summary>
@@ -24,17 +56,32 @@ public sealed class CameraStreamService : IDisposable
/// Path to the FFmpeg executable. Defaults to "ffmpeg" (search PATH).
/// Override in tests to use a non-existent path to simulate ffmpeg not being available.
/// </param>
public CameraStreamService(ILogger<CameraStreamService> logger, string ffmpegPath = "ffmpeg")
/// <param name="sceneState">Scene state tracker (defaults to a private one).</param>
/// <param name="metrics">System metrics provider for CPU-based interval throttling.</param>
/// <param name="snapshotInterval">Adaptive interval calculator (defaults to the spec values).</param>
public CameraStreamService(
ILogger<CameraStreamService> logger,
string ffmpegPath = "ffmpeg",
SceneStateTracker? sceneState = null,
SystemMetricsProvider? metrics = null,
AdaptiveSnapshotInterval? snapshotInterval = null)
{
_logger = logger;
_ffmpegPath = ffmpegPath;
_sceneState = sceneState ?? new SceneStateTracker();
_metrics = metrics ?? new SystemMetricsProvider();
_snapshotInterval = snapshotInterval ?? new AdaptiveSnapshotInterval();
}
private readonly string _ffmpegPath;
/// <summary>Start streaming from a camera. Launches FFmpeg in the background.</summary>
public async Task<bool> StartStreamAsync(Guid cameraId, string rtspUrl, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(rtspUrl) || !Uri.TryCreate(rtspUrl, UriKind.Absolute, out _))
{
_logger.LogWarning("Invalid or empty RTSP URL for camera {CameraId}", cameraId);
return false;
}
if (_sessions.ContainsKey(cameraId))
{
_logger.LogWarning("Stream already active for camera {CameraId}", cameraId);
@@ -104,9 +151,22 @@ public sealed class CameraStreamService : IDisposable
return Task.CompletedTask;
}
/// <summary>Stops every active stream (agent shutdown).</summary>
public async Task StopAllAsync()
{
foreach (var cameraId in _sessions.Keys.ToArray())
await StopStreamAsync(cameraId);
}
/// <summary>Number of currently active streams.</summary>
public int ActiveStreamCount => _sessions.Count;
/// <summary>IDs of the cameras with an active stream.</summary>
public IReadOnlyList<Guid> ActiveCameraIds => _sessions.Keys.ToArray();
/// <summary>Whether a stream is currently active for the given camera.</summary>
public bool IsStreamActive(Guid cameraId) => _sessions.ContainsKey(cameraId);
private async Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct)
{
var buffer = ArrayPool<byte>.Shared.Rent(256 * 1024);
@@ -119,9 +179,11 @@ public sealed class CameraStreamService : IDisposable
var bytesRead = await stream.ReadAsync(buffer.AsMemory(), ct);
if (bytesRead == 0) break;
// Frame available for analysis — will be passed to FrameAnalyzerService
// in a future phase. For now, we just count frames.
Interlocked.Increment(ref session.FrameCount);
session.Splitter.Append(buffer.AsSpan(0, bytesRead));
while (session.Splitter.TryReadFrame(out var frame))
MaybeEmitSnapshot(cameraId, session, frame);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
@@ -135,6 +197,39 @@ 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());
if (now - session.LastSnapshotAt < interval)
return; // sample less often than FFmpeg pushes frames
session.LastSnapshotAt = now;
if (!SnapshotChannel.Writer.TryWrite(new Snapshot(cameraId, now, frame)))
{
Interlocked.Increment(ref _droppedSnapshots);
if (now - _lastDropLogAt > TimeSpan.FromSeconds(30))
{
_lastDropLogAt = now;
_logger.LogWarning(
"Snapshot queue full for camera {CameraId} — oldest frame dropped (total: {Dropped})",
cameraId, Interlocked.Read(ref _droppedSnapshots));
}
}
}
private double? GetCpuPercent()
{
var now = DateTime.UtcNow;
if (_cpuSampleAt == default || (now - _cpuSampleAt).TotalSeconds >= 2)
{
_cpuPercent = _metrics.Collect().CpuUsagePercent;
_cpuSampleAt = now;
}
return _cpuPercent;
}
private void CleanupSession(Guid cameraId, StreamSession session)
{
try
@@ -169,6 +264,7 @@ public sealed class CameraStreamService : IDisposable
session.Process?.Dispose();
}
_sessions.Clear();
SnapshotChannel.Writer.TryComplete();
_throttle.Dispose();
}
@@ -179,6 +275,8 @@ public sealed class CameraStreamService : IDisposable
public Process Process { get; } = process;
public long FrameCount;
public bool SemaphoreReleased;
public JpegFrameSplitter Splitter { get; } = new();
public DateTime LastSnapshotAt { get; set; } = DateTime.MinValue;
private volatile bool _cancelled;
public bool IsCancelled => _cancelled;
public void Cancel() => _cancelled = true;
@@ -20,6 +20,7 @@ public sealed class ConfigReceiverService : BackgroundService
private readonly DiscoveryScanTrigger _scanTrigger;
private readonly AgentCredentialStore _credentialStore;
private readonly RuntimeLogLevel _runtimeLogLevel;
private readonly CameraConfigStore _cameraStore;
private HubConnection? _connection;
/// <summary>
@@ -36,7 +37,6 @@ public sealed class ConfigReceiverService : BackgroundService
"model.",
"ffmpeg.",
"yolo.",
"camera.",
};
public ConfigReceiverService(
@@ -46,7 +46,8 @@ public sealed class ConfigReceiverService : BackgroundService
IHttpClientFactory httpClientFactory,
DiscoveryScanTrigger scanTrigger,
AgentCredentialStore credentialStore,
RuntimeLogLevel runtimeLogLevel)
RuntimeLogLevel runtimeLogLevel,
CameraConfigStore cameraStore)
{
_state = state;
_options = options.Value;
@@ -55,6 +56,7 @@ public sealed class ConfigReceiverService : BackgroundService
_scanTrigger = scanTrigger;
_credentialStore = credentialStore;
_runtimeLogLevel = runtimeLogLevel;
_cameraStore = cameraStore;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -152,6 +154,14 @@ public sealed class ConfigReceiverService : BackgroundService
private void ApplySetting(string key, string value)
{
// Camera assignments are applied live: the capture pipeline resyncs
// on every store change (start new streams, stop removed ones).
if (key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
{
_cameraStore.ApplyCameraSetting(key, value);
return;
}
// Apply known settings locally (live, no restart required)
switch (key)
{
@@ -258,6 +268,10 @@ public sealed class ConfigReceiverService : BackgroundService
// documentation, everything.
foreach (var kvp in config)
ApplySetting(kvp.Key, kvp.Value);
// The Central camera list is authoritative once the full config
// arrives — even if it is empty, drop the local fallback.
_cameraStore.MarkCentralReceived();
}
catch (Exception ex)
{
@@ -57,6 +57,11 @@ public sealed class FrameAnalyzerService : IDisposable
private const int MaxQueueSize = 16;
private const int InputSize = 640; // YOLOv8 input size
private long _analyzedFrameCount;
/// <summary>Number of frames actually handed to the analyzer (real calls, including passthrough).</summary>
public long AnalyzedFrameCount => Interlocked.Read(ref _analyzedFrameCount);
public FrameAnalyzerService(ILogger<FrameAnalyzerService> logger)
{
_logger = logger;
@@ -88,6 +93,8 @@ public sealed class FrameAnalyzerService : IDisposable
/// </summary>
public async Task<FrameAnalysisResult?> AnalyzeFrameAsync(byte[] jpegData, CancellationToken ct = default)
{
Interlocked.Increment(ref _analyzedFrameCount);
if (!_modelLoaded)
return null;
@@ -110,6 +117,8 @@ public sealed class FrameAnalyzerService : IDisposable
/// </summary>
public FrameAnalysisResult? AnalyzeFrame(byte[] jpegData)
{
Interlocked.Increment(ref _analyzedFrameCount);
if (!_modelLoaded) return null;
var sw = System.Diagnostics.Stopwatch.StartNew();
@@ -0,0 +1,39 @@
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>
public sealed class FrameMotionDetector
{
private readonly double _thresholdPercent;
private long _lastFrameLength;
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)
{
var length = jpegFrame.Length;
if (_lastFrameLength == 0)
{
_lastFrameLength = length;
return false;
}
var change = Math.Abs(length - _lastFrameLength) / (double)_lastFrameLength * 100.0;
_lastFrameLength = length;
return change >= _thresholdPercent;
}
public void Reset() => _lastFrameLength = 0;
}
@@ -0,0 +1,105 @@
namespace Heimdall.Agent.Services;
/// <summary>
/// Splits a continuous MJPEG pipe (FFmpeg <c>image2pipe</c>) into complete JPEG
/// frames by scanning for the SOI (FF D8) and EOI (FF D9) markers. A new SOI
/// before the previous EOI discards the incomplete frame (mid-stream join).
/// Marker bytes never occur inside JPEG entropy data (0xFF is escaped), so a
/// size scan is safe.
/// </summary>
public sealed class JpegFrameSplitter
{
private byte[] _data = new byte[256 * 1024];
private int _length;
private int _scanPos;
private int _frameStart = -1;
private int _frameEnd = -1;
/// <summary>Appends the next chunk read from the pipe.</summary>
public void Append(ReadOnlySpan<byte> chunk)
{
EnsureCapacity(_length + chunk.Length);
chunk.CopyTo(_data.AsSpan(_length));
_length += chunk.Length;
Scan();
}
/// <summary>
/// Returns the next complete JPEG frame (SOI..EOI inclusive) and removes
/// it from the buffer, or false when no complete frame is available yet.
/// </summary>
public bool TryReadFrame(out byte[] frame)
{
if (_frameEnd < 0)
{
frame = [];
return false;
}
var length = _frameEnd - _frameStart;
frame = new byte[length];
Array.Copy(_data, _frameStart, frame, 0, length);
// Drop consumed bytes, keep whatever follows the EOI.
var remaining = _length - _frameEnd;
if (remaining > 0)
Array.Copy(_data, _frameEnd, _data, 0, remaining);
_length = remaining;
_frameStart = -1;
_frameEnd = -1;
// Restart scanning from the beginning of the remaining bytes — the
// previous _scanPos pointed into the consumed frame.
_scanPos = 0;
// Another complete frame may already be buffered — scan it now.
Scan();
return true;
}
public void Reset()
{
_length = 0;
_scanPos = 0;
_frameStart = -1;
_frameEnd = -1;
}
private void Scan()
{
var i = Math.Max(_scanPos, 0);
while (i < _length - 1)
{
if (_data[i] == 0xFF && _data[i + 1] == 0xD8)
{
// New SOI: restart the current frame (a newer frame wins).
_frameStart = i;
i += 2;
continue;
}
if (_data[i] == 0xFF && _data[i + 1] == 0xD9 && _frameStart >= 0)
{
_frameEnd = i + 2;
return; // complete frame — wait for TryReadFrame
}
i++;
}
// Nothing complete: resume scanning from the last two bytes next time
// (a marker can straddle two chunks).
_scanPos = _length >= 2 ? _length - 2 : 0;
}
private void EnsureCapacity(int required)
{
if (required <= _data.Length)
return;
var newSize = _data.Length;
while (newSize < required)
newSize *= 2;
Array.Resize(ref _data, newSize);
}
}
+13
View File
@@ -0,0 +1,13 @@
namespace Heimdall.Agent.Services;
/// <summary>
/// State of the scene in front of a camera, driving the adaptive snapshot
/// interval (MASTER_SPECIFICATION Phase 15):
/// idle 1000ms, motion 500ms, object detected 200ms.
/// </summary>
public enum SceneState
{
Idle = 0,
Motion = 1,
ObjectDetected = 2,
}
@@ -0,0 +1,24 @@
namespace Heimdall.Agent.Services;
/// <summary>
/// Holds the current scene state shared between the analysis pipeline
/// (writer) and the capture loop (reader). Volatile field so both sides see
/// the latest value without locks.
/// </summary>
public sealed class SceneStateTracker
{
private volatile SceneState _state = SceneState.Idle;
public SceneState State => _state;
public void Set(SceneState state) => _state = state;
/// <summary>
/// Updates the state from one analyzed frame: any detection wins over
/// motion, otherwise the motion proxy decides between Motion and Idle.
/// </summary>
public void UpdateFromAnalysis(bool hasDetections, bool hasMotion)
{
_state = hasDetections ? SceneState.ObjectDetected : hasMotion ? SceneState.Motion : SceneState.Idle;
}
}
+4
View File
@@ -0,0 +1,4 @@
namespace Heimdall.Agent.Services;
/// <summary>A JPEG frame captured from a camera, queued for analysis.</summary>
public sealed record Snapshot(Guid CameraId, DateTime TimestampUtc, byte[] JpegData);
@@ -0,0 +1,192 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
/// <summary>
/// Orchestrates the video capture pipeline (MASTER_SPEC Phase 15):
/// keeps the FFmpeg capture streams in sync with the assigned cameras
/// (from the Central config, local fallback before that) and consumes the
/// bounded snapshot channel, forwarding each frame to the
/// <see cref="FrameAnalyzerService"/> and updating the scene state that
/// drives the adaptive snapshot interval.
/// </summary>
public sealed class SnapshotPipelineService : BackgroundService
{
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly CameraConfigStore _cameraStore;
private readonly CameraStreamService _streams;
private readonly FrameAnalyzerService _analyzer;
private readonly SceneStateTracker _sceneState;
private readonly ILogger<SnapshotPipelineService> _logger;
private readonly ConcurrentDictionary<Guid, FrameMotionDetector> _motionDetectors = new();
private long _snapshotsProcessed;
private long _analysisFailures;
private bool _storeSubscribed;
public SnapshotPipelineService(
AgentState state,
IOptions<AgentOptions> options,
CameraConfigStore cameraStore,
CameraStreamService streams,
FrameAnalyzerService analyzer,
SceneStateTracker sceneState,
ILogger<SnapshotPipelineService> logger)
{
_state = state;
_options = options.Value;
_cameraStore = cameraStore;
_streams = streams;
_analyzer = analyzer;
_sceneState = sceneState;
_logger = logger;
}
/// <summary>Number of snapshots handed to the analyzer (real calls).</summary>
public long SnapshotsProcessed => Interlocked.Read(ref _snapshotsProcessed);
/// <summary>Number of frames that failed analysis (analyzer exceptions).</summary>
public long AnalysisFailures => Interlocked.Read(ref _analysisFailures);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Local fallback (Agent:Cameras) until the Central camera list arrives.
_cameraStore.SetLocalFallback(BuildLocalCameras());
// Wait until the agent is registered (has an AgentId), same as
// ConfigReceiverService — the Central config needs the agent identity.
while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
await Task.Delay(1000, stoppingToken);
if (stoppingToken.IsCancellationRequested) return;
_cameraStore.Changed += OnCameraConfigChanged;
_storeSubscribed = true;
var consumer = Task.Run(() => ConsumeSnapshotsAsync(stoppingToken), stoppingToken);
try
{
await SyncStreamsAsync(stoppingToken);
// Periodic resync catches assignments missed while we were busy
// (e.g. camera settings applied before we subscribed).
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
await SyncStreamsAsync(stoppingToken);
}
}
finally
{
if (_storeSubscribed)
_cameraStore.Changed -= OnCameraConfigChanged;
try { await consumer; } catch (OperationCanceledException) { }
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await _streams.StopAllAsync();
await base.StopAsync(cancellationToken);
}
private void OnCameraConfigChanged(object? sender, EventArgs e)
{
// Fire-and-forget resync; SyncStreamsAsync is idempotent and cheap.
_ = Task.Run(() => SyncStreamsAsync(CancellationToken.None));
}
private async Task SyncStreamsAsync(CancellationToken ct)
{
var desired = _cameraStore.Cameras
.Where(c => c.Enabled && !string.IsNullOrWhiteSpace(c.EffectiveRtspUrl))
.ToList();
// Stop streams for cameras no longer assigned/disabled.
foreach (var activeId in _streams.ActiveCameraIds)
{
if (!desired.Any(c => c.CameraId == activeId))
await _streams.StopStreamAsync(activeId);
}
// Start streams for newly assigned cameras.
foreach (var camera in desired)
{
if (_streams.IsStreamActive(camera.CameraId))
continue;
var started = await _streams.StartStreamAsync(camera.CameraId, camera.EffectiveRtspUrl, ct);
if (started)
_logger.LogInformation("Capture started for camera {CameraId} ({Name})", camera.CameraId, camera.Name);
else
_logger.LogWarning(
"Capture failed to start for camera {CameraId} ({Name}) — will retry at next sync",
camera.CameraId, camera.Name);
}
}
private async Task ConsumeSnapshotsAsync(CancellationToken ct)
{
try
{
await foreach (var snapshot in _streams.SnapshotChannel.Reader.ReadAllAsync(ct))
{
try
{
// Real call into the analyzer — the pipeline's reason to exist.
var result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, ct);
Interlocked.Increment(ref _snapshotsProcessed);
var detector = _motionDetectors.GetOrAdd(snapshot.CameraId, _ => new FrameMotionDetector());
_sceneState.UpdateFromAnalysis(
result?.Detections.Count > 0,
detector.Detect(snapshot.JpegData));
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
Interlocked.Increment(ref _analysisFailures);
_logger.LogWarning(ex, "Snapshot analysis failed for camera {CameraId}", snapshot.CameraId);
}
}
}
catch (OperationCanceledException)
{
// Shutdown.
}
}
private List<AgentCameraConfig> BuildLocalCameras()
{
var list = new List<AgentCameraConfig>();
var index = 0;
foreach (var camera in _options.Cameras)
{
index++;
if (string.IsNullOrWhiteSpace(camera.RtspUrl))
continue;
list.Add(new AgentCameraConfig(
StableCameraId(camera.Name, camera.RtspUrl),
string.IsNullOrWhiteSpace(camera.Name) ? $"camera-{index}" : camera.Name,
camera.RtspUrl,
string.IsNullOrWhiteSpace(camera.SubRtspUrl) ? null : camera.SubRtspUrl,
Enabled: true));
}
return list;
}
/// <summary>Stable ID for a locally-declared camera (no Central ID yet).</summary>
private static Guid StableCameraId(string name, string rtspUrl)
{
var hash = System.Security.Cryptography.SHA256.HashData(
System.Text.Encoding.UTF8.GetBytes($"{name}|{rtspUrl}"));
return new Guid(hash.AsSpan(0, 16));
}
}
@@ -1,6 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Security;
using Heimdall.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
@@ -68,6 +69,29 @@ public class GetEffectiveAgentConfigQueryHandler
}
}
// ── Camera assignments ──
// The agent needs the RTSP URLs of the cameras it must capture. The
// Central is the source of truth: cameras assigned to this agent (and
// not soft-deleted) are shipped as flat `camera.<id>.*` keys so the
// existing config pipeline (full reload + live SettingChanged events)
// carries them to the agent without a new API surface.
var cameras = await _db.Cameras
.AsNoTracking()
.Where(c => c.AgentId == request.AgentId && !c.IsDeleted)
.ToListAsync(ct)
.ConfigureAwait(false);
foreach (var camera in cameras)
{
var prefix = $"camera.{camera.Id}";
config[$"{prefix}.name"] = camera.Name;
if (!string.IsNullOrWhiteSpace(camera.RtspUrl))
config[$"{prefix}.rtsp"] = camera.RtspUrl;
if (!string.IsNullOrWhiteSpace(camera.SubRtspUrl))
config[$"{prefix}.sub_rtsp"] = camera.SubRtspUrl;
config[$"{prefix}.enabled"] = camera.Status != CameraStatus.Disabled ? "true" : "false";
}
return ServiceResult<Dictionary<string, string>>.Success(config);
}
}
@@ -0,0 +1,56 @@
using Heimdall.Agent.Services;
namespace Heimdall.Agent.Tests;
public class AdaptiveSnapshotIntervalTests
{
private readonly AdaptiveSnapshotInterval _interval = new();
[Fact]
public void Idle_Returns1000ms()
{
_interval.GetInterval(SceneState.Idle, cpuPercent: null).ShouldBe(TimeSpan.FromMilliseconds(1000));
}
[Fact]
public void Motion_Returns500ms()
{
_interval.GetInterval(SceneState.Motion, cpuPercent: null).ShouldBe(TimeSpan.FromMilliseconds(500));
}
[Fact]
public void ObjectDetected_Returns200ms()
{
_interval.GetInterval(SceneState.ObjectDetected, cpuPercent: null).ShouldBe(TimeSpan.FromMilliseconds(200));
}
[Fact]
public void HighCpu_DoublesIdleInterval()
{
_interval.GetInterval(SceneState.Idle, cpuPercent: 85.0).ShouldBe(TimeSpan.FromMilliseconds(2000));
}
[Fact]
public void HighCpu_DoublesObjectDetectedInterval()
{
_interval.GetInterval(SceneState.ObjectDetected, cpuPercent: 95.0).ShouldBe(TimeSpan.FromMilliseconds(400));
}
[Fact]
public void CpuBelowThreshold_NoThrottle()
{
_interval.GetInterval(SceneState.Motion, cpuPercent: 50.0).ShouldBe(TimeSpan.FromMilliseconds(500));
}
[Fact]
public void CpuExactlyAtThreshold_Throttles()
{
_interval.GetInterval(SceneState.Motion, cpuPercent: 80.0).ShouldBe(TimeSpan.FromMilliseconds(1000));
}
[Fact]
public void NullCpu_NoThrottle()
{
_interval.GetInterval(SceneState.Idle, cpuPercent: null).ShouldBe(TimeSpan.FromMilliseconds(1000));
}
}
@@ -0,0 +1,102 @@
using Heimdall.Agent.Services;
namespace Heimdall.Agent.Tests;
public class CameraConfigStoreTests
{
[Fact]
public void EmptyStore_NoCameras()
{
var store = new CameraConfigStore();
store.Cameras.ShouldBeEmpty();
}
[Fact]
public void SetLocalFallback_ReturnedBeforeCentralConfig()
{
var store = new CameraConfigStore();
var camera = new AgentCameraConfig(Guid.NewGuid(), "Locale", "rtsp://local/stream", null, true);
store.SetLocalFallback([camera]);
store.Cameras.ShouldBe([camera]);
}
[Fact]
public void ApplyCameraSetting_AssemblesConfigFromKeys()
{
var store = new CameraConfigStore();
var id = Guid.NewGuid();
var changed = 0;
store.Changed += (_, _) => changed++;
store.ApplyCameraSetting($"camera.{id}.name", "Entrée");
store.ApplyCameraSetting($"camera.{id}.rtsp", "rtsp://cam/stream");
store.ApplyCameraSetting($"camera.{id}.sub_rtsp", "rtsp://cam/sub");
store.ApplyCameraSetting($"camera.{id}.enabled", "true");
var camera = store.Cameras.ShouldHaveSingleItem();
camera.CameraId.ShouldBe(id);
camera.Name.ShouldBe("Entrée");
camera.RtspUrl.ShouldBe("rtsp://cam/stream");
camera.SubRtspUrl.ShouldBe("rtsp://cam/sub");
camera.Enabled.ShouldBeTrue();
camera.EffectiveRtspUrl.ShouldBe("rtsp://cam/sub");
changed.ShouldBe(4);
}
[Fact]
public void ApplyCameraSetting_EnabledFalse_Parsed()
{
var store = new CameraConfigStore();
var id = Guid.NewGuid();
store.ApplyCameraSetting($"camera.{id}.enabled", "false");
store.Cameras.ShouldHaveSingleItem().Enabled.ShouldBeFalse();
}
[Fact]
public void ApplyCameraSetting_InvalidKey_Ignored()
{
var store = new CameraConfigStore();
var changed = 0;
store.Changed += (_, _) => changed++;
store.ApplyCameraSetting("camera.not-a-guid.rtsp", "rtsp://x");
store.ApplyCameraSetting("other.key", "value");
store.Cameras.ShouldBeEmpty();
changed.ShouldBe(0);
}
[Fact]
public void MarkCentralReceived_DropsLocalFallbackEvenIfEmpty()
{
var store = new CameraConfigStore();
store.SetLocalFallback([new AgentCameraConfig(Guid.NewGuid(), "L", "rtsp://l", null, true)]);
store.MarkCentralReceived();
store.Cameras.ShouldBeEmpty();
}
[Fact]
public void MarkCentralReceived_KeepsCentralCameras()
{
var store = new CameraConfigStore();
store.SetLocalFallback([new AgentCameraConfig(Guid.NewGuid(), "L", "rtsp://l", null, true)]);
var id = Guid.NewGuid();
store.ApplyCameraSetting($"camera.{id}.rtsp", "rtsp://c");
store.MarkCentralReceived();
var camera = store.Cameras.ShouldHaveSingleItem();
camera.CameraId.ShouldBe(id);
camera.RtspUrl.ShouldBe("rtsp://c");
}
[Fact]
public void ApplyCameraSetting_WithoutRtspUrl_StillShipped()
{
var store = new CameraConfigStore();
var id = Guid.NewGuid();
store.ApplyCameraSetting($"camera.{id}.name", "No flux");
var camera = store.Cameras.ShouldHaveSingleItem();
camera.Name.ShouldBe("No flux");
camera.RtspUrl.ShouldBeEmpty();
}
}
@@ -126,6 +126,64 @@ public class CameraStreamServiceTests
result.ShouldBeFalse();
}
[Fact]
public void SnapshotChannel_IsBounded_AndWritable()
{
using var service = CreateService();
service.SnapshotChannel.ShouldNotBeNull();
service.SnapshotChannel.Writer.TryWrite(new Snapshot(Guid.NewGuid(), DateTime.UtcNow, [1, 2, 3])).ShouldBeTrue();
service.DroppedSnapshotCount.ShouldBe(0);
}
[Fact]
public void DroppedSnapshotCount_InitialZero()
{
using var service = CreateService();
service.DroppedSnapshotCount.ShouldBe(0);
}
[Fact]
public void IsStreamActive_UnknownCamera_ReturnsFalse()
{
using var service = CreateService();
service.IsStreamActive(Guid.NewGuid()).ShouldBeFalse();
}
[Fact]
public void ActiveCameraIds_InitialEmpty()
{
using var service = CreateService();
service.ActiveCameraIds.ShouldBeEmpty();
}
[Fact]
public async Task StopAllAsync_WithoutStreams_DoesNotThrow()
{
using var service = CreateService();
await service.StopAllAsync();
}
[Fact]
public async Task StartStreamAsync_InvalidUrl_DoesNotCreateSession()
{
using var service = CreateService();
await service.StartStreamAsync(Guid.NewGuid(), string.Empty);
service.ActiveStreamCount.ShouldBe(0);
service.IsStreamActive(Guid.NewGuid()).ShouldBeFalse();
}
[Fact]
public void Constructor_WithSceneDependencies_DoesNotThrow()
{
using var service = new CameraStreamService(
Substitute.For<ILogger<CameraStreamService>>(),
FfmpegNotFound,
new SceneStateTracker(),
new SystemMetricsProvider(),
new AdaptiveSnapshotInterval());
service.ShouldNotBeNull();
}
private static CameraStreamService CreateService()
=> new(Substitute.For<ILogger<CameraStreamService>>(), FfmpegNotFound);
}
@@ -15,7 +15,8 @@ public class ConfigReceiverServiceTests
AgentState? state = null,
AgentCredentialStore? store = null,
RuntimeLogLevel? runtimeLogLevel = null,
IHttpClientFactory? httpFactory = null)
IHttpClientFactory? httpFactory = null,
CameraConfigStore? cameraStore = null)
{
state ??= new AgentState { AgentId = Guid.Empty };
var options = Options.Create(new AgentOptions
@@ -27,7 +28,7 @@ public class ConfigReceiverServiceTests
httpFactory ??= Substitute.For<IHttpClientFactory>();
var scanTrigger = new DiscoveryScanTrigger();
runtimeLogLevel ??= CreateRuntimeLogLevel().Runtime;
return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel);
return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel, cameraStore ?? new CameraConfigStore());
}
/// <summary>
@@ -368,6 +369,60 @@ public class ConfigReceiverServiceTests
store.Pool[0].Password.ShouldBe("secret");
}
[Fact]
public async Task FetchFullConfigAsync_AppliesCameraKeys_AndDropsLocalFallback()
{
const string apiKey = "test-agent-api-key";
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = apiKey };
var cameraStore = new CameraConfigStore();
cameraStore.SetLocalFallback(
[new AgentCameraConfig(Guid.NewGuid(), "Locale", "rtsp://local/stream", null, true)]);
var cameraId = Guid.NewGuid();
var json = $$"""
{
"camera.{{cameraId}}.name": "Entrée",
"camera.{{cameraId}}.rtsp": "rtsp://central/stream",
"camera.{{cameraId}}.enabled": "true"
}
""";
var httpFactory = Substitute.For<IHttpClientFactory>();
httpFactory.CreateClient("Central").Returns(new HttpClient(new StubHttpMessageHandler(json)));
var service = CreateService(state, httpFactory: httpFactory, cameraStore: cameraStore);
var method = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
await (Task)method.Invoke(service, [CancellationToken.None])!;
// Central camera list replaced the local fallback.
var camera = cameraStore.Cameras.ShouldHaveSingleItem();
camera.CameraId.ShouldBe(cameraId);
camera.Name.ShouldBe("Entrée");
camera.RtspUrl.ShouldBe("rtsp://central/stream");
camera.Enabled.ShouldBeTrue();
}
[Fact]
public void ApplySetting_CameraKey_UpdatesCameraStore()
{
var cameraStore = new CameraConfigStore();
var service = CreateService(cameraStore: cameraStore);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
var id = Guid.NewGuid();
method.Invoke(service, [$"camera.{id}.rtsp", "rtsp://live/stream"]);
method.Invoke(service, [$"camera.{id}.enabled", "false"]);
var camera = cameraStore.Cameras.ShouldHaveSingleItem();
camera.RtspUrl.ShouldBe("rtsp://live/stream");
camera.Enabled.ShouldBeFalse();
}
[Fact]
public async Task StartStop_MultipleTimes_DoesNotThrow()
{
@@ -0,0 +1,127 @@
using Heimdall.Agent.Services;
namespace Heimdall.Agent.Tests;
public class JpegFrameSplitterTests
{
private static readonly byte[] Frame = [0xFF, 0xD8, 1, 2, 3, 0xFF, 0xD9];
[Fact]
public void Empty_Buffer_NoFrame()
{
var splitter = new JpegFrameSplitter();
splitter.TryReadFrame(out var frame).ShouldBeFalse();
frame.ShouldBeEmpty();
}
[Fact]
public void SingleFrame_SingleChunk_ReturnsFrame()
{
var splitter = new JpegFrameSplitter();
splitter.Append(Frame);
splitter.TryReadFrame(out var frame).ShouldBeTrue();
frame.ShouldBe(Frame);
}
[Fact]
public void SingleFrame_SplitAcrossChunks_ReturnsFrame()
{
var splitter = new JpegFrameSplitter();
splitter.Append(Frame.AsSpan(0, 3));
splitter.TryReadFrame(out _).ShouldBeFalse();
splitter.Append(Frame.AsSpan(3));
splitter.TryReadFrame(out var frame).ShouldBeTrue();
frame.ShouldBe(Frame);
}
[Fact]
public void Marker_SplitAcrossChunks_ReturnsFrame()
{
// The EOI (FF D9) straddles two chunks.
var splitter = new JpegFrameSplitter();
splitter.Append([0xFF, 0xD8, 1, 2, 3, 0xFF]);
splitter.TryReadFrame(out _).ShouldBeFalse();
splitter.Append([0xD9]);
splitter.TryReadFrame(out var frame).ShouldBeTrue();
frame.ShouldBe(Frame);
}
[Fact]
public void Garbage_BeforeSof_IsIgnored()
{
var splitter = new JpegFrameSplitter();
splitter.Append([0x00, 0x11, 0x22, 0xFF, 0xD9, 0x33]); // EOI before any SOI
splitter.TryReadFrame(out _).ShouldBeFalse();
splitter.Append(Frame);
splitter.TryReadFrame(out var frame).ShouldBeTrue();
frame.ShouldBe(Frame);
}
[Fact]
public void IncompleteFrame_ThenNewSof_KeepsNewestFrame()
{
var splitter = new JpegFrameSplitter();
// Start frame A (SOI.. partial) then start frame B without finishing A.
splitter.Append([0xFF, 0xD8, 9, 9, 9, 0xFF, 0xD8, 1, 2, 3, 0xFF, 0xD9]);
splitter.TryReadFrame(out var frame).ShouldBeTrue();
frame.ShouldBe(Frame);
}
[Fact]
public void TwoFrames_InOneChunk_ReturnsBoth()
{
var splitter = new JpegFrameSplitter();
var bytes = Concat(Frame, Frame);
splitter.Append(bytes);
splitter.TryReadFrame(out var first).ShouldBeTrue();
splitter.TryReadFrame(out var second).ShouldBeTrue();
first.ShouldBe(Frame);
second.ShouldBe(Frame);
}
[Fact]
public void Frame_ThenGarbage_ThenFrame_ReturnsTwoFrames()
{
var splitter = new JpegFrameSplitter();
var bytes = Concat(Concat(Frame, [0xAA, 0xBB]), Frame);
splitter.Append(bytes);
splitter.TryReadFrame(out var first).ShouldBeTrue();
splitter.TryReadFrame(out var second).ShouldBeTrue();
first.ShouldBe(Frame);
second.ShouldBe(Frame);
}
[Fact]
public void Reset_ClearsBufferedData()
{
var splitter = new JpegFrameSplitter();
splitter.Append([0xFF, 0xD8, 1, 2]); // partial frame
splitter.Reset();
splitter.TryReadFrame(out _).ShouldBeFalse();
splitter.Append(Frame);
splitter.TryReadFrame(out var frame).ShouldBeTrue();
frame.ShouldBe(Frame);
}
[Fact]
public void LargeFrame_ExpandsBuffer_ReturnsFrame()
{
var splitter = new JpegFrameSplitter();
var frame = new byte[512 * 1024]; // > default 256KB buffer
frame[0] = 0xFF;
frame[1] = 0xD8;
frame[^2] = 0xFF;
frame[^1] = 0xD9;
splitter.Append(frame);
splitter.TryReadFrame(out var result).ShouldBeTrue();
result.Length.ShouldBe(frame.Length);
}
private static byte[] Concat(byte[] a, byte[] b)
{
var result = new byte[a.Length + b.Length];
a.CopyTo(result, 0);
b.CopyTo(result, a.Length);
return result;
}
}
@@ -0,0 +1,88 @@
using Heimdall.Agent.Services;
namespace Heimdall.Agent.Tests;
public class SceneStateTrackerTests
{
[Fact]
public void Default_IsIdle()
{
var tracker = new SceneStateTracker();
tracker.State.ShouldBe(SceneState.Idle);
}
[Fact]
public void UpdateFromAnalysis_Detections_WinsOverMotion()
{
var tracker = new SceneStateTracker();
tracker.UpdateFromAnalysis(hasDetections: true, hasMotion: false);
tracker.State.ShouldBe(SceneState.ObjectDetected);
}
[Fact]
public void UpdateFromAnalysis_MotionOnly()
{
var tracker = new SceneStateTracker();
tracker.UpdateFromAnalysis(hasDetections: false, hasMotion: true);
tracker.State.ShouldBe(SceneState.Motion);
}
[Fact]
public void UpdateFromAnalysis_NoMotionNoDetections_IsIdle()
{
var tracker = new SceneStateTracker();
tracker.UpdateFromAnalysis(hasDetections: false, hasMotion: false);
tracker.State.ShouldBe(SceneState.Idle);
}
[Fact]
public void Set_OverridesState()
{
var tracker = new SceneStateTracker();
tracker.Set(SceneState.ObjectDetected);
tracker.State.ShouldBe(SceneState.ObjectDetected);
}
}
public class FrameMotionDetectorTests
{
[Fact]
public void FirstFrame_IsBaseline_NoMotion()
{
var detector = new FrameMotionDetector();
detector.Detect([1, 2, 3, 4]).ShouldBeFalse();
}
[Fact]
public void IdenticalFrames_NoMotion()
{
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.Reset();
detector.Detect(new byte[500]).ShouldBeFalse(); // baseline again
}
}
@@ -0,0 +1,116 @@
using Heimdall.Agent.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
namespace Heimdall.Agent.Tests;
public class SnapshotPipelineServiceTests
{
private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg";
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer) CreatePipeline(
List<AgentCameraOptions>? cameras = null)
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var options = Options.Create(new AgentOptions
{
CentralUrl = "http://localhost:5000",
SiteToken = "test",
Cameras = cameras ?? [],
});
var store = new CameraConfigStore();
var streams = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>(), FfmpegNotFound);
var analyzer = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var service = new SnapshotPipelineService(
state, options, store, streams, analyzer, new SceneStateTracker(),
Substitute.For<ILogger<SnapshotPipelineService>>());
return (service, state, store, streams, analyzer);
}
[Fact]
public async Task StartStop_WithoutRegistration_StopsGracefully()
{
var (service, state, _, _, _) = CreatePipeline();
state.AgentId = Guid.Empty; // never registered
await service.StartAsync(CancellationToken.None);
var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
await service.StopAsync(cts.Token);
}
[Fact]
public async Task StartStop_WithNoCameras_DoesNotStartStreams()
{
var (service, _, _, streams, _) = CreatePipeline();
await service.StartAsync(CancellationToken.None);
try
{
await Task.Delay(200);
streams.ActiveStreamCount.ShouldBe(0);
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task StartStop_WithLocalCameras_PopulatesStoreFallback()
{
var cameras = new List<AgentCameraOptions>
{
new() { Name = "Cam 1", RtspUrl = "rtsp://cam1/stream" },
};
var (service, _, store, streams, _) = CreatePipeline(cameras);
await service.StartAsync(CancellationToken.None);
try
{
await Task.Delay(200);
// Local fallback applied to the store…
var camera = store.Cameras.ShouldHaveSingleItem();
camera.Name.ShouldBe("Cam 1");
camera.EffectiveRtspUrl.ShouldBe("rtsp://cam1/stream");
// …and capture attempted (ffmpeg missing → no active stream, no crash).
streams.ActiveStreamCount.ShouldBe(0);
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer()
{
var (service, _, _, streams, analyzer) = CreatePipeline();
await service.StartAsync(CancellationToken.None);
try
{
await streams.SnapshotChannel.Writer.WriteAsync(
new Snapshot(Guid.NewGuid(), DateTime.UtcNow, [1, 2, 3]));
var deadline = DateTime.UtcNow.AddSeconds(5);
while (service.SnapshotsProcessed == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
// The frame reached the analyzer — real call, not just a counter.
service.SnapshotsProcessed.ShouldBe(1);
analyzer.AnalyzedFrameCount.ShouldBe(1);
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task StopAsync_WithoutStart_DoesNotThrow()
{
var (service, _, _, _, _) = CreatePipeline();
await service.StopAsync(CancellationToken.None);
}
}
@@ -4,6 +4,7 @@ using Heimdall.Application.Security;
using Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Settings;
@@ -23,13 +24,15 @@ public class GetEffectiveAgentConfigHandlerTests
List<AppSetting>? appSettings = null,
List<AgentSetting>? agentSettings = null,
List<Agent>? agents = null,
List<SiteCredential>? credentials = null)
List<SiteCredential>? credentials = null,
List<Camera>? cameras = null)
{
var context = Substitute.For<IApplicationDbContext>();
context.AppSettings.Returns(MockDbSetHelper.CreateFor<AppSetting>(appSettings ?? []));
context.AgentSettings.Returns(MockDbSetHelper.CreateFor<AgentSetting>(agentSettings ?? []));
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>(agents ?? []));
context.SiteCredentials.Returns(MockDbSetHelper.CreateFor<SiteCredential>(credentials ?? []));
context.Cameras.Returns(MockDbSetHelper.CreateFor<Camera>(cameras ?? []));
Protector.Encrypt(Arg.Any<string>()).Returns(c => $"enc_{c.Arg<string>()}");
Protector.Decrypt(Arg.Any<string>()).Returns(c => (c.Arg<string>() ?? "").Replace("enc_", ""));
@@ -114,4 +117,61 @@ public class GetEffectiveAgentConfigHandlerTests
result.Data.ShouldNotBeNull();
result.Data!.ShouldNotContainKey("discovery.credentials");
}
[Fact]
public async Task Get_effective_config_should_ship_assigned_cameras()
{
var agent = new Agent(SiteId, "agent-1", "host1", "1.0.0");
agent.Register(ApiKeyHash, ApiKeyHash[..8]);
var camera = new Camera(SiteId, "Entrée", "rtsp://camera/stream1");
camera.AssignAgent(agent.Id);
camera.SetStatus(CameraStatus.Online);
camera.SetStreamTestResult("rtsp://camera/sub", "[]", 1920, 1080, 120);
var otherCamera = new Camera(SiteId, "Autre agent", "rtsp://other/stream");
otherCamera.AssignAgent(Guid.NewGuid());
var deletedCamera = new Camera(SiteId, "Supprimée", "rtsp://deleted/stream");
deletedCamera.AssignAgent(agent.Id);
deletedCamera.SoftDelete();
var context = CreateContext(agents: [agent], cameras: [camera, otherCamera, deletedCamera]);
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
var prefix = $"camera.{camera.Id}";
result.Data[prefix + ".name"].ShouldBe("Entrée");
result.Data[prefix + ".rtsp"].ShouldBe("rtsp://camera/stream1");
result.Data[prefix + ".sub_rtsp"].ShouldBe("rtsp://camera/sub");
result.Data[prefix + ".enabled"].ShouldBe("true");
// Cameras of other agents and soft-deleted cameras must not leak.
result.Data!.ShouldNotContainKey($"camera.{otherCamera.Id}.name");
result.Data.ShouldNotContainKey($"camera.{deletedCamera.Id}.name");
}
[Fact]
public async Task Get_effective_config_disabled_camera_should_be_shipped_as_disabled()
{
var agent = new Agent(SiteId, "agent-1", "host1", "1.0.0");
agent.Register(ApiKeyHash, ApiKeyHash[..8]);
var camera = new Camera(SiteId, "Cam off", "rtsp://camera/stream");
camera.AssignAgent(agent.Id);
camera.SetStatus(CameraStatus.Disabled);
var context = CreateContext(agents: [agent], cameras: [camera]);
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data[$"camera.{camera.Id}.enabled"].ShouldBe("false");
}
}