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

diagnostics: correlate XeSS cycles with source presentation boundaries

Veyra Goal Agent0143baf3bcb0
diff --git a/docs/FG_STABILITY_COMPLETION_PLAN_2026-09-21.md b/docs/FG_STABILITY_COMPLETION_PLAN_2026-09-21.md
index 8048344f..160d3614 100644
--- a/docs/FG_STABILITY_COMPLETION_PLAN_2026-09-21.md
+++ b/docs/FG_STABILITY_COMPLETION_PLAN_2026-09-21.md
@@ -1,7 +1,9 @@
# 补帧稳定性与现有功能收尾方案
-日期:2026-09-21。状态:方案已编写,以下阶段尚未按本方案执行。
-本轮只更新文档,不启动性能测试、产品修改、构建、打包或发布。
+日期:2026-09-21。状态:用户已授权执行,P0 时间线诊断进行中。
+开工存档 `d2ae8ee` / `checkpoint/pre-fg-stability-20260921`;
+隔离分支 `codex/fg-stability-20260921`。尚无已验收的调度优化。
+允许本地修改、构建与有界测试,不推送、不打包发布。
## 目标与边界
@@ -22,7 +24,8 @@ GPU 平均占用低不证明关键资源有余量;功耗平稳也不独立证
## 基线与当前状态
- 工作区:`E:/项目/Veyra/worktrees/playback-nr-20260920`。
-- 分支:`codex/fg-utilization-20260921`,当前 HEAD `e71d715`。
+- 历史对照基线:`codex/fg-utilization-20260921` / `e71d715`;
+ 当前施工基线为上述 `d2ae8ee`,其中包含默认关闭、未接受的 overlap 实验。
- 已交付 beta:`f029707` 对应
`E:/项目/Veyra/test-packages/1.4.4beta-20260921-nr-followup/`。
- 正式版参照:`v1.4.3` / `3b4570e`,不代表高倍率稳定性已经通过。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index ccc1fe32..3b0e9932 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -5727,3 +5727,47 @@ XeSS时间/帧对应、DLSS整组空档、输出限帧、UI/字幕/采集回归
默认限帧和XeSS时间提示结论。保留所有既有未提交代码及实验,不启动新目标、
测试、构建或发布。本轮无新增二进制/临时产物。文档检查使用git diff --check
及新方案的本地Markdown链接存在性校验;不将文档检查算产品验收。
+
+## 2026-09-21 FG stability: source-linked XeSS diagnostics
+
+Execution authorized after the preceding planning entry. Baseline checkpoint:
+`d2ae8ee` / `checkpoint/pre-fg-stability-20260921`; isolated branch
+`codex/fg-stability-20260921`, worktree `worktrees/playback-nr-20260920`.
+Added opt-in VEYRA_TEST_TRACE_XESS bounded Sleep/Bind/Present events,
+provider-instance/cycle IDs, and actual source identity linkage. No scheduling,
+quality, multiplier or waiting policy changes. A preparation cycle may be
+shared by multiple queued sources; mismatched preparation/presentation cycle
+numbers alone are not evidence of a bug.
+
+Build succeeded with scripts/build-isolated.ps1, targets veyra, version
+1.4.4beta, BuildDirectory E:/项目/Veyra/build/playback-nr-20260920,
+DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt,
+TempDirectory E:/项目/Veyra/tmp/fg-stability-20260921. Output was captured in
+the tool session (72 steps), not a separate build log. Existing FFmpeg
+conversion warnings remain.
+
+Ran scripts/acceptance/fg-utilization-matrix.py with --cases native-nr-xess4
+sr-nr-xess4 --seconds 20 and VEYRA_TEST_TRACE_XESS=1. EXE staging:
+E:/项目/Veyra/tests/fg-stability-20260921/app/veyra.exe; existing runtime
+files linked without replacement. Native input p001.mp4; derived input
+tests/nr-fg-followup-20260921/p001-derived1080.mp4. Both exited 0,
+failed=false. Evidence: tests/fg-stability-20260921/timeline-a/<case>/
+{stdout.log,app.log,trace.txt,result.json,telemetry.json,xess-timeline.json}.
+All relative artifact paths in this entry are under E:/项目/Veyra/.
+
+Native NR XeSS4: ~60 source submissions/s; retained source interval P99
+17.358ms, maximum40.019ms, provider Present cycle wall P95 10.436ms.
+True1080p-to4K VideoSR quality3 + NR XeSS4: ~39.98 source submissions/s;
+retained interval mean24.982ms, P99 46.754ms, max47.097ms. Of594 retained
+intervals,149 cross epoch boundaries (mean45.736ms). Present cycle wall P95
+27.941ms; XeLL Sleep P95 12.256ms. NVML device-wide GPU averages87.51%
+and69.13% respectively are not per-stage utilization or proof of headroom.
+
+Corrected the first analyzer draft, which omitted epoch boundaries and
+misleadingly reported heavy source interval mean18.033ms. Whole retained
+stream and same-epoch distributions are now separate. Trace rings overwrote
+4698/1469 records respectively; these statistics are retained tails, not full
+run or physical display measurements. Present cycle wall includes the return
+path before afterPresent, not pure GPU or exact DXGI duration. Next: distinguish
+provider scheduler waits from resource waits before selecting a candidate.
+No performance improvement accepted, publication or goal completion claimed.
diff --git a/include/veyra/diagnostics/FrameTrace.h b/include/veyra/diagnostics/FrameTrace.h
index 74acf817..2048a4bd 100644
--- a/include/veyra/diagnostics/FrameTrace.h
+++ b/include/veyra/diagnostics/FrameTrace.h
@@ -5,7 +5,7 @@
#include <vector>
namespace veyra::diagnostics {
-enum class TraceKind { Submitted, Ready, Present, Gpu, Reset, Cancelled, FrameReady, Discarded };
+enum class TraceKind { Submitted, Ready, Present, Gpu, Reset, Cancelled, FrameReady, Discarded, XessSleep, XessBind, XessPresent };
inline const char* traceKindName(TraceKind kind) {
switch(kind){
case TraceKind::Submitted:return "Submitted";
@@ -16,6 +16,9 @@ inline const char* traceKindName(TraceKind kind) {
case TraceKind::Cancelled:return "Cancelled";
case TraceKind::FrameReady:return "FrameReady";
case TraceKind::Discarded:return "Discarded";
+ case TraceKind::XessSleep:return "XessSleep";
+ case TraceKind::XessBind:return "XessBind";
+ case TraceKind::XessPresent:return "XessPresent";
}
return "Unknown";
}
@@ -34,6 +37,10 @@ struct FrameTraceEvent {
double entryDeviationMs=0,returnDeviationMs=0;
uint32_t queueDepth=0;
bool mediaDeviationValid=false;
+ // Provider instance disambiguates cycles across rebuilds. A preparation
+ // cycle is not a source ID; several queued sources can share it.
+ uint64_t providerInstance=0;
+ uint32_t providerCycle=0,preparationCycle=0;
};
// Owned by the logger, independent of the deduplicated error history. No
// allocation, formatting or disk I/O occurs when an event is recorded.
diff --git a/include/veyra/gfx/XessPresenter.h b/include/veyra/gfx/XessPresenter.h
index c20ebe55..3aa4df07 100644
--- a/include/veyra/gfx/XessPresenter.h
+++ b/include/veyra/gfx/XessPresenter.h
@@ -3,6 +3,7 @@
#include <dxgi1_6.h>
#include <cstdint>
#include <memory>
+#include "veyra/pipeline/FrameBatch.h"
namespace veyra::gfx {
class XessPresenter {
@@ -15,7 +16,7 @@ public:
uint32_t beginInput();
bool beginProcessing(uint32_t frameId);
bool endProcessing(uint32_t frameId);
- bool beginFrame(uint32_t preparedFrameId=0);
+ bool beginFrame(uint32_t preparedFrameId=0,pipeline::FrameIdentity identity={});
bool tag(ID3D12GraphicsCommandList*,ID3D12Resource* color,ID3D12Resource* motion,ID3D12Resource* depth,
RECT region,bool enabled,bool reset,float elapsedMs);
bool beforePresent();
diff --git a/scripts/acceptance/analyze-xess-timeline.py b/scripts/acceptance/analyze-xess-timeline.py
new file mode 100644
index 00000000..d2ea90cf
--- /dev/null
+++ b/scripts/acceptance/analyze-xess-timeline.py
@@ -0,0 +1,89 @@
+"""Join opt-in XeSS cycle events to source Present events, without guessing IDs."""
+import argparse
+import json
+from pathlib import Path
+import re
+
+
+def distribution(values):
+ values = sorted(values)
+ if not values:
+ return {"samples": 0}
+ return dict(samples=len(values), mean=sum(values) / len(values),
+ p50=values[int((len(values) - 1) * .50)],
+ p95=values[int((len(values) - 1) * .95)],
+ p99=values[int((len(values) - 1) * .99)], max=values[-1])
+
+
+def analyze(path):
+ text = path.read_text(encoding="utf-8", errors="replace")
+ events = [dict(re.findall(r"(\w+)=([^\s]+)", line))
+ for line in text.splitlines() if line.startswith("event=")]
+ cycles = {}
+ presents = [row for row in events if row["event"] == "Present"]
+ for event in events:
+ if not event["event"].startswith("Xess"):
+ continue
+ key = (event["providerInstance"], event["providerCycle"])
+ cycle = cycles.setdefault(key, {})
+ if event["event"] in cycle:
+ raise ValueError(f"Duplicate event for provider cycle {key}")
+ cycle[event["event"]] = event
+ if not cycles:
+ raise ValueError("No XeSS trace events; enable VEYRA_TEST_TRACE_XESS")
+ rows = []
+ for key, cycle in cycles.items():
+ bind, present, sleep = (cycle.get(name) for name in ("XessBind", "XessPresent", "XessSleep"))
+ row = dict(instance=int(key[0]), cycle=int(key[1]),
+ sleepMs=float(sleep["ms"]) if sleep else None,
+ presentMs=float(present["ms"]) if present else None,
+ preparationCycle=int(bind["preparationCycle"]) if bind else None,
+ source=int(bind["source"]) if bind else None)
+ matches = []
+ if bind and present:
+ matches = [event for event in presents
+ if all(event[field] == bind[field] for field in ("source", "epoch", "revision"))
+ and int(event["presentBeginHost"]) <= int(present["presentBeginHost"])
+ and int(event["presentEndHost"]) >= int(present["presentEndHost"])]
+ row["matchingAppPresents"] = len(matches)
+ if len(matches) == 1:
+ event = matches[0]
+ row.update(pts100ns=int(event["pts"]), batch=int(event["batch"]),
+ epoch=int(event["epoch"]), revision=int(event["revision"]),
+ beginHost=int(event["presentBeginHost"]), endHost=int(event["presentEndHost"]))
+ rows.append(row)
+ linked = sorted((row for row in rows if row["matchingAppPresents"] == 1), key=lambda row: row["beginHost"])
+ gaps, same_epoch_gaps, boundary_gaps, pts_steps, long_gaps = [], [], [], [], []
+ for previous, current in zip(linked, linked[1:]):
+ if any(current[key] != previous[key] for key in ("instance", "revision")):
+ continue
+ gap = (current["beginHost"] - previous["beginHost"]) / 10000
+ gaps.append(gap)
+ epoch_changed = current["epoch"] != previous["epoch"]
+ (boundary_gaps if epoch_changed else same_epoch_gaps).append(gap)
+ pts_steps.append((current["pts100ns"] - previous["pts100ns"]) / 10000)
+ if gap > 25:
+ long_gaps.append(dict(cycle=current["cycle"], gapMs=gap,
+ epochChanged=epoch_changed,
+ previousPresentMs=previous["presentMs"], sleepMs=current["sleepMs"]))
+ header = re.search(r"Frame trace: records=(\d+) capacity=(\d+) overwritten=(\d+)", text)
+ return dict(scope="Retained bounded CPU trace only; Present wall time includes descheduling, not GPU execution or scanout.",
+ overwritten=int(header[3]) if header else None, cycles=len(rows), linkedCycles=len(linked),
+ missingOrAmbiguousLinks=len(rows)-len(linked),
+ preparationCycleMismatch=sum(row["preparationCycle"] not in (None, 0, row["cycle"]) for row in rows),
+ sleepMs=distribution([row["sleepMs"] for row in rows if row["sleepMs"] is not None]),
+ providerPresentMs=distribution([row["presentMs"] for row in rows if row["presentMs"] is not None]),
+ sourcePresentIntervalMs=distribution(gaps), sourcePtsStepMs=distribution(pts_steps),
+ sameEpochIntervalMs=distribution(same_epoch_gaps),
+ epochBoundaryIntervalMs=distribution(boundary_gaps),
+ longSourceGaps=long_gaps, rows=rows)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("trace", type=Path)
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ result = analyze(args.trace)
+ args.output.write_text(json.dumps(result, indent=2), encoding="utf-8")
+ print(json.dumps({key: value for key, value in result.items() if key not in ("rows", "longSourceGaps")}, indent=2))
diff --git a/scripts/acceptance/test-xess-timeline.py b/scripts/acceptance/test-xess-timeline.py
new file mode 100644
index 00000000..0be7d51f
--- /dev/null
+++ b/scripts/acceptance/test-xess-timeline.py
@@ -0,0 +1,54 @@
+"""Synthetic coverage for retained trace joins and discontinuity intervals."""
+import importlib.util
+from pathlib import Path
+import sys
+import unittest
+
+sys.dont_write_bytecode = True
+spec = importlib.util.spec_from_file_location("timeline", Path(__file__).with_name("analyze-xess-timeline.py"))
+timeline = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(timeline)
+
+
+class Trace:
+ def __init__(self, text):
+ self.text = text
+
+ def read_text(self, **kwargs):
+ return self.text
+
+
+def cycle(number, epoch, begin, instance=1, revision=1, app=True):
+ identity = f"source={number} epoch={epoch} revision={revision}"
+ provider = f"providerInstance={instance} providerCycle={number}"
+ lines = [f"event=XessBind {identity} {provider} preparationCycle={number}",
+ f"event=XessPresent {identity} {provider} ms=1 presentBeginHost={begin + 1} presentEndHost={begin + 10000}"]
+ if app:
+ lines.append(f"event=Present {identity} pts={begin} batch={number} presentBeginHost={begin} presentEndHost={begin + 10001}")
+ return "\n".join(lines) + "\n"
+
+
+class TimelineTests(unittest.TestCase):
+ def test_epoch_boundary_included(self):
+ result = timeline.analyze(Trace(cycle(1, 1, 0) + cycle(2, 1, 160000) + cycle(3, 2, 620000)))
+ self.assertEqual(result["sourcePresentIntervalMs"]["mean"], 31)
+ self.assertEqual(result["sameEpochIntervalMs"]["mean"], 16)
+ self.assertEqual(result["epochBoundaryIntervalMs"]["mean"], 46)
+ self.assertTrue(result["longSourceGaps"][0]["epochChanged"])
+
+ def test_rebuild_or_revision_not_joined(self):
+ result = timeline.analyze(Trace(cycle(1, 1, 0) + cycle(1, 1, 160000, instance=2)
+ + cycle(2, 1, 320000, instance=2, revision=2)))
+ self.assertEqual(result["linkedCycles"], 3)
+ self.assertEqual(result["sourcePresentIntervalMs"]["samples"], 0)
+
+ def test_overwritten_or_ambiguous_app_record(self):
+ text = cycle(1, 1, 0, app=False) + cycle(2, 1, 160000)
+ text += next(line for line in text.splitlines() if line.startswith("event=Present")) + "\n"
+ result = timeline.analyze(Trace(text))
+ self.assertEqual(result["linkedCycles"], 0)
+ self.assertEqual(result["missingOrAmbiguousLinks"], 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/base/Log.cpp b/src/base/Log.cpp
index 76b9db95..c14379ae 100644
--- a/src/base/Log.cpp
+++ b/src/base/Log.cpp
@@ -179,7 +179,8 @@ std::string Logger::diagnosticReport(){std::ostringstream o;o<<"Veyra 本地诊
<<" decodedHost="<<e.decodedHost<<" processHost="<<e.processHost<<" readyHost="<<e.readyHost
<<" presentBeginHost="<<e.presentBeginHost<<" presentEndHost="<<e.presentEndHost
<<" entryDeviationMs="<<e.entryDeviationMs<<" returnDeviationMs="<<e.returnDeviationMs
- <<" queueDepth="<<e.queueDepth<<" mediaDeviationValid="<<e.mediaDeviationValid<<'\n';
+ <<" queueDepth="<<e.queueDepth<<" mediaDeviationValid="<<e.mediaDeviationValid
+ <<" providerInstance="<<e.providerInstance<<" providerCycle="<<e.providerCycle<<" preparationCycle="<<e.preparationCycle<<'\n';
return diagnostics::redact(o.str());
}
void Logger::flush()
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index f9da89fa..246a89b4 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -114,7 +114,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
if(auto* xess=sink_.xess()){
uint32_t preparedId=0;
for(auto& work:xessWork_)if(work.id&&work.identity==identity){preparedId=work.id;work.id=0;break;}
- if(!xess->beginFrame(preparedId)){xessFailed_=true;return false;}
+ if(!xess->beginFrame(preparedId,identity)){xessFailed_=true;return false;}
}
const auto beginEnd=std::chrono::steady_clock::now();
if(presentationQueue_){
diff --git a/src/gfx/XessPresenter.cpp b/src/gfx/XessPresenter.cpp
index ebcb57ab..b652b90d 100644
--- a/src/gfx/XessPresenter.cpp
+++ b/src/gfx/XessPresenter.cpp
@@ -4,12 +4,15 @@
#include "veyra/RuntimePaths.h"
#include "veyra/gfx/XessMfgUnlock.h"
#include "veyra/gfx/XessPacing.h"
+#include <atomic>
#ifdef VEYRA_HAS_XESS
#include <xess_fg/xefg_swapchain_d3d12.h>
#include <xell/xell_d3d12.h>
#endif
namespace {
+std::atomic<uint64_t> nextTraceInstance{0};
+int64_t traceHost(){return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100;}
// Local wide->narrow for log lines (the presenter's detail strings are wide).
std::string narrowDetail(const std::wstring& value){
if(value.empty())return {};
@@ -23,6 +26,11 @@ std::string narrowDetail(const std::wstring& value){
namespace veyra::gfx {
struct XessPresenter::Impl {
+ const bool traceEnabled=GetEnvironmentVariableW(L"VEYRA_TEST_TRACE_XESS",nullptr,0)>0;
+ const uint64_t traceInstance=++nextTraceInstance;
+ pipeline::FrameIdentity traceIdentity{};
+ uint32_t preparationCycle=0;
+ int64_t presentBegin=0;
uint64_t generated=0,presented=0;
uint32_t requestedGenerated=0; // generated frames requested by the user (0 = 2X stock)
uint32_t maxInterpolations=1; // runtime-reported ceiling after the unlock
@@ -31,6 +39,17 @@ struct XessPresenter::Impl {
xefg_swapchain_handle_t fg=nullptr;
xell_context_handle_t ll=nullptr;
uint32_t id=0,nextId=0;
+ void record(diagnostics::TraceKind kind,uint32_t cycle,int64_t begin,int64_t end,uint32_t count=0){
+ if(!traceEnabled)return;
+ diagnostics::FrameTraceEvent event;
+ event.kind=kind;event.host100ns=end;
+ if(kind!=diagnostics::TraceKind::XessSleep)event.identity=traceIdentity;
+ event.providerInstance=traceInstance;event.providerCycle=cycle;
+ event.preparationCycle=kind==diagnostics::TraceKind::XessSleep?0:preparationCycle;
+ event.presentBeginHost=begin;event.presentEndHost=end;
+ event.milliseconds=double(end-begin)/10000;event.count=count;
+ Logger::instance().recordFrame(event);
+ }
bool cycleOpen=false,renderSubmitStarted=false,renderSubmitEnded=false;
#define XESS_PROC(name) decltype(&name) name##Fn=nullptr
XESS_PROC(xefgSwapChainD3D12CreateContext);
@@ -187,7 +206,9 @@ uint32_t XessPresenter::beginInput(){
if(p.cycleOpen)return p.nextId;
const auto frameId=++p.nextId;
diagnostics::CpuStallTrace trace("xess-begin-stall",frameId);
+ const auto sleepBegin=p.traceEnabled?traceHost():0;
const bool slept=p.check(p.xellSleepFn(p.ll,frameId),"XeLL sleep");trace.mark("sleep");
+ if(p.traceEnabled)p.record(diagnostics::TraceKind::XessSleep,frameId,sleepBegin,traceHost(),slept?1:0);
p.cycleOpen=slept&&p.marker(XELL_SIMULATION_START,frameId);
p.renderSubmitStarted=p.renderSubmitEnded=false;
return p.cycleOpen?frameId:0;
@@ -217,15 +238,17 @@ bool XessPresenter::endProcessing(uint32_t frameId){
(void)frameId;return false;
#endif
}
-bool XessPresenter::beginFrame(uint32_t preparedFrameId){
+bool XessPresenter::beginFrame(uint32_t preparedFrameId,pipeline::FrameIdentity identity){
#ifdef VEYRA_HAS_XESS
auto& p=*p_;
p.id=beginInput();
+ p.traceIdentity=identity;p.preparationCycle=preparedFrameId;
+ if(p.traceEnabled){const auto now=traceHost();p.record(diagnostics::TraceKind::XessBind,p.id,now,now);}
if(log::verboseFrameLogs()&&preparedFrameId!=p.id)
log::info("xess-fg",std::format("presentation cycle id={} preparationCycle={}; cycle timing is not source-frame latency",p.id,preparedFrameId));
return p.id&&beginProcessing(p.id);
#else
- (void)preparedFrameId;
+ (void)preparedFrameId;(void)identity;
return false;
#endif
}
@@ -257,14 +280,17 @@ bool XessPresenter::tag(ID3D12GraphicsCommandList* list,ID3D12Resource* color,ID
}
bool XessPresenter::beforePresent(){
#ifdef VEYRA_HAS_XESS
- auto& p=*p_;return endProcessing(p.id)&&p.check(p.xefgSwapChainSetPresentIdFn(p.fg,p.id),"SetPresentId")&&p.marker(XELL_PRESENT_START);
+ auto& p=*p_;const bool ok=endProcessing(p.id)&&p.check(p.xefgSwapChainSetPresentIdFn(p.fg,p.id),"SetPresentId")&&p.marker(XELL_PRESENT_START);
+ p.presentBegin=ok&&p.traceEnabled?traceHost():0;return ok;
#else
return false;
#endif
}
bool XessPresenter::afterPresent(){
#ifdef VEYRA_HAS_XESS
- auto& p=*p_;if(!p.marker(XELL_PRESENT_END))return false;
+ auto& p=*p_;const auto presentEnd=p.traceEnabled?traceHost():0;
+ if(p.traceEnabled&&p.presentBegin)p.record(diagnostics::TraceKind::XessPresent,p.id,p.presentBegin,presentEnd);
+ if(!p.marker(XELL_PRESENT_END))return false;
p.cycleOpen=false;
xefg_swapchain_present_status_t status{};
if(!p.check(p.xefgSwapChainGetLastPresentStatusFn(p.fg,&status),"PresentStatus"))return false;