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

fix: complete FRUC removal and bounded frame diagnostics

Veyra Goal Agent4e2bd73b46cf
diff --git a/README.md b/README.md
index cf9ae371..44423ddf 100644
--- a/README.md
+++ b/README.md
@@ -93,7 +93,7 @@ Video / image / capture card
- Depth is not a shipped default provider. Current motion guidance uses NVOF confidence handling where available.
- 3X and 4X frame generation are experimental. A selected multiplier does not guarantee that every source-frame pair produces a valid generated frame or that every configuration runs in real time.
- Actual scanout latency, long-term stability, capture audio behavior, and every GPU / driver combination require further real-device validation.
-- AMD FidelityFX supplies optical-flow estimation only. There is no AMD implementation of DLSS5/NR, DLSS SR, NVIDIA FRUC, DLSS frame generation, NVENC export, or an AMD AMF export backend. On a non-NVIDIA adapter, Veyra disables those NVIDIA paths; XeSS may still initialize when its runtime and device support it.
+- AMD FidelityFX supplies optical-flow estimation only. AMD NR development is on hold. NVIDIA NR, DLSS SR, DLSS frame generation and NVENC require compatible NVIDIA hardware; there is no AMD AMF export backend. XeSS may initialize on other adapters when its runtime and device support it.
- XeSS 2X diagnostics confirm SDK submissions only. They do not prove scanout frame rate, visual quality, or AMD-GPU compatibility.
- No NVIDIA runtime, SDK archive, headers, libraries, models, or samples are in this Git repository. The user-authorized Release Runtime Pack is a separate Release-only payload and remains experimental.
@@ -101,9 +101,9 @@ Video / image / capture card
当前修复以最新用户要求、`AGENTS.md`、对应 `docs` 修复方案和 `docs/WORKLOG.md` 为准。早期 `loop/` 状态、控制哈希与 Phase 队列已归档,不再作为开发前置门禁。Current work follows the latest task, `AGENTS.md`, its repair plan and `docs/WORKLOG.md`; the legacy Loop state and control-hash gates are historical only.
-当前修复进度:[后端、帧率、链路延迟与音画同步实施记录](docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md)。开发版已加入集中实时产出统计、XeSS切换修正及受控采集音频同步;FRUC 已从产品移除,AMD NR 本体和实体采集验收仍未完成。这里的开发改动尚未更新已发布的0.0.1用户包。
+当前修复进度:[FRUC移除与诊断收尾](docs/FRUC_REMOVAL_AND_DIAGNOSTICS_2026-09-11.md)。FRUC 已移除,旧预设迁移、真实产出统计、XeSS切换、受控音频同步和诊断收尾已有软件回归;AMD NR 暂时搁置,实体采集由用户验收。这里的开发改动尚未更新已发布的0.0.1用户包。
-Current development progress is recorded in the linked implementation log. Changes include completed-output telemetry, corrected XeSS switching, and controlled capture-audio synchronization. FRUC has been removed from the product; AMD NR integration and physical capture acceptance remain unfinished. These changes have not been published as an update to the 0.0.1 package.
+FRUC removal, legacy preset migration, completed-output telemetry, XeSS switching, controlled audio synchronization and diagnostic changes have software regression evidence in the linked report. AMD NR is on hold; physical capture acceptance belongs to user testing. These changes have not been published as an update to the 0.0.1 package.
| Path | Purpose |
| --- | --- |
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index 0eca8c5f..ed26abbf 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -425,7 +425,7 @@ CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
std::filesystem::create_directories(veyra::runtime::logsDirectory());wchar_t logOverride[32768]{};GetEnvironmentVariableW(L"VEYRA_LOG_FILE",logOverride,32768);veyra::Logger::instance().openFile(logOverride[0]?std::wstring(logOverride):(veyra::runtime::logsDirectory()/"veyra-app.log").wstring());
initialOptions=veyra::engine::PlayerOptions::from(veyra::ui::defaultSettings());
-int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-hover")smokeZoom=smokeHover=true;else if(arg==L"--smoke-protection")smokeProtection=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--fruc"){initialOptions.settings.frameGenerationBackend=veyra::engine::FrameGenerationBackend::Fruc;initialOptions.fg=true;}else if(arg==L"--video-sr"&&i+1<argc){initialOptions.settings.videoSrQuality=std::clamp(_wtoi(argv[++i]),1,4);initialOptions.sr=true;}else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);
+int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-hover")smokeZoom=smokeHover=true;else if(arg==L"--smoke-protection")smokeProtection=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--video-sr"&&i+1<argc){initialOptions.settings.videoSrQuality=std::clamp(_wtoi(argv[++i]),1,4);initialOptions.sr=true;}else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);
if(workerMapping){const int code=veyra::engine::runExportWorker(workerMapping);CoUninitialize();return code;}
if(smokeSeconds<=0&&exportOutput.empty()){uiPreferences=preferences.load();initialOptions=veyra::engine::PlayerOptions::from(preferences.startup(initialOptions.snapshot()));engine.setVolume(uiPreferences.volume,uiPreferences.muted);uiState.subtitles=uiPreferences.subtitles;subtitlePixels=uiPreferences.subtitleSize;}
engine.requestSettings(initialOptions.snapshot());
diff --git a/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md b/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md
index be3526e8..ec624870 100644
--- a/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md
+++ b/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md
@@ -1,5 +1,9 @@
# 继续修复实施记录
+## 2026-09-11 最新收尾状态(覆盖下方历史待办)
+
+用户决定暂缓AMD NR/性能继续优化/跨屏UI扩展/发布,实卡与音画同步由用户验收。本次已彻底移除FRUC、修正旧预设v4-v7迁移并写v8、修复打包脚本和过期测试,清掉运行目录旧FRUC组件;补齐reset原因及8192条有界事件轨迹,接入现有诊断预览。Release构建、77项合同、30组预设、28项实际RTX引擎回放、DLSS/XeSS正常与失败UI切换,以及23项delivery通过。完整文件/命令/失败/哈希见 [本次收尾记录](FRUC_REMOVAL_AND_DIAGNOSTICS_2026-09-11.md)。最新EXE SHA `E078E0B9348841E8A109E1160E704862F175B43F7C5E07C1ADB1D50F73432804`;未实卡、未发布。下一步为用户实测,不再沿下方历史“下一条AMD/重建计时”自动扩展。
+
状态:目标模式执行中。范围按 [继续修复方案](CONTINUATION_REPAIR_PLAN_2026-09-10.md),未完成全计划。起始代码 `be00e27`,保留上一轮方案文档改动。不启用旧Loop。
## 2026-09-11 续接实证:设置重置/重建生命周期计时
diff --git a/docs/CONTINUATION_REPAIR_PLAN_2026-09-10.md b/docs/CONTINUATION_REPAIR_PLAN_2026-09-10.md
index ab68ae27..73cd0944 100644
--- a/docs/CONTINUATION_REPAIR_PLAN_2026-09-10.md
+++ b/docs/CONTINUATION_REPAIR_PLAN_2026-09-10.md
@@ -1,5 +1,7 @@
# 后端切换、真实帧率、链路延迟与音画同步继续修复方案
+> 2026-09-11 最新用户收尾决定优先于本文旧范围:彻底移除FRUC;AMD NR搁置;性能/UI保持当前;实卡/音画同步由用户验收;发布暂缓。FRUC及计时诊断软件缺口已完成构建和回归,详见 [收尾实证](FRUC_REMOVAL_AND_DIAGNOSTICS_2026-09-11.md)。下方FRUC修复、AMD接入及旧下一步仅为历史计划,不是继续执行授权。
+
日期:2026-09-10。状态:方案已写入,待实施;本文不代表以下功能已经修复。代码基线:`be00e27`。
本轮对应用户提出的五项问题,并承接上一轮没有完成的 FRUC reset、GPU 调度和计时任务。当前执行入口为本文、最新用户指令和 [WORKLOG](WORKLOG.md)。旧 Loop、控制哈希和 Phase 排队不再生效;单次测试最多 300 秒,不是全部测试累计五分钟。
diff --git a/docs/FRUC_REMOVAL_AND_DIAGNOSTICS_2026-09-11.md b/docs/FRUC_REMOVAL_AND_DIAGNOSTICS_2026-09-11.md
new file mode 100644
index 00000000..a9c7bf17
--- /dev/null
+++ b/docs/FRUC_REMOVAL_AND_DIAGNOSTICS_2026-09-11.md
@@ -0,0 +1,71 @@
+# FRUC 移除与诊断收尾
+
+日期:2026-09-11。基线 `da5c1b4`。本次软件构建与相关回归通过;用户实卡验收未执行。
+
+## 本次范围
+
+按最新用户决定:收尾 FRUC 移除;已有帧率/计时保留,修复尚存的诊断缺口。性能优化暂缓,音画同步由用户实卡验收,UI/跨屏 DPI 保持现状,发布不急。AMD NR 暂时搁置,不是当前交付阻塞项,也不宣称已经实现。
+
+## FRUC 移除
+
+- 删除 `FrucBackend`、`FrucWorker`、IPC 协议、独立集成测试及旧 UI 测试脚本。此前提交已移除 CMake targets 和共享图执行分支,本次彻底删除残留源码与 `Fruc = Dlss` 别名、`--fruc` 参数。
+- 专业模式只提供 DLSS / XeSS,修正对应 UI 测试索引及 XeSS 初始化失败回退检查;保留 XeSS 预览 2X 边界。
+- 预设写入格式升到 v8:v4/v5 的旧 FRUC=1、v6/v7 的 FRUC=1 均迁移为 DLSS,原倍率保留;v6/v7 的 XeSS=2 迁移为新 XeSS=1。v8 的 2 是非法值,不会再写含糊的 v7。无效配置继续拒绝并保护原文件。
+- 修正 `package-portable.ps1` 的末尾逗号语法错误;应用 allowlist 不含 FRUC worker,runtime allowlist 不含 NvOFFRUC/CUDA11。未制作新包或修改已发布资产。
+- 删除本机开发运行目录的 `NvOFFRUC.dll`、`cudart64_110.dll` 和构建目录的两个旧 FRUC EXE。仅清理这四个明确路径;本地 SDK 原件、历史日志和旧发布资产保留。
+- 修正上一轮删分支后 `resolveGeneration` 日志仍引用未定义 `disabled` 的编译错误;保留 DLSS disable readback 原有语义。
+
+旧软件不理解 v8 预设;本次不提供把新预设直接交回旧版本使用的保证。历史 FRUC 文档保留为当时证据,不是当前功能清单。
+
+## 诊断修复
+
+此前普通 reset 原因最终默认成 SceneCut,设置切换一律记 Resize。现在明确保留 Seek / PauseResume / Settings,来源 Drop 与 PTS discontinuity 分开;共享图返回实际检测的 PTS 跳变、切镜或 cadence break。没有原因时保留 None,不编造切镜。
+
+新增 `diagnostics/ResetCause.h` 和 `FrameTrace.h`,接入 `EngineController` 与现有 Logger 诊断预览:
+
+- 固定 8192 条事件环、覆盖计数、按记录顺序导出;独立于64条去重错误记录。
+- 保存会话、revision、epoch、source、batch、fence、PTS、主机单调时间,记录 Submitted / Ready / Present / Gpu / Reset / Cancelled。
+- Submitted 的耗时是图 CPU 提交,Ready 是观察到 fence 完成,Gpu 是真实 GPU timestamp 样本,Present 是提交返回,均不等于屏幕扫描。
+- Reset 的 detail 对应 `ResetReason`,count 对应 `ResetOutcome`,总耗时为现有生命周期 CPU 观测;原因9=Settings、10=PtsDiscontinuity、11=CadenceBreak,原枚举编号保留。
+- 每秒只写轨迹容量/覆盖汇总;热路径记录不格式化、不写磁盘、不增加 GPU 像素回读。诊断预览读取固定上限快照后再格式化,格式化期间不占轨迹锁。
+- 实卡、物理 device lost 和屏幕扫描仍未测。轨迹是近期窗口,不是无限历史,不承诺崩溃后恢复尚未导出的内存事件。
+
+没有修改画质参数、SR -> NR -> FG 顺序、源帧淘汰策略或导出完整性检查。
+
+## 实际验证
+
+以下命令从项目根目录执行,日志位于 gitignored 目录。每个测试进程少于300秒;GPU测试串行。
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root "C:\Users\123\Desktop\Veyra DLSS Video Player" -Preset x64-release
+./scripts/acceptance/scheduler-short-test.ps1 -Name fruc-final-contract -Exe out/build/x64-release/veyra_repair_contract_tests.exe
+./scripts/acceptance/scheduler-short-test.ps1 -Name fruc-final-presets -Exe out/build/x64-release/veyra_repair_preset_tests.exe -TestArgs logs/continuation-repair-20260910/fruc-final-presets.v8
+./scripts/acceptance/scheduler-short-test.ps1 -Name fruc-final-live -Exe out/build/x64-release/veyra_live_presentation_tests.exe -TestArgs @('loop/local/fixed_clips/test_av_1080p.mp4','logs/continuation-repair-20260910/fruc-final-live')
+python scripts/acceptance/ui-fg-backends.py
+python scripts/acceptance/ui-fg-backends.py --reject-xess
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root "C:\Users\123\Desktop\Veyra DLSS Video Player"
+```
+
+使用旧目录中的固定测试视频不代表启用旧 Loop。
+
+| 项目 | 实际结果 / 证据 |
+| --- | --- |
+| Release 构建 | exit0;`logs/continuation-repair-20260910/fruc-trace-build-final.log` |
+| 合同 | 77项PASS,0.073秒;`logs/scheduler-repair-20260910/fruc-final-contract.result.json` |
+| 预设 | 原有roundtrip及30组v4-v8后端/倍率迁移PASS,0.177秒;`fruc-final-presets.result.json` |
+| 实际引擎回放 | 28项PASS,4.792秒;NR+DLSS2X/4X、设置、暂停恢复、诊断导出;`fruc-final-live.result.json` |
+| 后端UI切换 | XeSS -> DLSS -> off PASS;`logs/continuation-repair-20260910/ui-fg-1789091809460815600/result.json` |
+| UI故障回退 | XeSS拒绝后保留DLSS,再关闭PASS;`ui-fg-1789091833910763700/result.json` |
+| delivery | 23项PASS,42.852秒;`logs/delivery/ef265e2874624e6aa6e80f7a8c34f8d8/result.json` |
+| 脚本/残留 | PowerShell Parser解析打包脚本PASS;运行代码/构建/测试仅保留预设迁移注释中的FRUC;`git diff --check`通过 |
+
+真实 RTX 日志 `logs/continuation-repair-20260910/fruc-final-live/engine.log`:Feature18 Create `result=0x1 handle=non-null seh=0`;DLSSG Create / Evaluate `result=0x1 seh=0`。暂停恢复生命周期 reason=7/outcome=1;设置重建 reason=9。实际诊断导出465条事件、overwritten=0,见同目录 `diagnostics.txt`。delivery实际覆盖NR/NVOF、原生4K正确性、文件/图片、NVENC H.264/HEVC及取消,不是性能或实体采集验收。
+
+最终应用 SHA256:`E078E0B9348841E8A109E1160E704862F175B43F7C5E07C1ADB1D50F73432804`。
+本机 NR DLL SHA256仍为 `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`,Authenticode Valid;无SDK/runtime/模型进入Git。
+
+失败留档:第一轮新增轨迹编译因 `runSessionId` 声明顺序失败(`fruc-trace-build.log`),调整声明顺序后完整构建通过;一次由 Windows PowerShell `-File` 传数组导致测试参数绑定失败,尚未启动测试程序,改在当前PowerShell直接调用脚本后通过。前置纯FRUC构建与预设检查另存 `fruc-removal-build.log`、`fruc-removal-presets-first.result.json`,不替代最终证据。
+
+## 下一步
+
+本次授权软件收尾完成,等待用户用本机 `Veyra.cmd` 启动新EXE实测。原生4K高成本组合性能、真实采集音画同步、物理音频设备拔插、真实跨屏DPI和AMD NR不宣称通过;按用户决定不继续扩展、打包或发布。仅建立本地源码存档。
diff --git a/docs/HANDOFF_2026-09-10.md b/docs/HANDOFF_2026-09-10.md
index ed84182c..95f34c76 100644
--- a/docs/HANDOFF_2026-09-10.md
+++ b/docs/HANDOFF_2026-09-10.md
@@ -1,5 +1,9 @@
# 当前交接:后端切换、真实产出与音画同步
+## 最新用户决定与已完成收尾
+
+2026-09-11:当前授权的软件收尾完成,等待用户验收。FRUC完整移除,预设格式v8兼容旧DLSS/XeSS并将旧FRUC迁移至DLSS;打包清单、测试及运行目录残留已清理。reset原因误分类与有界诊断轨迹缺口已修复。构建/合同77/迁移30/真实引擎28/UI正常与失败/联合delivery23通过,证据见 [FRUC与诊断收尾](FRUC_REMOVAL_AND_DIAGNOSTICS_2026-09-11.md)。AMD NR搁置,性能与UI先保持现状,实卡及音画同步由用户验收,发布暂缓。以下所有“下一条任务”均是历史快照,不能据此恢复扩展或宣称实卡通过。
+
## 2026-09-11 最新进度
已加入设置事务及普通 open/history boundary 的 reset/rebuild 生命周期证据:session/revision/epoch/source identity、重建标记、drain/destroy/create/warmup/first GPU-ready 五段边界计时,以及 Completed/RolledBack/Cancelled/Failed 结果;reset counters 改为累计。旧完成事件不能结束新事务,暂停缓存预览、失败回滚、source-gap EOF 尾批都有实际回归。构建 `reset-lifecycle-build-final.log` exit0,设置/回滚32项及 source-gap 62.6秒最终通过。下一条任务是把 capture drop/seek/scene-cut/device-lost 的原因与有界逐帧轨迹进一步结构化,随后再审计 AMD provider 等未完成项。未实卡、未做AMD实机、未发布。
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index a3f06604..a2c46a57 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -77,4 +77,4 @@ PS5固定30fps、采集卡只能60fps:设备保持60fps,进入专业模式
## 2026-09-09 当前交接
-最新交接见 [HANDOFF_2026-09-10.md](HANDOFF_2026-09-10.md)。RTX Video SR已接入共享管线;专业模式补帧页可切换DLSS或XeSS。FRUC 已从产品移除。播放器时间戳支持到1000fps,实际吞吐取决于尺寸/处理链/硬件;已测256×144无增强约999fps,不是4K千帧保证。NR表盘只表示NR阶段GPU耗时,不是采集到屏幕总延迟;当前已按设置revision隔离统计。USB3Video实卡曾测1080p60与4K18;设备未公开1440p格式,不人为伪造模式。
+最新交接见 [HANDOFF_2026-09-10.md](HANDOFF_2026-09-10.md)。RTX Video SR已接入共享管线;专业模式补帧页可切换DLSS或XeSS。FRUC 已从产品移除,旧FRUC预设迁移为DLSS并保留倍率,旧XeSS预设仍是XeSS;新保存的v8预设不供旧版本读取。播放器时间戳支持到1000fps,实际吞吐取决于尺寸/处理链/硬件;已测256×144无增强约999fps,不是4K千帧保证。实时状态区显示真实产出与各链路计时,软件首尾延迟不等于HDMI到屏幕发光时间。诊断预览包含近期有界事件轨迹。USB3Video实卡曾测1080p60与4K18;设备未公开1440p格式,不人为伪造模式。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index b45e7500..92626f4c 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,23 @@
# 2026-09-11 继续修复目标模式执行中
+## 最新交付:FRUC 与诊断收尾完成,等待用户验收
+
+按最新用户六项决定收尾:彻底删除FRUC后端/worker/协议/命令行及旧测试,v8预设显式迁移v4-v7的FRUC和XeSS,打包脚本修复,旧运行DLL/EXE四文件清理。修正之前把暂停恢复/PTS跳变/设置记成切镜或Resize的诊断错误;新增固定8192事件轨迹及覆盖统计,接入现有脱敏诊断预览,不逐帧写磁盘,不改画质/调度和导出检查。
+
+完整命令、修改范围、失败及哈希见 [本次收尾记录](FRUC_REMOVAL_AND_DIAGNOSTICS_2026-09-11.md)。`scripts/build.ps1`最终exit0;合同77项、预设30组、实际RTX引擎28项、DLSS/XeSS UI正常和拒绝回退均通过;delivery `ef265e2874624e6aa6e80f7a8c34f8d8` 23项42.852秒PASS。真实Feature18/DLSSG Create/Evaluate `0x1`/SEH0;应用SHA `E078E0B9348841E8A109E1160E704862F175B43F7C5E07C1ADB1D50F73432804`。初次轨迹编译声明顺序错误与一次脚本数组传参失败保留,修正后最终回归通过。下方da5c1b4缺陷清单已由本次修复覆盖。
+
+AMD NR搁置,性能/UI不继续扩展;实卡、真实设备音画同步/拔插和跨屏DPI未由Agent验收;不打包/push/发布。下一步是用户启动 `Veyra.cmd` 实测,不因旧待办继续扩大任务。
+
+## 2026-09-11 用户搁置 AMD NR / 当前未完成核对
+
+用户最新决定:AMD NR 路线暂时搁置,停止本轮上游调查,不作为当前修复完成门槛。没有实现 AMD NR,不将已有 AMD 光流写成 NR。下方历史的“下一条 AMD provider”不再适用。
+
+当前源码 HEAD `da5c1b4`。FRUC 移除仅有部分代码及文档提交,不能称完整交付:`FrameGenerationBackend` 仍保留 `Fruc = Dlss` 别名与 `--fruc` 路径;UI 回归仍按 FRUC/XeSS/DLSS 三项索引;PresetStore 只迁移 v4/v5,旧 v6/v7 的 FRUC=1 会误解释为 XeSS(倍率过高则拒绝),旧 XeSS=2 被新枚举验证拒绝。schema 仍写 v7,需修正持久化兼容合同。打包脚本第26行删除 FRUC 后留下末尾逗号,PowerShell Parser 实测 `Missing expression after ','`。最新提交尚未完整构建/回归;前序 EXE 与 delivery 通过不能覆盖该提交。项目已有 `scripts/build.ps1` 负责定位 VS/CMake,前序终端 PATH 找不到 cmake 不构成工具链不可用的证明。
+
+剩余当前工作:先完整收尾 FRUC 移除及旧预设迁移,更新关联测试并构建/针对性回归/必要 delivery;随后补齐 reset 原因结构化及有界逐帧性能轨迹。单GPU所有者、实际完成帧率/阶段计时、设置生命周期、文件音频恢复和可控淡出已有前序软件证据,但未证明原生4K NR+SR+高倍率FG的性能问题全部解决或达到对照软件水平。真实采集卡的组合吞吐/节奏/A-V、物理音频设备拔插、真实150%/200%系统跨屏DPI尚待验收。默认音频设备改变而旧端点仍有效时尚不主动迁移。发布包仍未更新,文档历史快照须由当前状态覆盖。
+
+本轮实际只读检查:`git status --short`(开始干净)、`git log -6 --oneline`、读取当前方案/交接/实施记录、检查预设与后端代码、PowerShell Parser 解析打包脚本(上述失败)。未构建,未执行新的 RTX Create/Evaluate、AMD 或实卡测试,未 push/打包/发布。下一条唯一任务:FRUC 移除的兼容性、测试与构建收尾。
+
最新 reset/rebuild 计时:`FrameFlowMetrics` 增加带 session/revision/epoch/source identity 的设置生命周期记录,区分轻量重置与资源重建,并记录 drain/destroy/create/warmup/first GPU-ready 五段 CPU 观测、完成/回滚/取消/失败结果。真实设置事务、暂停缓存预览、注入失败回滚、停止中取消均已通过 `continuation-reset-final-rollback`(约8.8秒,32项,合成文件回放)。完整 release 构建 `reset-lifecycle-build-final.log` exit0。未执行实体采集卡、真实系统跨DPI或AMD provider;目标仍active。
普通 open/history boundary 随后接入同一记录,reset counters 改为累计;source-gap/EOF 最终 `continuation-reset-cause-live-final` 62.6秒通过(3600 real frames ready/presented,0 cancelled)。早期20/30秒窗口失败原因是素材在本机需要约一分钟读完,失败日志保留,测试上限调整为90秒(单次 watchdog仍290秒)。
diff --git a/include/veyra/Log.h b/include/veyra/Log.h
index 3622f5e7..a0134c01 100644
--- a/include/veyra/Log.h
+++ b/include/veyra/Log.h
@@ -5,6 +5,7 @@
#include <mutex>
#include <string>
#include "veyra/diagnostics/DiagnosticEvent.h"
+#include "veyra/diagnostics/FrameTrace.h"
namespace veyra {
@@ -42,9 +43,13 @@ public:
std::string diagnosticReport();
std::string latestProblem();
static void diagnosticContext(diagnostics::DiagnosticEvent);
+ void recordFrame(diagnostics::FrameTraceEvent event);
+ std::pair<size_t,uint64_t> frameTraceSize();
private:
std::mutex mutex_;
+ std::mutex traceMutex_;
+ diagnostics::FrameTrace frameTrace_;
std::FILE* file_ = nullptr;
bool consoleEnabled_ = true;
uint64_t lastFileFlushTick_=0;
diff --git a/include/veyra/diagnostics/FrameTrace.h b/include/veyra/diagnostics/FrameTrace.h
new file mode 100644
index 00000000..b4c9b7f7
--- /dev/null
+++ b/include/veyra/diagnostics/FrameTrace.h
@@ -0,0 +1,52 @@
+#pragma once
+#include "veyra/pipeline/FrameBatch.h"
+#include <algorithm>
+#include <array>
+#include <vector>
+
+namespace veyra::diagnostics {
+enum class TraceKind { Submitted, Ready, Present, Gpu, Reset, Cancelled };
+inline const char* traceKindName(TraceKind kind) {
+ switch(kind){
+ case TraceKind::Submitted:return "Submitted";
+ case TraceKind::Ready:return "Ready";
+ case TraceKind::Present:return "Present";
+ case TraceKind::Gpu:return "Gpu";
+ case TraceKind::Reset:return "Reset";
+ case TraceKind::Cancelled:return "Cancelled";
+ }
+ return "Unknown";
+}
+struct FrameTraceEvent {
+ int64_t host100ns=0;
+ uint64_t session=0;
+ pipeline::FrameIdentity identity;
+ uint64_t batch=0,fence=0;
+ int64_t pts100ns=0;
+ TraceKind kind=TraceKind::Submitted;
+ uint32_t detail=0,count=0;
+ double milliseconds=0;
+};
+// Owned by the logger, independent of the deduplicated error history. No
+// allocation, formatting or disk I/O occurs when an event is recorded.
+class FrameTrace {
+public:
+ static constexpr size_t capacity=8192;
+ void add(FrameTraceEvent event){
+ if(size_==capacity)++overwritten_;
+ events_[next_]=event;next_=(next_+1)%capacity;size_=std::min(size_+1,capacity);
+ }
+ size_t size()const{return size_;}
+ uint64_t overwritten()const{return overwritten_;}
+ std::vector<FrameTraceEvent> snapshot()const{
+ std::vector<FrameTraceEvent> result;result.reserve(size_);
+ const auto first=(next_+capacity-size_)%capacity;
+ for(size_t i=0;i<size_;++i)result.push_back(events_[(first+i)%capacity]);
+ return result;
+ }
+private:
+ std::array<FrameTraceEvent,capacity> events_{};
+ size_t next_=0,size_=0;
+ uint64_t overwritten_=0;
+};
+}
diff --git a/include/veyra/diagnostics/ResetCause.h b/include/veyra/diagnostics/ResetCause.h
new file mode 100644
index 00000000..50c3b16a
--- /dev/null
+++ b/include/veyra/diagnostics/ResetCause.h
@@ -0,0 +1,19 @@
+#pragma once
+#include "veyra/pipeline/FramePacket.h"
+#include "veyra/pipeline/ResetCoordinator.h"
+#include <utility>
+
+namespace veyra::diagnostics {
+inline pipeline::ResetReason resetCause(pipeline::FrameFlags flags,
+ pipeline::ResetReason requested, pipeline::ResetReason detected) {
+ using namespace pipeline;
+ if(hasFrameFlag(flags,FrameFlagBits::DeviceLost))return ResetReason::DeviceLost;
+ if(requested!=ResetReason::None)return requested;
+ for(auto [flag,reason]:{std::pair{FrameFlagBits::Open,ResetReason::Open},
+ {FrameFlagBits::Seek,ResetReason::Seek},{FrameFlagBits::Drop,ResetReason::FrameDrop},
+ {FrameFlagBits::Resize,ResetReason::Resize},{FrameFlagBits::PauseResume,ResetReason::PauseResume},
+ {FrameFlagBits::Discontinuity,ResetReason::PtsDiscontinuity},{FrameFlagBits::Cut,ResetReason::SceneCut}})
+ if(hasFrameFlag(flags,flag))return reason;
+ return detected;
+}
+}
diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.h
index cf109a97..215fedfe 100644
--- a/include/veyra/engine/EnhancementSettings.h
+++ b/include/veyra/engine/EnhancementSettings.h
@@ -6,7 +6,7 @@
#include <string_view>
#include "veyra/pipeline/ResolutionPlan.h"
namespace veyra::engine {
-enum class FrameGenerationBackend { Dlss, XeSS, Fruc = Dlss };
+enum class FrameGenerationBackend { Dlss, XeSS };
enum class FlowQuality { Performance, Balanced, Quality };
enum class OpticalFlowBackend { Nvidia, AmdFidelityFx };
enum class ContentRate { Transport, Auto, Fps30, Fps50, Fps60, Capture60To30 };
diff --git a/include/veyra/ngx/FrucBackend.h b/include/veyra/ngx/FrucBackend.h
deleted file mode 100644
index bf9ec0da..00000000
--- a/include/veyra/ngx/FrucBackend.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#pragma once
-#include <d3d12.h>
-#include <memory>
-#include <array>
-namespace veyra::gfx {class D3D12DeviceContext;}
-namespace veyra::ngx {
-// Independent adapter to locally installed NvOFFRUC, with GPU-only shared RGBA8
-// surfaces. Each fractional timestamp has its own temporal FRUC instance.
-class FrucBackend {
-public:
- FrucBackend();~FrucBackend();
- bool initialize(gfx::D3D12DeviceContext&,unsigned width,unsigned height,unsigned multiplier);
- bool reset(); // caller drains graph consumers before resetting history
- void recordInput(ID3D12GraphicsCommandList*,ID3D12Resource*,unsigned parity);
- bool execute(unsigned parity,double previousMs,double currentMs,std::array<bool,3>& repeated);
- void recordOutput(ID3D12GraphicsCommandList*,ID3D12Resource*,unsigned subframe);
-private:
- struct Impl;std::unique_ptr<Impl> p_;
-};
-}
diff --git a/include/veyra/ngx/FrucWorkerProtocol.h b/include/veyra/ngx/FrucWorkerProtocol.h
deleted file mode 100644
index 65560d7e..00000000
--- a/include/veyra/ngx/FrucWorkerProtocol.h
+++ /dev/null
@@ -1,16 +0,0 @@
-#pragma once
-#include <windows.h>
-#include <cstdint>
-namespace veyra::ngx {
-// Control messages only; pixel buffers and completion dependencies stay on GPU.
-struct FrucWorkerMessage {
- uint32_t version=1,width=0,height=0,multiplier=2;
- LUID adapter{};
- uint64_t textures[5]{},fence=0,request=0,response=0;
- uint64_t inputFence=0,outputFence=0;
- double previousMs=0,currentMs=0;
- uint32_t parity=0,command=0,result=1,seh=0;
- bool repeated[3]{};
- wchar_t logPath[1024]{};
-};
-}
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index b2ec1b62..0aa4f1a4 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -15,6 +15,7 @@
// and NGX/NVOF objects are created BEFORE any descriptor view; the FG
// warm-up evaluate runs before views exist; static views are created last.
#include <cstdint>
+#include "veyra/pipeline/ResetCoordinator.h"
#include <functional>
#include <memory>
#include <string>
@@ -110,6 +111,7 @@ public:
FrameBatch batch;
uint32_t fgCandidates=0,fgEvaluated=0,fgSkippedBeforeEval=0;
bool historyReset=false,fgRecovery=false;
+ ResetReason detectedReset=ResetReason::None;
bool contentDuplicate=false;int measuredContentRate=0;
double ptsMs = 0.0;
uint32_t videoSlot = 0; // videoFrame[videoSlot] holds this real frame
diff --git a/include/veyra/pipeline/ResetCoordinator.h b/include/veyra/pipeline/ResetCoordinator.h
index 0f5fa24b..ffb69ebc 100644
--- a/include/veyra/pipeline/ResetCoordinator.h
+++ b/include/veyra/pipeline/ResetCoordinator.h
@@ -19,6 +19,9 @@ enum class ResetReason : uint8_t {
SourceSwitch,
PauseResume,
DeviceLost,
+ Settings,
+ PtsDiscontinuity,
+ CadenceBreak,
_Count
};
@@ -32,6 +35,9 @@ inline const char* resetReasonName(ResetReason r) {
case ResetReason::SourceSwitch: return "SourceSwitch";
case ResetReason::PauseResume: return "PauseResume";
case ResetReason::DeviceLost: return "DeviceLost";
+ case ResetReason::Settings: return "Settings";
+ case ResetReason::PtsDiscontinuity: return "PtsDiscontinuity";
+ case ResetReason::CadenceBreak: return "CadenceBreak";
default: return "None";
}
}
diff --git a/scripts/acceptance/scheduler-short-test.ps1 b/scripts/acceptance/scheduler-short-test.ps1
index 01ed9a77..9d23b15f 100644
--- a/scripts/acceptance/scheduler-short-test.ps1
+++ b/scripts/acceptance/scheduler-short-test.ps1
@@ -19,9 +19,7 @@ try {
$handle=$process.Handle
if(-not $process.WaitForExit(290000)){Stop-Process -Id $process.Id -Force;throw "$Name exceeded 290 seconds"}
$inputs=@($TestArgs|Where-Object {$_ -match '\.(mp4|nv12)$' -and (Test-Path -LiteralPath $_ -PathType Leaf)}|ForEach-Object {@{path=$_;sha256=(Get-FileHash -LiteralPath $_ -Algorithm SHA256).Hash}})
-$worker=Join-Path (Split-Path $start.FilePath) 'veyra_fruc_worker.exe'
-$workerHash=if(Test-Path -LiteralPath $worker -PathType Leaf){(Get-FileHash -LiteralPath $worker -Algorithm SHA256).Hash}else{$null}
-$result=[ordered]@{test=$Name;exitCode=$process.ExitCode;seconds=$watch.Elapsed.TotalSeconds;exeHash=(Get-FileHash $Exe -Algorithm SHA256).Hash;workerHash=$workerHash;args=$TestArgs;inputs=$inputs}
+$result=[ordered]@{test=$Name;exitCode=$process.ExitCode;seconds=$watch.Elapsed.TotalSeconds;exeHash=(Get-FileHash $Exe -Algorithm SHA256).Hash;args=$TestArgs;inputs=$inputs}
$result|ConvertTo-Json|Set-Content "$dir/$Name.result.json"
Get-Content "$dir/$Name.stdout.log" -Tail 28
Write-Output ($result|ConvertTo-Json -Compress)
diff --git a/scripts/acceptance/ui-fg-backends.py b/scripts/acceptance/ui-fg-backends.py
index fc2941f3..340133db 100644
--- a/scripts/acceptance/ui-fg-backends.py
+++ b/scripts/acceptance/ui-fg-backends.py
@@ -130,7 +130,7 @@ with (out / 'stdout.log').open('w') as stdout, (out / 'stderr.log').open('w') as
multiplier = u.GetDlgItem(body, 202)
revision_label = u.GetDlgItem(panel, 400)
assert backend and title and multiplier, 'missing FG controls'
- assert send(backend, 0x146) == 3, 'FG selector must expose all three backends'
+ assert send(backend, 0x146) == 2, 'FG selector must expose DLSS and XeSS only'
for width, height in [(1280, 900), (1040, 540), (1040, 800)]:
u.SetWindowPos(main, None, 30, 30, width, height, 0x14)
time.sleep(.2)
@@ -159,17 +159,18 @@ with (out / 'stdout.log').open('w') as stdout, (out / 'stderr.log').open('w') as
wait_for(lambda: not windows(process.pid, 'VeyraGlassSelector'))
assert send(control, 0x147) == index, 'popup did not commit choice'
- for index, name in [(1, 'FRUC'), (2, 'XeSS'), (0, 'DLSS')]:
+ def applied():
+ current = text(revision_label)
+ values = re.findall(r'\d+', current.splitlines()[0])
+ return current != previous and len(values) >= 2 and values[0] == values[1]
+
+ for index, name in ([(1, 'XeSS')] if reject_xess else [(1, 'XeSS'), (0, 'DLSS')]):
previous = text(revision_label)
choose(backend, index)
if reject_xess and name == 'XeSS':
- wait_for(lambda: send(backend, 0x147) == 1 and 'XeSS' in text(u.GetDlgItem(panel, 401)), 18)
- result['switches'].append('XeSS rejected, FRUC retained')
+ wait_for(lambda: send(backend, 0x147) == 0 and 'XeSS' in text(u.GetDlgItem(panel, 401)), 18)
+ result['switches'].append('XeSS rejected, DLSS retained')
continue
- def applied():
- current = text(revision_label)
- values = re.findall(r'\d+', current.splitlines()[0])
- return current != previous and len(values) >= 2 and values[0] == values[1]
wait_for(applied, 18)
result['switches'].append(name)
assert send(multiplier, 0x146) == (2 if name == 'XeSS' else 4), 'incorrect multiplier choices'
@@ -201,7 +202,7 @@ with (out / 'stdout.log').open('w') as stdout, (out / 'stderr.log').open('w') as
result['exit'] = process.returncode
result['appliedBackends'] = re.findall(r'Applied revision=\d+.*?fgBackend=(\w+)', log())
if result.get('passed'):
- expected = ['FRUC', 'DLSS'] if reject_xess else ['FRUC', 'XeSS', 'DLSS']
+ expected = ['DLSS'] if reject_xess else ['XeSS', 'DLSS']
result['passed'] = all(name in result['appliedBackends'] for name in expected)
if reject_xess:
result['passed'] = result['passed'] and 'XeSS' not in result['appliedBackends']
diff --git a/scripts/acceptance/ui-fruc-switch.py b/scripts/acceptance/ui-fruc-switch.py
deleted file mode 100644
index 33c56d6f..00000000
--- a/scripts/acceptance/ui-fruc-switch.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# Regression: live per-field settings, wheel safety, discrete buttons, reset. Own app; 30-second app deadline.
-import ctypes as c,ctypes.wintypes as w,subprocess,os,time,pathlib,json,uuid
-r=pathlib.Path.cwd();u=c.WinDLL('user32');u.GetWindowThreadProcessId.argtypes=[w.HWND,c.POINTER(w.DWORD)];u.GetDlgCtrlID.argtypes=[w.HWND];u.GetParent.argtypes=[w.HWND];u.GetParent.restype=w.HWND
-u.SendMessageTimeoutW.argtypes=[w.HWND,w.UINT,w.WPARAM,w.LPARAM,w.UINT,w.UINT,c.POINTER(c.c_size_t)];u.SendMessageTimeoutW.restype=w.LPARAM
-cb=c.WINFUNCTYPE(w.BOOL,w.HWND,w.LPARAM);u.EnumWindows.argtypes=[cb,w.LPARAM];u.EnumChildWindows.argtypes=[w.HWND,cb,w.LPARAM]
-def send(h,m,a=0,b=0):
- result=c.c_size_t();assert u.SendMessageTimeoutW(h,m,a,b,2,1500,c.byref(result));return result.value
-log=r/('logs/fruc-switch-'+uuid.uuid4().hex+'.log');env=os.environ.copy();env['PATH']=r'C:\veyra-deps\installed\x64-windows\bin;'+env['PATH'];env['VEYRA_LOG_FILE']=str(log)
-p=subprocess.Popen([str(r/'out/build/x64-release/veyra.exe'),'--smoke-seconds','24','--no-nr','--no-sr','--fruc','--fg-multiplier','2',str(r/'logs/video-sdk-trial-20260909/known-pan15.mp4')],env=env)
-try:
- start=time.monotonic();time.sleep(3);controls={}
- @cb
- def child(h,l):
- ident=u.GetDlgCtrlID(h)
- if ident in [202,208,211]:controls[ident]=h
- return True
- @cb
- def top(h,l):
- pid=w.DWORD();u.GetWindowThreadProcessId(h,c.byref(pid))
- if pid.value==p.pid:u.EnumChildWindows(h,child,0)
- return True
- u.EnumWindows(top,0);assert len(controls)==3,controls
- def select(ident,index):
- h=controls[ident];send(h,0x14e,index);send(u.GetParent(h),0x111,ident|(1<<16),h)
- def click(ident):
- h=controls[ident];send(u.GetParent(h),0x111,ident,h)
- def textOf(ident):
- buf=c.create_unicode_buffer(100);send(controls[ident],13,100,c.addressof(buf));return buf.value
- def change(ident,index,token):
- old=log.read_text(encoding='utf-8',errors='replace').count(token)
- select(ident,index);deadline=time.monotonic()+6
- while time.monotonic()<deadline:
- data=log.read_text(encoding='utf-8',errors='replace')
- if data.count(token)>old:return
- assert p.poll() is None,'app exited early'
- time.sleep(.05)
- raise AssertionError('not applied: '+token)
- change(202,2,'backend=FRUC multiplier=3')
- change(202,3,'backend=FRUC multiplier=4')
- change(208,0,'backend=DLSS multiplier=4')
- change(208,1,'backend=FRUC multiplier=4')
- change(202,0,'backend=FRUC multiplier=1')
- change(202,1,'backend=FRUC multiplier=2')
- click(211)
- code=p.wait(timeout=max(1,35-(time.monotonic()-start)));data=log.read_text()
- ok=code==0 and 'failed=false' in data and 'backend=DLSS multiplier=1' in data
- print(json.dumps({'exit':code,'switch_2_3_4_dlss_fruc_off_on_reset':ok,'log':str(log)}));assert ok
-
-finally:
- if p.poll() is None:p.kill();p.wait()
diff --git a/scripts/acceptance/ui-layout-dpi.py b/scripts/acceptance/ui-layout-dpi.py
index a8cb4425..d1516e03 100644
--- a/scripts/acceptance/ui-layout-dpi.py
+++ b/scripts/acceptance/ui-layout-dpi.py
@@ -182,7 +182,7 @@ with (out / 'stdout.log').open('w') as stdout, (out / 'stderr.log').open('w') as
u.PostMessageW(backend, 0x201, 1, 10|(10<<16))
popup = wait_for(lambda: windows('VeyraGlassSelector'))[0]
listing = u.GetDlgItem(popup, 1)
- assert send(listing, 0x18B) == 3
+ assert send(listing, 0x18B) == 2
assert font_height(listing) == int(13*scale+.5), 'popup font has different scale'
time.sleep(.15)
ImageGrab.grab(window=popup).save(out / f'{dpi}-selector.png')
diff --git a/scripts/package-portable.ps1 b/scripts/package-portable.ps1
index 48f86fcb..d125e10d 100644
--- a/scripts/package-portable.ps1
+++ b/scripts/package-portable.ps1
@@ -23,7 +23,7 @@ $runtimeFiles = @(
@{ Name = 'nvngx_dlss.dll'; Source = (Join-Path $resolvedRoot 'runtime_local/nvidia/nvngx_dlss.dll'); Sha256 = 'BE6E434A94CA32499515EB62CA0E6C274526055D568D0426E4C652DCDFB6EE6E'; Classification = 'official-sdk-runtime'; Experimental = $false },
@{ Name = 'nvngx_dlssg.dll'; Source = (Join-Path $resolvedRoot 'runtime_local/nvidia/nvngx_dlssg.dll'); Sha256 = '135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F'; Classification = 'community-experimental-runtime'; Experimental = $true },
@{ Name = 'nvngx_dlssnr.dll'; Source = (Join-Path $resolvedRoot 'runtime_local/nvidia/nvngx_dlssnr.dll'); Sha256 = 'E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E'; Classification = 'community-experimental-runtime'; Experimental = $true },
- @{ Name = 'nvngx_vsr.dll'; Source = (Join-Path $resolvedRoot 'runtime_local/nvidia/nvngx_vsr.dll'); Sha256 = 'C3D88EEA5FF7A548EDEFA66414CF6E77464D0947277C904F324DD23ABF58A1ED'; Classification = 'official-rtx-video-sdk-runtime'; Experimental = $false },
+ @{ Name = 'nvngx_vsr.dll'; Source = (Join-Path $resolvedRoot 'runtime_local/nvidia/nvngx_vsr.dll'); Sha256 = 'C3D88EEA5FF7A548EDEFA66414CF6E77464D0947277C904F324DD23ABF58A1ED'; Classification = 'official-rtx-video-sdk-runtime'; Experimental = $false }
)
foreach ($item in $runtimeFiles) {
if (-not (Test-Path -LiteralPath $item.Source)) { throw "Missing approved runtime: $($item.Name)" }
diff --git a/src/base/Log.cpp b/src/base/Log.cpp
index cd5f824a..0a28edfc 100644
--- a/src/base/Log.cpp
+++ b/src/base/Log.cpp
@@ -156,12 +156,25 @@ bool verboseFrameLogs()
void Logger::diagnosticContext(diagnostics::DiagnosticEvent event){threadDiagnosticContext=std::move(event);}
std::string Logger::latestProblem(){std::lock_guard lock(mutex_);return diagnostics::redact(latestProblem_);}
-std::string Logger::diagnosticReport(){std::lock_guard lock(mutex_);std::ostringstream o;o<<"Veyra 本地诊断(复制前脱敏预览;不会上传)\n";
+void Logger::recordFrame(diagnostics::FrameTraceEvent event){std::lock_guard lock(traceMutex_);frameTrace_.add(event);}
+std::pair<size_t,uint64_t> Logger::frameTraceSize(){std::lock_guard lock(traceMutex_);return {frameTrace_.size(),frameTrace_.overwritten()};}
+std::string Logger::diagnosticReport(){std::ostringstream o;o<<"Veyra 本地诊断(复制前脱敏预览;不会上传)\n";
+ {std::lock_guard lock(mutex_);
for(size_t i=0;i<diagnostics_.size();++i){const auto& e=diagnostics_.events()[i];const auto& r=e.resolution;
auto code=[](std::optional<uint64_t> v){return v?std::format("0x{:X}",*v):std::string("未提供");};
o<<"\n时间="<<e.timestamp<<" 严重级别="<<e.severity<<"\n组件="<<e.component<<" 阶段="<<e.stage<<" 次数="<<e.occurrenceCount<<"\n"<<e.message<<"\nHRESULT="<<code(e.hresult)<<" NGX="<<code(e.ngx)<<" NVOF="<<code(e.nvof)<<" SEH="<<code(e.seh)<<"\n";
o<<"source="<<r.source.width<<'x'<<r.source.height<<" base="<<r.base.width<<'x'<<r.base.height<<" NR="<<r.nr.width<<'x'<<r.nr.height<<" flow="<<r.flow.width<<'x'<<r.flow.height<<" FG="<<r.fg.width<<'x'<<r.fg.height<<" output="<<r.output.width<<'x'<<r.output.height<<"\nepoch="<<e.identity.epoch<<" frame="<<e.identity.sourceFrameId<<" batch="<<e.batch<<" subframe="<<e.subframe<<" revision="<<e.identity.settingsRevision<<"\nruntime="<<e.runtimeHash<<" flow="<<e.flowApplied<<" fallback="<<e.fallbackReason<<"\n";
- }return diagnostics::redact(o.str());
+ }}
+ std::vector<diagnostics::FrameTraceEvent> trace;uint64_t overwritten=0;
+ {std::lock_guard lock(traceMutex_);trace=frameTrace_.snapshot();overwritten=frameTrace_.overwritten();}
+ o<<"\nFrame trace: records="<<trace.size()<<" capacity="<<diagnostics::FrameTrace::capacity<<" overwritten="<<overwritten
+ <<"\nHost timestamps are monotonic 100ns; Ready is observed GPU completion, Present is submission, not scanout."
+ <<"\nDetail: Submitted=skipped FG count, Ready=invalid FG count, Present=subframe, Gpu=stage index, Reset=reason enum."
+ <<" Count: Submitted=FG evaluated, Ready=valid FG, Present=1, Reset=outcome enum, Cancelled=unpresented frames.\n";
+ for(const auto& e:trace)o<<"event="<<diagnostics::traceKindName(e.kind)<<" host="<<e.host100ns<<" session="<<e.session
+ <<" revision="<<e.identity.settingsRevision<<" epoch="<<e.identity.epoch<<" source="<<e.identity.sourceFrameId
+ <<" batch="<<e.batch<<" fence="<<e.fence<<" pts="<<e.pts100ns<<" detail="<<e.detail<<" count="<<e.count<<" ms="<<e.milliseconds<<'\n';
+ return diagnostics::redact(o.str());
}
void Logger::flush()
{
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 47249356..1f62161c 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -14,6 +14,7 @@
#include "veyra/source/CaptureCardSource.h"
#include "veyra/pipeline/EnhanceGraph.h"
#include "veyra/pipeline/ResetCoordinator.h"
+#include "veyra/diagnostics/ResetCause.h"
#include "veyra/sink/WasapiAudioSink.h"
#include "veyra/sink/ImageExportSink.h"
#include "veyra/gfx/D3D12DeviceContext.h"
@@ -191,6 +192,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
};
std::vector<std::shared_ptr<CompletionWatch>> pendingCompletions;
std::shared_ptr<FrameFlowWindow> frameFlow;
+ const uint64_t runSessionId=[&]{std::lock_guard lock(mutex_);return snapshot_.sessionId;}();
+ pipeline::ResetReason pendingResetCause=pipeline::ResetReason::Open;
+ auto traceFrame=[&](diagnostics::TraceKind kind,pipeline::FrameIdentity identity,uint64_t batch,
+ uint64_t fence,int64_t pts,uint32_t detail,uint32_t count,double ms){
+ Logger::instance().recordFrame({host100ns(),runSessionId,identity,batch,fence,pts,kind,detail,count,ms});
+ };
std::optional<diagnostics::FrameFlowMetrics::ResetRecord> resetRecord;
std::optional<diagnostics::FrameFlowMetrics::ResetRecord> lastResetRecord;
Clock::time_point resetStart{},resetStageStart{};
@@ -207,6 +214,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
lastResetRecord=resetRecord;
if(frameFlow)frameFlow->resetLifecycle(*resetRecord);
const auto& r=*resetRecord;const auto ms=[&](diagnostics::ResetStage s){return r.stageMs[size_t(s)].value_or(-1.0);};
+ traceFrame(diagnostics::TraceKind::Reset,{r.epoch,r.settingsRevision,r.sourceFrameId},0,0,0,r.reason,unsigned(outcome),*r.totalMs);
veyra::log::info("reset-lifecycle",std::format("session={} revision={} epoch={} source={} reason={} outcome={} drainMs={:.3f} destroyMs={:.3f} createMs={:.3f} warmupSubmitMs={:.3f} firstValidObserveMs={:.3f} totalMs={:.3f} (CPU observed; -1=not measured)",r.sessionId,r.settingsRevision,r.epoch,r.sourceFrameId,unsigned(r.reason),unsigned(r.outcome),ms(diagnostics::ResetStage::Drain),ms(diagnostics::ResetStage::Destroy),ms(diagnostics::ResetStage::Create),ms(diagnostics::ResetStage::Warmup),ms(diagnostics::ResetStage::FirstValid),*r.totalMs));
resetRecord.reset();
};
@@ -215,21 +223,17 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
markResetStage(diagnostics::ResetStage::FirstValid);
finishReset(diagnostics::ResetOutcome::Completed);
};
- auto historyResetCause=[&](const pipeline::FramePacket& packet)->pipeline::ResetReason{
- if(pipeline::hasFrameFlag(packet.flags,pipeline::FrameFlagBits::Open))return pipeline::ResetReason::Open;
- if(pipeline::hasFrameFlag(packet.flags,pipeline::FrameFlagBits::Seek))return pipeline::ResetReason::Seek;
- if(pipeline::hasFrameFlag(packet.flags,pipeline::FrameFlagBits::Drop))return pipeline::ResetReason::FrameDrop;
- if(pipeline::hasFrameFlag(packet.flags,pipeline::FrameFlagBits::Resize))return pipeline::ResetReason::Resize;
- if(pipeline::hasFrameFlag(packet.flags,pipeline::FrameFlagBits::DeviceLost))return pipeline::ResetReason::DeviceLost;
- if(pipeline::hasFrameFlag(packet.flags,pipeline::FrameFlagBits::PauseResume))return pipeline::ResetReason::PauseResume;
- if(pipeline::hasFrameFlag(packet.flags,pipeline::FrameFlagBits::Discontinuity))return pipeline::ResetReason::FrameDrop;
- if(pipeline::hasFrameFlag(packet.flags,pipeline::FrameFlagBits::Cut))return pipeline::ResetReason::SceneCut;
- return pipeline::ResetReason::SceneCut;
- };
OnExit resetExit{[&]{finishReset(stop_?diagnostics::ResetOutcome::Cancelled:diagnostics::ResetOutcome::Failed);}};
auto collectTimings=[&]{
- for(const auto& sample:graph.takeGpuTimings())if(frameFlow)frameFlow->gpuFrame(sample,host100ns());
- for(const auto& sample:presenter.takeGpuTimings(ctx.fence()))if(frameFlow)frameFlow->gpuFrame(sample,host100ns());
+ auto record=[&](const diagnostics::GpuFrameTiming& sample){
+ if(frameFlow)frameFlow->gpuFrame(sample,host100ns());
+ for(size_t i=0;i<sample.gpu.size();++i){const auto& gpu=sample.gpu[i];
+ if(gpu.state==diagnostics::SampleState::Measured&&gpu.milliseconds)
+ traceFrame(diagnostics::TraceKind::Gpu,sample.identity,0,0,0,unsigned(i),1,*gpu.milliseconds);
+ }
+ };
+ for(const auto& sample:graph.takeGpuTimings())record(sample);
+ for(const auto& sample:presenter.takeGpuTimings(ctx.fence()))record(sample);
};
// Shared with the presenter: resolve each batch on this single
// object so SDK status and generated counts are consumed once.
@@ -242,6 +246,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(batch.batch.frames[i].validity==pipeline::GenerationValidity::Valid)++valid;else ++invalid;
}
watch.flow->ready(batch.batch.batchId,watch.real,valid,invalid,host100ns());
+ traceFrame(diagnostics::TraceKind::Ready,batch.batch.identity,batch.batch.batchId,std::max(batch.videoFenceValue,batch.genFenceValue),batch.batch.b100ns,invalid,valid,elapsedMs(watch.processStart));
if(watch.real)completedProcessing(batch.batch.identity);
{
if(liveStats.identity.epoch==batch.batch.identity.epoch&&liveStats.identity.settingsRevision==batch.batch.identity.settingsRevision&&batch.fgEvaluated&&!batch.historyReset&&!batch.fgRecovery){liveCompletion.add(elapsedMs(watch.processStart));lastFgCompletion=host100ns();}
@@ -257,7 +262,6 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
auto waitLive=[&]{const auto due=liveScheduler?liveScheduler->wakeAt():0;deadlineWait.slice(due>host100ns()?std::min(1.0,double(due-host100ns())/10000):1.0);};
uint64_t metricsRevision=options.settings.revision,metricsEpoch=0,statsSourceBase=0;
uint64_t slotWaitBase=ring.cpuWaitCount(),submitBase=ring.submitCount();double slotWaitMsBase=ring.cpuWaitMilliseconds();
- const uint64_t runSessionId=[&]{std::lock_guard lock(mutex_);return snapshot_.sessionId;}();
std::shared_ptr<FrameCompletionRates> completionRates;
source::CaptureMetrics captureFlowBase{},captureFlowLast{};
uint64_t rateSkippedBase=0;
@@ -293,7 +297,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
resetStart=resetStageStart=Clock::now();
resetRecord=diagnostics::FrameFlowMetrics::ResetRecord{};
resetRecord->sessionId=runSessionId;resetRecord->settingsRevision=requested.revision;
- resetRecord->reason=static_cast<uint8_t>(pipeline::ResetReason::Resize);
+ resetRecord->reason=static_cast<uint8_t>(pipeline::ResetReason::Settings);
if(frameFlow)frameFlow->resetLifecycle(*resetRecord);
drainLivePresentation();
// A drain may outlive several slider notifications. Build
@@ -335,7 +339,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
const double seek=seekSeconds_.exchange(-1);
if(seek>=0&&!isImage&&!isCapture){
if(!ring.drainQueue()||!activeSource->seek({static_cast<int64_t>(seek*1000000),1000000})){status(L"跳转失败",true);break;}
- discardBefore=seek*1000;seekPreviewPending=true;reset=true;anchorMs=discardBefore;anchor=Clock::now();lastAudioClockMs=discardBefore;audioClockExhausted=false;audioRebuffering=false;if(audioStarted){audioPipe.setPaused(paused_);audioPipe.requestSeek(discardBefore);}
+ discardBefore=seek*1000;seekPreviewPending=true;reset=true;pendingResetCause=pipeline::ResetReason::Seek;anchorMs=discardBefore;anchor=Clock::now();lastAudioClockMs=discardBefore;audioClockExhausted=false;audioRebuffering=false;if(audioStarted){audioPipe.setPaused(paused_);audioPipe.requestSeek(discardBefore);}
}
if(!transaction&&((paused_&&!seekPreviewPending)||(isImage&&hasOutput))){
drainLivePresentation();
@@ -345,7 +349,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(hasOutput&&graph.resolveGeneration(out))completeReset(out.batch.identity);
std::this_thread::sleep_for(std::chrono::milliseconds(16));continue;
}
- if(wasPaused&&!paused_){audioRebuffering=false;if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;wasPaused=false;}
+ if(wasPaused&&!paused_){audioRebuffering=false;if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;pendingResetCause=pipeline::ResetReason::PauseResume;wasPaused=false;}
// Backpressure before reading the capacity-one source mailbox:
// when a lease frees we consume the newest available sample.
if(liveScheduler&&!transaction){
@@ -411,7 +415,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
const bool injectedReject=transaction&&!options.nr&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_DISABLE",nullptr,0)>0;
if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");
pipeline::EnhanceGraph::FgAdmission admitFg;
- // Both graph FG backends can reseed after a skipped pair. XeSS
+ // DLSS can reseed after a skipped pair. XeSS
// owns generation inside its presenter and has no graph admission.
if(isCapture&&!rereadCached&&useLiveFgAdmission&&options.settings.frameGenerationBackend!=FrameGenerationBackend::XeSS){
std::optional<double> completionP95;double presentP95=0;uint64_t predictionEpoch=0;
@@ -443,7 +447,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
const auto processDone=Clock::now();
if(!resetRecord&&out.historyReset){
resetStart=processStart;resetStageStart=processStart;
- resetRecord=diagnostics::FrameFlowMetrics::ResetRecord{};resetRecord->sessionId=runSessionId;resetRecord->settingsRevision=out.batch.identity.settingsRevision;resetRecord->epoch=out.batch.identity.epoch;resetRecord->sourceFrameId=out.batch.identity.sourceFrameId;resetRecord->reason=static_cast<uint8_t>(historyResetCause(pkt));
+ resetRecord=diagnostics::FrameFlowMetrics::ResetRecord{};resetRecord->sessionId=runSessionId;resetRecord->settingsRevision=out.batch.identity.settingsRevision;resetRecord->epoch=out.batch.identity.epoch;resetRecord->sourceFrameId=out.batch.identity.sourceFrameId;resetRecord->reason=static_cast<uint8_t>(diagnostics::resetCause(pkt.flags,pendingResetCause,out.detectedReset));
resetRecord->stageMs[size_t(diagnostics::ResetStage::Drain)]=0.0;resetRecord->stageMs[size_t(diagnostics::ResetStage::Destroy)]=0.0;resetRecord->stageMs[size_t(diagnostics::ResetStage::Create)]=0.0;
resetRecord->rebuilt=false;markResetStage(diagnostics::ResetStage::Warmup);
if(frameFlow)frameFlow->resetLifecycle(*resetRecord);
@@ -452,6 +456,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
resetRecord->epoch=out.batch.identity.epoch;resetRecord->sourceFrameId=out.batch.identity.sourceFrameId;
markResetStage(diagnostics::ResetStage::Warmup);
}
+ pendingResetCause=pipeline::ResetReason::None;
if(!frameFlow||metricsRevision!=options.settings.revision||metricsEpoch!=out.batch.identity.epoch){
const bool settingsChanged=metricsRevision!=options.settings.revision;
metricsRevision=options.settings.revision;metricsEpoch=out.batch.identity.epoch;statsStart=Clock::now();statsSourceBase=sourceFrames-uint64_t(!rereadCached);
@@ -473,6 +478,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(veyra::log::verboseFrameLogs())veyra::log::info("frame-lineage",std::format("batch={} epoch={} revision={} sourceA={} sourceB={} ptsA={} ptsB={} arrivalA={} arrivalB={} captureCallbacks={}",out.batch.batchId,out.batch.identity.epoch,out.batch.identity.settingsRevision,lineage->a.identity.sourceFrameId,lineage->b.identity.sourceFrameId,lineage->a.pts100ns,lineage->b.pts100ns,lineage->a.host100ns,lineage->b.host100ns,lineage->a.captureCallback&&lineage->b.captureCallback));
}
processTimes.add(processMs);
+ traceFrame(diagnostics::TraceKind::Submitted,out.batch.identity,out.batch.batchId,std::max(out.videoFenceValue,out.genFenceValue),out.batch.b100ns,out.fgSkippedBeforeEval,out.fgEvaluated,processMs);
frameFlow->cpu(diagnostics::CpuStage::Decode,decodeMs,host100ns());
frameFlow->cpu(diagnostics::CpuStage::Submit,processMs,host100ns());
frameFlow->cpu(diagnostics::CpuStage::SlotWait,processSlotWaitMs,host100ns());
@@ -534,6 +540,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
const auto xessGenerated=presenter.xessGeneratedCount()-beforeXess,xessPresented=presenter.xessPresentedCount()-beforeXessPresented;
item.lease->consumerFence=ring.lastSignaledValue();const bool didPresent=presenter.submittedCount()>before;s.blit=presenter.blitTiming(ctx.fence());
const auto elapsed=elapsedMs(begin);s.presentMs+=elapsed;flow->cpu(diagnostics::CpuStage::Present,elapsed,host100ns());
+ if(didPresent)traceFrame(diagnostics::TraceKind::Present,item.identity,batch.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsed);
if(xessPresented)flow->xessSubmitted(xessPresented,xessGenerated,host100ns());
if(didPresent&&physicalCapture)captureSource.videoPresented(double(item.pts100ns)/10000,host100ns());
if(didPresent&&!generated&&!rereadCached)flow->latency(captureArrival,host100ns());
@@ -546,6 +553,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
},[&,watch,step,flow=frameFlow]{
const auto& batch=watch->output;const auto& s=*step;
if(s.handled<batch.batch.count)++presentationCancelledJobs;
+ if(s.handled<batch.batch.count)traceFrame(diagnostics::TraceKind::Cancelled,batch.batch.identity,batch.batch.batchId,0,batch.batch.b100ns,0,batch.batch.count-s.handled,0);
flow->update([&](auto& m){m.counters.cancelledBeforePresent+=batch.batch.count-s.handled;m.gpuReadyWaitMs=s.readyMs;m.deadlineWaitMs=s.waitMs;if(s.count)m.captureArrivalToPresentReturnMs=s.ageMs;m.counters.generatedExpiredAfterEval+=s.dropped;});
if(liveStats.identity.epoch!=batch.batch.identity.epoch||liveStats.identity.settingsRevision!=batch.batch.identity.settingsRevision)return;
liveStats.submitted+=s.count;liveStats.expired+=s.dropped;
@@ -566,9 +574,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
deadlineWait.slice(.2);
}
if(stop_)break;
- if((paused_&&!seekPreviewPending)||seekSeconds_>=0){reset=true;if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} cancelled before submit (pause/seek)",out.batch.batchId));continue;}
+ if((paused_&&!seekPreviewPending)||seekSeconds_>=0){reset=true;pendingResetCause=seekSeconds_>=0?pipeline::ResetReason::Seek:pipeline::ResetReason::PauseResume;if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} cancelled before submit (pause/seek)",out.batch.batchId));continue;}
unsigned valid=0,invalid=0;for(unsigned i=0;i<out.batch.count;++i)if(out.batch.frames[i].kind==pipeline::FrameKind::Generated){if(out.batch.frames[i].validity==pipeline::GenerationValidity::Valid)++valid;else ++invalid;}
frameFlow->ready(out.batch.batchId,!rereadCached&&!isImage,valid,invalid,host100ns());
+ traceFrame(diagnostics::TraceKind::Ready,out.batch.identity,out.batch.batchId,std::max(out.videoFenceValue,out.genFenceValue),out.batch.b100ns,invalid,valid,elapsedMs(processStart));
completeReset(out.batch.identity);
if(!rereadCached&&!isImage)completedProcessing(out.batch.identity);
gpuWaitMs=elapsedMs(readyStart);gpuReadyTimes.add(gpuWaitMs);
@@ -598,13 +607,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
frameFlow->cpu(diagnostics::CpuStage::Present,elapsedMs(begin),host100ns());
frameFlow->xessSubmitted(presenter.xessPresentedCount()-beforeXessPresented,presenter.xessGeneratedCount()-beforeXess,host100ns());
item.lease->consumerFence=ring.lastSignaledValue();
+ if(presenter.submittedCount()>before)traceFrame(diagnostics::TraceKind::Present,item.identity,out.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsedMs(begin));
if(presenter.submittedCount()>before){++handled;frameFlow->presented(generated,item.lease->consumerFence,host100ns());}
if(presenter.submittedCount()>before&&!generated&&!rereadCached)frameFlow->latency(std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100,host100ns());
if(presenter.submittedCount()>before&&generated&&lineage)frameFlow->generatedLatency(*lineage,host100ns());
if(presenter.submittedCount()>before){++submitted;const auto time=host100ns();submissionTimes.push_back(time);while(submissionTimes.size()>1&&time-submissionTimes.front()>10000000)submissionTimes.pop_front();if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",out.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));}
}
if(presentFailed){status(L"画面提交失败",true);break;}
- if(interrupted){reset=true;continue;}
+ if(interrupted){reset=true;pendingResetCause=seekSeconds_>=0?pipeline::ResetReason::Seek:pipeline::ResetReason::PauseResume;continue;}
seekPreviewPending=false;
}
if(!liveScheduler){scheduleWaits.add(frameWaitMs);presentTimes.add(framePresentMs);}
@@ -642,6 +652,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
snapshot_.schedulingWaitP95Ms=waitP95;snapshot_.processCpuP95Ms=processTimes.p95();snapshot_.presentCpuP95Ms=presentP95;
}
const auto gpuP95=[&](diagnostics::GpuStage stage){return gpuStageTimes[size_t(stage)].p95();};
+ if(Clock::now()>=nextTimingLog){const auto [retained,overwritten]=Logger::instance().frameTraceSize();
+ veyra::log::info("frame-trace",std::format("retained={} capacity=8192 overwritten={} (records available in diagnostic preview)",retained,overwritten));}
if(!isCapture&&Clock::now()>=nextTimingLog){veyra::log::info("player-timing",std::format("revision={} decodeP95Ms={:.3f} graphSubmitP95Ms={:.3f} gpuReadyP95Ms={:.3f} presentP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} processed={}",options.settings.revision,decodeTimes.p95(),processTimes.p95(),gpuReadyTimes.p95(),presentTimes.p95(),gpuP95(diagnostics::GpuStage::Color),gpuP95(diagnostics::GpuStage::Sr),gpuP95(diagnostics::GpuStage::Flow),gpuP95(diagnostics::GpuStage::Nr),gpuP95(diagnostics::GpuStage::Residual),gpuP95(diagnostics::GpuStage::FgBatch),gpuP95(diagnostics::GpuStage::Blit),slotWaitCount,slotWaitMilliseconds,commandSubmits,submitted,expired,sourceFrames-statsSourceBase));nextTimingLog=Clock::now()+std::chrono::seconds(1);}
if(isCapture&&Clock::now()>=nextTimingLog){
logFrameFlow(measured.flow,"active");
diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cpp
index 058b69aa..dc15ceee 100644
--- a/src/engine/PresetStore.cpp
+++ b/src/engine/PresetStore.cpp
@@ -13,21 +13,22 @@ bool nameOk(const std::wstring& s){return !s.empty()&&s.size()<=48&&s.front()!=L
std::wstring trim(std::wstring s){auto a=s.find_first_not_of(L" \t\r\n");if(a==s.npos)return {};auto b=s.find_last_not_of(L" \t\r\n");return s.substr(a,b-a+1);}
}
std::string PresetStore::serialize()const{
- std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 7\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';
+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 8\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';
for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<' '<<int(s.audioSync)<<' '<<s.audioOffsetMs<<'\n';}return o.str();
}
bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std::wstring& def){
if(data.size()>65536)return false;std::istringstream in(data);in.imbue(std::locale::classic());std::string magic,d;int version=0;size_t count=0;
- if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>7)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;
+ if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>8)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;
for(size_t i=0;i<count;++i){UserPreset p;std::string n;int policy,flow,content,nr,sr;auto& s=p.settings;auto& m=s.model;auto& r=s.residual;
if(!(in>>std::quoted(n)>>m.intensity>>m.tone>>m.structure>>m.skin>>m.style>>m.autoMask>>m.uiCorrection>>r.total>>r.darken>>r.brighten>>r.color>>r.luminance>>nr>>sr>>s.multiplier>>policy>>flow>>content))return false;
if(version>=2){int enabled;if(!(in>>enabled>>s.protection.featherPixels)||enabled<0||enabled>1)return false;s.protection.enabled=enabled!=0;
for(auto& q:s.protection.regions)if(!(in>>q.left>>q.top>>q.right>>q.bottom))return false;}
if(version>=3&&!(in>>s.videoSrQuality))return false;
- if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>(version>=6?2:1))return false;
- // Version 4-5 used value 1 for FRUC; preserve its intent as DLSS after removal.
- if(version<6 && backend==1) backend=0;
- s.frameGenerationBackend=static_cast<FrameGenerationBackend>(backend);}
+ if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>(version>=6&&version<=7?2:1))return false;
+ // Before v8, 1 meant removed FRUC and 2 meant XeSS. New writes use v8.
+ s.frameGenerationBackend=version<8
+ ?(backend==2?FrameGenerationBackend::XeSS:FrameGenerationBackend::Dlss)
+ :static_cast<FrameGenerationBackend>(backend);}
if(version>=5){uint32_t target;if(!(in>>target))return false;s.srTarget=static_cast<pipeline::SrTarget>(target);}
if(version>=6){int backend,half;if(!(in>>backend>>half)||half<0||half>1)return false;s.opticalFlowBackend=static_cast<OpticalFlowBackend>(backend);s.amdFlowHalfResolution=half!=0;}
if(version>=7){int sync;if(!(in>>sync>>s.audioOffsetMs))return false;s.audioSync=static_cast<AudioSyncMode>(sync);}
diff --git a/src/ngx/FrucBackend.cpp b/src/ngx/FrucBackend.cpp
deleted file mode 100644
index dbc097e0..00000000
--- a/src/ngx/FrucBackend.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-#include "veyra/ngx/FrucBackend.h"
-#include "veyra/ngx/FrucWorkerProtocol.h"
-#include "veyra/gfx/D3D12DeviceContext.h"
-#include "veyra/Log.h"
-#include <wrl/client.h>
-#include <filesystem>
-#include <format>
-#include <vector>
-namespace veyra::ngx {
-using Microsoft::WRL::ComPtr;
-namespace {
-bool hrOk(HRESULT hr,const char* op) {
- if(FAILED(hr))log::error("fruc-ipc",std::format("{} hr=0x{:X}",op,unsigned(hr)));
- return SUCCEEDED(hr);
-}
-void barrier(ID3D12GraphicsCommandList* list,ID3D12Resource* resource,D3D12_RESOURCE_STATES before,D3D12_RESOURCE_STATES after) {
- D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
- b.Transition={resource,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,before,after};list->ResourceBarrier(1,&b);
-}
-struct Handle {
- HANDLE value=nullptr;
- ~Handle(){if(value)CloseHandle(value);}
- void close(){if(value)CloseHandle(value);value=nullptr;}
-};
-}
-struct FrucBackend::Impl {
- gfx::D3D12DeviceContext* ctx=nullptr;
- unsigned width=0,height=0,count=0;uint64_t serial=0;
- ComPtr<ID3D12Resource> shared[5];ComPtr<ID3D12Fence> fence;
- Handle textures[5],fenceHandle,mapping,request,response,process,job;
- FrucWorkerMessage* message=nullptr;
- ~Impl() {
- stop();if(message)UnmapViewOfFile(message);
- }
- void stop() {
- if(!process.value)return;
- message->command=2;SetEvent(request.value);
- if(WaitForSingleObject(process.value,3000)!=WAIT_OBJECT_0) {
- // Only this owned worker is terminated; no user processes are touched.
- TerminateJobObject(job.value,1);WaitForSingleObject(process.value,1000);
- }
- process.close();job.close();
- }
- bool acknowledge(DWORD timeout) {
- HANDLE events[]{response.value,process.value};
- const auto result=WaitForMultipleObjects(2,events,FALSE,timeout);
- if(result!=WAIT_OBJECT_0) {
- DWORD exitCode=0;GetExitCodeProcess(process.value,&exitCode);
- log::error("fruc-ipc",std::format("worker wait={} exit={}",result,exitCode));return false;
- }
- if(message->result||message->seh) {
- log::error("fruc-ipc",std::format("worker result={} seh={}",message->result,message->seh));return false;
- }
- return true;
- }
- bool start() {
- SECURITY_ATTRIBUTES security{sizeof(security),nullptr,TRUE};
- if(!mapping.value) {
- mapping.value=CreateFileMappingW(INVALID_HANDLE_VALUE,&security,PAGE_READWRITE,0,sizeof(FrucWorkerMessage),nullptr);
- if(!mapping.value)return false;
- message=static_cast<FrucWorkerMessage*>(MapViewOfFile(mapping.value,FILE_MAP_ALL_ACCESS,0,0,sizeof(FrucWorkerMessage)));
- if(!message)return false;
- request.value=CreateEventW(&security,FALSE,FALSE,nullptr);response.value=CreateEventW(&security,FALSE,FALSE,nullptr);
- if(!request.value||!response.value)return false;
- }
- ResetEvent(request.value);ResetEvent(response.value);
- *message=FrucWorkerMessage{};
- message->width=width;message->height=height;message->multiplier=count+1;message->adapter=ctx->device()->GetAdapterLuid();
- message->fence=reinterpret_cast<uint64_t>(fenceHandle.value);
- message->request=reinterpret_cast<uint64_t>(request.value);message->response=reinterpret_cast<uint64_t>(response.value);
- std::vector<HANDLE> inherited{mapping.value,request.value,response.value,fenceHandle.value};
- for(unsigned j=0;j<count+2;++j){message->textures[j]=reinterpret_cast<uint64_t>(textures[j].value);inherited.push_back(textures[j].value);}
- wchar_t exePath[32768]{};if(!GetModuleFileNameW(nullptr,exePath,32768))return false;
- const auto executable=std::filesystem::path(exePath).parent_path()/L"veyra_fruc_worker.exe";
- // Unique worker log survives worker crashes and reset/reopen cycles.
- wchar_t existingLog[1024]{};GetEnvironmentVariableW(L"VEYRA_LOG_FILE",existingLog,1024);
- auto logPath=(existingLog[0]?std::filesystem::path(existingLog).parent_path():std::filesystem::path(L"logs"))/
- std::format(L"fruc-worker-{}-{}.log",GetCurrentProcessId(),GetTickCount64());
- const auto absoluteLog=std::filesystem::absolute(logPath).wstring();
- if(absoluteLog.size()>=std::size(message->logPath))return false;
- wcscpy_s(message->logPath,absoluteLog.c_str());
- SIZE_T bytes=0;InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
- std::vector<unsigned char> storage(bytes);auto* attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
- if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes))return false;
- struct AttributesCleanup{LPPROC_THREAD_ATTRIBUTE_LIST list;~AttributesCleanup(){DeleteProcThreadAttributeList(list);}}cleanup{attributes};
- if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited.data(),inherited.size()*sizeof(HANDLE),nullptr,nullptr))return false;
- job.value=CreateJobObjectW(nullptr,nullptr);JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
- limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
- if(!job.value||!SetInformationJobObject(job.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))return false;
- STARTUPINFOEXW startup{};startup.StartupInfo.cb=sizeof(startup);startup.lpAttributeList=attributes;
- PROCESS_INFORMATION pi{};auto command=std::format(L"\"{}\" {}",executable.wstring(),reinterpret_cast<uint64_t>(mapping.value));
- if(!CreateProcessW(executable.c_str(),command.data(),nullptr,nullptr,TRUE,CREATE_NO_WINDOW|CREATE_SUSPENDED|EXTENDED_STARTUPINFO_PRESENT,nullptr,nullptr,&startup.StartupInfo,&pi)) {
- log::error("fruc-ipc",std::format("CreateProcess error={}",GetLastError()));return false;
- }
- process.value=pi.hProcess;Handle thread;thread.value=pi.hThread;
- if(!AssignProcessToJobObject(job.value,process.value)) {TerminateProcess(process.value,1);return false;}
- if(ResumeThread(thread.value)==DWORD(-1))return false;
- log::info("fruc-ipc",std::format("worker pid={} streams={} extent={}x{}",pi.dwProcessId,count,width,height));
- return acknowledge(15000);
- }
-};
-FrucBackend::FrucBackend():p_(std::make_unique<Impl>()){}
-FrucBackend::~FrucBackend()=default;
-bool FrucBackend::initialize(gfx::D3D12DeviceContext& ctx,unsigned width,unsigned height,unsigned multiplier) {
- if(p_->ctx||!width||!height||multiplier<2||multiplier>4)return false;
- auto& p=*p_;p.ctx=&ctx;p.width=width;p.height=height;p.count=multiplier-1;
- SECURITY_ATTRIBUTES security{sizeof(security),nullptr,TRUE};
- if(!hrOk(ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_SHARED,IID_PPV_ARGS(&p.fence)),"CreateFence")||
- !hrOk(ctx.device()->CreateSharedHandle(p.fence.Get(),&security,GENERIC_ALL,nullptr,&p.fenceHandle.value),"ShareFence"))return false;
- D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_DEFAULT;
- D3D12_RESOURCE_DESC desc{};desc.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;desc.Width=width;desc.Height=height;
- desc.DepthOrArraySize=1;desc.MipLevels=1;desc.SampleDesc.Count=1;desc.Format=DXGI_FORMAT_R8G8B8A8_UNORM;
- desc.Flags=D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS|D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
- for(unsigned j=0;j<p.count+2;++j) {
- if(!hrOk(ctx.device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_SHARED,&desc,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&p.shared[j])),"SharedTexture")||
- !hrOk(ctx.device()->CreateSharedHandle(p.shared[j].Get(),&security,GENERIC_ALL,nullptr,&p.textures[j].value),"ShareTexture"))return false;
- }
- return p.start();
-}
-bool FrucBackend::reset() {
- // The next source frame updates FRUC history without warping across the
- // discontinuity. Keep CUDA allocations and worker alive during normal reset.
- p_->message->command=3;p_->message->result=1;p_->message->seh=0;
- if(SetEvent(p_->request.value)&&p_->acknowledge(10000))return true;
- log::warn("fruc-ipc","CUDA reseed failed; restarting owned worker");
- p_->stop();return p_->start();
-}
-void FrucBackend::recordInput(ID3D12GraphicsCommandList* list,ID3D12Resource* input,unsigned parity) {
- auto target=p_->shared[parity].Get();
- barrier(list,input,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE);
- barrier(list,target,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(target,input);
- barrier(list,target,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COMMON);
- barrier(list,input,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
-}
-bool FrucBackend::execute(unsigned parity,double previousMs,double currentMs,std::array<bool,3>& repeated) {
- auto& p=*p_;auto& m=*p.message;
- m.command=1;m.result=1;m.seh=0;m.parity=parity;m.previousMs=previousMs;m.currentMs=currentMs;
- m.inputFence=++p.serial;
- if(!hrOk(p.ctx->directQueue()->Signal(p.fence.Get(),m.inputFence),"InputSignal")||!SetEvent(p.request.value))return false;
- // Wait for CPU API submission/results, not for GPU completion. CUDA/FRUC's
- // internal CPU blocking is unchanged; all pixel synchronization is GPU-side.
- if(!p.acknowledge(10000))return false;
- p.serial=m.outputFence;for(unsigned j=0;j<p.count;++j)repeated[j]=m.repeated[j];
- return hrOk(p.ctx->directQueue()->Wait(p.fence.Get(),m.outputFence),"OutputQueueWait");
-}
-void FrucBackend::recordOutput(ID3D12GraphicsCommandList* list,ID3D12Resource* target,unsigned subframe) {
- auto input=p_->shared[subframe+1].Get();
- barrier(list,input,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE);
- barrier(list,target,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(target,input);
- barrier(list,target,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COMMON);
- barrier(list,input,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
-}
-}
diff --git a/src/ngx/FrucWorker.cpp b/src/ngx/FrucWorker.cpp
deleted file mode 100644
index df8011f0..00000000
--- a/src/ngx/FrucWorker.cpp
+++ /dev/null
@@ -1,256 +0,0 @@
-#include "veyra/ngx/FrucWorkerProtocol.h"
-
-#include "veyra/FileIdentity.h"
-#include "veyra/Log.h"
-#include "veyra/RuntimePaths.h"
-#include <d3d11_4.h>
-#include <dxgi1_4.h>
-#include <wrl/client.h>
-#include <filesystem>
-#include <format>
-#include <mutex>
-#pragma warning(push,0)
-#include <NvOFFRUC.h>
-#include <cuda.h>
-#pragma warning(pop)
-namespace veyra::ngx {
-using Microsoft::WRL::ComPtr;
-namespace {
-bool hrOk(HRESULT hr,const char* op,bool frequent=false){if(!frequent||FAILED(hr)||log::verboseFrameLogs())log::info("fruc",std::format("{} hr=0x{:X}",op,unsigned(hr)));return SUCCEEDED(hr);}
-template<class Fn, class... Args>
-NvOFFRUC_STATUS callSafe(unsigned& seh, Fn fn, Args... args) {
- __try { return fn(args...); }
- __except(EXCEPTION_EXECUTE_HANDLER) { seh=GetExceptionCode(); return NvOFFRUC_ERR_GENERIC; }
-}
-template<class Fn, class... Args>
-bool checkedCall(const char* operation, Fn fn, Args... args) {
- unsigned seh=0;
- const auto result=callSafe(seh,fn,args...);
- log::info("fruc",std::format("{} result={} seh={}",operation,int(result),seh));
- return result==NvOFFRUC_SUCCESS && !seh;
-}
-bool cudaOk(CUresult result,const char* op) {
- if(result!=CUDA_SUCCESS)log::error("fruc",std::format("{} cudaResult={}",op,int(result)));
- return result==CUDA_SUCCESS;
-}
-
-}
-struct WorkerKernel {
- using GetContext = CUresult (CUDAAPI*)(CUcontext*);
- using SetContext = CUresult (CUDAAPI*)(CUcontext);
- HMODULE cuda=nullptr; GetContext getContext=nullptr; SetContext setContext=nullptr;
- bool reseed=false;
- unsigned inputSlot=0;
- using DxDevice=CUresult(CUDAAPI*)(CUdevice*,IDXGIAdapter*);
- using DxRegister=CUresult(CUDAAPI*)(CUgraphicsResource*,ID3D11Resource*,unsigned);
- DxRegister dxRegister=nullptr;
- decltype(&cuCtxCreate) createContext=nullptr;
- decltype(&cuCtxDestroy) destroyContext=nullptr;
- decltype(&cuArrayCreate) createArray=nullptr;
- decltype(&cuArrayDestroy) destroyArray=nullptr;
- decltype(&cuGraphicsMapResources) mapResources=nullptr;
- decltype(&cuGraphicsUnmapResources) unmapResources=nullptr;
- decltype(&cuGraphicsUnregisterResource) unregisterGraphics=nullptr;
- decltype(&cuGraphicsSubResourceGetMappedArray) mappedArray=nullptr;
- decltype(&cuMemcpy2DAsync) copyAsync=nullptr;
- CUdevice cudaDevice=0;
- CUcontext ownedContext[3]={}; // Only slot 0 owns the context shared by all streams.
- CUarray arrays[3][3]={};
- CUgraphicsResource graphics[3][3]={};
- ComPtr<ID3D11Texture2D> bridge[3][3];
- ComPtr<ID3D11DeviceContext4> context4;
- CUcontext streamContext[3]={};
- HMODULE lib=nullptr;unsigned width=0,height=0,count=0;uint64_t serial=0;
- ComPtr<ID3D11Device> device;ComPtr<ID3D11Device5> device5;
- ComPtr<ID3D11DeviceContext> context;
- ComPtr<ID3D11Fence> fence11;
- ComPtr<ID3D11Texture2D> tex[5];
- NvOFFRUCHandle handles[3]={};bool registered[3]={};
- PtrToFuncNvOFFRUCCreate create=nullptr;PtrToFuncNvOFFRUCDestroy destroy=nullptr;
- PtrToFuncNvOFFRUCRegisterResource reg=nullptr;PtrToFuncNvOFFRUCUnregisterResource unreg=nullptr;PtrToFuncNvOFFRUCProcess process=nullptr;
- struct ContextScope {
- WorkerKernel& owner;
- CUcontext saved=nullptr;
- bool valid=false;
- explicit ContextScope(WorkerKernel& p):owner(p) {
- valid=p.getContext && cudaOk(p.getContext(&saved),"GetContext");
- }
- ~ContextScope() { if(valid)cudaOk(owner.setContext(saved),"RestoreContext"); }
- };
- void release() {
- ContextScope scope(*this);
- for(unsigned index=3;index>0;--index) {
- const unsigned j=index-1;
- if(!handles[j])continue;
- if(scope.saved==streamContext[j])scope.saved=nullptr;
- if(setContext&&streamContext[j])cudaOk(setContext(streamContext[j]),"ReleaseContext");
- if(registered[j]) {
- NvOFFRUC_UNREGISTER_RESOURCE_PARAM r{};
- r.uiCount=3;for(unsigned i=0;i<3;++i)r.pArrResource[i]=arrays[j][i];
- checkedCall("Unregister",unreg,handles[j],&r);
- registered[j]=false;
- }
- checkedCall("Destroy",destroy,handles[j]);
- handles[j]=nullptr;streamContext[j]=nullptr;
- }
- if(ownedContext[0]){
- cudaOk(setContext(ownedContext[0]),"InteropReleaseContext");
- for(unsigned j=0;j<3;++j){
- for(unsigned i=0;i<3;++i){if(graphics[j][i])cudaOk(unregisterGraphics(graphics[j][i]),"InteropUnregister");if(arrays[j][i])cudaOk(destroyArray(arrays[j][i]),"InteropFreeArray");graphics[j][i]=nullptr;arrays[j][i]=nullptr;}
- }
- if(scope.saved==ownedContext[0])scope.saved=nullptr;
- cudaOk(destroyContext(ownedContext[0]),"InteropDestroyContext");ownedContext[0]=nullptr;
- }
- }
- ~WorkerKernel() {
- release();
- for(auto& stream:bridge)for(auto& texture:stream)texture.Reset();
- context4.Reset();
- for(auto& t:tex)t.Reset();
- fence11.Reset();context.Reset();device5.Reset();device.Reset();
- if(lib)FreeLibrary(lib);
- if(cuda)FreeLibrary(cuda);
- }
- bool initialize(FrucWorkerMessage&);
- bool execute(FrucWorkerMessage&);
- bool createStreams() {
- ContextScope scope(*this);
- if(!scope.valid)return false;
- for(unsigned j=0;j<count;++j) {
- NvOFFRUC_CREATE_PARAM c{};
- c.uiWidth=width;c.uiHeight=height;c.pDevice=nullptr;
- c.eResourceType=CudaResource;c.eSurfaceFormat=ARGBSurface;c.eCUDAResourceType=CudaResourceCuArray;
- if(!ownedContext[0]&&!cudaOk(createContext(&ownedContext[0],0,cudaDevice),"InteropCreateContext"))return false;
- if(!cudaOk(setContext(ownedContext[0]),"InteropSharedContext"))return false;
- if(!checkedCall("Create",create,&c,&handles[j])||!handles[j])return false;
- // Each FRUC stream uses the caller-owned CUDA context and arrays.
- if(!cudaOk(getContext(&streamContext[j]),"StreamContext")||!streamContext[j])return false;
- if(streamContext[j]!=ownedContext[0]){log::error("fruc","CUDA context ownership changed during Create");return false;}
- log::info("fruc",std::format("Context stream={} ptr={}",j,static_cast<void*>(streamContext[j])));
- NvOFFRUC_REGISTER_RESOURCE_PARAM r{};
- r.uiCount=3;r.pD3D11FenceObj=nullptr;
- for(unsigned i=0;i<3;++i){
- {
- CUDA_ARRAY_DESCRIPTOR d{};d.Width=width;d.Height=height;d.Format=CU_AD_FORMAT_UNSIGNED_INT8;d.NumChannels=4;
- D3D11_TEXTURE2D_DESC texture{};texture.Width=width;texture.Height=height;texture.MipLevels=texture.ArraySize=1;texture.Format=DXGI_FORMAT_R8G8B8A8_UNORM;texture.SampleDesc.Count=1;texture.Usage=D3D11_USAGE_DEFAULT;texture.BindFlags=D3D11_BIND_SHADER_RESOURCE|D3D11_BIND_RENDER_TARGET;
- if(!hrOk(device->CreateTexture2D(&texture,nullptr,&bridge[j][i]),"InteropBridgeTexture")||!cudaOk(createArray(&arrays[j][i],&d),"InteropCreateArray")||!cudaOk(dxRegister(&graphics[j][i],bridge[j][i].Get(),0),"InteropRegisterTexture"))return false;
- }
- r.pArrResource[i]=arrays[j][i];
- }
- if(!checkedCall("Register",reg,handles[j],&r))return false;
- registered[j]=true;
- if(!cudaOk(setContext(scope.saved),"RestoreAfterCreate"))return false;
- }
- return true;
- }
-};
-bool WorkerKernel::initialize(FrucWorkerMessage& info) {
- auto& p=*this;const auto w=info.width,h=info.height;p.width=w;p.height=h;p.count=info.multiplier-1;
- const std::wstring path=(runtime::localRuntimeDirectory()/L"NvOFFRUC.dll").make_preferred().wstring();FileIdentity identity;IdentityError error;
- if(!computeFileIdentity(path,identity,error)||!identity.signatureValid||!identity.signerIsNvidia||identity.sha256Upper!="5A0B6701D30709E25E7E5B92CA46B18AAB1459160CECD4F629872369D85C8B0A"){log::error("fruc","local runtime identity mismatch or unavailable");return false;}
- log::info("fruc",std::format("runtime sha256={} extent={}x{} instances={}",identity.sha256Upper,w,h,p.count));
- p.lib=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);if(!p.lib){log::error("fruc",std::format("LoadLibrary error={}",GetLastError()));return false;}
- p.create=reinterpret_cast<PtrToFuncNvOFFRUCCreate>(GetProcAddress(p.lib,CreateProcName));p.destroy=reinterpret_cast<PtrToFuncNvOFFRUCDestroy>(GetProcAddress(p.lib,DestroyProcName));p.reg=reinterpret_cast<PtrToFuncNvOFFRUCRegisterResource>(GetProcAddress(p.lib,RegisterResourceProcName));p.unreg=reinterpret_cast<PtrToFuncNvOFFRUCUnregisterResource>(GetProcAddress(p.lib,UnregisterResourceProcName));p.process=reinterpret_cast<PtrToFuncNvOFFRUCProcess>(GetProcAddress(p.lib,ProcessProcName));if(!p.create||!p.destroy||!p.reg||!p.unreg||!p.process)return false;
- wchar_t systemDir[MAX_PATH]{};if(!GetSystemDirectoryW(systemDir,MAX_PATH))return false;
- const auto cudaPath=std::filesystem::path(systemDir)/L"nvcuda.dll";
- p.cuda=LoadLibraryExW(cudaPath.c_str(),nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32);if(!p.cuda)return false;
- p.getContext=reinterpret_cast<WorkerKernel::GetContext>(GetProcAddress(p.cuda,"cuCtxGetCurrent"));
- p.setContext=reinterpret_cast<WorkerKernel::SetContext>(GetProcAddress(p.cuda,"cuCtxSetCurrent"));if(!p.getContext||!p.setContext)return false;
- using InitCuda=CUresult(CUDAAPI*)(unsigned);auto initCuda=reinterpret_cast<InitCuda>(GetProcAddress(p.cuda,"cuInit"));if(!initCuda||!cudaOk(initCuda(0),"InitCuda"))return false;
- ComPtr<IDXGIFactory4> factory;ComPtr<IDXGIAdapter> adapter;if(!hrOk(CreateDXGIFactory1(IID_PPV_ARGS(&factory)),"Factory")||!hrOk(factory->EnumAdapterByLuid(info.adapter,IID_PPV_ARGS(&adapter)),"SameAdapter"))return false;
- if(!hrOk(D3D11CreateDevice(adapter.Get(),D3D_DRIVER_TYPE_UNKNOWN,nullptr,0,nullptr,0,D3D11_SDK_VERSION,&p.device,nullptr,&p.context),"D3D11Device")||!hrOk(p.device.As(&p.device5),"Device5"))return false;
-
- if(!hrOk(device5->OpenSharedFence(reinterpret_cast<HANDLE>(info.fence),IID_PPV_ARGS(&fence11)),"OpenFence"))return false;
- for(unsigned j=0;j<count+2;++j)
- if(!hrOk(device5->OpenSharedResource1(reinterpret_cast<HANDLE>(info.textures[j]),IID_PPV_ARGS(&tex[j])),"OpenTexture"))return false;
- {
- const auto getDevice=reinterpret_cast<DxDevice>(GetProcAddress(cuda,"cuD3D11GetDevice"));
- dxRegister=reinterpret_cast<DxRegister>(GetProcAddress(cuda,"cuGraphicsD3D11RegisterResource"));
- createContext=reinterpret_cast<decltype(createContext)>(GetProcAddress(cuda,"cuCtxCreate_v2"));
- destroyContext=reinterpret_cast<decltype(destroyContext)>(GetProcAddress(cuda,"cuCtxDestroy_v2"));
- createArray=reinterpret_cast<decltype(createArray)>(GetProcAddress(cuda,"cuArrayCreate_v2"));
- destroyArray=reinterpret_cast<decltype(destroyArray)>(GetProcAddress(cuda,"cuArrayDestroy"));
- mapResources=reinterpret_cast<decltype(mapResources)>(GetProcAddress(cuda,"cuGraphicsMapResources"));
- unmapResources=reinterpret_cast<decltype(unmapResources)>(GetProcAddress(cuda,"cuGraphicsUnmapResources"));
- unregisterGraphics=reinterpret_cast<decltype(unregisterGraphics)>(GetProcAddress(cuda,"cuGraphicsUnregisterResource"));
- mappedArray=reinterpret_cast<decltype(mappedArray)>(GetProcAddress(cuda,"cuGraphicsSubResourceGetMappedArray"));
- copyAsync=reinterpret_cast<decltype(copyAsync)>(GetProcAddress(cuda,"cuMemcpy2DAsync_v2"));
- if(!getDevice||!dxRegister||!createContext||!destroyContext||!createArray||!destroyArray||!mapResources||!unmapResources||!unregisterGraphics||!mappedArray||!copyAsync||!cudaOk(getDevice(&cudaDevice,adapter.Get()),"InteropSameAdapter")||!hrOk(context.As(&context4),"InteropContext4"))return false;
- }
- return createStreams();
-}
-bool WorkerKernel::execute(FrucWorkerMessage& info) {
- ContextScope scope(*this);if(!scope.valid)return false;
- auto wait=info.inputFence;
- if(!hrOk(context4->Wait(fence11.Get(),wait),"InteropInputWait",true))return false;
- if(!cudaOk(setContext(ownedContext[0]),"ProcessContext"))return false;
- CUgraphicsResource mapped[6]{};
- for(unsigned j=0;j<count;++j){mapped[j*2]=graphics[j][info.parity];mapped[j*2+1]=graphics[j][2];context->CopyResource(bridge[j][info.parity].Get(),tex[info.parity].Get());}
- context->Flush();
- struct MappingScope {
- WorkerKernel& owner;CUgraphicsResource* resources;unsigned count;bool active=false;
- ~MappingScope(){if(active)cudaOk(owner.unmapResources(count,resources,nullptr),"InteropErrorUnmap");}
- }mapping{*this,mapped,count*2};
- if(!cudaOk(mapResources(count*2,mapped,nullptr),"InteropMap"))return false;
- mapping.active=true;
- for(unsigned j=0;j<count;++j) {
- NvOFFRUC_PROCESS_IN_PARAMS in{};NvOFFRUC_PROCESS_OUT_PARAMS out{};
- // FRUC retains the previous CUDA array. Source parity can repeat after
- // admission skips; rotate owned inputs by actual SDK calls instead.
- in.stFrameDataInput.pFrame=arrays[j][inputSlot];in.stFrameDataInput.nTimeStamp=info.currentMs;
- in.bSkipWarp=reseed;
- out.stFrameDataOutput.pFrame=arrays[j][2];
- out.stFrameDataOutput.nTimeStamp=info.previousMs+(info.currentMs-info.previousMs)*double(j+1)/(count+1);
- out.stFrameDataOutput.bHasFrameRepetitionOccurred=&info.repeated[j];
- ++wait;
- {
- CUarray input=nullptr;if(!cudaOk(mappedArray(&input,mapped[j*2],0,0),"InteropInputArray"))return false;
- CUDA_MEMCPY2D copy{};copy.srcMemoryType=CU_MEMORYTYPE_ARRAY;copy.srcArray=input;copy.dstMemoryType=CU_MEMORYTYPE_ARRAY;copy.dstArray=arrays[j][inputSlot];copy.WidthInBytes=size_t(width)*4;copy.Height=height;
- if(!cudaOk(copyAsync(&copy,nullptr),"InteropInputCopy"))return false;
- }
- unsigned seh=0;auto result=callSafe(seh,process,handles[j],&in,&out);
- info.result=uint32_t(result);info.seh=seh;
- if(result!=NvOFFRUC_SUCCESS||seh||log::verboseFrameLogs())log::info("fruc",std::format("Process inputMs={} outputMs={} sub={} result={} seh={} repeated={}",info.currentMs,out.stFrameDataOutput.nTimeStamp,j+1,int(result),seh,info.repeated[j]));
- if(result!=NvOFFRUC_SUCCESS||seh)return false;
- {
- CUarray output=nullptr;if(!cudaOk(mappedArray(&output,mapped[j*2+1],0,0),"InteropOutputArray"))return false;
- CUDA_MEMCPY2D copy{};copy.srcMemoryType=CU_MEMORYTYPE_ARRAY;copy.srcArray=arrays[j][2];copy.dstMemoryType=CU_MEMORYTYPE_ARRAY;copy.dstArray=output;copy.WidthInBytes=size_t(width)*4;copy.Height=height;
- if(!cudaOk(copyAsync(&copy,nullptr),"InteropOutputCopy"))return false;
- }
- }
- if(!cudaOk(unmapResources(count*2,mapped,nullptr),"InteropUnmap"))return false;
- mapping.active=false;
- for(unsigned j=0;j<count;++j)context->CopyResource(tex[j+2].Get(),bridge[j][2].Get());
- if(!hrOk(context4->Signal(fence11.Get(),wait),"InteropOutputSignal",true))return false;context->Flush();
- inputSlot^=1;reseed=false;info.outputFence=wait;return true;
-}
-} // namespace veyra::ngx
-int wmain(int argc,wchar_t** argv) {
- using namespace veyra;using namespace veyra::ngx;
- if(argc!=2)return 2;
- auto mapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[1],nullptr,10));
- auto* info=static_cast<FrucWorkerMessage*>(MapViewOfFile(mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(FrucWorkerMessage)));
- if(!info||info->version!=1||info->multiplier<2||info->multiplier>4||!info->width||!info->height)return 2;
- Logger::instance().setConsoleEnabled(false);
- if(!Logger::instance().openFile(info->logPath))return 2;
- const auto response=reinterpret_cast<HANDLE>(info->response),request=reinterpret_cast<HANDLE>(info->request);
- int exitCode=0;
- {
- WorkerKernel kernel;
- bool ready=kernel.initialize(*info);info->result=ready?0:1;
- if(!SetEvent(response))return 2;
- if(ready)for(;;) {
- if(WaitForSingleObject(request,INFINITE)!=WAIT_OBJECT_0){exitCode=2;break;}
- if(info->command==2)break;
- if(info->command==3){kernel.reseed=true;info->result=0;info->seh=0;if(!SetEvent(response)){exitCode=2;break;}continue;}
- if(info->command!=1||info->parity>1){exitCode=2;break;}
- info->result=1;info->seh=0;
- const bool ok=kernel.execute(*info);
- if(!ok&&info->result==0)info->result=1;
- if(!SetEvent(response)){exitCode=2;break;}
- if(!ok){exitCode=1;break;}
- }
- else exitCode=1;
- }
- Logger::instance().flush();UnmapViewOfFile(info);CloseHandle(mapping);return exitCode;
-}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index e2a3d1b6..55c9e1a2 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -665,6 +665,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
if(std::abs(ptsMs)>9e13){veyra::log::error("timeline","PTS outside representable range");return false;}
if(prevValid_&&(std::llround(ptsMs*10000)-std::llround(prevPtsMs_*10000)<4||ptsMs-prevPtsMs_>1000)){
+ out.detectedReset=ResetReason::PtsDiscontinuity;
reset=true;veyra::log::info("timeline","non-monotonic or discontinuous PTS; atomic history reset");
}
if (reset) { prevValid_ = false; scene_.reset(); previousLuma_.clear();cadence_.reset(); }
@@ -704,6 +705,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
out.contentDuplicate=desc_.contentRate!=engine::ContentRate::Transport&&previousLuma_.size()==sample.size()&&sad<0.0001;
const auto analysis=scene_.analyze(realFrameIndex_,hist,sad,static_cast<uint64_t>(std::max(0.0,ptsMs)*1000));
if(analysis.isSceneCut||analysis.isCadenceBreak){
+ if(out.detectedReset==ResetReason::None)out.detectedReset=analysis.isSceneCut?ResetReason::SceneCut:ResetReason::CadenceBreak;
reset=true;prevValid_=false;if(analysis.isSceneCut)++metrics_.sceneCutCount;
veyra::log::info("scene",std::format("history boundary frame={} ptsMs={} cutCandidate={} cadenceBreak={} sad={} histogramDistance={}",
realFrameIndex_,ptsMs,analysis.isSceneCut,analysis.isCadenceBreak,analysis.sadScore,analysis.histogramDistance));
@@ -1200,7 +1202,8 @@ bool EnhanceGraph::resolveGeneration(FrameOutputs& out)
void* data=nullptr;D3D12_RANGE range{0,4};
HRESULT hr=fgDisableReadback_[frame.lease->slot]->Map(0,&range,&data);
if(FAILED(hr)){frame.validity=GenerationValidity::Failed;out.hasGenerated=false;veyra::log::error("fg-status",std::format("Map hr=0x{:X}",unsigned(hr)));return true;}
- const bool rejected=*static_cast<uint8_t*>(data)||out.contentDuplicate;
+ const bool disabled=*static_cast<uint8_t*>(data)!=0;
+ const bool rejected=disabled||out.contentDuplicate;
D3D12_RANGE written{0,0};fgDisableReadback_[frame.lease->slot]->Unmap(0,&written);
frame.validity=rejected?GenerationValidity::Disabled:GenerationValidity::Valid;
anyValid|=!rejected;if(rejected)++metrics_.fgDisabledFrames;else ++metrics_.fgGeneratedFrames;
diff --git a/tests/integration/FgAdmissionTests.cpp b/tests/integration/FgAdmissionTests.cpp
index 577c9ced..397657a8 100644
--- a/tests/integration/FgAdmissionTests.cpp
+++ b/tests/integration/FgAdmissionTests.cpp
@@ -13,7 +13,7 @@
int wmain(int argc,wchar_t** argv){
using namespace veyra;
if(argc!=5)return 2;
- const bool fruc=std::wstring(argv[1])==L"fruc";const unsigned multiplier=unsigned(std::stoi(argv[2]));
+ if(std::wstring(argv[1])!=L"dlss")return 2;const unsigned multiplier=unsigned(std::stoi(argv[2]));
if(multiplier<2||multiplier>4)return 2;
std::filesystem::create_directories(argv[4]);Logger::instance().openFile((std::filesystem::path(argv[4])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
@@ -26,7 +26,7 @@ int wmain(int argc,wchar_t** argv){
pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc desc;
desc.sourceWidth=desc.workWidth=source.info().width;desc.sourceHeight=desc.workHeight=source.info().height;
desc.enableNr=true;desc.enableFg=true;desc.fgMultiplier=multiplier;
- desc.frameGenerationBackend=fruc?engine::FrameGenerationBackend::Fruc:engine::FrameGenerationBackend::Dlss;
+ desc.frameGenerationBackend=engine::FrameGenerationBackend::Dlss;
desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
ok=ok&&graph.initialize(desc)&&graph.createViews();
unsigned skipped=0,evaluated=0,recoveries=0,generated=0,real=0;
@@ -62,6 +62,6 @@ int wmain(int argc,wchar_t** argv){
ring.drainQueue();graph.shutdown();source.close();
unsigned errors=0;if(info)for(UINT64 i=0;i<info->GetNumStoredMessagesAllowedByRetrievalFilter();++i){SIZE_T size=0;info->GetMessage(i,nullptr,&size);std::vector<uint8_t> data(size);auto* m=reinterpret_cast<D3D12_MESSAGE*>(data.data());if(SUCCEEDED(info->GetMessage(i,m,&size))&&m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;log::error("debug",m->pDescription);}}
ok=ok&&errors==0;
- std::cout<<"FG_ADMISSION backend="<<(fruc?"FRUC":"DLSS")<<" multiplier="<<multiplier<<" real="<<real<<" NR="<<nr<<" skipped="<<skipped<<" evaluated="<<evaluated<<" recoveries="<<recoveries<<" valid="<<generated<<" debugErrors="<<errors<<" pass="<<ok<<std::endl;
+ std::cout<<"FG_ADMISSION backend="<<"DLSS"<<" multiplier="<<multiplier<<" real="<<real<<" NR="<<nr<<" skipped="<<skipped<<" evaluated="<<evaluated<<" recoveries="<<recoveries<<" valid="<<generated<<" debugErrors="<<errors<<" pass="<<ok<<std::endl;
info.Reset();ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;
}
diff --git a/tests/integration/FrucTests.cpp b/tests/integration/FrucTests.cpp
deleted file mode 100644
index 9fd834ae..00000000
--- a/tests/integration/FrucTests.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-// Diagnostic pixel readback only. Known 8-pixel pan provides exact fractional GT.
-#include "veyra/pipeline/EnhanceGraph.h"
-#include "veyra/gfx/D3D12DeviceContext.h"
-#include "veyra/gfx/CommandSlotRing.h"
-#include "veyra/sink/ImageExportSink.h"
-#include <filesystem>
-#include <fstream>
-#include <iostream>
-#include <cmath>
-#include <string_view>
-#include <chrono>
-#include <deque>
-#include <thread>
-extern "C" {
-#include <libavutil/frame.h>
-#include <libavutil/pixfmt.h>
-}
-int main(int argc,char** argv){using namespace veyra;if(argc<3)return 2;const unsigned mult=unsigned(std::stoi(argv[1]));if(mult<2||mult>4)return 2;
- const bool throughput=argc>3&&(std::string_view(argv[3])=="--throughput"||std::string_view(argv[3])=="--4k-throughput");
- const unsigned W=argc>3&&std::string_view(argv[3])=="--4k-throughput"?3840:1920,H=W*9/16;
- std::vector<unsigned char> base(1920*1080);std::ifstream input(argv[2],std::ios::binary);if(!input.read(reinterpret_cast<char*>(base.data()),base.size()))return 2;
- CoInitializeEx(nullptr,COINIT_MULTITHREADED);gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;pipeline::EnhanceGraph graph(ctx,ring);Status st;
- gfx::DeviceContextDesc deviceDesc{};bool ok=ctx.initialize(deviceDesc,st)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st);
- pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=W;gd.sourceHeight=gd.workHeight=H;gd.rgbInput=true;gd.enableNr=gd.enableSr=false;gd.enableFg=true;gd.fgMultiplier=mult;gd.frameGenerationBackend=engine::FrameGenerationBackend::Fruc;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();if(ok)ok=graph.initialize(gd)&&graph.createViews();
- AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_RGBA;f->width=W;f->height=H;f->color_range=AVCOL_RANGE_JPEG;ok=ok&&av_frame_get_buffer(f,32)>=0;
- auto color=[&](int x,unsigned y,unsigned c){const unsigned v=base[size_t(y%1080)*1920+unsigned(std::clamp(x,0,int(W)-1))%1920];return c==0?v:c==1?v/2+32:255-v;};
- if(throughput){
- using Clock=std::chrono::steady_clock;std::deque<pipeline::EnhanceGraph::FrameOutputs> pending;
- std::vector<double> cpuMs,gpuMs;uint64_t completed=0,generated=0;const auto start=Clock::now();
- auto collect=[&]{
- if(!graph.resolveGeneration(pending.front()))return false;
- for(const auto& sample:pending.front().batch.frames)if(sample.kind==pipeline::FrameKind::Generated&&sample.validity==pipeline::GenerationValidity::Valid)++generated;
- ++completed;pending.pop_front();return true;
- };
- for(unsigned i=0;ok&&i<120;++i){
- while(pending.size()>=2){if(collect())break;if(Clock::now()-start>std::chrono::seconds(60)){ok=false;break;}std::this_thread::sleep_for(std::chrono::milliseconds(1));}
- if(!ok)break;
- for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;for(unsigned c=0;c<3;++c)p[c]=static_cast<unsigned char>(color(int(x)-int(i%30)*8,y,c));p[3]=255;}
- pipeline::EnhanceGraph::FrameOutputs output;const auto begin=Clock::now();
- ok=graph.process(f,i*1000.0/60,i%30==0,output);
- if(!ok)break;
- if(i>8)cpuMs.push_back(std::chrono::duration<double,std::milli>(Clock::now()-begin).count());
- pending.push_back(std::move(output));
- const auto timing=graph.gpuMetrics().gpu[size_t(diagnostics::GpuStage::FgBatch)];if(i>8&&timing.milliseconds)gpuMs.push_back(*timing.milliseconds);
- }
- while(ok&&!pending.empty()){if(!collect()){if(Clock::now()-start>std::chrono::seconds(60)){ok=false;break;}std::this_thread::sleep_for(std::chrono::milliseconds(1));}}
- auto percentile=[](std::vector<double> values,unsigned pct){if(values.empty())return -1.0;std::sort(values.begin(),values.end());return values[(values.size()*pct+99)/100-1];};
- const double elapsed=std::chrono::duration<double>(Clock::now()-start).count();
- ok=ok&&completed==120&&generated>0;
- std::cout<<"FRUC_THROUGHPUT extent="<<W<<'x'<<H<<" multiplier="<<mult<<" completed="<<completed<<" generated="<<generated<<" wallSeconds="<<elapsed<<" sourceFps="<<completed/elapsed<<" processCpuMedianMs="<<percentile(cpuMs,50)<<" processCpuP95Ms="<<percentile(cpuMs,95)<<" observedFgGpuMedianMs="<<percentile(gpuMs,50)<<" pixelReadback=0 pass="<<ok<<std::endl;
- pending.clear();ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;
- }
- unsigned generated=0;double worst=0;for(unsigned i=0;ok&&i<6;++i){for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;for(unsigned c=0;c<3;++c)p[c]=static_cast<unsigned char>(color(int(x)-int(i)*8,y,c));p[3]=255;}
- pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(f,i*1000.0/15,i==0,out)||!ring.waitIdle()||!graph.resolveGeneration(out)){ok=false;break;}
- for(unsigned j=0;j<out.batch.count;++j){auto& item=out.batch.frames[j];if(item.kind!=pipeline::FrameKind::Generated)continue;sink::RgbaImage image;if(!sink::readRgba8(ctx,ring,item.lease->texture.Get(),image)){ok=false;break;}
- double err=0,repeatError=0;size_t samples=0;double shift=(i-1+double(item.subframe)/mult)*8;
- for(unsigned y=32;y<H-32;++y)for(unsigned x=64;x<W-64;++x)for(unsigned c=0;c<3;++c){double pos=x-shift;int left=int(std::floor(pos));double t=pos-left;double expected=color(left,y,c)*(1-t)+color(left+1,y,c)*t;err+=std::abs(image.pixels[(size_t(y)*W+x)*4+c]-expected);repeatError+=std::abs(double(color(int(x)-int(i-1)*8,y,c))-expected);++samples;}
- err/=samples;repeatError/=samples;worst=std::max(worst,err);bool pass=item.validity==pipeline::GenerationValidity::Valid&&err<repeatError&&std::llabs(item.pts100ns-std::llround((i-1+double(item.subframe)/mult)*10000000.0/15))<=1;
- std::cout<<"FRUC_GT frame="<<i<<" sub="<<item.subframe<<" mae="<<err<<" repeatMae="<<repeatError<<" valid="<<pass<<std::endl;ok=ok&&pass;++generated;
- }
- }
- // Explicit discontinuity must reseed, never interpolate across the reset.
- for(unsigned epoch=1;ok&&epoch<=3;++epoch){
- pipeline::EnhanceGraph::FrameOutputs out;
- ok=graph.process(f,epoch*2000.0,true,out)&&ring.waitIdle()&&graph.resolveGeneration(out)&&out.batch.count==1;
- // A second frame after reseeding must run successfully, even for static input.
- if(ok)ok=graph.process(f,epoch*2000.0+1000.0/15,false,out)&&ring.waitIdle()&&graph.resolveGeneration(out);
- }
- const bool skipPixels=argc>3&&std::string_view(argv[3])=="--skip-pixels";
- if(skipPixels||(argc>3&&std::string_view(argv[3])=="--reset-pixels")){
- bool pixelsOk=true;
- for(unsigned epoch=1;ok&&epoch<=6;++epoch){const double start=epoch%2?10000+epoch*1000:500;const bool invert=epoch%2!=0;
- for(unsigned i=0;ok&&i<(skipPixels?7u:3u);++i){const int shift=int(epoch)*16+int(i)*8;
- for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;for(unsigned c=0;c<3;++c){const auto v=color(int(x)-shift,y,c);p[c]=static_cast<unsigned char>(invert?255-v:v);}p[3]=255;}
- const bool skip=skipPixels&&(i==1||i==4);
- pipeline::EnhanceGraph::FrameOutputs out;ok=graph.process(f,start+i*1000.0/15,i==0,out,i,nullptr,false,[skip](const pipeline::FrameBatch&){return !skip;})&&ring.waitIdle()&&graph.resolveGeneration(out);
- if(i==0){ok=ok&&out.batch.count==1;continue;}
- if(skip){ok=ok&&out.fgSkippedBeforeEval==mult-1&&out.fgEvaluated==0&&out.batch.count==1;continue;}
- if(skipPixels&&(i==2||i==5)){ok=ok&&out.fgRecovery&&out.batch.count==1;continue;}
- ok=ok&&out.batch.count==mult;
- for(unsigned j=0;ok&&j<out.batch.count;++j){const auto& item=out.batch.frames[j];if(item.kind!=pipeline::FrameKind::Generated)continue;
- sink::RgbaImage image;ok=sink::readRgba8(ctx,ring,item.lease->texture.Get(),image);if(!ok)break;
- double error=0,repeatError=0;size_t samples=0;const double target=shift-8+8.0*item.subframe/mult;
- for(unsigned y=32;y<H-32;++y)for(unsigned x=96;x<W-96;++x)for(unsigned c=0;c<3;++c){const double pos=x-target;const int left=int(std::floor(pos));const double t=pos-left;
- double expected=color(left,y,c)*(1-t)+color(left+1,y,c)*t;double repeated=color(int(x)-shift+8,y,c);if(invert){expected=255-expected;repeated=255-repeated;}
- error+=std::abs(image.pixels[(size_t(y)*W+x)*4+c]-expected);repeatError+=std::abs(repeated-expected);++samples;}
- const bool pass=item.validity==pipeline::GenerationValidity::Valid&&error<repeatError;
- pixelsOk=pixelsOk&&pass;std::cout<<"FRUC_RESET_GT epoch="<<epoch<<" frame="<<i<<" sub="<<item.subframe<<" mae="<<error/samples<<" repeatMae="<<repeatError/samples<<" pass="<<pass<<std::endl;
- if(!pass){
- double best=1e9;int bestOffset=0;
- for(int offset=-24;offset<=24;++offset){double candidate=0;unsigned count=0;
- for(unsigned y=32;y<H-32;y+=8)for(unsigned x=96;x<W-96;x+=8)for(unsigned c=0;c<3;++c){double expected=color(int(x)-shift-offset,y,c);if(invert)expected=255-expected;candidate+=std::abs(image.pixels[(size_t(y)*W+x)*4+c]-expected);++count;}
- candidate/=count;if(candidate<best){best=candidate;bestOffset=offset;}
- }
- std::cout<<"FRUC_RESET_NEAREST epoch="<<epoch<<" frame="<<i<<" offsetFromCurrent="<<bestOffset<<" mae="<<best<<std::endl;
- }
- }
- }
- }
- ok=ok&&pixelsOk;
- }
- ok=ok&&generated==5*(mult-1);std::cout<<"FRUC_RESULT multiplier="<<mult<<" generated="<<generated<<" worstMae="<<worst<<" pass="<<ok<<std::endl;
- ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;
-}
diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cpp
index cdbd1db0..a2d5e28d 100644
--- a/tests/integration/LivePresentationTests.cpp
+++ b/tests/integration/LivePresentationTests.cpp
@@ -9,21 +9,18 @@ using namespace veyra;
using namespace std::chrono_literals;
int wmain(int argc,wchar_t**argv){
SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");
- if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--fruc")==0||wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0||wcscmp(argv[3],L"--fruc-overload")==0||wcscmp(argv[3],L"--fruc-overload-baseline")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0||wcscmp(argv[3],L"--file-endpoint")==0||wcscmp(argv[3],L"--reset-rollback")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0||wcscmp(argv[3],L"--file-endpoint")==0||wcscmp(argv[3],L"--reset-rollback")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);
std::filesystem::create_directories(argv[2]);Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);
HWND window=CreateWindowExW(0,L"STATIC",L"Live scheduler replay",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
if(!window)return 3;engine::EngineController engine;engine::PlayerOptions options;options.nr=false;options.fg=false;options.captureReplayForTest=true;
const bool halfRate=argc==4&&wcscmp(argv[3],L"--half-rate")==0;
const bool sourceGap=argc==4&&wcscmp(argv[3],L"--source-gap")==0;
if(sourceGap){SetEnvironmentVariableW(L"VEYRA_TEST_REPLAY_SOURCE_GAP",L"1");options.nr=options.fg=true;options.fgMultiplier=2;}
- const bool frucOverload=argc==4&&std::wstring(argv[3]).find(L"--fruc-overload")==0;
- const bool overload=frucOverload||(argc==4&&std::wstring(argv[3]).find(L"--overload")==0);
+ const bool overload=(argc==4&&std::wstring(argv[3]).find(L"--overload")==0);
const bool fileOverload=argc==4&&wcscmp(argv[3],L"--file-overload")==0;
const bool fileEndpoint=argc==4&&wcscmp(argv[3],L"--file-endpoint")==0;
if(fileEndpoint){options.captureReplayForTest=false;SetEnvironmentVariableW(L"VEYRA_TEST_FILE_ENDPOINT_LOSS",L"1");engine.setVolume(0,true);}
- if(argc==4&&wcscmp(argv[3],L"--fruc")==0)options.settings.frameGenerationBackend=engine::FrameGenerationBackend::Fruc;
if(overload){options.nr=options.sr=options.fg=true;options.realtime=false;options.fgMultiplier=4;options.settings.videoSrQuality=4;options.captureReplayDisableFgAdmissionForTest=std::wstring(argv[3]).ends_with(L"-baseline");SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",nullptr);}
- if(frucOverload)options.settings.frameGenerationBackend=engine::FrameGenerationBackend::Fruc;
if(halfRate)options.settings.content=engine::ContentRate::Capture60To30;
if(fileOverload){options.captureReplayForTest=false;options.nr=options.sr=options.fg=true;options.realtime=false;options.fgMultiplier=4;options.settings.videoSrQuality=4;}
int failures=0;auto check=[&](bool pass,const char* s){std::cout<<(pass?"PASS ":"FAIL ")<<s<<std::endl;if(!pass)++failures;};
@@ -155,5 +152,10 @@ int wmain(int argc,wchar_t**argv){
}
check(liveFresh,"running capture settings process fresh source frame, never cached frame");
check(pausedCached,"paused settings retain cached-frame preview");
+ const auto report=Logger::instance().diagnosticReport();
+ check(report.find("event=Submitted")!=std::string::npos&&report.find("event=Ready")!=std::string::npos&&
+ report.find("event=Present")!=std::string::npos&&report.find("event=Gpu")!=std::string::npos&&report.find("event=Reset")!=std::string::npos,
+ "diagnostic preview contains real engine submission, completion, presentation, GPU and reset records");
+ {std::ofstream trace(std::filesystem::path(argv[2])/"diagnostics.txt");trace<<report;}
DestroyWindow(window);CoUninitialize();std::cout<<"failures="<<failures<<" (synthetic file replay, not physical capture)\n";return failures?1:0;
}
diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cpp
index cba37983..ad3fbc68 100644
--- a/tests/unit/RepairContractTests.cpp
+++ b/tests/unit/RepairContractTests.cpp
@@ -1,6 +1,7 @@
#include "veyra/engine/EnhancementSettings.h"
#include "veyra/diagnostics/DiagnosticEvent.h"
#include "veyra/diagnostics/FrameMetrics.h"
+#include "veyra/diagnostics/ResetCause.h"
#include "veyra/engine/PresentationScheduler.h"
#include "veyra/engine/LiveFgAdmission.h"
#include "veyra/engine/FrameFlowWindow.h"
@@ -62,7 +63,7 @@ int main(){
check(!lineage.observe(skipped,2100000,true,false),"missing A identity is unknown rather than extrapolated");
check(!lineage.observe(skipped,2400000,true,true),"cached preview cannot seed latency lineage");
check(!pairFlow.snapshot(13000000).pairTiming[size_t(diagnostics::PairTiming::GeneratedFromA)].mean,"generated latency expires when no new frames are presented");
- check(engine::frameGenerationBackendName(engine::FrameGenerationBackend::Dlss)=="DLSS"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::Fruc)=="FRUC"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::XeSS)=="XeSS","frame-generation backend names identify every backend");
+ check(engine::frameGenerationBackendName(engine::FrameGenerationBackend::Dlss)=="DLSS"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::XeSS)=="XeSS","frame-generation backend names identify every backend");
check(engine::opticalFlowBackendName(engine::OpticalFlowBackend::Nvidia)=="NVIDIA_NVOF"&&engine::opticalFlowBackendName(engine::OpticalFlowBackend::AmdFidelityFx)=="AMD_FIDELITYFX_OF","optical-flow backend names identify every backend");
s.model.intensity=std::numeric_limits<float>::quiet_NaN();check(!s.validate().empty(),"reject NaN transaction");
s={};s.multiplier=5;check(!s.validate().empty(),"reject unsupported multiplier");
@@ -144,11 +145,29 @@ int main(){
engine::CfrTimeline ticks(60,1,1.0/60,0);bool exactTicks=true;for(unsigned i=0;i<120;++i)exactTicks &= ticks.accepts(i,i/60.0);check(exactTicks&&!ticks.accepts(120,121.0/60),"one-tick CFR accepted but missing frame rejected");
std::vector<double> mkv;for(unsigned i=0;i<24;++i)mkv.push_back(std::round(i*1000.0/60)/1000);
check(engine::CfrTimeline::select(29990,499,.001,mkv)==std::pair<int,int>{60,1},"misdeclared MKV rate selects consistent standard CFR candidate");
+ using Reason=pipeline::ResetReason;
+ check(diagnostics::resetCause(0,Reason::PauseResume,Reason::SceneCut)==Reason::PauseResume&&
+ diagnostics::resetCause(0,Reason::Seek,Reason::None)==Reason::Seek&&
+ diagnostics::resetCause(0,Reason::Settings,Reason::None)==Reason::Settings,"explicit transport/settings reset causes are not invented scene cuts");
+ check(diagnostics::resetCause(unsigned(pipeline::FrameFlagBits::Discontinuity),Reason::None,Reason::None)==Reason::PtsDiscontinuity&&
+ diagnostics::resetCause(0,Reason::None,Reason::CadenceBreak)==Reason::CadenceBreak&&
+ diagnostics::resetCause(0,Reason::None,Reason::None)==Reason::None,"PTS/cadence and unknown reset causes remain distinct");
+ check(diagnostics::resetCause(unsigned(pipeline::FrameFlagBits::DeviceLost),Reason::Seek,Reason::None)==Reason::DeviceLost&&
+ diagnostics::resetCause(unsigned(pipeline::FrameFlagBits::Drop),Reason::None,Reason::SceneCut)==Reason::FrameDrop,"device loss and source drops retain explicit causes");
+ auto trace=std::make_unique<diagnostics::FrameTrace>();
+ for(unsigned i=0;i<diagnostics::FrameTrace::capacity+5;++i)
+ trace->add({int64_t(i),7,{i/100,9,i},i,2*i,int64_t(i)*100,diagnostics::TraceKind::Submitted,0,1,.25});
+ const auto traceCopy=trace->snapshot();
+ check(traceCopy.size()==8192&&trace->overwritten()==5&&traceCopy.front().identity.sourceFrameId==5&&traceCopy.back().identity.sourceFrameId==8196,"trace ring preserves chronological tail and reports overwritten events");
+ trace->add({});check(traceCopy.front().session==7&&traceCopy.back().batch==8196,"diagnostic trace snapshot is independent of later writes");
+ Logger::instance().recordFrame({12345,7,{3,9,55},6,8,100,diagnostics::TraceKind::Ready,0,2,.25});
Logger::instance().setConsoleEnabled(false);
log::error("nvof-session","test-only nvOFInit failed status=5");
log::error("nvof-session","test-only caps failed st=7");
log::error("ngx","test-only fg-backend failed result=0xBAD00005 seh=0xC0000005");
const auto report=Logger::instance().diagnosticReport();
+ check(report.find("event=Ready host=12345 session=7 revision=9 epoch=3 source=55 batch=6 fence=8")!=std::string::npos,
+ "existing diagnostic preview exports frame identity and actual completion events");
check(report.find("NVOF=0x5")!=std::string::npos&&report.find("NVOF=0x7")!=std::string::npos&&report.find("NGX=0xBAD00005")!=std::string::npos&&report.find("SEH=0xC0000005")!=std::string::npos,"diagnostic report retains NVOF aliases and NGX/SEH codes (synthetic errors)");
std::cout<<checks<<" checks "<<failures<<" failures\n";return failures?1:0;
}
diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cpp
index b9ee6232..865eb52f 100644
--- a/tests/unit/RepairPresetTests.cpp
+++ b/tests/unit/RepairPresetTests.cpp
@@ -1,7 +1,48 @@
#include "veyra/engine/PresetStore.h"
#include <iostream>
#include <fstream>
-int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engine;const std::filesystem::path p=argv[1];PresetStore a(p);bool ok=a.load();EnhancementSettings s;s.videoSrQuality=2;s.frameGenerationBackend=FrameGenerationBackend::Fruc;s.opticalFlowBackend=OpticalFlowBackend::AmdFidelityFx;s.amdFlowHalfResolution=true;s.protection.enabled=true;s.protection.featherPixels=3.5f;s.protection.regions[0]={.1f,.2f,.7f,.8f};s.protection.regions[3]={0,0,1,1};s.model.intensity=.375f;s.model.skin=1.5f;s.residual.darken=1.2f;s.multiplier=4;s.flow=FlowQuality::Quality;s.content=ContentRate::Fps50;s.nrPolicy=veyra::pipeline::NrSizePolicy::Native;
+#include <sstream>
+namespace {
+bool legacyBackends(const std::filesystem::path& path) {
+ using namespace veyra::engine;
+ unsigned checks=0;
+ for(int version=4;version<=8;++version)for(int backend=0;backend<=2;++backend)for(int multiplier:{2,4}){
+ std::ostringstream fixture;
+ fixture<<"VEYRA_PRESETS "<<version<<"\n\"legacy\" 1\n\"legacy\" 1 1 1 -1 0 0 0 1 1 1 1 1 1 0 "<<multiplier<<" 0 1 0";
+ fixture<<" 0 0";
+ for(int region=0;region<4;++region)fixture<<" 0 0 0 0";
+ fixture<<" 2 "<<backend;
+ if(version>=5)fixture<<" 1";
+ if(version>=6)fixture<<" 0 0";
+ if(version>=7)fixture<<" 1 137";
+ fixture<<'\n';
+ {std::ofstream file(path);file<<fixture.str();}
+ const bool xess=version<8?backend==2:backend==1;
+ const bool supportedValue=backend<2||(version>=6&&version<=7);
+ const bool expected=supportedValue&&(!xess||multiplier==2);
+ PresetStore store(path);
+ if(store.load()!=expected)return false;
+ if(expected){
+ const auto value=store.defaultSettings();
+ if(value.frameGenerationBackend!=(xess?FrameGenerationBackend::XeSS:FrameGenerationBackend::Dlss)||value.multiplier!=multiplier||value.videoSrQuality!=2)return false;
+ if(version>=7&&(value.audioSync!=AudioSyncMode::Manual||value.audioOffsetMs!=137))return false;
+ if(!store.put(L"legacy",value,true))return false;
+ std::ifstream file(path);std::string magic;int savedVersion=0;file>>magic>>savedVersion;
+ if(magic!="VEYRA_PRESETS"||savedVersion!=8)return false;
+ PresetStore reloaded(path);
+ if(!reloaded.load()||reloaded.defaultSettings()!=value)return false;
+ }else{
+ if(store.put(L"must not overwrite",{}))return false;
+ std::ifstream file(path);std::string unchanged((std::istreambuf_iterator<char>(file)),{});
+ if(unchanged!=fixture.str())return false;
+ }
+ ++checks;
+ }
+ std::cout<<"legacy/current backend migration cases="<<checks<<'\n';
+ return true;
+}
+}
+int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engine;const std::filesystem::path p=argv[1];PresetStore a(p);bool ok=a.load();EnhancementSettings s;s.videoSrQuality=2;s.frameGenerationBackend=FrameGenerationBackend::Dlss;s.opticalFlowBackend=OpticalFlowBackend::AmdFidelityFx;s.amdFlowHalfResolution=true;s.protection.enabled=true;s.protection.featherPixels=3.5f;s.protection.regions[0]={.1f,.2f,.7f,.8f};s.protection.regions[3]={0,0,1,1};s.model.intensity=.375f;s.model.skin=1.5f;s.residual.darken=1.2f;s.multiplier=4;s.flow=FlowQuality::Quality;s.content=ContentRate::Fps50;s.nrPolicy=veyra::pipeline::NrSizePolicy::Native;
s.srTarget=veyra::pipeline::SrTarget::Uhd8K;
s.audioSync=AudioSyncMode::Manual;s.audioOffsetMs=137;
ok=ok&&a.put(L"test",s)&&a.setDefault(0)&&!a.put(L"test",s);PresetStore b(p);ok=ok&&b.load()&&b.defaultSettings()==s&&b.rename(0,L"renamed")&&b.defaultSettings()==s;
@@ -18,4 +59,5 @@ int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engine
PresetStore old(p);ok=ok&&old.load()&&!old.defaultSettings().protection.enabled&&old.defaultSettings().srTarget==veyra::pipeline::SrTarget::Uhd4K&&old.put(L"v2",s);
PresetStore upgraded(p);ok=ok&&upgraded.load()&&upgraded.entries().size()==2&&upgraded.entries()[1].settings==s;
{std::ofstream f(p);f<<"VEYRA_PRESETS 99\ncorrupt mediaPath executable must reject";}PresetStore c(p);ok=ok&&!c.load()&&!c.put(L"override",{});std::ifstream f(p);std::string data((std::istreambuf_iterator<char>(f)),{});ok=ok&&data=="VEYRA_PRESETS 99\ncorrupt mediaPath executable must reject";
+ f.close();ok=legacyBackends(p)&&ok;
std::cout<<"preset roundtrip, all fields, duplicate, rename-default, delete, validation, unknown schema, corrupt-preservation="<<ok<<'\n';return ok?0:1;}