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;
}
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();
return 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)
};
}
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)
{
return new StreamTestSession(
sessionId,
session.Status,
session.TotalCount,
session.TestedCount,
session.AliveCount,
[.. session.GetResults()]);
}
private sealed class ActiveSession
{
private readonly List _results = [];
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); }
}
public void MarkDone() => Status = "done";
public void Cancel() { _cancelled = true; Status = "cancelled"; }
public ReadOnlyCollection GetResults()
{
lock (_lock) { return _results.ToList().AsReadOnly(); }
}
}
}