Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

fix: checkpoint output telemetry audio sync and FRUC reset repairs

Veyra Goal Agent631637651c5f
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e5a51f05..6a3eb69e 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -376,6 +376,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
# currently lives in veyra_gfx and moves here when the migration completes.
add_library(veyra_sinks STATIC
src/sink/WasapiAudioSink.cpp
+ src/sink/CaptureAudioSession.cpp
src/sink/ImageExportSink.cpp
src/sink/NvencD3D12Encoder.cpp
)
@@ -403,6 +404,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
veyra_apply_warnings(veyra_sources)
target_compile_options(veyra_sources PRIVATE /WX-)
target_compile_features(veyra_sources PRIVATE cxx_std_20)
+ target_link_libraries(veyra_sources PUBLIC veyra_sinks)
target_compile_definitions(veyra_sources PRIVATE
UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
target_include_directories(veyra_sources PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
@@ -448,6 +450,12 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_compile_features(veyra_presentation_worker_tests PRIVATE cxx_std_20)
target_include_directories(veyra_presentation_worker_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
add_executable(veyra_live_presentation_tests tests/integration/LivePresentationTests.cpp)
+ add_executable(veyra_audio_timeline_tests tests/integration/AudioTimelineTests.cpp)
+ target_compile_features(veyra_audio_timeline_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_audio_timeline_tests PRIVATE veyra_sinks)
+ add_executable(veyra_capture_audio_tests tests/integration/CaptureAudioTests.cpp)
+ target_compile_features(veyra_capture_audio_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_capture_audio_tests PRIVATE veyra_sinks)
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)
diff --git a/README.md b/README.md
index 6385c4eb..9b2db7ac 100644
--- a/README.md
+++ b/README.md
@@ -101,6 +101,10 @@ Video / image / capture card
当前修复以最新用户要求、`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.
+当前修复进度:[后端、帧率、链路延迟与音画同步实施记录](docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md)。开发版已加入集中实时产出统计、XeSS切换修正、受控采集音频同步及FRUC重置后错图修复;高倍率FRUC的性能、AMD NR本体和实体采集验收仍未完成。这里的开发改动尚未更新已发布的0.0.1用户包。
+
+Current development progress is recorded in the linked implementation log. Changes include completed-output telemetry, corrected XeSS switching, controlled capture-audio synchronization, and FRUC reset correctness. High-multiplier FRUC performance, AMD NR integration, and physical capture acceptance remain unfinished. These changes have not been published as an update to the 0.0.1 package.
+
| Path | Purpose |
| --- | --- |
| `apps/veyra` | Win32 application and the two-mode interface |
diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cpp
index e9aa4e88..4b3a26c0 100644
--- a/apps/veyra/SettingsWindow.cpp
+++ b/apps/veyra/SettingsWindow.cpp
@@ -11,6 +11,7 @@ namespace {
HWND window=nullptr,body=nullptr;engine::EngineController* controller=nullptr;HFONT font=nullptr;
std::function<bool(engine::EnhancementSettings)> apply;
engine::PresetStore store(runtime::localDataDirectory()/"user-presets.v1");bool loaded=false,dirty=false,populating=false,enhancementEnabled=true;int page=0,scroll=0,contentHeight=0;uint64_t displayedRevision=0;engine::EnhancementSettings configuredSettings;
+std::wstring displayedBackendWarning;
struct Item{HWND h;int page,x,y,w,height;};std::vector<Item> items;
HWND item(int id){for(auto& entry:items)if(GetDlgCtrlID(entry.h)==id)return entry.h;return nullptr;}
LRESULT send(int id,UINT message,WPARAM w=0,LPARAM l=0){return SendMessageW(item(id),message,w,l);}
@@ -54,6 +55,9 @@ void populate(engine::EnhancementSettings s){
send(204,CB_SETCURSEL,int(s.flow),0);send(205,CB_SETCURSEL,int(s.content),0);
send(209,CB_SETCURSEL,int(s.opticalFlowBackend),0);
check(215,s.amdFlowHalfResolution?BST_CHECKED:BST_UNCHECKED);
+ send(216,CB_SETCURSEL,int(s.audioSync));
+ if(GetFocus()!=item(217))putText(217,std::to_wstring(s.audioOffsetMs).c_str());
+ EnableWindow(item(217),s.audioSync==engine::AudioSyncMode::Manual);
EnableWindow(item(204),s.opticalFlowBackend==engine::OpticalFlowBackend::Nvidia);
EnableWindow(item(215),s.opticalFlowBackend==engine::OpticalFlowBackend::AmdFidelityFx);
displayedRevision=s.revision;populating=false;dirty=false;
@@ -64,6 +68,9 @@ bool read(engine::EnhancementSettings& s,bool allPages=false){s=enhancementEnabl
const auto multiplier=send(202,CB_GETCURSEL,0,0),generation=send(208,CB_GETCURSEL,0,0),flowBackend=send(209,CB_GETCURSEL,0,0),flowQuality=send(204,CB_GETCURSEL,0,0),content=send(205,CB_GETCURSEL,0,0);
if(multiplier==CB_ERR||generation==CB_ERR||flowBackend==CB_ERR||flowQuality==CB_ERR||content==CB_ERR){message(L"设置控件未完成初始化;未保存预设");return false;}
s.multiplier=uint32_t(multiplier+1);s.frameGenerationBackend=static_cast<engine::FrameGenerationBackend>(generation);s.opticalFlowBackend=static_cast<engine::OpticalFlowBackend>(flowBackend);s.amdFlowHalfResolution=checked(215)==BST_CHECKED;s.flow=static_cast<engine::FlowQuality>(flowQuality);s.content=static_cast<engine::ContentRate>(content);
+ s.audioSync=static_cast<engine::AudioSyncMode>(send(216,CB_GETCURSEL));
+ wchar_t offset[32]{};GetWindowTextW(item(217),offset,32);wchar_t* offsetEnd=nullptr;const auto parsed=wcstol(offset,&offsetEnd,10);
+ if(offsetEnd==offset||*offsetEnd||parsed<-250||parsed>250){message(L"声音偏移须为 -250 至 250 ms");return false;}s.audioOffsetMs=int(parsed);
for(int j=0;j<3;++j)if(GetPropW(item(730+j),L"veyra.selected")){s.srTarget=static_cast<pipeline::SrTarget>(j);break;}
if(s.frameGenerationBackend==engine::FrameGenerationBackend::XeSS)s.multiplier=std::min(s.multiplier,2u);
}if(!s.validate().empty()){message(L"参数越界,未提交。悬停数值框查看允许范围。");return false;}return true;}
@@ -85,6 +92,8 @@ bool liveField(int id){
case 208:s.frameGenerationBackend=static_cast<engine::FrameGenerationBackend>(send(id,CB_GETCURSEL));if(s.frameGenerationBackend==engine::FrameGenerationBackend::XeSS)s.multiplier=std::min(s.multiplier,2u);break;
case 209:s.opticalFlowBackend=static_cast<engine::OpticalFlowBackend>(send(id,CB_GETCURSEL));break;
case 215:s.amdFlowHalfResolution=checked(id)==BST_CHECKED;break;
+ case 216:s.audioSync=static_cast<engine::AudioSyncMode>(send(id,CB_GETCURSEL));break;
+ case 217:{wchar_t value[32]{};GetWindowTextW(item(id),value,32);wchar_t* end=nullptr;const auto parsed=wcstol(value,&end,10);if(end==value||*end||parsed<-250||parsed>250){message(L"声音偏移须为 -250 至 250 ms");return false;}s.audioOffsetMs=int(parsed);break;}
case 207:s.videoSrQuality=uint32_t(send(id,CB_GETCURSEL));break;
case 700:case 701:case 702:s.model.style=id-700;break;
case 710:case 711:s.model.autoMask=id-710;break;
@@ -120,9 +129,10 @@ HWND add(const wchar_t* cls,const wchar_t* text,int id,DWORD style,int group,int
void 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)==216&&HIWORD(wp)==CBN_SELCHANGE)||(LOWORD(wp)==217&&HIWORD(wp)==EN_CHANGE))){liveField(LOWORD(wp));return 0;}
if(msg==WM_COMMAND&&!populating&&((LOWORD(wp)==209&&HIWORD(wp)==CBN_SELCHANGE)||(LOWORD(wp)==215&&HIWORD(wp)==BN_CLICKED))){liveField(LOWORD(wp));return 0;}
switch(msg){
-case WM_CREATE:{window=h;font=makeFont(h);items.clear();
+case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.clear();
WNDCLASSW bodyClass{};bodyClass.lpfnWndProc=bodyProc;bodyClass.hInstance=GetModuleHandleW(nullptr);bodyClass.lpszClassName=L"VeyraInspectorBody";bodyClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&bodyClass);
body=CreateWindowExW(WS_EX_CONTROLPARENT,bodyClass.lpszClassName,L"滚动参数",WS_CHILD|WS_VISIBLE|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,0,88,300,300,h,nullptr,bodyClass.hInstance,nullptr);
add(L"BUTTON",L"实验性 NVIDIA NR 增强",200,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,12,-1,36);
@@ -138,10 +148,23 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();
add(L"STATIC",L"肤质 / 风格 / 遮罩 / UI键为本地实验参数。未验证的效果不会标成可用能力。",1102,0,0,12,956,-1,70);
button(L"还原默认",211,-1,12,86);
add(L"STATIC",L"补帧与运动估算",1103,0,1,12,12,-1,30);
- combo(202,1,52,{L"关闭补帧",L"2X · 一张中间帧",L"3X · 两张中间帧",L"4X · 三张中间帧"});
- combo(204,1,340,{L"NR / DLSS光流 · 性能",L"NR / DLSS光流 · 平衡",L"NR / DLSS光流 · 质量"});
- combo(205,1,392,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏",L"采集60→30fps处理(PS5 30帧)"});
- add(L"STATIC",L"FRUC倍率越高,耗时越多。光流档位用于NR/DLSS;FRUC内部自动控制。补帧需等待下一张源帧,倍率不等于实测显示帧率。",1104,0,1,12,446,-1,88);
+ add(L"STATIC",L"补帧方式",1111,0,1,12,50,-1,24);
+ combo(208,1,78,{L"DLSS 帧生成",L"NVIDIA FRUC · 视频补帧",L"Intel XeSS · 实验显示补帧 2X"});
+ add(L"STATIC",L"补帧倍率",1112,0,1,12,122,-1,24);
+ combo(202,1,150,{L"关闭补帧",L"2X · 一张中间帧",L"3X · 两张中间帧",L"4X · 三张中间帧"});
+ add(L"STATIC",L"运动估算",1113,0,1,12,194,-1,24);
+ combo(209,1,222,{L"NVIDIA NVOF 光流",L"AMD FidelityFX 光流 · 实验"});
+ add(L"BUTTON",L"AMD 性能档 · 光流宽高各减半",215,BS_AUTOCHECKBOX|WS_TABSTOP,1,12,266,-1,36);
+ combo(204,1,310,{L"NR / DLSS光流 · 性能",L"NR / DLSS光流 · 平衡",L"NR / DLSS光流 · 质量"});
+ add(L"STATIC",L"内容节奏",1114,0,1,12,354,-1,24);
+ combo(205,1,382,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏",L"采集60→30fps处理(PS5 30帧)"});
+ add(L"STATIC",L"AMD FidelityFX 为运动估算;不是 AMD NR。XeSS 为实验预览 2X,不支持导出。",1110,0,1,12,426,-1,72);
+ add(L"STATIC",L"FRUC倍率越高,耗时越多。光流档位用于NR/DLSS;FRUC内部自动控制。补帧需等待下一张源帧,倍率不等于实测显示帧率。",1104,0,1,12,506,-1,88);
+ add(L"STATIC",L"采集音频同步",1115,0,1,12,608,-1,26);
+ combo(216,1,644,{L"自动同步 · 软件估算",L"手动声音偏移",L"关闭补偿"});
+ add(L"STATIC",L"声音偏移 ms",1116,0,1,12,692,160,28);
+ add(L"EDIT",L"0",217,ES_AUTOHSCROLL|ES_RIGHT|WS_TABSTOP,1,182,692,-1,28);
+ SetPropW(item(217),L"veyra.tip",HANDLE(L"-250 至 250 ms;正值让声音更晚。负值只能减少已有延迟,实际补偿最低为0。"));
add(L"STATIC",L"用户预设",1105,0,2,12,12,-1,30);combo(300,2,56,{});add(L"EDIT",L"新预设",301,ES_AUTOHSCROLL|WS_TABSTOP,2,12,108,-1,36);send(301,EM_SETLIMITTEXT,48,0);
const wchar_t* names[]={L"载入所选预设",L"新建内建默认预设",L"保存当前参数为新预设",L"重命名所选",L"删除所选",L"设为启动增强默认"};for(int i=0;i<6;++i)button(names[i],310+i,2,12,164+i*44);
@@ -161,10 +184,6 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();
combo(207,0,100,{L"DLSS SR",L"RTX 视频超分 · 低",L"RTX 视频超分 · 中",L"RTX 视频超分 · 高",L"RTX 视频超分 · 最高"});
for(auto& entry:items)if(entry.page==0&&entry.y>=100)entry.y+=44;
button(L"2K",730,0,12,100,80);button(L"4K",731,0,100,100,80);button(L"8K",732,0,188,100,80);
- combo(208,1,8,{L"DLSS 帧生成",L"NVIDIA FRUC · 视频补帧",L"Intel XeSS · 实验显示补帧 2X"});
- combo(209,1,148,{L"NVIDIA NVOF 光流",L"AMD FidelityFX 光流 · 实验"});
- add(L"BUTTON",L"AMD 性能档 · 光流宽高各减半",215,BS_AUTOCHECKBOX|WS_TABSTOP,1,12,196,-1,36);
- add(L"STATIC",L"AMD FidelityFX 只替换运动估算,不提供 AMD DLSS5 / NR / 超分 / FRUC / DLSS 补帧 / NVENC。XeSS 当前只支持预览 2X,不能导出。",1110,0,1,12,244,-1,72);
loadStore();refreshPresets();populate(controller->snapshot().desired);message(store.error());SetTimer(h,1,250,nullptr);arrange();return 0;}
case WM_SIZE:arrange();return 0;
case WM_ERASEBKGND:return 1;
@@ -185,7 +204,14 @@ case WM_COMMAND:{const int id=LOWORD(wp);if(!populating&&((id>=202&&id<=205||id=
else if(id>=501&&id<=505)SendMessageW(GetParent(h),WM_APP+41,id,id==501?send(500,CB_GETCURSEL,0,0):id==505?checked(505):0);
if(!ok)message(store.error());return 0;}
case WM_HSCROLL:{int id=GetDlgCtrlID(reinterpret_cast<HWND>(lp));if(id>=600&&id<612){int index=id-600;float v=float(SendMessageW(reinterpret_cast<HWND>(lp),TBM_GETPOS,0,0))/(index>=4&&index<=6?1:100);if(index==3&&v<0)v=-1;std::wostringstream o;o<<std::setprecision(4)<<v;putText(100+index,o.str().c_str());}return 0;}
-case WM_TIMER:{auto s=controller->snapshot();syncProtection(enhancementEnabled?s.desired.protection:configuredSettings.protection);if(enhancementEnabled&&!dirty&&displayedRevision!=s.desired.revision)populate(s.desired);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"")<<L"\n强度 "<<s.applied.model.intensity<<L" · 变化量 "<<s.applied.residual.total<<L" · 倍率 "<<s.applied.multiplier<<L"X";setText(item(400),o.str());return 0;}
+case WM_TIMER:{auto s=controller->snapshot();syncProtection(enhancementEnabled?s.desired.protection:configuredSettings.protection);if(enhancementEnabled&&!dirty&&displayedRevision!=s.desired.revision)populate(s.desired);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::Fruc?L"FRUC":L"DLSS";
+ o<<L"\n"<<backend<<L" · "<<(s.applied.multiplier<=1?L"补帧关闭":s.fgActive?L"补帧运行":L"等待有效补帧");
+ if(!s.backendWarning.empty())message(s.backendWarning);
+ else if(!displayedBackendWarning.empty())message(L"设置已应用");
+ displayedBackendWarning=s.backendWarning;
+}setText(item(400),o.str());return 0;}
case WM_DESTROY:KillTimer(h,1);DeleteObject(font);window=nullptr;body=nullptr;items.clear();return 0;
}return DefWindowProcW(h,msg,wp,lp);}
}
diff --git a/apps/veyra/TelemetryWindow.cpp b/apps/veyra/TelemetryWindow.cpp
index 3212b43f..6590f847 100644
--- a/apps/veyra/TelemetryWindow.cpp
+++ b/apps/veyra/TelemetryWindow.cpp
@@ -11,14 +11,19 @@ namespace {
unsigned windowDpi=96;HWND window=nullptr;engine::EngineController* engine=nullptr;HFONT font=nullptr;std::wstring preview;
std::wstring wide(const std::string& s){int n=MultiByteToWideChar(CP_UTF8,0,s.data(),int(s.size()),nullptr,0);std::wstring r(n,0);MultiByteToWideChar(CP_UTF8,0,s.data(),int(s.size()),r.data(),n);return r;}
std::wstring value(std::optional<double> v){if(!v)return L"未能测量";std::wostringstream o;o<<std::fixed<<std::setprecision(3)<<*v;return o.str();}
-void refresh(){auto s=engine->snapshot();const wchar_t* names[]={L"上传/颜色转换",L"DLSS SR",L"NVOF GPU队列区间(含同步)",L"DLSS5 NR",L"NR变化量合成",L"DLSSG 子帧1",L"DLSSG 子帧2",L"DLSSG 子帧3",L"DLSSG批次",L"最终blit"};std::wostringstream o;
+void refresh(){auto s=engine->snapshot();const wchar_t* names[]={L"上传/颜色转换",L"超分 SR",L"光流 GPU队列区间(含同步)",L"NR",L"NR变化量合成",L"FG 子帧1",L"FG 子帧2",L"FG 子帧3",L"FG批次",L"最终blit"};std::wostringstream o;
o<<L"GPU时间戳(毫秒);未执行不记作0。样本帧 "<<s.metrics.identity.sourceFrameId<<L" / epoch "<<s.metrics.identity.epoch<<L" / 设置版本 "<<s.metrics.identity.settingsRevision<<L"\r\n";
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最近一秒链路统计:均值 / P95 ms,n为样本数\r\n";
+ for(size_t i=0;i<f.gpuTiming.size();++i){const auto& a=f.gpuTiming[i];o<<names[i]<<L":"<<value(a.mean)<<L" / "<<value(a.p95)<<L" n="<<a.samples<<L"\r\n";}
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\n实际源帧完成 "<<value(f.sourceCompletedFps)<<L" fps / 总处理产出 "<<value(f.outputCompletedFps)<<L" fps"
+ <<L"\r\nXeSS SDK送呈现 "<<value(f.xessSdkSubmitFps)<<L" fps(不能与处理产出混加)"
+ <<L"\r\n软件首尾延迟均值 "<<value(f.softwareLatencyMs)<<L" / P95 "<<value(f.softwareLatencyP95Ms)<<L" ms;有效样本 "<<f.latencySamples
<<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
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index 9850368c..605c42b1 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -3,6 +3,7 @@
#include "../SettingsWindow.h"
#include "Theme.h"
#include "WorkspaceChrome.h"
+#include "LiveStatusPanel.h"
#include "WorkspaceTransition.h"
#include "UiSessionState.h"
#include "UiPreferenceStore.h"
@@ -35,7 +36,7 @@ veyra::engine::EngineController engine;
veyra::engine::ExportJobManager exportJob;
veyra::ui::UiSessionState uiState;
veyra::ui::UiPreferenceStore preferences(veyra::runtime::localDataDirectory());veyra::ui::UiPreferences uiPreferences;
-HWND inspector=nullptr,metricLabel=nullptr,tooltips=nullptr,diagnosticPanel=nullptr;bool showDiagnostics=false,inspectorResizing=false;int proposedInspectorWidth=320;bool preferWatching=true,jobPaused=false;int subtitlePixels=22;
+HWND inspector=nullptr,metricLabel=nullptr,tooltips=nullptr,diagnosticPanel=nullptr,liveStatusPanel=nullptr;bool showDiagnostics=false,inspectorResizing=false;int proposedInspectorWidth=320;bool preferWatching=true,jobPaused=false;int subtitlePixels=22;
veyra::engine::EnhancementSettings lastSuccessful,jobExpected;bool haveSuccessful=false;uint64_t masterPendingRevision=0,masterPendingSession=0;bool masterPreviousEnabled=true;
std::wstring smokeView;bool smokeViewApplied=false;
std::wstring smokeDualOutput;bool smokeEmpty=false;DWORD modeGdiStart=0,modeHandlesStart=0;SIZE_T modePrivateStart=0;
@@ -138,7 +139,7 @@ void layout(){
auto pane=[&](int x,int y,int width,int height,int radius,BYTE tint){return GlassPane{{dip(mainWindow,x),dip(mainWindow,y),dip(mainWindow,x+width),dip(mainWindow,y+height)},dip(mainWindow,radius),tint};};
std::vector<GlassPane> panes;
if(full){if(fullControls)panes.push_back(pane(0,h-88,w,88,1,142));}
- else if(g.pro){panes.push_back(pane(4,4,64,h-8,22,24));panes.push_back(pane(g.left,g.bottom,g.viewWidth,h-g.bottom-20,20,32));if(g.panelWidth){panes.push_back(pane(g.right,g.top,g.panelWidth,g.viewHeight,20,30));panes.push_back(pane(g.right,g.bottom,g.panelWidth,h-g.bottom-20,20,40));}}
+ else if(g.pro){panes.push_back(pane(4,4,64,h-8,22,24));panes.push_back(pane(g.left,g.bottom,g.viewWidth,h-g.bottom-20,20,32));if(g.panelWidth){panes.push_back(pane(g.right,g.top,g.panelWidth,g.statusTop-g.top-10,20,30));panes.push_back(pane(g.right,g.statusTop,g.panelWidth,h-g.statusTop-20,20,40));}}
else{panes.push_back(pane(0,h-88,w,88,1,32));}
backdrop.render(r.right,r.bottom,g.pro,full,panes);
struct Placement{HWND child;int x,y,width,height;UINT flags;};std::vector<Placement> placements;
@@ -158,7 +159,8 @@ void layout(){
put(ProRailVideo,12,92,44,44,!full&&pro);put(ProRailCapture,12,148,44,44,!full&&pro);put(ImageOpen,12,204,44,44,!full&&pro);
for(int id:{ProRailVideo,ProRailCapture,ImageOpen})surface(GetDlgItem(mainWindow,id),RGB(16,17,18));
for(int i=0;i<4;++i)put(TabEnhance+i,g.right+12+i*((g.panelWidth-24)/4),g.top+12,(g.panelWidth-24)/4,32,rightVisible);
- pos(inspector,g.right+12,g.top+56,g.panelWidth-24,g.viewHeight-68,rightVisible);
+ pos(inspector,g.right+12,g.top+56,g.panelWidth-24,g.statusTop-g.top-68,rightVisible);
+ pos(liveStatusPanel,g.right,g.statusTop,g.panelWidth,h-g.statusTop-20,rightVisible);
const bool transport=!full||fullControls;int barTop=full?h-88:g.bottom;int tx=full?16:g.left+16,tw=full?w-32:g.viewWidth-32;
pos(playbackBar,0,h-88,w,88,full&&fullControls);
pos(seekBar,full?0:pro?tx:g.left,barTop-5,full?w:pro?tw:g.viewWidth,12,transport&&!target.capture&&!target.image&&!(pro&&showDiagnostics&&!full));surface(seekBar,pro&&!full?panel:cinemaPanel);
@@ -240,7 +242,7 @@ veyra::ui::icon(GetDlgItem(hwnd,ProRailVideo),Icon::Video);veyra::ui::icon(GetDl
veyra::ui::icon(GetDlgItem(hwnd,Recent),Icon::Recent);veyra::ui::icon(GetDlgItem(hwnd,Open),Icon::Video,true);veyra::ui::icon(GetDlgItem(hwnd,Capture),Icon::Capture,true);
for(int id:{Open,Capture,Recent,Master,Sr,ModeSwitch,WindowMin,WindowMax,WindowClose,Stop,Mute,Subtitle,Fullscreen,ProRailVideo,ProRailCapture,ImageOpen,Info})veyra::ui::ghost(GetDlgItem(hwnd,id));
SetPropW(GetDlgItem(hwnd,Open),L"veyra.tip",HANDLE(L"打开视频 / 图片 · Ctrl+O"));SetPropW(GetDlgItem(hwnd,Capture),L"veyra.tip",HANDLE(L"连接采集卡"));SetPropW(GetDlgItem(hwnd,Sr),L"veyra.tip",HANDLE(L"超分辨率 · 专业面板选择 DLSS / RTX 视频超分"));
-inspector=veyra::ui::createSettingsPanel(hwnd,engine,applySettings);selectInspector(uiPreferences.inspector);refreshDailyPresets();SendDlgItemMessageW(hwnd,Volume,TBM_SETPOS,TRUE,LPARAM(uiPreferences.volume*100));veyra::ui::marked(GetDlgItem(hwnd,Play));
+inspector=veyra::ui::createSettingsPanel(hwnd,engine,applySettings);liveStatusPanel=veyra::ui::createLiveStatusPanel(hwnd,engine);selectInspector(uiPreferences.inspector);refreshDailyPresets();SendDlgItemMessageW(hwnd,Volume,TBM_SETPOS,TRUE,LPARAM(uiPreferences.volume*100));veyra::ui::marked(GetDlgItem(hwnd,Play));
SetPropW(video,L"veyra.tip",HANDLE(L"专业模式:滚轮缩放 · 中键拖动画面 · 右键恢复适应窗口。缩放不影响增强或保存尺寸。"));tooltips=CreateWindowExW(WS_EX_TOPMOST,TOOLTIPS_CLASSW,nullptr,WS_POPUP|TTS_ALWAYSTIP|TTS_NOPREFIX,0,0,0,0,hwnd,nullptr,GetModuleHandleW(nullptr),nullptr);SendMessageW(tooltips,TTM_SETMAXTIPWIDTH,0,360);EnumChildWindows(hwnd,[](HWND child,LPARAM context)->BOOL{auto tip=reinterpret_cast<HWND>(context);wchar_t cls[32]{};GetClassNameW(child,cls,32);if(child==video||_wcsicmp(cls,L"BUTTON")==0||_wcsicmp(cls,L"EDIT")==0||_wcsicmp(cls,L"COMBOBOX")==0){TOOLINFOW info{sizeof(info)};info.uFlags=TTF_IDISHWND|TTF_SUBCLASS;info.hwnd=GetAncestor(child,GA_ROOT);info.uId=UINT_PTR(child);info.lpszText=LPSTR_TEXTCALLBACKW;SendMessageW(tip,TTM_ADDTOOLW,0,LPARAM(&info));}return TRUE;},LPARAM(tooltips));
if(smokeSeconds>0)startTick=GetTickCount64();diagnosticPanel=veyra::ui::createTelemetryPanel(hwnd,engine);DragAcceptFiles(hwnd,TRUE);SetTimer(hwnd,1,100,nullptr);layout();return 0;}
case WM_NCCALCSIZE:if(wp)return 0;break;
@@ -325,7 +327,8 @@ if(smokeStep==3&&elapsed>4100&&!smokeSave.empty()){engine.saveFrame(smokeSave);s
if(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_SAVE_THROW",nullptr,0)){const auto retained=engine.snapshot();if(!retained.failed&&retained.running&&retained.frames>0){engine.saveFrame(smokeSave);smokeStep=5;veyra::log::info("image-save-test","retry after injected allocation failure; result/session retained");}}
}auto s=engine.snapshot();const auto subtitleText=uiState.subtitles&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional&&!full)?veyra::engine::subtitleAt(subtitles,s.position):L"";veyra::ui::updateSubtitleOverlay(subtitleLabel,subtitleText,subtitlePixels);
const double submittedFps=s.submissionFps.value_or(0.0);
-veyra::ui::setText(GetDlgItem(hwnd,FpsLabel),std::format(L"处理 {:.1f} fps",s.fps));
+const bool xessRate=s.applied.frameGenerationBackend==veyra::engine::FrameGenerationBackend::XeSS&&s.applied.multiplier>1;
+veyra::ui::setText(GetDlgItem(hwnd,FpsLabel),s.running&&!s.image&&s.transport==veyra::engine::TransportState::Playing&&!s.metrics.flow.rateWindowReady?std::wstring(L"帧率采样中"):std::format(L"{} {:.1f} fps",xessRate?L"SDK提交":L"处理产出",xessRate?s.metrics.flow.xessSdkSubmitFps:s.metrics.flow.outputCompletedFps));
auto text=s.capture?std::format(L"{}\r\n输入 {:.1f} / 已处理 {:.1f} / 显示提交 {:.1f}fps | 回调至Present返回p95 {:.1f}ms(非总延迟)| 丢弃 {} | 有效生成 {}",s.status,s.captureFps,s.fps,submittedFps,s.captureAgeP95Ms,s.captureDropped,s.generated):std::format(L"{}\r\n{:.1f} / {:.1f}秒 已处理 {:.1f}fps 提交迟到 {:+.1f}ms 源帧 {} / 有效生成 {}",s.status,s.position,s.duration,s.fps,s.lateMs,s.frames,s.generated);
if(smokeZoom&&startTick&&s.frames>0){const auto elapsed=GetTickCount64()-startTick;
if(zoomStep==0&&elapsed>1300){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();zoomBefore=s;RECT r{};GetWindowRect(video,&r);const LPARAM point=MAKELPARAM(r.left+(r.right-r.left)*7/10,r.top+(r.bottom-r.top)/2);if(smokeHover){SetFocus(GetDlgItem(hwnd,ModeSwitch));PostMessageW(hwnd,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),point);hoverPostedTick=GetTickCount64();zoomStep=4;}else{SendMessageW(video,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),point);zoomStep=std::abs(engine.previewView().zoom-1.728f)<.001f?1:-1;}}
diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.h
new file mode 100644
index 00000000..30958159
--- /dev/null
+++ b/apps/veyra/ui/LiveStatusPanel.h
@@ -0,0 +1,107 @@
+#pragma once
+#include "WorkspaceChrome.h"
+
+namespace veyra::ui {
+namespace live_status {
+struct State {engine::EngineController* engine;int scroll=0,maxScroll=0;};
+inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
+ auto* state=reinterpret_cast<State*>(GetWindowLongPtrW(h,GWLP_USERDATA));
+ if(message==WM_NCCREATE){state=new State{static_cast<engine::EngineController*>(reinterpret_cast<CREATESTRUCTW*>(lp)->lpCreateParams)};SetWindowLongPtrW(h,GWLP_USERDATA,LONG_PTR(state));}
+ if(!state)return DefWindowProcW(h,message,wp,lp);
+ switch(message){
+ case WM_CREATE:SetTimer(h,1,250,nullptr);return 0;
+ case WM_TIMER:if(IsWindowVisible(h))InvalidateRect(h,nullptr,FALSE);return 0;
+ case WM_SIZE:InvalidateRect(h,nullptr,FALSE);return 0;
+ case WM_MOUSEWHEEL:state->scroll=std::clamp(state->scroll-GET_WHEEL_DELTA_WPARAM(wp)/WHEEL_DELTA*54,0,state->maxScroll);InvalidateRect(h,nullptr,FALSE);return 0;
+ case WM_ERASEBKGND:return 1;
+ case WM_PAINT:{
+ PaintBuffer paint(h);fillSurface(paint.dc,paint.rect,h);
+ const int width=MulDiv(paint.rect.right,96,GetDpiForWindow(h)),height=MulDiv(paint.rect.bottom,96,GetDpiForWindow(h));
+ const auto s=state->engine->snapshot();const auto& f=s.metrics.flow;
+ const bool playing=s.running&&!s.image&&s.transport==engine::TransportState::Playing;
+ const bool xess=s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS&&s.applied.multiplier>1;
+ auto write=[&](const std::wstring& value,int x,int y,int w,int ht,int size,COLORREF color){chromeText(paint.dc,h,value,x,y,w,ht,size,color);};
+ auto ms=[](std::optional<double> v){return v?std::format(L"{:.1f} ms",*v):std::wstring(L"未测");};
+ auto timing=[&](const diagnostics::TimingAggregate& a){return playing&&a.mean&&a.p95?std::format(L"{:.1f} / {:.1f}",*a.mean,*a.p95):std::wstring(L"未测");};
+ auto fps=[&](double value){return playing&&!f.rateWindowReady?std::wstring(L"采样中"):std::format(L"{:.1f} fps",value);};
+ write(L"实时处理状态",12,8,width-24,24,13,textColor);
+ const int half=(width-24)/2;
+ write(xess?L"输出提交 · XeSS SDK":L"处理产出",12,36,half,20,10,secondary);
+ write(s.capture?L"软件总延迟":L"软件驻留时间",12+half,36,half,20,10,secondary);
+ write(fps(xess?f.xessSdkSubmitFps:f.outputCompletedFps),12,57,half,28,18,textColor);
+ write(playing?ms(f.softwareLatencyMs):L"未测",12+half,57,half,28,18,textColor);
+ std::vector<std::pair<std::wstring,std::wstring>> rows;
+ rows.emplace_back(L"呈现提交",fps(xess?f.xessSdkSubmitFps:f.presentSubmitFps));
+ rows.emplace_back(L"源帧处理",fps(f.sourceCompletedFps));
+ rows.emplace_back(xess?L"补帧完成":L"有效补帧",xess?L"SDK内部不可测":fps(f.validGeneratedFps));
+ rows.emplace_back(L"输入",s.capture?std::format(L"{:.1f} fps",s.captureFps):L"文件 / 图片");
+ rows.emplace_back(L"总延迟 P95",playing?ms(f.softwareLatencyP95Ms):L"未测");
+ rows.emplace_back(L"采集覆盖 / 补帧过期",std::format(L"{} / {}",f.counters.mailboxOverwritten,f.counters.generatedExpiredAfterEval));
+ rows.emplace_back(L"链路耗时 · ms",L"均值 / P95");
+ rows.emplace_back(L"取帧 / 解码",timing(f.cpuTiming[size_t(diagnostics::CpuStage::Decode)]));
+ rows.emplace_back(L"命令槽等待",timing(f.cpuTiming[size_t(diagnostics::CpuStage::SlotWait)]));
+ rows.emplace_back(L"图提交",timing(f.cpuTiming[size_t(diagnostics::CpuStage::Submit)]));
+ const diagnostics::GpuStage stages[]={diagnostics::GpuStage::Color,diagnostics::GpuStage::Sr,diagnostics::GpuStage::Flow,diagnostics::GpuStage::Nr,diagnostics::GpuStage::Residual,diagnostics::GpuStage::FgBatch,diagnostics::GpuStage::Blit};
+ const wchar_t* names[]={L"输入颜色",L"超分 SR",L"光流队列区间",L"NR",L"残差合成",L"补帧 FG",L"输出 blit"};
+ for(size_t i=0;i<std::size(stages);++i){const auto& sample=s.metrics.gpu[size_t(stages[i])];
+ const auto value=xess&&stages[i]==diagnostics::GpuStage::FgBatch?L"SDK内部不可测":sample.state==diagnostics::SampleState::NotExecuted?L"未执行":timing(f.gpuTiming[size_t(stages[i])]);
+ rows.emplace_back(names[i],value);
+ }
+ rows.emplace_back(L"GPU就绪等待",timing(f.cpuTiming[size_t(diagnostics::CpuStage::ReadyWait)]));
+ rows.emplace_back(L"呈现等待",timing(f.cpuTiming[size_t(diagnostics::CpuStage::DeadlineWait)]));
+ rows.emplace_back(L"Present调用与锁等待",timing(f.cpuTiming[size_t(diagnostics::CpuStage::Present)]));
+ rows.emplace_back(L"延迟样本 / 统计溢出",std::format(L"{} / {}",f.latencySamples,f.timingOverflow));
+ rows.emplace_back(L"补帧方式",s.applied.multiplier<=1?L"关闭":std::format(L"{} {}X",xess?L"XeSS":s.applied.frameGenerationBackend==engine::FrameGenerationBackend::Fruc?L"FRUC":L"DLSS",s.applied.multiplier));
+ rows.emplace_back(L"NR内部尺寸",s.applied.nr?std::format(L"{} x {}",s.metrics.resolution.nr.width,s.metrics.resolution.nr.height):L"关闭");
+ rows.emplace_back(L"音频同步",s.audioAvailable?(s.capture?(s.captureAudio.running?L"软件估算同步":L"等待视频锚点"):(s.audioRebuffering?L"视频过载 · 同步缓冲":L"音频主时钟")):L"无音频");
+ if(!s.capture&&s.audioAvailable)rows.emplace_back(L"声音领先 · 软件估算",std::format(L"{:.1f} ms",s.lateMs));
+ if(s.capture&&s.audioAvailable){
+ rows.emplace_back(L"音画偏差 · 声音领先",ms(s.captureAudio.skewMs));
+ rows.emplace_back(L"声音补偿",std::format(L"{:.1f} ms{}",s.captureAudio.compensationMs,s.captureAudio.limited?L" · 已达边界":L""));
+ rows.emplace_back(L"PCM队列",std::format(L"{:.1f} ms",s.captureAudio.bufferedMs));
+ rows.emplace_back(L"音频重锚 / 溢出",std::format(L"{} / {}",s.captureAudio.resets,s.captureAudio.overflows));
+ }
+ if(!s.backendWarning.empty())rows.emplace_back(L"后端状态",s.backendWarning);
+ if(!s.captureAudio.error.empty())rows.emplace_back(L"采集音频异常",s.captureAudio.error);
+ std::vector<std::pair<std::wstring,std::wstring>> wrapped;
+ const auto rowFont=makeFont(h,11,FW_NORMAL);const auto oldFont=SelectObject(paint.dc,rowFont);
+ auto split=[&](std::wstring value,int room){
+ std::vector<std::wstring> lines;
+ do{
+ int fit=0;SIZE extent{};
+ GetTextExtentExPointW(paint.dc,value.c_str(),int(value.size()),dip(h,room),&fit,nullptr,&extent);
+ const auto count=std::min(value.size(),size_t(std::max(1,fit)));
+ lines.push_back(value.substr(0,count));value.erase(0,count);
+ }while(!value.empty());
+ return lines;
+ };
+ for(const auto& row:rows){
+ const auto labels=split(row.first,width/2-14),values=split(row.second,width/2-12);
+ for(size_t line=0;line<std::max(labels.size(),values.size());++line)wrapped.emplace_back(line<labels.size()?labels[line]:L"",line<values.size()?values[line]:L"");
+ }
+ SelectObject(paint.dc,oldFont);DeleteObject(rowFont);rows=std::move(wrapped);
+ const int top=96,rowHeight=25,available=std::max(0,height-top-30);
+ state->maxScroll=std::max(0,int(rows.size())*rowHeight-available);state->scroll=std::clamp(state->scroll,0,state->maxScroll);
+ const int saved=SaveDC(paint.dc);IntersectClipRect(paint.dc,0,dip(h,top),paint.rect.right,dip(h,top+available));
+ for(size_t i=0;i<rows.size();++i){const int y=top+int(i)*rowHeight-state->scroll;
+ // glassText renders through its own DIB; a parent DC clip does not
+ // constrain that buffer. Never draw partial rows into fixed text.
+ if(y<top||y+rowHeight>top+available)continue;
+ write(rows[i].first,12,y,width/2-14,rowHeight,11,secondary);
+ write(rows[i].second,width/2,y,width/2-12,rowHeight,11,textColor);
+ }
+ RestoreDC(paint.dc,saved);
+ if(state->maxScroll&&available>0){const int thumb=std::max(18,available*available/(int(rows.size())*rowHeight));const int y=top+(available-thumb)*state->scroll/state->maxScroll;RECT r{dip(h,width-4),dip(h,y),dip(h,width-2),dip(h,y+thumb)};FillRect(paint.dc,&r,panelBrush());}
+ write(xess?L"截止代理Present返回;屏幕扫描未测":L"源帧进入软件至Present返回;非光子延迟",12,height-28,width-24,24,9,secondary);
+ return 0;
+ }
+ case WM_NCDESTROY:KillTimer(h,1);delete state;SetWindowLongPtrW(h,GWLP_USERDATA,0);break;
+ }
+ return DefWindowProcW(h,message,wp,lp);
+}
+}
+inline HWND createLiveStatusPanel(HWND parent,engine::EngineController& engine){
+ WNDCLASSW wc{};wc.lpfnWndProc=live_status::proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraLiveStatus";wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);
+ return CreateWindowExW(0,wc.lpszClassName,L"实时处理状态",WS_CHILD,0,0,1,1,parent,nullptr,wc.hInstance,&engine);
+}
+}
diff --git a/apps/veyra/ui/WorkspaceChrome.h b/apps/veyra/ui/WorkspaceChrome.h
index 1fc24d7e..8d230b18 100644
--- a/apps/veyra/ui/WorkspaceChrome.h
+++ b/apps/veyra/ui/WorkspaceChrome.h
@@ -4,7 +4,7 @@
#include <format>
namespace veyra::ui {
struct ChromeLayout {
- int w,h,left,top,viewWidth,viewHeight,right,panelWidth,bottom;
+ int w,h,left,top,viewWidth,viewHeight,right,panelWidth,bottom,statusTop;
bool pro,drawer;
ChromeLayout(int width,int height,bool professional,bool showDrawer,int inspectorWidth=320):w(width),h(height),pro(professional),drawer(showDrawer){
panelWidth=pro?(w>=1180?std::clamp(inspectorWidth,296,420):w>=960?296:showDrawer?296:0):0;
@@ -12,6 +12,7 @@ struct ChromeLayout {
right=w-panelWidth-20;viewWidth=pro?((w>=960||showDrawer)?right-left-14:w-left-20):w-left*2;
viewHeight=pro?std::max(160,h-306):h-88;
bottom=top+viewHeight+(pro?14:0);
+ statusTop=std::min(h-136,std::max(top+336,h-330));
}
};
inline void chromeText(HDC dc,HWND window,std::wstring value,int x,int y,int w,int h,int size,COLORREF c,int weight=FW_NORMAL,UINT flags=DT_LEFT|DT_SINGLELINE|DT_VCENTER){auto font=makeFont(window,size,weight);auto old=SelectObject(dc,font);SetTextColor(dc,c);SetBkMode(dc,TRANSPARENT);RECT r{dip(window,x),dip(window,y),dip(window,x+w),dip(window,y+h)};glassText(dc,value.c_str(),-1,&r,flags|DT_END_ELLIPSIS);SelectObject(dc,old);DeleteObject(font);}
@@ -26,17 +27,6 @@ inline void paintChrome(HWND window,HDC dc,const ChromeLayout& l,const engine::P
const std::wstring dimensions[]={extent(resolution.source.width,resolution.source.height),extent(resolution.base.width,resolution.base.height),!s.applied.nr?L"关闭":extent(resolution.nr.width,resolution.nr.height)};
const wchar_t* headings[]={L"SOURCE",L"OUTPUT",L"NR PROCESS"};
for(int i=0;i<3;++i){chromeText(dc,window,headings[i],l.left+20+i*column,l.bottom+94,column-4,20,10,secondary);chromeText(dc,window,dimensions[i],l.left+20+i*column,l.bottom+118,column-4,30,size,textColor);}
- if(l.panelWidth){
- chromeText(dc,window,s.transport==engine::TransportState::Playing?L"实时处理状态":L"最近处理样本",l.right+22,l.bottom+16,l.panelWidth-44,24,13,textColor,FW_MEDIUM);
- chromeText(dc,window,L"NR单阶段 · 16.7 ms 参考刻度",l.right+22,l.bottom+42,l.panelWidth-44,16,10,secondary);
- const auto sample=s.metrics.gpu[size_t(diagnostics::GpuStage::Nr)];
- float cx=float(dip(window,l.right+86)),cy=float(dip(window,l.bottom+105)),radius=float(dip(window,45));Pen track(color(line),float(dip(window,3)));Pen arc(color(accent),float(dip(window,3)));g.DrawArc(&track,cx-radius,cy-radius,radius*2,radius*2,140,260);if(sample.milliseconds)g.DrawArc(&arc,cx-radius,cy-radius,radius*2,radius*2,140,float(std::clamp(*sample.milliseconds/16.667,0.0,1.0)*260));
- chromeText(dc,window,sample.milliseconds?std::format(L"{:.1f}",*sample.milliseconds):L"—",l.right+41,l.bottom+78,90,38,27,textColor,FW_NORMAL,DT_CENTER|DT_SINGLELINE|DT_VCENTER);
- chromeText(dc,window,L"NR · ms",l.right+43,l.bottom+112,86,20,10,secondary,FW_NORMAL,DT_CENTER|DT_SINGLELINE|DT_VCENTER);
- chromeText(dc,window,L"源帧处理",l.right+158,l.bottom+65,130,20,11,secondary);
- chromeText(dc,window,s.frames?std::format(L"{:.1f} fps",s.fps):L"未测",l.right+158,l.bottom+88,130,30,19,textColor);
- chromeText(dc,window,s.applied.nrPolicy==pipeline::NrSizePolicy::Realtime?L"实时档 · 非原生4K NR":L"原生 NR",l.right+22,l.bottom+170,l.panelWidth-44,22,11,secondary);
- }
}
}
}
diff --git a/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md b/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md
new file mode 100644
index 00000000..3a654929
--- /dev/null
+++ b/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md
@@ -0,0 +1,70 @@
+# 继续修复实施记录
+
+状态:目标模式执行中。范围按 [继续修复方案](CONTINUATION_REPAIR_PLAN_2026-09-10.md),未完成全计划。起始代码 `be00e27`,保留上一轮方案文档改动。不启用旧Loop。
+
+## 2026-09-11 续接实证(优先于下面历史进度)
+
+整合检查补充:`build-fruc-ui-integrated.log`构建通过;`continuation-fruc-batch-final2/3`最新CUDA候选2X/3X通过(2.84/3.33秒),`continuation-fruc-batch-live`真实controller19项通过6.20秒,正常UI `ui-fg-1789058417812768300`通过。最新联合delivery `ad0a4e4680d748d0b97de6fe0e665c53` 23项PASS、42.35秒,EXE `24216560E25D6C84D0BF3656E3AC70BFCD8917F2BED52AE82AB9B4BF2B168778`,worker `DE38EFBE302FB3664EEC167A7FC3105154B877A4BBDFC8980DCC7C168B0C1678`。UI长错误行换行已编译,完整DPI尚未验收。
+
+AMD新增依赖证据:官方NuGet `Microsoft.Direct3D.D3D12/1.721.3-preview`,包SHA `0131BCE1E4BACE3FC08C03018C29A09EDE2570B263721C6449B0EC75762AB22D`;D3D12Core签名Valid/Microsoft,LICENSE.txt和LICENSE-CODE.txt原样保留。仅置`third_party_local/microsoft`与ignored隔离探针,未进主程序/Release/Git。`continuation-amd-linalg-capability`实际返回0x887E0003(SDK加载失败),没有成功创建设备或查询linalg;探针进程exit0只是完成错误记录,**不是能力PASS**。未改系统开发者模式。另核实上游`NativeActualNetwork70::RecordUnsubmitted`是曾触发device hung的诊断路径,接入必须保留分段提交;当前计划中单列表假设不可直接落地。
+
+- R1:GPU完成检查现在在呈现deadline等待及生产者两批反压期间非阻塞执行。观察者与呈现任务共享同一个FrameOutputs,不重复解析SDK状态;去掉旧processingRate与会话平均FPS赋值。Drop仍只重置历史账本、保留同revision的完成速率。尚非完整单GPU所有者状态机。
+- 阶段统计最近一秒均值/P95/样本数,GPU timestamp去重,250ms刷新,有界8192条与溢出计数;P95改为nearest-rank。Submit使用processDone-processStart,不包含后续统计开销。53项合同通过 `continuation-stage-p95-watch`;worker反压期间完成观察测试通过 `continuation-worker-progress`。
+- 实际RTX共享controller回放 `continuation-watch-half` 23项通过,8.51秒,含30/60处理、NR/2X/4X、暂停/设置/退出;测试EXE `EBD6CF1E4C101B36D0DFA042B4994A5EC580EE29F26346A58A7613F632524C04`。这是文件模拟采集,未打开实体采集卡。
+- 文件过载保持音频主时钟/追帧恢复已通过 `continuation-file-overload-fixed`(5项、7.06秒,最大观察领先113.33ms)。修复暂停seek卡在目标前关键帧,以及seekPreviewPending在EOS不清理的问题。文件音频750ms完整PCM/采样级seek/真实WASAPI测试通过,详见下文;不承诺GPU不足时仍无停顿。
+- 采集音频增加初始化/运行错误状态;不支持PCM时保留视频并显示原因。空Chunk.discontinuity原未初始化,已修正;停止/重启清空旧队列、时钟和视频锚点,持续100ms以上无输入且欠载时重锚。首版任何欠载即重置导致手动/关闭模式频繁重置,失败 `continuation-capture-audio-recovery` 保留,已修正。
+- 音频恢复回归 `continuation-capture-audio-recovery2` 通过,11.05秒:自动80/160ms、手动100ms、关闭、负偏移钳制、350ms断流、停止/重启;平均软件偏差/预期偏差误差约2.7至12.8ms,未溢出。测试EXE `6FA43505594A63CED540E259DE5D65162A8A8877DC70330D718F4E4CAFA0C11B`。合成PTS+真实静音WASAPI,不是实卡/物理扫描延迟验收;微量漂移重采样和平滑仍待做。
+- 原生PCM pin合同 `continuation-native-pcm` 已通过;预设schema7音频设置roundtrip `continuation-presets-audio7` 已通过。
+- **FRUC重置像素错误已有通过候选并进入当前源码**:原DirectX11Resource交给FRUC内部互操作的路径撤换为应用拥有的CUDA arrays。D3D12共享纹理经D3D11自有纹理桥接,CUDA graphics map/unmap明确所有权转换,GPU fence向父进程传递完成。直接注册D3D12共享纹理失败CUDA400,记录 `continuation-fruc-cuda-map`;使用D3D11桥后正确。未加入cuCtxSynchronize、CPU像素回读或显式逐帧CPU fence等待;CUDA SDK map/unmap本身可能阻塞,不能称完全异步。
+- 新FRUC常规reset只通知下个真实帧bSkipWarp更新历史,不销毁SDK/上下文/资源、不重启worker、不为reset调用ring.drainQueue;失败才回退重启自己拥有的worker。2X/3X/4X六次重置、正向/反向PTS、颜色反转与实际亚帧GT均通过 `continuation-fruc-default2/3/4`,2.70/3.14/3.64秒。初版正式候选worker SHA `5533EBA3ED6E6E925CB53412761375A66C635B9AF17158CA309CC0DA9FA39906`。
+- 之后同一CUDA context/整批map-unmap候选4X像素通过 `continuation-fruc-batch-map4`,worker SHA `ECD33BDB87C4C3F38D9992DDBD63A494074E38795F9E703C0EE1B3384E95D6A1`,编译日志 `build-fruc-batch-map.log`。最新2X/3X和联合回归待补;源码未存档提交。
+- FRUC实际controller已知平移回放 `continuation-fruc-cuda-known-live` 19项通过、7.11秒。另一个pan15素材的NR后FRUC报告repeated、没有有效补帧,`continuation-fruc-cuda-live`失败保留,不能篡改成有效输出;正确known-pan15素材具有独立SHA,不混淆两份素材。
+- **FRUC性能仍有限**:新增同一图120帧、最多两批、每30帧reset、无像素回读的吞吐用例。初版CUDA4X原生4K实际完成120真实+348生成,FG区间中位70.58ms、图提交CPU中位73.49ms、合成图填充+整图源吞吐11.18fps,`continuation-fruc-native4k-throughput`;1080p最终批量map版本FG中位26.05ms、CPU26.61ms、源吞吐33.88fps,`continuation-fruc-batch-throughput`。计时包含互操作/排队,不是FRUC纯网络内核时长。不能把正确性通过说成原生4K实时性能已修好,也没有精确HEAD旧worker同源A/B性能结论。
+- 本轮此前联合delivery `aba35e073bfb41edb6507d5f2caae220` 23项PASS、46.80秒(audio之后、最新完成观察/FRUC之前),只证明当时版本。最新联合gate待运行,不能沿用旧结果。
+
+下一步:FRUC候选生命周期/2X3X/集成回归、状态区长文案与DPI、单所有者调度,以及AMD NR依赖/provider。本机仍缺AMD网络权重、SM6.10预览编译环境与目标RDNA4硬件,未实现AMD NR;不可用说明或光流不算实现。未push/发布。所有测试单次少于300秒。
+
+## 已推进
+
+- R0部分:补帧页标题、后端、倍率、光流和内容节奏按明确行位置排列,移除后追加到标题位置的ID208。NR独立实现切换仍待接入。
+- XeSS初始化失败的设置事务回滚旧后端,不再把普通呈现fallback当XeSS切换成功;启动时的基础播放fallback保留,新增持久后端警告和实际活动状态。选择器上方显示applied后端与等待有效补帧/运行。
+- R1首版:同一FrameFlowWindow记录源帧完成、有效生成完成、总产出、Present提交和XeSS SDK送呈现速率;按batch去重、容量8192、停流衰减。保留`s.fps`兼容字段为源处理,底栏改用总产出或明确标注的XeSS SDK提交。
+- 软件总延迟使用真实源帧进入本进程至Present返回端点,最近一秒均值/P95;文件为取帧开始至Present返回驻留,非扫描/光子延迟。生成帧年龄与完整逐阶段聚合仍待补齐。
+- 实时状态改为独立可滚动区域,主产出/总延迟固定,其余处理/生成/呈现/输入、各阶段、尺寸和音频状态集中显示。布局和像素审查仍在进行。
+
+## 实际验证
+
+运行时:`runtime_local/nvidia/nvngx_dlssnr.dll` SHA256仍为`E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`,签名Valid。未替换DLL。
+
+`python scripts/acceptance/ui-fg-backends.py`:旧EXE实测失败,标题 `[994,294,1266,324]` 与后端 `[994,290,1266,318]` 重叠,证据 `logs/continuation-repair-20260910/ui-fg-1789052091042365500/result.json`。初版脚本在专业动画前取状态误报隐藏,已改为等待专业模式。
+
+Release构建通过:`powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root <root> -Preset x64-release`,日志 `logs/continuation-repair-20260910/build-r0*.log`、`build-r1.log`。已有FFmpeg转换警告与probe未使用变量警告,未新增编译错误。
+
+R0正常UI切换通过:`ui-fg-1789052625652703800`,FRUC -> XeSS -> DLSS -> off,两种窗口尺寸、真实自绘popup点击提交、applied版本一致,9.73秒。对应EXE SHA `74ECED96D403B9CEB63E00836B981E81210A02B16087BF8B85B25641E69BCA44`。XeSS为实际SDK初始化与呈现,不是AMD实卡或扫描验收。
+
+`python scripts/acceptance/ui-fg-backends.py --reject-xess`通过:`ui-fg-1789052653905109600`;故障注入在加载前返回失败,FRUC保留、applied日志不出现XeSS,再切DLSS/关闭成功。没有破坏/重命名本机DLL。测试观察应用控件revision,退出后复核日志;之前只等缓冲日志曾超时,但退出日志确认DLSS已应用,已修测试判定。
+
+`scripts/acceptance/scheduler-short-test.ps1 -Name continuation-r1-contract -Exe out/build/x64-release/veyra_repair_contract_tests.exe`通过49项:60真实+40有效生成=100产出、90呈现、重复完成不计、XeSS单列、延迟样本衰减、1000fps支持;0.10秒,日志在`logs/scheduler-repair-20260910/continuation-r1-contract.*`。
+
+`scripts/acceptance/scheduler-short-test.ps1 -Name continuation-r1-half -Exe out/build/x64-release/veyra_live_presentation_tests.exe -TestArgs @('loop/local/fixed_clips/test_av_1080p.mp4','logs/continuation-repair-20260910/live-half','--half-rate')`通过23项,10.98秒。GPU真实完成30/60切换、NR/2X/4X、暂停/重配/退出、有界租约与epoch。文件模拟采集,未占实体采集卡。
+
+R1首版UI切换通过:`ui-fg-1789053218053203700/result.json`,EXE SHA `C4571EF78ED0F8883E61A2CD7B6B38D49C7719E4EB09B80502492F461817E6BC`。该次截屏被其它前台窗口遮住,不能作为状态区视觉通过证据;后续改用本应用窗口独立绘制截取,不操作其它软件。
+
+## 当前未完成
+
+### 续接进展(2026-09-10,仍在施工)
+
+- R1补正:Drop只重置epoch账本,同revision的完成速率窗口保留,避免重载时永远“采样中”;新revision仍独立。51项CPU合同通过,`continuation-rates-epoch`,0.072秒。小窗口保留参数区域至少约200逻辑像素,状态明细滚动;`ui-fg-1789055596503007200`正常切换通过,含1040x540请求尺寸;不是完整100/150/200DPI验收。之前独立窗口截图发现状态区glassText绕过父DC clip,已跳过半露行,`ui-fg-1789053467482583100`复测通过。截图不能证明flip视频像素。
+- 文件音频确认并修正:原`nextPtsMs_`在push前被赋为输入音频块结束PTS,错误偏移一个块;按输入PTS减swr延迟标记输出开头。处理decoder EAGAIN/EOF和resampler尾样本,seek按输出样本裁剪、清空swr历史,seekRequested改atomic、ring水位加锁。WASAPI先填真实PCM再Start,未启动/reset/clock失败返回NaN;requestSeek返回实际重锚PTS,不返回已被首缓冲消耗后的队头。初版paused-seek测试因此失败,修复后通过。
+- `veyra_audio_timeline_tests`两种PCM输入(44.1/48kHz)均完整输出36000个48k样本/750ms,PTS误差约1.7e-12ms;采样级seek、设备暂停、seek重锚、无效clock测试通过。实际WASAPI输出设静音,`continuation-audio-timeline-fixed`,0.544秒,测试EXE `3658B889A2E2E19F6B8F2242BDA226C356CA67CA666664321195D4ACE2DD5481`。
+- 采集音频施工:新增共享`AudioPcmSource`接口,`CaptureAudioSession`复用AudioRenderer;原NativeCaptureSink扩展明确PCM类型的终端pin。DirectShow音频不再RenderStream自动直通,协商PCM后写有界队列,图显式SystemClock,WASAPI线程转换/播放。视频Present PTS/host映射估算自动0..250ms补偿;声音队列/偏差/重锚/溢出显示。新设置自动/手动/关闭,手动-250..250ms,负值实际钳制到0;预设schema7兼容旧版,roundtrip通过`continuation-presets-audio7`。当前策略仍需审查突变、过载、端点错误和真实设备;不能称实体采集音画已经修好。
+- `veyra_capture_audio_tests`合成连续PCM与80ms视频延迟,真实WASAPI:平均绝对软件偏差12.795ms,89样本,补偿86.622ms、PCM队列58ms、0溢出/0欠载,`continuation-capture-audio80`,1.698秒。仅验证合成PTS,不打开实体采集卡,不测scanout。
+- 文件过载新增共同缓冲:音频领先视频>80ms暂停音频主时钟,视频保留所有源帧推进,追到20ms内恢复;刚写入,尚未构建/验证,不当通过。
+- FRUC新候选:worker双向D3D11自有纹理桥接(输入、输出均经D3D11复制)。首次缺NTHANDLE导致Register=3;补标志后API成功但reset像素仍旧输出(第二对偏移-12而应-4)。`continuation-fruc-owned{,2}`失败,全部候选已撤回,Worker与HEAD无逻辑diff。尚未修复FRUC reset,不引入cuCtxSynchronize产品等待。
+- AMD固定仓库成功克隆到ignored `third_party_local/amd/nr-d3d12`,sparse checkout `src/shaders/scripts`,detached `628620a74f3fcd3b5081620bd86308f57fc210a3`。README确认完整71block、SM6.10 FP8 linalg、Agility721,权重不在仓库(作者约16GB含参考dump),本机尚无权重/预览编译器/目标RX9070XT。本轮还未接provider,不将AMD光流或选择器算作AMD NR完成。未修改或抽取本机NR二进制。
+
+最新已构建UI EXE(音频设置后、文件过载补丁前)`BAE93B5DE106E8940815FDA017CFA9E93C599902EE8531817B469B72E8219792`,`build-audio-settings.log`。第一次采集音频构建因缺mmreg.h失败,修复后通过。所有失败日志保留,单次测试<300秒。未Git提交、未push、未发布。接着验证文件过载/采集突变与Native音频pin,再推进GPU完成观测/调度和AMD依赖。
+
+R0 NR backend/provider、R1完整计时与状态布局验收、A1 AMD完整网络、R2 FRUC同步/完整GPU状态机、R3音画同步及R4集成回归均未完成。新指标仍由原presentation worker观测GPU-ready,尚未解决该观测时机受调度等待影响的问题。文档和测试通过不是全目标完成。
+
+下一步:完成R1窗口自身截图与小尺寸布局审查、补充统计回归,再按方案推进AMD provider和FRUC/音频。代码在工作树,未push、打包或发布。
diff --git a/docs/CONTINUATION_REPAIR_PLAN_2026-09-10.md b/docs/CONTINUATION_REPAIR_PLAN_2026-09-10.md
new file mode 100644
index 00000000..ab68ae27
--- /dev/null
+++ b/docs/CONTINUATION_REPAIR_PLAN_2026-09-10.md
@@ -0,0 +1,281 @@
+# 后端切换、真实帧率、链路延迟与音画同步继续修复方案
+
+日期:2026-09-10。状态:方案已写入,待实施;本文不代表以下功能已经修复。代码基线:`be00e27`。
+
+本轮对应用户提出的五项问题,并承接上一轮没有完成的 FRUC reset、GPU 调度和计时任务。当前执行入口为本文、最新用户指令和 [WORKLOG](WORKLOG.md)。旧 Loop、控制哈希和 Phase 排队不再生效;单次测试最多 300 秒,不是全部测试累计五分钟。
+
+## 1. 为什么上一轮没有全部完成
+
+上一轮完成的是 DLSS 采集提交前跳过、帧流账本和部分生命周期修复。FRUC 同步候选失败后撤回是必要的,但随后以部分成果收尾,没有完成原计划 S3/S4,也没有解决用户端的完整操作闭环。这属于未完成交付,不能用联合短测通过替代。
+
+已有验证也存在覆盖缺口:
+
+- XeSS 独立 GPU 用例调用成功,不证明专业页上的选项可见、可点击、可实时切换。四个弹出选择器的通用 UI 回归也没有证明 XeSS 这一具体入口。
+- AMD FidelityFX 光流执行成功,不证明 AMD NR 已接入。目前没有 AMD NR provider,不能称为已经支持 AMD DLSS5。
+- 源帧完成计数正确,不代表满足用户要看的包含有效补帧的处理产出 FPS。
+- FRUC 普通回放通过,不覆盖已知失败的重置后像素检查。
+- 旧交接页没有跟上实施,仍把已加入的 XeSS 和 SR 目标称为研究阶段。本轮同步当前入口,旧记录只保留历史用途。
+
+后续每项完成必须同时满足:用户能操作、请求确实生效、真实数据能验证、异常状态可见。缺任一项都继续列为未完成。
+
+## 2. 当前事实与定位
+
+| 用户问题 | 源码核对结果 | 本轮结论 |
+| --- | --- | --- |
+| 找不到 XeSS FG | `SettingsWindow.cpp` 已创建 ID 208,含 DLSS/FRUC/XeSS;但 y=8 的选择器与 y=12、高30的标题1103重叠 | 已确认布局矩形冲突;是否完全遮住及点击命中仍需运行 UI 验证 |
+| AMD / NVIDIA NR 不能分开选 | `EnhancementSettings.h` 只有 NR 开关、参数、尺寸策略;没有 `NrBackend`。`OpticalFlowBackend::AmdFidelityFx` 只控制光流 | 需要真正的 NR provider 接入及切换事务,不能只补按钮 |
+| FPS 不符合实际产出 | `EngineController::snapshot()` 用 `processingRate_` 覆盖 `s.fps`,完成事件来自 `resolveGeneration`,只计真实源帧;生成/Present 已有另外的计数 | 并非直接把输入 FPS 填进处理 FPS,但未统计最终处理产出;完成观测还受呈现 worker 推进影响 |
+| 实时状态区信息不足 | `WorkspaceChrome.h` 固定画 NR 圆环和源帧处理,其他指标分散在 `TelemetryWindow.cpp` | 改成集中、紧凑的实时状态区,使用同一份指标快照 |
+| 处理后音画不同步 | `CaptureCardSource.cpp` 用 DirectShow `RenderStream(...Audio..., nullptr, nullptr)` 自动接音频 renderer;视频走独立 GPU/FG/Present | 采集没有可控 PCM 延迟队列与共同呈现时钟,具有音频先走、视频迟到的结构 |
+
+XeSS 的本地官方 SDK 3.0.2 在 `xefg_swapchain.h` 将 `framesPresented` 定义为 “Number of frames sent to be presented during the last call.” 当前 `XessPresenter::afterPresent()` 累加该值。它是 SDK 报告的送呈现数量,不是本应用测得的逐帧 GPU 完成或屏幕扫描数量。
+
+文件播放已有 `AudioPipeline`、WASAPI `AudioRenderer` 和音频主时钟,不能按采集直通问题一并推倒。需要核对首缓冲与 `IAudioClock` 锚点、暂停/seek、欠载及持续 GPU 过载时的共同推进。
+
+## 3. 后端开关与切换合同
+
+### 3.1 专业模式控件
+
+增强页按独立含义排列:
+
+1. NR 增强开关。
+2. NR 实现:`NVIDIA NR` / `AMD NR(实验)`。
+3. NR 处理尺寸:实时档 / 原生档,仅列当前 provider 真正支持的模式。
+4. 超分开关、算法与 2K/4K/8K 目标,保持现有功能。
+5. 当前 NR provider 实际支持的参数和保护区域。
+
+补帧页按固定行排列:页标题、`补帧方式`、后端选择器、倍率、`运动估算`、光流后端及其参数、内容节奏。DLSS / FRUC / XeSS 必须在独立可见的位置切换;XeSS 当前为预览 2X,不提供假 3X/4X。
+
+修改 `SettingsWindow.cpp` 的局部布局表,取消本页追加控件时反复推移 y 坐标的脆弱方式。区分 combo 折叠可视高度与下拉列表高度,使用同一组行高计算布局、滚动范围与命中区域。保持现有毛玻璃和自绘选择器;鼠标滚轮只滚页面,不改参数。选项不可用时保留名称并显示原因,不能直接隐藏。
+
+`NVIDIA NR` 是当前固定身份的实验 Feature 18 路径,不把“原版”改称官方公共 SDK 集成。`AMD NR(实验)` 是另一种网络执行实现,既不是 AMD 光流,也不是在 NVIDIA 下拉项上换名称。
+
+### 3.2 配置事务
+
+在共享设置中增加 `NrBackend`,沿用已有 desired/applied revision、校验、预设迁移和失败回滚。NR 开关、provider、内部尺寸、光流和 FG 分开保存。旧预设缺省为当前 NVIDIA 路径;未知枚举拒绝或明确迁移,不能索引越界。
+
+统一向 UI 提供 `requested / applied / capability / reason`,后端状态至少区分关闭、切换中、预热、运行、不可用、失败。只有成功初始化并得到对应 provider 的有效输出后,才能显示“运行”。SDK DLL 存在或配置写入成功不够。
+
+切换在源帧边界提交,取消旧异步工作、等待已用资源的消费者 fence、推进 epoch 并统一 reset。创建失败保留上次可用会话,UI 指出请求未应用;不能用户选择 AMD/XeSS 后悄悄继续 NVIDIA/DLSS 并显示已切换。更换物理适配器需要重开设备,不能伪装成同一 device 的无缝 provider 切换。
+
+XeSS 涉及代理交换链和 XeLL,验证 DLSS -> FRUC -> XeSS -> 关闭 -> DLSS 的资源释放与重建。呈现结果只计一次,切换关闭时不能残留旧 SDK 生成计数。XeSS 不支持导出;保留明确的预览能力边界。
+
+### 3.3 AMD NR 本体
+
+承接 [AMD NR 研究方案](SR_TARGETS_AMD_NR_PLAN_2026-09-10.md) 的固定来源。首选候选仍是 MIT D3D12/HLSL 网络核心,固定提交 `628620a74f3fcd3b5081620bd86308f57fc210a3`。本轮没有重新联网审计上游,不把旧研究当新增实测。
+
+实施闭环:
+
+1. 复核固定提交、许可证、最小依赖和本机编译条件。只复用网络核心并保留归因;不加载 ReShade add-on,不把 SDK、模型、权重或 dump 放进源码 Git。
+2. 在实际 device 上查询 SM6.10、D3D12 linear algebra、所需 FP8/FP16 类型和矩阵形状,验证对应 PSO 创建。以能力和结果为准,不能仅用 GPU 品牌判定。
+3. 独立实现 `AmdNativeNrBackend`,封装网络创建、记录、完成资源和 reset;优先同 device/queue。确需不同 Agility 环境才采用隔离 worker,资源与请求均有界。
+4. 按现有研究先支持 1920x1080 内部网络和1920x1152 padding;完整执行网络,核对时间历史、颜色 encode/decode 和输出随输入变化。不能默认叠加两次 parity,也不能把普通锐化或原图回传当 NR。
+5. 接入共享 `EnhanceGraph` 的 NR 节点,继续 SR -> NR -> FG。当前帧、motion、尺寸、epoch 和资源 fence 一致;参数仅暴露网络实证支持的部分。
+6. 用户可选择 AMD 实现;实际不支持的硬件/模式给具体原因。本候选暂不能兑现原生4K/8K NR时,必须显示实际内部1080尺寸,不能静默冒充原生模式。图片和视频导出沿用现有原生策略及检查,未通过的 AMD 组合明确不可用。
+7. 在合适的目标 AMD GPU 上完成网络与产品路径验证,记录 adapter LUID、完整执行、GPU时间、显存峰值、同图对照与连续帧reset。只有这些通过才称 AMD NR 功能完成。
+
+现有本机证据是 RTX5070 与 Ryzen9700X 核显,不是上游验证的 RX9070XT。没有目标硬件执行就明确“AMD 实机未验证”。灰色选择器和 capability 拒绝只是交互/错误处理完成,不能代替第3至7步。
+
+ZLUDA 保留离线技术候选;不把逐帧 CPU 同步或黑图路径接入默认实时图。HIP 二进制路线沿用已核对的限制,不假定外层 MIT 授予其再打包权。现有 Runtime Pack 授权也不自动涵盖新增模型/运行时;本次不扩大发布范围。
+
+## 4. 实际帧率统计
+
+### 4.1 指标定义
+
+| UI 名称 | 统计事件 | 不允许的替代 |
+| --- | --- | --- |
+| 处理产出 FPS,主值 | 最近一秒完成的真实输出帧 + 有效生成输出帧,同窗去重;两部分都必须已 GPU-ready | 输入FPS乘倍率、CPU提交、Evaluate次数、重复/无效/预热帧 |
+| 源帧处理 FPS | 真实源帧输出完成 | 采集回调或文件标称FPS |
+| 有效补帧 FPS | DLSS/FRUC实际有效且GPU完成的中间输出 | 请求倍率、候选数量、仅API成功 |
+| 呈现提交 FPS | 实际成功送入呈现的真实/生成帧事件,分别保留分量 | 显示器刷新率、理论目标FPS、失败Present |
+| 采集输入 FPS | 采集回调实际到达事件;标称模式单列 | 固定设备参数直接当实测 |
+| XeSS 提交 FPS(SDK) | 每次 Present 对应的 `framesPresented`,按present ID和窗口只累计一次 | 本应用GPU完成率或屏幕扫描率 |
+
+“处理产出”反映算出了多少,“呈现提交”反映送出了多少。已经完成但后来过期的有效生成帧属于已做的计算,必须同时进入过期/未呈现统计;不能靠高产出数遮住低呈现。页面主值旁始终保留呈现提交值及过载状态。
+
+XeSS 的生成帧在 SDK 代理交换链内部,目前没有本应用可独立读取的逐帧输出 fence。启用 XeSS 时主位置改为明确的 `输出提交 FPS(XeSS SDK)`,另保留源帧处理 FPS;`处理产出总计`显示不可独立测量。不能把两种口径混在一个无标签的“实时FPS”里。将来新增可信完成事件后才扩展测量。
+
+### 4.2 数据实现
+
+- 扩展 `FrameFlowWindow` 与 `FrameMetrics`,所有事件携带 session、applied revision、epoch、source sequence、batch、real/generated index和相关fence。完成、取消、过期、提交各计一次。
+- 统一采样时钟和窗口宽度,避免把两个不同起点的FPS相加。最近1秒事件窗口,UI每250ms刷新;窗口未满时标明采样中。保留支持1000fps的容量,不限制60。
+- GPU-ready观测从呈现等待中解开:不能等到某生成帧的计划显示时间才记录上一批处理完成。复用非阻塞fence检查与既有等待机制,不增加忙轮询或每帧CPU等待。
+- fence轮询是主机观测完成的时间,不能伪装成GPU精确完成时刻。记录观测滞后;GPU阶段耗时继续用timestamp。状态机改造后检查突发计数是否来自轮询被阻塞。
+- session/设置切换清空窗口,旧事务完成不能混入新设置;epoch reset时明确窗口边界与预热状态。高频Drop不能让UI不断把极短窗口外推成高FPS;样本不足就显示采样中并保留丢帧计数。
+- pause/stop一秒内归零,图片单次处理显示单帧耗时,不显示持续播放FPS;没有样本、阶段关闭、失败不可测、有效0分别表达。
+- 清理 `PlayerSnapshot::fps` 的歧义命名和内部旧平均值赋值;底栏、状态区、诊断窗与日志消费同一快照,不能各算一套。
+
+示例仅用于验收算术:60个真实输出+40个有效生成输出,应显示处理产出100;其中仅30个生成输出送呈现,则相应呈现最多90,不能显示240。这个例子不是当前软件实测值。
+
+## 5. 总延迟与分链路计时
+
+### 5.1 总延迟的可测边界
+
+主指标命名为 `软件总延迟`。采集真实帧采用该帧回调进入本进程至对应 Present 返回的时间差。同步显示测量边界;它不包含能准确还原的采集卡硬件前段,也不等于HDMI到屏幕发光延迟。
+
+生成帧没有独立采集回调。记录父帧A/B、生成PTS、B到达至送呈现时间,并按有效的源PTS到QPC映射计算其时间线年龄;不得直接拿B的arrival冒充生成帧完整年龄。无法建立映射时显示未测,不能用固定 `1/f` 替代lookahead。
+
+文件模式显示 `软件驻留时间`(该帧进入处理至Present返回)与 `PTS迟到`(相对音频主时钟),不把解码预取驻留全部叫交互延迟。非实时导出继续使用吞吐/进度口径。
+
+XeSS可测的总延迟终点是代理 Present 返回;SDK内部呈现排队和实际扫描若没有公开测量则显示未知。不要把这个时刻作为已经上屏。
+
+### 5.2 阶段与统计
+
+| 阶段 | 测量方式 |
+| --- | --- |
+| 采集等待 / 解码 | 回调、read/decode开始结束的QPC;硬解GPU耗时有独立支持才报告 |
+| GPU槽位 / CPU提交 | slot租约与submit边界QPC、等待次数、in-flight峰值 |
+| 输入颜色、SR、光流、NR、残差合成 | 现有D3D12 GPU timestamp,绑定当前frame identity |
+| FG | DLSS各子帧及整批区间;FRUC有证据的实际执行完成区间;XeSS内部耗时不可得则未知 |
+| 输出转换 / blit | 相关GPU timestamp,不漏算也不重复计入颜色项 |
+| GPU就绪等待 | 提交/观测与消费者等待分开,不称GPU执行耗时 |
+| 补帧等待下一源帧 | A/B的实际到达与PTS关系,单列算法等待与配置的lookahead数量 |
+| 呈现等待 / Present | deadline等待与API调用分别计时 |
+| reset / 重建 | 按原因记录排空、销毁、创建、预热与恢复首个有效输出时间 |
+
+总延迟直接由同一帧的首尾时刻取得,不通过相加上述行计算。CPU/GPU阶段可能重叠,多队列timestamp必须核对各自frequency与校准;各项P95相加也不等于总延迟P95。关闭、待完成、不可测不能全部显示0ms。
+
+状态区默认显示最近一秒均值和总延迟P95,详情列样本数与各阶段P95。聚合来自同一窗口、同一applied配置;过期样本不沿用为当前实时值。逐帧诊断用固定容量环(初值8192条、溢出计数),每秒落一次汇总;错误立即记录。不增加正常视频像素回读。
+
+## 6. 实时处理状态区布局
+
+改造截图中现有区域,不另开必须手动寻找的诊断窗口。删除占据大块面积的固定16.7ms NR圆环,将NR作为链路耗时一行。
+
+结构示意,`--`均为布局占位,不是测量结果:
+
+```text
+实时处理状态 运行 / 预热 / 过载
+处理产出 -- fps 软件总延迟 -- ms
+呈现提交 -- fps 总延迟 P95 -- ms
+源帧处理 -- fps 有效补帧 -- fps
+采集输入 -- fps 丢帧 / 过期 -- / --
+------------------------------------------------
+采集/解码 -- ms 槽位等待 -- ms
+颜色转换 -- ms 超分 SR -- ms
+光流 -- ms NR -- ms
+残差/合成 -- ms 补帧 FG -- ms
+输出转换 -- ms 呈现等待 -- ms
+Present -- ms 音画偏差 -- ms
+------------------------------------------------
+NR实现 + 实际内部尺寸 / SR目标 / FG方式与倍率
+音频同步状态 / 当前补偿量 / 不可用原因
+```
+
+文件输入、FG关闭、XeSS、无音轨时采用上述定义对应的行名和状态。输入FPS只作辅助,主值始终具有明确的处理或SDK输出含义。底栏也同步更改口径,不再一个位置叫处理、另一个位置拿输入值代替。
+
+布局实现约束:
+
+- 调整 `ChromeLayout` 和 `AppShell` 对状态区、参数区、播放条的边界预留,不能只往当前固定高度里继续画字。
+- 296至420逻辑像素侧栏使用紧凑两列指标;窄窗口按整行重排。短窗口可滚动状态明细,主值和总延迟保留可见;不遮视频、不遮播放条,日常模式保持简洁。
+- 数字用固定宽度区域,主值字号约18至22,阶段字号约11至12;小数变化不引起布局抖动。长后端名换行,不截掉重要不可用原因。
+- 保留现有真实毛玻璃、透明文字和自绘控件;只刷新变化区域,避免全窗口擦白和原生背景闪烁。
+- UI验收必须覆盖100%/150%/200%DPI、最小窗口、最大化、拖动缩放、专业展开、滚动、全屏进出和选择器弹出。
+
+## 7. 音画同步修复
+
+可以修复“Veyra里的音频先播放、画面后处理完成”这类错位,方法是按同一媒体时间线安排声音播放。它不能消除NR计算和FG等待成本,也不能延后PS5/电视/外部耳机绕过Veyra播放的声音。
+
+### 7.1 采集音频
+
+1. 把自动音频renderer直通改成受控音频接收,优先复用现有DirectShow原生sink模式,取得协商后的PCM格式、sample PTS、duration及discontinuity。回调只写有界PCM环,不进行GPU工作或阻塞等待。
+2. 明确DirectShow参考时钟及audio/video sample PTS到QPC的映射。新renderer不能无意改变图时钟而让视频回调节奏漂移。设备PTS缺失或时钟不一致时给估算标记,不能报告精确同步。
+3. 提取现有WASAPI sink可复用部分,以小范围PCM source接口接入文件和采集;不复制第二套播放器。格式转换/重采样只做必要一次,保留音量、静音、设备选择。
+4. 从对应视频PTS的实际送呈现进度估计音频目标播放时刻,结合 `IAudioClock`、当前padding、设备延迟决定PCM何时提交。FG用生成PTS参与时间线,不把整个NR耗时、总延迟和lookahead重复加三遍。
+5. 自动补偿初定0至250ms,默认自动;PCM环容量覆盖补偿和小幅抖动但有硬上限,队列满就明确报告并按采集恢复策略重锚,不能无限积压。实际队列量、设备队列量与总补偿分别可见。
+6. 微小偏差用有界平滑/缓慢重采样校正时钟漂移;突变在可控边界flush、短淡入淡出并重新锚定,避免一改NR质量就爆音或频繁拉扯音高。不要靠不断增加音频队列追逐持续过载的视频。
+7. 设置提供自动 / 手动 / 关闭。手动偏移初定-250至+250ms、1ms步进,正值表示声音更晚,负值只减少已有可用延迟;无法提前尚未到达的声音,显示实际钳制值。滚轮不修改偏移。
+8. GPU持续过载、音频已比视频更晚或达到补偿上限时,显示无法完全对齐的原因。默认不增大视频两批上限;更大的视频补偿必须另有显式模式,不能偷偷加队列。
+
+`音画偏差`按同一主机时刻下估算的正在播放音频PTS减去视频呈现PTS计算,正值定义为声音领先。呈现端仍有未知扫描延迟时标为软件估算。设备缓冲已包含的时间不再重复补偿。
+
+### 7.2 文件播放
+
+- 保留音频主时钟与源PTS;解码预取500ms不等于人为听觉延迟500ms,不直接删缓冲追求表面低延迟。
+- 核对先填首批真实PCM、启动WASAPI和建立有效clock anchor的顺序。时钟未启动或设备报错时必须是无效状态,不能以默认0作为可信媒体时间。
+- pause/resume、seek、EOF、换音频设备和切换后端时,音视频统一暂停、清旧缓存、重锚并恢复。取消旧epoch后不能播出旧音频。
+- 暂时欠载允许有界共同rebuffer;若当前画质持续低于实时速度,则明确提示当前组合无法实时播放,保持共同暂停或等待用户调档,不能音频一直前进、视频长期追赶。
+- 文件播放和导出不为追帧静默丢真实源帧,不改PTS,不把预览音频补偿写入导出的音轨时间线。导出完整性代码与既有检查保持现状。
+
+### 7.3 同步验收
+
+先用带已知同PTS闪光/蜂鸣的合成素材和可注入延迟的媒体时钟测试,覆盖0/20/60/120ms视频延迟、抖动、60传输30处理、后端切换、暂停/seek、音频设备丢失和补偿上限。
+
+内部目标:在处理能够持续实时且时钟有效的场景,收敛后软件估算A/V偏差绝对值P95不超过30ms;改变配置后两秒内重新收敛,不能持续漂移或无界排队。该数值是待验收目标,不是现有测量结果。首次先用120秒短测,单项仍不超过300秒。
+
+内部计时通过不证明外部听觉/屏幕同步通过。再由用户实卡验收;如进行loopback录音或屏幕捕获诊断,注明其自身延迟边界,不把它当高速相机光子测量。
+
+## 8. 上一轮遗留的调度与 FRUC 修复
+
+### 8.1 FRUC 必须以像素修复为通过条件
+
+沿用 [上轮实施记录](SCHEDULER_REPAIR_IMPLEMENTATION_2026-09-10.md) 的失败证据:重置后首对可能返回上一真实帧,第二对可能返回上一对插值。诊断性的 `cuCtxSynchronize` 加D3D11完成通知通过6个epoch,但纯GPU completion候选没有通过,最终均已撤回。
+
+下一步建立输入写入 -> CUDA/D3D11映射 -> FRUC执行 -> 输出可见 -> D3D12消费的逐步资源与fence证据。每一步必须指向同一个资源、generation和生产者完成条件,重点核对SDK实际操作的上下文/stream、共享资源映射生命周期及旧输出复用。
+
+先复现 `--reset-pixels`,再一次改变一个同步点;诊断回读只用于测试。生产路径不得采用每帧 `cuCtxSynchronize`、CPU fence wait或提高超时来掩盖错误。轻量reseed必须与fresh worker对比颜色/位移/PTS;fresh worker本身也要过像素检查,不能默认它正确。
+
+仅在reset像素和恢复时间通过后重新接FRUC admission。必须检查跳过 -> 恢复 -> 有效生成的闭环,避免重复重建导致一直预热、有效生成永远为0。失败时保留上一可用路径及明确已知限制,不能把FRUC项目标为完成。
+
+### 8.2 完整调度和已证实的性能浪费
+
+- 完成旧S3:单一GPU所有者推进submit、fence-ready、deadline及present;UI与回调只发命令。不能在锁内等待未来PTS,使GPU-ready统计和新源读取一起停住。
+- 采集真实源帧coalesce发生在昂贵SR/NR提交前,只消费仍有价值的最新帧;有意60->30取样与mailbox丢帧分开,正确reset历史。文件/导出不使用此淘汰规则。
+- 保持mailbox=1、呈现active+queued<=2、现有有界texture/command slot;已提交GPU工作不能撤销,其租约等消费者fence后再复用。
+- 完成旧S1剩余的reset耗时、逐帧固定环和ready观测,供本方案指标使用。
+- 旧S4按新证据逐项决定:仅合并确认浪费的小提交,核对NGX/NVOF/FRUC依赖和资源状态。没有收益就保留测量结论,不为完成任务强行合并。
+- 同配置对照源吞吐、有效生成、呈现节奏、总延迟P95、slotwait与显存;GPU占用降低但产出/呈现更低不算性能修复。
+
+## 9. 执行顺序和修改边界
+
+| 顺序 | 任务 | 主要文件/模块 | 完成条件 |
+| --- | --- | --- | --- |
+| R0 | XeSS可见性、独立NR后端设置、能力/实际后端状态 | `SettingsWindow.cpp`、`EnhancementSettings.h`、`PresetStore.cpp`、`EngineController`、`PopupSelector.h` | 用户能找到/选择XeSS,正常/失败切换真实可见,预设兼容;AMD本体仍单独验收 |
+| R1 | 统一FPS与链路计时、改实时状态区 | `FrameMetrics.h`、`FrameFlowWindow.h`、`FrameRateWindow.h`、`EngineController`、`EnhanceGraph`、`XessPresenter`、`WorkspaceChrome.h`、`AppShell.cpp`、`TelemetryWindow.cpp` | 数字来自事件,区分GPU完成/SDK提交/Present;所有链路与总延迟集中显示 |
+| A1 | AMD NR完整网络闭环及共享图接入 | 新NR provider、按能力初始化、候选独立构建target、共享颜色/reset | 真网络与有效输出;硬件缺口明确列出,不用光流/灰按钮算完成 |
+| R2 | FRUC同步、S3状态机、采集coalesce、S4测量决定 | `FrucBackend`、`FrucWorker`、协议、`PresentationWorker`、`EngineController`、`CommandSlotRing` | reset像素与恢复通过,事件/租约一致,无无界排队,性能A/B有证据 |
+| R3 | 采集/文件音画同步 | `CaptureCardSource`、`NativeCaptureSink`或音频sink、`WasapiAudioSink`、`EngineController`、专业设置 | 共同PTS/clock、受控补偿、过载/设备异常明确、A/V短测达标 |
+| R4 | 集成回归、当前交接与本地存档 | `tests`、`scripts/acceptance`、`docs` | 五项用户需求及R2分别交账,未验收项不被整体通过掩盖 |
+
+首项唯一动作:复现专业页ID208与1103重叠并修补帧页布局,验证XeSS项实际可选、applied后端真正变化。之后按上表推进。A1遇到真实硬件或依赖阻塞时,记录具体缺口并继续R2/R3;最终报告仍保留AMD未完成状态,不能因其它修复通过就写全部完成。
+
+R1的GPU-ready观测与R2状态机存在依赖:先完成可用统计合同和UI,再在R2后复验观测滞后;不能提前宣称最终处理速率已完全消除调度偏差。R3使用R1/R2稳定的时间线;AMD provider接入同一时间线,不额外建计数和音频系统。
+
+## 10. 测试与证据要求
+
+单次外部超时设为290秒,留进程清理余量;不并行抢同一GPU/采集卡。先窄测再集成,不重复跑与改动无关的长测试。
+
+| 检查 | 场景与真实证据 |
+| --- | --- |
+| 控件和事务 | 三个FG选项逐一点击、NR实现切换、关闭/暂停时修改、旧预设、不可用原因、快速连续操作、DPI/窄窗/滚动无覆盖 |
+| FPS事件合同 | 15/30/60/1000事件率,完成与CPU提交错开,重复完成、预热、过期、取消、reset、停流;60+40例子符合定义 |
+| GPU后端 | DLSS/FRUC 2X/3X/4X分别验证,XeSS 2X单列SDK呈现计数;AMD NR需目标设备完整执行和像素;API成功不够 |
+| 延迟 | 注入已知等待验证首尾总延迟;重叠CPU/GPU阶段不被重复相加;关闭/未知阶段状态正确,旧epoch不污染 |
+| FRUC | `--reset-pixels`全部epoch、fresh worker与reseed对照、2X/3X/4X恢复后有效生成;普通live通过不能替代 |
+| 调度 | realtime与原生4K高成本档各自固定配置A/B;source/setting切换、scene cut、drop、resize、device lost;界限/租约/PTS正确 |
+| 音频 | 合成A/V、可控延迟、补偿边界、时钟漂移、seek/pause/重开、设备丢失、无音轨;内部与实卡结论分开 |
+| 旧能力 | 60->30->60、SR2K/4K/8K已有路径、图片、文件播放、NVENC导出和取消;不扩大导出检查 |
+
+已有可复用命令示例,实施时按实际参数和新增target更新记录,不能复制为“已运行”:
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release
+./scripts/acceptance/scheduler-short-test.ps1 -Name continuation-contract -Exe ./out/build/x64-release/veyra_repair_contract_tests.exe
+./scripts/acceptance/scheduler-short-test.ps1 -Name continuation-worker -Exe ./out/build/x64-release/veyra_presentation_worker_tests.exe
+./scripts/acceptance/scheduler-short-test.ps1 -Name continuation-fruc-reset -Exe ./out/build/x64-release/veyra_fruc_tests.exe -TestArgs @('2','logs/video-sdk-trial-20260909/pan.nv12','--reset-pixels')
+./scripts/acceptance/scheduler-short-test.ps1 -Name continuation-xess -Exe ./out/build/x64-release/veyra_experimental_backend_tests.exe -TestArgs @('xess','logs/continuation-repair-20260910/xess')
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root .
+```
+
+每次记录提交/工作树状态、EXE和worker哈希、GPU/驱动、runtime身份、输入hash、完整applied配置、命令、退出码、耗时、日志和失败。联合delivery沿用现有23项合同;增加本次针对性用例,不修改其导出完整性门槛。
+
+最终逐项报告R0/R1/A1/R2/R3/R4状态。只有五项产品需求及所承接修复都有对应证据才可声称本计划完成。硬件未测、源码接入未完、失败候选、仅SDK提交的边界必须明确保留;不使用旧Phase或旧通过日志补位。
+
+## 11. 本轮文档交付记录
+
+本轮只做只读源码/本地SDK文档核对、截图查看和修复方案/交接入口更新。没有修改产品代码,没有重建EXE,没有运行新的Create/Evaluate、AMD网络、FRUC或实卡测试,也没有操作正在运行的软件设置。
+
+此前 `be00e27` 的RTX短测和失败证据仍见 [调度实施记录](SCHEDULER_REPAIR_IMPLEMENTATION_2026-09-10.md)。它们属于历史基线,不能证明本方案新增修复已通过。开始本轮时Git工作树干净;本轮不push、发布或打包运行时。
+
+文档检查:`git diff --check`通过;PowerShell核对7份文档的29个本地链接、代码围栏与新方案行尾空白通过。检查范围包括新方案、README、HANDOFF、WORKLOG、SR/AMD研究、XeSS研究与旧调度方案。没有将检查结果记为产品测试通过。
+
+下一步准备实施R0。方案范围已经确定,不需要重新讨论旧Loop或以五分钟累计额度为理由提前结束。
diff --git a/docs/HANDOFF_2026-09-10.md b/docs/HANDOFF_2026-09-10.md
index 70a84ca9..1dfde8f9 100644
--- a/docs/HANDOFF_2026-09-10.md
+++ b/docs/HANDOFF_2026-09-10.md
@@ -1,4 +1,51 @@
-# 当前交接:处理帧率与采集 60→30
+# 当前交接:后端切换、真实产出与音画同步
+
+用户已开启目标模式,当前仍在修复。当前入口:[继续修复实施记录](CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md) 的2026-09-11部分;任务合同见 [继续修复方案](CONTINUATION_REPAIR_PLAN_2026-09-10.md)。不启用旧Loop,不push/发布。
+
+## 2026-09-11 当前可续接状态
+
+- XeSS选择器重叠、失败事务回滚已修;真实UI后端切换回归通过。主状态区已改为真实GPU-ready产出、呈现提交、阶段均值/P95、总延迟和音频状态;长错误文字按实测宽度换行。
+- 完成观察已从单纯等待呈现时间改为在deadline等待与两批反压期间非阻塞检查,共享FrameOutputs避免重复解析;仍使用现有双线程GPU互斥,不是完整单所有者调度。53项合同、RTX23项30/60+NR/FG回放通过。
+- 文件PCM时间戳、首缓冲、重采样尾样本、暂停seek和GPU过载时的音频时钟保持已修;采集音频改受控PCM/WASAPI,有自动/手动/关闭与错误降级、断流恢复。合成PTS+真实WASAPI通过,不是实体采集验收,微量漂移和平滑仍待完善。
+- FRUC已切换为CUDA arrays与D3D11自有纹理桥,整批map/unmap后信号交给D3D12;保留有界资源、无正常像素回读。常规reset用bSkipWarp重新种入历史,停止重启worker和CPU排空。2X/3X/4X重置后像素/前后跳PTS通过;真实controller已知平移回放19项通过。CUDA SDK互操作仍可能阻塞,不能标完全异步。
+- FRUC正确性改善不等于高倍率性能修好:1080p4X候选FG区间约26ms;初版原生4K4X约70.6ms。未完成精确旧worker同源A/B,不声称性能倍数提升。其它素材若SDK报告重复就仍显示无有效补帧。
+- 最新联合交付检查:`logs/delivery/ad0a4e4680d748d0b97de6fe0e665c53/result.json`,23项PASS,42.35秒;EXE SHA `24216560E25D6C84D0BF3656E3AC70BFCD8917F2BED52AE82AB9B4BF2B168778`。实际RTX NR/NVOF、原生4K正确性、播放器、图像、NVENC H264/HEVC音轨和取消通过。不是整体目标/实体采集/AMD通过。
+- AMD NR仍未接入。固定上游MIT核心取得,但缺权重/目标RDNA4。官方Agility1.721.3-preview已取得并校验Microsoft签名,仅在ignored探针目录使用;设备创建返回`D3D12_ERROR_INVALID_REDIST (0x887E0003)`,未进入SM6.10/linalg能力查询。未改Windows开发者模式、未给主程序替换Agility。上游`RecordUnsubmitted`明确整网络单列表曾挂GPU,后续必须分段提交,不能直接嵌入单pass。
+
+下一任务:完成单GPU所有者/设置合并与生成帧时间线计量,同时解决AMD预览运行时、完整网络依赖及provider。UI完整DPI、实卡与长期体验仍需覆盖。具体命令、候选失败及数据边界都在实施记录,单次测试<300秒。
+
+## 以下为2026-09-10开工前快照
+
+下方“未实施”、旧EXE哈希与下一任务仅代表当时记录,当前状态以上述2026-09-11条目为准。
+
+## 当前基线
+
+- 本地代码提交 `be00e27`,进入本轮时工作树干净。当前 EXE 路径 `out/build/x64-release/veyra.exe`;上一交付记录 SHA256 为 `429C5600E2A4ABF8D72B83B0F658B3190FE5397FE9A11256946B924CABA560F4`,本轮未重新构建或测定其身份。
+- 已实现 SR 2K/4K/8K 目标、XeSS 预览2X与 AMD FidelityFX 光流;并非下方历史段落所说的全部停留在研究。AMD NR 本体仍未实现,不能将光流测试当NR支持。
+- 上一轮已完成 DLSS 采集 FG admission、session/revision/epoch 帧流账本、异步取消与部分生命周期修复;完整 S3/S4、FRUC reset像素和实卡未完成。
+- 上轮最终 delivery 23项通过,42.78秒,`logs/delivery/ac24ad4a2e1e4169a171fda66e4b7e84/result.json`。这是历史基线,不是新方案通过证据。
+- 旧 Loop、控制哈希、STOP 和 Phase 排队已退出当前流程。直接按新方案构建和针对性回归,单次测试最多300秒。运行时身份、源码/二进制隔离、真实验证和发布规则继续生效。
+
+## 本轮核实与待实施
+
+| 项目 | 真实状态与下一步 |
+| --- | --- |
+| XeSS入口 | 选择器ID208已有三种FG后端,但y=8与标题1103的y=12重叠;先修布局并验证实际点选/applied切换 |
+| AMD / NVIDIA NR | 新增独立NR provider设置与真实AMD网络接入,不能仅用光流或不可用按钮完成交付;目标AMD硬件仍需实测 |
+| 实时FPS | 当前 `s.fps` 是完成处理的真实源帧速率;新增有效补帧产出与呈现提交主指标,XeSS SDK提交明确单列 |
+| 实时处理状态 | 用紧凑指标区替换大NR圆环,集中总延迟、分阶段耗时、输入/处理/生成/呈现速率和音频状态 |
+| 音画同步 | 采集音频目前DirectShow renderer直通;接受控PCM/WASAPI、共同PTS与有界补偿,文件保留音频主时钟 |
+| FRUC / 调度 | 重置错图证据指向旧输出;诊断CPU全同步通过,生产可用GPU同步方案未通过。继续像素/资源交接定位及S3状态机 |
+
+实施顺序与依赖:R0选项/事务 -> R1指标/状态区 -> A1 AMD NR -> R2 FRUC/调度 -> R3音画同步 -> R4集成回归。AMD的实际硬件阻塞不阻止其它模块修复,但也不能在最终报告中抹去。详见新方案的任务表与验收条件。
+
+下一条唯一任务:复现ID208与1103的重叠,修补帧页布局,并验证XeSS实际可选择且applied后端正确。当前尚未执行此修复,不把方案完成称为软件完成。详细历史实现、命令和失败见 [调度实施记录](SCHEDULER_REPAIR_IMPLEMENTATION_2026-09-10.md) 与 [WORKLOG](WORKLOG.md)。
+
+## 以下为早期同日交接,仅供历史追溯
+
+下方“最新”“下一步”、Phase标签、EXE哈希及未实施描述均属于当时记录;当前状态以本页上半部分和新方案为准。它们不再作为执行队列、门禁或当前通过证明。
+
+### 早期主题:处理帧率与采集 60→30
最新补充:[2K / 8K 超分与 AMD NR 接入方案](SR_TARGETS_AMD_NR_PLAN_2026-09-10.md)。沿用先写方案范围,尚未改产品:SR目标明确QHD2K/4K/8K;AMD确有HIP/ZLUDA/D3D12网络移植,推荐MIT D3D12核心为RDNA4实验候选,不能把AMD光流当AMD NR。当前强制NVIDIA设备、统一NGX初始化、NVIDIA专属SR/FG/编码依赖均须拆开;8K资源及大图/导出分支须真实验证。下一实施项改为S0统一SR目标规划,Phase7与现有EXE不变。
diff --git a/docs/SCHEDULER_REPAIR_PLAN_2026-09-10.md b/docs/SCHEDULER_REPAIR_PLAN_2026-09-10.md
index c7a824f4..f15617b4 100644
--- a/docs/SCHEDULER_REPAIR_PLAN_2026-09-10.md
+++ b/docs/SCHEDULER_REPAIR_PLAN_2026-09-10.md
@@ -1,5 +1,7 @@
# 实时调度与无效 GPU 工作修复计划
+> 当前任务已续接至 [后端切换、真实帧率、链路延迟与音画同步方案](CONTINUATION_REPAIR_PLAN_2026-09-10.md)。本文未完成的S1计时、FRUC恢复及S3/S4仍在新方案范围内;最新第一步先修XeSS控件可见性,不能再将下方历史“下一项”作为唯一任务队列。
+
日期:2026-09-10。状态:S1 核心账本与 S2 的 DLSS 路径已实现并短测;完整 S3/S4 尚未完成。范围:采集卡实时预览和播放器实时呈现;不改变导出完整性检查,不接入 Depth Anything,也不调整 SR -> NR -> FG 的算法顺序。
## 2026-09-10 实施决定
diff --git a/docs/SR_TARGETS_AMD_NR_PLAN_2026-09-10.md b/docs/SR_TARGETS_AMD_NR_PLAN_2026-09-10.md
index b8ce0bd0..cdd08115 100644
--- a/docs/SR_TARGETS_AMD_NR_PLAN_2026-09-10.md
+++ b/docs/SR_TARGETS_AMD_NR_PLAN_2026-09-10.md
@@ -1,5 +1,7 @@
# 2K / 8K 超分与 AMD NR 接入方案
+> 当前续接:[后端切换、真实帧率与音画同步修复方案](CONTINUATION_REPAIR_PLAN_2026-09-10.md)。同日后续已实现SR目标、XeSS预览与AMD光流,AMD NR本体仍未接入。下方研究阶段的“尚未实施”、S0下一步及Phase标签属于历史状态,不再作为当前执行顺序;固定来源和技术约束继续作为研究依据。
+
日期:2026-09-10。状态:方案与来源核查完成,产品尚未实施。Phase 7 仍为 `in_progress`。
本文件补充 [XeSS 补帧与 AMD 光流方案](XESS_AMD_OPTICAL_FLOW_PLAN_2026-09-10.md)。用户继续要求增加 2K / 8K 超分选项,并寻找让 AMD 显卡运行 DLSS5 的方法;本轮沿用上一请求的“先找方法、写方案”范围,没有把研究结果写成应用已支持。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 28c27b9d..30faa3c9 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,3 +1,31 @@
+# 2026-09-11 继续修复目标模式执行中
+
+最新状态以 [实施记录的2026-09-11部分](CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md) 为准。已推进非阻塞完成观察(deadline/反压期间计数)、53项统计合同、真实RTX23项回放,以及文件过载/暂停seek和受控采集音频恢复。采集音频首版欠载重置过于激进的失败已保留,改为持续断流后重锚;11.05秒恢复测试通过,非实卡验收。
+
+FRUC取得新实证:应用自有CUDA arrays+D3D11纹理桥接、graphics map/unmap、同CUDAcontext/批量互操作,替代旧FRUC内部DX11同步路径。六次重置/向后PTS/颜色反转的2X3X4X像素GT通过;reset现在只重种首帧,不常规重启worker或CPU排空队列。最新批量版本4X正确性通过,2X3X/集成复测待做。未加入cuCtxSynchronize或产品像素回读。原生4K4X吞吐测试仍慢(初版FG区间70.58ms),1080p批量版本约26.05ms,不能声称整体性能已经解决;SDK map/unmap自身可能阻塞。
+
+实际命令均为 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root <root> -Preset x64-release` 和 `scripts/acceptance/scheduler-short-test.ps1 -Name <unique> -Exe <test> -TestArgs <args>`;完整名称、SHA、失败/通过与路径见实施记录,单次<300秒。AMD NR缺依赖/目标硬件且provider仍未接入,整体目标active。未commit/push/发布;下面2026-09-10内容为前序进度,不覆盖本条。
+
+## 2026-09-10 前序进度
+
+续接已修文件PCM时间戳/首缓冲/seek/解码尾包,并通过真实WASAPI与44.1/48k样本数回归;新增采集受控PCM/WASAPI与自动/手动/关闭同步设置,合成80ms视频延迟回归通过(平均软件偏差12.8ms、0溢出/欠载),实体采集未测试。帧率窗口不再因Drop连续清空,51项合同通过。FRUC双向D3D11桥接候选失败已撤回;AMD固定源码取得,但网络权重/preview工具链及目标硬件未就绪,provider未完成。详情及失败日志见实施记录。文件过载共同缓冲刚写待测,目标仍执行中;未commit/push/发布。
+
+用户明确开启目标模式,已建立目标并开始改代码。当前证据和未完成列表见 [继续修复实施记录](CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md)。R0补帧选择器布局及XeSS失败回滚已通过真实GUI正常/故障注入测试;R1统计与状态区首版已构建,49项合同与23项采集回放回归通过。AMD NR、完整FRUC/调度、音画同步仍待实施,未宣称全目标完成。单次测试<300秒,未测试实体采集卡,未发布。
+
+# 2026-09-10 后端切换、真实产出与音画同步继续修复方案
+
+用户要求先写新方案、汇报准备修复。本轮交付 [CONTINUATION_REPAIR_PLAN_2026-09-10.md](CONTINUATION_REPAIR_PLAN_2026-09-10.md),包含XeSS可见切换、独立AMD/NVIDIA NR、真实处理产出FPS、集中链路/总延迟、采集和文件音画同步,以及上轮未完成的FRUC reset与S3/S4。没有修改产品代码或把方案当已实现。
+
+本地基线 `be00e27`,进入本轮时Git干净。源码确认:SettingsWindow后端选择器208的y=8与标题1103的y=12重叠,尚未进行本轮UI复现;AMD当前只有光流、没有NR provider;`s.fps`统计GPU完成的真实源帧而非直接输入FPS,但不含有效生成;状态区只展示NR圆环和源帧速率。采集音频通过DirectShow自动renderer直通,未与GPU视频对齐;文件已有WASAPI音频主时钟,需保留并修复必要边界。
+
+核对本地Intel XeSS3.0.2官方header:`framesPresented`是上次调用送往呈现的帧数,不是逐帧GPU完成或屏幕扫描计数。新方案要求明确标为SDK提交;主处理产出与呈现提交分开,不能乘倍率或用旧计数伪造高FPS。延迟按同帧首尾时间直接测量,各阶段不能重复相加;音频采用共同PTS和有界补偿,不承诺消除计算延迟。
+
+同步HANDOFF与README当前入口,给既有研究/调度计划加入续接链接。旧Loop与Phase规则继续归档。只执行Git状态/日志、rg/Get-Content源码和文档读取、本地SDK接口核对、用户截图查看与文档编辑;本轮未构建、未执行新Create/Evaluate、AMD网络、FRUC测试或实卡,也未操作用户当前应用。未push、发布或打包运行时。
+
+文档验证:`git diff --check` exit0;PowerShell链接/围栏/空白检查通过,覆盖7份文档、29个本地链接,新方案也检查了未跟踪文件的行尾空白。Git仅提示既有CRLF自动转换设置。一次多文件patch因旧标题不匹配整体拒绝,没有写入;读取实际标题后重新应用成功。这些结果只证明文档一致性。
+
+下一条任务:R0,修专业页XeSS选择器的布局/命中并验证实际后端切换;完整任务顺序和真实阻塞处理见新方案。上轮的软件通过与FRUC失败证据保留,不冒充本轮新增修复结果。
+
# 2026-09-10 旧 Loop 退役与调度修复
用户明确废弃初期 Loop;AGENTS/README/旧 Playbook/ACTIVE_DELIVERY_PLAN/gates README 已标明旧控制哈希、STOP、Phase 队列不再阻塞当前修复,未改 CONTROL_HASHES 自我放行。delivery 删旧 STOP 依赖并显式加载当前 PowerShell 自带 Utility 模块;导出完整性代码和断言未改。
diff --git a/docs/XESS_AMD_OPTICAL_FLOW_PLAN_2026-09-10.md b/docs/XESS_AMD_OPTICAL_FLOW_PLAN_2026-09-10.md
index dd704716..2305a3f9 100644
--- a/docs/XESS_AMD_OPTICAL_FLOW_PLAN_2026-09-10.md
+++ b/docs/XESS_AMD_OPTICAL_FLOW_PLAN_2026-09-10.md
@@ -1,5 +1,7 @@
# XeSS 补帧与 AMD 光流接入方案
+> 当前续接:[后端切换、真实帧率与音画同步修复方案](CONTINUATION_REPAIR_PLAN_2026-09-10.md)。XeSS预览2X与AMD光流已有代码和RTX5070短测;XeSS实际UI可见性/切换、真实输出口径仍待修复,AMD NR本体未接入。本文早期“仅研究”与Phase顺序只代表当时状态,不代替当前验收。
+
日期:2026-09-10。状态:研究完成;已有窄范围产品接入,仍处于 Phase 7 `in_progress`。本文不改变阶段门槛或默认处理路线。
当前实现包含统一的 2K / 4K / 8K SR 目标、AMD FidelityFX 光流 provider 和 Intel XeSS-FG 代理交换链显示后端。RTX 5070 窄测记录了 AMD OF Create/Dispatch/Destroy 成功(48 次 dispatch),并以非周期纹理验证 canonical `current -> previous` 方向:源图右移 2 像素得到 `(-2, 0)`,左移 2 像素得到 `(2, 0)`;XeSS 初始化、资源标记和 Present 成功(43 次 SDK generated 计数,debugErrors=0);SR 2K/8K 输出非黑。它们只证明该机器上的所测 SDK 调用链与 AMD OF 的已知平移方向,**不证明** AMD GPU 兼容性、实际扫描输出帧率、画质、8K 实时性或长时稳定性。
diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.h
index d3e79587..bcede16d 100644
--- a/include/veyra/diagnostics/FrameMetrics.h
+++ b/include/veyra/diagnostics/FrameMetrics.h
@@ -6,6 +6,8 @@
namespace veyra::diagnostics {
enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, FgBatch, Blit, Count };
enum class SampleState { NotExecuted, Pending, Measured, Unavailable };
+enum class CpuStage { Decode, Submit, SlotWait, ReadyWait, DeadlineWait, Present, Count };
+struct TimingAggregate {std::optional<double> mean,p95;uint64_t samples=0;};
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
@@ -22,7 +24,7 @@ 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 xessSdkGenerated=0,xessSdkPresented=0,realReady=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;
@@ -32,7 +34,13 @@ struct FrameFlowMetrics {
FrameFlowCounters counters;
std::optional<double> slotReuseWaitMs,captureArrivalToPresentReturnMs,gpuReadyWaitMs,deadlineWaitMs;
uint64_t slotReuseWaitCount=0;
- double validGeneratedFps=0,presentSubmitFps=0;
+ double validGeneratedFps=0,presentSubmitFps=0,sourceCompletedFps=0,outputCompletedFps=0,xessSdkSubmitFps=0;
+ bool rateWindowReady=false;
+ std::optional<double> softwareLatencyMs,softwareLatencyP95Ms,slotWaitPerFrameMs;
+ uint64_t latencySamples=0;
+ std::array<TimingAggregate,size_t(GpuStage::Count)> gpuTiming;
+ std::array<TimingAggregate,size_t(CpuStage::Count)> cpuTiming;
+ uint64_t timingOverflow=0;
};
struct FrameMetrics {
pipeline::FrameIdentity identity;
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index 78ce8c6d..58dcdab3 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -9,7 +9,7 @@
#include "veyra/engine/EnhancementSettings.h"
#include "veyra/diagnostics/FrameMetrics.h"
#include "veyra/engine/PreviewView.h"
-#include "veyra/engine/FrameRateWindow.h"
+#include "veyra/sink/CaptureAudioSession.h"
namespace veyra::sink { struct RgbaImage; }
namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }
namespace veyra::engine {
@@ -26,6 +26,10 @@ struct PlayerSnapshot {
uint64_t sessionId=0,rejectedRevision=0;float volume=1;bool muted=false,audioAvailable=false;
std::wstring status=L"请打开视频或图片";
EnhancementSettings desired,applied;bool applying=false;
+ bool nrActive=false,srActive=false,fgActive=false;
+ std::wstring backendWarning;
+ sink::CaptureAudioState captureAudio;
+ bool audioRebuffering=false;
double position=0,duration=0,fps=0,lateMs=0,lateP95Ms=0;
diagnostics::FrameMetrics metrics;
std::optional<double> submissionFps;
@@ -64,7 +68,6 @@ private:
mutable std::mutex mutex_;
PlayerSnapshot snapshot_;
std::shared_ptr<FrameFlowWindow> activeFlow_;
- FrameRateWindow processingRate_;
PreviewView previewView_;
std::wstring savePath_;
std::thread worker_;
diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.h
index 3ea7292e..456208eb 100644
--- a/include/veyra/engine/EnhancementSettings.h
+++ b/include/veyra/engine/EnhancementSettings.h
@@ -10,6 +10,7 @@ enum class FrameGenerationBackend { Dlss, Fruc, XeSS };
enum class FlowQuality { Performance, Balanced, Quality };
enum class OpticalFlowBackend { Nvidia, AmdFidelityFx };
enum class ContentRate { Transport, Auto, Fps30, Fps50, Fps60, Capture60To30 };
+enum class AudioSyncMode { Automatic, Manual, Off };
constexpr std::string_view frameGenerationBackendName(FrameGenerationBackend backend) {
switch(backend) {
case FrameGenerationBackend::Dlss: return "DLSS";
@@ -66,11 +67,14 @@ struct EnhancementSettings {
OpticalFlowBackend opticalFlowBackend=OpticalFlowBackend::Nvidia;
bool amdFlowHalfResolution=false;
ContentRate content=ContentRate::Transport;
+ AudioSyncMode audioSync=AudioSyncMode::Automatic;
+ int32_t audioOffsetMs=0;
bool operator==(const EnhancementSettings&) const = default;
std::string validate() const {
auto range=[](float v,float hi){return std::isfinite(v)&&v>=0&&v<=hi;};
if(auto error=protection.validate();!error.empty())return error;
if(!revision)return "settingsRevision must be nonzero";
+ if(audioSync<AudioSyncMode::Automatic||audioSync>AudioSyncMode::Off||audioOffsetMs<-250||audioOffsetMs>250)return "invalid audio sync setting";
if(!range(model.intensity,1)||!range(model.tone,1)||!range(model.structure,1))return "model parameter out of range";
if(model.skin!=-1&&!range(model.skin,2))return "skin parameter out of range";
if(model.style<0||model.style>2||model.autoMask<0||model.autoMask>1||model.uiCorrection<0||model.uiCorrection>1)return "invalid experimental parameter";
diff --git a/include/veyra/engine/FrameFlowWindow.h b/include/veyra/engine/FrameFlowWindow.h
index bee19ef1..205a63a0 100644
--- a/include/veyra/engine/FrameFlowWindow.h
+++ b/include/veyra/engine/FrameFlowWindow.h
@@ -2,31 +2,107 @@
#include "veyra/diagnostics/FrameMetrics.h"
#include "veyra/engine/FrameRateWindow.h"
#include <mutex>
+#include <memory>
+#include <cmath>
+#include <vector>
namespace veyra::engine {
+// Completion rates belong to a settings revision, not a temporal history.
+// A capture drop resets motion history but must not erase measured throughput.
+class FrameCompletionRates {
+ mutable std::mutex mutex_;
+ FrameRateWindow generated_,presented_,source_,output_,xess_;
+ int64_t start_;
+public:
+ explicit FrameCompletionRates(int64_t now):start_(now){
+ generated_.reset(now);presented_.reset(now);source_.reset(now);output_.reset(now);xess_.reset(now);
+ }
+ void ready(bool real,unsigned valid,int64_t now){
+ std::lock_guard lock(mutex_);
+ if(real){source_.complete(now);output_.complete(now);}
+ for(unsigned i=0;i<valid;++i){generated_.complete(now);output_.complete(now);}
+ }
+ void presented(int64_t now){std::lock_guard lock(mutex_);presented_.complete(now);}
+ void xess(uint64_t count,int64_t now){std::lock_guard lock(mutex_);for(uint64_t i=0;i<count;++i)xess_.complete(now);}
+ void snapshot(diagnostics::FrameFlowMetrics& m,int64_t now)const{
+ std::lock_guard lock(mutex_);m.validGeneratedFps=generated_.rate(now);m.presentSubmitFps=presented_.rate(now);
+ m.sourceCompletedFps=source_.rate(now);m.outputCompletedFps=output_.rate(now);m.xessSdkSubmitFps=xess_.rate(now);m.rateWindowReady=now-start_>=10000000;
+ }
+};
// 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_;
+ std::shared_ptr<FrameCompletionRates> rates_;
+ std::array<uint64_t,8192> readyBatches_{};
+ struct Latency {int64_t time;double ms;};
+ std::deque<Latency> latency_;
+ mutable int64_t latencyRefresh_=0;
+ mutable std::optional<double> latencyMean_,latencyP95_;
+ mutable uint64_t latencyCount_=0;
+ struct StageTiming {int64_t time;double ms;unsigned stage;};
+ static constexpr unsigned gpuCount=unsigned(diagnostics::GpuStage::Count),stageCount=gpuCount+unsigned(diagnostics::CpuStage::Count);
+ std::vector<StageTiming> timing_=std::vector<StageTiming>(8192);size_t timingHead_=0,timingSize_=0;
+ std::array<uint64_t,gpuCount> lastGpuEnd_{};
+ mutable int64_t timingRefresh_=0;
+ mutable std::array<diagnostics::TimingAggregate,stageCount> aggregates_{};
+ void stage(unsigned stage,double ms,int64_t now){
+ if(stage>=stageCount||!std::isfinite(ms)||ms<0)return;
+ while(timingSize_&&timing_[timingHead_].time<=now-10000000){timingHead_=(timingHead_+1)%timing_.size();--timingSize_;}
+ if(timingSize_==timing_.size()){timingHead_=(timingHead_+1)%timing_.size();--timingSize_;++metrics_.timingOverflow;}
+ timing_[(timingHead_+timingSize_++)%timing_.size()]={now,ms,stage};
+ }
public:
- FrameFlowWindow(uint64_t session,pipeline::FrameIdentity id,int64_t now){
+ FrameFlowWindow(uint64_t session,pipeline::FrameIdentity id,int64_t now,std::shared_ptr<FrameCompletionRates> rates={}):rates_(rates?std::move(rates):std::make_shared<FrameCompletionRates>(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 cpu(diagnostics::CpuStage index,double ms,int64_t now){std::lock_guard lock(mutex_);stage(gpuCount+unsigned(index),ms,now);}
+ void gpu(const std::array<diagnostics::GpuSample,gpuCount>& samples,int64_t now){
+ std::lock_guard lock(mutex_);
+ for(unsigned i=0;i<gpuCount;++i){const auto& s=samples[i];if(s.state==diagnostics::SampleState::Measured&&s.milliseconds&&s.end&&s.end!=lastGpuEnd_[i]){lastGpuEnd_[i]=s.end;stage(i,*s.milliseconds,now);}}
+ }
+ void ready(uint64_t batch,bool real,unsigned valid,unsigned invalid,int64_t now){
+ std::lock_guard lock(mutex_);
+ if(!batch||readyBatches_[batch%readyBatches_.size()]==batch)return;
+ readyBatches_[batch%readyBatches_.size()]=batch;
+ metrics_.counters.fgReadyValid+=valid;metrics_.counters.fgInvalid+=invalid;
+ if(real)++metrics_.counters.realReady;
+ rates_->ready(real,valid,now);
+ }
+ void xessSubmitted(uint64_t count,uint64_t generated,int64_t now){
+ std::lock_guard lock(mutex_);metrics_.counters.xessSdkPresented+=count;metrics_.counters.xessSdkGenerated+=generated;
+ rates_->xess(count,now);
+ }
+ void latency(int64_t begin,int64_t end){
+ if(begin<=0||end<begin)return;
+ std::lock_guard lock(mutex_);latency_.push_back({end,double(end-begin)/10000});
+ while(latency_.size()>8192||(!latency_.empty()&&latency_.front().time<=end-10000000))latency_.pop_front();
}
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);
+ metrics_.latest.consumerFence=fence;rates_->presented(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;
+ std::lock_guard lock(mutex_);auto m=metrics_;rates_->snapshot(m,now);
+ if(now>=latencyRefresh_){
+ std::vector<double> values;double sum=0;
+ for(const auto& sample:latency_)if(sample.time>now-10000000){values.push_back(sample.ms);sum+=sample.ms;}
+ latencyCount_=values.size();latencyMean_.reset();latencyP95_.reset();
+ if(!values.empty()){latencyMean_=sum/values.size();const size_t p=(values.size()*95+99)/100-1;std::nth_element(values.begin(),values.begin()+p,values.end());latencyP95_=values[p];}
+ latencyRefresh_=now+2500000;
+ }
+ if(now>=timingRefresh_){
+ std::array<std::vector<double>,stageCount> values;
+ for(size_t i=0;i<timingSize_;++i){const auto& s=timing_[(timingHead_+i)%timing_.size()];if(s.time>now-10000000)values[s.stage].push_back(s.ms);}
+ for(unsigned i=0;i<stageCount;++i){auto& a=aggregates_[i];auto& v=values[i];a={};a.samples=v.size();if(v.empty())continue;double sum=0;for(auto ms:v)sum+=ms;a.mean=sum/v.size();const auto p=(v.size()*95+99)/100-1;std::nth_element(v.begin(),v.begin()+p,v.end());a.p95=v[p];}
+ timingRefresh_=now+2500000;
+ }
+ for(unsigned i=0;i<gpuCount;++i)m.gpuTiming[i]=aggregates_[i];
+ for(unsigned i=0;i<unsigned(diagnostics::CpuStage::Count);++i)m.cpuTiming[i]=aggregates_[gpuCount+i];
+ m.softwareLatencyMs=latencyMean_;m.softwareLatencyP95Ms=latencyP95_;m.latencySamples=latencyCount_;return m;
}
};
}
diff --git a/include/veyra/engine/PresentationWorker.h b/include/veyra/engine/PresentationWorker.h
index 8755a258..1fa7d69f 100644
--- a/include/veyra/engine/PresentationWorker.h
+++ b/include/veyra/engine/PresentationWorker.h
@@ -17,9 +17,12 @@ public:
explicit PresentationWorker(Cancelled interrupt):interrupt_(std::move(interrupt)),thread_([this]{run();}){}
~PresentationWorker(){stopping_=true;++epoch_;wake_.notify_all();if(thread_.joinable())thread_.join();}
PresentationWorker(const PresentationWorker&)=delete;
- bool waitForSlot(){
+ bool waitForSlot(const std::function<void()>& progress={}){
std::unique_lock lock(mutex_);
- while(queue_.size()+unsigned(active_)>=2&&!failed_&&!stopping_&&!interrupt_())wake_.wait_for(lock,std::chrono::milliseconds(1));
+ while(queue_.size()+unsigned(active_)>=2&&!failed_&&!stopping_&&!interrupt_()){
+ lock.unlock();if(progress)progress();lock.lock();
+ if(queue_.size()+unsigned(active_)>=2)wake_.wait_for(lock,std::chrono::milliseconds(1));
+ }
return !failed_&&!stopping_&&!interrupt_();
}
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;}
diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.h
index fb898af7..18e3b5ae 100644
--- a/include/veyra/engine/VideoPresenter.h
+++ b/include/veyra/engine/VideoPresenter.h
@@ -17,6 +17,7 @@ public:
bool readPresentedFrameForTest(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,sink::RgbaImage&);
uint64_t submittedCount() const {return sink_.presentCount();}
uint64_t xessGeneratedCount() const {return sink_.xess()?sink_.xess()->generatedCount():0;}
+ uint64_t xessPresentedCount() const {return sink_.xess()?sink_.xess()->presentedCount():0;}
bool xessActive() const {return sink_.xess()!=nullptr;}
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:
diff --git a/include/veyra/gfx/XessPresenter.h b/include/veyra/gfx/XessPresenter.h
index 51d23aaa..f0a871c4 100644
--- a/include/veyra/gfx/XessPresenter.h
+++ b/include/veyra/gfx/XessPresenter.h
@@ -16,6 +16,7 @@ public:
bool beforePresent();
bool afterPresent();
uint64_t generatedCount() const;
+ uint64_t presentedCount() const;
private:
struct Impl;
std::unique_ptr<Impl> p_;
diff --git a/include/veyra/sink/AudioPcmSource.h b/include/veyra/sink/AudioPcmSource.h
new file mode 100644
index 00000000..1fca53cb
--- /dev/null
+++ b/include/veyra/sink/AudioPcmSource.h
@@ -0,0 +1,9 @@
+#pragma once
+#include <cstddef>
+namespace veyra::sink {
+class AudioPcmSource {
+public:
+ virtual ~AudioPcmSource() = default;
+ virtual size_t pull(float* stereo, size_t frames, double* firstPtsMs) = 0;
+};
+}
diff --git a/include/veyra/sink/CaptureAudioSession.h b/include/veyra/sink/CaptureAudioSession.h
new file mode 100644
index 00000000..169061a7
--- /dev/null
+++ b/include/veyra/sink/CaptureAudioSession.h
@@ -0,0 +1,32 @@
+#pragma once
+#include <windows.h>
+#include <mmreg.h>
+#include <cstdint>
+#include <memory>
+#include <optional>
+#include <string>
+namespace veyra::sink {
+struct CaptureAudioState {
+ bool available=false,running=false,clockEstimated=true,limited=false;
+ double compensationMs=0,bufferedMs=0;
+ std::optional<double> skewMs;
+ uint64_t resets=0,overflows=0,underruns=0;
+ std::wstring error;
+};
+class CaptureAudioSession {
+public:
+ CaptureAudioSession();
+ ~CaptureAudioSession();
+ bool configure(const WAVEFORMATEX&);
+ bool start();
+ void stop();
+ bool push(const void* data,size_t bytes,double ptsMs,bool discontinuity);
+ void videoPresented(double ptsMs,int64_t host100ns);
+ void setGain(float);
+ // 0 automatic, 1 manual, 2 off. Positive offset delays sound.
+ void setSync(unsigned mode,int offsetMs);
+ CaptureAudioState snapshot()const;
+private:
+ struct Impl;std::unique_ptr<Impl> p_;
+};
+}
diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.h
index 84ec01ba..a3e72b94 100644
--- a/include/veyra/sink/WasapiAudioSink.h
+++ b/include/veyra/sink/WasapiAudioSink.h
@@ -1,10 +1,5 @@
#pragma once
-// WasapiAudioSink - product audio playback extracted verbatim from the
-// verified player_probe implementation (Phase 6 audio evidence: event-driven
-// shared mode, PTS-anchored master clock, atomic seek, bounded ring, never
-// dropping decoded audio in player mode).
-//
// AudioPipeline: FFmpeg audio demux/decode + watermarked bounded ring
// (low 250ms / prefill 500ms / high 1000ms, 2s hard bound).
// AudioRenderer: event-driven WASAPI shared-mode endpoint whose device clock
@@ -24,6 +19,7 @@
#include <vector>
#include "veyra/Log.h"
+#include "veyra/sink/AudioPcmSource.h"
struct AVFormatContext;
struct AVCodecContext;
@@ -41,7 +37,7 @@ constexpr uint32_t kAudioRate = 48000;
class AudioRenderer; // forward: pipeline thread needs the renderer
-class AudioPipeline {
+class AudioPipeline : public AudioPcmSource {
public:
AudioPipeline();
~AudioPipeline();
@@ -59,11 +55,12 @@ public:
uint64_t seekCount() const;
double lastPrefillMs() const;
double firstPtsAfterLastSeek() const;
+ bool decodingComplete() const { return decodedEof_.load(); }
// Pull up to maxFrames stereo frames; sets the PTS of the first pulled
// frame. Returns frames pulled (0 legal; caller writes silence and it is
// counted as an underrun by the pump only when the endpoint had space).
- size_t pull(float* dst, size_t maxFrames, double* firstPtsMs);
+ size_t pull(float* dst, size_t maxFrames, double* firstPtsMs) override;
void stopThread();
void setPaused(bool value) { paused_.store(value); }
@@ -83,8 +80,8 @@ private:
};
void pushDecoded(const AVFrame* frame);
+ void pushConverted(int frames);
void decodeBlock();
- double bufferedMsLocked() const;
void closeAll();
friend class AudioThread;
@@ -97,6 +94,8 @@ private:
int streamIndex_ = -1;
bool havePacket_ = false;
bool demuxEof_ = false;
+ bool drainSent_ = false;
+ std::atomic<bool> decodedEof_{false};
double nextPtsMs_ = 0.0; // PTS of the NEXT decoded sample
double discardUntilPtsMs_ = -1.0; // seek pruning
static constexpr size_t kMaxRingFrames = kAudioRate * 2; // 2s hard bound
@@ -110,7 +109,7 @@ private:
std::condition_variable seekDoneCv_;
std::atomic<bool> stopFlag_{false};
std::atomic<bool> paused_{false};
- bool seekRequested_ = false;
+ std::atomic<bool> seekRequested_{false};
bool seekDone_ = true;
double seekTargetMs_ = 0.0;
@@ -129,17 +128,16 @@ public:
bool start();
void setGain(float value){gain_.store(value);}
- // Called by the audio thread after prefill: begins playback anchored at
- // the PTS of the sample that will be written first.
- bool startAnchored(double firstBufferPtsMs);
+ // Write actual PCM before starting the endpoint and its media clock.
+ bool startAnchored(AudioPcmSource& pipeline);
void setPaused(bool value);
// Event-driven pump for ONE event cycle. Writes real data when the ring
// has it, silence otherwise (underrun counted). Returns false on hard
// failure.
- bool pumpOnce(AudioPipeline& pipeline, double* firstWrittenPtsMs);
+ bool pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs);
- // Master clock: real media PTS of the sample currently being played.
+ // Master clock, or NaN when unstarted/reset or the device clock failed.
double mediaTimeMs() const;
// Atomic seek support: stop + reset the endpoint; the clock is invalid
@@ -166,10 +164,10 @@ private:
std::atomic<UINT64> anchorPos_{0};
std::atomic<double> anchorPtsMs_{0.0};
std::atomic<bool> started_{false};
- bool running_ = false;
+ std::atomic<bool> running_{false};
bool comInited_ = false;
std::atomic<uint64_t> underruns_{0};
- uint64_t framesWritten_ = 0;
+ std::atomic<uint64_t> framesWritten_{0};
std::vector<float> chunk_{std::vector<float>(8192 * 2)};
};
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index fde896de..b65f4012 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -2,6 +2,7 @@
#include "veyra/source/IFrameSource.h"
#include <memory>
#include <vector>
+#include "veyra/sink/CaptureAudioSession.h"
namespace veyra::source {
struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;};
struct CaptureMetrics {
@@ -20,6 +21,9 @@ public:
bool start();
bool setAudioGain(float); // call on the graph owner thread; never system volume
CaptureMetrics metrics()const;
+ void videoPresented(double ptsMs,int64_t host100ns);
+ void setAudioSync(unsigned mode,int offsetMs);
+ sink::CaptureAudioState audioState()const;
const SourceInfo& info()const override;
SourceReadStatus read(pipeline::FramePacket&,const AVFrame**)override;
bool seek(const pipeline::Rational&)override{return false;}
diff --git a/include/veyra/source/NativeCaptureSink.h b/include/veyra/source/NativeCaptureSink.h
index dde2ff2b..87edf05d 100644
--- a/include/veyra/source/NativeCaptureSink.h
+++ b/include/veyra/source/NativeCaptureSink.h
@@ -7,4 +7,5 @@ namespace veyra::source {
// Native terminal filter: no legacy SampleGrabber orientation/VideoInfo2
// restriction, conversion filter or extra queue. Callback borrows the sample.
HRESULT createNativeCaptureSink(const AM_MEDIA_TYPE&,std::function<HRESULT(IMediaSample*)>,Microsoft::WRL::ComPtr<IBaseFilter>&,Microsoft::WRL::ComPtr<IPin>&);
+HRESULT createNativeAudioSink(const AM_MEDIA_TYPE&,std::function<HRESULT(IMediaSample*)>,Microsoft::WRL::ComPtr<IBaseFilter>&,Microsoft::WRL::ComPtr<IPin>&);
}
diff --git a/scripts/acceptance/ui-fg-backends.py b/scripts/acceptance/ui-fg-backends.py
new file mode 100644
index 00000000..fc2941f3
--- /dev/null
+++ b/scripts/acceptance/ui-fg-backends.py
@@ -0,0 +1,212 @@
+"""Exercise the actual professional FG selector and applied engine transactions."""
+import ctypes as c
+import ctypes.wintypes as w
+import hashlib
+import json
+import os
+import pathlib
+import re
+import subprocess
+import sys
+import time
+
+if '--worker' not in sys.argv:
+ child = subprocess.Popen([sys.executable, __file__, '--worker', *sys.argv[1:]])
+ try:
+ sys.exit(child.wait(timeout=90))
+ except subprocess.TimeoutExpired:
+ subprocess.run(['taskkill.exe', '/PID', str(child.pid), '/T', '/F'], capture_output=True, timeout=5)
+ sys.exit('FAIL: FG selector test exceeded 90 seconds')
+sys.argv.remove('--worker')
+reject_xess = '--reject-xess' in sys.argv
+if reject_xess:
+ sys.argv.remove('--reject-xess')
+u = c.WinDLL('user32', use_last_error=True)
+u.SetProcessDpiAwarenessContext.argtypes = [w.HANDLE]
+u.SetProcessDpiAwarenessContext(c.c_void_p(-4))
+u.GetDlgItem.argtypes = [w.HWND, c.c_int]
+u.GetDlgItem.restype = w.HWND
+u.GetParent.argtypes = [w.HWND]
+u.GetParent.restype = w.HWND
+u.GetWindowTextW.argtypes = [w.HWND, w.LPWSTR, c.c_int]
+u.GetWindowRect.argtypes = [w.HWND, c.POINTER(w.RECT)]
+u.IsWindowVisible.argtypes = [w.HWND]
+u.SetWindowPos.argtypes = [w.HWND, w.HWND, c.c_int, c.c_int, c.c_int, c.c_int, w.UINT]
+u.PostMessageW.argtypes = [w.HWND, w.UINT, w.WPARAM, w.LPARAM]
+u.SendMessageTimeoutW.argtypes = [w.HWND, w.UINT, w.WPARAM, w.LPARAM, w.UINT, w.UINT, c.POINTER(c.c_size_t)]
+visit_type = c.WINFUNCTYPE(w.BOOL, w.HWND, w.LPARAM)
+
+
+def send(hwnd, message, first=0, second=0):
+ result = c.c_size_t()
+ if not u.SendMessageTimeoutW(hwnd, message, first, second, 2, 1500, c.byref(result)):
+ raise RuntimeError('window message timed out')
+ return result.value
+
+
+def windows(pid, class_name, parent=None):
+ found = []
+
+ @visit_type
+ def visit(hwnd, unused):
+ owner = w.DWORD()
+ u.GetWindowThreadProcessId(hwnd, c.byref(owner))
+ name = c.create_unicode_buffer(128)
+ u.GetClassNameW(hwnd, name, 128)
+ if owner.value == pid and name.value == class_name:
+ found.append(hwnd)
+ return True
+
+ if parent:
+ u.EnumChildWindows(parent, visit, 0)
+ else:
+ u.EnumWindows(visit, 0)
+ return found
+
+
+def wait_for(action, seconds=8):
+ end = time.monotonic() + seconds
+ while time.monotonic() < end:
+ value = action()
+ if value:
+ return value
+ if process.poll() is not None:
+ raise RuntimeError('application exited before test completed')
+ time.sleep(.05)
+ raise RuntimeError('condition timed out')
+
+
+def rect(hwnd):
+ value = w.RECT()
+ if not u.GetWindowRect(hwnd, c.byref(value)):
+ raise RuntimeError('missing control rectangle')
+ return [value.left, value.top, value.right, value.bottom]
+
+
+def intersects(a, b):
+ return max(a[0], b[0]) < min(a[2], b[2]) and max(a[1], b[1]) < min(a[3], b[3])
+
+
+def text(hwnd):
+ value = c.create_unicode_buffer(1024)
+ u.GetWindowTextW(hwnd, value, len(value))
+ return value.value
+
+
+exe = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else 'out/build/x64-release/veyra.exe').resolve()
+media = pathlib.Path('logs/video-sdk-trial-20260909/known-pan15.mp4').resolve()
+out = pathlib.Path('logs/continuation-repair-20260910') / ('ui-fg-' + str(time.time_ns()))
+out.mkdir(parents=True)
+env = os.environ.copy()
+env['PATH'] = r'C:\veyra-deps\installed\x64-windows\bin;' + env['PATH']
+env['VEYRA_LOG_FILE'] = str((out / 'app.log').resolve())
+if reject_xess:
+ env['VEYRA_TEST_XESS_INIT_FAILURE'] = '1'
+result = {'exeHash': hashlib.sha256(exe.read_bytes()).hexdigest(), 'layouts': [], 'switches': [], 'error': ''}
+startup = subprocess.STARTUPINFO()
+startup.dwFlags = subprocess.STARTF_USESHOWWINDOW
+startup.wShowWindow = 0
+
+
+def log():
+ return (out / 'app.log').read_text(encoding='utf-8', errors='replace') if (out / 'app.log').exists() else ''
+
+
+with (out / 'stdout.log').open('w') as stdout, (out / 'stderr.log').open('w') as stderr:
+ process = subprocess.Popen([str(exe), '--smoke-view', 'professional', '--smoke-seconds', '80',
+ str(media), '--no-nr', '--no-sr', '--fg'],
+ stdout=stdout, stderr=stderr, env=env, startupinfo=startup)
+ try:
+ main = wait_for(lambda: windows(process.pid, 'VeyraApp'))[0]
+ u.ShowWindow(main, 4)
+ panel = wait_for(lambda: windows(process.pid, 'VeyraInspector', main))[0]
+ body = windows(process.pid, 'VeyraInspectorBody', panel)[0]
+ wait_for(lambda: 'professional=true' in log(), 15)
+ time.sleep(.5)
+ send(main, 0x111, 231) # TabFg
+ time.sleep(.4)
+ backend = u.GetDlgItem(body, 208)
+ title = u.GetDlgItem(body, 1103)
+ multiplier = u.GetDlgItem(body, 202)
+ revision_label = u.GetDlgItem(panel, 400)
+ assert backend and title and multiplier, 'missing FG controls'
+ assert send(backend, 0x146) == 3, 'FG selector must expose all three backends'
+ for width, height in [(1280, 900), (1040, 540), (1040, 800)]:
+ u.SetWindowPos(main, None, 30, 30, width, height, 0x14)
+ time.sleep(.2)
+ rectangles = {'title': rect(title), 'backend': rect(backend), 'multiplier': rect(multiplier)}
+ result['layouts'].append(rectangles)
+ assert u.IsWindowVisible(backend), 'backend selector hidden'
+ assert not intersects(rectangles['backend'], rectangles['title']), 'backend selector overlaps title'
+ assert not intersects(rectangles['backend'], rectangles['multiplier']), 'backend selector overlaps multiplier'
+ assert rectangles['backend'][1] >= rect(body)[1], 'backend selector clipped above viewport'
+
+ def choose(control, index):
+ for unused in range(10):
+ anchor, viewport = rect(control), rect(body)
+ if anchor[1] >= viewport[1] and anchor[3] <= viewport[3]:
+ break
+ delta = 120 if anchor[1] < viewport[1] else -120
+ send(body, 0x20A, (delta & 0xffff) << 16, 0)
+ assert rect(control)[1] >= rect(body)[1] and rect(control)[3] <= rect(body)[3], 'choice clipped by scroll viewport'
+ # Trigger the real custom popup through the same mouse event as a click.
+ u.PostMessageW(control, 0x201, 1, 12 | (12 << 16))
+ popup = wait_for(lambda: windows(process.pid, 'VeyraGlassSelector'))[0]
+ listing = u.GetDlgItem(popup, 1)
+ assert send(listing, 0x18B) > index, 'choice missing in popup'
+ send(listing, 0x186, index)
+ u.PostMessageW(listing, 0x100, 0x0D, 0)
+ wait_for(lambda: not windows(process.pid, 'VeyraGlassSelector'))
+ assert send(control, 0x147) == index, 'popup did not commit choice'
+
+ for index, name in [(1, 'FRUC'), (2, 'XeSS'), (0, 'DLSS')]:
+ previous = text(revision_label)
+ choose(backend, index)
+ if reject_xess and name == 'XeSS':
+ wait_for(lambda: send(backend, 0x147) == 1 and 'XeSS' in text(u.GetDlgItem(panel, 401)), 18)
+ result['switches'].append('XeSS rejected, FRUC retained')
+ continue
+ def applied():
+ current = text(revision_label)
+ values = re.findall(r'\d+', current.splitlines()[0])
+ return current != previous and len(values) >= 2 and values[0] == values[1]
+ wait_for(applied, 18)
+ result['switches'].append(name)
+ assert send(multiplier, 0x146) == (2 if name == 'XeSS' else 4), 'incorrect multiplier choices'
+ previous = text(revision_label)
+ choose(multiplier, 0)
+ wait_for(applied, 12)
+ result['switches'].append('off')
+ status_panel = windows(process.pid, 'VeyraLiveStatus', main)
+ if status_panel:
+ from PIL import ImageGrab
+ time.sleep(.25)
+ ImageGrab.grab(window=main).save(out / 'status-top.png')
+ send(status_panel[0], 0x20A, ((-120 * 4) & 0xffff) << 16, 0)
+ time.sleep(.25)
+ ImageGrab.grab(window=main).save(out / 'status-details.png')
+ result['passed'] = True
+ except Exception as error:
+ result['error'] = str(error)
+ result['passed'] = False
+ finally:
+ roots = windows(process.pid, 'VeyraApp')
+ if roots:
+ u.PostMessageW(roots[0], 0x10, 0, 0)
+ try:
+ process.wait(timeout=8)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ result['exit'] = process.returncode
+ result['appliedBackends'] = re.findall(r'Applied revision=\d+.*?fgBackend=(\w+)', log())
+ if result.get('passed'):
+ expected = ['FRUC', 'DLSS'] if reject_xess else ['FRUC', 'XeSS', 'DLSS']
+ result['passed'] = all(name in result['appliedBackends'] for name in expected)
+ if reject_xess:
+ result['passed'] = result['passed'] and 'XeSS' not in result['appliedBackends']
+ result['passed'] = result.get('passed', False) and process.returncode == 0
+ (out / 'result.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
+ print(out / 'result.json')
+ print(json.dumps(result))
+sys.exit(0 if result['passed'] else 1)
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 85079492..2c28ce84 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -52,13 +52,13 @@ bool EngineController::idle()const{std::lock_guard lock(mutex_);return !busy_&&!
void EngineController::open(HWND video,const std::wstring& path,PlayerOptions opts){
const bool captureReplay=opts.captureReplayForTest;
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_);}
+ {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();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;}
-void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);processingRate_.reset(monotonic100ns());if(snapshot_.running)snapshot_.transport=p?TransportState::Paused:TransportState::Playing;}
+void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);if(snapshot_.running)snapshot_.transport=p?TransportState::Paused:TransportState::Playing;}
void EngineController::setVolume(float gain,bool mute){if(!std::isfinite(gain))return;volume_=std::clamp(gain,0.0f,1.0f);muted_=mute;}
bool EngineController::requestSettings(EnhancementSettings s){
if(!s.validate().empty()){veyra::log::warn("settings","invalid whole settings transaction rejected");status(L"整套设置无效,未应用任何字段",false);return false;}
@@ -68,7 +68,15 @@ 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_;const bool playing=copy.running&&!copy.image&&copy.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;}
+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&&copy.transport==TransportState::Playing;
+ if(activeFlow_)copy.metrics.flow=activeFlow_->snapshot(monotonic100ns());
+ auto& flow=copy.metrics.flow;
+ if(!playing){flow.sourceCompletedFps=flow.outputCompletedFps=flow.validGeneratedFps=flow.presentSubmitFps=flow.xessSdkSubmitFps=0;}
+ copy.fps=flow.sourceCompletedFps;copy.submissionFps=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);
@@ -123,10 +131,16 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
status(L"当前非 NVIDIA 适配器:NR、NVIDIA 超分与 DLSS/FRUC 已禁用;可使用 XeSS 预览和 AMD 光流",false);
}
if(graph.xessEnabled()&&!presenter.xessActive())status(L"XeSS 未启用:运行时或设备不兼容;当前为普通呈现",false);
+ {
+ std::lock_guard lock(mutex_);
+ if(!nvidiaAdapter&&(options.nr||options.sr||(options.fg&&!xessFg)))snapshot_.backendWarning=L"当前 GPU 不支持所选 NVIDIA 增强";
+ if(graph.xessEnabled()&&!presenter.xessActive())snapshot_.backendWarning=L"XeSS 初始化失败;当前为普通呈现";
+ }
+ captureSource.setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
if(physicalCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}
{std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.running=true;snapshot_.transport=TransportState::Playing;snapshot_.image=isImage;snapshot_.capture=isCapture;snapshot_.applied=options.snapshot();snapshot_.desired=desired_;}
status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isCapture?L"实时采集":L"播放",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(性能成本较高)"));
- pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false;std::deque<double> latenessSamples;
+ pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false,audioRebuffering=false,seekPreviewPending=false;std::deque<double> latenessSamples;
TimingWindow captureAges,scheduleWaits,processTimes,presentTimes,decodeTimes,gpuReadyTimes;
std::array<TimingWindow,size_t(diagnostics::GpuStage::Count)> gpuStageTimes;
std::array<uint64_t,size_t(diagnostics::GpuStage::Count)> lastGpuSampleEnd{};
@@ -135,7 +149,7 @@ 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=[&](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 completedProcessing=[&](pipeline::FrameIdentity id){std::lock_guard lock(mutex_);if(snapshot_.applied.revision==id.settingsRevision)++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.
@@ -147,20 +161,51 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
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;
+ struct CompletionWatch {
+ pipeline::EnhanceGraph::FrameOutputs output;
+ std::shared_ptr<FrameFlowWindow> flow;
+ Clock::time_point processStart;
+ bool real=false;
+ std::atomic<bool> ready=false;
+ };
+ std::vector<std::shared_ptr<CompletionWatch>> pendingCompletions;
+ // Shared with the presenter: resolve each batch on this single
+ // object so SDK status and generated counts are consumed once.
+ auto pollCompletions=[&]{
+ std::unique_lock gpuLock(gpuMutex,std::try_to_lock);
+ if(!gpuLock.owns_lock())return;
+ for(auto it=pendingCompletions.begin();it!=pendingCompletions.end();){
+ auto& watch=**it;auto& batch=watch.output;
+ if(!graph.resolveGeneration(batch)){++it;continue;}
+ 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;
+ }
+ watch.flow->ready(batch.batch.batchId,watch.real,valid,invalid,host100ns());
+ if(watch.real)completedProcessing(batch.batch.identity);
+ {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(watch.processStart));lastFgCompletion=host100ns();}
+ }
+ watch.ready=true;it=pendingCompletions.erase(it);
+ }
+ };
if(isCapture)liveWorker=std::make_unique<PresentationWorker>([&]{return stop_.load()||paused_.load();});
- auto drainLivePresentation=[&]{if(liveWorker){++presentationDrains;liveWorker->cancelAndDrain();}};
+ auto drainLivePresentation=[&]{if(liveWorker){++presentationDrains;liveWorker->cancelAndDrain();pollCompletions();std::lock_guard gpuLock(gpuMutex);pendingCompletions.clear();}};
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;
+ std::shared_ptr<FrameCompletionRates> completionRates;
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)pollCompletions();
if(liveWorker&&liveWorker->failed()){status(L"采集画面呈现失败,请查看诊断",true);break;}
const float gain=muted_?0.0f:volume_.load();audio.setGain(gain);
- if(isCapture){const bool available=captureSource.setAudioGain(gain);std::lock_guard lock(mutex_);snapshot_.audioAvailable=available;}
+ captureSource.setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
+ if(isCapture){const bool available=captureSource.setAudioGain(gain);const auto audioState=captureSource.audioState();std::lock_guard lock(mutex_);snapshot_.audioAvailable=available;snapshot_.captureAudio=audioState;}
// Save the latest processed real frame before a settings transaction
// invalidates it (live rendering can be one batch behind processing).
std::wstring save;EnhancementSettings requested;{std::lock_guard lock(mutex_);requested=desired_;if(hasOutput)save.swap(savePath_);}
@@ -183,30 +228,34 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
const bool rebuild=gd.opticalFlowBackend!=nextDesc.opticalFlowBackend||gd.amdFlowHalfResolution!=nextDesc.amdFlowHalfResolution||gd.enableNr!=nextDesc.enableNr||gd.enableFg!=nextDesc.enableFg||gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||gd.fgMultiplier!=nextDesc.fgMultiplier||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;
bool accepted=ring.drainQueue();out={};hasOutput=false;
if(accepted&&rebuild){presenter.close();graph.shutdown();accepted=graph.initialize(nextDesc)&&presenter.open(ctx,window,graph)&&graph.createViews();
+ if(accepted&&graph.xessEnabled()&&!presenter.xessActive()){
+ veyra::log::warn("settings","requested XeSS presenter unavailable; rejecting transaction and restoring previous backend");
+ accepted=false;
+ }
if(!accepted){presenter.close();graph.shutdown();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"设置失败且旧资源恢复失败,已停止",true);break;}}
}else if(accepted)accepted=graph.applySettings(requested);
if(accepted){
options=next;gd=nextDesc;transaction=true;reset=true;
if(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))veyra::log::warn("capability",std::format("non-NVIDIA adapter disabled requested settings revision={} nr={} sr={} fgBackend={} flowBackend={}",requested.revision,next.nr,next.sr,frameGenerationBackendName(requested.frameGenerationBackend),opticalFlowBackendName(requested.opticalFlowBackend)));
}
- else {std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_.revision!=previous.revision;snapshot_.status=L"设置应用失败,已恢复上一套参数";}
+ else {std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_.revision!=previous.revision;snapshot_.status=L"设置应用失败,已恢复上一套参数";snapshot_.backendWarning=requested.frameGenerationBackend==FrameGenerationBackend::XeSS?L"XeSS 未能启用,已恢复上一套参数":L"后端切换失败,已恢复上一套参数";}
}
const double seek=seekSeconds_.exchange(-1);
if(seek>=0&&!isImage&&!isCapture){
if(!ring.drainQueue()||!activeSource->seek({static_cast<int64_t>(seek*1000000),1000000})){status(L"跳转失败",true);break;}
- discardBefore=seek*1000;reset=true;anchorMs=discardBefore;anchor=Clock::now();if(audioStarted)audioPipe.requestSeek(discardBefore);
+ discardBefore=seek*1000;seekPreviewPending=true;reset=true;anchorMs=discardBefore;anchor=Clock::now();audioRebuffering=false;if(audioStarted){audioPipe.setPaused(paused_);audioPipe.requestSeek(discardBefore);}
}
- if(!transaction&&((paused_&&seek<0)||(isImage&&hasOutput))){
+ if(!transaction&&((paused_&&!seekPreviewPending)||(isImage&&hasOutput))){
drainLivePresentation();
if(audioStarted)audioPipe.setPaused(true);wasPaused=true;
const bool referencesValid=hasOutput&&out.batch.count&&out.batch.frames[out.batch.count-1].lease&&out.batch.frames[out.batch.count-1].lease->referencesValid;
if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView())){status(L"画面呈现失败",true);break;}
std::this_thread::sleep_for(std::chrono::milliseconds(16));continue;
}
- if(wasPaused&&!paused_){if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;wasPaused=false;}
+ if(wasPaused&&!paused_){audioRebuffering=false;if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;wasPaused=false;}
// Backpressure before reading the capacity-one source mailbox:
// when a lease frees we consume the newest available sample.
- if(liveWorker&&!transaction&&!liveWorker->waitForSlot())continue;
+ if(liveWorker&&!transaction&&!liveWorker->waitForSlot(pollCompletions))continue;
const auto decodeStart=Clock::now();
pipeline::FramePacket pkt;const AVFrame* frame=imageFrame;
if(transaction&&cachedFrame&&(!isCapture||paused_)){frame=cachedFrame;pkt=cachedPacket;}
@@ -220,7 +269,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
}
if(stop_)break;
if(rs==source::SourceReadStatus::Waiting)continue;
- if(rs==source::SourceReadStatus::Eos){status(L"视频已播放完毕");paused_=true;{std::lock_guard lock(mutex_);snapshot_.transport=TransportState::Ended;}continue;}
+ if(rs==source::SourceReadStatus::Eos){seekPreviewPending=false;status(L"视频已播放完毕");paused_=true;{std::lock_guard lock(mutex_);snapshot_.transport=TransportState::Ended;}continue;}
if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){status(isCapture?L"采集信号中断,请检查设备连接或格式":L"视频解码或时间戳错误",true);break;}
}
const bool rereadCached=transaction&&frame==cachedFrame;
@@ -266,8 +315,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
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);}
+ uint64_t processWaitBase=0,processSubmitBase=0;double processWaitMsBase=0,processSlotWaitMs=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);processSlotWaitMs=ring.cpuWaitMilliseconds()-processWaitMsBase;}
if(!processed){
if(transaction){
ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);
@@ -287,16 +336,21 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
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;
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;});
+ if(settingsChanged||!completionRates)completionRates=std::make_shared<FrameCompletionRates>(host100ns());
+ frameFlow=std::shared_ptr<FrameFlowWindow>(new FrameFlowWindow(runSessionId,out.batch.identity,host100ns(),completionRates),[](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));
+ const double processMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();
+ processTimes.add(processMs);
+ frameFlow->cpu(diagnostics::CpuStage::Decode,decodeMs,host100ns());
+ frameFlow->cpu(diagnostics::CpuStage::Submit,processMs,host100ns());
+ frameFlow->cpu(diagnostics::CpuStage::SlotWait,processSlotWaitMs,host100ns());
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;
+ std::lock_guard lock(mutex_);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));
}
if(isCapture&&!rereadCached&&!liveTimeline.anchored(out.batch.identity.epoch)){
@@ -311,17 +365,17 @@ 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,flow=frameFlow,processStart](const PresentationWorker::Cancelled& cancelled)mutable{
+ auto watch=std::make_shared<CompletionWatch>();watch->output=out;watch->flow=frameFlow;watch->processStart=processStart;watch->real=!rereadCached;
+ {std::lock_guard gpuLock(gpuMutex);pendingCompletions.push_back(watch);}
+ if(!liveWorker->push([&,watch,timeline,captureArrival,jobGeneration,rereadCached,flow=frameFlow](const PresentationWorker::Cancelled& cancelled){
+ auto& batch=watch->output;
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;
+ for(;;){if(cancelled()){++presentationCancelledJobs;return true;}pollCompletions();if(watch->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);
- 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;
+ flow->cpu(diagnostics::CpuStage::ReadyWait,readyMs,host100ns());
diagnostics::GpuSample blit;
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
@@ -334,16 +388,20 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(generated&&comparisonMode_!=0)continue;
if(generated&&!generatedPresentationCurrent(jobGeneration,presentationGeneration.load())){++presentationSkippedGenerated;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;}
+ const auto waitStart=Clock::now();while(!cancelled()&&host100ns()<timeline.deadline(item.pts100ns)){pollCompletions();wait.slice();}const auto waited=elapsedMs(waitStart);waitMs+=waited;flow->cpu(diagnostics::CpuStage::DeadlineWait,waited,host100ns());if(cancelled()){++presentationCancelledJobs;return true;}
if(generated&&!generatedPresentationCurrent(jobGeneration,presentationGeneration.load())){++presentationSkippedGenerated;continue;}
- const auto begin=Clock::now();bool didPresent=false;uint64_t xessGenerated=0;
+ const auto begin=Clock::now();bool didPresent=false;uint64_t xessGenerated=0,xessPresented=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();
+ const auto beforeXess=presenter.xessGeneratedCount(),beforeXessPresented=presenter.xessPresentedCount();
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;
+ xessPresented=presenter.xessPresentedCount()-beforeXessPresented;
item.lease->consumerFence=ring.lastSignaledValue();didPresent=presenter.submittedCount()>before;blit=presenter.blitTiming(ctx.fence());}
presentMs+=elapsedMs(begin);
- if(xessGenerated)flow->update([&](auto& m){m.counters.xessSdkGenerated+=xessGenerated;});
+ flow->cpu(diagnostics::CpuStage::Present,elapsedMs(begin),host100ns());
+ if(xessPresented)flow->xessSubmitted(xessPresented,xessGenerated,host100ns());
+ if(didPresent&&physicalCapture)captureSource.videoPresented(double(item.pts100ns)/10000,host100ns());
+ if(didPresent&&!generated&&!rereadCached)flow->latency(captureArrival,host100ns());
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;
@@ -355,16 +413,25 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
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)){
+ while(!stop_&&(!paused_||seekPreviewPending)&&seekSeconds_<0&&!graph.resolveGeneration(out)){
if(elapsedMs(readyStart)>2000){status(L"补帧 GPU 就绪超时",true);stop_=true;break;}
deadlineWait.slice(.2);
}
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((paused_&&!seekPreviewPending)||seekSeconds_>=0){reset=true;if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} cancelled before submit (pause/seek)",out.batch.batchId));continue;}
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());
+ frameFlow->ready(out.batch.batchId,!rereadCached&&!isImage,valid,invalid,host100ns());
if(!rereadCached&&!isImage)completedProcessing(out.batch.identity);
gpuWaitMs=elapsedMs(readyStart);gpuReadyTimes.add(gpuWaitMs);
+ frameFlow->cpu(diagnostics::CpuStage::ReadyWait,gpuWaitMs,host100ns());
+ if(audioStarted&&!isCapture&&!paused_){
+ const double media=audio.mediaTimeMs();
+ if(std::isfinite(media)){
+ const double lead=media-pts;
+ if(!audioRebuffering&&lead>80){audioRebuffering=true;audioPipe.setPaused(true);veyra::log::info("audio-sync",std::format("video overload: holding audio clock leadMs={:.2f}",lead));}
+ else if(audioRebuffering&&lead<=20){audioRebuffering=false;audioPipe.setPaused(false);veyra::log::info("audio-sync",std::format("video caught up: resume common timeline leadMs={:.2f}",lead));}
+ }
+ }
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;
@@ -374,17 +441,21 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
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 beforeXess=presenter.xessGeneratedCount();
+ frameFlow->cpu(diagnostics::CpuStage::DeadlineWait,elapsedMs(waitStart),host100ns());
+ if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0){interrupted=true;break;}
+ const auto begin=Clock::now();const auto before=presenter.submittedCount();const auto beforeXess=presenter.xessGeneratedCount(),beforeXessPresented=presenter.xessPresentedCount();
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;});
+ frameFlow->cpu(diagnostics::CpuStage::Present,elapsedMs(begin),host100ns());
+ frameFlow->xessSubmitted(presenter.xessPresentedCount()-beforeXessPresented,presenter.xessGeneratedCount()-beforeXess,host100ns());
item.lease->consumerFence=ring.lastSignaledValue();
if(presenter.submittedCount()>before){++handled;frameFlow->presented(generated,item.lease->consumerFence,host100ns());}
+ if(presenter.submittedCount()>before&&!generated&&!rereadCached)frameFlow->latency(std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100,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;}
if(interrupted){reset=true;continue;}
+ seekPreviewPending=false;
}
if(!liveWorker){scheduleWaits.add(frameWaitMs);presentTimes.add(framePresentMs);}
const double lateness=isCapture?0:nowMs()-pts;
@@ -394,6 +465,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
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;}
+ frameFlow->gpu(measured.gpu,host100ns());
if(graph.xessEnabled()){
std::lock_guard gpuLock(gpuMutex);
graphStats.fgGeneratedFrames=presenter.xessGeneratedCount();
@@ -403,11 +475,17 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
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);});
+ frameFlow->update([&](auto& m){m.slotWaitPerFrameMs=processSlotWaitMs;});
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());
+ ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;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_.nrActive=graph.nrEnabled()&&graphStats.nrEvaluateCount>0;
+ snapshot_.audioRebuffering=audioRebuffering;
+ snapshot_.srActive=gd.enableSr&&graphStats.srEvaluateCount>0;
+ snapshot_.fgActive=options.fg&&(graph.xessEnabled()?presenter.xessActive()&&graphStats.fgGeneratedFrames>0:graph.fgEnabled()&&measured.flow.counters.fgReadyValid>0);
+ if(transaction&&nvidiaAdapter&&(!graph.xessEnabled()||presenter.xessActive()))snapshot_.backendWarning.clear();
snapshot_.flowPerf=graph.actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;
snapshot_.nrEvaluated=graphStats.nrEvaluateCount;snapshot_.nvofExecuted=graphStats.nvofExecuteCount;
snapshot_.captureReceived=captureStats.received;snapshot_.captureDropped=captureStats.dropped;snapshot_.captureFps=captureStats.callbackFps;snapshot_.captureReadAgeMs=captureStats.readAgeMs;snapshot_.captureAgeMs=liveWorker?completed.ageMs:captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=ageP95;
diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cpp
index 5b6fa365..5010661e 100644
--- a/src/engine/PresetStore.cpp
+++ b/src/engine/PresetStore.cpp
@@ -13,12 +13,12 @@ bool nameOk(const std::wstring& s){return !s.empty()&&s.size()<=48&&s.front()!=L
std::wstring trim(std::wstring s){auto a=s.find_first_not_of(L" \t\r\n");if(a==s.npos)return {};auto b=s.find_last_not_of(L" \t\r\n");return s.substr(a,b-a+1);}
}
std::string PresetStore::serialize()const{
- std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 6\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';
- for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<'\n';}return o.str();
+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 7\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';
+ for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<' '<<int(s.audioSync)<<' '<<s.audioOffsetMs<<'\n';}return o.str();
}
bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std::wstring& def){
if(data.size()>65536)return false;std::istringstream in(data);in.imbue(std::locale::classic());std::string magic,d;int version=0;size_t count=0;
- if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>6)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;
+ if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>7)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;
for(size_t i=0;i<count;++i){UserPreset p;std::string n;int policy,flow,content,nr,sr;auto& s=p.settings;auto& m=s.model;auto& r=s.residual;
if(!(in>>std::quoted(n)>>m.intensity>>m.tone>>m.structure>>m.skin>>m.style>>m.autoMask>>m.uiCorrection>>r.total>>r.darken>>r.brighten>>r.color>>r.luminance>>nr>>sr>>s.multiplier>>policy>>flow>>content))return false;
if(version>=2){int enabled;if(!(in>>enabled>>s.protection.featherPixels)||enabled<0||enabled>1)return false;s.protection.enabled=enabled!=0;
@@ -27,6 +27,7 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std
if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>(version>=6?2:1))return false;s.frameGenerationBackend=static_cast<FrameGenerationBackend>(backend);}
if(version>=5){uint32_t target;if(!(in>>target))return false;s.srTarget=static_cast<pipeline::SrTarget>(target);}
if(version>=6){int backend,half;if(!(in>>backend>>half)||half<0||half>1)return false;s.opticalFlowBackend=static_cast<OpticalFlowBackend>(backend);s.amdFlowHalfResolution=half!=0;}
+ if(version>=7){int sync;if(!(in>>sync>>s.audioOffsetMs))return false;s.audioSync=static_cast<AudioSyncMode>(sync);}
p.name=wide(n);if(!nameOk(p.name)||std::any_of(out.begin(),out.end(),[&](auto& a){return a.name==p.name;})||nr<0||nr>1||sr<0||sr>1)return false;
s.nr=nr;s.sr=sr;s.nrPolicy=static_cast<pipeline::NrSizePolicy>(policy);s.flow=static_cast<FlowQuality>(flow);s.content=static_cast<ContentRate>(content);
if(!s.validate().empty())return false;out.push_back(std::move(p));
diff --git a/src/gfx/XessPresenter.cpp b/src/gfx/XessPresenter.cpp
index 59499380..b2c9e755 100644
--- a/src/gfx/XessPresenter.cpp
+++ b/src/gfx/XessPresenter.cpp
@@ -9,7 +9,7 @@
namespace veyra::gfx {
struct XessPresenter::Impl {
- uint64_t generated=0;
+ uint64_t generated=0,presented=0;
#ifdef VEYRA_HAS_XESS
HMODULE fgDll=nullptr,llDll=nullptr;
xefg_swapchain_handle_t fg=nullptr;
@@ -48,6 +48,9 @@ struct XessPresenter::Impl {
XessPresenter::XessPresenter():p_(std::make_unique<Impl>()){}
XessPresenter::~XessPresenter()=default;
bool XessPresenter::initialize(ID3D12Device* device,ID3D12CommandQueue* queue,IDXGIFactory2* factory,HWND window,const DXGI_SWAP_CHAIN_DESC1& desc,IDXGISwapChain3** swapchain){
+ if(GetEnvironmentVariableW(L"VEYRA_TEST_XESS_INIT_FAILURE",nullptr,0)){
+ log::warn("xess-fg","test-only initialization rejection; runtime not loaded");return false;
+ }
#ifdef VEYRA_HAS_XESS
auto& p=*p_;const auto root=runtime::localDataDirectory()/"intel"/"experimental";
auto load=[&](const wchar_t* name,const char* hash){auto path=std::filesystem::absolute(root/name);
@@ -141,6 +144,7 @@ bool XessPresenter::afterPresent(){
xefg_swapchain_present_status_t status{};
if(!p.check(p.xefgSwapChainGetLastPresentStatusFn(p.fg,&status),"PresentStatus"))return false;
if(status.isFrameGenEnabled&&status.frameGenResult==XEFG_SWAPCHAIN_RESULT_SUCCESS&&status.framesPresented>1)p.generated+=status.framesPresented-1;
+ if(status.frameGenResult>=0)p.presented+=status.framesPresented;
if(log::verboseFrameLogs()||p.id%60==0||status.frameGenResult<0)log::info("xess-fg",std::format("presentId={} enabled={} result={} framesPresented={} generatedTotal={} (SDK submissions, not measured scanout)",p.id,status.isFrameGenEnabled,int(status.frameGenResult),status.framesPresented,p.generated));
return status.frameGenResult>=0;
#else
@@ -148,4 +152,5 @@ bool XessPresenter::afterPresent(){
#endif
}
uint64_t XessPresenter::generatedCount()const{return p_->generated;}
+uint64_t XessPresenter::presentedCount()const{return p_->presented;}
}
diff --git a/src/ngx/FrucBackend.cpp b/src/ngx/FrucBackend.cpp
index 2c370c25..dbc097e0 100644
--- a/src/ngx/FrucBackend.cpp
+++ b/src/ngx/FrucBackend.cpp
@@ -118,8 +118,11 @@ bool FrucBackend::initialize(gfx::D3D12DeviceContext& ctx,unsigned width,unsigne
return p.start();
}
bool FrucBackend::reset() {
- // Fresh process avoids the pinned FRUC runtime's invalid-handle/SEH after
- // destruction/recreation. Resources stay on GPU; caller drains consumers.
+ // The next source frame updates FRUC history without warping across the
+ // discontinuity. Keep CUDA allocations and worker alive during normal reset.
+ p_->message->command=3;p_->message->result=1;p_->message->seh=0;
+ if(SetEvent(p_->request.value)&&p_->acknowledge(10000))return true;
+ log::warn("fruc-ipc","CUDA reseed failed; restarting owned worker");
p_->stop();return p_->start();
}
void FrucBackend::recordInput(ID3D12GraphicsCommandList* list,ID3D12Resource* input,unsigned parity) {
diff --git a/src/ngx/FrucWorker.cpp b/src/ngx/FrucWorker.cpp
index 0bd10dff..f11fcb79 100644
--- a/src/ngx/FrucWorker.cpp
+++ b/src/ngx/FrucWorker.cpp
@@ -16,7 +16,7 @@
namespace veyra::ngx {
using Microsoft::WRL::ComPtr;
namespace {
-bool hrOk(HRESULT hr,const char* op){log::info("fruc",std::format("{} hr=0x{:X}",op,unsigned(hr)));return SUCCEEDED(hr);}
+bool hrOk(HRESULT hr,const char* op,bool frequent=false){if(!frequent||FAILED(hr)||log::verboseFrameLogs())log::info("fruc",std::format("{} hr=0x{:X}",op,unsigned(hr)));return SUCCEEDED(hr);}
template<class Fn, class... Args>
NvOFFRUC_STATUS callSafe(unsigned& seh, Fn fn, Args... args) {
__try { return fn(args...); }
@@ -39,6 +39,25 @@ struct WorkerKernel {
using GetContext = CUresult (CUDAAPI*)(CUcontext*);
using SetContext = CUresult (CUDAAPI*)(CUcontext);
HMODULE cuda=nullptr; GetContext getContext=nullptr; SetContext setContext=nullptr;
+ bool reseed=false;
+ using DxDevice=CUresult(CUDAAPI*)(CUdevice*,IDXGIAdapter*);
+ using DxRegister=CUresult(CUDAAPI*)(CUgraphicsResource*,ID3D11Resource*,unsigned);
+ DxRegister dxRegister=nullptr;
+ decltype(&cuCtxCreate) createContext=nullptr;
+ decltype(&cuCtxDestroy) destroyContext=nullptr;
+ decltype(&cuArrayCreate) createArray=nullptr;
+ decltype(&cuArrayDestroy) destroyArray=nullptr;
+ decltype(&cuGraphicsMapResources) mapResources=nullptr;
+ decltype(&cuGraphicsUnmapResources) unmapResources=nullptr;
+ decltype(&cuGraphicsUnregisterResource) unregisterGraphics=nullptr;
+ decltype(&cuGraphicsSubResourceGetMappedArray) mappedArray=nullptr;
+ decltype(&cuMemcpy2DAsync) copyAsync=nullptr;
+ CUdevice cudaDevice=0;
+ CUcontext ownedContext[3]={}; // Only slot 0 owns the context shared by all streams.
+ CUarray arrays[3][3]={};
+ CUgraphicsResource graphics[3][3]={};
+ ComPtr<ID3D11Texture2D> bridge[3][3];
+ ComPtr<ID3D11DeviceContext4> context4;
CUcontext streamContext[3]={};
HMODULE lib=nullptr;unsigned width=0,height=0,count=0;uint64_t serial=0;
ComPtr<ID3D11Device> device;ComPtr<ID3D11Device5> device5;
@@ -66,16 +85,26 @@ struct WorkerKernel {
if(setContext&&streamContext[j])cudaOk(setContext(streamContext[j]),"ReleaseContext");
if(registered[j]) {
NvOFFRUC_UNREGISTER_RESOURCE_PARAM r{};
- r.uiCount=3;r.pArrResource[0]=tex[0].Get();r.pArrResource[1]=tex[1].Get();r.pArrResource[2]=tex[2+j].Get();
+ r.uiCount=3;for(unsigned i=0;i<3;++i)r.pArrResource[i]=arrays[j][i];
checkedCall("Unregister",unreg,handles[j],&r);
registered[j]=false;
}
checkedCall("Destroy",destroy,handles[j]);
handles[j]=nullptr;streamContext[j]=nullptr;
}
+ if(ownedContext[0]){
+ cudaOk(setContext(ownedContext[0]),"InteropReleaseContext");
+ for(unsigned j=0;j<3;++j){
+ for(unsigned i=0;i<3;++i){if(graphics[j][i])cudaOk(unregisterGraphics(graphics[j][i]),"InteropUnregister");if(arrays[j][i])cudaOk(destroyArray(arrays[j][i]),"InteropFreeArray");graphics[j][i]=nullptr;arrays[j][i]=nullptr;}
+ }
+ if(scope.saved==ownedContext[0])scope.saved=nullptr;
+ cudaOk(destroyContext(ownedContext[0]),"InteropDestroyContext");ownedContext[0]=nullptr;
+ }
}
~WorkerKernel() {
release();
+ for(auto& stream:bridge)for(auto& texture:stream)texture.Reset();
+ context4.Reset();
for(auto& t:tex)t.Reset();
fence11.Reset();context.Reset();device5.Reset();device.Reset();
if(lib)FreeLibrary(lib);
@@ -88,16 +117,25 @@ struct WorkerKernel {
if(!scope.valid)return false;
for(unsigned j=0;j<count;++j) {
NvOFFRUC_CREATE_PARAM c{};
- c.uiWidth=width;c.uiHeight=height;c.pDevice=device.Get();
- c.eResourceType=DirectX11Resource;c.eSurfaceFormat=ARGBSurface;c.eCUDAResourceType=CudaResourceTypeUndefined;
+ c.uiWidth=width;c.uiHeight=height;c.pDevice=nullptr;
+ c.eResourceType=CudaResource;c.eSurfaceFormat=ARGBSurface;c.eCUDAResourceType=CudaResourceCuArray;
+ if(!ownedContext[0]&&!cudaOk(createContext(&ownedContext[0],0,cudaDevice),"InteropCreateContext"))return false;
+ if(!cudaOk(setContext(ownedContext[0]),"InteropSharedContext"))return false;
if(!checkedCall("Create",create,&c,&handles[j])||!handles[j])return false;
- // This local runtime leaves each newly created stream's CUDA context
- // current. Preserve it and explicitly bind it for subsequent calls.
+ // Each FRUC stream uses the caller-owned CUDA context and arrays.
if(!cudaOk(getContext(&streamContext[j]),"StreamContext")||!streamContext[j])return false;
+ if(streamContext[j]!=ownedContext[0]){log::error("fruc","CUDA context ownership changed during Create");return false;}
log::info("fruc",std::format("Context stream={} ptr={}",j,static_cast<void*>(streamContext[j])));
NvOFFRUC_REGISTER_RESOURCE_PARAM r{};
- r.uiCount=3;r.pD3D11FenceObj=fence11.Get();
- r.pArrResource[0]=tex[0].Get();r.pArrResource[1]=tex[1].Get();r.pArrResource[2]=tex[j+2].Get();
+ r.uiCount=3;r.pD3D11FenceObj=nullptr;
+ for(unsigned i=0;i<3;++i){
+ {
+ CUDA_ARRAY_DESCRIPTOR d{};d.Width=width;d.Height=height;d.Format=CU_AD_FORMAT_UNSIGNED_INT8;d.NumChannels=4;
+ D3D11_TEXTURE2D_DESC texture{};texture.Width=width;texture.Height=height;texture.MipLevels=texture.ArraySize=1;texture.Format=DXGI_FORMAT_R8G8B8A8_UNORM;texture.SampleDesc.Count=1;texture.Usage=D3D11_USAGE_DEFAULT;texture.BindFlags=D3D11_BIND_SHADER_RESOURCE|D3D11_BIND_RENDER_TARGET;
+ if(!hrOk(device->CreateTexture2D(&texture,nullptr,&bridge[j][i]),"InteropBridgeTexture")||!cudaOk(createArray(&arrays[j][i],&d),"InteropCreateArray")||!cudaOk(dxRegister(&graphics[j][i],bridge[j][i].Get(),0),"InteropRegisterTexture"))return false;
+ }
+ r.pArrResource[i]=arrays[j][i];
+ }
if(!checkedCall("Register",reg,handles[j],&r))return false;
registered[j]=true;
if(!cudaOk(setContext(scope.saved),"RestoreAfterCreate"))return false;
@@ -124,26 +162,64 @@ bool WorkerKernel::initialize(FrucWorkerMessage& info) {
if(!hrOk(device5->OpenSharedFence(reinterpret_cast<HANDLE>(info.fence),IID_PPV_ARGS(&fence11)),"OpenFence"))return false;
for(unsigned j=0;j<count+2;++j)
if(!hrOk(device5->OpenSharedResource1(reinterpret_cast<HANDLE>(info.textures[j]),IID_PPV_ARGS(&tex[j])),"OpenTexture"))return false;
+ {
+ const auto getDevice=reinterpret_cast<DxDevice>(GetProcAddress(cuda,"cuD3D11GetDevice"));
+ dxRegister=reinterpret_cast<DxRegister>(GetProcAddress(cuda,"cuGraphicsD3D11RegisterResource"));
+ createContext=reinterpret_cast<decltype(createContext)>(GetProcAddress(cuda,"cuCtxCreate_v2"));
+ destroyContext=reinterpret_cast<decltype(destroyContext)>(GetProcAddress(cuda,"cuCtxDestroy_v2"));
+ createArray=reinterpret_cast<decltype(createArray)>(GetProcAddress(cuda,"cuArrayCreate_v2"));
+ destroyArray=reinterpret_cast<decltype(destroyArray)>(GetProcAddress(cuda,"cuArrayDestroy"));
+ mapResources=reinterpret_cast<decltype(mapResources)>(GetProcAddress(cuda,"cuGraphicsMapResources"));
+ unmapResources=reinterpret_cast<decltype(unmapResources)>(GetProcAddress(cuda,"cuGraphicsUnmapResources"));
+ unregisterGraphics=reinterpret_cast<decltype(unregisterGraphics)>(GetProcAddress(cuda,"cuGraphicsUnregisterResource"));
+ mappedArray=reinterpret_cast<decltype(mappedArray)>(GetProcAddress(cuda,"cuGraphicsSubResourceGetMappedArray"));
+ copyAsync=reinterpret_cast<decltype(copyAsync)>(GetProcAddress(cuda,"cuMemcpy2DAsync_v2"));
+ if(!getDevice||!dxRegister||!createContext||!destroyContext||!createArray||!destroyArray||!mapResources||!unmapResources||!unregisterGraphics||!mappedArray||!copyAsync||!cudaOk(getDevice(&cudaDevice,adapter.Get()),"InteropSameAdapter")||!hrOk(context.As(&context4),"InteropContext4"))return false;
+ }
return createStreams();
}
bool WorkerKernel::execute(FrucWorkerMessage& info) {
ContextScope scope(*this);if(!scope.valid)return false;
auto wait=info.inputFence;
+ if(!hrOk(context4->Wait(fence11.Get(),wait),"InteropInputWait",true))return false;
+ if(!cudaOk(setContext(ownedContext[0]),"ProcessContext"))return false;
+ CUgraphicsResource mapped[6]{};
+ for(unsigned j=0;j<count;++j){mapped[j*2]=graphics[j][info.parity];mapped[j*2+1]=graphics[j][2];context->CopyResource(bridge[j][info.parity].Get(),tex[info.parity].Get());}
+ context->Flush();
+ struct MappingScope {
+ WorkerKernel& owner;CUgraphicsResource* resources;unsigned count;bool active=false;
+ ~MappingScope(){if(active)cudaOk(owner.unmapResources(count,resources,nullptr),"InteropErrorUnmap");}
+ }mapping{*this,mapped,count*2};
+ if(!cudaOk(mapResources(count*2,mapped,nullptr),"InteropMap"))return false;
+ mapping.active=true;
for(unsigned j=0;j<count;++j) {
- if(!cudaOk(setContext(streamContext[j]),"ProcessContext"))return false;
NvOFFRUC_PROCESS_IN_PARAMS in{};NvOFFRUC_PROCESS_OUT_PARAMS out{};
- in.stFrameDataInput.pFrame=tex[info.parity].Get();in.stFrameDataInput.nTimeStamp=info.currentMs;
- in.uSyncWait.FenceWaitValue.uiFenceValueToWaitOn=wait;
- out.stFrameDataOutput.pFrame=tex[j+2].Get();
+ in.stFrameDataInput.pFrame=arrays[j][info.parity];in.stFrameDataInput.nTimeStamp=info.currentMs;
+ in.bSkipWarp=reseed;
+ out.stFrameDataOutput.pFrame=arrays[j][2];
out.stFrameDataOutput.nTimeStamp=info.previousMs+(info.currentMs-info.previousMs)*double(j+1)/(count+1);
out.stFrameDataOutput.bHasFrameRepetitionOccurred=&info.repeated[j];
- out.uSyncSignal.FenceSignalValue.uiFenceValueToSignalOn=++wait;
+ ++wait;
+ {
+ CUarray input=nullptr;if(!cudaOk(mappedArray(&input,mapped[j*2],0,0),"InteropInputArray"))return false;
+ CUDA_MEMCPY2D copy{};copy.srcMemoryType=CU_MEMORYTYPE_ARRAY;copy.srcArray=input;copy.dstMemoryType=CU_MEMORYTYPE_ARRAY;copy.dstArray=arrays[j][info.parity];copy.WidthInBytes=size_t(width)*4;copy.Height=height;
+ if(!cudaOk(copyAsync(&copy,nullptr),"InteropInputCopy"))return false;
+ }
unsigned seh=0;auto result=callSafe(seh,process,handles[j],&in,&out);
info.result=uint32_t(result);info.seh=seh;
if(result!=NvOFFRUC_SUCCESS||seh||log::verboseFrameLogs())log::info("fruc",std::format("Process inputMs={} outputMs={} sub={} result={} seh={} repeated={}",info.currentMs,out.stFrameDataOutput.nTimeStamp,j+1,int(result),seh,info.repeated[j]));
if(result!=NvOFFRUC_SUCCESS||seh)return false;
+ {
+ CUarray output=nullptr;if(!cudaOk(mappedArray(&output,mapped[j*2+1],0,0),"InteropOutputArray"))return false;
+ CUDA_MEMCPY2D copy{};copy.srcMemoryType=CU_MEMORYTYPE_ARRAY;copy.srcArray=arrays[j][2];copy.dstMemoryType=CU_MEMORYTYPE_ARRAY;copy.dstArray=output;copy.WidthInBytes=size_t(width)*4;copy.Height=height;
+ if(!cudaOk(copyAsync(&copy,nullptr),"InteropOutputCopy"))return false;
+ }
}
- info.outputFence=wait;return true;
+ if(!cudaOk(unmapResources(count*2,mapped,nullptr),"InteropUnmap"))return false;
+ mapping.active=false;
+ for(unsigned j=0;j<count;++j)context->CopyResource(tex[j+2].Get(),bridge[j][2].Get());
+ if(!hrOk(context4->Signal(fence11.Get(),wait),"InteropOutputSignal",true))return false;context->Flush();
+ reseed=false;info.outputFence=wait;return true;
}
} // namespace veyra::ngx
int wmain(int argc,wchar_t** argv) {
@@ -163,6 +239,7 @@ int wmain(int argc,wchar_t** argv) {
if(ready)for(;;) {
if(WaitForSingleObject(request,INFINITE)!=WAIT_OBJECT_0){exitCode=2;break;}
if(info->command==2)break;
+ if(info->command==3){kernel.reseed=true;info->result=0;info->seh=0;if(!SetEvent(response)){exitCode=2;break;}continue;}
if(info->command!=1||info->parity>1){exitCode=2;break;}
info->result=1;info->seh=0;
const bool ok=kernel.execute(*info);
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index f85c3bd7..61625cf2 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1128,7 +1128,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
out.videoFenceValue = ring_.lastSignaledValue();
if(runFg&&frucBackend_){
- if(resetFg&&realFrameIndex_>0&&(!ring_.drainQueue()||!frucBackend_->reset()))return false;
+ // Reseeding changes the next FRUC call, not resource ownership. Its
+ // input fence follows previous output copies on the same direct queue.
+ if(resetFg&&realFrameIndex_>0&&!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);
diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cpp
new file mode 100644
index 00000000..7f896af0
--- /dev/null
+++ b/src/sink/CaptureAudioSession.cpp
@@ -0,0 +1,175 @@
+#include "veyra/sink/CaptureAudioSession.h"
+#include "veyra/sink/WasapiAudioSink.h"
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <format>
+extern "C" {
+#include <libswresample/swresample.h>
+}
+namespace veyra::sink {
+namespace {
+int64_t hostTime(){return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100;}
+}
+struct CaptureAudioSession::Impl : AudioPcmSource {
+ struct Chunk {std::vector<uint8_t> bytes;double pts=0;bool discontinuity=false;};
+ WAVEFORMATEX format{};
+ mutable std::mutex mutex;
+ std::condition_variable wake;
+ std::deque<Chunk> input;
+ size_t inputBytes=0;
+ std::deque<float> pcm;
+ double headPts=0;
+ bool haveHead=false,pendingReset=false;
+ std::atomic<bool> stop{false};
+ std::atomic<float> gain{1};
+ std::atomic<unsigned> mode{0};std::atomic<int> offset{0};
+ double videoPts=0,videoHost=0;bool haveVideo=false;
+ double ingressMapping=0;bool haveIngress=false;
+ int64_t lastArrival=0;
+ CaptureAudioState state;
+ std::thread thread;
+ void fail(const wchar_t* reason){std::lock_guard lock(mutex);state.available=false;state.running=false;state.skewMs.reset();state.error=reason;}
+ size_t pull(float* dst,size_t frames,double* pts)override{
+ const size_t take=std::min(frames,pcm.size()/2);
+ *pts=haveHead?headPts:-1;
+ for(size_t i=0;i<take*2;++i){dst[i]=pcm.front();pcm.pop_front();}
+ headPts+=1000.0*take/kAudioRate;
+ return take;
+ }
+ void run(){
+ AudioRenderer renderer;
+ if(!renderer.start()){renderer.shutdown();fail(L"音频输出设备初始化失败");return;}
+ SwrContext* swr=nullptr;
+ AVChannelLayout out=AV_CHANNEL_LAYOUT_STEREO,in{};av_channel_layout_default(&in,format.nChannels);
+ const auto inputFormat=format.wFormatTag==WAVE_FORMAT_IEEE_FLOAT?AV_SAMPLE_FMT_FLT:format.wBitsPerSample==16?AV_SAMPLE_FMT_S16:AV_SAMPLE_FMT_S32;
+ const int configured=swr_alloc_set_opts2(&swr,&out,AV_SAMPLE_FMT_FLT,kAudioRate,&in,inputFormat,format.nSamplesPerSec,0,nullptr);
+ av_channel_layout_uninit(&in);
+ if(configured<0||!swr||swr_init(swr)<0){log::error("capture-audio","resampler initialization failed");swr_free(&swr);renderer.shutdown();fail(L"音频重采样初始化失败");return;}
+ const auto releaseSwr=[](SwrContext* value){swr_free(&value);};
+ std::unique_ptr<SwrContext,decltype(releaseSwr)> resampler(swr,releaseSwr);
+ double anchorHostMinusPts=0;
+ int64_t lastReset=0;
+ unsigned appliedMode=mode.load();int appliedOffset=offset.load();
+ uint64_t lastUnderruns=0;
+ while(!stop){
+ renderer.setGain(gain);
+ Chunk chunk;bool reset=false;double vPts=0,vHost=0,ingress=0;bool video=false;int64_t arrival=0;
+ {
+ std::unique_lock lock(mutex);
+ if(input.empty())wake.wait_for(lock,std::chrono::milliseconds(2));
+ if(!input.empty()){chunk=std::move(input.front());input.pop_front();inputBytes-=chunk.bytes.size();}
+ reset=pendingReset;pendingReset=false;video=haveVideo;vPts=videoPts;vHost=videoHost;
+ ingress=ingressMapping;
+ arrival=lastArrival;
+ }
+ if(mode!=appliedMode||offset!=appliedOffset){reset=true;appliedMode=mode;appliedOffset=offset;}
+ if(reset||chunk.discontinuity){
+ renderer.stopAndReset();pcm.clear();haveHead=false;swr_close(swr);
+ if(swr_init(swr)<0){fail(L"音频重采样重置失败");break;}
+ std::lock_guard lock(mutex);++state.resets;
+ }
+ if(!chunk.bytes.empty()){
+ const int inputFrames=int(chunk.bytes.size()/format.nBlockAlign);
+ const auto delay=swr_get_delay(swr,format.nSamplesPerSec);
+ const int capacity=swr_get_out_samples(swr,inputFrames);
+ if(capacity<=0||capacity>int(kAudioRate)){log::error("capture-audio","invalid converted block capacity");fail(L"音频转换块大小无效");break;}
+ std::vector<float> converted(size_t(capacity)*2);
+ uint8_t* dst[]={reinterpret_cast<uint8_t*>(converted.data())};const uint8_t* src[]={chunk.bytes.data()};
+ const int count=swr_convert(swr,dst,capacity,src,inputFrames);
+ if(count<0){log::error("capture-audio",std::format("convert failed code={}",count));fail(L"音频转换失败");break;}
+ const double start=chunk.pts-1000.0*delay/format.nSamplesPerSec;
+ if(haveHead&&std::abs(start-(headPts+1000.0*(pcm.size()/2)/kAudioRate))>50){
+ renderer.stopAndReset();pcm.clear();haveHead=false;
+ std::lock_guard lock(mutex);++state.resets;
+ }
+ if(!haveHead){headPts=start;haveHead=true;}
+ pcm.insert(pcm.end(),converted.begin(),converted.begin()+size_t(count)*2);
+ }
+ // Both streams use graph PTS. Relate the latest displayed video PTS
+ // to host time; the endpoint's own queued frames are not added again.
+ const double now=double(hostTime())/10000;
+ const bool fresh=video&&now-vHost<500;
+ const double requested=appliedMode==0&&fresh?vHost-vPts-ingress:appliedMode==1?double(appliedOffset):0;
+ const double target=std::clamp(requested,0.0,250.0);
+ const double mapping=ingress+target;
+ const bool limited=requested<0||requested>250;
+ if(!renderer.started()&&haveHead&&!pcm.empty()&&(appliedMode!=0||fresh)){
+ // Live recovery discards expired sound rather than replaying
+ // an obsolete half-second after a GPU stall or graph reset.
+ const size_t expired=std::min(pcm.size()/2,size_t(std::max(0.0,(now-mapping-headPts-5)*kAudioRate/1000)));
+ for(size_t i=0;i<expired*2;++i)pcm.pop_front();headPts+=1000.0*expired/kAudioRate;
+ const bool due=now>=mapping+headPts;
+ if(due&&!pcm.empty()){
+ if(!renderer.startAnchored(*this)){log::error("capture-audio","endpoint start failed");fail(L"音频输出启动失败");break;}
+ anchorHostMinusPts=now-renderer.mediaTimeMs();lastReset=hostTime();
+ }
+ }
+ if(renderer.started()){
+ double pts=-1;if(!renderer.pumpOnce(*this,&pts)){log::error("capture-audio","endpoint pump failed");fail(L"音频输出中断,请重新打开采集");break;}
+ const auto underruns=renderer.underruns();
+ if(underruns>lastUnderruns&&hostTime()-arrival>1000000){
+ // Silence advances IAudioClock without consuming media.
+ // Re-anchor the next real block instead of retaining that drift.
+ renderer.stopAndReset();lastReset=hostTime();
+ std::lock_guard lock(mutex);++state.resets;
+ }
+ lastUnderruns=underruns;
+ // Large video-delay changes need a bounded re-anchor. Never
+ // chase every jitter sample by stopping the audio endpoint.
+ if(appliedMode==0&&fresh&&hostTime()-lastReset>10000000&&std::abs(mapping-anchorHostMinusPts)>40){
+ renderer.stopAndReset();lastReset=hostTime();
+ std::lock_guard lock(mutex);++state.resets;
+ }
+ }
+ if(pcm.size()>kAudioRate){
+ renderer.stopAndReset();pcm.clear();haveHead=false;
+ std::lock_guard lock(mutex);++state.overflows;pendingReset=true;
+ }
+ {
+ std::lock_guard lock(mutex);state.available=true;state.running=renderer.started();state.limited=limited;
+ state.bufferedMs=1000.0*(pcm.size()/2)/kAudioRate+1000.0*inputBytes/format.nAvgBytesPerSec;
+ state.compensationMs=target;state.underruns=renderer.underruns();
+ const auto audioPts=renderer.mediaTimeMs();
+ state.skewMs=fresh&&std::isfinite(audioPts)?std::optional<double>(audioPts-(vPts+now-vHost)):std::nullopt;
+ }
+ }
+ renderer.shutdown();std::lock_guard lock(mutex);state.available=false;state.running=false;state.skewMs.reset();
+ }
+};
+CaptureAudioSession::CaptureAudioSession():p_(std::make_unique<Impl>()){}
+CaptureAudioSession::~CaptureAudioSession(){stop();}
+bool CaptureAudioSession::configure(const WAVEFORMATEX& f){
+ if(p_->thread.joinable()||f.nChannels<1||f.nChannels>2||f.nSamplesPerSec<8000||f.nSamplesPerSec>192000||
+ (f.wFormatTag!=WAVE_FORMAT_PCM&&f.wFormatTag!=WAVE_FORMAT_IEEE_FLOAT)||
+ (f.wBitsPerSample!=16&&f.wBitsPerSample!=32)||(f.wFormatTag==WAVE_FORMAT_IEEE_FLOAT&&f.wBitsPerSample!=32)||
+ f.nBlockAlign!=f.nChannels*f.wBitsPerSample/8||f.nAvgBytesPerSec!=f.nBlockAlign*f.nSamplesPerSec)return false;
+ p_->format=f;return true;
+}
+bool CaptureAudioSession::start(){
+ if(!p_->format.nBlockAlign||p_->thread.joinable())return false;
+ {std::lock_guard lock(p_->mutex);p_->input.clear();p_->inputBytes=0;p_->pcm.clear();p_->haveHead=p_->haveVideo=p_->haveIngress=p_->pendingReset=false;p_->state={};}
+ p_->stop=false;
+ try{p_->thread=std::thread([this]{try{p_->run();}catch(const std::exception& e){log::error("capture-audio",std::format("audio thread failed: {}",e.what()));p_->fail(L"音频线程异常,请重新打开采集");}});}
+ catch(const std::exception& e){log::error("capture-audio",std::format("audio thread start failed: {}",e.what()));p_->fail(L"无法创建音频线程");return false;}
+ return true;
+}
+void CaptureAudioSession::stop(){p_->stop=true;p_->wake.notify_all();if(p_->thread.joinable())p_->thread.join();std::lock_guard lock(p_->mutex);p_->input.clear();p_->inputBytes=0;p_->pcm.clear();p_->state.bufferedMs=0;}
+bool CaptureAudioSession::push(const void* data,size_t bytes,double pts,bool discontinuity){
+ auto& p=*p_;if(!data||!p.format.nBlockAlign||bytes%p.format.nBlockAlign||bytes>p.format.nAvgBytesPerSec/2||!std::isfinite(pts))return false;if(!bytes)return true;
+ std::lock_guard lock(p.mutex);
+ if(p.stop||!p.state.error.empty())return true;
+ if(discontinuity){p.input.clear();p.inputBytes=0;p.pendingReset=true;p.haveVideo=false;}
+ const double mapping=double(hostTime())/10000-pts;
+ p.lastArrival=hostTime();
+ if(!p.haveIngress||discontinuity){p.ingressMapping=mapping;p.haveIngress=true;}
+ else p.ingressMapping=std::min(p.ingressMapping,mapping);
+ if(p.inputBytes+bytes>p.format.nAvgBytesPerSec/2){p.input.clear();p.inputBytes=0;p.pendingReset=true;++p.state.overflows;}
+ Impl::Chunk c;c.bytes.resize(bytes);memcpy(c.bytes.data(),data,bytes);c.pts=pts;c.discontinuity=discontinuity;
+ p.inputBytes+=bytes;p.input.push_back(std::move(c));p.wake.notify_one();return true;
+}
+void CaptureAudioSession::videoPresented(double pts,int64_t time){std::lock_guard lock(p_->mutex);p_->videoPts=pts;p_->videoHost=double(time)/10000;p_->haveVideo=true;}
+void CaptureAudioSession::setGain(float value){p_->gain=std::clamp(value,0.0f,1.0f);}
+void CaptureAudioSession::setSync(unsigned mode,int offset){p_->mode=std::min(mode,2u);p_->offset=std::clamp(offset,-250,250);}
+CaptureAudioState CaptureAudioSession::snapshot()const{std::lock_guard lock(p_->mutex);return p_->state;}
+}
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
index e67c6cc1..63ee75c6 100644
--- a/src/sink/WasapiAudioSink.cpp
+++ b/src/sink/WasapiAudioSink.cpp
@@ -1,14 +1,11 @@
#include "veyra/sink/AudioGain.h"
-// WasapiAudioSink implementation - moved verbatim from tools/player_probe
-// main.cpp (lines ~172-686, Phase 6 session evidence). Semantics preserved:
-// watermarked bounded production ring, event-driven pump, PTS-anchored master
-// clock, atomic seek re-sequence, player mode never drops decoded audio.
#include "veyra/sink/WasapiAudioSink.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <format>
+#include <limits>
extern "C" {
#include <libavformat/avformat.h>
@@ -120,7 +117,7 @@ double AudioPipeline::requestSeek(double targetMs)
if (!seekDoneCv_.wait_for(lock, std::chrono::milliseconds(3000), [this] { return seekDone_; })) {
veyra::log::error("audio", "seek prefill timed out");
}
- return segments_.empty() ? targetMs : segments_.front().startPtsMs;
+ return seekDone_ ? firstPtsAfterSeek_.load() : std::numeric_limits<double>::quiet_NaN();
}
void AudioPipeline::pushDecoded(const AVFrame* frame)
@@ -130,20 +127,50 @@ void AudioPipeline::pushDecoded(const AVFrame* frame)
AVChannelLayout outLayout = AV_CHANNEL_LAYOUT_STEREO;
AVChannelLayout inLayout = frame->ch_layout.nb_channels > 0
? frame->ch_layout : outLayout;
- swr_alloc_set_opts2(&swr_,
+ const int result = swr_alloc_set_opts2(&swr_,
&outLayout, AV_SAMPLE_FMT_FLT, kAudioRate,
&inLayout, static_cast<AVSampleFormat>(frame->format), frame->sample_rate,
0, nullptr);
- if (swr_ == nullptr || swr_init(swr_) < 0) return;
+ if (result < 0 || swr_ == nullptr || swr_init(swr_) < 0) {
+ log::error("audio", "resampler initialization failed");
+ return;
+ }
+ }
+ // Output begins at this input PTS minus the samples retained by swr.
+ // Tagging it with the input block end shifts audio by one whole block.
+ const auto timestamp = frame->best_effort_timestamp != AV_NOPTS_VALUE
+ ? frame->best_effort_timestamp : frame->pts;
+ if (timestamp != AV_NOPTS_VALUE) {
+ const double ptsMs = timestamp * av_q2d(stream_->time_base) * 1000.0;
+ nextPtsMs_ = ptsMs - 1000.0 * swr_get_delay(swr_, frame->sample_rate) / frame->sample_rate;
+ }
+ const auto capacity = swr_get_out_samples(swr_, frame->nb_samples);
+ if (capacity <= 0 || capacity > static_cast<int>(kMaxRingFrames)) {
+ log::error("audio", "decoded audio block exceeds bounded conversion capacity");
+ return;
}
+ converted_.resize(static_cast<size_t>(capacity) * 2);
uint8_t* planes[1] = { reinterpret_cast<uint8_t*>(converted_.data()) };
const int outSamples = swr_convert(swr_, planes,
static_cast<int>(converted_.size() / 2),
const_cast<const uint8_t**>(frame->extended_data), frame->nb_samples);
- if (outSamples <= 0) return;
+ if (outSamples < 0) { log::error("audio", std::format("swr_convert failed code={}", outSamples)); return; }
+ pushConverted(outSamples);
+}
+
+void AudioPipeline::pushConverted(int frames)
+{
+ if (frames <= 0) return;
+ size_t skip = 0;
+ if (discardUntilPtsMs_ >= 0 && nextPtsMs_ < discardUntilPtsMs_) {
+ skip = std::min(static_cast<size_t>(frames), static_cast<size_t>(
+ std::ceil((discardUntilPtsMs_ - nextPtsMs_) * kAudioRate / 1000.0 - 1e-7)));
+ }
+ nextPtsMs_ += 1000.0 * skip / kAudioRate;
+ const size_t addFrames = static_cast<size_t>(frames) - skip;
+ if (!addFrames) return;
std::unique_lock<std::mutex> lock(mutex_);
- const size_t addFrames = static_cast<size_t>(outSamples);
if (ringFrames_ + addFrames > kMaxRingFrames) {
// Player mode: never drop. This is a hard error (bounded ring
// should never overflow because production is watermarked).
@@ -151,7 +178,7 @@ void AudioPipeline::pushDecoded(const AVFrame* frame)
veyra::log::error("audio", "ring overflow despite watermarks (bug)");
return;
}
- ring_.insert(ring_.end(), converted_.data(), converted_.data() + addFrames * 2);
+ ring_.insert(ring_.end(), converted_.data() + skip * 2, converted_.data() + static_cast<size_t>(frames) * 2);
ringFrames_ += addFrames;
if (!segments_.empty()) {
Segment& last = segments_.back();
@@ -169,12 +196,43 @@ void AudioPipeline::pushDecoded(const AVFrame* frame)
void AudioPipeline::decodeBlock()
{
- // Decode until high watermark or EOF; called only when below high.
- while (bufferedMsLocked() < kAudioHighWatermarkMs && !stopFlag_ && !seekRequested_) {
+ AVFrame* frame = av_frame_alloc();
+ if (!frame) return;
+ // Always receive pending frames before sending another packet. EAGAIN
+ // leaves the packet owned here until the decoder actually accepts it.
+ while (bufferedMs() < kAudioHighWatermarkMs && !stopFlag_ && !seekRequested_ && !decodedEof_) {
+ const int received = avcodec_receive_frame(codecCtx_, frame);
+ if (received == 0) {
+ pushDecoded(frame);
+ av_frame_unref(frame);
+ continue;
+ }
+ if (received == AVERROR_EOF) {
+ if (swr_) {
+ uint8_t* planes[] = {reinterpret_cast<uint8_t*>(converted_.data())};
+ const int count = swr_convert(swr_, planes, static_cast<int>(converted_.size() / 2), nullptr, 0);
+ if (count > 0) { pushConverted(count); continue; }
+ if (count < 0) log::error("audio", std::format("resampler drain failed code={}", count));
+ }
+ decodedEof_ = true;
+ break;
+ }
+ if (received != AVERROR(EAGAIN)) {
+ log::error("audio", std::format("decode receive failed code={}", received));
+ decodedEof_ = true;
+ break;
+ }
+ if (demuxEof_) {
+ if (drainSent_) { log::error("audio", "decoder requested input after drain"); decodedEof_ = true; break; }
+ const int sent = avcodec_send_packet(codecCtx_, nullptr);
+ if (sent < 0 && sent != AVERROR_EOF) { log::error("audio", std::format("decoder drain failed code={}", sent)); break; }
+ drainSent_ = true;
+ continue;
+ }
if (!havePacket_) {
if (av_read_frame(fmt_, packet_) < 0) {
demuxEof_ = true;
- break;
+ continue;
}
havePacket_ = true;
if (packet_->stream_index != streamIndex_) {
@@ -183,29 +241,17 @@ void AudioPipeline::decodeBlock()
continue;
}
}
- if (avcodec_send_packet(codecCtx_, havePacket_ ? packet_ : nullptr) == 0 && havePacket_) {
+ const int sent = avcodec_send_packet(codecCtx_, packet_);
+ if (sent == 0) {
av_packet_unref(packet_);
havePacket_ = false;
+ } else if (sent != AVERROR(EAGAIN)) {
+ log::error("audio", std::format("decode send failed code={}", sent));
+ decodedEof_ = true;
+ break;
}
- AVFrame* frame = av_frame_alloc();
- bool enough = false;
- while (avcodec_receive_frame(codecCtx_, frame) == 0) {
- const double ptsMs = 1000.0 * frame->pts * stream_->time_base.num / stream_->time_base.den;
- nextPtsMs_ = ptsMs + 1000.0 * frame->nb_samples / kAudioRate;
- if (discardUntilPtsMs_ < 0.0 || ptsMs >= discardUntilPtsMs_) {
- pushDecoded(frame);
- }
- av_frame_unref(frame);
- if (bufferedMsLocked() >= kAudioHighWatermarkMs) { enough = true; break; }
- }
- av_frame_free(&frame);
- if (enough || demuxEof_) break;
}
-}
-
-double AudioPipeline::bufferedMsLocked() const
-{
- return 1000.0 * static_cast<double>(ringFrames_) / kAudioRate;
+ av_frame_free(&frame);
}
void AudioPipeline::closeAll()
@@ -256,13 +302,12 @@ bool AudioRenderer::start()
return true;
}
-bool AudioRenderer::startAnchored(double firstBufferPtsMs)
+bool AudioRenderer::startAnchored(AudioPcmSource& pipeline)
{
- // Prefill the whole endpoint buffer with REAL samples happens on the
- // first pump() call; anchor NOW at the device position with the PTS
- // of the first sample we are about to submit.
+ double firstBufferPtsMs = -1;
+ if (!pumpOnce(pipeline, &firstBufferPtsMs) || framesWritten_ == 0) return false;
UINT64 pos = 0, qpc = 0;
- (void)clock_->GetPosition(&pos, &qpc);
+ if (FAILED(clock_->GetPosition(&pos, &qpc)) || !clockFrequency_) return false;
anchorPos_ = pos;
anchorPtsMs_.store(firstBufferPtsMs);
if (FAILED(client_->Start())) return false;
@@ -272,23 +317,25 @@ bool AudioRenderer::startAnchored(double firstBufferPtsMs)
return true;
}
-bool AudioRenderer::pumpOnce(AudioPipeline& pipeline, double* firstWrittenPtsMs)
+bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs)
{
- if (!running_ || !started_) return true;
- if (WaitForSingleObject(event_, 50) != WAIT_OBJECT_0) return true;
+ if (!running_) return false;
+ if (started_ && WaitForSingleObject(event_, 50) != WAIT_OBJECT_0) return true;
UINT32 padding = 0;
if (FAILED(client_->GetCurrentPadding(&padding))) return false;
const UINT32 avail = bufferFrames_ - padding;
if (avail == 0) return true;
+ chunk_.resize(static_cast<size_t>(avail) * 2);
+ BYTE* dest = nullptr;
+ if (FAILED(render_->GetBuffer(avail, &dest))) return false;
double firstPts = -1.0;
const size_t got = pipeline.pull(chunk_.data(), avail, &firstPts);
if (firstWrittenPtsMs) *firstWrittenPtsMs = firstPts;
- BYTE* dest = nullptr;
- if (FAILED(render_->GetBuffer(avail, &dest))) return false;
+ if (!started_ && !got) { render_->ReleaseBuffer(0, 0); return true; }
if (got > 0) {
const float target=std::clamp(gain_.load(),0.0f,1.0f);
applyStereoGain(chunk_.data(),got,target,smoothedGain_);
- if(target!=loggedGain_&&std::abs(smoothedGain_-target)<.00001f){loggedGain_=target;log::info("audio-gain",std::format("target={} reached={} framesWritten={} clockPreserved=true applicationPCM=true",target,smoothedGain_,framesWritten_));}
+ if(target!=loggedGain_&&std::abs(smoothedGain_-target)<.00001f){loggedGain_=target;log::info("audio-gain",std::format("target={} reached={} framesWritten={} clockPreserved=true applicationPCM=true",target,smoothedGain_,framesWritten_.load()));}
std::memcpy(dest, chunk_.data(), got * 8);
if (got < avail) {
std::memset(dest + got * 8, 0, (avail - got) * 8);
@@ -298,17 +345,17 @@ bool AudioRenderer::pumpOnce(AudioPipeline& pipeline, double* firstWrittenPtsMs)
std::memset(dest, 0, static_cast<size_t>(avail) * 8);
underruns_.fetch_add(1);
}
- (void)render_->ReleaseBuffer(avail, 0);
+ if (FAILED(render_->ReleaseBuffer(avail, 0))) return false;
framesWritten_ += avail;
return true;
}
double AudioRenderer::mediaTimeMs() const
{
- if (!running_ || !started_) return anchorPtsMs_.load();
+ if (!running_ || !started_) return std::numeric_limits<double>::quiet_NaN();
UINT64 pos = 0, qpc = 0;
if (FAILED(clock_->GetPosition(&pos, &qpc)) || clockFrequency_ == 0) {
- return anchorPtsMs_.load();
+ return std::numeric_limits<double>::quiet_NaN();
}
const double consumedMs = 1000.0 * static_cast<double>(pos - anchorPos_) /
static_cast<double>(clockFrequency_);
@@ -317,8 +364,8 @@ double AudioRenderer::mediaTimeMs() const
void AudioRenderer::stopAndReset()
{
- if (client_) { (void)client_->Stop(); (void)client_->Reset(); }
started_ = false;
+ if (client_) { (void)client_->Stop(); (void)client_->Reset(); }
framesWritten_ = 0;
}
@@ -363,7 +410,7 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
}
const double firstPts = headPtsMs();
if (renderer != nullptr && firstPts >= 0.0) {
- renderer->startAnchored(firstPts);
+ if (!renderer->startAnchored(*this)) log::error("audio", "initial endpoint prefill/start failed");
}
lastPrefillMs_.store(std::chrono::duration<double>(
std::chrono::steady_clock::now() - t0).count() * 1000.0);
@@ -391,17 +438,25 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
segments_.clear();
if (havePacket_) { av_packet_unref(packet_); havePacket_ = false; }
avcodec_flush_buffers(codecCtx_);
+ if (swr_) swr_free(&swr_);
const int64_t tbTarget = static_cast<int64_t>(
target * stream_->time_base.den / 1000 / stream_->time_base.num);
- avformat_seek_file(fmt_, streamIndex_, INT64_MIN, tbTarget, INT64_MAX, 0);
+ const int seekResult = avformat_seek_file(fmt_, streamIndex_, INT64_MIN, tbTarget, INT64_MAX, 0);
+ if (seekResult < 0) log::error("audio", std::format("seek failed code={}", seekResult));
demuxEof_ = false;
+ drainSent_ = false;
+ decodedEof_ = false;
+ nextPtsMs_ = target;
discardUntilPtsMs_ = target;
}
decodeBlock(); // drops pts < target, fills to high watermark
double startPts = headPtsMs();
if (startPts < 0.0) startPts = target;
firstPtsAfterSeek_.store(startPts);
- if (renderer != nullptr) { renderer->startAnchored(startPts); if (pauseNow) renderer->setPaused(true); }
+ if (renderer != nullptr) {
+ if (!renderer->startAnchored(*this)) log::error("audio", "seek endpoint prefill/start failed");
+ if (pauseNow) renderer->setPaused(true);
+ }
{
std::lock_guard<std::mutex> l2(mutex_);
discardUntilPtsMs_ = -1.0;
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 872b2b60..e636f806 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -44,6 +44,9 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
Clock::time_point pendingArrival{},readArrival{},firstArrival{},latestArrival{};
ComPtr<IGraphBuilder> graph;ComPtr<ICaptureGraphBuilder2> builder;ComPtr<IBaseFilter> device,grabFilter,nullFilter,audioFilter;ComPtr<IAMStreamConfig> config;ComPtr<ISampleGrabber> grab;ComPtr<IMediaControl> control;ComPtr<IMediaEvent> events;
float lastAudioGain=-1;bool audioGainSupported=false;
+ ComPtr<IBaseFilter> audioSink;ComPtr<IReferenceClock> referenceClock;
+ std::unique_ptr<sink::CaptureAudioSession> audioSession;
+ std::wstring audioError;
SourceInfo info;CaptureMediaLayout layout;Clock::time_point lastFrame;
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;*pp=nullptr;if(id==IID_IUnknown||id==__uuidof(ISampleGrabberCB)){*pp=static_cast<ISampleGrabberCB*>(this);AddRef();return S_OK;}return E_NOINTERFACE;}
ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{return --refs;}
@@ -86,12 +89,15 @@ std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){ComPtr<IG
out.push_back({i,w,h,fps,std::format(L"{} x {} @ {:.2f} fps · {} [format {}]",w,h,fps,pixel,i)});}freeType(t);}return out;}
const SourceInfo& CaptureCardSource::info()const{return p_->info;}
bool CaptureCardSource::setAudioGain(float gain){
- auto& p=*p_;if(!p.graph||!p.audioFilter)return false;
+ auto& p=*p_;if(p.audioSession){p.audioSession->setGain(gain);return p.audioSession->snapshot().available;}if(!p.graph||!p.audioFilter)return false;
if(gain==p.lastAudioGain)return p.audioGainSupported;
ComPtr<IBasicAudio> audio;HRESULT hr=p.graph.As(&audio);
if(SUCCEEDED(hr)){long attenuation=gain<=0?-10000:long(std::clamp(2000.0*std::log10(double(gain)),-10000.0,0.0));hr=audio->put_Volume(attenuation);}
p.lastAudioGain=gain;p.audioGainSupported=SUCCEEDED(hr);log::info("capture-audio",std::format("application gain={} hr=0x{:X}",gain,unsigned(hr)));return p.audioGainSupported;
}
+void CaptureCardSource::videoPresented(double pts,int64_t time){if(p_->audioSession)p_->audioSession->videoPresented(pts,time);}
+void CaptureCardSource::setAudioSync(unsigned mode,int offset){if(p_->audioSession)p_->audioSession->setSync(mode,offset);}
+sink::CaptureAudioState CaptureCardSource::audioState()const{auto state=p_->audioSession?p_->audioSession->snapshot():sink::CaptureAudioState{};if(!p_->audioError.empty())state.error=p_->audioError;return state;}
bool CaptureCardSource::open(const SourceOpenDesc& desc){return configure(desc)&&start();}
bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAudioGain=-1;auto& p=*p_;unsigned index=0;int format=0,audio=-1;if(swscanf_s(desc.path.c_str(),L"capture:%u:%d:%d",&index,&format,&audio)!=3)return false;
if(!configuration(index,p.graph,p.builder,p.device,p.config))return false;
@@ -130,7 +136,45 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=p.layout.width;p.info.height=p.layout.height;p.info.averageFps=p.layout.duration>0?1e7/p.layout.duration:0;p.info.duration=pipeline::Rational::unknown();p.info.color=p.layout.color;
p.nominalDuration100ns=p.layout.duration;
log::info("capture-color",std::format("format={} stride={} rowBytes={} bytes={} bottomUp={} matrix={} assumed={} range={} assumed={} workingTransfer={} assumed={} (SDR display-referred)",int(p.layout.format),p.layout.stride,p.layout.rowBytes,p.layout.sampleBytes,p.layout.bottomUp,int(p.info.color.matrix),p.info.color.matrixAssumed,int(p.info.color.range),p.info.color.rangeAssumed,int(p.info.color.transfer),p.info.color.transferAssumed));
- if(audio>=0){if(!bind(unsigned(audio),true,p.audioFilter)||FAILED(p.graph->AddFilter(p.audioFilter.Get(),L"Capture audio"))||FAILED(p.builder->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Audio,p.audioFilter.Get(),nullptr,nullptr)))return false;}
+ if(audio>=0){
+ const bool connected=[&]{
+ if(!bind(unsigned(audio),true,p.audioFilter)||FAILED(p.graph->AddFilter(p.audioFilter.Get(),L"Capture audio")))return false;
+ ComPtr<IPin> audioPin;
+ if(FAILED(p.builder->FindPin(p.audioFilter.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Audio,FALSE,0,&audioPin)))return false;
+ ComPtr<IEnumMediaTypes> types;if(FAILED(audioPin->EnumMediaTypes(&types)))return false;
+ bool connectedAudio=false;
+ for(;;){
+ AM_MEDIA_TYPE* type=nullptr;if(types->Next(1,&type,nullptr)!=S_OK)break;
+ auto session=std::make_unique<sink::CaptureAudioSession>();ComPtr<IBaseFilter> candidate;ComPtr<IPin> terminal;
+ if(type->formattype==FORMAT_WaveFormatEx&&type->pbFormat&&type->cbFormat>=sizeof(WAVEFORMATEX)&&session->configure(*reinterpret_cast<WAVEFORMATEX*>(type->pbFormat))){
+ auto* target=session.get();
+ hr=createNativeAudioSink(*type,[target](IMediaSample* sample){
+ BYTE* bytes=nullptr;REFERENCE_TIME begin=0,end=0;
+ if(FAILED(sample->GetPointer(&bytes))||FAILED(sample->GetTime(&begin,&end)))return VFW_E_SAMPLE_TIME_NOT_SET;
+ return target->push(bytes,size_t(sample->GetActualDataLength()),double(begin)/10000,sample->IsDiscontinuity()==S_OK)?S_OK:E_FAIL;
+ },candidate,terminal);
+ if(SUCCEEDED(hr))hr=p.graph->AddFilter(candidate.Get(),L"Veyra audio PCM");
+ if(SUCCEEDED(hr))hr=p.graph->ConnectDirect(audioPin.Get(),terminal.Get(),type);
+ if(SUCCEEDED(hr)){p.audioSink=candidate;p.audioSession=std::move(session);connectedAudio=true;}
+ else if(candidate)p.graph->RemoveFilter(candidate.Get());
+ log::info("capture-audio",std::format("PCM ConnectDirect hr=0x{:X}",unsigned(hr)));
+ }
+ freeType(type);if(connectedAudio)break;
+ }
+ return connectedAudio;
+ }();
+ if(!connected){
+ p.audioError=L"采集音频设备或 PCM 格式不可用;视频继续运行";
+ log::warn("capture-audio","audio connection unavailable; retaining video capture");
+ if(p.audioFilter)p.graph->RemoveFilter(p.audioFilter.Get());
+ p.audioFilter.Reset();
+ }
+ // Pin the common graph clock before Run; removing DirectShow's audio
+ // renderer must not silently change the capture graph's reference.
+ ComPtr<IMediaFilter> mediaFilter;
+ if(FAILED(CoCreateInstance(CLSID_SystemClock,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.referenceClock)))||
+ FAILED(p.graph.As(&mediaFilter))||FAILED(mediaFilter->SetSyncSource(p.referenceClock.Get())))return false;
+ }
if(FAILED(p.graph.As(&p.control))||FAILED(p.graph.As(&p.events)))return false;
if(p.grab&&(FAILED(p.grab->SetBufferSamples(FALSE))||FAILED(p.grab->SetCallback(&p,0))))return false;
for(auto** f:{&p.frame,&p.pendingFrame}){
@@ -148,6 +192,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
}
bool CaptureCardSource::start(){
auto& p=*p_;if(p.info.opened)return true;if(!p.configured||!p.control)return false;
+ if(p.audioSession&&!p.audioSession->start())log::warn("capture-audio","audio start failed; retaining video capture");
p.lastFrame=Impl::Clock::now();const auto hr=p.control->Run();p.info.opened=SUCCEEDED(hr);
veyra::log::info("capture",std::format("Run hr=0x{:X} actual={}x{} nominalFps={:.3f} mailbox=1 ownedBuffers=2",unsigned(hr),p.info.width,p.info.height,p.info.averageFps));return p.info.opened;
}
@@ -178,7 +223,8 @@ SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVF
}
void CaptureCardSource::close()noexcept{
auto& p=*p_;if(p.control)p.control->Stop();if(p.grab)p.grab->SetCallback(nullptr,0);
- p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();
+ if(p.audioSession)p.audioSession->stop();p.audioError.clear();
+ p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioSink.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();p.referenceClock.Reset();p.audioSession.reset();
av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);p.info={};
p.sequence=p.received=p.dropped=p.lastDrop=0;p.pending=p.callbackError=p.configured=false;p.lastPts=p.readAgeMs=0;
}
diff --git a/src/source/NativeCaptureSink.cpp b/src/source/NativeCaptureSink.cpp
index 5c1199d7..5abf965d 100644
--- a/src/source/NativeCaptureSink.cpp
+++ b/src/source/NativeCaptureSink.cpp
@@ -2,6 +2,7 @@
#include "veyra/source/CaptureMediaType.h"
#include "veyra/Log.h"
#include <format>
+#include <mmreg.h>
#include <atomic>
#include <mutex>
#include <string>
@@ -15,6 +16,19 @@ HRESULT copyType(AM_MEDIA_TYPE& dst,const AM_MEDIA_TYPE& src){
if(src.cbFormat){if(!src.pbFormat)return E_INVALIDARG;dst.pbFormat=static_cast<BYTE*>(CoTaskMemAlloc(src.cbFormat));if(!dst.pbFormat)return E_OUTOFMEMORY;memcpy(dst.pbFormat,src.pbFormat,src.cbFormat);}
dst.pUnk=src.pUnk;if(dst.pUnk)dst.pUnk->AddRef();return S_OK;
}
+bool audioType(const AM_MEDIA_TYPE& t){
+ if(t.majortype!=MEDIATYPE_Audio||t.formattype!=FORMAT_WaveFormatEx||!t.pbFormat||t.cbFormat<sizeof(WAVEFORMATEX))return false;
+ const auto& f=*reinterpret_cast<const WAVEFORMATEX*>(t.pbFormat);
+ return (f.wFormatTag==WAVE_FORMAT_PCM||f.wFormatTag==WAVE_FORMAT_IEEE_FLOAT)&&
+ f.nChannels>=1&&f.nChannels<=2&&f.nSamplesPerSec>=8000&&f.nSamplesPerSec<=192000&&
+ (f.wBitsPerSample==16||f.wBitsPerSample==32)&&
+ (f.wFormatTag!=WAVE_FORMAT_IEEE_FLOAT||f.wBitsPerSample==32)&&
+ f.nBlockAlign==f.nChannels*f.wBitsPerSample/8&&f.nAvgBytesPerSec==f.nSamplesPerSec*f.nBlockAlign;
+}
+bool sameAudio(const AM_MEDIA_TYPE& a,const AM_MEDIA_TYPE& b){
+ return audioType(a)&&audioType(b)&&a.subtype==b.subtype&&
+ std::memcmp(a.pbFormat,b.pbFormat,sizeof(WAVEFORMATEX))==0;
+}
class PinEnum final:public IEnumPins {
std::atomic<ULONG> refs_{1};ComPtr<IPin> pin_;bool used_=false;
public:
@@ -45,9 +59,12 @@ class NativeSink final:public IBaseFilter,public IPin,public IMemInputPin {
ComPtr<IPin> peer_;ComPtr<IMemAllocator> allocator_;ComPtr<IReferenceClock> clock_;
IFilterGraph* graph_=nullptr;std::wstring name_=L"Native capture mailbox";
std::function<HRESULT(IMediaSample*)> callback_;
+ bool audio_=false;
public:
NativeSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(IMediaSample*)> cb):callback_(std::move(cb)){
- if(!captureMediaLayout(type,layout_)||FAILED(copyType(desired_,type)))throw std::bad_alloc();
+ audio_=audioType(type);
+ if((!audio_&&!captureMediaLayout(type,layout_))||FAILED(copyType(desired_,type)))throw std::bad_alloc();
+ if(audio_)layout_.sampleBytes=reinterpret_cast<const WAVEFORMATEX*>(type.pbFormat)->nBlockAlign;
}
~NativeSink(){clearType(desired_);clearType(connected_);}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{
@@ -74,7 +91,7 @@ public:
if(!peer||!type)return E_POINTER;std::lock_guard lock(mutex_);if(state_!=State_Stopped)return VFW_E_NOT_STOPPED;if(peer_)return VFW_E_ALREADY_CONNECTED;
PIN_DIRECTION direction;if(FAILED(peer->QueryDirection(&direction))||direction!=PINDIR_OUTPUT)return VFW_E_INVALID_DIRECTION;
if(QueryAccept(type)!=S_OK)return VFW_E_TYPE_NOT_ACCEPTED;
- const auto hr=copyType(connected_,*type);if(FAILED(hr))return hr;peer_=peer;captureMediaLayout(*type,layout_);return S_OK;
+ const auto hr=copyType(connected_,*type);if(FAILED(hr))return hr;peer_=peer;if(!audio_)captureMediaLayout(*type,layout_);return S_OK;
}
HRESULT STDMETHODCALLTYPE Disconnect()override{std::lock_guard lock(mutex_);if(state_!=State_Stopped)return VFW_E_NOT_STOPPED;const bool connected=bool(peer_);peer_.Reset();allocator_.Reset();clearType(connected_);return connected?S_OK:S_FALSE;}
HRESULT STDMETHODCALLTYPE ConnectedTo(IPin** p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);*p=nullptr;return peer_?peer_.CopyTo(p):VFW_E_NOT_CONNECTED;}
@@ -83,7 +100,7 @@ public:
HRESULT STDMETHODCALLTYPE QueryDirection(PIN_DIRECTION* p)override{if(!p)return E_POINTER;*p=PINDIR_INPUT;return S_OK;}
HRESULT STDMETHODCALLTYPE QueryId(LPWSTR* p)override{if(!p)return E_POINTER;*p=static_cast<LPWSTR>(CoTaskMemAlloc(sizeof(L"Input")));if(!*p)return E_OUTOFMEMORY;memcpy(*p,L"Input",sizeof(L"Input"));return S_OK;}
HRESULT STDMETHODCALLTYPE QueryAccept(const AM_MEDIA_TYPE* p)override{
- if(!p)return E_POINTER;std::lock_guard lock(mutex_);if(peer_)return equivalentCaptureTypes(*p,connected_)?S_OK:S_FALSE;CaptureMediaLayout candidate;
+ if(!p)return E_POINTER;std::lock_guard lock(mutex_);if(audio_)return sameAudio(*p,peer_?connected_:desired_)?S_OK:S_FALSE;if(peer_)return equivalentCaptureTypes(*p,connected_)?S_OK:S_FALSE;CaptureMediaLayout candidate;
return captureMediaLayout(*p,candidate)&&p->subtype==desired_.subtype&&candidate.width==layout_.width&&candidate.height==layout_.height?S_OK:S_FALSE;
}
HRESULT STDMETHODCALLTYPE EnumMediaTypes(IEnumMediaTypes** p)override{if(!p)return E_POINTER;try{*p=new TypeEnum(desired_);return S_OK;}catch(...){*p=nullptr;return E_OUTOFMEMORY;}}
@@ -102,10 +119,11 @@ public:
AM_MEDIA_TYPE* changed=nullptr;const auto typeHr=sample->GetMediaType(&changed);
if(FAILED(typeHr)){if(changed){clearType(*changed);CoTaskMemFree(changed);}log::error("capture",std::format("sample GetMediaType hr=0x{:08X}",uint32_t(typeHr)));return typeHr;}
if(typeHr==S_OK&&changed){
- const bool same=equivalentCaptureTypes(*changed,connected_);
+ const bool same=audio_?sameAudio(*changed,connected_):equivalentCaptureTypes(*changed,connected_);
clearType(*changed);CoTaskMemFree(changed);if(!same){log::error("capture",std::format("dynamic capture contract changed; reopen required hr=0x{:08X}",uint32_t(VFW_E_INVALIDMEDIATYPE)));return VFW_E_INVALIDMEDIATYPE;}
}
- if(sample->GetActualDataLength()<LONG(layout_.sampleBytes))return VFW_E_BUFFER_UNDERFLOW;
+ if(audio_){const auto block=reinterpret_cast<const WAVEFORMATEX*>(connected_.pbFormat)->nBlockAlign;if(sample->GetActualDataLength()<0||sample->GetActualDataLength()%block)return VFW_E_BUFFER_UNDERFLOW;}
+ else if(sample->GetActualDataLength()<LONG(layout_.sampleBytes))return VFW_E_BUFFER_UNDERFLOW;
try{return callback_(sample);}catch(...){return E_FAIL;}
}
HRESULT STDMETHODCALLTYPE ReceiveMultiple(IMediaSample** p,long n,long* done)override{if(!p||!done||n<0)return E_INVALIDARG;*done=0;while(*done<n){const auto hr=Receive(p[*done]);if(hr!=S_OK)return hr;++*done;}return S_OK;}
@@ -116,4 +134,8 @@ HRESULT createNativeCaptureSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(
filter.Reset();pin.Reset();CaptureMediaLayout layout;if(!captureMediaLayout(type,layout))return VFW_E_INVALIDMEDIATYPE;
try{filter.Attach(new NativeSink(type,std::move(callback)));return filter.As(&pin);}catch(...){return E_OUTOFMEMORY;}
}
+HRESULT createNativeAudioSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(IMediaSample*)> callback,ComPtr<IBaseFilter>& filter,ComPtr<IPin>& pin){
+ filter.Reset();pin.Reset();if(!audioType(type))return VFW_E_INVALIDMEDIATYPE;
+ try{filter.Attach(new NativeSink(type,std::move(callback)));return filter.As(&pin);}catch(...){return E_OUTOFMEMORY;}
+}
}
diff --git a/tests/integration/AudioTimelineTests.cpp b/tests/integration/AudioTimelineTests.cpp
new file mode 100644
index 00000000..74765891
--- /dev/null
+++ b/tests/integration/AudioTimelineTests.cpp
@@ -0,0 +1,72 @@
+#include "veyra/sink/WasapiAudioSink.h"
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <cmath>
+#include <functional>
+
+using namespace veyra::sink;
+using namespace std::chrono_literals;
+namespace {
+int failures = 0;
+void check(bool ok, const char* text) {
+ std::cout << (ok ? "PASS " : "FAIL ") << text << '\n';
+ failures += !ok;
+}
+bool until(const std::function<bool()>& ready) {
+ const auto limit = std::chrono::steady_clock::now() + 3s;
+ while (!ready() && std::chrono::steady_clock::now() < limit) std::this_thread::sleep_for(2ms);
+ return ready();
+}
+void fixture(const std::filesystem::path& file, uint32_t rate) {
+ std::ofstream out(file, std::ios::binary);
+ auto word = [&](uint32_t v, unsigned bytes) { for (unsigned i=0;i<bytes;++i) out.put(char(v >> (8*i))); };
+ const uint32_t frames = rate * 3 / 4;
+ out.write("RIFF",4); word(36+frames*2,4); out.write("WAVEfmt ",8); word(16,4);
+ word(1,2); word(1,2); word(rate,4); word(rate*2,4); word(2,2); word(16,2);
+ out.write("data",4); word(frames*2,4);
+ for (uint32_t i=0;i<frames;++i) word(uint16_t(int16_t(12000*std::sin(i*0.031))),2);
+}
+void decode(const std::filesystem::path& file) {
+ AudioPipeline pipe;
+ check(pipe.open(file.wstring()), "open PCM fixture");
+ pipe.startThread(nullptr);
+ check(until([&] { return pipe.decodingComplete(); }), "decoder and resampler fully drained");
+ check(std::abs(pipe.headPtsMs()) < 0.05, "first PCM timestamp is block start at zero");
+ check(std::abs(pipe.tailPtsMs()-750) < 0.05, "resampled tail preserves 750ms duration");
+ size_t total=0; double pts=0, maxError=0; std::vector<float> block(2*137);
+ while (auto n=pipe.pull(block.data(),137,&pts)) {
+ maxError=std::max(maxError,std::abs(pts-1000.0*total/kAudioRate)); total+=n;
+ }
+ std::cout << "samples=" << total << " maxPtsErrorMs=" << maxError << '\n';
+ check(total==36000 && maxError<0.05, "no samples lost and PTS contiguous across packet boundaries");
+ const double seek=pipe.requestSeek(123.25);
+ check(seek>=123.25-0.001 && seek<123.25+1000.0/kAudioRate+0.001, "seek trims within a block at sample precision");
+ check(until([&]{return pipe.decodingComplete();}), "seek drains through end");
+ check(std::abs(pipe.tailPtsMs()-750)<0.05, "seek resets resampler history and preserves end PTS");
+ check(pipe.overruns()==0, "bounded PCM ring did not overflow");
+ pipe.stopThread();
+}
+}
+int wmain(int argc, wchar_t** argv) {
+ if (argc!=2) return 2;
+ const std::filesystem::path dir=argv[1]; std::filesystem::create_directories(dir);
+ for(uint32_t rate:{48000u,44100u}) { const auto file=dir/(std::to_string(rate)+".wav"); fixture(file,rate); decode(file); }
+ AudioRenderer renderer;
+ check(!std::isfinite(renderer.mediaTimeMs()), "unstarted clock is invalid");
+ if (!renderer.start()) { check(false,"WASAPI endpoint initialization"); renderer.shutdown(); return 1; }
+ renderer.setGain(0);
+ AudioPipeline pipe; check(pipe.open((dir/"48000.wav").wstring()),"open renderer fixture");
+ pipe.startThread(&renderer);
+ check(until([&]{return renderer.started();}),"WASAPI prefilled and started");
+ check(renderer.framesWritten()>0 && std::isfinite(renderer.mediaTimeMs()),"valid clock only after actual PCM submission");
+ std::this_thread::sleep_for(80ms); pipe.setPaused(true); std::this_thread::sleep_for(100ms);
+ const auto before=renderer.mediaTimeMs(); std::this_thread::sleep_for(70ms);
+ check(std::abs(renderer.mediaTimeMs()-before)<2,"paused device clock remains fixed");
+ const auto seek=pipe.requestSeek(250);
+ std::this_thread::sleep_for(30ms);
+ check(std::abs(seek-250)<0.05 && std::abs(renderer.mediaTimeMs()-250)<20,"paused seek reanchors actual PCM");
+ pipe.stopThread(); renderer.stopAndReset();
+ check(!std::isfinite(renderer.mediaTimeMs()),"reset invalidates clock");
+ renderer.shutdown(); return failures ? 1 : 0;
+}
diff --git a/tests/integration/CaptureAudioTests.cpp b/tests/integration/CaptureAudioTests.cpp
new file mode 100644
index 00000000..4185983f
--- /dev/null
+++ b/tests/integration/CaptureAudioTests.cpp
@@ -0,0 +1,55 @@
+#include "veyra/sink/CaptureAudioSession.h"
+#include <chrono>
+#include <thread>
+#include <iostream>
+#include <vector>
+#include <cmath>
+int main(){
+ using namespace veyra::sink;using Clock=std::chrono::steady_clock;
+ CaptureAudioSession audio;WAVEFORMATEX f{};f.wFormatTag=WAVE_FORMAT_PCM;f.nChannels=2;f.nSamplesPerSec=48000;f.wBitsPerSample=16;f.nBlockAlign=4;f.nAvgBytesPerSec=192000;
+ if(!audio.configure(f)||!audio.start())return 2;audio.setGain(0);
+ std::vector<int16_t> pcm(960,0);const auto start=Clock::now();
+ double sum=0;unsigned count=0;bool bounded=true;
+ for(unsigned i=0;i<160;++i){
+ const auto due=start+std::chrono::milliseconds(i*10);std::this_thread::sleep_until(due);
+ const auto time=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;
+ if(!audio.push(pcm.data(),pcm.size()*2,i*10.0,i==0))return 3;
+ if(i>=8)audio.videoPresented(i*10.0-80,time);
+ const auto s=audio.snapshot();bounded&=s.bufferedMs<=520;
+ if(i>70&&s.running&&s.skewMs){sum+=std::abs(*s.skewMs);++count;}
+ }
+ const auto state=audio.snapshot();
+ std::cout<<"capture_audio meanAbsSkewMs="<<(count?sum/count:-1)<<" samples="<<count<<" compensationMs="<<state.compensationMs<<" queueMs="<<state.bufferedMs<<" resets="<<state.resets<<" overflows="<<state.overflows<<" underruns="<<state.underruns<<'\n';
+ bool ok=count>=60&&sum/count<25&&state.compensationMs>=65&&state.compensationMs<=95&&bounded&&state.overflows==0;
+ std::cout<<(ok?"PASS":"FAIL")<<" synthetic capture PTS with 80ms video delay; real WASAPI, no physical capture\n";
+ unsigned sequence=160;
+ auto phase=[&](unsigned mode,int offset,double delay,double expectedComp,double expectedSkew){
+ audio.setSync(mode,offset);double error=0;unsigned samples=0;bool boundedPhase=true;
+ for(unsigned j=0;j<150;++j,++sequence){
+ std::this_thread::sleep_until(start+std::chrono::milliseconds(sequence*10));
+ const auto host=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;
+ if(!audio.push(pcm.data(),pcm.size()*2,sequence*10.0,false))return false;
+ audio.videoPresented(sequence*10.0-delay,host);const auto s=audio.snapshot();
+ boundedPhase&=s.bufferedMs<=520;
+ if(j>70&&s.running&&s.skewMs){error+=std::abs(*s.skewMs-expectedSkew);++samples;}
+ }
+ const auto s=audio.snapshot();const bool pass=samples>=60&&error/samples<28&&std::abs(s.compensationMs-expectedComp)<15&&boundedPhase&&s.overflows==0;
+ std::cout<<(pass?"PASS ":"FAIL ")<<"capture phase mode="<<mode<<" delay="<<delay<<" compensation="<<s.compensationMs<<" meanSkewError="<<(samples?error/samples:-1)<<" resets="<<s.resets<<'\n';return pass;
+ };
+ ok=phase(0,0,160,160,0)&&ok;
+ ok=phase(1,100,80,100,-20)&&ok;
+ ok=phase(2,0,80,0,80)&&ok;
+ ok=phase(1,-100,80,0,80)&&ok;
+ const auto beforeStall=audio.snapshot().resets;
+ std::this_thread::sleep_for(std::chrono::milliseconds(350));sequence+=35;
+ ok=phase(0,0,80,80,0)&&ok;
+ const bool recovered=audio.snapshot().resets>beforeStall;
+ std::cout<<(recovered?"PASS ":"FAIL ")<<"audio reanchors real PCM after ingress stall\n";ok=recovered&&ok;
+ audio.stop();
+ const auto stopped=audio.snapshot();const bool stoppedClean=!stopped.available&&!stopped.running&&!stopped.skewMs&&stopped.bufferedMs==0;
+ std::cout<<(stoppedClean?"PASS ":"FAIL ")<<"stopped audio has no stale clock or queued state\n";ok=stoppedClean&&ok;
+ if(!audio.start())return 4;
+ ok=phase(0,0,80,80,0)&&ok;
+ audio.stop();
+ return ok?0:1;
+}
diff --git a/tests/integration/FrucTests.cpp b/tests/integration/FrucTests.cpp
index dedf3390..984e8718 100644
--- a/tests/integration/FrucTests.cpp
+++ b/tests/integration/FrucTests.cpp
@@ -8,17 +8,48 @@
#include <iostream>
#include <cmath>
#include <string_view>
+#include <chrono>
+#include <deque>
+#include <thread>
extern "C" {
#include <libavutil/frame.h>
#include <libavutil/pixfmt.h>
}
int main(int argc,char** argv){using namespace veyra;if(argc<3)return 2;const unsigned mult=unsigned(std::stoi(argv[1]));if(mult<2||mult>4)return 2;
- constexpr unsigned W=1920,H=1080;std::vector<unsigned char> base(W*H);std::ifstream input(argv[2],std::ios::binary);if(!input.read(reinterpret_cast<char*>(base.data()),base.size()))return 2;
+ const bool throughput=argc>3&&(std::string_view(argv[3])=="--throughput"||std::string_view(argv[3])=="--4k-throughput");
+ const unsigned W=argc>3&&std::string_view(argv[3])=="--4k-throughput"?3840:1920,H=W*9/16;
+ std::vector<unsigned char> base(1920*1080);std::ifstream input(argv[2],std::ios::binary);if(!input.read(reinterpret_cast<char*>(base.data()),base.size()))return 2;
CoInitializeEx(nullptr,COINIT_MULTITHREADED);gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;pipeline::EnhanceGraph graph(ctx,ring);Status st;
gfx::DeviceContextDesc deviceDesc{};bool ok=ctx.initialize(deviceDesc,st)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st);
pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=W;gd.sourceHeight=gd.workHeight=H;gd.rgbInput=true;gd.enableNr=gd.enableSr=false;gd.enableFg=true;gd.fgMultiplier=mult;gd.frameGenerationBackend=engine::FrameGenerationBackend::Fruc;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();if(ok)ok=graph.initialize(gd)&&graph.createViews();
AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_RGBA;f->width=W;f->height=H;f->color_range=AVCOL_RANGE_JPEG;ok=ok&&av_frame_get_buffer(f,32)>=0;
- auto color=[&](int x,unsigned y,unsigned c){const unsigned v=base[size_t(y)*W+std::clamp(x,0,int(W)-1)];return c==0?v:c==1?v/2+32:255-v;};
+ auto color=[&](int x,unsigned y,unsigned c){const unsigned v=base[size_t(y%1080)*1920+unsigned(std::clamp(x,0,int(W)-1))%1920];return c==0?v:c==1?v/2+32:255-v;};
+ if(throughput){
+ using Clock=std::chrono::steady_clock;std::deque<pipeline::EnhanceGraph::FrameOutputs> pending;
+ std::vector<double> cpuMs,gpuMs;uint64_t completed=0,generated=0;const auto start=Clock::now();
+ auto collect=[&]{
+ if(!graph.resolveGeneration(pending.front()))return false;
+ for(const auto& sample:pending.front().batch.frames)if(sample.kind==pipeline::FrameKind::Generated&&sample.validity==pipeline::GenerationValidity::Valid)++generated;
+ ++completed;pending.pop_front();return true;
+ };
+ for(unsigned i=0;ok&&i<120;++i){
+ while(pending.size()>=2){if(collect())break;if(Clock::now()-start>std::chrono::seconds(60)){ok=false;break;}std::this_thread::sleep_for(std::chrono::milliseconds(1));}
+ if(!ok)break;
+ for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;for(unsigned c=0;c<3;++c)p[c]=static_cast<unsigned char>(color(int(x)-int(i%30)*8,y,c));p[3]=255;}
+ pipeline::EnhanceGraph::FrameOutputs output;const auto begin=Clock::now();
+ ok=graph.process(f,i*1000.0/60,i%30==0,output);
+ if(!ok)break;
+ if(i>8)cpuMs.push_back(std::chrono::duration<double,std::milli>(Clock::now()-begin).count());
+ pending.push_back(std::move(output));
+ const auto timing=graph.gpuMetrics().gpu[size_t(diagnostics::GpuStage::FgBatch)];if(i>8&&timing.milliseconds)gpuMs.push_back(*timing.milliseconds);
+ }
+ while(ok&&!pending.empty()){if(!collect()){if(Clock::now()-start>std::chrono::seconds(60)){ok=false;break;}std::this_thread::sleep_for(std::chrono::milliseconds(1));}}
+ auto percentile=[](std::vector<double> values,unsigned pct){if(values.empty())return -1.0;std::sort(values.begin(),values.end());return values[(values.size()*pct+99)/100-1];};
+ const double elapsed=std::chrono::duration<double>(Clock::now()-start).count();
+ ok=ok&&completed==120&&generated>0;
+ std::cout<<"FRUC_THROUGHPUT extent="<<W<<'x'<<H<<" multiplier="<<mult<<" completed="<<completed<<" generated="<<generated<<" wallSeconds="<<elapsed<<" sourceFps="<<completed/elapsed<<" processCpuMedianMs="<<percentile(cpuMs,50)<<" processCpuP95Ms="<<percentile(cpuMs,95)<<" observedFgGpuMedianMs="<<percentile(gpuMs,50)<<" pixelReadback=0 pass="<<ok<<std::endl;
+ pending.clear();ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;
+ }
unsigned generated=0;double worst=0;for(unsigned i=0;ok&&i<6;++i){for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;for(unsigned c=0;c<3;++c)p[c]=static_cast<unsigned char>(color(int(x)-int(i)*8,y,c));p[3]=255;}
pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(f,i*1000.0/15,i==0,out)||!ring.waitIdle()||!graph.resolveGeneration(out)){ok=false;break;}
for(unsigned j=0;j<out.batch.count;++j){auto& item=out.batch.frames[j];if(item.kind!=pipeline::FrameKind::Generated)continue;sink::RgbaImage image;if(!sink::readRgba8(ctx,ring,item.lease->texture.Get(),image)){ok=false;break;}
@@ -39,7 +70,7 @@ int main(int argc,char** argv){using namespace veyra;if(argc<3)return 2;const un
// smoke above never claimed pixel correctness after its static reseeds.
if(argc>3&&std::string_view(argv[3])=="--reset-pixels"){
bool pixelsOk=true;
- for(unsigned epoch=1;ok&&epoch<=6;++epoch){const double start=10000+epoch*1000;const bool invert=epoch%2!=0;
+ for(unsigned epoch=1;ok&&epoch<=6;++epoch){const double start=epoch%2?10000+epoch*1000:500;const bool invert=epoch%2!=0;
for(unsigned i=0;ok&&i<3;++i){const int shift=int(epoch)*16+int(i)*8;
for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;for(unsigned c=0;c<3;++c){const auto v=color(int(x)-shift,y,c);p[c]=static_cast<unsigned char>(invert?255-v:v);}p[3]=255;}
pipeline::EnhanceGraph::FrameOutputs out;ok=graph.process(f,start+i*1000.0/15,i==0,out)&&ring.waitIdle()&&graph.resolveGeneration(out);
diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cpp
index cdd04a12..76f4c3bf 100644
--- a/tests/integration/LivePresentationTests.cpp
+++ b/tests/integration/LivePresentationTests.cpp
@@ -8,18 +8,31 @@ 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||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==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||wcscmp(argv[3],L"--file-overload")==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;
const bool overload=argc==4&&std::wstring(argv[3]).find(L"--overload")==0;
+ const bool fileOverload=argc==4&&wcscmp(argv[3],L"--file-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;
+ if(fileOverload){options.captureReplayForTest=false;options.nr=options.sr=options.fg=true;options.realtime=false;options.fgMultiplier=4;options.settings.videoSrQuality=4;}
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(fileOverload){
+ engine.setVolume(0,true);bool held=false,resumed=false;double maxLead=0;
+ check(until([&](const auto& s){held|=s.audioRebuffering;resumed|=held&&!s.audioRebuffering&&s.frames>10;maxLead=std::max(maxLead,s.lateMs);return s.frames>=100;},35),"overloaded file keeps advancing without dropping source frames or deadlocking");
+ check(held&&resumed,"actual GPU overload holds audio and resumes after video catches up");
+ const auto before=engine.snapshot();engine.pause(true);engine.seek(.5);
+ check(until([](const auto& s){return s.transport==engine::TransportState::Paused&&s.position>=.49&&s.position<.6;}),"paused seek survives an audio overload hold");
+ engine.pause(false);check(until([&](const auto& s){return s.frames>before.frames+8;}),"file resumes after overload and seek");
+ engine.stop();check(until([&](const auto&){return engine.idle();},5),"file overload shutdown");
+ std::cout<<"FILE_OVERLOAD held="<<held<<" resumed="<<resumed<<" maxObservedLeadMs="<<maxLead<<'\n';
+ DestroyWindow(window);CoUninitialize();return failures?1:0;
+ }
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;
diff --git a/tests/unit/CaptureColorContractTests.cpp b/tests/unit/CaptureColorContractTests.cpp
index 401de592..4729f8cf 100644
--- a/tests/unit/CaptureColorContractTests.cpp
+++ b/tests/unit/CaptureColorContractTests.cpp
@@ -72,5 +72,22 @@ int main(){
frame=av_frame_alloc();frame->format=AV_PIX_FMT_NV12;frame->width=4;frame->height=4;av_frame_get_buffer(frame,32);raw.assign(36,0xee);for(int y=0;y<6;++y)for(int x=0;x<4;++x)raw[y*6+x]=uint8_t(y*10+x);
check(source::copyCaptureSample(layout,raw.data(),raw.size(),*frame)&&frame->data[1][0]==40&&frame->data[1][frame->linesize[1]]==50,"NV12 UV offset respects input stride");av_frame_free(&frame);
type.subtype=MEDIASUBTYPE_RGB32;vi.bmiHeader.biHeight=2;vi.bmiHeader.biSizeImage=32;check(source::captureMediaLayout(type,layout)&&layout.bottomUp&&layout.rowBytes==16,"RGB DIB keeps bottom-up compatibility");
+ WAVEFORMATEX wave{};wave.wFormatTag=WAVE_FORMAT_PCM;wave.nChannels=2;wave.nSamplesPerSec=48000;wave.wBitsPerSample=16;wave.nBlockAlign=4;wave.nAvgBytesPerSec=192000;
+ AM_MEDIA_TYPE audio{};audio.majortype=MEDIATYPE_Audio;audio.subtype=MEDIASUBTYPE_PCM;audio.formattype=FORMAT_WaveFormatEx;audio.cbFormat=sizeof(wave);audio.pbFormat=reinterpret_cast<BYTE*>(&wave);
+ output.Attach(new OutputPin);unsigned audioReceived=0;
+ check(SUCCEEDED(source::createNativeAudioSink(audio,[&](IMediaSample*){++audioReceived;return S_OK;},filter,input)),"create shared native PCM terminal");
+ check(filter&&SUCCEEDED(filter.As(&memory))&&input->ReceiveConnection(output.Get(),&audio)==S_OK,"PCM format is accepted explicitly");
+ wave.nSamplesPerSec=44100;wave.nAvgBytesPerSec=176400;check(input->QueryAccept(&audio)==S_FALSE,"audio rate change requires reconnect");wave.nSamplesPerSec=48000;wave.nAvgBytesPerSec=192000;
+ ALLOCATOR_PROPERTIES audioWanted{},audioActual{};
+ check(memory->GetAllocatorRequirements(&audioWanted)==S_OK&&audioWanted.cbBuffer==4,"audio allocator retains frame alignment after connection");
+ audioWanted.cbBuffer=1920;
+ bool audioReady=memory->GetAllocator(&allocator)==S_OK&&allocator->SetProperties(&audioWanted,&audioActual)==S_OK&&allocator->Commit()==S_OK;
+ check(audioReady,"PCM allocator initialized");
+ if(audioReady){ComPtr<IMediaSample> sample;allocator->GetBuffer(&sample,nullptr,nullptr,0);sample->SetActualDataLength(1920);filter->Run(0);
+ check(memory->Receive(sample.Get())==S_OK&&audioReceived==1,"variable length aligned PCM delivered");
+ sample->SetActualDataLength(1919);check(FAILED(memory->Receive(sample.Get()))&&audioReceived==1,"partial PCM sample is rejected");
+ filter->Stop();sample.Reset();allocator->Decommit();input->Disconnect();
+ }
+ memory.Reset();input.Reset();filter.Reset();output.Reset();allocator.Reset();
CoUninitialize();std::cout<<"failures="<<failures<<'\n';return failures?1:0;
}
diff --git a/tests/unit/PresentationWorkerTests.cpp b/tests/unit/PresentationWorkerTests.cpp
index 9a361a79..57d58c57 100644
--- a/tests/unit/PresentationWorkerTests.cpp
+++ b/tests/unit/PresentationWorkerTests.cpp
@@ -16,6 +16,11 @@ int main(){
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();
+ std::atomic<bool> observed=false;std::promise<void> waiting;auto waitingFuture=waiting.get_future();
+ check(worker.push([&](const auto& cancelled){waiting.set_value();while(!observed&&!cancelled())std::this_thread::sleep_for(1ms);return true;}),"hold presenter behind independently completed work");
+ check(waitingFuture.wait_for(1s)==std::future_status::ready&&worker.push([](const auto&){return true;}),"fill bounded queue during presentation deadline");
+ check(worker.waitForSlot([&]{check(worker.occupancy()==2,"completion polling runs outside queue mutex");observed=true;})&&observed,"backpressure observes completion before presenter releases slot");
+ worker.cancelAndDrain();
check(worker.push([](const auto&){return false;}),"inject presentation failure");
auto deadline=std::chrono::steady_clock::now()+1s;while(!worker.failed()&&std::chrono::steady_clock::now()<deadline)std::this_thread::sleep_for(1ms);
check(worker.failed()&&!worker.waitForSlot(),"failure propagates without blocking producer");
diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cpp
index 41386452..64be9a74 100644
--- a/tests/unit/RepairContractTests.cpp
+++ b/tests/unit/RepairContractTests.cpp
@@ -48,10 +48,41 @@ int main(){
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);
+ oldWindow.ready(1,true,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");
+ engine::FrameFlowWindow rates(1,{1,1,1},0);
+ for(unsigned i=1;i<=60;++i){rates.ready(i,true,i<=40?1:0,0,i*100000);rates.presented(false,i,i*100000);if(i<=30)rates.presented(true,i,i*100000);}
+ rates.ready(60,true,3,0,7000000);
+ const auto counted=rates.snapshot(10000000);
+ check(counted.sourceCompletedFps==60&&counted.outputCompletedFps==100&&counted.validGeneratedFps==40&&counted.presentSubmitFps==90,"real60 plus valid40 yields output100 but present90; duplicate completion ignored");
+ check(counted.counters.realReady==60&&counted.counters.fgReadyValid==40,"GPU-ready counts are independent of requested multiplier");
+ rates.xessSubmitted(2,1,10000000);rates.xessSubmitted(1,0,10000000);
+ check(rates.snapshot(10000000).xessSdkSubmitFps==3&&rates.snapshot(10000000).outputCompletedFps==100,"XeSS SDK submissions never enter measured GPU completions");
+ rates.latency(10100000,10300000);rates.latency(10200000,10600000);
+ const auto times=rates.snapshot(13000000);
+ check(times.softwareLatencyMs==30&&times.softwareLatencyP95Ms==40&&times.latencySamples==2,"software latency measures same-frame endpoints and nearest-rank P95");
+ const auto stale=rates.snapshot(23000000);
+ check(!stale.softwareLatencyMs&&stale.outputCompletedFps==0&&stale.xessSdkSubmitFps==0,"stalled stream expires rates and latency samples");
+ engine::FrameFlowWindow thousand(1,{1,1,1},0);
+ for(unsigned i=1;i<=1000;++i)thousand.ready(i,true,0,0,i*10000);
+ check(thousand.snapshot(10000000).outputCompletedFps==1000,"completion accounting supports measured 1000fps without a 60fps clamp");
+ auto sharedRates=std::make_shared<engine::FrameCompletionRates>(0);
+ engine::FrameFlowWindow epochA(1,{1,1,1},0,sharedRates),epochB(1,{2,1,2},5000000,sharedRates);
+ epochA.ready(1,true,1,0,1000000);epochB.ready(1,true,1,0,6000000);
+ const auto acrossDrop=epochB.snapshot(10000000);
+ check(acrossDrop.outputCompletedFps==4&&acrossDrop.rateWindowReady&&acrossDrop.counters.realReady==1,"drop resets retain revision throughput without merging epoch counters");
+ engine::FrameFlowWindow newRevision(1,{3,2,3},6000000);
+ check(newRevision.snapshot(10000000).outputCompletedFps==0&&!newRevision.snapshot(10000000).rateWindowReady,"new settings revision has an independent rate window");
+ engine::FrameFlowWindow stageMetrics(1,{1,1,1},0);
+ stageMetrics.cpu(diagnostics::CpuStage::Present,10,1000000);stageMetrics.cpu(diagnostics::CpuStage::Present,30,2000000);
+ std::array<diagnostics::GpuSample,size_t(diagnostics::GpuStage::Count)> gpuSamples{};
+ gpuSamples[0]={diagnostics::SampleState::Measured,12,100,200,1000};stageMetrics.gpu(gpuSamples,2000000);stageMetrics.gpu(gpuSamples,3000000);
+ const auto timing=stageMetrics.snapshot(4000000);
+ check(timing.cpuTiming[size_t(diagnostics::CpuStage::Present)].mean==20&&timing.cpuTiming[size_t(diagnostics::CpuStage::Present)].p95==30&&timing.gpuTiming[0].samples==1,"stage window averages actual samples and deduplicates GPU timestamps");
+ const auto expiredTiming=stageMetrics.snapshot(14000000);
+ check(!expiredTiming.cpuTiming[size_t(diagnostics::CpuStage::Present)].mean&&!expiredTiming.gpuTiming[0].mean,"expired stage samples become unmeasured rather than stale zero");
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");
diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cpp
index b8754e63..b9ee6232 100644
--- a/tests/unit/RepairPresetTests.cpp
+++ b/tests/unit/RepairPresetTests.cpp
@@ -3,6 +3,7 @@
#include <fstream>
int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engine;const std::filesystem::path p=argv[1];PresetStore a(p);bool ok=a.load();EnhancementSettings s;s.videoSrQuality=2;s.frameGenerationBackend=FrameGenerationBackend::Fruc;s.opticalFlowBackend=OpticalFlowBackend::AmdFidelityFx;s.amdFlowHalfResolution=true;s.protection.enabled=true;s.protection.featherPixels=3.5f;s.protection.regions[0]={.1f,.2f,.7f,.8f};s.protection.regions[3]={0,0,1,1};s.model.intensity=.375f;s.model.skin=1.5f;s.residual.darken=1.2f;s.multiplier=4;s.flow=FlowQuality::Quality;s.content=ContentRate::Fps50;s.nrPolicy=veyra::pipeline::NrSizePolicy::Native;
s.srTarget=veyra::pipeline::SrTarget::Uhd8K;
+ s.audioSync=AudioSyncMode::Manual;s.audioOffsetMs=137;
ok=ok&&a.put(L"test",s)&&a.setDefault(0)&&!a.put(L"test",s);PresetStore b(p);ok=ok&&b.load()&&b.defaultSettings()==s&&b.rename(0,L"renamed")&&b.defaultSettings()==s;
auto badTarget=s;badTarget.srTarget=static_cast<veyra::pipeline::SrTarget>(3);ok=ok&&!b.put(L"invalid target",badTarget);
auto xess=s;xess.frameGenerationBackend=FrameGenerationBackend::XeSS;ok=ok&&!b.put(L"XeSS 4X rejected",xess);