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++
feat: add optional frame pacing with local acceptance report
Veyra Goal Agenta471474a972e
diff --git a/AGENTS.md b/AGENTS.mdindex 286f0b38..7c41e3f9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,9 @@# Veyra 项目 Agent 执行规则+> 2026-09-18 用户授权目标模式实施可关闭帧同步、多模式与实际延迟验收。开工存档 `6e69eeb` / `checkpoint/pre-frame-pacing-20260918`,隔离分支 `codex/frame-pacing-20260918`。按 `docs/FRAME_PACING_EXECUTION_PLAN_2026-09-18.md` 施工,默认关闭、直接 NGX、保留 6X,不推送或发布。报告必须区分进程内排队、系统显示事件与未测量的屏幕端到端延迟。++> 本轮交付状态见 `docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md`:本机软件短测完成,原生 Reflex 仅无补帧路径;FG 下显示回退低排队,XeSS 不叠加外部节奏。不得将软件驻留减少冒充屏幕延迟降低,不得把本机 RTX5070 验收扩展为 30/40、实卡采集、PS5 或 VRR 通过。完整 Reflex+FG 与显示延迟验收仍未完成;现有 beta 包不含本轮改动。+> 2026-09-18 当前用户授权制作 1.4.2beta 内测群便携包,包含 FSR4 回退及保留的 RTX Video HDR。允许携带已核验的 RTX Video SDK 1.1.0 TrueHDR 原件(SHA256 9A80575F247190C05FE80EAC0C4BAA1D0D4D932348F26808310B5EC4BF9EEB4B,3955752 bytes,1.1.0.0,Valid),其余组件沿用 1.4.1 身份,逐文件 manifest 及许可证随包提供。仅本地交付用户自行发群;无 GitHub 推送、Release 或 Agent 代发消息授权。> 2026-09-18 最新用户决定:停止并回退 NVIDIA FSR 4.1 实验,撤销其 UI、provider 接入及测试/打包入口;不继续画质修复。保留 RTX 超分、原有官方 FSR 和独立 RTX Video HDR 改动。本条覆盖下方 FSR4 本地试验授权;历史研究仅供追溯,不是待办。旧实验预设的 mode 6 读取时迁移到 RTX Video SR 高档,其他设置保留。diff --git a/CMakeLists.txt b/CMakeLists.txtindex c6c3a161..d8421fdd 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -666,6 +666,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_link_libraries(veyra_fg_presentation_tests PRIVATE veyra_engine)add_executable(veyra_player_tracks_tests tests/integration/PlayerTracksTests.cpp)add_executable(veyra_scheduling_chain_tests tests/integration/SchedulingChainTests.cpp)+ add_executable(veyra_presentation_pacing_tests tests/integration/PresentationPacingTests.cpp)+ target_compile_features(veyra_presentation_pacing_tests PRIVATE cxx_std_20)+ target_compile_options(veyra_presentation_pacing_tests PRIVATE /utf-8)+ target_link_libraries(veyra_presentation_pacing_tests PRIVATE veyra_engine)target_compile_features(veyra_scheduling_chain_tests PRIVATE cxx_std_20)target_link_libraries(veyra_scheduling_chain_tests PRIVATE veyra_engine)target_compile_features(veyra_player_tracks_tests PRIVATE cxx_std_20)diff --git a/README.md b/README.mdindex 5abe762a..ca7877b2 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@[English](README_EN.md) | 简体中文-[当前状态与开发任务](docs/CURRENT_STATUS.md) · [本机构建](docs/BUILD.md)。正式版为 1.4.1;RTX Video HDR 与 NVIDIA FSR 4.1.1 正在隔离开发,尚未包含在正式版中。+[当前状态与开发任务](docs/CURRENT_STATUS.md) · [本机构建](docs/BUILD.md)。正式版为 1.4.1;1.4.2beta 已本地交付 RTX Video HDR 内测,NVIDIA FSR 4.1 实验已撤回。隔离分支已实现默认关闭的帧同步,入口为专业模式 → 运动 → 帧同步;[本机验收与延迟报告](docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md)记录适用范围,尚未加入现有内测包。<p align="center"><a href="https://github.com/Likely7/Veyra-NRVideo/blob/main/REAMDE%20MP4.mp4">diff --git a/README_EN.md b/README_EN.mdindex 141223d6..85b291c5 100644--- a/README_EN.md+++ b/README_EN.md@@ -4,7 +4,7 @@English | [简体中文](README.md)-[Current status and development](docs/CURRENT_STATUS.md) · [Build instructions](docs/BUILD.md). The released version is 1.4.1. RTX Video HDR and experimental NVIDIA FSR 4.1.1 are being developed separately and are not included in that release.+[Current status and development](docs/CURRENT_STATUS.md) · [Build instructions](docs/BUILD.md). The released version is 1.4.1. The local 1.4.2beta package includes RTX Video HDR; the NVIDIA FSR 4.1 experiment was reverted. Optional frame pacing is implemented on an isolated branch, disabled by default, under Professional mode > Motion. See the [local acceptance and latency report](docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md); this change is not in the existing beta package. Native Reflex is experimental without frame generation; with FG it explicitly falls back to low queue mode while preserving the multiplier.<p align="center"><a href="https://github.com/Likely7/Veyra-NRVideo/blob/main/REAMDE%20MP4.mp4">diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 984be2dd..0703024c 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -315,6 +315,39 @@ This runtime retains the NVIDIA RTX Video SDK license; it is not relicensed undeVeyra's GPL. SDK/license and runtime remain external. This change does not publishor grant redistribution of a new runtime pack.+## NVAPI Reflex ABI reference (2026-09-18)++Source: https://github.com/NVIDIA/nvapi/tree/87dca625e83fd89a983e19b904e5f3a580da90d2+(`nvapi.h`, `nvapi_interface.h`, `nvapi_lite_common.h`), MIT.+`include/veyra/gfx/ReflexSession.h` contains minimal renamed ABI declarations for+SetSleepMode v1 and SetLatencyMarker v1, and QueryInterface IDs for initialization,+unloading, sleep and markers. Adaptations: independent RAII device lifetime,+absolute system-driver loading, return-code logging, successful call counts and+explicit disable. No complete SDK header or NVIDIA runtime is committed or bundled.+The driver is supplied by Windows/NVIDIA. Frame markers delimit Veyra enhancement+and presentation, not game input or physical display latency. Generated-frame+Reflex integration is not enabled; DLSS retains its selected multiplier.++Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.++Permission is hereby granted, free of charge, to any person obtaining a copy of+this software and associated documentation files (the "Software"), to deal in+the Software without restriction, including without limitation the rights to+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software is furnished to do so,+subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+## dav1d (1.3.0 AV1 playback)FFmpeg dynamically links dav1d 1.5.4 from the pinned local vcpkg build. The portable package includes its complete aggregated copyright/license text in `licenses/DAV1D-COPYRIGHT.txt` and provenance in `licenses/DAV1D-SPDX.json`. The FFmpeg corresponding-source ZIP includes dav1d source and its vcpkg port. Upstream: https://code.videolan.org/videolan/dav1d . License set recorded by the build: Apache-2.0, BSD-2-Clause, ISC and MIT; retain all notices supplied with the source.diff --git a/VEYRA_PRODUCT_SPEC_V1.md b/VEYRA_PRODUCT_SPEC_V1.mdindex 16f261b4..5529e57d 100644--- a/VEYRA_PRODUCT_SPEC_V1.md+++ b/VEYRA_PRODUCT_SPEC_V1.md@@ -1,6 +1,6 @@# Veyra V1 产品与技术规格-> 2026-09-18:本文保留 V1 历史基线。当前发布能力、HDR/多声道扩展、最高 6X 及新功能状态见 [CURRENT_STATUS](docs/CURRENT_STATUS.md)。当前任务按 [Video HDR / FSR4 施工方案](docs/VIDEO_HDR_FSR41_EXECUTION_PLAN_2026-09-18.md) 执行;下文旧 SDR 限制、2X 范围和门禁不撤销后续已授权实现。单次测试最多 300 秒,未实测项明确报告。+> 2026-09-18:本文保留 V1 历史基线。当前发布能力、HDR/多声道扩展、最高 6X 及新功能状态见 [CURRENT_STATUS](docs/CURRENT_STATUS.md)。当前任务按[可关闭帧同步方案](docs/FRAME_PACING_EXECUTION_PLAN_2026-09-18.md)与[实际验收报告](docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md)执行;NVIDIA FSR4 实验已由用户终止并回退。下文旧 SDR 限制、2X 范围和门禁不撤销后续已授权实现。单次测试最多 300 秒,未实测项明确报告。版本:Launch V1.3(2026-09-06 接管重基线)diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex 2da92236..7749a9fc 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -1094,7 +1094,7 @@ void arrange(){if(page==2)layoutColorPage();int helpHeight=0;if(smoothMotionHelpExpanded){auto dc=GetDC(window);auto old=SelectObject(dc,font);RECT textRect{0,0,dip(window,std::max(1,width-24)),0};DrawTextW(dc,smoothMotionHelp,-1,&textRect,DT_CALCRECT|DT_WORDBREAK|DT_NOPREFIX);SelectObject(dc,old);ReleaseDC(window,dc);helpHeight=MulDiv(textRect.bottom,96,layoutDpi(window))+16;}- const auto helpOffset=[&](const Item& entry){const auto id=GetDlgCtrlID(entry.h);return entry.page==1&&(id==1114||id==205||id==1110)?helpHeight:0;};+ const auto helpOffset=[&](const Item& entry){const auto id=GetDlgCtrlID(entry.h);return entry.page==1&&(id==1114||id==205||id==1110||id==240||id==241||id==242||id==1150)?helpHeight:0;};for(auto& entry:items){if(GetDlgCtrlID(entry.h)==1120)entry.height=helpHeight;if(entry.page==page&&!entry.hidden&&(GetDlgCtrlID(entry.h)!=1120||smoothMotionHelpExpanded)){wchar_t cls[32]{};GetClassNameW(entry.h,cls,32);contentHeight=std::max(contentHeight,entry.y+helpOffset(entry)+(_wcsicmp(cls,L"COMBOBOX")==0?36:entry.height)+12);}}if(page==2)contentHeight=std::max(contentHeight,colorPageContentHeight);@@ -1110,6 +1110,11 @@ HWND add(const wchar_t* cls,const wchar_t* text,int id,DWORD style,int group,intvoid button(const wchar_t* title,int id,int group,int x,int y,int width=-1){add(L"BUTTON",title,id,BS_PUSHBUTTON|WS_TABSTOP,group,x,y,width,36);}void combo(int id,int group,int y,std::initializer_list<const wchar_t*> names){auto h=add(L"COMBOBOX",L"",id,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,group,12,y,-1,200);for(auto name:names)SendMessageW(h,CB_ADDSTRING,0,LPARAM(name));}LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){+ if(msg==WM_COMMAND&&!populating&&((LOWORD(wp)==240&&HIWORD(wp)==BN_CLICKED)||((LOWORD(wp)==241||LOWORD(wp)==242)&&HIWORD(wp)==CBN_SELCHANGE))){+ auto setting=controller->snapshot().presentation;setting.enabled=checked(240)==BST_CHECKED;+ setting.mode=engine::PacingMode(send(241,CB_GETCURSEL));setting.display=engine::DisplaySync(send(242,CB_GETCURSEL));+ if(setting.valid()){controller->requestPresentation(setting);EnableWindow(item(241),setting.enabled);EnableWindow(item(242),setting.enabled);SendMessageW(GetParent(window),WM_APP+46,0,0);}return 0;+ }if(msg==WM_COMMAND&&LOWORD(wp)==221&&HIWORD(wp)==BN_CLICKED){smoothMotionHelpExpanded=!smoothMotionHelpExpanded;putText(221,smoothMotionHelpExpanded?L"Smooth Motion · 收起说明 ▴":L"Smooth Motion · 开启方法 ▾");arrange();return 0;}if(msg==WM_COMMAND&&!populating&&LOWORD(wp)==220&&HIWORD(wp)==BN_CLICKED){liveField(220);return 0;}if(msg==WM_COMMAND&&!populating&&LOWORD(wp)==230&&HIWORD(wp)==BN_CLICKED){SendMessageW(GetParent(window),WM_APP+44,230,checked(230));return 0;}@@ -1501,6 +1506,11 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.}}setText(item(1103),L"光流与补帧");+ add(L"BUTTON",L"帧同步",240,BS_AUTOCHECKBOX|WS_TABSTOP,1,12,550,-1,32);+ combo(241,1,590,{L"低排队",L"均匀呈现 · 前端同步",L"NVIDIA Reflex · 实验"});+ combo(242,1,634,{L"允许撕裂",L"垂直同步",L"自动"});+ add(L"STATIC",L"",1150,SS_NOPREFIX,1,12,678,-1,70);+ {const auto p=controller->snapshot().presentation;check(240,p.enabled?BST_CHECKED:BST_UNCHECKED);send(241,CB_SETCURSEL,unsigned(p.mode));send(242,CB_SETCURSEL,unsigned(p.display));EnableWindow(item(241),p.enabled);EnableWindow(item(242),p.enabled);}button(L"Smooth Motion · 开启方法 ▾",221,1,12,358);ghost(item(221));SetPropW(item(221),L"veyra.tip",HANDLE(L"查看 NVIDIA App 的 AI 插帧开启方法。这里只提供说明,不修改驱动,也不限制叠加补帧。"));@@ -1571,7 +1581,7 @@ case WM_HSCROLL:{int id=GetDlgCtrlID(reinterpret_cast<HWND>(lp));if(id>=600&&id<else if(id==622){// Feather slider: the edit box owns the value, its EN_CHANGE applies it.const int value=std::clamp(int(SendMessageW(reinterpret_cast<HWND>(lp),TBM_GETPOS,0,0)),0,64);putText(222,std::to_wstring(value).c_str());}return 0;}-case WM_TIMER:{auto s=controller->snapshot();syncProtection(enhancementEnabled?s.desired.protection:configuredSettings.protection);if(enhancementEnabled&&!dirty&&displayedSettings!=s.desired)populate(s.desired);syncColorControls();check(200,enhancementEnabled&&s.desired.nr?BST_CHECKED:BST_UNCHECKED);check(201,enhancementEnabled&&s.desired.sr?BST_CHECKED:BST_UNCHECKED);std::wostringstream o;if(!s.running&&!s.frames&&s.transport!=engine::TransportState::Opening)o<<L"未打开媒体 · 设置待启用\n";else{+case WM_TIMER:{auto s=controller->snapshot();putText(1150,s.presentationStatus.c_str());syncProtection(enhancementEnabled?s.desired.protection:configuredSettings.protection);if(enhancementEnabled&&!dirty&&displayedSettings!=s.desired)populate(s.desired);syncColorControls();check(200,enhancementEnabled&&s.desired.nr?BST_CHECKED:BST_UNCHECKED);check(201,enhancementEnabled&&s.desired.sr?BST_CHECKED:BST_UNCHECKED);std::wostringstream o;if(!s.running&&!s.frames&&s.transport!=engine::TransportState::Opening)o<<L"未打开媒体 · 设置待启用\n";else{o<<L"期望版本 "<<s.desired.revision<<L" / 已应用 "<<s.applied.revision<<(s.applying?L" · 应用中":L"");const wchar_t* backend=s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS?L"XeSS":s.applied.frameGenerationBackend==engine::FrameGenerationBackend::Fsr?L"AMD FSR":L"DLSS";o<<L"\n"<<backend<<L" · "<<(s.applied.multiplier<=1?L"补帧关闭":s.fgActive?L"补帧运行":L"等待有效补帧");diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex a3e915bd..b2cb07aa 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -588,6 +588,7 @@ case WM_CAPTURECHANGED:if(inspectorResizing){inspectorResizing=false;InvalidateRcase WM_NOTIFY:{auto header=reinterpret_cast<NMHDR*>(lp);if(header->code==TTN_GETDISPINFOW){auto info=reinterpret_cast<NMTTDISPINFOW*>(lp);HWND child=reinterpret_cast<HWND>(header->idFrom);if(auto tip=GetPropW(child,L"veyra.tip"))info->lpszText=reinterpret_cast<wchar_t*>(tip);else{static wchar_t value[512];GetWindowTextW(child,value,512);info->lpszText=value;}return 0;}break;}case WM_GETMINMAXINFO:{auto info=reinterpret_cast<MINMAXINFO*>(lp);info->ptMinTrackSize={veyra::ui::dip(hwnd,720),veyra::ui::dip(hwnd,540)};return 0;}case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORBTN:case WM_CTLCOLORLISTBOX:return veyra::ui::colors(msg,wp,lp);+case WM_APP+46:{uiPreferences.presentation=engine.snapshot().presentation;if(smokeSeconds<=0&&!preferences.save(uiPreferences,nullptr))veyra::log::warn("preferences","Could not persist presentation settings");return 0;}case WM_APP+45:{if(masterPendingRevision)return 0;auto settings=uiState.enhanced?engine.snapshot().desired:uiState.configured;if(wp==213){auto current=engine.snapshot();if(uiState.mode!=veyra::ui::Mode::Professional||!current.running||!current.frames)return 0;bool space=false;for(auto q:settings.protection.regions)space|=q.empty();if(!space)return 0;cancelProtection();protectionArmed=true;SetFocus(video);return 1;}if(wp==214){cancelProtection();settings.protection={};}else if(wp==206)settings.protection.enabled=lp==BST_CHECKED;else if(wp==222)settings.protection.featherPixels=float(std::clamp(int(lp),0,64));else return 0;@@ -1121,6 +1122,7 @@ int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<a}if(workerMapping){const int code=veyra::engine::runExportWorker(workerMapping);CoUninitialize();return code;}if(smokeSeconds<=0&&exportOutput.empty()){uiPreferences=preferences.load();initialOptions=veyra::engine::PlayerOptions::from(preferences.startup(initialOptions.snapshot()));engine.setVolume(uiPreferences.volume,uiPreferences.muted);uiState.subtitles=uiPreferences.subtitles;subtitlePixels=uiPreferences.subtitleSize;uiState.subtitleOutline=uiPreferences.subtitleOutline;uiState.subtitleBackground=uiPreferences.subtitleBackground;uiState.subtitleSecondLanguage=uiPreferences.subtitleSecondLanguage;uiState.subtitleMargin=uiPreferences.subtitleMargin;uiState.subtitleFont=uiPreferences.subtitleFont;}+engine.requestPresentation(uiPreferences.presentation);engine.requestSettings(initialOptions.snapshot());if(!exportOutput.empty()){std::atomic<bool> cancel{false},finished{false};std::thread cancelTimer;if(cancelAfterMs)cancelTimer=std::thread([&]{const auto start=GetTickCount64();while(!finished&&GetTickCount64()-start<cancelAfterMs)std::this_thread::sleep_for(std::chrono::milliseconds(5));if(!finished)cancel=true;});bool ok=veyra::engine::exportVideo(autoInput,exportOutput,initialOptions,exportHevc,cancel,[](double,const std::wstring& s){OutputDebugStringW(s.c_str());},exportFrames);finished=true;if(cancelTimer.joinable())cancelTimer.join();veyra::log::info("app",std::format("export result={}",ok));CoUninitialize();return ok?0:cancel?3:1;}WNDCLASSEXW wc{sizeof(wc)};wc.hInstance=instance;wc.lpfnWndProc=proc;wc.lpszClassName=L"VeyraApp";wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);wc.hbrBackground=veyra::ui::bgBrush();diff --git a/apps/veyra/ui/UiPreferenceStore.h b/apps/veyra/ui/UiPreferenceStore.hindex 051854ef..ded89f33 100644--- a/apps/veyra/ui/UiPreferenceStore.h+++ b/apps/veyra/ui/UiPreferenceStore.h@@ -1,11 +1,13 @@#pragma once#include "UiSessionState.h"#include "veyra/engine/PresetStore.h"+#include "veyra/engine/PresentationSettings.h"#include <filesystem>#include <fstream>#include <sstream>namespace veyra::ui {struct UiPreferences {+ engine::PresentationSettings presentation;float volume=1;bool muted=false,subtitles=true;// The colour page is a professional panel now (colour wheels, tone curve,// mixer strip): start wider so those controls are usable, still draggable@@ -31,7 +33,7 @@ public:// inspector index 4 is the audio page (selectInspector(4)), so the valid// range is 0..4. A narrower bound here silently discarded every saved// window size, volume and subtitle style for users who last sat on it.- if(!(file>>magic>>version>>read.volume>>mute>>sub>>read.width>>read.height>>read.x>>read.y>>pos>>read.inspector>>read.subtitleSize)||magic!="VEYRA_UI"||(version<1||version>5)||!std::isfinite(read.volume)||read.volume<0||read.volume>1||mute<0||mute>1||sub<0||sub>1||pos<0||pos>1||read.width<720||read.width>10000||read.height<540||read.height>10000||abs(int64_t(read.x))>100000||abs(int64_t(read.y))>100000||read.inspector<0||read.inspector>4||read.subtitleSize<16||read.subtitleSize>56){corrupt_=true;return result;}+ if(!(file>>magic>>version>>read.volume>>mute>>sub>>read.width>>read.height>>read.x>>read.y>>pos>>read.inspector>>read.subtitleSize)||magic!="VEYRA_UI"||(version<1||version>6)||!std::isfinite(read.volume)||read.volume<0||read.volume>1||mute<0||mute>1||sub<0||sub>1||pos<0||pos>1||read.width<720||read.width>10000||read.height<540||read.height>10000||abs(int64_t(read.x))>100000||abs(int64_t(read.y))>100000||read.inspector<0||read.inspector>4||read.subtitleSize<16||read.subtitleSize>56){corrupt_=true;return result;}if(version==2&&(!(file>>read.inspectorWidth)||read.inspectorWidth<296||read.inspectorWidth>420)){corrupt_=true;return result;}if(version>=3){int outline=0,background=0,second=0;@@ -45,12 +47,13 @@ public:// it must be read here - reading it earlier shifted every following field.if(version>=4&&!(file>>read.colourFoldMask)){corrupt_=true;return result;}if(version>=5&&(!(file>>read.enhancementEnabled)||read.enhancementEnabled< -1||read.enhancementEnabled>1)){corrupt_=true;return result;}+ if(version>=6){int enabled=0,mode=0,display=0;if(!(file>>enabled>>mode>>display)||enabled<0||enabled>1||mode<0||mode>2||display<0||display>2){corrupt_=true;return result;}read.presentation={enabled!=0,engine::PacingMode(mode),engine::DisplaySync(display)};}file>>std::ws;if(!file.eof()){corrupt_=true;return result;}read.muted=mute;read.subtitles=sub;read.positioned=pos;return read;}engine::EnhancementSettings startup(engine::EnhancementSettings fallback){engine::PresetStore last(folder_/"last-applied.v1");if(!last.load()||last.entries().empty())return fallback;return last.entries().front().settings;}bool save(const UiPreferences& p,const engine::EnhancementSettings* applied){bool ok=true;std::filesystem::create_directories(folder_);if(applied){engine::PresetStore last(folder_/"last-applied.v1");ok=last.load()&&last.put(L"Last applied",*applied,true);}- if(corrupt_)return false;std::ostringstream out;out<<"VEYRA_UI 5\n"<<p.volume<<' '<<p.muted<<' '<<p.subtitles<<' '<<p.width<<' '<<p.height<<' '<<p.x<<' '<<p.y<<' '<<p.positioned<<' '<<p.inspector<<' '<<p.subtitleSize<<' '<<p.inspectorWidth<<' '<<p.subtitleOutline<<' '<<p.subtitleBackground<<' '<<p.subtitleSecondLanguage<<' '<<p.subtitleMargin<<' '<<p.subtitleFont<<' '<<p.colourFoldMask<<' '<<p.enhancementEnabled<<'\n';+ if(corrupt_)return false;std::ostringstream out;out<<"VEYRA_UI 6\n"<<p.volume<<' '<<p.muted<<' '<<p.subtitles<<' '<<p.width<<' '<<p.height<<' '<<p.x<<' '<<p.y<<' '<<p.positioned<<' '<<p.inspector<<' '<<p.subtitleSize<<' '<<p.inspectorWidth<<' '<<p.subtitleOutline<<' '<<p.subtitleBackground<<' '<<p.subtitleSecondLanguage<<' '<<p.subtitleMargin<<' '<<p.subtitleFont<<' '<<p.colourFoldMask<<' '<<p.enhancementEnabled<<' '<<p.presentation.enabled<<' '<<unsigned(p.presentation.mode)<<' '<<unsigned(p.presentation.display)<<'\n';auto target=folder_/"ui-preferences.v1",tmp=folder_/(L"ui-preferences.tmp-"+std::to_wstring(GetCurrentProcessId()));auto data=out.str();HANDLE file=CreateFileW(tmp.c_str(),GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);if(file==INVALID_HANDLE_VALUE)return false;DWORD written=0;bool saved=WriteFile(file,data.data(),DWORD(data.size()),&written,nullptr)&&written==data.size()&&FlushFileBuffers(file);CloseHandle(file);if(saved)saved=MoveFileExW(tmp.c_str(),target.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)!=FALSE;return ok&&saved;}};diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.mdindex 1f268ef2..31a033c1 100644--- a/docs/CURRENT_STATUS.md+++ b/docs/CURRENT_STATUS.md@@ -16,7 +16,7 @@## 本轮开发-帧同步已形成[可完全关闭的实施方案](FRAME_PACING_EXECUTION_PLAN_2026-09-18.md):默认关闭,规划低排队、均匀呈现和经验证后开放的 Reflex 实验模式,独立保存显示同步偏好。当前仅文档,尚未施工或证明性能收益,未加入现有 1.4.2beta 测试包。+帧同步已在隔离分支 `codex/frame-pacing-20260918` 实现并完成本机短测,基线存档 `6e69eeb`。入口:专业模式 → 运动 → 帧同步,默认关闭;低排队、均匀呈现、Reflex 实验和独立显示同步偏好可保存。无补帧文件测试减少了一帧提前缓存驻留;6X 提交吞吐保持 144fps,未证明显著降延迟或更平滑。Reflex 无补帧时真实调用 NVAPI,开启补帧时明确回退低排队并保留倍率;XeSS 继续由提供方调度。屏幕端到端延迟、30/40 实卡、真实采集、PS5、VRR 未验证,完整原计划尚未全部验收。详见[验收报告](FRAME_PACING_ACCEPTANCE_2026-09-18.md)。未合并 main、推送、发布或更新现有 1.4.2beta 包。RTX Video HDR 独立改动保留。用户已明确终止 NVIDIA FSR 4.1 实验并要求回退,不再执行此前 FSR4 施工和画质修复计划。diff --git a/docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md b/docs/FRAME_PACING_ACCEPTANCE_2026-09-18.mdnew file mode 100644index 00000000..baf295a3--- /dev/null+++ b/docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md@@ -0,0 +1,119 @@+# 可关闭帧同步:本机验收与延迟报告++日期:2026-09-18。本机实现、构建、软件短测完成;完整硬件验收和 Reflex+FG 原生整合未完成。没有证明用户反馈的长期帧率波动已经根治。++## 交付与入口++- 开工存档:`6e69eeb`,tag `checkpoint/pre-frame-pacing-20260918`,包含此前 HDR、FSR4 回退和 beta 改动。+- 隔离分支:`codex/frame-pacing-20260918`;源码 `E:/项目/Veyra/worktrees/frame-pacing-20260918`。+- 本机程序:`E:/项目/Veyra/build/frame-pacing-20260918/veyra.exe`,仍标识 `1.4.2beta`,属于开发构建,依赖本机运行库目录,不是新的便携包。+- 专业模式 → **运动** → 向下滚动到 **帧同步**。默认关闭;关闭后记住模式和显示同步偏好,下次启动仍关闭。+- 未合并 main、推送、发布、重新打包。现有 1.4.2beta ZIP 不包含本轮改动。++| 选择 | 实际行为 |+| --- | --- |+| 关闭 | 不调用新增容量等待、均匀节奏或 Reflex 周期调用,恢复基线队列上限;正常音画同步及补帧依赖仍存在 |+| 低排队 | 无补帧时减少提前增强队列至一批,交换链最大排队设为 1;FG 保留两批资源窗口 |+| 均匀呈现 · 前端同步 | 低排队基础上,在 Present 前按媒体时间安排最小间隔;可有限追赶,过期生成帧跳过并统计 |+| NVIDIA Reflex · 实验 | 无补帧时原生 NVAPI Sleep/markers;开启 FG 时状态明确提示改用低排队,保留 2X/4X/6X |++显示同步独立可选“允许撕裂/垂直同步/自动”。自动目前采用 VSync,状态注明 VRR 未知,不检测或修改 G-SYNC 设置。XeSS/FSR 外部交换链保持提供方调度,新增选项明确显示暂不生效;实测 XeSS 2X 正常,未恢复 FSR UI。++“完全关闭”指关闭本轮新增策略。等待后的返回状态、关闭失败均有日志和 UI 提示;不能关闭 GPU 资源安全、媒体时钟、补帧后一帧依赖或系统/外部限速。现有 NR/SR 顺序的“低延迟模式”与此独立。++## 环境与测量口径++RTX 5070,驱动 616.56,2560×1440、100Hz、SDR。主对照素材为真实 1920×1080、24fps、E-AC3 音轨的 17.124 秒 MKV,路径 `E:/项目/Veyra/tests/1.4.2beta/visible-scene.mkv`。多数稳态对照采样 10 秒,统计日志排除开始 2 秒;帧率变体和组合效果为 6 秒短测。不是长时间稳定性证明,未测量实际音画偏移。++`ready→return` 是 **CPU 首次观测增强帧就绪,到 Present 返回** 的软件驻留时间,包含媒体定时和队列等待。它不是 GPU 执行时间,也不是 HDMI 输入、鼠标输入或屏幕发光延迟。文件可以提前解码,减少这一指标不等于影片在屏幕上提前相同时长。++PresentMon 2.5.1 实际尝试启动 ETW,失败:`failed to start trace session: access denied`,要求管理员或 Performance Log Users。没有修改系统组/权限;证据在 `tests/frame-pacing-20260918/low-initial/presentmon.stderr`。**实际显示事件、扫描节奏及屏幕端到端延迟未测量**,软件提交 FPS 不代表屏幕物理刷新率。++## 无补帧:各选项软件实测++单位 ms;P50 是中位数,P95 是 95 分位。所有以下稳态测试为 24.00 提交 fps,无源预览跳帧。++| 模式 / 显示同步 | ready→return P50 / P95 | 提交间隔 P95 | 证据目录名 |+| --- | ---: | ---: | --- |+| 关闭 | 81.548 / 82.543 | 42.371 | off-final |+| 关闭,旧非 waitable 交换链对照 | 81.602 / 82.618 | 42.470 | off-legacy |+| 低排队 / 允许撕裂 | 40.871 / 41.430 | 42.303 | low-final |+| 低排队 / VSync | 40.901 / 41.427 | 42.273 | low-vsync |+| 低排队 / 自动 | 40.952 / 41.454 | 42.335 | low-auto |+| 均匀呈现 / 允许撕裂 | 40.937 / 41.542 | 42.363 | even-final2 |+| 均匀呈现 / VSync | 40.838 / 41.464 | 42.297 | even-vsync |+| 均匀呈现 / 自动 | 40.855 / 41.537 | 42.368 | even-auto-final |+| Reflex / 允许撕裂 | 40.886 / 41.446 | 42.346 | reflex-final |+| Reflex / VSync | 40.842 / 41.447 | 42.345 | reflex-vsync |+| Reflex / 自动 | 40.871 / 41.450 | 42.322 | reflex-auto |++解释:关闭时提前增强两批,开启时一批,约减少一张 24fps 源帧的提前驻留。关闭与同一构建的旧交换链路径读数接近;不是两套完整历史二进制的性能对比。Reflex 没有显示优于低排队的额外收益,均匀模式也未证明显著改善正常素材的提交抖动。++Reflex 真实日志:`enable status=0 intervalUs=0 boost=0`;`disable status=0 successfulSleeps=252 successfulMarkers=1509`。没有逐子帧错误调用源帧 Sleep;无补帧标记围绕增强提交与呈现,不解释为游戏输入或仿真延迟。++## DLSS 补帧与刷新率++| 模式,24fps 输入 | 提交 fps | ready→return P50 / P95 ms | 间隔 P95 / P99 ms | 证据目录名 |+| --- | ---: | ---: | ---: | --- |+| 关闭,6X | 144.00 | 58.908 / 80.401 | 7.423 / 7.573 | off6 |+| 低排队,6X | 144.01 | 58.679 / 80.201 | 7.356 / 7.471 | low6 |+| 均匀呈现,6X | 144.00 | 60.689 / 80.205 | 7.348 / 7.494 | even6-final |+| Reflex 选择,实际低排队,6X | 144.00 | 58.498 / 80.213 | 7.356 / 7.458 | reflex6-final |+| 均匀呈现,2X | 48.00 | 77.549 / 81.394 | 21.389 / 21.502 | even2 |+| 均匀呈现,4X | 96.00 | 59.051 / 80.522 | 10.861 / 11.011 | even4 |+| 均匀呈现,6X + VSync | 100.00 | 53.971 / 77.182 | 11.558 / 11.965 | even6-vsync |++除最后一行外均允许撕裂。6X 的必要前后帧依赖和有界两批资源窗口保留,不能从低 GPU 占用推导为没有等待。几种模式的差别较小,不宣称 6X 大幅降延迟。++100Hz VSync 对照保持 6X 生成设置和媒体一倍速,实际提交约 100fps,最新定时日志累计记录 **445 张过期生成帧**、源预览跳帧 0。这是刷新率失配时的预览选择,不伪装成 144Hz 实际显示。普通 even4/even6-final/effects6 日志各有 1 张过期生成帧,不能称绝对零丢帧。上述过期计数是最新周期日志的累计值,不是去预热统计窗口内的精确计数。++有理数/其他帧率短测:23.976×6 → 143.85 提交 fps,25×2 → 50.00,30×4 → 120.00,60×2 → 120.00,媒体速率约 1。分别见 rate23976/rate25/rate30/rate60;不证明数小时漂移已验收。++NR + DLSS SR(1080p→1440p)+6X+均匀呈现:143.98 提交 fps,媒体速率 1.001,NR/SR/FG 真实启用。`effects6/engine.log` 中 Feature18、DLSS SR、DLSSG Create 均 `result=0x1 seh=0`,SR/FG Evaluate 同样成功,DLSSG `generatedCount=5`。该组合是运行回归,不是画质或 HDR 验收。++## 功能回归与发现的缺陷++- 设置与单测:18 种持久化组合、v1–5 迁移默认关闭、损坏文件保护、cadence reset;`preferences-final-result.txt` PASS。+- 实际 UI:三次真实启动,开启保存、关闭保存、重启恢复、1280×900/800×600、帮助展开与滚动可达,`ui-verified/result.json` PASS。已目视核对该目录大窗/小窗截图,画面非黑且新状态文本换行正常;小窗控件需滚动查看。被遮挡的一张截图跳过,不算视觉通过证据。+- 生命周期:无 FG 和 6X 分别完成暂停中关闭、暂停 seek、恢复、三模式现场切换、resize、关闭后继续播放和 stop,见 lifecycle/lifecycle6。+- 过载:注入每帧 80ms CPU 处理,无 FG/6X 均报告跳帧并维持媒体速率;关闭在 1 秒内生效,移除注入后恢复。无 FG 速率 0.970、跳过 33 帧;6X 速率约 0.922、跳过 32 帧。见 overload-final/overload6。不要拿包含过载及切换的整段汇总作稳态性能数据。+- 无音轨回归:chain-playback 保持墙钟播放速度,暂停/seek/恢复正常。+- NVENC 回归:chain-export 在 1/3/5 源帧时取消,保留 `.partial`;随后正常导出 12 源帧/12 编码帧,CreateInstance `status=0`。没有修改导出策略或加回结束逐帧扫描。+- XeSS 2X:真实提供方生成,新选项有效状态关闭、提供方继续调度,见 xess2。没有把应用 24fps Present 计数当作提供方最终显示帧率。+- 采集调度分支模拟:replay-off6-fixed/replay-low-fixed/replay-even6-fixed 通过。低排队无 FG 队列上限由实际 2 降为 1;这不是物理采集延迟测试。++本轮失败和修正保留原证据:++1. 最初把最小间隔设为完整一个输出周期,系统唤醒误差不断累积,6X 从 144 降到 136.67fps(even6-fixed)。改为媒体绝对时钟加 90% 最小间隔的有限追赶后恢复 144;不是修改 FPS 计数。+2. 控件状态 ID 1240 落入既有色彩控件范围,改为独立 ID 1150 后完成 UI 验收。+3. 采集分支 `fileAwaitingVideo` 不会被文件首帧路径清除,导致低排队上限未生效;改为显式采集条件。+4. 文件回放模拟缺少硬件到达节奏,却每批重置实时锚点。关闭也跑到约 1.895 倍速(replay-off6);仅模拟回放改用连续 PTS,真实硬件与远程串流的成对锚点保留,复测正常。+5. PrintWindow 截图有 GPU 黑区/残留,改成验证本应用遮挡状态后截屏;误捕获的遮挡图已删除。自动断言和目视截图证据分别记录。++## 构建、复现与文件++以下命令在隔离源码目录执行过;各单项限时不超过 240 秒。`B=E:/项目/Veyra/build/frame-pacing-20260918`、`T=E:/项目/Veyra/tests/frame-pacing-20260918`、`M=E:/项目/Veyra/tests/1.4.2beta/visible-scene.mkv` 为下列简写,运行时替换为完整路径。++```powershell+./scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/frame-pacing-20260918 -DependencyCache E:/项目/Veyra/build/fsr41-nvidia-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/frame-pacing-20260918 -DisplayVersion 1.4.2beta -Targets veyra,veyra_presentation_pacing_tests,veyra_scheduling_chain_tests+./scripts/test-frame-pacing.ps1 -Name even-final2 -Mode 1 -Seconds 10+./scripts/test-frame-pacing.ps1 -Name reflex6-final -Mode 2 -Multiplier 6 -Seconds 10+./scripts/test-frame-pacing.ps1 -Name effects6 -Mode 1 -Multiplier 6 -Seconds 6 -Scenario effects+./scripts/test-frame-pacing.ps1 -Name replay-even6-fixed -Mode 1 -Multiplier 6 -Seconds 6 -Scenario replay+./scripts/test-frame-pacing.ps1 -Name overload-final -Mode 1 -Seconds 3 -Scenario overload+python scripts/acceptance/analyze-frame-pacing.py E:/项目/Veyra/tests/frame-pacing-20260918+```++其余对照使用相同 runner 的 `-Mode -1/0/1/2`、`-Sync 0/1/2`、`-Multiplier 1/2/4/6`、`-Scenario legacy/lifecycle/xess` 与目录对应参数;帧率变体用 `-Media T/media/rate-*.mkv`。实际 UI 命令:`python scripts/acceptance/ui-frame-pacing.py B T/ui-verified M`。单测:`B/veyra_ui_contract_tests.exe T/preferences-final`;重跑必须使用新的目录,损坏配置用例会有意留下损坏文件。既有调度回归:`B/veyra_scheduling_chain_tests.exe T/media/silent24.mkv T/chain-playback playback` 及 `T/chain-export export`。均通过。++最终产品构建日志 `E:/项目/Veyra/logs/frame-pacing-20260918/build-closeout.log`,新增组合测试目标重编译日志 `build-effects-test.log`,均 exit 0。原始结果在 T 下各目录的 `result.txt`、`engine.log`、`snapshots.csv`;`summary.csv/json` 为分析脚本输出,保留中间方案与场景测试,本报告只引用明确列出的有效稳态对照。失败测试不进入汇总;功能 PASS 不自动证明性能有收益。++修改范围:PresentationSettings/ReflexSession 新增;EngineController/VideoPresenter/PresentSink 接入拥有线程、容量与生命周期;SettingsWindow/AppShell/UiPreferenceStore 接入设置和 v6 持久化;CMake、单元/集成测试、三个验收脚本及文档。NVAPI 最小 ABI 的来源固定为 NVIDIA/nvapi `87dca625e83fd89a983e19b904e5f3a580da90d2`,MIT 来源及改动记录在 THIRD_PARTY_NOTICES;没有引入 Streamline。++所有新构建、测试、下载及日志按 AGENTS 放在 `E:/项目/Veyra/`。源码 Git 不带 DLL、SDK、模型、媒体、截图或本机偏好;本轮未生成便携中间包/解压副本,tmp 为空,保留构建和必要验收证据。++## 未完成的验收与下一步++未执行 RTX30/40 实卡、真实采集设备、PS5、VRR/G-SYNC、60/120/144Hz 多显示器切换、HDR/fullscreen/OBS 组合、device-lost 和驱动失败故障注入、长时间播放或光子延迟测试。没有原用户此次逐帧记录,不能宣布其长时间抖动根因已解决。原生 Reflex+FG 的 out-of-band 标记与实际收益尚未完成,不能用回退模式的通过替代。++下一项唯一任务是让反馈者在 30/40 机器上做同素材、同 NR/SR、同倍率的关闭/低排队/均匀呈现对照,取得系统显示事件及音画证据;确认实际改善与延迟代价后再决定合并发布。diff --git a/docs/FRAME_PACING_EXECUTION_PLAN_2026-09-18.md b/docs/FRAME_PACING_EXECUTION_PLAN_2026-09-18.mdindex 38f205dd..cf0300f2 100644--- a/docs/FRAME_PACING_EXECUTION_PLAN_2026-09-18.md+++ b/docs/FRAME_PACING_EXECUTION_PLAN_2026-09-18.md@@ -2,7 +2,9 @@## 状态与目标-状态:方案,未施工。本轮只更新文档,不改播放代码、不构建、不更新内测包、不推送或发布。+状态:隔离实现与本机软件短测已交付,完整硬件验收未完成,结果见[验收报告](FRAME_PACING_ACCEPTANCE_2026-09-18.md)。开工存档 `6e69eeb` / `checkpoint/pre-frame-pacing-20260918`,施工分支 `codex/frame-pacing-20260918`,工作区 `E:/项目/Veyra/worktrees/frame-pacing-20260918`。未合并 main、推送、发布或重新打包。++实际范围相对原计划的差异:原生 Reflex 仅在无补帧时开放实验调用;FG 下所选 Reflex 显式回退低排队,保留倍率,不宣称 Reflex+FG 完成。XeSS/FSR 提供方路径不施加外部节奏。未迁移输入/呈现线程,未证明本次反馈的唯一根因。PresentMon ETW 权限不足,只有软件驻留与提交间隔实测;真实显示延迟和下文完整硬件矩阵仍待验证。依据用户最新要求:新增功能必须能完全关闭,并提供多个选项供用户权衡节奏与延迟。研发基线是 `codex/fsr41-nvidia-20260918` 当前工作树,包括尚未提交的 FSR4 回退和 1.4.2beta 改动;不能只从当前 HEAD 分支而遗漏这些改动。相关代码证据和官方资料见 [研究记录](FRAME_PACING_RESEARCH_2026-09-18.md)。@@ -19,7 +21,7 @@| 关闭 | 不启用本功能增加的节奏等待、队列限制、VSync 请求或 Reflex 调用;恢复关闭基线 | 仍有正常音画同步、补帧前后帧依赖及系统呈现延迟 || 低排队 | 根据真实 PTS、处理耗时和可用呈现容量安排工作,减少提前堆积;不额外缓存一整张源帧 | 以降低队列驻留为目标;输入断供时不能保证均匀输出,也不保证所有机器延迟下降 || 均匀呈现(前沿) | 在最终 Present 前按输出时间线安排提交,结合资源就绪与显示背压;迟到不成串追赶 | 允许有限余量换节奏,新增软件保留时间设计上最多一个输出帧间隔;不是端到端延迟上限 |-| NVIDIA Reflex(实验) | 通过核实的原生 NVAPI 实际控制 CPU/GPU 排队,使用正确的帧标记 | 必须通过直接 NGX、多帧和驱动兼容验证;不支持时不可选择,并显示原因 |+| NVIDIA Reflex(实验) | 无补帧时原生 NVAPI Sleep/markers;开启 FG 时显式回退低排队 | 本机接口成功、可关闭;未证明额外性能收益,多帧原生标记整合未完成 |总开关首次开启时默认选“低排队”,之后记住用户最后选择。上述“低排队”与现有改变 NR/SR 执行顺序的“低延迟模式”是不同设置,不能复用其字段或自动修改处理顺序。@@ -76,7 +78,7 @@ seek、源切换、resize、暂停恢复和 device lost 统一使旧任务失效保持直接 NGX,不引入 Streamline。先核对 `NvAPI_D3D_SetSleepMode`、`NvAPI_D3D_Sleep` 和 `NvAPI_D3D_SetLatencyMarker` 的设备、线程与帧边界合同,明确源帧和 MFG 子帧的 ID 对应。不能对每张子帧套用源帧限速,不能拿不存在的游戏 simulation/input 阶段制造延迟读数。-需要可复现证据证明接口成功、实际排队变化、模式可关闭、2X/4X/6X 稳定及音画正常后,才允许用户选择 Reflex。软件模式可以先交付,但 Reflex 未通过就记录未完成,不能把整个计划标记完成。50 系硬件 Flip Metering 是单独研究项,不凭型号或接口成功声称已经接入。+完整 Reflex+FG 原计划要求接口成功、实际排队变化、可关闭、2X/4X/6X 稳定及音画证据。本轮只交付无补帧的 Reflex 实验调用和有明确状态提示的 FG 回退,不能把整个 Reflex 计划标记完成。无补帧实测未显示优于低排队的额外收益。50 系硬件 Flip Metering 仍是单独研究项,不凭型号或接口成功声称已经接入。## 设置存储与改动范围@@ -89,14 +91,14 @@ seek、源切换、resize、暂停恢复和 device lost 统一使旧任务失效## 施工顺序与交付物-1. 保存当前实际工作树的源码存档,确认包含 FSR4 回退;随后开 `codex/frame-pacing-20260918` 隔离分支/工作区。不得回退现存改动,不推送、不发布。此步骤留到用户要求施工时执行。+1. 保存当前实际工作树的源码存档,确认包含 FSR4 回退;随后开 `codex/frame-pacing-20260918` 隔离分支/工作区。已完成,存档 `6e69eeb`;不推送、不发布。2. 增加低开销测量,取得关闭基线,并用 PresentMon/FrameView 对齐实际显示事件;区分计数窗口波动、输入断供、计算欠速、提交突发和显示失配。3. 按证据修复阻塞与迟到追赶,完成拥有权和取消合同;先验证关闭路径,再实施两个软件模式及显示同步。4. 接 UI 与独立持久化,完成开启/关闭/重启/跨后端切换回归。5. 完成 Reflex 原生接口试验,通过上述可行性关口后开放实验模式;采用成熟开源实现时记录来源、固定提交、许可和改动,不重复造已有可靠实现。6. 构建并完成相关自动和实机短测,记录真实失败与未覆盖硬件。用户要求测试包时再打包;不会仅凭本方案发布新版。-后续产物根目录统一为 `E:/项目/Veyra/`,各用 `build/frame-pacing-20260918`、`tests/frame-pacing-20260918`、`logs/frame-pacing-20260918`、`tmp/frame-pacing-20260918` 与 `worktrees/frame-pacing-20260918`。测试包按用户指定版本放 `test-packages/<版本>`。本轮未生成这些目录或产物。+本轮产物根目录统一为 `E:/项目/Veyra/`,已生成 `build/frame-pacing-20260918`、`tests/frame-pacing-20260918`、`logs/frame-pacing-20260918`、`tmp/frame-pacing-20260918` 与 `worktrees/frame-pacing-20260918`。未生成新测试包。## 验收与反证@@ -116,6 +118,6 @@ seek、源切换、resize、暂停恢复和 device lost 统一使旧任务失效关闭模式对比基线不能出现超出测量波动的新增延迟/吞吐回退;出现则先查开关是否真正旁路。均匀模式若只让 FPS 曲线更平、实际显示间隔未改善,判定收益未证实。Reflex 若未降低排队或导致音画/多帧回归,不宣传降低延迟。-主要风险是线程迁移破坏资源寿命、提供方重复 pacing、VRR 实际状态不可确认和外部限速叠加。呈现事件不是屏幕光子延迟测量,未做高速摄影或专用设备测量就不宣称测到端到端显示延迟。当前所有性能收益均待施工后验证。+主要风险是提供方重复 pacing、VRR 实际状态不可确认和外部限速叠加,本轮没有迁移线程。呈现事件不是屏幕光子延迟测量,未做高速摄影或专用设备测量就不宣称测到端到端显示延迟。已测软件数据和未测项目见验收报告。-下一项唯一施工任务:在保存当前源码状态后,录制一次关闭基线,确认最长断档发生在哪个环节。+下一项唯一验收任务:在反馈者 RTX30/40 机器上以同源、同效果、同倍率对照关闭/低排队/均匀呈现,取得显示事件和音画证据,再决定是否合入发布;本机短测不能证明原用户的长时间波动已经根治。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex ecdf8a42..f1096cf0 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,23 @@# Veyra 工作记录+## 2026-09-18 帧同步隔离实现与本机验收交付++在 `codex/frame-pacing-20260918` 完成默认关闭的低排队/均匀呈现/Reflex 实验、允许撕裂/VSync/自动、UI v6 独立持久化、请求与实际状态,以及相关回归。当前构建 `E:/项目/Veyra/build/frame-pacing-20260918/veyra.exe`。存档仍为 `6e69eeb` / `checkpoint/pre-frame-pacing-20260918`;没有合并 main、推送、发布或改动此前 beta 包。++完整命令、各选项延迟表、真实 Create/Evaluate/NVAPI 返回码、失败修复、修改文件范围及未覆盖项见 [FRAME_PACING_ACCEPTANCE_2026-09-18.md](FRAME_PACING_ACCEPTANCE_2026-09-18.md)。`build-isolated.ps1` 最终构建 `veyra,veyra_presentation_pacing_tests,veyra_scheduling_chain_tests` exit0,日志 `E:/项目/Veyra/logs/frame-pacing-20260918/build-closeout.log`;effects 组合测试追加编译 exit0,`build-effects-test.log`。单测、实际 UI 重启/关闭、九种模式显示组合、DLSS2/4/6、各帧率、NR+SR+6X、过载/seek/resize、XeSS 调度归属、文件模拟采集、无音轨播放和 NVENC 取消/12帧导出均有实际 PASS 证据,统一在 `E:/项目/Veyra/tests/frame-pacing-20260918`。++无补帧软件 ready→Present-return 中位数从81.548ms到约40.9ms,原因是提前增强从两批降至一批;不能解释为屏幕延迟降低40ms。6X各软件模式保持144提交fps,未证明显著延迟/抖动改善;100Hz VSync保持6X生成但只提交100fps,周期日志记录445张过期生成帧,不隐瞒丢弃。Reflex无补帧真实NVAPI开启/关闭status0,252次Sleep;FG下显式回退低排队,并没有完成原生Reflex+FG。++发现并修正:完整周期最小间隔累积唤醒误差导致6X降136.67fps;状态控件ID与色彩控件范围冲突;采集无FG单批上限误依赖文件启动标志;文件模拟采集每批重锚导致关闭模式也跑快。保留中间失败日志,不将模拟回放当实卡验收。截图遮挡/PrintWindow失真另行处理,最终本应用截图已目视核对,遮挡误图删除。++PresentMon ETW 因权限不足失败,显示事件及屏幕端到端延迟未测;未改变系统权限。30/40、实卡采集、PS5、VRR、多屏/HDR等未执行,完整原计划未全部验收。下一项唯一任务:反馈者同源同倍率的显示事件/音画对照,再决定是否合并。产物按规则集中,tmp为空,无新便携中间包;保留当前构建与必要证据,不新增专有SDK/运行库入Git。++## 2026-09-18 帧同步施工启动++用户授权先创建 Git 存档、更新文档、目标模式施工并验收各选项实际延迟。保存当前 FSR4 回退、HDR 和 beta 文档到 `6e69eeb`,标签 `checkpoint/pre-frame-pacing-20260918`;`git worktree add -b codex/frame-pacing-20260918 E:/项目/Veyra/worktrees/frame-pacing-20260918 HEAD` 创建隔离区。main 和旧 beta 包保持。更新 AGENTS、README、CURRENT_STATUS 与执行方案后开始代码工作,无 push/Release。++工具检查:Git 2.53.0.windows.2;全局 PATH 无 cmake,将使用既有 build-isolated.ps1 定位 Visual Studio 附带 CMake/Ninja。后续 build/tests/logs/tmp 使用 `E:/项目/Veyra/<用途>/frame-pacing-20260918`,依赖沿用上一轮经过核验的缓存路径。当前无新增运行时或 SDK 入 Git。验收待执行,不以此记录宣称完成。+## 2026-09-18 可关闭帧同步实施方案用户要求功能可完全关闭、提供多个选项,本轮新增 `docs/FRAME_PACING_EXECUTION_PLAN_2026-09-18.md` 并更新 CURRENT_STATUS。方案明确默认关闭、低排队/均匀呈现/Reflex 实验三种开启模式,显示同步独立选择;关闭撤销新增等待和 Reflex 配置,保留基础音画同步、资源安全与补帧必要依赖。30/40 的 6X 选择保留,Reflex 必须通过直接 NGX 实测后才开放,不以黑盒限帧冒充。diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 7c8c9d48..28f8fc01 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -7,6 +7,7 @@#include <condition_variable>#include <functional>#include "veyra/engine/EnhancementSettings.h"+#include "veyra/engine/PresentationSettings.h"#include "veyra/diagnostics/FrameMetrics.h"#include "veyra/engine/PreviewView.h"#include "veyra/sink/CaptureAudioSession.h"@@ -28,6 +29,9 @@ struct PlayerOptions { bool nr=false,sr=false,fg=false,realtime=true; uint32_t f};enum class TransportState { Empty, Opening, Playing, Paused, Ended, Stopping, Failed };struct PlayerSnapshot {+ PresentationSettings presentation, presentationEffective;+ uint64_t presentationRevision=0;+ std::wstring presentationStatus;TransportState transport=TransportState::Empty;uint64_t sessionId=0,rejectedRevision=0;float volume=1;bool muted=false,audioAvailable=false;std::wstring status=L"请打开视频或图片";@@ -92,6 +96,7 @@ public:~EngineController();bool idle()const;bool requestSettings(EnhancementSettings);+ void requestPresentation(PresentationSettings);void open(HWND video,const std::wstring& path,PlayerOptions options);#ifdef VEYRA_ENABLE_REMOTEPLAYvoid openRemotePlay(HWND, source::RemotePlayConnectDesc, PlayerOptions);@@ -118,6 +123,8 @@ private:void status(const std::wstring&,bool failed=false);mutable std::mutex mutex_;PlayerSnapshot snapshot_;+ PresentationSettings presentation_;+ uint64_t presentationRevision_=1;std::shared_ptr<FrameFlowWindow> activeFlow_;std::shared_ptr<source::RemotePlaySessionSource> activeRemote_;PreviewView previewView_;diff --git a/include/veyra/engine/PresentationSettings.h b/include/veyra/engine/PresentationSettings.hnew file mode 100644index 00000000..70f96068--- /dev/null+++ b/include/veyra/engine/PresentationSettings.h@@ -0,0 +1,28 @@+#pragma once+#include <algorithm>+#include <cstdint>+namespace veyra::engine {+enum class PacingMode : unsigned { LowQueue, Even, Reflex };+enum class DisplaySync : unsigned { Tearing, Vsync, Automatic };+struct PresentationSettings {+ bool enabled=false;+ PacingMode mode=PacingMode::LowQueue;+ DisplaySync display=DisplaySync::Tearing;+ bool operator==(const PresentationSettings&) const = default;+ bool valid()const{return unsigned(mode)<=2&&unsigned(display)<=2;}+};+// Media time remains the authority. Spacing adds at most one interval from+// the current decision; stale generated frames are discarded by the caller.+class PresentationCadence {+ int64_t last_=0;+public:+ void reset(){last_=0;}+ int64_t due(int64_t mediaDeadline,int64_t outputInterval)const{+ if(!last_)return mediaDeadline;+ // Bounded catch-up absorbs wakeup/Present jitter without moving the+ // media grid forward every frame. Never burst closer than 90% period.+ return std::max(mediaDeadline,last_+outputInterval-outputInterval/10);+ }+ void submitted(int64_t now){last_=now;}+};+}diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 18aa5b35..726013fd 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -4,6 +4,8 @@#include "veyra/pipeline/GpuPassUtils.h"#include "veyra/engine/PreviewView.h"#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/gfx/ReflexSession.h"+#include "veyra/engine/PresentationSettings.h"#include <chrono>namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }namespace veyra::pipeline { class EnhanceGraph; }@@ -15,6 +17,14 @@ public:bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&, bool captureCompatible=false);bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,bool referencesValid=true,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={});void close();+ PresentationSettings configurePresentation(gfx::D3D12DeviceContext&,PresentationSettings,bool fg,std::wstring& status);+ bool presentationReady(){return sink_.presentationReady();}+ uint64_t beginReflex(){return reflex_.begin();}+ void reflexFrame(uint64_t id){reflexFrame_=id;}+ bool reflexActive()const{return reflex_.active();}+ bool reflexDisablePending()const{return reflex_.disablePending();}+ bool pacingActive()const{return sink_.pacingActive();}+ uint64_t generation()const{return generation_;}// Explicit integration-test capture only; never called by playback/export.bool readPresentedFrameForTest(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,sink::RgbaImage&);// Test-only buffer reference for lossless HDR readback. Drains the private@@ -47,6 +57,8 @@ public:std::vector<diagnostics::GpuFrameTiming> takeGpuTimings(ID3D12Fence* fence){gpuTimer_.collect(presentationFence_?presentationFence_.Get():fence);return gpuTimer_.takeCompleted();}void recordGpuTimings(){gpuTimer_.recordCompleted();}private:+ gfx::ReflexSession reflex_;+ uint64_t reflexFrame_=0,generation_=0;Microsoft::WRL::ComPtr<ID3D12CommandQueue> presentationQueue_;Microsoft::WRL::ComPtr<ID3D12Fence> presentationFence_;HANDLE presentationEvent_=nullptr;diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.hindex ad775d04..23dbc347 100644--- a/include/veyra/gfx/PresentSink.h+++ b/include/veyra/gfx/PresentSink.h@@ -36,6 +36,7 @@ public:uint32_t width = 1280;uint32_t height = 720;bool vsync = true;+ bool waitable = false;bool xess = false;// AMD FSR frame generation: the provider creates the proxy swapchain.bool fsr = false;@@ -70,6 +71,9 @@ public:// Presents the current back buffer. Returns false on device-lost class// failures (caller must trigger recovery).bool present(Status& status);+ bool configurePacing(bool enabled,bool vsync);+ bool presentationReady();+ bool pacingActive()const{return pacing_;}void resize(uint32_t width, uint32_t height);@@ -126,6 +130,8 @@ private:UINT backBufferIndex_ = 0;bool closed_ = false;bool shutdownCalled_ = false;+ HANDLE latencyHandle_=nullptr;+ bool pacing_=false,capacityAcquired_=false;};} // namespace veyra::gfxdiff --git a/include/veyra/gfx/ReflexSession.h b/include/veyra/gfx/ReflexSession.hnew file mode 100644index 00000000..b390b0c3--- /dev/null+++ b/include/veyra/gfx/ReflexSession.h@@ -0,0 +1,54 @@+#pragma once+#include <windows.h>+#include <d3d12.h>+#include <cstdint>+#include <format>+#include "veyra/Log.h"+namespace veyra::gfx {+// Minimal ABI declarations checked against NVIDIA/nvapi public interfaces.+// Source: NVIDIA/nvapi 87dca625e83fd89a983e19b904e5f3a580da90d2 (MIT).+// Renamed subset and lifecycle integration; see THIRD_PARTY_NOTICES.md.+// No SDK header or runtime is distributed in the source tree.+class ReflexSession {+ struct SleepParams {uint32_t version;uint8_t low,boost;uint32_t interval;uint8_t markers,minQueue,reserved[30];};+ struct MarkerParams {uint32_t version;uint64_t frame;uint32_t type;uint64_t reserved0;uint8_t reserved[56];};+ static_assert(sizeof(SleepParams)==44&&sizeof(MarkerParams)==88);+ using Query=void*(__cdecl*)(uint32_t);+ using Init=int(__cdecl*)();+ using Set=int(__cdecl*)(IUnknown*,SleepParams*);+ using Sleep=int(__cdecl*)(IUnknown*);+ using Marker=int(__cdecl*)(IUnknown*,MarkerParams*);+ HMODULE module_=nullptr;ID3D12Device* device_=nullptr;+ Set set_=nullptr;Sleep sleep_=nullptr;Marker marker_=nullptr;Init unload_=nullptr;+ bool initialized_=false,active_=false,driverEnabled_=false;uint64_t next_=0,sleeps_=0,markers_=0;+public:+ ~ReflexSession(){close();}+ bool active()const{return active_;}+ bool disablePending()const{return driverEnabled_&&!active_;}+ void close(){disable();device_=nullptr;if(initialized_&&unload_)unload_();initialized_=false;if(module_)FreeLibrary(module_);module_=nullptr;set_=nullptr;sleep_=nullptr;marker_=nullptr;unload_=nullptr;driverEnabled_=false;}+ bool disable(){+ active_=false;+ if(driverEnabled_&&set_){SleepParams p{};p.version=sizeof(p)|(1u<<16);const int r=set_(device_,&p);log::info("reflex",std::format("disable status={} successfulSleeps={} successfulMarkers={}",r,sleeps_,markers_));if(r)return false;driverEnabled_=false;}+ return true;+ }+ bool enable(ID3D12Device* device){+ if(active_&&device_==device)return true;+ if(!disable())return false;+ close();device_=device;wchar_t system[MAX_PATH]{};GetSystemDirectoryW(system,MAX_PATH);+ const std::wstring path=std::wstring(system)+L"\\nvapi64.dll";+ module_=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32);+ auto query=module_?reinterpret_cast<Query>(GetProcAddress(module_,"nvapi_QueryInterface")):nullptr;+ if(!query)return false;+ auto init=reinterpret_cast<Init>(query(0x0150E828));unload_=reinterpret_cast<Init>(query(0xD22BDD7E));+ set_=reinterpret_cast<Set>(query(0xac1ca9e0));sleep_=reinterpret_cast<Sleep>(query(0x852cd1d2));marker_=reinterpret_cast<Marker>(query(0xd9984c05));+ if(!init||!set_||!sleep_||!marker_||!unload_)return false;+ const int initialized=init();initialized_=initialized==0;+ if(!initialized_){log::warn("reflex",std::format("initialize status={}",initialized));return false;}+ SleepParams p{};p.version=sizeof(p)|(1u<<16);p.low=1;p.markers=1;+ const int result=set_(device_,&p);log::info("reflex",std::format("enable status={} intervalUs=0 boost=0",result));+ sleeps_=markers_=0;return active_=driverEnabled_=result==0;+ }+ void mark(uint64_t frame,uint32_t type){if(!active_||!frame)return;MarkerParams p{};p.version=sizeof(p)|(1u<<16);p.frame=frame;p.type=type;const int r=marker_(device_,&p);if(r){log::warn("reflex",std::format("marker frame={} type={} status={}",frame,type,r));disable();}else ++markers_;}+ uint64_t begin(){if(!active_)return 0;const int r=sleep_(device_);if(r){log::warn("reflex",std::format("sleep status={}",r));disable();return 0;}++sleeps_;const auto frame=++next_;mark(frame,0);mark(frame,1);mark(frame,2);return frame;}+};+}diff --git a/scripts/acceptance/analyze-frame-pacing.py b/scripts/acceptance/analyze-frame-pacing.pynew file mode 100644index 00000000..2046068a--- /dev/null+++ b/scripts/acceptance/analyze-frame-pacing.py@@ -0,0 +1,66 @@+"""Summarize CPU observations, never physical display latency."""+import csv+import json+import pathlib+import re+import statistics+import sys++root = pathlib.Path(sys.argv[1]).resolve()+rows = []+++def percentile(values, fraction):+ values = sorted(values)+ return round(values[min(len(values)-1, int((len(values)-1)*fraction))], 3) if values else None+++for directory in sorted(root.iterdir()):+ log = directory / 'engine.log'+ result = directory / 'result.txt'+ if not log.is_file() or not result.is_file() or 'PASS clean stop' not in result.read_text(encoding='utf-8', errors='replace'):+ continue+ if 'FAIL ' in result.read_text(encoding='utf-8',errors='replace'):+ continue+ samples = []+ expired_generated = 0+ for line in log.read_text(encoding='utf-8', errors='replace').splitlines():+ expired = re.search(r'\bexpiredGenerated=(\d+)', line)+ if expired:+ expired_generated = int(expired.group(1))+ if '[pacing-sample]' in line:+ fields = dict(re.findall(r'(\w+)=([^ ]+)', line.split('[pacing-sample]', 1)[1]))+ samples.append(fields)+ if not samples:+ continue+ # Same 2-second warmup exclusion for every case, relative to first submission.+ threshold = int(samples[0]['end']) + 20_000_000+ samples = [s for s in samples if int(s['end']) >= threshold]+ if len(samples) < 2:+ continue+ ends = [int(s['end']) for s in samples]+ intervals = [(b-a)/10000 for a, b in zip(ends, ends[1:])]+ process = [(int(s['end'])-int(s['process']))/10000 for s in samples]+ ready = [(int(s['end'])-int(s['ready']))/10000 for s in samples if int(s['ready']) > 0]+ submit = [(int(s['end'])-int(s['begin']))/10000 for s in samples]+ snapshots = list(csv.DictReader((directory/'snapshots.csv').open(encoding='utf-8')))+ speed = ((float(snapshots[-1]['position'])-float(snapshots[0]['position'])) /+ (float(snapshots[-1]['wall'])-float(snapshots[0]['wall']))) if len(snapshots)>1 else 0+ row = dict(case=directory.name, samples=len(samples), generated=sum(s['generated']=='true' for s in samples),+ submitFps=round((len(ends)-1)*1e7/(ends[-1]-ends[0]), 2), mediaSpeed=round(speed, 3),+ intervalP50=percentile(intervals,.5), intervalP95=percentile(intervals,.95),+ intervalP99=percentile(intervals,.99), intervalMax=round(max(intervals),3),+ processToReturnP50=percentile(process,.5), processToReturnP95=percentile(process,.95),+ readyToReturnP50=percentile(ready,.5), readyToReturnP95=percentile(ready,.95),+ presentCpuP95=percentile(submit,.95), queueMax=max(int(s['queue']) for s in samples),+ finalSkipped=int(snapshots[-1]['skipped']), expiredGenerated=expired_generated)+ rows.append(row)+if not rows:+ raise SystemExit('No measurements')+with (root/'summary.csv').open('w', newline='', encoding='utf-8') as output:+ writer = csv.DictWriter(output, fieldnames=rows[0].keys())+ writer.writeheader()+ writer.writerows(rows)+(root/'summary.json').write_text(json.dumps({'units':'ms; software observations only; display unmeasured', 'cases':rows},indent=2), encoding='utf-8')+for row in rows:+ print(json.dumps(row))diff --git a/scripts/acceptance/ui-frame-pacing.py b/scripts/acceptance/ui-frame-pacing.pynew file mode 100644index 00000000..041b785c--- /dev/null+++ b/scripts/acceptance/ui-frame-pacing.py@@ -0,0 +1,142 @@+"""Own-process controls, persistence and layout acceptance; isolated build only."""+import ctypes as c+import ctypes.wintypes as w+import json+import os+import pathlib+import subprocess+import sys+import time+from PIL import ImageGrab++build, out, media = map(lambda p:pathlib.Path(p).resolve(), sys.argv[1:4])+assert build.name == 'frame-pacing-20260918', 'Use the isolated test build'+out.mkdir(parents=True, exist_ok=True)+u=c.WinDLL('user32', use_last_error=True)+u.SetProcessDpiAwarenessContext.argtypes=[w.HANDLE]+u.SetProcessDpiAwarenessContext(c.c_void_p(-4))+u.GetWindowThreadProcessId.argtypes=[w.HWND,c.POINTER(w.DWORD)]+u.GetClassNameW.argtypes=[w.HWND,w.LPWSTR,c.c_int]+u.GetDlgItem.argtypes=[w.HWND,c.c_int];u.GetDlgItem.restype=w.HWND+u.GetWindowRect.argtypes=[w.HWND,c.POINTER(w.RECT)]+u.GetParent.argtypes=[w.HWND];u.GetParent.restype=w.HWND+u.IsWindowEnabled.argtypes=[w.HWND]+u.IsWindowVisible.argtypes=[w.HWND]+u.SetForegroundWindow.argtypes=[w.HWND]+u.WindowFromPoint.argtypes=[w.POINT];u.WindowFromPoint.restype=w.HWND+u.GetAncestor.argtypes=[w.HWND,w.UINT];u.GetAncestor.restype=w.HWND+u.RedrawWindow.argtypes=[w.HWND,c.c_void_p,w.HANDLE,w.UINT]+u.SetWindowPos.argtypes=[w.HWND,w.HWND,c.c_int,c.c_int,c.c_int,c.c_int,w.UINT]+u.SendMessageTimeoutW.argtypes=[w.HWND,w.UINT,w.WPARAM,w.LPARAM,w.UINT,w.UINT,c.POINTER(c.c_size_t)]+callback=c.WINFUNCTYPE(w.BOOL,w.HWND,w.LPARAM)+u.EnumWindows.argtypes=[callback,w.LPARAM];u.EnumChildWindows.argtypes=[w.HWND,callback,w.LPARAM]+++def send(h,m,a=0,b=0):+ result=c.c_size_t()+ assert u.SendMessageTimeoutW(h,m,a,b,2,1500,c.byref(result)), 'UI timeout'+ return result.value+++def find(name,parent=None):+ found=[]+ @callback+ def visit(h,unused):+ pid=w.DWORD();u.GetWindowThreadProcessId(h,c.byref(pid))+ cls=c.create_unicode_buffer(80);u.GetClassNameW(h,cls,80)+ if pid.value==process.pid and cls.value==name:found.append(h)+ return True+ if parent:u.EnumChildWindows(parent,visit,0)+ else:u.EnumWindows(visit,0)+ return found[0] if found else None+++def wait(predicate):+ until=time.monotonic()+8+ while time.monotonic()<until:+ value=predicate()+ if value:return value+ assert process.poll() is None, 'Application exited'+ time.sleep(.05)+ raise AssertionError('UI condition timeout')+++def rect(h):+ r=w.RECT();assert u.GetWindowRect(h,c.byref(r))+ return [r.left,r.top,r.right,r.bottom]+++env=os.environ.copy();env['TEMP']=env['TMP']='E:/项目/Veyra/tmp/frame-pacing-20260918'+results=[]+process=None+try:+ # Real startup/close path, not smoke mode (which deliberately disables saves).+ for stage in ['configure','restart-on','restart-off']:+ env['VEYRA_LOG_FILE']=str(out/(stage+'.log'))+ process=subprocess.Popen([str(build/'veyra.exe'),str(media)],cwd=build,env=env,+ stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)+ main=wait(lambda:find('VeyraApp'))+ body=wait(lambda:find('VeyraInspectorBody',main))+ control=lambda ident:u.GetDlgItem(body,ident)+ wait(lambda:control(240))+ # Restore professional panel and select FG tab through real command handlers.+ send(main,0x111,115)+ send(main,0x111,231)+ time.sleep(.5)+ if stage=='configure':+ if send(control(240),0xf0):send(control(240),0xf5)+ assert send(control(240),0xf0)==0+ assert not u.IsWindowEnabled(control(241)) and not u.IsWindowEnabled(control(242))+ send(control(240),0xf5)+ for ident,value in [(241,1),(242,2)]:+ send(control(ident),0x14e,value);send(body,0x111,ident|(1<<16),control(ident))+ wait(lambda:'effective=true/1/2' in (out/(stage+'.log')).read_text(encoding='utf-8',errors='replace'))+ for width,height in [(1280,900),(800,600)]:+ u.SetWindowPos(main,None,20,20,width,height,0x14)+ time.sleep(.3)+ if not u.IsWindowVisible(body):send(main,0x111,229)+ wait(lambda:u.IsWindowVisible(body))+ for expanded in [False,True]:+ if expanded:send(control(221),0xf5)+ send(body,0x115,7) # SB_BOTTOM+ for unused in range(20):send(body,0x115,1) # body handles line scroll+ time.sleep(.3)+ boxes=[rect(control(i)) for i in [240,241,242,1150]]+ assert all(a[3]<=b[1] for a,b in zip(boxes,boxes[1:])), boxes+ viewport=rect(body)+ assert all(viewport[0]<=b[0] and b[2]<=viewport[2] for b in boxes), boxes+ # Compact drawers scroll; each control must be reachable,+ # not necessarily visible together in a 140-pixel viewport.+ for ident in [240,241,242,1150]:+ for unused in range(50):+ box=rect(control(ident));viewport=rect(body)+ if viewport[1]<=box[1] and box[3]<=viewport[3]:break+ send(body,0x115,0 if box[1]<viewport[1] else 1)+ else:raise AssertionError(('Unreachable control',ident,viewport,box))+ assert u.IsWindowVisible(control(ident))+ u.SetWindowPos(main,c.c_void_p(-1),0,0,0,0,0x43)+ u.SetForegroundWindow(main)+ u.RedrawWindow(main,None,None,0x185)+ time.sleep(.5)+ bounds=rect(main)+ points=[w.POINT(bounds[0]+10,bounds[1]+10),w.POINT(bounds[2]-10,bounds[3]-10)]+ if all(u.GetAncestor(u.WindowFromPoint(point),2)==main for point in points):+ image=ImageGrab.grab(bbox=tuple(bounds),all_screens=True).convert('RGB')+ image.save(out/f'layout-{width}-{expanded}.png')+ else:+ print('SKIP screenshot: test window is occluded')+ results.append(dict(width=width,height=height,helpExpanded=expanded,boxes=boxes))+ if expanded:send(control(221),0xf5)+ else:+ assert send(control(241),0x147)==1 and send(control(242),0x147)==2+ assert send(control(240),0xf0)==(1 if stage=='restart-on' else 0), stage+ if stage=='restart-on':+ send(control(240),0xf5)+ wait(lambda:'effective=false/' in (out/(stage+'.log')).read_text(encoding='utf-8',errors='replace'))+ assert not u.IsWindowEnabled(control(241))+ send(main,0x10)+ assert process.wait(timeout=15)==0+ (out/'result.json').write_text(json.dumps(dict(passed=True,restartOn=True,restartOff=True,layout=results),indent=2),encoding='utf-8')+ print('PASS actual UI controls, applied state, restart-on, restart-off, help expansion and two window sizes')+finally:+ if process and process.poll() is None:process.kill();process.wait()diff --git a/scripts/test-frame-pacing.ps1 b/scripts/test-frame-pacing.ps1new file mode 100644index 00000000..8f24e2e3--- /dev/null+++ b/scripts/test-frame-pacing.ps1@@ -0,0 +1,32 @@+[CmdletBinding()]+param(+ [string]$Build='E:/项目/Veyra/build/frame-pacing-20260918',+ [string]$Media='E:/项目/Veyra/tests/1.4.2beta/visible-scene.mkv',+ [string]$Output='E:/项目/Veyra/tests/frame-pacing-20260918',+ [string]$PresentMon='E:/项目/Veyra/downloads/PresentMon-2.5.1-x64.exe',+ [string]$Name='off', [int]$Mode=-1,[int]$Sync=0,[int]$Multiplier=1,[int]$Seconds=10,[string]$Scenario='normal',+ [switch]$CaptureDisplay+)+$ErrorActionPreference='Stop'+$dir=Join-Path $Output $Name+New-Item -ItemType Directory -Force $dir | Out-Null+$env:TEMP='E:/项目/Veyra/tmp/frame-pacing-20260918';$env:TMP=$env:TEMP+$monitorArgs=@('--process_name','veyra_presentation_pacing_tests.exe','--output_file',('"'+(Join-Path $dir 'presentmon.csv')+'"'),'--no_console_stats','--qpc_time','--timed',($Seconds+35),'--terminate_after_timed','--session_name',('VeyraPacing'+$PID))+$monitor=$null+if($CaptureDisplay){$monitor=Start-Process -FilePath $PresentMon -ArgumentList $monitorArgs -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $dir 'presentmon.stdout') -RedirectStandardError (Join-Path $dir 'presentmon.stderr')}+try {+ Start-Sleep -Milliseconds 700+ $testArgs=@($Media,$dir,$Mode,$Sync,$Multiplier,$Seconds,$Scenario)|ForEach-Object{'"'+$_+'"'}+ $test=Start-Process -FilePath (Join-Path $Build 'veyra_presentation_pacing_tests.exe') -ArgumentList $testArgs -WorkingDirectory $Build -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $dir 'result.txt') -RedirectStandardError (Join-Path $dir 'stderr.txt')+ $handle=$test.Handle+ if(!$test.WaitForExit(240000)){$test.Kill();throw 'Pacing acceptance exceeded 240 seconds'}+ $exit=$test.ExitCode+ # End only this test's ETW session; PresentMon flushes its pending events.+ if($monitor -and !$monitor.HasExited){+ & $PresentMon --session_name ('VeyraPacing'+$PID) --terminate_existing_session | Out-Null+ if(!$monitor.WaitForExit(10000)){$monitor.Kill();throw 'PresentMon did not finish'}+ }+ Get-Content (Join-Path $dir 'result.txt')+ if($CaptureDisplay){Get-Content (Join-Path $dir 'presentmon.stderr')}+ if($exit -ne 0){throw "Acceptance exit=$exit"}+} finally {if($monitor -and !$monitor.HasExited){$monitor.Kill()}}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 3b57803c..f7f5fbde 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -133,8 +133,14 @@ void EngineController::startExport(const std::wstring& input,const std::wstring&const auto frozen=opts.snapshot();const int audioStream=opts.audioStreamIndex;post([this,input,output,frozen,audioStream,hevc]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);auto options=PlayerOptions::from(frozen);options.audioStreamIndex=audioStream;bool ok=exportVideo(input,output,options,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();});}+void EngineController::requestPresentation(PresentationSettings settings){+ if(!settings.valid())return;+ std::lock_guard lock(mutex_);if(presentation_==settings)return;+ presentation_=settings;++presentationRevision_;+}PlayerSnapshot EngineController::snapshot()const{std::lock_guard lock(mutex_);auto copy=snapshot_;copy.volume=volume_;copy.muted=muted_;+ copy.presentation=presentation_;const bool playing=copy.running&&!copy.image&©.transport==TransportState::Playing;if(activeFlow_)copy.metrics.flow=activeFlow_->snapshot(monotonic100ns());copy.fgBudgetLimited=playing&©.metrics.flow.lastFgRejected100ns>0&&monotonic100ns()-copy.metrics.flow.lastFgRejected100ns<10000000;@@ -172,7 +178,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s(void)remoteRequest;const bool isRemote=false;#endifconst bool isCapture=physicalCapture||options.captureReplayForTest||isRemote;- const bool pairAnchoredLive=physicalCapture||options.captureReplayForTest||isRemote;+ // File replay has no hardware arrival clock; retain its continuous PTS anchor.+ const bool pairAnchoredLive=physicalCapture||isRemote;const bool useLiveFgAdmission=!options.captureReplayDisableFgAdmissionForTest;source::IFrameSource* activeSource=physicalCapture?static_cast<source::IFrameSource*>(&captureSource):&source;#ifdef VEYRA_ENABLE_REMOTEPLAY@@ -470,6 +477,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sstd::atomic<uint64_t> presentationGeneration{0};std::unique_ptr<LiveGpuScheduler> liveScheduler;struct CompletionWatch {+ uint64_t reflexFrame=0;pipeline::EnhanceGraph::FrameOutputs output;std::shared_ptr<FrameFlowWindow> flow;Clock::time_point processStart;@@ -562,8 +570,35 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,scollectTimings();};if(!isImage){liveScheduler=std::make_unique<LiveGpuScheduler>();veyra::log::info("scheduler",std::format("single GPU owner thread={} capacity=2 source={} (bounded enhanced lookahead)",GetCurrentThreadId(),isCapture?"live":"file"));}- auto drainLivePresentation=[&]{if(liveScheduler){++presentationDrains;liveScheduler->cancel();pollCompletions();pendingCompletions.clear();}};- auto advanceLive=[&]{if(liveScheduler){pollCompletions();if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0)liveScheduler->cancel();else liveScheduler->advance(host100ns());}};+ PresentationCadence cadence;+ PresentationSettings presentationEffective;+ uint64_t pacingRevision=0,presenterGeneration=0;+ auto applyPresentation=[&]{+ PresentationSettings requested;uint64_t revision;+ {std::lock_guard lock(mutex_);requested=presentation_;revision=presentationRevision_;}+ if(revision==pacingRevision&&presenterGeneration==presenter.generation()){+ if(presentationEffective.enabled&&presentationEffective.mode==PacingMode::Reflex&&!presenter.reflexActive()){+ presentationEffective.mode=PacingMode::LowQueue;+ std::lock_guard lock(mutex_);snapshot_.presentationEffective=presentationEffective;snapshot_.presentationStatus=presenter.reflexDisablePending()?L"Reflex 调用及驱动撤销失败;请关闭视频后重试":L"Reflex 调用失败,当前使用低排队;详见日志";+ }+ if(presentationEffective.enabled&&!presenter.pacingActive()){+ presentationEffective.enabled=false;+ std::wstring message;+ presentationEffective=presenter.configurePresentation(ctx,presentationEffective,options.fg,message);+ cadence.reset();+ std::lock_guard lock(mutex_);snapshot_.presentationEffective=presentationEffective;snapshot_.presentationStatus=L"显示队列等待失败;"+message;+ }+ return;+ }+ if(isImage)requested.enabled=false;+ std::wstring message;+ presentationEffective=presenter.configurePresentation(ctx,requested,options.fg,message);+ pacingRevision=revision;presenterGeneration=presenter.generation();cadence.reset();+ {std::lock_guard lock(mutex_);snapshot_.presentationEffective=presentationEffective;snapshot_.presentationRevision=revision;snapshot_.presentationStatus=message;}+ veyra::log::info("pacing",std::format("revision={} requested={}/{}/{} effective={}/{}/{}",revision,requested.enabled,unsigned(requested.mode),unsigned(requested.display),presentationEffective.enabled,unsigned(presentationEffective.mode),unsigned(presentationEffective.display)));+ };+ auto drainLivePresentation=[&]{cadence.reset();if(liveScheduler){++presentationDrains;liveScheduler->cancel();pollCompletions();pendingCompletions.clear();}};+ auto advanceLive=[&]{applyPresentation();if(liveScheduler){pollCompletions();if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0){liveScheduler->cancel();cadence.reset();}else liveScheduler->advance(host100ns());}};auto waitLive=[&]{const auto due=liveScheduler?liveScheduler->wakeAt():0;deadlineWait.slice(due>host100ns()?std::min(1.0,double(due-host100ns())/10000):1.0);};uint64_t metricsRevision=options.settings.revision,metricsEpoch=0,metricsWindowEpoch=0,statsSourceBase=0;uint64_t slotWaitBase=ring.cpuWaitCount(),submitBase=ring.submitCount();double slotWaitMsBase=ring.cpuWaitMilliseconds();@@ -835,7 +870,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// Backpressure before reading the capacity-one source mailbox:// when a lease frees we consume the newest available sample.if(liveScheduler&&!transaction){- const auto enhancementPending=[&]{return isCapture&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)&&!pendingCompletions.empty();};+ const auto enhancementPending=[&]{+ if(presentationEffective.enabled&&!options.fg&&(isCapture||!fileAwaitingVideo)&&liveScheduler->occupancy()>=1)return true;+ return isCapture&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)&&!pendingCompletions.empty();+ };const auto leaseWaitStart=Clock::now();while((liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable()||enhancementPending())&&!stop_&&(!paused_||seekPreviewPending)&&!liveScheduler->failed()){advanceLive();if(seekSeconds_>=0)break;@@ -1015,6 +1053,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// exercises missed deadlines and recovery without changing// settings/history or inventing GPU execution timestamps.wchar_t testWork[16]{};+ const auto currentReflexFrame=(!paused_&&!isImage)?presenter.beginReflex():0;if(!isImage&&GetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",testWork,16))std::this_thread::sleep_for(std::chrono::milliseconds(std::clamp(_wtoi(testWork),0,150)));bool processed=false;{processWaitBase=ring.cpuWaitCount();processWaitMsBase=ring.cpuWaitMilliseconds();processSubmitBase=ring.submitCount();processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0,admitFg);processSlotWaitMs=ring.cpuWaitMilliseconds()-processWaitMsBase;}previewSkipSinceProcess=false;@@ -1125,6 +1164,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto timeline=liveTimeline;const uint64_t jobGeneration=presentationGeneration.load();auto watch=std::make_shared<CompletionWatch>();watch->output=out;watch->flow=frameFlow;watch->processStart=processStart;watch->real=!rereadCached;+ watch->reflexFrame=currentReflexFrame;pendingCompletions.push_back(watch);struct LiveStepState {unsigned next=0,handled=0,remaining=0;bool readyReported=false;@@ -1180,9 +1220,19 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(audioStarted)audioPipe.videoReady(itemPtsMs);if(nowMs()+.25<itemPtsMs)return {State::Pending,now+std::min<int64_t>(10000,int64_t((itemPtsMs-nowMs())*10000))};}+ const auto optionalNow=host100ns();+ if(presentationEffective.enabled){+ const auto interval=std::max<int64_t>(1,int64_t(sourceIntervalMs*10000)/std::max(1u,options.fg?options.fgMultiplier:1u));+ const auto mediaDeadline=isCapture?timeline.deadline(item.pts100ns):fileAwaitingVideo?optionalNow:optionalNow+int64_t((itemPtsMs-nowMs())*10000);+ const auto due=presentationEffective.mode==PacingMode::Even?cadence.due(mediaDeadline,interval):mediaDeadline;+ if(generated&&presentationEffective.mode==PacingMode::Even&&due>mediaDeadline+interval){++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();continue;}+ if(optionalNow<due)return {State::Pending,due};+ if(!presenter.presentationReady())return {State::Pending,optionalNow+2000};+ }const auto waited=elapsedMs(*s.deadlineStart);s.deadlineStart.reset();s.waitMs+=waited;flow->cpu(diagnostics::CpuStage::DeadlineWait,waited,host100ns());const auto begin=Clock::now();const auto before=presenter.submittedCount();const auto presentSlotWaitBefore=presenter.cpuWaitMilliseconds(ring);+ presenter.reflexFrame(watch->reflexFrame);if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView()))return {State::Failed};item.lease->consumerFence=presenter.consumerFenceValue(ring.lastSignaledValue());const bool didPresent=presenter.submittedCount()>before;s.blit=presenter.blitTiming(ctx.fence());const auto elapsed=elapsedMs(begin);s.presentMs+=elapsed;flow->cpu(diagnostics::CpuStage::Present,elapsed,host100ns());@@ -1195,6 +1245,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,slivePresentService.add(std::max(0.0,elapsed-(presenter.cpuWaitMilliseconds(ring)-presentSlotWaitBefore)));}if(didPresent){+ cadence.submitted(optionalNow);+ if(veyra::log::verboseFrameLogs())veyra::log::info("pacing-sample",std::format("mode={} enabled={} sync={} pts={} begin={} end={} ready={} process={} generated={} queue={} lateMs={:.3f}",unsigned(presentationEffective.mode),presentationEffective.enabled,unsigned(presentationEffective.display),item.pts100ns,optionalNow,host100ns(),watch->frameReadyObserved[s.next],std::chrono::duration_cast<std::chrono::nanoseconds>(watch->processStart.time_since_epoch()).count()/100,generated,liveScheduler->occupancy(),isCapture?double(optionalNow-timeline.deadline(item.pts100ns))/10000:fileAwaitingVideo?0:nowMs()-itemPtsMs));traceFrame(diagnostics::TraceKind::Present,item.identity,batch.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsed);if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",batch.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));}diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 85c03482..f9e5f986 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -6,6 +6,7 @@namespace veyra::engine {bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph,bool captureCompatible) {close();+ ++generation_;Status st=Status::Ok;if(graph.fgEnabled()&&!graph.xessEnabled()&&!graph.fsrEnabled()){D3D12_COMMAND_QUEUE_DESC desc{};desc.Type=D3D12_COMMAND_LIST_TYPE_DIRECT;@@ -19,6 +20,7 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enhauto* queue=presentationQueue_?presentationQueue_.Get():ctx.directQueue();gpuTimer_.initialize(ctx.device(),queue);window_=window;RECT rc{};GetClientRect(window,&rc);gfx::PresentSink::Desc d;d.targetWindow=window;d.width=std::max(1L,rc.right);d.height=std::max(1L,rc.bottom);d.vsync=false;+ d.waitable=!GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_SWAPCHAIN",nullptr,0);d.hdr=graph.hdrOutput();d.hdr10=graph.hdr10Output();d.xess=graph.xessEnabled();d.fsr=graph.fsrEnabled();d.renderWidth=graph.workWidth();d.renderHeight=graph.workHeight();d.captureCompatible=captureCompatible;d.fgMultiplier=graph.fgMultiplier();lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=false;lastFsrFrame_={};lastFsrIdentity_={};fsrWasEnabled_=false;if(!sink_.initialize(ctx.device(),queue,d,st))return false;std::vector<uint8_t> vs,ps;@@ -153,7 +155,9 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());lastBuffer_=backBufferIndex;hasPresented_=true;if(presentationQueue_)graph.presentationSubmitted(slot,fence,ring.lastSignaledValue());const auto dxgiStart=std::chrono::steady_clock::now();+ reflex_.mark(reflexFrame_,3);reflex_.mark(reflexFrame_,4);const bool presented=sink_.present(st);+ reflex_.mark(reflexFrame_,5);reflexFrame_=0;const auto presentEnd=std::chrono::steady_clock::now();if(presentEnd>=nextCostLog_){nextCostLog_=presentEnd+std::chrono::seconds(1);@@ -171,11 +175,29 @@ bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx:return SUCCEEDED(sink_.swapChain()->GetBuffer(lastBuffer_,IID_PPV_ARGS(&buffer)))&&sink::readRgba8(ctx,ring,buffer.Get(),image);}void VideoPresenter::close(){+ reflex_.close();reflexFrame_=0;if(presentationRing_.initialized())presentationRing_.drainQueue();hasPresented_=false;gpuTimer_.close();rtvs_.Reset();pass_={};sink_.shutdown();presentationRing_.shutdown();presentationFence_.Reset();presentationQueue_.Reset();if(presentationEvent_){CloseHandle(presentationEvent_);presentationEvent_=nullptr;}}+PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceContext& ctx,PresentationSettings requested,bool fg,std::wstring& status){+ const bool reflexDisabled=reflex_.disable();reflexFrame_=0;+ auto effective=requested;+ if(!reflexDisabled){effective.enabled=false;sink_.configurePacing(false,false);status=L"Reflex 驱动状态撤销失败;应用等待已停用,请关闭视频后重试";return effective;}+ if(!requested.enabled){const bool restored=sink_.configurePacing(false,false);status=restored?L"帧同步已关闭":L"应用等待已关闭,但显示队列恢复失败;请关闭视频后重试";return effective;}+ if(xessActive()||fsrActive()){effective.enabled=false;sink_.configurePacing(false,false);status=L"当前由补帧提供方调度,帧同步选项暂不生效";return effective;}+ if(!sink_.configurePacing(true,requested.display!=DisplaySync::Tearing)){effective.enabled=false;status=L"显示队列控制不可用,已回退原呈现方式";return effective;}+ if(requested.mode==PacingMode::Reflex){+ // Generated outputs need separately validated out-of-band markers.+ if(fg||!reflex_.enable(ctx.device())){effective.mode=PacingMode::LowQueue;status=fg?L"补帧运行:Reflex 暂用低排队(保留补帧倍率)":L"Reflex 初始化失败,已回退低排队";return effective;}+ }+ status=effective.mode==PacingMode::Reflex?L"NVIDIA Reflex · 实验":effective.mode==PacingMode::Even?L"均匀呈现":L"低排队";+ if(requested.display==DisplaySync::Automatic)status+=L" · 自动:垂直同步(VRR 状态未知)";+ else if(requested.display==DisplaySync::Vsync)status+=L" · 垂直同步";+ else status+=L" · 允许撕裂";+ return effective;+}Microsoft::WRL::ComPtr<ID3D12Resource> VideoPresenter::presentedResourceForTest() {Microsoft::WRL::ComPtr<ID3D12Resource> buffer;if(presentationQueue_&&!presentationRing_.drainQueue())return buffer;diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cppindex 255f6bf0..442c374e 100644--- a/src/gfx/PresentSink.cpp+++ b/src/gfx/PresentSink.cpp@@ -119,6 +119,7 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,// external capture API. Neither mode changes the pixel format.scd.SwapEffect = desc.captureCompatible ? DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL : DXGI_SWAP_EFFECT_FLIP_DISCARD;scd.Flags = tearingSupported_ ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;+ if(desc.waitable&&!desc.xess&&!desc.fsr)scd.Flags|=DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;ComPtr<IDXGISwapChain1> swapChain1;// Backend switch bookkeeping. A retained AMD proxy and a live XeSS wrapper@@ -198,8 +199,15 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,}}if (!swapChain_) {- if (FAILED(factory_->CreateSwapChainForHwnd(queue, hwnd_, &scd, nullptr, nullptr, &swapChain1))) {- log::error("present", "CreateSwapChainForHwnd failed");+ HRESULT created=factory_->CreateSwapChainForHwnd(queue, hwnd_, &scd, nullptr, nullptr, &swapChain1);+ if(FAILED(created)&&(scd.Flags&DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT)){+ log::warn("pacing",std::format("waitable swapchain unavailable hr=0x{:X}; retrying baseline",unsigned(created)));+ scd.Flags&=~DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;+ swapChain1.Reset();+ created=factory_->CreateSwapChainForHwnd(queue,hwnd_,&scd,nullptr,nullptr,&swapChain1);+ }+ if (FAILED(created)) {+ log::error("present",std::format("CreateSwapChainForHwnd failed hr=0x{:X}",unsigned(created)));status = Status::WindowFailure;return false;}@@ -237,6 +245,10 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,}if(actual.SwapEffect!=scd.SwapEffect)log::warn("present",std::format("swapchain mode negotiated requested={} actual={} (compatible flip model)",unsigned(scd.SwapEffect),unsigned(actual.SwapEffect)));swapChainFlags_=actual.Flags;+ if(actual.Flags&DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT){+ latencyHandle_=swapChain_->GetFrameLatencyWaitableObject();+ if(!configurePacing(false,desc.vsync))log::warn("pacing","baseline latency configuration failed; playback remains available");+ }tearingSupported_=tearingSupported_&&(actual.Flags&DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING)!=0;log::info("present", std::format("present-sink: window {}x{} swapEffect={} buffers=3 vsync={} tearing={} captureCompatible={} (capture not verified)",width_, height_, actual.SwapEffect==DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL?"flip-sequential":"flip-discard", desc_.vsync ? 1 : 0, tearingSupported_ ? 1 : 0, desc.captureCompatible));@@ -292,6 +304,7 @@ ID3D12Resource* PresentSink::currentBackBuffer(uint32_t* acquiredIndex)bool PresentSink::present(Status& status){+ capacityAcquired_=false;xessFailed_=false;fsrFailed_=false;const UINT syncInterval = desc_.vsync ? 1 : 0;@@ -348,6 +361,21 @@ bool PresentSink::present(Status& status)return false;}+bool PresentSink::configurePacing(bool enabled,bool vsync){+ if(xess_||fsr_){pacing_=false;desc_.vsync=false;return !enabled;}+ const HRESULT hr=latencyHandle_?swapChain_->SetMaximumFrameLatency(enabled?1:3):enabled?E_NOTIMPL:S_OK;+ log::info("pacing",std::format("DXGI enabled={} maximumLatency={} vsync={} hr=0x{:X}",enabled,enabled?1:3,enabled&&vsync,unsigned(hr)));+ pacing_=enabled&&SUCCEEDED(hr);desc_.vsync=pacing_&&vsync;capacityAcquired_=false;+ return SUCCEEDED(hr);+}+bool PresentSink::presentationReady(){+ if(!pacing_||!latencyHandle_||capacityAcquired_)return true;+ const auto result=WaitForSingleObject(latencyHandle_,0);+ if(result==WAIT_OBJECT_0)capacityAcquired_=true;+ if(result==WAIT_FAILED){log::warn("pacing",std::format("DXGI capacity wait failed error={}",GetLastError()));configurePacing(false,false);return true;}+ return capacityAcquired_;+}+bool PresentSink::waitForQueueIdle(){if (queue_ == nullptr || device_ == nullptr) return true;@@ -399,6 +427,8 @@ void PresentSink::resize(uint32_t width, uint32_t height)void PresentSink::shutdown(){+ if(latencyHandle_){CloseHandle(latencyHandle_);latencyHandle_=nullptr;}+ pacing_=false;capacityAcquired_=false;// Dependency order (s10, proven by the 0x87D matrix): backbuffers ->// swapchain -> window -> factory. The window must OUTLIVE the swapchain:// with the D3D12 debug layer active, releasing a flip swapchain whosediff --git a/tests/integration/PresentationPacingTests.cpp b/tests/integration/PresentationPacingTests.cppnew file mode 100644index 00000000..d84cd3dd--- /dev/null+++ b/tests/integration/PresentationPacingTests.cpp@@ -0,0 +1,75 @@+#include "veyra/engine/EngineController.h"+#include "veyra/Log.h"+#include <filesystem>+#include <fstream>+#include <iostream>+#include <chrono>+#include <thread>+int wmain(int argc,wchar_t** argv){+ using namespace veyra::engine;using Clock=std::chrono::steady_clock;+ // media, evidence directory, mode(-1=off), display(0..2), multiplier, seconds, lifecycle/replay/xess+ if(argc<7)return 2;+ const int mode=_wtoi(argv[3]),display=_wtoi(argv[4]),multiplier=_wtoi(argv[5]),seconds=std::clamp(_wtoi(argv[6]),3,120);+ if(mode< -1||mode>2||display<0||display>2)return 2;+ const std::wstring scenario=argc>7?argv[7]:L"";+ if(scenario==L"legacy"){if(mode!=-1)return 2;SetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_SWAPCHAIN",L"1");}+ std::filesystem::path dir=argv[2];std::filesystem::create_directories(dir);+ SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");+ veyra::Logger::instance().openFile((dir/L"engine.log").wstring());veyra::Logger::instance().setConsoleEnabled(false);+ if(FAILED(CoInitializeEx(nullptr,COINIT_MULTITHREADED)))return 2;+ HWND window=CreateWindowExW(0,L"STATIC",L"Veyra pacing acceptance",WS_OVERLAPPEDWINDOW|WS_VISIBLE,40,40,1280,760,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);+ if(!window)return 2;+ MONITORINFOEXW monitor{};monitor.cbSize=sizeof(monitor);GetMonitorInfoW(MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST),&monitor);+ DEVMODEW dm{};dm.dmSize=sizeof(dm);EnumDisplaySettingsW(monitor.szDevice,ENUM_CURRENT_SETTINGS,&dm);+ std::cout<<"display="<<dm.dmPelsWidth<<"x"<<dm.dmPelsHeight<<" refreshHz="<<dm.dmDisplayFrequency<<std::endl;+ int failures=0;auto check=[&](bool value,const char* name){std::cout<<(value?"PASS ":"FAIL ")<<name<<std::endl;failures+=!value;};+ {+ EngineController engine;engine.setVolume(0,true);+ PresentationSettings p{mode>=0,PacingMode(std::max(0,mode)),DisplaySync(display)};engine.requestPresentation(p);+ EnhancementSettings effects;effects.multiplier=unsigned(multiplier);if(scenario==L"xess")effects.frameGenerationBackend=FrameGenerationBackend::XeSS;+ if(scenario==L"effects"){effects.nr=true;effects.sr=true;effects.srTarget=veyra::pipeline::SrTarget::Qhd;}+ auto options=PlayerOptions::from(effects);options.captureReplayForTest=scenario==L"replay";+ engine.open(window,argv[1],options);+ auto pump=[] {MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}};+ auto wait=[&](auto predicate,int ms=15000){auto end=Clock::now()+std::chrono::milliseconds(ms);while(Clock::now()<end){pump();auto s=engine.snapshot();if(s.failed)return false;if(predicate(s))return true;std::this_thread::sleep_for(std::chrono::milliseconds(2));}return false;};+ check(wait([](auto& s){return s.frames>10;}),"first frames");+ std::ofstream samples(dir/L"snapshots.csv");samples<<"wall,position,frames,generated,lateMs,queueReadyMs,presentMs,skipped,effective,mode,sync,revision\n";+ const auto start=Clock::now();auto last=engine.snapshot();const auto first=last;+ while(Clock::now()-start<std::chrono::seconds(seconds)&&!last.failed){+ pump();last=engine.snapshot();samples<<std::chrono::duration<double>(Clock::now()-start).count()<<','<<last.position<<','<<last.frames<<','<<last.generated<<','<<last.lateMs<<','<<last.schedulingWaitP95Ms<<','<<last.presentCpuP95Ms<<','<<last.previewSkipped<<','<<last.presentationEffective.enabled<<','<<unsigned(last.presentationEffective.mode)<<','<<unsigned(last.presentationEffective.display)<<','<<last.presentationRevision<<'\n';+ std::this_thread::sleep_for(std::chrono::milliseconds(50));+ }+ const auto speed=(last.position-first.position)/std::chrono::duration<double>(Clock::now()-start).count();+ std::cout<<"mediaSpeed="<<speed<<" processedDelta="<<last.frames-first.frames<<std::endl;+ check(!last.failed&&last.frames>first.frames+10&&speed>.8&&speed<1.2,"sustained playback at media speed");+ if(multiplier>1)check(last.fgActive&&last.generated>0,"real provider generated frames");+ if(scenario==L"effects")check(last.nrActive&&last.srActive&&last.nrEvaluated>first.nrEvaluated,"NR and SR remain active with pacing");+ if(mode>=0&&scenario!=L"xess")check(last.presentationEffective.enabled,"optional pacing active");+ if(mode==2&&multiplier==1)check(last.presentationEffective.mode==PacingMode::Reflex,"native Reflex active");+ if(mode==2&&multiplier>1&&scenario!=L"xess")check(last.presentationEffective.mode==PacingMode::LowQueue,"Reflex with FG explicitly falls back to low queue");+ if(mode>=0&&scenario==L"xess")check(!last.presentationEffective.enabled&&last.fgActive,"provider remains pacing owner");+ if(scenario==L"lifecycle"){+ engine.pause(true);check(wait([](auto& s){return s.transport==TransportState::Paused;}),"pause");+ p.enabled=false;engine.requestPresentation(p);check(wait([](auto& s){return !s.presentationEffective.enabled;}),"disable while paused");+ engine.seek(5);auto seek=engine.snapshot().seekRequested;check(wait([&](auto& s){return s.seekPresented>=seek;}),"paused seek");+ engine.pause(false);check(wait([](auto& s){return s.position>5.3;}),"resume");+ for(unsigned i=0;i<3;++i){const auto revision=engine.snapshot().presentationRevision;p={true,PacingMode(i),DisplaySync(i)};engine.requestPresentation(p);check(wait([&](auto& s){return s.presentationRevision>revision&&s.presentation==p&&s.presentationEffective.enabled&&s.presentationEffective.mode==(i==2&&multiplier>1?PacingMode::LowQueue:PacingMode(i))&&s.presentationEffective.display==DisplaySync(i);}),"live mode change applied");}+ SetWindowPos(window,nullptr,30,30,960,600,SWP_NOZORDER);p.enabled=false;engine.requestPresentation(p);check(wait([](auto& s){return !s.presentationEffective.enabled;}),"off after resize");+ const auto before=engine.snapshot().frames;check(wait([&](auto& s){return s.frames>before+10;}),"off keeps playing");+ }+ if(scenario==L"overload"){+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",L"80");+ auto before=engine.snapshot();const auto begin=Clock::now();+ check(wait([&](auto& s){return s.position>before.position+2.5;}),"overload progresses");+ const auto after=engine.snapshot();const auto rate=(after.position-before.position)/std::chrono::duration<double>(Clock::now()-begin).count();+ std::cout<<"overloadSpeed="<<rate<<" skippedDelta="<<after.previewSkipped-before.previewSkipped<<std::endl;+ check(rate>.8&&rate<1.2&&after.previewSkipped>before.previewSkipped,"overload stays real time with reported skips");+ p.enabled=false;engine.requestPresentation(p);+ check(wait([](auto& s){return !s.presentationEffective.enabled;},1000),"disable during overload within one second");+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);+ before=engine.snapshot();check(wait([&](auto& s){return s.frames>before.frames+20;}),"recover after overload");+ }+ engine.stop();check(wait([&](auto&){return engine.idle();}),"clean stop");+ }+ DestroyWindow(window);CoUninitialize();return failures?1:0;+}diff --git a/tests/unit/UiContractTests.cpp b/tests/unit/UiContractTests.cppindex 4944d653..1d29c7fa 100644--- a/tests/unit/UiContractTests.cpp+++ b/tests/unit/UiContractTests.cpp@@ -14,6 +14,7 @@void require(bool value,const char* why){if(!value)throw std::runtime_error(why);}int wmain(int argc,wchar_t** argv){try{using namespace veyra;+ {engine::PresentationCadence c;require(c.due(100,10)==100,"no startup pacing reserve");c.submitted(108);require(c.due(110,10)==117,"front edge spaces late outputs with bounded catch-up");c.submitted(999);require(c.due(120,10)==1008,"stale subframe cannot burst after stall");c.reset();require(c.due(120,10)==120,"reset revokes optional deadline");}{engine::PreviewView v;v.wheel(3,800,300,1000,600,1920,1080);require(std::abs(v.zoom-1.728f)<.0001f,"wheel scale");const float anchored=(800-500)/(1920.0f*(1000.0f/1920)*v.zoom)+v.centerX;require(std::abs(anchored-.8f)<.0001f,"pointer anchor fixed");v.wheel(-3,800,300,1000,600,1920,1080);require(std::abs(v.zoom-1)<.0001f&&std::abs(v.centerX-.5f)<.0001f,"inverse wheel returns same view");@@ -77,6 +78,9 @@ int wmain(int argc,wchar_t** argv){try{{ui::UiPreferences audio;audio.volume=.9f;audio.muted=true;audio.inspector=4;audio.inspectorWidth=380;audio.width=1600;audio.height=900;require(prefs.save(audio,nullptr),"audio-page preferences save");ui::UiPreferenceStore reload(dir);const auto back=reload.load();require(std::abs(back.volume-.9f)<1e-6&&back.inspector==4&&back.inspectorWidth==380&&back.width==1600,"audio page and geometry survive the version 3 round trip");}auto setting=loaded.startup({});before.revision=setting.revision;require(setting==before,"all confirmed parameters round trip");for(int enabled:{0,1}){p.enhancementEnabled=enabled;before.nr=true;before.nrRuntime=engine::NrRuntime::Community;require(prefs.save(p,&before),"master and runtime save");ui::UiPreferenceStore restart(dir);require(restart.load().enhancementEnabled==enabled,"master state survives restart");auto restoredSettings=restart.startup({});require(restoredSettings.nr&&restoredSettings.nrRuntime==before.nrRuntime,"bypassed effects and runtime survive restart");}- auto path=dir/"ui-preferences.v1";{std::ofstream bad(path);bad<<"UNKNOWN 9 invalid";}ui::UiPreferenceStore damaged(dir);damaged.load();require(!damaged.save(p,nullptr),"corrupt preference cannot be overwritten");std::ifstream f(path);std::string data((std::istreambuf_iterator<char>(f)),{});require(data=="UNKNOWN 9 invalid","corrupt original preserved");}+ for(bool enabled:{false,true})for(unsigned mode=0;mode<3;++mode)for(unsigned sync=0;sync<3;++sync){p.presentation={enabled,engine::PacingMode(mode),engine::DisplaySync(sync)};require(prefs.save(p,nullptr),"presentation atomic save");ui::UiPreferenceStore restart(dir);require(restart.load().presentation==p.presentation,"all presentation combinations survive restart");}+ auto path=dir/"ui-preferences.v1";+ for(int version=1;version<=5;++version){std::ofstream legacy(path);legacy<<"VEYRA_UI "<<version<<"\n1 0 1 1280 800 0 0 0 1 22";if(version>=2)legacy<<" 392";if(version>=3)legacy<<" 1 0 0 0 0";if(version>=4)legacy<<" 0";if(version>=5)legacy<<" 1";legacy.close();ui::UiPreferenceStore migration(dir);require(!migration.load().presentation.enabled,"old preferences default pacing off");require(migration.save({},nullptr),"old preferences migrate without corrupt lock");}+ {std::ofstream bad(path);bad<<"UNKNOWN 9 invalid";}ui::UiPreferenceStore damaged(dir);damaged.load();require(!damaged.save(p,nullptr),"corrupt preference cannot be overwritten");std::ifstream f(path);std::string data((std::istreambuf_iterator<char>(f)),{});require(data=="UNKNOWN 9 invalid","corrupt original preserved");}std::cout<<"PASS: mode/bypass, 384 layout cases at four DPI scales, actual PCM gain/mute, confirmed settings persistence/corruption\n";return 0;}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}}