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

Submit VFG preview work on a bounded worker with explicit frame validity

Veyra Goal Agentddf71b10cee6
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index d224cf45..6ec4153c 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,17 @@
# Veyra 工作记录
+## 2026-10-07 VFG 专项优化(进行中)
+
+用户授权“尝试优化VFG,其他的补帧暂时不动”。排查分支封存aec800e,优化隔离codex/vfg-optimization-20261007;开工tag checkpoint/pre-vfg-optimization-20261007,完整Git bundle与不可变start.json在E:/项目/Veyra/archives/vfg-optimization-20261007。当前任务计划docs/VFG_OPTIMIZATION_PLAN_2026-10-07.md;新guard逐文件保护其它全部工作树、正式2.0.5 EXE/Main/VFG运行库及非VFG实现,未改旧guard/start。所有构建、测试、日志、临时目录使用E:/项目/Veyra对应vfg-optimization-20261007目录;无子Agent、竞争GPU压力、驱动/用户配置变更、merge/push/Release/关机。
+
+P0源码b9394ea / checkpoint/vfg-cpu-profile-20261007:默认关闭的VFG CPU分段计时。命令python -B scripts/acceptance/vfg-opt-build.py profile-build-v1及vfg-opt-run.py case profile-medium4-nr --quality 1 --multiplier 4 --cpu-profile;GUI正式负载原GTA6/原版1080 NR/普通class2,Run均值约6.20ms,Src/SetU32为微秒级,FPS82。逐API日志记录证明阻塞发生在NvVFX_Run;不是从GPU利用率猜测CPU瓶颈。
+
+P1按已登记固定MIT样例52011f89…只在新输入对绑定Src0/1、仅倍率变化设置FrameMultiplier,capture修订检测相同CUDA地址的新像素;pair-cache-build-v1构建通过,pair-cache-medium4-nr仍83fps/FG12.18ms,未证明性能收益。保留其SDK调用契约修正但不计算优化百分比。P2实时VFG专用有界worker,CUDA推理仍串行,图owner预排producer/consumer fence;生成状态独立核验,失败帧不得当Valid。视频导出默认保留同步SDK判定路径;DLSS/XeSS/FSR代码与策略不改。
+
+async-build-v1构建通过。async-native-720-v1:8/10位、三质量、2X–8X、切镜及无效参数637项0失败。首轮async-medium4-nr-v1为120fps(原83–84),async-high2-nr-v1为60fps(前轮原版37);均同原片/原版1080 NR/普通class2,SDK worker日志仍约6.7ms调用,证明收益是送显解耦,不是推理算法或GPU成本下降。以上尚为首轮,重复对照、4K像素/输入刷新、热切换、异步拒绝回退和完整导出验收仍待完成,不能据此交付或宣称所有档位通过。
+
+P2后续:async-build-v2成功;async-native-720-v2、sync-native-720-v2、async-native-4k-v2各913检查0失败(4K进程108.453秒)。相同候选同步/异步42组共168插帧逐像素哈希完全一致,native-hash-comparison.json;新增相同导入地址更新像素、反向运动、parity切换、切镜后2X→4X→8X验证。async-medium8-nr-v2约191fps且仍降档,明确未达240fps。failure-verified-v2第3次Run注入拒绝后实际multiplier=1、fgActive=false、视频继续,进程7.860秒正常退出,无等待悬挂。初次failure-v2及复核failure-observe-v2测试断言失败:误把QML fgEnabled(保存的节点请求)当实际后端;日志证实实际已降为1X,fgActive=false/failed=false。修正的是测试语义,保留两个失败日志,未为此改产品UI或其它后端。最终默认路径只加拒绝hook长度边界和准确注释,再构建最终候选;全档位重复/热切换/完整导出仍在验收,不预先算通过。
+
## 2026-10-07 2.0.5 正式发布完成
已正式发布https://github.com/Likely7/Veyra-NRVideo/releases/tag/v2.0.5(Release ID 405358232,2026-10-07T03:59:46Z),5资产远端大小/SHA256 digest一致,最新正式版本、对应源码/依赖源码、正文/双QR和下载可用性核对通过。两最终ZIP冷启及26个包内模块路径各通过,产品字节保持。实际命令、结果、失败复核、哈希与日志路径见[PUBLISH_2.0.5_REPORT](PUBLISH_2.0.5_REPORT_2026-10-07.md)。main合并939f1a5afa7b1d122adf656d157d4df6b6fad9af、源码e44e828119710b8f031cc968e8ddb1982aecc873;随后只提交此正式回执,不改标签/资产/产品。NV显存未修复;公告≤1000字,只交用户,不代发不关机。
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 78d5f890..d1dcbf1a 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -125,6 +125,7 @@ struct EnhanceGraphDesc {
uint32_t fgMultiplier=2;
engine::FrameGenerationBackend frameGenerationBackend=engine::FrameGenerationBackend::Dlss;
uint32_t vfgQuality=1;
+ bool vfgAsyncSubmission=false; // preview-only; export retains synchronous SDK verdicts
uint64_t settingsRevision=1;
engine::FlowQuality flowQuality=engine::FlowQuality::Balanced;
engine::OpticalFlowBackend opticalFlowBackend=engine::OpticalFlowBackend::Nvidia;
diff --git a/include/veyra/pipeline/VfgBackend.h b/include/veyra/pipeline/VfgBackend.h
index f638d1e1..d9475534 100644
--- a/include/veyra/pipeline/VfgBackend.h
+++ b/include/veyra/pipeline/VfgBackend.h
@@ -10,6 +10,7 @@ namespace veyra::pipeline {
// Borrowed encoded textures stay in the graph's normal FrameLease pool.
class VfgBackend {
public:
+ enum class SubmissionState { Pending, Succeeded, Failed };
VfgBackend();
~VfgBackend();
VfgBackend(const VfgBackend&)=delete;
@@ -17,14 +18,20 @@ public:
static std::wstring runtimeDirectory(const std::wstring& runtimeRoot);
static bool runtimeAvailable(const std::wstring& runtimeRoot);
bool initialize(gfx::D3D12DeviceContext&,const std::wstring& runtimeRoot,
- unsigned width,unsigned height,DXGI_FORMAT,unsigned multiplier,unsigned quality);
+ unsigned width,unsigned height,DXGI_FORMAT,unsigned multiplier,unsigned quality,
+ bool asynchronousSubmission=false);
bool created() const;
// Caller transitions encoded texture to COPY_SOURCE and back to COMMON.
- // Submit this list before generate(). All CPU waits are confined to teardown.
+ // Submit this list before generate(). Normal frames never CPU-wait here;
+ // teardown and exceptional SDK rejection drain work before releasing it.
bool capture(ID3D12GraphicsCommandList*,ID3D12Resource*,unsigned parity);
- // Signals an OWNED producer fence, waits/runs/signals on the CUDA stream,
- // and queues a GPU wait before the caller records copyOutput().
+ // Signals an OWNED producer fence and queues a GPU wait before copyOutput.
+ // Preview offloads the serial CUDA wait/run/signal to a bounded worker;
+ // synchronous/export callers retain the immediate SDK rejection verdict.
bool generate(unsigned parity,unsigned subframe,unsigned multiplier,bool reset);
+ // Poll after the corresponding consumer fence. A submitted copy is not
+ // proof that the SDK accepted the generated frame.
+ SubmissionState submissionState(unsigned slot) const;
bool copyOutput(ID3D12GraphicsCommandList*,ID3D12Resource*,unsigned slot);
void shutdown();
private:
diff --git a/scripts/acceptance/vfg-opt-export.py b/scripts/acceptance/vfg-opt-export.py
new file mode 100644
index 00000000..ad75d09e
--- /dev/null
+++ b/scripts/acceptance/vfg-opt-export.py
@@ -0,0 +1,49 @@
+"""Serial real graph/NVENC export checks, including frame counts and PTS."""
+from pathlib import Path
+import argparse,json,os,re,shutil,subprocess,psutil
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-optimization-20261007';APP=BASE/'tests'/TASK/'app'
+p=argparse.ArgumentParser();p.add_argument('label');a=p.parse_args();assert a.label.replace('-','').isalnum()
+subprocess.run(['python','-B',str(ROOT/'scripts/acceptance/vfg-opt-control.py')],cwd=ROOT,check=True)
+assert not any(x.info['name'].lower() in ('veyra.exe','veyra_qml_ui.exe','veyra_vfg_gpu_tests.exe','veyra_vfg_export_probe.exe') for x in psutil.process_iter(['name']))
+out,logs,tmp=(BASE/k/TASK/a.label for k in ('tests','logs','tmp'))
+for x in (out,logs,tmp):x.mkdir(parents=True,exist_ok=False)
+probe=shutil.which('ffprobe');ffmpeg=shutil.which('ffmpeg');assert probe and ffmpeg
+shutil.copy2(BASE/'build'/TASK/'veyra_vfg_export_probe.exe',APP/'veyra_vfg_export_probe.exe')
+env={k:v for k,v in os.environ.items() if not k.startswith(('VEYRA_','QSG_','QT_QUICK_'))}
+env.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'),VEYRA_VFG_RUNTIME=str(APP/'runtime/nvidia-vfg'))
+env['PATH']=os.pathsep.join((env['WINDIR']+'/System32',env['WINDIR'],env['WINDIR']+'/System32/Wbem'))
+source=BASE/'tests/runtime-size-20261004/export-basic-v2/input.mp4';assert source.is_file();results=[]
+def run(name,media,m,q,flags=(),expected='success'):
+ file=out/(name+'.mp4');child=env.copy()
+ if expected=='missing':child['VEYRA_VFG_RUNTIME']=str(tmp/'missing-runtime')
+ log=logs/(name+'.log');cmd=[str(APP/'veyra_vfg_export_probe.exe'),str(media),str(file),str(m),str(q),*flags]
+ with log.open('xb') as f:
+ try:rc=subprocess.run(cmd,cwd=APP,env=child,stdout=f,stderr=subprocess.STDOUT,timeout=290).returncode
+ except subprocess.TimeoutExpired:rc=124
+ text=log.read_text(encoding='utf8',errors='replace');item={'case':name,'command':cmd,'exit':rc,'expected':expected}
+ if expected!='success':
+ assert rc==(1 if expected=='missing' else 0) and not file.exists(),text[-5000:]
+ assert ('cancelled=1' if expected=='cancel' else 'ok=0') in text,text[-5000:]
+ else:
+ assert rc==0 and 'backend=NVIDIA-VFG' in text and 'SDK submission=graph owner' in text and 'nvenc' in text.lower(),text[-5000:]
+ assert not re.search(r'\[ERROR\s*\]|\[FATAL\s*\]|device removed|not alive|substituting',text),text[-5000:]
+ data=json.loads(subprocess.check_output([probe,'-v','error','-count_frames','-show_streams','-of','json',str(file)],timeout=30))
+ v=next(x for x in data['streams'] if x['codec_type']=='video')
+ assert v['codec_name']=='hevc' and int(v['nb_read_frames'])==8*m,data
+ assert all(abs(int(v[k].split('/')[0])/int(v[k].split('/')[1])-30*m)<.00001 for k in ('avg_frame_rate','r_frame_rate')),data
+ assert abs(float(v['duration'])-8/30)<1/(30*m),data
+ for audio in (x for x in data['streams'] if x['codec_type']=='audio'):assert abs(float(audio['duration'])-8/30)<.06,data
+ packets=json.loads(subprocess.check_output([probe,'-v','error','-select_streams','v','-show_entries','packet=pts_time','-of','json',str(file)],timeout=30))['packets']
+ pts=[float(x['pts_time']) for x in packets];assert len(pts)==8*m and all(abs(b-a-1/(30*m))<.000003 for a,b in zip(pts,pts[1:])),pts
+ if '--nr' in flags:assert 'nr=1' in text and (v['width'],v['height'])==(3840,2160),text[-5000:]
+ item.update(frames=8*m,probe=data,pts=pts)
+ results.append(item);(logs/'summary.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8');print('VFG EXPORT PASS',name,flush=True)
+for quality in range(3):
+ for multiplier in range(2,9):run(f'720p30-q{quality}-{multiplier}x',source,multiplier,quality)
+gta=out/'gta-4k30-eight-frames.mp4'
+with (logs/'fixture.log').open('xb') as f:
+ subprocess.run([ffmpeg,'-v','warning','-n','-ss','42','-i','E:/Ai/知识/小七姐/GTAVI_An_Extended_Look_4K_Native.mp4','-map','0:v:0','-frames:v','8','-an','-c:v','libx264','-threads','6','-preset','fast','-crf','18',str(gta)],env=env,stdout=f,stderr=subprocess.STDOUT,timeout=90,check=True)
+run('gta-4k30-native-nr-vfg4',gta,4,1,('--nr',))
+run('cancel-vfg8',source,8,1,('--cancel',),expected='cancel')
+run('missing-runtime-vfg8',source,8,1,expected='missing')
+print('VFG EXPORT SUITE PASS',len(results),logs,flush=True)
diff --git a/scripts/acceptance/vfg-opt-failure.qml b/scripts/acceptance/vfg-opt-failure.qml
new file mode 100644
index 00000000..df9628ea
--- /dev/null
+++ b/scripts/acceptance/vfg-opt-failure.qml
@@ -0,0 +1,24 @@
+import QtQuick
+Item {
+ id: test
+ property string media: ""
+ property int step: 0
+ property int ticks: 0
+ Timer { interval: 500; running: true; repeat: true; onTriggered: { try {
+ if(!test.media.length)return
+ if(++test.ticks>240)throw new Error("120s fallback deadline")
+ if(test.step===0&&test.ticks>4){
+ veyra.muted=true;veyra.nrEnabled=false;veyra.srEnabled=false;veyra.videoHdr=false;veyra.colorEnabled=false
+ veyra.nodeMode=0;veyra.addEffect("vfg-fg");veyra.fgMultiplier=4;veyra.vfgQuality=1
+ veyra.openPath(test.media);test.step=1
+ }
+ if(test.step===1&&!veyra.applying&&veyra.running&&veyra.position>2&&veyra.backendWarning.length){
+ console.log("VFG_FAILURE_STATE",JSON.stringify({failed:veyra.failed,position:veyra.position,warning:veyra.backendWarning,backend:veyra.fgBackendName,enabled:veyra.fgEnabled,active:veyra.fgActive,multiplier:veyra.fgMultiplier}))
+ // fgEnabled is the saved chain node request, not the active backend. The
+ // engine recovery log separately verifies applied multiplier=1.
+ if(veyra.failed||veyra.fgActive)throw new Error("failed SDK frame remained active")
+ console.log("VFG_FAILURE_PASS",JSON.stringify({position:veyra.position,warning:veyra.backendWarning,backend:veyra.fgBackendName,enabled:veyra.fgEnabled,active:veyra.fgActive}))
+ Qt.quit()
+ }
+ } catch(e){console.error("VFG_FAILURE_FAIL",e.message);Qt.exit(3)} } }
+}
diff --git a/scripts/acceptance/vfg-opt-lifecycle.py b/scripts/acceptance/vfg-opt-lifecycle.py
new file mode 100644
index 00000000..d70d0d74
--- /dev/null
+++ b/scripts/acceptance/vfg-opt-lifecycle.py
@@ -0,0 +1,56 @@
+"""Use the existing product GUI hot-switch/export checks in a private app/profile."""
+from pathlib import Path
+import argparse,json,os,re,shutil,subprocess,time,psutil
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-optimization-20261007';APP=BASE/'tests'/TASK/'app'
+p=argparse.ArgumentParser();p.add_argument('label');p.add_argument('--failure-only',action='store_true');a=p.parse_args();assert a.label.replace('-','').isalnum()
+subprocess.run(['python','-B',str(ROOT/'scripts/acceptance/vfg-opt-control.py')],cwd=ROOT,check=True)
+assert not any(x.info['name'].lower() in ('veyra.exe','veyra_qml_ui.exe','veyra_vfg_gpu_tests.exe','veyra_vfg_export_probe.exe') for x in psutil.process_iter(['name']))
+out,logs,tmp=(BASE/k/TASK/a.label for k in ('tests','logs','tmp'))
+for x in (out,logs,tmp):x.mkdir(parents=True,exist_ok=False)
+profile=out/'profile';profile.mkdir();(profile/'qml-preferences.v1.json').write_text(json.dumps({'overlayCompat':'off','gpuPriority':'normal','obsGameCapture':False}),encoding='utf8')
+outputs=out/'outputs';outputs.mkdir()
+media=Path('E:/Ai/知识/小七姐/GTAVI_An_Extended_Look_4K_Native.mp4')
+short=BASE/'tests/runtime-size-20261004/export-basic-v2/input.mp4';assert short.is_file()
+shutil.copy2(BASE/'build'/TASK/'veyra_qml_ui.exe',APP/'veyra_qml_ui.exe')
+env={k:v for k,v in os.environ.items() if not k.startswith(('VEYRA_','QSG_','QT_QUICK_'))}
+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')
+env['PATH']=os.pathsep.join((env['WINDIR']+'/System32',env['WINDIR'],env['WINDIR']+'/System32/Wbem'))
+package=BASE/'releases/publish-2.0.5-20261007/packages/Veyra-2.0.5-NVIDIA-win64-portable'
+original=(package/'qml/Veyra/Main.qml').read_bytes();source=original.decode('utf8');at=source.rfind('}');main=APP/'qml/Veyra/Main.qml';results=[]
+try:
+ for phase in (['failure'] if a.failure_only else ['run','restore','missing','failure']):
+ child=env.copy();data=profile
+ child['VEYRA_LOG_FILE']=str(logs/(phase+'-engine.log'))
+ if phase in ('missing','failure'):
+ data=out/(phase+'-profile');shutil.copytree(profile,data)
+ if phase=='missing':child['VEYRA_VFG_RUNTIME']=str(tmp/'missing-runtime')
+ if phase=='failure':child['VEYRA_TEST_VFG_REJECT_RUN']='3'
+ qml=ROOT/'scripts/acceptance'/('vfg-opt-failure.qml' if phase=='failure' else 'vfg-ui.qml')
+ settings='item.media='+json.dumps(str(media))+';'
+ if phase!='failure':settings+='item.shortMedia='+json.dumps(str(short))+';item.evidence='+json.dumps(str(out))+';item.phase='+json.dumps(phase)+';'
+ loader='\nLoader { source: '+json.dumps(qml.as_uri())+'; onLoaded: { '+settings+' } }\n'
+ main.write_text(source[:at]+loader+source[at:],encoding='utf8')
+ start=time.monotonic()
+ with (logs/(phase+'.log')).open('xb') as f:
+ try:rc=subprocess.run([str(APP/'veyra_qml_ui.exe'),'--page','pro','--size','1280x900','--export-out',str(outputs),'--data-dir',str(data),'--exit-after','240000'],cwd=APP,env=child,stdout=f,stderr=subprocess.STDOUT,timeout=270).returncode
+ except subprocess.TimeoutExpired:rc=124
+ text=(logs/(phase+'.log')).read_text(encoding='utf8',errors='replace')
+ marker={'run':'VFG_UI_PASS','restore':'VFG_UI_RESTORE_PASS','missing':'VFG_UI_MISSING_PASS','failure':'VFG_FAILURE_PASS'}[phase]
+ engine=(logs/(phase+'-engine.log')).read_text(encoding='utf8',errors='replace')
+ results.append({'phase':phase,'exit':rc,'seconds':time.monotonic()-start,'marker':marker,'passed':rc==0 and marker in text and not re.search(r'VFG_UI_FAIL|VFG_FAILURE_FAIL',text)})
+ (logs/'summary.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8')
+ assert rc==0 and marker in text and not re.search(r'VFG_UI_FAIL|VFG_FAILURE_FAIL',text),text[-6000:]
+ if phase=='failure':assert 'injected VFG Run rejection' in engine and re.search(r'runtime component=6 disabled;.*multiplier=1;',engine),engine[-6000:]
+ if phase=='run':
+ ids=re.findall(r'\[export-worker\] started jobId=\d+ pid=(\d+)',text);assert len(ids)==1,ids
+ worker=APP/'logs'/('export-worker-'+ids[0]+'.log');worker_text=worker.read_text(encoding='utf8',errors='replace')
+ assert 'backend=NVIDIA-VFG vfgQuality=2' in worker_text and 'SDK submission=graph owner' in worker_text,worker_text[-4000:]
+ shutil.copy2(worker,logs/worker.name)
+ print(results[-1],flush=True)
+finally:main.write_bytes(original)
+if not a.failure_only:
+ files=list(outputs.glob('*.mp4'));assert len(files)==1,files
+ probe=json.loads(subprocess.check_output([shutil.which('ffprobe'),'-v','error','-count_frames','-show_streams','-of','json',str(files[0])],timeout=30))
+ video=next(x for x in probe['streams'] if x['codec_type']=='video');assert int(video['nb_read_frames'])==64 and video['r_frame_rate']=='240/1',probe
+ (logs/'export-probe.json').write_text(json.dumps(probe,indent=2),encoding='utf8')
+print('VFG LIFECYCLE PASS',logs,flush=True)
diff --git a/scripts/acceptance/vfg-opt-native.py b/scripts/acceptance/vfg-opt-native.py
new file mode 100644
index 00000000..12d06e3c
--- /dev/null
+++ b/scripts/acceptance/vfg-opt-native.py
@@ -0,0 +1,23 @@
+"""Bounded serial VFG GPU interop/pixel tests; all outputs stay on E:."""
+from pathlib import Path
+import argparse,json,os,subprocess,time,psutil
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-optimization-20261007'
+p=argparse.ArgumentParser();p.add_argument('label');p.add_argument('--width',type=int,default=1280);p.add_argument('--height',type=int,default=720);p.add_argument('--async-submit',action='store_true');p.add_argument('--pair-cache-baseline',action='store_true');a=p.parse_args()
+assert a.label.replace('-','').isalnum()
+subprocess.run(['python','-B',str(ROOT/'scripts/acceptance/vfg-opt-control.py')],cwd=ROOT,check=True)
+assert not any(x.info['name'].lower() in ('veyra.exe','veyra_qml_ui.exe','veyra_vfg_gpu_tests.exe','veyra_vfg_export_probe.exe') for x in psutil.process_iter(['name']))
+log=BASE/'logs'/TASK/(a.label+'.log');out=BASE/'tests'/TASK/a.label;tmp=BASE/'tmp'/TASK/a.label
+for x in (out,tmp):x.mkdir(parents=True,exist_ok=False)
+env={k:v for k,v in os.environ.items() if not k.startswith(('VEYRA_','QSG_','QT_QUICK_'))}
+env.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'))
+env['PATH']=os.pathsep.join((env['WINDIR']+'/System32',env['WINDIR'],env['WINDIR']+'/System32/Wbem'))
+exe=BASE/('tests/'+TASK+'/bin/pair-cache-v1' if a.pair_cache_baseline else 'build/'+TASK)/'veyra_vfg_gpu_tests.exe'
+cmd=[str(exe),str(BASE/'tests'/TASK/'app/runtime/nvidia-vfg'),str(a.width),str(a.height)]
+if a.async_submit:cmd.append('async')
+start=time.monotonic()
+with log.open('x',encoding='utf8') as f:
+ try:rc=subprocess.run(cmd,cwd=out,env=env,stdout=f,stderr=subprocess.STDOUT,timeout=290).returncode
+ except subprocess.TimeoutExpired:rc=124
+receipt={'command':cmd,'exit':rc,'seconds':time.monotonic()-start,'log':str(log)}
+log.with_suffix('.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')
+print(receipt);print('\n'.join(log.read_text(encoding='utf8',errors='replace').splitlines()[-15:]));raise SystemExit(rc)
diff --git a/scripts/acceptance/vfg-opt-run.py b/scripts/acceptance/vfg-opt-run.py
index 91e50d34..18439f06 100644
--- a/scripts/acceptance/vfg-opt-run.py
+++ b/scripts/acceptance/vfg-opt-run.py
@@ -89,9 +89,10 @@ def run(args):
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.sync_submit:env['VEYRA_TEST_VFG_SYNC_SUBMIT']='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)}
+ receipt={'config':config,'exeSha256':EXPECTED_EXE,'gpuBefore':gpu(),'noReduced':args.no_reduced,'softwareUi':args.software,'verboseFrameLogs':not args.no_verbose,'cpuProfile':args.cpu_profile,'syncSubmit':args.sync_submit,'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)
@@ -132,6 +133,7 @@ parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['prepare','
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')
+parser.add_argument('--sync-submit',action='store_true')
args=parser.parse_args()
if args.mode=='prepare':prepare()
elif args.mode=='case':run(args)
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 63bb372e..1c50ab42 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -587,6 +587,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
for(unsigned attempt=0;attempt<6;++attempt){
if(stop_)return false;
+ desc.vfgAsyncSubmission=!isImage&&selected.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&
+ GetEnvironmentVariableW(L"VEYRA_TEST_VFG_SYNC_SUBMIT",nullptr,0)==0;
desc.videoHdr=selected.settings.videoHdr;
desc.hdrOutput=selected.settings.useHdrPreview(desc.hdrInput,displayHdrActive());
// Auto is optional and preview-only; fixed/export policies
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index d247732c..8fdb76b6 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1043,7 +1043,7 @@ bool EnhanceGraph::initVfg()
if(!fgEnabled_||desc_.frameGenerationBackend!=engine::FrameGenerationBackend::Vfg)return true;
failedBackend_=engine::FailedBackend::Fg;
vfgBackend_=std::make_unique<VfgBackend>();
- if(!vfgBackend_->initialize(context_,desc_.runtimeAbsPath,workW_,workH_,outputFormat(),desc_.fgMultiplier,desc_.vfgQuality))return false;
+ if(!vfgBackend_->initialize(context_,desc_.runtimeAbsPath,workW_,workH_,outputFormat(),desc_.fgMultiplier,desc_.vfgQuality,desc_.vfgAsyncSubmission))return false;
fgCapsAvailable_=true;fgMultiFrameMax_=int(FrameBatch::Capacity)-1;
return true;
}
@@ -2987,6 +2987,14 @@ bool EnhanceGraph::resolveFrame(FrameOutputs& out,uint32_t index)
auto& frame=out.batch.frames[index];
if(!frame.lease||!frame.lease->ready())return false;
if(frame.kind!=FrameKind::Generated||frame.validity!=GenerationValidity::Pending)return true;
+ if(vfgBackend_){
+ const auto state=vfgBackend_->submissionState(frame.lease->slot);
+ if(state==VfgBackend::SubmissionState::Pending)return false;
+ if(state==VfgBackend::SubmissionState::Failed){
+ frame.validity=GenerationValidity::Failed;failedBackend_=engine::FailedBackend::Fg;
+ return true;
+ }
+ }
if(fsrActive()||vfgBackend_){
frame.validity=out.contentDuplicate?GenerationValidity::Disabled:GenerationValidity::Valid;
if(out.contentDuplicate){++metrics_.fgDisabledFrames;++metrics_.fgDuplicateSuppressed;}else ++metrics_.fgGeneratedFrames;
diff --git a/src/pipeline/VfgBackend.cpp b/src/pipeline/VfgBackend.cpp
index ce0d736e..2f446727 100644
--- a/src/pipeline/VfgBackend.cpp
+++ b/src/pipeline/VfgBackend.cpp
@@ -4,9 +4,15 @@
#include "veyra/Log.h"
#include <Windows.h>
#include <array>
+#include <algorithm>
#include <chrono>
+#include <atomic>
+#include <condition_variable>
+#include <deque>
#include <filesystem>
#include <format>
+#include <mutex>
+#include <thread>
#include <vector>
#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
#include <cuda.h>
@@ -105,6 +111,19 @@ struct VfgBackend::Impl {
unsigned width=0,height=0,maxMultiplier=2;
DXGI_FORMAT format=DXGI_FORMAT_UNKNOWN;
bool ready=false;
+ uint64_t inputRevision=0,boundInputRevision=0;
+ unsigned boundParity=2,boundMultiplier=0;
+ bool boundReset=false;
+ struct Job {unsigned parity,sub,multiplier;bool reset;uint64_t revision,value;};
+ std::array<std::atomic<SubmissionState>,kOutputs> states{};
+ std::atomic<bool> failed=false;
+ std::mutex jobsMutex,profileMutex;
+ std::condition_variable jobsChanged;
+ std::deque<Job> jobs;
+ std::thread worker;
+ bool asynchronous=false,stopping=false;
+ unsigned outstanding=0;
+ unsigned rejectRun=0,runCount=0; // process-local deterministic failure test
bool profileCpu=false;
std::array<double,13> cpuSum{},cpuMax{};
std::array<unsigned,13> cpuSamples{};
@@ -113,10 +132,13 @@ struct VfgBackend::Impl {
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();
+ std::lock_guard lock(profileMutex);
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;
+ if(!profileCpu)return;
+ std::lock_guard lock(profileMutex);
+ if(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]);
@@ -173,31 +195,107 @@ struct VfgBackend::Impl {
if(buffer.memory){cu(cuDestroyExternalMemoryFn(buffer.memory),"cuDestroyExternalMemory");buffer.memory=nullptr;}
buffer.resource.Reset();
}
- bool handoff(unsigned parity,unsigned sub,unsigned multiplier,bool reset){
+ bool cudaJob(const Job& job){
+ const auto [parity,sub,multiplier,reset,revision,value]=job;
Current current(*this);if(!current.active)return false;
- const uint64_t value=++signalValue;
- 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(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.
+ bool ok=cu(cpuCall(2,[&]{return cuWaitExternalSemaphoresAsyncFn(&inputSemaphore,&wait,1,stream);}),"cuWaitExternalSemaphoresAsync")&&!failed.load();
+ // NVIDIA MIT sample, commit 52011f89c1741d06b40ea312af1f20be8be9ec62,
+ // VideoFrameGenerationEffectApp: both input images must be rebound for
+ // each NEW pair, even when their pointers are unchanged. Rebinding for
+ // every subframe instead starts a new pair inside the SDK. Keep the
+ // same pair bound while selecting its remaining intermediate frames.
+ // capture() revisions also handle callers that start at another index.
+ if(ok&&(sub==1||revision!=boundInputRevision||parity!=boundParity||reset!=boundReset)){
+ 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(6,[&]{return setU32(effect,"ShotChange",reset?1u:0u);}),"SetU32 ShotChange");
+ if(ok){boundInputRevision=revision;boundParity=parity;boundReset=reset;}
+ }
+ if(ok&&boundMultiplier!=multiplier){
+ ok=cv(cpuCall(7,[&]{return setU32(effect,"FrameMultiplier",multiplier);}),"SetU32 FrameMultiplier");
+ if(ok)boundMultiplier=multiplier;
+ }
+ ok=ok&&cv(cpuCall(5,[&]{return setImage(effect,"DstImage0",outputs[parity+2*(sub-1)].image);}),"SetImage output")&&
+ cv(cpuCall(8,[&]{return setU32(effect,"FrameIndex",sub);}),"SetU32 FrameIndex");
+ if(ok){
+ if(rejectRun&&++runCount==rejectRun){log::warn("vfg","injected VFG Run rejection (test hook)");ok=false;}
+ else ok=cv(cpuCall(9,[&]{return run(effect,1);}),"NvVFX_Run async");
+ }
+ // Publish rejection before releasing the consumer. Its GPU copy still
+ // drains, but resolveFrame must never present that slot as a success.
+ if(!ok)failed.store(true);
CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS signal{};signal.params.fence.value=value;
- 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;
+ if(!cu(cpuCall(10,[&]{return cuSignalExternalSemaphoresAsyncFn(&outputSemaphore,&signal,1,stream);}),"cuSignalExternalSemaphoresAsync")){
+ failed.store(true);
+ // Exceptional recovery only: drain any earlier CUDA writes before
+ // releasing a prequeued D3D wait. Normal frames never synchronize.
+ cu(cuStreamSynchronizeFn(stream),"failed handoff cuStreamSynchronize");
+ hr(completion->Signal(value),"release rejected VFG completion");
+ ok=false;
+ }
return ok;
}
+ void work(){
+ for(;;){
+ Job job{};
+ {std::unique_lock lock(jobsMutex);jobsChanged.wait(lock,[&]{return stopping||!jobs.empty();});
+ if(jobs.empty())return;job=jobs.front();jobs.pop_front();}
+ bool ok=false;
+ try{ok=cudaJob(job);}catch(...){log::error("vfg","SDK worker exception; disabling VFG");}
+ if(!ok){
+ failed.store(true);
+ // A context push failure/exception must also release its wait.
+ // cudaJob normally signals on the CUDA stream, so only force a
+ // CPU signal after draining it in the same primary context.
+ Current current(*this);
+ if(current.active&&stream)cu(cuStreamSynchronizeFn(stream),"rejected job drain");
+ hr(completion->Signal(job.value),"release failed VFG job");
+ }
+ states[job.parity+2*(job.sub-1)].store(ok?SubmissionState::Succeeded:SubmissionState::Failed);
+ logCpu();
+ {std::lock_guard lock(jobsMutex);--outstanding;}
+ }
+ }
+ bool handoff(unsigned parity,unsigned sub,unsigned multiplier,bool reset){
+ const unsigned slot=parity+2*(sub-1);
+ if(!asynchronous){
+ const uint64_t value=++signalValue;
+ if(!hr(cpuCall(1,[&]{return context->directQueue()->Signal(producer.Get(),value);}),"signal VFG producer"))return false;
+ const bool ok=cudaJob({parity,sub,multiplier,reset,inputRevision,value});
+ if(!ok){
+ failed.store(true);Current current(*this);
+ if(current.active&&stream)cu(cuStreamSynchronizeFn(stream),"rejected synchronous job drain");
+ hr(completion->Signal(value),"release failed synchronous VFG job");
+ }
+ states[slot].store(ok?SubmissionState::Succeeded:SubmissionState::Failed);
+ if(!hr(cpuCall(11,[&]{return context->directQueue()->Wait(completion.Get(),value);}),"queue wait VFG completion"))return false;
+ logCpu();return ok;
+ }
+ std::lock_guard lock(jobsMutex);
+ if(stopping||failed.load()||outstanding>=kOutputs){
+ log::error("vfg","bounded VFG submission rejected; no GPU wait queued");return false;
+ }
+ const uint64_t value=++signalValue;
+ if(!hr(cpuCall(1,[&]{return context->directQueue()->Signal(producer.Get(),value);}),"signal VFG producer"))return false;
+ // Allocate the queue entry before adding a GPU dependency. Even a host
+ // allocation exception cannot leave a wait with no job to signal it.
+ jobs.push_back({parity,sub,multiplier,reset,inputRevision,value});
+ if(!hr(cpuCall(11,[&]{return context->directQueue()->Wait(completion.Get(),value);}),"queue wait VFG completion")){
+ jobs.pop_back();return false;
+ }
+ states[slot].store(SubmissionState::Pending);++outstanding;jobsChanged.notify_one();return true;
+ }
+ void stopWorker(){
+ {std::lock_guard lock(jobsMutex);stopping=true;}
+ jobsChanged.notify_one();if(worker.joinable())worker.join();
+ }
#endif
};
VfgBackend::VfgBackend():impl_(std::make_unique<Impl>()){}
VfgBackend::~VfgBackend(){shutdown();}
-bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring& root,unsigned width,unsigned height,DXGI_FORMAT format,unsigned multiplier,unsigned quality){
+bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring& root,unsigned width,unsigned height,DXGI_FORMAT format,unsigned multiplier,unsigned quality,bool asynchronousSubmission){
shutdown();
#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
auto& p=*impl_;
@@ -207,6 +305,9 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&
}
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;
+ wchar_t reject[16]{};
+ const auto rejectLength=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_REJECT_RUN",reject,16);
+ if(rejectLength&&rejectLength<16)p.rejectRun=unsigned(std::clamp(_wtoi(reject),0,1000000));
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
@@ -278,9 +379,16 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&
!p.cv(p.setImage(p.effect,"SrcImage0",p.inputs[0].image),"initial previous")||!p.cv(p.setImage(p.effect,"SrcImage1",p.inputs[1].image),"initial current")||
!p.cv(p.loadEffect(p.effect),"NvVFX_Load")||!p.cv(p.setImage(p.effect,"DstImage0",p.outputs[0].image),"initial output")||
!p.cv(p.setU32(p.effect,"FrameMultiplier",multiplier),"initial multiplier"))return false;
+ p.boundMultiplier=multiplier;
+ p.asynchronous=asynchronousSubmission;
+ if(p.asynchronous){
+ try{p.worker=std::thread([&p]{p.work();});}
+ catch(...){log::error("vfg","VFG worker creation failed");return false;}
+ }
+ log::info("vfg",std::format("SDK submission={} capacity={} (CUDA work remains serial)",p.asynchronous?"bounded worker":"graph owner",kOutputs));
p.ready=true;log::info("vfg","native VFG initialized; GPU-only D3D12 buffer/fence bridge");return true;
#else
- (void)context;(void)root;(void)width;(void)height;(void)format;(void)multiplier;(void)quality;
+ (void)context;(void)root;(void)width;(void)height;(void)format;(void)multiplier;(void)quality;(void)asynchronousSubmission;
log::error("vfg","VFG unavailable: configure VEYRA_CUDA_DRIVER_INCLUDE_DIR");return false;
#endif
}
@@ -293,7 +401,7 @@ bool VfgBackend::created()const{
}
bool VfgBackend::capture(ID3D12GraphicsCommandList* list,ID3D12Resource* texture,unsigned parity){
#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
- auto& p=*impl_;if(!p.ready||!list||!texture||parity>1)return false;
+ auto& p=*impl_;if(!p.ready||p.failed.load()||!list||!texture||parity>1)return false;
const auto desc=texture->GetDesc();if(desc.Width!=p.width||desc.Height!=p.height||desc.Format!=p.format)return false;
auto* buffer=p.inputs[parity].resource.Get();
D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;barrier.Transition={buffer,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST};
@@ -301,19 +409,26 @@ bool VfgBackend::capture(ID3D12GraphicsCommandList* list,ID3D12Resource* texture
D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=texture;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=buffer;dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=p.footprint;
list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
- std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);return true;
+ std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);++p.inputRevision;return true;
#else
(void)list;(void)texture;(void)parity;return false;
#endif
}
bool VfgBackend::generate(unsigned parity,unsigned sub,unsigned multiplier,bool reset){
#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
- auto& p=*impl_;if(!p.ready||parity>1||multiplier<2||multiplier>p.maxMultiplier||sub<1||sub>=multiplier)return false;
- const bool ok=p.handoff(parity,sub,multiplier,reset);p.logCpu();return ok;
+ auto& p=*impl_;if(!p.ready||p.failed.load()||parity>1||multiplier<2||multiplier>p.maxMultiplier||sub<1||sub>=multiplier)return false;
+ return p.handoff(parity,sub,multiplier,reset);
#else
(void)parity;(void)sub;(void)multiplier;(void)reset;return false;
#endif
}
+VfgBackend::SubmissionState VfgBackend::submissionState(unsigned slot)const{
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ return slot<kOutputs?impl_->states[slot].load():SubmissionState::Failed;
+#else
+ (void)slot;return SubmissionState::Failed;
+#endif
+}
bool VfgBackend::copyOutput(ID3D12GraphicsCommandList* list,ID3D12Resource* texture,unsigned slot){
#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
auto& p=*impl_;if(!p.ready||!list||!texture||slot>=2*(p.maxMultiplier-1))return false;
@@ -331,7 +446,7 @@ bool VfgBackend::copyOutput(ID3D12GraphicsCommandList* list,ID3D12Resource* text
}
void VfgBackend::shutdown(){
#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
- auto& p=*impl_;p.ready=false;
+ auto& p=*impl_;p.ready=false;p.stopWorker();
if(p.cudaContext&&p.cuCtxPushCurrentFn&&p.cuCtxPopCurrentFn){
Impl::Current current(p);
if(current.active){
diff --git a/tests/integration/VfgGpuTests.cpp b/tests/integration/VfgGpuTests.cpp
index c4a9d817..04e30ff7 100644
--- a/tests/integration/VfgGpuTests.cpp
+++ b/tests/integration/VfgGpuTests.cpp
@@ -15,6 +15,7 @@
#include <chrono>
#include <vector>
#include <algorithm>
+#include <string_view>
using namespace veyra;
void transition(ID3D12GraphicsCommandList* l,ID3D12Resource* r,D3D12_RESOURCE_STATES a,D3D12_RESOURCE_STATES b){
D3D12_RESOURCE_BARRIER x{};x.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;x.Transition={r,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,a,b};l->ResourceBarrier(1,&x);
@@ -25,9 +26,10 @@ Microsoft::WRL::ComPtr<ID3D12Resource> makeReadback(ID3D12Device* device,uint64_
Microsoft::WRL::ComPtr<ID3D12Resource> buffer;if(FAILED(device->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&desc,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&buffer))))return {};return buffer;
}
int wmain(int argc,wchar_t** argv){
- if(argc<2){std::puts("usage: veyra_vfg_gpu_tests <runtime dir> [width height]");return 2;}
+ if(argc<2){std::puts("usage: veyra_vfg_gpu_tests <runtime dir> [width height [async]]");return 2;}
const unsigned w=argc>2?unsigned(_wtoi(argv[2])):1280,h=argc>3?unsigned(_wtoi(argv[3])):720;
if(!w||!h||w>3840||h>2160)return 2;
+ const bool asynchronous=argc>4&&std::wstring_view(argv[4])==L"async";
unsigned checks=0,failed=0;const auto check=[&](bool b,const char* label){++checks;if(!b){++failed;std::printf("FAIL %s\n",label);}};
gfx::D3D12DeviceContext ctx;Status st=Status::Ok;gfx::DeviceContextDesc d{};d.enableDebugLayer=true;d.commandSlotCount=6;
if(!ctx.initialize(d,st))return 2;
@@ -56,7 +58,7 @@ int wmain(int argc,wchar_t** argv){
// Keep mapping for readback comparisons; upload memory is immutable.
for(unsigned quality=0;quality<3;++quality){
pipeline::VfgBackend vfg;
- if(!vfg.initialize(ctx,argv[1],w,h,format,8,quality)){std::puts("FAIL native VFG initialization");return 3;}
+ if(!vfg.initialize(ctx,argv[1],w,h,format,8,quality,asynchronous)){std::puts("FAIL native VFG initialization");return 3;}
for(unsigned p=0;p<2;++p){uint32_t slot=0;auto* l=ring.acquireNext(slot,st);if(!l)return 2;
transition(l,textures[p].Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);
D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=upload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;src.PlacedFootprint=fp;src.PlacedFootprint.Offset=p*bytes;
@@ -82,9 +84,11 @@ int wmain(int argc,wchar_t** argv){
if(!ring.submitAndSignal(slot))return 2;
}
check(ring.waitIdle(),"diagnostic final group completion");
+ for(unsigned sub=1;sub<multiplier;++sub)check(vfg.submissionState(1+2*(sub-1))==pipeline::VfgBackend::SubmissionState::Succeeded,"SDK success before consuming each generated subframe");
const double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count();
D3D12_RANGE range{0,size_t(bytes*(multiplier-1))};void* pixels=nullptr;if(FAILED(readback->Map(0,&range,&pixels)))return 2;
std::set<uint64_t> hashes;double previous=inputCentroid[0];
+ std::array<uint64_t,7> orderedHashes{};
std::printf("VFG format=%u size=%ux%u quality=%u multiplier=%u groupWallMs=%.3f centroids=",unsigned(format),w,h,quality,multiplier,ms);
for(unsigned sub=1;sub<multiplier;++sub){uint64_t hash=1469598103934665603ull;double weight=0,sum=0;
for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){const auto* pixel=static_cast<uint8_t*>(pixels)+(sub-1)*bytes+y*fp.Footprint.RowPitch+x*4;
@@ -93,9 +97,12 @@ int wmain(int argc,wchar_t** argv){
const double value=red>40?red-16:0;sum+=value;weight+=value*x;
}
const auto center=sum?weight/sum:-1;std::printf("%.3f,",center);hashes.insert(hash);
+ orderedHashes[sub-1]=hash;
check(center>previous-1&&center>inputCentroid[0]-1&&center<inputCentroid[1]+1,"intermediate red block advances between A/B");previous=center;
}
- std::printf(" distinct=%zu\n",hashes.size());check(hashes.size()==multiplier-1,"all generated subframes distinct");
+ std::printf(" distinct=%zu hashes=",hashes.size());
+ for(unsigned sub=1;sub<multiplier;++sub)std::printf("%016llx,",static_cast<unsigned long long>(orderedHashes[sub-1]));
+ std::puts("");check(hashes.size()==multiplier-1,"all generated subframes distinct");
D3D12_RANGE written{0,0};readback->Unmap(0,&written);
}
// Manual cut must not reuse the previous input; clear ShotChange on
@@ -108,10 +115,51 @@ int wmain(int argc,wchar_t** argv){
D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=readback.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=fp;
l->CopyTextureRegion(&dst,0,0,0,&src,nullptr);transition(l,output.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
check(ring.submitAndSignal(slot)&&ring.waitIdle(),"cut output ready");
+ check(vfg.submissionState(1)==pipeline::VfgBackend::SubmissionState::Succeeded,"manual cut SDK success");
void* pixels=nullptr;D3D12_RANGE range{0,size_t(bytes)};if(FAILED(readback->Map(0,&range,&pixels)))return 2;
unsigned maxError=0;for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w*4;++x){
const auto a=static_cast<uint8_t*>(pixels)[y*fp.Footprint.RowPitch+x];const auto b=static_cast<uint8_t*>(mapped)[bytes+y*fp.Footprint.RowPitch+x];maxError=std::max(maxError,unsigned(std::abs(int(a)-int(b))));}
check(maxError<=2,"manual cut equals current encoded input");std::printf("cutMaxByteError=%u\n",maxError);D3D12_RANGE written{0,0};readback->Unmap(0,&written);
+ // Reuse the exact imported addresses with fresh contents, then
+ // reverse parity. This catches stale-pair caches after a cut and
+ // exercises reduced 2X -> full 4X -> 8X without reallocating SDK images.
+ for(unsigned direction=0;direction<2;++direction){
+ const unsigned parity=direction?0:1,multiplier=direction?8:4;
+ for(unsigned p=0;p<2;++p){
+ auto* l=ring.acquireNext(slot,st);if(!l)return 2;
+ transition(l,textures[1-p].Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ check(vfg.capture(l,textures[1-p].Get(),p),"refresh pixels at same imported CUDA address");
+ transition(l,textures[1-p].Get(),D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
+ if(!ring.submitAndSignal(slot))return 2;
+ }
+ for(unsigned sub=1;sub<multiplier;++sub){
+ check(vfg.generate(parity,sub,multiplier,false),"resume full group after cut/reduced group");
+ auto* l=ring.acquireNext(slot,st);if(!l)return 2;
+ transition(l,output.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);
+ check(vfg.copyOutput(l,output.Get(),parity+2*(sub-1)),"refreshed pair output copy");
+ transition(l,output.Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ D3D12_TEXTURE_COPY_LOCATION from{};from.pResource=output.Get();from.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ D3D12_TEXTURE_COPY_LOCATION to{};to.pResource=readback.Get();to.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;to.PlacedFootprint=fp;to.PlacedFootprint.Offset=(sub-1)*bytes;
+ l->CopyTextureRegion(&to,0,0,0,&from,nullptr);
+ transition(l,output.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
+ if(!ring.submitAndSignal(slot))return 2;
+ }
+ check(ring.waitIdle(),"refreshed pair final completion");
+ range={0,size_t(bytes*(multiplier-1))};if(FAILED(readback->Map(0,&range,&pixels)))return 2;
+ double previous=inputCentroid[direction?0:1];std::printf("VFG_REFRESH format=%u quality=%u parity=%u multiplier=%u centroids=",unsigned(format),quality,parity,multiplier);
+ for(unsigned sub=1;sub<multiplier;++sub){double sum=0,weight=0;
+ check(vfg.submissionState(parity+2*(sub-1))==pipeline::VfgBackend::SubmissionState::Succeeded,"refreshed pair SDK success");
+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){
+ const auto* pixel=static_cast<uint8_t*>(pixels)+(sub-1)*bytes+y*fp.Footprint.RowPitch+x*4;
+ unsigned red=pixel[0];if(format!=DXGI_FORMAT_R8G8B8A8_UNORM){uint32_t packed=0;std::memcpy(&packed,pixel,4);red=(packed&1023)*255/1023;}
+ const double v=red>40?red-16:0;sum+=v;weight+=v*x;
+ }
+ const double center=sum?weight/sum:-1;std::printf("%.3f,",center);
+ check(center>inputCentroid[0]-1&&center<inputCentroid[1]+1&&
+ (direction?center>previous-1:center<previous+1),"new pair motion follows refreshed pixels and parity");previous=center;
+ }
+ std::puts("");readback->Unmap(0,&written);
+ }
check(!vfg.generate(1,8,8,false)&&!vfg.generate(2,1,2,false)&&!vfg.generate(0,1,9,false),"invalid slot/multiplier rejected");
vfg.shutdown();
}