diff --git a/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj b/src/components/BootstrapBlazor.HikVision/BootstrapBlazor.HikVision.csproj index 4c5fee95..b2d513a4 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 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/HikVisionChannel.cs b/src/components/BootstrapBlazor.HikVision/Components/HikVisionChannel.cs index 75de353d..c5c31105 100644 --- a/src/components/BootstrapBlazor.HikVision/Components/HikVisionChannel.cs +++ b/src/components/BootstrapBlazor.HikVision/Components/HikVisionChannel.cs @@ -20,7 +20,7 @@ public class HikVisionChannel public List DigitalChannels { get; set; } = []; /// - /// 获得/设置 数字通道信息集合 + /// 获得/设置 零通道信息集合 /// public List ZeroChannels { get; set; } = []; } diff --git a/src/components/BootstrapBlazor.HikVision/Components/HikVisionDigitalChannel.cs b/src/components/BootstrapBlazor.HikVision/Components/HikVisionDigitalChannel.cs index 587ba0e4..010a067a 100644 --- a/src/components/BootstrapBlazor.HikVision/Components/HikVisionDigitalChannel.cs +++ b/src/components/BootstrapBlazor.HikVision/Components/HikVisionDigitalChannel.cs @@ -5,7 +5,7 @@ namespace BootstrapBlazor.Components; /// -/// 模拟通道信息 +/// 数字通道信息 /// public class HikVisionDigitalChannel() { diff --git a/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebPlugin.razor.cs b/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebPlugin.razor.cs index a3da30f1..d840df6d 100644 --- a/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebPlugin.razor.cs +++ b/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebPlugin.razor.cs @@ -37,7 +37,7 @@ public partial class HikVisionWebPlugin public string? Password { get; set; } /// - /// 获得/设置 网络摄像机 登录类型 默认值 + /// 获得/设置 网络摄像机登录类型。未设置时为枚举默认值; 方法的默认参数为 。 /// [Parameter] public HikVisionLoginType LoginType { get; set; } @@ -67,7 +67,7 @@ public partial class HikVisionWebPlugin public Func? OnLoginAsync { get; set; } /// - /// 获得/设置 停止预览后回调方法 + /// 获得/设置 通道信息回调方法 /// [Parameter] public Func? OnGetChannelsAsync { get; set; } @@ -152,14 +152,14 @@ protected override void OnParametersSet() } /// - /// 登录方法 + /// 使用指定参数登录摄像机;插件未初始化时抛出异常。 /// /// /// /// /// /// - /// + /// 登录成功时为 true,否则为 false;失败信息可通过 LoginErrorCode 和 LoginErrorMessage 查看。 public async Task Login(string ip, int port, string userName, string password, HikVisionLoginType loginType = HikVisionLoginType.Http) { ThrowIfNotInited(); @@ -356,7 +356,7 @@ public async Task SetVolume(int value) } /// - /// 抓图方法并且下载方法 + /// 通过浏览器下载当前画面。 /// /// public async Task CapturePictureAndDownload(string? fileName = null, CancellationToken token = default) @@ -370,7 +370,7 @@ public async Task CapturePictureAndDownload(string? fileName = null, Cance } /// - /// 抓图方法返回 实例 + /// 通过 WebSDK 发起抓图;返回调用结果,不返回图片流。 /// /// public async Task CapturePicture(string? fileName = null, CancellationToken token = default) @@ -419,7 +419,7 @@ public async Task StopRecord() /// /// 更改视口数量方法 /// - /// 画面分割类型 1- 1*1,2- 2*2,3- 3*3,4- 4*4 (最大显示数值为4*4分割,数字超过4返回16分割) + /// 画面分割类型,例如 1、2、3、4、1*2 或 2*1;具体支持情况由 WebSDK 决定。 /// public async Task ChangeWindowNum(string iWndType) { diff --git a/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor b/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor index 41e5204c..3e9db3ce 100644 --- a/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor +++ b/src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor @@ -1,13 +1,40 @@ @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..30dd00fa 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 并提前部署 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.3 /// [Parameter] - public string? WebRtcUrl { get; set; } + public MediaMtxCameraOptions? Options { get; set; } /// /// 获得/设置 播放器的无障碍标题 @@ -31,13 +33,22 @@ public partial class HikVisionWebRtc public string Title { get; set; } = "WebRTC"; /// - /// 获得/设置是否静音,默认值为 true,此时保留原播放地址。设为 false 时添加 muted=false,有声自动播放仍受浏览器策略限制。 - /// Gets or sets whether playback is muted. Defaults to true, preserving the original player URL. Set to false to add muted=false; audible autoplay remains subject to browser policies. + /// 获得/设置静音选项,默认值为 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.2 /// [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,100 @@ public partial class HikVisionWebRtc 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) + { + // cancellation requested, do not log as an error + } + 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) + { + // cancellation requested, do not log as an error + } + 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(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 +167,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/Components/HikVisionZeroChannel.cs b/src/components/BootstrapBlazor.HikVision/Components/HikVisionZeroChannel.cs index fcadeed1..48bea31a 100644 --- a/src/components/BootstrapBlazor.HikVision/Components/HikVisionZeroChannel.cs +++ b/src/components/BootstrapBlazor.HikVision/Components/HikVisionZeroChannel.cs @@ -5,7 +5,7 @@ namespace BootstrapBlazor.Components; /// -/// 模拟通道信息 +/// 零通道信息 /// public class HikVisionZeroChannel() { diff --git a/src/components/BootstrapBlazor.HikVision/Locales/en.json b/src/components/BootstrapBlazor.HikVision/Locales/en.json new file mode 100644 index 00000000..266d76a1 --- /dev/null +++ b/src/components/BootstrapBlazor.HikVision/Locales/en.json @@ -0,0 +1,11 @@ +{ + "BootstrapBlazor.Components.HikVisionWebRtc": { + "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.HikVision/Locales/zh.json b/src/components/BootstrapBlazor.HikVision/Locales/zh.json new file mode 100644 index 00000000..167a1aba --- /dev/null +++ b/src/components/BootstrapBlazor.HikVision/Locales/zh.json @@ -0,0 +1,11 @@ +{ + "BootstrapBlazor.Components.HikVisionWebRtc": { + "OptionsMissingText": "未配置摄像头,无法初始化播放器。", + "InitializingText": "正在准备预览,请稍后 ...", + "MediaMtxToolMissingText": "未找到后台 MediaMTX 工具,请联系管理员部署。", + "MediaMtxToolMissingPathText": "未找到后台 MediaMTX 工具:{0}(相对于应用目录)。请联系管理员部署。", + "GatewayStartFailedText": "后台 MediaMTX 网关启动失败,请查看服务端日志。", + "RegistrationFailedText": "摄像头登记失败,请查看服务端日志。", + "InvalidUrlText": "播放地址必须是不含凭据的绝对 HTTP 或 HTTPS 地址。" + } +} diff --git a/src/components/BootstrapBlazor.HikVision/README.HikVision.md b/src/components/BootstrapBlazor.HikVision/README.HikVision.md new file mode 100644 index 00000000..75a4834f --- /dev/null +++ b/src/components/BootstrapBlazor.HikVision/README.HikVision.md @@ -0,0 +1,60 @@ +# BootstrapBlazor.HikVision + +海康威视摄像机预览组件,包括通过 MediaMTX 播放页面预览的 `HikVisionWebRtc`,以及依赖海康 WebSDK 的 `HikVisionWebPlugin`。 + +```powershell +dotnet add package BootstrapBlazor.HikVision +``` + +## WebRTC 预览 + +`HikVisionWebRtc` 使用服务端 `BootstrapBlazor.MediaMtx` 管理网关和登记摄像头,再以 iframe 展示播放页面。网关由服务管理,组件不负责下载工具或管理进程;此方案需要支持运行进程的服务端宿主,不适用于独立 WebAssembly 宿主。 + +在服务端注册: + +```csharp +builder.Services.AddBootstrapBlazor(); +builder.Services.AddMediaMtxService(); +``` + +在已授权的 Interactive Server 页面使用: + +```razor +@using BootstrapBlazor.Components + + + +@code { + private readonly MediaMtxCameraOptions camera = new() + { + Path = "entrance", + RtspUrl = "rtsp://192.0.2.1:554/Streaming/Channels/101" + }; +} +``` + +组件仅在首次交互渲染时启动网关并登记摄像头,预渲染不会启动。`Options` 未设置时显示配置缺失提示;异步加载配置时,应等配置就绪后再创建组件。首次渲染后的配置更改不会重新登记,重试或更换摄像头源时需要重新创建组件实例。 + +默认服务要求 `Path` 非空,`RtspUrl` 为不含用户信息的绝对 RTSP/RTSPS 地址。凭据使用 `UserName`、`Password` 由服务端安全配置提供,不要写入地址、日志或浏览器存储。登记成功只表示网关接受配置,不代表摄像机在线或已有首帧。相同路径的更新或删除会影响所有观看者。 + +`PlayUrl` 为 `null` 时由服务生成播放地址,空字符串无效;自定义地址必须是不含凭据的绝对 HTTP/HTTPS 地址。`IsMuted` 默认保留原地址及其 `muted` 参数;设为 `false` 时写入 `muted=false`,有声自动播放仍受浏览器策略限制。`Title` 默认为 `WebRTC`,用作 iframe 无障碍标题。 + +首次使用前需单独部署 MediaMTX 原生工具,例如使用独立的 `BootstrapBlazor.MediaMtx.Cli`: + +```powershell +dotnet tool install -g BootstrapBlazor.MediaMtx.Cli --prerelease +bb-mediamtx --download +bb-mediamtx --copy --output .\publish +``` + +`--download` 未指定 `--rid` 时准备本机平台的缓存,指定具体 RID 时只准备该平台,指定 `--rid all` 时准备全部支持平台。`--copy` 从缓存复制到指定目录的 `mediamtx-tools\`,未指定 RID 时复制本机平台;跨平台复制需指定目标 `--rid`。组合 `--download --copy --rid all` 时会准备全部平台缓存,但只复制本机平台;`--copy --rid all` 无效。CLI 失败时输出警告,但仍以成功状态退出,应检查提示和目标文件。服务不会自动下载工具;工具缺失、网关启动失败和摄像头登记失败分别显示对应提示。 + +默认网关的 HTTP、Control API 和 ICE 仅监听回环地址。远程播放需要可达的信令和媒体路径、HTTPS 与鉴权;仅设置 `WebRtcPublicUrl` 或 `PlayUrl` 不会改变 ICE 地址。工具部署、配置及安全限制详见 `BootstrapBlazor.MediaMtx` 包文档。 + +## WebSDK 插件 + +`HikVisionWebPlugin` 使用浏览器端海康 WebSDK,需先等待 `OnInitedAsync` 返回初始化状态,再调用 `Login`。登录成功后通过 `OnGetChannelsAsync` 接收通道信息;登录失败可检查 `LoginErrorCode` 和 `LoginErrorMessage`。 + +当前组件模块未导出 `getChannelList`,手动调用 `GetChannelList()` 可能触发 JSInterop 异常。`CapturePicture` 返回发起抓图的布尔结果,不返回图片流;`CapturePictureAndDownload` 通过浏览器下载画面。 + +摄像头管理页面须进行身份认证、摄像头级权限检查和 RTSP 目标地址限制。WebSDK 插件的安装及浏览器兼容性应以设备和供应商文档为准。 diff --git a/src/components/BootstrapBlazor.HikVision/skills/bb-hikvision/SKILL.md b/src/components/BootstrapBlazor.HikVision/skills/bb-hikvision/SKILL.md index 88eed86a..e39ced93 100644 --- a/src/components/BootstrapBlazor.HikVision/skills/bb-hikvision/SKILL.md +++ b/src/components/BootstrapBlazor.HikVision/skills/bb-hikvision/SKILL.md @@ -5,93 +5,84 @@ 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 - -