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

checkpoint: preserve repair v2 and approved dual-mode UI plan

Veyra Goal Agentddc515da990d
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d9e7e947..d2d1eb2a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -37,6 +37,7 @@ add_library(veyra_base STATIC
src/base/FileIdentity.cpp
)
veyra_apply_warnings(veyra_base)
+target_compile_options(veyra_base PUBLIC /utf-8)
target_compile_features(veyra_base PUBLIC cxx_std_20)
target_compile_definitions(veyra_base PUBLIC
UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -149,6 +150,9 @@ veyra_add_compute_shader(veyra_shader_nv12_upload Nv12Upload)
veyra_add_graphics_shader_pair(veyra_shader_present_blit PresentBlit)
# NvofDensify: SHORT2 S10.5 raw flow -> workingExtent float2 + confidence.
veyra_add_compute_shader(veyra_shader_nvof_densify NvofDensify)
+veyra_add_compute_shader(veyra_shader_nr_downsample NrDownsample)
+veyra_add_compute_shader(veyra_shader_nr_residual NrResidualComposite)
+veyra_add_compute_shader(veyra_shader_flow_adapt FlowAdapt)
veyra_add_compute_shader(veyra_shader_rgb_nv12 RgbToNv12)
# ---------------------------------------------------------------------------
@@ -371,6 +375,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
# veyra_sources: product input sources (Playbook R3/R7). MediaFileSource
# composes veyra_media; no second decode implementation exists.
+ add_dependencies(veyra_pipeline veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_flow_adapt)
add_library(veyra_sources STATIC
src/source/MediaFileSource.cpp
src/source/CaptureCardSource.cpp
@@ -395,13 +400,47 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_include_directories(veyra_source_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(veyra_source_tests PRIVATE veyra_sources)
+ add_executable(veyra_capture_tests tests/integration/CaptureSourceTests.cpp)
+ target_compile_features(veyra_capture_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_capture_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
+ target_link_libraries(veyra_capture_tests PRIVATE veyra_sources)
+
+ add_executable(veyra_live_timing_tests tests/unit/LivePresentationTimingTests.cpp)
+ target_compile_features(veyra_live_timing_tests PRIVATE cxx_std_20)
+ target_include_directories(veyra_live_timing_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
+
+ add_executable(veyra_repair_contract_tests tests/unit/RepairContractTests.cpp)
+ target_link_libraries(veyra_repair_contract_tests PRIVATE veyra_base)
+ target_compile_features(veyra_repair_contract_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_repair_contract_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_include_directories(veyra_repair_contract_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
+
+ add_executable(veyra_repair_parameter_tests tests/integration/RepairParameterTests.cpp)
+ target_compile_features(veyra_repair_parameter_tests PRIVATE cxx_std_20)
+ target_include_directories(veyra_repair_parameter_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
+ target_compile_definitions(veyra_repair_parameter_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
+ target_link_libraries(veyra_repair_parameter_tests PRIVATE veyra_pipeline veyra_sinks veyra_nvof)
+ add_executable(veyra_repair_fg_tests tests/integration/RepairFgTests.cpp)
+ add_executable(veyra_repair_shader_tests tests/integration/RepairShaderTests.cpp)
+ target_compile_features(veyra_repair_shader_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_repair_shader_tests PRIVATE veyra_pipeline)
+ target_include_directories(veyra_repair_fg_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
+ target_compile_features(veyra_repair_fg_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_repair_fg_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
+ target_link_libraries(veyra_repair_fg_tests PRIVATE veyra_pipeline veyra_sinks veyra_nvof)
+
# Headless quality-core runner (Playbook R3.3): the phase5 gate's quality
- add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/Subtitles.cpp)
+ add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/Subtitles.cpp)
target_compile_features(veyra_engine PUBLIC cxx_std_20)
target_compile_options(veyra_engine PRIVATE /utf-8)
target_compile_definitions(veyra_engine PUBLIC VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}" VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")
target_link_libraries(veyra_engine PUBLIC veyra_pipeline veyra_sources veyra_sinks veyra_ngx veyra_nvof)
- add_executable(veyra WIN32 apps/veyra/main.cpp)
+ add_executable(veyra_repair_preset_tests tests/unit/RepairPresetTests.cpp src/engine/PresetStore.cpp)
+ target_compile_features(veyra_repair_preset_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_repair_preset_tests PRIVATE /utf-8)
+ target_compile_definitions(veyra_repair_preset_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_include_directories(veyra_repair_preset_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
+ add_executable(veyra WIN32 apps/veyra/main.cpp apps/veyra/SettingsWindow.cpp apps/veyra/TelemetryWindow.cpp)
target_compile_features(veyra PRIVATE cxx_std_20)
target_compile_options(veyra PRIVATE /utf-8)
target_link_libraries(veyra PRIVATE veyra_engine comctl32 comdlg32 shell32)
diff --git a/apps/veyra/DpiWindow.h b/apps/veyra/DpiWindow.h
new file mode 100644
index 00000000..4f06e8d3
--- /dev/null
+++ b/apps/veyra/DpiWindow.h
@@ -0,0 +1,9 @@
+#pragma once
+#include <windows.h>
+namespace veyra::ui {
+inline void changeDpi(HWND window,WPARAM wp,LPARAM lp,unsigned& dpi,HFONT& font){
+ const unsigned next=HIWORD(wp);struct Scale{unsigned oldDpi,newDpi;HWND parent;};Scale scale{dpi,next,window};
+ EnumChildWindows(window,[](HWND child,LPARAM value)->BOOL{auto& s=*reinterpret_cast<Scale*>(value);RECT r{};GetWindowRect(child,&r);MapWindowPoints(nullptr,s.parent,reinterpret_cast<POINT*>(&r),2);MoveWindow(child,MulDiv(r.left,s.newDpi,s.oldDpi),MulDiv(r.top,s.newDpi,s.oldDpi),MulDiv(r.right-r.left,s.newDpi,s.oldDpi),MulDiv(r.bottom-r.top,s.newDpi,s.oldDpi),TRUE);return TRUE;},reinterpret_cast<LPARAM>(&scale));
+ auto oldFont=font;font=CreateFontW(-MulDiv(14,next,96),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");EnumChildWindows(window,[](HWND child,LPARAM value)->BOOL{SendMessageW(child,WM_SETFONT,WPARAM(value),TRUE);return TRUE;},LPARAM(font));DeleteObject(oldFont);dpi=next;auto* r=reinterpret_cast<RECT*>(lp);SetWindowPos(window,nullptr,r->left,r->top,r->right-r->left,r->bottom-r->top,SWP_NOZORDER|SWP_NOACTIVATE);
+}
+}
diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cpp
new file mode 100644
index 00000000..8c04f4bc
--- /dev/null
+++ b/apps/veyra/SettingsWindow.cpp
@@ -0,0 +1,50 @@
+#include "SettingsWindow.h"
+#include "veyra/engine/PresetStore.h"
+#include <filesystem>
+#include "DpiWindow.h"
+#include <sstream>
+#include <iomanip>
+#include <array>
+namespace veyra::ui {
+namespace {
+unsigned windowDpi=96;HWND window=nullptr;engine::EngineController* controller=nullptr;HFONT font=nullptr;
+engine::PresetStore store(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/user-presets.v1");bool loaded=false;
+const wchar_t* labels[]={L"模型强度 [0,1]",L"局部明暗 [0,1]",L"局部结构 [0,1]",L"肤质结构 [-1/0–2](效果未证实)",L"风格 [0,2整数](实验)",L"自动遮罩 [0/1](实验)",L"画面内UI修正 [0/1](效果未证实)",L"总变化强度 [0,2]",L"暗化变化 [0,2]",L"亮化变化 [0,2]",L"色彩变化 [0,2]",L"明度变化 [0,2]"};
+void loadStore(){if(!loaded){store.load();loaded=true;}}
+void message(const std::wstring& text){SetDlgItemTextW(window,401,text.c_str());}
+void populate(engine::EnhancementSettings s){float v[]={s.model.intensity,s.model.tone,s.model.structure,s.model.skin,float(s.model.style),float(s.model.autoMask),float(s.model.uiCorrection),s.residual.total,s.residual.darken,s.residual.brighten,s.residual.color,s.residual.luminance};for(int i=0;i<12;++i){std::wostringstream o;o<<std::setprecision(7)<<v[i];SetDlgItemTextW(window,100+i,o.str().c_str());}CheckDlgButton(window,200,s.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(window,201,s.sr?BST_CHECKED:BST_UNCHECKED);SendDlgItemMessageW(window,202,CB_SETCURSEL,s.multiplier-1,0);SendDlgItemMessageW(window,203,CB_SETCURSEL,int(s.nrPolicy),0);SendDlgItemMessageW(window,204,CB_SETCURSEL,int(s.flow),0);SendDlgItemMessageW(window,205,CB_SETCURSEL,int(s.content),0);}
+bool read(engine::EnhancementSettings& s){s=controller->snapshot().desired;float v[12]{};for(int i=0;i<12;++i){wchar_t b[64]{};GetDlgItemTextW(window,100+i,b,64);wchar_t* end=nullptr;v[i]=wcstof(b,&end);if(end==b||*end||!std::isfinite(v[i])){message(L"请输入完整的有限数值;未提交设置");return false;}}
+ for(int i=4;i<7;++i)if(v[i]!=std::floor(v[i])||v[i]<0||v[i]>(i==4?2:1)){message(L"风格/遮罩/UI修正必须为整数");return false;}
+ s.model={v[0],v[1],v[2],v[3],int(v[4]),int(v[5]),int(v[6])};s.residual={v[7],v[8],v[9],v[10],v[11]};s.nr=IsDlgButtonChecked(window,200)==BST_CHECKED;s.sr=IsDlgButtonChecked(window,201)==BST_CHECKED;s.multiplier=uint32_t(SendDlgItemMessageW(window,202,CB_GETCURSEL,0,0)+1);s.nrPolicy=static_cast<pipeline::NrSizePolicy>(SendDlgItemMessageW(window,203,CB_GETCURSEL,0,0));s.flow=static_cast<engine::FlowQuality>(SendDlgItemMessageW(window,204,CB_GETCURSEL,0,0));s.content=static_cast<engine::ContentRate>(SendDlgItemMessageW(window,205,CB_GETCURSEL,0,0));if(!s.validate().empty()){message(L"参数超出显示范围,整套设置未提交");return false;}return true;}
+void refreshPresets(){auto list=GetDlgItem(window,300);SendMessageW(list,CB_RESETCONTENT,0,0);for(auto& p:store.entries())SendMessageW(list,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(p.name.c_str()));if(!store.entries().empty())SendMessageW(list,CB_SETCURSEL,0,0);}
+LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
+case WM_CREATE:{window=h;const auto dpi=GetDpiForWindow(h);windowDpi=dpi;font=CreateFontW(-MulDiv(15,dpi,96),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");
+ auto add=[&](const wchar_t* cls,const wchar_t* text,int id,DWORD style,int x,int y,int w,int height){auto c=CreateWindowExW(cls==std::wstring(L"EDIT")?WS_EX_CLIENTEDGE:0,cls,text,WS_CHILD|WS_VISIBLE|style,MulDiv(x,dpi,96),MulDiv(y,dpi,96),MulDiv(w,dpi,96),MulDiv(height,dpi,96),h,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);return c;};
+ for(int i=0;i<12;++i){add(L"STATIC",labels[i],0,0,12,12+i*29,290,24);add(L"EDIT",L"",100+i,ES_AUTOHSCROLL|WS_TABSTOP,307,10+i*29,90,25);}
+ add(L"BUTTON",L"启用DLSS5 NR",200,BS_AUTOCHECKBOX,420,12,190,25);add(L"BUTTON",L"SR输出4K底图",201,BS_AUTOCHECKBOX,420,42,190,25);
+ auto combo=[&](int id,int y,std::initializer_list<const wchar_t*> names){auto c=add(L"COMBOBOX",L"",id,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,420,y,260,180);for(auto n:names)SendMessageW(c,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(n));};
+ combo(202,78,{L"关闭补帧",L"DLSSG 2X",L"DLSSG 3X(需硬件支持)",L"DLSSG 4X(需硬件支持)"});combo(203,114,{L"实时NR:约1080内部处理",L"原生NR:性能成本较高"});combo(204,150,{L"光流:性能",L"光流:平衡",L"光流:质量"});combo(205,186,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏"});
+ add(L"BUTTON",L"整套应用",210,BS_PUSHBUTTON|WS_TABSTOP,420,226,125,30);add(L"BUTTON",L"恢复内建默认",211,BS_PUSHBUTTON,552,226,128,30);
+ add(L"STATIC",L"实验参数沿用本地Feature18键;并非NVIDIA官方预设。\n实际效果需逐项验证。导出冻结启动时快照。",0,0,420,270,265,72);
+ add(L"COMBOBOX",L"",300,CBS_DROPDOWNLIST|WS_VSCROLL,12,375,300,180);add(L"EDIT",L"新预设",301,ES_AUTOHSCROLL,325,375,355,26);
+ const wchar_t* buttons[]={L"载入预设",L"新建",L"复制当前",L"重命名",L"删除",L"设为默认"};for(int i=0;i<6;++i)add(L"BUTTON",buttons[i],310+i,BS_PUSHBUTTON,12+i*113,413,108,30);
+ add(L"STATIC",L"",400,0,12,455,668,65);add(L"STATIC",L"",401,0,12,525,668,70);loadStore();refreshPresets();populate(controller->snapshot().desired);message(store.error());SetTimer(h,1,250,nullptr);return 0;}
+case WM_COMMAND:{const int id=LOWORD(wp);engine::EnhancementSettings s;wchar_t name[128]{};GetDlgItemTextW(h,301,name,128);const auto index=size_t(SendDlgItemMessageW(h,300,CB_GETCURSEL,0,0));bool ok=true;
+ if(id==210){if(read(s)&&controller->requestSettings(s))message(L"设置已请求;在真实帧边界确认Applied后生效");}
+ else if(id==211){s={};populate(s);controller->requestSettings(s);message(L"已请求恢复内建默认;用户预设保留");}
+ else if(id==310&&index<store.entries().size()){s=store.entries()[index].settings;populate(s);controller->requestSettings(s);}
+ else if(id==311){ok=store.put(name,{});refreshPresets();}
+ else if(id==312){if(read(s))ok=store.put(name,s);refreshPresets();}
+ else if(id==313){ok=store.rename(index,name);refreshPresets();}
+ else if(id==314){ok=store.erase(index);refreshPresets();}
+ else if(id==315)ok=store.setDefault(index);
+ if(!ok)message(store.error());return 0;}
+case WM_TIMER:{auto s=controller->snapshot();std::wostringstream o;o<<L"期望版本 "<<s.desired.revision<<L" / 已应用版本 "<<s.applied.revision<<(s.applying?L"(应用中)":L"")<<L"\n已应用:强度 "<<s.applied.model.intensity<<L" / 明暗 "<<s.applied.model.tone<<L" / 结构 "<<s.applied.model.structure<<L" / 变化量 "<<s.applied.residual.total<<L" / 倍率 "<<s.applied.multiplier<<L"\n"<<s.status;SetDlgItemTextW(h,400,o.str().c_str());return 0;}
+case WM_DPICHANGED:changeDpi(h,wp,lp,windowDpi,font);return 0;
+case WM_CLOSE:DestroyWindow(h);return 0;
+case WM_DESTROY:KillTimer(h,1);DeleteObject(font);window=nullptr;return 0;
+}return DefWindowProcW(h,msg,wp,lp);}
+}
+engine::EnhancementSettings defaultSettings(){loadStore();return store.defaultSettings();}
+void showSettings(HWND parent,engine::EngineController& engine){controller=&engine;if(window){SetForegroundWindow(window);return;}WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraSettings";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);auto dpi=GetDpiForWindow(parent);CreateWindowExW(0,wc.lpszClassName,L"参数与用户预设",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,MulDiv(720,dpi,96),MulDiv(645,dpi,96),parent,nullptr,wc.hInstance,nullptr);}
+}
diff --git a/apps/veyra/SettingsWindow.h b/apps/veyra/SettingsWindow.h
new file mode 100644
index 00000000..bd5bb513
--- /dev/null
+++ b/apps/veyra/SettingsWindow.h
@@ -0,0 +1,4 @@
+#pragma once
+#include <windows.h>
+#include "veyra/engine/EngineController.h"
+namespace veyra::ui { void showSettings(HWND,engine::EngineController&);engine::EnhancementSettings defaultSettings(); }
diff --git a/apps/veyra/TelemetryWindow.cpp b/apps/veyra/TelemetryWindow.cpp
new file mode 100644
index 00000000..9255728d
--- /dev/null
+++ b/apps/veyra/TelemetryWindow.cpp
@@ -0,0 +1,31 @@
+#include "TelemetryWindow.h"
+#include "veyra/Log.h"
+#include <shellapi.h>
+#include <filesystem>
+#include "DpiWindow.h"
+#include <sstream>
+#include <iomanip>
+namespace veyra::ui {
+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;
+ 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"质量";
+ o<<L"光流请求:"<<flowName<<L";实际SDK perf="<<s.flowPerf<<L";grid=4(已验证SDK能力)\r\n内容节奏:"<<(s.contentFps?std::to_wstring(s.contentFps)+L"fps":L"未确认(静态或证据不足)")<<L";保留源时间戳,重复内容不计有效生成\r\n"<<s.status;
+ SetDlgItemTextW(window,1,o.str().c_str());
+}
+LRESULT CALLBACK proc(HWND h,UINT m,WPARAM w,LPARAM l){switch(m){case WM_CREATE:{preview.clear();window=h;auto dpi=GetDpiForWindow(h);windowDpi=dpi;font=CreateFontW(-MulDiv(14,dpi,96),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");auto add=[&](const wchar_t* c,const wchar_t* t,int id,DWORD style,int y,int height){auto child=CreateWindowExW(WS_EX_CLIENTEDGE,c,t,WS_CHILD|WS_VISIBLE|style,10,MulDiv(y,dpi,96),MulDiv(820,dpi,96),MulDiv(height,dpi,96),h,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(child,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);};
+ add(L"EDIT",L"",1,ES_MULTILINE|ES_READONLY|WS_VSCROLL,10,340);add(L"BUTTON",L"查看 / 刷新脱敏诊断预览",3,BS_PUSHBUTTON,360,28);add(L"EDIT",L"点击上方按钮查看诊断。复制只会复制这里预览过的脱敏文字。",2,ES_MULTILINE|ES_READONLY|WS_VSCROLL,398,150);add(L"BUTTON",L"复制上方脱敏预览",4,BS_PUSHBUTTON,558,28);add(L"BUTTON",L"打开本应用日志目录",5,BS_PUSHBUTTON,596,28);SetTimer(h,1,250,nullptr);refresh();return 0;}
+case WM_TIMER:refresh();return 0;
+case WM_COMMAND:if(LOWORD(w)==3){preview=wide(Logger::instance().diagnosticReport());SetDlgItemTextW(h,2,preview.c_str());}else if(LOWORD(w)==4&&!preview.empty()){
+ if(OpenClipboard(h)){HGLOBAL data=GlobalAlloc(GMEM_MOVEABLE,(preview.size()+1)*sizeof(wchar_t));if(data){if(void* p=GlobalLock(data)){memcpy(p,preview.c_str(),(preview.size()+1)*sizeof(wchar_t));GlobalUnlock(data);EmptyClipboard();if(!SetClipboardData(CF_UNICODETEXT,data))GlobalFree(data);}else GlobalFree(data);}CloseClipboard();}
+}else if(LOWORD(w)==5)ShellExecuteW(h,L"open",(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs").c_str(),nullptr,nullptr,SW_SHOW);return 0;
+case WM_DPICHANGED:changeDpi(h,w,l,windowDpi,font);return 0;
+case WM_CLOSE:DestroyWindow(h);return 0;case WM_DESTROY:KillTimer(h,1);DeleteObject(font);window=nullptr;return 0;}return DefWindowProcW(h,m,w,l);}
+}
+void showTelemetry(HWND parent,engine::EngineController& controller){engine=&controller;if(window){SetForegroundWindow(window);return;}WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraTelemetry";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);RegisterClassW(&wc);auto dpi=GetDpiForWindow(parent);CreateWindowExW(0,wc.lpszClassName,L"性能与诊断中心",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,MulDiv(860,dpi,96),MulDiv(675,dpi,96),parent,nullptr,wc.hInstance,nullptr);}
+}
diff --git a/apps/veyra/TelemetryWindow.h b/apps/veyra/TelemetryWindow.h
new file mode 100644
index 00000000..b167b48c
--- /dev/null
+++ b/apps/veyra/TelemetryWindow.h
@@ -0,0 +1,4 @@
+#pragma once
+#include <windows.h>
+#include "veyra/engine/EngineController.h"
+namespace veyra::ui {void showTelemetry(HWND,engine::EngineController&);}
diff --git a/apps/veyra/main.cpp b/apps/veyra/main.cpp
index ddd583a0..8655f9ca 100644
--- a/apps/veyra/main.cpp
+++ b/apps/veyra/main.cpp
@@ -1,4 +1,6 @@
#include <windows.h>
+#include "SettingsWindow.h"
+#include "TelemetryWindow.h"
#include <objbase.h>
#include <commctrl.h>
#include <commdlg.h>
@@ -13,76 +15,141 @@
#include "veyra/Log.h"
#include "veyra/engine/Subtitles.h"
namespace {
-enum {Open=101,Play,Stop,Save,Nr,Sr,Fg,Seek,Info,Capture,Export,Realtime,Recent};
+enum {Open=101,Play,Stop,Save,Nr,Sr,Fg,Seek,Info,Capture,Export,Realtime,Recent,Multiplier,Settings,OriginalHold,CompareToggle,Split,Reference,Fullscreen,VideoSurface=1000};
veyra::engine::EngineController engine;
+struct ToolbarItem{HWND hwnd;int width;};std::vector<ToolbarItem> toolbar;
+bool full=false,holdOriginal=false,referenceBase=false;int compareMode=0;float compareSplit=.5f;WINDOWPLACEMENT windowPlacement{sizeof(windowPlacement)};
HWND mainWindow=nullptr,video=nullptr,statusBar=nullptr,seekBar=nullptr;
-std::wstring currentFile,autoInput;bool paused=false,dragging=false;int smokeSeconds=0;ULONGLONG startTick=0;int resultCode=0;
+std::wstring currentFile,autoInput;bool paused=false,dragging=false,closing=false;int smokeSeconds=0;ULONGLONG startTick=0;int resultCode=0;
std::wstring exportOutput;unsigned exportFrames=0;unsigned cancelAfterMs=0;bool exportHevc=false;veyra::engine::PlayerOptions initialOptions;
std::vector<veyra::engine::SubtitleCue> subtitles;HWND subtitleLabel=nullptr;
-HFONT font=nullptr;bool smokeControls=false;int smokeStep=0;std::wstring smokeSave;
+HFONT font=nullptr;bool smokeRollback=false,smokeRollbackFlow=false,smokeUi=false;int uiStep=0;bool smokeSettings=false;int settingsStep=0;bool smokeControls=false;int smokeStep=0;std::wstring smokeSave;
HWND captureWindow=nullptr,captureDevice=nullptr,captureFormat=nullptr,captureAudio=nullptr;
std::vector<veyra::source::CaptureFormat> captureFormats;
void openFile(const std::wstring&);
+void layout();
+void updateComparison(){engine.comparison(holdOriginal?1:compareMode,referenceBase,compareSplit);}
+void toggleFullscreen(){full=!full;if(full){GetWindowPlacement(mainWindow,&windowPlacement);SetWindowLongPtrW(mainWindow,GWL_STYLE,WS_POPUP|WS_VISIBLE);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromWindow(mainWindow,MONITOR_DEFAULTTONEAREST),&mi);SetWindowPos(mainWindow,HWND_TOP,mi.rcMonitor.left,mi.rcMonitor.top,mi.rcMonitor.right-mi.rcMonitor.left,mi.rcMonitor.bottom-mi.rcMonitor.top,SWP_FRAMECHANGED);}else{SetWindowLongPtrW(mainWindow,GWL_STYLE,WS_OVERLAPPEDWINDOW|WS_VISIBLE);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromRect(&windowPlacement.rcNormalPosition,MONITOR_DEFAULTTONEAREST),&mi);auto& r=windowPlacement.rcNormalPosition;if(r.right<mi.rcWork.left||r.left>mi.rcWork.right||r.bottom<mi.rcWork.top||r.top>mi.rcWork.bottom){OffsetRect(&r,mi.rcWork.left-r.left,mi.rcWork.top-r.top);}SetWindowPlacement(mainWindow,&windowPlacement);SetWindowPos(mainWindow,nullptr,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);}SetWindowTextW(GetDlgItem(mainWindow,Fullscreen),full?L"退出全屏":L"全屏 F11");layout();}
+LRESULT CALLBACK interaction(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR id,DWORD_PTR){
+ if(id==OriginalHold){if(m==WM_LBUTTONDOWN){holdOriginal=true;SetCapture(h);updateComparison();return 0;}if(m==WM_LBUTTONUP||m==WM_CAPTURECHANGED){holdOriginal=false;if(GetCapture()==h)ReleaseCapture();updateComparison();return 0;}}
+ if(id==VideoSurface&&compareMode==2&&(m==WM_LBUTTONDOWN||m==WM_MOUSEMOVE)&&(m==WM_LBUTTONDOWN||(w&MK_LBUTTON))){if(m==WM_LBUTTONDOWN)SetCapture(h);RECT r{};GetClientRect(h,&r);compareSplit=std::clamp(float(short(LOWORD(l)))/std::max(1L,r.right),0.0f,1.0f);updateComparison();return 0;}
+ if(id==VideoSurface&&m==WM_LBUTTONUP&&GetCapture()==h){ReleaseCapture();return 0;}
+ return DefSubclassProc(h,m,w,l);
+}
void refreshFormats(){SendMessageW(captureFormat,CB_RESETCONTENT,0,0);int i=int(SendMessageW(captureDevice,CB_GETCURSEL,0,0));captureFormats=i>=0?veyra::source::CaptureCardSource::formats(i):std::vector<veyra::source::CaptureFormat>{};for(auto& f:captureFormats)SendMessageW(captureFormat,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(f.label.c_str()));if(!captureFormats.empty())SendMessageW(captureFormat,CB_SETCURSEL,0,0);}
LRESULT CALLBACK captureProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){if(msg==WM_CREATE){auto add=[&](const wchar_t* cls,const wchar_t* text,int id,DWORD style,int y){return CreateWindowExW(0,cls,text,WS_CHILD|WS_VISIBLE|style,12,y,510,200,hwnd,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);};
captureDevice=add(L"COMBOBOX",L"",1,CBS_DROPDOWNLIST|WS_VSCROLL,15);captureFormat=add(L"COMBOBOX",L"",2,CBS_DROPDOWNLIST|WS_VSCROLL,55);captureAudio=add(L"COMBOBOX",L"",3,CBS_DROPDOWNLIST|WS_VSCROLL,95);
-auto devices=veyra::source::CaptureCardSource::devices();for(auto& name:devices)SendMessageW(captureDevice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));if(!devices.empty())SendMessageW(captureDevice,CB_SETCURSEL,0,0);else SendMessageW(captureDevice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(L"No capture device found — connect card and reopen"));
-SendMessageW(captureAudio,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(L"No audio (select HDMI input below to monitor audio)"));for(auto& name:veyra::source::CaptureCardSource::devices(true))SendMessageW(captureAudio,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));SendMessageW(captureAudio,CB_SETCURSEL,0,0);refreshFormats();
-CreateWindowExW(0,L"STATIC",L"Device / actual format / HDMI audio. NR, SR and FG use the main window settings. Hardware acceptance is pending your test. FG needs one arriving source frame of lookahead.",WS_CHILD|WS_VISIBLE,12,140,510,64,hwnd,nullptr,GetModuleHandleW(nullptr),nullptr);
-CreateWindowExW(0,L"BUTTON",L"Start capture",WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,12,211,180,32,hwnd,reinterpret_cast<HMENU>(4),GetModuleHandleW(nullptr),nullptr);return 0;}
-if(msg==WM_COMMAND){if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE)refreshFormats();if(LOWORD(wp)==4){int d=int(SendMessageW(captureDevice,CB_GETCURSEL,0,0)),f=int(SendMessageW(captureFormat,CB_GETCURSEL,0,0)),a=int(SendMessageW(captureAudio,CB_GETCURSEL,0,0))-1;if(d>=0&&f>=0&&size_t(f)<captureFormats.size()){openFile(std::format(L"capture:{}:{}:{}",d,captureFormats[f].index,a));DestroyWindow(hwnd);}else MessageBoxW(hwnd,L"No supported 1080p/4K 30/60 format selected.",L"Capture",MB_OK);}return 0;}if(msg==WM_DESTROY){captureWindow=nullptr;return 0;}return DefWindowProcW(hwnd,msg,wp,lp);}
-void showCapture(){if(captureWindow){SetForegroundWindow(captureWindow);return;}WNDCLASSW wc{};wc.lpfnWndProc=captureProc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraCaptureSetup";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);captureWindow=CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"Capture card setup",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,550,295,mainWindow,nullptr,wc.hInstance,nullptr);}
-veyra::engine::PlayerOptions options(){return {IsDlgButtonChecked(mainWindow,Nr)==BST_CHECKED,IsDlgButtonChecked(mainWindow,Sr)==BST_CHECKED,IsDlgButtonChecked(mainWindow,Fg)==BST_CHECKED,IsDlgButtonChecked(mainWindow,Realtime)==BST_CHECKED};}
+auto devices=veyra::source::CaptureCardSource::devices();for(auto& name:devices)SendMessageW(captureDevice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));if(!devices.empty())SendMessageW(captureDevice,CB_SETCURSEL,0,0);else SendMessageW(captureDevice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(L"未找到采集设备,请连接后重新打开"));
+SendMessageW(captureAudio,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(L"不监听音频(可选择下方HDMI音频输入)"));for(auto& name:veyra::source::CaptureCardSource::devices(true))SendMessageW(captureAudio,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));SendMessageW(captureAudio,CB_SETCURSEL,0,0);refreshFormats();
+CreateWindowExW(0,L"STATIC",L"设备 / 实际格式 / HDMI音频。增强采用主界面设置。实卡验收由用户完成;补帧必须等待下一张源帧到达。",WS_CHILD|WS_VISIBLE,12,140,510,64,hwnd,nullptr,GetModuleHandleW(nullptr),nullptr);
+CreateWindowExW(0,L"BUTTON",L"开始采集",WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,12,211,180,32,hwnd,reinterpret_cast<HMENU>(4),GetModuleHandleW(nullptr),nullptr);return 0;}
+if(msg==WM_COMMAND){if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE)refreshFormats();if(LOWORD(wp)==4){int d=int(SendMessageW(captureDevice,CB_GETCURSEL,0,0)),f=int(SendMessageW(captureFormat,CB_GETCURSEL,0,0)),a=int(SendMessageW(captureAudio,CB_GETCURSEL,0,0))-1;if(d>=0&&f>=0&&size_t(f)<captureFormats.size()){openFile(std::format(L"capture:{}:{}:{}",d,captureFormats[f].index,a));DestroyWindow(hwnd);}else MessageBoxW(hwnd,L"请选择支持的1080p/4K 30/60格式。",L"采集",MB_OK);}return 0;}if(msg==WM_DESTROY){captureWindow=nullptr;return 0;}return DefWindowProcW(hwnd,msg,wp,lp);}
+void showCapture(){if(captureWindow){SetForegroundWindow(captureWindow);return;}WNDCLASSW wc{};wc.lpfnWndProc=captureProc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraCaptureSetup";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);captureWindow=CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"采集卡设置",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,550,295,mainWindow,nullptr,wc.hInstance,nullptr);}
+veyra::engine::PlayerOptions options(){return veyra::engine::PlayerOptions::from(engine.snapshot().desired);}
+
std::wstring fileDialog(bool save){wchar_t name[32768]{};OPENFILENAMEW ofn{};ofn.lStructSize=sizeof(ofn);ofn.hwndOwner=mainWindow;ofn.lpstrFile=name;ofn.nMaxFile=32768;
-ofn.lpstrFilter=save?L"PNG image\0*.png\0JPEG image\0*.jpg\0":L"Video / image\0*.mp4;*.mkv;*.mov;*.avi;*.ts;*.png;*.jpg;*.jpeg\0All files\0*.*\0";
+ofn.lpstrFilter=save?L"PNG图片\0*.png\0JPEG图片\0*.jpg\0":L"视频 / 图片\0*.mp4;*.mkv;*.mov;*.avi;*.ts;*.png;*.jpg;*.jpeg\0所有文件\0*.*\0";
ofn.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|(save?OFN_OVERWRITEPROMPT:OFN_FILEMUSTEXIST);ofn.lpstrDefExt=save?L"png":nullptr;
return (save?GetSaveFileNameW(&ofn):GetOpenFileNameW(&ofn))?name:L"";}
-void openFile(const std::wstring& file){if(file.empty())return;currentFile=file;subtitles=veyra::engine::loadSrt(std::filesystem::path(file).replace_extension(L".srt").wstring());paused=false;SetWindowTextW(GetDlgItem(mainWindow,Play),L"Pause");engine.open(video,file,options());SetWindowTextW(mainWindow,(L"Veyra — "+std::filesystem::path(file).filename().wstring()).c_str());WritePrivateProfileStringW(L"Player",L"Recent",file.c_str(),(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring().c_str());}
-HWND control(const wchar_t* cls,const wchar_t* label,int id,DWORD style,int x,int y,int w,int h){auto hwnd=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|style,x,y,w,h,mainWindow,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(hwnd,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);return hwnd;}
-void layout(){RECT r{};GetClientRect(mainWindow,&r);MoveWindow(video,8,52,std::max(1L,r.right-16),std::max(1L,r.bottom-160),TRUE);if(subtitleLabel)MoveWindow(subtitleLabel,8,std::max(56L,r.bottom-104),std::max(1L,r.right-16),32,TRUE);MoveWindow(seekBar,8,std::max(56L,r.bottom-71),std::max(1L,r.right-16),24,TRUE);MoveWindow(statusBar,12,std::max(80L,r.bottom-42),std::max(1L,r.right-24),36,TRUE);}
+void openFile(const std::wstring& file){if(file.empty())return;currentFile=file;subtitles=veyra::engine::loadSrt(std::filesystem::path(file).replace_extension(L".srt").wstring());paused=false;SetWindowTextW(GetDlgItem(mainWindow,Play),L"暂停");engine.open(video,file,options());SetWindowTextW(mainWindow,(L"Veyra — "+std::filesystem::path(file).filename().wstring()).c_str());if(smokeSeconds<=0)WritePrivateProfileStringW(L"Player",L"最近打开",file.c_str(),(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring().c_str());}
+HWND control(const wchar_t* cls,const wchar_t* label,int id,DWORD style,int x,int y,int w,int h){auto hwnd=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|style,x,y,w,h,mainWindow,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(hwnd,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);if(id>=Open&&id<=Fullscreen&&id!=Seek)toolbar.push_back({hwnd,w});return hwnd;}
+void layout(){if(!mainWindow||!video)return;RECT r{};GetClientRect(mainWindow,&r);const int dpi=GetDpiForWindow(mainWindow);auto px=[&](int x){return MulDiv(x,dpi,96);};int x=px(8),y=px(8),row=px(32),gap=px(6);for(auto item:toolbar){const int id=GetDlgCtrlID(item.hwnd);ShowWindow(item.hwnd,full&&id!=Fullscreen?SW_HIDE:SW_SHOW);if(full){if(id==Fullscreen)MoveWindow(item.hwnd,std::max(0L,r.right-px(115)),px(8),px(108),row,TRUE);continue;}const int w=px(item.width);if(x+w>r.right-px(8)){x=px(8);y+=row+gap;}wchar_t cls[32]{};GetClassNameW(item.hwnd,cls,32);MoveWindow(item.hwnd,x,y,w,wcscmp(cls,L"ComboBox")==0?px(180):row,TRUE);x+=w+gap;}
+ const int top=full?0:y+row+gap,bottom=full?0:px(126);MoveWindow(video,full?0:px(8),top,std::max(1L,r.right-(full?0:px(16))),std::max(1L,r.bottom-top-bottom),TRUE);
+ ShowWindow(seekBar,full?SW_HIDE:SW_SHOW);ShowWindow(statusBar,full?SW_HIDE:SW_SHOW);MoveWindow(subtitleLabel,px(8),std::max(0L,r.bottom-px(full?48:120)),std::max(1L,r.right-px(16)),px(32),TRUE);MoveWindow(seekBar,px(8),std::max(0L,r.bottom-px(88)),std::max(1L,r.right-px(16)),px(24),TRUE);MoveWindow(statusBar,px(12),std::max(0L,r.bottom-px(61)),std::max(1L,r.right-px(24)),px(56),TRUE);
+ if(full){SetWindowPos(GetDlgItem(mainWindow,Fullscreen),HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);SetWindowPos(subtitleLabel,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);}
+}
+
LRESULT CALLBACK proc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
-case WM_CREATE:{mainWindow=hwnd;font=CreateFontW(-16,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");
-control(L"BUTTON",L"Open video / image",Open,BS_PUSHBUTTON,10,10,150,30);control(L"BUTTON",L"Play",Play,BS_PUSHBUTTON,168,10,68,30);control(L"BUTTON",L"Stop",Stop,BS_PUSHBUTTON,244,10,62,30);control(L"BUTTON",L"Save image",Save,BS_PUSHBUTTON,314,10,95,30);
-control(L"BUTTON",L"DLSS NR",Nr,BS_AUTOCHECKBOX,425,10,85,30);control(L"BUTTON",L"SR 4K",Sr,BS_AUTOCHECKBOX,518,10,78,30);control(L"BUTTON",L"FG 2X",Fg,BS_AUTOCHECKBOX,600,10,78,30);CheckDlgButton(hwnd,Nr,BST_CHECKED);
-control(L"BUTTON",L"Capture",Capture,BS_PUSHBUTTON,690,10,75,30);control(L"BUTTON",L"Export video",Export,BS_PUSHBUTTON,773,10,103,30);control(L"BUTTON",L"Logs",Info,BS_PUSHBUTTON,884,10,60,30);
-control(L"BUTTON",L"Live 1080",Realtime,BS_AUTOCHECKBOX,952,10,112,30);
-control(L"BUTTON",L"Recent",Recent,BS_PUSHBUTTON,1072,10,75,30);
+case WM_CREATE:{mainWindow=hwnd;font=CreateFontW(-16,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");
+control(L"BUTTON",L"打开视频/图片",Open,BS_PUSHBUTTON,10,10,150,30);control(L"BUTTON",L"播放",Play,BS_PUSHBUTTON,168,10,68,30);control(L"BUTTON",L"停止",Stop,BS_PUSHBUTTON,244,10,62,30);control(L"BUTTON",L"保存图片",Save,BS_PUSHBUTTON,314,10,95,30);
+control(L"BUTTON",L"DLSS5 NR",Nr,BS_AUTOCHECKBOX,425,10,110,30);control(L"BUTTON",L"SR 4K",Sr,BS_AUTOCHECKBOX,518,10,78,30);control(L"BUTTON",L"补帧",Fg,BS_AUTOCHECKBOX,600,10,78,30);CheckDlgButton(hwnd,Nr,BST_CHECKED);
+control(L"BUTTON",L"采集",Capture,BS_PUSHBUTTON,690,10,75,30);control(L"BUTTON",L"导出视频",Export,BS_PUSHBUTTON,773,10,103,30);control(L"BUTTON",L"性能/诊断",Info,BS_PUSHBUTTON,884,10,100,30);
+control(L"BUTTON",L"实时NR档",Realtime,BS_AUTOCHECKBOX,952,10,100,30);
+control(L"BUTTON",L"最近打开",Recent,BS_PUSHBUTTON,1072,10,75,30);
+auto mult=control(L"COMBOBOX",L"",Multiplier,CBS_DROPDOWNLIST,1150,10,70,180);for(auto label:{L"2X",L"3X",L"4X"})SendMessageW(mult,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));SendMessageW(mult,CB_SETCURSEL,initialOptions.fgMultiplier-2,0);
+control(L"BUTTON",L"参数与预设",Settings,BS_PUSHBUTTON,1225,10,100,30);
+auto original=control(L"BUTTON",L"按住原图 V",OriginalHold,BS_PUSHBUTTON,0,0,110,30);SetWindowSubclass(original,interaction,OriginalHold,0);
+control(L"BUTTON",L"原图/增强切换",CompareToggle,BS_PUSHBUTTON,0,0,120,30);control(L"BUTTON",L"分屏拖动",Split,BS_PUSHBUTTON,0,0,95,30);
+auto ref=control(L"COMBOBOX",L"",Reference,CBS_DROPDOWNLIST,0,0,170,180);for(auto label:{L"对比:输入原画",L"对比:增强前底图"})SendMessageW(ref,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));SendMessageW(ref,CB_SETCURSEL,0,0);control(L"BUTTON",L"全屏 F11",Fullscreen,BS_PUSHBUTTON,0,0,108,30);
subtitleLabel=control(L"STATIC",L"",0,SS_CENTER,8,640,1100,32);
-video=control(L"STATIC",L"",0,SS_BLACKRECT,8,52,1100,610);seekBar=control(TRACKBAR_CLASSW,L"",Seek,TBS_HORZ,8,675,1100,24);SendMessageW(seekBar,TBM_SETRANGE,TRUE,MAKELPARAM(0,10000));statusBar=control(L"STATIC",L"Open a local video or PNG/JPEG. Experimental local runtime; not an official NVIDIA product.",0,SS_LEFT,12,708,1080,36);
+video=control(L"STATIC",L"",VideoSurface,SS_BLACKRECT|SS_NOTIFY,8,52,1100,610);seekBar=control(TRACKBAR_CLASSW,L"",Seek,TBS_HORZ,8,675,1100,24);SendMessageW(seekBar,TBM_SETRANGE,TRUE,MAKELPARAM(0,10000));statusBar=control(L"STATIC",L"打开本地视频或PNG/JPEG。本地实验运行时,非NVIDIA官方产品。",0,SS_LEFT,12,708,1080,36);
+SetWindowSubclass(video,interaction,VideoSurface,0);
DragAcceptFiles(hwnd,TRUE);SetTimer(hwnd,1,200,nullptr);layout();return 0;}
-case WM_SIZE:layout();return 0;
+case WM_SIZE:if(wp!=SIZE_MINIMIZED)layout();return 0;
case WM_DROPFILES:{wchar_t file[32768]{};DragQueryFileW(reinterpret_cast<HDROP>(wp),0,file,32768);DragFinish(reinterpret_cast<HDROP>(wp));openFile(file);return 0;}
case WM_COMMAND:switch(LOWORD(wp)){
case Open:openFile(fileDialog(false));break;
-case Recent:{wchar_t recent[32768]{};GetPrivateProfileStringW(L"Player",L"Recent",L"",recent,32768,(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring().c_str());openFile(recent);break;}
-case Play:{auto s=engine.snapshot();if(!currentFile.empty()&&(!s.running||(s.duration>0&&s.position>=s.duration-0.1))){openFile(currentFile);break;}paused=!paused;engine.pause(paused);SetWindowTextW(GetDlgItem(hwnd,Play),paused?L"Play":L"Pause");break;}
+case Recent:{wchar_t recent[32768]{};GetPrivateProfileStringW(L"Player",L"最近打开",L"",recent,32768,(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring().c_str());openFile(recent);break;}
+case Play:{auto s=engine.snapshot();if(!currentFile.empty()&&(!s.running||(s.duration>0&&s.position>=s.duration-0.1))){openFile(currentFile);break;}paused=!paused;engine.pause(paused);SetWindowTextW(GetDlgItem(hwnd,Play),paused?L"播放":L"暂停");break;}
case Stop:engine.stop();break;
case Save:{auto name=fileDialog(true);if(!name.empty())engine.saveFrame(name);break;}
-case Realtime:case Nr:case Sr:case Fg:{auto opts=options();auto ini=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring();WritePrivateProfileStringW(L"Player",L"NR",opts.nr?L"1":L"0",ini.c_str());WritePrivateProfileStringW(L"Player",L"SR",opts.sr?L"1":L"0",ini.c_str());WritePrivateProfileStringW(L"Player",L"FG",opts.fg?L"1":L"0",ini.c_str());WritePrivateProfileStringW(L"Player",L"Realtime",opts.realtime?L"1":L"0",ini.c_str());if(!currentFile.empty())openFile(currentFile);break;}
+case Multiplier:case Realtime:case Nr:case Sr:case Fg:{auto changed=engine.snapshot().desired;const auto id=LOWORD(wp);
+if(id==Nr)changed.nr=IsDlgButtonChecked(hwnd,Nr)==BST_CHECKED;
+if(id==Sr)changed.sr=IsDlgButtonChecked(hwnd,Sr)==BST_CHECKED;
+if(id==Realtime)changed.nrPolicy=IsDlgButtonChecked(hwnd,Realtime)==BST_CHECKED?veyra::pipeline::NrSizePolicy::Realtime:veyra::pipeline::NrSizePolicy::Native;
+if(id==Fg)changed.multiplier=IsDlgButtonChecked(hwnd,Fg)==BST_CHECKED?uint32_t(SendDlgItemMessageW(hwnd,Multiplier,CB_GETCURSEL,0,0)+2):1;
+if(id==Multiplier&&HIWORD(wp)==CBN_SELCHANGE&&changed.multiplier>1)changed.multiplier=uint32_t(SendDlgItemMessageW(hwnd,Multiplier,CB_GETCURSEL,0,0)+2);
+engine.requestSettings(changed);break;}
+
+case Fullscreen:toggleFullscreen();break;
+case VideoSurface:if(HIWORD(wp)==STN_DBLCLK)toggleFullscreen();break;
+case CompareToggle:compareMode=compareMode==1?0:1;updateComparison();break;
+case Split:compareMode=compareMode==2?0:2;updateComparison();break;
+case Reference:referenceBase=SendDlgItemMessageW(hwnd,Reference,CB_GETCURSEL,0,0)==1;updateComparison();break;
+case Settings:veyra::ui::showSettings(hwnd,engine);break;
case Capture:showCapture();break;
-case Export:{if(currentFile.empty())break;wchar_t name[32768]{};OPENFILENAMEW d{};d.lStructSize=sizeof(d);d.hwndOwner=hwnd;d.lpstrFile=name;d.nMaxFile=32768;d.lpstrFilter=L"MP4 video\0*.mp4\0";d.lpstrDefExt=L"mp4";d.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT;if(GetSaveFileNameW(&d)){int codec=MessageBoxW(hwnd,L"Use HEVC? Yes = HEVC, No = H.264. Current NR / SR / FG options apply. Existing files are never overwritten.",L"Video export",MB_YESNOCANCEL);if(codec!=IDCANCEL)engine.startExport(currentFile,name,options(),codec==IDYES);}break;}
-case Info:ShellExecuteW(hwnd,L"open",(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs").wstring().c_str(),nullptr,nullptr,SW_SHOW);break;
+case Export:{if(currentFile.empty())break;wchar_t name[32768]{};OPENFILENAMEW d{};d.lStructSize=sizeof(d);d.hwndOwner=hwnd;d.lpstrFile=name;d.nMaxFile=32768;d.lpstrFilter=L"MP4视频\0*.mp4\0";d.lpstrDefExt=L"mp4";d.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT;if(GetSaveFileNameW(&d)){int codec=MessageBoxW(hwnd,L"使用HEVC编码?“是”为HEVC,“否”为H.264。导出冻结当前参数,NR默认原生尺寸;不覆盖已有文件。",L"视频导出",MB_YESNOCANCEL);if(codec!=IDCANCEL)engine.startExport(currentFile,name,options(),codec==IDYES);}break;}
+case Info:veyra::ui::showTelemetry(hwnd,engine);break;
}return 0;
case WM_HSCROLL:if(reinterpret_cast<HWND>(lp)==seekBar){dragging=LOWORD(wp)==TB_THUMBTRACK;auto s=engine.snapshot();if(!dragging&&s.duration>0)engine.seek(s.duration*SendMessageW(seekBar,TBM_GETPOS,0,0)/10000.0);}return 0;
-case WM_KEYDOWN:if(wp==VK_SPACE){SendMessageW(hwnd,WM_COMMAND,Play,0);return 0;}if(wp==VK_F11){static WINDOWPLACEMENT old{sizeof(old)};static bool full=false;full=!full;if(full){GetWindowPlacement(hwnd,&old);SetWindowLongPtrW(hwnd,GWL_STYLE,WS_POPUP|WS_VISIBLE);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromWindow(hwnd,MONITOR_DEFAULTTONEAREST),&mi);SetWindowPos(hwnd,HWND_TOP,mi.rcMonitor.left,mi.rcMonitor.top,mi.rcMonitor.right-mi.rcMonitor.left,mi.rcMonitor.bottom-mi.rcMonitor.top,SWP_FRAMECHANGED);}else{SetWindowLongPtrW(hwnd,GWL_STYLE,WS_OVERLAPPEDWINDOW|WS_VISIBLE);SetWindowPlacement(hwnd,&old);SetWindowPos(hwnd,nullptr,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);}return 0;}break;
-case WM_TIMER:{if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);startTick=GetTickCount64();}if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;
+case WM_KEYDOWN:if(wp==VK_SPACE){SendMessageW(hwnd,WM_COMMAND,Play,0);return 0;}if(wp==VK_F11){toggleFullscreen();return 0;}if(wp==VK_ESCAPE&&full){toggleFullscreen();return 0;}if(wp=='V'){holdOriginal=true;updateComparison();return 0;}break;
+case WM_KEYUP:if(wp=='V'){holdOriginal=false;updateComparison();return 0;}break;
+case WM_SYSKEYDOWN:if(wp==VK_RETURN&&(lp&(1LL<<29))){toggleFullscreen();return 0;}break;
+case WM_ACTIVATEAPP:if(!wp){holdOriginal=false;updateComparison();}break;
+case WM_DPICHANGED:{auto rect=reinterpret_cast<RECT*>(lp);if(!full)SetWindowPos(hwnd,nullptr,rect->left,rect->top,rect->right-rect->left,rect->bottom-rect->top,SWP_NOZORDER|SWP_NOACTIVATE);auto oldFont=font;font=CreateFontW(-MulDiv(15,HIWORD(wp),96),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");EnumChildWindows(hwnd,[](HWND c,LPARAM f)->BOOL{SendMessageW(c,WM_SETFONT,WPARAM(f),TRUE);return TRUE;},LPARAM(font));DeleteObject(oldFont);layout();return 0;}
+
+case WM_TIMER:{if(closing){if(engine.idle()){KillTimer(hwnd,1);DestroyWindow(hwnd);}return 0;}if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);startTick=GetTickCount64();}if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;
if(smokeStep==0&&elapsed>2200){engine.pause(true);smokeStep=1;}
if(smokeStep==1&&elapsed>2600){engine.seek(1.0);smokeStep=2;}
if(smokeStep==2&&elapsed>3200){engine.pause(false);smokeStep=3;}
if(smokeStep==3&&elapsed>4100&&!smokeSave.empty()){engine.saveFrame(smokeSave);smokeStep=4;}
-}auto s=engine.snapshot();SetWindowTextW(subtitleLabel,veyra::engine::subtitleAt(subtitles,s.position).c_str());auto text=std::format(L"{}\r\n{:.1f} / {:.1f}s {:.1f} processed fps lateness {:+.1f}ms source {} / generated {}",s.status,s.position,s.duration,s.fps,s.lateMs,s.frames,s.generated);SetWindowTextW(statusBar,text.c_str());if(!dragging&&s.duration>0)SendMessageW(seekBar,TBM_SETPOS,TRUE,LPARAM(s.position/s.duration*10000));
-if(smokeSeconds>0&&startTick&&GetTickCount64()-startTick>ULONGLONG(smokeSeconds)*1000){veyra::log::info("app",std::format("smoke frames={} generated={} failed={} latenessMs={:.2f} absLatenessP95Ms={:.2f} controlsStep={}",s.frames,s.generated,s.failed,s.lateMs,s.lateP95Ms,smokeStep));resultCode=s.frames>0&&!s.failed?0:1;PostMessageW(hwnd,WM_CLOSE,0,0);}return 0;}
-case WM_CLOSE:KillTimer(hwnd,1);engine.stop();DestroyWindow(hwnd);return 0;
+}auto s=engine.snapshot();CheckDlgButton(hwnd,Nr,s.desired.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Sr,s.desired.sr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Fg,s.desired.multiplier>1?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Realtime,s.desired.nrPolicy==veyra::pipeline::NrSizePolicy::Realtime?BST_CHECKED:BST_UNCHECKED);if(s.desired.multiplier>1)SendDlgItemMessageW(hwnd,Multiplier,CB_SETCURSEL,s.desired.multiplier-2,0);SetWindowTextW(subtitleLabel,veyra::engine::subtitleAt(subtitles,s.position).c_str());
+auto text=s.capture?std::format(L"{}\r\n输入 {:.1f} / 已处理 {:.1f}fps | 回调至Present返回p95 {:.1f}ms(非总延迟)| 丢弃 {} | 有效生成 {}",s.status,s.captureFps,s.fps,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(compareMode||holdOriginal)text+=L"\r\n真实帧对比:两侧同一源帧;此模式不展示生成帧。";
+const auto problem=veyra::Logger::instance().latestProblem();if(!problem.empty()){int n=MultiByteToWideChar(CP_UTF8,0,problem.data(),int(problem.size()),nullptr,0);std::wstring detail(n,0);MultiByteToWideChar(CP_UTF8,0,problem.data(),int(problem.size()),detail.data(),n);text+=L"\r\n最近问题:"+detail.substr(0,100)+L"(详见诊断)";}
+SetWindowTextW(statusBar,text.c_str());if(!dragging&&s.duration>0)SendMessageW(seekBar,TBM_SETPOS,TRUE,LPARAM(s.position/s.duration*10000));
+if(smokeRollback&&startTick){if(settingsStep==0&&s.frames>20){auto changed=s.desired;if(smokeRollbackFlow)changed.nr=false;else{changed.model.style=2;changed.model.intensity=.35f;}engine.requestSettings(changed);settingsStep=1;}if(settingsStep==1&&s.frames>50&&s.desired.model.style==0&&s.applied.model.style==0&&!s.applying&&(!smokeRollbackFlow||(s.applied.nr&&s.nvofExecuted>30))){settingsStep=3;veyra::log::info("rollback-test",std::format("whole snapshot restored revision={} position={} style={} intensity={}",s.applied.revision,s.position,s.applied.model.style,s.applied.model.intensity));}}
+if(smokeUi&&startTick){const auto elapsed=GetTickCount64()-startTick;
+if(uiStep==0&&elapsed>2300){SendMessageW(hwnd,WM_KEYDOWN,VK_F11,0);uiStep=1;}
+if(uiStep==1&&elapsed>2800){const bool entered=full&&(GetWindowLongPtrW(hwnd,GWL_STYLE)&WS_POPUP);SendMessageW(hwnd,WM_KEYDOWN,VK_ESCAPE,0);veyra::log::info("ui-test",std::format("F11 entered={} Esc restored={}",entered,!full));uiStep=entered&&!full?2:-1;}
+if(uiStep==2&&elapsed>3300){SendMessageW(hwnd,WM_SYSKEYDOWN,VK_RETURN,1LL<<29);uiStep=3;}
+if(uiStep==3&&elapsed>3800){const bool entered=full;SendMessageW(hwnd,WM_COMMAND,MAKEWPARAM(VideoSurface,STN_DBLCLK),LPARAM(video));veyra::log::info("ui-test",std::format("AltEnter entered={} doubleClick restored={}",entered,!full));uiStep=entered&&!full?4:-1;}
+if(uiStep==4&&elapsed>4200){compareMode=2;compareSplit=.4f;updateComparison();uiStep=5;}
+if(uiStep==5&&elapsed>4800){referenceBase=true;updateComparison();uiStep=6;}
+if(uiStep==6&&elapsed>5500){holdOriginal=true;updateComparison();uiStep=7;}
+if(uiStep==7&&elapsed>5900){holdOriginal=false;compareMode=0;updateComparison();veyra::log::info("ui-test",std::format("completed={} NR evaluations={} (no fullscreen NR re-create expected)",true,s.nrEvaluated));uiStep=8;}
+}
+if(smokeSettings&&startTick){const auto elapsed=GetTickCount64()-startTick;
+if(settingsStep==0&&s.frames>20){auto change=s.desired;change.model.intensity=.6f;change.model.tone=.7f;change.residual.total=.4f;change.residual.color=.8f;engine.requestSettings(change);settingsStep=1;}
+if(settingsStep==1&&s.applied.model.intensity==.6f&&elapsed>3300){auto change=s.desired;change.sr=true;engine.requestSettings(change);settingsStep=2;}
+if(settingsStep==2&&s.applied.sr&&elapsed>4500){auto invalid=s.desired;invalid.model.intensity=2;const bool rejected=!engine.requestSettings(invalid);veyra::log::info("settings-test",std::format("invalid-rejected={} position={} revision={} settingsStep={}",rejected,s.position,s.applied.revision,settingsStep));settingsStep=rejected?3:-1;}
+}
+if(smokeSeconds>0&&startTick&&GetTickCount64()-startTick>ULONGLONG(smokeSeconds)*1000){veyra::log::info("app",std::format("smoke frames={} generated={} failed={} latenessMs={:.2f} absLatenessP95Ms={:.2f} controlsStep={} capture={} processedFps={:.2f} callbackFps={:.2f} captureDropped={} callbackToPresentReturnP95Ms={:.3f} schedulingWaitP95Ms={:.3f} processCpuP95Ms={:.3f} presentCpuP95Ms={:.3f} nrEvaluated={} nvofExecuted={}",s.frames,s.generated,s.failed,s.lateMs,s.lateP95Ms,smokeStep,s.capture,s.fps,s.captureFps,s.captureDropped,s.captureAgeP95Ms,s.schedulingWaitP95Ms,s.processCpuP95Ms,s.presentCpuP95Ms,s.nrEvaluated,s.nvofExecuted));resultCode=s.frames>0&&!s.failed&&(!smokeSettings||settingsStep==3)&&(!smokeRollback||settingsStep==3)&&(!smokeUi||uiStep==8)?0:1;PostMessageW(hwnd,WM_CLOSE,0,0);}return 0;}
+case WM_CLOSE:closing=true;engine.stop();SetWindowTextW(statusBar,L"正在释放当前任务资源…");return 0;
case WM_DESTROY:DeleteObject(font);PostQuitMessage(resultCode);return 0;
}return DefWindowProcW(hwnd,msg,wp,lp);}
}
int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,LPWSTR,int show){
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);INITCOMMONCONTROLSEX controls{sizeof(controls),ICC_BAR_CLASSES};InitCommonControlsEx(&controls);
CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
-std::filesystem::create_directories(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs");veyra::Logger::instance().openFile((std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs/veyra-app.log").wstring());
-auto ini=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring();initialOptions.nr=GetPrivateProfileIntW(L"Player",L"NR",1,ini.c_str())!=0;initialOptions.sr=GetPrivateProfileIntW(L"Player",L"SR",0,ini.c_str())!=0;initialOptions.fg=GetPrivateProfileIntW(L"Player",L"FG",0,ini.c_str())!=0;initialOptions.realtime=GetPrivateProfileIntW(L"Player",L"Realtime",1,ini.c_str())!=0;
-int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else autoInput=arg;}LocalFree(argv);
+std::filesystem::create_directories(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs");wchar_t logOverride[32768]{};GetEnvironmentVariableW(L"VEYRA_LOG_FILE",logOverride,32768);veyra::Logger::instance().openFile(logOverride[0]?std::wstring(logOverride):(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs/veyra-app.log").wstring());
+initialOptions=veyra::engine::PlayerOptions::from(veyra::ui::defaultSettings());
+
+int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);
+engine.requestSettings(initialOptions.snapshot());
if(!exportOutput.empty()){std::atomic<bool> cancel{false},finished{false};std::thread cancelTimer;if(cancelAfterMs)cancelTimer=std::thread([&]{const auto start=GetTickCount64();while(!finished&&GetTickCount64()-start<cancelAfterMs)std::this_thread::sleep_for(std::chrono::milliseconds(5));if(!finished)cancel=true;});bool ok=veyra::engine::exportVideo(autoInput,exportOutput,initialOptions,exportHevc,cancel,[](double,const std::wstring& s){OutputDebugStringW(s.c_str());},exportFrames);finished=true;if(cancelTimer.joinable())cancelTimer.join();veyra::log::info("app",std::format("export result={}",ok));CoUninitialize();return ok?0:cancel?3:1;}
WNDCLASSEXW wc{sizeof(wc)};wc.hInstance=instance;wc.lpfnWndProc=proc;wc.lpszClassName=L"VeyraApp";wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);RegisterClassExW(&wc);
-auto hwnd=CreateWindowExW(0,wc.lpszClassName,L"Veyra — Local Experimental",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,1200,800,nullptr,nullptr,instance,nullptr);if(!hwnd)return 1;CheckDlgButton(hwnd,Nr,initialOptions.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Sr,initialOptions.sr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Fg,initialOptions.fg?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Realtime,initialOptions.realtime?BST_CHECKED:BST_UNCHECKED);ShowWindow(hwnd,show);MSG msg{};while(GetMessageW(&msg,nullptr,0,0)>0){TranslateMessage(&msg);DispatchMessageW(&msg);}CoUninitialize();return int(msg.wParam);
+auto hwnd=CreateWindowExW(0,wc.lpszClassName,L"Veyra — 本地实验版",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,1200,800,nullptr,nullptr,instance,nullptr);if(!hwnd)return 1;CheckDlgButton(hwnd,Nr,initialOptions.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Sr,initialOptions.sr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Fg,initialOptions.fg?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Realtime,initialOptions.realtime?BST_CHECKED:BST_UNCHECKED);ShowWindow(hwnd,show);MSG msg{};while(GetMessageW(&msg,nullptr,0,0)>0){if(GetAncestor(msg.hwnd,GA_ROOT)==hwnd&&(msg.message==WM_KEYDOWN||msg.message==WM_KEYUP||msg.message==WM_SYSKEYDOWN)){
+const bool key=msg.wParam==VK_F11||msg.wParam==VK_ESCAPE||msg.wParam==VK_SPACE||msg.wParam=='V'||(msg.wParam==VK_RETURN&&msg.message==WM_SYSKEYDOWN);if(key){SendMessageW(hwnd,msg.message,msg.wParam,msg.lParam);continue;}}
+TranslateMessage(&msg);DispatchMessageW(&msg);}CoUninitialize();return int(msg.wParam);
}
diff --git a/docs/CAPTURE_LATENCY_FIX_2026-09-07.md b/docs/CAPTURE_LATENCY_FIX_2026-09-07.md
new file mode 100644
index 00000000..a5915647
--- /dev/null
+++ b/docs/CAPTURE_LATENCY_FIX_2026-09-07.md
@@ -0,0 +1,60 @@
+# 采集延迟修复 — 2026-09-07
+
+状态:正式源代码与本机 EXE 已更新,实卡吞吐短测和软件联合回归通过;独立复核尚未完成,手柄体感/音画同步/实际显示帧间隔仍由用户确认。不是公开发布或新的阶段 checkpoint。
+
+## 根因与修复
+
+旧实现先 Run 采集,再初始化 NGX;回调保留唯一 RGB32 `IMediaSample`,占住生产者的单缓冲,积压旧帧。播放器拿第一张旧帧重建时间戳时钟,又对后来的新帧主动等待。诊断隔离到无 GPU/无 DLSS 后仍可复现:29 帧/4 秒,一次等待 940.79ms;仅去掉第二层等待,185 帧/4 秒。完整原始记录在 `logs/capture-diag-20260907/FINDINGS.md`,其中“退到 YUY2/10”的猜测已经由实际协商日志证伪。
+
+实施内容:
+
+- `src/source/CaptureCardSource.cpp` / 对应头文件:configure/start 分离,图与显示器就绪后才 Run;回调复制到自有的两张 AVFrame(一个读者持有,一个容量1待取帧),立即归还驱动 sample。消费者慢时覆盖待取帧而不积压;丢帧、时间戳断点触发历史 reset。记录实际上游 subtype、真实 callback cadence 和取帧年龄。
+- `src/engine/EngineController.cpp` / 对应头文件 / `LivePresentationTiming.h`:采集不再等待绝对源 PTS。无 FG 立即提交最新帧;FG 的生成帧先提交,真实帧按每一对当前 host-time 锚点最多等待半个输入间隔(硬上限33.33ms)。文件播放仍用原音频主时钟和 PTS 调度。全关增强时跳过 NGX 创建。
+- `src/engine/VideoPresenter.cpp`、`src/gfx/CommandSlotRing.cpp`、`src/pipeline/EnhanceGraph.cpp` / 对应头文件:图与显示共用 command-slot 游标,不再固定复用显示 slot;窗口 resize 限频并检查实际 buffer extent。最小化不再反复重建1×1 swapchain。
+- `apps/veyra/main.cpp`:采集状态显示输入/处理 FPS、丢帧和 callback→Present 返回的程序内部耗时;不再显示虚假的近零采集 lateness。smoke 测试不改用户 Recent。
+- `src/base/Log.cpp`:允许读取运行中的日志,仍排斥其他写入者。
+- `tests/unit/LivePresentationTimingTests.cpp`、`tests/integration/CaptureSourceTests.cpp`、`CMakeLists.txt`:纯时间策略回归,以及真实设备的延迟启动、消费者停顿、内存所有权、latest-frame/drop/reset 验证。
+- `scripts/gates/delivery.ps1`:增加 `-VisiblePlayer`,这轮播放器回归在可见窗口执行;不把隐藏窗口的成功提交当成可见显示证明。
+
+没有改变驱动、OBS、远程软件、用户设置或专有二进制。用户删除的 `validation/fixed_clips/test_h264_1080p.mp4` 保留。实卡测试不保存采集画面;图片/导出回归使用项目的合成测试媒体。
+
+## 实际命令与结果
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release
+out/build/x64-release/veyra_live_timing_tests.exe
+out/build/x64-release/veyra_capture_tests.exe capture:0:0:2
+out/build/x64-release/veyra.exe capture:0:0:2 --no-nr --smoke-seconds 6
+out/build/x64-release/veyra.exe capture:0:0:2 --smoke-seconds 6
+out/build/x64-release/veyra.exe capture:0:0:2 --fg --smoke-seconds 6
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -VisiblePlayer
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/loop-gate.ps1 -Gate preflight
+```
+
+采集测试使用同一实卡 USB2 Video、MJPEG 1920×1080/50、原音频索引2。NR/SR/FG 原设置为1/0/0,因此第二/第三条应用测试分别为 NR、NR+FG。其他用户配置复现时必须核对日志中的实际开关及 Evaluate 计数,不能只看退出码。
+
+| 首轮实卡短测 | 实际源处理 FPS | 源帧 / 生成帧 | 采集丢帧 | callback→Present返回 p95 |
+|---|---:|---:|---:|---:|
+| 增强全关 | 49.82 | 276 / 0 | 0 | 3.672ms |
+| NR | 49.83 | 181 / 0 | 0 | 4.770ms |
+| NR + FG | 49.53 | 201 / 200 | 0 | 16.277ms |
+
+这些是每个6秒应用窗口中的有效采集阶段,NR 模式有约1–2秒初始化,不拿总6秒除计数伪造运行 FPS。原始日志:`logs/capture-fix-20260907/{off,nr,nr-fg}.log`。NR181/NVOF180 与 NR201/NVOF200 都在实际 RTX/runtime 上执行,不是桩或纯 counter。
+
+最终 EXE SHA256:`4A9BA4B321DEEC17C5E3562AF03EF75A316856200A8708FA8E692475A05B59C9`。
+
+最终 EXE 实卡复验:`final-nr-fg.log`,exit0,49.40 processed / 50.13 callback fps、195源帧/193生成帧、0采集丢帧、NR195/NVOF193、callback→Present返回 p95 16.395ms;不把 history reset 跳过的生成帧算成功。
+
+时间策略单测7/7;实卡 source 测试8/8。消费者保留读帧停顿300ms时仍收到16个callback、覆盖14帧,读者持有的数据不变,恢复时读到最新帧(callback age 8.889ms),不是排队读旧帧。
+
+收尾状态校验发现把 `needs_review` 错放入 phase 子状态(该字段只允许 `gate_passed` 等)且阶段名称不一致;已按现有 schema 修正为顶层 `needs_review`、Phase7 `gate_passed`,未修改门禁或控制 hash。保留失败记录 `logs/capture-fix-20260907/preflight-final.log`;随后复验另存 `preflight-state-corrected.log`。
+
+软件联合 gate:exit0,21 checks,47.309秒,`logs/delivery/01b72df768524af9ab0aa8d2e3dbb59e/result.json`,EXE hash 与最终版本一致。包括真实 NR/NVOF/GBV、4K实时档文件播放和音频同步、暂停seek/resume、4K图片保存、4K H.264/HEVC各23帧输出+音轨解码、NVENC取消/partial。preflight71/71;`git diff --check` 无空白错误。没有跑30分钟耐久。
+
+## 限制与下一步
+
+- callback→Present返回不是 HDMI→屏幕光子的端到端延迟,也不是GPU完成时间。未测系统合成器实际显示了多少生成帧,不宣称屏幕100Hz或已证明FG均匀显示;GPU超预算时,CPU配对间隔不保证物理显示间隔。不得拿吞吐改善冒充所有画质/延迟问题都解决。
+- 这是当前 USB2 的1080p50实卡证据;历史 OBS 的 USB3/YUY2/1080p60记录保留,不混为同一次输入模式。4K实卡模式仍未测。
+- 原音频索引2对应Realtek麦克风,未擅自改成索引0的USB2数字音频。用户应在采集设置选择采集卡的USB数字音频,不能按旧索引猜设备。
+- 独立只读 Reviewer 尝试异常结束,未返回最终审查结论;此前版本的 REVIEW_F6 PASS 不覆盖本补丁。保留 `needs_review`,未创建新阶段 checkpoint。
+- 下一项:用户在重开的 NR 预览中操作主机确认体感和音频;若仍卡,读实时日志中的 callbackFps、processedFps、drop 和各段耗时,不再先怀疑驱动或关闭无关软件。
diff --git a/docs/DELIVERY_STATUS.md b/docs/DELIVERY_STATUS.md
index cfa9812b..a0917252 100644
--- a/docs/DELIVERY_STATUS.md
+++ b/docs/DELIVERY_STATUS.md
@@ -1,6 +1,40 @@
+# 当前本机状态 — 2026-09-08 Repair v2
+
+## 双模式UI改版计划已确认,尚未施工
+
+2026-09-08用户确认:默认日常模式,负责视频/采集;专业模式集中精细参数与导出,切换保留同一播放/采集会话。详细布局、工程缺口、UI0–UI9顺序及验收见 [双模式执行文档](UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md)。本次只写文档,以下Repair v2应用版本和实测状态不变。后台导出与观看并存、音量控制等新增工程仍待实现。
+
+已完成本次三个确认缺陷及源帧计数修复,18项联合软件检查通过,新上下文只读复审通过本次限定范围。全项目保持needs_review,实卡和完整性能/长期稳定尚未验收;不更新旧Phase,不公开发行。
+
+当前EXE SHA256:`1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266`。详细文件、命令、耗时、错误码、参数实验、功能与性能限制见 [最新交付报告](REPAIR_V2_DELIVERY_2026-09-08.md),操作见 [使用指南](USER_GUIDE.md)。
+
+用户已澄清:单次测试最多300秒,累计耗时不设本轮硬上限。最终联合耗时71.028秒;历史累计346.399秒。SR4K+4X设置测试仍观察到39.75源fps与约2.17秒落后,不宣称这个组合4K60实时。
+
+---
+
+以下完整保留历史状态,仅供追溯,不代表当前EXE或最新结论:
+
# 本机交付状态 — 2026-09-07
-状态:本机软件联合短测与独立只读复核均已通过,可交给用户使用和实卡验收。不是公开发行许可;实卡未接入。最终复验与范围见 REVIEW_F6.md。
+## 最新反馈与待执行方案
+
+用户仍报告 SR4K 开启后严重卡顿、补帧体感未达预期。下面已有的源帧吞吐短测不能证明这两项已修好,也不能证明 50→100 的实际显示效果。
+
+本轮仅按用户要求编写方案,没有改代码、构建、运行测试或更新 EXE:
+
+- [详细修复执行方案](<C:/Users/123/Desktop/Veyra DLSS Video Player/docs/REPAIR_EXECUTION_PLAN_2026-09-07.md>):分辨率解耦、真实 2X、3X/4X、DLSS5 模型/变化量参数、中文、完整全屏与五分钟验证设计。
+- [Magpie 功能与难度清单](<C:/Users/123/Desktop/Veyra DLSS Video Player/docs/MAGPIE_FEATURE_BACKLOG_2026-09-07.md>):用户已选择 B1–B5;其余候选分开,按独立实现评估。
+- [下一对话接管提示词](<C:/Users/123/Desktop/Veyra DLSS Video Player/docs/NEXT_AGENT_HANDOFF_2026-09-07.md>):可直接粘贴,明确旧门禁证据边界和禁止改哈希/门禁。
+
+这些新增功能处于计划状态,不代表当前已可使用。B1–B5 已选但尚未编码;现有 F11 基础切换仍需要完善,不是完整全屏验收证明。当前补丁仍为 `needs_review`,不创建新 checkpoint,也不把旧 Phase5–7 共享 gate 当作新版本发布证据。
+
+## 上一次实卡修复的实际状态
+
+当前状态:2026-09-07 实卡暴露的旧帧积压/错误 PTS 等待已修复,本机 EXE 已更新。增强全关和 NR 约49.8源fps,NR+FG约49.4–49.5源fps,短测0采集丢帧(当前卡为1080p50)。软件联合可见窗口回归21项/47.309秒通过。独立复核未完成,体感/音频/实际显示间隔仍待用户确认;不是公开发布。
+
+当前 EXE SHA256 `4A9BA4B321DEEC17C5E3562AF03EF75A316856200A8708FA8E692475A05B59C9`;联合回归 `logs/delivery/01b72df768524af9ab0aa8d2e3dbb59e/result.json`;实卡证据与完整限制见 [CAPTURE_LATENCY_FIX_2026-09-07.md](CAPTURE_LATENCY_FIX_2026-09-07.md)。本补丁状态 `needs_review`,不继承旧 Reviewer PASS。
+
+## 以下是修复前交付历史,不是当前实卡验收证明
最终构建EXE:`70DD23C44337004FC734FBAE8BB6139E185C52370AE97CCE6C3432A3C6F30DE1`;独立联合短测run `9be0614da5d642e394a35c71d80f6207`,40.31秒通过,包含新增4K图片保存与真实NVENC中途取消。下方31.59秒是初测历史,不是最终二进制身份。
@@ -9,7 +43,7 @@
- `Veyra.cmd` → `out/build/x64-release/veyra.exe`,Win32 UI + 同一共享增强引擎。
- 本地 H.264/HEVC 播放,音频主时钟,暂停/定位/全屏/开关/最近文件,外部同名 SRT。
- WIC PNG/JPEG 图片输入和保存;D3D12 NVENC 原生 4K H.264/HEVC MP4 + 兼容音轨,FG 2X、取消/partial。
-- DirectShow 视频设备/实际格式/HDMI 音频选择、容量1实时邮箱;没有实卡运行证据。
+- DirectShow 视频设备/实际格式/HDMI 音频选择;当时没有实卡证据,且所谓容量1邮箱仍持有生产者sample,缺陷已在上述修复中纠正。
## 本轮实测
diff --git a/docs/MAGPIE_FEATURE_BACKLOG_2026-09-07.md b/docs/MAGPIE_FEATURE_BACKLOG_2026-09-07.md
new file mode 100644
index 00000000..47b4ae33
--- /dev/null
+++ b/docs/MAGPIE_FEATURE_BACKLOG_2026-09-07.md
@@ -0,0 +1,127 @@
+# Magpie 功能清单:Veyra 值得加入什么
+
+调研日期:2026-09-07。核对范围:SAOG0721/Magpie 的可见发布说明、实验分支说明及参数/时序记录。本轮核对到的最新发布是 v0.6.6-experimental;没有在本机运行 Magpie 做画质、延迟或兼容性对照。
+
+“Magpie 有”在本文中表示公开仓库或发布说明记载,不等于本机验证成功。工程难度和需要程度是针对现有 Veyra 的评估,不是作者的评价,也不是工期承诺。
+
+配套:[详细修复执行方案](<C:/Users/123/Desktop/Veyra DLSS Video Player/docs/REPAIR_EXECUTION_PLAN_2026-09-07.md>)。
+
+## 1. 结论先说
+
+最值得参考的不是继续加更多 AI 名字,而是四件事:**可调参数、保留底图的低分辨率 NR、正确的补帧节奏、能解释性能的界面**。
+
+你已要求的 SR4K、2X 修复、3X/4X、DLSS5 调参、中文与全屏,以及 B1–B5,均已进入施工方案。B6–B8 与后续 C/V 项仍是候选。没有开始实现。
+
+按项目现有许可证边界,“搬过来”指独立实现相同的用户价值;不复制 Magpie GPL 源码、shader、UI 实现或二进制。若改为直接复用源码,需另外决定 GPL 与项目分发方案。
+
+### 1.1 评分怎么读
+
+- 难度 1/5:局部配置或少量 UI;2/5:单模块功能;3/5:多个模块与 GPU 资源协同;4/5:核心管线/时序/颜色改造;5/5:新算法后端、重大接口或长期兼容性成本。
+- 需要程度 5/5:当前产品能否正常使用或差异化的关键;4/5:明显改善使用;3/5:特定素材有价值;2/5:受众较窄;1/5:与当前目标不匹配。
+- 评分基于现有工程,不包括获准复制代码的假设;“界面容易加”不代表底层容易接。
+- “已纳入”指方案范围,不是软件已实现;“建议选”也不代表已获得实施授权。
+
+## 2. 已纳入本次方案的功能
+
+| 编号 | Magpie 相关能力 | Veyra 要做的版本 | 难度 | 需要 | 状态 |
+| --- | --- | --- | --- | --- | --- |
+| A1 | DLSSNR 模型参数 | 实际绑定强度、局部明暗/结构;实验参数单独标注并验证 | 3/5 | 5/5 | 已纳入 |
+| A2 | NR 变化量调节 | 总变化、暗化、亮化、色彩与明度变化;不能冒称语义材质控制 | 3/5 | 5/5 | 已纳入 |
+| A3 | NR 输入缩放与变化回填 | 解开 SR4K 与 NR4K,保留 4K 底图;原生 NR 可选 | 4/5 | 5/5 | 已纳入 |
+| A4 | FG 与输出节奏管理 | 先修真 2X,再把 3X/4X 接到显示和导出;按本地 SDK 验证 | 5/5 | 5/5 | 已纳入 |
+| A5 | 实时参数交互 | Desired/Applied、拖动合并、帧边界应用,不重新打开视频 | 4/5 | 5/5 | 已纳入 |
+| A6 | 中文、参数分组、快捷操作 | 完整汉化、分组说明、逐项默认恢复、可靠全屏输入 | 2/5 | 5/5 | 已纳入 |
+| A7 | 真实/输出 FPS 分开 | 源、生成、提交、可测显示四层统计和硬件限制提示 | 3/5 | 5/5 | 已纳入 |
+
+Magpie 的对应事实可查 [参数修订](https://github.com/SAOG0721/Magpie/blob/experimental/docs/experimental/todos/20260904-v0.6.5-r2-fix1-TODO.md)、[实时交互记录](https://github.com/SAOG0721/Magpie/blob/experimental/docs/experimental/reviews/20260906-v0.6.6-parameter-interaction.md)、[帧同步说明](https://github.com/SAOG0721/Magpie/blob/experimental/docs/FRAME_SYNC_GUIDE.md)。Veyra 的具体实现与验收要求由配套执行方案定义,不照搬其代码和验证结论。
+
+### 2.1 你能调什么:面向使用者的清单
+
+基础模型区:
+
+- **模型强度**:模型自身的处理控制,不等于简单混合原图。
+- **局部明暗**、**局部结构**:控制模型局部变化;不承诺能指定某个物体。
+- **肤质结构、风格、自动遮罩、画面内 UI 修正**:放实验折叠区。只有真实适配和证据支持后才标可用,不用漂亮标签掩盖未知行为。
+
+变化量区:
+
+- **总变化**:0 看底图、1 看未额外放大的 NR 变化、超过 1 额外放大。
+- **暗化变化 / 亮化变化**:分别压低或放大处理引起的暗/亮变化。可以近似满足“少加点阴影、保留些增亮”的需求,但不是获得了真实阴影/反射图。
+- **色彩变化 / 明度变化**:控制相对原图改变了多少,不是无条件“更鲜艳/更亮”。
+
+质量与性能区:
+
+- NR 实时/原生和实际内部尺寸;SR 的输出目标另外显示。
+- FG 关闭、2X、3X、4X;显示实际可用能力与吞吐,不只显示理论倍率。
+- 参数修改保持当前播放位置;图片调整模型参数时重算,调整变化量时尽量只重合成。
+
+上面的范围、NGX 键名、类型、默认值、失败回滚、导出参数冻结均已写进执行方案第 6 节。
+
+## 3. 用户已选择的 B1–B5 与剩余候选
+
+2026-09-07 用户明确回复“B1–B5 先加上”。下表 B1–B5 已转为本次范围;B6–B8 仍未选择。
+
+| 编号 | 功能与 Magpie 依据 | Veyra 的收益和边界 | 难度 | 需要 | 我的建议 |
+| --- | --- | --- | --- | --- | --- |
+| B1 | 原图/处理后对比:[发布说明](https://github.com/SAOG0721/Magpie/releases/tag/v0.6.5-experimental) | 同一 PTS、同一底图的瞬时切换与分屏拖杆;生成帧不伪装成同帧原画 | 2/5 | 5/5 | **已选择,纳入** |
+| B2 | 各效果性能监测:[仓库说明](https://github.com/SAOG0721/Magpie) | GPU timestamp 显示 SR/NR/光流/FG/合成,CPU 等待分栏,目标值不冒充实测 | 3/5 | 5/5 | **已选择,纳入** |
+| B3 | 效果组/配置管理:[发布说明](https://github.com/SAOG0721/Magpie/releases/tag/v0.6.5-experimental) | 受控用户预设,整套事务应用;不开放任意颠倒 SR→NR→FG 顺序 | 2/5 | 4/5 | **已选择,纳入** |
+| B4 | 各消费者光流配置:[光流记录](https://github.com/SAOG0721/Magpie/blob/experimental/docs/experimental/todos/20260905-v0.6.5-r8-TODO.md) | 性能/平衡/质量请求,共享一次估算,并显示本机实际采用档位 | 3/5 | 4/5 | **已选择,纳入** |
+| B5 | 最近错误、复制诊断、打开日志:[发布说明](https://github.com/SAOG0721/Magpie/releases/tag/v0.6.5-experimental) | 结构化错误、原因、建议、脱敏复制与本地日志目录;绝不自动上传 | 2/5 | 4/5 | **已选择,纳入** |
+| B6 | 可设置工具栏快捷键:[仓库说明](https://github.com/SAOG0721/Magpie) | NR 快速开关、按住看原图、打开参数、固定控制条;F11/Esc 等基础全屏键已在本次范围 | 2/5 | 3/5 | 按习惯选 |
+| B7 | 参数窗位置/尺寸记忆:[0.6.6](https://github.com/SAOG0721/Magpie/releases/tag/v0.6.6-experimental) | 多显示器和窗口变小时不挡主画面;恢复时防止弹窗落到屏幕外 | 2/5 | 3/5 | 有余量再选 |
+| B8 | 效果截图:[仓库说明](https://github.com/SAOG0721/Magpie) | 在已有图片保存上增加“同帧原图+增强图+参数说明”成对保存;必须由用户主动保存,不能后台录采集画面 | 2/5 | 3/5 | 制作演示素材时选 |
+
+B1–B5 的实现/验收合同已写入配套执行方案第 8 节。B1/B2 会直接回答“效果哪里改变、哪一步卡”;B3–B5 解决重复配置、性能取舍和报错沟通。这是产品判断,不是 Magpie 作者的测评结论。
+
+### 3.1 B1 与 B3 的建议做法
+
+对比:默认一键原图/增强切换;分屏是额外展示方式。比较同一时刻,固定同样缩放和色彩输出;“原图”要明确是源画面还是 SR 后、NR 前底图。FG 后不能把 A 时刻原图与 A/B 中间生成帧直接并排称为同帧对照。
+
+预设:存 NR 设置、变化量设置、SR 目标、NR 尺寸策略、FG 倍率与光流档位,不存进程指针/显卡资源/自动换 DLL。预设切换走同一参数应用协议。例子可以叫“我的主机游戏”“老视频”,不要未经内容验证就标“最佳画质”。
+
+## 4. 有价值,但现在接入成本明显更高
+
+| 编号 | Magpie 公开能力 | Veyra 可以解决什么 | 难度 | 需要 | 结论 |
+| --- | --- | --- | --- | --- | --- |
+| C1 | RTX Video VSR / 降噪:[仓库说明](https://github.com/SAOG0721/Magpie) | 为低码率、压缩严重的老视频提供另一条增强路线;可能比增加 NR 强度更对症,但不能预先保证 | 4/5 | 3/5 | 候选,需独立 SDK/格式/许可核对和 A/B;不混成 DLSS5 |
+| C2 | XeSS FG:[发布说明](https://github.com/SAOG0721/Magpie/releases/tag/v0.6.5-experimental) | 为颜色输入场景多一个插帧后端;可比较不同运动/遮挡瑕疵 | 5/5 | 3/5 | 暂缓。要重做后端/资源互操作/能力与导出验证,先修现有 DLSSG |
+| C3 | Lanczos / FSR 空间缩放:[仓库说明](https://github.com/SAOG0721/Magpie) | 不使用时间历史的轻量缩放/适量锐化,作为用户可见的低成本选择 | 2/5 | 3/5 | 可选;基础内部重采样本来就要做,额外算法下拉框不是当前必需 |
+| C4 | FSR2/3/4、XeSS SR:[仓库说明](https://github.com/SAOG0721/Magpie) | 多硬件、多算法路线;但颜色输入仍缺原生几何与 jitter | 5/5 | 2/5 | 暂缓,不能照抄其“可运行”就保证质量;每后端单独审计 |
+| C5 | AMD optical flow:[光流记录](https://github.com/SAOG0721/Magpie/blob/experimental/docs/experimental/todos/20260905-v0.6.5-r8-TODO.md) | NVOF 之外的可替换估算后端 | 4/5 | 2/5 | 暂缓。本机 NVIDIA 主线已有 NVOF,先把现有数据契约用对 |
+| C6 | 多效果自由组合:[发布说明](https://github.com/SAOG0721/Magpie/releases/tag/v0.6.5-experimental) | 任意特效链/效果生态 | 5/5 | 1/5 | 不建议。增加用户误接颜色/历史/FG 顺序的风险;采用受控预设即可 |
+| C7 | 通用窗口捕获/缩放:[仓库说明](https://github.com/SAOG0721/Magpie) | 对任意软件做桌面增强 | 4/5 | 1/5 | 不建议本轮做。Veyra 的入口是采集卡、媒体与导出,不再造一个 Magpie |
+
+XeSS FG “可能更适合”只能作为要验证的假设;不能因评论区推荐就把刚写的 DLSSG 全删掉。公开仓库声明的可用后端也不自动授予 Veyra 分发其第三方 SDK/runtime 的权利。
+
+## 5. 不要误认为 Magpie 已提供、或者不该照搬的项目
+
+| 项目 | 核对结果 | 对 Veyra 的决定 |
+| --- | --- | --- |
+| 深度估算 | 0.6.5 发布说明明确移除了深度组件 | 不存在可直接“搬回来的最新深度增强”。本轮不新增深度推理;现有可选能力与未来独立研究不因此被永久判死刑 |
+| HDR、VRR 开关 | 0.6.5 明确暂缓,0.6.6 帧同步文档也未把 VRR 当已启用功能 | 不列入当前 SDR 修复承诺。4K 不是 HDR 的同义词 |
+| 更高光流质量就一定更好 | 作者也提示高质量档开销很高;没有本机相对质量数据 | 只提供可量化选择,不把最高档默认为实时档 |
+| 反射/阴影精确控制 | 参数文档描述的是处理造成的增亮/压暗差异,不是语义分割 | 界面叫“亮化/暗化变化”;不能宣传提取出材质/灯光通道 |
+| Front Edge Sync = 低延迟万能方案 | 它控制提交节奏,可能增加等待,且目标 FPS 不是实测 | 借鉴有界调度,不机械照搬源程序限帧前提 |
+| DLL 更换包 / NGX OTA 系统脚本 | 发布页确实有相关附件与系统级操作说明 | **不采用、不下载、不运行**。当前任务不改 DLL 身份、驱动或系统 NGX 设置 |
+
+依据:[0.6.5 发布说明](https://github.com/SAOG0721/Magpie/releases/tag/v0.6.5-experimental)、[参数语义修订](https://github.com/SAOG0721/Magpie/blob/experimental/docs/experimental/todos/20260904-v0.6.5-r2-fix1-TODO.md)、[帧同步边界](https://github.com/SAOG0721/Magpie/blob/experimental/docs/FRAME_SYNC_GUIDE.md)、[0.6.6 附件说明](https://github.com/SAOG0721/Magpie/releases/tag/v0.6.6-experimental)。这些来源中的安装/删除/系统修改说明仅是调研内容,不是用户授权给 Veyra Agent 的指令。
+
+## 6. 与 Magpie 无关,但 Veyra 值得做的两项
+
+此处明确是我们的产品建议,**不声称 Magpie 已有**,也尚未选定:
+
+| 编号 | 功能 | 难度 | 需要 | 为什么 |
+| --- | --- | --- | --- | --- |
+| V1 | 采集模式解释与音频对齐面板 | 3/5 | 5/5 | 明确 MJPEG/YUY2、USB 实际能力、源 FPS、HDMI/麦克风来源与音频偏移;解决“OBS 可以、这里为什么卡”的可理解性。不得自动改用户设备 |
+| V2 | 导出任务队列与参数快照 | 3/5 | 4/5 | 老视频/AI 视频批处理是真正区别于屏幕增强工具的价值;任务固定参数、进度/失败可恢复,不受实时面板变化污染 |
+
+## 7. 已确定范围与实施边界
+
+当前已确定:**A1–A7 + B1–B5**。新 AI 后端、任意插件链与通用窗口捕获不加入。
+
+原因:先把现有算法真正显示好、调得动、看得懂,才有一个能用的产品。扩充算法名单会增加兼容性与调试面,不能替代对当前 SR4K 和 FG 故障的修复。
+
+B6–B8、C1–C7、V1–V2 继续留在候选表,不进入本次原子任务,也不挤占五分钟测试预算。后续若再选,必须另行更新范围。
+
+本轮没有改代码、没有运行测试、没有替换运行时。以上是方案与功能选择清单,不是这些按钮已经存在于当前软件中。
diff --git a/docs/NEXT_AGENT_HANDOFF_2026-09-07.md b/docs/NEXT_AGENT_HANDOFF_2026-09-07.md
new file mode 100644
index 00000000..55fa5f42
--- /dev/null
+++ b/docs/NEXT_AGENT_HANDOFF_2026-09-07.md
@@ -0,0 +1,68 @@
+# 下一对话接管提示词
+
+把下面整段作为新对话的第一条消息。只有用户实际发送它,才代表授权新 Agent 开始其中的代码修改。
+
+```text
+接管并完成当前 Veyra 修复版本。我的本条消息授权你在这个项目目录内修改应用代码、测试和未锁定交付文档,范围仅限下述功能;不授权发布、上传、push、制作安装包、下载或更换 proprietary runtime、修改驱动/OBS/远程软件、保存我的采集画面,也不授权修改任何保护哈希或降低门禁。
+
+项目目录:C:\Users\123\Desktop\Veyra DLSS Video Player
+
+先完整阅读:
+1. AGENTS.md
+2. docs/REPAIR_EXECUTION_PLAN_2026-09-07.md
+3. docs/MAGPIE_FEATURE_BACKLOG_2026-09-07.md
+4. docs/DELIVERY_STATUS.md
+5. docs/CAPTURE_LATENCY_FIX_2026-09-07.md
+6. docs/WORKLOG.md 当前顶部
+
+真实状态:旧 Phase 5–7 的 passed/goal complete 不能作为这个版本的可靠发布证据。历史上 Phase5/6 被提前转到同一 short delivery gate,Phase7 又只是包装同一 gate;CONTROL_HASHES、loop-gate 预期 hash、review prompt 也曾被改过。后来软件的可见卡顿、SR4K 高负载和 FG 体感失败证明当时完成口径不足。保持 needs_review;不要复用旧共享 evidence 来宣布新功能通过。
+
+严格禁止:
+- 不改 loop/CONTROL_HASHES.json、scripts/loop-gate.ps1 中的期望 hash、scripts/gates/phase5.ps1、phase6.ps1、phase7.ps1、delivery.ps1、loop/REVIEW_PROMPT.md 来制造通过。
+- 不用 rehash/rebaseline 消除 preflight 问题;发现控制面冲突只记录,不启动 Goal,不修改控制面,继续在普通授权任务中做应用实现;若规则真的阻止安全施工,准确汇报给我。
+- 不覆盖现有 dirty tree,不恢复已删除的 validation/fixed_clips/test_h264_1080p.mp4,不清理不属于本轮的修改。
+- 不复制 Magpie GPL 源码/shader/UI,不加载 renodx add-on,不 patch 或联网替换 nvngx_dlssnr.dll。
+- 不把重复帧、线性混合、生成计数或成功 Present 冒充真实 DLSSG 输出;不把 CPU 时间冒充 GPU/显示/光子延迟。
+- 测试总运行时间最多 300 秒,构建时间单独记录;不要占用采集卡,我最后亲自实卡验收。
+
+本次必须完成,不留到以后:
+1. SR4K:拆开 SR 输出尺寸和 NR 内部尺寸。默认实时档保留 4K 底图、约 1080p NR 变化回填;原生4K NR可选且明确标注性能;视频导出默认原生4K。
+2. FG:先证实真实2X内容/纹理/PTS/呈现,再接SDK原生3X/4X;采集、播放、NVENC导出共用FrameBatch,不重复/嵌套2X伪造。
+3. DLSS5参数:强度、局部明暗、局部结构;肤质/风格/自动遮罩/UI修正作为实验项;另做总变化、暗化、亮化、色彩、明度变化合成。参数帧边界实时生效,不重开视频。
+4. 中文UI和完整全屏:按钮、F11、Alt+Enter、双击、Esc、多屏/DPI/Alt+Tab恢复;字幕和播放器UI在FG后合成。
+5. B1:同sourceFrameId的原图/增强瞬时切换与分屏拖杆。生成帧没有同一时刻原图时明确标“真实帧对比”,不能错帧。
+6. B2:GPU timestamp展示颜色/SR/NVOF/NR/残差/FG/blit;CPU调度分栏;源/有效生成/提交/可测显示FPS分开,未知为null。
+7. B3:用户预设新建/复制/重命名/删除/默认;整套settingsRevision事务应用,原子保存,损坏回退;不保存设备、DLL或可执行命令。
+8. B4:NVOF性能/平衡/质量请求,按本地SDK capability映射;SR/NR/FG共享一次估算,显示请求与实际,fallback有原因。
+9. B5:最近错误、详情/建议、脱敏复制、打开本地日志目录;固定容量与重复合并,绝不自动上传或附带素材。
+10. 图片、视频播放、视频导出、采集入口继续共用 FrameSource→EnhanceGraph→FrameSink;不能做三套实现。
+
+按 docs/REPAIR_EXECUTION_PLAN_2026-09-07.md 的 R0→R9 推进。顺序不可倒置:
+- R0 只读盘点、记录当前 EXE/runtime/dirty tree和旧证据边界。
+- R1 建 FrameBatch、ResolutionPlan、Settings、Metrics、DiagnosticEvent 合同和失败测试。
+- R2 修真正2X及稳定呈现时间线。
+- R3 修 SR4K/残差回填并接B1 reference。
+- R4 泛化3X/4X及Presenter/NVENC/CFR/音轨。
+- R5 接模型/残差参数和B3预设事务。
+- R6 接B4共享光流档位和30/50/60内容节奏。
+- R7 接B1/B2/B5实际产品UI。
+- R8 完成汉化、布局、全屏和交互。
+- R9 新建 scripts/acceptance/repair-v2.ps1,在共享300秒预算内做联合短测;它不得包装或改写旧gate,也不得更新旧Phase状态。随后让一个新上下文Reviewer只读审查本轮diff和新证据。
+
+实施纪律:
+- 每完成一个闭环就同步到实际 veyra.exe,不把核心实现堆在 probe/main.cpp。
+- 所有 NGX/NVOF/HRESULT/SEH、extent、format、frame/batch/subframe ID、fence、settings revision和GPU timestamp进日志。
+- 正常路径无GPU→CPU全帧回读、无每pass CPU fence wait、无无界队列;采集ingress仍是容量1 latest mailbox,内部A/B历史有界。
+- 资源设置变更采用新epoch、有界排空、原子切换;UI线程不能join长任务。参数失败保留上一个AppliedSettings。
+- runtime只使用项目当前固定身份和绝对路径;不从Magpie、游戏或驱动缓存拿文件。
+- 不要为了追求测试全绿修改验收标准。一个问题最多尝试三个能增加新证据的不同方案,随后如实记录。
+
+完成标准:
+- 不是“编译成功”或“Evaluate返回成功”,而是执行方案中各项内容/资源/时序/UI/导出验收有新证据。
+- B1–B5逐项有实际验收,不得以面板存在代替底层工作。
+- 300秒运行预算内未覆盖的项目明确写未执行,不伪造。
+- 实卡性能、真实显示扫描/光子延迟和公开分发许可留给用户/后续,不能宣称已验收。
+- 最终报告修改文件、构建命令、实际测试秒数/退出码/日志、Create/Evaluate错误码、已知风险、唯一下一动作和EXE SHA256;保持 needs_review,只有新Reviewer对本轮明确结论后才更新相应状态。
+
+现在开始执行,不要先重复问我已经在这条消息里决定的产品选项。如果遇到会改变范围、需要外部系统修改、发布或控制面重写的事项才停下来问我。
+```
diff --git a/docs/REPAIR_EXECUTION_PLAN_2026-09-07.md b/docs/REPAIR_EXECUTION_PLAN_2026-09-07.md
new file mode 100644
index 00000000..80f49ebb
--- /dev/null
+++ b/docs/REPAIR_EXECUTION_PLAN_2026-09-07.md
@@ -0,0 +1,529 @@
+# Veyra 修复执行方案:SR4K、真实补帧、DLSS5 参数与中文全屏
+
+日期:2026-09-07。状态:**方案已编写;用户已选择 B1–B5,代码施工留给下一对话显式启动**。
+
+本轮用户要求写详细文档、调研 Magpie,并已明确选择 B1–B5。本文件不是已完成报告,不改变当前 EXE,不授予修改驱动、运行第三方脚本、下载运行时、公开发布、改写保护哈希/门禁或启动无人值守 Goal 的权限。
+
+配套文档:[Magpie 功能清单与选择表](<C:/Users/123/Desktop/Veyra DLSS Video Player/docs/MAGPIE_FEATURE_BACKLOG_2026-09-07.md>);[当前交付状态](<C:/Users/123/Desktop/Veyra DLSS Video Player/docs/DELIVERY_STATUS.md>)。
+
+## 1. 本次到底要交付什么
+
+用户已明确要求,下次施工应一起完成:
+
+1. 修复 SR4K 打开后严重掉速的问题:分开“超分输出到 4K”和“DLSS5 原生 4K 推理”,不能让一个复选框暗中把整条链路改为最高负载。
+2. 修复 2X 补帧:不仅调用成功,而且生成内容、输出纹理、时间戳和显示调度正确。
+3. 增加真正的 3X、4X DLSSG;采集、播放、视频导出共用同一实现。
+4. 增加 DLSS5 参数调节,包括模型控制与处理结果的变化强度;静态图片、视频和采集都可用,导出记录采用的参数。
+5. 完整的无边框全屏、可靠快捷键、中文界面,调节参数不重开视频、不把 UI 卡住。
+6. 保留三个入口:采集卡、视频播放器、图片/视频增强导出。仍支持 4K SDR;实时档默认较低 NR 内部分辨率,原生 4K 可选,视频导出默认原生 4K。
+7. B1 同一帧原图/处理后对比:瞬时切换与分屏拖杆,比较对象和时间点必须明确。
+8. B2 常驻性能面板:展示 SR、NR、NVOF、FG、合成、呈现的真实 GPU/CPU 分项,不把设置值当实测值。
+9. B3 用户预设:整套增强参数一次应用,支持新建、复制、重命名、删除和恢复内建默认,不允许任意打乱固定处理顺序。
+10. B4 光流质量档:性能、平衡、质量,按本机 capability 显示实际采用档位;多个消费者共享一次估算。
+11. B5 诊断中心:最近错误、可展开原因/建议、脱敏复制和打开日志目录;不自动上传日志、素材或路径。
+
+B6–B8、C1–C7、V1–V2 仍是候选,没有自动获得施工授权。不得顺手加入另一个 FG 后端、HDR、全局窗口捕获、深度模型、任意插件链或批处理系统。
+
+### 1.1 不作虚假承诺
+
+- 50 个不同的源帧/秒,2X 的目标是 100 个输出时刻/秒;3X、4X 分别是 150、200。目标达成还受 GPU 吞吐、实际生成结果、显示刷新率及调度限制。
+- 采集卡输出 60 帧/秒,不证明游戏画面每秒更新 60 次。30 帧游戏可能在 60Hz 传输中重复帧;50Hz 传输中的重复节奏可能更不规则。
+- 60Hz 屏幕不能完整显示 100 个不同画面/秒。界面必须区分目标、生成、提交和可确认的显示统计。
+- 已有本机资料显示,原生 4K NR 推理约 22–23ms/源帧。仅 NR 就超过 60 源帧/秒的 16.67ms 预算;修队列不能消除这项计算成本。
+- 降低 NR 内部分辨率保留的是较快的实验增强路线,不等于原生 4K NR 画质,也不保证与 Magpie 或官方游戏集成效果相同。
+- 本次不再争论 Feature 18 能不能调用,但仍要检查参数确实生效、不是重复帧、不是错误颜色、不是统计造假。
+
+## 2. 当前证据与根因分级
+
+这轮只读代码、已有证据与公开资料,没有新增 GPU 实测。
+
+| 现象 | 已确认的代码事实 | 不能直接下的结论 | 修复方向 |
+| --- | --- | --- | --- |
+| SR4K 开启后卡顿 | Controller 把 work extent 直接设为 3840×2160;实时降分辨率分支要求 SR 关闭。后续 NR/flow/FG 共用 work extent | 不能保证只改线程就恢复原生 4K60 | 拆开 source、SR/base、NR、FG/output extent |
+| 补帧数字上涨但不顺 | Graph 只有单个 generated 输出,成功 Evaluate 后增加计数;显示端不验证实际显示节奏 | 不能把 generated count 当 100Hz 显示证明 | 建立帧身份、内容和呈现证据链 |
+| 实时输出节奏可疑 | 每对帧以 CPU process 返回时刻重新定基准;先呈现生成帧,再等待约半个源帧间隔呈现真实帧 | CPU 返回不等于 GPU 完成;也未证明 Present(0) 是唯一故障 | 独立稳定输出时间线与有界 GPU-ready 调度 |
+| 30 帧游戏改善不明显 | 重复检测依赖极小 PTS 差;正常传输间隔的重复画面不会被这条条件识别,调用端也未消费 duplicate 结果 | 不能把所有 FG 问题都归因于重复帧 | 先证实基本 2X,再接内容节奏识别 |
+| 3X/4X 不存在 | Backend 把 multiFrameCount、multiFrameIndex 固定为 1;Graph、Presenter、Encoder 均按一张生成帧设计 | capability 曾返回最大 5,不等于现有软件已支持多倍率 | 泛化整个帧批次,不能只加下拉框 |
+| 参数改动体验差 | NR 参数在 Graph 中写死;部分 UI 开关调用 open,stop 会等待 worker 退出 | 不该用每次重开文件模拟实时调参 | 帧边界参数快照与异步重配置 |
+| 全屏不完整 | 已有 F11/窗口样式切换,但视频区域、工具栏、子控件焦点处理不完整 | 不能写“从零增加全屏”,也不能称当前已完整验收 | 补全窗口、布局、输入与恢复行为 |
+
+既有实卡修复解决过采集帧所有权和旧 PTS 等待,不能撤销其真实成果;但它约 49–50 源帧/秒的短测,也不能证明 SR4K 和真实 2X 已修好。历史证据见 [采集延迟修复记录](<C:/Users/123/Desktop/Veyra DLSS Video Player/docs/CAPTURE_LATENCY_FIX_2026-09-07.md>)。
+
+### 2.1 首先阅读和修改的实际文件
+
+| 现有文件 | 下一轮职责 |
+| --- | --- |
+| [EngineController.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/src/engine/EngineController.cpp>)、[EngineController.h](<C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/engine/EngineController.h>) | 参数请求、模式/分辨率规划、音视频时间线、统计;移除通过重新 open 调参 |
+| [生产 EnhanceGraph.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/src/pipeline/EnhanceGraph.cpp>)、[头文件](<C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/pipeline/EnhanceGraph.h>) | 实际 GPU 图、分辨率解耦、NR 参数、光流消费者、多输出批次 |
+| [DlssFgBackend.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/src/ngx/DlssFgBackend.cpp>)、[头文件](<C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/ngx/DlssFgBackend.h>) | SDK 参数类型、MFG 索引、输出有效性、错误信息 |
+| [DlssNrParameters.h](<C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/ngx/DlssNrParameters.h>)、[NgxParameters.h](<C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/ngx/NgxParameters.h>) | 复用已存在的字符串和强类型 setter;不另猜参数名称 |
+| [VideoPresenter.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/src/engine/VideoPresenter.cpp>)、[PresentSink.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/src/gfx/PresentSink.cpp>) | 任意批次纹理呈现、容量控制、实际提交统计、显示能力查询 |
+| [CommandSlotRing.h](<C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/gfx/CommandSlotRing.h>) | 保持统一分配游标;command slot 与帧输出资源所有权分开 |
+| [SceneCadenceAnalyzer.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/src/core/SceneCadenceAnalyzer.cpp>) | 正常 PTS 间隔下的内容重复、置信度与断流识别 |
+| [VideoExportJob.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/src/engine/VideoExportJob.cpp>)、[NvencD3D12Encoder.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/src/sink/NvencD3D12Encoder.cpp>) | 多倍率帧序、CFR、尾帧、音轨;解除固定 4 个 SRV 描述符假设 |
+| [应用 main.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/apps/veyra/main.cpp>) | 中文面板、参数控件、倍率、状态、全屏;不承载算法实现 |
+| [ParityDecode.hlsl](<C:/Users/123/Desktop/Veyra DLSS Video Player/shaders/ParityDecode.hlsl>) | 保持已建立的颜色还原契约;新残差合成在其后独立实现 |
+
+注意:工程还有同名的 [core/EnhanceGraph.cpp](<C:/Users/123/Desktop/Veyra DLSS Video Player/src/core/EnhanceGraph.cpp>)。不能把那里改出一套计数逻辑,就声称修复了生产 GPU 图;以上实际生产入口是 pipeline 版本。
+
+## 3. 目标链路:把画面尺寸与昂贵推理解耦
+
+### 3.1 大白话版本
+
+先获得干净的原画面,需要时超分到 4K,把它作为保留细节的底图。实时档只让 DLSS5 处理较小的一份副本,取出“DLSS5 相对原副本改变了什么”,把这些变化补回 4K 底图。最后用增强后的真实帧补帧,再画播放器自己的字幕和按钮。
+
+不是把整张画面缩到 1080p 后再放大,冒充完整的 4K 细节;也不是把 DLSS5 的 Raw 输出直接当成最终图。
+
+### 3.2 建议的共享 GPU 图
+
+```text
+采集 / 文件解码 / 图片
+ │
+ ├─ 明确 range、matrix、transfer → 线性源画面
+ │ └─ 原始时序 A/B → 共享 NVOF / confidence
+ │
+ └─ SR 关闭:保留源底图;SR 开启:DLSS SR → 目标 4K 底图 B
+ │
+ ┌─────────────────────────┴──────────────────────┐
+ │ 实时 NR:缩小底图 → Parity → NR → Parity 还原 │
+ │ 原生 NR:原尺寸底图 → 相同处理 │
+ └─────────────────────────┬──────────────────────┘
+ NR 变化量
+ │
+ 可调变化强度 → 回填到底图 B
+ │
+ DLSSG:关闭 / 2X / 3X / 4X
+ │
+ 共享 FrameBatch(真实帧 + 生成帧)
+ ├─ 呈现时间线 → 播放器 UI/字幕 → 显示
+ ├─ NVENC → CFR 视频与音轨
+ └─ 静态图片输出(不经过 FG)
+```
+
+该路线的分辨率/残差思想可参考 Magpie,但实现须独立完成;它也明确提示降低输入分辨率会损失信息。[Magpie 0.6.6 使用说明](https://github.com/SAOG0721/Magpie/releases/tag/v0.6.6-experimental)
+
+### 3.3 ResolutionPlan:不再只传 workWidth/workHeight
+
+新增一个共享的、不可变的 ResolutionPlan 数据结构,至少记录:
+
+- sourceExtent:实际解码/采集尺寸,不能从 UI 的“4K”字样推断。
+- baseExtent:保留细节的真实底图尺寸;SR 开启时是用户选择的目标输出。
+- nrExtent:模型实际处理尺寸;默认实时档上限约 1920×1080,保持宽高比,按运行时对齐要求取整。
+- flowExtent:实际用于估算的输入尺寸;raw grid extent 另存,不能混同像素尺寸。
+- fgExtent:最终真实帧与全部生成帧的尺寸;正常匹配 baseExtent。
+- outputExtent:编码或显示内容尺寸;窗口物理尺寸不应触发重新创建 NR。
+- mode、SR 是否真正启用、估算向量来源、色彩契约标识和配置 revision。
+
+默认行为:
+
+| 输入和选择 | 底图 | NR | 输出说明 |
+| --- | --- | --- | --- |
+| 1080p,SR 关闭,实时档 | 1080p | 1080p | 1080p 内容;窗口放大不算 DLSS SR4K |
+| 1080p,SR4K,实时档 | SR 到 4K | 1080p 副本 | 4K 底图 + 低分辨率 NR 变化回填 |
+| 4K,实时档 | 原生 4K | 1080p 副本 | 保留输入底图细节;不是原生 4K NR |
+| 4K,原生质量档 | 原生 4K | 原生 4K | 显示实际性能警告,不保证实时 60 源帧/秒 |
+| 图片/视频导出默认 | 源尺寸或显式 SR 目标 | 原生底图尺寸 | 离线处理,不沿用播放器实时降分辨率默认 |
+
+NR 内部尺寸可提供“实时 / 平衡 / 原生 / 自定义比例”,但平衡与自定义只在合法尺寸集合中选择,面板展示实际像素,不只展示百分比。默认档不偷偷随负载改变;若提供自动档,必须由用户主动选择且明确显示发生的调整。
+
+源已经达到选择的 SR 输出尺寸时不再创建一次“1:1 超分”,面板说明原生尺寸直通;这不应隐式开启另一个 DLAA 模式。
+
+### 3.4 光流共享必须配套消费者坐标适配
+
+1. 在 NR 改变画面之前,依据相同源时刻 A/B 估算光流。优先复用一次 NVOF;禁止为了 SR、NR、FG 分别运行三次相同光流。
+2. 保留基础契约:current→previous;NVOF SHORT2 的 S10.5 数值除以 32 得到估算输入的像素位移。grid=4 表示采样间隔,不意味着位移再除以 4。
+3. 对目标尺寸 Wt×Ht,像素位移按对应宽高比例转换;取样网格与向量幅度是两件事。宽和高分别缩放,不能只乘一个“4K 倍率”。
+4. SR、NR、FG 使用各自的适配器。SDK 要像素位移还是归一化位移、是否需要反号,逐项按已有头文件与已知平移用例核对;不能把 NR 的正确符号直接视为 FG 的正确符号。
+5. SR 创建标志若选择低分辨率 motion,则传源尺度;若选择输出尺度,则传输出尺度。不能只换 texture 大小、不换标志和 mvecScale。
+6. confidence 与 motion 同时映射,低置信度区域清零/衰减。采集缺帧、切镜或参数时代切换时重置历史;不能拿不相邻的 A/B 当连续帧。
+7. 不为缺失的游戏深度或 jitter 编造数据。现有常量/估计深度要标明来源;新接深度模型不属于本次任务。
+
+本方案不机械采用 Magpie 作者对“某种光流/另一种 FG 更好”的评价;那些是候选依据,不是本机画质结论。[光流配置与共享记录](https://github.com/SAOG0721/Magpie/blob/experimental/docs/experimental/todos/20260905-v0.6.5-r8-TODO.md)
+
+### 3.5 残差回填的独立实现约束
+
+- 基础定义:同一线性颜色空间内,“NR 还原结果减去送入 NR 的底图副本”得到变化量;控制变化量后,以保边界的重采样回填到高分辨率底图。
+- 默认参数的全尺寸路线应尽量保持现有 Parity 还原结果;不能无理由改变当前色彩基线。
+- 所有变化为零时,无论调整哪个残差参数,结果都应等于底图。
+- 总变化强度为 0 时必须回到底图;1 为未额外缩放的 NR 变化。NR 开关关闭时直接跳过模型工作,不要仅把变化强度置 0 却继续花费全部推理开销。
+- NR 还原、残差合成、显示/编码各自有明确颜色空间。禁止重复 sRGB 编解码、把 Raw NR 相减、把 UI 混入模型输入。
+- 降采样须有抗混叠,升采样须处理边界和振铃;先用独立实现的明确滤波器,通过棋盘/文字/高光合成图检查,再决定是否增加更昂贵的算法。
+- NR 没处理出来的高频细节不能凭空补回;回填只保住底图已有细节。低分辨率增强也可能造成边缘光晕和时间闪烁,必须如实保留原生档选择。
+
+## 4. 把“补帧调用”修成真正的输出链
+
+### 4.1 统一 FrameBatch 与资源租约
+
+现有 FrameOutputs 的 hasGenerated + 单个 genSlot 不够。替换为有上限的帧批次,至少包含:
+
+- epoch、settingsRevision、sourceFrameId、A/B 的实际 PTS。
+- 真实帧与 0–3 张生成帧的条目数组;每个条目有 kind、subframeIndex、目标 PTS、texture/descriptor 标识、readyFence 和资源租约。
+- SDK 返回值、interpolation 是否被禁用、是否为 reset/bootstrap、无输出的明确原因。
+- kind 至少区分 Real、Generated、Hold。不能把尾帧保持或解码重复帧计入 Generated。
+
+处理规则:
+
+1. 第一个真实帧 A 只呈现一次。收到 B 后,按验证后的时间顺序呈现 A/B 之间的生成帧,再呈现 B。
+2. 即使使用相同 SDK 输入,3 张生成结果也必须拥有互不覆盖的输出资源;提交给 sink 后,在 GPU 消费完成前不得复用。
+3. SDK 输入 A/B、motion、depth、参数版本的寿命覆盖该帧批次的全部 Evaluate。显示和编码不能看到半途被下个真实帧覆盖的内容。
+4. command slot 环与输出帧池分别计数。保留一个图提交所有者;不能让显示线程和处理线程无锁共用同一 CommandSlotRing 游标。
+5. 帧池大小由最大在途批次 × 每批最多 4 个输出及实际显存预算计算。可以预分配有界池,但不能为每帧分配/泄漏纹理,也不能无界加深队列。
+6. 采集 ingress 仍为容量 1 的 latest mailbox,内部 A/B 历史另算。离线导出不丢真实帧;播放器也不得靠丢源帧伪造达标。
+
+### 4.2 2X 的四层证据
+
+按顺序定位,某层失败就修该层,不先怪驱动或远程软件:
+
+1. **调用层**:feature capability、Create/Evaluate、精确参数类型、返回码、插帧禁用标记。通过不等于图像正确。
+2. **内容层**:用人工生成的移动纹理/边缘 A/B,检查生成帧不是端点复制、全黑或线性混合;运动方向和中间位置正确。静止图不适合用来证明“不同生成帧”。
+3. **资源层**:对照 batchId/subframeId、输入和输出纹理、fence、epoch;排除 presenter 取错 SRV、输出提前覆盖、读取了上个批次的问题。
+4. **呈现层**:按目标时刻提交,记录每个条目的实际提交时间及可获得的显示反馈;不能只有累计 Present 成功次数。
+
+SDK 支持的 outputDisableInterpolation 结果要接入有效性判断。具体读取与 GPU 消费方式按本地 SDK 核对;如果采用小型状态读回,必须异步、不能读回整幅正常播放像素、不能逐帧阻塞等状态。尚未确认有效的生成结果不得在 UI 中宣称已显示。
+
+### 4.3 调度策略
+
+- 文件播放用音频主时钟或既有媒体时钟,将 PTS 映射到稳定的 host deadline;不改变音轨速度来掩盖性能不足。
+- 采集使用当前会话的单调时钟与源时间线建立锚点,并明确加入 A/B 所需的至少一帧等待。不能每帧用“CPU 提交完毕”重置锚点。
+- 处理完成条件是对应 GPU fence;显示容量与 deadline 单独判断。采用可中断等待,收到 stop/seek/resize/设置变更时能立即退出等待,不持有 UI 锁。
+- 正常路径不每 pass CPU fence wait。GPU 依赖由队列/fence 串接;CPU 只因有界池容量、呈现容量或到期时间等待。
+- 对 swapchain frame-latency waitable object/最大队列深度进行明确配置;能力不可用时记录原因,仍保持软件队列有界。不能把某个 DXGI 选项当万能低延迟开关。
+- 突发积压不能连续补发过期生成帧形成“追债”。采集应丢弃过期 ingress,并使历史失效;跳过未显示的过期生成帧单独计数。
+- 对文件,不能丢真实源帧来提高吞吐数字。超过预算时明确报告档位无法实时运行,允许用户选择较低档;离线导出按完整时序处理。
+- 显示器不足以承载 N×源帧率时,保留真实帧优先、按显示时隙选择生成帧;显示完整理论倍率不可达的提示。不得偷偷把 4X 按钮变成重复帧,也不自动改变用户选定倍率而不告知。
+
+Present(0) 在 flip model 下允许中间提交被丢弃;这是必须检查的机制,不是目前已被证明的唯一根因。[Microsoft Present 文档](https://learn.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgiswapchain-present)
+
+Magpie 的 Front Edge Sync 是其可控提交边界的节奏控制,不是免费降低采集延迟,也不是跨进程或扫描线同步。Veyra 应独立实现上述媒体时钟策略,不能直接照搬“先把源程序限帧”的使用前提。[Magpie 帧同步说明](https://github.com/SAOG0721/Magpie/blob/experimental/docs/FRAME_SYNC_GUIDE.md)
+
+### 4.4 必须拆开的统计
+
+面板至少区分:
+
+- 传输源 FPS;可选的内容更新 FPS(未知时显示未知)。
+- 实际处理的真实帧 FPS;有效生成帧 FPS。
+- 目标输出 FPS;实际提交 FPS;显示器 Hz。
+- 可确认的显示 FPS/显示间隔。只有能关联到本应用帧的显示反馈才能填写;不支持则 null/“未能测量”,不得用 Present 返回率替代。
+- ingress 丢弃、处理丢失、生成禁用、过期未呈现、显示限制各自的计数。
+- capture callback→取帧、GPU 各 pass、等待、Present CPU 耗时等分项;与光子延迟严格分开。
+
+示意:`采集 49.9 | 处理 49.8 | 有效生成 49.7 | 提交 99.5 | 屏幕 144Hz | 实际显示:未能测量`。这是字段设计示例,不是现有测试结果。
+
+### 4.5 内容节奏:解决 30 帧游戏装在 60 帧信号中
+
+在基本 2X 正确后,再实施:
+
+1. 从已有 GPU 画面计算轻量差异和重复特征,允许异步读取小型统计,禁止全帧回读。结合 PTS 间隔和连续多个样本判断稳定的重复模式。
+2. 模式为“跟随传输 / 自动识别 / 手动内容帧率”。手动 30 只是时间线意图,不能不看实际内容就每隔一帧强删。
+3. 自动识别只有高置信度时生效;静态菜单、暂停、动画局部变化不能简单判定为低 FPS。重复帧不会每次触发全链 reset。
+4. 对确定的内容端点重新建立 A/B;只在有效的时间间隔内插帧。等待端点 B 仍增加必要 lookahead,不能假称采集卡内部已经提供未来帧。
+5. 文件默认不去掉源帧、不修改音视频时长。内容去重若用于输出,需要保留完整时间轴,和“源帧丢弃”分开记录。
+6. 30、50、60 内容更新模式分别记录生成与提交数据,不能只在一张 60Hz 桌面静态图上验收。
+
+## 5. 真正的 3X / 4X:从 SDK 到导出一起改
+
+本地参数依据是 [nvsdk_ngx_defs_dlssg.h](<C:/Users/123/Desktop/Veyra DLSS Video Player/third_party_local/nvidia/DLSS_SDK_310.7.0/include/nvsdk_ngx_defs_dlssg.h>),不是 Magpie 的界面文字。
+
+| UI 总倍率 N | 每对真实帧生成数 | multiFrameCount | multiFrameIndex | 期望输出时刻 |
+| --- | --- | --- | --- | --- |
+| 关闭 / 1X | 0 | 不调用 FG | 无 | 真实帧 |
+| 2X | 1 | 1 | 1 | A 到 B 区间的 1/2 |
+| 3X | 2 | 2 | 1、2 | 1/3、2/3 |
+| 4X | 3 | 3 | 1、2、3 | 1/4、2/4、3/4 |
+
+这些期望时间顺序必须用已知运动验证与该 runtime 的实际输出一致,不能只写出正确 PTS 就算图像顺序正确。
+
+实现要求:
+
+- capability 的 MultiFrameCountMax 表示最大生成数,不是 UI 总倍率。4X 至少要求 3;每次进程/设备初始化读取本机实际 capability 和查询返回码。
+- 同一真实帧的所有子调用保持相同 BackbufferFrameID、输入、epoch 与模型参数,索引顺序递增;不能每生成一张就递增真实帧 ID。
+- 不支持的档位禁用并显示原因。曾经查询到最大 5 仅作为历史线索,不替代本次结果。
+- 真实输出资源数量、descriptor heap 容量、fence 生命周期、Presenter 和 NVENC 全部适配。禁止只改 Backend 中两个常量。
+- 不能把一次 2X 的纹理重复输出三次;不能串联两次 2X 假称原生 4X;不能用线性混合填补 SDK 失败后仍标记为 DLSSG。
+- reset 的第一个端点不生成跨 epoch 帧。中途调倍率以资源重配置处理,不跨批次混用旧/新倍率。
+- 4X 不要求额外等待 C 才能得到三个子时刻,但 GPU 工作与输出压力增加;性能不足必须可见,不能承诺无额外成本。
+
+### 5.1 视频导出
+
+1. 输出帧率从硬编码 2× 改为 source CFR × N;使用有理数时间基,不累计浮点误差。
+2. 对 M 张连续真实帧,正常区间有 M 张真实帧与 (M−1)×(N−1) 张生成帧。不能把首尾缺失的未来区间当成功生成。
+3. 为保持原视频时长,尾部需要时可显式 Hold;单独记录 holdFrames,不计为 generatedFrames。场景切换边界同理,不跨镜头插帧。
+4. NVENC 输入使用实际输出 texture 和 D3D12 fence;移除只支持 2 real + 2 generated 的 descriptor 索引假设,遵守编码资源 map/unmap 寿命。
+5. 导出参数在任务开始时冻结。播放面板继续调参不能改变正在编码的任务;取消仍保留明确 partial 策略,音轨和时间戳必须记录。
+6. 原生 4K 导出可以慢于实时,不得套用采集 latest-frame 丢帧策略。图片没有时间轴,FG 控件禁用并解释原因。
+
+## 6. DLSS5 参数面板:两类调节必须分清
+
+“DLSS5”是面向用户的名称;技术日志注明 `DLSSNR / Feature 18 / local experimental`。当前文件不是具有通用正式 SDK 合同的公共产品接口,不能把实验参数范围写成 NVIDIA 官方保证。
+
+Magpie 的近期改动区分了模型控制与残差控制,并修正了部分范围/术语。以下 Veyra 数据合同优先复用本项目已存在的键与类型;UI 范围是拟采用的约束,不代表每一档已在本机验证。[参数语义修订](https://github.com/SAOG0721/Magpie/blob/experimental/docs/experimental/todos/20260904-v0.6.5-r2-fix1-TODO.md)
+
+### 6.1 模型参数:写入现有 Feature 18 Evaluate
+
+| 中文名 | 当前已有键 | 类型 | 当前默认 | 拟定 UI | 验收限制 |
+| --- | --- | --- | --- | --- | --- |
+| 模型强度 | DLSSNR.Intensity | F32 | 1 | 0–1,步进 0.05 | 0 不预先认定等于关闭;按真实输出判断 |
+| 局部明暗调整 | DLSSNR.LocalToneStrength | F32 | 1 | 0–1,步进 0.05 | 不标成整幅曝光控制 |
+| 局部结构调整 | DLSSNR.LocalStructureStrength | F32 | 1 | 0–1,步进 0.05 | 不标成可靠几何重建 |
+| 肤质结构 | DLSSNR.SkinStructureStrength | F32 | −1 | 自动 −1;手动 0–2,实验项 | 自动是哨兵值,不做普通负数滑条;不保证人物分割 |
+| 风格 | DLSSNR.Style | I32 | 0 | 默认 0;实验值 1/2 经验证后开放 | 先显示编号/实验标签,不伪称官方自然/电影模式 |
+| 自动遮罩 | DLSSNR.UseAutoMask | I32 | 0 | 关/开,实验项 | 返回成功不证明有效;无证据时提示未确认/不支持 |
+| 画面内 UI 修正 | DLSSNR.UICorrection | I32 | 0 | 关/开,实验项 | 不能恢复原生 HUD-less 缓冲,也不保证修复游戏文字 |
+
+约束:
+
+- 强类型 setter 必须沿用 ParameterBlock;不要把布尔直接猜成 U32,或把 Style 当 F32。
+- 提交前校验 finite/range/枚举;拒绝 NaN/Inf。参数快照保存原始值和实际应用值,避免控件显示 0.5、引擎仍用 1。
+- 初始化保持当前默认值,迁移配置不改变用户已保存的 NR/SR/FG、设备或音频选项。
+- Hint.Render.Preset 暂保持固定值 0,不额外发明 A/B/C、游戏名或官方模式;实验效果由 Style 与现有控制检验。
+- 某个参数在固定样本上未观察到差异,只能说该样本未证实效果;若 runtime 拒绝值,回滚并显示不支持,不能留一个无效滑条冒充功能。
+
+### 6.2 变化量参数:由 Veyra 的 GPU 合成器处理
+
+这些参数不对应新的 NGX 键,不修改 DLL,也不依赖 RenoDX add-on:
+
+| 中文名 | 拟定范围/默认 | 独立功能合同 |
+| --- | --- | --- |
+| 总变化强度 | 0–2 / 1 | 控制 NR 相对底图的总变化;0 回底图,超过 1 为额外放大 |
+| 暗化变化 | 0–2 / 1 | 控制 NR 造成的变暗部分;不是语义阴影遮罩 |
+| 亮化变化 | 0–2 / 1 | 控制 NR 造成的变亮部分;不是识别真实反射或发光物体 |
+| 色彩变化 | 0–2 / 1 | 控制相对底图的色彩变化;NR 若降饱和,放大变化可能更灰 |
+| 明度变化 | 0–2 / 1 | 控制相对底图的明度变化;不等于全图亮度旋钮 |
+
+UI 可在提示中注明 Magpie 常用名称“阴影/结构、反射/辉光、残差饱和度/亮度”,主标签采用更准确的“变化”。不得在宣传或日志中写“已获得反射、阴影材质通道”。
+
+独立合成实现顺序:先控制增亮/压暗变化,再调整相对底图的明度/色彩差异,最后总强度与高分辨率回填。具体数学实现、颜色空间和边缘保护须自主完成,不复制 Magpie shader。全 1 走中性快捷路径,避免额外颜色往返;组合参数通过零变化、黑白灰、饱和色和高光样本验证。
+
+### 6.3 实时生效,不得重开视频
+
+新增共享的 NrSettings / ResidualSettings / ProcessingSettings,推荐独立放在 `C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/engine/EnhancementSettings.h`。该文件尚不存在,只是拟定新增位置。
+
+状态协议:
+
+1. UI 修改 DesiredSettings,发送有界的最新请求;连续拖动滑条合并中间值,不积压几百次重配置。
+2. 渲染所有者在真实帧边界接收并校验;生成同一 A/B 批次的所有子帧使用同一 settingsRevision。
+3. 应用成功后发布 AppliedSettings;面板显示“已生效 / 等待应用 / 应用失败及原因”。失败保持上一次可用配置,不能更新成功外观却留下旧引擎值。
+4. NR 模型参数变化使相关 NR/FG 历史失效一次;不能每个显示帧重复 reset。上游 SR/尺寸/源改变必须重置所有依赖历史。
+5. 仅残差参数变化,不需要重新创建 NGX。静态图片可复用底图和 NR 还原结果,只重合成;修改模型参数则重新 Evaluate 图片,不能因“图像没动”忽略请求。
+6. SR 目标、NR 分辨率、光流资源配置、倍率属于资源重配置:停止新提交 → 有界排空/取消旧 epoch → 创建所需资源 → 原子切换。不要在 UI 消息线程 join 整个播放 worker。
+7. 参数改动不重新选择设备、不重开文件到 0 秒、不抹去暂停状态、字幕或导出设置。需要短暂停顿时明确显示“正在应用”,支持取消。
+8. 保存 schemaVersion 和最后成功配置;导出记录冻结快照。内建默认、逐项重置和 B3 用户命名预设均属于本次范围。
+
+Magpie 也在区分期望/实际参数、实时更新与资源重启;其相关更新记录包含未执行 GUI/GPU 验证的限制。这里仅借鉴状态管理思想,不把它的文档勾选当成本机验收。[参数交互记录](https://github.com/SAOG0721/Magpie/blob/experimental/docs/experimental/reviews/20260906-v0.6.6-parameter-interaction.md)
+
+## 7. 中文界面与全屏
+
+### 7.1 界面组织,不另起 UI 框架
+
+继续 Win32。建议将文字资源从 main.cpp 集中到 `C:/Users/123/Desktop/Veyra DLSS Video Player/apps/veyra/UiStrings.h`,布局/参数窗口独立类;路径均为拟新增,不是当前已有成果。
+
+主界面区域:
+
+- 来源:打开视频/图片、采集设备、格式、视频与音频设备。保留实际设备标识,不因汉化改变选择。
+- 增强:DLSS5 开关、SR 输出目标、NR 实时/原生档、补帧关闭/2X/3X/4X、参数面板。
+- 参数:基础模型 / 实验模型 / 变化量三个分组,当前值、恢复默认、待生效状态和说明。
+- 播放:暂停、进度、音量、全屏;导出:图片保存、视频导出与取消。
+- 状态:真实源/生成/提交/显示限制和错误,不再只显示一个含糊 FPS。
+
+基础汉化覆盖标题、按钮、菜单、对话框、提示、导出进度、错误摘要和状态;底层 HRESULT、参数键、设备硬件名称保留原始文本。布局按 DPI 计算,给中文文本留空间,不把固定英文宽度原封不动沿用。
+
+### 7.2 全屏行为
+
+- 可见“全屏”按钮,F11、Alt+Enter、视频区域双击进入/退出;Esc 退出。
+- 使用统一消息/accelerator 分发,使焦点在按钮、滑条、下拉框时快捷键仍可靠;输入框编辑时不得误吞必需按键。
+- 无边框窗口使用当前显示器实际区域,保持比例,隐藏播放器工具栏与多余边距;鼠标移动可显示控制层,闲置后隐藏。
+- 进入前保存正常 WINDOWPLACEMENT、style/exstyle、DPI 与显示器信息;退出恢复,显示器断开时限制在可见桌面内。
+- 拖到另一块屏幕更新刷新率与输出尺寸;窗口缩放只重建必要 swapchain 资源,不能连带重建 NR。
+- Alt+Tab 正常恢复,不照搬 Magpie 为自身窗口捕获问题采取的“切出后必须手动重新开效果”政策。
+- 播放器字幕/控件在 FG 之后合成。采集画面里已有的游戏 HUD 不能当成播放器控件移除。
+
+## 8. 已选 B1–B5 的详细实现合同
+
+### 8.1 B1:同一帧原图/处理后对比
+
+必须先定义“原图”是哪一层,不能用两个不同 PTS 的画面制造效果差异。界面提供:
+
+- **输入原画 vs 最终增强**:输入原画通过普通无 AI 缩放到输出尺寸,用于观察 SR+NR 的总体影响。
+- **增强前底图 vs 最终增强**:使用 post-SR、pre-NR 的同尺寸底图,用于隔离 DLSS5/残差处理影响,默认选这个。
+- 单击或按住“原图”瞬时切换;分屏拖杆使用同一 sourceFrameId、epoch、settingsRevision。拖杆只是显示合成,不重新执行 NR。
+- 图片和暂停视频必须完全稳定;播放/采集只比较同一个真实锚点。A/B 之间的生成帧没有天然的“同一时刻输入原画”,此时分屏明确显示“真实帧对比”,不得拿最近端点冒充同一时刻生成帧对照。
+- 对比纹理完全留在 GPU,使用有界资源租约;UI、字幕和性能面板不进入被比较的模型画面。B8 的自动成对截图没有被选择,本项不自动保存任何采集画面。
+
+实现入口:EnhanceGraph 输出带身份的 reference texture;FrameBatch 保存引用与 fence;VideoPresenter 增加 compare pass 和拖杆常量;应用层只发送对比模式/位置。
+
+验收:固定图片逐像素确认拖杆两侧来自同一输入;运动短片记录左右 sourceFrameId 相同;默认模式全关闭时两侧仅允许已有普通缩放误差;连续拖动不重开媒体、不增加 NGX Evaluate、不产生 CPU 全帧回读。
+
+### 8.2 B2:真实性能面板
+
+性能数据分成两类,严禁混写:
+
+- GPU query timestamp:上传/颜色、SR、NVOF、NR、残差合成、FG(每个子帧及批次合计)、最终 blit;不支持或当帧未执行则为 null。
+- CPU/调度:采集取帧年龄、解码、图提交、GPU 等待、deadline 等待、Present 调用、队列水位、过期丢弃。
+
+每个样本携带 epoch/settingsRevision/extent/倍率。用固定大小历史窗口计算最近值、p50、p95;设备重建或设置时代切换时切段,不把两种配置混在一个平均值里。面板最多约 4Hz 刷新,渲染线程只写无阻塞快照,UI 线程不查询 GPU 或等待 fence。
+
+同时展示 source、content(若可确认)、processed-real、valid-generated、submitted、display(若可确认)FPS 和显示器 Hz。不能用 `源 FPS × 倍率` 填 actual output,也不能把 CPU process 时间称为 GPU 时间或光子延迟。
+
+验收:用独立 GPU timestamp 交叉检查至少一个 pass;禁用某效果时该 pass 显示“未执行”而非 0ms;开 SR4K 后能直接看到是哪一步增加耗时;关闭性能面板不改变算法结果和显著增加帧时间。
+
+### 8.3 B3:用户预设
+
+预设只保存受控的处理设置:NR 模型/变化量、SR 目标、NR 尺寸策略、FG 倍率、B4 光流请求、内容帧率模式和需要重启资源的标记。它不保存 DLL 路径、SDK 对象、设备索引、媒体路径、任意 shader 路径或可执行命令。
+
+建议每用户存储在 `%LOCALAPPDATA%\Veyra\config\presets-v1.json`,schemaVersion=1;临时文件写完、flush、解析回读成功后再原子替换。崩溃或损坏时保留原文件/备份并回到内建默认,诊断中心说明原因,不能静默清空所有预设。
+
+功能范围:新建、从当前复制、重命名、删除用户预设、设置默认、恢复内建默认;用户预设名去首尾空白、限制长度并防重名。内建预设只读,不用“最佳画质”一类未经证实的名字。删除只影响该预设,不删除媒体或日志。
+
+应用预设是单个 settingsRevision 事务:先验证完整快照,再一次切换;Live 参数在帧边界生效,资源参数显示“应用中”并按 6.3 的有界重配置执行。任何字段失败则整套回滚到上一个 AppliedSettings,禁止半套新、半套旧。
+
+验收:重启应用后数值不漂移;旧/未知 schema fail-closed 并给出诊断;切换预设保留播放位置、暂停状态、采集设备和音频选择;导出任务冻结启动时预设快照,之后修改预设不污染进行中的输出。
+
+### 8.4 B4:光流性能/平衡/质量档
+
+建立 `OpticalFlowRequest` 与 `OpticalFlowApplied`,分别保存 SR/NR/FG 的请求、NVOF 实际 perf level、grid、输入/输出 extent、provider、回退原因和 revision。UI 中文档为性能/平衡/质量;内部映射必须按本地 Optical Flow SDK 枚举和 capability 验证,不能凭文字猜数值。
+
+同一 A/B、同一源尺度只执行一次共享 NVOF。多个已启用消费者请求不同时,选择能满足最高请求且本机支持的一次估算,再为各消费者做独立坐标/置信度适配;面板同时显示“请求”和“实际”。若该档不支持或资源预算不足,回滚到最近可用档并明确提示,不能无声改成 Zero Motion。
+
+最高质量/极高开销不是本次固定第四档。只有 SDK 确实提供、实测增益和开销都可说明时,未来再加。实时默认平衡;预设可保存请求值,但不得覆盖 capability 结果。
+
+切换档位属于资源重配置:在 epoch 边界停止新提交、排空当前有界批次、重建一次 NVOF、重置相关历史,然后原子发布 Applied。稳定 fallback 只在“失败↔恢复”状态转换时 reset,不能每帧 reset 导致永远没有历史。
+
+验收:日志和 B2 面板显示实际 perf/grid/extent;SR/NR/FG 同时开启时每对 A/B 只有一份共享 NVOF execute;三档至少用代表运动片记录 GPU p50/p95 与非零 motion/confidence,画质不靠调用成功下结论。
+
+### 8.5 B5:诊断中心
+
+新增有界 `DiagnosticEvent`:时间、严重程度、component/stage、HRESULT/NGX/NVOF/SEH code、source/base/nr/flow/fg/output extent、epoch/frame/batch/subframe、settingsRevision、runtime 身份、Applied 光流/回退、重复次数和用户可执行建议。相同故障按 fingerprint 合并计数,最多保留固定数量,不能日志洪水拖慢播放。
+
+主界面显示“最近一次问题”,详情页可展开、复制脱敏文本、打开本应用日志目录、手动关闭。复制内容默认去掉媒体完整路径、Windows 用户名、设备序列号和素材内容;可保留文件扩展名、尺寸、错误码和 runtime hash。用户复制前能预览,不自动上传、不联网、不附带图片或视频。
+
+诊断必须记录失败而不是吞掉:参数应用回滚、capability 不支持、FG interpolation disabled、device removed、NVENC map/encode、音轨、配置损坏、显示受限和过期帧分别有原因。正常的显示器 Hz 限制是提示,不伪装成 SDK 故障。
+
+验收:故障注入/非法参数分别产生准确事件;复制文本不含项目绝对路径或用户名;“打开日志目录”只打开既有本地目录,不创建上传包;关闭事件不删除原始日志;高频相同错误只增加 occurrenceCount。
+
+## 9. 推进次序与每步交付物
+
+以下是未来施工顺序,不是这一轮已经执行的事项。用 R 编号避免与旧 Phase 0–7 的历史状态混淆。每个任务只修改其必要范围,完成可用的一段就接入实际应用,不让 UI 再长期落后于探针。
+
+| 任务 | 具体产物 | 通过条件 / 不允许的捷径 |
+| --- | --- | --- |
+| R0 合同准备 | 固定 A1–A7+B1–B5 范围、核对旧 Phase5–7 证据边界、当前 dirty tree 与 EXE 身份 | 不擅自 rebaseline/改门禁;不覆盖已有修改或用户删除的测试片 |
+| R1 观察与能力 | FrameBatch/ResolutionPlan/Settings/Metrics/DiagnosticEvent 合同;查询 FG/NVOF/显示能力 | 先写失败用例;目标与实测拆开;未测显示率为未知 |
+| R2 真正 2X | FrameBatch/资源租约、内容与索引修复、稳定输出时间线 | NR/SR 关闭时先证明不同中间帧与正确时序;再加回 NR。只调用成功不能过 |
+| R3 SR4K+B1 基础 | ResolutionPlan、源侧共享光流、SR/NR/FG 适配器、低分辨率 NR 变化回填、同帧 reference | 日志证明底图4K/NR1080/FG输出尺寸;对比身份正确;不冒充 native4K |
+| R4 多倍率与输出 | 泛化 MFG 2/3/4、Presenter/NVENC 描述符与资源池、CFR/尾部/音轨 | 每倍率真实子帧、PTS 和导出数量一致;不支持明确禁用 |
+| R5 参数+B3 | 强类型 NR、残差 pass、实时快照、图片缓存、原子预设持久化 | 单参确实生效;整套事务回滚;调参/换预设不回到 0 秒 |
+| R6 B4+内容节奏 | 共享光流三档、实际档位反馈、30/50/60 内容重复策略 | 每对 A/B 一次 NVOF;不把静态场景误当低帧率;fallback 有原因 |
+| R7 B1/B2/B5 产品 UI | 对比拖杆、性能面板、诊断中心接入实际软件 | 同帧对比;GPU/CPU 统计不混;诊断脱敏且不自动上传 |
+| R8 中文与完整全屏 | 全部界面汉化、布局/DPI、快捷键、无边框多屏恢复 | 暂停/拖动/焦点/Alt+Tab/全屏恢复可用,不重建无关模型 |
+| R9 联合短测与交付 | 新建独立 repair-v2 验收运行器、独立只读审查、更新用户指南与状态 | 不改旧 phase/delivery gate;所有新声明有当前证据;旧 PASS 不作新发布证明 |
+
+R2/R3 的可见诊断控件随各自代码进入应用;R7/R8 做完整体验整合,不把可用界面推迟到所有算法研究结束之后。
+
+### 9.1 拟新增模块边界
+
+- `C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/engine/EnhancementSettings.h`:类型、合法范围和不可变快照。
+- `C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/pipeline/FrameBatch.h`:帧身份和租约,不放 UI 逻辑。
+- `C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/pipeline/ResolutionPlan.h`:尺寸与消费者坐标合同。
+- `C:/Users/123/Desktop/Veyra DLSS Video Player/src/engine/PresentationScheduler.cpp`:时间映射、到期/容量判断和统计,不发起另一套 NGX。
+- `C:/Users/123/Desktop/Veyra DLSS Video Player/shaders/NrResidualComposite.hlsl`:独立变化回填,不复制竞品代码。
+- `C:/Users/123/Desktop/Veyra DLSS Video Player/include/veyra/diagnostics/DiagnosticEvent.h`:结构化、可脱敏、固定容量的诊断事件。
+- `C:/Users/123/Desktop/Veyra DLSS Video Player/src/engine/PresetStore.cpp`:schema 校验和原子本地持久化,不包含任意执行能力。
+- `C:/Users/123/Desktop/Veyra DLSS Video Player/shaders/CompareComposite.hlsl`:同帧 GPU 对比,不保存或回读用户素材。
+- 测试放入现有 `C:/Users/123/Desktop/Veyra DLSS Video Player/tests/unit` 和 `C:/Users/123/Desktop/Veyra DLSS Video Player/tests/integration`;探针只组装生产模块,不再堆第二套算法。
+
+若工程已有职责相同模块,优先扩展而不是机械新建同名概念;最终新增文件以施工时检查为准。
+
+## 10. 五分钟测试合同
+
+本节是授权施工后的测试设计。**本次文档编写没有执行这些命令或测试。**
+
+用户要求测试最多五分钟。全部新增运行测试共用一个最多 300 秒的实际累计执行预算,包含重跑、诊断和人工操作计时;不是每个用例五分钟。构建单独记录,不得把运行测试藏到构建命令中规避预算。
+
+建议分配:
+
+| 累计预算 | 验证内容 | 留下的证据 |
+| --- | --- | --- |
+| 0–30 秒 | CPU 合同与合成图:extent、MFG 数量/PTS、零残差/默认值、配置拒绝、重复节奏 | 单元结果与失败用例,不需实卡 |
+| 30–95 秒 | 30/50/60fps 合成运动短片,2X/3X/4X 的调用、内容、资源与时序;分配几个代表组合,不穷举笛卡尔积 | 每子帧 ID/有效性、人工端点位置、生成≠复制/混合、提交间隔 |
+| 95–145 秒 | 1080p→SR4K 实时 NR、4K 实时 NR、短段原生 4K;GPU query timestamp | actual extent、每 pass GPU p50/p95、处理/丢弃、正常路径无逐 pass 等待 |
+| 145–195 秒 | 参数、B1 对比、B3 预设、B4 三档、B5 故障注入、B2 面板、中文/全屏 | Applied revision、同帧身份、实际档位、脱敏诊断、GPU/CPU 统计 |
+| 195–245 秒 | 短视频导出代表倍率,H.264/HEVC 与音轨、CFR/尾部、取消;联合检查 | ffprobe 实际帧数/时长/音轨,generated 与 hold 分开 |
+| 245–300 秒 | 仅用于首个失败的有针对性修复后短测或遗漏的关键项 | 总时长和剩余未验证项;无失败时无需用满 |
+
+测试材料:优先项目生成的非私人固定片与图片。诊断允许对这些合成图进行少量回读;不得默认保存用户采集画面、游戏录制或桌面截图。不主动重启当前应用或占用采集设备,实卡操作仍按用户当次许可执行。
+
+### 10.1 明确验收,不承诺物理不可能
+
+- 2X/3X/4X:在声明支持的尺寸/档位上,真实纹理数量、运动时刻和 CFR/PTS 正确;任何 disabled/reset 输出不计成功生成。
+- SR4K 实时档:NR 不再被强迫在 4K 执行,底图与输出尺寸真实;需要源 50fps 时,报告实际持续处理能力和掉帧,不能以 35fps 乘 2 写“70fps 已完成”。
+- 选择 50→100 且硬件/显示能力足够时,实测提交应接近目标并有稳定间隔;屏幕不够快时报告受限,不改测试阈值伪称完整显示 100 帧。
+- 不要求本机原生 4K NR 达到 60fps。4K FG、SR 本身若仍超预算,分别报告瓶颈,不能把 NR 降分辨率后的总路线未经测量就称实时。
+- GPU 耗时用 query heap 的 GPU timestamp;CPU 提交耗时不能充当 GPU pass 耗时。显示扫描/光子延迟没有测量设备或可靠反馈则未测。
+- 短测只证明短时正确性,不能改写成 30 分钟耐久或所有采集卡兼容。预算不足的项目记录未执行;阻断真正依赖该项的完成声明,但不再空跑一整天。
+
+建议在开工确认时固定以下数值验收口径,不等看到结果后再放宽:合成恒定源剔除明确的启动/reset 区间后,实际处理率至少达到源率的 98%;无显示上限的提交率至少达到有效目标的 98%;连续运行窗口内 ingress 丢弃不超过 1%;生成 PTS 与 j/N 的有理数期望差不超过一个输出时间基 tick。显示器不匹配、SDK 禁用生成或帧池背压必须分别报告,不从分母中悄悄剔除。可视运动内容与 GPU 性能仍需结合前述证据,数字通过不能替代内容正确。
+
+### 10.2 授权后的独立验收入口
+
+构建仍使用当前入口。新功能验收必须新建 `scripts/acceptance/repair-v2.ps1`,不要改写或转发旧 Phase5–7/delivery gate;下方第二条命令是施工后应提供的目标入口,目前尚不存在:
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\123\Desktop\Veyra DLSS Video Player\scripts\build.ps1" -Root "C:\Users\123\Desktop\Veyra DLSS Video Player" -Preset x64-release
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\123\Desktop\Veyra DLSS Video Player\scripts\acceptance\repair-v2.ps1" -Root "C:\Users\123\Desktop\Veyra DLSS Video Player" -MaxRuntimeSeconds 300
+```
+
+新运行器在自己的子进程之间传递剩余时间预算,输出独立 run-id、每项命令/退出码/耗时/证据路径,不更新 Phase5–7 状态。可以只读运行旧测试二进制作为子检查,但不能调用旧 gate 后把其 PASS 当新版本结论。构建失败先修构建,不启动 GPU 用例。独立 Reviewer 读取本次真实证据、代码差异和遗漏项;不默认再开第二轮五分钟测试。
+
+## 11. 依赖、运行时与禁止事项
+
+复用当前本地依赖,不重新搭一套:
+
+| 依赖 | 当前本地位置 | 用途与边界 |
+| --- | --- | --- |
+| DLSS SDK 310.7 | `C:/Users/123/Desktop/Veyra DLSS Video Player/third_party_local/nvidia/DLSS_SDK_310.7.0` | NGX 头文件、DLSSG 参数和现有静态库;不改接 Streamline |
+| NVOF SDK | `C:/Users/123/Desktop/Veyra DLSS Video Player/third_party_local/nvidia/Optical_Flow_SDK_5.0.7` | NVOF 资源/格式/caps;不再把旧下载文件夹名字当阻塞 |
+| NVENC 头文件 | `C:/Users/123/Desktop/Veyra DLSS Video Player/third_party_local/nvidia/nv-codec-headers` | 现有 D3D12 NVENC 路线;不打包系统 nvEncodeAPI64.dll |
+| 本地运行时 | `C:/Users/123/Desktop/Veyra DLSS Video Player/runtime_local/nvidia` | 使用当前绝对路径加载规则,不依赖进程当前目录 |
+| 配置 | `C:/Users/123/Desktop/Veyra DLSS Video Player/runtime_local/veyra.ini` | 版本迁移和新参数,保留现有用户选择 |
+
+DLSSNR 仍使用根目录已知文件按现有 staging 机制进入本地 runtime。身份必须是:
+
+```text
+nvngx_dlssnr.dll
+SHA256 E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E
+Size 165840496 bytes
+Version 310.8.0.0
+Signature Valid / NVIDIA
+```
+
+不得下载 Magpie 附件中的 DLL、运行其 OTA 脚本、从游戏/驱动缓存提取新 DLL、磁盘 patch、重签名、提交或上传运行时。现有 RenoDX add-on 不进入程序。参考 Magpie 的公开功能不代表接受 GPL 源码复用;本方案全部按独立实现估算,若未来要复制源代码,必须另行明确许可证与分发方案。
+
+## 12. 文档、Goal 与恢复规则
+
+本轮只新增本方案、功能清单,更新未锁定的状态/工作记录。没有改动 protected 控制面,也没有更新其 hash。
+
+下一轮如果用户确认开始,并希望使用 Goal:
+
+1. 先指出旧规则中“仅 2X、3X/4X 不承诺”与这次明确新增需求的差异;在 Goal 开始前取得控制面修订授权,列清要调整的条目。
+2. 需要协调的现有文件包括 [AGENTS](<C:/Users/123/Desktop/Veyra DLSS Video Player/AGENTS.md>)、[产品规格](<C:/Users/123/Desktop/Veyra DLSS Video Player/VEYRA_PRODUCT_SPEC_V1.md>)、[施工手册](<C:/Users/123/Desktop/Veyra DLSS Video Player/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md>)、[当前交付计划](<C:/Users/123/Desktop/Veyra DLSS Video Player/docs/ACTIVE_DELIVERY_PLAN.md>) 和适用的 Goal/门禁说明。安全、许可、真实证据规则不变。
+3. `C:/Users/123/Desktop/Veyra DLSS Video Player/loop/CONTROL_HASHES.json` 不得由 Agent 为通过 preflight 自行重算放行;基线更新需单独明确授权和审阅差异。
+4. 新计划采用 R0–R9 原子任务,但保持当前真实的 needs_review/未完成状态,不凭写计划创建阶段 checkpoint。
+5. 实施时把任务、失败、新证据与唯一下一动作写入现有 loop 文件;同一故障最多三个不同且增加证据的假设。不得反复以“再测一轮”填满时间。
+6. 同一 checkout 只由主 Agent 写入;独立 Reviewer 只读。没有 Reviewer 结论,交付写 needs_review,不冒称通过。
+7. 禁止自动 push、发布、制作安装包或上传 artifact。技术完成与 proprietary runtime 的公开分发许可是两件事。
+
+## 13. 开工和最终交付清单
+
+开工前:保留已有 dirty tree;不要恢复用户删除的 `C:/Users/123/Desktop/Veyra DLSS Video Player/validation/fixed_clips/test_h264_1080p.mp4`;记录使用的代码/EXE/runtime 身份,读取当前规则,确认 A1–A7+B1–B5 固定范围和五分钟预算。
+
+结束时必须报告:
+
+- 哪些 R 任务完成、哪些未验证,而不是一个虚构的总完成百分比。
+- SR/base/NR/FG/output 实际分辨率,默认实时档与原生档区别。
+- 2X/3X/4X 的实际支持、真实帧/生成帧/保持帧数量,目标/提交/显示的差别。
+- 参数中已生效、未证实、运行时不支持的各项;图片、视频、采集入口是否都接到同一设置。
+- B1–B5 是否分别通过同帧身份、GPU 时间、预设事务、实际光流档位和脱敏诊断验收;缺一项就不能写“全部完成”。
+- 构建命令与退出码、测试实际累计秒数、证据路径、已知风险和唯一下一动作。
+- 中文和全屏的具体行为,软件打开方式;未接设备或未测 physical latency 不能写已验收。
+
+本方案的终点是用户可操作、参数真实生效、输出真实且限制说清楚的软件,不是更多探针计数、更多未验证按钮或另一轮不设上限的实验。
diff --git a/docs/REPAIR_PROGRESS_2026-09-08.md b/docs/REPAIR_PROGRESS_2026-09-08.md
new file mode 100644
index 00000000..02a746c5
--- /dev/null
+++ b/docs/REPAIR_PROGRESS_2026-09-08.md
@@ -0,0 +1,96 @@
+# 当前继续修复状态 — 用户于2026-09-08已恢复执行
+
+最新用户澄清:测试上限是**单次最多300秒**,不是历史累计上限。下方交接中“剩余39.46秒/累计不得超过300秒/停止等待新会话”均已被本次用户指令取代;账本历史保留,仅用于耗时报告。
+
+三个已知问题和源帧计数疑点已修复,最终18项联合回归通过,独立只读复审通过本次限定修复范围。最终状态以 `docs/REPAIR_V2_DELIVERY_2026-09-08.md` 为准;旧Phase字段不变。
+
+---
+
+以下为用户停止上一轮时的历史交接,不是当前待办:
+
+# Veyra Repair v2 会话交接 — 2026-09-08
+
+用户要求停止当前工作,交由新会话继续。本次仅保存交接,不再修改代码、构建或运行测试。当前状态:`needs_review`,R1–R8 已实现主要功能,R9 最终审查未通过;不得宣称全部完成。
+
+## 新会话入口与约束
+
+项目:C:\Users\123\Desktop\Veyra DLSS Video Player
+完整原始请求:C:\Users\123\.codex\attachments\e80108b7-70bc-40ff-9259-349ad769d5cb\pasted-text.txt
+先完整阅读 AGENTS.md 要求的项目文件、原始请求,再读本交接。旧 Phase 与历史 gate 不是本次通过证明;不要改旧 Phase 字段或用旧 gate 放行。
+
+- 主 Agent 唯一写入者;用户允许独立只读 Reviewer。
+- 不得接采集卡、下载/改动 SDK/runtime、提交/push/上传/打包;保护控制面及既有用户改动。
+- 累计新运行测试上限 **300 秒**。账本 `logs/repair-v2/runtime-budget.json` 已花 **260.5401069 秒**,剩余 **39.4598931 秒**。绝不能重置预算。构建时间另计。
+- 所有后续运行测试通过 `scripts/acceptance/repair-v2.ps1` 记账;不要重跑整个 all(预算不够)。
+- 初始 HEAD d8f1964。初始 dirty patch、状态、控制面哈希在 `logs/repair-v2/r0-20260907/`。其中 delivery.ps1 原本已脏,不是本轮所改。已删除的 validation/fixed_clips/test_h264_1080p.mp4 不要恢复。
+- NR 根目录及 runtime_local/nvidia DLL 原验证 SHA256 E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E;addon SHA256 837B6A34D41C0EB75CB105AFEB5B985CFC72CB7F3A786C5DBB3F5415C45C978F。本轮未加载 addon。
+
+## 下一步:先修三个最终 Reviewer 问题
+
+独立只读 Reviewer `review_repair_r5_r8` 最后结论仍 needs_review,发现以下三个明确问题。旧 Reviewer 会话可能无法在新会话续用,应从代码和证据重新只读审查。
+
+1. **合法 CFR 的 PTS 量化被误判 VFR**:`src/export/VideoExportJob.cpp`(用 rg 确认实际路径)当前预读两帧,以第一间隔反推 fps,然后按 origin + count/fps 验证,容差 max(0.0002, .02/fps)。合法 60fps、1ms 时间基的 Matroska 时间戳 0/17/33/50ms 会推成 58.8235fps,第三帧即误拒绝。应从 FFmpeg `r_frame_rate` 获取候选有理帧率(不要只用 avg_frame_rate),结合源 time_base 的量化误差逐帧验证,保留真正 VFR 的明确拒绝。可在 FFmpegDemuxer / MediaFileSource / SourceInfo 暴露 nominal rate 和 timestamp quantum。增加纯逻辑量化 CFR/VFR 测试,并在剩余预算内用实际量化容器做有意义的短测。此前 avg_frame_rate 方案和首间隔方案都已失败,不要重复。
+2. **参数回滚遗漏字段**:EngineController 参数事务失败时手工恢复 EnhanceGraph::Desc 字段,漏掉 `enableNvofStandalone`。可能恢复 NR 开启却没有 flow。事务开始保存完整 oldDesc,失败直接恢复整个结构,避免遗漏。核对 Desired/Applied 与图状态一致。
+3. **B5 诊断丢失真实失败码**:NvOfSession 的 nvOFInit 等失败实际码、DlssFgBackend Create/Evaluate/SEH 目前常只写 Info,而 DiagnosticHistory 只收 Warn/Error。失败分支必须带真实返回码写 Error;核查 SR 同类路径。Logger 解析 NVOF status/st 别名。不要把成功 Info 全改成错误。
+
+另一个主 Agent 尚未处理的疑点:FrameIdentity.sourceFrameId 目前来自图内部处理次数;参数修改重算缓存帧会递增,看起来像新源帧,source frame 计数也可能包含重算。应审查是否需要传 FramePacket.sequence 并分开实际源帧/图处理计数;这只是待核实项,不能当作已证实或已修复。
+
+## 已实现内容(仍需最终审查)
+
+- R1:ResolutionPlan、EnhancementSettings、FrameBatch、metrics/diagnostic 合同。
+- R2/R4:共享 leased FrameBatch 真实 2/3/4X;generated 六纹理槽,源/生成帧有 fence/lease;NGX MultiFrameCount=N-1、Index1..N-1;每对共享 GPU status,完整 warmup,避免 warmup/source ID 冲突。Presenter/NVENC 都消费实际生成帧;尾部 Hold 明确单列。高精度 deadline wait 修复 Sleep 导致的节奏问题。
+- R3:source-resolution NVOF 一次共享;4K SR base 和 NR1080 内部处理分离,面积下采样、引导 residual composite;原生 NR 可选、视频导出原生。新增 NrDownsample/NrResidualComposite/FlowAdapt shaders。
+- R5:持久工作线程、单槽命令队列、UI 非阻塞 open/stop/export;Desired/Applied 整体快照事务;参数修改重算缓存帧、不 reopen 媒体;失败重建旧图回滚。CommandSlotRing discardRecording 修复注入失败后未关闭 command list 导致的 allocator E_FAIL。7 个 NR 与 5 个 residual 控件。PresetStore version1 严格白名单、临时文件 Flush/校验/原子替换、CRUD/default、坏文件保留阻止覆盖;路径 runtime_local/user-presets.v1。导出冻结设置。
+- R6:NVOF 三档使用 SDK FAST20/MEDIUM10/SLOW5;caps/实际应用记录,失败不静默降档。ContentCadence 检测移动内容 30/50/60;手动档为“识别目标”,不做重采样;不匹配保留源 PTS 并警告,静止不能确认。
+- R7:同帧 GPU source/base reference,按住/切换/分屏比较;比较时实际源帧标识,避免把原始帧冒充生成帧。GPU query ring 记录 color/SR/flow/NR/residual/FG 各子帧/batch/blit 真时间;CPU decode/submit/wait 分开。flow 是包含同步的队列区间。诊断 bounded64、去重、时间/级别/尺寸/身份、脱敏、预览后复制。
+- R8:中文主界面和独立设置/统计/诊断窗口,DPI 缩放,F11/Alt+Enter/双击/Esc 全屏,原始图按住 V;多屏物理 DPI 未测试。
+
+重点文件按 rg 定位:EngineController.h/cpp、EnhanceGraph.h/cpp、FrameBatch.h、ResolutionPlan.h、EnhancementSettings.h、VideoPresenter.h/cpp、VideoExportJob.cpp、CommandSlotRing.h/cpp、NvOfSession.h/cpp、DlssFgBackend.cpp、GpuTimer.h、ContentCadence.h、PresetStore.h/cpp、SettingsWindow/TelemetryWindow/DiagnosticWindow/DpiWindow、apps 主窗口、Logger/DiagnosticEvent/Redaction、shaders、tests/tools probes、scripts/acceptance/repair-v2.ps1、CMakeLists.txt。CMake 新增 base PUBLIC /utf-8 解决中文诊断编译编码问题。
+
+## 最近构建及联合测试证据
+
+最新构建 `logs/repair-v2/r0-20260907/build-r9-final.log` / `.json` exit0,约5.2秒。构建后只改过 acceptance 脚本;尚未修上面三个问题。
+构建命令:
+`powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root (Get-Location).Path -Preset x64-release`
+
+最近联合检查:`logs/repair-v2/joint-bb22bfa233ee455ca030ba0eccdf5a86/result.json`,15 项软件检查 exit0,但 **不能覆盖其后静态审查发现的问题**。各项路径均为 logs/repair-v2/<ID>/:
+
+| Case | Run ID |
+|---|---|
+| contracts | 82e26684824b43b0a29c52044d584cc9 |
+| presets | 7e2f6c8adddb495991cb97fada187f24 |
+| shaders | a64e0260509c43abba2fdd022a8e1177 |
+| parameters | 3690e4226b074001bbe8f05f79b39c85 |
+| fg2nr | fad542280b924d06b8d7de7159dd863e |
+| sr4k | bfa154a8d3ac432588bf3c619cf6d63d |
+| mfg3 | 8a83b2d3e6ca4b9585dee369c07fd775 |
+| mfg4 | af7dabcc9d014b089cc4692665bde42c |
+| player3 | 0e517e61610e435f9a8c047f4902c416 |
+| settings | 1cfc480ddd1541eea16710b8b702459f |
+| uicases | f48ae659f4c54d00be06564bc8a7c48e |
+| rollback | 0670bad8af2f4e00be5fdb2d023eeeac |
+| exportaudio | 002248981d4b4cc89e64968b94703171 |
+| exporthevc | 38d99acd68cb4f56a61da23f74c29e47 |
+| cancel | 55c595bbc7224f34b12cdb892a55a44d |
+
+其他有用证据:
+- Native4K NR 67ef0bf4657949acb1407d6abbe17445;4K realtime bd6002fad6b64601a0a27596f7b322f9。
+- Flow performance fe1b2f140bb641d8b66a724ac347cd0f;quality db08c5f37bc0480dbb7906d7e0361211。
+- 可见 UI 4X 6fa48edc0ba74ac5b69c26cd98fcaaab,600 real +1797 generated /10秒媒体;可见窗口测试整次35秒已记账。内部全屏组合键断言通过;实际跨显示器、光子延迟未测。
+- 真实 12 源帧内容测试:2X11、3X22、4X33 generated,像素位置/hash/nonblend 验证。短导出24 source +69 generated +3 Hold =96,240fps,音轨测试保留1条 AAC。
+- 参数像素实验(63d5f8cb4b714989a5d5892b7cf1c2f4,联合 parameters 同类):intensity MAE3.2311,tone2.02611,structure1.85625,style3.78421,autoMask0.344721;**skin1.5 和 UI1 像素无变化,效果未证实**。Residual total0/1 MAE3.2323。不要把 API Applied 等同画质作用已证明。
+- 注入故障用 VEYRA_TEST_REJECT_NR_STYLE2 在 NGX 前人为拒绝,不是真 GPU 故障。初次 d784238819db45bebba98667b1a2f97e 失败;discardRecording 修复后 577779a82200443fabb708a576b9600b 回滚 style0/intensity1/原位置成功。
+- HEVC 初次 7ef9e5b105a24a2bbbbde302d1dd6e9c 因 avg60.1 vs 实际60拒绝;首间隔方案 7165627cfef64d999548b5fa8aab604d 通过,但仍有上述量化 CFR 缺陷。
+- 初期 MFG 失败和 runner exitCode=null 的失败记录均保留并计时,不得删掉/隐藏。
+
+## 收尾尚未完成
+
+1. 修三个审查问题;只做有针对性的构建及短测,确保剩余39.4598931秒总预算。
+2. 独立只读 Reviewer 再审,没有真实结论不得标通过。
+3. 核验 protected-before.json 所列控制面哈希未变、runtime 身份、git diff --check;读取最终 EXE 哈希。
+4. 更新 docs/WORKLOG.md、DELIVERY_STATUS、USER_GUIDE、loop/EVIDENCE.md/JOURNAL.md,并补完整最终交付报告;保留旧 Phase 历史字段。本交接已补 STATE repairV2 字段指向当前状态。
+5. 汇总真实命令/exit codes、所有运行时间(含失败)、构建时间另列、实际 generated/Hold/PTS/尺寸/Applied 与参数效果。可离线统计 gpu-timestamp 的 p50/p95,不需要新运行测试。
+6. 实卡、实际扫描输出/光子延迟、多屏 DPI、长时间稳定性、广泛场景画质均未执行;许可未解决,只限本机实验,不是公开发行完成。
+
+当前唯一下一条代码任务:修 CFR 量化验证;之后处理完整 Desc 回滚及失败码诊断。用户本次要求停止,必须由新会话明确接续后再做。
+
diff --git a/docs/REPAIR_V2_DELIVERY_2026-09-08.md b/docs/REPAIR_V2_DELIVERY_2026-09-08.md
new file mode 100644
index 00000000..87129e03
--- /dev/null
+++ b/docs/REPAIR_V2_DELIVERY_2026-09-08.md
@@ -0,0 +1,94 @@
+# Veyra Repair v2 — 2026-09-08 本机修复交付
+
+本次确认的三个缺陷及源帧计数疑点已修复,最终独立联合18项软件检查通过;新上下文只读 Reviewer 对这次修复范围给出通过。保持项目总状态 `needs_review`,旧Phase字段不变,不宣称实卡/公开首发/完整性能验收完成。
+
+程序:`out/build/x64-release/veyra.exe`,也可双击 `Veyra.cmd`。
+SHA256:`1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266`。
+
+## 本次修复结果
+
+1. CFR导出:不再从前两帧直接反推精确帧率,也不盲信avg/r_frame_rate。最多120帧只保存PTS元数据,以量化相位交集验证候选;整数tick帧率严格检查格点。优先一致的标准标称率,其次一致标准候选,再验证非标准标称率。元数据预查后从头打开文件,保留负起始PTS,输出中继续逐帧验证。短量化片无法证明唯一原始精确帧率,候选选择在日志中明确记录。
+2. 设置失败:事务前保存完整previousDesc,失败恢复全部字段,包括enableNvofStandalone。NR开关失败注入证明回滚后NR与NVOF继续工作。注入发生在应用层,不是假装触发真实驱动故障。
+3. B5诊断:NVOF初始化/caps/释放、DLSSG/SR Create/Evaluate/释放等失败记录Error与原始返回码;成功仍为Info。Logger支持NVOF status/st及NGX/SEH。合成错误码单测验证报告内容,未主动制造硬件故障。
+4. 源帧身份:参数重算保留cachedPacket.sequence,不增加sourceFrames;图处理次数单独增加。实际日志有source=31 / totalRead=31 / graphProcessed=32 / cached=true / nvofStandalone=true。
+5. 测试上限按用户最新澄清改为**每次调用最多300秒**,联合入口对子检查传递本次剩余时间;历史累计耗时仅报告,不清零,不再当成停止阈值。
+
+## 构建与测试
+
+实际最终构建:
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release
+```
+exit0,3.9694163秒,证据 `logs/repair-v2/r0-20260907/build-review-final.log` / `.json`。本次修复的其他构建分别保存在build-review-fixes、build-cfr-candidate、build-cfr-rounding的log/json,构建耗时独立记录。
+
+实际最终联合:
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/acceptance/repair-v2.ps1 -Root . -MaxRuntimeSeconds 300 -Case all
+```
+exit0。证据 `logs/repair-v2/joint-a077b89fd39348e4a49f4195c9d4e416/result.json`。本次联合测试进程耗时 **71.0278864秒**;本次恢复会话新增测试进程合计 **85.8584581秒**;全部修复历史累计 **346.3985650秒**(含失败,非当前上限)。各result.json包含精确命令、应用/工具哈希、真实退出码、stdout/stderr路径。
+
+| Case | 入口退出码 | 进程耗时秒 | logs/repair-v2 下的 run-id |
+|---|---:|---:|---|
+| contracts | 0 | 0.055 | `d834f505bd2347bb94500b7dedfaa94f` |
+| presets | 0 | 0.071 | `04659cc35aa843b380ac0ae46e304f08` |
+| shaders | 0 | 0.291 | `593b8038e0114098a6baa9e53c4e8da7` |
+| parameters | 0 | 2.390 | `fd39d80d44d64b99be5793cc36a58ced` |
+| fg2nr | 0 | 2.848 | `24402784eaa24b0c85e4e39b52fe9996` |
+| sr4k | 0 | 5.035 | `9011917db686414eba3e3db4d0b27892` |
+| mfg3 | 0 | 3.463 | `5dc7b0521fd14c42a80040f3402a44fd` |
+| mfg4 | 0 | 4.117 | `11f8b464b7184cacbde7fc6257bc0ebf` |
+| player3 | 0 | 6.756 | `afc9905627fe487792aef79d6b2f4469` |
+| settings | 0 | 8.785 | `ec2c8902c9e54d519a09898449a31f26` |
+| uicases | 0 | 8.781 | `1c3b0630795e4cba9bcc584c50c470be` |
+| rollback | 0 | 8.785 | `d6391221195d4cbaa4d000daa5b2798d` |
+| rollbackflow | 0 | 8.785 | `daa66f6c43ec472bb99bf33deace0295` |
+| exportaudio | 0 | 2.751 | `c5432f50e744466f8ac171805b6d5b1d` |
+| exporthevc | 0 | 2.675 | `5f87a5e8439b482d98eb48d3a144053d` |
+| exportmkv | 0 | 2.761 | `bcf6947898c94f3dadb8614cb27cc4e4` |
+| exportvfr | 0 | 0.443 | `f872813a9eaf4dffbfb77f485cc67b32` |
+| cancel | 0 | 2.237 | `eb33b950acec4454949700aef85cb066` |
+
+VFR子程序预期exit1,拒绝检查通过;cancel子程序预期exit3,入口验证其为正常取消;没有把非零退出码伪装成程序成功。
+
+中间失败保留:38654a0a8a184b57815d2ba75ff7d58c 的MKV导出程序exit0,但错误输出119960/499被包时间戳检查抓到;017154fb30b443a28cd7c222577ef776 的小数帧率量化边界单测失败。随后针对实际错误修复;全部旧失败日志保留。此前测试记录及历史边界见REPAIR_PROGRESS。
+
+## 真实输出及功能边界
+
+- 2X:12源帧、11有效中间帧;3X:12源帧、22有效中间帧;4X:12源帧、33有效中间帧。合成纹理内容/位置/非线性混合检查通过;NGX真实Create/Evaluate成功码0x1、SEH0,NVOF status0(各run原始stdout日志)。仅像素验证probe允许读回合成图。
+- SR4K:1920×1080 source/flow,3840×2160 base/FG/output,1920×1080 NR。12源帧、11有效生成。4K输入实时档与原生NR额外证据沿用本修复早先67ef0bf4657949acb1407d6abbe17445、bd6002fad6b64601a0a27596f7b322f9,非旧Phase gate。
+- 最终H264+音轨、HEVC、量化MKV导出均为24源帧+69 generated+3 Hold=96编码帧;240/1fps,包PTS逐一检查i/240,H264音频case保留1条AAC。输出样本为1080p;本次三个缺陷修复后没有重跑4K视频导出,不把它写成本次新实测。
+- 最终3X播放含暂停/seek控制测试:204源帧、400有效生成,lateness P95 1.66ms。最终4X UI测试含比较模式抑制生成帧提交:385源帧、1152生成,处理统计约60.05fps。实际提交日志带PTS/host/fence,物理扫描/光子延迟未测,不能把生成数当成屏幕显示数。
+- **性能仍有限制**:设置测试在播放中切到SR4K并保留4X,最终统计39.75源fps、lateness约2170ms。此case验证事务与源不重开,未证明该组合4K60实时。NR1080回填解决了原生NR4K负载耦合,不会消除4K SR/FG及资源重建成本;不能把功能PASS说成所有组合实时性能PASS。
+
+GPU query实测,以下为median/p95毫秒,非CPU:1080 NR+4X color0.043/0.049、NVOF队列区间1.006/1.118、NR5.958/6.367、residual0.066/0.067、FG子帧1=1.229/1.421、子帧2=0.570/0.748、子帧3=0.566/0.737、FG batch2.414/2.705、blit0.010/0.050。SR4K+NR1080+FG2合成短测:SR2.735/2.826、NR5.909/6.034、FG2.561/2.701。不同阶段可能有包含/重叠,不能把这些统计简单相加称端到端延迟。
+
+## 参数与B1–B5
+
+| 项目 | 结果与限制 |
+|---|---|
+| B1 同帧比较 | GPU source/base references与源ID/epoch/revision绑定;按住、切换、分屏及reference模式内部UI检查通过。生成帧不冒充同一时刻原图。 |
+| B2 性能 | GPU query与CPU阶段分开;最新值、提交数/频率及未知项明确。物理扫描和光子延迟未测。 |
+| B3 预设 | version1、白名单、原子写入/坏文件保护/CRUD/default检查通过;Desired/Applied、整套事务及冻结导出设置已接产品。 |
+| B4 光流 | SDK FAST20/MEDIUM10/SLOW5,实际应用日志;性能/质量档先前repair-v2实测通过,当前联合使用平衡档。30/50/60是内容识别目标,非重采样。 |
+| B5 诊断 | bounded64、去重、错误码、脱敏预览/复制;本次补齐失败级别;没有主动制造真实GPU移除故障。 |
+
+参数实验逐项Applied revision1–9及原始setter日志见fd39d80d44d64b99be5793cc36a58ced。合成样本强度、明暗、结构、风格、自动遮罩、总变化强度均观测到像素变化;肤质/UI修正虽然设置提交,但像素不变,**效果未证实**。模型键与typed setter沿用现有本地实验接口,无新造官方预设。残差darken/brighten/color/luminance为Veyra独立GPU后处理,不修改DLL。
+
+## 修改文件
+
+本次三个问题/计数修复涉及:
+- include/veyra/engine/CfrTimeline.h;include/veyra/media/FFmpegDemuxer.h、src/media/FFmpegDemuxer.cpp;include/veyra/source/IFrameSource.h、src/source/MediaFileSource.cpp;src/engine/VideoExportJob.cpp。
+- src/engine/EngineController.cpp;include/veyra/pipeline/EnhanceGraph.h、src/pipeline/EnhanceGraph.cpp;apps/veyra/main.cpp。
+- src/ngx/NvOfSession.cpp、DlssFgBackend.cpp、DlssSrBackend.cpp;src/base/Log.cpp。
+- tests/unit/RepairContractTests.cpp;CMakeLists.txt;scripts/acceptance/repair-v2.ps1。
+- 本报告、DELIVERY_STATUS、USER_GUIDE、WORKLOG、REPAIR_PROGRESS、loop/STATE/EVIDENCE/JOURNAL。
+
+前续R1–R8完整实现模块与变更见REPAIR_PROGRESS。`logs/repair-v2/final-worktree-status.txt`保存整个未提交工作树清单,包含用户已有改动,不能把全部清单都归因于本次修复。`r0-20260907/before.patch`保留初始dirty资产。
+
+## 独立审查与下一动作
+
+新上下文Reviewer `review_known_fixes`只读审查最终代码、18项联合证据与应用EXE哈希,结论:“本次限定修复范围通过,无剩余阻塞发现。”它未修改文件、构建、运行测试或访问采集卡。此前只读Reviewer已复审其他R1–R8工作,本次结论不扩大为完整原规格或旧Phase重新放行。
+
+7个protected-before控制面哈希均未变(final-protected-check.json);NR root/staged与addon身份符合固定值,未加载addon。git diff --check exit0。未提交、push、发布、上传或打包。
+
+已知未执行:本修复版本实卡验收、实际扫描/光子延迟、多显示器物理DPI、长时间稳定、广泛画质比较。专有runtime分发仍阻塞。唯一下一动作:用户用当前EXE做实卡与实际体验验收;若要要求SR4K+4X达到60源fps,需另以该具体组合的性能瓶颈作为任务验收,不把本次事务功能短测冒充性能达标。
diff --git a/docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md b/docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md
new file mode 100644
index 00000000..24a06c1b
--- /dev/null
+++ b/docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md
@@ -0,0 +1,550 @@
+# Veyra 双模式界面改版执行文档
+
+日期:2026-09-08
+状态:**设计方向已确认;本次仅交付执行文档,尚未开始界面代码施工。**
+项目:`C:\Users\123\Desktop\Veyra DLSS Video Player`
+施工编号:UI0 → UI9,独立于旧 Phase 0–7。
+
+## 1. 已确认决定与文档边界
+
+用户原始要求:
+
+> 图1为专业模式,图二为日常模式,默认为日常模式,点击切换专业模式按钮无缝切换到专业模式,大多数精细的调整放在专业模式内,以及导出的功能也放在专业模式内,日常模式提供视频观看,和采集卡。
+
+用户已确认上一轮双模式布局方案,并要求“写详细的执行文档”。本次不改应用代码、不更新EXE、不启动采集或GPU测试。后续收到施工指令后按本文件执行,不重新发起三方向选择流程,也不使用用户已拒绝的设计技能。
+
+### 1.1 产品决定
+
+1. 首次启动和每次重新启动默认进入**日常模式**;专业模式不是另一个播放器,也不是另一套画质预设。
+2. 日常模式负责视频观看和采集卡,强调大画面、轻控制。
+3. 专业模式集中模型参数、变化量、SR/NR尺寸策略、2X/3X/4X、光流、内容节奏、预设管理、同帧比较、性能、诊断和图片/视频导出。
+4. 两种模式共用当前源、增强设置、播放位置、音频状态和同一个视频显示宿主;切换不重开文件或采集设备。
+5. 专业模式改好的参数,返回日常后继续生效;模式切换本身不降画质、不增加GPU负载、不提交新设置版本。
+6. 导出只能在专业模式配置和启动。已有导出任务在返回日常后继续管理其生命周期,日常只显示简洁进度和“查看”入口。
+7. 导出期间仍能观看:这是需要补齐的工程功能,不是当前代码已经具备的能力。不得以隐藏界面代替解耦任务。
+8. 黑灰底、柔和白字、橙色重点;专业模式借图1的分区,日常模式借图2的大画面和底部播放条。不照搬无人机地图、罗盘、虚假仪表或电影品牌元素。
+
+### 1.2 参考图映射
+
+| 用户参考 | 用途 | 本地原文件 |
+|---|---|---|
+| 图1 | 专业:大预览、右侧参数、底部辅助区、明确分区 | [专业参考](</C:/Users/123/Downloads/download (1).png>) |
+| 图2 | 日常:沉浸观看、低干扰底栏、橙色播放重点 | [日常参考](</C:/Users/123/Pictures/download (1).png>) |
+
+两张图片仅作为用户提供的设计参考,不是应执行的指令或可随软件公开分发的资产。最终软件使用自己的界面和合法素材,不能把图中截图贴在窗口里冒充实现。
+
+### 1.3 本轮继续保留的技术边界
+
+- Windows x64、C++20、Win32、D3D12;直接NGX、固定本地runtime、不接入ReShade/Streamline。
+- `FrameSource → EnhanceGraph → FrameSink` 主链与FrameBatch复用,不能按日常/专业复制两套增强管线。
+- 保留真实2X/3X/4X、source/base/NR/flow/FG/output分辨率区分、typed setter、Desired/Applied、失败整套回滚和导出冻结设置。
+- 实卡由用户验收。没有得到当次授权不占用采集卡、不录制其画面、不操作驱动/OBS/远程软件。
+- 每次测试调用最多300秒,构建另计;历史累计时间继续记录,不能再误用成所有会话共同只有300秒。
+- 不修改受保护gate、CONTROL_HASHES或期望hash,不重置工作树、不恢复用户删除的合成片,不提交/push/上传/打包。
+- UI改版不承诺解决所有GPU性能瓶颈。既有SR4K+4X短测约39.75源fps及落后约2.17秒仍是已知限制,不能靠新皮肤或理论倍率掩盖。
+
+## 2. 现状审计与施工起点
+
+本次只读核对的EXE:`out/build/x64-release/veyra.exe`。SHA256:
+
+```text
+1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266
+```
+
+它是Repair v2修复版本,不是双模式新版。现有证据见 [Repair v2交付报告](REPAIR_V2_DELIVERY_2026-09-08.md),旧联合检查不能替代新界面验收。
+
+| 当前文件/模块 | 已有事实 | 本次必须做的事 |
+|---|---|---|
+| `apps/veyra/main.cpp` | 顶部按钮自动换行;一个video子窗口;参数、统计弹独立窗口;包含采集配置、全屏、字幕、烟测入口 | 拆出窗口壳、布局、动作路由;保留行为,建立日常/专业界面 |
+| `apps/veyra/SettingsWindow.cpp` | 12项输入、预设CRUD、整套应用、Desired/Applied;PresetStore是此文件中的静态对象 | 将设置视图嵌入专业侧栏;预设存储上移到共享服务,不在两种模式分别缓存一份 |
+| `apps/veyra/TelemetryWindow.cpp` | GPU/CPU统计和诊断复制预览 | 拆成嵌入式性能面板和诊断视图;复用同一日志/快照 |
+| `src/engine/EngineController.cpp` | 一个持久worker、一个pending任务;post会置stop;startExport也post到该worker | 模式切换禁止调用post/open/stop;后台导出需独立任务边界 |
+| `include/veyra/engine/EngineController.h` | 快照未暴露完整transport/音量/静音状态;UI另存paused | 建立统一可观察状态,防止两种界面各自猜播放状态 |
+| `src/engine/VideoPresenter.cpp` | 使用既有video HWND;随客户区尺寸调整swapchain,resize有100ms节流及drain | 保留video宿主,不在切换中重建graph;将显示区resize集中协调、可观测 |
+| `src/sink/WasapiAudioSink.cpp` | 文件音频输出已实现;没有对UI的音量/静音接口 | 补本应用音频控制及快照,不改系统总音量 |
+| `src/source/CaptureCardSource.cpp` | DirectShow采集与可选HDMI音频直接RenderStream;容量1邮箱 | 复用采集会话;暴露设备/音频状态和本会话音量能力;避免UI线程枚举阻塞 |
+| `src/engine/VideoExportJob.cpp` | 本地导出函数、冻结参数、CFR验证、NVENC、partial保护 | 由独立导出作业调用同一函数/产品库,不复制增强实现 |
+| `src/engine/PresetStore.cpp` | version1、白名单、原子写入、损坏保护 | 保持兼容;增加UI偏好/启动设置时不要混入预设文件的媒体/设备字段 |
+| `scripts/acceptance/repair-v2.ps1` | 独立18项功能回归,单次300秒 | 保留;新增双模式UI验收入口,不弱化旧断言 |
+
+**三个必须正视的缺口:** 现有startExport会停止播放;现有UI音量接口缺失;现有模式与媒体状态没有独立合同。不能把它们当成布局调整已经自动解决。
+
+## 3. 功能分配与可见性
+
+| 功能 | 日常模式 | 专业模式 |
+|---|---|---|
+| 打开视频、拖放、最近打开 | 常用入口 | 视频入口内 |
+| 视频播放/暂停/进度/音量/字幕/全屏 | 底栏 | 预览下方,共享控制 |
+| 采集卡设备、格式、HDMI音频、开始/停止 | 简洁设置弹层 + 实时底栏 | 采集面板,保留完整状态 |
+| 增强总开关 | 显示 | 显示并提供各项独立控制 |
+| 已存预设选择 | 轻量菜单,只选不编辑 | 选择 + 新建/复制/重命名/删除/设默认 |
+| 7项NR模型参数、5项变化量 | 不出现 | 右侧“增强” |
+| SR、NR尺寸策略、补帧倍率、光流、内容节奏 | 当前状态简述,不能隐藏重负载事实 | 完整可调 |
+| 按住原图/同帧比较/分屏/参考来源 | 不放常驻工具栏 | 预览工具条 |
+| 图片导入与增强编辑 | 不提供入口 | 左侧“图片” |
+| PNG/JPEG保存、视频导出设置/启动/取消 | 无操作入口 | “导出”面板 |
+| 已有导出进度 | 小型状态条,“查看”切专业导出页 | 任务状态、暂停/继续、取消、错误详情 |
+| 性能 | 一行必要状态;出现负载问题时提示 | 可展开GPU/CPU数据 |
+| 诊断 | 最近问题摘要,详情切专业诊断 | 详情、脱敏预览、复制、日志目录 |
+
+补充边界:
+
+- 专业已经打开图片后返回日常,保留该静态画面,不偷偷换文件;底栏标“图片预览”,隐藏播放/进度,提供“打开视频/采集卡”。日常没有图片导入/导出能力不等于必须关闭已打开的图。
+- 日常收到图片拖放时自动进入专业图片页后执行导入;不悄悄丢弃文件。多文件拖放暂只接收第一项并提示,不新增媒体库/队列功能。
+- 点击“视频/采集卡”只是选择入口或展示配置;只有明确打开文件/开始采集才切换活动源。点错标签或关闭配置层不能中断当前播放。
+- 采集不是可回放视频:没有seek、虚假时长、上一帧/下一帧或录制开关。实时录制不在本次新增承诺。
+
+## 4. 视觉规范与尺寸
+
+### 4.1 共用视觉
+
+以下是施工初始token,后续可微调视觉数值,但不能破坏功能层级:
+
+| Token | 值(sRGB) | 用途 |
+|---|---|---|
+| windowBackground | `#101113` | 外壳 |
+| panelBackground | `#1B1D20` | 专业分区 |
+| raisedBackground | `#24272B` | 弹层、输入底色 |
+| divider | `#34373C` | 细分隔线 |
+| textPrimary | `#F2F2F3` | 主文字 |
+| textSecondary | `#B8BDC5` | 次文字,不用于仅靠颜色辨认的状态 |
+| accent | `#EF873E` | 播放按钮、选中、滑杆有效段 |
+| success | `#7DBC99` | 已连接/已应用;同时配文字 |
+| warning / error | `#E9B45B` / `#F17B7B` | 警告与错误,同时配可读原因 |
+
+- 中文使用本机“Microsoft YaHei UI”,缺失时采用系统可用中文字体;不联网下载字体。
+- 普通正文14 DIP,次级12–13 DIP,分组标题15–16 DIP,空状态标题22 DIP;数值采用等宽数字或固定宽度数值区。
+- 所有尺寸以DIP计算,最后统一乘DPI/96取整;禁止对已缩放坐标再次乘DPI。
+- 主控制命中区至少36×36 DIP;常用播放按钮44×44 DIP;图标16–20 DIP,提供可访问名称与tooltip。
+- 面板圆角12 DIP,控件6 DIP,面板间距12 DIP,内部16 DIP;按实际内容分组,不做满屏大小一致的卡片。
+- 阴影仅用于弹层;不在视频外加巨大装饰阴影或霓虹。视频保持原比例,默认contain,不裁切宽银幕内容。
+- 警告不会永久占据大画面:正常状态收敛,错误时展示一行原因与动作;详细码留专业诊断。
+
+### 4.2 日常布局
+
+```text
+┌───────────────────────────────────────────────────────────────┐
+│ VEYRA 视频 / 采集卡 切换专业模式 窗口键 │
+├───────────────────────────────────────────────────────────────┤
+│ │
+│ │
+│ 视频画面 │
+│ │
+│ │
+├───────────────────────────────────────────────────────────────┤
+│ 00:14 ────────────────●─────────────────────────────── 01:20 │
+│ 文件名 播放/暂停 增强 · 预设 音量 字幕 全屏 │
+└───────────────────────────────────────────────────────────────┘
+```
+
+- 初始窗口目标1280×800 DIP,可根据当前显示器工作区缩小;不能把窗口默认开到屏幕外。
+- 顶部52 DIP;底部视频transport96 DIP,其中进度命中区20 DIP、按钮行56 DIP、余量用于间距;视频区为剩余空间。
+- 文件名一行省略,悬停显示名称;不把媒体绝对路径塞进主界面或截图。
+- 无视频时中心只显示“打开视频”和“连接采集卡”两个主要动作、拖放提示;最近文件最多5项,路径不可用明确提示。
+- 采集已运行时底部不显示进度条,改为“设备名 · 实际输入尺寸/输入帧率 · 音频状态”及“停止采集”;名义输入帧率和实测帧率区分。
+- 仅鼠标停留、键盘操作和状态变化触发界面更新;空状态不持续高频重绘。
+
+### 4.3 专业布局
+
+```text
+┌───────────────────────────────────────────────────────────────┐
+│ VEYRA · 专业工作台 返回日常模式 窗口键 │
+├──────┬───────────────────────────────────────┬─────────────────┤
+│ 视频 │ │ 增强 补帧 │
+│ 采集 │ 共用视频画面 │ 预设 导出 │
+│ 图片 │ │ │
+│ ├───────────────────────────────────────┤ 当前页控件 │
+│ │ 按住原图 / 切换 / 分屏 / 输入或底图 │ │
+│ │ 进度 / 播放 / 音量 / 字幕 / 全屏 │ │
+├──────┴───────────────────────────────────────┤ 应用中/已应用 │
+│ 实际尺寸 · 性能摘要 展开性能 / 诊断 │ │
+└─────────────────────────────────────────────┴─────────────────┘
+```
+
+- 顶部52 DIP;左侧72 DIP;右侧参数面板初始328 DIP,可在296–420 DIP范围拖动;分区间距12 DIP。
+- 右侧仅当前页内容可见,纵向滚动;底部固定区域显示“应用中 / 已应用 / 失败已回滚”,不得被长表单滚出视野。
+- 左侧只有视频、采集、图片三个有名称的入口,不加无意义图标列。
+- 预览工具条44 DIP,文件播放transport76 DIP;下方性能摘要36 DIP,展开后约164–220 DIP。
+- 分屏拖杆只在有效视频内容矩形内移动,不拿窗口黑边当图像坐标。切换布局后按比例恢复分隔位置。
+- 同帧参考复用FrameLease中的source/base references;不得新增正常路径全帧读回。
+
+### 4.4 小窗口、DPI与多显示器
+
+- 客户区宽度≥1180 DIP:完整三列。
+- 960–1179 DIP:右栏296 DIP,左栏缩为56 DIP,次要label适当缩短但保留tooltip;性能默认收起。
+- 800–959 DIP:左栏改顶部源选择;专业参数以覆盖式右抽屉显示,由“参数”按钮展开;全宽预览优先。控件仍可完整操作。
+- 工作区小于800 DIP宽时仍允许窗口适配屏幕;底栏折行为两行,右抽屉不超过客户区宽度,不能为了固定最小尺寸把关闭按钮放到屏幕外。
+- 100/125/150/200% DPI、1366×768与1920×1080物理分辨率均需检查;高DPI下不能仅靠把窗口做大解决裁切。
+- `WM_DPICHANGED`按新DPI从原始DIP布局重新计算,不沿用逐控件累计缩放误差。
+- 保存窗口的普通位置/大小,恢复时夹入当前工作区;拔除旧显示器后仍可见。全屏状态与专业模式互不覆盖,退出全屏回到进入前布局。
+
+## 5. 状态模型:模式不是播放会话
+
+### 5.1 唯一状态来源
+
+建议新增UI层结构(名称可按项目约定调整,语义必须一致):
+
+```cpp
+enum class UiMode { Daily, Professional };
+enum class ProPage { Enhance, FrameGeneration, Presets, Export, Diagnostics };
+enum class SourcePane { Video, Capture, Image };
+struct UiSessionState {
+ UiMode mode = UiMode::Daily;
+ ProPage professionalPage = ProPage::Enhance;
+ SourcePane sourcePane = SourcePane::Video;
+ bool fullscreen = false;
+ bool performanceExpanded = false;
+ float inspectorWidthDip = 328;
+};
+```
+
+这不是第二份PlayerSnapshot。播放状态、当前源、当前PTS、实际音量、字幕选择、Desired/Applied、错误和输出作业分别由所属服务提供快照。
+
+禁止让日常与专业各自维护一个EngineController、PresetStore、paused、currentFile、settingsRevision或导出状态。
+
+### 5.2 setUiMode合同
+
+`setUiMode(target)`只允许:
+
+1. 更新UiSessionState.mode、恢复专业页签/滚动位置。
+2. 通过批量窗口布局一次提交目标矩形和可见性。
+3. 更新焦点、可访问名称、mode按钮文字;使焦点不落在隐藏控件。
+4. 通知Presenter最新显示区目标尺寸,等待显示线程按既有fence纪律处理。
+
+不得调用:`EngineController::open/stop/post/startExport/requestSettings`、`source.open/close/seek`、`capture.configure/start/close`、`EnhanceGraph::initialize/shutdown/reset`或重新创建Feature。
+
+只改变显示区大小可以resize swapchain;工作分辨率base/NR/FG不随面板尺寸改变。UI布局版本与enhancement settingsRevision必须分开。
+
+### 5.3 “无缝”的可测试定义
+
+- 切换中video HWND、活动source session ID、NR/SR/FG handles及同一播放任务保持不变。
+- 没有因mode-change而出现SourceOpen/Close、seek、graph reset、epoch变化或settingsRevision变化。
+- 原先暂停则继续暂停;原先播放则按媒体时钟推进,不回到0、不重复触发EOS重播;采集连接不重启。
+- 音量、静音、字幕、选中预设、已应用参数及导出作业ID保持。
+- 不展示空白/黑色过渡占位;可暂时保持最后一个有效GPU画面。显示资源resize若造成暂停要记录实际时间,不能宣称绝对零成本。
+- 稳定60源fps合成文件、排除源scene cut/reset且没有导出负载时,模式切换造成的额外连续提交间隔目标不超过100ms;超过必须定位并修复,不从统计中删掉。
+- UI模式命令处理耗时目标P95≤16ms,无单次>50ms;禁止在UI线程等待GPU fence、线程join、磁盘导出或设备枚举。
+- 连续往返20次,句柄/GPU资源不线性增长,不重复注册事件/计时器。
+
+可选120–180ms面板淡入,初版先实现正确的瞬时布局切换。不得逐动画帧改变video HWND大小触发连续ResizeBuffers;可先一次落到最终视频尺寸,再只对外围面板做视觉过渡。
+
+### 5.4 比较状态的特殊处理
+
+“输入原图/增强前底图”比较会抑制生成帧呈现,不应在日常模式隐藏地继续生效。返回日常时清除临时按住状态、将比较显示退出到增强画面,保留专业比较偏好供再次进入使用。这只是Presenter比较选择,不修改增强参数或reset历史。日志必须区分这一显示选择和增强设置。
+
+### 5.5 启动与偏好持久化
+
+- UiMode不持久化为启动专业;每次应用正常启动强制Daily。CLI导出worker不创建日常窗口。
+- 窗口位置、专业面板宽度/上次页签、音量/静音、字幕显示偏好可保存在独立versioned UI配置中。
+- 正常启动恢复最后一次**应用成功**的增强快照;无有效历史时用用户默认预设,再无则内建默认。Desired未确认的值、失败值、导出worker临时值不得写成下次启动设置。
+- “设为默认”保存预设默认关系并明确说明用于恢复默认/无历史启动;它不悄悄覆盖正在播放的设置。若需载入,用户单独点“应用”。
+- 不把UI偏好、最近媒体路径、设备索引混进EnhancementSettings或现有预设白名单。最近文件沿用独立存储;采集设备重连后重新枚举,不仅凭旧整数索引自动开机采集。
+- 配置写入沿用临时文件、校验、原子替换;损坏保留原文件、走明确默认并展示可查看的诊断。写操作做去抖,不能拖滑杆每一像素就写磁盘。
+
+## 6. 控件行为合同
+
+### 6.1 传输与快捷键
+
+| 操作 | 文件视频 | 采集卡 | 图片 |
+|---|---|---|---|
+| Space | 播放/暂停;不由控件文字推断状态 | 不实现冻结/回放,不触发stop | 无操作 |
+| 进度拖动 | 拖动预览时间,松开提交一次seek;保持此前播放/暂停状态 | 不显示 | 不显示 |
+| F11 / Alt+Enter / 双击视频 | 切全屏 | 同左 | 同左 |
+| Esc | 先关闭最上层弹层;无弹层时退出全屏 | 同左 | 同左 |
+| V按住 | 专业模式临时原图对比,释放/失焦立即恢复 | 专业同左 | 专业同左 |
+| Ctrl+O | 打开文件,专业支持图片 | 打开后是明确源切换 | 同左 |
+| Tab/Shift+Tab/方向键 | 正常焦点与控件操作 | 同左 | 同左 |
+
+编辑框有焦点时,Space/V/方向键不得被全局拦截;Alt+Enter/F11仅按明确约定路由。隐藏控件不能仍接收键盘命令。导出快捷键即使从日常触发,也只能切到专业导出页,不直接启动导出。
+
+### 6.2 日常增强总开关与预设
+
+- “增强”总开关必须含义清楚:关闭时停止应用SR/NR/FG增强,恢复普通画面;不是仅隐藏效果但继续把全部GPU负载算成已关闭。
+- 保存关闭前的完整有效设置作为可恢复配置;再次开启恢复它,不强制2X或重置强度。未曾开启某特性就不能凭总开关自动开启。
+- 实现上区分“用户增强配置”与“本次有效启用状态”,最终仍通过唯一Desired/Applied事务入口提交;关闭不会删除专业参数值或改写预设文件。
+- 关闭中的专业细调保存为待启用配置,控件明确标“增强已关闭”;用户显式开启后整套应用。不能显示参数已影响当前画面。
+- 预设菜单显示存储中的真实名字;参数偏离已应用预设时显示“自定义”。比较快照忽略运行期revision,不凭名称猜是否相等。
+- 日常选择重负载预设会显示“原生NR / 4X”等简述与负载警告;不能暗中改成轻量档。
+
+### 6.3 专业参数编辑
+
+- “增强”页:NR开关、SR底图目标、实时/原生NR策略;模型强度/局部明暗/局部结构;变化量五项;实验参数折叠。
+- “补帧”页:关闭/2X/3X/4X、请求与实际能力、光流三档、内容节奏识别;解释补帧需等待下一源帧,不把采集延迟称免费未来帧。
+- “预设”页:载入、新建、复制当前、重命名、删除、设默认、恢复内建默认;复用PresetStore,不重新发明存储格式。
+- 数值编辑允许暂存未完整输入的“1.”等文本;按Enter或失焦时校验,非法值停留并提示,不提交NaN/半份配置。
+- 普通连续参数滑杆采用短去抖(建议120ms),松开立即提交;同组更新合为一个完整快照。倍率/尺寸/光流等需要资源变更的控件只在用户完成选择后提交,不随拖动反复重建。
+- Desired与Applied均可查;应用中显示请求值和当前生效值。失败回滚整个事务,并显示失败来源,不逐字段伪装部分成功。
+- 从专业返回日常时,正在输入但尚未提交的文本保留为编辑草稿,不能因隐藏窗口自动提交非法数值。
+- skin=-1使用明确“默认/未指定”选项,其余0–2;style为0/1/2整数;autoMask/UI为开关。肤质/UI效果未证实标签保留,不虚构官方含义或预设。
+
+### 6.4 音量与字幕
+
+- 新增本应用volume[0,1]、mute状态命令及快照,UI只更改当前应用音频,不调用系统总音量/设备主音量接口。
+- 文件音频在现有WASAPI音频线程对float PCM应用短渐变增益,或采用经核实的本session增益;避免重新启动音频时钟和瞬时爆音。
+- HDMI音频通过当前DirectShow音频渲染链获得本graph音量能力;COM操作在所属线程执行。能力不可用时显示“此音频输出不支持应用内音量”,不能画一个没有作用的滑杆。能静音也必须验证真实输出路径。
+- 无音轨/未选采集音频时明确显示“无音轨/未启用监听”,避免显示虚假的有效音量状态。
+- 字幕提供当前外部SRT显示开关、载入外部SRT与基础大小选择;不新增内嵌字幕解码、字幕烧录或翻译。
+- 字幕、播放条和OSD只在最终显示层叠加,不能进入NR/FG输入。普通视频导出继续遵守原有不烧录字幕的边界。
+
+## 7. 导出与观看并存:必要的工程改造
+
+### 7.1 当前障碍与选择
+
+当前`EngineController::startExport()`调用`post()`,会设置播放stop并把导出放到同一个worker。新UI若继续调用它,“返回日常继续看”就是假功能。
+
+**本方案选用独立本地导出worker进程**:由当前Veyra.exe的无界面子模式调用共享`exportVideo()`和产品库,前台播放器保留原会话。不是再复制一套算法,也不同时在同一进程里盲目初始化第二套NGX全局状态。
+
+现有`--export-out`证明无界面入口已存在,但完整冻结预设传递、进度/取消IPC、子进程生命周期仍待实现,不能直接当现成功能。
+
+### 7.2 作业合同
+
+建议新增`ExportJobManager`与只读`ExportJobSnapshot`:
+
+- 一次最多1个活动导出任务;不增加无界队列。重复点击开始时展示现有任务。
+- 状态:Idle → Preparing → Running ⇄ Paused → Finishing → Succeeded / Failed / Cancelled;取消请求与取消完成分开。
+- 启动时冻结完整已应用设置、输入路径、输出路径、codec和导出尺寸策略;图像/视频路径不允许混用,采集源不支持“导出视频”按钮。
+- 导出固定原生质量策略,不能继承日常实时NR降分辨率;冻结的settingsRevision和当前播放revision分别显示。
+- 用户之后调播放参数、切模式、打开另一个视频,不影响已启动作业的源和设置。
+- 工作进程使用已验证的当前EXE绝对路径与固定DLL加载机制;不启动脚本解释器、不拼接shell命令、不向环境PATH寻找程序。
+- 任务描述与IPC按版本化白名单验证;路径属于显式用户输入,仅存在于本地任务通道,不写入用户预设或可复制诊断的明文路径。
+- 优先使用本用户访问范围内的命名管道和随机job ID;父进程负责创建、认证/关联自己启动的子进程、限制报文长度和频率。不要对外开放网络端口。
+- progress必须来自真实编码计数/时长,包含source/generated/Hold/output,不能按墙钟计时伪造百分比。100%只在flush/mux/回读检查和最终重命名全部成功后出现。
+- 取消通过本作业IPC通知循环、结束编码、释放资源、保留partial;强制终止仅作为有时限的故障兜底,限制本作业进程树,不能按进程名杀所有Veyra。
+- 父进程退出时先给合作取消和收尾时限,防止孤儿GPU作业。若仍在导出,关闭窗口提示“取消导出并退出 / 返回”;这是用户可能损失长任务的明确选择,不是每次模式切换弹确认。
+- 已存在输出/partial继续拒绝覆盖;不自动删除失败文件。
+
+### 7.3 并存不等于免费GPU性能
+
+- 允许返回日常观看,但两进程仍共享物理GPU;不能承诺重负载导出与4K4X播放同时满速。
+- 提供“观看优先”(默认)与“导出优先”。它们只影响导出作业节奏,不改播放画质、不丢播放源帧。
+- 观看优先可在有界源帧边界暂停/节流导出:结合播放实际提交迟到、视频负载与GPU资源错误;不通过每个pass CPU等待节流,不持锁等待。
+- 首版需要证明前台会话不中断、导出能继续/暂停/取消、状态一致;若该硬件无法并存,明确标“等待GPU资源”并保留作业及前台播放,不无声停止播放。
+- 如果前台因当前SR4K+4X本来就低于源率,UI应显示已有瓶颈;不可把所有落后归给导出。
+- 日常小进度条点击“查看”切到Professional/Export,操作本身不启动/暂停/取消任务。
+
+## 8. 原生UI实现路线与文件职责
+
+### 8.1 技术路线
+
+保留原生Win32窗口与D3D12视频宿主。用自绘深色控件和统一绘制/字体层实现参考图质感;建议用Windows SDK自带Direct2D/DirectWrite绘制UI面板、文字和功能图标,保留标准EDIT/COMBOBOX等输入语义并统一主题。若局部使用GDI,必须有一致的双缓冲、DPI及焦点表现。
+
+本计划不把产品迁成网页/Electron/WebView,不引入新的前后端服务,不安装设计插件。HTML效果图如果后来单独制作,只能是设计预览,不能代替真实veyra.exe交付。
+
+保留原生窗口操作、标题栏拖动/双击最大化、最小化/最大化/关闭、任务栏和键盘可访问性。自绘标题区不能只画三个无法操作的按钮;最终须验证实际Windows窗口行为。
+
+### 8.2 建议文件树(拟新增,当前不存在)
+
+```text
+apps/veyra/
+ main.cpp 入口、消息分发、CLI兼容;不承载所有页面
+ ui/AppShell.h/.cpp 稳定窗口壳、共享video宿主、模式控制
+ ui/UiSessionState.h 纯界面状态
+ ui/Layout.h/.cpp DIP矩形计算、响应式布局,支持纯数据测试
+ ui/Theme.h/.cpp 颜色、字体、绘制资源和统一控件状态
+ ui/CommandRouter.h/.cpp UI动作到服务;处理focus/快捷键边界
+ ui/TransportBar.h/.cpp 文件播放/采集底栏、音量、字幕
+ ui/DailyView.h/.cpp 日常入口、空状态、轻量菜单
+ ui/ProfessionalView.h/.cpp 专业壳、侧栏、下方面板
+ ui/EnhancementPanel.h/.cpp 模型/变化量/资源策略
+ ui/FrameGenerationPanel.h/.cpp 倍率、光流、内容节奏
+ ui/PresetPanel.h/.cpp 预设CRUD和应用
+ ui/CapturePanel.h/.cpp 异步枚举、格式、音频、连接状态
+ ui/ExportPanel.h/.cpp 配置/冻结信息/真实作业进度
+ ui/DiagnosticsPanel.h/.cpp 性能详情、脱敏预览和复制
+ ui/UiPreferenceStore.h/.cpp UI偏好与成功启动设置
+include/veyra/engine/ExportJobManager.h
+src/engine/ExportJobManager.cpp
+scripts/acceptance/ui-dual-mode.ps1
+```
+
+这是职责边界,不要求为凑文件机械拆每个小函数;但禁止继续把设置、作业、绘制、采集枚举全堆进main.cpp。
+
+### 8.3 已有文件的改造规则
+
+- SettingsWindow、TelemetryWindow分阶段提取可复用逻辑,再换嵌入式视图;删除旧入口前必须确保每项原功能在新界面可达。
+- PresetStore改由应用服务持有一个实例,两种模式订阅同一状态;其磁盘schema兼容与损坏保护不变。
+- PlayerSnapshot新增明确TransportState(Idle/Opening/Playing/Paused/Ended/Stopping/Failed)、source session ID和音量/字幕必要状态;running不再被UI解释成播放/暂停全部语义。
+- 输入设备枚举/格式查询在专用COM线程或已明确所有权的worker完成,以消息回主线程;结果过期可丢弃,不把查询绑定到每次UI刷新。
+- snapshot消费建议4Hz,只刷新变化文本;进度显示可以本地平滑,但不能用插值计数当实测帧率。
+- Resize调用合并到最后目标尺寸;UI线程不drainQueue。视频呈现和字幕叠加的线程/fence所有权明确,布局代码不能跨线程释放纹理。
+- Direct2D UI渲染与D3D12视频分层明确,不把视频纹理读到CPU供UI绘制。控件/字幕覆盖视频需解决真实HWND层级,不靠普通STATIC透明背景假装透明覆盖。
+
+## 9. 边界场景与错误呈现
+
+| 场景 | 必须表现 |
+|---|---|
+| 无媒体启动 | 日常空状态,打开视频/连接采集可达 |
+| 媒体加载中切模式 | 加载任务继续;两个模式展示同一Opening状态 |
+| 暂停中切模式/resize | 保持相同源帧与暂停状态,不能自动播放 |
+| 播放结束 | 显示重播,只有用户点击才重新打开/seek |
+| 无采集设备 | 明确未找到,刷新可用,不自动反复创建采集图 |
+| 采集配置层关闭 | 保留此前活动源;无新增打开/关闭事件 |
+| 实卡拔线 | 冻结/终止旧画面时明确“信号中断”,不要继续涨输入帧数 |
+| 设置失败 | 保留旧Applied,显示回滚;当前预设标签对应真实生效值 |
+| 缺失预设/配置损坏 | 原文件保留,诊断与默认策略明确 |
+| 后台导出失败 | 前台继续,日常显示小型失败提示;专业展示原因和partial路径 |
+| 模式快速反复点击 | 幂等、最后一次目标生效,不排队创建多窗口 |
+| 全屏失焦/Alt+Tab | 释放临时原图按住,光标和焦点恢复;不重置NR历史 |
+| 小窗口长文件名/超长设备名 | 省略+tooltip,关键操作不被挤出 |
+| 诊断复制 | 仅复制已预览脱敏内容,后续新日志不能悄悄替换待复制内容 |
+
+## 10. 施工顺序与每步退出条件
+
+每个UI阶段只由主Agent写入;代码变更先留工作记录。独立Reviewer只读,不替Maker改代码。未经实际检查不能把清单预勾为完成。
+
+### UI0:盘点、保护与新基线
+
+工作:完整读AGENTS及现有修复报告;记录git status/diff/stat、EXE/runtime身份、受保护文件hash;保存现有dirty patch;列出所有旧控件到新位置映射。
+
+退出:基线可恢复,删掉的测试媒体保持删除,现有文件不被覆盖;本次仅文档阶段的状态明确。禁止用rehash消除漂移。
+
+### UI1:共享状态与动作合同
+
+工作:UiMode/UiSessionState、TransportState、CommandRouter、Layout纯函数;一个video HWND贯穿两种模式;建立模式切换计数/日志。
+
+退出:在现有窗口上先验证切模式不调用open/stop/requestSettings,无媒体/播放/暂停状态一致;纯布局测试覆盖DPI和窄窗口。此阶段不先堆漂亮卡片。
+
+### UI2:统一深色控件与日常模式
+
+工作:Theme、底栏、空状态、顶部源入口与专业切换;文件播放/暂停/进度/最近文件可用;窗口布局和键盘焦点完整。
+
+退出:真实视频可看,普通窗口不再出现专业参数/导出按钮;日常与现有引擎行为一致。不能用静态视频截图当播放。
+
+### UI3:专业工作台与参数/预设迁移
+
+工作:专业导航、右侧四页、原图对比/分屏;提取SettingsWindow/PresetStore逻辑;Desired/Applied和错误回滚可见;明确总增强开关状态与可恢复设置。
+
+退出:全部7+5参数及倍率/尺寸/光流可达,预设CRUD完整,返回日常保留成功设置;失败注入整套回滚且NVOF不丢;缓存重算不增源帧计数。
+
+### UI4:音量/字幕与采集界面
+
+工作:补音频命令和快照、字幕显示控制;采集枚举异步化、连接状态、两种模式共享会话;采集底栏不显示seek。
+
+退出:合成音频证明音量/静音作用于本应用输出且不改音频时钟;无设备/配置失败状态通过;实卡项标awaiting_user_capture_test,不借模拟通过冒充设备通过。
+
+### UI5:后台导出任务
+
+工作:独立worker、冻结配置通道、进度/取消/暂停、父子进程清理、专业Export页与日常小进度。
+
+退出:同一视频导出时前台继续播放,切模式不换job ID;前台改设置不改变导出冻结快照;H.264/HEVC/CFR/音轨/partial行为不退化;不能用现有startExport停止播放器后仍宣称并存完成。
+
+### UI6:性能、诊断与负载提示
+
+工作:迁移TelemetryWindow;尺寸链摘要、GPU/CPU分项、实际提交频率、错误摘要、诊断脱敏预览;导出竞争和重负载提示。
+
+退出:无来源的数值显示未测;子进程导出与前台播放指标分开;错误真实码和上下文可查,复制前后内容一致。
+
+### UI7:全屏、DPI、小窗口与输入收尾
+
+工作:共享全屏逻辑、控制栏显隐、多个DPI、显示器变化、焦点/快捷键、长文本、分屏坐标。
+
+退出:F11/Alt+Enter/双击/Esc、编辑框快捷键隔离、20次切换资源有界;只有必要的显示资源resize,无Feature重新创建。未具备真实多屏条件时如实标手工待验,不假装自动模拟等于物理通过。
+
+### UI8:独立验收与反回归
+
+工作:新增ui-dual-mode入口;跑下节关键用例;再运行原repair-v2相关回归;截取真实新EXE日常/专业截图和必要的状态截图。
+
+退出:每条自动检查有本次run ID、真实退出码、日志与EXE哈希;每次≤300秒;无新的设备移除、无正常路径像素读回、无旧功能消失。视觉审核与功能审核分别记录。
+
+### UI9:只读审查和交付
+
+工作:新上下文Reviewer只读审当前差异/截图/新日志/遗漏;修发现后有针对性重测。更新交付状态、使用说明、WORKLOG与UI进度字段。
+
+退出:输出新EXE与SHA256、文件清单、实际命令/耗时、日常/专业截图、模式切换身份/性能证据、后台导出证据、未验实卡项及唯一下一动作。旧Phase字段不被改造成新UI通过证明。
+
+## 11. 验收矩阵与证据
+
+### 11.1 核心自动检查
+
+| ID | 检查 | 通过条件 / 证据 |
+|---|---|---|
+| M01 | 冷启动与重启 | 均Daily;有效增强设置按启动规则恢复;无自动连接采集 |
+| M02 | 播放中往返模式20次 | 同一sourceSession/video HWND;mode-change不产生源重开/seek/Feature create/reset |
+| M03 | 暂停中切模式 | PTS/源ID不变、pause状态不变;显示重绘不计新源帧 |
+| M04 | 模式和设置同时变化 | 仅真实设置动作增加revision/必要epoch,布局动作不混入 |
+| M05 | 模式切换间隔 | UI命令P95≤16ms、单次≤50ms;稳定60源fps额外提交间隔≤100ms,完整样本保留 |
+| M06 | 参数编辑与预设 | 7+5值域、整数/NaN、整套应用/回滚、加载/保存、坏配置保留 |
+| M07 | 总增强开关 | 关闭有真实作用、开恢复配置;不能只用comparison冒充关闭处理 |
+| M08 | 源帧计数 | 缓存重算同sourceId,read计数不增;UI刷新/模式切换不增计数 |
+| M09 | 导出并存 | 前台sourceSession/时钟持续,子job独立;输入/设置冻结,与前台后续变更隔离 |
+| M10 | 导出生命周期 | 准备/运行/暂停/取消/失败/成功显示真实;partial保护,父进程退出无孤儿任务 |
+| M11 | 导出内容 | 2X/3X/4X有效generated/Hold计数、96包240fps等合成合同保持;音轨检查 |
+| M12 | 音量 | 无音轨显示能力状态;音量0/中间值/静音有真实增益证据,不改变其他应用/系统音量 |
+| M13 | 键盘 | 输入框能输入V/空格;hidden控件不响应;全屏和focus恢复正确 |
+| M14 | 尺寸布局 | 100/125/150/200%纯布局无负尺寸/越界/关键按钮重叠;图像contain |
+| M15 | 诊断 | 实际错误码、源/作业区分、同fingerprint计数、64上限、脱敏预览与复制一致 |
+| M16 | 既有产品回归 | SR4K分辨率、真实FG、参数回滚、NVENC、CFR量化/VFR拒绝保持有效 |
+
+性能阈值是未来验收目标,当前未运行,不得预填PASS。硬件负载不达标应报告实际数据和影响,不修改分母或删除失败样本。
+
+### 11.2 必须看真实窗口的视觉检查
+
+- 日常播放、日常采集配置/无设备、专业增强、专业导出、展开诊断、全屏、小窗口至少7种状态。
+- 真实文字清晰,重要按钮无裁切,中文名长文本不挤压;橙色强调有主次,视频比例正确。
+- 原图/增强两侧在同一视频内容矩形,拖杆位置正确;暂态按住失焦后恢复。
+- 不把源视频截图或设计稿合成图当作新EXE运行截图。
+- 仅使用项目非私人合成媒体;不默认截取用户采集内容或桌面。
+- 手工不可得的多屏/DPI穿越和采集断线必须标未测,不以代码有分支就写通过。
+
+### 11.3 新验收入口(拟新增,本文编写时不存在)
+
+```powershell
+# 构建独立计时
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release
+
+# 未来新增;一次调用包含的所有子测试共同遵守本次300秒
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/acceptance/ui-dual-mode.ps1 -Root . -MaxRuntimeSeconds 300 -Case all
+
+# 已有repair-v2反回归,另一次调用也最多300秒
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/acceptance/repair-v2.ps1 -Root . -MaxRuntimeSeconds 300 -Case all
+```
+
+新入口支持state/layout/switch/settings/audio/export/visual/all等有限case;准备素材、子进程和probe都计入本次调用时限,超时记录并只停止自身进程树。不能通过拆无限子进程逃避单次时限,也不把历史累计耗时当未来剩余额度。
+
+证据目录建议:`logs/ui-dual-mode/<run-id>/`,包含result.json、真实命令、stdout/stderr、EXE/hash、可验证的截图路径、每项status/exit/time、未执行原因。
+
+建议日志事件:
+
+```text
+ui-mode: actionId, from, to, layoutRevision, sourceSessionId, videoHwnd
+ui-mode-state: ptsBefore/After, transportBefore/After, settingsRevisionBefore/After
+ui-mode-resources: featureCreate/reset/sourceOpen counters before/after
+ui-layout: dpi, clientExtent, contentRect, mode, resizeRequested/Completed
+export-job: jobId, workerPid, frozenRevision, status, source/generated/hold/output
+```
+
+GPU、Present、模式动作时间分开;要归因于mode-change,关联actionId而不是只比较总计数(实际scene cut/用户改设置可能合法改变epoch)。日志正常持续播放不可无界增长内存队列。
+
+## 12. 对抗式审查清单
+
+实现者交付前逐项回答,Reviewer至少抽查这些失败方式:
+
+1. 所谓两种模式是不是实际关闭/重开了播放器?隐藏窗口里的worker是否仍然重复工作?
+2. 专业切日常是否通过加载“日常预设”偷偷改了分辨率/倍率?
+3. 分屏仍开但日常看不到关闭入口,是否让有效生成帧被隐性抑制?
+4. 导出是否仍走旧startExport并停止前台?独立进程是否传齐全部设置,还是仅NR/SR/FG几个CLI开关?
+5. 进度100%时是否真的完成mux、音轨和最终文件验证?取消是否只杀了UI而留下GPU进程?
+6. 音量滑杆是否只是改了标签?采集音频路径与文件WASAPI是否分别有实际能力判断?
+7. 快捷键是否抢走输入框的V、空格和方向键?隐藏控件是否还会提交设置?
+8. 右栏收起/展开是否连续ResizeBuffers导致卡顿?暂停图片是否因为模式切换变黑?
+9. UI字段、PresetStore和EngineController是否形成三份不同的设置真源?Applied失败时视觉是否仍显示成功?
+10. 常驻性能更新是否同步文件I/O或GPU等待,导致UI新瓶颈?
+11. “关闭增强”是否仍运行全负载,或者恢复时丢掉用户的模型/光流设置?
+12. 在125/150%字体缩放与1366×768屏幕上是否有无法到达的导出取消/模式退出按钮?
+13. 仅按钮改了中文,但错误、tooltip、焦点名称和导出状态是否还是原英文?
+14. 既有SR4K+4X性能限制是否被改成漂亮的“240fps”理论数字?
+15. 新文档中的“已实现/通过”是否有当前EXE和run ID,不是复制旧Phase或设计稿?
+
+## 13. 最终交付与停点
+
+最终交付应包含:
+
+- 真实可运行新EXE及SHA256,仍由Veyra.cmd启动。
+- 日常与专业实际窗口截图、操作说明、两种模式功能映射。
+- 模式无重开/无参数改变的实测日志、DPI/全屏/键盘结果。
+- 后台导出并存/冻结设置/取消结果,音量真实作用证据。
+- 构建命令/退出码/独立耗时;每次短测耗时、run ID和失败/修复记录;不省略未测项。
+- 只读独立Reviewer结论与范围;已知性能和硬件限制。
+- 不改旧Phase字段、不制造公开首发完成状态、不打包专有DLL。
+
+本文件的设计方向已得到用户确认。本次到文档交付为止,后续唯一施工起点是**UI0盘点保护 → UI1共享状态与稳定视频宿主**,不是直接在main.cpp上堆另一排按钮。
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index d8decf77..7f4f51c3 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -1,39 +1,38 @@
-# Veyra 本机使用
+# Veyra 本机使用 — Repair v2
-双击项目根目录 `Veyra.cmd`。实际程序在 `out/build/x64-release/veyra.exe`;暂时不要移动项目目录,编译时绑定了本机 runtime / shader 路径。这不是含专有 DLL 的安装包。
+双击项目根目录 `Veyra.cmd`。实际程序为 `out/build/x64-release/veyra.exe`;本机 runtime / shader 路径在构建时绑定,不要移动项目目录。这不是可公开分发的安装包。
-## 播放器
+## 播放和参数
-1. 点 **Open video / image**,或拖入 MP4/MKV/H.264/HEVC 视频。
-2. **DLSS NR** 是实验 Feature 18;**FG 2X** 是补帧;**SR 4K** 是在 NR 前超分到 4K。
-3. **Live 1080** 是用户同意的默认实时档:4K 视频仍按 4K 解码,内部处理到 1080p,最终按窗口/全屏尺寸显示。状态行写真实 input / processing,绝不是原生 4K NR。
-4. 取消 **Live 1080** 使用原生分辨率。RTX 5070 本机实测原生 4K NR 单次约 22–23ms,因此它不能保证 4K60 实时;不要在这种负载下期待仅靠补帧修复音画落后。SR 4K 也走 4K NR 高成本路径。
-5. 拖进度条可 seek;暂停时也可定位。Space 暂停、F11 全屏。更改增强开关会重新打开源文件;不是无缝动态切换。
-6. **Recent** 打开最近文件。NR/SR/FG/Live 设置保存在 `runtime_local/veyra.ini`。
-7. 同名 UTF-8 / UTF-16LE `.srt` 自动加载,显示在画面下方独立字幕区域,不进入 NR/FG。当前不解码内嵌字幕,也不烧录字幕到导出文件。
+1. 点“打开视频/图片”或拖入 H.264/HEVC 视频、PNG/JPEG 图片。
+2. “SR 4K”把底图超分至4K;“实时NR档”保留该4K底图,约1080p内部NR的变化由GPU回填。状态显示输入、底图、NR、光流、FG与输出实际尺寸。
+3. 取消“实时NR档”可选原生NR,性能成本更高,不承诺原生4K60。“补帧”配合2X/3X/4X选择,倍率表示每对源帧的总时间格数;无效生成或reset不会计作有效补帧。
+4. “参数与预设”提供7项NR参数及5项变化量参数。Desired与Applied分开显示,真实帧边界整套应用,失败回滚;参数修改不重新打开视频或归零进度。修改尺寸/光流会有有界资源重建。
+5. 肤质结构、风格、自动遮罩、画面内UI修正属于实验参数。当前合成样本未观察到肤质/UI修正的像素变化,不能保证实际效果;风格和自动遮罩已观察到变化。
+6. 预设支持新建、复制当前、重命名、删除、设默认、恢复内建默认,保存在 `runtime_local/user-presets.v1`。配置损坏会保留原文件并报错,不静默覆盖。
+7. 光流三档为性能/平衡/质量;界面记录实际应用档。30/50/60模式用于识别内容节奏,不会把源时间轴重采样成指定帧率。静止画面不能确认较低内容帧率。
+8. 进度条定位,Space播放/暂停;F11、Alt+Enter、视频区域双击或全屏按钮切换,Esc退出全屏。设备丢失会停止并报错,重新打开源恢复,不是无缝恢复。
-## 图片 / 视频导出
+## 对比、性能与诊断
-- 打开 PNG/JPEG 后点 **Save image**,保存增强后的 PNG 或 JPG。播放视频时也可保存当前源帧增强截图。WIC 处理 JPEG EXIF 方向。
-- **Export video** 选择新 MP4 文件名,Yes 选择 HEVC、No 选择 H.264。使用当前 NR/SR/FG;**Live 1080 不影响视频导出**,4K 输入仍按原生 4K 处理。
-- 视频使用真正 D3D12 NVENC:GPU 纹理/fence 直接给编码器;CPU 只接压缩码流,不走 raw 像素 pipe。
-- 默认保留第一条可封装到 MP4 的音轨;不兼容的音频编码会报错拒绝导出,不偷偷丢音轨。多音轨选择、音频转码尚未提供。
-- Stop 取消导出;`.partial` 保留以便诊断,未完成文件不会改名成成功 MP4。没有断点续编;重新导出请选择新文件名。
-- 不覆盖已有文件。若上次有同名 `.partial`,换名字或自行确认删除它后再试。
-- V1 输出为 CFR,FG 2X。场景切换不跨镜头插帧,空出的时间格使用明确记录的源帧 hold,而非声称它是生成帧。
+- 按住V或“按住原图”临时查看原图;可用“原图/增强切换”和“分屏拖动”,并选择输入原画或增强前底图作为参考。对比显示同一源帧的GPU参考,生成帧没有天然原图时明确使用真实帧对比。
+- “性能/诊断”中GPU timestamp与CPU解码、提交、等待、Present分开。实际提交频率不等同物理屏幕扫描;没有测到的项目显示未测,不以源帧率乘倍率代替。
+- 诊断包括真实失败码、阶段/尺寸/帧身份与运行时标识;相同问题合并计数、固定上限。复制前可预览脱敏文本;不自动上传任何内容。
+- 同名 UTF-8/UTF-16LE `.srt` 在FG后的独立字幕区域显示;暂不解码内嵌字幕,也不烧录字幕进导出文件。
-## 采集卡:等待你实机测试
+## 图片与视频导出
-1. 接采集卡,点 **Capture**。依次选择真实视频设备、实际支持的 1080p/2160p 30/60 格式、HDMI 音频输入。
-2. 音频不是自动猜选;不选就无音频。点 Start capture。
-3. 先默认 Live 1080、NR 开、FG 关确认视频声音;再开 FG 2X。内部实时入口只保留最新一帧,丢帧会清除历史。
-4. 分别检查 1080p60、4K30/60(以设备实际提供为准)、停止重开、拔线后的错误提示、重接后重新打开 Capture、音画差和按键体感延迟。
-5. 补帧必须等待后一源帧到达,不是利用采集卡获得免费未来帧。HDMI 音频目前由 DirectShow 实时监听,尚未经过实卡端到端延迟校准。
+- “保存图片”保存当前真实源帧的增强PNG/JPEG。不会覆盖已有文件。
+- “导出视频”选择新MP4路径和H.264/HEVC。启动时冻结设置;实时NR档不降低导出分辨率,4K输入默认原生4K NR。编码使用D3D12 NVENC input/fence,CPU只接压缩码流。
+- 默认保留第一条可封装MP4的音轨;不兼容编码明确拒绝,不静默丢音轨。无多音轨选择或音频转码。
+- CFR输出支持2X/3X/4X;缺失/无效生成及尾部保持帧明确记为Hold。先采样最多120帧时间戳,只存元数据,再从头读取导出;全程继续验证时间轴,不均匀时间戳会拒绝。
+- 对量化短片,原始精确帧率可能无法唯一推断;优先使用与时间戳一致的标准标称帧率,否则选择一致的标准候选,再尝试非标准标称帧率,日志记录声明值和候选值。不宣称恢复了唯一原始帧率。
+- “停止”取消任务;已产生的 `.partial` 保留诊断,不改名成成功文件。预检查即失败时可能还没创建partial。重新导出使用新名称,不支持断点续编。
-## 真实边界
+## 采集卡与边界
-仅本机 Windows x64 / RTX / SDR,最高 3840×2160、偶数尺寸;HDR 会拒绝。Depth Anything provider 当前不可用,实际是 NVOF motion + cost 门控,不是游戏原生深度/运动向量。
+点“采集”选择真实视频设备、实际格式和HDMI音频输入。先NR开、FG关检查视频声音,再选补帧倍率。补帧需要等待下一源帧,不能消除采集卡固有延迟。当前修复版本的实卡验收由用户完成,本轮未占用采集卡。
-短测不证明长时间稳定,也不证明画质优于 Magpie/ReShade。设备丢失会停止并报错,重新打开源来重建引擎;不是无缝恢复。公开分发权尚未解决,勿打包/上传实验 runtime 或 ReShade add-on。
+仅Windows x64/NVIDIA/SDR,偶数尺寸最高3840×2160;HDR不支持。Depth provider未实现,当前为NVOF motion + confidence门控,不等同游戏原生深度/运动向量。短测不证明长期稳定、所有采集卡兼容或画质优于其他产品。实际屏幕扫描/光子延迟、多屏物理DPI穿越尚未测量。专有runtime分发权未解决,不打包、上传或发布DLL/SDK。
-错误先点 **Logs** 查看 `logs/veyra-app.log`。提交反馈只需日志与操作步骤,不要发送 runtime、SDK 或私人媒体。
+详细结果见 `docs/REPAIR_V2_DELIVERY_2026-09-08.md`。测试限制已按用户2026-09-08澄清改为每次最多300秒,历史累计时间仅作报告。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 49da17da..4aa26948 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,34 @@
# Veyra Worklog
+## 2026-09-08 Dual-mode UI execution document only
+
+User approved the two-mode design based on their references: Daily default for video/capture; Professional for fine controls, comparison, telemetry/diagnostics and export. Added docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md with verified code map, shared-session invariants, responsive DIP layout, controls/shortcut rules, UI0–UI9 tasks and test matrix. Read-only inspection identified necessary backend work: current startExport replaces the playback worker and audio volume is not exposed. The plan explicitly includes a bounded independent export worker using shared product libraries and real per-application audio controls; these are planned, not claimed implemented. User-rejected design skill was not used.
+
+No app code, runtime, protected gate, user media or EXE changed; no build/GPU/capture test, Goal, commit or upload. EXE remains 1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266. Static checks: document links exist, code fences balanced, UI0–UI9 present, 7 protected hashes unchanged, deleted fixture remains absent. Test limit remains per invocation <=300 seconds. UI status is design_approved / implementation_not_started. Next implementation task, when requested: UI0 inventory and UI1 shared state/stable video HWND.
+
+## 2026-09-08 Repair v2 final known-fix review
+
+User corrected test budget to per invocation <=300s. Implemented timestamp-quantization CFR validation and candidate selection, full Desc rollback, failure-code diagnostic capture, and cached source identity/count preservation. Final build exit0 (3.9694163s); joint joint-a077b89fd39348e4a49f4195c9d4e416 18 cases exit0 in 71.0278864s runtime. Historical cumulative 346.3985650s includes failures; not reset. Read-only fresh reviewer review_known_fixes passed this limited fix scope, verified EXE 1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266. No old Phase pass updated; global needs_review retained. Full evidence, modified files, intermediate failures, performance limitations and user capture next action: docs/REPAIR_V2_DELIVERY_2026-09-08.md. Protected hashes unchanged, runtime identity matches, no capture/commit/upload. SR4K+4X smoke39.75sourcefps/2.17s lateness remains an explicit performance limitation, not a functional transaction failure hidden as realtime pass.
+
+
+## 2026-09-07 B1–B5 selected; planning/handoff only
+
+User selected B1–B5 for the next implementation scope: same-frame comparison, per-stage performance UI, transactional user presets, shared optical-flow quality profiles, and a local privacy-aware diagnostics center. The repair plan now contains their precise data ownership, state transition, UI, failure and acceptance contracts; the Magpie backlog marks them selected. Added a paste-ready next-conversation handoff that explicitly refuses to treat the historical shared Phase5–7 gate as new release proof and forbids modifying protected hashes/gates to manufacture a pass.
+
+This entry is documentation only. No application code, gate, CONTROL_HASHES, review prompt, SDK/runtime, driver, external app, capture device or user media was changed or executed. No build/test/Goal/checkpoint/publication was performed. Current software remains needs_review with SR4K/FG user-visible defects unresolved.
+
+## 2026-09-07 SR4K / FG / parameters planning only
+
+User requested detailed documents and a Magpie feature shortlist before implementation. Added `C:/Users/123/Desktop/Veyra DLSS Video Player/docs/REPAIR_EXECUTION_PLAN_2026-09-07.md` and `C:/Users/123/Desktop/Veyra DLSS Video Player/docs/MAGPIE_FEATURE_BACKLOG_2026-09-07.md`; updated DELIVERY_STATUS with the unresolved SR4K/FG feedback and planning links. The plan covers resolution separation, real generated-frame ownership/content/pacing, SDK MFG 2/3/4, export timing, typed NR controls, independent residual controls, live settings, Chinese/fullscreen UI, and a shared 300-second future runtime-test budget. Other competitor features remain user-selectable candidates, not automatic implementation tasks.
+
+Evidence this turn: read-only current code inspection plus Magpie 0.6.6/0.6.5 release and parameter/frame-sync documents; no Magpie GPU benchmark. No application code, SDK/runtime, protected control file, control hash, user configuration or existing deleted fixture was changed. No build, GPU test, app/device operation, Goal, checkpoint, driver/remote-software operation or publication. Documentation static checks are recorded with this turn's tool results; prior EXE and needs_review state remain unchanged. Next action: user selection/implementation confirmation, then resolve protected-document scope before any new Goal.
+
+Static verification: `git diff --check` exit 0 (existing LF/CRLF notices only); all absolute local Markdown links in the two new documents and DELIVERY_STATUS resolve; no Unicode replacement characters; all 11 protected manifest file hashes match. No gate was run and no manifest was edited.
+
+## 2026-09-07 capture latency repair
+
+User explicitly requested implementation after the physical-card diagnosis. Owned bounded capture AVFrames + deferred Run + live-specific bounded pacing remove the stale-PTS wait; ring/presenter use one rotating cursor; live metrics no longer masquerade as photon latency. Code/files/commands/results are recorded in `docs/CAPTURE_LATENCY_FIX_2026-09-07.md`. Release build exit0; timing7/7, source8/8, physical 1080p50 off/NR/NR+FG ~49.4–49.8fps and0drops; final NR195/NVOF193/generated193. Visible-player consolidated gate21/21 exit0 in47.309s, run01b72df768524af9ab0aa8d2e3dbb59e, final EXE4A9BA4B321DEEC17C5E3562AF03EF75A316856200A8708FA8E692475A05B59C9. Preflight71/71. No proprietary files, external apps, driver, user settings or deleted user clip changed. Read-only reviewer attempt failed without final verdict; needs_review, no new checkpoint. User perceived latency/audio and actual generated-frame display cadence remain unverified.
+
## 2026-09-07 direct implementation delivery
See docs/DELIVERY_STATUS.md for current software, tests and limits. Actual app/controller/presenter, DirectShow source, WIC and D3D12 NVENC export now exist; earlier “no UI/export” entries are historical. Fixed NV12/uint shader inputs, real guidance-before-NR, scene resets, audio format/paused seek, GPU timestamp semantics. CMake x64-release exit0; consolidated gate run d28879b01b5c44dd86cad33d6f386d90 exit0 in31.59s. No 30-minute retests. User accepted realtime internal-resolution option after GPU measurement. Independent review next; do not claim phase checkpoint yet.
diff --git a/include/veyra/Log.h b/include/veyra/Log.h
index 430be92c..abfc17de 100644
--- a/include/veyra/Log.h
+++ b/include/veyra/Log.h
@@ -4,6 +4,7 @@
#include <cstdio>
#include <mutex>
#include <string>
+#include "veyra/diagnostics/DiagnosticEvent.h"
namespace veyra {
@@ -38,11 +39,15 @@ public:
// Flush the file sink immediately (staged-teardown markers must survive
// a crash on the very next call).
void flush();
+ std::string diagnosticReport();
+ std::string latestProblem();
+ static void diagnosticContext(diagnostics::DiagnosticEvent);
private:
std::mutex mutex_;
std::FILE* file_ = nullptr;
bool consoleEnabled_ = true;
+ diagnostics::DiagnosticHistory diagnostics_;std::string latestProblem_;
};
namespace log {
diff --git a/include/veyra/diagnostics/DiagnosticEvent.h b/include/veyra/diagnostics/DiagnosticEvent.h
new file mode 100644
index 00000000..bd77a194
--- /dev/null
+++ b/include/veyra/diagnostics/DiagnosticEvent.h
@@ -0,0 +1,30 @@
+#pragma once
+#include <array>
+#include <optional>
+#include <string>
+#include "veyra/pipeline/FrameBatch.h"
+#include "veyra/pipeline/ResolutionPlan.h"
+namespace veyra::diagnostics {
+struct DiagnosticEvent {
+ std::string timestamp,severity;
+ std::string fingerprint,component,stage,message,runtimeHash,flowApplied,fallbackReason;
+ std::optional<uint64_t> hresult,ngx,nvof,seh;
+ pipeline::ResolutionPlan resolution;
+ pipeline::FrameIdentity identity;
+ uint64_t batch=0,occurrenceCount=1;
+ uint32_t subframe=0;
+};
+class DiagnosticHistory {
+public:
+ static constexpr size_t capacity=64;
+ void add(DiagnosticEvent event) {
+ for(size_t i=0;i<size_;++i)if(events_[i].fingerprint==event.fingerprint){event.occurrenceCount=events_[i].occurrenceCount+1;events_[i]=std::move(event);return;}
+ events_[next_]=std::move(event);next_=(next_+1)%capacity;size_=std::min(size_+1,capacity);
+ }
+ size_t size() const{return size_;}
+ const auto& events() const{return events_;}
+private:
+ std::array<DiagnosticEvent,capacity> events_{};
+ size_t size_=0,next_=0;
+};
+}
diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.h
new file mode 100644
index 00000000..4d1a83b9
--- /dev/null
+++ b/include/veyra/diagnostics/FrameMetrics.h
@@ -0,0 +1,18 @@
+#pragma once
+#include <array>
+#include <optional>
+#include "veyra/pipeline/FrameBatch.h"
+#include "veyra/pipeline/ResolutionPlan.h"
+namespace veyra::diagnostics {
+enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, FgBatch, Blit, Count };
+enum class SampleState { NotExecuted, Pending, Measured, Unavailable };
+struct GpuSample {SampleState state=SampleState::NotExecuted;std::optional<double> milliseconds;uint64_t begin=0,end=0,frequency=0;};
+struct FrameMetrics {
+ pipeline::FrameIdentity identity;
+ pipeline::ResolutionPlan resolution;
+ std::array<GpuSample,size_t(GpuStage::Count)> gpu{};
+ std::optional<double> decodeCpuMs,submitCpuMs,gpuWaitCpuMs,deadlineWaitCpuMs,presentCpuMs,displayFps;
+ uint64_t sourceFrames=0,validGenerated=0,submitted=0,expired=0;
+ uint32_t queueWatermark=0;
+};
+}
diff --git a/include/veyra/diagnostics/GpuTimer.h b/include/veyra/diagnostics/GpuTimer.h
new file mode 100644
index 00000000..851c23be
--- /dev/null
+++ b/include/veyra/diagnostics/GpuTimer.h
@@ -0,0 +1,39 @@
+#pragma once
+#include "veyra/diagnostics/FrameMetrics.h"
+#include "veyra/Log.h"
+#include <format>
+namespace veyra::diagnostics {
+// Timestamp query ring, resolved only after the producing fence is complete.
+// No image readback, no CPU waits. Samples carry the identity they measured.
+class GpuTimer {
+ static constexpr unsigned stages=unsigned(GpuStage::Count),slots=4,stride=stages*2;
+ struct Pending{pipeline::FrameIdentity id;uint32_t mask=0;uint64_t fence=0;};
+ Microsoft::WRL::ComPtr<ID3D12QueryHeap> heap_;
+ Microsoft::WRL::ComPtr<ID3D12Resource> readback_;
+ std::array<Pending,slots> pending_{};uint64_t frequency_=0;int active_=-1;
+ FrameMetrics last_;
+public:
+ bool initialize(ID3D12Device* device,ID3D12CommandQueue* queue){
+ close();HRESULT hr=queue->GetTimestampFrequency(&frequency_);if(FAILED(hr)||!frequency_)return false;
+ D3D12_QUERY_HEAP_DESC q{};q.Type=D3D12_QUERY_HEAP_TYPE_TIMESTAMP;q.Count=slots*stride;hr=device->CreateQueryHeap(&q,IID_PPV_ARGS(&heap_));if(FAILED(hr)){log::error("gpu-timestamp",std::format("query heap hr=0x{:X}",unsigned(hr)));return false;}
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC d{};d.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;d.Width=slots*stride*8;d.Height=1;d.DepthOrArraySize=1;d.MipLevels=1;d.SampleDesc.Count=1;d.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ hr=device->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&d,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback_));if(FAILED(hr)){log::error("gpu-timestamp",std::format("readback hr=0x{:X}",unsigned(hr)));return false;}return true;
+ }
+ void collect(ID3D12Fence* fence){if(!readback_||!fence)return;const auto completed=fence->GetCompletedValue();
+ for(unsigned slot=0;slot<slots;++slot){auto& p=pending_[slot];if(!p.fence||p.fence>completed)continue;void* data=nullptr;D3D12_RANGE range{slot*stride*8,(slot+1)*stride*8};auto hr=readback_->Map(0,&range,&data);if(FAILED(hr)){log::error("gpu-timestamp",std::format("Map hr=0x{:X}",unsigned(hr)));p.fence=0;continue;}
+ FrameMetrics m;m.identity=p.id;auto values=static_cast<const uint64_t*>(data)+slot*stride;
+ for(unsigned stage=0;stage<stages;++stage)if(p.mask&(1u<<stage)){auto& v=m.gpu[stage];v.begin=values[stage*2];v.end=values[stage*2+1];v.frequency=frequency_;if(v.end>=v.begin){v.state=SampleState::Measured;v.milliseconds=double(v.end-v.begin)*1000/frequency_;}else v.state=SampleState::Unavailable;
+ log::info("gpu-timestamp",std::format("frame={} epoch={} revision={} stage={} begin={} end={} frequency={} ms={} (GPU queue timestamps)",p.id.sourceFrameId,p.id.epoch,p.id.settingsRevision,stage,v.begin,v.end,frequency_,v.milliseconds.value_or(-1)));
+ }
+ D3D12_RANGE written{0,0};readback_->Unmap(0,&written);if(m.identity.sourceFrameId>=last_.identity.sourceFrameId)last_=m;p.fence=0;
+ }
+ }
+ void frame(pipeline::FrameIdentity id,ID3D12Fence* fence){collect(fence);active_=-1;if(!heap_||!readback_)return;auto i=unsigned(id.sourceFrameId%slots);if(pending_[i].fence)return;active_=int(i);pending_[i]={id,0,0};}
+ void identity(pipeline::FrameIdentity id){if(active_>=0)pending_[active_].id=id;}
+ void mark(ID3D12GraphicsCommandList* list,GpuStage stage,bool end=false){if(active_<0)return;unsigned i=unsigned(stage);list->EndQuery(heap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,active_*stride+i*2+unsigned(end));if(end)pending_[active_].mask|=1u<<i;}
+ void resolve(ID3D12GraphicsCommandList* list){if(active_<0)return;auto mask=pending_[active_].mask;for(unsigned i=0;i<stages;++i)if(mask&(1u<<i)){unsigned index=active_*stride+i*2;list->ResolveQueryData(heap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,index,2,readback_.Get(),index*8);}}
+ void submitted(uint64_t fence){if(active_>=0)pending_[active_].fence=fence;active_=-1;}
+ const FrameMetrics& last()const{return last_;}
+ void close(){heap_.Reset();readback_.Reset();pending_={};last_={};active_=-1;frequency_=0;}
+};
+}
diff --git a/include/veyra/diagnostics/Redaction.h b/include/veyra/diagnostics/Redaction.h
new file mode 100644
index 00000000..99201795
--- /dev/null
+++ b/include/veyra/diagnostics/Redaction.h
@@ -0,0 +1,13 @@
+#pragma once
+#include <regex>
+#include <string>
+namespace veyra::diagnostics {
+inline std::string redact(std::string s){
+ // Fail closed on unknown path formats: remove from a Windows absolute
+ // path to end of line, even when the path contains spaces.
+ s=std::regex_replace(s,std::regex(R"([A-Za-z]:[\\/][^\r\n]*)"),"[本地路径已隐藏]");
+ s=std::regex_replace(s,std::regex(R"(\\\\[^\r\n]*)"),"[设备或网络路径已隐藏]");
+ s=std::regex_replace(s,std::regex(R"((serial|serialnumber|devicepath|username|user)[=: ]+[^\s,;]+)",std::regex::icase),"$1=[已隐藏]");
+ return s;
+}
+}
diff --git a/include/veyra/engine/CfrTimeline.h b/include/veyra/engine/CfrTimeline.h
new file mode 100644
index 00000000..7d2bd643
--- /dev/null
+++ b/include/veyra/engine/CfrTimeline.h
@@ -0,0 +1,47 @@
+#pragma once
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <span>
+#include <utility>
+
+namespace veyra::engine {
+// A rate is only a candidate. All timestamps must fit one common quantizer
+// phase; a one-tick-per-frame time base is legal, a missing whole tick is not.
+class CfrTimeline {
+public:
+ CfrTimeline(int num, int den, double quantum, double origin)
+ : num_(num), den_(den), quantum_(quantum), origin_(origin), low_(-quantum/2), high_(quantum/2) {}
+ bool valid() const {
+ return num_ > 0 && den_ > 0 && fps() <= 120 && fps() >= 1 &&
+ std::isfinite(origin_) && std::isfinite(quantum_) && quantum_ > 0 && quantum_ <= 1.0 / fps() + 1e-12;
+ }
+ double fps() const { return double(num_) / den_; }
+ double expected(uint64_t index) const { return origin_ + double(index) * den_ / num_; }
+ bool accepts(uint64_t index, double pts) {
+ if(!valid() || !std::isfinite(pts) || (havePrevious_ && pts<=previous_))return false;
+ const double error=pts-expected(index);
+ const double ticksPerFrame=1.0/(fps()*quantum_);
+ if(std::abs(ticksPerFrame-std::round(ticksPerFrame))<1e-9 && std::abs(error)>1e-9)return false;
+ const double lo=std::max(low_,error-quantum_/2),hi=std::min(high_,error+quantum_/2);
+ if(lo>hi+1e-9)return false;
+ low_=lo;high_=hi;previous_=pts;havePrevious_=true;return true;
+ }
+ static std::pair<int,int> select(int nominalNum,int nominalDen,double quantum,std::span<const double> samples) {
+ if(samples.empty())return {0,0};
+ auto fits=[&](int n,int d){CfrTimeline t(n,d,quantum,samples.front());for(size_t i=0;i<samples.size();++i)if(!t.accepts(i,samples[i]))return false;return t.valid();};
+ // Prefer a declared standard rate when consistent. Otherwise choose a
+ // simple, timestamp-consistent standard candidate, then the declaration.
+ // Quantized short clips cannot prove a unique exact original rate.
+ const std::pair<int,int> standard[]={{24,1},{25,1},{30,1},{48,1},{50,1},{60,1},{100,1},{120,1},{24000,1001},{30000,1001},{60000,1001},{120000,1001}};
+ for(auto [n,d]:standard)if(int64_t(n)*nominalDen==int64_t(nominalNum)*d && fits(n,d))return {n,d};
+ for(auto [n,d]:standard)if(fits(n,d))return {n,d};
+ if(fits(nominalNum,nominalDen))return {nominalNum,nominalDen};
+ return {0,0};
+ }
+private:
+ int num_, den_;
+ double quantum_, origin_, low_, high_,previous_=0;
+ bool havePrevious_=false;
+};
+}
diff --git a/include/veyra/engine/ContentCadence.h b/include/veyra/engine/ContentCadence.h
new file mode 100644
index 00000000..0ed616dd
--- /dev/null
+++ b/include/veyra/engine/ContentCadence.h
@@ -0,0 +1,28 @@
+#pragma once
+#include <deque>
+#include "veyra/engine/EnhancementSettings.h"
+#include <cmath>
+#include <algorithm>
+namespace veyra::engine {
+// Only reports a rate after repeated moving observations. A static scene
+// cannot establish a lower content frame rate merely through equality.
+class ContentCadence {
+public:
+ void reset(){changes_.clear();deltas_.clear();last_=-1;rate_=0;}
+ void observe(double ptsMs,double sad,bool comparable){
+ if(!comparable||!std::isfinite(ptsMs)){reset();return;}
+ if(last_>=0){const auto d=ptsMs-last_;if(d<=0||d>100){reset();last_=ptsMs;return;}deltas_.push_back(d);if(deltas_.size()>60)deltas_.pop_front();}
+ last_=ptsMs;changes_.push_back(sad>0.002?1:0);if(changes_.size()>60)changes_.pop_front();rate_=0;
+ if(changes_.size()<30||deltas_.empty())return;int changed=0;for(int c:changes_)changed+=c;if(changed<12)return;
+ double elapsed=0;for(double d:deltas_)elapsed+=d;const double transport=1000*deltas_.size()/elapsed;const double candidate=transport*changed/changes_.size();
+ for(int r:{30,50,60})if(std::abs(candidate-r)<1.6)rate_=r;
+ }
+ int measuredRate()const{return rate_;}
+ int confirmedRate(ContentRate mode)const{
+ const int requested=mode==ContentRate::Fps30?30:mode==ContentRate::Fps50?50:mode==ContentRate::Fps60?60:0;
+ return mode==ContentRate::Transport?0:requested?(rate_==requested?rate_:0):rate_;
+ }
+ bool conflicts(ContentRate mode)const{return rate_!=0&&mode>=ContentRate::Fps30&&confirmedRate(mode)==0;}
+private:std::deque<int> changes_;std::deque<double>deltas_;double last_=-1;int rate_=0;
+};
+}
diff --git a/include/veyra/engine/DeadlineWait.h b/include/veyra/engine/DeadlineWait.h
new file mode 100644
index 00000000..aca13061
--- /dev/null
+++ b/include/veyra/engine/DeadlineWait.h
@@ -0,0 +1,25 @@
+#pragma once
+#include <windows.h>
+#include <algorithm>
+#include "veyra/Log.h"
+namespace veyra::engine {
+class DeadlineWait {
+public:
+ DeadlineWait(){
+ timer_=CreateWaitableTimerExW(nullptr,nullptr,CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,TIMER_ALL_ACCESS);
+ if(!timer_){const auto code=GetLastError();timer_=CreateWaitableTimerExW(nullptr,nullptr,0,TIMER_ALL_ACCESS);log::warn("scheduler","high resolution wait timer unavailable; error="+std::to_string(code));}
+ else log::info("scheduler","high resolution waitable timer active; no global timer resolution changes");
+ }
+ ~DeadlineWait(){if(timer_)CloseHandle(timer_);}
+ DeadlineWait(const DeadlineWait&)=delete;
+ DeadlineWait& operator=(const DeadlineWait&)=delete;
+ void slice(double milliseconds=1){
+ if(!timer_){Sleep(1);return;}
+ LARGE_INTEGER due;due.QuadPart=-std::max<LONGLONG>(1,static_cast<LONGLONG>(std::clamp(milliseconds,0.05,2.0)*10000));
+ if(!SetWaitableTimer(timer_,&due,0,nullptr,nullptr,FALSE)){log::error("scheduler","SetWaitableTimer error="+std::to_string(GetLastError()));return;}
+ const auto result=WaitForSingleObject(timer_,10);
+ if(result!=WAIT_OBJECT_0)log::warn("scheduler","wait timer result="+std::to_string(result));
+ }
+private:HANDLE timer_=nullptr;
+};
+}
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index 6bfd7c2c..11172ee4 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -4,19 +4,37 @@
#include <mutex>
#include <string>
#include <thread>
+#include <condition_variable>
+#include <functional>
+#include "veyra/engine/EnhancementSettings.h"
+#include "veyra/diagnostics/FrameMetrics.h"
namespace veyra::engine {
-struct PlayerOptions { bool nr=true,sr=false,fg=false,realtime=true; };
+struct PlayerOptions { bool nr=true,sr=false,fg=false,realtime=true; uint32_t fgMultiplier=2; EnhancementSettings settings;
+ EnhancementSettings snapshot()const{auto s=settings;s.nr=nr;s.sr=sr;s.multiplier=fg?fgMultiplier:1;s.nrPolicy=realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native;return s;}
+ static PlayerOptions from(EnhancementSettings s){PlayerOptions o;o.nr=s.nr;o.sr=s.sr;o.fg=s.multiplier>1;o.fgMultiplier=std::max(2u,s.multiplier);o.realtime=s.nrPolicy==pipeline::NrSizePolicy::Realtime;o.settings=s;return o;}
+};
struct PlayerSnapshot {
- std::wstring status=L"Open a video or image";
+ std::wstring status=L"请打开视频或图片";
+ EnhancementSettings desired,applied;bool applying=false;
double position=0,duration=0,fps=0,lateMs=0,lateP95Ms=0;
+ diagnostics::FrameMetrics metrics;
+ std::optional<double> submissionFps;
+ uint32_t flowPerf=0;int contentFps=0;
uint64_t frames=0,generated=0;
- bool running=false,failed=false,image=false;
+ uint64_t captureReceived=0,captureDropped=0,nrEvaluated=0,nvofExecuted=0;
+ double captureFps=0,captureReadAgeMs=0,captureAgeMs=0,captureAgeP95Ms=0;
+ double schedulingWaitP95Ms=0,processCpuP95Ms=0,presentCpuP95Ms=0;
+ bool running=false,failed=false,image=false,capture=false;
};
class EngineController {
public:
- ~EngineController(){stop();}
+ EngineController();
+ ~EngineController();
+ bool idle()const;
+ bool requestSettings(EnhancementSettings);
void open(HWND video,const std::wstring& path,PlayerOptions options);
void stop();
+ void comparison(int mode,bool base,float split=.5f){comparisonMode_=mode;comparisonBase_=base;comparisonSplit_=std::clamp(split,0.0f,1.0f);}
void pause(bool p){paused_.store(p);}
void seek(double seconds){seekSeconds_.store(seconds);}
void saveFrame(const std::wstring& path);
@@ -24,12 +42,17 @@ public:
PlayerSnapshot snapshot()const;
private:
void run(HWND,std::wstring,PlayerOptions);
+ void post(std::function<void()>);
+ void dispatch();
void status(const std::wstring&,bool failed=false);
mutable std::mutex mutex_;
PlayerSnapshot snapshot_;
std::wstring savePath_;
std::thread worker_;
+ std::condition_variable wake_;std::function<void()> pending_;bool shutdown_=false,busy_=false;
+ EnhancementSettings desired_;uint64_t nextRevision_=1;
std::atomic<bool> stop_{false},paused_{false};
std::atomic<double> seekSeconds_{-1};
+ std::atomic<int> comparisonMode_{0};std::atomic<bool> comparisonBase_{false};std::atomic<float> comparisonSplit_{.5f};
};
}
diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.h
new file mode 100644
index 00000000..bd3c56ae
--- /dev/null
+++ b/include/veyra/engine/EnhancementSettings.h
@@ -0,0 +1,41 @@
+#pragma once
+#include <cmath>
+#include <cstdint>
+#include <string>
+#include "veyra/pipeline/ResolutionPlan.h"
+namespace veyra::engine {
+enum class FlowQuality { Performance, Balanced, Quality };
+enum class ContentRate { Transport, Auto, Fps30, Fps50, Fps60 };
+struct NrSettings {
+ float intensity=1,tone=1,structure=1,skin=-1;
+ int32_t style=0,autoMask=0,uiCorrection=0;
+ bool operator==(const NrSettings&) const = default;
+};
+struct ResidualSettings {
+ float total=1,darken=1,brighten=1,color=1,luminance=1;
+ bool operator==(const ResidualSettings&) const = default;
+};
+struct EnhancementSettings {
+ uint64_t revision=1;
+ NrSettings model;
+ ResidualSettings residual;
+ bool nr=true,sr=false;
+ uint32_t multiplier=1;
+ pipeline::NrSizePolicy nrPolicy=pipeline::NrSizePolicy::Realtime;
+ FlowQuality flow=FlowQuality::Balanced;
+ ContentRate content=ContentRate::Transport;
+ 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(!revision)return "settingsRevision must be nonzero";
+ 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";
+ for(float v:{residual.total,residual.darken,residual.brighten,residual.color,residual.luminance})if(!range(v,2))return "residual parameter out of range";
+ if(multiplier<1||multiplier>4)return "unsupported multiplier";
+ if(nrPolicy!=pipeline::NrSizePolicy::Realtime&&nrPolicy!=pipeline::NrSizePolicy::Native)return "invalid NR size policy";
+ if(flow<FlowQuality::Performance||flow>FlowQuality::Quality||content<ContentRate::Transport||content>ContentRate::Fps60)return "invalid flow/content mode";
+ return {};
+ }
+};
+}
diff --git a/include/veyra/engine/LivePresentationTiming.h b/include/veyra/engine/LivePresentationTiming.h
new file mode 100644
index 00000000..3ae58906
--- /dev/null
+++ b/include/veyra/engine/LivePresentationTiming.h
@@ -0,0 +1,13 @@
+#pragma once
+#include <algorithm>
+#include <cmath>
+
+namespace veyra::engine {
+// Live capture never waits on an absolute source PTS. Once B is available,
+// display generated(A,B), then B up to half an input interval later. Anchor
+// each pair to current host time, not to the first (possibly stale) sample.
+inline double livePairHoldMs(bool hasGenerated,double realPtsMs,double generatedPtsMs) {
+ if(!hasGenerated||!std::isfinite(realPtsMs)||!std::isfinite(generatedPtsMs))return 0;
+ return std::clamp(realPtsMs-generatedPtsMs,0.0,1000.0/30.0);
+}
+}
diff --git a/include/veyra/engine/PresentationScheduler.h b/include/veyra/engine/PresentationScheduler.h
new file mode 100644
index 00000000..a6aa4778
--- /dev/null
+++ b/include/veyra/engine/PresentationScheduler.h
@@ -0,0 +1,17 @@
+#pragma once
+#include <cstdint>
+namespace veyra::engine {
+// Maps a continuous source epoch to one monotonic host timeline. Processing
+// completion must never re-anchor individual pairs. Units are 100 ns.
+class PresentationScheduler {
+public:
+ void reset(uint64_t epoch,int64_t source,int64_t host,int64_t lookahead) {
+ epoch_=epoch;source_=source;host_=host;delay_=lookahead;anchored_=true;
+ }
+ bool anchored(uint64_t epoch)const{return anchored_&&epoch==epoch_;}
+ int64_t deadline(int64_t pts)const{return host_+(pts-source_)+delay_;}
+ bool expired(int64_t pts,int64_t now,int64_t tolerance)const{return now>deadline(pts)+tolerance;}
+private:
+ uint64_t epoch_=0;int64_t source_=0,host_=0,delay_=0;bool anchored_=false;
+};
+}
diff --git a/include/veyra/engine/PresetStore.h b/include/veyra/engine/PresetStore.h
new file mode 100644
index 00000000..8728c8cf
--- /dev/null
+++ b/include/veyra/engine/PresetStore.h
@@ -0,0 +1,28 @@
+#pragma once
+#include "veyra/engine/EnhancementSettings.h"
+#include <filesystem>
+#include <vector>
+namespace veyra::engine {
+struct UserPreset { std::wstring name; EnhancementSettings settings; };
+// Strict versioned whitelist schema; no paths, devices, or executable fields.
+class PresetStore {
+public:
+ explicit PresetStore(std::filesystem::path path):path_(std::move(path)){}
+ bool load();
+ bool save();
+ bool put(std::wstring name,EnhancementSettings,bool replace=false);
+ bool rename(size_t,std::wstring);
+ bool erase(size_t);
+ bool setDefault(size_t);
+ EnhancementSettings defaultSettings()const;
+ const std::vector<UserPreset>& entries()const{return entries_;}
+ const std::wstring& error()const{return error_;}
+private:
+ static bool parse(const std::string&,std::vector<UserPreset>&,std::wstring&);
+ std::string serialize()const;
+ std::filesystem::path path_;
+ std::vector<UserPreset> entries_;
+ std::wstring default_,error_;
+ bool corrupt_=false;
+};
+}
diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.h
index 06fa2111..623124c5 100644
--- a/include/veyra/engine/VideoPresenter.h
+++ b/include/veyra/engine/VideoPresenter.h
@@ -1,20 +1,26 @@
#pragma once
+#include "veyra/diagnostics/GpuTimer.h"
#include "veyra/gfx/PresentSink.h"
#include "veyra/pipeline/GpuPassUtils.h"
+#include <chrono>
namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }
namespace veyra::pipeline { class EnhanceGraph; }
namespace veyra::engine {
class VideoPresenter {
public:
bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&);
- bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated);
+ bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={});
void close();
+ uint64_t submittedCount() const {return sink_.presentCount();}
+diagnostics::GpuSample blitTiming(ID3D12Fence* f){gpuTimer_.collect(f);return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}
private:
+ diagnostics::GpuTimer gpuTimer_;
gfx::PresentSink sink_;
pipeline::GraphicsPass pass_;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> rtvs_;
unsigned inc_=0;
HWND window_=nullptr;
+ std::chrono::steady_clock::time_point lastResize_{};
void refresh(ID3D12Device*);
};
}
diff --git a/include/veyra/gfx/CommandSlotRing.h b/include/veyra/gfx/CommandSlotRing.h
index 16e410f0..abcd4107 100644
--- a/include/veyra/gfx/CommandSlotRing.h
+++ b/include/veyra/gfx/CommandSlotRing.h
@@ -46,9 +46,16 @@ public:
// Waits for this slot's outstanding fence value (if any), then resets the
// allocator and command list. Returns the recycled list ready for record.
ID3D12GraphicsCommandList* acquire(uint32_t slot, Status& status);
+ // Shared cursor for graph and presenter: independent cursors can select
+ // the allocator just submitted by the other consumer and serialize frames.
+ ID3D12GraphicsCommandList* acquireNext(uint32_t& slot,Status& status) {
+ if(!slotCount_){status=Status::InvalidArgument;return nullptr;}
+ slot=nextSlot_++%slotCount_;return acquire(slot,status);
+ }
// Closes, submits and signals the slot; advances the fence timeline.
bool submitAndSignal(uint32_t slot);
+ bool discardRecording(); // Error rollback: never execute a partially recorded list.
void tag(uint32_t slot,const char* label){slots_.at(slot).label=label;}
// The fence value most recently signaled by this ring. Callers that need
@@ -82,12 +89,13 @@ private:
ComPtr<ID3D12CommandAllocator> allocator;
ComPtr<ID3D12GraphicsCommandList> list;
uint64_t fenceValue = 0; // 0 means "never submitted"
- bool timed = false;
+ bool timed = false,recording=false;
std::string label;
};
bool initialized_ = false;
uint32_t slotCount_ = 0;
+ uint32_t nextSlot_ = 0;
ID3D12Device* device_ = nullptr;
ID3D12CommandQueue* queue_ = nullptr;
ID3D12Fence* fence_ = nullptr;
diff --git a/include/veyra/media/FFmpegDemuxer.h b/include/veyra/media/FFmpegDemuxer.h
index 3667d45e..a7888e5a 100644
--- a/include/veyra/media/FFmpegDemuxer.h
+++ b/include/veyra/media/FFmpegDemuxer.h
@@ -34,6 +34,8 @@ public:
int videoStreamIndex() const { return videoStreamIndex_; }
int64_t durationUs() const;
double averageFps() const; // informational only; the pipeline is PTS-driven
+ int nominalRateNum() const;
+ int nominalRateDen() const;
const AVCodecParameters* videoCodecParameters() const;
int videoTimeBaseNum() const; // stream time_base for frame PTS conversion
int videoTimeBaseDen() const;
diff --git a/include/veyra/ngx/DlssFgBackend.h b/include/veyra/ngx/DlssFgBackend.h
index 1e7398a1..cbe0497e 100644
--- a/include/veyra/ngx/DlssFgBackend.h
+++ b/include/veyra/ngx/DlssFgBackend.h
@@ -64,6 +64,7 @@ public:
uint64_t frameId; // monotonically increasing real-frame id
float mvecScaleX; // convention under test (Playbook 14.2)
float mvecScaleY;
+ uint32_t multiFrameCount=1,multiFrameIndex=1;
};
// Queries FrameGeneration capability through NVSDK_NGX_GetCapabilityParameters.
diff --git a/include/veyra/ngx/NvOfSession.h b/include/veyra/ngx/NvOfSession.h
index f85dd597..677f2304 100644
--- a/include/veyra/ngx/NvOfSession.h
+++ b/include/veyra/ngx/NvOfSession.h
@@ -36,10 +36,12 @@ public:
ID3D12Fence* inFence = nullptr; // signaled when inputs are GPU-ready
ID3D12Fence* outFence = nullptr; // signaled when flow is GPU-ready
// P0.4: raw output lives at hardware-grid extent in SHORT2 (S10.5).
+ uint32_t quality=1; // 0 performance / 1 balanced / 2 quality; mapped to SDK symbols
uint32_t gridSize = 4; // requested grid (validated vs caps)
};
struct Caps {
+ uint32_t requestedQuality=1,appliedQuality=1,actualPerfLevel=0;
bool queried = false;
std::vector<uint32_t> supportedGrids; // raw capability list (two-call protocol)
uint32_t minWidth = 0, maxWidth = 0, minHeight = 0, maxHeight = 0;
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index db6342c3..70c5777b 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -24,6 +24,10 @@
#include "veyra/pipeline/GpuPassUtils.h"
#include "veyra/core/SceneCadenceAnalyzer.h"
+#include "veyra/pipeline/FrameBatch.h"
+#include "veyra/engine/EnhancementSettings.h"
+#include "veyra/engine/ContentCadence.h"
+#include "veyra/diagnostics/GpuTimer.h"
struct AVFrame;
struct SwsContext;
@@ -56,6 +60,13 @@ struct EnhanceGraphDesc {
bool enableNvofStandalone = false; // run NVOF+densify per frame without FG (quality core)
bool noFeatures = false; // VEYRA_NO_FEATURES: NVOF/NGX objects skipped
bool noNgx = false; // VEYRA_NO_NGX: core/features skipped, NVOF only
+ uint32_t nrWidth=0,nrHeight=0; // zero preserves legacy native working extent
+ uint32_t fgMultiplier=2;
+ uint64_t settingsRevision=1;
+ engine::FlowQuality flowQuality=engine::FlowQuality::Balanced;
+ engine::ContentRate contentRate=engine::ContentRate::Transport;
+ engine::NrSettings model;
+ engine::ResidualSettings residual;
std::wstring runtimeAbsPath; // absolute runtime_local/nvidia path
// Optional stage instrumentation hook (GPU timing experiments).
std::function<void(const char*)> stageMark;
@@ -76,6 +87,8 @@ public:
bool createViews();
struct FrameOutputs {
+ FrameBatch batch;
+ bool contentDuplicate=false;int measuredContentRate=0;
double ptsMs = 0.0;
uint32_t videoSlot = 0; // videoFrame[videoSlot] holds this real frame
uint64_t videoFenceValue = 0; // ring fence covering the video work
@@ -92,7 +105,11 @@ public:
// does not own the demuxer). `reset` marks the first frame of a new
// temporal epoch (open/seek/...): NVOF/FG history is not consumed.
// Returns false on hard failure (run verdict must FAIL).
- bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out);
+ bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0);
+ // Nonblocking. The scheduler polls at a GPU-ready/deadline boundary; no
+ // full image readback and no waits inside the graph's individual passes.
+ bool resolveGeneration(FrameOutputs& out);
+ bool applySettings(const engine::EnhancementSettings&);
// s10 ownership-order teardown: NVOF fence drain must happen BEFORE this
// call (it needs the ring and out-fence alive). Releases features, NVOF
@@ -106,6 +123,7 @@ public:
uint64_t nvofExecuteCount = 0;
uint64_t nvofFrameFailures = 0;
uint64_t fgGeneratedFrames = 0;
+ uint64_t fgSubmittedCandidates = 0, fgDisabledFrames = 0;
uint64_t nrMotionFrames = 0, sceneCutCount = 0, resetCount = 0;
};
const Metrics& metrics() const { return metrics_; }
@@ -116,6 +134,13 @@ public:
uint32_t sourceHeight() const { return srcH_; }
uint32_t workWidth() const { return workW_; }
uint32_t workHeight() const { return workH_; }
+ uint32_t nrWidth() const {return nrW_;}
+ uint32_t nrHeight() const {return nrH_;}
+ uint32_t actualFlowPerf() const;
+ diagnostics::FrameMetrics gpuMetrics(){gpuTimer_.collect(contextFence());return gpuTimer_.last();}
+ ID3D12Fence* contextFence() const;
+ ID3D12Resource* baseReference(unsigned slot=0)const{return baseReferences_[slot%2].Get();}
+ ID3D12Resource* sourceReference(unsigned slot=0)const{return sourceReferences_[slot%2].Get();}
bool srEnabled() const { return srEnabled_; }
bool nrEnabled() const { return nrEnabled_; }
bool fgEnabled() const { return fgEnabled_; }
@@ -159,6 +184,7 @@ private:
bool initialized_ = false;
uint32_t srcW_ = 0, srcH_ = 0, workW_ = 3840, workH_ = 2160;
+ uint32_t nrW_=0,nrH_=0;
uint32_t nvofW_ = 0, nvofH_ = 0, rawW_ = 0, rawH_ = 0, nvofGrid_ = 4, selectedGrid_ = 4;
bool srEnabled_ = false, nrEnabled_ = false, fgEnabled_ = false, nvofStandalone_ = false;
size_t lumaPitch_ = 0, chromaPitch_ = 0, lumaSize_ = 0, chromaSize_ = 0, dPitch_ = 0;
@@ -173,6 +199,7 @@ private:
ComPtr<ID3D12Resource> chromaTex_;
ComPtr<ID3D12Resource> srcRgba_;
ComPtr<ID3D12Resource> workRgba_;
+ ComPtr<ID3D12Resource> nrInput_,residualRgba_,nrFlow_,baseFlow_;
ComPtr<ID3D12Resource> proxyTex_;
ComPtr<ID3D12Resource> neuralTex_;
ComPtr<ID3D12Resource> finalRgba_;
@@ -180,7 +207,8 @@ private:
ComPtr<ID3D12Resource> confTex_;
ComPtr<ID3D12Resource> flowTex_;
ComPtr<ID3D12Resource> depthTex_;
- ComPtr<ID3D12Resource> genFrame_[2];
+ ComPtr<ID3D12Resource> genFrame_[6];
+ ComPtr<ID3D12Resource> fgDisable_[6],fgDisableReadback_[6],fgDisableInit_;
ComPtr<ID3D12Resource> nrZeroMotion_;
ComPtr<ID3D12Resource> nrZeroDepth_;
ComPtr<ID3D12Resource> nvofRawTex_;
@@ -192,8 +220,12 @@ private:
std::vector<uint8_t> nv12Buf_;
ComputePass yuvPass_, encPass_, decPass_, blitPass_, uploadPass_, densifyPass_;
+ ComputePass downsamplePass_,residualPass_,flowAdaptPass_;
DescriptorStager stager_;
+ Microsoft::WRL::ComPtr<ID3D12Resource> sourceReferences_[2],baseReferences_[2];
StateTracker tracker_;
+ engine::ContentCadence cadence_;
+ diagnostics::GpuTimer gpuTimer_;
SwsContext* nv12Ctx_ = nullptr;
// NVOF + NGX (owned by the graph, render-thread only).
@@ -213,6 +245,8 @@ private:
// Per-run state.
uint64_t realFrameIndex_ = 0;
+ uint64_t epoch_ = 0;
+ std::weak_ptr<FrameLease> realLeases_[2],generatedLeases_[6];
uint32_t nextListSlot_ = 0;
uint64_t uploadFences_[2] = {};
core::SceneCadenceAnalyzer scene_;
diff --git a/include/veyra/pipeline/FrameBatch.h b/include/veyra/pipeline/FrameBatch.h
new file mode 100644
index 00000000..f78f8520
--- /dev/null
+++ b/include/veyra/pipeline/FrameBatch.h
@@ -0,0 +1,48 @@
+#pragma once
+#include <array>
+#include <cstdint>
+#include <memory>
+#include <stdexcept>
+#include <d3d12.h>
+#include <wrl/client.h>
+namespace veyra::pipeline {
+enum class FrameKind { Real, Generated, Hold };
+enum class GenerationValidity { NotApplicable, Pending, Valid, Disabled, Failed };
+struct FrameIdentity {
+ uint64_t epoch=0,settingsRevision=0,sourceFrameId=0;
+ bool operator==(const FrameIdentity&) const = default;
+};
+// A lease keeps the resource alive; the producer additionally waits for the
+// consumer fence before overwriting a pool slot. COM lifetime alone is insufficient.
+struct FrameLease {
+ Microsoft::WRL::ComPtr<ID3D12Resource> texture,sourceReference,baseReference;
+ uint64_t readyFence=0,consumerFence=0;
+ uint32_t slot=0;
+};
+struct BatchFrame {
+ FrameIdentity identity;
+ FrameKind kind=FrameKind::Real;
+ GenerationValidity validity=GenerationValidity::NotApplicable;
+ uint32_t subframe=0;
+ int64_t pts100ns=0;
+ std::shared_ptr<FrameLease> lease;
+};
+struct FrameBatch {
+ uint64_t batchId=0;
+ FrameIdentity identity;
+ int64_t a100ns=0,b100ns=0;
+ std::array<BatchFrame,4> frames{};
+ uint32_t count=0;
+ static int64_t interpolate(int64_t a,int64_t b,uint32_t j,uint32_t n) {
+ // The application accepts at most one second between continuous endpoints.
+ if(n<2||n>4||j==0||j>=n||b<=a||a>INT64_MAX-10000000||b>a+10000000)
+ throw std::invalid_argument("invalid interpolation interval");
+ const int64_t d=b-a;return a+(d/n)*j+((d%n)*j+n/2)/n;
+ }
+ void append(BatchFrame frame) {
+ if(count==frames.size()||frame.identity!=identity||(count&&frame.pts100ns<=frames[count-1].pts100ns))
+ throw std::invalid_argument("cross-revision or unordered frame batch");
+ frames[count++]=std::move(frame);
+ }
+};
+}
diff --git a/include/veyra/pipeline/ResolutionPlan.h b/include/veyra/pipeline/ResolutionPlan.h
new file mode 100644
index 00000000..0d3184bb
--- /dev/null
+++ b/include/veyra/pipeline/ResolutionPlan.h
@@ -0,0 +1,27 @@
+#pragma once
+#include <algorithm>
+#include <cstdint>
+#include <stdexcept>
+namespace veyra::pipeline {
+struct Extent {
+ uint32_t width=0,height=0;
+ bool operator==(const Extent&) const = default;
+ bool valid() const {return width>=2&&height>=2&&width<=3840&&height<=2160&&!(width%2)&&!(height%2);}
+};
+enum class NrSizePolicy { Realtime, Native };
+struct ResolutionPlan {
+ Extent source,base,nr,flow,fg,output;
+ bool srApplied=false;
+ uint64_t settingsRevision=0;
+ static ResolutionPlan make(Extent source,bool sr,NrSizePolicy policy,bool exporting,uint64_t revision=0) {
+ if(!source.valid())throw std::invalid_argument("invalid SDR source extent");
+ ResolutionPlan p; p.source=source;p.base=sr?Extent{3840,2160}:source;
+ p.srApplied=sr&&p.base!=source;p.nr=p.base;
+ if(!exporting&&policy==NrSizePolicy::Realtime) {
+ const double scale=std::min({1.0,1920.0/p.base.width,1080.0/p.base.height});
+ p.nr={std::max(2u,uint32_t(p.base.width*scale)&~1u),std::max(2u,uint32_t(p.base.height*scale)&~1u)};
+ }
+ p.flow=source;p.fg=p.output=p.base;p.settingsRevision=revision;return p;
+ }
+};
+}
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index bbf18243..7d7a95c5 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -4,12 +4,21 @@
#include <vector>
namespace veyra::source {
struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;};
+struct CaptureMetrics {
+ uint64_t received=0, delivered=0, dropped=0;
+ double callbackFps=0, readAgeMs=0, frameAgeMs=0;
+};
class CaptureCardSource final:public IFrameSource {
public:
CaptureCardSource();~CaptureCardSource()override;
static std::vector<std::wstring> devices(bool audio=false);
static std::vector<CaptureFormat> formats(unsigned device);
bool open(const SourceOpenDesc&)override;
+ // Negotiate/allocate before GPU initialization, but do not queue frames
+ // or start audio until the presenter and enhancement graph are ready.
+ bool configure(const SourceOpenDesc&);
+ bool start();
+ CaptureMetrics metrics()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/IFrameSource.h b/include/veyra/source/IFrameSource.h
index 54a89b49..a1d1d569 100644
--- a/include/veyra/source/IFrameSource.h
+++ b/include/veyra/source/IFrameSource.h
@@ -29,6 +29,8 @@ struct SourceInfo {
uint32_t height = 0;
pipeline::Rational duration;
double averageFps = 0.0; // informational only; the pipeline is PTS-driven
+ int nominalRateNum = 0, nominalRateDen = 0; // candidate, not proof of CFR
+ double timestampQuantum = 0.0;
bool hardwareDecodeActive = false;
pipeline::ColorDescription color;
};
diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.md
index a4308cb1..1e99221e 100644
--- a/loop/EVIDENCE.md
+++ b/loop/EVIDENCE.md
@@ -1,6 +1,10 @@
# Veyra Gate Evidence
-## FINAL current binary / independent PASS — 2026-09-07
+## Current capture fix candidate — 2026-09-07 (not independently approved)
+
+EXE4A9BA4B321DEEC17C5E3562AF03EF75A316856200A8708FA8E692475A05B59C9. Actual real-card source FPS~49.4–49.8 atMJPEG1080p50,0capture drops; final NR195/NVOF193/FG193. Logs `logs/capture-fix-20260907/`. Visible file/image/export gate `logs/delivery/01b72df768524af9ab0aa8d2e3dbb59e/result.json`,47.309s,21 checks. Full evidence/caveats `docs/CAPTURE_LATENCY_FIX_2026-09-07.md`. Reviewer attempt ended without verdict, needs_review; old PASS below only applies to its old binary. Do not mark physical latency/audio/FG display cadence verified.
+
+## Historical delivered binary / independent PASS — 2026-09-07
Current EXE SHA256 70DD23C44337004FC734FBAE8BB6139E185C52370AE97CCE6C3432A3C6F30DE1. New-context Reviewer preflight/phase5 (consolidated delivery) exit0/0, PASS, no reviewer source mutations. logs/delivery/9be0614da5d642e394a35c71d80f6207/result.json,40.31s. Initial3 P1 fixed and independently reproduced correction: image4K dimensions, cancel callback lifetime43encodes exit3/partial only, audio fail-closed code review. Review persisted docs/REVIEW_F6.md. Local contract only; awaiting_user_capture_test and distribution_blocked remain.
@@ -355,3 +359,9 @@ INCOMPLETE stub 崩溃样本。
- State action: Phase 5 reopened; Phase 6/7 locked; lastGoodCommit restored to Phase 4 content checkpoint `8cdf1ea2f9b0bb1331f9219a2305cef5efd3c8d8`.
- No new RTX runtime test, phase gate, Reviewer or checkpoint was claimed in this audit.
- Post-rebaseline preflight: 70/70, exit 0; final control manifest hash `45A54E674D32A8055B338C0AE9B77F4A6440D7BC08D4BCF00D27CE8E01D556BF`; phase sequence/state/evidence/Git-pointer checks all passed.
+
+## Repair v2 handoff — 2026-09-08
+Current evidence and unresolved review findings: docs/REPAIR_PROGRESS_2026-09-08.md. Latest joint: logs/repair-v2/joint-bb22bfa233ee455ca030ba0eccdf5a86/result.json (15 software cases exit0; final static review NOT passed). Budget ledger: logs/repair-v2/runtime-budget.json, 260.5401069 seconds spent. User requested stop and new-session continuation; no new Phase pass.
+
+## Repair v2 final known-fix delivery 2026-09-08
+Joint joint-a077b89fd39348e4a49f4195c9d4e416: 18/18 software checks, 71.0278864s. EXE 1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266. Read-only review_known_fixes PASS in scoped fixes; global needs_review and old Phase fields unchanged. Per-invocation <=300 seconds; cumulative 346.3985650s preserved. Full evidence, failures and performance limits: docs/REPAIR_V2_DELIVERY_2026-09-08.md. No capture or publication.
diff --git a/loop/JOURNAL.md b/loop/JOURNAL.md
index 09bf6ba1..c8f6f199 100644
--- a/loop/JOURNAL.md
+++ b/loop/JOURNAL.md
@@ -1261,3 +1261,25 @@ C staged teardown 定位崩溃=swapChain_.Release,矩阵证明 NVOF+debug layer+
- 产品代码动作:无。未 reset、未恢复 tracked clip、未提交旧 Agent 的 dirty tree。
- 下一任务:新 Maker R0.1 接管指纹,然后 R1.1 重建 phase5 gate 并先红。
- 收尾验证:10 个 control hash 与 manifest hardcode 已同步;修改后 preflight 70/70 exit 0,STATE phase sequence/current phase/Git links 全绿。
+# 2026-09-07 Capture latency repair (user explicitly requested implementation)
+
+Task: repair the reproduced live-capture scheduling defect, not change drivers or external apps. Evidence: `logs/capture-diag-20260907/FINDINGS.md`; original PTS pacing produced 29 frames / 4 s without GPU, removing that wait produced 185. Preserve the user's deleted validation clip and settings.
+
+Plan: (1) owned two-buffer/capacity-one capture mailbox, configure/start split and explicit timing/reset metadata; (2) live arrival-based scheduling with bounded FG half-interval, retaining file audio/PTS scheduling; (3) rotating presentation command slots and honest capture timing display; (4) short real-card off/NR/FG runs and file/image regressions, all test invocations under 300 s; (5) independent read-only review and update real delivery evidence. No production fix was applied in the preceding diagnosis. No proprietary binaries will be modified/distributed.
+
+Result: implemented; source8/8 and timing7/7, real-card~49.4–49.8fps/0drops, finalNR195/NVOF193/FG193, visible combined regression21checks/47.309s exit0. Evidence `docs/CAPTURE_LATENCY_FIX_2026-09-07.md`. Independent reviewer attempt did not complete; STATE needs_review, no checkpoint. Original user INI hash unchanged after tests; physical photon latency/audio/FG display cadence are not claimed. Next is user experience confirmation and independent review, not more blind performance loops.
+
+## 2026-09-07 repair-v2 R0 / R1 started (ordinary authorized task)
+
+User attachment explicitly authorizes R0–R9, native MFG 3X/4X and B1–B5. Preserve needs_review and historical phase fields; no Goal or protected control edits. Baseline dirty diff SHA256 7CEB994CBAA1D48B64F2E019AD686F9CE9BF630F7A2F0125282B20C6B4E75661, HEAD d8f1964. Baseline EXE 4A9BA4B321DEEC17C5E3562AF03EF75A316856200A8708FA8E692475A05B59C9. Root NR/add-on identities match; staged NR matches. Existing tracked edits and untracked additions are keep/repair assets; deleted tracked test_h264_1080p.mp4 stays deleted. No obsolete assets removed. Baseline status, binary diff and protected hashes: logs/repair-v2/r0-20260907. git diff --check exit 0. CMake absent from interactive PATH; use existing VS build wrapper.
+
+R1 intent: add bounded FrameBatch identity/lease contract, separate resolution plan, validated settings, nullable GPU/display metrics and bounded diagnostics. Production wiring follows; headers alone are not completed features. Runtime test budget consumed: 0 seconds so far. No capture use, runtime execution, downloads, commits or publication.
+
+## 2026-09-08 Repair v2 — user-requested handoff
+User stopped this session for a new conversation. No further code/build/tests. Saved docs/REPAIR_PROGRESS_2026-09-08.md; status remains needs_review. Joint 15 checks passed before final reviewer found quantized CFR, incomplete Desc rollback, and missing diagnostic failure-code issues. Runtime budget spent 260.5401069 / 300 seconds; do not reset.
+
+## 2026-09-08 Resume: per-invocation test limit and reviewer fixes
+User explicitly clarified 300 seconds means each test invocation, not lifetime aggregate. Kept cumulative ledger; repaired the standalone acceptance timer. Implemented timestamp-consistent CFR candidate/quantizer validation, full previousDesc rollback, NVOF/NGX failure diagnostics, cached source identity/count separation. First MKV test exposed incorrect container declaration 29990/499; it was not accepted as correct output. Updated to bounded metadata-only sampling with continued per-frame validation; negative PTS uses export preflight close/open, not UI seek. Fractional rounding unit initially failed; endpoint tolerance plus exact integral tick verification fixed it. Independent read-only reviewer review_known_fixes is checking the final code/evidence. No protected gate/control/runtime edits or capture activity.
+
+## Repair v2 final known-fix delivery 2026-09-08
+Joint joint-a077b89fd39348e4a49f4195c9d4e416: 18/18 software checks, 71.0278864s. EXE 1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266. Read-only review_known_fixes PASS in scoped fixes; global needs_review and old Phase fields unchanged. Per-invocation <=300 seconds; cumulative 346.3985650s preserved. Full evidence, failures and performance limits: docs/REPAIR_V2_DELIVERY_2026-09-08.md. No capture or publication.
diff --git a/loop/STATE.json b/loop/STATE.json
index 8efa487e..700838a3 100644
--- a/loop/STATE.json
+++ b/loop/STATE.json
@@ -2,11 +2,11 @@
"schemaVersion": 1,
"engineVersion": "veyra-loop-v1",
"objective": "Ship Launch V1, not an MVP: one shared engine, native 4K SDR capture/player/export, Feature 18, DLSSG 2X, bounded live lookahead, D3D12 NVENC H.264/HEVC, and product recovery/diagnostics.",
- "status": "distribution_blocked",
+ "status": "needs_review",
"phase": {
"id": 7,
- "name": "Local player/capture/export delivery (user hardware acceptance pending)",
- "state": "passed",
+ "name": "Capture latency repair; physical throughput retested, review/user experience pending",
+ "state": "gate_passed",
"gate": "phase7"
},
"phases": [
@@ -68,10 +68,10 @@
},
{
"id": 7,
- "name": "Local player/capture/export delivery (user hardware acceptance pending)",
- "status": "passed",
- "gateEvidence": "logs/delivery/9be0614da5d642e394a35c71d80f6207/result.json: shared delivery body invoked by independent phase5 wrapper; consolidated user-authorized F6 scope (not original full specification)",
- "reviewEvidence": "docs/REVIEW_F6.md: independent read-only PASS; covers current Phase5-7 local delivery together",
+ "name": "Capture latency repair; physical throughput retested, review/user experience pending",
+ "status": "gate_passed",
+ "gateEvidence": "logs/delivery/01b72df768524af9ab0aa8d2e3dbb59e/result.json plus logs/capture-fix-20260907/final-nr-fg.log; capture latency repair candidate",
+ "reviewEvidence": "Current repair attempt ended without a final reviewer verdict. docs/REVIEW_F6.md applies only to the historical checkpoint below.",
"commit": "d681541a8fca77e3bfd5f496c8ee2dfe2d6a9031"
}
],
@@ -83,12 +83,12 @@
"noProgressCycles": 0,
"maximumNoProgressCycles": 5
},
- "currentTask": "Local software delivered; independent reviewed short contract passed. No autonomous expansion or publication.",
+ "currentTask": "Repair v2 known defects fixed and read-only reviewed; broader physical/performance acceptance remains.",
"lastGate": {
- "name": "phase5 consolidated delivery",
+ "name": "visible consolidated delivery regression",
"status": "passed",
"exitCode": 0,
- "evidence": "logs/delivery/9be0614da5d642e394a35c71d80f6207/result.json"
+ "evidence": "logs/delivery/01b72df768524af9ab0aa8d2e3dbb59e/result.json"
},
"lastFailureFingerprint": null,
"failureLedger": [],
@@ -96,13 +96,14 @@
"lastGoodCommit": "d681541a8fca77e3bfd5f496c8ee2dfe2d6a9031",
"openP0P1Findings": [],
"blockers": [
- "Capture hardware absent: awaiting user capture test.",
+ "Read-only reviewer attempt failed without final verdict; needs_review, no new checkpoint.",
+ "Current USB2 1080p50 physical throughput passed; user perceived latency/audio/actual FG display cadence still need confirmation.",
"Public proprietary runtime distribution rights unresolved; local delivery only."
],
- "nextAction": "User connects physical capture card and follows docs/USER_GUIDE.md. Public packaging requires separate explicit license/distribution approval.",
- "updatedAt": "2026-09-06T17:02:49.809Z",
+ "nextAction": "User accepts current EXE on capture hardware; see docs/REPAIR_V2_DELIVERY_2026-09-08.md for measured performance limits.",
+ "updatedAt": "2026-09-07T13:20:00Z",
"deliveryPlan": "docs/ACTIVE_DELIVERY_PLAN.md",
- "captureAcceptance": "awaiting_user_capture_test",
+ "captureAcceptance": "throughput_short_test_passed_user_latency_audio_pending",
"testInvocationLimitSeconds": 300,
"currentEvidence": [
"logs/f6-diag.json: diagnostic native1080 12frames exit0 (prior to statistics stride correction rebuild)",
@@ -111,6 +112,45 @@
"preflight 71 checks exit0"
],
"reviewBaseCommit": "6f0ebaa687e3966d989bf138c86b6882380f20fb",
- "localDelivery": "delivered",
- "acceptanceScope": "User-approved short local software contract, default realtime4K-input/1080working, optional native4K playback, native4K exports; capture hardware acceptance reserved for user."
+ "localDelivery": "capture_fix_candidate_needs_review",
+ "acceptanceScope": "User-approved short local software contract, default realtime4K-input/1080working, optional native4K playback, native4K exports; capture hardware acceptance reserved for user.",
+ "repairV2": {
+ "status": "known_fixes_review_passed",
+ "execution": "local_repair_delivered_user_acceptance_pending",
+ "report": "docs/REPAIR_V2_DELIVERY_2026-09-08.md",
+ "testLimitScope": "per_invocation",
+ "testLimitSeconds": 300,
+ "runtimeSpentSeconds": 346.3985649999999,
+ "jointRuntimeSeconds": 71.02788640000001,
+ "jointEvidence": "logs/repair-v2/joint-a077b89fd39348e4a49f4195c9d4e416/result.json",
+ "reviewer": "review_known_fixes: readonly PASS within known-fix scope",
+ "exeSha256": "1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266",
+ "remainingLimits": [
+ "user capture acceptance",
+ "physical display/photon latency",
+ "long stability",
+ "SR4K+4X not proven 60 source fps"
+ ]
+ },
+ "uiRedesign": {
+ "status": "design_approved_implementation_not_started",
+ "plan": "docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md",
+ "currentDeliverable": "execution_document_only",
+ "defaultMode": "daily",
+ "professionalScope": [
+ "fine settings",
+ "presets management",
+ "same-frame comparison",
+ "performance diagnostics",
+ "image and video export"
+ ],
+ "invariants": [
+ "same preview source and video host on mode switch",
+ "no implicit settings change",
+ "existing app unchanged in documentation turn"
+ ],
+ "nextAction": "On implementation request, start UI0 inventory then UI1 shared state and stable video host",
+ "testLimitScope": "per_invocation",
+ "testLimitSeconds": 300
+ }
}
diff --git a/scripts/acceptance/repair-v2.ps1 b/scripts/acceptance/repair-v2.ps1
new file mode 100644
index 00000000..dbc0bf98
--- /dev/null
+++ b/scripts/acceptance/repair-v2.ps1
@@ -0,0 +1,134 @@
+[CmdletBinding()]
+param([Parameter(Mandatory=$true)][string]$Root,
+ [ValidateRange(1,300)][double]$MaxRuntimeSeconds=300,
+ [ValidateSet('contracts','shaders','sr4k','mfg3','mfg4','fg2','fg2nr','player2','player3','player4','export4','exportaudio','settings','presets','flowP','flowQ','ui','parameters','rollback','rollbackflow','uicases','native4k','realtime4k','exporthevc','exportmkv','exportvfr','cancel','all')][string]$Case='all')
+Set-StrictMode -Version Latest
+$ErrorActionPreference='Stop'
+$Root=(Resolve-Path -LiteralPath $Root).Path
+# User correction 2026-09-08: limit applies to each invocation, not lifetime.
+$invocationTimer=[Diagnostics.Stopwatch]::StartNew()
+if($Case -eq 'all'){
+ $combined=[guid]::NewGuid().ToString('N');$summaryDir=Join-Path $Root ('logs/repair-v2/joint-'+$combined);New-Item -ItemType Directory -Force -Path $summaryDir|Out-Null
+ $results=[Collections.Generic.List[object]]::new()
+ foreach($caseName in @('contracts','presets','shaders','parameters','fg2nr','sr4k','mfg3','mfg4','player3','settings','uicases','rollback','rollbackflow','exportaudio','exporthevc','exportmkv','exportvfr','cancel')){
+ $ledger=Join-Path $Root 'logs/repair-v2/runtime-budget.json'
+ $remainingInvocation=$MaxRuntimeSeconds-$invocationTimer.Elapsed.TotalSeconds
+ if($remainingInvocation -lt 1){break}
+ & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath -Root $Root -MaxRuntimeSeconds $remainingInvocation -Case $caseName
+ $exitCode=$LASTEXITCODE;$entry=Get-Content $ledger -Raw|ConvertFrom-Json
+ $results.Add([ordered]@{case=$caseName;exitCode=$exitCode;runId=$entry.lastRunId})
+ if($exitCode -ne 0){break}
+ }
+ $passed=$results.Count -eq 18 -and @($results|Where-Object exitCode -ne 0).Count -eq 0
+ [ordered]@{status='needs_review';functionalChecksPassed=$passed;cases=$results;runtimeLedger=(Get-Content $ledger -Raw|ConvertFrom-Json);limits=@('capture reserved for user','physical scanout/photon latency unmeasured','short test only','skin and UI correction effect unproven on synthetic fixture')}|ConvertTo-Json -Depth 9|Set-Content (Join-Path $summaryDir 'result.json')
+ Write-Host "Joint evidence=$summaryDir functionalChecksPassed=$passed"
+ if($passed){exit 0}else{exit 1}
+}
+$base=Join-Path $Root 'logs/repair-v2'
+New-Item -ItemType Directory -Force -Path $base | Out-Null
+$ledgerLock=[IO.File]::Open((Join-Path $base 'runtime-budget.lock'),[IO.FileMode]::OpenOrCreate,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
+$ledgerPath=Join-Path $base 'runtime-budget.json'
+$spent=0.0
+if(Test-Path -LiteralPath $ledgerPath){$spent=[double](Get-Content -LiteralPath $ledgerPath -Raw|ConvertFrom-Json).spentSeconds}
+$runId=[guid]::NewGuid().ToString('N')
+$runDir=Join-Path $base $runId
+New-Item -ItemType Directory -Path $runDir | Out-Null
+$items=[Collections.Generic.List[object]]::new()
+function Run-Check([string]$name,[string]$exe,[string]$arguments){
+ $remaining=$MaxRuntimeSeconds-$invocationTimer.Elapsed.TotalSeconds
+ if($remaining -le 0){throw 'This test invocation reached its runtime limit'}
+ $stdout=Join-Path $runDir ($name+'.stdout.log');$stderr=Join-Path $runDir ($name+'.stderr.log')
+ $before=$script:spent
+ # Keep cumulative history for reporting; it is not a stop threshold.
+ # Reserve before launch so an interrupted process remains visible.
+ [ordered]@{spentSeconds=$before+$remaining;perInvocationLimitSeconds=$MaxRuntimeSeconds;budgetScope='per-invocation';activeRun=$runId;reservedSeconds=$remaining}|ConvertTo-Json|Set-Content -LiteralPath $ledgerPath
+ $timer=[Diagnostics.Stopwatch]::StartNew();$p=$null;$code=125
+ $processArgs=@{FilePath=$exe;WorkingDirectory=$Root;WindowStyle=$(if($Case -eq 'ui'){'Normal'}else{'Hidden'});PassThru=$true;RedirectStandardOutput=$stdout;RedirectStandardError=$stderr}
+ if($arguments){$processArgs.ArgumentList=$arguments}
+ try {
+ $p=Start-Process @processArgs
+ $processHandle=$p.Handle # Keep native handle until ExitCode is read.
+ $timedOut=-not $p.WaitForExit([int][Math]::Floor([Math]::Max(1,$remaining*1000-$timer.Elapsed.TotalMilliseconds)))
+ if($timedOut){$code=124}else{$code=$p.ExitCode}
+ if($null -eq $code){$code=125}
+ } finally {
+ if($null -ne $p -and -not $p.HasExited){ & "$env:SystemRoot/System32/taskkill.exe" /PID $p.Id /T /F | Out-Null; $p.WaitForExit() }
+ $timer.Stop();$script:spent=$before+$timer.Elapsed.TotalSeconds
+ [ordered]@{spentSeconds=$script:spent;perInvocationLimitSeconds=$MaxRuntimeSeconds;budgetScope='per-invocation';lastRunId=$runId}|ConvertTo-Json|Set-Content -LiteralPath $ledgerPath
+ }
+ $items.Add([ordered]@{case=$name;command=$exe+' '+$arguments;exitCode=$code;seconds=$timer.Elapsed.TotalSeconds;stdout=$stdout;stderr=$stderr;exeSha256=(Get-FileHash -LiteralPath $exe).Hash})
+}
+try {
+ if($Case -in @('all','parameters')){Run-Check 'parameters' (Join-Path $Root 'out/build/x64-release/veyra_repair_parameter_tests.exe') ''}
+ if($Case -in @('all','presets')){Run-Check 'presets' (Join-Path $Root 'out/build/x64-release/veyra_repair_preset_tests.exe') ('"'+(Join-Path $runDir 'presets.v1')+'"')}
+ if($Case -in @('all','contracts')){Run-Check 'contracts' (Join-Path $Root 'out/build/x64-release/veyra_repair_contract_tests.exe') ''}
+ if($Case -in @('all','shaders')){Run-Check 'shaders' (Join-Path $Root 'out/build/x64-release/veyra_repair_shader_tests.exe') ''}
+ if($Case -in @('flowP','flowQ')){Run-Check $Case (Join-Path $Root 'out/build/x64-release/veyra_repair_fg_tests.exe') $Case}
+ if($Case -in @('all','fg2')){Run-Check 'fg2-product-content' (Join-Path $Root 'out/build/x64-release/veyra_repair_fg_tests.exe') ''}
+ if($Case -in @('all','fg2nr')){Run-Check 'fg2-nr-product-content' (Join-Path $Root 'out/build/x64-release/veyra_repair_fg_tests.exe') 'nr'}
+ if($Case -in @('all','sr4k')){Run-Check 'sr4k-product-content' (Join-Path $Root 'out/build/x64-release/veyra_repair_fg_tests.exe') 'sr'}
+ if($Case -in @('all','mfg3')){Run-Check 'mfg3-product-content' (Join-Path $Root 'out/build/x64-release/veyra_repair_fg_tests.exe') 'mfg3'}
+ if($Case -in @('all','mfg4')){Run-Check 'mfg4-product-content' (Join-Path $Root 'out/build/x64-release/veyra_repair_fg_tests.exe') 'mfg4'}
+ if($Case -in @('all','player2','player3','player4','export4','exportaudio','settings','ui','rollback','rollbackflow','uicases','native4k','realtime4k','exporthevc','exportmkv','exportvfr','cancel')){
+ $clip=Join-Path $Root 'loop/local/fixed_clips/corpus/translation_1080p60.mp4'
+ if((Get-FileHash -LiteralPath $clip).Hash -ne '62BA4375DA00C9B14ECE97485AE2C06223401AE873EF0CAD8520B736A5D4D236'){throw 'Synthetic clip identity mismatch'}
+ $oldLog=$env:VEYRA_LOG_FILE;$oldFault=$env:VEYRA_TEST_REJECT_NR_STYLE2;$oldFlowFault=$env:VEYRA_TEST_REJECT_NR_DISABLE
+ try {
+ $env:VEYRA_LOG_FILE=Join-Path $runDir 'player-app.log'
+ $mult=if($Case -eq 'player3'){3}elseif($Case -in @('player4','export4','exportaudio','settings','ui','rollback','rollbackflow','uicases','native4k','realtime4k','exporthevc','exportmkv','exportvfr','cancel')){4}else{2}
+ if($Case -eq 'exportaudio'){
+ $audioClip=Join-Path $runDir 'synthetic-audio.mp4'
+ Run-Check 'create-synthetic-audio' (Get-Command ffmpeg).Source ('-nostdin -v error -i "'+$clip+'" -f lavfi -i "sine=frequency=440:sample_rate=48000:duration=0.4" -t 0.4 -c:v copy -c:a aac "'+$audioClip+'"')
+ if($items[$items.Count-1].exitCode -ne 0){throw 'Synthetic audio creation failed'}
+ $clip=$audioClip
+ }
+ if($Case -in @('exportmkv','exportvfr')){
+ $quantizedClip=Join-Path $runDir 'quantized.mkv'
+ if($Case -eq 'exportmkv'){$makeArgs='-nostdin -v error -i "'+$clip+'" -t 0.4 -an -c:v copy "'+$quantizedClip+'"'}
+ else {$makeArgs='-nostdin -v error -i "'+$clip+'" -an -vf "setpts=PTS+gte(N\,6)/(30*TB)" -frames:v 24 -fps_mode passthrough -c:v libx264 -preset ultrafast "'+$quantizedClip+'"'}
+ Run-Check 'create-quantized-fixture' (Get-Command ffmpeg).Source $makeArgs
+ if($items[$items.Count-1].exitCode -ne 0){throw 'Quantized fixture creation failed'}
+ $clip=$quantizedClip
+ }
+ if($Case -in @('native4k','realtime4k')){
+ $clip=Join-Path $Root 'loop/local/fixed_clips/corpus/translation_4k60.mp4'
+ if((Get-FileHash $clip).Hash -ne '0470A34BA62FF994DC6806FF8E92DA1FE38E388EF527692C4591D4E5AE9AEACA'){throw '4K synthetic identity mismatch'}
+ }
+ $args='"'+$clip+'" --nr --no-sr --fg-multiplier '+$mult
+ if($Case -eq 'native4k'){$args+=' --native --no-fg'}
+ if($Case -eq 'realtime4k'){$args+=' --realtime'}
+ if($Case -eq 'rollback'){$env:VEYRA_TEST_REJECT_NR_STYLE2='1';$args+=' --smoke-rollback'}
+ if($Case -eq 'rollbackflow'){$env:VEYRA_TEST_REJECT_NR_DISABLE='1';$args+=' --no-fg --smoke-rollback-flow'}
+ if($Case -eq 'uicases'){$args+=' --smoke-ui'}
+ if($Case -eq 'exporthevc'){$args+=' --hevc'}
+ if($Case -eq 'cancel'){$args+=' --cancel-after-ms 1500'}
+ if($Case -in @('export4','exportaudio','exporthevc','exportmkv','exportvfr','cancel')){$args+=' --no-nr --max-frames 24 --export-out "'+(Join-Path $runDir 'export4.mp4')+'"'}else{$args+= $(if($Case -eq 'ui'){' --smoke-seconds 35'}elseif($Case -eq 'settings'){' --smoke-seconds 8 --smoke-settings'}elseif($Case -in @('rollback','rollbackflow','uicases')){' --smoke-seconds 8'}else{' --smoke-seconds 6 --smoke-controls'})}
+ Run-Check $Case (Join-Path $Root 'out/build/x64-release/veyra.exe') $args
+ if($Case -in @('export4','exportaudio','exporthevc','exportmkv') -and $items[$items.Count-1].exitCode -eq 0){
+ Run-Check 'export-probe' (Get-Command ffprobe).Source ('-v error -show_streams -show_packets -of json "'+(Join-Path $runDir 'export4.mp4')+'"')
+ $probe=Get-Content (Join-Path $runDir 'export-probe.stdout.log') -Raw|ConvertFrom-Json
+ $v=@($probe.streams|Where-Object codec_type -eq 'video')[0]
+ $packets=@($probe.packets|Where-Object stream_index -eq $v.index)
+ $ok=$packets.Count -eq 96 -and $v.avg_frame_rate -eq '240/1'
+ for($i=0;$i -lt $packets.Count;$i++){if([Math]::Abs([double]$packets[$i].pts_time-$i/240.0) -gt 0.00001){$ok=$false}}
+ if($Case -eq 'exportaudio'){$ok=$ok -and @($probe.streams|Where-Object codec_type -eq 'audio').Count -eq 1}
+ $items.Add([ordered]@{case='CFR-packets-audio';command='validate ffprobe packet PTS and stream count';exitCode=$(if($ok){0}else{1});seconds=0;evidence=(Join-Path $runDir 'export-probe.stdout.log')})
+ }
+ if($Case -eq 'exportvfr'){
+ $ok=$items[$items.Count-1].exitCode -eq 1 -and (Select-String -Path $env:VEYRA_LOG_FILE -Pattern 'CFR rejected source=' -Quiet) -and -not (Test-Path (Join-Path $runDir 'export4.mp4'))
+ $items.Add([ordered]@{case='VFR-rejected';command='require export exit1, explicit CFR rejection and no final output';exitCode=$(if($ok){0}else{1});seconds=0})
+ }
+ }
+ finally {$env:VEYRA_LOG_FILE=$oldLog;$env:VEYRA_TEST_REJECT_NR_STYLE2=$oldFault;$env:VEYRA_TEST_REJECT_NR_DISABLE=$oldFlowFault}
+ }
+} finally {
+ $failed=@($items|Where-Object {if($_.case -eq 'cancel'){$_.exitCode -ne 3}elseif($_.case -eq 'exportvfr'){$_.exitCode -ne 1}else{$_.exitCode -ne 0}}).Count
+ [ordered]@{runId=$runId;status='needs_review';scope=$Case;checks=$items;failedChecks=$failed;runtimeSpentSeconds=$spent;perInvocationLimitSeconds=$MaxRuntimeSeconds;budgetScope='per-invocation';unexecuted=@('capture hardware acceptance','physical scanout/photon latency','multi-monitor physical DPI traversal','long-run stability');capture='reserved for user';displayScan='unmeasured';photonLatency='unmeasured'}|ConvertTo-Json -Depth 8|Set-Content -LiteralPath (Join-Path $runDir 'result.json')
+ Write-Host "repair-v2 run=$runId spent=$spent evidence=$runDir"
+ $ledgerLock.Dispose()
+}
+if($failed){exit 1}
+# Individual development checks do not certify the unexecuted repair contract.
+if($Case -eq 'all'){exit 2}
+exit 0
+
diff --git a/scripts/gates/delivery.ps1 b/scripts/gates/delivery.ps1
index 5cec87b7..129e6fe4 100644
--- a/scripts/gates/delivery.ps1
+++ b/scripts/gates/delivery.ps1
@@ -1,5 +1,5 @@
[CmdletBinding()]
-param([Parameter(Mandatory=$true)][string]$Root)
+param([Parameter(Mandatory=$true)][string]$Root,[switch]$VisiblePlayer)
# User-authorized local software acceptance, <=300s for this entire suite.
# Native-4K realtime60 is NOT asserted: user selected an explicit 1080 working realtime profile.
# Real capture acceptance and proprietary distribution are separate, never synthetic PASS.
@@ -17,7 +17,9 @@ function Run([string]$Name,[string]$Exe,[string[]]$Argv,[int]$Limit=30,[int]$Exp
$remaining=290-[int]$timer.Elapsed.TotalSeconds
if($remaining -lt 1){throw 'Combined suite budget exhausted'}
$timeout=[Math]::Min($Limit,$remaining)
- $p=Start-Process -FilePath $Exe -ArgumentList @($Argv|ForEach-Object{'"'+$_.Replace('"','\"')+'"'}) -PassThru -WindowStyle Hidden -RedirectStandardOutput "$dir/$Name.stdout.log" -RedirectStandardError "$dir/$Name.stderr.log"
+ $windowStyle='Hidden'
+ if($VisiblePlayer -and $Argv -contains '--smoke-seconds'){$windowStyle='Normal'}
+ $p=Start-Process -FilePath $Exe -ArgumentList @($Argv|ForEach-Object{'"'+$_.Replace('"','\"')+'"'}) -PassThru -WindowStyle $windowStyle -RedirectStandardOutput "$dir/$Name.stdout.log" -RedirectStandardError "$dir/$Name.stderr.log"
$processHandle=$p.Handle
if(-not $p.WaitForExit($timeout*1000)){Stop-Process -Id $p.Id -Force;throw "$Name timeout"}
$exitCode=$p.ExitCode;Check "$Name-exit" ($null -ne $exitCode -and $exitCode -eq $ExpectedExit) "exit=$exitCode expected=$ExpectedExit"
diff --git a/shaders/FlowAdapt.hlsl b/shaders/FlowAdapt.hlsl
new file mode 100644
index 00000000..cccf7c3b
--- /dev/null
+++ b/shaders/FlowAdapt.hlsl
@@ -0,0 +1,8 @@
+Texture2D<float2> inputFlow:register(t0);
+RWTexture2D<float2> outputFlow:register(u0);
+cbuffer Dims:register(b0){uint sourceW;uint sourceH;uint outW;uint outH;float4 unused;}
+[numthreads(16,16,1)] void main(uint3 id:SV_DispatchThreadID){
+ if(id.x>=outW||id.y>=outH)return;
+ uint2 at=min(uint2((float2(id.xy)+0.5)*float2(sourceW,sourceH)/float2(outW,outH)),uint2(sourceW-1,sourceH-1));
+ outputFlow[id.xy]=inputFlow[at]*float2(outW,outH)/float2(sourceW,sourceH);
+}
diff --git a/shaders/NrDownsample.hlsl b/shaders/NrDownsample.hlsl
new file mode 100644
index 00000000..bd972982
--- /dev/null
+++ b/shaders/NrDownsample.hlsl
@@ -0,0 +1,15 @@
+Texture2D<float4> baseTex:register(t0);
+RWTexture2D<float4> nrInput:register(u0);
+cbuffer Dims:register(b0){uint sourceW;uint sourceH;uint outW;uint outH;float4 unused;}
+// Exact area box filter for downsampling, including fractional boundary pixels.
+[numthreads(16,16,1)] void main(uint3 id:SV_DispatchThreadID){
+ if(id.x>=outW||id.y>=outH)return;
+ float2 low=float2(id.xy)*float2(sourceW,sourceH)/float2(outW,outH);
+ float2 high=float2(id.xy+1)*float2(sourceW,sourceH)/float2(outW,outH);
+ float4 sum=0;float weights=0;
+ for(uint y=(uint)floor(low.y);y<(uint)ceil(high.y);++y)for(uint x=(uint)floor(low.x);x<(uint)ceil(high.x);++x){
+ float weight=max(0,min(high.x,x+1.0)-max(low.x,(float)x))*max(0,min(high.y,y+1.0)-max(low.y,(float)y));
+ sum+=baseTex[uint2(min(x,sourceW-1),min(y,sourceH-1))]*weight;weights+=weight;
+ }
+ nrInput[id.xy]=sum/max(weights,1e-6);
+}
diff --git a/shaders/NrResidualComposite.hlsl b/shaders/NrResidualComposite.hlsl
new file mode 100644
index 00000000..8f4a3d65
--- /dev/null
+++ b/shaders/NrResidualComposite.hlsl
@@ -0,0 +1,26 @@
+Texture2D<float4> baseTex:register(t0);
+Texture2D<float4> nrInput:register(t1);
+Texture2D<float4> nrFinal:register(t2);
+RWTexture2D<float4> outputTex:register(u0);
+cbuffer Params:register(b0){float total;float darken;float brighten;float color;float luminance;float3 unused;}
+// Bilateral resampling of the change uses the preserved high-resolution base
+// as the edge guide. It never interpolates the high-resolution base itself.
+[numthreads(16,16,1)] void main(uint3 id:SV_DispatchThreadID){
+ uint w,h,nw,nh;baseTex.GetDimensions(w,h);nrInput.GetDimensions(nw,nh);
+ if(id.x>=w||id.y>=h)return;
+ float4 base=baseTex[id.xy];
+ if(total==0){outputTex[id.xy]=base;return;}
+ float2 pos=(float2(id.xy)+0.5)*float2(nw,nh)/float2(w,h)-0.5;
+ int2 origin=(int2)floor(pos);float2 f=frac(pos);float3 delta=0;float weights=0;
+ for(int y=0;y<2;++y)for(int x=0;x<2;++x){
+ int2 q=clamp(origin+int2(x,y),int2(0,0),int2(nw-1,nh-1));
+ float3 low=nrInput[q].rgb;
+ float weight=(x?f.x:1-f.x)*(y?f.y:1-f.y);
+ if(w!=nw||h!=nh)weight/=1+16*dot(abs(base.rgb-low),float3(0.2126,0.7152,0.0722));
+ delta+=(nrFinal[q].rgb-low)*weight;weights+=weight;
+ }
+ delta/=max(weights,1e-6);
+ if(darken!=1||brighten!=1)delta=min(delta,0)*darken+max(delta,0)*brighten;
+ if(color!=1||luminance!=1){float dy=dot(delta,float3(0.2126,0.7152,0.0722));delta=dy*luminance+(delta-dy)*color;}
+ outputTex[id.xy]=float4(max(0,base.rgb+total*delta),base.a);
+}
diff --git a/shaders/PresentBlit.hlsl b/shaders/PresentBlit.hlsl
index f8825699..0223405c 100644
--- a/shaders/PresentBlit.hlsl
+++ b/shaders/PresentBlit.hlsl
@@ -32,5 +32,7 @@ float4 psMain(VSOut input) : SV_Target
{
(void)srcDims;
(void)dstDims;
- return sourceTex.SampleLevel(linearClamp, input.uv, 0);
+ float4 color=sourceTex.SampleLevel(linearClamp,input.uv,0);
+ if(srcDims.z>0.5){float3 c=max(color.rgb,0);color.rgb=lerp(1.055*pow(c,1.0/2.4)-0.055,c*12.92,step(c,0.0031308));}
+ return color;
}
diff --git a/src/base/Log.cpp b/src/base/Log.cpp
index e362b036..13b06df4 100644
--- a/src/base/Log.cpp
+++ b/src/base/Log.cpp
@@ -1,14 +1,18 @@
#include "veyra/Log.h"
+#include "veyra/diagnostics/Redaction.h"
+#include <sstream>
#include <windows.h>
#include <chrono>
#include <filesystem>
#include <format>
+#include <share.h>
namespace veyra {
namespace {
+thread_local diagnostics::DiagnosticEvent threadDiagnosticContext;
const char* levelTag(LogLevel level)
{
@@ -62,7 +66,10 @@ bool Logger::openFile(const std::wstring& path)
std::fclose(file_);
file_ = nullptr;
}
- if (_wfopen_s(&file_, path.c_str(), L"wb") != 0 || file_ == nullptr) {
+ // Diagnostics may read a running session without stopping capture. Keep
+ // concurrent writers excluded so another instance cannot truncate this log.
+ file_ = _wfsopen(path.c_str(), L"wb", _SH_DENYWR);
+ if (file_ == nullptr) {
return false;
}
return true;
@@ -90,6 +97,13 @@ void Logger::write(LogLevel level, const char* component, const std::string& mes
timestampUtc(), threadId, levelTag(level), component, message);
std::lock_guard<std::mutex> lock(mutex_);
+ if(level==LogLevel::Warn||level==LogLevel::Error){auto event=threadDiagnosticContext;event.timestamp=timestampUtc();event.severity=levelTag(level);event.component=component;
+ auto extract=[&](const char* pattern)->std::optional<uint64_t>{std::smatch m;if(std::regex_search(message,m,std::regex(pattern,std::regex::icase))){try{return std::stoull(m[1].str(),nullptr,m[1].str().starts_with("0x")?16:10);}catch(...){}}return {};};
+ if(auto c=extract("(?:HRESULT|hr)[=: ]+(0x[0-9a-f]+|[0-9]+)"))event.hresult=c;
+ if(auto c=extract("seh[=: ]+(0x[0-9a-f]+|[0-9]+)"))event.seh=c;
+ if(event.component.find("nvof")!=std::string::npos){if(auto c=extract("(?:status|st)[=: ]+(0x[0-9a-f]+|[0-9]+)"))event.nvof=c;}
+ if(event.component=="ngx"||message.find("evaluate")!=std::string::npos){if(auto c=extract("(?:result[=: ]+|failed +)(0x[0-9a-f]+|[0-9]+)"))event.ngx=c;}
+ event.stage=event.stage.empty()?"runtime":event.stage;event.message=message;event.fingerprint=event.component+"|"+event.stage+"|"+diagnostics::redact(message);latestProblem_=event.component+": "+event.message;diagnostics_.add(std::move(event));}
if (consoleEnabled_) {
std::fprintf(stdout, "%s\n", line.c_str());
std::fflush(stdout);
@@ -125,6 +139,15 @@ void error(const char* component, const std::string& message)
} // namespace log
+void Logger::diagnosticContext(diagnostics::DiagnosticEvent event){threadDiagnosticContext=std::move(event);}
+std::string Logger::latestProblem(){std::lock_guard lock(mutex_);return diagnostics::redact(latestProblem_);}
+std::string Logger::diagnosticReport(){std::lock_guard lock(mutex_);std::ostringstream o;o<<"Veyra 本地诊断(复制前脱敏预览;不会上传)\n";
+ for(size_t i=0;i<diagnostics_.size();++i){const auto& e=diagnostics_.events()[i];const auto& r=e.resolution;
+ auto code=[](std::optional<uint64_t> v){return v?std::format("0x{:X}",*v):std::string("未提供");};
+ o<<"\n时间="<<e.timestamp<<" 严重级别="<<e.severity<<"\n组件="<<e.component<<" 阶段="<<e.stage<<" 次数="<<e.occurrenceCount<<"\n"<<e.message<<"\nHRESULT="<<code(e.hresult)<<" NGX="<<code(e.ngx)<<" NVOF="<<code(e.nvof)<<" SEH="<<code(e.seh)<<"\n";
+ o<<"source="<<r.source.width<<'x'<<r.source.height<<" base="<<r.base.width<<'x'<<r.base.height<<" NR="<<r.nr.width<<'x'<<r.nr.height<<" flow="<<r.flow.width<<'x'<<r.flow.height<<" FG="<<r.fg.width<<'x'<<r.fg.height<<" output="<<r.output.width<<'x'<<r.output.height<<"\nepoch="<<e.identity.epoch<<" frame="<<e.identity.sourceFrameId<<" batch="<<e.batch<<" subframe="<<e.subframe<<" revision="<<e.identity.settingsRevision<<"\nruntime="<<e.runtimeHash<<" flow="<<e.flowApplied<<" fallback="<<e.fallbackReason<<"\n";
+ }return diagnostics::redact(o.str());
+}
void Logger::flush()
{
std::lock_guard<std::mutex> lock(mutex_);
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 77d2667e..fae6e1c2 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1,6 +1,9 @@
#include "veyra/engine/EngineController.h"
#include "veyra/engine/VideoPresenter.h"
#include "veyra/engine/VideoExportJob.h"
+#include "veyra/engine/LivePresentationTiming.h"
+#include "veyra/engine/PresentationScheduler.h"
+#include "veyra/engine/DeadlineWait.h"
#include "veyra/source/MediaFileSource.h"
#include "veyra/source/CaptureCardSource.h"
#include "veyra/pipeline/EnhanceGraph.h"
@@ -20,86 +23,197 @@ extern "C" {
}
namespace veyra::engine {
using Clock=std::chrono::steady_clock;
-void EngineController::open(HWND video,const std::wstring& path,PlayerOptions opts){stop();{std::lock_guard lock(mutex_);snapshot_={};savePath_.clear();}stop_=false;paused_=false;seekSeconds_=-1;worker_=std::thread(&EngineController::run,this,video,path,opts);}
-void EngineController::stop(){stop_=true;if(worker_.joinable())worker_.join();}
+namespace {
+double elapsedMs(Clock::time_point from){return std::chrono::duration<double,std::milli>(Clock::now()-from).count();}
+struct TimingWindow {
+ std::deque<double> values;
+ void add(double v){values.push_back(v);if(values.size()>1200)values.pop_front();}
+ double p95()const{if(values.empty())return 0;std::vector<double> sorted(values.begin(),values.end());std::sort(sorted.begin(),sorted.end());return sorted[size_t((sorted.size()-1)*.95)];}
+};
+}
+EngineController::EngineController(){worker_=std::thread(&EngineController::dispatch,this);}
+EngineController::~EngineController(){ {std::lock_guard lock(mutex_);shutdown_=true;pending_={};stop_=true;}wake_.notify_one();if(worker_.joinable())worker_.join(); }
+void EngineController::dispatch(){
+ for(;;){std::function<void()> task;{std::unique_lock lock(mutex_);wake_.wait(lock,[&]{return shutdown_||bool(pending_);});if(shutdown_)break;task=std::move(pending_);pending_={};busy_=true;stop_=false;}
+ try{task();}catch(const std::exception&){status(L"任务异常,已停止;请查看诊断",true);}
+ {std::lock_guard lock(mutex_);busy_=false;snapshot_.running=false;}
+ }
+}
+void EngineController::post(std::function<void()> task){ {std::lock_guard lock(mutex_);stop_=true;pending_=std::move(task);}wake_.notify_one(); }
+bool EngineController::idle()const{std::lock_guard lock(mutex_);return !busy_&&!pending_;}
+void EngineController::open(HWND video,const std::wstring& path,PlayerOptions opts){
+ {std::lock_guard lock(mutex_);snapshot_={};savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}
+ post([this,video,path,opts]{paused_=false;seekSeconds_=-1;run(video,path,opts);});
+}
+void EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};}
+bool EngineController::requestSettings(EnhancementSettings s){
+ if(!s.validate().empty()){veyra::log::warn("settings","invalid whole settings transaction rejected");status(L"整套设置无效,未应用任何字段",false);return false;}
+ std::lock_guard lock(mutex_);s.revision=++nextRevision_;desired_=s;snapshot_.desired=s;snapshot_.applying=true;return true;
+}
void EngineController::saveFrame(const std::wstring& path){std::lock_guard lock(mutex_);savePath_=path;}
-void EngineController::startExport(const std::wstring& input,const std::wstring& output,PlayerOptions opts,bool hevc){stop();stop_=false;worker_=std::thread([this,input,output,opts,hevc]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);bool ok=exportVideo(input,output,opts,hevc,stop_,[this](double p,const std::wstring& s){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.position=p;snapshot_.duration=1;snapshot_.running=true;});{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.failed=!ok&&!stop_;}CoUninitialize();});}
+void EngineController::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_);return snapshot_;}
void EngineController::status(const std::wstring& s,bool failed){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.failed=failed;}
void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
- status(L"Initializing GPU and local runtime...");
+ status(L"正在初始化GPU与本地运行时…");
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;
sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;
- pipeline::EnhanceGraph graph(ctx,ring);AVFrame* imageFrame=nullptr;
+ pipeline::EnhanceGraph graph(ctx,ring);AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;
source::CaptureCardSource captureSource;const bool isCapture=path.rfind(L"capture:",0)==0;
source::IFrameSource* activeSource=isCapture?static_cast<source::IFrameSource*>(&captureSource):&source;
bool audioStarted=false;bool failed=false;
try {
do {
Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;
- if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st)){status(L"D3D12 initialization failed; see logs",true);break;}
+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st)){status(L"D3D12初始化失败,请查看诊断",true);break;}
auto ext=std::filesystem::path(path).extension().wstring();for(auto& c:ext)c=towlower(c);
const bool isImage=ext==L".png"||ext==L".jpg"||ext==L".jpeg";
sink::RgbaImage image;
uint32_t width=0,height=0;double duration=0;
if(isImage){
- if(!sink::loadImage(path,image)){status(L"Cannot decode PNG/JPEG",true);break;}
+ if(!sink::loadImage(path,image)){status(L"无法解码PNG/JPEG",true);break;}
imageFrame=av_frame_alloc();imageFrame->format=AV_PIX_FMT_RGBA;imageFrame->width=image.width;imageFrame->height=image.height;imageFrame->pts=0;imageFrame->color_range=AVCOL_RANGE_JPEG;
- if(av_frame_get_buffer(imageFrame,32)<0){status(L"Image allocation failed",true);break;}
+ if(av_frame_get_buffer(imageFrame,32)<0){status(L"图片资源分配失败",true);break;}
for(unsigned y=0;y<image.height;++y)memcpy(imageFrame->data[0]+size_t(y)*imageFrame->linesize[0],image.pixels.data()+size_t(y)*image.width*4,size_t(image.width)*4);
width=image.width;height=image.height;options.fg=false;
}else{
source::SourceOpenDesc od;od.path=path;od.preferHardwareDecode=false;
- if(!activeSource->open(od)){status(L"Cannot open video; see logs",true);break;}
+ if(!(isCapture?captureSource.configure(od):activeSource->open(od))){status(L"无法打开视频,请查看诊断",true);break;}
width=activeSource->info().width;height=activeSource->info().height;duration=activeSource->info().duration.toDouble();
}
- if(width>3840||height>2160||width%2||height%2){status(L"V1 supports even-sized SDR inputs up to 3840 x 2160",true);break;}
+ if(width>3840||height>2160||width%2||height%2){status(L"仅支持偶数尺寸SDR输入,最大3840×2160",true);break;}
pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;
- gd.workWidth=options.sr?3840:width;gd.workHeight=options.sr?2160:height;
- if(!isImage&&options.realtime&&!options.sr&&width>1920){gd.workWidth=1920;gd.workHeight=((uint64_t(height)*1920/width)+1)&~1u;}
- gd.enableSr=options.sr&&(width!=3840||height!=2160);gd.enableNr=options.nr;gd.enableFg=options.fg;gd.enableNvofStandalone=options.nr;
+ const auto resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,1);
+ gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;
+ gd.enableSr=options.sr&&(width!=3840||height!=2160);gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.enableNvofStandalone=options.nr;
+ gd.noFeatures=false;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;
gd.runtimeAbsPath=std::filesystem::path(VEYRA_PROJECT_ROOT).wstring()+L"\\runtime_local\\nvidia";
- if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"Enhancement initialization failed; local runtime required",true);break;}
- {std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.running=true;snapshot_.image=isImage;}
- status(isImage?L"Image enhanced — Save image to export":std::format(L"{} | Input {}x{} / processing {}x{} | Depth unavailable",isCapture?L"Capture (hardware test pending)":L"Playing",width,height,gd.workWidth,gd.workHeight));
+ if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"增强初始化失败,请核对本地运行时",true);break;}
+ if(isCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}
+ {std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.running=true;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,width,height,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时NR变化回填":L"原生NR(性能成本较高)"));
pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false;std::deque<double> latenessSamples;
- auto anchor=Clock::now(),statsStart=anchor;double anchorMs=0;uint64_t frames=0;bool wasPaused=false;double discardBefore=0;
+ TimingWindow captureAges,scheduleWaits,processTimes,presentTimes;auto nextTimingLog=Clock::now()+std::chrono::seconds(1);
+ auto anchor=Clock::now(),statsStart=anchor;double anchorMs=0;uint64_t frames=0,sourceFrames=0;bool wasPaused=false;double discardBefore=0;
+ PresentationScheduler liveTimeline;uint64_t submitted=0,expired=0;std::deque<int64_t> submissionTimes;
+ DeadlineWait deadlineWait;
+ auto host100ns=[](){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;};
while(!stop_){
+ EnhancementSettings requested;{std::lock_guard lock(mutex_);requested=desired_;}
+ const auto previous=options.snapshot();const auto previousDesc=gd;bool transaction=false;
+ if(requested.revision!=previous.revision){
+ auto next=PlayerOptions::from(requested);auto nextDesc=gd;
+ const auto plan=pipeline::ResolutionPlan::make({width,height},next.sr,requested.nrPolicy,isImage,requested.revision);
+ nextDesc.workWidth=plan.base.width;nextDesc.workHeight=plan.base.height;nextDesc.nrWidth=plan.nr.width;nextDesc.nrHeight=plan.nr.height;
+ nextDesc.enableSr=next.sr&&(width!=3840||height!=2160);nextDesc.enableNr=next.nr;nextDesc.enableFg=next.fg;nextDesc.fgMultiplier=next.fgMultiplier;nextDesc.enableNvofStandalone=next.nr;
+ nextDesc.model=requested.model;nextDesc.residual=requested.residual;nextDesc.settingsRevision=requested.revision;nextDesc.flowQuality=requested.flow;nextDesc.contentRate=requested.content;
+ const bool rebuild=gd.flowQuality!=nextDesc.flowQuality||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight;
+ 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){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;}
+ else {std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.applying=false;snapshot_.status=L"设置应用失败,已恢复上一套参数";}
+ }
std::wstring save;{std::lock_guard lock(mutex_);save.swap(savePath_);}
if(!save.empty()&&hasOutput){sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();
- if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"Save failed (destination may already exist)",true);else status(L"Saved image: "+save);}
+ if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在)",true);else status(L"图片已保存:"+save);}
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"Seek failed",true);break;}
+ 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);
}
- if((paused_&&seek<0)||(isImage&&hasOutput)){
+ if(!transaction&&((paused_&&seek<0)||(isImage&&hasOutput))){
if(audioStarted)audioPipe.setPaused(true);wasPaused=true;
- if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false)){status(L"Present failed",true);break;}
+ if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity)){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;}
+ const auto decodeStart=Clock::now();
pipeline::FramePacket pkt;const AVFrame* frame=imageFrame;
- if(!isImage){auto rs=activeSource->read(pkt,&frame);if(rs==source::SourceReadStatus::Waiting)continue;if(rs==source::SourceReadStatus::Eos){status(L"End of video");paused_=true;continue;}if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){status(L"Video decode/timestamp error",true);break;}}
+ if(transaction&&cachedFrame){frame=cachedFrame;pkt=cachedPacket;}
+ else if(!isImage){auto rs=activeSource->read(pkt,&frame);if(rs==source::SourceReadStatus::Waiting)continue;if(rs==source::SourceReadStatus::Eos){status(L"视频已播放完毕");paused_=true;continue;}if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){status(L"视频解码或时间戳错误",true);break;}}
+ const bool rereadCached=transaction&&frame==cachedFrame;
+ if(isImage)pkt.sequence=1;
+ if(!rereadCached)++sourceFrames;
+ const double decodeMs=elapsedMs(decodeStart);
const double pts=isImage?0:pkt.pts.toDouble()*1000;
if(isCapture&&frames==0){anchor=Clock::now();anchorMs=pts;}
if(pts+0.1<discardBefore)continue;
- if(!graph.process(frame,pts,reset||pipeline::breaksHistory(pkt.flags),out)){status(L"Enhancement failed; see logs",true);break;}reset=false;hasOutput=true;
+ if(frame!=cachedFrame){av_frame_free(&cachedFrame);cachedFrame=av_frame_clone(frame);cachedPacket=pkt;}
+ const auto processStart=Clock::now();
+ const bool injectedReject=transaction&&!options.nr&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_DISABLE",nullptr,0)>0;
+ if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");
+ if(injectedReject||!graph.process(frame,pts,reset||pipeline::breaksHistory(pkt.flags),out,pkt.sequence)){
+ if(transaction){
+ ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);
+ gd=previousDesc;
+ if(graph.initialize(gd)&&presenter.open(ctx,window,graph)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence)){
+ std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.applying=false;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;
+ }else{status(L"参数回滚失败,已停止",true);break;}
+ }else{status(L"增强执行失败;请查看日志",true);break;}
+ }
+ if(transaction){std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_.revision!=options.settings.revision;snapshot_.status=std::format(L"输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,width,height,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时NR变化回填":L"原生NR(性能成本较高)");veyra::log::info("settings",std::format("Applied revision={} sourcePtsMs={} (source kept open)",options.settings.revision,pts));}
+ veyra::log::info("source-identity",std::format("source={} totalRead={} graphProcessed={} cached={} revision={} nvofStandalone={}",pkt.sequence,sourceFrames,frames+1,rereadCached,options.settings.revision,gd.enableNvofStandalone));
+ reset=false;hasOutput=true;
+ const auto processDone=Clock::now();processTimes.add(elapsedMs(processStart));
+ if(isCapture&&!liveTimeline.anchored(out.batch.identity.epoch)){
+ const auto duration100ns=pkt.duration.isUnknown()?200000:std::clamp<int64_t>(pkt.duration.to100ns(),83333,1000000);
+ liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,std::chrono::duration_cast<std::chrono::nanoseconds>(processStart.time_since_epoch()).count()/100,options.fg?duration100ns:0);
+ }
if(!audioStarted&&!isImage&&!isCapture&&frames==0){if(audioPipe.open(path)&&audio.start()){audioPipe.startThread(&audio);audioStarted=true;}anchor=Clock::now();anchorMs=pts;}
auto nowMs=[&](){const double a=audioStarted?audio.mediaTimeMs():-1;return a>=0?a:anchorMs+std::chrono::duration<double,std::milli>(Clock::now()-anchor).count();};
- auto show=[&](double target,bool generated){while(!stop_&&!paused_&&seekSeconds_<0&&nowMs()+0.5<target)std::this_thread::sleep_for(std::chrono::milliseconds(1));return !stop_&&presenter.present(ctx,ring,graph,generated?out.genSlot:out.videoSlot,generated);};
- if(out.hasGenerated&&!show(out.generatedPtsMs,true))break;
- if(!show(pts,false)){status(L"Present failed",!stop_);break;}
- const double lateness=nowMs()-pts;
- if(!paused_){latenessSamples.push_back(std::abs(lateness));if(latenessSamples.size()>1200)latenessSamples.pop_front();}
+ double frameWaitMs=0,framePresentMs=0;
+ const auto readyStart=Clock::now();
+ while(!stop_&&!paused_&&seekSeconds_<0&&!graph.resolveGeneration(out)){
+ if(elapsedMs(readyStart)>2000){status(L"补帧 GPU 就绪超时",true);stop_=true;break;}
+ deadlineWait.slice();
+ }
+ if(stop_)break;
+ if(paused_||seekSeconds_>=0){reset=true;veyra::log::info("submit",std::format("batch={} cancelled before submit (pause/seek)",out.batch.batchId));continue;}
+ const double gpuWaitMs=elapsedMs(readyStart);
+ bool interrupted=false,presentFailed=false;
+ for(uint32_t i=0;i<out.batch.count;++i){
+ auto& item=out.batch.frames[i];const bool generated=item.kind==pipeline::FrameKind::Generated;
+ if(generated&&(item.validity!=pipeline::GenerationValidity::Valid||comparisonMode_!=0))continue;
+ if(isCapture&&generated&&liveTimeline.expired(item.pts100ns,host100ns(),100000)){++expired;continue;}
+ 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();
+ if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity)){presentFailed=true;break;}
+ framePresentMs+=elapsedMs(begin);
+ item.lease->consumerFence=ring.lastSignaledValue();
+ if(presenter.submittedCount()>before){++submitted;const auto time=host100ns();submissionTimes.push_back(time);while(submissionTimes.size()>1&&time-submissionTimes.front()>10000000)submissionTimes.pop_front();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;}
+ scheduleWaits.add(frameWaitMs);presentTimes.add(framePresentMs);
+ const double lateness=isCapture?0:nowMs()-pts;
+ if(!paused_&&!isCapture){latenessSamples.push_back(std::abs(lateness));if(latenessSamples.size()>1200)latenessSamples.pop_front();}
std::vector<double> sorted(latenessSamples.begin(),latenessSamples.end());std::sort(sorted.begin(),sorted.end());
- ++frames;{std::lock_guard lock(mutex_);snapshot_.position=pts/1000;snapshot_.frames=frames;snapshot_.generated=graph.metrics().fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];snapshot_.fps=frames/std::max(0.001,std::chrono::duration<double>(Clock::now()-statsStart).count());}
+ const auto captureStats=isCapture?captureSource.metrics():source::CaptureMetrics{};
+ if(isCapture)captureAges.add(captureStats.frameAgeMs);
+ auto measured=graph.gpuMetrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence());measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=elapsedMs(processStart)-elapsedMs(processDone);measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.submitted=submitted;measured.expired=expired;measured.sourceFrames=sourceFrames;measured.validGenerated=graph.metrics().fgGeneratedFrames;measured.queueWatermark=out.batch.count;
+ ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;if(submissionTimes.size()>1)snapshot_.submissionFps=double(submissionTimes.size()-1)*1e7/(submissionTimes.back()-submissionTimes.front());snapshot_.position=pts/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graph.metrics().fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];snapshot_.fps=sourceFrames/std::max(0.001,std::chrono::duration<double>(Clock::now()-statsStart).count());
+ snapshot_.flowPerf=graph.actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;
+ snapshot_.nrEvaluated=graph.metrics().nrEvaluateCount;snapshot_.nvofExecuted=graph.metrics().nvofExecuteCount;
+ snapshot_.captureReceived=captureStats.received;snapshot_.captureDropped=captureStats.dropped;snapshot_.captureFps=captureStats.callbackFps;snapshot_.captureReadAgeMs=captureStats.readAgeMs;snapshot_.captureAgeMs=captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=captureAges.p95();
+ snapshot_.schedulingWaitP95Ms=scheduleWaits.p95();snapshot_.processCpuP95Ms=processTimes.p95();snapshot_.presentCpuP95Ms=presentTimes.p95();
+ }
+ if(isCapture&&Clock::now()>=nextTimingLog){
+ veyra::log::info("capture-timing",std::format("received={} processed={} dropped={} callbackFps={:.2f} readAgeMs={:.3f} callbackToPresentReturnP95Ms={:.3f} processCpuP95Ms={:.3f} schedulingWaitP95Ms={:.3f} presentCpuP95Ms={:.3f} nr={} nvof={} generated={} (not HDMI-to-display latency)",captureStats.received,frames,captureStats.dropped,captureStats.callbackFps,captureStats.readAgeMs,captureAges.p95(),processTimes.p95(),scheduleWaits.p95(),presentTimes.p95(),graph.metrics().nrEvaluateCount,graph.metrics().nvofExecuteCount,graph.metrics().fgGeneratedFrames));
+ nextTimingLog=Clock::now()+std::chrono::seconds(1);
+ }
}
}while(false);
- }catch(const std::exception& e){veyra::log::error("engine",e.what());status(L"Engine exception; see logs",true);failed=true;}
+ }catch(const std::exception& e){veyra::log::error("engine",e.what());status(L"引擎异常,请查看诊断",true);failed=true;}
(void)failed;
- audioPipe.stopThread();audio.shutdown();ring.drainQueue();presenter.close();graph.shutdown();captureSource.close();source.close();av_frame_free(&imageFrame);ring.shutdown();ctx.shutdown();
+ audioPipe.stopThread();audio.shutdown();ring.drainQueue();presenter.close();graph.shutdown();captureSource.close();source.close();av_frame_free(&cachedFrame);av_frame_free(&imageFrame);ring.shutdown();ctx.shutdown();
{std::lock_guard lock(mutex_);snapshot_.running=false;}
CoUninitialize();
}
diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cpp
new file mode 100644
index 00000000..34eb79d3
--- /dev/null
+++ b/src/engine/PresetStore.cpp
@@ -0,0 +1,52 @@
+#include "veyra/engine/PresetStore.h"
+#include <windows.h>
+#include <fstream>
+#include <sstream>
+#include <iomanip>
+#include <algorithm>
+#include <limits>
+namespace veyra::engine {
+namespace {
+std::string utf8(const std::wstring& s){int n=WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,s.data(),int(s.size()),nullptr,0,nullptr,nullptr);std::string r(n,0);if(n)WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,s.data(),int(s.size()),r.data(),n,nullptr,nullptr);return r;}
+std::wstring wide(const std::string& s){int n=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,s.data(),int(s.size()),nullptr,0);std::wstring r(n,0);if(n)MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,s.data(),int(s.size()),r.data(),n);return r;}
+bool nameOk(const std::wstring& s){return !s.empty()&&s.size()<=48&&s.front()!=L' '&&s.back()!=L' '&&std::none_of(s.begin(),s.end(),[](wchar_t c){return c<32;});}
+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 1\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)<<'\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||!(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;
+ 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));
+ }
+ in>>std::ws;if(!in.eof())return false;
+ return def.empty()||std::any_of(out.begin(),out.end(),[&](auto& a){return a.name==def;});
+}
+bool PresetStore::load(){
+ error_.clear();if(!std::filesystem::exists(path_))return true;if(std::filesystem::file_size(path_)>65536){corrupt_=true;error_=L"预设文件超过64KiB,原文件保留";return false;}std::ifstream f(path_,std::ios::binary);std::string data((std::istreambuf_iterator<char>(f)),{});std::vector<UserPreset> loaded;std::wstring def;
+ if(!f||!parse(data,loaded,def)){corrupt_=true;error_=L"预设文件损坏或版本不支持;原文件已保留,禁止覆盖。当前使用内建设置。";return false;}
+ entries_=std::move(loaded);default_=std::move(def);corrupt_=false;return true;
+}
+bool PresetStore::save(){
+ if(corrupt_){error_=L"损坏原文件受保护,未写入任何设置;请先备份并移走该文件";return false;}
+ const auto data=serialize();std::vector<UserPreset> check;std::wstring def;if(!parse(data,check,def)){error_=L"预设校验失败";return false;}
+ std::error_code ec;std::filesystem::create_directories(path_.parent_path(),ec);if(ec){error_=L"无法创建预设目录";return false;}
+ auto tmp=path_;tmp+=L".tmp-"+std::to_wstring(GetCurrentProcessId())+L"-"+std::to_wstring(GetTickCount64());
+ HANDLE h=CreateFileW(tmp.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,nullptr);if(h==INVALID_HANDLE_VALUE){error_=L"无法创建预设临时文件";return false;}
+ DWORD written=0;bool ok=WriteFile(h,data.data(),DWORD(data.size()),&written,nullptr)&&written==data.size()&&FlushFileBuffers(h);CloseHandle(h);
+ std::ifstream verify(tmp,std::ios::binary);std::string back((std::istreambuf_iterator<char>(verify)),{});verify.close();check.clear();ok=ok&&back==data&&parse(back,check,def);
+ if(ok)ok=MoveFileExW(tmp.c_str(),path_.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)!=FALSE;
+ if(!ok){error_=L"预设原子保存失败,原文件未替换;临时文件保留";return false;}error_.clear();return true;
+}
+bool PresetStore::put(std::wstring name,EnhancementSettings s,bool replace){name=trim(name);if(!nameOk(name)||!s.validate().empty()){error_=L"预设名称或参数无效(名称最多48字)";return false;}auto old=entries_;auto i=std::find_if(entries_.begin(),entries_.end(),[&](auto& p){return p.name==name;});if(i!=entries_.end()){if(!replace){error_=L"预设名称已存在";return false;}i->settings=s;}else{if(entries_.size()>=64){error_=L"最多保存64套预设";return false;}entries_.push_back({name,s});}if(save())return true;entries_=old;return false;}
+bool PresetStore::rename(size_t i,std::wstring name){name=trim(name);if(i>=entries_.size()||!nameOk(name)||std::any_of(entries_.begin(),entries_.end(),[&](auto& p){return p.name==name;})){error_=L"名称无效或重复";return false;}auto old=entries_;auto d=default_;if(default_==entries_[i].name)default_=name;entries_[i].name=name;if(save())return true;entries_=old;default_=d;return false;}
+bool PresetStore::erase(size_t i){if(i>=entries_.size())return false;auto old=entries_;auto d=default_;if(default_==entries_[i].name)default_.clear();entries_.erase(entries_.begin()+i);if(save())return true;entries_=old;default_=d;return false;}
+bool PresetStore::setDefault(size_t i){if(i>=entries_.size())return false;auto old=default_;default_=entries_[i].name;if(save())return true;default_=old;return false;}
+EnhancementSettings PresetStore::defaultSettings()const{for(auto& p:entries_)if(p.name==default_)return p.settings;return {};}
+}
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index eaab2698..0f88a9e5 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -1,4 +1,5 @@
#include "veyra/engine/VideoExportJob.h"
+#include "veyra/engine/CfrTimeline.h"
#include "veyra/source/MediaFileSource.h"
#include "veyra/pipeline/EnhanceGraph.h"
#include "veyra/sink/NvencD3D12Encoder.h"
@@ -6,6 +7,9 @@
#include "veyra/gfx/CommandSlotRing.h"
#include <filesystem>
#include <format>
+#include <thread>
+#include <chrono>
+#include <cmath>
extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
@@ -14,28 +18,38 @@ extern "C" {
namespace veyra::engine {
namespace { std::string utf8(const std::wstring& s){const int n=WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),nullptr,0,nullptr,nullptr);std::string r(n,0);WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),r.data(),n,nullptr,nullptr);return r;} }
bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptions options,bool hevc,std::atomic<bool>& cancel,const std::function<void(double,const std::wstring&)>& progress,unsigned maxFrames){
- if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial")){progress(0,L"Output/partial already exists; choose another name");return false;}
+ if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial")){progress(0,L"目标或partial文件已存在,请使用其他名称");return false;}
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);sink::NvencD3D12Encoder enc;
AVFormatContext *mux=nullptr,*audioInput=nullptr;AVStream* videoStream=nullptr;AVStream* audioStream=nullptr;AVPacket* audioPacket=av_packet_alloc();
int audioIndex=-1;bool audioPending=false,audioEof=false,ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;
const auto partial=output+L".partial";
- do {
+ try { do {
Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;
if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st))break;
source::SourceOpenDesc od;od.path=input;od.preferHardwareDecode=false;if(!source.open(od))break;
const auto info=source.info();if(info.width>3840||info.height>2160||!info.width||!info.height)break;
- const double fps=info.averageFps;if(fps<=0||fps>120)break;const AVRational rate=av_d2q(fps*(options.fg?2:1),1001000);
- pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=options.sr?3840:info.width;gd.workHeight=options.sr?2160:info.height;gd.enableSr=options.sr&&(info.width!=3840||info.height!=2160);gd.enableNr=options.nr;gd.enableFg=options.fg;gd.enableNvofStandalone=options.nr;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();
+ // Bounded metadata scan; decoded pixels are not retained. Rewind the
+ // file source afterwards, preserving all source frames for the export.
+ std::vector<double> samples;bool scanError=false;
+ for(unsigned i=0;i<120&&!cancel;++i){pipeline::FramePacket p;const AVFrame* f=nullptr;const auto rs=source.read(p,&f);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||p.pts.isUnknown()){scanError=true;break;}samples.push_back(p.pts.toDouble());}
+ if(scanError||samples.empty()||cancel)break;
+ const auto [rateNum,rateDen]=CfrTimeline::select(info.nominalRateNum,info.nominalRateDen,info.timestampQuantum,samples);
+ CfrTimeline timeline(rateNum,rateDen,info.timestampQuantum,samples.front());
+ if(!timeline.valid()){progress(0,L"无法确认一致的恒定帧率,已停止导出");veyra::log::error("export-timeline","CFR rejected source=preflight; no timestamp-consistent rate candidate");break;}
+ source.close();if(!source.open(od))break; // reopen from the true beginning, including negative PTS
+ const AVRational rate=av_mul_q({rateNum,rateDen},{int(options.fg?options.fgMultiplier:1),1});
+ veyra::log::info("export-timeline",std::format("CFR declared={}/{} candidate={}/{} timestampQuantum={} sampled={} output={}/{} (timestamp-consistent candidate, quantized short clips may be ambiguous; every PTS validated)",info.nominalRateNum,info.nominalRateDen,rateNum,rateDen,info.timestampQuantum,samples.size(),rate.num,rate.den));
+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=options.sr?3840:info.width;gd.workHeight=options.sr?2160:info.height;gd.enableSr=options.sr&&(info.width!=3840||info.height!=2160);gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();
if(!graph.initialize(gd)||!graph.createViews())break;
if(avformat_alloc_output_context2(&mux,nullptr,"mp4",utf8(partial).c_str())<0||!mux)break;
videoStream=avformat_new_stream(mux,nullptr);if(!videoStream)break;videoStream->time_base={rate.den,rate.num};videoStream->avg_frame_rate=rate;
auto* cp=videoStream->codecpar;cp->codec_type=AVMEDIA_TYPE_VIDEO;cp->codec_id=hevc?AV_CODEC_ID_HEVC:AV_CODEC_ID_H264;cp->width=gd.workWidth;cp->height=gd.workHeight;cp->format=AV_PIX_FMT_YUV420P;cp->color_range=AVCOL_RANGE_MPEG;cp->color_space=AVCOL_SPC_BT709;cp->color_primaries=AVCOL_PRI_BT709;cp->color_trc=AVCOL_TRC_IEC61966_2_1;
auto inputUtf8=utf8(input);
- if(avformat_open_input(&audioInput,inputUtf8.c_str(),nullptr,nullptr)<0||avformat_find_stream_info(audioInput,nullptr)<0){progress(0,L"Cannot inspect source audio; export refused rather than silently losing audio");break;}
+ if(avformat_open_input(&audioInput,inputUtf8.c_str(),nullptr,nullptr)<0||avformat_find_stream_info(audioInput,nullptr)<0){progress(0,L"无法读取源音轨信息,已停止导出");break;}
{
audioIndex=av_find_best_stream(audioInput,AVMEDIA_TYPE_AUDIO,-1,-1,nullptr,0);
if(audioIndex>=0){auto* acp=audioInput->streams[audioIndex]->codecpar;
- if(avformat_query_codec(mux->oformat,acp->codec_id,FF_COMPLIANCE_NORMAL)<=0){progress(0,L"Audio codec cannot be remuxed into MP4; export refused rather than dropping audio");break;}
+ if(avformat_query_codec(mux->oformat,acp->codec_id,FF_COMPLIANCE_NORMAL)<=0){progress(0,L"此音频编码不能封装为MP4,已停止导出");break;}
audioStream=avformat_new_stream(mux,nullptr);if(!audioStream||avcodec_parameters_copy(audioStream->codecpar,acp)<0)break;audioStream->codecpar->codec_tag=0;audioStream->time_base=audioInput->streams[audioIndex]->time_base;
}
av_dict_copy(&mux->metadata,audioInput->metadata,0);
@@ -55,26 +69,46 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(!enc.open(ctx,ring,graph,hevc,rate.num,rate.den,writer))break;
auto headers=enc.headers();cp->extradata=static_cast<uint8_t*>(av_mallocz(headers.size()+AV_INPUT_BUFFER_PADDING_SIZE));if(!cp->extradata)break;memcpy(cp->extradata,headers.data(),headers.size());cp->extradata_size=int(headers.size());
if(avio_open(&mux->pb,utf8(partial).c_str(),AVIO_FLAG_WRITE)<0||avformat_write_header(mux,nullptr)<0)break;headerWritten=true;
- uint64_t sourceCount=0;int64_t outputIndex=0;bool error=false;
- while(!cancel){pipeline::FramePacket packet;const AVFrame* frame=nullptr;auto rs=source.read(packet,&frame);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){error=true;break;}
+ uint64_t sourceCount=0,generatedCount=0,holdCount=0;int64_t outputIndex=0;bool error=false;std::shared_ptr<pipeline::FrameLease> lastReal;
+ while(!cancel){pipeline::FramePacket packet;const AVFrame* frame=nullptr;const auto rs=source.read(packet,&frame);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){error=true;break;}
if(sourceCount==0)videoOriginSeconds=packet.pts.toDouble();
- pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out)){error=true;break;}
- if(out.hasGenerated&&!enc.encode(out.genSlot,true,outputIndex++)){error=true;break;}
- if(options.fg&&sourceCount>0&&!out.hasGenerated){
- veyra::log::info("export","history reset: hold current source for missing interpolation interval (not a generated frame)");
- if(!enc.encode(out.videoSlot,false,outputIndex++)){error=true;break;}
+ const double expectedPts=timeline.expected(sourceCount);
+ if(!timeline.accepts(sourceCount,packet.pts.toDouble())){
+ progress(0,L"此文件时间戳不均匀,当前CFR导出不支持;已保留partial,未改写音画时间轴");
+ veyra::log::error("export-timeline",std::format("CFR rejected source={} pts={} expected={}",sourceCount,packet.pts.toDouble(),expectedPts));error=true;break;
}
- if(!enc.encode(out.videoSlot,false,outputIndex++)){error=true;break;}
- ++sourceCount;progress(info.duration.toDouble()>0?packet.pts.toDouble()/info.duration.toDouble():0,std::format(L"Exporting {} source frames / {} encoded frames (D3D12 NVENC)",sourceCount,outputIndex));
+ pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out,packet.sequence)){error=true;break;}
+ const auto readyStart=std::chrono::steady_clock::now();
+ while(!cancel&&!graph.resolveGeneration(out)){
+ if(std::chrono::steady_clock::now()-readyStart>std::chrono::seconds(2)){error=true;break;}
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ }
+ if(error||cancel)break;
+ if(sourceCount>0&&options.fg){
+ for(uint32_t j=1;j<options.fgMultiplier;++j){
+ pipeline::BatchFrame* item=nullptr;
+ for(uint32_t k=0;k<out.batch.count;++k)if(out.batch.frames[k].subframe==j&&out.batch.frames[k].validity==pipeline::GenerationValidity::Valid)item=&out.batch.frames[k];
+ if(item){if(!enc.encode(item->lease->slot,true,outputIndex++)){error=true;break;}item->lease->consumerFence=ring.lastSignaledValue();++generatedCount;}
+ else {if(!lastReal||!enc.encode(lastReal->slot,false,outputIndex++)){error=true;break;}lastReal->consumerFence=ring.lastSignaledValue();++holdCount;}
+ }
+ }
+ if(error)break;
+ auto& real=out.batch.frames[out.batch.count-1];
+ if(!enc.encode(real.lease->slot,false,outputIndex++)){error=true;break;}
+ real.lease->consumerFence=ring.lastSignaledValue();lastReal=real.lease;
+ ++sourceCount;progress(info.duration.toDouble()>0?packet.pts.toDouble()/info.duration.toDouble():0,std::format(L"正在导出:{}张源帧 / {}张编码帧(D3D12 NVENC)",sourceCount,outputIndex));
if(maxFrames&&sourceCount>=maxFrames)break;
}
if(error||cancel)break;
+ if(options.fg&&lastReal)for(uint32_t j=1;j<options.fgMultiplier;++j){if(!enc.encode(lastReal->slot,false,outputIndex++)){error=true;break;}++holdCount;}
+ if(error)break;
+ veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} (CFR holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,options.fg?options.fgMultiplier:1));
if(!enc.finish()||!writeAudioUntil(audioEndSeconds)||av_write_trailer(mux)<0)break;
ok=written>0;
- }while(false);
+ }while(false); }catch(const std::exception&){progress(0,L"导出异常,已保留partial,请查看诊断");ok=false;}
enc.close();if(mux){if(mux->pb)avio_closep(&mux->pb);avformat_free_context(mux);}if(audioInput)avformat_close_input(&audioInput);av_packet_free(&audioPacket);
ring.drainQueue();graph.shutdown();source.close();ring.shutdown();ctx.shutdown();
if(ok){source::MediaFileSource check;source::SourceOpenDesc od;od.path=partial;od.preferHardwareDecode=false;pipeline::FramePacket pkt;const AVFrame* frame=nullptr;ok=check.open(od)&&check.read(pkt,&frame)==source::SourceReadStatus::Frame;check.close();if(ok)ok=MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;}
- progress(ok?1:0,ok?L"Video exported and decoded back successfully":cancel?L"Export cancelled; partial retained":L"Video export failed; partial retained, see logs");return ok;
+ progress(ok?1:0,ok?L"视频导出完成,解码回读成功":cancel?L"导出已取消,partial文件已保留":L"视频导出失败,partial文件已保留,请查看诊断");return ok;
}
}
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index e2a47a22..bdf4a9ac 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -4,22 +4,29 @@
#include "veyra/gfx/CommandSlotRing.h"
namespace veyra::engine {
bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph) {
- window_=window;RECT rc{};GetClientRect(window,&rc);
+ gpuTimer_.initialize(ctx.device(),ctx.directQueue());window_=window;RECT rc{};GetClientRect(window,&rc);
gfx::PresentSink::Desc d;d.targetWindow=window;d.width=std::max(1L,rc.right);d.height=std::max(1L,rc.bottom);d.vsync=false;
Status st=Status::Ok;if(!sink_.initialize(ctx.device(),ctx.directQueue(),d,st))return false;
std::vector<uint8_t> vs,ps;
- if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,4))return false;
+ if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,12))return false;
D3D12_DESCRIPTOR_HEAP_DESC hd{};hd.Type=D3D12_DESCRIPTOR_HEAP_TYPE_RTV;hd.NumDescriptors=3;
if(FAILED(ctx.device()->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&rtvs_))))return false;
inc_=ctx.device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);refresh(ctx.device());
- for(unsigned i=0;i<4;++i)pipeline::makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),DXGI_FORMAT_R8G8B8A8_UNORM,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*pass_.increment});
+ for(unsigned i=0;i<8;++i)pipeline::makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),DXGI_FORMAT_R8G8B8A8_UNORM,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*pass_.increment});
+ for(unsigned i=0;i<4;++i)pipeline::makeSrv(ctx.device(),i<2?graph.sourceReference(i):graph.baseReference(i-2),DXGI_FORMAT_R16G16B16A16_FLOAT,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i+8)*pass_.increment});
return true;
}
void VideoPresenter::refresh(ID3D12Device* device){for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}
-bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,pipeline::EnhanceGraph& graph,unsigned slot,bool generated) {
+bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity) {
RECT rc{};GetClientRect(window_,&rc);if(rc.right<1||rc.bottom<1)return true;
- if(unsigned(rc.right)!=sink_.width()||unsigned(rc.bottom)!=sink_.height()) {if(!ring.drainQueue())return false;sink_.resize(rc.right,rc.bottom);refresh(ctx.device());}
- Status st=Status::Ok;const auto commandSlot=ring.slotCount()-1;auto* list=ring.acquire(commandSlot,st);if(!list)return false;
+ const auto now=std::chrono::steady_clock::now();
+ if((unsigned(rc.right)!=sink_.width()||unsigned(rc.bottom)!=sink_.height())&&now-lastResize_>=std::chrono::milliseconds(100)) {
+ if(!ring.drainQueue())return false;sink_.resize(rc.right,rc.bottom);
+ if(sink_.bufferWidth()!=unsigned(rc.right)||sink_.bufferHeight()!=unsigned(rc.bottom))return false;
+ refresh(ctx.device());lastResize_=now;
+ }
+ Status st=Status::Ok;uint32_t commandSlot=0;auto* list=ring.acquireNext(commandSlot,st);if(!list)return false;
+ gpuTimer_.frame(identity.sourceFrameId?identity:pipeline::FrameIdentity{0,0,submittedCount()+1},ctx.fence());gpuTimer_.mark(list,diagnostics::GpuStage::Blit);
auto* source=generated?graph.generatedFrameResource(slot):graph.videoFrameResource(slot);auto* bb=sink_.currentBackBuffer();if(!bb)return false;
D3D12_RESOURCE_BARRIER barriers[2]{};
for(auto& b:barriers){b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;}
@@ -35,8 +42,17 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
float dims[8]={float(graph.workWidth()),float(graph.workHeight()),0,0,float(sink_.bufferWidth()),float(sink_.bufferHeight()),0,0};list->SetGraphicsRoot32BitConstants(0,8,dims,0);
list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(slot+(generated?2:0))*pass_.increment});
list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);list->DrawInstanced(3,1,0,0);
+ if(comparison&&!generated){
+ auto* reference=baseReference?graph.baseReference(slot):graph.sourceReference(slot);
+ D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.pResource=reference;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.StateAfter=D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;list->ResourceBarrier(1,&b);
+ dims[2]=1;list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(8+slot+(baseReference?2:0))*pass_.increment});
+ if(comparison==2)rect.right=LONG(viewport.TopLeftX+viewport.Width*std::clamp(split,0.0f,1.0f));list->RSSetScissorRects(1,&rect);list->DrawInstanced(3,1,0,0);
+ std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);
+ veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));
+ }
for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(2,barriers);
- return ring.submitAndSignal(commandSlot)&&sink_.present(st);
+ gpuTimer_.mark(list,diagnostics::GpuStage::Blit,true);gpuTimer_.resolve(list);
+ if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());return sink_.present(st);
}
-void VideoPresenter::close(){rtvs_.Reset();pass_={};sink_.shutdown();}
+void VideoPresenter::close(){gpuTimer_.close();rtvs_.Reset();pass_={};sink_.shutdown();}
}
diff --git a/src/gfx/CommandSlotRing.cpp b/src/gfx/CommandSlotRing.cpp
index 8362cf04..b4de7077 100644
--- a/src/gfx/CommandSlotRing.cpp
+++ b/src/gfx/CommandSlotRing.cpp
@@ -27,6 +27,7 @@ bool CommandSlotRing::initialize(ID3D12Device* device,
fence_ = fence;
fenceEvent_ = fenceEvent;
slotCount_ = slotCount;
+ nextSlot_ = 0;
if (device_ == nullptr || queue_ == nullptr || fence_ == nullptr || fenceEvent_ == nullptr || slotCount_ == 0) {
status = Status::InvalidArgument;
@@ -145,7 +146,7 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statu
veyra::log::error("gfx", std::format("slot-ring: list reset slot={} failed hr={}", slot, veyra::hresultString(result)));
return nullptr;
}
- target.list->EndQuery(timestampHeap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,slot*2);
+ target.recording=true;target.list->EndQuery(timestampHeap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,slot*2);
return target.list.Get();
}
@@ -160,7 +161,7 @@ bool CommandSlotRing::submitAndSignal(uint32_t slot)
target.list->EndQuery(timestampHeap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,slot*2+1);
target.list->ResolveQueryData(timestampHeap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,slot*2,2,timingReadback_.Get(),slot*2*sizeof(uint64_t));
target.timed=true;
- const HRESULT closeResult = target.list->Close();
+ const HRESULT closeResult = target.list->Close();target.recording=false;
if (FAILED(closeResult)) {
veyra::log::error("gfx", std::format("slot-ring: close slot={} failed hr={}", slot, veyra::hresultString(closeResult)));
return false;
@@ -178,6 +179,9 @@ bool CommandSlotRing::submitAndSignal(uint32_t slot)
return true;
}
+bool CommandSlotRing::discardRecording(){
+ bool ok=true;for(uint32_t i=0;i<slots_.size();++i){auto& s=slots_[i];if(s.recording){const HRESULT hr=s.list->Close();s.recording=false;s.timed=false;s.label.clear();veyra::log::info("gfx",std::format("discard unsubmitted command list slot={} hr=0x{:X}",i,unsigned(hr)));if(FAILED(hr)){s.list.Reset();const HRESULT created=device_->CreateCommandList(0,D3D12_COMMAND_LIST_TYPE_DIRECT,s.allocator.Get(),nullptr,IID_PPV_ARGS(&s.list));if(FAILED(created)||FAILED(s.list->Close()))ok=false;}}}return ok;
+}
bool CommandSlotRing::drainQueue()
{
// s10: waitIdle() only waits for ALREADY-signaled values. The last
diff --git a/src/media/FFmpegDemuxer.cpp b/src/media/FFmpegDemuxer.cpp
index 6c2b4b1b..73812af0 100644
--- a/src/media/FFmpegDemuxer.cpp
+++ b/src/media/FFmpegDemuxer.cpp
@@ -106,6 +106,13 @@ double FFmpegDemuxer::averageFps() const
return static_cast<double>(stream->avg_frame_rate.num) / stream->avg_frame_rate.den;
}
+int FFmpegDemuxer::nominalRateNum() const {
+ return context_ && videoStreamIndex_ >= 0 ? context_->streams[videoStreamIndex_]->r_frame_rate.num : 0;
+}
+int FFmpegDemuxer::nominalRateDen() const {
+ return context_ && videoStreamIndex_ >= 0 ? context_->streams[videoStreamIndex_]->r_frame_rate.den : 0;
+}
+
const AVCodecParameters* FFmpegDemuxer::videoCodecParameters() const
{
if (context_ == nullptr || videoStreamIndex_ < 0) {
diff --git a/src/ngx/DlssFgBackend.cpp b/src/ngx/DlssFgBackend.cpp
index cbb90881..8f29aeb0 100644
--- a/src/ngx/DlssFgBackend.cpp
+++ b/src/ngx/DlssFgBackend.cpp
@@ -79,6 +79,7 @@ bool DlssFgBackend::queryCapability(NgxCoreHost& coreHost, Capability& caps, Sta
log::info("ngx", std::format("fg-backend: capability query result={} params={}",
ngxResultString(static_cast<uint64_t>(capResult)), capParams != nullptr ? "non-null" : "null"));
if (capParams == nullptr || capResult != NVSDK_NGX_Result_Success) {
+ log::error("ngx",std::format("fg-backend capability failed result=0x{:X} nullParams={}",unsigned(capResult),capParams==nullptr));
status = Status::DeviceFailure;
return false;
}
@@ -193,6 +194,7 @@ bool DlssFgBackend::create(NgxCoreHost& coreHost,
ngxResultString(createResult_), handle_ != nullptr ? "non-null" : "null", sehCode));
if (result != NVSDK_NGX_Result_Success) {
+ log::error("ngx", std::format("fg-backend failed result=0x{:X} seh=0x{:X}", static_cast<unsigned>(result), sehCode));
// Query FeatureInitResult for diagnostic detail (user directive).
unsigned long long initResult = 0;
const NVSDK_NGX_Result gir = params->Get(NVSDK_NGX_Parameter_FrameGeneration_FeatureInitResult, &initResult);
@@ -211,7 +213,7 @@ void DlssFgBackend::release()
{
if (handle_ != nullptr) {
const NVSDK_NGX_Result result = NVSDK_NGX_D3D12_ReleaseFeature(handle_);
- log::info("ngx", std::format("fg-backend: ReleaseFeature result={} evaluates={} resets={}",
+ (result == NVSDK_NGX_Result_Success ? log::info : log::error)("ngx", std::format("fg-backend: ReleaseFeature result={} evaluates={} resets={}",
ngxResultString(static_cast<uint64_t>(result)), evaluateCount_, resetCount_));
handle_ = nullptr;
}
@@ -222,7 +224,7 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
const EvalDesc& desc,
Status& status)
{
- if (handle_ == nullptr) {
+ if (handle_ == nullptr || desc.multiFrameCount<1 || desc.multiFrameCount>3 || desc.multiFrameIndex<1 || desc.multiFrameIndex>desc.multiFrameCount) {
status = Status::InvalidArgument;
return false;
}
@@ -237,8 +239,8 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
NVSDK_NGX_DLSSG_Opt_Eval_Params optParams{};
// 2X fixed: one generated frame per real pair.
- optParams.multiFrameCount = 1;
- optParams.multiFrameIndex = 1;
+ optParams.multiFrameCount = desc.multiFrameCount;
+ optParams.multiFrameIndex = desc.multiFrameIndex;
// Static synthetic camera: identity matrices, all motion carried by the
// mvec buffer (cameraMotionIncluded = 1).
for (int r = 0; r < 4; ++r) {
@@ -268,6 +270,10 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
optParams.orthoProjection = 0;
optParams.motionVectorsDilated = 0;
optParams.menuDetectionEnabled = 0;
+ optParams.backbufferSubrectSize={width_,height_};
+ optParams.outputInterpSubrectSize={width_,height_};
+ optParams.mvecsSubrectSize={width_,height_};
+ optParams.depthSubrectSize={width_,height_};
if (desc.reset) {
++resetCount_;
@@ -279,11 +285,12 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
uint32_t sehCode = 0;
const NVSDK_NGX_Result result = CallEvaluateDlssg(cmdList, handle_, params,
&evalParams, &optParams, sehCode);
- log::info("ngx", std::format("fg-backend: Evaluate #{} frameId={} reset={} result={} seh={}",
- evaluateCount_ + 1, desc.frameId, desc.reset ? 1 : 0,
+ log::info("ngx", std::format("fg-backend: Evaluate #{} frameId={} reset={} generatedCount={} subframe={} result={} seh={}",
+ evaluateCount_ + 1, desc.frameId, desc.reset ? 1 : 0,desc.multiFrameCount,desc.multiFrameIndex,
ngxResultString(static_cast<uint64_t>(result)), sehCode));
if (result != NVSDK_NGX_Result_Success) {
+ log::error("ngx", std::format("fg-backend failed result=0x{:X} seh=0x{:X}", static_cast<unsigned>(result), sehCode));
status = Status::DeviceFailure;
return false;
}
diff --git a/src/ngx/DlssSrBackend.cpp b/src/ngx/DlssSrBackend.cpp
index f983536a..d28fc712 100644
--- a/src/ngx/DlssSrBackend.cpp
+++ b/src/ngx/DlssSrBackend.cpp
@@ -106,6 +106,7 @@ bool DlssSrBackend::create(NgxCoreHost& coreHost,
ngxResultString(createResult_), handle_ != nullptr ? "non-null" : "null", sehCode));
if (result != NVSDK_NGX_Result_Success) {
+ log::error("ngx", std::format("sr-backend failed result=0x{:X} seh=0x{:X}", static_cast<unsigned>(result), sehCode));
// Query FeatureInitResult for diagnostic detail (user directive).
int featureInitResult = 0;
const NVSDK_NGX_Result gir = params->Get(NVSDK_NGX_Parameter_SuperSampling_FeatureInitResult, &featureInitResult);
@@ -122,7 +123,7 @@ void DlssSrBackend::release()
if (handle_ != nullptr) {
// SR is a core NGX feature; release through the core API.
const NVSDK_NGX_Result result = NVSDK_NGX_D3D12_ReleaseFeature(handle_);
- log::info("ngx", std::format("sr-backend: ReleaseFeature result={}", ngxResultString(static_cast<uint64_t>(result))));
+ (result == NVSDK_NGX_Result_Success ? log::info : log::error)("ngx", std::format("sr-backend: ReleaseFeature result={}", ngxResultString(static_cast<uint64_t>(result))));
handle_ = nullptr;
}
}
@@ -164,6 +165,7 @@ bool DlssSrBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
evaluateCount_ + 1, ngxResultString(static_cast<uint64_t>(result)), sehCode));
if (result != NVSDK_NGX_Result_Success) {
+ log::error("ngx", std::format("sr-backend failed result=0x{:X} seh=0x{:X}", static_cast<unsigned>(result), sehCode));
status = Status::DeviceFailure;
return false;
}
diff --git a/src/ngx/NvOfSession.cpp b/src/ngx/NvOfSession.cpp
index e479d4f9..76e098ad 100644
--- a/src/ngx/NvOfSession.cpp
+++ b/src/ngx/NvOfSession.cpp
@@ -78,6 +78,7 @@ bool NvOfSession::initialize(ID3D12Device* device,
log::info("nvof-session", std::format("maxApiVersion status={} version=0x{:X}",
static_cast<int>(vst), maxVer));
if (vst != NV_OF_SUCCESS) {
+ log::error("nvof-session", std::format("GetMaxSupportedApiVersion failed status={}", int(vst)));
status = Status::DeviceFailure;
return false;
}
@@ -95,6 +96,7 @@ bool NvOfSession::initialize(ID3D12Device* device,
if (ist != NV_OF_SUCCESS || fn_->list.nvCreateOpticalFlowD3D12 == nullptr ||
fn_->list.nvOFInit == nullptr || fn_->list.nvOFExecuteD3D12 == nullptr ||
fn_->list.nvOFRegisterResourceD3D12 == nullptr || fn_->list.nvOFDestroy == nullptr) {
+ log::error("nvof-session", std::format("CreateInstance/function table failed status={}", int(ist)));
status = Status::DeviceFailure;
return false;
}
@@ -105,6 +107,7 @@ bool NvOfSession::initialize(ID3D12Device* device,
log::info("nvof-session", std::format("CreateOpticalFlowD3D12 status={} handle={}",
static_cast<int>(cst), ofHandle != nullptr ? "non-null" : "null"));
if (cst != NV_OF_SUCCESS || ofHandle == nullptr) {
+ log::error("nvof-session", std::format("CreateOpticalFlow failed status={} nullHandle={}", int(cst), ofHandle == nullptr));
status = Status::DeviceFailure;
return false;
}
@@ -228,7 +231,12 @@ bool NvOfSession::initialize(ID3D12Device* device,
init.height = desc.height;
init.outGridSize = static_cast<NV_OF_OUTPUT_VECTOR_GRID_SIZE>(grid);
init.mode = NV_OF_MODE_OPTICALFLOW;
- init.perfLevel = NV_OF_PERF_LEVEL_MEDIUM;
+ if(desc.quality>2){status=Status::InvalidArgument;return false;}
+ // SDK nvOpticalFlowCommon.h: FAST=20, MEDIUM=10, SLOW=5.
+ // No perf-level capability query exists; nvOFInit acceptance is required.
+ init.perfLevel = desc.quality==0?NV_OF_PERF_LEVEL_FAST:desc.quality==1?NV_OF_PERF_LEVEL_MEDIUM:NV_OF_PERF_LEVEL_SLOW;
+ caps_.requestedQuality=desc.quality;caps_.appliedQuality=desc.quality;caps_.actualPerfLevel=init.perfLevel;
+ log::info("nvof-quality",std::format("requested={} SDK-perf={} grid={} extent={}x{}; nvOFInit will validate support; no silent fallback",desc.quality,int(init.perfLevel),grid,desc.width,desc.height));
init.enableExternalHints = NV_OF_FALSE;
init.enableOutputCost = NV_OF_TRUE; // cost is mandatory (explicit costOut param)
init.hPrivData = nullptr;
@@ -241,6 +249,7 @@ bool NvOfSession::initialize(ID3D12Device* device,
log::info("nvof-session", std::format("nvOFInit status={} ({}x{} grid{} fwd ABGR8 flowExtent={}x{})",
static_cast<int>(initSt), desc.width, desc.height, grid, gridW_, gridH_));
if (initSt != NV_OF_SUCCESS) {
+ log::error("nvof-session", std::format("nvOFInit failed status={}", int(initSt)));
status = Status::DeviceFailure;
return false;
}
@@ -254,7 +263,7 @@ bool NvOfSession::initialize(ID3D12Device* device,
NV_OF_UNREGISTER_RESOURCE_PARAMS_D3D12 up{};
up.hOFGpuBuffer = reinterpret_cast<NvOfBufferT>(h);
const NV_OF_STATUS us = fn_->list.nvOFUnregisterResourceD3D12(&up);
- log::info("nvof-session", std::format("rollback unregister {} status={}", name, (int)us));
+ (us == NV_OF_SUCCESS ? log::info : log::error)("nvof-session", std::format("rollback unregister {} status={}", name, (int)us));
if (us == NV_OF_SUCCESS) h = nullptr;
};
auto rollbackAll = [&]() {
@@ -356,7 +365,7 @@ bool NvOfSession::unregisterAll(Status& status)
NV_OF_UNREGISTER_RESOURCE_PARAMS_D3D12 p{};
p.hOFGpuBuffer = reinterpret_cast<NvOfBufferT>(h);
const NV_OF_STATUS st = fn_->list.nvOFUnregisterResourceD3D12(&p);
- log::info("nvof-session", std::format("unregister {} status={}", name, static_cast<int>(st)));
+ (st == NV_OF_SUCCESS ? log::info : log::error)("nvof-session", std::format("unregister {} status={}", name, static_cast<int>(st)));
if (st == NV_OF_SUCCESS) h = nullptr;
else allOk = false;
};
@@ -379,7 +388,7 @@ void NvOfSession::shutdown()
NV_OF_UNREGISTER_RESOURCE_PARAMS_D3D12 p{};
p.hOFGpuBuffer = reinterpret_cast<NvOfBufferT>(h);
const NV_OF_STATUS st = fn_->list.nvOFUnregisterResourceD3D12(&p);
- log::info("nvof-session", std::format("unregister {} status={}", name, static_cast<int>(st)));
+ (st == NV_OF_SUCCESS ? log::info : log::error)("nvof-session", std::format("unregister {} status={}", name, static_cast<int>(st)));
if (st == NV_OF_SUCCESS) h = nullptr;
};
unregister(hCost_, "costOut");
@@ -388,7 +397,7 @@ void NvOfSession::shutdown()
unregister(hInputA_, "inputA");
if (ofHandle_ != nullptr && fn_ != nullptr && fn_->list.nvOFDestroy != nullptr) {
const NV_OF_STATUS st = fn_->list.nvOFDestroy(reinterpret_cast<NvOfHandleT>(ofHandle_));
- log::info("nvof-session", std::format("nvOFDestroy status={} executes={}",
+ (st == NV_OF_SUCCESS ? log::info : log::error)("nvof-session", std::format("nvOFDestroy status={} executes={}",
static_cast<int>(st), executeCount_));
ofHandle_ = nullptr;
}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index c3e26a03..b1494d75 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -33,6 +33,7 @@ extern "C" {
}
namespace veyra::pipeline {
+using diagnostics::GpuStage;
namespace {
@@ -57,13 +58,17 @@ EnhanceGraph::~EnhanceGraph()
// ---------------------------------------------------------------------------
bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
{
- desc_ = desc;
+ desc_ = desc;tracker_={};prevValid_=false;cadence_.reset();scene_.reset();previousLuma_.clear();
+ diagnostics::DiagnosticEvent initDiagnostic;initDiagnostic.stage="initialize";initDiagnostic.identity={epoch_+1,desc.settingsRevision,0};initDiagnostic.resolution.source={desc.sourceWidth,desc.sourceHeight};initDiagnostic.resolution.base=initDiagnostic.resolution.fg=initDiagnostic.resolution.output={desc.workWidth,desc.workHeight};initDiagnostic.resolution.nr={desc.nrWidth?desc.nrWidth:desc.workWidth,desc.nrHeight?desc.nrHeight:desc.workHeight};initDiagnostic.resolution.flow=initDiagnostic.resolution.source;initDiagnostic.flowApplied=std::to_string(unsigned(desc.flowQuality));initDiagnostic.runtimeHash="E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E";Logger::diagnosticContext(initDiagnostic);
srcW_ = desc.sourceWidth;
srcH_ = desc.sourceHeight;
workW_ = desc.workWidth;
workH_ = desc.workHeight;
- nvofW_ = workW_;
- nvofH_ = workH_;
+ nrW_=desc.nrWidth?desc.nrWidth:workW_; nrH_=desc.nrHeight?desc.nrHeight:workH_;
+ nvofW_ = srcW_;
+ nvofH_ = srcH_;
+ if(!Extent{nrW_,nrH_}.valid()||nrW_>workW_||nrH_>workH_){veyra::log::error("resolution","invalid NR extent");return false;}
+ veyra::log::info("resolution",std::format("source={}x{} base={}x{} nr={}x{} flow={}x{} fg={}x{} output={}x{}",srcW_,srcH_,workW_,workH_,nrW_,nrH_,nvofW_,nvofH_,workW_,workH_,workW_,workH_));
srEnabled_ = desc.enableSr;
nrEnabled_ = desc.enableNr && !desc.noFeatures && !desc.noNgx;
fgEnabled_ = desc.enableFg && !desc.noNgx;
@@ -78,6 +83,7 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
const size_t dSize = dPitch_ * workH_;
nv12Buf_.resize(lumaSize_ + chromaSize_);
+ if(!gpuTimer_.initialize(context_.device(),context_.directQueue()))veyra::log::warn("gpu-timestamp","GPU timing unavailable");
if (!createResources()) return false;
if (!initZeroAndDepthTextures()) return false;
if (!initNvof()) return false;
@@ -93,6 +99,19 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
bool EnhanceGraph::createResources()
{
+ fgDisableInit_=makeUploadBuffer(context_.device(),4);
+ if(!fgDisableInit_)return false;
+ void* initial=nullptr;if(FAILED(fgDisableInit_->Map(0,nullptr,&initial)))return false;
+ *static_cast<uint32_t*>(initial)=1;fgDisableInit_->Unmap(0,nullptr);
+ for(unsigned i=0;i<6;++i){
+ D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=4;bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;bd.Flags=D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_DEFAULT;
+ HRESULT hr=context_.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&fgDisable_[i]));
+ if(FAILED(hr)){veyra::log::error("fg-status",std::format("allocate UAV hr=0x{:X}",unsigned(hr)));return false;}
+ hp.Type=D3D12_HEAP_TYPE_READBACK;bd.Flags=D3D12_RESOURCE_FLAG_NONE;
+ hr=context_.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&fgDisableReadback_[i]));
+ if(FAILED(hr)){veyra::log::error("fg-status",std::format("allocate readback hr=0x{:X}",unsigned(hr)));return false;}
+ }
// NV12 CPU upload keeps UPLOAD-heap BUFFERS (upload-heap textures are
// size-limited) with persistent mapping, but the GPU ingestion is now a
// PLACED_FOOTPRINT CopyTextureRegion instead of the retired RAW-buffer
@@ -109,9 +128,15 @@ bool EnhanceGraph::createResources()
chromaTex_ = makeTexture(context_.device(), srcW_ / 2, srcH_ / 2, DXGI_FORMAT_R8G8_UNORM, true);
srcRgba_ = makeTexture(context_.device(), srcW_, srcH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);
workRgba_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);
- proxyTex_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
- neuralTex_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
- finalRgba_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);
+ for(unsigned i=0;i<2;++i){sourceReferences_[i]=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);baseReferences_[i]=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);if(!sourceReferences_[i]||!baseReferences_[i])return false;}
+ nrInput_=makeTexture(context_.device(),nrW_,nrH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);
+ residualRgba_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);
+ nrFlow_=makeTexture(context_.device(),nrW_,nrH_,DXGI_FORMAT_R16G16_FLOAT,true);
+ baseFlow_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16_FLOAT,true);
+ if(!nrInput_||!residualRgba_||!nrFlow_||!baseFlow_)return false;
+ proxyTex_ = makeTexture(context_.device(), nrW_, nrH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
+ neuralTex_ = makeTexture(context_.device(), nrW_, nrH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
+ finalRgba_ = makeTexture(context_.device(), nrW_, nrH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);
videoFrame_[0] = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
videoFrame_[1] = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
confTex_ = makeTexture(context_.device(), nvofW_, nvofH_, DXGI_FORMAT_R8_UNORM, true);
@@ -119,6 +144,7 @@ bool EnhanceGraph::createResources()
depthTex_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R32_FLOAT, false);
genFrame_[0] = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
genFrame_[1] = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
+ for(unsigned i=2;i<6;++i){genFrame_[i]=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R8G8B8A8_UNORM,true);if(!genFrame_[i])return false;}
nrZeroMotion_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R16G16_FLOAT, false);
nrZeroDepth_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R32_FLOAT, false);
rawW_ = (nvofW_ + nvofGrid_ - 1) / nvofGrid_;
@@ -243,7 +269,7 @@ bool EnhanceGraph::initNvof()
nd.width = nvofW_; nd.height = nvofH_;
nd.inFence = context_.fence();
nd.outFence = nvofOutFence_.Get();
- nd.gridSize = 4;
+ nd.gridSize = 4;nd.quality=uint32_t(desc_.flowQuality);
// s6 contract: B8G8R8A8 inputs, raw R16G16_SINT + R8_UINT cost at grid
// extent, passed explicitly; allocation failure = fail closed.
Status st = Status::Ok;
@@ -258,8 +284,8 @@ bool EnhanceGraph::initNvof()
bool EnhanceGraph::initNgxFeatures()
{
- if (desc_.noNgx) {
- veyra::log::warn("graph", "VEYRA_NO_NGX: core+features skipped; NVOF only");
+ if (desc_.noNgx || desc_.noFeatures) {
+ veyra::log::info("graph", "NGX core/features skipped by disabled-feature configuration");
return true;
}
// Read the local NGX identity (same loader contract as the probes).
@@ -298,6 +324,7 @@ bool EnhanceGraph::initNgxFeatures()
veyra::log::error("graph", "FG unavailable; fail closed");
return false;
}
+ if(desc_.enableFg&&(desc_.fgMultiplier<2||desc_.fgMultiplier>4||fgCaps.multiFrameCountMax<desc_.fgMultiplier-1)){veyra::log::error("graph","requested MFG multiplier unsupported");return false;}
fgCapsAvailable_ = fgCaps.available;
fgMultiFrameMax_ = fgCaps.multiFrameCountMax;
veyra::log::info("graph", std::format("FG capability available={} multiFrameMax={}",
@@ -320,16 +347,16 @@ bool EnhanceGraph::initNgxFeatures()
{
namespace p = ngx::dlssnr;
ngx::ParameterBlock pb(ngxParams_);
- pb.setU32(p::kWidth, workW_); pb.setU32(p::kHeight, workH_);
- pb.setU32(p::kInputWidth, workW_); pb.setU32(p::kInputHeight, workH_);
- pb.setU32(p::kOutputWidth, workW_); pb.setU32(p::kOutputHeight, workH_);
- pb.setU32(p::kOutputDotWidth, workW_); pb.setU32(p::kOutputDotHeight, workH_);
+ pb.setU32(p::kWidth, nrW_); pb.setU32(p::kHeight, nrH_);
+ pb.setU32(p::kInputWidth, nrW_); pb.setU32(p::kInputHeight, nrH_);
+ pb.setU32(p::kOutputWidth, nrW_); pb.setU32(p::kOutputHeight, nrH_);
+ pb.setU32(p::kOutputDotWidth, nrW_); pb.setU32(p::kOutputDotHeight, nrH_);
pb.setU32(p::kUpscaling, 0);
pb.setF32(p::kScale, 1.0f); pb.setF32(p::kScalingRatio, 1.0f);
pb.setVoid(p::kComputeScalingRatioCallback,
reinterpret_cast<void*>(&ngx::DlssNrRuntimeAdapter::scalingRatioCallback));
pb.setI32(p::kHintRenderPreset, 0);
- pb.setU32(p::kStdWidth, workW_); pb.setU32(p::kStdHeight, workH_);
+ pb.setU32(p::kStdWidth, nrW_); pb.setU32(p::kStdHeight, nrH_);
pb.setI32(p::kPerfQualityValue, 1);
pb.setU32(p::kCreationNodeMask, 1); pb.setU32(p::kVisibilityNodeMask, 1);
ID3D12GraphicsCommandList* list = ring_.acquire(0, st);
@@ -382,7 +409,7 @@ bool EnhanceGraph::initNgxFeatures()
b[i].Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
b[i].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
}
- b[0].Transition.pResource = nvofInB_.Get();
+ b[0].Transition.pResource = videoFrame_[0].Get();
b[0].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
b[1].Transition.pResource = nrZeroMotion_.Get();
b[1].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
@@ -392,16 +419,22 @@ bool EnhanceGraph::initNgxFeatures()
b[3].Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
wlist->ResourceBarrier(4, b);
ngx::DlssFgBackend::EvalDesc fe{};
- fe.backbuffer = nvofInB_.Get();
+ fe.backbuffer = videoFrame_[0].Get();
fe.depth = depthTex_.Get();
fe.mvecs = nrZeroMotion_.Get();
fe.outputInterpolated = genFrame_[0].Get();
fe.reset = true;
- fe.frameId = 0;
+ fe.multiFrameCount=desc_.enableFg?desc_.fgMultiplier-1:1;fe.multiFrameIndex=1;
+ fe.frameId = 0; // warm-up has its own identity; product IDs start at 1
fe.mvecScaleX = 1.0f;
fe.mvecScaleY = 1.0f;
- const bool warmOk = fgBackend_->evaluate(wlist, ngxParams_, fe, st);
- (void)warmOk;
+ bool warmOk = true;
+ for(uint32_t sub=1;sub<=fe.multiFrameCount;++sub){
+ fe.multiFrameIndex=sub;
+ warmOk=fgBackend_->evaluate(wlist,ngxParams_,fe,st)&&warmOk;
+ D3D12_RESOURCE_BARRIER u{};u.Type=D3D12_RESOURCE_BARRIER_TYPE_UAV;u.UAV.pResource=fe.outputInterpolated;wlist->ResourceBarrier(1,&u);
+ }
+ if(!warmOk)return false;
for (int i = 0; i < 4; ++i) b[i].Transition.StateBefore = b[i].Transition.StateAfter;
b[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON;
b[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON;
@@ -418,6 +451,9 @@ bool EnhanceGraph::initNgxFeatures()
bool EnhanceGraph::createComputePasses()
{
std::vector<uint8_t> cs;
+ if(!downsamplePass_.loadShader("NrDownsample.dxil",cs)||!downsamplePass_.create(context_.device(),cs,2,1,1))return false;
+ if(!residualPass_.loadShader("NrResidualComposite.dxil",cs)||!residualPass_.create(context_.device(),cs,4,3,1))return false;
+ if(!flowAdaptPass_.loadShader("FlowAdapt.dxil",cs)||!flowAdaptPass_.create(context_.device(),cs,3,1,1))return false;
if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 8, 2, 1)) return false;
if (!encPass_.loadShader("ParityEncode.dxil", cs) || !encPass_.create(context_.device(), cs, 8, 1, 1)) return false;
if (!decPass_.loadShader("ParityDecode.dxil", cs) || !decPass_.create(context_.device(), cs, 8)) return false;
@@ -469,14 +505,23 @@ bool EnhanceGraph::createViews()
stager_.stageSrv(resource, &srv, pass.heap.Get(), slot);
};
- stagedSrv(workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 15);
+ stagedSrv(srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 15);
+ stagedSrv(workRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,downsamplePass_,0);
+ makeUav(context_.device(),nrInput_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(downsamplePass_,1));
+ stagedSrv(workRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,residualPass_,0);
+ stagedSrv(nrInput_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,residualPass_,1);
+ stagedSrv(finalRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,residualPass_,2);
+ makeUav(context_.device(),residualRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(residualPass_,3));
+ stagedSrv(flowTex_.Get(),DXGI_FORMAT_R16G16_FLOAT,flowAdaptPass_,0);
+ makeUav(context_.device(),nrFlow_.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,1));
+ makeUav(context_.device(),baseFlow_.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,2));
// Immutable per-resource views.
if (viewsTex) stagedSrv(lumaTex_.Get(), DXGI_FORMAT_R8_UNORM, yuvPass_, 0);
if (viewsTex) stagedSrv(chromaTex_.Get(), DXGI_FORMAT_R8G8_UNORM, yuvPass_, 1);
if (viewsUav) makeUav(context_.device(), srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(yuvPass_, 2));
- if (viewsTex) stagedSrv(workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, encPass_, 0);
+ if (viewsTex) stagedSrv(nrInput_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, encPass_, 0);
if (viewsUav) makeUav(context_.device(), proxyTex_.Get(), DXGI_FORMAT_R8G8B8A8_UNORM, cpu(encPass_, 1));
- if (viewsTex) stagedSrv(workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, decPass_, 0);
+ if (viewsTex) stagedSrv(nrInput_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, decPass_, 0);
if (viewsTex) stagedSrv(proxyTex_.Get(), DXGI_FORMAT_R8G8B8A8_UNORM, decPass_, 1);
if (viewsTex) stagedSrv(neuralTex_.Get(), DXGI_FORMAT_R8G8B8A8_UNORM, decPass_, 2);
if (viewsUav) makeUav(context_.device(), finalRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(decPass_, 3));
@@ -492,7 +537,7 @@ bool EnhanceGraph::createViews()
// 13/14: genTex SRV (slot 2)
if (viewsTex) stagedSrv(srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 0);
if (viewsUav) makeUav(context_.device(), workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(blitPass_, 1));
- if (viewsTex) stagedSrv(nrEnabled_ ? finalRgba_.Get() : workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 2);
+ if (viewsTex) stagedSrv(nrEnabled_ ? residualRgba_.Get() : workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 2);
if (viewsUav) makeUav(context_.device(), videoFrame_[0].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, cpu(blitPass_, 3));
if (viewsUav) makeUav(context_.device(), videoFrame_[1].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, cpu(blitPass_, 4));
if (viewsTex) stagedSrv(nvofInB_.Get(), DXGI_FORMAT_B8G8R8A8_UNORM, blitPass_, 5);
@@ -541,18 +586,29 @@ bool EnhanceGraph::createViews()
// ---------------------------------------------------------------------------
// process: the per-frame chain (verbatim from the probe lambda).
// ---------------------------------------------------------------------------
-bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out)
+bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId)
{
out = FrameOutputs{};
out.ptsMs = ptsMs;
+ if(!sourceFrameId)sourceFrameId=realFrameIndex_+1;
+ diagnostics::DiagnosticEvent diagnostic;diagnostic.stage="frame";diagnostic.identity={epoch_+uint64_t(reset),desc_.settingsRevision,sourceFrameId};diagnostic.batch=realFrameIndex_+1;
+ diagnostic.resolution.source={srcW_,srcH_};diagnostic.resolution.base={workW_,workH_};diagnostic.resolution.nr={nrW_,nrH_};diagnostic.resolution.flow={nvofW_,nvofH_};diagnostic.resolution.fg=diagnostic.resolution.output={workW_,workH_};diagnostic.runtimeHash="E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E";diagnostic.flowApplied=std::to_string(actualFlowPerf());diagnostic.fallbackReason=mvecSource_;Logger::diagnosticContext(diagnostic);
static const bool graphOff = GetEnvironmentVariableW(L"VEYRA_GRAPH_OFF", nullptr, 0) != 0;
if (!frame || !initialized_ || !std::isfinite(ptsMs)) return false;
if (frame->color_trc == AVCOL_TRC_SMPTE2084 || frame->color_trc == AVCOL_TRC_ARIB_STD_B67) {
veyra::log::error("graph", "HDR input is unsupported by the V1 SDR pipeline"); return false;
}
- if (reset) { prevValid_ = false; scene_.reset(); previousLuma_.clear(); }
+ if(std::abs(ptsMs)>9e13){veyra::log::error("timeline","PTS outside representable range");return false;}
+ if(prevValid_&&(std::llround(ptsMs*10000)-std::llround(prevPtsMs_*10000)<4||ptsMs-prevPtsMs_>1000)){
+ reset=true;veyra::log::info("timeline","non-monotonic or discontinuous PTS; atomic history reset");
+ }
+ if (reset) { prevValid_ = false; scene_.reset(); previousLuma_.clear();cadence_.reset(); }
const uint32_t parity = static_cast<uint32_t>(realFrameIndex_ % 2);
+ if(!realLeases_[parity].expired()||!generatedLeases_[parity].expired()){
+ veyra::log::error("frame-pool",std::format("slot={} still leased; refusing overwrite, batch={}",parity,realFrameIndex_+1));return false;
+ }
+ for(unsigned i=parity;i<6;i+=2)if(!generatedLeases_[i].expired()){veyra::log::error("frame-pool","generated subframe still leased; refusing overwrite");return false;}
if (graphOff) {
prevPtsMs_ = ptsMs;
prevValid_ = true;
@@ -562,14 +618,15 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
out.passthrough = true;
return true;
}
- uint32_t slot = nextListSlot_++ % ring_.slotCount();
+ uint32_t slot = 0;
if (uploadFences_[parity] && !context_.waitForFenceValue(uploadFences_[parity])) return false;
Status st = Status::Ok;
// 1. Source NV12: D3D12VA texture directly (GPU) or CPU upload.
ID3D12Resource* nv12Texture = nullptr;
- ID3D12GraphicsCommandList* list = ring_.acquire(slot, st);
+ ID3D12GraphicsCommandList* list = ring_.acquireNext(slot, st);
if (list == nullptr) { veyra::log::error("graph", "ring acquire"); return false; }
+ gpuTimer_.frame({epoch_,desc_.settingsRevision,realFrameIndex_+1},context_.fence());gpuTimer_.mark(list,GpuStage::Color);
if (frame->format == AV_PIX_FMT_D3D12) {
auto* d3dFrame = reinterpret_cast<AVD3D12VAFrame*>(frame->data[0]);
@@ -644,6 +701,10 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
std::vector<uint8_t> sample;sample.reserve(64*36);std::vector<double> hist(256,0);double sad=0;
for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){const uint8_t v=planes[0][size_t(y*srcH_/36)*lumaPitch_+x*srcW_/64];hist[v]+=1.0/(64*36);sample.push_back(v);}
if(previousLuma_.size()==sample.size())for(size_t i=0;i<sample.size();++i)sad+=std::abs(int(sample[i])-int(previousLuma_[i]))/(255.0*sample.size());
+ cadence_.observe(ptsMs,sad,previousLuma_.size()==sample.size());
+ out.measuredContentRate=cadence_.confirmedRate(desc_.contentRate);
+ if(cadence_.conflicts(desc_.contentRate)&&realFrameIndex_%60==0)veyra::log::warn("cadence","requested content-rate identification conflicts with observed motion; preserving source timestamps");
+ out.contentDuplicate=desc_.contentRate!=engine::ContentRate::Transport&&previousLuma_.size()==sample.size()&&sad<0.0001;
const auto analysis=scene_.analyze(realFrameIndex_,hist,sad,static_cast<uint64_t>(std::max(0.0,ptsMs)*1000));
if(analysis.isSceneCut||analysis.isCadenceBreak){reset=true;prevValid_=false;if(analysis.isSceneCut)++metrics_.sceneCutCount;}
previousLuma_=std::move(sample);
@@ -686,58 +747,30 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if (nv12Texture != nullptr) {
tracker_.transition(list, nv12Texture, D3D12_RESOURCE_STATE_COMMON);
}
+ gpuTimer_.mark(list,GpuStage::Color,true);
if (desc_.stageMark) desc_.stageMark("yuv");
- // 3. SR into workRgba (or 1:1 blit bypass).
- if(reset)++metrics_.resetCount;
- if (srEnabled_ && srBackend_ && srBackend_->created()) {
- tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- ngx::DlssSrBackend::EvalDesc ed{};
- ed.color = srcRgba_.Get();
- ed.output = workRgba_.Get();
- ed.depth = nrZeroDepth_.Get();
- ed.motionVectors = nrZeroMotion_.Get();
- ed.reset = reset;
- if (!srBackend_->evaluate(list, ngxParams_, ed, st)) {
- veyra::log::error("graph", "sr evaluate failed");
- return false;
- }
- ++metrics_.srEvaluateCount;
- tracker_.uavBarrier(list, workRgba_.Get());
- tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- } else {
- tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- const float constants[8] = {
- uintBits(srcW_), uintBits(srcH_),
- uintBits(workW_), uintBits(workH_), 0, 0, 0, 0 };
- blitPass_.bind(list, constants, gpuHandleOf(blitPass_, 0).ptr, gpuHandleOf(blitPass_, 1).ptr);
- list->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
- tracker_.uavBarrier(list, workRgba_.Get());
- tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- }
- if (desc_.stageMark) desc_.stageMark("sr");
-
-
// Guidance from original post-SR color BEFORE NR. Queue waits are GPU-side.
bool haveFlow = false;
- const bool runMotion = nvofStandalone_ || fgEnabled_;
+ const bool runMotion = nvofStandalone_ || fgEnabled_ || srEnabled_;
if (runMotion && nvof_ && nvof_->initialized()) {
- const float dims[8] = {uintBits(workW_),uintBits(workH_),uintBits(workW_),uintBits(workH_),0,0,0,0};
+ const float dims[8] = {uintBits(nvofW_),uintBits(nvofH_),uintBits(nvofW_),uintBits(nvofH_),0,0,0,0};
if (prevValid_) {
tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(list,nvofInA_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
blitPass_.bind(list,dims,gpuHandleOf(blitPass_,5).ptr,gpuHandleOf(blitPass_,6).ptr);
- list->Dispatch((workW_+15)/16,(workH_+15)/16,1);
+ list->Dispatch((nvofW_+15)/16,(nvofH_+15)/16,1);
tracker_.uavBarrier(list,nvofInA_.Get());
tracker_.transition(list,nvofInA_.Get(),D3D12_RESOURCE_STATE_COMMON);
}
tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- const float encodedDims[8] = {uintBits(workW_),uintBits(workH_),uintBits(workW_),uintBits(workH_),1,0,0,0};
+ const float encodedDims[8] = {uintBits(nvofW_),uintBits(nvofH_),uintBits(nvofW_),uintBits(nvofH_),1,0,0,0};
blitPass_.bind(list,encodedDims,gpuHandleOf(blitPass_,15).ptr,gpuHandleOf(blitPass_,9).ptr);
- list->Dispatch((workW_+15)/16,(workH_+15)/16,1);
+ list->Dispatch((nvofW_+15)/16,(nvofH_+15)/16,1);
tracker_.uavBarrier(list,nvofInB_.Get());
tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_COMMON);
if (prevValid_) {
+ gpuTimer_.mark(list,GpuStage::Flow);
if(!ring_.submitAndSignal(slot))return false;
haveFlow=nvof_->execute(ring_.lastSignaledValue(),st);
if(!haveFlow) { ++metrics_.nvofFrameFailures; mvecSource_="zero-motion-fallback (NVOF execute failed)"; }
@@ -745,16 +778,17 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
++metrics_.nvofExecuteCount;
if(FAILED(context_.directQueue()->Wait(nvofOutFence_.Get(),nvof_->nextOutValue()-1)))return false;
}
- slot=nextListSlot_++%ring_.slotCount(); list=ring_.acquire(slot,st);if(!list)return false;
+ list=ring_.acquireNext(slot,st);if(!list)return false;
+ gpuTimer_.mark(list,GpuStage::Flow,true);
if(haveFlow) {
tracker_.transition(list,nvofRawTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(list,nvofCostTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(list,flowTex_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
tracker_.transition(list,confTex_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- const float dc[8]={uintBits(rawW_),uintBits(rawH_),uintBits(workW_),uintBits(workH_),
+ const float dc[8]={uintBits(rawW_),uintBits(rawH_),uintBits(nvofW_),uintBits(nvofH_),
uintBits(selectedGrid_),uintBits(0),uintBits(32),0};
densifyPass_.bind(list,dc,gpuHandleOf(densifyPass_,0).ptr,gpuHandleOf(densifyPass_,2).ptr);
- list->Dispatch((workW_+15)/16,(workH_+15)/16,1);
+ list->Dispatch((nvofW_+15)/16,(nvofH_+15)/16,1);
tracker_.uavBarrier(list,flowTex_.Get());tracker_.uavBarrier(list,confTex_.Get());
tracker_.transition(list,nvofRawTex_.Get(),D3D12_RESOURCE_STATE_COMMON);
tracker_.transition(list,nvofCostTex_.Get(),D3D12_RESOURCE_STATE_COMMON);
@@ -764,52 +798,107 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
}
+ // 3. SR into workRgba (or 1:1 blit bypass).
+ if(haveFlow){
+ auto adapt=[&](ID3D12Resource* output,uint32_t w,uint32_t h,uint32_t descriptor){
+ tracker_.transition(list,output,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const float c[8]={uintBits(nvofW_),uintBits(nvofH_),uintBits(w),uintBits(h),0,0,0,0};
+ flowAdaptPass_.bind(list,c,gpuHandleOf(flowAdaptPass_,0).ptr,gpuHandleOf(flowAdaptPass_,descriptor).ptr);
+ list->Dispatch((w+15)/16,(h+15)/16,1);tracker_.uavBarrier(list,output);tracker_.transition(list,output,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ };
+ adapt(nrFlow_.Get(),nrW_,nrH_,1);adapt(baseFlow_.Get(),workW_,workH_,2);
+ }
+ if(reset){++metrics_.resetCount;++epoch_;}
+ out.batch.batchId=realFrameIndex_+1;out.batch.identity={epoch_,desc_.settingsRevision,sourceFrameId};
+ out.batch.a100ns=static_cast<int64_t>(std::llround(prevPtsMs_*10000));
+ out.batch.b100ns=static_cast<int64_t>(std::llround(ptsMs*10000));gpuTimer_.identity(out.batch.identity);
+ if (srEnabled_ && srBackend_ && srBackend_->created()) {
+ gpuTimer_.mark(list,GpuStage::Sr);
+ tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ ngx::DlssSrBackend::EvalDesc ed{};
+ ed.color = srcRgba_.Get();
+ ed.output = workRgba_.Get();
+ ed.depth = nrZeroDepth_.Get();
+ ed.motionVectors = haveFlow?baseFlow_.Get():nrZeroMotion_.Get();
+ ed.reset = reset;
+ if (!srBackend_->evaluate(list, ngxParams_, ed, st)) {
+ veyra::log::error("graph", "sr evaluate failed");
+ return false;
+ }
+ ++metrics_.srEvaluateCount;gpuTimer_.mark(list,GpuStage::Sr,true);
+ tracker_.uavBarrier(list, workRgba_.Get());
+ tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ } else {
+ tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const float constants[8] = {
+ uintBits(srcW_), uintBits(srcH_),
+ uintBits(workW_), uintBits(workH_), 0, 0, 0, 0 };
+ blitPass_.bind(list, constants, gpuHandleOf(blitPass_, 0).ptr, gpuHandleOf(blitPass_, 1).ptr);
+ list->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
+ tracker_.uavBarrier(list, workRgba_.Get());
+ tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ }
+ if (desc_.stageMark) desc_.stageMark("sr");
+ // GPU copies retain exact pre-enhancement references under the real lease.
+ auto retain=[&](ID3D12Resource* src,ID3D12Resource* dst){tracker_.transition(list,src,D3D12_RESOURCE_STATE_COPY_SOURCE);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(dst,src);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,src,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);};
+ retain(srcRgba_.Get(),sourceReferences_[parity].Get());retain(workRgba_.Get(),baseReferences_[parity].Get());
+
+
// 4a. Parity encode.
if (nrEnabled_ && nrHandle_ != nullptr) {
+ tracker_.transition(list,nrInput_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const float down[8]={uintBits(workW_),uintBits(workH_),uintBits(nrW_),uintBits(nrH_),0,0,0,0};
+ downsamplePass_.bind(list,down,gpuHandleOf(downsamplePass_,0).ptr,gpuHandleOf(downsamplePass_,1).ptr);
+ list->Dispatch((nrW_+15)/16,(nrH_+15)/16,1);tracker_.uavBarrier(list,nrInput_.Get());tracker_.transition(list,nrInput_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(list, proxyTex_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const float constants[8] = { 1.0f, 1.0f, 1.0f, 0.0f,
- uintBits(workW_), uintBits(workH_), 0.0f, 0.0f };
+ uintBits(nrW_), uintBits(nrH_), 0.0f, 0.0f };
encPass_.bind(list, constants, gpuHandleOf(encPass_, 0).ptr, gpuHandleOf(encPass_, 1).ptr);
- list->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
+ list->Dispatch((nrW_ + 15) / 16, (nrH_ + 15) / 16, 1);
tracker_.uavBarrier(list, proxyTex_.Get());
tracker_.transition(list, proxyTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
if (desc_.stageMark) desc_.stageMark("encode");
// 4b. NR evaluate on a FRESH list (snippet constraint).
if (!ring_.submitAndSignal(slot)) { veyra::log::error("graph", "submit before nr"); return false; }
- slot = nextListSlot_++ % ring_.slotCount();
- ID3D12GraphicsCommandList* nlist = ring_.acquire(slot, st);
+ ID3D12GraphicsCommandList* nlist = ring_.acquireNext(slot, st);
if (nlist == nullptr) { veyra::log::error("graph", "acquire nr list"); return false; }
{
namespace p = ngx::dlssnr;
ngx::ParameterBlock pb(ngxParams_);
pb.setD3D12Resource(p::kColor, proxyTex_.Get());
pb.setD3D12Resource(p::kOutput, neuralTex_.Get());
- pb.setD3D12Resource(p::kMVec, haveFlow ? flowTex_.Get() : nrZeroMotion_.Get());
+ pb.setD3D12Resource(p::kMVec, haveFlow ? nrFlow_.Get() : nrZeroMotion_.Get());
pb.setD3D12Resource(p::kDepth, nrZeroDepth_.Get());
- pb.setU32(p::kColorSubrectWidth, workW_); pb.setU32(p::kColorSubrectHeight, workH_);
- pb.setU32(p::kOutputSubrectWidth, workW_); pb.setU32(p::kOutputSubrectHeight, workH_);
- pb.setU32(p::kMVecSubrectWidth, workW_); pb.setU32(p::kMVecSubrectHeight, workH_);
- pb.setU32(p::kDepthSubrectWidth, workW_); pb.setU32(p::kDepthSubrectHeight, workH_);
+ pb.setU32(p::kColorSubrectWidth, nrW_); pb.setU32(p::kColorSubrectHeight, nrH_);
+ pb.setU32(p::kOutputSubrectWidth, nrW_); pb.setU32(p::kOutputSubrectHeight, nrH_);
+ pb.setU32(p::kMVecSubrectWidth, nrW_); pb.setU32(p::kMVecSubrectHeight, nrH_);
+ pb.setU32(p::kDepthSubrectWidth, nrW_); pb.setU32(p::kDepthSubrectHeight, nrH_);
pb.setF32(p::kMVecScaleX, 1.0f); pb.setF32(p::kMVecScaleY, 1.0f);
pb.setI32(p::kDepthInverted, 1);
pb.setI32(p::kIndicatorInvertX, 0);
pb.setI32(p::kIndicatorInvertY, 0);
pb.setI32(p::kEnabled, 1);
pb.setI32(p::kReset, reset ? 1 : 0);
- pb.setI32(p::kStyle, 0);
- pb.setF32(p::kIntensity, 1.0f);
- pb.setF32(p::kLocalToneStrength, 1.0f);
- pb.setF32(p::kLocalStructureStrength, 1.0f);
- pb.setF32(p::kSkinStructureStrength, -1.0f);
- pb.setI32(p::kUseAutoMask, 0);
- pb.setI32(p::kUICorrection, 0);
+ pb.setI32(p::kStyle, desc_.model.style);
+ pb.setF32(p::kIntensity, desc_.model.intensity);
+ pb.setF32(p::kLocalToneStrength, desc_.model.tone);
+ pb.setF32(p::kLocalStructureStrength, desc_.model.structure);
+ pb.setF32(p::kSkinStructureStrength, desc_.model.skin);
+ pb.setI32(p::kUseAutoMask, desc_.model.autoMask);
+ pb.setI32(p::kUICorrection, desc_.model.uiCorrection);
+ static bool injectedFailureConsumed=false;
+ if(!injectedFailureConsumed&&desc_.model.style==2&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_STYLE2",nullptr,0)){
+ injectedFailureConsumed=true;veyra::log::error("settings-test","injected NR execution rejection before NGX; rollback exercise, not a hardware failure");return false;
+ }
+ gpuTimer_.mark(nlist,GpuStage::Nr);
uint64_t er = 0; uint32_t es = 0;
if (!nrAdapter_->snippetEvaluateFeature(nlist, nrHandle_, ngxParams_, er, es) ||
er != static_cast<uint64_t>(NVSDK_NGX_Result_Success)) {
- veyra::log::error("graph", std::format("NR evaluate failed 0x{:X} seh={}", er, es));
+ diagnostic.stage="NR Evaluate";diagnostic.ngx=er;diagnostic.seh=es;Logger::diagnosticContext(diagnostic);veyra::log::error("graph", std::format("NR evaluate failed 0x{:X} seh={}", er, es));
return false;
}
+ gpuTimer_.mark(nlist,GpuStage::Nr,true);
++metrics_.nrEvaluateCount;
if(haveFlow)++metrics_.nrMotionFrames;
tracker_.uavBarrier(nlist, neuralTex_.Get());
@@ -819,15 +908,15 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if(GetEnvironmentVariableW(L"VEYRA_PROFILE_SPLIT",profileFlag,2)&&profileFlag[0]==L'1'){
ring_.tag(slot,"nr-only");
if(!ring_.submitAndSignal(slot))return false;
- slot=nextListSlot_++%ring_.slotCount();nlist=ring_.acquire(slot,st);if(!nlist)return false;
+ nlist=ring_.acquireNext(slot,st);if(!nlist)return false;
ring_.tag(slot,"decode-output-fg");
}
// 4c. Parity decode.
tracker_.transition(nlist, finalRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const float constants[8] = { 1.0f, 1.0f, 1.0f, 0.0f,
- uintBits(workW_), uintBits(workH_), 0.0f, 0.0f };
+ uintBits(nrW_), uintBits(nrH_), 0.0f, 0.0f };
decPass_.bind(nlist, constants, gpuHandleOf(decPass_, 0).ptr, gpuHandleOf(decPass_, 3).ptr);
- nlist->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
+ nlist->Dispatch((nrW_ + 15) / 16, (nrH_ + 15) / 16, 1);
tracker_.uavBarrier(nlist, finalRgba_.Get());
tracker_.transition(nlist, finalRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
}
@@ -835,11 +924,19 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
if (desc_.stageMark) desc_.stageMark("nr");
+ if(nrEnabled_&&nrHandle_){
+ gpuTimer_.mark(list,GpuStage::Residual);
+ tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const auto& r=desc_.residual;const float c[8]={r.total,r.darken,r.brighten,r.color,r.luminance,0,0,0};
+ residualPass_.bind(list,c,gpuHandleOf(residualPass_,0).ptr,gpuHandleOf(residualPass_,3).ptr);
+ list->Dispatch((workW_+15)/16,(workH_+15)/16,1);tracker_.uavBarrier(list,residualRgba_.Get());tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);gpuTimer_.mark(list,GpuStage::Residual,true);
+ }
+
// 5. Working frame -> SDR RGBA8 videoFrame[parity] + NVOF chain.
{
const UINT srcSlot = 2;
const UINT uavSlot = 3 + parity;
- tracker_.transition(list, (nrEnabled_ && nrHandle_ != nullptr) ? finalRgba_.Get() : workRgba_.Get(),
+ tracker_.transition(list, (nrEnabled_ && nrHandle_ != nullptr) ? residualRgba_.Get() : workRgba_.Get(),
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(list, videoFrame_[parity].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const float constants[8] = {
@@ -851,35 +948,61 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
tracker_.transition(list, videoFrame_[parity].Get(), D3D12_RESOURCE_STATE_COMMON);
}
+ if(!fgEnabled_)gpuTimer_.resolve(list);
if (!ring_.submitAndSignal(slot)) return false;
+ if(!fgEnabled_)gpuTimer_.submitted(ring_.lastSignaledValue());
out.videoFenceValue = ring_.lastSignaledValue();
// FG reads enhanced SDR color, not the pre-NR guidance input.
if (fgEnabled_ && fgBackend_ && fgBackend_->created()) {
- slot=nextListSlot_++%ring_.slotCount();
- auto* flist=ring_.acquire(slot,st); if(!flist)return false;
- auto* motion=haveFlow?flowTex_.Get():nrZeroMotion_.Get();
+ for(uint32_t sub=1;sub<desc_.fgMultiplier;++sub){
+ const uint32_t generatedSlot=parity+(sub-1)*2;
+ auto* flist=ring_.acquireNext(slot,st); if(!flist)return false;
+ auto* motion=haveFlow?baseFlow_.Get():nrZeroMotion_.Get();
tracker_.transition(flist,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(flist,motion,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(flist,depthTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- tracker_.transition(flist,genFrame_[parity].Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ tracker_.transition(flist,genFrame_[generatedSlot].Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ // One status resource for the whole input-frame pair, just like the
+ // unchanged input parameters. Later MFG calls may retain its value.
+ if(sub==1){
+ tracker_.transition(flist,fgDisable_[parity].Get(),D3D12_RESOURCE_STATE_COPY_DEST);
+ flist->CopyBufferRegion(fgDisable_[parity].Get(),0,fgDisableInit_.Get(),0,4);
+ }
+ tracker_.transition(flist,fgDisable_[parity].Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
ngx::DlssFgBackend::EvalDesc fe{};
fe.backbuffer=videoFrame_[parity].Get(); fe.depth=depthTex_.Get(); fe.mvecs=motion;
- fe.outputInterpolated=genFrame_[parity].Get(); fe.reset=reset||!prevValid_;
- fe.frameId=realFrameIndex_;
+ fe.outputInterpolated=genFrame_[generatedSlot].Get(); fe.reset=reset||!prevValid_;
+ fe.outputDisableInterpolation=fgDisable_[parity].Get();
+ fe.multiFrameCount=desc_.fgMultiplier-1;fe.multiFrameIndex=sub;
+ fe.frameId=realFrameIndex_+1;
// FG consumer adapter: current->previous pixel flow -> normalized reverse flow.
fe.mvecScaleX=haveFlow?-1.0f/static_cast<float>(workW_):1.0f;
fe.mvecScaleY=haveFlow?-1.0f/static_cast<float>(workH_):1.0f;
+ if(sub==1)gpuTimer_.mark(flist,GpuStage::FgBatch);
+ const auto timingStage=static_cast<GpuStage>(unsigned(GpuStage::Fg1)+sub-1);gpuTimer_.mark(flist,timingStage);
if(!fgBackend_->evaluate(flist,ngxParams_,fe,st))return false;
- tracker_.uavBarrier(flist,genFrame_[parity].Get());
+ gpuTimer_.mark(flist,timingStage,true);if(sub==desc_.fgMultiplier-1)gpuTimer_.mark(flist,GpuStage::FgBatch,true);
+ tracker_.uavBarrier(flist,genFrame_[generatedSlot].Get());
+ tracker_.uavBarrier(flist,fgDisable_[parity].Get());
+ tracker_.transition(flist,fgDisable_[parity].Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);
+ flist->CopyBufferRegion(fgDisableReadback_[generatedSlot].Get(),0,fgDisable_[parity].Get(),0,4);
tracker_.transition(flist,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);
- tracker_.transition(flist,genFrame_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);
+ tracker_.transition(flist,genFrame_[generatedSlot].Get(),D3D12_RESOURCE_STATE_COMMON);
tracker_.transition(flist,depthTex_.Get(),D3D12_RESOURCE_STATE_COMMON);
+ if(sub==desc_.fgMultiplier-1)gpuTimer_.resolve(flist);
if(!ring_.submitAndSignal(slot))return false;
+ if(sub==desc_.fgMultiplier-1)gpuTimer_.submitted(ring_.lastSignaledValue());
out.hasGenerated=prevValid_&&!reset;
out.genSlot=parity; out.genFenceValue=ring_.lastSignaledValue();
out.generatedPtsMs=(prevPtsMs_+ptsMs)*0.5;
- if(out.hasGenerated)++metrics_.fgGeneratedFrames;
+ if(out.hasGenerated){
+ ++metrics_.fgSubmittedCandidates;
+ BatchFrame f;f.identity=out.batch.identity;f.kind=FrameKind::Generated;f.validity=GenerationValidity::Pending;f.subframe=sub;
+ f.pts100ns=FrameBatch::interpolate(out.batch.a100ns,out.batch.b100ns,sub,desc_.fgMultiplier);
+ f.lease=std::make_shared<FrameLease>();f.lease->texture=genFrame_[generatedSlot];f.lease->slot=generatedSlot;f.lease->readyFence=out.genFenceValue;generatedLeases_[generatedSlot]=f.lease;out.batch.append(std::move(f));
+ }
+ }
}
uploadFences_[parity]=ring_.lastSignaledValue();
@@ -888,19 +1011,52 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
++realFrameIndex_;
out.realFrameIndex = realFrameIndex_;
out.videoSlot = parity;
+ BatchFrame real;real.identity=out.batch.identity;real.pts100ns=out.batch.b100ns;real.lease=std::make_shared<FrameLease>();real.lease->texture=videoFrame_[parity];real.lease->sourceReference=sourceReferences_[parity];real.lease->baseReference=baseReferences_[parity];real.lease->slot=parity;real.lease->readyFence=out.videoFenceValue;realLeases_[parity]=real.lease;out.batch.append(std::move(real));
+ veyra::log::info("frame-batch",std::format("batch={} epoch={} revision={} source={} a={} b={} count={} realSlot={} realFence={} genSlot={} genFence={}",out.batch.batchId,epoch_,out.batch.identity.settingsRevision,out.batch.identity.sourceFrameId,out.batch.a100ns,out.batch.b100ns,out.batch.count,parity,out.videoFenceValue,out.genSlot,out.genFenceValue));
return true;
}
+bool EnhanceGraph::resolveGeneration(FrameOutputs& out)
+{
+ if(!out.hasGenerated)return true;
+ if(context_.fence()->GetCompletedValue()<out.genFenceValue)return false;
+ bool anyValid=false;
+ for(uint32_t i=0;i<out.batch.count;++i){
+ auto& frame=out.batch.frames[i];if(frame.kind!=FrameKind::Generated)continue;
+ if(frame.validity!=GenerationValidity::Pending){anyValid|=frame.validity==GenerationValidity::Valid;continue;}
+ void* data=nullptr;D3D12_RANGE range{0,4};
+ HRESULT hr=fgDisableReadback_[frame.lease->slot]->Map(0,&range,&data);
+ if(FAILED(hr)){frame.validity=GenerationValidity::Failed;out.hasGenerated=false;veyra::log::error("fg-status",std::format("Map hr=0x{:X}",unsigned(hr)));return true;}
+ const uint32_t disabled=*static_cast<uint8_t*>(data); // SDK writes the first byte only
+ D3D12_RANGE written{0,0};fgDisableReadback_[frame.lease->slot]->Unmap(0,&written);
+ const bool rejected=disabled||out.contentDuplicate;
+ frame.validity=rejected?GenerationValidity::Disabled:GenerationValidity::Valid;
+ anyValid|=!rejected;if(rejected)++metrics_.fgDisabledFrames;else ++metrics_.fgGeneratedFrames;
+ veyra::log::info("fg-status",std::format("batch={} frame={} epoch={} revision={} subframe={} fence={} disable={} valid={}",out.batch.batchId,out.realFrameIndex,out.batch.identity.epoch,out.batch.identity.settingsRevision,frame.subframe,frame.lease->readyFence,disabled,!rejected));
+ }
+ out.hasGenerated=anyValid;return true;
+}
+
+bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){
+ if(!s.validate().empty()||(s.multiplier>1&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;
+ desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.settingsRevision=s.revision;
+ desc_.fgMultiplier=std::max(2u,s.multiplier);desc_.enableNvofStandalone=s.nr;nvofStandalone_=s.nr;
+ setNrEnabled(s.nr);setFgEnabled(s.multiplier>1);
+ veyra::log::info("settings",std::format("requested revision={} intensity={} tone={} structure={} skin={} style={} autoMask={} UI={} residual={}/{}/{}/{}/{} multiplier={}",s.revision,s.model.intensity,s.model.tone,s.model.structure,s.model.skin,s.model.style,s.model.autoMask,s.model.uiCorrection,s.residual.total,s.residual.darken,s.residual.brighten,s.residual.color,s.residual.luminance,s.multiplier));
+ return true;
+}
void EnhanceGraph::setNrEnabled(bool on)
{
nrEnabled_ = on && nrHandle_ != nullptr;
// Refresh the section-5 blit SRV exactly as the probe did at runtime
// (direct write into the visible heap - proven safe for this refresh).
makeSrv(context_.device(),
- nrEnabled_ ? finalRgba_.Get() : workRgba_.Get(),
+ nrEnabled_ ? residualRgba_.Get() : workRgba_.Get(),
DXGI_FORMAT_R16G16B16A16_FLOAT, cpuHandleOf(blitPass_, 2));
}
+ID3D12Fence* EnhanceGraph::contextFence()const{return context_.fence();}
+uint32_t EnhanceGraph::actualFlowPerf()const{return nvof_?nvof_->caps().actualPerfLevel:0;}
bool EnhanceGraph::fgCreated() const
{
return fgBackend_ && fgBackend_->created();
@@ -928,7 +1084,7 @@ ID3D12Resource* EnhanceGraph::videoFrameResource(uint32_t slot) const
ID3D12Resource* EnhanceGraph::generatedFrameResource(uint32_t slot) const
{
- return slot < 2 ? genFrame_[slot].Get() : nullptr;
+ return slot < 6 ? genFrame_[slot].Get() : nullptr;
}
// ---------------------------------------------------------------------------
@@ -939,7 +1095,7 @@ ID3D12Resource* EnhanceGraph::generatedFrameResource(uint32_t slot) const
void EnhanceGraph::shutdown()
{
if (!initialized_ && !nrAdapter_ && !nvof_ && !srcRgba_) return;
- (void)ring_.drainQueue();
+ (void)ring_.drainQueue();(void)ring_.discardRecording();
Status st = Status::Ok;
if (nv12Ctx_ != nullptr) { sws_freeContext(nv12Ctx_); nv12Ctx_ = nullptr; }
@@ -980,6 +1136,9 @@ void EnhanceGraph::shutdown()
// Staged explicit release (scope-end destructors then have nothing left).
decPass_ = ComputePass{};
+ downsamplePass_={};residualPass_={};flowAdaptPass_={};
+ nrInput_.Reset();residualRgba_.Reset();nrFlow_.Reset();baseFlow_.Reset();
+ for(unsigned i=0;i<6;++i){fgDisable_[i].Reset();fgDisableReadback_[i].Reset();generatedLeases_[i].reset();genFrame_[i].Reset();}for(auto& lease:realLeases_)lease.reset();fgDisableInit_.Reset();
encPass_ = ComputePass{};
blitPass_ = ComputePass{};
yuvPass_ = ComputePass{};
@@ -996,7 +1155,7 @@ void EnhanceGraph::shutdown()
finalRgba_.Reset();
neuralTex_.Reset();
proxyTex_.Reset();
- workRgba_.Reset();
+ for(auto& r:sourceReferences_)r.Reset();for(auto& r:baseReferences_)r.Reset();workRgba_.Reset();
srcRgba_.Reset();
chromaTex_.Reset();
lumaTex_.Reset();
@@ -1013,7 +1172,7 @@ void EnhanceGraph::shutdown()
srBackend_.reset();
nrAdapter_.reset();
coreHost_.reset();
- initialized_ = false;
+ gpuTimer_.close();initialized_ = false;
veyra::log::info("graph", "shutdown complete (ordered)");
(void)st;
}
diff --git a/src/sink/NvencD3D12Encoder.cpp b/src/sink/NvencD3D12Encoder.cpp
index 869f4ec4..5bac7105 100644
--- a/src/sink/NvencD3D12Encoder.cpp
+++ b/src/sink/NvencD3D12Encoder.cpp
@@ -53,9 +53,9 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
if(!p.check(p.api.nvEncGetSequenceParams(p.encoder,&seq),"GetSequenceParams"))return false;p.sequence.resize(size);
if(FAILED(ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&p.fence))))return false;p.event=CreateEventW(nullptr,FALSE,FALSE,nullptr);if(!p.event)return false;
p.y=makeTexture(ctx.device(),p.w,p.h,DXGI_FORMAT_R8_UNORM,true);p.uv=makeTexture(ctx.device(),p.w/2,p.h/2,DXGI_FORMAT_R8G8_UNORM,true);if(!p.y||!p.uv)return false;
- std::vector<uint8_t> cs;if(!p.convert.loadShader("RgbToNv12.dxil",cs)||!p.convert.create(ctx.device(),cs,6,1,2))return false;
- for(unsigned i=0;i<4;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),DXGI_FORMAT_R8G8B8A8_UNORM,cpuHandleOf(p.convert,i));
- makeUav(ctx.device(),p.y.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(p.convert,4));makeUav(ctx.device(),p.uv.Get(),DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(p.convert,5));
+ std::vector<uint8_t> cs;if(!p.convert.loadShader("RgbToNv12.dxil",cs)||!p.convert.create(ctx.device(),cs,10,1,2))return false;
+ for(unsigned i=0;i<8;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),DXGI_FORMAT_R8G8B8A8_UNORM,cpuHandleOf(p.convert,i));
+ makeUav(ctx.device(),p.y.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(p.convert,8));makeUav(ctx.device(),p.uv.Get(),DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(p.convert,9));
for(auto& s:p.slots){
s.input=makeTexture(ctx.device(),p.w,p.h,DXGI_FORMAT_NV12,false);if(!s.input)return false;
D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=(uint64_t(p.w)*p.h*4+4095)&~4095ull;bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
@@ -69,10 +69,10 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
}return true;
}
bool NvencD3D12Encoder::encode(unsigned frameSlot,bool generated,int64_t pts){auto& p=*p_;auto& s=p.slots[p.submitted%4];if(!p.drain(s))return false;
- Status st=Status::Ok;const auto slot=p.ring->slotCount()-1;auto* list=p.ring->acquire(slot,st);if(!list)return false;
+ Status st=Status::Ok;uint32_t slot=0;auto* list=p.ring->acquireNext(slot,st);if(!list)return false;
auto* color=generated?p.graph->generatedFrameResource(frameSlot):p.graph->videoFrameResource(frameSlot);
p.states.transition(list,color,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);p.states.transition(list,p.y.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);p.states.transition(list,p.uv.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- const float dims[8]={std::bit_cast<float>(p.w),std::bit_cast<float>(p.h),0,0,0,0,0,0};p.convert.bind(list,dims,gpuHandleOf(p.convert,frameSlot+(generated?2:0)).ptr,gpuHandleOf(p.convert,4).ptr);list->Dispatch((p.w+15)/16,(p.h+15)/16,1);
+ const float dims[8]={std::bit_cast<float>(p.w),std::bit_cast<float>(p.h),0,0,0,0,0,0};p.convert.bind(list,dims,gpuHandleOf(p.convert,frameSlot+(generated?2:0)).ptr,gpuHandleOf(p.convert,8).ptr);list->Dispatch((p.w+15)/16,(p.h+15)/16,1);
p.states.uavBarrier(list,p.y.Get());p.states.uavBarrier(list,p.uv.Get());p.states.transition(list,p.y.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);p.states.transition(list,p.uv.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);p.states.transition(list,s.input.Get(),D3D12_RESOURCE_STATE_COPY_DEST);
for(unsigned plane=0;plane<2;++plane){D3D12_TEXTURE_COPY_LOCATION a{},b{};a.pResource=plane?p.uv.Get():p.y.Get();a.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.pResource=s.input.Get();b.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.SubresourceIndex=plane;list->CopyTextureRegion(&b,0,0,0,&a,nullptr);}
p.states.transition(list,s.input.Get(),D3D12_RESOURCE_STATE_COMMON);p.states.transition(list,color,D3D12_RESOURCE_STATE_COMMON);if(!p.ring->submitAndSignal(slot))return false;
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index c4551176..e9caf9f5 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -9,6 +9,7 @@
#include <atomic>
#include <format>
#include <chrono>
+#include <cmath>
extern "C" {
#include <libavutil/frame.h>
#include <libavutil/pixfmt.h>
@@ -28,12 +29,40 @@ bool bind(unsigned index,bool audio,ComPtr<IBaseFilter>& filter){auto list=monik
bool configuration(unsigned device,ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c){return SUCCEEDED(CoCreateInstance(CLSID_FilterGraph,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&g)))&&SUCCEEDED(CoCreateInstance(CLSID_CaptureGraphBuilder2,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&b)))&&SUCCEEDED(b->SetFiltergraph(g.Get()))&&bind(device,false,f)&&SUCCEEDED(g->AddFilter(f.Get(),L"Capture card"))&&SUCCEEDED(b->FindInterface(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,f.Get(),IID_PPV_ARGS(&c)));}
}
struct CaptureCardSource::Impl:ISampleGrabberCB {
- std::atomic<ULONG> refs{1};std::mutex mutex;std::condition_variable wake;ComPtr<IMediaSample> pending;double pendingTime=0;uint64_t dropped=0,lastDrop=0,sequence=0;
+ using Clock=std::chrono::steady_clock;
+ std::atomic<ULONG> refs{1};std::mutex mutex;std::condition_variable wake;
+ // One pending frame plus one reader-owned frame, never an IMediaSample
+ // reference. Holding the producer's sole RGB32 sample starves its allocator.
+ AVFrame* frame=nullptr;AVFrame* pendingFrame=nullptr;bool pending=false,callbackError=false,configured=false;
+ double pendingTime=0,lastPts=0,readAgeMs=0;bool pendingDiscontinuity=false;
+ uint64_t received=0,dropped=0,lastDrop=0,sequence=0;
+ 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;
- SourceInfo info;AVFrame* frame=nullptr;bool bottomUp=true;unsigned stride=0;std::chrono::steady_clock::time_point lastFrame;
+ SourceInfo info;bool bottomUp=true;unsigned stride=0;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;}
- HRESULT STDMETHODCALLTYPE SampleCB(double time,IMediaSample* sample)override{{std::lock_guard lock(mutex);if(pending)++dropped;pending=sample;pendingTime=time;}wake.notify_one();return S_OK;}
+ HRESULT STDMETHODCALLTYPE SampleCB(double time,IMediaSample* sample)override{
+ const auto arrival=Clock::now();BYTE* data=nullptr;
+ const bool valid=sample&&std::isfinite(time)&&SUCCEEDED(sample->GetPointer(&data))&&data&&
+ sample->GetActualDataLength()>=LONG(size_t(stride)*info.height);
+ {
+ std::lock_guard lock(mutex);
+ if(!valid||!pendingFrame){callbackError=true;}
+ else {
+ // Copy directly into our bounded mailbox; read() swaps frames
+ // under this lock, so the frame consumed by the GPU is untouched.
+ for(unsigned y=0;y<info.height;++y)
+ memcpy(pendingFrame->data[0]+size_t(y)*pendingFrame->linesize[0],
+ data+size_t(bottomUp?info.height-1-y:y)*stride,stride);
+ if(pending)++dropped;
+ pending=true;pendingTime=time;pendingArrival=arrival;
+ pendingDiscontinuity=sample->IsDiscontinuity()==S_OK;
+ if(!received)firstArrival=arrival;
+ ++received;latestArrival=arrival;
+ }
+ }
+ wake.notify_one();return S_OK;
+ }
HRESULT STDMETHODCALLTYPE BufferCB(double,BYTE*,long)override{return E_NOTIMPL;}
};
CaptureCardSource::CaptureCardSource():p_(std::make_unique<Impl>()){}
@@ -42,7 +71,8 @@ std::vector<std::wstring> CaptureCardSource::devices(bool audio){std::vector<std
std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;std::vector<CaptureFormat> out;if(!configuration(device,g,b,f,c))return out;int count=0,size=0;if(FAILED(c->GetNumberOfCapabilities(&count,&size))||size<1||size>65536)return out;std::vector<BYTE> caps(size);for(int i=0;i<count;++i){AM_MEDIA_TYPE* t=nullptr;if(FAILED(c->GetStreamCaps(i,&t,caps.data())))continue;BITMAPINFOHEADER* bm=nullptr;REFERENCE_TIME duration=0;if(t->formattype==FORMAT_VideoInfo&&t->cbFormat>=sizeof(VIDEOINFOHEADER)){auto* vi=reinterpret_cast<VIDEOINFOHEADER*>(t->pbFormat);bm=&vi->bmiHeader;duration=vi->AvgTimePerFrame;}else if(t->formattype==FORMAT_VideoInfo2&&t->cbFormat>=sizeof(VIDEOINFOHEADER2)){auto* vi=reinterpret_cast<VIDEOINFOHEADER2*>(t->pbFormat);bm=&vi->bmiHeader;duration=vi->AvgTimePerFrame;}
if(bm&&bm->biWidth>0&&bm->biWidth<=3840&&abs(bm->biHeight)<=2160&&duration>0){unsigned w=bm->biWidth,h=abs(bm->biHeight);double fps=1e7/duration;if((w==1920&&h==1080||w==3840&&h==2160)&&fps>=29&&fps<=61)out.push_back({i,w,h,fps,std::format(L"{} x {} @ {:.2f} fps [format {}]",w,h,fps,i)});}freeType(t);}return out;}
const SourceInfo& CaptureCardSource::info()const{return p_->info;}
-bool CaptureCardSource::open(const SourceOpenDesc& desc){close();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;
+bool CaptureCardSource::open(const SourceOpenDesc& desc){return configure(desc)&&start();}
+bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();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;
int count=0,size=0;if(FAILED(p.config->GetNumberOfCapabilities(&count,&size))||format<0||format>=count||size<=0||size>65536)return false;std::vector<BYTE> caps(size);AM_MEDIA_TYPE* native=nullptr;if(FAILED(p.config->GetStreamCaps(format,&native,caps.data())))return false;HRESULT hr=p.config->SetFormat(native);freeType(native);if(FAILED(hr))return false;
if(FAILED(CoCreateInstance(SampleGrabberClass,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.grabFilter)))||FAILED(p.grabFilter.As(&p.grab))||FAILED(p.graph->AddFilter(p.grabFilter.Get(),L"Latest frame mailbox")))return false;
@@ -54,15 +84,51 @@ bool CaptureCardSource::open(const SourceOpenDesc& desc){close();auto& p=*p_;uns
p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=vi.bmiHeader.biWidth;p.info.height=abs(vi.bmiHeader.biHeight);p.info.averageFps=vi.AvgTimePerFrame>0?1e7/vi.AvgTimePerFrame:0;p.info.duration=pipeline::Rational::unknown();p.bottomUp=vi.bmiHeader.biHeight>0;p.stride=p.info.width*4;
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(FAILED(p.graph.As(&p.control))||FAILED(p.graph.As(&p.events))||FAILED(p.grab->SetBufferSamples(FALSE))||FAILED(p.grab->SetCallback(&p,0)))return false;
- p.frame=av_frame_alloc();p.frame->format=AV_PIX_FMT_BGRA;p.frame->width=p.info.width;p.frame->height=p.info.height;p.frame->color_range=AVCOL_RANGE_JPEG;if(av_frame_get_buffer(p.frame,32)<0)return false;
- p.lastFrame=std::chrono::steady_clock::now();hr=p.control->Run();veyra::log::info("capture",std::format("Run hr=0x{:X} actual={}x{} fps={:.3f} mailbox=1 audioDevice={}",unsigned(hr),p.info.width,p.info.height,p.info.averageFps,audio));p.info.opened=SUCCEEDED(hr);return p.info.opened;
+ for(auto** f:{&p.frame,&p.pendingFrame}){
+ *f=av_frame_alloc();if(!*f)return false;
+ (*f)->format=AV_PIX_FMT_BGRA;(*f)->width=p.info.width;(*f)->height=p.info.height;(*f)->color_range=AVCOL_RANGE_JPEG;
+ if(av_frame_get_buffer(*f,32)<0)return false;
+ }
+ p.configured=true;
+ // Log the upstream type after DirectShow has finished negotiation. The
+ // RGB32 output's nominal FPS alone is not proof of actual callback cadence.
+ AM_MEDIA_TYPE* actual=nullptr;const auto formatHr=p.config->GetFormat(&actual);
+ veyra::log::info("capture",std::format("configured {}x{} nominalFps={:.3f} upstreamSubtype=0x{:08X} formatHr=0x{:X} mailbox=1 ownedBuffers=2 deferredRun=1 audioDevice={}",
+ p.info.width,p.info.height,p.info.averageFps,actual?unsigned(actual->subtype.Data1):0,unsigned(formatHr),audio));freeType(actual);
+ return true;
+}
+bool CaptureCardSource::start(){
+ auto& p=*p_;if(p.info.opened)return true;if(!p.configured||!p.control)return false;
+ 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;
+}
+CaptureMetrics CaptureCardSource::metrics()const{
+ auto& p=*p_;std::lock_guard lock(p.mutex);CaptureMetrics m;
+ m.received=p.received;m.delivered=p.sequence;m.dropped=p.dropped;m.readAgeMs=p.readAgeMs;
+ if(p.received>1){const double elapsed=std::chrono::duration<double>(p.latestArrival-p.firstArrival).count();if(elapsed>0)m.callbackFps=(p.received-1)/elapsed;}
+ if(p.sequence)m.frameAgeMs=std::chrono::duration<double,std::milli>(Impl::Clock::now()-p.readArrival).count();return m;
}
SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFrame** frame){auto& p=*p_;*frame=nullptr;if(!p.info.opened)return SourceReadStatus::Error;
long code=0;LONG_PTR a=0,b=0;while(p.events&&p.events->GetEvent(&code,&a,&b,0)==S_OK){p.events->FreeEventParams(code,a,b);if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)return SourceReadStatus::Error;}
- ComPtr<IMediaSample> sample;double time=0;bool drop=false;{std::unique_lock lock(p.mutex);p.wake.wait_for(lock,std::chrono::milliseconds(30),[&]{return p.pending!=nullptr;});if(!p.pending)return std::chrono::steady_clock::now()-p.lastFrame>std::chrono::seconds(3)?SourceReadStatus::Error:SourceReadStatus::Waiting;sample.Swap(p.pending);time=p.pendingTime;drop=p.dropped!=p.lastDrop;p.lastDrop=p.dropped;}
- BYTE* data=nullptr;if(FAILED(sample->GetPointer(&data))||sample->GetActualDataLength()<LONG(p.stride*p.info.height))return SourceReadStatus::Error;
- for(unsigned y=0;y<p.info.height;++y)memcpy(p.frame->data[0]+size_t(y)*p.frame->linesize[0],data+size_t(p.bottomUp?p.info.height-1-y:y)*p.stride,p.stride);
- p.frame->pts=static_cast<int64_t>(time*10000000);packet={};packet.pts={p.frame->pts,10000000};packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=++p.sequence;packet.flags=drop?static_cast<uint32_t>(pipeline::FrameFlagBits::Drop):0;packet.sourceEpoch=1;*frame=p.frame;p.lastFrame=std::chrono::steady_clock::now();return SourceReadStatus::Frame;
+ double time=0;uint32_t flags=0;uint64_t sequence=0;
+ {
+ std::unique_lock lock(p.mutex);p.wake.wait_for(lock,std::chrono::milliseconds(30),[&]{return p.pending||p.callbackError;});
+ if(p.callbackError)return SourceReadStatus::Error;
+ if(!p.pending)return Impl::Clock::now()-p.lastFrame>std::chrono::seconds(3)?SourceReadStatus::Error:SourceReadStatus::Waiting;
+ std::swap(p.frame,p.pendingFrame);p.pending=false;time=p.pendingTime;p.readArrival=p.pendingArrival;
+ p.readAgeMs=std::chrono::duration<double,std::milli>(Impl::Clock::now()-p.readArrival).count();
+ if(!p.sequence)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Open);
+ if(p.dropped!=p.lastDrop)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Drop);
+ const double maxGap=p.info.averageFps>0?2.5/p.info.averageFps:0.1;
+ if(p.pendingDiscontinuity||(p.sequence&&(time<=p.lastPts||time-p.lastPts>maxGap)))flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);
+ p.lastDrop=p.dropped;p.lastPts=time;sequence=++p.sequence;
+ }
+ p.frame->pts=static_cast<int64_t>(time*10000000);packet={};packet.pts={p.frame->pts,10000000};packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;*frame=p.frame;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;
+}
+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();
+ 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;
}
-void CaptureCardSource::close()noexcept{auto& p=*p_;if(p.control)p.control->Stop();if(p.grab)p.grab->SetCallback(nullptr,0);{std::lock_guard lock(p.mutex);p.pending.Reset();}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();av_frame_free(&p.frame);p.info={};p.sequence=p.dropped=p.lastDrop=0;}
}
diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cpp
index 86c1b53c..3328d683 100644
--- a/src/source/MediaFileSource.cpp
+++ b/src/source/MediaFileSource.cpp
@@ -137,6 +137,9 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)
info_.duration = pipeline::Rational::unknown();
}
info_.averageFps = demuxer_.averageFps();
+ info_.nominalRateNum = demuxer_.nominalRateNum();
+ info_.nominalRateDen = demuxer_.nominalRateDen();
+ info_.timestampQuantum = demuxer_.videoTimeBaseDen() > 0 ? double(demuxer_.videoTimeBaseNum()) / demuxer_.videoTimeBaseDen() : 0;
info_.hardwareDecodeActive = decoder_.usingD3D12Frames();
info_.color = parseColor(params);
diff --git a/tests/integration/CaptureSourceTests.cpp b/tests/integration/CaptureSourceTests.cpp
new file mode 100644
index 00000000..245f18d6
--- /dev/null
+++ b/tests/integration/CaptureSourceTests.cpp
@@ -0,0 +1,41 @@
+// Optional real-device integration test. Saves no media; validates the product
+// source's deferred Run, bounded mailbox, and reader-buffer lifetime.
+#include "veyra/source/CaptureCardSource.h"
+#include <windows.h>
+#include <chrono>
+#include <thread>
+#include <cstdio>
+#include <vector>
+#include <cstring>
+extern "C" {
+#include <libavutil/frame.h>
+}
+int wmain(int argc,wchar_t** argv){
+ if(argc!=2){printf("Specify capture:device:format:audio; real hardware required\n");return 2;}
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ veyra::source::CaptureCardSource source;veyra::source::SourceOpenDesc d;d.path=argv[1];
+ int failures=0;auto check=[&](bool ok,const char* label){printf("%s %s\n",ok?"PASS":"FAIL",label);if(!ok)++failures;};
+ if(!source.configure(d)){printf("FAIL configure\n");return 3;}
+ std::this_thread::sleep_for(std::chrono::milliseconds(150));
+ check(!source.info().opened&&source.metrics().received==0,"configure does not start capture/audio");
+ if(!source.start()){printf("FAIL start\n");return 4;}
+ const AVFrame* frame=nullptr;veyra::pipeline::FramePacket packet;
+ auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(2);
+ auto readFrame=[&](){while(std::chrono::steady_clock::now()<deadline){auto r=source.read(packet,&frame);if(r==veyra::source::SourceReadStatus::Frame)return true;if(r==veyra::source::SourceReadStatus::Error)return false;}return false;};
+ if(!readFrame()){printf("FAIL first frame\n");return 5;}
+ const auto initialPts=packet.pts.toDouble();const auto initialReceived=source.metrics().received;
+ std::vector<unsigned char> row(frame->data[0],frame->data[0]+frame->width*4);
+ std::this_thread::sleep_for(std::chrono::milliseconds(300));
+ auto stalled=source.metrics();
+ check(stalled.received>=initialReceived+3,"callbacks continue while reader retains frame");
+ check(stalled.dropped>=2,"bounded pending frame overwritten while reader stalls");
+ check(memcmp(row.data(),frame->data[0],row.size())==0,"returned frame remains owned and unchanged");
+ deadline=std::chrono::steady_clock::now()+std::chrono::seconds(2);
+ check(readFrame(),"read after consumer stall");
+ auto recovered=source.metrics();
+ check(packet.pts.toDouble()>initialPts+.15,"read skips stale frames rather than draining FIFO");
+ check(veyra::pipeline::hasFrameFlag(packet.flags,veyra::pipeline::FrameFlagBits::Drop),"drop invalidates temporal history");
+ check(recovered.readAgeMs<100,"latest frame callback age below 100ms");
+ printf("received=%llu dropped=%llu callbackFps=%.3f readAgeMs=%.3f\n",recovered.received,recovered.dropped,recovered.callbackFps,recovered.readAgeMs);
+ source.close();CoUninitialize();return failures?1:0;
+}
diff --git a/tests/integration/RepairFgTests.cpp b/tests/integration/RepairFgTests.cpp
new file mode 100644
index 00000000..d445a3f8
--- /dev/null
+++ b/tests/integration/RepairFgTests.cpp
@@ -0,0 +1,57 @@
+// Synthetic pixels only. Diagnostic readback is intentionally outside all
+// player/capture/export paths. The actual product EnhanceGraph is under test.
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/sink/ImageExportSink.h"
+#include <cmath>
+#include <filesystem>
+#include <iostream>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+namespace {
+uint64_t hash(const veyra::sink::RgbaImage& im){uint64_t v=14695981039346656037ull;for(auto b:im.pixels){v^=b;v*=1099511628211ull;}return v;}
+double center(const veyra::sink::RgbaImage& im){double total=0,sum=0;for(unsigned y=300;y<780;++y)for(unsigned x=0;x<im.width;++x){const auto v=im.pixels[(size_t(y)*im.width+x)*4];if(v>160){total+=1;sum+=x;}}return total?sum/total:-1;}
+}
+int main(int argc,char** argv){
+ using namespace veyra;CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;pipeline::EnhanceGraph graph(ctx,ring);
+ Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;bool ok=ctx.initialize(dd,st)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st);
+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=1920;gd.sourceHeight=gd.workHeight=1080;gd.enableNr=false;gd.enableSr=false;gd.enableFg=true;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();
+ const std::string mode=argc>1?argv[1]:"off";
+ gd.enableNr=mode!="off";gd.enableNvofStandalone=gd.enableNr;
+ if(mode=="flowP")gd.flowQuality=engine::FlowQuality::Performance;
+ if(mode=="flowQ")gd.flowQuality=engine::FlowQuality::Quality;
+ if(mode=="sr"){gd.workWidth=3840;gd.workHeight=2160;gd.nrWidth=1920;gd.nrHeight=1080;gd.enableSr=true;}
+ if(mode=="mfg3"||mode=="mfg4"){gd.fgMultiplier=mode=="mfg3"?3:4;gd.enableNr=false;gd.enableNvofStandalone=false;}
+ if(ok)ok=graph.initialize(gd)&&graph.createViews();
+ AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_RGBA;f->width=1920;f->height=1080;f->color_range=AVCOL_RANGE_JPEG;ok=ok&&av_frame_get_buffer(f,32)>=0;
+ sink::RgbaImage previous;unsigned generated=0,valid=0;pipeline::FrameBatch retained;
+ for(unsigned i=0;ok&&i<12;++i){
+ for(int y=0;y<1080;++y)for(int x=0;x<1920;++x){auto* p=f->data[0]+size_t(y)*f->linesize[0]+x*4;const bool square=x>=240+int(i)*16&&x<880+int(i)*16&&y>=220&&y<860;p[0]=p[1]=p[2]=square?240:20;p[3]=255;}
+ pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(f,i*20.0,i==0,out)){ok=false;break;}
+ sink::RgbaImage real,g;if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),real)){ok=false;break;}
+ if(!ring.waitIdle()||!graph.resolveGeneration(out)){ok=false;break;}
+ uint64_t previousGeneratedHash=0;
+ for(uint32_t j=0;j<out.batch.count;++j){const auto& item=out.batch.frames[j];if(item.kind!=pipeline::FrameKind::Generated)continue;
+ ++generated;if(!sink::readRgba8(ctx,ring,graph.generatedFrameResource(item.lease->slot),g)){ok=false;break;}
+ const double t=double(item.subframe)/gd.fgMultiplier;
+ double blendResidual=0;for(size_t k=0;k<g.pixels.size();k+=4)blendResidual+=std::abs(double(g.pixels[k])-(double(previous.pixels[k])*(1-t)+real.pixels[k]*t));blendResidual/=g.width*g.height;
+ const double expected=center(previous)*(1-t)+center(real)*t;
+ const bool good=item.validity==pipeline::GenerationValidity::Valid&&hash(g)!=hash(previous)&&hash(g)!=hash(real)&&hash(g)!=previousGeneratedHash&&blendResidual>0.1&&std::abs(center(g)-expected)<=3.0&&std::abs(item.pts100ns/10000.0-((i-1+t)*20.0))<=0.0001;
+ valid+=good;
+ previousGeneratedHash=hash(g);
+ std::cout<<"CONTENT frame="<<i<<" subframe="<<item.subframe<<" pts="<<item.pts100ns<<" previousHash="<<hash(previous)<<" realHash="<<hash(real)<<" generatedHash="<<hash(g)<<" expectedCenter="<<expected<<" actualCenter="<<center(g)<<" blendResidual="<<blendResidual<<" valid="<<good<<std::endl;
+ }
+ previous=std::move(real);
+ if(i==10)retained=out.batch;
+ }
+ std::cout<<"RESULT source="<<graph.metrics().nvofExecuteCount+1<<" generated="<<generated<<" contentValid="<<valid<<" display=unmeasured"<<std::endl;
+ pipeline::EnhanceGraph::FrameOutputs rejected;
+ const bool protectedLease=ok&&!graph.process(f,240,false,rejected);
+ std::cout<<"LEASE retained-slot-overwrite-rejected="<<protectedLease<<std::endl;
+ retained={};rejected={};
+ ok=ok&&generated==11*(gd.fgMultiplier-1)&&valid==generated&&protectedLease;ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;
+}
diff --git a/tests/integration/RepairParameterTests.cpp b/tests/integration/RepairParameterTests.cpp
new file mode 100644
index 00000000..e5135f68
--- /dev/null
+++ b/tests/integration/RepairParameterTests.cpp
@@ -0,0 +1,19 @@
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/sink/ImageExportSink.h"
+#include <filesystem>
+#include <iostream>
+#include <cmath>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+int main(){using namespace veyra;CoInitializeEx(nullptr,COINIT_MULTITHREADED);gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;pipeline::EnhanceGraph graph(ctx,ring);Status st;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;bool ok=ctx.initialize(dd,st)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=1920;gd.sourceHeight=gd.workHeight=1080;gd.enableNr=true;gd.enableFg=false;gd.enableSr=false;gd.enableNvofStandalone=true;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();ok=ok&&graph.initialize(gd)&&graph.createViews();
+AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_RGBA;f->width=1920;f->height=1080;f->color_range=AVCOL_RANGE_JPEG;ok=ok&&av_frame_get_buffer(f,32)>=0;
+for(int y=0;y<1080;++y)for(int x=0;x<1920;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;float noise=float((x*73+y*91)%31)-15;bool face=(x-960)*(x-960)/2+(y-540)*(y-540)<200*200;float base=95+45*std::sin(x*.02f)*std::cos(y*.026f)+noise;p[0]=uint8_t(std::clamp(base+(face?55:0),0.f,255.f));p[1]=uint8_t(std::clamp(base+(face?15:0),0.f,255.f));p[2]=uint8_t(std::clamp(base-(face?10:0),0.f,255.f));p[3]=255;}
+sink::RgbaImage baseline;unsigned ordinal=0;const char* names[]={"baseline","intensity","localTone","localStructure","skin-experimental","style-experimental","autoMask-experimental","UI-experimental","residual-total-zero"};
+for(unsigned mode=0;ok&&mode<9;++mode){engine::EnhancementSettings s;s.revision=mode+1;s.multiplier=1;if(mode==1)s.model.intensity=0;if(mode==2)s.model.tone=0;if(mode==3)s.model.structure=0;if(mode==4)s.model.skin=1.5f;if(mode==5)s.model.style=1;if(mode==6)s.model.autoMask=1;if(mode==7)s.model.uiCorrection=1;if(mode==8)s.residual.total=0;ok=graph.applySettings(s);sink::RgbaImage result;
+for(int j=0;ok&&j<4;++j){pipeline::EnhanceGraph::FrameOutputs out;ok=graph.process(f,(ordinal++)*20.0,j==0,out);if(j==3&&ok)ok=sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result);}
+if(!ok)break;if(mode==0)baseline=result;double mae=0;uint64_t changed=0;for(size_t k=0;k<result.pixels.size();k+=4)for(int c=0;c<3;++c){int d=std::abs(int(result.pixels[k+c])-baseline.pixels[k+c]);mae+=d;changed+=d!=0;}mae/=result.width*result.height*3.0;std::cout<<"PARAM name="<<names[mode]<<" appliedRevision="<<s.revision<<" changedRGB="<<changed<<" meanAbs8bit="<<mae<<" effect="<<(changed?"observed-on-synthetic":"not-proven-on-synthetic")<<'\n';}
+ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;}
diff --git a/tests/integration/RepairShaderTests.cpp b/tests/integration/RepairShaderTests.cpp
new file mode 100644
index 00000000..3c840c97
--- /dev/null
+++ b/tests/integration/RepairShaderTests.cpp
@@ -0,0 +1,34 @@
+#include "veyra/pipeline/GpuPassUtils.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include <bit>
+#include <cmath>
+#include <iostream>
+#include <cstring>
+int main(){
+ using namespace veyra;using namespace pipeline;gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status=Status::Ok;gfx::DeviceContextDesc dd;
+ if(!ctx.initialize(dd,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return 2;
+ auto base=makeTexture(ctx.device(),16,16,DXGI_FORMAT_R32G32B32A32_FLOAT,true),low=makeTexture(ctx.device(),8,8,DXGI_FORMAT_R32G32B32A32_FLOAT,true),result=makeTexture(ctx.device(),16,16,DXGI_FORMAT_R32G32B32A32_FLOAT,true);
+ auto upload=makeUploadBuffer(ctx.device(),16*256);void* data=nullptr;upload->Map(0,nullptr,&data);auto* values=static_cast<float*>(data);
+ for(int y=0;y<16;++y)for(int x=0;x<16;++x){const size_t at=y*64+x*4;values[at]=values[at+1]=values[at+2]=((x+y)%2)?0.75f:0.25f;values[at+3]=1;}
+ upload->Unmap(0,nullptr);
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=16*256;bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;ComPtr<ID3D12Resource> readback;
+ if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback))))return 2;
+ ComputePass down,residual;std::vector<uint8_t> cs;
+ if(!down.loadShader("NrDownsample.dxil",cs)||!down.create(ctx.device(),cs,2,1,1)||!residual.loadShader("NrResidualComposite.dxil",cs)||!residual.create(ctx.device(),cs,4,3,1))return 2;
+ makeSrv(ctx.device(),base.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(down,0));makeUav(ctx.device(),low.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(down,1));
+ makeSrv(ctx.device(),base.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(residual,0));makeSrv(ctx.device(),low.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(residual,1));makeSrv(ctx.device(),low.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(residual,2));makeUav(ctx.device(),result.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(residual,3));
+ StateTracker states;uint32_t slot;auto* list=ring.acquireNext(slot,status);states.transition(list,base.Get(),D3D12_RESOURCE_STATE_COPY_DEST);
+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=base.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;src.pResource=upload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;src.PlacedFootprint.Footprint={DXGI_FORMAT_R32G32B32A32_FLOAT,16,16,1,256};list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);states.transition(list,base.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);states.transition(list,low.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ float dims[8]={std::bit_cast<float>(16u),std::bit_cast<float>(16u),std::bit_cast<float>(8u),std::bit_cast<float>(8u),0,0,0,0};down.bind(list,dims,gpuHandleOf(down,0).ptr,gpuHandleOf(down,1).ptr);list->Dispatch(1,1,1);states.uavBarrier(list,low.Get());states.transition(list,low.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);
+ auto copy=[&](ID3D12Resource* texture,unsigned w,unsigned h){D3D12_TEXTURE_COPY_LOCATION a{},b{};a.pResource=texture;a.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.pResource=readback.Get();b.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;b.PlacedFootprint.Footprint={DXGI_FORMAT_R32G32B32A32_FLOAT,w,h,1,256};list->CopyTextureRegion(&b,0,0,0,&a,nullptr);};
+ copy(low.Get(),8,8);if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;
+ D3D12_RANGE range{0,16*256};readback->Map(0,&range,&data);values=static_cast<float*>(data);bool ok=true;for(int y=0;y<8;++y)for(int x=0;x<8;++x)ok=ok&&std::abs(values[y*64+x*4]-0.5f)<1e-6f;D3D12_RANGE written{0,0};readback->Unmap(0,&written);
+ std::cout<<"area downsample checkerboard mean="<<ok<<std::endl;
+ for(float strength:{0.0f,1.0f,2.0f}){
+ list=ring.acquireNext(slot,status);states.transition(list,low.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);states.transition(list,result.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ float c[8]={strength,0.5f,1.5f,2,0,0,0,0};residual.bind(list,c,gpuHandleOf(residual,0).ptr,gpuHandleOf(residual,3).ptr);list->Dispatch(1,1,1);states.uavBarrier(list,result.Get());states.transition(list,result.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);copy(result.Get(),16,16);if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;
+ readback->Map(0,&range,&data);values=static_cast<float*>(data);bool identity=true;for(int y=0;y<16;++y)for(int x=0;x<16;++x)identity=identity&&values[y*64+x*4]==(((x+y)%2)?0.75f:0.25f);readback->Unmap(0,&written);ok=ok&&identity;std::cout<<"zero residual strength="<<strength<<" base identity="<<identity<<std::endl;
+ }
+ ring.drainQueue();return ok?0:1;
+}
diff --git a/tests/unit/LivePresentationTimingTests.cpp b/tests/unit/LivePresentationTimingTests.cpp
new file mode 100644
index 00000000..54b52a4e
--- /dev/null
+++ b/tests/unit/LivePresentationTimingTests.cpp
@@ -0,0 +1,17 @@
+#include "veyra/engine/LivePresentationTiming.h"
+#include <cmath>
+#include <limits>
+#include <cstdio>
+int main(){
+ using veyra::engine::livePairHoldMs;
+ int failed=0;
+ auto check=[&](bool ok,const char* label){printf("%s %s\n",ok?"PASS":"FAIL",label);if(!ok)++failed;};
+ check(livePairHoldMs(false,1822.09,22.64)==0,"no-FG never waits on stale source PTS");
+ check(livePairHoldMs(false,1e12,0)==0,"no-FG absolute PTS cannot add latency");
+ check(livePairHoldMs(true,100,90)==10,"50fps FG pair half interval");
+ check(std::abs(livePairHoldMs(true,100,100-1000./120)-1000./120)<1e-8,"60fps FG pair half interval");
+ check(livePairHoldMs(true,1e12,0)<=1000./30,"timestamp jump has bounded hold");
+ check(livePairHoldMs(true,10,20)==0,"backwards PTS cannot sleep negatively");
+ check(livePairHoldMs(true,std::numeric_limits<double>::infinity(),0)==0,"nonfinite PTS rejected");
+ return failed?1:0;
+}
diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cpp
new file mode 100644
index 00000000..8ad3c01a
--- /dev/null
+++ b/tests/unit/RepairContractTests.cpp
@@ -0,0 +1,59 @@
+#include "veyra/engine/EnhancementSettings.h"
+#include "veyra/diagnostics/DiagnosticEvent.h"
+#include "veyra/diagnostics/FrameMetrics.h"
+#include "veyra/engine/PresentationScheduler.h"
+#include <iostream>
+#include "veyra/engine/ContentCadence.h"
+#include "veyra/diagnostics/Redaction.h"
+#include <limits>
+#include <vector>
+#include "veyra/engine/CfrTimeline.h"
+#include "veyra/Log.h"
+int main(){
+ using namespace veyra;int failures=0,checks=0;
+ auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';};
+ auto p=pipeline::ResolutionPlan::make({1920,1080},true,pipeline::NrSizePolicy::Realtime,false);
+ check(p.base==pipeline::Extent{3840,2160}&&p.nr==pipeline::Extent{1920,1080}&&p.output==p.base,"SR4K preserves base; NR1080");
+ p=pipeline::ResolutionPlan::make({3840,2160},true,pipeline::NrSizePolicy::Realtime,true);
+ check(!p.srApplied&&p.nr==p.base,"native export and 1:1 SR bypass");
+ engine::EnhancementSettings s;check(s.validate().empty(),"default settings valid");
+ s.model.intensity=std::numeric_limits<float>::quiet_NaN();check(!s.validate().empty(),"reject NaN transaction");
+ s={};s.multiplier=5;check(!s.validate().empty(),"reject unsupported multiplier");
+ check(pipeline::FrameBatch::interpolate(-200000,0,1,2)==-100000,"negative PTS midpoint");
+ check(pipeline::FrameBatch::interpolate(0,200000,1,3)==66667&&pipeline::FrameBatch::interpolate(0,200000,2,3)==133333,"rational 3X PTS within tick");
+ pipeline::FrameBatch b;b.identity={1,2,3};pipeline::BatchFrame f;f.identity=b.identity;f.pts100ns=1;b.append(f);f.identity.settingsRevision=3;
+ bool rejected=false;try{b.append(f);}catch(...){rejected=true;}check(rejected,"reject mixed settingsRevision");
+ diagnostics::FrameMetrics m;check(!m.displayFps&& !m.gpu[0].milliseconds,"unknown display/GPU is not zero");
+ diagnostics::DiagnosticHistory h;diagnostics::DiagnosticEvent e;e.fingerprint="same";for(int i=0;i<100;++i)h.add(e);
+ check(h.size()==1&&h.events()[0].occurrenceCount==100,"merge repeated error");
+ engine::PresentationScheduler timeline;timeline.reset(3,0,1000000,200000);
+ check(timeline.deadline(200000)==1400000&&timeline.deadline(400000)==1600000,"live deadlines do not drift with CPU completion");
+ check(timeline.expired(0,1400000,100000)&&!timeline.anchored(4),"expire generated debt and reject epoch change");
+ for(int i=0;i<100;++i){e.fingerprint=std::to_string(i);h.add(e);}check(h.size()==64,"bounded diagnostic queue");
+ engine::ContentCadence cadence;for(int i=0;i<120;++i)cadence.observe(i*1000.0/60,i%2?.01:0,true);check(cadence.measuredRate()==30,"moving 30 in 60 cadence");
+ cadence.reset();for(int i=0;i<120;++i)cadence.observe(i*1000.0/60,0,true);check(cadence.measuredRate()==0,"static scene cannot establish lower FPS");
+ cadence.reset();for(int i=0;i<120;++i)cadence.observe(i*20.0,.01,true);check(cadence.measuredRate()==50,"moving 50fps cadence");
+ cadence.reset();for(int i=0;i<120;++i)cadence.observe(i*1000.0/60,.01,true);check(cadence.measuredRate()==60,"moving 60fps cadence");check(cadence.confirmedRate(engine::ContentRate::Fps60)==60&&cadence.confirmedRate(engine::ContentRate::Fps30)==0&&cadence.conflicts(engine::ContentRate::Fps30),"manual identification target is not a resampling fiction");
+ check(diagnostics::redact("failure C:\\Users\\private-user\\media file.mp4\nserial=DEVICE123\nuser=private-user").find("private-user")==std::string::npos,"redact Windows paths, usernames and serials");
+ engine::CfrTimeline cfr(60,1,.001,0);bool quantized=true;
+ for(unsigned i=0;i<6000;++i)quantized &= cfr.accepts(i,std::round(i*1000.0/60)/1000);
+ check(quantized,"60fps millisecond quantization does not drift or reject");
+ engine::CfrTimeline ntsc(30000,1001,.001,-.017);bool fractional=true;
+ for(unsigned i=0;i<30000;++i)fractional &= ntsc.accepts(i,std::round((i*1001.0/30000-.017)*1000)/1000);
+ check(fractional,"fractional CFR with negative origin survives quantization");
+ engine::CfrTimeline gap(60,1,.001,0);gap.accepts(0,0);gap.accepts(1,.017);
+ engine::CfrTimeline drift(60,1,.001,0);for(unsigned i=0;i<60;++i)drift.accepts(i,std::round(i*1000.0/60)/1000);
+ engine::CfrTimeline invalid(60,1,.001,0);
+ check(!gap.accepts(2,.05)&&!drift.accepts(60,1.016667)&&!invalid.accepts(0,std::numeric_limits<double>::quiet_NaN()),"VFR gap, drift and invalid PTS rejected with fresh timelines");
+ check(!engine::CfrTimeline(60,1,.02,0).valid(),"time base coarser than one frame rejected");
+ engine::CfrTimeline ticks(60,1,1.0/60,0);bool exactTicks=true;for(unsigned i=0;i<120;++i)exactTicks &= ticks.accepts(i,i/60.0);check(exactTicks&&!ticks.accepts(120,121.0/60),"one-tick CFR accepted but missing frame rejected");
+ std::vector<double> mkv;for(unsigned i=0;i<24;++i)mkv.push_back(std::round(i*1000.0/60)/1000);
+ check(engine::CfrTimeline::select(29990,499,.001,mkv)==std::pair<int,int>{60,1},"misdeclared MKV rate selects consistent standard CFR candidate");
+ Logger::instance().setConsoleEnabled(false);
+ log::error("nvof-session","test-only nvOFInit failed status=5");
+ log::error("nvof-session","test-only caps failed st=7");
+ log::error("ngx","test-only fg-backend failed result=0xBAD00005 seh=0xC0000005");
+ const auto report=Logger::instance().diagnosticReport();
+ check(report.find("NVOF=0x5")!=std::string::npos&&report.find("NVOF=0x7")!=std::string::npos&&report.find("NGX=0xBAD00005")!=std::string::npos&&report.find("SEH=0xC0000005")!=std::string::npos,"diagnostic report retains NVOF aliases and NGX/SEH codes (synthetic errors)");
+ std::cout<<checks<<" checks "<<failures<<" failures\n";return failures?1:0;
+}
diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cpp
new file mode 100644
index 00000000..46ce5586
--- /dev/null
+++ b/tests/unit/RepairPresetTests.cpp
@@ -0,0 +1,8 @@
+#include "veyra/engine/PresetStore.h"
+#include <iostream>
+#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.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;
+ 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 invalid=s;invalid.model.tone=9;ok=ok&&!b.put(L"bad",invalid)&&b.entries().size()==1&&b.erase(0)&&b.entries().empty();
+ {std::ofstream f(p);f<<"VEYRA_PRESETS 99\ncorrupt mediaPath executable must reject";}PresetStore c(p);ok=ok&&!c.load()&&!c.put(L"override",{});std::ifstream f(p);std::string data((std::istreambuf_iterator<char>(f)),{});ok=ok&&data=="VEYRA_PRESETS 99\ncorrupt mediaPath executable must reject";
+ std::cout<<"preset roundtrip, all fields, duplicate, rename-default, delete, validation, unknown schema, corrupt-preservation="<<ok<<'\n';return ok?0:1;}
diff --git a/validation/fixed_clips/test_h264_1080p.mp4 b/validation/fixed_clips/test_h264_1080p.mp4
deleted file mode 100644
index b00ef75a..00000000
Binary files a/validation/fixed_clips/test_h264_1080p.mp4 and /dev/null differ