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++
perf: retain paused idle after GPU utilization fell from 2.237 to 0.011 percent
Veyra Goal Agentc593679694b3
diff --git a/CMakeLists.txt b/CMakeLists.txtindex e6d8270f..68a34c04 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1026,6 +1026,10 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_compile_features(veyra_nr_paused_residual_experiment PRIVATE cxx_std_20)target_compile_options(veyra_nr_paused_residual_experiment PRIVATE /utf-8)target_link_libraries(veyra_nr_paused_residual_experiment PRIVATE veyra_engine bcrypt)+ add_executable(veyra_paused_present_experiment tests/perf/PausedPresentExperiment.cpp)+ target_compile_features(veyra_paused_present_experiment PRIVATE cxx_std_20)+ target_compile_options(veyra_paused_present_experiment PRIVATE /utf-8)+ target_link_libraries(veyra_paused_present_experiment PRIVATE veyra_engine)add_executable(veyra_nr_core_cache_contract_tests tests/perf/NrCoreCacheContractTests.cpp)target_compile_features(veyra_nr_core_cache_contract_tests PRIVATE cxx_std_20)target_compile_options(veyra_nr_core_cache_contract_tests PRIVATE /utf-8)diff --git a/apps/veyra-qml/main.cpp b/apps/veyra-qml/main.cppindex dd1948e6..4f6462ff 100644--- a/apps/veyra-qml/main.cpp+++ b/apps/veyra-qml/main.cpp@@ -665,6 +665,8 @@ static int runApplication(int argc, char** argv, QString& restartProgram, QStrinconst QStringList args = QCoreApplication::arguments();QString openPath;QVariantMap testOptions;+ if(qEnvironmentVariableIsSet("VEYRA_TEST_DISABLE_PAUSED_UI_IDLE"))+ testOptions.insert(QStringLiteral("disablePausedUiIdle"),true);QSize testSize;// --exit-after: see the switch table. 0 means "run until closed".int exitAfterMs = 0;diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.mdindex 8036280c..d28f2bc9 100644--- a/docs/CURRENT_STATUS.md+++ b/docs/CURRENT_STATUS.md@@ -4,7 +4,7 @@公开版本:2.0.3(main `354b1c6`,产品源码 `f82f649`);AMD/NVIDIA分包、AMD NR宿主、VFG全档、Xbox/导出码率/背景/极简缺口修复已发布。当前优化从本地修复tip `8cdc612` 开出 `codex/perf-nr-20261004`,工作树 `E:/项目/Veyra/worktrees/perf-nr-20261004`;继承已验RTSS误提示/重启循环、自定义倍速/字幕/UI热路径/专业布局和全屏恢复。它们尚未进入远端2.0.3,不能将本地候选称为公开版本。-本轮按 `PERF_PLAN_NR_2026-10-03.md` / `PERF_EXECUTION_NR_2026-10-04.md`:先对齐文档/归档,再全新构建当前基线、逐节点A/B/B-off复测和存档,负优化回退。原方案中RTSS/启动优化“未合并”和2.0.1基线为历史状态,不再执行重复合并。M1五设置各三轮优化前基线已封存;2a核心复用暖创建减少约65–76%,三轮画面完全一致,保留待R0。重复帧整链复用/节奏盲预测均有画面反例,未加入产品;E1/E2/E3实验分别记录边界。5c窄范围候选及其余节点继续,不能称全方案完成。下面早期阶段条目均按各自日期理解。+本轮按 `PERF_PLAN_NR_2026-10-03.md` / `PERF_EXECUTION_NR_2026-10-04.md`:先对齐文档/归档,再全新构建当前基线、逐节点A/B/B-off复测和存档,负优化回退。原方案中RTSS/启动优化“未合并”和2.0.1基线为历史状态,不再执行重复合并。M1五设置各三轮优化前基线已封存;2a核心复用暖创建减少约65–76%,三轮画面完全一致,保留待R0。重复帧整链复用/节奏盲预测均有画面反例,未加入产品;E1/E2/E3实验分别记录边界。5c已保留:单NR暂停残差编辑减少89.74%,自身暂停GPU三轮约2.237→0.011%;四FG暂停/恢复/seek通过,导出等最终回归仍待。其余节点继续,不能称全方案完成。下面早期阶段条目均按各自日期理解。仍未解决/未验:严重后台掉帧根因;真实Xbox有声/长期稳定;AMD RX9000推理/画质;RTX30/40实际NR/FG;用户616.92;物理显示节奏/端到端延迟。HDR/Dolby PR13/14用户暂缓,不纳入此次优化。不merge/push/Release/关机,不改用户驱动、配置或原桌面工作树。diff --git a/docs/PERF_5C_PAUSED_NR_2026-10-04.md b/docs/PERF_5C_PAUSED_NR_2026-10-04.mdindex 2f9397cf..a53045ed 100644--- a/docs/PERF_5C_PAUSED_NR_2026-10-04.md+++ b/docs/PERF_5C_PAUSED_NR_2026-10-04.md@@ -27,6 +27,22 @@ v1/v2未产生收益:测试单层使用legacy平铺参数但保留数组,残`B5c-paused-ui-v4`三配置均通过。静止暂停30.0–30.5秒,真实NR计数不增长、媒体位置不漂;20次残差请求内第10次换模型,单NR计数162→164并记录19次缓存复用,恢复播放164→228,暂停跳转2秒后230。SR组合155→176、抗闪烁161→182,缓存命中均0,维持完整处理。实际GPU解码、公共Bridge、独立profile、无桌面自动点击。-初始真实UI v3与v4未采集进程级GPU计数;整卡nvidia-smi暂停读数14–19%不能归因于本进程。新增只读取测试PID的Windows PDH GPU Engine计数器后补做A/B/B-off。暂停NR空闲与界面/呈现GPU占用分别记录,不据NR计数0宣称整个软件GPU占用0。此节点缓存有收益,最终保留及暂停占用结论在补测后记录;R0全产品回归仍待完成。+初始真实UI v3与v4未采集进程级GPU计数;整卡nvidia-smi暂停读数14–19%不能归因于本进程。新增只读取测试PID的Windows PDH GPU Engine计数器后补做A/B/B-off。暂停NR空闲与界面/呈现GPU占用分别记录,不据NR计数0宣称整个软件GPU占用0。补测细节见下节;R0全产品回归仍待完成。计数器依据:[微软PdhGetFormattedCounterArrayW](https://learn.microsoft.com/en-us/windows/win32/api/pdh/nf-pdh-pdhgetformattedcounterarrayw)、[PDH_FMT_COUNTERVALUE](https://learn.microsoft.com/en-us/windows/win32/api/pdh/ns-pdh-pdh_fmt_countervalue)。读取结果只保留本轮测试PID实例,缺失计数器报告unavailable,不用0代替未测。++## 呈现与界面空闲补测++仅靠暂停NR不求值,自身GPU仍约2.3%,不能标验收通过。定位到两条实际开销:Engine每50ms重新Present相同输出;专业页性能球每秒数据变化触发600ms Canvas动画。暂停呈现现在按成功生产者fence、帧身份、slot、view、对比模式/分割、实际client与buffer尺寸、显示/隐藏、显示器判断保留;互动拖动/DPI与尚未落实resize不能命中,设备检查/失败缓存失效保持。仅明确暂停调用启用;普通播放、导出没有去重。暂停性能球仍每秒更新数值,取消数值动画,正常播放保持。++`nr-present.py B5c B5c-present-v1`:真实产品Graph、VideoPresenter及本轮拥有的HWND,启用/关闭各三轮。300次相同暂停调用时实际Present分别1/301次;zoom、compare/split、resize、NR残差生产者变更、隐藏/恢复各迫使正确刷新。每轮八张完整RGBA8图像、对应启用/关闭共48张,全部SHA一致,debug错误0、设备正常。此项不是仅检查函数返回。++真实Qt `B5c-paused-ui-v6` 与同EXE回退 `B5c-paused-ui-v6-off`:单NR、NR+DLSS SR、抗闪烁各一次,每次30秒暂停、稳定区24个PID专属PDH样本、20次含模型变更的残差编辑、恢复播放及暂停跳转全部通过。单NR/超分/抗闪烁进程最大引擎占用的稳定样本中位数:B为0.010828/0.011633/0.010752%,B-off为2.287588/2.318904/2.250025%;优化前A旧EXE+旧QML单NR为2.360637%。这些是进程GPU引擎利用率,不是整卡利用率、视频帧率或实屏刷新率。单NR三轮数据如下。++取消重复Present但保留性能球动画的中间版本v5仍2.261%,没有把它算作完整暂停优化。v6单NR Qt真实frameSwapped每10秒约8–10次,A约1356–1734次;此计数只描述Qt渲染窗口。GPU解码、publicBridge、独立profile,没有桌面自动点击。`B5c-paused-ui-v6-fg` 的实际DLSS/XeSS/FSR3/VFG 2X四组30秒暂停、恢复、跳转均通过,未把后端初始化回退算通过;NR残差复用在这些组合保持关闭。++同EXE关闭开关:`VEYRA_TEST_DISABLE_PAUSED_PRESENT_REUSE`、`VEYRA_TEST_DISABLE_PAUSED_UI_IDLE`、`VEYRA_TEST_DISABLE_PAUSED_NR_RESIDUAL_REUSE`。产品EXE bf4952347424f500df45a29ab3f7289742e4ecae188ac66b71805b9743978568;原生呈现实验EXE 0184961e015605a919bf1cd6cfb4641d6f5db56ed6ddd49723afe57527478b75。原始证据均在 `E:/项目/Veyra/logs/perf-nr-20261004/` 对应标签目录。++单NR最终三轮(每轮24个稳定样本)GPU最大引擎利用率的中位数再取三轮中位数:A 2.237185%(2.236872–2.360637),B 0.010999%(0.010828–0.011035),同EXE B-off 2.237174%(2.193295–2.287588)。B约为A的0.492%,下降99.51%;这是暂停软件自身GPU引擎占用的变化,不是GPU整卡空闲保证。九轮暂停/残差/模型/恢复/跳转全通过。A为本节点开工前已保留2a的B2a构建及旧QML,EXE b92c47b64a36036a9c708fc55b018512f90c7945606236c7f5aca4b5f213679b;最初全项目A便携包继续封存,未用新QML改写基线。JSON `B5c-paused-ui-v6-three-run-comparison.json`。四个实际FG后端暂停稳定区GPU样本中位数0.009983–0.010625%,各24样本;该四组各一轮,不扩大为三轮长稳。++结论:暂停残差缓存与呈现/性能球空闲优化保留;首次暂停残差刷新和模型变更仍完整NR求值,随后纯残差编辑不求值。只对已测窄范围缓存NR,通用暂停呈现适用于已回归后端。R0仍需验证长期播放、导出及最终完整包,不宣称整个优化方案完成。diff --git a/docs/PERF_EXECUTION_NR_2026-10-04.md b/docs/PERF_EXECUTION_NR_2026-10-04.mdindex d278fb1d..9f8c4b12 100644--- a/docs/PERF_EXECUTION_NR_2026-10-04.md+++ b/docs/PERF_EXECUTION_NR_2026-10-04.md@@ -42,7 +42,7 @@| 5b | 文件/导出跨帧并行 | pending | 保留源帧/PTS/flow依赖,不扩大实时延迟 || 4a | 多NR整链低分辨率调度 | pending | 保留每层残差参数;先测同尺寸与一致性 || 4b | 先粗后细组合 | pending | 核对现有逐层尺寸;不新增强制预设 |-| 5c | 暂停不重跑/残差重合成 | in-progress | 残差缓存v4三轮A/B/B-off、真实Qt通过,7.461→0.766ms约89.74%;普通暂停自身GPU仍约2.5%,重复呈现继续排查;PERF_5C_PAUSED_NR |+| 5c | 暂停不重跑/残差重合成 | retained-pending-R0 | 残差7.461→0.766ms约89.74%;真实Qt自身暂停GPU三轮2.237→0.011%(off2.237%);48完整呈现图像一致、四FG暂停/恢复/seek通过;PERF_5C_PAUSED_NR || UI | 性能设置及状态 | pending | 只暴露保留实现,统一持久化/能力/翻译 || R0 | 全产品回归与最终候选 | pending | 合同/Xbox/Qt/字幕/导出/兼容及源码存档 |diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex c9c62a7e..90cc053e 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -8189,3 +8189,12 @@ release. 5090 live acceptance, 15-second hitch and user flicker remain unresolve- nr-paused-ui.py B5c B5c-paused-ui-v4 与 B5c-off B5c-paused-ui-v4-off 各三组真实Qt通过,30秒NR计数和位置不变,20残差编辑中途换模型、恢复播放、暂停seek2秒成功。B单NR19次复用/NR增2,Boff无复用/NR增20;SR与抗闪烁0复用。Windows PDH GPU Engine只记录本轮测试PID,Boff单NR24样本中位2.481%/max2.546%,所以普通暂停整软件GPU接近0门槛未通过,继续优化重复呈现;nvidia-smi整卡14–19%不能当进程GPU。- 原始日志/结果/完整截图:E:/项目/Veyra/logs/perf-nr-20261004/{A5c-paused-v1,B5c-paused-v4,B5c-paused-v4-off,B5c-paused-ui-v4,B5c-paused-ui-v4-off}*;comparison JSON同目录。软件节点仅残差缓存定向通过,5c整体及R0未完成。- 增加测试/构建串行guard,拒绝其他本轮GPU测试进程,不杀用户程序;目标保持active,不合并/推送/发布。+++## 2026-10-04 PERF 5c 暂停呈现/Qt动画保留++本节点前存档74a6216/checkpoint/perf-nr-5c-present-before-20261004。build-paused-present-v1、build-paused-present-fixture-v1、build-paused-present-ui-v2均构建exit0,输出在E:/项目/Veyra/build/perf-nr-20261004/B5c,日志同任务logs。候选按生产者fence/帧/view/尺寸/visibility/monitor保留成功暂停flip buffer,保留resize/DPI/device检查;停止暂停性能球每秒600ms动画,数值仍更新。普通播放/导出不去重。++命令:py -3.11 -B scripts/perf/nr-present.py B5c B5c-present-v1:开/关各三轮,300次同帧实际Present1/301,48完整图像SHA一致,debug0/device正常。py -3.11 -B scripts/perf/nr-paused-ui.py B5c B5c-paused-ui-v6 及 B5c-off ...-off:NR/SR/temporal30秒空闲、20次编辑含模型变更、恢复播放、暂停seek全通过;四实际DLSS/XeSS/FSR3/VFG 2X组...-v6-fg也全通过。单NR又跑r2/r3 A(B2a旧QML)/B/B-off,全九轮通过。过程各子进程≤299秒、无桌面点击,不关闭用户应用。++数据:三轮单NR自身PDH最大引擎占用样本中位数再取三轮中位数A2.237185%(2.236872–2.360637)、B0.010999%(0.010828–0.011035)、off2.237174%(2.193295–2.287588),每轮24样本;下降99.51%。此为进程引擎利用率,不是整卡/实屏刷新率。中间v5仅去重复Present仍2.261%,不算完整通过。残差native三轮10800全输出SHA与89.74%收益沿用74a已归档证据,详见PERF_5C_PAUSED_NR。最终UI EXE bf4952347424f500df45a29ab3f7289742e4ecae188ac66b71805b9743978568。保留5c,R0及余节点继续;无merge/push/Release。diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex eb5b35b1..b9fde910 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -8,6 +8,7 @@#include "veyra/engine/PresentationSettings.h"#include <chrono>#include <array>+#include <optional>namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }namespace veyra::pipeline { class EnhanceGraph; }namespace veyra::sink { struct RgbaImage; }@@ -19,7 +20,7 @@ public:// source (file playback). Retained for diagnostics; XeLL low latency must// stay enabled or the provider refuses generation (result -15).bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&, bool captureCompatible=false, bool mediaClockPaced=false);- bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,bool referencesValid=true,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={},int64_t sourcePts100ns=-1);+ bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,bool referencesValid=true,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={},int64_t sourcePts100ns=-1,bool retainUnchanged=false);void close();// Present-sink providers (XeSS) block inside Present while pacing// their generated frames. A helper-thread Present was tried on@@ -83,6 +84,18 @@ private:Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> rtvs_;unsigned inc_=0;unsigned lastBuffer_=0;bool hasPresented_=false;+ struct RetainedFrame {+ ID3D12Fence* producer=nullptr;+ uint64_t fence=0;+ unsigned slot=0,width=0,height=0;+ bool generated=false,referencesValid=false,baseReference=false,visible=false;+ int comparison=0;float split=.5f;+ PreviewView view{};+ pipeline::FrameIdentity identity{};+ HMONITOR monitor=nullptr;+ bool operator==(const RetainedFrame&)const=default;+ };+ std::optional<RetainedFrame> retainedFrame_;HWND window_=nullptr;std::chrono::steady_clock::time_point lastResize_{};unsigned viewWidth_=0,viewHeight_=0;diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex 8f4f5700..9314a492 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -179,7 +179,9 @@ VPage {property real shown: known ? Math.min(1, Math.max(0, fraction)) : 0// Live data changes every second; animating it behind another page redrew the// window continuously (see VDot.qml), so only while shown.- Behavior on shown { enabled: orb.visible; NumberAnimation { duration: Theme.d(600); easing.bezierCurve: Theme.springSoft } }+ // Paused telemetry still updates, but it does not need a 600 ms canvas+ // animation every second. Keep live playback and user edits responsive.+ Behavior on shown { enabled: orb.visible && (!veyra.paused || (typeof vyTest !== "undefined" && vyTest.disablePausedUiIdle === true)); NumberAnimation { duration: Theme.d(600); easing.bezierCurve: Theme.springSoft } }onShownChanged: ring.requestPaint()onToneChanged: ring.requestPaint()Canvas {diff --git a/scripts/perf/nr-paused-ui.py b/scripts/perf/nr-paused-ui.pyindex 7f10a85c..24e0a4aa 100644--- a/scripts/perf/nr-paused-ui.py+++ b/scripts/perf/nr-paused-ui.py@@ -17,13 +17,14 @@ variant,label=sys.argv[1:3];groups=sys.argv[3:] or ['nr','srnr','temporal']app=BASE/'tests'/TASK/(label+'-app');assert not app.exists()shutil.copytree(BASE/'test-packages'/TASK/'Veyra-2.0.3-perf-baseline-A-NVIDIA-win64-portable',app,copy_function=matrix.copy_dependency)shutil.copy2(BASE/'build'/TASK/variant.removesuffix('-off')/'veyra_qml_ui.exe',app/'veyra_qml_ui.exe')+if variant.removesuffix('-off')=='B5c':shutil.copytree(ROOT/'qml',app/'qml',dirs_exist_ok=True)shutil.copy2(ROOT/'scripts/perf/nr-paused-ui.qml',app/'qml/Veyra/NrPausedUiProbe.qml')main=app/'qml/Veyra/Main.qml';text=main.read_text(encoding='utf-8');at=text.rfind('}')loader='\n Loader {source:"NrPausedUiProbe.qml";onLoaded:{const r=new XMLHttpRequest();r.open("GET","'+(app/'paused-run.json').as_uri()+'",false);r.send();const c=JSON.parse(r.responseText);item.media=c.media;item.group=c.group}}\n'main.write_text(text[:at]+loader+text[at:],encoding='utf-8');results=[]for group in groups:matrix.assert_gpu_tests_idle()- assert group in ('nr','srnr','temporal')+ assert group in ('nr','srnr','temporal','dlss','xess','fsr3','vfg')name=label+'-'+group;out=BASE/'logs'/TASK/name;profile=BASE/'tests'/TASK/name/'profile';tmp=BASE/'tmp'/TASK/namefor p in (out,profile,tmp):p.mkdir(parents=True,exist_ok=False)(profile/'qml-preferences.v1.json').write_text(json.dumps({'overlayCompat':'off','language':'zh_CN'}),encoding='utf-8')@@ -32,7 +33,10 @@ for group in groups:for key in tuple(env):if key.upper().startswith(('VEYRA_','QT_QUICK_BACKEND','QSG_RHI_BACKEND')):env.pop(key)env.update(TEMP=str(tmp),TMP=str(tmp),VEYRA_LOG_FILE=str(out/'player.log'),QML_DISABLE_DISK_CACHE='1',QT_FORCE_STDERR_LOGGING='1',QML_XHR_ALLOW_FILE_READ='1')- if variant.endswith('-off'):env['VEYRA_TEST_DISABLE_PAUSED_NR_RESIDUAL_REUSE']='1'+ if variant.endswith('-off'):+ env['VEYRA_TEST_DISABLE_PAUSED_NR_RESIDUAL_REUSE']='1'+ env['VEYRA_TEST_DISABLE_PAUSED_PRESENT_REUSE']='1'+ env['VEYRA_TEST_DISABLE_PAUSED_UI_IDLE']='1'command=[str(app/'veyra_qml_ui.exe'),'--data-dir',str(profile),'--page','pro','--size','1280x800','--exit-after','270000']print('START',name,flush=True);before=matrix.gpu_query();start=time.monotonic();samples=[]with (out/'console.log').open('xb') as log:diff --git a/scripts/perf/nr-paused-ui.qml b/scripts/perf/nr-paused-ui.qmlindex 27769699..236b15a7 100644--- a/scripts/perf/nr-paused-ui.qml+++ b/scripts/perf/nr-paused-ui.qml@@ -11,6 +11,7 @@ Item {property int pausedNr: 0property int edits: 0property int editedNr: 0+ property bool expectedFg: group === "dlss" || group === "xess" || group === "fsr3" || group === "vfg"property double resumePosition: 0function require(ok, why) {if(!ok){console.log("PAUSED_UI_FAIL",why,veyra.diagnosticsReport());Qt.exit(3)}}function nrCount() {@@ -33,11 +34,12 @@ Item {probe.require(veyra.setNrLayerParameter(idx,"sizePolicy",1),"native NR")probe.require(veyra.setNrLayerParameter(idx,"temporal",probe.group==="temporal"?1:0),"temporal")if(probe.group==="srnr"){veyra.videoSrQuality=0;veyra.srTargetIndex=2;veyra.srEnabled=true}+ if(probe.expectedFg){veyra.fgBackendName=probe.group;veyra.fgMultiplier=2;veyra.fgEnabled=true}console.log("PAUSED_UI_CONFIG",JSON.stringify({group:probe.group,layers:veyra.nrLayers,sr:veyra.srEnabled,fg:veyra.fgEnabled}))veyra.openPath(probe.media);probe.stage=1;return}if(probe.stage===1){- if(!veyra.running||veyra.position<5||!veyra.nrActive||veyra.applying)return+ if(!veyra.running||veyra.position<5||!veyra.nrActive||veyra.applying||veyra.fgActive!==probe.expectedFg)returnveyra.togglePlayPause();probe.phaseAt=now;probe.stage=2;return}if(probe.stage===2){diff --git a/scripts/perf/nr-present.py b/scripts/perf/nr-present.pynew file mode 100644index 00000000..e17ef955--- /dev/null+++ b/scripts/perf/nr-present.py@@ -0,0 +1,33 @@+"""Owned native backbuffer idle/invalidation experiment, enabled/off paired."""+from pathlib import Path+import importlib.util+import json+import os+import shutil+import subprocess+import sys+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='perf-nr-20261004'+spec=importlib.util.spec_from_file_location('matrix',ROOT/'scripts/perf/nr-matrix.py');matrix=importlib.util.module_from_spec(spec);spec.loader.exec_module(matrix)+variant,label=sys.argv[1:3];matrix.assert_gpu_tests_idle()+app=BASE/'tests'/TASK/(label+'-app');assert not app.exists()+shutil.copytree(BASE/'test-packages'/TASK/'Veyra-2.0.3-perf-baseline-A-NVIDIA-win64-portable',app,copy_function=matrix.copy_dependency)+exe=app/'veyra_paused_present_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe);results=[];reference=None+for mode in ('enabled','off'):+ for repeat in range(1,4):+ matrix.assert_gpu_tests_idle();name=f'{label}-{mode}-r{repeat}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name+ out.mkdir(parents=True,exist_ok=False);tmp.mkdir(parents=True,exist_ok=False)+ env=os.environ.copy()+ for key in tuple(env):+ if key.upper().startswith('VEYRA_'):env.pop(key)+ env.update(TEMP=str(tmp),TMP=str(tmp))+ if mode=='off':env['VEYRA_TEST_DISABLE_PAUSED_PRESENT_REUSE']='1'+ print('START',name,flush=True)+ with (out/'console.log').open('xb') as log:+ proc=subprocess.run([str(exe),str(matrix.SOURCES['M1']),str(out)],cwd=app,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=280)+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace');files={p.name:matrix.digest(p) for p in out.glob('*.rgba')}+ if reference is None:reference=files+ result={'mode':mode,'repeat':repeat,'exitCode':proc.returncode,'exeSha256':matrix.digest(exe),'imagesSha256':files,+ 'differentImages':sum(reference[k]!=v for k,v in files.items()),'passed':proc.returncode==0 and 'RESULT pass=1' in text and files==reference and len(files)==8}+ (out/'result.json').write_text(json.dumps(result,indent=2),encoding='utf-8');results.append(result);print('RESULT',name,json.dumps(result),flush=True)+ if not result['passed']:print(text[-6000:],flush=True);raise SystemExit(1)+with (BASE/'logs'/TASK/(label+'-summary.json')).open('x',encoding='utf-8') as f:json.dump(results,f,indent=2)diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex c4ee6854..74929836 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -1280,11 +1280,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}if(audioStarted)audioPipe.setPaused(true);wasPaused=true;const bool referencesValid=hasOutput&&out.batch.count&&out.batch.frames[out.batch.count-1].lease&&out.batch.frames[out.batch.count-1].lease->referencesValid;- if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView())){if(recoverXessPresentation())continue;status(L"画面呈现失败",true);break;}+ if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView(),-1,true)){if(recoverXessPresentation())continue;status(L"画面呈现失败",true);break;}if(hasOutput&&graph.resolveGeneration(out))completeReset(out.batch.identity);- // Paused: the swapchain already holds the frame; re-present- // (present() handles resize and takes the view each call)- // at 50 ms instead of 16 ms unless a parameter refresh is due.+ // Poll live view/size changes at 50 ms; unchanged flip+ // buffers are retained without commands or another Present.std::this_thread::sleep_for(std::chrono::milliseconds(refreshPausedFrame_?1:50));continue;}if(wasPaused&&!paused_){holdFileAudio();audioRebuffering=false;if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;pendingResetCause=pipeline::ResetReason::PauseResume;wasPaused=false;}diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 49326ddd..8d3ed4a3 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -81,7 +81,7 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enhreturn true;}void VideoPresenter::refresh(ID3D12Device* device){for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}-bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& sharedRing,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,bool referencesValid,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view,int64_t sourcePts100ns) {+bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& sharedRing,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,bool referencesValid,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view,int64_t sourcePts100ns,bool retainUnchanged) {auto& ring=presentationQueue_?presentationRing_:sharedRing;auto* fence=presentationFence_?presentationFence_.Get():ctx.fence();const auto presentStart=std::chrono::steady_clock::now();@@ -110,6 +110,18 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&// stretch current buffers there instead of repeatedly draining the GPU// and rebuilding provider resources at monitor/DPI boundaries.const bool windowChanging=GetPropW(window_,L"Veyra.InteractiveMove")||GetPropW(window_,L"Veyra.DpiTransition");+ view=filmPixelAlignedView(window_,rc.right,rc.bottom,graph.workWidth(),graph.workHeight(),view);+ const RetainedFrame retained{graph.presentationReadyFenceObject(slot,generated),graph.presentationReadyFence(slot,generated),+ slot,unsigned(rc.right),unsigned(rc.bottom),generated,referencesValid,baseReference,IsWindowVisible(window_)!=FALSE,+ comparison,split,view,identity,MonitorFromWindow(window_,MONITOR_DEFAULTTONEAREST)};+ // Pausing keeps the last flip-model buffer visible. Re-submit only when+ // its producer fence, view, comparison, visibility, monitor or size changes.+ // Deferred resize must keep polling until the actual buffers match.+ if(retainUnchanged&&retained.producer&&retained.fence&&retainedFrame_&&*retainedFrame_==retained&&+ !windowChanging&&targetWidth==sink_.width()&&targetHeight==sink_.height()&&+ SUCCEEDED(ctx.device()->GetDeviceRemovedReason())&&+ !GetEnvironmentVariableW(L"VEYRA_TEST_DISABLE_PAUSED_PRESENT_REUSE",nullptr,0))return true;+ retainedFrame_.reset(); // A failed present never seeds an idle cache.if(!windowChanging&&(targetWidth!=sink_.width()||targetHeight!=sink_.height())&&GetTickCount64()>=deferUntil&&now-lastResize_>=std::chrono::milliseconds(100)&&sink_.resizeDue()) {resized=true;if(!ring.drainQueue())return false;sink_.resize(targetWidth,targetHeight);@@ -144,7 +156,6 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&// DXGI stretches the retained buffer while the native workspace unfolds.// Compute contain in CURRENT client coordinates, then map back to buffer// coordinates so that the onscreen image keeps its aspect throughout.- view=filmPixelAlignedView(window_,rc.right,rc.bottom,graph.workWidth(),graph.workHeight(),view);const auto [renderW,renderH]=view.renderedSize(float(rc.right),float(rc.bottom),float(graph.workWidth()),float(graph.workHeight()));D3D12_VIEWPORT viewport{0,0,float(sink_.bufferWidth()),float(sink_.bufferHeight()),0,1};D3D12_RECT rect{0,0,LONG(sink_.bufferWidth()),LONG(sink_.bufferHeight())};list->RSSetViewports(1,&viewport);list->RSSetScissorRects(1,&rect);@@ -268,7 +279,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&ms(presentEnd-dxgiStart),slow,identity.sourceFrameId,identity.epoch,sink_.xess()?"XeSS":"DXGI",resized,ms(resizeEnd-presentStart),ms(beginEnd-resizeEnd),ms(dxgiStart-beginEnd),timing.beforeMs,timing.callMs,timing.bufferMs,timing.afterMs,unsigned(timing.result)));}- xessFailed_=sink_.xessFailed();return presented;+ xessFailed_=sink_.xessFailed();if(presented)retainedFrame_=retained;return presented;}bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,sink::RgbaImage& image){if(presentationQueue_&&!presentationRing_.drainQueue())return false;@@ -277,6 +288,7 @@ bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx:return SUCCEEDED(sink_.swapChain()->GetBuffer(lastBuffer_,IID_PPV_ARGS(&buffer)))&&sink::readRgba8(ctx,ring,buffer.Get(),image);}void VideoPresenter::close(){+ retainedFrame_.reset();xessInputId_=0;xessWork_={};xessWorkPosition_=0;reflex_.close();reflexFrame_=0;if(presentationRing_.initialized())presentationRing_.drainQueue();diff --git a/tests/perf/PausedPresentExperiment.cpp b/tests/perf/PausedPresentExperiment.cppnew file mode 100644index 00000000..14298153--- /dev/null+++ b/tests/perf/PausedPresentExperiment.cpp@@ -0,0 +1,72 @@+#include "veyra/engine/VideoPresenter.h"+#include "veyra/engine/GraphDescription.h"+#include "veyra/engine/EffectChain.h"+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/source/MediaFileSource.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/RuntimePaths.h"+#include "veyra/Log.h"+#include <d3d12sdklayers.h>+#include <filesystem>+#include <iostream>+#include <fstream>++// Own window/backbuffer only, matching the QML video's WM_PAINT contract.+// Uses the real graph/presenter and checks full pixels after each invalidation.+namespace {+LRESULT CALLBACK procedure(HWND window,UINT message,WPARAM wp,LPARAM lp){+ if(message==WM_PAINT){ValidateRect(window,nullptr);return 0;}+ return DefWindowProcW(window,message,wp,lp);+}+void pump(){MSG m{};while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}}+}+int wmain(int argc,wchar_t** argv){+ using namespace veyra;if(argc!=3)return 2;SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);+ const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);Logger::instance().openFile((out/L"engine.log").wstring());+ WNDCLASSW wc{};wc.hInstance=GetModuleHandleW(nullptr);wc.lpfnWndProc=procedure;wc.lpszClassName=L"VeyraPausedPresentOwnedFixture";+ if(!RegisterClassW(&wc))return 2;+ HWND window=CreateWindowExW(WS_EX_NOACTIVATE,wc.lpszClassName,L"Veyra paused-present test",WS_POPUP,50,50,640,384,nullptr,nullptr,wc.hInstance,nullptr);+ if(!window)return 2;ShowWindow(window,SW_SHOWNOACTIVATE);pump();+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;gfx::DeviceContextDesc device;device.enableDebugLayer=true;+ if(!ctx.initialize(device,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,status))return 2;+ source::MediaFileSource media;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;if(!media.open(open))return 2;+ pipeline::FramePacket packet;const AVFrame* input=nullptr;if(media.read(packet,&input)!=source::SourceReadStatus::Frame)return 2;+ engine::EffectChain chain;chain.nodeCount=1;chain.nodes[0].type=engine::EffectType::NrEnhance;chain.nodes[0].enabled=true;+ chain.nodes[0].nr.sizePolicy=pipeline::NrSizePolicy::Native;engine::EnhancementSettings settings;engine::fromChain(chain,settings);+ engine::StageRequest request;request.width=media.info().width;request.height=media.info().height;request.nr=true;+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);desc.enableNvofStandalone=true;desc.enableFg=false;desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ pipeline::EnhanceGraph graph(ctx,ring);engine::VideoPresenter presenter;+ if(!graph.initialize(desc)||!presenter.open(ctx,window,graph)||!graph.createViews())return 2;+ pipeline::EnhanceGraph::FrameOutputs output;bool pass=graph.process(input,0,true,output,1,&packet.colorInfo,nullptr,true)&&ring.waitIdle();+ engine::PreviewView view{};int comparison=0;float split=.5f;+ auto present=[&]{return presenter.present(ctx,ring,graph,output.videoSlot,false,true,comparison,false,split,output.batch.identity,view,-1,true);};+ auto snapshot=[&](const wchar_t* name){sink::RgbaImage image;if(!presenter.readPresentedFrameForTest(ctx,ring,image)){pass=false;return image;}+ std::ofstream f(out/(std::wstring(name)+L".rgba"),std::ios::binary);f.write(reinterpret_cast<const char*>(image.pixels.data()),std::streamsize(image.pixels.size()));return image;};+ pass=pass&&present();auto first=snapshot(L"initial");const auto initialCount=presenter.submittedCount();+ for(unsigned i=0;i<300&&pass;++i)pass=present();auto idle=snapshot(L"idle");+ const bool disabled=GetEnvironmentVariableW(L"VEYRA_TEST_DISABLE_PAUSED_PRESENT_REUSE",nullptr,0)>0;+ pass=pass&&first.pixels==idle.pixels&&presenter.submittedCount()==initialCount+(disabled?300:0);+ std::cout<<"IDLE pixelsEqual="<<(first.pixels==idle.pixels)<<" presents="<<presenter.submittedCount()<<" disabled="<<disabled<<std::endl;+ view.zoom=1.2f;auto count=presenter.submittedCount();pass=pass&&present()&&presenter.submittedCount()==count+1;auto zoom=snapshot(L"zoom");pass=pass&&zoom.pixels!=idle.pixels;+ comparison=2;count=presenter.submittedCount();pass=pass&&present()&&presenter.submittedCount()==count+1;auto compare=snapshot(L"comparison");pass=pass&&compare.pixels!=zoom.pixels;+ split=.25f;count=presenter.submittedCount();pass=pass&&present()&&presenter.submittedCount()==count+1;auto moved=snapshot(L"split");pass=pass&&moved.pixels!=compare.pixels;+ // Match the debounced resize deadline without touching any other window.+ Sleep(120);SetWindowPos(window,nullptr,50,50,768,432,SWP_NOACTIVATE|SWP_NOZORDER);pump();count=presenter.submittedCount();+ pass=pass&&present()&&presenter.submittedCount()==count+1;auto resized=snapshot(L"resized");pass=pass&&resized.width==768&&resized.height==432;+ settings.residual.total=0;settings.nrLayers[0].residual.total=0;pass=pass&&graph.applySettings(settings);+ pass=pass&&graph.process(input,0,true,output,1,&packet.colorInfo,nullptr,true)&&ring.waitIdle();count=presenter.submittedCount();+ pass=pass&&present()&&presenter.submittedCount()==count+1;auto edited=snapshot(L"producer-changed");pass=pass&&edited.pixels!=resized.pixels;+ count=presenter.submittedCount();ShowWindow(window,SW_HIDE);pump();pass=pass&&present()&&presenter.submittedCount()==count+1;+ ShowWindow(window,SW_SHOWNOACTIVATE);pump();count=presenter.submittedCount();pass=pass&&present()&&presenter.submittedCount()==count+1;+ auto restored=snapshot(L"restored");pass=pass&&restored.pixels==edited.pixels;+ std::cout<<"INVALIDATIONS pass="<<pass<<" finalPresents="<<presenter.submittedCount()<<" image="<<resized.width<<'x'<<resized.height<<std::endl;+ ring.drainQueue();output={};presenter.close();graph.shutdown();media.close();+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;+ for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){SIZE_T size=0;debug->GetMessage(i,nullptr,&size);std::vector<unsigned char> data(size);auto* m=reinterpret_cast<D3D12_MESSAGE*>(data.data());+ if(FAILED(debug->GetMessage(i,m,&size)))return 2;if(m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<m->pDescription<<std::endl;}}+ const auto removed=ctx.device()->GetDeviceRemovedReason();DestroyWindow(window);UnregisterClassW(wc.lpszClassName,wc.hInstance);+ std::cout<<"RESULT pass="<<(pass&&errors==0&&SUCCEEDED(removed))<<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;+ return pass&&errors==0&&SUCCEEDED(removed)?0:1;+}