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++

test(perf): quantify existing independent NR layer dimensions

Veyra Goal Agent725a6c5ac1ff
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 69b78ae7..e6743fed 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1048,6 +1048,10 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionT
target_compile_features(veyra_nr_graph_queue_experiment PRIVATE cxx_std_20)
target_compile_options(veyra_nr_graph_queue_experiment PRIVATE /utf-8)
target_link_libraries(veyra_nr_graph_queue_experiment PRIVATE veyra_engine)
+ add_executable(veyra_nr_mixed_resolution_experiment tests/perf/NrMixedResolutionExperiment.cpp)
+ target_compile_features(veyra_nr_mixed_resolution_experiment PRIVATE cxx_std_20)
+ target_compile_options(veyra_nr_mixed_resolution_experiment PRIVATE /utf-8)
+ target_link_libraries(veyra_nr_mixed_resolution_experiment PRIVATE veyra_engine)
add_executable(veyra_nr_queue_migration_experiment tests/perf/NrQueueMigrationExperiment.cpp)
target_compile_features(veyra_nr_queue_migration_experiment PRIVATE cxx_std_20)
target_compile_options(veyra_nr_queue_migration_experiment PRIVATE /utf-8)
diff --git a/scripts/perf/nr-mixed-native.py b/scripts/perf/nr-mixed-native.py
new file mode 100644
index 00000000..9bebf89e
--- /dev/null
+++ b/scripts/perf/nr-mixed-native.py
@@ -0,0 +1,58 @@
+"""Full-frame determinism/seek proof and inspectable existing-size tradeoffs."""
+from pathlib import Path
+import csv,importlib.util,json,os,shutil,subprocess,sys,time,math
+import numpy as np
+from PIL import Image,ImageDraw
+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()
+folder=BASE/'logs'/TASK/(label+'-summary');folder.mkdir(parents=True,exist_ok=False)
+app=matrix.stage(variant,label);exe=app/'veyra_nr_mixed_resolution_experiment.exe'
+shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)
+identity={str(p.relative_to(app)):matrix.digest(p) for p in app.rglob('*') if p.is_file() and p.suffix.lower() in ('.exe','.dll','.qml')}
+(folder/'artifacts.json').write_text(json.dumps(identity,ensure_ascii=False,indent=2),encoding='utf-8')
+results=[];frameGroups={}
+for group in ('none','2-native','2-mixed','3-native','3-mixed'):
+ for repeat in range(1,(2 if group=='none' else 3)):
+ name=f'{label}-{group}-r{repeat}';out=BASE/'tests'/TASK/name;out.mkdir(parents=True,exist_ok=False)
+ tmp=BASE/'tmp'/TASK/name;tmp.mkdir(parents=True,exist_ok=False)
+ env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_QUICK_BACKEND','QSG_RHI_BACKEND'))}
+ env.update(TEMP=str(tmp),TMP=str(tmp),VEYRA_VERBOSE_FRAME_LOGS='1');matrix.assert_gpu_tests_idle()
+ print('START',name,flush=True);start=time.monotonic()
+ with (out/'console.log').open('x',encoding='utf-8') as stream:
+ proc=subprocess.run([str(exe),str(matrix.SOURCES['M1']),str(out),group],cwd=app,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=250)
+ console=(out/'console.log').read_text(encoding='utf-8',errors='replace')
+ log=(out/'engine.log').read_text(encoding='utf-8',errors='replace')
+ passValue=proc.returncode==0 and 'NR_MIXED_RESULT pass=1 frames=40 debugErrors=0 deviceRemoved=0' in console and '[ERROR]' not in log
+ receipt={'name':name,'group':group,'repeat':repeat,'passed':passValue,'exitCode':proc.returncode,'wallSeconds':time.monotonic()-start,
+ 'exeSha256':matrix.digest(exe),'runtimeSha256':identity['runtime/experimental/nvngx_dlssnr.dll'],'sourceSha256':matrix.digest(matrix.SOURCES['M1']),
+ 'sourceCommit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD']).decode().strip(),'plan':next((l for l in console.splitlines() if l.startswith('NR_MIXED_PLAN ')),None)}
+ (out/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf-8');results.append(receipt)
+ (folder/'completed.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8');assert passValue,receipt
+ with (out/'frames.csv').open(encoding='utf-8') as stream:frames=list(csv.DictReader(stream))
+ assert len(frames)==40 and {int(f['epoch']) for f in frames}=={1,2} and int(frames[20]['pts100ns'])>=100000000
+ if group in frameGroups:assert frames==frameGroups[group],'Same configuration re-run differs'
+ else:frameGroups[group]=frames
+quality=BASE/'tests'/TASK/(label+'-quality');quality.mkdir(parents=True,exist_ok=False)
+comparisons=[];html=['<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>4b逐层尺寸画面对照</title><style>body{background:#18191c;color:#eee;font-family:system-ui;margin:24px}.pair{display:flex;gap:12px}figure{margin:0;flex:1}img{width:100%}p{color:#bbc1ca}a{color:#9abaff}</style><h1>既有逐层尺寸 · 画面对照</h1><p>左:每层1080p;右:先降低前层,末层1080p。不同配置会改变画面。PSNR只描述差异,不能证明画质更好。所有图来自同一产品实际完整输出;未获用户画质确认。点击打开全尺寸PNG。</p>']
+for count in (2,3):
+ rows=[];sheet=Image.new('RGB',(960,4*292),(24,25,28));draw=ImageDraw.Draw(sheet)
+ for index,frame in enumerate((0,1,19,20,21,39)):
+ paths=[BASE/'tests'/TASK/f'{label}-{count}-{mode}-r1'/f'frame-{frame}.png' for mode in ('native','mixed')]
+ images=[np.asarray(Image.open(p).convert('RGBA'),dtype=np.int16) for p in paths];assert images[0].shape==images[1].shape==(1080,1920,4)
+ diff=images[1]-images[0];assert np.count_nonzero(diff[:,:,3])==0
+ mse=float(np.mean(diff[:,:,:3].astype(np.float64)**2));row={'frame':frame,'changedRgbPixelsPercent':float(np.any(diff[:,:,:3]!=0,axis=2).mean()*100),
+ 'maxRgb8':int(np.abs(diff[:,:,:3]).max()),'psnrRgb8Db':10*math.log10(255**2/mse) if mse else None,'alphaDifferentPixels':0}
+ psnrLabel=f'{row["psnrRgb8Db"]:.2f}dB' if mse else '完全一致'
+ rows.append(row);html.append(f'<h2>{count}层 · 输出帧{frame}</h2><p>变化像素 {row["changedRgbPixelsPercent"]:.2f}% · PSNR {psnrLabel} · 最大RGB8差 {row["maxRgb8"]}</p><div class="pair">')
+ for p,caption in zip(paths,('所有层1080p','前层降低,末层1080p')):html.append(f'<figure><figcaption>{caption}</figcaption><a href="{p.as_uri()}"><img src="{p.as_uri()}"></a></figure>')
+ html.append('</div>')
+ if frame in (0,19,20,39):
+ sheetIndex=(0,19,20,39).index(frame);draw.text((4,sheetIndex*292+4),f'{count} layers / frame {frame}: full 1080 | mixed',fill='white')
+ for x,p in enumerate(paths):sheet.paste(Image.open(p).convert('RGB').resize((480,270)),(x*480,sheetIndex*292+22))
+ sheet.save(quality/f'{count}-comparison.png');comparisons.append({'layers':count,'frames':rows})
+html.append('</html>');(quality/'review.html').write_text('\n'.join(html),encoding='utf-8')
+assert all(matrix.digest(app/name)==sha for name,sha in identity.items());matrix.assert_gpu_tests_idle()
+(folder/'summary.json').write_text(json.dumps({'results':results,'completeRgbaFrames':360,'sameConfigurationDifferences':0,'seekPairs':8,'comparisons':comparisons,
+ 'payloadUnchanged':True,'humanQualityApproval':False,'diagnosticReadbackOnly':True},ensure_ascii=False,indent=2),encoding='utf-8')
+print('MIXED_NATIVE_COMPLETE',len(results),flush=True)
diff --git a/scripts/perf/nr-mixed-normal.py b/scripts/perf/nr-mixed-normal.py
new file mode 100644
index 00000000..678dcf99
--- /dev/null
+++ b/scripts/perf/nr-mixed-normal.py
@@ -0,0 +1,50 @@
+"""Matched normal playback: existing per-layer dimensions, no test GPU load."""
+from pathlib import Path
+import importlib.util,json,statistics,sys,re
+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]
+folder=BASE/'logs'/TASK/(label+'-summary');folder.mkdir(parents=True,exist_ok=False)
+matrix.assert_gpu_tests_idle();app=matrix.stage(variant,label)
+payload={str(p.relative_to(app)):matrix.digest(p) for p in app.rglob('*') if p.is_file() and p.suffix.lower() in ('.exe','.dll','.qml')}
+(folder/'artifacts.json').write_text(json.dumps(payload,ensure_ascii=False,indent=2),encoding='utf-8')
+results=[]
+for count in (2,3):
+ for repeat in range(1,4):
+ for mode in (('native','mixed') if repeat%2 else ('mixed','native')):
+ group=f'{count}-{mode}';setting='MIX-'+group
+ policies=[0]*count if mode=='native' else ([3,0] if count==2 else [2,3,0])
+ matrix.CONFIGS[setting]={'layers':count,'policies':policies,'temporal':False,'sr':False}
+ name=f'{label}-{group}-r{repeat}';print('START',name,flush=True)
+ matrix.run(variant,'M1',setting,name,50,gpuPriority=2,stageLabel=label)
+ receiptPath=BASE/'logs'/TASK/name/'result.json';receipt=json.loads(receiptPath.read_text(encoding='utf-8'))
+ log=(receiptPath.parent/'player.log').read_text(encoding='utf-8',errors='replace')
+ assert receipt['gpuPriority']['applied'] and not receipt['testEnv']
+ configLine=next(line for line in log.splitlines() if 'NR_PERF_CONFIG ' in line)
+ actual=json.loads(configLine.split('NR_PERF_CONFIG ',1)[1]);assert [n['sizePolicy'] for n in actual['layers']]==policies
+ keys=('gpuNrP95Ms','gpuResidualP95Ms','gpuFlowP95Ms','enhancementProcessingMs','gpuReadyP95Ms')
+ skips=[int(value) for value in re.findall(r'previewSkipped=(\d+)',log)]
+ submits=[{k:int(v) for k,v in re.findall(r'(\w+)=(-?\d+)',line)} for line in log.splitlines() if '[submit]' in line]
+ submits=[s for s in submits if 100000000<=s.get('pts100ns',-1)<=480000000]
+ intervals=sorted((b['host100ns']-a['host100ns'])/10000 for a,b in zip(submits,submits[1:]));assert len(intervals)>100
+ meters=json.loads((receiptPath.parent/'meters.json').read_text(encoding='utf-8'))
+ row={'name':name,'group':group,'repeat':repeat,'receipt':str(receiptPath),'maxPreviewSkipped':max(skips,default=0),
+ 'presentIntervalsMs':{'p99':intervals[int(len(intervals)*.99)],'max':max(intervals),'count':len(intervals)},
+ 'gpuMemoryMiBPeak':max(float(m['gpu']['memoryMiB']) for m in meters if 'memoryMiB' in m['gpu']),
+ 'cpuOneCoreMedianPercent':statistics.median(m['cpuPercentOneCoreScale'] for m in meters),
+ 'actualLayers':actual['layers'],'stallLines':[line for line in log.splitlines() if '[engine-stall]' in line],
+ 'metrics':{k:receipt['summary'][k]['medianOfRollingObservations'] for k in keys}}
+ results.append(row);(folder/'completed.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8')
+ print('MIXED_NORMAL_RESULT',json.dumps(row,ensure_ascii=False),flush=True)
+summary={}
+for group in ('2-native','2-mixed','3-native','3-mixed'):
+ rows=[r for r in results if r['group']==group]
+ values={key:[r['metrics'][key] for r in rows] for key in rows[0]['metrics']}
+ values.update(presentP99Ms=[r['presentIntervalsMs']['p99'] for r in rows],presentMaxMs=[r['presentIntervalsMs']['max'] for r in rows],
+ gpuMemoryMiBPeak=[r['gpuMemoryMiBPeak'] for r in rows],cpuOneCoreMedianPercent=[r['cpuOneCoreMedianPercent'] for r in rows],
+ maxPreviewSkipped=[r['maxPreviewSkipped'] for r in rows])
+ summary[group]={key:{'median':statistics.median(v),'min':min(v),'max':max(v),'runs':v} for key,v in values.items()}
+assert all(matrix.digest(app/name)==sha for name,sha in payload.items()),'Product payload mutated';matrix.assert_gpu_tests_idle()
+(folder/'comparison.json').write_text(json.dumps({'runs':results,'summary':summary,'payloadUnchanged':True,'extraGpuLoad':False,
+ 'comparison':'Same unchanged product, different user-selected layer dimensions; this is not a new algorithm speedup'},ensure_ascii=False,indent=2),encoding='utf-8')
+print('MIXED_NORMAL_COMPLETE',len(results),flush=True)
diff --git a/tests/perf/NrMixedResolutionExperiment.cpp b/tests/perf/NrMixedResolutionExperiment.cpp
new file mode 100644
index 00000000..e664d406
--- /dev/null
+++ b/tests/perf/NrMixedResolutionExperiment.cpp
@@ -0,0 +1,75 @@
+#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 "veyra/FileIdentity.h"
+#include <d3d12sdklayers.h>
+#include <fstream>
+#include <iostream>
+
+// Diagnostic readback only: exercise the existing per-layer product contract.
+// It is deliberately separate from the timed, ordinary QML player runs.
+int wmain(int argc,wchar_t** argv) {
+ using namespace veyra;
+ if(argc!=4)return 2;
+ const std::wstring group=argv[3];
+ if(group!=L"none"&&group!=L"2-native"&&group!=L"2-mixed"&&group!=L"3-native"&&group!=L"3-mixed")return 2;
+ const HRESULT com=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ if(FAILED(com))return 2;
+ struct ComLifetime {~ComLifetime(){CoUninitialize();}} comLifetime;
+ 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();
+ const bool nr=group!=L"none",mixed=group.find(L"mixed")!=std::wstring::npos;
+ const unsigned count=nr?(group.front()==L'3'?3:2):0;
+ engine::EffectChain chain;chain.nodeCount=count;
+ for(unsigned i=0;i<count;++i) {
+ auto& node=chain.nodes[i];node.type=engine::EffectType::NrEnhance;node.enabled=true;
+ node.nr.temporal=false;node.nr.sizePolicy=pipeline::NrSizePolicy::Realtime;
+ if(mixed&&i+1<count)node.nr.sizePolicy=count==3&&i==0?pipeline::NrSizePolicy::P480:pipeline::NrSizePolicy::P720;
+ }
+ engine::EnhancementSettings settings;engine::fromChain(chain,settings);settings.sr=false;settings.multiplier=1;
+ engine::StageRequest request;request.width=1920;request.height=1080;request.nr=nr;
+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);
+ desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ if(!desc.fixedExecutionPlanError.empty()||(nr&&desc.nrLayersExtent.size()!=count))return 2;
+ std::cout<<"NR_MIXED_PLAN layers="<<count<<" work="<<desc.workWidth<<'x'<<desc.workHeight;
+ if(nr)for(const auto& extent:desc.nrLayersExtent)std::cout<<" nr="<<extent.width<<'x'<<extent.height;
+ std::cout<<std::endl;
+ engine::PreviewGpuSession session;
+ if(!session.initialize()||!session.graph->initialize(desc)||!session.graph->createViews())return 2;
+ source::MediaFileSource source;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;
+ if(!source.open(open))return 2;
+ std::ofstream frames(out/L"frames.csv");frames<<"frame,epoch,sequence,pts100ns,width,height,sha256\n";
+ bool pass=true;unsigned completed=0;
+ for(unsigned i=0;i<40&&pass;++i) {
+ if(i==20)pass=source.seek({10,1});
+ pipeline::FramePacket packet;const AVFrame* input=nullptr;pipeline::EnhanceGraph::FrameOutputs output;
+ pass=pass&&source.read(packet,&input)==source::SourceReadStatus::Frame&&
+ session.graph->process(input,packet.pts.toDouble()*1000,i==0||i==20,output,packet.sequence,&packet.colorInfo)&&session.ring.waitIdle();
+ sink::RgbaImage image;
+ if(pass)pass=sink::readRgba8(session.context,session.ring,session.graph->videoFrameResource(output.videoSlot),image)&&
+ image.width==1920&&image.height==1080;
+ if(pass) {
+ frames<<i<<','<<source.epoch()<<','<<packet.sequence<<','<<int64_t(packet.pts.toDouble()*10000000)<<','<<image.width<<','<<image.height<<','
+ <<sha256Hex(image.pixels.data(),image.pixels.size())<<'\n';frames.flush();
+ if(i==0||i==1||i==19||i==20||i==21||i==39)pass=sink::saveImage((out/(L"frame-"+std::to_wstring(i)+L".png")).wstring(),image);
+ if(pass)++completed;
+ }
+ }
+ source.close();session.ring.drainQueue();session.graph->shutdown();pass=session.core.close("mixed-resolution-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<<"DEBUG_ERROR "<<message->pDescription<<std::endl;}
+ }
+ const auto removed=session.context.device()->GetDeviceRemovedReason();
+ pass=pass&&completed==40&&errors==0&&SUCCEEDED(removed);debug.Reset();session.shutdown();
+ std::cout<<"NR_MIXED_RESULT pass="<<pass<<" frames="<<completed<<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;
+ return pass?0:1;
+}