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++
Instrument VFG API submission CPU cost in isolated optimization scope
Veyra Goal Agentb9394ea4e860
diff --git a/AGENTS.md b/AGENTS.mdindex fda2ca93..fed709c4 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-07 VFG专项优化授权**:用户明确“尝试优化VFG,其他的补帧暂时不动”。从已封存排查aec800e在E盘codex/vfg-optimization-20261007按docs/VFG_OPTIMIZATION_PLAN_2026-10-07.md实施VFG必要提交/互操作/专属调度及定向构建验收、本地候选;这些具体接点覆盖旧冻结。DLSS/XeSS/FSR实现与策略保持,不改NR算法、用户配置、驱动或其它工作树。独立不可变start及source-before.bundle在archives/vfg-optimization-20261007,先运行vfg-opt-control.py,不改旧guard/baseline。不派Agent、无压力/竞争负载,测试≤300秒、构建≤900秒,产物全在E盘;没有新merge/push/Release/关机授权,运行库/模型原字节保留且不进源码Git。+> **2026-10-07 2.0.5 正式发布授权**:用户明确“发布吧,2.0.5 老样子发完给我弄个群公告”。按docs/PUBLISH_2.0.5_PLAN_2026-10-07.md,仅将已测2.0.5做发布文档/元数据整理,允许本轮main合并、普通推送、v2.0.5标签、正式GitHub Release与5项资产上传;本条覆盖此前本地交付的no-push/no-Release限制。产品EXE/QML/shader/运行库/模型保持;NVIDIA显存持续增长未修复,留待下一版,不实施假说。群公告只交用户、不代发,不关机。独立start基线保护28既有工作树/495修改文件/53历史证据,先运行本轮publish-2.0.5-control.py,旧guard不修改。不派Agent、无压力/竞争负载、不改用户配置/驱动,所有产物E盘,保留双二维码width220、Discord和Ko-fi。> **2026-10-07 2.0.5 本地整合授权**:用户明确要求先将目前完成的修复合入 main,构建 2.0.5 给用户测试,显存持续增长留待下一版本详细排查。按 `docs/RELEASE_2.0.5_PLAN_2026-10-07.md` 在 E盘 `codex/release-2.0.5-20261007` 整合已测 ef2069f/4c917aa 及其调查记录,仅修改版本、文档和必要构建/定向验收/打包脚本;不实施未证实的 NR Shutdown、驱动或显存假说修复。允许本地 commit/checkpoint/main 合并和 NVIDIA/AMD 同源码测试包,不新增 push/GitHub Release/上传/关机授权。独立不可变基线 `archives/release-2.0.5-20261007/start.json` 保护27个原工作树(main只按授权推进)、495个未提交文件及14份已发布文件;先执行本轮 control,不修改旧 guard/baseline。不派Agent、不做压力/竞争负载、不改DLL/模型/驱动/用户配置;测试每进程≤300秒,构建≤900秒,全部产物统一 E:/项目/Veyra。diff --git a/docs/VFG_OPTIMIZATION_PLAN_2026-10-07.md b/docs/VFG_OPTIMIZATION_PLAN_2026-10-07.mdnew file mode 100644index 00000000..77ed83b2--- /dev/null+++ b/docs/VFG_OPTIMIZATION_PLAN_2026-10-07.md@@ -0,0 +1,11 @@+# VFG 专项优化(2026-10-07)++用户明确“尝试优化VFG,其他的补帧暂时不动”。从已封存排查 aec800e 创建 codex/vfg-optimization-20261007,工作树 E:/项目/Veyra/worktrees/vfg-optimization-20261007。上一轮25组原始日志、正式2.0.5包、main、桌面与其他工作树保持。仅VFG所需实现及其定向测试/诊断/构建/候选交付获本轮授权;不改DLSS/XeSS/FSR实现或它们的默认行为,不改NR算法、显示/驱动/用户配置,无新merge/push/Release/关机、子Agent或压力/竞争负载。++1. P0:独立不可变start基线、源码checkpoint,保护其它工作树/运行库及非VFG后端;先做可关闭的VFG各API CPU计时,用同一原GTA6片段复核阻塞调用。+2. P1:对照SDK固定样例,尝试仅必要的VFG参数/输入绑定;必须比较真实FPS、GPU成本、已就绪帧过期与像素结果,不将猜测当收益。+3. P2:如果SDK调用仍阻塞送显,VFG专用有界异步提交或安全的分段推进;保持已存在的独立呈现GPU队列、批次租约/PTS/源帧完整、producer/consumer fence、失败signal、seek/reset/退出顺序。不能增加无界队列、放宽过期阈值或放慢时钟来伪造倍率。+4. P3:需要时以VFG专用策略修正完整成本过期后的重试尖峰与输出达成状态;共享逻辑中的改动必须显式只作用VFG。其他后端的原策略/默认/文件逐字节保留。+5. P4:匹配原片4K30/原版单层1080NR/强度1/零运动/调控关/GPU普通/Auto同步/限帧关,先测Medium3/4与High2,再按效果扩大档位。GUI正常负载串行,每进程≤300秒、构建≤900秒;验证8/10-bit所有质量/倍率、切镜/reset、关闭/seek/倍率与后端切换、完整导出计数与异常回退。只承诺本机实测,不预先承诺高档8X实时。++产物统一E:/项目/Veyra/{archives,build,logs,tests,tmp,test-packages,verify}/vfg-optimization-20261007。先执行scripts/acceptance/vfg-opt-control.py,旧guard/start基线不改。各节点commit/checkpoint,负优化回退并留证据;最终提供有实测收益的本地候选与报告。源代码/运行组件严格分开,DLL/模型保持原字节。diff --git a/scripts/acceptance/vfg-opt-build.py b/scripts/acceptance/vfg-opt-build.pynew file mode 100644index 00000000..f50b287a--- /dev/null+++ b/scripts/acceptance/vfg-opt-build.py@@ -0,0 +1,26 @@+"""Isolated VFG build using the accepted 2.0.5 dependency configuration."""+from pathlib import Path+import hashlib,json,os,subprocess,sys+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-optimization-20261007'+label=sys.argv[1];assert label.replace('-','').isalnum()+BUILD=BASE/'build'/TASK;TMP=BASE/'tmp'/TASK/'build';LOG=BASE/'logs'/TASK/(label+'.log')+for p in (BUILD,TMP,LOG.parent):p.mkdir(parents=True,exist_ok=True)+guard=[sys.executable,'-B',str(ROOT/'scripts/acceptance/vfg-opt-control.py')];subprocess.run(guard,check=True)+cache=BASE/'build/release-2.0.5-20261007/standard/CMakeCache.txt';settings=[]+for line in cache.read_text(encoding='utf8').splitlines():+ if ':' not in line or '=' not in line or line.startswith(('#','//')):continue+ keytype,value=line.split('=',1);key,kind=keytype.split(':',1)+ if kind in ('INTERNAL','STATIC') or key in ('VEYRA_DISPLAY_VERSION','VEYRA_AMD_NR_TEST_GRAPH_SOURCE'):continue+ if key.startswith('VEYRA_') or key in ('CMAKE_PREFIX_PATH','CMAKE_MAKE_PROGRAM','PROTOC','PKG_CONFIG_EXECUTABLE'):+ settings.append(f'set({key} [[{value}]] CACHE {kind} "Accepted dependencies" FORCE)')+settings.append('set(VEYRA_DISPLAY_VERSION [[2.0.5-vfg-test]] CACHE STRING "Local VFG candidate" FORCE)')+(TMP/'dependencies.cmake').write_text('\n'.join(settings),encoding='utf8')+targets=sys.argv[2:] or ['veyra_qml_ui','veyra_vfg_gpu_tests','veyra_vfg_export_probe','veyra_vfg_settings_tests']+assert all(t.replace('_','').isalnum() for t in targets)+cmd=TMP/'build.cmd';cmd.write_text('@echo off\nchcp 65001 >nul\ncall "C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Auxiliary\\Build\\vcvars64.bat" >nul 2>&1\nif errorlevel 1 exit /b 4\n"%TASK_CMAKE%" --preset x64-release -S "%TASK_ROOT%" -B "%TASK_BUILD%" -C "%TASK_TMP%\\dependencies.cmake"\nif errorlevel 1 exit /b 5\n"%TASK_CMAKE%" --build "%TASK_BUILD%" --parallel 6 --target '+' '.join(targets)+'\nexit /b %errorlevel%\n',encoding='ascii')+env=os.environ.copy();env.update(TEMP=str(TMP),TMP=str(TMP),VSLANG='1033',TASK_ROOT=str(ROOT),TASK_BUILD=str(BUILD),TASK_TMP=str(TMP),TASK_CMAKE='C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe')+with LOG.open('x',encoding='utf8') as stream:+ try:rc=subprocess.run(['cmd.exe','/d','/c',str(cmd)],cwd=ROOT,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=890).returncode+ except subprocess.TimeoutExpired:rc=124+LOG.with_suffix('.json').write_text(json.dumps({'exit':rc,'targets':targets,'sourceHead':subprocess.check_output(['git','rev-parse','HEAD'],encoding='ascii').strip(),'dependencyCacheSha256':hashlib.sha256(cache.read_bytes()).hexdigest()},indent=2),encoding='utf8')+print('BUILD',rc,LOG);print('\n'.join(LOG.read_text(encoding='utf8',errors='replace').splitlines()[-12:]));subprocess.run(guard,check=True);raise SystemExit(rc)diff --git a/scripts/acceptance/vfg-opt-control.py b/scripts/acceptance/vfg-opt-control.pynew file mode 100644index 00000000..828dc7b1--- /dev/null+++ b/scripts/acceptance/vfg-opt-control.py@@ -0,0 +1,41 @@+"""Immutable scope/ownership baseline for the explicitly authorized VFG work."""+from pathlib import Path+import hashlib,json,subprocess,sys+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-optimization-20261007'+START=BASE/'archives'/TASK/'start.json'+ALLOWED={'AGENTS.md','docs/WORKLOG.md','src/pipeline/VfgBackend.cpp','include/veyra/pipeline/VfgBackend.h',+ 'src/pipeline/EnhanceGraph.cpp','include/veyra/pipeline/EnhanceGraph.h','src/engine/EngineController.cpp',+ 'tests/integration/VfgGpuTests.cpp'}+def sha(path):+ with path.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()+def git(*args,cwd=ROOT):return subprocess.check_output(['git',*args],cwd=cwd)+def others():+ output=[]+ for line in git('worktree','list','--porcelain').decode('utf8').splitlines():+ if not line.startswith('worktree '):continue+ path=Path(line[9:])+ if path.resolve()==ROOT.resolve():continue+ names=git('ls-files','-m','-o','--exclude-standard','-z',cwd=path).decode('utf8').split('\0')+ output.append({'path':str(path),'head':git('rev-parse','HEAD',cwd=path).decode().strip(),'statusHex':git('status','--porcelain=v1','-z','--untracked-files=all',cwd=path).hex(),+ 'changed':{name:sha(path/name) if (path/name).is_file() else None for name in sorted(set(names)-{''})}})+ return output+def allowed(name):return name in ALLOWED or name.startswith(('docs/VFG_OPTIMIZATION_','scripts/acceptance/vfg-opt-','include/veyra/pipeline/Vfg','include/veyra/engine/Vfg','tests/unit/Vfg'))+if '--start' in sys.argv:+ assert not START.exists();assert git('rev-parse','HEAD').decode().strip().startswith('aec800e')+ files={name:sha(ROOT/name) for name in git('ls-files','-z').decode('utf8').split('\0') if name and (ROOT/name).is_file()}+ package=BASE/'releases/publish-2.0.5-20261007/packages/Veyra-2.0.5-NVIDIA-win64-portable'+ runtime=json.loads((package/'vfg-runtime-manifest.json').read_text(encoding='utf-8-sig'))+ immutable={str(package/'veyra_qml_ui.exe'):sha(package/'veyra_qml_ui.exe'),str(package/'qml/Veyra/Main.qml'):sha(package/'qml/Veyra/Main.qml')}+ immutable.update({str(package/f['path']):sha(package/f['path']) for f in runtime['files']})+ START.parent.mkdir(parents=True,exist_ok=True);START.write_text(json.dumps({'head':git('rev-parse','HEAD').decode().strip(),'files':files,'otherWorktrees':others(),'immutable':immutable},ensure_ascii=False,indent=2),encoding='utf8')+ print('VFG baseline created',START)+else:+ start=json.loads(START.read_text(encoding='utf8'));changed=[]+ for name,digest in start['files'].items():+ if not (ROOT/name).is_file() or sha(ROOT/name)!=digest:changed.append(name)+ tracked=set(start['files']);current=set(git('ls-files','-c','-o','--exclude-standard','-z').decode('utf8').split('\0'))-{''}+ changed+=sorted(current-tracked)+ assert all(allowed(name) for name in changed),[name for name in changed if not allowed(name)]+ assert others()==start['otherWorktrees'],'Another worktree changed; preserve and investigate'+ for name,digest in start['immutable'].items():assert sha(Path(name))==digest,name+ print('VFG guard passed; other worktrees, published runtime and non-VFG files preserved;',len(set(changed)),'allowed files')diff --git a/scripts/acceptance/vfg-opt-report.py b/scripts/acceptance/vfg-opt-report.pynew file mode 100644index 00000000..e6a341ea--- /dev/null+++ b/scripts/acceptance/vfg-opt-report.py@@ -0,0 +1,70 @@+"""Read-only analysis of production VFG logs; no GPU work or app mutations."""+from pathlib import Path+from datetime import datetime+import json, re, statistics++BASE=Path('E:/项目/Veyra/logs/vfg-optimization-20261007')+def fields(text):+ result={}+ for k,v in re.findall(r'([A-Za-z][A-Za-z0-9]*)=([^\s]+)',text):result.setdefault(k,v)+ return result+def numbers(row):+ result={}+ for k,v in row.items():+ try:result[k]=float(v)+ except ValueError:result[k]=v+ return result+def percentile(values,q):+ return sorted(values)[min(len(values)-1,int((len(values)-1)*q))] if values else None++output=[]+for path in sorted(BASE.glob('*/result.json')):+ result=json.loads(path.read_text(encoding='utf8'))+ samples=json.loads(path.with_name('samples.json').read_text(encoding='utf8'))+ if not samples:continue+ first,last=samples[0]['wall'],samples[-1]['wall']+ records=[];present=[];timing=[];batches={};offsets=[];last_pacing=None;closed={};admissions=[]+ for line in path.with_name('player.log').read_text(encoding='utf8',errors='replace').splitlines():+ try:utc=datetime.fromisoformat(line[:24].replace('Z','+00:00')).timestamp()*1000+ except ValueError:continue+ row=numbers(fields(line));row['utcMs']=utc+ if '[pacing-sample]' in line:last_pacing=row+ if '[submit]' in line and 'host100ns' in row:+ offsets.append(utc-row['host100ns']/10000)+ if last_pacing and row['pts100ns']==last_pacing.get('pts'):+ last_pacing['batch']=int(row['batch']);present.append(last_pacing);last_pacing=None+ if '[frame-batch]' in line:batches[int(row['batch'])]=row+ if first<=utc<=last:+ if '[player-timing]' in line:timing.append(row)+ if '[live-fg-admission]' in line:admissions.append(row)+ if '[frame-flow]' in line and row.get('state')=='closed':closed=row+ offset=statistics.median(offsets) if offsets else 0+ starts={int(p['batch']):p['process'] for p in present}+ intervals=[]+ for batch,start in starts.items():+ if batch in batches:+ b=batches[batch];end=(b['utcMs']-offset)*10000+ if first<=b['utcMs']<=last:intervals.append({'batch':batch,'start':start,'end':end,'ms':(end-start)/10000})+ steady=[p for p in present if first<=p['utcMs']<=last]+ gaps=[];examples=[]+ target=1000/(30*result['config']['multiplier'])+ for a,b in zip(steady,steady[1:]):+ gap=(b['begin']-a['begin'])/10000;gaps.append(gap)+ if gap<target*2:continue+ matches=[]+ for i in intervals:+ overlap=max(0,min(b['begin'],i['end'])-max(a['end'],i['start']))/10000+ if overlap>gap*.8 and 0<b['ready']<i['start']:+ matches.append({'processingBatch':i['batch'],'processingMs':i['ms'],'overlapMs':overlap,'nextFrameReadyBeforeProcessMs':(i['start']-b['ready'])/10000})+ if matches:examples.append({'presentGapMs':gap,'previousPtsMs':a['pts']/10000,'nextPtsMs':b['pts']/10000,'presentedBatch':b['batch'],'nextLateMs':b.get('lateMs'),**max(matches,key=lambda m:m['overlapMs'])})+ timing_summary={}+ if len(timing)>1:+ a,b=timing[0],timing[-1];seconds=(b['utcMs']-a['utcMs'])/1000+ timing_summary={'seconds':seconds,'medianReportedWindowP95Ms':{k:statistics.median([r[k] for r in timing]) for k in ('decodeP95Ms','graphSubmitP95Ms','gpuReadyP95Ms','presentP95Ms','entryAbsP95Ms')},'cumulativeDeltas':{k:b[k]-a[k] for k in ('displaySubmits','expiredGenerated','previewSkipped','processed','slotWaits')},'playbackSpeedRange':[min(r['playbackSpeed'] for r in timing),max(r['playbackSpeed'] for r in timing)]}+ admission={k:[min(r[k] for r in admissions if k in r),max(r[k] for r in admissions if k in r)] for k in ('admittedPairs','rejectedPairs','predictedMs','remainingDeadlineMs','firstDeadlineMs') if any(k in r for r in admissions)}+ meters=json.loads(path.with_name('meters.json').read_text(encoding='utf8'))+ analysis={'label':path.parent.name,'result':result,'closedCounters':closed,'timing':timing_summary,'admissionRanges':admission,'foregroundOwnedSamples':sum(bool(m['foregroundAlreadyOwned']) for m in meters),'foregroundSamples':len(meters),'submissionCadenceMs':{'target':target,'median':statistics.median(gaps) if gaps else None,'p95':percentile(gaps,.95),'max':max(gaps) if gaps else None},'graphCpuIntervalMsApproxUtcMapping':{'samples':len(intervals),'median':statistics.median(i['ms'] for i in intervals) if intervals else None,'p95':percentile([i['ms'] for i in intervals],.95)},'longGapsWithReadyFrameBlockedByNextGraph':len(examples),'examples':examples[:5]}+ path.with_name('analysis.json').write_text(json.dumps(analysis,ensure_ascii=False,indent=2),encoding='utf8')+ output.append(analysis)+ print(path.parent.name, 'fps',result['fps'],'total',round(result['totalMs'],2),'graphCpu',timing_summary.get('medianReportedWindowP95Ms',{}).get('graphSubmitP95Ms'),'blockedReadyGaps',len(examples))+(BASE/'analysis.json').write_text(json.dumps(output,ensure_ascii=False,indent=2),encoding='utf8')diff --git a/scripts/acceptance/vfg-opt-run.py b/scripts/acceptance/vfg-opt-run.pynew file mode 100644index 00000000..91e50d34--- /dev/null+++ b/scripts/acceptance/vfg-opt-run.py@@ -0,0 +1,148 @@+"""Serial production VFG measurements; private profile/staging, normal playback only."""+from pathlib import Path+import argparse, ctypes, hashlib, json, os, re, shutil, statistics, subprocess, sys, time+from ctypes import wintypes+import psutil++ROOT=Path(__file__).resolve().parents[2]+BASE=Path('E:/项目/Veyra'); TASK='vfg-optimization-20261007'+PACKAGE=BASE/'releases/publish-2.0.5-20261007/packages/Veyra-2.0.5-NVIDIA-win64-portable'+APP=BASE/'tests'/TASK/'app'+MEDIA=Path('E:/Ai/知识/小七姐/GTAVI_An_Extended_Look_4K_Native.mp4')+EXPECTED_EXE='acd49a23074b58ec9698d260d63b2d5a59a640627e09a9b83f0127ae47ebb936'++def sha(path):+ with Path(path).open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()++def save(path,data):+ path.parent.mkdir(parents=True,exist_ok=True)+ path.write_text(json.dumps(data,ensure_ascii=False,indent=2),encoding='utf8')++def inherited_state():+ entries=[]+ for line in subprocess.check_output(['git','worktree','list','--porcelain'],cwd=ROOT,encoding='utf8').splitlines():+ if line.startswith('worktree '):+ path=Path(line[9:])+ if path.resolve()==ROOT.resolve():continue+ status=subprocess.check_output(['git','status','--porcelain=v1','-z','--untracked-files=all'],cwd=path)+ changes=[]+ names=subprocess.check_output(['git','ls-files','-m','-o','--exclude-standard','-z'],cwd=path).split(b'\0')+ for name in sorted(set(x for x in names if x)):+ file=path/os.fsdecode(name)+ changes.append({'path':os.fsdecode(name),'sha256':sha(file) if file.is_file() else None})+ entries.append({'path':str(path),'head':subprocess.check_output(['git','rev-parse','HEAD'],cwd=path,encoding='ascii').strip(),'statusHex':status.hex(),'changes':changes})+ return entries++def prepare():+ archive=BASE/'archives'/TASK/'app-start.json'+ assert not archive.exists() and not APP.exists()+ assert sha(PACKAGE/'veyra_qml_ui.exe')==EXPECTED_EXE+ runtime=json.loads((PACKAGE/'vfg-runtime-manifest.json').read_text(encoding='utf-8-sig'))+ for item in runtime['files']:assert sha(PACKAGE/item['path'])==item['sha256'].lower(),item['path']+ stat=MEDIA.stat();prior=json.loads((BASE/'logs/release-2.0.5-20261007/gta-media.json').read_text(encoding='utf8'))+ assert stat.st_size==prior['bytes'] and stat.st_mtime_ns==prior['mtimeNs']+ receipt={'sourceHead':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,encoding='ascii').strip(),'worktrees':inherited_state(),'media':prior,'exeSha256':EXPECTED_EXE,'vfgRuntime':runtime,'originalMainSha256':sha(PACKAGE/'qml/Veyra/Main.qml')}+ save(archive,receipt)+ def copy(src,dst):+ if Path(src).suffix.lower() in ('.dll','.bin','.hsaco','.ptx','.onnx','.cubin','.f16'):os.link(src,dst)+ else:shutil.copy2(src,dst)+ return dst+ shutil.copytree(PACKAGE,APP,copy_function=copy,ignore=shutil.ignore_patterns('*.log','logs','user-data-*','*.dmp','*.pdb'))+ shutil.copy2(ROOT/'scripts/acceptance/vfg-diagnosis.qml',APP/'qml/Veyra/VfgDiagnosis.qml')+ print('prepared',APP,flush=True)++def gpu():+ return subprocess.check_output(['nvidia-smi','--query-gpu=utilization.gpu,memory.used,clocks.current.graphics,power.draw','--format=csv,noheader,nounits'],encoding='utf8',timeout=8).strip()++def focus(proc):+ user=ctypes.WinDLL('user32');user.GetForegroundWindow.restype=wintypes.HWND+ user.GetWindowThreadProcessId.argtypes=[wintypes.HWND,ctypes.POINTER(wintypes.DWORD)]+ pid=wintypes.DWORD();user.GetWindowThreadProcessId(user.GetForegroundWindow(),ctypes.byref(pid))+ if pid.value==proc.pid:return True+ callback=ctypes.WINFUNCTYPE(wintypes.BOOL,wintypes.HWND,wintypes.LPARAM);windows=[]+ def collect(hwnd,_):+ pid=wintypes.DWORD();user.GetWindowThreadProcessId(hwnd,ctypes.byref(pid))+ if pid.value==proc.pid and user.IsWindowVisible(hwnd):windows.append(hwnd)+ return True+ user.EnumWindows(callback(collect),0)+ if windows:user.SetForegroundWindow(windows[0])+ return False++def run(args):+ assert re.fullmatch(r'[a-z0-9-]+',args.label)+ for proc in psutil.process_iter(['pid','name']):+ assert proc.info['name'].lower() not in ('veyra.exe','veyra_qml_ui.exe'),f'Existing player PID {proc.pid}; no concurrent GPU runs'+ global EXPECTED_EXE+ selected=PACKAGE/'veyra_qml_ui.exe' if args.original else BASE/'build'/TASK/'veyra_qml_ui.exe'+ EXPECTED_EXE=sha(selected);shutil.copy2(selected,APP/'veyra_qml_ui.exe')+ assert sha(APP/'veyra_qml_ui.exe')==EXPECTED_EXE+ out=BASE/'logs'/TASK/args.label;profile=BASE/'tests'/TASK/args.label/'profile';tmp=BASE/'tmp'/TASK/args.label+ for path in (out,profile,tmp):path.mkdir(parents=True,exist_ok=False)+ save(profile/'qml-preferences.v1.json',{'overlayCompat':'off','gpuPriority':'normal','decode':'auto','reducedMotion':False,'obsGameCapture':False})+ config={'media':MEDIA.as_posix(),'multiplier':args.multiplier,'quality':args.quality,'nr':not args.no_nr,'strict':args.strict,'flow':args.flow,'display':0 if args.tearing else 2,'seconds':args.seconds}+ text=(PACKAGE/'qml/Veyra/Main.qml').read_text(encoding='utf8');at=text.rfind('}')+ loader='\nLoader { source: "VfgDiagnosis.qml"; onLoaded: item.config='+json.dumps(config,ensure_ascii=True)+' }\n'+ (APP/'qml/Veyra/Main.qml').write_text(text[:at]+loader+text[at:],encoding='utf8')+ env=os.environ.copy()+ for key in list(env):+ if key.upper().startswith(('VEYRA_','QT_QUICK_BACKEND','QSG_')):env.pop(key)+ env.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'),QML_DISABLE_DISK_CACHE='1',QT_FORCE_STDERR_LOGGING='1',VEYRA_LOG_FILE=str(out/'player.log'))+ if not args.no_verbose:env['VEYRA_VERBOSE_FRAME_LOGS']='1'+ if args.cpu_profile:env['VEYRA_TEST_VFG_CPU_PROFILE']='1'+ if args.no_reduced:env['VEYRA_TEST_FG_NO_REDUCED']='1'+ if args.software:env['QT_QUICK_BACKEND']='software'+ receipt={'config':config,'exeSha256':EXPECTED_EXE,'gpuBefore':gpu(),'noReduced':args.no_reduced,'softwareUi':args.software,'verboseFrameLogs':not args.no_verbose,'cpuProfile':args.cpu_profile,'selectedBinary':str(selected)}+ started=time.monotonic();meters=[]+ with (out/'console.log').open('xb') as stream:+ proc=subprocess.Popen([str(APP/'veyra_qml_ui.exe'),'--data-dir',str(profile),'--page','pro','--size','1280x800','--exit-after','135000'],cwd=APP,env=env,stdout=stream,stderr=subprocess.STDOUT)+ receipt['pid']=proc.pid+ try:+ while proc.poll() is None and time.monotonic()-started<145:+ meters.append({'elapsed':time.monotonic()-started,'foregroundAlreadyOwned':focus(proc),'gpu':gpu()});time.sleep(1)+ if proc.poll() is None:proc.kill();proc.wait(timeout=10);rc=124+ else:rc=proc.returncode+ finally:+ if proc.poll() is None:proc.kill();proc.wait(timeout=10)+ text=(out/'player.log').read_text(encoding='utf8',errors='replace');rows=[]+ for line in text.splitlines():+ if 'VFG_DIAG_SAMPLE ' in line:+ row=json.loads(line.split('VFG_DIAG_SAMPLE ',1)[1])+ if row['ready'] and 5<=row['seconds']<=args.seconds+5:rows.append(row)+ stages={}+ for name in sorted({stage['label'] for row in rows for stage in row['stages'] if stage['measured']}):+ values=[stage['ms'] for row in rows for stage in row['stages'] if stage['label']==name and stage['measured']]+ stages[name]={'medianOneSecondMeansMs':statistics.median(values),'min':min(values),'max':max(values)}+ median=lambda key:statistics.median([r[key] for r in rows]) if rows else None+ receipt.update(exitCode=rc,wallSeconds=time.monotonic()-started,passed=rc==0 and 'VFG_DIAG_PASS' in text and 'VFG_DIAG_FAIL' not in text and len(rows)>=args.seconds-3,observations=len(rows),fps=median('fps'),totalMs=median('total'),budgetMs=median('budget'),gpuPercent=median('gpu'),status=sorted({r['status'] for r in rows}),detail=sorted({r['detail'] for r in rows}),stages=stages,errors=[line for line in text.splitlines() if any(x in line for x in ('[ERROR]','[FATAL]','TypeError:','ReferenceError:'))])+ receipt['normalSchedulingClass']=[line for line in text.splitlines() if 'priority' in line.lower()][:5]+ for name,data in [('result',receipt),('samples',rows),('meters',meters)]:save(out/(name+'.json'),data)+ print(json.dumps(receipt,ensure_ascii=False),flush=True)+ if not receipt['passed']:+ print('\n'.join(text.splitlines()[-20:]));raise SystemExit(1)++def audit():+ start=json.loads((BASE/'archives'/TASK/'app-start.json').read_text(encoding='utf8'))+ assert start['worktrees']==inherited_state(),'Other worktree changed'+ assert sha(PACKAGE/'veyra_qml_ui.exe')==start['exeSha256']+ assert sha(PACKAGE/'qml/Veyra/Main.qml')==start['originalMainSha256']+ for item in start['vfgRuntime']['files']:assert sha(PACKAGE/item['path'])==item['sha256'].lower()+ print('original worktrees and published app/runtime unchanged',flush=True)++parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['prepare','case','audit','matrix']);parser.add_argument('label',nargs='?')+parser.add_argument('--multiplier',type=int,choices=range(2,9),default=2);parser.add_argument('--quality',type=int,choices=range(3),default=1)+parser.add_argument('--no-nr',action='store_true');parser.add_argument('--strict',action='store_true');parser.add_argument('--flow',action='store_true');parser.add_argument('--tearing',action='store_true');parser.add_argument('--no-reduced',action='store_true');parser.add_argument('--software',action='store_true');parser.add_argument('--no-verbose',action='store_true');parser.add_argument('--seconds',type=int,default=20)+parser.add_argument('--original',action='store_true');parser.add_argument('--cpu-profile',action='store_true')+args=parser.parse_args()+if args.mode=='prepare':prepare()+elif args.mode=='case':run(args)+elif args.mode=='matrix':+ for quality in (1,0,2):+ for multiplier in range(2,9):+ label=f'{("low","medium","high")[quality]}{multiplier}-nr'+ output=BASE/'logs'/TASK/label/'result.json'+ if output.exists():+ result=json.loads(output.read_text(encoding='utf8'));assert result['passed']+ continue+ command=[sys.executable,'-B',str(Path(__file__).resolve()),'case',label,'--quality',str(quality),'--multiplier',str(multiplier)]+ subprocess.run(command,cwd=ROOT,check=True,timeout=160)+else:audit()diff --git a/src/pipeline/VfgBackend.cpp b/src/pipeline/VfgBackend.cppindex 941e6603..ce0d736e 100644--- a/src/pipeline/VfgBackend.cpp+++ b/src/pipeline/VfgBackend.cpp@@ -4,6 +4,7 @@#include "veyra/Log.h"#include <Windows.h>#include <array>+#include <chrono>#include <filesystem>#include <format>#include <vector>@@ -104,6 +105,23 @@ struct VfgBackend::Impl {unsigned width=0,height=0,maxMultiplier=2;DXGI_FORMAT format=DXGI_FORMAT_UNKNOWN;bool ready=false;+ bool profileCpu=false;+ std::array<double,13> cpuSum{},cpuMax{};+ std::array<unsigned,13> cpuSamples{};+ std::chrono::steady_clock::time_point nextCpuLog{};+ template<class F> auto cpuCall(unsigned stage,F&& operation){+ if(!profileCpu)return operation();+ const auto start=std::chrono::steady_clock::now();const auto result=operation();+ const double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count();+ cpuSum[stage]+=ms;cpuMax[stage]=std::max(cpuMax[stage],ms);++cpuSamples[stage];return result;+ }+ void logCpu(){+ if(!profileCpu||std::chrono::steady_clock::now()<nextCpuLog)return;+ static constexpr std::array<const char*,13> names={"push","producer","cudaWait","src0","src1","dst","shot","multiplier","index","run","cudaSignal","queueWait","pop"};+ std::string message;+ for(unsigned i=0;i<names.size();++i)message+=std::format(" {}MeanMs={:.4f} {}MaxMs={:.4f} {}Calls={}",names[i],cpuSamples[i]?cpuSum[i]/cpuSamples[i]:0,names[i],cpuMax[i],names[i],cpuSamples[i]);+ log::info("vfg-cpu",message);cpuSum={};cpuMax={};cpuSamples={};nextCpuLog=std::chrono::steady_clock::now()+std::chrono::seconds(1);+ }bool cv(int code,const char* name){if(code==0)return true;log::error("vfg",std::format("{} status={} detail={}",name,code,errorString?errorString(code):"unavailable"));return false;@@ -117,8 +135,8 @@ struct VfgBackend::Impl {}struct Current {Impl& owner;bool active=false;- explicit Current(Impl& p):owner(p){active=p.cu(p.cuCtxPushCurrentFn(p.cudaContext),"cuCtxPushCurrent");}- ~Current(){if(active){CUcontext previous=nullptr;owner.cu(owner.cuCtxPopCurrentFn(&previous),"cuCtxPopCurrent");}}+ explicit Current(Impl& p):owner(p){active=p.cu(p.cpuCall(0,[&]{return p.cuCtxPushCurrentFn(p.cudaContext);}),"cuCtxPushCurrent");}+ ~Current(){if(active){CUcontext previous=nullptr;owner.cu(owner.cpuCall(12,[&]{return owner.cuCtxPopCurrentFn(&previous);}),"cuCtxPopCurrent");}}};bool importFence(ID3D12Fence* fence,CUexternalSemaphore& semaphore){HANDLE handle=nullptr;@@ -158,20 +176,20 @@ struct VfgBackend::Impl {bool handoff(unsigned parity,unsigned sub,unsigned multiplier,bool reset){Current current(*this);if(!current.active)return false;const uint64_t value=++signalValue;- if(!hr(context->directQueue()->Signal(producer.Get(),value),"signal VFG producer"))return false;+ if(!hr(cpuCall(1,[&]{return context->directQueue()->Signal(producer.Get(),value);}),"signal VFG producer"))return false;CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS wait{};wait.params.fence.value=value;- if(!cu(cuWaitExternalSemaphoresAsyncFn(&inputSemaphore,&wait,1,stream),"cuWaitExternalSemaphoresAsync"))return false;- bool ok=cv(setImage(effect,"SrcImage0",inputs[reset?parity:1-parity].image),"SetImage previous")&&- cv(setImage(effect,"SrcImage1",inputs[parity].image),"SetImage current")&&- cv(setImage(effect,"DstImage0",outputs[parity+2*(sub-1)].image),"SetImage output")&&- cv(setU32(effect,"ShotChange",reset?1u:0u),"SetU32 ShotChange")&&- cv(setU32(effect,"FrameMultiplier",multiplier),"SetU32 FrameMultiplier")&&- cv(setU32(effect,"FrameIndex",sub),"SetU32 FrameIndex")&&cv(run(effect,1),"NvVFX_Run async");+ if(!cu(cpuCall(2,[&]{return cuWaitExternalSemaphoresAsyncFn(&inputSemaphore,&wait,1,stream);}),"cuWaitExternalSemaphoresAsync"))return false;+ bool ok=cv(cpuCall(3,[&]{return setImage(effect,"SrcImage0",inputs[reset?parity:1-parity].image);}),"SetImage previous")&&+ cv(cpuCall(4,[&]{return setImage(effect,"SrcImage1",inputs[parity].image);}),"SetImage current")&&+ cv(cpuCall(5,[&]{return setImage(effect,"DstImage0",outputs[parity+2*(sub-1)].image);}),"SetImage output")&&+ cv(cpuCall(6,[&]{return setU32(effect,"ShotChange",reset?1u:0u);}),"SetU32 ShotChange")&&+ cv(cpuCall(7,[&]{return setU32(effect,"FrameMultiplier",multiplier);}),"SetU32 FrameMultiplier")&&+ cv(cpuCall(8,[&]{return setU32(effect,"FrameIndex",sub);}),"SetU32 FrameIndex")&&cv(cpuCall(9,[&]{return run(effect,1);}),"NvVFX_Run async");// Complete the ownership handoff even after a synchronous SDK rejection;// never leave the direct queue waiting on a signal we did not enqueue.CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS signal{};signal.params.fence.value=value;- if(!cu(cuSignalExternalSemaphoresAsyncFn(&outputSemaphore,&signal,1,stream),"cuSignalExternalSemaphoresAsync"))return false;- if(!hr(context->directQueue()->Wait(completion.Get(),value),"queue wait VFG completion"))return false;+ if(!cu(cpuCall(10,[&]{return cuSignalExternalSemaphoresAsyncFn(&outputSemaphore,&signal,1,stream);}),"cuSignalExternalSemaphoresAsync"))return false;+ if(!hr(cpuCall(11,[&]{return context->directQueue()->Wait(completion.Get(),value);}),"queue wait VFG completion"))return false;return ok;}#endif@@ -188,6 +206,7 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&log::error("vfg","unsupported adapter/runtime/dimensions/multiplier/quality/encoding");return false;}p.context=&context;p.width=width;p.height=height;p.format=format;p.maxMultiplier=multiplier;+ p.profileCpu=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_CPU_PROFILE",nullptr,0)>0;std::array<wchar_t,32768> system{};const auto n=GetSystemDirectoryW(system.data(),UINT(system.size()));if(!n||n>=system.size())return false;HMODULE driver=load(fs::path(system.data())/L"nvcuda.dll");if(!driver)return false;p.libraries.push_back(driver);#define BIND_CU(name,exported) if(!bind(driver,exported,p.name##Fn))return false@@ -290,7 +309,7 @@ bool VfgBackend::capture(ID3D12GraphicsCommandList* list,ID3D12Resource* texturebool VfgBackend::generate(unsigned parity,unsigned sub,unsigned multiplier,bool reset){#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERSauto& p=*impl_;if(!p.ready||parity>1||multiplier<2||multiplier>p.maxMultiplier||sub<1||sub>=multiplier)return false;- return p.handoff(parity,sub,multiplier,reset);+ const bool ok=p.handoff(parity,sub,multiplier,reset);p.logCpu();return ok;#else(void)parity;(void)sub;(void)multiplier;(void)reset;return false;#endif