Files
Heimdall/src/Heimdall.Agent/Services/CameraStreamService.cs
T

284 lines
11 KiB
C#
Raw Normal View History

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 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>
/// <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>
/// <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();
}
/// <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);
return false;
}
await _throttle.WaitAsync(ct);
try
{
var psi = new ProcessStartInfo
{
FileName = _ffmpegPath,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
// 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("-");
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)
{
if (_sessions.TryRemove(cameraId, out var session))
{
session.Cancel();
// Mark semaphore as released BEFORE releasing, so CleanupSession's
// finally block does NOT double-release (see SemaphoreReleased flag).
session.SemaphoreReleased = true;
_throttle.Release();
_logger.LogInformation("Stream stopped for camera {CameraId}", cameraId);
}
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);
try
{
var stream = session.Process.StandardOutput.BaseStream;
while (!ct.IsCancellationRequested && !session.IsCancelled && !session.Process.HasExited)
{
var bytesRead = await stream.ReadAsync(buffer.AsMemory(), ct);
if (bytesRead == 0) break;
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)
{
_logger.LogWarning(ex, "Frame read loop ended for camera {CameraId}", cameraId);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
CleanupSession(cameraId, session);
}
}
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
{
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
{
if (!session.SemaphoreReleased)
{
session.SemaphoreReleased = true;
_throttle.Release();
}
_sessions.TryRemove(cameraId, out _);
}
}
public void Dispose()
{
foreach (var session in _sessions.Values)
{
session.Cancel();
session.Process?.Dispose();
}
_sessions.Clear();
SnapshotChannel.Writer.TryComplete();
_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;
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;
}
}