Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(build): 随 Windows 制品携带媒体工具与对应源码

longmeidao841d0e86126f
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 59598f742..613b6265a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -14,9 +14,32 @@ env:
PYTHONIOENCODING: "utf-8"
jobs:
+ ffmpeg:
+ name: Windows FFmpeg 与对应源码
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7
+ - name: 安装交叉编译工具
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y build-essential gcc-mingw-w64-x86-64-posix mingw-w64-x86-64-dev nasm pkg-config python3 clang ca-certificates curl xz-utils
+ - name: 构建固定版本媒体工具
+ run: bash scripts/build_ffmpeg_windows.sh build/ffmpeg-windows
+ - name: 构建固定版本索引修复工具
+ run: bash scripts/build_untrunc_windows.sh build/untrunc-windows
+ - uses: actions/upload-artifact@v7
+ with:
+ name: ffmpeg-windows
+ path: build/ffmpeg-windows/
+ - uses: actions/upload-artifact@v7
+ with:
+ name: untrunc-windows
+ path: build/untrunc-windows/
+
windows:
name: Windows x64 独立测试包
runs-on: windows-latest
+ needs: ffmpeg
outputs:
version: ${{ steps.version.outputs.version }}
steps:
@@ -58,6 +81,14 @@ jobs:
- name: 获取并校验 cloudflared 旁路文件
shell: pwsh
run: '& ./scripts/fetch_cloudflared.ps1 -OutputPath "$env:RUNNER_TEMP/cloudflared.exe"'
+ - uses: actions/download-artifact@v8
+ with:
+ name: ffmpeg-windows
+ path: ${{ runner.temp }}/ffmpeg-build
+ - uses: actions/download-artifact@v8
+ with:
+ name: untrunc-windows
+ path: ${{ runner.temp }}/untrunc-build
- name: 准备 Inno Setup
shell: pwsh
run: |
@@ -70,13 +101,15 @@ jobs:
run: '& ./scripts/test.ps1 -Scope packaging -Focus test_desktop_installer'
- name: 构建独立目录包与安装包
shell: pwsh
- run: '& ./scripts/build_windows.ps1 -Installer -CloudflaredPath "$env:RUNNER_TEMP/cloudflared.exe"'
+ run: '& ./scripts/build_windows.ps1 -Installer -CloudflaredPath "$env:RUNNER_TEMP/cloudflared.exe" -FFmpegPath "$env:RUNNER_TEMP/ffmpeg-build/ffmpeg" -UntruncPath "$env:RUNNER_TEMP/untrunc-build/untrunc"'
- name: 压缩完整程序目录
shell: pwsh
run: |
New-Item -ItemType Directory -Path release | Out-Null
Compress-Archive -Path dist/Peach -DestinationPath 'release/Peach-${{ steps.version.outputs.version }}-windows-x64.zip'
Copy-Item 'dist/Peach-${{ steps.version.outputs.version }}-windows-x64-setup.exe' release/
+ Copy-Item dist/ffmpeg-corresponding-source.zip release/
+ Copy-Item dist/untrunc-corresponding-source.zip release/
Copy-Item scripts/smoke_desktop.py release/smoke_desktop.py
Copy-Item scripts/smoke_update_tasks.py release/smoke_update_tasks.py
python scripts/changelog.py --notes '${{ steps.version.outputs.version }}' --to release/RELEASE_NOTES.md
diff --git a/README.en.md b/README.en.md
index f2726875e..32e2dffda 100644
--- a/README.en.md
+++ b/README.en.md
@@ -112,11 +112,11 @@ Windows standalone builds can check for and download updates under **应用与
Downloading an update leaves tasks running. Installing an update saves progress and pauses scraping and preview generation; collection requests made during installation wait for it to finish. After installation finishes or is cancelled, a running Peach service resumes the tasks automatically. If Peach has exited, it resumes unfinished library metadata, local previews, timeline thumbnails and cover tasks on the next launch, reusing completed results. Turning thumbnail collection off explicitly keeps it stopped.
-The test package is not code-signed yet. If Windows says "Windows protected your PC", make sure the file came from this project's Releases, then choose "More info → Run anyway". Transcoding and thumbnails need FFmpeg; without it you can still browse and play MP4 and WebM. See [Windows test build](docs/TESTING_DESKTOP.md) for how to install it.
+Both the Windows installer and portable ZIP include FFmpeg, ffprobe and untrunc for transcoding, thumbnails and MP4 index recovery. Corresponding source is available in the same Release; the tools directory contains licenses and build notes. See [Windows test build](docs/TESTING_DESKTOP.md). The test package is not code-signed yet. If Windows says "Windows protected your PC", make sure the file came from this project's Releases, then choose "More info → Run anyway".
On Windows, the tray runs independently. Closing the Codex, Claude, or terminal session that started it keeps Peach running. Peach attempts to recover after an unexpected tray exit, up to three times within five minutes. Choosing “Quit Peach” keeps it closed. Exit reasons and recovery results are recorded in `tray-lifecycle.log` in the logs folder.
-Startup error dialogs show where a diagnostic report was saved. While Peach is running, choose “Export diagnostic report” in the tray menu or “Download diagnostic report” on the diagnostics page to collect a redacted ZIP for feedback.
+Startup error dialogs show where a diagnostic report was saved. While Peach is running, choose “Export diagnostic report” in the tray menu or “Download diagnostic report” on the diagnostics page to collect a redacted ZIP for feedback. The tray export dialog can open the report folder, open the file, or close.
### Run from source (Windows, macOS)
diff --git a/README.md b/README.md
index ee39d8b1f..87614d9df 100644
--- a/README.md
+++ b/README.md
@@ -111,11 +111,11 @@ Windows 独立包可在配置页「应用与维护」检查并下载更新;下
下载更新不会停止任务。应用内重启安装和安装包覆盖安装会保存采集进度、暂停刮削与抽帧;安装期间发起的采集任务会等待安装完成。安装完成或取消后,仍在运行的 Peach 会自动续跑;如果 Peach 已退出,则在下次启动时恢复未完成的馆藏资料、本地预览、时间轴缩略图和封面任务,复用已完成结果。主动关闭缩略图采集则不恢复。
-测试包还没有代码签名。Windows 提示「已保护你的电脑」时,确认文件来自本项目的 Release,再点「更多信息 → 仍要运行」。转码和缩略图要用到 FFmpeg,没装也能浏览和播放 MP4、WebM,安装方法见 [Windows 测试版](docs/TESTING_DESKTOP.md)。
+Windows 安装包和免安装包均携带 FFmpeg、ffprobe、untrunc,转码、缩略图和缺索引 MP4 修复可直接使用。对应源码随同一 Release 提供,工具目录包含许可证和构建说明,见 [Windows 测试版](docs/TESTING_DESKTOP.md)。测试包还没有代码签名。Windows 提示「已保护你的电脑」时,确认文件来自本项目的 Release,再点「更多信息 → 仍要运行」。
Windows 托盘独立运行,关闭启动它的 Codex、Claude 或终端不会退出 Peach。托盘异常退出后会自动尝试恢复;5 分钟内最多恢复 3 次。主动选择「退出 Peach」会保持关闭。退出原因和恢复结果可在日志目录的 `tray-lifecycle.log` 中查看。
-启动失败弹窗会给出诊断报告位置。程序能运行时,可从托盘「导出诊断报告」或系统诊断页「下载诊断报告」取得脱敏 ZIP,用于问题反馈。
+启动失败弹窗会给出诊断报告位置。程序能运行时,可从托盘「导出诊断报告」或系统诊断页「下载诊断报告」取得脱敏 ZIP,用于问题反馈。托盘导出完成后可打开报告所在目录、打开文件或关闭提示。
### 从源码运行(Windows、macOS)
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 73653efc9..c1ffc091c 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -460,7 +460,7 @@ A 盘垃圾隔离使用短名称 `peach-purge-<32 位 UUID>.peach-quarantine`,
| 已确认厂牌的目录归位 | Javinizer-Go v1.5.2 organizer(MIT)只作冲突预检、模板化目录和回滚边界的协议参考,不调用它,不让它持有 Peach ledger | `rehome_unknown_jav.py` 只消费人工确认映射;先出逐文件 CSV,拒绝扁平化重名与厂牌冲突,SQLite 备份后移动文件并同步 Peach 路径/实体 provenance |
| FC2 目录元数据与跨号证据 | 已缓存的 fc2cmadb Inertia `article`/评论;Javinizer-Go v1.5.2 的 FC2 解析器(MIT)只作商品页字段边界参考 | 旧文章仍有标题、原始标签、日期、时长、卖家、FC2 CDN 封面与 `comments`(2026-08-31 登录态实测);无歧义标签译成现有词表,标题/标签进 `/review`,`w1200` 封面过尺寸与解码门槛落生成产物;pair、合集/分片保护、hash/时长/尺寸佐证、库外 evidence、健康统计与复核归 Peach,不依赖 FC2-Leak-Detector/JavSP,镜像候选不直写 ledger |
| 缺索引 MP4 重建 | untrunc(anthwlock,GPL-2.0,用户自行解压到 `<数据根>/tools/untrunc/`,也认 `PEACH_UNTRUNC` 与 PATH),`-n -s -dst` 借一部同编码器的完整片子当参照切 `mdat`;不随 Peach 分发,「运行信息」给下载入口 | `src/peach/mp4recover.py` 挑参照(同目录文件名最近的先试,最多 4 部)、验收(解码错误 ≤3 行、音视频时长差 ≤5%)、换回原路径并把坏原件改名成同目录的 `.文件名.peach-original`;缺整个 `moov` 的片子哪里都打不开,所以结果替换原文件,不像缺 `ctts` 那样另存头。实测见 [取证](SOURCING.md#媒体与关注实测) |
-| 媒体探测/转码 | Peach 管理的 FFmpeg/ffprobe(Windows 实测 9.0.1 full build 的 CUDA/NVDEC、`scale_cuda` 与 NVENC,二进制启用 GPL/version3);CI 用 `FedericoCarboni/setup-ffmpeg@v3`(MIT)固定 9.0.1,从 GyanD/codexffmpeg 的精确 release 资产下载,不走访问 Gyan 易失端点的默认 `release`([取证](SOURCING.md#依赖与工具实测)) | 容器与编码分别检查:MP4/M4V 的 H.264 8-bit 加兼容音轨直出,其余容器里的 H.264 8-bit 只换 MP4 封装;其余 Windows 输入依次 CUDA→NVENC、软件解码→NVENC、`libx264`,macOS 封装复制或软件转码 |
+| 媒体探测/转码 | Windows 独立包从固定源码交叉编译 FFmpeg 9.0.2、x264 与 nv-codec-headers,按 GPL-3.0-or-later 分发;版本、来源和哈希见 `scripts/ffmpeg-sources.json`。工具与完整对应源码一起构建,安装包和免安装 ZIP 共用经校验的 `tools/ffmpeg`。源码与 CI 媒体测试仍可使用 PATH 工具([取证](SOURCING.md#依赖与工具实测)) | 容器与编码分别检查:MP4/M4V 的 H.264 8-bit 加兼容音轨直出,其余容器里的 H.264 8-bit 只换 MP4 封装;其余 Windows 输入依次 CUDA→NVENC、软件解码→NVENC、`libx264`,macOS 封装复制或软件转码 |
| HTML5/HLS/DASH 播放 | Video.js 8.24.2 + 内置 VHS(Apache-2.0,本地固定版本) | 流方案、授权、稳定时长、回退顺序和统计面板;详情不兼容片源复用 HlsSegmentService 与 FFmpeg 按六秒编码 H.264/AAC,独立缓存、绝对时间轴及会话取消,无整片预转码 |
| 播放器设置与影院布局 | Video.js 8.24.2 的 `playbackRate`、既有 QualityLevel、原生 tooltip 与控制栏插槽;YouTube `e937390a` 实际 DOM/CSS/JS 给几何、状态、动画和图形证据 | 在现有 DOM 上组合氛围模式、倍速、真实清晰度和影院模式:59 px 两排控制栏、40→111 px 横向音量、4→6 px 进度、右侧共享胶囊、整行悬停的 274 px 设置菜单、视口级全屏;普通视图 `contain`,全屏 `cover`(接受非等比片源的边缘裁切)。全屏判定同时看 Video.js/原生类、`isFullscreen()` 同步的 `data-peach-fullscreen` 与 `body.vjs-full-window`;浏览器专用伪类放进 forgiving `:is(...)` 或拆开写,免得未知伪类废掉整组。设置项、选中勾、菜单箭头、中央 bezel 与 loading 只 vendoring 锁定版本的 SVG path/spinner,音量 hover 与滑轨中心沿用上游外层伪元素与 50% 几何,tooltip 只补层级与越界可见;不复制控制逻辑、不迁 Video.js 10 Menu、不引重复质量选择的插件 |
| 播放器时刻预览 | Video.js 原生进度控件 + Peach 的 `/timeline?id=&s=`(10×10 接触印相),取不到时退到 `/poster?id=&c=0…8` 九宫格切片 | `peach.timeline_sheets` 按每 10 或 30 秒一帧预铺,只覆盖 `location='local'`(网盘每抽一帧都回源,[流量实测](SOURCING.md#媒体与关注实测));其余退回只给近似时刻的九宫格。抽帧与拼图共用 `peach.frame_capture`。`videojs-vtt-thumbnails`/`videojs-sprite-thumbnails` 要另建 sprite/VTT 契约与运行时依赖,格子换算在 Peach 是一行整除,不引入 |
diff --git a/docs/TESTING_DESKTOP.md b/docs/TESTING_DESKTOP.md
index 4f263fd15..790e57821 100644
--- a/docs/TESTING_DESKTOP.md
+++ b/docs/TESTING_DESKTOP.md
@@ -50,11 +50,15 @@ Windows 第一次询问防火墙权限时,只勾选「专用网络」。
## 播放与 FFmpeg
-浏览器能直接播放的格式(例如常见的 MP4)不需要额外软件。转码、抽帧和缩略图需要 FFmpeg 与 ffprobe,测试包不附带,需要自己安装:
+安装包和免安装 ZIP 均包含 FFmpeg 与 ffprobe,位于程序目录的 `tools\ffmpeg\bin`。转码、媒体信息探测与缩略图可直接使用,无需安装系统工具或设置 PATH。应用更新同时更新随包工具。
-1. 下载 FFmpeg(配置页「运行信息」缺少它时会给出下载入口)。
-2. 把 `ffmpeg.exe` 和 `ffprobe.exe` 加入 PATH,或放进数据目录下的 `tools\ffmpeg\bin`。
-3. 从托盘退出 Peach,再重新打开。
+缺索引 MP4 修复使用随包的 `tools\untrunc\untrunc.exe`,需要同编码参数的完整片作为参照。该工具与其兼容的 FFmpeg 库独立构建,按 GPL-2.0-or-later 分发;完整对应源码制品为同一 Release 中的 `untrunc-corresponding-source.zip`。显式 `PEACH_UNTRUNC` 优先于随包工具,其后查数据目录与 PATH。
+
+工具以独立进程调用,按 GPL-3.0-or-later 分发;工具目录包含许可证、构建配置、来源清单和 SHA-256。完整对应源码制品 `ffmpeg-corresponding-source.zip` 与应用放在同一个 Release,包含 FFmpeg、x264、nv-codec-headers 的固定源码和构建脚本。发行构建会校验工具及对应源码,任何一项缺失或哈希不符都停止打包。
+
+源码运行可将 FFmpeg、ffprobe 加入 PATH,或放在数据目录的 `tools\ffmpeg\bin`。显式指定的 `PEACH_FFMPEG`、`PEACH_FFPROBE` 优先;独立包随后使用随包工具,再查数据目录和 PATH。
+
+已在系统安装媒体工具时,可运行 [`import_windows_media_tools.cmd`](../scripts/import_windows_media_tools.cmd),它调用同目录 PowerShell 脚本检测 WinGet、Scoop、Chocolatey、PATH 和下载目录,将工具及同目录 DLL 放入 Peach 的数据目录,替换文件时保留备份。没有检测到已解压工具时,可识别下载目录中的 Gyan `ffmpeg-9.0.2-essentials_build.zip`,校验固定 SHA-256 后解压接入。脚本不修改系统 PATH 或馆藏账本;完成后刷新配置页。
## 从外网临时访问
diff --git a/scripts/build_windows.ps1 b/scripts/build_windows.ps1
index 330c79088..e4a253522 100644
--- a/scripts/build_windows.ps1
+++ b/scripts/build_windows.ps1
@@ -3,7 +3,9 @@
[switch]$Standalone,
# 在独立目录包之上再编一个 Inno Setup 安装包,放在输出目录的上一层。
[switch]$Installer,
- [string]$CloudflaredPath = ''
+ [string]$CloudflaredPath = '',
+ [string]$FFmpegPath = '',
+ [string]$UntruncPath = ''
)
$ErrorActionPreference = 'Stop'
@@ -87,6 +89,18 @@ $CloudflaredSource = $null
$CloudflaredManifest = $null
$CloudflaredHash = $null
if ($Standalone) {
+ if (-not $FFmpegPath) { $FFmpegPath = $env:PEACH_FFMPEG_BUILD }
+ if (-not $FFmpegPath) { $FFmpegPath = Join-Path $ProjectRoot 'build\ffmpeg-windows\ffmpeg' }
+ & $Python -X utf8 (Join-Path $PSScriptRoot 'media_tool_bundle.py') --source $FFmpegPath --validate-only
+ if ($LASTEXITCODE -ne 0) {
+ throw 'Standalone build requires verified FFmpeg tools and corresponding source. Run scripts/build_ffmpeg_windows.sh first or pass -FFmpegPath.'
+ }
+ if (-not $UntruncPath) { $UntruncPath = $env:PEACH_UNTRUNC_BUILD }
+ if (-not $UntruncPath) { $UntruncPath = Join-Path $ProjectRoot 'build\untrunc-windows\untrunc' }
+ & $Python -X utf8 (Join-Path $PSScriptRoot 'media_tool_bundle.py') --tool untrunc --source $UntruncPath --validate-only
+ if ($LASTEXITCODE -ne 0) {
+ throw 'Standalone build requires verified untrunc and corresponding source. Run scripts/build_untrunc_windows.sh first or pass -UntruncPath.'
+ }
$CloudflaredCandidates = @()
if ($CloudflaredPath) { $CloudflaredCandidates += $CloudflaredPath }
if ($env:PEACH_CLOUDFLARED_BUILD) { $CloudflaredCandidates += $env:PEACH_CLOUDFLARED_BUILD }
@@ -126,6 +140,20 @@ if ($Standalone) {
Copy-Item -LiteralPath $CloudflaredSource -Destination (Join-Path $OutputPath 'cloudflared.exe') -Force
$CloudflaredManifest | Add-Member -NotePropertyName packaged_sha256 -NotePropertyValue $CloudflaredHash -Force
$CloudflaredManifest | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $OutputPath 'cloudflared-manifest.json') -Encoding utf8
+ $PackagedFFmpeg = [IO.Path]::GetFullPath((Join-Path $OutputPath 'tools\ffmpeg'))
+ if (-not $PackagedFFmpeg.StartsWith($OutputPath.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase)) {
+ throw 'FFmpeg packaging destination must stay inside the application output directory.'
+ }
+ if (Test-Path -LiteralPath $PackagedFFmpeg) { Remove-Item -LiteralPath $PackagedFFmpeg -Recurse -Force }
+ & $Python -X utf8 (Join-Path $PSScriptRoot 'media_tool_bundle.py') --source $FFmpegPath --destination $PackagedFFmpeg
+ if ($LASTEXITCODE -ne 0) { throw 'FFmpeg packaging failed.' }
+ $PackagedUntrunc = [IO.Path]::GetFullPath((Join-Path $OutputPath 'tools\untrunc'))
+ if (-not $PackagedUntrunc.StartsWith($OutputPath.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase)) {
+ throw 'untrunc packaging destination must stay inside the application output directory.'
+ }
+ if (Test-Path -LiteralPath $PackagedUntrunc) { Remove-Item -LiteralPath $PackagedUntrunc -Recurse -Force }
+ & $Python -X utf8 (Join-Path $PSScriptRoot 'media_tool_bundle.py') --tool untrunc --source $UntruncPath --destination $PackagedUntrunc
+ if ($LASTEXITCODE -ne 0) { throw 'untrunc packaging failed.' }
}
# 工作目录只服务这一次构建:`--clean` 已让下一次不复用它,留着只是几十 MB 的中间产物。
diff --git a/scripts/import_windows_media_tools.cmd b/scripts/import_windows_media_tools.cmd
new file mode 100644
index 000000000..f96aabaca
--- /dev/null
+++ b/scripts/import_windows_media_tools.cmd
@@ -0,0 +1,4 @@
+@echo off
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0import_windows_media_tools.ps1"
+echo.
+pause
diff --git a/scripts/import_windows_media_tools.ps1 b/scripts/import_windows_media_tools.ps1
new file mode 100644
index 000000000..51f845d90
--- /dev/null
+++ b/scripts/import_windows_media_tools.ps1
@@ -0,0 +1,138 @@
+param(
+ [string]$DataRoot = '',
+ [string[]]$SearchRoots = @(),
+ [string]$ArchivePath = ''
+)
+
+$ErrorActionPreference = 'Stop'
+if (-not $DataRoot) {
+ $DataRoot = Join-Path $env:LOCALAPPDATA 'Peach\peach-data'
+ $LocationRecord = Join-Path $DataRoot 'state\data-root.txt'
+ if (Test-Path -LiteralPath $LocationRecord -PathType Leaf) {
+ $SelectedRoot = (Get-Content -LiteralPath $LocationRecord -Raw -Encoding utf8).Trim()
+ if ($SelectedRoot -and (Test-Path -LiteralPath $SelectedRoot -PathType Container)) {
+ $DataRoot = $SelectedRoot
+ }
+ }
+}
+$DataRoot = [IO.Path]::GetFullPath($DataRoot)
+if (-not (Test-Path -LiteralPath $DataRoot -PathType Container)) {
+ throw "Peach data directory not found: $DataRoot. Pass -DataRoot with the directory shown in Peach Configuration."
+}
+
+function Find-PeachBinary([string]$Name, [string[]]$Roots) {
+ foreach ($Root in $Roots) {
+ if (-not $Root -or -not (Test-Path -LiteralPath $Root -PathType Container)) { continue }
+ $Matches = @(Get-ChildItem -LiteralPath $Root -Filter $Name -File -Recurse -Depth 6 -ErrorAction SilentlyContinue |
+ Sort-Object LastWriteTimeUtc -Descending)
+ foreach ($Match in $Matches) {
+ # Chocolatey bin contains launch shims; select the tools in lib instead.
+ if ($Match.FullName -match '[\\/]chocolatey[\\/]bin[\\/]') { continue }
+ $RealPath = $Match.FullName
+ if ($Match.LinkType -and $Match.Target) {
+ $RealPath = [string]@($Match.Target)[0]
+ if (-not [IO.Path]::IsPathRooted($RealPath)) { $RealPath = Join-Path $Match.DirectoryName $RealPath }
+ }
+ if (-not (Test-Path -LiteralPath $RealPath -PathType Leaf)) { continue }
+ $Stream = [IO.File]::OpenRead($RealPath)
+ try { $IsExecutable = ($Stream.ReadByte() -eq 77 -and $Stream.ReadByte() -eq 90) }
+ finally { $Stream.Dispose() }
+ if ($IsExecutable) { return [IO.Path]::GetFullPath($RealPath) }
+ }
+ }
+ return $null
+}
+
+$Roots = @($SearchRoots)
+if ($Roots.Count -eq 0) {
+ $Roots = @(
+ "$env:LOCALAPPDATA\Microsoft\WinGet\Packages",
+ "$env:ProgramFiles\WinGet\Packages",
+ "$env:USERPROFILE\scoop\apps\ffmpeg\current",
+ "$env:USERPROFILE\scoop\apps\ffmpeg-essentials\current",
+ "$env:ProgramData\scoop\apps\ffmpeg\current",
+ "$env:ProgramData\chocolatey\lib\ffmpeg",
+ "$env:ProgramData\chocolatey\lib\ffmpeg-full",
+ "$env:ProgramFiles\ffmpeg", "$env:LOCALAPPDATA\Programs\ffmpeg", 'C:\ffmpeg',
+ "$env:USERPROFILE\Downloads"
+ )
+ foreach ($ToolName in @('ffmpeg.exe', 'ffprobe.exe', 'untrunc.exe')) {
+ $Command = Get-Command $ToolName -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($Command) { $Roots += Split-Path -Parent $Command.Source }
+ }
+}
+
+function Install-PeachBinary([string]$Source, [string]$RelativeDirectory, [string[]]$Names) {
+ $SourceDirectory = Split-Path -Parent $Source
+ $TargetDirectory = Join-Path (Join-Path $DataRoot 'tools') $RelativeDirectory
+ $Copies = @()
+ foreach ($Name in $Names) {
+ $Candidate = Join-Path $SourceDirectory $Name
+ if (-not (Test-Path -LiteralPath $Candidate -PathType Leaf)) { throw "Companion tool not found: $Candidate" }
+ $Copies += Get-Item -LiteralPath $Candidate
+ }
+ $Copies += @(Get-ChildItem -LiteralPath $SourceDirectory -Filter '*.dll' -File -ErrorAction SilentlyContinue)
+ New-Item -ItemType Directory -Path $TargetDirectory -Force | Out-Null
+ $BackupDirectory = Join-Path $DataRoot ('tools\import-backup-' + [guid]::NewGuid().ToString('N'))
+ foreach ($File in $Copies) {
+ $Target = Join-Path $TargetDirectory $File.Name
+ if ([IO.Path]::GetFullPath($File.FullName) -eq [IO.Path]::GetFullPath($Target)) { continue }
+ if (Test-Path -LiteralPath $Target -PathType Leaf) {
+ if ((Get-FileHash -LiteralPath $Target).Hash -eq (Get-FileHash -LiteralPath $File.FullName).Hash) { continue }
+ New-Item -ItemType Directory -Path $BackupDirectory -Force | Out-Null
+ Copy-Item -LiteralPath $Target -Destination (Join-Path $BackupDirectory $File.Name)
+ }
+ Copy-Item -LiteralPath $File.FullName -Destination $Target -Force
+ if ((Get-FileHash -LiteralPath $Target).Hash -ne (Get-FileHash -LiteralPath $File.FullName).Hash) {
+ throw "File copy verification failed: $Target"
+ }
+ }
+ Write-Output "READY: $TargetDirectory"
+}
+
+Write-Output "Peach data: $DataRoot"
+$ExtractionRoot = $null
+try {
+ $FFmpeg = Find-PeachBinary 'ffmpeg.exe' $Roots
+ if (-not $FFmpeg) {
+ if (-not $ArchivePath) {
+ foreach ($Folder in @("$env:USERPROFILE\Downloads", $PSScriptRoot, (Split-Path -Parent $PSScriptRoot))) {
+ $CandidateArchive = Join-Path $Folder 'ffmpeg-9.0.2-essentials_build.zip'
+ if (Test-Path -LiteralPath $CandidateArchive -PathType Leaf) { $ArchivePath = $CandidateArchive; break }
+ }
+ }
+ if ($ArchivePath) {
+ $ExpectedHash = '60f467265b1e312373dbcd92200c2618a74850f98d3d078e94296bb3fa2047ba'
+ if ((Get-FileHash -LiteralPath $ArchivePath -Algorithm SHA256).Hash.ToLowerInvariant() -ne $ExpectedHash) {
+ throw 'The FFmpeg ZIP does not match the verified Gyan 9.0.2 essentials download. Download the exact linked file again.'
+ }
+ $ExtractionRoot = Join-Path ([IO.Path]::GetTempPath()) ('peach-ffmpeg-import-' + [guid]::NewGuid().ToString('N'))
+ Expand-Archive -LiteralPath $ArchivePath -DestinationPath $ExtractionRoot
+ $FFmpeg = Find-PeachBinary 'ffmpeg.exe' @($ExtractionRoot)
+ }
+ }
+ if ($FFmpeg) {
+ Write-Output "Found FFmpeg: $FFmpeg"
+ Install-PeachBinary $FFmpeg 'ffmpeg\bin' @('ffmpeg.exe', 'ffprobe.exe')
+ } else {
+ Write-Output 'NOT FOUND: ffmpeg.exe. Put ffmpeg-9.0.2-essentials_build.zip in Downloads, then run this script again.'
+ }
+ $Untrunc = Find-PeachBinary 'untrunc.exe' $Roots
+ if ($Untrunc) {
+ Write-Output "Found untrunc: $Untrunc"
+ Install-PeachBinary $Untrunc 'untrunc' @('untrunc.exe')
+ } else {
+ Write-Output 'NOT FOUND: untrunc.exe. This does not affect FFmpeg detection.'
+ }
+ Write-Output 'Refresh Peach Configuration. If a running task still reports missing tools, restart Peach.'
+ if (-not $FFmpeg) { exit 1 }
+} finally {
+ if ($ExtractionRoot -and (Test-Path -LiteralPath $ExtractionRoot)) {
+ $ResolvedExtraction = [IO.Path]::GetFullPath($ExtractionRoot)
+ $ResolvedTemporary = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\'
+ if (-not $ResolvedExtraction.StartsWith($ResolvedTemporary, [StringComparison]::OrdinalIgnoreCase)) {
+ throw 'Temporary extraction directory is outside TEMP; cleanup refused.'
+ }
+ Remove-Item -LiteralPath $ResolvedExtraction -Recurse -Force
+ }
+}
diff --git a/scripts/media_tool_bundle.py b/scripts/media_tool_bundle.py
new file mode 100644
index 000000000..2b73f14be
--- /dev/null
+++ b/scripts/media_tool_bundle.py
@@ -0,0 +1,93 @@
+"""校验并复制 Windows 媒体工具及其对应源码制品。"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from pathlib import Path, PurePosixPath
+import re
+import shutil
+
+
+REQUIRED_FILES = {"bin/ffmpeg.exe", "bin/ffprobe.exe", "LICENSE.txt", "NOTICE.md", "buildconf.txt"}
+POLICIES = {
+ "ffmpeg": (REQUIRED_FILES, {"ffmpeg", "x264", "nv-codec-headers"}, "GPL-3.0-or-later"),
+ "untrunc": ({"untrunc.exe", "LICENSE.txt", "NOTICE.md", "buildconf.txt"},
+ {"untrunc", "ffmpeg"}, "GPL-2.0-or-later"),
+}
+
+
+def digest(path: Path) -> str:
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def checked_file(root: Path, name: str, expected: str) -> Path:
+ relative = PurePosixPath(name)
+ if not name or "\\" in name or relative.is_absolute() or ".." in relative.parts or ":" in name:
+ raise ValueError(f"FFmpeg 制品路径无效:{name}")
+ target = root.joinpath(*relative.parts)
+ if not target.resolve().is_relative_to(root.resolve()) or target.is_symlink() or not target.is_file():
+ raise ValueError(f"FFmpeg 制品文件缺失或越界:{name}")
+ if not re.fullmatch(r"[0-9a-f]{64}", expected) or digest(target) != expected:
+ raise ValueError(f"FFmpeg SHA-256 mismatch: {name}")
+ return target
+
+
+def validate(root: Path, tool: str = "ffmpeg") -> tuple[dict, Path]:
+ """构建和制品验收共用;哈希不匹配时不复制任何文件。"""
+ manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
+ required, source_names, license_name = POLICIES[tool]
+ if manifest.get("license") != license_name or not manifest.get("version"):
+ raise ValueError("FFmpeg 清单缺少版本或 GPL 许可证声明")
+ files = manifest.get("files", {})
+ if not required.issubset(files):
+ raise ValueError("FFmpeg 清单缺少工具或分发材料")
+ actual = {path.relative_to(root).as_posix() for path in root.rglob("*") if path.is_file()}
+ if actual != set(files) | {"manifest.json"}:
+ raise ValueError("FFmpeg 目录与清单文件不一致")
+ for name, expected in files.items():
+ checked_file(root, name, expected)
+ sources = manifest.get("sources", [])
+ if {source.get("name") for source in sources} != source_names:
+ raise ValueError("FFmpeg 清单缺少完整源码来源")
+ for source in sources:
+ if (not source.get("revision") or not source.get("url", "").startswith("https://")
+ or not re.fullmatch(r"[0-9a-f]{64}", source.get("sha256", ""))):
+ raise ValueError("FFmpeg 源码来源缺少固定版本或哈希")
+ archive = manifest["source_archive"]
+ source_path = checked_file(root.parent, archive["name"], archive["sha256"])
+ return manifest, source_path
+
+
+def package(root: Path, destination: Path, tool: str = "ffmpeg") -> dict:
+ manifest, source_path = validate(root, tool)
+ if destination.exists():
+ raise ValueError(f"FFmpeg 目标目录必须不存在:{destination}")
+ shutil.copytree(root, destination)
+ output = destination.parents[2] / source_path.name
+ if output.resolve() != source_path.resolve():
+ shutil.copyfile(source_path, output)
+ return manifest
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source", required=True, type=Path)
+ parser.add_argument("--destination", type=Path)
+ parser.add_argument("--validate-only", action="store_true")
+ parser.add_argument("--tool", choices=tuple(POLICIES), default="ffmpeg")
+ args = parser.parse_args()
+ if args.validate_only:
+ manifest, _source = validate(args.source.resolve(), args.tool)
+ print(json.dumps({"version": manifest["version"], "verified": True}))
+ return 0
+ if args.destination is None:
+ parser.error("--destination is required unless --validate-only is set")
+ manifest = package(args.source.resolve(), args.destination.resolve(), args.tool)
+ print(json.dumps({"version": manifest["version"], "destination": str(args.destination)}, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/smoke_desktop.py b/scripts/smoke_desktop.py
index 71deeb636..6a93c0845 100644
--- a/scripts/smoke_desktop.py
+++ b/scripts/smoke_desktop.py
@@ -5,6 +5,7 @@ import argparse
from contextlib import contextmanager
import ctypes
from ctypes import wintypes
+import hashlib
import json
import http.cookiejar
import os
@@ -22,6 +23,62 @@ import urllib.parse
import uuid
+def assert_bundled_media_tools(application: Path) -> None:
+ """在没有系统媒体工具的机器上验证随包转码、探测和抽帧。"""
+ tools = application / "tools" / "ffmpeg"
+ manifest = json.loads((tools / "manifest.json").read_text(encoding="utf-8"))
+ assert manifest["license"] == "GPL-3.0-or-later"
+ for name, expected in manifest["files"].items():
+ path = tools / name
+ assert path.resolve().is_relative_to(tools.resolve()), name
+ with path.open("rb") as stream:
+ assert hashlib.file_digest(stream, "sha256").hexdigest() == expected, name
+ untrunc_root = application / "tools/untrunc"
+ repair_manifest = json.loads((untrunc_root / "manifest.json").read_text(encoding="utf-8"))
+ assert repair_manifest["license"] == "GPL-2.0-or-later"
+ for name, expected in repair_manifest["files"].items():
+ path = untrunc_root / name
+ assert path.resolve().is_relative_to(untrunc_root.resolve()), name
+ with path.open("rb") as stream:
+ assert hashlib.file_digest(stream, "sha256").hexdigest() == expected, name
+ # resources 是冻结资源的一部分,首次扫描可读到随版本附带的种子。
+ seed = json.loads((application / "_internal/resources/seed/entities.json").read_text(encoding="utf-8"))
+ assert seed["version"] and seed["entities"], "随包种子缺失"
+ ffmpeg, ffprobe = tools / "bin/ffmpeg.exe", tools / "bin/ffprobe.exe"
+ with tempfile.TemporaryDirectory(prefix="peach-media-smoke-") as directory:
+ root = Path(directory).resolve()
+ video, image = root / "sample.mp4", root / "frame.jpg"
+ for command in (
+ [str(ffmpeg), "-v", "error", "-f", "lavfi", "-i", "testsrc2=s=64x64:r=5",
+ "-t", "1", "-c:v", "libx264", "-pix_fmt", "yuv420p", str(video)],
+ [str(ffmpeg), "-v", "error", "-i", str(video), "-frames:v", "1", str(image)],
+ ):
+ result = subprocess.run(command, capture_output=True, timeout=30)
+ assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace")
+ result = subprocess.run([str(ffprobe), "-v", "error", "-show_streams", "-of", "json", str(video)],
+ capture_output=True, text=True, encoding="utf-8", timeout=15, check=True)
+ assert json.loads(result.stdout)["streams"][0]["codec_name"] == "h264"
+ assert image.stat().st_size > 0
+ # 合成片的 moov 位于 mdat 之后;移掉索引后用同编码参数的完整片重建。
+ payload = video.read_bytes()
+ offset = 0
+ while offset + 8 <= len(payload):
+ size = int.from_bytes(payload[offset:offset + 4], "big")
+ assert size >= 8, "合成 MP4 盒子长度无效"
+ if payload[offset + 4:offset + 8] == b"moov":
+ break
+ offset += size
+ assert offset < len(payload), "合成 MP4 缺少 moov"
+ broken, repaired = root / "broken.mp4", root / "repaired.mp4"
+ broken.write_bytes(payload[:offset])
+ result = subprocess.run([str(untrunc_root / "untrunc.exe"), "-n", "-s", "-dst", str(repaired),
+ str(video), str(broken)], capture_output=True, timeout=30)
+ assert repaired.is_file(), result.stderr.decode("utf-8", errors="replace")
+ result = subprocess.run([str(ffprobe), "-v", "error", "-show_streams", "-of", "json", str(repaired)],
+ capture_output=True, text=True, encoding="utf-8", timeout=15, check=True)
+ assert json.loads(result.stdout)["streams"][0]["codec_name"] == "h264"
+
+
@contextmanager
def smoke_directory(evidence_dir: Path):
"""失败时只保留本次临时运行的日志,不打包账本与配置。"""
@@ -293,6 +350,7 @@ def main() -> int:
parser.add_argument("--evidence-dir", type=Path, default=Path("smoke-evidence"))
args = parser.parse_args()
executable = args.executable.resolve(strict=True)
+ assert_bundled_media_tools(executable.parent)
evidence_dir = args.evidence_dir.resolve()
smoke_tray(executable, evidence_dir)
with smoke_directory(evidence_dir) as root:
@@ -340,6 +398,7 @@ def main() -> int:
assert response.status == 200, path
with opener.open(base + "/api/configuration", timeout=5) as response:
configuration = json.load(response)
+ assert not any(row["term"] in ("FFmpeg", "untrunc") for row in configuration["facts"]), configuration["facts"]
assert configuration['media_sources'][0]['location'] == '115'
assert_standalone_tunnel(configuration)
second = root / 'pikpak'
diff --git a/src/peach/ffmpeg.py b/src/peach/ffmpeg.py
index a792b799b..3de65337b 100644
--- a/src/peach/ffmpeg.py
+++ b/src/peach/ffmpeg.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import os
import shutil
+import sys
from dataclasses import dataclass
from pathlib import Path
@@ -13,7 +14,7 @@ class BinaryChoice:
class FFmpegResolver:
- """Resolve explicit, Peach-managed, or PATH binaries without backend coupling."""
+ """按显式配置、随包工具、数据目录与 PATH 查找媒体工具。"""
def __init__(self, managed_root: Path):
self.managed_root = managed_root
@@ -32,6 +33,11 @@ class FFmpegResolver:
if path.is_file():
return BinaryChoice(path.resolve(), "environment")
+ if getattr(sys, "frozen", False):
+ bundled = Path(sys.executable).parent / "tools" / "ffmpeg" / "bin" / f"{executable}{suffix}"
+ if bundled.is_file():
+ return BinaryChoice(bundled.resolve(), "peach-bundled")
+
managed = self.managed_root / "bin" / f"{executable}{suffix}"
if managed.is_file():
return BinaryChoice(managed.resolve(), "peach-managed")
diff --git a/tests/test_ffmpeg_bundle.py b/tests/test_ffmpeg_bundle.py
new file mode 100644
index 000000000..8388736ad
--- /dev/null
+++ b/tests/test_ffmpeg_bundle.py
@@ -0,0 +1,95 @@
+import json
+from pathlib import Path
+import tempfile
+import unittest
+
+from scripts import media_tool_bundle as ffmpeg_bundle
+
+
+class FFmpegBundleTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name).resolve()
+ self.source = self.root / "build" / "ffmpeg"
+ self.source.mkdir(parents=True)
+ self.manifest = {"version": "9.0.2", "license": "GPL-3.0-or-later", "files": {}}
+ for name in ffmpeg_bundle.REQUIRED_FILES:
+ path = self.source / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(name.encode())
+ self.manifest["files"][name] = ffmpeg_bundle.digest(path)
+ self.manifest["sources"] = [
+ {"name": name, "revision": "fixed", "url": f"https://example.org/{name}.tar.gz", "sha256": "1" * 64}
+ for name in ("ffmpeg", "x264", "nv-codec-headers")]
+ archive = self.source.parent / "ffmpeg-corresponding-source.zip"
+ archive.write_bytes(b"source fixture")
+ self.manifest["source_archive"] = {"name": archive.name, "sha256": ffmpeg_bundle.digest(archive)}
+ self.destination = self.root / "dist" / "Peach" / "tools" / "ffmpeg"
+ self.write_manifest()
+
+ def write_manifest(self):
+ (self.source / "manifest.json").write_text(json.dumps(self.manifest), encoding="utf-8")
+
+ def test_packages_verified_tools_not_ffplay_and_keeps_source_beside_application(self):
+ result = ffmpeg_bundle.package(self.source, self.destination)
+ self.assertEqual(result["version"], "9.0.2")
+ self.assertEqual((self.destination / "bin/ffmpeg.exe").read_bytes(), b"bin/ffmpeg.exe")
+ self.assertTrue((self.destination / "bin/ffprobe.exe").is_file())
+ self.assertFalse((self.destination / "bin/ffplay.exe").exists())
+ self.assertEqual((self.root / "dist/ffmpeg-corresponding-source.zip").read_bytes(), b"source fixture")
+
+ def test_rejects_corrupted_binary_without_copying(self):
+ (self.source / "bin/ffprobe.exe").write_bytes(b"corrupted")
+ with self.assertRaisesRegex(ValueError, "SHA-256 mismatch"):
+ ffmpeg_bundle.package(self.source, self.destination)
+ self.assertFalse(self.destination.exists())
+
+ def test_rejects_corrupted_or_missing_corresponding_source(self):
+ archive = self.source.parent / self.manifest["source_archive"]["name"]
+ for content in (b"corrupt", None):
+ if content is None:
+ archive.unlink()
+ else:
+ archive.write_bytes(content)
+ with self.assertRaises(ValueError):
+ ffmpeg_bundle.package(self.source, self.destination)
+ self.assertFalse(self.destination.exists())
+
+ def test_rejects_incomplete_sources_and_unlisted_files(self):
+ self.manifest["sources"].pop()
+ self.write_manifest()
+ with self.assertRaisesRegex(ValueError, "源码来源"):
+ ffmpeg_bundle.validate(self.source)
+ (self.source / "bin/ffplay.exe").write_bytes(b"unverified")
+ with self.assertRaisesRegex(ValueError, "目录与清单"):
+ ffmpeg_bundle.validate(self.source)
+
+ def test_rejects_source_archive_path_escape(self):
+ outside = self.root / "outside.zip"
+ outside.write_bytes(b"source fixture")
+ self.manifest["source_archive"]["name"] = "../outside.zip"
+ self.write_manifest()
+ with self.assertRaisesRegex(ValueError, "路径无效"):
+ ffmpeg_bundle.validate(self.source)
+
+ def test_rejects_stale_destination(self):
+ self.destination.mkdir(parents=True)
+ with self.assertRaisesRegex(ValueError, "必须不存在"):
+ ffmpeg_bundle.package(self.source, self.destination)
+
+ def test_untrunc_uses_the_same_integrity_gate_with_its_own_source_and_license(self):
+ self.manifest["license"] = "GPL-2.0-or-later"
+ (self.source / "bin/ffprobe.exe").unlink()
+ (self.source / "bin/ffmpeg.exe").unlink()
+ self.manifest["files"].pop("bin/ffmpeg.exe")
+ self.manifest["files"].pop("bin/ffprobe.exe")
+ (self.source / "untrunc.exe").write_bytes(b"untrunc")
+ self.manifest["files"]["untrunc.exe"] = ffmpeg_bundle.digest(self.source / "untrunc.exe")
+ self.manifest["sources"] = [s for s in self.manifest["sources"] if s["name"] != "x264"]
+ self.manifest["sources"][1]["name"] = "untrunc"
+ self.write_manifest()
+ result = ffmpeg_bundle.package(self.source, self.destination, "untrunc")
+ self.assertEqual(result["license"], "GPL-2.0-or-later")
+ self.assertEqual((self.destination / "untrunc.exe").read_bytes(), b"untrunc")
+
diff --git a/tests/test_media.py b/tests/test_media.py
index 0937f2bb0..eca1cdb02 100644
--- a/tests/test_media.py
+++ b/tests/test_media.py
@@ -1,5 +1,6 @@
import os
import tempfile
+import sys
import unittest
from pathlib import Path
from unittest.mock import patch
@@ -80,6 +81,35 @@ class MediaEngineTests(unittest.TestCase):
choice = FFmpegResolver(root).ffmpeg()
self.assertEqual(choice.source, "peach-managed")
+ def test_frozen_application_uses_both_bundled_tools_without_path(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ bundle = root / "app" / "tools" / "ffmpeg" / "bin"
+ bundle.mkdir(parents=True)
+ suffix = ".exe" if os.name == "nt" else ""
+ for name in ("ffmpeg", "ffprobe"):
+ (bundle / (name + suffix)).write_bytes(b"tool")
+ with patch.object(sys, "frozen", True, create=True), \
+ patch.object(sys, "executable", str(root / "app" / "Peach.exe")), \
+ patch.dict(os.environ, {"PEACH_FFMPEG": "", "PEACH_FFPROBE": ""}), \
+ patch("peach.ffmpeg.shutil.which", return_value=None):
+ resolver = FFmpegResolver(root / "data")
+ for choice in (resolver.ffmpeg(), resolver.ffprobe()):
+ self.assertEqual(choice.source, "peach-bundled")
+ self.assertEqual(choice.path.parent, bundle)
+
+ def test_source_environment_does_not_use_tools_beside_python(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ tool = root / "tools" / "ffmpeg" / "bin" / ("ffmpeg.exe" if os.name == "nt" else "ffmpeg")
+ tool.parent.mkdir(parents=True)
+ tool.write_bytes(b"tool")
+ with patch.object(sys, "frozen", False, create=True), \
+ patch.object(sys, "executable", str(root / "python.exe")), \
+ patch.dict(os.environ, {"PEACH_FFMPEG": ""}), \
+ patch("peach.ffmpeg.shutil.which", return_value=None):
+ self.assertIsNone(FFmpegResolver(root / "data").ffmpeg())
+
def test_offline_windows_root_does_not_block_startup(self):
with patch.object(Path, "resolve", side_effect=OSError("offline")):
path = normalized_path(Path("B:/"))
diff --git a/tests/test_media_tool_import.py b/tests/test_media_tool_import.py
new file mode 100644
index 000000000..e3f3b1d83
--- /dev/null
+++ b/tests/test_media_tool_import.py
@@ -0,0 +1,53 @@
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+PWSH = shutil.which("pwsh")
+
+
[email protected](os.name == "nt" and PWSH, "Windows PowerShell tool import")
+class MediaToolImportTests(unittest.TestCase):
+ def test_imports_installed_tools_companion_dlls_and_preserves_existing_copy(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ data = root / "Peach data"
+ data.mkdir()
+ installed = root / "WinGet/Packages/Gyan.FFmpeg/version/bin"
+ installed.mkdir(parents=True)
+ for name in ("ffmpeg.exe", "ffprobe.exe", "avcodec.dll"):
+ (installed / name).write_bytes(b"MZ" + name.encode())
+ repair = root / "WinGet/Packages/untrunc"
+ repair.mkdir()
+ (repair / "untrunc.exe").write_bytes(b"MZrepair")
+ target = data / "tools/ffmpeg/bin"
+ target.mkdir(parents=True)
+ (target / "ffmpeg.exe").write_bytes(b"MZold")
+ result = subprocess.run([PWSH, "-NoProfile", "-File",
+ str(ROOT / "scripts/import_windows_media_tools.ps1"),
+ "-DataRoot", str(data), "-SearchRoots", str(root / "WinGet")],
+ capture_output=True, text=True, timeout=30)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ for name in ("ffmpeg.exe", "ffprobe.exe", "avcodec.dll"):
+ self.assertEqual((target / name).read_bytes(), (installed / name).read_bytes())
+ self.assertEqual((data / "tools/untrunc/untrunc.exe").read_bytes(), b"MZrepair")
+ backups = list((data / "tools").glob("import-backup-*/ffmpeg.exe"))
+ self.assertEqual(len(backups), 1)
+ self.assertEqual(backups[0].read_bytes(), b"MZold")
+
+ def test_missing_download_does_not_claim_ready_or_touch_other_data(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ (root / "ledger.db").write_bytes(b"kept")
+ result = subprocess.run([PWSH, "-NoProfile", "-File",
+ str(ROOT / "scripts/import_windows_media_tools.ps1"),
+ "-DataRoot", str(root), "-SearchRoots", str(root)],
+ capture_output=True, text=True, timeout=30)
+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
+ self.assertIn("NOT FOUND", result.stdout)
+ self.assertEqual((root / "ledger.db").read_bytes(), b"kept")
+ self.assertFalse((root / "tools").exists())