Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
fix(subtitles): decode compressed PGS and external bitmap formats
Veyra Goal Agenta29243c1753c
diff --git a/AGENTS.md b/AGENTS.mdindex 29f1eecf..c0f7be1c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-09 字幕格式修复授权**:用户要求修复PGS/SUP不显示并检查其它字幕格式,确认多位其他用户的内嵌PGS轨道显示不可用。按docs/SUBTITLE_FORMATS_PLAN_2026-10-09.md从main 0e7018ad在E盘codex/subtitle-formats-20261009隔离排查/修复共享字幕解码/加载/字幕层和必要bridge/菜单/翻译及定向验收,这些具体接点覆盖历史冻结。独立start/bundle保护39既有工作树/495脏文件;main与其它工作树保持,不改旧guard。所有产物E盘;原runtime/模型/SDK字节不变、不进Git;允许针对已复现的Matroska压缩PGS缺口,在E盘另行构建同版本patched FFmpeg,仅启用现有静态zlib、保留PS5 slices256/dav1d/原解码能力并记录对应源码/许可证/实际配置,不覆盖原件。此为字幕修复必要接点,不改proprietary运行库。不派Agent/造压,不改用户配置/驱动,无新merge/push/Release/版本更新/关机授权。现场视频未提供,不以公开样本冒充反馈者全部通过。+> **2026-10-09 HDR 补帧开关与 main 整合授权**:用户先要求将目前修复合入 main,再明确 HDR 补帧兼容必须改为设置页开关、默认关闭。按 docs/HDR_FG_COMPAT_TOGGLE_PLAN_2026-10-09.md 在当前 FG 隔离工作树修改必要呈现设置/bridge/QML/翻译及定向验收,覆盖这些接点的历史冻结。通过后允许本地 commit/checkpoint/main 合并 BMD、HDR 开关和对应诊断脚本/记录;不 push/Release/更新版本/关机,不派 Agent、不造压、不改运行库/模型/驱动/用户配置。39 工作树、495 脏文件按 archives/hdr-fg-toggle-20261009/start.json 保护,旧 guard/start 不改,产物全 E 盘;测试≤300秒、构建≤900秒。HDR 现场根因、5090 复测及 BMD 实卡/延迟仍未确认,不把兼容候选或开关测试冒充根治。> **2026-10-09 补帧闪黑现场续修**:用户提交诊断ZIP与日志44,反馈诊断不闪、原版闪,授权排查修复并收尾关机。按docs/FG_FLASH_FIX_PLAN_2026-10-09.md,从main dbfceab在E盘codex/fg-flash-fix-20261009隔离实现NVIDIA HDR应用FG最终合成GPU复制候选与定向测试/本地可回退包;这些具体presenter/ABI重编译接点覆盖历史冻结。诊断增加GPU拷贝、改名EXE/私有配置/关QML缓存,不能当根因证明;本机5070未复现5090闪黑,候选现场效果未验,禁止宣称根治。先执行fg-flash-fix-control.py,独立不可变pre-document-state保护37工作树/495脏文件,不改旧guard。不派Agent/竞争压力,不改驱动、DLL/模型、用户配置或其它工作树;无新main合并/push/Release。正常链路不加像素回读/CPU逐帧等待。测试≤300秒、构建≤900秒、产物全E盘;源码、候选、回执保存核对后按用户要求关机,不强制丢弃未保存内容。diff --git a/CMakeLists.txt b/CMakeLists.txtindex 05e2ae8e..28e5842f 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -654,6 +654,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_link_libraries(veyra_screenshot_combination_tests PRIVATE veyra_engine)target_compile_features(veyra_screenshot_combination_tests PRIVATE cxx_std_20)add_executable(veyra_bitmap_subtitle_tests tests/integration/BitmapSubtitleTests.cpp)+ add_executable(veyra_subtitle_format_tests tests/integration/SubtitleFormatTests.cpp)+ target_compile_features(veyra_subtitle_format_tests PRIVATE cxx_std_20)+ target_compile_options(veyra_subtitle_format_tests PRIVATE /utf-8)+ target_link_libraries(veyra_subtitle_format_tests PRIVATE veyra_engine)target_link_libraries(veyra_bitmap_subtitle_tests PRIVATE veyra_engine)target_compile_features(veyra_bitmap_subtitle_tests PRIVATE cxx_std_20)target_link_libraries(veyra_subtitle_loading_tests PRIVATE veyra_engine)diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 12d577b4..2f54c38c 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -1,5 +1,17 @@# Third-party dependencies+## Compressed Matroska subtitles (2026-10-09)++The subtitle candidate rebuilds the existing LGPL FFmpeg n9.0.1 with zlib+enabled, retaining the Veyra PS5 H.264 slices256 patch and dav1d 1.5.4.+It statically links zlib 1.3.2 (zlib license; Jean-loup Gailly, Mark Adler and+contributors), using the existing external dependency built with the dynamic+MSVC CRT. FFmpeg handles compressed Matroska PGS/DVD and text subtitle packets;+Veyra does not implement another decompressor. The original runtime files are+preserved. Candidate DLL hashes, actual configuration, LGPL/zlib notices and+the matching FFmpeg/dav1d/zlib source archive accompany the local candidate.+No dependency source, model, SDK, library or DLL is added to Veyra source Git.+NVIDIA SDKs and runtimes are excluded from source control. The publisher-authorized experimental Release package contains only selected runtime DLLs and applicable notices, as documented in `docs/RUNTIME_COMPONENTS_0.0.2.md`. This is not vendor endorsement or a general redistribution grant. ReShade/RenoDX add-ons are not loaded or distributed by the product.## NVIDIA Video Frame Generation (local integration, 2026-10-03)diff --git a/docs/SUBTITLE_FORMATS_PLAN_2026-10-09.md b/docs/SUBTITLE_FORMATS_PLAN_2026-10-09.mdnew file mode 100644index 00000000..5d75306d--- /dev/null+++ b/docs/SUBTITLE_FORMATS_PLAN_2026-10-09.md@@ -0,0 +1,17 @@+# 字幕格式与内嵌 PGS 不可用排查++用户要求修复 PGS/SUP 不显示并检查其它常见字幕格式;随后确认内嵌 PGS 在菜单中均显示“不可用”,提供五条 HDMV_PGS_SUBTITLE 轨道的截图。尚无该视频文件或现场日志,不把短样本通过冒充此文件根治。++基线 main 0e7018ad,隔离分支 codex/subtitle-formats-20261009。开工独立 archives/subtitle-formats-20261009/start.json、source-before.bundle 保护39既有工作树/495脏文件;main不变。本轮只改共享字幕解析/解码/字幕层、必要bridge/字幕菜单/翻译和定向验收,不改NR/补帧/视频解码/音频/导出算法。当前用户授权覆盖这些字幕接点的历史冻结,不运行或重写历史UI迁移guard。++1. 先验证随包 FFmpeg 的实际字幕解码器与既有位图样本。已只读确认随包 pgssub、dvdsub、dvbsub、xsub 和多种文本 decoder 存在,TTML不存在;不能归因为缺PGS解码器。记录各层失败的真实返回值和轨道状态。+2. 修正经样本或源码验证的PGS加载/时间线/清屏/发布问题;区分正在读取、无内容、格式不支持、初始化失败与损坏数据,不在扫描期间笼统称不可用。+3. 外置SUP/PGS和VobSub等可复用现有FFmpeg解码器,不把二进制当UTF文本解析。文本格式优先复用已随包decoder/现有ASS/SRT/VTT解析,拓展常见SubViewer、MicroDVD、SAMI等。只列出已实测支持,不用扩展名白名单代替端到端支持。+4. 定向回归内嵌与外置、主副轨/选择、延时/seek/清屏/缩放、Unicode路径、坏文件和取消/旧异步结果;验证实际字幕层像素与QML轨道状态,不只看解码计数。+5. 构建当前main全部必要覆盖对象,不混旧ABI;原SDK/运行库/模型/已验母包字节保持。每测试≤300秒、构建≤900秒,产物E:/项目/Veyra/{reports,build,tests,logs,tmp,test-packages,archives}/subtitle-formats-20261009,仅一个共享测试app。完工记录失败/限制、提交隔离分支;没有新merge/push/Release/版本更新/关机授权,不派Agent、不造压、不代发消息。++## 实证补充:压缩PGS++公开FFmpeg样本 `https://samples.ffmpeg.org/sub/PGS/supsample.mkv` 在产品原DLL上轨道存在但0条cue,输出 `Unsupported encoding type`。同文件在FFmpeg CLI上解封装为2个PGS显示包;原DLL配置为 `--disable-zlib`,Matroska源码明确拒绝zlib压缩轨道。另一公开PGS样本不压缩,可正常解码。这是已经复现的封装能力缺口,不是PGS decoder缺失;不能推断所有反馈片源均为此原因。++本轮另行构建同一n9.0.1 patched源码,仅切换 `--enable-zlib`,链接已有libass依赖中的静态zlib1.3.2。保留slices256、dav1d、LGPL配置及全部旧格式能力;输入原件不覆盖,FFmpeg/zlib对应源码及许可证留在E盘、哈希/配置随候选交付。构建脚本/打包接点纳入范围,不增加专有运行库。回归原样本、未压缩对照与既有视频解码。diff --git a/docs/SUBTITLE_FORMATS_REPORT_2026-10-09.md b/docs/SUBTITLE_FORMATS_REPORT_2026-10-09.mdnew file mode 100644index 00000000..2af3407a--- /dev/null+++ b/docs/SUBTITLE_FORMATS_REPORT_2026-10-09.md@@ -0,0 +1,54 @@+# PGS / SUP 与其它字幕格式修复记录++基线 main `0e7018adab9b211d76dd05da40cfbaeb9d77cf2c`,实施分支 `codex/subtitle-formats-20261009`。用户确认截图中的五条 HDMV_PGS_SUBTITLE 不可用并非仅一位用户反馈,片源在其他用户电脑;本机没有这些实际失败文件或对应播放日志。++## 已确认的问题++原包具备 `pgssub` decoder,不能归因为没有 PGS 解码器。实际 FFmpeg n9.0.1 配置为 `--disable-zlib`,Matroska demuxer 因而拒绝 zlib 压缩的轨道数据。公开样本 [supsample.mkv](https://samples.ffmpeg.org/sub/PGS/supsample.mkv) 在原 DLL 上可以列出 PGS 轨道,但日志为 `Unsupported encoding type`、0 条 cue、usable=false。++固定同一个旧 probe EXE,只替换 FFmpeg DLL 后,同一文件变为 1 条位图 cue,1.001–9.009 秒、usable=true;未压缩的 [另一 PGS 样本](https://samples.ffmpeg.org/sub/PGS/Girl_With_The_Dragon_Tattoo_2%3A23%3A56.mkv) 前后均正常。两份原始输出、EXE / DLL / 样本 SHA 保存在 `E:/项目/Veyra/logs/subtitle-formats-20261009/pgs-ab-20261009-134011/receipt.json`。这证明一个可复现的封装支持缺口,不能据此断定所有反馈者的原因均相同。++另有两个代码缺口:外挂 SUP/PGS 原先只走 UTF 文本读取;PGS 只有 Matroska BlockDuration、没有后继 clear set 时,旧字幕缓存没有按该时长结束。后者根据 [Matroska 字幕契约](https://www.matroska.org/technical/subtitles.html) 修正,并用独立构造、不含 clear set 的文件验证 3/7 秒边界。++## 实施结果++- 在独立目录重建同一份 patched FFmpeg n9.0.1,仅启用 zlib,保留 PS5 H.264 slices256、dav1d 1.5.4 与 LGPL 配置。静态 zlib 1.3.2 使用动态 MSVC CRT `/MD`;没有新增 zlib DLL,没有覆盖旧 prefix 或修改任何专有运行时。+- 内嵌和外挂位图复用同一 FFmpeg 字幕解码路径。支持 SUP/PGS、VobSub IDX+SUB 的多个语言轨道;二进制 `.sub` 重定向至同名 `.idx`,文本 `.sub` 保持按内容解析。保留原始画布、位置、颜色和透明度。+- 接通并实测 MicroDVD、SubViewer/SBV、SAMI、MPL2、Spruce STL。SRT、ASS/SSA、WebVTT 沿用原有解析及 ASS 脚本/样式。选择文件的过滤器与同名外挂自动发现同步更新。+- 外挂读取进入可取消的后台 loader;一次插入 VobSub 多语言,保留副字幕、独立延时和自动对齐索引。坏文件不清空当前字幕,换源取消旧请求。+- 菜单区分正在读取、无字幕数据、解码失败、缺少 decoder 与缓存上限,不再在扫描过程中统一标成不可用。每轨记录 packet/display/error/cue 计数和真实 FFmpeg 返回值。+- 保留 64 MiB 解码字幕缓存、120000 条 cue 与 16 MiB 文本文件限制;VobSub 二进制文件不套用文本限制,其 IDX 索引仍受限制。没有增加 GPU 像素回读或逐帧 fence wait。+- QML 打包接点校验 zlib-enabled FFmpeg 及实际 DLL SHA,拒绝误用旧缓存;提供显式 `--ffmpeg-root`。同步保留 zlib 许可证、SPDX 和对应源码。++## 验证++最终应用 EXE SHA256:`3be70422720f22272ff39eac6b79ddd837892b5923972ea0b4442ebe30d6f99b`。构建使用当前 main 必要覆盖对象,逐源/对象 SHA 核验,保留之前 HDR 开关与 BMD 改动;没有直接拿旧静态库冒充当前 main。++| 验证 | 结果与证据 |+| --- | --- |+| FFmpeg 构建 | 270.48 秒、exit 0;原 patched 源树、输入库和原 DLL SHA 保持。`logs/.../ffmpeg-build-20261009-131500/receipt.json` |+| 最终应用及 5 个测试程序构建 | 全部 exit 0,原输入不变。`logs/.../build-20261009-133206/receipt.json` |+| 原生字幕回归 | 格式 322、实际字幕层像素 28、原文本 5、PGS 21、DVD 16、DVB 21,共 **413 项断言通过**;异步加载另行通过。`logs/.../tests-20261009-133424/receipt.json` |+| 多轨压缩 PGS | 独立构造的 5 条压缩轨与未压缩轨逐像素相等、共 10 条 cue;首条可用及时发布,加载提示正确清除 |+| 位图显示 | 真实解码的 SUP 进入产品 SubtitleOverlay;验证作者坐标/letterbox、半透明与透明间隙、调色板更新、清屏、回退 seek、窗口尺寸变化。不是仅统计 cue 数量 |+| 实际 QML / bridge | 最终 EXE 的 embedded / external / sidecar / english 四组均 exit 0、无错误:`gui-embedded-20261009-133438`、`gui-external-20261009-133515`、`gui-sidecar-20261009-133543`、`gui-english-20261009-133622`。同名前置 SUP、两条 VobSub 语言、主副选择与各自延时、Unicode 路径、坏文件保留、换源取消、菜单可选及英文错误说明通过 |+| 常规视频播放短测 | GTA6 原片 H.264 4K D3D12 硬解提交 350 原帧;HEVC 4K D3D11 硬解 180/180 帧播放至 EOS。两组 exit 0、无 ERROR。不是性能或全片长稳验收 |+| 发布者打包检查 | 原无 zlib prefix 被拒,新 prefix 的 6 DLL 身份通过。`reports/.../package-ffmpeg-audit.json` |++上述 `logs/...` / `reports/...` 均以 `E:/项目/Veyra/` 为根、任务目录为 `subtitle-formats-20261009`。QML 抓图仅检视菜单与界面,不包含原生视频子窗口像素;字幕层像素结论来自原生回归。++### 回归中发现的已有问题++AV1 4K 测试片 `tests/stream-fix-20261001/av1_4k_150m.mkv` 回退 libdav1d 软件解码后,12 秒观察仅提交 4 个原帧。候选 EXE+新 FFmpeg、候选 EXE+旧 FFmpeg、原 EXE+旧 FFmpeg 三组均复现,均无 ERROR,不能将这一项记作通过。日志显示 software fallback 后 `prepareMs` 约 11.9 秒;这不是已确定的根因。三组证据分别为 `video-20261009-133700`、`video-20261009-133833`、`video-20261009-133918`。本轮不修改 AV1 播放/调度链路;它不是本次 FFmpeg 重编译特有的回归。++### 失败和修正++首次 FFmpeg configure 因 MinGW pkg-config 损坏中文路径失败;改用 `E:/veyra-subtitle-20261009` junction(实际仍在 E:/项目/Veyra)后成功。首次格式测试暴露短 MPL2 被误探为 LRC,按明确扩展名选择已有 demuxer 后通过;loading fixture 实为两个内嵌加一个同名外挂,期望值纠正为 3。原失败回执保留,没有覆盖为通过。++## 本地交付与边界++覆盖包:`E:/项目/Veyra/test-packages/subtitle-formats-20261009/Veyra-2.0.6-subtitle-fix-overlay.zip`。关闭播放器、备份将被覆盖的文件,再将包内文件解压覆盖现有 **2.0.6** 目录。必须一起更新 EXE 和 FFmpeg DLL,单换 EXE 不会修复压缩 PGS。包内附对应 Veyra 源码、patched FFmpeg/dav1d/zlib 源码、许可证和逐文件 manifest;不包含新 NR/FG DLL、模型、SDK、个人配置、凭据、测试媒体或现场日志。++仍未验证受影响用户实际原片、整部影片大量 PGS、AMD/Intel 实机与 HDR 字幕显示;本机是 RTX5070。缓存上限未提高,达到上限会明确提示后续内容未加载。TTML decoder 不在当前 FFmpeg 中,不宣称支持;STL 指 Spruce 文本格式,不是 EBU 二进制 STL;TXT 只识别带支持格式时间码的内容,不自动生成字幕。没有更改字幕渲染顺序、NR、补帧或导出实现。++本轮仅本地隔离分支存档与候选包,未合并 main、未 push、未创建 Release、未更改正式版本号。开工的 39 既有工作树/495 脏文件与 main 固定快照由 `subtitle-formats-control.py` 逐项核对;候选完整性、源码包和最终保全以 `reports/subtitle-formats-20261009/final.json` 为准。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 5c47f212..df35d771 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -8847,3 +8847,23 @@ package-field.py交付test-packages/fg-source-flash-20261008/Veyra-2.0.6-black-f实际命令:build-diagnostic.py 编译三对象+GUI重链接 exit0,原缓存和产品输入SHA不变;run-field.py final-exe-nr-stop-powershell51 97.875秒exit0,RTX5070原版NR1080/NVOF/窗口→全屏→关NR→停止;DXGI92条0失败、27有效WDDM、同PID7012、停止后36条segment记录,135资源创建/135最终销毁ID配对、存活0;原配置和1614母包文件SHA不变,凭据哨兵未复制/入ZIP。只是短测,没有复现长稳泄漏或量化性能开销。check-tools.py PS5.1解析/缺数据/连续标记段/恢复打包/隐私通过;package.py ZIP与内层源码CRC/每文件SHA通过;git diff --check和audit-state.py check保护36原工作树/495脏文件通过。失败:首轮继承PS7模块路径导致PS5.1 Get-FileHash不可用,启动前失败后显式加载宿主模块;初版NVOF验证器频道误匹配修正;补最终释放/DPI采样后重编重测最终EXE,原失败证据保留。产物 E:/项目/Veyra/{reports,tests,logs,tmp,test-packages}/nv-vram-field-20261008,只保留一共享硬链接app、独立profile和必要证据;未重试旧被拒清理。交付ZIP Veyra-2.0.6-NVIDIA-VRAM-diagnostic.zip 78,606,236字节、SHA92a2a807202489a023a884c9fab998bd1f6d177e056e3b0ae7c04c06d832775d,EXE7519d7e864cfcf7cff9ef27ecff2a584d2a685175bc3cc5c6a18ea68e0c9f04b;包内有对应源码和补充诊断代码,无DLL/模型/SDK。详见docs/NV_VRAM_FIELD_REPORT_2026-10-08.md。不合并main、不push/Release、不代发文件、不关机。下一步受影响用户实际复现后返回同PID原始CSV/JSONL/日志,不能承诺一轮诊断包必然确定所有者。++## 2026-10-09 PGS / SUP 与字幕格式修复++用户要求修复内嵌 PGS 标不可用并支持更多字幕格式,确认是其他用户多份片源;本机无失败原片/现场日志。基线 main 0e7018ad,隔离 codex/subtitle-formats-20261009 / E:/项目/Veyra/worktrees/subtitle-formats-20261009。39 既有工作树/495 脏文件先固定,source-before.bundle 通过验证。本轮仅共享字幕/菜单/bridge/翻译、必要 FFmpeg 构建和打包接点,没有子 Agent、main 合并、推送、Release、版本号更新或关机。++实证:原产品 FFmpeg 具备 PGS decoder,却 --disable-zlib;公开 supsample.mkv 在同一旧 probe EXE 上,原 DLL 为 Unsupported encoding type / 轨道存在但 0 cue,独立重建 zlib-enabled DLL 后变 1 cue、1.001–9.009 秒可用,未压缩对照均正常。py -3.11 -B E:/项目/Veyra/reports/subtitle-formats-20261009/pgs-ab.py 保存 logs/.../pgs-ab-20261009-134011/receipt.json 及原始输出/输入 SHA。只证明此类压缩封装缺口,不推断所有反馈者相同。++修复外挂 SUP/PGS 二进制读取、VobSub IDX+SUB 全语言、PGS BlockDuration 截止、加载状态/每轨错误诊断,接通常见 MicroDVD/SubViewer/SBV/SAMI/MPL2/Spruce STL,同名外挂自动发现。手动外挂异步可取消、坏文件保留现有轨道,主副延时/选择与 ASS 样式保持。保留 64MiB/120000 cue 与文本 16MiB 限制;二进制 SUB 先规范化 IDX 再检查,防止绕过索引大小限制。没有增加像素回读/fence 等待或改 NR/FG/导出。++命令 py -3.11 -B E:/项目/Veyra/reports/subtitle-formats-20261009/build-ffmpeg.py,独立新 prefix deps/ffmpeg-subtitle-formats-20261009/installed,仅启用静态 zlib1.3.2 /MD,保留 n9.0.1 slices256/dav1d1.5.4/LGPL。270.48秒 exit0,原 patched 树/输入库/旧 DLL 全 SHA 保持,logs/.../ffmpeg-build-20261009-131500/receipt.json。中文路径首次 configure 失败改显式 junction 后成功,失败保留。prepare-slice-build.py 与 package-ffmpeg-source.py 支持 zlib;QML 打包拒旧无 zlib prefix,新6DLL通过,reports/.../package-ffmpeg-audit.json。对应 FFmpeg/dav1d/zlib 源码 ZIP SHA49db22049f072bd5448faa664aa736074dccfe6e72b4a933f673d8ae954b0bb6,CRC通过,未入 Git。++py -3.11 -B scripts/tests/make-subtitle-format-fixtures.py --output E:/项目/Veyra/tests/subtitle-formats-20261009/formats --dvd-fixture E:/项目/Veyra/tests/5060-presets-subtitles-20260918/bitmap-dvd.mkv;py -3.11 -B scripts/acceptance/subtitle-formats-build.py 最终 logs/.../build-20261009-133206/receipt.json,验证当前 main 覆盖对象与原缓存输入 SHA,GUI+5测试可构建。py -3.11 -B scripts/acceptance/subtitle-formats-test.py 最终 tests-20261009-133424 全部 exit0,322格式+28原生字幕层像素+5文本+21PGS+16DVD+21DVB =413断言,异步加载另外通过。独立五轨 zlib PGS 与未压缩逐像素一致、BlockDuration/clear/seek/缩放/透明度/主副/错误/取消覆盖。首次 MPL2 探测误判和 fixture 期望轨数问题修正后重测,原失败保留。++py -3.11 -B scripts/acceptance/subtitle-formats-gui-test.py 依次 embedded / external / sidecar / english,最终 EXE SHA3be70422720f22272ff39eac6b79ddd837892b5923972ea0b4442ebe30d6f99b;四组 exit0,无错误,记录 gui-embedded-20261009-133438 / gui-external-20261009-133515 / gui-sidecar-20261009-133543 / gui-english-20261009-133622。共享单一硬链接 app/独立 profile/temp,1614母包文件 SHA 每组保持,Main.qml 测试 timer 收尾还原,原偏好不动。QML抓图只证实菜单,真实位图显示由原生产品 overlay DIB 像素断言验证。++py -3.11 -B E:/项目/Veyra/reports/subtitle-formats-20261009/video-smoke.py:H264原GTA6 4K D3D12 350提交/HEVC4K D3D11 180/180到EOS均 exit0/无ERROR;AV1 4K 12秒只提交4帧,不记通过。追加 --case av1-4k --reference-ffmpeg 以及 --reference-app 两组,原 DLL/原 EXE 同样卡住,三组 logs/.../video-20261009-133700 / 133833 / 133918。只排除这是新 FFmpeg 特有回归,未定位/修复该已有 AV1 播放问题。++产物统一 E:/项目/Veyra/{reports,build,tests,logs,tmp,downloads,test-packages,archives}/subtitle-formats-20261009;本地交付 Veyra-2.0.6-subtitle-fix-overlay.zip,含 EXE+FFmpeg+所需QML/许可证/对应源码,需完整覆盖2.0.6,单换EXE无效。详细边界见 docs/SUBTITLE_FORMATS_REPORT_2026-10-09.md;远端原片/全片大量PGS/AMD/Intel/HDR尚未验收,不宣称所有用户根治。不重试被拒的历史清理,保留一共享app、当前构建及必要证据;最终 manifest / 源码提交 / 保全回执见 reports/.../final.json。++打包与收尾命令 py -3.11 -B E:/项目/Veyra/reports/subtitle-formats-20261009/package-overlay.py、py -3.11 -B scripts/acceptance/subtitle-formats-control.py final。覆盖包/source两个内层ZIP CRC及逐文件SHA核对,源码排除既有两个MP4宣传文件与一个旧pyc,不移除仓库原文件。候选不替换原完整package-manifest,另附subtitle-fix-manifest.json列明变更。单份共享app恢复最终EXE/新FFmpeg/原Main.qml,母包1614文件SHA保持。提交仅本轮23个白名单源码/文档/脚本,main与39原树保持;独立checkpoint与source-after.bundle在archives目录,未冒称独立Reviewer。diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex 5e8563af..180c650f 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -14365,6 +14365,97 @@"zh-TW": "OBS、監控軟體相容需重新啟動;HDR 補幀相容可在播放中切換。","en": "OBS and monitoring compatibility require a restart; HDR frame generation compatibility can be switched during playback.","ja": "OBS とモニタリングソフトの互換設定は再起動が必要です。HDR フレーム生成の互換設定は再生中に切り替えられます。"+ },+ {+ "zh": "正在读取字幕",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "正在讀取字幕",+ "en": "Reading subtitles",+ "ja": "字幕を読み込み中"+ },+ {+ "zh": "缺少此字幕格式的解码器",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "缺少此字幕格式的解碼器",+ "en": "Decoder for this subtitle format is unavailable",+ "ja": "この字幕形式のデコーダーがありません"+ },+ {+ "zh": "字幕数据解码失败(请查看日志)",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "字幕資料解碼失敗(請查看日誌)",+ "en": "Subtitle decoding failed (see log)",+ "ja": "字幕のデコードに失敗しました(ログを確認)"+ },+ {+ "zh": "没有读到字幕数据(请检查封装或压缩支持)",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "未讀到字幕資料(請檢查封裝或壓縮支援)",+ "en": "No subtitle packets read (check container or compression support)",+ "ja": "字幕データを読み取れません(コンテナまたは圧縮形式を確認)"+ },+ {+ "zh": "未解码出可显示的字幕",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "未解碼出可顯示的字幕",+ "en": "No displayable subtitles decoded",+ "ja": "表示できる字幕がありません"+ },+ {+ "zh": "字幕文件不存在或无法读取",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "字幕檔案不存在或無法讀取",+ "en": "Subtitle file is missing or unreadable",+ "ja": "字幕ファイルが存在しないか読み取れません"+ },+ {+ "zh": "VobSub 需要同名 .idx 和 .sub 文件,请加载 .idx",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "VobSub 需要同名 .idx 和 .sub 檔案,請載入 .idx",+ "en": "VobSub requires matching .idx and .sub files; load the .idx file",+ "ja": "VobSub には同名の .idx と .sub が必要です。.idx を読み込んでください"+ },+ {+ "zh": "文件格式不支持、数据损坏或没有字幕内容",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "檔案格式不支援、資料損壞或沒有字幕內容",+ "en": "Unsupported format, damaged data, or no subtitle content",+ "ja": "未対応の形式、破損したデータ、または字幕なし"+ },+ {+ "zh": "外部字幕加载失败:%1 · %2",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "外部字幕載入失敗:%1 · %2",+ "en": "External subtitle loading failed: %1 · %2",+ "ja": "外部字幕の読み込みに失敗:%1 · %2"+ },+ {+ "zh": "正在加载外部字幕:%1",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "正在載入外部字幕:%1",+ "en": "Loading external subtitles: %1",+ "ja": "外部字幕を読み込み中:%1"+ },+ {+ "zh": "字幕文件 (*.srt *.ass *.ssa *.vtt *.sup *.pgs *.idx *.sub *.smi *.sami *.sbv *.mpl *.stl *.txt);;所有文件 (*.*)",+ "src": "src/engine/Subtitles.cpp;src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "字幕檔案 (*.srt *.ass *.ssa *.vtt *.sup *.pgs *.idx *.sub *.smi *.sami *.sbv *.mpl *.stl *.txt);;所有檔案 (*.*)",+ "en": "Subtitle files (*.srt *.ass *.ssa *.vtt *.sup *.pgs *.idx *.sub *.smi *.sami *.sbv *.mpl *.stl *.txt);;All files (*.*)",+ "ja": "字幕ファイル (*.srt *.ass *.ssa *.vtt *.sup *.pgs *.idx *.sub *.smi *.sami *.sbv *.mpl *.stl *.txt);;すべてのファイル (*.*)"+ },+ {+ "zh": "文本字幕 · PGS/SUP · VobSub(IDX+SUB)",+ "src": "qml/Veyra/DialogHost.qml",+ "zh-TW": "文字字幕 · PGS/SUP · VobSub(IDX+SUB)",+ "en": "Text · PGS/SUP · VobSub (IDX+SUB)",+ "ja": "テキスト字幕 · PGS/SUP · VobSub(IDX+SUB)"+ },+ {+ "zh": "文本字幕超过 16 MiB 上限",+ "src": "src/engine/Subtitles.cpp",+ "zh-TW": "文字字幕超過 16 MiB 上限",+ "en": "Text subtitles exceed the 16 MiB limit",+ "ja": "テキスト字幕が 16 MiB の上限を超えています"}]}diff --git a/include/veyra/engine/Subtitles.h b/include/veyra/engine/Subtitles.hindex d2a65b47..c6aeca1e 100644--- a/include/veyra/engine/Subtitles.h+++ b/include/veyra/engine/Subtitles.h@@ -1,7 +1,7 @@#pragma once-// Subtitle engine: external text formats (SRT/ASS/SSA/WebVTT), subtitle tracks-// embedded in the media container, including FFmpeg-decoded PGS/DVD/DVB images.+// Shared text and bitmap subtitle loading, including external SUP/VobSub and+// container tracks. Bitmap subtitles retain their authored canvas and palette.#include <string>#include <vector>#include <functional>@@ -77,6 +77,10 @@ struct SubtitleTrack {// Format is chosen from the file extension first, then sniffed from content.SubtitleTrack loadSubtitleFile(const std::wstring& path);+// External files may contain several languages (VobSub IDX/SUB). Uses the same+// cancellable FFmpeg path as embedded subtitles; never reads bitmap data as text.+std::vector<SubtitleTrack> loadExternalSubtitleTracks(const std::wstring& path,std::stop_token stop={},+ const std::function<void(const std::vector<SubtitleTrack>&)>& metadata={});// Subtitle tracks inside the container (Matroska/MP4/...).std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,std::stop_token stop={},@@ -90,8 +94,10 @@ public:SubtitleLoader();~SubtitleLoader();uint64_t request(std::wstring path);+ uint64_t requestFile(std::wstring path);std::optional<Result> poll();private:+ uint64_t request(std::wstring path,bool external);struct Impl;std::unique_ptr<Impl> p_;};diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qmlindex 1cc8ee6c..844fb861 100644--- a/qml/Veyra/DialogHost.qml+++ b/qml/Veyra/DialogHost.qml@@ -1284,7 +1284,7 @@ Item {DGroup {VRow {label: qsTr("主字幕")- hint: veyra.subtitleTracks.length === 0 ? (veyra.hasSource ? qsTr("当前片源没有字幕") : qsTr("打开视频后显示可用字幕")) : ""+ hint: veyra.subtitleTracks.length === 0 ? (veyra.subtitleStatus.length > 0 ? veyra.subtitleStatus : (veyra.hasSource ? qsTr("当前片源没有字幕") : qsTr("打开视频后显示可用字幕"))) : ""VSelect {objectName: "subtitle-primary"implicitWidth: 220@@ -1306,7 +1306,7 @@ Item {}VRow {label: qsTr("外挂字幕")- hint: "SRT / ASS / SSA / WebVTT"+ hint: qsTr("文本字幕 · PGS/SUP · VobSub(IDX+SUB)")VButton { objectName: "subtitle-load"; text: qsTr("加载文件…"); onClicked: veyra.loadSubtitleDialog() }}VRow {diff --git a/scripts/acceptance/subtitle-formats-build.py b/scripts/acceptance/subtitle-formats-build.pynew file mode 100644index 00000000..2bd98c3e--- /dev/null+++ b/scripts/acceptance/subtitle-formats-build.py@@ -0,0 +1,115 @@+"""Scoped build against verified current-main objects; never writes old caches."""+from pathlib import Path+import ctypes+import hashlib+import json+import os+import re+import subprocess+import time++ROOT=Path(__file__).resolve().parents[2]+BASE=Path('E:/项目/Veyra');TASK='subtitle-formats-20261009'+CACHE=BASE/'build/vfg-next-20261007';OUT=BASE/'build'/TASK+LOG=BASE/'logs'/TASK/('build-'+time.strftime('%Y%m%d-%H%M%S'));TMP=BASE/'tmp'/TASK/'build'+for p in (OUT,LOG,TMP):p.mkdir(parents=True,exist_ok=True)+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()+shell=ctypes.WinDLL('shell32');shell.CommandLineToArgvW.argtypes=[ctypes.c_wchar_p,ctypes.POINTER(ctypes.c_int)]+shell.CommandLineToArgvW.restype=ctypes.POINTER(ctypes.c_wchar_p);ctypes.windll.kernel32.LocalFree.argtypes=[ctypes.c_void_p]+def args(s):+ n=ctypes.c_int();p=shell.CommandLineToArgvW(s,ctypes.byref(n));a=[p[i] for i in range(n.value)];ctypes.windll.kernel32.LocalFree(p);return a+def unescape(s):return s.replace('$ ',' ').replace('$:',':').replace('$$','$')+tool=re.search(r'^CMAKE_MAKE_PROGRAM:FILEPATH=(.*)$',(CACHE/'CMakeCache.txt').read_text(encoding='utf8'),re.M).group(1)+ninja=(CACHE/'build.ninja').read_text(encoding='utf8');inputs={};sources={};commands=[];start=time.monotonic()+def protect(p):+ p=Path(p);p=p if p.is_absolute() else CACHE/p+ assert p.is_file(),p+ if str(p) not in inputs:inputs[str(p)]=sha(p)+ return p+def rule(name,objectsRequired=True):+ lines=re.search(r'^build '+re.escape(name)+r': .*?(?=\n\n)',ninja,re.M|re.S).group().splitlines()+ var=dict(re.match(r' ([A-Z_]+) = (.*)',l).groups() for l in lines[1:] if re.match(r' ([A-Z_]+) = (.*)',l))+ objects=[unescape(n).replace('\\','/') for n in lines[0].split('Release ',1)[1].split(' | ',1)[0].split(' ')]+ if objectsRequired:+ for p in objects:protect(p)+ for value in args(unescape(var.get('LINK_LIBRARIES',''))):+ if value.lower().endswith('.lib') and (Path(value).is_file() or (CACHE/value).is_file()):protect(value)+ return objects,var+def compiler(name):+ return args(subprocess.check_output([tool,'-t','commands',name],cwd=CACHE,text=True,encoding='utf8').splitlines()[-1])+env=dict(os.environ);env.update(TEMP=str(TMP),TMP=str(TMP))+setup=subprocess.run(['cmd.exe','/u','/d','/c',r'call C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Auxiliary\Build\vcvars64.bat >nul && set'],capture_output=True,text=True,encoding='utf-16-le',env=env,check=True)+for line in setup.stdout.splitlines():+ if '=' in line:+ key,value=line.split('=',1)+ if key and not key.startswith('='):env[key]=value+env.update(TEMP=str(TMP),TMP=str(TMP))+def run(command,name):+ commands.append(command);remaining=890-(time.monotonic()-start);assert remaining>0+ with (LOG/(name+'.log')).open('wb') as stream:r=subprocess.run(command,cwd=CACHE,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=min(300,remaining))+ print(name,'exit',r.returncode,flush=True)+ if r.returncode:print((LOG/(name+'.log')).read_text(encoding='utf8',errors='replace')[-5000:]);raise SystemExit(r.returncode)+def compile(source,name,a):+ sources[str(source)]=sha(source);target=OUT/(name+'.obj')+ command=a[:1]+['/I'+str(ROOT/'include')]+[v for v in a[1:-1] if not v.startswith(('/Fo','/Fd')) and v!='/showIncludes']+ run(command+['/Fo'+str(target),'/Fd'+str(OUT/(name+'.pdb')),str(source)],'compile-'+name)+ return target++# The cached CMake build predates HDR compatibility and the BMD follow-up.+# Retain ALL current-main overrides, verifying sources and immutable objects.+previous=json.loads((BASE/'logs/hdr-fg-toggle-20261009/build-20261009-113817/receipt.json').read_text(encoding='utf8'))+overrides={}+for name,row in previous['overrides'].items():+ if name.endswith(('QmlPlayerBridge.cpp.obj','qrc_veyra_i18n.cpp.obj')):continue+ source=name.split('.dir/',1)[1][:-4]+ if source.startswith(('src/','apps/')):+ original=next((p for p in previous['sources'] if p.replace('\\','/').endswith('/'+source)),None)+ assert original and sha(ROOT/source)==previous['sources'][original],source+ sources[str(ROOT/source)]=sha(ROOT/source)+ assert sha(Path(row['path']))==row['sha256'],name+ overrides[name]=protect(row['path'])+for relative in ('src/engine/Subtitles.cpp','src/ui/QmlPlayerBridge.cpp'):+ group='veyra_engine' if relative.startswith('src/engine/') else 'veyra_qml_bridge'+ name=f'CMakeFiles/{group}.dir/{relative}.obj'+ overrides[name]=compile(ROOT/relative,Path(relative).stem,compiler(name))+sources[str(ROOT/'include/veyra/engine/Subtitles.h')]=sha(ROOT/'include/veyra/engine/Subtitles.h')++gui=rule('veyra_qml_ui.exe')+resource=next(p for p in gui[0] if p.endswith('/qrc_veyra_i18n.cpp.obj'))+lines=subprocess.check_output([tool,'-t','commands',resource],cwd=CACHE,text=True,encoding='utf8').splitlines()+rccLine=next(l for l in lines if 'rcc.exe' in l.lower() and 'veyra_i18n' in l)+rcc=next(a for part in args(rccLine) for a in args(part) if a.lower().endswith('rcc.exe'))+qrc=OUT/'i18n.qrc';qrc.write_text('<RCC><qresource prefix="/i18n"><file alias="catalog.json">'+(ROOT/'i18n/catalog.json').as_posix()+'</file></qresource></RCC>',encoding='utf8')+generated=OUT/'qrc_veyra_i18n.cpp';run([rcc,'--name','veyra_i18n','--no-zstd','-o',str(generated),str(qrc)],'generate-i18n')+sources[str(ROOT/'i18n/catalog.json')]=sha(ROOT/'i18n/catalog.json')+overrides[resource]=compile(generated,'qrc_veyra_i18n',compiler(resource))+core=[p for name,p in overrides.items() if name.startswith(('CMakeFiles/veyra_engine.','CMakeFiles/veyra_sources.'))]+assert any(p.name=='Subtitles.obj' for p in core) and len(core)==11++cmake=r'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'+link=r'C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Tools\MSVC\1444~1.352\bin\Hostx64\x64\link.exe'+executables=[]+def linkTarget(name,objects,variables):+ rsp=OUT/(name+'.rsp')+ rsp.write_text('\n'.join(subprocess.list2cmdline([str(p)]) for p in objects)+'\n'+unescape(variables.get('LINK_PATH',''))+'\n'+unescape(variables['LINK_LIBRARIES']),encoding='utf8')+ directory=OUT/('manifest-'+name);directory.mkdir(exist_ok=True)+ flags=[('/MANIFESTINPUT:'+str(CACHE/'veyra-qml.manifest')) if a.startswith('/MANIFESTINPUT:') else a for a in args(unescape(variables.get('LINK_FLAGS','')))]+ protect(CACHE/'veyra-qml.manifest')+ command=[cmake,'-E','vs_link_exe','--msvc-ver=1944','--intdir='+str(directory),r'--rc=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\rc.exe',r'--mt=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\mt.exe','--manifests','--',link,'/nologo','@'+str(rsp),'/out:'+str(OUT/(name+'.exe')),'/implib:'+str(OUT/(name+'.lib')),'/pdb:'+str(OUT/(name+'.pdb')),'/version:0.0']+flags+ run(command,'link-'+name);executables.append(OUT/(name+'.exe'))+linkTarget('veyra_qml_ui',list(overrides.values())+[CACHE/p for p in gui[0] if p not in overrides],gui[1])+for target in ('bitmap','loading','text','overlay'):+ objectNames,var=rule(f'veyra_{"bitmap_subtitle" if target=="bitmap" else "subtitle_"+target}_tests.exe',False)+ assert len(objectNames)==1,objectNames+ source=ROOT/objectNames[0].split('.dir/',1)[1][:-4]+ obj=compile(source,'test-'+target,compiler(objectNames[0]))+ linkTarget('subtitle-'+target+'-tests',core+[obj],var)+objects,var=rule('veyra_bitmap_subtitle_tests.exe',False)+obj=compile(ROOT/'tests/integration/SubtitleFormatTests.cpp','test-formats',compiler(objects[0]))+linkTarget('subtitle-format-tests',core+[obj],var)+for p,d in inputs.items():assert sha(Path(p))==d,p+for relative in ('CMakeLists.txt','qml/Veyra/DialogHost.qml'):sources[str(ROOT/relative)]=sha(ROOT/relative)+receipt={'commands':commands,'sources':sources,'overrides':{n:{'path':str(p),'sha256':sha(p)} for n,p in overrides.items()},'inputsUnchanged':inputs,'seconds':time.monotonic()-start,'executables':{p.name:sha(p) for p in executables}}+(LOG/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+(BASE/'reports'/TASK/'build-current.json').write_text(json.dumps({'receipt':str(LOG/'receipt.json')},indent=2),encoding='utf8')+print('Built current-main GUI and subtitle tests; original inputs unchanged;',LOG,flush=True)diff --git a/scripts/acceptance/subtitle-formats-control.py b/scripts/acceptance/subtitle-formats-control.pynew file mode 100644index 00000000..5545d0c6--- /dev/null+++ b/scripts/acceptance/subtitle-formats-control.py@@ -0,0 +1,39 @@+"""Verify the immutable pre-task worktrees and the explicit subtitle scope."""+from pathlib import Path+import hashlib+import json+import re+import subprocess+import sys++ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='subtitle-formats-20261009'+start=json.loads((BASE/'archives'/TASK/'start.json').read_text(encoding='utf8'))+def git(*args,cwd=ROOT):return subprocess.check_output(['git',*args],cwd=cwd)+def sha(p):+ with p.open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()+for name,record in start['worktrees'].items():+ path=Path(name)+ assert git('rev-parse','HEAD',cwd=path).decode().strip()==record['head'],name+ assert hashlib.sha256(git('status','--porcelain=v1','-z',cwd=path)).hexdigest()==record['statusSha256'],name+ for relative,digest in record['dirtyFiles'].items():+ file=path/relative+ assert (sha(file) if file.is_file() else None)==digest,str(file)+assert git('branch','--show-current').decode().strip()=='codex/'+TASK+allowed={'AGENTS.md','CMakeLists.txt','THIRD_PARTY_NOTICES.md','docs/WORKLOG.md',+ 'docs/SUBTITLE_FORMATS_PLAN_2026-10-09.md','docs/SUBTITLE_FORMATS_REPORT_2026-10-09.md',+ 'i18n/catalog.json','include/veyra/engine/Subtitles.h','qml/Veyra/DialogHost.qml',+ 'scripts/ffmpeg/README.md','scripts/ffmpeg/prepare-slice-build.py','scripts/package-ffmpeg-source.py','scripts/package-qml-release.py',+ 'src/engine/Subtitles.cpp','src/ui/QmlPlayerBridge.cpp','tests/integration/SubtitleFormatTests.cpp',+ 'tests/integration/SubtitleLoadingTests.cpp','tests/integration/SubtitleOverlayTests.cpp',+ 'scripts/tests/make-subtitle-format-fixtures.py',+ 'scripts/acceptance/subtitle-formats-build.py','scripts/acceptance/subtitle-formats-test.py',+ 'scripts/acceptance/subtitle-formats-gui-test.py','scripts/acceptance/subtitle-formats-control.py'}+dirty={name.decode('utf8') for name in git('ls-files','-m','-d','--others','--exclude-standard','-z').split(b'\0') if name}+assert dirty<=allowed,dirty-allowed+changed={name.decode('utf8') for name in git('diff','--name-only',start['mainHead']).splitlines() if name}+assert changed<=allowed,changed-allowed+git('diff','--check');git('diff','--cached','--check')+label=sys.argv[1] if len(sys.argv)>1 else 'audit';assert re.fullmatch('[a-z0-9-]+',label)+report={'baselineWorktreesUnchanged':len(start['worktrees']),'dirtyFilesUnchanged':sum(len(row['dirtyFiles']) for row in start['worktrees'].values()),'scopePass':True,'changed':sorted(changed|dirty),'mainHead':start['mainHead']}+(BASE/'reports'/TASK/(label+'.json')).write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf8')+print(json.dumps(report,ensure_ascii=False),flush=True)diff --git a/scripts/acceptance/subtitle-formats-gui-test.py b/scripts/acceptance/subtitle-formats-gui-test.pynew file mode 100644index 00000000..a8db0e08--- /dev/null+++ b/scripts/acceptance/subtitle-formats-gui-test.py@@ -0,0 +1,155 @@+"""Real QML bridge checks in one private, hardlinked app and private profiles."""+from pathlib import Path+import hashlib+import json+import os+import re+import shutil+import subprocess+import sys+import time+import psutil++ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='subtitle-formats-20261009'+DONOR=BASE/'test-packages/vfg-next-20261007/Veyra-2.0.6-VFG-next-NVIDIA-win64-portable'+APP=BASE/'tests'/TASK/'app';BUILD=BASE/'build'/TASK;FIX=BASE/'tests'/TASK/'formats'+FFMPEG=BASE/'deps'/('ffmpeg-'+TASK)/'installed/bin'+case=sys.argv[1];assert case in ('embedded','external','sidecar','english')+LOG=BASE/'logs'/TASK/('gui-'+case+'-'+time.strftime('%Y%m%d-%H%M%S'));LOG.mkdir(parents=True,exist_ok=False)+TMP=BASE/'tmp'/TASK/LOG.name;TMP.mkdir(parents=True,exist_ok=False)+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()+manifest=json.loads((DONOR/'package-manifest.json').read_text(encoding='utf8'))+def verify():+ for row in manifest['files']:assert sha(DONOR/row['path'])==row['sha256'],row['path']+verify()+for proc in psutil.process_iter(['pid','name']):+ name=(proc.info['name'] or '').lower()+ assert not name.startswith(('veyra','fg-presentation','flash-pixel')),f'Player already running: {name} {proc.pid}'+if not APP.exists():+ APP.mkdir(parents=True)+ for row in manifest['files']:+ rel=Path(row['path'])+ if rel.parts[0] in ('runtime_local','logs') or rel.name=='veyra_qml_ui.exe':continue+ target=APP/rel;target.parent.mkdir(parents=True,exist_ok=True)+ if rel.as_posix()=='qml/Veyra/Main.qml':shutil.copy2(DONOR/rel,target)+ else:os.link(DONOR/rel,target)+ (APP/'runtime_local').mkdir(exist_ok=True)+def replace(source,target):+ target.parent.mkdir(parents=True,exist_ok=True)+ swap=target.with_name(target.name+'.swap');shutil.copy2(source,swap);os.replace(swap,target)+for rel in ('veyra_qml_ui.exe','qml/Veyra/SettingsPage.qml','qml/Veyra/DialogHost.qml'):+ replace(BUILD/rel if rel.endswith('.exe') else ROOT/rel,APP/rel)+for source in FFMPEG.glob('*.dll'):replace(source,APP/source.name)+for source,relative in (+ (FFMPEG.parent/'share/ffmpeg/veyra-local-build.json','licenses/FFMPEG-VEYRA-BUILD.json'),+ (FFMPEG.parent/'share/zlib/copyright','licenses/ZLIB-COPYRIGHT.txt'),+ (FFMPEG.parent/'share/zlib/vcpkg.spdx.json','licenses/ZLIB-SPDX.json'),+ (ROOT/'THIRD_PARTY_NOTICES.md','THIRD_PARTY_NOTICES.md'),+):replace(source,APP/relative)+profile=BASE/'tests'/TASK/'profiles'/LOG.name;profile.mkdir(parents=True,exist_ok=False)+(profile/'qml-preferences.v1.json').write_text(json.dumps({'language':'en' if case=='english' else 'zh-CN','gpuPriority':'normal','autoResume':False,'prewarmEnhancement':False,'subtitleEnabled':True,'sentinel':'preserved'}),encoding='utf8')+media=BASE/'downloads'/TASK/'pgs-real.mkv'+if case=='sidecar':+ folder=BASE/'tests'/TASK/'sidecar';folder.mkdir(exist_ok=True)+ media=folder/'movie.mkv'+ if not media.exists():os.link(BASE/'tests/5060-presets-subtitles-20260918/bitmap.mkv',media)+ replace(FIX/'bitmap.sup',folder/'movie.sup')+env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_','QSG_'))}+env.update(PATH=str(APP)+os.pathsep+env['PATH'],TEMP=str(TMP),TMP=str(TMP),CUDA_CACHE_PATH=str(TMP/'cuda-cache'),QML_DISK_CACHE_PATH=str(TMP/'qml-cache'),QT_FORCE_STDERR_LOGGING='1',VEYRA_LOG_FILE=str(LOG/'engine.log'))+timer=r'''+ property int subTestStep: 0+ property int subTestTicks: 0+ property int subTestBase: 0+ function subTestFail(message) { console.error("SUBGUI_FAIL", message); subTestTimer.stop() }+ function subTestCheck(ok, message) { if (!ok) { subTestFail(message); return false }; console.log("SUBGUI_CHECK", message); return true }+ function subTestFind(item, name) {+ if(item.objectName === name) return item+ if(item.children) for(let k=0;k<item.children.length;++k) { const found=subTestFind(item.children[k],name); if(found)return found }+ return null+ }+ Timer {+ id: subTestTimer; interval: 200; repeat: true; running: true+ onTriggered: {+ ++root.subTestTicks+ if(root.subTestTicks>85) { root.subTestFail("timeout step="+root.subTestStep); return }+ const mode=MODE+ const tracks=veyra.subtitleTracks+ if(root.subTestStep===0) {+ if(!veyra.running || !tracks.length || !tracks.every(t=>t.usable)) return+ if(!root.subTestCheck(!veyra.preferences.hdrFgCompatibility,"HDR compatibility stays off by default"))return+ if(!root.subTestCheck(tracks.every(t=>t.note.indexOf("不可用")<0),"decoded PGS is selectable"))return+ console.log("SUBGUI_TRACKS",JSON.stringify(tracks))+ if(mode==="sidecar") {+ if(!root.subTestCheck(tracks.length===2 && !tracks[0].embedded && tracks[1].embedded,"same-name bitmap file is loaded beside embedded PGS"))return+ } else if(!root.subTestCheck(tracks.length===1 && tracks[0].embedded,"compressed PGS is available in the actual player"))return+ if(!veyra.paused)veyra.togglePlayPause()+ veyra.seekTo(2)+ root.subTestBase=tracks.length+ if(mode==="external") {+ const start=Date.now()+ if(!root.subTestCheck(veyra.loadSubtitleFile(VOBSUB),"external load accepted"))return+ if(!root.subTestCheck(Date.now()-start<100,"external load returns without blocking QML"))return+ root.subTestStep=1;return+ }+ if(mode==="english") {+ veyra.loadSubtitleFile(BROKEN);root.subTestStep=7;return+ }+ veyra.subtitlePrimary=0;veyra.subtitleOffsetMs=250+ if(!root.subTestCheck(veyra.subtitleTracks[0].offsetMs===250,"PGS offset applies to selected track"))return+ root.subTestStep=9+ } else if(root.subTestStep===1) {+ if(tracks.length!==root.subTestBase+2)return+ if(!root.subTestCheck(!tracks[0].embedded&&!tracks[1].embedded&&tracks[0].usable&&tracks[1].usable,"both VobSub languages enter the list"))return+ veyra.subtitlePrimary=1;veyra.subtitleOffsetMs=375+ veyra.subtitlePrimary=0;veyra.subtitleOffsetMs=-250;veyra.subtitleSecondary=1+ if(!root.subTestCheck(veyra.subtitlePrimary===0&&veyra.subtitleSecondary===1&&veyra.subtitleTracks[0].offsetMs===-250&&veyra.subtitleTracks[1].offsetMs===375,"primary secondary and per-track offsets remain independent"))return+ veyra.loadSubtitleFile(BROKEN);root.subTestStep=2+ } else if(root.subTestStep===2) {+ if(veyra.subtitleStatus.indexOf("加载失败")<0)return+ if(!root.subTestCheck(tracks.length===root.subTestBase+2&&veyra.subtitlePrimary===0,"bad file preserves current subtitles"))return+ veyra.loadSubtitleFile(UNICODE);root.subTestStep=3+ } else if(root.subTestStep===3) {+ if(tracks.length!==root.subTestBase+3)return+ if(!root.subTestCheck(tracks[0].usable&&!tracks[0].embedded&&tracks[0].label.indexOf("中文")>=0,"manual Unicode text file loads asynchronously"))return+ veyra.loadSubtitleFile(SUP)+ veyra.openPath(MEDIA)+ root.subTestStep=4+ } else if(root.subTestStep===4) {+ if(!veyra.running || tracks.length!==1 || !tracks[0].embedded || !tracks[0].usable)return+ if(!root.subTestCheck(tracks.every(t=>t.embedded),"source change cancels pending external addition"))return+ root.subTestStep=9+ } else if(root.subTestStep===7) {+ if(veyra.subtitleStatus.indexOf("loading failed")<0)return+ if(!root.subTestCheck(veyra.subtitleStatus.indexOf("Subtitle decoding failed")>=0&&tracks.length===1,"final failure detail uses English catalog"))return+ root.subTestStep=9+ }+ if(root.subTestStep===9) {+ dialogs.open("subtitle");root.subTestStep=10;return+ }+ if(root.subTestStep===10) {+ const dialog=root.subTestFind(dialogs,"subtitle-dialog")+ if(!root.subTestCheck(dialog&&dialog.trackOptions.length===veyra.subtitleTracks.length+1&&dialog.trackOptions.slice(1).every(t=>!t.disabled),"actual subtitle dialog exposes usable tracks"))return+ root.contentItem.grabToImage(result=>result.saveToFile(SCREENSHOT))+ console.log("SUBGUI_PASS",mode);subTestTimer.stop()+ }+ }+ }+'''+replacements={'MODE':case,'VOBSUB':str(FIX/'vobsub.idx'),'BROKEN':str(FIX/'broken.sup'),'UNICODE':str(FIX/'中文 路径.srt'),'SUP':str(FIX/'bitmap.sup'),'MEDIA':str(media),'SCREENSHOT':str(LOG/'subtitle-dialog.png')}+for token,value in replacements.items():timer=timer.replace(token,json.dumps(value.replace('\\','/'),ensure_ascii=False))+main=APP/'qml/Veyra/Main.qml';original=main.read_bytes()+assert original.decode('utf8').count(' id: root')==1+swap=main.with_suffix('.swap');swap.write_text(original.decode('utf8').replace(' id: root',' id: root'+timer,1),encoding='utf8');os.replace(swap,main)+command=[str(APP/'veyra_qml_ui.exe'),'--data-dir',str(profile),'--page','pro','--size','1280x800','--exit-after','20000',str(media)]+start=time.monotonic()+try:+ with (LOG/'console.log').open('wb') as stream:run=subprocess.run(command,cwd=APP,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=40)+finally:+ swap=main.with_suffix('.swap');swap.write_bytes(original);os.replace(swap,main)+verify()+text=(LOG/'console.log').read_text(encoding='utf8',errors='replace')+errors=[l for l in text.splitlines() if re.search(r'SUBGUI_FAIL|ReferenceError:|TypeError:|\[ERROR\s*\]|\[FATAL\s*\]|D3D12 ERROR|D3D12 CORRUPTION',l)]+receipt={'case':case,'command':command,'exit':run.returncode,'seconds':time.monotonic()-start,'errors':errors,'passed':'SUBGUI_PASS' in text and not errors and run.returncode==0,'events':[l for l in text.splitlines() if 'SUBGUI_' in l],'exeSha256':sha(APP/'veyra_qml_ui.exe'),'donorUnchanged':True}+(LOG/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+print(json.dumps(receipt,ensure_ascii=False,indent=2),flush=True)+raise SystemExit(not receipt['passed'])diff --git a/scripts/acceptance/subtitle-formats-test.py b/scripts/acceptance/subtitle-formats-test.pynew file mode 100644index 00000000..878c7d52--- /dev/null+++ b/scripts/acceptance/subtitle-formats-test.py@@ -0,0 +1,36 @@+"""Run actual subtitle decoders and the native subtitle raster, with bounded tests."""+from pathlib import Path+import hashlib+import json+import os+import subprocess+import time++BASE=Path('E:/项目/Veyra');TASK='subtitle-formats-20261009'+BUILD=BASE/'build'/TASK;FIXTURES=BASE/'tests'/TASK/'formats'+DONOR=BASE/'test-packages/vfg-next-20261007/Veyra-2.0.6-VFG-next-NVIDIA-win64-portable'+FFMPEG=BASE/'deps'/('ffmpeg-'+TASK)/'installed/bin'+LOG=BASE/'logs'/TASK/('tests-'+time.strftime('%Y%m%d-%H%M%S'));TMP=BASE/'tmp'/TASK/'tests'+LOG.mkdir(parents=True,exist_ok=False);TMP.mkdir(parents=True,exist_ok=True)+env=dict(os.environ);env.update(PATH=str(FFMPEG)+os.pathsep+str(DONOR)+os.pathsep+env['PATH'],TEMP=str(TMP),TMP=str(TMP))+commands=[('formats',[BUILD/'subtitle-format-tests.exe',FIXTURES,BASE/'downloads'/TASK/'pgs-real.mkv',BASE/'downloads'/TASK/'pgs-dragon.mkv']),+ ('overlay',[BUILD/'subtitle-overlay-tests.exe',FIXTURES/'bitmap.sup']),+ ('text',[BUILD/'subtitle-text-tests.exe',BASE/'tests/playback-smoothness-20261004/fixtures'])]+for kind in ('pgs','dvd','dvb'):+ name='bitmap.mkv' if kind=='pgs' else 'bitmap-'+kind+'.mkv'+ commands.append(('bitmap-'+kind,[BUILD/'subtitle-bitmap-tests.exe',BASE/'tests/5060-presets-subtitles-20260918'/name]))+# This fixture has two embedded languages plus its same-name external SRT.+commands.append(('loading',[BUILD/'subtitle-loading-tests.exe',BASE/'tests/playback-smoothness-20261004/fixtures/golden.mkv','3']))+results=[]+for name,values in commands:+ command=list(map(str,values));env['VEYRA_LOG_FILE']=str(LOG/(name+'-engine.log'))+ start=time.monotonic()+ with (LOG/(name+'.log')).open('wb') as stream:run=subprocess.run(command,cwd=TMP,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=180)+ text=(LOG/(name+'.log')).read_text(encoding='utf8',errors='replace')+ failures=[line for line in text.splitlines() if line.startswith('FAIL') or 'MISMATCH' in line]+ results.append({'name':name,'command':command,'exit':run.returncode,'seconds':time.monotonic()-start,'failures':failures,'assertions':sum(line.startswith('PASS') for line in text.splitlines()),'exeSha256':hashlib.sha256(Path(command[0]).read_bytes()).hexdigest()})+ print(name,'exit',run.returncode,'checks',results[-1]['assertions'],'failures',failures,flush=True)+(LOG/'receipt.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8')+(BASE/'reports'/TASK/'tests-current.json').write_text(json.dumps({'receipt':str(LOG/'receipt.json')},indent=2),encoding='utf8')+print(LOG,flush=True)+raise SystemExit(any(r['exit'] or r['failures'] for r in results))diff --git a/scripts/ffmpeg/README.md b/scripts/ffmpeg/README.mdindex a858b2d3..adfb9ea7 100644--- a/scripts/ffmpeg/README.md+++ b/scripts/ffmpeg/README.md@@ -12,3 +12,14 @@ The H.264 D3D12 backend uses `MAX_SLICES` from `libavcodec/h264dec.h` for its fi6. Build and run `veyra_hw_import_image_tests <1080p H.264 file> <image-prefix>`, HDR color tests, and the opt-in `veyra_ps5_hw_image_tests --last-paired-ps5 <image-prefix>`. The latter briefly connects the last DPAPI-saved PS5 and compares software/hardware decoding of the **same** compressed AU; never package its images or private logs.For a later release, pass the actual Veyra-patched source directory to `scripts/package-ffmpeg-source.py`; the stock vcpkg source directory must be rejected when the local-build record is present. Include the resulting corresponding-source archive, original licenses, original vcpkg SPDX (baseline provenance), and the extra Veyra build record. No FFmpeg DLL or copied dependency source is committed to Veyra Git.++For the 2026-10-09 compressed-subtitle repair, additionally pass `--zlib-prefix`+to `prepare-slice-build.py`. This changes only `--disable-zlib` to+`--enable-zlib`, using the existing static zlib 1.3.2 built with `/MD` and its+pkg-config metadata. Preserve dav1d's `PKG_CONFIG_PATH` in the child process.+The original MinGW pkg-config corrupts non-ASCII include paths on this machine;+an explicitly supplied E-drive junction alias is preserved by the helper. All+physical build/install/temp outputs remain under `E:/项目/Veyra/`.+Supply `--zlib-source` when packaging the corresponding source, and include+`share/zlib` notices/provenance. The baseline vcpkg FFmpeg SPDX identifies the+base port; the new `veyra-local-build.json` identifies the actual rebuilt DLLs.diff --git a/scripts/ffmpeg/prepare-slice-build.py b/scripts/ffmpeg/prepare-slice-build.pyindex 59a5061d..e5c563e1 100644--- a/scripts/ffmpeg/prepare-slice-build.py+++ b/scripts/ffmpeg/prepare-slice-build.py@@ -12,6 +12,8 @@ import shlexp = argparse.ArgumentParser()for name in ('reference-bin', 'source', 'build', 'prefix', 'msys', 'msvc-bin', 'nasm', 'output'):p.add_argument('--' + name, type=Path, required=True)+p.add_argument('--zlib-prefix', type=Path,+ help='Enable the existing static zlib dependency for compressed Matroska subtitles')a = p.parse_args()if '#define MAX_SLICES 256' not in (a.source / 'libavcodec/h264dec.h').read_text():raise SystemExit('Apply ps5-h264-slices.patch to a separate n9.0.1 source tree first')@@ -23,16 +25,31 @@ with os.add_dll_directory(str(a.reference_bin.resolve())):raise SystemExit('Unexpected reference license')config = lib.avcodec_configuration().decode()def posix(path):- value = path.resolve().as_posix()+ # Preserve an explicitly supplied junction alias. Some MinGW pkg-config+ # builds corrupt non-ASCII paths before MSVC receives the include flags.+ value = path.absolute().as_posix()return '/' + value[0].lower() + value[2:] if len(value) > 2 and value[1] == ':' else valueargs = shlex.split(config)ar = a.msys / 'usr/share/automake-1.18/ar-lib'-args = [('--prefix=' + a.prefix.resolve().as_posix() if x.startswith('--prefix=') else+args = [('--prefix=' + a.prefix.absolute().as_posix() if x.startswith('--prefix=') else'--ar=' + shlex.quote(posix(ar)) + ' lib.exe' if x.startswith('--ar=') else x) for x in args]+extra_environment = ''+if a.zlib_prefix:+ pc = a.zlib_prefix.absolute() / 'lib/pkgconfig/zlib.pc'+ if not pc.is_file() or not (a.zlib_prefix / 'include/zlib.h').is_file():+ raise SystemExit('zlib-prefix must contain matching headers and pkg-config metadata')+ args = ['--enable-zlib' if x == '--disable-zlib' else x for x in args]+ if '--enable-zlib' not in args:+ args.append('--enable-zlib')+ # The recorded pkg-config is a MinGW executable: its path-list separator+ # is ';'. Keep any existing path (dav1d) and do not modify global settings.+ extra_environment = ('export PKG_CONFIG_PATH=' + shlex.quote(pc.parent.as_posix())+ + '${PKG_CONFIG_PATH:+;"$PKG_CONFIG_PATH"}\n')a.build.mkdir(parents=True, exist_ok=True)a.output.parent.mkdir(parents=True, exist_ok=True)search = ':'.join(posix(x) for x in (a.msvc_bin, a.msys / 'usr/bin', a.nasm))script = ('#!/bin/bash\nset -eu\nexport PATH=' + shlex.quote(search) + ':"$PATH"\n'+ + extra_environment+ 'cd ' + shlex.quote(posix(a.build)) + '\n'+ shlex.quote(posix(a.source / 'configure')) + ' ' + shlex.join(args)+ '\nmake -j8\nmake install\n')diff --git a/scripts/package-ffmpeg-source.py b/scripts/package-ffmpeg-source.pyindex d8eb79c1..8d45e066 100644--- a/scripts/package-ffmpeg-source.py+++ b/scripts/package-ffmpeg-source.py@@ -14,6 +14,7 @@ parser.add_argument('--source', type=Path, required=True)parser.add_argument('--output', type=Path, required=True)parser.add_argument('--version', required=True)parser.add_argument('--dav1d-source', type=Path)+parser.add_argument('--zlib-source', type=Path)args = parser.parse_args()if args.output.exists():raise SystemExit('Output exists; choose a new candidate')@@ -50,6 +51,13 @@ with os.add_dll_directory(str((args.prefix / 'bin').resolve())):if license_name != 'LGPL version 2.1 or later':raise SystemExit(f'Unexpected library license: {license_name}')extra_sources = []+if '--enable-zlib' in configuration:+ if not args.zlib_source or not (args.zlib_source / 'LICENSE').is_file():+ raise SystemExit('The statically linked zlib requires its matching source and notices')+ notice = args.prefix / 'share/zlib'+ if not (notice / 'vcpkg.spdx.json').is_file():+ raise SystemExit('The zlib build provenance must accompany the corresponding source')+ extra_sources += [(args.zlib_source, 'zlib-source'), (notice, 'zlib-notices')]if '--enable-libdav1d' in configuration:if not args.dav1d_source or not (args.dav1d_source / 'COPYING').is_file():raise SystemExit('The linked dav1d requires its matching source and notices')@@ -60,7 +68,7 @@ if '--enable-libdav1d' in configuration:expected = next(c['checksumValue'] for c in item['checksums'] if c['algorithm'] == 'SHA256')if hashlib.sha256((dav1d_port / item['fileName']).read_bytes()).hexdigest() != expected.lower():raise SystemExit('dav1d port provenance mismatch')- extra_sources = [(args.dav1d_source, 'dav1d-source'), (dav1d_port, 'dav1d-vcpkg-port'),+ extra_sources += [(args.dav1d_source, 'dav1d-source'), (dav1d_port, 'dav1d-vcpkg-port'),(args.prefix / 'share/dav1d', 'dav1d-notices')]args.output.parent.mkdir(parents=True, exist_ok=True)with zipfile.ZipFile(args.output, 'x', compression=zipfile.ZIP_DEFLATED, compresslevel=7) as archive:@@ -96,6 +104,9 @@ with zipfile.ZipFile(args.output, 'x', compression=zipfile.ZIP_DEFLATED, compres'external libraries exactly as listed in binary-configuration.txt, no CLI programs).\n''When dav1d is enabled, dav1d-source and dav1d-vcpkg-port contain its source/recipe;\n''build and install it first, then configure FFmpeg with --enable-libdav1d.\n'+ 'When zlib is enabled, zlib-source/zlib-notices contain its matching source/provenance.\n'+ 'Build the static zlib library with the dynamic MSVC CRT (/MD), install its pkg-config file,\n'+ 'then add --enable-zlib using prepare-slice-build.py --zlib-prefix. No zlib DLL is needed.\n''See portfile.cmake and build.sh.in.\n''The recorded configuration includes original local build paths; adapt paths locally.\n''Veyra links dynamically; compatible rebuilt libraries may replace the shipped DLLs.\n'diff --git a/scripts/package-qml-release.py b/scripts/package-qml-release.pyindex 770b779a..22f95a8a 100644--- a/scripts/package-qml-release.py+++ b/scripts/package-qml-release.py@@ -129,10 +129,29 @@ def source_snapshot(output, label, app_sha):return dict(name=archive.name, sha256=digest(archive), files=len(records), completeCorrespondingSource=False)+def audit_ffmpeg(prefix):+ """Publisher check: an old cache must not silently drop compressed PGS."""+ build = json.loads((prefix / 'share/ffmpeg/veyra-local-build.json').read_text(encoding='utf-8-sig'))+ if '--enable-zlib' not in build.get('configuration', ''):+ raise ValueError('FFmpeg lacks compressed Matroska subtitle support; use the tested zlib-enabled prefix')+ if build['patchSha256'].lower() != digest(ROOT / 'scripts/ffmpeg/ps5-h264-slices.patch'):+ raise ValueError('PS5 FFmpeg patch provenance mismatch')+ for record in build['files']:+ if Path(record['name']).name != record['name'] or not record['name'].endswith('.dll'):+ raise ValueError('Invalid FFmpeg publisher manifest path')+ if digest(prefix / 'bin' / record['name']) != record['sha256'].lower():+ raise ValueError('Patched FFmpeg binary mismatch: ' + record['name'])+ for name in ('copyright','vcpkg.spdx.json'):+ if not (prefix / 'share/zlib' / name).is_file():+ raise ValueError('Missing zlib license or build provenance')+ return build++def main():p = argparse.ArgumentParser()p.add_argument('--verify', type=Path)p.add_argument('--build', type=Path)+ p.add_argument('--ffmpeg-root', type=Path, help='Tested patched FFmpeg prefix; overrides a historical build cache')p.add_argument('--runtime-source', type=Path)p.add_argument('--original-nr', type=Path, help='Approved original NR DLL, audited against the version runtime lock')p.add_argument('--legacy-licenses', type=Path)@@ -163,6 +182,9 @@ def main():notes = 'RELEASE_NOTES_' + version + '.md' if (ROOT / 'docs' / ('RELEASE_NOTES_' + version + '.md')).is_file() else 'RELEASE_NOTES_2.0.0.md'if not args.output.resolve().is_relative_to(ARTIFACTS.resolve()):raise ValueError('Candidate output must stay in the E: artifact tree')+ cache = (args.build / 'CMakeCache.txt').read_text(encoding='utf8')+ ffmpeg = args.ffmpeg_root or Path(re.search(r'^VEYRA_FFMPEG_ROOT:[^=]+=(.+)$', cache, re.M).group(1))+ ffbuild = audit_ffmpeg(ffmpeg)stage = args.output / ('Veyra-' + args.label + '-win64-portable')archive = Path(str(stage) + '.zip')if stage.exists() or archive.exists():@@ -202,8 +224,6 @@ def main():for option in ('VEYRA_BUILD_QML_UI', 'VEYRA_ENABLE_REMOTEPLAY', 'VEYRA_ENABLE_MOONLIGHT', 'VEYRA_ENABLE_XBOX'):if not re.search(r'^' + option + r':BOOL=ON$', cache, re.M):raise ValueError('Missing full product build option: ' + option)- ffmpeg = Path(re.search(r'^VEYRA_FFMPEG_ROOT:[^=]+=(.+)$', cache, re.M).group(1))- ffbuild = json.loads((ffmpeg / 'share/ffmpeg/veyra-local-build.json').read_text(encoding='utf-8-sig'))if ffbuild['patchSha256'].lower() != digest(ROOT / 'scripts/ffmpeg/ps5-h264-slices.patch'):raise ValueError('PS5 FFmpeg patch provenance mismatch')for record in ffbuild['files']:@@ -265,6 +285,8 @@ foreach($f in $lock.files) {tree(args.qt_licenses, 'licenses/qt')tree(args.qt / 'sbom', 'licenses/qt/sbom')copy(ffmpeg / 'share/ffmpeg/veyra-local-build.json', 'licenses/FFMPEG-VEYRA-BUILD.json')+ copy(ffmpeg / 'share/zlib/copyright', 'licenses/ZLIB-COPYRIGHT.txt')+ copy(ffmpeg / 'share/zlib/vcpkg.spdx.json', 'licenses/ZLIB-SPDX.json')# Use a known Microsoft redistributable installation, not arbitrary PATH DLLs.redist = Path('C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/VC/Redist/MSVC')crt = sorted((f for f in redist.iterdir() if re.fullmatch(r'\d+\.\d+\.\d+', f.name)),diff --git a/scripts/tests/make-subtitle-format-fixtures.py b/scripts/tests/make-subtitle-format-fixtures.pynew file mode 100644index 00000000..a370efd7--- /dev/null+++ b/scripts/tests/make-subtitle-format-fixtures.py@@ -0,0 +1,133 @@+"""Small authored subtitle fixtures; no media or dependency enters source Git.++The compressed and BlockDuration MKVs are independent Matroska writers so the+test does not depend on the same demuxer/muxer applying matching assumptions.+"""+import argparse+import json+from pathlib import Path+import struct+import subprocess+import sys+import zlib++p = argparse.ArgumentParser()+p.add_argument('--output', type=Path, required=True)+p.add_argument('--dvd-fixture', type=Path, required=True, help='Authored bitmap fixture encoded as DVD subtitles')+a = p.parse_args()+root = a.output+root.mkdir(parents=True, exist_ok=True)+subprocess.run([sys.executable, str(Path(__file__).with_name('make-bitmap-subtitle-fixture.py')),+ str(root / 'bitmap.sup')], check=True)+(root / 'bitmap.pgs').write_bytes((root / 'bitmap.sup').read_bytes())+++def element(tag, data):+ if isinstance(data, str):+ data = data.encode('utf8')+ if isinstance(data, int):+ data = data.to_bytes(max(1, (data.bit_length() + 7) // 8), 'big')+ length = len(data)+ size = next(n for n in range(1, 9) if length < (1 << (7*n)) - 1)+ return tag.to_bytes((tag.bit_length()+7)//8, 'big') + ((1 << (7*size)) | length).to_bytes(size, 'big') + data+++sets = {}+data = (root / 'bitmap.sup').read_bytes()+while data:+ assert data[:2] == b'PG'+ pts, _, kind, size = struct.unpack('>IIBH', data[2:13])+ sets.setdefault(round(pts/90), bytearray()).extend(data[10:13+size])+ data = data[13+size:]+++def matroska(name, compressed=False, duration=False, corrupt=False, languages=1):+ ebml = element(0x1A45DFA3, b''.join(element(t, v) for t, v in+ [(0x4286, 1), (0x42F7, 1), (0x42F2, 4), (0x42F3, 8),+ (0x4282, 'matroska'), (0x4287, 4), (0x4285, 2)]))+ info = element(0x1549A966, element(0x2AD7B1, 1000000) + element(0x4489, struct.pack('>d', 8000))+ + element(0x4D80, 'subtitle fixture') + element(0x5741, 'subtitle fixture'))+ tracks = b''+ for index in range(1, languages+1):+ entry = b''.join(element(t, v) for t, v in [(0xD7,index),(0x73C5,index),(0x83,17),+ (0x86,'S_HDMV/PGS'),(0x22B59C,'zho' if index==1 else 'eng'),(0x536E,f'PGS {index}')])+ if compressed:+ entry += element(0x6D80, element(0x6240, element(0x5031,0) + element(0x5032,1)+ + element(0x5033,0) + element(0x5034,element(0x4254,0))))+ tracks += element(0xAE, entry)+ cluster = element(0xE7, 0)+ for time, payload in sets.items():+ if duration and time in (3000, 7000):+ continue # Deliberately no later clear set.+ for index in range(1, languages+1):+ value = b'\x16\xff\xff\x00' if corrupt else bytes(payload)+ if compressed:+ value = zlib.compress(value)+ block = bytes([0x80 | index]) + struct.pack('>hB', time, 0) + value+ cluster += element(0xA0, element(0xA1,block) + (element(0x9B,2000) if duration else b''))+ segment = info + element(0x1654AE6B,tracks) + element(0x1F43B675,cluster)+ (root/name).write_bytes(ebml + element(0x18538067,segment))+++matroska('compressed.mkv', compressed=True, languages=5)+matroska('plain.mkv', languages=5)+matroska('duration-only.mkv', duration=True)+matroska('corrupt.mkv', corrupt=True)++texts = {+ 'microdvd.sub': '{1}{1}25.000\n{25}{75}First|Two\n{125}{175}Second\n',+ 'mpl2.mpl': '[10][30]First|Two\n[50][70]Second\n',+ 'subviewer.sub': '[INFORMATION]\n[TITLE]Test\n[END INFORMATION]\n[SUBTITLE]\n'+ '00:00:01.00,00:00:03.00\nFirst[br]Two\n\n00:00:05.00,00:00:07.00\nSecond\n',+ 'subviewer.sbv': '0:00:01.000,0:00:03.000\nFirst[br]Two\n\n0:00:05.000,0:00:07.000\nSecond\n',+ 'spruce.stl': '$FontName = Arial\n00:00:01:00 , 00:00:03:00 , First|Two\n00:00:05:00 , 00:00:07:00 , Second\n',+ 'sami.smi': '<SAMI>\n<HEAD><STYLE TYPE="text/css">.ENCC {Name: English; lang: en-US; SAMIType: CC;}</STYLE></HEAD>\n'+ '<BODY>\n<SYNC Start=1000><P Class=ENCC>First<br>Two\n<SYNC Start=3000><P Class=ENCC> \n'+ '<SYNC Start=5000><P Class=ENCC>Second\n<SYNC Start=7000><P Class=ENCC> \n</BODY></SAMI>\n',+ '中文 路径.srt': '1\n00:00:01,000 --> 00:00:03,000\n中文,第一行\nEnglish, second line\n\n'+ '2\n00:00:05,000 --> 00:00:07,000\nSecond\n',+ 'broken.sup': 'PG truncated',+ 'missing.idx': '# VobSub index file, v7 (do not modify this line!)\n',+}+for name, text in texts.items():+ (root/name).write_text(text,encoding='utf8',newline='\n')+(root/'sami.sami').write_bytes((root/'sami.smi').read_bytes())+(root/'字幕.txt').write_bytes((root/'中文 路径.srt').read_bytes())+(root/'orphan.sub').write_bytes(b'\0\0\1\xba'+b'\0'*12)+with (root/'oversized.srt').open('wb') as oversized:+ oversized.truncate(17*1024*1024)++# VobSub stores DVD subtitle PES packets in .sub and language/timestamps in+# .idx. Each fixture language has its own substream ID and file positions.+probe = json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','s',+ '-show_packets','-show_streams','-show_data','-of','json',str(a.dvd_fixture)]))+++def unhex(dump):+ return bytes.fromhex(''.join(line.split(':',1)[1].split(' ',1)[0].replace(' ','')+ for line in dump.splitlines() if ':' in line))+++payloads = [unhex(packet['data']) for packet in probe['packets']]+assert len(payloads) == 2+header = unhex(probe['streams'][0]['extradata']).decode('ascii').rstrip('\0')+ps = bytearray()+positions = {0:[],1:[]}+for at, payload in zip((1,5),payloads):+ for language in (0,1):+ positions[language].append(len(ps))+ pts = at*90000+ stamp = bytes([0x21|((pts>>29)&14),(pts>>22)&255,((pts>>14)&254)|1,(pts>>7)&255,((pts<<1)&254)|1])+ body = b'\x80\x80\x05'+stamp+bytes([0x20+language])+payload+ ps += bytes.fromhex('000001ba44000400040189c3f800') + b'\0\0\1\xbd'+struct.pack('>H',len(body))+body+idx = '# VobSub index file, v7 (do not modify this line!)\n'+header+'\n'+for language, name in ((0,'zh'),(1,'en')):+ idx += f'id: {name}, index: {language}\n'+ for time, position in zip((1,5),positions[language]):+ idx += f'timestamp: 00:00:{time:02d}:000, filepos: {position:09x}\n'+(root/'vobsub.idx').write_text(idx,encoding='ascii')+(root/'vobsub.sub').write_bytes(ps)+(root/'oversized-vobsub.sub').write_bytes(ps)+with (root/'oversized-vobsub.idx').open('wb') as oversized:+ oversized.truncate(17*1024*1024)+print(root)diff --git a/src/engine/Subtitles.cpp b/src/engine/Subtitles.cppindex 99ede0d6..b8a92582 100644--- a/src/engine/Subtitles.cpp+++ b/src/engine/Subtitles.cpp@@ -19,7 +19,9 @@extern "C" {#include <libavcodec/avcodec.h>+#include <libavcodec/codec_desc.h>#include <libavformat/avformat.h>+#include <libavutil/error.h>#include <libavutil/channel_layout.h>#include <libavutil/mathematics.h>#include <libavutil/opt.h>@@ -316,15 +318,15 @@ void SubtitleTrack::rebuildIndex(){}bool isTextSubtitleCodec(const std::wstring& codec){- const auto name=lower(codec);- return name==L"subrip"||name==L"srt"||name==L"ass"||name==L"ssa"||name==L"mov_text"- ||name==L"webvtt"||name==L"text"||name==L"subviewer"||name==L"subviewer1"||name==L"microdvd";+ auto name=lower(codec);+ if(name==L"srt")name=L"subrip";+ const auto* descriptor=avcodec_descriptor_get_by_name(utf8(name).c_str());+ return descriptor&&(descriptor->props&AV_CODEC_PROP_TEXT_SUB)&&avcodec_find_decoder(descriptor->id);}-SubtitleTrack loadSubtitleFile(const std::wstring& path){+static SubtitleTrack loadTextSubtitleFile(const std::wstring& path){std::wstring data;if(!readTextFile(path,data)){- log::warn("subtitle",std::format("cannot read subtitle file (missing, empty, >{}MiB or not UTF-8/UTF-16LE): {}",kMaxSubtitleFileBytes>>20,utf8(std::filesystem::path(path).filename().wstring())));return {};}std::wstring extension=lower(std::filesystem::path(path).extension().wstring());@@ -345,6 +347,12 @@ SubtitleTrack loadSubtitleFile(const std::wstring& path){return track;}+SubtitleTrack loadSubtitleFile(const std::wstring& path){+ auto tracks=loadExternalSubtitleTracks(path);+ for(auto& track:tracks)if(track.usable())return std::move(track);+ return tracks.empty()?SubtitleTrack{}:std::move(tracks.front());+}+std::vector<const SubtitleCue*> cuesAt(const SubtitleTrack& track,double seconds,size_t limit){std::vector<const SubtitleCue*> found;if(track.starts.empty())return found;@@ -397,8 +405,8 @@ std::vector<uint32_t> SubtitleBitmap::pixels()const{return result;}-std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,std::stop_token stop,- const std::function<void(const std::vector<SubtitleTrack>&)>& metadata){+static std::vector<SubtitleTrack> loadDemuxedSubtitleTracks(const std::wstring& path,std::stop_token stop,+ const std::function<void(const std::vector<SubtitleTrack>&)>& metadata,const AVInputFormat* format=nullptr){std::vector<SubtitleTrack> tracks;if(stop.stop_requested())return tracks;const auto started=std::chrono::steady_clock::now();@@ -407,13 +415,18 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,sinput->interrupt_callback={[](void* opaque){return static_cast<std::stop_token*>(opaque)->stop_requested()?1:0;},&stop};struct InputCleanup {AVFormatContext*& input;~InputCleanup(){avformat_close_input(&input);}} cleanup{input};const auto utf8Path=utf8(path);- if(avformat_open_input(&input,utf8Path.c_str(),nullptr,nullptr)<0||!input){- log::warn("subtitle","cannot open media for embedded subtitle listing");+ const int openResult=avformat_open_input(&input,utf8Path.c_str(),format,nullptr);+ if(openResult<0||!input){+ log::warn("subtitle",std::format("open failed ret={} file={}",openResult,utf8(std::filesystem::path(path).filename().wstring())));return tracks;}- if(avformat_find_stream_info(input,nullptr)<0){+ const int infoResult=avformat_find_stream_info(input,nullptr);+ if(infoResult<0){+ log::warn("subtitle",std::format("stream info failed ret={}",infoResult));return tracks;}+ log::info("subtitle",std::format("scan file={} demuxer={} zlib={}",utf8(std::filesystem::path(path).filename().wstring()),+ input->iformat?input->iformat->name:"",std::strstr(avformat_configuration(),"--enable-zlib")!=nullptr));struct DecoderCleanup {void operator()(AVCodecContext* context)const{avcodec_free_context(&context);}};std::vector<std::unique_ptr<AVCodecContext,DecoderCleanup>> decoders;std::vector<int> streamToTrack(input->nb_streams,-1);@@ -453,7 +466,8 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,sstreamToTrack[streamIndex]=int(tracks.size());decoders.emplace_back();const auto codec=stream->codecpar->codec_id;- if(!isTextSubtitleCodec(track.codec)&&codec!=AV_CODEC_ID_HDMV_PGS_SUBTITLE&&codec!=AV_CODEC_ID_DVD_SUBTITLE&&codec!=AV_CODEC_ID_DVB_SUBTITLE){+ const auto* descriptor=avcodec_descriptor_get(codec);+ if(!descriptor||!(descriptor->props&(AV_CODEC_PROP_TEXT_SUB|AV_CODEC_PROP_BITMAP_SUB))){track.note=L"暂不支持此字幕格式";log::info("subtitle",std::format("embedded track {} codec={} listed as unsupported",streamIndex,codecName?codecName:""));tracks.push_back(std::move(track));@@ -462,13 +476,17 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,sconst AVCodec* decoder=avcodec_find_decoder(stream->codecpar->codec_id);AVCodecContext* context=decoder?avcodec_alloc_context3(decoder):nullptr;if(context){context->pkt_timebase=stream->time_base;}- if(!decoder||!context||avcodec_parameters_to_context(context,stream->codecpar)<0||avcodec_open2(context,decoder,nullptr)<0){- track.note=L"字幕解码器初始化失败";+ int initResult=!context?AVERROR(ENOMEM):avcodec_parameters_to_context(context,stream->codecpar);+ if(initResult>=0)initResult=avcodec_open2(context,decoder,nullptr);+ if(!decoder||initResult<0){+ track.note=decoder?L"字幕解码器初始化失败":L"缺少此字幕格式的解码器";+ log::warn("subtitle",std::format("decoder init stream={} codec={} present={} ret={}",streamIndex,codecName?codecName:"",decoder!=nullptr,initResult));if(context)avcodec_free_context(&context);tracks.push_back(std::move(track));continue;}decoders.back().reset(context);+ track.note=L"正在读取字幕";if((codec==AV_CODEC_ID_ASS||codec==AV_CODEC_ID_SSA)&&context->subtitle_header&&context->subtitle_header_size>0){auto ass=std::make_shared<SubtitleAssData>();ass->header.assign(reinterpret_cast<const char*>(context->subtitle_header),size_t(context->subtitle_header_size));@@ -488,23 +506,37 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,sstruct PacketCleanup {AVPacket*& packet;~PacketCleanup(){av_packet_free(&packet);}} packetCleanup{packet};constexpr size_t maxCacheBytes=64u*1024u*1024u;size_t cacheBytes=0,totalCues=0;uint64_t packets=0;+ struct DecodeStats {uint64_t packets=0,displays=0,errors=0;int lastError=0;};+ std::vector<DecodeStats> stats(tracks.size());int videoWidth=1920,videoHeight=1080;for(unsigned i=0;i<input->nb_streams;++i)if(input->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_VIDEO){videoWidth=std::max(1,input->streams[i]->codecpar->width);videoHeight=std::max(1,input->streams[i]->codecpar->height);break;}auto nextPublish=std::chrono::steady_clock::now()+std::chrono::milliseconds(250);- while(packet&&!stop.stop_requested()&&av_read_frame(input,packet)>=0){+ int readResult=0;+ while(packet&&!stop.stop_requested()&&(readResult=av_read_frame(input,packet))>=0){++packets;const int index=packet->stream_index>=0&&size_t(packet->stream_index)<streamToTrack.size()?streamToTrack[packet->stream_index]:-1;if(index<0||!decoders[index]){av_packet_unref(packet);continue;}auto& track=tracks[index];auto* context=decoders[index].get();+ auto& stat=stats[index];++stat.packets;+ const bool firstCue=track.cues.empty();const double timeBase=av_q2d(input->streams[packet->stream_index]->time_base);AVSubtitle subtitle{};int got=0;- if(avcodec_decode_subtitle2(context,&subtitle,&got,packet)<0||!got){avsubtitle_free(&subtitle);av_packet_unref(packet);continue;}+ const int decodeResult=avcodec_decode_subtitle2(context,&subtitle,&got,packet);+ if(decodeResult<0){+ ++stat.errors;stat.lastError=decodeResult;+ if(stat.errors<=3){char detail[AV_ERROR_MAX_STRING_SIZE]{};av_strerror(decodeResult,detail,sizeof(detail));+ log::warn("subtitle",std::format("decode failed stream={} codec={} ret={} detail={} pts={} size={}",+ track.streamIndex,utf8(track.codec),decodeResult,detail,packet->pts,packet->size));}+ }+ if(decodeResult<0||!got){avsubtitle_free(&subtitle);av_packet_unref(packet);continue;}+ ++stat.displays;const double packetSeconds=(subtitle.pts!=AV_NOPTS_VALUE?double(subtitle.pts)/AV_TIME_BASE:packet->pts==AV_NOPTS_VALUE?0:double(packet->pts)*timeBase);- const bool bitmapCodec=context->codec_id==AV_CODEC_ID_HDMV_PGS_SUBTITLE||context->codec_id==AV_CODEC_ID_DVD_SUBTITLE||context->codec_id==AV_CODEC_ID_DVB_SUBTITLE;+ const auto* descriptor=avcodec_descriptor_get(context->codec_id);+ const bool bitmapCodec=descriptor&&(descriptor->props&AV_CODEC_PROP_BITMAP_SUB);if(bitmapCodec){const double begin=packetSeconds+double(subtitle.start_display_time)/1000.0;// A new display set (including an empty clear set) replaces the old one.@@ -542,6 +574,12 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,sSubtitleCue cue;cue.begin=begin;cue.end=subtitle.end_display_time>subtitle.start_display_time&&subtitle.end_display_time!=UINT32_MAX?packetSeconds+double(subtitle.end_display_time)/1000.0:std::numeric_limits<double>::infinity();+ // Matroska BlockDuration is authoritative even when PGS has+ // no later clear set (the decoder itself has no end time).+ if(context->codec_id==AV_CODEC_ID_HDMV_PGS_SUBTITLE&&packet->duration>0&&packet->pts!=AV_NOPTS_VALUE){+ const double end=(double(packet->pts)+double(packet->duration))*timeBase;+ if(end>begin)cue.end=std::min(cue.end,end);+ }cue.bitmap=std::move(frame);if(totalCues<kMaxCues&&bytes<=maxCacheBytes-cacheBytes){cacheBytes+=bytes;++totalCues;track.cues.push_back(std::move(cue));}else track.note=L"字幕缓存已达上限,后续字幕未加载";@@ -576,7 +614,8 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,s}avsubtitle_free(&subtitle);av_packet_unref(packet);- if(metadata&&std::chrono::steady_clock::now()>=nextPublish){+ if(!track.cues.empty()&&track.note==L"正在读取字幕")track.note.clear();+ if(metadata&&((firstCue&&!track.cues.empty())||std::chrono::steady_clock::now()>=nextPublish)){for(auto& t:tracks)t.rebuildIndex();snapshotAss();metadata(tracks);@@ -584,21 +623,96 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,s}}if(stop.stop_requested())return {};+ if(readResult<0&&readResult!=AVERROR_EOF)log::warn("subtitle",std::format("scan read failed ret={}",readResult));snapshotAss();- for(auto& track:tracks){+ for(size_t i=0;i<tracks.size();++i){+ auto& track=tracks[i];const auto& stat=stats[i];+ if(track.note==L"正在读取字幕"){+ if(stat.errors)track.note=L"字幕数据解码失败(请查看日志)";+ else if(!stat.packets)track.note=L"没有读到字幕数据(请检查封装或压缩支持)";+ else track.note=L"未解码出可显示的字幕";+ }track.rebuildIndex();- log::info("subtitle",std::format("embedded track {} codec={} cues={}",track.streamIndex,utf8(track.codec),track.cues.size()));+ log::info("subtitle",std::format("track stream={} codec={} packets={} displays={} errors={} lastRet={} cues={} note={}",+ track.streamIndex,utf8(track.codec),stat.packets,stat.displays,stat.errors,stat.lastError,track.cues.size(),utf8(track.note)));}log::info("subtitle",std::format("single-pass complete tracks={} packets={} cues={} cacheBytes={} elapsedMs={:.3f}",tracks.size(),packets,totalCues,cacheBytes,std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-started).count()));return tracks;}+std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,std::stop_token stop,+ const std::function<void(const std::vector<SubtitleTrack>&)>& metadata){+ return loadDemuxedSubtitleTracks(path,stop,metadata);+}++std::vector<SubtitleTrack> loadExternalSubtitleTracks(const std::wstring& path,std::stop_token stop,+ const std::function<void(const std::vector<SubtitleTrack>&)>& metadata){+ if(stop.stop_requested())return {};+ auto source=std::filesystem::path(path);+ const auto extension=lower(source.extension().wstring());+ auto failure=[&](const wchar_t* note){+ SubtitleTrack track;track.name=source.filename().wstring();track.note=note;+ log::warn("subtitle",std::format("external file={} note={}",utf8(track.name),utf8(track.note)));+ return std::vector<SubtitleTrack>{std::move(track)};+ };+ std::error_code ec;+ if(!std::filesystem::is_regular_file(source,ec))return failure(L"字幕文件不存在或无法读取");+ // Keep the existing text-file memory bound when falling back to FFmpeg:+ // several text demuxers queue the entire file while reading the header.+ bool binarySub=false;+ if(extension==L".sub"){+ std::ifstream input(source,std::ios::binary);unsigned char head[3]{};+ input.read(reinterpret_cast<char*>(head),sizeof(head));+ binarySub=head[0]==0&&head[1]==0&&head[2]==1;+ }+ if(binarySub){+ source.replace_extension(L".idx");+ if(!std::filesystem::is_regular_file(source,ec))return failure(L"VobSub 需要同名 .idx 和 .sub 文件,请加载 .idx");+ }+ if(extension!=L".sup"&&extension!=L".pgs"){+ const auto bytes=std::filesystem::file_size(source,ec);+ if(!ec&&bytes>kMaxSubtitleFileBytes)return failure(L"文本字幕超过 16 MiB 上限");+ }+ if(extension==L".idx"){+ auto companion=source;companion.replace_extension(L".sub");+ if(!std::filesystem::is_regular_file(companion,ec))return failure(L"VobSub 需要同名 .idx 和 .sub 文件,请加载 .idx");+ }+ // .sub is ambiguous: MicroDVD text or the binary half of VobSub. Prefer+ // the existing text parser when it recognizes content; otherwise demux.+ const bool bitmapFile=extension==L".sup"||extension==L".pgs"||extension==L".idx"||binarySub;+ if(!bitmapFile){+ auto track=loadTextSubtitleFile(path);+ if(stop.stop_requested())return {};+ if(track.usable())return {std::move(track)};+ }+ auto externalize=[&](std::vector<SubtitleTrack> tracks){+ for(auto& track:tracks){+ track.embedded=false;+ track.name=source.filename().wstring()+(track.language.empty()?L"":L" · "+track.language);+ }+ return tracks;+ };+ const char* demuxer=extension==L".sup"||extension==L".pgs"?"sup":+ extension==L".idx"||binarySub?"vobsub":extension==L".mpl"?"mpl2":+ extension==L".smi"||extension==L".sami"?"sami":extension==L".stl"?"stl":+ extension==L".sbv"?"subviewer":nullptr;+ // Small, valid MPL2 files otherwise fail FFmpeg's multi-line probe and can+ // be mistaken for LRC. The explicit file type chooses its existing reader.+ auto tracks=loadDemuxedSubtitleTracks(source.wstring(),stop,[&](const auto& listing){+ if(metadata)metadata(externalize(listing));+ },demuxer?av_find_input_format(demuxer):nullptr);+ if(stop.stop_requested())return {};+ if(tracks.empty())return failure(L"文件格式不支持、数据损坏或没有字幕内容");+ return externalize(std::move(tracks));+}+struct SubtitleLoader::Impl {std::mutex mutex;std::condition_variable_any wake;std::wstring pending;uint64_t generation=0;bool requested=false;+ bool pendingExternal=false;std::stop_source cancel;std::optional<Result> ready;std::jthread worker;@@ -606,7 +720,8 @@ struct SubtitleLoader::Impl {while(!shutdown.stop_requested()){std::unique_lock lock(mutex);if(!wake.wait(lock,shutdown,[&]{return requested;}))break;- const auto path=std::move(pending);const auto id=generation;const auto stop=cancel.get_token();requested=false;+ const auto path=std::move(pending);const auto id=generation;const auto stop=cancel.get_token();+ const bool externalFile=pendingExternal;requested=false;lock.unlock();auto publish=[&](std::vector<SubtitleTrack> tracks,bool complete){std::lock_guard guard(mutex);@@ -615,13 +730,19 @@ struct SubtitleLoader::Impl {try{std::vector<SubtitleTrack> external;if(path.empty()||path.starts_with(L"capture:")||path.starts_with(L"capture2:")||path.starts_with(L"remoteplay:")||path.starts_with(L"moonlight:")||path.starts_with(L"xbox:")||path.starts_with(L"screen:")){publish({},true);continue;}- for(const wchar_t* extension:{L".srt",L".ass",L".ssa",L".vtt"}){+ if(externalFile){+ auto tracks=loadExternalSubtitleTracks(path,stop,[&](const auto& listing){publish(listing,false);});+ publish(std::move(tracks),true);continue;+ }+ for(const wchar_t* extension:{L".srt",L".ass",L".ssa",L".vtt",L".sup",L".pgs",L".idx",L".sub",L".smi",L".sami",L".mpl",L".sbv",L".stl"}){if(stop.stop_requested())break;auto candidate=std::filesystem::path(path);candidate.replace_extension(extension);std::error_code ec;if(!std::filesystem::exists(candidate,ec))continue;- auto track=loadSubtitleFile(candidate.wstring());if(!track.usable())continue;- track.name=std::format(L"外挂 · {}",candidate.filename().wstring());external.push_back(std::move(track));break;+ auto tracks=loadExternalSubtitleTracks(candidate.wstring(),stop);+ if(std::none_of(tracks.begin(),tracks.end(),[](const auto& t){return t.usable();}))continue;+ external=std::move(tracks);break;}+ if(!external.empty())publish(external,false);auto embedded=loadEmbeddedSubtitleTracks(path,stop,[&](const auto& tracks){auto listing=external;listing.insert(listing.end(),tracks.begin(),tracks.end());publish(std::move(listing),false);});for(auto& track:embedded)external.push_back(std::move(track));publish(std::move(external),true);@@ -632,9 +753,11 @@ struct SubtitleLoader::Impl {};SubtitleLoader::SubtitleLoader():p_(std::make_unique<Impl>()){}SubtitleLoader::~SubtitleLoader()=default;-uint64_t SubtitleLoader::request(std::wstring path){+uint64_t SubtitleLoader::request(std::wstring path){return request(std::move(path),false);}+uint64_t SubtitleLoader::requestFile(std::wstring path){return request(std::move(path),true);}+uint64_t SubtitleLoader::request(std::wstring path,bool external){std::lock_guard lock(p_->mutex);p_->cancel.request_stop();p_->cancel=std::stop_source{};- p_->pending=std::move(path);p_->requested=true;p_->ready.reset();++p_->generation;p_->wake.notify_all();return p_->generation;+ p_->pending=std::move(path);p_->pendingExternal=external;p_->requested=true;p_->ready.reset();++p_->generation;p_->wake.notify_all();return p_->generation;}std::optional<SubtitleLoader::Result> SubtitleLoader::poll(){std::lock_guard lock(p_->mutex);auto result=std::move(p_->ready);p_->ready.reset();return result;}diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex f19d3210..b147f0d3 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -297,6 +297,9 @@ struct QmlPlayerBridge::Impl {std::filesystem::path dataDir;// --- subtitles (ported from the Win32 shell, same semantics) ---std::unique_ptr<engine::SubtitleLoader> subLoader;+ std::unique_ptr<engine::SubtitleLoader> subFileLoader;+ uint64_t subFileGeneration = 0;+ std::wstring subFilePath;uint64_t subGeneration = 0;std::vector<engine::SubtitleTrack> subTracks; // external files first, then the loader'ssize_t subExternal = 0; // user-loaded files at the front@@ -3514,7 +3517,9 @@ void QmlPlayerBridge::refreshSubtitles(const std::wstring& media) {auto& i = *impl_;i.subTracks.clear(); i.subExternal = i.subLoaded = 0;i.subPrimary = i.subSecondary = -1; i.subPrimaryChosen = i.subSecondaryChosen = false;- i.subStatus.clear(); i.subMedia = media;+ i.subStatus=QFileInfo(QString::fromStdWString(media)).isFile()?tr("正在读取字幕"):QString{}; i.subMedia = media;+ if(i.subFileLoader)i.subFileGeneration=i.subFileLoader->requestFile(L"");+ i.subFilePath.clear();if (i.subAlignWorker.joinable()) { i.subAlignWorker.request_stop(); i.subAlignWorker = {}; }i.subAligning = false; i.subAlignReady = false;if (!i.subLoader) i.subLoader = std::make_unique<engine::SubtitleLoader>();@@ -3535,6 +3540,7 @@ void QmlPlayerBridge::tickSubtitles() {i.subTracks.insert(i.subTracks.begin() + std::ptrdiff_t(i.subExternal),std::make_move_iterator(result->tracks.begin()), std::make_move_iterator(result->tracks.end()));i.subLoaded = count;+ if(result->complete&&i.subStatus==tr("正在读取字幕"))i.subStatus.clear();int firstUsable = -1, firstChinese = -1;for (size_t k = 0; k < i.subTracks.size(); ++k) {if (!i.subTracks[k].usable()) continue;@@ -3557,6 +3563,30 @@ void QmlPlayerBridge::tickSubtitles() {changed = true;}}+ if(i.subFileLoader){+ if(auto result=i.subFileLoader->poll();result&&result->generation==i.subFileGeneration&&result->complete&&!i.subFilePath.empty()){+ const auto file=QFileInfo(QString::fromStdWString(i.subFilePath)).fileName();+ i.subFilePath.clear();+ const bool usable=std::any_of(result->tracks.begin(),result->tracks.end(),[](const auto& t){return t.usable();});+ if(!usable){+ const auto detail=result->tracks.empty()?tr("文件格式不支持、数据损坏或没有字幕内容"):uiText(result->tracks.front().note);+ i.subStatus=tr("外部字幕加载失败:%1 · %2").arg(file,detail);+ emit notice(i.subStatus,true);+ }else{+ const int added=int(result->tracks.size());+ int first=0;+ while(!result->tracks[size_t(first)].usable())++first;+ i.subTracks.insert(i.subTracks.begin(),std::make_move_iterator(result->tracks.begin()),std::make_move_iterator(result->tracks.end()));+ i.subExternal+=size_t(added);+ if(i.subSecondary>=0)i.subSecondary+=added;+ if(i.subAlignTrack>=0)i.subAlignTrack+=added;+ i.subPrimary=first;i.subPrimaryChosen=true;+ i.subStatus=tr("已加载外部字幕:%1").arg(file);+ veyra::log::info("subtitle",std::format("external loaded tracks={} file={}",added,file.toStdString()));+ }+ changed=true;+ }+ }if (i.subAlignReady.exchange(false) && i.subAlignGeneration == i.subGeneration &&i.subAlignTrack >= 0 && size_t(i.subAlignTrack) < i.subTracks.size()) {i.subTracks[size_t(i.subAlignTrack)].offsetMs = i.subAlignOffset.load();@@ -3656,7 +3686,8 @@ QVariantList QmlPlayerBridge::subtitleTracks() const {if (label.isEmpty()) label = tr("字幕 %1").arg(k + 1);QString note = t.embedded ? tr("内嵌") : tr("外挂");if (!t.codec.empty()) note += QStringLiteral(" · ") + QString::fromStdWString(t.codec).toUpper();- if (!t.usable()) note += QStringLiteral(" · ") + (t.note.empty() ? tr("不可用") : QString::fromStdWString(t.note));+ if (!t.note.empty()) note += QStringLiteral(" · ") + uiText(t.note);+ else if(!t.usable()) note += QStringLiteral(" · ") + tr("未解码出可显示的字幕");out << QVariantMap{{"index", int(k)}, {"label", label}, {"note", note}, {"usable", t.usable()},{"embedded", t.embedded}, {"cues", int(t.cues.size())}, {"offsetMs", t.offsetMs}};}@@ -3711,27 +3742,18 @@ void QmlPlayerBridge::setSubtitleBottomInset(int value) {void QmlPlayerBridge::loadSubtitleDialog() {const QString start = impl_->subMedia.empty() ? QString() : QFileInfo(QString::fromStdWString(impl_->subMedia)).absolutePath();const QString path = QFileDialog::getOpenFileName(nullptr, tr("加载外部字幕"), start,- tr("字幕文件 (*.srt *.ass *.ssa *.vtt);;所有文件 (*.*)"));+ tr("字幕文件 (*.srt *.ass *.ssa *.vtt *.sup *.pgs *.idx *.sub *.smi *.sami *.sbv *.mpl *.stl *.txt);;所有文件 (*.*)"));if (!path.isEmpty()) loadSubtitleFile(path);}bool QmlPlayerBridge::loadSubtitleFile(const QString& path) {- engine::SubtitleTrack track;- try { track = engine::loadSubtitleFile(wideOf(path)); } catch (...) {}- if (!track.usable()) {- veyra::log::warn("subtitle", "external file has no usable cues path=" + path.toStdString());- emit notice(tr("字幕文件无法读取或没有字幕内容:%1").arg(QFileInfo(path).fileName()), true);+ if(!QFileInfo(path).isFile()){+ emit notice(tr("字幕文件不存在或无法读取"),true);return false;}- if (track.name.empty()) track.name = QFileInfo(path).fileName().toStdWString();- impl_->subTracks.insert(impl_->subTracks.begin(), std::move(track));- ++impl_->subExternal;- if (impl_->subPrimary >= 0) ++impl_->subPrimary;- if (impl_->subSecondary >= 0) ++impl_->subSecondary;- if (impl_->subAlignTrack >= 0) ++impl_->subAlignTrack;- impl_->subPrimary = 0; impl_->subPrimaryChosen = true;- if (impl_->subSecondary == 0) impl_->subSecondary = -1;- impl_->subStatus = tr("已加载外部字幕:%1").arg(QFileInfo(path).fileName());- veyra::log::info("subtitle", std::format("external loaded cues={} path={}", impl_->subTracks.front().cues.size(), path.toStdString()));+ if(!impl_->subFileLoader)impl_->subFileLoader=std::make_unique<engine::SubtitleLoader>();+ impl_->subFilePath=wideOf(path);+ impl_->subFileGeneration=impl_->subFileLoader->requestFile(impl_->subFilePath);+ impl_->subStatus=tr("正在加载外部字幕:%1").arg(QFileInfo(path).fileName());emit subtitlesChanged();return true;}diff --git a/tests/integration/SubtitleFormatTests.cpp b/tests/integration/SubtitleFormatTests.cppnew file mode 100644index 00000000..868ff4ec--- /dev/null+++ b/tests/integration/SubtitleFormatTests.cpp@@ -0,0 +1,100 @@+#include "veyra/engine/Subtitles.h"+#include <chrono>+#include <cmath>+#include <filesystem>+#include <iostream>+#include <thread>++int wmain(int argc,wchar_t** argv){+ using namespace veyra::engine;+ if(argc!=4)return 2; // authored fixtures, two independent public PGS files+ const std::filesystem::path root=argv[1];+ int checks=0,failures=0;+ auto check=[&](bool ok,const char* label){++checks;failures+=!ok;std::cout<<(ok?"PASS ":"FAIL ")<<label<<'\n';};+ auto times=[&](const SubtitleTrack& track){+ check(track.usable()&&track.cues.size()==2,"two authored cues decoded");+ if(track.cues.size()!=2)return;+ check(std::abs(track.cues[0].begin-1)<.015&&std::abs(track.cues[0].end-3)<.015,"first display timing");+ check(std::abs(track.cues[1].begin-5)<.015&&std::abs(track.cues[1].end-7)<.015,"last display timing");+ for(double at:{0.,3.,4.,7.,8.})check(cuesAt(track,at).empty(),"clear gap and exact end boundary");+ for(double at:{6.,2.,5.,1.})check(cuesAt(track,at).size()==1,"backward seek and exact start boundary");+ };+ for(const auto* name:{L"microdvd.sub",L"mpl2.mpl",L"subviewer.sub",L"subviewer.sbv",L"spruce.stl",L"sami.smi",L"sami.sami"}){+ std::wcout<<L"FORMAT "<<name<<L'\n';+ const auto track=loadSubtitleFile((root/name).wstring());times(track);+ if(track.cues.size()==2){+ check(track.cues[0].text==L"First\nTwo","authored line break preserved through FFmpeg text decoder");+ check(track.cues[1].text==L"Second","plain text retained");+ }+ check(!track.embedded,"external text is labeled external");+ }+ const auto unicode=loadSubtitleFile((root/L"中文 路径.srt").wstring());times(unicode);+ check(unicode.usable()&&unicode.cues[0].text==L"中文,第一行\nEnglish, second line","Unicode content and path retained");+ const auto sniffed=loadSubtitleFile((root/L"字幕.txt").wstring());+ check(sniffed.usable()&&sniffed.cues[0].text==unicode.cues[0].text,"text extension uses recognizable subtitle content");+ for(const auto* name:{L"bitmap.sup",L"bitmap.pgs",L"vobsub.idx",L"vobsub.sub"}){+ std::wcout<<L"BITMAP "<<name<<L'\n';+ const auto tracks=loadExternalSubtitleTracks((root/name).wstring());+ const bool dvd=std::wstring_view(name).starts_with(L"vobsub");+ check(tracks.size()==size_t(dvd?2:1),"all external bitmap languages retained");+ for(const auto& track:tracks){+ times(track);check(!track.embedded,"external bitmap is labeled external");+ check(track.usable()&&track.cues[0].bitmap&&!track.cues[0].bitmap->images.empty(),"decoded bitmap reaches cue");+ if(track.usable()&&track.cues[0].bitmap){+ const auto& frame=*track.cues[0].bitmap;+ check(frame.width==1280&&frame.height==720,"authored bitmap canvas");+ for(const auto& image:frame.images)check(!image.pixels().empty(),"cached bitmap expands to real pixels");+ }+ }+ }+ bool loading=false,progress=false;+ const auto compressed=loadEmbeddedSubtitleTracks((root/L"compressed.mkv").wstring(),{},[&](const auto& tracks){+ if(tracks.size()==5){loading|=!tracks[0].usable()&&tracks[0].note==L"正在读取字幕";progress|=tracks[0].usable();}+ });+ const auto plain=loadEmbeddedSubtitleTracks((root/L"plain.mkv").wstring());+ check(loading&&progress,"loading state and first cue published during scan");+ check(compressed.size()==5&&plain.size()==5,"five compressed and five plain PGS languages discovered");+ for(size_t k=0;k<compressed.size();++k){+ times(compressed[k]);check(compressed[k].note.empty(),"successful track clears loading status");+ if(k<plain.size()&&compressed[k].cues.size()==2&&plain[k].cues.size()==2){+ const auto a=compressed[k].cues[0].bitmap,b=plain[k].cues[0].bitmap;+ check(a&&b&&a->images[0].pixels()==b->images[0].pixels(),"compressed PGS pixels match uncompressed reference");+ }+ }+ const auto duration=loadEmbeddedSubtitleTracks((root/L"duration-only.mkv").wstring());+ check(duration.size()==1,"PGS with container duration discovered");+ if(duration.size()==1)times(duration[0]);+ const auto corrupt=loadEmbeddedSubtitleTracks((root/L"corrupt.mkv").wstring());+ check(corrupt.size()==1&&!corrupt[0].usable()&&!corrupt[0].note.empty()&&corrupt[0].note!=L"正在读取字幕","broken PGS reports a final reason");+ for(const auto* name:{L"broken.sup",L"missing.idx",L"orphan.sub",L"absent.sup",L"oversized.srt",L"oversized-vobsub.sub"}){+ const auto track=loadSubtitleFile((root/name).wstring());+ check(!track.usable()&&!track.note.empty(),"bad or incomplete external file reports reason");+ }+ for(int k=2;k<4;++k){+ const auto tracks=loadEmbeddedSubtitleTracks(argv[k]);+ check(tracks.size()==1&&tracks[0].usable()&&tracks[0].cues[0].bitmap,"independent public PGS decodes actual bitmap");+ }+ std::stop_source stopped;stopped.request_stop();+ check(loadExternalSubtitleTracks((root/L"bitmap.sup").wstring(),stopped.get_token()).empty(),"pre-cancelled external load performs no work");+ SubtitleLoader loader;+ auto await=[&](uint64_t id){+ const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(5);+ while(std::chrono::steady_clock::now()<deadline){+ if(auto result=loader.poll()){+ check(result->generation==id,"no cancelled result reaches current generation");+ if(result->generation==id&&result->complete)return *result;+ }+ std::this_thread::sleep_for(std::chrono::milliseconds(2));+ }+ return SubtitleLoader::Result{};+ };+ loader.requestFile((root/L"vobsub.idx").wstring());+ check(await(loader.requestFile(L"")).tracks.empty(),"cancelled external work cannot add old tracks");+ const auto loaded=await(loader.requestFile((root/L"vobsub.idx").wstring()));+ check(loaded.complete&&loaded.tracks.size()==2&&loaded.tracks[0].usable(),"async external VobSub retains both languages");+ loader.requestFile((root/L"compressed.mkv").wstring());+ const auto replaced=await(loader.request((root/L"duration-only.mkv").wstring()));+ check(replaced.complete&&replaced.tracks.size()==1&&replaced.tracks[0].embedded,"changing from external file to source cancels stale task");+ std::cout<<"checks="<<checks<<" failures="<<failures<<'\n';+ return failures?1:0;+}diff --git a/tests/integration/SubtitleLoadingTests.cpp b/tests/integration/SubtitleLoadingTests.cppindex c5ca0e86..2bfd86ab 100644--- a/tests/integration/SubtitleLoadingTests.cpp+++ b/tests/integration/SubtitleLoadingTests.cpp@@ -1,5 +1,6 @@#include "veyra/engine/Subtitles.h"#include <chrono>+#include <cmath>#include <iostream>#include <thread>@@ -63,7 +64,12 @@ int wmain(int argc,wchar_t** argv){if(cue.begin<previous||cue.end<=cue.begin)return 1;previous=cue.begin;}- if(track.usable()&&textAt(track,(track.cues.front().begin+track.cues.front().end)/2).empty())return 1;+ if(track.usable()){+ const auto& cue=track.cues.front();+ const double at=std::isfinite(cue.end)?(cue.begin+cue.end)/2:cue.begin+.1;+ if(cuesAt(track,at).empty())return 1;+ if(!cue.bitmap&&textAt(track,at).empty())return 1;+ }}std::cout<<"tracks="<<result.tracks.size()<<" usable="<<usable<<" cues="<<cues<<" elapsedMs="<<std::chrono::duration<double,std::milli>(Clock::now()-start).count()<<'\n';diff --git a/tests/integration/SubtitleOverlayTests.cpp b/tests/integration/SubtitleOverlayTests.cppindex e330eaaa..ffbc4474 100644--- a/tests/integration/SubtitleOverlayTests.cpp+++ b/tests/integration/SubtitleOverlayTests.cpp@@ -15,7 +15,7 @@ static BOOL captureLayer(HWND,HDC,POINT*,SIZE* size,HDC source,POINT*,COLORREF,B#include "../../apps/veyra/ui/SubtitleOverlay.cpp"#undef UpdateLayeredWindow-int main(){+int wmain(int argc,wchar_t** argv){using namespace veyra::ui;Gdiplus::GdiplusStartupInput input;ULONG_PTR token=0;if(Gdiplus::GdiplusStartup(&token,&input,nullptr)!=Gdiplus::Ok)return 1;@@ -66,6 +66,31 @@ int main(){updateSubtitleOverlay(overlay,{red},view);check(updates==count,"unchanged cues reuse cache");red.style.bold=true;updateSubtitleOverlay(overlay,{red},view);check(updates==count+1&&pixels!=before,"bold change repaints actual raster");+ if(argc>1){+ const auto track=veyra::engine::loadSubtitleFile(argv[1]);+ check(track.cues.size()==2&&track.cues[0].bitmap,"real decoded SUP feeds the production overlay");+ if(track.cues.size()==2&&track.cues[0].bitmap){+ SubtitleLine image;image.bitmap=track.cues[0].bitmap;+ view.videoWidth=1280;view.videoHeight=720;view.scale=1;+ updateSubtitleOverlay(overlay,{image},view);+ auto pixel=[&](int x,int y){return pixels[size_t(y)*imageWidth+x];};+ check((pixel(56,366)>>24)==255&&(pixel(456,116)>>24)==255,"authored lower and upper rectangles map into letterboxed video");+ check((pixel(72,366)>>24)==128&&((pixel(72,366)>>16)&255)<=128,"partial alpha survives the real GDI raster");+ check(pixel(320,240)==0,"transparent bitmap gap remains transparent");+ before=pixels;view.scale=3;view.fontOverride=L"Arial";+ updateSubtitleOverlay(overlay,{image},view);+ check(pixels==before,"text size and font do not distort bitmap subtitles");+ image.bitmap=track.cues[1].bitmap;updateSubtitleOverlay(overlay,{image},view);+ check(pixel(56,366)!=before[size_t(366)*imageWidth+56],"new palette repaints immutable bitmap snapshot");+ updateSubtitleOverlay(overlay,{},view);+ check(!IsWindowVisible(overlay),"clear display hides the native subtitle layer");+ image.bitmap=track.cues[0].bitmap;updateSubtitleOverlay(overlay,{image},view);+ check(IsWindowVisible(overlay)&&pixels==before,"backward seek restores original bitmap pixels");+ SetWindowPos(overlay,nullptr,0,0,960,540,SWP_NOZORDER|SWP_NOACTIVATE);+ updateSubtitleOverlay(overlay,{image},view);+ check(imageWidth==960&&imageHeight==540&&(pixel(84,459)>>24)==255&&(pixel(684,84)>>24)==255,"resize/fullscreen aspect maps both authored rectangles");+ }+ }DestroyWindow(overlay);DestroyWindow(parent);Gdiplus::GdiplusShutdown(token);return failures?1:0;}