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(screen): capture every frame WGC composes, not one per 16 ms
Veyra Goal Agent637656455b80
diff --git a/scripts/acceptance/screen-capture-rate.py b/scripts/acceptance/screen-capture-rate.pynew file mode 100644index 00000000..0e700d78--- /dev/null+++ b/scripts/acceptance/screen-capture-rate.py@@ -0,0 +1,102 @@+"""Window-capture rate, real app (claude-capture-fps-audio-20261027).++A probe window presents exactly 60 FPS (tmp/<task>/bench/wgc_rate_probe.exe source+free60); the player captures it with WGC at the 60 and the 120 FPS limit, no game+mode and no effects, on a private profile. Runs the 2.1.1 release EXE (--exe+release, the baseline) or this tree's build (--exe build) in a hard-linked copy of+the 2.1.1 NVIDIA package; rates come from the per-second [capture-timing] lines.+usage: py -3.11 -X utf8 -B -I scripts/acceptance/screen-capture-rate.py --exe build|release+"""+from pathlib import Path+import argparse, ctypes, hashlib, json, os, re, shutil, subprocess, time+from ctypes import wintypes++ap = argparse.ArgumentParser(); ap.add_argument('--exe', choices=['build', 'release'], required=True); args = ap.parse_args()+B = Path('E:/项目/Veyra'); T = 'claude-capture-fps-audio-20261027'; R = Path(__file__).resolve().parents[2]+D = B/'build/claude-screen-recording-20261022'; A = B/'tests'/T/'app'; P = B/'tests'/T/('profile-' + args.exe)+L = B/'logs'/T/('screen-rate-' + args.exe); TMP = B/'tmp'/T/'screen-rate'; OUT = B/'reports'/T+PROBE = B/'tmp'/T/'bench/wgc_rate_probe.exe'+DONOR = B/'test-packages/codex-release-2.1.1-final-20261027/Veyra-2.1.1-NVIDIA-win64-portable'+for p in [L, TMP, OUT]: p.mkdir(parents=True, exist_ok=True)+if P.exists(): shutil.rmtree(P)+P.mkdir(parents=True)+++def sha(p):+ with p.open('rb') as f: return hashlib.file_digest(f, 'sha256').hexdigest()+++def replace(p, data):+ # Unlink first: a hard link to the donor is never written through.+ p.parent.mkdir(parents=True, exist_ok=True)+ if p.exists(): p.unlink()+ p.write_bytes(data)+++manifest = json.loads((DONOR/'package-manifest.json').read_text('utf8'))+if not A.exists():+ for e in manifest['files']:+ rel = e['path']+ if rel.startswith('logs/') or any(x.startswith('user-data-') for x in Path(rel).parts): continue+ p = A/rel; p.parent.mkdir(parents=True, exist_ok=True); os.link(DONOR/rel, p)+ shutil.copyfile(DONOR/'package-manifest.json', A/'package-manifest.json')+exe = D/'veyra_qml_ui.exe' if args.exe == 'build' else DONOR/'veyra_qml_ui.exe'+replace(A/'veyra_qml_ui.exe', exe.read_bytes())+for folder in ['qml', 'i18n']:+ src = R if args.exe == 'build' else DONOR+ for p in (src/folder).rglob('*'):+ if p.is_file(): replace(A/folder/p.relative_to(src/folder), p.read_bytes())+for e in manifest['files']:+ if Path(e['path']).suffix.lower() in ['.dll', '.onnx', '.tflite', '.hsaco', '.dxil']: assert sha(A/e['path']) == e['sha256'], e['path']+(P/'qml-preferences.v1.json').write_text(json.dumps(dict(language='zh-CN', autoResume=False, prewarmEnhancement=False)), 'utf8')++probe = subprocess.Popen([str(PROBE), 'source', 'free60', '50'], stdout=subprocess.PIPE, text=True)+user32 = ctypes.WinDLL('user32', use_last_error=True)+hwnd = None+for _ in range(200):+ time.sleep(0.02); w = user32.FindWindowExW(None, None, 'VeyraRateProbeSource', None)+ while w:+ pid = wintypes.DWORD(); user32.GetWindowThreadProcessId(w, ctypes.byref(pid))+ if pid.value == probe.pid: hwnd = w; break+ w = user32.FindWindowExW(None, w, 'VeyraRateProbeSource', None)+ if hwnd: break+assert hwnd, 'probe window not found'++env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_', 'QML_'))}+log_file = L/'engine.log'; console = L/'console.log'+for f in (log_file, console):+ if f.exists(): f.unlink()+env.update(TEMP=str(TMP), TMP=str(TMP), APPDATA=str(P/'AppData'), LOCALAPPDATA=str(P/'LocalAppData'), CUDA_CACHE_PATH=str(TMP/'cuda'),+ QML_DISABLE_DISK_CACHE='1', QT_FORCE_STDERR_LOGGING='1', VEYRA_LOG_FILE=str(log_file))+main_src = (R if args.exe == 'build' else DONOR)/'qml/Veyra/Main.qml'+main = main_src.read_text('utf8'); pos = main.rfind('}')+loader = ('\nLoader { source: ' + json.dumps((R/'scripts/acceptance/screen-capture-rate.qml').as_uri()) ++ '; onLoaded: item.targetId=' + json.dumps(str(hwnd)) + ' }\n')+replace(A/'qml/Veyra/Main.qml', (main[:pos] + loader + main[pos:]).encode('utf8'))+started = time.time()+try:+ with console.open('wb') as f:+ run = subprocess.run([str(A/'veyra_qml_ui.exe'), '--size', '960x540', '--data-dir', str(P), '--exit-after', '70000'],+ cwd=A, env=env, stdout=f, stderr=subprocess.STDOUT, timeout=120)+finally:+ replace(A/'qml/Veyra/Main.qml', main_src.read_bytes())+ probe_out = probe.communicate(timeout=40)[0]+seconds = round(time.time() - started, 1)+lines = log_file.read_text('utf8', errors='replace').splitlines(); text = console.read_text('utf8', errors='replace')+stamp = lambda l: time.mktime(time.strptime(l[:19], '%Y-%m-%dT%H:%M:%S')) + float('0' + l[19:23])+phases = {}+for i, l in enumerate(lines):+ if m := re.search(r'\[screen-rate-test\] steady-(start|end) fps=(\d)', l): phases.setdefault(m.group(2), {})[m.group(1)] = i+rates = {}+for fps, span in phases.items():+ rows = [(stamp(l), int(m.group(1)), int(m.group(2))) for l in lines[span['start']:span['end']]+ if (m := re.search(r'\[capture-timing\] revision=\d+ received=(\d+) processed=(\d+)', l))]+ first, last = rows[0], rows[-1]; dt = last[0] - first[0]+ rates[{'2': 'limit60', '3': 'limit120'}[fps]] = dict(seconds=round(dt, 2), receivedFps=round((last[1] - first[1]) / dt, 2), processedFps=round((last[2] - first[2]) / dt, 2))+result = dict(exe=args.exe, exeSha256=sha(A/'veyra_qml_ui.exe'), exit=run.returncode, seconds=seconds, passed='SR_PASS' in text and 'SR_FAIL' not in text,+ probe=probe_out.strip(), rates=rates,+ minUpdateInterval=[l.split('] ', 2)[-1] for l in lines if 'minUpdateInterval' in l],+ screenOpened=[l.split('] ', 2)[-1] for l in lines if '[screen] opened' in l],+ qmlErrors=[l for l in text.splitlines() if any(s in l for s in ['ReferenceError:', 'TypeError:', 'SR_FAIL'])][:10], log=str(log_file))+(OUT/f'screen-rate-{args.exe}.json').write_text(json.dumps(result, ensure_ascii=False, indent=1), 'utf8')+print(json.dumps({k: result[k] for k in ['exe', 'exit', 'seconds', 'passed', 'probe', 'rates', 'minUpdateInterval']}, ensure_ascii=False, indent=1))diff --git a/scripts/acceptance/screen-capture-rate.qml b/scripts/acceptance/screen-capture-rate.qmlnew file mode 100644index 00000000..b3fab283--- /dev/null+++ b/scripts/acceptance/screen-capture-rate.qml@@ -0,0 +1,45 @@+// Loaded only into a private staging copy, never the user's running package.+// claude-capture-fps-audio-20261027: window capture (WGC, no game mode, no+// effects) of a probe window that presents exactly 60 FPS, at the 60 and the 120+// FPS limit; 10 s steady state each. screen-capture-rate.py reads the rates from+// the engine log between the marks.+import QtQuick+Item {+ id: test+ property string targetId: ""+ property int phase: 0+ property int ticks: 0+ property var limits: [2, 3] // setScreenOption("fps") index: 60, 120+ property int limitIndex: 0+ function log(text) { veyra.logUi("screen-rate-test", text); console.log("SR", text) }+ function state() { return "running=" + veyra.running + " applying=" + veyra.applying + " source=" + veyra.sourceSummary + " submitFps=" + veyra.submitFps.toFixed(2) }+ Timer {+ interval: 250; repeat: true; running: test.targetId.length > 0+ onTriggered: { try {+ ++test.ticks+ if (test.phase === 0) {+ if (test.ticks < 8) return+ const fps = test.limits[test.limitIndex]+ for (const [k, v] of [["kind", 0], ["method", 0], ["fps", fps], ["cursor", false], ["passthrough", false], ["fill", false]])+ if (!veyra.setScreenOption(k, v)) throw new Error("setScreenOption " + k)+ veyra.refreshCaptureTargets()+ veyra.screenTargetId = test.targetId+ if (veyra.screenTargetId !== test.targetId) throw new Error("probe window not listed: " + test.targetId)+ if (!veyra.startScreenCapture()) throw new Error("startScreenCapture refused")+ test.log("start limitIndex=" + fps + " | " + test.state())+ test.phase = 1; test.ticks = 0+ } else if (test.phase === 1) {+ if (!veyra.running || veyra.applying) { if (test.ticks > 80) throw new Error("capture did not start"); return }+ if (test.ticks === 12) test.log("steady-start fps=" + test.limits[test.limitIndex] + " | " + test.state())+ if (test.ticks < 12 + 40) return+ test.log("steady-end fps=" + test.limits[test.limitIndex] + " | " + test.state())+ veyra.stopPlayback()+ test.phase = 2; test.ticks = 0+ } else if (test.phase === 2) {+ if (test.ticks < 8) return+ if (++test.limitIndex < test.limits.length) { test.phase = 0; test.ticks = 8; return }+ console.log("SR_PASS"); Qt.quit()+ }+ } catch (e) { console.error("SR_FAIL", test.phase, e.message); test.log("FAIL " + e.message); Qt.quit() } }+ }+}diff --git a/src/source/ScreenCaptureSource.cpp b/src/source/ScreenCaptureSource.cppindex f5052072..80ac6d59 100644--- a/src/source/ScreenCaptureSource.cpp+++ b/src/source/ScreenCaptureSource.cpp@@ -103,8 +103,8 @@ DXGI_RATIONAL monitorRate(HMONITOR monitor){if(EnumDisplaySettingsW(mi.szDevice,ENUM_CURRENT_SETTINGS,&mode)&&mode.dmDisplayFrequency>1&&mode.dmDisplayFrequency<=1000)return {mode.dmDisplayFrequency,1};return {};}-bool hdrMonitor(HMONITOR monitor){- ComPtr<IDXGIFactory1> factory;if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))))return false;+bool hdrMonitor(IDXGIFactory1* factory,HMONITOR monitor){+ if(!factory)return false;for(UINT a=0;;++a){ComPtr<IDXGIAdapter1> adapter;if(factory->EnumAdapters1(a,&adapter)==DXGI_ERROR_NOT_FOUND)break;for(UINT o=0;;++o){ComPtr<IDXGIOutput> output;if(adapter->EnumOutputs(o,&output)==DXGI_ERROR_NOT_FOUND)break;DXGI_OUTPUT_DESC d{};if(FAILED(output->GetDesc(&d))||d.Monitor!=monitor)continue;@@ -194,6 +194,7 @@ struct ScreenCaptureSource::Impl {session=pool.CreateCaptureSession(item);session.IsCursorCaptureEnabled(options.cursor);if(borderDisabled)session.IsBorderRequired(false);+ applyMinUpdateInterval();session.StartCapture();wasWaiting=true;log::info("screen","restarted WGC session once for a static resized target");}@@ -201,6 +202,17 @@ struct ScreenCaptureSource::Impl {AVFrame* frame=nullptr;uint64_t signal=0,sequence=0;int64_t lastPts=0,nextPts=0,clockOffset=0,lastColorCheck=0;DWORD targetPid=0;bool hdr=false,wasWaiting=false,exclusion=false;+ // An output's color space changes only with the display configuration, which+ // invalidates the DXGI factory. Walking the outputs with a new factory every+ // second cost about 0.4 ms on the engine thread (one 20 ms spike, bench+ // 2026-10-27), so it is repeated only when the factory or the monitor changed.+ ComPtr<IDXGIFactory1> displayFactory;HMONITOR displayMonitor=nullptr;+ bool displayHdr(HMONITOR monitor,bool& value){+ if(displayFactory&&displayFactory->IsCurrent()&&monitor==displayMonitor)return false;+ displayFactory.Reset();displayMonitor=monitor;+ if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&displayFactory))))displayFactory.Reset();+ value=hdrMonitor(displayFactory.Get(),monitor);return true;+ }std::wstring message;DXGI_FORMAT format=DXGI_FORMAT_B8G8R8A8_UNORM;~Impl(){av_frame_free(&frame);}int64_t interval()const{return 10000000LL*info.nominalRateDen/info.nominalRateNum;}@@ -215,6 +227,26 @@ struct ScreenCaptureSource::Impl {info.averageFps=double(rate.Numerator)/rate.Denominator;nextPts=0;if(sequence)wasWaiting=true;log::info("screen-rate",std::format("followDisplay={} limit={}/{} ({:.3f} Hz) monitor={}",options.fps==0,rate.Numerator,rate.Denominator,info.averageFps,uint64_t(monitor)));+ applyMinUpdateInterval();+ }+ // WGC's default MinUpdateInterval (16 ms on Windows 11 24H2) skips a frame that+ // composes sooner than that after the last one: a 60 FPS window on a 165 Hz+ // display arrived at 55 FPS (every third refresh) and no limit above 60 was+ // reachable. On any refresh grid, composed frames of a source at or below the+ // limit are at least half a limit interval apart, so ask for that less 1 ms of+ // timestamp jitter; the deadline accumulator in read() still enforces the limit.+ void applyMinUpdateInterval(){+ if(!session||!info.nominalRateNum)return;+ try{+ if(!winrt::Windows::Foundation::Metadata::ApiInformation::IsPropertyPresent(L"Windows.Graphics.Capture.GraphicsCaptureSession",L"MinUpdateInterval"))return;+ const int64_t value=std::max<int64_t>(10000,interval()/2-10000);+ const auto previous=session.MinUpdateInterval().count();+ if(previous==value)return;+ session.MinUpdateInterval(winrt::Windows::Foundation::TimeSpan{value});+ log::info("screen-rate",std::format("WGC minUpdateInterval={:.3f} ms (was {:.3f} ms)",value/1e4,previous/1e4));+ }catch(const winrt::hresult_error& e){+ log::warn("screen-rate",std::format("WGC minUpdateInterval kept hr=0x{:08X}",uint32_t(e.code())));+ }}void color(){auto& c=info.color;c={};c.pixelFormat=hdr?pipeline::SourcePixelFormat::Rgba16F:pipeline::SourcePixelFormat::Bgra8;@@ -270,7 +302,7 @@ bool ScreenCaptureSource::open(const SourceOpenDesc& desc){const auto& o=p.options;HWND window=o.kind==ScreenTargetKind::Window?reinterpret_cast<HWND>(o.target):nullptr;if(window){GetWindowThreadProcessId(window,&p.targetPid);if(!IsWindow(window)||p.targetPid==GetCurrentProcessId())throw winrt::hresult_error(E_INVALIDARG,L"窗口已关闭或属于 Veyra");}HMONITOR monitor=window?MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST):reinterpret_cast<HMONITOR>(o.target);- p.hdr=hdrMonitor(monitor);p.format=p.hdr?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_B8G8R8A8_UNORM;+ p.displayHdr(monitor,p.hdr);p.format=p.hdr?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_B8G8R8A8_UNORM;p.consumer=static_cast<ID3D12Device*>(desc.d3d12Device);ComPtr<IDXGIFactory4> factory;check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)),"factory");ComPtr<IDXGIAdapter> adapter;check(factory->EnumAdapterByLuid(p.consumer->GetAdapterLuid(),IID_PPV_ARGS(&adapter)),"processing adapter");@@ -294,6 +326,7 @@ bool ScreenCaptureSource::open(const SourceOpenDesc& desc){p.poolSize=p.item.Size();p.pool=Direct3D11CaptureFramePool::CreateFreeThreaded(p.wrapped,DirectXPixelFormat(p.format),2,p.poolSize);p.session=p.pool.CreateCaptureSession(p.item);p.session.IsCursorCaptureEnabled(o.cursor);if(o.borderless||o.kind==ScreenTargetKind::Monitor)p.dropBorder();+ p.updateRate(monitor);p.applyMinUpdateInterval();p.session.StartCapture();}if(p.poolSize.Width<=int(o.left+o.right)||p.poolSize.Height<=int(o.top+o.bottom))throw winrt::hresult_error(E_INVALIDARG,L"裁剪范围超出画面");@@ -321,8 +354,8 @@ SourceReadStatus ScreenCaptureSource::read(pipeline::FramePacket& packet,const AMONITORINFO mi{sizeof(mi)};if(!GetMonitorInfoW(monitor,&mi)){p.message=L"显示器已断开,请重新选择目标";return SourceReadStatus::Error;}if(!p.options.fps)p.updateRate(monitor);- const bool hdr=hdrMonitor(monitor);- if(hdr!=p.hdr){+ bool hdr=p.hdr;+ if(p.displayHdr(monitor,hdr)&&hdr!=p.hdr){p.hdr=hdr;p.format=hdr?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_B8G8R8A8_UNORM;p.color();p.wasWaiting=true;p.info.videoPixelFormatName=hdr?"scRGB FP16":"BGRA8 sRGB";if(p.duplication){p.duplication.Reset();p.startDuplication();}@@ -358,8 +391,12 @@ SourceReadStatus ScreenCaptureSource::read(pipeline::FramePacket& packet,const Apts=captured.SystemRelativeTime().count()+p.clockOffset;}// Accumulate deadlines: comparing each jittery interval to an exact- // 1/60 would accidentally discard nearly half of a 60 Hz stream.- if(pts<=p.lastPts||pts<p.nextPts-5000){++p.metrics.dropped;return SourceReadStatus::Waiting;}+ // 1/60 would accidentally discard nearly half of a 60 Hz stream. The+ // compositor timestamp of a busy desktop also lands a refresh or two late+ // and the next one on time, so a frame may come a quarter interval early:+ // with 0.5 ms a 60 FPS window lost about 2 FPS at the 60 limit (58.1,+ // 2026-10-27). The accumulated deadline still holds the average to the limit.+ if(pts<=p.lastPts||pts<p.nextPts-p.interval()/4){++p.metrics.dropped;return SourceReadStatus::Waiting;}D3D11_TEXTURE2D_DESC td{};texture->GetDesc(&td);if(td.Format!=p.format)throw winrt::hresult_error(E_UNEXPECTED,L"采集颜色格式发生变化,请重新连接");const auto& o=p.options;unsigned w=std::min(td.Width,unsigned(p.poolSize.Width)),h=std::min(td.Height,unsigned(p.poolSize.Height));