diff --git a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs
index ef193bb..26ed765 100644
--- a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs
+++ b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs
@@ -40,6 +40,8 @@ public sealed class NetworkCameraScanner
private static readonly TimeSpan OnvifUdpTimeout = TimeSpan.FromMilliseconds(500);
private static readonly TimeSpan ReverseDnsTimeout = TimeSpan.FromMilliseconds(500);
private static readonly TimeSpan DvripTimeout = TimeSpan.FromSeconds(3);
+ private static readonly TimeSpan ScreenshotTimeout = TimeSpan.FromSeconds(6);
+ private const int MaxScreenshotBytes = 512 * 1024; // 512 KB max per frame
// ReSharper disable once InconsistentNaming
private static readonly XNamespace SoapNs = "http://www.w3.org/2003/05/soap-envelope";
@@ -180,14 +182,26 @@ public sealed class NetworkCameraScanner
if (device.StreamUrls is { Length: > 0 })
{
var alive = await TestUrlsAsync(device.StreamUrls, ct).ConfigureAwait(false);
- return device with { StreamUrls = alive.Count > 0 ? [.. alive] : device.StreamUrls };
+ var screenshot = device.ScreenshotBase64 is null && alive.Count > 0
+ ? await CaptureScreenshotAsync(alive[0], ct).ConfigureAwait(false)
+ : device.ScreenshotBase64;
+ return device with
+ {
+ StreamUrls = alive.Count > 0 ? [.. alive] : device.StreamUrls,
+ ScreenshotBase64 = screenshot,
+ };
}
// Build + test candidate stream URLs (the agent is on the camera LAN,
// the Central is not — this is where the live stream is proven).
var tested = await TestStreamUrlsAsync(device, credentialPool, ct).ConfigureAwait(false);
if (tested.Count > 0)
- return device with { StreamUrls = [.. tested] };
+ {
+ var screenshot = device.ScreenshotBase64 is null
+ ? await CaptureScreenshotAsync(tested[0], ct).ConfigureAwait(false)
+ : device.ScreenshotBase64;
+ return device with { StreamUrls = [.. tested], ScreenshotBase64 = screenshot };
+ }
if (HasDefinitiveCameraEvidence(device))
{
@@ -1409,6 +1423,102 @@ public sealed class NetworkCameraScanner
}
}
+ // ─── Screenshot capture ──────────────────────────────────────────────
+
+ ///
+ /// Capture one JPEG frame from a stream URL with ffmpeg (the agent image
+ /// ships ffmpeg). Best-effort: returns null on any failure (no ffmpeg,
+ /// timeout, unreadable stream) — the discovery must never fail because of
+ /// a screenshot. ArgumentList is used (never Arguments) to avoid RTSP
+ /// argument injection.
+ ///
+ private async Task CaptureScreenshotAsync(string url, CancellationToken ct)
+ {
+ try
+ {
+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ cts.CancelAfter(ScreenshotTimeout);
+
+ 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(ScreenshotTimeout, 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 > MaxScreenshotBytes)
+ return null;
+
+ return Convert.ToBase64String(bytes);
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested)
+ {
+ return null;
+ }
+ catch (Exception ex)
+ {
+ _logger?.LogTrace(ex, "Screenshot capture 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
+ }
+ }
+
// ─── Network helpers ────────────────────────────────────────────────
private static (string? LocalIp, string? GatewayIp) GetLocalNetworkInfo()
diff --git a/src/Heimdall.Application/DTOs/SiteCredentialDto.cs b/src/Heimdall.Application/DTOs/SiteCredentialDto.cs
index 7ec56b6..2239d17 100644
--- a/src/Heimdall.Application/DTOs/SiteCredentialDto.cs
+++ b/src/Heimdall.Application/DTOs/SiteCredentialDto.cs
@@ -57,7 +57,8 @@ public record AgentDiscoveredDevice(
string? HomeKitDeviceId,
string? HomeKitModel,
string? CredentialLabel = null,
- string[]? StreamUrls = null);
+ string[]? StreamUrls = null,
+ string? ScreenshotBase64 = null);
/// Response to an agent's discovery submission.
public record AgentDiscoverySubmitResponse(
@@ -90,7 +91,8 @@ public record PendingDiscoveryResponse(
int? HttpPort,
DateTime ProbedAt,
bool IsProcessed,
- string[] StreamUrls);
+ string[] StreamUrls,
+ bool HasScreenshot = false);
/// Request to reject (ignore) a pending discovery result.
public record RejectDiscoveryRequest(Guid ResultId);
diff --git a/src/Heimdall.Application/Services/ICameraDiscoveryService.cs b/src/Heimdall.Application/Services/ICameraDiscoveryService.cs
index c47f41d..8497f10 100644
--- a/src/Heimdall.Application/Services/ICameraDiscoveryService.cs
+++ b/src/Heimdall.Application/Services/ICameraDiscoveryService.cs
@@ -101,4 +101,10 @@ public interface ICameraDiscoveryService
/// in the pending list. Does not delete the row.
///
Task RejectDiscoveryAsync(Guid resultId, CancellationToken ct);
+
+ ///
+ /// Get the in-memory screenshot (agent-captured JPEG) for a discovery
+ /// result. Returns null when absent or expired (TTL 10 min).
+ ///
+ byte[]? GetDiscoveryScreenshot(Guid resultId);
}
diff --git a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs
index 97579b2..6e72f32 100644
--- a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs
+++ b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs
@@ -31,6 +31,14 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
private readonly ICredentialProtector _credentialProtector;
private readonly ILogger _logger;
+ ///
+ /// In-memory screenshot cache for discovery results (agent-captured JPEG,
+ /// base64). Never persisted — TTL 10 min, matching the discovery workflow.
+ ///
+ private readonly ConcurrentDictionary _screenshots = new();
+
+ private sealed record ScreenshotEntry(byte[] Bytes, DateTime ExpiresAt);
+
/// Built-in camera database entries (StrixCamDB-inspired).
private static readonly CameraDbEntry[] BuiltInCameraDb =
[
@@ -491,6 +499,21 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
ApplyAgentProbeData(result, device);
+ // Screenshot (agent-captured JPEG, base64) → in-memory cache keyed
+ // by the discovery result id. Never persisted.
+ if (!string.IsNullOrEmpty(device.ScreenshotBase64))
+ {
+ try
+ {
+ var bytes = Convert.FromBase64String(device.ScreenshotBase64);
+ _screenshots[result.Id] = new ScreenshotEntry(bytes, DateTime.UtcNow.AddMinutes(10));
+ }
+ catch (FormatException)
+ {
+ _logger.LogDebug("Invalid screenshot base64 for {Ip}, ignoring", device.Ip);
+ }
+ }
+
// The agent performs the authenticated ONVIF enrichment itself
// (it is on the camera network and holds the site's credential
// pool via the encrypted agent config). When it reports the label
@@ -743,12 +766,26 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
r.OnvifDeviceServiceUrl, r.OnvifName, r.OnvifHardware, r.OnvifPort,
r.HttpServerHeader, r.HttpStatusCode, r.HttpPort,
r.ProbedAt, r.IsProcessed,
- r.DiscoveredStreams.Select(s => s.Url).ToArray()))
+ r.DiscoveredStreams.Select(s => s.Url).ToArray(),
+ HasScreenshot: _screenshots.TryGetValue(r.Id, out var shot) && shot.ExpiresAt > DateTime.UtcNow))
.ToList();
return ServiceResult>.Success(response);
}
+ /// Get the in-memory screenshot (agent-captured) for a discovery result.
+ public byte[]? GetDiscoveryScreenshot(Guid resultId)
+ {
+ if (!_screenshots.TryGetValue(resultId, out var shot))
+ return null;
+ if (shot.ExpiresAt <= DateTime.UtcNow)
+ {
+ _screenshots.TryRemove(resultId, out _);
+ return null;
+ }
+ return shot.Bytes;
+ }
+
public async Task RejectDiscoveryAsync(Guid resultId, CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
diff --git a/src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs b/src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs
index cdf8da9..b93e5e8 100644
--- a/src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs
+++ b/src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs
@@ -75,6 +75,18 @@ public sealed partial class StreamTesterService
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
@@ -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;
+ }
+
+ ///
+ /// 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);
+ 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 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 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
.
+ 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 _results = [];
+ private readonly List _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 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;
+ }
+ }
}
}
diff --git a/src/Heimdall.Web/Controllers/DiscoveryController.cs b/src/Heimdall.Web/Controllers/DiscoveryController.cs
index 9ad7f13..6ec4a55 100644
--- a/src/Heimdall.Web/Controllers/DiscoveryController.cs
+++ b/src/Heimdall.Web/Controllers/DiscoveryController.cs
@@ -32,10 +32,12 @@ namespace Heimdall.Api.Controllers;
public class DiscoveryController : ControllerBase
{
private readonly IMediator _mediator;
+ private readonly ICameraDiscoveryService _discovery;
- public DiscoveryController(IMediator mediator)
+ public DiscoveryController(IMediator mediator, ICameraDiscoveryService discovery)
{
_mediator = mediator;
+ _discovery = discovery;
}
/// Probe a single IP address for camera services.
@@ -130,6 +132,22 @@ public class DiscoveryController : ControllerBase
return File(result.Data, "image/jpeg");
}
+ ///
+ /// Get the agent-captured screenshot of a pending discovery result
+ /// (in-memory only, TTL 10 min).
+ ///
+ [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
+ [HttpGet("results/{resultId:guid}/screenshot")]
+ [ProducesResponseType(typeof(byte[]), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
+ public IActionResult GetDiscoveryScreenshot(Guid resultId)
+ {
+ var bytes = _discovery.GetDiscoveryScreenshot(resultId);
+ if (bytes is null or { Length: 0 })
+ return NotFound(new { error = "Screenshot not available" });
+ return File(bytes, "image/jpeg");
+ }
+
/// Cancel a running stream test session.
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPost("test/{sessionId:guid}/cancel")]