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 reversible NVIDIA HDR frame-generation presentation compatibility path
Veyra Goal Agentce50d18f6295
diff --git a/AGENTS.md b/AGENTS.mdindex 814c228e..6058cdb6 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **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 归档成本分别报告。> **2026-10-08 本地合并与项目清理授权**:用户要求把当前修复合入 main,然后排查并清理项目磁盘占用。已验 VFG 71723e0 从 main 96a7c8de 快进合并;按 docs/PROJECT_STORAGE_CLEANUP_PLAN_2026-10-08.md 盘点并删除经清单核实的过时可重建构建、私有测试 app/缓存、冗余解压副本。此授权覆盖这些产物的历史保留限制,不改历史 guard/start 基线,不删除工作树、源码、未提交修改、依赖/SDK/运行库原件、用户素材或正式发布 ZIP/对应源码。独立 start/495 份脏文件备份在 E:/项目/Veyra/archives/project-cleanup-20261008;按硬链接身份及实际磁盘空间分别报告。保留当前可用构建、2.0.6 两显卡包与最新 VFG 候选、必要日志/验收记录。不派 Agent、不改产品实现或用户配置、不 push/Release/关机。diff --git a/docs/FG_FLASH_FIX_PLAN_2026-10-09.md b/docs/FG_FLASH_FIX_PLAN_2026-10-09.mdnew file mode 100644index 00000000..8e3c7647--- /dev/null+++ b/docs/FG_FLASH_FIX_PLAN_2026-10-09.md@@ -0,0 +1,25 @@+# HDR 补帧闪黑兼容修复与现场证据++用户提供 diagnostic ZIP 与日志44,确认诊断版不闪、原版闪,授权排查修复并在收尾关机。本轮从 main `dbfceabee804cd81bac4a4781f0b7b4cf272902e` 开隔离分支 `codex/fg-flash-fix-20261009`;不包含新 main 合并或公开发布。历史 UI 冻结不覆盖本次明确授权的 presenter 修复。单进程测试≤300秒,构建≤900秒,无子 Agent、竞争负载或驱动/用户配置修改。++## 已知事实与不能推断的内容++- ZIP EXE SHA256 与交付诊断版一致。它在约28.6秒实际采集期间记录3278次呈现,源纹理及交换链9点均未全黑,Present全部成功;这不是90秒连续视频测试,也不代表面板实际扫描验证。+- 与原版末次设置对齐:RTX5090/617.42、4K PQ HDR59.94、DLSS2X、AMD光流、NR4K+1440p、原始时间戳、VSync队列1;原版最后一段约65秒,诊断版约29秒,不能当等长A/B。+- 诊断版逐呈现额外18次单像素GPU拷贝与额外资源屏障,使用私有配置并关闭QML磁盘缓存。取样仅在退出时读取,无逐帧CPU fence等待。它会改变GPU时间与访问路径,不能以“不闪”证明已经修复。+- 租约/producer→consumer→producer GPU fence及同线程有界调度暂未发现确定越界。不能将推测写成确定驱动、NGX或采集卡故障。++## 候选与最小实现范围++NVIDIA HDR10 + 应用侧补帧使用独立合成纹理,再通过GPU完整复制到交换链。目的:保留诊断实验中改变最终GPU访问路径的方向,用实际最终图像复制代替读取像素、空转或额外睡眠。原帧和生成帧采用同一链路;不改媒体时间、补帧倍率、过期判断、算法或显示同步。++只改 `VideoPresenter.h/.cpp` 及必要回归脚本/测试/文档。单个与实际交换链同尺寸/格式的 DEFAULT 纹理,有界复用;正常逐帧仅GPU屏障/CopyResource,无CPU像素回读/新fence等待。重建必须在呈现队列排空后,分配失败明确记录并回退现有直接路径。SDR/非NVIDIA/关闭补帧/XeSS保持现有路径。测试环境变量允许切回直接路径,便于同EXE同配置A/B。++## 验收与交付++1. 编译全部受 presenter 布局改变影响的3个产品源文件,链接GUI与定向原生回归;缓存构建及运行组件前后SHA保持。+2. 无损HDR10像素一致、原帧/生成帧、窗口/全屏、resize/rebuild/close、开启/关闭补帧、SDR及无增强回归。D3D12 debug错误为0。正常GUI不加像素探针。+3. GTA6 4K视频/1080 NR普通负载对照,记录最终合成GPU耗时、FPS、固定纹理内存;不得以短测或时间戳替代物理扫描。+4. 本地可回退候选+精确源码/哈希/说明;37个原工作树及495份脏文件独立基线保持。主报告如实区分“兼容候选”与“5090现场确认”。保存全部证据后按用户要求关机,无强制结束其它应用。++所有产物:`E:/项目/Veyra/{reports,tests,logs,tmp,test-packages}/fg-flash-fix-20261009`。开工基线:reports目录的 `pre-document-state.json`(不可改写)。diff --git a/docs/FG_FLASH_FIX_REPORT_2026-10-09.md b/docs/FG_FLASH_FIX_REPORT_2026-10-09.mdnew file mode 100644index 00000000..ca376026--- /dev/null+++ b/docs/FG_FLASH_FIX_REPORT_2026-10-09.md@@ -0,0 +1,61 @@+# HDR 补帧闪黑排查与可回退候选++交付状态:已构建、定向回归通过的 NVIDIA HDR 呈现兼容候选。**没有在本机 RTX5070 复现现场闪黑,也没有取得本候选在用户 RTX5090/采集卡上的反馈;根因尚未确认,不能写“已根治”。** 代码保留在 `codex/fg-flash-fix-20261009`,未合 main、未推送或发布。++## 现场证据++输入 ZIP SHA256 `06854d0447ea60cb0208cf211aa4c0c100c2ef028ab81f31b3725587504bbb90`;日志44 SHA256 `6f92bc96793405b6e5cf9004f70a04413f959d674ed4911b2e8df2529d6395f1`。诊断 EXE `4c38d320585ff545dac231910fe7f64b71a2930af5e164f6c40fb32fce9804a1` 与交付件一致。输入只当证据数据,不执行其中内容。++两次末尾运行的主要设置对齐:RTX5090/617.42、4K PQ HDR59.94、DLSS2X、AMD光流、NR4K+1440p、保留源时间戳、VSync队列1。原版曾使用3层原生NR与60→30,但最终切换后的配置已与诊断版对齐,不能将前面设置差异冒充最终解释。++诊断实际视频采样约28.6秒(进程运行约92秒,大部分时间用于操作/打开);1658张原帧+1620张生成帧,3278次Present全部成功,源纹理与交换链各9点没有全黑。9点采样不覆盖每个像素,更不是面板扫描证据。原版相邻末段约65秒,两个窗口不等长。++诊断与原版并非单变量实验:++1. 每次呈现增加源纹理与交换链共18次单像素GPU拷贝及额外资源屏障。即使退出才读取CPU数据,也会改变缓存/布局与GPU执行时序。+2. EXE由`veyra_qml_ui.exe`改名为`veyra-flash-diagnostic.exe`,可能避开NVIDIA App、RTSS等程序配置;用户的驱动配置没有随日志采集,不能认定开启了Smooth Motion/外部HDR或认定它们就是原因。+3. 私有配置与`QML_DISABLE_DISK_CACHE=1`改变了运行环境。最新日志看起来主要效果相同,不等于逐项排除所有配置/缓存差异。++这些差异足以解释“诊断不闪”为什么不等于“已经定位”。本次检查共享输出租约、producer/consumer GPU fence、生成帧有效性与原帧等待最后FG列表的合同,暂未发现确定的提前复用。没有编造NGX错误、采集源黑帧或线程竞态。++## 候选改动++仅`VideoPresenter`增加GPU最终合成纹理:原帧/生成帧先完成现有绘制、比较与HDR曲线,然后完整`CopyResource`到交换链,最后回到PRESENT。自动范围是NVIDIA + HDR10 + 应用侧FG独立呈现队列;SDR、非NVIDIA、无补帧与XeSS保留直接呈现。没有改变源时间戳、倍率、丢帧/过期规则、光流/NR/FG算法或VSync。++目的在于避开“直接绘制HDR交换链→Present”的路径,保留诊断改变最终GPU访问方式这一线索,用实际图像复制取代探针。**这仍是有依据的兼容候选,不能由规范正确推断5090闪黑必然消失。** 相关屏障和复制合同依据 [Microsoft 资源屏障说明](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12) 与 [CopyResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-copyresource)。++单张DEFAULT合成纹理固定复用;队列排空后才重建/释放。4K实际分配33,423,360字节,即31.875MiB;不是每帧累积。分配失败记录HRESULT并回退原路径;未做显存压力或真实OOM测试。正常链路没有像素回读、额外CPU fence等待或睡眠。++由于类布局改变,独立重编译`VideoPresenter.cpp`、`EngineController.cpp`、`EngineControllerImage.cpp`,其余库复用已验71723e0构建并核对SHA。缓存构建与1614项捐赠便携包原件前后不变。GUI EXE SHA256 `3576fce737fd989396c42be15432e82957f8ef6d21e009854f35baf67dd199fa`。++## 本机回归++RTX5070/616.56,单进程串行普通负载,无竞争/压力。每个GPU测试均小于300秒;构建25秒左右。++| 场景 | 结果 |+| --- | --- |+| HDR DLSS自动/直接对照,1X/2X/4X/2X、窗口/全屏、resize/reset、两种销毁顺序 | 每组512原帧、620生成帧;67次640×360无损10位对照,最大RGB码值误差0;D3D12错误0 |+| 3840×2160 HDR交换链,DLSS自动/直接对照 | 呈现/复制/resize/重建通过;相同窗口像素检查误差0、D3D12错误0。是4K缓冲测试,640×360 P010测试输入,不冒充4K NR吞吐或4K物理显示验收 |+| HDR VFG异步CUDA→D3D12、4K交换链、2X/4X/2X | 512原帧、620生成帧、67次窗口无损检查误差0、D3D12错误0 |+| SDR原路径与强制复制路径,DLSS4X/6X/4X | 各114/190/114生成帧;原帧提前呈现等待、resize与双缓冲复用通过;RGB误差0、D3D12错误0 |+| GTA6 4K文件、1080原版NR、DLSS2X,原程序名、缓存开启,复制/直接各40秒启动窗口 | 正常退出、跳源0、开场过期生成帧各1、播放速率中位数1.000;观察窗口长于实际媒体运行时间,不将启动耗时当吞吐 |+| GTA6同设置VFG2X自动路径,30秒启动窗口 | 643生成帧呈现,跳源0、开场过期1,正常退出,无ERROR/FATAL |+| 实际PowerShell启动器,原程序名/路径、私有配置、25秒 | exit0、forcedStop=false、源配置SHA保持;日志ZIP不含私有配置/凭据或像素探针 |++GTA6文件14,115,273,308字节,SHA256 `93db61292353f19aaf6bfa2fbd3a094d1140300785ab2d93b0c06aa7881f8b3f`,没有复制媒体。原生测试中的图像回读只用于测试,不进入交付播放链路。++GTA窗口1280×720的25/26个稳定1秒窗口P95读数中位数:合成GPU0.039/0.034ms(复制/直接),NR6.599/6.736ms,进程显存2641/2637MiB。不能将NR差异当优化收益。4K独立原生测试的合成GPU中位数约0.125–0.128ms(复制)与0.130–0.136ms(直接),属于不同执行窗口的微量读数;不能保证5090的开销,也不宣称复制使算法更快。++失败/修正保留:首个原生用例缺少测试目录shaders,未真正出帧;补齐只读shader硬链接后通过。扩展测试计时时忘记解引用optional导致一次编译失败,修正后重编译测试,GUI不变;首次计时忘记启用完成样本收集,重跑后取得有效数据。Windows PowerShell继承模块路径缺少Get-FileHash;启动器改用.NET SHA与ZIP API后实跑通过。这些不是用户故障的根因。++## 交付与下一次现场验证++本地覆盖测试包:`E:/项目/Veyra/test-packages/fg-flash-fix-20261009/Veyra-2.0.6-HDR-flash-fix-test.zip`;对应完整源码在同目录。只有EXE、启动器、说明/哈希/许可证,不更换DLL/模型。先备份原`veyra_qml_ui.exe`再覆盖,保留原名字和路径。原版保存好同一配置后,用Compatible与Direct启动器分别测试;两个启动器都复制同一原配置,默认手动关闭,保留缓存开关,不改驱动配置。++若Compatible稳定而Direct闪,才支持“最终呈现路径”假说;若只要EXE改名就稳定,优先检查程序级驱动/叠加配置;若两种都稳定,需延长现场观察和检查缓存/配置,不能直接宣布根治。新包对照不含任何像素探针。++现场分析:`E:/项目/Veyra/reports/fg-flash-fix-20261009/field-analysis.json`。构建/测试回执与成功、失败日志:`E:/项目/Veyra/logs/fg-flash-fix-20261009`。原日志及诊断ZIP已无损归档为11,571,275字节的`field-inputs.zip`,CRC及逐项SHA通过,用户原文件保持。独立控制基线保护37个原工作树与495份脏文件。测试产生的默认目录QML/JS缓存按本任务源URL精确识别清理49项、1,695,772字节,其余2207项保持;后续测试缓存保持开启并重定向E盘,参见 [Qt缓存配置](https://doc.qt.io/qt-6.8/qmldiskcache.html)。++原日志副本带只读属性,首次清理停在此处;随后清理本轮两个重复E盘文件被自动审批拒绝,工具只返回`blocked by policy`,未提供更具体原因。未换命令绕过;保留135,317,279字节日志副本及19,798,016字节旧命名EXE,不影响候选包。所有独立产物与清理回执保留E盘。++用户明确要求收尾关机。保存源码、测试包与回执后安排关机,不强制结束未保存的其它应用;系统拦截时不能声称已物理关机。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex f6372f25..906482b1 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,17 @@# WORKLOG+## 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份脏文件。+- 证据:E盘reports/fg-flash-fix-20261009/analyze-field.py流式分析;ZIP CRC/EXE SHA与原诊断一致。约28.6秒实际采集、3278次Present/9点源与输出均无全黑。最终配置与原版末段对齐:5090/617.42、4K HDR59.94、DLSS2X、AMDflow、NR4K+1440p、源PTS。诊断额外18次GPU像素拷贝、改EXE名、私有配置与关QML缓存皆为混杂变量,根因未确认。+- 实现:只改VideoPresenter.h/.cpp,NVIDIA HDR10应用FG自动采用单张GPU最终合成纹理→交换链完整复制;原帧与生成帧共用。4K33,423,360字节固定复用;分配失败记录并回退。SDR/AMD/关闭FG/XeSS直接呈现,媒体时序/算法/倍率/同步保持;无像素读回、新CPU等待/睡眠。诊断环境变量可同EXE关闭复制。为类布局重编译3个直接使用者,未改EngineController逻辑。+- 构建:python -B scripts/acceptance/fg-flash-fix-build.py通过,约25秒;GUI3576fce737fd989396c42be15432e82957f8ef6d21e009854f35baf67dd199fa。之后--tests-only仅重编译测试,GUI不变;原库/GUI/manifest及1614项便携包身份前后SHA不变。+- 验证:fg-flash-fix-test.py串行native hdr-copy-auto-second、hdr-direct-control、hdr-4k-auto/direct、hdr-4k-measured-copy/direct、hdr-vfg-4k-auto及sdr-normal/sdr-forced-copy通过。HDR每组512原帧/620生成帧、67次窗口无损10位对照误差0、D3D12错误0;4K缓冲/resize/rebuild与双销毁顺序通过,非4K物理显示验收。SDR4/6/4X生成114/190/114,误差0。早期一次缺shader测试环境与一次optional计时编译失败已修复,原失败日志保留;计时收集未启用的两组不作为性能数据,随后重跑。+- GTA6源14,115,273,308字节/SHA93db6129…,只读不复制。原程序名/开启缓存、4K输入1080原版NR、DLSS2X复制与直接各40秒启动窗口通过;跳源0、开场生成帧过期各1、播放速率1.000。稳定1秒窗口P95中位数合成0.039/0.034ms、NR6.599/6.736ms,不把NR波动当收益;VFG2X30秒回归通过,643生成呈现/跳源0。普通日志与回执在logs/fg-flash-fix-20261009,性能汇总reports同任务目录。+- 现场启动器Start-HDR-Flash-Fix.ps1保持veyra_qml_ui.exe名字/路径,不改缓存开关,Compatible/Direct复制同一原设置到私有目录。Windows PowerShell继承模块路径缺Get-FileHash时首跑失败;改.NET SHA/ZIP后25秒实际运行exit0、无强停、原配置SHA保持,证据ZIP仅log/json无配置/凭据。原生无损回读只在测试代码。+- 交付:test-packages/fg-flash-fix-20261009的覆盖候选ZIP与完整对应源码;先备份原EXE再覆盖,运行库/模型不变。详细结论与未验边界见docs/FG_FLASH_FIX_REPORT_2026-10-09.md;现场尚未测此候选,不能宣称已根治。收尾控制、ZIP/源码/输入归档哈希及实际清理量由该目录final-check/cleanup回执记录;保存完成后按用户要求安排无强制关机。+- 收尾:现场输入field-inputs.zip=11,571,275字节,CRC及逐项SHA通过;实际清理本任务URL的49项QML/JS缓存1,695,772字节,其余2207项核对。首次删除停在本轮只读日志副本;随后删除两份重复E盘文件被自动审批拒绝(仅blocked by policy,无具体理由),未绕过,155,115,295字节副本保留。打包脚本一次缩进语法检查失败已修正;对抗复查补齐Windows反斜线路径归一化与4项编译源码集合断言,未改已验产品。+## 2026-10-07 VFG本地候选交付完成- 最终归档源码e18942096bb65789a1701f0468acdc64f1be415e,candidate-final构建20.312秒exit0,EXE仍c007c7fc9072a6114eb2479b1880b65f5386a5fd445e6c58513faf3c1328a2b2;仅整理文档/验收脚本,产品与全部已测编译输入一致。diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 71c83315..457cafa5 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -96,6 +96,10 @@ private:PreviewView previousXessView_{};unsigned previousXessWidth_=0,previousXessHeight_=0;Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> rtvs_;+ // 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;unsigned inc_=0;unsigned lastBuffer_=0;bool hasPresented_=false;struct RetainedFrame {@@ -127,6 +131,6 @@ private:struct XessWork {pipeline::FrameIdentity identity{};uint32_t id=0;};std::array<XessWork,4> xessWork_{};size_t xessWorkPosition_=0;- void refresh(ID3D12Device*);+ bool refresh(ID3D12Device*);};}diff --git a/scripts/acceptance/fg-flash-fix-build.py b/scripts/acceptance/fg-flash-fix-build.pynew file mode 100644index 00000000..6a3ffc36--- /dev/null+++ b/scripts/acceptance/fg-flash-fix-build.py@@ -0,0 +1,82 @@+"""Build isolated presenter/layout dependents against immutable current libraries."""+from pathlib import Path+import ctypes,hashlib,json,os,re,subprocess,sys,time++SRC=Path(__file__).resolve().parents[2]+BASE=Path('E:/项目/Veyra');TASK='fg-flash-fix-20261009'+BUILD=BASE/'build/vfg-next-20261007';OUT=BASE/'build'/TASK;LOG=BASE/'logs'/TASK/'build';TMP=BASE/'tmp'/TASK+for p in (OUT,LOG,TMP):p.mkdir(parents=True,exist_ok=True)+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()+shell32=ctypes.WinDLL('shell32',use_last_error=True)+shell32.CommandLineToArgvW.argtypes=[ctypes.c_wchar_p,ctypes.POINTER(ctypes.c_int)]+shell32.CommandLineToArgvW.restype=ctypes.POINTER(ctypes.c_wchar_p)+ctypes.windll.kernel32.LocalFree.argtypes=[ctypes.c_void_p]+def args(text):+ n=ctypes.c_int();p=shell32.CommandLineToArgvW(text,ctypes.byref(n));result=[p[i] for i in range(n.value)];ctypes.windll.kernel32.LocalFree(p);return result+def unescape(s):return s.replace('$ ', ' ').replace('$:', ':').replace('$$', '$')+ninja=(BUILD/'build.ninja').read_text(encoding='utf-8')+gui=re.search(r'^build veyra_qml_ui.exe: .*?(?=\n\n)',ninja,re.M|re.S).group().splitlines()+variables=dict(re.match(r' ([A-Z_]+) = (.*)',line).groups() for line in gui[1:] if re.match(r' ([A-Z_]+) = (.*)',line))+guiobjects=[BUILD/unescape(n) for n in gui[0].split('Release ',1)[1].split(' | ',1)[0].split(' ')]+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])+inputs={}+for p in guiobjects+[BUILD/'veyra_qml_ui.exe',BUILD/'veyra-qml.manifest']:+ assert p.is_file(),p;inputs[str(p)]=sha(p)+for item in args(unescape(variables['LINK_LIBRARIES']))+native:+ if item.lower().endswith('.lib'):+ p=Path(item);p=p if p.is_absolute() else BUILD/p+ if p.is_file():inputs[str(p)]=sha(p)+(LOG/'inputs-before.json').write_text(json.dumps(inputs,indent=2),encoding='utf8')+env=dict(os.environ);env.update(TEMP=str(TMP),TMP=str(TMP))+vcvars=r'C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Auxiliary\Build\vcvars64.bat'+setup=subprocess.run(['cmd.exe','/u','/d','/c','call '+vcvars+' >nul && set'],capture_output=True,text=True,encoding='utf-16-le',check=True,env=env)+for line in setup.stdout.splitlines():+ if '=' in line:+ key,value=line.split('=',1)+ if key and not key.startswith('='):env[key]=value+env.update(TEMP=str(TMP),TMP=str(TMP))+commands=[]+def run(command,name):+ commands.append(command);start=time.monotonic()+ with (LOG/(name+'.log')).open('w',encoding='utf8') as stream:+ r=subprocess.run(command,cwd=BUILD,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=300)+ print(name,'exit',r.returncode,'seconds',round(time.monotonic()-start,2),flush=True)+ if r.returncode:raise SystemExit(r.returncode)+compile_args=args(original[0])+def compile(source,name):+ target=OUT/(name+'.obj')+ command=compile_args[:1]+['/I'+str(SRC/'include')]+[a for a in compile_args[1:] if not a.startswith(('/Fo','/Fd')) and a!='/showIncludes' and not a.endswith('FgPresentationTests.cpp')]+ command+=['/Fo'+str(target),'/Fd'+str(OUT/(name+'.pdb')),str(source)]+ run(command,'compile-'+name);return target+only_tests=sys.argv[1:]==['--tests-only']+objects=[OUT/(file[:-4]+'.obj') for file in ('VideoPresenter.cpp','EngineController.cpp','EngineControllerImage.cpp')] if only_tests else [compile(SRC/'src/engine'/file,file[:-4]) for file in ('VideoPresenter.cpp','EngineController.cpp','EngineControllerImage.cpp')]+if only_tests:+ before=json.loads((LOG/'receipt.json').read_text(encoding='utf8'))+ for rel,digest in before['sources'].items():+ if rel.startswith(('src/','include/')):assert sha(SRC/rel)==digest,rel+test=compile(SRC/'tests/integration/FgPresentationTests.cpp','fg-presentation-tests')+native_link=[]+native_exe=OUT/'fg-presentation-tests.exe'+for a in native:+ if a.endswith('FgPresentationTests.cpp.obj'):native_link+=list(map(str,objects+[test]))+ elif a.startswith('/out:'):native_link.append('/out:'+str(native_exe))+ elif a.startswith('/implib:'):native_link.append('/implib:'+str(OUT/'fg-tests.lib'))+ elif a.startswith('/pdb:'):native_link.append('/pdb:'+str(OUT/'fg-tests.pdb'))+ else:native_link.append(a)+run(native_link,'link-native')+if only_tests:+ for p,digest in inputs.items():assert sha(Path(p))==digest,p+ receipt={'commands':commands,'exeSha256':sha(native_exe),'guiUnchanged':sha(OUT/'veyra-hdr-flash-fix.exe'),'fixtureSha256':sha(SRC/'tests/integration/HdrCopyPresentationFixture.h'),'productObjectsReused':{str(p):sha(p) for p in objects},'inputsUnchanged':inputs}+ (LOG/'native-receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8');print('Native test rebuilt; GUI unchanged',flush=True);raise SystemExit(0)+response=OUT/'gui-link.rsp'+response.write_text('\n'.join(subprocess.list2cmdline([str(p)]) for p in objects+guiobjects)+'\n'+unescape(variables.get('LINK_PATH',''))+'\n'+unescape(variables['LINK_LIBRARIES']),encoding='utf8')+exe=OUT/'veyra-hdr-flash-fix.exe';(OUT/'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(BUILD/'veyra-qml.manifest')) if a.startswith('/MANIFESTINPUT:') else a for a in args(unescape(variables['LINK_FLAGS']))]+run([cmake,'-E','vs_link_exe','--msvc-ver=1944','--intdir='+str(OUT/'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(exe),'/implib:'+str(OUT/'gui.lib'),'/pdb:'+str(OUT/'gui.pdb'),'/version:0.0']+flags,'link-gui')+for p,digest in inputs.items():assert sha(Path(p))==digest,p+receipt={'baseProduct':'71723e0249a17764696796fd204a6eb69d6da276','baseMain':'dbfceabee804cd81bac4a4781f0b7b4cf272902e','commands':commands,'inputsUnchanged':inputs,'sources':{str(p.relative_to(SRC)):sha(p) for p in [SRC/'include/veyra/engine/VideoPresenter.h']+[SRC/'src/engine'/f for f in ('VideoPresenter.cpp','EngineController.cpp','EngineControllerImage.cpp')]+[SRC/'tests/integration/FgPresentationTests.cpp']},'executables':{str(p):{'sha256':sha(p),'bytes':p.stat().st_size} for p in (exe,native_exe)}}+(LOG/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+print('Build and immutable input verification passed',flush=True)diff --git a/scripts/acceptance/fg-flash-fix-control.py b/scripts/acceptance/fg-flash-fix-control.pynew file mode 100644index 00000000..93387f16--- /dev/null+++ b/scripts/acceptance/fg-flash-fix-control.py@@ -0,0 +1,24 @@+"""Read-only preservation/scope checks against this task's immutable start."""+from pathlib import Path+import hashlib,json,subprocess+ROOT=Path(__file__).resolve().parents[2];REPORT=Path('E:/项目/Veyra/reports/fg-flash-fix-20261009')+def git(*args,cwd=ROOT):return subprocess.check_output(['git',*args],cwd=cwd)+before=json.loads((REPORT/'pre-document-state.json').read_text(encoding='utf8'))+errors=[]+for name,expected in before.items():+ p=Path(name)+ names=sorted(set(v.decode('utf8') for v in git('ls-files','-m','-d','--others','--exclude-standard','-z',cwd=p).split(b'\0') if v))+ actual={'head':git('rev-parse','HEAD',cwd=p).decode().strip(),'statusSha256':hashlib.sha256(git('status','--porcelain=v1','-z',cwd=p)).hexdigest(),+ 'dirtyFiles':{n:hashlib.sha256((p/n).read_bytes()).hexdigest() if (p/n).is_file() else None for n in names}}+ if actual!=expected:errors.append(name)+allowed={'AGENTS.md','docs/WORKLOG.md','docs/FG_FLASH_FIX_PLAN_2026-10-09.md','docs/FG_FLASH_FIX_REPORT_2026-10-09.md',+ 'include/veyra/engine/VideoPresenter.h','src/engine/VideoPresenter.cpp','tests/integration/FgPresentationTests.cpp','tests/integration/HdrCopyPresentationFixture.h',+ 'scripts/acceptance/fg-flash-fix-build.py','scripts/acceptance/fg-flash-fix-test.py','scripts/acceptance/fg-flash-fix-control.py','scripts/acceptance/fg-flash-fix-package.py','scripts/diagnostics/Start-HDR-Flash-Fix.ps1'}+changed=set(git('diff','dbfceabee804cd81bac4a4781f0b7b4cf272902e','--name-only').decode('utf8').splitlines())+changed.update(git('ls-files','--others','--exclude-standard').decode('utf8').splitlines())+unexpected=sorted(changed-allowed)+assert not unexpected,unexpected+for n in changed:assert Path(n).suffix.lower() not in ('.dll','.lib','.exe','.pdb','.onnx','.cubin','.hipfb','.zip'),n+receipt={'originalWorktrees':len(before),'originalDirtyFiles':sum(len(v['dirtyFiles']) for v in before.values()),'changedOriginals':errors,'changedScope':sorted(changed),'passed':not errors}+(REPORT/'control.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+print(json.dumps(receipt,ensure_ascii=False));assert not errorsdiff --git a/scripts/acceptance/fg-flash-fix-package.py b/scripts/acceptance/fg-flash-fix-package.pynew file mode 100644index 00000000..dbfb047f--- /dev/null+++ b/scripts/acceptance/fg-flash-fix-package.py@@ -0,0 +1,66 @@+"""Local overlay with exact corresponding source; no runtime/SDK/model upload."""+from pathlib import Path+import hashlib,io,json,os,shutil,subprocess,zipfile+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='fg-flash-fix-20261009'+OUT=BASE/'test-packages'/TASK;OUT.mkdir(parents=True,exist_ok=True)+def sha(p):+ with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()+assert not subprocess.check_output(['git','status','--porcelain'],cwd=ROOT)+commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,encoding='ascii').strip()+exe=BASE/'build'/TASK/'veyra-hdr-flash-fix.exe'+receipt=json.loads((BASE/'logs'/TASK/'build/receipt.json').read_text(encoding='utf8'))+assert sha(exe)==receipt['executables'][str(exe)]['sha256']+productSources={rel.replace('\\','/'):digest for rel,digest in receipt['sources'].items() if rel.replace('\\','/').startswith(('src/','include/'))}+assert set(productSources)=={'include/veyra/engine/VideoPresenter.h','src/engine/VideoPresenter.cpp','src/engine/EngineController.cpp','src/engine/EngineControllerImage.cpp'}+for rel,digest in productSources.items():assert sha(ROOT/rel)==digest,rel+source=OUT/'Veyra-2.0.6-HDR-flash-fix-source.zip';assert not source.exists()+subprocess.run(['git','archive','--format=zip','--prefix=Veyra-hdr-flash-fix/','--output='+str(source),'HEAD'],cwd=ROOT,check=True)+with zipfile.ZipFile(source) as z:+ assert z.testzip() is None+ for n in z.namelist():assert Path(n).suffix.lower() not in ('.dll','.lib','.exe','.pdb','.onnx','.cubin','.hipfb'),n+ for rel,digest in productSources.items():+ assert z.read('Veyra-hdr-flash-fix/'+rel).replace(b'\r\n',b'\n')==(ROOT/rel).read_bytes().replace(b'\r\n',b'\n'),rel+stage=OUT/'overlay';stage.mkdir(exist_ok=False)+shutil.copy2(exe,stage/'veyra_qml_ui.exe')+shutil.copy2(ROOT/'scripts/diagnostics/Start-HDR-Flash-Fix.ps1',stage/'Start-HDR-Flash-Fix.ps1')+os.link(source,stage/source.name)+for name in ('LICENSE','LICENSE.md','LICENSE.txt','THIRD_PARTY_NOTICES.md'):+ if (ROOT/name).is_file():shutil.copy2(ROOT/name,stage/name)+for name,variant in [('01-Test-Compatible.cmd','Compatible'),('02-Test-Direct-Control.cmd','Direct')]:+ (stage/name).write_text('@echo off\npowershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Start-HDR-Flash-Fix.ps1" -AppDirectory "%~dp0." -Variant '+variant+'\npause\n',encoding='ascii')+text='''Veyra 2.0.6 · HDR补帧闪黑兼容候选(2026-10-09)++这是可回退测试候选,本机验证通过;用户RTX5090/采集卡上的闪黑是否消失仍待复测,不能认定已经根治。++使用:+1. 关闭所有Veyra。先把原目录的veyra_qml_ui.exe复制为veyra_qml_ui.original.exe.bak保留,再将本包覆盖到完整2.0.6 NVIDIA便携目录。不要改EXE名字,不要放到缺少Qt/运行库的空目录直接运行。+2. 原版提前保存好同一输入与画质/补帧设置。双击01-Test-Compatible.cmd,使用原来会闪的4K HDR采集、源时间戳和补帧设置。默认不会定时退出,测完手动关闭即可。+3. 双击02-Test-Direct-Control.cmd,用同一输入/设置再测。它运行同一个EXE、同一路径,只关闭新复制路径。两个启动器都从原设置复制到私有目录,测试内修改不会写回原设置;不要在两次之间改驱动配置。+4. 日志与回执自动打包在logs/hdr-flash-*.zip,只包含日志,不含私有配置/凭据。把两次ZIP与是否闪的结果一起反馈。Compatible不闪、Direct闪才支持呈现路径假说;两者都不闪仍不能认定根治。++改变:NVIDIA HDR10 + DLSS/VFG/应用侧FSR补帧,先GPU合成到独立纹理再复制到交换链。默认SDR、无补帧、AMD、XeSS保持直接呈现。没有像素采样、额外CPU等待或自动降倍率。4K额外纹理固定约31.9MiB。+本机GTA6 4K输入/1080p原版NR/DLSS2X测试:两路径播放速率1.000、跳源0;1280×720合成GPU窗口P95中位数0.034→0.039ms。该数据不能外推5090或面板扫描。++基于当前main,包含此前已经合入的VFG优化。Direct只代表当前main原呈现路径,不能完全替代旧2.0.6整包对照。+没有更换运行库/模型,没有修改NVIDIA App/RTSS或驱动设置。若只有改EXE名字就不闪,需要另查程序级配置,不能归功于本候选。++回退:关闭Veyra,把备份EXE复制回veyra_qml_ui.exe即可;DLL和原用户设置保持。标准双击EXE会按正常产品行为使用原设置,两个测试启动器则使用私有副本。+精确完整源码:同包Veyra-2.0.6-HDR-flash-fix-source.zip;源码和构建身份见hdr-flash-fix-manifest.json。完整2.0.6依赖/许可证沿用原包。+'''+(stage/'使用说明.txt').write_text(text,encoding='utf-8-sig')+shutil.copy2(ROOT/'docs/FG_FLASH_FIX_REPORT_2026-10-09.md',stage/'排查与测试报告.md')+manifest={'kind':'local-hdr-flash-compatibility-candidate','version':'2.0.6','sourceCommit':commit,'baseMain':'dbfceabee804cd81bac4a4781f0b7b4cf272902e','baseProduct':'71723e0249a17764696796fd204a6eb69d6da276','executableSha256':sha(exe),'sourceArchive':source.name,'sourceSha256':sha(source),'runtimeIncluded':False,'pixelProbeIncluded':False,'field5090Validated':False}+(stage/'hdr-flash-fix-manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf8')+files={p.name:sha(p) for p in stage.iterdir() if p.is_file()}+target=OUT/'Veyra-2.0.6-HDR-flash-fix-test.zip';assert not target.exists()+with zipfile.ZipFile(target,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=6) as z:+ for name in sorted(files):z.write(stage/name,name,compress_type=zipfile.ZIP_STORED if name.endswith('.zip') else zipfile.ZIP_DEFLATED)+with zipfile.ZipFile(target) as z:+ assert z.testzip() is None+ for name,digest in files.items():assert hashlib.sha256(z.read(name)).hexdigest()==digest,name+ assert z.namelist().count('veyra_qml_ui.exe')==1+ assert json.loads(z.read('hdr-flash-fix-manifest.json'))==manifest+assert sha(stage/'veyra_qml_ui.exe')==sha(BASE/'tests'/TASK/'app/veyra_qml_ui.exe')+result={'sourceCommit':commit,'package':{'path':str(target),'bytes':target.stat().st_size,'sha256':sha(target),'files':files},'source':{'path':str(source),'bytes':source.stat().st_size,'sha256':sha(source)},'passed':True}+(BASE/'reports'/TASK/'package-check.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')+print(json.dumps({k:v for k,v in result.items() if k!='package'},ensure_ascii=False));print('Package:',target.stat().st_size,sha(target))diff --git a/scripts/acceptance/fg-flash-fix-test.py b/scripts/acceptance/fg-flash-fix-test.pynew file mode 100644index 00000000..883a66f1--- /dev/null+++ b/scripts/acceptance/fg-flash-fix-test.py@@ -0,0 +1,95 @@+"""Serial, bounded tests. One shared task app, independent profiles/logs/TEMP."""+from pathlib import Path+import hashlib,json,os,re,shutil,statistics,subprocess,sys,time+import psutil+SRC=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='fg-flash-fix-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 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']+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);os.link(DONOR/rel,p)+ (APP/'runtime_local').mkdir(exist_ok=True)+exe=APP/'veyra_qml_ui.exe'+swap=APP/'candidate.swap';shutil.copy2(BUILD/'veyra-hdr-flash-fix.exe',swap);os.replace(swap,exe)+mode,label=sys.argv[1:3];assert mode in ('native','gui') and re.fullmatch('[a-z0-9-]+',label)+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}'+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'))+copy=sys.argv[3] if len(sys.argv)>3 else 'auto'+assert copy in ('auto','0','1')+if copy!='auto':env['VEYRA_TEST_HDR_PRESENT_COPY']=copy+main=APP/'qml/Veyra/Main.qml';original=main.read_bytes();mutated=False+if mode=='native':+ testmode=sys.argv[4] if len(sys.argv)>4 else 'hdr-copy'+ if testmode=='hdr-copy-vfg':env['VEYRA_TEST_HDR_VFG']='1';env['VEYRA_TEST_HDR_4K_WINDOW']='1';testmode='hdr-copy'+ if testmode=='hdr-copy-4k':env['VEYRA_TEST_HDR_4K_WINDOW']='1';testmode='hdr-copy'+ command=[str(BUILD/'fg-presentation-tests.exe'),str(case),str(APP/'runtime/experimental')]+ if testmode!='sdr':command.append(testmode)+else:+ backend=sys.argv[4] if len(sys.argv)>4 else 'dlss';assert backend in ('dlss','vfg','xess','off')+ seconds=int(sys.argv[5]) if len(sys.argv)>5 else 35;assert 15<=seconds<=90+ profile=BASE/'tests'/TASK/'profiles'/label+ shutil.copytree(BASE/'tests/vfg-next-20261007/candidate-cold/profile',profile)+ prefs=json.loads((profile/'qml-preferences.v1.json').read_text(encoding='utf8'));prefs['positions']={};prefs['gpuPriority']='normal'+ (profile/'qml-preferences.v1.json').write_text(json.dumps(prefs),encoding='utf8')+ # Fresh private session. Configure the existing bridge, then open the media.+ timer='''+ Timer { interval: 700; running: true; repeat: false; onTriggered: {+ veyra.fgEnabled = false; veyra.nrEnabled = true; veyra.fgMultiplier = 2;+ veyra.fgBackendName = "%s"; veyra.contentRate = 0;+ veyra.fgEnabled = %s;+ veyra.openPath("E:/Ai/知识/小七姐/GTAVI_An_Extended_Look_4K_Native.mp4");+ } }+'''%(backend if backend!='off' else 'dlss','true' if backend!='off' else 'false')+ # Match the source invocation used by the earlier private QML smoke tests.+ text=original.decode('utf8');assert text.count(' id: root')==1+ modified=text.replace(' id: root',' id: root'+timer,1);swap=main.with_suffix('.test-swap');swap.write_text(modified,encoding='utf8');os.replace(swap,main);mutated=True+ (case/'Main.test.qml').write_text(modified,encoding='utf8')+ command=[str(exe),'--data-dir',str(profile),'--page','min','--size','1280x800','--exit-after',str(seconds*1000)]+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('.test-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():+ engine=(case/'engine.log').read_text(encoding='utf8',errors='replace')+ text=engine+'\n'+'\n'.join(l for l in text.splitlines() if l not in engine)+errors=[l for l in text.splitlines() if re.search(r'\[ERROR\s*\]|\[FATAL\s*\]|ReferenceError:|TypeError:|D3D12 ERROR|D3D12 CORRUPTION',l)]+receipt={'mode':mode,'command':command,'copyOverride':copy,'exit':r.returncode,'elapsedSeconds':time.monotonic()-begin,'exeSha256':sha(Path(command[0])),'errors':errors,'copyEvents':[l for l in text.splitlines() if '[present-copy]' in l],'summaries':[l for l in text.splitlines() if re.match(r'^(HDR_COPY|PRESENTATION|EARLY_ORIGINAL|D3D12 errors)',l)]}+if mode=='gui':+ receipt['graphEvents']=[l for l in text.splitlines() if '[graph]' in l and ('processing=' in l or 'initialized src' in l)]+ receipt['validity']=[l for l in text.splitlines() if '[fg-validity]' in l][-3:]+ receipt['rates']=[l for l in text.splitlines() if '[frame-rate]' in l][-5:]+ receipt['stageTimings']=[l for l in text.splitlines() if '[player-timing]' in l][-5:]+ receipt['closed']=[l for l in text.splitlines() if '[frame-flow] state=closed' in l]+ receipt['presentCosts']=[l for l in text.splitlines() if '[present-cost]' in l][-8:]+receipt['passed']=r.returncode==0 and not errors and (any('SUMMARY' in l and 'pass=1' in l for l in receipt['summaries']) if mode=='native' and testmode=='hdr-copy' else True)+if mode=='gui':+ receipt['passed']=receipt['passed'] and any('processing=1920x1080' in l for l in receipt['graphEvents']) and bool(receipt['closed'])+ if backend!='off':receipt['passed']=receipt['passed'] and any(re.search(r' valid=[1-9]\d* invalid=0',l) for l in receipt['validity'])+ if copy!='auto':receipt['passed']=receipt['passed'] and any(('enabled='+('true' if copy=='1' else 'false')) in l for l in receipt['copyEvents'])+verify();receipt['donorUnchanged']=True+(case/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+print(json.dumps(receipt,ensure_ascii=False,indent=2),flush=True)+raise SystemExit(0 if receipt['passed'] else 1)diff --git a/scripts/diagnostics/Start-HDR-Flash-Fix.ps1 b/scripts/diagnostics/Start-HDR-Flash-Fix.ps1new file mode 100644index 00000000..e6b16f9f--- /dev/null+++ b/scripts/diagnostics/Start-HDR-Flash-Fix.ps1@@ -0,0 +1,91 @@+param(+ [string]$AppDirectory = $PSScriptRoot,+ [string]$ProfileSource = '',+ [string]$OutputDirectory = '',+ [string]$Source = '',+ [ValidateSet('Compatible','Direct')][string]$Variant = 'Compatible',+ [ValidateRange(0,3600)][int]$DurationSeconds = 0+)+$ErrorActionPreference = 'Stop'+function File-Sha256([string]$Path) {+ $stream=[IO.File]::OpenRead($Path);$hasher=[Security.Cryptography.SHA256]::Create()+ try { return [BitConverter]::ToString($hasher.ComputeHash($stream)).Replace('-','') }+ finally { $hasher.Dispose();$stream.Dispose() }+}+$app = [IO.Path]::GetFullPath($AppDirectory)+$player = Join-Path $app 'veyra_qml_ui.exe'+foreach ($required in @($player,(Join-Path $app 'qt.conf'),(Join-Path $app 'Qt6Core.dll'),(Join-Path $app 'qml/Veyra/Main.qml'))) {+ if (-not (Test-Path -LiteralPath $required -PathType Leaf)) { throw 'Place this overlay in a complete Veyra 2.0.6 NVIDIA folder first. Back up the original EXE.' }+}+$manifest = Join-Path $app 'hdr-flash-fix-manifest.json'+if (Test-Path -LiteralPath $manifest -PathType Leaf) {+ $expected = (Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json).executableSha256+ if ((File-Sha256 $player) -ne $expected) { throw 'The EXE is not the matching HDR flash candidate. Runtime DLL replacement remains allowed.' }+}+if (@(Get-Process -Name 'veyra_qml_ui','veyra-flash-diagnostic','veyra-hdr-flash-fix','flash-pixel-probe' -ErrorAction SilentlyContinue).Count -gt 0) { throw 'Close other Veyra players before this test.' }+if ([string]::IsNullOrWhiteSpace($ProfileSource)) { $ProfileSource = Join-Path $app 'runtime_local/user-data-2.0.0' }+if ([string]::IsNullOrWhiteSpace($OutputDirectory)) { $OutputDirectory = Join-Path $app ('logs/hdr-flash-' + $Variant + '-' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff')) }+$output = [IO.Path]::GetFullPath($OutputDirectory)+if (Test-Path -LiteralPath $output) { throw 'Output already exists; refusing to overwrite evidence.' }+$profile = Join-Path $output 'private-profile';$tmp = Join-Path $output 'tmp'+$null = New-Item -ItemType Directory -Path $profile,$tmp -Force+$copied = @()+foreach ($name in @('chain-session.v1','chain-session.v1.vfg','qml-preferences.v1.json','ui-session.v1','presets.v1','node-anchors.json')) {+ $from = Join-Path $ProfileSource $name+ if (Test-Path -LiteralPath $from -PathType Leaf) {+ $digest = File-Sha256 $from+ Copy-Item -LiteralPath $from -Destination (Join-Path $profile $name)+ $copied += [pscustomobject]@{path=$from;sha256=$digest}+ }+}+$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') }+$arguments = @('--data-dir',$profile,'--page','pro')+if ($DurationSeconds -gt 0) { $arguments += @('--exit-after',($DurationSeconds*1000).ToString()) }+if (-not [string]::IsNullOrWhiteSpace($Source)) { $arguments += $Source }+if (@($arguments | Where-Object { $_.Contains('"') -or $_.EndsWith('\') }).Count -gt 0) { throw 'Unsupported argument quoting.' }+$quoted = @($arguments | ForEach-Object { '"' + $_ + '"' })+$result=1;$forcedStop=$false+try {+ $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') }+ # 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)+ $process=Start-Process -FilePath $player -ArgumentList $quoted -WorkingDirectory $app -PassThru -WindowStyle Normal `+ -RedirectStandardOutput (Join-Path $output 'console.log') -RedirectStandardError (Join-Path $output 'stderr.log')+ $null=$process.Handle+ if ($DurationSeconds -eq 0) { $process.WaitForExit() }+ elseif (-not $process.WaitForExit(($DurationSeconds+35)*1000)) { $forcedStop=$true;Stop-Process -Id $process.Id -Force;$process.WaitForExit() }+ $process.WaitForExit();$process.Refresh();$result=$process.ExitCode+ if ($forcedStop) { $result=124 } elseif ($null -eq $result) { $result=125 }+} finally {+ foreach ($name in $envNames) { [Environment]::SetEnvironmentVariable($name,$savedEnv[$name],'Process') }+}+$unchanged=$true+foreach ($item in $copied) {+ if (-not (Test-Path -LiteralPath $item.path -PathType Leaf) -or (File-Sha256 $item.path) -ne $item.sha256) { $unchanged=$false }+}+$receipt=[pscustomobject]@{+ exit=$result;forcedStop=$forcedStop;variant=$Variant;executable=$player;fileName='veyra_qml_ui.exe';+ executableSha256=(File-Sha256 $player);+ privateProfile=$profile;sourceProfileUnchanged=$unchanged;durationLimitSeconds=$DurationSeconds;+ qmlDiskCacheInherited=[Environment]::GetEnvironmentVariable('QML_DISABLE_DISK_CACHE','Process');+ pixelProbeIncluded=$false+}+$receipt | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $output 'test-receipt.json') -Encoding UTF8+$evidence=@(Get-ChildItem -LiteralPath $output -File | Where-Object { $_.Extension -in '.log','.json' } | Select-Object -ExpandProperty FullName)+if ($evidence.Count -gt 0) {+ Add-Type -AssemblyName System.IO.Compression+ Add-Type -AssemblyName System.IO.Compression.FileSystem+ $zipStream=[IO.File]::Open(($output+'.zip'),[IO.FileMode]::CreateNew)+ $zip=[IO.Compression.ZipArchive]::new($zipStream,[IO.Compression.ZipArchiveMode]::Create)+ try { foreach ($file in $evidence) { $null=[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$file,[IO.Path]::GetFileName($file),[IO.Compression.CompressionLevel]::Optimal) } }+ finally { $zip.Dispose();$zipStream.Dispose() }+ Write-Host ('Evidence: '+$output+'.zip')+}+if (-not $unchanged) { throw 'The original profile changed during the test; evidence is not a controlled comparison.' }+exit $resultdiff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 7456cc99..7b8d1ca9 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -88,18 +88,57 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enhpipeline::makeUav(ctx.device(),presentMotion_[i].Get(),DXGI_FORMAT_R16G16_FLOAT,{heap.ptr+size_t(i*2+1)*presentMotionPass_.increment});}}- D3D12_DESCRIPTOR_HEAP_DESC hd{};hd.Type=D3D12_DESCRIPTOR_HEAP_TYPE_RTV;hd.NumDescriptors=3;+ // Field 2026-10-09: HDR application FG flashes on an RTX5090 while the+ // 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;+ }+ 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);refresh(ctx.device());+ inc_=ctx.device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);if(!refresh(ctx.device()))return false;+ veyra::log::info("present-copy",std::format("enabled={} format={} extent={}x{} (GPU-only final composition; no pixel readback)",copyBeforePresent_,unsigned(graph.outputFormat()),sink_.bufferWidth(),sink_.bufferHeight()));for(unsigned i=0;i<pipeline::kOutputPoolSlots;++i)pipeline::makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*pass_.increment});for(unsigned i=0;i<4;++i)pipeline::makeSrv(ctx.device(),i<2?graph.sourceReference(i):graph.baseReference(i-2),DXGI_FORMAT_R16G16B16A16_FLOAT,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i+pipeline::kOutputPoolSlots)*pass_.increment});return true;}-void VideoPresenter::refresh(ID3D12Device* device){+bool VideoPresenter::refresh(ID3D12Device* device){// ResizeBuffers keeps the swapchain object and may retain its metadata.// Request a resend without forgetting an active hint that must be cleared// if the user disables metadata immediately after a resize.- metadataDirty_=true;metadataAttempt_={};for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}+ metadataDirty_=true;metadataAttempt_={};+ Microsoft::WRL::ComPtr<ID3D12Resource> bb;+ for(unsigned i=0;i<3;++i){+ bb.Reset();const HRESULT hr=sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb));+ if(FAILED(hr)){veyra::log::error("present-copy",std::format("GetBuffer index={} hr=0x{:X}",i,unsigned(hr)));return false;}+ device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});+ }+ if(copyBeforePresent_){+ auto desc=bb->GetDesc();+ if(!compositeTarget_||compositeTarget_->GetDesc().Width!=desc.Width||compositeTarget_->GetDesc().Height!=desc.Height||compositeTarget_->GetDesc().Format!=desc.Format){+ D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_DEFAULT;+ desc.Flags=D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;+ D3D12_CLEAR_VALUE clear{};clear.Format=desc.Format;clear.Color[3]=1;+ Microsoft::WRL::ComPtr<ID3D12Resource> target;+ const HRESULT hr=device->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&desc,D3D12_RESOURCE_STATE_COMMON,&clear,IID_PPV_ARGS(&target));+ if(FAILED(hr)){+ veyra::log::warn("present-copy",std::format("composition allocation {}x{} format={} hr=0x{:X}; using direct presentation",desc.Width,desc.Height,unsigned(desc.Format),unsigned(hr)));+ compositeTarget_.Reset();copyBeforePresent_=false;+ }else{+ target->SetName(L"Veyra HDR final composition");compositeTarget_=std::move(target);+ const auto allocation=device->GetResourceAllocationInfo(0,1,&desc);+ veyra::log::info("present-copy",std::format("composition allocation {}x{} format={} bytes={} surfaces=1",desc.Width,desc.Height,unsigned(desc.Format),allocation.SizeInBytes));+ }+ }+ if(compositeTarget_)device->CreateRenderTargetView(compositeTarget_.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(3)*inc_});+ }+ return true;+}bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& sharedRing,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,bool referencesValid,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view,int64_t sourcePts100ns,bool retainUnchanged) {auto& ring=presentationQueue_?presentationRing_:sharedRing;auto* fence=presentationFence_?presentationFence_.Get():ctx.fence();@@ -163,7 +202,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&// A capture hook may temporarily retain a DXGI buffer. Keep the old// valid buffers and let DXGI scale them until a later resize succeeds.if(!sink_.currentBackBuffer()||FAILED(ctx.device()->GetDeviceRemovedReason()))return false;- refresh(ctx.device());lastResize_=now;xessWasEnabled_=false;+ if(!refresh(ctx.device()))return false;lastResize_=now;xessWasEnabled_=false;}const auto resizeEnd=std::chrono::steady_clock::now();if(auto* xess=sink_.xess()){@@ -182,11 +221,13 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&gpuTimer_.frame(identity.sourceFrameId?identity:pipeline::FrameIdentity{0,0,submittedCount()+1},fence);gpuTimer_.mark(list,diagnostics::GpuStage::Blit);uint32_t backBufferIndex=0;auto* source=generated?graph.generatedFrameResource(slot):graph.videoFrameResource(slot);auto* bb=sink_.currentBackBuffer(&backBufferIndex);if(!bb)return false;+ auto* renderTarget=copyBeforePresent_?compositeTarget_.Get():bb;+ if(!source||!renderTarget)return false;D3D12_RESOURCE_BARRIER barriers[2]{};for(auto& b:barriers){b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;}barriers[0].Transition.pResource=source;barriers[0].Transition.StateAfter=D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;- barriers[1].Transition.pResource=bb;barriers[1].Transition.StateAfter=D3D12_RESOURCE_STATE_RENDER_TARGET;list->ResourceBarrier(2,barriers);- D3D12_CPU_DESCRIPTOR_HANDLE rtv{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(backBufferIndex)*inc_};+ barriers[1].Transition.pResource=renderTarget;barriers[1].Transition.StateAfter=D3D12_RESOURCE_STATE_RENDER_TARGET;list->ResourceBarrier(2,barriers);+ D3D12_CPU_DESCRIPTOR_HANDLE rtv{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(copyBeforePresent_?3:backBufferIndex)*inc_};const float black[4]={0,0,0,1};list->ClearRenderTargetView(rtv,black,0,nullptr);list->OMSetRenderTargets(1,&rtv,FALSE,nullptr);// DXGI stretches the retained buffer while the native workspace unfolds.// Compute contain in CURRENT client coordinates, then map back to buffer@@ -228,7 +269,18 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);if(veyra::log::verboseFrameLogs())veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));}- for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(2,barriers);+ for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);+ if(copyBeforePresent_)barriers[1].Transition.StateAfter=D3D12_RESOURCE_STATE_COPY_SOURCE;+ list->ResourceBarrier(2,barriers);+ if(copyBeforePresent_){+ D3D12_RESOURCE_BARRIER copy{};copy.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ copy.Transition.pResource=bb;copy.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;+ copy.Transition.StateBefore=D3D12_RESOURCE_STATE_PRESENT;copy.Transition.StateAfter=D3D12_RESOURCE_STATE_COPY_DEST;+ list->ResourceBarrier(1,©);list->CopyResource(bb,renderTarget);+ copy.Transition.StateBefore=D3D12_RESOURCE_STATE_COPY_DEST;copy.Transition.StateAfter=D3D12_RESOURCE_STATE_PRESENT;+ barriers[1].Transition.StateBefore=D3D12_RESOURCE_STATE_COPY_SOURCE;barriers[1].Transition.StateAfter=D3D12_RESOURCE_STATE_COMMON;+ list->ResourceBarrier(1,&barriers[1]);list->ResourceBarrier(1,©);+ }// Interpolation region for the XeSS present-sink FG backend.// It must follow the PresentBlit view mapping (contain * zoom, view// center) rather than assuming the default centered view: the previous@@ -347,7 +399,7 @@ void VideoPresenter::close(){xessInputId_=0;xessWork_={};xessWorkPosition_=0;reflex_.close();reflexFrame_=0;if(presentationRing_.initialized())presentationRing_.drainQueue();- hasPresented_=false;gpuTimer_.close();rtvs_.Reset();pass_={};sink_.shutdown();+ hasPresented_=false;gpuTimer_.close();compositeTarget_.Reset();copyBeforePresent_=false;rtvs_.Reset();pass_={};sink_.shutdown();presentMotionPass_={};presentMotion_={};previousXessWidth_=previousXessHeight_=0;presentationRing_.shutdown();presentationFence_.Reset();presentationQueue_.Reset();if(presentationEvent_){CloseHandle(presentationEvent_);presentationEvent_=nullptr;}diff --git a/tests/integration/FgPresentationTests.cpp b/tests/integration/FgPresentationTests.cppindex 42ac2b91..661e5d63 100644--- a/tests/integration/FgPresentationTests.cpp+++ b/tests/integration/FgPresentationTests.cpp@@ -11,12 +11,14 @@ extern "C" {#include <libavutil/frame.h>#include <libavutil/pixfmt.h>}+#include "HdrCopyPresentationFixture.h"int wmain(int argc,wchar_t** argv){using namespace veyra;if((argc<2||argc>4)||FAILED(CoInitializeEx(nullptr,COINIT_MULTITHREADED)))return 2;const bool displaySync=argc==4&&std::wstring_view(argv[3])==L"display-sync";- const bool temporal=argc==4&&!displaySync;+ const bool hdrCopy=argc==4&&std::wstring_view(argv[3])==L"hdr-copy";+ const bool temporal=argc==4&&!displaySync&&!hdrCopy;const bool exact=temporal&&std::wstring_view(argv[3])==L"temporal-exact";if(temporal&&!exact&&std::wstring_view(argv[3])!=L"temporal")return 2;const auto runtimePath=argc>=3?std::filesystem::absolute(argv[2]):std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia";@@ -32,6 +34,7 @@ int wmain(int argc,wchar_t** argv){if(frame){frame->format=AV_PIX_FMT_RGBA;frame->width=640;frame->height=360;frame->color_range=AVCOL_RANGE_JPEG;frame->color_trc=AVCOL_TRC_IEC61966_2_1;}ok=ok&&frame&&av_frame_get_buffer(frame,32)>=0;unsigned cycle=0;+ if(hdrCopy)ok=ok&&hdrCopyPresentation(ctx,ring,window,runtimePath);if(displaySync){// Real windowed and borderless-fullscreen swapchains, including both// latency-queue settings. The runner checks actual Present flags in@@ -74,7 +77,7 @@ int wmain(int argc,wchar_t** argv){}}for(unsigned multiplier:{4u,6u,4u}){- if(temporal||displaySync)break;+ if(temporal||displaySync||hdrCopy)break;if(!ok)break;++cycle;pipeline::EnhanceGraphDesc desc;desc.sourceWidth=desc.workWidth=640;desc.sourceHeight=desc.workHeight=360;diff --git a/tests/integration/HdrCopyPresentationFixture.h b/tests/integration/HdrCopyPresentationFixture.hnew file mode 100644index 00000000..b6f9c9fb--- /dev/null+++ b/tests/integration/HdrCopyPresentationFixture.h@@ -0,0 +1,98 @@+#pragma once+#include <cstring>++// Lossless readback belongs to this bounded integration test only. Playback+// uses neither this helper nor the full-image CPU wait below.+static bool readHdrWords(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing& ring,+ ID3D12Resource* texture,std::vector<uint32_t>& words,unsigned& w,unsigned& h){+ if(!texture||texture->GetDesc().Format!=DXGI_FORMAT_R10G10B10A2_UNORM)return false;+ const auto desc=texture->GetDesc();D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};UINT64 total=0;+ ctx.device()->GetCopyableFootprints(&desc,0,1,0,&footprint,nullptr,nullptr,&total);+ D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC buffer{};buffer.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;buffer.Width=total;+ buffer.Height=1;buffer.DepthOrArraySize=buffer.MipLevels=1;buffer.SampleDesc.Count=1;buffer.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ Microsoft::WRL::ComPtr<ID3D12Resource> readback;+ if(FAILED(ctx.device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&buffer,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback))))return false;+ veyra::Status status=veyra::Status::Ok;unsigned slot=0;auto* list=ring.acquireNext(slot,status);if(!list)return false;+ D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barrier.Transition={texture,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE};list->ResourceBarrier(1,&barrier);+ D3D12_TEXTURE_COPY_LOCATION src{},dst{};src.pResource=texture;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ dst.pResource=readback.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=footprint;+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return false;+ void* mapped=nullptr;D3D12_RANGE range{0,size_t(total)};if(FAILED(readback->Map(0,&range,&mapped)))return false;+ w=unsigned(desc.Width);h=desc.Height;words.resize(size_t(w)*h);+ for(unsigned y=0;y<h;++y)std::memcpy(words.data()+size_t(y)*w,static_cast<uint8_t*>(mapped)+footprint.Offset+size_t(y)*footprint.Footprint.RowPitch,size_t(w)*4);+ D3D12_RANGE empty{0,0};readback->Unmap(0,&empty);return true;+}++static bool hdrCopyPresentation(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing& ring,+ HWND window,const std::filesystem::path& runtime){+ using namespace veyra;+ pipeline::EnhanceGraph graph(ctx,ring);engine::VideoPresenter presenter;+ AVFrame* frame=av_frame_alloc();if(!frame)return false;+ frame->format=AV_PIX_FMT_P010LE;frame->width=640;frame->height=360;+ frame->color_range=AVCOL_RANGE_MPEG;frame->colorspace=AVCOL_SPC_BT2020_NCL;+ frame->color_primaries=AVCOL_PRI_BT2020;frame->color_trc=AVCOL_TRC_SMPTE2084;+ bool ok=av_frame_get_buffer(frame,32)>=0;+ MONITORINFO monitor{sizeof(monitor)};ok=ok&&GetMonitorInfoW(MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST),&monitor);+ unsigned real=0,generated=0,pixelChecks=0;int maxError=0;+ const bool buffers4k=GetEnvironmentVariableW(L"VEYRA_TEST_HDR_4K_WINDOW",nullptr,0)>0;+ for(unsigned multiplier:{1u,2u,4u,2u})for(bool full:{false,true}){+ if(!ok)break;+ SetWindowPos(window,nullptr,0,0,full?(buffers4k?3840:monitor.rcMonitor.right-monitor.rcMonitor.left):640,full?(buffers4k?2160:monitor.rcMonitor.bottom-monitor.rcMonitor.top):360,SWP_NOZORDER|SWP_NOACTIVATE);+ ShowWindow(window,SW_SHOWNOACTIVATE);+ pipeline::EnhanceGraphDesc desc;desc.sourceWidth=desc.workWidth=640;desc.sourceHeight=desc.workHeight=360;+ if(GetEnvironmentVariableW(L"VEYRA_TEST_HDR_VFG",nullptr,0)>0){desc.frameGenerationBackend=engine::FrameGenerationBackend::Vfg;desc.vfgAsyncSubmission=true;desc.vfgQuality=1;}+ desc.enableNr=desc.enableSr=false;desc.enableFg=multiplier>1;desc.fgMultiplier=std::max(2u,multiplier);+ desc.hdrInput=desc.hdrOutput=true;desc.captureBitDepth=10;desc.runtimeAbsPath=runtime.wstring();+ ok=graph.initialize(desc)&&graph.createViews()&&presenter.open(ctx,window,graph);+ if(!ok)break;+ presenter.recordGpuTimings();+ std::vector<double> blitTimes;+ const auto collect=[&]{for(const auto& sample:presenter.takeGpuTimings(ctx.fence())){+ 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);+ for(unsigned i=0;ok&&i<64;++i){+ 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);+ }+ for(unsigned y=0;y<360;++y){auto* row=reinterpret_cast<uint16_t*>(frame->data[0]+size_t(y)*frame->linesize[0]);+ for(unsigned x=0;x<640;++x)row[x]=uint16_t((400+i+(x/80)%2*60)<<6);}+ for(unsigned y=0;y<180;++y){auto* row=reinterpret_cast<uint16_t*>(frame->data[1]+size_t(y)*frame->linesize[1]);for(unsigned x=0;x<640;++x)row[x]=uint16_t(512<<6);}+ const auto start=std::chrono::steady_clock::now();+ while(!graph.nextFrameSlotAvailable()&&std::chrono::steady_clock::now()-start<std::chrono::seconds(2))Sleep(1);+ pipeline::EnhanceGraph::FrameOutputs out;+ ok=graph.nextFrameSlotAvailable()&&graph.process(frame,i*16.6827,i==0||i==32,out,i+1)&&ring.waitIdle()&&graph.resolveGeneration(out);+ for(unsigned j=0;ok&&j<out.batch.count;++j){+ const auto& item=out.batch.frames[j];const bool gen=item.kind==pipeline::FrameKind::Generated;+ if(gen&&item.validity!=pipeline::GenerationValidity::Valid)continue;+ 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){+ 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){+ for(size_t p=0;p<actual.size();++p)for(unsigned c=0;c<3;++c)+ maxError=std::max(maxError,std::abs(int((actual[p]>>(10*c))&1023)-int((expected[p]>>(10*c))&1023)));+ ok=maxError<=1;++pixelChecks;+ }+ }+ }+ }+ // Exercise both teardown orders. HDR/no-FG uses the shared queue.+ ok=ring.drainQueue()&&ok;+ auto last=presenter.presentedResourceForTest();last.Reset();collect();+ std::sort(blitTimes.begin(),blitTimes.end());+ if(!blitTimes.empty())std::cout<<"HDR_COPY_COST multiplier="<<multiplier<<" full="<<full<<" buffers4k="<<buffers4k+ <<" samples="<<blitTimes.size()<<" medianGpuMs="<<blitTimes[blitTimes.size()/2]<<" p95GpuMs="<<blitTimes[std::min(blitTimes.size()-1,blitTimes.size()*95/100)]<<std::endl;+ if(multiplier==4){graph.shutdown();presenter.close();}else{presenter.close();graph.shutdown();}+ std::cout<<"HDR_COPY multiplier="<<multiplier<<" full="<<full<<" checks="<<pixelChecks<<" max10BitError="<<maxError<<" pass="<<ok<<std::endl;+ }+ ring.drainQueue();presenter.close();graph.shutdown();av_frame_free(&frame);+ std::cout<<"HDR_COPY_SUMMARY real="<<real<<" generated="<<generated<<" checks="<<pixelChecks<<" max10BitError="<<maxError<<" pass="<<ok<<std::endl;+ return ok&&real>0&&generated>0&&pixelChecks>0;+}