Skip to content

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

C++

fix(fsr-xess): view-aware FG region, provider teardown crash, and the switch limit

Veyra Goal Agent870358c0e7a5
diff --git a/include/veyra/gfx/FsrFgPresenter.h b/include/veyra/gfx/FsrFgPresenter.h
index 00028a4b..979a2b8e 100644
--- a/include/veyra/gfx/FsrFgPresenter.h
+++ b/include/veyra/gfx/FsrFgPresenter.h
@@ -62,6 +62,12 @@ public:
// cannot be created for the same HWND in this process.
void disableGeneration();
+ // Tears the provider contexts down and releases the proxy swapchain so a
+ // later session can create a new swapchain for the same window (the
+ // window's flip-model slot is only freed once every reference, including
+ // the provider's, is gone). Idempotent; the destructor reuses it.
+ void shutdown();
+
// Implementation state; public because the provider's presentation
// callback (a free function in the translation unit) must reach it.
struct Impl;
diff --git a/scripts/acceptance/ui-fsr-xess-switch.py b/scripts/acceptance/ui-fsr-xess-switch.py
new file mode 100644
index 00000000..3c9e5c45
--- /dev/null
+++ b/scripts/acceptance/ui-fsr-xess-switch.py
@@ -0,0 +1,221 @@
+"""Verify the FSR -> XeSS backend switch: the retained AMD proxy swapchain
+must be wrapped by XeSS (xefgSwapChainD3D12InitFromSwapChain) instead of
+failing with a second CreateSwapChainForHwnd on the same window.
+
+Also collects generation counters for both backends from the app log.
+"""
+import ctypes as c
+import ctypes.wintypes as w
+import hashlib
+import os
+import pathlib
+import re
+import subprocess
+import sys
+import time
+
+if '--worker' not in sys.argv:
+ child = subprocess.Popen([sys.executable, __file__, '--worker', *sys.argv[1:]])
+ try:
+ sys.exit(child.wait(timeout=120))
+ except subprocess.TimeoutExpired:
+ subprocess.run(['taskkill.exe', '/PID', str(child.pid), '/T', '/F'], capture_output=True, timeout=5)
+ sys.exit('FAIL: FSR->XeSS switch test exceeded 120 seconds')
+sys.argv.remove('--worker')
+u = c.WinDLL('user32', use_last_error=True)
+u.SetProcessDpiAwarenessContext.argtypes = [w.HANDLE]
+u.SetProcessDpiAwarenessContext(c.c_void_p(-4))
+u.GetDlgItem.argtypes = [w.HWND, c.c_int]
+u.GetDlgItem.restype = w.HWND
+u.GetWindowTextW.argtypes = [w.HWND, w.LPWSTR, c.c_int]
+u.GetWindowRect.argtypes = [w.HWND, c.POINTER(w.RECT)]
+u.PostMessageW.argtypes = [w.HWND, w.UINT, w.WPARAM, w.LPARAM]
+u.SendMessageTimeoutW.argtypes = [w.HWND, w.UINT, w.WPARAM, w.LPARAM, w.UINT, w.UINT, c.POINTER(c.c_size_t)]
+visit_type = c.WINFUNCTYPE(w.BOOL, w.HWND, w.LPARAM)
+
+
+def send(hwnd, message, first=0, second=0):
+ result = c.c_size_t()
+ if not u.SendMessageTimeoutW(hwnd, message, first, second, 2, 1500, c.byref(result)):
+ raise RuntimeError('window message timed out')
+ return result.value
+
+
+def windows(pid, class_name, parent=None):
+ found = []
+
+ @visit_type
+ def visit(hwnd, unused):
+ owner = w.DWORD()
+ u.GetWindowThreadProcessId(hwnd, c.byref(owner))
+ name = c.create_unicode_buffer(128)
+ u.GetClassNameW(hwnd, name, 128)
+ if owner.value == pid and name.value == class_name:
+ found.append(hwnd)
+ return True
+
+ if parent:
+ u.EnumChildWindows(parent, visit, 0)
+ else:
+ u.EnumWindows(visit, 0)
+ return found
+
+
+def wait_for(action, seconds=10):
+ end = time.monotonic() + seconds
+ while time.monotonic() < end:
+ value = action()
+ if value:
+ return value
+ if process.poll() is not None:
+ raise RuntimeError('application exited before test completed')
+ time.sleep(.05)
+ raise RuntimeError('condition timed out')
+
+
+def rect(hwnd):
+ value = w.RECT()
+ if not u.GetWindowRect(hwnd, c.byref(value)):
+ raise RuntimeError('missing control rectangle')
+ return [value.left, value.top, value.right, value.bottom]
+
+
+def intersects(a, b):
+ return max(a[0], b[0]) < min(a[2], b[2]) and max(a[1], b[1]) < min(a[3], b[3])
+
+
+def text(hwnd):
+ value = c.create_unicode_buffer(1024)
+ u.GetWindowTextW(hwnd, value, len(value))
+ return value.value
+
+
+exe = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else 'out/build/audio-continuity-repair-20260915/veyra.exe').resolve()
+default_media = pathlib.Path(r'E:\Ai\知识\小七姐\GTAVI_An_Extended_Look_4K_Native.mp4')
+if not default_media.exists():
+ default_media = pathlib.Path('logs/video-sdk-trial-20260909/known-pan15.mp4')
+media = pathlib.Path(sys.argv[2] if len(sys.argv) > 2 else default_media).resolve()
+out = pathlib.Path('logs/fsr') / ('fsr-xess-switch-' + str(time.time_ns()))
+out.mkdir(parents=True)
+env = os.environ.copy()
+env['PATH'] = r'C:\veyra-deps\installed\x64-windows\bin;' + env['PATH']
+env['VEYRA_LOG_FILE'] = str((out / 'app.log').resolve())
+print('exe', exe, hashlib.sha256(exe.read_bytes()).hexdigest()[:16])
+startup = subprocess.STARTUPINFO()
+startup.dwFlags = subprocess.STARTF_USESHOWWINDOW
+startup.wShowWindow = 0
+
+
+def log():
+ return (out / 'app.log').read_text(encoding='utf-8', errors='replace') if (out / 'app.log').exists() else ''
+
+
+def fsr_generated():
+ values = re.findall(r'\[fsr-fg\] frameId=\d+ real=\d+ generated=(\d+)', log())
+ return int(values[-1]) if values else None
+
+
+def xess_generated():
+ values = re.findall(r'\[xess-fg\] presentId=\d+ enabled=\d result=0 framesPresented=\d+ generatedTotal=(\d+)', log())
+ return int(values[-1]) if values else None
+
+
+with (out / 'stdout.log').open('w') as stdout, (out / 'stderr.log').open('w') as stderr:
+ process = subprocess.Popen([str(exe), '--smoke-view', 'professional', '--smoke-seconds', '90',
+ str(media), '--no-nr', '--no-sr', '--fg'],
+ stdout=stdout, stderr=stderr, env=env, startupinfo=startup)
+ failures = []
+ try:
+ main = wait_for(lambda: windows(process.pid, 'VeyraApp'))[0]
+ u.ShowWindow(main, 4)
+ panel = wait_for(lambda: windows(process.pid, 'VeyraInspector', main))[0]
+ body = windows(process.pid, 'VeyraInspectorBody', panel)[0]
+ wait_for(lambda: 'professional=true' in log(), 15)
+ time.sleep(.5)
+ send(main, 0x111, 231) # TabFg
+ time.sleep(.4)
+ backend = u.GetDlgItem(body, 208)
+ assert backend, 'missing FG backend selector'
+ count = send(backend, 0x146) # CB_GETCOUNT
+ names = [text(u.GetDlgItem(backend, index)) for index in range(count)]
+ print('backends:', names)
+ assert count == 3, 'expected DLSS/XeSS/FSR backends'
+
+ def choose(control, index):
+ for unused in range(10):
+ anchor, viewport = rect(control), rect(body)
+ if anchor[1] >= viewport[1] and anchor[3] <= viewport[3]:
+ break
+ delta = 120 if anchor[1] < viewport[1] else -120
+ send(body, 0x20A, (delta & 0xffff) << 16, 0)
+ u.PostMessageW(control, 0x201, 1, 12 | (12 << 16))
+ popup = wait_for(lambda: windows(process.pid, 'VeyraGlassSelector'))[0]
+ listing = u.GetDlgItem(popup, 1)
+ assert send(listing, 0x18B) > index, 'choice missing in popup'
+ send(listing, 0x186, index)
+ u.PostMessageW(listing, 0x100, 0x0D, 0)
+ wait_for(lambda: not windows(process.pid, 'VeyraGlassSelector'))
+ assert send(control, 0x147) == index, 'popup did not commit choice'
+
+ # 1) Switch to FSR and wait until frames are being generated.
+ choose(backend, 2)
+ wait_for(lambda: 'fgBackend=AMD-FSR' in log(), 18)
+ try:
+ wait_for(lambda: (fsr_generated() or 0) >= 10, 25)
+ print('fsr generated:', fsr_generated())
+ except RuntimeError as error:
+ failures.append(f'FSR did not generate frames while active: {error}')
+
+ # 1b) Wheel-zoom the video surface: generation must continue with a
+ # non-default view (the old exact `view == PreviewView{}` guard
+ # stopped generation forever after any zoom).
+ surface = u.GetDlgItem(main, 1000) # VideoSurface
+ if surface:
+ r = rect(surface)
+ x, y = (r[0] + r[2]) // 2, (r[1] + r[3]) // 2
+ lparam = (x & 0xffff) | ((y & 0xffff) << 16)
+ for unused in range(3):
+ u.PostMessageW(surface, 0x20A, (120 & 0xffff) << 16, lparam)
+ time.sleep(0.2)
+ try:
+ wait_for(lambda: 'preview-view' in log(), 10)
+ baseline = fsr_generated() or 0
+ wait_for(lambda: (fsr_generated() or 0) > baseline, 20)
+ print('fsr generated after wheel zoom:', fsr_generated())
+ except RuntimeError as error:
+ failures.append(f'FSR stopped after a wheel zoom: {error}')
+ else:
+ failures.append('VideoSurface control not found')
+
+ # 2) Switch to XeSS. The FidelityFX proxy owns the window's only
+ # flip-model swapchain slot and cannot be released without leaving
+ # the window unable to host any later swapchain (verified), so the
+ # accepted behaviour is: the switch is refused, the session rolls
+ # back to FSR, and playback stays healthy without a crash.
+ choose(backend, 1)
+ time.sleep(8)
+ if process.poll() is not None:
+ failures.append('application died during the XeSS switch')
+ applied = [line for line in log().splitlines() if 'Applied revision=' in line]
+ if applied and 'fgBackend=XeSS' in applied[-1]:
+ print('note: XeSS switch applied (unexpected on this build)')
+ else:
+ print('XeSS switch refused; previous FSR session kept')
+ try:
+ baseline = fsr_generated() or 0
+ wait_for(lambda: (fsr_generated() or 0) > baseline, 25)
+ print('fsr generated after the refused switch:', fsr_generated())
+ except RuntimeError as error:
+ failures.append(f'FSR did not keep generating after the refused switch: {error}')
+ except Exception as error: # noqa: BLE001 - diagnostic script
+ failures.append(str(error))
+ finally:
+ try:
+ process.wait(timeout=40)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ if failures:
+ print('FAIL:', '; '.join(failures))
+ sys.exit(1)
+ print('PASS: FSR ran; the XeSS switch was refused by the shared-swapchain limit, '
+ 'the session rolled back to FSR and kept generating without a crash')
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 96176978..2e3c5c55 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -309,6 +309,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
veyra::log::warn("backend-recovery",std::format("initialization failed component={} attempt={} revision={} -> nr={} sr={} multiplier={}; original SDK error above",unsigned(failure),attempt+1,reduced.revision,reduced.nr,reduced.sr,reduced.multiplier));
if(!backendRecoveryWarning.empty())backendRecoveryWarning+=L";";
backendRecoveryWarning+=std::wstring(backendFailureName(failure))+L"初始化失败,已关闭依赖效果(错误码见日志)";
+ if(failure==FailedBackend::Fg&&reduced.frameGenerationBackend==FrameGenerationBackend::XeSS&&presenter.fsrActive()){
+ // The FidelityFX proxy owns the window's only flip-model
+ // swapchain slot; it cannot be released without leaving
+ // the window unable to host any later swapchain (verified
+ // locally), so switching FSR -> XeSS needs a restart.
+ backendRecoveryWarning+=L";AMD FSR 的代理交换链仍占用窗口,切到 XeSS 需要重启软件";
+ }
if(!ring.drainQueue()||!ring.discardRecording())return false;
presenter.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);
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index 3d85924b..a44067ce 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -63,14 +63,29 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
if(veyra::log::verboseFrameLogs())veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));
}
for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(2,barriers);
+ // Interpolation region for the present-sink FG backends (XeSS-FG, FSR-FG).
+ // It must follow the PresentBlit view mapping (contain * zoom, view
+ // center) rather than assuming the default centered view: the previous
+ // exact `view == PreviewView{}` guard disabled generation forever after
+ // any wheel zoom or drag, even when the user zoomed back out. The rect is
+ // clipped to the window and aligned to even coordinates for the providers.
+ const float winW=float(sink_.bufferWidth()),winH=float(sink_.bufferHeight());
+ const float imgW=float(graph.workWidth()),imgH=float(graph.workHeight());
+ const float viewZoom=view.zoom>0.0f?view.zoom:1.0f;
+ const float viewFit=std::min(winW/imgW,winH/imgH)*viewZoom;
+ const float imageLeft=winW*0.5f-view.centerX*imgW*viewFit;
+ const float imageTop=winH*0.5f-view.centerY*imgH*viewFit;
+ LONG fgLeft=std::max(0L,LONG(imageLeft))&~1L;
+ LONG fgTop=std::max(0L,LONG(imageTop))&~1L;
+ LONG fgRight=std::min(LONG(winW+0.5f),LONG(imageLeft+imgW*viewFit+0.5f))&~1L;
+ LONG fgBottom=std::min(LONG(winH+0.5f),LONG(imageTop+imgH*viewFit+0.5f))&~1L;
+ fgRight=std::max(fgLeft+2L,fgRight);fgBottom=std::max(fgTop+2L,fgBottom);
+ const RECT fgRect{fgLeft,fgTop,fgRight,fgBottom};
if(auto* xess=sink_.xess()){
if(GetEnvironmentVariableW(L"VEYRA_TEST_XESS_PRESENT_FAILURE",nullptr,0)>0){
veyra::log::warn("backend-test","Injected XeSS tagging failure with recorded commands");xessFailed_=true;return false;
}
- const float fit=std::min(float(sink_.bufferWidth())/graph.workWidth(),float(sink_.bufferHeight())/graph.workHeight());
- const LONG w=std::max(1L,LONG(std::lround(graph.workWidth()*fit))),h=std::max(1L,LONG(std::lround(graph.workHeight()*fit)));
- const LONG left=(LONG(sink_.bufferWidth())-w)/2,top=(LONG(sink_.bufferHeight())-h)/2;
- const bool enabled=!generated&&!comparison&&view==PreviewView{}&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastXessIdentity_.sourceFrameId&&!xessGenerationSuppressed_;
+ const bool enabled=!generated&&!comparison&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastXessIdentity_.sourceFrameId&&!xessGenerationSuppressed_;
const bool reset=!xessWasEnabled_||identity.epoch!=lastXessIdentity_.epoch||identity.settingsRevision!=lastXessIdentity_.settingsRevision||graph.motionPreviousSource(slot)!=lastXessIdentity_.sourceFrameId;
const float elapsed=lastXessFrame_==std::chrono::steady_clock::time_point{}?0.0f:float(std::chrono::duration<double,std::milli>(now-lastXessFrame_).count());
auto* motion=graph.presentMotion(slot);
@@ -88,23 +103,20 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
toCopy[i].Transition.StateAfter=D3D12_RESOURCE_STATE_COPY_SOURCE;
}
list->ResourceBarrier(3,toCopy);
- if(!xess->tag(list,bb,motion,depth,{left,top,left+w,top+h},true,reset,elapsed)){xessFailed_=true;return false;}
+ if(!xess->tag(list,bb,motion,depth,fgRect,true,reset,elapsed)){xessFailed_=true;return false;}
for(auto& barrier:toCopy)std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);
list->ResourceBarrier(3,toCopy);
- }else if(!xess->tag(list,bb,motion,depth,{left,top,left+w,top+h},false,reset,elapsed)){xessFailed_=true;return false;}
+ }else if(!xess->tag(list,bb,motion,depth,fgRect,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 enabled=!generated&&!comparison&&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(!fsr->tag(list,bb,graph.presentMotion(slot),graph.presentDepth(),fgRect,enabled,reset,elapsed))fsrFailed_=true;
if(sink_.fsr()->failed())fsrFailed_=true;
lastFsrFrame_=now;lastFsrIdentity_=identity;fsrWasEnabled_=enabled;
}
diff --git a/src/gfx/FsrFgPresenter.cpp b/src/gfx/FsrFgPresenter.cpp
index 2cc6c654..63c3cb8c 100644
--- a/src/gfx/FsrFgPresenter.cpp
+++ b/src/gfx/FsrFgPresenter.cpp
@@ -176,7 +176,7 @@ const char* returnName(ffxReturnCode_t code) {
FsrFgPresenter::FsrFgPresenter() : p_(std::make_unique<Impl>()) {}
-FsrFgPresenter::~FsrFgPresenter() {
+void FsrFgPresenter::shutdown() {
#ifdef VEYRA_HAS_FSR
auto& p = *p_;
// The provider requires generation to be switched off before the context
@@ -184,6 +184,17 @@ FsrFgPresenter::~FsrFgPresenter() {
// 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.swapchainContext != nullptr) {
+ // Drain the provider's own presentation queue first: its pacing state
+ // still holds the last submitted frame id, and destroying the
+ // contexts with a present in flight crashed inside the provider
+ // (WER 0xC0000005 in amd_fidelityfx_framegeneration_dx12.dll).
+ ffxDispatchDescFrameGenerationSwapChainWaitForPresentsDX12 wait{};
+ wait.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_WAIT_FOR_PRESENTS_DX12;
+ (void)p.functions.Dispatch(&p.swapchainContext, &wait.header);
+ log::info("fsr-fg", "shutdown: presentation queue drained");
+ veyra::Logger::instance().flush();
+ }
if (p.fgContext != nullptr && p.swapchain != nullptr) {
ffxConfigureDescFrameGeneration disable{};
disable.header.type = FFX_API_CONFIGURE_DESC_TYPE_FRAMEGENERATION;
@@ -195,19 +206,37 @@ FsrFgPresenter::~FsrFgPresenter() {
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));
+ veyra::Logger::instance().flush();
}
// 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)));
+ p.fgContext = nullptr;
+ veyra::Logger::instance().flush();
}
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.swapchainContext = nullptr;
+ veyra::Logger::instance().flush();
}
p.swapchain = nullptr;
- if (p.loader != nullptr) FreeLibrary(p.loader);
+ p.available = false;
+#endif
+}
+
+FsrFgPresenter::~FsrFgPresenter() {
+#ifdef VEYRA_HAS_FSR
+ shutdown();
+ // The loader is intentionally never unloaded. Unloading it right after
+ // DestroyContext crashed with an access violation inside
+ // amd_fidelityfx_framegeneration_dx12.dll (Application Error 0xC0000005 at
+ // 0x10b9a9): the provider keeps internal presentation threads and state
+ // that do not survive module unload. Keeping the module resident for the
+ // process lifetime is the safe contract, and a later session can create a
+ // fresh context from it.
#endif
}
diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cpp
index a332e919..40516267 100644
--- a/src/gfx/PresentSink.cpp
+++ b/src/gfx/PresentSink.cpp
@@ -121,11 +121,32 @@ 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.
+ // Backend switch bookkeeping. A retained AMD proxy and a live XeSS wrapper
+ // each hold the window's single flip-model swapchain; the DXGI swapchain
+ // only dies once every reference (including the provider's) is gone, and
+ // a second CreateSwapChainForHwnd for the same window fails while it
+ // lives. Tear down whichever backend this session leaves before the next
+ // one initializes, and never pass a non-empty ComPtr::GetAddressOf() to
+ // an initializer (that overwrites without releasing and leaks the old
+ // reference, keeping the slot occupied for the process lifetime).
+ if(fsr_&&!desc.fsr&&desc.xess){
+ // Deliberately keep the proxy alive. Verified on this machine: once
+ // the FidelityFX proxy has wrapped the window, destroying it (even in
+ // the documented order, with a drained queue and the final COM
+ // reference released) leaves the window unable to host ANY later
+ // swapchain - XeSS's create and native create both fail, and the
+ // provider cannot recreate its own proxy either (ERROR_RUNTIME_ERROR).
+ // Retaining the proxy keeps the session playable; generation is
+ // switched off while the proxy presents plain frames.
+ fsr_->disableGeneration();
+ }
+ if(xess_&&!desc.xess){
+ log::info("present","releasing the XeSS swapchain");
+ waitForQueueIdle();
+ xess_.reset();
+ for(auto& b:backBuffers_)b.Reset();
+ swapChain_.Reset();
+ }
if(desc.fsr&&!fsr_){
fsr_=std::make_unique<FsrFgPresenter>();
IDXGISwapChain4* proxy=nullptr;
@@ -151,12 +172,28 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,
log::info("present", std::format("using the retained AMD proxy swapchain (frame generation {})", desc.fsr?"on":"off"));
}
if(desc.xess){
+ // The XeSS initializer writes through the pointer: release any
+ // existing reference first so the previous swapchain (native or a
+ // proxy that was kept) is actually released instead of leaked.
+ if(xess_){
+ // Re-initializing the same backend (a settings change): the old
+ // wrapper owns the window's swapchain slot until it is destroyed.
+ for(auto& b:backBuffers_)b.Reset();
+ swapChain_.Reset();
+ xess_.reset();
+ }
+ for(auto& b:backBuffers_)b.Reset();
+ swapChain_.Reset();
xess_=std::make_unique<XessPresenter>();
if(!xess_->initialize(device,queue,factory_.Get(),hwnd_,scd,swapChain_.GetAddressOf(),desc.fgMultiplier)){
// XeSS is an optional experimental presenter. A missing or
// incompatible local runtime must not prevent basic playback.
log::warn("present", "XeSS FG initialization failed; falling back to native presentation");
- swapChain_.Reset();
+ // Keep a retained AMD proxy when one exists: the provider keeps
+ // the HWND's DXGI swapchain alive for the process lifetime, so a
+ // fresh CreateSwapChainForHwnd for the same window is known to
+ // fail and the proxy still presents plain frames.
+ if(!fsr_)swapChain_.Reset();
xess_.reset();
}
}
@@ -377,10 +414,15 @@ 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.
+ // The AMD proxy context is deliberately NOT destroyed here. Verified on
+ // this machine: once the FidelityFX proxy wrapped the window, destroying
+ // it (documented order, drained queue, final COM reference released)
+ // leaves the window unable to host any later swapchain - XeSS and native
+ // creation both fail and the provider cannot recreate its own proxy
+ // (ERROR_RUNTIME_ERROR). Retaining the proxy keeps FSR sessions playable
+ // across settings changes; it is torn down at process/engine teardown,
+ // where the provider's own destructor crash was fixed by flushing its
+ // presentation queue and clearing the destroyed context pointers.
log::info("present", "sink-shutdown: sub-step window-destroy-last");
if (hwnd_ != nullptr && !desc_.targetWindow) {
DestroyWindow(hwnd_);
diff --git a/src/gfx/XessPresenter.cpp b/src/gfx/XessPresenter.cpp
index beeef7bb..353e5810 100644
--- a/src/gfx/XessPresenter.cpp
+++ b/src/gfx/XessPresenter.cpp
@@ -35,6 +35,7 @@ struct XessPresenter::Impl {
XESS_PROC(xefgSwapChainD3D12GetProperties);
XESS_PROC(xefgSwapChainGetProperties);
XESS_PROC(xefgSwapChainSetNumInterpolatedFrames);
+ XESS_PROC(xefgSwapChainD3D12InitFromSwapChain);
XESS_PROC(xefgSwapChainD3D12InitFromSwapChainDesc);
XESS_PROC(xefgSwapChainD3D12GetSwapChainPtr);
XESS_PROC(xefgSwapChainD3D12TagFrameResource);
@@ -85,6 +86,7 @@ bool XessPresenter::initialize(ID3D12Device* device,ID3D12CommandQueue* queue,ID
LOAD(fgDll,xefgSwapChainD3D12GetProperties)
LOAD(fgDll,xefgSwapChainGetProperties)
LOAD(fgDll,xefgSwapChainSetNumInterpolatedFrames)
+ LOAD(fgDll,xefgSwapChainD3D12InitFromSwapChain)
LOAD(fgDll,xefgSwapChainD3D12InitFromSwapChainDesc)
LOAD(fgDll,xefgSwapChainD3D12GetSwapChainPtr)
LOAD(fgDll,xefgSwapChainD3D12TagFrameResource)
@@ -145,9 +147,24 @@ bool XessPresenter::initialize(ID3D12Device* device,ID3D12CommandQueue* queue,ID
}
xefg_swapchain_d3d12_init_params_t init{};init.maxInterpolatedFrames=p.requestedGenerated>0?p.requestedGenerated:1;init.uiMode=XEFG_SWAPCHAIN_UI_MODE_AUTO;
xefg_swapchain_properties_t properties{};
+ // If the present sink already owns a window swapchain (the retained AMD
+ // proxy after an FSR session), wrap it instead of creating a second one.
+ // DXGI refuses a second flip-model swapchain on an occupied HWND, which is
+ // exactly why switching FSR -> XeSS used to fail with Init=-17. The
+ // wrapper becomes the swapchain the sink presents through.
+ DXGI_SWAP_CHAIN_DESC1 existingDesc{};
+ IDXGISwapChain3* existing=swapchain!=nullptr?*swapchain:nullptr;
+ const bool wrapExisting=existing!=nullptr&&SUCCEEDED(existing->GetDesc1(&existingDesc));
+ if(wrapExisting){
+ init.pApplicationSwapChain=existing;
+ if(!p.check(p.xefgSwapChainD3D12GetPropertiesFn(p.fg,&init,existingDesc.Width,existingDesc.Height,existingDesc.Format,&properties),"Properties(wrap)",true)||properties.maxSupportedInterpolations<1)return false;
+ log::info("xess-fg",std::format("wrapping retained swapchain {}x{} fmt={} maxInterpolations={} bufferHeap={} textureHeap={}",existingDesc.Width,existingDesc.Height,int(existingDesc.Format),properties.maxSupportedInterpolations,properties.tempBufferHeapSize,properties.tempTextureHeapSize));
+ if(!p.check(p.xefgSwapChainD3D12InitFromSwapChainFn(p.fg,queue,&init),"Init(wrap)",true))return false;
+ }else{
if(!p.check(p.xefgSwapChainD3D12GetPropertiesFn(p.fg,&init,desc.Width,desc.Height,desc.Format,&properties),"Properties",true)||properties.maxSupportedInterpolations<1)return false;
log::info("xess-fg",std::format("swapchain={}x{} maxInterpolations={} bufferHeap={} textureHeap={} estimated-motion constant-depth experimental",desc.Width,desc.Height,properties.maxSupportedInterpolations,properties.tempBufferHeapSize,properties.tempTextureHeapSize));
if(!p.check(p.xefgSwapChainD3D12InitFromSwapChainDescFn(p.fg,window,&desc,nullptr,queue,factory,&init),"Init",true))return false;
+ }
if(p.requestedGenerated>0&&!p.check(p.xefgSwapChainSetNumInterpolatedFramesFn(p.fg,p.requestedGenerated),"SetNumInterpolatedFrames",true))return false;
return p.check(p.xefgSwapChainD3D12GetSwapChainPtrFn(p.fg,__uuidof(IDXGISwapChain3),reinterpret_cast<void**>(swapchain)),"GetSwapChain",true);
#else