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: sample actual presentation timing and document bounded NR FG acceptance

Veyra Goal Agentf029707cfd8e
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d306d5d5..aff520dc 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -729,6 +729,9 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_motion_validation_tests PRIVATE veyra_pipeline)
add_executable(veyra_repair_shader_tests tests/integration/RepairShaderTests.cpp)
add_executable(veyra_nr_temporal_gpu_tests tests/integration/NrTemporalGpuTests.cpp)
+ add_executable(veyra_nr_video_quality_probe tests/integration/NrVideoQualityProbe.cpp)
+ target_compile_features(veyra_nr_video_quality_probe PRIVATE cxx_std_20)
+ target_link_libraries(veyra_nr_video_quality_probe PRIVATE veyra_engine)
target_compile_features(veyra_nr_temporal_gpu_tests PRIVATE cxx_std_20)
target_link_libraries(veyra_nr_temporal_gpu_tests PRIVATE veyra_pipeline)
add_executable(veyra_gpu_timing_tests tests/integration/GpuTimingTests.cpp)
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index 7a8414ff..d5d29ad0 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -31,6 +31,7 @@
#include <shellapi.h>
#include <shlobj.h>
#include <filesystem>
+#include <fstream>
#include <format>
#include "veyra/engine/ColorLookStore.h"
#include <string>
@@ -1115,7 +1116,10 @@ tickTransportChecks(hwnd,s);
tickFgOnlyChecks(hwnd,s);
if(smokeProtection&&startTick&&GetTickCount64()-startTick>1500){
auto indicator=[&](bool enabled,const wchar_t* count){wchar_t text[128]{},draft[64]{};auto control=veyra::ui::settingsControlForTest(206);GetWindowTextW(control,text,128);GetWindowTextW(veyra::ui::settingsControlForTest(100),draft,64);return (SendMessageW(control,BM_GETCHECK,0,0)==BST_CHECKED)==enabled&&std::wstring(text).find(count)!=std::wstring::npos&&std::wstring(draft)==L"0.42";};
- if(protectionStep==0&&s.frames){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();if(!transition.running){
+ if(protectionStep==0&&s.frames){
+ // The watchdog launches hidden; child-overlay visibility requires a visible parent.
+ ShowWindow(hwnd,SW_SHOWNORMAL);
+ if(uiState.mode==veyra::ui::Mode::Daily)switchMode();if(!transition.running){
SetWindowTextW(veyra::ui::settingsControlForTest(100),L"0.42");protectionSession=s.sessionId;auto view=engine.previewView();view.zoom=2;engine.previewView(view);RECT r{};GetClientRect(video,&r);auto e=s.metrics.resolution.output;
const float scale=std::min(float(r.right)/e.width,float(r.bottom)/e.height)*view.zoom;
auto pixel=[&](float u,float v){return POINT{LONG(r.right*.5f+(u-view.centerX)*e.width*scale),LONG(r.bottom*.5f+(v-view.centerY)*e.height*scale)};};
@@ -1310,5 +1314,19 @@ if(msg.message==WM_MOUSEWHEEL&&GetAncestor(msg.hwnd,GA_ROOT)==hwnd&&!veyra::ui::
if(steps){const auto state=engine.snapshot();engine.setVolume(std::clamp(state.volume+steps*.05f,0.0f,1.0f),false);}continue;
}
}
-if(veyra::ui::subtitleSettingsDialogMessage(msg)||veyra::ui::screenCaptureDialogMessage(msg)||IsDialogMessageW(hwnd,&msg))continue;TranslateMessage(&msg);DispatchMessageW(&msg);}CoUninitialize();return int(msg.wParam);
+if(veyra::ui::subtitleSettingsDialogMessage(msg)||veyra::ui::screenCaptureDialogMessage(msg)||IsDialogMessageW(hwnd,&msg))continue;TranslateMessage(&msg);DispatchMessageW(&msg);}
+if(smokeSeconds>0){
+ const DWORD size=GetEnvironmentVariableW(L"VEYRA_SMOKE_TRACE_FILE",nullptr,0);
+ if(size){
+ std::wstring path(size,L'\0');
+ const DWORD length=GetEnvironmentVariableW(L"VEYRA_SMOKE_TRACE_FILE",path.data(),size);
+ if(length>0&&length<size){
+ path.resize(length);
+ std::ofstream report{std::filesystem::path(path)};
+ report<<veyra::Logger::instance().diagnosticReport();
+ if(!report)veyra::log::error("app","Failed to write smoke diagnostic report");
+ }
+ }
+}
+CoUninitialize();return int(msg.wParam);
}
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index ec18c921..e0d11b78 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -1,5 +1,15 @@
# 当前项目状态 / Current Status
+2026-09-21 follow-up: retained temporal mask/time corrections and GPU
+neighborhood reuse; fixed repeated Present-deviation sampling and added
+separate entry/return diagnostics. NR temporal remains default-off.
+Local 120-second DLSS/XeSS 4X tests with original 4K (SR bypass) pass;
+true 1080p-to-4K SR plus NR fails 4X/6X cadence acceptance. Independent
+VFX denoise cannot create its effect and is not integrated. No fixed delay,
+hidden downshift, new runtime, main merge or publication. Detailed results:
+[current follow-up acceptance](NR_FG_FOLLOWUP_ACCEPTANCE_2026-09-21.md).
+This supersedes the timing interpretation and pending tests below.
+
2026-09-21 local bounded NR/performance review: temporal protection/time fixes
and shared-neighborhood GPU optimization tested on RTX 5070. Default remains
off; natural-video visual acceptance and independent VFX denoise are not
diff --git a/docs/NR_FG_FOLLOWUP_ACCEPTANCE_2026-09-21.md b/docs/NR_FG_FOLLOWUP_ACCEPTANCE_2026-09-21.md
new file mode 100644
index 00000000..b9b84257
--- /dev/null
+++ b/docs/NR_FG_FOLLOWUP_ACCEPTANCE_2026-09-21.md
@@ -0,0 +1,200 @@
+# NR and FG follow-up: local acceptance
+
+Scope: `codex/playback-nr-20260920`, starting at `09b4ad7`, with the accepted
+temporal correction/optimization at `ab7979c`. RTX 5070, video input only.
+No main merge, publication, shutdown, NR layering or general 1.4.2 performance
+investigation. This report records partial capability acceptance, not a claim
+that all reported picture-quality and cadence issues are solved.
+
+## Retained changes
+
+- Correct lateness sampling: one observation per actual application Present,
+ rather than repeating the last observation on every engine iteration.
+ Reuse the bounded, cached TimingWindow quantile implementation instead of
+ sorting 1200 entries each iteration. This is a diagnostic/CPU bookkeeping
+ repair, not evidence of lower screen latency.
+- Record Present entry and return separately, with signed media deviation,
+ source/revision/epoch identity, queue depth and CPU-observed GPU readiness.
+ The bounded trace is flushed after a smoke run, not written per frame.
+- Add an offline natural-video NR probe and motion-compensated analysis.
+ Readback and CPU waits are confined to the diagnostic executable.
+- The sustained harness checks XeSS provider throughput, since application
+ Present counts omit frames submitted inside the XeSS swapchain.
+- Keep the existing temporal mask/time fixes and equivalent tiled shader.
+ No new scheduler, delay, multiplier downgrade or resolution reduction.
+
+## A. Timing and true SR
+
+The previous 41.71/43.35 ms figure was an absolute deviation from the media
+clock after Present, repeatedly sampled by the engine. It is not 42 ms of
+added anti-flicker latency. The 80 ms shader constant weights past history;
+it does not wait for future frames. Neither is screen-to-eye latency.
+
+Four sequential 30-second UI tests on original 4K60 p001, NR on, SR off,
+XeSS 4X, off/on/on/off:
+
+| Measurement, P95 ms | Off A | On A | On B | Off B |
+| --- | ---: | ---: | ---: | ---: |
+| Present entry media deviation | .479 | .500 | .500 | .500 |
+| Present return media deviation | 1.229 | 1.271 | 1.229 | 1.229 |
+| Process to observed ready | 14.843 | 15.482 | 15.436 | 14.910 |
+| Decode ready to Present return | 32.936 | 32.981 | 32.970 | 32.936 |
+
+All source rates were approximately 60. These retained-window observations
+do not reproduce an added 42 ms delay in the SR-off case.
+
+Original 4K to target 4K bypasses SR. To test actual SR, derive a 1080p60
+version of p001, then request RTX Video SR quality 3 to 4K, NR, XeSS 4X.
+Clean 30-second repeats, with no simultaneous build:
+
+| Measurement | Temporal off | Temporal on |
+| --- | ---: | ---: |
+| Retained application submissions/s | 54.205 | 39.878 |
+| Present call P95 ms | 17.497 | 28.610 |
+| Process to observed ready P95 ms | 21.857 | 29.430 |
+| Observed ready to Present entry P95 ms | .0046 | .0068 |
+| Decode ready to Present return P95 ms | 38.899 | 57.410 |
+| Last reported residual GPU P95 ms | .269 | 1.129 |
+| Last reported preview source skips | 154 | 542 |
+
+This combined configuration does NOT pass full-rate acceptance. There is no
+measured long CPU hold after readiness in these samples. Present/backpressure
+and GPU readiness increase; XeSS internal GPU cost is not separately measured,
+so this is not proof of GPU saturation or a proven fixable redundant wait.
+One earlier on-run overlapped compilation and is excluded as performance
+evidence; the clean repeat confirms the slowdown. Default anti-flicker remains
+off. Do not present disabling it, reducing NR detail or lowering FG as a repair.
+
+## B. Picture quality
+
+The existing synthetic GPU tests pass protection/feather, zero-residual decay,
+invalid interval, motion rejection, reset and signed HDR cases. All 41 FP16
+fingerprints match the corrected non-tiled implementation; D3D12 debug clean.
+
+Three real-video 120-frame samples (starts 0, 25, 85 seconds), same-size
+1080p NR/NVOF, centered 640x360 linear FP16 crops, completed with zero D3D12
+errors. Matched base/raw/filtered observations use the same source frames.
+
+| Segment | Raw residual change | Filtered residual change | Raw edge energy | Filtered edge energy |
+| --- | ---: | ---: | ---: | ---: |
+| 0 | .00278450 | .00065995 | .02048084 | .02153499 |
+| 25 | .00039777 | .00011532 | .00429858 | .00436498 |
+| 85 | .00069813 | .00020498 | .00298797 | .00299468 |
+
+Motion-compensated stable-source residual variation falls about 71-76%.
+This measures enhancement stability, not independent source-noise removal.
+Global edge energy in these crops does not decrease; that alone cannot prove
+detail preservation. Inspected contact sheets show no obvious duplicate edges
+in sampled frames. p001 is mainly screen/text material, including pixel-game
+content. Fast-gameplay ghosting and complete temporal viewing remain unverified.
+
+## C. FG and released 1.4.3 comparison
+
+Sequential 30-second original-4K tests, NR1080, Performance flow, 4K target,
+temporal off. SR bypasses at equal input/output size. Counts are software
+submissions, not scanout. Trace metrics cover the final bounded window.
+
+| Backend | Result | Retained submit/s | P95 gap ms | Max gap ms |
+| --- | --- | ---: | ---: | ---: |
+| DLSS 2X | Lifecycle and 95% throughput threshold pass | 120.002 | 8.745 | 9.077 |
+| DLSS 4X | Lifecycle and 95% throughput threshold pass | 240.001 | 4.541 | 5.087 |
+| DLSS 6X | Lifecycle only; uniform cadence fails | 317.056 | 4.200 | 17.157 |
+| XeSS 2X | Provider throughput threshold pass | 120 provider / 60 app | Not measured inside SDK | Not measured inside SDK |
+| XeSS 4X | Provider throughput threshold pass | 240 provider / 60 app | Not measured inside SDK | Not measured inside SDK |
+| XeSS 6X | Unsupported, test fails as expected | N/A | N/A | N/A |
+
+DLSS 6X retained 14 gaps exceeding 16.667 ms and 43 real-only rejected/warmup
+batches. A zero minimum-throughput threshold was used for that lifecycle test;
+exit 0 must not be advertised as successful 360 fps or uniform cadence.
+The local XeSS runtime reports maxInterpolations=3 (4X); requested 6X is not
+an implemented mode. No multiplier or proprietary binary was changed.
+
+The actual released 1.4.3 application was also run on the derived1080 true-SR
+configuration, temporal off. It reported 1597 source frames and 1599 generated
+frames; current clean off reported 1493 and 3978. The old log repeatedly shows
+`xess-fg-gate event=suppress/resume` and SDK `enabled=0, framesPresented=1`.
+Its final source rate of 57 versus current 54 therefore does NOT demonstrate
+better FG service: it repeatedly stops interpolation. The current gate removal
+is retained. The provider pacing implementation remains unchanged. No reliable
+capture of SDK-generated pixels was obtained, so XeSS jelly/visual superiority
+over 1.4.3 is not accepted or claimed.
+
+Two sequential 120-second tests, temporal on, original 4K60 (SR bypass),
+NR1080 and Performance flow, both exit 0 at the 95% throughput threshold.
+XeSS provider mean is 240; application mean is about 60. DLSS retained
+submission rate is 240.018, gap P95 4.575 ms, maximum 5.584 ms, zero gaps
+over 16.667 ms. These gap figures cover the last 6.20 seconds, not all 120.
+XeSS internal generated-frame intervals are not observed by this trace.
+
+Additional true-SR UI tests: derived 1080p60, RTX Video SR quality 3 to 4K,
+NR, temporal off, identical professional window, 30 seconds each:
+
+| DLSS multiplier | Retained submit/s | Gap P95 ms | Maximum gap ms | Gaps >16.667 ms |
+| --- | ---: | ---: | ---: | ---: |
+| 2X | 120.003 | 8.730 | 9.114 | 0 |
+| 4X | 163.083 | 16.795 | 17.317 | 93 |
+| 6X | 162.566 | 16.875 | 17.658 | 151 |
+
+All exit normally and preserve source progress around 60 fps, but 4X and 6X
+FAIL full-rate/uniform-cadence acceptance. An exit-zero smoke is only a
+lifecycle result. This also prevents applying the SR-bypass 240/317 results
+to real 4K upscaling. No speculative scheduling change was retained.
+
+## D. Independent denoise prerequisite result
+
+Investigated the official NVIDIA VFX SDK 1.2.0 Python package 0.1.0.1, cp311,
+from https://pypi.nvidia.com/nvidia-vfx/. Wheel SHA256:
+`FF7E3E65B4A6ACD507C3C9DDE0D8D881891B0643AF80C4ACC5B7D886463764BD`.
+Local-only dependencies are under `E:/项目/Veyra/deps/nvidia-vfx-audit-20260921`.
+No new VFX/CUDA DLL is included in Git or the player package.
+
+CuPy sees the RTX 5070; SDK reports 1.2.0. All 17 bundled DLLs explicitly load.
+`VideoSuperRes` creation fails with code -2, "The requested feature is not yet
+implemented", before quality selection, model load or inference. A corrected
+process-local DLL search directory and NV_VIDEO_EFFECTS_PATH did not change
+the result. This does not establish that the GPU itself is unsupported.
+No denoising output, D3D12/CUDA interop, quality or performance acceptance was
+obtained. Stop this bounded attempt; there is no new working denoise switch.
+
+Official denoise quality modes are 8..11. Modes 16..19 are high-bitrate
+upscaling with artifact suppression skipped, not additional NR/denoise styles.
+Magpie reference is commit 3841698348bfb246623d4acf791984c8b68a577b (GPLv3).
+Its synchronous CUDA path and CPU 8-bit HDR fallback were not copied into live
+playback. The new probe uses the public Python API only, not copied SDK source.
+
+## Final lifecycle regression
+
+Release build succeeds. CPU live-timing tests and UI contracts pass (384
+layout cases). Temporal-on DLSS 4X transport and zoom smokes pass, including
+seek, pause/resume and fullscreen focus. Protection smoke initially failed
+because the watchdog launched a hidden parent while asserting child overlay
+visibility. Its setup now shows the window; the unchanged rectangle, overlay,
+clear/cancel and dirty-draft assertions pass. This is a test-setup correction,
+not a product overlay change.
+
+The actual professional selectors pass repeated DLSS/XeSS transitions,
+2X/4X/6X selection, off, three window sizes, and injected XeSS initialization
+failure recovery to DLSS. XeSS explicitly offers only its supported 2X..4X;
+switching from DLSS 6X is not proof of XeSS 6X support. Evidence directories:
+`final-backends`, `final-backends-reject`, and `ui-protection-temporal-retest.log`.
+Final EXE SHA256:
+`318C6B0F44ADFC3BD8094DFD5BA39B1570AA56C5D01E9A95BC40430DFD28BDA8`.
+Optional PE stack inspection was not run because this build has no linker
+map. Hardware capture and physical display latency are not tested here.
+
+## Evidence and commands
+
+- Source/build: `E:/项目/Veyra/worktrees/playback-nr-20260920` and
+ `E:/项目/Veyra/build/playback-nr-20260920`.
+- Evidence: `E:/项目/Veyra/tests/nr-fg-followup-20260921`, logs under the
+ matching `E:/项目/Veyra/logs/nr-fg-followup-20260921` directory.
+- Process-local TEMP/TMP: `E:/项目/Veyra/tmp/nr-fg-followup-20260921`.
+- Build via vcvars64 and CMake --build, targets veyra,
+ veyra_nr_video_quality_probe, veyra_fg_sustained_tests.
+- Bounded launches use scripts/run-short-test.ps1; 30-second tests use 95-second
+ watchdogs, 120-second tests use 180-second watchdogs.
+- Natural probe: `<derived1080> <output> <start> 120`; analyze with
+ scripts/acceptance/analyze-nr-natural.py.
+- Trace analysis: scripts/acceptance/analyze-fg-cadence.py <trace> --trace
+ --output <json>. GPU-ready stamps are CPU observations, not calibrated GPU
+ timestamps. Never sum unrelated P95s as an end-to-end latency.
diff --git a/docs/NR_FG_NEXT_REPAIR_PLAN_2026-09-21.md b/docs/NR_FG_NEXT_REPAIR_PLAN_2026-09-21.md
index 5be5f792..4b8885a7 100644
--- a/docs/NR_FG_NEXT_REPAIR_PLAN_2026-09-21.md
+++ b/docs/NR_FG_NEXT_REPAIR_PLAN_2026-09-21.md
@@ -28,7 +28,8 @@ fixed presentation holdback, resolution reduction or blur as a performance fix.
- NrTemporal.hlsl now reuses neighborhood observations. Existing GPU tests
prove equivalence on 41 synthetic frames, not natural-video quality.
- Magpie at 3841698348bfb246623d4acf791984c8b68a577b uses NvVFX
- VideoSuperRes with denoise quality 8..11 / 16..19. SDR uses D3D11/CUDA
+ VideoSuperRes. Official denoise quality is 8..11; 16..19 is high-bitrate
+ upscaling without artifact suppression, not denoise. SDR uses D3D11/CUDA
interop followed by stream synchronization; HDR falls back to CPU U8 staging.
These are not NGX VSR quality values and not a suitable direct HDR port.
- Current XeSS timing/motion code previously matched released 1.4.3. The
diff --git a/docs/NR_QUALITY_PERFORMANCE_ACCEPTANCE_2026-09-21.md b/docs/NR_QUALITY_PERFORMANCE_ACCEPTANCE_2026-09-21.md
index c4a50c35..06bc0850 100644
--- a/docs/NR_QUALITY_PERFORMANCE_ACCEPTANCE_2026-09-21.md
+++ b/docs/NR_QUALITY_PERFORMANCE_ACCEPTANCE_2026-09-21.md
@@ -1,5 +1,11 @@
# NR / XeSS bounded review result
+Follow-up correction: the historical 41.71/43.35 ms below is repeatedly sampled
+media-clock deviation after Present, not added filter or screen latency.
+New per-Present measurements, natural-video probes, true-SR limits and the
+official VFX creation failure are recorded in
+[the follow-up acceptance](NR_FG_FOLLOWUP_ACCEPTANCE_2026-09-21.md).
+
Branch: codex/playback-nr-20260920. Starting checkpoint:
checkpoint/pre-nr-quality-perf-20260921 (bcdbfbf).
This closes the bounded local investigation, not universal picture-quality
@@ -50,9 +56,11 @@ the whole-run average. None is physical scanout or screen-to-eye latency.
The tiled shader matches the corrected non-tiled shader's full-frame FP16
fingerprints on all 41 test frames. Both test runs pass and report zero D3D12
debug errors. This proves equality on this corpus only. Natural-video
-flicker/detail/ghosting has NOT passed subjective acceptance. Temporal-on is
-still substantially later than off (off smoke P95 1.65 ms); do not claim
-the feature is free or that its remaining delay is fixed. No further tuning.
+flicker/detail/ghosting has NOT passed subjective acceptance. The historical
+off smoke P95 was 1.65 ms, but its comparison to 41.71 ms did not isolate added
+filter latency. The follow-up's corrected per-Present ABBA measurements
+supersede that interpretation. Actual SR plus temporal still has a measured
+performance penalty; do not claim the feature is free. No further tuning.
## Release comparison and limits
diff --git a/docs/RELEASE_NOTES_1.4.4.md b/docs/RELEASE_NOTES_1.4.4.md
index c0a75846..cacd54be 100644
--- a/docs/RELEASE_NOTES_1.4.4.md
+++ b/docs/RELEASE_NOTES_1.4.4.md
@@ -2,6 +2,22 @@
本地内测版,基于 1.4.3,未发布 GitHub 正式版本。
+本轮测试包补充(2026-09-21):
+
+- 输出帧率可选择不限制、沿用显示器或自定义,默认不限制。XeSS 的提供方呈现路径暂不支持该自定义限制,不通过压低输入帧率冒充实现。
+- 字幕默认保留设置字号,双行不再自动缩小;全屏新增锁定,锁定时鼠标活动不弹出控制条。
+- 修正设置面板布局、滚动重绘和采集启动节奏问题;撤回未经验证的 XeSS 时间提示,保留生成路径的修正。
+- NR 保留三个真实模型风格及命名预设,没有新增“033 模型风格”。时间域防闪烁默认关闭。
+- 防闪烁修正保护区、羽化、零残差衰减和时间异常处理;复用 GPU 邻域数据,降低该阶段开销。
+- 修正呈现时间统计的重复采样,区分进入与返回 Present 的媒体时间偏差;这些数据不是屏幕到人眼延迟。
+
+已知限制:本机原始 4K60、NR、防闪烁加 DLSS/XeSS 4X 的 120 秒测试约
+240 次提交/秒,但原片与目标同尺寸,超分被跳过。真正 1080p→4K 超分加 NR
+时,DLSS 2X 约 120,4X/6X 约 163 次提交/秒并仍有长间隔;XeSS 4X 叠加
+防闪烁也有明显掉速。这些组合尚未修好,不能承诺稳定高倍率。
+独立输入降噪尚未实现;防闪烁不是源画面降噪。XeSS 果冻观感没有通过
+可靠生成帧的画质对照。杜比视界新增处理仍按用户要求暂缓。
+
- 采集卡新增独立的自动 / 有限 / 完整输入范围,以及手动 Rec.709 SDR。保留 PQ 与 HLG 输入选择。
- 色彩空间和范围按设备保存,修改立即记忆;切换格式、帧率、刷新和重连保留该设备的选择。旧配置自动兼容。
- 手动 HDR 使用 P010/P016。压缩采集继续读取码流元数据;不支持的手动组合明确报错,不静默忽略。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 466427fa..d36a7e33 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,52 @@
# Veyra 工作记录
+## 2026-09-21 NR/FG bounded repair and acceptance
+
+Continued from plan checkpoint 09b4ad7, preserving accepted ab7979c.
+Fixed repeated lateness sampling and per-loop quantile sorting; recorded
+actual Present entry/return with host-domain lineage and signed deviation.
+No scheduler wait, downshift, resolution or runtime changes. Added offline
+natural NR quality probe/analysis and local public-API VFX prerequisite probe.
+Full evidence: docs/NR_FG_FOLLOWUP_ACCEPTANCE_2026-09-21.md.
+
+Build: scripts/build-isolated.ps1, worktree playback-nr-20260920, matching
+build directory, MSVC Release/1.4.4beta. First diagnostics build passed.
+Tests use scripts/run-short-test.ps1; 30-second cases have 95-second watchdogs,
+120-second sustained cases 180 seconds. TEMP/TMP only process-local, under
+E:/项目/Veyra/tmp/nr-fg-followup-20260921. Logs and evidence under
+E:/项目/Veyra/{logs,tests}/nr-fg-followup-20260921.
+
+SR-off UI ABBA and actual 1080p-to-4K RTX Video SR tests distinguish media
+deviation from latency. Historical 42 ms is not measured extra filter delay.
+True-SR NR+DLSS: 2X ~120, 4X/6X ~163 submissions/s with ~17 ms gaps.
+True-SR XeSS4 temporal-on remains slower than off. Both combinations remain
+unresolved; no speculative scheduling patch retained. Original-4K SR-bypass
+DLSS4 and XeSS4 temporal-on sustained tests both pass at ~240 software
+submissions/s; XeSS is SDK throughput, not measured individual intervals.
+Three 120-frame natural quality samples pass debug validation and reduce
+stable-source residual variation; no blanket fast-gameplay quality claim.
+Actual released 1.4.3 true-SR run repeatedly suppresses XeSS generation;
+its higher source FPS does not justify reverting the current gate removal.
+
+VFX 1.2.0 official cp311 wheel verified, all 17 DLLs load, CUDA sees RTX5070,
+but VideoSuperRes Create returns -2 before load/inference. One DLL-directory
+correction reproduced it. No independent denoiser added or packaged; stop
+this bounded direction. Corrected prior documentation: modes 8..11 denoise,
+16..19 skip artifact suppression. No proprietary SDK source copied to Git.
+
+Final CPU live timing and UI contracts pass (384 layout cases). Temporal-on
+transport and zoom smokes pass. Protection smoke initially fails visibility
+because its watchdog starts the parent hidden; added ShowWindow in smoke-only
+setup, preserving the real overlay assertion. Rebuild and retest pass:
+ui-protection-temporal-retest.log confirms rectangle/overlay, clear/cancel,
+master-off and dirty-draft retention. Actual professional FG selector tests
+pass normal switching and injected XeSS initialization failure recovery;
+results in final-backends/result.json and final-backends-reject/result.json.
+Final executable SHA256 is
+318C6B0F44ADFC3BD8094DFD5BA39B1570AA56C5D01E9A95BC40430DFD28BDA8.
+Optional PE stack inspection could not run: this build has no linker .map;
+do not claim it passed. No published package, main merge or shutdown.
+
## 2026-09-21 Follow-up scope and repair plan
User closed the general 1.4.3 performance investigation and assigned external
diff --git a/include/veyra/diagnostics/FrameTrace.h b/include/veyra/diagnostics/FrameTrace.h
index b9ec2850..74acf817 100644
--- a/include/veyra/diagnostics/FrameTrace.h
+++ b/include/veyra/diagnostics/FrameTrace.h
@@ -28,6 +28,12 @@ struct FrameTraceEvent {
TraceKind kind=TraceKind::Submitted;
uint32_t detail=0,count=0;
double milliseconds=0;
+ // Populated for Present only. All host stamps use the same monotonic clock;
+ // GPU readiness is CPU-observed, never physical display completion.
+ int64_t decodedHost=0,processHost=0,readyHost=0,presentBeginHost=0,presentEndHost=0;
+ double entryDeviationMs=0,returnDeviationMs=0;
+ uint32_t queueDepth=0;
+ bool mediaDeviationValid=false;
};
// 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/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 35d943aa..5efd3ea5 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -277,6 +277,10 @@ public:
ID3D12Resource* confidenceResource() const { return confTex_.Get(); }
// Test-only borrowed ingress output. Read after process, restore NON_PIXEL_SHADER_RESOURCE.
ID3D12Resource* diagnosticLinearInput() const { return srcRgba_.Get(); }
+ // Offline diagnostics only. Borrowed after process; restore NON_PIXEL_SHADER_RESOURCE.
+ ID3D12Resource* diagnosticNrBase() const { return desc_.nrBeforeSr?srcRgba_.Get():workRgba_.Get(); }
+ ID3D12Resource* diagnosticNrRaw() const { return desc_.nrTemporal?nrTemporal_.raw():residualRgba_.Get(); }
+ ID3D12Resource* diagnosticNrFiltered() const { return residualRgba_.Get(); }
// Non-empty when the colour stage refused the referenced LUT (input space
// does not match the content domain). The engine surfaces this in the
// status panel so the refusal is visible, not only logged.
diff --git a/scripts/acceptance/analyze-fg-cadence.py b/scripts/acceptance/analyze-fg-cadence.py
index 0dde6494..e44b7720 100644
--- a/scripts/acceptance/analyze-fg-cadence.py
+++ b/scripts/acceptance/analyze-fg-cadence.py
@@ -143,6 +143,21 @@ def analyze_trace(path):
"readyObservedBeforePreviousPresent": int(observed["host"]) <= int(a["host"]) if observed else None,
})
discarded = [e for e in events if e["event"] == "Discarded"]
+ timed = [p for p in presents if int(p.get("presentBeginHost", 0)) > 0]
+ media = [p for p in timed if p.get("mediaDeviationValid") == "1"]
+ def host_delta(end, start):
+ return distribution([(int(p[end]) - int(p[start])) / 10000 for p in timed
+ if int(p.get(start, 0)) > 0 and int(p.get(end, 0)) >= int(p[start])])
+ presentation_timing = {
+ "scope": "Each actual app Present once. Signed media deviation; host intervals exclude scanout. Readiness is an upper-bound CPU observation. SDK-generated XeSS frames are not individual app Presents.",
+ "samples": len(timed),
+ "entryDeviationMs": distribution([float(p["entryDeviationMs"]) for p in media]),
+ "returnDeviationMs": distribution([float(p["returnDeviationMs"]) for p in media]),
+ "presentCallMs": host_delta("presentEndHost", "presentBeginHost"),
+ "processToReadyObservedMs": host_delta("readyHost", "processHost"),
+ "readyObservedToPresentEntryMs": host_delta("presentBeginHost", "readyHost"),
+ "decodedToPresentReturnMs": host_delta("presentEndHost", "decodedHost"),
+ }
observed_delays = [(int(e["host"]) - int(ready[(e["batch"], e["detail"])]["host"])) / 10000
for e in discarded if (e["batch"], e["detail"]) in ready]
discard_summary = {
@@ -165,6 +180,7 @@ def analyze_trace(path):
"onlyRealRejectedBatches": rejected, "onlyRealWarmupBatches": warmup,
"batchTransitions": transitions,
"discardedSubframes": discard_summary,
+ "presentationTiming": presentation_timing,
"full6GpuCosts": gpu_group_costs(events),
"presentCpuMs": distribution([float(p["ms"]) for p in presents]),
"longestGaps": sorted(gaps, key=lambda g: g["intervalMs"], reverse=True)[:12],
diff --git a/scripts/acceptance/analyze-nr-natural.py b/scripts/acceptance/analyze-nr-natural.py
new file mode 100644
index 00000000..34dfa07b
--- /dev/null
+++ b/scripts/acceptance/analyze-nr-natural.py
@@ -0,0 +1,81 @@
+"""Offline matched NR crops. Metrics are diagnostic, not a perceptual score."""
+import argparse
+import json
+from pathlib import Path
+
+import numpy as np
+from PIL import Image, ImageDraw
+
+
+def srgb(x):
+ x = np.clip(x, 0, 1)
+ return np.where(x <= .0031308, 12.92*x, 1.055*x**(1/2.4)-.055)
+
+
+def warp(image, motion):
+ h, w = motion.shape[:2]
+ y, x = np.mgrid[:h, :w]
+ px, py = x+motion[..., 0], y+motion[..., 1]
+ valid = np.isfinite(px) & np.isfinite(py) & (px >= 1) & (px < w-2) & (py >= 1) & (py < h-2)
+ px = np.clip(np.nan_to_num(px), 0, w-2)
+ py = np.clip(np.nan_to_num(py), 0, h-2)
+ ix, iy = np.floor(px).astype(int), np.floor(py).astype(int)
+ fx, fy = (px-ix)[..., None], (py-iy)[..., None]
+ result = (image[iy, ix]*(1-fx)+image[iy, ix+1]*fx)*(1-fy)+(image[iy+1, ix]*(1-fx)+image[iy+1, ix+1]*fx)*fy
+ return result, valid
+
+
+def analyze(directory):
+ width, height = 640, 360
+ arrays = {}
+ for name, channels in (("base", 4), ("raw", 4), ("filtered", 4), ("motion", 2)):
+ path = directory/(name+(".rg16f" if channels == 2 else ".rgba16f"))
+ if path.stat().st_size % (width*height*channels*2):
+ raise ValueError(f"Incomplete frames: {path}")
+ arrays[name] = np.memmap(path, dtype="<f2", mode="r").reshape(-1, height, width, channels)
+ count = len(arrays["base"])
+ if count < 2 or any(len(a) != count for a in arrays.values()):
+ raise ValueError("Unmatched frame counts")
+ rows, previous = [], None
+ selected = {0, count//4, count//2, 3*count//4, count-1}
+ sheet = Image.new("RGB", (width*3, (height+24)*len(selected)), "black")
+ draw = ImageDraw.Draw(sheet)
+ sheet_row = 0
+ for i in range(count):
+ base, raw, filtered = (np.asarray(arrays[k][i, ..., :3], dtype=np.float32) for k in ("base", "raw", "filtered"))
+ motion = np.asarray(arrays["motion"][i], dtype=np.float32)
+ if not all(np.isfinite(a).all() for a in (base, raw, filtered, motion)):
+ raise ValueError(f"Nonfinite pixels: frame {i}")
+ if i in selected:
+ for col, (name, pixels) in enumerate((("Input", base), ("NR raw", raw), ("NR anti-flicker", filtered))):
+ x, y = col*width, sheet_row*(height+24)
+ draw.text((x+6, y+4), f"Frame {i}: {name}", fill="white")
+ sheet.paste(Image.fromarray(np.uint8(np.rint(srgb(pixels)*255))), (x, y+24))
+ sheet_row += 1
+ row = {"frame": i, "changeMAE": float(np.abs(filtered-raw).mean()),
+ "edgeRaw": float(np.abs(np.diff(raw, axis=1)).mean()),
+ "edgeFiltered": float(np.abs(np.diff(filtered, axis=1)).mean()),
+ "motionP95": float(np.percentile(np.linalg.norm(motion, axis=2), 95))}
+ if previous is not None:
+ old_base, valid = warp(previous[0], motion)
+ # Restrict to photometrically matching source pixels, excluding disocclusion/cuts.
+ stable = valid & (np.max(np.abs(base/(1+np.abs(base))-old_base/(1+np.abs(old_base))), axis=2) < .008)
+ row["stablePixels"] = int(stable.sum())
+ if stable.any():
+ for k, current, old in (("raw", raw, previous[1]), ("filtered", filtered, previous[2])):
+ old_residual, _ = warp(old-previous[0], motion)
+ row[k+"ResidualDelta"] = float(np.abs((current-base)-old_residual)[stable].mean())
+ rows.append(row)
+ previous = (base, raw, filtered)
+ averages = {k: float(np.mean([r[k] for r in rows if k in r])) for k in rows[-1] if k != "frame"}
+ result = {"scope": "Same-frame SDR linear crops with real NR/NVOF; motion-compensated stable-source residuals. Edge energy is not a perceptual quality guarantee; cropped/offline results do not measure latency.",
+ "frames": count, "averages": averages, "perFrame": rows}
+ (directory/"quality.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
+ sheet.save(directory/"contact.png")
+ print(json.dumps({"directory": str(directory), "frames": count, "averages": averages}, indent=2))
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("directory", type=Path)
+ analyze(parser.parse_args().directory)
diff --git a/scripts/acceptance/probe-vfx-denoise.py b/scripts/acceptance/probe-vfx-denoise.py
new file mode 100644
index 00000000..ed08d1cf
--- /dev/null
+++ b/scripts/acceptance/probe-vfx-denoise.py
@@ -0,0 +1,64 @@
+"""Local SDK prerequisite probe, not a live D3D12 integration or latency test."""
+import argparse
+import json
+from pathlib import Path
+import time
+
+import numpy as np
+import cupy as cp
+from nvvfx import VideoSuperRes, get_sdk_version
+from nvvfx.effects.video_super_res import QualityLevel
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("output", type=Path)
+ parser.add_argument("--quality", type=int, choices=range(8, 12), default=8)
+ args = parser.parse_args()
+ args.output.mkdir(parents=True, exist_ok=True)
+ report = {"scope": "Official CUDA SDR prerequisite probe; CPU transfers are diagnostic only. No D3D12 interop or display latency measured.",
+ "sdk": str(get_sdk_version()), "quality": args.quality,
+ "device": cp.cuda.runtime.getDeviceProperties(0)["name"].decode()}
+ try:
+ h, w = 1080, 1920
+ y, x = np.mgrid[:h, :w]
+ clean = np.stack([.2+.6*x/w, .2+.6*y/h, .25+.5*((x//8+y//8) % 2)]).astype(np.float32)
+ rng = np.random.default_rng(1234)
+ times, mse_input, mse_output = [], [], []
+ with VideoSuperRes(quality=QualityLevel(args.quality)) as effect:
+ effect.output_width, effect.output_height = w, h
+ start = time.perf_counter()
+ effect.load()
+ report["loadMs"] = 1000*(time.perf_counter()-start)
+ for index in range(40):
+ noisy = np.clip(clean+rng.normal(0, .02, clean.shape), 0, 1).astype(np.float32)
+ device_input = cp.asarray(noisy)
+ cp.cuda.runtime.deviceSynchronize()
+ start = time.perf_counter()
+ result = effect.run(device_input)
+ # DLPack capsule owns a view of reusable SDK storage. Consume it
+ # before the next run; host copies are excluded from run timing.
+ output = cp.from_dlpack(result.image)
+ cp.cuda.runtime.deviceSynchronize()
+ elapsed = 1000*(time.perf_counter()-start)
+ pixels = output.get()
+ if pixels.shape != clean.shape or not np.isfinite(pixels).all():
+ raise ValueError("Invalid denoise output")
+ if index >= 10:
+ times.append(elapsed)
+ mse_input.append(float(np.mean((noisy-clean)**2)))
+ mse_output.append(float(np.mean((pixels-clean)**2)))
+ if index == 39:
+ for name, image in (("clean", clean), ("noisy", noisy), ("denoised", pixels)):
+ np.save(args.output/(name+".npy"), image)
+ report.update(passed=True, runP50Ms=float(np.median(times)), runP95Ms=float(np.percentile(times, 95)),
+ inputMSE=float(np.mean(mse_input)), outputMSE=float(np.mean(mse_output)))
+ except Exception as error:
+ report.update(passed=False, error=repr(error))
+ (args.output/"result.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
+ print(json.dumps(report, indent=2))
+ return 0 if report["passed"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/base/Log.cpp b/src/base/Log.cpp
index 4758d1fd..76b9db95 100644
--- a/src/base/Log.cpp
+++ b/src/base/Log.cpp
@@ -175,7 +175,11 @@ std::string Logger::diagnosticReport(){std::ostringstream o;o<<"Veyra 本地诊
<<" Discarded: detail=subframe, count=PreviewFrameReadiness enum, ms=deadline lateness.\n";
for(const auto& e:trace)o<<"event="<<diagnostics::traceKindName(e.kind)<<" host="<<e.host100ns<<" session="<<e.session
<<" revision="<<e.identity.settingsRevision<<" epoch="<<e.identity.epoch<<" source="<<e.identity.sourceFrameId
- <<" batch="<<e.batch<<" fence="<<e.fence<<" pts="<<e.pts100ns<<" detail="<<e.detail<<" count="<<e.count<<" ms="<<e.milliseconds<<'\n';
+ <<" batch="<<e.batch<<" fence="<<e.fence<<" pts="<<e.pts100ns<<" detail="<<e.detail<<" count="<<e.count<<" ms="<<e.milliseconds
+ <<" 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';
return diagnostics::redact(o.str());
}
void Logger::flush()
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index d46953c0..bf708aa6 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -427,7 +427,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
uint64_t activeSeekId=0;
Clock::time_point seekStarted{};
uint64_t seekDecoded=0;
- bool fileAwaitingVideo=true,fileAudioAlignPending=true,fileInputEnded=false;double lastFilePresentedMs=0,lastFilePresentLateness=0;std::deque<double> latenessSamples;
+ bool fileAwaitingVideo=true,fileAudioAlignPending=true,fileInputEnded=false;double lastFilePresentedMs=0,lastFilePresentLateness=0;
+ TimingWindow presentEntryDeviation,presentReturnDeviation;
if(!isImage&&!isCapture&&audioPipe.open(path)){
{std::lock_guard lock(mutex_);snapshot_.audioTracks=audioPipe.tracks();snapshot_.selectedAudioTrack=audioPipe.selectedTrack();}
audioPipe.holdForVideo();audioPipe.startThread(&audio,true);audioStarted=true;
@@ -1203,7 +1204,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const bool settingsChanged=metricsRevision!=options.settings.revision;
metricsRevision=options.settings.revision;metricsEpoch=metricsWindowEpoch;statsStart=Clock::now();statsSourceBase=sourceFrames-uint64_t(!rereadCached);
slotWaitBase=processWaitBase;slotWaitMsBase=processWaitMsBase;submitBase=processSubmitBase;
- captureAges.clear();scheduleWaits.clear();processTimes.clear();presentTimes.clear();decodeTimes.clear();gpuReadyTimes.clear();for(auto& window:gpuStageTimes)window.clear();lastGpuSampleEnd={};latenessSamples.clear();submissionTimes.clear();submitted=expired=0;
+ captureAges.clear();scheduleWaits.clear();processTimes.clear();presentTimes.clear();decodeTimes.clear();gpuReadyTimes.clear();for(auto& window:gpuStageTimes)window.clear();lastGpuSampleEnd={};presentEntryDeviation.clear();presentReturnDeviation.clear();submissionTimes.clear();submitted=expired=0;
// Admission predictions and the XeSS gate must not carry
// samples across a settings revision (new backend/dimensions);
// soft preview-skip history breaks do NOT reopen them.
@@ -1340,9 +1341,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(!presenter.presentationReady())return {State::Pending,optionalNow+2000};
}
const auto waited=elapsedMs(*s.deadlineStart);s.deadlineStart.reset();s.waitMs+=waited;flow->cpu(diagnostics::CpuStage::DeadlineWait,waited,host100ns());
+ const bool deviationValid=!isCapture&&!isImage&&!fileAwaitingVideo&&!paused_;
+ const double entryDeviation=deviationValid?nowMs()-itemPtsMs:0;
+ const auto presentBeginHost=host100ns();
const auto begin=Clock::now();const auto before=presenter.submittedCount();
presenter.reflexFrame(watch->reflexFrame);
if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView()))return {State::Failed};
+ const auto presentEndHost=host100ns();
+ const double returnDeviation=deviationValid?nowMs()-itemPtsMs:0;
item.lease->consumerFence=presenter.consumerFenceValue(ring.lastSignaledValue());const bool didPresent=presenter.submittedCount()>before;s.blit=presenter.blitTiming(ctx.fence());
const auto elapsed=elapsedMs(begin);s.presentMs+=elapsed;flow->cpu(diagnostics::CpuStage::Present,elapsed,host100ns());
// A soft history reset retains this metrics window. Older
@@ -1356,7 +1362,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
cadence.submitted(optionalNow);
if(physicalCapture&&veyra::log::verboseFrameLogs())veyra::log::info("capture-present-sample",std::format("source={} epoch={} revision={} batch={} subframe={} generated={} arrival={} arrivalA={} ready={} begin={} end={}",item.identity.sourceFrameId,item.identity.epoch,item.identity.settingsRevision,batch.batch.batchId,item.subframe,generated,captureArrival,lineage?lineage->a.host100ns:0,watch->frameReadyObserved[s.next],optionalNow,host100ns()));
if(veyra::log::verboseFrameLogs())veyra::log::info("pacing-sample",std::format("mode={} enabled={} sync={} pts={} begin={} end={} ready={} process={} generated={} queue={} lateMs={:.3f}",unsigned(presentationEffective.mode),presentationEffective.enabled,unsigned(presentationEffective.display),item.pts100ns,optionalNow,host100ns(),watch->frameReadyObserved[s.next],std::chrono::duration_cast<std::chrono::nanoseconds>(watch->processStart.time_since_epoch()).count()/100,generated,liveScheduler->occupancy(),isCapture?double(optionalNow-timeline.deadline(item.pts100ns))/10000:fileAwaitingVideo?0:nowMs()-itemPtsMs));
- traceFrame(diagnostics::TraceKind::Present,item.identity,batch.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsed);
+ diagnostics::FrameTraceEvent event{presentEndHost,runSessionId,item.identity,batch.batch.batchId,item.lease->consumerFence,item.pts100ns,diagnostics::TraceKind::Present,item.subframe,1,elapsed};
+ event.decodedHost=baselineReady;event.processHost=std::chrono::duration_cast<std::chrono::nanoseconds>(watch->processStart.time_since_epoch()).count()/100;
+ event.readyHost=watch->frameReadyObserved[s.next];event.presentBeginHost=presentBeginHost;event.presentEndHost=presentEndHost;
+ event.entryDeviationMs=entryDeviation;event.returnDeviationMs=returnDeviation;event.queueDepth=unsigned(liveScheduler->occupancy());event.mediaDeviationValid=deviationValid;
+ Logger::instance().recordFrame(event);
+ if(deviationValid){presentEntryDeviation.add(std::abs(entryDeviation));presentReturnDeviation.add(std::abs(returnDeviation));}
if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",batch.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));
}
// Cumulative alignment: feed whatever the providers reported
@@ -1374,7 +1385,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(fsrPresented){flow->xessSubmitted(fsrPresented,fsrGenerated,host100ns());fedFsrPresented=fsrPresentedTotal;fedFsrGenerated=fsrGeneratedTotal;}
}
if(didPresent&&!isCapture){
- lastFilePresentedMs=itemPtsMs;lastFilePresentLateness=fileAwaitingVideo?0:nowMs()-itemPtsMs;
+ lastFilePresentedMs=itemPtsMs;lastFilePresentLateness=returnDeviation;
{std::lock_guard lock(mutex_);if(snapshot_.sessionId==runSessionId&&snapshot_.applied.revision==item.identity.settingsRevision){
if(activeSeekId&&snapshot_.seekPresented!=activeSeekId)veyra::log::info("seek-latency",std::format("request={} firstPresentMs={:.3f} decodedToTarget={} ptsMs={:.3f}",activeSeekId,elapsedMs(seekStarted),seekDecoded,itemPtsMs));
snapshot_.position=itemPtsMs/1000;snapshot_.lateMs=lastFilePresentLateness;snapshot_.seekPresented=activeSeekId;}}
@@ -1460,8 +1471,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
loopTrace.mark("scheduleAndPresent");
audioRebuffering=audioStarted&&audioPipe.waitingForVideo();
const double lateness=isCapture?0:isImage?nowMs()-pts:lastFilePresentLateness;
- if(!paused_&&!isCapture){latenessSamples.push_back(std::abs(lateness));if(latenessSamples.size()>1200)latenessSamples.pop_front();}
- std::vector<double> sorted(latenessSamples.begin(),latenessSamples.end());std::sort(sorted.begin(),sorted.end());
+ // Sample only actual presentations above, not each engine iteration.
auto captureStats=physicalCapture?captureSource.metrics():source::CaptureMetrics{};
if(isScreen){const auto screen=screenSource.metrics();captureStats.received=screen.received;captureStats.delivered=screen.delivered;captureStats.dropped=screen.dropped;captureStats.readAgeMs=screen.ageMs;captureStats.frameAgeMs=double(std::max<int64_t>(0,host100ns()-pkt.pts.to100ns()))/10000;}
#ifdef VEYRA_ENABLE_REMOTEPLAY
@@ -1506,7 +1516,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
loopTrace.mark("flowSnapshot");
measured.sourceFrames=measured.flow.counters.sourceAccepted;measured.validGenerated=measured.flow.counters.fgReadyValid;measured.submitted=measured.flow.counters.realPresented+measured.flow.counters.generatedPresented;measured.expired=measured.flow.counters.generatedExpiredAfterEval;
const double ageP95=liveScheduler?completed.ageP95:captureAges.p95(),waitP95=liveScheduler?completed.waitP95:scheduleWaits.p95(),presentP95=liveScheduler?completed.presentP95:presentTimes.p95();
- ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.colorStatus=graph.videoHdrActive()?L"SDR → RTX Video HDR":options.settings.videoHdr.enabled&&!gd.hdrInput?L"SDR → SDR(HDR显示未启用)":gd.hdrOutput?(graph.hdr10Output()?L"HDR → HDR10 / PQ":L"HDR → scRGB / 浮点"):gd.hdrInput?L"HDR → SDR色调映射":L"SDR → SDR";snapshot_.position=(isCapture||isImage?pts:lastFilePresentedMs)/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];
+ ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.colorStatus=graph.videoHdrActive()?L"SDR → RTX Video HDR":options.settings.videoHdr.enabled&&!gd.hdrInput?L"SDR → SDR(HDR显示未启用)":gd.hdrOutput?(graph.hdr10Output()?L"HDR → HDR10 / PQ":L"HDR → scRGB / 浮点"):gd.hdrInput?L"HDR → SDR色调映射":L"SDR → SDR";snapshot_.position=(isCapture||isImage?pts:lastFilePresentedMs)/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=presentReturnDeviation.p95();
snapshot_.videoHdrStatus=graph.videoHdrActive()?L"预览:SDR 转 HDR 已运行":
!options.settings.videoHdr.enabled?L"RTX Video HDR 已关闭":
gd.hdrInput?L"原生 HDR 输入,无需 SDR 转 HDR":
@@ -1543,6 +1553,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(Clock::now()>=nextTimingLog){const auto [retained,overwritten]=Logger::instance().frameTraceSize();
veyra::log::info("frame-trace",std::format("retained={} capacity=8192 overwritten={} (records available in diagnostic preview)",retained,overwritten));}
if(!isCapture&&Clock::now()>=nextTimingLog){const double playbackSpeedNow=[&]{std::lock_guard lock(mutex_);return snapshot_.playbackSpeed;}();
+ veyra::log::info("present-deviation",std::format("samples={} entryAbsP95Ms={:.3f} returnAbsP95Ms={:.3f} (one sample per actual submission; media-clock deviation, not scanout latency)",presentReturnDeviation.size(),presentEntryDeviation.p95(),presentReturnDeviation.p95()));
{const auto dashboard=frameFlow->snapshot(host100ns());veyra::log::info("output-queue",std::format("pendingFrames={} enhancementProcessingMs={:.3f} extraDelayEstimateMs={:.3f}",dashboard.pendingOutputFrames,dashboard.enhancementProcessing.mean.value_or(-1),dashboard.cpuTiming[size_t(diagnostics::CpuStage::EnhancementDelayEstimate)].mean.value_or(-1)));}
veyra::log::info("player-timing",std::format("revision={} decodeP95Ms={:.3f} graphSubmitP95Ms={:.3f} gpuReadyP95Ms={:.3f} presentP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} previewSkipped={} playbackSpeed={:.3f} processed={}",options.settings.revision,decodeTimes.p95(),processTimes.p95(),liveScheduler?completed.readyP95:gpuReadyTimes.p95(),presentP95,gpuP95(diagnostics::GpuStage::Color),gpuP95(diagnostics::GpuStage::Sr),gpuP95(diagnostics::GpuStage::Flow),gpuP95(diagnostics::GpuStage::Nr),gpuP95(diagnostics::GpuStage::Residual),gpuP95(diagnostics::GpuStage::FgBatch),gpuP95(diagnostics::GpuStage::Blit),slotWaitCount,slotWaitMilliseconds,commandSubmits,submitted,expired,measured.flow.counters.previewSkippedBeforeGraph,playbackSpeedNow,sourceFrames-statsSourceBase));nextTimingLog=Clock::now()+std::chrono::seconds(1);}
if(isCapture&&Clock::now()>=nextTimingLog){
diff --git a/tests/integration/FgSustainedTests.cpp b/tests/integration/FgSustainedTests.cpp
index 70e74412..40b73dcf 100644
--- a/tests/integration/FgSustainedTests.cpp
+++ b/tests/integration/FgSustainedTests.cpp
@@ -43,6 +43,8 @@ int wmain(int argc,wchar_t** argv){
const std::wstring_view effects=argv[6];
settings.nr=effects==L"on"||effects==L"nr";
settings.sr=effects==L"on"||effects==L"sr";
+ settings.nrTemporal=GetEnvironmentVariableW(L"VEYRA_TEST_NR_TEMPORAL",nullptr,0)>0;
+ veyra::log::info("test",std::string("NR temporal=")+(settings.nrTemporal?"on":"off"));
if(liveProfile){settings.flow=FlowQuality::Performance;settings.videoSrQuality=0;settings.srTarget=veyra::pipeline::SrTarget::Uhd4K;}
if(nr900Profile)settings.nrPolicy=veyra::pipeline::NrSizePolicy::P900;
if(nr720Profile)settings.nrPolicy=veyra::pipeline::NrSizePolicy::P720;
@@ -81,7 +83,7 @@ int wmain(int argc,wchar_t** argv){
for(const auto stage:{veyra::diagnostics::GpuStage::Nr,veyra::diagnostics::GpuStage::Sr,veyra::diagnostics::GpuStage::Flow,veyra::diagnostics::GpuStage::FgBatch})
std::cout<<" gpu"<<int(stage)<<"="<<f.gpuTiming[size_t(stage)].p95.value_or(-1);
std::cout<<std::endl;
- if(elapsed>=22){recoveredRate+=f.presentSubmitFps;++recoveredSamples;}
+ if(elapsed>=22){recoveredRate+=xessProfile?f.xessSdkSubmitFps:f.presentSubmitFps;++recoveredSamples;}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(5));
@@ -92,6 +94,7 @@ int wmain(int argc,wchar_t** argv){
const double mean=recoveredSamples?recoveredRate/recoveredSamples:0;
const bool throughput=minimumRatio<=0||(recoveredSamples&&mean>=s.nominalSourceFps*multiplier*minimumRatio);
std::cout<<"SUSTAINED lifecycle="<<ok<<" recoveredMeanSubmitFps="<<mean
+ <<" rateSource="<<(xessProfile?"xess-provider":"app")
<<" minimumTargetRatio="<<minimumRatio<<" throughput="<<throughput
<<" nominalTarget="<<s.nominalSourceFps*multiplier<<" frames="<<s.frames<<" generated="<<s.generated<<std::endl;
ok=ok&&throughput;
diff --git a/tests/integration/NrVideoQualityProbe.cpp b/tests/integration/NrVideoQualityProbe.cpp
new file mode 100644
index 00000000..97a29e08
--- /dev/null
+++ b/tests/integration/NrVideoQualityProbe.cpp
@@ -0,0 +1,110 @@
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/source/MediaFileSource.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/RuntimePaths.h"
+#include "veyra/Log.h"
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <array>
+#include <d3d12sdklayers.h>
+#include <vector>
+
+// Offline, matched natural-frame observations. Readbacks and CPU waits are
+// confined to this executable; these timings are NOT playback performance.
+namespace {
+using namespace veyra;
+constexpr unsigned cropWidth=640,cropHeight=360;
+bool dumpCrop(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,
+ ID3D12Resource* texture,std::ofstream& output){
+ if(!texture)return false;
+ const auto desc=texture->GetDesc();
+ const unsigned channels=desc.Format==DXGI_FORMAT_R16G16_FLOAT?2:4;
+ if((desc.Format!=DXGI_FORMAT_R16G16_FLOAT&&desc.Format!=DXGI_FORMAT_R16G16B16A16_FLOAT)||
+ desc.Width<cropWidth||desc.Height<cropHeight)return false;
+ const unsigned rowBytes=cropWidth*channels*2;
+ const unsigned pitch=(rowBytes+255)&~255u;
+ const UINT64 bytes=UINT64(pitch)*cropHeight;
+ D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_READBACK;
+ D3D12_RESOURCE_DESC buffer{};buffer.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;
+ buffer.Width=bytes;buffer.Height=1;buffer.DepthOrArraySize=1;buffer.MipLevels=1;
+ buffer.SampleDesc.Count=1;buffer.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ Microsoft::WRL::ComPtr<ID3D12Resource> readback;
+ if(FAILED(ctx.device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&buffer,
+ D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback))))return false;
+ Status status;unsigned slot;auto* list=ring.acquireNext(slot,status);if(!list)return false;
+ D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ barrier.Transition={texture,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
+ D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,D3D12_RESOURCE_STATE_COPY_SOURCE};
+ list->ResourceBarrier(1,&barrier);
+ D3D12_TEXTURE_COPY_LOCATION src{},dst{};src.pResource=texture;
+ src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;dst.pResource=readback.Get();
+ dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ dst.PlacedFootprint.Footprint={desc.Format,cropWidth,cropHeight,1,pitch};
+ const unsigned x=(unsigned(desc.Width)-cropWidth)/2,y=(desc.Height-cropHeight)/2;
+ const D3D12_BOX box{x,y,0,x+cropWidth,y+cropHeight,1};
+ list->CopyTextureRegion(&dst,0,0,0,&src,&box);
+ std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return false;
+ void* data=nullptr;D3D12_RANGE range{0,SIZE_T(bytes)};
+ if(FAILED(readback->Map(0,&range,&data)))return false;
+ for(unsigned row=0;row<cropHeight;++row)
+ output.write(static_cast<const char*>(data)+size_t(row)*pitch,rowBytes);
+ D3D12_RANGE empty{};readback->Unmap(0,&empty);return bool(output);
+}
+}
+int wmain(int argc,wchar_t** argv){
+ if(argc!=5)return 2; // source, output directory, start seconds, frame count
+ const double start=_wtof(argv[3]);const unsigned count=unsigned(_wtoi(argv[4]));
+ if(start<0||count<2||count>240)return 2;
+ const std::filesystem::path directory=argv[2];std::filesystem::create_directories(directory);
+ Logger::instance().openFile((directory/L"engine.log").wstring());
+ Logger::instance().setConsoleEnabled(false);
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;
+ gfx::DeviceContextDesc device;device.enableDebugLayer=true;
+ if(!ctx.initialize(device,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,status))return 2;
+ source::MediaFileSource source;source::SourceOpenDesc open;
+ open.path=argv[1];open.preferHardwareDecode=false;
+ if(!source.open(open))return 2;
+ const auto info=source.info();
+ // Same-size SDR avoids resampling the motion crop or hiding colour conversion.
+ if(info.width!=1920||info.height!=1080)return 2;
+ if(start>0&&!source.seek({int64_t(start*1000),1000}))return 2;
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc settings;
+ settings.sourceWidth=settings.workWidth=settings.nrWidth=settings.flowWidth=info.width;
+ settings.sourceHeight=settings.workHeight=settings.nrHeight=settings.flowHeight=info.height;
+ settings.enableNr=true;settings.nrTemporal=true;settings.enableFg=false;settings.enableSr=false;
+ settings.enableNvofStandalone=true;settings.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ if(!graph.initialize(settings)||!graph.createViews())return 2;
+ std::array<std::ofstream,4> streams;
+ const char* names[]={"base.rgba16f","raw.rgba16f","filtered.rgba16f","motion.rg16f"};
+ for(unsigned i=0;i<4;++i)streams[i].open(directory/names[i],std::ios::binary);
+ std::ofstream metadata(directory/L"frames.csv");metadata<<"index,source,ptsMs,epoch\n";
+ bool ok=true;unsigned captured=0;
+ while(captured<count){
+ pipeline::FramePacket packet;const AVFrame* frame=nullptr;
+ if(source.read(packet,&frame)!=source::SourceReadStatus::Frame){ok=false;break;}
+ if(packet.pts.toDouble()<start)continue;
+ pipeline::EnhanceGraph::FrameOutputs output;
+ if(!graph.process(frame,packet.pts.toDouble()*1000,captured==0,output,packet.sequence,&packet.colorInfo)||!ring.waitIdle()){ok=false;break;}
+ ID3D12Resource* textures[]={graph.diagnosticNrBase(),graph.diagnosticNrRaw(),graph.diagnosticNrFiltered(),graph.flowResource()};
+ for(unsigned i=0;i<4;++i)ok=dumpCrop(ctx,ring,textures[i],streams[i])&&ok;
+ if(!ok)break;
+ metadata<<captured<<','<<packet.sequence<<','<<packet.pts.toDouble()*1000<<','<<output.batch.identity.epoch<<'\n';
+ ++captured;
+ }
+ ring.drainQueue();graph.shutdown();source.close();
+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;
+ unsigned errors=0;
+ if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;
+ for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){
+ SIZE_T size=0;if(FAILED(debug->GetMessage(i,nullptr,&size)))return 2;
+ std::vector<unsigned char> bytes(size);auto* message=reinterpret_cast<D3D12_MESSAGE*>(bytes.data());
+ if(FAILED(debug->GetMessage(i,message,&size)))return 2;
+ if(message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<message->pDescription<<'\n';}
+ }
+ std::cout<<"captured="<<captured<<" requested="<<count<<" crop=640x360 centered; linear FP16; real NR/NVOF, offline only\n";
+ std::cout<<"debugErrors="<<errors<<'\n';
+ return ok&&captured==count&&metadata&&errors==0?0:1;
+}