2026-07-19 19:58:45 +00:00
|
|
|
using System.Buffers;
|
2026-07-19 13:43:48 +00:00
|
|
|
using System.Collections.Concurrent;
|
2026-07-19 12:55:05 +00:00
|
|
|
using System.Diagnostics;
|
2026-08-11 21:16:28 +02:00
|
|
|
using System.Threading.Channels;
|
2026-07-19 12:55:05 +00:00
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Agent.Services;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Manages RTSP stream connections for each assigned camera.
|
2026-08-11 21:16:28 +02:00
|
|
|
/// 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 <see cref="DroppedSnapshotCount"/> and a rate-limited log.
|
2026-07-19 12:55:05 +00:00
|
|
|
/// </summary>
|
|
|
|
|
public sealed class CameraStreamService : IDisposable
|
|
|
|
|
{
|
2026-08-11 21:16:28 +02:00
|
|
|
/// <summary>Max queued snapshots before oldest frames are dropped (MASTER_SPEC Phase 15: >100).</summary>
|
|
|
|
|
public const int MaxQueueSize = 100;
|
|
|
|
|
|
2026-07-19 12:55:05 +00:00
|
|
|
private readonly ILogger<CameraStreamService> _logger;
|
2026-08-11 21:16:28 +02:00
|
|
|
private readonly string _ffmpegPath;
|
|
|
|
|
private readonly SceneStateTracker _sceneState;
|
|
|
|
|
private readonly SystemMetricsProvider _metrics;
|
|
|
|
|
private readonly AdaptiveSnapshotInterval _snapshotInterval;
|
2026-07-19 13:43:48 +00:00
|
|
|
private readonly ConcurrentDictionary<Guid, StreamSession> _sessions = new();
|
2026-07-19 12:55:05 +00:00
|
|
|
private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg
|
|
|
|
|
|
2026-08-11 21:16:28 +02:00
|
|
|
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);
|
|
|
|
|
|
2026-07-24 06:38:15 +00:00
|
|
|
/// <summary>
|
|
|
|
|
/// Creates a new CameraStreamService.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="logger">Logger instance.</param>
|
|
|
|
|
/// <param name="ffmpegPath">
|
|
|
|
|
/// 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>
|
2026-08-11 21:16:28 +02:00
|
|
|
/// <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)
|
2026-07-19 12:55:05 +00:00
|
|
|
{
|
|
|
|
|
_logger = logger;
|
2026-07-24 06:38:15 +00:00
|
|
|
_ffmpegPath = ffmpegPath;
|
2026-08-11 21:16:28 +02:00
|
|
|
_sceneState = sceneState ?? new SceneStateTracker();
|
|
|
|
|
_metrics = metrics ?? new SystemMetricsProvider();
|
|
|
|
|
_snapshotInterval = snapshotInterval ?? new AdaptiveSnapshotInterval();
|
2026-07-19 12:55:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Start streaming from a camera. Launches FFmpeg in the background.</summary>
|
|
|
|
|
public async Task<bool> StartStreamAsync(Guid cameraId, string rtspUrl, CancellationToken ct = default)
|
|
|
|
|
{
|
2026-08-11 21:16:28 +02:00
|
|
|
if (string.IsNullOrWhiteSpace(rtspUrl) || !Uri.TryCreate(rtspUrl, UriKind.Absolute, out _))
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning("Invalid or empty RTSP URL for camera {CameraId}", cameraId);
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-19 12:55:05 +00:00
|
|
|
if (_sessions.ContainsKey(cameraId))
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning("Stream already active for camera {CameraId}", cameraId);
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await _throttle.WaitAsync(ct);
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var psi = new ProcessStartInfo
|
|
|
|
|
{
|
2026-07-24 06:38:15 +00:00
|
|
|
FileName = _ffmpegPath,
|
2026-07-19 12:55:05 +00:00
|
|
|
RedirectStandardOutput = true,
|
|
|
|
|
RedirectStandardError = true,
|
|
|
|
|
UseShellExecute = false,
|
|
|
|
|
CreateNoWindow = true,
|
|
|
|
|
};
|
|
|
|
|
|
2026-07-20 09:50:43 +00:00
|
|
|
// Use ArgumentList to prevent argument injection via rtspUrl
|
|
|
|
|
psi.ArgumentList.Add("-rtsp_transport");
|
|
|
|
|
psi.ArgumentList.Add("tcp");
|
|
|
|
|
psi.ArgumentList.Add("-i");
|
|
|
|
|
psi.ArgumentList.Add(rtspUrl);
|
|
|
|
|
psi.ArgumentList.Add("-f");
|
|
|
|
|
psi.ArgumentList.Add("image2pipe");
|
|
|
|
|
psi.ArgumentList.Add("-vcodec");
|
|
|
|
|
psi.ArgumentList.Add("mjpeg");
|
|
|
|
|
psi.ArgumentList.Add("-q:v");
|
|
|
|
|
psi.ArgumentList.Add("3");
|
|
|
|
|
psi.ArgumentList.Add("-update");
|
|
|
|
|
psi.ArgumentList.Add("1");
|
|
|
|
|
psi.ArgumentList.Add("-");
|
|
|
|
|
|
2026-07-19 12:55:05 +00:00
|
|
|
var process = new Process { StartInfo = psi };
|
|
|
|
|
process.Start();
|
|
|
|
|
|
|
|
|
|
var session = new StreamSession(cameraId, rtspUrl, process);
|
|
|
|
|
_sessions[cameraId] = session;
|
|
|
|
|
|
|
|
|
|
_logger.LogInformation("Stream started for camera {CameraId}: {Url}", cameraId, rtspUrl);
|
|
|
|
|
|
|
|
|
|
// Background read loop
|
|
|
|
|
_ = Task.Run(() => ReadFramesLoop(cameraId, session, ct), ct);
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogError(ex, "Failed to start stream for camera {CameraId}", cameraId);
|
|
|
|
|
_throttle.Release();
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Stop streaming from a camera.</summary>
|
|
|
|
|
public Task StopStreamAsync(Guid cameraId)
|
|
|
|
|
{
|
2026-07-19 13:43:48 +00:00
|
|
|
if (_sessions.TryRemove(cameraId, out var session))
|
2026-07-19 12:55:05 +00:00
|
|
|
{
|
|
|
|
|
session.Cancel();
|
2026-07-20 09:50:43 +00:00
|
|
|
// Mark semaphore as released BEFORE releasing, so CleanupSession's
|
|
|
|
|
// finally block does NOT double-release (see SemaphoreReleased flag).
|
|
|
|
|
session.SemaphoreReleased = true;
|
2026-07-19 12:55:05 +00:00
|
|
|
_throttle.Release();
|
|
|
|
|
_logger.LogInformation("Stream stopped for camera {CameraId}", cameraId);
|
|
|
|
|
}
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 21:16:28 +02:00
|
|
|
/// <summary>Stops every active stream (agent shutdown).</summary>
|
|
|
|
|
public async Task StopAllAsync()
|
|
|
|
|
{
|
|
|
|
|
foreach (var cameraId in _sessions.Keys.ToArray())
|
|
|
|
|
await StopStreamAsync(cameraId);
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-19 12:55:05 +00:00
|
|
|
/// <summary>Number of currently active streams.</summary>
|
|
|
|
|
public int ActiveStreamCount => _sessions.Count;
|
|
|
|
|
|
2026-08-11 21:16:28 +02:00
|
|
|
/// <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);
|
|
|
|
|
|
2026-07-19 19:58:45 +00:00
|
|
|
private async Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct)
|
2026-07-19 12:55:05 +00:00
|
|
|
{
|
2026-07-19 19:58:45 +00:00
|
|
|
var buffer = ArrayPool<byte>.Shared.Rent(256 * 1024);
|
2026-07-19 12:55:05 +00:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var stream = session.Process.StandardOutput.BaseStream;
|
|
|
|
|
|
|
|
|
|
while (!ct.IsCancellationRequested && !session.IsCancelled && !session.Process.HasExited)
|
|
|
|
|
{
|
2026-07-19 19:58:45 +00:00
|
|
|
var bytesRead = await stream.ReadAsync(buffer.AsMemory(), ct);
|
2026-07-19 12:55:05 +00:00
|
|
|
if (bytesRead == 0) break;
|
|
|
|
|
|
|
|
|
|
Interlocked.Increment(ref session.FrameCount);
|
2026-08-11 21:16:28 +02:00
|
|
|
session.Splitter.Append(buffer.AsSpan(0, bytesRead));
|
|
|
|
|
|
|
|
|
|
while (session.Splitter.TryReadFrame(out var frame))
|
|
|
|
|
MaybeEmitSnapshot(cameraId, session, frame);
|
2026-07-19 12:55:05 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning(ex, "Frame read loop ended for camera {CameraId}", cameraId);
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
2026-07-19 19:58:45 +00:00
|
|
|
ArrayPool<byte>.Shared.Return(buffer);
|
2026-07-19 12:55:05 +00:00
|
|
|
CleanupSession(cameraId, session);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 21:16:28 +02:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-19 12:55:05 +00:00
|
|
|
private void CleanupSession(Guid cameraId, StreamSession session)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
if (!session.Process.HasExited)
|
|
|
|
|
{
|
|
|
|
|
session.Process.Kill(entireProcessTree: true);
|
|
|
|
|
session.Process.WaitForExit(2000);
|
|
|
|
|
}
|
|
|
|
|
session.Process.Dispose();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning(ex, "Cleanup error for camera {CameraId}", cameraId);
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
2026-07-19 13:43:48 +00:00
|
|
|
if (!session.SemaphoreReleased)
|
|
|
|
|
{
|
|
|
|
|
session.SemaphoreReleased = true;
|
|
|
|
|
_throttle.Release();
|
|
|
|
|
}
|
|
|
|
|
_sessions.TryRemove(cameraId, out _);
|
2026-07-19 12:55:05 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Dispose()
|
|
|
|
|
{
|
|
|
|
|
foreach (var session in _sessions.Values)
|
|
|
|
|
{
|
|
|
|
|
session.Cancel();
|
|
|
|
|
session.Process?.Dispose();
|
|
|
|
|
}
|
|
|
|
|
_sessions.Clear();
|
2026-08-11 21:16:28 +02:00
|
|
|
SnapshotChannel.Writer.TryComplete();
|
2026-07-19 12:55:05 +00:00
|
|
|
_throttle.Dispose();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private sealed class StreamSession(Guid cameraId, string rtspUrl, Process process)
|
|
|
|
|
{
|
|
|
|
|
public Guid CameraId { get; } = cameraId;
|
|
|
|
|
public string RtspUrl { get; } = rtspUrl;
|
|
|
|
|
public Process Process { get; } = process;
|
|
|
|
|
public long FrameCount;
|
2026-07-19 13:43:48 +00:00
|
|
|
public bool SemaphoreReleased;
|
2026-08-11 21:16:28 +02:00
|
|
|
public JpegFrameSplitter Splitter { get; } = new();
|
|
|
|
|
public DateTime LastSnapshotAt { get; set; } = DateTime.MinValue;
|
2026-07-19 12:55:05 +00:00
|
|
|
private volatile bool _cancelled;
|
|
|
|
|
public bool IsCancelled => _cancelled;
|
|
|
|
|
public void Cancel() => _cancelled = true;
|
|
|
|
|
}
|
|
|
|
|
}
|