Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
perf: trial bounded NVENC exports and independent fence event waits
Veyra Goal Agentb823f08cd0e6
diff --git a/docs/PERF_5B_CROSS_FRAME_2026-10-05.md b/docs/PERF_5B_CROSS_FRAME_2026-10-05.mdindex 85fc577f..533ff95b 100644--- a/docs/PERF_5B_CROSS_FRAME_2026-10-05.md+++ b/docs/PERF_5B_CROSS_FRAME_2026-10-05.md@@ -17,3 +17,7 @@ build-export-baseline-v1 UI/probe构建成功,编译产品源码86e0458;只串行总耗时三轮中位约普通4K2.484s、1080单NR4.306s、双NR4.544s、NR+SR4K6.341s、4K→8K的SR4.400s。除最后60帧,其余120帧。包含创建的总耗时和排除创建的pipeline计时必须分开,前者是实际用户等待。观察到多个配置pipeline每源帧约15.8ms、NR+SR4K约31.4ms,completionWait占比很高。当前等待是Sleep(1)轮询,尚未测其真实休眠时长,不能直接断言系统timer根因。候选将把fence事件等待和两帧在途作为独立开关/组,避免混淆等待精度与跨帧并行的收益。++基线完整软件解码15/15、1620帧,三轮A-A全图/PTS/尺寸/轨道/时长完全一致;核实SR8K实际7680×4320,NR+SR实际3840×2160。review在E:/项目/Veyra/logs/perf-nr-20261004/B5b-serial-v2-decoded-review.json,framemd5每帧覆盖完整重建图。后续复用这些不可变源与已核验hash,避免无依据重复解码。++候选实现:每个pending持有完整FrameOutputs/lease与NVENC转换consumerFence,最多两帧;在第3帧进入Graph前确认最旧producer+consumer完成并释放lease,末尾全部收齐再encoder.finish。Graph上传/allocator和NVENC4槽依赖不变。fence事件仅同一fence对象上的值取max,FG status仍完成后resolve;50ms有界wait、250ms健康检查和30s超时保留,事件注册失败记HRESULT并回退轮询。两个测试ENV分别启用,默认关闭,未测不标产品通过。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 5b59d419..acc23dbe 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -8300,3 +8300,5 @@ B4a-native-v2 20/20通过、800 PNG及逐图SHA/PTS保留;debug/设备移除05b build-export-baseline-v1构建UI/实际导出probe成功(21步);基线EXE编译源码86e0458。serial-v1驱动启动前错误调用不存在matrix.gpu,未启动导出;改实际函数gpu_query,脚本HEAD字段明确为driverSourceHead而不是冒充编译HEAD。原staging/空运行目录保留,后续用serial-v2新标签;与当前产品源码diff仅脚本/本条文档。5b serial-v2五组各三轮15/15实际完成,最终帧数/encoder drain通过,payload SHA全同。总耗时中位普通4K2.484s、单NR4.306s、双NR4.544s、NR+SR4K6.341s、SR8K4.400s。pipeline多组15.8ms/帧与Sleep(1)轮询有关联但根因待验证;下一候选独立测fence事件、两帧在途和组合,不能将两者混算。原全部导出/日志及基线EXE在B5b-serial-v2对应E盘目录。新增导出后全decoded frame/PTS/mux核对工具,当前先执行A-A。++5b基线A-A完整1620 decoded帧及PTS/尺寸/轨道/时长15/15全同,8K实为7680×4320,收据B5b-serial-v2-decoded-review.json。新增默认关闭候选:两帧pending lease/producer/consumer fence严格有界、复用前GPU完成、NVENC独立inputFence;独立fence事件等待、失败回轮询、取消/健康/30秒保留。源码审查修正std::move(out)之后取real.lease的潜在空指针,改先保存consumerFence再move,未构建/执行有缺陷版本。两个机制分组计时,尚未标收益。diff --git a/scripts/perf/nr-export-pipeline.py b/scripts/perf/nr-export-pipeline.pyindex be633f40..6028cb43 100644--- a/scripts/perf/nr-export-pipeline.py+++ b/scripts/perf/nr-export-pipeline.py@@ -4,7 +4,7 @@ import importlib.util,json,os,re,shutil,subprocess,sys,timeROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='perf-nr-20261004'spec=importlib.util.spec_from_file_location('matrix',ROOT/'scripts/perf/nr-matrix.py');matrix=importlib.util.module_from_spec(spec);spec.loader.exec_module(matrix)variant,label,mode=sys.argv[1:4];groups=sys.argv[4:] or ['none4k','nr','nr2','nrsr4k','sr8k']-assert mode in ('serial','async','interleaved')+assert mode in ('serial','events','async','async-events','interleaved','all')assert all(g in ('none4k','nr','nr2','sr4k','nrsr4k','sr8k','fg2') for g in groups)matrix.assert_gpu_tests_idle();app=BASE/'tests'/TASK/(label+'-app');assert not app.exists()shutil.copytree(BASE/'test-packages'/TASK/'Veyra-2.0.3-perf-baseline-A-NVIDIA-win64-portable',app,copy_function=matrix.copy_dependency)@@ -17,7 +17,7 @@ for group in groups:source=BASE/'tests/perf-matrix/media/M2.mkv' if group in ('none4k','sr8k') else matrix.SOURCES['M1']config='none' if group=='none4k' else group;frames=60 if group=='sr8k' else 120for repeat in range(1,4):- modes=(('serial','async') if repeat%2 else ('async','serial')) if mode=='interleaved' else (mode,)+ modes=(('serial','async') if repeat%2 else ('async','serial')) if mode=='interleaved' else (('serial','events','async','async-events') if repeat%2 else ('async-events','async','events','serial')) if mode=='all' else (mode,)for current in modes:matrix.assert_gpu_tests_idle();name=f'{label}-{group}-{current}-r{repeat}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/namefor p in (out,tmp):p.mkdir(parents=True,exist_ok=False)@@ -25,7 +25,8 @@ for group in groups:for key in tuple(env):if key.upper().startswith('VEYRA_'):env.pop(key)env.update(TEMP=str(tmp),TMP=str(tmp))- if current=='async':env['VEYRA_TEST_EXPORT_ASYNC']='1'+ if current in ('async','async-events'):env['VEYRA_TEST_EXPORT_ASYNC']='1'+ if current in ('events','async-events'):env['VEYRA_TEST_EXPORT_FENCE_EVENTS']='1'command=[str(exe),str(source),str(dest),config,str(frames),str(out)]before=matrix.gpu_query();print('START',name,flush=True);start=time.monotonic()with (out/'console.log').open('xb') as stream:diff --git a/scripts/perf/nr-export-verify.py b/scripts/perf/nr-export-verify.pyindex b7ce841a..a93c1625 100644--- a/scripts/perf/nr-export-verify.py+++ b/scripts/perf/nr-export-verify.py@@ -10,12 +10,19 @@ for label in labels:for run in summary['runs']:matrix.assert_gpu_tests_idle();out=BASE/'logs'/TASK/run['name'];source=Path(run['command'][2]);assert matrix.digest(source)==run['outputSha256']print('VERIFY',run['name'],flush=True);env=os.environ.copy();env.update(TEMP=str(BASE/'tmp'/TASK/run['name']),TMP=str(BASE/'tmp'/TASK/run['name']))- metadata=subprocess.run([ffprobe,'-v','error','-count_frames','-show_streams','-show_format','-of','json',str(source)],capture_output=True,env=env,timeout=180,check=True)- (out/'ffprobe.json').write_bytes(metadata.stdout);data=json.loads(metadata.stdout)+ metadataFile=out/'ffprobe.json'+ if not metadataFile.exists():+ metadata=subprocess.run([ffprobe,'-v','error','-count_frames','-show_streams','-show_format','-of','json',str(source)],capture_output=True,env=env,timeout=180,check=True)+ metadataFile.write_bytes(metadata.stdout)+ data=json.loads(metadataFile.read_bytes())video=next(s for s in data['streams'] if s['codec_type']=='video');assert int(video['nb_read_frames'])==int(run['metrics']['encoded']),run['name']- hashfile=out/'decoded.framemd5';assert not hashfile.exists()- with (out/'decode-console.log').open('xb') as stream:- subprocess.run([ffmpeg,'-v','error','-threads','2','-i',str(source),'-map','0:v:0','-fps_mode','passthrough','-f','framemd5',str(hashfile)],stdout=stream,stderr=subprocess.STDOUT,env=env,timeout=180,check=True)+ hashfile=out/'decoded.framemd5'+ if hashfile.exists():+ old=json.loads((BASE/'logs'/TASK/(label+'-decoded-review.json')).read_text(encoding='utf-8'))+ receipt=next(r for r in old['runs'] if r['name']==run['name']);assert matrix.digest(hashfile)==receipt['framemd5Sha256']+ else:+ with (out/'decode-console.log').open('xb') as stream:+ subprocess.run([ffmpeg,'-v','error','-threads','2','-i',str(source),'-map','0:v:0','-fps_mode','passthrough','-f','framemd5',str(hashfile)],stdout=stream,stderr=subprocess.STDOUT,env=env,timeout=180,check=True)hashes=[s for s in hashfile.read_text().splitlines() if s and not s.startswith('#')];assert len(hashes)==int(run['metrics']['encoded'])signature={'codec':video['codec_name'],'width':video['width'],'height':video['height'],'rate':video['avg_frame_rate'],'timeBase':video['time_base'],'audio':[{k:s.get(k) for k in ('codec_name','channels','sample_rate','start_time','duration')} for s in data['streams'] if s['codec_type']=='audio'],diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex a7ab7cd0..499352ef 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -9,6 +9,7 @@#include "veyra/RuntimePaths.h"#include "veyra/engine/GraphDescription.h"#include <filesystem>+#include <algorithm>#include <format>#include <thread>#include <chrono>@@ -42,6 +43,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptioptions.settings.frameGenerationBackend=FrameGenerationBackend::Dlss;}gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);+ struct CompletionEvent {HANDLE value=nullptr;~CompletionEvent(){if(value)CloseHandle(value);}} completionEvent;std::unique_ptr<sink::VideoEncoder> encoder;AVFormatContext* mux=nullptr;AVStream* videoStream=nullptr;ExportStreams streams;bool ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;@@ -216,6 +218,66 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiint removeDeviceIndex=-1;{wchar_t hook[16]{};if(resumeAttempt==0&&GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_REMOVE_DEVICE_AT",hook,16))removeDeviceIndex=_wtoi(hook);}bool deviceLost=false;uint32_t removedReason=0;+ // Isolated 5b candidates. FG status still requires completed GPU readback;+ // NVENC receives the existing conversion fence, never an unready pixel read.+ const bool asyncNvenc=GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_ASYNC",nullptr,0)>0&&+ !options.fg&&encoder->backend()==sink::EncoderBackend::Nvenc&&slowFrameIndex<0;+ bool fenceEvents=GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_FENCE_EVENTS",nullptr,0)>0;+ if(fenceEvents){+ completionEvent.value=CreateEventW(nullptr,FALSE,FALSE,nullptr);+ if(!completionEvent.value){veyra::log::warn("export-pipeline",std::format("completion event create failed error={}; keeping polling",GetLastError()));fenceEvents=false;}+ }+ struct PendingFrame {pipeline::EnhanceGraph::FrameOutputs output;uint64_t consumerFence=0,source=0;std::chrono::steady_clock::time_point submitted;};+ std::deque<PendingFrame> pendingFrames;unsigned maxInFlight=1;+ // Preserve the 30s alive-device contract, cancellation and slow-frame hook.+ // With two frames in flight this waits only before a pool slot is reused.+ auto waitCompleted=[&](pipeline::EnhanceGraph::FrameOutputs& out,std::chrono::steady_clock::time_point submitted,uint64_t sourceIndex,uint64_t consumerFence=0){+ const auto waitStart=std::chrono::steady_clock::now();+ auto nextHealthCheck=submitted+std::chrono::milliseconds(250);+ const bool injectedStall=slowFrameIndex>=0&&sourceIndex==uint64_t(slowFrameIndex);+ const bool commonFence=(!out.videoFenceValue||out.videoFenceObject.Get()==ctx.fence())&&+ (!out.genFenceValue||out.genFenceObject.Get()==ctx.fence());+ const uint64_t waitFence=std::max({out.videoFenceValue,out.genFenceValue,consumerFence});+ bool eventRegistered=false;+ while(!cancel&&((injectedStall&&std::chrono::steady_clock::now()-submitted<std::chrono::milliseconds(slowFrameMs))||+ !graph.resolveGeneration(out)||!pipeline::fenceComplete(ctx.fence(),consumerFence))){+ const auto now=std::chrono::steady_clock::now();+ if(now>=nextHealthCheck){+ nextHealthCheck=now+std::chrono::milliseconds(250);+ if(!ctx.checkDeviceAlive(removedReason)){+ ctx.reportDeviceFailure("export-frame",ring.lastSignaledValue());deviceLost=true;error=true;+ failureReason=std::format(L"显卡驱动在第 {} 帧卡死并被系统重置(0x{:X})。40 系显卡开社区版 NR 时偶发;可关闭 NR、把 NR 内部分辨率调低或换光流后重试",sourceIndex+1,removedReason);break;+ }+ }+ if(now-submitted>std::chrono::seconds(30)){+ ctx.reportDeviceFailure("export-frame-timeout",ring.lastSignaledValue());error=true;+ failureReason=std::format(L"GPU 30 秒内未完成第 {} 帧的增强(显卡未报告重置);可降低 NR / 超分分辨率后重试",sourceIndex+1);+ veyra::log::error("export","frame GPU completion timed out after 30s");break;+ }+ if(fenceEvents&&commonFence&&!injectedStall&&!eventRegistered){+ const HRESULT hr=ctx.fence()->SetEventOnCompletion(waitFence,completionEvent.value);+ if(SUCCEEDED(hr))eventRegistered=true;+ else {veyra::log::warn("export-pipeline",std::format("completion event registration failed hr=0x{:X}; keeping polling",unsigned(hr)));fenceEvents=false;}+ }+ if(eventRegistered){+ const DWORD result=WaitForSingleObject(completionEvent.value,50);+ if(result!=WAIT_OBJECT_0&&result!=WAIT_TIMEOUT){veyra::log::warn("export-pipeline",std::format("completion event wait failed result={} error={}; keeping polling",result,GetLastError()));fenceEvents=false;eventRegistered=false;}+ }else std::this_thread::sleep_for(std::chrono::milliseconds(1));+ }+ completionWaitMs+=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-waitStart).count();+ if(error||cancel)return false;+ const double latency=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-submitted).count();+ if(latency>1000){+ ++slowFrames;uint64_t budget=0,usage=0;ctx.videoMemoryInfo(budget,usage);+ if(slowFrames<=20)veyra::log::warn("export",std::format("slow frame source={} gpuWaitMs={:.0f} vramMiB={} budgetMiB={}",sourceIndex,latency,usage>>20,budget>>20));+ }+ return true;+ };+ auto finishOldest=[&](){+ auto& old=pendingFrames.front();+ if(!waitCompleted(old.output,old.submitted,old.source,old.consumerFence))return false;+ pendingFrames.pop_front();return true;+ };const uint32_t multiplier=options.fg?options.fgMultiplier:1u;auto encodeAt=[&](unsigned slot,bool generated,double seconds){const int64_t timeUs=std::max(lastOutputUs+1,int64_t(std::llround(seconds*1000000)));@@ -223,6 +285,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptireturn encoder->encode(slot,generated,outputIndex++);};while(!cancel){if(frameBoundary&&!frameBoundary()){error=true;break;}pipeline::FramePacket packet;const AVFrame* frame=nullptr;+ if(pendingFrames.size()>=2&&!finishOldest())break;source::SourceReadStatus rs;if(sourceCount==0){packet=firstPacket;frame=firstFrame;rs=source::SourceReadStatus::Frame;}else rs=source.read(packet,&frame);@@ -241,38 +304,8 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiif(SUCCEEDED(ctx.device()->QueryInterface(IID_PPV_ARGS(&device5)))){device5->RemoveDevice();veyra::log::warn("export","test hook: D3D12 device removed at this frame");}}pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,(pts+videoOriginSeconds)*1000,sourceCount==0||repairPts||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo,&packet.hardwareSurface,false)){error=true;break;}- // One frame's GPU work. A fixed 2 s limit failed whole exports on a frame that- // was only slow (8K NR + optical flow + NVENC near the VRAM budget; field log- // 2026-10-02, RTX 4070 Ti SUPER, 8K VR). Wait up to 30 s while the device is- // alive; a device Windows reset after a hang fails at once, with its reason.const auto readyStart=std::chrono::steady_clock::now();- auto nextHealthCheck=readyStart+std::chrono::milliseconds(250);- const bool injectedStall=slowFrameIndex>=0&&sourceCount==uint64_t(slowFrameIndex);- while(!cancel&&((injectedStall&&std::chrono::steady_clock::now()-readyStart<std::chrono::milliseconds(slowFrameMs))||!graph.resolveGeneration(out))){- const auto now=std::chrono::steady_clock::now();- if(now>=nextHealthCheck){- nextHealthCheck=now+std::chrono::milliseconds(250);- if(!ctx.checkDeviceAlive(removedReason)){- ctx.reportDeviceFailure("export-frame",ring.lastSignaledValue());- deviceLost=true;- error=true;failureReason=std::format(L"显卡驱动在第 {} 帧卡死并被系统重置(0x{:X})。40 系显卡开社区版 NR 时偶发;可关闭 NR、把 NR 内部分辨率调低或换光流后重试",sourceCount+1,removedReason);- break;- }- }- if(now-readyStart>std::chrono::seconds(30)){- ctx.reportDeviceFailure("export-frame-timeout",ring.lastSignaledValue());- error=true;failureReason=std::format(L"GPU 30 秒内未完成第 {} 帧的增强(显卡未报告重置);可降低 NR / 超分分辨率后重试",sourceCount+1);- veyra::log::error("export","frame GPU completion timed out after 30s");break;- }- std::this_thread::sleep_for(std::chrono::milliseconds(1));- }- if(error||cancel)break;- const double waited=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-readyStart).count();- completionWaitMs+=waited;- if(waited>1000){- ++slowFrames;uint64_t budget=0,usage=0;ctx.videoMemoryInfo(budget,usage);- if(slowFrames<=20)veyra::log::warn("export",std::format("slow frame source={} gpuWaitMs={:.0f} vramMiB={} budgetMiB={}",sourceCount,waited,usage>>20,budget>>20));- }+ if(!asyncNvenc&&!waitCompleted(out,readyStart,sourceCount))break;if(sourceCount>0&&options.fg){for(uint32_t j=1;j<options.fgMultiplier;++j){pipeline::BatchFrame* item=nullptr;@@ -286,10 +319,16 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiauto& real=out.batch.frames[out.batch.count-1];if(!encodeAt(real.lease->slot,false,pts)){error=true;break;}real.lease->consumerFence=ring.lastSignaledValue();lastReal=real.lease;+ if(asyncNvenc){+ const uint64_t consumerFence=real.lease->consumerFence;+ pendingFrames.push_back({std::move(out),consumerFence,sourceCount,readyStart});+ maxInFlight=std::max(maxInFlight,unsigned(pendingFrames.size()));+ }previousPts=pts;++sourceCount;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});const double clipDuration=requestedEnd>0?requestedEnd-requestedStart:std::max(0.001,info.duration.toDouble()-videoOriginSeconds);progress(clipDuration>0?std::clamp(pts/clipDuration,0.0,.99):0,std::format(L"正在导出:{}张源帧 / {}张编码帧({})",sourceCount,outputIndex,encoderName));if(maxFrames&&sourceCount>=maxFrames)break;}+ while(!pendingFrames.empty()&&!error&&!cancel)if(!finishOldest())break;// Submission or encoding can also be the first call to see the reset.if(error&&!cancel&&!deviceLost&&!ctx.checkDeviceAlive(removedReason)){ctx.reportDeviceFailure("export-frame",ring.lastSignaledValue());@@ -316,8 +355,8 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiveyra::log::info("export-counts",std::format("slowFrames={} source={} generated={} hold={} output={} multiplier={} repairedTimestamps={} backend={} vfgQuality={} encoder={} bitrateMbps={} note={} (holds are not generated frames)",slowFrames,sourceCount,generatedCount,holdCount,outputIndex,multiplier,repairedTimestamps,frameGenerationBackendName(options.settings.frameGenerationBackend),options.settings.vfgQuality,std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));progress(.99,L"正在收尾:等待编码器输出剩余帧");if(!encoder->finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看编码器诊断";break;}- veyra::log::info("export-pipeline",std::format("source={} pipelineMs={:.3f} completionWaitMs={:.3f} mode=serial",- sourceCount,std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-pipelineStart).count(),completionWaitMs));+ veyra::log::info("export-pipeline",std::format("source={} pipelineMs={:.3f} completionWaitMs={:.3f} mode={} fenceEvents={} maxInFlight={}",+ sourceCount,std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-pipelineStart).count(),completionWaitMs,asyncNvenc?"async":"serial",fenceEvents,maxInFlight));const int64_t estimatedEnd=lastOutputUs+std::max<int64_t>(1,int64_t(std::llround(sourceInterval*1000000/multiplier)));const int64_t finalEnd=requestedEnd>0?std::min(estimatedEnd,int64_t(std::llround((requestedEnd-videoOriginSeconds)*1000000))):estimatedEnd;if(!flushVideo(finalEnd))break;