Repository navigation
feat(MediaMtx): add MediaMtxPlayer component for WebRTC preview #1408
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
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
bfebb33
feat: 增加 MediaMtxPlayer 组件
ArgoZhang ccdabc0
chore: bump version 10.0.5
ArgoZhang 52a6886
Merge branch 'refactor-hik' into feat-mediamtx
ArgoZhang b91af2e
refactor: 移动代码
ArgoZhang f987497
chore: bump version 11.0.6
ArgoZhang 92bc384
fix(MediaMtx): align docs and version metadata for MediaMtxPlayer
ArgoZhang 8980a72
fix(MediaMtx): align docs and version metadata for MediaMtxPlayer
ArgoZhang 2becb8a
refactor: 精简逻辑
ArgoZhang 91ec529
doc: 更新文档
ArgoZhang c3116a0
refactor(MediaMtx): remove PlayUrl from MediaMtxCameraOptions
ArgoZhang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
src/components/BootstrapBlazor.MediaMtx/Components/MediaMtxPlayer.razor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
184 changes: 184 additions & 0 deletions
184
src/components/BootstrapBlazor.MediaMtx/Components/MediaMtxPlayer.razor.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } |
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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." | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 地址。" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.