using System.Buffers; using System.Collections.Concurrent; using System.Diagnostics; using System.Threading.Channels; using Heimdall.Application.Metrics; using Microsoft.Extensions.Logging; namespace Heimdall.Agent.Services; /// /// 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 > 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 readonly ConcurrentDictionary _profiles = new(); public void SetDetectionProfile(Guid cameraId, Heimdall.Application.DTOs.DetectionProfileDto profile) => _profiles[cameraId] = profile; 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.Wait, 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. /// /// 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. /// /// 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(); } /// 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); 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; // FFmpeg can block once its stderr pipe fills. Drain it independently // from stdout; do not log its contents because diagnostics may include // the RTSP URL (and credentials). _ = DrainStandardErrorAsync(cameraId, process); _logger.LogInformation("Stream started for camera {CameraId}", cameraId); // Background read loop _ = Task.Run(() => ReadFramesLoop(cameraId, session, ct), ct); return true; } catch (Exception ex) { _logger.LogError("Failed to start stream for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name); _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; } /// 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); 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("Frame read loop ended for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name); } finally { ArrayPool.Shared.Return(buffer); CleanupSession(cameraId, session); } } private async Task DrainStandardErrorAsync(Guid cameraId, Process process) { var buffer = new char[2048]; try { while (await process.StandardError.ReadAsync(buffer.AsMemory()) > 0) { } } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogDebug("FFmpeg diagnostic stream ended for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name); } } private void MaybeEmitSnapshot(Guid cameraId, StreamSession session, byte[] frame) { var now = DateTime.UtcNow; var interval = _snapshotInterval.GetInterval(_sceneState.State, GetCpuPercent(), _profiles.GetValueOrDefault(cameraId)); // Update snapshot interval metric (spec 13.1) HeimdallMetrics.SetSnapshotInterval(interval); 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} — new frame rejected (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("Cleanup error for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name); } 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; } }