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

158 lines
5.1 KiB
C#
Raw Normal View History

using System.Collections.Concurrent;
using System.Diagnostics;
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.
/// </summary>
public sealed class CameraStreamService : IDisposable
{
private readonly ILogger<CameraStreamService> _logger;
private readonly ConcurrentDictionary<Guid, StreamSession> _sessions = new();
private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg
public CameraStreamService(ILogger<CameraStreamService> logger)
{
_logger = logger;
}
/// <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 (_sessions.ContainsKey(cameraId))
{
_logger.LogWarning("Stream already active for camera {CameraId}", cameraId);
return false;
}
await _throttle.WaitAsync(ct);
try
{
var psi = new ProcessStartInfo
{
FileName = "ffmpeg",
Arguments = $"-rtsp_transport tcp -i \"{rtspUrl}\" -f image2pipe -vcodec mjpeg -q:v 3 -update 1 -",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
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();
_throttle.Release();
_logger.LogInformation("Stream stopped for camera {CameraId}", cameraId);
}
return Task.CompletedTask;
}
/// <summary>Number of currently active streams.</summary>
public int ActiveStreamCount => _sessions.Count;
private Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct)
{
try
{
var buffer = new byte[256 * 1024]; // 256KB buffer
var stream = session.Process.StandardOutput.BaseStream;
while (!ct.IsCancellationRequested && !session.IsCancelled && !session.Process.HasExited)
{
var bytesRead = stream.Read(buffer, 0, buffer.Length);
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);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Frame read loop ended for camera {CameraId}", cameraId);
}
finally
{
CleanupSession(cameraId, session);
}
return Task.CompletedTask;
}
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();
_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;
private volatile bool _cancelled;
public bool IsCancelled => _cancelled;
public void Cancel() => _cancelled = true;
}
}