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

fix(vfg): budget queued reduced groups from measured single-frame work

Veyra Goal Agentadb1c8be544a
diff --git a/AGENTS.md b/AGENTS.md
index 70cdaef6..45742d95 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,6 +1,6 @@
# Veyra 项目 Agent 执行规则
-> **2026-10-07 VFG继续优化授权**:用户要求继续尝试VFG优化。按docs/VFG_NEXT_PLAN_2026-10-07.md从正式2.0.6后main 96a7c8de在E盘codex/vfg-next-20261007隔离实施VFG必要互操作/提交及定向测试、本地候选;覆盖对应旧冻结。先运行vfg-next-control.py,独立start/bundle保护34工作树、495脏文件和3691项原件,不改旧guard。其它补帧/NR/时钟/显示策略不动,DLL/模型原字节;不派Agent/压力竞争、不改用户配置/驱动,不merge/push/Release/关机。测试≤300秒、构建≤900秒、产物全E盘。
+> **2026-10-07 VFG继续优化授权**:用户要求继续尝试VFG优化。按docs/VFG_NEXT_PLAN_2026-10-07.md从正式2.0.6后main 96a7c8de在E盘codex/vfg-next-20261007隔离实施VFG必要互操作/提交/专属排队预算及定向测试、本地候选;覆盖对应旧冻结。先运行vfg-next-control.py,独立start/bundle保护34工作树、495脏文件和3691项原件,不改旧guard。其它补帧/NR/时钟/显示策略不动,DLL/模型原字节;不派Agent/压力竞争、不改用户配置/驱动,不merge/push/Release/关机。测试≤300秒、构建≤900秒、产物全E盘。
> **2026-10-07 2.0.6正式发布授权**:用户明确构建2.0.6并发布GitHub,替换满员4群为所附5群二维码,发布后交付群公告。按docs/RELEASE_2.0.6_PLAN_2026-10-07.md从已验bf6e651在E盘codex/release-2.0.6-20261007整合VFG/Blackmagic/AMD NR-FSR修复,允许版本/双语README/新二维码/构建定向验收/同源码双显卡包及本轮commit/tag/main合并/普通push/v2.0.6正式Release与5资产上传。覆盖历史no-merge/no-push/no-Release;不扩改已验算法或运行组件,不改用户配置/驱动/其它工作树,不派Agent/竞争压力,不关机,群公告只交用户不代发。先运行release-2.0.6-control.py,独立start/bundle保护33工作树、495脏文件与3678项原件;仅main允许按合并回执推进,旧guard/baseline不改。测试≤300秒、构建≤900秒、产物全E盘。保留赞助QR/Discord/Ko-fi、双QR各width220,AMD/Blackmagic实卡与NV显存增长边界如实说明。
diff --git a/docs/VFG_NEXT_PLAN_2026-10-07.md b/docs/VFG_NEXT_PLAN_2026-10-07.md
index 24c28e2d..60076b1f 100644
--- a/docs/VFG_NEXT_PLAN_2026-10-07.md
+++ b/docs/VFG_NEXT_PLAN_2026-10-07.md
@@ -9,3 +9,10 @@
5. 只有证据支持才处理额外VFG专属瓶颈;禁止靠放宽过期门槛、丢更多帧、降低画质或放慢时钟伪造收益。所有产物E:/项目/Veyra下同名任务目录,测试每进程≤300秒、构建≤900秒。正常GPU串行;已有SDK/DLL/模型原字节保持且不进源码Git。
当前:开工保护完成,优化尚未实现,收益待测。NVIDIA显存增长及其它硬件长稳不由本轮短测视为解决。
+
+
+## 第二节点:VFG排队预算修正
+
+同步减量实验已测:同EXE High3 68/68.5fps、Medium8 210/210fps、Medium6 180/180fps,未证明收益,撤回VfgBackend.cpp;实验ff8fdf4及独立EXE保留在tests/vfg-next-20261007/bin/producer-v1。SDK1.3官方CudaGraph selector实查get/set均-5,不实施CUDA图假说。能力探针首次未建CUDA context创建失败,补齐产品相同初始化后成功,原失败记录不作SDK不支持证据。
+
+具体发现:EngineController文件来源pendingCompletions的GPU成本,对fgReduced=true且fgEvaluated=1的VFG组仍用fgBudget.predicted的请求倍率完整成本。只在VFG这一分支按baseCost + Fg1 GPU P95核算一张插帧,并以完整成本为上界;无测量/非1次/历史恢复沿用原估计。其它补帧、admitFile、截止时间/宽限/倍率/reset/画质不改。必要接点扩展到src/engine/EngineController.cpp、独立include/veyra/engine/VfgQueueBudget.h和tests/unit/VfgSettingsTests.cpp,guard独立范围同步扩展,不改start或旧保护。环境VEYRA_TEST_VFG_FULL_REDUCED_QUEUE_COST仅作旧估计对照。先相邻High3、Medium8/7,若无收益或增加过期/跳源帧则撤回;已有全像素合同和生命周期/导出在保留候选后验收。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 839045e0..9c272a4b 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,13 @@
# WORKLOG
+## 2026-10-07 VFG第二节点:排队预算实验
+
+- 同EXE同步减量High3 68/68.5、Medium8 210/210、Medium6 180/180fps:无明确收益,已将VfgBackend.cpp恢复96a7c8de原字节;ff8fdf4及EXE在tests/vfg-next-20261007/bin/producer-v1存档。SDK1.3 CudaGraph selector get/set=-5,未实施;能力探针首次未建CUDA context创建失败,补齐产品初始化后成功,sdk-capabilities.json保留正确返回码。
+- VFG降档2X(fgReduced=true且一次evaluate)在文件pendingCompletions仍按请求完整倍率计费。只为VFG改用baseCost+Fg1 GPU P95,并以完整成本为上界;缺失/非法测量、历史恢复、多次evaluate保持原估算。其它后端和截止时间/宽限/画质/时钟/导出不变。回退开关VEYRA_TEST_VFG_FULL_REDUCED_QUEUE_COST只用于同EXE对照。
+- queue-budget-v1构建通过,VFG设置/预算339检查0失败。High3修正a/b=73/74.5fps,对照b=69fps(a原始日志也是69);b观察段过期插帧1比4,跳源0,播放速率0.997–1.005;软件呈现entry P95中位2.326ms比3.500ms。仍低于完整90fps,不冒充GPU模型加速或屏幕延迟。
+- 新增日志解析最初正则遗漏P95中的数字,queue-control-high3-a与queue-medium8-a GUI均PASS但驱动收尾KeyError,无持久化退出回执,不纳入正式对照;raw/recovered-analysis留证,修正解析并在启动及退出提前落盘,重新跑b。单独离线分析首次忽略SDK日志非UTF8字节而解码失败,改errors=replace后成功,不改原始日志。
+- 后续:串行档位对照及必要像素/GUI生命周期/完整导出回归,全部任务目录E:/项目/Veyra/{build,logs,tests,tmp,verify,test-packages}/vfg-next-20261007。尚未交付或合入main。
+
## 2026-10-07 VFG继续优化实验v1
- 首次构建目标veyra_settings_tests不存在,Ninja未编译;改为已存在的veyra_fg_settings_tests,candidate-v1-retry构建成功。日志logs/vfg-next-20261007/candidate-v1*.log/json保留失败,不掩盖。
diff --git a/include/veyra/engine/VfgQueueBudget.h b/include/veyra/engine/VfgQueueBudget.h
new file mode 100644
index 00000000..7dcfd18b
--- /dev/null
+++ b/include/veyra/engine/VfgQueueBudget.h
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include <algorithm>
+#include <cmath>
+#include <optional>
+
+namespace veyra::engine {
+// A reduced VFG group executes one interpolation, not the requested M-1.
+// Its queued work is base + the measured first interpolation. Retain the full
+// estimate when measurement/history is unavailable, and never increase it.
+inline std::optional<double> vfgQueuedGroupCost(std::optional<double> full,
+ std::optional<double> base,std::optional<double> first,bool reduced,
+ unsigned evaluations,bool warmingHistory){
+ const auto valid=[](std::optional<double> value){return value&&std::isfinite(*value)&&*value>=0;};
+ if(!reduced||evaluations!=1||warmingHistory||!valid(full)||!valid(base)||!valid(first)||*full<*base)return full;
+ return std::min(*full,*base+*first);
+}
+}
diff --git a/scripts/acceptance/vfg-next-capabilities.py b/scripts/acceptance/vfg-next-capabilities.py
new file mode 100644
index 00000000..60ef5bea
--- /dev/null
+++ b/scripts/acceptance/vfg-next-capabilities.py
@@ -0,0 +1,36 @@
+"""Query documented SDK selectors without loading models or changing binaries."""
+from pathlib import Path
+import ctypes as c,json,os,subprocess,sys
+import psutil
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-next-20261007'
+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/vfg-next-control.py')],check=True)
+assert not any(p.info['name'].lower() in ('veyra.exe','veyra_qml_ui.exe','veyra_vfg_gpu_tests.exe','veyra_vfg_export_probe.exe') for p in psutil.process_iter(['name']))
+runtime=BASE/'tests'/TASK/'app/runtime/nvidia-vfg'
+tmp=BASE/'tmp'/TASK/'capabilities-v2';tmp.mkdir(parents=True,exist_ok=False)
+os.environ.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'))
+driver=c.CDLL(str(Path(os.environ['WINDIR'])/'System32/nvcuda.dll'),winmode=0x800)
+def cu(name,args):
+ f=getattr(driver,name);f.argtypes=args;f.restype=c.c_int;return f
+assert cu('cuInit',[c.c_uint])(0)==0
+context=c.c_void_p();assert cu('cuDevicePrimaryCtxRetain',[c.POINTER(c.c_void_p),c.c_int])(c.byref(context),0)==0
+assert cu('cuCtxPushCurrent_v2',[c.c_void_p])(context)==0
+with os.add_dll_directory(str(runtime)):
+ loaded=[c.CDLL(str(runtime/name),winmode=0x100|0x800|0x400) for name in ('cudart64_12.dll','NVCVImage.dll','nvngxruntime.dll','NVVideoEffects.dll','nvVFXVideoFrameGeneration.dll')]
+ sdk=c.CDLL(str(runtime/'NVVideoEffects.dll'),winmode=0x100|0x800|0x400)
+ create=sdk.NvVFX_CreateEffect;create.argtypes=[c.c_char_p,c.POINTER(c.c_void_p)];create.restype=c.c_int
+ destroy=sdk.NvVFX_DestroyEffect;destroy.argtypes=[c.c_void_p];destroy.restype=None
+ get=sdk.NvVFX_GetU32;get.argtypes=[c.c_void_p,c.c_char_p,c.POINTER(c.c_uint)];get.restype=c.c_int
+ setu=sdk.NvVFX_SetU32;setu.argtypes=[c.c_void_p,c.c_char_p,c.c_uint];setu.restype=c.c_int
+ version=c.c_uint();sdk.NvVFX_GetVersion.argtypes=[c.POINTER(c.c_uint)];sdk.NvVFX_GetVersion.restype=c.c_int
+ result={'runtime':str(runtime),'versionStatus':sdk.NvVFX_GetVersion(c.byref(version)),'version':hex(version.value),'selectors':[]}
+ effect=c.c_void_p();result['createStatus']=create(b'VideoFrameGeneration',c.byref(effect));print('createStatus',result['createStatus'],flush=True);assert result['createStatus']==0
+ try:
+ for name,value in [('Mode',1),('CudaGraph',1),('BatchSize',1)]:
+ before=c.c_uint();rc=get(effect,name.encode(),c.byref(before));setRc=setu(effect,name.encode(),value)
+ after=c.c_uint();afterRc=get(effect,name.encode(),c.byref(after))
+ result['selectors'].append({'name':name,'getStatus':rc,'before':before.value,'setStatus':setRc,'afterStatus':afterRc,'after':after.value})
+ finally:destroy(effect)
+previous=c.c_void_p();assert cu('cuCtxPopCurrent_v2',[c.POINTER(c.c_void_p)])(c.byref(previous))==0
+assert cu('cuDevicePrimaryCtxRelease_v2',[c.c_int])(0)==0
+out=BASE/'logs'/TASK/'sdk-capabilities.json';out.write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')
+print(json.dumps(result,ensure_ascii=False))
diff --git a/scripts/acceptance/vfg-next-control.py b/scripts/acceptance/vfg-next-control.py
index 88840e31..4cd43fca 100644
--- a/scripts/acceptance/vfg-next-control.py
+++ b/scripts/acceptance/vfg-next-control.py
@@ -3,7 +3,7 @@ from pathlib import Path
import hashlib,json,subprocess
ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-next-20261007'
START=BASE/'archives'/TASK/'start.json'
-ALLOWED={'AGENTS.md','docs/WORKLOG.md','src/pipeline/VfgBackend.cpp','tests/integration/VfgGpuTests.cpp'}
+ALLOWED={'AGENTS.md','docs/WORKLOG.md','src/pipeline/VfgBackend.cpp','tests/integration/VfgGpuTests.cpp','src/engine/EngineController.cpp','include/veyra/engine/VfgQueueBudget.h','tests/unit/VfgSettingsTests.cpp'}
def sha(p):
with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
def git(*args,cwd=ROOT):return subprocess.check_output(['git',*args],cwd=cwd)
diff --git a/scripts/acceptance/vfg-next-preview.py b/scripts/acceptance/vfg-next-preview.py
index 15a3e425..33283210 100644
--- a/scripts/acceptance/vfg-next-preview.py
+++ b/scripts/acceptance/vfg-next-preview.py
@@ -1,6 +1,7 @@
"""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 datetime import datetime
from ctypes import wintypes
import psutil
@@ -41,7 +42,7 @@ def run(args):
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'
+ selected=PACKAGE/'veyra_qml_ui.exe' if args.original else BASE/'tests'/TASK/'bin/producer-v1/veyra_qml_ui.exe' if args.producer_experiment 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
@@ -58,10 +59,12 @@ def run(args):
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.full_reduced_queue_cost:env['VEYRA_TEST_VFG_FULL_REDUCED_QUEUE_COST']='1'
if args.per_frame_producer:env['VEYRA_TEST_VFG_PER_FRAME_PRODUCER']='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,'syncSubmit':args.sync_submit,'perFrameProducer':args.per_frame_producer,'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,'perFrameProducer':args.per_frame_producer,'fullReducedQueueCost':args.full_reduced_queue_cost,'selectedBinary':str(selected)}
+ save(out/'launch.json',receipt)
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)
@@ -73,6 +76,9 @@ def run(args):
else:rc=proc.returncode
finally:
if proc.poll() is None:proc.kill();proc.wait(timeout=10)
+ receipt.update(exitCode=rc,wallSeconds=time.monotonic()-started)
+ save(out/'process-exit.json',receipt)
+ save(out/'meters.json',meters)
text=(out/'player.log').read_text(encoding='utf8',errors='replace');rows=[]
for line in text.splitlines():
if 'VFG_DIAG_SAMPLE ' in line:
@@ -85,6 +91,19 @@ def run(args):
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]
+ counters=[line for line in text.splitlines() if '[frame-flow] state=closed ' in line]
+ receipt['closedCounters']={k:float(v) for k,v in re.findall(r'([A-Za-z][A-Za-z0-9]*)=(-?\d+(?:\.\d+)?)',counters[-1])} if counters else {}
+ timing=[]
+ for line in text.splitlines():
+ if '[player-timing]' not in line:continue
+ wall=datetime.fromisoformat(line.split()[0].replace('Z','+00:00')).timestamp()*1000
+ if rows and rows[0]['wall']<=wall<=rows[-1]['wall']:
+ timing.append({k:float(v) for k,v in re.findall(r'([A-Za-z][A-Za-z0-9]*)=(-?\d+(?:\.\d+)?)',line)})
+ if timing:
+ receipt['observationTiming']={'samples':len(timing),'expiredGenerated':timing[-1]['expiredGenerated']-timing[0]['expiredGenerated'],'previewSkipped':timing[-1]['previewSkipped']-timing[0]['previewSkipped'],
+ 'playbackSpeedMin':min(t['playbackSpeed'] for t in timing),'playbackSpeedMax':max(t['playbackSpeed'] for t in timing),
+ 'entryAbsP95MsMedian':statistics.median(t['entryAbsP95Ms'] for t in timing),'entryAbsP95MsMax':max(t['entryAbsP95Ms'] for t in timing),'returnAbsP95MsMedian':statistics.median(t['returnAbsP95Ms'] for t in timing),
+ 'gpuFgBatchP95MsMedian':statistics.median(t['gpuFgBatchP95Ms'] for t in timing),'gpuReadyP95MsMedian':statistics.median(t['gpuReadyP95Ms'] for t in timing)}
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']:
@@ -95,6 +114,7 @@ parser.add_argument('--multiplier',type=int,choices=range(2,9),default=2);parser
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');parser.add_argument('--per-frame-producer',action='store_true')
+parser.add_argument('--full-reduced-queue-cost',action='store_true');parser.add_argument('--producer-experiment',action='store_true')
args=parser.parse_args()
subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/vfg-next-control.py')],check=True)
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index b39d7760..293f1f33 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -16,6 +16,7 @@
#include "veyra/engine/AutoNrController.h"
#include "veyra/engine/LiveFgAdmission.h"
#include "veyra/engine/FgRecoveryBudget.h"
+#include "veyra/engine/VfgQueueBudget.h"
#include "veyra/engine/LivePairLatency.h"
#include "veyra/engine/RealtimePreviewScheduling.h"
#include "veyra/engine/CaptureHalfRate.h"
@@ -905,6 +906,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
TimingWindow livePresent{std::chrono::seconds(1)};
TimingWindow livePresentGpu{std::chrono::seconds(1)};
FgRecoveryBudget fgBudget;uint64_t fgBudgetRevision=options.settings.revision;
+ const bool vfgMeasuredReducedQueue=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_FULL_REDUCED_QUEUE_COST",nullptr,0)==0;
+ int64_t nextVfgQueueLog=0;
unsigned previewFgMultiplier=options.fgMultiplier;
LivePairLatency pairLatency;
const bool adaptiveCapturePhase=physicalCapture&&GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_CAPTURE_PHASE",nullptr,0)==0;
@@ -1798,7 +1801,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
for(const auto& previous:pendingCompletions){
if(previous->output.gpuComplete())continue;
const auto began=std::chrono::duration_cast<std::chrono::nanoseconds>(previous->processStart.time_since_epoch()).count()/100;
- const auto cost=previous->output.fgEvaluated?fgBudget.predicted(start,previous->output.historyReset||previous->output.fgRecovery):fgBudget.baseCost(start);
+ auto cost=previous->output.fgEvaluated?fgBudget.predicted(start,previous->output.historyReset||previous->output.fgRecovery):fgBudget.baseCost(start);
+ if(vfgMeasuredReducedQueue&&options.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&previous->output.fgReduced){
+ const auto first=frameFlow->snapshot(start).gpuTiming[size_t(diagnostics::GpuStage::Fg1)].p95;
+ const auto measured=vfgQueuedGroupCost(cost,fgBudget.baseCost(start),first,true,previous->output.fgEvaluated,previous->output.historyReset||previous->output.fgRecovery);
+ if(cost&&measured&&*measured<*cost&&start>=nextVfgQueueLog){nextVfgQueueLog=start+10000000;
+ veyra::log::info("vfg-queue-budget",std::format("source={} queuedReduced=2X requested={} fullEstimateMs={:.3f} singleEstimateMs={:.3f} (base plus measured first interpolation; deadlines unchanged)",previous->output.batch.identity.sourceFrameId,options.fgMultiplier,*cost,*measured));}
+ cost=measured;
+ }
finish=std::max({finish,began,previous->predictedGpuStart100ns})+int64_t(cost.value_or(0)*10000);
}
queuedGpuMs=double(std::max<int64_t>(0,finish-start))/10000;
diff --git a/src/pipeline/VfgBackend.cpp b/src/pipeline/VfgBackend.cpp
index ca818f36..2f446727 100644
--- a/src/pipeline/VfgBackend.cpp
+++ b/src/pipeline/VfgBackend.cpp
@@ -114,12 +114,7 @@ struct VfgBackend::Impl {
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,producerValue;};
- // Owner-thread state is separate from the worker's SDK input binding. A
- // monotonic subframe sequence reads one immutable pair and writes distinct
- // outputs; new/repeated sequences must first drain the previous consumers.
- Job submitted{};
- bool haveSubmitted=false,perFrameProducer=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;
@@ -201,13 +196,10 @@ struct VfgBackend::Impl {
buffer.resource.Reset();
}
bool cudaJob(const Job& job){
- const auto [parity,sub,multiplier,reset,revision,value,producerValue]=job;
+ const auto [parity,sub,multiplier,reset,revision,value]=job;
Current current(*this);if(!current.active)return false;
- bool ok=!failed.load();
- if(producerValue){
- CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS wait{};wait.params.fence.value=producerValue;
- ok=cu(cpuCall(2,[&]{return cuWaitExternalSemaphoresAsyncFn(&inputSemaphore,&wait,1,stream);}),"cuWaitExternalSemaphoresAsync")&&ok;
- }
+ CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS wait{};wait.params.fence.value=value;
+ 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
@@ -267,18 +259,10 @@ struct VfgBackend::Impl {
}
bool handoff(unsigned parity,unsigned sub,unsigned multiplier,bool reset){
const unsigned slot=parity+2*(sub-1);
- const bool newDependency=perFrameProducer||!haveSubmitted||inputRevision!=submitted.revision||
- parity!=submitted.parity||reset!=submitted.reset||multiplier!=submitted.multiplier||sub<=submitted.sub;
- // The producer signal for a NEW pair follows capture and the preceding
- // pair's output copies on the direct queue. Later subframes use distinct
- // output buffers on the same serial CUDA stream, so waiting for each
- // preceding D3D copy would unnecessarily serialize the two queues.
- // Repeated/backward indices retain that dependency for safe slot reuse.
if(!asynchronous){
const uint64_t value=++signalValue;
- if(newDependency&&!hr(cpuCall(1,[&]{return context->directQueue()->Signal(producer.Get(),value);}),"signal VFG producer"))return false;
- const Job job{parity,sub,multiplier,reset,inputRevision,value,newDependency?value:0};
- const bool ok=cudaJob(job);
+ 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");
@@ -286,7 +270,6 @@ struct VfgBackend::Impl {
}
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;
- if(ok){submitted=job;haveSubmitted=true;}
logCpu();return ok;
}
std::lock_guard lock(jobsMutex);
@@ -294,15 +277,13 @@ struct VfgBackend::Impl {
log::error("vfg","bounded VFG submission rejected; no GPU wait queued");return false;
}
const uint64_t value=++signalValue;
- if(newDependency&&!hr(cpuCall(1,[&]{return 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;
// Allocate the queue entry before adding a GPU dependency. Even a host
// allocation exception cannot leave a wait with no job to signal it.
- const Job job{parity,sub,multiplier,reset,inputRevision,value,newDependency?value:0};
- jobs.push_back(job);
+ 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;
}
- submitted=job;haveSubmitted=true;
states[slot].store(SubmissionState::Pending);++outstanding;jobsChanged.notify_one();return true;
}
void stopWorker(){
@@ -324,7 +305,6 @@ 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;
- p.perFrameProducer=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_PER_FRAME_PRODUCER",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));
@@ -400,7 +380,6 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&
!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;
- log::info("vfg",std::format("input dependency={}; completion remains per output",p.perFrameProducer?"per output (test control)":"per input pair"));
p.asynchronous=asynchronousSubmission;
if(p.asynchronous){
try{p.worker=std::thread([&p]{p.work();});}
diff --git a/tests/unit/VfgSettingsTests.cpp b/tests/unit/VfgSettingsTests.cpp
index cc3b125a..e53b3f3b 100644
--- a/tests/unit/VfgSettingsTests.cpp
+++ b/tests/unit/VfgSettingsTests.cpp
@@ -1,16 +1,26 @@
#include "veyra/engine/PresetStore.h"
#include "veyra/engine/PresetLibrary.h"
+#include "veyra/engine/VfgQueueBudget.h"
#include "veyra/pipeline/FrameBatch.h"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
+#include <limits>
using namespace veyra::engine;
namespace {unsigned checks=0,failures=0;void check(bool ok,const char* why){++checks;if(!ok){++failures;std::cout<<"FAIL "<<why<<'\n';}}
std::string bytes(const std::filesystem::path& p){std::ifstream f(p,std::ios::binary);return {(std::istreambuf_iterator<char>(f)),{}};}}
int wmain(int argc,wchar_t** argv){
if(argc!=2||!std::filesystem::path(argv[1]).is_absolute())return 2;
const std::filesystem::path root=argv[1];if(!std::filesystem::create_directories(root))return 2;
+ check(vfgQueuedGroupCost(38.,7.,12.,true,1,false)==19.,"queued reduced group charges one interpolation instead of seven");
+ check(vfgQueuedGroupCost(38.,7.,12.,false,7,false)==38.,"full group keeps its measured full cost");
+ check(vfgQueuedGroupCost(38.,7.,12.,true,1,true)==38.,"history recovery retains conservative full cost");
+ check(vfgQueuedGroupCost(38.,7.,{},true,1,false)==38.&&vfgQueuedGroupCost(38.,{},12.,true,1,false)==38.,"missing measurements preserve full estimate");
+ check(!vfgQueuedGroupCost({},7.,12.,true,1,false),"unknown full cost stays unknown");
+ check(vfgQueuedGroupCost(38.,7.,12.,true,2,false)==38.,"unexpected multi-evaluation reduced group is not undercharged");
+ check(vfgQueuedGroupCost(38.,7.,std::numeric_limits<double>::quiet_NaN(),true,1,false)==38.&&vfgQueuedGroupCost(38.,7.,-1.,true,1,false)==38.,"invalid first timing cannot lower queue budget");
+ check(vfgQueuedGroupCost(15.,7.,12.,true,1,false)==15.,"reduced estimate never exceeds existing full cost");
check(!motionUsesFlow(MotionSource::OpticalFlow,FrameGenerationBackend::Vfg)&&
!motionUsesFlow(MotionSource::Automatic,FrameGenerationBackend::Vfg),"VFG uses its own motion even after a DLSS flow preset");
check(motionUsesFlow(MotionSource::OpticalFlow)&&motionUsesFlow(MotionSource::Automatic),"SR/NR external motion remains enabled");