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: experimental XeSS and AMD flow backends
Veyra Goal Agentc35b51c221b3
diff --git a/CMakeLists.txt b/CMakeLists.txtindex a0d3ee1c..86ef3a8b 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -25,6 +25,8 @@ option(VEYRA_ENABLE_DLSS_SR "Enable public DLSS SR backend" OFF)option(VEYRA_ENABLE_DLSS_FG "Enable public DLSSG backend" OFF)option(VEYRA_ENABLE_NVOF "Enable NVIDIA Optical Flow guidance" OFF)option(VEYRA_ENABLE_D3D12_DEBUG "Enable D3D12 debug layer" ON)+set(VEYRA_FIDELITYFX_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third_party_local/amd/FidelityFX-SDK/sdk" CACHE PATH "Local official FidelityFX SDK 1.1.4")+set(VEYRA_XESS_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third_party_local/intel/xess-3.0.2" CACHE PATH "Local Intel XeSS SDK 3.0.2")list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")include(VeyraWarnings)@@ -55,10 +57,15 @@ add_library(veyra_gfx STATICsrc/gfx/D3D12DeviceContext.cppsrc/gfx/CommandSlotRing.cppsrc/gfx/PresentSink.cpp+ src/gfx/XessPresenter.cpp)veyra_apply_warnings(veyra_gfx)target_compile_features(veyra_gfx PUBLIC cxx_std_20)target_link_libraries(veyra_gfx PUBLIC veyra_base d3d12 dxgi dxguid)+if(EXISTS "${VEYRA_XESS_ROOT}/inc/xess_fg/xefg_swapchain_d3d12.h")+ target_include_directories(veyra_gfx PRIVATE "${VEYRA_XESS_ROOT}/inc")+ target_compile_definitions(veyra_gfx PRIVATE VEYRA_HAS_XESS=1)+endif()if(VEYRA_ENABLE_D3D12_DEBUG)target_compile_definitions(veyra_gfx PUBLIC VEYRA_D3D12_DEBUG=1)endif()@@ -456,6 +463,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_definitions(veyra_image_dimension_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")target_link_libraries(veyra_image_dimension_tests PRIVATE veyra_engine)add_executable(veyra_preview_geometry_tests tests/integration/PreviewGeometryTests.cpp)+ add_executable(veyra_experimental_backend_tests tests/integration/ExperimentalBackendTests.cpp)+ target_compile_features(veyra_experimental_backend_tests PRIVATE cxx_std_20)+ target_include_directories(veyra_experimental_backend_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})+ target_compile_definitions(veyra_experimental_backend_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+ target_link_libraries(veyra_experimental_backend_tests PRIVATE veyra_engine)target_compile_features(veyra_preview_geometry_tests PRIVATE cxx_std_20)target_include_directories(veyra_preview_geometry_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})target_compile_definitions(veyra_preview_geometry_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)@@ -501,6 +513,14 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform# Headless quality-core runner (Playbook R3.3): the phase5 gate's qualityadd_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineControllerImage.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp)+ target_sources(veyra_pipeline PRIVATE src/guidance/AmdOpticalFlow.cpp)+ if(EXISTS "${VEYRA_FIDELITYFX_ROOT}/bin/ffx_sdk/ffx_opticalflow_x64.lib")+ target_compile_definitions(veyra_pipeline PRIVATE VEYRA_HAS_AMD_OF=1)+ target_include_directories(veyra_pipeline PRIVATE "${VEYRA_FIDELITYFX_ROOT}/include")+ target_link_libraries(veyra_pipeline PRIVATE+ "${VEYRA_FIDELITYFX_ROOT}/bin/ffx_sdk/ffx_opticalflow_x64.lib"+ "${VEYRA_FIDELITYFX_ROOT}/bin/ffx_sdk/ffx_backend_dx12_x64.lib")+ endif()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")diff --git a/README.md b/README.mdindex 2c199927..4ab96abb 100644--- a/README.md+++ b/README.md@@ -11,7 +11,8 @@ Veyra is a native Windows video player and image-enhancement workspace. It combi- 默认日常模式:大画面、底部播放控制、打开媒体、采集卡、音量、字幕和全屏。- 专业模式:带展开动画的参数工作台;同一播放会话不中断。- H.264 / HEVC 视频、PNG / JPEG 图片、DirectShow / UVC 采集设备。-- 可选 DLSS SR、RTX Video SR、实验性 NR、NVOF 运动置信度,以及 DLSS / FRUC 补帧后端。+- 可选 DLSS SR、RTX Video SR、实验性 NVIDIA NR、NVOF 运动置信度,以及 DLSS / FRUC 补帧后端。+- 实验性 Intel XeSS 显示补帧 2X,以及 AMD FidelityFX 光流运动估算;XeSS 当前只用于预览。- 原图与增强结果的即时对比、分屏拖动、专业模式内的画面缩放和性能诊断。- PNG / JPEG 图片导出,D3D12 NVENC H.264 / HEVC 视频导出。- Windows 11 Desktop Acrylic 控制面板;视频区域保持不透明,未打开媒体时为纯黑。@@ -19,7 +20,8 @@ Veyra is a native Windows video player and image-enhancement workspace. It combi- Daily mode by default: a large picture area with playback, media opening, capture, volume, subtitles, and fullscreen controls.- Professional mode: an expanding settings workspace without interrupting the current session.- H.264 / HEVC video, PNG / JPEG images, and DirectShow / UVC capture devices.-- Optional DLSS SR, RTX Video SR, experimental NR, NVOF motion confidence, plus DLSS and FRUC frame-generation backends.+- Optional DLSS SR, RTX Video SR, experimental NVIDIA NR, NVOF motion confidence, plus DLSS and FRUC frame-generation backends.+- Experimental Intel XeSS 2X display frame generation and AMD FidelityFX optical-flow estimation; XeSS is currently preview-only.- Same-frame comparison, split view, preview zoom in Professional mode, and performance diagnostics.- PNG / JPEG image export and D3D12 NVENC H.264 / HEVC video export.- Windows 11 Desktop Acrylic for controls; the video area stays opaque and is pure black with no media open.@@ -91,6 +93,8 @@ Video / image / capture card- Depth is not a shipped default provider. Current motion guidance uses NVOF confidence handling where available.- 3X and 4X frame generation are experimental. A selected multiplier does not guarantee that every source-frame pair produces a valid generated frame or that every configuration runs in real time.- Actual scanout latency, long-term stability, capture audio behavior, and every GPU / driver combination require further real-device validation.+- AMD FidelityFX supplies optical-flow estimation only. There is no AMD implementation of DLSS5/NR, DLSS SR, NVIDIA FRUC, DLSS frame generation, NVENC export, or an AMD AMF export backend. On a non-NVIDIA adapter, Veyra disables those NVIDIA paths; XeSS may still initialize when its runtime and device support it.+- XeSS 2X diagnostics confirm SDK submissions only. They do not prove scanout frame rate, visual quality, or AMD-GPU compatibility.- No NVIDIA runtime, SDK archive, headers, libraries, models, or samples are in this Git repository. The user-authorized Release Runtime Pack is a separate Release-only payload and remains experimental.## 项目结构 / Project layoutdiff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex 8710b3d7..e9aa4e88 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -39,10 +39,34 @@ void syncProtection(const engine::ProtectionSettings& protection){putText(206,(L"NR保护区域 · "+std::to_wstring(count)+L"/4").c_str());}void selectDiscrete(int group,int value){for(int j=0;j<(group==0?3:2);++j){auto h=item(700+group*10+j);if(j==value)SetPropW(h,L"veyra.selected",HANDLE(1));else RemovePropW(h,L"veyra.selected");InvalidateRect(h,nullptr,FALSE);}}-void populate(engine::EnhancementSettings s){populating=true;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];if(i>=4&&i<=6){selectDiscrete(i-4,int(v[i]));continue;}if(GetFocus()!=item(100+i))putText(100+i,o.str().c_str());send(600+i,TBM_SETPOS,TRUE,LPARAM(v[i]*100));}syncProtection(s.protection);check(200,enhancementEnabled&&s.nr?BST_CHECKED:BST_UNCHECKED);check(201,enhancementEnabled&&s.sr?BST_CHECKED:BST_UNCHECKED);send(207,CB_SETCURSEL,s.videoSrQuality,0);send(202,CB_SETCURSEL,s.multiplier-1,0);send(208,CB_SETCURSEL,int(s.frameGenerationBackend),0);send(203,CB_SETCURSEL,int(s.nrPolicy),0);send(204,CB_SETCURSEL,int(s.flow),0);send(205,CB_SETCURSEL,int(s.content),0);displayedRevision=s.revision;populating=false;dirty=false;}+void populate(engine::EnhancementSettings s){+ populating=true;+ 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];if(i>=4&&i<=6){selectDiscrete(i-4,int(v[i]));continue;}if(GetFocus()!=item(100+i))putText(100+i,o.str().c_str());send(600+i,TBM_SETPOS,TRUE,LPARAM(v[i]*100));}+ syncProtection(s.protection);+ check(200,enhancementEnabled&&s.nr?BST_CHECKED:BST_UNCHECKED);+ check(201,enhancementEnabled&&s.sr?BST_CHECKED:BST_UNCHECKED);+ for(int j=0;j<3;++j){auto h=item(730+j);if(j==int(s.srTarget))SetPropW(h,L"veyra.selected",HANDLE(1));else RemovePropW(h,L"veyra.selected");InvalidateRect(h,nullptr,FALSE);}+ const int multiplierCount=s.frameGenerationBackend==engine::FrameGenerationBackend::XeSS?2:4;+ if(send(202,CB_GETCOUNT)!=multiplierCount){send(202,CB_RESETCONTENT);const wchar_t* choices[]={L"关闭补帧",L"2X · 一张中间帧",L"3X · 两张中间帧",L"4X · 三张中间帧"};for(int i=0;i<multiplierCount;++i)send(202,CB_ADDSTRING,0,LPARAM(choices[i]));}+ send(207,CB_SETCURSEL,s.videoSrQuality,0);send(202,CB_SETCURSEL,s.multiplier-1,0);+ send(208,CB_SETCURSEL,int(s.frameGenerationBackend),0);send(203,CB_SETCURSEL,int(s.nrPolicy),0);+ send(204,CB_SETCURSEL,int(s.flow),0);send(205,CB_SETCURSEL,int(s.content),0);+ send(209,CB_SETCURSEL,int(s.opticalFlowBackend),0);+ check(215,s.amdFlowHalfResolution?BST_CHECKED:BST_UNCHECKED);+ EnableWindow(item(204),s.opticalFlowBackend==engine::OpticalFlowBackend::Nvidia);+ EnableWindow(item(215),s.opticalFlowBackend==engine::OpticalFlowBackend::AmdFidelityFx);+ displayedRevision=s.revision;populating=false;dirty=false;+}bool read(engine::EnhancementSettings& s,bool allPages=false){s=enhancementEnabled?controller->snapshot().desired:configuredSettings;float v[12]{};for(int i=0;i<12;++i){if(i>=4&&i<=6){v[i]=float(i==4?s.model.style:i==5?s.model.autoMask:s.model.uiCorrection);continue;}wchar_t b[64]{};GetWindowTextW(item(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]};if(enhancementEnabled){s.nr=checked(200)==BST_CHECKED;s.sr=checked(201)==BST_CHECKED;}s.videoSrQuality=uint32_t(send(207,CB_GETCURSEL,0,0));if(allPages)s.multiplier=uint32_t(send(202,CB_GETCURSEL,0,0)+1);s.nrPolicy=static_cast<pipeline::NrSizePolicy>(send(203,CB_GETCURSEL,0,0));if(allPages){s.flow=static_cast<engine::FlowQuality>(send(204,CB_GETCURSEL,0,0));s.content=static_cast<engine::ContentRate>(send(205,CB_GETCURSEL,0,0));}if(!s.validate().empty()){message(L"参数越界,未提交。悬停数值框查看允许范围。");return false;}return true;}+ 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]};if(enhancementEnabled){s.nr=checked(200)==BST_CHECKED;s.sr=checked(201)==BST_CHECKED;}s.videoSrQuality=uint32_t(send(207,CB_GETCURSEL,0,0));s.nrPolicy=static_cast<pipeline::NrSizePolicy>(send(203,CB_GETCURSEL,0,0));if(allPages){+ const auto multiplier=send(202,CB_GETCURSEL,0,0),generation=send(208,CB_GETCURSEL,0,0),flowBackend=send(209,CB_GETCURSEL,0,0),flowQuality=send(204,CB_GETCURSEL,0,0),content=send(205,CB_GETCURSEL,0,0);+ if(multiplier==CB_ERR||generation==CB_ERR||flowBackend==CB_ERR||flowQuality==CB_ERR||content==CB_ERR){message(L"设置控件未完成初始化;未保存预设");return false;}+ s.multiplier=uint32_t(multiplier+1);s.frameGenerationBackend=static_cast<engine::FrameGenerationBackend>(generation);s.opticalFlowBackend=static_cast<engine::OpticalFlowBackend>(flowBackend);s.amdFlowHalfResolution=checked(215)==BST_CHECKED;s.flow=static_cast<engine::FlowQuality>(flowQuality);s.content=static_cast<engine::ContentRate>(content);+ for(int j=0;j<3;++j)if(GetPropW(item(730+j),L"veyra.selected")){s.srTarget=static_cast<pipeline::SrTarget>(j);break;}+ if(s.frameGenerationBackend==engine::FrameGenerationBackend::XeSS)s.multiplier=std::min(s.multiplier,2u);+ }if(!s.validate().empty()){message(L"参数越界,未提交。悬停数值框查看允许范围。");return false;}return true;}// Each notification changes one field on the latest desired settings. Hidden// controls and incomplete numeric text can never overwrite another field.@@ -58,11 +82,14 @@ bool liveField(int id){case 203:s.nrPolicy=static_cast<pipeline::NrSizePolicy>(send(id,CB_GETCURSEL));break;case 204:s.flow=static_cast<engine::FlowQuality>(send(id,CB_GETCURSEL));break;case 205:s.content=static_cast<engine::ContentRate>(send(id,CB_GETCURSEL));break;- case 208:s.frameGenerationBackend=static_cast<engine::FrameGenerationBackend>(send(id,CB_GETCURSEL));break;+ case 208:s.frameGenerationBackend=static_cast<engine::FrameGenerationBackend>(send(id,CB_GETCURSEL));if(s.frameGenerationBackend==engine::FrameGenerationBackend::XeSS)s.multiplier=std::min(s.multiplier,2u);break;+ case 209:s.opticalFlowBackend=static_cast<engine::OpticalFlowBackend>(send(id,CB_GETCURSEL));break;+ case 215:s.amdFlowHalfResolution=checked(id)==BST_CHECKED;break;case 207:s.videoSrQuality=uint32_t(send(id,CB_GETCURSEL));break;case 700:case 701:case 702:s.model.style=id-700;break;case 710:case 711:s.model.autoMask=id-710;break;case 720:case 721:s.model.uiCorrection=id-720;break;+ case 730:case 731:case 732:s.srTarget=static_cast<pipeline::SrTarget>(id-730);break;default:return false;}if(!s.validate().empty()){message(L"数值超出范围;仍使用上次有效值");return false;}@@ -92,12 +119,14 @@ void arrange(){HWND add(const wchar_t* cls,const wchar_t* text,int id,DWORD style,int group,int x,int y,int width,int height){auto h=CreateWindowExW(0,cls,text,WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|style,0,0,1,1,group==-1?window:body,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(h,WM_SETFONT,WPARAM(font),TRUE);themeControl(h);if(group!=-1)SetWindowSubclass(h,scrollOnly,950,0);items.push_back({h,group,x,y,width,height});return h;}void button(const wchar_t* title,int id,int group,int x,int y,int width=-1){add(L"BUTTON",title,id,BS_PUSHBUTTON|WS_TABSTOP,group,x,y,width,36);}void combo(int id,int group,int y,std::initializer_list<const wchar_t*> names){auto h=add(L"COMBOBOX",L"",id,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,group,12,y,-1,200);for(auto name:names)SendMessageW(h,CB_ADDSTRING,0,LPARAM(name));}-LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){+LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){+ if(msg==WM_COMMAND&&!populating&&((LOWORD(wp)==209&&HIWORD(wp)==CBN_SELCHANGE)||(LOWORD(wp)==215&&HIWORD(wp)==BN_CLICKED))){liveField(LOWORD(wp));return 0;}+ switch(msg){case WM_CREATE:{window=h;font=makeFont(h);items.clear();WNDCLASSW bodyClass{};bodyClass.lpfnWndProc=bodyProc;bodyClass.hInstance=GetModuleHandleW(nullptr);bodyClass.lpszClassName=L"VeyraInspectorBody";bodyClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&bodyClass);body=CreateWindowExW(WS_EX_CONTROLPARENT,bodyClass.lpszClassName,L"滚动参数",WS_CHILD|WS_VISIBLE|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,0,88,300,300,h,nullptr,bodyClass.hInstance,nullptr);- add(L"BUTTON",L"DLSS5 NR 增强",200,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,12,-1,36);- add(L"BUTTON",L"超分辨率 · 4K",201,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,56,-1,36);+ add(L"BUTTON",L"实验性 NVIDIA NR 增强",200,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,12,-1,36);+ add(L"BUTTON",L"超分辨率",201,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,56,-1,36);combo(203,0,104,{L"实时NR · 约1080内部处理",L"原生NR · 高性能成本"});add(L"STATIC",L"模型参数",1100,0,0,12,146,-1,24);for(int i=0;i<12;++i){const int y=174+i*62+(i>=7?32:0);add(L"STATIC",labels[i],1000+i,0,0,12,y,176,28);@@ -110,9 +139,9 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();button(L"还原默认",211,-1,12,86);add(L"STATIC",L"补帧与运动估算",1103,0,1,12,12,-1,30);combo(202,1,52,{L"关闭补帧",L"2X · 一张中间帧",L"3X · 两张中间帧",L"4X · 三张中间帧"});- combo(204,1,104,{L"NR / DLSS光流 · 性能",L"NR / DLSS光流 · 平衡",L"NR / DLSS光流 · 质量"});- combo(205,1,156,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏",L"采集60→30fps处理(PS5 30帧)"});- add(L"STATIC",L"FRUC倍率越高,耗时越多。光流档位用于NR/DLSS;FRUC内部自动控制。补帧需等待下一张源帧,倍率不等于实测显示帧率。",1104,0,1,12,210,-1,100);+ combo(204,1,340,{L"NR / DLSS光流 · 性能",L"NR / DLSS光流 · 平衡",L"NR / DLSS光流 · 质量"});+ combo(205,1,392,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏",L"采集60→30fps处理(PS5 30帧)"});+ add(L"STATIC",L"FRUC倍率越高,耗时越多。光流档位用于NR/DLSS;FRUC内部自动控制。补帧需等待下一张源帧,倍率不等于实测显示帧率。",1104,0,1,12,446,-1,88);add(L"STATIC",L"用户预设",1105,0,2,12,12,-1,30);combo(300,2,56,{});add(L"EDIT",L"新预设",301,ES_AUTOHSCROLL|WS_TABSTOP,2,12,108,-1,36);send(301,EM_SETLIMITTEXT,48,0);const wchar_t* names[]={L"载入所选预设",L"新建内建默认预设",L"保存当前参数为新预设",L"重命名所选",L"删除所选",L"设为启动增强默认"};for(int i=0;i<6;++i)button(names[i],310+i,2,12,164+i*44);@@ -130,8 +159,12 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();add(L"STATIC",L"最多4区,左键拖框,Esc取消。仅抑制NR变化;不保护SR或补帧。可随预设保存;换源清空。",1109,0,0,12,232,-1,82);for(auto& entry:items)if(entry.page==0&&entry.y>=104)entry.y+=48;combo(207,0,100,{L"DLSS SR",L"RTX 视频超分 · 低",L"RTX 视频超分 · 中",L"RTX 视频超分 · 高",L"RTX 视频超分 · 最高"});- for(auto& entry:items)if(entry.page==1)entry.y+=48;- combo(208,1,8,{L"DLSS 帧生成",L"NVIDIA FRUC · 视频补帧"});+ for(auto& entry:items)if(entry.page==0&&entry.y>=100)entry.y+=44;+ button(L"2K",730,0,12,100,80);button(L"4K",731,0,100,100,80);button(L"8K",732,0,188,100,80);+ combo(208,1,8,{L"DLSS 帧生成",L"NVIDIA FRUC · 视频补帧",L"Intel XeSS · 实验显示补帧 2X"});+ combo(209,1,148,{L"NVIDIA NVOF 光流",L"AMD FidelityFX 光流 · 实验"});+ add(L"BUTTON",L"AMD 性能档 · 光流宽高各减半",215,BS_AUTOCHECKBOX|WS_TABSTOP,1,12,196,-1,36);+ add(L"STATIC",L"AMD FidelityFX 只替换运动估算,不提供 AMD DLSS5 / NR / 超分 / FRUC / DLSS 补帧 / NVENC。XeSS 当前只支持预览 2X,不能导出。",1110,0,1,12,244,-1,72);loadStore();refreshPresets();populate(controller->snapshot().desired);message(store.error());SetTimer(h,1,250,nullptr);arrange();return 0;}case WM_SIZE:arrange();return 0;case WM_ERASEBKGND:return 1;@@ -139,7 +172,7 @@ case WM_PAINT:{PaintBuffer paint(h);fillSurface(paint.dc,paint.rect,h);return 0;case WM_VSCROLL:{switch(LOWORD(wp)){case SB_LINEUP:scroll-=40;break;case SB_LINEDOWN:scroll+=40;break;case SB_PAGEUP:scroll-=240;break;case SB_PAGEDOWN:scroll+=240;break;case SB_THUMBTRACK:{SCROLLINFO si{sizeof(si),SIF_TRACKPOS};GetScrollInfo(h,SB_VERT,&si);scroll=si.nTrackPos;break;}}arrange();return 0;}case WM_MOUSEWHEEL:scroll-=GET_WHEEL_DELTA_WPARAM(wp)/WHEEL_DELTA*90;arrange();return 0;case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORLISTBOX:case WM_CTLCOLORBTN:return colors(msg,wp,lp);-case WM_COMMAND:{const int id=LOWORD(wp);if(!populating&&((id>=202&&id<=205||id==207||id==208)&&HIWORD(wp)==CBN_SELCHANGE||(id>=700&&id<=721)&&HIWORD(wp)==BN_CLICKED)){liveField(id);return 0;}if((id==206||id==213||id==214)&&HIWORD(wp)==BN_CLICKED){const auto accepted=SendMessageW(GetParent(h),WM_APP+45,id,checked(206));message(accepted?(id==213?L"请在画面中左键拖动框选;Esc取消。":L"已请求更新NR保护区域。"):L"未能操作:请先打开画面,或清除已满的4个区域。");return 0;}if((id==200||id==201)&&HIWORD(wp)==BN_CLICKED){const bool accepted=SendMessageW(GetParent(h),WM_APP+44,id,checked(id))!=0;message(accepted?L"已请求开关;确认帧边界结果后生效。":L"总增强正在切换,请待当前事务完成。");return 0;}if(HIWORD(wp)==EN_SETFOCUS){for(auto& item:items)if(GetDlgCtrlID(item.h)==id&&item.page==page){RECT r{};GetClientRect(h,&r);int height=MulDiv(r.bottom,96,GetDpiForWindow(h))-128;if(item.y<scroll)scroll=item.y;if(item.y+item.height>scroll+height)scroll=item.y+item.height-height;arrange();break;}}if(!populating&&id>=100&&id<=111&&HIWORD(wp)==EN_CHANGE){liveField(id);return 0;}+case WM_COMMAND:{const int id=LOWORD(wp);if(!populating&&((id>=202&&id<=205||id==207||id==208)&&HIWORD(wp)==CBN_SELCHANGE||(id>=700&&id<=732)&&HIWORD(wp)==BN_CLICKED)){liveField(id);return 0;}if((id==206||id==213||id==214)&&HIWORD(wp)==BN_CLICKED){const auto accepted=SendMessageW(GetParent(h),WM_APP+45,id,checked(206));message(accepted?(id==213?L"请在画面中左键拖动框选;Esc取消。":L"已请求更新NR保护区域。"):L"未能操作:请先打开画面,或清除已满的4个区域。");return 0;}if((id==200||id==201)&&HIWORD(wp)==BN_CLICKED){const bool accepted=SendMessageW(GetParent(h),WM_APP+44,id,checked(id))!=0;message(accepted?L"已请求开关;确认帧边界结果后生效。":L"总增强正在切换,请待当前事务完成。");return 0;}if(HIWORD(wp)==EN_SETFOCUS){for(auto& item:items)if(GetDlgCtrlID(item.h)==id&&item.page==page){RECT r{};GetClientRect(h,&r);int height=MulDiv(r.bottom,96,GetDpiForWindow(h))-128;if(item.y<scroll)scroll=item.y;if(item.y+item.height>scroll+height)scroll=item.y+item.height-height;arrange();break;}}if(!populating&&id>=100&&id<=111&&HIWORD(wp)==EN_CHANGE){liveField(id);return 0;}if(!populating&&id>=100&&id<=111&&HIWORD(wp)==EN_KILLFOCUS){populate(enhancementEnabled?controller->snapshot().desired:configuredSettings);return 0;}engine::EnhancementSettings s;wchar_t name[128]{};GetWindowTextW(item(301),name,128);const auto index=size_t(send(300,CB_GETCURSEL,0,0));bool ok=true;if(id==211){SetFocus(body);s={};if(submit(s)){populate(s);message(L"已还原内建默认;用户预设保留");}}diff --git a/docs/SR_TARGETS_AMD_NR_PLAN_2026-09-10.md b/docs/SR_TARGETS_AMD_NR_PLAN_2026-09-10.mdindex 9005e8c6..506c9338 100644--- a/docs/SR_TARGETS_AMD_NR_PLAN_2026-09-10.md+++ b/docs/SR_TARGETS_AMD_NR_PLAN_2026-09-10.md@@ -202,7 +202,7 @@ AMF只替换压缩编码器,继续共享颜色转换、源PTS、CFR判定、应用EXE未变:`E97B716B99116BEC942262FFEF1612299CBB2F4B0BDA7C308A5BFF318B3B5157`。原NR仍为指定SHA `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`、165840496字节、310.8.0.0、签名Valid。-本轮没有构建、2K/8K Create/Evaluate、AMD网络执行、实卡测试、阶段gate或独立Reviewer通过结论;没有提交、push或Release变更。UI闪白修复的原工作树保留;原生NR性能、FRUC reset像素等历史未决问题没有被本方案关闭。+本文最初研究阶段没有构建、2K/8K Create/Evaluate、AMD网络执行、实卡测试、阶段gate或独立Reviewer通过结论。后续同日实施已完成 Release 构建;RTX 5070 上 `veyra_experimental_backend_tests.exe sr2k` 和 `sr8k` 各完成三次 DLSS SR Evaluate,并读回确认非黑的 `2560x1440` 与 `7680x4320` 输出;AMD OF 独立短测成功 Create/Dispatch/Destroy 48 次。没有 AMD GPU、AMD NR 网络、实卡、阶段 gate 或独立 Reviewer 通过结论;没有提交、push 或 Release 变更。UI闪白修复的原工作树保留;原生NR性能、FRUC reset像素等历史未决问题没有被本方案关闭。文档检查通过:两份方案及交接页的本地链接、代码围栏和行尾空白检查;`loop/STATE.json`解析及Phase7状态检查;`git diff --check`。研究文本缓存经`git check-ignore`确认仍被忽略。这些检查只证明文档一致性,不是新后端或画质验收。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 0a9753f9..d8f1e63f 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,3 +1,13 @@+# 2026-09-10 XeSS、AMD 光流与 SR 目标接入++用户要求把 AMD DLSS5 作为实验功能接入,并同时完成 XeSS FG、AMD 光流和 2K/4K/8K SR 目标。当前实现新增统一 SR 目标设置、专业模式 2K/4K/8K 选择、Intel XeSS 实验显示补帧 2X,以及 AMD FidelityFX 光流 provider 与半分辨率性能档。XeSS 只作用于预览,不能导出;AMD 光流只替换运动估算,不提供 AMD NR、DLSS SR、NVIDIA FRUC/DLSS 补帧、NVENC 或 AMD AMF。++专业模式第二页已按实际控件高度重排:补帧后端、光流后端、AMD 性能档、能力说明、光流档位、内容节奏和 FRUC 说明不再占用同一区域。此前新增说明文本与光流档位下拉框重叠,滚动时会影响可见性和点击范围;这是布局错误,不是渲染能力问题。++实际验证:`powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\build.ps1 -Root . -Preset x64-release` exit 0;`veyra_repair_contract_tests.exe` 36 项通过;`veyra_repair_preset_tests.exe .\logs\backend-20260910-final\presets.v1` 通过;RTX 5070 上 `veyra_experimental_backend_tests.exe xess` 成功初始化、标记资源并 Present,`generated=43`、`debugErrors=0`;`... amd` 成功执行 AMD OF Create/Dispatch/Destroy,`amdDispatches=48`、`debugErrors=0`;`... sr2k` 3 次 DLSS SR Evaluate 并读回得到非黑 `2560x1440`,`... sr8k` 3 次 Evaluate 并读回得到非黑 `7680x4320`。每个测试进程少于五秒。它们不证明真实扫描输出帧率、画质、AMD GPU 兼容性、实卡效果、8K 实时性或长期稳定性。++没有提交 NVIDIA SDK/runtime、模型、头文件、库、样例或测试媒体;没有 push、Release 或 Runtime Pack 变更。Phase 7 仍为 `in_progress`。本地 checkpoint 前还需复跑本轮构建和短测、检查 Git 跟踪范围与差异;AMD 实机兼容、XeSS 实际显示节奏、FRUC reset 像素和原生 NR 全链路性能仍未解决。+# 2026-09-10 2K / 8K SR 与 AMD NR 研究补充用户继续增加2K/8K超分和AMD显卡运行DLSS5的研究要求。按上一请求先写方案,交付 `docs/SR_TARGETS_AMD_NR_PLAN_2026-09-10.md`,同步XeSS方案/交接/loop研究记录。已确认Daniel HIP、RedDuke ZLUDA、Kien D3D12/HLSL三条真实技术路线;公开源码/作者自述/本机实测严格分开。推荐MIT D3D12网络作为RDNA4候选;其当前网络固定1080及SM6.10/FP8依赖、HIP原许可与无公开API、ZLUDA逐帧CPU等待与黑图问题均明确列出。社区4K60帖子混合FSR/FG,不能当原生4K NR60证据。diff --git a/docs/XESS_AMD_OPTICAL_FLOW_PLAN_2026-09-10.md b/docs/XESS_AMD_OPTICAL_FLOW_PLAN_2026-09-10.mdindex 1f5a384b..3b23829c 100644--- a/docs/XESS_AMD_OPTICAL_FLOW_PLAN_2026-09-10.md+++ b/docs/XESS_AMD_OPTICAL_FLOW_PLAN_2026-09-10.md@@ -1,10 +1,12 @@# XeSS 补帧与 AMD 光流接入方案-日期:2026-09-10。状态:研究完成,尚未实施。产品仍为 Phase 7 `in_progress`,本文不改变阶段门槛或默认处理路线。+日期:2026-09-10。状态:研究完成;已有窄范围产品接入,仍处于 Phase 7 `in_progress`。本文不改变阶段门槛或默认处理路线。-最新扩展:[2K / 8K 超分与 AMD NR 接入方案](SR_TARGETS_AMD_NR_PLAN_2026-09-10.md)。增加统一SR目标,并核对真正的AMD网络运行项目;AMD光流与AMD执行NR是两个不同模块。合并施工先做新方案S0,再按依赖接本文的AMD OF / XeSS步骤。两个文档均不是新增功能已运行的证明。+当前实现包含统一的 2K / 4K / 8K SR 目标、AMD FidelityFX 光流 provider 和 Intel XeSS-FG 代理交换链显示后端。`logs/backend-20260910` 的 RTX 5070 窄测记录了 AMD OF Create/Dispatch/Destroy 成功(48 次 dispatch)和 XeSS 初始化、资源标记、Present 成功(43 次 SDK generated 计数,debugErrors=0);SR 2K/8K 输出非黑。它们只证明该机器上的 SDK 调用链,**不证明** AMD GPU 兼容性、实际扫描输出帧率、画质、8K 实时性或长时稳定性。-用户要求:研究截图中作者提到的“DLSS5 + XeSS FG,以 AMD 光流给前两者提供运动信息”,先找方法、写方案。本轮只核对公开资料、源码和本地结构,没有运行新效果、占用采集卡或修改应用。+最新扩展:[2K / 8K 超分与 AMD NR 接入方案](SR_TARGETS_AMD_NR_PLAN_2026-09-10.md)。AMD 光流与 AMD 执行 NR 是两个不同模块:当前接入不提供 AMD DLSS5/NR、DLSS SR、NVIDIA FRUC、DLSS 帧生成、NVENC 或 AMD AMF 导出。该文保留 AMD NR 的后续研究路线,不能把已有光流实现写成 AMD DLSS5。++原始用户要求是研究截图中作者提到的“DLSS5 + XeSS FG,以 AMD 光流给前两者提供运动信息”。以下研究、接口合同和验收条件继续作为实现依据;其中“后续实施”段落应按当前已接入范围理解,尚未实际验收的部分仍需按证据完成。## 1. 结论与推荐@@ -212,7 +214,7 @@ R1 如没有速度收益但能在明确场景改善运动/NR,可以作为用## 9. 依赖与复用方式-本轮没有复制第三方代码进入产品或引入新 DLL。建议从官方接口和 AMD 明确许可的 OF 源文件实现,不需要复制 Magpie 的整套 Renderer/UI。+本轮没有复制 Magpie 代码进入产品或引入新的受版本控制 DLL。AMD OF 和 XeSS 开发依赖仍在本地忽略目录,产品以其公开接口独立接入,不需要复制 Magpie 的整套 Renderer/UI。- AMD 当前大 SDK 是混合许可证;已核对 OF `.h/.cpp` 和相关 shader 在 MIT 文件清单内,源文件本身也有 MIT notice。可以使用该子集,但必须保留逐文件来源、版权和完整 notice,不能把整个 Redstone SDK 当 MIT。- Intel `LICENSE.txt` 允许原样再分发二进制并保留许可/版权,禁止修改与逆向。后续成套 DLL、运行库、notice 和 manifest 外置,头文件不因 `main` 新增部分 MIT 文件就假定全部开放。本文不更改 Veyra 的 GPLv3;分发集成版时须核对相容性/所需链接许可,不能仅凭外置 DLL 判定已解决。@@ -222,15 +224,15 @@ R1 如没有速度收益但能在明确场景改善运动/NR,可以作为用## 10. 本轮结果与下一步-实际执行:Git 状态/日志、`rg`与源码读取、`gh api` 查询 Magpie/Intel/AMD 的固定提交、树、Release和compare,以及官方 raw 文档/源码下载到忽略目录;本机 Magpie版本读取;应用和指定NR hash/签名核对。+实际执行:Git 状态/日志、`rg`与源码读取、`gh api` 查询 Magpie/Intel/AMD 的固定提交、树、Release和compare,以及官方 raw 文档/源码下载到忽略目录;本机 Magpie版本读取;应用和指定NR hash/签名核对。随后完成 Release 构建,并执行契约、预设、XeSS 和 AMD OF 短测。-没有构建、没有执行 FFX Create/Dispatch、XeSS/XeLL 初始化或新的 RTX/NGX/实卡测试。可行性判断依据接口与实现,不是性能实测。+`veyra_repair_contract_tests.exe` 的 36 项检查通过;`veyra_repair_preset_tests.exe` 使用临时预设文件路径通过。RTX 5070 上的 `veyra_experimental_backend_tests.exe xess` 成功完成 XeSS 初始化、资源标记和 Present,记录 `generated=43`、`debugErrors=0`;`... amd` 成功完成 AMD OF Create/Dispatch/Destroy,记录 `amdDispatches=48`、`debugErrors=0`;`... sr2k` 与 `... sr8k` 各完成三次 DLSS SR Evaluate,并读回确认非黑的 `2560x1440` 与 `7680x4320` 输出。每项执行均少于五秒。这些短测只证明本机 SDK 调用、资源提交和所测 SR 输出,不证明真实扫描输出帧率、画质、AMD GPU 兼容性、实卡效果、8K 实时性或长期稳定性。-应用 EXE 仍为上一轮 UI 修复:SHA256 `E97B716B99116BEC942262FFEF1612299CBB2F4B0BDA7C308A5BFF318B3B5157`。指定 NR hash仍为 `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`,签名 Valid。本轮仅新增本文并同步 WORKLOG/交接索引,不修改控制面或原始产品方案。+本轮应用 EXE 由当前 Release 构建生成;指定 NR hash 仍为 `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`,签名 Valid。没有修改控制面或原始产品方案,没有 push、Release 或 Runtime Pack 变更。查询失败留实记录:尝试 Intel Release 名称 `v3.0` 得到404,随后采用已核实存在的 `v3.0.2`;一次 Windows `rg`字面通配路径失败,已改用结构化manifest及实际文件枚举。均非效果测试失败或成功。-本文原下一条任务为R0/R1的AMD光流诊断。用户随后新增2K/8K及AMD NR要求,合并后的下一条实施任务以 [补充方案](SR_TARGETS_AMD_NR_PLAN_2026-09-10.md) 的S0为准;本文R0/R1仍保留在后续步骤。研究阶段不自动运行未验证后端。+本文原下一条任务为R0/R1的AMD光流诊断,现已完成窄范围实现与 SDK 提交测试。下一步是 AMD 实机兼容性、真实呈现节奏和画质对照;AMD NR 的后续边界仍以 [补充方案](SR_TARGETS_AMD_NR_PLAN_2026-09-10.md) 为准。当前不把实验后端标为可交付的 AMD DLSS5。## 11. 原始来源diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex e46bdcb6..3ea7292e 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -3,11 +3,28 @@#include <array>#include <cstdint>#include <string>+#include <string_view>#include "veyra/pipeline/ResolutionPlan.h"namespace veyra::engine {-enum class FrameGenerationBackend { Dlss, Fruc };+enum class FrameGenerationBackend { Dlss, Fruc, XeSS };enum class FlowQuality { Performance, Balanced, Quality };+enum class OpticalFlowBackend { Nvidia, AmdFidelityFx };enum class ContentRate { Transport, Auto, Fps30, Fps50, Fps60, Capture60To30 };+constexpr std::string_view frameGenerationBackendName(FrameGenerationBackend backend) {+ switch(backend) {+ case FrameGenerationBackend::Dlss: return "DLSS";+ case FrameGenerationBackend::Fruc: return "FRUC";+ case FrameGenerationBackend::XeSS: return "XeSS";+ }+ return "unknown";+}+constexpr std::string_view opticalFlowBackendName(OpticalFlowBackend backend) {+ switch(backend) {+ case OpticalFlowBackend::Nvidia: return "NVIDIA_NVOF";+ case OpticalFlowBackend::AmdFidelityFx: return "AMD_FIDELITYFX_OF";+ }+ return "unknown";+}struct NrSettings {float intensity=1,tone=1,structure=1,skin=-1;int32_t style=0,autoMask=0,uiCorrection=0;@@ -40,11 +57,14 @@ struct EnhancementSettings {ResidualSettings residual;ProtectionSettings protection;bool nr=true,sr=false;+ pipeline::SrTarget srTarget=pipeline::SrTarget::Uhd4K;uint32_t videoSrQuality=0; // 0 DLSS SR; 1–4 RTX Video SRuint32_t multiplier=1;FrameGenerationBackend frameGenerationBackend=FrameGenerationBackend::Dlss;pipeline::NrSizePolicy nrPolicy=pipeline::NrSizePolicy::Realtime;FlowQuality flow=FlowQuality::Balanced;+ OpticalFlowBackend opticalFlowBackend=OpticalFlowBackend::Nvidia;+ bool amdFlowHalfResolution=false;ContentRate content=ContentRate::Transport;bool operator==(const EnhancementSettings&) const = default;std::string validate() const {@@ -55,8 +75,11 @@ struct EnhancementSettings {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(frameGenerationBackend!=FrameGenerationBackend::Dlss&&frameGenerationBackend!=FrameGenerationBackend::Fruc)return "invalid frame generation backend";+ if(frameGenerationBackend<FrameGenerationBackend::Dlss||frameGenerationBackend>FrameGenerationBackend::XeSS)return "invalid frame generation backend";+ if(frameGenerationBackend==FrameGenerationBackend::XeSS&&multiplier>2)return "XeSS preview currently supports 2X only";if(videoSrQuality>4)return "invalid video SR quality";+ if(!pipeline::validSrTarget(srTarget))return "invalid SR target";+ if(opticalFlowBackend!=OpticalFlowBackend::Nvidia&&opticalFlowBackend!=OpticalFlowBackend::AmdFidelityFx)return "invalid optical flow backend";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::Capture60To30)return "invalid flow/content mode";diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex f911435e..1f931fab 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -16,6 +16,8 @@ public:// Explicit integration-test capture only; never called by playback/export.bool readPresentedFrameForTest(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,sink::RgbaImage&);uint64_t submittedCount() const {return sink_.presentCount();}+ uint64_t xessGeneratedCount() const {return sink_.xess()?sink_.xess()->generatedCount():0;}+ bool xessActive() const {return sink_.xess()!=nullptr;}diagnostics::GpuSample blitTiming(ID3D12Fence* f,uint64_t revision=0){gpuTimer_.collect(f);if(revision&&gpuTimer_.last().identity.settingsRevision!=revision){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}private:diagnostics::GpuTimer gpuTimer_;@@ -26,6 +28,9 @@ private:unsigned lastBuffer_=0;bool hasPresented_=false;HWND window_=nullptr;std::chrono::steady_clock::time_point lastResize_{};+ std::chrono::steady_clock::time_point lastXessFrame_{};+ pipeline::FrameIdentity lastXessIdentity_{};+ bool xessWasEnabled_=false;void refresh(ID3D12Device*);};}diff --git a/include/veyra/gfx/D3D12DeviceContext.h b/include/veyra/gfx/D3D12DeviceContext.hindex 4e8bf2e4..1db76c63 100644--- a/include/veyra/gfx/D3D12DeviceContext.h+++ b/include/veyra/gfx/D3D12DeviceContext.h@@ -29,6 +29,7 @@ struct AdapterInfo {struct DeviceContextDesc {bool enableDebugLayer = false;uint32_t commandSlotCount = 4;+ uint32_t requiredVendorId = 0; // 0: highest-performance hardware adapter};// One DXGI adapter + one ID3D12Device + one direct command queue + one fence@@ -63,6 +64,7 @@ public:const AdapterInfo& adapter() const { return adapterInfo_; }const std::string& featureLevelString() const { return featureLevel_; }uint32_t commandSlotCount() const { return commandSlotCount_; }+ bool videoMemoryInfo(uint64_t& budget,uint64_t& usage) const;// CPU wait until `value` completes; returns false on wait timeout/failure.bool waitForFenceValue(uint64_t value, uint32_t timeoutMs = 10000);diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.hindex 14582218..b365e3bb 100644--- a/include/veyra/gfx/PresentSink.h+++ b/include/veyra/gfx/PresentSink.h@@ -15,6 +15,7 @@#include <string>#include "veyra/Result.h"+#include "veyra/gfx/XessPresenter.h"namespace veyra::gfx {@@ -33,6 +34,7 @@ public:uint32_t width = 1280;uint32_t height = 720;bool vsync = true;+ bool xess = false;// Probe runs create their own window class name per process.std::wstring title = L"Veyra";HWND targetWindow = nullptr; // borrowed UI-owned child HWND; never destroyed by sink@@ -69,6 +71,7 @@ public:bool tearingSupported() const { return tearingSupported_; }HWND hwnd() const { return hwnd_; }IDXGISwapChain3* swapChain() const { return swapChain_.Get(); }+ XessPresenter* xess() const { return xess_.get(); }void shutdown();@@ -76,6 +79,7 @@ private:static LRESULT CALLBACK wndProcThunk(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp);bool refetchBackBuffers();+ bool waitForQueueIdle();void recreateSwapChain(UINT flags);HWND hwnd_ = nullptr;@@ -96,6 +100,7 @@ private:ID3D12CommandQueue* queue_ = nullptr;ComPtr<IDXGIFactory2> factory_;ComPtr<IDXGISwapChain3> swapChain_;+ std::unique_ptr<XessPresenter> xess_;ComPtr<ID3D12Resource> backBuffers_[3];UINT backBufferIndex_ = 0;bool closed_ = false;diff --git a/include/veyra/gfx/XessPresenter.h b/include/veyra/gfx/XessPresenter.hnew file mode 100644index 00000000..51d23aaa--- /dev/null+++ b/include/veyra/gfx/XessPresenter.h@@ -0,0 +1,23 @@+#pragma once+#include <d3d12.h>+#include <dxgi1_6.h>+#include <cstdint>+#include <memory>++namespace veyra::gfx {+class XessPresenter {+public:+ XessPresenter();+ ~XessPresenter();+ bool initialize(ID3D12Device*,ID3D12CommandQueue*,IDXGIFactory2*,HWND,const DXGI_SWAP_CHAIN_DESC1&,IDXGISwapChain3**);+ bool beginFrame();+ bool tag(ID3D12GraphicsCommandList*,ID3D12Resource* color,ID3D12Resource* motion,ID3D12Resource* depth,+ RECT region,bool enabled,bool reset,float elapsedMs);+ bool beforePresent();+ bool afterPresent();+ uint64_t generatedCount() const;+private:+ struct Impl;+ std::unique_ptr<Impl> p_;+};+}diff --git a/include/veyra/guidance/AmdOpticalFlow.h b/include/veyra/guidance/AmdOpticalFlow.hnew file mode 100644index 00000000..1a715c82--- /dev/null+++ b/include/veyra/guidance/AmdOpticalFlow.h@@ -0,0 +1,24 @@+#pragma once+#include <d3d12.h>+#include <cstdint>+#include <memory>++namespace veyra::guidance {+// Records FidelityFX OF on the application's queue. The caller drains that+// queue before destruction; input/output return to their incoming states.+class AmdOpticalFlow {+public:+ AmdOpticalFlow();+ ~AmdOpticalFlow();+ bool initialize(ID3D12Device*,uint32_t width,uint32_t height);+ bool dispatch(ID3D12GraphicsCommandList*,ID3D12Resource* color,bool reset);+ ID3D12Resource* vectors() const;+ ID3D12Resource* sceneChanges() const;+ bool warmedUp() const;+ uint32_t width() const;+ uint32_t height() const;+private:+ struct Impl;+ std::unique_ptr<Impl> p_;+};+}diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 7ef92252..18bfe413 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -33,6 +33,7 @@ struct AVFrame;struct SwsContext;struct NVSDK_NGX_Parameter;struct NVSDK_NGX_Handle;+namespace veyra::guidance { class AmdOpticalFlow; }namespace veyra::gfx {class D3D12DeviceContext;@@ -74,6 +75,8 @@ struct EnhanceGraphDesc {engine::FrameGenerationBackend frameGenerationBackend=engine::FrameGenerationBackend::Dlss;uint64_t settingsRevision=1;engine::FlowQuality flowQuality=engine::FlowQuality::Balanced;+ engine::OpticalFlowBackend opticalFlowBackend=engine::OpticalFlowBackend::Nvidia;+ bool amdFlowHalfResolution=false;engine::ContentRate contentRate=engine::ContentRate::Transport;engine::NrSettings model;engine::ResidualSettings residual;@@ -139,6 +142,7 @@ public:uint64_t nrEvaluateCount = 0;uint64_t srEvaluateCount = 0;uint64_t nvofExecuteCount = 0;+ uint64_t amdOfExecuteCount = 0;uint64_t nvofFrameFailures = 0;uint64_t fgGeneratedFrames = 0;uint64_t fgSubmittedCandidates = 0, fgDisabledFrames = 0;@@ -164,6 +168,11 @@ public:bool srEnabled() const { return srEnabled_; }bool nrEnabled() const { return nrEnabled_; }bool fgEnabled() const { return fgEnabled_; }+ bool xessEnabled() const { return desc_.enableFg && !desc_.noFeatures && !desc_.stillImage && desc_.frameGenerationBackend==engine::FrameGenerationBackend::XeSS; }+ ID3D12Resource* presentMotion(uint32_t slot) const { return presentMotion_[slot%2].Get(); }+ ID3D12Resource* presentDepth() const { return depthTex_.Get(); }+ bool presentMotionValid(uint32_t slot) const { return presentMotionValid_[slot%2]; }+ uint64_t motionPreviousSource(uint32_t slot) const { return motionPreviousSource_[slot%2]; }uint64_t lastNvofSignal() const;// Present-side access to the produced frame slots (probe sink path).@@ -227,6 +236,9 @@ private:ComPtr<ID3D12Resource> workRgba_;ComPtr<ID3D12Resource> videoSrInput_,videoSrOutput_;ComPtr<ID3D12Resource> nrInput_,residualRgba_,nrFlow_,baseFlow_;+ ComPtr<ID3D12Resource> presentMotion_[2];+ bool presentMotionValid_[2]={};+ uint64_t motionPreviousSource_[2]={},previousSource_=0;ComPtr<ID3D12Resource> proxyTex_;ComPtr<ID3D12Resource> neuralTex_;ComPtr<ID3D12Resource> finalRgba_;@@ -263,6 +275,7 @@ private:std::unique_ptr<ngx::NgxCoreHost> coreHost_;std::unique_ptr<ngx::DlssNrRuntimeAdapter> nrAdapter_;std::unique_ptr<ngx::DlssSrBackend> srBackend_;+ std::unique_ptr<guidance::AmdOpticalFlow> amdOf_;std::unique_ptr<ngx::VideoSrBackend> videoSrBackend_;std::unique_ptr<ngx::DlssFgBackend> fgBackend_;std::unique_ptr<ngx::FrucBackend> frucBackend_;diff --git a/include/veyra/pipeline/ResolutionPlan.h b/include/veyra/pipeline/ResolutionPlan.hindex 75eacaf0..2037e837 100644--- a/include/veyra/pipeline/ResolutionPlan.h+++ b/include/veyra/pipeline/ResolutionPlan.h@@ -10,14 +10,25 @@ struct Extent {bool valid() const {return width>=1&&height>=1&&width<=16384&&height<=16384;}};enum class NrSizePolicy { Realtime, Native };+enum class SrTarget : uint32_t { Qhd, Uhd4K, Uhd8K };+constexpr bool validSrTarget(SrTarget target) { return target<=SrTarget::Uhd8K; }+constexpr Extent srTargetExtent(SrTarget target) {+ switch(target) {+ case SrTarget::Qhd:return {2560,1440};+ case SrTarget::Uhd4K:return {3840,2160};+ case SrTarget::Uhd8K:return {7680,4320};+ }+ return {};+}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) {+ static ResolutionPlan make(Extent source,bool sr,NrSizePolicy policy,bool exporting,uint64_t revision=0,SrTarget target=SrTarget::Uhd4K) {if(!source.valid())throw std::invalid_argument("invalid SDR source extent");+ if(!validSrTarget(target))throw std::invalid_argument("invalid SR target");ResolutionPlan p; p.source=source;p.base=source;- if(sr){const double scale=std::min(3840.0/source.width,2160.0/source.height);if(scale>1.0)p.base={std::max(2u,uint32_t(source.width*scale+1e-6)&~1u),std::max(2u,uint32_t(source.height*scale+1e-6)&~1u)};}+ if(sr){const auto limit=srTargetExtent(target);const double scale=std::min(double(limit.width)/source.width,double(limit.height)/source.height);if(scale>1.0)p.base={std::max(2u,uint32_t(source.width*scale+1e-6)&~1u),std::max(2u,uint32_t(source.height*scale+1e-6)&~1u)};}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});diff --git a/loop/JOURNAL.md b/loop/JOURNAL.mdindex 7255d4de..5034ce01 100644--- a/loop/JOURNAL.md+++ b/loop/JOURNAL.md@@ -1,5 +1,11 @@# Veyra Loop Journal+## 2026-09-10 XeSS, AMD OF and SR target implementation++User authorized implementation of experimental AMD DLSS5-related options, XeSS FG, AMD optical flow and SR targets. The committed worktree candidate adds 2K/4K/8K target selection, AMD FidelityFX optical-flow dispatch, XeSS proxy-swapchain display FG and adapter-specific capability messages. Professional-page layout was corrected after static inspection found the AMD/XeSS explanation text overlapped the NVOF-quality combo box.++Actual commands: Release build exited 0; `veyra_repair_contract_tests.exe` reported 36 checks and 0 failures; `veyra_repair_preset_tests.exe .\\logs\\backend-20260910-final\\presets.v1` passed; RTX 5070 `veyra_experimental_backend_tests.exe xess` passed with generated=43 and debugErrors=0; `... amd` passed with amdDispatches=48 and debugErrors=0; `... sr2k` and `... sr8k` each performed 3 DLSS SR Evaluates and read back nonblack 2560x1440 and 7680x4320 outputs. Each test process was under five seconds. The executable tests prove local SDK submission and the tested SR outputs only; they do not prove scanout FPS, visual quality, AMD-GPU compatibility, 8K realtime behavior, physical capture behavior or long-term stability. No runtime/SDK/media was tracked, and no remote mutation occurred. Phase 7 remains in progress; FRUC reset pixels and full native-NR performance remain open.+## 2026-09-10 SR targets and AMD NR research planScope follows the user's preceding plan-first request, extended with 2K/8K SR targets and actual AMD GPU NR research. Read-only source/API/license/hardware inspection is complete; next write the implementation supplement and cross-link the XeSS/AMD OF plan and handoff. No product code, runtime, driver, protected control or remote changes. Hypothesis to preserve for implementation: a native D3D12 network port is a viable candidate, not yet a verified Veyra backend. Validation for this documentation task: source citations, local links/fences, JSON parse and git diff --check; no GPU gate or new backend success will be claimed.diff --git a/shaders/NvofDensify.hlsl b/shaders/NvofDensify.hlslindex 4e77b642..ef47d8d4 100644--- a/shaders/NvofDensify.hlsl+++ b/shaders/NvofDensify.hlsl@@ -6,6 +6,7 @@ Texture2D<int2> rawFlow : register(t0); // grid-extent SHORT2Texture2D<float4> previousColor : register(t2);Texture2D<float4> currentColor : register(t3);Texture2D<uint> rawCost : register(t1); // grid-extent cost (0..255, higher = worse)+Texture2D<uint> sceneChanges : register(t4); // FidelityFX SCD: history bits at (1,0)RWTexture2D<float2> flowOut : register(u0); // source extent, pixelsRWTexture2D<float> confOut : register(u1); // source extent [0,1], cost and reprojection@@ -26,12 +27,17 @@ cbuffer NvofDensifyConstants : register(b0)void main(uint3 globalId : SV_DispatchThreadID){if (globalId.x >= workingW || globalId.y >= workingH) return;+ // FidelityFX excludes frame indices 0..5 and the four-frame cut history.+ if ((validationFlags & 8u) != 0 || ((validationFlags & 4u) != 0 && (sceneChanges[uint2(1,0)] & 15u) != 0)) {+ flowOut[globalId.xy]=0;confOut[globalId.xy]=0;return;+ }const uint gx = min(globalId.x / gridSize, gridW - 1);const uint gy = min(globalId.y / gridSize, gridH - 1);const int2 raw = rawFlow[uint2(gx, gy)];- float2 v = float2(raw) / 32.0; // S10.5 -> float pixels (fixed)+ const bool amd = (validationFlags & 4u) != 0;+ float2 v = float2(raw) / (amd ? 1.0 : 32.0);if (negate != 0) v = -v;- const uint cost = rawCost[uint2(gx, gy)];+ const uint cost = amd ? 0 : rawCost[uint2(gx, gy)];// Higher cost = less reliable: confidence falls as cost rises.float confidence = float(255u - min(cost, 255u)) / 255.0;if (cost >= costThreshold) { v = 0; confidence = 0; }diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 168f7e8c..da0770b8 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -100,12 +100,20 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;gd.rgbInput=isImage||(isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Bgra8);gd.yuy2Input=isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Yuy2;gd.stillImage=isImage;- const auto resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,1);+ const auto resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision,options.settings.srTarget);gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;- gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;+ const bool nvidiaAdapter=ctx.adapter().isNvidia;+ const bool xessFg=options.settings.frameGenerationBackend==FrameGenerationBackend::XeSS;+ gd.enableSr=resolution.srApplied&&nvidiaAdapter;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr&&nvidiaAdapter;gd.enableFg=options.fg&&(nvidiaAdapter||xessFg);gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=gd.enableNr;gd.noFeatures=false;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;+ gd.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"增强初始化失败,请核对本地运行时",true);break;}+ if(!nvidiaAdapter&&(options.nr||options.sr||(options.fg&&!xessFg))){+ veyra::log::warn("capability",std::format("non-NVIDIA adapter disabled requested features: nr={} sr={} fgBackend={} flowBackend={}",options.nr,options.sr,frameGenerationBackendName(options.settings.frameGenerationBackend),opticalFlowBackendName(options.settings.opticalFlowBackend)));+ status(L"当前非 NVIDIA 适配器:NR、NVIDIA 超分与 DLSS/FRUC 已禁用;可使用 XeSS 预览和 AMD 光流",false);+ }+ if(graph.xessEnabled()&&!presenter.xessActive())status(L"XeSS 未启用:运行时或设备不兼容;当前为普通呈现",false);if(physicalCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}{std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.running=true;snapshot_.transport=TransportState::Playing;snapshot_.image=isImage;snapshot_.capture=isCapture;snapshot_.applied=options.snapshot();snapshot_.desired=desired_;}status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isCapture?L"实时采集":L"播放",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)"));@@ -149,16 +157,22 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(requested.revision!=previous.revision){drainLivePresentation();auto next=PlayerOptions::from(requested);auto nextDesc=gd;- const auto plan=pipeline::ResolutionPlan::make({width,height},next.sr,requested.nrPolicy,isImage,requested.revision);+ const auto plan=pipeline::ResolutionPlan::make({width,height},next.sr,requested.nrPolicy,isImage,requested.revision,requested.srTarget);nextDesc.workWidth=plan.base.width;nextDesc.workHeight=plan.base.height;nextDesc.nrWidth=plan.nr.width;nextDesc.nrHeight=plan.nr.height;nextDesc.flowWidth=plan.flow.width;nextDesc.flowHeight=plan.flow.height;- nextDesc.enableSr=plan.srApplied;nextDesc.videoSrQuality=next.settings.videoSrQuality;nextDesc.enableNr=next.nr;nextDesc.enableFg=next.fg;nextDesc.fgMultiplier=next.fgMultiplier;nextDesc.frameGenerationBackend=next.settings.frameGenerationBackend;nextDesc.enableNvofStandalone=next.nr;+ const bool nvidiaAdapter=ctx.adapter().isNvidia;+ const bool xessFg=next.settings.frameGenerationBackend==FrameGenerationBackend::XeSS;+ nextDesc.enableSr=plan.srApplied&&nvidiaAdapter;nextDesc.videoSrQuality=next.settings.videoSrQuality;nextDesc.enableNr=next.nr&&nvidiaAdapter;nextDesc.enableFg=next.fg&&(nvidiaAdapter||xessFg);nextDesc.fgMultiplier=next.fgMultiplier;nextDesc.frameGenerationBackend=next.settings.frameGenerationBackend;nextDesc.enableNvofStandalone=nextDesc.enableNr;nextDesc.model=requested.model;nextDesc.residual=requested.residual;nextDesc.protection=requested.protection;nextDesc.settingsRevision=requested.revision;nextDesc.flowQuality=requested.flow;nextDesc.contentRate=requested.content;- const bool rebuild=gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||(nextDesc.frameGenerationBackend==FrameGenerationBackend::Fruc&&(gd.fgMultiplier!=nextDesc.fgMultiplier||gd.enableFg!=nextDesc.enableFg))||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;+ nextDesc.opticalFlowBackend=requested.opticalFlowBackend;nextDesc.amdFlowHalfResolution=requested.amdFlowHalfResolution;+ const bool rebuild=gd.opticalFlowBackend!=nextDesc.opticalFlowBackend||gd.amdFlowHalfResolution!=nextDesc.amdFlowHalfResolution||gd.enableNr!=nextDesc.enableNr||gd.enableFg!=nextDesc.enableFg||gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||gd.fgMultiplier!=nextDesc.fgMultiplier||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;bool accepted=ring.drainQueue();out={};hasOutput=false;if(accepted&&rebuild){presenter.close();graph.shutdown();accepted=graph.initialize(nextDesc)&&presenter.open(ctx,window,graph)&&graph.createViews();if(!accepted){presenter.close();graph.shutdown();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"设置失败且旧资源恢复失败,已停止",true);break;}}}else if(accepted)accepted=graph.applySettings(requested);- if(accepted){options=next;gd=nextDesc;transaction=true;reset=true;}+ if(accepted){+ options=next;gd=nextDesc;transaction=true;reset=true;+ if(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))veyra::log::warn("capability",std::format("non-NVIDIA adapter disabled requested settings revision={} nr={} sr={} fgBackend={} flowBackend={}",requested.revision,next.nr,next.sr,frameGenerationBackendName(requested.frameGenerationBackend),opticalFlowBackendName(requested.opticalFlowBackend)));+ }else {std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_.revision!=previous.revision;snapshot_.status=L"设置应用失败,已恢复上一套参数";}}const double seek=seekSeconds_.exchange(-1);@@ -230,7 +244,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){}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,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)");veyra::log::info("settings",std::format("Applied revision={} sourcePtsMs={} backend={} multiplier={} (source kept open)",options.settings.revision,pts,options.settings.frameGenerationBackend==FrameGenerationBackend::Fruc?"FRUC":"DLSS",options.snapshot().multiplier));}+ if(transaction){std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_.revision!=options.settings.revision;snapshot_.status=std::format(L"输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)");veyra::log::info("settings",std::format("Applied revision={} sourcePtsMs={} fgBackend={} flowBackend={} multiplier={} (source kept open)",options.settings.revision,pts,frameGenerationBackendName(options.settings.frameGenerationBackend),opticalFlowBackendName(options.settings.opticalFlowBackend),options.snapshot().multiplier));}if(veyra::log::verboseFrameLogs())veyra::log::info("source-identity",std::format("source={} totalRead={} graphProcessed={} cached={} revision={} nvofStandalone={}",pkt.sequence,sourceFrames,frames+1,rereadCached,options.settings.revision,gd.enableNvofStandalone));reset=false;hasOutput=true;const auto processDone=Clock::now();processTimes.add(elapsedMs(processStart));@@ -325,8 +339,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){diagnostics::FrameMetrics measured;pipeline::EnhanceGraph::Metrics graphStats;uint64_t slotWaitCount=0,commandSubmits=0;double slotWaitMilliseconds=0;{std::lock_guard gpuLock(gpuMutex);measured=graph.gpuMetrics();graphStats=graph.metrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence(),options.settings.revision);slotWaitCount=ring.cpuWaitCount()-slotWaitBase;slotWaitMilliseconds=ring.cpuWaitMilliseconds()-slotWaitMsBase;commandSubmits=ring.submitCount()-submitBase;}if(measured.identity.settingsRevision!=options.settings.revision){measured={};measured.identity=out.batch.identity;for(auto& sample:measured.gpu)sample.state=diagnostics::SampleState::Pending;}+ if(graph.xessEnabled()){+ std::lock_guard gpuLock(gpuMutex);+ graphStats.fgGeneratedFrames=presenter.xessGeneratedCount();+ }for(size_t stage=0;stage<measured.gpu.size();++stage){const auto& sample=measured.gpu[stage];if(sample.state==diagnostics::SampleState::Measured&&sample.milliseconds&&sample.end&&sample.end!=lastGpuSampleEnd[stage]){gpuStageTimes[stage].add(*sample.milliseconds);lastGpuSampleEnd[stage]=sample.end;}}- measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.submitted=submitted;measured.expired=expired;measured.sourceFrames=sourceFrames-statsSourceBase;measured.validGenerated=graphStats.fgGeneratedFrames-statsGeneratedBase;measured.queueWatermark=out.batch.count;+ measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision,options.settings.srTarget);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.submitted=submitted;measured.expired=expired;measured.sourceFrames=sourceFrames-statsSourceBase;measured.validGenerated=graphStats.fgGeneratedFrames-statsGeneratedBase;measured.queueWatermark=out.batch.count;LiveStats completed;if(liveWorker){std::lock_guard statsLock(liveStatsMutex);completed=liveStats;}const double ageP95=liveWorker?completed.ageP95:captureAges.p95(),waitP95=liveWorker?completed.waitP95:scheduleWaits.p95(),presentP95=liveWorker?completed.presentP95:presentTimes.p95();++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;if(liveWorker)snapshot_.submissionFps=completed.fps;else snapshot_.submissionFps=submissionTimes.size()>1?double(submissionTimes.size()-1)*1e7/(submissionTimes.back()-submissionTimes.front()):0;snapshot_.position=pts/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];snapshot_.fps=(sourceFrames-statsSourceBase)/std::max(0.001,std::chrono::duration<double>(Clock::now()-statsStart).count());diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cppindex e07f1635..5b6fa365 100644--- a/src/engine/PresetStore.cpp+++ b/src/engine/PresetStore.cpp@@ -13,18 +13,20 @@ bool nameOk(const std::wstring& s){return !s.empty()&&s.size()<=48&&s.front()!=Lstd::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 4\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';- for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<'\n';}return o.str();+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 6\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';+ for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<'\n';}return o.str();}bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std::wstring& def){if(data.size()>65536)return false;std::istringstream in(data);in.imbue(std::locale::classic());std::string magic,d;int version=0;size_t count=0;- if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version!=1&&version!=2&&version!=3&&version!=4)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;+ if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>6)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;for(size_t i=0;i<count;++i){UserPreset p;std::string n;int policy,flow,content,nr,sr;auto& s=p.settings;auto& m=s.model;auto& r=s.residual;if(!(in>>std::quoted(n)>>m.intensity>>m.tone>>m.structure>>m.skin>>m.style>>m.autoMask>>m.uiCorrection>>r.total>>r.darken>>r.brighten>>r.color>>r.luminance>>nr>>sr>>s.multiplier>>policy>>flow>>content))return false;if(version>=2){int enabled;if(!(in>>enabled>>s.protection.featherPixels)||enabled<0||enabled>1)return false;s.protection.enabled=enabled!=0;for(auto& q:s.protection.regions)if(!(in>>q.left>>q.top>>q.right>>q.bottom))return false;}if(version>=3&&!(in>>s.videoSrQuality))return false;- if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>1)return false;s.frameGenerationBackend=static_cast<FrameGenerationBackend>(backend);}+ if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>(version>=6?2:1))return false;s.frameGenerationBackend=static_cast<FrameGenerationBackend>(backend);}+ if(version>=5){uint32_t target;if(!(in>>target))return false;s.srTarget=static_cast<pipeline::SrTarget>(target);}+ if(version>=6){int backend,half;if(!(in>>backend>>half)||half<0||half>1)return false;s.opticalFlowBackend=static_cast<OpticalFlowBackend>(backend);s.amdFlowHalfResolution=half!=0;}p.name=wide(n);if(!nameOk(p.name)||std::any_of(out.begin(),out.end(),[&](auto& a){return a.name==p.name;})||nr<0||nr>1||sr<0||sr>1)return false;s.nr=nr;s.sr=sr;s.nrPolicy=static_cast<pipeline::NrSizePolicy>(policy);s.flow=static_cast<FlowQuality>(flow);s.content=static_cast<ContentRate>(content);if(!s.validate().empty())return false;out.push_back(std::move(p));diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex ec51bdae..069fded6 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -21,6 +21,11 @@ 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,const std::function<bool()>& frameBoundary,const std::function<void(const ExportCounts&)>& counts){if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial")){progress(0,L"目标或partial文件已存在,请使用其他名称");return false;}+ if(options.fg&&options.settings.frameGenerationBackend==FrameGenerationBackend::XeSS){+ progress(0,L"XeSS 帧生成目前仅支持预览;导出请选择 DLSS、FRUC 或关闭补帧");+ veyra::log::warn("export","XeSS FG export rejected: public XeSS swapchain API has no encoder texture output contract");+ 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;@@ -28,8 +33,13 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptitry { 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;+ if(!ctx.adapter().isNvidia){+ progress(0,L"当前视频导出使用 NVIDIA NVENC;尚未实现 AMD AMF 或 Intel 编码后端");+ veyra::log::warn("export","export rejected: selected adapter has no NVIDIA NVENC; AMD AMF and Intel encoder backends are not implemented");+ 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 auto info=source.info();if(!pipeline::Extent{info.width,info.height}.valid()){progress(0,L"输入尺寸超出GPU单纹理能力");break;}// 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;@@ -41,8 +51,8 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptisource.close();if(!source.open(od))break; // reopen from the true beginning, including negative PTSconst 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));- const auto resolution=pipeline::ResolutionPlan::make({info.width,info.height},options.sr,pipeline::NrSizePolicy::Native,true,options.settings.revision);- pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ const auto resolution=pipeline::ResolutionPlan::make({info.width,info.height},options.sr,pipeline::NrSizePolicy::Native,true,options.settings.revision,options.settings.srTarget);+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().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;diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 2f73f7a2..83cb1805 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -7,6 +7,7 @@ namespace veyra::engine {bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph) {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;+ d.xess=graph.xessEnabled();lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=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,12))return false;@@ -25,8 +26,9 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&if((unsigned(rc.right)!=sink_.width()||unsigned(rc.bottom)!=sink_.height())&&GetTickCount64()>=deferUntil&&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;+ refresh(ctx.device());lastResize_=now;xessWasEnabled_=false;}+ if(sink_.xess()&&!sink_.xess()->beginFrame())return false;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;@@ -55,6 +57,34 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&if(veyra::log::verboseFrameLogs())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);+ if(auto* xess=sink_.xess()){+ const float fit=std::min(float(sink_.bufferWidth())/graph.workWidth(),float(sink_.bufferHeight())/graph.workHeight());+ const LONG w=std::max(1L,LONG(std::lround(graph.workWidth()*fit))),h=std::max(1L,LONG(std::lround(graph.workHeight()*fit)));+ const LONG left=(LONG(sink_.bufferWidth())-w)/2,top=(LONG(sink_.bufferHeight())-h)/2;+ const bool enabled=!generated&&!comparison&&view==PreviewView{}&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastXessIdentity_.sourceFrameId;+ const bool reset=!xessWasEnabled_||identity.epoch!=lastXessIdentity_.epoch||identity.settingsRevision!=lastXessIdentity_.settingsRevision||graph.motionPreviousSource(slot)!=lastXessIdentity_.sourceFrameId;+ const float elapsed=lastXessFrame_==std::chrono::steady_clock::time_point{}?0.0f:float(std::chrono::duration<double,std::milli>(now-lastXessFrame_).count());+ auto* motion=graph.presentMotion(slot);+ auto* depth=graph.presentDepth();+ if(enabled){+ // XeSS-FG ONLY_NOW records its input copies on this same command+ // list. Keep the Veyra state contract explicit on both sides.+ ID3D12Resource* resources[]={bb,motion,depth};+ D3D12_RESOURCE_BARRIER toCopy[3]{};+ for(unsigned i=0;i<3;++i){+ toCopy[i].Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ toCopy[i].Transition.pResource=resources[i];+ toCopy[i].Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;+ toCopy[i].Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;+ toCopy[i].Transition.StateAfter=D3D12_RESOURCE_STATE_COPY_SOURCE;+ }+ list->ResourceBarrier(3,toCopy);+ if(!xess->tag(list,bb,motion,depth,{left,top,left+w,top+h},true,reset,elapsed))return false;+ for(auto& barrier:toCopy)std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);+ list->ResourceBarrier(3,toCopy);+ }else if(!xess->tag(list,bb,motion,depth,{left,top,left+w,top+h},false,reset,elapsed))return false;+ lastXessFrame_=now;lastXessIdentity_=identity;xessWasEnabled_=enabled;+ }gpuTimer_.mark(list,diagnostics::GpuStage::Blit,true);gpuTimer_.resolve(list);if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());lastBuffer_=sink_.swapChain()->GetCurrentBackBufferIndex();hasPresented_=true;return sink_.present(st);}diff --git a/src/gfx/D3D12DeviceContext.cpp b/src/gfx/D3D12DeviceContext.cppindex 1b190351..1ebfc1e8 100644--- a/src/gfx/D3D12DeviceContext.cpp+++ b/src/gfx/D3D12DeviceContext.cpp@@ -101,9 +101,9 @@ bool fillAdapterInfo(const DXGI_ADAPTER_DESC1& desc, AdapterInfo& info)info.dedicatedVideoMemoryBytes = desc.DedicatedVideoMemory;info.isNvidia = desc.VendorId == 0x10DE;info.isSoftware = (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0;- info.driverVersion = queryNvidiaDriverVersion();+ info.driverVersion = info.isNvidia?queryNvidiaDriverVersion():std::wstring{};info.driverVersionSource = info.driverVersion.empty() ? L"unavailable" : L"registry";- return info.isNvidia && !info.isSoftware;+ return !info.isSoftware;}} // namespace@@ -142,7 +142,7 @@ bool D3D12DeviceContext::initialize(const DeviceContextDesc& desc, Status& statureturn false;}- // 3. Highest-performance NVIDIA adapter (vendor 0x10DE, non-software).+ // Keep every backend on one hardware adapter. Never silently use WARP.DXGI_ADAPTER_DESC1 chosenDesc{};bool chosen = false;for (UINT index = 0;; ++index) {@@ -172,7 +172,8 @@ bool D3D12DeviceContext::initialize(const DeviceContextDesc& desc, Status& statucandidateDesc.DedicatedVideoMemory / (1024 * 1024),narrow(candidateDesc.Description)));- if (candidateDesc.VendorId == 0x10DE && !isSoftware) {+ if ((!desc.requiredVendorId||candidateDesc.VendorId==desc.requiredVendorId) && !isSoftware &&+ SUCCEEDED(D3D12CreateDevice(candidate.Get(),D3D_FEATURE_LEVEL_12_0,__uuidof(ID3D12Device),nullptr))) {adapter_ = candidate;chosenDesc = candidateDesc;chosen = true;@@ -182,7 +183,7 @@ bool D3D12DeviceContext::initialize(const DeviceContextDesc& desc, Status& statuif (!chosen) {status = Status::DeviceFailure;- veyra::log::error("gfx", "no NVIDIA (vendor 0x10DE) hardware adapter found; refusing WARP fallback");+ veyra::log::error("gfx", "no compatible requested D3D12 hardware adapter found");return false;}fillAdapterInfo(chosenDesc, adapterInfo_);@@ -285,6 +286,12 @@ bool D3D12DeviceContext::checkDeviceAlive(uint32_t& removedReason) constreturn SUCCEEDED(reason);}+bool D3D12DeviceContext::videoMemoryInfo(uint64_t& budget,uint64_t& usage) const {+ ComPtr<IDXGIAdapter3> adapter;DXGI_QUERY_VIDEO_MEMORY_INFO info{};+ if(!adapter_||FAILED(adapter_.As(&adapter))||FAILED(adapter->QueryVideoMemoryInfo(0,DXGI_MEMORY_SEGMENT_GROUP_LOCAL,&info)))return false;+ budget=info.Budget;usage=info.CurrentUsage;return true;+}+bool D3D12DeviceContext::exerciseSlotRing(){CommandSlotRing ring;diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cppindex 7fd229f0..5b1a75ef 100644--- a/src/gfx/PresentSink.cpp+++ b/src/gfx/PresentSink.cpp@@ -107,6 +107,17 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,scd.Flags = tearingSupported_ ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;ComPtr<IDXGISwapChain1> swapChain1;+ if(desc.xess){+ xess_=std::make_unique<XessPresenter>();+ if(!xess_->initialize(device,queue,factory_.Get(),hwnd_,scd,swapChain_.GetAddressOf())){+ // XeSS is an optional experimental presenter. A missing or+ // incompatible local runtime must not prevent basic playback.+ log::warn("present", "XeSS FG initialization failed; falling back to native presentation");+ swapChain_.Reset();+ xess_.reset();+ }+ }+ if (!swapChain_) {if (FAILED(factory_->CreateSwapChainForHwnd(queue, hwnd_, &scd, nullptr, nullptr, &swapChain1))) {log::error("present", "CreateSwapChainForHwnd failed");status = Status::WindowFailure;@@ -117,6 +128,7 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,status = Status::WindowFailure;return false;}+ }// Block ALT+ENTER; the engine owns mode changes.(void)factory_->MakeWindowAssociation(hwnd_, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);queue_ = queue;@@ -182,10 +194,12 @@ bool PresentSink::present(Status& status)const UINT syncInterval = desc_.vsync ? 1 : 0;const UINT flags = (!desc_.vsync && tearingSupported_) ? DXGI_PRESENT_ALLOW_TEARING : 0;++attemptedPresentCount_;+ if(xess_&&!xess_->beforePresent()){status=Status::WindowFailure;return false;}const HRESULT hr = swapChain_->Present(syncInterval, flags);if (SUCCEEDED(hr)) {++presentCount_;backBufferIndex_ = swapChain_->GetCurrentBackBufferIndex();+ if(xess_&&!xess_->afterPresent()){status=Status::WindowFailure;return false;}return true;}++failedPresentCount_;@@ -230,36 +244,47 @@ bool PresentSink::present(Status& status)return false;}+bool PresentSink::waitForQueueIdle()+{+ if (queue_ == nullptr || device_ == nullptr) return true;+ ComPtr<ID3D12Fence> idleFence;+ if (FAILED(device_->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&idleFence)))) return false;+ HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr);+ if (ev == nullptr) return false;+ bool completed=false;+ const HRESULT signal = queue_->Signal(idleFence.Get(), 1);+ const HRESULT wait = SUCCEEDED(signal) ? idleFence->SetEventOnCompletion(1, ev) : signal;+ if (SUCCEEDED(wait)) {+ const DWORD result = WaitForSingleObject(ev, 5000);+ completed=result==WAIT_OBJECT_0;+ if (result != WAIT_OBJECT_0) log::warn("present", std::format("queue idle wait result={}", result));+ } else {+ log::warn("present", std::format("queue idle setup failed hr=0x{:X}", static_cast<unsigned>(wait)));+ }+ CloseHandle(ev);+ return completed;+}+void PresentSink::resize(uint32_t width, uint32_t height){if (width == 0 || height == 0) return;if (width == width_ && height == height_) return;- width_ = width;- height_ = height;const UINT flags = tearingSupported_ ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;// DXGI spec compliance before ResizeBuffers: wait for outstanding GPU// work on the presenting queue, then release ALL back-buffer references.- if (queue_ != nullptr) {- // Block until the queue is idle via an explicit signal+wait fence.- ID3D12Fence* idleFence = nullptr;- if (SUCCEEDED(device_->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&idleFence)))) {- HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr);- queue_->Signal(idleFence, 1);- idleFence->SetEventOnCompletion(1, ev);- WaitForSingleObject(ev, 5000);- CloseHandle(ev);- idleFence->Release();- }- }+ if (!waitForQueueIdle()) return;for (auto& b : backBuffers_) b.Reset();HRESULT hr = swapChain_->ResizeBuffers(3, width, height,DXGI_FORMAT_R8G8B8A8_UNORM, flags);if (FAILED(hr)) {log::error("present", std::format("ResizeBuffers FAILED hr=0x{:X} (queue idle, buffers released)",static_cast<unsigned>(hr)));+ refetchBackBuffers();return;}if (!refetchBackBuffers()) return;+ width_ = width;+ height_ = height;scBufferWidth_ = width_;scBufferHeight_ = height_;bufferExtentW_ = width_;@@ -278,6 +303,9 @@ void PresentSink::shutdown()// must also be released BEFORE the D3D12 queue it presents on.if (shutdownCalled_) return; // second call (destructor) has nothing leftshutdownCalled_ = true;+ // XeSS owns a proxy swapchain and may have copied tagged inputs on the+ // presenting queue. Its shutdown contract requires that work to finish.+ waitForQueueIdle();log::info("present", "sink-shutdown: sub-step backbuffers-release");for (auto& b : backBuffers_) b.Reset();log::info("present", "sink-shutdown: sub-step swapchain-release");@@ -287,6 +315,7 @@ void PresentSink::shutdown()log::info("present", std::format("sink-shutdown: swapchain pre-release refcount={} (2 = only our ComPtr + probe)", rc));}swapChain_.Reset();+ xess_.reset();log::info("present", "sink-shutdown: sub-step window-destroy-last");if (hwnd_ != nullptr && !desc_.targetWindow) {DestroyWindow(hwnd_);diff --git a/src/gfx/XessPresenter.cpp b/src/gfx/XessPresenter.cppnew file mode 100644index 00000000..59499380--- /dev/null+++ b/src/gfx/XessPresenter.cpp@@ -0,0 +1,151 @@+#include "veyra/gfx/XessPresenter.h"+#include "veyra/Log.h"+#include "veyra/RuntimePaths.h"+#include "veyra/FileIdentity.h"+#ifdef VEYRA_HAS_XESS+#include <xess_fg/xefg_swapchain_d3d12.h>+#include <xell/xell_d3d12.h>+#endif++namespace veyra::gfx {+struct XessPresenter::Impl {+ uint64_t generated=0;+#ifdef VEYRA_HAS_XESS+ HMODULE fgDll=nullptr,llDll=nullptr;+ xefg_swapchain_handle_t fg=nullptr;+ xell_context_handle_t ll=nullptr;+ uint32_t id=0;+#define XESS_PROC(name) decltype(&name) name##Fn=nullptr+ XESS_PROC(xefgSwapChainD3D12CreateContext);+ XESS_PROC(xefgSwapChainD3D12GetProperties);+ XESS_PROC(xefgSwapChainD3D12InitFromSwapChainDesc);+ XESS_PROC(xefgSwapChainD3D12GetSwapChainPtr);+ XESS_PROC(xefgSwapChainD3D12TagFrameResource);+ XESS_PROC(xefgSwapChainTagFrameConstants);+ XESS_PROC(xefgSwapChainSetEnabled);+ XESS_PROC(xefgSwapChainSetPresentId);+ XESS_PROC(xefgSwapChainGetLastPresentStatus);+ XESS_PROC(xefgSwapChainSetLatencyReduction);+ XESS_PROC(xefgSwapChainDestroy);+ XESS_PROC(xellD3D12CreateContext);+ XESS_PROC(xellDestroyContext);+ XESS_PROC(xellSetSleepMode);+ XESS_PROC(xellSleep);+ XESS_PROC(xellAddMarkerData);+#undef XESS_PROC+ bool check(int result,const char* operation,bool always=false){+ if(result!=0||always||log::verboseFrameLogs())log::info("xess-fg",std::format("{} result={} presentId={}",operation,result,id));+ return result>=0;+ }+ bool marker(xell_latency_marker_type_t m){return check(xellAddMarkerDataFn(ll,id,m),"XeLL marker");}+ ~Impl(){+ if(fg&&xefgSwapChainDestroyFn)check(xefgSwapChainDestroyFn(fg),"Destroy",true);+ if(ll&&xellDestroyContextFn)check(xellDestroyContextFn(ll),"XeLL destroy",true);+ if(fgDll)FreeLibrary(fgDll);if(llDll)FreeLibrary(llDll);+ }+#endif+};+XessPresenter::XessPresenter():p_(std::make_unique<Impl>()){}+XessPresenter::~XessPresenter()=default;+bool XessPresenter::initialize(ID3D12Device* device,ID3D12CommandQueue* queue,IDXGIFactory2* factory,HWND window,const DXGI_SWAP_CHAIN_DESC1& desc,IDXGISwapChain3** swapchain){+#ifdef VEYRA_HAS_XESS+ auto& p=*p_;const auto root=runtime::localDataDirectory()/"intel"/"experimental";+ auto load=[&](const wchar_t* name,const char* hash){auto path=std::filesystem::absolute(root/name);+ FileIdentity identity;IdentityError error;+ if(!computeFileIdentity(path.wstring(),identity,error)||!identity.signatureValid||identity.sha256Upper!=hash){+ log::error("xess-fg",std::format("runtime identity rejected {} hash={} signed={} error={}",path.string(),identity.sha256Upper,identity.signatureValid,int(error)));return HMODULE(nullptr);+ }+ log::info("xess-fg",std::format("runtime verified {} sha256={} signed={}",path.string(),identity.sha256Upper,identity.signatureValid));+ auto module=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);+ log::info("xess-fg",std::format("load {} result={} win32={}",path.string(),module!=nullptr,module?0:GetLastError()));return module;};+ p.llDll=load(L"libxell.dll","D2030DCD694FDA8F2EC7E044B13E6DB8F0B56D4BA9113A5EFAD334E3F3DED8C7");if(!p.llDll)return false;+ p.fgDll=load(L"libxess_fg.dll","EC5E0C65E075570C6EDE72618BB666D0BE0C2E10B2EA9762C0FE8CB8E375AB27");if(!p.fgDll)return false;+#define LOAD(module,name) p.name##Fn=reinterpret_cast<decltype(p.name##Fn)>(GetProcAddress(p.module,#name));if(!p.name##Fn){log::error("xess-fg","missing export " #name);return false;}+ LOAD(fgDll,xefgSwapChainD3D12CreateContext)+ LOAD(fgDll,xefgSwapChainD3D12GetProperties)+ LOAD(fgDll,xefgSwapChainD3D12InitFromSwapChainDesc)+ LOAD(fgDll,xefgSwapChainD3D12GetSwapChainPtr)+ LOAD(fgDll,xefgSwapChainD3D12TagFrameResource)+ LOAD(fgDll,xefgSwapChainTagFrameConstants)+ LOAD(fgDll,xefgSwapChainSetEnabled)+ LOAD(fgDll,xefgSwapChainSetPresentId)+ LOAD(fgDll,xefgSwapChainGetLastPresentStatus)+ LOAD(fgDll,xefgSwapChainSetLatencyReduction)+ LOAD(fgDll,xefgSwapChainDestroy)+ LOAD(llDll,xellD3D12CreateContext)+ LOAD(llDll,xellDestroyContext)+ LOAD(llDll,xellSetSleepMode)+ LOAD(llDll,xellSleep)+ LOAD(llDll,xellAddMarkerData)+#undef LOAD+ if(!p.check(p.xellD3D12CreateContextFn(device,&p.ll),"XeLL create",true)||!p.check(p.xefgSwapChainD3D12CreateContextFn(device,&p.fg),"Create",true))return false;+ if(!p.check(p.xefgSwapChainSetLatencyReductionFn(p.fg,p.ll),"Attach XeLL",true))return false;+ xell_sleep_params_t sleep{};sleep.bLowLatencyMode=1;+ if(!p.check(p.xellSetSleepModeFn(p.ll,&sleep),"XeLL sleep mode",true))return false;+ xefg_swapchain_d3d12_init_params_t init{};init.maxInterpolatedFrames=1;init.uiMode=XEFG_SWAPCHAIN_UI_MODE_AUTO;+ xefg_swapchain_properties_t properties{};+ if(!p.check(p.xefgSwapChainD3D12GetPropertiesFn(p.fg,&init,desc.Width,desc.Height,desc.Format,&properties),"Properties",true)||properties.maxSupportedInterpolations<1)return false;+ log::info("xess-fg",std::format("swapchain={}x{} maxInterpolations={} bufferHeap={} textureHeap={} estimated-motion constant-depth experimental",desc.Width,desc.Height,properties.maxSupportedInterpolations,properties.tempBufferHeapSize,properties.tempTextureHeapSize));+ if(!p.check(p.xefgSwapChainD3D12InitFromSwapChainDescFn(p.fg,window,&desc,nullptr,queue,factory,&init),"Init",true))return false;+ return p.check(p.xefgSwapChainD3D12GetSwapChainPtrFn(p.fg,__uuidof(IDXGISwapChain3),reinterpret_cast<void**>(swapchain)),"GetSwapChain",true);+#else+ (void)device;(void)queue;(void)factory;(void)window;(void)desc;(void)swapchain;+ log::error("xess-fg","Intel XeSS SDK unavailable at build time");return false;+#endif+}+bool XessPresenter::beginFrame(){+#ifdef VEYRA_HAS_XESS+ auto& p=*p_;++p.id;+ return p.check(p.xellSleepFn(p.ll,p.id),"XeLL sleep")&&p.marker(XELL_SIMULATION_START)&&p.marker(XELL_SIMULATION_END)&&p.marker(XELL_RENDERSUBMIT_START);+#else+ return false;+#endif+}+bool XessPresenter::tag(ID3D12GraphicsCommandList* list,ID3D12Resource* color,ID3D12Resource* motion,ID3D12Resource* depth,RECT region,bool enabled,bool reset,float elapsedMs){+#ifdef VEYRA_HAS_XESS+ auto& p=*p_;+ if(!p.check(p.xefgSwapChainSetEnabledFn(p.fg,enabled?1:0),"SetEnabled"))return false;+ if(!enabled)return true;+ if(!color||!motion||!depth||!list||region.right<=region.left||region.bottom<=region.top)return false;+ // ONLY_NOW makes XeSS copy each input into its own storage on this+ // submitted command list. The caller transitions the resources to and+ // from COPY_SOURCE around this call, which is the state required by the+ // XeSS-FG resource contract for this validity mode.+ auto resource=[&](xefg_swapchain_resource_type_t type,ID3D12Resource* tex,bool regionColor){+ xefg_swapchain_d3d12_resource_data_t data{};data.type=type;data.validity=XEFG_SWAPCHAIN_RV_ONLY_NOW;+ data.pResource=tex;data.incomingState=D3D12_RESOURCE_STATE_COPY_SOURCE;+ const auto d=tex->GetDesc();data.resourceSize={uint32_t(d.Width),d.Height};+ if(regionColor){data.resourceBase={uint32_t(region.left),uint32_t(region.top)};data.resourceSize={uint32_t(region.right-region.left),uint32_t(region.bottom-region.top)};}+ return p.check(p.xefgSwapChainD3D12TagFrameResourceFn(p.fg,list,p.id,&data),"Tag resource");+ };+ if(!resource(XEFG_SWAPCHAIN_RES_BACKBUFFER,color,true)||!resource(XEFG_SWAPCHAIN_RES_HUDLESS_COLOR,color,true)||!resource(XEFG_SWAPCHAIN_RES_MOTION_VECTOR,motion,false)||!resource(XEFG_SWAPCHAIN_RES_DEPTH,depth,false))return false;+ xefg_swapchain_frame_constant_data_t constants{};+ for(unsigned i=0;i<4;++i){constants.viewMatrix[i*5]=1;constants.projectionMatrix[i*5]=1;}+ constants.motionVectorScaleX=constants.motionVectorScaleY=1;+ constants.resetHistory=reset?1:0;constants.frameRenderTime=elapsedMs;+ return p.check(p.xefgSwapChainTagFrameConstantsFn(p.fg,p.id,&constants),"Tag constants");+#else+ (void)list;(void)color;(void)motion;(void)depth;(void)region;(void)enabled;(void)reset;(void)elapsedMs;return false;+#endif+}+bool XessPresenter::beforePresent(){+#ifdef VEYRA_HAS_XESS+ auto& p=*p_;return p.marker(XELL_RENDERSUBMIT_END)&&p.check(p.xefgSwapChainSetPresentIdFn(p.fg,p.id),"SetPresentId")&&p.marker(XELL_PRESENT_START);+#else+ return false;+#endif+}+bool XessPresenter::afterPresent(){+#ifdef VEYRA_HAS_XESS+ auto& p=*p_;if(!p.marker(XELL_PRESENT_END))return false;+ xefg_swapchain_present_status_t status{};+ if(!p.check(p.xefgSwapChainGetLastPresentStatusFn(p.fg,&status),"PresentStatus"))return false;+ if(status.isFrameGenEnabled&&status.frameGenResult==XEFG_SWAPCHAIN_RESULT_SUCCESS&&status.framesPresented>1)p.generated+=status.framesPresented-1;+ if(log::verboseFrameLogs()||p.id%60==0||status.frameGenResult<0)log::info("xess-fg",std::format("presentId={} enabled={} result={} framesPresented={} generatedTotal={} (SDK submissions, not measured scanout)",p.id,status.isFrameGenEnabled,int(status.frameGenResult),status.framesPresented,p.generated));+ return status.frameGenResult>=0;+#else+ return false;+#endif+}+uint64_t XessPresenter::generatedCount()const{return p_->generated;}+}diff --git a/src/guidance/AmdOpticalFlow.cpp b/src/guidance/AmdOpticalFlow.cppnew file mode 100644index 00000000..600da655--- /dev/null+++ b/src/guidance/AmdOpticalFlow.cpp@@ -0,0 +1,69 @@+#include "veyra/guidance/AmdOpticalFlow.h"+#include "veyra/pipeline/GpuPassUtils.h"+#include "veyra/Log.h"+#ifdef VEYRA_HAS_AMD_OF+#include <FidelityFX/host/ffx_opticalflow.h>+#include <FidelityFX/host/backends/dx12/ffx_dx12.h>+#endif++namespace veyra::guidance {+struct AmdOpticalFlow::Impl {+ uint32_t w=0,h=0;+ uint32_t framesSinceReset=0;+ ID3D12Device* device=nullptr;+ pipeline::ComPtr<ID3D12Resource> flow,scd;+#ifdef VEYRA_HAS_AMD_OF+ FfxOpticalflowContext context{};+ std::vector<uint8_t> scratch;+ bool created=false;+ ~Impl(){if(created)log::info("amd-of",std::format("Destroy result={}",unsigned(ffxOpticalflowContextDestroy(&context))));}+ bool check(FfxErrorCode r,const char* operation){log::info("amd-of",std::format("{} result={}",operation,unsigned(r)));return r==FFX_OK;}+#endif+};+AmdOpticalFlow::AmdOpticalFlow():p_(std::make_unique<Impl>()){}+AmdOpticalFlow::~AmdOpticalFlow()=default;+bool AmdOpticalFlow::initialize(ID3D12Device* device,uint32_t w,uint32_t h){+#ifdef VEYRA_HAS_AMD_OF+ auto& p=*p_;+ if(!device||!w||!h||w>16384||h>16384||p.created){log::error("amd-of","invalid initialization contract");return false;}+ p.w=w;p.h=h;p.device=device;+ p.scratch.resize(ffxGetScratchMemorySizeDX12(1));+ FfxOpticalflowContextDescription desc{};desc.resolution={w,h};+ if(!p.check(ffxGetInterfaceDX12(&desc.backendInterface,ffxGetDeviceDX12(device),p.scratch.data(),p.scratch.size(),1),"Interface"))return false;+ if(!p.check(ffxOpticalflowContextCreate(&p.context,&desc),"Create"))return false;p.created=true;+ FfxOpticalflowSharedResourceDescriptions resources{};+ if(!p.check(ffxOpticalflowGetSharedResourceDescriptions(&p.context,&resources),"Resources"))return false;+ auto allocate=[&](const FfxCreateResourceDescription& r){return pipeline::makeTexture(device,r.resourceDescription.width,r.resourceDescription.height,ffxGetDX12FormatFromSurfaceFormat(r.resourceDescription.format),true);};+ p.flow=allocate(resources.opticalFlowVector);p.scd=allocate(resources.opticalFlowSCD);+ log::info("amd-of",std::format("input={}x{} raw={}x{} grid=8 integer-pixel motion",w,h,width(),height()));+ return p.flow&&p.scd;+#else+ (void)device;(void)w;(void)h;log::error("amd-of","FidelityFX SDK not compiled into this build");return false;+#endif+}+bool AmdOpticalFlow::dispatch(ID3D12GraphicsCommandList* list,ID3D12Resource* color,bool reset){+#ifdef VEYRA_HAS_AMD_OF+ auto& p=*p_;if(!p.created||!list||!color||!p.flow||!p.scd)return false;+ const auto cd=color->GetDesc();pipeline::ComPtr<ID3D12Device> owner,listOwner;+ if(cd.Dimension!=D3D12_RESOURCE_DIMENSION_TEXTURE2D||cd.Width!=p.w||cd.Height!=p.h||cd.DepthOrArraySize!=1||cd.MipLevels!=1||cd.SampleDesc.Count!=1||cd.Format!=DXGI_FORMAT_B8G8R8A8_UNORM||FAILED(color->GetDevice(IID_PPV_ARGS(&owner)))||owner.Get()!=p.device||FAILED(list->GetDevice(IID_PPV_ARGS(&listOwner)))||listOwner.Get()!=p.device){+ log::error("amd-of","dispatch input extent/format/device mismatch");return false;+ }+ FfxOpticalflowDispatchDescription d{};d.commandList=ffxGetCommandListDX12(list);+ d.color=ffxGetResourceDX12(color,ffxGetResourceDescriptionDX12(color),L"Veyra OF color",FFX_RESOURCE_STATE_COMMON);+ d.opticalFlowVector=ffxGetResourceDX12(p.flow.Get(),ffxGetResourceDescriptionDX12(p.flow.Get()),L"Veyra OF vectors",FFX_RESOURCE_STATE_COMMON);+ d.opticalFlowSCD=ffxGetResourceDX12(p.scd.Get(),ffxGetResourceDescriptionDX12(p.scd.Get()),L"Veyra OF cut",FFX_RESOURCE_STATE_COMMON);+ d.reset=reset;d.backbufferTransferFunction=0;d.minMaxLuminance={0,1};+ const auto result=ffxOpticalflowContextDispatch(&p.context,&d);+ if(result==FFX_OK)p.framesSinceReset=reset?1:std::min(p.framesSinceReset+1,7u);+ if(result!=FFX_OK||log::verboseFrameLogs()||reset)log::info("amd-of",std::format("Dispatch reset={} result={}",reset,unsigned(result)));+ return result==FFX_OK;+#else+ (void)list;(void)color;(void)reset;return false;+#endif+}+ID3D12Resource* AmdOpticalFlow::vectors()const{return p_->flow.Get();}+ID3D12Resource* AmdOpticalFlow::sceneChanges()const{return p_->scd.Get();}+bool AmdOpticalFlow::warmedUp()const{return p_->framesSinceReset>=7;}+uint32_t AmdOpticalFlow::width()const{return p_->flow?uint32_t(p_->flow->GetDesc().Width):0;}+uint32_t AmdOpticalFlow::height()const{return p_->flow?p_->flow->GetDesc().Height:0;}+}diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex 990e0b94..c94116ea 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -28,6 +28,7 @@#include "veyra/ngx/NgxCoreHost.h"#include "veyra/ngx/NgxParameters.h"#include "veyra/ngx/NvOfSession.h"+#include "veyra/guidance/AmdOpticalFlow.h"extern "C" {#include <libavutil/frame.h>@@ -88,8 +89,15 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)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 && (srcW_ != workW_ || srcH_ != workH_);nrEnabled_ = desc.enableNr && !desc.noFeatures && !desc.noNgx;- fgEnabled_ = desc.enableFg && !desc.noNgx && !desc.stillImage;+ fgEnabled_ = desc.enableFg && !desc.noNgx && !desc.stillImage && desc.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS;nvofStandalone_ = desc.enableNvofStandalone && !desc.noFeatures;+ if(desc.opticalFlowBackend==engine::OpticalFlowBackend::AmdFidelityFx&&desc.amdFlowHalfResolution){nvofW_=std::max(1u,nvofW_/2);nvofH_=std::max(1u,nvofH_/2);}+ uint64_t budget=0,usage=0;+ const uint64_t estimate=uint64_t(workW_)*workH_*(fgEnabled_?100:76)+uint64_t(nrW_)*nrH_*32+uint64_t(srcW_)*srcH_*32;+ if(context_.videoMemoryInfo(budget,usage)){+ veyra::log::info("memory",std::format("graph lower-bound={}MiB budget={}MiB usage={}MiB; SDK allocations additional",estimate>>20,budget>>20,usage>>20));+ if(usage>=budget||estimate>budget-usage){veyra::log::error("memory","insufficient adapter budget for requested graph textures");return false;}+ }Status st = Status::Ok;lumaPitch_ = (static_cast<size_t>(srcW_) + 255) & ~size_t(255);@@ -162,6 +170,7 @@ bool EnhanceGraph::createResources()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(xessEnabled())for(auto& motion:presentMotion_){motion=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16_FLOAT,false);if(!motion)return false;}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);@@ -171,9 +180,9 @@ bool EnhanceGraph::createResources()confTex_ = makeTexture(context_.device(), nvofW_, nvofH_, DXGI_FORMAT_R8_UNORM, true);flowTex_ = makeTexture(context_.device(), nvofW_, nvofH_, DXGI_FORMAT_R16G16_FLOAT, true);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;}+ // Valid placeholder descriptors keep disabled FG inexpensive. Enabling it+ // is a graph rebuild, so no in-flight descriptor is resized in place.+ for(auto& frame:genFrame_){frame=makeTexture(context_.device(),fgEnabled_?workW_:1,fgEnabled_?workH_:1,DXGI_FORMAT_R8G8B8A8_UNORM,true);if(!frame)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_;@@ -280,10 +289,17 @@ bool EnhanceGraph::initZeroAndDepthTextures()bool EnhanceGraph::initNvof(){if(desc_.stillImage){mvecSource_="single-image (no temporal motion)";return true;}- if (desc_.noFeatures) {+ if (desc_.noFeatures || !(nvofStandalone_ || xessEnabled() || (fgEnabled_&&desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) || (srEnabled_&&!desc_.videoSrQuality))) {veyra::log::info("graph", "VEYRA_NO_FEATURES: NVOF session skipped");return true;}+ if(desc_.opticalFlowBackend==engine::OpticalFlowBackend::AmdFidelityFx){+ amdOf_=std::make_unique<guidance::AmdOpticalFlow>();+ if(!amdOf_->initialize(context_.device(),nvofW_,nvofH_))return false;+ nvofRawTex_=amdOf_->vectors();rawW_=amdOf_->width();rawH_=amdOf_->height();selectedGrid_=8;+ mvecSource_="amd-fidelityfx + photometric confidence";+ return true;+ }nvof_ = std::make_unique<ngx::NvOfSession>();if (nvofOutFence_ == nullptr) {if (FAILED(context_.device()->CreateFence(0, D3D12_FENCE_FLAG_NONE,@@ -314,7 +330,7 @@ bool EnhanceGraph::initNvof()bool EnhanceGraph::initNgxFeatures(){- if (desc_.noNgx || desc_.noFeatures) {+ if (desc_.noNgx || desc_.noFeatures || (!nrEnabled_&&!srEnabled_&&!fgEnabled_)) {veyra::log::info("graph", "NGX core/features skipped by disabled-feature configuration");return true;}@@ -349,7 +365,7 @@ bool EnhanceGraph::initNgxFeatures()fgCapsAvailable_ = false;fgMultiFrameMax_ = 0;- if (!desc_.stillImage && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) {+ if (fgEnabled_ && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) {fgBackend_ = std::make_unique<ngx::DlssFgBackend>();ngx::DlssFgBackend::Capability fgCaps{};const bool fgAvailable = fgBackend_->queryCapability(*coreHost_, fgCaps, st);@@ -371,6 +387,7 @@ bool EnhanceGraph::initNgxFeatures()}fgCapsAvailable_=true;fgMultiFrameMax_=3;}+ if(nrEnabled_){nrAdapter_ = std::make_unique<ngx::DlssNrRuntimeAdapter>();if (!nrAdapter_->load(desc_.runtimeAbsPath.c_str(), st) ||!nrAdapter_->installCallerCompatibility(st) ||@@ -379,13 +396,14 @@ bool EnhanceGraph::initNgxFeatures()veyra::log::error("graph", std::format("NR snippet init failed 0x{:X}", nrResult_));return false;}+ }ngxParams_ = coreHost_->allocateParameters(st);if (ngxParams_ == nullptr) return false;srBackend_ = std::make_unique<ngx::DlssSrBackend>();// NR feature create (8.5 create parameter contract).- {+ if(nrEnabled_) {namespace p = ngx::dlssnr;ngx::ParameterBlock pb(ngxParams_);pb.setU32(p::kWidth, nrW_); pb.setU32(p::kHeight, nrH_);@@ -431,7 +449,7 @@ bool EnhanceGraph::initNgxFeatures()// FG create + warm-up evaluate BEFORE descriptor views (the runtime// allocates internals at the first evaluate and would fail after views// exist on this system).- if (!desc_.stillImage && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) {+ if (fgEnabled_ && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) {ngx::DlssFgBackend::CreateDesc fd{};fd.width = workW_; fd.height = workH_;fd.renderWidth = workW_; fd.renderHeight = workH_;@@ -507,7 +525,7 @@ bool EnhanceGraph::createComputePasses()// upload is the proven frame-path ingestion on this system.if (!uploadPass_.loadShader("Nv12Upload.dxil", cs) || !uploadPass_.create(context_.device(), cs, 4, 1, 2)) return false;if (!densifyPass_.loadShader("NvofDensify.dxil", cs) ||- !densifyPass_.create(context_.device(), cs, 6, 4, 2)) return false;+ !densifyPass_.create(context_.device(), cs, 7, 5, 2)) return false;if (!stager_.initialize(context_.device(), 64)) {veyra::log::error("graph", "descriptor stager init failed");return false;@@ -601,7 +619,7 @@ bool EnhanceGraph::createViews()if (viewsTex) stagedSrv(videoFrame_[1].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 12);// Densify pass views: 0=rawFlow SRV(int2) 1=cost SRV(uint)- // 2=previous RGB SRV,3=current RGB SRV;4=flow UAV,5=confidence UAV.+ // 2=previous RGB,3=current RGB,4=AMD SCD;5=flow UAV,6=confidence UAV.{D3D12_SHADER_RESOURCE_VIEW_DESC rf{};rf.Format = DXGI_FORMAT_R16G16_SINT;@@ -622,14 +640,15 @@ bool EnhanceGraph::createViews()rc.Texture2D.ResourceMinLODClamp = 0.0f;if (viewsTex) stager_.stageSrv(nvofCostTex_.Get(), &rc, densifyPass_.heap.Get(), 1);if(viewsTex){stagedSrv(nvofInA_.Get(),DXGI_FORMAT_B8G8R8A8_UNORM,densifyPass_,2);stagedSrv(nvofInB_.Get(),DXGI_FORMAT_B8G8R8A8_UNORM,densifyPass_,3);}+ if(viewsTex){rc.Format=DXGI_FORMAT_R32_UINT;stager_.stageSrv(amdOf_?amdOf_->sceneChanges():nullptr,&rc,densifyPass_.heap.Get(),4);}D3D12_UNORDERED_ACCESS_VIEW_DESC uf{};uf.Format = DXGI_FORMAT_R16G16_FLOAT;uf.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;- context_.device()->CreateUnorderedAccessView(flowTex_.Get(), nullptr, &uf, cpu(densifyPass_, 4));+ context_.device()->CreateUnorderedAccessView(flowTex_.Get(), nullptr, &uf, cpu(densifyPass_, 5));D3D12_UNORDERED_ACCESS_VIEW_DESC uc{};uc.Format = DXGI_FORMAT_R8_UNORM;uc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;- context_.device()->CreateUnorderedAccessView(confTex_.Get(), nullptr, &uc, cpu(densifyPass_, 5));+ context_.device()->CreateUnorderedAccessView(confTex_.Get(), nullptr, &uc, cpu(densifyPass_, 6));}return true;}@@ -855,8 +874,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// Guidance from original source-space color before SR/NR. Queue waits are GPU-side.bool haveFlow = false;- const bool runMotion = nvofStandalone_ || (fgEnabled_&&!frucBackend_) || (srEnabled_ && !desc_.videoSrQuality);- if (runMotion && nvof_ && nvof_->initialized()) {+ const bool runMotion = nvofStandalone_ || xessEnabled() || (fgEnabled_&&!frucBackend_) || (srEnabled_ && !desc_.videoSrQuality);+ if (runMotion && (amdOf_ || (nvof_ && nvof_->initialized()))) {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);@@ -872,7 +891,14 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Framelist->Dispatch((nvofW_+15)/16,(nvofH_+15)/16,1);tracker_.uavBarrier(list,nvofInB_.Get());tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_COMMON);+ if(amdOf_){+ gpuTimer_.mark(list,GpuStage::Flow);+ if(!amdOf_->dispatch(list,nvofInB_.Get(),!prevValid_))return false;+ ++metrics_.amdOfExecuteCount;haveFlow=prevValid_;+ gpuTimer_.mark(list,GpuStage::Flow,true);+ }if (prevValid_) {+ if(!amdOf_){gpuTimer_.mark(list,GpuStage::Flow);if(!ring_.submitAndSignal(slot))return false;haveFlow=nvof_->execute(ring_.lastSignaledValue(),st);@@ -883,7 +909,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame}list=ring_.acquireNext(slot,st);if(!list)return false;gpuTimer_.mark(list,GpuStage::Flow,true);+ }if(haveFlow) {+ if(amdOf_)tracker_.transition(list,amdOf_->sceneChanges(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);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);@@ -891,13 +919,14 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frametracker_.transition(list,nvofInA_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);const float dc[8]={uintBits(rawW_),uintBits(rawH_),uintBits(nvofW_),uintBits(nvofH_),- uintBits(selectedGrid_),uintBits(0),uintBits(32),uintBits(desc_.validateMotion?3u:0u)};- densifyPass_.bind(list,dc,gpuHandleOf(densifyPass_,0).ptr,gpuHandleOf(densifyPass_,4).ptr);+ uintBits(selectedGrid_),uintBits(0),uintBits(32),uintBits((desc_.validateMotion?3u:0u)|(amdOf_?4u:0u)|(amdOf_&&!amdOf_->warmedUp()?8u:0u))};+ densifyPass_.bind(list,dc,gpuHandleOf(densifyPass_,0).ptr,gpuHandleOf(densifyPass_,5).ptr);list->Dispatch((nvofW_+15)/16,(nvofH_+15)/16,1);tracker_.uavBarrier(list,flowTex_.Get());tracker_.uavBarrier(list,confTex_.Get());tracker_.transition(list,nvofInA_.Get(),D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,nvofRawTex_.Get(),D3D12_RESOURCE_STATE_COMMON);+ if(amdOf_)tracker_.transition(list,amdOf_->sceneChanges(),D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,nvofCostTex_.Get(),D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,flowTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list,confTex_.Get(),D3D12_RESOURCE_STATE_COMMON);@@ -1075,6 +1104,17 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frametracker_.transition(list, videoFrame_[parity].Get(), D3D12_RESOURCE_STATE_COMMON);}+ if(xessEnabled()){+ auto* input=haveFlow?baseFlow_.Get():nrZeroMotion_.Get();+ tracker_.transition(list,input,D3D12_RESOURCE_STATE_COPY_SOURCE);+ tracker_.transition(list,presentMotion_[parity].Get(),D3D12_RESOURCE_STATE_COPY_DEST);+ list->CopyResource(presentMotion_[parity].Get(),input);+ tracker_.transition(list,input,D3D12_RESOURCE_STATE_COMMON);+ tracker_.transition(list,presentMotion_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);+ presentMotionValid_[parity]=haveFlow&&!reset;+ motionPreviousSource_[parity]=previousSource_;+ }+ previousSource_=sourceFrameId;if(!fgEnabled_)gpuTimer_.resolve(list);if (!ring_.submitAndSignal(slot)) return false;if(!fgEnabled_)gpuTimer_.submitted(ring_.lastSignaledValue());@@ -1191,10 +1231,18 @@ bool EnhanceGraph::resolveGeneration(FrameOutputs& out)}bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){- if((s.frameGenerationBackend==engine::FrameGenerationBackend::Fruc&&s.multiplier>1&&!frucBackend_)||s.frameGenerationBackend!=desc_.frameGenerationBackend||(frucBackend_&&s.multiplier>1&&s.multiplier!=desc_.fgMultiplier)||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;+ // A non-NVIDIA adapter keeps the user's requested NR setting in the UI+ // but has this NGX-only stage explicitly disabled in the graph. Do not+ // reject unrelated live settings in that degraded, playable state.+ if(s.nr&&desc_.enableNr&&!nrHandle_)return false;+ if(s.opticalFlowBackend!=desc_.opticalFlowBackend||s.amdFlowHalfResolution!=desc_.amdFlowHalfResolution)return false;+ // DLSS and FRUC allocate multiplier-specific feature/output resources;+ // XeSS has a fixed 2X proxy swapchain contract. Settings callers must+ // rebuild instead of accepting a change that cannot take effect in place.+ if(s.multiplier!=desc_.fgMultiplier||(s.frameGenerationBackend==engine::FrameGenerationBackend::Fruc&&s.multiplier>1&&!frucBackend_)||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&s.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.protection=s.protection;desc_.settingsRevision=s.revision;desc_.fgMultiplier=std::max(2u,s.multiplier);desc_.enableNvofStandalone=s.nr&&!desc_.stillImage;nvofStandalone_=desc_.enableNvofStandalone;- setNrEnabled(s.nr);setFgEnabled(s.multiplier>1);+ setNrEnabled(s.nr);setFgEnabled(s.multiplier>1&&s.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS);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;}@@ -1258,6 +1306,8 @@ void EnhanceGraph::shutdown()nrHandle_ = nullptr;}frucBackend_.reset();+ amdOf_.reset();+ for(auto& motion:presentMotion_)motion.Reset();if (fgBackend_) fgBackend_->release();if(videoSrBackend_){videoSrBackend_->release();videoSrBackend_.reset();}if (srBackend_) srBackend_->release();diff --git a/src/sink/NvencD3D12Encoder.cpp b/src/sink/NvencD3D12Encoder.cppindex 5bac7105..eab233d4 100644--- a/src/sink/NvencD3D12Encoder.cpp+++ b/src/sink/NvencD3D12Encoder.cpp@@ -41,6 +41,15 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS open{};open.version=NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;open.apiVersion=NVENCAPI_VERSION;open.device=ctx.device();open.deviceType=NV_ENC_DEVICE_TYPE_DIRECTX;if(!p.check(p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder),"OpenD3D12Session"))return false;const GUID codec=hevc?NV_ENC_CODEC_HEVC_GUID:NV_ENC_CODEC_H264_GUID;+ int maxWidth=0,maxHeight=0;+ NV_ENC_CAPS_PARAM caps{};caps.version=NV_ENC_CAPS_PARAM_VER;caps.capsToQuery=NV_ENC_CAPS_WIDTH_MAX;+ if(!p.check(p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&maxWidth),"WidthMax"))return false;+ caps.capsToQuery=NV_ENC_CAPS_HEIGHT_MAX;+ if(!p.check(p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&maxHeight),"HeightMax"))return false;+ veyra::log::info("nvenc",std::format("codec={} requested={}x{} maximum={}x{}",hevc?"HEVC":"H264",p.w,p.h,maxWidth,maxHeight));+ if(maxWidth<=0||maxHeight<=0||p.w>unsigned(maxWidth)||p.h>unsigned(maxHeight)||(p.w&1)||(p.h&1)){+ veyra::log::error("nvenc","requested dimensions unsupported by selected codec/NV12 input");return false;+ }NV_ENC_PRESET_CONFIG preset{};preset.version=NV_ENC_PRESET_CONFIG_VER;preset.presetCfg.version=NV_ENC_CONFIG_VER;if(!p.check(p.api.nvEncGetEncodePresetConfigEx(p.encoder,codec,NV_ENC_PRESET_P4_GUID,NV_ENC_TUNING_INFO_LOW_LATENCY,&preset),"GetPreset"))return false;preset.presetCfg.frameIntervalP=1;preset.presetCfg.gopLength=120;preset.presetCfg.rcParams.rateControlMode=NV_ENC_PARAMS_RC_CONSTQP;diff --git a/tests/integration/ExperimentalBackendTests.cpp b/tests/integration/ExperimentalBackendTests.cppnew file mode 100644index 00000000..49a8700b--- /dev/null+++ b/tests/integration/ExperimentalBackendTests.cpp@@ -0,0 +1,218 @@+#include "veyra/engine/VideoPresenter.h"+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/RuntimePaths.h"+#include <d3d12sdklayers.h>+#include <wrl/client.h>+#include <algorithm>+#include <bit>+#include <cmath>+#include <filesystem>+#include <iostream>+#include <vector>+extern "C" {+#include <libavutil/frame.h>+#include <libavutil/pixfmt.h>+}+using namespace veyra;++namespace {++struct FlowSample {+ float x = 0.0f;+ float y = 0.0f;+ size_t count = 0;+};++float halfToFloat(uint16_t bits)+{+ const uint32_t sign = uint32_t(bits & 0x8000u) << 16;+ uint32_t exponent = (bits >> 10) & 0x1Fu;+ uint32_t mantissa = bits & 0x03FFu;+ uint32_t result = 0;+ if (exponent == 0) {+ if (mantissa != 0) {+ exponent = 127 - 14;+ while ((mantissa & 0x0400u) == 0) {+ mantissa <<= 1;+ --exponent;+ }+ result = sign | (exponent << 23) | ((mantissa & 0x03FFu) << 13);+ } else {+ result = sign;+ }+ } else if (exponent == 0x1Fu) {+ result = sign | 0x7F800000u | (mantissa << 13);+ } else {+ result = sign | ((exponent + 112) << 23) | (mantissa << 13);+ }+ return std::bit_cast<float>(result);+}++// Test-only readback. Normal playback, capture, and video export never call this.+bool readCanonicalFlow(gfx::D3D12DeviceContext& ctx, gfx::CommandSlotRing& ring,+ ID3D12Resource* flow, FlowSample& sample)+{+ if (flow == nullptr || flow->GetDesc().Format != DXGI_FORMAT_R16G16_FLOAT) return false;+ const D3D12_RESOURCE_DESC desc = flow->GetDesc();+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};+ UINT rows = 0;+ UINT64 rowBytes = 0, total = 0;+ ctx.device()->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, &rows, &rowBytes, &total);+ D3D12_HEAP_PROPERTIES heap{};+ heap.Type = D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC buffer{};+ buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;+ buffer.Width = total;+ buffer.Height = 1;+ buffer.DepthOrArraySize = 1;+ buffer.MipLevels = 1;+ buffer.SampleDesc.Count = 1;+ buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ Microsoft::WRL::ComPtr<ID3D12Resource> readback;+ if (FAILED(ctx.device()->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer,+ D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))) return false;++ Status status = Status::Ok;+ uint32_t slot = 0;+ ID3D12GraphicsCommandList* list = ring.acquireNext(slot, status);+ if (list == nullptr) return false;+ D3D12_RESOURCE_BARRIER barrier{};+ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barrier.Transition = {flow, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,+ D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_SOURCE};+ list->ResourceBarrier(1, &barrier);+ D3D12_TEXTURE_COPY_LOCATION source{};+ source.pResource = flow;+ source.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ D3D12_TEXTURE_COPY_LOCATION destination{};+ destination.pResource = readback.Get();+ destination.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ destination.PlacedFootprint = footprint;+ list->CopyTextureRegion(&destination, 0, 0, 0, &source, nullptr);+ std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter);+ list->ResourceBarrier(1, &barrier);+ if (!ring.submitAndSignal(slot) || !ring.waitIdle()) return false;++ uint8_t* data = nullptr;+ D3D12_RANGE range{0, static_cast<SIZE_T>(total)};+ if (FAILED(readback->Map(0, &range, reinterpret_cast<void**>(&data)))) return false;+ std::vector<float> xs, ys;+ // Ignore the outer quarter. It contains intentional out-of-bounds rejection.+ for (uint32_t y = desc.Height / 4; y < desc.Height * 3 / 4; y += 4) {+ const uint16_t* row = reinterpret_cast<const uint16_t*>(data + footprint.Offset + size_t(y) * footprint.Footprint.RowPitch);+ for (uint32_t x = uint32_t(desc.Width) / 4; x < uint32_t(desc.Width) * 3 / 4; x += 4) {+ const float vx = halfToFloat(row[x * 2]);+ const float vy = halfToFloat(row[x * 2 + 1]);+ if (std::isfinite(vx) && std::isfinite(vy)) {+ xs.push_back(vx);+ ys.push_back(vy);+ }+ }+ }+ D3D12_RANGE empty{0, 0};+ readback->Unmap(0, &empty);+ if (xs.size() < 64) return false;+ std::sort(xs.begin(), xs.end());+ std::sort(ys.begin(), ys.end());+ sample = {xs[xs.size() / 2], ys[ys.size() / 2], xs.size()};+ return true;+}++} // namespace++int wmain(int argc,wchar_t** argv){+ if(argc!=3)return 2;+ const bool xess=wcscmp(argv[1],L"xess")==0;+ const bool amd=wcscmp(argv[1],L"amd")==0;+ const bool sr=std::wstring(argv[1]).find(L"sr")==0;+ if(!xess&&!amd&&!sr)return 2;+ const unsigned width=sr?1920:640,height=sr?1080:360,frames=sr?3:48;+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ std::filesystem::create_directories(argv[2]);+ Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());+ SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");+ HWND window=CreateWindowExW(0,L"STATIC",L"Veyra experimental backend test",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);+ if(!window)return 1;+ ShowWindow(window,SW_SHOWNOACTIVATE);+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;+ gfx::DeviceContextDesc device;device.enableDebugLayer=true;+ if(!ctx.initialize(device,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 1;+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> info;ctx.device()->QueryInterface(IID_PPV_ARGS(&info));+ pipeline::EnhanceGraph graph(ctx,ring);engine::VideoPresenter presenter;+ pipeline::EnhanceGraphDesc desc;+ desc.sourceWidth=desc.workWidth=640;desc.sourceHeight=desc.workHeight=360;+ desc.rgbInput=true;desc.enableNr=false;desc.enableFg=xess;desc.noNgx=true;+ desc.enableNvofStandalone=true;+ desc.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;+ desc.opticalFlowBackend=amd?engine::OpticalFlowBackend::AmdFidelityFx:engine::OpticalFlowBackend::Nvidia;+ if(sr){+ desc.sourceWidth=width;desc.sourceHeight=height;+ desc.workWidth=std::wstring(argv[1]).find(L"8k")!=std::wstring::npos?7680:2560;+ desc.workHeight=desc.workWidth==7680?4320:1440;+ desc.nrWidth=1920;desc.nrHeight=1080;desc.noNgx=false;desc.enableSr=true;+ desc.enableNvofStandalone=false;+ desc.videoSrQuality=std::wstring(argv[1]).find(L"video")!=std::wstring::npos?1:0;+ desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ }+ bool ok=graph.initialize(desc)&&presenter.open(ctx,window,graph)&&graph.createViews();+ if(xess)ok=ok&&presenter.xessActive();+ AVFrame* frame=av_frame_alloc();frame->format=AV_PIX_FMT_RGBA;frame->width=int(width);frame->height=int(height);frame->color_trc=AVCOL_TRC_IEC61966_2_1;+ ok=ok&&av_frame_get_buffer(frame,32)>=0;+ pipeline::EnhanceGraph::FrameOutputs out;+ FlowSample rightward{}, leftward{};+ for(unsigned i=0;ok&&i<frames;++i){+ MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}+ const int phase = i < 24 ? int(i) : int(i - 24);+ const int velocity = i < 24 ? 2 : -2;+ for(int y=0;y<int(height);++y)for(int x=0;x<int(width);++x){+ const int px=(x-phase*velocity+int(width))%int(width);auto* p=frame->data[0]+y*frame->linesize[0]+x*4;+ p[0]=uint8_t((px*17+y*7)%256);p[1]=uint8_t(((px/16+y/16)%2)*180+30);p[2]=uint8_t((px*3+y*11)%256);p[3]=255;+ }+ out={};ok=graph.process(frame,i*1000.0/30,i==0||i==24,out,i+1);+ if(ok)ok=presenter.present(ctx,ring,graph,out.videoSlot,false,false,0,false,.5f,out.batch.identity);+ if(ok&&i==16){+ const auto before=presenter.xessGeneratedCount();+ ok=presenter.present(ctx,ring,graph,out.videoSlot,false,false,0,false,.5f,out.batch.identity);+ if(xess)ok=ok&&presenter.xessGeneratedCount()==before;+ }+ if(i==24)SetWindowPos(window,nullptr,0,0,800,600,SWP_NOACTIVATE|SWP_NOZORDER);+ if(amd&&(i==23||i==47)){+ ok=ring.drainQueue()&&ok;+ FlowSample& sample=i==23?rightward:leftward;+ ok=ok&&readCanonicalFlow(ctx,ring,graph.flowResource(),sample);+ }+ Sleep(34);+ }+ ok=ring.drainQueue()&&ok;+ const auto generated=presenter.xessGeneratedCount();+ const auto dispatches=graph.metrics().amdOfExecuteCount;+ if(sr&&ok){+ sink::RgbaImage image;+ ok=graph.metrics().srEvaluateCount==frames&&sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);+ uint64_t nonblack=0;for(size_t i=0;i+3<image.pixels.size();i+=4)nonblack+=image.pixels[i]>8||image.pixels[i+1]>8||image.pixels[i+2]>8;+ ok=ok&&image.width==desc.workWidth&&image.height==desc.workHeight&&nonblack>uint64_t(image.width)*image.height/2;+ std::cout<<"SR extent="<<image.width<<"x"<<image.height<<" evaluate="<<graph.metrics().srEvaluateCount<<" nonblack="<<nonblack<<" pass="<<ok<<std::endl;+ }+ if(xess)ok=ok&&generated>10;+ if(amd){+ // The source moves right then left. Canonical current->previous motion+ // must therefore point left then right with no material vertical drift.+ const bool directionOk=rightward.count>0&&leftward.count>0&&rightward.x<-0.5f&&leftward.x>0.5f&&+ std::abs(rightward.y)<0.5f&&std::abs(leftward.y)<0.5f;+ std::cout<<"AMD flow rightward=("<<rightward.x<<","<<rightward.y<<") leftward=("<<leftward.x<<","<<leftward.y<<") samples="<<rightward.count<<"/"<<leftward.count<<" directionPass="<<directionOk<<std::endl;+ ok=ok&&dispatches==48&&directionOk;+ }+ out={};presenter.close();graph.shutdown();av_frame_free(&frame);+ uint64_t errors=0;+ if(info)for(UINT64 i=0;i<info->GetNumStoredMessagesAllowedByRetrievalFilter();++i){+ SIZE_T size=0;info->GetMessage(i,nullptr,&size);std::vector<uint8_t> data(size);+ auto* message=reinterpret_cast<D3D12_MESSAGE*>(data.data());+ if(SUCCEEDED(info->GetMessage(i,message,&size))&&message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;log::error("debug",message->pDescription);}+ }+ ok=ok&&errors==0;+ std::cout<<"BACKEND "<<(xess?"xess":amd?"amd-of":"sr")<<" generated="<<generated<<" amdDispatches="<<dispatches<<" debugErrors="<<errors<<" pass="<<ok<<" (SDK submissions, not scanout or visual quality)\n";+ info.Reset();ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();return ok?0:1;+}diff --git a/tests/integration/MotionValidationTests.cpp b/tests/integration/MotionValidationTests.cppindex 21aa3c05..71000d79 100644--- a/tests/integration/MotionValidationTests.cpp+++ b/tests/integration/MotionValidationTests.cpp@@ -25,14 +25,15 @@ int run(bool vertical){!upload(previous.Get(),32,32,16,[&](uint8_t* p,unsigned x,unsigned y){if(vertical)std::swap(x,y);float v[4]={x/40.f,x/40.f,x/40.f,1};memcpy(p,v,16);})||!upload(current.Get(),32,32,16,[&](uint8_t* p,unsigned x,unsigned y){if(vertical)std::swap(x,y);float shift=y>=24?-2.5f:y>=16?2.5f:2.f;float c=(x+shift)/40.f+(y>=8&&y<16?.3f:y>=16&&y<24?.08f:0);float v[4]={c,c,c,1};memcpy(p,v,16);}))return 2;if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;- ComputePass pass;std::vector<uint8_t> shader;if(!pass.loadShader("NvofDensify.dxil",shader)||!pass.create(ctx.device(),shader,6,4,2))return 2;+ ComputePass pass;std::vector<uint8_t> shader;if(!pass.loadShader("NvofDensify.dxil",shader)||!pass.create(ctx.device(),shader,7,5,2))return 2;unsigned index=0;for(auto* r:{flow.Get(),cost.Get(),previous.Get(),current.Get()})makeSrv(ctx.device(),r,r->GetDesc().Format,cpuHandleOf(pass,index++));- makeUav(ctx.device(),output.Get(),DXGI_FORMAT_R16G16_FLOAT,cpuHandleOf(pass,4));makeUav(ctx.device(),confidence.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(pass,5));+ makeSrv(ctx.device(),nullptr,DXGI_FORMAT_R32_UINT,cpuHandleOf(pass,4));+ makeUav(ctx.device(),output.Get(),DXGI_FORMAT_R16G16_FLOAT,cpuHandleOf(pass,5));makeUav(ctx.device(),confidence.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(pass,6));D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=16384;bd.Height=1;bd.DepthOrArraySize=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;bool ok=true;- for(unsigned flags:{0u,3u}){+ for(unsigned flags:{0u,3u,8u}){list=ring.acquireNext(slot,st);if(!list)return 2;states.transition(list,output.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);states.transition(list,confidence.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- float c[8];unsigned values[8]={8,8,32,32,4,0,32,flags};memcpy(c,values,sizeof c);pass.bind(list,c,gpuHandleOf(pass,0).ptr,gpuHandleOf(pass,4).ptr);list->Dispatch(2,2,1);+ float c[8];unsigned values[8]={8,8,32,32,4,0,32,flags};memcpy(c,values,sizeof c);pass.bind(list,c,gpuHandleOf(pass,0).ptr,gpuHandleOf(pass,5).ptr);list->Dispatch(2,2,1);auto copy=[&](ID3D12Resource* tex,UINT64 offset){states.uavBarrier(list,tex);states.transition(list,tex,D3D12_RESOURCE_STATE_COPY_SOURCE);D3D12_TEXTURE_COPY_LOCATION a{},b{};a.pResource=tex;a.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.pResource=readback.Get();b.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;b.PlacedFootprint.Offset=offset;b.PlacedFootprint.Footprint={tex->GetDesc().Format,32,32,1,256};list->CopyTextureRegion(&b,0,0,0,&a,nullptr);};copy(output.Get(),0);copy(confidence.Get(),8192);if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;void* ptr=nullptr;D3D12_RANGE read{0,16384};if(FAILED(readback->Map(0,&read,&ptr)))return 2;unsigned rejected=0,retained=0,attenuated=0;bool passOk=true;@@ -40,12 +41,12 @@ int run(bool vertical){unsigned sx=vertical?y:x,sy=vertical?x:y;if(vertical)std::swap(vx,vy);float expected=sy>=24?-2.5f:sy>=16?2.5f:2.f;bool outside=sx+expected<0||sx+expected>31;unsigned expectedCost=sx/4==3?255:sx/4==5?31:sx/4==6?32:sx/4==7?16:0;- bool reject=expectedCost>=32||(flags&&(outside||(sy>=8&&sy<16)));bool attenuate=flags&&!reject&&sy>=16&&sy<24;+ bool reject=flags==8||expectedCost>=32||(flags&&(outside||(sy>=8&&sy<16)));bool attenuate=flags&&!reject&&sy>=16&&sy<24;if(reject){++rejected;passOk=passOk&&vx==0&&vy==0&&conf==0;}else if(attenuate){++attenuated;passOk=passOk&&vx>0&&vx<expected&&vy==0&&conf>0&&conf<255-expectedCost;}else{++retained;passOk=passOk&&vx==expected&&vy==0&&conf==255-expectedCost;}}- D3D12_RANGE written{0,0};readback->Unmap(0,&written);ok=ok&&passOk&&retained>100&&rejected>100&&(!flags||attenuated>100);+ D3D12_RANGE written{0,0};readback->Unmap(0,&written);ok=ok&&passOk&&(flags==8?rejected==1024:retained>100&&rejected>100&&(!flags||attenuated>100));std::cout<<"MOTION_VALIDATION vertical="<<vertical<<" flags="<<flags<<" rejected="<<rejected<<" retained="<<retained<<" attenuated="<<attenuated<<" pass="<<passOk<<std::endl;}ring.drainQueue();ComPtr<ID3D12InfoQueue> iq;unsigned errors=0;if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&iq))))return 2;diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cppindex eb3d34fb..f5a27221 100644--- a/tests/unit/RepairContractTests.cpp+++ b/tests/unit/RepairContractTests.cpp@@ -20,7 +20,15 @@ int main(){check(p.nr==p.source&&p.flow==p.source,"native mode retains native4K NR and flow");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");+ for(auto target:{pipeline::SrTarget::Qhd,pipeline::SrTarget::Uhd4K,pipeline::SrTarget::Uhd8K}){+ const auto plan=pipeline::ResolutionPlan::make({1920,1080},true,pipeline::NrSizePolicy::Realtime,false,7,target);+ check(plan.output==pipeline::srTargetExtent(target)&&plan.nr==pipeline::Extent{1920,1080}&&plan.settingsRevision==7,"SR target changes real output, retains realtime NR and revision");+ }+ check(pipeline::ResolutionPlan::make({1448,1086},true,pipeline::NrSizePolicy::Native,true,1,pipeline::SrTarget::Uhd8K).output==pipeline::Extent{5760,4320},"8K 4:3 aspect preserved");+ check(pipeline::ResolutionPlan::make({8000,2000},true,pipeline::NrSizePolicy::Native,true,1,pipeline::SrTarget::Qhd).output==pipeline::Extent{8000,2000},"small target never shrinks long image");engine::EnhancementSettings s;check(s.validate().empty(),"default settings valid");+ check(engine::frameGenerationBackendName(engine::FrameGenerationBackend::Dlss)=="DLSS"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::Fruc)=="FRUC"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::XeSS)=="XeSS","frame-generation backend names identify every backend");+ check(engine::opticalFlowBackendName(engine::OpticalFlowBackend::Nvidia)=="NVIDIA_NVOF"&&engine::opticalFlowBackendName(engine::OpticalFlowBackend::AmdFidelityFx)=="AMD_FIDELITYFX_OF","optical-flow backend names identify every backend");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");diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cppindex 2da18138..b8754e63 100644--- a/tests/unit/RepairPresetTests.cpp+++ b/tests/unit/RepairPresetTests.cpp@@ -1,15 +1,20 @@#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.videoSrQuality=2;s.frameGenerationBackend=FrameGenerationBackend::Fruc;s.protection.enabled=true;s.protection.featherPixels=3.5f;s.protection.regions[0]={.1f,.2f,.7f,.8f};s.protection.regions[3]={0,0,1,1};s.model.intensity=.375f;s.model.skin=1.5f;s.residual.darken=1.2f;s.multiplier=4;s.flow=FlowQuality::Quality;s.content=ContentRate::Fps50;s.nrPolicy=veyra::pipeline::NrSizePolicy::Native;+int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engine;const std::filesystem::path p=argv[1];PresetStore a(p);bool ok=a.load();EnhancementSettings s;s.videoSrQuality=2;s.frameGenerationBackend=FrameGenerationBackend::Fruc;s.opticalFlowBackend=OpticalFlowBackend::AmdFidelityFx;s.amdFlowHalfResolution=true;s.protection.enabled=true;s.protection.featherPixels=3.5f;s.protection.regions[0]={.1f,.2f,.7f,.8f};s.protection.regions[3]={0,0,1,1};s.model.intensity=.375f;s.model.skin=1.5f;s.residual.darken=1.2f;s.multiplier=4;s.flow=FlowQuality::Quality;s.content=ContentRate::Fps50;s.nrPolicy=veyra::pipeline::NrSizePolicy::Native;+ s.srTarget=veyra::pipeline::SrTarget::Uhd8K;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 badBackend=s;badBackend.frameGenerationBackend=static_cast<FrameGenerationBackend>(2);ok=ok&&!b.put(L"invalid backend",badBackend);+ auto badTarget=s;badTarget.srTarget=static_cast<veyra::pipeline::SrTarget>(3);ok=ok&&!b.put(L"invalid target",badTarget);+ auto xess=s;xess.frameGenerationBackend=FrameGenerationBackend::XeSS;ok=ok&&!b.put(L"XeSS 4X rejected",xess);+ xess.multiplier=2;ok=ok&&b.put(L"XeSS 2X",xess);PresetStore xessReload(p);ok=ok&&xessReload.load()&&xessReload.entries().back().settings==xess&&b.erase(1);+ auto badBackend=s;badBackend.frameGenerationBackend=static_cast<FrameGenerationBackend>(3);ok=ok&&!b.put(L"invalid backend",badBackend);+ auto badFlow=s;badFlow.opticalFlowBackend=static_cast<OpticalFlowBackend>(2);ok=ok&&!b.put(L"invalid flow backend",badFlow);auto half=s;half.content=ContentRate::Capture60To30;ok=ok&&b.put(L"capture half rate",half);PresetStore halfReload(p);ok=ok&&halfReload.load()&&halfReload.entries().back().settings.content==ContentRate::Capture60To30&&b.erase(1);auto badSr=s;badSr.videoSrQuality=5;ok=ok&&!b.put(L"invalid video SR",badSr);auto invalid=s;invalid.model.tone=9;ok=ok&&!b.put(L"bad",invalid)&&b.entries().size()==1&&b.erase(0)&&b.entries().empty();auto badRegion=s;badRegion.protection.regions[0].left=2;ok=ok&&!b.put(L"invalid region",badRegion);{std::ofstream legacy(p);legacy<<"VEYRA_PRESETS 1\n\"legacy\" 1\n\"legacy\" 1 1 1 -1 0 0 0 1 1 1 1 1 1 0 1 0 1 0\n";}- PresetStore old(p);ok=ok&&old.load()&&!old.defaultSettings().protection.enabled&&old.put(L"v2",s);+ PresetStore old(p);ok=ok&&old.load()&&!old.defaultSettings().protection.enabled&&old.defaultSettings().srTarget==veyra::pipeline::SrTarget::Uhd4K&&old.put(L"v2",s);PresetStore upgraded(p);ok=ok&&upgraded.load()&&upgraded.entries().size()==2&&upgraded.entries()[1].settings==s;{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;}