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 live DLSS admission and frame accounting; retire legacy Loop gates
Veyra Goal Agentbe00e271c1f1
diff --git a/AGENTS.md b/AGENTS.mdindex 82c77239..9a364b32 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> 2026-09-10 用户废弃旧 Loop:`loop/`、`scripts/loop-gate.ps1`、`CONTROL_HASHES.json` 及早期 Phase 排队/控制哈希停工规则全部退出当前执行流程,仅保留作历史记录。不得因旧 Loop 状态、STOP、控制哈希或旧文档顺序阻塞用户明确要求的修复,也不得更新旧清单来制造通过。当前任务以最新用户指令、对应修复计划和 `docs/WORKLOG.md` 为准。构建、针对性回归及必要的 `scripts/gates/delivery.ps1` 直接执行;单次测试最多 300 秒,并非全部测试累计 300 秒。运行时身份、源码/二进制隔离、真实验证与发布授权规则继续生效。+> 2026-09-07 新用户决定:默认明确标注的实时档(4K输入可用1080内部处理),保留原生4K可选;视频导出仍原生4K。不得要求以本机原生4K NR达到60fps作为本次默认档门槛,也不得把实时档冒充native4K。最终统一软件短测为 `scripts/gates/delivery.ps1`(phase5–7本次合同的合并检查),实卡仍由用户验收。其他安全/许可规则不变。> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。@@ -8,23 +10,12 @@本文件对在本目录工作的所有 Agent 生效。不要只扫标题;开工前必须完整阅读:1. `README.md`——当前状态和唯一入口;-2. `VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md`——唯一施工手册;+2. 当前任务对应的 `docs/*PLAN*.md`——当前施工方案;旧 `VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md` 仅作技术契约与历史参考;3. `VEYRA_PRODUCT_SPEC_V1.md`——产品与技术边界;4. `docs/COMPETITOR_AUDIT_2026-09-03.md`——竞品事实、许可证和可迁移启发;5. 当前阶段的 `docs/WORKLOG.md`——已完成、失败记录和下一步。-如果任务以 Goal/无人值守模式运行,还必须先完整阅读:--6. `loop/LOOP_ENGINE.md`——循环、恢复、审查和停机协议;-7. `loop/STATE.json`——当前真实阶段和下一动作;-8. `loop/BACKLOG.md` 与 `loop/INBOX.md`——唯一任务队列和人工阻塞;-9. `loop/REVIEW_PROMPT.md`——阶段独立复核的固定只读任务。--Goal 启动后,`.gitignore`、上述规则/方案、`loop/CONTROL_HASHES.json`、-基础 `scripts/loop-gate.ps1` 和 `scripts/gates/README.md` 都是只读控制面。-preflight 报控制面 hash 漂移时必须停下,不得改 manifest 或 gate 自我放行。--若施工手册与 Product Spec 冲突,以施工手册中更具体、更新的实现指令为准;若本文件与施工手册冲突,以本文件的安全、许可证和阶段门禁为准。+旧 Loop 不再要求阅读、同步或运行。最新用户指令优先于历史方案;仍适用的技术、运行时身份和许可证约束以本文件为准。## 不可擅自改变的决定@@ -73,28 +64,21 @@ renodx-dlss5-1.addon64- **范围最小化。** 用户包只包含运行所需 DLL/模型与适用许可证、notice、manifest;绝不包含 SDK 开发文件、样例、私有测试媒体、日志、PDB、LIB 或游戏文件。官方 SDK 中明确可集成分发的组件仍须逐项保留其许可证与来源记录。- **人工发布。** 任何 push、GitHub Release、Runtime Pack 上传、替换或删除都必须由用户在当前对话明确授权;无人值守 Goal 仍禁止发布。若平台或权利方要求移除,先移除/下架 Runtime Pack,再保留不含该 Pack 的 Veyra 基础包。-## 阶段门禁+## 当前修复验收-严格按 Playbook 的 Phase 0→7 完成 V1;Phase 7 通过后停止,不再自动扩展。每个阶段必须同时满足:+当前修复按用户请求和当前方案推进,不再按旧 Phase 0→7 排队。每次交付必须同时满足:1. 代码可构建;-2. 本阶段列出的自动或手工检查通过;+2. 本次改动相关的自动或手工检查通过,未执行项明确报告;3. `docs/WORKLOG.md` 写明命令、结果、日志路径、失败与修复;4. 没有把 proprietary runtime 或本地 SDK 提交进版本控制;-5. 下一阶段没有建立在未验证假设上。+5. 后续改动没有建立在未验证假设上。-Phase 0–4 的历史 checkpoint 只能证明各基础 harness 当时通过,不能冒充三种产品模式完成。2026-09-06 审查已撤销历史 Phase 5 的产品级通过状态:旧 gate 接受 manifest-only depth、假 4K endurance,且共享 EnhanceGraph 只是计数壳;组件日志保留,Phase 5 必须重验。Phase 7 的三条端到端 gate 全过前只能是开发中;功能 gate 通过但公开分发权未解决时只能写 `release_candidate / distribution_blocked`,不得写已公开首发或 complete。+历史 Phase/checkpoint 只证明当时的测试结果,不代表当前产品已经验收。当前状态按本次构建、回归、实卡和发布证据分别报告;不得拿早期通过或失败标签替代当前事实。-## 无人值守 Goal Loop+## 历史 Loop-- 用户以 `loop/GOAL_PROMPT.md` 启动 Goal 时,允许在阶段硬门禁和独立 Reviewer 均通过后自动进入下一 Phase;安全、许可证和验收规则没有自动豁免。-- 主 Agent 是唯一写入者。禁止多个 Agent 同时修改同一 checkout;阶段 Reviewer 必须是新上下文、只读,不能替 Maker 改代码。-- 每个 cycle 只处理 `loop/BACKLOG.md` 当前 Phase 的第一个可执行原子任务。改动前写 `loop/JOURNAL.md`,改动后运行当前 gate。-- 统一 gate 入口:`powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate phaseN`。-- 同一 failure fingerprint 最多尝试 3 个真正不同、能增加证据的方案;连续 5 轮无新证据或总计 120 轮后必须留档停机,不得空转。-- `loop/STOP` 是用户停机开关。看到它就更新状态并退出,Agent 不得删除。-- 未实际获得独立 Reviewer 结论时只能标 `needs_review`;不能降级成“自己再看一遍”后自动放行。-- 只准本地 checkpoint commit。禁止无人值守 push、PR、发布、上传 artifact 或制作安装包。+旧循环状态与 Phase 记录只代表当时证据,不是当前任务队列或通过证明。保留历史文件供追溯,不再据其自动推进、阻塞或发布。工作记录统一更新到 `docs/WORKLOG.md` 和本次修复文档;未经实际独立复核不得声称有 Reviewer 验收。## 实现纪律@@ -127,13 +111,13 @@ Phase 0–4 的历史 checkpoint 只能证明各基础 harness 当时通过,## 每次交付必须报告-- 当前 Phase 与完成门槛;+- 当前修复任务与完成门槛;- 修改的文件;- 实际运行过的构建/测试命令;- Create/Evaluate 或失败码的真实日志,不得用“应该可以”代替;- 已知风险和下一条唯一任务;- 若没实际在 RTX/NVIDIA runtime 上执行,明确写“未执行”,绝不能声称成功。-- Goal 模式还必须同步更新 `loop/STATE.json`、`loop/EVIDENCE.md` 和 `loop/JOURNAL.md`,保证上下文压缩或进程中断后可从磁盘恢复。+- 长任务必须在当前修复文档保留可续接的状态、证据与下一步;不再同步旧 Loop 状态。## 禁止用假完成糊弄diff --git a/CMakeLists.txt b/CMakeLists.txtindex 86ef3a8b..e5a51f05 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -450,6 +450,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformadd_executable(veyra_live_presentation_tests tests/integration/LivePresentationTests.cpp)target_compile_features(veyra_live_presentation_tests PRIVATE cxx_std_20)target_link_libraries(veyra_live_presentation_tests PRIVATE veyra_engine)+ add_executable(veyra_fg_admission_tests tests/integration/FgAdmissionTests.cpp)+ target_compile_features(veyra_fg_admission_tests PRIVATE cxx_std_20)+ target_compile_definitions(veyra_fg_admission_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+ target_link_libraries(veyra_fg_admission_tests PRIVATE veyra_engine)target_compile_features(veyra_capture_color_tests PRIVATE cxx_std_20)target_link_libraries(veyra_capture_color_tests PRIVATE veyra_sources)add_executable(veyra_yuy2_color_tests tests/integration/Yuy2ColorTests.cpp)diff --git a/README.md b/README.mdindex 4ab96abb..6385c4eb 100644--- a/README.md+++ b/README.md@@ -99,6 +99,8 @@ Video / image / capture card## 项目结构 / Project layout+当前修复以最新用户要求、`AGENTS.md`、对应 `docs` 修复方案和 `docs/WORKLOG.md` 为准。早期 `loop/` 状态、控制哈希与 Phase 队列已归档,不再作为开发前置门禁。Current work follows the latest task, `AGENTS.md`, its repair plan and `docs/WORKLOG.md`; the legacy Loop state and control-hash gates are historical only.+| Path | Purpose || --- | --- || `apps/veyra` | Win32 application and the two-mode interface |diff --git a/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md b/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.mdindex b4512c22..4d623cb0 100644--- a/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md+++ b/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md@@ -1,5 +1,7 @@# Veyra Launch V1 施工手册+> 2026-09-10:本手册为历史参考。用户已废弃旧 Loop、控制哈希 preflight 与早期 Phase/R0–R12 强制执行顺序;不得按本文的旧入口阻塞当前修复。当前任务以最新用户指令、AGENTS.md、对应修复计划及 WORKLOG 为准。仍适用的 GPU、颜色、资源生命周期契约继续参考,测试单次不超过 300 秒。+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。版本:1.2(强 Agent 接管恢复版)diff --git a/apps/veyra/TelemetryWindow.cpp b/apps/veyra/TelemetryWindow.cppindex 48b4a053..3212b43f 100644--- a/apps/veyra/TelemetryWindow.cpp+++ b/apps/veyra/TelemetryWindow.cpp@@ -16,6 +16,15 @@ void refresh(){auto s=engine->snapshot();const wchar_t* names[]={L"上传/颜色for(size_t i=0;i<s.metrics.gpu.size();++i){const auto& g=s.metrics.gpu[i];o<<names[i]<<L":"<<(g.state==diagnostics::SampleState::NotExecuted?L"未执行":g.state==diagnostics::SampleState::Pending?L"待GPU完成":value(g.milliseconds))<<L"\r\n";}o<<L"\r\nCPU与调度(毫秒,独立于GPU):取帧 "<<value(s.metrics.decodeCpuMs)<<L" / 图提交 "<<value(s.metrics.submitCpuMs)<<L" / GPU就绪等待 "<<value(s.metrics.gpuWaitCpuMs)<<L"\r\n截止时间等待 "<<value(s.metrics.deadlineWaitCpuMs)<<L" / Present调用 "<<value(s.metrics.presentCpuMs)<<L"\r\n源帧 "<<s.metrics.sourceFrames<<L" / 有效生成 "<<s.metrics.validGenerated<<L" / 实际提交 "<<s.metrics.submitted<<L" / 过期补帧 "<<s.metrics.expired<<L"\r\n当前批次容量 "<<s.metrics.queueWatermark<<L"(上限4);采集入口容量1;采集丢弃 "<<s.captureDropped<<L"\r\n实际提交频率(最近1秒观察):"<<value(s.submissionFps)<<L"fps;实际显示扫描率/光子延迟:未测\r\n";const auto flowName=s.applied.flow==engine::FlowQuality::Performance?L"性能":s.applied.flow==engine::FlowQuality::Balanced?L"平衡":L"质量";+ const auto& f=s.metrics.flow;const auto& c=f.counters;+ o<<L"\r\n当前统计窗口:会话 "<<f.latest.sessionId<<L" / 设置 "<<f.latest.frame.settingsRevision<<L" / epoch "<<f.latest.frame.epoch+ <<L"\r\nDLSS/FRUC 有效生成 "<<value(f.validGeneratedFps)<<L" fps / Present 提交 "<<value(f.presentSubmitFps)<<L" fps"+ <<L"\r\nXeSS SDK 生成提交 "<<c.xessSdkGenerated<<L"(不等于屏幕扫描帧数)"+ <<L"\r\n补帧候选 "<<c.fgCandidate<<L" / 提交前跳过 "<<c.fgSkippedBeforeEval<<L" / 已执行 "<<c.fgEvaluated<<L" / 预热 "<<c.fgWarmup+ <<L"\r\n有效生成 "<<c.fgReadyValid<<L" / 无效 "<<c.fgInvalid<<L" / 已呈现 "<<c.generatedPresented<<L" / 过期 "<<c.generatedExpiredAfterEval+ <<L"\r\n真实帧呈现 "<<c.realPresented<<L" / 取消呈现 "<<c.cancelledBeforePresent<<L" / 采样跳过 "<<c.sourceSkippedBeforeGraph+ <<L"\r\n命令槽占用 "<<c.commandSlotsInFlight<<L" / 6;观察峰值 "<<c.commandSlotHighWater<<L";呈现批次峰值 "<<c.presentationBatchHighWater<<L" / 2"+ <<L"\r\n槽复用等待 "<<f.slotReuseWaitCount<<L" 次 / "<<value(f.slotReuseWaitMs)<<L" ms\r\n";o<<L"光流请求:"<<flowName<<L";实际SDK perf="<<s.flowPerf<<L";grid=4(已验证SDK能力)\r\n内容节奏:"<<(s.contentFps?std::to_wstring(s.contentFps)+L"fps":L"未确认(静态或证据不足)")<<L";保留源时间戳,重复内容不计有效生成\r\n"<<s.status;setText(GetDlgItem(window,1),o.str());}diff --git a/docs/ACTIVE_DELIVERY_PLAN.md b/docs/ACTIVE_DELIVERY_PLAN.mdindex 2d774f97..81c4e0d1 100644--- a/docs/ACTIVE_DELIVERY_PLAN.md+++ b/docs/ACTIVE_DELIVERY_PLAN.md@@ -1,4 +1,6 @@-# 2026-09-06 用户直接接管执行计划(当前唯一推进顺序)+# 2026-09-06 用户直接接管执行计划(历史记录)++> 2026-09-10:用户已废弃旧 Loop 与本计划的强制推进顺序。当前按最新用户指令和对应修复方案执行,不运行旧控制哈希 preflight,不以旧 STATE/BACKLOG 阻塞修复。保留本文件供追溯,已有测试工具仍可直接用于相关回归。授权原话:直接接手,先整理文档并制定详细计划,完成软件;测试最多五分钟;当前采集卡未接入,由用户亲自实卡测试;开启目标模式。diff --git a/docs/SCHEDULER_REPAIR_IMPLEMENTATION_2026-09-10.md b/docs/SCHEDULER_REPAIR_IMPLEMENTATION_2026-09-10.mdnew file mode 100644index 00000000..841f3856--- /dev/null+++ b/docs/SCHEDULER_REPAIR_IMPLEMENTATION_2026-09-10.md@@ -0,0 +1,93 @@+# 调度修复实施与证据++日期:2026-09-10。当前状态:已构建并通过本轮软件短测;FRUC 恢复问题和完整 S3/S4 仍开放,不宣称所有性能问题解决。++## 旧 Loop 为何阻塞,以及现在的规则++旧 `scripts/loop-gate.ps1 -Gate preflight` 仍把 `loop/CONTROL_HASHES.json` 内的早期内容作为唯一基线。README 和 AGENTS 已随功能、发布策略更新,因此只有这两项控制哈希失败;并非构建错误、DLL 身份失败或 SDK 缺失。用户明确要求废弃旧体系后,已更新 AGENTS、README、早期 Playbook、ACTIVE_DELIVERY_PLAN 和 gates README:旧 Loop、STOP、Phase 排队和控制哈希不再控制当前任务。没有改旧哈希清单,也没有伪造 preflight 通过。++`delivery.ps1` 删除对旧 `loop/STOP` 的依赖,并显式加载当前 PowerShell 自带的 Utility 模块,修复 Windows PowerShell 从 PowerShell 7 继承模块路径后找不到 Get-FileHash 的问题。播放、图像、编码、帧数、音轨和取消检查原样保留。产品导出完整性代码未修改。历史测试素材仍位于 ignored `loop/local`,路径保留并不意味着启用旧工作流。++## 实现++1. `FrameFlowWindow` 为每个 session/revision/epoch 独立保存账本。异步任务持有自己的窗口,设置切换或 Drop 后的旧完成不能写入新窗口。关闭窗口仍落一次完整计数,活动窗口每秒汇总。+2. 统计源帧接受/采样跳过、真实帧提交、FG 候选/提交前跳过/Evaluate/预热/有效/无效、真实/生成呈现、过期和取消。每个窗口记录最后的源 sequence、batch 和 ready/consumer fence。GPU 计时和 blit 同时过滤 revision 与 epoch。+3. 有效生成 FPS 和 Present 提交 FPS 采用最近一秒事件窗口,暂停显示零,停流会衰减。XeSS 的 SDK 生成提交单列,不把它叫经过本应用逐帧验证的生成数或屏幕扫描率。+4. 采集 packet.sequence 改为对应回调的序号,读出计数仍独立;mailbox 覆盖后序号缺口可见。容量仍为 1,half-rate 的有意跳过单独统计。+5. 仅采集的 DLSS FG 在 Evaluate 前执行 admission。沿原 arrival/PTS 时间线判断;整对的最后生成时间戳也已过期,或同窗口实测预测无法赶上时,跳过该对全部 FG 工作。保留既有 10ms 呈现容差,不改变 SR/NR 质量。+6. 跳过后只使 FG 内部历史失效,下一次执行先 reset/reseed,恢复帧只输出真实画面。NR、SR 与运动估算继续遵守原历史边界;文件与导出不启用 admission。+7. `PresentationWorker` 的 queued 取消也有回调计数;析构前先 join,防止任务引用的局部统计对象已被析构。呈现前取得 GPU 锁后再次检查过期,避免在等锁期间失去时效仍提交。+8. 修复 `EnhanceGraph::applySettings` 的倍率比较:界面的关闭值 1 应对应至少 2 倍的已分配容量。原来关闭 FG 后再改内容节奏会被错误拒绝。60 -> 30 -> 60 的回归已复现并修复。++文件:`include/veyra/{diagnostics/FrameMetrics,engine/FrameFlowWindow,engine/LiveFgAdmission,engine/EngineController,engine/PresentationWorker,engine/TimingWindow,engine/VideoPresenter,gfx/CommandSlotRing,pipeline/EnhanceGraph}.h`;`src/{engine/EngineController,gfx/CommandSlotRing,pipeline/EnhanceGraph,source/CaptureCardSource}.cpp`;`apps/veyra/TelemetryWindow.cpp`;对应 tests、CMake 和 `scripts/acceptance/scheduler-short-test.ps1`。++## 同源过载对照++测试实际调用同一产品 EngineController 和实时 PresentationWorker,使用文件回放模拟实时调度;没有打开物理采集卡,回放没有模拟 DirectShow mailbox 的回调覆盖。++输入:`loop/local/fixed_clips/test_av_1080p.mp4`,SHA256 `7952AD2904C8FED78402BC299EA2A04D1D869663EBCE17BBAC0C297F84FA2A91`。配置:1080p60 -> RTX Video SR quality4 -> 原生 3840x2160 NR -> DLSS 4X。唯一差异是 test-only admission 关闭/开启。++| 150 源帧观察点 | 旧调度对照 | 新 admission |+| --- | ---: | ---: |+| FG Evaluate | 450 | 0 |+| 提交前跳过 | 0 | 450 |+| 已计算后过期 | 444 | 0 |+| 生成帧呈现 | 0 | 0 |+| GPU 完成处理速率 | 27 fps | 33 fps |+| 真实帧 Present | 149 | 148 |+| 合成回放 arrival 到 Present 返回 P95 | 71.9153 ms | 60.6036 ms |++最后 1--2 批由测试停止取消,不是把真实源帧当生成帧跳过。旧对照结束时多处理了 1 源帧,因此 closed 汇总为 151 源帧/453 Evaluate/447 expired;表格固定使用停止前 150 源帧观察点,不能混用两个采样时刻。++日志:`logs/scheduler-repair-20260910/overload-{baseline,admission}/{engine.log}`,stdout 和 result JSON 位于同级,记录测试 EXE hash。结束后的旧槽复用等待 752 次/4821.273ms,新策略为 0 次;这是此过载回放的观察结果,不是所有配置都没有 CPU 等待。++没有实测 GPU 占用百分比,没有外部 scanout/光子延迟测量,不据此声称与 Magpie 等效或原生 4K NR 已达 60fps。++## 构建和回归++所有测试串行,每次进程由短测脚本限制到 290 秒。GPU 为本机 RTX 5070;不读取实体采集卡。++```powershell+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release+./scripts/acceptance/scheduler-short-test.ps1 -Name cpu-final -Exe ./out/build/x64-release/veyra_repair_contract_tests.exe+./scripts/acceptance/scheduler-short-test.ps1 -Name worker-final -Exe ./out/build/x64-release/veyra_presentation_worker_tests.exe+./scripts/acceptance/scheduler-short-test.ps1 -Name live-half-final -Exe ./out/build/x64-release/veyra_live_presentation_tests.exe -TestArgs @('loop/local/fixed_clips/test_av_1080p.mp4','logs/scheduler-repair-20260910/live-half-final','--half-rate')+./scripts/acceptance/scheduler-short-test.ps1 -Name live-fruc-verified -Exe ./out/build/x64-release/veyra_live_presentation_tests.exe -TestArgs @('logs/video-sdk-trial-20260909/known-pan15.mp4','logs/scheduler-repair-20260910/live-fruc-verified','--fruc')+./scripts/gates/delivery.ps1 -Root .+```++- Release build exit0,`logs/scheduler-build-20260910-final.log`;首轮 LNK1104 因正在运行的 EXE 被占用,正常关闭应用后成功。+- CPU 43 项、worker 12 项 PASS;half-rate 实际 engine 23 项 PASS(10.89秒),FRUC 保留路径 18 项 PASS(6.98秒)。+- `veyra_fg_admission_tests.exe dlss N <1080 clip> <logdir>`,N=2/3/4:各处理 40 真实帧、40 次 NR;分别跳过 8/16/24,Evaluate 32/64/96,恢复 2 次,有效生成 29/58/87,D3D12 debug errors=0;真实输出读回非黑,合法 PTS。单次约 3--5秒。它不是自然运动质量评分。+- `veyra_experimental_backend_tests.exe xess logs/scheduler-repair-20260910/xess-final`:SDK generated=43、debugErrors=0,2.92秒;不是 AMD 实机或屏幕扫描验证。+- `python scripts/acceptance/ui-window-resize.py out/build/x64-release/veyra.exe loop/local/fixed_clips/test_av_1080p.mp4`:24移动、24缩放、4弹出选择器、干净退出,20.12秒;`logs/optimization-goal-20260908/resize-1789042165506228700/result.json`。+- 联合 delivery 23 项 PASS,47.64秒,`logs/delivery/13a7fe7290f643d29c64f6acc8fe8a32/result.json`。包括真实 NR/NVOF、GBV、native4K、播放/暂停/seek、PNG/JPEG、NVENC H.264/HEVC、CFR/音轨/取消;后续仅补充采集统计归属与 XeSS 计数,已分别复跑 live 和 XeSS 回归。++NR CreateFeature 的实际日志为 `id=18 result=0x1 (NVSDK_NGX_Result_Success) handle=non-null seh=0`;上面的 NR Evaluate 数来自实际 graph metrics,DLSS 次数来自实际调用。固定 NR 运行时身份沿用本次已核对的 E16BCF15...1FC8E / NVIDIA Valid,没有替换文件。++## 失败与明确保留项++### 续接审查与 FRUC 定位++本轮继续审查后补齐新窗口首批 command-slot wait 统计,以及文件播放在暂停/seek/对比时取消输出的计数。短测脚本新增 FRUC worker SHA256 和独立运行日志目录;此前 JSON 只记录主测试 EXE,worker 单独构建后 EXE hash 不变,不能据此推断 worker 也没变化。++`--reset-pixels` 在当前基线复现失败。新增失败输出的平移匹配诊断:首对错误输出对应上一真实帧,第二对常对应上一对插值结果(相对当前输入为 -12px,正确目标为 -4px)。因此存在读取旧输出的证据,不能简单说成光流估计不准。++按独立实验依次验证:FRUC 重建后相对时间起点、仅首帧上传等待、所有输入上传等待、D3D11 Wait/Signal/Flush、CUDA legacy-stream 完成信号、官方 `cuCtxRecordEvent` + GPU semaphore、独立完成 fence、持久化参数,以及 D3D11 输出纹理再拷贝共享纹理。上述候选全部未通过 reset 像素检查,均已撤下;Backend/Worker/Protocol 最终与本轮前一致。++诊断性 `cuCtxSynchronize` 加 D3D11 完成通知的版本通过全部 6 个重置 epoch 的像素检查(`fruc-reset-cuda-sync`,5.54秒)。这是同步/可见性问题的线索,尚不能确定具体漏掉的资源交接;该同步版本没有进入产品,不引入逐帧 CPU GPU 等待。后续应检查 CUDA/D3D11 互操作的资源映射、实际完成与缓存可见性,不能再次只凭 API 成功或 event 到达宣称修好。++证据位于 `logs/scheduler-repair-20260910/fruc-reset-*.{stdout.log,result.json}`;对应 build 日志同目录。最初输出桥接纹理 Register 返回3,补共享标志后可初始化但像素仍失败。官方 API 依据:<https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html>,仅查阅文档,没有新增或替换 SDK/runtime。++最终审查构建 `scheduler-reviewed-build.log` exit0;`cpu-reviewed` 43项、`worker-reviewed` 12项、`live-half-reviewed` 23项(8.42秒)、`live-fruc-reviewed` 18项(7.02秒)通过。联合短测 `delivery-reviewed` 的23项功能检查通过,但结果落盘缺少 Get-FileHash 导致整体exit1(44.74秒,run `52145ee98a0140b799749c8c3792f106`),保留失败记录并修正模块加载后完整重跑。++修正后 `delivery-reviewed-fixed` exit0,23项全部通过,外部计时42.78秒(gate内部42.43秒);`logs/delivery/ac24ad4a2e1e4169a171fda66e4b7e84/result.json`。对应最终产品 EXE SHA256 `429C5600E2A4ABF8D72B83B0F658B3190FE5397FE9A11256946B924CABA560F4`。`git diff --check` 通过;Git跟踪/待加入范围未发现runtime、SDK、EXE、DLL、LIB、模型或测试媒体。实卡仍未执行。++- `live-half` 初次因关闭 FG 后倍率比较错误而两项失败;修复后 `live-half-fixed` / `live-half-final` 全过。原失败日志保留。+- `admission-fruc4` 使用普通测试片时 API/资源调用成功,但 valid=0,测试 exit1;明确运动的 `known-pan15.mp4` 得到 valid=87。没有把重复帧计成有效生成。+- `live-fruc-final` 试启用产品 FRUC admission 后,90 候选中 73 跳过、17 次全用于预热,未产出有效生成;原因是恢复每次重启 worker,导致再次迟到。产品入口已撤下 FRUC admission,`live-fruc-retained` / `live-fruc-verified` 全过。+- FRUC 既有 reset-pixels 失败仍未解决。最终保留原 worker,不声称像素质量或轻量 reset 已通过。+- S3 单线程 GPU 所有者状态机、真实源帧进一步 coalesce、全部 reset 耗时分解、固定容量逐帧诊断环,以及 S4 额外提交合并尚未实施。保留双线程互斥 GPU 访问、容量 2 呈现队列和 6 槽环;本次没有增加无界队列、全帧 CPU 回读或每 pass fence wait。+- 下一任务:先以 FRUC 重置后像素与时间戳复现定位恢复链,再决定轻量 reseed 与 admission;实卡表现由用户观察,禁止以此回放代替实卡验收。++未 push、未发布、未打包 runtime,未提交 SDK/二进制/测试媒体。当前可执行文件为 `out/build/x64-release/veyra.exe`;使用 `Veyra.cmd` 启动。diff --git a/docs/SCHEDULER_REPAIR_PLAN_2026-09-10.md b/docs/SCHEDULER_REPAIR_PLAN_2026-09-10.mdnew file mode 100644index 00000000..c7a824f4--- /dev/null+++ b/docs/SCHEDULER_REPAIR_PLAN_2026-09-10.md@@ -0,0 +1,141 @@+# 实时调度与无效 GPU 工作修复计划++日期:2026-09-10。状态:S1 核心账本与 S2 的 DLSS 路径已实现并短测;完整 S3/S4 尚未完成。范围:采集卡实时预览和播放器实时呈现;不改变导出完整性检查,不接入 Depth Anything,也不调整 SR -> NR -> FG 的算法顺序。++## 2026-09-10 实施决定++用户已明确废弃旧 Loop、控制哈希停工及早期 Phase 排队,当前直接按修复任务执行。旧文件保留为历史资料,不更新 CONTROL_HASHES 来制造通过。详情和实际命令见 `SCHEDULER_REPAIR_IMPLEMENTATION_2026-09-10.md`。++- 已完成:独立 session/revision/epoch 账本、取消回调、有效生成/Present 速率、GPU 样本 epoch 过滤、真实采集 callback sequence、DLSS 整对 FG 提交前判断及跳过后 reseed、2X/3X/4X 资源和 PTS 回归。+- S2 首版按整对判断,以最后一个生成时间戳判断该对是否还有价值;不跳过 MFG 中间 index。预测使用同窗口的图开始至 GPU-ready 实测 P95 加 Present P95,扣掉当前已耗时;不相加可能重叠的 GPU 子阶段。8 个有效样本前只有已过期判断,500ms 无有效样本清除旧预测,不会永久禁止恢复尝试。+- FRUC 试接后发生重复重建、有效生成不增长,已撤下产品入口的 deadline skip。保留原来的 FRUC 路径;不得拿诊断 API 测试成功掩盖该回归。+- 续接定位:reset 像素错误常为旧真实帧/上一对插值输出;诊断性 CUDA 全上下文 CPU 同步通过,但多个纯 GPU completion 候选仍失败,已全部撤下。下一步需定位 CUDA/D3D11 资源映射和完成可见性,不能把失败候选接入产品。+- 原生 4K NR + VSR 最高 + DLSS4X 的同源过载回放:150 源帧观察点,旧策略 450 次 FG Evaluate、444 个过期输出、0 个生成呈现;新策略跳过 450 次、0 个过期输出、0 个生成呈现,处理约 27 -> 33 fps。仅证明该回放的无效计算减少,不是实卡延迟、GPU 占用百分比或 NR 推理加速证明。+- S1 的全部 reset 耗时分解、详细逐帧固定环追踪尚未补齐;默认仍使用已有按需逐帧日志,加每秒活动窗口和窗口关闭汇总。命令槽 high-water 为观察值,非逐提交的精确峰值。+- S3 的单线程 GPU 所有者状态机与真实源帧进一步 coalesce 未实施;当前保留 mutex 串行保护的图/呈现双线程及两批上限。既有 Drop 策略保留已完成真实帧,只抑制旧生成帧,不冒充所有旧 epoch 真实帧都被取消。+- S4 不合并未知依赖的 command list,不替换未通过像素验证的 FRUC reset。下一项是 FRUC reset 的同步、时间戳及恢复像素问题;实卡仍由用户验收。++## 结论和目标++当前实现已经限制了帧积压,但不具备完整的 deadline-aware 前沿调度:一部分补帧可能在 GPU 完成后才因过期被放弃呈现。过载时,这会表现为 GPU 利用率高、实际提交帧率低、画面周期性卡顿。++这不是无限队列失控。采集输入是容量 1 的 latest-frame mailbox,实时呈现 worker 的 active + queued batch 总数最多为 2,D3D12 command slot ring 固定为 6。修复目标不是扩大这些上限,而是在提交可选的昂贵工作前判断它是否仍有显示价值,并让每个丢弃点可观测。++Depth Anything 不在本次修复范围。当前产品没有 TensorRT、ONNX 或 DirectML 深度推理;NR 绑定固定 `nrZeroDepth_`,FG 绑定静态 `depthTex_`。因此 FP16/INT8 深度模型不可能是当前高占用或卡顿的来源。++## 已知事实++| 项目 | 当前行为 | 依据 | 影响 |+| --- | --- | --- | --- |+| 采集输入 | 一个待读取帧;新回调覆盖旧帧并计为 dropped | `CaptureCardSource.cpp` | 不会无限堆积,但过载会丢旧源帧 |+| 呈现批次 | active + queue 总数最多 2 | `PresentationWorker.h` | 防止租约/纹理无限占用 |+| GPU 命令 | 固定 6 个 command slot;slot 复用前等待其 fence | `CommandSlotRing.cpp` | 有硬性背压,不能无限向 GPU 发送命令 |+| 生成帧 | 已提交的 generated frame 到 deadline 后会跳过呈现 | `EngineController.cpp` | 存在已计算但无显示价值的 GPU 工作 |+| 原生成本 | 原生 4K NR 约 22.9 ms,最高档 RTX Video SR 约 6.6 ms | `PHYSICAL_CAPTURE_DIAGNOSIS_2026-09-09.md` | 二者已经超过 60 fps 的 16.67 ms 源帧预算;调度优化不能把它变成实时档 |++## 不可破坏的约束++1. 采集保持 mailbox 容量 1;不得为了提高表面 FPS 增加秒级缓冲。+2. 文件播放不得丢源帧、篡改 PTS 或破坏音频主时钟。采集可以淘汰过时源帧,但必须记录来源序列和 reset。+3. 只允许单一 graph/GPU 所有者提交和修改资源状态。不能让 UI、采集回调和呈现线程并发调用 `EnhanceGraph`。+4. source switch、pause/resume、seek、resize、capture drop、scene cut、device lost 和 settings revision 切换必须原子取消旧 epoch;任何被取消 batch 的 lease 只能在消费者 fence 完成后重用。+5. 正常播放、采集和视频导出不得增加 GPU->CPU 像素回读、每 pass CPU fence wait 或无界日志/帧队列。+6. 原生 4K NR 仍保留为非默认的高成本选项。实时档必须继续明确标识内部 NR 尺寸,不能因调度修复改写其含义。++## 实施顺序++### S1:先建立可信的帧流账本++修改 `FrameMetrics`、`EngineController`、诊断日志和专业模式 telemetry。每个计数和时间样本必须绑定 `sessionId`、实际 `settingsRevision`、`epoch`、source sequence、batch id 与 fence value;异步完成的旧 revision 样本不能混进当前窗口。++新增以下单调计数,按 revision/epoch 分窗显示和落盘:++- `captureReceived`、`mailboxOverwritten`、`sourceAccepted`、`sourceSkippedBeforeGraph`;+- `realSubmitted`、`fgCandidate`、`fgSkippedBeforeEval`、`fgEvaluated`、`fgReadyValid`;+- `realPresented`、`generatedPresented`、`generatedExpiredAfterEval`、`cancelledBeforePresent`;+- `commandSlotsInFlight`、`commandSlotHighWater`、`slotReuseWaitCount/Ms`;+- `presentationBatchHighWater`、`gpuReadyWaitMs`、`deadlineWaitMs`、`captureArrivalToPresentReturnMs`;+- reset 总数及每个原因的次数、排空耗时、FRUC worker 重建耗时。++日志改为每秒一条聚合记录,逐帧细节只在显式诊断开关下写入固定容量环形缓冲。错误、HRESULT、SEH、NGX/NVOF 返回值、配置事务和 reset 仍立即记录。专业模式显示“有效生成 fps”和“Present 提交 fps”,不把两者叫真实扫描率或 HDMI 到屏幕延迟。++验收:快速切换 NR 尺寸、SR 后端、FG 倍率、暂停和恢复后,旧样本不会污染新 revision;故意令生成 deadline 过期时,`fgEvaluated`、`generatedExpiredAfterEval` 与 `generatedPresented` 的关系可从单个日志窗口复原。++### S2:在提交前淘汰没有显示价值的可选工作++仅对实时采集启用,文件播放保持完整帧语义。++1. 收到 B 帧后,按该帧的 arrival host timestamp、源 duration、当前 epoch 和已应用配置计算真实/生成帧 deadline。不得把采集卡内部缓冲当未来帧。+2. 使用同 revision 的近期 GPU P95 加上已测 CPU submit/present P95 形成保守预测。窗口无样本或刚切换配置时,标记为 warm-up,不做虚假的乐观估计。+3. 若生成帧在开始 FG Evaluate 前已经过期,或预测完成时间已越过其 deadline,则不提交该帧的 DLSSG/FRUC Evaluate;记录 `fgSkippedBeforeEval`,仍允许当前真实 B 帧按最新可用时机呈现。+4. 如果 B 帧本身已经过时,回到最新 mailbox 样本,不对已经失去预览价值的旧源帧执行 SR/NR/FG。该跳过必须设置 Drop/Discontinuity 并触发同一 epoch reset,不能把旧 motion/depth/history 接给新帧。+5. 已经提交到 GPU 的命令不能撤回。其生成输出若过期继续按当前 lease/fence 回收,但必须计入 `generatedExpiredAfterEval`,不能被合并进“有效生成”。++第一版只在过载时减掉可选 FG 工作,不自动关闭用户手动选择的 NR/SR,也不改变实际使用的质量档。若 NR/SR 本身连续超过输入预算,UI 直接显示“当前组合无法实时处理”,由用户切换到实时档或较低质量。++验收:在故意超过预算的 1080p60 输入上,`generatedExpiredAfterEval` 显著下降,`fgSkippedBeforeEval` 对应增加,纹理租约、epoch、PTS 和 reset 契约保持通过。真实帧不得被“补帧优化”错误地重复或跨 epoch 呈现。++### S3:把实时路径整理为显式状态机++将当前“处理整批 -> 等 GPU 完成 -> 依 PTS 呈现”的隐式循环整理为单一 GPU 所有者下的可推进状态机:++```text+capture callback -> mailbox(1) -> admission/coalesce -> graph submit+ | |+ | fence poll+ v v+ reset boundary <- ready batch -> deadline/present+```++- `admission` 只消费最新源帧,并以现实可用的 slot、lease 和 deadline 决定是否提交。+- `graph submit` 允许在安全的两个 batch 资源窗口内继续推进,不能等待某个将来 generated PTS 时阻塞 source 读取。+- `fence poll` 保持非阻塞;轮询等待由已有 `DeadlineWait` 统一处理,不能重新引入 busy spin 或每个 batch 新建定时器。+- `present` 优先处理将到 deadline 的有效帧;旧 epoch、已取消或已过期生成帧只释放 lease,不补交欠帧。+- 资源上限维持当前两套 real parity slot、最多六个 generated slot和 6 个 command slot。任何新队列必须有容量、high-water、丢弃理由和消费者 fence 生命周期。++不在此步骤把 `PresentationWorker` 的上限简单从 2 提高。那会提高表面吞吐,同时把卡顿改成更长的采集延迟。++验收:模拟 15/30/60 fps 输入、2X/3X/4X、暂停、source switch 和 capture drop,检查 source 序列递增、PTS 合法、没有跨 epoch 显示、没有 `frame-pool still leased`,队列峰值永远不超过设计值。++### S4:减少已证实的提交路径浪费++完成 S1 数据后再决定,不预先假定收益。++- 比较每帧 command-list 数、`slotReuseWaitMs`、graph submit CPU 时间和 GPU queue 区间。若多个紧邻的小提交造成 slot wait,合并同一依赖链中可合并的 copy/compute/FG 记录;不跨 NGX/NVOF 实际要求强行合并。+- 比较默认日志与详细追踪日志。若批量日志降低提交 P95 或 source overwrite,保留批量模式;若收益不可复现,不作为性能结论。+- 检查 settings/resize/rebuild 中的 `drainQueue()` 只发生在真正资源生命周期边界,绝不挪入稳态每帧路径。+- FRUC worker 的轻量 reset 仍是独立实验。必须先用切镜、丢帧、PTS 回退后的连续像素/PTS 对照证明与 fresh worker 一致,才允许替换重建;不通过就保持正确但昂贵的 fresh worker。++验收:每项改动单独做同源 A/B,并记录命令、输入 hash、配置、GPU timestamps、CPU waits、丢帧和输出契约。GPU 阶段本身未缩短时,不得把调度收益写成“NR 加速”。++## 测试矩阵++每次完整调用不超过 300 秒;绝大多数单项 10--60 秒。先离线/回放,再由用户进行实卡验收。++| 场景 | 目标证据 |+| --- | --- |+| 1080p60 回放,NR realtime,VSR low,FG off/2X/4X | 基线吞吐、各阶段时间、slot wait、实际提交和生成有效率 |+| 同源 1080p60,原生 4K NR + VSR high | 明确过载时的 `skip-before-eval` 与 `expired-after-eval`;不要求 60fps |+| 15/30 fps 内容封装在 60 fps 采集传输 | cadence 识别、输入速率与有效处理速率分离、无重复历史污染 |+| seek/pause/resize/source switch/capture drop | epoch/reset、lease、PTS 和取消安全 |+| DLSSG 2X/3X/4X 与 FRUC 2X/3X/4X | 多子帧的有效性、deadline、重复标志和资源上限分别验证 |+| 用户真实采集卡 | callback FPS、mailbox overwrite、有效处理/生成/提交 FPS、画面年龄;真实扫描率和端到端光子延迟仍需外部测量 |++通过标准不是“GPU 占用降低到某个百分比”。必须同时满足:无界队列为零、没有跨 epoch/错误 PTS/早期纹理覆盖、过载时不再大量执行注定过期的 FG、同配置有效呈现节奏没有回退、实时档与原生 4K 档标签仍然诚实。++## 风险与回退++- 预测低估成本会让生成帧仍迟到;预测高估会少生成。第一版保守跳过并把原因公开,之后只能以同配置日志校准。+- 过早丢弃真实 B 帧会损害采集连贯性,因此 S2 先只跳过 FG;真实帧 coalesce 需要单独 gate 和用户实卡观察。+- 线程边界/lease 改动可能引入 resize、切换或 device-lost 崩溃。每一阶段保持旧路径可切换,且先通过现有 reset/resize 短测。+- 调度修复不能抵消原生 4K NR 的物理 GPU 开销。若关键路径持续超过预算,正确结果是提示质量选择,不是伪造更低延迟。++## 交付顺序++1. S1 指标与固定容量诊断缓冲。+2. S2 仅对采集 FG 的 pre-evaluate deadline skip。+3. S3 实时状态机和生命周期回归。+4. S4 经同源 A/B 证实的提交、日志或 FRUC 改动。+5. 用户实卡验收后,再决定默认策略是否需要调整。++每一步完成后更新 `docs/WORKLOG.md`,记录实际 build/test 命令、日志路径、失败证据和未解决风险。任何 GPU/实卡未执行项必须明确标为未执行。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 87f909b6..28c27b9d 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,3 +1,19 @@+# 2026-09-10 旧 Loop 退役与调度修复++用户明确废弃初期 Loop;AGENTS/README/旧 Playbook/ACTIVE_DELIVERY_PLAN/gates README 已标明旧控制哈希、STOP、Phase 队列不再阻塞当前修复,未改 CONTROL_HASHES 自我放行。delivery 删旧 STOP 依赖并显式加载当前 PowerShell 自带 Utility 模块;导出完整性代码和断言未改。++实施 session/revision/epoch 独立帧流账本、异步取消计数、真实/有效生成/Present 分离、GPU/blit epoch 过滤、采集 callback sequence 和 DLSS 采集 FG 提交前整对 deadline admission。跳过后的 FG 先 reset/reseed,不跨缺帧输出。另修关闭 FG(UI 值1)与内部倍率容量(至少2)误比较导致内容节奏设置被拒绝。详细文件、命令、失败及未完成项见 `docs/SCHEDULER_REPAIR_IMPLEMENTATION_2026-09-10.md`。++RTX5070 实际短测:Release exit0;CPU43/worker12 PASS;60->30->60 live23、FRUC保留路径18 PASS;DLSS2/3/4X 每项40真实帧和40 NR、skip8/16/24、Evaluate32/64/96、有效生成29/58/87、debug0;XeSS SDK generated43/debug0;专业UI24移动/24缩放/4弹出选择器 PASS;delivery23 PASS47.64秒(`13a7fe7290f643d29c64f6acc8fe8a32`)。均单次<300秒,没有打开实体采集卡。++同源原生4K NR+VSR最高+DLSS4X过载回放:150源帧观察点,旧策略450次FG计算/444过期/0生成呈现;新策略450提交前跳过/0过期/0生成呈现,处理约27->33fps。只证明该配置无效工作减少,不是NR自身加速或实卡/光子延迟测量。++FRUC试接admission造成重复worker重建、有效生成不增长,已从产品入口撤下该策略并复测通过。FRUC reset-pixels旧失败、完整S3/S4和实卡仍开放。首轮EXE占用链接失败、half-rate设置拒绝、FRUC反例日志均保留。本轮未发布或上传,源码与SDK/runtime隔离;下一任务为FRUC恢复像素/同步/时间戳定位。++续接审查补齐首批命令槽等待与文件播放取消账本,短测新增 worker hash 与独立日志目录。`scheduler-reviewed-build.log` 构建成功;`cpu-reviewed`43、`worker-reviewed`12、`live-half-reviewed`23、`live-fruc-reviewed`18项通过。FRUC reset 错图匹配上一真实帧或上一对插值,诊断性 cuCtxSynchronize+D3D11通知通过6个epoch像素检查,但相对时间、GPU事件、独立fence、参数生命周期和D3D11桥接候选仍失败,全部撤下;生产FRUC未变,不引入逐帧CPU等待。详见实施文档与 `logs/scheduler-repair-20260910/fruc-reset-*`。联合短测第一次23项功能全过但落盘找不到Get-FileHash整体失败,已修模块加载并重跑。下一条任务为FRUC CUDA/D3D11资源交接与完成可见性。++最终 `delivery-reviewed-fixed` 23项全部通过,外部42.78秒;`logs/delivery/ac24ad4a2e1e4169a171fda66e4b7e84/result.json`。当前EXE `429C5600E2A4ABF8D72B83B0F658B3190FE5397FE9A11256946B924CABA560F4`。diff检查通过,Git范围不含SDK/runtime/二进制。仅本地checkpoint,不push或发布;FRUC重置像素、完整S3/S4及实卡仍未完成。+# 2026-09-10 XeSS、AMD 光流与 SR 目标接入用户要求把 AMD DLSS5 作为实验功能接入,并同时完成 XeSS FG、AMD 光流和 2K/4K/8K SR 目标。当前实现新增统一 SR 目标设置、专业模式 2K/4K/8K 选择、Intel XeSS 实验显示补帧 2X,以及 AMD FidelityFX 光流 provider 与半分辨率性能档。XeSS 只作用于预览,不能导出;AMD 光流只替换运动估算,不提供 AMD NR、DLSS SR、NVIDIA FRUC/DLSS 补帧、NVENC 或 AMD AMF。@@ -1388,3 +1404,9 @@ EXE SHA256: 61618AF18F7B985BD4C1FECA06EBE7A07C30EAA01B2CC0682A217E89EAD3C372。FRUC候选bSkipWarp/延后重建/时间归零/首对预热均未通过新增reset后像素检查,生产改动撤回,失败证据和候选diff保留。原FRUC新增`--reset-pixels`同样exit1:API成功而部分重复/偏移,不能称原实现通过更严格验收;重建循环未解决。既有短测通过不覆盖这一失败。本机原生1440p NR额外执行90帧/89NVOF,88条完成GPU timestamp:中位9.74784ms、P95 10.11734ms;Magpie既有同尺寸窗口平均9.718–10.095ms。素材/全链路不完全匹配,只说明纯NR同尺寸未显示倍数差距。用户补充顺序可拖动且实测差异不大,已撤回“顺序是主因”的推断;不变更产品路线。下一任务是同尺寸、同倍率完整链路CPU等待/GPU/呈现节奏诊断。未占实卡、未修改runtime/控制面、未push发布。Phase7仍in_progress。++## 2026-09-10 实时调度修复计划(仅文档)++用户询问截图所述“前沿同步/有限队列与 Depth Anything FP16”是否是当前问题。源码核对确认:采集邮箱为1、presentation active+queued batch上限为2、command ring固定6,因此不存在无界GPU堆帧;但当前缺少完整deadline-aware提交,生成帧可能已经完成GPU计算后才因过期跳过呈现。Depth Anything/TensorRT/ONNX/DirectML目前均未接入;NR使用`nrZeroDepth_`,所以深度推理不是本机高负载根因。++新增 `docs/SCHEDULER_REPAIR_PLAN_2026-09-10.md`:先按revision/epoch建立帧流账本和批量诊断,再仅为实时采集FG加入pre-evaluate deadline skip,随后以有界状态机处理source/graph/fence/present,最后只合入有同源A/B收益的提交、日志或FRUC改动。明确保留mailbox=1、资源lease/fence和文件播放完整性;不把扩大队列、降低质量或原生4K伪装成实时优化。此轮未改产品代码,未运行新的构建/GPU/实卡测试,未更改runtime、控制面、远端或发布;整体Phase7仍in_progress。diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.hindex 4d1a83b9..d3e79587 100644--- a/include/veyra/diagnostics/FrameMetrics.h+++ b/include/veyra/diagnostics/FrameMetrics.h@@ -7,6 +7,33 @@ namespace veyra::diagnostics {enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, FgBatch, Blit, Count };enum class SampleState { NotExecuted, Pending, Measured, Unavailable };struct GpuSample {SampleState state=SampleState::NotExecuted;std::optional<double> milliseconds;uint64_t begin=0,end=0,frequency=0;};+// Live presentation is asynchronous. Keep the identity of the window that+// owns these counters so a finished job from a prior reset cannot be reported+// as work performed by the current settings or temporal epoch.+struct FrameFlowIdentity {+ uint64_t sessionId=0;+ pipeline::FrameIdentity frame;+ uint64_t batchId=0,readyFence=0,consumerFence=0;+ bool sameWindow(uint64_t session,const pipeline::FrameIdentity& candidate)const{+ return sessionId==session&&frame.epoch==candidate.epoch&&frame.settingsRevision==candidate.settingsRevision;+ }+};+struct FrameFlowCounters {+ uint64_t captureReceived=0,mailboxOverwritten=0;+ uint64_t sourceAccepted=0,sourceSkippedBeforeGraph=0,realSubmitted=0;+ uint64_t fgCandidate=0,fgEvaluated=0,fgSkippedBeforeEval=0,fgReadyValid=0,fgInvalid=0,fgWarmup=0;+ uint64_t xessSdkGenerated=0;+ uint64_t realPresented=0,generatedPresented=0,generatedExpiredAfterEval=0,cancelledBeforePresent=0;+ uint64_t historyResets=0,captureDropResets=0,settingsResets=0;+ uint32_t commandSlotsInFlight=0,commandSlotHighWater=0,presentationBatchHighWater=0;+};+struct FrameFlowMetrics {+ FrameFlowIdentity latest;+ FrameFlowCounters counters;+ std::optional<double> slotReuseWaitMs,captureArrivalToPresentReturnMs,gpuReadyWaitMs,deadlineWaitMs;+ uint64_t slotReuseWaitCount=0;+ double validGeneratedFps=0,presentSubmitFps=0;+};struct FrameMetrics {pipeline::FrameIdentity identity;pipeline::ResolutionPlan resolution;@@ -14,5 +41,6 @@ struct FrameMetrics {std::optional<double> decodeCpuMs,submitCpuMs,gpuWaitCpuMs,deadlineWaitCpuMs,presentCpuMs,displayFps;uint64_t sourceFrames=0,validGenerated=0,submitted=0,expired=0;uint32_t queueWatermark=0;+ FrameFlowMetrics flow;};}diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 697c4e2c..78ce8c6d 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -13,8 +13,10 @@namespace veyra::sink { struct RgbaImage; }namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }namespace veyra::engine {+class FrameFlowWindow;struct PlayerOptions { bool nr=true,sr=false,fg=false,realtime=true; uint32_t fgMultiplier=2; EnhancementSettings settings;bool captureReplayForTest=false; // file-backed live scheduler test; never enabled by UI+ bool captureReplayDisableFgAdmissionForTest=false; // controlled scheduler A/B onlyEnhancementSettings snapshot()const{auto s=settings;s.nr=nr;s.sr=sr;s.multiplier=fg?fgMultiplier:1;s.nrPolicy=realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native;return s;}static PlayerOptions from(EnhancementSettings s){PlayerOptions o;o.nr=s.nr;o.sr=s.sr;o.fg=s.multiplier>1;o.fgMultiplier=std::max(2u,s.multiplier);o.realtime=s.nrPolicy==pipeline::NrSizePolicy::Realtime;o.settings=s;return o;}};@@ -61,6 +63,7 @@ private:void status(const std::wstring&,bool failed=false);mutable std::mutex mutex_;PlayerSnapshot snapshot_;+ std::shared_ptr<FrameFlowWindow> activeFlow_;FrameRateWindow processingRate_;PreviewView previewView_;std::wstring savePath_;diff --git a/include/veyra/engine/FrameFlowWindow.h b/include/veyra/engine/FrameFlowWindow.hnew file mode 100644index 00000000..bee19ef1--- /dev/null+++ b/include/veyra/engine/FrameFlowWindow.h@@ -0,0 +1,32 @@+#pragma once+#include "veyra/diagnostics/FrameMetrics.h"+#include "veyra/engine/FrameRateWindow.h"+#include <mutex>++namespace veyra::engine {+// Each asynchronous job retains its own window. Replacing the current window+// never lets an old job increment the new revision/epoch's counters.+class FrameFlowWindow {+ mutable std::mutex mutex_;+ diagnostics::FrameFlowMetrics metrics_;+ FrameRateWindow generated_,presented_;+public:+ FrameFlowWindow(uint64_t session,pipeline::FrameIdentity id,int64_t now){+ metrics_.latest.sessionId=session;metrics_.latest.frame=id;+ generated_.reset(now);presented_.reset(now);+ }+ template<class F> void update(F action){std::lock_guard lock(mutex_);action(metrics_);}+ void ready(unsigned valid,unsigned invalid,int64_t now){+ std::lock_guard lock(mutex_);metrics_.counters.fgReadyValid+=valid;metrics_.counters.fgInvalid+=invalid;+ for(unsigned i=0;i<valid;++i)generated_.complete(now);+ }+ void presented(bool generated,uint64_t fence,int64_t now){+ std::lock_guard lock(mutex_);+ if(generated)++metrics_.counters.generatedPresented;else ++metrics_.counters.realPresented;+ metrics_.latest.consumerFence=fence;presented_.complete(now);+ }+ diagnostics::FrameFlowMetrics snapshot(int64_t now)const{+ std::lock_guard lock(mutex_);auto m=metrics_;m.validGeneratedFps=generated_.rate(now);m.presentSubmitFps=presented_.rate(now);return m;+ }+};+}diff --git a/include/veyra/engine/LiveFgAdmission.h b/include/veyra/engine/LiveFgAdmission.hnew file mode 100644index 00000000..25803673--- /dev/null+++ b/include/veyra/engine/LiveFgAdmission.h@@ -0,0 +1,18 @@+#pragma once+#include <algorithm>+#include <cmath>+#include <cstdint>+#include <optional>++namespace veyra::engine {+// A pair is indivisible: NGX MFG indices and FRUC instances share history.+// Admit while at least its last generated timestamp can still be useful.+inline bool admitLiveFg(int64_t now, int64_t lastDeadline, double elapsedMs,+ std::optional<double> completionP95Ms, double presentP95Ms) {+ constexpr int64_t tolerance = 100000; // Same 10 ms grace as presentation.+ if(now > lastDeadline && now-lastDeadline > tolerance)return false;+ if(!completionP95Ms || !std::isfinite(*completionP95Ms))return true;+ const double remaining=(std::max)(0.0,*completionP95Ms-elapsedMs)+(std::max)(0.0,presentP95Ms);+ return double(lastDeadline-now)/10000.0+10.0 >= remaining;+}+}diff --git a/include/veyra/engine/PresentationWorker.h b/include/veyra/engine/PresentationWorker.hindex de5ebd49..8755a258 100644--- a/include/veyra/engine/PresentationWorker.h+++ b/include/veyra/engine/PresentationWorker.h@@ -22,24 +22,26 @@ public:while(queue_.size()+unsigned(active_)>=2&&!failed_&&!stopping_&&!interrupt_())wake_.wait_for(lock,std::chrono::milliseconds(1));return !failed_&&!stopping_&&!interrupt_();}- bool push(Job job){std::lock_guard lock(mutex_);if(failed_||stopping_||queue_.size()+unsigned(active_)>=2)return false;queue_.push_back({epoch_.load(),std::move(job)});wake_.notify_all();return true;}+ bool push(Job job,std::function<void()> discarded={}){std::lock_guard lock(mutex_);if(failed_||stopping_||queue_.size()+unsigned(active_)>=2)return false;queue_.push_back({epoch_.load(),std::move(job),std::move(discarded)});wake_.notify_all();return true;}+ uint32_t occupancy()const{std::lock_guard lock(mutex_);return uint32_t(queue_.size()+unsigned(active_));}void cancelAndDrain(){- ++epoch_;std::unique_lock lock(mutex_);queue_.clear();wake_.notify_all();wake_.wait(lock,[&]{return !active_;});+ ++epoch_;std::unique_lock lock(mutex_);discardQueued();wake_.notify_all();wake_.wait(lock,[&]{return !active_;});}bool failed()const{std::lock_guard lock(mutex_);return failed_;}private:- struct Entry{uint64_t epoch;Job job;};+ struct Entry{uint64_t epoch;Job job;std::function<void()> discarded;};Cancelled interrupt_;mutable std::mutex mutex_;std::condition_variable wake_;std::deque<Entry> queue_;bool active_=false,failed_=false;std::atomic<bool> stopping_{false};std::atomic<uint64_t> epoch_{0};std::thread thread_;+ void discardQueued(){for(auto& entry:queue_)if(entry.discarded)entry.discarded();queue_.clear();}void run(){for(;;){Entry entry;{- std::unique_lock lock(mutex_);wake_.wait(lock,[&]{return stopping_||!queue_.empty();});if(stopping_)break;+ std::unique_lock lock(mutex_);wake_.wait(lock,[&]{return stopping_||!queue_.empty();});if(stopping_){discardQueued();break;}entry=std::move(queue_.front());queue_.pop_front();active_=true;}bool ok=true;try{ok=entry.job([&,generation=entry.epoch]{return stopping_||epoch_!=generation||interrupt_();});}catch(...){ok=false;}// Drop captured FrameOutputs/leases before advertising a reusable slot.entry.job={};{- std::lock_guard lock(mutex_);active_=false;if(!ok){failed_=true;queue_.clear();}wake_.notify_all();+ std::lock_guard lock(mutex_);active_=false;if(!ok){failed_=true;discardQueued();}wake_.notify_all();}}}};diff --git a/include/veyra/engine/TimingWindow.h b/include/veyra/engine/TimingWindow.hindex e8e7fe13..7396259a 100644--- a/include/veyra/engine/TimingWindow.h+++ b/include/veyra/engine/TimingWindow.h@@ -12,6 +12,7 @@ class TimingWindow {public:void add(double v){if(!std::isfinite(v)||v<0)return;values_.push_back(v);if(values_.size()>1200)values_.pop_front();}void clear(){values_.clear();cached_=0;refresh_={};}+ size_t size()const{return values_.size();}double p95()const{if(values_.empty())return 0;const auto now=std::chrono::steady_clock::now();if(now<refresh_)return cached_;diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 1f931fab..fb898af7 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -18,7 +18,7 @@ public:uint64_t submittedCount() const {return sink_.presentCount();}uint64_t xessGeneratedCount() const {return sink_.xess()?sink_.xess()->generatedCount():0;}bool xessActive() const {return sink_.xess()!=nullptr;}-diagnostics::GpuSample blitTiming(ID3D12Fence* f,uint64_t revision=0){gpuTimer_.collect(f);if(revision&&gpuTimer_.last().identity.settingsRevision!=revision){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}+diagnostics::GpuSample blitTiming(ID3D12Fence* f,uint64_t revision=0,uint64_t epoch=0){gpuTimer_.collect(f);if((revision&&gpuTimer_.last().identity.settingsRevision!=revision)||(epoch&&gpuTimer_.last().identity.epoch!=epoch)){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}private:diagnostics::GpuTimer gpuTimer_;gfx::PresentSink sink_;diff --git a/include/veyra/gfx/CommandSlotRing.h b/include/veyra/gfx/CommandSlotRing.hindex 99eb2d98..273536b9 100644--- a/include/veyra/gfx/CommandSlotRing.h+++ b/include/veyra/gfx/CommandSlotRing.h@@ -84,6 +84,7 @@ public:uint64_t cpuWaitCount() const { return cpuWaitCount_; }double cpuWaitMilliseconds() const { return cpuWaitMilliseconds_; }uint64_t submitCount() const { return submitCount_; }+ uint32_t inFlightCount() const;const std::vector<double>& gpuCommandTimesMs() const { return gpuCommandTimesMs_; }private:diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 18bfe413..a2a32469 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -109,6 +109,8 @@ public:struct FrameOutputs {FrameBatch batch;+ uint32_t fgCandidates=0,fgEvaluated=0,fgSkippedBeforeEval=0;+ bool historyReset=false,fgRecovery=false;bool contentDuplicate=false;int measuredContentRate=0;double ptsMs = 0.0;uint32_t videoSlot = 0; // videoFrame[videoSlot] holds this real frame@@ -126,7 +128,8 @@ public:// does not own the demuxer). `reset` marks the first frame of a new// temporal epoch (open/seek/...): NVOF/FG history is not consumed.// Returns false on hard failure (run verdict must FAIL).- bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, bool retainReferences = true);+ using FgAdmission=std::function<bool(const FrameBatch&)>;+ bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, bool retainReferences = true, const FgAdmission& admitFg = {});// Nonblocking. The scheduler polls at a GPU-ready/deadline boundary; no// full image readback and no waits inside the graph's individual passes.bool resolveGeneration(FrameOutputs& out);@@ -297,6 +300,7 @@ private:std::vector<uint8_t> previousLuma_;double prevPtsMs_ = -1.0;bool prevValid_ = false;+ bool fgHistorySkipped_ = false;Metrics metrics_{};std::string mvecSource_ = "nvof";};diff --git a/scripts/acceptance/scheduler-short-test.ps1 b/scripts/acceptance/scheduler-short-test.ps1new file mode 100644index 00000000..01ed9a77--- /dev/null+++ b/scripts/acceptance/scheduler-short-test.ps1@@ -0,0 +1,28 @@+param(+ [Parameter(Mandatory=$true)][ValidatePattern('^[A-Za-z0-9][A-Za-z0-9_-]*$')][string]$Name,+ [Parameter(Mandatory=$true)][string]$Exe,+ [string[]]$TestArgs=@()+)+$ErrorActionPreference='Stop'+$dir=Join-Path (Get-Location) 'logs/scheduler-repair-20260910'+[IO.Directory]::CreateDirectory($dir)|Out-Null+$runDir=Join-Path $dir $Name+[IO.Directory]::CreateDirectory($runDir)|Out-Null+$watch=[Diagnostics.Stopwatch]::StartNew()+$start=@{FilePath=(Resolve-Path $Exe).Path;PassThru=$true;WindowStyle='Hidden';RedirectStandardOutput="$dir/$Name.stdout.log";RedirectStandardError="$dir/$Name.stderr.log"}+if($TestArgs.Count){$start.ArgumentList=@($TestArgs|ForEach-Object{'"'+$_.Replace('"','\"')+'"'})}+$previousLog=$env:VEYRA_LOG_FILE+try {+ $env:VEYRA_LOG_FILE=Join-Path $runDir 'runtime.log'+ $process=Start-Process @start+} finally { $env:VEYRA_LOG_FILE=$previousLog }+$handle=$process.Handle+if(-not $process.WaitForExit(290000)){Stop-Process -Id $process.Id -Force;throw "$Name exceeded 290 seconds"}+$inputs=@($TestArgs|Where-Object {$_ -match '\.(mp4|nv12)$' -and (Test-Path -LiteralPath $_ -PathType Leaf)}|ForEach-Object {@{path=$_;sha256=(Get-FileHash -LiteralPath $_ -Algorithm SHA256).Hash}})+$worker=Join-Path (Split-Path $start.FilePath) 'veyra_fruc_worker.exe'+$workerHash=if(Test-Path -LiteralPath $worker -PathType Leaf){(Get-FileHash -LiteralPath $worker -Algorithm SHA256).Hash}else{$null}+$result=[ordered]@{test=$Name;exitCode=$process.ExitCode;seconds=$watch.Elapsed.TotalSeconds;exeHash=(Get-FileHash $Exe -Algorithm SHA256).Hash;workerHash=$workerHash;args=$TestArgs;inputs=$inputs}+$result|ConvertTo-Json|Set-Content "$dir/$Name.result.json"+Get-Content "$dir/$Name.stdout.log" -Tail 28+Write-Output ($result|ConvertTo-Json -Compress)+exit $process.ExitCodediff --git a/scripts/gates/README.md b/scripts/gates/README.mdindex 6ca64925..1d66db23 100644--- a/scripts/gates/README.md+++ b/scripts/gates/README.md@@ -1,5 +1,7 @@# Phase gate contract+> 2026-09-10:旧 Loop/控制哈希/Phase 队列已由用户废弃,下文是历史合同。当前直接执行构建、相关回归和必要的 `delivery.ps1`,不经 `loop-gate.ps1`,不受旧 STOP 或 CONTROL_HASHES 约束。单次测试最多 300 秒;运行时身份和源码隔离校验继续生效。+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `../docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。每个 scripts/gates/phaseN.ps1 都必须:diff --git a/scripts/gates/delivery.ps1 b/scripts/gates/delivery.ps1index 10a29fd5..86846fb8 100644--- a/scripts/gates/delivery.ps1+++ b/scripts/gates/delivery.ps1@@ -4,6 +4,9 @@ param([Parameter(Mandatory=$true)][string]$Root,[switch]$VisiblePlayer)# Native-4K realtime60 is NOT asserted: user selected an explicit 1080 working realtime profile.# Real capture acceptance and proprietary distribution are separate, never synthetic PASS.$ErrorActionPreference='Stop'+# A PowerShell 7 parent can pass module paths that exclude Windows PowerShell's+# own Utility module. Resolve hashing/JSON cmdlets from the executing host.+Import-Module (Join-Path $PSHOME 'Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1') -Force$Root=(Resolve-Path -LiteralPath $Root).PathSet-Location -LiteralPath $Root$timer=[Diagnostics.Stopwatch]::StartNew()@@ -25,7 +28,6 @@ function Run([string]$Name,[string]$Exe,[string[]]$Argv,[int]$Limit=30,[int]$Exp$exitCode=$p.ExitCode;Check "$Name-exit" ($null -ne $exitCode -and $exitCode -eq $ExpectedExit) "exit=$exitCode expected=$ExpectedExit"}try{- if(Test-Path -LiteralPath 'loop/STOP'){throw 'User STOP exists'}$ffprobe=(Get-Command ffprobe -ErrorAction Stop).Source$clip1080=(Resolve-Path 'loop/local/fixed_clips/test_av_1080p.mp4').Path$clip4k=(Resolve-Path 'loop/local/fixed_clips/test_av_4k.mp4').Pathdiff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex da0770b8..85079492 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -7,6 +7,8 @@#include "veyra/engine/PresentationWorker.h"#include "veyra/engine/LivePresentationResetPolicy.h"#include "veyra/engine/TimingWindow.h"+#include "veyra/engine/FrameFlowWindow.h"+#include "veyra/engine/LiveFgAdmission.h"#include "veyra/engine/CaptureHalfRate.h"#include "veyra/source/MediaFileSource.h"#include "veyra/source/CaptureCardSource.h"@@ -32,6 +34,10 @@ namespace {double elapsedMs(Clock::time_point from){return std::chrono::duration<double,std::milli>(Clock::now()-from).count();}int64_t monotonic100ns(){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;}struct OnExit {std::function<void()> action;~OnExit(){action();}};+void logFrameFlow(const diagnostics::FrameFlowMetrics& m,const char* state){+ const auto& c=m.counters;const auto& id=m.latest;+ veyra::log::info("frame-flow",std::format("state={} session={} revision={} epoch={} source={} batch={} readyFence={} consumerFence={} captureReceived={} mailboxOverwritten={} sourceAccepted={} sourceSkippedBeforeGraph={} realSubmitted={} fgCandidate={} fgSkippedBeforeEval={} fgEvaluated={} fgWarmup={} fgReadyValid={} fgInvalid={} realPresented={} generatedPresented={} generatedExpiredAfterEval={} cancelledBeforePresent={} commandSlots={} commandHighWater={} presentationHighWater={} slotWaitCount={} slotWaitMs={:.3f} generatedFps={:.2f} presentSubmitFps={:.2f}",state,id.sessionId,id.frame.settingsRevision,id.frame.epoch,id.frame.sourceFrameId,id.batchId,id.readyFence,id.consumerFence,c.captureReceived,c.mailboxOverwritten,c.sourceAccepted,c.sourceSkippedBeforeGraph,c.realSubmitted,c.fgCandidate,c.fgSkippedBeforeEval,c.fgEvaluated,c.fgWarmup,c.fgReadyValid,c.fgInvalid,c.realPresented,c.generatedPresented,c.generatedExpiredAfterEval,c.cancelledBeforePresent,c.commandSlotsInFlight,c.commandSlotHighWater,c.presentationBatchHighWater,m.slotReuseWaitCount,m.slotReuseWaitMs.value_or(0),m.validGeneratedFps,m.presentSubmitFps));+}}EngineController::EngineController(){worker_=std::thread(&EngineController::dispatch,this);}EngineController::~EngineController(){ {std::lock_guard lock(mutex_);shutdown_=true;pending_={};stop_=true;}wake_.notify_one();if(worker_.joinable())worker_.join(); }@@ -45,8 +51,10 @@ void EngineController::post(std::function<void()> task){ {std::lock_guard lock(mbool EngineController::idle()const{std::lock_guard lock(mutex_);return !busy_&&!pending_;}void EngineController::open(HWND video,const std::wstring& path,PlayerOptions opts){const bool captureReplay=opts.captureReplayForTest;- {std::lock_guard lock(mutex_);snapshot_={};processingRate_.reset(monotonic100ns());previewView_={};snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}+ const bool disableAdmission=opts.captureReplayDisableFgAdmissionForTest;+ {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();processingRate_.reset(monotonic100ns());previewView_={};snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}opts.captureReplayForTest=captureReplay;+ opts.captureReplayDisableFgAdmissionForTest=disableAdmission;post([this,video,path,opts]{paused_=false;seekSeconds_=-1;run(video,path,opts);});}void EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};snapshot_.transport=busy_?TransportState::Stopping:TransportState::Empty;}@@ -60,7 +68,7 @@ void EngineController::saveFrame(const std::wstring& path){std::lock_guard lock(void EngineController::startExport(const std::wstring& input,const std::wstring& output,PlayerOptions opts,bool hevc){const auto frozen=opts.snapshot();post([this,input,output,frozen,hevc]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);bool ok=exportVideo(input,output,PlayerOptions::from(frozen),hevc,stop_,[this](double p,const std::wstring& s){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.position=p;snapshot_.duration=1;snapshot_.running=true;});{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.failed=!ok&&!stop_;}CoUninitialize();});}-PlayerSnapshot EngineController::snapshot()const{std::lock_guard lock(mutex_);auto copy=snapshot_;copy.volume=volume_;copy.muted=muted_;copy.fps=copy.running&&!copy.image&©.transport==TransportState::Playing?processingRate_.rate(monotonic100ns()):0;return copy;}+PlayerSnapshot EngineController::snapshot()const{std::lock_guard lock(mutex_);auto copy=snapshot_;copy.volume=volume_;copy.muted=muted_;const bool playing=copy.running&&!copy.image&©.transport==TransportState::Playing;copy.fps=playing?processingRate_.rate(monotonic100ns()):0;if(activeFlow_){copy.metrics.flow=activeFlow_->snapshot(monotonic100ns());if(!playing)copy.metrics.flow.validGeneratedFps=copy.metrics.flow.presentSubmitFps=0;copy.submissionFps=copy.metrics.flow.presentSubmitFps;}return copy;}void EngineController::status(const std::wstring& s,bool failed){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.failed=failed;if(failed)snapshot_.transport=TransportState::Failed;}void EngineController::run(HWND window,std::wstring path,PlayerOptions options){CoInitializeEx(nullptr,COINIT_MULTITHREADED);@@ -70,6 +78,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){pipeline::EnhanceGraph graph(ctx,ring);AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;source::CaptureCardSource captureSource;const bool physicalCapture=path.rfind(L"capture:",0)==0;const bool isCapture=physicalCapture||options.captureReplayForTest;+ const bool useLiveFgAdmission=!(options.captureReplayForTest&&options.captureReplayDisableFgAdmissionForTest);source::IFrameSource* activeSource=physicalCapture?static_cast<source::IFrameSource*>(&captureSource):&source;if(options.captureReplayForTest)veyra::log::info("capture-test","file replay exercises live scheduler; no physical capture device or latency measurement");bool audioStarted=false;bool failed=false;@@ -126,21 +135,28 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){PresentationScheduler liveTimeline;uint64_t submitted=0,expired=0;std::deque<int64_t> submissionTimes;DeadlineWait deadlineWait;CaptureHalfRate captureSampler;- auto completedProcessing=[&](uint64_t revision){std::lock_guard lock(mutex_);if(snapshot_.applied.revision==revision){processingRate_.complete(monotonic100ns());++snapshot_.processedCompleted;}};+ auto completedProcessing=[&](pipeline::FrameIdentity id){std::lock_guard lock(mutex_);if(snapshot_.applied.revision==id.settingsRevision&&activeFlow_&&activeFlow_->snapshot(monotonic100ns()).latest.sameWindow(snapshot_.sessionId,id)){processingRate_.complete(monotonic100ns());++snapshot_.processedCompleted;}};auto host100ns=[](){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;};// Only the live source may discard stale input. File playback keeps// its audio-clock scheduler and lossless source ordering.std::mutex gpuMutex,liveStatsMutex;- struct LiveStats {uint64_t submitted=0,expired=0;double waitMs=0,presentMs=0,readyMs=0,ageMs=0,fps=0,ageP95=0,waitP95=0,presentP95=0,readyP95=0;diagnostics::GpuSample blit;};+ struct LiveStats {pipeline::FrameIdentity identity;uint64_t submitted=0,expired=0;double waitMs=0,presentMs=0,readyMs=0,ageMs=0,fps=0,ageP95=0,waitP95=0,presentP95=0,readyP95=0;diagnostics::GpuSample blit;};LiveStats liveStats;std::deque<int64_t> liveSubmissions;- TimingWindow liveAges,liveWaits,livePresent,liveReady;+ TimingWindow liveAges,liveWaits,livePresent,liveReady,liveCompletion;+ int64_t lastFgCompletion=0;std::atomic<uint64_t> historyResets=0,presentationDrains=0,presentationCompletedReal=0,presentationSkippedGenerated=0,presentationCancelledJobs=0;std::atomic<uint64_t> presentationGeneration{0};std::unique_ptr<PresentationWorker> liveWorker;if(isCapture)liveWorker=std::make_unique<PresentationWorker>([&]{return stop_.load()||paused_.load();});auto drainLivePresentation=[&]{if(liveWorker){++presentationDrains;liveWorker->cancelAndDrain();}};- uint64_t metricsRevision=options.settings.revision,statsSourceBase=0,statsGeneratedBase=0;+ uint64_t metricsRevision=options.settings.revision,metricsEpoch=0,statsSourceBase=0;uint64_t slotWaitBase=ring.cpuWaitCount(),submitBase=ring.submitCount();double slotWaitMsBase=ring.cpuWaitMilliseconds();+ const uint64_t runSessionId=[&]{std::lock_guard lock(mutex_);return snapshot_.sessionId;}();+ std::shared_ptr<FrameFlowWindow> frameFlow;+ source::CaptureMetrics captureFlowBase{},captureFlowLast{};+ uint64_t rateSkippedBase=0;+ // The worker captures these locals; join before their destruction.+ OnExit stopPresentation{[&]{liveWorker.reset();std::lock_guard lock(mutex_);if(snapshot_.sessionId==runSessionId){if(frameFlow)snapshot_.metrics.flow=frameFlow->snapshot(host100ns());activeFlow_.reset();}}};while(!stop_){if(liveWorker&&liveWorker->failed()){status(L"采集画面呈现失败,请查看诊断",true);break;}const float gain=muted_?0.0f:volume_.load();audio.setGain(gain);@@ -227,6 +243,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(pts+0.1<discardBefore)continue;if(frame!=cachedFrame){av_frame_free(&cachedFrame);cachedFrame=av_frame_clone(frame);cachedPacket=pkt;}const auto processStart=Clock::now();+ const auto captureArrival=pkt.arrivalHost100ns?pkt.arrivalHost100ns:host100ns();const bool historyReset=reset||pipeline::breaksHistory(pkt.flags);if(historyReset){++historyResets;++presentationGeneration;}// A mailbox Drop must reset SR/NR/flow/FG history, but draining@@ -234,7 +251,23 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(liveWorker&&presentationDrainRequired(reset,pkt.flags))drainLivePresentation();const bool injectedReject=transaction&&!options.nr&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_DISABLE",nullptr,0)>0;if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");- bool processed=false;{std::lock_guard gpuLock(gpuMutex);processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,comparisonMode_!=0);}+ pipeline::EnhanceGraph::FgAdmission admitFg;+ // FRUC's current recovery restarts its worker. A deadline skip+ // would repeatedly trigger that expensive restart and starve FG.+ // Keep its existing path until lightweight reseeding is verified.+ if(isCapture&&!rereadCached&&useLiveFgAdmission&&options.settings.frameGenerationBackend==FrameGenerationBackend::Dlss){+ std::optional<double> completionP95;double presentP95=0;uint64_t predictionEpoch=0;+ {std::lock_guard statsLock(liveStatsMutex);if(host100ns()-lastFgCompletion>5000000)liveCompletion.clear();if(!historyReset&&liveStats.identity.settingsRevision==options.settings.revision&&liveCompletion.size()>=8){completionP95=liveCompletion.p95();presentP95=livePresent.p95();predictionEpoch=liveStats.identity.epoch;}}+ admitFg=[&,completionP95,presentP95,predictionEpoch](const pipeline::FrameBatch& batch){+ if(!liveTimeline.anchored(batch.identity.epoch))liveTimeline.reset(batch.identity.epoch,batch.b100ns,captureArrival,liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps));+ const auto interval=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);+ const auto a=(historyReset||batch.b100ns<=batch.a100ns||batch.b100ns-batch.a100ns>10000000)?batch.b100ns-interval:batch.a100ns;+ const auto lastGenerated=pipeline::FrameBatch::interpolate(a,batch.b100ns,options.fgMultiplier-1,options.fgMultiplier);+ return admitLiveFg(host100ns(),liveTimeline.deadline(lastGenerated),elapsedMs(processStart),predictionEpoch==batch.identity.epoch?completionP95:std::nullopt,presentP95);+ };+ }+ uint64_t processWaitBase=0,processSubmitBase=0;double processWaitMsBase=0;+ bool processed=false;{std::lock_guard gpuLock(gpuMutex);processWaitBase=ring.cpuWaitCount();processWaitMsBase=ring.cpuWaitMilliseconds();processSubmitBase=ring.submitCount();processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,comparisonMode_!=0,admitFg);}if(!processed){if(transaction){ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);@@ -247,20 +280,25 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(transaction){std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_.revision!=options.settings.revision;snapshot_.status=std::format(L"输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)");veyra::log::info("settings",std::format("Applied revision={} sourcePtsMs={} fgBackend={} flowBackend={} multiplier={} (source kept open)",options.settings.revision,pts,frameGenerationBackendName(options.settings.frameGenerationBackend),opticalFlowBackendName(options.settings.opticalFlowBackend),options.snapshot().multiplier));}if(veyra::log::verboseFrameLogs())veyra::log::info("source-identity",std::format("source={} totalRead={} graphProcessed={} cached={} revision={} nvofStandalone={}",pkt.sequence,sourceFrames,frames+1,rereadCached,options.settings.revision,gd.enableNvofStandalone));reset=false;hasOutput=true;- const auto processDone=Clock::now();processTimes.add(elapsedMs(processStart));- if(metricsRevision!=options.settings.revision){- metricsRevision=options.settings.revision;statsStart=Clock::now();statsSourceBase=sourceFrames;statsGeneratedBase=graph.metrics().fgGeneratedFrames;+ const auto processDone=Clock::now();+ if(!frameFlow||metricsRevision!=options.settings.revision||metricsEpoch!=out.batch.identity.epoch){+ const bool settingsChanged=metricsRevision!=options.settings.revision;+ metricsRevision=options.settings.revision;metricsEpoch=out.batch.identity.epoch;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;- slotWaitBase=ring.cpuWaitCount();slotWaitMsBase=ring.cpuWaitMilliseconds();submitBase=ring.submitCount();- if(liveWorker){std::lock_guard statsLock(liveStatsMutex);liveStats={};liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();liveReady.clear();historyResets=0;presentationDrains=0;presentationCompletedReal=0;presentationSkippedGenerated=0;presentationCancelledJobs=0;}- veyra::log::info("metrics",std::format("reset appliedRevision={} sourceBase={}",metricsRevision,statsSourceBase));+ if(liveWorker){std::lock_guard statsLock(liveStatsMutex);liveStats={};liveStats.identity=out.batch.identity;liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();liveReady.clear();liveCompletion.clear();}+ frameFlow=std::shared_ptr<FrameFlowWindow>(new FrameFlowWindow(runSessionId,out.batch.identity,host100ns()),[](FrameFlowWindow* window){logFrameFlow(window->snapshot(monotonic100ns()),"closed");delete window;});+ frameFlow->update([&](auto& m){m.counters.historyResets=out.historyReset;m.counters.settingsResets=settingsChanged;m.counters.captureDropResets=pipeline::hasFrameFlag(pkt.flags,pipeline::FrameFlagBits::Drop);});+ captureFlowBase=captureFlowLast;+ {std::lock_guard lock(mutex_);rateSkippedBase=snapshot_.captureRateSkipped;activeFlow_=frameFlow;}+ veyra::log::info("metrics",std::format("reset session={} appliedRevision={} epoch={} sourceBase={}",runSessionId,metricsRevision,metricsEpoch,statsSourceBase));}+ processTimes.add(elapsedMs(processStart));+ frameFlow->update([&](auto& m){m.latest.frame=out.batch.identity;m.latest.batchId=out.batch.batchId;m.latest.readyFence=std::max(out.videoFenceValue,out.genFenceValue);m.counters.sourceAccepted+=!rereadCached;++m.counters.realSubmitted;m.counters.fgCandidate+=out.fgCandidates;m.counters.fgEvaluated+=out.fgEvaluated;m.counters.fgSkippedBeforeEval+=out.fgSkippedBeforeEval;if(!out.hasGenerated)m.counters.fgWarmup+=out.fgEvaluated;});if(transaction||frames==0){std::lock_guard lock(mutex_);processingRate_.reset(monotonic100ns());snapshot_.captureHalfRate=halfRate;veyra::log::info("capture-rate",std::format("revision={} requested60To30={} active={} transportFps={} originalPtsPreserved=true",options.settings.revision,options.settings.content==ContentRate::Capture60To30,halfRate,isCapture?activeSource->info().averageFps:0));}- const auto captureArrival=pkt.arrivalHost100ns?pkt.arrivalHost100ns:- std::chrono::duration_cast<std::chrono::nanoseconds>(processStart.time_since_epoch()).count()/100;if(isCapture&&!rereadCached&&!liveTimeline.anchored(out.batch.identity.epoch)){const auto duration100ns=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg));@@ -273,37 +311,49 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(liveWorker){const auto timeline=liveTimeline;const uint64_t jobGeneration=presentationGeneration.load();- if(!liveWorker->push([&,batch=out,timeline,captureArrival,jobGeneration,rereadCached](const PresentationWorker::Cancelled& cancelled)mutable{+ if(!liveWorker->push([&,batch=out,timeline,captureArrival,jobGeneration,rereadCached,flow=frameFlow,processStart](const PresentationWorker::Cancelled& cancelled)mutable{+ unsigned handled=0;+ OnExit accountCancelled{[&]{flow->update([&](auto& m){m.counters.cancelledBeforePresent+=batch.batch.count-handled;});}};auto& wait=deadlineWait;const auto readyStart=Clock::now();for(;;){if(cancelled()){++presentationCancelledJobs;return true;}bool ready;{std::lock_guard gpuLock(gpuMutex);ready=graph.resolveGeneration(batch);}if(ready)break;if(elapsedMs(readyStart)>2000){veyra::log::error("capture-present","GPU ready timeout");return false;}wait.slice(.2);}- if(!rereadCached)completedProcessing(batch.batch.identity.settingsRevision);+ if(!rereadCached)completedProcessing(batch.batch.identity);+ unsigned valid=0,invalid=0;for(unsigned i=0;i<batch.batch.count;++i)if(batch.batch.frames[i].kind==pipeline::FrameKind::Generated){if(batch.batch.frames[i].validity==pipeline::GenerationValidity::Valid)++valid;else ++invalid;}+ flow->ready(valid,invalid,host100ns());+ {std::lock_guard statsLock(liveStatsMutex);if(liveStats.identity.epoch==batch.batch.identity.epoch&&liveStats.identity.settingsRevision==batch.batch.identity.settingsRevision&&batch.fgEvaluated&&!batch.historyReset&&!batch.fgRecovery){liveCompletion.add(elapsedMs(processStart));lastFgCompletion=host100ns();}}const double readyMs=elapsedMs(readyStart);double waitMs=0,presentMs=0,ageMs=0;uint64_t count=0,dropped=0;diagnostics::GpuSample blit;- OnExit publish{[&]{if(!count&&!dropped)return;std::lock_guard statsLock(liveStatsMutex);liveStats.submitted+=count;liveStats.expired+=dropped;+ OnExit publish{[&]{flow->update([&](auto& m){m.gpuReadyWaitMs=readyMs;m.deadlineWaitMs=waitMs;if(count)m.captureArrivalToPresentReturnMs=ageMs;m.counters.generatedExpiredAfterEval+=dropped;});if(!count&&!dropped)return;std::lock_guard statsLock(liveStatsMutex);if(liveStats.identity.epoch!=batch.batch.identity.epoch||liveStats.identity.settingsRevision!=batch.batch.identity.settingsRevision)return;liveStats.submitted+=count;liveStats.expired+=dropped;// Accumulate at completion, not at producer polling: two// completions between reads must not lose a timing sample.if(count){liveStats.waitMs=waitMs;liveStats.presentMs=presentMs;liveStats.readyMs=readyMs;liveStats.ageMs=ageMs;liveStats.blit=blit;liveAges.add(ageMs);liveWaits.add(waitMs);livePresent.add(presentMs);liveReady.add(readyMs);liveStats.ageP95=liveAges.p95();liveStats.waitP95=liveWaits.p95();liveStats.presentP95=livePresent.p95();liveStats.readyP95=liveReady.p95();}liveStats.fps=liveSubmissions.size()>1?double(liveSubmissions.size()-1)*1e7/(liveSubmissions.back()-liveSubmissions.front()):0;}};for(unsigned i=0;i<batch.batch.count;++i){auto& item=batch.batch.frames[i];const bool generated=item.kind==pipeline::FrameKind::Generated;- if(generated&&(item.validity!=pipeline::GenerationValidity::Valid||comparisonMode_!=0))continue;+ if(generated&&item.validity!=pipeline::GenerationValidity::Valid){++handled;continue;}+ if(generated&&comparisonMode_!=0)continue;if(generated&&!generatedPresentationCurrent(jobGeneration,presentationGeneration.load())){++presentationSkippedGenerated;continue;}- if(generated&&timeline.expired(item.pts100ns,host100ns(),100000)){++dropped;continue;}+ if(generated&&timeline.expired(item.pts100ns,host100ns(),100000)){++dropped;++handled;continue;}const auto waitStart=Clock::now();while(!cancelled()&&host100ns()<timeline.deadline(item.pts100ns))wait.slice();waitMs+=elapsedMs(waitStart);if(cancelled()){++presentationCancelledJobs;return true;}if(generated&&!generatedPresentationCurrent(jobGeneration,presentationGeneration.load())){++presentationSkippedGenerated;continue;}- const auto begin=Clock::now();bool didPresent=false;- {std::lock_guard gpuLock(gpuMutex);if(cancelled()){++presentationCancelledJobs;return true;}const auto before=presenter.submittedCount();+ const auto begin=Clock::now();bool didPresent=false;uint64_t xessGenerated=0;+ {std::lock_guard gpuLock(gpuMutex);if(cancelled()){++presentationCancelledJobs;return true;}if(generated&&timeline.expired(item.pts100ns,host100ns(),100000)){++dropped;++handled;continue;}const auto before=presenter.submittedCount();+ const auto beforeXess=presenter.xessGeneratedCount();if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView()))return false;+ xessGenerated=presenter.xessGeneratedCount()-beforeXess;item.lease->consumerFence=ring.lastSignaledValue();didPresent=presenter.submittedCount()>before;blit=presenter.blitTiming(ctx.fence());}presentMs+=elapsedMs(begin);- if(didPresent){++count;if(!generated)++presentationCompletedReal;ageMs=double(host100ns()-captureArrival)/10000;std::lock_guard statsLock(liveStatsMutex);const auto time=host100ns();liveSubmissions.push_back(time);while(liveSubmissions.size()>1&&time-liveSubmissions.front()>10000000)liveSubmissions.pop_front();}+ if(xessGenerated)flow->update([&](auto& m){m.counters.xessSdkGenerated+=xessGenerated;});+ if(didPresent){++handled;++count;flow->presented(generated,item.lease->consumerFence,host100ns());if(!generated)++presentationCompletedReal;ageMs=double(host100ns()-captureArrival)/10000;std::lock_guard statsLock(liveStatsMutex);if(liveStats.identity.epoch==batch.batch.identity.epoch&&liveStats.identity.settingsRevision==batch.batch.identity.settingsRevision){const auto time=host100ns();liveSubmissions.push_back(time);while(liveSubmissions.size()>1&&time-liveSubmissions.front()>10000000)liveSubmissions.pop_front();}}}return true;- })){status(L"采集呈现队列失败",true);break;}+ },[flow=frameFlow,count=out.batch.count]{flow->update([&](auto& m){m.counters.cancelledBeforePresent+=count;});})){status(L"采集呈现队列失败",true);break;}+ const auto occupancy=liveWorker->occupancy();frameFlow->update([&](auto& m){m.counters.presentationBatchHighWater=std::max(m.counters.presentationBatchHighWater,occupancy);});LiveStats completed;{std::lock_guard statsLock(liveStatsMutex);completed=liveStats;}frameWaitMs=completed.waitMs;framePresentMs=completed.presentMs;gpuWaitMs=completed.readyMs;submitted=completed.submitted;expired=completed.expired;}else{+ unsigned handled=0;+ OnExit accountCancelled{[&]{frameFlow->update([&](auto& m){m.counters.cancelledBeforePresent+=out.batch.count-handled;});}};const auto readyStart=Clock::now();while(!stop_&&!paused_&&seekSeconds_<0&&!graph.resolveGeneration(out)){if(elapsedMs(readyStart)>2000){status(L"补帧 GPU 就绪超时",true);stop_=true;break;}@@ -311,21 +361,26 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){}if(stop_)break;if(paused_||seekSeconds_>=0){reset=true;if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} cancelled before submit (pause/seek)",out.batch.batchId));continue;}- if(!rereadCached&&!isImage)completedProcessing(out.batch.identity.settingsRevision);+ unsigned valid=0,invalid=0;for(unsigned i=0;i<out.batch.count;++i)if(out.batch.frames[i].kind==pipeline::FrameKind::Generated){if(out.batch.frames[i].validity==pipeline::GenerationValidity::Valid)++valid;else ++invalid;}+ frameFlow->ready(valid,invalid,host100ns());+ if(!rereadCached&&!isImage)completedProcessing(out.batch.identity);gpuWaitMs=elapsedMs(readyStart);gpuReadyTimes.add(gpuWaitMs);bool interrupted=false,presentFailed=false;for(uint32_t i=0;i<out.batch.count;++i){auto& item=out.batch.frames[i];const bool generated=item.kind==pipeline::FrameKind::Generated;- if(generated&&(item.validity!=pipeline::GenerationValidity::Valid||comparisonMode_!=0))continue;- if(isCapture&&generated&&liveTimeline.expired(item.pts100ns,host100ns(),100000)){++expired;continue;}+ if(generated&&item.validity!=pipeline::GenerationValidity::Valid){++handled;continue;}+ if(generated&&comparisonMode_!=0)continue;+ if(isCapture&&generated&&liveTimeline.expired(item.pts100ns,host100ns(),100000)){++expired;++handled;frameFlow->update([](auto& m){++m.counters.generatedExpiredAfterEval;});continue;}const auto waitStart=Clock::now();while(!stop_&&!paused_&&seekSeconds_<0&&(isCapture?host100ns()<liveTimeline.deadline(item.pts100ns):nowMs()+0.25<item.pts100ns/10000.0))deadlineWait.slice();frameWaitMs+=elapsedMs(waitStart);if(stop_||paused_||seekSeconds_>=0){interrupted=true;break;}- const auto begin=Clock::now();const auto before=presenter.submittedCount();+ const auto begin=Clock::now();const auto before=presenter.submittedCount();const auto beforeXess=presenter.xessGeneratedCount();if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView())){presentFailed=true;break;}framePresentMs+=elapsedMs(begin);+ frameFlow->update([&](auto& m){m.counters.xessSdkGenerated+=presenter.xessGeneratedCount()-beforeXess;});item.lease->consumerFence=ring.lastSignaledValue();+ if(presenter.submittedCount()>before){++handled;frameFlow->presented(generated,item.lease->consumerFence,host100ns());}if(presenter.submittedCount()>before){++submitted;const auto time=host100ns();submissionTimes.push_back(time);while(submissionTimes.size()>1&&time-submissionTimes.front()>10000000)submissionTimes.pop_front();if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",out.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));}}if(presentFailed){status(L"画面提交失败",true);break;}@@ -336,16 +391,21 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){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());const auto captureStats=isCapture?captureSource.metrics():source::CaptureMetrics{};- diagnostics::FrameMetrics measured;pipeline::EnhanceGraph::Metrics graphStats;uint64_t slotWaitCount=0,commandSubmits=0;double slotWaitMilliseconds=0;- {std::lock_guard gpuLock(gpuMutex);measured=graph.gpuMetrics();graphStats=graph.metrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence(),options.settings.revision);slotWaitCount=ring.cpuWaitCount()-slotWaitBase;slotWaitMilliseconds=ring.cpuWaitMilliseconds()-slotWaitMsBase;commandSubmits=ring.submitCount()-submitBase;}- if(measured.identity.settingsRevision!=options.settings.revision){measured={};measured.identity=out.batch.identity;for(auto& sample:measured.gpu)sample.state=diagnostics::SampleState::Pending;}+ diagnostics::FrameMetrics measured;pipeline::EnhanceGraph::Metrics graphStats;uint64_t slotWaitCount=0,commandSubmits=0;double slotWaitMilliseconds=0;uint32_t slotsInFlight=0;+ {std::lock_guard gpuLock(gpuMutex);measured=graph.gpuMetrics();graphStats=graph.metrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence(),options.settings.revision,out.batch.identity.epoch);slotWaitCount=ring.cpuWaitCount()-slotWaitBase;slotWaitMilliseconds=ring.cpuWaitMilliseconds()-slotWaitMsBase;commandSubmits=ring.submitCount()-submitBase;slotsInFlight=ring.inFlightCount();}+ if(measured.identity.settingsRevision!=options.settings.revision||measured.identity.epoch!=out.batch.identity.epoch){measured={};measured.identity=out.batch.identity;for(auto& sample:measured.gpu)sample.state=diagnostics::SampleState::Pending;}if(graph.xessEnabled()){std::lock_guard gpuLock(gpuMutex);graphStats.fgGeneratedFrames=presenter.xessGeneratedCount();}for(size_t stage=0;stage<measured.gpu.size();++stage){const auto& sample=measured.gpu[stage];if(sample.state==diagnostics::SampleState::Measured&&sample.milliseconds&&sample.end&&sample.end!=lastGpuSampleEnd[stage]){gpuStageTimes[stage].add(*sample.milliseconds);lastGpuSampleEnd[stage]=sample.end;}}- measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision,options.settings.srTarget);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.submitted=submitted;measured.expired=expired;measured.sourceFrames=sourceFrames-statsSourceBase;measured.validGenerated=graphStats.fgGeneratedFrames-statsGeneratedBase;measured.queueWatermark=out.batch.count;+ measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision,options.settings.srTarget);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.queueWatermark=out.batch.count;LiveStats completed;if(liveWorker){std::lock_guard statsLock(liveStatsMutex);completed=liveStats;}+ uint64_t skipped=0;{std::lock_guard lock(mutex_);skipped=snapshot_.captureRateSkipped-rateSkippedBase;}+ frameFlow->update([&](auto& m){m.counters.captureReceived=captureStats.received-captureFlowBase.received;m.counters.mailboxOverwritten=captureStats.dropped-captureFlowBase.dropped;m.counters.sourceSkippedBeforeGraph=skipped;m.slotReuseWaitCount=slotWaitCount;m.slotReuseWaitMs=slotWaitMilliseconds;m.counters.commandSlotsInFlight=slotsInFlight;m.counters.commandSlotHighWater=std::max(m.counters.commandSlotHighWater,slotsInFlight);});+ captureFlowLast=captureStats;+ measured.flow=frameFlow->snapshot(host100ns());+ 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=liveWorker?completed.ageP95:captureAges.p95(),waitP95=liveWorker?completed.waitP95:scheduleWaits.p95(),presentP95=liveWorker?completed.presentP95:presentTimes.p95();++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;if(liveWorker)snapshot_.submissionFps=completed.fps;else snapshot_.submissionFps=submissionTimes.size()>1?double(submissionTimes.size()-1)*1e7/(submissionTimes.back()-submissionTimes.front()):0;snapshot_.position=pts/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];snapshot_.fps=(sourceFrames-statsSourceBase)/std::max(0.001,std::chrono::duration<double>(Clock::now()-statsStart).count());snapshot_.flowPerf=graph.actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;@@ -356,6 +416,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){const auto gpuP95=[&](diagnostics::GpuStage stage){return gpuStageTimes[size_t(stage)].p95();};if(!isCapture&&Clock::now()>=nextTimingLog){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={} processed={}",options.settings.revision,decodeTimes.p95(),processTimes.p95(),gpuReadyTimes.p95(),presentTimes.p95(),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,sourceFrames-statsSourceBase));nextTimingLog=Clock::now()+std::chrono::seconds(1);}if(isCapture&&Clock::now()>=nextTimingLog){+ logFrameFlow(measured.flow,"active");const auto rates=snapshot();veyra::log::info("frame-rate",std::format("revision={} gpuCompletedFps={:.2f} completedReal={} capture60To30={} rateSkipped={} presentSubmitFps={:.2f} windowMs=1000 (not scanout FPS)",options.settings.revision,rates.fps,rates.processedCompleted,rates.captureHalfRate,rates.captureRateSkipped,rates.submissionFps.value_or(0)));veyra::log::info("capture-timing",std::format("revision={} received={} processed={} dropped={} callbackFps={:.2f} readAgeMs={:.3f} callbackToPresentReturnP95Ms={:.3f} processCpuP95Ms={:.3f} gpuReadyP95Ms={:.3f} schedulingWaitP95Ms={:.3f} presentCpuP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} nr={} nvof={} generated={} historyResets={} presentationDrains={} presentationCompletedReal={} presentationSkippedGenerated={} presentationCancelledJobs={} presentationWorker=1 batchCapacity=2 (not HDMI-to-display latency)",options.settings.revision,captureStats.received,sourceFrames-statsSourceBase,captureStats.dropped,captureStats.callbackFps,captureStats.readAgeMs,ageP95,processTimes.p95(),liveWorker?completed.readyP95:gpuReadyTimes.p95(),waitP95,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,graphStats.nrEvaluateCount,graphStats.nvofExecuteCount,graphStats.fgGeneratedFrames,historyResets.load(),presentationDrains.load(),presentationCompletedReal.load(),presentationSkippedGenerated.load(),presentationCancelledJobs.load()));diff --git a/src/gfx/CommandSlotRing.cpp b/src/gfx/CommandSlotRing.cppindex d2a2ed87..75cce1f5 100644--- a/src/gfx/CommandSlotRing.cpp+++ b/src/gfx/CommandSlotRing.cpp@@ -185,6 +185,21 @@ bool CommandSlotRing::submitAndSignal(uint32_t slot)return true;}+uint32_t CommandSlotRing::inFlightCount() const+{+ if (!initialized_ || fence_ == nullptr) {+ return 0;+ }+ const uint64_t completed = fence_->GetCompletedValue();+ uint32_t count = 0;+ for (const Slot& slot : slots_) {+ if (slot.fenceValue != 0 && slot.fenceValue > completed) {+ ++count;+ }+ }+ return count;+}+bool CommandSlotRing::discardRecording(){bool ok=true;for(uint32_t i=0;i<slots_.size();++i){auto& s=slots_[i];if(s.recording){const HRESULT hr=s.list->Close();s.recording=false;s.timed=false;s.label.clear();veyra::log::info("gfx",std::format("discard unsubmitted command list slot={} hr=0x{:X}",i,unsigned(hr)));if(FAILED(hr)){s.list.Reset();const HRESULT created=device_->CreateCommandList(0,D3D12_COMMAND_LIST_TYPE_DIRECT,s.allocator.Get(),nullptr,IID_PPV_ARGS(&s.list));if(FAILED(created)||FAILED(s.list->Close()))ok=false;}}}return ok;}diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex c94116ea..f85c3bd7 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -70,7 +70,7 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)}veyra::log::info("graph","diagnostic SR motion override active; no product entry point enables this");}- desc_ = desc;tracker_={};prevValid_=false;cadence_.reset();scene_.reset();previousLuma_.clear();+ desc_ = desc;tracker_={};prevValid_=false;fgHistorySkipped_=false;cadence_.reset();scene_.reset();previousLuma_.clear();if(desc.videoSrQuality>4)return false;srcW_ = desc.sourceWidth;srcH_ = desc.sourceHeight;@@ -656,7 +656,7 @@ bool EnhanceGraph::createViews()// ---------------------------------------------------------------------------// process: the per-frame chain (verbatim from the probe lambda).// ----------------------------------------------------------------------------bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, bool retainReferences)+bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, bool retainReferences, const FgAdmission& admitFg){out = FrameOutputs{};out.ptsMs = ptsMs;@@ -945,6 +945,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameadapt(nrFlow_.Get(),nrW_,nrH_,1);adapt(baseFlow_.Get(),workW_,workH_,2);}if(reset){++metrics_.resetCount;++epoch_;}+ out.historyReset=reset;out.batch.batchId=realFrameIndex_+1;out.batch.identity={epoch_,desc_.settingsRevision,sourceFrameId};out.batch.a100ns=static_cast<int64_t>(std::llround(prevPtsMs_*10000));out.batch.b100ns=static_cast<int64_t>(std::llround(ptsMs*10000));gpuTimer_.identity(out.batch.identity);@@ -1115,31 +1116,38 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FramemotionPreviousSource_[parity]=previousSource_;}previousSource_=sourceFrameId;- if(!fgEnabled_)gpuTimer_.resolve(list);+ const bool fgBackendAvailable=fgEnabled_&&(frucBackend_||(fgBackend_&&fgBackend_->created()));+ out.fgCandidates=fgBackendAvailable?desc_.fgMultiplier-1:0;+ const bool runFg=fgBackendAvailable&&(!admitFg||admitFg(out.batch));+ const bool resetFg=reset||!prevValid_||fgHistorySkipped_;+ out.fgRecovery=runFg&&fgHistorySkipped_;+ if(fgBackendAvailable&&!runFg){out.fgSkippedBeforeEval=out.fgCandidates;fgHistorySkipped_=true;}+ if(!runFg)gpuTimer_.resolve(list);if (!ring_.submitAndSignal(slot)) return false;- if(!fgEnabled_)gpuTimer_.submitted(ring_.lastSignaledValue());+ if(!runFg)gpuTimer_.submitted(ring_.lastSignaledValue());out.videoFenceValue = ring_.lastSignaledValue();- if(fgEnabled_&&frucBackend_){- if(reset&&realFrameIndex_>0&&(!ring_.drainQueue()||!frucBackend_->reset()))return false;+ if(runFg&&frucBackend_){+ if(resetFg&&realFrameIndex_>0&&(!ring_.drainQueue()||!frucBackend_->reset()))return false;auto* flist=ring_.acquireNext(slot,st);if(!flist)return false;gpuTimer_.mark(flist,GpuStage::FgBatch);frucBackend_->recordInput(flist,videoFrame_[parity].Get(),parity);if(!ring_.submitAndSignal(slot))return false;std::array<bool,3> repeats{};- if(!frucBackend_->execute(parity,prevValid_&&!reset?prevPtsMs_:ptsMs,ptsMs,repeats))return false;+ if(!frucBackend_->execute(parity,!resetFg?prevPtsMs_:ptsMs,ptsMs,repeats))return false;+ out.fgEvaluated=desc_.fgMultiplier-1;flist=ring_.acquireNext(slot,st);if(!flist)return false;for(uint32_t sub=1;sub<desc_.fgMultiplier;++sub){const unsigned generatedSlot=parity+(sub-1)*2;frucBackend_->recordOutput(flist,genFrame_[generatedSlot].Get(),sub);frucRepeated_[generatedSlot]=repeats[sub-1];}gpuTimer_.mark(flist,GpuStage::FgBatch,true);gpuTimer_.resolve(flist);if(!ring_.submitAndSignal(slot))return false;gpuTimer_.submitted(ring_.lastSignaledValue());- out.genFenceValue=ring_.lastSignaledValue();out.genSlot=parity;out.hasGenerated=prevValid_&&!reset;+ out.genFenceValue=ring_.lastSignaledValue();out.genSlot=parity;out.hasGenerated=!resetFg;if(out.hasGenerated)for(uint32_t sub=1;sub<desc_.fgMultiplier;++sub){const unsigned generatedSlot=parity+(sub-1)*2;++metrics_.fgSubmittedCandidates;BatchFrame f;f.identity=out.batch.identity;f.kind=FrameKind::Generated;f.validity=GenerationValidity::Pending;f.subframe=sub;f.pts100ns=FrameBatch::interpolate(out.batch.a100ns,out.batch.b100ns,sub,desc_.fgMultiplier);f.lease=std::make_shared<FrameLease>();f.lease->texture=genFrame_[generatedSlot];f.lease->slot=generatedSlot;f.lease->readyFence=out.genFenceValue;generatedLeases_[generatedSlot]=f.lease;out.batch.append(std::move(f));}}// FG reads enhanced SDR color, not the pre-NR guidance input.- if (fgEnabled_ && fgBackend_ && fgBackend_->created()) {+ if (runFg && fgBackend_ && fgBackend_->created()) {for(uint32_t sub=1;sub<desc_.fgMultiplier;++sub){const uint32_t generatedSlot=parity+(sub-1)*2;auto* flist=ring_.acquireNext(slot,st); if(!flist)return false;@@ -1157,7 +1165,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frametracker_.transition(flist,fgDisable_[parity].Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);ngx::DlssFgBackend::EvalDesc fe{};fe.backbuffer=videoFrame_[parity].Get(); fe.depth=depthTex_.Get(); fe.mvecs=motion;- fe.outputInterpolated=genFrame_[generatedSlot].Get(); fe.reset=reset||!prevValid_;+ fe.outputInterpolated=genFrame_[generatedSlot].Get(); fe.reset=resetFg;fe.outputDisableInterpolation=fgDisable_[parity].Get();fe.multiFrameCount=desc_.fgMultiplier-1;fe.multiFrameIndex=sub;fe.frameId=realFrameIndex_+1;@@ -1167,6 +1175,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif(sub==1)gpuTimer_.mark(flist,GpuStage::FgBatch);const auto timingStage=static_cast<GpuStage>(unsigned(GpuStage::Fg1)+sub-1);gpuTimer_.mark(flist,timingStage);if(!fgBackend_->evaluate(flist,ngxParams_,fe,st))return false;+ ++out.fgEvaluated;gpuTimer_.mark(flist,timingStage,true);if(sub==desc_.fgMultiplier-1)gpuTimer_.mark(flist,GpuStage::FgBatch,true);tracker_.uavBarrier(flist,genFrame_[generatedSlot].Get());tracker_.uavBarrier(flist,fgDisable_[parity].Get());@@ -1178,7 +1187,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif(sub==desc_.fgMultiplier-1)gpuTimer_.resolve(flist);if(!ring_.submitAndSignal(slot))return false;if(sub==desc_.fgMultiplier-1)gpuTimer_.submitted(ring_.lastSignaledValue());- out.hasGenerated=prevValid_&&!reset;+ out.hasGenerated=!resetFg;out.genSlot=parity; out.genFenceValue=ring_.lastSignaledValue();out.generatedPtsMs=(prevPtsMs_+ptsMs)*0.5;if(out.hasGenerated){@@ -1189,6 +1198,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame}}}+ if(runFg)fgHistorySkipped_=false;uploadFences_[parity]=ring_.lastSignaledValue();prevPtsMs_ = ptsMs;@@ -1239,7 +1249,7 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){// DLSS and FRUC allocate multiplier-specific feature/output resources;// XeSS has a fixed 2X proxy swapchain contract. Settings callers must// rebuild instead of accepting a change that cannot take effect in place.- if(s.multiplier!=desc_.fgMultiplier||(s.frameGenerationBackend==engine::FrameGenerationBackend::Fruc&&s.multiplier>1&&!frucBackend_)||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&s.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;+ if(std::max(2u,s.multiplier)!=desc_.fgMultiplier||(s.frameGenerationBackend==engine::FrameGenerationBackend::Fruc&&s.multiplier>1&&!frucBackend_)||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&s.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.protection=s.protection;desc_.settingsRevision=s.revision;desc_.fgMultiplier=std::max(2u,s.multiplier);desc_.enableNvofStandalone=s.nr&&!desc_.stillImage;nvofStandalone_=desc_.enableNvofStandalone;setNrEnabled(s.nr);setFgEnabled(s.multiplier>1&&s.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS);diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex a30de541..872b2b60 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -170,7 +170,7 @@ SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFif(!p.sequence)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Open);if(p.dropped!=p.lastDrop)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Drop);if(p.pendingDiscontinuity)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);- p.lastDrop=p.dropped;p.lastPts=time;sequence=++p.sequence;+ p.lastDrop=p.dropped;p.lastPts=time;++p.sequence;sequence=p.received;}p.frame->pts=static_cast<int64_t>(time*10000000);p.frame->duration=duration.isUnknown()?0:duration.to100ns();p.frame->time_base={1,10000000};packet={};packet.pts={p.frame->pts,10000000};packet.duration=duration;packet.colorInfo=p.info.color;packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;packet.arrivalHost100ns=std::chrono::duration_cast<std::chrono::nanoseconds>(p.readArrival.time_since_epoch()).count()/100;diff --git a/tests/integration/FgAdmissionTests.cpp b/tests/integration/FgAdmissionTests.cppnew file mode 100644index 00000000..577c9ced--- /dev/null+++ b/tests/integration/FgAdmissionTests.cpp@@ -0,0 +1,67 @@+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/engine/DeadlineWait.h"+#include "veyra/engine/LiveFgAdmission.h"+#include "veyra/source/MediaFileSource.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/RuntimePaths.h"+#include <d3d12sdklayers.h>+#include <filesystem>+#include <iostream>++int wmain(int argc,wchar_t** argv){+ using namespace veyra;+ if(argc!=5)return 2;+ const bool fruc=std::wstring(argv[1])==L"fruc";const unsigned multiplier=unsigned(std::stoi(argv[2]));+ if(multiplier<2||multiplier>4)return 2;+ std::filesystem::create_directories(argv[4]);Logger::instance().openFile((std::filesystem::path(argv[4])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;+ gfx::DeviceContextDesc device;device.enableDebugLayer=true;+ bool ok=ctx.initialize(device,status)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,status);+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> info;if(ok)ctx.device()->QueryInterface(IID_PPV_ARGS(&info));+ source::MediaFileSource source;source::SourceOpenDesc input;input.path=argv[3];input.preferHardwareDecode=false;+ ok=ok&&source.open(input);+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc desc;+ desc.sourceWidth=desc.workWidth=source.info().width;desc.sourceHeight=desc.workHeight=source.info().height;+ desc.enableNr=true;desc.enableFg=true;desc.fgMultiplier=multiplier;+ desc.frameGenerationBackend=fruc?engine::FrameGenerationBackend::Fruc:engine::FrameGenerationBackend::Dlss;+ desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ ok=ok&&graph.initialize(desc)&&graph.createViews();+ unsigned skipped=0,evaluated=0,recoveries=0,generated=0,real=0;+ engine::DeadlineWait wait;+ for(unsigned i=0;ok&&i<40;++i){+ pipeline::FramePacket packet;const AVFrame* frame=nullptr;+ ok=source.read(packet,&frame)==source::SourceReadStatus::Frame;if(!ok)break;+ pipeline::EnhanceGraph::FrameOutputs out;+ const bool reject=(i>=8&&i<12)||(i>=24&&i<28);+ auto admission=[&](const auto&){return engine::admitLiveFg(reject?2000000:900000,1000000,0,std::nullopt,0);};+ ok=graph.process(frame,packet.pts.toDouble()*1000,i==0,out,packet.sequence,&packet.colorInfo,false,admission);+ const auto start=std::chrono::steady_clock::now();+ while(ok&&!graph.resolveGeneration(out)){+ if(std::chrono::steady_clock::now()-start>std::chrono::seconds(2)){ok=false;break;}wait.slice(.2);+ }+ if(!ok)break;+ skipped+=out.fgSkippedBeforeEval;evaluated+=out.fgEvaluated;recoveries+=out.fgRecovery;+ ok=out.fgCandidates==multiplier-1&&out.fgCandidates==out.fgSkippedBeforeEval+out.fgEvaluated;+ if(reject)ok=ok&&out.fgEvaluated==0&&out.batch.count==1&&!out.hasGenerated;+ if(i==12||i==28)ok=ok&&out.fgRecovery&&out.batch.count==1;+ for(unsigned j=0;j<out.batch.count;++j){const auto& f=out.batch.frames[j];+ if(f.kind==pipeline::FrameKind::Real){++real;ok=ok&&f.pts100ns==packet.pts.to100ns();}+ else if(f.validity==pipeline::GenerationValidity::Valid){++generated;ok=ok&&f.pts100ns>out.batch.a100ns&&f.pts100ns<out.batch.b100ns;}+ }+ if(i==10||i==30){sink::RgbaImage image;ok=ok&&sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);+ unsigned nonblack=0;for(size_t p=0;p+3<image.pixels.size();p+=4)nonblack+=image.pixels[p]>8||image.pixels[p+1]>8||image.pixels[p+2]>8;+ ok=ok&&nonblack>image.width*image.height/20;+ }+ std::cout<<"frame="<<i<<" skip="<<out.fgSkippedBeforeEval<<" evaluate="<<out.fgEvaluated<<" recovery="<<out.fgRecovery<<" batch="<<out.batch.count<<" pass="<<ok<<std::endl;+ }+ const auto nr=graph.metrics().nrEvaluateCount;+ ok=ok&&real==40&&nr==40&&skipped==8*(multiplier-1)&&evaluated==32*(multiplier-1)&&recoveries==2&&generated>0;+ ring.drainQueue();graph.shutdown();source.close();+ unsigned errors=0;if(info)for(UINT64 i=0;i<info->GetNumStoredMessagesAllowedByRetrievalFilter();++i){SIZE_T size=0;info->GetMessage(i,nullptr,&size);std::vector<uint8_t> data(size);auto* m=reinterpret_cast<D3D12_MESSAGE*>(data.data());if(SUCCEEDED(info->GetMessage(i,m,&size))&&m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;log::error("debug",m->pDescription);}}+ ok=ok&&errors==0;+ std::cout<<"FG_ADMISSION backend="<<(fruc?"FRUC":"DLSS")<<" multiplier="<<multiplier<<" real="<<real<<" NR="<<nr<<" skipped="<<skipped<<" evaluated="<<evaluated<<" recoveries="<<recoveries<<" valid="<<generated<<" debugErrors="<<errors<<" pass="<<ok<<std::endl;+ info.Reset();ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;+}diff --git a/tests/integration/FrucTests.cpp b/tests/integration/FrucTests.cppindex a425d087..dedf3390 100644--- a/tests/integration/FrucTests.cpp+++ b/tests/integration/FrucTests.cpp@@ -53,6 +53,14 @@ int main(int argc,char** argv){using namespace veyra;if(argc<3)return 2;const unerror+=std::abs(image.pixels[(size_t(y)*W+x)*4+c]-expected);repeatError+=std::abs(repeated-expected);++samples;}const bool pass=item.validity==pipeline::GenerationValidity::Valid&&error<repeatError;pixelsOk=pixelsOk&&pass;std::cout<<"FRUC_RESET_GT epoch="<<epoch<<" frame="<<i<<" sub="<<item.subframe<<" mae="<<error/samples<<" repeatMae="<<repeatError/samples<<" pass="<<pass<<std::endl;+ if(!pass){+ double best=1e9;int bestOffset=0;+ for(int offset=-24;offset<=24;++offset){double candidate=0;unsigned count=0;+ for(unsigned y=32;y<H-32;y+=8)for(unsigned x=96;x<W-96;x+=8)for(unsigned c=0;c<3;++c){double expected=color(int(x)-shift-offset,y,c);if(invert)expected=255-expected;candidate+=std::abs(image.pixels[(size_t(y)*W+x)*4+c]-expected);++count;}+ candidate/=count;if(candidate<best){best=candidate;bestOffset=offset;}+ }+ std::cout<<"FRUC_RESET_NEAREST epoch="<<epoch<<" frame="<<i<<" offsetFromCurrent="<<bestOffset<<" mae="<<best<<std::endl;+ }}}}diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cppindex b4b82760..cdd04a12 100644--- a/tests/integration/LivePresentationTests.cpp+++ b/tests/integration/LivePresentationTests.cpp@@ -8,16 +8,26 @@ using namespace veyra;using namespace std::chrono_literals;int wmain(int argc,wchar_t**argv){SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");- if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--fruc")==0||wcscmp(argv[3],L"--half-rate")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--fruc")==0||wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);std::filesystem::create_directories(argv[2]);Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);HWND window=CreateWindowExW(0,L"STATIC",L"Live scheduler replay",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);if(!window)return 3;engine::EngineController engine;engine::PlayerOptions options;options.nr=false;options.fg=false;options.captureReplayForTest=true;const bool halfRate=argc==4&&wcscmp(argv[3],L"--half-rate")==0;- if(argc==4&&!halfRate)options.settings.frameGenerationBackend=engine::FrameGenerationBackend::Fruc;+ const bool overload=argc==4&&std::wstring(argv[3]).find(L"--overload")==0;+ if(argc==4&&wcscmp(argv[3],L"--fruc")==0)options.settings.frameGenerationBackend=engine::FrameGenerationBackend::Fruc;+ if(overload){options.nr=options.sr=options.fg=true;options.realtime=false;options.fgMultiplier=4;options.settings.videoSrQuality=4;options.captureReplayDisableFgAdmissionForTest=wcscmp(argv[3],L"--overload-baseline")==0;SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",nullptr);}if(halfRate)options.settings.content=engine::ContentRate::Capture60To30;int failures=0;auto check=[&](bool pass,const char* s){std::cout<<(pass?"PASS ":"FAIL ")<<s<<std::endl;if(!pass)++failures;};auto until=[&](auto predicate,int seconds=8){auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(seconds);while(std::chrono::steady_clock::now()<deadline){MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}auto s=engine.snapshot();if(s.failed){std::wcerr<<s.status<<'\n';return false;}if(predicate(s))return true;std::this_thread::sleep_for(5ms);}return false;};engine.open(window,argv[1],options);+ if(overload){+ check(until([](const auto& s){return s.frames>=150;},35),"native4K NR + VSR high + FG4 completes bounded overload replay");+ const auto s=engine.snapshot();const auto& c=s.metrics.flow.counters;+ check(c.fgCandidate==c.fgEvaluated+c.fgSkippedBeforeEval&&c.presentationBatchHighWater<=2&&c.commandSlotHighWater<=6,"overload work accounting and resource bounds");+ check(options.captureReplayDisableFgAdmissionForTest?c.fgSkippedBeforeEval==0:c.fgSkippedBeforeEval>0,"overload comparison uses requested admission policy");+ std::cout<<"OVERLOAD baseline="<<options.captureReplayDisableFgAdmissionForTest<<" frames="<<s.frames<<" processedFps="<<s.fps<<" realPresented="<<c.realPresented<<" generatedPresented="<<c.generatedPresented<<" expired="<<c.generatedExpiredAfterEval<<" skipped="<<c.fgSkippedBeforeEval<<" evaluated="<<c.fgEvaluated<<" ageP95Ms="<<s.captureAgeP95Ms<<std::endl;+ engine.stop();check(until([&](const auto&){return engine.idle();},5),"overload shutdown releases leases");DestroyWindow(window);CoUninitialize();return failures?1:0;+ }check(until([](const auto& s){return s.capture&&s.frames>=8&&s.metrics.submitted>=4;}),"file replay runs actual live worker and presents");if(halfRate){auto s=engine.snapshot();check(s.captureHalfRate&&s.captureRateSkipped>=s.frames-2,"60fps input is sampled before GPU processing");}check(engine.snapshot().processedCompleted>0,"real-only GPU completions are counted without FG");@@ -28,6 +38,10 @@ int wmain(int argc,wchar_t**argv){auto state=engine.snapshot();auto settings=state.desired;settings.nr=true;settings.multiplier=2;engine.requestSettings(settings);check(until([](const auto& s){return s.applied.nr&&s.applied.multiplier==2&&!s.applying&&s.nrEvaluated>2&&s.generated>0;}),"NR and 2x transaction while two batches are in flight");state=engine.snapshot();const auto liveRevision=state.applied.revision;check(state.metrics.identity.settingsRevision==state.applied.revision,"GPU metrics belong to applied revision");+ const auto& flow=state.metrics.flow;+ check(flow.latest.sameWindow(state.sessionId,state.metrics.identity)&&flow.counters.fgEvaluated>0,"flow counters carry actual session, epoch and revision");+ check(flow.counters.commandSlotHighWater<=6&&flow.counters.presentationBatchHighWater<=2,"command and presentation queues remain bounded");+ check(flow.counters.fgCandidate==flow.counters.fgSkippedBeforeEval+flow.counters.fgEvaluated,"each candidate is accounted before evaluate");engine.pause(true);check(until([](const auto& s){return s.transport==engine::TransportState::Paused;}),"pause returns without queue deadlock");check(engine.snapshot().fps==0,"paused FPS is zero rather than a retained session average");settings=engine.snapshot().desired;settings.model.style=1;engine.requestSettings(settings);@@ -39,6 +53,7 @@ int wmain(int argc,wchar_t**argv){settings=engine.snapshot().desired;settings.nr=false;settings.multiplier=1;engine.requestSettings(settings);check(until([](const auto& s){return !s.applied.nr&&s.applied.multiplier==1&&!s.applying&&s.metrics.sourceFrames>4;}),"disable features and keep live source open");check(engine.snapshot().metrics.validGenerated==0,"disabled revision cannot retain prior generated-frame count");+ check(engine.snapshot().metrics.flow.counters.fgEvaluated==0&&engine.snapshot().metrics.flow.counters.generatedPresented==0,"late FG completion never enters disabled revision flow counters");if(halfRate){settings=engine.snapshot().desired;settings.content=engine::ContentRate::Transport;engine.requestSettings(settings);check(until([](const auto& s){return !s.applying&&!s.captureHalfRate&&s.metrics.sourceFrames>=80;}),"switch back to original capture cadence live");diff --git a/tests/unit/PresentationWorkerTests.cpp b/tests/unit/PresentationWorkerTests.cppindex 90c25b7b..9a361a79 100644--- a/tests/unit/PresentationWorkerTests.cpp+++ b/tests/unit/PresentationWorkerTests.cpp@@ -9,9 +9,11 @@ int main(){veyra::engine::PresentationWorker worker([]{return false;});check(worker.push([&](const auto& cancelled){entered.set_value();while(!cancelled())std::this_thread::sleep_for(1ms);released=true;return true;}),"queue active presentation");check(enteredFuture.wait_for(1s)==std::future_status::ready,"worker starts independently of producer");- check(worker.push([&](const auto&){++ran;return true;}),"next batch can queue while active job sleeps");+ std::atomic<unsigned> discarded=0;+ check(worker.push([&](const auto&){++ran;return true;},[&]{++discarded;}),"next batch can queue while active job sleeps");check(!worker.push([](const auto&){return true;}),"two-batch capacity includes active lease");worker.cancelAndDrain();check(released&&ran==0,"cancel waits for active callback and drops queued job");+ check(discarded==1&&worker.occupancy()==0,"queued cancellation counted exactly once and occupancy drains");std::promise<void> next;auto nextFuture=next.get_future();check(worker.waitForSlot()&&worker.push([&](const auto&){next.set_value();return true;}),"producer resumes after cancellation");check(nextFuture.wait_for(1s)==std::future_status::ready,"new epoch job executes");worker.cancelAndDrain();check(worker.push([](const auto&){return false;}),"inject presentation failure");diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cppindex f5a27221..41386452 100644--- a/tests/unit/RepairContractTests.cpp+++ b/tests/unit/RepairContractTests.cpp@@ -2,6 +2,8 @@#include "veyra/diagnostics/DiagnosticEvent.h"#include "veyra/diagnostics/FrameMetrics.h"#include "veyra/engine/PresentationScheduler.h"+#include "veyra/engine/LiveFgAdmission.h"+#include "veyra/engine/FrameFlowWindow.h"#include <iostream>#include "veyra/engine/ContentCadence.h"#include "veyra/diagnostics/Redaction.h"@@ -41,6 +43,16 @@ int main(){engine::PresentationScheduler timeline;timeline.reset(3,0,1000000,200000);check(timeline.deadline(200000)==1400000&&timeline.deadline(400000)==1600000,"live deadlines do not drift with CPU completion");check(timeline.expired(0,1400000,100000)&&!timeline.anchored(4),"expire generated debt and reject epoch change");+ check(!engine::admitLiveFg(1200000,1000000,0,std::nullopt,0),"warmup rejects already-expired FG before evaluate");+ check(engine::admitLiveFg(900000,1000000,0,std::nullopt,0),"warmup does not invent a measured completion estimate");+ check(!engine::admitLiveFg(900000,1000000,2,30.0,1),"predicted completion beyond deadline skips optional pair");+ check(engine::admitLiveFg(900000,1000000,10,15.0,1),"remaining predicted work fits deadline");+ engine::FrameFlowWindow oldWindow(1,{3,4,5},0),newWindow(1,{4,5,6},0);+ oldWindow.ready(3,0,10000000);oldWindow.presented(true,9,10000000);+ auto oldStats=oldWindow.snapshot(10000000),newStats=newWindow.snapshot(10000000);+ check(oldStats.counters.generatedPresented==1&&newStats.counters.generatedPresented==0&&newStats.counters.fgReadyValid==0,"old asynchronous completion cannot contaminate new epoch/revision");+ check(oldStats.validGeneratedFps==3&&oldWindow.snapshot(21000000).validGeneratedFps==0,"effective generation rate expires without new frames");+ check(!oldStats.latest.sameWindow(2,{3,4,5})&&!oldStats.latest.sameWindow(1,{4,4,5})&&!oldStats.latest.sameWindow(1,{3,5,5}),"session, epoch and revision all partition flow counters");for(int i=0;i<100;++i){e.fingerprint=std::to_string(i);h.add(e);}check(h.size()==64,"bounded diagnostic queue");engine::ContentCadence cadence;for(int i=0;i<120;++i)cadence.observe(i*1000.0/60,i%2?.01:0,true);check(cadence.measuredRate()==30,"moving 30 in 60 cadence");cadence.reset();for(int i=0;i<120;++i)cadence.observe(i*1000.0/60,0,true);check(cadence.measuredRate()==0,"static scene cannot establish lower FPS");