Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<PropertyGroup>
<PackageTags>Bootstrap Blazor Server UI Components HikVision WebRTC</PackageTags>
<Description>Bootstrap UI components extensions of HikVision</Description>
<PackageReadmeFile>README.HikVision.md</PackageReadmeFile>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk.Razor">

<PropertyGroup>
<Version>11.0.4</Version>
<Version>11.0.5</Version>
<SkillName>bb-mediamtx</SkillName>
</PropertyGroup>

Expand All @@ -19,6 +19,11 @@
<SupportedPlatform Remove="browser" />
</ItemGroup>

<ItemGroup>
<Content Remove="Locales\*.json" />
<EmbeddedResource Include="Locales\*.json" />
</ItemGroup>

<ItemGroup>
<None Remove="readme.md" />
<None Include="README.MediaMtx.md" Pack="true" PackagePath="" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
@namespace BootstrapBlazor.Components
@inherits BootstrapComponentBase

<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>
}
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
@@ -0,0 +1,184 @@
// Copyright (c) BootstrapBlazor & Argo Zhang ([email protected]). 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;

/// <summary>
/// <para lang="zh">通过 MediaMTX 播放页面以 WebRTC 方式实时预览 RTSP 或 RTSPS 摄像机。</para>
/// <para lang="en">Displays a live WebRTC preview of an RTSP or RTSPS camera using the MediaMTX player page.</para>
/// <para><version>11.0.6</version></para>
/// </summary>
public partial class MediaMtxPlayer : IDisposable
{
/// <summary>
/// <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.6</version></para>
/// </summary>
[Parameter]
public MediaMtxCameraOptions? Options { get; set; }

/// <summary>
/// <para lang="zh">获得/设置播放器的无障碍标题。</para>
/// <para lang="en">Gets or sets the accessible title of the player.</para>
/// <para><version>11.0.6</version></para>
/// </summary>
[Parameter]
public string Title { get; set; } = "WebRTC";

/// <summary>
/// <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.6</version></para>
/// </summary>
[Parameter]
public bool IsMuted { get; set; } = true;

[Inject, NotNull]
private IStringLocalizer<MediaMtxPlayer>? Localizer { get; set; }

[Inject, NotNull]
private ILogger<MediaMtxPlayer>? 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;

/// <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);
}
}
_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)
{
}
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)
{
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;
}

/// <summary>
/// <inheritdoc/>
/// </summary>
public void Dispose()
{
if (_disposed)
{
return;
}

_disposed = true;
_initializationCancellation.Cancel();
_initializationCancellation.Dispose();
GC.SuppressFinalize(this);
}
}
11 changes: 11 additions & 0 deletions src/components/BootstrapBlazor.MediaMtx/Locales/en.json
Original file line number Diff line number Diff line change
@@ -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."
}
}
11 changes: 11 additions & 0 deletions src/components/BootstrapBlazor.MediaMtx/Locales/zh.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"BootstrapBlazor.Components.MediaMtxPlayer": {
"OptionsMissingText": "未配置摄像头,无法初始化播放器。",
"InitializingText": "正在准备预览,请稍后 ...",
"MediaMtxToolMissingText": "未找到后台 MediaMTX 工具,请联系管理员部署。",
"MediaMtxToolMissingPathText": "未找到后台 MediaMTX 工具:{0}(相对于应用目录)。请联系管理员部署。",
"GatewayStartFailedText": "后台 MediaMTX 网关启动失败,请查看服务端日志。",
"RegistrationFailedText": "摄像头登记失败,请查看服务端日志。",
"InvalidUrlText": "播放地址必须是不含凭据的绝对 HTTP 或 HTTPS 地址。"
}
}
24 changes: 11 additions & 13 deletions src/components/BootstrapBlazor.MediaMtx/README.MediaMtx.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,19 @@ dotnet user-secrets set "MediaMtxOptions:Cameras:hikvision:Password" "<camera-pa
| `WebRtc:Ice:AdditionalHosts` | 默认为 `["127.0.0.1"]`,额外公布的 ICE IP 或主机名。 |
| `WebRtc:PublicUrl` | 可选的 HTTP/HTTPS 播放基址,可带路径前缀,不允许凭据、查询字符串或片段;不配置 ICE。 |
| `Gateway:MediaMtxPath` | 默认 `mediamtx-tools\<RID>\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<MediaMtxOptions> GatewayOptions

<HikVisionWebRtc Options="@camera" />
<MediaMtxPlayer Options="@camera" />
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved

@code {
private MediaMtxCameraOptions camera = default!;
Expand All @@ -111,7 +111,7 @@ dotnet user-secrets set "MediaMtxOptions:Cameras:hikvision:Password" "<camera-pa
}
```

组件首次交互渲染时依次调用 `EnsureStartedAsync()`、`AddOrUpdateAsync(camera)`,成功后显示 iframe;预渲染不启动网关。组件不自动重试,修改源或重试需重新创建组件实例。
组件首次交互渲染时依次调用 `EnsureStartedAsync()`、`AddOrUpdateAsync(camera)`,成功后显示 iframe;预渲染不启动网关。组件不自动重试,修改源或重试需重新创建组件实例。登记失败时不显示播放器。

自行管理时,在服务端注入 `IMediaMtxService`:

Expand All @@ -126,7 +126,7 @@ await mediaMtx.RemoveAsync(camera.Path!, cancellationToken);

- `Path` 必须非空。建议调用方限制为小写字母开头,仅包含小写字母、数字和连字符,最长 63 个字符,排除 `all`。
- `RtspUrl` 必须是包含主机名且不含用户信息的绝对 RTSP/RTSPS 地址。`UserName`、`Password` 传原始值,由服务编码;没有用户名时忽略密码。
- `PlayUrl` 为 `null` 时生成 `<WebRtc:PublicUrl>/<Path>/`,未配置公开基址则使用 `http://127.0.0.1:<WebRtc:Port>/<Path>/`。非 `null` 时必须是无凭据的绝对 HTTP/HTTPS 地址,空字符串无效;它不改变监听、允许的来源或 ICE。
- 播放地址由 `<WebRtc:PublicUrl>/<Path>/` 生成,未配置公开基址则使用 `http://127.0.0.1:<WebRtc:Port>/<Path>/`;它不改变监听、允许的来源或 ICE。
- 更新、删除同一路径会影响所有观看者。动态配置只保存在网关内存中,网关重启后需重新登记;关闭播放器不删除路径。

播放页默认静音;有声自动播放受浏览器策略限制。音频可使用 G.711 μ-law(PCMU)或 A-law(PCMA)等浏览器支持的编码,不兼容编码需另行转码。
Expand Down Expand Up @@ -165,18 +165,16 @@ MediaMTX → 摄像头 RTSP 地址:源流

## 进程复用

同一服务实例的网关仍运行时,`EnsureStartedAsync` 直接返回。新的宿主通过当前系统用户的本机应用数据目录 `BootstrapBlazor\mediamtx-gateways` 及文件锁协调,按 `Gateway:Port` 查找状态,再核对 PID、启动时间和进程路径。
同一服务实例的网关仍运行时,`EnsureStartedAsync` 直接返回。其他宿主先检查 `127.0.0.1:<Gateway:Port>/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` 才会尝试启动。启动失败会清理本次启动的进程。

## 外部本机网关

Expand Down Expand Up @@ -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、日志或浏览器存储。
Loading
Loading