diff --git a/tools/BootstrapBlazor.MediaMtx.Cli/BootstrapBlazor.MediaMtx.Cli.csproj b/tools/BootstrapBlazor.MediaMtx.Cli/BootstrapBlazor.MediaMtx.Cli.csproj
index 18021b95..b5ac2262 100644
--- a/tools/BootstrapBlazor.MediaMtx.Cli/BootstrapBlazor.MediaMtx.Cli.csproj
+++ b/tools/BootstrapBlazor.MediaMtx.Cli/BootstrapBlazor.MediaMtx.Cli.csproj
@@ -1,19 +1,25 @@
+
-
- net8.0
+ 11.0.2
Exe
- 11.0.0
+
+
+
+ BootstrapBlazor MediaMTX CLI
+ Downloads and verifies MediaMTX from GitHub and copies tools to application build and publish directories.
true
bb-mediamtx
- Major
- BootstrapBlazor.MediaMtx.Cli
- Downloads and verifies MediaMTX from GitHub and copies tools to application build and publish directories.
BootstrapBlazor MediaMTX CLI
readme.md
+
+
+
+
+
diff --git a/tools/BootstrapBlazor.MediaMtx.Cli/MediaMtxInstaller.cs b/tools/BootstrapBlazor.MediaMtx.Cli/MediaMtxInstaller.cs
index 9f3b7cd0..e9063e82 100644
--- a/tools/BootstrapBlazor.MediaMtx.Cli/MediaMtxInstaller.cs
+++ b/tools/BootstrapBlazor.MediaMtx.Cli/MediaMtxInstaller.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
// Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone
+using System.Diagnostics;
using System.Formats.Tar;
using System.IO.Compression;
using System.Runtime.InteropServices;
@@ -12,9 +13,13 @@
namespace BootstrapBlazor.MediaMtx.Cli;
-static class MediaMtxInstaller
+static partial class MediaMtxInstaller
{
private const string Repository = "https://api.github.com/repos/bluenviron/mediamtx";
+ private static readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ WriteIndented = true
+ };
private static readonly Dictionary _platforms = new(StringComparer.Ordinal)
{
["win-x64"] = "windows_amd64.zip",
@@ -25,19 +30,46 @@ static class MediaMtxInstaller
["osx-arm64"] = "darwin_arm64.tar.gz"
};
- public static async Task DeployAsync(string? rid, CancellationToken cancellationToken, bool force = false)
+ public static async Task DownloadAllAsync(string? output, bool copy, bool force, CancellationToken cancellationToken)
+ {
+ foreach (var rid in _platforms.Keys)
+ {
+ try
+ {
+ await DeployAsync(rid, null, download: true, copy: false, force: false, skipExistingOutput: false, cancellationToken);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception exception)
+ {
+ await Console.Out.WriteLineAsync($"[MediaMTX] Warning - deployment failed for {rid}: {exception.Message}", cancellationToken);
+ }
+ }
+
+ if (copy)
+ {
+ await DeployAsync(null, output, download: false, copy: true, force, skipExistingOutput: false, cancellationToken);
+ }
+ }
+
+ public static async Task DeployAsync(string? rid, string? output, bool download, bool copy,
+ bool force, bool skipExistingOutput, CancellationToken cancellationToken)
{
rid ??= GetCurrentRid();
if (!_platforms.TryGetValue(rid, out var platform))
{
throw new ArgumentException($"Unsupported RID '{rid}'. Supported RIDs: {string.Join(", ", _platforms.Keys)}.");
}
- var outputDirectory = Path.Combine(Directory.GetCurrentDirectory(), "mediamtx-tools", rid);
+ var outputDirectory = copy
+ ? Path.Combine(Path.GetFullPath(output ?? Directory.GetCurrentDirectory()), "mediamtx-tools", rid)
+ : string.Empty;
var executableName = rid == "win-x64" ? "mediamtx.exe" : "mediamtx";
- if (!force && File.Exists(Path.Combine(outputDirectory, executableName)) &&
+ if (copy && skipExistingOutput && !force && File.Exists(Path.Combine(outputDirectory, executableName)) &&
File.Exists(Path.Combine(outputDirectory, "LICENSE.MediaMTX")))
{
- await Console.Out.WriteLineAsync($"MediaMTX tools already exist at {outputDirectory}; skipping deployment.");
+ await Console.Out.WriteLineAsync($"MediaMTX tools already exist at {outputDirectory}; skipping deployment.", cancellationToken);
return;
}
@@ -57,11 +89,19 @@ await GetHashAsync(executable, cancellationToken) == installed.ExecutableSha256
await GetHashAsync(license, cancellationToken) == installed.LicenseSha256)
{
SetExecutablePermission(executable);
- await Console.Out.WriteLineAsync($"MediaMTX {tag} for {rid}: verified cached tools at {toolDirectory}");
- await CopyToolsAsync(toolDirectory, rid, outputDirectory, cancellationToken, force);
+ await Console.Out.WriteLineAsync($"MediaMTX {tag} for {rid}: verified cached tools at {toolDirectory}", cancellationToken);
+ if (copy)
+ {
+ await CopyToolsAsync(toolDirectory, rid, outputDirectory, force, cancellationToken);
+ }
return;
}
+ if (!download)
+ {
+ throw new InvalidDataException($"MediaMTX cache for {rid} is missing or invalid at {toolDirectory}. Run dotnet bb-mediamtx --download first.");
+ }
+
using var client = CreateClient();
using var releaseStream = await client.GetStreamAsync($"{Repository}/releases/tags/{tag}", cancellationToken);
using var release = await JsonDocument.ParseAsync(releaseStream, cancellationToken: cancellationToken);
@@ -82,12 +122,9 @@ await GetHashAsync(license, cancellationToken) == installed.LicenseSha256)
try
{
var archivePath = Path.Combine(staging, platform.EndsWith(".zip", StringComparison.Ordinal) ? "archive.zip" : "archive.tar.gz");
- await Console.Out.WriteLineAsync($"Downloading {assetName} from GitHub...");
- await using (var source = await client.GetStreamAsync(GetAssetUrl(asset), cancellationToken))
- await using (var destination = File.Create(archivePath))
- {
- await source.CopyToAsync(destination, cancellationToken);
- }
+ var assetUrl = GetAssetUrl(asset);
+ await Console.Out.WriteLineAsync($"Downloading {assetName} from {assetUrl}", cancellationToken);
+ await DownloadAsync(client, assetUrl, archivePath, cancellationToken);
if (await GetHashAsync(archivePath, cancellationToken) != digest)
{
throw new InvalidDataException($"SHA-256 verification failed for '{assetName}'. No tool files were installed.");
@@ -108,11 +145,14 @@ await GetHashAsync(stagedExecutable, cancellationToken),
File.Move(stagedExecutable, executable, overwrite: true);
File.Move(stagedLicense, license, overwrite: true);
var stagedMarker = Path.Combine(staging, "installation.json");
- await File.WriteAllTextAsync(stagedMarker, JsonSerializer.Serialize(installation, new JsonSerializerOptions { WriteIndented = true }), cancellationToken);
+ await File.WriteAllTextAsync(stagedMarker, JsonSerializer.Serialize(installation, _jsonOptions), cancellationToken);
File.Move(stagedMarker, markerPath, overwrite: true);
- await Console.Out.WriteLineAsync($"Prepared MediaMTX {tag} for {rid}.");
- await Console.Out.WriteLineAsync($"Tools: {toolDirectory}");
- await CopyToolsAsync(toolDirectory, rid, outputDirectory, cancellationToken, force);
+ await Console.Out.WriteLineAsync($"Prepared MediaMTX {tag} for {rid}.", cancellationToken);
+ await Console.Out.WriteLineAsync($"Tools: {toolDirectory}", cancellationToken);
+ if (copy)
+ {
+ await CopyToolsAsync(toolDirectory, rid, outputDirectory, force, cancellationToken);
+ }
}
finally
{
@@ -132,7 +172,7 @@ await GetHashAsync(stagedExecutable, cancellationToken),
}
catch (JsonException exception)
{
- await Console.Error.WriteLineAsync($"Invalid MediaMTX cache record '{markerPath}': {exception.Message}. Tools will be verified and downloaded again.");
+ await Console.Error.WriteLineAsync($"Invalid MediaMTX cache record '{markerPath}': {exception.Message}.", cancellationToken);
return null;
}
}
@@ -144,7 +184,40 @@ private static HttpClient CreateClient()
return client;
}
- private static async Task CopyToolsAsync(string toolDirectory, string rid, string destinationDirectory, CancellationToken cancellationToken, bool force)
+ private static async Task DownloadAsync(HttpClient client, Uri uri, string archivePath, CancellationToken cancellationToken)
+ {
+ using var response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
+ response.EnsureSuccessStatusCode();
+ var total = response.Content.Headers.ContentLength;
+ await using var source = await response.Content.ReadAsStreamAsync(cancellationToken);
+ await using var destination = File.Create(archivePath);
+ var buffer = new byte[81920];
+ long downloaded = 0;
+ var lastPercent = -5;
+ var timer = Stopwatch.StartNew();
+ while (await source.ReadAsync(buffer, cancellationToken) is var count && count > 0)
+ {
+ await destination.WriteAsync(buffer.AsMemory(0, count), cancellationToken);
+ downloaded += count;
+ if (total is > 0)
+ {
+ var percent = (int)Math.Min(100, downloaded * 100.0 / total.Value);
+ if (percent >= lastPercent + 5)
+ {
+ await Console.Out.WriteLineAsync($"Downloaded {downloaded} / {total} bytes ({percent}%).", cancellationToken);
+ lastPercent = percent;
+ }
+ }
+ else if (timer.Elapsed >= TimeSpan.FromSeconds(1))
+ {
+ await Console.Out.WriteLineAsync($"Downloaded {downloaded} bytes.", cancellationToken);
+ timer.Restart();
+ }
+ }
+ await Console.Out.WriteLineAsync($"Download complete: {downloaded} bytes.", cancellationToken);
+ }
+
+ private static async Task CopyToolsAsync(string toolDirectory, string rid, string destinationDirectory, bool force, CancellationToken cancellationToken)
{
Directory.CreateDirectory(destinationDirectory);
var executableName = rid == "win-x64" ? "mediamtx.exe" : "mediamtx";
@@ -175,7 +248,7 @@ private static async Task CopyToolsAsync(string toolDirectory, string rid, strin
File.Delete(temporary);
}
}
- await Console.Out.WriteLineAsync($"MediaMTX tools copied to {destinationDirectory}");
+ await Console.Out.WriteLineAsync($"MediaMTX tools copied to {destinationDirectory}", cancellationToken);
}
private static async Task AcquireCacheLockAsync(string path, CancellationToken cancellationToken)
@@ -238,13 +311,16 @@ private static async Task GetAssetDigestAsync(HttpClient client, JsonEle
private static string ValidateHash(string value)
{
- if (!Regex.IsMatch(value, "^[0-9a-fA-F]{64}$", RegexOptions.CultureInvariant))
+ if (!Sha256Regex().IsMatch(value))
{
throw new InvalidDataException("The release SHA-256 checksum is invalid.");
}
return value.ToLowerInvariant();
}
+ [GeneratedRegex("^[0-9a-fA-F]{64}$", RegexOptions.CultureInvariant)]
+ private static partial Regex Sha256Regex();
+
private static async Task GetHashAsync(string path, CancellationToken cancellationToken)
{
await using var stream = File.OpenRead(path);
diff --git a/tools/BootstrapBlazor.MediaMtx.Cli/Program.cs b/tools/BootstrapBlazor.MediaMtx.Cli/Program.cs
index 31ba20dc..60964f8b 100644
--- a/tools/BootstrapBlazor.MediaMtx.Cli/Program.cs
+++ b/tools/BootstrapBlazor.MediaMtx.Cli/Program.cs
@@ -4,21 +4,44 @@
// Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone
using BootstrapBlazor.MediaMtx.Cli;
-using System.Text.Json;
if (args.Contains("--help") || args.Contains("-h"))
{
await Console.Out.WriteLineAsync("""
- bb-mediamtx [--rid ] [--force]
+ Usage: bb-mediamtx [--download] [--copy] [--rid ] [--output ] [--force]
+ bb-mediamtx --help
+ bb-mediamtx -h
- Copies missing MediaMTX 1.21.4 tools to mediamtx-tools/ in the current directory.
- By default, existing files are not overwritten and complete output skips cache checks and downloads.
- The tool cache is stored under local application data in BootstrapBlazor/mediamtx.
- --rid win-x64, linux-x64, linux-arm64, linux-arm, osx-x64, osx-arm64.
- Defaults to the current operating system and architecture.
- --force Verify/prepare the cache and overwrite the output executable and license.
- """);
- return 0;
+ Without --download or --copy, copy missing files from the cache.
+ --download Verify the cache for the selected RID; download from GitHub if missing
+ or invalid. Shows the download URL and progress. Does not copy by itself.
+ --copy Copy the executable and license from the verified cache without downloading.
+ Can be combined with --download.
+ --rid Select win-x64, linux-x64, linux-arm64, linux-arm, osx-x64, or osx-arm64.
+ Omitted or empty selects the current OS and architecture.
+ With --download, all prepares every supported RID; combined with --copy,
+ only the current RID is copied. all cannot be used for copy alone.
+ When preparing all RIDs, failures are reported and processing continues.
+ --output Base directory for copies; defaults to the current working directory.
+ Relative paths are based on the current working directory.
+ Files go to mediamtx-tools/ under this directory.
+ --force Overwrite existing output files; does not force a download.
+ Cannot be used with --download unless --copy is also specified.
+ --help, -h Show this help without performing other actions.
+
+ Existing output files are preserved unless --force is used. Copy-only skips cache validation
+ when both output files already exist. The cache is under local application data in
+ BootstrapBlazor/mediamtx. Options and RIDs are case-sensitive; options other than help
+ cannot be repeated.
+ Failures and cancellations are warnings and do not produce a nonzero exit code.
+
+ Examples:
+ bb-mediamtx --download
+ bb-mediamtx --download --rid all
+ bb-mediamtx --download --copy --rid linux-arm64 --output publish
+ bb-mediamtx --copy --rid linux-arm64 --output publish --force
+ """, CancellationToken.None);
+ return;
}
using var cancellation = new CancellationTokenSource();
@@ -32,7 +55,11 @@ Defaults to the current operating system and architecture.
try
{
string? rid = null;
+ string? output = null;
+ var ridSpecified = false;
var force = false;
+ var download = false;
+ var copy = false;
for (var index = 0; index < args.Length; index++)
{
switch (args[index])
@@ -40,28 +67,54 @@ Defaults to the current operating system and architecture.
case "--force" when !force:
force = true;
break;
- case "--rid" when rid is null:
+ case "--download" when !download:
+ download = true;
+ break;
+ case "--copy" when !copy:
+ copy = true;
+ break;
+ case "--rid" when !ridSpecified:
if (index + 1 == args.Length || args[index + 1].StartsWith("--", StringComparison.Ordinal))
{
throw new ArgumentException("Option '--rid' requires a value.");
}
- rid = args[++index];
+ ridSpecified = true;
+ var ridArgument = args[++index].Trim();
+ rid = ridArgument.Length == 0 ? null : ridArgument;
+ break;
+ case "--output" when output is null:
+ if (index + 1 == args.Length || args[index + 1].StartsWith("--", StringComparison.Ordinal) ||
+ string.IsNullOrWhiteSpace(args[index + 1]))
+ {
+ throw new ArgumentException("Option '--output' requires a directory.");
+ }
+ output = args[++index];
break;
default:
- throw new ArgumentException("Usage: bb-mediamtx [--rid ] [--force].");
+ throw new ArgumentException("Usage: bb-mediamtx [--download] [--copy] [--rid ] [--output ] [--force].");
}
}
- await MediaMtxInstaller.DeployAsync(rid, cancellation.Token, force);
- return 0;
+ if (download && !copy && force)
+ {
+ throw new ArgumentException("Option '--force' requires copying; use it with '--copy'.");
+ }
+ var defaultAction = !download && !copy;
+ if (download && rid == "all")
+ {
+ cancellation.CancelAfter(TimeSpan.FromMinutes(30));
+ await MediaMtxInstaller.DownloadAllAsync(output, copy, force, cancellation.Token);
+ }
+ else
+ {
+ await MediaMtxInstaller.DeployAsync(rid, output, download, copy || defaultAction, force,
+ skipExistingOutput: !download, cancellationToken: cancellation.Token);
+ }
}
catch (OperationCanceledException)
{
- await Console.Error.WriteLineAsync("MediaMTX deployment was canceled or timed out.");
- return 130;
+ await Console.Out.WriteLineAsync("[MediaMTX] Warning - deployment was canceled or timed out.", CancellationToken.None);
}
-catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or
- IOException or UnauthorizedAccessException or HttpRequestException or JsonException or NotSupportedException)
+catch (Exception exception)
{
- await Console.Error.WriteLineAsync($"MediaMTX deployment failed: {exception.Message}");
- return 1;
+ await Console.Out.WriteLineAsync($"[MediaMTX] Warning - deployment failed: {exception.Message}", CancellationToken.None);
}
diff --git a/tools/BootstrapBlazor.MediaMtx.Cli/readme.md b/tools/BootstrapBlazor.MediaMtx.Cli/readme.md
index 14e070d2..02d5511c 100644
--- a/tools/BootstrapBlazor.MediaMtx.Cli/readme.md
+++ b/tools/BootstrapBlazor.MediaMtx.Cli/readme.md
@@ -1,20 +1,19 @@
# BootstrapBlazor.MediaMtx.Cli
-独立的轻量 .NET CLI 工具,负责部署 MediaMTX 可执行文件和许可证。按目标 RID 复用本机缓存,必要时从 [MediaMTX GitHub Releases](https://github.com/bluenviron/mediamtx/releases) 下载并校验,再复制到当前工作目录的 `mediamtx-tools\`。NuGet 工具包不内置 MediaMTX 二进制文件。需要 .NET 8 或更高版本。
+独立的 .NET CLI 工具,用于下载、校验和缓存 [MediaMTX](https://github.com/bluenviron/mediamtx/releases),并将可执行文件和许可证复制到应用目录。工具包不包含 MediaMTX 二进制文件;`BootstrapBlazor.MediaMtx` 主包也不会自动安装 CLI 或下载 MediaMTX。
-## 使用
+CLI 目标为 .NET 11:安装工具需要 .NET SDK,运行需要 .NET 11 运行时。若只有更高主版本的运行时,需另行启用运行时 roll-forward。
-```powershell
-dotnet tool install -g BootstrapBlazor.MediaMtx.Cli --prerelease
-```
+## 安装
-在编译或发布后的应用目录执行,自动识别本机平台并复制工具:
+全局安装后使用 `bb-mediamtx`:
```powershell
-bb-mediamtx
+dotnet tool install -g BootstrapBlazor.MediaMtx.Cli
+bb-mediamtx --help
```
-也支持宿主手动维护的根目录 `dotnet-tools.json` 工具清单,不使用 `.config` 目录。例如:
+如需安装预览版,可在安装命令中添加 `--prerelease`。也可在宿主中维护本地工具清单;例如项目根目录的 `dotnet-tools.json`:
```json
{
@@ -22,61 +21,106 @@ bb-mediamtx
"isRoot": true,
"tools": {
"bootstrapblazor.mediamtx.cli": {
- "version": "11.0.0-beta15",
+ "version": "11.0.2",
"commands": ["bb-mediamtx"]
}
}
}
```
-以下示例假定应用已发布到仓库根目录下的 `.\publish`。本地工具使用 `dotnet bb-mediamtx` 调用,不需要全局安装:
+从包含该清单的目录还原和调用本地工具:
```powershell
dotnet tool restore --tool-manifest .\dotnet-tools.json
-Push-Location .\publish
-dotnet bb-mediamtx --rid linux-arm64
-Pop-Location
+dotnet bb-mediamtx --help
+```
+
+清单和工具包由宿主维护;普通 NuGet restore 不会还原本地工具。以下示例使用全局工具,本地工具将 `bb-mediamtx` 替换为 `dotnet bb-mediamtx` 即可。
+
+## 参数
+
+```text
+bb-mediamtx [--download] [--copy] [--rid ] [--output ] [--force]
+bb-mediamtx --help
+```
+
+参数顺序不限;参数名和 RID 区分大小写,动作及其选项不能重复。包含 `--help` 或 `-h` 时只显示帮助。
+
+| 参数 | 说明 |
+| --- | --- |
+| `--download` | 检查目标 RID 的缓存,缺失或校验失败时从 GitHub 下载并校验;不单独复制到输出目录。下载时显示资源地址和进度。 |
+| `--copy` | 从已校验的缓存复制工具和许可证,不联网;缓存缺失或损坏时输出警告。可与 `--download` 组合。 |
+| `--rid ` | 指定目标平台。省略或显式传入空字符串时使用当前操作系统和架构。`--download --rid all` 准备全部支持平台;与 `--copy` 组合时只复制本机平台。`all` 不能单独用于复制。 |
+| `--output ` | 复制的输出基目录。省略时使用命令执行时的当前工作目录;相对路径也以当前工作目录为基准。仅下载时不使用此参数。 |
+| `--force` | 复制时覆盖输出目录中已有的可执行文件和许可证,不强制重新下载;有效缓存仍会复用。单独 `--download` 不能与 `--force` 组合。 |
+| `--help`、`-h` | 显示帮助,不执行下载或复制。 |
+
+支持的 RID 为 `win-x64`、`linux-x64`、`linux-arm64`、`linux-arm`(ARMv7)、`osx-x64` 和 `osx-arm64`。未指定动作时,默认从缓存复制到当前目录;例如 `bb-mediamtx --rid linux-x64 --output .\publish` 等同于使用相同参数的 `--copy`。
+
+复制到 `<输出基目录>\mediamtx-tools\`,文件为 `mediamtx.exe`(Windows)或 `mediamtx`(其他平台),以及 `LICENSE.MediaMTX`。CLI 不查找工程,也不自动推断编译或发布输出目录。
+
+不带 `--force` 时,输出文件已存在就保留,缺少的文件才会复制。无参数或仅复制时,如果两个文件都已存在,CLI 会直接跳过,不校验缓存或输出文件内容。需要更新已有输出时使用 `--force`。
+
+## 常用示例
+
+准备本机平台缓存,并复制到发布目录:
+
+```powershell
+bb-mediamtx --download
+bb-mediamtx --copy --output .\publish
```
-CLI 支持无参数部署、`--rid` 和 `--force`,准备固定版本 MediaMTX `1.21.4`,复制到当前目录的 `mediamtx-tools\`。跨平台部署通过 `--rid` 指定目标平台,不需要工程文件:
+准备指定平台并复制;也可以合并两个动作:
```powershell
-bb-mediamtx --rid linux-arm64
+bb-mediamtx --download --rid linux-arm64
+bb-mediamtx --copy --rid linux-arm64 --output .\publish
+
+bb-mediamtx --download --copy --rid linux-arm64 --output .\publish
```
-强制覆盖已有工具和许可证,可与 `--rid` 组合,参数顺序不限:
+预热全部平台缓存,或者预热全部平台并只复制本机平台:
```powershell
-bb-mediamtx --force
-bb-mediamtx --rid linux-arm64 --force
+bb-mediamtx --download --rid all
+bb-mediamtx --download --copy --rid all --output .\publish
```
-支持 `win-x64`、`linux-x64`、`linux-arm64`、`linux-arm`(ARMv7)、`osx-x64` 和 `osx-arm64`。该工具只部署 MediaMTX,不增加核心包引用;应用仍需引用 `BootstrapBlazor.MediaMtx` 并调用 `AddMediaMtxService()`。
+覆盖目标平台已有工具和许可证:
+
+```powershell
+bb-mediamtx --copy --rid linux-arm64 --output .\publish --force
+```
+
+## 缓存和故障排查
+
+CLI 固定使用 MediaMTX `1.21.4`,缓存位于本机应用数据目录下的 `BootstrapBlazor\mediamtx\v1.21.4\`,构建和发布共用。下载通过 GitHub 发布 API 获取资源,校验 SHA-256 后只提取可执行文件和许可证,不使用压缩包中的 `mediamtx.yml`。有效缓存会校验后复用;下载进度在可获取文件大小时显示百分比,否则显示已下载字节数。
+
+`--download --rid all` 逐个平台处理,某个平台失败会输出警告并继续;其他模式处理指定或本机平台。参数、下载、校验、复制失败或取消时 CLI 输出警告,但仍以成功状态退出,以免阻断宿主构建或发布。因此不能只依据退出码判断是否部署成功,应检查警告及目标文件。
+
+离线构建前需在有网络时准备目标 RID 的缓存,并提前安装 CLI。若复制时提示缓存缺失或损坏,先用相同 RID 执行 `--download`。如需更新已经存在的输出文件,复制时添加 `--force`;它不强制从 GitHub 重新下载。
+
+在 Linux/macOS 上安装时会设置可执行权限;从 Windows 跨平台复制后,需在目标机器上设置执行权限。`--force` 不能绕过文件占用或权限限制。
## 宿主构建与发布
-- 通过 GitHub 发布 API 选择资源,验证 SHA-256 后只解压可执行文件和许可证,不使用压缩包内的 `mediamtx.yml`。
-- CLI 不读取或修改工程,不创建或更新工具清单,不生成、导入、迁移或清理构建规则和 `.targets` 文件。
-- 构建、发布调用由宿主维护:先执行 `dotnet tool restore` 还原根目录 `dotnet-tools.json` 中的 CLI,再在 `TargetDir`、`PublishDir` 中执行 `dotnet bb-mediamtx`;跨平台传入 `--rid`。普通 NuGet restore 不会自动还原 .NET 本地工具,也不下载 MediaMTX。
-- 默认先检查当前目录的 `mediamtx-tools\`:可执行文件和许可证都存在时立即结束,不读取文件内容、不校验缓存、不下载或覆盖。缺少文件时只补齐缺失文件,已有文件保持不变。`--force` 跳过输出存在性判断,校验或准备缓存后覆盖两个输出文件,用于升级或修复;有效缓存仍可复用,不强制重新下载。
-- 默认缓存位于本机应用数据目录的 `BootstrapBlazor\mediamtx\v\`,构建和发布共用。输出缺文件或指定 `--force` 时检查缓存;缓存有效时校验并复用,不访问 GitHub,缓存缺失、记录损坏或校验失败时才下载。按缓存项加锁,临时解压并在完成后写入安装记录;损坏的 JSON 记录会先输出诊断,不静默跳过。
-- 宿主的 `dotnet publish --no-build` 仍可通过 Publish Target 调用 CLI;单文件发布时工具仍作为外部文件保留。这不是 CLI 的 `publish` 子命令。
-- 默认 MediaMTX 版本和缓存位置由 CLI 固定,输出位置由工作目录决定。升级默认版本时更新 CLI 包,并在已有输出目录执行 `--force`,否则默认存在性检查会保留旧工具。
-- 使用 `dotnet tool restore --add-source` 添加私有或本地 CLI 包源。工具包和清单由宿主提前准备,不由 CLI 生成。
-- 宿主应在实际构建、发布时调用 CLI,跳过 IDE 设计时构建;应用运行时不下载。输出缺文件或使用 `--force` 且缓存无效时会联网,下载、校验或还原失败通过非零退出码报告。`--force` 不绕过操作系统的权限和文件占用限制,必要时先停止使用该工具的应用。
-- 在 Linux/macOS 上安装时自动设置可执行权限。从 Windows 跨平台发布后,需要在目标机器上设置执行权限。
+CLI 不读取或修改工程,不创建或更新工具清单,也不生成构建规则或 `.targets` 文件。宿主负责还原工具,并在构建或发布后调用 CLI;应用仍需引用 `BootstrapBlazor.MediaMtx` 并调用 `AddMediaMtxService()`。
-CI 使用提交的工具清单和宿主维护的调用规则:
+例如先发布,再从缓存复制目标平台的工具:
```powershell
-dotnet publish .\MyApp.csproj -r linux-x64 --self-contained false
+dotnet publish .\MyApp.csproj -r linux-x64 --self-contained false --output .\publish
+dotnet bb-mediamtx --download --rid linux-x64
+dotnet bb-mediamtx --copy --rid linux-x64 --output .\publish
```
-离线构建需要预先准备 CLI 包,并在有网络时于空的输出目录执行 `bb-mediamtx` 或 `bb-mediamtx --rid ` 预热默认缓存,避免已有输出直接跳过准备。输出缺文件时,有效缓存不访问 GitHub;缓存无效会尝试下载,下载失败通过非零退出码报告。
+从 MSBuild 调用时,若 `MediaMtxRidArgument` 只包含 RID 值,可使用 `--rid "$(MediaMtxRidArgument)"`;属性为空时使用本机 RID。Build 和 Publish 输出目录需通过 `--output` 显式指定,例如 `--output "$([MSBuild]::EnsureTrailingSlash('$(TargetDir)'))."` 或 `--output "$([MSBuild]::EnsureTrailingSlash('$(PublishDir)'))."`。末尾的 `.` 可避免 Windows 目录末尾反斜杠转义结束引号。宿主维护的构建规则应跳过 IDE 设计时构建。
+
+`dotnet publish --no-build` 仍可通过宿主的 Publish Target 调用 CLI;单文件发布时工具仍作为外部文件保留。升级 CLI 固定的 MediaMTX 版本后,已有输出文件不会自动覆盖,应使用 `--force`。
## 源码开发
-源码开发时先手动打包 CLI,并通过 `dotnet tool restore --tool-manifest .\dotnet-tools.json --add-source <本地包目录>` 还原工具。CLI 不向宿主工程添加打包或包源配置。全局安装本地预览包时仍需 `--prerelease`:
+源码开发时先手动打包 CLI,并通过 `dotnet tool restore --tool-manifest .\dotnet-tools.json --add-source <本地包目录>` 还原工具。全局安装本地预览包时可使用:
```powershell
dotnet tool install -g BootstrapBlazor.MediaMtx.Cli --prerelease --add-source <本地包目录>