Repository navigation
feat(HikVision): integrate WebRTC preview with MediaMTX #1389
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
c8a1bf9
60b6a63
f3894a1
8b6e681
7ff3164
f604e79
1406c67
7833489
db167df
337b6f8
afba336
ce2a144
559feaa
2127814
909c9c3
65fac33
35f530a
8cd92c4
a4007d5
ad7fce7
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,21 +1,31 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Razor"> | ||
| <Project Sdk="Microsoft.NET.Sdk.Razor"> | ||
|
|
||
| <PropertyGroup> | ||
| <Version>11.0.2</Version> | ||
| <Version>11.0.3</Version> | ||
| <SkillName>bb-hikvision</SkillName> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup> | ||
| <PackageTags>Bootstrap Blazor WebAssembly wasm UI Components HikVision WebRTC</PackageTags> | ||
| <PackageTags>Bootstrap Blazor Server UI Components HikVision WebRTC</PackageTags> | ||
| <Description>Bootstrap UI components extensions of HikVision</Description> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="BootstrapBlazor" Version="$(BBVersion)" /> | ||
| <PackageReference Include="BootstrapBlazor.MediaMtx" Version="11.0.1" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <SupportedPlatform Remove="browser" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Using Include="Microsoft.JSInterop" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Content Remove="Locales\*.json" /> | ||
| <EmbeddedResource Include="Locales\*.json" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,40 @@ | ||
| @namespace BootstrapBlazor.Components | ||
| @inherits BootstrapComponentBase | ||
|
|
||
| @if (PlayerUrl is { } url) | ||
| { | ||
| <div @attributes="AdditionalAttributes" class="@ClassString" style="@StyleString"> | ||
| <div @attributes="AdditionalAttributes" class="@ClassString" style="@StyleString" aria-busy="@(_initializing ? "true" : "false")"> | ||
| @if (Options is null) | ||
| { | ||
| <div class="bg-black text-white d-flex align-items-center justify-content-center" role="status"> | ||
| @Localizer["OptionsMissingText"] | ||
| </div> | ||
| } | ||
| else if (_initializing) | ||
| { | ||
| <div class="bg-black text-white d-flex align-items-center justify-content-center" role="status"> | ||
| @Localizer["InitializingText"] | ||
| </div> | ||
| } | ||
| else if (string.IsNullOrEmpty(_registeredUrl)) | ||
| { | ||
| <div class="bg-black text-white d-flex align-items-center justify-content-center" role="alert"> | ||
| @if (_missingToolPath is not null) | ||
| { | ||
| @Localizer[_failureTextKey, _missingToolPath] | ||
| } | ||
| else | ||
| { | ||
| @Localizer[_failureTextKey] | ||
| } | ||
| </div> | ||
| } | ||
| else if (PlayerUrl is { } url) | ||
| { | ||
| <iframe src="@url.AbsoluteUri" title="@Title" class="border-0" allow="autoplay; fullscreen" referrerpolicy="no-referrer"></iframe> | ||
| </div> | ||
| } | ||
| else | ||
| { | ||
| <div role="alert">WebRtcUrl must be an absolute HTTP or HTTPS player URL without credentials.</div> | ||
| } | ||
| } | ||
| else | ||
| { | ||
| <div class="bg-black text-white d-flex align-items-center justify-content-center" role="alert"> | ||
| @Localizer["InvalidUrlText"] | ||
| </div> | ||
| } | ||
| </div> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | |
| /// <para lang="en">Displays a live WebRTC preview from a Hikvision camera using the MediaMTX player page</para> | ||
| /// <para><version>11.0.2</version></para> | ||
| /// </summary> | ||
| public partial class HikVisionWebRtc | ||
| public partial class HikVisionWebRtc : IDisposable | ||
| { | ||
| /// <summary> | ||
| /// <para lang="zh">获得/设置浏览器访问的 WebRTC 播放页面地址,例如经 nginx 代理后的完整地址,不应包含凭据,应保留播放路径结尾的 /。如 http://camera.blazor.zone/hikvision/</para> | ||
| /// <para lang="en">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.</para> | ||
| /// <para><version>11.0.2</version></para> | ||
| /// <para lang="zh">获得/设置摄像头配置。首次交互渲染时调用 IMediaMtxService 启动网关并登记摄像头,成功后显示播放器。需在服务端注册 AddMediaMtxService 并提前部署 MediaMTX 工具;组件不负责下载工具。首次渲染后更改配置不会重新登记。</para> | ||
| /// <para lang="en">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.</para> | ||
| /// <para><version>11.0.3</version></para> | ||
| /// </summary> | ||
| [Parameter] | ||
| public string? WebRtcUrl { get; set; } | ||
| public MediaMtxCameraOptions? Options { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// <para lang="zh">获得/设置 播放器的无障碍标题</para> | ||
|
|
@@ -31,13 +33,22 @@ public partial class HikVisionWebRtc | |
| public string Title { get; set; } = "WebRTC"; | ||
|
|
||
| /// <summary> | ||
| /// <para lang="zh">获得/设置是否静音,默认值为 true,此时保留原播放地址。设为 false 时添加 muted=false,有声自动播放仍受浏览器策略限制。</para> | ||
| /// <para lang="en">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.</para> | ||
| /// <para lang="zh">获得/设置静音选项,默认值为 true,此时保留原播放地址,不覆盖已有的 muted 参数。设为 false 时写入 muted=false,有声自动播放仍受浏览器策略限制。</para> | ||
| /// <para lang="en">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.</para> | ||
| /// <para><version>11.0.2</version></para> | ||
| /// </summary> | ||
| [Parameter] | ||
| public bool IsMuted { get; set; } = true; | ||
|
|
||
| [Inject, NotNull] | ||
| private IStringLocalizer<HikVisionWebRtc>? Localizer { get; set; } | ||
|
|
||
| [Inject, NotNull] | ||
| private ILogger<HikVisionWebRtc>? 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; | ||
|
|
||
| /// <summary> | ||
| /// <inheritdoc/> | ||
| /// </summary> | ||
| 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); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Restart leaves preview failed When a component's startup check returns just before the gateway exits, and another component restarts it while the first proceeds to register, Coordinate registration with gateway restart, or retry startup and registration when the service reports that the gateway is not running. Prompt for AI agentsIn `src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs` at line 92:
**Restart leaves preview failed**
When a component's startup check returns just before the gateway exits, and another component restarts it while the first proceeds to register, `RegisterUrl` calls `AddOrUpdateAsync` during the restart gap; the service has cleared its API password, so registration throws. `RegisterUrl` catches the exception and leaves `_registeredUrl` null, and this first-render-only initialization then displays a registration error even after the gateway recovers.
Coordinate registration with gateway restart, or retry startup and registration when the service reports that the gateway is not running. |
||
| } | ||
| } | ||
| _initializing = false; | ||
| if (!_disposed) | ||
| { | ||
| StateHasChanged(); | ||
| } | ||
| } | ||
|
|
||
| private async Task<bool> 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<string?> RegisterUrl(MediaMtxCameraOptions options, CancellationToken cancellationToken) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ⚪ Low · Async helper misses naming suffix The private Rename Prompt for AI agentsIn `src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs` at line 134:
**Async helper misses naming suffix**
The private `RegisterUrl` method is asynchronous but lacks the `Async` suffix, so it violates the repository’s naming convention for async methods.
Rename `RegisterUrl` to `RegisterUrlAsync` and update its call site.From - **C#**。遵循 `.editorconfig` 和相邻文件的风格,优先使用文件范围命名空间,添加源文件时沿用文件头。源码启用可空引用类型和隐式 `using`。处理无效输入或已释放状态时可用早期返回,新增异步方法优先用 `Async` 后缀,保留已有公开签名和接口约定。[编辑器配置](.editorconfig) · [共享构建属性](Directory.Build.props) |
||
| { | ||
| string? registeredUrl = null; | ||
| try | ||
| { | ||
| registeredUrl = await MediaMtxService.AddOrUpdateAsync(options, cancellationToken); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟠 High · Camera streams lack reader authorization When the MediaMTX listener is reachable through a reverse proxy or other network route that does not enforce authentication, the registered camera is served through MediaMTX, whose generated configuration grants Require authorization at the MediaMTX reader or reverse-proxy boundary before exposing camera streams, and document that page authorization alone does not protect the iframe endpoint. Prompt for AI agentsIn `src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs` at line 139:
**Camera streams lack reader authorization**
When the MediaMTX listener is reachable through a reverse proxy or other network route that does not enforce authentication, the registered camera is served through MediaMTX, whose generated configuration grants `read` permission to user `any`. An unauthenticated visitor who can reach the gateway or an unauthenticated reverse proxy can view streams by path, bypassing authorization on the page that renders this component.
Require authorization at the MediaMTX reader or reverse-proxy boundary before exposing camera streams, and document that page authorization alone does not protect the iframe endpoint.There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟠 High · Camera options enable server-side SSRF When an application lets an untrusted user choose or modify the component's Validate the RTSP destination against a server-side allowlist or equivalent network policy before registering it, and prevent access to loopback, link-local, and other restricted destinations. Prompt for AI agentsIn `src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs` at line 139:
**Camera options enable server-side SSRF**
When an application lets an untrusted user choose or modify the component's `Options`, `RegisterUrl` passes the supplied camera options to the server-side MediaMTX service, which accepts any absolute RTSP/RTSPS host and lets MediaMTX connect to it. A user who can influence those options can make the application server connect to internal or otherwise restricted RTSP services.
Validate the RTSP destination against a server-side allowlist or equivalent network policy before registering it, and prevent access to loopback, link-local, and other restricted destinations.There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Closed previews leave registrations When a preview component is removed after registering a path that is not intended to remain available, each successful Define ownership and cleanup semantics for component-created registrations, such as an explicit opt-in cleanup policy or a documented caller-managed registration lifecycle. Prompt for AI agentsIn `src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs` at line 139:
**Closed previews leave registrations**
When a preview component is removed after registering a path that is not intended to remain available, each successful `RegisterUrl` call adds or updates a path in the shared gateway, but disposing the component only cancels pending work and never calls `RemoveAsync`; applications that create previews for transient or changing paths leave stale path configuration and its source credentials active until explicitly removed or the gateway stops.
Define ownership and cleanup semantics for component-created registrations, such as an explicit opt-in cleanup policy or a documented caller-managed registration lifecycle. |
||
| 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."); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Invalid URLs show registration error When the default MediaMTX service receives an invalid Preserve or set the invalid-URL failure state when registration rejects Also at Prompt for AI agentsIn `src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs` at line 148:
**Invalid URLs show registration error**
When the default MediaMTX service receives an invalid `Options.PlayUrl`, `RegisterUrl` catches the service exception and leaves `_registeredUrl` null, so the markup shows `RegistrationFailedText` before checking `PlayerUrl` and users see a registration error instead of the invalid-URL message.
Preserve or set the invalid-URL failure state when registration rejects `PlayUrl`, and render that message instead of the generic registration error.
Also at `src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor:17`. |
||
| } | ||
| 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) || | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Preview switches to unregistered camera When the parent changes Register the updated options when they change, or have the iframe use only the URL corresponding to the registered options. Prompt for AI agentsIn `src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs` at line 155:
**Preview switches to unregistered camera**
When the parent changes `Options.PlayUrl` after initial registration, including while gateway startup is awaited, `GetPlayerUrl` reads the latest `Options.PlayUrl`, while registration uses the options captured during initialization, so the iframe points to a source that is not registered and the preview shows the wrong camera or fails.
Register the updated options when they change, or have the iframe use only the URL corresponding to the registered options. |
||
| 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; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// <inheritdoc/> | ||
| /// </summary> | ||
| public void Dispose() | ||
| { | ||
| if (_disposed) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| _disposed = true; | ||
| _initializationCancellation.Cancel(); | ||
| _initializationCancellation.Dispose(); | ||
| GC.SuppressFinalize(this); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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." | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| { | ||
| "BootstrapBlazor.Components.HikVisionWebRtc": { | ||
| "OptionsMissingText": "未配置摄像头,无法初始化播放器。", | ||
| "InitializingText": "正在准备预览,请稍后 ...", | ||
| "MediaMtxToolMissingText": "未找到后台 MediaMTX 工具,请联系管理员部署。", | ||
| "MediaMtxToolMissingPathText": "未找到后台 MediaMTX 工具:{0}(相对于应用目录)。请联系管理员部署。", | ||
| "GatewayStartFailedText": "后台 MediaMTX 网关启动失败,请查看服务端日志。", | ||
| "RegistrationFailedText": "摄像头登记失败,请查看服务端日志。", | ||
| "InvalidUrlText": "播放地址必须是不含凭据的绝对 HTTP 或 HTTPS 地址。" | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟠 High · Existing consumers stop compiling
When an application upgrades from 11.0.2 while still passing
WebRtcUrl,HikVisionWebRtcno longer exposesWebRtcUrl, so existing Razor or C# usages fail to compile instead of working as a patch upgrade.Keep
WebRtcUrlcompatible, or make its removal in a major release.Also at
src/components/BootstrapBlazor.HikVision/Components/HikVisionWebRtc.razor.cs:26.Prompt for AI agents
From
docs/agents/component-checklist.mdL5: