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++
Move periodic VRR queries off video owner and verify 1440p60 NV12 capture
Veyra Goal Agent038beacd51b1
diff --git a/AGENTS.md b/AGENTS.mdindex 9c923ad3..7fa13ecb 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-24 补帧调度修复追加授权**:用户明确要求另开分支排查修复,覆盖上一轮仅诊断限制;从97959cc在codex/fg-scheduling-repair-20261024按docs/FG_SCHEDULING_REPAIR_PLAN_2026-10-24.md施工,允许有证据的调度/必要链路/限频诊断/定向测试接点。用户正在E:/App运行,只读日志,不停止其进程/改真实配置/争抢采集或添加GPU负载;不放宽期限/掩盖告警/无界排队。单Agent、全E盘、复用构建-j2<=900秒/单测<=300秒,无main合并/push/Release,Lecram暂停。+> **2026-10-24 NR手动比例及日志排查(用户请求)**:从108c010在codex/nr-manual-scale-20261024实施每层NR内部手动百分比与条件滑条,按docs/NR_MANUAL_SCALE_PLAN_2026-10-24.md,仅扩展NR尺寸规划/既有参数桥接/共用QML滑条/翻译/必要合同测试与持久化兼容;这些新功能必要接点覆盖旧2.0.0 UI迁移冻结。不改FG预算/调度/采集/告警判定,用户指定调度降档只诊断。用户E:/App包/日志只读,私有测试不连真实主机或采集卡。单Agent,全E盘,复用当前同源构建-j2<=900秒/单测试<=300秒;不改专有运行文件/驱动/真实配置,无main合并/push/Release,Lecram暂停。> **2026-10-23 依赖迁移与历史产物清理(用户明确授权)**:`C:\veyra-deps` 的149125个普通文件已逐文件SHA256核验并迁到 **`E:\项目\Veyra\deps\core`**,C盘旧实体已删除;`C:\veyra-deps` 仅为指向该E盘目录的 Junction,保留兼容旧脚本/CMake缓存,禁止删除此入口或重新在C盘建依赖实体。Qt实体仍为 `E:\项目\Veyra\deps\qt\6.8.3\msvc2022_64`,`deps\core\qt-veyra` 仅指向 `deps\qt`。新任务优先使用E盘实体路径;旧缓存不必为改路径强制全量重编译。共享路径清单 `E:\项目\Veyra\deps\DEPENDENCY_ROOTS.json`,共享规则 `E:\项目\Veyra\AGENTS.md`,证据 `E:\项目\Veyra\reports\dependency-migration-cleanup-20261023`。本条覆盖旧“C:\veyra-deps暂保留不迁移”的限制。历史测试/包按本轮清单清理;正式发布资产只保留2.0.7及以后(当前2.0.7/2.0.8/2.0.9/2.1.0),依GitHub资产SHA而非内部test文件名判定。当前未合入正式版的rot1交付单独保留;不删源码工作树/未提交改动/依赖模型/对应源码与必要验收记录。清理实际结果以该目录FINAL.json为准,不从计划推断已删除。不merge/push/发布,不继续Lecram。diff --git a/CMakeLists.txt b/CMakeLists.txtindex 38c6000d..dd56fac4 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -800,6 +800,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_definitions(veyra_capture_format_selection_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)target_link_libraries(veyra_capture_format_selection_tests PRIVATE ole32 strmiids)add_executable(veyra_presentation_worker_tests tests/unit/LiveGpuSchedulerTests.cpp)+ add_executable(veyra_async_display_query_tests tests/unit/AsyncDisplayQueryTests.cpp)+ target_compile_features(veyra_async_display_query_tests PRIVATE cxx_std_20)+ target_compile_definitions(veyra_async_display_query_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)+ target_link_libraries(veyra_async_display_query_tests PRIVATE veyra_engine)target_compile_features(veyra_presentation_worker_tests PRIVATE cxx_std_20)target_compile_definitions(veyra_presentation_worker_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)target_include_directories(veyra_presentation_worker_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)diff --git a/docs/FG_SCHEDULING_REPAIR_PLAN_2026-10-24.md b/docs/FG_SCHEDULING_REPAIR_PLAN_2026-10-24.mdnew file mode 100644index 00000000..6dc3edda--- /dev/null+++ b/docs/FG_SCHEDULING_REPAIR_PLAN_2026-10-24.md@@ -0,0 +1,12 @@+# 2026-10-24 实时采集补帧调度降档修复++用户在上一轮仅诊断后追加授权:开独立分支排查并尝试修复,用户正在实际运行且持续看到问题。本授权覆盖本问题必要的引擎/处理图/呈现/采集/状态及针对性测试接点,不扩展为其它效果重构。基线97959cc840698243f76d3005a7906e4eb3a134aa,分支codex/fg-scheduling-repair-20261024,存档checkpoint/pre-fg-scheduling-repair-20261024;复用当前源码工作树与同源构建,不覆盖其它脏树,不合main/push/Release,Lecram暂停,单Agent。++1. 只读快照用户E:/App的运行日志,按本次进程/会话/revision分开定位预算不足、准入前CPU迟到、生成有效性、呈现过期。运行中文件属性缓存不代表日志停止,读取真实文件尾部。用户当前原版2.1.0进程保持运行,不停止、不写其配置/包,不另开采集争抢设备,也不加GPU压力。+2. 先用现有日志和源码证明故障路径,必要时增加限频且低开销的原因/阶段探针。修复必须针对可复现的错误;不通过延长期限、堆积帧队列、抹除告警或伪造FPS获得通过。保持真实PTS、原帧、有界资源/历史、既有后端同步与运行库身份。+3. 先做确定性日志回放/时序/预算/状态回归,构建-j2<=900秒、单测试<=300秒。复用E盘依赖与现有build/claude-screen-recording-20261022。用户播放期间不运行GPU回归;CPU侧验收/静态核对和小更新包可先完成,现场修复需独立新进程由用户切换后再采证,不能把旧进程日志冒充修复结果。+4. 产物统一E:/项目/Veyra/{archives,reports,logs,tmp,tests,test-packages}/fg-scheduling-repair-20261024。记录失败、命令、测试覆盖与未验项;本地小更新不携带DLL/模型/SDK/日志/用户配置,不覆盖正式发布资产。++初始实时观察:09:47 LA,session3/revision10,采集回调60fps、主动60->30、VFG2X、NR关闭,FG GPU约3.1ms;有准入elapsed17.688ms导致剩余期限-13.335ms被拒绝,也有大量contentDuplicate导致的无效生成。这两类必须分开,不能把后端重复帧直接当作准入超时。++09:56用户追加要求用采集卡测试2K60 NV12。允许在无其它Veyra进程占用时,以私有配置打开KUHAIMI G50的精确2560x1440p60 NV12身份,实际日志核对SetFormat/ConnectDirect/Run;执行原nr1基线与fg1修复的顺序A/B,NR/SR关闭、VFG2X,分别检查原60和主动60->30,单用例40秒稳定测量。共享一份任务专用app,逐例独立profile/log/TEMP;不读写真实用户配置,不同时开两个采集进程,截图放私有profile且在测量结束后执行。文件播放4K30的VFG2X/4X、跟随显示器/VRR、暂停恢复及关闭重开已先行通过,它不能替代此次真采集证据。diff --git a/docs/FG_SCHEDULING_REPAIR_REPORT_2026-10-24.md b/docs/FG_SCHEDULING_REPAIR_REPORT_2026-10-24.mdnew file mode 100644index 00000000..cb8ecc1e--- /dev/null+++ b/docs/FG_SCHEDULING_REPAIR_REPORT_2026-10-24.md@@ -0,0 +1,37 @@+# 2026-10-24 补帧调度降档修复与真采集对照++已在隔离分支`codex/fg-scheduling-repair-20261024`修复一个明确的周期性阻塞:显示器刷新/VRR查询原本在播放线程同步执行,采集帧已读取、准入期限已开始计时后,每约两秒调用一次NVIDIA显示状态接口。该组只读查询在本机耗时10.5–22.0ms,足以让约3ms的VFG也错过期限。改为单个在途后台查询,播放线程仅非阻塞取结果;窗口/显示器/图生命周期改变时丢弃旧代结果,异步失败保留缓存并限频重试。跟随显示器限帧和VRR策略在新结果到达后重新应用,不拿未知值或旧显示器状态当当前值。++未扩大准入期限、未隐藏降档提示、未堆积帧、未降低用户设置倍率;`FgRecoveryBudget.h`、`LivePairLatency.h`、`PresentationScheduler.h`、`LiveStatusHistory.h`、`EnhanceGraph.cpp`、`CaptureCardSource.cpp`内容相对97959cc保持不变(Git换行规范化比较)。此前诊断中的真实GPU超预算依然应降档;本修复不保证任何负载都不跳帧。++## 用户要求的2K60 NV12真采集++用户明确追加要求后,在无其它Veyra进程占用时,以私有配置顺序运行KUHAIMI G50。每例都核对驱动日志:`SetFormat`/`ConnectDirect`成功,实际`2560x1440 nominalFps=60.000`,上游子类型`0x3231564E`(NV12),无转换滤镜;回调5529600字节与1440p NV12相符。NR/SR关闭,NVIDIA VFG2X Medium,显示同步Automatic,输出限帧关闭、VRR开关关闭,音频禁用以隔离视频问题。完整原60与主动60->30分开对照。旧基线为nr1(d43a5384…60289),修复为fg1(32296020…a6a),运行库与QML/测试步骤相同。++各例先预热6秒,再测量40秒。下表使用该窗口内首末**同会话/同revision累计计数之差**,对应计数区间约38.6–39.2秒,绝非把限频日志行数冒充丢帧总数。++| 路径 | 版本 | 计数区间 | FG候选 | 准入前跳过 | 生成后过期 | 平均采集回调 |+| --- | --- | ---: | ---: | ---: | ---: | ---: |+| 原60→VFG2X | nr1旧基线 | 38.600s | 2316 | 10 | 2 | 60.00fps |+| 原60→VFG2X | fg1修复 | 38.600s | 2316 | 0 | 0 | 60.00fps |+| 主动60→30→VFG2X | nr1旧基线 | 39.166s | 1175 | 13 | 0 | 60.00fps |+| 主动60→30→VFG2X | fg1修复 | 39.100s | 1173 | 0 | 0 | 60.00fps |++四例计数区间的邮箱覆盖均为0。旧版被限频采样记录到的准入前CPU最大耗时分别13.188/16.729ms;修复版相应采样最大0.151/0.210ms,后台查询仍耗时最高14.602/14.366ms,但不再由播放线程等待。此采样最大值不冒充全部帧的真实最大值。两组修复中所有候选均完成评估并实际提交生成帧,不能用减少候选/关闭补帧解释通过。原帧数、主动半帧计数保持真实。测量结束后才抓一张处理后画面,实际2560x1440、非黑,已人工查看;截图不用于断言生成帧视觉质量、扫描率或屏幕端到端延迟。++这证明本机该配置下的周期性问题得到修复,不能扩展为长期零掉帧、其它卡/后端/重NR/HDR全部通过。日志里其它长控制/提交停顿、过高GPU负载仍可能触发提示。++## 其它验证、命令与失败记录++- `scripts/acceptance/build-recording-handoff.py --task codex-fg-scheduling-repair-20261024 --root E:/项目/Veyra/worktrees/screen-recording-fix-20261022 --build-dir E:/项目/Veyra/build/claude-screen-recording-20261022 --reconfigure --label 2.1.0-fg1 veyra_qml_ui veyra_async_display_query_tests veyra_presentation_worker_tests veyra_realtime_preview_tests veyra_hdr_display_state_tests veyra_ui_contract_tests veyra_repair_contract_tests`:配置/构建通过,50.3秒,-j2。后仅重编读显示探针测试目标2.8秒,应用EXE未变化。+- 六项CPU合同全部通过:异步查询10项(阻塞驱动时1000次owner轮询不等待、不堆worker;关闭重开/旧代丢弃/异常重试)、调度/预算127项、实时预览57项、HDR显示状态、UI合同含384布局、Repair272项。Repair首启缺FFmpeg运行路径报0xC0000135,补入现有Qt/FFmpeg依赖PATH后返回0,保留初始失败,不归为产品修复。首次保护文件原始字节比较因CRLF工作树/LF Git blob不同而拒绝,改为Git换行规范化比较六文件均无内容改动。+- `veyra_async_display_query_tests.exe --probe 0`:只读显示状态探针,无D3D设备/队列/捕获初始化,八次VRR查询10.5–22.0ms,刷新率查询约0.01–0.16ms。+- `python -X utf8 -B -I scripts/acceptance/fg-display-query.py`:真实4K30文件,VFG2X/4X、跟随显示器320Hz/VRR、暂停恢复、关闭重开通过;后台查询15次,媒体时钟继续,VFG实际生成提交,未借此替代真采集。+- `python -X utf8 -B -I scripts/acceptance/fg-capture-query.py --case <baseline-transport|fixed-transport|baseline-half|fixed-half> [--baseline] [--half] --seconds 40`:上述四个真采集用例均通过。+- `python -X utf8 -B -I scripts/acceptance/analyze-fg-capture-query.py`:生成按测量窗口的累计计数对照。探针、用例与分析脚本在源码,媒体/截图/配置/日志不入Git。++证据根目录`E:/项目/Veyra/reports/fg-scheduling-repair-20261024`;原始实时快照`archives/fg-scheduling-repair-20261024/live-0949.log`;构建`logs/codex-fg-scheduling-repair-20261024/build-20261024-095142`;四例日志`logs/fg-scheduling-repair-20261024/capture-*`,私有配置和截图`tests/fg-scheduling-repair-20261024/capture-*`。每次测试独立profile/log/TEMP,共用一份任务app,非可变输入才共享硬链接,未改供体DLL/模型,不产生多套实体运行库。++## 本地交付++`Veyra-2.1.0-fg1-NVIDIA-update.zip`为需已有完整2.1.0 NVIDIA底包的小更新层。关闭播放器,把文件解压覆盖原包根目录;包含NR手动比例及此前旋转/录制改动。更新不含DLL/模型/SDK/用户配置/日志,身份以`LOCAL_UPDATE.json`为准。源提交、ZIP/EXE SHA与逐文件核验见同任务`update-package.json`。原用户E:/App包未由Agent覆盖,未合main、未push/Release;Lecram暂停。本任务保留当前测试app与必要验收证据用于续测,没有复制整工程备份。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 8965d1dd..656c5b78 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -9945,3 +9945,15 @@ NR模型、EffectChain、PresetLibrary、旧PresetStore、Repair272、UI384布收尾:产品f743556,EXE SHA d43a5384be9e840912f260c1995c8c7d18f9a61176f4a9e45acfb3202df60289;Veyra-2.1.0-nr1-NVIDIA-update.zip 9886711字节,SHA14b3e0afcaf4fac569d31ea89737bc2027d40ae4f49248b344b05417c2ab3eaa。83文件CRC/逐SHA通过,79操作文件来自更新、其余1523操作输入与用户原包匹配,0额外运行库;177用户运行身份、4原日志、1739旧rot1清单文件均不变。旧供体manifest含日志及启动状态,非必要操作输入;新测试helper显式过滤这些可变文件,不共享其硬链接,更新包不含用户状态。产品代码未再改,后续只提交该测试工具/文档收尾。本轮E:/项目/Veyra/tests/nr-manual-scale-20261024/app、media在包验证后尝试原生绝对路径守卫删除,被自动审批blocked by policy拒绝,未提供详细原因;未执行、未用其他工具/移动绕过,两个目录及私有profile/证据保留。reports/.../test-cleanup.json记录受阻,FINAL.json区分已完成更新/诊断与未清理中间物。++## 2026-10-24 补帧调度追加修复与2K60 NV12真采集++用户从仅诊断追加为另开分支修复,后明确用采集卡2K60 NV12测试。97959cc干净树切codex/fg-scheduling-repair-20261024,存档checkpoint/pre-fg-scheduling-repair-20261024,不另复制工作树。计划/报告FG_SCHEDULING_REPAIR_{PLAN,REPORT}_2026-10-24.md。读取当前运行日志时发现Win32文件属性尚显示08:30但真实尾部持续更新,直接快照16:36之后会话,旧程序无需停止。读到NR关闭、输入60、VFG约3ms却反复准入elapsed11–17ms;源码定位processStart后每两秒同步queryVrr/刷新率。独立只读探针8次测得VRR10.5–22ms,刷新查询约0.01–0.16ms。++AsyncDisplayQuery单在途future,owner只wait_for(0)取完成结果,按代号丢弃旧窗口/监视器结果,不捕获presenter/GPU对象,reset不销毁future阻塞播放;异常限频重试,跟随显示器cap/VRR在结果到达后重应用。保留预算/期限/状态/原帧/历史,不改FG算法或运行库。保护六文件做Git换行规范化内容比较相同,首次原始比较CRLF/LF差异失败已记录,未伪装二进制相同。++build-recording-handoff.py --task codex-fg-scheduling-repair-20261024 --root 当前E工作树 --build-dir E:/项目/Veyra/build/claude-screen-recording-20261022 --reconfigure --label 2.1.0-fg1,-j2配置构建50.3秒通过;探针测试小改独立重编2.8秒。应用SHA322960200acbbe39ce5c7f783c4b3df429d9de46a706984bcb318dfadb241a6a。六CPU回归通过:Async10、scheduler127、realtime57、HDR状态、UI384layout、Repair272。Repair首次启动依赖PATH缺FFmpeg报0xC0000135,同源依赖PATH补齐后通过,保留initial receipt。真实文件4K30 VFG2X/4X、FollowDisplay/VRR、暂停、关闭重开通过。++用户原进程自行退出后,经明确授权在独立配置测KUHAIMI G50,NV12 subtype0x3231564E、ConnectDirect无converters、Run2560x1440/60均核对。NR/SR关闭、VFG2X Medium,四例各预热6秒+稳定40秒;同revision累计差计数:transport旧nr1 38.600秒/2316候选/10准入跳过/2生成过期,对照fg1相同38.600秒/2316候选/0/0;60->30旧39.166秒/1175候选/13/0,对照新39.100秒/1173/0/0。平均回调均60,邮箱覆盖0;旧准入采样最大13.188/16.729ms,新0.151/0.210ms,后台VRR仍最高14.602/14.366ms。所有新候选均实际评估与生成提交,没有通过关闭FG或删告警过关。截图在计数结束后抓,2560x1440非黑并已查看。四例均正常停止,没有争抢设备/写用户真实配置/碰PS5,供体运行字节不改。++证据reports/fg-scheduling-repair-20261024,日志logs/fg-scheduling-repair-20261024,原快照archives同任务;private tests同任务一份app+四profile,无新大媒体。构建保留当前同源目录。交付EXE/QML/i18n更新层2.1.0-fg1,需完整2.1.0 NVIDIA底包,含nr1手动比例/此前旋转录制。当前短测不证明其它后端/卡/重NR/HDR/长期/光学延迟,也不修真实GPU超预算。单Agent,无merge/push/Release,Lecram暂停。diff --git a/include/veyra/engine/AsyncDisplayQuery.h b/include/veyra/engine/AsyncDisplayQuery.hnew file mode 100644index 00000000..90c282c3--- /dev/null+++ b/include/veyra/engine/AsyncDisplayQuery.h@@ -0,0 +1,36 @@+#pragma once+#include <chrono>+#include <cstdint>+#include <future>+#include <optional>+#include <utility>++namespace veyra::engine {+// Owner-thread mailbox for infrequent display/driver queries. One query may+// be in flight; polling never waits. A window/graph replacement invalidates+// its result without destroying (and therefore joining) the running future.+// The worker must capture values only, never presenter/GPU resources. The+// future joins once at destruction, outside the per-frame playback path.+template<class Value> class AsyncDisplayQuery {+ struct Result {uint64_t generation;Value value;};+ std::future<Result> pending_;+ uint64_t generation_=0;+public:+ void invalidate(){++generation_;}+ bool pending()const{return pending_.valid();}+ template<class Query> bool request(Query query){+ if(pending())return false;+ const auto generation=generation_;+ pending_=std::async(std::launch::async,[generation,query=std::move(query)]()mutable{+ return Result{generation,query()};+ });+ return true;+ }+ std::optional<Value> poll(){+ if(!pending()||pending_.wait_for(std::chrono::seconds(0))!=std::future_status::ready)return {};+ auto result=pending_.get();+ if(result.generation!=generation_)return {};+ return std::move(result.value);+ }+};+}diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex f847db78..71357d5c 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -10,6 +10,7 @@#include "veyra/gfx/NvidiaVrr.h"#include "veyra/engine/PresentationSettings.h"#include "veyra/engine/PresentCapture.h"+#include "veyra/engine/AsyncDisplayQuery.h"#include <chrono>#include <array>#include <optional>@@ -77,6 +78,8 @@ public:// 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.double displayRefreshHz();// Variable refresh state of that monitor (NVIDIA only), re-read with it.gfx::VrrState displayVrr()const{return vrr_;}@@ -170,6 +173,8 @@ 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_{};uint32_t xessInputId_=0;struct XessWork {pipeline::FrameIdentity identity{};uint32_t id=0;};diff --git a/scripts/acceptance/analyze-fg-capture-query.py b/scripts/acceptance/analyze-fg-capture-query.pynew file mode 100644index 00000000..a2358274--- /dev/null+++ b/scripts/acceptance/analyze-fg-capture-query.py@@ -0,0 +1,30 @@+"""Analyse bounded physical-capture A/B intervals, not sampled log counts as totals."""+from pathlib import Path+import json,re,statistics,datetime+B=Path('E:/项目/Veyra');T='fg-scheduling-repair-20261024';O=B/'reports'/T+results=[]+for receipt in sorted(O.glob('capture-*.json')):+ r=json.loads(receipt.read_text('utf8'))+ if 'case' not in r:continue+ lines=(Path(r['log'])/'engine.log').read_text('utf8',errors='replace').splitlines()+ begin=next(l[:24] for l in lines if 'CAPTURE_FG_BEGIN ' in l);end=next(l[:24] for l in lines if 'CAPTURE_FG_END ' in l)+ window=[l for l in lines if begin<=l[:24]<=end]+ def events(tag):+ return [dict(re.findall(r'(\w+)=([^\s]+)',l),time=l[:24]) for l in window if '['+tag+']' in l]+ flow=events('frame-flow');timing=events('capture-timing');admit=events('live-fg-admission');query=events('display-query')+ assert len(flow)>20 and len(timing)>20 and r['passed'],r+ first,last=flow[0],flow[-1];assert first['revision']==last['revision'] and first['session']==last['session']+ keys=['captureReceived','mailboxOverwritten','sourceAccepted','sourceSkippedBeforeGraph','realSubmitted','fgCandidate','fgSkippedBeforeEval','fgEvaluated','fgWarmup','fgSkippedForReset','fgReadyValid','fgInvalid','realPresented','generatedPresented','generatedExpiredAfterEval','cancelledBeforePresent']+ delta={k:int(last[k])-int(first[k]) for k in keys}+ rejects=[d for d in admit if d.get('admitted')=='false']+ def values(items,k):return [float(d[k]) for d in items if k in d]+ fps=values(timing,'callbackFps');elapsed=values(admit,'elapsedMs')+ configured=any('[capture] configured 2560x1440 nominalFps=60.000 upstreamSubtype=0x3231564E' in l for l in lines)+ connected=any('native ConnectDirect subtype=0x3231564E hr=0x00000000 converters=0' in l for l in lines)+ running=any('[capture] Run hr=0x0 actual=2560x1440 nominalFps=60.000' in l for l in lines)+ assert configured and connected and running,'actual NV12 capture contract missing'+ data=dict(case=r['case'],baseline=r['baseline'],half=r['half'],exeSha256=r['exeSha256'],measurementBegin=begin,measurementEnd=end,counterBegin=first['time'],counterEnd=last['time'],delta=delta,rejectionRatio=delta['fgSkippedBeforeEval']/max(1,delta['fgCandidate']),callbackFpsMin=min(fps),callbackFpsMax=max(fps),callbackFpsMean=statistics.mean(fps),sampledAdmissionCount=len(admit),sampledRejections=len(rejects),sampledElapsedMaxMs=max(elapsed),sampledRejectedElapsedMs=values(rejects,'elapsedMs'),graphCpuP95MaxMs=max(values(timing,'processCpuP95Ms')),fgGpuP95MaxMs=max(values(timing,'gpuFgBatchP95Ms')),asyncQueries=len(query),asyncVrrMaxMs=max(values(query,'vrrMs'),default=0),actualFormat='2560x1440p60 NV12, direct connection, no converters',screenshots=[str(p) for p in Path(r['profile']).glob('*.png')])+ results.append(data)+ data['counterSeconds']=(datetime.datetime.fromisoformat(last['time'].replace('Z','+00:00'))-datetime.datetime.fromisoformat(first['time'].replace('Z','+00:00'))).total_seconds()+(O/'capture-comparison.json').write_text(json.dumps(results,ensure_ascii=False,indent=1),'utf8')+for r in results:print(json.dumps({k:r[k] for k in ['case','delta','callbackFpsMean','sampledElapsedMaxMs','asyncQueries','asyncVrrMaxMs']},ensure_ascii=False))diff --git a/scripts/acceptance/fg-capture-query.py b/scripts/acceptance/fg-capture-query.pynew file mode 100644index 00000000..c861c25f--- /dev/null+++ b/scripts/acceptance/fg-capture-query.py@@ -0,0 +1,29 @@+"""Authorized physical G50 1440p60 NV12 A/B, private profiles, one GPU owner."""+from pathlib import Path+import os,json,hashlib,subprocess,time,argparse+parser=argparse.ArgumentParser();parser.add_argument('--case',required=True);parser.add_argument('--baseline',action='store_true');parser.add_argument('--half',action='store_true');parser.add_argument('--seconds',type=int,default=40);a=parser.parse_args()+B=Path('E:/项目/Veyra');T='fg-scheduling-repair-20261024';R=Path(__file__).resolve().parents[2]+A=B/'tests'/T/'app';P=B/'tests'/T/('capture-'+a.case);L=B/'logs'/T/('capture-'+a.case);TMP=B/'tmp'/T/('capture-'+a.case);OUT=B/'reports'/T+assert A.exists() and not P.exists(),P+for p in [P,L,TMP,OUT]:p.mkdir(parents=True,exist_ok=True)+def replace(p,data):+ if p.exists():p.unlink()+ p.write_bytes(data)+def sha(p):+ with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()+exe=(B/'test-packages/nr-manual-scale-20261024/Veyra-2.1.0-nr1-NVIDIA-update/veyra_qml_ui.exe') if a.baseline else B/'build/claude-screen-recording-20261022/veyra_qml_ui.exe'+replace(A/'veyra_qml_ui.exe',exe.read_bytes())+(P/'qml-preferences.v1.json').write_text(json.dumps(dict(language='zh-CN',autoResume=False,prewarmEnhancement=False,screenshotDir=P.as_posix())),'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')+main=(R/'qml/Veyra/Main.qml').read_text('utf8');pos=main.rfind('}');cfg=dict(name=a.case,half=a.half,seconds=a.seconds)+loader='\nLoader { source: '+json.dumps(Path(__file__).with_suffix('.qml').as_uri())+'; onLoaded: item.config='+json.dumps(json.dumps(cfg))+' }\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; no device competition'+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','130000'],cwd=A,env=env,stdout=f,stderr=subprocess.STDOUT,timeout=150)+finally:replace(A/'qml/Veyra/Main.qml',(R/'qml/Veyra/Main.qml').read_bytes())+text=(L/'console.log').read_text('utf8',errors='replace');errors=[l for l in text.splitlines() if any(s in l for s in ['CAPTURE_FG_FAIL','[ERROR]','ReferenceError:','TypeError:','Binding loop detected'])]+passed=p.returncode==0 and 'CAPTURE_FG_PASS' in text and not errors+result=dict(case=a.case,baseline=a.baseline,half=a.half,seconds=a.seconds,exit=p.returncode,passed=passed,log=str(L),profile=str(P),exeSha256=sha(A/'veyra_qml_ui.exe'),errors=errors)+(OUT/('capture-'+a.case+'.json')).write_text(json.dumps(result,ensure_ascii=False,indent=1),'utf8');print(json.dumps(result,ensure_ascii=False),flush=True)+assert passed,text[-6000:]diff --git a/scripts/acceptance/fg-capture-query.qml b/scripts/acceptance/fg-capture-query.qmlnew file mode 100644index 00000000..7d29ac03--- /dev/null+++ b/scripts/acceptance/fg-capture-query.qml@@ -0,0 +1,52 @@+import QtQuick+Item {+ id: test+ property string config: "{}"+ readonly property var cfg: JSON.parse(config)+ property int phase: 0+ property int ticks: 0+ property int total: 0+ function check(ok,why){if(!ok)throw new Error(why)}+ function next(n){phase=n;ticks=0}+ function sample(mark){console.log("CAPTURE_FG_"+mark,JSON.stringify({caseName:cfg.name,half:cfg.half,format:veyra.captureFormatLabel,source:veyra.sourceSummary,fgActive:veyra.fgActive,backend:veyra.fgBackendName,submitFps:veyra.submitFps,inputFps:veyra.captureFps,dropped:veyra.captureDropped,status:veyra.runStatusDetail}))}+ Timer {id: timer;interval:250;repeat:true;running:test.config!=="{}"+ onTriggered:{try{+ ++test.ticks;if(++test.total>480)throw new Error("120 second deadline phase "+test.phase)+ if(test.phase===0){+ if(test.ticks<8)return+ root.page="pro";veyra.muted=true;veyra.nrEnabled=false;veyra.srEnabled=false;veyra.refreshCaptureDevices();next(1)+ }else if(test.phase===1){+ if(veyra.captureQueryBusy||test.ticks<4)return+ const device=veyra.captureDevices.find(x=>x.label.indexOf("KUHAIMI G50")>=0)+ check(!!device,"KUHAIMI G50 not present")+ veyra.captureDeviceId=device.id;next(2)+ }else if(test.phase===2){+ if(veyra.captureQueryBusy||test.ticks<4)return+ const format=veyra.captureFormats.find(x=>x.width===2560&&x.height===1440&&Math.abs(x.fps-60)<0.01&&x.pixel==="NV12"&&!x.interlaced&&!x.disabled)+ check(!!format,"exact 2560x1440p60 NV12 not advertised")+ veyra.captureFormatKey=format.id;veyra.captureAudioChoice=-1;veyra.captureBufferMode=0+ veyra.contentRate=test.cfg.half?5:0;veyra.outputRateMode=0;veyra.variableRefresh=false;veyra.displaySync=2+ check(veyra.addEffect("vfg-fg")>=0,"VFG stage")+ veyra.vfgQuality=1;veyra.fgMultiplier=2+ check(veyra.startCaptureSession(),"capture open refused: "+veyra.captureStatus)+ next(3)+ }else if(test.phase===3){+ if(!veyra.running||!veyra.fgActive||veyra.applying||test.ticks<24)return+ check(veyra.captureFormatLabel.indexOf("NV12")>=0,"selection changed pixel format")+ sample("BEGIN");next(4)+ }else if(test.phase===4){+ check(veyra.running&&veyra.fgActive,"capture or VFG stopped: "+veyra.statusText)+ if(test.ticks%4===0)sample("SAMPLE")+ if(test.ticks<test.cfg.seconds*4)return+ sample("END");veyra.takeScreenshot();next(5)+ }else if(test.phase===5){+ if(test.ticks<8)return+ veyra.stopPlayback();next(6)+ }else if(test.phase===6){+ if(test.ticks<8)return+ check(!veyra.running,"capture did not stop")+ console.log("CAPTURE_FG_PASS",test.cfg.name);timer.stop();Qt.quit()+ }+ }catch(e){console.error("CAPTURE_FG_FAIL",test.cfg.name,test.phase,e.message);veyra.stopPlayback();timer.stop();Qt.quit()}}+ }+}diff --git a/scripts/acceptance/fg-display-query.py b/scripts/acceptance/fg-display-query.pynew file mode 100644index 00000000..3d8a2780--- /dev/null+++ b/scripts/acceptance/fg-display-query.py@@ -0,0 +1,45 @@+"""Private real-VFG playback/async-display regression; no capture or real profile."""+from pathlib import Path+import os,json,hashlib,shutil,subprocess,time+B=Path('E:/项目/Veyra');T='fg-scheduling-repair-20261024';R=Path(__file__).resolve().parents[2]+D=B/'build/claude-screen-recording-20261022';A=B/'tests'/T/'app';P=B/'tests'/T/'profile';L=B/'logs'/T/'native';TMP=B/'tmp'/T/'native';OUT=B/'reports'/T+for p in [P,L,TMP,OUT]:p.mkdir(parents=True,exist_ok=True)+def sha(p):+ with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()+def replace(p,data):+ p.parent.mkdir(parents=True,exist_ok=True)+ if p.exists():p.unlink()+ p.write_bytes(data)+donor=B/'test-packages/codex-picture-rotation-20261023/Veyra-2.1.0-rot1-NVIDIA-win64-portable'+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']+media=B/'tests/nr-manual-scale-20261024/media/nr-4k30.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')+main=(R/'qml/Veyra/Main.qml').read_text('utf8');pos=main.rfind('}')+loader='\nLoader { source: '+json.dumps(Path(__file__).with_suffix('.qml').as_uri())+'; onLoaded: 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','80000'],cwd=A,env=env,stdout=f,stderr=subprocess.STDOUT,timeout=100)+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 ['FG_DISPLAY_FAIL','[ERROR]','ReferenceError:','TypeError:','Binding loop detected'])]+queries=[x for x in log.splitlines() if '[display-query]' in x]+passed=p.returncode==0 and 'FG_DISPLAY_PASS' in text and not errors and len(queries)>=3+result=dict(exit=p.returncode,passed=passed,log=str(L),exeSha256=sha(A/'veyra_qml_ui.exe'),displayQueries=queries,errors=errors,scope='actual 4K30 file VFG2X/4X, FollowDisplay/VRR, pause/resume, close/reopen; no capture device or photon measurement')+(OUT/'native.json').write_text(json.dumps(result,ensure_ascii=False,indent=1),'utf8');print(json.dumps(result,ensure_ascii=False),flush=True)+assert passed,text[-5000:]diff --git a/scripts/acceptance/fg-display-query.qml b/scripts/acceptance/fg-display-query.qmlnew file mode 100644index 00000000..3b2c857b--- /dev/null+++ b/scripts/acceptance/fg-display-query.qml@@ -0,0 +1,55 @@+// Loaded only into a private staging copy, never the user's running package.+import QtQuick+Item {+ id: test+ property string media: ""+ property int phase: 0+ property int ticks: 0+ property int total: 0+ property real beforePosition: 0+ function check(ok,why){if(!ok)throw new Error(why)}+ function next(n){phase=n;ticks=0;beforePosition=veyra.position}+ function active(){check(veyra.running&&veyra.fgActive&&veyra.fgBackendName==="vfg","VFG not active: "+veyra.statusText);check(veyra.position>beforePosition+1,"media clock stopped")}+ Timer {id: timer;interval: 250;repeat: true;running: test.media!==""+ onTriggered: {try {+ ++test.ticks;if(++test.total>280)throw new Error("70 second deadline phase "+test.phase)+ if(test.phase===0){+ if(test.ticks<8)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(1)+ }else if(test.phase===1){+ if(!veyra.running||!veyra.fgActive||veyra.applying||veyra.position<1)return+ next(2)+ }else if(test.phase===2){+ if(test.ticks<24||veyra.applying)return+ active();console.log("FG_DISPLAY_CASE","2X",veyra.submitFps,veyra.runStatusDetail)+ veyra.outputRateMode=1;veyra.variableRefresh=true;next(3)+ }else if(test.phase===3){+ if(test.ticks<20||veyra.applying)return+ active();console.log("FG_DISPLAY_CASE","follow-display-VRR",veyra.presentationStatus)+ veyra.fgMultiplier=4;next(4)+ }else if(test.phase===4){+ if(test.ticks<20||veyra.applying)return+ active();check(veyra.fgMultiplier===4,"4X rollback")+ console.log("FG_DISPLAY_CASE","4X",veyra.submitFps,veyra.runStatusDetail)+ veyra.togglePlayPause();next(5)+ }else if(test.phase===5){+ if(test.ticks<4)return+ check(veyra.paused,"pause")+ veyra.togglePlayPause();next(6)+ }else if(test.phase===6){+ if(test.ticks<16||veyra.applying)return+ active();veyra.stopPlayback();next(7)+ }else if(test.phase===7){+ if(test.ticks<8)return+ check(!veyra.running,"close drains")+ veyra.fgMultiplier=2;veyra.openPath(test.media);next(8)+ }else if(test.phase===8){+ if(test.ticks<24||veyra.applying||!veyra.fgActive)return+ active();console.log("FG_DISPLAY_PASS",veyra.submitFps,veyra.runStatusDetail)+ timer.stop();Qt.quit()+ }+ }catch(e){console.error("FG_DISPLAY_FAIL",test.phase,e.message);timer.stop();Qt.quit()}}+ }+}diff --git a/scripts/acceptance/package-fg-scheduling.py b/scripts/acceptance/package-fg-scheduling.pynew file mode 100644index 00000000..da778291--- /dev/null+++ b/scripts/acceptance/package-fg-scheduling.py@@ -0,0 +1,49 @@+"""Seal verified local scheduling update; no runtimes, logs or user configuration."""+from pathlib import Path+import json,hashlib,subprocess,zipfile,shutil+B=Path('E:/项目/Veyra');T='fg-scheduling-repair-20261024';R=Path(__file__).resolve().parents[2];O=B/'reports'/T+D=B/'build/claude-screen-recording-20261022';P=B/'test-packages'/T/'Veyra-2.1.0-fg1-NVIDIA-update'+assert not subprocess.check_output(['git','-C',str(R),'status','--porcelain']).strip(),'commit reviewed source first'+head=subprocess.check_output(['git','-C',str(R),'rev-parse','HEAD'],text=True).strip()+assert json.loads((O/'native.json').read_text('utf8'))['passed']+comparisons=json.loads((O/'capture-comparison.json').read_text('utf8'));assert len(comparisons)==4 and all(x['actualFormat'].startswith('2560x1440p60 NV12') for x in comparisons)+assert all(x['exit']==0 for x in json.loads((O/'contracts.json').read_text('utf8')))+assert not P.exists();P.mkdir(parents=True)+def sha(p):+ with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()+def copy(src,rel):+ dst=P/rel;dst.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(src,dst)+copy(D/'veyra_qml_ui.exe','veyra_qml_ui.exe')+assert sha(P/'veyra_qml_ui.exe')==json.loads((O/'native.json').read_text('utf8'))['exeSha256']+for folder in ['qml','i18n']:+ for p in (R/folder).rglob('*'):+ if p.is_file():copy(p,Path(folder)/p.relative_to(R/folder))+for name in ['FG_SCHEDULING_REPAIR_PLAN_2026-10-24.md','FG_SCHEDULING_REPAIR_REPORT_2026-10-24.md','NR_MANUAL_SCALE_REPORT_2026-10-24.md']:+ copy(R/'docs'/name,Path('docs')/name)+for name in ['LICENSE','THIRD_PARTY_NOTICES.md']:copy(R/name,name)+note='''# Veyra 2.1.0-fg1 NVIDIA 本地测试更新++需要已有完整2.1.0 NVIDIA便携包。先关闭播放器,将本目录文件复制到原包根目录(veyra_qml_ui.exe所在目录),覆盖同名文件,再启动。+本更新只含程序、QML、翻译和说明,不含DLL/模型/SDK/日志/用户配置。原package-manifest描述完整底包;本更新的程序/UI身份以LOCAL_UPDATE.json为准。++- 将显示器刷新率及NVIDIA G-SYNC/VRR状态查询移到后台,避免每两秒同步驱动查询使当前采集帧错过补帧期限。播放线程只取完成结果。+- 保留原补帧预算、期限、跳帧及告警判定,不积压帧,不保证负载真正超预算时仍能补帧。+- 同时保留nr1新增的每层NR手动25%–100%内部比例滑条,以及此前旋转/录制修复;Lecram仍暂停。+- 已在本机KUHAIMI G50真采集2560x1440p60 NV12、NR/SR关闭、VFG2X下做旧nr1与fg1对照,含原60和60->30两组;详细计数见随包修复报告。+- 已验证4K30文件VFG2X/4X、跟随显示器/VRR、暂停恢复、关闭重开和针对性CPU回归。其它采集卡/其它FG后端/重NR负载/HDR/长期与光学延迟不由本次短测证明。++版本标识2.1.0-fg1,PE数值版本2.1.0.0。本地隔离分支交付,未合main、未push或公开发布。+'''+(P/'README-FG1.zh-CN.md').write_text(note,'utf8')+files=[dict(path=p.relative_to(P).as_posix(),bytes=p.stat().st_size,sha256=sha(p)) for p in sorted(P.rglob('*')) if p.is_file()]+assert not any(Path(x['path']).suffix.lower() in ['.dll','.onnx','.tflite','.lib','.pdb','.hsaco','.dxil','.log'] for x in files)+(P/'LOCAL_UPDATE.json').write_text(json.dumps(dict(version='2.1.0-fg1-local-update',base='Complete 2.1.0 NVIDIA portable package',sourceCommit=head,sourceWorktree=str(R),localOnly=True,releaseReady=False,containsRuntime=False,files=files),ensure_ascii=False,indent=1),'utf8')+zpath=P.parent/(P.name+'.zip');assert not zpath.exists()+with zipfile.ZipFile(zpath,'x',zipfile.ZIP_DEFLATED,compresslevel=6) as z:+ for p in P.rglob('*'):+ if p.is_file():z.write(p,p.relative_to(P).as_posix())+with zipfile.ZipFile(zpath) as z:+ assert z.testzip() is None+ for e in files:assert hashlib.sha256(z.read(e['path'])).hexdigest()==e['sha256']+result=dict(sourceCommit=head,zip=str(zpath),bytes=zpath.stat().st_size,sha256=sha(zpath),exeSha256=sha(P/'veyra_qml_ui.exe'),manifestFiles=len(files),runtimeFiles=0)+(O/'update-package.json').write_text(json.dumps(result,ensure_ascii=False,indent=1),'utf8');print(json.dumps(result,ensure_ascii=False),flush=True)diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 45b07386..25d3e9a6 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -1309,14 +1309,18 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// source while the previous one is still on the GPU, as before.static const bool xessPresentAfterReady=GetEnvironmentVariableW(L"VEYRA_TEST_XESS_PRESENT_AFTER_READY",nullptr,0)>0;static const bool xessStackedReads=GetEnvironmentVariableW(L"VEYRA_TEST_XESS_STACKED_READS",nullptr,0)>0;- uint64_t pacingRevision=0,presenterGeneration=0;+ uint64_t pacingRevision=0,presenterGeneration=0;double pacingRefreshHz=0;auto applyPresentation=[&]{PresentationSettings requested;uint64_t revision;{std::lock_guard lock(mutex_);requested=presentation_;revision=presentationRevision_;}+ // Poll completed display/VRR queries before comparing policy.+ // 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.const bool vrrChanged=presenter.vrrSync()!=VideoPresenter::vrrSyncWanted(requested,presenter.displayVrr());- if(revision==pacingRevision&&presenterGeneration==presenter.generation()&&!vrrChanged){+ if(revision==pacingRevision&&presenterGeneration==presenter.generation()&&!vrrChanged&&!capRefreshChanged){// Reflex dropped out at runtime: the queue-depth part of the// low-latency setting stays, so only the status line changes.if(presentationEffective.enabled&&!presenter.reflexActive()&&presenter.reflexDisablePending()){@@ -1333,7 +1337,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sstd::wstring message;presentationEffective=presenter.configurePresentation(ctx,requested,options.fg,message);presentationPaced=presenter.pacingActive()&&!legacyVsyncQueue;- pacingRevision=revision;presenterGeneration=presenter.generation();cadence.reset();+ pacingRevision=revision;presenterGeneration=presenter.generation();pacingRefreshHz=refreshHz;cadence.reset();{std::lock_guard lock(mutex_);snapshot_.presentationEffective=presentationEffective;snapshot_.presentationRevision=revision;snapshot_.presentationStatus=message;snapshot_.presentationProviderOwned=presenter.providerOwnedPresentation();}veyra::log::info("pacing",std::format("revision={} requested={}/{}/{} effective={}/{}/{} displayQueuePaced={} variableRefresh={} vrrLevel={} vrrSync={}",revision,requested.enabled,unsigned(requested.mode),unsigned(requested.display),presentationEffective.enabled,unsigned(presentationEffective.mode),unsigned(presentationEffective.display),presentationPaced,requested.variableRefresh,gfx::vrrLevel(presenter.displayVrr()),presenter.vrrSync()));};diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 33a1c319..9a31669e 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -31,7 +31,7 @@ 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;refreshMonitor_=nullptr;refreshHz_=0;refreshQuery_={};vrr_={};refreshQueried_=false;vrrSync_=false;+ viewWidth_=viewHeight_=0;bufferMonitor_=nullptr;monitorWidth_=monitorHeight_=0;displayQuery_.invalidate();refreshMonitor_=nullptr;refreshHz_=0;refreshQuery_={};vrr_={};refreshQueried_=false;vrrSync_=false;++generation_;Status st=Status::Ok;// Keep one presentation queue for the native chain's lifetime. A later@@ -489,7 +489,7 @@ void VideoPresenter::publishLiveCoverage(const HdrCurveSettings& curve,pipeline:void VideoPresenter::close(){metadataSent_=false;metadataDirty_=false;lastMetadata_={};sourceMetadata_={};metadataAttempt_={};hdrPeakMonitor_=nullptr;hdrPeakInfo_={};hdrPeakQuery_={};- refreshMonitor_=nullptr;refreshHz_=0;refreshQuery_={};vrr_={};refreshQueried_=false;vrrSync_=false;+ displayQuery_.invalidate();refreshMonitor_=nullptr;refreshHz_=0;refreshQuery_={};vrr_={};refreshQueried_=false;vrrSync_=false;retainedFrame_.reset();xessInputId_=0;xessWork_={};xessWorkPosition_=0;reflex_.close();reflexFrame_=0;@@ -505,13 +505,42 @@ double VideoPresenter::displayRefreshHz(){if(!window_)return 0;const auto now=std::chrono::steady_clock::now();const auto monitor=MonitorFromWindow(window_,MONITOR_DEFAULTTONEAREST);- if(monitor!=refreshMonitor_||now-refreshQuery_>=std::chrono::seconds(2)){- const double hz=gfx::PresentSink::displayRefreshFps(window_);- if(refreshMonitor_&&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;refreshMonitor_=monitor;refreshQuery_=now;sink_.setDisplayRefreshHz(hz);- const auto vrr=gfx::queryVrr(window_);+ 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()));}return refreshHz_;}@@ -541,7 +570,7 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceConteconst bool reflexDisabled=reflex_.disable();reflexFrame_=0;const bool followDisplay=requested.outputRate==OutputRateMode::FollowDisplay;if(followDisplay){- const double hz=gfx::PresentSink::displayRefreshFps(sink_.hwnd());+ const double hz=displayRefreshHz();if(hz>=1.0&&std::isfinite(hz)){requested.outputRate=OutputRateMode::Custom;requested.customFps=hz;}else requested.outputRate=OutputRateMode::Off;}diff --git a/tests/unit/AsyncDisplayQueryTests.cpp b/tests/unit/AsyncDisplayQueryTests.cppnew file mode 100644index 00000000..99b229d9--- /dev/null+++ b/tests/unit/AsyncDisplayQueryTests.cpp@@ -0,0 +1,55 @@+#include "veyra/engine/AsyncDisplayQuery.h"+#include "veyra/gfx/PresentSink.h"+#include "veyra/gfx/NvidiaVrr.h"+#include <future>+#include <iostream>+#include <stdexcept>+#include <thread>++int wmain(int argc,wchar_t** argv){+ using Clock=std::chrono::steady_clock;+ using veyra::engine::AsyncDisplayQuery;+ // Read-only field probe: no device/queue/swapchain/capture initialization.+ if(argc==3&&std::wstring(argv[1])==L"--probe"){+ const auto requested=std::stoull(argv[2]);+ const auto window=requested?reinterpret_cast<HWND>(requested):GetDesktopWindow();+ if(!IsWindow(window))return 2;+ for(unsigned i=0;i<8;++i){+ const auto start=Clock::now();+ const auto hz=veyra::gfx::PresentSink::displayRefreshFps(window);+ const auto refresh=Clock::now();+ const auto vrr=veyra::gfx::queryVrr(window);+ const auto finish=Clock::now();+ std::cout<<"DISPLAY_QUERY_PROBE refreshMs="<<std::chrono::duration<double,std::milli>(refresh-start).count()+ <<" vrrMs="<<std::chrono::duration<double,std::milli>(finish-refresh).count()<<" hz="<<hz<<" vrrLevel="<<veyra::gfx::vrrLevel(vrr)<<std::endl;+ std::this_thread::sleep_for(std::chrono::milliseconds(50));+ }+ return 0;+ }+ int failures=0;auto check=[&](bool ok,const char* why){std::cout<<(ok?"PASS ":"FAIL ")<<why<<std::endl;failures+=!ok;};+ AsyncDisplayQuery<int> query;+ check(!query.poll()&&!query.pending(),"empty cache has no fabricated display state");+ std::promise<void> entered,release;+ auto wait=release.get_future().share();const auto owner=std::this_thread::get_id();+ check(query.request([&]{entered.set_value();wait.wait();return std::this_thread::get_id()!=owner?320:-1;}),"one background query accepted");+ entered.get_future().wait();+ bool nonblocking=true;+ for(unsigned i=0;i<1000;++i)nonblocking&=!query.poll()&&!query.request([]{return -2;});+ check(nonblocking&&query.pending(),"blocked driver query cannot block owner polls or enqueue a second worker");+ release.set_value();+ const auto take=[&]{std::optional<int> result;const auto until=Clock::now()+std::chrono::seconds(2);while(query.pending()&&Clock::now()<until){result=query.poll();if(result)break;std::this_thread::yield();}return result;};+ check(take()==320&&!query.pending(),"completed result published once from another thread");+ check(!query.poll(),"a result cannot be consumed twice");+ std::promise<void> staleEntered,staleRelease;auto staleWait=staleRelease.get_future().share();+ query.request([&]{staleEntered.set_value();staleWait.wait();return 60;});staleEntered.get_future().wait();+ query.invalidate();query.invalidate();+ check(!query.poll()&&!query.request([]{return -3;}),"close/reopen invalidates without joining or spawning more work");+ staleRelease.set_value();check(!take()&&!query.pending(),"old monitor/window generation never updates replacement");+ query.request([]{return 144;});check(take()==144,"fresh monitor query recovers after discarded result");+ query.request([]()->int{throw std::runtime_error("simulated driver query failure");});+ 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");+ std::cout<<"ASYNC_DISPLAY_QUERY failures="<<failures<<std::endl;+ return failures?1:0;+}