From c8a1bf9b59fd2280f799f5624e6e652a5e700751 Mon Sep 17 00:00:00 2001 From: Argo Zhang Date: Tue, 1 Dec 2026 16:13:27 +0800 Subject: [PATCH 01/19] =?UTF-8?q?refactor:=20=E7=A7=BB=E5=8A=A8=20MediaMtx?= =?UTF-8?q?=20=E5=B7=A5=E7=A8=8B=E5=BD=92=E5=B1=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BootstrapBlazor.Extensions.slnx | 2 +- .../BootstrapBlazor.MediaMtx.csproj | 6 +- .../HttpClientExtensions.cs | 0 .../IMediaMtxProcessLauncher.cs | 0 .../IMediaMtxService.cs | 14 ++- .../MediaMtxCameraOptions.cs | 9 +- .../MediaMtxOptions.cs | 4 +- .../MediaMtxProcessLauncher.cs | 0 .../MediaMtxService.Gateway.cs} | 108 ++++++------------ .../MediaMtxService.cs | 47 ++++++-- .../MediaMtxServiceCollectionExtensions.cs | 17 +-- .../MediaMtxToolInstaller.cs | 82 +++++++++++++ .../README.MediaMtx.md | 83 ++++++++++---- .../skills/bb-mediamtx/SKILL.md | 22 ++-- 14 files changed, 263 insertions(+), 131 deletions(-) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj (87%) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs (100%) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs (100%) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/IMediaMtxService.cs (68%) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs (77%) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs (93%) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/MediaMtxProcessLauncher.cs (100%) rename src/{extensions/BootstrapBlazor.MediaMtx/MediaMtxHostedService.cs => components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs} (78%) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/MediaMtxService.cs (78%) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs (66%) create mode 100644 src/components/BootstrapBlazor.MediaMtx/MediaMtxToolInstaller.cs rename src/{extensions => components}/BootstrapBlazor.MediaMtx/README.MediaMtx.md (68%) rename src/{extensions => components}/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md (59%) 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..000d6f31 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-beta01 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 100% rename from src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs rename to src/components/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs diff --git a/src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxService.cs b/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs similarity index 68% rename from src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxService.cs rename to src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs index 94426337..50768a56 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/IMediaMtxService.cs +++ b/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs @@ -14,6 +14,16 @@ namespace BootstrapBlazor.Components; /// public interface IMediaMtxService { + /// + /// 确保网关已启动并就绪。默认实现复用本宿主的运行中进程,工具缺失时安装 CLI 并部署工具。自定义服务需实现此方法才支持按需启动。 + /// Ensures the gateway is running and ready. The default service reuses its running process and installs the CLI to deploy missing tools. Custom services must implement this method to support on-demand startup. + /// 11.0.0 + /// + /// 取消令牌。The cancellation token. + /// 网关就绪任务。A task that completes when the gateway is ready. + Task EnsureStartedAsync(CancellationToken cancellationToken = default) => + throw new NotSupportedException("This MediaMTX service does not support on-demand startup."); + /// /// 由宿主设置已就绪网关的 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. @@ -24,8 +34,8 @@ public interface IMediaMtxService 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. + /// 登记新路径或更新已有路径的摄像头源配置,返回播放 URL。优先使用摄像头 PlayUrl,否则使用 WebRtcPublicUrl 或同机回环地址与 Path 生成地址。更新可能中断现有播放;成功不代表源已连通。 + /// Registers a new path or updates the camera source configuration and returns its playback URL. Uses the camera's PlayUrl when set, otherwise builds the URL from WebRtcPublicUrl or the loopback address and Path. Updates may interrupt existing playback; success does not verify source connectivity. /// 11.0.0 /// /// 由管理 UI 提交的摄像头配置。Camera configuration submitted by the management UI. diff --git a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs similarity index 77% rename from src/extensions/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs rename to src/components/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs index b46881da..7fb79b9e 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs @@ -19,12 +19,19 @@ public sealed class MediaMtxCameraOptions /// public string? Path { get; set; } + /// + /// 获得/设置浏览器访问的完整 HTTP 或 HTTPS 播放页面地址,不应包含凭据。未设置时使用网关 WebRtcPublicUrl 或本机地址与 Path 生成播放地址;此选项不改变网关监听和 ICE 配置。 + /// Gets or sets the complete browser-facing HTTP or HTTPS player URL without credentials. When unset, the URL is built from WebRtcPublicUrl or the loopback address and Path. 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 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; } + public string? RtspUrl { get; set; } /// /// 获得/设置未进行 URL 编码的摄像头用户名。 diff --git a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs similarity index 93% rename from src/extensions/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs rename to src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs index 51f8cf1d..786331dd 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs @@ -29,8 +29,8 @@ public sealed class MediaMtxOptions 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; missing default tools are deployed automatically, while custom paths must be provisioned separately. /// 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..9ac6f649 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) @@ -72,12 +67,6 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) var settings = options.Value; 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; - } - var httpAddress = $"{Loopback}:{settings.WebRtcPort}"; var apiAddress = $"{Loopback}:{settings.ApiPort}"; var iceAddress = $"{Loopback}:{settings.WebRtcIcePort}"; @@ -85,14 +74,18 @@ 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)) { return false; } + if (!File.Exists(executable)) + { + logger.LogInformation("MediaMTX was not found at {MediaMtxPath}; deploying it through BootstrapBlazor.MediaMtx.Cli.", executable); + await MediaMtxToolInstaller.EnsureInstalledAsync(executable, cancellationToken); + } + var apiPassword = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(_startupTimeout); @@ -123,7 +116,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 +164,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 +179,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 +293,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 78% rename from src/extensions/BootstrapBlazor.MediaMtx/MediaMtxService.cs rename to src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs index 2f5734f7..0835a736 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, IDisposable, IAsyncDisposable { private readonly SemaphoreSlim _gate = new(1, 1); private readonly HashSet _registeredPaths = new(StringComparer.Ordinal); @@ -20,10 +22,11 @@ sealed class MediaMtxService(IOptions options) : IMediaMtxServi Timeout = TimeSpan.FromSeconds(10) }; private string? _apiPassword; + private int _disposeState; public async Task SetGatewayStateAsync(string? apiPassword) { - await _gate.WaitAsync(); + await _gate.WaitAsync().ConfigureAwait(false); try { _apiPassword = apiPassword; @@ -38,15 +41,25 @@ public async Task SetGatewayStateAsync(string? apiPassword) 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 { @@ -137,8 +150,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 +167,27 @@ source.Scheme is not ("rtsp" or "rtsps") || source.Host.Length == 0) return url.Insert(authorityStart, credentials); } - public void Dispose() + public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult(); + + 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 66% rename from src/extensions/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs rename to src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs index e262bc74..802cf66b 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. + /// 从 MediaMtx 配置节绑定选项,注册默认进程启动器和摄像头管理服务,不注册 HostedService。由组件初始化时调用 EnsureStartedAsync 检查并启动网关,默认工具缺失时通过 CLI 部署。保留已注册的自定义进程启动器。 + /// Binds options from the MediaMtx configuration section and registers the default process launcher and camera management service, without a hosted service. Component initialization calls EnsureStartedAsync to check and start the gateway, deploying missing default tools through the CLI. 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/MediaMtxToolInstaller.cs b/src/components/BootstrapBlazor.MediaMtx/MediaMtxToolInstaller.cs new file mode 100644 index 00000000..2c2f0fbe --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/MediaMtxToolInstaller.cs @@ -0,0 +1,82 @@ +// 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.Diagnostics; + +namespace BootstrapBlazor.Components; + +static class MediaMtxToolInstaller +{ + internal static async Task EnsureInstalledAsync(string executable, CancellationToken cancellationToken) + { + var defaultPath = Path.GetFullPath(new MediaMtxOptions().MediaMtxPath, AppContext.BaseDirectory); + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + if (!string.Equals(executable, defaultPath, comparison)) + { + throw new FileNotFoundException("Provision MediaMTX at the configured custom path before starting the gateway.", executable); + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromMinutes(5)); + var toolPath = Path.Combine(AppContext.BaseDirectory, "mediamtx-tools", "cli"); + var cli = Path.Combine(toolPath, OperatingSystem.IsWindows() ? "bb-mediamtx.exe" : "bb-mediamtx"); + if (!File.Exists(cli)) + { + await RunAsync("dotnet", + ["tool", "install", "BootstrapBlazor.MediaMtx.Cli", "--prerelease", "--tool-path", toolPath], + timeout.Token); + } + + await RunAsync(cli, [], timeout.Token); + if (!File.Exists(executable)) + { + throw new FileNotFoundException("The MediaMTX CLI completed without deploying the expected executable.", executable); + } + } + + private static async Task RunAsync(string fileName, string[] arguments, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + var startInfo = new ProcessStartInfo(fileName) + { + WorkingDirectory = AppContext.BaseDirectory, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (var argument in arguments) + { + startInfo.ArgumentList.Add(argument); + } + + using var process = Process.Start(startInfo) + ?? throw new InvalidOperationException($"Could not start {Path.GetFileName(fileName)}."); + // Drain output without logging package-source credentials or inherited configuration. + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + try + { + await process.WaitForExitAsync(cancellationToken); + } + catch (OperationCanceledException) + { + try + { + process.Kill(entireProcessTree: true); + } + catch (InvalidOperationException) when (process.HasExited) + { + } + await process.WaitForExitAsync(CancellationToken.None); + throw; + } + + if (process.ExitCode != 0) + { + throw new InvalidOperationException($"{Path.GetFileName(fileName)} failed with exit code {process.ExitCode}. Verify the .NET SDK, package sources, network access and application directory permissions."); + } + } +} diff --git a/src/extensions/BootstrapBlazor.MediaMtx/README.MediaMtx.md b/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md similarity index 68% rename from src/extensions/BootstrapBlazor.MediaMtx/README.MediaMtx.md rename to src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md index 3060ccfe..b2b124a3 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/README.MediaMtx.md +++ b/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md @@ -1,13 +1,13 @@ # BootstrapBlazor.MediaMtx -ASP.NET Core 动态 RTSP 摄像头服务。一个托管的 MediaMTX 进程管理多个播放路径。 +ASP.NET Core 动态 RTSP 摄像头服务。组件初始化时按需启动一个 MediaMTX 进程,管理多个播放路径,不使用 HostedService。 启动不连接摄像头;首次观看时通过 RTSP/TCP 按需拉流,转发为 WebRTC。 主包提供默认进程启动器,但不附带 MediaMTX;通过 `bb-mediamtx` CLI 从 GitHub 下载或自行部署工具,详见“工具部署与进程生命周期”。 ## 注册与网关配置 ```csharp -// 先准备工具缓存并配置宿主复制工具,所有平台使用同一个注册入口: +// 仅注册服务;不会随应用启动而安装或运行 MediaMTX: builder.Services.AddMediaMtxService(); ``` @@ -19,11 +19,11 @@ builder.Services.AddMediaMtxService(); "ApiPort": 9997, "Cameras": { "hikvision": { - "Url": "rtsp://192.0.2.1:554/stream", + "RtspUrl": "rtsp://192.0.2.1:554/stream", "UserName": "camera" }, "gate": { - "Url": "rtsp://192.0.2.2:554/stream", + "RtspUrl": "rtsp://192.0.2.2:554/stream", "UserName": "camera" } } @@ -32,7 +32,7 @@ builder.Services.AddMediaMtxService(); ``` `Cameras` 是可选的静态摄像头字典,网关启动时自动登记,无需调用 `AddOrUpdateAsync`。 -键即播放路径,值包含不含凭据的 `Url` 和可选的 `UserName`、`Password`,值中的 `Path` 会被忽略;路径和 URL 规则与动态登记相同。 +键即播放路径,值包含不含凭据的 `RtspUrl` 和可选的 `UserName`、`Password`、`PlayUrl`,值中的 `Path` 会被忽略;路径和 URL 规则与动态登记相同。不兼容旧的 `Url` 配置键。 密码应通过 User Secrets 或环境变量等安全配置源提供,不要提交到 `appsettings.json`。 User Secrets 的 `secrets.json` 使用与 `appsettings.json` 相同的层次结构,按路径合并: @@ -54,21 +54,57 @@ User Secrets 的 `secrets.json` 使用与 `appsettings.json` 相同的层次结 不再支持原来的全局 `Url`、`UserName`、`Password`。 `AddMediaMtxService` 注册默认进程启动器和主服务,从 `MediaMtx` 配置节绑定选项,也可通过 `configureOptions` 回调覆盖选项。 `BootstrapBlazor.MediaMtx` 核心包负责网关进程生命周期和摄像头管理;原生工具由独立的 `BootstrapBlazor.MediaMtx.Cli` 部署,所有平台统一调用 `AddMediaMtxService`。 -默认启动器支持 Windows x64、Linux x64/ARM64/ARMv7 和 macOS x64/ARM64。不支持的操作系统或系统架构会记录警告并跳过网关,宿主仍可启动。 +默认启动器支持 Windows x64、Linux x64/ARM64/ARMv7 和 macOS x64/ARM64。不支持的操作系统或系统架构会记录警告,并向 Init 调用方报告启动失败。 自行实现 `IMediaMtxProcessLauncher` 时,在调用 `AddMediaMtxService` 前注册该接口,默认启动器不会覆盖已有注册;启动器使用宿主提供的 `ProcessStartInfo` 启动并返回进程,宿主负责就绪探测和清理。 HTTP 和 Control API 使用不同 TCP 端口,ICE 使用 UDP。 Control API 仅监听回环地址,使用每个宿主实例生成的内部随机密码,不提供浏览器调用入口。 `IMediaMtxService.SetGatewayStateAsync` 仅供宿主同步网关状态;自定义实现应在密码为 `null` 时 停止管理请求,并在网关就绪后使用提供的密码认证 Control API 请求。 +### WebRTC 首次加载时启动 + +在服务端注册服务,不注册 HostedService,也不在应用启动时运行网关: + +```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 安装到 `mediamtx-tools\cli`,随后在应用目录执行 CLI, +部署 `mediamtx-tools\` 后再启动并等待 Control API 就绪。不会全局安装工具或修改工具清单。 +安装部署合计最多等待 5 分钟,网关就绪最多等待 10 秒;支持取消,失败向调用方抛出异常,后续调用可重试。 +运行时安装要求服务器提供 .NET SDK、可写的应用目录,并能访问 NuGet 包源及 GitHub(或已有有效缓存)。 +生产或离线部署仍建议提前准备原生工具,已存在工具时不会安装 CLI 或下载。 +自定义 `MediaMtxPath` 缺失时不会自动覆盖或复制到该路径,需自行部署。 +自定义 `IMediaMtxService` 要支持此接入方式,需实现 `EnsureStartedAsync`。 + ### MediaMTX 配置 -MediaMTX 的配置由组件生成,不支持用户提供的 MediaMTX JSON 配置文件。 -组件关闭 RTSP、RTMP、HLS、SRT、MoQ 等监听器,并配置本机 Control API 和 WebRTC。 -端口和摄像头通过 `MediaMtx` 选项设置;组件将配置写入临时 YAML 文件供子进程启动, +MediaMTX 的配置由服务生成,不支持用户提供的 MediaMTX JSON 配置文件。 +服务关闭 RTSP、RTMP、HLS、SRT、MoQ 等监听器,并配置本机 Control API 和 WebRTC。 +端口和摄像头通过 `MediaMtx` 选项设置;服务将配置写入临时 YAML 文件供子进程启动, 摄像头源地址和内部 API 密码仅通过子进程环境传递。正常停止时会清理临时文件, 强制终止进程时可能无法清理。 -组件将子进程日志限制到标准输出并丢弃,不转发可能含源凭据的输出。 +服务将子进程日志限制到标准输出并丢弃,不转发可能含源凭据的输出。 ## UI 动态登记 @@ -81,7 +117,7 @@ MediaMTX 的配置由组件生成,不支持用户提供的 MediaMTX JSON 配 - + @@ -92,7 +128,7 @@ MediaMTX 的配置由组件生成,不支持用户提供的 MediaMTX JSON 配 } @if (playerUrl is not null) { - + } @code { @@ -107,6 +143,7 @@ MediaMTX 的配置由组件生成,不支持用户提供的 MediaMTX JSON 配 error = null; try { + await MediaMtx.EnsureStartedAsync(); playerUrl = await MediaMtx.AddOrUpdateAsync(camera); } catch (ArgumentException) @@ -134,7 +171,7 @@ MediaMTX 的配置由组件生成,不支持用户提供的 MediaMTX JSON 配 } ``` -页面所在应用同时引用 `BootstrapBlazor.HikVision` 才能使用播放器。 +此手动管理示例使用原生 iframe;使用 HikVision 时只需传入 `Options`,不要重复调用登记方法。 `IMediaMtxService.AddOrUpdateAsync(camera)` 按 `Path` 登记新路径或更新已有路径的源和凭据。默认服务对未记录的路径优先新增,对已成功登记或更新的路径优先更新;若网关报告路径已存在或不存在,则改用相应的操作。删除成功或网关状态变更后会清除相应记录。更新已有路径可能中断现有播放。 另一个摄像头使用 `parking` 等不同 Path 即可同时播放。 Path 必须以小写字母开头,仅包含小写字母、数字和连字符,最长 63 个字符,不允许保留名称 `all`。 @@ -142,11 +179,11 @@ RTSP/RTSPS URL 必须包含显式端口和流路径,不允许内嵌凭据、 用户名、密码传原始值,服务端负责 URL 编码;提供密码时必须提供用户名。 示例在每次登记操作结束后清空密码,再次登记时需要重新输入。 -`AddOrUpdateAsync` 默认返回 `http://127.0.0.1://`。 +`AddOrUpdateAsync` 优先返回摄像头的 `PlayUrl`;未设置时默认返回 `http://127.0.0.1://`。 如果 nginx 已将公开地址反向代理到本机 WebRTC HTTP 端口,可在 `MediaMtx` 配置节设置 `"WebRtcPublicUrl": "https://example.com/mediamtx/"`,返回的地址将以该基址开头。 支持带路径前缀的绝对 HTTP/HTTPS 地址,不允许包含凭据、查询字符串或片段;未设置时使用回环地址。 -组件同时允许该地址的来源访问 WebRTC 信令。代理需要正确转发播放页面、WHEP 请求及会话地址; +服务同时允许该地址的来源访问 WebRTC 信令。单路 `PlayUrl` 不改变允许的来源或 ICE 配置,应与 `WebRtcPublicUrl` 对应的反向代理配置一致。代理需要正确转发播放页面、WHEP 请求及会话地址; 路径前缀场景还需正确处理上游 `Location` 响应头。 `RemoveAsync(path)` 显式删除路径并影响所有观看者;关闭播放器不会自动删除路径。 多个观看者共享一路源,未观看时按 MediaMTX 的按需设置停止拉流。 @@ -195,23 +232,23 @@ 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 使用提交的清单和宿主维护的调用规则,不提交工具缓存。 +普通 NuGet restore 不下载 MediaMTX;宿主应跳过 IDE 设计时构建。运行时默认路径的工具缺失时,服务自动调用 CLI 准备工具。输出缺文件且缓存不可用时需要访问 GitHub,下载或校验失败通过非零退出码报告。离线环境预先准备 CLI 包,并在有网络时于空的输出目录执行默认命令预热对应 RID 的工具缓存。 +构建使用的 CLI 版本由宿主根目录工具清单固定;运行时回退执行 `dotnet tool install BootstrapBlazor.MediaMtx.Cli --prerelease --tool-path <应用目录>\mediamtx-tools\cli`,已有该目录下的 CLI 时直接复用。默认 MediaMTX 版本由 CLI 固定。源码开发需先手动打包并还原 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`。相对路径以应用目录为基准。 -找不到工具时记录警告并跳过网关,宿主正常启动,管理调用报告网关未运行。 +默认路径找不到工具时尝试自动部署;自定义路径缺失或安装失败时向 Init 调用方报告异常。 在 Linux/macOS 上执行 CLI 时会自动设置工具执行权限;从 Windows 跨平台发布后,需要在目标机器设置执行权限,例如 Linux x64 使用 `chmod a+x mediamtx-tools/linux-x64/mediamtx`。 启动时在 10 秒内重试已认证的 Control API 请求,不依赖子进程日志。只有子进程仍在运行且 Control API 返回 HTTP 200,网关才标记为就绪。 就绪日志包含 PID、工具路径、WebRTC 基址和 ICE 地址,不包含摄像头源或凭据。 -路径有效但进程启动、就绪探测失败或超时时记录错误日志并跳过网关,宿主正常启动;停止时尝试回收自有进程和临时配置文件,清理失败记录错误日志。 +进程启动、就绪探测失败或超时时向 Init 调用方报告异常,并清理本次启动的进程和临时配置文件;失败后可重新调用。服务容器释放单例服务时回收自有进程和临时配置文件,清理失败记录错误日志。 默认启动器使用 .NET `Process` 启动进程,主包负责管理和停止;宿主被强制终止时不保证自动回收 MediaMTX。 -下次启动网关前,会结束可执行文件完整路径与 `MediaMtx:MediaMtxPath` 解析结果相同的现有进程,并等待退出后再启动。 -同一路径的 MediaMTX 应由一个宿主管理;启动新宿主会中断该路径下已有实例的播放。其他目录的实例不会被结束。 +重复调用启动入口会复用本宿主的运行中进程,不会重新安装或重启。 +服务不终止或接管其他宿主及手动启动的实例,因为其 Control API 凭据不属于当前宿主;若占用配置端口会报告错误,不中断已有播放。 启动前检查 WebRTC HTTP、Control API 的 TCP 端口和 ICE 的 UDP 端口是否可绑定。 -地址仍不可用或被其他进程占用时记录错误日志并跳过网关,宿主正常启动,管理调用报告网关未运行;应检查端口配置及占用情况,处理后重启。 +地址仍不可用或被其他进程占用时记录错误日志,并向 Init 调用方报告失败;应检查端口配置及占用情况,处理后重试。 端口检查与进程启动之间仍可能发生竞争,此时同样记录错误日志并给出处理提示。 -网关配置修改后需要重启应用。程序不自动重启崩溃的 MediaMTX;管理调用会报告连接失败。 +网关配置修改后需要重启应用。程序不在后台持续重启崩溃的 MediaMTX;再次调用 `EnsureStartedAsync` 会尝试重新启动,动态摄像头需重新登记。 diff --git a/src/extensions/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md b/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md similarity index 59% rename from src/extensions/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md rename to src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md index cd17749b..b0063097 100644 --- a/src/extensions/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md +++ b/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md @@ -12,7 +12,7 @@ description: 提供 BootstrapBlazor.MediaMtx 的配置与 API 参考。适用于 ## 注册与配置 ```csharp -// 先准备工具缓存并配置宿主复制工具,所有平台使用同一个注册入口: +// 仅注册服务;不会随应用启动而安装或运行 MediaMTX: builder.Services.AddMediaMtxService(); ``` @@ -28,14 +28,16 @@ builder.Services.AddMediaMtxService(); - `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 的工具缓存;失败通过非零退出码报告。 +- CLI 将工具和许可证部署到当前目录的 `mediamtx-tools\`;默认两者都存在时立即结束,不读取内容或检查缓存,缺文件时只补齐缺失文件。升级或修复使用 `--force`,校验缓存后覆盖两个输出文件,不强制重新下载;可与 `--rid` 组合,参数顺序不限。宿主的 `dotnet publish --no-build` 仍可通过发布规则调用 CLI,单文件发布时工具仍保留在外部。普通 NuGet restore 不下载 MediaMTX;运行时默认路径的可执行文件缺失时,会自动安装 CLI 并准备工具。离线环境仍应提前部署工具。 +- 不注册 HostedService,也没有 StartOnDemand 开关。HikVision 引用本包,`HikVisionWebRtc.Options` 使用 `MediaMtxCameraOptions`。组件首次交互渲染时依次调用 `IMediaMtxService.EnsureStartedAsync()` 和 `AddOrUpdateAsync()`,完成前显示黑底占位,完成后显示 iframe;预渲染不会触发。自定义服务需实现启动和登记方法。工具部署、进程管理及 Control API 请求都属于 MediaMtx 服务,组件只负责展示。 +- `EnsureStartedAsync` 串行检查并复用本宿主的运行中进程。默认路径没有工具时,执行 `dotnet tool install BootstrapBlazor.MediaMtx.Cli --prerelease --tool-path <应用目录>\mediamtx-tools\cli`,已有该目录下的 CLI 则复用;随后以应用目录为工作目录运行 `bb-mediamtx`,再启动网关并探测就绪。安装部署最多等待 5 分钟,就绪最多等待 10 秒;取消或失败抛出异常,后续可重试。要求服务器有 .NET SDK、目录写权限及相应网络/缓存;不会全局安装或修改工具清单。自定义工具路径缺失时需自行部署。 - `MediaMtxPath` 默认为应用目录下的 `mediamtx-tools\<平台-架构>\<可执行文件>`,例如 `mediamtx-tools\win-x64\mediamtx.exe`;可通过配置指定其他路径,相对路径以应用目录为基准。在 Linux/macOS 上执行 CLI 会自动设置执行权限;从 Windows 跨平台发布后需在目标机器设置执行权限。 -- `AddMediaMtxService` 同时注册默认进程启动器和主服务,从 `MediaMtx` 配置节绑定选项,也支持通过 `configureOptions` 回调覆盖选项。自行实现 `IMediaMtxProcessLauncher` 时,在调用 `AddMediaMtxService` 前注册该接口,默认启动器不会覆盖已有注册;启动器使用宿主提供的 `ProcessStartInfo` 启动并返回进程,宿主负责就绪探测和清理。不支持的操作系统或系统架构会记录警告并跳过网关,宿主继续启动。 +- `AddMediaMtxService` 同时注册默认进程启动器和主服务,从 `MediaMtx` 配置节绑定选项,也支持通过 `configureOptions` 回调覆盖选项。自行实现 `IMediaMtxProcessLauncher` 时,在调用 `AddMediaMtxService` 前注册该接口,默认启动器不会覆盖已有注册;启动器使用服务提供的 `ProcessStartInfo` 启动并返回进程,服务负责就绪探测和清理。不支持的操作系统或系统架构会记录警告,并由 Init 调用报告启动失败。 - 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:Cameras` 是以播放路径为键的静态摄像头字典,值提供 `RtspUrl` 和可选的 `UserName`、`Password`、`PlayUrl`(值中的 `Path` 被忽略),网关启动时自动登记,无需手动调用 `AddOrUpdateAsync`。不兼容旧的 `Url` 字段。密码通过 User Secrets(`secrets.json` 中与 `appsettings.json` 相同的层次结构)或环境变量(如 `MediaMtx__Cameras__hikvision__Password`)提供。修改后重启应用。 +- MediaMTX 配置由服务生成,不支持用户提供的 MediaMTX JSON 配置文件。服务生成临时 YAML,摄像头源地址和内部 API 密码仅通过子进程环境传递;就绪探测使用已认证的 Control API 请求,不依赖子进程日志。 +- 安装、启动或就绪探测失败时向 Init 调用方抛出异常;后续调用可重试。网关未运行时摄像头管理调用抛出 `InvalidOperationException`。 +- 服务容器释放单例服务时会尝试回收自有 MediaMTX 进程和临时配置文件。重复启动请求复用本服务的运行中实例,不终止或接管其他宿主、手动启动的实例;端口被占用时报告错误,不中断已有播放。进程退出后,再次调用 `EnsureStartedAsync` 可尝试重启;动态摄像头需重新登记。 - 本包只支持 MediaMTX,不支持其他 RTSP 转流工具。 ## 摄像头管理 @@ -43,8 +45,8 @@ builder.Services.AddMediaMtxService(); 在服务端(如 Interactive Server 页面)注入 `IMediaMtxService`: - 调用方应校验唯一播放路径 `MediaMtxCameraOptions.Path`:以小写字母开头,只允许小写字母、数字和连字符,最长 63 个字符,不能是 `all`。删除时传入已登记的路径。 -- `Url` 为不含凭据、查询字符串或片段的 RTSP/RTSPS 地址,必须显式指定端口和流路径。`UserName`、`Password` 使用未编码的原始值;提供密码时必须提供用户名。 -- `IMediaMtxService.AddOrUpdateAsync(camera)` 登记新路径或更新已有路径的源和凭据,返回可传给 `BootstrapBlazor.HikVision` 的 `HikVisionWebRtc.WebRtcUrl` 的播放 URL。成功只表示网关接受配置,不代表摄像头已连通;更新可能中断现有播放。 +- `RtspUrl` 为不含凭据、查询字符串或片段的 RTSP/RTSPS 地址,必须显式指定端口和流路径。`UserName`、`Password` 使用未编码的原始值;提供密码时必须提供用户名。 +- `IMediaMtxService.AddOrUpdateAsync(camera)` 登记新路径或更新已有路径的源和凭据,返回播放 URL。HikVision 通过 `Options` 传入摄像头配置并在内部调用服务。成功只表示网关接受配置,不代表摄像头已连通;更新可能中断现有播放。 - 默认服务记住当前网关中已成功登记或更新的路径,后续优先更新;路径状态不一致时以网关为准。 - `RemoveAsync(path)` 显式删除路径并影响所有观看者。关闭页面不会删除路径。 - 多路摄像头使用不同路径,共用一个网关;首次观看时通过 RTSP/TCP 按需拉流。动态配置只保存在 MediaMTX 内存中,重启后需由宿主恢复;`Cameras` 中的静态配置会在启动时重新加载。 @@ -53,7 +55,7 @@ builder.Services.AddMediaMtxService(); ## 播放与声音 -- 默认返回 `http://127.0.0.1://`;可设置 `WebRtcPublicUrl` 为已配置的 WebRTC HTTP 反向代理基址,播放 URL 和允许的信令来源随之调整。HTTP、Control API 和 ICE 仍仅监听回环地址;普通 HTTP 代理不提供远程 ICE 媒体路径,远程播放仍需另行配置可达的媒体路径、HTTPS 与鉴权。 +- 摄像头 `PlayUrl` 非空时优先返回该完整 HTTP/HTTPS 地址(不允许凭据);否则默认返回 `http://127.0.0.1://`。可设置 `WebRtcPublicUrl` 为反向代理基址,默认播放地址和允许的信令来源随之调整。单路 `PlayUrl` 不改变允许的来源,应与公开基址的代理配置对应。HTTP、Control API 和 ICE 仍仅监听回环地址;远程播放需另行配置可达的媒体路径、HTTPS 与鉴权。 - MediaMTX 在此方案中转发协议,不自动转码。摄像头需启用音频并选择浏览器支持的 WebRTC 编码,例如 G.711 μ-law(PCMU)或 A-law(PCMA);AAC 等不兼容编码需另行转码。 - MediaMTX 播放页默认静音,用户需在播放器中取消静音。无声音时还应检查摄像头的音频配置及源流。 From 60b6a63f838c133c7c158f40f1126843faf1238a Mon Sep 17 00:00:00 2001 From: Argo Zhang Date: Tue, 1 Dec 2026 16:13:55 +0800 Subject: [PATCH 02/19] =?UTF-8?q?chore:=20=E6=9B=B4=E6=96=B0=20HikVision?= =?UTF-8?q?=20=E7=BB=84=E4=BB=B6=E4=BE=9D=E8=B5=96=20MediaMtx=20=E5=B7=A5?= =?UTF-8?q?=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BootstrapBlazor.HikVision.csproj | 14 ++- .../Components/HikVisionWebRtc.razor | 38 +++++-- .../Components/HikVisionWebRtc.razor.cs | 89 ++++++++++++++-- .../BootstrapBlazor.HikVision/Locales/en.json | 8 ++ .../BootstrapBlazor.HikVision/Locales/zh.json | 8 ++ .../skills/bb-hikvision/SKILL.md | 100 ++++++++---------- 6 files changed, 182 insertions(+), 75 deletions(-) create mode 100644 src/components/BootstrapBlazor.HikVision/Locales/en.json create mode 100644 src/components/BootstrapBlazor.HikVision/Locales/zh.json diff --git a/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj b/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj index 4c5fee95..db01ede3 100644 --- a/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj +++ b/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj @@ -1,21 +1,31 @@ - 11.0.2 + 11.0.3-beta01 bb-hikvision - Bootstrap Blazor WebAssembly wasm UI Components HikVision WebRTC + Bootstrap Blazor Server UI Components HikVision WebRTC Bootstrap UI components extensions of HikVision + + + + + + + + + + diff --git a/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor b/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor index 41e5204c..6d97101d 100644 --- a/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor +++ b/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor @@ -1,13 +1,33 @@ @namespace BootstrapBlazor.Components @inherits BootstrapComponentBase -@if (PlayerUrl is { } url) -{ -
+
+ @if (Options is null) + { +
+ @Localizer["OptionsMissingText"] +
+ } + else if (_initializing) + { +
+ @Localizer["InitializingText"] +
+ } + else if (string.IsNullOrEmpty(_registeredUrl)) + { + + } + else if (PlayerUrl is { } url) + { -
-} -else -{ -
WebRtcUrl must be an absolute HTTP or HTTPS player URL without credentials.
-} + } + else + { + + } +
diff --git a/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs b/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs index 3660c6ad..5614d351 100644 --- a/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs +++ b/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs @@ -3,6 +3,8 @@ // Website: https://www.blazor.zone or https://argozhang.github.io/ using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; using System.Web; namespace BootstrapBlazor.Components; @@ -12,15 +14,15 @@ namespace BootstrapBlazor.Components; /// Displays a live WebRTC preview from a Hikvision camera using the MediaMTX player page /// 11.0.2 ///
-public partial class HikVisionWebRtc +public partial class HikVisionWebRtc : IDisposable { /// - /// 获得/设置浏览器访问的 WebRTC 播放页面地址,例如经 nginx 代理后的完整地址,不应包含凭据,应保留播放路径结尾的 /。如 http://camera.blazor.zone/hikvision/ - /// Gets or sets the browser-accessible WebRTC player URL, such as a complete URL behind an nginx proxy, without credentials. Keep the trailing / of the player path. - /// 11.0.2 + /// 获得/设置摄像头配置。首次交互渲染时调用 IMediaMtxService 启动网关并登记摄像头,就绪后显示播放器。需在服务端注册 AddMediaMtxService。 + /// Gets or sets the camera options. On the first interactive render, calls IMediaMtxService to start the gateway and register the camera before displaying the player. Requires AddMediaMtxService on the server. + /// 11.0.3 /// [Parameter] - public string? WebRtcUrl { get; set; } + public MediaMtxCameraOptions? Options { get; set; } /// /// 获得/设置 播放器的无障碍标题 @@ -38,6 +40,15 @@ public partial class HikVisionWebRtc [Parameter] public bool IsMuted { get; set; } = true; + [Inject, NotNull] + private IStringLocalizer? Localizer { get; set; } + + [Inject, NotNull] + private ILogger? Log { get; set; } + + [Inject, NotNull] + private IMediaMtxService? MediaMtxService { get; set; } + private string? ClassString => CssBuilder.Default("ratio ratio-16x9") .AddClassFromAttributes(AdditionalAttributes) .Build(); @@ -48,9 +59,59 @@ public partial class HikVisionWebRtc private Uri? PlayerUrl => GetPlayerUrl(); + private bool _initializing = true; + + private string? _registeredUrl; + + private readonly CancellationTokenSource _initializationCancellation = new(); + + private bool _disposed; + + /// + /// + /// + protected override async Task OnAfterRenderAsync(bool firstRender) + { + await base.OnAfterRenderAsync(firstRender); + + if (!firstRender || _disposed) + { + return; + } + + var cancellationToken = _initializationCancellation.Token; + try + { + if (Options is { } options) + { + await MediaMtxService.EnsureStartedAsync(cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + + var registeredUrl = await MediaMtxService.AddOrUpdateAsync(options, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + _registeredUrl = registeredUrl; + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + catch (Exception ex) + { + Log.LogError(ex, "Failed to initialize the MediaMTX gateway or register the camera for WebRTC preview. Check the camera path and RTSP URL, MediaMTX installation, network access, and listener ports."); + } + finally + { + _initializing = false; + if (!_disposed) + { + StateHasChanged(); + } + } + } + private Uri? GetPlayerUrl() { - if (!Uri.TryCreate(WebRtcUrl, UriKind.Absolute, out var url) || + if (!Uri.TryCreate(Options?.PlayUrl ?? _registeredUrl, UriKind.Absolute, out var url) || url.Scheme is not ("http" or "https") || url.UserInfo.Length != 0) { return null; @@ -65,4 +126,20 @@ url.Scheme is not ("http" or "https") || url.UserInfo.Length != 0) query["muted"] = "false"; return new UriBuilder(url) { Query = query.ToString() }.Uri; } + + /// + /// + /// + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + _initializationCancellation.Cancel(); + _initializationCancellation.Dispose(); + GC.SuppressFinalize(this); + } } diff --git a/src/components/BootstrapBlazor.HikVision/Locales/en.json b/src/components/BootstrapBlazor.HikVision/Locales/en.json new file mode 100644 index 00000000..90e912df --- /dev/null +++ b/src/components/BootstrapBlazor.HikVision/Locales/en.json @@ -0,0 +1,8 @@ +{ + "BootstrapBlazor.Components.HikVisionWebRtc": { + "OptionsMissingText": "Camera configuration is missing. Unable to initialize the player.", + "InitializingText": "Initializing camera, please wait ...", + "InitializationFailedText": "Camera initialization failed.", + "InvalidUrlText": "The player URL must be an absolute HTTP or HTTPS URL without credentials." + } +} diff --git a/src/components/BootstrapBlazor.HikVision/Locales/zh.json b/src/components/BootstrapBlazor.HikVision/Locales/zh.json new file mode 100644 index 00000000..5a1260a3 --- /dev/null +++ b/src/components/BootstrapBlazor.HikVision/Locales/zh.json @@ -0,0 +1,8 @@ +{ + "BootstrapBlazor.Components.HikVisionWebRtc": { + "OptionsMissingText": "未配置摄像头,无法初始化播放器。", + "InitializingText": "正在初始化摄像头,请稍后 ...", + "InitializationFailedText": "摄像头初始化失败。", + "InvalidUrlText": "播放地址必须是不含凭据的绝对 HTTP 或 HTTPS 地址。" + } +} diff --git a/src/components/BootstrapBlazor.HikVision/skills/bb-hikvision/SKILL.md b/src/components/BootstrapBlazor.HikVision/skills/bb-hikvision/SKILL.md index 88eed86a..8d713c22 100644 --- a/src/components/BootstrapBlazor.HikVision/skills/bb-hikvision/SKILL.md +++ b/src/components/BootstrapBlazor.HikVision/skills/bb-hikvision/SKILL.md @@ -5,93 +5,77 @@ description: 随 BootstrapBlazor.HikVision NuGet 包提供的 API 参考。需 # HikVision API 参考 -此 skill 随 `BootstrapBlazor.HikVision` NuGet 包分发,用于集成海康威视 Web 插件或无插件 WebRTC 预览。参考文档从打包时的工程源码生成。 - -先阅读 [references/llms.txt](references/llms.txt) 确认当前包收录的组件和服务,再按需读取对应的 API 文档: +此 skill 随 `BootstrapBlazor.HikVision` NuGet 包分发。先阅读 [references/llms.txt](references/llms.txt) 确认当前包收录的组件,再读取对应的 API 文档: - [HikVisionWebPlugin](references/components/HikVisionWebPlugin.txt) - [HikVisionWebRtc](references/components/HikVisionWebRtc.txt) -## 两种预览方式 +## 项目依赖与职责 + +HikVision 引用 `BootstrapBlazor.MediaMtx`,网关需要支持运行进程的服务端宿主,不适用于独立 WebAssembly 宿主。 -- `HikVisionWebPlugin`:在浏览器加载海康 WebSDK 静态资源,用摄像机账号登录,支持实时预览、抓图、通道列表和声音开关。 -- `HikVisionWebRtc`:只嵌入 MediaMTX 的 WebRTC 播放页,浏览器不需要海康插件,摄像机凭据留在服务端,但需要另行托管网关。 +- `HikVisionWebPlugin` 在浏览器加载海康 WebSDK,通过摄像机账号登录,支持预览、抓图、通道列表和声音开关。 +- `HikVisionWebRtc` 负责初始化占位、错误提示和 iframe 展示。首次交互渲染时调用注入的 `IMediaMtxService`,不管理进程、下载工具或直接调用 Control API。 +- `BootstrapBlazor.MediaMtx` 负责共享网关的启动、就绪探测、摄像头登记及进程清理;CLI 只负责工具下载和复制。不使用 HostedService。 ## WebRTC 预览 -`HikVisionWebRtc` 将 MediaMTX 的 WebRTC 播放页面嵌入 16:9 的 iframe,无需安装海康威视 Web 插件。组件只显示播放地址,不负责登记摄像头、读取凭据或启动网关。 +在服务端注册: -网关和摄像头可由 `BootstrapBlazor.MediaMtx` 核心包管理:所有平台统一调用 `AddMediaMtxService()`,核心包提供默认进程启动器,但不附带原生工具。宿主维护根目录 `dotnet-tools.json` 和 `Directory.Build.targets`,在 Build、Publish 完成后还原 CLI,再到输出目录执行 `dotnet bb-mediamtx`。`BootstrapBlazor.MediaMtx.Cli` 按目标 RID 准备并复制 MediaMTX 可执行文件和许可证,本机平台自动识别,跨平台传入 `--rid`;也可由宿主自行部署原生工具。调用页面在服务端自行登记摄像头,再将返回的播放地址传给组件。注册、配置和摄像头管理的细节以该包的 `bb-mediamtx` skill 为准。 +```csharp +builder.Services.AddBootstrapBlazor(); +builder.Services.AddMediaMtxService(); +``` -下面的示例同时引用 `BootstrapBlazor.HikVision` 与 `BootstrapBlazor.MediaMtx`,宿主已准备工具并调用 `AddMediaMtxService()`;`IMediaMtxService` 由 MediaMtx 包提供,不属于 HikVision 包。 +在已授权的 Interactive Server 页面使用: ```razor -@inject IMediaMtxService MediaMtxService - -