Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
feat(fsr): AMD FSR frame generation in the present sink (2X, RTX verified)
Veyra Goal Agent27656a6df911
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 6ac5377d..2508b8ef 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -43,6 +43,7 @@ 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")+set(VEYRA_FIDELITYFX2_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third_party_local/amd/FidelityFX-SDK-2.3.0/Kits/FidelityFX" CACHE PATH "Local AMD FidelityFX SDK 2.3.0 Kits/FidelityFX tree")list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")include(VeyraWarnings)@@ -76,6 +77,7 @@ add_library(veyra_gfx STATICsrc/gfx/PresentSink.cppsrc/gfx/XessPresenter.cppsrc/gfx/XessMfgUnlock.cpp+ src/gfx/FsrFgPresenter.cpp)veyra_apply_warnings(veyra_gfx)target_compile_features(veyra_gfx PUBLIC cxx_std_20)@@ -84,6 +86,12 @@ 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(EXISTS "${VEYRA_FIDELITYFX2_ROOT}/framegeneration/include/dx12/ffx_api_framegeneration_dx12.h")+ target_include_directories(veyra_gfx PRIVATE+ "${VEYRA_FIDELITYFX2_ROOT}/api/include"+ "${VEYRA_FIDELITYFX2_ROOT}/framegeneration/include")+ target_compile_definitions(veyra_gfx PRIVATE VEYRA_HAS_FSR=1)+endif()if(VEYRA_ENABLE_D3D12_DEBUG)target_compile_definitions(veyra_gfx PUBLIC VEYRA_D3D12_DEBUG=1)endif()diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex 95b7f1d2..6f7388e5 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -73,6 +73,12 @@ int multiplierChoiceCount(engine::FrameGenerationBackend backend){cap=providerAudited?4:2;if(controller){const auto snapshot=controller->snapshot();if(snapshot.xessMaxInterpolatedFrames>1)cap=std::clamp(snapshot.xessMaxInterpolatedFrames+1,2,4);}}+ else if(backend==engine::FrameGenerationBackend::Fsr){+ // AMD 3.1.x frame generation delivers one generated frame per present;+ // tools/fsr_probe measured the same count for 2/3/4 requested frames.+ cap=2;+ if(controller){const auto snapshot=controller->snapshot();if(snapshot.fsrMaxGeneratedFrames>0)cap=std::clamp(int(snapshot.fsrMaxGeneratedFrames)+1,2,2);}+ }else if(controller){const auto snapshot=controller->snapshot();if(snapshot.fgMultiFrameMax>0)cap=std::clamp(snapshot.fgMultiFrameMax+1,2,6);}int count=1;for(size_t i=1;i<engine::kFgMultiplierChoiceCount;++i)if(int(engine::kFgMultiplierChoices[i])<=cap)++count;@@ -144,7 +150,7 @@ 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));if(s.frameGenerationBackend==engine::FrameGenerationBackend::XeSS){const int choices=multiplierChoiceCount(engine::FrameGenerationBackend::XeSS);const size_t index=size_t(std::clamp(choices-1,1,int(engine::kFgMultiplierChoiceCount)-1));s.multiplier=std::min(s.multiplier,engine::kFgMultiplierChoices[index]);}break;}+ case 208:{s.frameGenerationBackend=static_cast<engine::FrameGenerationBackend>(send(id,CB_GETCURSEL));if(engine::presentSinkFrameGeneration(s.frameGenerationBackend)){const int choices=multiplierChoiceCount(s.frameGenerationBackend);const size_t index=size_t(std::clamp(choices-1,1,int(engine::kFgMultiplierChoiceCount)-1));s.multiplier=std::min(s.multiplier,engine::kFgMultiplierChoices[index]);}break;}case 209:s.opticalFlowBackend=static_cast<engine::OpticalFlowBackend>(send(id,CB_GETCURSEL));break;case 220:s.lowLatency=checked(id)==BST_CHECKED;break;case 215:s.amdFlowHalfResolution=checked(id)==BST_CHECKED;break;@@ -215,7 +221,7 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.SetPropW(item(219),L"veyra.tip",HANDLE(L"直播兼容模式:切换显示交换链,会短暂停顿;不改变增强算法或导出。不保证所有捕获方式有效。"));add(L"STATIC",L"补帧与运动估算",1103,0,1,12,12,-1,30);add(L"STATIC",L"补帧方式",1111,0,1,12,50,-1,24);- combo(208,1,78,{L"DLSS 帧生成",L"Intel XeSS · 实验显示补帧 2X"});+ combo(208,1,78,{L"DLSS 帧生成",L"Intel XeSS · 实验显示补帧 2X",L"AMD FSR 帧生成 · 2X"});add(L"STATIC",L"补帧倍率",1112,0,1,12,122,-1,24);combo(202,1,150,{L"关闭补帧",L"2X · 一张中间帧",L"3X · 两张中间帧",L"4X · 三张中间帧"});add(L"STATIC",L"运动估算",1113,0,1,12,194,-1,24);@@ -307,7 +313,7 @@ case WM_COMMAND:{const int id=LOWORD(wp);if(!populating&&((id>=202&&id<=205||id=case WM_HSCROLL:{int id=GetDlgCtrlID(reinterpret_cast<HWND>(lp));if(id>=600&&id<612){int index=id-600;float v=float(SendMessageW(reinterpret_cast<HWND>(lp),TBM_GETPOS,0,0))/(index>=4&&index<=6?1:100);if(index==3&&v<0)v=-1;std::wostringstream o;o<<std::setprecision(4)<<v;putText(100+index,o.str().c_str());}return 0;}case WM_TIMER:{auto s=controller->snapshot();syncProtection(enhancementEnabled?s.desired.protection:configuredSettings.protection);if(enhancementEnabled&&!dirty&&displayedSettings!=s.desired)populate(s.desired);check(200,enhancementEnabled&&s.desired.nr?BST_CHECKED:BST_UNCHECKED);check(201,enhancementEnabled&&s.desired.sr?BST_CHECKED:BST_UNCHECKED);std::wostringstream o;if(!s.running&&!s.frames&&s.transport!=engine::TransportState::Opening)o<<L"未打开媒体 · 设置待启用\n";else{o<<L"期望版本 "<<s.desired.revision<<L" / 已应用 "<<s.applied.revision<<(s.applying?L" · 应用中":L"");- const wchar_t* backend=s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS?L"XeSS":L"DLSS";+ const wchar_t* backend=s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS?L"XeSS":s.applied.frameGenerationBackend==engine::FrameGenerationBackend::Fsr?L"AMD FSR":L"DLSS";o<<L"\n"<<backend<<L" · "<<(s.applied.multiplier<=1?L"补帧关闭":s.fgActive?L"补帧运行":L"等待有效补帧");if(!s.backendWarning.empty())message(s.backendWarning);else if(!displayedBackendWarning.empty())message(L"设置已应用");diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex d08c5244..966917ed 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -452,7 +452,7 @@ if(smokeStep==3&&elapsed>4100&&!smokeSave.empty()){engine.saveFrame(smokeSave);sif(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_SAVE_THROW",nullptr,0)){const auto retained=engine.snapshot();if(!retained.failed&&retained.running&&retained.frames>0){engine.saveFrame(smokeSave);smokeStep=5;veyra::log::info("image-save-test","retry after injected allocation failure; result/session retained");}}}auto s=engine.snapshot();const auto subtitleText=uiState.subtitles&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional&&!full)?veyra::engine::subtitleAt(subtitles,s.position):L"";veyra::ui::updateSubtitleOverlay(subtitleLabel,subtitleText,subtitlePixels);const double submittedFps=s.submissionFps.value_or(0.0);-const bool xessRate=s.applied.frameGenerationBackend==veyra::engine::FrameGenerationBackend::XeSS&&s.applied.multiplier>1;+const bool xessRate=s.applied.multiplier>1&&veyra::engine::presentSinkFrameGeneration(s.applied.frameGenerationBackend);veyra::ui::setText(GetDlgItem(hwnd,FpsLabel),s.running&&!s.image&&s.transport==veyra::engine::TransportState::Playing&&!s.metrics.flow.rateWindowReady?std::wstring(L"帧率采样中"):std::format(L"{} {:.1f} fps",xessRate?L"SDK提交":L"显示提交",xessRate?s.metrics.flow.xessSdkSubmitFps:s.metrics.flow.presentSubmitFps));auto text=s.remotePlay?std::format(L"{}\r\nPS5 接收 {:.1f} / 解码 {:.1f} / 处理 {:.1f} fps | 解码后跳过 {} | 入队丢弃 {}",s.status,s.remoteReceivedFps,s.remoteDecodedFps,s.fps,s.remotePlaySkipped,s.remoteIngressDropped):s.capture?std::format(L"{}\r\n输入 {:.1f} / 已处理 {:.1f} / 显示提交 {:.1f}fps | 回调至Present返回p95 {:.1f}ms(非总延迟)| 丢弃 {} | 有效生成 {}",s.status,s.captureFps,s.fps,submittedFps,s.captureAgeP95Ms,s.captureDropped,s.generated):std::format(L"{}\r\n{:.1f} / {:.1f}秒 已处理 {:.1f}fps 提交迟到 {:+.1f}ms 源帧 {} / 有效生成 {}",s.status,s.position,s.duration,s.fps,s.lateMs,s.frames,s.generated);if(smokeZoom&&startTick&&s.frames>0){const auto elapsed=GetTickCount64()-startTick;@@ -563,7 +563,7 @@ int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<a// The legacy argument clamp caps --fg-multiplier at 4X. Re-read the flag here so// 6X (and 2X/3X/4X) can be exercised from the command line for diagnostics and// smoke tests; the interactive UI uses the capability-driven list instead.-{int fgArgc=0;auto fgArgv=CommandLineToArgvW(GetCommandLineW(),&fgArgc);for(int i=1;i<fgArgc;++i){if(!_wcsicmp(fgArgv[i],L"--fg-multiplier")&&i+1<fgArgc){const int value=_wtoi(fgArgv[i+1]);if(value>=2&&value<=6){initialOptions.fgMultiplier=uint32_t(value);initialOptions.fg=true;}else if(value==1){initialOptions.fg=false;initialOptions.fgMultiplier=2;}}else if(!_wcsicmp(fgArgv[i],L"--fg-xess")){initialOptions.settings.frameGenerationBackend=veyra::engine::FrameGenerationBackend::XeSS;if(initialOptions.fgMultiplier<2)initialOptions.fgMultiplier=2;initialOptions.fg=true;}else if(!_wcsicmp(fgArgv[i],L"--fg-dlss")){initialOptions.settings.frameGenerationBackend=veyra::engine::FrameGenerationBackend::Dlss;}}if(fgArgv)LocalFree(fgArgv);}+{int fgArgc=0;auto fgArgv=CommandLineToArgvW(GetCommandLineW(),&fgArgc);for(int i=1;i<fgArgc;++i){if(!_wcsicmp(fgArgv[i],L"--fg-multiplier")&&i+1<fgArgc){const int value=_wtoi(fgArgv[i+1]);if(value>=2&&value<=6){initialOptions.fgMultiplier=uint32_t(value);initialOptions.fg=true;}else if(value==1){initialOptions.fg=false;initialOptions.fgMultiplier=2;}}else if(!_wcsicmp(fgArgv[i],L"--fg-xess")){initialOptions.settings.frameGenerationBackend=veyra::engine::FrameGenerationBackend::XeSS;if(initialOptions.fgMultiplier<2)initialOptions.fgMultiplier=2;initialOptions.fg=true;}else if(!_wcsicmp(fgArgv[i],L"--fg-fsr")){initialOptions.settings.frameGenerationBackend=veyra::engine::FrameGenerationBackend::Fsr;if(initialOptions.fgMultiplier<2)initialOptions.fgMultiplier=2;initialOptions.fg=true;}else if(!_wcsicmp(fgArgv[i],L"--fg-dlss")){initialOptions.settings.frameGenerationBackend=veyra::engine::FrameGenerationBackend::Dlss;}}if(fgArgv)LocalFree(fgArgv);}if(workerMapping){const int code=veyra::engine::runExportWorker(workerMapping);CoUninitialize();return code;}if(smokeSeconds<=0&&exportOutput.empty()){uiPreferences=preferences.load();initialOptions=veyra::engine::PlayerOptions::from(preferences.startup(initialOptions.snapshot()));engine.setVolume(uiPreferences.volume,uiPreferences.muted);uiState.subtitles=uiPreferences.subtitles;subtitlePixels=uiPreferences.subtitleSize;}engine.requestSettings(initialOptions.snapshot());diff --git a/apps/veyra/ui/LiveStatusDashboard.h b/apps/veyra/ui/LiveStatusDashboard.hindex c6bea06e..ccb88c6b 100644--- a/apps/veyra/ui/LiveStatusDashboard.h+++ b/apps/veyra/ui/LiveStatusDashboard.h@@ -11,7 +11,7 @@ struct DashboardHistory {const bool active=s.running&&!s.image&&s.transport==engine::TransportState::Playing&&!s.applying;auto value=active?s.metrics.flow.enhancementProcessing.mean:std::optional<double>{};points.push_back(value);if(points.size()>120)points.pop_front();- const bool xess=s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS&&s.applied.multiplier>1;+ const bool xess=s.applied.multiplier>1&&engine::presentSinkFrameGeneration(s.applied.frameGenerationBackend);const double actual=xess?s.metrics.flow.xessSdkSubmitFps:s.metrics.flow.presentSubmitFps;const double target=s.nominalSourceFps*(s.captureHalfRate?.5:1)*s.applied.multiplier;if(!active||!s.metrics.flow.rateWindowReady||target<=0){low=good=0;overloaded=false;return;}@@ -36,13 +36,13 @@ inline void paintDashboard(HWND h,HDC dc,int w,int height,const engine::PlayerSnfor(int i=0;i<4;++i){int x=left+i*(cw+gap);card(x,top,cw,58);text(names[i],x+6,top+7,cw-10,17,9,secondary);const auto& a=f.gpuTiming[size_t(stages[i])];std::wstring value=L"—";if(active){if(a.mean)value=std::format(L"{:.1f}",*a.mean);else if(s.metrics.gpu[size_t(stages[i])].state==diagnostics::SampleState::NotExecuted)value=(i==3&&s.applied.multiplier>1)?L"等待补帧":L"未开启";}- if(i==3&&s.applied.multiplier>1&&s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS)value=L"不可测";+ if(i==3&&s.applied.multiplier>1&&engine::presentSinkFrameGeneration(s.applied.frameGenerationBackend))value=L"不可测";text(value,x+6,top+27,cw-10,24,14,textColor);}const int chartTop=104,chartH=std::max(92,height-188),bottom=chartTop+chartH+8,bw=(w-26)/2;card(10,chartTop,w-20,chartH);- const bool xess=s.applied.multiplier>1&&s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS;- text(advanced?L"精细数据":xess?L"增强处理耗时 · 不含XeSS FG":L"总增强处理耗时",20,chartTop+8,w-100,20,10,secondary);+ const bool xess=s.applied.multiplier>1&&engine::presentSinkFrameGeneration(s.applied.frameGenerationBackend);+ text(advanced?L"精细数据":xess?L"增强处理耗时 · 不含显示补帧":L"总增强处理耗时",20,chartTop+8,w-100,20,10,secondary);text(advanced?L"◂":L"▸",w-38,chartTop+5,24,24,14,secondary);if(!advanced){const auto extra=active?f.enhancementProcessing.mean:std::optional<double>{};diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.hindex f19ab47d..8dbebec8 100644--- a/apps/veyra/ui/LiveStatusPanel.h+++ b/apps/veyra/ui/LiveStatusPanel.h@@ -24,7 +24,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){paintDashboard(h,paint.dc,width,height,s,state->history,state->advanced);if(!state->advanced)return 0;const bool playing=s.running&&!s.image&&s.transport==engine::TransportState::Playing;- const bool xess=s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS&&s.applied.multiplier>1;+ const bool xess=s.applied.multiplier>1&&engine::presentSinkFrameGeneration(s.applied.frameGenerationBackend);auto write=[&](const std::wstring& value,int x,int y,int w,int ht,int size,COLORREF color){chromeText(paint.dc,h,value,x,y,w,ht,size,color);};auto ms=[](std::optional<double> v){return v?std::format(L"{:.1f} ms",*v):std::wstring(L"未测");};auto timing=[&](const diagnostics::TimingAggregate& a){return playing&&a.mean&&a.p95?(state->advanced?std::format(L"{:.1f} / {:.1f}",*a.mean,*a.p95):ms(a.mean)):std::wstring(L"未测");};@@ -37,7 +37,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){rows.emplace_back(L"测量范围",L"非屏幕实测 · 非增强处理耗时");rows.emplace_back(L"增强处理 · 平均 / P95",timing(f.enhancementProcessing));rows.emplace_back(L"处理统计口径",L"同帧光流+NR+SR+残差+FG区间去重");- rows.emplace_back(L"处理范围",xess?L"不含XeSS内部FG":L"不含输入颜色、输出、声音和呈现等待");+ rows.emplace_back(L"处理范围",xess?L"不含显示补帧(XeSS/AMD FSR)":L"不含输入颜色、输出、声音和呈现等待");rows.emplace_back(L"平均范围",L"总计按源帧;单项按执行次数");rows.emplace_back(L"光流范围",L"含光流GPU依赖等待");rows.emplace_back(xess?L"SDK提交(非屏幕实测)":L"显示提交(非屏幕实测)",fps(xess?f.xessSdkSubmitFps:f.presentSubmitFps));diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 83fcc5f8..b9678620 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -66,6 +66,9 @@ struct PlayerSnapshot {// 0 = no XeSS session has reported yet; the settings UI then falls back to// the audited-provider probe.int xessMaxInterpolatedFrames=0;+ // AMD FSR frame-generation ceiling (generated frames per presented frame;+ // 1 = 2X). 0 = no FSR session has reported yet.+ int fsrMaxGeneratedFrames=0;bool running=false,failed=false,image=false,capture=false,remotePlay=false;int remotePlayState=0; uint64_t remotePlaySkipped=0;bool remoteRecovering=false;unsigned remoteReconnectAttempts=0;std::wstring remoteRecoveryMessage;@@ -118,5 +121,7 @@ private:int fgMultiFrameMaxCap_=0;// Guarded by mutex_: XeSS provider ceiling of the active session (0 = unknown).int xessMaxInterpolatedFramesCap_=0;+ // Guarded by mutex_: AMD FSR ceiling of the active session (0 = unknown).+ int fsrMaxGeneratedFramesCap_=0;};}diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex bb6f8910..c3b13606 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -6,7 +6,12 @@#include <string_view>#include "veyra/pipeline/ResolutionPlan.h"namespace veyra::engine {-enum class FrameGenerationBackend { Dlss, XeSS };+enum class FrameGenerationBackend { Dlss, XeSS, Fsr };+// Frame generation that runs inside the present sink (external frame+// interpolation swapchain) instead of the in-graph DLSSG backend.+constexpr bool presentSinkFrameGeneration(FrameGenerationBackend backend) {+ return backend==FrameGenerationBackend::XeSS||backend==FrameGenerationBackend::Fsr;+}// Multipliers the UI offers. 5X is intentionally absent: the DLSS runtime// exposes 2/3/4/6 and MFG buyers pick from those; 1 = generation off.inline constexpr uint32_t kFgMultiplierChoices[]={1,2,3,4,6};@@ -28,6 +33,7 @@ constexpr std::string_view frameGenerationBackendName(FrameGenerationBackend bacswitch(backend) {case FrameGenerationBackend::Dlss: return "DLSS";case FrameGenerationBackend::XeSS: return "XeSS";+ case FrameGenerationBackend::Fsr: return "AMD-FSR";}return "unknown";}@@ -113,11 +119,14 @@ 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::XeSS)return "invalid frame generation backend";+ if(frameGenerationBackend<FrameGenerationBackend::Dlss||frameGenerationBackend>FrameGenerationBackend::Fsr)return "invalid frame generation backend";// The XeSS provider reports its own generated-frame ceiling at session// start; the engine clamps/rejects above it, so validation only guards// the absolute API range here.if(frameGenerationBackend==FrameGenerationBackend::XeSS&&multiplier>4)return "XeSS frame generation supports up to 4X";+ // The AMD 3.1.x provider delivers one generated frame per present; the+ // probe measured the same count for 2/3/4 requested frames.+ if(frameGenerationBackend==FrameGenerationBackend::Fsr&&multiplier>2)return "AMD FSR frame generation supports up to 2X";if(videoSrQuality>4)return "invalid video SR quality";if(!pipeline::validSrTarget(srTarget))return "invalid SR target";if(opticalFlowBackend!=OpticalFlowBackend::Nvidia&&opticalFlowBackend!=OpticalFlowBackend::AmdFidelityFx&&opticalFlowBackend!=OpticalFlowBackend::GpuDis)return "invalid optical flow backend";diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 6c02e90f..08c83549 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -23,6 +23,13 @@ public:uint64_t xessPresentedCount() const {return sink_.xess()?sink_.xess()->presentedCount():0;}bool xessActive() const {return sink_.xess()!=nullptr;}bool xessFailed() const {return xessFailed_;}+ uint64_t fsrGeneratedCount() const {return sink_.fsr()?sink_.fsr()->generatedCount():0;}+ uint64_t fsrPresentedCount() const {return sink_.fsr()?sink_.fsr()->presentedCount():0;}+ bool fsrActive() const {return sink_.fsr()!=nullptr;}+ bool fsrFailed() const {return fsrFailed_;}+ // Provider-reported generated frames per real frame (1 = 2X); 0 when the+ // AMD runtime is unavailable.+ uint32_t fsrMaxGeneratedFrames() const {return sink_.fsr()?sink_.fsr()->maxGeneratedFrames():0;}// Sustained under-rate may suppress SDK-owned XeSS-FG generation over a// stable interval (xefgSwapChainSetEnabled); re-enabling goes through the// per-frame history reset, never a per-frame toggle.@@ -45,6 +52,10 @@ private:bool xessWasEnabled_=false;bool xessFailed_=false;bool xessGenerationSuppressed_=false;+ std::chrono::steady_clock::time_point lastFsrFrame_{};+ pipeline::FrameIdentity lastFsrIdentity_{};+ bool fsrWasEnabled_=false;+ bool fsrFailed_=false;void refresh(ID3D12Device*);};}diff --git a/include/veyra/gfx/FsrFgPresenter.h b/include/veyra/gfx/FsrFgPresenter.hnew file mode 100644index 00000000..00028a4b--- /dev/null+++ b/include/veyra/gfx/FsrFgPresenter.h@@ -0,0 +1,73 @@+#pragma once++// AMD FidelityFX Super Resolution frame generation behind the Veyra present+// path. The provider creates (and owns) a proxy IDXGISwapChain4 for our HWND;+// the engine renders into that proxy and calls Present on it, and the provider+// inserts interpolated frames according to the per-frame dispatch we record.+//+// Evidence and limits (local RTX 5070, FSR SDK 2.3.0, provider 3.1.7/3.1.6):+// docs/FRAMEGEN_FSR_DOLBY_STATUS_2026-09-16.md and tools/fsr_probe. The 3.1.x+// provider delivers exactly one generated frame per presented frame, so the+// requested multiplier is capped at 2X for this provider.++#include <d3d12.h>+#include <dxgi1_6.h>++#include <cstdint>+#include <memory>++namespace veyra::gfx {++class FsrFgPresenter {+public:+ FsrFgPresenter();+ ~FsrFgPresenter();++ FsrFgPresenter(const FsrFgPresenter&) = delete;+ FsrFgPresenter& operator=(const FsrFgPresenter&) = delete;++ // Creates the AMD proxy swapchain for the window. On success `swapchain`+ // receives a BORROWED pointer: the provider owns one reference and releases+ // it when this object destroys its context, so a caller that wants to keep+ // the swapchain must take its own reference (QueryInterface/AddRef) and+ // release it before the presenter is destroyed.+ bool initialize(ID3D12Device* device, ID3D12CommandQueue* queue, IDXGIFactory2* factory, HWND window,+ const DXGI_SWAP_CHAIN_DESC1& desc, uint32_t renderWidth, uint32_t renderHeight,+ IDXGISwapChain4** swapchain, uint32_t fgMultiplier);++ // Records one frame of frame-generation work on the caller's command list:+ // prepare dispatch (motion + depth), per-frame configure and the+ // interpolation dispatch. `motion` is the guidance motion in working-extent+ // pixels (previous = current + motion), `depth` is the guidance depth.+ bool tag(ID3D12GraphicsCommandList* list, ID3D12Resource* backBuffer, ID3D12Resource* motion,+ ID3D12Resource* depth, RECT region, bool enabled, bool reset, float elapsedMs);++ // Frame ids must advance by exactly one per presented frame, including the+ // frames that carry no generation work.+ void afterPresent();++ uint64_t generatedCount() const;+ uint64_t presentedCount() const;+ // Generated frames per real frame the provider delivers (1 = 2X) once a+ // context exists; 0 while unavailable.+ uint32_t maxGeneratedFrames() const;+ bool available() const;+ bool failed() const;+ const char* providerVersion() const;+ // Borrowed proxy swapchain (valid while this object lives).+ IDXGISwapChain4* swapchainHandle() const;+ // Turns generation off while the proxy keeps presenting real frames. Used+ // when the session stops using AMD frame generation but the swapchain has+ // to stay: the provider retains the DXGI swapchain, so a second swapchain+ // cannot be created for the same HWND in this process.+ void disableGeneration();++ // Implementation state; public because the provider's presentation+ // callback (a free function in the translation unit) must reach it.+ struct Impl;++private:+ std::unique_ptr<Impl> p_;+};++} // namespace veyra::gfxdiff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.hindex 7d94d54f..0a7a5c92 100644--- a/include/veyra/gfx/PresentSink.h+++ b/include/veyra/gfx/PresentSink.h@@ -16,6 +16,7 @@#include "veyra/Result.h"#include "veyra/gfx/XessPresenter.h"+#include "veyra/gfx/FsrFgPresenter.h"namespace veyra::gfx {@@ -36,6 +37,12 @@ public:uint32_t height = 720;bool vsync = true;bool xess = false;+ // AMD FSR frame generation: the provider creates the proxy swapchain.+ bool fsr = false;+ // Working (render) extent for the AMD provider's maxRenderSize; 0 keeps+ // it equal to the swapchain extent.+ uint32_t renderWidth = 0;+ uint32_t renderHeight = 0;bool captureCompatible = false;bool hdr = false;bool hdr10 = false;@@ -80,6 +87,8 @@ public:IDXGISwapChain3* swapChain() const { return swapChain_.Get(); }XessPresenter* xess() const { return xess_.get(); }bool xessFailed() const { return xessFailed_; }+ FsrFgPresenter* fsr() const { return fsr_.get(); }+ bool fsrFailed() const { return fsrFailed_; }void shutdown();@@ -106,11 +115,13 @@ private:UINT swapChainFlags_ = 0;bool pendingResize_ = false;bool xessFailed_ = false;+ bool fsrFailed_ = false;ID3D12Device* device_ = nullptr;ID3D12CommandQueue* queue_ = nullptr;ComPtr<IDXGIFactory2> factory_;ComPtr<IDXGISwapChain3> swapChain_;std::unique_ptr<XessPresenter> xess_;+ std::unique_ptr<FsrFgPresenter> fsr_;ComPtr<ID3D12Resource> backBuffers_[3];UINT backBufferIndex_ = 0;bool closed_ = false;diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 20f70b8d..9285ddbd 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -201,6 +201,10 @@ public:DXGI_FORMAT outputFormat() const { return hdr10Output()?DXGI_FORMAT_R10G10B10A2_UNORM:desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM; }bool highQualityPresentation() const { return desc_.highQualityPresentation; }bool xessEnabled() const { return desc_.enableFg && !desc_.noFeatures && !desc_.stillImage && desc_.frameGenerationBackend==engine::FrameGenerationBackend::XeSS; }+ bool fsrEnabled() const { return desc_.enableFg && !desc_.noFeatures && !desc_.stillImage && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Fsr; }+ // Frame generation implemented by the present sink (XeSS, FSR) instead of+ // the in-graph DLSSG path; both consume the same guidance motion texture.+ bool presentSinkFg() const { return xessEnabled() || fsrEnabled(); }// Requested output multiplier (2 = one generated frame). Consumed by the// present sink so the XeSS provider knows how many frames to generate.uint32_t fgMultiplier() const { return desc_.fgMultiplier; }diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 6af29957..7e483b1c 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -62,7 +62,7 @@ bool EngineController::idle()const{std::lock_guard lock(mutex_);return !busy_&&!void EngineController::open(HWND video,const std::wstring& path,PlayerOptions opts){const bool captureReplay=opts.captureReplayForTest;const bool disableAdmission=opts.captureReplayDisableFgAdmissionForTest;- {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}+ {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}opts.captureReplayForTest=captureReplay;opts.captureReplayDisableFgAdmissionForTest=disableAdmission;post([this,video,path,opts]{paused_=false;seekSeconds_=-1;run(video,path,opts);});@@ -70,7 +70,7 @@ void EngineController::open(HWND video,const std::wstring& path,PlayerOptions op#ifdef VEYRA_ENABLE_REMOTEPLAYvoid EngineController::openRemotePlay(HWND window,source::RemotePlayConnectDesc desc,PlayerOptions opts){auto request=std::make_shared<source::RemotePlayConnectDesc>(std::move(desc));- {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.remotePlay=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}+ {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.remotePlay=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}post([this,window,request,opts]{paused_=false;seekSeconds_=-1;run(window,L"remoteplay:",opts,request);});}remoteplay::ControllerFeedback EngineController::remotePlayFeedback(){std::lock_guard lock(mutex_);return activeRemote_?activeRemote_->takeFeedback():remoteplay::ControllerFeedback{};}@@ -100,6 +100,16 @@ bool EngineController::requestSettings(EnhancementSettings s){veyra::log::info("settings",std::format("xess multiplier gate: requested={} maxInterpolatedFrames={} applied=unchanged",s.multiplier,xessMaxInterpolatedFramesCap_));return false;}+ // The AMD 3.1.x frame-generation provider delivers exactly one generated+ // frame per presented frame; the probe (tools/fsr_probe) measured this on+ // every requested count, so anything above 2X is refused instead of+ // silently presenting 2X under a 4X label.+ if(s.multiplier>2&&s.frameGenerationBackend==FrameGenerationBackend::Fsr){+ snapshot_.status=L"AMD FSR 帧生成上限为 2X;请求未应用";+ snapshot_.failed=false;+ veyra::log::info("settings",std::format("fsr multiplier gate: requested={} maxGeneratedFrames=1 applied=unchanged",s.multiplier));+ return false;+ }// Revision partitions GPU history and measurements. Audio-only edits must// not invalidate in-flight video, and identical notifications are no-ops.s.revision=desired_.revision;if(s==desired_)return true;@@ -232,7 +242,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.snapshot().nrPolicy,isImage,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);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;const bool nvidiaAdapter=ctx.adapter().isNvidia;- const bool xessFg=options.settings.frameGenerationBackend==FrameGenerationBackend::XeSS;+ const bool xessFg=presentSinkFrameGeneration(options.settings.frameGenerationBackend);gd.nrBeforeSr=!isImage&&options.settings.lowLatency&&options.nr&&resolution.srApplied;gd.enableSr=resolution.srApplied&&nvidiaAdapter;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr&&nvidiaAdapter;gd.nrRuntime=options.settings.nrRuntime;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;@@ -258,6 +268,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sopened=presenter.open(ctx,window,graph,selected.settings.captureCompatible)&&graph.createViews();failure=FailedBackend::Infrastructure;if(opened&&graph.xessEnabled()&&!presenter.xessActive()){opened=false;failure=FailedBackend::Fg;}+ if(opened&&graph.fsrEnabled()&&!presenter.fsrActive()){opened=false;failure=FailedBackend::Fg;}}if(opened)return true;auto reduced=selected.snapshot();@@ -273,6 +284,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto xessState=gfx::XessMfgUnlock::snapshot();if(xessState.applied)capabilityGeneratedFrames=int(xessState.maxInterpolations);}+ else if(reduced.frameGenerationBackend==FrameGenerationBackend::Fsr){+ capabilityGeneratedFrames=int(presenter.fsrMaxGeneratedFrames());+ }}if(capabilityGeneratedFrames>0&&int(reduced.multiplier)-1>capabilityGeneratedFrames){const uint32_t clamped=uint32_t(capabilityGeneratedFrames+1);@@ -291,7 +305,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,spresenter.close();graph.shutdown();selected=PlayerOptions::from(reduced);const auto plan=pipeline::ResolutionPlan::make({width,height},selected.sr,reduced.nrPolicy,isImage,reduced.revision,reduced.srTarget,reduced.lowLatency&&selected.nr);desc.workWidth=plan.base.width;desc.workHeight=plan.base.height;desc.nrWidth=plan.nr.width;desc.nrHeight=plan.nr.height;desc.flowWidth=plan.flow.width;desc.flowHeight=plan.flow.height;- desc.enableNr=selected.nr&&nvidiaAdapter;desc.enableSr=plan.srApplied&&nvidiaAdapter;desc.enableFg=selected.fg&&(nvidiaAdapter||reduced.frameGenerationBackend==FrameGenerationBackend::XeSS);desc.fgMultiplier=selected.fgMultiplier;+ desc.enableNr=selected.nr&&nvidiaAdapter;desc.enableSr=plan.srApplied&&nvidiaAdapter;desc.enableFg=selected.fg&&(nvidiaAdapter||presentSinkFrameGeneration(reduced.frameGenerationBackend));desc.fgMultiplier=selected.fgMultiplier;desc.enableNvofStandalone=desc.enableNr;desc.nrBeforeSr=!isImage&&reduced.lowLatency&&selected.nr&&desc.enableSr;}return false;@@ -312,8 +326,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// session must not restrict the XeSS choices in the UI.xessMaxInterpolatedFramesCap_=xessState.providerLoaded?(xessState.applied&&xessState.maxInterpolations>0?int(xessState.maxInterpolations):1):0;snapshot_.xessMaxInterpolatedFrames=xessMaxInterpolatedFramesCap_;+ // AMD FSR ceiling comes from the running presenter; 0 keeps the+ // settings UI on its static 2X fallback until a session ran.+ fsrMaxGeneratedFramesCap_=graph.fsrEnabled()&&presenter.fsrActive()?int(presenter.fsrMaxGeneratedFrames()):0;+ snapshot_.fsrMaxGeneratedFrames=fsrMaxGeneratedFramesCap_;if(fgMultiFrameMaxCap_>0)veyra::log::info("settings",std::format("frame-generation capability: maxGeneratedFrames={} maxMultiplier={}",fgMultiFrameMaxCap_,fgMultiFrameMaxCap_+1));veyra::log::info("settings",std::format("xess capability: maxInterpolatedFrames={} unlockApplied={} => maxMultiplier={}",xessState.maxInterpolations,xessState.applied,xessMaxInterpolatedFramesCap_+1));+ if(fsrMaxGeneratedFramesCap_>0)veyra::log::info("settings",std::format("fsr capability: generatedPerPresent={} => maxMultiplier={}",fsrMaxGeneratedFramesCap_,fsrMaxGeneratedFramesCap_+1));}if(!previewInitialized){status(L"视频初始化失败,请查看对应组件的诊断日志",true);break;}if(!backendRecoveryWarning.empty()){@@ -515,8 +534,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sbool captureRecovering=false;unsigned captureRetries=0;Clock::time_point captureRetryAt{};bool xessPresentationRecovery=false;+ bool fsrPresentationRecovery=false;+ bool fsrDegradedReported=false;auto recoverXessPresentation=[&]{- if(!presenter.xessFailed()||FAILED(ctx.device()->GetDeviceRemovedReason()))return false;+ const bool fsrFailed=presenter.fsrFailed();+ if((!presenter.xessFailed()&&!fsrFailed)||FAILED(ctx.device()->GetDeviceRemovedReason()))return false;auto reduced=options.snapshot();if(!disableFailedBackend(reduced,FailedBackend::Fg))return false;holdFileAudio();fileAudioAlignPending=true;@@ -530,10 +552,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sstd::lock_guard lock(mutex_);desired_.rejectVideoRequest(options.snapshot(),reduced);desired_.revision=++nextRevision_;snapshot_.desired=desired_;snapshot_.applying=true;- snapshot_.backendWarning=L"XeSS 呈现失败,正在恢复基础播放;错误码见日志";+ snapshot_.backendWarning=fsrFailed?L"AMD FSR 帧生成呈现失败,正在恢复基础播放;错误码见日志":L"XeSS 呈现失败,正在恢复基础播放;错误码见日志";}- veyra::log::warn("backend-recovery","XeSS presentation failed; drained commands, requesting swapchain rebuild without FG");- xessPresentationRecovery=true;+ veyra::log::warn("backend-recovery",std::format("{} presentation failed; drained commands, requesting swapchain rebuild without FG",fsrFailed?"AMD FSR":"XeSS"));+ xessPresentationRecovery=!fsrFailed;+ fsrPresentationRecovery=fsrFailed;reset=true;pendingResetCause=pipeline::ResetReason::Settings;return true;};@@ -613,7 +636,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto plan=pipeline::ResolutionPlan::make({width,height},next.sr,requested.nrPolicy,isImage,requested.revision,requested.srTarget,requested.lowLatency&&requested.nr);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;const bool nvidiaAdapter=ctx.adapter().isNvidia;- const bool xessFg=next.settings.frameGenerationBackend==FrameGenerationBackend::XeSS;+ const bool xessFg=presentSinkFrameGeneration(next.settings.frameGenerationBackend);nextDesc.nrBeforeSr=!isImage&&requested.lowLatency&&requested.nr&&plan.srApplied;nextDesc.enableSr=plan.srApplied&&nvidiaAdapter;nextDesc.videoSrQuality=next.settings.videoSrQuality;nextDesc.enableNr=next.nr&&nvidiaAdapter;nextDesc.nrRuntime=next.settings.nrRuntime;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;nextDesc.opticalFlowBackend=requested.opticalFlowBackend;nextDesc.amdFlowHalfResolution=requested.amdFlowHalfResolution;@@ -630,6 +653,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}else if(accepted)accepted=graph.applySettings(requested);if(accepted){if(xessPresentationRecovery){backendRecoveryWarning=L"XeSS 呈现失败,已关闭补帧并恢复播放;错误码见日志";xessPresentationRecovery=false;}+ if(fsrPresentationRecovery){backendRecoveryWarning=L"AMD FSR 帧生成呈现失败,已关闭补帧并恢复播放;错误码见日志";fsrPresentationRecovery=false;}if(!backendRecoveryWarning.empty()){std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,next.snapshot());snapshot_.desired=desired_;snapshot_.backendWarning=backendRecoveryWarning;}@@ -639,7 +663,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}else {finishReset(diagnostics::ResetOutcome::RolledBack);- std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"设置应用失败,已恢复上一套参数";snapshot_.backendWarning=requested.nrRuntime!=previous.nrRuntime?L"NR运行版本切换失败,已恢复上一套参数":requested.frameGenerationBackend==FrameGenerationBackend::XeSS?L"XeSS 未能启用,已恢复上一套参数":L"后端切换失败,已恢复上一套参数";}+ std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"设置应用失败,已恢复上一套参数";snapshot_.backendWarning=requested.nrRuntime!=previous.nrRuntime?L"NR运行版本切换失败,已恢复上一套参数":requested.frameGenerationBackend==FrameGenerationBackend::XeSS?L"XeSS 未能启用,已恢复上一套参数":requested.frameGenerationBackend==FrameGenerationBackend::Fsr?L"AMD FSR 帧生成未能启用,已恢复上一套参数":L"后端切换失败,已恢复上一套参数";}}if(stop_)break;double seek;{std::lock_guard lock(mutex_);seek=seekSeconds_.exchange(-1);if(seek>=0)activeSeekId=snapshot_.seekRequested;}@@ -805,7 +829,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(fgBudgetRevision!=options.settings.revision){fgBudget.reset();fgBudgetRevision=options.settings.revision;}// DLSS can reseed after a skipped pair. XeSS// owns generation inside its presenter and has no graph admission.- if(isCapture&&!rereadCached&&useLiveFgAdmission&&options.settings.frameGenerationBackend!=FrameGenerationBackend::XeSS){+ if(isCapture&&!rereadCached&&useLiveFgAdmission&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)){const auto presentP95=livePresent.p95();admitFg=[&,presentP95](const pipeline::FrameBatch& batch){// Physical capture and PS5 delivery clocks are not@@ -829,7 +853,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// deadlines on the audio master clock. A pair whose last// generated timestamp can no longer be reached spends no FG// Evaluate; the real frame keeps its normal cadence (plan §4.1).- if(!isCapture&&!isImage&&!rereadCached&&!transaction&&options.fg&&options.settings.frameGenerationBackend!=FrameGenerationBackend::XeSS){+ if(!isCapture&&!isImage&&!rereadCached&&!transaction&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)){admitFg=[&,historyReset](const pipeline::FrameBatch& batch){if(fileAwaitingVideo)return true; // Bounded startup lookahead; audio has not started.const auto interval=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);@@ -861,7 +885,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,soptions=PlayerOptions::from(reduced);const auto plan=pipeline::ResolutionPlan::make({width,height},options.sr,reduced.nrPolicy,isImage,reduced.revision,reduced.srTarget,reduced.lowLatency&&reduced.nr);gd.workWidth=plan.base.width;gd.workHeight=plan.base.height;gd.nrWidth=plan.nr.width;gd.nrHeight=plan.nr.height;gd.flowWidth=plan.flow.width;gd.flowHeight=plan.flow.height;- gd.enableNr=options.nr&&nvidiaAdapter;gd.enableSr=plan.srApplied&&nvidiaAdapter;gd.enableFg=options.fg&&(nvidiaAdapter||reduced.frameGenerationBackend==FrameGenerationBackend::XeSS);gd.fgMultiplier=options.fgMultiplier;gd.enableNvofStandalone=gd.enableNr;gd.settingsRevision=reduced.revision;gd.nrBeforeSr=!isImage&&reduced.lowLatency&&gd.enableNr&&gd.enableSr;+ gd.enableNr=options.nr&&nvidiaAdapter;gd.enableSr=plan.srApplied&&nvidiaAdapter;gd.enableFg=options.fg&&(nvidiaAdapter||presentSinkFrameGeneration(reduced.frameGenerationBackend));gd.fgMultiplier=options.fgMultiplier;gd.enableNvofStandalone=gd.enableNr;gd.settingsRevision=reduced.revision;gd.nrBeforeSr=!isImage&&reduced.lowLatency&&gd.enableNr&&gd.enableSr;if(!initializePreview(gd,options)){status(L"增强故障后的基础图重建失败",true);break;}backendRecoveryWarning=std::wstring(backendFailureName(failedComponent))+L"运行失败,已关闭对应效果;错误码见日志"+(backendRecoveryWarning.empty()?L"":L";"+backendRecoveryWarning);{std::lock_guard lock(mutex_);desired_.rejectVideoRequest(attempted,options.snapshot());snapshot_.desired=desired_;snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;snapshot_.backendWarning=backendRecoveryWarning;}@@ -1011,8 +1035,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto waited=elapsedMs(*s.deadlineStart);s.deadlineStart.reset();s.waitMs+=waited;flow->cpu(diagnostics::CpuStage::DeadlineWait,waited,host100ns());const auto begin=Clock::now();const auto before=presenter.submittedCount();const auto beforeXess=presenter.xessGeneratedCount(),beforeXessPresented=presenter.xessPresentedCount();+ const auto beforeFsr=presenter.fsrGeneratedCount(),beforeFsrPresented=presenter.fsrPresentedCount();if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView()))return {State::Failed};const auto xessGenerated=presenter.xessGeneratedCount()-beforeXess,xessPresented=presenter.xessPresentedCount()-beforeXessPresented;+ const auto fsrGenerated=presenter.fsrGeneratedCount()-beforeFsr,fsrPresented=presenter.fsrPresentedCount()-beforeFsrPresented;item.lease->consumerFence=ring.lastSignaledValue();const bool didPresent=presenter.submittedCount()>before;s.blit=presenter.blitTiming(ctx.fence());const auto elapsed=elapsedMs(begin);s.presentMs+=elapsed;flow->cpu(diagnostics::CpuStage::Present,elapsed,host100ns());if(didPresent){@@ -1020,6 +1046,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",batch.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));}if(xessPresented)flow->xessSubmitted(xessPresented,xessGenerated,host100ns());+ // Same metric shape for the AMD provider: frames it actually+ // submitted to the display, real and generated.+ if(fsrPresented)flow->xessSubmitted(fsrPresented,fsrGenerated,host100ns());if(didPresent&&!isCapture){lastFilePresentedMs=itemPtsMs;lastFilePresentLateness=fileAwaitingVideo?0:nowMs()-itemPtsMs;{std::lock_guard lock(mutex_);if(snapshot_.sessionId==runSessionId&&snapshot_.applied.revision==item.identity.settingsRevision){@@ -1116,6 +1145,15 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(graph.xessEnabled()){graphStats.fgGeneratedFrames=presenter.xessGeneratedCount();}+ if(graph.fsrEnabled()){+ graphStats.fgGeneratedFrames=presenter.fsrGeneratedCount();+ }+ if(graph.fsrEnabled()&&presenter.fsrFailed()&&!fsrDegradedReported){+ fsrDegradedReported=true;+ std::lock_guard lock(mutex_);+ snapshot_.backendWarning=L"AMD FSR 帧生成已停用(原因见日志),继续基础播放";+ veyra::log::warn("backend-recovery","AMD FSR frame generation degraded to plain presentation inside the provider");+ }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.snapshot().nrPolicy,isImage,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.queueWatermark=out.batch.count;LiveStats completed;if(liveScheduler)completed=liveStats;diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cppindex fc01f761..d0e8cd89 100644--- a/src/engine/PresetStore.cpp+++ b/src/engine/PresetStore.cpp@@ -13,18 +13,18 @@ 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 12\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 13\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<' '<<int(s.audioSync)<<' '<<s.audioOffsetMs<<' '<<int(s.nrRuntime)<<' '<<s.captureCompatible<<' '<<s.lowLatency<<' '<<s.forceSdrPreview<<'\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>12)||!(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>13)||!(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>(version>=6&&version<=7?2:1))return false;+ if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>(version>=13?2:(version>=6&&version<=7?2:1)))return false;// Before v8, 1 meant removed FRUC and 2 meant XeSS. New writes use v10.s.frameGenerationBackend=version<8?(backend==2?FrameGenerationBackend::XeSS:FrameGenerationBackend::Dlss)diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex ec3975eb..b9f23f4c 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -22,9 +22,9 @@ 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 或关闭补帧");- veyra::log::warn("export","XeSS FG export rejected: public XeSS swapchain API has no encoder texture output contract");+ if(options.fg&&presentSinkFrameGeneration(options.settings.frameGenerationBackend)){+ progress(0,L"XeSS / AMD FSR 帧生成目前仅支持预览;导出请选择 DLSS 或关闭补帧");+ veyra::log::warn("export","present-sink frame generation export rejected: the swapchain interpolation APIs have no encoder texture output contract");return false;}gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);sink::NvencD3D12Encoder enc;diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 490518d7..3d85924b 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -7,7 +7,7 @@ namespace veyra::engine {bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph,bool captureCompatible) {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.hdr=graph.hdrOutput();d.hdr10=graph.hdr10Output();d.xess=graph.xessEnabled();d.captureCompatible=captureCompatible;d.fgMultiplier=graph.fgMultiplier();lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=false;+ d.hdr=graph.hdrOutput();d.hdr10=graph.hdr10Output();d.xess=graph.xessEnabled();d.fsr=graph.fsrEnabled();d.renderWidth=graph.workWidth();d.renderHeight=graph.workHeight();d.captureCompatible=captureCompatible;d.fgMultiplier=graph.fgMultiplier();lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=false;lastFsrFrame_={};lastFsrIdentity_={};fsrWasEnabled_=false;Status st=Status::Ok;if(!sink_.initialize(ctx.device(),ctx.directQueue(),d,st))return false;std::vector<uint8_t> vs,ps;// SRV layout: 0..1 video frames, 2..11 generated frames (2 parities x 5@@ -22,7 +22,7 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh}void VideoPresenter::refresh(ID3D12Device* device){for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,bool referencesValid,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view) {- xessFailed_=false;+ xessFailed_=false;fsrFailed_=false;RECT rc{};GetClientRect(window_,&rc);if(rc.right<1||rc.bottom<1)return true;const auto now=std::chrono::steady_clock::now();const auto deferUntil=uint64_t(uintptr_t(GetPropW(window_,L"Veyra.ResizeDeferUntil")));@@ -94,9 +94,23 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&}else if(!xess->tag(list,bb,motion,depth,{left,top,left+w,top+h},false,reset,elapsed)){xessFailed_=true;return false;}lastXessFrame_=now;lastXessIdentity_=identity;xessWasEnabled_=enabled;}+ if(auto* fsr=sink_.fsr()){+ 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!=lastFsrIdentity_.sourceFrameId;+ const bool reset=!fsrWasEnabled_||identity.epoch!=lastFsrIdentity_.epoch||identity.settingsRevision!=lastFsrIdentity_.settingsRevision||graph.motionPreviousSource(slot)!=lastFsrIdentity_.sourceFrameId;+ const float elapsed=lastFsrFrame_==std::chrono::steady_clock::time_point{}?0.0f:float(std::chrono::duration<double,std::milli>(now-lastFsrFrame_).count());+ // The AMD presenter degrades inside the provider (generation off, plain+ // presentation continues) instead of failing the frame: tearing the+ // swapchain down would only cost the session a restart.+ if(!fsr->tag(list,bb,graph.presentMotion(slot),graph.presentDepth(),{left,top,left+w,top+h},enabled,reset,elapsed))fsrFailed_=true;+ if(sink_.fsr()->failed())fsrFailed_=true;+ lastFsrFrame_=now;lastFsrIdentity_=identity;fsrWasEnabled_=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;- const bool presented=sink_.present(st);xessFailed_=sink_.xessFailed();return presented;+ const bool presented=sink_.present(st);xessFailed_=sink_.xessFailed();fsrFailed_=fsrFailed_||sink_.fsrFailed();return presented;}bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,sink::RgbaImage& image){if(!hasPresented_||!sink_.swapChain()||!ring.drainQueue())return false;diff --git a/src/gfx/FsrFgPresenter.cpp b/src/gfx/FsrFgPresenter.cppnew file mode 100644index 00000000..ccfeba2c--- /dev/null+++ b/src/gfx/FsrFgPresenter.cpp@@ -0,0 +1,567 @@+#include "veyra/gfx/FsrFgPresenter.h"++#include "veyra/Log.h"+#include "veyra/RuntimePaths.h"++#include <atomic>+#include <filesystem>+#include <string>++#ifdef VEYRA_HAS_FSR+#include <ffx_api_loader.h>+#include <ffx_framegeneration.h>+#include <dx12/ffx_api_framegeneration_dx12.h>+#endif++namespace veyra::gfx {++#ifdef VEYRA_HAS_FSR+namespace {++void fsrMessage(uint32_t type, const wchar_t* message) {+ if (message == nullptr) return;+ const int length = WideCharToMultiByte(CP_UTF8, 0, message, -1, nullptr, 0, nullptr, nullptr);+ std::string text(size_t(length > 0 ? length - 1 : 0), '\0');+ if (length > 1) {+ WideCharToMultiByte(CP_UTF8, 0, message, -1, text.data(), length, nullptr, nullptr);+ }+ if (type == FFX_API_MESSAGE_TYPE_ERROR) log::error("fsr-sdk", text);+ else log::warn("fsr-sdk", text);+}++FfxApiSurfaceFormat surfaceFormatFromDxgi(DXGI_FORMAT format) {+ switch (format) {+ case DXGI_FORMAT_R8G8B8A8_UNORM: return FFX_API_SURFACE_FORMAT_R8G8B8A8_UNORM;+ case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return FFX_API_SURFACE_FORMAT_R8G8B8A8_SRGB;+ case DXGI_FORMAT_R10G10B10A2_UNORM: return FFX_API_SURFACE_FORMAT_R10G10B10A2_UNORM;+ case DXGI_FORMAT_R16G16B16A16_FLOAT: return FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT;+ case DXGI_FORMAT_R16G16_FLOAT: return FFX_API_SURFACE_FORMAT_R16G16_FLOAT;+ case DXGI_FORMAT_R32_FLOAT: return FFX_API_SURFACE_FORMAT_R32_FLOAT;+ default: return FFX_API_SURFACE_FORMAT_UNKNOWN;+ }+}++FfxApiResource makeResource(ID3D12Resource* resource, uint32_t state) {+ FfxApiResource api{};+ if (resource == nullptr) return api;+ const D3D12_RESOURCE_DESC desc = resource->GetDesc();+ api.resource = resource;+ api.description.type = FFX_API_RESOURCE_TYPE_TEXTURE2D;+ api.description.format = surfaceFormatFromDxgi(desc.Format);+ api.description.width = uint32_t(desc.Width);+ api.description.height = desc.Height;+ api.description.depth = desc.DepthOrArraySize;+ api.description.mipCount = desc.MipLevels;+ api.description.flags = 0;+ api.description.usage = FFX_API_RESOURCE_USAGE_READ_ONLY;+ if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0) {+ api.description.usage = FfxApiResourceUsage(api.description.usage | FFX_API_RESOURCE_USAGE_UAV);+ }+ api.state = state;+ return api;+}++D3D12_RESOURCE_STATES dx12State(uint32_t ffxState) {+ switch (ffxState) {+ case FFX_API_RESOURCE_STATE_UNORDERED_ACCESS: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;+ case FFX_API_RESOURCE_STATE_PIXEL_COMPUTE_READ:+ return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;+ case FFX_API_RESOURCE_STATE_COMPUTE_READ: return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;+ case FFX_API_RESOURCE_STATE_COPY_SRC: return D3D12_RESOURCE_STATE_COPY_SOURCE;+ case FFX_API_RESOURCE_STATE_COPY_DEST: return D3D12_RESOURCE_STATE_COPY_DEST;+ case FFX_API_RESOURCE_STATE_PRESENT: return D3D12_RESOURCE_STATE_PRESENT;+ case FFX_API_RESOURCE_STATE_RENDER_TARGET: return D3D12_RESOURCE_STATE_RENDER_TARGET;+ default: return D3D12_RESOURCE_STATE_COMMON;+ }+}++} // namespace+#endif++struct FsrFgPresenter::Impl {+ // Written from the provider's presentation thread.+ std::atomic<uint64_t> realFrames{0};+ std::atomic<uint64_t> generatedFrames{0};+ std::atomic<uint64_t> callbackFailures{0};+ // Render thread.+ uint64_t frameId = 0;+ uint32_t requestedGenerated = 0;+ uint32_t deliveredGenerated = 0;+ bool failed = false;+ bool softDisabled = false;+ bool available = false;+ std::string providerVersion;++ // A provider failure must not take playback down with it: generation is+ // switched off, the frame keeps presenting through the proxy swapchain and+ // the engine is told once so it can surface a warning.+ void disableGeneration(const char* reason) {+ if (!softDisabled) {+ softDisabled = true;+ failed = true;+ log::warn("fsr-fg", std::format("frame generation disabled after {}; plain presentation continues", reason));+ }+ }+#ifdef VEYRA_HAS_FSR+ HMODULE loader = nullptr;+ ffxFunctions functions{};+ ffxContext swapchainContext = nullptr;+ ffxContext fgContext = nullptr;+ IDXGISwapChain4* swapchain = nullptr; // borrowed; owned by the sink and the context+ uint32_t width = 0;+ uint32_t height = 0;+ uint32_t backBufferFormat = FFX_API_SURFACE_FORMAT_UNKNOWN;+#endif+};++#ifdef VEYRA_HAS_FSR+namespace {++// Called by the provider for every frame that reaches the swapchain, real or+// interpolated, on its presentation thread. Veyra has no UI surface to+// composite, so this performs the same copy the provider's default callback+// would and only keeps counters. No logging or allocation happens here.+ffxReturnCode_t presentCallback(ffxCallbackDescFrameGenerationPresent* params, void* userCtx) {+ auto* impl = static_cast<FsrFgPresenter::Impl*>(userCtx);+ if (params == nullptr || impl == nullptr) return FFX_API_RETURN_ERROR_PARAMETER;+ if (params->isGeneratedFrame) {+ impl->generatedFrames.fetch_add(1, std::memory_order_relaxed);+ } else {+ impl->realFrames.fetch_add(1, std::memory_order_relaxed);+ }+ if (params->currentUI.resource != nullptr || params->commandList == nullptr ||+ params->outputSwapChainBuffer.resource == nullptr || params->currentBackBuffer.resource == nullptr) {+ impl->callbackFailures.fetch_add(1, std::memory_order_relaxed);+ return FFX_API_RETURN_OK;+ }+ auto* list = static_cast<ID3D12GraphicsCommandList*>(params->commandList);+ auto* destination = static_cast<ID3D12Resource*>(params->outputSwapChainBuffer.resource);+ auto* source = static_cast<ID3D12Resource*>(params->currentBackBuffer.resource);+ D3D12_RESOURCE_BARRIER barriers[2]{};+ barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barriers[0].Transition.pResource = source;+ barriers[0].Transition.StateBefore = dx12State(params->currentBackBuffer.state);+ barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;+ barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barriers[1].Transition.pResource = destination;+ barriers[1].Transition.StateBefore = dx12State(params->outputSwapChainBuffer.state);+ barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;+ list->ResourceBarrier(2, barriers);+ list->CopyResource(destination, source);+ for (auto& barrier : barriers) {+ const D3D12_RESOURCE_STATES before = barrier.Transition.StateBefore;+ barrier.Transition.StateBefore = barrier.Transition.StateAfter;+ barrier.Transition.StateAfter = before;+ }+ list->ResourceBarrier(2, barriers);+ return FFX_API_RETURN_OK;+}++const char* returnName(ffxReturnCode_t code) {+ switch (code) {+ case FFX_API_RETURN_OK: return "OK";+ case FFX_API_RETURN_ERROR: return "ERROR";+ case FFX_API_RETURN_ERROR_UNKNOWN_DESCTYPE: return "ERROR_UNKNOWN_DESCTYPE";+ case FFX_API_RETURN_ERROR_RUNTIME_ERROR: return "ERROR_RUNTIME_ERROR";+ case FFX_API_RETURN_NO_PROVIDER: return "NO_PROVIDER";+ case FFX_API_RETURN_ERROR_MEMORY: return "ERROR_MEMORY";+ case FFX_API_RETURN_ERROR_PARAMETER: return "ERROR_PARAMETER";+ case FFX_API_RETURN_PROVIDER_NO_SUPPORT_NEW_DESCTYPE: return "PROVIDER_NO_SUPPORT_NEW_DESCTYPE";+ default: return "OTHER";+ }+}++} // namespace+#endif++FsrFgPresenter::FsrFgPresenter() : p_(std::make_unique<Impl>()) {}++FsrFgPresenter::~FsrFgPresenter() {+#ifdef VEYRA_HAS_FSR+ auto& p = *p_;+ // The provider requires generation to be switched off before the context+ // goes away: that call flushes interpolation and UI composition GPU work,+ // after which the context can release the proxy swapchain (and with it the+ // real DXGI swapchain, which is what lets another swapchain be created for+ // the same HWND later).+ if (p.fgContext != nullptr && p.swapchain != nullptr) {+ ffxConfigureDescFrameGeneration disable{};+ disable.header.type = FFX_API_CONFIGURE_DESC_TYPE_FRAMEGENERATION;+ disable.swapChain = p.swapchain;+ disable.frameGenerationEnabled = false;+ disable.presentCallback = presentCallback;+ disable.presentCallbackUserContext = &p;+ disable.generationRect = {0, 0, int32_t(p.width), int32_t(p.height)};+ disable.frameID = p.frameId;+ const auto result = p.functions.Configure(&p.fgContext, &disable.header);+ log::info("fsr-fg", std::format("shutdown disable result={} frameId={}", returnName(result), p.frameId));+ }+ // The context owns one reference to the proxy swapchain and releases it+ // here; the sink drops its own reference before this object is destroyed.+ if (p.fgContext != nullptr) {+ const auto result = p.functions.DestroyContext(&p.fgContext, nullptr);+ log::info("fsr-fg", std::format("framegen context destroyed result={}", returnName(result)));+ }+ if (p.swapchainContext != nullptr) {+ const auto result = p.functions.DestroyContext(&p.swapchainContext, nullptr);+ log::info("fsr-fg", std::format("swapchain context destroyed result={}", returnName(result)));+ }+ p.swapchain = nullptr;+ if (p.loader != nullptr) FreeLibrary(p.loader);+#endif+}++bool FsrFgPresenter::initialize(ID3D12Device* device, ID3D12CommandQueue* queue, IDXGIFactory2* factory,+ HWND window, const DXGI_SWAP_CHAIN_DESC1& desc, uint32_t renderWidth,+ uint32_t renderHeight, IDXGISwapChain4** swapchain, uint32_t fgMultiplier) {+#ifdef VEYRA_HAS_FSR+ auto& p = *p_;+ (void)fgMultiplier;+ const auto root = runtime::localDataDirectory() / "amd" / "framegeneration";+ const auto loaderPath = std::filesystem::absolute(root / "amd_fidelityfx_loader_dx12.dll");+ const auto providerPath = std::filesystem::absolute(root / "amd_fidelityfx_framegeneration_dx12.dll");++ p.requestedGenerated = 1; // FSR 3.1.x providers deliver one generated frame per present++ // The loader resolves provider DLLs by base name through the normal search+ // order, so pre-loading the provider by absolute path and pointing the+ // legacy DLL directory at the same folder keeps the discovery deterministic+ // without leaking the directory into the rest of the process.+ wchar_t previousDirectory[MAX_PATH]{};+ const DWORD previousLength = GetDllDirectoryW(MAX_PATH, previousDirectory);+ SetDllDirectoryW(root.c_str());+ struct DirectoryGuard {+ const wchar_t* previous = nullptr;+ DWORD previousLength = 0;+ wchar_t buffer[MAX_PATH]{};+ ~DirectoryGuard() { SetDllDirectoryW(previousLength > 0 ? buffer : nullptr); }+ } directoryGuard;+ directoryGuard.previous = previousDirectory;+ directoryGuard.previousLength = previousLength;+ if (previousLength > 0 && previousLength < MAX_PATH) {+ wcsncpy_s(directoryGuard.buffer, previousDirectory, previousLength);+ }++ p.loader = LoadLibraryExW(loaderPath.c_str(), nullptr,+ LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);+ if (p.loader == nullptr) {+ log::error("fsr-fg", std::format("loader load failed path={} win32={}", loaderPath.string(), GetLastError()));+ return false;+ }+ if (std::filesystem::exists(providerPath)) {+ // Signed AMD provider; the loader is expected to pick this module up.+ if (LoadLibraryExW(providerPath.c_str(), nullptr,+ LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32) == nullptr) {+ log::warn("fsr-fg", std::format("provider preload failed path={} win32={}", providerPath.string(), GetLastError()));+ }+ }+ ffxLoadFunctions(&p.functions, p.loader);+ if (p.functions.CreateContext == nullptr || p.functions.DestroyContext == nullptr ||+ p.functions.Configure == nullptr || p.functions.Query == nullptr || p.functions.Dispatch == nullptr) {+ log::error("fsr-fg", "loader is missing the FidelityFX API entry points");+ return false;+ }++ // Report which provider version serves this adapter before creating it, so+ // the log carries the same evidence as the standalone probe.+ {+ uint64_t count = 0;+ ffxQueryDescGetVersions versions{};+ versions.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS;+ versions.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION;+ versions.device = device;+ versions.outputCount = &count;+ uint64_t ids[8]{};+ const char* names[8]{};+ uint64_t capacity = 8;+ versions.versionIds = ids;+ versions.versionNames = names;+ versions.outputCount = &capacity;+ const auto queryResult = p.functions.Query(nullptr, &versions.header);+ if (queryResult == FFX_API_RETURN_OK && capacity > 0) {+ p.providerVersion = names[0] != nullptr ? names[0] : "unknown";+ }+ log::info("fsr-fg", std::format("providers query={} count={} framegen={} swapchainVersion={}", returnName(queryResult),+ capacity, p.providerVersion.empty() ? "none" : p.providerVersion,+ FFX_FRAMEGENERATION_SWAPCHAIN_DX12_VERSION));+ }++ ffxCreateContextDescFrameGenerationSwapChainVersionDX12 swapchainVersion{};+ swapchainVersion.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_VERSION_DX12;+ swapchainVersion.version = FFX_FRAMEGENERATION_SWAPCHAIN_DX12_VERSION;+ IDXGISwapChain4* proxy = nullptr;+ ffxCreateContextDescFrameGenerationSwapChainForHwndDX12 swapchainDesc{};+ swapchainDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_FOR_HWND_DX12;+ swapchainDesc.header.pNext = &swapchainVersion.header;+ swapchainDesc.swapchain = &proxy;+ swapchainDesc.hwnd = window;+ swapchainDesc.desc = &const_cast<DXGI_SWAP_CHAIN_DESC1&>(desc);+ swapchainDesc.fullscreenDesc = nullptr;+ swapchainDesc.dxgiFactory = factory;+ swapchainDesc.gameQueue = queue;+ const auto swapchainResult = p.functions.CreateContext(&p.swapchainContext, &swapchainDesc.header, nullptr);+ if (swapchainResult != FFX_API_RETURN_OK || p.swapchainContext == nullptr || proxy == nullptr) {+ log::error("fsr-fg", std::format("swapchain context failed result={} (0x{:X})", returnName(swapchainResult),+ unsigned(swapchainResult)));+ p.failed = true;+ return false;+ }+ p.swapchain = proxy;+ p.width = desc.Width;+ p.height = desc.Height;+ p.backBufferFormat = surfaceFormatFromDxgi(desc.Format);++ ffxCreateBackendDX12Desc backendDesc{};+ backendDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_DX12;+ backendDesc.device = device;+ ffxCreateContextDescFrameGenerationVersion fgVersion{};+ fgVersion.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION_VERSION;+ fgVersion.version = FFX_FRAMEGENERATION_VERSION;+ ffxCreateContextDescFrameGeneration fgDesc{};+ fgDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION;+ fgDesc.header.pNext = &backendDesc.header;+ backendDesc.header.pNext = &fgVersion.header;+ // Debug checking makes the provider report the exact reason a dispatch is+ // rejected instead of a bare runtime error code.+ fgDesc.flags = 0;+ fgDesc.displaySize = {p.width, p.height};+ // The provider validates the per-frame renderSize against maxRenderSize; the+ // working extent can be larger than the window buffer (contain-scaled+ // preview), so the ceiling covers both.+ fgDesc.maxRenderSize = {std::max(p.width, renderWidth), std::max(p.height, renderHeight)};+ fgDesc.backBufferFormat = p.backBufferFormat;+ auto fgResult = p.functions.CreateContext(&p.fgContext, &fgDesc.header, nullptr);+ if (fgResult != FFX_API_RETURN_OK || p.fgContext == nullptr) {+ log::warn("fsr-fg", std::format("frame generation context with version desc failed result={}; retrying without it",+ returnName(fgResult)));+ backendDesc.header.pNext = nullptr;+ fgResult = p.functions.CreateContext(&p.fgContext, &fgDesc.header, nullptr);+ }+ if (fgResult != FFX_API_RETURN_OK || p.fgContext == nullptr) {+ log::error("fsr-fg", std::format("frame generation context failed result={} (0x{:X})", returnName(fgResult),+ unsigned(fgResult)));+ p.failed = true;+ return false;+ }+ p.available = true;+ p.deliveredGenerated = p.requestedGenerated;+ {+ ffxConfigureDescGlobalDebug1 global{};+ global.header.type = FFX_API_CONFIGURE_DESC_TYPE_GLOBALDEBUG1;+ global.fpMessage = fsrMessage;+ global.debugLevel = FFX_API_CONFIGURE_GLOBALDEBUG_LEVEL_WARNINGS;+ p.functions.Configure(nullptr, &global.header);+ p.functions.Configure(&p.fgContext, &global.header);+ if (p.swapchainContext != nullptr) p.functions.Configure(&p.swapchainContext, &global.header);+ }+ *swapchain = proxy;+ log::info("fsr-fg", std::format("provider={} swapchain={}x{} maxRender={}x{} format={} multiplierRequested={}X (delivered multiplier is reported per frame)",+ p.providerVersion.empty() ? "unknown" : p.providerVersion, p.width, p.height,+ fgDesc.maxRenderSize.width, fgDesc.maxRenderSize.height,+ int(desc.Format), p.requestedGenerated + 1));+ return true;+#else+ (void)device; (void)queue; (void)factory; (void)window; (void)desc; (void)swapchain; (void)fgMultiplier;+ log::error("fsr-fg", "AMD FidelityFX SDK headers were unavailable at build time");+ return false;+#endif+}++bool FsrFgPresenter::tag(ID3D12GraphicsCommandList* list, ID3D12Resource* backBuffer, ID3D12Resource* motion,+ ID3D12Resource* depth, RECT region, bool enabled, bool reset, float elapsedMs) {+#ifdef VEYRA_HAS_FSR+ auto& p = *p_;+ if (!p.available) return false;+ if (region.right <= region.left || region.bottom <= region.top) return false;++ ffxConfigureDescFrameGeneration configure{};+ configure.header.type = FFX_API_CONFIGURE_DESC_TYPE_FRAMEGENERATION;+ configure.swapChain = p.swapchain;+ configure.presentCallback = presentCallback;+ configure.presentCallbackUserContext = &p;+ configure.frameGenerationEnabled = enabled;+ configure.allowAsyncWorkloads = false;+ configure.flags = 0;+ configure.generationRect = {region.left, region.top, region.right - region.left, region.bottom - region.top};+ configure.frameID = p.frameId;++ if (!enabled) {+ const auto result = p.functions.Configure(&p.fgContext, &configure.header);+ if (result != FFX_API_RETURN_OK) {+ log::warn("fsr-fg", std::format("configure(disabled) result={} frameId={}", returnName(result), p.frameId));+ p.disableGeneration("configure(disabled) rejection");+ }+ return true;+ }+ if (list == nullptr || backBuffer == nullptr || motion == nullptr || depth == nullptr) return false;+ if (p.softDisabled) return true;++ // The provider runs its own presentation/pacing threads; flushing their+ // outstanding presentations before recording the next frame is what the+ // swapchain contract expects from an application that is not otherwise+ // synchronized to the display (the player submits as fast as it decodes).+ {+ ffxDispatchDescFrameGenerationSwapChainWaitForPresentsDX12 wait{};+ wait.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_WAIT_FOR_PRESENTS_DX12;+ const auto waitResult = p.functions.Dispatch(&p.swapchainContext, &wait.header);+ if (waitResult != FFX_API_RETURN_OK) {+ log::warn("fsr-fg", std::format("wait-for-presents result={} frameId={}", returnName(waitResult), p.frameId));+ }+ }++ ffxDispatchDescFrameGenerationPrepareV2 prepare{};+ prepare.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATION_PREPARE_V2;+ prepare.frameID = p.frameId;+ prepare.flags = 0;+ prepare.commandList = list;+ prepare.renderSize = {uint32_t(motion->GetDesc().Width), motion->GetDesc().Height};+ prepare.jitterOffset = {0.0f, 0.0f};+ // Guidance motion is pixel space in working-extent units, so the scale that+ // converts it to UV inside the provider is 1:1. FSR reprojects with+ // "previous = current + motion", which already matches Veyra's+ // current->previous guidance (DLSSG needs the opposite sign).+ prepare.motionVectorScale = {1.0f, 1.0f};+ prepare.frameTimeDelta = elapsedMs > 0.0f ? elapsedMs : 16.6f;+ prepare.reset = reset;+ prepare.cameraNear = 0.1f;+ prepare.cameraFar = 1000.0f;+ prepare.cameraFovAngleVertical = 1.0f;+ prepare.viewSpaceToMetersFactor = 0.0f;+ // The graph leaves both guidance textures in the common state after each+ // frame, so the declared state must be the truthful one: a mismatched+ // barrier would corrupt the queue instead of failing loudly.+ prepare.depth = makeResource(depth, FFX_API_RESOURCE_STATE_COMMON);+ prepare.motionVectors = makeResource(motion, FFX_API_RESOURCE_STATE_COMMON);+ const auto prepareResult = p.functions.Dispatch(&p.fgContext, &prepare.header);+ if (prepareResult != FFX_API_RETURN_OK) {+ log::warn("fsr-fg", std::format("prepare dispatch result={} frameId={}", returnName(prepareResult), p.frameId));+ p.disableGeneration("prepare dispatch rejection");+ return true;+ }++ ffxDispatchDescFrameGeneration dispatch{};+ dispatch.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATION;+ dispatch.commandList = nullptr;+ dispatch.presentColor = makeResource(backBuffer, FFX_API_RESOURCE_STATE_COMMON);+ dispatch.numGeneratedFrames = p.requestedGenerated;+ dispatch.reset = reset;+ dispatch.backbufferTransferFunction = FFX_API_BACKBUFFER_TRANSFER_FUNCTION_SRGB;+ dispatch.minMaxLuminance[0] = 0.0f;+ dispatch.minMaxLuminance[1] = 1000.0f;+ dispatch.generationRect = configure.generationRect;+ dispatch.frameID = p.frameId;++ const auto configureResult = p.functions.Configure(&p.fgContext, &configure.header);+ if (configureResult != FFX_API_RETURN_OK) {+ log::warn("fsr-fg", std::format("configure result={} frameId={}", returnName(configureResult), p.frameId));+ p.disableGeneration("configure rejection");+ return true;+ }+ // The swapchain only hands out an interpolation command list while its own+ // generation flag is on, so the queries must follow the configure.+ ffxQueryDescFrameGenerationSwapChainInterpolationCommandListDX12 queryList{};+ queryList.header.type = FFX_API_QUERY_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_INTERPOLATIONCOMMANDLIST_DX12;+ queryList.pOutCommandList = &dispatch.commandList;+ auto queryResult = p.functions.Query(&p.swapchainContext, &queryList.header);+ if (queryResult != FFX_API_RETURN_OK || dispatch.commandList == nullptr) {+ log::warn("fsr-fg", std::format("interpolation command list query result={} list={}", returnName(queryResult),+ dispatch.commandList));+ p.disableGeneration("interpolation command list query rejection");+ return true;+ }+ ffxQueryDescFrameGenerationSwapChainInterpolationTextureDX12 queryTexture{};+ queryTexture.header.type = FFX_API_QUERY_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_INTERPOLATIONTEXTURE_DX12;+ queryTexture.pOutTexture = &dispatch.outputs[0];+ queryResult = p.functions.Query(&p.swapchainContext, &queryTexture.header);+ if (queryResult != FFX_API_RETURN_OK) {+ log::warn("fsr-fg", std::format("interpolation texture query result={}", returnName(queryResult)));+ p.disableGeneration("interpolation texture query rejection");+ return true;+ }++ if (p.frameId <= 2 || log::verboseFrameLogs()) {+ const auto backBufferDesc = backBuffer->GetDesc();+ const auto motionDesc = motion->GetDesc();+ const auto depthDesc = depth->GetDesc();+ const auto outputDesc = dispatch.outputs[0].resource != nullptr+ ? static_cast<ID3D12Resource*>(dispatch.outputs[0].resource)->GetDesc()+ : D3D12_RESOURCE_DESC{};+ log::info("fsr-fg", std::format(+ "trace frameId={} reset={} render={}x{} rect={}+{} {}x{} numGenerated={} present={}x{} fmt={} motion={}x{} fmt={} depth={}x{} fmt={} output={}x{} fmt={}",+ p.frameId, reset, prepare.renderSize.width, prepare.renderSize.height, configure.generationRect.left,+ configure.generationRect.top, configure.generationRect.width, configure.generationRect.height,+ dispatch.numGeneratedFrames, uint32_t(backBufferDesc.Width), backBufferDesc.Height,+ int(backBufferDesc.Format), uint32_t(motionDesc.Width), motionDesc.Height, int(motionDesc.Format),+ uint32_t(depthDesc.Width), depthDesc.Height, int(depthDesc.Format), uint32_t(outputDesc.Width),+ outputDesc.Height, int(outputDesc.Format)));+ }+ const auto dispatchResult = p.functions.Dispatch(&p.fgContext, &dispatch.header);+ if (dispatchResult != FFX_API_RETURN_OK) {+ log::warn("fsr-fg", std::format("frame generation dispatch result={} frameId={}", returnName(dispatchResult), p.frameId));+ p.disableGeneration("frame generation dispatch rejection");+ return true;+ }+ if (log::verboseFrameLogs()) {+ log::info("fsr-fg", std::format("frameId={} region={}x{}+{}+{} generatedPerFrame={}", p.frameId,+ configure.generationRect.width, configure.generationRect.height,+ configure.generationRect.left, configure.generationRect.top,+ p.requestedGenerated));+ }+ return true;+#else+ (void)list; (void)backBuffer; (void)motion; (void)depth; (void)region; (void)enabled; (void)reset; (void)elapsedMs;+ return false;+#endif+}++void FsrFgPresenter::afterPresent() {+ // Frame ids must advance by exactly one per presented frame; a gap makes the+ // provider reset its interpolation history.+ auto& p = *p_;+ ++p.frameId;+ // The provider reports on its own thread; a periodic sample is the only+ // honest way to show whether interpolation reached the display path.+ if (log::verboseFrameLogs() || p.frameId % 120 == 0) {+ log::info("fsr-fg", std::format("frameId={} real={} generated={} presented={} callbackFailures={}",+ p.frameId, p.realFrames.load(), p.generatedFrames.load(),+ p.realFrames.load() + p.generatedFrames.load(), p.callbackFailures.load()));+ }+}++uint64_t FsrFgPresenter::generatedCount() const { return p_->generatedFrames.load(); }+uint64_t FsrFgPresenter::presentedCount() const { return p_->realFrames.load() + p_->generatedFrames.load(); }+uint32_t FsrFgPresenter::maxGeneratedFrames() const { return p_->available ? p_->deliveredGenerated : 0; }+bool FsrFgPresenter::available() const { return p_->available; }+bool FsrFgPresenter::failed() const { return p_->failed; }+const char* FsrFgPresenter::providerVersion() const { return p_->providerVersion.c_str(); }++IDXGISwapChain4* FsrFgPresenter::swapchainHandle() const {+#ifdef VEYRA_HAS_FSR+ return p_->swapchain;+#else+ return nullptr;+#endif+}++void FsrFgPresenter::disableGeneration() {+#ifdef VEYRA_HAS_FSR+ auto& p = *p_;+ if (!p.available || p.softDisabled || p.fgContext == nullptr || p.swapchain == nullptr) return;+ ffxConfigureDescFrameGeneration configure{};+ configure.header.type = FFX_API_CONFIGURE_DESC_TYPE_FRAMEGENERATION;+ configure.swapChain = p.swapchain;+ configure.frameGenerationEnabled = false;+ configure.presentCallback = presentCallback;+ configure.presentCallbackUserContext = &p;+ configure.generationRect = {0, 0, int32_t(p.width), int32_t(p.height)};+ configure.frameID = p.frameId;+ const auto result = p.functions.Configure(&p.fgContext, &configure.header);+ if (result != FFX_API_RETURN_OK) {+ log::warn("fsr-fg", std::format("disableGeneration result={} frameId={}", returnName(result), p.frameId));+ return;+ }+ log::info("fsr-fg", "generation disabled; the AMD proxy keeps presenting real frames");+#endif+}++} // namespace veyra::gfxdiff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cppindex dd8baf02..a332e919 100644--- a/src/gfx/PresentSink.cpp+++ b/src/gfx/PresentSink.cpp@@ -121,6 +121,35 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,scd.Flags = tearingSupported_ ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;ComPtr<IDXGISwapChain1> swapChain1;+ // Once the AMD provider has wrapped this HWND it retains the DXGI swapchain+ // for the process lifetime (verified: a second CreateSwapChainForHwnd for+ // the same window fails afterwards). The proxy therefore stays with the+ // sink and keeps working as a plain swapchain whenever frame generation is+ // not requested by the session.+ if(desc.fsr&&!fsr_){+ fsr_=std::make_unique<FsrFgPresenter>();+ IDXGISwapChain4* proxy=nullptr;+ const uint32_t renderW=desc.renderWidth?desc.renderWidth:scd.Width;+ const uint32_t renderH=desc.renderHeight?desc.renderHeight:scd.Height;+ if(!fsr_->initialize(device,queue,factory_.Get(),hwnd_,scd,renderW,renderH,&proxy,desc.fgMultiplier)){+ // Like XeSS: a missing or incompatible local runtime must never+ // prevent basic playback.+ log::warn("present", "AMD FSR frame generation unavailable; falling back to native presentation");+ fsr_.reset();+ }+ }+ if(fsr_){+ if(!desc.fsr)fsr_->disableGeneration();+ IDXGISwapChain4* proxy=fsr_->swapchainHandle();+ ComPtr<IDXGISwapChain3> proxied;+ if(proxy==nullptr||FAILED(proxy->QueryInterface(IID_PPV_ARGS(&proxied)))){+ log::error("present", "retained FSR proxy swapchain is no longer usable");+ status = Status::WindowFailure;+ return false;+ }+ swapChain_=proxied;+ log::info("present", std::format("using the retained AMD proxy swapchain (frame generation {})", desc.fsr?"on":"off"));+ }if(desc.xess){xess_=std::make_unique<XessPresenter>();if(!xess_->initialize(device,queue,factory_.Get(),hwnd_,scd,swapChain_.GetAddressOf(),desc.fgMultiplier)){@@ -221,6 +250,7 @@ ID3D12Resource* PresentSink::currentBackBuffer()bool PresentSink::present(Status& status){xessFailed_=false;+ fsrFailed_=false;const UINT syncInterval = desc_.vsync ? 1 : 0;const UINT flags = (!desc_.vsync && tearingSupported_) ? DXGI_PRESENT_ALLOW_TEARING : 0;++attemptedPresentCount_;@@ -230,6 +260,7 @@ bool PresentSink::present(Status& status)++presentCount_;backBufferIndex_ = swapChain_->GetCurrentBackBufferIndex();if(xess_&&!xess_->afterPresent()){xessFailed_=true;status=Status::WindowFailure;return false;}+ if(fsr_)fsr_->afterPresent();return true;}++failedPresentCount_;@@ -346,6 +377,10 @@ void PresentSink::shutdown()}swapChain_.Reset();xess_.reset();+ // The AMD proxy context is deliberately NOT destroyed here: the provider+ // keeps the real DXGI swapchain alive, so releasing it would leave this+ // HWND permanently unable to host a swapchain. It is destroyed with the+ // sink at process/engine teardown instead.log::info("present", "sink-shutdown: sub-step window-destroy-last");if (hwnd_ != nullptr && !desc_.targetWindow) {DestroyWindow(hwnd_);diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex 65020fd7..3d973afc 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -94,7 +94,8 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)if(desc.hdrOutput&&!desc.hdrInput){veyra::log::error("hdr","HDR output requires an explicit HDR input contract");return false;}srEnabled_ = desc.enableSr && (srcW_ != workW_ || srcH_ != workH_);nrEnabled_ = desc.enableNr && !desc.noFeatures && !desc.noNgx;- fgEnabled_ = desc.enableFg && !desc.noNgx && !desc.stillImage && desc.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS;+ fgEnabled_ = desc.enableFg && !desc.noNgx && !desc.stillImage && desc.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS+ && desc.frameGenerationBackend!=engine::FrameGenerationBackend::Fsr;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;@@ -181,7 +182,7 @@ bool EnhanceGraph::createResources()residualRgba_=makeTexture(context_.device(),desc_.nrBeforeSr?srcW_:workW_,desc_.nrBeforeSr?srcH_: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(presentSinkFg())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);@@ -300,7 +301,7 @@ bool EnhanceGraph::initZeroAndDepthTextures()bool EnhanceGraph::initNvof(){if(desc_.stillImage){mvecSource_="single-image (no temporal motion)";return true;}- if (desc_.noFeatures || !(nvofStandalone_ || xessEnabled() || (fgEnabled_&&desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) || (srEnabled_&&!desc_.videoSrQuality))) {+ if (desc_.noFeatures || !(nvofStandalone_ || presentSinkFg() || (fgEnabled_&&desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) || (srEnabled_&&!desc_.videoSrQuality))) {veyra::log::info("graph", "VEYRA_NO_FEATURES: NVOF session skipped");return true;}@@ -969,7 +970,7 @@ 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_ || xessEnabled() || fgEnabled_ || (srEnabled_ && !desc_.videoSrQuality);+ const bool runMotion = nvofStandalone_ || presentSinkFg() || fgEnabled_ || (srEnabled_ && !desc_.videoSrQuality);if (runMotion && (gpuDis_ || amdOf_ || (nvof_ && nvof_->initialized()))) {const float dims[8] = {uintBits(nvofW_),uintBits(nvofH_),uintBits(nvofW_),uintBits(nvofH_),0,0,0,0};if (prevValid_) {@@ -1230,7 +1231,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frametracker_.transition(list, videoFrame_[parity].Get(), D3D12_RESOURCE_STATE_COMMON);}- if(xessEnabled()){+ if(presentSinkFg()){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);@@ -1360,10 +1361,10 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){// DLSS allocates 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.nrRuntime!=desc_.nrRuntime||std::max(2u,s.multiplier)!=desc_.fgMultiplier||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&s.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;+ if(s.nrRuntime!=desc_.nrRuntime||std::max(2u,s.multiplier)!=desc_.fgMultiplier||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&!engine::presentSinkFrameGeneration(s.frameGenerationBackend)&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.protection=s.protection;desc_.settingsRevision=s.revision;desc_.fgMultiplier=std::max(2u,s.multiplier);desc_.enableNvofStandalone=s.nr&&!desc_.stillImage;nvofStandalone_=desc_.enableNvofStandalone;- setNrEnabled(s.nr);setFgEnabled(s.multiplier>1&&s.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS);+ setNrEnabled(s.nr);setFgEnabled(s.multiplier>1&&!engine::presentSinkFrameGeneration(s.frameGenerationBackend));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;}diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cppindex 838db9d3..e17eb1b2 100644--- a/tests/unit/RepairContractTests.cpp+++ b/tests/unit/RepairContractTests.cpp@@ -182,7 +182,17 @@ int main(){check(!lineage.observe(skipped,2100000,true,false),"missing A identity is unknown rather than extrapolated");check(!lineage.observe(skipped,2400000,true,true),"cached preview cannot seed latency lineage");check(!pairFlow.snapshot(13000000).pairTiming[size_t(diagnostics::PairTiming::GeneratedFromA)].mean,"generated latency expires when no new frames are presented");- check(engine::frameGenerationBackendName(engine::FrameGenerationBackend::Dlss)=="DLSS"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::XeSS)=="XeSS","frame-generation backend names identify every backend");+ check(engine::frameGenerationBackendName(engine::FrameGenerationBackend::Dlss)=="DLSS"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::XeSS)=="XeSS"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::Fsr)=="AMD-FSR","frame-generation backend names identify every backend");+ // The present-sink backends own generation inside their swapchain provider;+ // the in-graph DLSSG path must never try to run for them.+ check(engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::XeSS)&&engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::Fsr)&&!engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::Dlss),"present-sink frame generation covers XeSS and AMD FSR only");+ {+ engine::EnhancementSettings settings;+ settings.multiplier=4;settings.frameGenerationBackend=engine::FrameGenerationBackend::Fsr;+ check(!settings.validate().empty()&&std::string(settings.validate()).find("2X")!=std::string::npos,"AMD FSR requests above 2X are rejected by validation");+ settings.multiplier=2;+ check(settings.validate().empty(),"AMD FSR 2X is a valid request");+ }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(),"5X multiplier accepted by the API guard (6X ceiling)");diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cppindex b6774c1d..b968d474 100644--- a/tests/unit/RepairPresetTests.cpp+++ b/tests/unit/RepairPresetTests.cpp@@ -7,7 +7,7 @@ namespace {bool legacyBackends(const std::filesystem::path& path) {using namespace veyra::engine;unsigned checks=0;- for(int version=4;version<=11;++version)for(int backend=0;backend<=2;++backend)for(int multiplier:{2,4}){+ for(int version=4;version<=13;++version)for(int backend=0;backend<=2;++backend)for(int multiplier:{2,4}){std::ostringstream fixture;fixture<<"VEYRA_PRESETS "<<version<<"\n\"legacy\" 1\n\"legacy\" 1 1 1 -1 0 0 0 1 1 1 1 1 1 0 "<<multiplier<<" 0 1 0";fixture<<" 0 0";@@ -19,11 +19,16 @@ bool legacyBackends(const std::filesystem::path& path) {if(version>=9)fixture<<" 1";if(version>=10)fixture<<" 1";if(version>=11)fixture<<" 0";+ if(version>=12)fixture<<" 0";fixture<<'\n';{std::ofstream file(path);file<<fixture.str();}const bool xess=version<8?backend==2:backend==1;- const bool supportedValue=backend<2||(version>=6&&version<=7);- const bool expected=supportedValue&&(!xess||multiplier==2);+ const bool fsr=version>=13&&backend==2;+ const bool supportedValue=backend<2||(version>=6&&version<=7)||fsr;+ // FSR accepts 2X only (the 3.1.x provider generates one frame per present).+ // XeSS presets up to 4X stay loadable: the audited unlock raises the ceiling+ // and the engine clamps to the runtime value. DLSS accepts both here.+ const bool expected=supportedValue&&(!fsr||multiplier==2);PresetStore store(path);if(store.load()!=expected)return false;if(expected){@@ -31,11 +36,12 @@ bool legacyBackends(const std::filesystem::path& path) {if(value.lowLatency||value.forceSdrPreview)return false;if(value.captureCompatible!=(version>=10))return false;if(value.nrRuntime!=(version>=9?NrRuntime::Community:NrRuntime::Original))return false;- if(value.frameGenerationBackend!=(xess?FrameGenerationBackend::XeSS:FrameGenerationBackend::Dlss)||value.multiplier!=multiplier||value.videoSrQuality!=2)return false;+ const auto expectedBackend=fsr?FrameGenerationBackend::Fsr:xess?FrameGenerationBackend::XeSS:FrameGenerationBackend::Dlss;+ if(value.frameGenerationBackend!=expectedBackend||value.multiplier!=multiplier||value.videoSrQuality!=2)return false;if(version>=7&&(value.audioSync!=AudioSyncMode::Manual||value.audioOffsetMs!=137))return false;if(!store.put(L"legacy",value,true))return false;std::ifstream file(path);std::string magic;int savedVersion=0;file>>magic>>savedVersion;- if(magic!="VEYRA_PRESETS"||savedVersion!=12)return false;+ if(magic!="VEYRA_PRESETS"||savedVersion!=13)return false;PresetStore reloaded(path);if(!reloaded.load()||reloaded.defaultSettings()!=value)return false;}else{@@ -57,12 +63,26 @@ int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engines.srTarget=veyra::pipeline::SrTarget::Uhd8K;s.audioSync=AudioSyncMode::Manual;s.audioOffsetMs=137;s.nrRuntime=NrRuntime::Community;s.captureCompatible=true;s.lowLatency=true;s.forceSdrPreview=true;- 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;+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;+ if(!ok){std::cerr<<"stage basic-preset failed\n";return 1;}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);+ if(!ok){std::cerr<<"stage bad-target failed\n";return 1;}+ // XeSS presets may request up to 4X since the audited multi-frame unlock; the+ // engine clamps to the ceiling the provider reports at session start.+ auto xess=s;xess.frameGenerationBackend=FrameGenerationBackend::XeSS;ok=ok&&b.put(L"XeSS 4X",xess);+ PresetStore xessReload(p);ok=ok&&xessReload.load()&&xessReload.entries().back().settings==xess&&b.erase(1);+ xess.multiplier=5;ok=ok&&!b.put(L"XeSS 5X rejected",xess);+ xess.multiplier=2;ok=ok&&b.put(L"XeSS 2X",xess);PresetStore xess2Reload(p);ok=ok&&xess2Reload.load()&&xess2Reload.entries().back().settings==xess&&b.erase(1);+ if(!ok){std::cerr<<"stage xess-cases failed\n";return 1;}+ // AMD FSR frame generation: the 3.1.x provider delivers one generated frame+ // per present, so 2X round-trips and 4X is refused by validation.+ auto fsr=s;fsr.frameGenerationBackend=FrameGenerationBackend::Fsr;ok=ok&&!b.put(L"FSR 4X rejected",fsr);+ if(!ok){std::cerr<<"stage fsr-4x failed\n";return 1;}+ fsr.multiplier=2;ok=ok&&b.put(L"FSR 2X",fsr);PresetStore fsrReload(p);ok=ok&&fsrReload.load()&&fsrReload.entries().back().settings==fsr&&b.erase(1);+ if(!ok){std::cerr<<"stage backend-cases failed\n";return 1;}auto badBackend=s;badBackend.frameGenerationBackend=static_cast<FrameGenerationBackend>(3);ok=ok&&!b.put(L"invalid backend",badBackend);auto dis=s;dis.opticalFlowBackend=OpticalFlowBackend::GpuDis;ok=ok&&b.put(L"GPU DIS",dis)&&b.save();PresetStore disReload(p);ok=ok&&disReload.load()&&disReload.entries().back().settings==dis&&b.erase(1);+ if(!ok){std::cerr<<"stage flow-cases failed\n";return 1;}auto badFlow=s;badFlow.opticalFlowBackend=static_cast<OpticalFlowBackend>(3);ok=ok&&!b.put(L"invalid flow backend",badFlow);auto ampere=s;ampere.nr=true;ampere.nrRuntime=NrRuntime::Ampere;ok=ok&&b.put(L"RTX30",ampere);PresetStore ampereReload(p);ok=ok&&ereReload.load()&&ereReload.entries().back().settings==ampere&&b.erase(1);auto badNr=s;badNr.nrRuntime=static_cast<NrRuntime>(3);ok=ok&&!b.put(L"invalid NR runtime",badNr);@@ -73,6 +93,8 @@ int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engine{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.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;+ if(!ok){std::cerr<<"stage legacy-v1 failed\n";return 1;}{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";f.close();ok=legacyBackends(p)&&ok;+ if(!ok){std::cerr<<"stage closing failed\n";return 1;}std::cout<<"preset roundtrip, all fields, duplicate, rename-default, delete, validation, unknown schema, corrupt-preservation="<<ok<<'\n';return ok?0:1;}diff --git a/tools/fsr_probe/main.cpp b/tools/fsr_probe/main.cppindex 05480b87..b323eb35 100644--- a/tools/fsr_probe/main.cpp+++ b/tools/fsr_probe/main.cpp@@ -1,18 +1,28 @@// AMD FSR frame-generation probe (diagnostic only, never shipped in the player).//-// Loads the vendored AMD FidelityFX loader DLL, enumerates the frame-generation-// and upscaling providers and then tries to create the DX12 frame-generation-// proxy swapchain context on the local GPU. The result tells us, with evidence,-// whether the ML frame generation of FSR SDK 2.3.0 can initialise on the host-// adapter (NVIDIA in this project's test machine) or is gated to AMD hardware.+// Two stages of evidence:+// 1. provider inventory: loads the vendored AMD FidelityFX loader DLL and+// enumerates the frame-generation / swapchain provider versions that this+// machine actually advertises;+// 2. full frame-generation run: creates the swapchain proxy context and the+// frame-generation context, renders a moving back buffer, records+// prepare + configure + dispatch every frame and presents through the+// AMD proxy swapchain. A present callback counts real vs generated+// frames, which is the only ground truth that interpolation actually+// reached the display path.//-// Usage: veyra_fsr_probe [path-to-amd_fidelityfx_loader_dx12.dll]+// Usage: veyra_fsr_probe [path-to-amd_fidelityfx_loader_dx12.dll] [generated-frames-per-real-frame] [upscale]+//+// The optional "upscale" mode reproduces the player's geometry: the render+// resolution (guidance) is larger than the swapchain and the interpolation+// rectangle is the letterboxed fit inside it.#include <windows.h>#include <d3d12.h>#include <dxgi1_6.h>#include <wrl/client.h>+#include <atomic>#include <cstdio>#include <filesystem>#include <string>@@ -26,6 +36,10 @@ using Microsoft::WRL::ComPtr;namespace {+constexpr UINT kProbeWidth = 1280;+constexpr UINT kProbeHeight = 720;+constexpr UINT kProbeFrames = 90;+const char* resultName(ffxReturnCode_t code) {switch (code) {case FFX_API_RETURN_OK: return "OK";@@ -44,6 +58,106 @@ LRESULT CALLBACK probeProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {return DefWindowProcW(hwnd, msg, wp, lp);}+// Resource description conversion, mirroring the FidelityFX DX12 backend.+FfxApiSurfaceFormat surfaceFormatFromDxgi(DXGI_FORMAT format) {+ switch (format) {+ case DXGI_FORMAT_R8G8B8A8_UNORM: return FFX_API_SURFACE_FORMAT_R8G8B8A8_UNORM;+ case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return FFX_API_SURFACE_FORMAT_R8G8B8A8_SRGB;+ case DXGI_FORMAT_R10G10B10A2_UNORM: return FFX_API_SURFACE_FORMAT_R10G10B10A2_UNORM;+ case DXGI_FORMAT_R16G16_FLOAT: return FFX_API_SURFACE_FORMAT_R16G16_FLOAT;+ case DXGI_FORMAT_R16G16B16A16_FLOAT: return FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT;+ case DXGI_FORMAT_R32_FLOAT: return FFX_API_SURFACE_FORMAT_R32_FLOAT;+ case DXGI_FORMAT_R32_UINT: return FFX_API_SURFACE_FORMAT_R32_UINT;+ default: return FFX_API_SURFACE_FORMAT_UNKNOWN;+ }+}++FfxApiResourceDescription describeResource(ID3D12Resource* resource) {+ FfxApiResourceDescription description{};+ if (resource == nullptr) return description;+ const D3D12_RESOURCE_DESC desc = resource->GetDesc();+ description.type = FFX_API_RESOURCE_TYPE_TEXTURE2D;+ description.format = surfaceFormatFromDxgi(desc.Format);+ description.width = uint32_t(desc.Width);+ description.height = desc.Height;+ description.depth = desc.DepthOrArraySize;+ description.mipCount = desc.MipLevels;+ description.flags = 0;+ description.usage = FFX_API_RESOURCE_USAGE_READ_ONLY;+ if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0) {+ description.usage = FfxApiResourceUsage(description.usage | FFX_API_RESOURCE_USAGE_UAV);+ }+ return description;+}++FfxApiResource makeResource(ID3D12Resource* resource, uint32_t state) {+ FfxApiResource api{};+ api.resource = resource;+ api.description = describeResource(resource);+ api.state = state;+ return api;+}++D3D12_RESOURCE_STATES dx12State(uint32_t ffxState) {+ switch (ffxState) {+ case FFX_API_RESOURCE_STATE_UNORDERED_ACCESS: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;+ case FFX_API_RESOURCE_STATE_PIXEL_COMPUTE_READ:+ return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;+ case FFX_API_RESOURCE_STATE_COMPUTE_READ: return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;+ case FFX_API_RESOURCE_STATE_COPY_SRC: return D3D12_RESOURCE_STATE_COPY_SOURCE;+ case FFX_API_RESOURCE_STATE_COPY_DEST: return D3D12_RESOURCE_STATE_COPY_DEST;+ case FFX_API_RESOURCE_STATE_PRESENT: return D3D12_RESOURCE_STATE_PRESENT;+ case FFX_API_RESOURCE_STATE_RENDER_TARGET: return D3D12_RESOURCE_STATE_RENDER_TARGET;+ default: return D3D12_RESOURCE_STATE_COMMON;+ }+}++struct PresentCounters {+ std::atomic<uint64_t> real{0};+ std::atomic<uint64_t> generated{0};+ std::atomic<uint64_t> callbackFailures{0};+};++// The swapchain context calls this for every frame it presents (real and+// interpolated). With no UI resource registered the SDK's own default callback+// would only copy the finished frame into the real swapchain buffer, so the+// same copy is performed here and the frame is counted.+ffxReturnCode_t presentCallback(ffxCallbackDescFrameGenerationPresent* params, void* userCtx) {+ auto* counters = static_cast<PresentCounters*>(userCtx);+ if (params == nullptr || counters == nullptr) return FFX_API_RETURN_ERROR_PARAMETER;+ if (params->isGeneratedFrame) {+ counters->generated.fetch_add(1, std::memory_order_relaxed);+ } else {+ counters->real.fetch_add(1, std::memory_order_relaxed);+ }+ if (params->currentUI.resource != nullptr || params->commandList == nullptr ||+ params->outputSwapChainBuffer.resource == nullptr || params->currentBackBuffer.resource == nullptr) {+ counters->callbackFailures.fetch_add(1, std::memory_order_relaxed);+ return FFX_API_RETURN_OK;+ }+ auto* list = static_cast<ID3D12GraphicsCommandList*>(params->commandList);+ auto* destination = static_cast<ID3D12Resource*>(params->outputSwapChainBuffer.resource);+ auto* source = static_cast<ID3D12Resource*>(params->currentBackBuffer.resource);+ D3D12_RESOURCE_BARRIER barriers[2]{};+ barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barriers[0].Transition.pResource = source;+ barriers[0].Transition.StateBefore = dx12State(params->currentBackBuffer.state);+ barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;+ barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barriers[1].Transition.pResource = destination;+ barriers[1].Transition.StateBefore = dx12State(params->outputSwapChainBuffer.state);+ barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;+ list->ResourceBarrier(2, barriers);+ list->CopyResource(destination, source);+ for (auto& barrier : barriers) {+ const auto before = barrier.Transition.StateBefore;+ barrier.Transition.StateBefore = barrier.Transition.StateAfter;+ barrier.Transition.StateAfter = before;+ }+ list->ResourceBarrier(2, barriers);+ return FFX_API_RETURN_OK;+}+void reportVersions(const ffxFunctions& functions, uint64_t createDescType, const char* label, void* device) {uint64_t count = 0;ffxQueryDescGetVersions query{};@@ -72,17 +186,60 @@ void reportVersions(const ffxFunctions& functions, uint64_t createDescType, cons}}+ComPtr<ID3D12Resource> makeTexture(ID3D12Device* device, UINT width, UINT height, DXGI_FORMAT format,+ D3D12_RESOURCE_FLAGS flags) {+ D3D12_HEAP_PROPERTIES heap{};+ heap.Type = D3D12_HEAP_TYPE_DEFAULT;+ D3D12_RESOURCE_DESC desc{};+ desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;+ desc.Width = width;+ desc.Height = height;+ desc.DepthOrArraySize = 1;+ desc.MipLevels = 1;+ desc.Format = format;+ desc.SampleDesc.Count = 1;+ desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;+ desc.Flags = flags;+ ComPtr<ID3D12Resource> resource;+ if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc,+ D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&resource)))) {+ return {};+ }+ return resource;+}+} // namespaceint wmain(int argc, wchar_t** argv) {+ setvbuf(stdout, nullptr, _IONBF, 0); // evidence survives a probe crashstd::filesystem::path loaderPath;if (argc > 1) loaderPath = argv[1];else loaderPath = std::filesystem::current_path() /L"third_party_local/amd/FidelityFX-SDK-2.3.0/Kits/FidelityFX/signedbin/amd_fidelityfx_loader_dx12.dll";+ UINT generatedPerFrame = 1;+ if (argc > 2) {+ const int requested = _wtoi(argv[2]);+ if (requested >= 1 && requested <= 4) generatedPerFrame = UINT(requested);+ }+ bool upscaleMode = argc > 3 && _wcsicmp(argv[3], L"upscale") == 0;+ const bool pipelined = argc > 4 && _wcsicmp(argv[4], L"pipelined") == 0;+ const UINT renderWidth = upscaleMode ? 1920u : kProbeWidth;+ const UINT renderHeight = upscaleMode ? 1080u : kProbeHeight;+ const FfxApiRect2D generationRect = upscaleMode+ ? FfxApiRect2D{7, 0, 1266, 712}+ : FfxApiRect2D{0, 0, int32_t(kProbeWidth), int32_t(kProbeHeight)};std::printf("[fsr-probe] loader=%s\n", loaderPath.string().c_str());+ std::printf("[fsr-probe] requested generated frames per real frame=%u (multiplier %uX)\n", generatedPerFrame,+ generatedPerFrame + 1);+ std::printf("[fsr-probe] display=%ux%u render=%ux%u generationRect=%d+%d %dx%d\n", kProbeWidth, kProbeHeight,+ renderWidth, renderHeight, generationRect.left, generationRect.top, generationRect.width,+ generationRect.height);- HMODULE loader = LoadLibraryExW(loaderPath.wstring().c_str(), nullptr,- LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);+ // The loader only discovers providers when the directory holding the AMD+ // binaries is on the search path; changing the process directory is the+ // cheapest way to prove that for the probe.+ SetCurrentDirectoryW(loaderPath.parent_path().wstring().c_str());+ HMODULE loader = LoadLibraryW(loaderPath.filename().wstring().c_str());if (loader == nullptr) {std::printf("[fsr-probe] loader load failed win32=%lu\n", GetLastError());return 2;@@ -90,14 +247,13 @@ int wmain(int argc, wchar_t** argv) {ffxFunctions functions{};ffxLoadFunctions(&functions, loader);- if (functions.CreateContext == nullptr || functions.Query == nullptr || functions.DestroyContext == nullptr) {+ if (functions.CreateContext == nullptr || functions.Query == nullptr || functions.DestroyContext == nullptr ||+ functions.Configure == nullptr || functions.Dispatch == nullptr) {std::printf("[fsr-probe] loader is missing the FSR API entry points\n");return 3;}std::printf("[fsr-probe] FSR API entry points resolved\n");- // Minimal D3D12 host: default adapter, one queue, hidden window, flip-model- // swapchain descriptor identical in shape to the player's present sink.ComPtr<IDXGIFactory6> factory;if (FAILED(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory)))) {std::printf("[fsr-probe] CreateDXGIFactory2 failed\n");@@ -125,8 +281,6 @@ int wmain(int argc, wchar_t** argv) {return 7;}- // Provider/version inventory runs with the real device attached: some- // providers only advertise the ML (4.0.x) family when a device is present.reportVersions(functions, FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_FOR_HWND_DX12, "framegen-swapchain-forhwnd", device.Get());reportVersions(functions, FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION, "framegen", device.Get());reportVersions(functions, FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_VERSION_DX12, "framegen-swapchain-version", device.Get());@@ -138,15 +292,16 @@ int wmain(int argc, wchar_t** argv) {wc.lpszClassName = L"VeyraFsrProbe";RegisterClassW(&wc);HWND hwnd = CreateWindowExW(0, wc.lpszClassName, L"FSR probe", WS_OVERLAPPEDWINDOW,- CW_USEDEFAULT, CW_USEDEFAULT, 1280, 720, nullptr, nullptr, wc.hInstance, nullptr);+ CW_USEDEFAULT, CW_USEDEFAULT, LONG(kProbeWidth), LONG(kProbeHeight),+ nullptr, nullptr, wc.hInstance, nullptr);if (hwnd == nullptr) {std::printf("[fsr-probe] CreateWindow failed\n");return 8;}DXGI_SWAP_CHAIN_DESC1 scd{};- scd.Width = 1280;- scd.Height = 720;+ scd.Width = kProbeWidth;+ scd.Height = kProbeHeight;scd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;scd.SampleDesc.Count = 1;scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;@@ -155,26 +310,322 @@ int wmain(int argc, wchar_t** argv) {scd.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;scd.Scaling = DXGI_SCALING_STRETCH;+ // Stage 1: swapchain proxy context.+ ffxCreateContextDescFrameGenerationSwapChainVersionDX12 swapchainVersion{};+ swapchainVersion.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_VERSION_DX12;+ swapchainVersion.version = FFX_FRAMEGENERATION_SWAPCHAIN_DX12_VERSION;++ // The context hands out a borrowed pointer: it owns one reference of its+ // own and releases it in ffxDestroyContext, so the application must take+ // its own reference instead of adopting the pointer.+ IDXGISwapChain4* proxySwapchain = nullptr;ComPtr<IDXGISwapChain4> swapchain;- ffxCreateContextDescFrameGenerationSwapChainForHwndDX12 desc{};- desc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_FOR_HWND_DX12;- desc.swapchain = swapchain.GetAddressOf();- desc.hwnd = hwnd;- desc.desc = &scd;- desc.fullscreenDesc = nullptr;- desc.dxgiFactory = factory.Get();- desc.gameQueue = queue.Get();-- ffxContext context = nullptr;- const auto createResult = functions.CreateContext(&context, &desc.header, nullptr);- std::printf("[fsr-probe] CreateContext(framegen swapchain for hwnd) result=%s (0x%llX) context=%p swapchain=%p\n",- resultName(createResult), static_cast<unsigned long long>(createResult),- static_cast<void*>(context), static_cast<void*>(swapchain.Get()));- if (context != nullptr) {- const auto destroyResult = functions.DestroyContext(&context, nullptr);- std::printf("[fsr-probe] DestroyContext result=%s\n", resultName(destroyResult));+ ffxCreateContextDescFrameGenerationSwapChainForHwndDX12 swapchainDesc{};+ swapchainDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_FOR_HWND_DX12;+ swapchainDesc.header.pNext = &swapchainVersion.header;+ swapchainDesc.swapchain = &proxySwapchain;+ swapchainDesc.hwnd = hwnd;+ swapchainDesc.desc = &scd;+ swapchainDesc.fullscreenDesc = nullptr;+ swapchainDesc.dxgiFactory = factory.Get();+ swapchainDesc.gameQueue = queue.Get();++ ffxContext swapchainContext = nullptr;+ const auto swapchainResult = functions.CreateContext(&swapchainContext, &swapchainDesc.header, nullptr);+ std::printf("[fsr-probe] CreateContext(swapchain for hwnd, version=%u) result=%s (0x%llX) context=%p swapchain=%p\n",+ swapchainVersion.version, resultName(swapchainResult),+ static_cast<unsigned long long>(swapchainResult), static_cast<void*>(swapchainContext),+ static_cast<void*>(proxySwapchain));+ if (swapchainResult != FFX_API_RETURN_OK || swapchainContext == nullptr || proxySwapchain == nullptr) {+ if (swapchainContext != nullptr) functions.DestroyContext(&swapchainContext, nullptr);+ DestroyWindow(hwnd);+ return 9;+ }+ swapchain.Attach(proxySwapchain);+ proxySwapchain->AddRef(); // application-owned reference (Attach adopted the borrowed one)+ DXGI_SWAP_CHAIN_DESC1 actual{};+ std::printf("[fsr-probe] proxy swapchain GetDesc1=%s format=%d buffers=%u\n",+ SUCCEEDED(swapchain->GetDesc1(&actual)) ? "OK" : "FAILED", int(actual.Format), actual.BufferCount);++ // Stage 2: frame-generation context. The version desc asks for the newest+ // API surface the header knows; when a provider rejects that the probe+ // retries without it so the failure mode is recorded instead of guessed.+ ComPtr<ID3D12Resource> motionTexture = makeTexture(device.Get(), renderWidth, renderHeight,+ DXGI_FORMAT_R16G16_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);+ ComPtr<ID3D12Resource> depthTexture = makeTexture(device.Get(), renderWidth, renderHeight,+ DXGI_FORMAT_R32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);+ if (!motionTexture || !depthTexture) {+ std::printf("[fsr-probe] guidance texture creation failed\n");+ functions.DestroyContext(&swapchainContext, nullptr);+ DestroyWindow(hwnd);+ return 10;+ }++ ffxCreateBackendDX12Desc backendDesc{};+ backendDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_DX12;+ backendDesc.device = device.Get();+ ffxCreateContextDescFrameGenerationVersion fgVersion{};+ fgVersion.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION_VERSION;+ fgVersion.version = FFX_FRAMEGENERATION_VERSION;++ ffxCreateContextDescFrameGeneration fgDesc{};+ fgDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION;+ fgDesc.flags = 0;+ fgDesc.displaySize = {kProbeWidth, kProbeHeight};+ fgDesc.maxRenderSize = {std::max(kProbeWidth, renderWidth), std::max(kProbeHeight, renderHeight)};+ fgDesc.backBufferFormat = FFX_API_SURFACE_FORMAT_R8G8B8A8_UNORM;++ ffxContext fgContext = nullptr;+ fgDesc.header.pNext = &backendDesc.header;+ fgVersion.header.pNext = nullptr;+ backendDesc.header.pNext = &fgVersion.header;+ auto fgResult = functions.CreateContext(&fgContext, &fgDesc.header, nullptr);+ std::printf("[fsr-probe] CreateContext(framegen, headerVersion=%u) result=%s (0x%llX) context=%p\n",+ fgVersion.version, resultName(fgResult), static_cast<unsigned long long>(fgResult),+ static_cast<void*>(fgContext));+ if (fgResult != FFX_API_RETURN_OK || fgContext == nullptr) {+ fgDesc.header.pNext = &backendDesc.header;+ backendDesc.header.pNext = nullptr;+ fgResult = functions.CreateContext(&fgContext, &fgDesc.header, nullptr);+ std::printf("[fsr-probe] CreateContext(framegeneration, no version desc) result=%s (0x%llX) context=%p\n",+ resultName(fgResult), static_cast<unsigned long long>(fgResult), static_cast<void*>(fgContext));+ }+ if (fgResult != FFX_API_RETURN_OK || fgContext == nullptr) {+ std::printf("[fsr-probe] frame-generation context unavailable; stopping\n");+ functions.DestroyContext(&swapchainContext, nullptr);+ DestroyWindow(hwnd);+ return 11;+ }++ ComPtr<ID3D12CommandAllocator> allocator;+ ComPtr<ID3D12GraphicsCommandList> list;+ ComPtr<ID3D12Fence> fence;+ ComPtr<ID3D12DescriptorHeap> rtvHeap, uavHeap;+ HANDLE fenceEvent = nullptr;+ if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) ||+ FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) ||+ FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) {+ std::printf("[fsr-probe] command objects failed\n");+ functions.DestroyContext(&fgContext, nullptr);+ functions.DestroyContext(&swapchainContext, nullptr);+ DestroyWindow(hwnd);+ return 12;+ }+ list->Close();+ D3D12_DESCRIPTOR_HEAP_DESC rtvDesc{};+ rtvDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;+ rtvDesc.NumDescriptors = 4;+ D3D12_DESCRIPTOR_HEAP_DESC uavDesc{};+ uavDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;+ uavDesc.NumDescriptors = 2;+ if (FAILED(device->CreateDescriptorHeap(&rtvDesc, IID_PPV_ARGS(&rtvHeap))) ||+ FAILED(device->CreateDescriptorHeap(&uavDesc, IID_PPV_ARGS(&uavHeap)))) {+ std::printf("[fsr-probe] descriptor heaps failed\n");+ functions.DestroyContext(&fgContext, nullptr);+ functions.DestroyContext(&swapchainContext, nullptr);+ DestroyWindow(hwnd);+ return 13;+ }+ const UINT rtvIncrement = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);+ const UINT uavIncrement = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);+ for (UINT i = 0; i < scd.BufferCount; ++i) {+ ComPtr<ID3D12Resource> buffer;+ if (SUCCEEDED(swapchain->GetBuffer(i, IID_PPV_ARGS(&buffer)))) {+ device->CreateRenderTargetView(buffer.Get(), nullptr,+ {rtvHeap->GetCPUDescriptorHandleForHeapStart().ptr + size_t(i) * rtvIncrement});+ }+ }+ device->CreateUnorderedAccessView(motionTexture.Get(), nullptr, nullptr,+ {uavHeap->GetCPUDescriptorHandleForHeapStart().ptr});+ device->CreateUnorderedAccessView(depthTexture.Get(), nullptr, nullptr,+ {uavHeap->GetCPUDescriptorHandleForHeapStart().ptr + uavIncrement});+ fenceEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);++ PresentCounters counters{};+ uint64_t prepareFailures = 0, configureFailures = 0, dispatchFailures = 0, queryFailures = 0, presentFailures = 0;+ uint64_t preparedFrames = 0;++ for (UINT frame = 0; frame < kProbeFrames; ++frame) {+ if (FAILED(allocator->Reset())) break;+ list->Reset(allocator.Get(), nullptr);++ ComPtr<ID3D12Resource> backBuffer;+ const UINT backBufferIndex = swapchain->GetCurrentBackBufferIndex();+ if (FAILED(swapchain->GetBuffer(backBufferIndex, IID_PPV_ARGS(&backBuffer)))) break;++ D3D12_RESOURCE_BARRIER toTarget{};+ toTarget.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ toTarget.Transition.pResource = backBuffer.Get();+ toTarget.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;+ toTarget.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;+ list->ResourceBarrier(1, &toTarget);+ const float shade = float(frame % 60) / 60.0f;+ const float clear[4] = {shade, 0.25f, 1.0f - shade, 1.0f};+ const D3D12_CPU_DESCRIPTOR_HANDLE rtv{+ rtvHeap->GetCPUDescriptorHandleForHeapStart().ptr + size_t(backBufferIndex) * rtvIncrement};+ list->ClearRenderTargetView(rtv, clear, 0, nullptr);+ std::swap(toTarget.Transition.StateBefore, toTarget.Transition.StateAfter);+ list->ResourceBarrier(1, &toTarget);++ // Guidance: constant horizontal pixel motion, mid depth. Real content+ // would give richer interpolation, but the counters only need the+ // workload to be valid.+ D3D12_RESOURCE_BARRIER guidance[2]{};+ for (auto& barrier : guidance) {+ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;+ barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;+ }+ guidance[0].Transition.pResource = motionTexture.Get();+ guidance[1].Transition.pResource = depthTexture.Get();+ list->ResourceBarrier(2, guidance);+ const float motion[4] = {4.0f, 0.0f, 0.0f, 0.0f};+ const float depth = 0.5f;+ list->ClearUnorderedAccessViewFloat(uavHeap->GetGPUDescriptorHandleForHeapStart(),+ {uavHeap->GetCPUDescriptorHandleForHeapStart().ptr}, motionTexture.Get(), motion, 0, nullptr);+ list->ClearUnorderedAccessViewFloat(+ {uavHeap->GetGPUDescriptorHandleForHeapStart().ptr + uavIncrement},+ {uavHeap->GetCPUDescriptorHandleForHeapStart().ptr + uavIncrement},+ depthTexture.Get(), &depth, 0, nullptr);+ for (auto& barrier : guidance) std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter);+ guidance[0].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;+ guidance[1].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;+ list->ResourceBarrier(2, guidance);++ ffxDispatchDescFrameGenerationPrepareV2 prepare{};+ prepare.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATION_PREPARE_V2;+ prepare.frameID = frame;+ prepare.flags = 0;+ prepare.commandList = list.Get();+ prepare.renderSize = {renderWidth, renderHeight};+ prepare.jitterOffset = {0.0f, 0.0f};+ prepare.motionVectorScale = {1.0f, 1.0f}; // guidance is already pixel space+ prepare.frameTimeDelta = 16.6f;+ prepare.reset = frame == 0;+ prepare.cameraNear = 0.1f;+ prepare.cameraFar = 1000.0f;+ prepare.cameraFovAngleVertical = 1.0f;+ prepare.viewSpaceToMetersFactor = 0.0f;+ prepare.depth = makeResource(depthTexture.Get(), FFX_API_RESOURCE_STATE_PIXEL_COMPUTE_READ);+ prepare.motionVectors = makeResource(motionTexture.Get(), FFX_API_RESOURCE_STATE_PIXEL_COMPUTE_READ);+ const auto prepareResult = functions.Dispatch(&fgContext, &prepare.header);+ if (prepareResult != FFX_API_RETURN_OK) ++prepareFailures;+ else ++preparedFrames;++ ffxConfigureDescFrameGeneration configure{};+ configure.header.type = FFX_API_CONFIGURE_DESC_TYPE_FRAMEGENERATION;+ configure.swapChain = swapchain.Get();+ configure.presentCallback = presentCallback;+ configure.presentCallbackUserContext = &counters;+ configure.frameGenerationEnabled = true;+ configure.allowAsyncWorkloads = false;+ configure.flags = 0;+ configure.generationRect = generationRect;+ configure.frameID = frame;+ const auto configureResult = functions.Configure(&fgContext, &configure.header);+ if (configureResult != FFX_API_RETURN_OK) ++configureFailures;++ ffxDispatchDescFrameGeneration dispatch{};+ dispatch.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATION;+ dispatch.commandList = nullptr;+ dispatch.presentColor = makeResource(backBuffer.Get(), FFX_API_RESOURCE_STATE_COMMON);+ dispatch.numGeneratedFrames = generatedPerFrame;+ dispatch.reset = frame == 0;+ dispatch.backbufferTransferFunction = FFX_API_BACKBUFFER_TRANSFER_FUNCTION_SRGB;+ dispatch.minMaxLuminance[0] = 0.0f;+ dispatch.minMaxLuminance[1] = 1000.0f;+ dispatch.generationRect = generationRect;+ dispatch.frameID = frame;++ ffxQueryDescFrameGenerationSwapChainInterpolationCommandListDX12 queryList{};+ queryList.header.type = FFX_API_QUERY_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_INTERPOLATIONCOMMANDLIST_DX12;+ queryList.pOutCommandList = &dispatch.commandList;+ auto queryResult = functions.Query(&swapchainContext, &queryList.header);+ if (queryResult != FFX_API_RETURN_OK) ++queryFailures;+ ffxQueryDescFrameGenerationSwapChainInterpolationTextureDX12 queryTexture{};+ queryTexture.header.type = FFX_API_QUERY_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_INTERPOLATIONTEXTURE_DX12;+ queryTexture.pOutTexture = &dispatch.outputs[0];+ queryResult = functions.Query(&swapchainContext, &queryTexture.header);+ if (queryResult != FFX_API_RETURN_OK) ++queryFailures;++ const auto dispatchResult = functions.Dispatch(&fgContext, &dispatch.header);+ if (dispatchResult != FFX_API_RETURN_OK) ++dispatchFailures;+ if (frame == 0) {+ std::printf("[fsr-probe] frame0 prepare=%s configure=%s dispatch=%s interpCommandList=%p interpTexture=%p\n",+ resultName(prepareResult), resultName(configureResult), resultName(dispatchResult),+ dispatch.commandList, dispatch.outputs[0].resource);+ }++ list->Close();+ ID3D12CommandList* lists[] = {list.Get()};+ queue->ExecuteCommandLists(1, lists);+ const HRESULT presentResult = pipelined ? swapchain->Present(0, DXGI_PRESENT_ALLOW_TEARING)+ : swapchain->Present(1, 0);+ if (FAILED(presentResult)) ++presentFailures;+ // Pipelined mode mirrors the player: no per-frame GPU idle wait, so the+ // provider's pacing threads stay busy while the next frame is recorded.+ const UINT64 signal = frame + 1;+ queue->Signal(fence.Get(), signal);+ fence->SetEventOnCompletion(signal, fenceEvent);+ WaitForSingleObject(fenceEvent, pipelined ? 0 : 5000);+ }++ std::printf("[fsr-probe] frames=%u requestedGenerated=%u prepared=%llu real=%llu generated=%llu\n", kProbeFrames,+ generatedPerFrame,+ static_cast<unsigned long long>(preparedFrames),+ static_cast<unsigned long long>(counters.real.load()),+ static_cast<unsigned long long>(counters.generated.load()));+ std::printf("[fsr-probe] failures prepare=%llu configure=%llu dispatch=%llu query=%llu present=%llu callback=%llu\n",+ static_cast<unsigned long long>(prepareFailures),+ static_cast<unsigned long long>(configureFailures),+ static_cast<unsigned long long>(dispatchFailures),+ static_cast<unsigned long long>(queryFailures),+ static_cast<unsigned long long>(presentFailures),+ static_cast<unsigned long long>(counters.callbackFailures.load()));++ // Ground truth: the swapchain context reports how many frames it actually+ // presented, so require the requested multiplier to be reached.+ const uint64_t expectedGenerated = uint64_t(kProbeFrames - 1) * generatedPerFrame;+ const bool generatedFrames = counters.generated.load() >= expectedGenerated;+ const bool clean = prepareFailures == 0 && configureFailures == 0 && dispatchFailures == 0 &&+ queryFailures == 0 && presentFailures == 0 && counters.callbackFailures.load() == 0;+ if (fenceEvent) CloseHandle(fenceEvent);+ list.Reset();+ allocator.Reset();+ // The proxy swapchain is owned by its context: drop our reference before+ // destroying the context, otherwise the release calls into freed memory.+ swapchain.Reset();+ const auto destroyFg = functions.DestroyContext(&fgContext, nullptr);+ const auto destroySwapchain = functions.DestroyContext(&swapchainContext, nullptr);+ std::printf("[fsr-probe] DestroyContext framegen=%s swapchain=%s\n", resultName(destroyFg), resultName(destroySwapchain));++ // Settings changes in the player destroy the AMD swapchain and create a new+ // one for the same HWND; DXGI allows a single swapchain per HWND, so this+ // proves the teardown really releases the previous one.+ {+ IDXGISwapChain4* second = nullptr;+ ffxCreateContextDescFrameGenerationSwapChainForHwndDX12 again{};+ again.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_FOR_HWND_DX12;+ again.header.pNext = &swapchainVersion.header;+ again.swapchain = &second;+ again.hwnd = hwnd;+ again.desc = &scd;+ again.dxgiFactory = factory.Get();+ again.gameQueue = queue.Get();+ ffxContext secondContext = nullptr;+ const auto recreate = functions.CreateContext(&secondContext, &again.header, nullptr);+ std::printf("[fsr-probe] re-create after teardown result=%s swapchain=%p\n", resultName(recreate),+ static_cast<void*>(second));+ if (secondContext != nullptr) functions.DestroyContext(&secondContext, nullptr);}DestroyWindow(hwnd);FreeLibrary(loader);- return createResult == FFX_API_RETURN_OK ? 0 : 1;++ if (clean && generatedFrames) {+ std::printf("[fsr-probe] VERDICT generated frames reached the present callback on this adapter\n");+ return 0;+ }+ std::printf("[fsr-probe] VERDICT no proof of generated output (clean=%d generated=%d)\n",+ clean ? 1 : 0, generatedFrames ? 1 : 0);+ return 1;}