Skip to content

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++

checkpoint: preserve completed release P1 repairs before GPU DIS integration

Veyra Goal Agent3ae4d5c8a8a4
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ba8c02c9..b5cdeef4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -574,6 +574,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_popup_selector_tests PRIVATE veyra_base comctl32)
add_executable(veyra_hdr_color_tests tests/integration/HdrColorTests.cpp)
add_executable(veyra_source_fidelity_tests tests/integration/SourceFidelityTests.cpp)
+ add_executable(veyra_file_safety_tests tests/integration/FileSafetyTests.cpp)
+ target_compile_features(veyra_file_safety_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_file_safety_tests PRIVATE /utf-8)
+ target_compile_definitions(veyra_file_safety_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_link_libraries(veyra_file_safety_tests PRIVATE veyra_engine)
target_compile_features(veyra_source_fidelity_tests PRIVATE cxx_std_20)
target_compile_definitions(veyra_source_fidelity_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_link_libraries(veyra_source_fidelity_tests PRIVATE veyra_engine)
diff --git a/docs/RELEASE_AUDIT_2026-09-13.md b/docs/RELEASE_AUDIT_2026-09-13.md
new file mode 100644
index 00000000..a6510e52
--- /dev/null
+++ b/docs/RELEASE_AUDIT_2026-09-13.md
@@ -0,0 +1,181 @@
+# 正式发布前审查 — 2026-09-13
+
+> 后续:用户随后授权仅修复三个 P1。本地修复及针对性/交付回归已完成,见 [P1 修复记录](RELEASE_P1_REPAIR_PLAN_2026-09-13.md)。两个 P2 未修。以下保留修复前基线的审查证据,不代表新构建仍存在这三个已修 P1。
+
+结论:当前候选版本不建议作为正式版发布。确认 5 项问题,其中 3 项 P1(发布前应修复)、2 项 P2。本次是审查,不是修复交付;产品源码未改,未提交、推送或发布。
+
+## 审查基线与证据范围
+
+- 分支:`codex/ps5-sampling-repair`;HEAD:`f037f49`(`fix(remoteplay): add chroma-aware sampling and cubic presentation`)。开工时工作区干净。
+- 独立构建:`out/release-audit-20260913/build`,Remote Play 实际后端开启,444 步编译/链接成功。
+- 构建 EXE SHA256:`F08F2C1E1296591CD3C2F2CDC3C1701195EAA37F51DC5F0147F2594A1E63C694`。
+- 本机:Windows x64、RTX 5070、驱动 616.56、MSVC 19.44.35226.0。构造测试素材使用本机 FFmpeg 8.1.1;产品实际运行使用下述 patched FFmpeg 9.0.1。
+- 审查覆盖:文件 demux/decode、颜色/上传、共享增强图、播放调度与缓存寿命、暂停/seek/reset、音频、采集入口、图片/视频导出、PS5 会话/恢复/配置、UI 设置及便携包依赖。重点检查 v0.0.5 之后的变更,同时复查共享旧代码。
+- 所有本轮日志、合成素材和临时诊断代码位于忽略目录 `logs/release-audit-20260913/`、`out/release-audit-20260913/`。没有拿历史通过代替本轮结果,也没有独立 Reviewer 验收。
+
+## 确认的问题
+
+### F1 · P1 · 播放过载到文件尾部时崩溃
+
+位置:`src/engine/EngineController.cpp:555-568`,尤其第 558 行;关联 `src/media/FFmpegVideoDecoder.cpp:209`。
+
+过载追赶循环继续调用 `activeSource->read()`,遇到 EOS 后仅 `break`,注释宣称保留最后候选帧。但 `frame` 是 decoder 内部复用的 AVFrame;下一次 `avcodec_receive_frame()` 会先 unref/清空该对象,即使最终返回 EOS。此时保存的指针已不代表原先有效帧,后续 clone/process 收到 format=-1、尺寸被清空的帧,触发 libswscale 断言。
+
+本轮复现:2 秒、640×360、30fps、H.264/AAC 合成文件 `repros/regular.mp4`,关闭 NR/SR/FG,正常播放退出 0;仅加入已有的负载注入 `VEYRA_TEST_VIDEO_WORK_MS=150`,相同文件到尾部退出 `3221226505 / 0xC0000409`。负载注入模拟逐帧工作欠速,不修改 decoder、EOF 或帧数据。
+
+日志证据:
+
+```text
+[player-timing] ... previewSkipped=38 playbackSpeed=1.004 processed=14
+Assertion desc failed at C:\veyra-deps\ffmpeg-ps5-slices-source\libswscale\swscale_internal.h:778
+```
+
+完整命令和结果:`logs/release-audit-20260913/repros/commands.json`,`play-normal.*.log`、`play-overload-tail.*.log`。生成与复现代码:`out/release-audit-20260913/reproduce.py`。
+
+修复门槛:在继续拉取下一帧之前持有最后候选帧的独立引用,或将 EOS 与候选帧寿命分开处理;不能把空 AVFrame 交给图。相同负载跑到 EOS 应正常结束,保留真实尾部时序,不能靠禁用追赶或丢弃声音掩盖。
+
+### F2 · P1 · 文件中途改变分辨率会写出原有上传缓冲范围
+
+位置:`src/pipeline/EnhanceGraph.cpp:820-835`;原缓冲容量在 `104-110`、`146-149` 行确定;`src/engine/EngineController.cpp:520` 的尺寸变化重建仅适用于 Remote Play。
+
+软件 YUV 分支将 swscale 输入、输出尺寸都设为当前 `frame->width/height`,但目标地址、行跨度和容量仍按图初始化时的 `srcW_/srcH_` 分配。文件路径没有统一的每帧尺寸校验或重建,视频导出也直接复用同一图。合法 H.264 分辨率切换即可进入该路径。
+
+本轮复现:拼接 1 秒 320×180 与 1 秒 640×360 H.264,容器初始尺寸 320×180,ffprobe 确认两种尺寸各 30 帧。播放和导出均返回 0,仍按初始 320×180 图处理 60 帧,没有 Resize 重建。本轮没有观察到该素材导致进程崩溃,不能将其报告为已复现崩溃。
+
+进一步采用安全 canary 检查:使用产品同一 `swscale-10.dll`、相同尺寸及 stride,但实际分配更大的诊断数组,避免诊断本身破坏内存。结果如下:
+
+| 平面 | 产品初始声明容量 | 超过该容量仍被写入的字节数 |
+| --- | ---: | ---: |
+| Y | 92,160 | 92,288 |
+| UV | 46,080 | 46,208 |
+
+这是已验证的越界写入条件;系统/GPU 分配留白可能使某次运行没有立即崩溃,不构成安全性证明。
+
+证据:`repros/changing-inspect.stdout.log`、`repros/play-changing-size.*.log`、`repros/export-changing-size.*.log`、`resolution-canary.json`。安全 canary 在 `out/release-audit-20260913/final_checks.py` 中。
+
+修复门槛:在任何像素读取/转换前校验实际帧尺寸和格式;文件预览按契约重建全部历史或明确拒绝;固定尺寸视频导出应明确定义缩放/拒绝策略。不能继续用新帧尺寸写旧容量。
+
+### F3 · P1 · 损坏尾部视频帧后仍报告导出成功,并截短音频
+
+位置:`src/source/MediaFileSource.cpp:173-175`;关联 `src/media/FFmpegVideoDecoder.cpp:209-212`、`src/engine/VideoExportJob.cpp:85-124`。
+
+源读取对 `sendPacket` 的硬错误仅记录日志并跳过;`receiveFrame()` 也把 EAGAIN、EOF、真正解码失败统一折叠成 nullptr。导出因此把“跳过坏帧后耗尽”当作正常 EOF。完成验证只重新解码第一帧,未发现尾部缺失,随后把 partial 提升为正式输出。
+
+本轮控制实验:原文件 60 帧、2 秒,只将最后 8 个视频 packet 的 payload 置零,保留容器、时间戳和完整音轨。输入已经损坏;问题不是要求修复坏数据,而是导出应该明确失败或报告损失,不能宣称完整成功。
+
+| 项目 | 输入 | 被报告成功的输出 |
+| --- | ---: | ---: |
+| 视频 | 容器 60 帧;可解码 52 帧;2.000 秒 | 52 帧;1.733333 秒 |
+| 音频 | 2.000 秒 | 1.749333 秒 |
+| 程序结果 | 解码错误 `-1094995529` | 退出 0;`export result=true` |
+
+日志同时出现 `send_packet failed ... Invalid data found when processing input`、`source=52 generated=0 hold=0 output=52` 与最终成功。损坏的源文件测试使用故意构造的尾部错误,没有修改用户媒体。
+
+证据:`repros/corrupt-source-inspect.stdout.log`、`repros/export-corrupt-tail.*.log`、`repros/corrupt-export-inspect.stdout.log`;详细命令见 `repros/commands.json`。
+
+修复门槛:区分 decoder 的待输入、正常 EOF 与硬错误,导出严格传播硬错误;核查源帧/输出帧、尾部时间线及音轨,而非只读第一帧。失败应保留 partial,并明确告知用户。
+
+### F4 · P2 · 视频导出对 partial 文件的保护不是原子的
+
+位置:`src/engine/VideoExportJob.cpp:23` 与 `84`。
+
+入口只检查一次目标/partial 是否存在,随后进行设备、源扫描与增强图初始化;最终 `avio_open(..., AVIO_FLAG_WRITE)` 会截断打开已有文件。另一导出进程在检查与打开之间创建相同 partial 时,双方都可能通过初始检查,导致覆盖或交错写入。
+
+本轮在第一进程完成 preflight 后、打开输出前,用审查脚本独占创建该进程目标的 partial 哨兵文件。进程继续退出 0,哨兵被覆盖,文件最终被提升为正式输出。实验仅涉及本轮专用路径和本轮创建的哨兵,没有覆盖用户文件。
+
+证据:`partial-collision.json`(`inserted_after_preflight=true`、`sentinel_preserved=false`、`exit=0`)、`partial-collision.*.log`;命令/控制逻辑位于 `final_checks.py`。
+
+修复门槛:用原子独占创建/持有的句柄接入 FFmpeg AVIO,或为任务生成并持有独有临时文件,再无覆盖地提升目标;不能依赖 exists 后普通 write-open。
+
+### F5 · P2 · 视频导出无提示丢弃内嵌字幕
+
+位置:`src/engine/VideoExportJob.cpp:58-68`、`124-125`。
+
+导出只创建视频和第一条音频流,不检查字幕,也没有导出前缺失提示或结果报告。本轮 MP4 输入包含 H.264、AAC、mov_text 三条流,导出成功文件只剩 H.264、AAC;mov_text 本身可由当前 MP4 muxer 承载。
+
+产品规格第 315 行要求兼容字幕复制/转换,否则开始前明确报告;这项要求并未被当前执行例外撤销。额外静态检查发现播放器 `AppShell.cpp:137` 仅自动读取同名外置 SRT;不能据 README 的“字幕”入口宣称已实现容器内基础字幕。内嵌字幕播放缺失是代码检查结论,本轮未进行可视化播放验收。
+
+证据:`subtitles-inspect.stdout.log`、`subtitles-export-inspect.stdout.log`、`export-subtitles.*.log`;源文件 `repros/subtitles.mp4`,只有本轮生成的测试文本。
+
+修复门槛:实现并验证兼容字幕保留,或开始前明确告知不保留、给出可检查的结果;同步澄清播放器支持范围。
+
+## 本轮实际验证
+
+| 检查 | 结果 | 证据 |
+| --- | --- | --- |
+| 独立 x64 Release + PS5 后端完整构建 | 444 步成功 | `build.log` |
+| 当前 `scripts/gates/delivery.ps1` | 23 项通过,45.033 秒 | `logs/delivery/c992884d6d924d02a4cce0374a758094/result.json` |
+| 第一组单元/集成/实 GPU 检查 | 27 次运行通过 | `checks.json` |
+| 扩展采集/FG/图像/HDR/调度检查 | 16 次通过;seek 素材不符合条件的一次作废,另用有效素材重跑通过 | `more-checks.json`、`final-checks.json` |
+| Remote Play 离线 core | 新构建,73/73 通过 | `core.log` |
+| 最新精细采样数值对照 | 30 组通过:2 ingress、16 呈现、12 色度位置 | `sampling-result.log` |
+| 本地便携包制作与内容扫描 | 通过,7 个批准运行文件,forbiddenFiles=0 | `out/release-audit-20260913/package/package-audit.json` |
+| 便携包独立启动 | 5/5 通过 | `portable-smoke/result.json` |
+| 故障/边界验证 | 确认 F1–F5;常规 gate 未覆盖这些边界 | 上述逐项证据 |
+
+除证据单列完整路径者外,表内日志均相对 `logs/release-audit-20260913/`。
+
+交付 gate 实际包含 1080p NR/NVOF/GBV、native 4K 正确性、4K 输入实时档播放器、暂停 seek、PNG/JPEG、native 4K H.264/HEVC D3D12 NVENC 导出、完整短片解码/时长/音轨核验及取消保留 partial。它只证明所测短场景。
+
+额外测试确实执行了 DLSS 2X/3X/4X、SR/NR/FG、双向光流、图片尺寸/方向、软件/硬件 Main10 和 HDR 转 SDR 增强组合、运行时切换、NR→SR 预览、文件欠速、音频端点故障、有效素材 seek 压力、配置损坏保护和 WASAPI 时间线。XeSS 记录 generated=43、debugErrors=0;AMD OF 记录 dispatches=48、debugErrors=0;这些是在本机 RTX 上的 SDK 执行,不是 AMD/Intel 显卡验收或显示器扫描输出证明。
+
+采集卡 `USB3 Video` 实际读帧:YUY2 与 MJPEG 1920×1080@60 均收到 19 帧,消费者停顿时丢弃过期 17 帧,返回帧保持拥有权,callback fps 约 60、最新帧年龄分别 1.103/3.808ms。没有据此判断画面内容、端到端延迟或完成 4K60 实卡验收;该设备本次枚举的 3840×2160 模式为 18fps。
+
+新采样测试使用独立临时诊断程序,显式启用 `highQualityPresentation`,对 720p 缩小、1080p 1:1、1440p/2160p 放大以及两个交换链模式采样比较;与 CPU Catmull-Rom/局部限幅参考的最大码值误差 0.560/255,1:1 误差 0。YUV420P/NV12 的六种色度位置与 CPU 双线性/颜色参考最大误差 0.588/255。这里只验证合成 SDR 数据到呈现缓冲;没有作游戏画质判断或测量该新路径的 PS5 实时成本。临时文件 `SamplingAudit.cpp` 的统计均值分母未针对抽样步长调整,因此报告只引用正确的最大误差,不引用 meanError。
+
+最初 seek 压力测试使用 60.016 秒素材,但 harness 固定跳到 344.93/643.709/700 秒,并要求超过目标后继续呈现;因此那次退出 1 不能算产品失败。改用新生成的 710 秒素材,相同未修改的测试程序全部断言通过,22.156 秒结束。原失败日志保留,没有删除失败来制造通过。
+
+真实运行日志摘录:
+
+```text
+snippet CreateFeature id=18 result=0x1 (NVSDK_NGX_Result_Success) handle=non-null seh=0
+sr-backend: Create DLSS 1920x1080 -> 3840x2160 result=0x1 ... seh=0
+fg-backend: Create DLSSG 3840x2160 ... result=0x1 ... seh=0
+RESULT source=12 generated=11 contentValid=11 display=unmeasured
+fg-backend: ReleaseFeature result=0x1 ... evaluates=13 resets=2
+nvOFDestroy status=0 executes=11
+[video-sr] op=0 result=0x1 seh=0x0
+smoke frames=150 generated=115 failed=false ... nrEvaluated=120 nvofExecuted=117
+```
+
+对应 `nr-flow.stdout.log`、`sr-nr-fg.stdout.log`、`portable-smoke/video-sr-nr-fg.stdout.log`。FrameLease 测试中的 `still leased; refusing overwrite` 是故意保留旧帧触发的防御成功,不是本轮新增故障。
+
+## 实际命令入口
+
+以下均在项目根目录执行,构建依赖路径使用本机已有的受控资源:
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release -BuildDirectory out/release-audit-20260913/build -RemotePlay -ChiakiCheckout C:/veyra-deps/chiaki-source -ChiakiStage out/remoteplay/chiaki-msvc-stage -RemotePlayPrefixPath C:/veyra-deps/remoteplay-installed/x64-windows-static -ProtocPath C:/veyra-deps/remoteplay-installed/x64-windows/tools/protobuf/protoc.exe -PkgConfigPath C:/veyra-deps/vcpkg/downloads/tools/msys2/3e71d1f8e22ab23f/mingw64/bin/pkg-config.exe
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/release-audit-20260913/build
+python out/release-audit-20260913/run_checks.py
+python out/release-audit-20260913/more_checks.py
+python out/release-audit-20260913/reproduce.py
+python out/release-audit-20260913/final_checks.py
+& out/release-audit-20260913/core.cmd
+python out/release-audit-20260913/prepare_sampling.py
+& out/release-audit-20260913/sampling.cmd
+& out/release-audit-20260913/build/SamplingAudit.exe
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/package-portable.ps1 -Root . -Version 0.0.5 -OutputDirectory out/release-audit-20260913/package -BuildDirectory out/release-audit-20260913/build
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/acceptance/portable-smoke.ps1 -PackageDirectory out/release-audit-20260913/package/Veyra-0.0.5-win64-portable -InputFile logs/ps5-p1-1080p30-long.mp4 -OutputDirectory logs/release-audit-20260913/portable-smoke
+git diff --check
+```
+
+详细逐条 EXE 参数和退出码在三份 `*-checks.json` / `checks.json` 与 `repros/commands.json`;每个运行有 stdout/stderr。诊断脚本生成的素材/输出采用独有路径,重跑应另选新的审查目录以保留原证据。
+
+## 运行时与源码隔离
+
+- 原版 NR SHA256 `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`,165840496 字节、310.8.0.0、Valid。
+- 批准的社区 NR SHA256 `984BEE0F775C277D5829B8FD6775D53A7B0F75396C852B3AAF06A18375F81014`,同版本/大小、HashMismatch;未伪称有效原版签名。
+- patched `avcodec-63.dll` SHA256 `0710F0D87A7FFCC9F998F1A35D0500345F6C66EB9A5A39C51D60D293142BD84F`,19345920 字节。实际构建依赖、此前修复版与新审查版一致,保留 H.264 slices 32→256 修复。
+- 本地包带 `licenses/FFMPEG-VEYRA-BUILD.json`,通过当前构建来源 manifest 校验;未把 vcpkg SPDX 当作 patched tree 的完整身份。
+- 包内运行组件按现有 7 文件清单校验来源/哈希/签名/许可证;未新增或替换运行组件。测试移除 publisher manifest 后,软件仍能独立加载符合用户选择的原版/社区运行时,测试结束恢复 manifest。
+- 审查 ZIP SHA256 `4746BCCFCDEB789DB291E5A2A1130A14996EDD33EAC7F549BE1BF2EFE01CC2A1`;它是有上述已知问题的本地审查材料,不是批准发布的新版本。
+- `git ls-files` 对 DLL/LIB/EXE/模型/PDB/ZIP/addon 与本地 runtime/SDK 目录扫描为空;未把凭据、个人配置、测试媒体、SDK 或运行时纳入 Git。
+
+## 未执行与后续门槛
+
+本轮未连接实际 PS5,未操作 PSN 登录/注册/唤醒/真实网络重连,未读取或导出主机密钥;未复测真实 PS5 AU 的软硬解全图一致性。Main10/HDR 的合成/文件检查不等于 HDR 显示器验收。精细采样的 P010 与实际 PS5 HDR 组合、游戏主观画质、扫描输出和端到端延迟仍未执行。
+
+未进行数小时稳定性、真实设备拔插/显卡 device-lost、电源睡眠恢复、多 GPU/驱动矩阵、AMD/Intel 独立显卡、4K60 采集卡持续增强及人工全 UI 验收。此次短测不能证明这些项目已通过,也不能保证项目不存在其他 bug。
+
+下一项唯一任务:先修复 F1 的 EOF 候选帧寿命,加入正常/欠速/暂停 seek 到尾部的回归;随后按 F2→F3→F4→F5 处理。正式发布前至少清零本报告 P1,并对导出数据保留问题完成修复或明确可验收的功能边界,再运行针对性回归和 delivery gate。
diff --git a/docs/RELEASE_P1_REPAIR_PLAN_2026-09-13.md b/docs/RELEASE_P1_REPAIR_PLAN_2026-09-13.md
new file mode 100644
index 00000000..e7609c9a
--- /dev/null
+++ b/docs/RELEASE_P1_REPAIR_PLAN_2026-09-13.md
@@ -0,0 +1,93 @@
+# 发布审查 P1 修复 — 2026-09-13
+
+用户授权:仅修复 `RELEASE_AUDIT_2026-09-13.md` 的 F1/F2/F3(三个 P1)。F4/F5 两个 P2 不在本次范围,不发布、不替换 NVIDIA/FFmpeg 运行组件。
+
+基线 `f037f49`;开工保留审查报告与 WORKLOG 未提交改动,存档 tag `checkpoint/release-p1-2026-09-13`,施工分支 `codex/release-p1-repair`。
+
+## 最小修复闭环
+
+1. F1:过载追赶跨 `read()` 前持有候选帧自己的 AVFrame 引用;复用现有缓存,不增加像素复制、GPU 回读或无界队列,保留最后有效 PTS 与尾帧。
+2. F2:共享图在任何像素转换/提交前校验实际帧尺寸与格式。文件源遇到尺寸变化明确返回错误并停止,固定尺寸导出拒绝此输入;保留已有 PS5 尺寸变化重建路径。
+3. F3:区分解码待输入、正常 EOF、硬错误;文件源错误保持到 seek/reopen,拒绝损坏 packet/frame。导出预检和执行阶段传播源错误,结束时逐帧验证编码输出的数量、尺寸、CFR 时间线,并保留取消能力;仅成功时提升正式文件。预检失败、尚未创建 partial 时不假称已保留 partial。
+
+## 验证门槛
+
+- 针对三个 P1 增加持久回归,用真实文件/实际产品图验证,不能只测试模拟返回值。
+- 复用审查合成素材并添加 B 帧、晚于预检窗口的坏尾帧/尺寸变化;正常文件解码/导出保持完整。
+- 正常/欠速播放到尾部、暂停 seek 尾部后恢复;错误后 seek/reopen 能重新开始。
+- 直接向图传入错误尺寸和空格式,必须在访问像素和提交 GPU 工作前拒绝,再处理有效帧仍成功。
+- 独立构建,运行适用软件/硬解/采集/HDR 回归及 `scripts/gates/delivery.ps1`;每次测试 ≤300 秒。
+- 保留 patched FFmpeg avcodec SHA256 `0710F0D87A7FFCC9F998F1A35D0500345F6C66EB9A5A39C51D60D293142BD84F`。
+
+## 当前状态
+
+三个 P1 已完成本地修复与回归。F4/F5 两个 P2 未修;未推送、发布或替换既有便携包。旧审查构建与旧日志保留供对照。
+
+## 实际修改
+
+- `src/engine/EngineController.cpp`:复用现有缓存持有跨 read 的候选帧引用,检查 clone 失败,保留尾帧和原始 PTS;文件错误显示具体原因。没有修改音频调度和预览跳帧政策。
+- `src/pipeline/EnhanceGraph.cpp`:所有入口在 CPU 像素读取、swscale 和 command slot 获取前校验实际 extent/像素格式;错误输入不触碰纹理。
+- `include/veyra/media/FFmpegVideoDecoder.h`、`src/media/FFmpegVideoDecoder.cpp`:暴露 NeedInput/Frame/EndOfStream/Error 四态,记录 receive 硬错误,open/seek/close 清状态;原 borrowed-frame 寿命契约不变。
+- `include/veyra/source/MediaFileSource.h`、`src/source/MediaFileSource.cpp`:损坏 packet、硬解码错误、标记损坏的帧和尺寸变化都停止读取,错误保持到成功 seek/reopen。尺寸变化不再偷偷缩放或写旧容量。
+- `src/engine/VideoExportJob.cpp`:源错误覆盖预检和编码阶段;音频 demux 硬错误不当作 EOF;取消/边界中止不能成为短片成功。编码完成后完整解码输出,逐帧核对 CFR PTS、尺寸和编码帧总数,正常 EOF 后才提升输出;区分尚未创建 partial 与保留 partial。
+- `src/engine/ExportJobManager.cpp`:子进程退出后保留具体失败说明,避免预检失败被覆盖成“partial 已保留”;沿用现有 Finishing 状态消息,取消监视线程继续有效。
+- `tests/integration/FileSafetyTests.cpp`、`scripts/gates/release-p1.py`、`CMakeLists.txt`:增加真实产品库/进程回归及独有目录素材生成器。
+
+## 本轮验证与真实结果
+
+最终 EXE:`out/release-p1-20260913/build/veyra.exe`。
+
+SHA256:`B116AB6855D69CDEB29927AB3AD80422D54051339FCE47D7EE5939CAA987519D`。
+
+| 项目 | 实际结果 | 证据 |
+| --- | --- | --- |
+| 独立 Remote Play Release 构建 | 初次 446 步成功;后续增量及最终构建成功 | `logs/release-p1-20260913/build.log`、`rebuild.log`、`final-build.log` |
+| P1 专用回归 | 29 次进程调用及 12 条文件/时长断言通过,29 次包含素材生成与 ffprobe;内部 C++ 断言另保存在各日志 | `logs/release-p1-20260913/verified/result.json` |
+| F1 | 正常/150ms 注入欠速均到 Ended,尾帧位置 ≥1.96 秒;确实出现 previewSkipped;暂停 seek 到尾部后恢复再次到 EOF;退出 0 | `verified/play-eof.stdout.log`、`play-overload-eof.stdout.log` |
+| F2 | 大/小/零尺寸和空格式在无像素缓冲条件下被拒绝;随后有效帧输出可读取且非黑;第 151 帧变尺寸时源/导出报错,保留 partial,不生成正式文件 | `verified/graph-contract.stdout.log`、`source-resize.stdout.log`、`export-resize.stdout.log` |
+| F3 输入损坏 | 2 秒坏尾帧在预检失败、未创建输出;8 秒文件在第 120 帧预检后遇坏尾帧仍失败,只保留 partial;退出 1,非成功/取消 | `verified/export-bad-early.*.log`、`export-bad-late.*.log` |
+| F3 输出损坏 | 编码后故意破坏最后一个视频 packet,完整验证读到 59/60 帧,passed=false;未提升正式文件 | `verified/export-corrupt-output.stdout.log` |
+| 取消/子进程 UI | 验证阶段取消、帧边界中止均保留 partial 且不成功;真实独立 worker 预检错误传到父进程,明确“未生成输出文件” | `verified/export-cancel-verify.stdout.log`、`export-abort-boundary.stdout.log`、`export-worker-failure.stdout.log` |
+| 正常数据 | 2 秒 60 帧、8 秒 240 帧及对应音轨/时长完整;4K 24 张 B 帧与单线程基准逐像素/PTS 一致,seek 后也通过 | `verified/result.json`、`threaded-bframes-reference.stdout.log` |
+| 共享路径 | 硬解导入、Main10/HDR 文件组合、采集回放、NR→SR、文件欠速/FG恢复、图片尺寸、source fidelity 均退出 0 | `logs/release-p1-20260913/cross/result.json` |
+| 非整数帧率 | 30000/1001 视频完整验证 90/90 帧,CFR 校验通过 | `cross/export-ntsc.stdout.log`、`inspect-ntsc.stdout.log` |
+| RTX 欠速尾部 | 实际 NR 16 次、NVOF 2 次、生成 1 帧,failed=false,退出 0;不是零迟到证明 | `cross/nr-fg-overloaded-tail.stdout.log` |
+| Delivery | 23 项全部通过,含 native 4K H.264/HEVC NVENC、音轨、完整短片解码及取消 | `logs/delivery/7490c0d852a04aadbe96eced2106524f/result.json` |
+
+表中 `verified/`、`cross/` 均相对 `logs/release-p1-20260913/`。单次调用 ≤180 秒,符合项目单项 ≤300 秒要求。
+
+RTX5070/驱动616.56 实际日志:
+
+```text
+snippet CreateFeature id=18 result=0x1 (NVSDK_NGX_Result_Success) handle=non-null seh=0
+fg-backend: Create DLSSG 640x360 ... result=0x1 ... seh=0
+smoke frames=16 generated=1 failed=false ... nrEvaluated=16 nvofExecuted=2
+fg-backend: ReleaseFeature result=0x1 ... evaluates=3 resets=2
+HDR_MAIN10_NR mode=1 sr=12 generated=11 hardware=1 confirmed=1 frames=12 evaluate=12 pass=1
+[export-verify] decoded=59 expected=60 eof=false cancelled=false passed=false
+[export-verify] decoded=90 expected=90 eof=true cancelled=false passed=true
+```
+
+初轮 `regression/result.json` 总结果为 false,因为脚本把实际失败码 1 误写成取消码 3。产品当时已正确失败、文件状态断言通过;修正期望后重跑通过。原记录保留。第二轮 `regression-final/` 通过后,自查清理重复状态初始化并补上提升输出前的取消检查,最终构建再跑 `verified/` 全部通过。没有修改 gate 门槛掩盖产品故障。
+
+## 实际命令
+
+在项目根目录执行:
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release -BuildDirectory out/release-p1-20260913/build -RemotePlay -ChiakiCheckout C:/veyra-deps/chiaki-source -ChiakiStage out/remoteplay/chiaki-msvc-stage -RemotePlayPrefixPath C:/veyra-deps/remoteplay-installed/x64-windows-static -ProtocPath C:/veyra-deps/remoteplay-installed/x64-windows/tools/protobuf/protoc.exe -PkgConfigPath C:/veyra-deps/vcpkg/downloads/tools/msys2/3e71d1f8e22ab23f/mingw64/bin/pkg-config.exe
+python scripts/gates/release-p1.py --root . --build-directory out/release-p1-20260913/build --output-directory logs/release-p1-20260913/verified
+python out/release-p1-20260913/cross_checks.py
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/release-p1-20260913/build
+git diff --check
+```
+
+delivery 命令由 cross runner 调用一次;完整命令、耗时和退出码保存于两个 result.json。重跑 P1 gate 要选择新的 output-directory,脚本拒绝覆盖旧证据。
+
+## 边界与后续
+
+普通文件中途改变尺寸会明确停止,本次没有增加自动变分辨率播放/导出功能。导出结束增加全片 CPU 解码验证,会延长验证阶段;这不是增强路径 GPU→CPU 像素回读,验证可取消。
+
+patched FFmpeg hash 与开工一致;未修改 SDK、NVIDIA 运行时、模型、凭据、个人配置或旧发布资产。实机 PS5/PSN、HDR 显示器、长时稳定性、4K60 采集卡和多 GPU 验收未执行;本轮 HDR/采集回放不能代替它们。
+
+下一步唯一事项:使用本轮新构建做用户试用验收;已运行的旧构建不会被自动替换。两个 P2 保留在审查报告中,不自动修复或发布。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 9c5f8815..6b156aff 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1792,3 +1792,31 @@ apps/veyra/SettingsWindow.cpp调整布局;apps/veyra/ui/AppShell.cpp新增音
用户授权修复后关机,随后撤回音频缓冲选项;未改任何音频逻辑。基线320f860,存档checkpoint/ps5-sampling-2026-09-13,分支codex/ps5-sampling-repair。新增显式色度位置契约与按位置插值(缺失left回退有日志);PS5普通放大使用带局部范围限幅的Catmull-Rom,像素中心1:1直接读取,缩小保留旧路径。默认精细、保留兼容采样,PS5面板可选且重连生效,选择保存在现有本地settings.ini;不改变主机配对、codec、码率和HDR选择,不另造播放循环/音频/队列或回读。文件、采集、导出默认不启用新采样。
cmd /c out/remoteplay/build-clock-product.cmd 两次成功,日志logs/ps5-sampling-product-build.log与logs/ps5-sampling-final-build.log;DXIL及C++编译链接成功,diff检查通过。按用户要求不运行测试、不连接PS5、不做肉眼判断;NR/SR/FG Create/Evaluate、GPU采样成本、HDR与UI显示均未执行,不能把编译成功说成视觉改善已验收。修改文件/链路边界/明天A-B方法见docs/PS5_SAMPLING_REPAIR_PLAN_2026-09-13.md。桌面测试版对应out/remoteplay/product-repair/veyra.exe。未推送发布,未提交SDK/运行时/凭据/日志/测试媒体;完成本地存档后执行用户授权的正常关机请求。
+
+## 2026-09-13 正式发布前完整审查(发现发布阻断,未修产品代码)
+
+用户要求正式发布前审查 bug。基线 f037f49,codex/ps5-sampling-repair,开工工作区干净;本轮用户要求审查后实际执行测试,不能继续沿用上次“仅编译”的证据限制。报告 `docs/RELEASE_AUDIT_2026-09-13.md` 列出 5 项确认问题:P1 欠速播放到 EOF 复用已清空 AVFrame 导致 0xC0000409;P1 变分辨率文件用新尺寸写旧 YUV 上传容量;P1 损坏尾部导出 52/60 帧仍报成功且音轨缩短;P2 partial 检查/打开竞争可覆盖另一任务文件;P2 内嵌字幕导出无提示丢失。只形成审查结果,未修复这些问题。
+
+执行 `scripts/build.ps1 -Preset x64-release -BuildDirectory out/release-audit-20260913/build -RemotePlay`(完整依赖参数见报告),444 步成功;`scripts/gates/delivery.ps1 -Root . -BuildDirectory out/release-audit-20260913/build` 的 23 项通过,45.033 秒,result=`logs/delivery/c992884d6d924d02a4cce0374a758094/result.json`。临时 runner 的 27 项及扩展 16 项运行通过;初次 seek 压力用 60 秒素材却要求跳到 700 秒导致退出 1,保留原失败,改 710 秒素材后相同测试全部通过(22.156 秒)。Remote Play core 新构建 73/73;精细采样临时数值对照 30 组通过,1:1 最大误差 0、放大 0.560/255、六色度位置 0.588/255,均为合成 SDR 呈现缓冲检查;不是游戏画质或显示器验收。
+
+本机 RTX5070/616.56 实际 NR Feature18、SR、DLSSG Create 均 result=0x1/seh=0;NR/FG/NVOF 实际执行及输出验证见 nr-flow/sr-nr-fg 日志,便携 VSR smoke 记录 nrEvaluated=120、nvofExecuted=117、generated=115。真实 USB3 Video 1080p60 YUY2/MJPEG 各收到 19 帧,消费者停顿时正确丢过期帧;未据此宣称实卡画质/4K60通过。本地 `package-portable.ps1` 与 `acceptance/portable-smoke.ps1` 的 5 场景通过,七文件 manifest 身份/许可证/扫描通过,软件不依赖 publisher manifest 的决定保持有效。审查 ZIP 只在本地,未上传,不能作无缺陷正式候选。
+
+完整命令/日志/失败复现位于 `logs/release-audit-20260913/` 和报告,辅助脚本/合成素材均在忽略目录。原版/社区 NR 身份符合批准记录;patched avcodec SHA256=0710F0D87A7FFCC9F998F1A35D0500345F6C66EB9A5A39C51D60D293142BD84F,未退回未补丁 FFmpeg。未修改、提交任何 SDK/DLL/模型/个人配置/凭据/测试媒体。未连接实际 PS5、未做 PSN/HDR 显示器/长时稳定性/多 GPU/4K60采集端到端验收;本轮没有独立 Reviewer。修改仅为本审查报告与 WORKLOG。下一项唯一任务:修复 EOF 候选帧寿命并针对性回归,再按报告优先级清理其余问题,当前不建议正式发布。
+
+## 2026-09-13 仅修复发布审查三个 P1(本地回归通过)
+
+用户明确“只修复p1”,本轮仅处理 F1/F2/F3,F4/F5 两个 P2 未改。基线 f037f49,存档 tag 为 checkpoint/release-p1-2026-09-13,施工分支 codex/release-p1-repair;保留此前审查报告与工作记录。完整修改清单、命令、证据与限制见 docs/RELEASE_P1_REPAIR_PLAN_2026-09-13.md。
+
+F1:EngineController 在追帧读取下一帧前用 av_frame_clone 持有候选帧引用,EOF 不再使用被源清空的借用 AVFrame;复用原缓存,不增加像素拷贝。F2:EnhanceGraph 在访问像素/上传资源前校验尺寸及像素格式,MediaFileSource 对中途变尺寸明确报错并锁存失败;普通文件不会自动重建图。F3:解码器区分 NeedInput/Frame/EndOfStream/Error,源拒绝损坏包/帧及硬解码错误,导出传播视频/音频读取错误,结束时全片解码校验输出帧数、尺寸、CFR PTS 与真实 EOF,成功后才提升 partial;验证可取消。ExportJobManager 保留子进程最终失败原因,避免早期失败被误写成已保留 partial。未修改音频调度或两个 P2。
+
+scripts/build.ps1 -Root . -Preset x64-release -BuildDirectory out/release-p1-20260913/build -RemotePlay(依赖完整参数见修复文档)初次 446 步、最终增量 31 步成功;日志 logs/release-p1-20260913/build.log、rebuild.log、final-build.log。新增 tests/integration/FileSafetyTests.cpp 与 scripts/gates/release-p1.py;python scripts/gates/release-p1.py --root . --build-directory out/release-p1-20260913/build --output-directory logs/release-p1-20260913/verified 最终 29 次进程调用及 12 项额外文件/音频/计数断言全部通过,总耗时 25.032 秒。覆盖正常/强制欠速 EOF、暂停 seek/resume、大小/零尺寸/非法格式、坏帧失败锁存及 seek/reopen、早晚损坏输入、变尺寸输入、输出损坏、验证取消、边界中止、实际导出 worker 失败消息、4K B 帧线程解码逐像素与 PTS 一致性。早期损坏返回 1 且无输出,晚期损坏/变尺寸返回 1 且只保留 partial;篡坏刚编码的尾包得到 decoded=59 expected=60 eof=false passed=false;健康输出 60/240 帧及音频时长正确。
+
+首轮 regression/result.json 为 false:测试脚本将失败退出码误写为取消码 3,实际产品正确返回 1,文件状态断言正确;修正期望后 regression-final 全通过。自查去除重复状态初始化、增加提升输出前取消检查后重新构建,最终 verified 全通过;原失败证据保留。没有独立 Reviewer。
+
+python out/release-p1-20260913/cross_checks.py 的 13 项调用全部退出 0,结果 logs/release-p1-20260913/cross/result.json;包含硬解导入、HDR Main10 软件/硬件路径、实时回放、NR 先行、欠速音频连续性、FG 恢复、图片尺寸、源保真、NTSC 导出及 NR/FG 实际欠速尾帧。RTX5070/616.56 实际 Feature18/DLSSG Create result=0x1、seh=0;欠速尾帧 nrEvaluated=16、nvofExecuted=2、generated=1、failed=false;Main10 硬解 confirmed=1,NR/SR 各 12、FG 11。NTSC 30000/1001 输出验证 90/90 帧,视频 3.003 秒、音频 3.000 秒。强制欠速测试不代表性能改善。
+
+cross runner 调用 scripts/gates/delivery.ps1 -Root . -BuildDirectory out/release-p1-20260913/build 一次,23/23 通过,45.3460832 秒;证据 logs/delivery/7490c0d852a04aadbe96eced2106524f/result.json,status=software_short_gate_passed。包含实际 native4K NR/NVOF、D3D12 NVENC H.264/HEVC、FG、输出解码/音频、暂停 seek、图片及取消。
+
+新程序 out/release-p1-20260913/build/veyra.exe,SHA256=B116AB6855D69CDEB29927AB3AD80422D54051339FCE47D7EE5939CAA987519D。patched avcodec-63.dll SHA256=0710F0D87A7FFCC9F998F1A35D0500345F6C66EB9A5A39C51D60D293142BD84F,与开工一致,未退回未打补丁的 FFmpeg;原版/社区 NR 身份符合已批准记录。未修改运行时、SDK、模型、凭据、个人配置或既有发布资产;未推送、打包上传或发布。
+
+限制:变分辨率文件明确停止;全片 CPU 解码验证会增加导出收尾时间,但可取消,不是增强路径 GPU→CPU 回读。实机 PS5/PSN、HDR 显示器、长时稳定性、多 GPU、4K60 采集卡端到端验收未执行,本轮回放不代表实卡通过。下一项唯一任务:用户试用本轮新构建;正在运行的旧程序不会自动更新。两个 P2 按用户范围保留。
diff --git a/include/veyra/media/FFmpegVideoDecoder.h b/include/veyra/media/FFmpegVideoDecoder.h
index c60b0df1..3931b544 100644
--- a/include/veyra/media/FFmpegVideoDecoder.h
+++ b/include/veyra/media/FFmpegVideoDecoder.h
@@ -25,6 +25,8 @@ struct DecoderStats {
uint64_t pixelReadbackCount = 0; // software decode uploads only; always 0 on the GPU path
};
+enum class DecodeReceiveStatus { NeedInput, Frame, EndOfStream, Error };
+
class FFmpegVideoDecoder {
public:
FFmpegVideoDecoder() = default;
@@ -61,6 +63,8 @@ public:
// Receive one decoded frame; false when more input is needed or at EOF.
// The frame stays owned by the decoder and is valid until the next call.
const AVFrame* receiveFrame();
+ // nullptr can mean pending input, normal EOF, or a hard decode error.
+ DecodeReceiveStatus receiveStatus() const { return receiveStatus_; }
void flushBuffers(); // seek boundary (Playbook 13.4)
const DecoderStats& stats() const { return stats_; }
@@ -78,6 +82,7 @@ public:
private:
AVCodecContext* context_ = nullptr;
AVFrame* frame_ = nullptr;
+ DecodeReceiveStatus receiveStatus_ = DecodeReceiveStatus::NeedInput;
int frameTimeBaseNum_ = 0;
int frameTimeBaseDen_ = 0;
DecoderStats stats_{};
diff --git a/include/veyra/source/MediaFileSource.h b/include/veyra/source/MediaFileSource.h
index 21f913a7..b5445b94 100644
--- a/include/veyra/source/MediaFileSource.h
+++ b/include/veyra/source/MediaFileSource.h
@@ -30,6 +30,7 @@ public:
uint64_t framesRead() const { return framesRead_; }
uint64_t seekCount() const { return seekCount_; }
uint64_t epoch() const { return epoch_; }
+ const std::wstring& errorMessage() const { return errorMessage_; }
private:
pipeline::ColorDescription parseColor(const AVCodecParameters* params) const;
@@ -44,6 +45,7 @@ private:
bool pendingSeekFlag_ = false;
bool draining_ = false;
bool eofSignalled_ = false;
+ std::wstring errorMessage_;
int64_t lastPtsUs_ = INT64_MIN;
};
diff --git a/scripts/gates/release-p1.py b/scripts/gates/release-p1.py
new file mode 100644
index 00000000..4a04f419
--- /dev/null
+++ b/scripts/gates/release-p1.py
@@ -0,0 +1,129 @@
+"""Generate owned fixtures and exercise the three 2026-09-13 release P1 fixes.
+
+Uses the real product EXE/libraries, FFmpeg/ffprobe, and the local NVIDIA GPU.
+All outputs go into a new directory; existing evidence is never overwritten.
+"""
+import argparse
+import json
+import pathlib
+import shutil
+import subprocess
+import time
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--root', type=pathlib.Path, default=pathlib.Path(__file__).resolve().parents[2])
+parser.add_argument('--build-directory', type=pathlib.Path, required=True)
+parser.add_argument('--output-directory', type=pathlib.Path, required=True)
+args = parser.parse_args()
+root = args.root.resolve()
+build = args.build_directory.resolve()
+output = args.output_directory.resolve()
+output.mkdir(parents=True, exist_ok=False)
+ffmpeg, ffprobe = shutil.which('ffmpeg'), shutil.which('ffprobe')
+if not ffmpeg or not ffprobe:
+ raise SystemExit('FFmpeg and ffprobe must be on PATH')
+test = build / 'veyra_file_safety_tests.exe'
+player = build / 'veyra.exe'
+startup = subprocess.STARTUPINFO()
+startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW
+startup.wShowWindow = 0
+records = []
+assertions = []
+
+
+def run(name, command, expected=0):
+ command = [str(item) for item in command]
+ start = time.monotonic()
+ with (output / (name + '.stdout.log')).open('wb') as stdout, (output / (name + '.stderr.log')).open('wb') as stderr:
+ try:
+ code = subprocess.run(command, cwd=root, stdout=stdout, stderr=stderr,
+ timeout=180, startupinfo=startup).returncode
+ except subprocess.TimeoutExpired:
+ code = 124
+ records.append(dict(name=name, command=command, exit=code, expected=expected,
+ passed=code == expected, seconds=round(time.monotonic() - start, 3)))
+ save()
+ print(f'{name}: exit={code} expected={expected}', flush=True)
+ return code == expected
+
+
+def check(name, condition):
+ assertions.append(dict(name=name, passed=bool(condition)))
+ save()
+ print(('PASS ' if condition else 'FAIL ') + name, flush=True)
+
+
+def save():
+ (output / 'result.json').write_text(json.dumps(dict(runs=records, assertions=assertions,
+ passed=all(r['passed'] for r in records + assertions)), indent=2), encoding='utf-8')
+
+
+def make_clip(name, duration):
+ path = output / (name + '.mp4')
+ if not run('make-' + name, [ffmpeg, '-v', 'error', '-f', 'lavfi', '-i',
+ f'testsrc2=size=640x360:rate=30:duration={duration}', '-f', 'lavfi', '-i',
+ f'sine=frequency=400:sample_rate=48000:duration={duration}', '-c:v', 'libx264',
+ '-preset', 'ultrafast', '-g', '1', '-bf', '0', '-c:a', 'aac', '-movflags', '+faststart', path]):
+ raise SystemExit('Fixture generation failed')
+ return path
+
+
+def damage_tail(source, name):
+ run('packets-' + name, [ffprobe, '-v', 'error', '-select_streams', 'v:0', '-show_packets',
+ '-show_entries', 'packet=pos,size', '-of', 'json', source])
+ packets = json.loads((output / ('packets-' + name + '.stdout.log')).read_text())['packets']
+ data = bytearray(source.read_bytes())
+ for packet in packets[-8:]:
+ position, size = int(packet['pos']), int(packet['size'])
+ data[position:position + size] = bytes(size)
+ path = output / (name + '.mp4')
+ path.write_bytes(data)
+ return path
+
+
+short = make_clip('healthy', 2)
+long = make_clip('healthy-long', 8)
+bad_short = damage_tail(short, 'bad-early')
+bad_late = damage_tail(long, 'bad-late')
+for name, size, seconds in [('small', '320x180', 5), ('large', '640x360', 1)]:
+ run('make-' + name, [ffmpeg, '-v', 'error', '-f', 'lavfi', '-i',
+ f'testsrc2=size={size}:rate=30:duration={seconds}', '-c:v', 'libx264', '-preset', 'ultrafast',
+ '-g', '30', '-bf', '0', '-f', 'h264', output / (name + '.h264')])
+(output / 'resize.h264').write_bytes((output / 'small.h264').read_bytes() + (output / 'large.h264').read_bytes())
+resize = output / 'resize.mp4'
+run('mux-resize', [ffmpeg, '-v', 'error', '-fflags', '+genpts', '-r', '30', '-i',
+ output / 'resize.h264', '-c:v', 'copy', resize])
+bframes = output / 'bframes-4k.mp4'
+run('make-bframes-4k', [ffmpeg, '-v', 'error', '-f', 'lavfi', '-i',
+ 'testsrc2=size=3840x2160:rate=30:duration=0.8', '-c:v', 'libx264', '-preset', 'ultrafast',
+ '-g', '12', '-bf', '3', '-threads', '4', bframes])
+
+run('graph-contract', [test, 'graph'])
+for name, path, frames, damaged in [('healthy', short, 60, False), ('healthy-long', long, 240, False),
+ ('bframes-4k', bframes, 24, False), ('bad-early', bad_short, 60, True),
+ ('bad-late', bad_late, 240, True), ('resize', resize, 180, True)]:
+ run('source-' + name, [test, 'source-bad' if damaged else 'source-good', path, frames])
+run('threaded-bframes-reference', [build / 'veyra_source_tests.exe', bframes, '--threaded'])
+run('play-eof', [test, 'play-eof', short])
+run('play-overload-eof', [test, 'play-overload-eof', short])
+
+for name, path, expected, partial in [('healthy', short, 0, False), ('healthy-long', long, 0, False),
+ ('bad-early', bad_short, 1, False), ('bad-late', bad_late, 1, True), ('resize', resize, 1, True)]:
+ destination = output / (name + '-export.mp4')
+ run('export-' + name, [player, path, '--export-out', destination, '--no-nr', '--no-sr', '--no-fg'], expected)
+ check(name + '-final-file-state', destination.exists() == (expected == 0))
+ check(name + '-partial-state', pathlib.Path(str(destination) + '.partial').exists() == partial)
+ if expected == 0:
+ run('inspect-' + name, [ffprobe, '-v', 'error', '-count_frames', '-show_streams', '-of', 'json', destination])
+ streams = json.loads((output / ('inspect-' + name + '.stdout.log')).read_text())['streams']
+ video = next(s for s in streams if s['codec_type'] == 'video')
+ audio = next(s for s in streams if s['codec_type'] == 'audio')
+ duration = 2 if name == 'healthy' else 8
+ check(name + '-all-frames-audio-duration', int(video['nb_read_frames']) == duration * 30
+ and abs(float(video['duration']) - duration) < .001 and abs(float(audio['duration']) - duration) < .03)
+
+for mode in ['export-corrupt-output', 'export-cancel-verify', 'export-abort-boundary']:
+ run(mode, [test, mode, short, output / (mode + '.mp4')])
+run('export-worker-failure', [test, 'export-worker-failure', bad_short, output / 'worker-failure.mp4'])
+
+raise SystemExit(0 if all(r['passed'] for r in records + assertions) else 1)
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 223d85b6..b5d113dd 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -515,7 +515,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote){const auto recovery=remote->recoveryStatus();status(recovery.message.empty()?L"PS5 串流异常,请检查主机状态后重新连接。":recovery.message,true);break;}
#endif
- status(isCapture?L"采集信号中断,请检查设备连接或格式":L"视频解码或时间戳错误",true);break;}
+ status(isCapture?L"采集信号中断,请检查设备连接或格式":source.errorMessage().empty()?L"视频解码或时间戳错误":source.errorMessage(),true);break;}
}
if(isRemote&&frame&&(uint32_t(frame->width)!=width||uint32_t(frame->height)!=height)){
drainLivePresentation();if(!ring.drainQueue()){status(L"串流尺寸切换排空失败",true);break;}
@@ -545,6 +545,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
double pts=isImage?0:pkt.pts.toDouble()*1000;
if(isCapture&&frames==0){anchor=Clock::now();anchorMs=pts;}
if(pts+0.1<discardBefore)continue;
+ auto retainCandidate=[&](){
+ if(frame==cachedFrame)return true;
+ AVFrame* owned=av_frame_clone(frame);
+ if(!owned)return false;
+ av_frame_free(&cachedFrame);cachedFrame=owned;cachedPacket=pkt;frame=cachedFrame;
+ return true;
+ };
// Realtime preview candidates: decode stays ordered and
// reference-lossless; an expired candidate loses only its
// enhancement/display opportunity (plan §4.3). The open/seek
@@ -553,6 +560,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const double previewIntervalMs=double(liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps))/10000.0;
bool previewSourceFailed=false;
while(!stop_&&previewCandidateExpired(nowMs(),pts,previewIntervalMs)){
+ // read() can clear the decoder's borrowed AVFrame even
+ // on EOS/EAGAIN. Own this candidate before looking ahead.
+ if(!retainCandidate()){previewSourceFailed=true;break;}
pipeline::FramePacket next;const AVFrame* raw=nullptr;
const auto rs=activeSource->read(next,&raw);
if(rs==source::SourceReadStatus::Eos)break; // final decoded candidate is kept
@@ -563,9 +573,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
pts=nextPts;
++previewSkippedTotal;++previewSkippedSinceSubmit;previewSkipSinceProcess=true;
}
- if(previewSourceFailed){status(L"视频解码或时间戳错误",true);break;}
+ if(previewSourceFailed){status(source.errorMessage().empty()?L"视频读取或候选帧保存失败":source.errorMessage(),true);break;}
}
- if(frame!=cachedFrame){av_frame_free(&cachedFrame);cachedFrame=av_frame_clone(frame);cachedPacket=pkt;}
+ if(!retainCandidate()){status(L"无法保存解码帧,已停止播放",true);break;}
const auto processStart=Clock::now();
const auto captureArrival=pkt.arrivalHost100ns?pkt.arrivalHost100ns:host100ns();
// A PS5 callback is a compressed AU, not a decoded video frame.
diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cpp
index 29f20b24..4cdadf06 100644
--- a/src/engine/ExportJobManager.cpp
+++ b/src/engine/ExportJobManager.cpp
@@ -63,7 +63,11 @@ ExportJobSnapshot ExportJobManager::poll(){
if(!p_->shared)return p_->snapshot;
auto& s=*p_->shared;p_->snapshot.sourceFrames=InterlockedCompareExchange64(&s.sourceFrames,0,0);p_->snapshot.generated=InterlockedCompareExchange64(&s.generated,0,0);p_->snapshot.holds=InterlockedCompareExchange64(&s.holds,0,0);p_->snapshot.encoded=InterlockedCompareExchange64(&s.encoded,0,0);p_->snapshot.state=static_cast<ExportState>(InterlockedCompareExchange(&s.state,0,0));p_->snapshot.progress=InterlockedCompareExchange(&s.progress,0,0)/10000.0;
if(p_->cancelAt&&GetTickCount64()-p_->cancelAt>5000&&WaitForSingleObject(p_->process,0)==WAIT_TIMEOUT)TerminateJobObject(p_->job,3);
- if(WaitForSingleObject(p_->process,0)==WAIT_OBJECT_0){DWORD code=1;GetExitCodeProcess(p_->process,&code);p_->snapshot.state=code==0?ExportState::Succeeded:code==3||p_->cancelAt?ExportState::Cancelled:ExportState::Failed;if(code==0)p_->snapshot.progress=1;p_->snapshot.message=label(p_->snapshot.state);p_->clear();}
+ if(WaitForSingleObject(p_->process,0)==WAIT_OBJECT_0){DWORD code=1;GetExitCodeProcess(p_->process,&code);p_->snapshot.state=code==0?ExportState::Succeeded:code==3||p_->cancelAt?ExportState::Cancelled:ExportState::Failed;if(code==0)p_->snapshot.progress=1;
+ // The completed worker owns the final failure explanation, including
+ // whether preflight stopped before a partial file was ever created.
+ const bool explained=p_->snapshot.state==ExportState::Failed&&InterlockedCompareExchange(&s.state,0,0)==LONG(ExportState::Failed)&&s.message[0];
+ p_->snapshot.message=explained?s.message:label(p_->snapshot.state);p_->clear();}
if(p_->shared&&InterlockedCompareExchange(&p_->shared->messageLock,1,0)==0){if(p_->shared->message[0])p_->snapshot.message=p_->shared->message;InterlockedExchange(&p_->shared->messageLock,0);}if(p_->snapshot.message.empty()||p_->snapshot.state==ExportState::Paused||p_->snapshot.state==ExportState::Cancelled)p_->snapshot.message=label(p_->snapshot.state);return p_->snapshot;
}
int runExportWorker(HANDLE mapping){
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index d9794ec1..2e702851 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -29,6 +29,8 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);sink::NvencD3D12Encoder enc;
AVFormatContext *mux=nullptr,*audioInput=nullptr;AVStream* videoStream=nullptr;AVStream* audioStream=nullptr;AVPacket* audioPacket=av_packet_alloc();
int audioIndex=-1;bool audioPending=false,audioEof=false,ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;
+ std::wstring failureReason;
+ uint32_t outputWidth=0,outputHeight=0;AVRational outputRate{};
const auto partial=output+L".partial";
try { do {
Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;
@@ -43,17 +45,19 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
// Bounded metadata scan; decoded pixels are not retained. Rewind the
// file source afterwards, preserving all source frames for the export.
std::vector<double> samples;bool scanError=false;
- for(unsigned i=0;i<120&&!cancel;++i){pipeline::FramePacket p;const AVFrame* f=nullptr;const auto rs=source.read(p,&f);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||p.pts.isUnknown()){scanError=true;break;}samples.push_back(p.pts.toDouble());}
+ for(unsigned i=0;i<120&&!cancel;++i){pipeline::FramePacket p;const AVFrame* f=nullptr;const auto rs=source.read(p,&f);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||p.pts.isUnknown()){failureReason=source.errorMessage();scanError=true;break;}samples.push_back(p.pts.toDouble());}
if(scanError||samples.empty()||cancel)break;
const auto [rateNum,rateDen]=CfrTimeline::select(info.nominalRateNum,info.nominalRateDen,info.timestampQuantum,samples);
CfrTimeline timeline(rateNum,rateDen,info.timestampQuantum,samples.front());
if(!timeline.valid()){progress(0,L"无法确认一致的恒定帧率,已停止导出");veyra::log::error("export-timeline","CFR rejected source=preflight; no timestamp-consistent rate candidate");break;}
source.close();if(!source.open(od))break; // reopen from the true beginning, including negative PTS
const AVRational rate=av_mul_q({rateNum,rateDen},{int(options.fg?options.fgMultiplier:1),1});
+ outputRate=rate;
veyra::log::info("export-timeline",std::format("CFR declared={}/{} candidate={}/{} timestampQuantum={} sampled={} output={}/{} (timestamp-consistent candidate, quantized short clips may be ambiguous; every PTS validated)",info.nominalRateNum,info.nominalRateDen,rateNum,rateDen,info.timestampQuantum,samples.size(),rate.num,rate.den));
const auto resolution=pipeline::ResolutionPlan::make({info.width,info.height},options.sr,pipeline::NrSizePolicy::Native,true,options.settings.revision,options.settings.srTarget);
pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.nrRuntime=options.settings.nrRuntime;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
if(!graph.initialize(gd)||!graph.createViews())break;
+ outputWidth=gd.workWidth;outputHeight=gd.workHeight;
if(avformat_alloc_output_context2(&mux,nullptr,"mp4",utf8(partial).c_str())<0||!mux)break;
videoStream=avformat_new_stream(mux,nullptr);if(!videoStream)break;videoStream->time_base={rate.den,rate.num};videoStream->avg_frame_rate=rate;
auto* cp=videoStream->codecpar;cp->codec_type=AVMEDIA_TYPE_VIDEO;cp->codec_id=hevc?AV_CODEC_ID_HEVC:AV_CODEC_ID_H264;cp->width=gd.workWidth;cp->height=gd.workHeight;cp->format=AV_PIX_FMT_YUV420P;cp->color_range=AVCOL_RANGE_MPEG;cp->color_space=AVCOL_SPC_BT709;cp->color_primaries=AVCOL_PRI_BT709;cp->color_trc=AVCOL_TRC_IEC61966_2_1;
@@ -68,7 +72,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
av_dict_copy(&mux->metadata,audioInput->metadata,0);
}
auto writeAudioUntil=[&](double seconds){if(!audioStream)return true;
- for(;;){if(!audioPending){if(audioEof)return true;av_packet_unref(audioPacket);if(av_read_frame(audioInput,audioPacket)<0){audioEof=true;return true;}if(audioPacket->stream_index!=audioIndex)continue;audioPending=true;}
+ for(;;){if(!audioPending){if(audioEof)return true;av_packet_unref(audioPacket);const int readResult=av_read_frame(audioInput,audioPacket);if(readResult==AVERROR_EOF){audioEof=true;return true;}if(readResult<0){veyra::log::error("export-audio",std::format("source packet read failed code={}",readResult));return false;}if(audioPacket->stream_index!=audioIndex)continue;if(audioPacket->flags&AV_PKT_FLAG_CORRUPT){veyra::log::error("export-audio","corrupt source audio packet");return false;}audioPending=true;}
const auto tb=audioInput->streams[audioIndex]->time_base;const int64_t ts=audioPacket->pts!=AV_NOPTS_VALUE?audioPacket->pts:audioPacket->dts;const double time=ts==AV_NOPTS_VALUE?0:ts*av_q2d(tb)-videoOriginSeconds;if(time>seconds)return true;
const int64_t origin=av_rescale_q(static_cast<int64_t>(videoOriginSeconds*1000000),{1,1000000},tb);
if(audioPacket->pts!=AV_NOPTS_VALUE)audioPacket->pts-=origin;if(audioPacket->dts!=AV_NOPTS_VALUE)audioPacket->dts-=origin;
@@ -83,7 +87,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
auto headers=enc.headers();cp->extradata=static_cast<uint8_t*>(av_mallocz(headers.size()+AV_INPUT_BUFFER_PADDING_SIZE));if(!cp->extradata)break;memcpy(cp->extradata,headers.data(),headers.size());cp->extradata_size=int(headers.size());
if(avio_open(&mux->pb,utf8(partial).c_str(),AVIO_FLAG_WRITE)<0||avformat_write_header(mux,nullptr)<0)break;headerWritten=true;
uint64_t sourceCount=0,generatedCount=0,holdCount=0;int64_t outputIndex=0;bool error=false;std::shared_ptr<pipeline::FrameLease> lastReal;
- while(!cancel){if(frameBoundary&&!frameBoundary())break;pipeline::FramePacket packet;const AVFrame* frame=nullptr;const auto rs=source.read(packet,&frame);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){error=true;break;}
+ while(!cancel){if(frameBoundary&&!frameBoundary()){error=true;break;}pipeline::FramePacket packet;const AVFrame* frame=nullptr;const auto rs=source.read(packet,&frame);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){failureReason=source.errorMessage();error=true;break;}
if(sourceCount==0)videoOriginSeconds=packet.pts.toDouble();
const double expectedPts=timeline.expected(sourceCount);
if(!timeline.accepts(sourceCount,packet.pts.toDouble())){
@@ -121,7 +125,33 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
}while(false); }catch(const std::exception&){progress(0,L"导出异常,已保留partial,请查看诊断");ok=false;}
enc.close();if(mux){if(mux->pb)avio_closep(&mux->pb);avformat_free_context(mux);}if(audioInput)avformat_close_input(&audioInput);av_packet_free(&audioPacket);
ring.drainQueue();graph.shutdown();source.close();ring.shutdown();ctx.shutdown();
- if(ok){progress(.999,L"正在封装和验证输出");source::MediaFileSource check;source::SourceOpenDesc od;od.path=partial;od.preferHardwareDecode=false;pipeline::FramePacket pkt;const AVFrame* frame=nullptr;ok=check.open(od)&&check.read(pkt,&frame)==source::SourceReadStatus::Frame;check.close();if(ok)ok=MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;}
- progress(ok?1:0,ok?L"视频导出完成,解码回读成功":cancel?L"导出已取消,partial文件已保留":L"视频导出失败,partial文件已保留,请查看诊断");return ok;
+ if(ok){
+ progress(.999,L"正在封装和验证输出");
+ source::MediaFileSource check;source::SourceOpenDesc od;od.path=partial;od.preferHardwareDecode=false;
+ ok=!cancel&&check.open(od);
+ const auto info=check.info();
+ CfrTimeline verifiedTimeline(outputRate.num,outputRate.den,info.timestampQuantum,0);
+ ok=ok&&info.width==outputWidth&&info.height==outputHeight&&verifiedTimeline.valid();
+ uint64_t decoded=0;bool reachedEos=false;
+ while(ok&&!cancel){
+ pipeline::FramePacket pkt;const AVFrame* frame=nullptr;const auto rs=check.read(pkt,&frame);
+ if(rs==source::SourceReadStatus::Eos){reachedEos=true;break;}
+ if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()||decoded>=uint64_t(written)||!verifiedTimeline.accepts(decoded,pkt.pts.toDouble())){ok=false;break;}
+ ++decoded;
+ }
+ ok=ok&&!cancel&&reachedEos&&decoded==uint64_t(written);
+ veyra::log::info("export-verify",std::format("decoded={} expected={} eof={} cancelled={} passed={}",decoded,written,reachedEos,bool(cancel),ok));
+ check.close();
+ if(!ok&&!cancel)failureReason=L"输出完整性验证失败,未生成正式文件";
+ if(ok)ok=!cancel&&MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;
+ }
+ if(ok)progress(1,L"视频导出完成,逐帧完整性验证通过");
+ else {
+ std::wstring message=cancel?L"导出已取消":failureReason.empty()?L"视频导出失败,请查看诊断":failureReason;
+ std::error_code ec;
+ message+=std::filesystem::exists(partial,ec)?L";partial文件已保留":L";未生成输出文件";
+ progress(0,message);
+ }
+ return ok;
}
}
diff --git a/src/media/FFmpegVideoDecoder.cpp b/src/media/FFmpegVideoDecoder.cpp
index a1b083cb..a010cd8d 100644
--- a/src/media/FFmpegVideoDecoder.cpp
+++ b/src/media/FFmpegVideoDecoder.cpp
@@ -39,6 +39,7 @@ FFmpegVideoDecoder::~FFmpegVideoDecoder()
bool FFmpegVideoDecoder::openSoftware(const AVCodecParameters* codecParameters,
int streamTimeBaseNum, int streamTimeBaseDen, unsigned softwareThreads)
{
+ receiveStatus_ = DecodeReceiveStatus::NeedInput;
if (context_ != nullptr) {
close();
}
@@ -91,6 +92,7 @@ bool FFmpegVideoDecoder::openD3D12VA(const AVCodecParameters* codecParameters,
int streamTimeBaseNum, int streamTimeBaseDen,
ID3D12Device* device, ID3D12CommandQueue* queue)
{
+ receiveStatus_ = DecodeReceiveStatus::NeedInput;
if (context_ != nullptr) {
close();
}
@@ -160,6 +162,7 @@ bool FFmpegVideoDecoder::openD3D12VA(const AVCodecParameters* codecParameters,
void FFmpegVideoDecoder::close()
{
+ receiveStatus_ = DecodeReceiveStatus::NeedInput;
if (frame_ != nullptr) {
av_frame_free(&frame_);
}
@@ -204,12 +207,22 @@ bool FFmpegVideoDecoder::sendPacket(const AVPacket* packet)
const AVFrame* FFmpegVideoDecoder::receiveFrame()
{
if (context_ == nullptr) {
+ receiveStatus_ = DecodeReceiveStatus::Error;
return nullptr;
}
const int result = avcodec_receive_frame(context_, frame_);
if (result < 0) {
+ if (result == AVERROR(EAGAIN)) receiveStatus_ = DecodeReceiveStatus::NeedInput;
+ else if (result == AVERROR_EOF) receiveStatus_ = DecodeReceiveStatus::EndOfStream;
+ else {
+ receiveStatus_ = DecodeReceiveStatus::Error;
+ char errorText[AV_ERROR_MAX_STRING_SIZE]{};
+ av_strerror(result, errorText, sizeof(errorText));
+ log::error("media", std::format("decoder: receive_frame failed code={} text={}", result, errorText));
+ }
return nullptr;
}
+ receiveStatus_ = DecodeReceiveStatus::Frame;
++stats_.framesDecoded;
// Frame timestamps are in the CODEC context time_base; AVFrame.time_base
// is not reliably populated by every decoder path.
@@ -257,6 +270,7 @@ const AVFrame* FFmpegVideoDecoder::receiveFrame()
void FFmpegVideoDecoder::flushBuffers()
{
+ receiveStatus_ = DecodeReceiveStatus::NeedInput;
if (context_ != nullptr) {
avcodec_flush_buffers(context_);
}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index d8732fb9..5d028d8d 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -31,6 +31,7 @@
extern "C" {
#include <libavutil/frame.h>
+#include <libavutil/pixdesc.h>
#include <libavutil/hwcontext_d3d12va.h>
#include <libswscale/swscale.h>
}
@@ -663,6 +664,13 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
diagnostic.resolution.source={srcW_,srcH_};diagnostic.resolution.base={workW_,workH_};diagnostic.resolution.nr={nrW_,nrH_};diagnostic.resolution.flow={nvofW_,nvofH_};diagnostic.resolution.fg=diagnostic.resolution.output={workW_,workH_};diagnostic.runtimeHash="unverified-user-replaceable";diagnostic.flowApplied=std::to_string(actualFlowPerf());diagnostic.fallbackReason=mvecSource_;Logger::diagnosticContext(diagnostic);
static const bool graphOff = GetEnvironmentVariableW(L"VEYRA_GRAPH_OFF", nullptr, 0) != 0;
if (!frame || !initialized_ || !std::isfinite(ptsMs)) return false;
+ // Reject before CPU plane access, swscale, or command-slot acquisition.
+ // Source-side resize handling must rebuild the graph before submitting a
+ // new extent; all upload sizes/strides still belong to this graph's extent.
+ if (frame->width <= 0 || frame->height <= 0 || uint32_t(frame->width) != srcW_ || uint32_t(frame->height) != srcH_ || !av_pix_fmt_desc_get(static_cast<AVPixelFormat>(frame->format))) {
+ veyra::log::error("graph", std::format("frame contract rejected: expected={}x{} actual={}x{} format={}", srcW_, srcH_, frame->width, frame->height, frame->format));
+ return false;
+ }
const auto resolved=resolveFrameColor(*frame,color?*color:ColorDescription{});
if(resolved.matrix==YuvMatrix::BT2020CL||resolved.transfer==TransferFunction::BT2020_10||(resolved.matrix==YuvMatrix::BT2020NCL&&!desc_.hdrInput)){veyra::log::error("graph","BT.2020 input is not supported by the BT.601/709 SDR conversion");return false;}
if(resolved.transfer==TransferFunction::PQ&&(resolved.matrix!=YuvMatrix::BT2020NCL||resolved.primaries!=ColorPrimaries::BT2020)){
diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cpp
index 25dd1bef..b51d37ca 100644
--- a/src/source/MediaFileSource.cpp
+++ b/src/source/MediaFileSource.cpp
@@ -153,30 +153,53 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)
SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame** decodedFrame)
{
- if (!info_.opened) { return SourceReadStatus::Error; }
if (decodedFrame != nullptr) { *decodedFrame = nullptr; }
+ out = pipeline::FramePacket{};
+ if (!info_.opened || !errorMessage_.empty()) { return SourceReadStatus::Error; }
const AVFrame* frame = nullptr;
for (;;) {
frame = decoder_.receiveFrame();
if (frame != nullptr) { break; }
- if (draining_) {
- // Decoder fully drained after EOF.
+ if (decoder_.receiveStatus() == media::DecodeReceiveStatus::EndOfStream) {
return SourceReadStatus::Eos;
}
+ if (decoder_.receiveStatus() == media::DecodeReceiveStatus::Error || draining_) {
+ errorMessage_ = L"视频解码失败,已停止处理,请检查源文件是否损坏";
+ return SourceReadStatus::Error;
+ }
bool eof = false;
if (!demuxer_.readVideoPacket(eof)) {
- if (!eof) { return SourceReadStatus::Error; }
+ if (!eof) { errorMessage_ = L"源视频读取失败,已停止处理"; return SourceReadStatus::Error; }
draining_ = true;
- decoder_.sendPacket(nullptr); // enter drain mode
+ if (!decoder_.sendPacket(nullptr)) {
+ errorMessage_ = L"视频尾帧解码失败,已停止处理";
+ return SourceReadStatus::Error;
+ }
continue;
}
+ if (demuxer_.currentPacket()->flags & AV_PKT_FLAG_CORRUPT) {
+ veyra::log::error("source-file", "corrupt video packet; refusing to skip source data");
+ errorMessage_ = L"源视频包含损坏数据,已停止处理";
+ return SourceReadStatus::Error;
+ }
if (!decoder_.sendPacket(demuxer_.currentPacket())) {
- veyra::log::warn("source-file", "sendPacket rejected; retrying next packet");
+ errorMessage_ = L"视频解码失败,已停止处理,请检查源文件是否损坏";
+ return SourceReadStatus::Error;
}
}
- out = pipeline::FramePacket{};
+ if ((frame->flags & AV_FRAME_FLAG_CORRUPT) || frame->decode_error_flags) {
+ veyra::log::error("source-file", std::format("corrupt decoded frame flags={} decodeErrors={}", frame->flags, frame->decode_error_flags));
+ errorMessage_ = L"源视频包含损坏画面,已停止处理";
+ return SourceReadStatus::Error;
+ }
+ if (frame->width <= 0 || frame->height <= 0 || uint32_t(frame->width) != info_.width || uint32_t(frame->height) != info_.height) {
+ veyra::log::error("source-file", std::format("frame extent changed: opened={}x{} decoded={}x{}; file processing stopped before upload", info_.width, info_.height, frame->width, frame->height));
+ errorMessage_ = L"视频中途改变分辨率,当前文件处理不支持,已安全停止";
+ return SourceReadStatus::Error;
+ }
+
++sequence_;
out.sequence = sequence_;
const int tbNum = decoder_.frameTimeBaseNum();
@@ -229,6 +252,7 @@ bool MediaFileSource::seek(const pipeline::Rational& targetSeconds)
const int64_t targetUs = rationalToUs(targetSeconds);
if (!demuxer_.seekToUs(targetUs)) { return false; }
decoder_.flushBuffers();
+ errorMessage_.clear();
draining_ = false;
eofSignalled_ = false;
pendingSeekFlag_ = true;
@@ -241,6 +265,7 @@ bool MediaFileSource::seek(const pipeline::Rational& targetSeconds)
void MediaFileSource::close() noexcept
{
+ errorMessage_.clear();
decoder_.close();
demuxer_.close();
info_ = SourceInfo{};
diff --git a/tests/integration/FileSafetyTests.cpp b/tests/integration/FileSafetyTests.cpp
new file mode 100644
index 00000000..b96311f7
--- /dev/null
+++ b/tests/integration/FileSafetyTests.cpp
@@ -0,0 +1,144 @@
+#include "veyra/engine/EngineController.h"
+#include "veyra/engine/VideoExportJob.h"
+#include "veyra/engine/ExportJobManager.h"
+#include "veyra/source/MediaFileSource.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/sink/ImageExportSink.h"
+#include <chrono>
+#include <algorithm>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <thread>
+#include <vector>
+extern "C" {
+#include <libavformat/avformat.h>
+#include <libavutil/frame.h>
+}
+
+using namespace veyra;
+namespace {
+int failures=0;
+void check(bool ok,const char* name){std::cout<<(ok?"PASS ":"FAIL ")<<name<<std::endl;failures+=!ok;}
+
+void sourceTest(const std::wstring& path,unsigned expected,bool damaged){
+ source::MediaFileSource input;source::SourceOpenDesc desc;desc.path=path;desc.preferHardwareDecode=false;
+ if(!input.open(desc)){check(false,"source opens");return;}
+ pipeline::FramePacket packet;const AVFrame* frame=nullptr;
+ unsigned count=0;auto state=source::SourceReadStatus::Error;
+ while(count<=expected&&(state=input.read(packet,&frame))==source::SourceReadStatus::Frame){
+ if(!frame||frame->width!=int(input.info().width)||frame->height!=int(input.info().height)){check(false,"source never returns mismatched extent");return;}
+ ++count;
+ }
+ if(damaged){
+ check(state==source::SourceReadStatus::Error&&count>0&&count<expected,"bad input is an error, not short successful EOF");
+ check(!input.errorMessage().empty(),"source explains failure");
+ check(input.read(packet,&frame)==source::SourceReadStatus::Error&&frame==nullptr,"error stays latched");
+ }else check(state==source::SourceReadStatus::Eos&&count==expected,"healthy input drains every frame");
+ check(input.seek({0,1}),"seek after EOF/error accepted");
+ check(input.errorMessage().empty()&&input.read(packet,&frame)==source::SourceReadStatus::Frame,"seek clears error and restarts decoding");
+ input.close();check(input.open(desc)&&input.read(packet,&frame)==source::SourceReadStatus::Frame,"reopen clears error and restarts decoding");
+}
+
+void graphTest(){
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;
+ if(!ctx.initialize({},status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status)){check(false,"graph device initialized");return;}
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc desc;
+ desc.sourceWidth=desc.workWidth=32;desc.sourceHeight=desc.workHeight=16;
+ desc.enableNr=desc.enableSr=desc.enableFg=false;desc.noFeatures=true;
+ if(!graph.initialize(desc)||!graph.createViews()){check(false,"graph initialized");return;}
+ pipeline::EnhanceGraph::FrameOutputs out;
+ // No pixel allocation: a rejected input must never touch any plane.
+ for(auto size:{std::pair{64,32},std::pair{16,8},std::pair{0,16}}){
+ AVFrame invalid{};invalid.width=size.first;invalid.height=size.second;invalid.format=AV_PIX_FMT_YUV420P;
+ check(!graph.process(&invalid,0,true,out)&&out.batch.count==0,"wrong extent rejected before pixel access");
+ }
+ AVFrame invalid{};invalid.width=32;invalid.height=16;invalid.format=AV_PIX_FMT_NONE;
+ check(!graph.process(&invalid,0,true,out),"empty decoder frame rejected");
+ AVFrame* valid=av_frame_alloc();valid->width=32;valid->height=16;valid->format=AV_PIX_FMT_YUV420P;
+ if(av_frame_get_buffer(valid,32)<0){av_frame_free(&valid);check(false,"valid frame allocation");return;}
+ for(int p=0;p<3;++p)for(int y=0;y<(p?8:16);++y)std::fill_n(valid->data[p]+y*valid->linesize[p],p?16:32,uint8_t(128));
+ check(graph.process(valid,0,true,out),"valid frame accepted after rejection");
+ sink::RgbaImage image;
+ check(sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image)&&image.width==32&&image.height==16&&!image.pixels.empty()&&image.pixels[0]>0,"valid output remains readable and nonblack");
+ out={};ring.drainQueue();graph.shutdown();av_frame_free(&valid);
+}
+
+void playbackTest(const std::wstring& path,bool overload){
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",overload?L"150":nullptr);
+ HWND window=CreateWindowExW(0,L"STATIC",L"File safety regression",WS_POPUP,0,0,640,360,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ engine::EngineController player;engine::PlayerOptions options;options.nr=options.sr=options.fg=false;player.setVolume(0,true);
+ auto until=[&](auto predicate){
+ auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(15);
+ while(std::chrono::steady_clock::now()<deadline){
+ auto snapshot=player.snapshot();if(snapshot.failed)return false;if(predicate(snapshot))return true;
+ MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}
+ std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ }return false;
+ };
+ player.open(window,path,options);
+ check(until([](const auto& s){return s.transport==engine::TransportState::Ended;}),"playback reaches EOS without crash");
+ auto end=player.snapshot();
+ check(end.position>=1.96&&end.frames>0,"last source frame reaches presentation");
+ if(overload)check(end.previewSkipped>0,"overload actually used preview catch-up");
+ player.pause(true);player.seek(1.9);const auto request=player.snapshot().seekRequested;
+ check(until([&](const auto& s){return s.seekPresented==request&&s.position>=1.9;}),"paused tail seek presents requested frame");
+ player.pause(false);
+ check(until([](const auto& s){return s.transport==engine::TransportState::Ended;}),"resume after paused tail seek reaches EOS");
+ player.stop();check(until([&](const auto&){return player.idle();}),"playback worker closes");DestroyWindow(window);
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);
+}
+
+bool corruptLastVideoPacket(const std::filesystem::path& file){
+ const auto u8=file.u8string();const std::string name(u8.begin(),u8.end());AVFormatContext* input=nullptr;
+ if(avformat_open_input(&input,name.c_str(),nullptr,nullptr)<0)return false;
+ int64_t position=-1;int size=0;AVPacket* packet=av_packet_alloc();
+ if(avformat_find_stream_info(input,nullptr)>=0){
+ const int video=av_find_best_stream(input,AVMEDIA_TYPE_VIDEO,-1,-1,nullptr,0);
+ while(av_read_frame(input,packet)>=0){if(packet->stream_index==video){position=packet->pos;size=packet->size;}av_packet_unref(packet);}
+ }
+ av_packet_free(&packet);avformat_close_input(&input);
+ if(position<0||size<=0)return false;
+ std::fstream stream(file,std::ios::binary|std::ios::in|std::ios::out);stream.seekp(position);
+ const std::vector<char> zeros(size);stream.write(zeros.data(),size);return bool(stream);
+}
+
+void exportFaultTest(const std::wstring& path,const std::wstring& output,const std::wstring& mode){
+ std::atomic<bool> cancel=false;bool injected=false;std::wstring finalMessage;
+ engine::PlayerOptions options;options.nr=options.sr=options.fg=false;unsigned boundaries=0;
+ const bool ok=engine::exportVideo(path,output,options,false,cancel,[&](double progress,const std::wstring& message){
+ finalMessage=message;
+ if(progress==.999){
+ if(mode==L"export-corrupt-output"){injected=corruptLastVideoPacket(output+L".partial");check(injected,"damaged final encoded packet before integrity check");}
+ else if(mode==L"export-cancel-verify"){cancel=true;injected=true;}
+ }
+ },0,[&]{if(mode==L"export-abort-boundary"&&++boundaries>10){injected=true;return false;}return true;});
+ check(injected&&!ok,"injected failure/cancellation cannot report success");
+ check(!std::filesystem::exists(output)&&std::filesystem::exists(output+L".partial"),"failed output stays partial, never promoted");
+ check(finalMessage.find(L"完成")==std::wstring::npos,"completion message does not claim success");
+}
+
+void exportWorkerTest(const std::wstring& path,const std::wstring& output){
+ engine::ExportJobManager job;engine::PlayerOptions options;options.nr=options.sr=options.fg=false;
+ if(!job.start(path,output,options.snapshot(),false)){check(false,"export worker starts");return;}
+ engine::ExportJobSnapshot result;const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(30);
+ do{result=job.poll();if(!result.active())break;std::this_thread::sleep_for(std::chrono::milliseconds(10));}while(std::chrono::steady_clock::now()<deadline);
+ check(result.state==engine::ExportState::Failed,"independent worker reports source failure");
+ check(result.message.find(L"未生成输出文件")!=std::wstring::npos,"UI preserves preflight failure without claiming partial exists");
+ check(!std::filesystem::exists(output)&&!std::filesystem::exists(output+L".partial"),"preflight failure creates neither final nor partial");
+}
+}
+
+int wmain(int argc,wchar_t** argv){
+ if(argc==3&&std::wstring_view(argv[1])==L"--export-worker")return engine::runExportWorker(reinterpret_cast<HANDLE>(std::stoull(argv[2])));
+ if(argc<2)return 2;CoInitializeEx(nullptr,COINIT_MULTITHREADED);const std::wstring mode=argv[1];
+ if(mode==L"graph")graphTest();
+ else if(argc==4&&(mode==L"source-good"||mode==L"source-bad"))sourceTest(argv[2],unsigned(std::stoul(argv[3])),mode==L"source-bad");
+ else if(argc==3&&(mode==L"play-eof"||mode==L"play-overload-eof"))playbackTest(argv[2],mode==L"play-overload-eof");
+ else if(argc==4&&mode==L"export-worker-failure")exportWorkerTest(argv[2],argv[3]);
+ else if(argc==4&&mode.starts_with(L"export-"))exportFaultTest(argv[2],argv[3],mode);
+ else return 2;
+ CoUninitialize();return failures?1:0;
+}