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++
Query refresh/VRR on events only and add 重新检测 beside 可变刷新
Veyra Goal Agent5a809487b30e
diff --git a/AGENTS.md b/AGENTS.mdindex 9aa3ecc9..6000383b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-25 VRR事件触发查询(Claude)**:用户要求可变刷新/刷新率不再定时查询,改为事件触发并在“可变刷新”旁加“重新检测”按钮,引擎和界面都去掉2秒轮询。从main 68def10在claude/vrr-event-query-20261025按docs/VRR_EVENT_QUERY_PLAN_2026-10-25.md施工,起点标签checkpoint/pre-vrr-event-query-20261025;允许必要的呈现器/引擎/桥接/QML/翻译/CMake/定向测试接点,覆盖这些范围旧冻结。补帧调度、显示同步策略、33ms/250ms刷新不变,不加定时器。单Agent、全E盘、复用build/claude-screen-recording-20261022构建-j2<=900秒/单测<=300秒;不改运行库/模型/驱动/真实配置,无merge/push/Release,Lecram暂停。本机屏幕不支持VRR,真实VRR生效须用户设备验证。+> **2026-10-25 采集内置音频修复与整合授权**:用户明确要求修复 CV710 开监听卡画面,并把近期全部修复/功能合入本地 main。从207555b在codex/capture-audio-main-20261025按docs/CAPTURE_AUDIO_MAIN_PLAN_2026-10-25.md施工;包含 #67/全屏退出与当前录制/AMD SR关/旋转/NR比例/FG异步查询/NR导出,覆盖这些接点旧冻结及无main合并限制。先存档原main与101工作树/原全屏脏文件,不覆盖其它工作树。保持单Agent、全E盘、-j2构建<=900秒/单测试<=300秒、真实配置/运行库/模型/驱动不变。CV710现场修复必须原卡复测,不拿本机卡或夹具替代;无push/Release/代发/关机授权,Lecram暂停。> **2026-10-25 社区NR导出尺寸补丁接入(用户授权)**:从038beac在codex/export-nr-scale-20261025按docs/EXPORT_NR_SCALE_PLAN_2026-10-25.md接入固定档与百分比的视频导出NR尺寸,允许必要export policy/图描述/执行计划/导出日志/QML四语/定向测试接点,覆盖这些范围旧UI冻结及此前“导出保持Native”限制。输出尺寸不变、图片完整处理、AMD预算、非法值校验及既有NR手动编码保留。不改补帧调度/运行库/模型/驱动/真实配置;单Agent、全E盘、复用构建-j2<=900秒/单测<=300秒,无merge/push/Release,Lecram暂停。diff --git a/CMakeLists.txt b/CMakeLists.txtindex 376cb149..ce237133 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1379,7 +1379,7 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_link_libraries(veyra_repair_fg_tests PRIVATE veyra_pipeline veyra_sinks veyra_nvof)# Headless quality-core runner (Playbook R3.3): the phase5 gate's quality- add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineWatchdog.cpp src/engine/PreviewGpuSession.cpp src/engine/EngineControllerImage.cpp src/engine/PosterFrame.cpp src/engine/EffectChain.cpp src/engine/PresetLibrary.cpp src/ui/PlayerUiFacade.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportStreams.cpp src/engine/ExportQueue.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp src/engine/FgCompatibilityProbe.cpp src/engine/LiveRecorder.cpp)+ add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineWatchdog.cpp src/engine/PreviewGpuSession.cpp src/engine/EngineControllerImage.cpp src/engine/PosterFrame.cpp src/engine/EffectChain.cpp src/engine/PresetLibrary.cpp src/ui/PlayerUiFacade.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/DisplayStateService.cpp src/engine/VideoExportJob.cpp src/engine/ExportStreams.cpp src/engine/ExportQueue.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp src/engine/FgCompatibilityProbe.cpp src/engine/LiveRecorder.cpp)target_sources(veyra_pipeline PRIVATE src/guidance/AmdOpticalFlow.cppsrc/guidance/GpuDisOpticalFlow.cpp third_party/gpu-dis/src/gpu/native_strict_dis_provider.cpp)target_include_directories(veyra_pipeline PRIVATE third_party/gpu-dis/src/gpu)diff --git a/docs/VRR_EVENT_QUERY_PLAN_2026-10-25.md b/docs/VRR_EVENT_QUERY_PLAN_2026-10-25.mdnew file mode 100644index 00000000..222901be--- /dev/null+++ b/docs/VRR_EVENT_QUERY_PLAN_2026-10-25.md@@ -0,0 +1,30 @@+# 2026-10-25 可变刷新/刷新率改为事件触发查询(Claude)++用户审查补帧链路后决定:VRR 状态不再定时查询,改为事件触发,并在“可变刷新”旁加“重新检测”按钮;引擎和界面都去掉 2 秒轮询。从 main 68def10 开 `claude/vrr-event-query-20261025`,起点标签 `checkpoint/pre-vrr-event-query-20261025`,开工状态 `archives/claude-vrr-event-query-20261025/start.json`。单 Agent、全 E 盘、复用 `build/claude-screen-recording-20261022`(-j2、≤900 秒)、单测试 ≤300 秒;不改运行库/模型/驱动/真实配置,不 merge/push/Release,Lecram 暂停。++## 现状++- 2.0.8–2.1.0:播放线程每 2 秒同步调用 NVAPI 查 VRR(本机 10.5–22 ms),与 VRR 开关无关。038beac 已改到后台执行,但仍每 2 秒查一次。+- 界面不播放时,`QmlPlayerBridge::updateRunStatus()` 每 2 秒在界面线程同步调用 `gfx::queryVrr`。+- 每次新建呈现器或处理图重建都把 VRR/刷新率清零:先按“未知”配置一次,结果回来后再重配一次。++## 方案++1. 新增进程内共享的 `engine::DisplayStateService`(由 `EngineController` 持有,呈现器和界面共用):按显示器缓存刷新率与 VRR 状态;后台一次只跑一个查询,其余排队;读取从不等待,只有开播首次配置可等待 ≤100 ms。不加任何定时器。+2. 查询时机:+ - 软件启动后界面第一次刷新状态(空闲,主窗口所在屏)。+ - 新建呈现链(开播):先用该屏缓存立即配置,同时后台核对一次;没有缓存时等 ≤100 ms。处理图重建(沿用同一交换链)保留当前状态,不查询。+ - 窗口换到另一块屏:用该屏缓存,没有才查。+ - 显示配置变化(`WM_DISPLAYCHANGE`:分辨率、刷新率、HDR、插拔屏幕)、打开“可变刷新”开关、点“重新检测”:全部状态作废,正在用的屏各查一次。+ - 可变刷新呈现已开启但驱动尚未确认生效:开启后、或画面尺寸变化(进出全屏)停止 3 秒后补查一次,只为把状态更新为“生效中”。+ - 查询失败(NVAPI 返回错误、查询期间窗口换屏):2 秒后最多自动重试 2 次,之后等下一次事件或按钮。+3. 界面:去掉空闲时的 2 秒同步查询,改读共享缓存。“可变刷新”旁加图标按钮(刷新图标,提示“重新检测”,检测中转圈),专业页“显示”与节点页输出框各一处。开关仍在屏幕不支持时变灰,按钮始终可用;手动重新检测完成后弹出结果提示。+4. 日志:每次实际查询记一行原因(ui、session-start、monitor-change、display-change、manual、vrr-confirm、retry)和耗时,不再每 2 秒一行。++## 验证++- CPU 单测(`veyra_async_display_query_tests`):缓存命中不查询、作废后每屏只查一次、同屏在途不重复、排队、失败限次重试、有界等待、换屏不套用旧屏状态。+- 构建 `veyra_qml_ui` 与相关测试目标;运行异步查询、实时预览、UI 合同、Repair 合同、翻译测试,以及 `scripts/i18n/extract.py --check`。+- 私有配置实际运行(确认没有其他 Veyra 进程):播放本地视频 ≥30 秒,日志里的查询次数不随时间增长;点“重新检测”、切换开关各只查一次。本机屏幕驱动报告不支持 VRR,真实 VRR 是否生效仍需用户在支持 VRR 的设备上验证。++产物:`E:/项目/Veyra/{tests,logs,tmp,reports,archives}/claude-vrr-event-query-20261025`;构建复用 `build/claude-screen-recording-20261022`。diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex e1f552a1..1a4c120e 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -7680,6 +7680,13 @@"en": "Keyboard and mouse released (click the picture to capture again)","ja": "キーボードとマウスを解放しました(映像をクリックすると再度キャプチャー)"},+ {+ "zh": "已重新检测:%1",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "已重新偵測:%1",+ "en": "Checked again: %1",+ "ja": "再検出しました:%1"+ },{"zh": "已锁定全屏 · Ctrl+L 解锁,Esc 退出全屏","src": "qml/Main.qml",@@ -16970,6 +16977,20 @@"en": "Continue from the last position when the same file is reopened","ja": "同じファイルを開き直すと前回の位置から再開"},+ {+ "zh": "重新检测",+ "src": "qml/NodePage.qml",+ "zh-TW": "重新偵測",+ "en": "Check again",+ "ja": "再検出"+ },+ {+ "zh": "重新检测没有完成,请稍后再试",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "重新偵測未完成,請稍後再試",+ "en": "The check did not finish. Please try again shortly.",+ "ja": "再検出が完了しませんでした。しばらくしてから再試行してください。"+ },{"zh": "重置本页","src": "qml/ProPage.qml",diff --git a/include/veyra/engine/DisplayStateService.h b/include/veyra/engine/DisplayStateService.hnew file mode 100644index 00000000..ae403398--- /dev/null+++ b/include/veyra/engine/DisplayStateService.h@@ -0,0 +1,80 @@+#pragma once+#include "veyra/gfx/NvidiaVrr.h"+#include <windows.h>+#include <chrono>+#include <cstdint>+#include <functional>+#include <future>+#include <map>+#include <mutex>+#include <optional>+#include <vector>++namespace veyra::engine {+// Refresh rate and NVIDIA variable-refresh state of one monitor.+struct DisplayState {+ HMONITOR monitor=nullptr;+ double refreshHz=0;+ gfx::VrrState vrr{};+ uint64_t generation=0; // display generation the query ran in+ uint64_t serial=0; // stored-result counter (all monitors): a holder applies each state once+ double refreshMs=0,vrrMs=0; // driver call wall time on the worker thread+};+// Display states shared by the presenter and the UI (2026-10-25,+// docs/VRR_EVENT_QUERY_PLAN_2026-10-25.md). Nothing re-reads them on a timer:+// holders may call request() every frame or tick, and a query only runs when+// the monitor has no state of the current display generation. invalidate() (a+// display change, the 可变刷新 switch turned on, 重新检测) makes every state+// stale; force is for the session-start check and the VRR confirmation. One+// query runs at a time on a worker thread and the others wait in a queue.+// Reading never waits, except wait(), which only a new presentation chain uses.+// A failed query (an NVAPI error, the window closed or moved meanwhile, an+// exception) is retried at most twice per generation, retryDelay apart.+class DisplayStateService {+public:+ using Clock=std::chrono::steady_clock;+ using Query=std::function<DisplayState(HWND,HMONITOR)>;+ using MonitorOf=std::function<HMONITOR(HWND)>;+ // QueryDisplayConfig refresh + NVAPI VRR of the window's monitor.+ DisplayStateService();+ // Tests: fake query, monitor lookup and retry delay.+ DisplayStateService(Query,MonitorOf,std::chrono::milliseconds retryDelay=std::chrono::seconds(2));+ // Waits for a running query: one driver call, never a queue.+ ~DisplayStateService();+ DisplayStateService(const DisplayStateService&)=delete;+ DisplayStateService& operator=(const DisplayStateService&)=delete;+ uint64_t invalidate(const char* reason);+ uint64_t generation()const;+ // Never waits. True when a query for the window's monitor was started or+ // queued by this call.+ bool request(HWND window,const char* reason,bool force=false);+ // Publishes a finished query and returns the monitor's newest state, current+ // or stale (generation below generation()); none before its first answer.+ std::optional<DisplayState> state(HMONITOR monitor);+ // Waits up to `limit` until the monitor has a state of the current+ // generation, while a query for it runs or waits. New presentation chains only.+ std::optional<DisplayState> wait(HMONITOR monitor,std::chrono::milliseconds limit);+ // A query runs or waits (after publishing a finished one).+ bool busy();+ HMONITOR monitorOf(HWND window)const{return monitorOf_(window);}+ // The real query: values only, never presenter or swap-chain resources. A+ // window that closed or moved to another monitor meanwhile yields monitor=nullptr.+ static DisplayState queryDisplayState(HWND window,HMONITOR monitor);+private:+ struct Job {HWND window=nullptr;HMONITOR monitor=nullptr;uint64_t generation=0;const char* reason="";bool force=false;};+ struct Entry {std::optional<DisplayState> state;uint64_t failedGeneration=0;unsigned failures=0;Clock::time_point retryAt{};};+ bool currentLocked(const Entry&,Clock::time_point now)const;+ void startLocked(Job);+ void collectLocked();+ void failedLocked(Entry&,const Job&,const std::string& why);+ Query query_;+ MonitorOf monitorOf_;+ std::chrono::milliseconds retryDelay_;+ mutable std::mutex mutex_;+ std::map<HMONITOR,Entry> entries_;+ std::vector<Job> queue_;+ std::optional<Job> running_;+ std::shared_future<DisplayState> result_;+ uint64_t generation_=1,serial_=0;+};+}diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 152277ad..fdee0ee3 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -27,6 +27,7 @@#include "veyra/sink/VideoEncoder.h"#include "veyra/engine/ExportOptions.h"#include "veyra/engine/LiveRecorder.h"+#include "veyra/engine/DisplayStateService.h"namespace veyra::source { struct RemotePlayConnectDesc; class RemotePlaySessionSource; struct MoonlightConnectDesc; class MoonlightSessionSource; struct XboxConnectDesc; class XboxSessionSource; }namespace veyra::remoteplay { struct ControllerState;struct ControllerFeedback; }namespace veyra::sink { struct RgbaImage; }@@ -257,6 +258,9 @@ public:bool requestRecording(const RecordingSettings& options,std::wstring& error);void stopRecording();RecordingStatus recordingSnapshot()const;+ // Refresh/VRR state of monitors, shared by every session's presenter and+ // the UI; queried in the background on events only. Any thread.+ DisplayStateService& displayStates(){return displayStates_;}private:void run(HWND,std::wstring,PlayerOptions,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest={},std::shared_ptr<source::MoonlightConnectDesc> moonlightRequest={},std::shared_ptr<source::XboxConnectDesc> xboxRequest={});void runLargeImage(HWND,const sink::RgbaImage&,PlayerOptions,gfx::D3D12DeviceContext&,gfx::CommandSlotRing&);@@ -292,6 +296,8 @@ private:// Live recorder: every session's presenter records into it; it owns its// encoder and writer threads. Created before the engine thread starts.std::unique_ptr<LiveRecorder> recorder_=std::make_unique<LiveRecorder>();+ // Declared before worker_: it outlives the engine thread's presenters.+ DisplayStateService displayStates_;std::thread worker_;std::unique_ptr<PreviewGpuSession> prewarmed_; // engine dispatcher onlystd::atomic<bool> prewarmEnabled_{false}; // off until the saved preference enables it (default off since 2026-10-05)diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 71357d5c..8971c9f6 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -10,7 +10,7 @@#include "veyra/gfx/NvidiaVrr.h"#include "veyra/engine/PresentationSettings.h"#include "veyra/engine/PresentCapture.h"-#include "veyra/engine/AsyncDisplayQuery.h"+#include "veyra/engine/DisplayStateService.h"#include <chrono>#include <array>#include <optional>@@ -22,6 +22,8 @@ class VideoPresenter {public:// Live recording hook; the object must outlive every present() call.void setCapture(PresentCapture* capture){capture_=capture;}+ // Shared refresh/VRR states (the engine's); must outlive the presenter.+ void setDisplayStates(DisplayStateService* states){displayStates_=states;}~VideoPresenter(){close();}// mediaClockPaced: the owner already waits on a media clock before each// source (file playback). Retained for diagnostics; XeLL low latency must@@ -75,13 +77,13 @@ public:// per-frame history reset, never a per-frame toggle.void setXessGenerationSuppressed(bool v){xessGenerationSuppressed_=v;}bool xessGenerationSuppressed() const {return xessGenerationSuppressed_;}- // Monitor refresh for the live output budget. The swap chain samples it- // only at creation; the window may move to another monitor or the mode- // may change, so it is re-read on a monitor change and every 2 s.- // This accessor only polls a bounded asynchronous query; it never waits- // on QueryDisplayConfig or NVIDIA's monitor/VRR driver calls.+ // Monitor refresh for the live output budget and 跟随显示器, from the shared+ // DisplayStateService. It is read again only on events: a new presentation+ // chain, the window moving to another monitor, a display change or+ // 重新检测, and one VRR confirmation (vrrConfirmAt_); never on a timer.+ // This accessor never waits on QueryDisplayConfig or NVIDIA's driver calls.double displayRefreshHz();- // Variable refresh state of that monitor (NVIDIA only), re-read with it.+ // Variable refresh state of that monitor (NVIDIA only), read with it.gfx::VrrState displayVrr()const{return vrr_;}// The 可变刷新 rule: the switch is on, Automatic is selected and VRR is// possible on the monitor, so Automatic presents like explicit Vsync.@@ -173,9 +175,13 @@ private:bool xessFailed_=false;bool xessGenerationSuppressed_=false;HMONITOR refreshMonitor_=nullptr;double refreshHz_=0;gfx::VrrState vrr_{};bool refreshQueried_=false,vrrSync_=false;- struct DisplayQueryResult {HMONITOR monitor=nullptr;double hz=0;gfx::VrrState vrr;double refreshMs=0,vrrMs=0;};- AsyncDisplayQuery<DisplayQueryResult> displayQuery_;- std::chrono::steady_clock::time_point refreshQuery_{};+ DisplayStateService* displayStates_=nullptr;+ uint64_t displayStateSerial_=0,displayGeneration_=0;+ // VRR presentation may start or stop after it is requested or when the+ // window enters/leaves fullscreen: one forced query 3 s after that settles.+ std::optional<std::chrono::steady_clock::time_point> vrrConfirmAt_;+ void startDisplayState();+ void applyDisplayState(const DisplayState&);uint32_t xessInputId_=0;struct XessWork {pipeline::FrameIdentity identity{};uint32_t id=0;};std::array<XessWork,4> xessWork_{};diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex d8d54c0e..67552863 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -436,6 +436,10 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(bool variableRefresh READ variableRefresh WRITE setVariableRefresh NOTIFY presentationChanged)Q_PROPERTY(int vrrState READ vrrState NOTIFY perfChanged)Q_PROPERTY(QString vrrHint READ vrrHint NOTIFY perfChanged)+ // The level is read on events only (startup, another monitor, a display+ // change, the switch turned on); 重新检测 (recheckDisplay) asks the driver+ // again, and vrrChecking is true until that answer arrives.+ Q_PROPERTY(bool vrrChecking READ vrrChecking NOTIFY perfChanged)Q_PROPERTY(int outputRateMode READ outputRateMode WRITE setOutputRateMode NOTIFY presentationChanged)Q_PROPERTY(double outputCustomFps READ outputCustomFps WRITE setOutputCustomFps NOTIFY presentationChanged)Q_PROPERTY(bool presentationOwned READ presentationOwned NOTIFY snapshotChanged)@@ -1063,6 +1067,8 @@ public:void setVariableRefresh(bool value);int vrrState() const;QString vrrHint() const;+ bool vrrChecking() const;+ Q_INVOKABLE void recheckDisplay();QString fgDisplayHint() const;Q_INVOKABLE void setPresentationFullscreen(bool value);bool fullscreenMemorySafe() const;@@ -1416,6 +1422,8 @@ private:void startGpuSampler();void requestApplicationRestart(bool overlayCompatibility);void updateRunStatus();+ // vrrHint's text for a VRR level (the 重新检测 result notice uses it too).+ QString vrrHintText(int level) const;void applyPresentation();void applyAspect(bool force);// Live sources started from the start page: switch to 极简 first, show thediff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qmlindex dbd78d55..685b042e 100644--- a/qml/Veyra/NodePage.qml+++ b/qml/Veyra/NodePage.qml@@ -831,19 +831,31 @@ VPage {current: String(veyra.displaySync)onPicked: id => veyra.displaySync = Number(id)}- // 可变刷新 (G-SYNC / FreeSync): greyed when the monitor cannot do it.+ // 可变刷新 (G-SYNC / FreeSync): the switch greys when the monitor+ // cannot do it; 重新检测 stays available (read on events only).RowLayout {Layout.fillWidth: true- enabled: veyra.vrrState >= 2- opacity: enabled ? 1 : 0.5NodeLabel { Layout.fillWidth: true; text: qsTr("可变刷新"); wrapMode: Text.WordWrap }+ Item {+ implicitWidth: Theme.ctlHeight; implicitHeight: Theme.ctlHeight+ VButton {+ objectName: "node-vrr-recheck"+ anchors.fill: parent+ visible: !veyra.vrrChecking+ icon: true; ghost: true; iconName: "refresh"; tip: qsTr("重新检测")+ onClicked: veyra.recheckDisplay()+ }+ VSpinner { anchors.centerIn: parent; visible: veyra.vrrChecking }+ }VSwitch {objectName: "node-vrr"+ enabled: veyra.vrrState >= 2+ opacity: enabled ? 1 : 0.5checked: veyra.variableRefreshonToggled: checked => veyra.variableRefresh = checked}}- NodeLabel { Layout.fillWidth: true; text: veyra.vrrHint; wrapMode: Text.WordWrap; opacity: veyra.vrrState >= 2 ? 1 : 0.5 }+ NodeLabel { Layout.fillWidth: true; text: veyra.vrrHint; wrapMode: Text.WordWrap }NodeLabel { text: qsTr("输出上限") }VSeg {objectName: "node-output-rate"diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex 81707a06..91ab7058 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -142,16 +142,32 @@ VPage {onPicked: id => veyra.displaySync = Number(id)}}- // 可变刷新 (G-SYNC / FreeSync): greyed when the monitor cannot do it.+ // 可变刷新 (G-SYNC / FreeSync): the switch greys when the monitor cannot+ // do it. The state is read on events only; 重新检测 stays available and+ // asks the driver again (its icon becomes a spinner meanwhile).VRow {label: qsTr("可变刷新")- enabled: veyra.vrrState >= 2- opacity: enabled ? 1 : 0.5hint: veyra.vrrHint- VSwitch {- objectName: "presentation-vrr"- checked: veyra.variableRefresh- onToggled: checked => veyra.variableRefresh = checked+ RowLayout {+ spacing: 6+ Item {+ implicitWidth: Theme.ctlHeight; implicitHeight: Theme.ctlHeight+ VButton {+ objectName: "presentation-vrr-recheck"+ anchors.fill: parent+ visible: !veyra.vrrChecking+ icon: true; ghost: true; iconName: "refresh"; tip: qsTr("重新检测")+ onClicked: veyra.recheckDisplay()+ }+ VSpinner { anchors.centerIn: parent; visible: veyra.vrrChecking }+ }+ VSwitch {+ objectName: "presentation-vrr"+ enabled: veyra.vrrState >= 2+ opacity: enabled ? 1 : 0.5+ checked: veyra.variableRefresh+ onToggled: checked => veyra.variableRefresh = checked+ }}}VRow {diff --git a/scripts/acceptance/vrr-event-query.py b/scripts/acceptance/vrr-event-query.pynew file mode 100644index 00000000..463c2bac--- /dev/null+++ b/scripts/acceptance/vrr-event-query.py@@ -0,0 +1,107 @@+"""Private refresh/VRR event-query check (claude-vrr-event-query-20261025).++Real 1080p30 file with VFG 2X in a hard-linked copy of the 2.1.0 NVIDIA runtime+base, the task build's EXE and this tree's QML/i18n, a private profile and log.+No capture device, never the user's package or profile. vrr-event-query.qml marks+each step in the engine log; this script counts DisplayStateService queries between+the marks. --case native uses the real NVAPI answer; --case novrr sets+VEYRA_TEST_VRR_LEVEL=1 (a monitor without VRR: no VRR presentation, no confirmation).++usage: py -3.11 -X utf8 -B -I scripts/acceptance/vrr-event-query.py --case native|novrr+"""+from pathlib import Path+import argparse, hashlib, json, os, re, shutil, subprocess++B = Path('E:/项目/Veyra'); T = 'claude-vrr-event-query-20261025'; R = Path(__file__).resolve().parents[2]+parser = argparse.ArgumentParser(); parser.add_argument('--case', choices=['native', 'novrr'], required=True)+args = parser.parse_args()+D = B/'build/claude-screen-recording-20261022'; A = B/'tests'/T/'app'; P = B/'tests'/T/('profile-'+args.case)+L = B/'logs'/T/('native-'+args.case); TMP = B/'tmp'/T/('native-'+args.case); OUT = B/'reports'/T+for p in [L, TMP, OUT]: p.mkdir(parents=True, exist_ok=True)+if P.exists(): shutil.rmtree(P) # fresh private profile per run+P.mkdir(parents=True)+for old in ['engine.log', 'console.log']:+ if (L/old).exists(): (L/old).unlink()+++def sha(p):+ with p.open('rb') as f: return hashlib.file_digest(f, 'sha256').hexdigest()+++def replace(p, data):+ # Unlink first: a hard link to the donor is never written through.+ p.parent.mkdir(parents=True, exist_ok=True)+ if p.exists(): p.unlink()+ p.write_bytes(data)+++donor = B/'releases/release-2.1.0-20261019/runtime-base/NVIDIA'+manifest = json.loads((donor/'package-manifest.json').read_text('utf8'))+if not A.exists():+ for e in manifest['files']:+ rel = e['path']+ if rel.startswith('logs/') or any(x.startswith('user-data-') for x in Path(rel).parts): continue+ p = A/rel; p.parent.mkdir(parents=True, exist_ok=True); os.link(donor/rel, p)+ shutil.copyfile(donor/'package-manifest.json', A/'package-manifest.json')+replace(A/'veyra_qml_ui.exe', (D/'veyra_qml_ui.exe').read_bytes())+for folder in ['qml', 'i18n']:+ for p in (R/folder).rglob('*'):+ if p.is_file(): replace(A/folder/p.relative_to(R/folder), p.read_bytes())+for e in manifest['files']:+ if Path(e['path']).suffix.lower() in ['.dll', '.onnx', '.tflite', '.hsaco', '.dxil']: assert sha(A/e['path']) == e['sha256'], e['path']+media = B/'tests/nr-manual-scale-20261024/media/nr-1080p30.mp4'; assert media.is_file()+(P/'qml-preferences.v1.json').write_text(json.dumps(dict(language='zh-CN', autoResume=False, prewarmEnhancement=False)), 'utf8')+env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_', 'QML_'))}+env.update(TEMP=str(TMP), TMP=str(TMP), APPDATA=str(P/'AppData'), LOCALAPPDATA=str(P/'LocalAppData'), CUDA_CACHE_PATH=str(TMP/'cuda'),+ VEYRA_LOG_FILE=str(L/'engine.log'), QML_DISABLE_DISK_CACHE='1', QT_FORCE_STDERR_LOGGING='1')+if args.case == 'novrr': env['VEYRA_TEST_VRR_LEVEL'] = '1'+main = (R/'qml/Veyra/Main.qml').read_text('utf8'); pos = main.rfind('}')+shot = B/'tests'/T/'shots'/f'display-tab-{args.case}.png'; shot.parent.mkdir(parents=True, exist_ok=True)+if shot.exists(): shot.unlink()+loader = ('\nLoader { source: ' + json.dumps(Path(__file__).with_suffix('.qml').as_uri()) ++ '; onLoaded: { item.mode=' + json.dumps(args.case) + '; item.shot=' + json.dumps(shot.as_posix()) ++ '; item.media=' + json.dumps(media.as_posix()) + ' } }\n')+replace(A/'qml/Veyra/Main.qml', (main[:pos] + loader + main[pos:]).encode('utf8'))+running = subprocess.check_output(['tasklist', '/fo', 'csv', '/nh'], text=True, errors='replace')+assert not any(l.lower().startswith('"veyra') for l in running.splitlines()), 'another player is running; do not compete'+try:+ with (L/'console.log').open('wb') as f:+ p = subprocess.run([str(A/'veyra_qml_ui.exe'), '--page', 'pro', '--size', '1280x800', '--data-dir', str(P), '--exit-after', '110000'],+ cwd=A, env=env, stdout=f, stderr=subprocess.STDOUT, timeout=140)+finally:+ replace(A/'qml/Veyra/Main.qml', (R/'qml/Veyra/Main.qml').read_bytes())++text = (L/'console.log').read_text('utf8', errors='replace'); log = (L/'engine.log').read_text('utf8', errors='replace')+errors = [x for x in text.splitlines() if any(s in x for s in ['VRR_FAIL', '[ERROR]', 'ReferenceError:', 'TypeError:', 'Binding loop detected'])]+# The step marks and the queries DisplayStateService actually started, in log order.+events = []+for line in log.splitlines():+ if (m := re.search(r'\[vrr-test\] mark (\S+)', line)): events.append(('mark', m.group(1), line[:24]))+ elif (m := re.search(r'\[display-query\] query reason=(\S+)', line)): events.append(('query', m.group(1), line[:24]))+failures = [x for x in log.splitlines() if '[display-query]' in x and 'query failed' in x]+between, current = {}, 'before-idle-start'+for kind, name, stamp in events:+ if kind == 'mark': current = name; between.setdefault(current, [])+ else: between.setdefault(current, []).append(name)+# VRR presentation (vrrSync) after the switch decides whether confirmations follow.+vrr_sync = bool(re.search(r'\[pacing\] revision=\d+ .*variableRefresh=true .*vrrSync=true', log))+expected = {'before-idle-start': ['ui'], 'idle-start': [], 'open': ['session-start'], 'play-quiet': [], 'recheck': 1,+ 'vrr-on': 2 if vrr_sync else 1, 'resize': ['vrr-confirm'] if vrr_sync else [], 'stopped': [], 'node-page': [], 'end': []}+problems = []+for step, want in expected.items():+ got = between.get(step)+ if got is None: problems.append(f'missing mark {step}'); continue+ if isinstance(want, int):+ if len(got) != want: problems.append(f'{step}: {len(got)} queries {got}, expected {want}')+ elif got != want: problems.append(f'{step}: queries {got}, expected {want}')+if vrr_sync and between.get('vrr-on', [])[-1:] != ['vrr-confirm']: problems.append('vrr-on: no VRR confirmation after the switch')+if args.case == 'novrr' and vrr_sync: problems.append('novrr: VRR presentation must not start')+passed = p.returncode == 0 and 'VRR_PASS' in text and not errors and not problems and not failures+result = dict(case=args.case, vrrPresentation=vrr_sync, exit=p.returncode, passed=passed, log=str(L), exeSha256=sha(A/'veyra_qml_ui.exe'), screenshot=str(shot) if shot.exists() else None,+ queriesBetweenMarks=between, problems=problems, queryFailures=failures, errors=errors,+ events=[list(e) for e in events],+ scope='real 1080p30 file, VFG 2X, private profile; counts background display queries per step; '+ 'native = real NVAPI answer of this monitor, novrr = simulated level 1; no capture device, no optical VRR measurement')+(OUT/f'native-{args.case}.json').write_text(json.dumps(result, ensure_ascii=False, indent=1), 'utf8')+print(json.dumps(dict(case=args.case, passed=passed, exit=p.returncode, problems=problems, errors=errors[:5], queries=between), ensure_ascii=False), flush=True)+assert passed, text[-4000:]diff --git a/scripts/acceptance/vrr-event-query.qml b/scripts/acceptance/vrr-event-query.qmlnew file mode 100644index 00000000..a979adc2--- /dev/null+++ b/scripts/acceptance/vrr-event-query.qml@@ -0,0 +1,81 @@+// Loaded only into a private staging copy, never the user's running package.+// claude-vrr-event-query-20261025: marks each step in the engine log+// (vrr-test) so vrr-event-query.py can count display queries between them.+import QtQuick+Item {+ id: test+ property string media: ""+ property string mode: "native" // "novrr": VEYRA_TEST_VRR_LEVEL=1 (a monitor without VRR)+ property int phase: 0+ property int ticks: 0+ property int total: 0+ property real beforePosition: 0+ property var notices: []+ property string shot: "" // PNG of the QML scene (显示 tab): the 重新检测 button beside the switch+ property bool shotSaved: false+ function check(ok,why){if(!ok)throw new Error(why)}+ function mark(name){veyra.logUi("vrr-test","mark "+name);console.log("VRR_MARK",name)}+ function next(n,name){phase=n;ticks=0;beforePosition=veyra.position;mark(name)}+ function active(){check(veyra.running&&veyra.fgActive&&veyra.fgBackendName==="vfg","VFG not active: "+veyra.statusText);check(veyra.position>beforePosition+1,"media clock stopped")}+ Connections {+ target: veyra+ function onNotice(text,isError){test.notices.push(text);console.log("VRR_NOTICE",isError,text)}+ }+ Timer {id: timer;interval: 250;repeat: true;running: test.media!==""+ onTriggered: {try {+ ++test.ticks;if(++test.total>400)throw new Error("100 second deadline phase "+test.phase)+ if(test.phase===0){+ // The startup query answers during these 2 s; nothing follows while idle.+ if(test.ticks<8)return+ next(1,"idle-start")+ }else if(test.phase===1){+ if(test.ticks<16)return+ root.page="pro";veyra.muted=true;veyra.nrEnabled=false;veyra.srEnabled=false+ check(veyra.addEffect("vfg-fg")>=0,"VFG stage creation")+ veyra.vfgQuality=1;veyra.fgMultiplier=2;veyra.openPath(test.media);next(2,"open")+ }else if(test.phase===2){+ if(!veyra.running||!veyra.fgActive||veyra.applying||veyra.position<1)return+ next(3,"play-quiet")+ }else if(test.phase===3){+ // 15 s of VFG 2X playback: no display query at all.+ if(test.ticks<60||veyra.applying)return+ active();console.log("VRR_CASE","play",veyra.submitFps,veyra.runStatusDetail)+ // Mark first: the presenter may start the query before this handler returns.+ test.notices=[];next(4,"recheck");veyra.recheckDisplay()+ // The spinner shows at once; the next 250 ms status update may already clear it.+ check(veyra.vrrChecking,"重新检测 shows the spinner at once")+ }else if(test.phase===4){+ if(test.ticks<16)return+ check(test.notices.some(t=>t.indexOf("已重新检测")===0),"re-check notice: "+JSON.stringify(test.notices))+ check(!veyra.vrrChecking,"vrrChecking cleared after the answer")+ next(5,"vrr-on");veyra.variableRefresh=true+ }else if(test.phase===5){+ // Switch on: one query, plus one VRR confirmation 3 s later when VRR presents.+ if(test.ticks<24||veyra.applying)return+ active()+ proPage.tab="display"+ if(test.mode==="novrr")check(veyra.vrrState===1&&veyra.presentationStatus.indexOf("可变刷新")<0,"no VRR presentation: "+veyra.vrrState+" "+veyra.presentationStatus)+ else if(veyra.vrrState>=3)check(veyra.presentationStatus.indexOf("可变刷新")>=0,"VRR presentation: "+veyra.presentationStatus)+ console.log("VRR_CASE","vrr-on",veyra.vrrState,veyra.presentationStatus)+ // A window size change (as entering/leaving fullscreen does).+ next(6,"resize");root.width=root.width-120+ }else if(test.phase===6){+ // VRR presenting: one confirmation 3 s after the size settles; otherwise nothing.+ if(test.ticks<32||veyra.applying)return+ active();console.log("VRR_CASE","end-play",veyra.submitFps,veyra.vrrState,veyra.vrrHint,veyra.presentationStatus)+ if(test.shot!=="")root.contentItem.grabToImage(r=>{test.shotSaved=r.saveToFile(test.shot)})+ veyra.stopPlayback();next(7,"stopped")+ }else if(test.phase===7){+ // Idle 5 s: nothing; then the node page with its output box.+ if(test.ticks<20)return+ check(!veyra.running,"close drains")+ check(test.shot===""||test.shotSaved,"screenshot saved")+ root.page="node";next(8,"node-page")+ }else if(test.phase===8){+ if(test.ticks<8)return+ check(root.page==="node","node page shown")+ test.mark("end");console.log("VRR_PASS");timer.stop();Qt.quit()+ }+ }catch(e){console.error("VRR_FAIL",test.phase,e.message);timer.stop();Qt.quit()}}+ }+}diff --git a/src/engine/DisplayStateService.cpp b/src/engine/DisplayStateService.cppnew file mode 100644index 00000000..5955c3d9--- /dev/null+++ b/src/engine/DisplayStateService.cpp@@ -0,0 +1,157 @@+#include "veyra/engine/DisplayStateService.h"+#include "veyra/gfx/PresentSink.h"+#include "veyra/Log.h"+#include <algorithm>+#include <exception>+#include <format>+#include <string>++namespace veyra::engine {+namespace {+constexpr unsigned kRetries=2;+std::string monitorName(HMONITOR monitor){return std::format("0x{:X}",reinterpret_cast<uintptr_t>(monitor));}+}++DisplayState DisplayStateService::queryDisplayState(HWND window,HMONITOR monitor){+ using Ms=std::chrono::duration<double,std::milli>;+ DisplayState state;+ if(!IsWindow(window)||MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST)!=monitor)return state;+ const auto began=Clock::now();+ state.refreshHz=gfx::PresentSink::displayRefreshFps(window);+ const auto refreshed=Clock::now();+ state.vrr=gfx::queryVrr(window);+ const auto finished=Clock::now();+ state.refreshMs=Ms(refreshed-began).count();state.vrrMs=Ms(finished-refreshed).count();+ if(IsWindow(window)&&MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST)==monitor)state.monitor=monitor;+ return state;+}++DisplayStateService::DisplayStateService()+ :DisplayStateService(&DisplayStateService::queryDisplayState,[](HWND window){return MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST);}){}+DisplayStateService::DisplayStateService(Query query,MonitorOf monitorOf,std::chrono::milliseconds retryDelay)+ :query_(std::move(query)),monitorOf_(std::move(monitorOf)),retryDelay_(retryDelay){}+DisplayStateService::~DisplayStateService(){+ std::shared_future<DisplayState> running;+ {std::lock_guard lock(mutex_);queue_.clear();running=result_;}+ if(running.valid())running.wait();+}++uint64_t DisplayStateService::invalidate(const char* reason){+ std::lock_guard lock(mutex_);+ ++generation_;+ veyra::log::info("display-query",std::format("invalidate reason={} generation={} (stored states are stale; each monitor in use is queried once more)",reason,generation_));+ return generation_;+}+uint64_t DisplayStateService::generation()const{std::lock_guard lock(mutex_);return generation_;}++bool DisplayStateService::currentLocked(const Entry& entry,Clock::time_point now)const{+ // A failure of this generation waits for its retry, and gives up after kRetries.+ if(entry.failedGeneration==generation_&&entry.failures)return entry.failures>kRetries||now<entry.retryAt;+ return entry.state&&entry.state->generation==generation_;+}++bool DisplayStateService::request(HWND window,const char* reason,bool force){+ if(!window)return false;+ const auto monitor=monitorOf_(window);+ if(!monitor)return false;+ std::lock_guard lock(mutex_);+ collectLocked();+ auto& entry=entries_[monitor];+ const auto now=Clock::now();+ if(!force&¤tLocked(entry,now))return false;+ // This generation's answer for the monitor is already on its way.+ if(running_&&running_->monitor==monitor&&running_->generation==generation_)return false;+ for(auto& job:queue_)if(job.monitor==monitor){job.window=window;job.force=job.force||force;return false;}+ const bool retry=!force&&entry.failedGeneration==generation_&&entry.failures;+ const Job job{window,monitor,generation_,retry?"retry":reason,force};+ if(running_)queue_.push_back(job);+ else startLocked(job);+ return true;+}++void DisplayStateService::startLocked(Job job){+ veyra::log::info("display-query",std::format("query reason={} monitor={} generation={} force={} (background thread; nothing waits for it)",+ job.reason,monitorName(job.monitor),job.generation,job.force));+ try{+ result_=std::async(std::launch::async,[query=query_,job]{return query(job.window,job.monitor);}).share();+ running_=job;+ }catch(const std::exception& error){+ result_={};+ failedLocked(entries_[job.monitor],job,std::format("worker start failed: {}",error.what()));+ }+}++void DisplayStateService::failedLocked(Entry& entry,const Job& job,const std::string& why){+ if(entry.failedGeneration!=job.generation){entry.failedGeneration=job.generation;entry.failures=0;}+ ++entry.failures;entry.retryAt=Clock::now()+retryDelay_;+ veyra::log::warn("display-query",std::format("query failed reason={} monitor={} generation={} attempt={} {} ({})",+ job.reason,monitorName(job.monitor),job.generation,entry.failures,why,+ entry.failures>kRetries?"no more automatic retries in this generation; a display change or the re-check button asks again":"retried on the next request after the delay"));+}++void DisplayStateService::collectLocked(){+ while(running_&&result_.valid()&&result_.wait_for(std::chrono::seconds(0))==std::future_status::ready){+ const Job job=*running_;running_.reset();+ const auto finished=std::move(result_);result_={};+ auto& entry=entries_[job.monitor];+ try{+ auto state=finished.get();+ if(state.monitor!=job.monitor)failedLocked(entry,job,"the window closed or moved to another monitor during the query");+ else{+ state.generation=job.generation;state.serial=++serial_;+ if(!entry.state||entry.state->generation<=job.generation)entry.state=state;+ veyra::log::info("display-query",std::format("result reason={} monitor={} generation={} refreshHz={:.3f} vrrLevel={} status={} refreshMs={:.3f} vrrMs={:.3f} (driver wall time on the worker thread)",+ job.reason,monitorName(job.monitor),job.generation,state.refreshHz,gfx::vrrLevel(state.vrr),state.vrr.status,state.refreshMs,state.vrrMs));+ if(state.vrr.status!=0)failedLocked(entry,job,std::format("NVAPI status={}",state.vrr.status));+ else if(entry.failedGeneration==job.generation)entry.failures=0;+ }+ }catch(const std::exception& error){failedLocked(entry,job,std::format("exception: {}",error.what()));}+ catch(...){failedLocked(entry,job,"unknown exception");}+ // The next waiting monitor that still lacks this generation's state.+ const auto now=Clock::now();+ while(!running_&&!queue_.empty()){+ Job next=queue_.front();queue_.erase(queue_.begin());+ next.generation=generation_;+ if(!next.force&¤tLocked(entries_[next.monitor],now))continue;+ startLocked(next);+ }+ }+}++std::optional<DisplayState> DisplayStateService::state(HMONITOR monitor){+ std::lock_guard lock(mutex_);+ collectLocked();+ const auto found=entries_.find(monitor);+ return found==entries_.end()?std::nullopt:found->second.state;+}++std::optional<DisplayState> DisplayStateService::wait(HMONITOR monitor,std::chrono::milliseconds limit){+ const auto until=Clock::now()+limit;+ for(;;){+ std::shared_future<DisplayState> running;+ {+ std::lock_guard lock(mutex_);+ collectLocked();+ const auto found=entries_.find(monitor);+ const auto stored=found==entries_.end()?std::nullopt:found->second.state;+ const bool current=stored&&stored->generation==generation_;+ const bool answering=(running_&&running_->monitor==monitor)||+ std::any_of(queue_.begin(),queue_.end(),[monitor](const Job& job){return job.monitor==monitor;});+ if(current||!answering||!result_.valid()||Clock::now()>=until)return stored;+ running=result_;+ }+ // Outside the lock: the UI keeps reading while a session starts.+ if(running.wait_until(until)!=std::future_status::ready){+ std::lock_guard lock(mutex_);+ const auto found=entries_.find(monitor);+ return found==entries_.end()?std::nullopt:found->second.state;+ }+ }+}++bool DisplayStateService::busy(){+ std::lock_guard lock(mutex_);+ collectLocked();+ return running_.has_value()||!queue_.empty();+}+}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 25d3e9a6..03306129 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -481,7 +481,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// only name the stopped command list after the removal, so teardown checks once more.bool gpuFailureAwaitingRemoval=false;sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;- presenter.setCapture(recorder_.get());+ presenter.setCapture(recorder_.get());presenter.setDisplayStates(&displayStates_);auto& coreCache=gpu->core;auto& recentGraphCache=gpu->recent;auto& graph=gpu->graph;auto& graphBytes=gpu->graphBytes;auto cacheBudgetPolledAt=Clock::now();const bool recentCacheAllowed=!GetEnvironmentVariableW(L"VEYRA_TEST_DISABLE_RECENT_GRAPH_CACHE",nullptr,0);@@ -1317,8 +1317,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// It must not make synchronous driver calls on the GPU owner.const double refreshHz=presenter.displayRefreshHz();const bool capRefreshChanged=requested.outputRate==OutputRateMode::FollowDisplay&&std::abs(refreshHz-pacingRefreshHz)>0.001;- // 可变刷新: the monitor's VRR availability is re-read every 2 s- // (window moved, driver setting changed); a change re-applies.+ // 可变刷新: the monitor's VRR availability is read again on events+ // (another monitor, a display change, 重新检测, the VRR+ // confirmation); a change re-applies.const bool vrrChanged=presenter.vrrSync()!=VideoPresenter::vrrSyncWanted(requested,presenter.displayVrr());if(revision==pacingRevision&&presenterGeneration==presenter.generation()&&!vrrChanged&&!capRefreshChanged){// Reflex dropped out at runtime: the queue-depth part of the@@ -2404,8 +2405,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}// Published after the metrics window switch above: a snapshot that already reports// the new revision never carries the previous revision's totals. The publish of- // this frame's metrics can be a while later (the first frame after a rebuild- // re-reads the display VRR state, ~11 ms on the RTX 5070 rig).+ // this frame's metrics can be a while later.if(transaction||pendingSettingsAck){std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;pendingSettingsAck=false;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));}const double processMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();frameFlow->advanceHistory(out.batch.identity);@@ -2759,8 +2759,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sloopTrace.mark("flowSnapshot");measured.sourceFrames=measured.flow.counters.sourceAccepted;measured.validGenerated=measured.flow.counters.fgReadyValid;measured.submitted=measured.flow.counters.realPresented+measured.flow.counters.generatedPresented;measured.expired=measured.flow.counters.generatedExpiredAfterEval;const double ageP95=liveScheduler?completed.ageP95:captureAges.p95(),waitP95=liveScheduler?completed.waitP95:scheduleWaits.p95(),presentP95=liveScheduler?completed.presentP95:presentTimes.p95();- // Refresh and VRR state (NVAPI, every 2 s) are read outside the- // snapshot lock.+ // Refresh and VRR state (DisplayStateService, queried on events+ // only) are polled outside the snapshot lock; this never waits.presenter.displayRefreshHz();++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.colorStatus=graph->videoHdrActive()?L"SDR → RTX Video HDR":options.settings.videoHdr.enabled&&!gd.hdrInput?L"SDR → SDR(HDR显示未启用)":gd.hdrOutput?(graph->hdr10Output()?L"HDR → HDR10 / PQ":L"HDR → scRGB / 浮点"):gd.hdrInput?L"HDR → SDR色调映射":L"SDR → SDR";snapshot_.position=(isCapture||isImage?pts:lastFilePresentedMs)/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=presentReturnDeviation.p95();snapshot_.videoHdrActive=graph->videoHdrActive();diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 9a31669e..61321b2e 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -31,7 +31,9 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enhveyra::log::warn("present","presentation creation cancelled: target window is no longer available");return false;}- viewWidth_=viewHeight_=0;bufferMonitor_=nullptr;monitorWidth_=monitorHeight_=0;displayQuery_.invalidate();refreshMonitor_=nullptr;refreshHz_=0;refreshQuery_={};vrr_={};refreshQueried_=false;vrrSync_=false;+ // A graph change on the same chain (reuse) keeps the display state and the+ // VRR presentation; a new chain starts them at the end (startDisplayState).+ viewWidth_=viewHeight_=0;bufferMonitor_=nullptr;monitorWidth_=monitorHeight_=0;++generation_;Status st=Status::Ok;// Keep one presentation queue for the native chain's lifetime. A later@@ -111,6 +113,7 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enhveyra::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});+ if(!reuse)startDisplayState();return true;}bool VideoPresenter::prepareGraphChange(){@@ -166,6 +169,9 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&bool resized=false;const auto deferUntil=uint64_t(uintptr_t(GetPropW(window_,L"Veyra.ResizeDeferUntil")));if(viewWidth_!=unsigned(rc.right)||viewHeight_!=unsigned(rc.bottom)){+ // 进出全屏 or a resized window during VRR presentation: VRR may start+ // or stop for it, so ask once 3 s after the size settles.+ if(viewWidth_&&vrrSync_)vrrConfirmAt_=now+std::chrono::seconds(3);viewWidth_=rc.right;viewHeight_=rc.bottom;xessWasEnabled_=false;}unsigned targetWidth=rc.right,targetHeight=rc.bottom;@@ -489,7 +495,7 @@ void VideoPresenter::publishLiveCoverage(const HdrCurveSettings& curve,pipeline:void VideoPresenter::close(){metadataSent_=false;metadataDirty_=false;lastMetadata_={};sourceMetadata_={};metadataAttempt_={};hdrPeakMonitor_=nullptr;hdrPeakInfo_={};hdrPeakQuery_={};- displayQuery_.invalidate();refreshMonitor_=nullptr;refreshHz_=0;refreshQuery_={};vrr_={};refreshQueried_=false;vrrSync_=false;+ refreshMonitor_=nullptr;refreshHz_=0;vrr_={};refreshQueried_=false;vrrSync_=false;displayStateSerial_=0;vrrConfirmAt_.reset();retainedFrame_.reset();xessInputId_=0;xessWork_={};xessWorkPosition_=0;reflex_.close();reflexFrame_=0;@@ -501,47 +507,45 @@ void VideoPresenter::close(){if(presentationEvent_){CloseHandle(presentationEvent_);presentationEvent_=nullptr;}presentationDevice_=nullptr;presentationFormat_=DXGI_FORMAT_UNKNOWN;window_=nullptr;}+void VideoPresenter::startDisplayState(){+ // A new presentation chain (session start): the monitor's stored state+ // applies at once and is checked once more in the background; without one+ // the first configuration waits up to 100 ms for the first answer.+ if(!displayStates_||!window_)return;+ const auto monitor=MonitorFromWindow(window_,MONITOR_DEFAULTTONEAREST);+ refreshMonitor_=monitor;displayGeneration_=displayStates_->generation();+ auto state=displayStates_->state(monitor);+ const bool cached=state.has_value();+ displayStates_->request(window_,"session-start",cached);+ if(!cached)state=displayStates_->wait(monitor,std::chrono::milliseconds(100));+ if(state)applyDisplayState(*state);+ veyra::log::info("display-query",std::format("presentation chain start monitor=0x{:X} cached={} answered={} (read again only on events, never on a timer)",+ reinterpret_cast<uintptr_t>(monitor),cached,state.has_value()));+}+void VideoPresenter::applyDisplayState(const DisplayState& state){+ if(state.monitor!=refreshMonitor_)return;+ const auto hz=state.refreshHz;const auto& vrr=state.vrr;+ if(refreshQueried_&&std::abs(hz-refreshHz_)>0.5)veyra::log::info("display-refresh",std::format("monitor refresh={:.3f} Hz (was {:.3f}; window moved or display mode changed)",hz,refreshHz_));+ refreshHz_=hz;sink_.setDisplayRefreshHz(hz);+ if(!(vrr==vrr_)||!refreshQueried_)veyra::log::info("display-vrr",std::format("level={} known={} monitorSupportsVrr={} currentlyCapable={} trueGsync={} capsKnown={} possible={} requested={} active={} displayInVrrMode={} indicator={} simulated={} status={} refreshHz={:.3f} (NVIDIA G-SYNC / G-SYNC Compatible state of the window's monitor; enabled by the user in the NVIDIA Control Panel, never changed by Veyra)",gfx::vrrLevel(vrr),vrr.known,vrr.supportsVrr,vrr.currentlyCapable,vrr.trueGsync,vrr.capsKnown,vrr.possible,vrr.requested,vrr.enabled,vrr.inVrrMode,vrr.indicator,vrr.simulated,vrr.status,hz));+ vrr_=vrr;refreshQueried_=true;displayStateSerial_=state.serial;+}double VideoPresenter::displayRefreshHz(){if(!window_)return 0;- const auto now=std::chrono::steady_clock::now();+ if(!displayStates_)return refreshHz_;const auto monitor=MonitorFromWindow(window_,MONITOR_DEFAULTTONEAREST);+ const char* reason="presenter";if(monitor!=refreshMonitor_){- // Never apply the previous monitor's VRR/cap to a moved window.- displayQuery_.invalidate();refreshMonitor_=monitor;refreshQuery_={};- refreshHz_=0;vrr_={};refreshQueried_=false;- }- try{- if(auto result=displayQuery_.poll();result&&result->monitor==monitor){- const auto hz=result->hz;const auto& vrr=result->vrr;- if(refreshQueried_&&std::abs(hz-refreshHz_)>0.5)veyra::log::info("display-refresh",std::format("monitor refresh={:.3f} Hz (was {:.3f}; window moved or display mode changed)",hz,refreshHz_));- refreshHz_=hz;sink_.setDisplayRefreshHz(hz);- if(!(vrr==vrr_)||!refreshQueried_)veyra::log::info("display-vrr",std::format("level={} known={} monitorSupportsVrr={} currentlyCapable={} trueGsync={} capsKnown={} possible={} requested={} active={} displayInVrrMode={} indicator={} simulated={} status={} refreshHz={:.3f} (NVIDIA G-SYNC / G-SYNC Compatible state of the window's monitor; enabled by the user in the NVIDIA Control Panel, never changed by Veyra)",gfx::vrrLevel(vrr),vrr.known,vrr.supportsVrr,vrr.currentlyCapable,vrr.trueGsync,vrr.capsKnown,vrr.possible,vrr.requested,vrr.enabled,vrr.inVrrMode,vrr.indicator,vrr.simulated,vrr.status,hz));- vrr_=vrr;refreshQueried_=true;- if(result->refreshMs+result->vrrMs>=2.0)veyra::log::info("display-query",std::format("refreshMs={:.3f} vrrMs={:.3f} asynchronous=true (driver query wall time; not GPU execution or owner-thread wait)",result->refreshMs,result->vrrMs));- }- if(monitor&&now-refreshQuery_>=std::chrono::seconds(2)&&!displayQuery_.pending()){- const HWND window=window_;- // Captures no presenter/swapchain/device. An obsolete HWND/monitor is- // rejected both here and by the owner's invalidation generation.- displayQuery_.request([window,monitor]{- DisplayQueryResult result;result.monitor=monitor;- if(!IsWindow(window)||MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST)!=monitor)return result;- const auto began=std::chrono::steady_clock::now();- result.hz=gfx::PresentSink::displayRefreshFps(window);- const auto refreshed=std::chrono::steady_clock::now();- result.vrr=gfx::queryVrr(window);- const auto finished=std::chrono::steady_clock::now();- result.refreshMs=std::chrono::duration<double,std::milli>(refreshed-began).count();- result.vrrMs=std::chrono::duration<double,std::milli>(finished-refreshed).count();- if(!IsWindow(window)||MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST)!=monitor)result.monitor=nullptr;- return result;- });- refreshQuery_=now;- }- }catch(const std::exception& error){- refreshQuery_=now;- veyra::log::warn("display-query",std::format("asynchronous display query failed: {} (retaining cached state; retry after 2 s)",error.what()));+ // Never apply the previous monitor's VRR/cap to a moved window; its own+ // stored state (an earlier visit) applies at once when there is one.+ refreshMonitor_=monitor;refreshHz_=0;vrr_={};refreshQueried_=false;displayStateSerial_=0;reason="monitor-change";}+ if(const auto generation=displayStates_->generation();generation!=displayGeneration_){displayGeneration_=generation;reason="display-change";}+ // request() starts a query only when this monitor's state is stale or+ // missing, so calling it every loop costs a lock and a lookup.+ if(vrrConfirmAt_&&std::chrono::steady_clock::now()>=*vrrConfirmAt_){vrrConfirmAt_.reset();displayStates_->request(window_,"vrr-confirm",true);}+ else displayStates_->request(window_,reason);+ if(const auto state=displayStates_->state(monitor);state&&state->serial!=displayStateSerial_)applyDisplayState(*state);return refreshHz_;}PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceContext& ctx,PresentationSettings requested,bool fg,std::wstring& status){@@ -590,7 +594,10 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceConte// one-deep VSync queue below holds. Without VRR (switch off, another// monitor, driver setting off) Automatic stays Present(0,0).displayRefreshHz();+ const bool wasVrrSync=vrrSync_;vrrSync_=vrrSyncWanted(requested,vrr_);+ // VRR presentation just started: ask the driver once more whether it runs.+ if(vrrSync_&&!wasVrrSync)vrrConfirmAt_=std::chrono::steady_clock::now()+std::chrono::seconds(3);if(vrrSync_){requested.display=DisplaySync::Vsync;effective.display=DisplaySync::Vsync;}const bool vsync=presentationVsync(requested),tearing=presentationTearing(requested);providerOwnedPresentation_=xessActive();diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 2c52aadc..df568924 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -6,6 +6,7 @@#include "veyra/ngx/DlssgLite.h"#include "veyra/RuntimePaths.h"#include "veyra/ui/GamePassthrough.h"+#include <QAbstractNativeEventFilter>#include <QGuiApplication>#include <QScreen>#include <QtGui/qscreen_platform.h>@@ -182,6 +183,19 @@ static QString unavailableEffects(const engine::EnhancementSettings& settings);static QString disableUnavailableEffects(engine::ChainConfiguration& configuration);static ui::EffectGpu effectGpu();+namespace {+// WM_DISPLAYCHANGE reaches every top-level window when a display mode, refresh+// rate or HDR state, or the set of screens, changes: the 可变刷新 state is then+// read once more (DisplayStateService) instead of on a timer.+struct DisplayChangeFilter final : QAbstractNativeEventFilter {+ bool* changed = nullptr;+ bool nativeEventFilter(const QByteArray& type, void* message, qintptr*) override {+ if (changed && type == "windows_generic_MSG" && static_cast<const MSG*>(message)->message == WM_DISPLAYCHANGE) *changed = true;+ return false;+ }+};+}+struct QmlPlayerBridge::Impl {// Per-layer on/off before the NR master switch turned them all off.std::vector<bool> nrMasterRestore;@@ -485,8 +499,12 @@ struct QmlPlayerBridge::Impl {// presenting monitor, or of the main window's monitor while idle.QString fgDisplayHint;int vrrState=0;- gfx::VrrState idleVrr{};- std::chrono::steady_clock::time_point idleVrrQuery{};+ // 重新检测: the display generation it asked for, until the shown monitor+ // answers (vrrChecking also covers any query in flight).+ bool vrrChecking=false,vrrRecheckPending=false,displayChanged=false;+ uint64_t vrrRecheckGeneration=0;+ std::chrono::steady_clock::time_point vrrRecheckSince{};+ DisplayChangeFilter displayChangeFilter;std::atomic<double> gpuUtil{-1.0};// Hardware adapters in Windows' high-performance order (discrete first). The// sampler only counts engines of the adapter whose LUID is in gpuMonitorLuid@@ -1240,6 +1258,8 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst// 游戏模式. The native filter also keeps windows shown during a monitor capture// out of that capture, so it is installed for every run.if (qApp) qApp->installNativeEventFilter(&impl_->game);+ impl_->displayChangeFilter.changed = &impl_->displayChanged;+ if (qApp) qApp->installNativeEventFilter(&impl_->displayChangeFilter);impl_->game.onEvent = [this](ui::GamePassthrough::Event event) {using E = ui::GamePassthrough::Event;switch (event) {@@ -1759,6 +1779,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystQmlPlayerBridge::~QmlPlayerBridge() {flushHdrMemory();if (qApp) qApp->removeEventFilter(this);+ if (qApp) qApp->removeNativeEventFilter(&impl_->displayChangeFilter);rememberPosition(true);if (impl_->sessionSaveTimer) impl_->sessionSaveTimer->stop();if (!impl_->persistSession())@@ -8208,19 +8229,30 @@ void QmlPlayerBridge::updateRunStatus() {options<<((refresh>0)?tr("%1 · 屏幕 %2 Hz").arg(sync).arg(refresh,0,'f',1):sync);}// Variable refresh (NVIDIA G-SYNC / G-SYNC Compatible): the presenting- // monitor while playing, otherwise the main window's monitor (NVAPI,- // at most every 2 s). The driver setting is the user's; the 可变刷新- // switch decides how Veyra presents when it is possible.- int vrrLevel=int(s.displayVrr);- if(!s.running){- const auto now=std::chrono::steady_clock::now();- if(i.idleVrrQuery==std::chrono::steady_clock::time_point{}||now-i.idleVrrQuery>=std::chrono::seconds(2)){- HWND host=owner;- if(!host)if(auto* window=QGuiApplication::focusWindow())host=reinterpret_cast<HWND>(window->winId());- if(host){i.idleVrr=gfx::queryVrr(host);i.idleVrrQuery=now;}+ // monitor while playing, otherwise the main window's monitor. Both come+ // from the engine's DisplayStateService, queried in the background on+ // events only (startup, another monitor, WM_DISPLAYCHANGE, the switch+ // turned on, 重新检测), never on a timer. The driver setting is the+ // user's; the 可变刷新 switch decides how Veyra presents when it is possible.+ auto& displays=i.engine.displayStates();+ if(i.displayChanged){i.displayChanged=false;displays.invalidate("display-change");}+ HWND host=s.running&&i.videoWindow?i.videoWindow:owner;+ if(!host)if(auto* window=QGuiApplication::focusWindow())host=reinterpret_cast<HWND>(window->winId());+ // request() starts a query only when this monitor's state is stale or+ // missing (the presenter asks for the same monitor while playing).+ if(host)displays.request(host,i.vrrRecheckPending?"manual":"ui");+ const auto display=host?displays.state(displays.monitorOf(host)):std::nullopt;+ const int vrrLevel=s.running?int(s.displayVrr):display?int(gfx::vrrLevel(display->vrr)):0;+ QString recheckNotice;bool recheckFailed=false;+ if(i.vrrRecheckPending){+ // Answered once the shown monitor has a state of the re-check's generation.+ if(display&&display->generation>=i.vrrRecheckGeneration){+ i.vrrRecheckPending=false;recheckNotice=tr("已重新检测:%1").arg(vrrHintText(int(gfx::vrrLevel(display->vrr))));+ }else if(std::chrono::steady_clock::now()-i.vrrRecheckSince>std::chrono::seconds(5)){+ i.vrrRecheckPending=false;recheckNotice=tr("重新检测没有完成,请稍后再试");recheckFailed=true;}- vrrLevel=int(gfx::vrrLevel(i.idleVrr));}+ const bool vrrChecking=i.vrrRecheckPending||displays.busy();if(i.presentation.variableRefresh){if(vrrLevel>=4)options<<tr("可变刷新 · 生效中");else if(vrrLevel==3)options<<tr("可变刷新 · 等待驱动确认");@@ -8314,10 +8346,11 @@ void QmlPlayerBridge::updateRunStatus() {const double gpu = i.gpuUtil.load();const double target=active&&f.rateWindowReady&&rate.targetFps>0?rate.targetFps:-1;const bool changed = ratioChanged || active || status != i.runStatus || level != i.runLevel || text != i.runDetail || options!=i.runOptions || std::abs(target-i.effectiveOutputFps)>.05 || std::abs(gpu - i.gpuPublished) > 0.05 ||- fgHint != i.fgDisplayHint || vrrLevel != i.vrrState;+ fgHint != i.fgDisplayHint || vrrLevel != i.vrrState || vrrChecking != i.vrrChecking;i.runStatus = status; i.runLevel = level; i.runDetail = text; i.gpuPublished = gpu;- i.runOptions=options;i.effectiveOutputFps=target;i.fgDisplayHint=fgHint;i.vrrState=vrrLevel;+ i.runOptions=options;i.effectiveOutputFps=target;i.fgDisplayHint=fgHint;i.vrrState=vrrLevel;i.vrrChecking=vrrChecking;if (changed) emit perfChanged();+ if (!recheckNotice.isEmpty()) emit notice(recheckNotice, recheckFailed);}// --- NR protection regions drawn on the picture (#8) ------------------------@@ -8566,14 +8599,27 @@ bool QmlPlayerBridge::variableRefresh() const { return impl_->presentation.variavoid QmlPlayerBridge::setVariableRefresh(bool value) {if (impl_->presentation.variableRefresh == value) return;impl_->presentation.variableRefresh = value;+ // Turning it on reads the monitor again: the driver setting may have changed.+ if (value) impl_->engine.displayStates().invalidate("vrr-switch-on");applyPresentation();}int QmlPlayerBridge::vrrState() const { return impl_->vrrState; }-QString QmlPlayerBridge::vrrHint() const {+bool QmlPlayerBridge::vrrChecking() const { return impl_->vrrChecking; }+void QmlPlayerBridge::recheckDisplay() {+ // Every stored display state becomes stale; the next status update (or the+ // presenter's next loop) queries the shown monitor in the background.+ auto& i = *impl_;+ i.vrrRecheckGeneration = i.engine.displayStates().invalidate("manual");+ i.vrrRecheckPending = true;+ i.vrrRecheckSince = std::chrono::steady_clock::now();+ if (!i.vrrChecking) { i.vrrChecking = true; emit perfChanged(); }+}+QString QmlPlayerBridge::vrrHint() const { return vrrHintText(impl_->vrrState); }+QString QmlPlayerBridge::vrrHintText(int level) const {// The 可变刷新 switch is available (not grey) from level 2: the monitor// can do VRR even if the driver setting is still off.const bool on = impl_->presentation.variableRefresh, running = impl_->snapshot.running;- switch (impl_->vrrState) {+ switch (level) {case 0: return tr("无法检测屏幕是否支持(目前只支持 NVIDIA 显卡)");case 1: return tr("当前屏幕不支持可变刷新");case 2: return tr("屏幕支持可变刷新,但当前显示模式不可用;请检查连接、刷新率及驱动设置");diff --git a/tests/unit/AsyncDisplayQueryTests.cpp b/tests/unit/AsyncDisplayQueryTests.cppindex 99b229d9..d1db434a 100644--- a/tests/unit/AsyncDisplayQueryTests.cpp+++ b/tests/unit/AsyncDisplayQueryTests.cpp@@ -1,8 +1,12 @@#include "veyra/engine/AsyncDisplayQuery.h"+#include "veyra/engine/DisplayStateService.h"#include "veyra/gfx/PresentSink.h"#include "veyra/gfx/NvidiaVrr.h"+#include <atomic>+#include <condition_variable>#include <future>#include <iostream>+#include <mutex>#include <stdexcept>#include <thread>@@ -50,6 +54,104 @@ int wmain(int argc,wchar_t** argv){bool caught=false;try{take();}catch(const std::runtime_error&){caught=true;}check(caught&&!query.pending(),"query failure leaves no stuck pending future");query.request([]{return 120;});check(take()==120,"query can retry after driver exception");++ // DisplayStateService (2026-10-25): shared states, queried on events only.+ {+ using veyra::engine::DisplayState;using veyra::engine::DisplayStateService;+ const auto windowA=reinterpret_cast<HWND>(uintptr_t(0x10)),windowB=reinterpret_cast<HWND>(uintptr_t(0x20));+ const auto monitorA=reinterpret_cast<HMONITOR>(uintptr_t(0x1000)),monitorB=reinterpret_cast<HMONITOR>(uintptr_t(0x2000));+ std::atomic<unsigned> calls{0};std::atomic<int> status{0};std::atomic<bool> moved{false},raise{false};+ std::mutex gateMutex;std::condition_variable gateWake;bool gateOpen=true;+ auto setGate=[&](bool open){{std::lock_guard lock(gateMutex);gateOpen=open;}gateWake.notify_all();};+ auto fakeQuery=[&](HWND window,HMONITOR monitor){+ ++calls;+ {std::unique_lock lock(gateMutex);gateWake.wait(lock,[&]{return gateOpen;});}+ if(raise.load())throw std::runtime_error("simulated NVAPI crash");+ DisplayState state;state.monitor=moved.load()?nullptr:monitor;state.refreshHz=window==windowA?144.0:60.0;+ state.vrr.known=true;state.vrr.capsKnown=state.vrr.supportsVrr=state.vrr.currentlyCapable=true;state.vrr.status=status.load();+ return state;+ };+ auto monitorOf=[&](HWND window){return window==windowA?monitorA:window==windowB?monitorB:HMONITOR(nullptr);};+ {+ DisplayStateService service(fakeQuery,monitorOf,std::chrono::milliseconds(50));+ auto settle=[&](HMONITOR monitor){+ const auto until=Clock::now()+std::chrono::seconds(2);+ while(service.busy()&&Clock::now()<until)std::this_thread::sleep_for(std::chrono::milliseconds(1));+ return service.state(monitor);+ };+ // The worker counts a call when it starts, which may trail request().+ auto waitCalls=[&](unsigned n){+ const auto until=Clock::now()+std::chrono::seconds(2);+ while(calls<n&&Clock::now()<until)std::this_thread::yield();+ return calls==n;+ };+ check(!service.state(monitorA)&&!service.busy(),"no display state is fabricated before the first answer");+ check(service.request(windowA,"test"),"the first request starts one query");+ auto a=settle(monitorA);+ check(a&&a->refreshHz==144.0&&a->generation==service.generation()&&calls==1,"the answer is stored for its monitor in the current generation");+ bool quiet=true;for(unsigned i=0;i<1000;++i)quiet&=!service.request(windowA,"test");+ check(quiet&&calls==1&&!service.busy(),"requests every frame/tick never query a current monitor again");++ const auto first=a->serial;setGate(false);+ const auto generation=service.invalidate("test");+ check(service.request(windowA,"display-change"),"a display change queries the monitor once more");+ const auto start=Clock::now();bool held=true;+ for(unsigned i=0;i<1000;++i)held&=!service.request(windowA,"test");+ const bool nonblocking=Clock::now()-start<std::chrono::milliseconds(500);+ const auto stale=service.state(monitorA);+ check(held&&nonblocking&&service.busy()&&waitCalls(2),"a blocked driver call never blocks or duplicates requests");+ check(stale&&stale->serial==first&&stale->generation<generation,"readers keep the stale state until the new answer");+ check(service.request(windowB,"monitor-change")&&calls==2,"another monitor waits in the queue behind the running query");+ setGate(true);+ auto fresh=settle(monitorA);auto b=service.state(monitorB);+ check(fresh&&fresh->generation==generation&&fresh->serial!=first&&b&&b->refreshHz==60.0&&calls==3,"both monitors answered once each after the release");++ check(service.request(windowA,"vrr-confirm",true)&&!service.request(windowA,"vrr-confirm",true),"a forced check runs once even while current");+ settle(monitorA);check(calls==4,"the forced check queried exactly once");++ status=-5;service.invalidate("test");+ check(service.request(windowA,"test"),"query with a failing driver call");+ auto failed=settle(monitorA);+ check(failed&&failed->vrr.status==-5&&!service.request(windowA,"test"),"an NVAPI error is stored and the retry waits for its delay");+ unsigned retries=0;+ for(unsigned i=0;i<4;++i){std::this_thread::sleep_for(std::chrono::milliseconds(70));if(service.request(windowA,"test")){++retries;settle(monitorA);}}+ check(retries==2&&calls==7,"two automatic retries per generation, then none");+ status=0;service.invalidate("test");+ check(service.request(windowA,"test"),"a new generation asks again after the failures");+ auto recovered=settle(monitorA);+ check(recovered&&recovered->vrr.status==0&&!service.request(windowA,"test"),"a good answer ends the retries");++ moved=true;service.invalidate("test");service.request(windowA,"test");+ auto discarded=settle(monitorA);+ check(discarded&&discarded->serial==recovered->serial,"a window that moved during the query never stores that answer");+ moved=false;std::this_thread::sleep_for(std::chrono::milliseconds(70));+ check(service.request(windowA,"test")&&settle(monitorA)->serial!=recovered->serial,"the moved-window answer is retried after the delay");++ raise=true;service.invalidate("test");service.request(windowA,"test");settle(monitorA);+ check(!service.busy(),"a query exception leaves nothing running or queued");+ raise=false;++ setGate(false);service.invalidate("test");service.request(windowA,"session-start");+ const auto waitStart=Clock::now();+ auto timedOut=service.wait(monitorA,std::chrono::milliseconds(40));+ const auto waited=Clock::now()-waitStart;+ check(timedOut&&timedOut->generation<service.generation()&&waited>=std::chrono::milliseconds(35)&&waited<std::chrono::milliseconds(1000),+ "session start waits at most its limit and then uses the stored state");+ std::jthread opener([&]{std::this_thread::sleep_for(std::chrono::milliseconds(30));setGate(true);});+ auto answered=service.wait(monitorA,std::chrono::milliseconds(1000));+ check(answered&&answered->generation==service.generation(),"session start uses the answer that arrives within the limit");+ const auto quick=Clock::now();+ auto notAnswering=service.wait(monitorB,std::chrono::milliseconds(500));+ check(notAnswering&¬Answering->generation<service.generation()&&Clock::now()-quick<std::chrono::milliseconds(100),+ "waiting without a query for the monitor returns at once");+ }+ // Destruction waits for the running driver call, never for the queue.+ setGate(false);+ std::jthread opener([&]{std::this_thread::sleep_for(std::chrono::milliseconds(30));setGate(true);});+ const auto closing=Clock::now();+ {DisplayStateService service(fakeQuery,monitorOf,std::chrono::milliseconds(50));service.request(windowA,"test");service.request(windowB,"test");}+ check(Clock::now()-closing<std::chrono::seconds(2),"destruction returns after the running query, without starting queued ones");+ }std::cout<<"ASYNC_DISPLAY_QUERY failures="<<failures<<std::endl;return failures?1:0;}