diff --git a/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj b/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj index 8cbcfcdd..62dde65a 100644 --- a/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj +++ b/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj @@ -8,6 +8,7 @@ Bootstrap Blazor Server UI Components HikVision WebRTC Bootstrap UI components extensions of HikVision + README.HikVision.md diff --git a/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj b/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj index f4d79680..37dd3bc0 100644 --- a/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj +++ b/src/components/BootstrapBlazor.MediaMtx/BootstrapBlazor.MediaMtx.csproj @@ -1,7 +1,7 @@ - + - 11.0.4 + 11.0.5 bb-mediamtx @@ -19,6 +19,11 @@ + + + + + diff --git a/src/components/BootstrapBlazor.MediaMtx/Components/MediaMtxPlayer.razor b/src/components/BootstrapBlazor.MediaMtx/Components/MediaMtxPlayer.razor new file mode 100644 index 00000000..3e9db3ce --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/Components/MediaMtxPlayer.razor @@ -0,0 +1,40 @@ +@namespace BootstrapBlazor.Components +@inherits BootstrapComponentBase + +
+ @if (Options is null) + { +
+ @Localizer["OptionsMissingText"] +
+ } + else if (_initializing) + { +
+ @Localizer["InitializingText"] +
+ } + else if (string.IsNullOrEmpty(_registeredUrl)) + { + + } + else if (PlayerUrl is { } url) + { + + } + else + { + + } +
diff --git a/src/components/BootstrapBlazor.MediaMtx/Components/MediaMtxPlayer.razor.cs b/src/components/BootstrapBlazor.MediaMtx/Components/MediaMtxPlayer.razor.cs new file mode 100644 index 00000000..767471e8 --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/Components/MediaMtxPlayer.razor.cs @@ -0,0 +1,184 @@ +// Copyright (c) BootstrapBlazor & Argo Zhang (argo@live.ca). All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// 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; + +/// +/// 通过 MediaMTX 播放页面以 WebRTC 方式实时预览 RTSP 或 RTSPS 摄像机。 +/// Displays a live WebRTC preview of an RTSP or RTSPS camera using the MediaMTX player page. +/// 11.0.6 +/// +public partial class MediaMtxPlayer : IDisposable +{ + /// + /// 获得/设置摄像头配置。首次交互渲染时调用 IMediaMtxService 启动网关并登记摄像头,成功后显示播放器。需在服务端注册 AddMediaMtxService 并提前部署 MediaMTX 工具;组件不负责下载工具。首次渲染后更改配置不会重新登记。 + /// 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 and pre-deployed MediaMTX tools; the component does not download tools. Changing the options after the first render does not re-register the camera. + /// 11.0.6 + /// + [Parameter] + public MediaMtxCameraOptions? Options { get; set; } + + /// + /// 获得/设置播放器的无障碍标题。 + /// Gets or sets the accessible title of the player. + /// 11.0.6 + /// + [Parameter] + public string Title { get; set; } = "WebRTC"; + + /// + /// 获得/设置静音选项,默认值为 true,此时保留原播放地址,不覆盖已有的 muted 参数。设为 false 时写入 muted=false,有声自动播放仍受浏览器策略限制。 + /// Gets or sets the mute option. Defaults to true, preserving the original player URL and any existing muted parameter. Set to false to write muted=false; audible autoplay remains subject to browser policies. + /// 11.0.6 + /// + [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(); + + private string? StyleString => CssBuilder.Default() + .AddStyleFromAttributes(AdditionalAttributes) + .Build(); + + private Uri? PlayerUrl => GetPlayerUrl(); + + private bool _initializing = true; + + private string? _registeredUrl; + + private string _failureTextKey = "RegistrationFailedText"; + + private string? _missingToolPath; + + 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; + if (Options is { } options) + { + var started = await TryEnsureStartedAsync(cancellationToken); + if (started) + { + _registeredUrl = await RegisterUrl(options, cancellationToken); + } + } + _initializing = false; + if (!_disposed) + { + StateHasChanged(); + } + } + + private async Task TryEnsureStartedAsync(CancellationToken cancellationToken) + { + var started = false; + try + { + await MediaMtxService.EnsureStartedAsync(cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + started = true; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + catch (MediaMtxToolNotFoundException ex) + { + Log.LogError(ex, "The MediaMTX gateway executable is missing."); + var path = ex.FileName; + if (!string.IsNullOrEmpty(path)) + { + var relativePath = Path.IsPathFullyQualified(path) ? Path.GetRelativePath(AppContext.BaseDirectory, path) : path; + _missingToolPath = Path.IsPathRooted(relativePath) ? null : relativePath; + } + _failureTextKey = _missingToolPath is null ? "MediaMtxToolMissingText" : "MediaMtxToolMissingPathText"; + } + catch (Exception ex) + { + _failureTextKey = "GatewayStartFailedText"; + Log.LogError(ex, "Failed to start the MediaMTX gateway. Check the installation and listener ports."); + } + return started; + } + + private async Task RegisterUrl(MediaMtxCameraOptions options, CancellationToken cancellationToken) + { + string? registeredUrl = null; + try + { + registeredUrl = await MediaMtxService.AddOrUpdateAsync(options, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + catch (Exception ex) + { + Log.LogError(ex, "Failed to register the camera for WebRTC preview. Check the camera path and RTSP URL."); + } + return registeredUrl; + } + + private Uri? GetPlayerUrl() + { + if (!Uri.TryCreate(_registeredUrl, UriKind.Absolute, out var url) || + url.Scheme is not ("http" or "https") || url.UserInfo.Length != 0) + { + return null; + } + + if (IsMuted) + { + return url; + } + + var query = HttpUtility.ParseQueryString(url.Query); + 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.MediaMtx/HttpClientExtensions.cs b/src/components/BootstrapBlazor.MediaMtx/Extensions/HttpClientExtensions.cs similarity index 100% rename from src/components/BootstrapBlazor.MediaMtx/HttpClientExtensions.cs rename to src/components/BootstrapBlazor.MediaMtx/Extensions/HttpClientExtensions.cs diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs b/src/components/BootstrapBlazor.MediaMtx/Extensions/MediaMtxServiceCollectionExtensions.cs similarity index 100% rename from src/components/BootstrapBlazor.MediaMtx/MediaMtxServiceCollectionExtensions.cs rename to src/components/BootstrapBlazor.MediaMtx/Extensions/MediaMtxServiceCollectionExtensions.cs diff --git a/src/components/BootstrapBlazor.MediaMtx/Locales/en.json b/src/components/BootstrapBlazor.MediaMtx/Locales/en.json new file mode 100644 index 00000000..ded71db2 --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/Locales/en.json @@ -0,0 +1,11 @@ +{ + "BootstrapBlazor.Components.MediaMtxPlayer": { + "OptionsMissingText": "Camera configuration is missing. Unable to initialize the player.", + "InitializingText": "Preparing preview, please wait ...", + "MediaMtxToolMissingText": "The MediaMTX backend tool is missing. Contact an administrator to deploy it.", + "MediaMtxToolMissingPathText": "The MediaMTX backend tool is missing: {0} (relative to the application directory). Contact an administrator to deploy it.", + "GatewayStartFailedText": "The MediaMTX backend gateway could not start. Check the server logs.", + "RegistrationFailedText": "Camera registration failed. Check the server logs.", + "InvalidUrlText": "The player URL must be an absolute HTTP or HTTPS URL without credentials." + } +} diff --git a/src/components/BootstrapBlazor.MediaMtx/Locales/zh.json b/src/components/BootstrapBlazor.MediaMtx/Locales/zh.json new file mode 100644 index 00000000..b1ba5b4c --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/Locales/zh.json @@ -0,0 +1,11 @@ +{ + "BootstrapBlazor.Components.MediaMtxPlayer": { + "OptionsMissingText": "未配置摄像头,无法初始化播放器。", + "InitializingText": "正在准备预览,请稍后 ...", + "MediaMtxToolMissingText": "未找到后台 MediaMTX 工具,请联系管理员部署。", + "MediaMtxToolMissingPathText": "未找到后台 MediaMTX 工具:{0}(相对于应用目录)。请联系管理员部署。", + "GatewayStartFailedText": "后台 MediaMTX 网关启动失败,请查看服务端日志。", + "RegistrationFailedText": "摄像头登记失败,请查看服务端日志。", + "InvalidUrlText": "播放地址必须是不含凭据的绝对 HTTP 或 HTTPS 地址。" + } +} diff --git a/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md b/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md index 1c27aa8d..9c2eed17 100644 --- a/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md +++ b/src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md @@ -80,19 +80,19 @@ dotnet user-secrets set "MediaMtxOptions:Cameras:hikvision:Password" "\mediamtx.exe`(Windows)或对应的 `mediamtx`;相对应用目录解析。 | -| `Cameras` | 可选的静态摄像头字典,以键作为播放路径,忽略值中的 `Path`、`PlayUrl`。 | +| `Cameras` | 可选的静态摄像头字典,以键作为播放路径,忽略值中的 `Path`。 | 自管网关的完整 YAML 由服务生成,关闭其他协议监听器和 MediaMTX 日志目的地。API 密码和摄像头源通过子进程环境传递,不写入生成的 YAML。 ## 播放与动态登记 -使用 `BootstrapBlazor.HikVision` 的播放器时,在已授权的 Interactive Server 页面直接渲染组件即可。以下示例从服务器配置取得摄像头凭据: +使用本包的 `MediaMtxPlayer` 组件时,在已授权的 Interactive Server 页面直接渲染即可。以下示例从服务器配置取得摄像头凭据: ```razor @using BootstrapBlazor.Components @inject Microsoft.Extensions.Options.IOptions GatewayOptions - + @code { private MediaMtxCameraOptions camera = default!; @@ -111,7 +111,7 @@ dotnet user-secrets set "MediaMtxOptions:Cameras:hikvision:Password" "//`,未配置公开基址则使用 `http://127.0.0.1://`。非 `null` 时必须是无凭据的绝对 HTTP/HTTPS 地址,空字符串无效;它不改变监听、允许的来源或 ICE。 +- 播放地址由 `//` 生成,未配置公开基址则使用 `http://127.0.0.1://`;它不改变监听、允许的来源或 ICE。 - 更新、删除同一路径会影响所有观看者。动态配置只保存在网关内存中,网关重启后需重新登记;关闭播放器不删除路径。 播放页默认静音;有声自动播放受浏览器策略限制。音频可使用 G.711 μ-law(PCMU)或 A-law(PCMA)等浏览器支持的编码,不兼容编码需另行转码。 @@ -165,18 +165,16 @@ MediaMTX → 摄像头 RTSP 地址:源流 ## 进程复用 -同一服务实例的网关仍运行时,`EnsureStartedAsync` 直接返回。新的宿主通过当前系统用户的本机应用数据目录 `BootstrapBlazor\mediamtx-gateways` 及文件锁协调,按 `Gateway:Port` 查找状态,再核对 PID、启动时间和进程路径。 +同一服务实例的网关仍运行时,`EnsureStartedAsync` 直接返回。其他宿主先检查 `127.0.0.1:/v3/info`;未能复用时再通过当前用户本机应用数据目录 `BootstrapBlazor\mediamtx-gateways` 下的端口锁协调,并在锁内重试检查。 | 情况 | 行为 | | --- | --- | -| 进程有效、指纹相同 | 使用配置的 API 密码通过就绪检查后复用。 | -| 指纹不同、进程路径与当前目标路径相同 | 先停止旧进程,再按当前配置启动;中断共享该网关的播放,动态路径需恢复。 | -| 指纹不同、目标路径不同 | 报错,不终止旧进程。 | -| 没有有效登记进程 | 预检端口后启动;端口被其他实例占用则报错,不擅自接管。 | +| Control API 返回 HTTP 200 | 使用配置的 API 密码复用该网关,不要求服务记录其 PID。 | +| Control API 不可用 | 检查平台、工具及配置后预检端口并启动;端口被其他进程占用则报错,不接管该进程。 | -指纹由可执行文件内容、生成的 YAML 和静态摄像头源配置计算 SHA-256,包含摄像头凭据,**不包含 `Gateway:Password` 或运行时动态登记**。仅更换 API 密码不会触发自动重启;需先确认并手动停止对应网关,再用新密码启动。共享宿主应保持配置一致,避免反复触发重启。 +复用基于 Control API 探测,不保存或核验进程 PID、启动时间或可执行文件路径;只要 API 探测通过,即使本机没有工具文件或启动平台不受支持,也可复用。HTTP 401/403 会立即报错,不会尝试启动替代进程。配置变化不触发自动重启或停止旧进程;复用已有网关时不会应用新的启动 YAML,摄像头路径需通过管理 API 登记。 -共享状态只保存进程身份和指纹,不保存 API 密码;不要共享或提交状态文件。宿主释放只关闭自身句柄,网关继续运行。服务不后台守护进程,网关退出后再次调用 `EnsureStartedAsync` 才会尝试启动。启动失败会清理本次启动的进程。 +端口锁文件只用于协调并发启动,不记录 PID 或 API 密码。宿主释放只关闭自身句柄,网关继续运行。服务不后台守护进程,网关退出后再次调用 `EnsureStartedAsync` 才会尝试启动。启动失败会清理本次启动的进程。 ## 外部本机网关 @@ -211,7 +209,7 @@ MediaMTX → 摄像头 RTSP 地址:源流 | 工具缺失 | `Gateway:MediaMtxPath`、目标 RID、执行权限及 CLI 警告。 | | ICE 配置无效 | 检查 `WebRtc:Ice:Address`、`WebRtc:Ice:Port` 和 `WebRtc:Ice:AdditionalHosts`。 | | HTTP 401/403 | 配置密码是否与运行中网关一致;自管模式认证被拒立即失败。 | -| 端口占用、进程退出或就绪超时 | 服务端日志中的 PID、端口、工具版本;启动和复用的 API 就绪检查最多等待 10 秒。 | +| 端口占用、进程退出或就绪超时 | 服务端日志中的端口、工具版本;每次 API 探测最多等待 10 秒,跨宿主未复用时可能探测两次。 | | 播放页可见但无画面 | 服务器到摄像头的 RTSP、凭据、编码,以及浏览器到 ICE 公网地址的 UDP 连通性。 | 部署方负责 UI 身份认证、摄像头级授权、RTSP 目标限制和播放访问控制。API 密码不保护播放路径,内置读取权限不提供摄像头级播放鉴权;仅保护 BB 页面不足以保护独立播放地址。不要将 `9997` Control API 代理到公网,也不要将凭据放入播放 URL、日志或浏览器存储。 diff --git a/src/components/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs b/src/components/BootstrapBlazor.MediaMtx/Services/IMediaMtxProcessLauncher.cs similarity index 100% rename from src/components/BootstrapBlazor.MediaMtx/IMediaMtxProcessLauncher.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/IMediaMtxProcessLauncher.cs diff --git a/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs b/src/components/BootstrapBlazor.MediaMtx/Services/IMediaMtxService.cs similarity index 81% rename from src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/IMediaMtxService.cs index e4f67cbc..ed9c4b9a 100644 --- a/src/components/BootstrapBlazor.MediaMtx/IMediaMtxService.cs +++ b/src/components/BootstrapBlazor.MediaMtx/Services/IMediaMtxService.cs @@ -15,8 +15,8 @@ namespace BootstrapBlazor.Components; public interface IMediaMtxService { /// - /// 确保网关已启动并就绪,失败时抛出异常。默认实现复用同一用户启动的兼容网关;外部网关模式连接已部署的本机网关。 - /// Ensures the gateway is running and ready, throwing an exception on failure. The default service reuses a compatible gateway started by the same user; external gateway mode connects to an independently deployed local gateway. + /// 确保网关已启动并就绪,失败时抛出异常。默认实现优先复用本机在 Gateway:Port 上已就绪且 API 密码一致的网关(同一服务实例的存活进程直接使用),无法复用时按配置启动新进程;外部网关模式连接已部署的本机网关。 + /// Ensures the gateway is running and ready, throwing an exception on failure. The default service first reuses a ready gateway on the local Gateway:Port whose Control API accepts the configured password (a live process owned by the same service instance is used directly), and starts a new process from configuration when reuse is not possible; external gateway mode connects to an independently deployed local gateway. /// 11.0.0 /// /// 取消令牌。The cancellation token. @@ -34,8 +34,8 @@ public interface IMediaMtxService Task SetGatewayStateAsync(string? apiPassword); /// - /// 登记新路径或更新已有路径的摄像头源配置,返回播放 URL。摄像头 PlayUrl 为 null 时使用 WebRtc.PublicUrl 或同机回环地址与 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 WebRtc.PublicUrl 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. + /// 登记新路径或更新已有路径的摄像头源配置,返回播放 URL。播放地址由 WebRtc.PublicUrl 或同机回环地址与 Path 生成。更新可能中断现有播放;成功不代表源已连通。 + /// Registers a new path or updates the camera source configuration and returns its playback URL, built from WebRtc.PublicUrl 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/components/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxCameraOptions.cs similarity index 79% rename from src/components/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxCameraOptions.cs index 6e64e9b6..0efc50ca 100644 --- a/src/components/BootstrapBlazor.MediaMtx/MediaMtxCameraOptions.cs +++ b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxCameraOptions.cs @@ -19,13 +19,6 @@ public sealed class MediaMtxCameraOptions /// public string? Path { get; set; } - /// - /// 获得/设置浏览器访问的完整 HTTP 或 HTTPS 播放页面地址,不应包含凭据。为 null 时使用 WebRtc.PublicUrl 或本机地址与 Path 生成播放地址;空字符串无效。此选项不改变网关监听和 ICE 配置。 - /// Gets or sets the complete browser-facing HTTP or HTTPS player URL without credentials. When null, the URL is built from WebRtc.PublicUrl 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 diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxOptions.cs similarity index 96% rename from src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxOptions.cs index 71d6f26c..e4abc087 100644 --- a/src/components/BootstrapBlazor.MediaMtx/MediaMtxOptions.cs +++ b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxOptions.cs @@ -29,8 +29,8 @@ public sealed class MediaMtxOptions public MediaMtxWebRtcOptions WebRtc { get; set; } = new(); /// - /// 获得/设置网关启动或连接外部网关时登记的摄像头,键为播放路径,值中的 Path 和 PlayUrl 被忽略。密码应通过安全配置源提供;环境变量可能被子进程继承。 - /// Gets or sets the cameras configured when starting or connecting to the gateway. Keys are playback paths; Path and PlayUrl in each value are ignored. Supply passwords through a secure configuration source; environment variables may be inherited by child processes. + /// 获得/设置网关启动或连接外部网关时登记的摄像头,键为播放路径,值中的 Path 被忽略。密码应通过安全配置源提供;环境变量可能被子进程继承。 + /// Gets or sets the cameras configured when starting or connecting to the gateway. Keys are playback paths; Path in each value is ignored. Supply passwords through a secure configuration source; environment variables may be inherited by child processes. /// 11.0.0 /// public Dictionary Cameras { get; set; } = new(); diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxProcessLauncher.cs b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxProcessLauncher.cs similarity index 100% rename from src/components/BootstrapBlazor.MediaMtx/MediaMtxProcessLauncher.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxProcessLauncher.cs diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxService.Gateway.cs similarity index 78% rename from src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxService.Gateway.cs index e7517363..7c7ad1f7 100644 --- a/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.Gateway.cs +++ b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxService.Gateway.cs @@ -7,7 +7,6 @@ using System.Diagnostics; using System.Net; using System.Net.Sockets; -using System.Security.Cryptography; using System.Text; using System.Text.Json; @@ -129,18 +128,37 @@ await AddOrUpdateAsync(new MediaMtxCameraOptions private async Task StartGatewayAsync(CancellationToken cancellationToken) { - if (!launcher.IsSupported) - { - logger.LogWarning("The registered MediaMTX platform launcher does not support this operating system or OS architecture; the gateway is disabled."); - return false; - } - var settings = options.Value; var apiPassword = settings.Gateway.Password; if (string.IsNullOrWhiteSpace(apiPassword)) { throw new InvalidOperationException("MediaMtxOptions:Gateway:Password is required for the managed gateway."); } + var apiAddress = $"{Loopback}:{settings.Gateway.Port}"; + if (await TryReuseGatewayAsync(apiAddress, apiPassword, cancellationToken)) + { + await SetGatewayStateAsync(apiPassword); + logger.LogInformation("Reusing the MediaMTX gateway at {ApiAddress}.", apiAddress); + return true; + } + + var directory = MediaMtxSharedGateway.GetDirectory(); + await using var sharedLock = await MediaMtxSharedGateway.AcquireAsync(directory, settings.Gateway.Port, cancellationToken); + var legacyStatePath = Path.Combine(directory, $"{settings.Gateway.Port}.json"); + File.Delete(legacyStatePath); + if (await TryReuseGatewayAsync(apiAddress, apiPassword, cancellationToken)) + { + await SetGatewayStateAsync(apiPassword); + logger.LogInformation("Reusing the MediaMTX gateway at {ApiAddress}.", apiAddress); + return true; + } + + if (!launcher.IsSupported) + { + logger.LogWarning("The registered MediaMTX platform launcher does not support this operating system or OS architecture; the gateway is disabled."); + return false; + } + var executable = Path.GetFullPath(settings.Gateway.MediaMtxPath, AppContext.BaseDirectory); if (!File.Exists(executable)) { @@ -148,65 +166,12 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) } var httpAddress = $"{Loopback}:{settings.WebRtc.Port}"; - var apiAddress = $"{Loopback}:{settings.Gateway.Port}"; var webRtc = MediaMtxWebRtcConfiguration.Create(settings); var publicUri = settings.WebRtc.GetPublicUri(); var cameraSources = new Dictionary(); var cameras = settings.Cameras.OrderBy(item => item.Key, StringComparer.Ordinal) .ToDictionary(item => item.Key, item => item.Value, StringComparer.Ordinal); var config = CreateConfiguration(cameras, httpAddress, webRtc, apiAddress, publicUri, cameraSources); - using var sha = SHA256.Create(); - using var executableStream = File.OpenRead(executable); - var fingerprintInput = JsonSerializer.SerializeToUtf8Bytes(new - { - Executable = Convert.ToHexString(sha.ComputeHash(executableStream)), - Configuration = config, - Sources = cameraSources.OrderBy(item => item.Key, StringComparer.Ordinal).ToArray() - }); - var fingerprint = Convert.ToHexString(SHA256.HashData(fingerprintInput)); - var directory = MediaMtxSharedGateway.GetDirectory(); - await using var sharedLock = await MediaMtxSharedGateway.AcquireAsync(directory, settings.Gateway.Port, cancellationToken); - var statePath = Path.Combine(directory, $"{settings.Gateway.Port}.json"); - var state = await MediaMtxSharedGateway.ReadAsync(statePath, cancellationToken); - if (state is not null && GetRecordedProcess(state) is { } existing) - { - try - { - if (!string.Equals(state.Fingerprint, fingerprint, StringComparison.Ordinal)) - { - var pathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - if (!string.Equals(state.Executable, executable, pathComparison)) - { - throw new InvalidOperationException("The existing MediaMTX gateway has different configuration and executable path. Stop it before changing the gateway configuration."); - } - - logger.LogWarning("Stopping the existing MediaMTX gateway (PID {ProcessId}) because its configuration changed. Executable: {ExecutablePath}.", - existing.Id, executable); - await TerminateProcessAsync(existing, cancellationToken); - File.Delete(statePath); - existing.Dispose(); - } - else - { - using var reuseTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - reuseTimeout.CancelAfter(_startupTimeout); - await WaitForControlApiAsync(apiAddress, apiPassword, reuseTimeout.Token); - if (existing.HasExited) - { - throw new InvalidOperationException("The existing MediaMTX gateway exited during readiness verification."); - } - await SetGatewayStateAsync(apiPassword); - _process = existing; - logger.LogInformation("Reusing the MediaMTX gateway (PID {ProcessId}).", existing.Id); - return true; - } - } - catch - { - existing.Dispose(); - throw; - } - } if (!IsPortAvailable(new IPEndPoint(IPAddress.Loopback, settings.WebRtc.Port), ProtocolType.Tcp) | !IsPortAvailable(new IPEndPoint(IPAddress.Loopback, settings.Gateway.Port), ProtocolType.Tcp) | @@ -224,9 +189,6 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) await File.WriteAllTextAsync(configPath, config, timeout.Token); process = StartMediaMtx(launcher, executable, configPath, apiPassword, cameraSources); _process = process; - var processPath = await GetStartedProcessPathAsync(process, timeout.Token); - state = new(process.Id, process.StartTime.ToUniversalTime().Ticks, processPath, fingerprint); - await MediaMtxSharedGateway.WriteAsync(statePath, state, timeout.Token); var exited = process.WaitForExitAsync(timeout.Token); var ready = WaitForControlApiAsync(apiAddress, apiPassword, timeout.Token); @@ -252,7 +214,6 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) try { await TerminateProcessAsync(process, CancellationToken.None); - File.Delete(statePath); } finally { @@ -267,61 +228,37 @@ private async Task StartGatewayAsync(CancellationToken cancellationToken) } } - private static async Task GetStartedProcessPathAsync(Process process, CancellationToken cancellationToken) + private async Task TryReuseGatewayAsync(string apiAddress, string apiPassword, CancellationToken cancellationToken) { - while (true) + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(_startupTimeout); + using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { - cancellationToken.ThrowIfCancellationRequested(); - process.Refresh(); - if (process.HasExited) - { - throw new InvalidOperationException($"The MediaMTX process exited before it was ready (exit code {process.ExitCode})."); - } - if (process.MainModule?.FileName is { Length: > 0 } path) - { - return path; - } - await Task.Delay(_probeInterval, cancellationToken); - } - } - - private static Process? GetRecordedProcess(MediaMtxSharedGateway.State state) - { - Process process; + BaseAddress = new Uri($"http://{apiAddress}/v3/") + }; + using var request = client.CreateAuthorizationRequest(HttpMethod.Get, "info", apiPassword); + HttpResponseMessage response; try { - process = Process.GetProcessById(state.ProcessId); + response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token); } - catch (ArgumentException) + catch (HttpRequestException) { - return null; + return false; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return false; } - try + using (response) { - if (process.HasExited || process.StartTime.ToUniversalTime().Ticks != state.ProcessStartTicks) - { - process.Dispose(); - return null; - } - var path = process.MainModule?.FileName; - var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - if (!string.Equals(path, state.Executable, comparison)) + if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) { - process.Dispose(); - return null; + throw new HttpRequestException($"MediaMTX Control API rejected the configured password with HTTP {(int)response.StatusCode}.", + null, response.StatusCode); } - return process; - } - catch (InvalidOperationException) - { - process.Dispose(); - return null; - } - catch - { - process.Dispose(); - throw; + return response.StatusCode == HttpStatusCode.OK; } } diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxService.cs similarity index 97% rename from src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxService.cs index 01b26e7c..d07d3054 100644 --- a/src/components/BootstrapBlazor.MediaMtx/MediaMtxService.cs +++ b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxService.cs @@ -48,11 +48,11 @@ public async Task SetGatewayStateAsync(string? apiPassword) } var source = BuildRtspSourceUrl(camera) ?? throw new ArgumentException("Camera URL must be an absolute RTSP or RTSPS URL.", nameof(camera)); var playerBaseUrl = options.Value.WebRtc.GetPublicUri()?.AbsoluteUri ?? $"http://127.0.0.1:{options.Value.WebRtc.Port}/"; - var playerUrl = camera.PlayUrl ?? $"{playerBaseUrl}{path}/"; + var playerUrl = $"{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)); + throw new ArgumentException("Camera Path must produce an absolute HTTP or HTTPS playback URL.", nameof(camera)); } var content = new { source, rtspTransport = "tcp", sourceOnDemand = true }; await _gate.WaitAsync(cancellationToken); diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxSharedGateway.cs b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxSharedGateway.cs similarity index 72% rename from src/components/BootstrapBlazor.MediaMtx/MediaMtxSharedGateway.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxSharedGateway.cs index cf80f10c..b09ed9aa 100644 --- a/src/components/BootstrapBlazor.MediaMtx/MediaMtxSharedGateway.cs +++ b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxSharedGateway.cs @@ -7,14 +7,11 @@ using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; -using System.Text.Json; namespace BootstrapBlazor.Components; static class MediaMtxSharedGateway { - public sealed record State(int ProcessId, long ProcessStartTicks, string Executable, string Fingerprint); - public static string GetDirectory() { var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); @@ -86,37 +83,4 @@ public static async Task AcquireAsync(string directory, int port, Ca } } } - - public static async Task ReadAsync(string path, CancellationToken cancellationToken) - { - if (!File.Exists(path)) - { - return null; - } - await using var stream = File.OpenRead(path); - var state = await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); - if (state is null || state.ProcessId <= 0 || state.ProcessStartTicks <= 0 || - string.IsNullOrEmpty(state.Executable) || string.IsNullOrEmpty(state.Fingerprint)) - { - throw new InvalidDataException("The MediaMTX gateway state is invalid."); - } - return state; - } - - public static async Task WriteAsync(string path, State state, CancellationToken cancellationToken) - { - var temporary = $"{path}.{Guid.NewGuid():N}.tmp"; - try - { - await using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) - { - await JsonSerializer.SerializeAsync(stream, state, cancellationToken: cancellationToken); - } - File.Move(temporary, path, overwrite: true); - } - finally - { - File.Delete(temporary); - } - } } diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxToolNotFoundException.cs b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxToolNotFoundException.cs similarity index 100% rename from src/components/BootstrapBlazor.MediaMtx/MediaMtxToolNotFoundException.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxToolNotFoundException.cs diff --git a/src/components/BootstrapBlazor.MediaMtx/MediaMtxWebRtcConfiguration.cs b/src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxWebRtcConfiguration.cs similarity index 100% rename from src/components/BootstrapBlazor.MediaMtx/MediaMtxWebRtcConfiguration.cs rename to src/components/BootstrapBlazor.MediaMtx/Services/MediaMtxWebRtcConfiguration.cs diff --git a/src/components/BootstrapBlazor.MediaMtx/_Imports.razor b/src/components/BootstrapBlazor.MediaMtx/_Imports.razor new file mode 100644 index 00000000..66ebfa5d --- /dev/null +++ b/src/components/BootstrapBlazor.MediaMtx/_Imports.razor @@ -0,0 +1 @@ +@using Microsoft.AspNetCore.Components.Web diff --git a/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md b/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md index bf4db9ec..1031fa90 100644 --- a/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md +++ b/src/components/BootstrapBlazor.MediaMtx/skills/bb-mediamtx/SKILL.md @@ -26,7 +26,7 @@ builder.Services.AddMediaMtxService(); | `WebRtc:Port` / `WebRtc:Ice:Port` | 默认回环 TCP `8889` / UDP `8189`;API 与播放 TCP 端口须不同。 | | `WebRtc:Ice:Address` / `WebRtc:Ice:IpsFromInterfaces` / `WebRtc:Ice:AdditionalHosts` | 自管网关的 UDP 监听 IP、网卡候选地址开关和额外 ICE 主机;默认分别为 `127.0.0.1`、`false`、`["127.0.0.1"]`。 | | `WebRtc:PublicUrl` | 浏览器使用的绝对 HTTP/HTTPS 播放基址,无凭据、查询字符串或片段;自管模式同时设置允许的信令来源。 | -| `Cameras` | 静态摄像头字典,键为路径;值提供 `RtspUrl`、`UserName`、`Password`,忽略 `Path`、`PlayUrl`。 | +| `Cameras` | 静态摄像头字典,键为路径;值提供 `RtspUrl`、`UserName`、`Password`,忽略 `Path`。 | API 密码与摄像头密码分开配置,通过 Secret 或环境变量提供,不写入文档、日志或浏览器存储。生产环境默认不加载 Development 配置或 User Secrets;子进程会接收凭据,需限制访问权限。 @@ -37,20 +37,27 @@ await mediaMtx.EnsureStartedAsync(cancellationToken); var playerUrl = await mediaMtx.AddOrUpdateAsync(camera, cancellationToken); ``` -- 同一服务已有存活进程时直接返回。新宿主按当前用户、`Gateway:Port` 和共享状态核对进程身份;指纹相同且 API 认证通过才复用。 -- 指纹包含可执行文件内容、生成 YAML、静态摄像头源及其凭据,**不包含 `Gateway:Password` 或动态登记**。指纹变化且可执行文件路径与当前目标一致时自动停止旧进程并重启,路径不同时报错。共享配置不同可能反复重启,影响所有观看者。 -- 仅更换 API 密码不触发指纹重启,需手动停止对应网关后重新启动。API 认证返回 401/403 时立即失败;其他就绪探测最多等待 10 秒。 -- 共享状态位于当前用户本机应用数据目录的 `BootstrapBlazor\mediamtx-gateways`,保存进程身份和指纹,不保存 API 密码。没有有效登记的占用端口实例不会被接管。 +- 同一服务已有存活进程时直接返回。其他宿主先探测 `127.0.0.1:/v3/info`;若未复用,则通过当前用户和 `Gateway:Port` 的文件锁协调后再次探测。HTTP 200 且当前 API 密码认证通过即复用,不保存或核验 PID、启动时间及可执行文件路径;复用优先于平台及工具文件检查。 +- 配置变化不触发自动重启或停止旧进程。 +- API 认证返回 401/403 时立即失败;每次 API 探测最多等待 10 秒,跨宿主未复用时可能探测两次。API 不可用时只有端口预检通过才会启动新进程;不接管未知占用进程。 +- `BootstrapBlazor\mediamtx-gateways` 下的端口锁只用于并发协调,不保存进程或密码状态。 - 宿主释放不停止网关、不删除路径。网关崩溃后不后台重启,再次调用 `EnsureStartedAsync` 才尝试启动;启动失败会清理本次启动的进程。 - `AddOrUpdateAsync` 新增或更新路径,默认返回播放 URL、失败抛异常;自定义实现可返回 `null`。同一路径的更新影响所有观看者,成功不代表摄像头连通。 - `RemoveAsync(path)` 显式删除路径,默认成功返回 `true`,不存在或失败抛异常。动态路径只保存在网关内存中,重启后需恢复;静态 `Cameras` 在启动时配置。 - `SetGatewayStateAsync` 仅供宿主同步状态。自定义 `IMediaMtxProcessLauncher` 在注册服务前注入,默认注册不会覆盖它。 +## 组件渲染 + +在已授权的 Interactive Server 页面渲染 `MediaMtxPlayer`,`Options` 传 `MediaMtxCameraOptions`。组件首次交互渲染时依次调用 `EnsureStartedAsync()`、`AddOrUpdateAsync(camera)`,成功后以 iframe 显示播放页。 + +- `IsMuted` 默认 `true`,保留播放页默认静音;设为 `false` 写入 `muted=false`,有声自动播放仍受浏览器策略限制。 +- 预渲染不启动网关,登记失败时不显示播放器;组件不下载工具、不自动重试,修改源或重试需重新创建组件实例。 + ## 摄像头与公网播放 - `Path` 非空;建议调用方限制为小写字母开头,仅含小写字母、数字、连字符,最长 63 个字符,排除 `all`。 - `RtspUrl` 是无用户信息的绝对 RTSP/RTSPS 地址,必须包含主机名;用户名、密码传原始值,由服务编码,无用户名时忽略密码。 -- `PlayUrl` 为 `null` 时使用 `WebRtc:PublicUrl` 或 `http://127.0.0.1:/` 加 `Path/`;非 `null` 时必须是无凭据的绝对 HTTP/HTTPS 地址,空字符串无效。它不改变来源或 ICE。 +- 播放地址使用 `WebRtc:PublicUrl` 或 `http://127.0.0.1:/` 加 `Path/`;它不改变来源或 ICE。 - 公网需同时配置 HTTPS 反向代理和可达的 UDP ICE;使用 `WebRtc:Ice:Address`、`WebRtc:Ice:Port` 和 `WebRtc:Ice:AdditionalHosts`,不必维护 YAML。 - 公布的 ICE 地址必须指向 MediaMTX 服务器而非摄像头或仅代理 HTTP 的 CDN;放行 UDP、防火墙及 NAT 映射。普通 nginx HTTP 代理不转发媒体 UDP,`WebRtc:PublicUrl` 也不改变 ICE。 - MediaMTX 按需 RTSP/TCP 拉流,不转码;编码须与浏览器兼容。播放默认静音,有声自动播放受浏览器限制。