diff --git a/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj b/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj index 0d24fb23..5d52f165 100644 --- a/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj +++ b/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj @@ -1,7 +1,7 @@ - 11.0.1 + 11.0.2 bb-mediamtx diff --git a/src/components/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs b/src/components/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs index 2fa89871..5cd09e0a 100644 --- a/src/components/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs +++ b/src/components/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs @@ -12,11 +12,11 @@ static class HttpClientExtensions { extension(HttpClient client) { - internal HttpRequestMessage CreateAuthorizationRequest(HttpMethod method, string relativeUri, string password) + internal HttpRequestMessage CreateAuthorizationRequest(HttpMethod method, string relativeUri, string password, string userName = "gateway") { var baseAddress = client.BaseAddress!; var request = new HttpRequestMessage(method, new Uri(baseAddress, relativeUri)); - var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"gateway:{password}"))); + var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userName}:{password}"))); request.Headers.Authorization = authValue; return request; } diff --git a/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs b/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs index af7cef44..f7b64d2e 100644 --- a/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs +++ b/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs @@ -15,8 +15,8 @@ namespace BootstrapBlazor.Components; public interface IMediaMtxService { /// - /// 确保网关已启动并就绪,失败时抛出异常。默认实现复用本宿主的运行中进程;工具缺失时需手动部署。 - /// Ensures the gateway is running and ready, throwing an exception on failure. The default service reuses its running process; missing tools must be deployed manually. + /// 确保网关已启动并就绪,失败时抛出异常。默认实现复用同一用户启动的兼容网关;外部网关模式连接已部署的本机网关。 + /// Ensures the gateway is running and ready, throwing an exception on failure. The default service reuses a compatible gateway started by the same user; external gateway mode connects to an independently deployed local gateway. /// 11.0.0 /// /// 取消令牌。The cancellation token. diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs index fe07287f..9c8ea65e 100644 --- a/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs @@ -22,8 +22,29 @@ public sealed class MediaMtxOptions public int ApiPort { get; set; } = 9997; /// - /// 获得/设置网关启动时配置的摄像头,键为播放路径,值中的 Path 和 PlayUrl 被忽略。密码应通过安全配置源提供;环境变量可能被子进程继承。 - /// Gets or sets the cameras configured when the gateway starts. Keys are playback paths; Path and PlayUrl in each value are ignored. Supply passwords through a secure configuration source; environment variables may be inherited by child processes. + /// 获得/设置是否连接由外部管理的本机 MediaMTX 网关。默认值为 false。 + /// Gets or sets whether to connect to an externally managed local MediaMTX gateway. Defaults to false. + /// 11.0.2 + /// + public bool UseExternalGateway { get; set; } + + /// + /// 获得/设置外部网关 Control API 的用户名,默认为 gateway。仅在外部网关模式下使用。 + /// Gets or sets the external gateway Control API user name. Defaults to gateway and is used only in external gateway mode. + /// 11.0.2 + /// + public string ExternalApiUserName { get; set; } = "gateway"; + + /// + /// 获得/设置外部网关 Control API 的密码。仅在外部网关模式下使用,应通过安全配置源提供。 + /// Gets or sets the external gateway Control API password. Used only in external gateway mode; supply it through a secure configuration source. + /// 11.0.2 + /// + public string? ExternalApiPassword { get; set; } + + /// + /// 获得/设置网关启动或连接外部网关时登记的摄像头,键为播放路径,值中的 Path 和 PlayUrl 被忽略。密码应通过安全配置源提供;环境变量可能被子进程继承。 + /// Gets or sets the cameras configured when starting or connecting to the gateway. Keys are playback paths; Path and PlayUrl in each value are ignored. Supply passwords through a secure configuration source; environment variables may be inherited by child processes. /// 11.0.0 /// public Dictionary Cameras { get; set; } = new(); diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs index f331875e..373d5435 100644 --- a/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs @@ -21,7 +21,8 @@ sealed partial class MediaMtxService private static readonly TimeSpan _probeInterval = TimeSpan.FromMilliseconds(100); private static readonly TimeSpan _stopTimeout = TimeSpan.FromSeconds(5); private Process? _process; - private string? _configPath; + private bool _externalReady; + private DateTimeOffset _externalStarted; private readonly SemaphoreSlim _startupGate = new(1, 1); private readonly CancellationTokenSource _stopping = new(); @@ -32,12 +33,18 @@ public async Task EnsureStartedAsync(CancellationToken cancellationToken = defau try { linked.Token.ThrowIfCancellationRequested(); + if (options.Value.UseExternalGateway) + { + await ConnectExternalGatewayAsync(linked.Token); + return; + } + if (_process is { HasExited: false }) { return; } - await StopGatewayAsync(); + await ReleaseGatewayAsync(); try { if (!await StartGatewayAsync(linked.Token)) @@ -47,7 +54,7 @@ public async Task EnsureStartedAsync(CancellationToken cancellationToken = defau } catch { - await StopGatewayAsync(); + await ReleaseGatewayAsync(); throw; } } @@ -57,6 +64,70 @@ public async Task EnsureStartedAsync(CancellationToken cancellationToken = defau } } + private async Task ConnectExternalGatewayAsync(CancellationToken cancellationToken) + { + var settings = options.Value; + var userName = settings.ExternalApiUserName; + var password = settings.ExternalApiPassword; + if (string.IsNullOrWhiteSpace(userName) || userName.Contains(':') || string.IsNullOrEmpty(password)) + { + throw new InvalidOperationException("External MediaMTX gateway credentials are required."); + } + + try + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(_startupTimeout); + using var request = _client.CreateAuthorizationRequest(HttpMethod.Get, "info", password, userName); + using var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token); + if (response.StatusCode != HttpStatusCode.OK) + { + throw new HttpRequestException($"External MediaMTX gateway readiness check failed with HTTP {(int)response.StatusCode}.", + null, response.StatusCode); + } + + using var stream = await response.Content.ReadAsStreamAsync(timeout.Token); + using var info = await JsonDocument.ParseAsync(stream, cancellationToken: timeout.Token); + if (info.RootElement.ValueKind != JsonValueKind.Object || + !info.RootElement.TryGetProperty("started", out var startedValue) || + startedValue.ValueKind != JsonValueKind.String || + !startedValue.TryGetDateTimeOffset(out var started)) + { + throw new InvalidDataException("External MediaMTX gateway returned invalid readiness information."); + } + + if (_externalReady && _externalStarted == started) + { + return; + } + + _externalReady = false; + await SetGatewayStateAsync(password); + foreach (var (path, camera) in settings.Cameras) + { + await AddOrUpdateAsync(new MediaMtxCameraOptions + { + Path = path, + RtspUrl = camera.RtspUrl, + UserName = camera.UserName, + Password = camera.Password + }, cancellationToken); + } + _externalStarted = started; + _externalReady = true; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested && _externalReady) + { + throw; + } + catch + { + _externalReady = false; + await SetGatewayStateAsync(null); + throw; + } + } + private async Task StartGatewayAsync(CancellationToken cancellationToken) { if (!launcher.IsSupported) @@ -77,7 +148,48 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) var iceAddress = $"{Loopback}:{settings.WebRtcIcePort}"; var publicUri = settings.GetWebRtcPublicUri(); var cameraSources = new Dictionary(); - var config = CreateConfiguration(settings.Cameras, httpAddress, iceAddress, apiAddress, publicUri, cameraSources); + var cameras = settings.Cameras.OrderBy(item => item.Key, StringComparer.Ordinal) + .ToDictionary(item => item.Key, item => item.Value, StringComparer.Ordinal); + var config = CreateConfiguration(cameras, httpAddress, iceAddress, apiAddress, publicUri, cameraSources); + using var sha = SHA256.Create(); + using var executableStream = File.OpenRead(executable); + var fingerprintInput = JsonSerializer.SerializeToUtf8Bytes(new + { + Executable = Convert.ToHexString(sha.ComputeHash(executableStream)), + Configuration = config, + Sources = cameraSources.OrderBy(item => item.Key, StringComparer.Ordinal).ToArray() + }); + var fingerprint = Convert.ToHexString(SHA256.HashData(fingerprintInput)); + var directory = MediaMtxSharedGateway.GetDirectory(); + await using var sharedLock = await MediaMtxSharedGateway.AcquireAsync(directory, settings.ApiPort, cancellationToken); + var statePath = Path.Combine(directory, $"{settings.ApiPort}.json"); + var state = await MediaMtxSharedGateway.ReadAsync(statePath, cancellationToken); + if (state is not null && GetRecordedProcess(state) is { } existing) + { + try + { + if (!string.Equals(state.Fingerprint, fingerprint, StringComparison.Ordinal)) + { + throw new InvalidOperationException("The existing MediaMTX gateway has different configuration. Stop it before changing the gateway configuration."); + } + using var reuseTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + reuseTimeout.CancelAfter(_startupTimeout); + await WaitForControlApiAsync(apiAddress, state.Password, reuseTimeout.Token); + if (existing.HasExited) + { + throw new InvalidOperationException("The existing MediaMTX gateway exited during readiness verification."); + } + await SetGatewayStateAsync(state.Password); + _process = existing; + logger.LogInformation("Reusing the MediaMTX gateway (PID {ProcessId}).", existing.Id); + return true; + } + catch + { + existing.Dispose(); + throw; + } + } if (!IsPortAvailable(settings.WebRtcPort, ProtocolType.Tcp) | !IsPortAvailable(settings.ApiPort, ProtocolType.Tcp) | @@ -89,15 +201,17 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(_startupTimeout); - _configPath = Path.GetTempFileName(); - await File.WriteAllTextAsync(_configPath, config, timeout.Token); - var process = StartMediaMtx(launcher, executable, _configPath, apiPassword, cameraSources); - _process = process; - process.BeginOutputReadLine(); - process.BeginErrorReadLine(); - + Process? process = null; + var configPath = Path.Combine(directory, $"{settings.ApiPort}.yml"); try { + await File.WriteAllTextAsync(configPath, config, timeout.Token); + process = StartMediaMtx(launcher, executable, configPath, apiPassword, cameraSources); + _process = process; + var processPath = await GetStartedProcessPathAsync(process, timeout.Token); + state = new(process.Id, process.StartTime.ToUniversalTime().Ticks, processPath, fingerprint, apiPassword); + await MediaMtxSharedGateway.WriteAsync(statePath, state, timeout.Token); + var exited = process.WaitForExitAsync(timeout.Token); var ready = WaitForControlApiAsync(apiAddress, apiPassword, timeout.Token); var completed = await Task.WhenAny(ready, exited); @@ -107,18 +221,92 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) { logger.LogError("MediaMTX exited before the gateway was ready (exit code {ExitCode}); the RTSP gateway is disabled. Verify the MediaMTX version and listener ports. {RestartHint}", process.ExitCode, RestartHint); - return false; + throw new InvalidOperationException("The MediaMTX gateway exited before it was ready."); } + await SetGatewayStateAsync(apiPassword); + logger.LogInformation("MediaMTX gateway is ready (PID {ProcessId}). Executable: {ExecutablePath}; WebRTC base URL: {PlayerUrl}; ICE (UDP): {IceAddress}.", + process.Id, executable, $"http://{httpAddress}/", iceAddress); + return true; + } + catch + { + if (process is not null) + { + _process = null; + try + { + await TerminateProcessAsync(process, CancellationToken.None); + File.Delete(statePath); + } + finally + { + process.Dispose(); + } + } + throw; } finally { timeout.Cancel(); } + } + + private static async Task GetStartedProcessPathAsync(Process process, CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + process.Refresh(); + if (process.HasExited) + { + throw new InvalidOperationException($"The MediaMTX process exited before it was ready (exit code {process.ExitCode})."); + } + if (process.MainModule?.FileName is { Length: > 0 } path) + { + return path; + } + await Task.Delay(_probeInterval, cancellationToken); + } + } + + private static Process? GetRecordedProcess(MediaMtxSharedGateway.State state) + { + Process process; + try + { + process = Process.GetProcessById(state.ProcessId); + } + catch (ArgumentException) + { + return null; + } - await SetGatewayStateAsync(apiPassword); - logger.LogInformation("MediaMTX gateway is ready (PID {ProcessId}). Executable: {ExecutablePath}; WebRTC base URL: {PlayerUrl}; ICE (UDP): {IceAddress}.", - process.Id, executable, $"http://{httpAddress}/", iceAddress); - return true; + try + { + if (process.HasExited || process.StartTime.ToUniversalTime().Ticks != state.ProcessStartTicks) + { + process.Dispose(); + return null; + } + var path = process.MainModule?.FileName; + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + if (!string.Equals(path, state.Executable, comparison)) + { + process.Dispose(); + return null; + } + return process; + } + catch (InvalidOperationException) + { + process.Dispose(); + return null; + } + catch + { + process.Dispose(); + throw; + } } private static async Task WaitForControlApiAsync(string apiAddress, string apiPassword, CancellationToken cancellationToken) @@ -163,7 +351,7 @@ private bool IsPortAvailable(int port, ProtocolType protocol) } } - private static async Task StopProcessAsync(Process process, CancellationToken cancellationToken) + private static async Task TerminateProcessAsync(Process process, CancellationToken cancellationToken) { if (!process.HasExited) { @@ -224,7 +412,7 @@ private static string CreateConfiguration(Dictionary 0) { @@ -248,9 +436,7 @@ private static Process StartMediaMtx(IMediaMtxProcessLauncher launcher, string e var startInfo = new ProcessStartInfo(executable) { UseShellExecute = false, - CreateNoWindow = true, - RedirectStandardOutput = true, - RedirectStandardError = true + CreateNoWindow = true }; startInfo.ArgumentList.Add(configPath); var environment = startInfo.Environment; @@ -288,7 +474,7 @@ private static bool IsSourceConfiguration(string key) name.StartsWith("MediaMtx:", StringComparison.OrdinalIgnoreCase); } - private async Task StopGatewayAsync() + private async Task ReleaseGatewayAsync() { try { @@ -296,21 +482,12 @@ private async Task StopGatewayAsync() if (_process is { } process) { _process = null; - using (process) - { - await StopProcessAsync(process, CancellationToken.None).ConfigureAwait(false); - } - } - - if (_configPath is { } configPath) - { - _configPath = null; - File.Delete(configPath); + process.Dispose(); } } catch (Exception exception) { - logger.LogError(exception, "Failed to stop the MediaMTX gateway cleanly."); + logger.LogError(exception, "Failed to release the MediaMTX gateway handle cleanly."); } } } diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs index 0cba0ef0..5eb5909e 100644 --- a/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs @@ -15,7 +15,7 @@ sealed partial class MediaMtxService(IOptions options, ILogger< IMediaMtxProcessLauncher launcher) : IMediaMtxService, IAsyncDisposable { private readonly SemaphoreSlim _gate = new(1, 1); - private readonly HashSet _registeredPaths = new(StringComparer.Ordinal); + private readonly HashSet _registeredPaths = new(StringComparer.Ordinal); private readonly HttpClient _client = new(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = new Uri($"http://127.0.0.1:{options.Value.ApiPort}/v3/"), @@ -60,6 +60,9 @@ player.Scheme is not ("http" or "https") || player.UserInfo.Length != 0) { await AddOrUpdatePathAsync(path, content, cancellationToken); _registeredPaths.Add(path); + logger.LogInformation("MediaMTX camera path registered or updated. RTSP source: {SourceUrl}; player URL: {PlayerUrl}.", + new Uri(camera.RtspUrl!, UriKind.Absolute).GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped), + player.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped)); return playerUrl; } finally @@ -83,7 +86,7 @@ public async Task RemoveAsync(string path, CancellationToken cancellationT } } - private async Task AddOrUpdatePathAsync(string? path, object content, CancellationToken cancellationToken) + private async Task AddOrUpdatePathAsync(string path, object content, CancellationToken cancellationToken) { if (_registeredPaths.Contains(path)) { @@ -100,7 +103,7 @@ private async Task AddOrUpdatePathAsync(string? path, object content, Cancellati } } - private Task UpdatePathAsync(string? path, object content, CancellationToken cancellationToken, bool allowMissing = false) => + private Task UpdatePathAsync(string path, object content, CancellationToken cancellationToken, bool allowMissing = false) => SendAsync(HttpMethod.Patch, $"config/paths/patch/{path}", content, cancellationToken, allowMissing ? HttpStatusCode.NotFound : null); private async Task SendAsync(HttpMethod method, string route, object? content, CancellationToken cancellationToken, @@ -110,7 +113,8 @@ private async Task SendAsync(HttpMethod method, string route, object? cont { throw new InvalidOperationException("The MediaMTX gateway is not running."); } - using var request = _client.CreateAuthorizationRequest(method, route, apiPassword); + var userName = options.Value.UseExternalGateway ? options.Value.ExternalApiUserName : "gateway"; + using var request = _client.CreateAuthorizationRequest(method, route, apiPassword, userName); if (content is not null) { request.Content = JsonContent.Create(content); @@ -180,7 +184,7 @@ public async ValueTask DisposeAsync() await _startupGate.WaitAsync().ConfigureAwait(false); try { - await StopGatewayAsync().ConfigureAwait(false); + await ReleaseGatewayAsync().ConfigureAwait(false); _client.Dispose(); _gate.Dispose(); } diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs index c602db95..40f6df91 100644 --- a/src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs @@ -16,8 +16,8 @@ namespace Microsoft.Extensions.DependencyInjection; public static class MediaMtxServiceCollectionExtensions { /// - /// 从 MediaMtxOptions 配置节绑定选项,注册默认进程启动器和摄像头管理服务。调用 EnsureStartedAsync 启动已部署的网关工具并等待就绪。保留已注册的自定义进程启动器。 - /// Binds options from the MediaMtxOptions configuration section and registers the default process launcher and camera management service. Call EnsureStartedAsync to start the deployed gateway tool and wait until it is ready. Preserves custom launchers. + /// 从 MediaMtxOptions 配置节绑定选项,注册默认进程启动器和摄像头管理服务。调用 EnsureStartedAsync 启动自管网关或连接外部网关并等待就绪。保留已注册的自定义进程启动器。 + /// Binds options from the MediaMtxOptions configuration section and registers the default process launcher and camera management service. Call EnsureStartedAsync to start the managed gateway or connect to an external gateway. Preserves custom launchers. /// 11.0.0 /// /// 宿主服务集合。The host's service collection. diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxSharedGateway.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxSharedGateway.cs new file mode 100644 index 00000000..f73c3e2d --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxSharedGateway.cs @@ -0,0 +1,123 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License +// See the LICENSE file in the project root for more information. +// Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone + +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Text.Json; + +namespace BootstrapBlazor.Components; + +static class MediaMtxSharedGateway +{ + public sealed record State(int ProcessId, long ProcessStartTicks, string Executable, string Fingerprint, string Password); + + public static string GetDirectory() + { + var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (string.IsNullOrEmpty(root)) + { + throw new InvalidOperationException("The local application data directory is unavailable."); + } + + var directory = new DirectoryInfo(Path.Combine(root, "BootstrapBlazor", "mediamtx-gateways")); + if (OperatingSystem.IsWindows()) + { + var user = WindowsIdentity.GetCurrent().User ?? throw new InvalidOperationException("The current user identity is unavailable."); + var security = new DirectorySecurity(); + security.SetOwner(user); + security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + security.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); + if (!directory.Exists) + { + directory.Create(security); + } + directory.Refresh(); + if ((directory.Attributes & FileAttributes.ReparsePoint) != 0 || + !user.Equals(directory.GetAccessControl().GetOwner(typeof(SecurityIdentifier)))) + { + throw new InvalidOperationException("The MediaMTX gateway state directory is not owned by the current user."); + } + directory.SetAccessControl(security); + } + else + { + directory.Create(); + if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) + { + throw new InvalidOperationException("The MediaMTX gateway state directory cannot be a symbolic link."); + } + if (Chown(directory.FullName, GetEffectiveUserId(), uint.MaxValue) != 0 || + Chmod(directory.FullName, 0x1C0) != 0) + { + throw new Win32Exception(Marshal.GetLastWin32Error(), "Cannot secure the MediaMTX gateway state directory."); + } + } + + return directory.FullName; + } + + [DllImport("libc", EntryPoint = "chmod", SetLastError = true)] + private static extern int Chmod(string path, uint mode); + + [DllImport("libc", EntryPoint = "chown", SetLastError = true)] + private static extern int Chown(string path, uint owner, uint group); + + [DllImport("libc", EntryPoint = "geteuid")] + private static extern uint GetEffectiveUserId(); + + public static async Task AcquireAsync(string directory, int port, CancellationToken cancellationToken) + { + var path = Path.Combine(directory, $"{port}.lock"); + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + } + catch (IOException exception) when ((exception.HResult & 0xffff) is 11 or 32 or 33 or 35) + { + await Task.Delay(100, cancellationToken); + } + } + } + + public static async Task ReadAsync(string path, CancellationToken cancellationToken) + { + if (!File.Exists(path)) + { + return null; + } + await using var stream = File.OpenRead(path); + var state = await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); + if (state is null || state.ProcessId <= 0 || state.ProcessStartTicks <= 0 || + string.IsNullOrEmpty(state.Executable) || string.IsNullOrEmpty(state.Fingerprint) || + string.IsNullOrEmpty(state.Password)) + { + throw new InvalidDataException("The MediaMTX gateway state is invalid."); + } + return state; + } + + public static async Task WriteAsync(string path, State state, CancellationToken cancellationToken) + { + var temporary = $"{path}.{Guid.NewGuid():N}.tmp"; + try + { + await using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + await JsonSerializer.SerializeAsync(stream, state, cancellationToken: cancellationToken); + } + File.Move(temporary, path, overwrite: true); + } + finally + { + File.Delete(temporary); + } + } +} diff --git a/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md b/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md index 9f429d82..38ade242 100644 --- a/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md +++ b/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md @@ -1,6 +1,6 @@ # BootstrapBlazor.MediaMtx -ASP.NET Core 动态 RTSP 摄像头服务。调用方通过 `EnsureStartedAsync` 按需启动 MediaMTX 进程,管理多个播放路径,并按需转发 RTSP 到 WebRTC;HikVision 播放组件在首次交互渲染时调用该服务。 +ASP.NET Core 动态 RTSP 摄像头服务。调用方通过 `EnsureStartedAsync` 按需启动 MediaMTX 进程或连接独立运行的本机网关,管理多个播放路径,并按需转发 RTSP 到 WebRTC;HikVision 播放组件在首次交互渲染时调用该服务。 启动不连接摄像头;首次观看时通过 RTSP/TCP 按需拉流,转发为 WebRTC。 主包提供默认进程启动器,但不附带 MediaMTX;通过 `bb-mediamtx` CLI 从 GitHub 下载或自行部署工具,详见“工具部署与进程生命周期”。 @@ -39,7 +39,7 @@ builder.Services.AddMediaMtxService(); } ``` -`Cameras` 是可选的静态摄像头字典,网关启动时自动登记,无需调用 `AddOrUpdateAsync`。 +`Cameras` 是可选的静态摄像头字典,自管网关启动时或首次连接外部网关时自动登记,无需调用 `AddOrUpdateAsync`。 键即播放路径,值使用不含用户信息的 `RtspUrl` 和可选的 `UserName`、`Password`;值中的 `Path` 和 `PlayUrl` 在生成静态网关配置时被忽略。 密码应通过 User Secrets 等安全配置源提供,不要提交到 `appsettings.json`。 User Secrets 的 `secrets.json` 使用与 `appsettings.json` 相同的层次结构,按路径合并: @@ -58,17 +58,30 @@ User Secrets 的 `secrets.json` 使用与 `appsettings.json` 相同的层次结 对应的环境变量名为 `MediaMtxOptions__Cameras__hikvision__Password`。ASP.NET Core 默认只在 Development 环境加载 User Secrets。 **注意**:该环境变量可能被 MediaMTX 子进程继承;使用环境变量时需评估子进程及宿主的访问权限。 -网关通过子进程环境传递包含凭据的源地址,不会将其写入生成的临时配置文件;不要把凭据放在 URL 查询字符串或日志中。 -静态摄像头同样按需使用 RTSP/TCP 拉流;修改摄像头配置后需重启应用。 +自管网关通过子进程环境传递包含凭据的源地址,不会将其写入生成的临时配置文件;外部网关模式通过 Control API 登记源地址。不要把凭据放在 URL 查询字符串或日志中。 +静态摄像头同样按需使用 RTSP/TCP 拉流;自管网关的配置变化需先停止旧网关,再重启应用。 `AddMediaMtxService` 注册默认进程启动器和主服务,从 `MediaMtxOptions` 配置节绑定选项,也可通过 `configureOptions` 回调覆盖选项。默认服务使用 `IOptions`,配置变更后需重启应用。 `BootstrapBlazor.MediaMtx` 核心包负责网关进程生命周期和摄像头管理;原生工具由独立的 `BootstrapBlazor.MediaMtx.Cli` 部署,所有平台统一调用 `AddMediaMtxService`。 -默认启动器支持 Windows x64、Linux x64/ARM64/ARMv7 和 macOS x64/ARM64。不支持的操作系统或系统架构会记录警告,并向 `EnsureStartedAsync` 调用方报告启动失败。 -自行实现 `IMediaMtxProcessLauncher` 时,在调用 `AddMediaMtxService` 前注册该接口,默认启动器不会覆盖已有注册;启动器使用宿主提供的 `ProcessStartInfo` 启动并返回进程,宿主负责就绪探测和清理。 +自管模式的默认启动器支持 Windows x64、Linux x64/ARM64/ARMv7 和 macOS x64/ARM64。不支持的操作系统或系统架构会记录警告,并向 `EnsureStartedAsync` 调用方报告启动失败。 +自行实现 `IMediaMtxProcessLauncher` 时,在调用 `AddMediaMtxService` 前注册该接口,默认启动器不会覆盖已有注册;启动器使用宿主提供的 `ProcessStartInfo` 启动并返回进程,服务负责就绪探测和共享状态。 HTTP 和 Control API 使用不同 TCP 端口,ICE 使用 UDP。 -Control API 仅监听回环地址,使用每个宿主实例生成的内部随机密码,不提供浏览器调用入口。 +自管网关的 Control API 仅监听回环地址,使用随机密码,不提供浏览器调用入口。外部网关的配置和权限由部署方负责。 `IMediaMtxService.SetGatewayStateAsync` 仅供宿主同步网关状态;自定义实现应在密码为 `null` 时 停止管理请求,并在网关就绪后使用提供的密码认证 Control API 请求。 +## 进程复用与路径登记 + +`AddMediaMtxService()` 注册单例服务,但不会在应用启动时立即启动 MediaMTX。首次调用 `EnsureStartedAsync()` 时才启动或连接网关;重复或并发调用会串行检查并复用已就绪的网关,不会为每次播放重新启动进程。 + +自管模式会在同一操作系统用户下协调多个宿主:只有可执行文件和配置指纹匹配、进程身份有效且 Control API 认证通过时才复用。配置不一致时会报错,不会擅自停止或重配正在运行的网关。宿主释放时只释放自身的进程句柄,网关继续运行供后续宿主复用;升级工具或更改网关配置前,应先确认并手动停止旧进程。需要由独立服务管理进程时,使用 `UseExternalGateway`;此模式只连接本机 Control API,不启动或停止网关。 + +路径登记分为两种: + +- `MediaMtxOptions:Cameras` 是静态摄像头配置,以字典键作为播放路径。自管模式启动时写入网关配置;外部模式首次连接或检测到网关重启时,通过 Control API 重新登记。 +- `AddOrUpdateAsync()` 和 `RemoveAsync()` 用于动态增改、删除路径。重复登记会更新已有路径,删除会影响该路径的所有观看者。动态配置只保存在 MediaMTX 内存中;网关重启后,宿主需自行持久化并恢复。多个宿主共享网关时,应避免用不同摄像头配置争用同一路径。 + +所有路径共用同一个网关进程;源流按需拉取,多个观看者可共享一路摄像头流。 + ### WebRTC 首次加载时启动 在服务端注册服务;应用启动时不运行网关: @@ -96,19 +109,68 @@ builder.Services.AddMediaMtxService(); 只在首次交互渲染时执行,不在预渲染时执行。HikVision 由本服务管理进程并调用 Control API。 两个包使用同一个 `MediaMtxCameraOptions` 类型,不支持独立 WASM 宿主。 -`EnsureStartedAsync()` 串行处理启动请求:本宿主的网关仍在运行时直接复用;未运行时尝试启动; +自管模式的 `EnsureStartedAsync()` 串行处理启动请求:复用同一用户已启动且配置一致的网关;未运行时尝试启动; 服务只启动已部署的工具,不自动安装 CLI 或下载;可执行文件缺失时抛出 `MediaMtxToolNotFoundException`(继承自 `FileNotFoundException`),需手动部署后重试。HikVision 预览会显示工具缺失提示及相对应用目录的路径。 网关就绪最多等待 10 秒;`EnsureStartedAsync` 就绪时完成,取消或失败时抛出异常,后续调用可重试。自定义实现也应在启动失败时抛出异常。 自定义 `IMediaMtxService` 要支持此接入方式,需实现 `EnsureStartedAsync`。 +### 连接外部本机网关 + +当多个宿主需要共享网关时,可独立部署并启动 MediaMTX,配置其 Control API 监听 `127.0.0.1`,启用具有 API 权限的账号,并自行配置 WebRTC、ICE、播放权限及进程守护。此模式只连接本机回环 Control API,不支持远程 API;应用不会启动、停止或修改外部进程的监听器。配置端口须与外部网关一致: + +例如 MediaMTX 1.22.0 的独立配置: + +```yaml +rtsp: false +rtmp: false +hls: false +srt: false +moq: false +api: true +apiAddress: 127.0.0.1:9997 +authMethod: internal +authInternalUsers: + - user: gateway + ips: [127.0.0.1] + permissions: + - action: api + - user: any + permissions: + - action: read +webrtc: true +webrtcAddress: 127.0.0.1:8889 +webrtcLocalUDPAddress: 127.0.0.1:8189 +webrtcIPsFromInterfaces: false +webrtcAdditionalHosts: [127.0.0.1] +webrtcAllowOrigins: [http://127.0.0.1:8889] +paths: {} +``` + +使用独立网关进程的安全环境变量 `MTX_AUTHINTERNALUSERS_0_PASS` 设置 API 密码,并确保宿主配置使用相同密码。以上示例只允许本机媒体连接且不提供多租户播放鉴权;远程访问及播放鉴权需由部署方另行配置。 + +```json +{ + "MediaMtxOptions": { + "UseExternalGateway": true, + "ApiPort": 9997, + "ExternalApiUserName": "gateway", + "WebRtcPort": 8889 + } +} +``` + +使用 User Secrets 或其他安全配置源提供 `MediaMtxOptions:ExternalApiPassword`,不要提交密码。API 使用 HTTP Basic 认证,首次连接会检查 `/v3/info`,然后按字典键通过 API 新增或更新 `Cameras`;值中的 `Path` 和 `PlayUrl` 被忽略。多个宿主应协调路径,更新同一路径可能中断其他观看者;若某项登记失败或取消,之前已完成的登记不会回滚,重试前应核实网关状态。 + +每次调用 `EnsureStartedAsync` 都会检查外部网关,首次连接、检测到网关启动时间变化或连接失败后的重连会重新登记静态摄像头。其他动态配置仍需由宿主自行恢复,服务不会在后台监控网关。配置的 `WebRtcPort`、`WebRtcPublicUrl` 仅用于生成播放地址,不会更改外部网关配置。宿主停止不会删除路径或停止外部进程;共享网关的访问控制、凭据保护及播放鉴权由部署方负责。 + +自管模式遗留进程的随机密码不提供给新宿主,不能直接用此模式接管;需先部署使用已知凭据的独立网关。工具部署步骤及临时 YAML 配置仅适用于自管模式。 + ### MediaMTX 配置 -MediaMTX 的配置由服务生成,不支持用户提供的 MediaMTX JSON 配置文件。 +自管模式的 MediaMTX 配置由服务生成,不支持用户提供的 MediaMTX JSON 配置文件。 服务关闭 RTSP、RTMP、HLS、SRT、MoQ 等监听器,并配置本机 Control API 和 WebRTC。 -端口和摄像头通过 `MediaMtxOptions` 选项设置;服务将配置写入临时 YAML 文件供子进程启动, -摄像头源地址和内部 API 密码仅通过子进程环境传递。正常停止时会清理临时文件, -强制终止进程时可能无法清理。 -服务将子进程日志限制到标准输出并丢弃,不转发可能含源凭据的输出。 +端口和摄像头通过 `MediaMtxOptions` 选项设置;服务将配置写入当前用户私有目录的 YAML 文件供子进程启动, +摄像头源地址通过子进程环境传递,不写入 YAML。服务禁用 MediaMTX 日志目的地,避免输出可能包含源凭据的日志。 ## UI 动态登记 @@ -201,7 +263,7 @@ MediaMTX 的配置由服务生成,不支持用户提供的 MediaMTX JSON 配 如果 nginx 已将公开地址反向代理到本机 WebRTC HTTP 端口,可在 `MediaMtxOptions` 配置节设置 `"WebRtcPublicUrl": "https://example.com/mediamtx/"`,返回的地址将以该基址开头。 支持带路径前缀的绝对 HTTP/HTTPS 地址,不允许包含凭据、查询字符串或片段;未设置时使用回环地址。 -服务同时允许该地址的来源访问 WebRTC 信令。单路 `PlayUrl` 不改变允许的来源或 ICE 配置,应与 `WebRtcPublicUrl` 对应的反向代理配置一致。代理需要正确转发播放页面、WHEP 请求及会话地址; +自管模式同时允许该地址的来源访问 WebRTC 信令;外部网关需由部署方配置允许的来源。单路 `PlayUrl` 不改变允许的来源或 ICE 配置,应与 `WebRtcPublicUrl` 对应的反向代理配置一致。代理需要正确转发播放页面、WHEP 请求及会话地址; 路径前缀场景还需正确处理上游 `Location` 响应头。 `RemoveAsync(path)` 显式删除路径并影响所有观看者;关闭播放器不会自动删除路径。 默认实现删除成功返回 `true`,失败(包括路径不存在)抛出异常;自定义实现可能返回 `false`。 @@ -211,7 +273,7 @@ MediaMTX 的配置由服务生成,不支持用户提供的 MediaMTX JSON 配 请求取消或超时时,网关可能已经完成变更,调用方应核实状态,不要盲目重复登记。 登记成功仅表示配置被网关接受,不代表摄像头在线或凭据正确。 -动态配置保存在 MediaMTX 内存中,停止或重启后清空,宿主需要自行安全持久化并在启动后恢复;`Cameras` 中的静态配置会在启动时重新加载。 +动态配置保存在 MediaMTX 内存中,停止或重启后清空,宿主需要自行安全持久化并在启动后恢复;自管网关启动时会重新加载 `Cameras` 中的静态配置。 ## 声音 @@ -227,12 +289,12 @@ UI 必须通过 HTTPS 与服务端通信。调用方负责身份认证、摄像 流路径不是访问令牌;当前播放端允许本机读取,内置服务不提供多租户播放鉴权。 不要直接将 Control API 反向代理给浏览器。 -HTTP、Control API、UDP ICE 只监听 `127.0.0.1`。默认返回 URL 中的回环地址指浏览器所在设备。 +自管网关的 HTTP、Control API、UDP ICE 只监听 `127.0.0.1`。默认返回 URL 中的回环地址指浏览器所在设备。 `WebRtcPublicUrl` 仅改变返回的播放 URL 和允许的信令来源,不会配置 nginx 或更改 ICE 地址; 普通 HTTP 反向代理不能单独使远程浏览器访问回环 UDP ICE,远程播放还需可达的媒体路径和鉴权。 摄像头管理不属于 iframe 播放组件的职责。 -## 工具部署与进程生命周期 +## 自管模式:工具部署与进程生命周期 MediaMTX 可执行文件和许可证由独立的 `BootstrapBlazor.MediaMtx.Cli` 按目标 RID 准备并复制,核心包不附带原生工具。也可全局安装 CLI,在编译或发布后的应用目录手动执行: @@ -254,7 +316,7 @@ bb-mediamtx --copy --rid linux-arm64 --output .\publish 从 MSBuild 调用时,若 `MediaMtxRidArgument` 仅包含 RID 值,使用 `--rid "$(MediaMtxRidArgument)"`;若属性已包含 `--rid` 和 RID,直接传入该属性。Build 或 Publish 输出目录需通过 `--output` 显式指定;Windows 上目录末尾反斜杠可能转义结束引号,可分别使用 `"$([MSBuild]::EnsureTrailingSlash('$(TargetDir)'))."` 或 `"$([MSBuild]::EnsureTrailingSlash('$(PublishDir)'))."`。 -CLI 准备固定版本 MediaMTX `1.21.4`,缓存位于本机应用数据目录的 `BootstrapBlazor\mediamtx\v\`。`--download` 只检查或下载缓存,未传 `--rid` 时准备本机平台,传入具体 RID 时准备指定平台,传入 `--rid all` 时准备全部平台;下载时显示进度,准备全部平台时单个平台失败会提示并继续处理其他平台。`--copy` 只从已校验缓存复制,不联网;未传 `--rid` 时复制本机平台。两者组合且传入 `--rid all` 时准备全部平台,只复制本机平台;`all` 不能单独用于 `--copy`。显式传入空 RID 时按本机系统和架构选择。 +CLI 准备固定版本 MediaMTX `1.22.0`,缓存位于本机应用数据目录的 `BootstrapBlazor\mediamtx\v\`。`--download` 只检查或下载缓存,未传 `--rid` 时准备本机平台,传入具体 RID 时准备指定平台,传入 `--rid all` 时准备全部平台;下载时显示进度,准备全部平台时单个平台失败会提示并继续处理其他平台。`--copy` 只从已校验缓存复制,不联网;未传 `--rid` 时复制本机平台。两者组合且传入 `--rid all` 时准备全部平台,只复制本机平台;`all` 不能单独用于 `--copy`。显式传入空 RID 时按本机系统和架构选择。 `--copy` 将工具及 `LICENSE.MediaMTX` 复制到 `--output` 指定目录(默认当前工作目录)的 `mediamtx-tools\`,已存在的文件默认不覆盖;两个文件都存在时直接结束,不校验缓存。`--copy --force` 覆盖两个文件,但不强制下载。无参数时同样只从缓存补齐缺失文件。 普通 NuGet restore 不下载 MediaMTX;运行时不安装 CLI 或下载工具。离线环境需提前安装 CLI 并通过 `--download` 准备目标 RID 缓存。`--download` 在缓存无效时下载并验证 SHA-256;CLI 失败或取消时输出警告并以成功状态退出,不阻断构建或发布,需检查警告并确认工具已部署。 例如 Windows x64 工具位于 `mediamtx-tools\win-x64\mediamtx.exe`,许可证位于 `mediamtx-tools\win-x64\LICENSE.MediaMTX`;Linux ARMv7 工具位于 `mediamtx-tools\linux-arm\mediamtx`。默认启动路径按运行时操作系统及系统架构选择。 @@ -265,13 +327,14 @@ CLI 准备固定版本 MediaMTX `1.21.4`,缓存位于本机应用数据目录 Linux 和 macOS 没有扩展名,例如 `/opt/mediamtx/mediamtx`。相对路径以应用目录为基准。 默认或自定义路径找不到工具时向 `EnsureStartedAsync` 调用方报告异常;服务不会自动部署。 在 Linux/macOS 上执行 CLI 时会自动设置工具执行权限;从 Windows 跨平台发布后,需要在目标机器设置执行权限,例如 Linux x64 使用 `chmod a+x mediamtx-tools/linux-x64/mediamtx`。 -启动时在 10 秒内重试已认证的 Control API 请求,不依赖子进程日志。只有子进程仍在运行且 Control API 返回 HTTP 200,网关才标记为就绪。 +启动或复用时在 10 秒内重试已认证的 Control API 请求,不依赖子进程日志。只有进程仍在运行且 Control API 返回 HTTP 200,网关才标记为就绪。 就绪日志包含 PID、工具路径、WebRTC 基址和 ICE 地址,不包含摄像头源或凭据。 -进程启动、就绪探测失败或超时时向 `EnsureStartedAsync` 调用方报告异常,并清理本次启动的进程和临时配置文件;失败后可重新调用。默认服务仅支持异步释放;宿主需异步释放服务容器以回收自有进程和临时配置文件,清理失败记录错误日志。 -默认启动器使用 .NET `Process` 启动进程,主包负责管理和停止;宿主被强制终止时不保证自动回收 MediaMTX。 -重复调用启动入口会复用本宿主的运行中进程,不会重启。 -服务不终止或接管其他宿主及手动启动的实例,因为其 Control API 凭据不属于当前宿主;若占用配置端口会报告错误,不中断已有播放。 +摄像头登记或更新成功后只记录操作类型,不记录 RTSP 源地址或摄像头凭据。 +服务在当前用户本机应用数据目录的 `BootstrapBlazor\mediamtx-gateways` 中保存进程身份、配置指纹和随机 API 密码;目录限制为当前用户访问,但同一用户及特权管理员仍可能读取凭据。不要共享、复制或提交这些文件。 +同一用户的多个宿主通过文件锁协调启动,核对进程 PID、启动时间、可执行文件路径、配置指纹及 API 认证后复用。不同工具内容、端口、公开地址或静态摄像头配置不会被自动合并;配置不同时启动失败,不会停止已有网关。 +宿主正常或异常退出后网关仍运行,供后续宿主复用;服务释放不会停止进程或删除共享状态。需要停止或更改配置时,先确认日志中的 PID 属于该网关,再手动停止对应进程,之后重新启动应用。停止网关会中断所有观看者;共享的动态路径不会因宿主退出而删除。 +服务不接管没有共享状态记录的旧版本网关、手动启动的实例或其他用户的实例;端口被占用时报告错误,不中断已有播放。升级前遗留进程需手动停止一次。进程启动或就绪探测失败时会尝试清理本次启动的进程;失败后可重新调用。 启动前检查 WebRTC HTTP、Control API 的 TCP 端口和 ICE 的 UDP 端口是否可绑定。 地址仍不可用或被其他进程占用时记录错误日志,并向 `EnsureStartedAsync` 调用方报告失败;应检查端口配置及占用情况,处理后重试。 端口检查与进程启动之间仍可能发生竞争,此时同样记录错误日志并给出处理提示。 -网关配置修改后需要重启应用。程序不在后台持续重启崩溃的 MediaMTX;再次调用 `EnsureStartedAsync` 会尝试重新启动,动态摄像头需重新登记。 +程序不在后台持续重启崩溃的 MediaMTX;再次调用 `EnsureStartedAsync` 会尝试重新启动,动态摄像头需重新登记。 diff --git a/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md b/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md index d9f2ca0b..18d791ea 100644 --- a/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md +++ b/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md @@ -29,19 +29,21 @@ builder.Services.AddMediaMtxService(); ``` - `BootstrapBlazor.MediaMtx` 核心包负责网关进程生命周期和摄像头管理,不附带原生工具;`BootstrapBlazor.MediaMtx.Cli` 负责按目标 RID 准备并复制可执行文件和许可证。CLI 不读取或修改工程,不创建或更新工具清单,也不生成或清理构建规则。宿主可维护本地工具清单,手动还原 CLI 并使用 `dotnet bb-mediamtx --copy --output <输出目录>`;跨平台传入 `--rid`。 -- CLI 的 `--download` 只准备缓存并在下载时显示进度;未传 `--rid` 时准备本机平台,传入具体 RID 时准备指定平台,传入 `--rid all` 时准备全部平台,单个平台失败会提示并继续处理其他平台。`--copy` 只从已校验缓存复制,不联网,未传 `--rid` 时复制本机平台。两者组合且传入 `--rid all` 时准备全部平台,只复制本机平台;`all` 不能单独用于 `--copy`。显式传入空 RID 时使用本机平台。固定版本 `1.21.4` 的缓存位于本机应用数据目录的 `BootstrapBlazor\mediamtx\v\`,下载需校验 SHA-256。 +- CLI 的 `--download` 只准备缓存并在下载时显示进度;未传 `--rid` 时准备本机平台,传入具体 RID 时准备指定平台,传入 `--rid all` 时准备全部平台,单个平台失败会提示并继续处理其他平台。`--copy` 只从已校验缓存复制,不联网,未传 `--rid` 时复制本机平台。两者组合且传入 `--rid all` 时准备全部平台,只复制本机平台;`all` 不能单独用于 `--copy`。显式传入空 RID 时使用本机平台。固定版本 `1.22.0` 的缓存位于本机应用数据目录的 `BootstrapBlazor\mediamtx\v\`,下载需校验 SHA-256。 - CLI 失败或取消时输出警告并以成功状态退出,不阻断宿主构建或发布;需检查警告并确认工具已部署。 - CLI 将工具和许可证部署到 `--output` 指定目录下的 `mediamtx-tools\`,默认使用当前工作目录,不自动查询工程输出目录;无参数或仅 `--copy` 时,默认两者都存在即结束,不读取内容或检查缓存,缺文件时只从缓存补齐缺失文件。升级或修复使用 `--copy --force`,校验缓存后覆盖两个输出文件,不强制重新下载。普通 NuGet restore 不下载 MediaMTX;运行时不安装 CLI 或下载工具。 - MSBuild 调用时,`MediaMtxRidArgument` 若只包含 RID 值,使用 `--rid "$(MediaMtxRidArgument)"`;若已包含 `--rid` 和 RID,则直接传入该属性。Build、Publish 输出目录需通过 `--output` 显式指定;为避免 Windows 路径末尾反斜杠转义引号,可使用 `"$([MSBuild]::EnsureTrailingSlash('$(TargetDir)'))."` 或 `"$([MSBuild]::EnsureTrailingSlash('$(PublishDir)'))."`。 - 网关按使用场景启动,不通过后台托管服务启动。HikVision 引用本包,`HikVisionWebRtc.Options` 使用 `MediaMtxCameraOptions`。组件首次交互渲染时依次调用 `IMediaMtxService.EnsureStartedAsync()` 和 `AddOrUpdateAsync()`,完成前显示黑底占位,完成后显示 iframe;预渲染不会触发。自定义服务需实现启动和登记方法。工具部署、进程管理及 Control API 请求都属于 MediaMtx 服务,组件只负责展示。 -- `EnsureStartedAsync` 串行检查并复用本宿主的运行中进程;工具缺失时抛出异常,需手动部署后重试。网关就绪最多等待 10 秒;取消或失败抛出异常,后续可重试。自定义实现也应在启动失败时抛出异常。 +- 自管模式的 `EnsureStartedAsync` 使用文件锁协调同一用户的宿主,核对进程身份、配置指纹及 API 认证后复用网关;配置不同则报错,不终止已有进程。工具缺失时抛出异常,需手动部署后重试。网关就绪最多等待 10 秒;取消或失败抛出异常,后续可重试。 +- `UseExternalGateway` 默认 `false`;设为 `true` 时连接独立部署的本机网关,只访问 `http://127.0.0.1:/v3/`。通过 `ExternalApiUserName`(默认 `gateway`)和安全配置源中的 `ExternalApiPassword` 进行 HTTP Basic 认证。外部网关必须自行配置监听、API 权限、WebRTC、ICE 和播放鉴权;本服务不启动、停止或修改其进程配置。 +- 外部模式每次 `EnsureStartedAsync` 检查 Control API;首次连接、检测到网关启动时间变化或连接失败后的重连会通过 API 新增或更新 `Cameras` 中的路径,忽略值中的 `Path` 和 `PlayUrl`。多个宿主须协调路径,更新会影响所有观看者;登记失败或取消不回滚已完成的变更。其他动态配置需由宿主自行恢复。自管模式遗留进程的随机密码不可供新宿主接管。 - `MediaMtxPath` 默认为应用目录下的 `mediamtx-tools\<平台-架构>\<可执行文件>`,例如 `mediamtx-tools\win-x64\mediamtx.exe`;可通过配置指定其他路径,相对路径以应用目录为基准。在 Linux/macOS 上执行 CLI 会自动设置执行权限;从 Windows 跨平台发布后需在目标机器设置执行权限。 - `AddMediaMtxService` 同时注册默认进程启动器和主服务,从 `MediaMtxOptions` 配置节绑定选项,也支持通过 `configureOptions` 回调覆盖选项。默认服务使用 `IOptions`,配置变更后需重启应用。自行实现 `IMediaMtxProcessLauncher` 时,在调用 `AddMediaMtxService` 前注册该接口,默认启动器不会覆盖已有注册;启动器使用服务提供的 `ProcessStartInfo` 启动并返回进程,服务负责就绪探测和清理。不支持的操作系统或系统架构会记录警告,并由 `EnsureStartedAsync` 调用报告启动失败。 - WebRTC 页面和 Control API 分别使用 TCP 端口 8889、9997,ICE 使用 UDP 端口 8189;HTTP 与 Control API 端口应不同。 -- `MediaMtxOptions:Cameras` 是以播放路径为键的静态摄像头字典,值提供 `RtspUrl` 和可选的 `UserName`、`Password`;生成静态网关配置时忽略值中的 `Path` 和 `PlayUrl`。网关启动时自动配置,无需手动调用 `AddOrUpdateAsync`。密码可通过 User Secrets 提供;环境变量(如 `MediaMtxOptions__Cameras__hikvision__Password`)可能被 MediaMTX 子进程继承,需评估访问权限。修改后重启应用。 -- MediaMTX 配置由服务生成,不支持用户提供的 MediaMTX JSON 配置文件。服务生成临时 YAML,摄像头源地址和内部 API 密码仅通过子进程环境传递;就绪探测使用已认证的 Control API 请求,不依赖子进程日志。 +- `MediaMtxOptions:Cameras` 是以播放路径为键的静态摄像头字典,值提供 `RtspUrl` 和可选的 `UserName`、`Password`;自管网关启动时或首次连接外部网关时自动配置,无需手动调用 `AddOrUpdateAsync`。密码可通过 User Secrets 提供;环境变量(如 `MediaMtxOptions__Cameras__hikvision__Password`)可能被 MediaMTX 子进程继承,需评估访问权限。自管网关配置变更需先停止旧网关。 +- 自管模式的 MediaMTX 配置由服务生成,不支持用户提供的 MediaMTX JSON 配置文件。YAML 保存在当前用户私有目录,不含摄像头源地址;就绪探测使用已认证的 Control API 请求,不依赖子进程日志。外部网关由部署方配置。 - 工具缺失、启动或就绪探测失败时默认实现向 `EnsureStartedAsync` 调用方抛出异常;服务不会安装工具,后续调用可重试。网关未运行时,有效的摄像头登记和删除调用抛出 `InvalidOperationException`。 -- 默认服务仅支持异步释放;宿主异步释放服务容器时会尝试回收自有 MediaMTX 进程和临时配置文件。重复启动请求复用本服务的运行中实例,不终止或接管其他宿主、手动启动的实例;端口被占用时报告错误,不中断已有播放。进程退出后,再次调用 `EnsureStartedAsync` 可尝试重启;动态摄像头需重新登记。 +- 自管网关在宿主正常或异常退出后继续运行;停止或更改配置前确认网关 PID,再手动停止对应进程,其他观看者会中断。进程身份、配置指纹和 API 密码保存在当前用户私有的本机应用数据目录 `BootstrapBlazor\mediamtx-gateways`;同一用户及特权管理员可能读取,不要共享或提交。无共享记录的旧版本网关、手动实例及其他用户实例不会被接管,端口占用时需自行处理。网关退出后再次调用 `EnsureStartedAsync` 可尝试重启;动态摄像头需重新登记。 - 本包只支持 MediaMTX,不支持其他 RTSP 转流工具。 ## 摄像头管理 @@ -51,15 +53,16 @@ builder.Services.AddMediaMtxService(); - 调用方应校验唯一播放路径 `MediaMtxCameraOptions.Path`:建议以小写字母开头,只允许小写字母、数字和连字符,最长 63 个字符,排除 `all`。默认服务仅检查动态登记的路径非空;删除时传入已登记的路径。 - 默认服务要求 `RtspUrl` 为不含用户信息且包含主机名的绝对 RTSP/RTSPS 地址;建议显式指定端口和流路径,不要在查询字符串中放置凭据。`UserName`、`Password` 使用未编码的原始值;没有用户名时密码会被忽略。 - `IMediaMtxService.AddOrUpdateAsync(camera)` 登记新路径或更新已有路径的源和凭据,默认实现成功返回播放 URL、失败抛出异常;自定义实现可返回 `null`,调用方应检查结果。HikVision 通过 `Options` 传入摄像头配置并在内部调用服务。成功只表示网关接受配置,不代表摄像头已连通;更新可能中断现有播放。 +- 默认服务在登记成功后记录 RTSP 源地址和 WebRTC 播放地址,省略用户名、密码、查询字符串和片段;不要将凭据放在 URL 路径中。 - 默认服务记住当前网关中已成功登记或更新的路径,后续优先更新;路径状态不一致时以网关为准。 - `RemoveAsync(path)` 显式删除路径并影响所有观看者。默认实现成功返回 `true`、失败抛出异常;自定义实现可返回 `false`。关闭页面不会删除路径。 -- 多路摄像头使用不同路径,共用一个网关;首次观看时通过 RTSP/TCP 按需拉流。动态配置只保存在 MediaMTX 内存中,重启后需由宿主恢复;`Cameras` 中的静态配置会在启动时重新加载。 +- 多路摄像头使用不同路径,共用一个网关;首次观看时通过 RTSP/TCP 按需拉流。动态配置只保存在 MediaMTX 内存中,重启后需由宿主恢复;自管网关启动时重新加载 `Cameras` 中的静态配置。 - 启动、登记和删除操作支持 `CancellationToken`;登记或删除取消、超时后网关可能已经完成变更,应核实状态后再重试。 - `SetGatewayStateAsync` 仅供宿主同步网关状态,业务代码不要调用。 ## 播放与声音 -- 摄像头 `PlayUrl` 不为 `null` 时使用该完整 HTTP/HTTPS 地址(不允许凭据,空字符串无效);为 `null` 时默认返回 `http://127.0.0.1://`。可设置 `WebRtcPublicUrl` 为反向代理基址,默认播放地址和允许的信令来源随之调整。单路 `PlayUrl` 不改变允许的来源,应与公开基址的代理配置对应。HTTP、Control API 和 ICE 仍仅监听回环地址;远程播放需另行配置可达的媒体路径、HTTPS 与鉴权。 +- 摄像头 `PlayUrl` 不为 `null` 时使用该完整 HTTP/HTTPS 地址(不允许凭据,空字符串无效);为 `null` 时默认返回 `http://127.0.0.1://`。可设置 `WebRtcPublicUrl` 为反向代理基址,自管网关的默认播放地址和允许的信令来源随之调整;外部网关的信令来源需自行配置。单路 `PlayUrl` 不改变允许的来源,应与公开基址的代理配置对应。自管网关的 HTTP、Control API 和 ICE 仅监听回环地址;远程播放需另行配置可达的媒体路径、HTTPS 与鉴权。 - MediaMTX 在此方案中转发协议,不自动转码。摄像头需启用音频并选择浏览器支持的 WebRTC 编码,例如 G.711 μ-law(PCMU)或 A-law(PCMA);AAC 等不兼容编码需另行转码。 - MediaMTX 播放页默认静音,用户需在播放器中取消静音。无声音时还应检查摄像头的音频配置及源流。 @@ -67,7 +70,7 @@ builder.Services.AddMediaMtxService(); - UI 应通过 HTTPS 访问;调用方负责身份认证、摄像头级权限和 RTSP 目标地址白名单,不要把服务暴露为匿名内网代理。 - 凭据通过 `UserName`、`Password` 传原始值,不要写入 URL、日志或浏览器存储。 -- Control API 使用内部随机密码,不要反向代理给浏览器;播放路径不是访问令牌,本机读取不提供多租户播放鉴权。 +- 自管网关的 Control API 使用内部随机密码;外部网关需由部署方保护 API 凭据并限制访问。不要将 Control API 反向代理给浏览器;播放路径不是访问令牌,自管网关的本机读取不提供多租户播放鉴权。 以文档中的公开签名为准,优先读取当前项目实际还原版本的文档,不要凭记忆编造 API。资料缺失时说明缺口,不要猜测。