using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.Globalization; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using Heimdall.Application.DTOs; using Microsoft.Extensions.Logging; namespace Heimdall.Infrastructure.Services.Discovery; /// /// Stream testing service. /// Connects to RTSP/HTTP stream URLs, extracts codecs and resolution, /// measures latency, and captures key frames as screenshots. /// Uses raw TCP connections for RTSP and HttpClient for HTTP streams. /// public sealed partial class StreamTesterService { private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; private readonly ConcurrentDictionary _sessions = new(); private static readonly TimeSpan RtspTimeout = TimeSpan.FromSeconds(5); private static readonly TimeSpan HttpTimeout = TimeSpan.FromSeconds(10); private static readonly TimeSpan SessionTtl = TimeSpan.FromMinutes(10); private const int MaxConcurrentTests = 20; public StreamTesterService(IHttpClientFactory httpClientFactory, ILogger logger) { _httpClientFactory = httpClientFactory; _logger = logger; } /// Create a new stream test session and start testing in background. public async Task CreateSessionAsync(StreamTestRequest request, CancellationToken ct = default) { var sessionId = Guid.NewGuid(); var session = new ActiveSession(request.Streams.Length); _sessions[sessionId] = session; _logger.LogInformation( "Stream test session {SessionId} created with {Count} URLs", sessionId, request.Streams.Length); _ = Task.Run(() => RunTestsAsync(sessionId, request, session, ct), CancellationToken.None) .ContinueWith(t => { if (t.IsFaulted) _logger.LogError(t.Exception, "Stream test session {SessionId} crashed", sessionId); }, TaskContinuationOptions.OnlyOnFaulted); return MapSession(sessionId, session); } /// Get current state of a test session. #pragma warning disable CA1822 // Member does not access instance data public Task GetSessionAsync(Guid sessionId, CancellationToken ct = default) #pragma warning restore CA1822 { return _sessions.TryGetValue(sessionId, out var session) ? Task.FromResult(MapSession(sessionId, session)) : Task.FromResult(null); } /// Cancel a running test session. public Task CancelSessionAsync(Guid sessionId, CancellationToken ct = default) { if (_sessions.TryGetValue(sessionId, out var session)) { session.Cancel(); _logger.LogInformation("Stream test session {SessionId} cancelled", sessionId); } return Task.CompletedTask; } /// /// Get the captured screenshot (raw JPEG bytes) for a session result index. /// Screenshots are captured live for alive streams; a camera that does not /// answer has no screenshot (null, no error). /// public Task GetScreenshotAsync(Guid sessionId, int index, CancellationToken ct = default) { if (!_sessions.TryGetValue(sessionId, out var session)) return Task.FromResult(null); return Task.FromResult(session.GetScreenshot(index)); } private async Task RunTestsAsync(Guid sessionId, StreamTestRequest request, ActiveSession session, CancellationToken ct) { try { using var throttler = new SemaphoreSlim(MaxConcurrentTests); var tasks = new List(); foreach (var url in request.Streams) { if (session.IsCancelled) break; await throttler.WaitAsync(ct).ConfigureAwait(false); var urlCopy = url; tasks.Add(Task.Run(async () => { try { var result = await TestSingleUrlAsync(urlCopy, ct).ConfigureAwait(false); session.AddResult(result); } catch (Exception ex) { _logger.LogWarning(ex, "Stream test failed for {Url}", urlCopy); session.AddResult(new Application.DTOs.StreamTestResult( urlCopy, [], 0, 0, 0, null, false)); } finally { throttler.Release(); } }, ct)); } await Task.WhenAll(tasks).ConfigureAwait(false); session.MarkDone(); _logger.LogInformation( "Stream test session {SessionId} completed: {Alive}/{Total} alive", sessionId, session.AliveCount, request.Streams.Length); } catch (Exception ex) { _logger.LogError(ex, "Stream test session {SessionId} failed", sessionId); session.MarkDone(); } finally { // Schedule cleanup regardless of success/failure _ = Task.Run(async () => { await Task.Delay(SessionTtl, CancellationToken.None).ConfigureAwait(false); _sessions.TryRemove(sessionId, out _); }, CancellationToken.None); } } private async Task TestSingleUrlAsync(string url, CancellationToken ct) { var uri = new Uri(url); var sw = System.Diagnostics.Stopwatch.StartNew(); var result = uri.Scheme.ToLowerInvariant() switch { "rtsp" or "rtsps" => await TestRtspStreamAsync(url, uri, sw, ct), "http" or "https" => await TestHttpStreamAsync(url, uri, sw, ct), "rtmp" or "rtmps" or "dvrip" or "bubble" or "homekit" => await TestTcpReachableAsync(url, uri, sw, ct), _ => new Application.DTOs.StreamTestResult(url, [], 0, 0, 0, null, false) }; // Capture a live frame for alive streams (best-effort — a dead camera // simply yields no screenshot). ffmpeg is used when present; fallback // for HTTP MJPEG is a direct GET of one frame. if (result.IsAlive && result.ScreenshotUrl is null) { var shot = await CaptureScreenshotAsync(url, ct).ConfigureAwait(false); if (shot is not null) result = result with { ScreenshotUrl = shot }; } return result; } /// /// Best-effort capture of one JPEG frame (returns base64 data URI when OK). /// Uses ffmpeg when available, else a raw HTTP GET for MJPEG endpoints. /// private async Task CaptureScreenshotAsync(string url, CancellationToken ct) { try { // 1) Try ffmpeg (handles RTSP/RTMP/etc.). var ffmpegShot = await CaptureWithFfmpegAsync(url, ct).ConfigureAwait(false); if (ffmpegShot is not null) return ffmpegShot; // 2) HTTP MJPEG fallback: GET and read one JPEG frame boundary. if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { var httpShot = await CaptureHttpJpegAsync(url, ct).ConfigureAwait(false); if (httpShot is not null) return httpShot; } return null; } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogTrace(ex, "Screenshot capture failed for {Url}", url); return null; } } private async Task CaptureWithFfmpegAsync(string url, CancellationToken ct) { try { using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(TimeSpan.FromSeconds(8)); var psi = new System.Diagnostics.ProcessStartInfo { FileName = "ffmpeg", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, }; psi.ArgumentList.Add("-hide_banner"); psi.ArgumentList.Add("-loglevel"); psi.ArgumentList.Add("error"); psi.ArgumentList.Add("-rtsp_transport"); psi.ArgumentList.Add("tcp"); psi.ArgumentList.Add("-i"); psi.ArgumentList.Add(url); psi.ArgumentList.Add("-frames:v"); psi.ArgumentList.Add("1"); psi.ArgumentList.Add("-f"); psi.ArgumentList.Add("image2pipe"); psi.ArgumentList.Add("-vcodec"); psi.ArgumentList.Add("mjpeg"); psi.ArgumentList.Add("pipe:1"); using var process = System.Diagnostics.Process.Start(psi); if (process is null) return null; using var ms = new MemoryStream(); var copyTask = process.StandardOutput.BaseStream.CopyToAsync(ms, cts.Token); _ = process.StandardError.ReadToEndAsync(cts.Token); // drain stderr to prevent deadlock var completed = await Task.WhenAny(copyTask, Task.Delay(TimeSpan.FromSeconds(8), ct)).ConfigureAwait(false); if (completed != copyTask) { TryKill(process); return null; } await copyTask.ConfigureAwait(false); if (!process.HasExited) { var exitTask = process.WaitForExitAsync(cts.Token); var exited = await Task.WhenAny(exitTask, Task.Delay(TimeSpan.FromSeconds(2), ct)).ConfigureAwait(false); if (exited != exitTask) { TryKill(process); return null; } } var bytes = ms.ToArray(); if (bytes.Length is 0 or > 512_000) return null; return $"data:image/jpeg;base64,{Convert.ToBase64String(bytes)}"; } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogTrace(ex, "ffmpeg screenshot failed for {Url}", url); return null; } } private async Task CaptureHttpJpegAsync(string url, CancellationToken ct) { try { using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(TimeSpan.FromSeconds(6)); var client = _httpClientFactory.CreateClient("Discovery"); client.Timeout = TimeSpan.FromSeconds(6); using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cts.Token).ConfigureAwait(false); if (!response.IsSuccessStatusCode) return null; var contentType = response.Content.Headers.ContentType?.MediaType ?? ""; if (!contentType.Contains("jpeg", StringComparison.OrdinalIgnoreCase) && !contentType.Contains("multipart", StringComparison.OrdinalIgnoreCase) && !contentType.Contains("mjpg", StringComparison.OrdinalIgnoreCase)) return null; await using var stream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); using var ms = new MemoryStream(); // Read up to 512 KB looking for a complete JPEG (SOI FFD8 → EOI FFD9). var buffer = new byte[8192]; var foundStart = false; var total = 0; while (total < 512_000) { var n = await stream.ReadAsync(buffer, cts.Token).ConfigureAwait(false); if (n == 0) break; await ms.WriteAsync(buffer.AsMemory(0, n), cts.Token).ConfigureAwait(false); total += n; var data = ms.GetBuffer(); if (!foundStart) { for (var i = 0; i < total - 1; i++) { if (data[i] == 0xFF && data[i + 1] == 0xD8) { foundStart = true; break; } } } if (foundStart) { for (var i = 1; i < total - 1; i++) { if (data[i] == 0xFF && data[i + 1] == 0xD9) { ms.SetLength(i + 2); var jpeg = ms.ToArray(); if (jpeg.Length > 4) return $"data:image/jpeg;base64,{Convert.ToBase64String(jpeg)}"; } } } } // Single-frame JPEG (image/jpeg) without multipart boundaries. if (ms.Length > 4 && ms.GetBuffer()[0] == 0xFF && ms.GetBuffer()[1] == 0xD8) { var bytes = ms.ToArray(); return $"data:image/jpeg;base64,{Convert.ToBase64String(bytes)}"; } return null; } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogTrace(ex, "HTTP screenshot failed for {Url}", url); return null; } } private static void TryKill(System.Diagnostics.Process process) { try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { // best effort } } private async Task TestRtspStreamAsync(string url, Uri uri, System.Diagnostics.Stopwatch sw, CancellationToken ct) { try { using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(RtspTimeout); using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await socket.ConnectAsync(uri.Host, uri.Port, cts.Token).ConfigureAwait(false); sw.Stop(); var latencyMs = sw.ElapsedMilliseconds; // Send RTSP DESCRIBE to get stream info var describeRequest = $"DESCRIBE {url} RTSP/1.0\r\nCSeq: 1\r\nAccept: application/sdp\r\nUser-Agent: Heimdall/1.0\r\n\r\n"; var bytes = Encoding.ASCII.GetBytes(describeRequest); await socket.SendAsync(bytes, SocketFlags.None, cts.Token).ConfigureAwait(false); var buffer = new byte[4096]; var received = await socket.ReceiveAsync(buffer, SocketFlags.None, cts.Token).ConfigureAwait(false); var response = Encoding.ASCII.GetString(buffer, 0, received); var codecs = ParseSdpCodecs(response); var (width, height) = ParseResolution(response); var isAlive = response.StartsWith("RTSP/1.0 200", StringComparison.Ordinal) || response.Contains("200 OK", StringComparison.Ordinal); return new Application.DTOs.StreamTestResult(url, [.. codecs], width, height, latencyMs, null, isAlive); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogTrace(ex, "RTSP test failed for {Url}", url); return new Application.DTOs.StreamTestResult(url, [], 0, 0, 0, null, false); } } private async Task TestHttpStreamAsync(string url, Uri uri, System.Diagnostics.Stopwatch sw, CancellationToken ct) { try { using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(HttpTimeout); var client = _httpClientFactory.CreateClient("Discovery"); client.Timeout = HttpTimeout; using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cts.Token).ConfigureAwait(false); sw.Stop(); if (!response.IsSuccessStatusCode) return new Application.DTOs.StreamTestResult(url, [], 0, 0, 0, null, false); var contentType = response.Content.Headers.ContentType?.MediaType ?? ""; var codecs = contentType switch { "image/jpeg" => new[] { "MJPEG" }, "multipart/x-mixed-replace" => new[] { "MJPEG" }, _ => [contentType] }; return new Application.DTOs.StreamTestResult(url, codecs, 0, 0, sw.ElapsedMilliseconds, null, true); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogTrace(ex, "HTTP stream test failed for {Url}", url); return new Application.DTOs.StreamTestResult(url, [], 0, 0, 0, null, false); } } private static async Task TestTcpReachableAsync(string url, Uri uri, System.Diagnostics.Stopwatch sw, CancellationToken ct) { try { using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(RtspTimeout); await socket.ConnectAsync(uri.Host, uri.Port, cts.Token).ConfigureAwait(false); sw.Stop(); return new Application.DTOs.StreamTestResult(url, [], 0, 0, sw.ElapsedMilliseconds, null, true); } catch { return new Application.DTOs.StreamTestResult(url, [], 0, 0, 0, null, false); } } [GeneratedRegex(@"a=rtpmap:\d+\s+(\S+)\s*/\s*\d+", RegexOptions.Compiled | RegexOptions.IgnoreCase)] private static partial Regex CodecPattern(); [GeneratedRegex(@"a=fmtp:\d+\s+.*?(?:width|Width)=(\d+).*?(?:height|Height)=(\d+)", RegexOptions.Compiled)] private static partial Regex ResolutionInFmtpPattern(); private static ReadOnlyCollection ParseSdpCodecs(string sdp) { var codecs = new List(); foreach (Match match in CodecPattern().Matches(sdp)) { var codec = match.Groups[1].Value; if (!codecs.Contains(codec)) codecs.Add(codec); } return codecs.AsReadOnly(); } private static (int width, int height) ParseResolution(string response) { var fmtpMatch = ResolutionInFmtpPattern().Match(response); return fmtpMatch.Success ? (int.Parse(fmtpMatch.Groups[1].Value, CultureInfo.InvariantCulture), int.Parse(fmtpMatch.Groups[2].Value, CultureInfo.InvariantCulture)) : (0, 0); } private static StreamTestSession MapSession(Guid sessionId, ActiveSession session) { var results = session.GetResults(); var mapped = results.Select((r, i) => { // The in-session screenshot bytes are exposed via the endpoint; // the DTO carries the URL the UI can . if (session.HasScreenshot(i)) return r with { ScreenshotUrl = $"/api/discovery/test/{sessionId}/screenshot/{i}" }; return r; }).ToArray(); return new StreamTestSession( sessionId, session.Status, session.TotalCount, session.TestedCount, session.AliveCount, mapped); } private sealed class ActiveSession { private readonly List _results = []; private readonly List _screenshots = []; private readonly object _lock = new(); private volatile bool _cancelled; public int TotalCount { get; } public string Status { get; private set; } = "running"; public int TestedCount { get { lock (_lock) { return _results.Count; } } } public int AliveCount { get { lock (_lock) { return _results.Count(r => r.IsAlive); } } } public bool IsCancelled => _cancelled; public ActiveSession(int totalCount) => TotalCount = totalCount; public void AddResult(Application.DTOs.StreamTestResult result) { lock (_lock) { _results.Add(result); _screenshots.Add(ExtractJpeg(result.ScreenshotUrl)); } } public void MarkDone() => Status = "done"; public void Cancel() { _cancelled = true; Status = "cancelled"; } public bool HasScreenshot(int index) { lock (_lock) { return index >= 0 && index < _screenshots.Count && _screenshots[index] is { Length: > 0 }; } } public byte[]? GetScreenshot(int index) { lock (_lock) { return index >= 0 && index < _screenshots.Count ? _screenshots[index] : null; } } public ReadOnlyCollection GetResults() { lock (_lock) { return _results.ToList().AsReadOnly(); } } /// Extract raw JPEG bytes from a data-URI screenshot URL (or null). private static byte[]? ExtractJpeg(string? screenshotUrl) { if (string.IsNullOrEmpty(screenshotUrl) || !screenshotUrl.StartsWith("data:image/jpeg;base64,", StringComparison.Ordinal)) return null; try { return Convert.FromBase64String(screenshotUrl["data:image/jpeg;base64,".Length..]); } catch (FormatException) { return null; } } } }