Heimdall Gitea / Detect CI scope (pull_request) Successful in 30s
Heimdall Gitea / Build and tests (pull_request) Failing after 7m59s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s
122 lines
5.9 KiB
C#
122 lines
5.9 KiB
C#
using System.Diagnostics;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json.Serialization;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Heimdall.Agent.Services;
|
|
|
|
/// <summary>Re-publishes assigned primary streams to the configured Central MediaMTX.</summary>
|
|
public sealed class LiveCameraRelayService(
|
|
AgentState state,
|
|
IOptions<AgentOptions> options,
|
|
CameraConfigStore cameras,
|
|
IHttpClientFactory clients,
|
|
ILogger<LiveCameraRelayService> logger) : BackgroundService
|
|
{
|
|
private const int MaxPublishers = 2;
|
|
private readonly Dictionary<Guid, Relay> _relays = [];
|
|
private readonly Dictionary<Guid, DateTimeOffset> _retryAt = [];
|
|
private sealed record Relay(Process Process, DateTimeOffset RenewAt);
|
|
private sealed record PublishSession(string Url, DateTimeOffset RenewAt);
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
try
|
|
{
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
try { await SynchronizeAsync(stoppingToken); }
|
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
|
catch (Exception ex) { logger.LogWarning("Live relay synchronization failed ({ErrorType})", ex.GetType().Name); }
|
|
try { await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); }
|
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
|
}
|
|
}
|
|
finally { await StopAllAsync(); }
|
|
}
|
|
|
|
private async Task SynchronizeAsync(CancellationToken ct)
|
|
{
|
|
var assigned = SelectAssignedCameras(cameras);
|
|
foreach (var id in _relays.Keys.Where(id => !assigned.ContainsKey(id)).ToArray())
|
|
await StopAsync(id);
|
|
|
|
foreach (var camera in assigned.Values)
|
|
{
|
|
if (_relays.TryGetValue(camera.CameraId, out var relay) && !relay.Process.HasExited &&
|
|
relay.RenewAt > DateTimeOffset.UtcNow) continue;
|
|
await StopAsync(camera.CameraId);
|
|
if (state.AgentId == Guid.Empty || string.IsNullOrWhiteSpace(state.ApiKey) ||
|
|
_retryAt.GetValueOrDefault(camera.CameraId) > DateTimeOffset.UtcNow) continue;
|
|
if (!await StartAsync(camera, ct)) _retryAt[camera.CameraId] = DateTimeOffset.UtcNow.AddSeconds(20);
|
|
}
|
|
}
|
|
|
|
internal static IReadOnlyDictionary<Guid, AgentCameraConfig> SelectAssignedCameras(CameraConfigStore cameras) =>
|
|
cameras.HasCentralConfiguration
|
|
? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.RtspUrl))
|
|
.Take(MaxPublishers).ToDictionary(c => c.CameraId)
|
|
: new Dictionary<Guid, AgentCameraConfig>();
|
|
|
|
private static bool IsRtspSource(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) &&
|
|
(uri.Scheme.Equals("rtsp", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("rtsps", StringComparison.OrdinalIgnoreCase));
|
|
|
|
private async Task<bool> StartAsync(AgentCameraConfig camera, CancellationToken ct)
|
|
{
|
|
var client = clients.CreateClient();
|
|
client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", state.ApiKey);
|
|
using var response = await client.PostAsync(
|
|
$"{options.Value.CentralUrl.TrimEnd('/')}/api/live-media/agents/{state.AgentId:D}/cameras/{camera.CameraId:D}/publish-session",
|
|
content: null, ct);
|
|
if (!response.IsSuccessStatusCode) return false;
|
|
var session = await response.Content.ReadFromJsonAsync<PublishSession>(cancellationToken: ct);
|
|
if (session is null || !Uri.TryCreate(session.Url, UriKind.Absolute, out var destination)) return false;
|
|
|
|
var start = CreateStartInfo("ffmpeg", camera.RtspUrl, destination);
|
|
try
|
|
{
|
|
var process = Process.Start(start);
|
|
if (process is null) return false;
|
|
_ = DrainErrorsAsync(process);
|
|
_relays[camera.CameraId] = new Relay(process, session.RenewAt.AddSeconds(-30));
|
|
logger.LogInformation("Live relay started for camera {CameraId}", camera.CameraId);
|
|
return true;
|
|
}
|
|
catch (Exception ex) { logger.LogWarning("Live relay failed for camera {CameraId} ({ErrorType})", camera.CameraId, ex.GetType().Name); return false; }
|
|
}
|
|
|
|
internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string source, Uri destination)
|
|
{
|
|
var start = new ProcessStartInfo { FileName = ffmpegPath, UseShellExecute = false,
|
|
RedirectStandardError = true, RedirectStandardOutput = false, CreateNoWindow = true };
|
|
foreach (var arg in new[] { "-nostdin", "-hide_banner", "-loglevel", "error", "-fflags", "nobuffer", "-flags", "low_delay", "-rtsp_transport", "tcp", "-i", source,
|
|
"-map", "0:v:0", "-map", "0:a:0?", "-c:v", "copy", "-c:a", "libopus", "-b:a", "64k", "-f", "rtsp", "-rtsp_transport", "tcp", destination.ToString() })
|
|
start.ArgumentList.Add(arg);
|
|
return start;
|
|
}
|
|
|
|
private static async Task DrainErrorsAsync(Process process)
|
|
{
|
|
try { while (await process.StandardError.ReadLineAsync() is not null) { } }
|
|
catch (IOException) { }
|
|
}
|
|
|
|
private async Task StopAsync(Guid cameraId)
|
|
{
|
|
if (!_relays.Remove(cameraId, out var relay)) return;
|
|
try
|
|
{
|
|
if (!relay.Process.HasExited) relay.Process.Kill(entireProcessTree: true);
|
|
await relay.Process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(3));
|
|
}
|
|
catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or TimeoutException)
|
|
{ logger.LogDebug("Live relay cleanup for camera {CameraId} ended with {ErrorType}", cameraId, ex.GetType().Name); }
|
|
finally { relay.Process.Dispose(); }
|
|
}
|
|
|
|
private async Task StopAllAsync()
|
|
{
|
|
foreach (var cameraId in _relays.Keys.ToArray()) await StopAsync(cameraId);
|
|
}
|
|
}
|