using System.Buffers; using System.Collections.Concurrent; using System.Diagnostics; 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. /// public sealed class CameraStreamService : IDisposable { private readonly ILogger _logger; private readonly ConcurrentDictionary _sessions = new(); private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg /// /// Creates a new CameraStreamService. /// /// Logger instance. /// /// 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") { _logger = logger; _ffmpegPath = ffmpegPath; } 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 (_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; } } /// Stop streaming from a camera. 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; } /// Number of currently active streams. public int ActiveStreamCount => _sessions.Count; private async Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct) { var buffer = ArrayPool.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; // 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 { ArrayPool.Shared.Return(buffer); CleanupSession(cameraId, session); } } 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; } }