Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
Checkpoint existing XeSS and cross-monitor repairs before capture UI fixes
Veyra Goal Agent7761f3429669
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 8934e6ab..9b58c6be 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -246,6 +246,7 @@ veyra_add_compute_shader(veyra_shader_scale_blit ScaleBlit)veyra_add_compute_shader(veyra_shader_nv12_upload Nv12Upload)# PresentBlit: fullscreen-triangle pixel blit onto flip-model back buffers.veyra_add_graphics_shader_pair(veyra_shader_present_blit PresentBlit)+veyra_add_compute_shader(veyra_shader_present_motion PresentMotion)# NvofDensify: SHORT2 S10.5 raw flow -> workingExtent float2 + confidence.veyra_add_compute_shader(veyra_shader_nvof_densify NvofDensify)veyra_add_compute_shader(veyra_shader_nr_downsample NrDownsample)@@ -797,7 +798,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_options(veyra_popup_selector_tests PRIVATE /utf-8)target_compile_definitions(veyra_popup_selector_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)target_link_libraries(veyra_popup_selector_tests PRIVATE veyra_base comctl32)- add_dependencies(veyra_engine veyra_shader_hdr_video_sr)+ add_dependencies(veyra_engine veyra_shader_hdr_video_sr veyra_shader_present_motion)add_executable(veyra_hdr_color_tests tests/integration/HdrColorTests.cpp)add_executable(veyra_multichannel_tests tests/integration/MultichannelTests.cpp)target_compile_features(veyra_multichannel_tests PRIVATE cxx_std_20)diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex b3325002..a882bec8 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -22,6 +22,8 @@ Source: https://github.com/Coldwood1026/OptiScaler , commit `70676c5f037c8c26f1eThe provider DLL on disk is never modified, re-signed or renamed; only the mapped image of the process is patched, and every patched byte is restored when the XeFG/XeLL contexts are destroyed. Because Veyra itself is GPLv3, the ported GPL-3.0 code is compatible; the upstream authorship above is attributed here. Locked provider identity: `libxess_fg.dll` 1.3.1.78, 22,957,432 bytes, SHA-256 `EC5E0C65E075570C6EDE72618BB666D0BE0C2E10B2EA9762C0FE8CB8E375AB27`, PE TimeDateStamp `0x69CB0F4D`, SizeOfImage `0x015ED000`.+XeSS pacing adaptation (2026-09-19): `include/veyra/gfx/XessPacing.h` and `src/gfx/XessPacing.cpp` also adapt the above pinned OptiScaler `XeFGPacing.h` NoteFrame/PaceFrame/WaitUntil logic: a bounded 15-period median, generated-frame deadlines, and the provider-owned tail limiter condition. Veyra retains its audited call-site hooks, adds synchronized statistics and complete hooked-present-return gap measurements, and does not port upstream timestamp hooks. Provider scheduling remains preferred; wall-clock pacing is used only when its scheduler is unavailable. No on-disk runtime changes.+## AMD FidelityFX Optical FlowFidelityFX SDK 1.1.4, upstream commit `c6efa6bf7f2027b3ec94f28578bb5965eabb9e55`, https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK . The optical-flow and DX12 backend libraries are statically linked. Copyright (C) 2024 Advanced Micro Devices, Inc.; MIT license, reproduced in the package's `licenses/AMD_FIDELITYFX_LICENSE.txt`. This is optical flow, not AMD NR or AMD super resolution.diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex 37f563b8..770e2a60 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -248,7 +248,7 @@ std::wstring screenshotPath;ULONGLONG screenshotTick=0;bool screenshotPending=fa#include "SeekPreview.h"void openFile(const std::wstring&);void layout();-void updateComparison(){engine.comparison(holdOriginal?1:compareMode,referenceBase,compareSplit);}+void updateComparison(){engine.comparison(holdOriginal?1:compareMode,holdOriginal?false:referenceBase,compareSplit);}void toggleFullscreen(){endTransition();full=!full;if(tooltips){SendMessageW(tooltips,TTM_POP,0,0);SendMessageW(tooltips,TTM_ACTIVATE,full?FALSE:TRUE,0);}DWORD corner=full?1:2;DwmSetWindowAttribute(mainWindow,33,&corner,sizeof(corner));fullControls=true;pointerTick=GetTickCount64();if(full){GetWindowPlacement(mainWindow,&windowPlacement);SetWindowLongPtrW(mainWindow,GWL_STYLE,WS_POPUP|WS_VISIBLE|WS_CLIPCHILDREN);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromWindow(mainWindow,MONITOR_DEFAULTTONEAREST),&mi);SetWindowPos(mainWindow,HWND_TOP,mi.rcMonitor.left,mi.rcMonitor.top,mi.rcMonitor.right-mi.rcMonitor.left,mi.rcMonitor.bottom-mi.rcMonitor.top,SWP_FRAMECHANGED);}else{SetWindowLongPtrW(mainWindow,GWL_STYLE,ShellStyle|WS_VISIBLE);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromRect(&windowPlacement.rcNormalPosition,MONITOR_DEFAULTTONEAREST),&mi);auto& r=windowPlacement.rcNormalPosition;if(r.right<mi.rcWork.left||r.left>mi.rcWork.right||r.bottom<mi.rcWork.top||r.top>mi.rcWork.bottom){OffsetRect(&r,mi.rcWork.left-r.left,mi.rcWork.top-r.top);}SetWindowPlacement(mainWindow,&windowPlacement);SetWindowPos(mainWindow,nullptr,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);}SetWindowTextW(GetDlgItem(mainWindow,Fullscreen),full?L"退出全屏":L"全屏 F11");SetCursor(LoadCursorW(nullptr,IDC_ARROW));layout();SetFocus(mainWindow);veyra::log::info("ui-fullscreen",std::format("enabled={} video-only viewport; transport auto-hides",full));}bool smokeProtection=false;int protectionStep=0;uint64_t protectionSession=0;bool protectionOverlayShown=false;bool protectionArmed=false,protectionDragging=false;POINT protectionStart{};std::pair<float,float> protectionSourceStart;HWND protectionOverlay=nullptr;@@ -601,6 +601,16 @@ case WM_APP+44:{if(masterPendingRevision)return 0;auto setting=uiState.enhanced?const bool enablesMaster=enabled&&!uiState.enhanced;if(enablesMaster){masterPreviousEnabled=false;uiState.enhanced=true;}applySettings(setting);if(auto pending=engine.snapshot();enablesMaster&&pending.running){masterPendingRevision=pending.desired.revision;masterPendingSession=pending.sessionId;}veyra::log::info("ui-feature",std::format("click={} enabled={} requestedRevision={} draft-independent=true",wp==200?"NR":wp==201?"SR":wp==230?"VideoHDR":"FG",enabled,engine.snapshot().desired.revision));return 1;}case WM_APP+43:showDiagnostics=false;layout();return 0;case WM_APP+41:switch(wp){case 501:startVideoExport(lp!=0);break;case 502:{auto path=fileDialog(true);if(!path.empty())engine.saveFrame(path);break;}case 503:jobPaused=!jobPaused;exportJob.pause(jobPaused);break;case 504:exportJob.cancel();break;case 505:preferWatching=lp==BST_CHECKED;break;}return 0;+case WM_ENTERSIZEMOVE:+ endTransition();+ SetPropW(video,L"Veyra.InteractiveMove",HANDLE(1));+ veyra::log::info("ui-display","interactive move begin; retaining presentation buffers");+ return 0;+case WM_EXITSIZEMOVE:+ RemovePropW(video,L"Veyra.InteractiveMove");+ layout();+ veyra::log::info("ui-display","interactive move end; presentation resize released");+ return 0;case WM_SIZE:cancelProtection();if(wp!=SIZE_MINIMIZED){endTransition();layout();}return 0;case WM_DROPFILES:{std::vector<wchar_t> file(32768);DragQueryFileW(reinterpret_cast<HDROP>(wp),0,file.data(),32768);DragFinish(reinterpret_cast<HDROP>(wp));openFile(file.data());layout();return 0;}case WM_COMMAND:switch(LOWORD(wp)){@@ -670,12 +680,16 @@ case WM_APP+90:[[fallthrough]];case WM_DPICHANGED:{endTransition();veyra::ui::cancelPopupSelector();+ veyra::log::info("ui-display",std::format("DPI transition begin dpi={} synthetic={} moving={}",veyra::ui::layoutDpi(hwnd),msg!=WM_DPICHANGED,GetPropW(video,L"Veyra.InteractiveMove")!=nullptr));+ SetPropW(video,L"Veyra.DpiTransition",HANDLE(1));if(msg==WM_DPICHANGED&&!full){auto rect=reinterpret_cast<RECT*>(lp);SetWindowPos(hwnd,nullptr,rect->left,rect->top,rect->right-rect->left,rect->bottom-rect->top,SWP_NOZORDER|SWP_NOACTIVATE);}auto oldFont=font;font=veyra::ui::makeFont(hwnd);EnumChildWindows(hwnd,[](HWND c,LPARAM f)->BOOL{SendMessageW(c,WM_SETFONT,WPARAM(f),FALSE);return TRUE;},LPARAM(font));DeleteObject(oldFont);DeleteObject(emptyFont);emptyFont=veyra::ui::makeFont(hwnd,26);SendDlgItemMessageW(hwnd,EmptyTitle,WM_SETFONT,WPARAM(emptyFont),FALSE);- veyra::ui::settingsDpi();veyra::ui::telemetryDpi();layout();return 0;}+ veyra::ui::settingsDpi();veyra::ui::telemetryDpi();layout();+ RemovePropW(video,L"Veyra.DpiTransition");+ veyra::log::info("ui-display","DPI transition complete");return 0;}case WM_TIMER:#ifdef VEYRA_ENABLE_REMOTEPLAYdiff --git a/docs/CAPTURE_SCREENSHOT_SUBTITLE_SYNC_PLAN_2026-09-19.md b/docs/CAPTURE_SCREENSHOT_SUBTITLE_SYNC_PLAN_2026-09-19.mdnew file mode 100644index 00000000..1dd8b03f--- /dev/null+++ b/docs/CAPTURE_SCREENSHOT_SUBTITLE_SYNC_PLAN_2026-09-19.md@@ -0,0 +1,57 @@+# 采集、HDR截图、字幕与防撕裂修复方案++日期:2026-09-19。范围:本轮代码调查和施工方案,未修改产品实现,未构建或复现实卡问题。保留此前 XeSS 等未提交修改。用户报告的 573 暂按 GC573 理解,准确型号、分辨率、RGB24/32、音频及帧率日志待补充。++## 1. GC551 无音频++现状:CaptureCardSource.cpp 支持视频 filter 内嵌音频 pin 与独立音频设备,兼容无 capture category 的 audio pin。找不到内嵌 pin 后会停止无效重试,提示选独立设备;尚无证据证明本次失败具体发生在枚举、连接、PCM/位流协商还是收到数据后的输出。++方案:记录视频/音频设备稳定路径、Container ID、pin 媒体类型、连接 HRESULT、实际 WAVEFORMAT、音频回调数/字节数和输出欠载。依据设备关联自动推荐同卡音频端点,保留手动选择;不能因为品牌相同就绑定另一块卡或麦克风。明确区分无音频 pin、无兼容格式、连接成功无数据、收到数据但未播放。根据实际协商补充 PCM/位流类型,沿用现有解码路径,不先套其他圆刚型号私有开关。++验收:GC551 HDMI PCM 同参数与 OBS 顺序对照,冷启动/重连/音视频同时运行各60秒;多音频设备时不串选。若用户输入为Dolby另测,不能用PCM通过代替位流。++## 2. 573 RGB 60fps 只有57fps++现状:手动帧率通过 AvgTimePerFrame 协商,日志明确 softwareLimiter=0。callbackFps 是首帧到最近帧累计均值,不是当前滚动窗口;处理/呈现 FPS 与采集回调 FPS 不同。不能由界面57直接判为设备只有57,也不能拿OBS输出60证明60个不同源帧。++方案:同时记录请求/连接媒体类型与精确分数帧率、回调滚动FPS、源PTS间隔、处理/呈现FPS、mailbox覆盖、回调耗时、锁等待、缓冲协商实际值。顺序对照全关、NR、VideoHDR及组合,各60秒。先用实际回调数判定在哪段少帧:回调60处理57查RGB上传/GPU与owner阻塞;回调57查DirectShow graph、pin、缓冲与回调重活;仅累计读数偏低则修统计显示。保留latest mailbox,不靠延长队列或重复帧冒充60;保留用户选择RGB。++验收:确认RGB24/32、分辨率、59.94或60、设备缓冲及OBS设置一致。用源序号/PTS与墙钟报告,不强行把59.94显示为丢帧。缺实卡日志前不声称根因。++## 3. NR + RTX Video HDR 截图失败++现状:EngineController.cpp 根据graph.hdrOutput进入 saveHdrScreenshot;ImageExportSink.cpp接受FP16 scRGB或RGB10 PQ,写JPEG XR后重解码并要求FP16逐位相同。大量失败出口直接return false,通用提示无法识别资源格式、GPU读回、WIC编码还是回读校验失败。位级比较是否误拒本次输出仍待验证。++方案:为各失败阶段记录HRESULT、格式、尺寸、源帧identity、输出路径和必要的数值摘要。相同素材跑四组合(全关/仅NR/仅HDR/NR+HDR),包含暂停截图与连续截图;核对输出纹理颜色合同、fence/资源有效期及FP16非有限值。按证据修资源或编码问题;不要静默关闭任一效果。生产截图保留写入成功/完整性检查,把全面逐像素比较移到测试;HDR输出仍为HDR,SDR兼容预览如增加应独立明确,不以8位PNG冒充HDR。++验收:四组合可保存并重新打开,尺寸正确、HDR高光保留,无空白或损坏;已有文件不覆盖;失败保留播放并给具体原因。scRGB/PQ、SDR显示器预览分开验证。++## 4. 音量交互++需求按新增处理:上下方向键及滚轮调音量。当前专业模式画面滚轮用于缩放,必须保留。++方案:上下键在播放快捷键上下文以5个百分点调节,支持长按;文本输入、弹窗、滑杆/列表操作不抢键。普通模式画面滚轮及音量控件滚轮调音量,专业模式画面默认继续缩放,提供滚轮用途选项。复用engine.setVolume与现有持久化,明确静音时调节行为,累计高精度滚轮delta,显示短暂音量OSD。++## 5. 字幕连续调节及显示不全++已确认:AppShell::subtitleMenu 调用popupSelector返回后才执行单次action,字号/偏移/位置每次点击必然关菜单。SubtitleOverlay.cpp以height*2区域排版,非定位字幕自底向上堆叠,无总高度适配,多行/双语可越出视区。++方案:轨道选择保留选择器;样式/时间改为常驻可关闭面板,字号、偏移、位置使用滑杆/数值输入/步进器,更新即时生效、焦点稳定、不重建面板。文本字幕默认每轨目标两行,可选自动或自定义行数,按实际字体测量换行,保留全部文本,超过空间先合理缩字号并限制到底部安全区;不能截去第三行充当修复。双语按两个轨道共同分配高度。极长文本无法同时满足固定字号/固定两行/不丢内容时,优先完整显示并明确行数为布局目标。ASS定位/多角色及图形字幕保留原版式,可单独缩放/安全区适配,不强拆成两行。设置持久化和旧配置迁移一起做。++验收:连续20次调节不关面板、不抢焦点;长中英文、手动换行、双语、定位ASS、PGS、小窗口/全屏/高DPI均不裁文字或遮挡控制条。++## 6. 帧同步与撕裂++已确认:PresentationSettings默认display=Tearing;低排队/Reflex主要控制队列,并非防撕裂。PresentSink::present仅vsync为真才Present(1,0),否则允许DXGI_PRESENT_ALLOW_TEARING。configurePacing在XeSS/FSR分支强制vsync=false,VideoPresenter对提供方路径也有能力回退。因此“开启帧同步就消除撕裂”在当前实现不成立。++方案:独立展示帧节奏模式和显示同步策略(允许撕裂/垂直同步/自动),说明请求值与实际生效值。防撕裂必须落实到最终Present,垂直同步禁止tearing flag;保留完全关闭。无补帧/DLSS先验证DXGI参数和高于刷新率的节奏;XeSS/FSR核对SDK对同步间隔/flags的支持和最终代理呈现行为,再接入,不能只改外层布尔值假装生效,也不能叠两个等待器。自动模式未知VRR时明确使用VSync,不宣称已识别G-SYNC。同步可能增加等待,报告代价;不承诺任意倍率都能被固定刷新率屏幕显示。++验收:各后端关闭/2X/4X,窗口/全屏、刷新率上下、VRR开关,核对最终Present参数与实际显示事件;撕裂用运动测试图及外部屏幕观察,普通软件截图不足以证明无撕裂。同时保留输出节奏、排队时间和延迟对照,软件延迟不冒充到眼睛延迟。++## 施工顺序与交付++1. HDR截图失败定位与修复、字幕连续调节/布局、音量交互。+2. GC551/573诊断与对应采集修复,需要实卡证据验收。+3. 显示同步与帧节奏分离,各提供方真实防撕裂支持及延迟回归。++执行时先更新存档与施工状态,保护已有XeSS等改动;源码/文档在仓库,构建/测试/日志统一E:/项目/Veyra对应用途目录。针对性测试单次不超过300秒。当前未授权本轮发布;报告逐项区分已复现、代码证据、待实卡验证。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex eb698a51..876d4fdf 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,25 @@# Veyra 工作记录+## 2026-09-19 XeSS 游玩转身卡顿深度审计(方案,未施工)++用户要求排查与修复方案。保留当前 `codex/cross-monitor-20260919` 上已有跨屏、V 原图等未提交修改,新增 `docs/XESS_GAMEPLAY_STUTTER_REPAIR_PLAN_2026-09-19.md`。审计确认 XeLL 标记未覆盖 graph 工作、暂时 motion 无效触发 SetEnabled 造成额外历史预热、多倍 pacing 省略上游 fallback、统计遗漏批次边界,以及重复 install 嵌套 mutex 的条件死锁。快速转身误切、mailbox Drop 反馈、双重排期、motion 空间域为待实证假说,不称作已复现根因。采集不走文件 XessGenerationGate,明确排除该误判。++实际检查:`git status --short`、针对 Engine/Graph/Presenter/Pacing/Scene 的 `rg` 和文件读取;对照本机 Intel XeSS 3.0.2 官方开发文档;本地 OptiScaler 固定 `70676c5f037c8c26f1ec355b250a72303cd268da`;`git ls-remote https://github.com/Coldwood1026/OptiScaler.git HEAD` 返回 `68d4c37c0c60eeda64234a106bf9d93289d2eb53`(未逐行审计新 HEAD)。读取旧 `E:/项目/Veyra/logs/xess-view-reset-20260919/` pan/package 证据,实际旧测试 bypassed/refused 均为 0,不能声称 fallback 缺失曾在该测试触发。桌面旧用户日志虽有 XeSS 2X 会话,无本次转身关联。首次查找 `include/veyra/engine/LiveTimeline.h` 路径不存在,已定位真正的 `PresentationScheduler.h`,未据失败搜索下结论。++未运行新的构建、实机游玩、功耗或屏幕延迟测试;本轮仅文档,`git diff --check` 通过。后续产物约定 `E:/项目/Veyra/{tests,logs,tmp,build}/xess-gameplay-20260919/`,本轮未生成这些产物,未新增运行组件或上传发布。++## 2026-09-19 按住 V 的原图对照排除调色++在 `codex/cross-monitor-20260919` 保留已有跨屏修复,修正原图引用在输入转换融合调色后才复制的问题。++- `src/pipeline/EnhanceGraph.cpp`:仅在调色开启且请求对照时,按相同输入颜色合同生成未调色 FP16 引用,再执行正常调色输入。原图与增强基底引用分离,基底保持既有调色语义;不增加产品路径 CPU 像素回读。普通播放未请求对照时没有额外转换。+- `apps/veyra/ui/AppShell.cpp`:按住 V 或原图按钮强制选择源图;释放时恢复原对照模式及基底选项,不改写调色设置。+- `tests/integration/ColorGradeGpuTests.cpp`:新增 RGB/NV12 GPU 回归,强曝光下交替覆盖两个帧槽,原图与中性基准逐字节一致、基底仍带调色、取消引用后输出仍等于调色输出。++实际验证:`scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/slider-reset-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/original-grade-20260919 -DisplayVersion 1.4.2 -Targets veyra,veyra_color_grade_gpu_tests` 成功;`veyra_color_grade_gpu_tests.exe` 退出 0,新增案例及原有调色/LUT 回归全部通过。`scripts/run-short-test.ps1` 主程序 `--smoke-empty --smoke-seconds 5` 退出 0;`git diff --check` 通过。未实际操作键盘验收,未覆盖 HDR/补帧组合,不以 GPU 引用测试冒充全链路人工验收。++构建复用 `E:/项目/Veyra/build/slider-reset-20260919/`;证据在 `E:/项目/Veyra/logs/original-grade-20260919/`(build.log、gpu-test.log、gpu.log、app.log、smoke.*),临时目录 `E:/项目/Veyra/tmp/original-grade-20260919/`。未打包、推送或发布,未新增运行组件。+## 2026-09-19 字幕按钮弹窗立即关闭修复分支 `codex/subtitle-popup-20260919`,基线 `fd67b58`。`Theme.h` 的按钮鼠标消息曾在 `WM_SETREDRAW(FALSE)` 内调用原生按钮过程;`WM_LBUTTONUP` 同步发出 `BN_CLICKED` 并进入字幕菜单消息循环。此时按钮的 `WS_VISIBLE` 被临时移除,菜单 100ms 的锚点检查关闭弹窗。旧代码真实复现:菜单打开约 100ms 后 selection=-1,新增测试报告按钮在通知期间不可见。@@ -4527,8 +4547,48 @@ Blackwell 上会改变一条已经正常工作的路径,无法区分"补丁生用户授权本轮修复、整合 main、GitHub 发布及新群/HDR 对比图片公开。AppShell 全屏切换先 TTM_POP,再按 full 状态 TTM_ACTIVATE,退出恢复正常提示。更新中英文 README、1.4.2 notes、组件与对应源码说明、RELEASE_SUPPORT;打包正式纳入已授权 TrueHDR,附 README 图片与窗口采集 MIT 许可。具体命令与最终状态见 RELEASE_1.4.2_EXECUTION.md。产物统一在 E:/项目/Veyra/releases/1.4.2、build/screen-capture-20260919,以及 logs/tests/tmp/release-1.4.2-20260919。未覆盖上一轮内测包。+# 2026-09-19 跨屏拖动卡住/闪退:首轮排查与重建时机修正++分支 `codex/cross-monitor-20260919`,基于 `412a19f`。尚未确认用户闪退根因,不标记真实多屏问题已解决。本机 EnumDisplayMonitors 仅返回一块 2560x1440 显示器;原程序空白页合成 96/144/192 DPI 切换通过,先前 user-preview.log 正常退出,没有对应崩溃证据。待补充空白/播放、DLSS/XeSS、双屏缩放及问题日志。++- `AppShell.cpp` 在原生移动循环及 DPI 更新期间向视频窗口标记状态,增加开始/结束日志。+- `VideoPresenter.cpp` 在上述状态下保留现有缓冲继续呈现,不执行队列 drain/ResizeBuffers;松开后沿用原来的尺寸更新路径。没有关闭补帧,也不修改源时间线。此修改减少拖动过程中反复重建的风险,不等于已经证明用户崩溃就是该原因。+- `scripts/acceptance/ui-cross-monitor.py` 为独立进程回归,120 秒总超时;枚举实际显示器,三轮模拟移动循环、DPI、尺寸切换,验证窗口响应及正常退出。播放模式额外断言移动期间持续呈现且不重建、松开后恢复重建。单屏上的模拟事件不代表真实多屏拖动验收。++实际验证:++1. `scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/slider-reset-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/cross-monitor-20260919 -DisplayVersion 1.4.2 -Targets veyra` 通过,复用上轮构建目录及已核验运行库。+2. `python scripts/acceptance/ui-cross-monitor.py <上述目录>/veyra.exe E:/项目/Veyra/logs/cross-monitor-20260919/baseline` 原版空白页通过。+3. 同脚本对修改后程序运行 `.../playback E:/项目/Veyra/tests/1.4.2beta/visible-scene.mp4 --no-nr --no-sr --no-fg` 通过;`.../dlss4x <同媒体> --no-nr --no-sr --fg-multiplier 4` 通过,实际 generated=true / Present hr=0,最终 706x414 缓冲恢复调整。DLSS 本机实际执行,不推广到其他硬件;XeSS 未测。+4. 音轨测试媒体记录 decoder rejected stream=1 code=-22,不将该次视频呈现测试冒充音频验收。++证据 `E:/项目/Veyra/logs/cross-monitor-20260919/`,临时目录 `E:/项目/Veyra/tmp/cross-monitor-20260919/`。未打包/推送/发布;真实双屏闪退仍待复现和验收。+# 2026-09-19 参数滑杆单项还原(方案一)+## 2026-09-19 XeSS 转身卡顿接入修复(本轮执行补记)++当前分支 `codex/cross-monitor-20260919`,基线 `412a19f`;保留已有跨屏、V 对照、UI 修改。实施范围与证据边界见 `docs/XESS_GAMEPLAY_STUTTER_REPAIR_PLAN_2026-09-19.md`。未打包、提交、推送或发布。++修改 EngineController/VideoPresenter/XessPresenter 的 XeLL 输入/处理/呈现生命周期及有界身份关联;合法历史断点用零 motion + resetHistory;新增 PresentMotion shader 和 CMake 依赖,使 motion 与 contain/zoom/pan 的显示域一致、固定插值区域;未知 frameRenderTime 为 0;XessPacing 修重复安装死锁、统计锁、补固定上游 fallback 与跨批间隔日志。THIRD_PARTY_NOTICES 保留固定提交和许可证。没有修改磁盘运行库或引入 SDK 到 Git。++实际命令:`scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/slider-reset-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/xess-gameplay-20260919 -DisplayVersion 1.4.2 -Targets veyra,veyra_experimental_backend_tests`;主程序/测试均构建成功,日志 `build-final.log`,随后仅增加测试 soak 模式构建 `build-soak.log` 成功。++测试统一使用 `scripts/run-short-test.ps1 -Exe <上述构建目录>/veyra_experimental_backend_tests.exe -Arguments <mode>,E:/项目/Veyra/tests/xess-gameplay-20260919/<case> -TimeoutSeconds 60 -LogPrefix E:/项目/Veyra/logs/xess-gameplay-20260919/<case>`;soak 使用 160 秒超时。TEMP/TMP 仅对子进程设为本轮 tmp;PATH 加已发布 1.4.2 便携包依赖。++- `xess-recovery2/3/4`、`xess-resize4`、`xess-pan2/4` 通过;证据 final2/final3/verified4/mapped-resize4/verified-pan2/final-pan4。最终4X三次断点后的下一帧均生成3帧,重复呈现未生成;准备帧被重绘超越编号回归通过。2X/4X移动期间分别生成37/111帧,未通过移动时关闭补帧取巧。+- GPU motion 数值回读仅存在于集成测试:恒定 (-2,1)、2X缩放约(-4,1.99902)、平移(62,1)、reset(0,0),四项通过。所有上述成功场景 debugErrors=0。+- 尺寸变化旧路径复现119条GPU状态错误;仅改时间或仅改资源生命周期均仍119条,日志 zero-resize4/deferred-resize4;稳定插值域与motion映射后 mapped-resize4 为0。不把失败实验当成修复收益。+- `xess-soak4`:3600源帧,绝对30fps期限约120秒,640x360合成移动纹理、NR关闭、真实提供方4X;generated=10788、debugErrors=0、scheduled=7192、refused=0、bypassed=0、fallbackFrames=0,退出0。最后约30秒附近与主程序smoke重叠,仅作稳定性检查,不作隔离性能A/B。完整hook返回间隔日志包含批次边界,不能当物理扫描事件。+- 主程序 `-Arguments E:/项目/Veyra/tests/1.4.2beta/visible-scene.mp4,--fg-xess,--fg-multiplier,4,--nr,--no-sr,--smoke-seconds,15`,TimeoutSeconds45,final-engine退出0,生成591帧。此前25秒engine-nr4退出0、生成588。媒体会先结束而进入暂停重绘,不声称全程连续补帧或真实游戏画质验收。+- 早期误列XeSS6X的测试初始化失败,已纠正文档/测试为XeSS2/3/4X,DLSS6X不变;一次PowerShell数组经`-File`传参错误退出2,非产品失败。`git diff --check`通过(仅CRLF提示)。++当前未验证:fallback在真实提供方scheduler不可用时的触发、用户转身录屏/实卡NV12/P010、30/40显卡、功耗因果与屏幕延迟。未改切镜检测阈值或capture pairDelay。完整A/B验收矩阵仍待对应输入与设备;本轮只能宣称上述接入缺陷修复及本机回归通过。++本轮产物保留 `E:/项目/Veyra/build/slider-reset-20260919` 可运行构建,`E:/项目/Veyra/{logs,tests,tmp}/xess-gameplay-20260919/` 诊断证据;无中间便携包或解压副本。++## 以下为此前滑杆修复记录+用户选择数值右侧固定还原图标。分支 `codex/slider-reset-20260919` 从字幕弹窗修复 `4bce05e` 创建,未合并、推送或发布。- `SettingsWindow.cpp` 为调色、NR、剔除区羽化和 RTX Video HDR 参数滑杆增加 28 DIP 独立按钮;读取 `EnhancementSettings{}` / `ColorSettings{}` 的实际默认值,只改对应字段,保留开关和其他参数。调色使用现有提交与撤销路径;提交失败保留原设置。默认态禁用,修改后启用,提示显示参数和默认值。diff --git a/docs/XESS_GAMEPLAY_STUTTER_REPAIR_PLAN_2026-09-19.md b/docs/XESS_GAMEPLAY_STUTTER_REPAIR_PLAN_2026-09-19.mdnew file mode 100644index 00000000..6efb3f43--- /dev/null+++ b/docs/XESS_GAMEPLAY_STUTTER_REPAIR_PLAN_2026-09-19.md@@ -0,0 +1,106 @@+# XeSS 游玩转身卡顿与功率波动:调查和修复方案++日期:2026-09-19。状态:用户随后授权实施,已修复下述接入问题并完成本机针对性构建和 GPU 回归;受影响用户的真实转身场景仍待验收。未打包、推送或发布。以下审计段落描述修改前基线,执行结果见文末。++## 结论与证据边界++不能把 GPU 功率上下波动直接判为显卡性能不足。源帧断供、CPU 等待、历史重建、GPU 工作量变化均可造成这种现象,需要同一时间轴区分先后。当前存在足以影响连续性的接入缺陷;尚无本批用户的日志/录屏,不能宣称已锁定共同根因。++审计基线:`codex/cross-monitor-20260919`,HEAD `412a19f`,包含未提交的跨屏、V 原图对照等已有修改。本方案不覆盖这些改动。++## 已确认的实现问题++### 1. XeLL 标记没有覆盖实际增强工作(优先级 P1)++`src/gfx/XessPresenter.cpp:183` 的 `beginFrame()` 调用 Sleep 后立即连续发送 SIMULATION_START/END、RENDERSUBMIT_START;调用入口在 `src/engine/VideoPresenter.cpp:87`。此时 Engine 已完成该源帧的 graph 处理/提交,并可能等待过呈现期限。XeLL 看不到主要处理阶段,所学习的时序不代表完整一帧。++本机 Intel XeSS 3.0.2 文档 `doc/xell_developer_guide_english.md:294` 要求 Sleep 在帧开始、输入采样前执行,且为该 frame ID 首次 XeLL 调用;SIMULATION 与 RENDERSUBMIT 应分别覆盖实际 CPU 准备和命令提交。因此这是接入位置/计时合同问题,实际贡献多少卡顿尚待测量。++当前呈现与处理在同一 owner 上同步执行(`EngineController.cpp` 的 `advanceLive`、`LiveGpuScheduler.h`)。Sleep/Present 阻塞时会推迟后续取帧。XeSS 还共享 direct queue/ring;DLSS 使用独立呈现队列,不能拿 DLSS 顺畅证明这段 XeSS 链路正常。++### 2. 暂时失去光流被扩大为关闭提供方(P1)++`EnhanceGraph.cpp:1886` 使用 `haveFlow && !reset` 标记 motion 有效;`VideoPresenter.cpp:135` 附近将 motion 有效性纳入 enabled,随后 `XessPresenter::tag` 调用 SetEnabled(false),不再 Tag。恢复时又因 `!xessWasEnabled_` 发送 reset。++官方 FG 指南 `doc/xess_fg_developer_guide_english.md:885` 后明确区分:resetHistory 跳过当前帧插值但保留当前输入;SetEnabled(false) 不保留历史,恢复多需一帧预热。当前路径会放大历史中断。具体缺帧数量须以每帧状态测量,不能固定推算为所有设备相同。++修复必须让“用户关闭”“资源不可用”“当前帧历史不连续”成为独立状态。只有当前 color/depth/MV 资源合法时,才可保持 provider enabled 并用 resetHistory 表达断点;不能提交悬空资源或冒用上一帧运动。初始/断点帧需提供符合合同的中性 guidance。不得以拖动或转身时停补帧作为解决办法。++### 3. 多倍节奏移植缺少上游兜底(P1,条件触发)++`src/gfx/XessPacing.cpp:141` 附近在内部 scheduler 不可用时只增加 bypassed,不约束中间生成帧的节奏。固定上游 `Coldwood1026/OptiScaler` 提交 `70676c5f037c8c26f1ec355b250a72303cd268da` 的 `OptiScaler/proxies/XeFGPacing.h:750` 则检查 scheduler gate,必要时调用 PaceFrame,并避免重复等待提供方已调度的尾帧。++本地移植计划确实只移植 scheduler 核心,省略 wall-clock fallback 和时间戳相关 hooks。这是覆盖缺口,不证明本批用户触发。历史 pan4 与 package-xess4 均报告 bypassed=0、refused=0,该次运行不能归因于缺少兜底。2X 不经过这个多帧补丁,若 2X 同样卡顿应优先检查前两项及源帧断供。++GitHub 只读 `git ls-remote https://github.com/Coldwood1026/OptiScaler.git HEAD` 返回 `68d4c37c0c60eeda64234a106bf9d93289d2eb53`;本轮逐行比较的是上述固定本地版本,不声称已审计远端最新源码。++### 4. 现有平滑度指标遗漏批次边界(P1)++`XessPacing.cpp` 的 inBurstGaps 只计批内调度返回间隔,burstBoundaries 只记次数、不记时长,亦不是完整真实 Present/扫描事件。于是“批内均匀、一批之后停很久”可以显示正常的平均间隔。++历史 `E:/项目/Veyra/logs/xess-view-reset-20260919/package-xess4.engine.log` 后半段确有 backend=XeSS(前半是 DXGI),批内 mean 约 10.37ms;退出 scheduled=544/refused=0/bypassed=0。不能据此认定整段画面平滑或物理显示达到某帧率。++### 5. 生命周期与统计并发缺陷(P2)++`XessPacing::install` 持有非递归 mutex 后,在已 installed 分支调用再次取锁的 snapshot,会死锁。是否有运行路径重复 install 尚须调用生命周期测试,不当作持续转身卡顿的证据。Hook 线程写统计而 snapshot 的读取锁未被写侧遵循;需原子计数或有界快照传递,并核查卸载时在途回调。不能简单在整个 hook 外层加大锁,把等待锁带进逐帧路径。++## 高风险机制,尚未确认为本批根因++1. **转身被当作切镜。** `SceneCadenceAnalyzer.cpp` 使用未运动补偿的 SAD 与 256 档直方图,`EnhanceGraph.cpp:1348` 使用 64x36 点采样。相同场景快速转向不同亮度区域可能触发 histogram replacement(SAD > .08 且 histogram distance > .9)或 hard cut。当前测试仅有直方图稳定的移动纹理,不覆盖该情况。CPU NV12/RGB/YUY2 等输入走此判定;GPU RGB 和硬解纹理分支不走此 CPU 分析,不能把所有窗口采集问题都归因于它。+2. **断供反馈。** 采集 latest mailbox 覆盖记 Drop(`CaptureCardSource.cpp:1123`);Engine 将 Drop/previewSkip 变为 historyReset(`EngineController.cpp:1029`)。可能形成“owner 等待 → mailbox 覆盖 → reset → 补帧预热 → 输出断档”。保留丢帧真实统计和断点重置,优先解决等待来源,不能粗暴忽略 Drop。+3. **重复排期。** 采集 XeSS 仍使用一源帧间隔的 pairDelay(`EngineController.cpp:1046,1195,1258`);随后进入 XeLL 和 provider。`PresentationScheduler::deadline` 明确是 host+(PTS-source)+delay。须测明 provider 自带延迟与该 delay 是否重复,不能未经验证直接删掉全部等待或真实 A/B 依赖。+4. **帧时间反馈污染。** 传入 frameRenderTime 的是 presenter 调用间隔,可能夹带前次等待和源端抖动。Intel 文档称该值为帧时间,非 Intel GPU 可用于 pacing sanity-check;未知可填 0。比较有效源 PTS 间隔、当前值、0 三种诊断设置,不能把增强 GPU 耗时误填为该值。+5. **转身视觉错误与时间卡顿混淆。** 色彩图裁剪、motion/depth 全资源及单位映射需要验证。资源分辨率不同本身不构成错误,官方允许 low-res MV 与 letterbox。裁剪后空间域、缩放后的向量单位、上一帧有效区域变化才是审计重点。指南还要求前后帧插值区域尺寸相同,否则可跳过插值。不能在没有画面和尺寸证据时宣称已找到坐标 bug。++已排除的错误方向:`XessGenerationGate::observe` 位于 `if(didPresent && !isCapture)` 内(EngineController.cpp:1309-1325),只作用于文件播放,不能解释采集卡门控停补帧。文件播放的 gate 仍应单独审计其 lateness 是否包含 provider 主动等待。++## 施工顺序++### A. 先建立可关联时间线++使用同一 epoch/sourceFrameId/providerPresentId 关联:采集回调、mailbox 取帧/覆盖、graph 开始结束和 GPU 完成、计划 deadline/实际等待、XeLL Sleep、命令提交、Present 起止、provider 返回。每次 reset 写原因、MV 有效性、SetEnabled 变化、resetHistory、生成数量及批次 ID。++用预分配有界事件环、汇总输出和异常前后窗口,避免逐 API 同步日志改变结果。补全原帧/生成帧及批次边界事件;调度 hook、DXGI 调用、系统显示事件三者分开。所有耗时输出 P50/P95/P99/max 及超期计数,GPU 功耗按 QPC 对齐辅助判因。++### B. 修复状态语义和 XeLL 生命周期++先修重复 install 锁问题并补生命周期回归。然后在合法资源合同下,以 resetHistory 代替短暂 SetEnabled(false)。独立验证 XeSS 2X/3X/4X 首帧、连续转身、真实切镜、Drop、用户关闭/重开。当前 XeSS 提供方上限为 4X,6X 是 DLSS 路径,不能混用验收倍率。++将 XeLL frame ID 从 presenter 自增移到共享 owner 的实际源帧工作起点,经处理批次传到 presenter;Sleep 返回后再选取 latest 输入并设置真实 markers。明确被跳过、失败、取消的帧如何结束或放弃,不能对同一 ID Sleep 两次,不能让已提交批次错误配对。marker 改动与 pairDelay 改动分开 A/B,先确认时序,再决定实时 XeSS 由哪个时钟唯一控制呈现;文件音频主时钟不随意改变。++若等待仍占用 source owner,才评估独立呈现 owner/queue。必须先审计纹理 lease、描述符、帧槽、provider 线程归属、GPU fence、退出/resize 顺序;队列严格有界,不通过无限缓存换平滑度。++### C. 内容判定与多帧 fallback++用真实转身素材证明误切后再改 detector:优先结合已有光流置信度和运动补偿残差,检查直方图候选的空间连续性;无需额外等待 C 帧,不新增正常路径像素回读。避免只提高阈值导致真实切镜跨场景插值。先做 CPU 路径针对性验证,不能将未验证逻辑全局推广。++fallback 按固定上游实现适配,先诊断 gate 状态与 bypass 是否真实出现,再导入 provider 时间基准/尾帧归属保护。保留来源、固定提交、GPL 许可及改动记录于 THIRD_PARTY_NOTICES。只进程内修改、保持原 DLL;不得无条件对每个生成帧追加 Sleep。验证 provider scheduler 与 limiter 两种状态,以及倍率切换和退出。++### D. 验收标准++- 同一输入/窗口/刷新率,XeSS 2X/3X/4X 对比关闭 FG 与 DLSS 4X;1080p60、1440p60、4K30,NR 关闭/开启,采集 NV12/P010 与 GPU 窗口采集分开。+- 每项 120 秒(单测上限 300 秒),覆盖静止、慢转、快速 180 度转身、亮暗方向切换、闪光、真实切镜;保留输入帧或获授权素材,以相同运动段复测。+- 补测中键拖动/缩放、全屏/裁剪、跨屏、暂停恢复、倍率切换。不得出现修拖动后 XeSS 开不了的回归。+- 首先通过 API/GPU debug 与资源生命周期检查;真实切镜仍明确 reset。连续同场景转身不可无原因反复 enable/disable;所有停补帧必须有合法原因和关联事件。+- 对完整输出事件统计相对目标间隔的 >1.5x、>2x、>3x 长间隔数量,逐个归因启动/真实切镜/源丢帧/处理欠速/调度。目标是消除软件额外长间隔,不将源断流算作可凭空生成的内容。+- 以相同素材/设置比较基线与修改后的 P95/P99、最长停顿、reset 次数及源帧年龄;不能仅因平均 FPS 或功率升高判通过。修补一项后重复对应场景再继续下一项。+- 若要声称“到眼睛延迟”,需要摄像/光电等外部测量。本次软件事件只证明进程与系统显示路径,不冒充屏幕扫描延迟;本机 50 系不能替代用户 30/40 系验收。++## 本轮实际检查++读取上述产品实现、Intel 本机 SDK 文档、固定 OptiScaler 源码、现有 pan/package 日志,并只读查询 GitHub HEAD。旧 Desktop/logs/veyra-app.log 确有 XeSS 2X 会话及 API 成功记录,但来自既往反馈、缺乏本次转身场景关联,不能冒充本批复现。没有新的实机/GPU/功耗测试,也没有证明硬件驱动本身无问题。++后续产物统一置于 `E:/项目/Veyra/`;本轮复用 `build/slider-reset-20260919`,日志、测试、临时目录使用 `xess-gameplay-20260919`。源码仓库只新增源码、测试与文档。++## 授权实施结果++- XeLL Sleep 移到取源帧前,simulation/render markers 覆盖准备和 graph 提交;通过有界 identity 映射关联待呈现帧。旧画面重绘抢先呈现时,退休被超越的准备编号,使用新呈现编号,避免倒序 SetPresentId;该回退标记不冒充覆盖先前 graph 工作。+- 合法输入的历史断点提交中性 motion + resetHistory,保留当前帧,不再因暂时无有效光流关闭提供方。真实用户关闭、重复呈现、原图对照仍不生成。+- 复现 retained buffer 2560x1440、client 960x540 切到 800x600 时 119 条 COMMON/UAV 调试错误。仅将 frameRenderTime 改 0 或仅改资源 lifetime 均不能解决;固定全 buffer 插值域、按实际 contain/zoom/pan 变换 motion 后同场景错误降为 0。+- 新 `PresentMotion.hlsl` 输出 current-to-previous、低分辨率 motion 像素单位;前后 view 均参与计算,黑边/越界/reset 输出零。正常链路只有 GPU pass,不增加像素回读。测试专用回读验证恒定向量、2 倍缩放、10% 平移和 reset,结果分别约 (-2,1)、(-4,2)、(62,1)、(0,0)。+- 资源以 UNTIL_NEXT_PRESENT/COMMON 标记,同队列提交,Present 返回前不复用。未知 frameRenderTime 填 SDK 允许的 0,不将含等待的 presenter 间隔反馈为处理帧时间。+- 修重复 install 嵌套 mutex 死锁与统计读写锁不一致;移植固定上游 15 周期中位数 fallback、尾帧 limiter 归属保护;完整 hook present 返回间隔含批次边界。实测 scheduler 均可用,fallbackFrames=0,因此 fallback 尚未得到实际提供方条件触发验证。++本机 RTX 5070、驱动 32.0.16.1656:2X/3X/4X 恢复、2X/4X 平移及尺寸变化回归通过,调试错误 0。最终 4X 恢复测试三次断点下一帧均生成 3 帧,重复呈现不生成,编号超越案例正常退出。主程序 NR+XeSS4X smoke 退出 0,累计生成 588;25 秒进程中媒体先结束,末段为暂停刷新,不算 25 秒连续补帧。详细命令、日志和后续连续测试结果见 WORKLOG。++未完成:受影响用户游戏素材、真实采集 NV12/P010、30/40 系、功耗对齐、物理屏幕延迟,以及方案中完整分辨率/倍率 A/B 矩阵。未调整切镜阈值、未删除 capture pairDelay,不声称所有转身卡顿已根治。diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 6bd73a16..4ab11112 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -7,6 +7,7 @@#include "veyra/gfx/ReflexSession.h"#include "veyra/engine/PresentationSettings.h"#include <chrono>+#include <array>namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }namespace veyra::pipeline { class EnhanceGraph; }namespace veyra::sink { struct RgbaImage; }@@ -17,6 +18,9 @@ public:bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&, bool captureCompatible=false);bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,bool referencesValid=true,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={});void close();+ bool beginSourceInput();+ bool beginSourceProcessing();+ void sourceProcessed(pipeline::FrameIdentity);PresentationSettings configurePresentation(gfx::D3D12DeviceContext&,PresentationSettings,bool fg,std::wstring& status);bool presentationReady(){return sink_.presentationReady();}uint64_t beginReflex(){return reflex_.begin();}@@ -66,6 +70,10 @@ private:diagnostics::GpuTimer gpuTimer_;gfx::PresentSink sink_;pipeline::GraphicsPass pass_;+ pipeline::ComputePass presentMotionPass_;+ std::array<Microsoft::WRL::ComPtr<ID3D12Resource>,2> presentMotion_;+ PreviewView previousXessView_{};+ unsigned previousXessWidth_=0,previousXessHeight_=0;Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> rtvs_;unsigned inc_=0;unsigned lastBuffer_=0;bool hasPresented_=false;@@ -80,6 +88,10 @@ private:bool xessWasEnabled_=false;bool xessFailed_=false;bool xessGenerationSuppressed_=false;+ uint32_t xessInputId_=0;+ struct XessWork {pipeline::FrameIdentity identity{};uint32_t id=0;};+ std::array<XessWork,4> xessWork_{};+ size_t xessWorkPosition_=0;std::chrono::steady_clock::time_point lastFsrFrame_{};pipeline::FrameIdentity lastFsrIdentity_{};bool fsrWasEnabled_=false;diff --git a/include/veyra/gfx/XessPacing.h b/include/veyra/gfx/XessPacing.hindex 94aa38b2..160acf12 100644--- a/include/veyra/gfx/XessPacing.h+++ b/include/veyra/gfx/XessPacing.h@@ -21,7 +21,9 @@ namespace veyra::gfx {// thunk, recognises the two call sites that present generated frames, and hands// the loop's frames to the provider's own scheduler with the arguments the// present already carries (burst, frame index, gate byte, ring snapshot).-// Everything else is forwarded untouched.+// If that scheduler is unavailable, the upstream bounded 15-period median+// supplies wall-clock pacing, respecting the provider's tail-frame limiter.+// Everything outside those generated-frame call sites is forwarded untouched.//// Provider identity and structure are verified before the thunk is touched; a// mismatch refuses the hook instead of guessing, and release() restores the@@ -56,7 +58,7 @@ public:uint64_t scheduled = 0; // frames handed to the provider scheduleruint64_t refused = 0; // scheduler said no (its own gate)uint64_t forwarded = 0; // presents left untouched- uint64_t bypassed = 0; // frames skipped because the scheduler was off+ uint64_t bypassed = 0; // frames routed to the wall-clock fallback// Measured spacing between two consecutive scheduled frames.double meanGapMs = 0.0, minGapMs = 0.0, maxGapMs = 0.0;uint64_t gapSamples = 0;diff --git a/include/veyra/gfx/XessPresenter.h b/include/veyra/gfx/XessPresenter.hindex d75193f9..64ba01b6 100644--- a/include/veyra/gfx/XessPresenter.h+++ b/include/veyra/gfx/XessPresenter.h@@ -12,7 +12,9 @@ public:// fgMultiplier is the requested output multiplier (2 = one generated frame,// 3 = two, 4 = three). >2 requires the audited provider unlock.bool initialize(ID3D12Device*,ID3D12CommandQueue*,IDXGIFactory2*,HWND,const DXGI_SWAP_CHAIN_DESC1&,IDXGISwapChain3**,uint32_t fgMultiplier=1);- bool beginFrame();+ uint32_t beginInput();+ bool beginProcessing(uint32_t frameId);+ bool beginFrame(uint32_t preparedFrameId=0);bool tag(ID3D12GraphicsCommandList*,ID3D12Resource* color,ID3D12Resource* motion,ID3D12Resource* depth,RECT region,bool enabled,bool reset,float elapsedMs);bool beforePresent();diff --git a/scripts/acceptance/ui-cross-monitor.py b/scripts/acceptance/ui-cross-monitor.pynew file mode 100644index 00000000..33082d96--- /dev/null+++ b/scripts/acceptance/ui-cross-monitor.py@@ -0,0 +1,103 @@+"""Bounded own-process DPI and real monitor transition regression."""+import ctypes as c+import ctypes.wintypes as w+import json+import os+from pathlib import Path+import subprocess+import sys+import time++if '--worker' not in sys.argv:+ child = subprocess.Popen([sys.executable, __file__, '--worker', *sys.argv[1:]])+ try:+ sys.exit(child.wait(timeout=120))+ except subprocess.TimeoutExpired:+ subprocess.run(['taskkill.exe', '/PID', str(child.pid), '/T', '/F'], capture_output=True, timeout=5)+ sys.exit('FAIL: cross-monitor test exceeded 120 seconds')+sys.argv.remove('--worker')++exe, output = Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve()+output.mkdir(parents=True, exist_ok=True)+u = c.WinDLL('user32', use_last_error=True)+u.SetProcessDpiAwarenessContext.argtypes = [w.HANDLE]+u.SetProcessDpiAwarenessContext(c.c_void_p(-4))+u.GetWindowThreadProcessId.argtypes = [w.HWND, c.POINTER(w.DWORD)]+u.GetClassNameW.argtypes = [w.HWND, w.LPWSTR, c.c_int]+u.SetWindowPos.argtypes = [w.HWND, w.HWND, c.c_int, c.c_int, c.c_int, c.c_int, w.UINT]+u.SendMessageTimeoutW.argtypes = [w.HWND, w.UINT, w.WPARAM, w.LPARAM, w.UINT, w.UINT, c.POINTER(c.c_size_t)]+visit_type = c.WINFUNCTYPE(w.BOOL, w.HWND, w.LPARAM)+monitor_type = c.WINFUNCTYPE(w.BOOL, w.HANDLE, w.HDC, c.POINTER(w.RECT), w.LPARAM)+monitors = []++@monitor_type+def monitor_visit(handle, dc, rect, unused):+ r = rect.contents+ monitors.append([r.left, r.top, r.right, r.bottom])+ return True++u.EnumDisplayMonitors(None, None, monitor_visit, 0)+env = os.environ.copy()+env['VEYRA_LOG_FILE'] = str(output / 'app.log')+result = {'monitors': monitors, 'cases': [], 'passed': False}+media_args = sys.argv[3:] or ['--smoke-empty']+with (output / 'stdout.log').open('w') as stdout, (output / 'stderr.log').open('w') as stderr:+ process = subprocess.Popen([str(exe), '--smoke-view', 'pro', '--smoke-seconds', '90', *media_args], env=env, stdout=stdout, stderr=stderr)+ try:+ found = []++ @visit_type+ def visit(hwnd, unused):+ pid = w.DWORD()+ u.GetWindowThreadProcessId(hwnd, c.byref(pid))+ name = c.create_unicode_buffer(128)+ u.GetClassNameW(hwnd, name, 128)+ if pid.value == process.pid and name.value == 'VeyraApp':+ found.append(hwnd)+ return True++ end = time.monotonic() + 10+ while not found and time.monotonic() < end:+ u.EnumWindows(visit, 0)+ time.sleep(.1)+ assert found, 'main window missing'+ main = found[0]++ def send(message, first=0):+ reply = c.c_size_t()+ assert process.poll() is None, f'application exited {process.returncode}'+ assert u.SendMessageTimeoutW(main, message, first, 0, 2, 4000, c.byref(reply)), 'UI message timeout'++ time.sleep(5 if sys.argv[3:] else .3)+ for cycle in range(3):+ send(0x231) # Native interactive move entry.+ for dpi in [96, 144, 192, 0]:+ send(0x8000 + 90, dpi)+ assert u.SetWindowPos(main, None, 30, 30, 960+cycle*80+dpi, 640+cycle*40, 0x14)+ time.sleep(.2)+ result['cases'].append({'cycle': cycle, 'syntheticDpi': dpi})+ for rect in monitors:+ assert u.SetWindowPos(main, None, rect[0]+30, rect[1]+30, 960+cycle*80, 640+cycle*40, 0x14)+ time.sleep(.3)+ send(0)+ result['cases'].append({'cycle': cycle, 'monitor': rect})+ send(0x232)+ time.sleep(.4)+ send(0x10)+ assert process.wait(timeout=10) == 0+ if sys.argv[3:]:+ log = (output / 'app.log').read_text(encoding='utf-8')+ assert '[present-cost]' in log, 'no actual presentation evidence'+ for segment in log.split('interactive move begin;')[1:]:+ moving, released = segment.split('interactive move end;', 1)+ assert 'present-sink: resized' not in moving, 'buffers rebuilt during move'+ assert '[present-cost]' in moving, 'no presentation observed during move'+ assert 'present-sink: resized' in released, 'final resize did not resume'+ result['passed'] = True+ finally:+ if process.poll() is None:+ process.kill()+ process.wait(timeout=5)+ result['exitCode'] = process.returncode+ (output / 'result.json').write_text(json.dumps(result, indent=2), encoding='utf-8')+print(json.dumps(result))diff --git a/shaders/PresentMotion.hlsl b/shaders/PresentMotion.hlslnew file mode 100644index 00000000..a62768b4--- /dev/null+++ b/shaders/PresentMotion.hlsl@@ -0,0 +1,27 @@+// Same contain/zoom/pan mapping as PresentBlit, with current->previous motion.+Texture2D<float2> sourceMotion : register(t0);+RWTexture2D<float2> outputMotion : register(u0);+cbuffer Mapping : register(b0) {+ float4 extent; // source extent, current client extent+ float4 currentView; // zoom, center x/y, reset+ float4 previousView; // zoom, center x/y, unused+ float4 previousClient; // width/height, unused+};+[numthreads(8,8,1)]+void main(uint3 tid : SV_DispatchThreadID) {+ uint2 size; outputMotion.GetDimensions(size.x,size.y);+ if(any(tid.xy>=size))return;+ float2 displayUv=(float2(tid.xy)+.5)/float2(size);+ float fit=min(extent.z/extent.x,extent.w/extent.y)*currentView.x;+ float2 sourceUv=(displayUv-.5)*extent.zw/(extent.xy*fit)+currentView.yz;+ if(currentView.w!=0||any(sourceUv<0)||any(sourceUv>=1)) {+ outputMotion[tid.xy]=0;return;+ }+ uint2 motionSize;sourceMotion.GetDimensions(motionSize.x,motionSize.y);+ int2 samplePixel=min(int2(sourceUv*motionSize),int2(motionSize)-1);+ float2 previousUv=sourceUv+sourceMotion.Load(int3(samplePixel,0))/extent.xy;+ float previousFit=min(previousClient.x/extent.x,previousClient.y/extent.y)*previousView.x;+ float2 previousDisplay=.5+(previousUv-previousView.yz)*extent.xy*previousFit/previousClient.xy;+ outputMotion[tid.xy]=(any(previousUv<0)||any(previousUv>=1)||any(previousDisplay<0)||any(previousDisplay>=1))?+ float2(0,0):(previousDisplay-displayUv)*float2(size);+}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 36f27edf..d55a8e3e 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -912,6 +912,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}if(stop_||seekSeconds_>=0||(paused_&&!seekPreviewPending)||liveScheduler->failed()||liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable()||enhancementPending())continue;}+ // Wait before selecting the latest sample, not after enhancement.+ if(!presenter.beginSourceInput()){status(L"XeSS input timing failed",true);break;}const auto decodeStart=Clock::now();loopTrace.mark("controlAndSchedule");if(injectSourceGap&&frames>=12){@@ -1091,6 +1093,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto currentReflexFrame=(!paused_&&!isImage)?presenter.beginReflex():0;if(!isImage&&GetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",testWork,16))std::this_thread::sleep_for(std::chrono::milliseconds(std::clamp(_wtoi(testWork),0,150)));loopTrace.mark("prepare");+ if(!presenter.beginSourceProcessing()){status(L"XeSS processing timing failed",true);break;}bool processed=false;{processWaitBase=ring.cpuWaitCount();processWaitMsBase=ring.cpuWaitMilliseconds();processSubmitBase=ring.submitCount();processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0,admitFg);processSlotWaitMs=ring.cpuWaitMilliseconds()-processWaitMsBase;}loopTrace.mark("graphSubmit");previewSkipSinceProcess=false;@@ -1130,6 +1133,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}if(transaction){std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;snapshot_.status=std::format(L"输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrBeforeSr?L"低延迟 · NR先行后超分":gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)");veyra::log::info("display-color",std::format("hdrInput={} hdrOutput={} forceSdrPreview={}",gd.hdrInput,gd.hdrOutput,options.settings.forceSdrPreview));veyra::log::info("settings",std::format("Applied revision={} sourcePtsMs={} fgBackend={} flowBackend={} multiplier={} (source kept open)",options.settings.revision,pts,frameGenerationBackendName(options.settings.frameGenerationBackend),opticalFlowBackendName(options.settings.opticalFlowBackend),options.snapshot().multiplier));}if(veyra::log::verboseFrameLogs())veyra::log::info("source-identity",std::format("source={} totalRead={} graphProcessed={} cached={} revision={} nvofStandalone={}",pkt.sequence,sourceFrames,frames+1,rereadCached,options.settings.revision,gd.enableNvofStandalone));+ presenter.sourceProcessed(out.batch.identity);reset=false;hasOutput=true;const auto processDone=Clock::now();if(physicalCapture&&veyra::log::verboseFrameLogs())veyra::log::info("capture-graph-sample",std::format("source={} epoch={} revision={} arrival={} start={} submitted={} slotWaitMs={:.6f}",pkt.sequence,out.batch.identity.epoch,out.batch.identity.settingsRevision,captureArrival,std::chrono::duration_cast<std::chrono::nanoseconds>(processStart.time_since_epoch()).count()/100,std::chrono::duration_cast<std::chrono::nanoseconds>(processDone.time_since_epoch()).count()/100,processSlotWaitMs));diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 429beafa..dc73e002 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -5,6 +5,21 @@#include "veyra/gfx/CommandSlotRing.h"#include "veyra/sink/ImageExportSink.h"namespace veyra::engine {+bool VideoPresenter::beginSourceInput(){+ auto* xess=sink_.xess();if(!xess)return true;+ // Waiting/filtered inputs keep the same preparation ID. Do not sleep again+ // until one accepted source has been submitted to the enhancement graph.+ if(!xessInputId_)xessInputId_=xess->beginInput();+ return xessInputId_!=0;+}+bool VideoPresenter::beginSourceProcessing(){+ auto* xess=sink_.xess();return !xess||(beginSourceInput()&&xess->beginProcessing(xessInputId_));+}+void VideoPresenter::sourceProcessed(pipeline::FrameIdentity identity){+ if(!xessInputId_)return;+ xessWork_[xessWorkPosition_]={identity,xessInputId_};+ xessWorkPosition_=(xessWorkPosition_+1)%xessWork_.size();xessInputId_=0;+}bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph,bool captureCompatible) {close();viewWidth_=viewHeight_=0;bufferMonitor_=nullptr;monitorWidth_=monitorHeight_=0;@@ -38,6 +53,18 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh// SRV layout: 0..1 video frames, 2..11 generated frames (2 parities x 5// subframes, 6X), 12..15 comparison references.if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,16,graph.outputFormat()))return false;+ if(sink_.xess()){+ std::vector<uint8_t> cs;+ if(!pipeline::loadShaderBytes("PresentMotion.dxil",cs)||!presentMotionPass_.create(ctx.device(),cs,4,1,1,16))return false;+ const auto heap=presentMotionPass_.heap->GetCPUDescriptorHandleForHeapStart();+ for(unsigned i=0;i<2;++i){+ presentMotion_[i]=pipeline::makeTexture(ctx.device(),graph.workWidth(),graph.workHeight(),DXGI_FORMAT_R16G16_FLOAT,true);+ if(!presentMotion_[i])return false;+ presentMotion_[i]->SetName(L"Veyra XeSS display motion");+ pipeline::makeSrv(ctx.device(),graph.presentMotion(i),DXGI_FORMAT_R16G16_FLOAT,{heap.ptr+size_t(i*2)*presentMotionPass_.increment});+ pipeline::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;if(FAILED(ctx.device()->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&rtvs_))))return false;inc_=ctx.device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);refresh(ctx.device());@@ -71,7 +98,11 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&targetWidth=std::max({targetWidth,sink_.width(),monitorWidth_});targetHeight=std::max({targetHeight,sink_.height(),monitorHeight_});}- if((targetWidth!=sink_.width()||targetHeight!=sink_.height())&&GetTickCount64()>=deferUntil&&now-lastResize_>=std::chrono::milliseconds(100)) {+ // The UI keeps pumping messages during the native move loop. Retain and+ // stretch current buffers there instead of repeatedly draining the GPU+ // and rebuilding provider resources at monitor/DPI boundaries.+ const bool windowChanging=GetPropW(window_,L"Veyra.InteractiveMove")||GetPropW(window_,L"Veyra.DpiTransition");+ if(!windowChanging&&(targetWidth!=sink_.width()||targetHeight!=sink_.height())&&GetTickCount64()>=deferUntil&&now-lastResize_>=std::chrono::milliseconds(100)) {resized=true;if(!ring.drainQueue())return false;sink_.resize(targetWidth,targetHeight);// A capture hook may temporarily retain a DXGI buffer. Keep the old@@ -80,7 +111,11 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&refresh(ctx.device());lastResize_=now;xessWasEnabled_=false;}const auto resizeEnd=std::chrono::steady_clock::now();- if(sink_.xess()&&!sink_.xess()->beginFrame()){xessFailed_=true;return false;}+ if(auto* xess=sink_.xess()){+ uint32_t preparedId=0;+ for(auto& work:xessWork_)if(work.id&&work.identity==identity){preparedId=work.id;work.id=0;break;}+ if(!xess->beginFrame(preparedId)){xessFailed_=true;return false;}+ }const auto beginEnd=std::chrono::steady_clock::now();if(presentationQueue_){const HRESULT hr=presentationQueue_->Wait(ctx.fence(),graph.presentationReadyFence(slot,generated));@@ -128,35 +163,44 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&if(GetEnvironmentVariableW(L"VEYRA_TEST_XESS_PRESENT_FAILURE",nullptr,0)>0){veyra::log::warn("backend-test","Injected XeSS tagging failure with recorded commands");xessFailed_=true;return false;}- const bool enabled=regionVisible&&!generated&&!comparison&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastXessIdentity_.sourceFrameId&&!xessGenerationSuppressed_;- const bool reset=!xessWasEnabled_||identity.epoch!=lastXessIdentity_.epoch||identity.settingsRevision!=lastXessIdentity_.settingsRevision||graph.motionPreviousSource(slot)!=lastXessIdentity_.sourceFrameId;- const float elapsed=lastXessFrame_==std::chrono::steady_clock::time_point{}?0.0f:float(std::chrono::duration<double,std::milli>(now-lastXessFrame_).count());+ // A history break is not a user disable: the graph supplies initialized+ // zero motion in this case. Keep the current color in XeSS history so+ // the next continuous frame can interpolate without another warmup.+ const bool enabled=regionVisible&&!generated&&!comparison&&graph.presentMotion(slot)&&graph.presentDepth()&&identity.sourceFrameId!=lastXessIdentity_.sourceFrameId&&!xessGenerationSuppressed_;+ const bool reset=!graph.presentMotionValid(slot)||!xessWasEnabled_||identity.epoch!=lastXessIdentity_.epoch||identity.settingsRevision!=lastXessIdentity_.settingsRevision||graph.motionPreviousSource(slot)!=lastXessIdentity_.sourceFrameId;+ // Present-to-present time includes provider waits. Feeding it back as+ // render time can lengthen the next burst. Intel documents zero as the+ // supported value when an independent frame-time estimate is absent.+ constexpr float elapsed=0.0f;auto* motion=graph.presentMotion(slot);auto* depth=graph.presentDepth();if(enabled){- // XeSS-FG ONLY_NOW records its input copies on this same command- // list. Keep the Veyra state contract explicit on both sides.- // Timed as the application-side frame-generation stage: the- // provider's internal interpolation cannot be timestamped, but the- // copies and barriers it makes us record can, and that is what the- // dashboard shows for present-sink FG backends.+ // Stable full-buffer interpolation avoids provider letterbox+ // reallocations. Guidance must follow the same displayed domain.+ auto* mapped=presentMotion_[slot].Get();+ pipeline::StateTracker states;+ states.transition(list,motion,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ states.transition(list,mapped,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ const auto previous=reset?view:previousXessView_;+ const float mapping[16]={float(graph.workWidth()),float(graph.workHeight()),float(rc.right),float(rc.bottom),+ view.zoom,view.centerX,view.centerY,reset?1.0f:0.0f,+ previous.zoom,previous.centerX,previous.centerY,0,+ float(reset?rc.right:previousXessWidth_),float(reset?rc.bottom:previousXessHeight_),0,0};+ const auto heap=presentMotionPass_.heap->GetGPUDescriptorHandleForHeapStart().ptr;+ presentMotionPass_.bind(list,mapping,heap+size_t(slot*2)*presentMotionPass_.increment,heap+size_t(slot*2+1)*presentMotionPass_.increment);+ list->Dispatch((graph.workWidth()+7)/8,(graph.workHeight()+7)/8,1);+ states.transition(list,mapped,D3D12_RESOURCE_STATE_COMMON);+ states.transition(list,motion,D3D12_RESOURCE_STATE_COMMON);+ // No graph work or resource reuse may occur between tagging and+ // Present. XeSS transitions from/to COMMON on this same queue.+ // This timer covers application commands, not provider execution.gpuTimer_.mark(list,diagnostics::GpuStage::FgBatch);- ID3D12Resource* resources[]={bb,motion,depth};- D3D12_RESOURCE_BARRIER toCopy[3]{};- for(unsigned i=0;i<3;++i){- toCopy[i].Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;- toCopy[i].Transition.pResource=resources[i];- toCopy[i].Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;- toCopy[i].Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;- toCopy[i].Transition.StateAfter=D3D12_RESOURCE_STATE_COPY_SOURCE;- }- list->ResourceBarrier(3,toCopy);- if(!xess->tag(list,bb,motion,depth,fgRect,true,reset,elapsed)){xessFailed_=true;return false;}- for(auto& barrier:toCopy)std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);- list->ResourceBarrier(3,toCopy);+ const RECT fullBuffer{0,0,LONG(sink_.bufferWidth()),LONG(sink_.bufferHeight())};+ if(!xess->tag(list,bb,mapped,depth,fullBuffer,true,reset,elapsed)){xessFailed_=true;return false;}gpuTimer_.mark(list,diagnostics::GpuStage::FgBatch,true);}else if(!xess->tag(list,bb,motion,depth,fgRect,false,reset,elapsed)){xessFailed_=true;return false;}lastXessFrame_=now;lastXessIdentity_=identity;xessWasEnabled_=enabled;+ previousXessView_=view;previousXessWidth_=rc.right;previousXessHeight_=rc.bottom;}if(auto* fsr=sink_.fsr()){const bool enabled=regionVisible&&!generated&&!comparison&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastFsrIdentity_.sourceFrameId;@@ -199,9 +243,11 @@ bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx:return SUCCEEDED(sink_.swapChain()->GetBuffer(lastBuffer_,IID_PPV_ARGS(&buffer)))&&sink::readRgba8(ctx,ring,buffer.Get(),image);}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();+ presentMotionPass_={};presentMotion_={};previousXessWidth_=previousXessHeight_=0;presentationRing_.shutdown();presentationFence_.Reset();presentationQueue_.Reset();if(presentationEvent_){CloseHandle(presentationEvent_);presentationEvent_=nullptr;}}diff --git a/src/gfx/XessPacing.cpp b/src/gfx/XessPacing.cppindex ed0942a7..36cb745e 100644--- a/src/gfx/XessPacing.cpp+++ b/src/gfx/XessPacing.cpp@@ -4,6 +4,7 @@#include "veyra/ThunkHook.h"#include <algorithm>+#include <array>#include <cstring>#include <filesystem>#include <intrin.h>@@ -21,6 +22,7 @@ using RingSnapshotFn = void* (*)(void*, void*);struct PacingState {std::mutex mutex;+ std::mutex statsMutex;ThunkHook hook;bool installed = false;uint8_t* base = nullptr;@@ -43,6 +45,12 @@ struct PacingState {int64_t statsDeadlineQpc = 0;int64_t lastMultiplier = 0;int32_t logBudget = 6;+ int64_t lastPresentQpc = 0, presentGapSum = 0, presentGapMax = 0;+ uint64_t presentGapSamples = 0;+ std::array<int64_t,15> periods{};+ size_t periodCount=0,periodPosition=0;+ int64_t lastBurstQpc=0,periodQpc=0,intervalQpc=0,targetQpc=0;+ uint64_t fallbackFrames=0;};PacingState& state() {@@ -71,6 +79,39 @@ bool schedulerUsable(void* ctx) {return bytes[XessPacing::kSchedLimiterOffset] == 0 && bytes[XessPacing::kSchedEnableOffset] != 0;}+// Adapted from OptiScaler 70676c5f XeFGPacing.h NoteFrame/PaceFrame/WaitUntil.+// The provider present thread owns this bounded median and deadline state.+void noteBurst(uint64_t index,uint64_t count,int64_t now) {+ if(index>1)return;+ auto& s=state();+ if(s.lastBurstQpc&&now>s.lastBurstQpc){+ s.periods[s.periodPosition]=(now-s.lastBurstQpc);+ s.periodPosition=(s.periodPosition+1)%s.periods.size();+ s.periodCount=(std::min)(s.periodCount+1,s.periods.size());+ auto sorted=s.periods;std::sort(sorted.begin(),sorted.begin()+s.periodCount);+ s.periodQpc=sorted[s.periodCount/2];+ }+ s.lastBurstQpc=now;+ s.intervalQpc=s.periodQpc/int64_t(count+1);+}++void paceFallback(void* ctx,uint8_t* burst,uint64_t index,uint64_t count,bool isLast) {+ // Match the provider's tail-frame limiter condition; never wait twice.+ if(isLast&&count>2&&reinterpret_cast<uint8_t*>(ctx)[XessPacing::kSchedLimiterOffset]!=0&&+ *reinterpret_cast<uint32_t*>(burst+0x28)==0)return;+ auto& s=state();LARGE_INTEGER now{};QueryPerformanceCounter(&now);+ if(s.intervalQpc<=0)return;+ if(index<=1)s.targetQpc=now.QuadPart+s.intervalQpc;+ else s.targetQpc+=s.intervalQpc;+ s.targetQpc=(std::min)(s.targetQpc,now.QuadPart+s.periodQpc);+ const auto yieldBelow=s.frequency.QuadPart/5000;+ while(now.QuadPart<s.targetQpc){+ if(s.targetQpc-now.QuadPart>yieldBelow)Sleep(0);else YieldProcessor();+ QueryPerformanceCounter(&now);+ }+ std::lock_guard statsLock(s.statsMutex);++s.fallbackFrames;+}+// One schedule call per generated frame, mirroring the provider's own order:// snapshot the ring first, then schedule. Every argument is in hand because we// sit inside the present call the provider itself made.@@ -87,6 +128,7 @@ void scheduleFrame(void* ctx, uint8_t* burst, uint64_t index) {const bool ok = s.sched(ctx, burst, gate, timing, static_cast<uint32_t>(index));QueryPerformanceCounter(&after);+ std::lock_guard statsLock(s.statsMutex);++s.scheduled;if (!ok) ++s.refused;@@ -136,7 +178,7 @@ void tryPace(void* ctx, void* arg5, void* arg6, uint64_t arg7, bool isLast) {if ((flag == 1) == isLast) return;auto* burst = reinterpret_cast<uint8_t*>(arg5) - 0x38;const uint64_t count = *reinterpret_cast<uint64_t*>(burst + 8);- if (count < 1 || count > 5) return;+ if (count < 2 || count > 5) return;uint64_t index = count;if (!isLast) {auto* frames = *reinterpret_cast<uint8_t**>(burst);@@ -147,14 +189,15 @@ void tryPace(void* ctx, void* arg5, void* arg6, uint64_t arg7, bool isLast) {if (index < 1 || index >= count) return;}auto& s = state();+ LARGE_INTEGER burstNow{};QueryPerformanceCounter(&burstNow);noteBurst(index,count,burstNow.QuadPart);if (s.sched != nullptr && schedulerUsable(ctx)) {// The provider keeps the last frame of the burst; scheduling it twice// would put two timestamps on one frame.if (!isLast) scheduleFrame(ctx, burst, index);return;}- // Limiter owns the pacing: the provider already waits for the last frame,- // and nothing here pretends to have paced the intermediate ones.+ paceFallback(ctx,burst,index,count,isLast);+ std::lock_guard statsLock(s.statsMutex);++s.bypassed;}@@ -164,9 +207,21 @@ int64_t detour(void* ctx, uint32_t a2, uint32_t a3, uint64_t a4, void* arg5, voiauto* caller = static_cast<uint8_t*>(_ReturnAddress());if (caller == s.base + XessPacing::kPacedCallerRva) tryPace(ctx, arg5, arg6, arg7, false);else if (caller == s.base + XessPacing::kLastFrameCallerRva) tryPace(ctx, arg5, arg6, arg7, true);- else ++s.forwarded;+ else {std::lock_guard statsLock(s.statsMutex);++s.forwarded;}+ }+ const auto result=s.native(ctx, a2, a3, a4, arg5, arg6, arg7);+ LARGE_INTEGER now{};QueryPerformanceCounter(&now);+ std::lock_guard statsLock(s.statsMutex);+ if(s.lastPresentQpc!=0){+ const auto gap=now.QuadPart-s.lastPresentQpc;+ s.presentGapSum+=gap;s.presentGapMax=(std::max)(s.presentGapMax,gap);+ if(++s.presentGapSamples==240){+ log::info("xess-present-gaps",std::format("samples={} meanMs={:.3f} maxMs={:.3f} (all hooked present returns, includes burst boundaries; not scanout)",s.presentGapSamples,msFromQpc(s,s.presentGapSum/int64_t(s.presentGapSamples)),msFromQpc(s,s.presentGapMax)));+ s.presentGapSamples=0;s.presentGapSum=s.presentGapMax=0;+ }}- return s.native(ctx, a2, a3, a4, arg5, arg6, arg7);+ s.lastPresentQpc=now.QuadPart;+ return result;}// A thunk is `E9 rel32` followed by 0xCC padding; the rel32 must reach@@ -185,7 +240,7 @@ bool thunkTargets(const uint8_t* base, uint32_t rva, uint32_t expectedTargetRva)XessPacing::State XessPacing::install(HMODULE provider, uint32_t generatedFrames) {auto& s = state();- std::lock_guard lock(s.mutex);+ std::unique_lock lock(s.mutex);State result{};result.generatedFrames = generatedFrames;if (provider == nullptr) {@@ -198,6 +253,7 @@ XessPacing::State XessPacing::install(HMODULE provider, uint32_t generatedFramesreturn result;}if (s.installed) {+ lock.unlock();result = snapshot();return result;}@@ -230,6 +286,9 @@ XessPacing::State XessPacing::install(HMODULE provider, uint32_t generatedFramess.generatedFrames = generatedFrames;s.scheduled = s.refused = s.forwarded = s.bypassed = 0;s.lastScheduledQpc = 0;+ s.lastPresentQpc=s.presentGapSum=s.presentGapMax=0;s.presentGapSamples=0;+ s.periods={};s.periodCount=s.periodPosition=0;+ s.lastBurstQpc=s.periodQpc=s.intervalQpc=s.targetQpc=0;s.fallbackFrames=0;s.gapSum = s.gapSamples = 0;s.gapMin = s.gapMax = 0;s.lastMultiplier = 0;@@ -265,13 +324,14 @@ void XessPacing::release() {s.native = nullptr;s.sched = nullptr;s.ringSnapshot = nullptr;- log::info("xess-pacing", std::format("removed (scheduled={} refused={} bypassed={} forwarded={})",- s.scheduled, s.refused, s.bypassed, s.forwarded));+ log::info("xess-pacing", std::format("removed (scheduled={} refused={} bypassed={} forwarded={} fallbackFrames={})",+ s.scheduled, s.refused, s.bypassed, s.forwarded,s.fallbackFrames));}XessPacing::State XessPacing::snapshot() {auto& s = state();std::lock_guard lock(s.mutex);+ std::lock_guard statsLock(s.statsMutex);State result{};result.providerLoaded = s.base != nullptr;result.structureVerified = s.sched != nullptr;diff --git a/src/gfx/XessPresenter.cpp b/src/gfx/XessPresenter.cppindex b6000d49..7c5978f5 100644--- a/src/gfx/XessPresenter.cpp+++ b/src/gfx/XessPresenter.cpp@@ -30,7 +30,7 @@ struct XessPresenter::Impl {HMODULE fgDll=nullptr,llDll=nullptr;xefg_swapchain_handle_t fg=nullptr;xell_context_handle_t ll=nullptr;- uint32_t id=0;+ uint32_t id=0,nextId=0;#define XESS_PROC(name) decltype(&name) name##Fn=nullptrXESS_PROC(xefgSwapChainD3D12CreateContext);XESS_PROC(xefgSwapChainD3D12GetProperties);@@ -56,7 +56,8 @@ struct XessPresenter::Impl {if(result!=0||always||log::verboseFrameLogs())log::info("xess-fg",std::format("{} result={} presentId={}",operation,result,id));return result>=0;}- bool marker(xell_latency_marker_type_t m){return check(xellAddMarkerDataFn(ll,id,m),"XeLL marker");}+ bool marker(xell_latency_marker_type_t m,uint32_t frameId){return check(xellAddMarkerDataFn(ll,frameId,m),"XeLL marker");}+ bool marker(xell_latency_marker_type_t m){return marker(m,id);}~Impl(){if(fg&&xefgSwapChainDestroyFn)check(xefgSwapChainDestroyFn(fg),"Destroy",true);if(ll&&xellDestroyContextFn)check(xellDestroyContextFn(ll),"XeLL destroy",true);@@ -173,13 +174,35 @@ bool XessPresenter::initialize(ID3D12Device* device,ID3D12CommandQueue* queue,IDlog::error("xess-fg","Intel XeSS SDK unavailable at build time");return false;#endif}-bool XessPresenter::beginFrame(){+uint32_t XessPresenter::beginInput(){#ifdef VEYRA_HAS_XESS- auto& p=*p_;++p.id;- diagnostics::CpuStallTrace trace("xess-begin-stall",p.id);- const bool slept=p.check(p.xellSleepFn(p.ll,p.id),"XeLL sleep");trace.mark("sleep");- return slept&&p.marker(XELL_SIMULATION_START)&&p.marker(XELL_SIMULATION_END)&&p.marker(XELL_RENDERSUBMIT_START);+ auto& p=*p_;const auto frameId=++p.nextId;+ diagnostics::CpuStallTrace trace("xess-begin-stall",frameId);+ const bool slept=p.check(p.xellSleepFn(p.ll,frameId),"XeLL sleep");trace.mark("sleep");+ return slept&&p.marker(XELL_SIMULATION_START,frameId)?frameId:0;#else+ return 0;+#endif+}+bool XessPresenter::beginProcessing(uint32_t frameId){+#ifdef VEYRA_HAS_XESS+ auto& p=*p_;return frameId&&p.marker(XELL_SIMULATION_END,frameId)&&p.marker(XELL_RENDERSUBMIT_START,frameId);+#else+ (void)frameId;return false;+#endif+}+bool XessPresenter::beginFrame(uint32_t preparedFrameId){+#ifdef VEYRA_HAS_XESS+ auto& p=*p_;+ // Prepared frames keep the ID assigned before source sampling, even while+ // another source frame is in flight. Repaints have no enhancement phase.+ if(preparedFrameId>p.id){p.id=preparedFrameId;return true;}+ // A repaint can overtake queued work. Never submit an older present ID;+ // the fallback measures this presentation only, not the earlier graph work.+ if(preparedFrameId)log::info("xess-fg",std::format("retire overtaken preparation id={} lastPresentId={}; new presentation markers",preparedFrameId,p.id));+ p.id=beginInput();return p.id&&beginProcessing(p.id);+#else+ (void)preparedFrameId;return false;#endif}@@ -189,16 +212,15 @@ bool XessPresenter::tag(ID3D12GraphicsCommandList* list,ID3D12Resource* color,IDif(!p.check(p.xefgSwapChainSetEnabledFn(p.fg,enabled?1:0),"SetEnabled"))return false;if(!enabled)return true;if(!color||!motion||!depth||!list||region.right<=region.left||region.bottom<=region.top)return false;- // ONLY_NOW makes XeSS copy each input into its own storage on this- // submitted command list. The caller transitions the resources to and- // from COPY_SOURCE around this call, which is the state required by the- // XeSS-FG resource contract for this validity mode.+ // The presenter owns these inputs until Present returns and submits on the+ // same queue. Let the provider defer its reads to Present instead of making+ // immediate staging copies while our blit list is still being recorded.auto resource=[&](xefg_swapchain_resource_type_t type,ID3D12Resource* tex,bool regionColor){- xefg_swapchain_d3d12_resource_data_t data{};data.type=type;data.validity=XEFG_SWAPCHAIN_RV_ONLY_NOW;- data.pResource=tex;data.incomingState=D3D12_RESOURCE_STATE_COPY_SOURCE;+ xefg_swapchain_d3d12_resource_data_t data{};data.type=type;data.validity=XEFG_SWAPCHAIN_RV_UNTIL_NEXT_PRESENT;+ data.pResource=tex;data.incomingState=D3D12_RESOURCE_STATE_COMMON;const auto d=tex->GetDesc();data.resourceSize={uint32_t(d.Width),d.Height};if(regionColor){data.resourceBase={uint32_t(region.left),uint32_t(region.top)};data.resourceSize={uint32_t(region.right-region.left),uint32_t(region.bottom-region.top)};}- return p.check(p.xefgSwapChainD3D12TagFrameResourceFn(p.fg,list,p.id,&data),"Tag resource");+ return p.check(p.xefgSwapChainD3D12TagFrameResourceFn(p.fg,nullptr,p.id,&data),"Tag resource");};if(!resource(XEFG_SWAPCHAIN_RES_BACKBUFFER,color,true)||!resource(XEFG_SWAPCHAIN_RES_HUDLESS_COLOR,color,true)||!resource(XEFG_SWAPCHAIN_RES_MOTION_VECTOR,motion,false)||!resource(XEFG_SWAPCHAIN_RES_DEPTH,depth,false))return false;xefg_swapchain_frame_constant_data_t constants{};diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex b8223b3f..87881b8a 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -392,7 +392,7 @@ bool EnhanceGraph::createResources()}const bool directBase=!srEnabled_&&srcW_==workW_&&srcH_==workH_;workRgba_=directBase?srcRgba_:makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);- for(unsigned i=0;i<2;++i){sourceReferences_[i]=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);baseReferences_[i]=directBase?sourceReferences_[i]:makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);if(!sourceReferences_[i]||!baseReferences_[i])return false;}+ for(unsigned i=0;i<2;++i){sourceReferences_[i]=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);baseReferences_[i]=(directBase&&!desc_.color.enabled)?sourceReferences_[i]:makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);if(!sourceReferences_[i]||!baseReferences_[i])return false;}nrInput_=(desc_.nrBeforeSr&&nrW_==srcW_&&nrH_==srcH_)?srcRgba_:(nrW_==workW_&&nrH_==workH_)?workRgba_:makeTexture(context_.device(),nrW_,nrH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);residualRgba_=makeTexture(context_.device(),desc_.nrBeforeSr?srcW_:workW_,desc_.nrBeforeSr?srcH_:workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);nrFlow_=makeTexture(context_.device(),nrW_,nrH_,DXGI_FORMAT_R16G16_FLOAT,true);@@ -1530,11 +1530,12 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// 2. YUV -> RGBA16F.if(colorActive_&&colorDirty_)uploadColorTables(list);+ auto convertInput=[&](bool grade){tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);if(desc_.rgbInput||desc_.yuy2Input||desc_.packedInput){float c[8+kColorGradeConstantCount]={uintBits(srcW_),uintBits(srcH_),uintBits(workingTransferCode(resolved)),uintBits(resolved.range==ColorRange::Limited?1u:0u),resolved.range==ColorRange::Full?0.0f:1.0f,resolved.matrix==YuvMatrix::BT2020NCL?2.0f:resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,resolved.primaries==ColorPrimaries::BT2020?1.0f:0.0f,uintBits(desc_.packedInput)};- if(colorActive_)packColorGradeConstants(colorTables_,c+8);+ if(grade)packColorGradeConstants(colorTables_,c+8);if(resolved.scRgb){c[4]=desc_.hdrWorking()?1.f:2.f;c[5]=toneMapPeakNits_;}rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,gpuRgb?3+parity:0).ptr,gpuHandleOf(rgbPass_,1).ptr,gpuHandleOf(rgbPass_,8).ptr);list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);@@ -1544,11 +1545,22 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameresolved.transfer==TransferFunction::HLG?5.0f:resolved.transfer==TransferFunction::PQ?4.0f:float(workingTransferCode(resolved)), (nv12Texture?(nv12Texture->GetDesc().Format==DXGI_FORMAT_P010?1.0f:0.0f):(desc_.captureBitDepth==16?2.0f:desc_.wideYuvInput()?1.0f:0.0f)),uintBits(srcW_), uintBits(srcH_), uintBits((desc_.hdrWorking()?1u:0u)|(resolved.primaries==ColorPrimaries::BT2020?2u:0u)),uintBits(resolved.reconstructChroma?std::max(1u,unsigned(resolved.chromaLocation)):0u),toneMapPeakNits_,203.0f,0,0 };- if(colorActive_)packColorGradeConstants(colorTables_,constants+12);+ if(grade)packColorGradeConstants(colorTables_,constants+12);yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, nv12Texture ? 3 + parity * 2 : 0).ptr, gpuHandleOf(yuvPass_, 2).ptr,gpuHandleOf(yuvPass_,8).ptr);list->Dispatch((srcW_ + 15) / 16, (srcH_ + 15) / 16, 1);}tracker_.uavBarrier(list, srcRgba_.Get());+ };+ // Grading is fused into input conversion. Retain a genuinely ungraded+ // reference only when comparison requests it, then run the normal input.+ if(colorActive_&&retainReferences){+ convertInput(false);+ tracker_.transition(list,srcRgba_.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);+ tracker_.transition(list,sourceReferences_[parity].Get(),D3D12_RESOURCE_STATE_COPY_DEST);+ list->CopyResource(sourceReferences_[parity].Get(),srcRgba_.Get());+ tracker_.transition(list,sourceReferences_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);+ }+ convertInput(colorActive_);tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);if(gpuRgb)tracker_.transition(list,hardwareSurface->texture,D3D12_RESOURCE_STATE_COMMON);if (nv12Texture != nullptr) {@@ -1725,7 +1737,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// Comparison references belong to this real-frame lease. Avoid the two// full-frame copies when comparison is disabled.auto retain=[&](ID3D12Resource* src,ID3D12Resource* dst){tracker_.transition(list,src,D3D12_RESOURCE_STATE_COPY_SOURCE);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(dst,src);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,src,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);};- retain(srcRgba_.Get(),sourceReferences_[parity].Get());+ if(!colorActive_)retain(srcRgba_.Get(),sourceReferences_[parity].Get());if(baseReferences_[parity].Get()!=sourceReferences_[parity].Get())retain(workRgba_.Get(),baseReferences_[parity].Get());}@@ -1865,7 +1877,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame}if(presentSinkFg()){- auto* input=haveFlow?baseFlow_.Get():nrZeroMotion_.Get();+ auto* input=haveFlow&&!reset?baseFlow_.Get():nrZeroMotion_.Get();tracker_.transition(list,input,D3D12_RESOURCE_STATE_COPY_SOURCE);tracker_.transition(list,presentMotion_[parity].Get(),D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(presentMotion_[parity].Get(),input);diff --git a/tests/integration/ColorGradeGpuTests.cpp b/tests/integration/ColorGradeGpuTests.cppindex 216ca85c..12651d31 100644--- a/tests/integration/ColorGradeGpuTests.cpp+++ b/tests/integration/ColorGradeGpuTests.cpp@@ -68,13 +68,13 @@ struct Graph {gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;pipeline::EnhanceGraph g{ctx,ring};bool up=false;- bool start(bool colorEnabled){+ bool start(bool colorEnabled,bool rgb=true){gfx::DeviceContextDesc device;Status st;if(!ctx.initialize(device,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return false;up=true;pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.sourceHeight=gd.workWidth=gd.workHeight=kSize;- gd.rgbInput=true;gd.stillImage=true;gd.noFeatures=true;gd.enableNr=false;gd.enableSr=false;gd.enableFg=false;+ gd.rgbInput=rgb;gd.stillImage=true;gd.noFeatures=true;gd.enableNr=false;gd.enableSr=false;gd.enableFg=false;gd.color.enabled=colorEnabled;return g.initialize(gd)&&g.createViews();}@@ -112,12 +112,67 @@ struct Graph {~Graph(){if(up){ring.drainQueue();g.shutdown();ring.shutdown();ctx.shutdown();}}};struct Pixel { int r=0,g=0,b=0; };+// Test-only raw FP16 readback preserves exact comparison-reference values.+bool readReference(Graph& graph,ID3D12Resource* texture,std::vector<uint8_t>& pixels){+ if(!texture)return false;+ const auto desc=texture->GetDesc();+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT64 bytes=0;+ graph.ctx.device()->GetCopyableFootprints(&desc,0,1,0,&fp,nullptr,nullptr,&bytes);+ D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC buffer{};buffer.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;buffer.Width=bytes;+ buffer.Height=1;buffer.DepthOrArraySize=1;buffer.MipLevels=1;buffer.SampleDesc.Count=1;buffer.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ Microsoft::WRL::ComPtr<ID3D12Resource> readback;+ if(FAILED(graph.ctx.device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&buffer,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback))))return false;+ Status status;uint32_t slot;auto* list=graph.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=fp;+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);+ std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);+ if(!graph.ring.submitAndSignal(slot)||!graph.ring.waitIdle())return false;+ void* data=nullptr;D3D12_RANGE range{0,SIZE_T(bytes)};if(FAILED(readback->Map(0,&range,&data)))return false;+ pixels.resize(size_t(desc.Width)*desc.Height*8);+ for(unsigned y=0;y<desc.Height;++y)memcpy(pixels.data()+size_t(y)*desc.Width*8,static_cast<uint8_t*>(data)+fp.Offset+size_t(y)*fp.Footprint.RowPitch,size_t(desc.Width)*8);+ D3D12_RANGE empty{};readback->Unmap(0,&empty);return true;+}Pixel center(const sink::RgbaImage& image){const auto index=(std::size_t(kSize/2)*std::size_t(image.width)+std::size_t(kSize/2))*4;return {image.pixels[index],image.pixels[index+1],image.pixels[index+2]};}}int wmain(){+ for(bool rgb:{true,false}){+ Graph graph;Frame frame;+ bool ok=graph.start(true,rgb);+ if(rgb)ok=ok&&frame.make(100,120,140);+ else{+ frame.frame=av_frame_alloc();frame.frame->format=AV_PIX_FMT_NV12;frame.frame->width=frame.frame->height=kSize;+ frame.frame->color_range=AVCOL_RANGE_MPEG;frame.frame->colorspace=AVCOL_SPC_BT709;frame.frame->color_trc=AVCOL_TRC_BT709;+ ok=ok&&av_frame_get_buffer(frame.frame,32)>=0;+ if(ok){for(int y=0;y<kSize;++y)memset(frame.frame->data[0]+y*frame.frame->linesize[0],100,kSize);+ for(int y=0;y<kSize/2;++y)memset(frame.frame->data[1]+y*frame.frame->linesize[1],128,kSize);}+ }+ pipeline::EnhanceGraph::FrameOutputs out;+ std::vector<uint8_t> baseline,original,base;+ sink::RgbaImage graded,released;+ ok=ok&&graph.g.process(frame.frame,0,true,out,1)&&readReference(graph,graph.g.sourceReference(out.videoSlot),baseline);+ engine::EnhancementSettings settings;settings.color.enabled=true;settings.color.exposure=1.5f;+ ok=ok&&graph.apply(settings);+ for(uint64_t id=2;ok&&id<=5;++id){+ out={};+ ok=graph.g.process(frame.frame,double(id)*33,false,out,id)&&+ readReference(graph,graph.g.sourceReference(out.videoSlot),original)&&+ readReference(graph,graph.g.baseReference(out.videoSlot),base)&&+ sink::readRgba8(graph.ctx,graph.ring,graph.g.videoFrameResource(out.videoSlot),graded);+ ok=ok&&original==baseline&&base!=original;+ }+ out={};+ ok=ok&&graph.g.process(frame.frame,200,false,out,6,nullptr,nullptr,false)&&+ sink::readRgba8(graph.ctx,graph.ring,graph.g.videoFrameResource(out.videoSlot),released)&&released.pixels==graded.pixels;+ check(ok,rgb?"RGB original excludes grade across both slots; base and released output retain grade":"NV12 original excludes grade across both slots; base and released output retain grade");+ }// 1. Master switch off and enabled-neutral are both identity.{Graph off,on;diff --git a/tests/integration/ExperimentalBackendTests.cpp b/tests/integration/ExperimentalBackendTests.cppindex 6c327f98..dfa05f49 100644--- a/tests/integration/ExperimentalBackendTests.cpp+++ b/tests/integration/ExperimentalBackendTests.cpp@@ -4,6 +4,7 @@#include "veyra/gfx/CommandSlotRing.h"#include "veyra/sink/ImageExportSink.h"#include "veyra/RuntimePaths.h"+#include "veyra/gfx/XessPacing.h"#include <d3d12sdklayers.h>#include <wrl/client.h>#include <algorithm>@@ -11,6 +12,7 @@#include <cmath>#include <filesystem>#include <iostream>+#include <thread>#include <vector>extern "C" {#include <libavutil/frame.h>@@ -121,22 +123,75 @@ bool readCanonicalFlow(gfx::D3D12DeviceContext& ctx, gfx::CommandSlotRing& ring,return true;}+bool checkDisplayMotion(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring){+ constexpr unsigned w=640,h=360;+ auto source=pipeline::makeTexture(ctx.device(),w,h,DXGI_FORMAT_R16G16_FLOAT,true);+ auto output=pipeline::makeTexture(ctx.device(),w,h,DXGI_FORMAT_R16G16_FLOAT,true);+ pipeline::ComputePass pass;std::vector<uint8_t> cs;+ if(!source||!output||!pipeline::loadShaderBytes("PresentMotion.dxil",cs)||!pass.create(ctx.device(),cs,3,1,1,16))return false;+ const auto cpu=pass.heap->GetCPUDescriptorHandleForHeapStart();+ const auto gpu=pass.heap->GetGPUDescriptorHandleForHeapStart();+ pipeline::makeSrv(ctx.device(),source.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu);+ pipeline::makeUav(ctx.device(),output.Get(),DXGI_FORMAT_R16G16_FLOAT,{cpu.ptr+pass.increment});+ pipeline::makeUav(ctx.device(),source.Get(),DXGI_FORMAT_R16G16_FLOAT,{cpu.ptr+2*pass.increment});+ Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> clearHeap;+ D3D12_DESCRIPTOR_HEAP_DESC hd{};hd.Type=D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;hd.NumDescriptors=1;+ if(FAILED(ctx.device()->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&clearHeap))))return false;+ pipeline::makeUav(ctx.device(),source.Get(),DXGI_FORMAT_R16G16_FLOAT,clearHeap->GetCPUDescriptorHandleForHeapStart());+ for(unsigned test=0;test<4;++test){+ Status st;uint32_t slot=0;auto* list=ring.acquireNext(slot,st);if(!list)return false;+ pipeline::StateTracker states;+ states.transition(list,source.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ ID3D12DescriptorHeap* heaps[]={pass.heap.Get()};list->SetDescriptorHeaps(1,heaps);+ const float velocity[4]={-2,1,0,0};+ list->ClearUnorderedAccessViewFloat({gpu.ptr+2*pass.increment},clearHeap->GetCPUDescriptorHandleForHeapStart(),source.Get(),velocity,0,nullptr);+ states.transition(list,source.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ states.transition(list,output.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ // Identity; 2X zoom; view shifted 10% right; explicit history reset.+ const float zoom=test==1?2.0f:1.0f;+ const float map[16]={640,360,960,540,zoom,test==2?.6f:.5f,.5f,test==3?1.0f:0.0f,+ zoom,.5f,.5f,0,960,540,0,0};+ pass.bind(list,map,gpu.ptr,gpu.ptr+pass.increment);list->Dispatch(w/8,h/8,1);+ states.transition(list,source.Get(),D3D12_RESOURCE_STATE_COMMON);+ states.transition(list,output.Get(),D3D12_RESOURCE_STATE_COMMON);+ if(!ring.submitAndSignal(slot)||!ring.drainQueue())return false;+ list=ring.acquireNext(slot,st);if(!list)return false;+ pipeline::StateTracker readStates;+ readStates.transition(list,output.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ if(!ring.submitAndSignal(slot))return false;+ FlowSample sample;if(!readCanonicalFlow(ctx,ring,output.Get(),sample))return false;+ const float expectedX=test==3?0:test==2?62:-2*zoom;+ const float expectedY=test==3?0:zoom;+ const bool ok=std::abs(sample.x-expectedX)<.08f&&std::abs(sample.y-expectedY)<.08f;+ std::cout<<"DISPLAY_MOTION case="<<test<<" actual="<<sample.x<<","<<sample.y<<" expected="<<expectedX<<","<<expectedY<<" pass="<<ok<<std::endl;+ list=ring.acquireNext(slot,st);if(!list)return false;+ D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ b.Transition={output.Get(),D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,D3D12_RESOURCE_STATE_COMMON};+ list->ResourceBarrier(1,&b);+ if(!ring.submitAndSignal(slot)||!ring.drainQueue()||!ok)return false;+ }+ return true;+}+} // namespaceint wmain(int argc,wchar_t** argv){if(argc!=3)return 2;const bool dis=std::wstring(argv[1]).find(L"dis")==0;const bool pan=wcscmp(argv[1],L"xess-pan2")==0||wcscmp(argv[1],L"xess-pan4")==0;- const bool xess=pan||wcscmp(argv[1],L"xess")==0||wcscmp(argv[1],L"dis-xess")==0;+ const bool recovery=wcscmp(argv[1],L"xess-recovery2")==0||wcscmp(argv[1],L"xess-recovery3")==0||wcscmp(argv[1],L"xess-recovery4")==0||wcscmp(argv[1],L"xess-resize4")==0;+ const bool resizeRecovery=wcscmp(argv[1],L"xess-resize4")==0;+ const bool soak=wcscmp(argv[1],L"xess-soak4")==0;+ const bool xess=soak||recovery||pan||wcscmp(argv[1],L"xess")==0||wcscmp(argv[1],L"dis-xess")==0;const bool amd=wcscmp(argv[1],L"amd")==0;const bool sr=std::wstring(argv[1]).find(L"sr")==0;if(!xess&&!amd&&!sr&&!dis&&wcscmp(argv[1],L"nvof1080")!=0)return 2;const bool full=std::wstring(argv[1]).find(L"1080")!=std::wstring::npos;- const unsigned width=(sr||full)?1920:640,height=(sr||full)?1080:360,frames=sr?3:48;+ const unsigned width=(sr||full)?1920:640,height=(sr||full)?1080:360,frames=soak?3600:sr?3:48;CoInitializeEx(nullptr,COINIT_MULTITHREADED);std::filesystem::create_directories(argv[2]);Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());- SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");+ SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",soak?nullptr:L"1");HWND window=CreateWindowExW(0,L"STATIC",L"Veyra experimental backend test",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);if(!window)return 1;ShowWindow(window,SW_SHOWNOACTIVATE);@@ -150,7 +205,8 @@ int wmain(int argc,wchar_t** argv){desc.rgbInput=true;desc.enableNr=false;desc.enableFg=xess;desc.noNgx=true;desc.enableNvofStandalone=true;desc.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;- if(wcscmp(argv[1],L"xess-pan4")==0)desc.fgMultiplier=4;+ if(soak||wcscmp(argv[1],L"xess-pan4")==0)desc.fgMultiplier=4;+ if(recovery)desc.fgMultiplier=(resizeRecovery||wcscmp(argv[1],L"xess-recovery4")==0)?4:wcscmp(argv[1],L"xess-recovery3")==0?3:2;desc.opticalFlowBackend=dis?engine::OpticalFlowBackend::GpuDis:amd?engine::OpticalFlowBackend::AmdFidelityFx:engine::OpticalFlowBackend::Nvidia;if(sr){desc.sourceWidth=width;desc.sourceHeight=height;@@ -163,14 +219,24 @@ int wmain(int argc,wchar_t** argv){}bool ok=graph.initialize(desc)&&presenter.open(ctx,window,graph)&&graph.createViews();if(xess)ok=ok&&presenter.xessActive();+ if(xess)ok=ok&&checkDisplayMotion(ctx,ring);+ if(xess&&desc.fgMultiplier>2&&ok){+ const auto again=gfx::XessPacing::install(GetModuleHandleW(L"libxess_fg.dll"),desc.fgMultiplier-1);+ ok=again.installed;+ }AVFrame* frame=av_frame_alloc();frame->format=AV_PIX_FMT_RGBA;frame->width=int(width);frame->height=int(height);frame->color_trc=AVCOL_TRC_IEC61966_2_1;ok=ok&&av_frame_get_buffer(frame,32)>=0;pipeline::EnhanceGraph::FrameOutputs out;FlowSample rightward{}, leftward{};engine::PreviewView view;uint64_t panGenerated=0;+ unsigned recovered=0;+ UINT64 previousMessages=0;if(pan)view.zoom=1.5f;+ const auto cadenceStart=std::chrono::steady_clock::now();for(unsigned i=0;ok&&i<frames;++i){+ if(soak)std::this_thread::sleep_until(cadenceStart+std::chrono::microseconds(uint64_t(i)*1000000/30));+ ok=presenter.beginSourceInput()&&ok;MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}const int phase = i < 24 ? int(i) : int(i - 24);const int velocity = i < 24 ? 2 : -2;@@ -182,24 +248,45 @@ int wmain(int argc,wchar_t** argv){hash^=hash>>16;hash*=0x7FEB352Du;hash^=hash>>15;hash*=0x846CA68Bu;hash^=hash>>16;p[0]=uint8_t(hash);p[1]=uint8_t(hash>>8);p[2]=uint8_t(hash>>16);p[3]=255;}- out={};ok=graph.process(frame,i*1000.0/30,i==0||i==24,out,i+1);+ const bool forcedReset=i==0||i==24||(recovery&&(i==8||i==32||i==40));+ out={};ok=ok&&presenter.beginSourceProcessing()&&graph.process(frame,i*1000.0/30,forcedReset,out,i+1);+ if(ok)presenter.sourceProcessed(out.batch.identity);+ if(ok&&recovery&&i==18){+ // Repaint an older identity while the next source is prepared.+ // It must not consume that source's identity or add generated frames.+ const auto before=presenter.xessGeneratedCount();+ auto older=out.batch.identity;--older.sourceFrameId;+ ok=presenter.present(ctx,ring,graph,out.videoSlot,false,false,0,false,.5f,older,view);+ ok=ok&&presenter.xessGeneratedCount()==before;+ }const bool moving=pan&&i>=4&&i<44;if(moving)view.pan(i<24?3.0f:-3.0f,1.0f,960,540,float(width),float(height));const auto beforePresent=presenter.xessGeneratedCount();if(ok)ok=presenter.present(ctx,ring,graph,out.videoSlot,false,false,0,false,.5f,out.batch.identity,view);if(moving)panGenerated+=presenter.xessGeneratedCount()-beforePresent;+ if(recovery&&(i==9||i==33||i==41)){+ const auto delta=presenter.xessGeneratedCount()-beforePresent;+ std::cout<<"RECOVERY frame="<<i<<" generated="<<delta<<" expected="<<desc.fgMultiplier-1<<std::endl;+ ok=ok&&delta==desc.fgMultiplier-1;+ if(delta==desc.fgMultiplier-1)++recovered;+ }if(ok&&i==16){const auto before=presenter.xessGeneratedCount();ok=presenter.present(ctx,ring,graph,out.videoSlot,false,false,0,false,.5f,out.batch.identity,view);if(xess)ok=ok&&presenter.xessGeneratedCount()==before;}- if(i==24)SetWindowPos(window,nullptr,0,0,800,600,SWP_NOACTIVATE|SWP_NOZORDER);+ if(i==24&&(!recovery||resizeRecovery))SetWindowPos(window,nullptr,0,0,800,600,SWP_NOACTIVATE|SWP_NOZORDER);if((amd||dis)&&(i==23||i==47)){ok=ring.drainQueue()&&ok;FlowSample& sample=i==23?rightward:leftward;ok=ok&&readCanonicalFlow(ctx,ring,graph.flowResource(),sample);}- Sleep(34);+ if(!soak)Sleep(34);+ if(recovery&&info){+ const auto messages=info->GetNumStoredMessagesAllowedByRetrievalFilter();+ if(messages!=previousMessages)std::cout<<"DEBUG frame="<<i<<" messages="<<messages<<std::endl;+ previousMessages=messages;+ }}ok=ring.drainQueue()&&ok;const auto generated=presenter.xessGeneratedCount();@@ -212,6 +299,7 @@ int wmain(int argc,wchar_t** argv){std::cout<<"SR extent="<<image.width<<"x"<<image.height<<" evaluate="<<graph.metrics().srEvaluateCount<<" nonblack="<<nonblack<<" pass="<<ok<<std::endl;}if(xess)ok=ok&&generated>10;+ if(recovery)ok=ok&&recovered==3;if(pan){ok=ok&&panGenerated>10;std::cout<<"PAN multiplier="<<desc.fgMultiplier<<" generatedWhileMoving="<<panGenerated<<" pass="<<ok<<std::endl;