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: prewarm single-owner features, first successful Present 1942 to 100 ms
Veyra Goal Agent23591e2deecc
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 2df19132..96dba241 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1036,6 +1036,10 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_compile_options(veyra_nr_gpu_competition_load PRIVATE /utf-8)target_link_libraries(veyra_nr_gpu_competition_load PRIVATE veyra_engine)add_executable(veyra_nr_recent_cache_experiment tests/perf/NrRecentCacheExperiment.cpp)+ add_executable(veyra_nr_prewarm_experiment tests/perf/NrPrewarmExperiment.cpp)+ target_compile_features(veyra_nr_prewarm_experiment PRIVATE cxx_std_20)+ target_compile_options(veyra_nr_prewarm_experiment PRIVATE /utf-8)+ target_link_libraries(veyra_nr_prewarm_experiment PRIVATE veyra_engine)target_compile_features(veyra_nr_recent_cache_experiment PRIVATE cxx_std_20)target_compile_options(veyra_nr_recent_cache_experiment PRIVATE /utf-8)target_link_libraries(veyra_nr_recent_cache_experiment PRIVATE veyra_engine bcrypt)@@ -1056,7 +1060,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/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)+ add_library(veyra_engine STATIC src/engine/EngineController.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)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/PERF_2D_PREWARM_2026-10-04.md b/docs/PERF_2D_PREWARM_2026-10-04.mdnew file mode 100644index 00000000..35f5240f--- /dev/null+++ b/docs/PERF_2D_PREWARM_2026-10-04.md@@ -0,0 +1,27 @@+# 2d:空闲预热实测与保留++前存档 `034c2d8` / `checkpoint/perf-nr-2d-before-20261004`。保留待最终R0;不将首次打开收益当成稳态NR提速。设备、command ring、Core、完整Graph由一个PreviewGpuSession持有,所有创建、接管与释放在原Engine dispatcher串行执行。首页空闲2秒后预建一次,用户期间打开视频进入原任务队列等待,不创建第二个设备/snippet/IAT owner。预热只创建Feature/纹理,Evaluate计数必须为0;接管后首帧完整reset。++范围:NVIDIA、普通视频文件、单NR和/或现有DLSS/RTX Video SR、无FG/TrueHDR/颜色额外节点/自定义节点顺序;AMD、多NR、图片、采集和串流不复用。严格key包含完整设置、实际源/内部/输出尺寸及颜色格式、runtime路径/DLL身份元数据;revision归零允许来源打开产生新revision。配置不匹配释放预建Feature,复用已健康Core后正常创建。采用已保存的普通视频源尺寸,无记录使用1920×1080;尺寸上下限64、3840×2160。WDDM测得占用且预算满足才保留,设备失效/设置关闭/取消/退出均释放。预热关闭时不创建增强设备或Feature;Qt界面自身GPU占用不在这一结论中。++## 实际界面A/B/B-off++RTX5070/616.56,同M1、Lecram F95运行库、1280×800、静音、无其它测试GPU负载。全新进程各等8秒,公开open请求的墙钟时间到第一笔成功`[submit]`的软件Present日志;这是成功调用而不是屏幕扫描/端到端显示。每组3次,表中中位数(范围),ms:++| 设置 | 原封存A | B预热 | 同EXE B-off | 相对B-off |+|---|---:|---:|---:|---:|+| 单NR | 1963(1918–1990) | 100(98–110) | 1942(1926–2085) | -94.85% |+| NR+SR到4K | 2000(1998–2029) | 107(104–107) | 2053(2049–2066) | -94.79% |+| SR到4K | 1698(1696–1698) | 92(88–92) | 1733(1727–1740) | -94.69% |++27/27通过,各预热组ready/adopt/CoreInit均1;A/off均无预热、正常CoreInit1。预建工作依然需约2–3秒,只移到首页空闲时,不声称消灭了模型初始化成本。++## 完整像素与生命周期++原生使用实际产品PreviewGpuSession、M1前三个自然帧、每组3次off/on,54张完整RGBA8输出;fresh A-A噪声0,预热差异0,单NR与NR+SR第三帧均匹配此前封存B2a-v2的对应三个完整输出。预建NR/SR Evaluate计数0,播放各3次应有Evaluate,无D3D12 debug错误/设备移除,Core正常关闭。仅图接管CPU时间三轮中位NR0.0596ms、NR+SR0.0988ms、SR0.0652ms;首帧GPU完成18.7769/26.4205/19.8392ms,不含Present,不能与上表混用。++5个独立真实Qt生命周期检查通过:预热进行中打开(1162ms、单Core)、进行中退出(join后释放)、进行中关闭开关(discard后正常冷建、1647ms)、改变NR720内部尺寸(key miss、同Core重新创建、608ms)、全部效果关闭(ready/adopt/CoreInit0)。首次进行中打开不保证100ms;配置不匹配和显存不足回退正常路径。++build-prewarm-v1 475步失败于误把activeRuntime的EffectChain当成含chain包装,修正实际类型;v2 13步exit0。build-prewarm-native-v1 2步exit0。UI v1用baseline属性撞Qt Item FINAL anchor,未打开来源,保留失败样本而不计入;改referenceBuild后v2有效。新增性能设置/能力灰态/偏好持久化,四语言1947项extract检查无缺失/占位问题。导出、全产品R0仍待,其他硬件不推断通过。++原始证据统一在`E:/项目/Veyra/logs/perf-nr-20261004/`:`A2d-ui-v1-*`、`B2d-ui-v2-*`、`B2d-ui-off-v1-*`、`B2d-ui-lifecycle-v1-*`及各summary;`B2d-native-v1-*`/summary含完整原始像素、SHA、CSV、命令、EXE/runtime/source身份和GPU环境;失败构建/loader日志原样保留。所有进程有上限,未操作用户桌面、驱动或原配置。diff --git a/docs/PERF_EXECUTION_NR_2026-10-04.md b/docs/PERF_EXECUTION_NR_2026-10-04.mdindex 20d9efb6..96d2b855 100644--- a/docs/PERF_EXECUTION_NR_2026-10-04.md+++ b/docs/PERF_EXECUTION_NR_2026-10-04.md@@ -33,7 +33,7 @@| 3a | 进程GPU调度优先级 | retained-pending-R0 | 18组交错实际三档;60Hz实时P99改善6.83%,High无稳定收益,普通默认;两绘制模式40次Set/Get及重启通过;PERF_3A_GPU_PRIORITY || 2a | 跨重建保留NGX核心 | retained-pending-R0 | v2三轮A/B/B-off完整输出0差异;暖创建减少75.83/71.23/64.58/72.04%;真实UI及SDK拒绝路径通过;导出待R0 || 2c | 最近配置实例缓存 | retained-single-NR-pending-R0 | 三轮native/Qt画面与生命周期通过;实际NR开create363.851→3.602ms,显存压力/key/关闭源失效通过;SR历史另核验;PERF_2C_RECENT_CACHE |-| 2d | 空闲预热 | pending | 首帧收益与开关关闭时显存 |+| 2d | 空闲预热 | retained-pending-R0 | Qt27组A/B/off首次成功Present1942→100 / 2053→107 / 1733→92ms;54完整输出0差异、5生命周期通过;PERF_2D_PREWARM || 2b | 后台建图与帧边界切换 | pending | 取决于E2,不移除必要同步 || 3b | NR自动内部尺寸 | pending | 取决于E1、真实预算/画质证据 || 1b | 内容帧率预算 | rejected-prerequisite | 1a画面不成立,完整求值仍按transport次数;实测成本构造预算反例,PERF_1B_CONTENT_BUDGET;无生产改动 |diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 3e19326e..6e0f12cc 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,11 @@# Veyra 工作记录+## 2026-10-04 PERF 2d预热保留,2c-SR/2b反例归档中++单owner PreviewGpuSession将device/ring/core/recent/graph从首页空闲预建交给普通文件播放;Engine dispatcher串行,无第二adapter/并行Init,首次full-reset,关闭/取消/预算/key/直播路径回退。性能开关、显卡能力与四语言接入。build-prewarm-v1因EffectChain.chain错误失败,v2修正13步exit0;native-v1 2步exit0。nr-prewarm-ui.py的v1 baseline属性冲突未打开,修正referenceBuild;A2d-ui-v1/B2d-ui-v2/B2d-ui-off-v1各NR/SRNR/SR三轮,27组全部通过,首次成功软件Present中位A1963/2000/1698ms、B100/107/92、off1942/2053/1733。5个lifecycle(预建中打开/退出/关闭、尺寸miss、全效果关闭)通过。nr-prewarm-native.py B2d B2d-native-v1十八进程54张完整输出SHA0差异、A-A噪声0,NR/SRNR匹配此前2a封存自然第三帧;debug/device0,预建Evaluate0。详PERF_2D_PREWARM,原始日志/身份/CSV/E盘路径均同任务label。保留待R0,不称全方案完成。++2c-SR诊断与2b新鲜输出Present实验仅新增tests/perf、scripts/perf接点;生产SR缓存/后台创建未启用。SR/SRNR每轮21/50完整输出差异;并行50创建的Present P99三轮中位32.044→74.189ms。单独拒绝结论文档与节点存档随后的提交记录,原始失败证据不删。所有GPU测试与构建串行,不改用户桌面或配置。+## 2026-10-04 NR优化1a:真实链4500帧反例,拒绝默认整链复用- 1a-before标签3e28be0后,`nr-static.py B2a static-M1-v1` 五组各300帧×三轮15/15测量exit0,NR/SR实际Evaluate计数符合配置,debug0/设备正常。固定M1真实解码自然画面、PTS/序号增加,没有生产跳过,也没有注入Core缓存。EXE082bb45…ffb33,NR F95FEB/616.56。diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex 71930e39..401fbe2c 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -3830,6 +3830,13 @@"en": "When RivaTuner (RTSS) is running at start, the interface is drawn in software and the OSD shows on the video only","ja": "起動時に RivaTuner(RTSS)を検出するとインターフェースをソフトウェア描画にし、OSD は映像にだけ表示します"},+ {+ "zh": "启动时预热增强组件",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "啟動時預熱增強元件",+ "en": "Prewarm enhancement components at startup",+ "ja": "起動時に画質向上コンポーネントを準備"+ },{"zh": "启动窗口大小","src": "qml/SettingsPage.qml",@@ -6028,6 +6035,13 @@"en": "SDR preview at the moment; HDR conversion is not running","ja": "現在は SDR プレビューで、HDR 変換は動作していません"},+ {+ "zh": "当前仅支持 NVIDIA 显卡",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "目前僅支援 NVIDIA 顯示卡",+ "en": "Currently available on NVIDIA GPUs",+ "ja": "現在は NVIDIA GPU のみ対応"+ },{"zh": "当前修改尚未保存:","src": "src/ui/QmlPlayerBridge.cpp",@@ -13302,6 +13316,13 @@"en": "Home = the page for choosing a source (clicking the logo at the top also returns here)","ja": "ホーム = ソースを選ぶ画面(上部のロゴをクリックしても戻れます)"},+ {+ "zh": "首页空闲时准备已启用的单层 NR 或超分,首次打开更快",+ "src": "qml/SettingsPage.qml",+ "zh-TW": "首頁閒置時準備已啟用的單層 NR 或超解析,首次開啟更快",+ "en": "Prepare enabled single-layer NR or upscaling while the home page is idle for a faster first open",+ "ja": "ホーム画面の待機中に有効な単層 NR またはアップスケーリングを準備し、最初の起動を高速化"+ },{"zh": "驱动默认","src": "qml/DialogHost.qml",diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 459d2daf..df3d4514 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -6,6 +6,7 @@#include <thread>#include <condition_variable>#include <functional>+#include <memory>#include "veyra/engine/EnhancementSettings.h"#include "veyra/engine/EffectChain.h"#include "veyra/engine/PresentationSettings.h"@@ -28,6 +29,7 @@ namespace veyra::sink { struct RgbaImage; }namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }namespace veyra::engine {class FrameFlowWindow;+struct PreviewGpuSession;struct PlayerOptions { bool nr=false,sr=false,fg=false,realtime=true; uint32_t fgMultiplier=2; EnhancementSettings settings;std::optional<ChainRuntimeOrder> nodeOrder; // in-process only; not export shared memoryint audioStreamIndex=-1; // export selection; -1 selects the container default@@ -140,6 +142,8 @@ public:EngineController();~EngineController();bool idle()const;+ bool prewarmEnhancement(EnhancementSettings,unsigned width=1920,unsigned height=1080);+ void setEnhancementPrewarmEnabled(bool);bool requestSettings(EnhancementSettings,std::optional<ChainRuntimeOrder> = std::nullopt,uint64_t* acceptedRevision=nullptr);void requestPresentation(PresentationSettings);void open(HWND video,const std::wstring& path,PlayerOptions options);@@ -196,6 +200,8 @@ private:PreviewView previewView_;std::wstring savePath_;std::thread worker_;+ std::unique_ptr<PreviewGpuSession> prewarmed_; // engine dispatcher only+ std::atomic<bool> prewarmEnabled_{true};std::condition_variable wake_;std::function<void()> pending_;bool shutdown_=false,busy_=false;EnhancementSettings desired_;uint64_t nextRevision_=1;std::optional<ChainRuntimeOrder> desiredNodeOrder_; // protected by mutex_, paired with desired_diff --git a/include/veyra/engine/PreviewGpuSession.h b/include/veyra/engine/PreviewGpuSession.hnew file mode 100644index 00000000..2984080c--- /dev/null+++ b/include/veyra/engine/PreviewGpuSession.h@@ -0,0 +1,24 @@+#pragma once+#include "veyra/engine/RecentGraphCache.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/ngx/NgxCoreCache.h"++namespace veyra::engine {+// One owner, on the engine dispatcher only. The entire device/ring/core/graph+// moves from idle prewarm to playback; no second device or snippet Init owner.+struct PreviewGpuSession {+ gfx::D3D12DeviceContext context;+ gfx::CommandSlotRing ring;+ ngx::NgxCoreCache core;+ RecentGraphCache recent{context};+ std::unique_ptr<pipeline::EnhanceGraph> graph=std::make_unique<pipeline::EnhanceGraph>(context,ring,&core);+ uint64_t graphBytes=0;+ std::optional<RecentGraphCache::Key> prepared;+ ~PreviewGpuSession();+ bool initialize(unsigned slots=16);+ static bool requestAllowed(const EnhancementSettings&);+ bool prepare(EnhancementSettings,unsigned width,unsigned height);+ bool adopt(const EnhancementSettings&,const pipeline::EnhanceGraphDesc&);+ void shutdown();+};+}diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex f3d71fa7..10c22b82 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -180,6 +180,7 @@ class QmlPlayerBridge : public QObject {// validated key by key in setPreference(); anything unknown is refused.Q_PROPERTY(QVariantMap preferences READ preferences NOTIFY preferencesChanged)Q_PROPERTY(QString gpuPriorityStatus READ gpuPriorityStatus NOTIFY preferencesChanged)+ Q_PROPERTY(bool enhancementPrewarmAvailable READ enhancementPrewarmAvailable CONSTANT)// The interface language in use (zh-CN / zh-TW / en / ja), after "auto" is resolved;// preferences.language holds the choice itself.Q_PROPERTY(QString uiLanguage READ uiLanguage NOTIFY preferencesChanged)@@ -615,6 +616,7 @@ public:QVariantMap preferences() const;QString gpuPriorityStatus() const;+ bool enhancementPrewarmAvailable() const;QString uiLanguage() const;// main.cpp hands over the QML engine so a language change retranslates the scene.void setQmlEngine(QQmlEngine* engine);@@ -1089,6 +1091,7 @@ private:// Pushes a stored preference to whatever consumes it (subtitle overlay,// audio endpoint). Called after load and after every accepted change.void applyPreference(const QString& key);+ void scheduleEnhancementPrewarm();// Hold-to-compare key (press/release), handled for the whole application.bool eventFilter(QObject* watched, QEvent* event) override;void rememberPosition(bool flush);diff --git a/qml/Veyra/SettingsPage.qml b/qml/Veyra/SettingsPage.qmlindex 4d1e57be..106f68db 100644--- a/qml/Veyra/SettingsPage.qml+++ b/qml/Veyra/SettingsPage.qml@@ -281,6 +281,18 @@ VPage {onPicked: id => veyra.setPreference("gpuPriority", id)}}+ VRow {+ label: qsTr("启动时预热增强组件")+ hint: veyra.enhancementPrewarmAvailable+ ? qsTr("首页空闲时准备已启用的单层 NR 或超分,首次打开更快")+ : qsTr("当前仅支持 NVIDIA 显卡")+ VSwitch {+ objectName: "set-prewarm-enhancement"+ enabled: veyra.enhancementPrewarmAvailable+ checked: veyra.preferences.prewarmEnhancement !== false+ onToggled: v => veyra.setPreference("prewarmEnhancement", v)+ }+ }}VGroup {VRow {diff --git a/scripts/perf/nr-concurrent-present.py b/scripts/perf/nr-concurrent-present.pynew file mode 100644index 00000000..f82e7cb0--- /dev/null+++ b/scripts/perf/nr-concurrent-present.py@@ -0,0 +1,56 @@+"""E2 extension: every successful Present carries a newly evaluated NR output."""+from pathlib import Path+import csv+import importlib.util+import json+import os+import re+import shutil+import statistics+import subprocess+import sys+import time+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_nr_concurrent_create_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)+results=[]+for repeat in range(1,4):+ for mode in ('serial','concurrent'):+ matrix.assert_gpu_tests_idle();name=f'{label}-{mode}-r{repeat}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name+ for p in (out,tmp):p.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))+ command=[str(exe),str(app/'runtime/experimental'),str(out),'60','50',mode,'present']+ start=time.monotonic();print('START',name,flush=True);meters=[]+ with (out/'console.log').open('xb') as f:+ proc=subprocess.Popen(command,cwd=app,env=env,stdout=f,stderr=subprocess.STDOUT)+ while proc.poll() is None and time.monotonic()-start<280:+ meters.append({'elapsed':time.monotonic()-start,'gpu':matrix.gpu_query()});time.sleep(1)+ if proc.poll() is None:proc.kill();proc.wait(timeout=8);rc=124+ else:rc=proc.returncode+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace')+ line=next((s for s in text.splitlines() if s.startswith('RESULT ')),'')+ metrics={k:float(v) for k,v in re.findall(r'(\w+)=(-?\d+(?:\.\d+)?)',line)}+ rows=list(csv.DictReader((out/'present.csv').open()));intervals=[float(r['intervalMs']) for r in rows[1:]]+ def percentile(p):+ values=sorted(intervals);at=(len(values)-1)*p/100;lo=int(at);hi=min(lo+1,len(values)-1)+ return values[lo]+(values[hi]-values[lo])*(at-lo)+ pass_fresh=all(int(r['sequence'])==int(r['presentCount'])==i+1 for i,r in enumerate(rows))+ result={'repeat':repeat,'mode':mode,'command':command,'exeSha256':matrix.digest(exe),+ 'runtimeSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),'exitCode':rc,'metrics':metrics,+ 'wallSeconds':time.monotonic()-start,'presentSamples':len(rows),'freshEveryPresent':pass_fresh,+ 'intervals':{'p50':statistics.median(intervals),'p95':percentile(95),'p99':percentile(99),'max':max(intervals)},+ 'gapsAboveTwo60HzIntervals':sum(x>1000/30 for x in intervals),+ 'safetyPassed':rc==0 and metrics.get('pass')==1 and metrics.get('debugErrors')==0 and len(rows)>1000 and pass_fresh,+ 'seamlessPassed':max(intervals)<1000/30,+ 'measurement':'Actual newly evaluated Feature18 output CopyResource and successful Present return; static authored source, no scanout or AV drift proof'}+ (out/'meters.json').write_text(json.dumps(meters,ensure_ascii=False,indent=2),encoding='utf-8')+ (out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8');results.append(result)+ print('RESULT',name,result['safetyPassed'],result['intervals'],result['gapsAboveTwo60HzIntervals'],flush=True)+ if not result['safetyPassed']:print(text[-5000:],flush=True);raise SystemExit(1)+with (BASE/'logs'/TASK/(label+'-summary.json')).open('x',encoding='utf-8') as f:json.dump(results,f,ensure_ascii=False,indent=2)diff --git a/scripts/perf/nr-feature-cache.py b/scripts/perf/nr-feature-cache.pyindex e57c6aee..f522c5e4 100644--- a/scripts/perf/nr-feature-cache.py+++ b/scripts/perf/nr-feature-cache.py@@ -14,7 +14,8 @@ import timeROOT=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];app=BASE/'tests'/TASK/(label+'-app')+variant,label=sys.argv[1:3];group=sys.argv[3] if len(sys.argv)>3 else 'nr';assert group in ('nr','sr','srnr')+app=BASE/'tests'/TASK/(label+'-app')assert not app.exists();matrix.assert_gpu_tests_idle()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_nr_recent_cache_experiment.exe'@@ -30,7 +31,7 @@ for repeat in range(1,4):if key.upper().startswith('VEYRA_'):env.pop(key)env.update(TEMP=str(tmp),TMP=str(tmp))if disabled:env['VEYRA_TEST_DISABLE_RECENT_GRAPH_CACHE']='1'- command=[str(exe),str(matrix.SOURCES['M1']),str(out)];before=matrix.gpu_query();start=time.monotonic()+ command=[str(exe),str(matrix.SOURCES['M1']),str(out),group];before=matrix.gpu_query();start=time.monotonic()print('START',name,flush=True)with (out/'console.log').open('xb') as f:try:rc=subprocess.run(command,cwd=app,env=env,stdout=f,stderr=subprocess.STDOUT,timeout=280).returncode@@ -39,7 +40,7 @@ for repeat in range(1,4):rows=list(csv.DictReader((out/'cache.csv').open())) if (out/'cache.csv').exists() else []hits=sum(int(r['hit']) for r in rows)creates=[float(r['createMs']) for r in rows if int(r['nr']) and int(r['cycle'])>0]- result={'variant':variant,'label':label,'disabled':disabled,'repeat':repeat,'exeSha256':matrix.digest(exe),+ result={'variant':variant,'label':label,'group':group,'disabled':disabled,'repeat':repeat,'exeSha256':matrix.digest(exe),'runtimeSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),'sourceSha256':matrix.digest(matrix.SOURCES['M1']),'beforeGpu':before,'afterGpu':matrix.gpu_query(),'command':command,'exitCode':rc,'wallSeconds':time.monotonic()-start,'frameCount':len(rows),diff --git a/scripts/perf/nr-prewarm-native.py b/scripts/perf/nr-prewarm-native.pynew file mode 100644index 00000000..2f27b4f9--- /dev/null+++ b/scripts/perf/nr-prewarm-native.py@@ -0,0 +1,57 @@+"""Never-evaluated prepared features versus fresh features: three full outputs."""+from pathlib import Path+import csv+import importlib.util+import json+import os+import re+import shutil+import statistics+import subprocess+import sys+import time+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_nr_prewarm_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)+results=[]+for group in ('nr','srnr','sr'):+ for repeat in range(1,4):+ for mode in ('off','on'):+ matrix.assert_gpu_tests_idle();name=f'{label}-{group}-{mode}-r{repeat}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name+ for p in (out,tmp):p.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));command=[str(exe),str(matrix.SOURCES['M1']),str(out),mode,group]+ print('START',name,flush=True);before=matrix.gpu_query();start=time.monotonic()+ with (out/'console.log').open('xb') as f:+ try:rc=subprocess.run(command,cwd=app,env=env,stdout=f,stderr=subprocess.STDOUT,timeout=90).returncode+ except subprocess.TimeoutExpired:rc=124+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace')+ metrics={k:float(v) for k,v in re.findall(r'(\w+)=(-?\d+(?:\.\d+)?)',next((s for s in text.splitlines() if s.startswith('PREWARM_RESULT ')),''))}+ hashes={p.name:matrix.digest(p) for p in out.glob('*.rgba')}+ result={'group':group,'repeat':repeat,'mode':mode,'command':command,'exitCode':rc,'metrics':metrics,+ 'exeSha256':matrix.digest(exe),'runtimeSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),+ 'sourceSha256':matrix.digest(matrix.SOURCES['M1']),'wallSeconds':time.monotonic()-start,+ 'gpuBefore':before,'gpuAfter':matrix.gpu_query(),'hashes':hashes,+ 'passed':rc==0 and metrics.get('pass')==1 and metrics.get('debugErrors')==0 and len(hashes)==3,+ 'measurement':'Product PreviewGpuSession and actual natural GPU output; CPU create/adoption/first GPU-completion, no Present/scanout'}+ (out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8');results.append(result)+ print('RESULT',name,result['passed'],metrics.get('firstGpuCompleteMs'),flush=True)+ if not result['passed']:print(text[-4500:],flush=True);raise SystemExit(1)+comparisons=[]+for group in ('nr','srnr','sr'):+ runs=[r for r in results if r['group']==group];reference=runs[0]['hashes']+ comparison={'group':group,'freshNoiseDifferentFrames':sum(a['hashes'][f]!=reference[f] for a in runs if a['mode']=='off' for f in reference),+ 'prewarmDifferentFrames':sum(a['hashes'][f]!=reference[f] for a in runs if a['mode']=='on' for f in reference)}+ if group!='sr':+ legacy_group='nr' if group=='nr' else 'sr'+ legacy=[matrix.digest(BASE/'logs'/TASK/f'B2a-rebuild-v2-{legacy_group}-r{r}'/'frame-0.rgba') for r in range(1,4)]+ comparison['matchesSealedPriorNodeFirstThreeFrames']=all(a['hashes']['frame-2.rgba']==h for a in runs for h in legacy)+ comparisons.append(comparison)+summary={'results':results,'comparisons':comparisons,'passed':all(c['freshNoiseDifferentFrames']==0 and c['prewarmDifferentFrames']==0 and c.get('matchesSealedPriorNodeFirstThreeFrames',True) for c in comparisons)}+with (BASE/'logs'/TASK/(label+'-summary.json')).open('x',encoding='utf-8') as f:json.dump(summary,f,ensure_ascii=False,indent=2)+print('PIXEL_COMPARISONS',comparisons,flush=True);raise SystemExit(0 if summary['passed'] else 1)diff --git a/scripts/perf/nr-prewarm-ui.py b/scripts/perf/nr-prewarm-ui.pynew file mode 100644index 00000000..b863166e--- /dev/null+++ b/scripts/perf/nr-prewarm-ui.py@@ -0,0 +1,67 @@+"""Matched cold/open UI tests. Latency is first successful software Present."""+from pathlib import Path+from datetime import datetime+import importlib.util+import json+import os+import re+import shutil+import subprocess+import sys+import time+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];groups=sys.argv[3:] or ['nr','srnr','sr'];matrix.assert_gpu_tests_idle()+assert all(g in ('nr','srnr','sr','during','quit','disable','mismatch','alloff') for g in groups)+baseline=variant=='A';disabled=variant.endswith('-off');build_variant=variant.removesuffix('-off')+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)+if not baseline:+ shutil.copy2(BASE/'build'/TASK/build_variant/'veyra_qml_ui.exe',app/'veyra_qml_ui.exe')+ shutil.copytree(ROOT/'qml',app/'qml',dirs_exist_ok=True)+shutil.copy2(ROOT/'scripts/perf/nr-prewarm-ui.qml',app/'qml/Veyra/PrewarmUiProbe.qml')+main=app/'qml/Veyra/Main.qml';text=main.read_text(encoding='utf-8');at=text.rfind('}')+main.write_text(text[:at]+'\n Loader {source:"PrewarmUiProbe.qml";onLoaded:{const r=new XMLHttpRequest();r.open("GET","'+(app/'prewarm-run.json').as_uri()+'",false);r.send();const c=JSON.parse(r.responseText);item.media=c.media;item.group=c.group;item.referenceBuild=c.baseline}}\n'+text[at:],encoding='utf-8')+results=[]+for group in groups:+ for repeat in range(1,4) if group in ('nr','srnr','sr') else (1,):+ matrix.assert_gpu_tests_idle();name=f'{label}-{group}-r{repeat}'+ out=BASE/'logs'/TASK/name;profile=BASE/'tests'/TASK/name/'profile';tmp=BASE/'tmp'/TASK/name+ for p in (out,profile,tmp):p.mkdir(parents=True,exist_ok=False)+ (profile/'qml-preferences.v1.json').write_text(json.dumps({'overlayCompat':'off','prewarmEnhancement':not disabled}),encoding='utf-8')+ (app/'prewarm-run.json').write_text(json.dumps({'media':str(matrix.SOURCES['M1']).replace('\\','/'),'group':group,'baseline':baseline}),encoding='utf-8')+ env=os.environ.copy()+ 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',VEYRA_VERBOSE_FRAME_LOGS='1')+ command=[str(app/'veyra_qml_ui.exe'),'--data-dir',str(profile),'--page','pro','--size','1280x800','--exit-after','95000']+ print('START',name,flush=True);before=matrix.gpu_query();start=time.monotonic()+ with (out/'console.log').open('xb') as f:+ try:rc=subprocess.run(command,cwd=app,env=env,stdout=f,stderr=subprocess.STDOUT,timeout=105).returncode+ except subprocess.TimeoutExpired:rc=124+ text=(out/'player.log').read_text(encoding='utf-8',errors='replace')+ marks=[int(m) for m in re.findall(r'PREWARM_UI_OPEN (\d+)',text)]+ submits=[line for line in text.splitlines() if '[submit]' in line]+ latency=None+ if marks and submits:latency=datetime.fromisoformat(submits[0].split()[0].replace('Z','+00:00')).timestamp()*1000-marks[0]+ events=[line for line in text.splitlines() if '[prewarm]' in line]+ ready=sum('event=ready' in line for line in events);adopted=sum('event=adopt' in line for line in events)+ expect_no_open=group in ('quit','alloff')+ passed=rc==0 and not any(x in text for x in ('PREWARM_UI_FAIL','ReferenceError:','TypeError:','[ERROR]','[FATAL]','leaked parameter block'))+ if expect_no_open:passed=passed and not submits and ('PREWARM_UI_QUIT_DURING' in text if group=='quit' else 'PREWARM_UI_ALL_OFF_PASS' in text)+ else:passed=passed and 'PREWARM_UI_PASS' in text and latency is not None and latency>0+ if not baseline and not disabled and group in ('nr','srnr','sr','during'):passed=passed and ready==1 and adopted==1+ if baseline or disabled or group=='alloff':passed=passed and ready==0 and adopted==0+ if group=='disable':passed=passed and ready==1 and adopted==0 and any('event=discard' in s or 'event=disabled' in s for s in events)+ if group=='mismatch':passed=passed and ready==1 and adopted==0 and any('event=miss' in s for s in events)+ result={'variant':variant,'group':group,'repeat':repeat,'command':command,'exitCode':rc,+ 'exeSha256':matrix.digest(app/'veyra_qml_ui.exe'),'runtimeSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),+ 'sourceSha256':matrix.digest(matrix.SOURCES['M1']),'wallSeconds':time.monotonic()-start,'gpuBefore':before,'gpuAfter':matrix.gpu_query(),+ 'openToFirstSuccessfulPresentMs':latency,'ready':ready,'adopted':adopted,'events':events,+ 'coreInitCalls':text.count('core-host: Init_with_ProjectID result='),'coreShutdownCalls':text.count('core-host: Shutdown1 result='),+ 'passed':bool(passed),'measurement':'Public open request wall time to first successful Present log; includes queue/device/decode; no scanout'}+ (out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8');results.append(result)+ print('RESULT',name,result['passed'],latency,ready,adopted,result['coreInitCalls'],flush=True)+ if not result['passed']:print('\n'.join([s for s in text.splitlines() if '[prewarm]' in s or 'PREWARM_UI_' in s or '[ERROR]' in s])[-4000:],flush=True);raise SystemExit(1)+with (BASE/'logs'/TASK/(label+'-summary.json')).open('x',encoding='utf-8') as f:json.dump(results,f,ensure_ascii=False,indent=2)diff --git a/scripts/perf/nr-prewarm-ui.qml b/scripts/perf/nr-prewarm-ui.qmlnew file mode 100644index 00000000..cc932481--- /dev/null+++ b/scripts/perf/nr-prewarm-ui.qml@@ -0,0 +1,47 @@+import QtQuick+Item {+ id: probe+ property string media: ""+ property string group: "nr"+ property bool referenceBuild: false+ property int stage: 0+ property double startedAt: Date.now()+ property double openedAt: 0+ function require(ok,why){if(!ok){console.log("PREWARM_UI_FAIL",why,veyra.diagnosticsReport());Qt.exit(3)}}+ Timer {+ interval: 100;repeat: true;running: true+ onTriggered: {+ const elapsed=Date.now()-probe.startedAt+ require(elapsed<90000,"timeout");require(!veyra.failed,"engine failure")+ if(probe.stage===0){+ veyra.muted=true;veyra.lowLatency=false;veyra.videoHdr=false;veyra.colorEnabled=false;veyra.fgEnabled=false+ veyra.nrEnabled=probe.group!=="alloff"&&probe.group!=="sr"+ veyra.srEnabled=probe.group==="srnr"||probe.group==="sr"+ veyra.videoSrQuality=0;veyra.srTargetIndex=2+ require(veyra.setNrLayerParameter(veyra.nrLayers[0].index,"temporal",0),"temporal")+ require(veyra.setNrLayerParameter(veyra.nrLayers[0].index,"sizePolicy",0),"size")+ console.log("PREWARM_UI_CONFIG",JSON.stringify({group:probe.group,at:Date.now(),nr:veyra.nrEnabled,sr:veyra.srEnabled}));probe.stage=1;return+ }+ if(probe.stage===1){+ if(probe.group==="quit"&&elapsed>=2300){console.log("PREWARM_UI_QUIT_DURING");Qt.quit();return}+ if(probe.group==="alloff"&&elapsed>=6500){console.log("PREWARM_UI_ALL_OFF_PASS");Qt.quit();return}+ if(probe.group==="disable"&&elapsed>=2500){require(veyra.setPreference("prewarmEnhancement",false),"disable prewarm");probe.stage=2;return}+ const openAt=probe.group==="during"?2300:8000+ if(elapsed<openAt)return+ if(probe.group==="mismatch")require(veyra.setNrLayerParameter(veyra.nrLayers[0].index,"sizePolicy",2),"size key change")+ probe.openedAt=Date.now();console.log("PREWARM_UI_OPEN",probe.openedAt);veyra.openPath(probe.media);probe.stage=3;return+ }+ if(probe.stage===2){+ if(elapsed<8000)return+ probe.openedAt=Date.now();console.log("PREWARM_UI_OPEN",probe.openedAt);veyra.openPath(probe.media);probe.stage=3;return+ }+ if(probe.stage===3){+ if(!veyra.running||veyra.applying||veyra.position<1.5)return+ require(veyra.nrActive===(probe.group!=="sr"),"NR active")+ require(veyra.srActive===(probe.group==="srnr"||probe.group==="sr"),"SR active")+ console.log("PREWARM_UI_PASS",JSON.stringify({group:probe.group,observedOpenMs:Date.now()-probe.openedAt,+ nr:veyra.nrActive,sr:veyra.srActive,position:veyra.position,details:veyra.diagnosticsReport()}));Qt.quit()+ }+ }+ }+}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex be73299c..b72cdd2e 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -36,12 +36,12 @@#include "veyra/sink/WasapiAudioSink.h"#include "veyra/sink/ImageExportSink.h"#include "veyra/gfx/D3D12DeviceContext.h"-#include "veyra/gfx/GpuSchedulingPriority.h"#include "veyra/gfx/CommandSlotRing.h"#include "veyra/gfx/PresentationHooks.h"#include "veyra/RuntimePaths.h"#include "veyra/engine/GraphDescription.h"#include "veyra/engine/RecentGraphCache.h"+#include "veyra/engine/PreviewGpuSession.h"#include "veyra/engine/EffectChain.h"#include "veyra/engine/PosterFrame.h"#include <avrt.h>@@ -76,9 +76,33 @@ void EngineController::dispatch(){try{task();}catch(const std::exception&){status(L"任务异常,已停止;请查看诊断",true);}{std::lock_guard lock(mutex_);busy_=false;snapshot_.running=false;if(snapshot_.transport==TransportState::Stopping)snapshot_.transport=TransportState::Empty;}}+ prewarmed_.reset();}void EngineController::post(std::function<void()> task){ {std::lock_guard lock(mutex_);stop_=true;pending_=std::move(task);}wake_.notify_one(); }bool EngineController::idle()const{std::lock_guard lock(mutex_);return !busy_&&!pending_;}+bool EngineController::prewarmEnhancement(EnhancementSettings settings,unsigned width,unsigned height){+ if(!prewarmEnabled_||!PreviewGpuSession::requestAllowed(settings))return false;+ {+ std::lock_guard lock(mutex_);if(shutdown_||busy_||pending_)return false;+ pending_=[this,settings,width,height]{+ if(!prewarmEnabled_)return;+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ auto candidate=std::make_unique<PreviewGpuSession>();prewarmed_.reset();+ log::info("prewarm","event=begin owner=engine-dispatcher");+ const bool ready=candidate->prepare(settings,width,height);+ bool keep=false;{std::lock_guard lock(mutex_);keep=ready&&prewarmEnabled_&&!shutdown_&&(!stop_||bool(pending_));}+ if(keep)prewarmed_=std::move(candidate);+ else log::info("prewarm","event=discard reason=not-ready-disabled-or-cancelled");+ candidate.reset();CoUninitialize();+ };+ }+ wake_.notify_one();return true;+}+void EngineController::setEnhancementPrewarmEnabled(bool enabled){+ prewarmEnabled_=enabled;+ if(!enabled){std::lock_guard lock(mutex_);if(!busy_&&!pending_)pending_=[this]{prewarmed_.reset();log::info("prewarm","event=disabled released=true");};}+ wake_.notify_one();+}bool EngineController::setPlaybackRate(double rate){if(!validPlaybackRate(rate))return false;std::lock_guard lock(mutex_);@@ -145,7 +169,11 @@ void EngineController::openXbox(HWND window,source::XboxConnectDesc desc,PlayerOpost([this,window,request,opts]{paused_=false;seekSeconds_=-1;run(window,L"xbox:",opts,{},{},request);});}#endif-void EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};snapshot_.transport=busy_?TransportState::Stopping:TransportState::Empty;}+void EngineController::stop(){+ {std::lock_guard lock(mutex_);stop_=true;pending_={};snapshot_.transport=busy_?TransportState::Stopping:TransportState::Empty;+ if(!busy_)pending_=[this]{prewarmed_.reset();};}+ wake_.notify_one();+}void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);if(snapshot_.running)snapshot_.transport=p?TransportState::Paused:TransportState::Playing;}void EngineController::setVolume(float gain,bool mute){if(!std::isfinite(gain))return;volume_=std::clamp(gain,0.0f,1.0f);muted_=mute;}bool EngineController::selectAudioTrack(uint64_t session,int streamIndex){@@ -205,7 +233,7 @@ void EngineController::startExport(const std::wstring& input,const std::wstring&status(L"节点链尚未接入导出执行器,请切换列表模式后导出",false);return;}const auto frozen=opts.snapshot();const int audioStream=opts.audioStreamIndex;- post([this,input,output,frozen,audioStream,hevc]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);auto options=PlayerOptions::from(frozen);options.audioStreamIndex=audioStream;bool ok=exportVideo(input,output,options,hevc,stop_,[this](double p,const std::wstring& s){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.position=p;snapshot_.duration=1;snapshot_.running=true;});{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.failed=!ok&&!stop_;}CoUninitialize();});+ post([this,input,output,frozen,audioStream,hevc]{prewarmed_.reset();CoInitializeEx(nullptr,COINIT_MULTITHREADED);auto options=PlayerOptions::from(frozen);options.audioStreamIndex=audioStream;bool ok=exportVideo(input,output,options,hevc,stop_,[this](double p,const std::wstring& s){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.position=p;snapshot_.duration=1;snapshot_.running=true;});{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.failed=!ok&&!stop_;}CoUninitialize();});}void EngineController::requestPresentation(PresentationSettings settings){if(!settings.valid())return;@@ -292,12 +320,16 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sCoInitializeEx(nullptr,COINIT_MULTITHREADED);MmcssScope mmcss(L"Pro Audio");status(L"正在初始化GPU与本地运行时…");- gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;+ auto extension=std::filesystem::path(path).extension().wstring();for(auto& c:extension)c=towlower(c);+ const bool ordinaryFile=!remoteRequest&&!moonlightRequest&&!xboxRequest&&+ !path.starts_with(L"capture:")&&!path.starts_with(L"capture2:")&&!path.starts_with(L"screen:")&&+ extension!=L".png"&&extension!=L".jpg"&&extension!=L".jpeg";+ if(!prewarmEnabled_||!ordinaryFile)prewarmed_.reset();+ auto gpu=prewarmed_?std::move(prewarmed_):std::make_unique<PreviewGpuSession>();+ auto& ctx=gpu->context;auto& ring=gpu->ring;source::MediaFileSource source;sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;- ngx::NgxCoreCache coreCache;- RecentGraphCache recentGraphCache(ctx);- auto graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);- uint64_t graphBytes=0;auto cacheBudgetPolledAt=Clock::now();+ 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);AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;source::CaptureCardSource captureSource;const bool physicalCapture=path.starts_with(L"capture:")||path.starts_with(L"capture2:");@@ -353,8 +385,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// MFG lists. Allocators must not stall the presentation owner.wchar_t testSlots[16]{};unsigned commandSlots=16;if(GetEnvironmentVariableW(L"VEYRA_TEST_COMMAND_SLOTS",testSlots,16))commandSlots=std::clamp(unsigned(_wtoi(testSlots)),6u,24u);- if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),commandSlots,st)){status(L"D3D12初始化失败,请查看诊断",true);break;}- gfx::applyRequestedGpuPriority();+ if(!gpu->initialize(commandSlots)){status(L"D3D12初始化失败,请查看诊断",true);break;}auto ext=std::filesystem::path(path).extension().wstring();for(auto& c:ext)c=towlower(c);const bool isImage=ext==L".png"||ext==L".jpg"||ext==L".jpeg";sink::RgbaImage image;@@ -548,7 +579,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sgraph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);}uint64_t buildBudget=0,buildUsage=0;const bool measuredBefore=ctx.videoMemoryInfo(buildBudget,buildUsage);- bool opened=graph->initialize(desc);+ const bool adopted=gpu->adopt(selected.snapshot(),desc);+ bool opened=adopted||graph->initialize(desc);auto failure=graph->failedBackend();if(opened){opened=presenter.open(ctx,window,*graph,selected.settings.captureCompatible,!isCapture&&!isImage)&&graph->createViews();@@ -562,7 +594,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}if(opened){uint64_t afterBudget=0,afterUsage=0;- graphBytes=measuredBefore&&ctx.videoMemoryInfo(afterBudget,afterUsage)&&afterUsage>buildUsage?afterUsage-buildUsage:0;+ const auto newBytes=measuredBefore&&ctx.videoMemoryInfo(afterBudget,afterUsage)&&afterUsage>buildUsage?afterUsage-buildUsage:0;+ graphBytes=adopted?graphBytes+newBytes:newBytes;return true;}// A live backend/multiplier switch must not turn a working FG@@ -2220,7 +2253,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sveyra::log::info("engine","teardown: closing sources");captureSource.close();screenSource.close();source.close();av_frame_free(&cachedFrame);av_frame_free(&imageFrame);veyra::log::info("engine","teardown: sources closed");- ring.shutdown();ctx.shutdown();+ gpu->shutdown();{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.audioEndpointRecovering=false;snapshot_.audioRebuffering=false;}CoUninitialize();}diff --git a/src/engine/PreviewGpuSession.cpp b/src/engine/PreviewGpuSession.cppnew file mode 100644index 00000000..df74715c--- /dev/null+++ b/src/engine/PreviewGpuSession.cpp@@ -0,0 +1,57 @@+#include "veyra/engine/PreviewGpuSession.h"+#include "veyra/engine/GraphDescription.h"+#include "veyra/engine/EngineController.h"+#include "veyra/gfx/GpuSchedulingPriority.h"+#include "veyra/RuntimePaths.h"+#include <chrono>++namespace veyra::engine {+PreviewGpuSession::~PreviewGpuSession(){shutdown();}+bool PreviewGpuSession::initialize(unsigned slots){+ if(context.initialized()&&ring.initialized())return true;+ Status status;gfx::DeviceContextDesc desc;desc.commandSlotCount=6;+ if(!context.initialize(desc,status)||!ring.initialize(context.device(),context.directQueue(),context.fence(),context.fenceEvent(),slots,status))return false;+ gfx::applyRequestedGpuPriority();return true;+}+bool PreviewGpuSession::requestAllowed(const EnhancementSettings& settings){+ return settings.validate().empty()&&(settings.nr||settings.sr)&&settings.multiplier==1&&+ settings.nrRuntime==NrRuntime::Original&&settings.activeNrLayerCount()<=1&&+ !settings.videoHdr.enabled&&!settings.color.enabled&&settings.additionalColorCount==0&&+ (settings.videoSrQuality==0||settings.videoSrQuality==4);+}+bool PreviewGpuSession::prepare(EnhancementSettings settings,unsigned width,unsigned height){+ if(!requestAllowed(settings)||width<64||height<64||width>3840||height>2160)return false;+ const auto start=std::chrono::steady_clock::now();settings=PlayerOptions::from(settings).snapshot();+ if(!initialize()||!context.adapter().isNvidia||ngx::FgCompatibilitySession::requested(context.adapter().vendorId,context.adapter().deviceId))return false;+ StageRequest request;request.width=width;request.height=height;request.nr=settings.nr;request.sr=settings.sr;+ pipeline::EnhanceGraphDesc desc;describeStages(request,settings,desc);desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ uint64_t budget=0,before=0;const bool measured=context.videoMemoryInfo(budget,before);+ if(!graph->initialize(desc)||!graph->createViews()||!ring.waitIdle())return false;+ if((settings.nr&&!graph->nrEnabled())||(settings.sr&&settings.videoSrQuality==0&&!graph->srEnabled()))return false;+ uint64_t after=0;if(!measured||!context.videoMemoryInfo(budget,after)||after<=before)return false;+ graphBytes=after-before;+ if(!RecentGraphCache::fits(budget,after,graphBytes)){log::info("prewarm","event=discard reason=memory-budget");return false;}+ prepared=RecentGraphCache::key(settings,{},desc);+ log::info("prewarm",std::format("event=ready source={}x{} bytes={} usage={} budget={} buildMs={:.3f} evaluated=0",+ width,height,graphBytes,after,budget,std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()));+ return true;+}+bool PreviewGpuSession::adopt(const EnhancementSettings& settings,const pipeline::EnhanceGraphDesc& desc){+ if(!prepared)return false;+ const auto requested=RecentGraphCache::key(settings,{},desc);+ uint64_t budget=0,usage=0;+ const bool compatible=*prepared==requested&&context.videoMemoryInfo(budget,usage)&&+ RecentGraphCache::fits(budget,usage,graphBytes)&&SUCCEEDED(context.device()->GetDeviceRemovedReason());+ prepared.reset();+ if(compatible&&graph->applySettings(settings)){+ graph->invalidatePausedResidualCache();log::info("prewarm",std::format("event=adopt bytes={} full-first-frame-reset=true",graphBytes));return true;+ }+ log::info("prewarm","event=miss reason=config-dimensions-color-or-budget");+ graph->shutdown();graph=std::make_unique<pipeline::EnhanceGraph>(context,ring,&core);graphBytes=0;return false;+}+void PreviewGpuSession::shutdown(){+ if(ring.initialized())ring.drainQueue();+ if(graph){graph->shutdown();graph.reset();}recent.evict("device-close");+ core.close("device-close");ring.shutdown();context.shutdown();prepared.reset();graphBytes=0;+}+}diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 80460031..41906934 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -981,6 +981,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystcapabilityTimer->start(2000);impl_->loadPrefs();applyPreference(QStringLiteral("gpuPriority"));+ applyPreference(QStringLiteral("prewarmEnhancement"));impl_->engine.setFullscreenMemoryProtection(impl_->prefBool("fullscreenMemoryProtection",false));impl_->enumerateGpuAdapters();impl_->resolveGpuMonitor();@@ -1164,7 +1165,16 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystemit notice(tr("已从上次位置 %1 继续").arg(formatTime(at)), false);}}- if (++impl_->positionTicks >= 120) { impl_->positionTicks = 0; rememberPosition(false); }+ if (++impl_->positionTicks >= 120) {+ impl_->positionTicks = 0; rememberPosition(false);+ if(s.running&&!s.capture&&!s.image&&s.sourceWidth>=64&&s.sourceHeight>=64&&s.sourceWidth<=3840&&s.sourceHeight<=2160){+ const QVariantMap extent{{"width",s.sourceWidth},{"height",s.sourceHeight}};+ if(impl_->prefs.value(QStringLiteral("lastSourceExtent")).toMap()!=extent){+ impl_->prefs[QStringLiteral("lastSourceExtent")]=extent;+ if(!impl_->savePrefs())veyra::log::warn("ui-prefs","last source extent not saved");+ }+ }+ }}// Status light: 1.4.4 sampled its dashboard history every 250 ms.if (++impl_->historyTicks >= 16) {@@ -4640,6 +4650,17 @@ QString QmlPlayerBridge::gpuPriorityStatus() const {if(status.state==gfx::GpuPriorityState::Rejected)return tr("系统未接受设置,当前:%1").arg(status.actual<0?tr("未知"):name(status.actual));return tr("已生效:%1").arg(name(status.actual));}+bool QmlPlayerBridge::enhancementPrewarmAvailable() const {return effectGpu().vendor==0x10DE;}+void QmlPlayerBridge::scheduleEnhancementPrewarm(){+ QTimer::singleShot(2000,this,[this]{+ if(!impl_->prefBool("prewarmEnhancement",true)||!enhancementPrewarmAvailable()||impl_->openingSource||impl_->snapshot.running||!impl_->engine.idle())return;+ if(engine::runtimeOrder(impl_->activeRuntime()))return;+ const auto saved=impl_->prefs.value(QStringLiteral("lastSourceExtent")).toMap();+ const auto width=saved.value("width",1920).toUInt(),height=saved.value("height",1080).toUInt();+ const bool valid=width>=64&&height>=64&&width<=3840&&height<=2160;+ impl_->engine.prewarmEnhancement(impl_->facade.pendingSettings(),valid?width:1920,valid?height:1080);+ });+}void QmlPlayerBridge::rememberWindowSize(int width, int height) {// Only kept when the user chose "记住上次"; the key is internal.if (width < 400 || height < 200 || width > 16384 || height > 16384) return;@@ -4664,7 +4685,7 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {{"subtitleMargin", {0, 240}}, {"subtitleLines", {0, 8}}};static const QStringList flags{"subtitleEnabled", "subtitleBackground", "subtitleFit","subtitleSecondLanguage", "audioForceStereo", "holdCompare",- "magewellLowLatency", "cinePillHidden", "exportStopsPlayback", "obsGameCapture", "autoResume", "fullscreenMemoryProtection"};+ "magewellLowLatency", "cinePillHidden", "exportStopsPlayback", "obsGameCapture", "autoResume", "fullscreenMemoryProtection", "prewarmEnhancement"};QVariant stored;if (ranges.contains(key)) {bool ok = false; const int n = value.toInt(&ok);@@ -4742,6 +4763,10 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {return true;}void QmlPlayerBridge::applyPreference(const QString& key) {+ if(key==QLatin1String("prewarmEnhancement")){+ impl_->engine.setEnhancementPrewarmEnabled(impl_->prefBool("prewarmEnhancement",true));+ if(impl_->prefBool("prewarmEnhancement",true))scheduleEnhancementPrewarm();+ }if(key==QLatin1String("gpuPriority")){const auto value=impl_->prefString("gpuPriority");gfx::requestGpuPriority(value==QLatin1String("realtime")?gfx::GpuPriority::Realtime:diff --git a/tests/perf/NrConcurrentCreateExperiment.cpp b/tests/perf/NrConcurrentCreateExperiment.cppindex c757660e..15f3b866 100644--- a/tests/perf/NrConcurrentCreateExperiment.cpp+++ b/tests/perf/NrConcurrentCreateExperiment.cpp@@ -4,6 +4,7 @@#include <thread>#include <dxgi1_4.h>#include <d3d12sdklayers.h>+#include "veyra/gfx/PresentSink.h"// E2. Foreground Feature18 Evaluate and background independent Feature18// Create/Evaluate/Release share one device, one queue and one snippet session.@@ -11,7 +12,9 @@// CLI: runtime-dir output-dir duration-seconds create-count concurrent|serialint wmain(int argc,wchar_t** argv) {using namespace nrperf;- if(argc!=6)return 2;+ if(argc!=6&&argc!=7)return 2;+ const bool actualPresent=argc==7&&std::wstring_view(argv[6])==L"present";+ if(argc==7&&!actualPresent)return 2;const unsigned seconds=unsigned(_wtoi(argv[3])),count=unsigned(_wtoi(argv[4]));const bool concurrent=std::wstring_view(argv[5])==L"concurrent";if(!seconds||seconds>240||!count||count>50)return 2;@@ -27,6 +30,11 @@ int wmain(int argc,wchar_t** argv) {double maxForegroundGap=0;uint64_t after=0;std::ofstream csv(out/L"background.csv");csv<<"cycle,w,h,createMs,evaluateOK,releaseOK,vramLive,vramReleased\n";{+ gfx::PresentSink sink;+ if(actualPresent){gfx::PresentSink::Desc desc;desc.width=1920;desc.height=1080;+ desc.vsync=false;desc.tearing=false;desc.title=L"Veyra owned concurrent NR experiment";Status status;+ if(!sink.initialize(s.device.device(),s.device.directQueue(),desc,status))return 2;}+ std::ofstream presentCsv;if(actualPresent){presentCsv.open(out/L"present.csv");presentCsv<<"sequence,presentCount,returnedMs,intervalMs,evalGpuMs\n";}Feature foreground(s),background(s); // Parameter tracking is mutated only on this thread.if(!foreground.create(s.ring,1920,1080)||!foreground.textures(s.ring,1920,1080,1920,1080))return 2;for(unsigned i=0;i<30;++i)if(!foreground.evaluate(s.ring,1920,1080,i==0))return 2;@@ -57,14 +65,32 @@ int wmain(int argc,wchar_t** argv) {std::thread thread;if(concurrent)thread=std::thread(worker);else worker();auto next=nowMs(),previous=next;- while(!failed.load()&&nowMs()-start<double(seconds)*1000.0){+ const auto foregroundStart=actualPresent?next:start;+ while(!failed.load()&&nowMs()-foregroundStart<double(seconds)*1000.0){if(!foreground.evaluate(s.ring,1920,1080,false)){failed=true;break;}+ if(actualPresent){+ bool closed=false;if(!sink.processMessages(closed)||closed){failed=true;break;}+ Status status;uint32_t slot;auto* list=s.ring.acquireNext(slot,status);+ auto* buffer=sink.currentBackBuffer();+ if(!list||!buffer){failed=true;break;}+ foreground.states.transition(list,foreground.output.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);+ foreground.states.transition(list,buffer,D3D12_RESOURCE_STATE_COPY_DEST);+ list->CopyResource(buffer,foreground.output.Get());+ foreground.states.transition(list,foreground.output.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ foreground.states.transition(list,buffer,D3D12_RESOURCE_STATE_PRESENT);+ if(!s.ring.submitAndSignal(slot)||!sink.present(status)){failed=true;break;}+ }++foregroundEvaluated;const auto current=nowMs();maxForegroundGap=std::max(maxForegroundGap,current-previous);previous=current;+ if(actualPresent){+ static double last=0;+ presentCsv<<foregroundEvaluated<<','<<sink.presentCount()<<','<<current<<','<<(last?current-last:0)<<','<<foreground.lastGpuEvaluateMs<<'\n';presentCsv.flush();last=current;+ }next+=1000.0/60.0;if(next>nowMs())std::this_thread::sleep_for(std::chrono::duration<double,std::milli>(next-nowMs()));else next=nowMs();}if(thread.joinable())thread.join();+ if(actualPresent){s.ring.drainQueue();sink.shutdown();}const auto actual=foreground.read(s.ring);// Static input history is warmed for 30 frames before the worker.// Save actual and reference pixels even if the model keeps changing.diff --git a/tests/perf/NrPrewarmExperiment.cpp b/tests/perf/NrPrewarmExperiment.cppnew file mode 100644index 00000000..5cccdabe--- /dev/null+++ b/tests/perf/NrPrewarmExperiment.cpp@@ -0,0 +1,68 @@+#include "veyra/engine/PreviewGpuSession.h"+#include "veyra/engine/GraphDescription.h"+#include "veyra/source/MediaFileSource.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/RuntimePaths.h"+#include <d3d12sdklayers.h>+#include <chrono>+#include <fstream>+#include <iostream>++// First-use equality: prepared features have never been evaluated. Readbacks+// belong to this fixture, after measured GPU completion, never playback.+int wmain(int argc,wchar_t** argv){+ using namespace veyra;using Clock=std::chrono::steady_clock;+ if(argc!=5)return 2;const bool enabled=std::wstring_view(argv[3])==L"on";+ if(!enabled&&std::wstring_view(argv[3])!=L"off")return 2;+ const std::wstring group=argv[4];if(group!=L"nr"&&group!=L"sr"&&group!=L"srnr")return 2;+ const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);+ Logger::instance().openFile((out/L"engine.log").wstring());+ Microsoft::WRL::ComPtr<ID3D12Debug> debugLayer;+ if(FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugLayer))))return 2;+ debugLayer->EnableDebugLayer();+ engine::EffectChain chain;chain.nodeCount=1;chain.nodes[0].type=engine::EffectType::NrEnhance;+ chain.nodes[0].enabled=group!=L"sr";chain.nodes[0].nr.temporal=false;chain.nodes[0].nr.sizePolicy=pipeline::NrSizePolicy::Realtime;+ engine::EnhancementSettings settings;engine::fromChain(chain,settings);settings.multiplier=1;+ settings.sr=group!=L"nr";settings.videoSrQuality=0;settings.srTarget=pipeline::SrTarget::Uhd4K;+ engine::PreviewGpuSession session;bool pass=true,ready=false;+ const auto prewarmStart=Clock::now();+ if(enabled){ready=session.prepare(settings,1920,1080);pass=ready;}+ const auto prewarmMs=std::chrono::duration<double,std::milli>(Clock::now()-prewarmStart).count();+ pass=pass&&session.graph->metrics().nrEvaluateCount==0&&session.graph->metrics().srEvaluateCount==0;+ source::MediaFileSource source;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;+ if(!source.open(open)||source.info().width!=1920||source.info().height!=1080)return 2;+ settings.revision=31; // A source open always receives a new revision.+ engine::StageRequest request;request.width=1920;request.height=1080;request.nr=settings.nr;request.sr=settings.sr;+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ const auto openStart=Clock::now();pass=pass&&session.initialize();+ const bool adopted=pass&&session.adopt(settings,desc);+ if(!adopted)pass=pass&&session.graph->initialize(desc)&&session.graph->createViews();+ pass=pass&&adopted==enabled;+ const auto createMs=std::chrono::duration<double,std::milli>(Clock::now()-openStart).count();+ std::ofstream csv(out/L"frames.csv");csv<<"frame,width,height,nrEvaluations,srEvaluations\n";+ double firstGpuCompleteMs=-1;+ for(unsigned frame=0;frame<3&&pass;++frame){+ pipeline::FramePacket packet;const AVFrame* input=nullptr;pipeline::EnhanceGraph::FrameOutputs output;+ pass=source.read(packet,&input)==source::SourceReadStatus::Frame&&+ session.graph->process(input,packet.pts.toDouble()*1000,frame==0,output,packet.sequence,&packet.colorInfo)&&session.ring.waitIdle();+ if(frame==0)firstGpuCompleteMs=std::chrono::duration<double,std::milli>(Clock::now()-openStart).count();+ sink::RgbaImage image;if(pass)pass=sink::readRgba8(session.context,session.ring,session.graph->videoFrameResource(output.videoSlot),image);+ if(pass){std::ofstream file(out/(L"frame-"+std::to_wstring(frame)+L".rgba"),std::ios::binary);+ file.write(reinterpret_cast<const char*>(image.pixels.data()),std::streamsize(image.pixels.size()));+ csv<<frame<<','<<image.width<<','<<image.height<<','<<session.graph->metrics().nrEvaluateCount<<','<<session.graph->metrics().srEvaluateCount<<'\n';csv.flush();}+ }+ pass=pass&&session.graph->metrics().nrEvaluateCount==unsigned(settings.nr?3:0)&&session.graph->metrics().srEvaluateCount==unsigned(settings.sr?3:0);+ source.close();session.ring.drainQueue();session.graph->shutdown();pass=session.core.close("native-prewarm-test")&&pass;+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;+ if(FAILED(session.context.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;+ for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){SIZE_T n=0;debug->GetMessage(i,nullptr,&n);+ std::vector<unsigned char> bytes(n);auto* message=reinterpret_cast<D3D12_MESSAGE*>(bytes.data());+ if(FAILED(debug->GetMessage(i,message,&n)))return 2;+ if(message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<message->pDescription<<std::endl;}}+ const auto removed=session.context.device()->GetDeviceRemovedReason();debug.Reset();session.shutdown();+ pass=pass&&errors==0&&SUCCEEDED(removed);+ std::cout<<"PREWARM_RESULT pass="<<pass<<" enabled="<<enabled<<" ready="<<ready<<" adopted="<<adopted+ <<" prewarmMs="<<prewarmMs<<" createMs="<<createMs<<" firstGpuCompleteMs="<<firstGpuCompleteMs+ <<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;+ return pass?0:1;+}diff --git a/tests/perf/NrRecentCacheExperiment.cpp b/tests/perf/NrRecentCacheExperiment.cppindex cb1ccbec..d2b6b631 100644--- a/tests/perf/NrRecentCacheExperiment.cpp+++ b/tests/perf/NrRecentCacheExperiment.cpp@@ -23,7 +23,10 @@ std::string sha(const std::vector<uint8_t>& pixels){BCRYPT_ALG_HANDLE alg=nullpt}int wmain(int argc,wchar_t** argv){using namespace veyra;using Clock=std::chrono::steady_clock;- if(argc!=3)return 2;const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);+ if(argc!=3&&argc!=4)return 2;+ const std::wstring group=argc==4?argv[3]:L"nr";+ if(group!=L"nr"&&group!=L"sr"&&group!=L"srnr")return 2;+ const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);Logger::instance().openFile((out/L"engine.log").wstring());gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;gfx::DeviceContextDesc device;device.enableDebugLayer=true;@@ -38,25 +41,30 @@ int wmain(int argc,wchar_t** argv){std::ofstream csv(out/L"cache.csv");csv<<"cycle,nr,hit,createMs,vramBefore,vramLive,graphBytes,nrEvaluations,sourceFrame,sha256\n";bool pass=true;unsigned hits=0;for(unsigned cycle=0;cycle<50&&pass;++cycle){- const bool nr=cycle%2==0;engine::EffectChain chain;chain.nodeCount=1;+ const bool active=cycle%2==0,nr=active&&group!=L"sr",sr=active&&group!=L"nr";+ engine::EffectChain chain;chain.nodeCount=1;chain.nodes[0].type=engine::EffectType::NrEnhance;chain.nodes[0].enabled=nr;chain.nodes[0].nr.temporal=false;chain.nodes[0].nr.sizePolicy=pipeline::NrSizePolicy::Realtime;engine::EnhancementSettings settings;engine::fromChain(chain,settings);settings.revision=cycle+1;settings.multiplier=1;- engine::StageRequest request;request.width=1920;request.height=1080;request.nr=nr;+ settings.sr=sr;settings.videoSrQuality=0;settings.srTarget=pipeline::SrTarget::Uhd4K;+ engine::StageRequest request;request.width=1920;request.height=1080;request.nr=nr;request.sr=sr;pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);desc.enableNvofStandalone=nr;desc.enableFg=false;desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();if(!ring.drainQueue())return 2;if(graph){- if(enabled&&engine::RecentGraphCache::eligible(priorDesc)&&engine::RecentGraphCache::effectsOff(desc)&&+ // SR admission is experimental here; production remains single NR+ // until fresh-vs-retained hidden history is proven pixel identical.+ const bool mayRetain=group==L"nr"?engine::RecentGraphCache::eligible(priorDesc):prior.sr;+ if(enabled&&mayRetain&&engine::RecentGraphCache::effectsOff(desc)&&cache.retain(graph,engine::RecentGraphCache::key(prior,{},priorDesc),graphBytes)){}else{graph->shutdown();graph.reset();}}const auto cachedBytes=cache.bytes();bool hit=false;const auto before=memory();const auto start=Clock::now();- if(enabled&&nr)graph=cache.take(engine::RecentGraphCache::key(settings,{},desc));+ if(enabled&&active)graph=cache.take(engine::RecentGraphCache::key(settings,{},desc));if(graph){hit=true;graphBytes=cachedBytes;pass=graph->applySettings(settings);++hits;}else{- if(nr)cache.evict("new-enhancement-key");+ if(active)cache.evict("new-enhancement-key");graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,cache.hasCachedGraph()?nullptr:&core);pass=graph->initialize(desc);const auto after=memory();graphBytes=after>before?after-before:0;}@@ -74,11 +82,12 @@ int wmain(int argc,wchar_t** argv){if(pass&&frame==2)pass=sink::readRgba8(ctx,ring,graph->videoFrameResource(output.videoSlot),image);}const auto nrDelta=graph->metrics().nrEvaluateCount-priorMetrics.nrEvaluateCount;- pass=pass&&nrDelta==unsigned(nr?3:0);+ const auto srDelta=graph->metrics().srEvaluateCount-priorMetrics.srEvaluateCount;+ pass=pass&&nrDelta==unsigned(nr?3:0)&&srDelta==unsigned(sr?3:0);const auto hash=sha(image.pixels);pass=pass&&!hash.empty();if(pass&&(cycle==0||cycle==1||cycle==2||cycle==18||cycle==20||cycle==30||cycle==48||cycle==49)){std::ofstream f(out/(L"frame-"+std::to_wstring(cycle)+L".rgba"),std::ios::binary);f.write(reinterpret_cast<const char*>(image.pixels.data()),std::streamsize(image.pixels.size()));}- csv<<cycle<<','<<nr<<','<<hit<<','<<createMs<<','<<before<<','<<live<<','<<graphBytes<<','<<nrDelta<<','<<sequence<<','<<hash<<'\n';csv.flush();+ csv<<cycle<<','<<active<<','<<hit<<','<<createMs<<','<<before<<','<<live<<','<<graphBytes<<','<<nrDelta<<','<<sequence<<','<<hash<<'\n';csv.flush();std::cout<<"CACHE_CYCLE i="<<cycle<<" hit="<<hit<<" createMs="<<createMs<<" pass="<<pass<<std::endl;prior=settings;priorDesc=desc;}