From c38d69a1e5ca4ccb95b74b229e81157382b86d89 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 11 Aug 2026 21:16:28 +0200 Subject: [PATCH] =?UTF-8?q?feat(agent):=20pipeline=20capture=20vid=C3=A9o?= =?UTF-8?q?=20=E2=80=94=20FFmpeg=20par=20cam=C3=A9ra,=20snapshots=20adapta?= =?UTF-8?q?tifs,=20frames=20=E2=86=92=20analyseur=20(Fixes=20#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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..* 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 --- src/Heimdall.Agent/AgentCameraOptions.cs | 22 ++ src/Heimdall.Agent/AgentOptions.cs | 8 + src/Heimdall.Agent/Program.cs | 8 + .../Services/AdaptiveSnapshotInterval.cs | 29 +++ .../Services/AgentCameraConfig.cs | 20 ++ .../Services/CameraConfigStore.cs | 82 ++++++++ .../Services/CameraStreamService.cs | 112 +++++++++- .../Services/ConfigReceiverService.cs | 18 +- .../Services/FrameAnalyzerService.cs | 9 + .../Services/FrameMotionDetector.cs | 39 ++++ .../Services/JpegFrameSplitter.cs | 105 ++++++++++ src/Heimdall.Agent/Services/SceneState.cs | 13 ++ .../Services/SceneStateTracker.cs | 24 +++ src/Heimdall.Agent/Services/Snapshot.cs | 4 + .../Services/SnapshotPipelineService.cs | 192 ++++++++++++++++++ .../GetEffectiveAgentConfigQuery.cs | 24 +++ .../AdaptiveSnapshotIntervalTests.cs | 56 +++++ .../CameraConfigStoreTests.cs | 102 ++++++++++ .../CameraStreamServiceTests.cs | 58 ++++++ .../ConfigReceiverServiceTests.cs | 59 +++++- .../JpegFrameSplitterTests.cs | 127 ++++++++++++ .../SceneStateTrackerTests.cs | 88 ++++++++ .../SnapshotPipelineServiceTests.cs | 116 +++++++++++ .../GetEffectiveAgentConfigHandlerTests.cs | 62 +++++- 24 files changed, 1365 insertions(+), 12 deletions(-) create mode 100644 src/Heimdall.Agent/AgentCameraOptions.cs create mode 100644 src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs create mode 100644 src/Heimdall.Agent/Services/AgentCameraConfig.cs create mode 100644 src/Heimdall.Agent/Services/CameraConfigStore.cs create mode 100644 src/Heimdall.Agent/Services/FrameMotionDetector.cs create mode 100644 src/Heimdall.Agent/Services/JpegFrameSplitter.cs create mode 100644 src/Heimdall.Agent/Services/SceneState.cs create mode 100644 src/Heimdall.Agent/Services/SceneStateTracker.cs create mode 100644 src/Heimdall.Agent/Services/Snapshot.cs create mode 100644 src/Heimdall.Agent/Services/SnapshotPipelineService.cs create mode 100644 tests/Heimdall.Agent.Tests/AdaptiveSnapshotIntervalTests.cs create mode 100644 tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs create mode 100644 tests/Heimdall.Agent.Tests/JpegFrameSplitterTests.cs create mode 100644 tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs create mode 100644 tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs diff --git a/src/Heimdall.Agent/AgentCameraOptions.cs b/src/Heimdall.Agent/AgentCameraOptions.cs new file mode 100644 index 0000000..7ef43a1 --- /dev/null +++ b/src/Heimdall.Agent/AgentCameraOptions.cs @@ -0,0 +1,22 @@ +using System.ComponentModel.DataAnnotations; + +namespace Heimdall.Agent; + +/// +/// A camera assignment declared in the local agent configuration +/// (Agent:Cameras). Used only as a fallback before the Central camera +/// list is received through the settings pipeline. +/// +public sealed class AgentCameraOptions +{ + /// Display name of the camera. + public string Name { get; init; } = string.Empty; + + /// Primary RTSP URL of the camera. + [Required, Url] + public string RtspUrl { get; init; } = string.Empty; + + /// Secondary / sub-stream RTSP URL (lower resolution, preferred for AI). + [Url] + public string? SubRtspUrl { get; init; } +} diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs index 524f059..2063cce 100644 --- a/src/Heimdall.Agent/AgentOptions.cs +++ b/src/Heimdall.Agent/AgentOptions.cs @@ -44,4 +44,12 @@ public sealed class AgentOptions /// Agent software version reported to Central. public string Version { get; init; } = "1.0.0"; + + /// + /// 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. + /// + public List Cameras { get; init; } = []; } diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 6361d7c..90914f5 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -71,6 +71,14 @@ builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); +// Video capture pipeline (ticket #1): FFmpeg capture per assigned camera, +// bounded snapshot channel, adaptive interval, frames → FrameAnalyzerService. +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); + // Log capture & upload to Central (ticket #50) builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs b/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs new file mode 100644 index 0000000..4d6f710 --- /dev/null +++ b/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs @@ -0,0 +1,29 @@ +namespace Heimdall.Agent.Services; + +/// +/// 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%. +/// +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); + } +} diff --git a/src/Heimdall.Agent/Services/AgentCameraConfig.cs b/src/Heimdall.Agent/Services/AgentCameraConfig.cs new file mode 100644 index 0000000..13dc713 --- /dev/null +++ b/src/Heimdall.Agent/Services/AgentCameraConfig.cs @@ -0,0 +1,20 @@ +namespace Heimdall.Agent.Services; + +/// +/// Immutable camera assignment consumed by the capture pipeline. Built either +/// from the Central settings keys (camera.<id>.name|rtsp|sub_rtsp|enabled) +/// or from the local Agent:Cameras fallback. +/// +public sealed record AgentCameraConfig( + Guid CameraId, + string Name, + string RtspUrl, + string? SubRtspUrl, + bool Enabled) +{ + /// + /// URL used for AI capture: the low-res sub-stream when available, + /// otherwise the primary stream. + /// + public string EffectiveRtspUrl => !string.IsNullOrWhiteSpace(SubRtspUrl) ? SubRtspUrl : RtspUrl; +} diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs new file mode 100644 index 0000000..d093e7a --- /dev/null +++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs @@ -0,0 +1,82 @@ +using System.Collections.Concurrent; + +namespace Heimdall.Agent.Services; + +/// +/// Holds the camera assignments the agent must capture. The Central is the +/// source of truth: cameras are shipped as flat camera.<id>.name|rtsp|sub_rtsp|enabled +/// keys through the settings pipeline (full reload + live SettingChanged). +/// A local list from AgentOptions.Cameras serves as a fallback until +/// the first Central config is received. +/// +public sealed class CameraConfigStore +{ + private readonly ConcurrentDictionary _central = new(); + private IReadOnlyList _localFallback = []; + private volatile bool _centralReceived; + + /// Raised whenever the effective camera list may have changed. + public event EventHandler? Changed; + + /// Sets the local fallback list (used until Central config arrives). + public void SetLocalFallback(IReadOnlyList cameras) + { + _localFallback = cameras; + RaiseChanged(); + } + + /// + /// Applies a single camera.<id>.<field> setting key received from + /// the Central. Any such key marks the Central list as authoritative. + /// + public void ApplyCameraSetting(string key, string value) + { + // camera.. + 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(); + } + + /// + /// Marks the Central config as received; the local fallback is no longer + /// used, even if the Central list is empty. + /// + public void MarkCentralReceived() + { + if (_centralReceived) + return; + _centralReceived = true; + RaiseChanged(); + } + + /// Effective camera assignments: Central list, or local fallback before that. + public IReadOnlyList 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); +} diff --git a/src/Heimdall.Agent/Services/CameraStreamService.cs b/src/Heimdall.Agent/Services/CameraStreamService.cs index 536243a..a91614a 100644 --- a/src/Heimdall.Agent/Services/CameraStreamService.cs +++ b/src/Heimdall.Agent/Services/CameraStreamService.cs @@ -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; /// /// 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 > 80%) and queues them on a bounded channel for the analysis +/// pipeline. Queue overflow drops the oldest frame (backpressure) and is +/// surfaced through and a rate-limited log. /// public sealed class CameraStreamService : IDisposable { + /// Max queued snapshots before oldest frames are dropped (MASTER_SPEC Phase 15: >100). + public const int MaxQueueSize = 100; + private readonly ILogger _logger; + private readonly string _ffmpegPath; + private readonly SceneStateTracker _sceneState; + private readonly SystemMetricsProvider _metrics; + private readonly AdaptiveSnapshotInterval _snapshotInterval; private readonly ConcurrentDictionary _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; + + /// + /// Bounded channel receiving sampled snapshots. Full mode DropOldest — + /// when the queue is full the oldest frame is dropped (backpressure). + /// + public Channel SnapshotChannel { get; } = Channel.CreateBounded( + new BoundedChannelOptions(MaxQueueSize) + { + FullMode = BoundedChannelFullMode.DropOldest, + SingleReader = true, + SingleWriter = false, + }); + + /// Total number of frames dropped because the queue was full. + public long DroppedSnapshotCount => Interlocked.Read(ref _droppedSnapshots); + /// /// Creates a new CameraStreamService. /// @@ -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. /// - public CameraStreamService(ILogger logger, string ffmpegPath = "ffmpeg") + /// Scene state tracker (defaults to a private one). + /// System metrics provider for CPU-based interval throttling. + /// Adaptive interval calculator (defaults to the spec values). + public CameraStreamService( + ILogger 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; - /// Start streaming from a camera. Launches FFmpeg in the background. public async Task 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; } + /// Stops every active stream (agent shutdown). + public async Task StopAllAsync() + { + foreach (var cameraId in _sessions.Keys.ToArray()) + await StopStreamAsync(cameraId); + } + /// Number of currently active streams. public int ActiveStreamCount => _sessions.Count; + /// IDs of the cameras with an active stream. + public IReadOnlyList ActiveCameraIds => _sessions.Keys.ToArray(); + + /// Whether a stream is currently active for the given camera. + public bool IsStreamActive(Guid cameraId) => _sessions.ContainsKey(cameraId); + private async Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct) { var buffer = ArrayPool.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; diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index 53698b1..973a3d9 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -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; /// @@ -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) { diff --git a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs index 59c8f31..67fae43 100644 --- a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs +++ b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs @@ -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; + + /// Number of frames actually handed to the analyzer (real calls, including passthrough). + public long AnalyzedFrameCount => Interlocked.Read(ref _analyzedFrameCount); + public FrameAnalyzerService(ILogger logger) { _logger = logger; @@ -88,6 +93,8 @@ public sealed class FrameAnalyzerService : IDisposable /// public async Task AnalyzeFrameAsync(byte[] jpegData, CancellationToken ct = default) { + Interlocked.Increment(ref _analyzedFrameCount); + if (!_modelLoaded) return null; @@ -110,6 +117,8 @@ public sealed class FrameAnalyzerService : IDisposable /// public FrameAnalysisResult? AnalyzeFrame(byte[] jpegData) { + Interlocked.Increment(ref _analyzedFrameCount); + if (!_modelLoaded) return null; var sw = System.Diagnostics.Stopwatch.StartNew(); diff --git a/src/Heimdall.Agent/Services/FrameMotionDetector.cs b/src/Heimdall.Agent/Services/FrameMotionDetector.cs new file mode 100644 index 0000000..61bc72a --- /dev/null +++ b/src/Heimdall.Agent/Services/FrameMotionDetector.cs @@ -0,0 +1,39 @@ +namespace Heimdall.Agent.Services; + +/// +/// Lightweight frame-level motion proxy: compares the compressed size of +/// consecutive JPEG frames — a large relative change usually means scene +/// activity. Deliberately cheap (no JPEG decoding) and clearly documented as +/// a placeholder for the real pixel-diff Motion Gate of Phase 16 +/// (MASTER_SPECIFICATION). One instance per camera. +/// +public sealed class FrameMotionDetector +{ + private readonly double _thresholdPercent; + private long _lastFrameLength; + + public FrameMotionDetector(double thresholdPercent = 8.0) + { + _thresholdPercent = thresholdPercent; + } + + /// + /// Feeds the next frame and reports whether the scene changed enough to + /// count as motion. The first frame is always a baseline (no motion). + /// + public bool Detect(byte[] jpegFrame) + { + 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; +} diff --git a/src/Heimdall.Agent/Services/JpegFrameSplitter.cs b/src/Heimdall.Agent/Services/JpegFrameSplitter.cs new file mode 100644 index 0000000..4e8755f --- /dev/null +++ b/src/Heimdall.Agent/Services/JpegFrameSplitter.cs @@ -0,0 +1,105 @@ +namespace Heimdall.Agent.Services; + +/// +/// Splits a continuous MJPEG pipe (FFmpeg image2pipe) 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. +/// +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; + + /// Appends the next chunk read from the pipe. + public void Append(ReadOnlySpan chunk) + { + EnsureCapacity(_length + chunk.Length); + chunk.CopyTo(_data.AsSpan(_length)); + _length += chunk.Length; + Scan(); + } + + /// + /// Returns the next complete JPEG frame (SOI..EOI inclusive) and removes + /// it from the buffer, or false when no complete frame is available yet. + /// + 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); + } +} diff --git a/src/Heimdall.Agent/Services/SceneState.cs b/src/Heimdall.Agent/Services/SceneState.cs new file mode 100644 index 0000000..f2790fe --- /dev/null +++ b/src/Heimdall.Agent/Services/SceneState.cs @@ -0,0 +1,13 @@ +namespace Heimdall.Agent.Services; + +/// +/// 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. +/// +public enum SceneState +{ + Idle = 0, + Motion = 1, + ObjectDetected = 2, +} diff --git a/src/Heimdall.Agent/Services/SceneStateTracker.cs b/src/Heimdall.Agent/Services/SceneStateTracker.cs new file mode 100644 index 0000000..e16922e --- /dev/null +++ b/src/Heimdall.Agent/Services/SceneStateTracker.cs @@ -0,0 +1,24 @@ +namespace Heimdall.Agent.Services; + +/// +/// 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. +/// +public sealed class SceneStateTracker +{ + private volatile SceneState _state = SceneState.Idle; + + public SceneState State => _state; + + public void Set(SceneState state) => _state = state; + + /// + /// Updates the state from one analyzed frame: any detection wins over + /// motion, otherwise the motion proxy decides between Motion and Idle. + /// + public void UpdateFromAnalysis(bool hasDetections, bool hasMotion) + { + _state = hasDetections ? SceneState.ObjectDetected : hasMotion ? SceneState.Motion : SceneState.Idle; + } +} diff --git a/src/Heimdall.Agent/Services/Snapshot.cs b/src/Heimdall.Agent/Services/Snapshot.cs new file mode 100644 index 0000000..950c09f --- /dev/null +++ b/src/Heimdall.Agent/Services/Snapshot.cs @@ -0,0 +1,4 @@ +namespace Heimdall.Agent.Services; + +/// A JPEG frame captured from a camera, queued for analysis. +public sealed record Snapshot(Guid CameraId, DateTime TimestampUtc, byte[] JpegData); diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs new file mode 100644 index 0000000..7e6453d --- /dev/null +++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs @@ -0,0 +1,192 @@ +using System.Collections.Concurrent; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent.Services; + +/// +/// 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 +/// and updating the scene state that +/// drives the adaptive snapshot interval. +/// +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 _logger; + private readonly ConcurrentDictionary _motionDetectors = new(); + + private long _snapshotsProcessed; + private long _analysisFailures; + private bool _storeSubscribed; + + public SnapshotPipelineService( + AgentState state, + IOptions options, + CameraConfigStore cameraStore, + CameraStreamService streams, + FrameAnalyzerService analyzer, + SceneStateTracker sceneState, + ILogger logger) + { + _state = state; + _options = options.Value; + _cameraStore = cameraStore; + _streams = streams; + _analyzer = analyzer; + _sceneState = sceneState; + _logger = logger; + } + + /// Number of snapshots handed to the analyzer (real calls). + public long SnapshotsProcessed => Interlocked.Read(ref _snapshotsProcessed); + + /// Number of frames that failed analysis (analyzer exceptions). + 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 BuildLocalCameras() + { + var list = new List(); + 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; + } + + /// Stable ID for a locally-declared camera (no Central ID yet). + 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)); + } +} diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs index ee3ddf4..928e809 100644 --- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs +++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs @@ -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..*` 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>.Success(config); } } diff --git a/tests/Heimdall.Agent.Tests/AdaptiveSnapshotIntervalTests.cs b/tests/Heimdall.Agent.Tests/AdaptiveSnapshotIntervalTests.cs new file mode 100644 index 0000000..a14e8fe --- /dev/null +++ b/tests/Heimdall.Agent.Tests/AdaptiveSnapshotIntervalTests.cs @@ -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)); + } +} diff --git a/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs b/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs new file mode 100644 index 0000000..8657142 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs @@ -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(); + } +} diff --git a/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs index 208ccea..f9ab642 100644 --- a/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs @@ -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>(), + FfmpegNotFound, + new SceneStateTracker(), + new SystemMetricsProvider(), + new AdaptiveSnapshotInterval()); + service.ShouldNotBeNull(); + } + private static CameraStreamService CreateService() => new(Substitute.For>(), FfmpegNotFound); } diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index 1170fee..14fea82 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -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(); 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()); } /// @@ -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(); + 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() { diff --git a/tests/Heimdall.Agent.Tests/JpegFrameSplitterTests.cs b/tests/Heimdall.Agent.Tests/JpegFrameSplitterTests.cs new file mode 100644 index 0000000..f33b72f --- /dev/null +++ b/tests/Heimdall.Agent.Tests/JpegFrameSplitterTests.cs @@ -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; + } +} diff --git a/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs b/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs new file mode 100644 index 0000000..cb8b675 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs @@ -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 + } +} diff --git a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs new file mode 100644 index 0000000..f520079 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs @@ -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? 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>(), FfmpegNotFound); + var analyzer = new FrameAnalyzerService(Substitute.For>()); + var service = new SnapshotPipelineService( + state, options, store, streams, analyzer, new SceneStateTracker(), + Substitute.For>()); + 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 + { + 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); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs index 0e09a7a..60b14f8 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs @@ -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? appSettings = null, List? agentSettings = null, List? agents = null, - List? credentials = null) + List? credentials = null, + List? cameras = null) { var context = Substitute.For(); context.AppSettings.Returns(MockDbSetHelper.CreateFor(appSettings ?? [])); context.AgentSettings.Returns(MockDbSetHelper.CreateFor(agentSettings ?? [])); context.Agents.Returns(MockDbSetHelper.CreateFor(agents ?? [])); context.SiteCredentials.Returns(MockDbSetHelper.CreateFor(credentials ?? [])); + context.Cameras.Returns(MockDbSetHelper.CreateFor(cameras ?? [])); Protector.Encrypt(Arg.Any()).Returns(c => $"enc_{c.Arg()}"); Protector.Decrypt(Arg.Any()).Returns(c => (c.Arg() ?? "").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"); + } }