diff --git a/BootstrapBlazor.Extensions.slnx b/BootstrapBlazor.Extensions.slnx index b3561e51..21f26d47 100644 --- a/BootstrapBlazor.Extensions.slnx +++ b/BootstrapBlazor.Extensions.slnx @@ -43,6 +43,7 @@ + @@ -78,7 +79,6 @@ - diff --git a/src/extensions/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj b/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj similarity index 87% rename from src/extensions/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj rename to src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj index e4f2330f..0d24fb23 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj +++ b/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj @@ -1,7 +1,7 @@ - 11.0.0 + 11.0.1 bb-mediamtx @@ -12,11 +12,11 @@ - + - + diff --git a/src/extensions/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs b/src/components/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs similarity index 100% rename from src/extensions/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs rename to src/components/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs diff --git a/src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs b/src/components/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs similarity index 81% rename from src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs rename to src/components/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs index c37d3280..d0b14fa0 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs +++ b/src/components/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs @@ -22,8 +22,8 @@ public interface IMediaMtxProcessLauncher bool IsSupported { get; } /// - /// 使用宿主提供的配置启动 MediaMTX 进程。 - /// Starts the MediaMTX process using the host-provided configuration. + /// 使用服务提供的配置启动 MediaMTX 进程。默认服务负责就绪探测和清理返回的进程。 + /// Starts the MediaMTX process using the service-provided configuration. The default service probes readiness and cleans up the returned process. /// 11.0.0 /// /// 进程启动配置。The process start configuration. diff --git a/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs b/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs new file mode 100644 index 00000000..af7cef44 --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs @@ -0,0 +1,55 @@ +// 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 + +namespace BootstrapBlazor.Components; + +/// +/// 服务端动态摄像头管理。调用方负责身份认证、权限检查和 RTSP 目标地址的访问策略。 +/// Server-side dynamic camera management. Callers must enforce authentication, authorization and RTSP destination access policies. +/// 默认实现处理有效的摄像头登记和删除请求时,若网关未运行则抛出 。 +/// The default implementation throws for valid camera registration and deletion requests when the gateway is not running. +/// 11.0.0 +/// +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. + /// 11.0.0 + /// + /// 取消令牌。The cancellation token. + /// 网关就绪时完成的任务。A task that completes when the gateway is ready. + /// 默认实现找不到网关工具。The default implementation cannot find the gateway tool. + Task EnsureStartedAsync(CancellationToken cancellationToken = default); + + /// + /// 由宿主设置已就绪网关的 Control API 密码;传入 null 表示网关已停止。 + /// Sets the Control API password for the ready gateway; null indicates that the gateway has stopped. Intended for use by the host. + /// 11.0.0 + /// + /// 网关密码,或表示停止的 null。The gateway password, or null when stopped. + /// 状态更新成功时为 true;默认实现更新状态并清除已登记路径记录。True when the state is updated; the default implementation updates the state and clears its registered path records. + Task SetGatewayStateAsync(string? apiPassword); + + /// + /// 登记新路径或更新已有路径的摄像头源配置,返回播放 URL。摄像头 PlayUrl 为 null 时使用 WebRtcPublicUrl 或同机回环地址与 Path 生成地址;空字符串不是有效的播放地址。更新可能中断现有播放;成功不代表源已连通。 + /// Registers a new path or updates the camera source configuration and returns its playback URL. When the camera's PlayUrl is null, builds the URL from WebRtcPublicUrl or the loopback address and Path; an empty string is not a valid playback URL. Updates may interrupt existing playback; success does not verify source connectivity. + /// 11.0.0 + /// + /// 由管理 UI 提交的摄像头配置。Camera configuration submitted by the management UI. + /// 取消令牌。The cancellation token. + /// 播放 URL;自定义实现可返回 null 表示登记失败。默认实现失败时抛出异常。The playback URL; custom implementations may return null on failure. The default implementation throws on failure. + Task AddOrUpdateAsync(MediaMtxCameraOptions camera, CancellationToken cancellationToken = default); + + /// + /// 显式删除摄像头路径,影响所有观看者;默认实现删除不存在的路径时抛出异常。 + /// Explicitly deletes a camera path for all viewers. The default implementation throws when the path does not exist. + /// 11.0.0 + /// + /// 要删除的摄像头路径。The camera path to delete. + /// 取消令牌。The cancellation token. + /// 删除成功时为 true;自定义实现可返回 false 表示失败,默认实现失败时抛出异常。True when deleted; custom implementations may return false on failure, while the default implementation throws. + Task RemoveAsync(string path, CancellationToken cancellationToken = default); +} diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs new file mode 100644 index 00000000..72bc1d75 --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs @@ -0,0 +1,49 @@ +// 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 + +namespace BootstrapBlazor.Components; + +/// +/// 由服务端配置或 UI 提供的摄像头配置,不应持久化到浏览器或写入日志。 +/// Camera configuration supplied by server-side configuration or UI. Do not persist it in the browser or write it to logs. +/// 11.0.0 +/// +public sealed class MediaMtxCameraOptions +{ + /// + /// 获得/设置唯一的播放路径。建议调用方限制为小写字母开头,后接小写字母、数字或连字符,最长 63 个字符,排除名称 all;默认服务仅检查非空。例如:camera01 + /// Gets or sets the unique playback path. Callers should restrict it to a lowercase letter followed by lowercase letters, digits or hyphens, up to 63 characters, excluding all; the default service only checks that it is nonempty. For example: camera01 + /// 11.0.0 + /// + public string? Path { get; set; } + + /// + /// 获得/设置浏览器访问的完整 HTTP 或 HTTPS 播放页面地址,不应包含凭据。为 null 时使用网关 WebRtcPublicUrl 或本机地址与 Path 生成播放地址;空字符串无效。此选项不改变网关监听和 ICE 配置。 + /// Gets or sets the complete browser-facing HTTP or HTTPS player URL without credentials. When null, the URL is built from WebRtcPublicUrl or the loopback address and Path; an empty string is invalid. This option does not change listener or ICE configuration. + /// 11.0.1 + /// + public string? PlayUrl { get; set; } + + /// + /// 获得/设置不含用户信息的绝对 RTSP 或 RTSPS 地址,必须包含主机名。建议显式指定端口和流路径,不要在查询字符串中放置凭据。例如:rtsp://192.168.1.100:554/Streaming/Channels/101 + /// Gets or sets the absolute RTSP or RTSPS URL with a host and without user information. Specify the port and stream path explicitly, and do not put credentials in the query string. For example: rtsp://192.168.1.100:554/Streaming/Channels/101 + /// 11.0.0 + /// + public string? RtspUrl { get; set; } + + /// + /// 获得/设置未进行 URL 编码的摄像头用户名。 + /// Gets or sets the camera user name without URL encoding. + /// 11.0.0 + /// + public string? UserName { get; set; } + + /// + /// 获得/设置未进行 URL 编码的摄像头密码。未提供用户名时默认服务忽略密码。 + /// Gets or sets the camera password without URL encoding. The default service ignores the password when no user name is supplied. + /// 11.0.0 + /// + public string? Password { get; set; } +} diff --git a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs similarity index 79% rename from src/extensions/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs rename to src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs index 51f8cf1d..fe07287f 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs @@ -8,8 +8,8 @@ namespace BootstrapBlazor.Components; /// -/// 从服务器配置的 MediaMtx 节读取的 MediaMTX 网关选项。 -/// MediaMTX gateway options bound from the server's MediaMtx configuration section. +/// 从服务器配置的 MediaMtxOptions 节读取的 MediaMTX 网关选项。 +/// MediaMTX gateway options bound from the server's MediaMtxOptions configuration section. /// 11.0.0 /// public sealed class MediaMtxOptions @@ -22,15 +22,15 @@ public sealed class MediaMtxOptions public int ApiPort { get; set; } = 9997; /// - /// 获得/设置网关启动时自动登记的摄像头,键为播放路径,值中的 Path 被忽略。密码应通过 User Secrets 或环境变量等安全配置源提供。 - /// Gets or sets the cameras registered automatically when the gateway starts. Keys are playback paths, and the Path value of each entry is ignored. Supply passwords through a secure configuration source such as User Secrets or environment variables. + /// 获得/设置网关启动时配置的摄像头,键为播放路径,值中的 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. /// 11.0.0 /// public Dictionary Cameras { get; set; } = new(); /// - /// 获得/设置 MediaMTX 可执行文件路径,默认按当前系统和架构选择应用目录 mediamtx-tools 子目录下的工具。相对路径以应用目录为基准,文件不存在时不启动网关。 - /// Gets or sets the MediaMTX executable path. By default, the tool is selected under the application directory's mediamtx-tools subdirectory according to the current OS and architecture. Relative paths are resolved against the application directory; the gateway is not started when the file does not exist. + /// 获得/设置 MediaMTX 可执行文件路径,默认按当前系统和架构选择应用目录 mediamtx-tools 子目录下的工具。相对路径以应用目录为基准;工具需预先手动部署。 + /// Gets or sets the MediaMTX executable path. Defaults to the current platform's tool under the application's mediamtx-tools directory. Relative paths use the application directory; the tool must be deployed manually in advance. /// 11.0.0 /// public string MediaMtxPath { get; set; } = Path.Combine("mediamtx-tools", diff --git a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxProcessLauncher.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxProcessLauncher.cs similarity index 100% rename from src/extensions/BootstrapBlazor.MediaMtx/MediaMtxProcessLauncher.cs rename to src/components/BootstrapBlazor.MediaMtx/MediaMtxProcessLauncher.cs diff --git a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxHostedService.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs similarity index 78% rename from src/extensions/BootstrapBlazor.MediaMtx/MediaMtxHostedService.cs rename to src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs index 747564c4..f331875e 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxHostedService.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs @@ -3,10 +3,7 @@ // See the LICENSE file in the project root for more information. // Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System.ComponentModel; using System.Diagnostics; using System.Net; using System.Net.Sockets; @@ -16,50 +13,48 @@ namespace BootstrapBlazor.Components; -sealed class MediaMtxHostedService(IOptions options, ILogger logger, IMediaMtxService service, IMediaMtxProcessLauncher launcher) : BackgroundService +sealed partial class MediaMtxService { private const string Loopback = "127.0.0.1"; - private const string ReleaseUrl = "https://github.com/bluenviron/mediamtx/releases"; private const string RestartHint = "Check the port configuration and stop any other process occupying the address, then restart the application."; private static readonly TimeSpan _startupTimeout = TimeSpan.FromSeconds(10); private static readonly TimeSpan _probeInterval = TimeSpan.FromMilliseconds(100); private static readonly TimeSpan _stopTimeout = TimeSpan.FromSeconds(5); private Process? _process; private string? _configPath; + private readonly SemaphoreSlim _startupGate = new(1, 1); + private readonly CancellationTokenSource _stopping = new(); - /// - /// - /// - protected override async Task ExecuteAsync(CancellationToken stoppingToken) + public async Task EnsureStartedAsync(CancellationToken cancellationToken = default) { + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _stopping.Token); + await _startupGate.WaitAsync(linked.Token); try { - if (await StartGatewayAsync(stoppingToken)) + linked.Token.ThrowIfCancellationRequested(); + if (_process is { HasExited: false }) { return; } + + await StopGatewayAsync(); + try + { + if (!await StartGatewayAsync(linked.Token)) + { + throw new InvalidOperationException("The MediaMTX gateway could not be started. Check the server logs."); + } + } + catch + { + await StopGatewayAsync(); + throw; + } } - catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested) - { - logger.LogError("MediaMTX did not become ready within {Timeout} seconds; the RTSP gateway is disabled. Verify the installed MediaMTX version and listener ports. {RestartHint}", - _startupTimeout.TotalSeconds, RestartHint); - } - catch (Exception exception) + finally { - logger.LogError(exception, "Failed to start MediaMTX; the RTSP gateway is disabled. {RestartHint}", RestartHint); + _startupGate.Release(); } - - await StopGatewayAsync(); - } - - /// - /// - /// - public override async Task StopAsync(CancellationToken cancellationToken) - { - await StopGatewayAsync(); - - await base.StopAsync(cancellationToken); } private async Task StartGatewayAsync(CancellationToken cancellationToken) @@ -74,8 +69,7 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) var executable = Path.GetFullPath(settings.MediaMtxPath, AppContext.BaseDirectory); if (!File.Exists(executable)) { - logger.LogWarning("MediaMTX was not found at {MediaMtxPath}; the RTSP gateway is disabled. Download it from {ReleaseUrl}.", executable, ReleaseUrl); - return false; + throw new MediaMtxToolNotFoundException(executable); } var httpAddress = $"{Loopback}:{settings.WebRtcPort}"; @@ -85,8 +79,6 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) var cameraSources = new Dictionary(); var config = CreateConfiguration(settings.Cameras, httpAddress, iceAddress, apiAddress, publicUri, cameraSources); - await StopExistingGatewaysAsync(executable, cancellationToken); - if (!IsPortAvailable(settings.WebRtcPort, ProtocolType.Tcp) | !IsPortAvailable(settings.ApiPort, ProtocolType.Tcp) | !IsPortAvailable(settings.WebRtcIcePort, ProtocolType.Udp)) @@ -123,7 +115,7 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) timeout.Cancel(); } - await service.SetGatewayStateAsync(apiPassword); + 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; @@ -171,39 +163,6 @@ private bool IsPortAvailable(int port, ProtocolType protocol) } } - private async Task StopExistingGatewaysAsync(string executable, CancellationToken cancellationToken) - { - var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - foreach (var process in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(executable))) - { - using (process) - { - string? path; - try - { - if (process.HasExited) - { - continue; - } - path = process.MainModule?.FileName; - } - catch (Exception exception) when (exception is Win32Exception or InvalidOperationException) - { - logger.LogWarning(exception, "Could not inspect MediaMTX process {ProcessId}; it will not be stopped.", process.Id); - continue; - } - - if (!string.Equals(path, executable, comparison)) - { - continue; - } - - logger.LogInformation("Stopping existing MediaMTX process {ProcessId} at {ExecutablePath}.", process.Id, executable); - await StopProcessAsync(process, cancellationToken); - } - } - } - private static async Task StopProcessAsync(Process process, CancellationToken cancellationToken) { if (!process.HasExited) @@ -219,7 +178,7 @@ private static async Task StopProcessAsync(Process process, CancellationToken ca } using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(_stopTimeout); - await process.WaitForExitAsync(timeout.Token); + await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false); } private static string CreateConfiguration(Dictionary cameras, string httpAddress, string iceAddress, @@ -333,13 +292,13 @@ private async Task StopGatewayAsync() { try { - await service.SetGatewayStateAsync(null); + await SetGatewayStateAsync(null).ConfigureAwait(false); if (_process is { } process) { _process = null; using (process) { - await StopProcessAsync(process, CancellationToken.None); + await StopProcessAsync(process, CancellationToken.None).ConfigureAwait(false); } } diff --git a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxService.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs similarity index 75% rename from src/extensions/BootstrapBlazor.MediaMtx/MediaMtxService.cs rename to src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs index 2f5734f7..0cba0ef0 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxService.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. // Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System.Net; using System.Net.Http.Json; @@ -10,7 +11,8 @@ namespace BootstrapBlazor.Components; -sealed class MediaMtxService(IOptions options) : IMediaMtxService, IDisposable +sealed partial class MediaMtxService(IOptions options, ILogger logger, + IMediaMtxProcessLauncher launcher) : IMediaMtxService, IAsyncDisposable { private readonly SemaphoreSlim _gate = new(1, 1); private readonly HashSet _registeredPaths = new(StringComparer.Ordinal); @@ -20,14 +22,16 @@ sealed class MediaMtxService(IOptions options) : IMediaMtxServi Timeout = TimeSpan.FromSeconds(10) }; private string? _apiPassword; + private int _disposeState; - public async Task SetGatewayStateAsync(string? apiPassword) + public async Task SetGatewayStateAsync(string? apiPassword) { - await _gate.WaitAsync(); + await _gate.WaitAsync().ConfigureAwait(false); try { _apiPassword = apiPassword; _registeredPaths.Clear(); + return true; } finally { @@ -35,18 +39,28 @@ public async Task SetGatewayStateAsync(string? apiPassword) } } - public async Task AddOrUpdateAsync(MediaMtxCameraOptions camera, CancellationToken cancellationToken = default) + public async Task AddOrUpdateAsync(MediaMtxCameraOptions camera, CancellationToken cancellationToken = default) { var path = camera.Path; + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("Camera Path is required.", nameof(camera)); + } var source = BuildRtspSourceUrl(camera) ?? throw new ArgumentException("Camera URL must be an absolute RTSP or RTSPS URL.", nameof(camera)); var playerBaseUrl = options.Value.GetWebRtcPublicUri()?.AbsoluteUri ?? $"http://127.0.0.1:{options.Value.WebRtcPort}/"; + var playerUrl = camera.PlayUrl ?? $"{playerBaseUrl}{path}/"; + if (!Uri.TryCreate(playerUrl, UriKind.Absolute, out var player) || + player.Scheme is not ("http" or "https") || player.UserInfo.Length != 0) + { + throw new ArgumentException("Camera PlayUrl must be an absolute HTTP or HTTPS URL without credentials.", nameof(camera)); + } var content = new { source, rtspTransport = "tcp", sourceOnDemand = true }; await _gate.WaitAsync(cancellationToken); try { await AddOrUpdatePathAsync(path, content, cancellationToken); _registeredPaths.Add(path); - return $"{playerBaseUrl}{path}/"; + return playerUrl; } finally { @@ -54,13 +68,14 @@ public async Task AddOrUpdateAsync(MediaMtxCameraOptions camera, Cancell } } - public async Task RemoveAsync(string path, CancellationToken cancellationToken = default) + public async Task RemoveAsync(string path, CancellationToken cancellationToken = default) { await _gate.WaitAsync(cancellationToken); try { await SendAsync(HttpMethod.Delete, $"config/paths/delete/{path}", null, cancellationToken); _registeredPaths.Remove(path); + return true; } finally { @@ -137,8 +152,8 @@ private static async Task IsDuplicatePathAsync(HttpContent content, Cancel internal static string? BuildRtspSourceUrl(MediaMtxCameraOptions camera) { - if (!Uri.TryCreate(camera.Url, UriKind.Absolute, out var source) || - source.Scheme is not ("rtsp" or "rtsps") || source.Host.Length == 0) + if (!Uri.TryCreate(camera.RtspUrl, UriKind.Absolute, out var source) || + source.Scheme is not ("rtsp" or "rtsps") || source.Host.Length == 0 || source.UserInfo.Length != 0) { return null; } @@ -154,9 +169,25 @@ source.Scheme is not ("rtsp" or "rtsps") || source.Host.Length == 0) return url.Insert(authorityStart, credentials); } - public void Dispose() + public async ValueTask DisposeAsync() { - _client.Dispose(); - _gate.Dispose(); + if (Interlocked.Exchange(ref _disposeState, 1) != 0) + { + return; + } + + _stopping.Cancel(); + await _startupGate.WaitAsync().ConfigureAwait(false); + try + { + await StopGatewayAsync().ConfigureAwait(false); + _client.Dispose(); + _gate.Dispose(); + } + finally + { + _startupGate.Release(); + _stopping.Dispose(); + } } } diff --git a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs similarity index 65% rename from src/extensions/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs rename to src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs index e262bc74..c602db95 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs @@ -16,8 +16,8 @@ namespace Microsoft.Extensions.DependencyInjection; public static class MediaMtxServiceCollectionExtensions { /// - /// 从 MediaMtx 配置节绑定选项,并注册默认进程启动器、摄像头管理服务和托管网关。保留已注册的自定义进程启动器;工具由接入的 bb-mediamtx 构建流程准备或由宿主提供,运行时不下载。 - /// Binds options from the MediaMtx configuration section and registers the default process launcher, camera management and a hosted gateway. Preserves an existing custom launcher; prepare tools through the bb-mediamtx build integration or provide them in the host. Runtime does not download tools. + /// 从 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. /// 11.0.0 /// /// 宿主服务集合。The host's service collection. @@ -27,13 +27,16 @@ public static IServiceCollection AddMediaMtxService(this IServiceCollection serv { services.TryAddSingleton(); - var options = services.AddOptions().BindConfiguration("MediaMtx"); - if (configureOptions is not null) + services.AddOptionsMonitor(); + services.Configure(options => { - options.Configure(configureOptions); - } + if (configureOptions is not null) + { + configureOptions(options); + } + }); services.TryAddSingleton(); - return services.AddHostedService(); + return services; } } diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxToolNotFoundException.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxToolNotFoundException.cs new file mode 100644 index 00000000..772f13f2 --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxToolNotFoundException.cs @@ -0,0 +1,25 @@ +// 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 + +namespace BootstrapBlazor.Components; + +/// +/// 找不到 MediaMTX 可执行文件时抛出的异常。默认服务将解析后的绝对路径放在 FileName 中;需部署工具后重试。 +/// The exception thrown when the MediaMTX executable is missing. The default service puts the resolved absolute path in FileName; deploy the tool before retrying. +/// 11.0.1 +/// +public sealed class MediaMtxToolNotFoundException : FileNotFoundException +{ + /// + /// 使用缺失工具的路径创建异常。 + /// Creates an exception with the path to the missing tool. + /// 11.0.1 + /// + /// 工具路径。The tool path. + public MediaMtxToolNotFoundException(string fileName) + : base("MediaMTX was not found. Deploy it manually before starting the gateway; for the default path, run bb-mediamtx --download and then bb-mediamtx --copy in the application directory.", fileName) + { + } +} diff --git a/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md b/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md new file mode 100644 index 00000000..9f429d82 --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md @@ -0,0 +1,277 @@ +# BootstrapBlazor.MediaMtx + +ASP.NET Core 动态 RTSP 摄像头服务。调用方通过 `EnsureStartedAsync` 按需启动 MediaMTX 进程,管理多个播放路径,并按需转发 RTSP 到 WebRTC;HikVision 播放组件在首次交互渲染时调用该服务。 +启动不连接摄像头;首次观看时通过 RTSP/TCP 按需拉流,转发为 WebRTC。 +主包提供默认进程启动器,但不附带 MediaMTX;通过 `bb-mediamtx` CLI 从 GitHub 下载或自行部署工具,详见“工具部署与进程生命周期”。 + +## 安装 + +在服务端项目中安装: + +```powershell +dotnet add package BootstrapBlazor.MediaMtx +``` + +## 注册与网关配置 + +```csharp +// 仅注册服务;调用 EnsureStartedAsync 时启动网关: +builder.Services.AddMediaMtxService(); +``` + +```json +{ + "MediaMtxOptions": { + "WebRtcPort": 8889, + "WebRtcIcePort": 8189, + "ApiPort": 9997, + "Cameras": { + "hikvision": { + "RtspUrl": "rtsp://192.0.2.1:554/stream", + "UserName": "camera" + }, + "gate": { + "RtspUrl": "rtsp://192.0.2.2:554/stream", + "UserName": "camera" + } + } + } +} +``` + +`Cameras` 是可选的静态摄像头字典,网关启动时自动登记,无需调用 `AddOrUpdateAsync`。 +键即播放路径,值使用不含用户信息的 `RtspUrl` 和可选的 `UserName`、`Password`;值中的 `Path` 和 `PlayUrl` 在生成静态网关配置时被忽略。 +密码应通过 User Secrets 等安全配置源提供,不要提交到 `appsettings.json`。 +User Secrets 的 `secrets.json` 使用与 `appsettings.json` 相同的层次结构,按路径合并: + +```json +{ + "MediaMtxOptions": { + "Cameras": { + "hikvision": { + "Password": "" + } + } + } +} +``` + +对应的环境变量名为 `MediaMtxOptions__Cameras__hikvision__Password`。ASP.NET Core 默认只在 Development 环境加载 User Secrets。 +**注意**:该环境变量可能被 MediaMTX 子进程继承;使用环境变量时需评估子进程及宿主的访问权限。 +网关通过子进程环境传递包含凭据的源地址,不会将其写入生成的临时配置文件;不要把凭据放在 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` 启动并返回进程,宿主负责就绪探测和清理。 +HTTP 和 Control API 使用不同 TCP 端口,ICE 使用 UDP。 +Control API 仅监听回环地址,使用每个宿主实例生成的内部随机密码,不提供浏览器调用入口。 +`IMediaMtxService.SetGatewayStateAsync` 仅供宿主同步网关状态;自定义实现应在密码为 `null` 时 +停止管理请求,并在网关就绪后使用提供的密码认证 Control API 请求。 + +### WebRTC 首次加载时启动 + +在服务端注册服务;应用启动时不运行网关: + +```csharp +builder.Services.AddMediaMtxService(); +``` + +在已授权的 Interactive Server 页面使用播放器(引用 `BootstrapBlazor.HikVision`,它会依赖本包): + +```razor + + +@code { + private readonly MediaMtxCameraOptions camera = new() + { + Path = "hikvision", + RtspUrl = "rtsp://192.0.2.1:554/stream" + }; +} +``` + +组件只负责展示和调用服务,依次等待 `EnsureStartedAsync()`、`AddOrUpdateAsync(camera)`, +在服务返回播放地址后切换为 iframe。初始化期间显示黑底占位;失败时记录日志并显示错误提示。 +只在首次交互渲染时执行,不在预渲染时执行。HikVision 由本服务管理进程并调用 Control API。 +两个包使用同一个 `MediaMtxCameraOptions` 类型,不支持独立 WASM 宿主。 + +`EnsureStartedAsync()` 串行处理启动请求:本宿主的网关仍在运行时直接复用;未运行时尝试启动; +服务只启动已部署的工具,不自动安装 CLI 或下载;可执行文件缺失时抛出 `MediaMtxToolNotFoundException`(继承自 `FileNotFoundException`),需手动部署后重试。HikVision 预览会显示工具缺失提示及相对应用目录的路径。 +网关就绪最多等待 10 秒;`EnsureStartedAsync` 就绪时完成,取消或失败时抛出异常,后续调用可重试。自定义实现也应在启动失败时抛出异常。 +自定义 `IMediaMtxService` 要支持此接入方式,需实现 `EnsureStartedAsync`。 + +### MediaMTX 配置 + +MediaMTX 的配置由服务生成,不支持用户提供的 MediaMTX JSON 配置文件。 +服务关闭 RTSP、RTMP、HLS、SRT、MoQ 等监听器,并配置本机 Control API 和 WebRTC。 +端口和摄像头通过 `MediaMtxOptions` 选项设置;服务将配置写入临时 YAML 文件供子进程启动, +摄像头源地址和内部 API 密码仅通过子进程环境传递。正常停止时会清理临时文件, +强制终止进程时可能无法清理。 +服务将子进程日志限制到标准输出并丢弃,不转发可能含源凭据的输出。 + +## UI 动态登记 + +在自己的 **Interactive Server** 页面注入 `IMediaMtxService`。以下代码放在已授权的管理页面中; +使用原生 Blazor 表单,不需要把凭据传给播放组件: + +```razor +@using BootstrapBlazor.Components +@inject IMediaMtxService MediaMtx + + + + + + + + +@if (error is not null) +{ +

@error

+} +@if (playerUrl is not null) +{ + +} + +@code { + private readonly MediaMtxCameraOptions camera = new() { Path = "entrance" }; + private string? playerUrl; + private string? error; + private bool busy; + + private async Task ConnectAsync() + { + busy = true; + error = null; + playerUrl = null; + try + { + await MediaMtx.EnsureStartedAsync(); + playerUrl = await MediaMtx.AddOrUpdateAsync(camera); + if (string.IsNullOrEmpty(playerUrl)) + { + playerUrl = null; + error = "登记或更新失败,请检查摄像头配置和网关是否可用。"; + } + } + catch (MediaMtxToolNotFoundException) + { + error = "缺少 MediaMTX 后台工具,请联系管理员部署。"; + } + catch (ArgumentException) + { + error = "请检查摄像头地址和网关播放地址配置。"; + } + catch (HttpRequestException) + { + error = "登记或更新失败,请检查摄像头配置和网关是否可用。"; + } + catch (InvalidOperationException) + { + error = "网关尚未就绪。"; + } + catch (OperationCanceledException) + { + error = "启动或登记操作已取消或超时。"; + } + catch (Exception) + { + error = "启动或登记失败,请检查服务端配置和网关状态。"; + } + finally + { + camera.Password = null; + busy = false; + } + } +} +``` + +此手动管理示例使用原生 iframe;使用 HikVision 时只需传入 `Options`,不要重复调用登记方法。 +`IMediaMtxService.AddOrUpdateAsync(camera)` 按 `Path` 登记新路径或更新已有路径的源和凭据。默认服务对未记录的路径优先新增,对已成功登记或更新的路径优先更新;若网关报告路径已存在或不存在,则改用相应的操作。删除成功或网关状态变更后会清除相应记录。更新已有路径可能中断现有播放。 +另一个摄像头使用 `parking` 等不同 Path 即可同时播放。 +建议调用方限制 Path 以小写字母开头,仅包含小写字母、数字和连字符,最长 63 个字符,排除名称 `all`。默认服务仅检查动态登记的 Path 非空,不执行这些格式校验。 +默认服务要求 RTSP/RTSPS URL 为包含主机名且不含用户信息的绝对地址;建议显式提供端口和流路径,不要在查询字符串中放置凭据。调用方需自行限制 RTSP 目标。 +用户名、密码传原始值,服务端负责 URL 编码;未提供用户名时密码会被忽略。 +示例在每次登记操作结束后清空密码,再次登记时需要重新输入。 + +`AddOrUpdateAsync` 优先返回摄像头的 `PlayUrl`;为 `null` 时默认返回 `http://127.0.0.1://`。空字符串不是有效地址,会导致登记失败。 +如果 nginx 已将公开地址反向代理到本机 WebRTC HTTP 端口,可在 `MediaMtxOptions` 配置节设置 +`"WebRtcPublicUrl": "https://example.com/mediamtx/"`,返回的地址将以该基址开头。 +支持带路径前缀的绝对 HTTP/HTTPS 地址,不允许包含凭据、查询字符串或片段;未设置时使用回环地址。 +服务同时允许该地址的来源访问 WebRTC 信令。单路 `PlayUrl` 不改变允许的来源或 ICE 配置,应与 `WebRtcPublicUrl` 对应的反向代理配置一致。代理需要正确转发播放页面、WHEP 请求及会话地址; +路径前缀场景还需正确处理上游 `Location` 响应头。 +`RemoveAsync(path)` 显式删除路径并影响所有观看者;关闭播放器不会自动删除路径。 +默认实现删除成功返回 `true`,失败(包括路径不存在)抛出异常;自定义实现可能返回 `false`。 +默认 `AddOrUpdateAsync` 成功返回播放地址,失败抛出异常;自定义实现可能返回 `null`,调用方应检查结果。 +多个观看者共享一路源,未观看时按 MediaMTX 的按需设置停止拉流。 +登记和删除调用支持 `CancellationToken`;HTTP 错误保留状态码,但不暴露可能含源凭据的响应正文。 +请求取消或超时时,网关可能已经完成变更,调用方应核实状态,不要盲目重复登记。 + +登记成功仅表示配置被网关接受,不代表摄像头在线或凭据正确。 +动态配置保存在 MediaMTX 内存中,停止或重启后清空,宿主需要自行安全持久化并在启动后恢复;`Cameras` 中的静态配置会在启动时重新加载。 + +## 声音 + +MediaMTX 在此方案中转发协议,不自动转码。摄像头需启用音频并选择浏览器支持的 WebRTC 编码, +例如 G.711 μ-law(PCMU)或 A-law(PCMA);AAC 等不兼容编码需要另行转码。 +MediaMTX 播放页面默认静音,播放后需取消静音;仍无声音时检查摄像头的音频配置及源流。 + +## 安全与访问范围 + +UI 必须通过 HTTPS 与服务端通信。调用方负责身份认证、摄像头级权限检查和目标 RTSP 地址白名单, +避免将该服务暴露成可访问任意内网地址的匿名代理。 +不要将摄像头密码放进播放 URL、日志、浏览器本地存储,或在列表查询中回传。 +流路径不是访问令牌;当前播放端允许本机读取,内置服务不提供多租户播放鉴权。 +不要直接将 Control API 反向代理给浏览器。 + +HTTP、Control API、UDP ICE 只监听 `127.0.0.1`。默认返回 URL 中的回环地址指浏览器所在设备。 +`WebRtcPublicUrl` 仅改变返回的播放 URL 和允许的信令来源,不会配置 nginx 或更改 ICE 地址; +普通 HTTP 反向代理不能单独使远程浏览器访问回环 UDP ICE,远程播放还需可达的媒体路径和鉴权。 +摄像头管理不属于 iframe 播放组件的职责。 + +## 工具部署与进程生命周期 + +MediaMTX 可执行文件和许可证由独立的 `BootstrapBlazor.MediaMtx.Cli` 按目标 RID 准备并复制,核心包不附带原生工具。也可全局安装 CLI,在编译或发布后的应用目录手动执行: + +```powershell +dotnet tool install -g BootstrapBlazor.MediaMtx.Cli --prerelease +bb-mediamtx --download +Push-Location .\publish +bb-mediamtx --copy +Pop-Location +``` + +CLI 不内置 MediaMTX 二进制,不读取或修改工程,也不创建或更新工具清单或构建规则。宿主可维护本地工具清单,在 Build、Publish 完成后使用 `--output` 指定输出目录。未指定时使用当前工作目录,不自动解析工程。例如跨平台发布: + +```powershell +dotnet publish .\MyApp.csproj -r linux-arm64 --self-contained false --output .\publish +bb-mediamtx --download --rid linux-arm64 +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 时按本机系统和架构选择。 +`--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`。默认启动路径按运行时操作系统及系统架构选择。 +也可以自行从 [MediaMTX Releases](https://github.com/bluenviron/mediamtx/releases) 下载并配置路径,调用 `AddMediaMtxService` 即可使用默认启动器。压缩包中的 `mediamtx.yml` 不会被使用。 + +`MediaMtxOptions:MediaMtxPath` 默认为 `mediamtx-tools\<平台-架构>\<可执行文件>`,相对应用目录。 +自行部署到其他位置时需配置可执行文件路径,Windows 包含 `.exe` 扩展名,例如 `C:\tools\mediamtx\mediamtx.exe`; +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,网关才标记为就绪。 +就绪日志包含 PID、工具路径、WebRTC 基址和 ICE 地址,不包含摄像头源或凭据。 +进程启动、就绪探测失败或超时时向 `EnsureStartedAsync` 调用方报告异常,并清理本次启动的进程和临时配置文件;失败后可重新调用。默认服务仅支持异步释放;宿主需异步释放服务容器以回收自有进程和临时配置文件,清理失败记录错误日志。 +默认启动器使用 .NET `Process` 启动进程,主包负责管理和停止;宿主被强制终止时不保证自动回收 MediaMTX。 +重复调用启动入口会复用本宿主的运行中进程,不会重启。 +服务不终止或接管其他宿主及手动启动的实例,因为其 Control API 凭据不属于当前宿主;若占用配置端口会报告错误,不中断已有播放。 +启动前检查 WebRTC HTTP、Control API 的 TCP 端口和 ICE 的 UDP 端口是否可绑定。 +地址仍不可用或被其他进程占用时记录错误日志,并向 `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 new file mode 100644 index 00000000..d9f2ca0b --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md @@ -0,0 +1,74 @@ +--- +name: bb-mediamtx +description: 提供 BootstrapBlazor.MediaMtx 的配置与 API 参考。适用于在 ASP.NET Core 中托管 MediaMTX 网关、动态管理 RTSP 摄像头,以及排查 WebRTC 播放问题。 +--- + +# MediaMTX API 参考 + +此 skill 随 `BootstrapBlazor.MediaMtx` NuGet 包分发,用于在服务端托管 MediaMTX 网关并动态管理 RTSP 摄像头。参考文档从打包时的工程源码生成。 +`BootstrapBlazor.MediaMtx` 是面向 .NET 6 至 .NET 11 的服务端 NuGet 包,不是 .NET Tool,也不支持独立浏览器端宿主。 +`BootstrapBlazor.MediaMtx.Cli` 是另行安装、目标为 .NET 11 的 .NET Tool,用于下载和复制 MediaMTX 原生网关程序;仅安装更高版本运行时时需为 CLI 启用运行时 roll-forward。 + +先阅读 [references/llms.txt](references/llms.txt) 确认当前包收录的服务和选项,再按需读取对应的 API 文档。 + +## 注册与配置 + +```csharp +// 仅注册服务;不会随应用启动而安装或运行 MediaMTX: +builder.Services.AddMediaMtxService(); +``` + +```json +{ + "MediaMtxOptions": { + "WebRtcPort": 8889, + "WebRtcIcePort": 8189, + "ApiPort": 9997 + } +} +``` + +- `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 失败或取消时输出警告并以成功状态退出,不阻断宿主构建或发布;需检查警告并确认工具已部署。 +- 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 秒;取消或失败抛出异常,后续可重试。自定义实现也应在启动失败时抛出异常。 +- `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 请求,不依赖子进程日志。 +- 工具缺失、启动或就绪探测失败时默认实现向 `EnsureStartedAsync` 调用方抛出异常;服务不会安装工具,后续调用可重试。网关未运行时,有效的摄像头登记和删除调用抛出 `InvalidOperationException`。 +- 默认服务仅支持异步释放;宿主异步释放服务容器时会尝试回收自有 MediaMTX 进程和临时配置文件。重复启动请求复用本服务的运行中实例,不终止或接管其他宿主、手动启动的实例;端口被占用时报告错误,不中断已有播放。进程退出后,再次调用 `EnsureStartedAsync` 可尝试重启;动态摄像头需重新登记。 +- 本包只支持 MediaMTX,不支持其他 RTSP 转流工具。 + +## 摄像头管理 + +在服务端(如 Interactive Server 页面)注入 `IMediaMtxService`: + +- 调用方应校验唯一播放路径 `MediaMtxCameraOptions.Path`:建议以小写字母开头,只允许小写字母、数字和连字符,最长 63 个字符,排除 `all`。默认服务仅检查动态登记的路径非空;删除时传入已登记的路径。 +- 默认服务要求 `RtspUrl` 为不含用户信息且包含主机名的绝对 RTSP/RTSPS 地址;建议显式指定端口和流路径,不要在查询字符串中放置凭据。`UserName`、`Password` 使用未编码的原始值;没有用户名时密码会被忽略。 +- `IMediaMtxService.AddOrUpdateAsync(camera)` 登记新路径或更新已有路径的源和凭据,默认实现成功返回播放 URL、失败抛出异常;自定义实现可返回 `null`,调用方应检查结果。HikVision 通过 `Options` 传入摄像头配置并在内部调用服务。成功只表示网关接受配置,不代表摄像头已连通;更新可能中断现有播放。 +- 默认服务记住当前网关中已成功登记或更新的路径,后续优先更新;路径状态不一致时以网关为准。 +- `RemoveAsync(path)` 显式删除路径并影响所有观看者。默认实现成功返回 `true`、失败抛出异常;自定义实现可返回 `false`。关闭页面不会删除路径。 +- 多路摄像头使用不同路径,共用一个网关;首次观看时通过 RTSP/TCP 按需拉流。动态配置只保存在 MediaMTX 内存中,重启后需由宿主恢复;`Cameras` 中的静态配置会在启动时重新加载。 +- 启动、登记和删除操作支持 `CancellationToken`;登记或删除取消、超时后网关可能已经完成变更,应核实状态后再重试。 +- `SetGatewayStateAsync` 仅供宿主同步网关状态,业务代码不要调用。 + +## 播放与声音 + +- 摄像头 `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 播放页默认静音,用户需在播放器中取消静音。无声音时还应检查摄像头的音频配置及源流。 + +## 安全约束 + +- UI 应通过 HTTPS 访问;调用方负责身份认证、摄像头级权限和 RTSP 目标地址白名单,不要把服务暴露为匿名内网代理。 +- 凭据通过 `UserName`、`Password` 传原始值,不要写入 URL、日志或浏览器存储。 +- Control API 使用内部随机密码,不要反向代理给浏览器;播放路径不是访问令牌,本机读取不提供多租户播放鉴权。 + +以文档中的公开签名为准,优先读取当前项目实际还原版本的文档,不要凭记忆编造 API。资料缺失时说明缺口,不要猜测。 + +此 skill 为只读参考资料,不包含脚本。 diff --git a/src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxService.cs b/src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxService.cs deleted file mode 100644 index 94426337..00000000 --- a/src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxService.cs +++ /dev/null @@ -1,45 +0,0 @@ -// 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 - -namespace BootstrapBlazor.Components; - -/// -/// 服务端动态摄像头管理。调用方负责身份认证、权限检查和 RTSP 目标地址的访问策略。 -/// Server-side dynamic camera management. Callers must enforce authentication, authorization and RTSP destination access policies. -/// 网关未运行时,管理方法抛出 。 -/// Management methods throw when the gateway is not running. -/// 11.0.0 -/// -public interface IMediaMtxService -{ - /// - /// 由宿主设置已就绪网关的 Control API 密码;传入 null 表示网关已停止。 - /// Sets the Control API password for the ready gateway; null indicates that the gateway has stopped. Intended for use by the host. - /// 11.0.0 - /// - /// 网关密码,或表示停止的 null。The gateway password, or null when stopped. - /// 状态更新任务。The state update task. - Task SetGatewayStateAsync(string? apiPassword); - - /// - /// 登记新路径或更新已有路径的摄像头源配置,返回播放 URL。默认使用同机回环地址,可通过 WebRtcPublicUrl 配置反向代理地址。更新可能中断现有播放;成功不代表源已连通。 - /// Registers a new path or updates the camera source configuration for an existing path and returns its playback URL. Uses the loopback address by default or WebRtcPublicUrl for a reverse proxy. Updates may interrupt existing playback; success does not verify source connectivity. - /// 11.0.0 - /// - /// 由管理 UI 提交的摄像头配置。Camera configuration submitted by the management UI. - /// 取消令牌。The cancellation token. - /// 播放 URL。The playback URL. - Task AddOrUpdateAsync(MediaMtxCameraOptions camera, CancellationToken cancellationToken = default); - - /// - /// 显式删除摄像头路径,影响所有观看者;路径不存在时报错。 - /// Explicitly deletes a camera path for all viewers. Missing paths fail. - /// 11.0.0 - /// - /// 要删除的摄像头路径。The camera path to delete. - /// 取消令牌。The cancellation token. - /// 删除操作任务。The deletion task. - Task RemoveAsync(string path, CancellationToken cancellationToken = default); -} diff --git a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs b/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs deleted file mode 100644 index b46881da..00000000 --- a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs +++ /dev/null @@ -1,42 +0,0 @@ -// 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 - -namespace BootstrapBlazor.Components; - -/// -/// 由服务端配置或 UI 提供的摄像头配置,不应持久化到浏览器或写入日志。 -/// Camera configuration supplied by server-side configuration or UI. Do not persist it in the browser or write it to logs. -/// 11.0.0 -/// -public sealed class MediaMtxCameraOptions -{ - /// - /// 获得/设置唯一的播放路径,使用小写字母开头,后接小写字母、数字或连字符,最长 63 个字符,不允许保留名称 all。例如:camera01 - /// Gets or sets the unique playback path: a lowercase letter followed by lowercase letters, digits or hyphens, up to 63 characters, excluding the reserved name all. For example: camera01 - /// 11.0.0 - /// - public string? Path { get; set; } - - /// - /// 获得/设置不含凭据的绝对 RTSP 或 RTSPS 地址,必须指定端口和流路径。例如:rtsp://192.168.1.100:554/Streaming/Channels/101 - /// Gets or sets the absolute RTSP or RTSPS URL without credentials, with an explicit port and stream path. For example: rtsp://192.168.1.100:554/Streaming/Channels/101 - /// 11.0.0 - /// - public string? Url { get; set; } - - /// - /// 获得/设置未进行 URL 编码的摄像头用户名。 - /// Gets or sets the camera user name without URL encoding. - /// 11.0.0 - /// - public string? UserName { get; set; } - - /// - /// 获得/设置未进行 URL 编码的摄像头密码。 - /// Gets or sets the camera password without URL encoding. - /// 11.0.0 - /// - public string? Password { get; set; } -} diff --git a/src/extensions/BootstrapBlazor.MediaMtx/README.MediaMtx.md b/src/extensions/BootstrapBlazor.MediaMtx/README.MediaMtx.md deleted file mode 100644 index 3060ccfe..00000000 --- a/src/extensions/BootstrapBlazor.MediaMtx/README.MediaMtx.md +++ /dev/null @@ -1,217 +0,0 @@ -# BootstrapBlazor.MediaMtx - -ASP.NET Core 动态 RTSP 摄像头服务。一个托管的 MediaMTX 进程管理多个播放路径。 -启动不连接摄像头;首次观看时通过 RTSP/TCP 按需拉流,转发为 WebRTC。 -主包提供默认进程启动器,但不附带 MediaMTX;通过 `bb-mediamtx` CLI 从 GitHub 下载或自行部署工具,详见“工具部署与进程生命周期”。 - -## 注册与网关配置 - -```csharp -// 先准备工具缓存并配置宿主复制工具,所有平台使用同一个注册入口: -builder.Services.AddMediaMtxService(); -``` - -```json -{ - "MediaMtx": { - "WebRtcPort": 8889, - "WebRtcIcePort": 8189, - "ApiPort": 9997, - "Cameras": { - "hikvision": { - "Url": "rtsp://192.0.2.1:554/stream", - "UserName": "camera" - }, - "gate": { - "Url": "rtsp://192.0.2.2:554/stream", - "UserName": "camera" - } - } - } -} -``` - -`Cameras` 是可选的静态摄像头字典,网关启动时自动登记,无需调用 `AddOrUpdateAsync`。 -键即播放路径,值包含不含凭据的 `Url` 和可选的 `UserName`、`Password`,值中的 `Path` 会被忽略;路径和 URL 规则与动态登记相同。 -密码应通过 User Secrets 或环境变量等安全配置源提供,不要提交到 `appsettings.json`。 -User Secrets 的 `secrets.json` 使用与 `appsettings.json` 相同的层次结构,按路径合并: - -```json -{ - "MediaMtx": { - "Cameras": { - "hikvision": { - "Password": "" - } - } - } -} -``` - -对应的环境变量名为 `MediaMtx__Cameras__hikvision__Password`。ASP.NET Core 默认只在 Development 环境加载 User Secrets。 -网关通过子进程环境传递包含凭据的源地址,不会将其写入生成的临时配置文件或日志。 -静态摄像头同样按需使用 RTSP/TCP 拉流;修改摄像头配置后需重启应用。 -不再支持原来的全局 `Url`、`UserName`、`Password`。 -`AddMediaMtxService` 注册默认进程启动器和主服务,从 `MediaMtx` 配置节绑定选项,也可通过 `configureOptions` 回调覆盖选项。 -`BootstrapBlazor.MediaMtx` 核心包负责网关进程生命周期和摄像头管理;原生工具由独立的 `BootstrapBlazor.MediaMtx.Cli` 部署,所有平台统一调用 `AddMediaMtxService`。 -默认启动器支持 Windows x64、Linux x64/ARM64/ARMv7 和 macOS x64/ARM64。不支持的操作系统或系统架构会记录警告并跳过网关,宿主仍可启动。 -自行实现 `IMediaMtxProcessLauncher` 时,在调用 `AddMediaMtxService` 前注册该接口,默认启动器不会覆盖已有注册;启动器使用宿主提供的 `ProcessStartInfo` 启动并返回进程,宿主负责就绪探测和清理。 -HTTP 和 Control API 使用不同 TCP 端口,ICE 使用 UDP。 -Control API 仅监听回环地址,使用每个宿主实例生成的内部随机密码,不提供浏览器调用入口。 -`IMediaMtxService.SetGatewayStateAsync` 仅供宿主同步网关状态;自定义实现应在密码为 `null` 时 -停止管理请求,并在网关就绪后使用提供的密码认证 Control API 请求。 - -### MediaMTX 配置 - -MediaMTX 的配置由组件生成,不支持用户提供的 MediaMTX JSON 配置文件。 -组件关闭 RTSP、RTMP、HLS、SRT、MoQ 等监听器,并配置本机 Control API 和 WebRTC。 -端口和摄像头通过 `MediaMtx` 选项设置;组件将配置写入临时 YAML 文件供子进程启动, -摄像头源地址和内部 API 密码仅通过子进程环境传递。正常停止时会清理临时文件, -强制终止进程时可能无法清理。 -组件将子进程日志限制到标准输出并丢弃,不转发可能含源凭据的输出。 - -## UI 动态登记 - -在自己的 **Interactive Server** 页面注入 `IMediaMtxService`。以下代码放在已授权的管理页面中; -使用原生 Blazor 表单,不需要把凭据传给播放组件: - -```razor -@using BootstrapBlazor.Components -@inject IMediaMtxService MediaMtx - - - - - - - - -@if (error is not null) -{ -

@error

-} -@if (playerUrl is not null) -{ - -} - -@code { - private readonly MediaMtxCameraOptions camera = new() { Path = "entrance" }; - private string? playerUrl; - private string? error; - private bool busy; - - private async Task ConnectAsync() - { - busy = true; - error = null; - try - { - playerUrl = await MediaMtx.AddOrUpdateAsync(camera); - } - catch (ArgumentException) - { - error = "请检查 RTSP 地址和用户名。"; - } - catch (HttpRequestException) - { - error = "登记或更新失败,请检查摄像头配置和网关是否可用。"; - } - catch (InvalidOperationException) - { - error = "网关尚未就绪。"; - } - catch (OperationCanceledException) - { - error = "登记操作已取消或超时。"; - } - finally - { - camera.Password = null; - busy = false; - } - } -} -``` - -页面所在应用同时引用 `BootstrapBlazor.HikVision` 才能使用播放器。 -`IMediaMtxService.AddOrUpdateAsync(camera)` 按 `Path` 登记新路径或更新已有路径的源和凭据。默认服务对未记录的路径优先新增,对已成功登记或更新的路径优先更新;若网关报告路径已存在或不存在,则改用相应的操作。删除成功或网关状态变更后会清除相应记录。更新已有路径可能中断现有播放。 -另一个摄像头使用 `parking` 等不同 Path 即可同时播放。 -Path 必须以小写字母开头,仅包含小写字母、数字和连字符,最长 63 个字符,不允许保留名称 `all`。 -RTSP/RTSPS URL 必须包含显式端口和流路径,不允许内嵌凭据、查询字符串或片段。 -用户名、密码传原始值,服务端负责 URL 编码;提供密码时必须提供用户名。 -示例在每次登记操作结束后清空密码,再次登记时需要重新输入。 - -`AddOrUpdateAsync` 默认返回 `http://127.0.0.1://`。 -如果 nginx 已将公开地址反向代理到本机 WebRTC HTTP 端口,可在 `MediaMtx` 配置节设置 -`"WebRtcPublicUrl": "https://example.com/mediamtx/"`,返回的地址将以该基址开头。 -支持带路径前缀的绝对 HTTP/HTTPS 地址,不允许包含凭据、查询字符串或片段;未设置时使用回环地址。 -组件同时允许该地址的来源访问 WebRTC 信令。代理需要正确转发播放页面、WHEP 请求及会话地址; -路径前缀场景还需正确处理上游 `Location` 响应头。 -`RemoveAsync(path)` 显式删除路径并影响所有观看者;关闭播放器不会自动删除路径。 -多个观看者共享一路源,未观看时按 MediaMTX 的按需设置停止拉流。 -所有管理调用支持 `CancellationToken`;HTTP 错误保留状态码,但不暴露可能含源凭据的响应正文。 -请求取消或超时时,网关可能已经完成变更,调用方应核实状态,不要盲目重复登记。 - -登记成功仅表示配置被网关接受,不代表摄像头在线或凭据正确。 -动态配置保存在 MediaMTX 内存中,停止或重启后清空,宿主需要自行安全持久化并在启动后恢复;`Cameras` 中的静态配置会在启动时重新加载。 - -## 声音 - -MediaMTX 在此方案中转发协议,不自动转码。摄像头需启用音频并选择浏览器支持的 WebRTC 编码, -例如 G.711 μ-law(PCMU)或 A-law(PCMA);AAC 等不兼容编码需要另行转码。 -MediaMTX 播放页面默认静音,播放后需取消静音;仍无声音时检查摄像头的音频配置及源流。 - -## 安全与访问范围 - -UI 必须通过 HTTPS 与服务端通信。调用方负责身份认证、摄像头级权限检查和目标 RTSP 地址白名单, -避免将该服务暴露成可访问任意内网地址的匿名代理。 -不要将摄像头密码放进播放 URL、日志、浏览器本地存储,或在列表查询中回传。 -流路径不是访问令牌;当前播放端允许本机读取,内置服务不提供多租户播放鉴权。 -不要直接将 Control API 反向代理给浏览器。 - -HTTP、Control API、UDP ICE 只监听 `127.0.0.1`。默认返回 URL 中的回环地址指浏览器所在设备。 -`WebRtcPublicUrl` 仅改变返回的播放 URL 和允许的信令来源,不会配置 nginx 或更改 ICE 地址; -普通 HTTP 反向代理不能单独使远程浏览器访问回环 UDP ICE,远程播放还需可达的媒体路径和鉴权。 -摄像头管理不属于 iframe 播放组件的职责。 - -## 工具部署与进程生命周期 - -MediaMTX 可执行文件和许可证由独立的 `BootstrapBlazor.MediaMtx.Cli` 按目标 RID 准备并复制,核心包不附带原生工具。也可全局安装 CLI,在编译或发布后的应用目录手动执行: - -```powershell -dotnet tool install -g BootstrapBlazor.MediaMtx.Cli --prerelease -bb-mediamtx -``` - -CLI 不内置 MediaMTX 二进制,不读取或修改工程,也不创建或更新工具清单。宿主维护根目录 `dotnet-tools.json` 和构建规则,在 Build、Publish 完成后还原 CLI,再到输出目录执行 `dotnet bb-mediamtx`;跨平台只传 `--rid`。CLI 不生成或清理构建规则和 `.targets` 文件。也可手动发布后复制: - -```powershell -dotnet publish .\MyApp.csproj -r linux-arm64 --self-contained false --output .\publish -Push-Location .\publish -bb-mediamtx --rid linux-arm64 -Pop-Location -``` - -CLI 支持无参数部署、`--rid` 和 `--force`,准备固定版本 MediaMTX `1.21.4`,缓存位于本机应用数据目录的 `BootstrapBlazor\mediamtx\v\`,构建和发布共用。完整缓存不访问 GitHub,缺失或文件校验失败时才下载并验证 SHA-256。下载只保留可执行文件和许可证,并按缓存项加锁。 -宿主将 CLI 的工作目录设为编译或发布目录,由 CLI 将工具及 `LICENSE.MediaMTX` 复制到当前目录的 `mediamtx-tools\`。默认两个文件都存在时立即结束,不读取内容或检查缓存;缺文件时只补齐缺失文件,不覆盖已有文件。升级或修复可执行 `bb-mediamtx --force`,本地工具使用 `dotnet bb-mediamtx --force`;校验缓存后覆盖工具和许可证,不强制重新下载。未传 `--rid` 时按本机系统和架构选择,跨平台需传入目标 RID,可与 `--force` 组合。宿主的 `dotnet publish --no-build` 仍可通过发布规则调用 CLI,单文件发布时工具始终作为外部文件保留。 -普通 NuGet restore 不下载 MediaMTX;宿主应跳过 IDE 设计时构建,应用运行时不执行准备。输出缺文件且缓存不可用时需要访问 GitHub,下载或校验失败通过非零退出码报告。离线环境预先准备 CLI 包,并在有网络时于空的输出目录执行默认命令预热对应 RID 的工具缓存。 -CLI 版本由宿主根目录工具清单固定,默认 MediaMTX 版本由 CLI 固定,不需要 Server 的版本、缓存或下载开关属性。源码开发需先手动打包并还原 CLI;CI 使用提交的清单和宿主维护的调用规则,不提交工具缓存。 -例如 Windows x64 工具位于 `mediamtx-tools\win-x64\mediamtx.exe`,许可证位于 `mediamtx-tools\win-x64\LICENSE.MediaMTX`;Linux ARMv7 工具位于 `mediamtx-tools\linux-arm\mediamtx`。默认启动路径按运行时操作系统及系统架构选择。 -也可以自行从 [MediaMTX Releases](https://github.com/bluenviron/mediamtx/releases) 下载并配置路径,调用 `AddMediaMtxService` 即可使用默认启动器。压缩包中的 `mediamtx.yml` 不会被使用。 - -`MediaMtx:MediaMtxPath` 默认为 `mediamtx-tools\<平台-架构>\<可执行文件>`,相对应用目录。 -自行部署到其他位置时需配置可执行文件路径,Windows 包含 `.exe` 扩展名,例如 `C:\tools\mediamtx\mediamtx.exe`; -Linux 和 macOS 没有扩展名,例如 `/opt/mediamtx/mediamtx`。相对路径以应用目录为基准。 -找不到工具时记录警告并跳过网关,宿主正常启动,管理调用报告网关未运行。 -在 Linux/macOS 上执行 CLI 时会自动设置工具执行权限;从 Windows 跨平台发布后,需要在目标机器设置执行权限,例如 Linux x64 使用 `chmod a+x mediamtx-tools/linux-x64/mediamtx`。 -启动时在 10 秒内重试已认证的 Control API 请求,不依赖子进程日志。只有子进程仍在运行且 Control API 返回 HTTP 200,网关才标记为就绪。 -就绪日志包含 PID、工具路径、WebRTC 基址和 ICE 地址,不包含摄像头源或凭据。 -路径有效但进程启动、就绪探测失败或超时时记录错误日志并跳过网关,宿主正常启动;停止时尝试回收自有进程和临时配置文件,清理失败记录错误日志。 -默认启动器使用 .NET `Process` 启动进程,主包负责管理和停止;宿主被强制终止时不保证自动回收 MediaMTX。 -下次启动网关前,会结束可执行文件完整路径与 `MediaMtx:MediaMtxPath` 解析结果相同的现有进程,并等待退出后再启动。 -同一路径的 MediaMTX 应由一个宿主管理;启动新宿主会中断该路径下已有实例的播放。其他目录的实例不会被结束。 -启动前检查 WebRTC HTTP、Control API 的 TCP 端口和 ICE 的 UDP 端口是否可绑定。 -地址仍不可用或被其他进程占用时记录错误日志并跳过网关,宿主正常启动,管理调用报告网关未运行;应检查端口配置及占用情况,处理后重启。 -端口检查与进程启动之间仍可能发生竞争,此时同样记录错误日志并给出处理提示。 -网关配置修改后需要重启应用。程序不自动重启崩溃的 MediaMTX;管理调用会报告连接失败。 diff --git a/src/extensions/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md b/src/extensions/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md deleted file mode 100644 index cd17749b..00000000 --- a/src/extensions/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -name: bb-mediamtx -description: 提供 BootstrapBlazor.MediaMtx 的配置与 API 参考。适用于在 ASP.NET Core 中托管 MediaMTX 网关、动态管理 RTSP 摄像头,以及排查 WebRTC 播放问题。 ---- - -# MediaMTX API 参考 - -此 skill 随 `BootstrapBlazor.MediaMtx` NuGet 包分发,用于在服务端托管 MediaMTX 网关并动态管理 RTSP 摄像头。参考文档从打包时的工程源码生成。 - -先阅读 [references/llms.txt](references/llms.txt) 确认当前包收录的服务和选项,再按需读取对应的 API 文档。 - -## 注册与配置 - -```csharp -// 先准备工具缓存并配置宿主复制工具,所有平台使用同一个注册入口: -builder.Services.AddMediaMtxService(); -``` - -```json -{ - "MediaMtx": { - "WebRtcPort": 8889, - "WebRtcIcePort": 8189, - "ApiPort": 9997 - } -} -``` - -- `BootstrapBlazor.MediaMtx` 核心包负责网关进程生命周期和摄像头管理,不附带原生工具;`BootstrapBlazor.MediaMtx.Cli` 负责按目标 RID 准备并复制可执行文件和许可证。CLI 不读取或修改工程,不创建或更新工具清单,也不生成或清理构建规则。宿主维护根目录 `dotnet-tools.json` 和 `Directory.Build.targets`,先还原 CLI,再到 Build、Publish 输出目录执行 `dotnet bb-mediamtx`;跨平台传入 `--rid`。 -- CLI 支持无参数部署、`--rid` 和 `--force`,自动识别本机平台,准备固定版本 `1.21.4`,缓存位于本机应用数据目录的 `BootstrapBlazor\mediamtx\v\`。有效缓存不访问 GitHub;缺失或文件校验失败时下载、校验 SHA-256,并按缓存项加锁。源码开发需先手动打包并还原 CLI。 -- CLI 将工具和许可证部署到当前目录的 `mediamtx-tools\`;默认两者都存在时立即结束,不读取内容或检查缓存,缺文件时只补齐缺失文件。升级或修复使用 `--force`,校验缓存后覆盖两个输出文件,不强制重新下载;可与 `--rid` 组合,参数顺序不限。宿主的 `dotnet publish --no-build` 仍可通过发布规则调用 CLI,单文件发布时工具仍保留在外部。普通 NuGet restore 不下载 MediaMTX,运行时不准备工具。离线环境需预热 CLI 包,并在有网络时于空的输出目录执行默认命令预热对应 RID 的工具缓存;失败通过非零退出码报告。 -- `MediaMtxPath` 默认为应用目录下的 `mediamtx-tools\<平台-架构>\<可执行文件>`,例如 `mediamtx-tools\win-x64\mediamtx.exe`;可通过配置指定其他路径,相对路径以应用目录为基准。在 Linux/macOS 上执行 CLI 会自动设置执行权限;从 Windows 跨平台发布后需在目标机器设置执行权限。 -- `AddMediaMtxService` 同时注册默认进程启动器和主服务,从 `MediaMtx` 配置节绑定选项,也支持通过 `configureOptions` 回调覆盖选项。自行实现 `IMediaMtxProcessLauncher` 时,在调用 `AddMediaMtxService` 前注册该接口,默认启动器不会覆盖已有注册;启动器使用宿主提供的 `ProcessStartInfo` 启动并返回进程,宿主负责就绪探测和清理。不支持的操作系统或系统架构会记录警告并跳过网关,宿主继续启动。 -- WebRTC 页面和 Control API 分别使用 TCP 端口 8889、9997,ICE 使用 UDP 端口 8189;HTTP 与 Control API 端口应不同。 -- `MediaMtx:Cameras` 是以播放路径为键的静态摄像头字典,值提供 `Url` 和可选的 `UserName`、`Password`(值中的 `Path` 被忽略),网关启动时自动登记,无需手动调用 `AddOrUpdateAsync`。密码通过 User Secrets(`secrets.json` 中与 `appsettings.json` 相同的层次结构)或环境变量(如 `MediaMtx__Cameras__hikvision__Password`)提供。修改后重启应用。 -- MediaMTX 配置由组件生成,不支持用户提供的 MediaMTX JSON 配置文件。组件生成临时 YAML,摄像头源地址和内部 API 密码仅通过子进程环境传递;就绪探测使用已认证的 Control API 请求,不依赖子进程日志。 -- 文件不存在时记录警告;端口被占用、进程启动失败、就绪探测失败或超时时记录错误日志。网关不启动,宿主继续启动;网关未运行时管理调用抛出 `InvalidOperationException`。 -- 正常停止宿主时服务会尝试回收自有 MediaMTX 进程。启动时会先结束可执行文件完整路径匹配 `MediaMtx:MediaMtxPath` 的已有实例,并等待退出。同一可执行文件路径应只交给一个宿主管理,否则新宿主启动会中断已有播放。其他路径的进程不受影响;若端口仍被占用,检查占用情况后重启。 -- 本包只支持 MediaMTX,不支持其他 RTSP 转流工具。 - -## 摄像头管理 - -在服务端(如 Interactive Server 页面)注入 `IMediaMtxService`: - -- 调用方应校验唯一播放路径 `MediaMtxCameraOptions.Path`:以小写字母开头,只允许小写字母、数字和连字符,最长 63 个字符,不能是 `all`。删除时传入已登记的路径。 -- `Url` 为不含凭据、查询字符串或片段的 RTSP/RTSPS 地址,必须显式指定端口和流路径。`UserName`、`Password` 使用未编码的原始值;提供密码时必须提供用户名。 -- `IMediaMtxService.AddOrUpdateAsync(camera)` 登记新路径或更新已有路径的源和凭据,返回可传给 `BootstrapBlazor.HikVision` 的 `HikVisionWebRtc.WebRtcUrl` 的播放 URL。成功只表示网关接受配置,不代表摄像头已连通;更新可能中断现有播放。 -- 默认服务记住当前网关中已成功登记或更新的路径,后续优先更新;路径状态不一致时以网关为准。 -- `RemoveAsync(path)` 显式删除路径并影响所有观看者。关闭页面不会删除路径。 -- 多路摄像头使用不同路径,共用一个网关;首次观看时通过 RTSP/TCP 按需拉流。动态配置只保存在 MediaMTX 内存中,重启后需由宿主恢复;`Cameras` 中的静态配置会在启动时重新加载。 -- 操作支持 `CancellationToken`;取消或超时后网关可能已经完成变更,应核实状态后再重试。 -- `SetGatewayStateAsync` 仅供宿主同步网关状态,业务代码不要调用。 - -## 播放与声音 - -- 默认返回 `http://127.0.0.1://`;可设置 `WebRtcPublicUrl` 为已配置的 WebRTC HTTP 反向代理基址,播放 URL 和允许的信令来源随之调整。HTTP、Control API 和 ICE 仍仅监听回环地址;普通 HTTP 代理不提供远程 ICE 媒体路径,远程播放仍需另行配置可达的媒体路径、HTTPS 与鉴权。 -- MediaMTX 在此方案中转发协议,不自动转码。摄像头需启用音频并选择浏览器支持的 WebRTC 编码,例如 G.711 μ-law(PCMU)或 A-law(PCMA);AAC 等不兼容编码需另行转码。 -- MediaMTX 播放页默认静音,用户需在播放器中取消静音。无声音时还应检查摄像头的音频配置及源流。 - -## 安全约束 - -- UI 应通过 HTTPS 访问;调用方负责身份认证、摄像头级权限和 RTSP 目标地址白名单,不要把服务暴露为匿名内网代理。 -- 凭据通过 `UserName`、`Password` 传原始值,不要写入 URL、日志或浏览器存储。 -- Control API 使用内部随机密码,不要反向代理给浏览器;播放路径不是访问令牌,本机读取不提供多租户播放鉴权。 - -以文档中的公开签名为准,优先读取当前项目实际还原版本的文档,不要凭记忆编造 API。资料缺失时说明缺口,不要猜测。 - -此 skill 为只读参考资料,不包含脚本。