chore: auto-commit 2026-08-11 22:57 [Heimdall] src/Heimdall.Agent/Services/NetworkCameraScanner.cs, src/Heimdall.Application/DTOs/SiteCredentialDto.cs, src/Heimdall.Application/Services/ICameraDiscoveryService.cs, src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs, src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs…

This commit is contained in:
Arnaud Dartois committed 2026-08-11 22:57:42 +02:00
1 parent ac1871e8d9
commit 6df44cb9e0
6 files changed
+444 -9

No files matched your search

@@ -75,6 +75,18 @@ public sealed partial class StreamTesterService
return Task.CompletedTask;
}
/// <summary>
/// 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).
/// </summary>
public Task<byte[]?> GetScreenshotAsync(Guid sessionId, int index, CancellationToken ct = default)
{
if (!_sessions.TryGetValue(sessionId, out var session))
return Task.FromResult<byte[]?>(null);
return Task.FromResult(session.GetScreenshot(index));
}
private async Task RunTestsAsync(Guid sessionId, StreamTestRequest request, ActiveSession session, CancellationToken ct)
{
try
@@ -137,13 +149,216 @@ public sealed partial class StreamTesterService
var uri = new Uri(url);
var sw = System.Diagnostics.Stopwatch.StartNew();
return uri.Scheme.ToLowerInvariant() switch
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;
}
/// <summary>
/// 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.
/// </summary>
private async Task<string?> 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<string?> 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);
var stderrTask = process.StandardError.ReadToEndAsync(cts.Token);
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<string?> 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;
ms.Write(buffer, 0, n);
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<Application.DTOs.StreamTestResult> TestRtspStreamAsync(string url, Uri uri, System.Diagnostics.Stopwatch sw, CancellationToken ct)
@@ -263,18 +478,29 @@ public sealed partial class StreamTesterService
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 <img src="...">.
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,
[.. session.GetResults()]);
mapped);
}
private sealed class ActiveSession
{
private readonly List<Application.DTOs.StreamTestResult> _results = [];
private readonly List<byte[]?> _screenshots = [];
private readonly object _lock = new();
private volatile bool _cancelled;
@@ -288,15 +514,51 @@ public sealed partial class StreamTesterService
public void AddResult(Application.DTOs.StreamTestResult result)
{
lock (_lock) { _results.Add(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<Application.DTOs.StreamTestResult> GetResults()
{
lock (_lock) { return _results.ToList().AsReadOnly(); }
}
/// <summary>Extract raw JPEG bytes from a data-URI screenshot URL (or null).</summary>
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;
}
}
}
}