Skip to content

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: evict NGX core on release failures and preserve matched 63-75 percent rebuild gains

Veyra Goal Agent3e28be0b94a8
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d4be51c8..e54cd46d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1014,6 +1014,14 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionT
target_compile_features(veyra_nr_rebuild_benchmark PRIVATE cxx_std_20)
target_compile_options(veyra_nr_rebuild_benchmark PRIVATE /utf-8)
target_link_libraries(veyra_nr_rebuild_benchmark PRIVATE veyra_engine)
+ add_executable(veyra_nr_static_input_experiment tests/perf/NrStaticInputExperiment.cpp)
+ target_compile_features(veyra_nr_static_input_experiment PRIVATE cxx_std_20)
+ target_compile_options(veyra_nr_static_input_experiment PRIVATE /utf-8)
+ target_link_libraries(veyra_nr_static_input_experiment PRIVATE veyra_engine bcrypt)
+ 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)
+ target_link_libraries(veyra_nr_core_cache_contract_tests PRIVATE veyra_engine)
target_compile_features(veyra_nr_temporal_gpu_tests PRIVATE cxx_std_20)
target_link_libraries(veyra_nr_temporal_gpu_tests PRIVATE veyra_pipeline)
add_executable(veyra_gpu_timing_tests tests/integration/GpuTimingTests.cpp)
diff --git a/docs/PERF_2A_CORE_REUSE_2026-10-04.md b/docs/PERF_2A_CORE_REUSE_2026-10-04.md
index 3b148ed5..e7ea2412 100644
--- a/docs/PERF_2A_CORE_REUSE_2026-10-04.md
+++ b/docs/PERF_2A_CORE_REUSE_2026-10-04.md
@@ -21,3 +21,22 @@
先只在同设备、同 runtime、同 NR 模块与相同补帧配置下保留 NGX 核心;功能及参数仍释放。设备移除、初始化失败、运行库/补帧配置改变或未释放参数均清空核心。Ada/Ampere 补丁会话先保持完整原流程,待实卡验证后再扩大。候选必须支持同一二进制 `VEYRA_TEST_DISABLE_NGX_CORE_REUSE=1` 对照,参数销毁与最终核心关闭顺序必须可核对。
候选将核心所有者放在 EngineController 的设备会话中,Graph 使用共享借用;缓存仅一份,借用者未释放时拒绝下一次 prepare,旧图全部参数释放且设备正常才 retain。普通 Graph 消费者默认不启用。NR 适配器仍每次重建加载/释放,是否允许在保留核心时重新 Init_Ext 必须实测。benchmark 通过显式缓存注入测试,B-off 同一 EXE 环境开关;最终关闭发生在设备销毁之前。此时尚未测得收益;上述时间全部是优化前数据。
+
+## 第一候选 A / B / B-off 结果
+
+`fbaffeb10158d3bea63f53b1d913b18182e694f1`,全新479步构建exit0。四组各20次×三轮,B12/12、同一B EXE关闭缓存12/12有效;合计A/B/B-off720次重建。下表排除每进程第一次冷创建,取每轮暖创建中位数,再取三轮中位;NR开只取开的时候,避免把基础播放器的39ms混入。
+
+| 组 | A ms | B ms | B-off ms | 对A减少 |
+|---|---:|---:|---:|---:|
+| NR开 | 1569.510 | 386.758 | 1563.090 | 75.36% |
+| SR开关 | 1409.580 | 415.158 | 1580.430 | 70.55% |
+| 1/2/3层 | 1456.600 | 544.314 | 1701.260 | 62.63% |
+| 原生/720/480 | 1348.730 | 403.039 | 1596.630 | 70.12% |
+
+逐轮完整输出240张对A相同,B-off240张也相同;A自身重复一致。没有用PSNR容差掩盖像素差异,相同像素数学上PSNR=∞、SSIM=1;这不是尚未执行的视频编码导出比较。每轮Core Init/Shutdown:NR组A及B-off10/10、其他组20/20,B所有组1/1,liveParameters=0、漏参数警告0、debug0、设备正常。证据 `B2a-rebuild-v1-comparison.json` 及三组原始目录。
+
+限制:B首次冷创建仍约1.99–2.50秒;多层暖创建P95仍约0.7–0.85秒,不能宣称全体低于0.6秒。B-off SR/层数/尺寸比早些运行A慢,保留原始范围;未采逐秒频率的native v1不能归因CPU/GPU时钟,不用该差额虚增收益。NR开组同构对照1563ms与1569ms吻合。
+
+核心保留会保留运行库内部资源,SR组释放图后的DXGI使用量约605MiB,A/B-off末周期约175MiB,额外缓存要明确报告;其他组缓存使用量更低。20次内B每周期增长小于A,不声称所有显存完全释放。后续补最终Core close显存及生命周期拒绝检查。还未做真实UI/导出/其他GPU验收。
+
+审查后的第二候选为功能release结果、参数destroy结果和SEH建立健康状态;任何失败不缓存,初始化早于Core借用失败也清理旧缓存。此补充尚未实测,不将v1的成功证据替代修订后验收。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index afb2c786..4b53e43d 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,11 @@
# Veyra 工作记录
+## 2026-10-04 NR优化2a:三组实测有收益,补生命周期拒绝检查
+
+- fbaffeb候选全新build-B2a-v1 479步exit0。A/B/B-off四组各20×三轮,720次重建36/36 native有效;对A三轮暖创建中位:NR开1569.510→386.758ms(-75.36%),SR1409.580→415.158(-70.55%),层数1456.600→544.314(-62.63%),尺寸1348.730→403.039(-70.12%)。B-off分别1563.090/1580.430/1701.260/1596.630,后几组时钟未采不能解释慢于A,不用差额虚增收益。
+- `nr-rebuild-report.py A-rebuild-v1 B2a-rebuild-v1 B2a-off-rebuild-v1` exit0:候选及off每240张全像素与A一致,A自身0噪声。CoreInit每轮A/off10或20,B1;最终CoreShutdown1、无漏参数、debug0设备正常。v1首冷1.99–2.50sec,多层暖P95仍0.7–0.85sec,没有全体<0.6sec或无缝Present证明。SR核心保留约605MiB,旧A/off末周期约175MiB,不能隐藏缓存显存。
+- 增加Core参数释放healthy状态、各NGX功能release bool/SEH结果,失败不保留;初始化早期失败也清理旧Core。准备实际SDK64参数表边界/活动借用拒绝/早期失败重开检查及20UI请求驱动;诊断读回仅测试。另准备1a同自然像素300次实际NR/SR输出测量,尚未测或实施重复帧跳过。
+
## 2026-10-04 NR优化2a:设备会话核心缓存候选
- A-baseline commit181e4ab/tag与增量bundle验证后,添加render线程限定NgxCoreCache、Graph可选借用和Engine设备会话生命周期。无缓存的所有现有Graph构造调用维持完整原流程。核心key含设备/规范绝对runtime/NR模块/补帧开关后端倍率;设备错误、失败、参数残留或key变化完整关闭。Ada/Ampere补丁型号主动不缓存。
diff --git a/include/veyra/ngx/DlssFgBackend.h b/include/veyra/ngx/DlssFgBackend.h
index 3c607eee..e2658bd2 100644
--- a/include/veyra/ngx/DlssFgBackend.h
+++ b/include/veyra/ngx/DlssFgBackend.h
@@ -86,7 +86,7 @@ public:
const CreateDesc& desc,
Status& status);
- void release();
+ bool release();
// Evaluates DLSSG for one real frame on the given command list. With 2X,
// the runtime writes the frame interpolated between the previous and the
diff --git a/include/veyra/ngx/DlssSrBackend.h b/include/veyra/ngx/DlssSrBackend.h
index 49fc616e..89e17650 100644
--- a/include/veyra/ngx/DlssSrBackend.h
+++ b/include/veyra/ngx/DlssSrBackend.h
@@ -52,7 +52,7 @@ public:
const CreateDesc& desc,
Status& status);
- void release();
+ bool release();
// Evaluates SR for one frame on the given command list.
bool evaluate(ID3D12GraphicsCommandList* cmdList,
diff --git a/include/veyra/ngx/NgxCoreHost.h b/include/veyra/ngx/NgxCoreHost.h
index 8cf24173..a93cb18d 100644
--- a/include/veyra/ngx/NgxCoreHost.h
+++ b/include/veyra/ngx/NgxCoreHost.h
@@ -35,6 +35,7 @@ public:
bool initialized() const { return initialized_; }
uint64_t initResult() const { return initResult_; }
uint32_t liveParameterBlockCount() const { return liveParameterBlockCount_; }
+ bool healthy() const { return initialized_ && healthy_; }
// Parameter blocks are tracked; shutdown() destroys any still-live block
// before core Shutdown1 (defense in depth; consumers should destroy them
@@ -44,6 +45,7 @@ public:
private:
bool initialized_ = false;
+ bool healthy_ = false;
ID3D12Device* device_ = nullptr; // non-owning; consumer owns the device
uint64_t initResult_ = 0;
NVSDK_NGX_Parameter* liveParameterBlocks_[64] = {};
diff --git a/include/veyra/ngx/TrueHdrBackend.h b/include/veyra/ngx/TrueHdrBackend.h
index 2845ff7b..4710cb76 100644
--- a/include/veyra/ngx/TrueHdrBackend.h
+++ b/include/veyra/ngx/TrueHdrBackend.h
@@ -11,7 +11,7 @@ public:
~TrueHdrBackend(){release();}
bool create(NgxCoreHost&,ID3D12GraphicsCommandList*,const std::wstring& runtimeDirectory);
bool evaluate(ID3D12GraphicsCommandList*,ID3D12Resource* sdr,ID3D12Resource* scrgb,const engine::VideoHdrSettings&);
- void release();
+ bool release();
private:
NgxCoreHost* core_=nullptr;
NVSDK_NGX_Parameter* params_=nullptr;
diff --git a/include/veyra/ngx/VideoSrBackend.h b/include/veyra/ngx/VideoSrBackend.h
index 46746f16..9f0de000 100644
--- a/include/veyra/ngx/VideoSrBackend.h
+++ b/include/veyra/ngx/VideoSrBackend.h
@@ -10,7 +10,7 @@ public:
~VideoSrBackend(){release();}
bool create(NgxCoreHost&,ID3D12GraphicsCommandList*);
bool evaluate(ID3D12GraphicsCommandList*,ID3D12Resource*,ID3D12Resource*,unsigned);
- void release();
+ bool release();
private:
NgxCoreHost* core_=nullptr;
NVSDK_NGX_Parameter* params_=nullptr;
diff --git a/scripts/perf/nr-core-ui.py b/scripts/perf/nr-core-ui.py
new file mode 100644
index 00000000..03d31647
--- /dev/null
+++ b/scripts/perf/nr-core-ui.py
@@ -0,0 +1,56 @@
+"""20 real UI requests per switch family, isolated profiles and raw evidence."""
+from pathlib import Path
+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','sr','layers','sizes','fg','runtime']
+assert all(x.replace('-','').isalnum() for x in (variant,label))
+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')
+shutil.copy2(ROOT/'scripts/perf/nr-core-ui.qml',app/'qml/Veyra/NrCoreUiProbe.qml')
+main=app/'qml/Veyra/Main.qml';text=main.read_text(encoding='utf-8');at=text.rfind('}')
+loader='\n Loader {source:"NrCoreUiProbe.qml"; onLoaded:{const r=new XMLHttpRequest();r.open("GET","'+(app/'core-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:
+ assert group in ('nr','sr','layers','sizes','fg','runtime')
+ name=label+'-'+group;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'}),encoding='utf-8')
+ (app/'core-run.json').write_text(json.dumps({'media':str(matrix.SOURCES['M1']).replace('\\','/'),'group':group}),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')
+ if variant.endswith('-off'):env['VEYRA_TEST_DISABLE_NGX_CORE_REUSE']='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()
+ with (out/'console.log').open('xb') as log:
+ try:rc=subprocess.run(command,cwd=app,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=280).returncode
+ except subprocess.TimeoutExpired:rc=124
+ text=(out/'player.log').read_text(encoding='utf-8',errors='replace')
+ settled=[json.loads(line.split('CORE_UI_SETTLED ',1)[1]) for line in text.splitlines() if 'CORE_UI_SETTLED ' in line]
+ resets=[{k:float(v) for k,v in re.findall(r'(\w+)=(-?\d+(?:\.\d+)?)',line)} for line in text.splitlines() if '[reset-lifecycle]' in line]
+ result={'variant':variant,'group':group,'exeSha256':matrix.digest(app/'veyra_qml_ui.exe'),
+ 'nrSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),'command':command,'exitCode':rc,
+ 'wallSeconds':time.monotonic()-start,'gpuBefore':before,'gpuAfter':matrix.gpu_query(),
+ 'settledRequests':settled,'actualResetEvents':resets,'coreInitCalls':text.count('core-host: Init_with_ProjectID result='),
+ 'coreShutdownCalls':text.count('core-host: Shutdown1 result='),'cacheHits':text.count('[ngx-core-cache] event=hit'),
+ 'passed':rc==0 and len(settled)==20 and 'CORE_UI_PASS' in text and not any(s in text for s in ('CORE_UI_FAIL','[ERROR]','[FATAL]','leaked parameter block','ReferenceError:','TypeError:')),
+ 'measurement':'Real UI requests and CPU-observed reset lifecycle; bridge settling includes snapshot polling, not scanout'}
+ results.append(result);(out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
+ print('RESULT',name,{k:result[k] for k in ('exitCode','wallSeconds','coreInitCalls','cacheHits','passed')},flush=True)
+ if not result['passed']:
+ print('\n'.join(text.splitlines()[-30:]),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-core-ui.qml b/scripts/perf/nr-core-ui.qml
new file mode 100644
index 00000000..edeb5b19
--- /dev/null
+++ b/scripts/perf/nr-core-ui.qml
@@ -0,0 +1,87 @@
+import QtQuick
+
+// Owned test loader: uses only the existing public QML bridge, no input hooks.
+Item {
+ id: probe
+ property string media: ""
+ property string group: "nr"
+ property bool started: false
+ property int cycle: 0
+ property bool awaiting: false
+ property double changeAt: 0
+ property double startedAt: Date.now()
+ property double settledAt: 0
+ property bool targetOn: true
+ property int targetLayers: 1
+ property int targetPolicy: 0
+ property int targetRuntime: 0
+ function require(value, why) {
+ if (!value) { console.log("CORE_UI_FAIL", why); Qt.exit(3) }
+ }
+ function change() {
+ targetOn = group === "nr" ? cycle % 2 === 1 : cycle % 2 === 0
+ if (group === "nr") veyra.nrEnabled = targetOn
+ if (group === "sr") veyra.srEnabled = targetOn
+ if (group === "fg") veyra.fgEnabled = targetOn
+ if (group === "runtime") {
+ targetRuntime = cycle % 2 ? 0 : 2
+ require(veyra.setNrLayerParameter(veyra.nrLayers[0].index, "runtime", targetRuntime), "runtime request")
+ }
+ if (group === "sizes") {
+ targetPolicy = [1, 3, 2][cycle % 3]
+ require(veyra.setNrLayerParameter(veyra.nrLayers[0].index, "sizePolicy", targetPolicy), "size request")
+ }
+ if (group === "layers") {
+ targetLayers = 1 + (cycle + 1) % 3
+ for (let i=0; i<veyra.nrLayers.length; ++i)
+ require(veyra.setEffectEnabled(veyra.nrLayers[i].index, i < targetLayers), "enable layer")
+ }
+ changeAt = Date.now(); awaiting = true
+ console.log("CORE_UI_CHANGE", JSON.stringify({group:group, cycle:cycle, on:targetOn,
+ layers:targetLayers, policy:targetPolicy, runtime:targetRuntime, position:veyra.position}))
+ }
+ function matches() {
+ if (group === "nr") return veyra.nrActive === targetOn
+ if (group === "sr") return veyra.nrActive && veyra.srActive === targetOn
+ if (group === "fg") return veyra.nrActive && veyra.fgActive === targetOn
+ if (group === "runtime") return veyra.nrActive && veyra.nrLayers[0].runtime === targetRuntime
+ if (group === "sizes") return veyra.nrActive && veyra.nrLayers[0].sizePolicy === targetPolicy
+ if (group === "layers") return veyra.nrActive && veyra.nrLayers.filter(x=>x.enabled).length === targetLayers
+ return veyra.nrActive
+ }
+ Timer {
+ interval: 200; running: true; repeat: true
+ onTriggered: {
+ require(!veyra.failed, "engine failure")
+ require(Date.now()-probe.startedAt < 250000, "timeout")
+ if (!probe.started) {
+ probe.started = true
+ veyra.muted = true; veyra.lowLatency = false
+ veyra.nrEnabled = true; veyra.srEnabled = false; veyra.fgEnabled = false
+ veyra.videoHdr = false; veyra.colorEnabled = false; veyra.videoSrQuality = 0
+ veyra.srTargetIndex = 2; veyra.fgBackendName = "dlss"; veyra.fgMultiplier = 2
+ while (veyra.nrLayers.length < (probe.group === "layers" ? 3 : 1))
+ require(veyra.duplicateNrLayer(veyra.nrLayers[0].index)>=0,"duplicate NR")
+ for (let i=0;i<veyra.nrLayers.length;++i) {
+ require(veyra.setNrLayerParameter(veyra.nrLayers[i].index,"temporal",0),"temporal")
+ require(veyra.setNrLayerParameter(veyra.nrLayers[i].index,"sizePolicy",0),"initial size")
+ require(veyra.setEffectEnabled(veyra.nrLayers[i].index,i===0),"initial enable")
+ }
+ veyra.openPath(probe.media)
+ return
+ }
+ if (!veyra.running || veyra.applying || veyra.position <= 0) return
+ if (probe.awaiting) {
+ if (!probe.matches()) return
+ console.log("CORE_UI_SETTLED", JSON.stringify({group:probe.group,cycle:probe.cycle,
+ observedBridgeMs:Date.now()-probe.changeAt, position:veyra.position, nr:veyra.nrActive,
+ sr:veyra.srActive,fg:veyra.fgActive,layers:veyra.nrLayers,detail:veyra.runStatusDetail}))
+ probe.awaiting = false; probe.settledAt = Date.now(); ++probe.cycle
+ if (probe.cycle>=20) {console.log("CORE_UI_PASS",probe.group);Qt.quit();return}
+ }
+ if (veyra.position>45) {veyra.seekTo(0);return}
+ if (Date.now()-probe.settledAt<600) return
+ probe.change()
+ }
+ }
+}
diff --git a/scripts/perf/nr-rebuild-report.py b/scripts/perf/nr-rebuild-report.py
new file mode 100644
index 00000000..b9ed1b17
--- /dev/null
+++ b/scripts/perf/nr-rebuild-report.py
@@ -0,0 +1,61 @@
+"""Compare immutable per-run receipts, rebuild samples and complete frame hashes."""
+from pathlib import Path
+import csv
+import json
+import statistics
+import sys
+
+BASE=Path('E:/项目/Veyra/logs/perf-nr-20261004')
+labels=sys.argv[1:4]
+assert len(labels)==3 and all(x.replace('-','').isalnum() for x in labels)
+groups=('nr','sr','layers','sizes')
+all_runs={label:json.loads((BASE/(label+'-summary.json')).read_text(encoding='utf-8')) for label in labels}
+def aggregate(samples):
+ return {'medianOfRunMedians':statistics.median(samples),'minRunMedian':min(samples),'maxRunMedian':max(samples)}
+report={'labels':labels,'groups':{},'measurement':'CPU creation includes necessary GPU waits; no actual Present; full-frame hashes'}
+passed=True
+for group in groups:
+ reference=next(r for r in all_runs[labels[0]] if r['group']==group and r['repeat']==1)
+ variants={}
+ for label,runs in all_runs.items():
+ rr=[r for r in runs if r['group']==group]
+ assert len(rr)==3
+ measurements=[];differing=0;checks=[]
+ for run in rr:
+ assert run['passed'] and run['sourceSha256']==reference['sourceSha256'] and run['nrSha256']==reference['nrSha256']
+ differing+=sum(run['frameHashes'][name]!=sha for name,sha in reference['frameHashes'].items())
+ out=BASE/f"{label}-{group}-r{run['repeat']}"
+ rows=list(csv.DictReader((out/'rebuild.csv').open()))
+ assert len(rows)==20
+ # First creation remains reported in raw/all-cycle samples, but
+ # a warm-switch comparison must not hide its separate cold cost.
+ subsets={'all':rows,'warm':rows[1:]}
+ if group=='nr':subsets.update({'nr-on':[r for r in rows if int(r['nr'])],
+ 'nr-on-warm':[r for r in rows[1:] if int(r['nr'])],
+ 'nr-off':[r for r in rows if not int(r['nr'])]})
+ measurements.append({name:{key:statistics.median(float(r[key]) for r in selected)
+ for key in ('createMs','destroyMs','totalMs','vramLive','vramAfter')}
+ for name,selected in subsets.items()})
+ engine=(out/'engine.log').read_text(encoding='utf-8',errors='replace')
+ checks.append({'repeat':run['repeat'],'coreInitCalls':engine.count('core-host: Init_with_ProjectID result='),
+ 'coreShutdownCalls':engine.count('core-host: Shutdown1 result='),
+ 'cacheHits':engine.count('[ngx-core-cache] event=hit'),
+ 'leakedParameterWarnings':engine.count('leaked parameter block'),
+ 'coldCreateMs':float(rows[0]['createMs']),
+ 'vramAfterLastCycleBytes':int(rows[-1]['vramAfter'])})
+ metrics={name:{key:aggregate([m[name][key] for m in measurements]) for key in measurements[0][name]}
+ for name in measurements[0]}
+ variants[label]={'metrics':metrics,'differingFramesAgainstA':differing,'comparedFrames':60,
+ 'identicalPixelsPsnr':'inf' if differing==0 else 'requires per-pixel comparison',
+ 'identicalPixelsSsim':1 if differing==0 else None,'lifecycle':checks}
+ passed&=differing==0 and all(c['leakedParameterWarnings']==0 for c in checks)
+ report['groups'][group]=variants
+report['pixelAndParameterChecksPassed']=passed
+out=BASE/(labels[1]+'-comparison.json')
+with out.open('x',encoding='utf-8') as f:json.dump(report,f,ensure_ascii=False,indent=2)
+for g,v in report['groups'].items():
+ subset='nr-on-warm' if g=='nr' else 'warm'
+ print(g,{label:{'create':r['metrics'][subset]['createMs'],'differentFrames':r['differingFramesAgainstA'],
+ 'coreInitCalls':[c['coreInitCalls'] for c in r['lifecycle']]} for label,r in v.items()})
+print('PIXEL_PARAMETER_CHECK',passed,out)
+raise SystemExit(0 if passed else 1)
diff --git a/scripts/perf/nr-static.py b/scripts/perf/nr-static.py
new file mode 100644
index 00000000..2bc852b4
--- /dev/null
+++ b/scripts/perf/nr-static.py
@@ -0,0 +1,49 @@
+"""Real SDK/static-input output contract, before any 1a product optimization."""
+from pathlib import Path
+import csv
+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];modes=sys.argv[3:] or ['nr','nr-temporal','srnr','sr','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)
+exe=app/'veyra_nr_static_input_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)
+results=[]
+for mode in modes:
+ assert mode in ('nr','nr-temporal','srnr','sr','off')
+ for repeat in range(1,4):
+ 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),VEYRA_VERBOSE_FRAME_LOGS='1')
+ command=[str(exe),str(matrix.SOURCES['M1']),str(out),mode]
+ print('START',name,flush=True);start=time.monotonic()
+ with (out/'console.log').open('xb') as log:
+ try:rc=subprocess.run(command,cwd=app,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=280).returncode
+ except subprocess.TimeoutExpired:rc=124
+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace')
+ rows=list(csv.DictReader((out/'frames.csv').open())) if (out/'frames.csv').exists() else []
+ changes=[int(r['frame']) for r in rows if r['equalFirst']=='0']
+ result={'variant':variant,'mode':mode,'repeat':repeat,'exeSha256':matrix.digest(exe),
+ 'nrSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),'sourceSha256':matrix.digest(matrix.SOURCES['M1']),
+ 'command':command,'exitCode':rc,'wallSeconds':time.monotonic()-start,'frameCount':len(rows),
+ 'differentOutputFramesToFirst':len(changes),'firstDifferentFrame':changes[0] if changes else None,
+ 'sha256Sequence':[r['sha256'] for r in rows],
+ 'safetyPassed':rc==0 and len(rows)==300 and 'RESULT safetyPass=1' in text and 'debugErrors=0 deviceRemoved=0' in text,
+ 'reuseFirstOutputIsByteIdentical':not changes,'measurement':'Actual product graph; static natural input; diagnostic readbacks excluded from process timing'}
+ results.append(result);(out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
+ print('RESULT',name,{k:result[k] for k in ('exitCode','differentOutputFramesToFirst','firstDifferentFrame','safetyPassed')},flush=True)
+ if not result['safetyPassed']:
+ print('\n'.join(text.splitlines()[-30:]),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/src/ngx/DlssFgBackend.cpp b/src/ngx/DlssFgBackend.cpp
index b34b0cbf..0c2e877e 100644
--- a/src/ngx/DlssFgBackend.cpp
+++ b/src/ngx/DlssFgBackend.cpp
@@ -266,11 +266,13 @@ bool DlssFgBackend::create(NgxCoreHost& coreHost,
return true;
}
-void DlssFgBackend::release()
+bool DlssFgBackend::release()
{
+ bool ok=true;
if (handle_ != nullptr) {
uint32_t sehCode = 0;
const NVSDK_NGX_Result result = CallReleaseDlssg(handle_, sehCode);
+ ok=result==NVSDK_NGX_Result_Success&&sehCode==0;
(result == NVSDK_NGX_Result_Success ? log::info : log::error)("ngx", std::format("fg-backend: ReleaseFeature result={} evaluates={} resets={}",
ngxResultString(static_cast<uint64_t>(result)), evaluateCount_, resetCount_));
if (sehCode != 0) {
@@ -278,6 +280,7 @@ void DlssFgBackend::release()
}
handle_ = nullptr;
}
+ return ok;
}
bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
diff --git a/src/ngx/DlssSrBackend.cpp b/src/ngx/DlssSrBackend.cpp
index 54fa6455..97f9b528 100644
--- a/src/ngx/DlssSrBackend.cpp
+++ b/src/ngx/DlssSrBackend.cpp
@@ -17,6 +17,12 @@ namespace veyra::ngx {
namespace {
+__declspec(noinline) NVSDK_NGX_Result CallReleaseDlss(NVSDK_NGX_Handle* handle,uint32_t& sehCode){
+ sehCode=0;
+ __try{return NVSDK_NGX_D3D12_ReleaseFeature(handle);}
+ __except(EXCEPTION_EXECUTE_HANDLER){sehCode=uint32_t(GetExceptionCode());return NVSDK_NGX_Result_FAIL_PlatformError;}
+}
+
__declspec(noinline) NVSDK_NGX_Result CallCreateDlss(
ID3D12GraphicsCommandList* cmdList,
unsigned int creationNodeMask,
@@ -123,14 +129,17 @@ bool DlssSrBackend::create(NgxCoreHost& coreHost,
return true;
}
-void DlssSrBackend::release()
+bool DlssSrBackend::release()
{
+ bool ok=true;
if (handle_ != nullptr) {
// SR is a core NGX feature; release through the core API.
- const NVSDK_NGX_Result result = NVSDK_NGX_D3D12_ReleaseFeature(handle_);
- (result == NVSDK_NGX_Result_Success ? log::info : log::error)("ngx", std::format("sr-backend: ReleaseFeature result={}", ngxResultString(static_cast<uint64_t>(result))));
+ uint32_t seh=0;const auto result=CallReleaseDlss(handle_,seh);
+ ok=result==NVSDK_NGX_Result_Success&&seh==0;
+ (ok ? log::info : log::error)("ngx", std::format("sr-backend: ReleaseFeature result={} seh={}", ngxResultString(static_cast<uint64_t>(result)),seh));
handle_ = nullptr;
}
+ return ok;
}
bool DlssSrBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
diff --git a/src/ngx/NgxCoreCache.cpp b/src/ngx/NgxCoreCache.cpp
index b57c46e4..a8c1ea59 100644
--- a/src/ngx/NgxCoreCache.cpp
+++ b/src/ngx/NgxCoreCache.cpp
@@ -32,7 +32,7 @@ bool NgxCoreCache::prepare(Key key, bool enabled) {
std::shared_ptr<NgxCoreHost> NgxCoreCache::borrow() {
if (!enabled_ || !core_) return {};
- if (!core_->initialized() || core_->liveParameterBlockCount() != 0 ||
+ if (!core_->healthy() || core_->liveParameterBlockCount() != 0 ||
!key_.device || FAILED(key_.device->GetDeviceRemovedReason())) {
(void)close("invalid-core-or-parameters");
return {};
@@ -42,7 +42,7 @@ std::shared_ptr<NgxCoreHost> NgxCoreCache::borrow() {
}
void NgxCoreCache::publish(const std::shared_ptr<NgxCoreHost>& core) {
- if (!enabled_ || !core || !core->initialized()) return;
+ if (!enabled_ || !core || !core->healthy()) return;
if (core_ && core_ != core) {
log::error("ngx-core-cache", "event=refused-publish different core already retained");
return;
diff --git a/src/ngx/NgxCoreHost.cpp b/src/ngx/NgxCoreHost.cpp
index f211b104..0f12fda7 100644
--- a/src/ngx/NgxCoreHost.cpp
+++ b/src/ngx/NgxCoreHost.cpp
@@ -135,6 +135,7 @@ bool NgxCoreHost::initialize(ID3D12Device* device,
}
device_ = device;
initialized_ = true;
+ healthy_ = true;
veyra::log::info("ngx", "core-host: initialized (single core session for this device)");
return true;
}
@@ -159,6 +160,7 @@ void NgxCoreHost::shutdown()
device_ = nullptr;
initialized_ = false;
+ healthy_ = false;
}
NVSDK_NGX_Parameter* NgxCoreHost::allocateParameters(Status& status)
@@ -169,6 +171,7 @@ NVSDK_NGX_Parameter* NgxCoreHost::allocateParameters(Status& status)
return nullptr;
}
if (liveParameterBlockCount_ >= 64) {
+ healthy_ = false;
status = Status::InvalidArgument;
veyra::log::error("ngx", "core-host: parameter block tracking table full");
return nullptr;
@@ -176,10 +179,11 @@ NVSDK_NGX_Parameter* NgxCoreHost::allocateParameters(Status& status)
NVSDK_NGX_Parameter* parameters = nullptr;
uint32_t allocSeh = 0;
const NVSDK_NGX_Result result = CallAllocateParameters(&parameters, allocSeh);
- if (result != NVSDK_NGX_Result_Success || parameters == nullptr) {
+ if (result != NVSDK_NGX_Result_Success || parameters == nullptr || allocSeh != 0) {
+ healthy_ = false;
status = Status::DeviceFailure;
- veyra::log::error("ngx", std::format("core-host: AllocateParameters result={}",
- veyra::ngxResultString(static_cast<uint64_t>(result))));
+ veyra::log::error("ngx", std::format("core-host: AllocateParameters result={} seh={}",
+ veyra::ngxResultString(static_cast<uint64_t>(result)),allocSeh));
return nullptr;
}
liveParameterBlocks_[liveParameterBlockCount_++] = parameters;
@@ -200,9 +204,15 @@ void NgxCoreHost::destroyParameters(NVSDK_NGX_Parameter* parameters)
}
}
if (!tracked) {
+ healthy_ = false;
veyra::log::warn("ngx", "core-host: destroyParameters for an untracked block");
}
- { uint32_t seh = 0; (void)CallDestroyParameters(parameters, seh); }
+ uint32_t seh = 0;
+ const auto result=CallDestroyParameters(parameters,seh);
+ if(result!=NVSDK_NGX_Result_Success||seh!=0){
+ healthy_=false;
+ log::error("ngx",std::format("core-host: DestroyParameters result={} seh={}",ngxResultString(uint64_t(result)),seh));
+ }
}
} // namespace veyra::ngx
diff --git a/src/ngx/TrueHdrBackend.cpp b/src/ngx/TrueHdrBackend.cpp
index 4f2ab3ba..94e17f89 100644
--- a/src/ngx/TrueHdrBackend.cpp
+++ b/src/ngx/TrueHdrBackend.cpp
@@ -83,9 +83,11 @@ bool TrueHdrBackend::evaluate(ID3D12GraphicsCommandList* list,ID3D12Resource* in
unsigned seh=0;const auto result=invoke(1,list,params_,&handle_,seh);
const bool ok=report(1,result,seh,first_);first_=false;return ok;
}
-void TrueHdrBackend::release(){
- if(handle_){unsigned seh=0;const auto r=invoke(2,nullptr,params_,&handle_,seh);report(2,r,seh);handle_=nullptr;}
+bool TrueHdrBackend::release(){
+ bool ok=true;
+ if(handle_){unsigned seh=0;const auto r=invoke(2,nullptr,params_,&handle_,seh);ok=report(2,r,seh);handle_=nullptr;}
if(params_&&core_)core_->destroyParameters(params_);params_=nullptr;core_=nullptr;
if(module_)FreeLibrary(module_);module_=nullptr;first_=true;
+ return ok;
}
}
diff --git a/src/ngx/VideoSrBackend.cpp b/src/ngx/VideoSrBackend.cpp
index 5cbfbf98..006d1a3d 100644
--- a/src/ngx/VideoSrBackend.cpp
+++ b/src/ngx/VideoSrBackend.cpp
@@ -34,8 +34,10 @@ bool VideoSrBackend::evaluate(ID3D12GraphicsCommandList* list,ID3D12Resource* in
params_->Set("VSR.QualityLevel",quality);
unsigned seh=0;auto r=invoke(1,list,params_,&handle_,seh);return result(1,r,seh);
}
-void VideoSrBackend::release(){
- if(handle_){unsigned seh=0;auto r=invoke(2,nullptr,params_,&handle_,seh);result(2,r,seh);handle_=nullptr;}
+bool VideoSrBackend::release(){
+ bool ok=true;
+ if(handle_){unsigned seh=0;auto r=invoke(2,nullptr,params_,&handle_,seh);ok=result(2,r,seh);handle_=nullptr;}
if(params_&&core_)core_->destroyParameters(params_);params_=nullptr;core_=nullptr;
+ return ok;
}
}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 0c04fefb..59f9fc12 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -3089,6 +3089,7 @@ void EnhanceGraph::shutdown()
for(auto& input:hardwareInputFrames_)input.reset();
Status st = Status::Ok;
if (nv12Ctx_ != nullptr) { sws_freeContext(nv12Ctx_); nv12Ctx_ = nullptr; }
+ bool featuresReleased=true;
// Release every layer's handle before the session goes away. The snippet
// requires release before Shutdown1, and each handle was created on this
@@ -3097,7 +3098,8 @@ void EnhanceGraph::shutdown()
layer->amd.reset(); // drain HIP while the borrowed graph input/queue still exist
if(layer->handle()==nullptr)continue;
uint64_t layerResult=0;uint32_t layerSeh=0;
- (void)nrAdapter_->snippetReleaseFeature(layer->handle(),layerResult,layerSeh);
+ const bool safe=nrAdapter_->snippetReleaseFeature(layer->handle(),layerResult,layerSeh);
+ featuresReleased=featuresReleased&&safe&&layerResult==uint64_t(NVSDK_NGX_Result_Success)&&layerSeh==0;
layer->setHandle(nullptr);
}
gpuDis_.reset();
@@ -3109,10 +3111,11 @@ void EnhanceGraph::shutdown()
upFsrSrDepth_.Reset();
fsrFgBackend_.reset();
vfgBackend_.reset();
- if (fgBackend_) fgBackend_->release();
- if(videoSrBackend_){videoSrBackend_->release();videoSrBackend_.reset();}
+ if (fgBackend_) featuresReleased=fgBackend_->release()&&featuresReleased;
+ if(videoSrBackend_){featuresReleased=videoSrBackend_->release()&&featuresReleased;videoSrBackend_.reset();}
+ if(videoHdrBackend_)featuresReleased=videoHdrBackend_->release()&&featuresReleased;
videoHdrBackend_.reset();videoHdrInput_.Reset();videoHdrOutput_.Reset();
- if (srBackend_) srBackend_->release();
+ if (srBackend_) featuresReleased=srBackend_->release()&&featuresReleased;
// NVOF teardown in THREE phases (ownership rule proven by t10-L0-r2):
// a. unregisterAll() while the textures are still alive;
@@ -3154,7 +3157,7 @@ void EnhanceGraph::shutdown()
nrAdapter_->restoreCallerCompatibility();
nrAdapter_->unload();
}
- const bool retainCore=coreCache_&&coreCache_->owns(coreHost_)&&initialized_&&
+ const bool retainCore=coreCache_&&coreCache_->owns(coreHost_)&&initialized_&&featuresReleased&&coreHost_->healthy()&&
failedBackend_==engine::FailedBackend::None&&SUCCEEDED(context_.device()->GetDeviceRemovedReason())&&
coreHost_->liveParameterBlockCount()==0;
if(retainCore){
@@ -3165,6 +3168,10 @@ void EnhanceGraph::shutdown()
if(coreCache_&&coreCache_->owns(coreHost_)){
coreHost_.reset();(void)coreCache_->close("graph-failure-or-device-removed");
}else coreHost_->shutdown();
+ }else if(coreCache_&&(!initialized_||failedBackend_!=engine::FailedBackend::None)){
+ // A failure before NGX initialization can still leave the previous
+ // clean core in this device session; do not carry it through recovery.
+ (void)coreCache_->close("graph-failed-before-core-borrow");
}
// Restore the DLSS-G runtime image only after the NGX core released the
// feature (the unlock is process memory only; the file on disk is untouched).
diff --git a/tests/perf/NrCoreCacheContractTests.cpp b/tests/perf/NrCoreCacheContractTests.cpp
new file mode 100644
index 00000000..d3026fe9
--- /dev/null
+++ b/tests/perf/NrCoreCacheContractTests.cpp
@@ -0,0 +1,55 @@
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/engine/GraphDescription.h"
+#include "veyra/engine/EffectChain.h"
+#include "veyra/ngx/NgxCoreCache.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/RuntimePaths.h"
+#include "veyra/Log.h"
+#include <iostream>
+#include <array>
+
+// Real GPU + SDK lifetime exercises. Intentional rejected operations below
+// are caller contract tests; they do not simulate a real TDR or SDK failure.
+int wmain(){
+ using namespace veyra;
+ Logger::instance().openFile((runtime::logsDirectory()/L"core-cache-contract.log").wstring());
+ 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;
+ ngx::NgxCoreCache cache;pipeline::EnhanceGraph graph(ctx,ring,&cache);
+ engine::EnhancementSettings settings;settings.nr=true;settings.multiplier=1;
+ engine::StageRequest request;request.width=1920;request.height=1080;request.nr=true;
+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);
+ desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ desc.enableNvofStandalone=true;desc.enableFg=false;
+ bool pass=graph.initialize(desc)&&graph.createViews();
+ // A second graph/core must never be initialized through this cache while
+ // a successful first graph still borrows the core.
+ ngx::NgxCoreCache::Key key;key.device=ctx.device();key.runtimeDirectory=desc.runtimeAbsPath;
+ const bool activeRefused=!cache.prepare(key,true);
+ pass=pass&&activeRefused;std::cout<<"CONTRACT activeBorrowRefused="<<activeRefused<<std::endl;
+ graph.shutdown();
+ auto core=cache.borrow();pass=pass&&bool(core)&&core->liveParameterBlockCount()==0;
+ std::array<NVSDK_NGX_Parameter*,64> parameters{};
+ for(auto& p:parameters){if(!core){pass=false;break;}p=core->allocateParameters(status);pass=pass&&p!=nullptr;}
+ auto* rejected=core?core->allocateParameters(status):nullptr;
+ const bool capacityRefused=core&&rejected==nullptr&&!core->healthy();pass=pass&&capacityRefused;
+ if(rejected)core->destroyParameters(rejected);
+ if(core)for(auto p:parameters)if(p)core->destroyParameters(p);
+ pass=pass&&core&&core->liveParameterBlockCount()==0;core.reset();
+ const bool unhealthyEvicted=!cache.borrow();pass=pass&&unhealthyEvicted;
+ std::cout<<"CONTRACT capacityRefused="<<capacityRefused<<" unhealthyEvicted="<<unhealthyEvicted<<std::endl;
+ pass=pass&&graph.initialize(desc)&&graph.createViews();graph.shutdown();
+ // Failure before initNgxFeatures/borrow must also close the previous core.
+ SetEnvironmentVariableW(L"VEYRA_TEST_NR_INIT_FAILURE",L"1");
+ const bool earlyFailed=!graph.initialize(desc);graph.shutdown();
+ SetEnvironmentVariableW(L"VEYRA_TEST_NR_INIT_FAILURE",nullptr);
+ const bool earlyEvicted=!cache.borrow();pass=pass&&earlyFailed&&earlyEvicted;
+ std::cout<<"CONTRACT earlyFailure="<<earlyFailed<<" previousCoreEvicted="<<earlyEvicted<<std::endl;
+ pass=pass&&graph.initialize(desc)&&graph.createViews();graph.shutdown();
+ pass=cache.close("contract-final-close")&&pass;
+ ring.drainQueue();const auto removed=ctx.device()->GetDeviceRemovedReason();pass=pass&&SUCCEEDED(removed);
+ std::cout<<"RESULT pass="<<pass<<" deviceRemoved="<<unsigned(removed)<<std::endl;
+ return pass?0:1;
+}
diff --git a/tests/perf/NrRebuildBenchmark.cpp b/tests/perf/NrRebuildBenchmark.cpp
index 535512ec..2191418b 100644
--- a/tests/perf/NrRebuildBenchmark.cpp
+++ b/tests/perf/NrRebuildBenchmark.cpp
@@ -97,5 +97,6 @@ int wmain(int argc,wchar_t** argv){
if(m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<m->pDescription<<std::endl;}}
const auto removed=ctx.device()->GetDeviceRemovedReason();
std::cout<<"RESULT pass="<<(pass&&errors==0&&SUCCEEDED(removed))<<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;
+ std::cout<<"MEMORY afterFinalCoreClose="<<usage()<<std::endl;
return pass&&errors==0&&SUCCEEDED(removed)?0:1;
}
diff --git a/tests/perf/NrStaticInputExperiment.cpp b/tests/perf/NrStaticInputExperiment.cpp
new file mode 100644
index 00000000..6dd249c7
--- /dev/null
+++ b/tests/perf/NrStaticInputExperiment.cpp
@@ -0,0 +1,101 @@
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/engine/GraphDescription.h"
+#include "veyra/engine/EffectChain.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 <bcrypt.h>
+#include <d3d12sdklayers.h>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <array>
+#include <algorithm>
+#include <chrono>
+
+// Counterexample/measurement for plan 1a: the actual graph receives the same
+// decoded natural image 300 times with genuine increasing PTS/sequence.
+// No candidate shader or invented motion/model substitutes are used here.
+namespace {
+std::string sha256(const std::vector<uint8_t>& pixels){
+ BCRYPT_ALG_HANDLE alg=nullptr;BCRYPT_HASH_HANDLE hash=nullptr;
+ std::array<unsigned char,32> digest{};
+ if(BCryptOpenAlgorithmProvider(&alg,BCRYPT_SHA256_ALGORITHM,nullptr,0)<0)return {};
+ const bool ok=BCryptCreateHash(alg,&hash,nullptr,0,nullptr,0,0)>=0&&
+ BCryptHashData(hash,const_cast<PUCHAR>(pixels.data()),ULONG(pixels.size()),0)>=0&&
+ BCryptFinishHash(hash,digest.data(),ULONG(digest.size()),0)>=0;
+ if(hash)BCryptDestroyHash(hash);BCryptCloseAlgorithmProvider(alg,0);
+ if(!ok)return {};const char digits[]="0123456789abcdef";std::string text;
+ for(auto b:digest){text+=digits[b>>4];text+=digits[b&15];}return text;
+}
+}
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra;
+ if(argc!=4)return 2;
+ const std::wstring mode=argv[3];
+ if(mode!=L"nr"&&mode!=L"nr-temporal"&&mode!=L"srnr"&&mode!=L"sr"&&mode!=L"off")return 2;
+ const bool nr=mode!=L"off"&&mode!=L"sr",sr=mode==L"srnr"||mode==L"sr";
+ 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;
+ 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;
+ // NR temporal control is the real product implementation; model/runtime
+ // state may advance even when that optional control is disabled.
+ engine::EffectChain chain;chain.nodeCount=1;chain.nodes[0].type=engine::EffectType::NrEnhance;
+ chain.nodes[0].enabled=nr;chain.nodes[0].nr.temporal=mode==L"nr-temporal";
+ chain.nodes[0].nr.sizePolicy=pipeline::NrSizePolicy::Realtime;
+ engine::EnhancementSettings settings;engine::fromChain(chain,settings);
+ settings.sr=sr;settings.videoSrQuality=0;settings.srTarget=pipeline::SrTarget::Uhd4K;
+ settings.multiplier=1;
+ engine::StageRequest request;request.width=media.info().width;request.height=media.info().height;request.nr=nr;request.sr=sr;
+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);
+ desc.enableNvofStandalone=nr||sr;desc.enableFg=false;desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ pipeline::EnhanceGraph graph(ctx,ring); // deliberately no core cache
+ if(!graph.initialize(desc)||!graph.createViews())return 2;
+ std::ofstream csv(out/L"frames.csv");csv<<"frame,ptsMs,sha256,equalFirst,equalPrevious,differentBytesToFirst,maeToFirst,processCpuWithWaitMs\n";
+ std::vector<uint8_t> first,previous;unsigned differing=0;bool pass=true;
+ const unsigned snapshots[]={0,1,2,4,8,16,32,64,127,255,299};
+ for(unsigned i=0;i<300&&pass;++i){
+ pipeline::EnhanceGraph::FrameOutputs output;const auto start=std::chrono::steady_clock::now();
+ pass=graph.process(input,(i+1)*1000.0/60,i==0,output,i+1,&packet.colorInfo)&&ring.waitIdle();
+ const double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count();
+ sink::RgbaImage image;if(pass)pass=sink::readRgba8(ctx,ring,graph.videoFrameResource(output.videoSlot),image);
+ if(!pass)break;
+ if(i==0)first=image.pixels;
+ const bool equalFirst=first==image.pixels,equalPrevious=i==0||previous==image.pixels;
+ uint64_t differentBytes=0,absolute=0;
+ for(size_t b=0;b<first.size();++b){differentBytes+=first[b]!=image.pixels[b];absolute+=unsigned(std::abs(int(first[b])-int(image.pixels[b])));}
+ differing+=!equalFirst;
+ const auto hash=sha256(image.pixels);if(hash.empty()){pass=false;break;}
+ csv<<i<<','<<(i+1)*1000.0/60<<','<<hash<<','<<equalFirst<<','<<equalPrevious<<','<<differentBytes<<','<<double(absolute)/first.size()<<','<<ms<<'\n';csv.flush();
+ if(std::find(std::begin(snapshots),std::end(snapshots),i)!=std::end(snapshots)){
+ std::ofstream f(out/(L"frame-"+std::to_wstring(i)+L".rgba"),std::ios::binary);
+ f.write(reinterpret_cast<const char*>(image.pixels.data()),std::streamsize(image.pixels.size()));
+ }
+ previous=std::move(image.pixels);
+ if(i%60==0)std::cout<<"FRAME "<<i<<" equalFirst="<<equalFirst<<" differentBytes="<<differentBytes<<" size="<<image.width<<'x'<<image.height<<std::endl;
+ }
+ const auto metrics=graph.metrics();
+ pass=pass&&metrics.nrEvaluateCount==(nr?300u:0u)&&metrics.srEvaluateCount==(sr?300u:0u);
+ ring.drainQueue();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();
+ std::cout<<"RESULT safetyPass="<<(pass&&errors==0&&SUCCEEDED(removed))<<" differentOutputFrames="<<differing
+ <<" nrEvaluations="<<metrics.nrEvaluateCount<<" srEvaluations="<<metrics.srEvaluateCount
+ <<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;
+ // Exit success means the measurement is valid, not that reuse is valid.
+ return pass&&errors==0&&SUCCEEDED(removed)?0:1;
+}