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++
Add opt-in HDR frame generation presentation compatibility setting
Veyra Goal Agentf6a8fa270773
diff --git a/AGENTS.md b/AGENTS.mdindex 6058cdb6..878bd3df 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-09 HDR 补帧开关与 main 整合授权**:用户先要求将目前修复合入 main,再明确 HDR 补帧兼容必须改为设置页开关、默认关闭。按 docs/HDR_FG_COMPAT_TOGGLE_PLAN_2026-10-09.md 在当前 FG 隔离工作树修改必要呈现设置/bridge/QML/翻译及定向验收,覆盖这些接点的历史冻结。通过后允许本地 commit/checkpoint/main 合并 BMD、HDR 开关和对应诊断脚本/记录;不 push/Release/更新版本/关机,不派 Agent、不造压、不改运行库/模型/驱动/用户配置。39 工作树、495 脏文件按 archives/hdr-fg-toggle-20261009/start.json 保护,旧 guard/start 不改,产物全 E 盘;测试≤300秒、构建≤900秒。HDR 现场根因、5090 复测及 BMD 实卡/延迟仍未确认,不把兼容候选或开关测试冒充根治。+> **2026-10-09 补帧闪黑现场续修**:用户提交诊断ZIP与日志44,反馈诊断不闪、原版闪,授权排查修复并收尾关机。按docs/FG_FLASH_FIX_PLAN_2026-10-09.md,从main dbfceab在E盘codex/fg-flash-fix-20261009隔离实现NVIDIA HDR应用FG最终合成GPU复制候选与定向测试/本地可回退包;这些具体presenter/ABI重编译接点覆盖历史冻结。诊断增加GPU拷贝、改名EXE/私有配置/关QML缓存,不能当根因证明;本机5070未复现5090闪黑,候选现场效果未验,禁止宣称根治。先执行fg-flash-fix-control.py,独立不可变pre-document-state保护37工作树/495脏文件,不改旧guard。不派Agent/竞争压力,不改驱动、DLL/模型、用户配置或其它工作树;无新main合并/push/Release。正常链路不加像素回读/CPU逐帧等待。测试≤300秒、构建≤900秒、产物全E盘;源码、候选、回执保存核对后按用户要求关机,不强制丢弃未保存内容。> **2026-10-08 桌面项目清理追加授权**:用户要求“桌面这个也清一清”,仅处理桌面 Veyra 项目的忽略产物。按 docs/DESKTOP_STORAGE_CLEANUP_2026-10-08.md,历史 logs lossless 去重归档 E 盘后移除桌面副本,8 套旧 CMake 构建保留 EXE/配置/源码片段后清缓存,旧 1.2.0 解压副本与原 ZIP/额外日志归档核对后移除;35 工作树、495 脏文件及 66,680 个保留文件哈希通过。保留 out/remoteplay 当前依赖、out 内工作树、SDK/runtime/素材及 .git,不涉及桌面其它文件。不改历史 guard/start,不改产品、不 push/Release/关机;C 回收与 E 归档成本分别报告。diff --git a/docs/FG_FLASH_FIX_REPORT_2026-10-09.md b/docs/FG_FLASH_FIX_REPORT_2026-10-09.mdindex ca376026..289b6355 100644--- a/docs/FG_FLASH_FIX_REPORT_2026-10-09.md+++ b/docs/FG_FLASH_FIX_REPORT_2026-10-09.md@@ -1,5 +1,7 @@# HDR 补帧闪黑排查与可回退候选+> 后续用户要求:兼容路径改为“设置 → 兼容 → HDR 补帧闪黑兼容”,默认关闭并保存选择。以下“自动范围”描述是 ce50d18 初版历史;当前行为以 docs/HDR_FG_COMPAT_TOGGLE_PLAN_2026-10-09.md 及对应开关验收为准。现场根因/5090 结果依然未确认。+交付状态:已构建、定向回归通过的 NVIDIA HDR 呈现兼容候选。**没有在本机 RTX5070 复现现场闪黑,也没有取得本候选在用户 RTX5090/采集卡上的反馈;根因尚未确认,不能写“已根治”。** 代码保留在 `codex/fg-flash-fix-20261009`,未合 main、未推送或发布。## 现场证据diff --git a/docs/HDR_FG_COMPAT_TOGGLE_PLAN_2026-10-09.md b/docs/HDR_FG_COMPAT_TOGGLE_PLAN_2026-10-09.mdnew file mode 100644index 00000000..cb628fee--- /dev/null+++ b/docs/HDR_FG_COMPAT_TOGGLE_PLAN_2026-10-09.md@@ -0,0 +1,21 @@+# HDR 补帧兼容开关与本地 main 整合++用户在授权“先把目前修复合并到 main”后,要求先解释 HDR 补帧闪黑原因、修复和代价,随后明确“把这个弄成一个开关吧,弄到设置页里,默认关闭”。根因仍未确认;本轮把 ce50d18 的兼容候选改为明确选择启用,再执行既有本地合并授权,不发布、不推送、不关机。++## 实施范围++- 沿用 `codex/fg-flash-fix-20261009` / E 盘工作树;仅改 PresentationSettings、VideoPresenter、QmlPlayerBridge、SettingsPage、翻译及直接测试/验收文档。其它算法、源时间戳、音频、补帧倍率、运行库和驱动保持。+- 设置 → 兼容增加“HDR 补帧闪黑兼容”,全局偏好保存,首次和缺字段旧配置均为 false。不进入画质预设、节点配置或导出设置。+- 默认使用原直接呈现,且不分配合成纹理;仅用户开启且为 NVIDIA HDR10 应用补帧才使用兼容复制。SDR、非 NVIDIA、关闭补帧和 XeSS 保留原路径。+- 使用既有 presentation revision 将选择送到渲染线程。仅切换时排空呈现队列后创建/释放单张合成纹理;逐帧没有新增 CPU 等待或像素回读。切换可能短暂停顿;分配/排空失败有日志并保留有效路径,不伪报生效。+- 保留仅诊断使用的环境覆盖入口;正常程序不靠环境变量持久化。现场启动脚本的 Compatible/Direct 应修改私有配置中的同一开关,不强迫修改用户原配置。++## 保全、构建与检查++不可变开工基线 `E:/项目/Veyra/archives/hdr-fg-toggle-20261009/start.json` 保护 39 工作树、495 脏文件;增量 `source-before.bundle` 110765 字节,verify 通过。允许本轮 FG 工作树修改与按授权推进 main;其余工作树、原工作区、分支及原包保持。旧 start/guard 不改,不派 Agent、不做压力或竞争 GPU 负载。++构建产物、日志、独立运行配置与脚本分别在 E:/项目/Veyra/{build,logs,tests,tmp,reports}/hdr-fg-toggle-20261009。按头文件依赖重编译受影响生产 objects,复用并逐项校验 71723e0 缓存中未改的依赖,链接同一 GUI 与原生回归。单测试 ≤300 秒、单构建 ≤900 秒。++验收:新配置/旧配置默认关闭、真实设置开关保存/重启恢复、HDR DLSS/VFG 开关热切换与纹理释放、无损 HDR 输出、SDR/无 FG 不误启用、窗口/全屏/resize/close 与 D3D12 错误。正常 GUI 不含像素探针。BMD 实卡黑屏/延迟、5090 现场闪黑及显存增长根因仍未验,不能由本轮开关测试宣称已解决。++通过后保留原提交与来源,合入 BMD 886b461、HDR 候选与本轮开关、两个仅含诊断脚本/记录的分支。合并冲突仅允许合并新增文档段落,不覆盖原工作内容;合并后检查生产差异、编译输入与针对性回归。合并前后打 checkpoint,本地 main 干净为完成条件,Release 及版本号保持。diff --git a/docs/HDR_FG_COMPAT_TOGGLE_REPORT_2026-10-09.md b/docs/HDR_FG_COMPAT_TOGGLE_REPORT_2026-10-09.mdnew file mode 100644index 00000000..0ca4c97b--- /dev/null+++ b/docs/HDR_FG_COMPAT_TOGGLE_REPORT_2026-10-09.md@@ -0,0 +1,28 @@+# HDR 补帧兼容:默认关闭的设置开关++用户要求将 HDR 闪黑兼容候选改为设置页开关、默认关闭。已在“设置 → 兼容”增加“HDR 补帧闪黑兼容”,保存为全局偏好 `hdrFgCompatibility`,新配置和没有该字段的旧配置均关闭。画质预设、节点和导出设置不接管这个选择。++## 行为与代价++默认继续直接呈现,不分配兼容合成纹理。用户开启且输出满足 NVIDIA HDR10 应用侧补帧条件时,才使用单张 GPU 合成纹理 → 交换链复制。非适用输出保留选择,实际路径不启用。使用既有 presentation revision 传递到 GPU 所属线程,允许播放中切换;仅切换时排空呈现队列,关闭后释放该纹理。切换可能短暂停顿,正常逐帧没有新增 CPU 等待、睡眠或像素回读。++4K 兼容纹理实际分配 33,423,360 字节(31.875 MiB),固定复用。开启后每次显示增加 GPU 图像复制与屏障,可能增加带宽、GPU 耗时及满载时的延迟;不保证零开销。分配失败或切换排空失败记录日志,effective 设置反映实际路径,保留有效呈现。没有做真实 OOM/显存压力测试。++随包 Compatible/Direct 启动器改为设置私有配置中的同一个布尔值,移除环境强制;正常设置不依赖环境变量。仅原生回归保留测试覆盖变量。启动器保持原 EXE 名字和用户原配置。++## 本机验证++RTX5070 / 616.56,普通单进程串行负载,无竞争或压力测试。缓存产品为已验 71723e0,未改缓存原件。按 Ninja 实际头依赖重新编译 13 个生产消费者及新的翻译资源,然后链接 GUI;GUI SHA256 `8f69759434fe96036d768755db3d890307321f47f188e33a40ccc9d9bbe43e00`。测试 fixture 单独重编后 native SHA256 `108e827fcace3d9d09c019ffa8dd5c3ca881f9d40a94037dc00a9e9579f3ffd6`,GUI 保持。++- 真实 QML/bridge 五次运行:新配置关闭 → 开启保存 → 重启恢复开启 → 关闭保存 → 重启关闭;旧配置缺字段关闭;其它显示设置不擦除选择、哨兵偏好保留;英文翻译从 EXE 内新资源加载。各进程约 8 秒、exit0,无 QML 错误。测试调用真实组件 toggled 信号,不冒充人工鼠标点击。设置页稳定截图已查看,控件显示正常、默认关闭。+- HDR DLSS 4K 交换链与 HDR VFG 4K 交换链:各 512 原帧 / 620 生成帧、94 次无损 10-bit 窗口对照,最大 RGB 码值误差 0,D3D12 错误 0。包括默认 false、启用、关闭、再次启用;窗口/全屏、resize、reset 与销毁顺序。4K 是输出缓冲验证,测试输入 640×360 P010,不宣称 4K NR 或物理 HDR 显示验收。+- 原 HDR 直接路径对照同样 94 次无损检查误差 0,D3D12 错误 0。SDR 4X/6X/4X 分别生成 114/190/114 帧,误差 0、D3D12 错误 0,默认没有启用复制。+- Windows PowerShell 5.1 实际 Compatible/Direct 入口各 15 秒私有配置测试,结果与原配置保护见 launcher 回执。正常 GUI 没有诊断像素探针。++实际命令:`py -3.11 -B scripts/acceptance/hdr-fg-toggle-build.py`,fixture 更正后仅 `--tests-only`;`hdr-fg-toggle-test.py gui <label> fresh|restore-on|restore-off|legacy|visual`,`native <label> hdr-4k|vfg-4k|sdr|direct`。构建/测试完整 argv、哈希、退出码和成功/失败原日志在 `E:/项目/Veyra/logs/hdr-fg-toggle-20261009`,构建指针在对应 reports/build-current.json。全部新产物在 E 盘;1614 项原便携母包前后逐项 SHA 相同。++## 失败与边界++构建包装脚本初次把 `/implib:` 输出选项当输入库;之后翻译资源的 `.qt/rcc` 路径及 Windows 分隔符识别错误,均在最终链接前中止。修正后构建成功,未写缓存。原生回归新增像素检查落在 800×450 resize 窗口内,错误与 640×360 原图逐位比较而失败;将检查移到恢复相同尺寸后,仅重编测试并通过,产品 GUI 没改。首张 UI 截图拍在入场动画完成前,只能证明组件存在;补取稳定截图确认实际可见布局。没有把这些测试环境错误当现场闪黑原因。++HDR 闪黑根因未确认,用户 RTX5090 尚未回测本兼容候选;不能承诺开启必然解决、所有显卡通过或屏幕延迟不变。NVIDIA 持续显存增长仍未定位。BMD 另一项兼容候选的实卡黑屏和延迟仍需测试。用户已授权本地 main 整合,最终合并提交、组合构建/回归及保全结果见 docs/MERGE_MAIN_2026-10-09.md;未推送或发布新版本。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 906482b1..dee43333 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,12 @@# WORKLOG+## 2026-10-09 HDR 补帧兼容开关(默认关闭)与 main 整合准备++- 用户要求先将目前修复合入 main,解释 HDR 闪黑候选原因/代价后,明确要求设置页开关、默认关闭。按 HDR_FG_COMPAT_TOGGLE_PLAN_2026-10-09.md,在原 FG 分支实施;独立 start/bundle 保护39工作树/495脏文件,只有 FG 与后续获授权 main 可变,其余37工作树保持。+- 新全局偏好 hdrFgCompatibility=false;设置→兼容可保存选择,旧配置缺字段关闭。既有 presentation revision 送到 GPU 线程;仅切换时排空队列再创建/释放单张合成纹理,逐帧不增加CPU等待/回读。仅用户开启且 NVIDIA HDR10 应用 FG 适用时复制,4K固定31.875MiB,不改变算法/PTS/倍率/同步。Compatible/Direct诊断入口设置私有偏好,不改用户原配置。+- hdr-fg-toggle-build.py 最终重编13个受头文件影响的生产消费者与翻译资源并链接GUI,缓存原件SHA不变。GUI8f697594…,fixture更正后native108e827f…。五次QML真实bridge检查默认/保存/重启/旧配置/英文资源/其它显示设置保持通过;稳定截图已查看。HDR DLSS/VFG各512原帧+620生成/94无损检查误差0/D3D12错误0,含反复开关、4K缓冲/窗口/全屏/resize/reset/销毁;SDR4/6/4X与直接路径通过。+- 已保留构建包装路径/分隔符错误、测试resize尺寸不匹配失败;仅修测试环境,没有将失败冒充产品根因。详细命令/证据/限制见HDR_FG_COMPAT_TOGGLE_REPORT_2026-10-09.md;所有产物E:/项目/Veyra/{build,logs,tests,tmp,reports}/hdr-fg-toggle-20261009。HDR根因/5090反馈、BMD实卡和延迟、NV显存增长仍未确认。本轮不push/Release/更新版本/关机,不派Agent或造压。+## 2026-10-09 HDR补帧闪黑现场续修与本地候选- 授权:用户反馈诊断版不闪、原版闪,提交flash-diagnostic-20261008-205614-027(1).zip与日志44,要求修复后关机。隔离分支codex/fg-flash-fix-20261009,起点main dbfceabee;没有新merge/push/Release。开工独立reports/fg-flash-fix-20261009/pre-document-state.json保护37个原工作树、495份脏文件。diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex 55ea7213..5e8563af 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -14344,6 +14344,27 @@"zh-TW": "目前匯出裝置無法執行所選補幀後端,未替換後端或降低倍率","en": "The export device cannot run the selected frame-generation backend. The backend and multiplier were kept.","ja": "この書き出しデバイスでは選択した補間バックエンドを実行できません。バックエンドと倍率は保持されています。"+ },+ {+ "zh": "HDR 补帧闪黑兼容",+ "src": "qml/Veyra/SettingsPage.qml",+ "zh-TW": "HDR 補幀閃黑相容",+ "en": "HDR frame generation flash compatibility",+ "ja": "HDR フレーム生成の暗転対策"+ },+ {+ "zh": "默认关闭。仅 NVIDIA HDR10 补帧时生效;4K 额外约 32 MiB 显存,可能增加 GPU 开销。切换时画面可能短暂停顿。",+ "src": "qml/Veyra/SettingsPage.qml",+ "zh-TW": "預設關閉。僅 NVIDIA HDR10 補幀時生效;4K 額外約 32 MiB 顯存,可能增加 GPU 負擔。切換時畫面可能短暫停頓。",+ "en": "Off by default. Applies to NVIDIA HDR10 frame generation; uses about 32 MiB of extra VRAM at 4K and may increase GPU work. Switching may briefly pause the picture.",+ "ja": "初期設定はオフです。NVIDIA の HDR10 フレーム生成に適用されます。4K では約 32 MiB の追加 VRAM を使用し、GPU 負荷が増える場合があります。切り替え時に映像が一時停止する場合があります。"+ },+ {+ "zh": "OBS、监控软件兼容需重启;HDR 补帧兼容可在播放中切换。",+ "src": "qml/Veyra/SettingsPage.qml",+ "zh-TW": "OBS、監控軟體相容需重新啟動;HDR 補幀相容可在播放中切換。",+ "en": "OBS and monitoring compatibility require a restart; HDR frame generation compatibility can be switched during playback.",+ "ja": "OBS とモニタリングソフトの互換設定は再起動が必要です。HDR フレーム生成の互換設定は再生中に切り替えられます。"}]}diff --git a/include/veyra/engine/PresentationSettings.h b/include/veyra/engine/PresentationSettings.hindex c3fe5aed..2faa3c7d 100644--- a/include/veyra/engine/PresentationSettings.h+++ b/include/veyra/engine/PresentationSettings.h@@ -20,6 +20,8 @@ struct PresentationSettings {OutputRateMode outputRate=OutputRateMode::Off;double customFps=60.0;bool fullscreen=false; // transient UI state, never persisted as a preference+ // Global opt-in compatibility choice; never part of enhancement presets.+ bool hdrFgCompatibility=false;bool operator==(const PresentationSettings&) const = default;bool valid()const{return unsigned(mode)<=2&&unsigned(display)<=2&&unsigned(outputRate)<=2&&std::isfinite(customFps)&&customFps>=1.0&&customFps<=1000.0;}};diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 457cafa5..215ffa50 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -99,7 +99,7 @@ private:// One bounded GPU-only composition surface, shared by sequential lists on// the presentation queue. Recreated only after that queue has drained.Microsoft::WRL::ComPtr<ID3D12Resource> compositeTarget_;- bool copyBeforePresent_=false;+ bool copyBeforePresent_=false,copyEligible_=false;unsigned inc_=0;unsigned lastBuffer_=0;bool hasPresented_=false;struct RetainedFrame {diff --git a/qml/Veyra/SettingsPage.qml b/qml/Veyra/SettingsPage.qmlindex ed448838..073aadcb 100644--- a/qml/Veyra/SettingsPage.qml+++ b/qml/Veyra/SettingsPage.qml@@ -652,7 +652,7 @@ VPage {visible: root.section === "compat"VH1 { text: qsTr("兼容") }Text {- text: qsTr("与 OBS、监控软件(小飞机 / RTSS)同时使用时的设置;修改后需要重启。")+ text: qsTr("OBS、监控软件兼容需重启;HDR 补帧兼容可在播放中切换。")color: Theme.t2font.family: Theme.fontUifont.pixelSize: Theme.fsBody@@ -660,6 +660,15 @@ VPage {wrapMode: Text.WordWrap}VGroup {+ VRow {+ label: qsTr("HDR 补帧闪黑兼容")+ hint: qsTr("默认关闭。仅 NVIDIA HDR10 补帧时生效;4K 额外约 32 MiB 显存,可能增加 GPU 开销。切换时画面可能短暂停顿。")+ VSwitch {+ objectName: "set-hdr-fg-compatibility"+ checked: !!veyra.preferences.hdrFgCompatibility+ onToggled: v => veyra.setPreference("hdrFgCompatibility", v)+ }+ }VRow {label: qsTr("OBS 游戏采集兼容")hint: (!!veyra.preferences.obsGameCapture !== veyra.obsGameCaptureActive)diff --git a/scripts/acceptance/hdr-fg-toggle-build.py b/scripts/acceptance/hdr-fg-toggle-build.pynew file mode 100644index 00000000..1e894148--- /dev/null+++ b/scripts/acceptance/hdr-fg-toggle-build.py@@ -0,0 +1,141 @@+"""Build all cached consumers of the changed presentation headers, without writing the cache."""+from pathlib import Path+import ctypes, hashlib, json, os, re, subprocess, sys, time++ROOT=Path(__file__).resolve().parents[2]+BASE=Path('E:/项目/Veyra'); TASK='hdr-fg-toggle-20261009'+CACHE=BASE/'build/vfg-next-20261007'; OUT=BASE/'build'/TASK+LOG=BASE/'logs'/TASK/('build-'+time.strftime('%Y%m%d-%H%M%S')); TMP=BASE/'tmp'/TASK/'build'+for p in (OUT,LOG,TMP):p.mkdir(parents=True,exist_ok=True)+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()+shell=ctypes.WinDLL('shell32'); shell.CommandLineToArgvW.argtypes=[ctypes.c_wchar_p,ctypes.POINTER(ctypes.c_int)]+shell.CommandLineToArgvW.restype=ctypes.POINTER(ctypes.c_wchar_p); ctypes.windll.kernel32.LocalFree.argtypes=[ctypes.c_void_p]+def args(s):+ n=ctypes.c_int();p=shell.CommandLineToArgvW(s,ctypes.byref(n));a=[p[i] for i in range(n.value)];ctypes.windll.kernel32.LocalFree(p);return a+def unescape(s):return s.replace('$ ', ' ').replace('$:', ':').replace('$$','$')+ninja=(CACHE/'build.ninja').read_text(encoding='utf8')+tool=re.search(r'^CMAKE_MAKE_PROGRAM:FILEPATH=(.*)$',(CACHE/'CMakeCache.txt').read_text(encoding='utf8'),re.M).group(1)+inputs={}; sources={}; commands=[]; start=time.monotonic()+def protect(p):+ p=Path(p);p=p if p.is_absolute() else CACHE/p+ assert p.is_file(),p+ if str(p) not in inputs:inputs[str(p)]=sha(p)+ return p+def rule(name,objectsRequired=True):+ lines=re.search(r'^build '+re.escape(name)+r': .*?(?=\n\n)',ninja,re.M|re.S).group().splitlines()+ var=dict(re.match(r' ([A-Z_]+) = (.*)',l).groups() for l in lines[1:] if re.match(r' ([A-Z_]+) = (.*)',l))+ objects=[unescape(n).replace('\\','/') for n in lines[0].split('Release ',1)[1].split(' | ',1)[0].split(' ')]+ if objectsRequired:+ for p in objects:protect(p)+ for a in args(unescape(var.get('LINK_LIBRARIES',''))):+ if a.lower().endswith('.lib') and (Path(a).is_file() or (CACHE/a).is_file()):protect(a)+ return objects,var+gui=rule('veyra_qml_ui.exe')+original=json.loads((BASE/'reports/fg-source-flash-20261008/native-build-inputs.json').read_text(encoding='utf8'))+native=args(original[1].split(' -- ',1)[1].rsplit(' && cd .',1)[0])+for a in native:+ if a.lower().endswith('.lib') and not a.startswith('/') and (Path(a).is_file() or (CACHE/a).is_file()):protect(a)+for p in ('build.ninja','CMakeCache.txt','veyra_qml_ui.exe','veyra-qml.manifest'):protect(CACHE/p)+env=dict(os.environ);env.update(TEMP=str(TMP),TMP=str(TMP))+setup=subprocess.run(['cmd.exe','/u','/d','/c',r'call C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Auxiliary\Build\vcvars64.bat >nul && set'],capture_output=True,text=True,encoding='utf-16-le',env=env,check=True)+for line in setup.stdout.splitlines():+ if '=' in line:+ k,v=line.split('=',1)+ if k and not k.startswith('='):env[k]=v+env.update(TEMP=str(TMP),TMP=str(TMP))+def run(cmd,name):+ commands.append(cmd);t=time.monotonic();remaining=890-(t-start);assert remaining>0+ with (LOG/(name+'.log')).open('w',encoding='utf8') as stream:r=subprocess.run(cmd,cwd=CACHE,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=min(300,remaining))+ print(name,'exit',r.returncode,'seconds',round(time.monotonic()-t,2),flush=True)+ if r.returncode:print((LOG/(name+'.log')).read_text(encoding='utf8',errors='replace')[-3000:]);raise SystemExit(r.returncode)+def compiler(objectRule):+ line=subprocess.check_output([tool,'-t','commands',objectRule],cwd=CACHE,text=True,encoding='utf8').splitlines()[-1]+ a=args(line);assert a[0].lower().endswith('cl.exe'),line;return a+def compileSource(source,name,a):+ target=OUT/(name+'.obj');sources[str(source)]=sha(source)+ command=a[:1]+['/I'+str(ROOT/'include'),'/I'+str(ROOT/'tests/unit')]+[v for v in a[1:-1] if not v.startswith(('/Fo','/Fd')) and v!='/showIncludes']+ command+=['/Fo'+str(target),'/Fd'+str(OUT/(name+'.pdb')),str(source)]+ run(command,'compile-'+name);return target+if '--tests-only' in sys.argv:+ previous=json.loads((BASE/'reports'/TASK/'build-current.json').read_text(encoding='utf8'))+ previous=json.loads(Path(previous['receipt']).read_text(encoding='utf8'))+ for p,d in previous['sources'].items():+ if not p.endswith('FgPresentationTests.cpp'):assert sha(Path(p))==d,p+ for row in previous['overrides'].values():assert sha(Path(row['path']))==row['sha256'],row['path']+ guiSha=sha(OUT/'veyra_qml_ui.exe')+ compileSource(ROOT/'tests/integration/FgPresentationTests.cpp','fg-presentation-tests',args(original[0]))+ command=next(cmd for cmd in previous['commands'] if any(a.startswith('/out:') and a.endswith('fg-presentation-tests.exe') for a in cmd))+ run(command,'link-native')+ assert sha(OUT/'veyra_qml_ui.exe')==guiSha+ for p,d in inputs.items():assert sha(Path(p))==d,p+ receipt={'commands':commands,'sources':sources,'fixtureSha256':sha(ROOT/'tests/integration/HdrCopyPresentationFixture.h'),'guiUnchanged':guiSha,'nativeSha256':sha(OUT/'fg-presentation-tests.exe'),'inputsUnchanged':inputs}+ (LOG/'native-receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+ print('Native fixture rebuilt; GUI and original inputs unchanged',flush=True);raise SystemExit(0)+for file in ('include/veyra/engine/PresentationSettings.h','include/veyra/engine/VideoPresenter.h','tests/integration/HdrCopyPresentationFixture.h'):+ sources[str(ROOT/file)]=sha(ROOT/file)+deps=subprocess.check_output([tool,'-t','deps'],cwd=CACHE,text=True,encoding='utf8')+headers=('include/veyra/engine/PresentationSettings.h','include/veyra/engine/VideoPresenter.h')+dependent=[]+for block in deps.split('\n\n'):+ if any(h in block.replace('\\','/') for h in headers):+ name=block.splitlines()[0].split(': #deps',1)[0].replace('\\','/')+ if name.endswith('.obj') and not name.startswith(('CMakeFiles/veyra_fg_settings_tests.','CMakeFiles/veyra_vfg_export_probe.')):dependent.append(name)+assert len(dependent)>=10,dependent+overrides={}+for name in dependent:+ a=compiler(name);source=Path(a[-1]);relative=name.split('.dir/',1)[1][:-4]+ if not relative.startswith('veyra_qml_bridge_autogen/'):+ source=ROOT/relative+ else:protect(source)+ overrides[name]=compileSource(source,Path(relative).stem,a)+# catalog.json is an executable resource, so replacing the staged JSON alone+# would leave the new settings untranslated. Regenerate only our private qrc.+resource=next(p for p in gui[0] if p.endswith('/qrc_veyra_i18n.cpp.obj'))+lines=subprocess.check_output([tool,'-t','commands',resource],cwd=CACHE,text=True,encoding='utf8').splitlines()+rccLine=next(l for l in lines if 'rcc.exe' in l.lower() and 'veyra_i18n' in l)+rcc=next(a for part in args(rccLine) for a in args(part) if a.lower().endswith('rcc.exe'))+qrc=OUT/'i18n.qrc';qrc.write_text('<RCC><qresource prefix="/i18n"><file alias="catalog.json">'+(ROOT/'i18n/catalog.json').as_posix()+'</file></qresource></RCC>',encoding='utf8')+generated=OUT/'qrc_veyra_i18n.cpp';run([rcc,'--name','veyra_i18n','--no-zstd','-o',str(generated),str(qrc)],'generate-i18n')+sources[str(ROOT/'i18n/catalog.json')]=sha(ROOT/'i18n/catalog.json')+overrides[resource]=compileSource(generated,'qrc_veyra_i18n',compiler(resource))+combined='--combined' in sys.argv+if combined:+ for file in ('NativeCaptureSink.cpp','CaptureCardSource.cpp'):+ name='CMakeFiles/veyra_sources.dir/src/source/'+file+'.obj'+ overrides[name]=compileSource(ROOT/'src/source'/file,file[:-4],compiler(name))+fixture=compileSource(ROOT/'tests/integration/FgPresentationTests.cpp','fg-presentation-tests',args(original[0]))+core=[p for name,p in overrides.items() if '/src/engine/' in name and Path(name).stem in ('VideoPresenter.cpp','EngineController.cpp','EngineControllerImage.cpp') or name.startswith('CMakeFiles/veyra_sources.')]+assert sum(p.stem in ('VideoPresenter','EngineController','EngineControllerImage') for p in core)==3,core+nativeLink=[]+for a in native:+ if a.endswith('FgPresentationTests.cpp.obj'):nativeLink+=list(map(str,core+[fixture]))+ elif a.startswith('/out:'):nativeLink.append('/out:'+str(OUT/'fg-presentation-tests.exe'))+ elif a.startswith('/implib:'):nativeLink.append('/implib:'+str(OUT/'fg-tests.lib'))+ elif a.startswith('/pdb:'):nativeLink.append('/pdb:'+str(OUT/'fg-tests.pdb'))+ else:nativeLink.append(a)+run(nativeLink,'link-native')+objects,var=gui;response=OUT/'gui-link.rsp'+objects=[CACHE/p for p in objects if p not in overrides]+response.write_text('\n'.join(subprocess.list2cmdline([str(p)]) for p in list(overrides.values())+objects)+'\n'+unescape(var.get('LINK_PATH',''))+'\n'+unescape(var['LINK_LIBRARIES']),encoding='utf8')+manifest=OUT/'manifest';manifest.mkdir(exist_ok=True)+link=r'C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Tools\MSVC\1444~1.352\bin\Hostx64\x64\link.exe'+cmake=r'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'+flags=[('/MANIFESTINPUT:'+str(CACHE/'veyra-qml.manifest')) if a.startswith('/MANIFESTINPUT:') else a for a in args(unescape(var.get('LINK_FLAGS','')))]+run([cmake,'-E','vs_link_exe','--msvc-ver=1944','--intdir='+str(manifest),r'--rc=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\rc.exe',r'--mt=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\mt.exe','--manifests','--',link,'/nologo','@'+str(response),'/out:'+str(OUT/'veyra_qml_ui.exe'),'/implib:'+str(OUT/'gui.lib'),'/pdb:'+str(OUT/'gui.pdb'),'/version:0.0']+flags,'link-gui')+extras=[]+if combined:+ captureObjects=[p for n,p in overrides.items() if n.startswith('CMakeFiles/veyra_sources.')]+ for target,name in (('veyra_capture_color_tests.exe','capture-contract'),('veyra_hdr_color_tests.exe','capture-gpu')):+ names,variables=rule(target,False);assert len(names)==1,(target,names)+ rel=names[0].split('.dir/',1)[1][:-4]+ testObject=compileSource(ROOT/rel,name,compiler(names[0]))+ rsp=OUT/(name+'.rsp');rsp.write_text('\n'.join(subprocess.list2cmdline([str(p)]) for p in captureObjects+[testObject])+'\n'+unescape(variables.get('LINK_PATH',''))+'\n'+unescape(variables['LINK_LIBRARIES']),encoding='utf8')+ directory=OUT/('manifest-'+name);directory.mkdir(exist_ok=True)+ testFlags=args(unescape(variables.get('LINK_FLAGS','')))+ run([cmake,'-E','vs_link_exe','--msvc-ver=1944','--intdir='+str(directory),r'--rc=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\rc.exe',r'--mt=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\mt.exe','--manifests','--',link,'/nologo','@'+str(rsp),'/out:'+str(OUT/(name+'.exe')),'/implib:'+str(OUT/(name+'.lib')),'/pdb:'+str(OUT/(name+'.pdb')),'/version:0.0']+testFlags,'link-'+name)+ extras.append(OUT/(name+'.exe'))+for p,d in inputs.items():assert sha(Path(p))==d,p+receipt={'root':str(ROOT),'combined':combined,'commands':commands,'sources':sources,'headerDependents':dependent,'overrides':{n:{'path':str(p),'sha256':sha(p)} for n,p in overrides.items()},'inputsUnchanged':inputs,'seconds':time.monotonic()-start,'executables':{p.name:sha(p) for p in [OUT/'veyra_qml_ui.exe',OUT/'fg-presentation-tests.exe']+extras}}+(LOG/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+report=BASE/'reports'/TASK;report.mkdir(exist_ok=True,parents=True);(report/'build-current.json').write_text(json.dumps({'receipt':str(LOG/'receipt.json')},indent=2),encoding='utf8')+print('Build passed; cached inputs unchanged; receipt',LOG/'receipt.json',flush=True)diff --git a/scripts/acceptance/hdr-fg-toggle-test.py b/scripts/acceptance/hdr-fg-toggle-test.pynew file mode 100644index 00000000..331afc26--- /dev/null+++ b/scripts/acceptance/hdr-fg-toggle-test.py@@ -0,0 +1,117 @@+"""Serial HDR presentation and real-QML preference persistence checks."""+from pathlib import Path+import hashlib,json,os,re,shutil,subprocess,sys,time+import psutil+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='hdr-fg-toggle-20261009'+DONOR=BASE/'test-packages/vfg-next-20261007/Veyra-2.0.6-VFG-next-NVIDIA-win64-portable'+APP=BASE/'tests'/TASK/'app';BUILD=BASE/'build'/TASK+def sha(p):+ with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()+manifest=json.loads((DONOR/'package-manifest.json').read_text(encoding='utf8'))+def verify():+ for row in manifest['files']:assert sha(DONOR/row['path'])==row['sha256'],row['path']+verify()+for proc in psutil.process_iter(['pid','name']):+ name=(proc.info['name'] or '').lower()+ assert not name.startswith(('veyra','fg-presentation','flash-pixel')),f'Existing player/probe: {name} PID {proc.pid}'+if not APP.exists():+ APP.mkdir(parents=True)+ for row in manifest['files']:+ rel=Path(row['path'])+ if rel.parts[0] in ('runtime_local','logs') or rel.name=='veyra_qml_ui.exe':continue+ p=APP/rel;p.parent.mkdir(parents=True,exist_ok=True)+ if rel.as_posix() in ('qml/Veyra/Main.qml','qml/Veyra/SettingsPage.qml'):shutil.copy2(DONOR/rel,p)+ else:os.link(DONOR/rel,p)+ (APP/'runtime_local').mkdir(exist_ok=True)+for rel in ('veyra_qml_ui.exe','qml/Veyra/SettingsPage.qml'):+ source=BUILD/rel if rel.endswith('.exe') else ROOT/rel+ swap=APP/(rel+'.swap');shutil.copy2(source,swap);os.replace(swap,APP/rel)+for row in manifest['files']:+ rel=Path(row['path'])+ if rel.parts[0]=='shaders':+ p=BUILD/rel;p.parent.mkdir(parents=True,exist_ok=True)+ if not p.exists():os.link(DONOR/rel,p)+ assert sha(p)==row['sha256']+mode,label=sys.argv[1:3];assert mode in ('native','gui','capture') and re.fullmatch('[a-z0-9-]+',label)+case=BASE/'logs'/TASK/label;case.mkdir(parents=True,exist_ok=False)+tmp=BASE/'tmp'/TASK/label;tmp.mkdir(parents=True,exist_ok=False)+env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_','QSG_'))}+env.update(PATH=str(APP)+os.pathsep+env['PATH'],TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'),QML_DISK_CACHE_PATH=str(tmp/'qml-cache'),QT_FORCE_STDERR_LOGGING='1',VEYRA_LOG_FILE=str(case/'engine.log'))+main=APP/'qml/Veyra/Main.qml';original=main.read_bytes();mutated=False+if mode=='capture':+ test=sys.argv[3];assert test in ('contracts','pixels')+ command=[str(BUILD/('capture-contract.exe' if test=='contracts' else 'capture-gpu.exe'))]+elif mode=='native':+ test=sys.argv[3] if len(sys.argv)>3 else 'hdr'+ assert test in ('hdr','hdr-4k','vfg-4k','sdr','direct')+ if test in ('hdr-4k','vfg-4k'):env['VEYRA_TEST_HDR_4K_WINDOW']='1'+ if test=='vfg-4k':env['VEYRA_TEST_HDR_VFG']='1'+ if test=='direct':env['VEYRA_TEST_HDR_PRESENT_COPY']='0'+ command=[str(BUILD/'fg-presentation-tests.exe'),str(case),str(APP/'runtime/experimental')]+ if test!='sdr':command.append('hdr-copy')+else:+ phase=sys.argv[3];assert phase in ('fresh','restore-on','restore-off','legacy','visual')+ profile=BASE/'tests'/TASK/'profiles'/(phase if phase in ('legacy','visual') else 'persistence')+ if phase in ('fresh','legacy','visual'):+ profile.mkdir(parents=True,exist_ok=False)+ prefs={'gpuPriority':'normal','language':'en' if phase=='legacy' else 'zh-CN','autoResume':False,'prewarmEnhancement':False,'sentinel':'preserved'}+ if phase=='legacy':prefs['presentation']={'lowQueue':True,'display':1,'outputRate':0,'customFps':60}+ (profile/'qml-preferences.v1.json').write_text(json.dumps(prefs),encoding='utf8')+ expected=phase=='restore-on';toggle='true' if phase=='fresh' else 'false'+ timer='''+ Timer { interval: 1500; running: true; repeat: false; onTriggered: {+ root.goPage("set"); settingsPage.section = "compat";+ function find(item) {+ if (item.objectName === "set-hdr-fg-compatibility") return item;+ if (item.children) for (let i = 0; i < item.children.length; ++i) { const hit = find(item.children[i]); if (hit) return hit; }+ return null;+ }+ const sw = find(settingsPage);+ if (!sw || sw.checked !== EXPECTED || !!veyra.preferences.hdrFgCompatibility !== EXPECTED) { console.error("HDRGUI_FAIL initial"); return; }+ console.log("HDRGUI_INITIAL", sw.checked);+ console.log("HDRGUI_LABEL", qsTr("HDR 补帧闪黑兼容"));+ sw.toggled(TOGGLE);+ Qt.callLater(() => {+ if (sw.checked !== TOGGLE || veyra.preferences.hdrFgCompatibility !== TOGGLE) { console.error("HDRGUI_FAIL saved"); return; }+ // Other presentation controls must not erase this global choice.+ veyra.outputCustomFps = 61;+ console.log("HDRGUI_PASS");+ });+ } }+ Timer { interval: 3200; running: true; repeat: false; onTriggered: {+ root.contentItem.grabToImage(result => result.saveToFile("SCREENSHOT"));+ } }+'''.replace('EXPECTED',str(expected).lower()).replace('TOGGLE',toggle).replace('SCREENSHOT',(case/'settings.png').as_posix())+ text=original.decode('utf8');assert text.count(' id: root')==1+ swap=main.with_suffix('.swap');swap.write_text(text.replace(' id: root',' id: root'+timer,1),encoding='utf8');os.replace(swap,main);mutated=True+ command=[str(APP/'veyra_qml_ui.exe'),'--data-dir',str(profile),'--page','set','--size','1280x800','--exit-after','6000']+begin=time.monotonic()+try:+ with (case/'console.log').open('xb') as stream:r=subprocess.run(command,cwd=case if mode=='native' else APP,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=180)+finally:+ if mutated:+ swap=main.with_suffix('.swap');swap.write_bytes(original);os.replace(swap,main)+text=(case/'console.log').read_text(encoding='utf8',errors='replace')+if (case/'engine.log').is_file():text+='\n'+(case/'engine.log').read_text(encoding='utf8',errors='replace')+errors=[l for l in text.splitlines() if re.search(r'\[ERROR\s*\]|\[FATAL\s*\]|ReferenceError:|TypeError:|D3D12 ERROR|D3D12 CORRUPTION|HDRGUI_FAIL',l)]+passed=r.returncode==0 and not errors+receipt={'mode':mode,'command':command,'exit':r.returncode,'seconds':time.monotonic()-begin,'errors':errors,'exeSha256':sha(Path(command[0])),'events':[l for l in text.splitlines() if '[present-copy]' in l or l.startswith(('HDR_COPY','PRESENTATION','D3D12 errors')) or 'HDRGUI_' in l]}+if mode=='gui':+ prefs=json.loads((profile/'qml-preferences.v1.json').read_text(encoding='utf8'))+ passed=passed and 'HDRGUI_PASS' in text and prefs.get('hdrFgCompatibility')==(phase=='fresh') and prefs.get('sentinel')=='preserved' and (case/'settings.png').is_file()+ if phase=='legacy':passed=passed and 'HDR frame generation flash compatibility' in text+ receipt['savedPreference']=prefs.get('hdrFgCompatibility');receipt['screenshot']=str(case/'settings.png')+elif mode=='native':+ passed=passed and (('HDR_COPY_SUMMARY' in text and 'pass=1' in text) if test!='sdr' else 'D3D12 errors=0' in text)+ if test in ('hdr','hdr-4k','vfg-4k'):+ passed=passed and 'requested=true eligible=true enabled=true' in text and 'requested=false eligible=true enabled=false' in text+else:+ passed=passed and not re.search(r'^FAIL\b|\bpass=0\b',text,re.M)+ if test=='contracts':passed=passed and text.count('PASS BMD source pixels delivered exactly')==2 and 'failures=0' in text+ else:passed=passed and len(re.findall(r'BLACKMAGIC_HDYC_GPU flip=[01] identical709=1.*pass=1',text))==2+ receipt['checksPrinted']=len(re.findall(r'^PASS\b|\bpass=1\b',text,re.M))+verify();receipt.update(passed=passed,donorUnchanged=True)+(case/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+print(json.dumps({k:v for k,v in receipt.items() if k!='events'},ensure_ascii=False,indent=2),flush=True)+print('\n'.join(receipt['events'][-10:]),flush=True)+raise SystemExit(0 if passed else 1)diff --git a/scripts/diagnostics/Start-HDR-Flash-Fix.ps1 b/scripts/diagnostics/Start-HDR-Flash-Fix.ps1index e6b16f9f..a8145b70 100644--- a/scripts/diagnostics/Start-HDR-Flash-Fix.ps1+++ b/scripts/diagnostics/Start-HDR-Flash-Fix.ps1@@ -38,6 +38,10 @@ foreach ($name in @('chain-session.v1','chain-session.v1.vfg','qml-preferences.v$copied += [pscustomobject]@{path=$from;sha256=$digest}}}+$prefsPath=Join-Path $profile 'qml-preferences.v1.json'+$prefs=if(Test-Path -LiteralPath $prefsPath -PathType Leaf){Get-Content -LiteralPath $prefsPath -Raw | ConvertFrom-Json}else{'{}' | ConvertFrom-Json}+$prefs | Add-Member -NotePropertyName 'hdrFgCompatibility' -NotePropertyValue ($Variant -eq 'Compatible') -Force+[IO.File]::WriteAllText($prefsPath,($prefs | ConvertTo-Json -Depth 40),(New-Object Text.UTF8Encoding($false)))$envNames = @('TEMP','TMP','CUDA_CACHE_PATH','VEYRA_LOG_FILE','VEYRA_TEST_HDR_PRESENT_COPY')$savedEnv = @{}foreach ($name in $envNames) { $savedEnv[$name] = [Environment]::GetEnvironmentVariable($name,'Process') }@@ -50,8 +54,9 @@ $result=1;$forcedStop=$falsetry {$env:TEMP=$tmp;$env:TMP=$tmp;$env:CUDA_CACHE_PATH=Join-Path $tmp 'cuda-cache'$env:VEYRA_LOG_FILE=Join-Path $output 'engine.log'- if ($Variant -eq 'Direct') { $env:VEYRA_TEST_HDR_PRESENT_COPY='0' }- else { [Environment]::SetEnvironmentVariable('VEYRA_TEST_HDR_PRESENT_COPY',$null,'Process') }+ # Exercise the same saved setting as Settings > Compatibility, with no+ # environment override. Only this private configuration is changed.+ [Environment]::SetEnvironmentVariable('VEYRA_TEST_HDR_PRESENT_COPY',$null,'Process')# Keep the normal filename/path and QML disk-cache setting. Changing the# filename could bypass NVIDIA App/RTSS per-program profiles.Write-Host ('Variant: {0}. Use the same source/settings in both runs; close the player when finished.' -f $Variant)diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 7b8d1ca9..a4da46bd 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -92,13 +92,10 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh// pixel-copy diagnostic does not. This is a compatibility candidate, not// proof of a driver defect. Compose separately and copy the actual final// image to DXGI; never retain the diagnostic's CPU readback or add sleeps.- copyBeforePresent_=ctx.adapter().isNvidia&&graph.hdr10Output()&&graph.fgEnabled()&&bool(presentationQueue_);- wchar_t copyOverride[4]{};- if(GetEnvironmentVariableW(L"VEYRA_TEST_HDR_PRESENT_COPY",copyOverride,4)&©Override[1]==L'\0'){- if(copyOverride[0]==L'0')copyBeforePresent_=false;- // A forced path is for bounded regression tests, including SDR.- else if(copyOverride[0]==L'1'&&!sink_.xess())copyBeforePresent_=true;- }+ copyEligible_=ctx.adapter().isNvidia&&graph.hdr10Output()&&graph.fgEnabled()&&bool(presentationQueue_);+ // Opening a source never opts the user in or allocates the copy surface.+ // configurePresentation applies the saved global choice on the GPU owner.+ copyBeforePresent_=false;D3D12_DESCRIPTOR_HEAP_DESC hd{};hd.Type=D3D12_DESCRIPTOR_HEAP_TYPE_RTV;hd.NumDescriptors=4;if(FAILED(ctx.device()->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&rtvs_))))return false;inc_=ctx.device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);if(!refresh(ctx.device()))return false;@@ -399,12 +396,34 @@ void VideoPresenter::close(){xessInputId_=0;xessWork_={};xessWorkPosition_=0;reflex_.close();reflexFrame_=0;if(presentationRing_.initialized())presentationRing_.drainQueue();- hasPresented_=false;gpuTimer_.close();compositeTarget_.Reset();copyBeforePresent_=false;rtvs_.Reset();pass_={};sink_.shutdown();+ hasPresented_=false;gpuTimer_.close();compositeTarget_.Reset();copyBeforePresent_=copyEligible_=false;rtvs_.Reset();pass_={};sink_.shutdown();presentMotionPass_={};presentMotion_={};previousXessWidth_=previousXessHeight_=0;presentationRing_.shutdown();presentationFence_.Reset();presentationQueue_.Reset();if(presentationEvent_){CloseHandle(presentationEvent_);presentationEvent_=nullptr;}}PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceContext& ctx,PresentationSettings requested,bool fg,std::wstring& status){+ bool wanted=requested.hdrFgCompatibility&©Eligible_;+ wchar_t copyOverride[4]{};+ if(GetEnvironmentVariableW(L"VEYRA_TEST_HDR_PRESENT_COPY",copyOverride,4)&©Override[1]==L'\0'){+ if(copyOverride[0]==L'0')wanted=false;+ // Only bounded regression tests may force the copy path on SDR.+ else if(copyOverride[0]==L'1'&&!sink_.xess())wanted=true;+ }+ if(wanted!=copyBeforePresent_){+ // Switching is infrequent and runs on the presentation owner thread.+ // Drain once before changing the target, never in the per-frame path.+ if(presentationRing_.initialized()&&!presentationRing_.drainQueue()){+ veyra::log::warn("present-copy","compatibility switch deferred: presentation queue drain failed");+ }else{+ copyBeforePresent_=wanted;+ if(wanted&&!refresh(ctx.device())){+ copyBeforePresent_=false;+ veyra::log::warn("present-copy","compatibility target setup failed; retaining direct presentation");+ }+ if(!copyBeforePresent_)compositeTarget_.Reset();+ veyra::log::info("present-copy",std::format("requested={} eligible={} enabled={} (user preference; switch drains once)",requested.hdrFgCompatibility,copyEligible_,copyBeforePresent_));+ }+ }const bool reflexDisabled=reflex_.disable();reflexFrame_=0;const bool followDisplay=requested.outputRate==OutputRateMode::FollowDisplay;if(followDisplay){@@ -413,6 +432,7 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceConteelse requested.outputRate=OutputRateMode::Off;}auto effective=requested;+ effective.hdrFgCompatibility=copyBeforePresent_;std::wstring capNotice;if((xessActive())&&requested.outputRate!=OutputRateMode::Off){// Provider owns generated Present calls. Capping our real-frame inputdiff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex fe84522b..f19d3210 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -1161,6 +1161,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst{const auto saved = impl_->prefs.value(QStringLiteral("presentation")).toMap();auto& pr = impl_->presentation;+ pr.hdrFgCompatibility = impl_->prefBool("hdrFgCompatibility", false);if (!saved.isEmpty()) {pr.enabled = saved.value(QStringLiteral("lowQueue")).toBool();pr.display = static_cast<engine::DisplaySync>(std::clamp(saved.value(QStringLiteral("display")).toInt(), 0, 2));@@ -4977,7 +4978,7 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {{"listInspectorWidth", {376, 4000}}};static const QStringList flags{"subtitleEnabled", "subtitleBackground", "subtitleFit","subtitleSecondLanguage", "audioForceStereo", "holdCompare",- "magewellLowLatency", "cinePillHidden", "exportStopsPlayback", "obsGameCapture", "autoResume", "fullscreenMemoryProtection", "prewarmEnhancement"};+ "magewellLowLatency", "cinePillHidden", "exportStopsPlayback", "obsGameCapture", "autoResume", "fullscreenMemoryProtection", "prewarmEnhancement", "hdrFgCompatibility"};QVariant stored;if (ranges.contains(key)) {bool ok = false; const int n = value.toInt(&ok);@@ -5055,6 +5056,11 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {return true;}void QmlPlayerBridge::applyPreference(const QString& key) {+ if(key==QLatin1String("hdrFgCompatibility")){+ impl_->presentation.hdrFgCompatibility=impl_->prefBool("hdrFgCompatibility",false);+ impl_->engine.requestPresentation(impl_->presentation);+ emit presentationChanged();+ }if(key==QLatin1String("prewarmEnhancement")){impl_->engine.setEnhancementPrewarmEnabled(impl_->prefBool("prewarmEnhancement",false));if(impl_->prefBool("prewarmEnhancement",false))scheduleEnhancementPrewarm();diff --git a/tests/integration/HdrCopyPresentationFixture.h b/tests/integration/HdrCopyPresentationFixture.hindex b6f9c9fb..4dd46f7e 100644--- a/tests/integration/HdrCopyPresentationFixture.h+++ b/tests/integration/HdrCopyPresentationFixture.h@@ -54,8 +54,20 @@ static bool hdrCopyPresentation(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::const auto& blit=sample.gpu[size_t(diagnostics::GpuStage::Blit)];if(blit.state==diagnostics::SampleState::Measured&&blit.milliseconds)blitTimes.push_back(*blit.milliseconds);}};- engine::PresentationSettings requested;requested.fullscreen=full;std::wstring text;presenter.configurePresentation(ctx,requested,desc.enableFg,text);+ engine::PresentationSettings requested;requested.fullscreen=full;std::wstring text;+ // No override: exercise the real persisted-choice route, including an+ // old/missing preference (false) and live off/on/off/on transitions.+ const bool overridden=GetEnvironmentVariableW(L"VEYRA_TEST_HDR_PRESENT_COPY",nullptr,0)>0;+ const auto applyCompatibility=[&](bool enabled){+ requested.hdrFgCompatibility=enabled;+ const auto effective=presenter.configurePresentation(ctx,requested,desc.enableFg,text);+ return overridden||effective.hdrFgCompatibility==(enabled&&desc.enableFg);+ };+ ok=applyCompatibility(false)&&ok;+ ok=applyCompatibility(true)&&ok;for(unsigned i=0;ok&&i<64;++i){+ if(i==16)ok=applyCompatibility(false)&&ok;+ if(i==32)ok=applyCompatibility(true)&&ok;if(!full&&(i==24||i==40)){SetWindowPos(window,nullptr,0,0,i==24?800:640,i==24?450:360,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);Sleep(110);}@@ -72,7 +84,7 @@ static bool hdrCopyPresentation(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::ok=presenter.present(ctx,ring,graph,item.lease->slot,gen,false,0,false,.5f,item.identity,{},item.pts100ns);collect();if(gen)++generated;else ++real;- if(ok&&!full&&i<8){+ if(ok&&!full&&(i<8||i==17||i==41||i==49)){auto shown=presenter.presentedResourceForTest();std::vector<uint32_t> actual,expected;unsigned w=0,h=0,ew=0,eh=0;ok=readHdrWords(ctx,ring,shown.Get(),actual,w,h)&&readHdrWords(ctx,ring,item.lease->texture.Get(),expected,ew,eh)&&w==ew&&h==eh;if(ok){