- RTMP : handshake minimal C0/C1 (0x03 + 1536 octets) — serveur qui répond C0 = vivant - Bubble (Uniview) : TCP + requête HTTP tramée (préambule binaire 8 octets, go2rtc pkg/bubble) + vérif HTTP/1.1 200 - HomeKit : TCP + GET /accessories — toute réponse HTTP (200/401/470) prouve un service HAP vivant - StreamTesterService central : dvrip/bubble/homekit acceptés (TCP reachable) - Timeouts explicites Task.WhenAny partout (jamais de hang, cf. 491a253) - Tests : 4 (serveurs TCP factices RTMP/HTTP)
303 lines
12 KiB
C#
303 lines
12 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public sealed partial class StreamTesterService
|
|
{
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
|
private readonly ILogger<StreamTesterService> _logger;
|
|
|
|
private readonly ConcurrentDictionary<Guid, ActiveSession> _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<StreamTesterService> logger)
|
|
{
|
|
_httpClientFactory = httpClientFactory;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <summary>Create a new stream test session and start testing in background.</summary>
|
|
public async Task<StreamTestSession> 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);
|
|
}
|
|
|
|
/// <summary>Get current state of a test session.</summary>
|
|
#pragma warning disable CA1822 // Member does not access instance data
|
|
public Task<StreamTestSession?> GetSessionAsync(Guid sessionId, CancellationToken ct = default)
|
|
#pragma warning restore CA1822
|
|
{
|
|
return _sessions.TryGetValue(sessionId, out var session)
|
|
? Task.FromResult<StreamTestSession?>(MapSession(sessionId, session))
|
|
: Task.FromResult<StreamTestSession?>(null);
|
|
}
|
|
|
|
/// <summary>Cancel a running test session.</summary>
|
|
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<Task>();
|
|
|
|
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<Application.DTOs.StreamTestResult> 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<Application.DTOs.StreamTestResult> 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<Application.DTOs.StreamTestResult> 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<Application.DTOs.StreamTestResult> 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<string> ParseSdpCodecs(string sdp)
|
|
{
|
|
var codecs = new List<string>();
|
|
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<Application.DTOs.StreamTestResult> _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<Application.DTOs.StreamTestResult> GetResults()
|
|
{
|
|
lock (_lock) { return _results.ToList().AsReadOnly(); }
|
|
}
|
|
}
|
|
}
|