Compare commits

..
Author SHA1 Message Date
The412Banner b9a535170e fix(upscale): FSR 4 Lite stands in for FSR 4 full on Turnip
The FSR 4.1.1 full path (descriptor buffers) runs on Turnip but writes a black frame (Elite, Adreno 830:
5 screenshots, no lit pixel, while the status said ok). FSR 4.1.2 Lite, on classic descriptors, works there,
so the full path now declines on VK_DRIVER_ID_MESA_TURNIP and the pipeline's own fallback runs Lite, with
reason full_black_on_turnip_lite_used in the status. DROIDDECK_UPSCALE_FULL_ON_TURNIP=1 runs it anyway.
2026-11-30 02:46:33 -05:00
The412Banner b6457b0cf7 fix(upscale): fixes from the first Elite test round
- Bridge DLLs: staged from an exact list (24 files) and only reported done when all of them are in
  place; the local copy is also read from the app's own external files folder, which needs no storage
  permission (Download/ alone could not be listed without it, so nothing was copied while the log said
  true). An installed add-on pack is staged again when the rootfs copy is gone.
- "Upscaler files" counts the bridge DLLs, not only the data files.
- FSR 4 / FSR 4 Lite: a render-sized D32 stand-in depth (cleared to the far plane) when the game sends
  none, as XeSS allows; both used to fall back to FSR 3.1 for such games.
- droiddeck-game-env writes the live switch file from the game's own settings at every launch, so the
  previous game's or the in-game menu's choice no longer wins at start.
- Intel's XeSS runtime goes into every upscaler game's prefix once downloaded (hard link where the file
  system allows), so XeSS 3 also works when picked in the in-game menu.
2026-11-30 02:22:54 -05:00
The412Banner 217817fa83 fix(upscale): read every export row whatever objdump prints above them
The check skipped two lines after the export table header, but older binutils
(CI's) print no column titles there, so the first export (ffxConfigure) was
never read.
2026-11-29 23:04:09 -05:00
The412Banner d78ff7ddc7 fix(upscale): no identical-code folding in the bridge DLLs
CI's mingw folded ffxConfigure into an identical stub and dropped its export
(amd_fidelityfx_vk.dll: missing ffxConfigure); every exported name keeps its
own body.
2026-11-29 22:58:33 -05:00
The412Banner f2309c8a09 merge: upscale bridge DLLs (tools/upscale/bridges, add-on pack 'upscale') from wip/upscale-bridges 2026-11-29 22:52:43 -05:00
The412Banner 491106ac3c feat(upscale): build the DLSS / FSR / XeSS bridge DLLs from source and ship them as the upscale pack
Ports the Windows x64 bridge DLLs of michaelisomer-cyber/Winlator-NeuralScale (a0ab6b0f,
GPL-3.0) to tools/upscale/bridges. They replace a game's nvngx, nvapi64, FidelityFX,
FSR 2/3 and XeSS DLLs inside Wine and hand each frame to the Android Vulkan layer
through the unchanged fsr4_seam_proto.h buffers.

- build.sh builds the 12 DLLs with MinGW-w64 GCC, deterministically, checks each
  export table against its .def and stamps them as Wine builtins (winebuild --builtin
  signature at 0x40), into x86_64-windows/ and aarch64-windows/.
- CI: recipe upscale-bridges into linuxfs/usr/local/lib/droiddeck-upscale/bridges,
  kept out of the APK and shipped as the upscale add-on pack, like dirt.
- D3D11 NGX now reports DLSS unavailable instead of succeeding and rendering nothing.
- The nvapi64 signature hooks run only with DROIDDECK_UPSCALE_SIGFIX=1, logging only
  with DROIDDECK_UPSCALE_LOG=1; DROIDDECK_UPSCALE_* variables are read before the
  fork's WINLATOR_FSR4_* names.
2026-11-29 22:51:53 -05:00
The412Banner c0af05f103 feat(upscale): bridges from Download/droiddeck-upscale/bridges when the pack is not installed
Branch builds publish no add-on packs; a local copy beside the data files lets
such a build be tested.
2026-11-29 22:46:36 -05:00
The412Banner 02d57b2a78 merge: VK_LAYER_DROIDDECK_upscale (tools/upscale/layer) from wip/upscale-layer 2026-11-29 22:34:38 -05:00
The412Banner b4210b5a67 upscale: build the upscaler layer as VK_LAYER_DROIDDECK_upscale
Port of the NeuralScale layer (previous commit) for DroidDeck:

- Layer VK_LAYER_DROIDDECK_upscale, library libVkLayer_droiddeck_upscale.so,
  implicit manifest template (DROIDDECK_UPSCALE=1 / DROIDDECK_UPSCALE_DISABLE=1).
- Settings read as DROIDDECK_UPSCALE_<KEY>, then WINLATOR_FSR4_<KEY>.
- No hardcoded com.winlator.cmod data dir; without a dir frames get the blit
  fallback.
- Compiled NPU graph caches go to <dir>/<htp arch>/ (v79/v81 from HTP_ARCH,
  the SoC properties or the mapped QNN stub) instead of <dir>/v81/.
- The arch stub is loaded from the QNN library search list first, so
  NATIVELIB_DIR is enough without LD_LIBRARY_PATH.
- driverID/driverName are only rewritten with GPU_SPOOF word "1";
  SPOOF_DLSS=1 alone reports RTX vendor/device IDs.
- APK build via app/src/main/cpp/CMakeLists.txt; glibc build for the PRoot
  guest (build-glibc.sh, DD_UPSCALE_NO_ANDROID: QNN stubs, stderr log) in
  the runtime recipe, installed to usr/local/lib/droiddeck-upscale-layer/.
- -Bsymbolic so the exported vkGetInstanceProcAddr is not interposed by a
  libvulkan in the global scope.
- Pack scripts take their paths as arguments.

Seam protocol, buffer sizes, magic values and backend IDs are unchanged.
2026-11-29 22:34:00 -05:00
The412Banner 63311bdeaf feat(upscale): in-game upscaler settings, launch wiring, live controls and HUD row
Per-game choice (FSR/XeSS, DLSS or native FSR 4 mode, engine, sharpness, NPU
sync, DLSS signature fix) in the game environment; droiddeck-game-env turns it
into the bridge DLL overrides and folder, the layer switch, the control and
status files, the NVIDIA or AMD identity for DLSS / native mode and the NGX
registry entries (DLSS mode only). Bionic: paths converted in proton, names
kept in launch.sh, the APK layer's manifest on VK_ADD_IMPLICIT_LAYER_PATH.
UpscaleComponent fetches AMD's FSR 4 data, Intel's XeSS runtime and Qualcomm's
QNN files from Winlator-NeuralScale at a pinned commit (SHA-256 checked),
stages the upscale add-on pack and writes the live control file.
2026-11-29 22:27:38 -05:00
The412Banner 7972c18e50 upscale: import the NeuralScale Vulkan upscaler layer sources unchanged
Verbatim copy of app/src/main/cpp/fsr4npu/ (C sources, headers, shaders,
weight pack scripts) from michaelisomer-cyber/Winlator-NeuralScale at
a0ab6b0f770e1a6786b4e68def46b4edb8baafd0 (GPL-3.0, fork of
StevenMXZ/Winlator-Ludashi). Not built yet; the DroidDeck port follows.
2026-11-29 22:18:41 -05:00
104 changed files with 19675 additions and 1158 deletions

No files matched your search

+3
View File
@@ -322,6 +322,9 @@ jobs:
- name: Build the DiRT 3 / DiRT Showdown ws2_32 stand-in
run: python3 tools/components/prepare.py dirt-ws2
- name: Build the DLSS / FSR / XeSS upscale bridges
run: python3 tools/components/prepare.py upscale-bridges
- name: Cache graphics driver inputs
uses: actions/cache@v4
with:
+1 -1
View File
@@ -55,7 +55,7 @@ jobs:
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
}
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic; do
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic upscale; do
file="packs/$name.tar.zst"
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
sha=$(sha256sum "$file" | cut -d' ' -f1)
+2 -2
View File
@@ -93,7 +93,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name ->
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic', 'upscale'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
@@ -203,7 +203,7 @@ android {
}
androidResources {
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>droiddeck-ubisoft:<dir>droiddeck-rockstar:<dir>droiddeck-dirt:<dir>droiddeck-epic:<dir>directaudio:<dir>hybris'
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>droiddeck-ubisoft:<dir>droiddeck-rockstar:<dir>droiddeck-dirt:<dir>droiddeck-epic:<dir>droiddeck-upscale:<dir>directaudio:<dir>hybris'
}
packagingOptions {
+1
View File
@@ -30,6 +30,7 @@ message(STATUS "dd-fg chain: win-fg ${DDFG_UPSTREAM} (src ${DDFG_CHAIN_HASH})")
add_subdirectory(waylandcomp)
add_subdirectory(questxr)
add_subdirectory(../../../../tools/upscale/layer upscale_layer)
add_library(sdnative SHARED sdnative/sdnative.c)
target_link_libraries(sdnative log)
-22
View File
@@ -4130,17 +4130,6 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) {
return read_input(fd, buf, count);
}
extern "C" [[noreturn]] void __chk_fail(void);
/* Programs built with _FORTIFY_SOURCE (Flatpak runtimes among them) call these instead of read, poll
* and ppoll, and glibc's versions go straight to the kernel. */
EXPORT ssize_t __read_chk(int fd, void *buf, size_t count, size_t buflen) {
static auto next_read_chk = reinterpret_cast<ssize_t (*)(int, void *, size_t, size_t)>(dlsym(RTLD_NEXT, "__read_chk"));
if (count > buflen) __chk_fail();
if (next_read_chk && !is_fake_input_fd(fd)) return next_read_chk(fd, buf, count, buflen);
return read_input(fd, buf, count);
}
EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
if (!is_fake_input_fd(fd)) return syscall(SYS_readv, fd, iov, iovcnt);
if (iovcnt < 0 || iovcnt > IOV_MAX) {
@@ -4389,17 +4378,6 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
return my_ppoll(fds, nfds, timeout, sigmask);
}
EXPORT int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
return poll(fds, nfds, timeout);
}
EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout,
const sigset_t *sigmask, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
return ppoll(fds, nfds, timeout, sigmask);
}
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout) {
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
+39 -286
View File
@@ -242,10 +242,6 @@ struct surface {
enum surface_role role;
struct wl_resource *idle_buffer;
struct wl_listener idle_buffer_destroy;
struct surface_state *waiting;
struct wl_event_source *waiting_source, *waiting_timer;
int waiting_fd;
int64_t waiting_since_ns;
uint32_t *idle_px;
int idle_w, idle_h;
struct wl_resource *xdg_surface, *xdg_toplevel;
@@ -377,8 +373,6 @@ static struct {
unsigned copy_scenes;
unsigned releases, releases_held;
int64_t release_ns, release_max_ns;
unsigned commit_waits, commit_wait_limits;
int64_t commit_wait_ns, commit_wait_max_ns;
} g_perf;
static void schedule_render(void);
@@ -852,55 +846,6 @@ static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) {
s->pending_buffer = NULL;
}
struct surface_state {
struct wl_resource *buffer;
struct wl_listener buffer_destroy;
int attach;
int src_set, dst_set, opaque_set;
float src[4];
int dst[2], opaque[4];
struct damage_list damage_buf, damage_local;
struct wl_list frames, feedback;
};
static void on_state_buffer_destroyed(struct wl_listener *l, void *data) {
struct surface_state *st = wl_container_of(l, st, buffer_destroy);
wl_list_remove(&st->buffer_destroy.link);
wl_list_init(&st->buffer_destroy.link);
st->buffer = NULL;
st->attach = 0;
}
static void surface_state_take(struct surface *s, struct surface_state *st) {
st->attach = s->pending_attach;
st->buffer = s->pending_buffer;
wl_list_init(&st->buffer_destroy.link);
if (st->buffer) {
wl_list_remove(&s->pending_buffer_destroy.link);
wl_list_init(&s->pending_buffer_destroy.link);
st->buffer_destroy.notify = on_state_buffer_destroyed;
wl_resource_add_destroy_listener(st->buffer, &st->buffer_destroy);
}
s->pending_buffer = NULL;
s->pending_attach = 0;
st->src_set = s->pending_src_set;
memcpy(st->src, s->pending_src, sizeof(st->src));
st->dst_set = s->pending_dst_set;
memcpy(st->dst, s->pending_dst, sizeof(st->dst));
st->opaque_set = s->pending_opaque_set;
memcpy(st->opaque, s->pending_opaque, sizeof(st->opaque));
s->pending_src_set = s->pending_dst_set = s->pending_opaque_set = 0;
st->damage_buf = s->pending_damage_buf;
st->damage_local = s->pending_damage_local;
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
wl_list_init(&st->frames);
wl_list_insert_list(&st->frames, &s->pending_frames);
wl_list_init(&s->pending_frames);
wl_list_init(&st->feedback);
wl_list_insert_list(&st->feedback, &s->pending_feedback);
wl_list_init(&s->pending_feedback);
}
static void fire_frames(struct wl_list *frames) {
struct wl_resource *cb, *tmp;
uint32_t t;
@@ -1418,23 +1363,35 @@ static void surface_drop_idle(struct surface *s) {
if (buffer) send_buffer_release(buffer);
}
static void surface_state_apply(struct surface *s, struct surface_state *st) {
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
struct surface *child;
if (st->src_set) {
s->src_set = st->src[2] > 0;
memcpy(s->src, st->src, sizeof(s->src));
if (s->xdg_toplevel && !s->toplevel_committed) {
s->toplevel_committed = 1;
send_toplevel_configure(s);
}
if (st->dst_set) {
s->dst_set = st->dst[0] > 0;
memcpy(s->dst, st->dst, sizeof(s->dst));
}
if (st->opaque_set) memcpy(s->opaque, st->opaque, sizeof(s->opaque));
s->damage_buf = st->damage_buf;
s->damage_local = st->damage_local;
if (st->attach) {
struct wl_resource *buffer = st->buffer;
if (s->pending_src_set) {
s->src_set = s->pending_src[2] > 0;
memcpy(s->src, s->pending_src, sizeof(s->src));
s->pending_src_set = 0;
}
if (s->pending_dst_set) {
s->dst_set = s->pending_dst[0] > 0;
memcpy(s->dst, s->pending_dst, sizeof(s->dst));
s->pending_dst_set = 0;
}
if (s->pending_opaque_set) {
memcpy(s->opaque, s->pending_opaque, sizeof(s->opaque));
s->pending_opaque_set = 0;
}
s->damage_buf = s->pending_damage_buf;
s->damage_local = s->pending_damage_local;
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
if (s->pending_attach) {
struct wl_resource *buffer = s->pending_buffer;
struct dmabuf_buffer *db = get_dmabuf(buffer);
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
uint8_t pixel[4];
@@ -1443,10 +1400,12 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
if (!buffer) g_pace.null_attaches++;
else if (!db) s->last_dmabuf = NULL;
wl_list_remove(&st->buffer_destroy.link);
wl_list_init(&st->buffer_destroy.link);
st->buffer = NULL;
st->attach = 0;
if (buffer) {
wl_list_remove(&s->pending_buffer_destroy.link);
wl_list_init(&s->pending_buffer_destroy.link);
}
s->pending_buffer = NULL;
s->pending_attach = 0;
surface_drop_idle(s);
buf_trace_attach(buffer);
@@ -1483,10 +1442,10 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
}
}
wl_list_insert_list(s->frames.prev, &st->frames);
wl_list_init(&st->frames);
wl_list_insert_list(s->feedback.prev, &st->feedback);
wl_list_init(&st->feedback);
wl_list_insert_list(s->frames.prev, &s->pending_frames);
wl_list_init(&s->pending_frames);
wl_list_insert_list(s->feedback.prev, &s->pending_feedback);
wl_list_init(&s->pending_feedback);
constraints_surface_commit(s);
droiddeck_color_commit(s->resource);
@@ -1496,186 +1455,6 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
}
schedule_render();
}
#define COMMIT_WAIT_LIMIT_MS 1000
static struct surface *g_zero_copy_shown, *g_unwaited;
static int state_unfinished_fd(const struct surface *s, const struct surface_state *st, int *unwaited) {
struct dmabuf_buffer *db = st->attach ? get_dmabuf(st->buffer) : NULL;
int fd = -1;
*unwaited = 0;
for (int i = 0; db && fd < 0 && i < db->n_planes; i++) {
if (db->fd[i] < 0) continue;
struct pollfd p = {.fd = db->fd[i], .events = POLLIN};
int r;
do { r = poll(&p, 1, 0); } while (r < 0 && errno == EINTR);
if (r == 0) fd = db->fd[i];
}
if (fd >= 0 && s == g_zero_copy_shown && ahb_swapchain_has_ahb(db)) {
*unwaited = 1;
return -1;
}
return fd;
}
static void settle_unwaited(void) {
struct surface *s = g_unwaited;
if (!s) return;
g_unwaited = NULL;
struct dmabuf_buffer *db = s->dmabuf_buf;
const int64_t deadline = now_ns() + 100000000LL;
for (int i = 0; db && i < db->n_planes; i++) {
if (db->fd[i] < 0) continue;
struct pollfd p = {.fd = db->fd[i], .events = POLLIN};
for (;;) {
const int64_t left = deadline - now_ns();
const int r = poll(&p, 1, left > 0 ? (int)((left + 999999) / 1000000) : 0);
if (r >= 0 || errno != EINTR || left <= 0) break;
}
}
}
static void surface_state_discard(struct surface_state *st) {
struct wl_resource *cb, *tmp;
wl_list_remove(&st->buffer_destroy.link);
wl_resource_for_each_safe(cb, tmp, &st->frames) wl_resource_destroy(cb);
feedback_discard_all(&st->feedback);
free(st);
}
static void surface_state_merge(struct surface_state *older, struct surface_state *newer) {
if (older->attach && !newer->attach) {
newer->attach = 1;
newer->buffer = older->buffer;
wl_list_remove(&older->buffer_destroy.link);
wl_list_init(&older->buffer_destroy.link);
if (newer->buffer) {
newer->buffer_destroy.notify = on_state_buffer_destroyed;
wl_resource_add_destroy_listener(newer->buffer, &newer->buffer_destroy);
}
wl_list_insert_list(&newer->feedback, &older->feedback);
wl_list_init(&older->feedback);
} else if (older->attach) {
if (older->buffer && older->buffer != newer->buffer) send_buffer_release(older->buffer);
g_pace.replaced += feedback_discard_all(&older->feedback);
}
if (older->src_set && !newer->src_set) {
newer->src_set = 1;
memcpy(newer->src, older->src, sizeof(newer->src));
}
if (older->dst_set && !newer->dst_set) {
newer->dst_set = 1;
memcpy(newer->dst, older->dst, sizeof(newer->dst));
}
if (older->opaque_set && !newer->opaque_set) {
newer->opaque_set = 1;
memcpy(newer->opaque, older->opaque, sizeof(newer->opaque));
}
for (int i = 0; i < older->damage_buf.n; i++)
note_damage(&newer->damage_buf, older->damage_buf.r[i][0], older->damage_buf.r[i][1],
older->damage_buf.r[i][2], older->damage_buf.r[i][3]);
for (int i = 0; i < older->damage_local.n; i++)
note_damage(&newer->damage_local, older->damage_local.r[i][0], older->damage_local.r[i][1],
older->damage_local.r[i][2], older->damage_local.r[i][3]);
wl_list_insert_list(&newer->frames, &older->frames);
wl_list_init(&older->frames);
surface_state_discard(older);
}
static void surface_wait_stop(struct surface *s) {
if (s->waiting_source) wl_event_source_remove(s->waiting_source);
if (s->waiting_timer) wl_event_source_remove(s->waiting_timer);
if (s->waiting_fd >= 0) close(s->waiting_fd);
s->waiting_source = s->waiting_timer = NULL;
s->waiting_fd = -1;
}
static void surface_wait_end(struct surface *s, int over_limit) {
struct surface_state *st = s->waiting;
if (!st) return;
surface_wait_stop(s);
s->waiting = NULL;
const int64_t waited = now_ns() - s->waiting_since_ns;
g_perf.commit_waits++;
g_perf.commit_wait_ns += waited;
if (waited > g_perf.commit_wait_max_ns) g_perf.commit_wait_max_ns = waited;
if (over_limit) g_perf.commit_wait_limits++;
if (st->attach && g_unwaited == s) g_unwaited = NULL;
surface_state_apply(s, st);
free(st);
}
static int on_commit_ready(int fd, uint32_t mask, void *data) {
surface_wait_end(data, 0);
return 0;
}
static int on_commit_wait_limit(void *data) {
static int said;
if (!said) {
said = 1;
droiddeck_log("compositor", "a client's GPU writes ran past %d ms; its frame is shown as it is", COMMIT_WAIT_LIMIT_MS);
}
surface_wait_end(data, 1);
return 0;
}
static int surface_wait_start(struct surface *s, int fd, int timeout_ms) {
struct wl_event_loop *loop = wl_display_get_event_loop(g_display);
s->waiting_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
if (s->waiting_fd >= 0) {
s->waiting_source = wl_event_loop_add_fd(loop, s->waiting_fd, WL_EVENT_READABLE, on_commit_ready, s);
s->waiting_timer = wl_event_loop_add_timer(loop, on_commit_wait_limit, s);
}
if (!s->waiting_source || !s->waiting_timer ||
wl_event_source_timer_update(s->waiting_timer, timeout_ms) != 0) {
surface_wait_stop(s);
return -1;
}
return 0;
}
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
if (s->xdg_toplevel && !s->toplevel_committed) {
s->toplevel_committed = 1;
send_toplevel_configure(s);
}
struct surface_state *st = calloc(1, sizeof(*st));
if (!st) {
struct surface_state now;
surface_state_take(s, &now);
surface_state_apply(s, &now);
return;
}
surface_state_take(s, st);
const int was_waiting = s->waiting != NULL;
if (was_waiting) {
surface_wait_stop(s);
surface_state_merge(s->waiting, st);
s->waiting = NULL;
}
int unwaited;
const int fd = state_unfinished_fd(s, st, &unwaited);
if (!was_waiting) s->waiting_since_ns = now_ns();
const int64_t left_ms = COMMIT_WAIT_LIMIT_MS - (now_ns() - s->waiting_since_ns) / 1000000;
if (fd >= 0 && left_ms > 0 && surface_wait_start(s, fd, (int)left_ms) == 0) {
s->waiting = st;
return;
}
const int attaches = st->attach;
if (was_waiting) {
s->waiting = st;
surface_wait_end(s, fd >= 0 && left_ms <= 0);
} else {
surface_state_apply(s, st);
free(st);
}
if (unwaited) g_unwaited = s;
else if (attaches && g_unwaited == s) g_unwaited = NULL;
}
static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {}
static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {}
static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r,
@@ -1737,13 +1516,6 @@ static void surface_resource_destroy(struct wl_resource *r) {
child->parent = NULL;
}
if (s->pending_buffer) wl_list_remove(&s->pending_buffer_destroy.link);
if (s->waiting) {
surface_wait_stop(s);
surface_state_discard(s->waiting);
s->waiting = NULL;
}
if (g_zero_copy_shown == s) g_zero_copy_shown = NULL;
if (g_unwaited == s) g_unwaited = NULL;
pending_releases_forget_surface(s);
drop_dmabuf(s, 0);
ahb_swapchain_surface_gone(s);
@@ -1807,7 +1579,6 @@ static void compositor_create_surface(struct wl_client *c, struct wl_resource *r
wl_list_init(&s->child_link);
wl_list_init(&s->toplevel_link);
wl_list_init(&s->pending_buffer_destroy.link);
s->waiting_fd = -1;
wl_list_init(&s->idle_buffer_destroy.link);
wl_list_insert(&g_surfaces, &s->link);
wl_resource_set_implementation(s->resource, &surface_impl, s, surface_resource_destroy);
@@ -2731,13 +2502,7 @@ static int64_t scene_next_due(int64_t now, int64_t due, int limit) {
static void render_scene(void) {
g_scene_due_ns = scene_next_due(now_ns(), g_scene_due_ns, g_fps_limit);
if (atomic_load(&g_stream_on)) {
g_dirty_since_ns = 0;
g_zero_copy_shown = NULL;
settle_unwaited();
render_stream();
return;
}
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
struct draw_list dl = {0};
struct surface *s;
int w, h;
@@ -2811,8 +2576,6 @@ static void render_scene(void) {
} else {
cursor_hdr_said = 0;
}
g_zero_copy_shown = NULL;
if (hdr_route == 1 || hdr_route == 2) settle_unwaited();
if (hdr_route == 1) {
static int fell_back;
vkp_apply_window_request();
@@ -2846,7 +2609,6 @@ static void render_scene(void) {
}
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
!ahb_only) {
settle_unwaited();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen;
@@ -2896,7 +2658,6 @@ static void render_scene(void) {
vkp_apply_window_request();
int r = -1;
const int fg_pass = framegen && fx_on && li >= 0;
if (framegen && li >= 0) settle_unwaited();
const int generated = (framegen && li >= 0)
? sc_layer_present_generated(&dl.d[li], 1, NULL, w, h, fg_pass,
ls ? droiddeck_surface_color(ls) : NULL) : 0;
@@ -2910,8 +2671,6 @@ static void render_scene(void) {
r = generated >= 0 ? 0 : -1;
else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf))
r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld);
if (r == 0 && !fg_pass) g_zero_copy_shown = ls;
else settle_unwaited();
if (!fg_pass && generated >= 0 && r != 0 && li >= 0)
r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h)
: sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL);
@@ -2922,7 +2681,6 @@ static void render_scene(void) {
ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1;
if (ov <= 0) sc_layer_hide_overlay();
if (ov < 0) {
settle_unwaited();
sc_layer_hide();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
copy = 1;
@@ -2932,14 +2690,12 @@ static void render_scene(void) {
g_scene_queues = sc_layer_queues();
}
} else {
settle_unwaited();
sc_layer_hide();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
copy = 1;
hdr_copy = "its display layer was unavailable this frame";
}
} else {
settle_unwaited();
sc_layer_hide();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
copy = 1;
@@ -4588,12 +4344,11 @@ static int on_stats_timer(void *data) {
unsigned aimed_next, aimed_later, aimed_even;
sc_layer_aim_take(&aimed_next, &aimed_later, &aimed_even);
#define PERF_MS(sum, n) ((n) ? (double)(sum) / 1e6 / (double)(n) : 0.0)
if (g_perf.scenes || vp.presents || g_perf.releases || drops || g_perf.commit_waits)
if (g_perf.scenes || vp.presents || g_perf.releases || drops)
droiddeck_log("perf", "last 10 s: %u ticks, %u scenes, %u on screen (copy %u, zero-copy %u, layer copy %u) | "
"render_scene %.2f/%.2f ms | base %u black kept, %u presented | acquire %.2f/%.2f ms | "
"present %.2f/%.2f ms (%u) | fence wait %.2f/%.2f ms (%u, %u GPU release waits) | "
"release %.2f/%.2f ms (%u, %u held) | commits held for client writes %.2f/%.2f ms (%u, %u past the limit) | "
"%u pool drops | layer frames timed for the next refresh %u, "
"release %.2f/%.2f ms (%u, %u held) | %u pool drops | layer frames timed for the next refresh %u, "
"the one after %u, held to an even step %u",
g_perf.ticks, g_perf.scenes, g_stat_frames, g_perf.copy_scenes, zero_copy, layer_frames,
PERF_MS(g_perf.scene_ns, g_perf.scenes), (double)g_perf.scene_max_ns / 1e6,
@@ -4602,9 +4357,7 @@ static int on_stats_timer(void *data) {
PERF_MS(vp.present_ns, vp.presents), (double)vp.present_max_ns / 1e6, vp.presents,
PERF_MS(vp.wait_ns, vp.waits), (double)vp.wait_max_ns / 1e6, vp.waits, vp.gpu_release_waits,
PERF_MS(g_perf.release_ns, g_perf.releases), (double)g_perf.release_max_ns / 1e6,
g_perf.releases, g_perf.releases_held,
PERF_MS(g_perf.commit_wait_ns, g_perf.commit_waits), (double)g_perf.commit_wait_max_ns / 1e6,
g_perf.commit_waits, g_perf.commit_wait_limits, drops, aimed_next, aimed_later, aimed_even);
g_perf.releases, g_perf.releases_held, drops, aimed_next, aimed_later, aimed_even);
#undef PERF_MS
memset(&g_perf, 0, sizeof(g_perf));
}
@@ -175,6 +175,9 @@ internal class AddonPack(
val ROCKSTAR = AddonPack("rockstar", BuildConfig.PACK_ROCKSTAR_SHA256, BuildConfig.PACK_ROCKSTAR_SIZE,
listOf("Launcher32.exe", "Launcher64.exe"))
val DIRT = AddonPack("dirt", BuildConfig.PACK_DIRT_SHA256, BuildConfig.PACK_DIRT_SIZE, listOf("ws2_32.dll"))
/** The in-game upscaler's bridge DLLs (tools/upscale/bridges), staged by UpscaleComponent. */
val UPSCALE = AddonPack("upscale", BuildConfig.PACK_UPSCALE_SHA256, BuildConfig.PACK_UPSCALE_SIZE,
listOf("bridges/x86_64-windows/libxess.dll", "bridges/x86_64-windows/nvngx.dll"))
val EPIC = AddonPack("epic", BuildConfig.PACK_EPIC_SHA256, BuildConfig.PACK_EPIC_SIZE, listOf("EpicGamesLauncher.exe"))
}
}
@@ -61,19 +61,7 @@ object GameEnvironment {
}
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else knownGames[scope].orEmpty() + config.games[scope].orEmpty()
/**
* What some Steam games need here whatever the shared settings say; the game's own settings still win.
* GTA III dies at 0042A703 when a new game starts with FEX's reduced x87 precision, as the Rockstar store copy does.
*/
val knownGames: Map<String, Map<String, String?>> = mapOf(
"12100" to mapOf("FEX_X87REDUCEDPRECISION" to "0"),
)
/** [config] with [knownGames] folded under each game's own settings, for the guest to read. */
fun withKnownGames(config: Config): Config =
config.copy(games = config.games + knownGames.mapValues { (scope, known) -> known + config.games[scope].orEmpty() })
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
fun hasOverride(config: Config, scope: String, name: String): Boolean =
scope.isNotEmpty() && config.entries(scope).containsKey(name)
@@ -90,7 +78,7 @@ object GameEnvironment {
val entries = config.games[scope].orEmpty()
if (FexPreset.environmentKeys.none(entries::containsKey)) return null
return FexPreset.all.firstOrNull { preset ->
val expected = presetFor(scope, preset.id)
val expected = FexPreset.environment(preset.id)
FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] }
}?.id ?: CUSTOM_FEX_PRESET
}
@@ -100,16 +88,12 @@ object GameEnvironment {
require(preset == null || FexPreset.all.any { it.id == preset })
val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap()
if (preset != null) {
val values = presetFor(scope, preset)
val values = FexPreset.environment(preset)
FexPreset.environmentKeys.forEach { key -> entries[key] = values[key] }
}
return config.withEntries(scope, entries)
}
/** A FEX preset as a game gets it: picking one never undoes a fix the game is known to need. */
private fun presetFor(scope: String, preset: String): Map<String, String?> =
FexPreset.environment(preset) + knownGames[scope].orEmpty().filterKeys { it in FexPreset.environmentKeys }
const val CUSTOM_FEX_PRESET = "__custom__"
val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER)
@@ -0,0 +1,132 @@
package com.droiddeck.launcher.core
/**
* The in-game upscaler (tools/upscale): bridge DLLs stand in for a game's own DLSS / FidelityFX / FSR 2/3 /
* XeSS DLLs and hand each frame to the VK_LAYER_DROIDDECK_upscale layer, which runs FSR 4 (GPU or Hexagon NPU),
* XeSS 3 DP4a or a basic temporal upscaler in its place. Ported from Winlator-NeuralScale
* (michaelisomer-cyber, GPL-3.0, a fork of StevenMXZ/Winlator-Ludashi).
*
* Per game it is a few entries of the game environment; droiddeck-game-env turns them into the DLL overrides,
* the bridge folder, the layer switch and the files the layer reads.
*/
object GameUpscaler {
const val MODE = "DROIDDECK_UPSCALE_MODE"
const val ENGINE = "DROIDDECK_UPSCALE_ENGINE"
const val SHARPNESS = "DROIDDECK_UPSCALE_SHARPNESS"
const val NPU_SYNC = "DROIDDECK_UPSCALE_NPU_SYNC"
const val SIGFIX = "DROIDDECK_UPSCALE_SIGFIX"
val keys = listOf(MODE, ENGINE, SHARPNESS, NPU_SYNC, SIGFIX)
/** Which of the game's upscalers are replaced, and what GPU the game is shown. */
enum class Mode(val id: String) {
/** FidelityFX (FSR 4 API), FSR 2/3 and XeSS games; the real GPU is reported. */
FSR_XESS("fsr"),
/** DLSS games: also nvngx + nvapi64, and the game sees an RTX 2060. */
DLSS("dlss"),
/** Games whose FSR 4 path wants an RDNA 4 card: the game sees a Radeon RX 9070 XT, shader model 6.8. */
NATIVE_FSR4("native");
companion object {
fun byId(id: String?): Mode? = entries.firstOrNull { it.id == id?.trim()?.lowercase() }
}
}
/** What runs in the game's upscaler's place. Ids are the layer's backend names (fsr4_layer.c parse_backend_str). */
enum class Engine(val id: String, val npu: Boolean) {
FSR4_LITE_GPU("fsr4_1_lite_gpu", false),
FSR4_FULL_GPU("fsr4_1_full_gpu", false),
XESS("xess3_gpu", false),
BASIC("fsr3_gpu", false),
FSR4_NPU("fsr4_0_npu", true),
FSR4_LITE_NPU("fsr4_1_lite_npu", true);
companion object {
fun byId(id: String?): Engine? = entries.firstOrNull { it.id == id?.trim()?.lowercase() }
}
}
val DEFAULT_ENGINE = Engine.FSR4_LITE_GPU
const val DEFAULT_SHARPNESS = 55
val sharpnessSteps = listOf(0, 25, 40, 55, 70, 85, 100)
data class Choice(
val mode: Mode,
val engine: Engine = DEFAULT_ENGINE,
val sharpness: Int = DEFAULT_SHARPNESS,
val npuSync: Boolean = false,
val signatureFix: Boolean = false,
)
fun choice(config: GameEnvironment.Config, scope: String): Choice? {
if (scope.isEmpty()) return null
val entries = config.games[scope].orEmpty()
val mode = Mode.byId(entries[MODE]) ?: return null
return Choice(
mode = mode,
engine = Engine.byId(entries[ENGINE]) ?: DEFAULT_ENGINE,
sharpness = entries[SHARPNESS]?.toIntOrNull()?.coerceIn(0, 100) ?: DEFAULT_SHARPNESS,
npuSync = entries[NPU_SYNC] == "1",
signatureFix = entries[SIGFIX] == "1",
)
}
fun entries(choice: Choice?): Map<String, String> = if (choice == null) emptyMap() else buildMap {
put(MODE, choice.mode.id)
put(ENGINE, choice.engine.id)
put(SHARPNESS, choice.sharpness.coerceIn(0, 100).toString())
if (choice.npuSync) put(NPU_SYNC, "1")
if (choice.signatureFix && choice.mode == Mode.DLSS) put(SIGFIX, "1")
}
fun withChoice(config: GameEnvironment.Config, scope: String, choice: Choice?): GameEnvironment.Config {
require(scope.isNotEmpty() && GameEnvironment.validScope(scope))
val kept = config.entries(scope).filterKeys { it !in keys }
return config.withEntries(scope, kept + entries(choice))
}
/** NPU engines on a device without a usable Hexagon NPU run the matching GPU engine instead. */
fun effectiveEngine(engine: Engine, npuAvailable: Boolean): Engine = when {
!engine.npu || npuAvailable -> engine
engine == Engine.FSR4_NPU -> Engine.FSR4_FULL_GPU
else -> Engine.FSR4_LITE_GPU
}
/** The control file the layer polls (fsr4_layer.c read_live_ctrl): backend, sharpness 0..1, NPU sync, on/off. */
fun controlText(engine: Engine, sharpness: Int, npuSync: Boolean, enabled: Boolean): String =
"enabled=${if (enabled) 1 else 0}\nbackend=${engine.id}\nsharpness=" +
String.format(java.util.Locale.ROOT, "%.2f", sharpness.coerceIn(0, 100) / 100f) +
"\nnpu_sync=${if (npuSync) 1 else 0}\n"
/** One status file the layer writes (fsr4_layer.c write_live_status): key=value lines. */
data class Status(
val active: Boolean,
val npu: Boolean,
val backendTag: String,
val render: String,
val output: String,
val gpuMs: Float,
val npuMs: Float,
val reason: String,
val timestampMs: Long,
)
fun parseStatus(text: String): Status? {
val values = text.lineSequence().mapNotNull { line ->
val eq = line.indexOf('=')
if (eq <= 0) null else line.substring(0, eq).trim() to line.substring(eq + 1).trim()
}.toMap()
if (values["layer"] != "1") return null
return Status(
active = values["active"] == "1",
npu = values["npu"] == "1",
backendTag = values["backend_tag"].orEmpty().ifEmpty { values["backend"].orEmpty() },
render = values["render"].orEmpty(),
output = values["output"].orEmpty(),
gpuMs = (values["gpu_us"]?.toLongOrNull() ?: 0L) / 1000f,
npuMs = (values["htp_us"]?.toLongOrNull() ?: 0L) / 1000f,
reason = values["reason"].orEmpty(),
timestampMs = values["ts_ms"]?.toLongOrNull() ?: 0L,
)
}
}
@@ -14,7 +14,7 @@ internal object DroidDeckHudConfig {
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1",
"showEngine" to "1", "showRenderer" to "1",
"showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1",
"showProton" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
"showProton" to "1", "showUpscale" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
)
@@ -287,6 +287,9 @@ class DroidDeckHudHost(context: Context) {
proton = protonName(pid) ?: proton
}
hud.setWineVersion(proton)
hud.setUpscale(com.droiddeck.launcher.session.UpscaleComponent.status(context)?.takeIf { it.active }?.let {
it.backendTag + " " + String.format(java.util.Locale.ROOT, "%.1fms", if (it.npu) it.npuMs else it.gpuMs)
})
hud.setPresentedFps(presentedFps())
}
@@ -74,12 +74,13 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
FULL to listOf(
"showFPS", "showFPSGraph", "showGpuModel", "showDisplay", "showHdr", "showGPULoad", "showGpuTemp",
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
"showPower", "showLatency", "showAvg", "showLow1", "showLow01", "showLow001",
"showPower", "showLatency", "showAvg", "showLow1", "showLow01", "showLow001", "showUpscale",
),
TILES to listOf(
"showFPS", "showFPSGraph", "showLatency", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
"showVram", "showRAM", "showEngine", "showDisplay", "showHdr", "showAvg", "showLow1",
"showLow01", "showLow001", "showGpuModel", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower",
"showUpscale",
),
PILL to listOf(
"showFPS", "showFPSGraph", "showGpuModel", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
@@ -114,6 +114,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private var gpuModel = ""
private var gpuSpoofName = ""
private var wineVersion = ""
private var upscaleText = ""
private var graphicsWrapper = ""
private var dxvkVersion = ""
private var vkd3dVersion = ""
@@ -277,6 +278,8 @@ class DroidDeckHudView(context: Context) : View(context) {
fun setEngineLabel(s: String?) { if ((s ?: "") != engineLabel) { engineLabel = s ?: ""; post { rebuildAndInvalidate() } } }
fun setGpuModel(s: String?) { if ((s ?: "") != gpuModel) { gpuModel = s ?: ""; post { rebuildAndInvalidate() } } }
fun setWineVersion(s: String?) { if ((s ?: "") != wineVersion) { wineVersion = s ?: ""; post { rebuildAndInvalidate() } } }
/** The in-game upscaler's backend and its time per frame (empty: not running). */
fun setUpscale(s: String?) { if ((s ?: "") != upscaleText) { upscaleText = s ?: ""; post { rebuildAndInvalidate() } } }
fun setResolution(s: String?) { resolution = s ?: "" }
@@ -772,6 +775,7 @@ class DroidDeckHudView(context: Context) : View(context) {
"showHdr" -> "HDR" to colHdr
"showResolution" -> "RES" to colDim
"showProton" -> "PROTON" to colVram
"showUpscale" -> "UPSCALE" to colFps
"showSession" -> "TIME" to colDim
else -> key.removePrefix("show") to colDim
}
@@ -809,6 +813,7 @@ class DroidDeckHudView(context: Context) : View(context) {
"showHdr" -> if (showHdrLine()) hdrValue(valuePx) else listOf(Span("off", colDim, valuePx))
"showResolution" -> listOf(Span(resolutionString(), colValue, valuePx))
"showProton" -> listOf(Span(wineVersion.ifBlank { "—" }, colVram, valuePx))
"showUpscale" -> listOf(Span(upscaleText.ifBlank { "—" }, colValue, valuePx))
"showSession" -> listOf(Span(elapsedString(), colValue, valuePx))
else -> listOf(Span("—", colDim, valuePx))
}
@@ -98,6 +98,13 @@ object GameEnvironmentStore {
return config
}
@Synchronized
fun setGameUpscaler(context: Context, scope: String, choice: com.droiddeck.launcher.core.GameUpscaler.Choice?): GameEnvironment.Config {
val config = com.droiddeck.launcher.core.GameUpscaler.withChoice(read(context), scope, choice)
save(context, config)
return config
}
@Synchronized
fun setDefault(context: Context, scope: String, name: String, value: String): Boolean {
val config = read(context)
@@ -114,7 +121,7 @@ object GameEnvironmentStore {
) {
publishGameCores(context)
val stored = config ?: read(context)
val resolved = GameEnvironment.withKnownGames(stored).copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
val resolved = stored.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
val json = encode(resolved)
val dxvk = TextureFiltering.dxvkOptions(
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
@@ -35,7 +35,6 @@ object SessionFiles {
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
"usr/share/applications/droiddeck-return-gaming.desktop" to "usr/share/applications/droiddeck-return-gaming.desktop",
"etc/xdg/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc",
)
@@ -251,6 +250,11 @@ object SessionFiles {
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_gpu_load.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_gpu_load.json",
)
// The in-game upscaler's layer for PRoot games (UpscaleComponent; off unless DROIDDECK_UPSCALE=1).
val upscaleLayer = listOf(
"usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so" to "usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so",
"usr/local/lib/droiddeck-upscale-layer/VK_LAYER_DROIDDECK_upscale.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_upscale.json",
)
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
listOf("libddsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
@@ -273,7 +277,7 @@ object SessionFiles {
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + upscaleLayer + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
}
@@ -1084,6 +1084,8 @@ class SessionService : Service() {
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
guest.add("MESA_DISK_CACHE_DATABASE=1")
guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this)))
guest.addAll(UpscaleComponent.guestEnv(this))
UpscaleComponent.prepare(this)
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
if (SessionState.mode == MODE_STEAM) guest.add("DD_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
SessionPaths.current()?.let { SessionArtifacts.markRpcs3Log(it, LinuxRuntime.rootDir(this)) }
@@ -0,0 +1,397 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Environment
import android.util.Log
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.GameUpscaler
import com.droiddeck.launcher.gpu.SocNames
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.security.MessageDigest
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
/**
* The in-game upscaler's files on the device (see [GameUpscaler]):
* - the bridge DLLs, built from tools/upscale/bridges, come in the "upscale" add-on pack;
* - the Vulkan layer is in the APK (bionic games) and in the Linux runtime (PRoot games);
* - the parts with no source to build from (AMD's FSR 4 SPIR-V and weights, Intel's XeSS 3 runtime, Qualcomm's
* QNN libraries for the Hexagon NPU) are fetched from Winlator-NeuralScale at a pinned commit and checked against
* the SHA-256 listed here, or copied from a folder of the same files under Download.
* Everything lands under [GUEST_ROOT] in the rootfs, where both PRoot and bionic games read it.
*/
object UpscaleComponent {
private const val TAG = "UpscaleComponent"
const val UPSTREAM = "michaelisomer-cyber/Winlator-NeuralScale"
const val UPSTREAM_COMMIT = "a0ab6b0f770e1a6786b4e68def46b4edb8baafd0"
const val GUEST_ROOT = "/usr/local/lib/droiddeck-upscale"
const val GUEST_RUN = "/run/droiddeck-hud/upscale"
private const val LOCAL_COPY = "droiddeck-upscale"
private const val LAYER_LIBRARY = "libVkLayer_droiddeck_upscale.so"
private const val BRIDGES_STAMP = ".pack"
enum class Group { CORE, XESS, NPU }
data class DataFile(val group: Group, val relative: String, val upstreamPath: String, val sha256: String, val size: Long) {
val url get() = "https://raw.githubusercontent.com/$UPSTREAM/$UPSTREAM_COMMIT/$upstreamPath"
}
val FILES = listOf(
DataFile(Group.CORE, "fsr4/fsr3_accumulate.spv", "app/src/main/assets/fsr4/fsr3_accumulate.spv", "06334f81fee9afff829085612bbedee4fae06a1d7cca62c0ce62fc4c49e11c85", 12168L),
DataFile(Group.CORE, "fsr4/fsr3_prepare.spv", "app/src/main/assets/fsr4/fsr3_prepare.spv", "a9bf26007c37daf775036558cf00af70e69d12c0b2e0d0c12b0372b085149c78", 8308L),
DataFile(Group.CORE, "fsr4/fsr3_rcas.spv", "app/src/main/assets/fsr4/fsr3_rcas.spv", "80d54b9a3b29626fee7c57ff24f5e5e0bb288c40375462bcd4f3a1e26f30aac3", 6312L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/initializers.bin", "app/src/main/assets/fsr4/fsr411_full/performance/initializers.bin", "a54e552ff69a3f7199861417f7ae461d1f67f636ab532c6ec9d8ea5d2963735a", 131072L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-00.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-00.spv", "d6a01100a56327713d2f7c1a768e41f8a31f2cadce5f37b7dac81630722ff5a2", 33116L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-01.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-01.spv", "759396dc2eccd731bebac13e8818568c8cc410150d24ed4cc01aa8b5ea873fbb", 58172L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-02.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-02.spv", "bdabc7c28f18c31ac8574856a386a268ae4d866f68a65e72b59bf3bad2235132", 3208L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-03.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-03.spv", "bcb4d1d01e33114c68bb13059577c280bb05b5a3af7218fdbc38e99883e0632d", 108840L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-04.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-04.spv", "d85b605d066d89178994ba835b6c3b267ed771de530117a5b9e6103d49e866e7", 3244L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-05.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-05.spv", "e44f0ccd272e4a85ad38894a38db7adae019d18660b166e6c28e82b328d7cc84", 109048L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-06.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-06.spv", "df469b6481234bf7b964a7c0ecf8a5829d84d1bc34fdb7c72e87014f82e31326", 3208L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-07.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-07.spv", "a873b766b2b8923aeb7d325a61cbea251cbac6450e708a23a7714c553ce577ff", 132572L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-08.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-08.spv", "c4aba5b9cd11100308aa2e3d8a4d39e66713c46c35edbe6496552764459a2228", 3580L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-09.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-09.spv", "d757fd28efbd09259f82918de5d3765784933d5b26eea56babe45fd6fefc5cfa", 190032L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-10.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-10.spv", "295873b3ecbd9db40cc4c50ecf15a72964d5846b96642d2e4743a9333382b557", 3580L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-11.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-11.spv", "73e05c6727408d5b1f472112c5d68060e9db9aaf918e892055e6619d5f0e4edc", 190032L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-12.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-12.spv", "007315c42072370919ac393b63a04a0ac025a802f927b490a6749bd6034c15fd", 3596L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-13.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-13.spv", "020929f63d8a70f90bd628a92c50b4049db89155d5e062bf03eb1e8cb8ee7c60", 497604L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-14.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-14.spv", "f26dc72bbe9ccc70e2cc2dc1f4b2a868baf3c2e470b4e76994f98c50674ec3d8", 4268L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-15.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-15.spv", "9487c52cec7e259f4cb212335e84db43c52902b4e3243afcd34305b95ad1b83b", 79128L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-16.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-16.spv", "55c48a8b7627343d996f7818ee6055e143d3b956b8f65911d6b6c337bd8f72ca", 4268L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-17.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-17.spv", "810636645f52d5b8c019206deb046e954af730fc13edaa6a00ebf66e686c3ac0", 79128L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-18.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-18.spv", "a3d130ad8fc6438766f3cdeb7e062d03291a25f6a5e439f71b905795cfc856ec", 4268L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-19.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-19.spv", "e1b576f7e8cedc46615a90f5d2026a43a525a2e43cfc66b62def8e700f55688a", 84476L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-20.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-20.spv", "70c2b7b4e55d665591b2dca3efddb6e99e6d393020722cec635fb8df3bd81bf1", 3596L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-21.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-21.spv", "bb1798794d6c8b0ad3760059bf36e2c396594226c0835202040a4a515a8beb01", 189952L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-22.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-22.spv", "b0545fc4c1886fa0a6252029eb6e3a2f999974bc0bc89539c8d6005c184d8a6f", 3580L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-23.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-23.spv", "e9aee05cec78f0659fa570bfc0f495a51d00d2bc80c4e99cde4106a3df51c35e", 61308L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-24.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-24.spv", "1e93b681a9264afc07f0ab41086474b3afaa2ff8d37b5b75c9ceae005e21e558", 3260L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-25.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-25.spv", "6292dd68a4da9370c7dabb3b192fe6958b1a12daffd92b7fa80ed6fe231e1e5d", 109064L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-26.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-26.spv", "abc2426ff739d25cba4d271cad08ec9f25056ae197a9727b7b7e72467ba49d28", 3224L),
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-27.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-27.spv", "fa5fc1de4625915c25a637b091f26f32c398f4985a14392a48505cfac111aaea", 125196L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/initializers.bin", "app/src/main/assets/fsr4/fsr411_full/quality/initializers.bin", "a54e552ff69a3f7199861417f7ae461d1f67f636ab532c6ec9d8ea5d2963735a", 131072L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-00.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-00.spv", "d6a01100a56327713d2f7c1a768e41f8a31f2cadce5f37b7dac81630722ff5a2", 33116L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-01.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-01.spv", "759396dc2eccd731bebac13e8818568c8cc410150d24ed4cc01aa8b5ea873fbb", 58172L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-02.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-02.spv", "bdabc7c28f18c31ac8574856a386a268ae4d866f68a65e72b59bf3bad2235132", 3208L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-03.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-03.spv", "bcb4d1d01e33114c68bb13059577c280bb05b5a3af7218fdbc38e99883e0632d", 108840L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-04.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-04.spv", "d85b605d066d89178994ba835b6c3b267ed771de530117a5b9e6103d49e866e7", 3244L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-05.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-05.spv", "e44f0ccd272e4a85ad38894a38db7adae019d18660b166e6c28e82b328d7cc84", 109048L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-06.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-06.spv", "df469b6481234bf7b964a7c0ecf8a5829d84d1bc34fdb7c72e87014f82e31326", 3208L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-07.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-07.spv", "a873b766b2b8923aeb7d325a61cbea251cbac6450e708a23a7714c553ce577ff", 132572L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-08.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-08.spv", "c4aba5b9cd11100308aa2e3d8a4d39e66713c46c35edbe6496552764459a2228", 3580L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-09.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-09.spv", "d757fd28efbd09259f82918de5d3765784933d5b26eea56babe45fd6fefc5cfa", 190032L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-10.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-10.spv", "295873b3ecbd9db40cc4c50ecf15a72964d5846b96642d2e4743a9333382b557", 3580L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-11.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-11.spv", "73e05c6727408d5b1f472112c5d68060e9db9aaf918e892055e6619d5f0e4edc", 190032L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-12.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-12.spv", "007315c42072370919ac393b63a04a0ac025a802f927b490a6749bd6034c15fd", 3596L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-13.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-13.spv", "020929f63d8a70f90bd628a92c50b4049db89155d5e062bf03eb1e8cb8ee7c60", 497604L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-14.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-14.spv", "f26dc72bbe9ccc70e2cc2dc1f4b2a868baf3c2e470b4e76994f98c50674ec3d8", 4268L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-15.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-15.spv", "9487c52cec7e259f4cb212335e84db43c52902b4e3243afcd34305b95ad1b83b", 79128L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-16.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-16.spv", "55c48a8b7627343d996f7818ee6055e143d3b956b8f65911d6b6c337bd8f72ca", 4268L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-17.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-17.spv", "810636645f52d5b8c019206deb046e954af730fc13edaa6a00ebf66e686c3ac0", 79128L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-18.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-18.spv", "a3d130ad8fc6438766f3cdeb7e062d03291a25f6a5e439f71b905795cfc856ec", 4268L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-19.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-19.spv", "e1b576f7e8cedc46615a90f5d2026a43a525a2e43cfc66b62def8e700f55688a", 84476L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-20.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-20.spv", "70c2b7b4e55d665591b2dca3efddb6e99e6d393020722cec635fb8df3bd81bf1", 3596L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-21.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-21.spv", "bb1798794d6c8b0ad3760059bf36e2c396594226c0835202040a4a515a8beb01", 189952L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-22.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-22.spv", "b0545fc4c1886fa0a6252029eb6e3a2f999974bc0bc89539c8d6005c184d8a6f", 3580L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-23.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-23.spv", "e9aee05cec78f0659fa570bfc0f495a51d00d2bc80c4e99cde4106a3df51c35e", 61308L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-24.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-24.spv", "1e93b681a9264afc07f0ab41086474b3afaa2ff8d37b5b75c9ceae005e21e558", 3260L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-25.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-25.spv", "6292dd68a4da9370c7dabb3b192fe6958b1a12daffd92b7fa80ed6fe231e1e5d", 109064L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-26.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-26.spv", "abc2426ff739d25cba4d271cad08ec9f25056ae197a9727b7b7e72467ba49d28", 3224L),
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-27.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-27.spv", "fa5fc1de4625915c25a637b091f26f32c398f4985a14392a48505cfac111aaea", 125196L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0000.spv", "app/src/main/assets/fsr4/fsr412_lite/0000.spv", "2ec08c00ba47d5812078073c68622101158762b2e885ae965afee39596243840", 97808L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0001.spv", "app/src/main/assets/fsr4/fsr412_lite/0001.spv", "71c2571ccc5ad447a0d41da49472aaf1c5a2b19dcfe3f871dca53b8c42cc53ed", 3456L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0002.spv", "app/src/main/assets/fsr4/fsr412_lite/0002.spv", "5b07b9b4ea0597811e069d684929ce0f74a0ab111665c83f5fdda97ef68b1a34", 120964L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0003.spv", "app/src/main/assets/fsr4/fsr412_lite/0003.spv", "6dd4ceef841a8aedf2e3222e23ef1b7a83788ff5eed3a4baf02cce2d9bd334c3", 3492L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0004.spv", "app/src/main/assets/fsr4/fsr412_lite/0004.spv", "61c63223e337584361af1ab8f28cc1bd3a9b1713608985dcb41d9255c734d1b1", 3928L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0005.spv", "app/src/main/assets/fsr4/fsr412_lite/0005.spv", "2cb371b67efc07da60d6c30a9fc4239d4d194306dbf4fb7bd90f82039968a8b7", 201880L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0006.spv", "app/src/main/assets/fsr4/fsr412_lite/0006.spv", "96aab40505a5fa1992cd02d9cd32b6ee799858e896b6a357a2cce09fd58f7c23", 3892L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0007.spv", "app/src/main/assets/fsr4/fsr412_lite/0007.spv", "20ec164ffc3f6269bc4f50e53825503188e157715989ae1841a8f485999d0a30", 279304L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0008.spv", "app/src/main/assets/fsr4/fsr412_lite/0008.spv", "a2c57206f1f8b79366b42497de16533a3e679d43bed97eee4fbaf695ce104b7f", 3508L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0009.spv", "app/src/main/assets/fsr4/fsr412_lite/0009.spv", "35453061b2637f1e4837d2dd1026b1b262ceabbda6911411829d716169220c60", 104052L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0010.spv", "app/src/main/assets/fsr4/fsr412_lite/0010.spv", "a60c0492e22ae608ba9b7e9d479db03ad198a8d9523edb7b65cc0eaef5829a29", 28988L),
DataFile(Group.CORE, "fsr4/fsr412_lite/0013.spv", "app/src/main/assets/fsr4/fsr412_lite/0013.spv", "f34905ea5d71368dd3e85be79424a94f68dfdf866e38d33bc9954701ebd0e64d", 57232L),
DataFile(Group.CORE, "fsr4/fsr412_lite/fsr412_lite_i8.wpack", "app/src/main/assets/fsr4/fsr412_lite/fsr412_lite_i8.wpack", "7de72e7bdcade967a4a64d81e4d625384ee8e0575c355dca432dc72db23d7adc", 27104L),
DataFile(Group.CORE, "fsr4/fsr412_lite/lite_npu_pack.spv", "app/src/main/assets/fsr4/fsr412_lite/lite_npu_pack.spv", "1b369e959ded731f4cfff895c9e7e5d045469742fb3a6db6a6fd3f039a076404", 1412L),
DataFile(Group.CORE, "fsr4/fsr412_lite/lite_npu_unpack.spv", "app/src/main/assets/fsr4/fsr412_lite/lite_npu_unpack.spv", "e2de130c7024667b57b0cbf12c3a62f6860b5954c0e03add6d44c5794034982a", 1712L),
DataFile(Group.CORE, "fsr4/fsr412_lite/weights.bin", "app/src/main/assets/fsr4/fsr412_lite/weights.bin", "4b9898da719dc2dca5dc45fd71dec5f80bdb9886a580fe3038af59efe637d55e", 27392L),
DataFile(Group.CORE, "fsr4/fsr4_builtin_post_a.spv", "app/src/main/assets/fsr4/fsr4_builtin_post_a.spv", "aca1e6ae4e9a303b8ce8c6b066266ea6ef64857bd5f6a97ac9ab818809fb5e24", 7764L),
DataFile(Group.CORE, "fsr4/fsr4_builtin_post_b.spv", "app/src/main/assets/fsr4/fsr4_builtin_post_b.spv", "898cc07bc0b175778264ec2dc1ef8df5b3a1ed463befaaf08e5f5686235d5963", 9076L),
DataFile(Group.CORE, "fsr4/fsr4_builtin_pre.spv", "app/src/main/assets/fsr4/fsr4_builtin_pre.spv", "314273b20839952b0829b8aa51bb3d5a23a5c11d620c239f99dd2f9c41b30458", 45340L),
DataFile(Group.CORE, "fsr4/fsr4_v07_i8.wpack", "app/src/main/assets/fsr4/fsr4_v07_i8.wpack", "a34d8b9fb5bb7dc8ff0fabf143f8cdc989ee412b3c80561107844ec768d90a58", 169624L),
DataFile(Group.NPU, "fsr4/adsp/libQnnHtpV79Skel.so", "app/src/main/assets/fsr4/adsp/libQnnHtpV79Skel.so", "974583f0cdc3d42de7a0633c9b987b160ad033a4cd53be30f9b5480b7e5a3213", 11702104L),
DataFile(Group.NPU, "fsr4/adsp/libQnnHtpV81Skel.so", "app/src/main/assets/fsr4/adsp/libQnnHtpV81Skel.so", "a0b9750d900a0afbba240e3506ba63ba91ec0e7f1b3a44de9afbb6818a665a32", 12606648L),
DataFile(Group.NPU, "jni/libQnnHtp.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtp.so", "6e6da5284060ca4369bb6fd3c6f2b661a9cebabb2cf4cf695cd77f558082265f", 3760136L),
DataFile(Group.NPU, "jni/libQnnHtpNetRunExtensions.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtpNetRunExtensions.so", "9776e906cff859504e9e5fd5f9cbb0ec592d9ae6be312ef0650cb95eb8e3aef6", 1383928L),
DataFile(Group.NPU, "jni/libQnnHtpPrepare.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtpPrepare.so", "cd31f94ae79ad402312e75262297d1e1073f85927d95f7905357a10b1d32a263", 87913152L),
DataFile(Group.NPU, "jni/libQnnHtpV79Stub.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtpV79Stub.so", "b3b4cca02e1f2cb5778ef9f18850814358d62a0b90123b25bb2806731a6af8b3", 754480L),
DataFile(Group.NPU, "jni/libQnnHtpV81Stub.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtpV81Stub.so", "16188365d86ef09a9067e8e04b7fa1c604729d1870219b1bbf04ee904e6c3ffa", 777848L),
DataFile(Group.NPU, "jni/libQnnSystem.so", "app/src/main/jniLibs/arm64-v8a/libQnnSystem.so", "4cd077547a939b131c4733391545d64bdc4f9d0c86de78793335ddd18348789e", 4052904L),
DataFile(Group.XESS, "xess/wl_xess_official.dll", "app/src/main/assets/fsr4_bridge/wl_xess_official.dll", "251659dd84a3e84de67c886a4186e01f3eca49b00641906fe38bb6b807e5d5b7", 77795704L),
)
sealed interface State {
data object Missing : State
data class Downloading(val progress: Float) : State
data object Ready : State
data class Failed(val message: String) : State
}
private val mutableState = MutableStateFlow<State>(State.Missing)
val state: StateFlow<State> = mutableState.asStateFlow()
private val lock = Any()
@Volatile private var busy = false
fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_ROOT.removePrefix("/"))
fun dataDir(context: Context) = File(root(context), "data")
fun bridgesDir(context: Context) = File(root(context), "bridges")
fun runDir(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_RUN.removePrefix("/"))
/** The Hexagon NPU generation the bundled QNN files serve, or null: v79 on the Snapdragon 8 Elite, v81 on the 8 Elite Gen 5. */
fun npuArch(model: String = SocNames.model()): String? {
val soc = SocNames.normalizedModel(model)
val arch = when {
soc.startsWith("SM8750") -> "v79"
soc.startsWith("SM8850") || soc.startsWith("SM8845") -> "v81"
else -> null
} ?: return null
val fastrpc = listOf("/dev/fastrpc-cdsp", "/dev/fastrpc-cdsp-secure", "/dev/adsprpc-smd").any { File(it).exists() }
return arch.takeIf { fastrpc }
}
fun groups(engine: GameUpscaler.Engine, npu: Boolean = npuArch() != null): Set<Group> = buildSet {
add(Group.CORE)
if (engine == GameUpscaler.Engine.XESS) add(Group.XESS)
if (engine.npu && npu) add(Group.NPU)
}
/** The bridge DLLs (tools/upscale/bridges/build.sh), each in both Wine PE folders. */
private val BRIDGE_NAMES = listOf(
"_nvngx.dll", "amd_fidelityfx_dx12.dll", "amd_fidelityfx_loader_dx12.dll", "amd_fidelityfx_upscaler_dx12.dll",
"amd_fidelityfx_upscaler_vk.dll", "amd_fidelityfx_vk.dll", "ffx_fsr2_api_x64.dll", "ffx_fsr3upscaler_x64.dll",
"libxess.dll", "nvapi64.dll", "nvngx.dll", "nvngx_dlss.dll",
)
internal val BRIDGE_FILES = listOf("x86_64-windows", "aarch64-windows").flatMap { arch -> BRIDGE_NAMES.map { "$arch/$it" } }
fun filesReady(context: Context, groups: Set<Group>): Boolean =
FILES.filter { it.group in groups }.all { f -> File(dataDir(context), f.relative).let { it.isFile && it.length() == f.size } }
fun bridgesReady(context: Context): Boolean =
BRIDGE_FILES.all { File(bridgesDir(context), it).let { f -> f.isFile && f.length() > 0 } }
/** Everything a game with [groups] needs: the data files and the bridge DLLs. */
fun ready(context: Context, groups: Set<Group>): Boolean = filesReady(context, groups) && bridgesReady(context)
/** Fetches what [groups] still lack (data files, then the bridge DLLs) in the background. */
fun ensure(context: Context, groups: Set<Group>, onDone: (Boolean) -> Unit = {}) {
val app = context.applicationContext
if (ready(app, groups)) {
mutableState.value = State.Ready
onDone(true)
return
}
synchronized(lock) {
if (busy) return
busy = true
}
Thread({
val ok = try {
val files = filesReady(app, groups) || download(app, groups)
val bridges = files && (bridgesReady(app) || fetchBridges(app))
when {
bridges -> mutableState.value = State.Ready
files -> mutableState.value = State.Failed("upscaler DLLs not installed")
}
bridges
} catch (e: Exception) {
Log.w(TAG, "upscaler files not fetched", e)
mutableState.value = State.Failed(e.message ?: e.javaClass.simpleName)
false
} finally {
synchronized(lock) { busy = false }
}
onDone(ok)
}, "upscale-files").start()
}
private fun download(context: Context, groups: Set<Group>): Boolean {
val wanted = FILES.filter { it.group in groups }
val missing = wanted.filter { f -> File(dataDir(context), f.relative).let { !it.isFile || it.length() != f.size } }
val total = missing.sumOf { it.size }.coerceAtLeast(1L)
var done = 0L
mutableState.value = State.Downloading(0f)
for (f in missing) {
val target = File(dataDir(context), f.relative)
target.parentFile?.mkdirs()
val part = File(target.path + ".part")
val ok = copyLocal(context, f, part) || Downloader.downloadFile(f.url, part, true, f.sha256) { p ->
mutableState.value = State.Downloading(((done + p * f.size) / total).coerceIn(0f, 1f))
}
if (!ok || !part.renameTo(target)) {
part.delete()
val reason = Downloader.lastFailure() ?: "could not fetch ${f.relative}"
mutableState.value = State.Failed(reason)
Log.w(TAG, "upscaler file ${f.relative} not fetched: $reason")
return false
}
if (f.group == Group.NPU) {
target.setReadable(true, false)
target.setExecutable(true, false)
}
done += f.size
mutableState.value = State.Downloading((done.toFloat() / total).coerceIn(0f, 1f))
}
Log.i(TAG, "upscaler files ready (${wanted.size} files, groups $groups)")
return true
}
/**
* Folders that may hold a local copy (same layout as the upstream tree): the app's own external
* files folders, readable without any storage permission, then Download/droiddeck-upscale.
*/
@Suppress("DEPRECATION")
private fun localRoots(context: Context): List<File> =
context.getExternalFilesDirs(null).orEmpty().filterNotNull().map { File(it, LOCAL_COPY) } +
File(Environment.getExternalStorageDirectory(), "Download/$LOCAL_COPY")
/** A local copy of [f] (see [localRoots]), used when its SHA-256 matches. */
private fun copyLocal(context: Context, f: DataFile, part: File): Boolean = localRoots(context).any { root ->
runCatching {
val local = File(root, f.relative)
if (!local.isFile || !local.canRead() || local.length() != f.size || sha256(local) != f.sha256) return@runCatching false
local.inputStream().use { input -> part.outputStream().use { output -> input.copyTo(output, 1 shl 20) } }
sha256(part) == f.sha256
}.getOrDefault(false)
}
private fun sha256(file: File): String {
val digest = MessageDigest.getInstance("SHA-256")
file.inputStream().use { input ->
val buffer = ByteArray(1 shl 20)
while (true) {
val n = input.read(buffer)
if (n < 0) break
digest.update(buffer, 0, n)
}
}
return digest.digest().joinToString("") { "%02x".format(it) }
}
/** The add-on pack's bridges/ (fetched now when there is no local copy), staged into the rootfs. */
private fun fetchBridges(context: Context): Boolean {
val pack = AddonPack.UPSCALE
if (!pack.installed(context) && localBridges(context) == null && pack.available) pack.await(context)
return stageBridges(context)
}
/** A complete, readable bridges/ tree in one of [localRoots]: builds without a published pack. */
private fun localBridges(context: Context): File? = localRoots(context).map { File(it, "bridges") }.firstOrNull { dir ->
runCatching { BRIDGE_FILES.all { File(dir, it).let { f -> f.isFile && f.canRead() && f.length() > 0 } } }.getOrDefault(false)
}
/**
* Copies the bridge DLLs from the add-on pack (or the local tree) into the rootfs, once per version. True only
* when every one of [BRIDGE_FILES] is in place afterwards.
*/
@Synchronized
fun stageBridges(context: Context): Boolean {
val packDir = AddonPack.UPSCALE.takeIf { it.installed(context) }?.dir(context)
val pack = packDir?.let { File(it, "bridges") }
val source = pack?.takeIf { dir -> BRIDGE_FILES.all { File(dir, it).isFile } } ?: localBridges(context)
if (source == null) {
val ready = bridgesReady(context)
if (!ready) Log.w(TAG, "upscaler bridges: no add-on pack and no readable local copy")
return ready
}
val version = if (packDir != null && source == pack) packDir.name
else "local-" + File(source, "x86_64-windows/libxess.dll").let { it.length().toString() + "-" + it.lastModified() }
val target = bridgesDir(context)
val stamp = File(target, BRIDGES_STAMP)
if (bridgesReady(context) && runCatching { stamp.readText() }.getOrNull() == version) return true
var copied = 0
for (name in BRIDGE_FILES) {
val from = File(source, name)
val out = File(target, name)
out.parentFile?.mkdirs()
val staged = File(out.path + ".staged")
val ok = runCatching {
from.inputStream().use { input -> staged.outputStream().use { output -> input.copyTo(output) } }
staged.length() == from.length() && staged.renameTo(out)
}.getOrDefault(false)
staged.delete()
if (ok) copied++ else Log.w(TAG, "upscaler bridge $name not staged from $source")
}
val ok = copied == BRIDGE_FILES.size && bridgesReady(context)
if (ok) runCatching { stamp.writeText(version) }
Log.i(TAG, "upscaler bridges staged from $version: $copied/${BRIDGE_FILES.size} files")
return ok
}
/** The bionic layer's manifest (the layer itself is the APK's native library). */
fun bionicLayerDir(context: Context): File {
val dir = File(context.filesDir, "upscale/layer")
val library = File(context.applicationInfo.nativeLibraryDir, LAYER_LIBRARY)
val manifest = """{
"file_format_version": "1.0.0",
"layer": {
"name": "VK_LAYER_DROIDDECK_upscale",
"type": "GLOBAL",
"library_path": "${library.absolutePath}",
"api_version": "1.3.275",
"implementation_version": "1",
"description": "DroidDeck in-game upscaler (FSR 4, XeSS 3, Hexagon NPU)",
"enable_environment": { "DROIDDECK_UPSCALE": "1" },
"disable_environment": { "DROIDDECK_UPSCALE_DISABLE": "1" }
}
}
"""
runCatching {
dir.mkdirs()
val file = File(dir, "VK_LAYER_DROIDDECK_upscale.json")
if (!file.isFile || file.readText() != manifest) file.writeText(manifest)
}.onFailure { Log.w(TAG, "could not write the upscaler layer manifest", it) }
return dir
}
/** Session-wide guest variables: whether NPU engines can run here, and the bionic layer's manifest folder. */
fun guestEnv(context: Context): List<String> {
runCatching { runDir(context).mkdirs() }
return listOf(
"DROIDDECK_UPSCALE_NPU=" + (if (npuArch() != null) "1" else "0"),
"DROIDDECK_UPSCALE_LAYER=" + bionicLayerDir(context).absolutePath,
)
}
/** Fetches what the games set to use the upscaler need, at session start. */
fun prepare(context: Context) {
val config = runCatching { GameEnvironmentStore.read(context) }.getOrNull() ?: return
val choices = config.games.keys.mapNotNull { GameUpscaler.choice(config, it) }
if (choices.isEmpty()) return
val npu = npuArch() != null
ensure(context, choices.flatMap { groups(it.engine, npu) }.toSet())
}
/** Live switch while a game runs: the layer polls this file (fsr4_layer.c read_live_ctrl). */
fun writeControl(context: Context, engine: GameUpscaler.Engine, sharpness: Int, npuSync: Boolean, enabled: Boolean = true) {
runCatching {
val dir = runDir(context).apply { mkdirs() }
val ctrl = File(dir, "ctrl")
val staged = File(dir, "ctrl.tmp")
val effective = GameUpscaler.effectiveEngine(engine, npuArch() != null)
staged.writeText(GameUpscaler.controlText(effective, sharpness, npuSync, enabled))
staged.renameTo(ctrl)
}.onFailure { Log.w(TAG, "could not write the upscaler control file", it) }
}
/** What the layer reports, if it wrote in the last few seconds. */
fun status(context: Context, nowMs: Long = System.currentTimeMillis()): GameUpscaler.Status? {
val file = File(runDir(context), "status")
if (!file.isFile || nowMs - file.lastModified() > 5000) return null
return runCatching { GameUpscaler.parseStatus(file.readText()) }.getOrNull()
}
fun anyGame(config: GameEnvironment.Config): Boolean = config.games.keys.any { GameUpscaler.choice(config, it) != null }
}
@@ -121,8 +121,6 @@ object StoresState {
var unfinished by mutableStateOf<List<StoreInstallRoot.Unfinished>>(emptyList())
internal set
var steamPicking by mutableStateOf<CatalogItem?>(null)
fun isUnfinished(item: CatalogItem): Boolean = unfinished.any {
it.store == item.store && (it.id == item.id || (it.id == null && it.folder.name == StoreInstallRoot.folderName(item.title, item.id)))
}
@@ -6,6 +6,9 @@ import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionService
@@ -43,6 +46,8 @@ internal object SteamStore {
/** InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, AccountLogonDenied. */
private val REFUSALS = setOf(5, 15, 18, 26, 27, 63)
var picking by mutableStateOf<CatalogItem?>(null)
class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String, val linuxBuild: Boolean) {
companion object {
fun of(json: JSONObject): Plan? {
@@ -217,7 +222,7 @@ internal object SteamStore {
toast(context, R.string.steam_store_close_steam)
return
}
StoresState.steamPicking = item
picking = item
}
fun install(context: Context, item: CatalogItem, target: SteamClient.Target) {
@@ -210,6 +210,7 @@ private val METRICS = listOf(
HudMetric("showNet", R.string.hud_metric_network),
HudMetric("showResolution", R.string.hud_metric_resolution),
HudMetric("showProton", R.string.hud_metric_proton),
HudMetric("showUpscale", R.string.hud_metric_upscale),
HudMetric("showSession", R.string.hud_metric_session),
HudMetric("showClock", R.string.hud_metric_clock),
)
@@ -847,7 +847,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
com.droiddeck.launcher.stores.StoresState.steamPicking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.StoresState.steamPicking = null } } }
com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } }
StepsLayer(screenAt)
UiZooSheet()
SessionDrawerPreview(s.secondScreenDisplays)
@@ -983,6 +983,38 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameResolution(it, scope, choice) }
}
var editResolution by remember(scope) { mutableStateOf(false) }
val upKey = "game-settings-upscale"
val upEngineKey = "game-settings-upscale-engine"
val upSharpKey = "game-settings-upscale-sharp"
val upscale = current?.let { com.droiddeck.launcher.core.GameUpscaler.choice(it, scope) }
val npuHere = remember { com.droiddeck.launcher.session.UpscaleComponent.npuArch() != null }
val upFiles by com.droiddeck.launcher.session.UpscaleComponent.state.collectAsState()
val modeLabels = mapOf(
com.droiddeck.launcher.core.GameUpscaler.Mode.FSR_XESS to stringResource(R.string.game_upscaler_mode_fsr),
com.droiddeck.launcher.core.GameUpscaler.Mode.DLSS to stringResource(R.string.game_upscaler_mode_dlss),
com.droiddeck.launcher.core.GameUpscaler.Mode.NATIVE_FSR4 to stringResource(R.string.game_upscaler_mode_native),
)
val engineLabels = mapOf(
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_LITE_GPU to stringResource(R.string.game_upscaler_engine_fsr4_lite),
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_FULL_GPU to stringResource(R.string.game_upscaler_engine_fsr4_full),
com.droiddeck.launcher.core.GameUpscaler.Engine.XESS to stringResource(R.string.game_upscaler_engine_xess),
com.droiddeck.launcher.core.GameUpscaler.Engine.BASIC to stringResource(R.string.game_upscaler_engine_basic),
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_NPU to stringResource(R.string.game_upscaler_engine_fsr4_npu),
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_LITE_NPU to stringResource(R.string.game_upscaler_engine_fsr4_lite_npu),
)
val upOff = stringResource(R.string.game_upscaler_off)
val filesLabel = when (val f = upFiles) {
is com.droiddeck.launcher.session.UpscaleComponent.State.Downloading -> stringResource(R.string.game_upscaler_files_downloading, (f.progress * 100).toInt())
is com.droiddeck.launcher.session.UpscaleComponent.State.Failed -> stringResource(R.string.game_upscaler_files_failed, f.message)
else -> if (upscale != null && com.droiddeck.launcher.session.UpscaleComponent.ready(appContext,
com.droiddeck.launcher.session.UpscaleComponent.groups(upscale.engine, npuHere)))
stringResource(R.string.game_upscaler_files_ready) else stringResource(R.string.game_upscaler_files_missing)
}
fun pickUpscale(choice: com.droiddeck.launcher.core.GameUpscaler.Choice?) {
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameUpscaler(it, scope, choice) }
if (choice != null) com.droiddeck.launcher.session.UpscaleComponent.ensure(appContext,
com.droiddeck.launcher.session.UpscaleComponent.groups(choice.engine, npuHere))
}
AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = stringResource(R.string.game_settings_menu_title, game.name)) { first ->
MenuItem(stringResource(R.string.game_no_steam_title), checked = noSteam, enabled = ready,
detail = stringResource(R.string.game_no_steam_detail), focusRequester = first) {
@@ -1014,6 +1046,37 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
},
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
) { host.open = syncKey }
MenuItem(
stringResource(R.string.game_upscaler_title), checked = false, enabled = ready,
detail = upscale?.let { modeLabels[it.mode] } ?: upOff,
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
) { host.open = upKey }
if (upscale != null) {
MenuItem(
stringResource(R.string.game_upscaler_engine), checked = false, enabled = ready,
detail = engineLabels[com.droiddeck.launcher.core.GameUpscaler.effectiveEngine(upscale.engine, npuHere)],
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
) { host.open = upEngineKey }
MenuItem(
stringResource(R.string.game_upscaler_sharpness), checked = false, enabled = ready,
detail = stringResource(R.string.game_upscaler_sharpness_value, upscale.sharpness),
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
) { host.open = upSharpKey }
if (upscale.mode == com.droiddeck.launcher.core.GameUpscaler.Mode.DLSS) {
MenuItem(stringResource(R.string.game_upscaler_sigfix), checked = upscale.signatureFix, enabled = ready) {
pickUpscale(upscale.copy(signatureFix = !upscale.signatureFix))
}
}
if (upscale.engine.npu && npuHere) {
MenuItem(stringResource(R.string.game_upscaler_npu_sync), checked = upscale.npuSync, enabled = ready) {
pickUpscale(upscale.copy(npuSync = !upscale.npuSync))
}
}
MenuItem(stringResource(R.string.game_upscaler_files), checked = false, enabled = ready, detail = filesLabel) {
com.droiddeck.launcher.session.UpscaleComponent.ensure(appContext,
com.droiddeck.launcher.session.UpscaleComponent.groups(upscale.engine, npuHere))
}
}
}
MenuItem(stringResource(R.string.game_settings_default), checked = false, enabled = ready,
detail = stringResource(R.string.game_settings_default_detail)) {
@@ -1030,6 +1093,36 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
}
}
}
AnchoredMenu(host.open == upKey, onDismiss = { if (host.open == upKey) host.open = null }, title = stringResource(R.string.game_upscaler_title)) { first ->
MenuItem(upOff, checked = upscale == null, enabled = ready, focusRequester = first) {
host.open = key
pickUpscale(null)
}
com.droiddeck.launcher.core.GameUpscaler.Mode.entries.forEach { mode ->
MenuItem(modeLabels.getValue(mode), checked = upscale?.mode == mode, enabled = ready) {
host.open = key
pickUpscale((upscale ?: com.droiddeck.launcher.core.GameUpscaler.Choice(mode)).copy(mode = mode))
}
}
}
AnchoredMenu(host.open == upEngineKey, onDismiss = { if (host.open == upEngineKey) host.open = null }, title = stringResource(R.string.game_upscaler_engine)) { first ->
com.droiddeck.launcher.core.GameUpscaler.Engine.entries.filter { !it.npu || npuHere }.forEachIndexed { index, engine ->
MenuItem(engineLabels.getValue(engine), checked = upscale?.engine == engine, enabled = ready && upscale != null,
focusRequester = if (index == 0) first else null) {
host.open = key
upscale?.let { pickUpscale(it.copy(engine = engine)) }
}
}
}
AnchoredMenu(host.open == upSharpKey, onDismiss = { if (host.open == upSharpKey) host.open = null }, title = stringResource(R.string.game_upscaler_sharpness)) { first ->
com.droiddeck.launcher.core.GameUpscaler.sharpnessSteps.forEachIndexed { index, value ->
MenuItem(stringResource(R.string.game_upscaler_sharpness_value, value), checked = upscale?.sharpness == value,
enabled = ready && upscale != null, focusRequester = if (index == 0) first else null) {
host.open = key
upscale?.let { pickUpscale(it.copy(sharpness = value)) }
}
}
}
AnchoredMenu(host.open == resKey, onDismiss = { if (host.open == resKey) host.open = null }, title = stringResource(R.string.game_res_title)) { first ->
MenuItem(matchScreen, checked = resolution == null, enabled = ready, focusRequester = first) { pickResolution(null) }
com.droiddeck.launcher.core.GameResolution.scales.forEach { scale ->
@@ -937,6 +937,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
Text(stringResource(R.string.fex_next_launch), fontSize = 12.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp))
TextureFilteringGroup(host, a) { key -> focus.track(page, key) }
if (a.steam || a.direct) DrawerUpscalerGroup(host, a) { key -> focus.track(page, key) }
if (a.steam || a.direct) SettingsGroup(stringResource(R.string.game_settings_title)) {
DrawerFexPresetRow(host, a, focus.track(page, "fex"))
DrawerNoSteamRow(host, a, focus.track(page, "no-steam"))
@@ -1652,6 +1653,51 @@ private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (Stri
}
}
/** The selected game's in-game upscaler: engine and sharpness switch live (the layer polls its control file). */
@Composable
private fun DrawerUpscalerGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val appId = a.selectedGameProfileId ?: return
val context = LocalContext.current.applicationContext
val scope = appId.toString()
var choice by remember(scope) {
mutableStateOf(runCatching { com.droiddeck.launcher.core.GameUpscaler.choice(com.droiddeck.launcher.session.GameEnvironmentStore.read(context), scope) }.getOrNull())
}
val current = choice ?: return
val npuHere = remember { com.droiddeck.launcher.session.UpscaleComponent.npuArch() != null }
var status by remember { mutableStateOf<com.droiddeck.launcher.core.GameUpscaler.Status?>(null) }
LaunchedEffect(scope) {
while (true) {
status = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.droiddeck.launcher.session.UpscaleComponent.status(context) }
delay(1000)
}
}
val engines = com.droiddeck.launcher.core.GameUpscaler.Engine.entries.filter { !it.npu || npuHere }.map { engine ->
engine to stringResource(when (engine) {
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_LITE_GPU -> R.string.game_upscaler_engine_fsr4_lite
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_FULL_GPU -> R.string.game_upscaler_engine_fsr4_full
com.droiddeck.launcher.core.GameUpscaler.Engine.XESS -> R.string.game_upscaler_engine_xess
com.droiddeck.launcher.core.GameUpscaler.Engine.BASIC -> R.string.game_upscaler_engine_basic
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_NPU -> R.string.game_upscaler_engine_fsr4_npu
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_LITE_NPU -> R.string.game_upscaler_engine_fsr4_lite_npu
})
}
val sharpness = com.droiddeck.launcher.core.GameUpscaler.sharpnessSteps.map { it to stringResource(R.string.game_upscaler_sharpness_value, it) }
fun applyChoice(next: com.droiddeck.launcher.core.GameUpscaler.Choice) {
choice = next
Thread({
com.droiddeck.launcher.session.UpscaleComponent.writeControl(context, next.engine, next.sharpness, next.npuSync)
runCatching { com.droiddeck.launcher.session.GameEnvironmentStore.setGameUpscaler(context, scope, next) }
}, "upscale-live").start()
}
SettingsGroup(stringResource(R.string.game_upscaler_title)) {
ChoiceRow(host, "upscale-engine", stringResource(R.string.game_upscaler_engine),
status?.let { "${it.backendTag} · ${it.render} → ${it.output} · " + String.format(java.util.Locale.ROOT, "%.1f ms", if (it.npu) it.npuMs else it.gpuMs) },
engines, current.engine, chipModifier = track("upscale-engine")) { engine -> applyChoice(current.copy(engine = engine)) }
ChoiceRow(host, "upscale-sharpness", stringResource(R.string.game_upscaler_sharpness), null,
sharpness, current.sharpness, chipModifier = track("upscale-sharpness")) { value -> applyChoice(current.copy(sharpness = value)) }
}
}
private fun signed(v: Int) = if (v > 0) "+$v" else "$v"
@Composable
+22
View File
@@ -552,6 +552,27 @@
<string name="game_steam_with">Starts with Steam</string>
<string name="game_steam_without">Starts without Steam</string>
<string name="game_res_title">Game resolution</string>
<string name="game_upscaler_title">In-game upscaler</string>
<string name="game_upscaler_off">Off</string>
<string name="game_upscaler_mode_fsr">FSR and XeSS games</string>
<string name="game_upscaler_mode_dlss">DLSS games</string>
<string name="game_upscaler_mode_native">Native FSR 4</string>
<string name="game_upscaler_engine">Upscaler</string>
<string name="game_upscaler_engine_fsr4_lite">FSR 4 Lite</string>
<string name="game_upscaler_engine_fsr4_full">FSR 4</string>
<string name="game_upscaler_engine_xess">XeSS 3</string>
<string name="game_upscaler_engine_basic">Basic temporal</string>
<string name="game_upscaler_engine_fsr4_npu">FSR 4 on NPU</string>
<string name="game_upscaler_engine_fsr4_lite_npu">FSR 4 Lite on NPU</string>
<string name="game_upscaler_sharpness">Sharpness</string>
<string name="game_upscaler_sharpness_value">%1$d%%</string>
<string name="game_upscaler_sigfix">DLSS signature fix</string>
<string name="game_upscaler_npu_sync">NPU sync</string>
<string name="game_upscaler_files">Upscaler files</string>
<string name="game_upscaler_files_ready">Ready</string>
<string name="game_upscaler_files_missing">Not downloaded</string>
<string name="game_upscaler_files_downloading">Downloading %1$d%%</string>
<string name="game_upscaler_files_failed">Failed: %1$s</string>
<string name="game_settings_card">Settings</string>
<string name="game_settings_menu_title">%1$s Settings</string>
<string name="game_settings_default">Default</string>
@@ -768,6 +789,7 @@
<string name="hud_metric_network">Network</string>
<string name="hud_metric_resolution">Resolution</string>
<string name="hud_metric_proton">Proton version</string>
<string name="hud_metric_upscale">In-game upscaler</string>
<string name="hud_metric_session">Session time</string>
<string name="hud_metric_clock">Clock</string>
<string name="hud_group_temps">Temperatures</string>
@@ -20,24 +20,6 @@ class GameEnvironmentTest {
assertEquals("1", GameEnvironment.effective(config, "", "43", forceSsbs = true)[GameEnvironment.FORCE_SSBS])
}
@Test fun knownGameFixesBeatSharedSettingsButNotTheGamesOwn() {
val shared = GameEnvironment.Config(shared = mapOf("FEX_X87REDUCEDPRECISION" to "1"))
assertEquals("0", GameEnvironment.effective(shared, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"])
assertEquals("1", GameEnvironment.effective(shared, "PERFORMANCE_TSO", "12110")["FEX_X87REDUCEDPRECISION"])
val own = shared.withEntries("12100", mapOf("FEX_X87REDUCEDPRECISION" to "1"))
assertEquals("1", GameEnvironment.effective(own, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"])
assertEquals("1", GameEnvironment.withKnownGames(own).games["12100"]?.get("FEX_X87REDUCEDPRECISION"))
assertEquals("0", GameEnvironment.withKnownGames(shared).games["12100"]?.get("FEX_X87REDUCEDPRECISION"))
}
@Test fun aGamePresetKeepsTheGamesKnownFix() {
val picked = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "12100", "PERFORMANCE")
assertEquals("0", GameEnvironment.effective(picked, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"])
assertEquals("PERFORMANCE", GameEnvironment.gameFexPreset(picked, "12100"))
val other = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "12110", "PERFORMANCE")
assertEquals("1", GameEnvironment.effective(other, "PERFORMANCE_TSO", "12110")["FEX_X87REDUCEDPRECISION"])
}
@Test fun gameOverridesSharedAndPresetWithoutLeakingToOtherGames() {
val config = GameEnvironment.Config(
shared = mapOf("FEX_MULTIBLOCK" to "0", "VKD3D_FEATURE_LEVEL" to "12_2"),
@@ -0,0 +1,59 @@
package com.droiddeck.launcher.core
import org.junit.Assert.*
import org.junit.Test
class GameUpscalerTest {
@Test fun aChoiceRoundTripsThroughTheGameEnvironment() {
val choice = GameUpscaler.Choice(GameUpscaler.Mode.DLSS, GameUpscaler.Engine.XESS, 70, npuSync = true, signatureFix = true)
val config = GameUpscaler.withChoice(GameEnvironment.Config(), "42", choice)
assertEquals(choice, GameUpscaler.choice(config, "42"))
assertNull(GameUpscaler.choice(config, "43"))
}
@Test fun offRemovesOnlyTheUpscalerEntries() {
val start = GameEnvironment.Config().withEntries("42", mapOf("FEX_MULTIBLOCK" to "0"))
val on = GameUpscaler.withChoice(start, "42", GameUpscaler.Choice(GameUpscaler.Mode.FSR_XESS))
val off = GameUpscaler.withChoice(on, "42", null)
assertEquals(mapOf("FEX_MULTIBLOCK" to "0"), off.games["42"])
}
@Test fun theSignatureFixIsOnlyKeptForDlss() {
val fsr = GameUpscaler.entries(GameUpscaler.Choice(GameUpscaler.Mode.FSR_XESS, signatureFix = true))
assertFalse(fsr.containsKey(GameUpscaler.SIGFIX))
val dlss = GameUpscaler.entries(GameUpscaler.Choice(GameUpscaler.Mode.DLSS, signatureFix = true))
assertEquals("1", dlss[GameUpscaler.SIGFIX])
}
@Test fun unknownValuesFallBackToDefaults() {
val config = GameEnvironment.Config().withEntries("7", mapOf(
GameUpscaler.MODE to "fsr", GameUpscaler.ENGINE to "bogus", GameUpscaler.SHARPNESS to "250"))
val choice = GameUpscaler.choice(config, "7")!!
assertEquals(GameUpscaler.DEFAULT_ENGINE, choice.engine)
assertEquals(100, choice.sharpness)
assertNull(GameUpscaler.choice(GameEnvironment.Config().withEntries("7", mapOf(GameUpscaler.MODE to "x")), "7"))
}
@Test fun npuEnginesRunOnTheGpuWithoutAnNpu() {
assertEquals(GameUpscaler.Engine.FSR4_FULL_GPU, GameUpscaler.effectiveEngine(GameUpscaler.Engine.FSR4_NPU, false))
assertEquals(GameUpscaler.Engine.FSR4_LITE_GPU, GameUpscaler.effectiveEngine(GameUpscaler.Engine.FSR4_LITE_NPU, false))
assertEquals(GameUpscaler.Engine.FSR4_NPU, GameUpscaler.effectiveEngine(GameUpscaler.Engine.FSR4_NPU, true))
assertEquals(GameUpscaler.Engine.XESS, GameUpscaler.effectiveEngine(GameUpscaler.Engine.XESS, false))
}
@Test fun theControlFileUsesTheLayersKeys() {
assertEquals("enabled=1\nbackend=fsr4_1_lite_gpu\nsharpness=0.55\nnpu_sync=0\n",
GameUpscaler.controlText(GameUpscaler.Engine.FSR4_LITE_GPU, 55, npuSync = false, enabled = true))
}
@Test fun theLayersStatusFileParses() {
val status = GameUpscaler.parseStatus(
"layer=1\nengine=fsr4\nbackend=fsr4_1_lite_gpu\nbackend_tag=FSR4.1-Lite-GPU\nactive=1\nnpu=0\n" +
"render=960x540\noutput=1920x1080\ngpu_us=3250\nhtp_us=0\nreason=ok\nts_ms=99\n")!!
assertTrue(status.active)
assertEquals("FSR4.1-Lite-GPU", status.backendTag)
assertEquals(3.25f, status.gpuMs, 0.001f)
assertEquals("1920x1080", status.output)
assertNull(GameUpscaler.parseStatus("active=1\n"))
}
}
@@ -202,19 +202,11 @@ class GameEnvironmentStoreTest {
assertEquals("false", published.shared["MESA_SHADER_CACHE_DISABLE"])
assertFalse(published.shared.containsKey("VKD3D_FEATURE_LEVEL"))
assertFalse(published.shared.containsKey("VKD3D_SHADER_MODEL"))
assertEquals(config.games + GameEnvironment.knownGames, published.games)
assertEquals(config.games, published.games)
assertEquals(config.shared["LITERAL"], published.shared["LITERAL"])
assertEquals("", published.shared["EMPTY"])
}
@Test fun aKnownGamesFixReachesTheGuestWithoutBeingSavedAsTheUsersSetting() {
GameEnvironmentStore.save(context, GameEnvironment.Config())
assertEquals(emptyMap<String, Map<String, String?>>(), GameEnvironmentStore.read(context).games)
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertEquals(GameEnvironment.knownGames, published.games)
assertEquals("0", published.entries("12100")["FEX_X87REDUCEDPRECISION"])
}
@Test fun publishingPreservesExplicitSharedGraphicsCapabilities() {
val config = GameEnvironment.Config(shared = mapOf(
"VKD3D_FEATURE_LEVEL" to "12_1", "VKD3D_SHADER_MODEL" to "6_6",
@@ -274,7 +266,7 @@ class GameEnvironmentStoreTest {
assertEquals(original.entries("43"), saved.entries("43"))
assertEquals("PERFORMANCE_TSO", SessionPrefs.fexPreset(context))
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertEquals(saved.games + GameEnvironment.knownGames, published.games)
assertEquals(saved.games, published.games)
assertEquals("0", published.shared["FEX_HALFBARRIERTSOENABLED"])
assertEquals("1", published.entries("42")["FEX_HALFBARRIERTSOENABLED"])
}
@@ -1,37 +0,0 @@
package com.droiddeck.launcher.stores.steam
import androidx.compose.runtime.State
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.runtime.snapshots.StateObject
import com.droiddeck.launcher.stores.StoresState
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import kotlin.concurrent.thread
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE)
class SteamPickingSnapshotTest {
@Test
fun theInstallPickerIsReadableInASnapshotOpenedBeforeTheSteamEngineStarts() {
StoresState.steamPicking = null
val snapshot = Snapshot.takeMutableSnapshot()
try {
thread { SteamStore.hashCode() }.join()
assertNull(snapshot.enter { StoresState.steamPicking })
} finally {
snapshot.dispose()
}
}
@Test
fun theSteamEngineHoldsNoComposeState() {
val stateFields = SteamStore::class.java.declaredFields.filter {
StateObject::class.java.isAssignableFrom(it.type) || State::class.java.isAssignableFrom(it.type)
}
assertTrue(stateFields.joinToString { it.name }, stateFields.isEmpty())
}
}
@@ -9,25 +9,6 @@ import org.junit.Test
class XodusDiagnosticsTest {
private val rejected = Regex(Xodus.SIGN_IN_REJECTED)
@Test fun aDeviceLimitReachesTheInstallerWithoutBecomingASignInFailure() {
val line = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200"
val tail = listOf(line).filter { it.matches(Xodus.reportable) }
assertEquals(listOf(line), tail)
assertFalse(line.matches(rejected))
assertEquals(com.droiddeck.launcher.R.string.stores_xbox_device_group_full, XboxInstaller.licenseRefusal(tail))
}
@Test fun aLaterLicenseSuccessClearsTheDeviceLimitThroughTheDiagnosticFilter() {
val stderr = listOf(
"NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200",
"NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-parsed 200",
"NEXUS_EXTRACT_DIAGNOSTIC_V1 extract-failed"
)
val tail = stderr.filter { it.matches(Xodus.reportable) }
assertEquals(stderr, tail)
assertNull(XboxInstaller.licenseRefusal(tail))
}
@Test fun aContentLicenseRejectionIsRecognised() {
assertTrue("Microsoft content licensing rejected sign-in (HTTP 401). Sign in again in Settings.".matches(rejected))
}
+5 -1
View File
@@ -51,6 +51,7 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
DXVK_LOG_PATH|VKD3D_LOG_FILE|MESA_LOG_FILE) ;;
DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;;
DROIDDECK_GUEST_ROOT) ;;
DROIDDECK_UPSCALE|DROIDDECK_UPSCALE_*|WINEDLLPATH|ADSP_LIBRARY_PATH|PROTON_ENABLE_NVAPI|DXVK_ENABLE_NVAPI|WINE_HIDE_NVIDIA_GPU) ;;
VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;;
*) unset "$v" 2>/dev/null ;;
esac
@@ -85,7 +86,10 @@ echo "driver $DRVDIR"
RTD=$APP/.wayland-rt
export VK_ICD_FILENAMES=$PACK/adapter/icd.json ADRENOTOOLS_DRIVER_PATH=$DRVDIR/ ADRENOTOOLS_HOOKS_PATH=$PACK/lib
export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR")
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
# The in-game upscaler's layer is in the APK; DroidDeck writes its manifest to DROIDDECK_UPSCALE_LAYER.
UPSCALE_LAYER=""
[ -n "${DROIDDECK_UPSCALE:-}" ] && [ -n "${DROIDDECK_UPSCALE_LAYER:-}" ] && [ -d "$DROIDDECK_UPSCALE_LAYER" ] && UPSCALE_LAYER=":$DROIDDECK_UPSCALE_LAYER"
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer$UPSCALE_LAYER ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=1
[ -e "$RTD/droiddeck-gamescope-limiter" ] && export GAMESCOPE_LIMITER_FILE=$RTD/droiddeck-gamescope-limiter
+15
View File
@@ -103,6 +103,21 @@ case "$verb" in
done
# The HUD's GPU-load folder is a guest path; the bionic game writes to it by its Android path.
[ -n "${DROIDDECK_GPU_LOAD_DIR:-}" ] && { DROIDDECK_GPU_LOAD_DIR=$(real "$DROIDDECK_GPU_LOAD_DIR"); export DROIDDECK_GPU_LOAD_DIR; }
# The in-game upscaler's folders and files (droiddeck-game-env sets them as guest paths); the bridge folder on
# WINEDLLPATH and the NPU skeleton folder at the head of ADSP_LIBRARY_PATH as well.
for v in DROIDDECK_UPSCALE_DIR DROIDDECK_UPSCALE_CTRL_FILE DROIDDECK_UPSCALE_STATUS_FILE DROIDDECK_UPSCALE_NATIVELIB_DIR; do
[ -n "${!v:-}" ] && { printf -v "$v" '%s' "$(real "${!v}")"; export "${v?}"; }
done
if [ -n "${DROIDDECK_UPSCALE:-}" ] && [ -n "${WINEDLLPATH:-}" ]; then
out=""
IFS=: read -r -a parts <<< "$WINEDLLPATH"
for part in "${parts[@]}"; do [ -n "$part" ] && out="${out:+$out:}$(real "$part")"; done
WINEDLLPATH=$out; export WINEDLLPATH
fi
if [ -n "${DROIDDECK_UPSCALE:-}" ] && [ -n "${ADSP_LIBRARY_PATH:-}" ]; then
head=${ADSP_LIBRARY_PATH%%;*}
ADSP_LIBRARY_PATH="$(real "$head")${ADSP_LIBRARY_PATH#"$head"}"; export ADSP_LIBRARY_PATH
fi
# So are the graphics log locations Detailed graphics logs or game debugging set for this launch.
for v in DXVK_LOG_PATH VKD3D_LOG_FILE MESA_LOG_FILE; do
[ -n "${!v:-}" ] && { printf -v "$v" '%s' "$(real "${!v}")"; export "${v?}"; }
+40 -1
View File
@@ -16,6 +16,7 @@
"tools/pipewire",
"tools/vr",
"tools/gpuload",
"tools/upscale/layer",
"app/src/main/cpp/waylandcomp/generated",
"app/src/main/cpp/waylandcomp/src/headpose_shm.h",
"app/src/main/cpp/waylandcomp/src/spatialpose_shm.h",
@@ -24,7 +25,9 @@
"outputs": [
"app/src/main/assets/linuxfs/usr/local/bin/gamescope",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/bin/linuxarm64/driver_droiddeck.so",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so"
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/VK_LAYER_DROIDDECK_upscale.json"
],
"ndk": true,
"packages": [
@@ -266,5 +269,41 @@
"lld",
"llvm"
]
},
"upscale-bridges": {
"script": "tools/components/recipes/upscale-bridges.sh",
"inputs": [
"tools/upscale/bridges",
"tools/components/recipes/upscale-bridges.sh"
],
"outputs": [
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/_nvngx.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_dx12.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_loader_dx12.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_upscaler_dx12.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_upscaler_vk.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_vk.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/ffx_fsr2_api_x64.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/ffx_fsr3upscaler_x64.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/libxess.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/nvapi64.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/nvngx.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/nvngx_dlss.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/_nvngx.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_dx12.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_loader_dx12.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_upscaler_dx12.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_upscaler_vk.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_vk.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/ffx_fsr2_api_x64.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/ffx_fsr3upscaler_x64.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/libxess.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/nvapi64.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/nvngx.dll",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/nvngx_dlss.dll"
],
"packages": [
"gcc-mingw-w64-x86-64"
]
}
}
+2
View File
@@ -6,6 +6,8 @@ VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_
tools/vr/build.sh --native "$D/usr/local/lib/droiddeck-vr"
VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
tools/gpuload/build.sh --native "$D/usr/local/lib/droiddeck-gpuload"
VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
tools/upscale/layer/build-glibc.sh "$D/usr/local/lib/droiddeck-upscale-layer"
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
done
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
set -euo pipefail
bash tools/upscale/bridges/build.sh app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges
@@ -0,0 +1,9 @@
[Desktop Entry]
Name=Return to Gaming Mode
Comment=Log out of the desktop and go back to Steam
Exec=dbus-send --session --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout
Icon=steamdeck-gaming-return
Terminal=false
Type=Application
StartupNotify=false
NoDisplay=true
+1 -5
View File
@@ -229,16 +229,12 @@ fi
if ! /usr/local/bin/droiddeck-pipewire start; then
echo "== pipewire: not running; screen capture has no picture"
fi
return_gaming=/run/droiddeck/return-gaming
mkdir -p /run/droiddeck
rm -f "$return_gaming"
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
dbus-run-session -- startplasma-wayland
rc=$?
/usr/local/bin/droiddeck-pipewire stop
echo "== droiddeck-desktop: Plasma ended ($rc)"
if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ] && [ -e "$return_gaming" ]; then
rm -f "$return_gaming"
if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ]; then
/usr/local/bin/droiddeck-steam-launch bigpicture
sleep 30
fi
@@ -1,9 +0,0 @@
[Desktop Entry]
Name=Return to Gaming Mode
Comment=Log out of the desktop and go back to Steam
Exec=sh -c ": > /run/droiddeck/return-gaming; dbus-send --session --print-reply --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout >/dev/null || rm -f /run/droiddeck/return-gaming"
Icon=steamdeck-gaming-return
Terminal=false
Type=Application
StartupNotify=false
NoDisplay=true
@@ -1080,6 +1080,176 @@ def directaudio_settings(env):
return env
# The in-game upscaler (tools/upscale, ported from Winlator-NeuralScale, GPL-3.0): bridge DLLs stand in for the
# game's DLSS / FidelityFX / FSR 2/3 / XeSS DLLs and hand each frame to VK_LAYER_DROIDDECK_upscale. The app keeps
# the game's choice in DROIDDECK_UPSCALE_MODE (fsr, dlss, native) and DROIDDECK_UPSCALE_ENGINE/_SHARPNESS/_NPU_SYNC.
UPSCALE_ROOT = "/usr/local/lib/droiddeck-upscale"
UPSCALE_RUN = "/run/droiddeck-hud/upscale"
UPSCALE_MODES = ("fsr", "dlss", "native")
UPSCALE_ENGINES = ("fsr4_1_lite_gpu", "fsr4_1_full_gpu", "xess3_gpu", "fsr3_gpu", "fsr4_0_npu", "fsr4_1_lite_npu")
UPSCALE_NPU_FALLBACK = {"fsr4_0_npu": "fsr4_1_full_gpu", "fsr4_1_lite_npu": "fsr4_1_lite_gpu"}
UPSCALE_FSR_DLLS = ("libxess", "ffx_fsr3upscaler_x64", "ffx_fsr2_api_x64", "amd_fidelityfx_vk", "amd_fidelityfx_dx12",
"amd_fidelityfx_upscaler_vk", "amd_fidelityfx_upscaler_dx12", "amd_fidelityfx_loader_dx12")
UPSCALE_DLSS_DLLS = ("nvngx", "_nvngx", "nvngx_dlss", "nvapi64")
UPSCALE_XESS = "wl_xess_official.dll"
NV_SIGNATURE_OVERRIDE = "{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}"
# CurrentControlSet is a link to ControlSet001 in Wine's registry, so only ControlSet001 is written.
NGX_KEYS = ("Software\\NVIDIA Corporation\\Global\\NGXCore",
"System\\ControlSet001\\Services\\nvlddmkm\\NGXCore")
NGX_SIGNATURE_KEYS = ("Software\\NVIDIA Corporation\\Global",
"System\\ControlSet001\\Services\\nvlddmkm")
def upscale_registry(prefix):
"""NVIDIA's NGX core location and its signature override, which DLSS games read to load nvngx.dll (DLSS mode only)."""
path = os.path.join(prefix, "pfx", "system.reg")
if not os.path.isfile(path):
return False
with open(path, encoding="utf-8", errors="replace") as reg:
text = reg.read()
# Section names in Wine's registry files double their backslashes.
present = {line[1:line.find("]")].replace("\\\\", "\\").lower()
for line in text.splitlines() if line.startswith("[") and "]" in line}
stamp = int(time_now())
added = []
for key in NGX_KEYS:
if key.lower() not in present:
added.append("[%s] %d\n\"Enable\"=dword:00000001\n\"FullPath\"=\"C:\\\\windows\\\\system32\"\n"
"\"NGXPath\"=\"C:\\\\windows\\\\system32\"\n" % (key.replace("\\", "\\\\"), stamp))
for key in NGX_SIGNATURE_KEYS:
if key.lower() not in present:
added.append("[%s] %d\n\"%s\"=hex:01\n" % (key.replace("\\", "\\\\"), stamp, NV_SIGNATURE_OVERRIDE))
if not added:
return False
with open(path, "a", encoding="utf-8") as reg:
reg.write("\n" + "\n".join(added))
return True
def time_now():
import time
return time.time()
def upscale_xess(prefix, data):
"""Intel's XeSS runtime beside the bridge: libxess.dll loads wl_xess_official.dll from system32. A hard link
when the prefix is on the same file system as the data, else a copy."""
source = os.path.join(data, "xess", UPSCALE_XESS)
if not os.path.isfile(source):
return "XeSS runtime not downloaded"
target = os.path.join(prefix, "pfx", "drive_c", "windows", "system32", UPSCALE_XESS)
if os.path.isfile(target) and os.path.getsize(target) == os.path.getsize(source):
return None
staged = target + ".droiddeck-tmp"
if os.path.lexists(staged):
os.unlink(staged)
try:
os.link(source, staged)
except OSError:
with open(source, "rb") as src, open(staged, "wb") as dst:
while True:
chunk = src.read(1 << 20)
if not chunk:
break
dst.write(chunk)
os.replace(staged, target)
return None
def upscale_control(engine, sharpness, npu_sync, run=None):
"""The live switch file the layer polls, written from this game's settings at every launch: a file left by the
previous game (or the in-game menu) would otherwise win over them."""
run = run or UPSCALE_RUN
os.makedirs(run, exist_ok=True)
staged = os.path.join(run, "ctrl.%d" % os.getpid())
with open(staged, "w") as f:
f.write("enabled=1\nbackend=%s\nsharpness=%.2f\nnpu_sync=%d\n" % (engine, sharpness / 100.0, 1 if npu_sync else 0))
os.replace(staged, os.path.join(run, "ctrl"))
def upscale_settings(env, prefix):
"""The game's upscaler choice -> DLL overrides, bridge folder, layer switch and the files the layer reads."""
mode = (env.get("DROIDDECK_UPSCALE_MODE") or "").strip().lower()
if mode not in UPSCALE_MODES:
return env, []
notes = []
bridges = UPSCALE_ROOT + "/bridges"
data = UPSCALE_ROOT + "/data"
if not os.path.isfile(os.path.join(bridges, "x86_64-windows", "libxess.dll")):
return env, ["in-game upscaler chosen but its bridge pack is not installed; launched without it"]
result = dict(env)
engine = (env.get("DROIDDECK_UPSCALE_ENGINE") or "").strip().lower()
if engine not in UPSCALE_ENGINES:
engine = "fsr4_1_lite_gpu"
if engine in UPSCALE_NPU_FALLBACK and env.get("DROIDDECK_UPSCALE_NPU") != "1":
notes.append("no usable NPU on this device: %s runs as %s" % (engine, UPSCALE_NPU_FALLBACK[engine]))
engine = UPSCALE_NPU_FALLBACK[engine]
try:
sharpness = min(100, max(0, int(env.get("DROIDDECK_UPSCALE_SHARPNESS") or "55")))
except ValueError:
sharpness = 55
result["DROIDDECK_UPSCALE"] = "1"
result["DROIDDECK_UPSCALE_DIR"] = data + "/fsr4"
result["DROIDDECK_UPSCALE_BACKEND"] = engine
result["DROIDDECK_UPSCALE_ENGINE"] = engine
result["DROIDDECK_UPSCALE_SHARPNESS"] = "%.2f" % (sharpness / 100.0)
result["DROIDDECK_UPSCALE_NPU_SYNC"] = "sync" if env.get("DROIDDECK_UPSCALE_NPU_SYNC") == "1" else "async"
result["DROIDDECK_UPSCALE_PRESET"] = "auto"
result["DROIDDECK_UPSCALE_POWER"] = env.get("DROIDDECK_UPSCALE_POWER") or "balanced"
result["DROIDDECK_UPSCALE_CTRL_FILE"] = UPSCALE_RUN + "/ctrl"
result["DROIDDECK_UPSCALE_STATUS_FILE"] = UPSCALE_RUN + "/status"
result["DROIDDECK_UPSCALE_NATIVELIB_DIR"] = data + "/jni"
result["DROIDDECK_UPSCALE_VRAM_OVERRIDE"] = "0"
result["ADSP_LIBRARY_PATH"] = data + "/fsr4/adsp;/vendor/dsp/cdsp;/vendor/lib/rfsa/adsp;/system/lib/rfsa/adsp"
own = result.get("WINEDLLPATH")
result["WINEDLLPATH"] = bridges + (":" + own if own else "")
overrides = ["%s=b,n" % name for name in UPSCALE_FSR_DLLS] + ["wl_xess_official=n"]
dxvk = None
if mode == "dlss":
overrides += ["%s=b,n" % name for name in UPSCALE_DLSS_DLLS]
result["DROIDDECK_UPSCALE_SPOOF_DLSS"] = "1"
result["DROIDDECK_UPSCALE_GPU_SPOOF"] = "rtx"
result["PROTON_ENABLE_NVAPI"] = "1"
result["DXVK_ENABLE_NVAPI"] = "1"
result["WINE_HIDE_NVIDIA_GPU"] = "0"
dxvk = 'dxgi.hideNvidiaGpu = False; dxgi.customVendorId = 10de; dxgi.customDeviceId = 1f08; dxgi.customDeviceDesc = "NVIDIA GeForce RTX 2060"'
if env.get("DROIDDECK_UPSCALE_SIGFIX") == "1":
result["DROIDDECK_UPSCALE_SIGFIX"] = "1"
try:
if prefix and upscale_registry(prefix):
notes.append("NVIDIA NGX registry entries added to the prefix (DLSS mode)")
except OSError as error:
notes.append("NGX registry entries not written (%s)" % error)
elif mode == "native":
result["DROIDDECK_UPSCALE_SPOOF_DLSS"] = "0"
result["DROIDDECK_UPSCALE_GPU_SPOOF"] = "rdna4"
result.setdefault("VKD3D_SHADER_MODEL", "6_8")
dxvk = 'dxgi.customVendorId = 1002; dxgi.customDeviceId = 7550; dxgi.customDeviceDesc = "AMD Radeon RX 9070 XT"'
else:
result["DROIDDECK_UPSCALE_SPOOF_DLSS"] = "0"
result["DROIDDECK_UPSCALE_GPU_SPOOF"] = "off"
if dxvk:
current = result.get("DXVK_CONFIG", "").strip().rstrip(";").strip()
result["DXVK_CONFIG"] = current + "; " + dxvk if current else dxvk
own = result.get("WINEDLLOVERRIDES")
result["WINEDLLOVERRIDES"] = (own + ";" if own else "") + ";".join(overrides)
# Intel's runtime goes into every upscaler game once it is downloaded, so XeSS 3 also works when it is
# picked in the in-game menu; a game started on XeSS 3 without it falls back to FSR.
if prefix and (engine == "xess3_gpu" or os.path.isfile(os.path.join(data, "xess", UPSCALE_XESS))):
try:
problem = upscale_xess(prefix, data)
except OSError as error:
problem = str(error)
if problem and engine == "xess3_gpu":
notes.append("XeSS: %s; the layer falls back to FSR" % problem)
try:
upscale_control(engine, sharpness, env.get("DROIDDECK_UPSCALE_NPU_SYNC") == "1")
except OSError as error:
notes.append("upscaler control file not written (%s)" % error)
notes.append("in-game upscaler: mode %s, engine %s, sharpness %d%%" % (mode, engine, sharpness))
return result, notes
DIRT_GAMES = {"dirt3_game": "dirt3", "showdown": "dirtshowdown", "showdown_avx": "dirtshowdown"}
DIRT_WS2 = "/usr/local/lib/droiddeck-dirt/ws2_32.dll"
DIRT_MARKER = b"droiddeck-dirt-ws2_32"
@@ -1771,6 +1941,9 @@ def main():
env = dict(env, **installer)
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
if waiting:
env, upscale_notes = upscale_settings(env, prefix_path)
for note in upscale_notes:
print("droiddeck-game-env: " + note, file=sys.stderr)
before_debug = env
env = apply_game_debug_logs(env, config, debug_dir)
if env is not before_debug:
@@ -1149,7 +1149,6 @@ case $mode in
droiddeck-steam-library "$steam_root" || true
step "setting up the ARM64 Proton compatibility tool"
steam-compatibility "$steam_root" || true
steam-compatibility "$steam_root" --seed-arm64-tools || true
if [ -z "${DD_DESKTOP:-}" ] && [ "${DD_STEAM_UI:-}" != desktop ]; then
droiddeck-steam-ui-scale "$steam_root" "${DD_WIDTH:-1280}" "${DD_HEIGHT:-720}" || true
fi
@@ -5,7 +5,6 @@ import re
import runpy
import shutil
import sys
import tempfile
TOOL = "droiddeck-proton-arm64"
TOOL_11 = "droiddeck-proton-11-arm64"
@@ -27,8 +26,6 @@ SNIPER_APPID = "1628350"
SLR4_APPID = "4183110"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID)
REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES
ARM64_TOOL_DEPENDENCIES = (("1826330", "Proton EasyAntiCheat Runtime"),
("1070560", "Steam Linux Runtime 1.0 (scout)"))
# "0" = the app's "Valve Proton only when needed": Valve's ARM64 Proton is fetched only for a title or
# default set to a tool built from it, or while no own Proton build is installed.
VALVE_PROTON_ENV = "DD_VALVE_PROTON"
@@ -1015,15 +1012,10 @@ def manifest_text(appid, name, installdir, bare=False):
return text[:-2] + ' "AutoUpdateBehavior" "1"\n}\n' if bare else text
def manifest_paths(steam_root, app):
for library in libraries(steam_root):
yield os.path.join(library, "steamapps", "appmanifest_%s.acf" % app)
def app_manifest(steam_root, app):
for path in manifest_paths(steam_root, app):
for library in libraries(steam_root):
try:
with open(path, encoding="utf-8", errors="replace") as f:
with open(os.path.join(library, "steamapps", "appmanifest_%s.acf" % app), encoding="utf-8", errors="replace") as f:
return tokenize(f.read())
except OSError:
continue
@@ -1038,57 +1030,6 @@ def manifest_flags(tokens):
return 0
def installed_manifest(path):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return bool(manifest_flags(tokenize(f.read())) & FULLY_INSTALLED)
except OSError:
return False
def seed_unavailable_arm64_tools(steam_root):
entries = appinfo_entries(os.path.join(steam_root, "appcache", "appinfo.vdf"),
[app for app, _ in ARM64_TOOL_DEPENDENCIES])
steamapps = os.path.join(steam_root, "steamapps")
os.makedirs(steamapps, exist_ok=True)
seeded = []
for app, display in ARM64_TOOL_DEPENDENCIES:
entry = entries.get(app)
if entry is not None:
if entry["type"] not in ("", "tool"):
continue
if "arm64" in entry["osarch"] or "aarch64" in entry["osarch"]:
continue
existing = [p for p in manifest_paths(steam_root, app) if os.path.isfile(p)]
if any(installed_manifest(p) for p in existing):
continue
name = (entry or {}).get("name") or display
installdir = (entry or {}).get("installdir") or name
path = existing[0] if existing else os.path.join(steamapps, "appmanifest_%s.acf" % app)
temporary = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8",
dir=os.path.dirname(path),
prefix=".appmanifest_", delete=False) as f:
temporary = f.name
f.write(manifest_text(app, name, installdir, True))
if existing:
os.replace(temporary, path)
else:
os.link(temporary, path)
except OSError as e:
print("steam-compatibility: could not mark %s installed (%s)" % (app, e))
continue
finally:
if temporary is not None:
try:
os.unlink(temporary)
except OSError:
pass
seeded.append(app)
return seeded
def valve_proton_on_demand():
return os.environ.get(VALVE_PROTON_ENV) == "0"
@@ -1860,11 +1801,6 @@ def main():
steam_root = sys.argv[1]
if "--valve-proton-needed" in sys.argv[2:]:
sys.exit(0 if valve_proton_needed(steam_root) else 1)
if "--seed-arm64-tools" in sys.argv[2:]:
seeded = seed_unavailable_arm64_tools(steam_root)
if seeded:
print("steam-compatibility: marked unavailable ARM64 tool(s) installed: %s" % ", ".join(seeded))
return
if "--x64" in sys.argv[2:]:
x64_repoint(steam_root, os.environ.get("DD_COMPAT_TOOL"), "--live" in sys.argv[2:])
return
+2 -4
View File
@@ -452,8 +452,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
char resolved_target[PATH_MAX];
// Only intercept binaries/scripts within DDNATV_ROOT
if ((g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(filename) ||
is_bound_guest_program(target)) {
if ((g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(filename)) {
struct exec_probe probe;
const char *elf_target = select_exec_target(target, resolved_target, sizeof(resolved_target), &probe);
if (probe.is_elf && !probe.is_dynamic) static_elf = elf_target;
@@ -970,8 +969,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
}
char *const *orig_ep = envp ? envp : environ;
int in_root = (g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(path) ||
is_bound_guest_program(target);
int in_root = (g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(path);
struct exec_probe probe;
char resolved_target[PATH_MAX];
-8
View File
@@ -983,14 +983,6 @@ static int is_host_interpreter(const char *interp, const char *rewritten) {
return probe.android_interp;
}
static int is_bound_guest_program(const char *path) {
if (g_ddnatv_root[0] == '\0' || !is_identity_bound_path(path)) return 0;
struct exec_probe probe;
probe_exec_file(path, &probe);
if (probe.is_elf) return probe.is_dynamic && !probe.android_interp;
return probe.n >= 2 && probe.hdr[0] == '#' && probe.hdr[1] == '!';
}
// argv for running `script` with its interpreter: interp [arg] script args... (the script's own
// argv[0] is dropped, as the kernel does). free() the result.
static char **build_script_argv(const char *interp, const char *interp_arg, const char *script, char *const argv[]) {
-7
View File
@@ -234,13 +234,6 @@ static int is_mapped_guest_path(const char *path) {
return 0;
}
static int is_identity_bound_path(const char *path) {
if (!path || path[0] != '/') return 0;
for (int i = 0; i < g_nbinds; i++)
if (g_binds[i].identity && is_path_prefix(path, g_binds[i].dst, g_binds[i].dst_len)) return 1;
return 0;
}
// Android's own mounts and files, which must never be redirected into the rootfs.
// `path` starts with '/'; a prefix can only match when its second character does.
static int is_android_host_path(const char *path) {
+5
View File
@@ -98,6 +98,11 @@ pack powervr "$repo/app/src/main/assets/hybris" runtime.tzst version.txt
[ ! -f "$linuxfs/droiddeck-ubisoft/droiddeck-upc.exe" ] || pack ubisoft "$linuxfs/droiddeck-ubisoft" droiddeck-upc.exe
[ ! -f "$linuxfs/droiddeck-rockstar/Launcher64.exe" ] || pack rockstar "$linuxfs/droiddeck-rockstar" Launcher32.exe Launcher64.exe
[ ! -f "$linuxfs/droiddeck-dirt/ws2_32.dll" ] || pack dirt "$linuxfs/droiddeck-dirt" ws2_32.dll
upscale=(_nvngx.dll amd_fidelityfx_dx12.dll amd_fidelityfx_loader_dx12.dll amd_fidelityfx_upscaler_dx12.dll
amd_fidelityfx_upscaler_vk.dll amd_fidelityfx_vk.dll ffx_fsr2_api_x64.dll ffx_fsr3upscaler_x64.dll
libxess.dll nvapi64.dll nvngx.dll nvngx_dlss.dll)
[ ! -f "$linuxfs/droiddeck-upscale/bridges/x86_64-windows/nvngx.dll" ] || pack upscale "$linuxfs/droiddeck-upscale" \
"${upscale[@]/#/bridges/x86_64-windows/}" "${upscale[@]/#/bridges/aarch64-windows/}"
[ ! -f "$linuxfs/droiddeck-epic/EpicGamesLauncher.exe" ] || pack epic "$linuxfs/droiddeck-epic" EpicGamesLauncher.exe
mkdir "$work/butler"
-1
View File
@@ -32,7 +32,6 @@ def source_assets(overlay=OVERLAY):
result[desktop / name] = 'assets/linuxfs/usr/local/bin/' + name
result[desktop / 'firefox-droiddeck.js'] = 'assets/linuxfs/usr/lib/firefox/defaults/pref/droiddeck.js'
result[desktop / 'droiddeck-clipboard.desktop'] = 'assets/linuxfs/etc/xdg/autostart/droiddeck-clipboard.desktop'
result[desktop / 'droiddeck-return-gaming.desktop'] = 'assets/linuxfs/usr/share/applications/droiddeck-return-gaming.desktop'
result[desktop / 'fastfetch.jsonc'] = 'assets/linuxfs/etc/xdg/fastfetch/config.jsonc'
result[overlay.parent.parent / 'mangoapp/mangoapp'] = 'assets/linuxfs/usr/local/bin/mangoapp'
return result
+5 -3
View File
@@ -16,17 +16,19 @@ PACKS = Path('app/build/packs')
PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet',
'assets/linuxfs/usr/local/lib/droiddeck-ubisoft/': 'ubisoft', 'assets/linuxfs/usr/local/lib/droiddeck-rockstar/': 'rockstar',
'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt', 'assets/linuxfs/usr/local/lib/droiddeck-epic/': 'epic',
'assets/linuxfs/usr/local/lib/droiddeck-upscale/': 'upscale',
'assets/directaudio/': 'directaudio', 'assets/hybris/': 'powervr'}
# DrWeb flags proot itself as Tool.Linux.Proot; the app runs the pack's copy through Android's linker.
PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so')}
# The loader is execve'd, which targetSdk 29+ allows only from the APK's native library directory.
PROOT_LOADER = {'lib/arm64-v8a/libproot-loader.so': 'libproot-loader.so'}
PACKED_LIBRARIES = ['lib/arm64-v8a/libopencv_java4.so', 'lib/arm64-v8a/libmediapipe_tasks_jni.so']
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic']
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic',
'upscale']
SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst',
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/upscale', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
@@ -253,7 +255,7 @@ def windows_binaries(package):
def check_apk(apk, root=ROOT):
data = verify(root)
packs = {name: pack_digests(root, name) for name in PACK_NAMES
if name not in ('ubisoft', 'rockstar', 'dirt', 'epic') or (root / PACKS / (name + '.tar.zst')).is_file()}
if name not in ('ubisoft', 'rockstar', 'dirt', 'epic', 'upscale') or (root / PACKS / (name + '.tar.zst')).is_file()}
for name, rel in PROOT_LOADER.items():
if packs['proot'].get(rel) != data['outputs'][name]['sha256']:
raise ValueError('Add-on pack proot is missing or has a stale ' + rel)
@@ -1,293 +0,0 @@
"""A commit whose dma-buf the client's GPU is still writing is held until the buffer polls readable.
The compiled functions come from compositor.c; libwayland's lists and event loop, poll and the clock are faked.
"""
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[2] / 'app/src/main/cpp/waylandcomp/src/compositor.c'
def function(text, name):
match = re.search(r'^(?:static )?[^\n;]+\b' + name + r'\([^;]*?\)\s*\{', text, re.M)
if not match:
raise AssertionError('Production function not found: ' + name)
pos = text.index('{', match.start())
depth, end = 1, pos + 1
while depth:
depth += (text[end] == '{') - (text[end] == '}')
end += 1
return text[match.start():end]
def block(text, start):
begin = text.index(start)
return text[begin:text.index('\n};\n', begin) + 4]
HARNESS = r'''
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#define DAMAGE_RECTS 4
#define POLLIN 1
#define F_DUPFD_CLOEXEC 1030
#define WL_EVENT_READABLE 1
struct pollfd { int fd; short events, revents; };
struct wl_list { struct wl_list *prev, *next; };
struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); };
static void wl_list_init(struct wl_list *l) { l->prev = l->next = l; }
static void wl_list_remove(struct wl_list *l) { l->prev->next = l->next; l->next->prev = l->prev; l->prev = l->next = NULL; }
static void wl_list_insert(struct wl_list *list, struct wl_list *elm) {
elm->prev = list; elm->next = list->next; list->next = elm; elm->next->prev = elm;
}
static void wl_list_insert_list(struct wl_list *list, struct wl_list *other) {
if (other->next == other) return;
other->next->prev = list; other->prev->next = list->next; list->next->prev = other->prev; list->next = other->next;
}
static int wl_list_length(const struct wl_list *l) { int n = 0; for (struct wl_list *e = l->next; e != l; e = e->next) n++; return n; }
#define wl_container_of(ptr, sample, member) (__typeof__(sample))((char *)(ptr) - offsetof(__typeof__(*sample), member))
struct dmabuf_buffer { int fd[4]; int n_planes; int ahb; };
struct wl_resource { struct wl_list link; struct wl_listener *listener; struct dmabuf_buffer *db; int released, destroyed; };
static struct wl_resource *from_link(struct wl_list *l) { return wl_container_of(l, (struct wl_resource *)0, link); }
#define wl_resource_for_each_safe(r, t, list) \
for (r = from_link((list)->next), t = from_link(r->link.next); &r->link != (list); r = t, t = from_link(t->link.next))
static void wl_resource_destroy(struct wl_resource *r) { wl_list_remove(&r->link); r->destroyed = 1; }
static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) { r->listener = l; wl_list_init(&l->link); }
static void client_destroys(struct wl_resource *r) {
if (r->listener) { struct wl_listener *l = r->listener; r->listener = NULL; l->notify(l, r); }
}
static int ready[64], dup_of[64], next_dup = 40, closed[64];
static int poll(struct pollfd *p, unsigned n, int timeout) {
if (n != 1 || timeout != 0 || p->events != POLLIN) { puts("FAIL poll args"); exit(1); }
return ready[p->fd] ? 1 : 0;
}
static int fcntl(int fd, int cmd, int arg) { (void)cmd; (void)arg; dup_of[next_dup] = fd; return next_dup++; }
static int close(int fd) { closed[fd]++; return 0; }
struct wl_event_source { int fd; int (*fd_cb)(int, uint32_t, void *); int (*timer_cb)(void *); void *data; int armed_ms, removed; };
struct wl_event_loop;
struct wl_display;
static struct wl_display *g_display;
static struct wl_event_source sources[32];
static int n_sources;
static struct wl_event_loop *wl_display_get_event_loop(struct wl_display *d) { (void)d; return NULL; }
static struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd, uint32_t mask,
int (*cb)(int, uint32_t, void *), void *data) {
(void)l; (void)mask; struct wl_event_source *s = &sources[n_sources++]; memset(s, 0, sizeof(*s));
s->fd = fd; s->fd_cb = cb; s->data = data; return s;
}
static struct wl_event_source *wl_event_loop_add_timer(struct wl_event_loop *l, int (*cb)(void *), void *data) {
(void)l; struct wl_event_source *s = &sources[n_sources++]; memset(s, 0, sizeof(*s));
s->fd = -1; s->timer_cb = cb; s->data = data; return s;
}
static int wl_event_source_timer_update(struct wl_event_source *s, int ms) { s->armed_ms = ms; return 0; }
static int wl_event_source_remove(struct wl_event_source *s) { s->removed = 1; return 0; }
static void dispatch(int timers_expire) {
for (int i = 0; i < n_sources; i++) {
struct wl_event_source *s = &sources[i];
if (s->removed) continue;
if (s->fd_cb && ready[dup_of[s->fd]]) s->fd_cb(s->fd, WL_EVENT_READABLE, s->data);
else if (s->timer_cb && s->armed_ms && timers_expire) { s->armed_ms = 0; s->timer_cb(s->data); }
}
}
static int64_t clock_ns;
static int64_t now_ns(void) { return clock_ns; }
static struct { unsigned replaced; } g_pace;
static struct { unsigned commit_waits, commit_wait_limits; int64_t commit_wait_ns, commit_wait_max_ns; } g_perf;
static int logged;
static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; logged++; }
static void send_buffer_release(struct wl_resource *r) { r->released++; }
static unsigned feedback_discard_all(struct wl_list *list) {
unsigned n = 0; struct wl_resource *r, *t; wl_resource_for_each_safe(r, t, list) { wl_resource_destroy(r); n++; } return n;
}
static struct dmabuf_buffer *get_dmabuf(struct wl_resource *r) { return r ? r->db : NULL; }
static int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b) { return b->ahb; }
static int64_t rect_area(const int32_t *r, int bw, int bh) { (void)bw; (void)bh; return (int64_t)r[2] * r[3]; }
struct damage_list { int32_t r[DAMAGE_RECTS][4]; int n; };
struct surface {
struct wl_resource *resource, *xdg_toplevel;
int toplevel_committed;
struct wl_resource *pending_buffer;
struct wl_listener pending_buffer_destroy;
int pending_attach, pending_src_set, pending_dst_set, pending_opaque_set;
float pending_src[4];
int pending_dst[2], pending_opaque[4];
struct damage_list pending_damage_buf, pending_damage_local;
struct wl_list pending_frames, pending_feedback;
struct surface_state *waiting;
struct wl_event_source *waiting_source, *waiting_timer;
int waiting_fd;
int64_t waiting_since_ns;
};
static void send_toplevel_configure(struct surface *s) { (void)s; }
struct wl_client;
static struct surface surf;
STATE_STRUCT
static int applies, applied_attach, applied_frames, applied_opaque, applied_damage;
static struct wl_resource *applied_buffer;
static void surface_state_apply(struct surface *s, struct surface_state *st);
FUNCTIONS
static void surface_state_apply(struct surface *s, struct surface_state *st) {
(void)s;
applies++;
applied_attach = st->attach;
applied_buffer = st->attach ? st->buffer : NULL;
applied_frames = wl_list_length(&st->frames);
applied_opaque = st->opaque_set ? st->opaque[2] : -1;
applied_damage = st->damage_buf.n;
if (st->attach) { wl_list_remove(&st->buffer_destroy.link); wl_list_init(&st->buffer_destroy.link); }
struct wl_resource *r, *t;
wl_resource_for_each_safe(r, t, &st->frames) wl_resource_destroy(r);
feedback_discard_all(&st->feedback);
}
static struct wl_resource frame_res[16];
static int n_frames;
static void attach(struct wl_resource *b) {
if (surf.pending_buffer) wl_list_remove(&surf.pending_buffer_destroy.link);
wl_list_init(&surf.pending_buffer_destroy.link);
surf.pending_buffer = b; surf.pending_attach = 1;
}
static void frame(void) { struct wl_resource *f = &frame_res[n_frames++]; wl_list_insert(surf.pending_frames.prev, &f->link); }
static void damage(int w) { surf.pending_damage_buf.r[surf.pending_damage_buf.n][2] = w;
surf.pending_damage_buf.r[surf.pending_damage_buf.n][3] = 1; surf.pending_damage_buf.n++; }
static void commit(void) { surface_commit(NULL, NULL); }
#define CHECK(c, what) do { if (!(c)) { printf("FAIL %s (line %d)\n", what, __LINE__); return 1; } } while (0)
int main(void) {
wl_list_init(&surf.pending_frames); wl_list_init(&surf.pending_feedback);
wl_list_init(&surf.pending_buffer_destroy.link);
surf.waiting_fd = -1;
struct dmabuf_buffer d1 = {{10, -1}, 1, 0}, d2 = {{11, -1}, 1, 0}, d3 = {{12, -1}, 1, 0}, dz = {{13, -1}, 1, 1};
struct wl_resource b1 = {.db = &d1}, b2 = {.db = &d2}, b3 = {.db = &d3}, bz = {.db = &dz};
ready[10] = 1;
attach(&b1); frame(); commit();
CHECK(applies == 1 && applied_buffer == &b1 && applied_frames == 1 && !surf.waiting && n_sources == 0, "ready buffer");
ready[11] = 0;
clock_ns = 1000000;
attach(&b2); frame(); damage(5); commit();
CHECK(applies == 1 && surf.waiting && surf.waiting_fd >= 40 && dup_of[surf.waiting_fd] == 11, "held");
CHECK(sources[0].armed_ms == 0 && sources[1].armed_ms == 1000, "waits on the buffer with a 1 s limit");
dispatch(0);
CHECK(applies == 1, "nothing before the writes end");
clock_ns = 4000000;
ready[11] = 1;
dispatch(0);
CHECK(applies == 2 && applied_buffer == &b2 && applied_frames == 1 && applied_damage == 1 && !surf.waiting, "applied once ready");
CHECK(closed[40] == 1 && sources[0].removed && sources[1].removed, "wait cleaned up");
CHECK(g_perf.commit_waits == 1 && g_perf.commit_wait_max_ns == 3000000, "wait counted");
ready[11] = 0; ready[12] = 0;
attach(&b2); frame(); damage(7); commit();
attach(&b3); frame(); damage(9); commit();
CHECK(applies == 2 && b2.released == 1 && dup_of[surf.waiting_fd] == 12, "replaced while waiting");
ready[12] = 1;
dispatch(0);
CHECK(applies == 3 && applied_buffer == &b3 && applied_frames == 2 && applied_damage == 2, "newest shown with both callbacks");
CHECK(g_perf.commit_waits == 2, "merged wait counted once");
ready[11] = 0;
attach(&b2); commit();
surf.pending_opaque[2] = 640; surf.pending_opaque_set = 1; frame(); commit();
CHECK(applies == 3 && b2.released == 1 && dup_of[surf.waiting_fd] == 11, "the waiting buffer is not released");
ready[11] = 1;
dispatch(0);
CHECK(applies == 4 && applied_buffer == &b2 && applied_opaque == 640 && applied_frames == 1, "buffer kept, opaque applied");
g_zero_copy_shown = &surf;
attach(&bz); commit();
CHECK(applies == 5 && applied_buffer == &bz && !surf.waiting && g_unwaited == &surf, "zero-copy buffer");
g_zero_copy_shown = NULL;
ready[13] = 0;
attach(&bz); commit();
CHECK(applies == 5 && surf.waiting, "a droiddeck-ahb buffer not shown zero-copy waits");
ready[13] = 1;
dispatch(0);
CHECK(applies == 6 && !g_unwaited, "waited buffer clears the mark");
ready[13] = 0;
ready[10] = 0;
attach(&b1); frame(); commit();
client_destroys(&b1);
ready[10] = 1;
dispatch(0);
CHECK(applies == 7 && !applied_attach && applied_frames == 1, "destroyed buffer dropped from the commit");
ready[11] = 0;
attach(&b2); commit();
dispatch(1);
CHECK(applies == 8 && applied_buffer == &b2 && g_perf.commit_wait_limits == 1 && logged == 1 && !surf.waiting, "limit");
ready[11] = 0; ready[12] = 0;
clock_ns = 10000000000;
attach(&b2); commit();
CHECK(applies == 8 && sources[n_sources - 1].armed_ms == 1000, "held again");
clock_ns += 600000000;
attach(&b3); commit();
CHECK(applies == 8 && surf.waiting && sources[n_sources - 1].armed_ms == 400, "a newer commit keeps the first deadline");
clock_ns += 500000000;
attach(&b2); commit();
CHECK(applies == 9 && applied_buffer == &b2 && g_perf.commit_wait_limits == 2 && !surf.waiting, "commits past the deadline are applied at once");
puts("PASS");
return 0;
}
'''
class CommitWaitsForClientWritesTest(unittest.TestCase):
def test_commits_wait_for_the_clients_gpu_writes(self):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if not compiler:
self.skipTest('A host C compiler is required')
source = SOURCE.read_text()
functions = '\n'.join(re.search(pattern, source, re.M).group(0) for pattern in
(r'^#define COMMIT_WAIT_LIMIT_MS .*$', r'^static struct surface \*g_zero_copy_shown, \*g_unwaited;$')) + '\n' + '\n'.join(
function(source, name) for name in
('note_damage', 'on_state_buffer_destroyed', 'surface_state_take', 'state_unfinished_fd',
'surface_state_discard', 'surface_state_merge', 'surface_wait_stop', 'surface_wait_end', 'on_commit_ready',
'on_commit_wait_limit', 'surface_wait_start', 'surface_commit'))
probe = HARNESS.replace('STATE_STRUCT', block(source, 'struct surface_state {')).replace('FUNCTIONS', functions)
probe = probe.replace('struct surface *s = wl_resource_get_user_data(r);', 'struct surface *s = &surf; (void)r;')
with tempfile.TemporaryDirectory(prefix='droiddeck-commit-wait-') as temp:
folder = Path(temp)
(folder / 'probe.c').write_text(probe)
built = subprocess.run([compiler, '-std=gnu11', '-Wall', '-Wextra', '-Wno-unused-parameter', '-Wno-unused-function',
str(folder / 'probe.c'), '-o', str(folder / 'probe')],
capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
run = subprocess.run([str(folder / 'probe')], capture_output=True, text=True, timeout=10)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
self.assertEqual(run.stdout.strip(), 'PASS')
def test_scenes_settle_an_unwaited_buffer_before_copying_it(self):
body = function(SOURCE.read_text(), 'render_scene').splitlines()
copies = [i for i, line in enumerate(body) if 'vkp_render(w, h, dl.d, dl.n)' in line]
self.assertGreaterEqual(len(copies), 4)
for i in copies:
self.assertTrue(any('settle_unwaited();' in line for line in body[max(0, i - 3):i]), body[i])
text = '\n'.join(body)
self.assertIn('if (hdr_route == 1 || hdr_route == 2) settle_unwaited();', text)
self.assertIn('settle_unwaited();\n render_stream();', text)
self.assertIn('if (r == 0 && !fg_pass) g_zero_copy_shown = ls;\n else settle_unwaited();', text)
if __name__ == '__main__':
unittest.main()
-75
View File
@@ -1,75 +0,0 @@
import os
import re
import shlex
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DESKTOP = ROOT / "tools/linuxfs/desktop"
SCRIPT = (DESKTOP / "droiddeck-desktop").read_text()
ENTRY = (DESKTOP / "droiddeck-return-gaming.desktop").read_text()
class DesktopReturnGamingTest(unittest.TestCase):
def session(self, logout, rc=0, bottom=False):
with tempfile.TemporaryDirectory() as tmp:
run = Path(tmp, "run")
launched = Path(tmp, "launched")
exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1)
inner = shlex.split(exec_line)[2].replace("dbus-send", "true")
plasma = Path(tmp, "plasma")
plasma.write_text("#!/bin/sh\n%s\nexit %d\n" % (inner if logout == "return" else ":", rc))
plasma.chmod(0o755)
steam = Path(tmp, "steam-launch")
steam.write_text('#!/bin/sh\necho "$*" > %s\n' % launched)
steam.chmod(0o755)
tail = SCRIPT[SCRIPT.index("return_gaming="):]
tail = tail.replace("dbus-run-session -- startplasma-wayland", str(plasma))
tail = tail.replace("/usr/local/bin/droiddeck-pipewire stop", ":")
tail = tail.replace("/usr/local/bin/droiddeck-steam-launch", str(steam))
tail = tail.replace("sleep 30", ":")
tail = tail.replace("/run/droiddeck", str(run))
plasma.write_text(plasma.read_text().replace("/run/droiddeck", str(run)))
env = {k: v for k, v in os.environ.items() if k != "DD_BOTTOM_DESKTOP"}
if bottom:
env["DD_BOTTOM_DESKTOP"] = "1"
run.mkdir()
(run / "return-gaming").write_text("")
status = subprocess.run(["sh", "-c", tail], env=env, capture_output=True, text=True).returncode
return status, launched.read_text().strip() if launched.exists() else None, (run / "return-gaming").exists()
def test_return_to_gaming_mode_opens_steam(self):
self.assertEqual(self.session("return"), (0, "bigpicture", False))
def test_log_out_goes_back_without_steam_even_after_an_earlier_request(self):
self.assertEqual(self.session("logout"), (0, None, False))
def test_a_failed_session_and_the_bottom_desktop_never_open_steam(self):
self.assertEqual(self.session("return", rc=1)[:2], (1, None))
self.assertEqual(self.session("return", bottom=True)[:2], (0, None))
def test_the_logout_request_outlives_starting_the_shutdown_service(self):
exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1)
call = shlex.split(shlex.split(exec_line)[2].split(";")[-1])
self.assertEqual(call[0], "dbus-send")
self.assertIn("--print-reply", call)
def test_a_rejected_logout_request_forgets_the_return_to_gaming_mode(self):
exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1)
with tempfile.TemporaryDirectory() as tmp:
inner = shlex.split(exec_line)[2].replace("/run/droiddeck", tmp)
for sender, kept in (("true", True), ("false", False)):
subprocess.run(["sh", "-c", inner.replace("dbus-send", sender, 1)], check=False)
self.assertEqual(Path(tmp, "return-gaming").exists(), kept)
def test_the_app_ships_the_shortcut_with_the_script(self):
source = (ROOT / "app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt").read_text()
self.assertIn('"usr/share/applications/droiddeck-return-gaming.desktop" to '
'"usr/share/applications/droiddeck-return-gaming.desktop"', source)
self.assertIn("droiddeck-return-gaming.desktop", (ROOT / "tools/release/check_session_assets.py").read_text())
if __name__ == "__main__":
unittest.main()
+3 -21
View File
@@ -29,21 +29,14 @@ PAD_TYPE_STEAM = 1
READER = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <poll.h>
#include <stdio.h>
#include <sys/uio.h>
#include <unistd.h>
ssize_t __read_chk(int fd, void *buffer, size_t size, size_t buffer_size);
int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fds_size);
static int vector_count;
static int fortified;
static ssize_t controller_read(int fd, void *buffer, size_t size)
{
if (fortified)
return __read_chk(fd, buffer, size, size);
if (!vector_count)
return read(fd, buffer, size);
struct iovec vectors[3] = {
@@ -60,8 +53,7 @@ static ssize_t controller_read(int fd, void *buffer, size_t size)
int main(int argc, char **argv)
{
fortified = argc > 1 && argv[1][0] == 'f';
vector_count = argc > 1 && !fortified ? (argv[1][0] == '1' ? 1 : 3) : 0;
vector_count = argc > 1 ? (argv[1][0] == '1' ? 1 : 3) : 0;
struct input_event events[64];
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0) {
@@ -70,17 +62,11 @@ int main(int argc, char **argv)
}
while (controller_read(fd, events, sizeof(events)) > 0)
;
struct pollfd idle = {fd, POLLIN, 0};
if (fortified && __poll_chk(&idle, 1, 0, sizeof(idle)) != 0)
return 3;
puts("ready");
fflush(stdout);
char go;
if (read(0, &go, 1) != 1)
return 1;
struct pollfd ready = {fd, POLLIN, 0};
if (fortified && (__poll_chk(&ready, 1, 1000, sizeof(ready)) != 1 || !(ready.revents & POLLIN)))
return 2;
ssize_t got = controller_read(fd, events, sizeof(events));
for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++)
printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type,
@@ -359,7 +345,7 @@ class FakeinputRingTest(unittest.TestCase):
subprocess.run(["gcc", bits, "-o", str(binary), str(self.tmp / (name + ".c"))], check=True)
return library, binary
def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER, fortified=False):
def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER):
if not virtual:
program = program.replace("event16", "event0")
library, reader = self.build(bits, program, "reader")
@@ -373,7 +359,7 @@ class FakeinputRingTest(unittest.TestCase):
overlay_library = self.tmp / "overlay.so"
subprocess.run(["gcc", bits, "-shared", "-fPIC", "-o", str(overlay_library), str(source)], check=True)
env["LD_PRELOAD"] = str(overlay_library) + ":" + str(library)
command = [str(reader)] + (["fortified"] if fortified else [str(vectors)] if vectors else [])
command = [str(reader)] + ([str(vectors)] if vectors else [])
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
self.addCleanup(process.kill)
self.assertEqual(process.stdout.readline(), "ready\n")
@@ -395,10 +381,6 @@ class FakeinputRingTest(unittest.TestCase):
self.assertEqual(self.read_through("-m64"),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_a_fortified_guest_polls_and_reads_the_ring(self):
self.assertEqual(self.read_through("-m64", virtual=False, fortified=True),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_readv_reads_events_instead_of_the_backing_file(self):
self.assertEqual(self.read_through("-m64", vectors=1),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
+98
View File
@@ -4,6 +4,7 @@ import hashlib
import io
import json
import os
import re
import shutil
from pathlib import Path
import runpy
@@ -24,6 +25,103 @@ STATE = tempfile.TemporaryDirectory()
COMPAT["main"].__globals__["COMPAT_DIR"] = STATE.name
class UpscalerSettingsTest(unittest.TestCase):
def setUp(self):
self.root = tempfile.mkdtemp()
Path(self.root, "bridges/x86_64-windows").mkdir(parents=True)
Path(self.root, "bridges/x86_64-windows/libxess.dll").write_bytes(b"MZ")
self.run = os.path.join(self.root, "run")
self.patch = patch.dict(MODULE["upscale_settings"].__globals__, {"UPSCALE_ROOT": self.root, "UPSCALE_RUN": self.run})
self.patch.start()
def tearDown(self):
self.patch.stop()
shutil.rmtree(self.root)
def test_off_leaves_the_environment_alone(self):
env = {"DROIDDECK_UPSCALE_MODE": "off", "WINEDLLOVERRIDES": "dxgi=n"}
self.assertEqual((env, []), MODULE["upscale_settings"](env, None))
def test_fsr_mode_overrides_the_upscaler_dlls_without_spoofing(self):
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "WINEDLLOVERRIDES": "dxgi=n"}, None)
self.assertEqual("1", env["DROIDDECK_UPSCALE"])
self.assertTrue(env["WINEDLLOVERRIDES"].startswith("dxgi=n;libxess=b,n;"))
self.assertNotIn("nvapi64", env["WINEDLLOVERRIDES"])
self.assertNotIn("DXVK_CONFIG", env)
self.assertEqual(self.root + "/bridges", env["WINEDLLPATH"])
self.assertEqual("off", env["DROIDDECK_UPSCALE_GPU_SPOOF"])
def test_dlss_mode_spoofs_an_nvidia_gpu(self):
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "dlss", "DXVK_CONFIG": "a = 1"}, None)
self.assertIn("nvngx=b,n", env["WINEDLLOVERRIDES"])
self.assertIn("nvapi64=b,n", env["WINEDLLOVERRIDES"])
self.assertEqual("1", env["PROTON_ENABLE_NVAPI"])
self.assertTrue(env["DXVK_CONFIG"].startswith("a = 1; dxgi.hideNvidiaGpu = False; dxgi.customVendorId = 10de"))
def test_npu_engines_fall_back_to_the_gpu_without_an_npu(self):
env, notes = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "fsr4_1_lite_npu"}, None)
self.assertEqual("fsr4_1_lite_gpu", env["DROIDDECK_UPSCALE_BACKEND"])
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "fsr4_1_lite_npu",
"DROIDDECK_UPSCALE_NPU": "1"}, None)
self.assertEqual("fsr4_1_lite_npu", env["DROIDDECK_UPSCALE_BACKEND"])
def test_without_the_bridge_pack_the_game_starts_without_the_upscaler(self):
os.unlink(os.path.join(self.root, "bridges/x86_64-windows/libxess.dll"))
env = {"DROIDDECK_UPSCALE_MODE": "fsr"}
result, notes = MODULE["upscale_settings"](env, None)
self.assertEqual(env, result)
self.assertTrue(notes)
def test_the_control_file_follows_this_games_settings(self):
Path(self.run).mkdir()
Path(self.run, "ctrl").write_text("enabled=0\nbackend=fsr4_1_lite_gpu\nsharpness=0.55\nnpu_sync=0\n")
_, notes = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "xess3_gpu",
"DROIDDECK_UPSCALE_SHARPNESS": "40"}, None)
self.assertEqual("enabled=1\nbackend=xess3_gpu\nsharpness=0.40\nnpu_sync=0\n", Path(self.run, "ctrl").read_text())
self.assertFalse([n for n in notes if "control file" in n])
def test_the_xess_runtime_goes_into_any_upscaler_game_once_downloaded(self):
prefix = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, prefix, True)
Path(prefix, "pfx/drive_c/windows/system32").mkdir(parents=True)
source = Path(self.root, "data/xess", MODULE["UPSCALE_XESS"])
source.parent.mkdir(parents=True)
source.write_bytes(b"MZ-xess")
MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "fsr4_1_lite_gpu"}, prefix)
target = Path(prefix, "pfx/drive_c/windows/system32", MODULE["UPSCALE_XESS"])
self.assertEqual(b"MZ-xess", target.read_bytes())
self.assertEqual(source.stat().st_ino, target.stat().st_ino)
def test_a_game_started_on_xess_without_the_runtime_says_so(self):
prefix = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, prefix, True)
Path(prefix, "pfx/drive_c/windows/system32").mkdir(parents=True)
_, notes = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "xess3_gpu"}, prefix)
self.assertTrue([n for n in notes if "XeSS runtime not downloaded" in n])
def test_the_app_stages_every_dll_the_bridge_build_makes(self):
repo = Path(__file__).resolve().parents[2]
build = (repo / "tools/upscale/bridges/build.sh").read_text()
built = set(re.search(r"names=\(([^)]*)\)", build).group(1).split())
kotlin = (repo / "app/src/main/java/com/droiddeck/launcher/session/UpscaleComponent.kt").read_text()
staged = set(re.findall(r'"([A-Za-z0-9_]+\.dll)"', kotlin[kotlin.index("BRIDGE_NAMES"):kotlin.index("BRIDGE_FILES")]))
self.assertEqual(built, staged)
def test_ngx_registry_entries_are_added_once(self):
prefix = tempfile.mkdtemp()
try:
Path(prefix, "pfx").mkdir()
Path(prefix, "pfx/system.reg").write_text("WINE REGISTRY Version 2\n\n[Software\\\\Wine] 1\n")
self.assertTrue(MODULE["upscale_registry"](prefix))
self.assertFalse(MODULE["upscale_registry"](prefix))
text = Path(prefix, "pfx/system.reg").read_text()
self.assertIn("[Software\\\\NVIDIA Corporation\\\\Global\\\\NGXCore]", text)
self.assertIn('"FullPath"="C:\\\\windows\\\\system32"', text)
self.assertNotIn("CurrentControlSet", text)
finally:
shutil.rmtree(prefix)
class SupergiantDotnetReporterTest(unittest.TestCase):
def test_allows_the_builtin_mscoree_for_supergiant_reporter(self):
game = mock.Mock(files={"basecampbugreporter.native.dll"})
@@ -120,14 +120,6 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
script.parent.mkdir(exist_ok=True)
script.write_text(f"#!{interpreter}\n")
script.chmod(0o755)
cls.app_files = tmp / "app-files"
cls.app_files.mkdir()
shutil.copy(cls.probe, cls.app_files / "tool")
shutil.copy(cls.android / "sh", cls.app_files / "android-tool")
for name, interpreter in (("guest.py", GUEST_TOOL), ("android.sh", f"{ANDROID_DIR}/sh")):
(cls.app_files / name).write_text(f"#!{interpreter}\n")
for entry in cls.app_files.iterdir():
entry.chmod(0o755)
@classmethod
def tearDownClass(cls):
@@ -228,32 +220,6 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
call = self.call(how, "/opt/host.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}")
self.assertEqual([HOST_SHELL, HOST_SHELL, str(self.root / "opt/host.sh"), "x"], call)
def test_a_script_on_a_mount_at_its_host_path_runs_with_the_guest_interpreter(self):
script = str(self.app_files / "guest.py")
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, script, "x", binds=f"{self.app_files}:{self.app_files}")
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
self.assertEqual([str(self.root / GUEST_TOOL.lstrip("/")), script, "x"], call[-3:])
def test_a_glibc_program_on_a_mount_at_its_host_path_starts_through_the_guest_ldso(self):
tool = str(self.app_files / "tool")
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, tool, "x", binds=f"{self.app_files}:{self.app_files}")
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
self.assertEqual([tool, "x"], call[-2:])
def test_android_programs_on_a_mount_at_its_host_path_stay_on_the_host(self):
tool = str(self.app_files / "android-tool")
script = str(self.app_files / "android.sh")
sh = str(self.android / "sh")
binds = f"{self.app_files}:{self.app_files}|{self.android}:{ANDROID_DIR}"
for how in ("exec", "spawn"):
with self.subTest(how=how):
self.assertEqual([tool, tool, "x"], self.call(how, tool, "x", binds=binds))
self.assertEqual([sh, sh, script, "x"], self.call(how, script, "x", binds=binds))
def test_an_android_interpreter_reached_through_a_bind_stays_on_the_host(self):
sh = str(self.android / "sh")
for how in ("exec", "spawn"):
@@ -1,205 +0,0 @@
import runpy
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from tools.tests.test_droiddeck_fex import AppInfoTest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
SESSION = BIN / "droiddeck-session"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
EAC = 1826330
SCOUT = 1070560
EAC_ID = str(EAC)
SCOUT_ID = str(SCOUT)
EAC_NAME = "Proton EasyAntiCheat Runtime"
SCOUT_NAME = "Steam Linux Runtime 1.0 (scout)"
def tool(name, osarch="", kind="tool", installdir=None):
return {
"common": {"name": name, "oslist": "linux", "osarch": osarch, "type": kind},
"config": {"installdir": installdir or name},
}
class SteamToolManifestSeedTest(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
self.steam = self.root / "Steam"
(self.steam / "appcache").mkdir(parents=True)
(self.steam / "steamapps").mkdir()
self.entries = {EAC: tool(EAC_NAME), SCOUT: tool(SCOUT_NAME)}
self.write_appinfo()
def write_appinfo(self, entries=None):
COMPAT["APPINFO_CACHE"].clear()
(self.steam / "appcache/appinfo.vdf").write_bytes(
AppInfoTest.appinfo(self.entries if entries is None else entries))
def manifest(self, app, root=None):
return (root or self.steam) / ("steamapps/appmanifest_%s.acf" % app)
def seed(self):
return COMPAT["seed_unavailable_arm64_tools"](str(self.steam))
def test_seeds_bare_manifests_for_unavailable_tool_dependencies(self):
self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID])
for app, name in ((EAC_ID, EAC_NAME), (SCOUT_ID, SCOUT_NAME)):
text = self.manifest(app).read_text()
for expected in ('"appid" "%s"' % app, '"Universe" "1"', '"StateFlags" "4"',
'"name" "%s"' % name, '"installdir" "%s"' % name,
'"AutoUpdateBehavior" "1"'):
self.assertIn(expected, text)
self.assertFalse(self.manifest("976730").exists())
def test_seeding_is_idempotent(self):
self.seed()
first = {app: self.manifest(app).read_text() for app in (EAC_ID, SCOUT_ID)}
self.assertEqual(self.seed(), [])
self.assertEqual({app: self.manifest(app).read_text() for app in first}, first)
def test_a_real_install_in_another_library_is_never_overwritten(self):
other = self.root / "SD"
(other / "steamapps").mkdir(parents=True)
existing = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"4"\n}\n' % SCOUT_ID
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(existing)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertEqual((other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text(), existing)
def test_a_partial_install_in_another_library_is_completed_in_place(self):
other = self.root / "SD"
(other / "steamapps").mkdir(parents=True)
partial = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"2"\n}\n' % SCOUT_ID
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(partial)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertIn('"StateFlags" "4"',
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text())
def test_a_real_install_in_any_library_wins_over_a_partial_one(self):
other = self.root / "SD"
(other / "steamapps").mkdir(parents=True)
partial = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"2"\n}\n' % SCOUT_ID
installed = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"4"\n}\n' % SCOUT_ID
self.manifest(SCOUT_ID).write_text(partial)
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(installed)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.assertEqual(self.seed(), [EAC_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(), partial)
self.assertEqual((other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text(), installed)
def test_a_failed_write_leaves_no_manifest_behind(self):
real_link = COMPAT["os"].link
def fail_for_scout(source, target):
if SCOUT_ID in str(target):
raise OSError("disk full")
return real_link(source, target)
with mock.patch.object(COMPAT["os"], "link", side_effect=fail_for_scout):
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertEqual(sorted(p.name for p in (self.steam / "steamapps").iterdir()),
["appmanifest_%s.acf" % EAC_ID])
self.assertEqual(self.seed(), [SCOUT_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(),
COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True))
def test_new_manifest_publication_preserves_a_concurrent_install(self):
real_link = COMPAT["os"].link
installed = COMPAT["manifest_text"](SCOUT_ID, "Existing tool", "Existing", False)
def publish(source, target):
if SCOUT_ID in str(target):
Path(target).write_text(installed)
return real_link(source, target)
with mock.patch.object(COMPAT["os"], "link", side_effect=publish):
self.assertEqual(self.seed(), [EAC_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(), installed)
self.assertEqual(self.seed(), [])
self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*")))
def test_partial_staged_write_is_not_published_and_retry_repairs(self):
real_temporary = COMPAT["tempfile"].NamedTemporaryFile
def temporary(*args, **kwargs):
output = real_temporary(*args, **kwargs)
real_write = output.write
def write(text):
if SCOUT_ID in text:
real_write(text[:text.index(' "installdir"')])
output.flush()
raise OSError("disk full")
return real_write(text)
output.write = write
return output
with mock.patch.object(COMPAT["tempfile"], "NamedTemporaryFile", side_effect=temporary):
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*")))
self.assertEqual(self.seed(), [SCOUT_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(),
COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True))
def test_failed_replacement_preserves_partial_manifest_and_retry_repairs(self):
partial = '"AppState" { "appid" "%s" "StateFlags" "2" }' % SCOUT_ID
self.manifest(SCOUT_ID).write_text(partial)
with mock.patch.object(COMPAT["os"], "replace", side_effect=OSError("disk full")):
self.assertEqual(self.seed(), [EAC_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(), partial)
self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*")))
self.assertEqual(self.seed(), [SCOUT_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(),
COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True))
def test_tools_with_an_arm64_depot_are_skipped(self):
entries = dict(self.entries)
entries[SCOUT] = tool(SCOUT_NAME, osarch="arm64")
self.write_appinfo(entries)
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
def test_an_app_that_is_not_a_tool_is_skipped(self):
entries = dict(self.entries)
entries[SCOUT] = tool(SCOUT_NAME, kind="game")
self.write_appinfo(entries)
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
def test_missing_appinfo_uses_the_display_names(self):
(self.steam / "appcache/appinfo.vdf").unlink()
COMPAT["APPINFO_CACHE"].clear()
self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID])
self.assertIn('"name" "%s"' % SCOUT_NAME, self.manifest(SCOUT_ID).read_text())
def test_flag_seeds_without_running_full_compatibility_setup(self):
with mock.patch.object(COMPAT["sys"], "argv",
["steam-compatibility", str(self.steam), "--seed-arm64-tools"]):
COMPAT["main"]()
self.assertTrue(self.manifest(EAC_ID).is_file())
self.assertTrue(self.manifest(SCOUT_ID).is_file())
self.assertFalse((self.steam / "compatibilitytools.d").exists())
def test_session_seeds_only_on_the_arm64_client_path(self):
arm64, x64 = SESSION.read_text().split(
" else\n _dd_x64_tool=$(droiddeck-steam-x64 --default-tool)", 1)
self.assertIn('steam-compatibility "$steam_root" --seed-arm64-tools', arm64)
self.assertNotIn("--seed-arm64-tools", x64)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -95,7 +95,7 @@ class SubsurfaceReleaseTest(unittest.TestCase):
def test_compositor_attach_and_commit_use_the_release_hold(self):
self.assertIn('pending_releases_cancel(buffer);', function_body(self.source, 'take_dmabuf'))
commit = function_body(self.source, 'surface_state_apply')
commit = function_body(self.source, 'surface_commit')
self.assertIn('pending_releases_apply(s);', commit)
self.assertLess(commit.index('take_dmabuf(s, db, buffer);'), commit.index('pending_releases_apply(s);'))
self.assertLess(commit.index('buf_trace_attach(buffer);'), commit.index('if (s->role == ROLE_CURSOR)'))
@@ -0,0 +1,9 @@
[Desktop Entry]
Name=Return to Gaming Mode
Comment=Log out of the desktop and go back to Steam
Exec=dbus-send --session --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout
Icon=steamdeck-gaming-return
Terminal=false
Type=Application
StartupNotify=false
NoDisplay=true
+85
View File
@@ -0,0 +1,85 @@
# Upscale bridge DLLs
Windows x86-64 DLLs that stand in for a game's DLSS, FidelityFX (FSR 2, FSR 3, FidelityFX API) and
XeSS libraries inside Wine. They do not upscale anything themselves: each frame's colour, depth,
motion-vector and output images are written into a host-visible Vulkan mailbox buffer, and a
`vkCmdUpdateBuffer` "doorbell" on a marker buffer tells the Android Vulkan layer to record the
upscaler into the game's command buffer. The layer finds both buffers by their sizes and magic
numbers. `fsr4_seam_proto.h` is that contract and is a verbatim copy of the fork's
`app/src/main/cpp/fsr4npu/fsr4_seam_proto.h` (sha256 `a9f614c53ae9209edf0fa9c5acb0a27fdf923c08026362b23f60e1bcb39acd15`).
It must stay byte-identical to the layer's copy. If the layer does not acknowledge a frame,
the bridge blits the render-resolution image to the output (bilinear) so the game never shows
stale memory. D3D12 games reach Vulkan through vkd3d-proton's `ID3D12DXVKInteropDevice1`.
| DLL | Source | Export list | Replaces |
| --- | --- | --- | --- |
| `amd_fidelityfx_vk.dll` | `wl_ffx_bridge.c` | `wl_ffx_bridge.def` | FidelityFX API (`ffxCreateContext`, `ffxDispatch`, ...) |
| `amd_fidelityfx_dx12.dll`, `amd_fidelityfx_upscaler_vk.dll`, `amd_fidelityfx_upscaler_dx12.dll`, `amd_fidelityfx_loader_dx12.dll` | copies of `amd_fidelityfx_vk.dll` | | the same API under the other SDK file names |
| `ffx_fsr3upscaler_x64.dll` | `wl_fsr23_bridge.c` | `ffx_fsr3upscaler_x64.def` | FSR 3.0 / 3.1 upscaler |
| `ffx_fsr2_api_x64.dll` | `wl_fsr23_bridge.c` | `ffx_fsr2_api_x64.def` | FSR 2.0 / 2.1 / 2.2 |
| `libxess.dll` | `wl_xess_bridge.c` | `libxess.def` | Intel XeSS 1.3 / 2.0 (D3D12 + Vulkan) |
| `nvngx.dll` | `wl_ngx_bridge.c` | `nvngx.def` | NVIDIA NGX / DLSS Super Resolution (Vulkan + D3D12) |
| `_nvngx.dll`, `nvngx_dlss.dll` | copies of `nvngx.dll` | | the names games and Streamline load NGX by |
| `nvapi64.dll` | `wl_nvapi_shim.c` (+ `wl_ngx_hooks.h`) | `nvapi64.def` | NVAPI, reporting an RTX 2060 so games offer DLSS |
`wl_fsr23_bridge.c` exports both the FSR 2 and FSR 3 entry points, so both DLLs carry all 21.
`nvngx.dll` exports the 88 `.def` names plus 9 that only its source marks `__declspec(dllexport)`. `build.sh`
fails when a DLL's exports (from `x86_64-w64-mingw32-objdump -p`) differ from its `.def` plus
its source's `dllexport` names.
When the XeSS 3.0 backend is selected, `wl_xess3_direct.h` loads Intel's XeSS SDK runtime as
`wl_xess_official.dll` (from the DLL search path, then `C:\windows\system32`). When it is missing or
fails, the frame goes to the layer flagged `WLFSR4_FLAG_XESS_FALLBACK` (FSR 3.1 on the GPU). That DLL is Intel's prebuilt binary and is not built here.
## Build
```sh
bash tools/upscale/bridges/build.sh OUT
```
Needs `x86_64-w64-mingw32-gcc` (Ubuntu `gcc-mingw-w64-x86-64`) and `python3`. The output is
deterministic (`-s`, `-Wl,--no-insert-timestamp`, linked under the bare DLL name because `ld`
derives the image base from the output path). Every DLL is stamped as a Wine builtin the way
`winebuild --builtin` does it: the 32-byte `"Wine builtin DLL"` signature, zero-padded, at file
offset 0x40 (`pe.py stamp`). Wine then loads them from `WINEDLLPATH` when the override is
`builtin`. The same x86-64 files are installed to `OUT/x86_64-windows/` and
`OUT/aarch64-windows/`, because the ARM64EC Wine loads x86-64 builtins from the latter.
CI builds them with the `upscale-bridges` component recipe into
`app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/`. The APK may not carry
Windows executables (`tools/release/runtime_inputs.py`), so they ship in the `upscale` add-on
pack (`tools/packs/build.sh`), whose entries are `bridges/{x86_64,aarch64}-windows/<dll>`.
## Environment
| Variable | Default | Effect |
| --- | --- | --- |
| `DROIDDECK_UPSCALE_BACKEND` (then `DROIDDECK_UPSCALE_ENGINE`, `WINLATOR_FSR4_BACKEND`, `WINLATOR_FSR4_ENGINE`) | `fsr4_0_npu` | Backend the bridges assume until the layer writes its live control word: `fsr3_gpu`, `xess3_gpu`, `fsr4_0_npu`, `fsr4_1_lite_npu`, `fsr4_1_full_npu`, `fsr4_1_lite_gpu`, `fsr4_1_full_gpu` |
| `DROIDDECK_UPSCALE_VRAM_MB` (then `WINLATOR_FSR4_VRAM_MB`, `WRAPPER_VMEM_MAX_SIZE`) | DXGI adapter 0, else 12 GB | VRAM `nvapi64.dll` reports (512-65536 MB) |
| `DROIDDECK_UPSCALE_SIGFIX=1` | off | `nvapi64.dll` patches the import tables of loaded modules (LoadLibrary*, GetProcAddress, GetFileAttributes*, CreateFileW, Reg*), redirects `nvngx`/`_nvngx` loads to `C:\windows\system32\_nvngx.dll`, fakes the NVIDIA signature-override registry keys, forces `WinVerifyTrust` success and redirects `CryptQueryObject` for `nvngx`/`amd_fidelityfx*`, so games that signature-check NGX load the bridge. Never applied to rdr2.exe, playrdr2.exe or gta5.exe |
| `DROIDDECK_UPSCALE_LOG=1` | off | Hook messages appended to `C:\windows\temp\wl_fsr4_bridge.log` |
## Changes from the fork
- D3D11 NGX reports DLSS unavailable (`SuperSampling.Available` 0, feature requirements
`AdapterUnsupported`, `CreateFeature`/`EvaluateFeature` return
`NVSDK_NGX_Result_FAIL_FeatureNotSupported`). The fork returned success and rendered nothing,
because D3D11 has no route to the Vulkan layer.
- The `nvapi64.dll` hooks are off unless `DROIDDECK_UPSCALE_SIGFIX=1`; the fork always installed them.
- Logging is off unless `DROIDDECK_UPSCALE_LOG=1`; the fork always wrote the log.
- `DROIDDECK_UPSCALE_*` variables are read first, the fork's names after them (`dd_env.h`).
- `fsr4_seam_proto.h` is included from this folder instead of `../fsr4npu/`.
- Built with Ubuntu's MinGW-w64 GCC (msvcrt) instead of the fork's PowerShell script; flags as in
its `build_win_dlls.ps1` plus `-s` and `-Wl,--no-insert-timestamp`. The fork stamped the
signature at install time; here it is stamped at build time.
Seam protocol, struct layouts, magics and backend IDs are unchanged.
## Credits and licence
Ported from [michaelisomer-cyber/Winlator-NeuralScale](https://github.com/michaelisomer-cyber/Winlator-NeuralScale)
at `a0ab6b0f770e1a6786b4e68def46b4edb8baafd0` (`app/src/main/cpp/fsr4npu_win/`), GPL-3.0. That fork
builds on [StevenMXZ/Winlator-Ludashi](https://github.com/StevenMXZ/Winlator-Ludashi). The NGX
and NVAPI shims follow OptiScaler's approach (and fakenvapi's NVAPI interface). These files stay
under the GPL-3.0, the licence of this repository (`LICENSE`); modified files say so in their
first line.
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
mkdir -p "${1:?usage: build.sh <out-dir>}"
out=$(cd "$1" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
cc=x86_64-w64-mingw32-gcc
objdump=x86_64-w64-mingw32-objdump
for tool in "$cc" "$objdump"; do
command -v "$tool" >/dev/null || { echo "upscale-bridges: $tool not found (apt install gcc-mingw-w64-x86-64)" >&2; exit 1; }
done
cflags=(-O2 -fno-ipa-icf -shared -s -Wall -Wextra -Wno-unused-function -static-libgcc -I"$here"
-ffile-prefix-map="$here"=. -Wl,--no-insert-timestamp)
build() {
local name=$1 source=$2 definition=$3
shift 3
# ld derives the DLL's image base from the -o path, so link in $work under the bare name.
(cd "$work" && "$cc" "${cflags[@]}" "$here/$source" "$here/$definition" "$@" -o "$name")
python3 -I "$here/pe.py" verify "$work/$name" "$here/$definition" "$here/$source" "$objdump"
python3 -I "$here/pe.py" stamp "$work/$name"
}
build amd_fidelityfx_vk.dll wl_ffx_bridge.c wl_ffx_bridge.def -lm
for name in amd_fidelityfx_dx12.dll amd_fidelityfx_upscaler_vk.dll amd_fidelityfx_upscaler_dx12.dll amd_fidelityfx_loader_dx12.dll; do
cp "$work/amd_fidelityfx_vk.dll" "$work/$name"
done
build libxess.dll wl_xess_bridge.c libxess.def -lm
build ffx_fsr3upscaler_x64.dll wl_fsr23_bridge.c ffx_fsr3upscaler_x64.def -lm
build ffx_fsr2_api_x64.dll wl_fsr23_bridge.c ffx_fsr2_api_x64.def -lm
build nvngx.dll wl_ngx_bridge.c nvngx.def -lm
for name in _nvngx.dll nvngx_dlss.dll; do
cp "$work/nvngx.dll" "$work/$name"
done
build nvapi64.dll wl_nvapi_shim.c nvapi64.def
names=(_nvngx.dll amd_fidelityfx_dx12.dll amd_fidelityfx_loader_dx12.dll amd_fidelityfx_upscaler_dx12.dll
amd_fidelityfx_upscaler_vk.dll amd_fidelityfx_vk.dll ffx_fsr2_api_x64.dll ffx_fsr3upscaler_x64.dll
libxess.dll nvapi64.dll nvngx.dll nvngx_dlss.dll)
[ "$(ls "$work" | sort)" = "$(printf '%s\n' "${names[@]}" | sort)" ] || { echo "upscale-bridges: unexpected outputs" >&2; exit 1; }
# The ARM64EC Wine loads x86-64 builtins from aarch64-windows as well.
for arch in x86_64-windows aarch64-windows; do
rm -rf "${out:?}/$arch"
mkdir -p "$out/$arch"
for name in "${names[@]}"; do
install -m 644 "$work/$name" "$out/$arch/$name"
done
done
+20
View File
@@ -0,0 +1,20 @@
// DroidDeck: environment lookups shared by the upscale bridges.
#pragma once
#include <windows.h>
// Copies the first variable in the NULL-terminated list that is set and fits into buf.
static DWORD dd_env_first(const char *const *names, char *buf, DWORD size) {
for (; *names; names++) {
DWORD n = GetEnvironmentVariableA(*names, buf, size);
if (n > 0 && n < size) return n;
}
if (size) buf[0] = '\0';
return 0;
}
static int dd_env_is_on(const char *name) {
char buf[8];
DWORD n = GetEnvironmentVariableA(name, buf, sizeof buf);
return n == 1 && buf[0] == '1';
}
@@ -0,0 +1,11 @@
LIBRARY ffx_fsr2_api_x64.dll
EXPORTS
ffxFsr2ContextCreate
ffxFsr2ContextDispatch
ffxFsr2ContextGenerateReactiveMask
ffxFsr2ContextDestroy
ffxFsr2GetUpscaleRatioFromQualityMode
ffxFsr2GetRenderResolutionFromQualityMode
ffxFsr2GetJitterPhaseCount
ffxFsr2GetJitterOffset
ffxFsr2ResourceIsNull
@@ -0,0 +1,14 @@
LIBRARY ffx_fsr3upscaler_x64.dll
EXPORTS
ffxFsr3UpscalerContextCreate
ffxFsr3UpscalerGetSharedResourceDescriptions
ffxFsr3UpscalerContextDispatch
ffxFsr3UpscalerContextGenerateReactiveMask
ffxFsr3UpscalerContextDestroy
ffxFsr3UpscalerGetUpscaleRatioFromQualityMode
ffxFsr3UpscalerGetRenderResolutionFromQualityMode
ffxFsr3UpscalerGetJitterPhaseCount
ffxFsr3UpscalerGetJitterOffset
ffxFsr3UpscalerResourceIsNull
ffxFsr3UpscalerSetConstant
ffxFsr3UpscalerGetEffectVersion
+162
View File
@@ -0,0 +1,162 @@
// Shared in-process zero-copy Wine <-> Android Vulkan Layer mailbox/doorbell protocol
// for Winlator Ludashi FSR 4.1.1 on Qualcomm Hexagon HTP v81 NPU.
//
// Used identically by:
// - Android ARM64 Vulkan Layer: libVkLayer_winlator_fsr4_npu.so
// - Windows x86_64 Bridge DLLs: amd_fidelityfx_vk.dll, amd_fidelityfx_dx12.dll, nvngx.dll
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// Exact buffer creation signatures recognized by libVkLayer_winlator_fsr4_npu.so
// via vkCreateBuffer / vkBindBufferMemory / vkMapMemory / vkCmdUpdateBuffer.
#define WLFSR4_MAILBOX_BYTES 0x2000u /* 8192 bytes: header + 4 ring slots */
#define WLFSR4_MARKER_BYTES 0x02D0u /* 720 bytes: doorbell target buffer */
#define WLFSR4_MAILBOX_MAGIC 0x345253464E4C5755ULL /* "UWLNFSR4" */
#define WLFSR4_DOORBELL_MAGIC 0x444246535234574CULL /* "LWR4SFBD" */
#define WLFSR4_HELLO_MAGIC 0x48454C4F46535234ULL /* "4RSFOLEH" */
#define WLFSR4_TELEMETRY_MAGIC 0x54454C4D46535234ULL /* "4RSFMLET" (XeSS 3.0 direct telemetry ping) */
#define WLFSR4_PROTO_VERSION 2u
#define WLFSR4_SLOTS 4u
// Multi-backend IDs shared across Android Vulkan layer, Windows bridge DLLs, and Java/Kotlin UI
enum {
WL_FSR_BACKEND_FSR3_GPU = 0, /* FSR 3.1 (GPU) */
WL_FSR_BACKEND_XESS3_GPU = 1, /* XeSS 3.0 DP4a (GPU, official libxess.dll) */
WL_FSR_BACKEND_FSR4_0_NPU = 2, /* FSR 4.0.2 INT8 (Hexagon HTP NPU) */
WL_FSR_BACKEND_FSR4_1_LITE_NPU = 3, /* FSR 4.1.2 Lite INT8 (Hexagon HTP NPU) */
WL_FSR_BACKEND_FSR4_1_FULL_NPU = 4, /* FSR 4.1.1 Full INT8 (Hexagon HTP NPU) */
WL_FSR_BACKEND_FSR4_1_LITE_GPU = 5, /* FSR 4.1.2 Lite INT8 (Adreno Vulkan DP4a GPU) */
WL_FSR_BACKEND_FSR4_1_FULL_GPU = 6, /* FSR 4.1.1 Full INT8 (Adreno Vulkan DP4a GPU) */
};
// Packed live control bits written by the Vulkan layer into mailbox->live_ctrl
#define WLFSR4_CTRL_BACKEND_MASK 0xFFULL
#define WLFSR4_CTRL_ENABLED_BIT (1ULL << 8)
#define WLFSR4_CTRL_SYNC_BIT (1ULL << 9)
#define WLFSR4_CTRL_SHARP_SHIFT 16u
#define WLFSR4_CTRL_SHARP_MASK 0xFFFFULL /* sharpness * 1000 */
// Ack flags written by the Vulkan layer into mailbox->ack
#define WLFSR4_ACK_WORK_BIT 0x8000000000000000ULL /* real GPU/NPU work recorded */
#define WLFSR4_ACK_NPU_ACTIVE_BIT 0x4000000000000000ULL /* Hexagon HTP NPU path active */
#define WLFSR4_ACK_SEQ_MASK 0x0000FFFFFFFFFFFFULL
// Frame flags
#define WLFSR4_FLAG_RESET (1u << 0)
#define WLFSR4_FLAG_HDR (1u << 1)
#define WLFSR4_FLAG_SRGB_OUT (1u << 2)
#define WLFSR4_FLAG_DEPTH_INVERTED (1u << 3)
#define WLFSR4_FLAG_DISPLAY_RES_MV (1u << 4)
#define WLFSR4_FLAG_SHARPEN (1u << 5)
#define WLFSR4_FLAG_MV_JITTERED (1u << 6)
#define WLFSR4_FLAG_AUTO_EXPOSURE (1u << 7)
#define WLFSR4_FLAG_XESS_FALLBACK (1u << 8) /* Bridge fell back from XeSS 3.0 -> request FSR 3.1 GPU */
// Source API tag (for logging & heuristics)
enum {
WLFSR4_API_UNKNOWN = 0,
WLFSR4_API_FFX_VK = 1,
WLFSR4_API_FFX_DX12 = 2,
WLFSR4_API_NGX_VK = 3,
WLFSR4_API_NGX_DX12 = 4,
WLFSR4_API_XESS_VK = 5,
WLFSR4_API_XESS_DX12 = 6,
WLFSR4_API_FSR3_VK = 7,
WLFSR4_API_FSR3_DX12 = 8,
WLFSR4_API_FSR2_VK = 9,
WLFSR4_API_FSR2_DX12 = 10,
};
// Preset hint
enum {
WLFSR4_PRESET_AUTO = 0,
WLFSR4_PRESET_PERF = 1,
WLFSR4_PRESET_ULTRAPERF = 2,
};
// In-game quality mode reported by DLSS / FidelityFX bridge -> Vulkan layer -> Left Sidebar
enum {
WLFSR4_QUALITY_AUTO = 0,
WLFSR4_QUALITY_NATIVE_AA = 1, /* DLAA / Native AA (1.0x) */
WLFSR4_QUALITY_QUALITY = 2, /* Quality (1.5x) */
WLFSR4_QUALITY_BALANCED = 3, /* Balanced (1.7x) */
WLFSR4_QUALITY_PERF = 4, /* Performance (2.0x) */
WLFSR4_QUALITY_ULTRA_PERF = 5, /* Ultra Performance (3.0x) */
WLFSR4_QUALITY_ULTRA_QUAL = 6, /* Ultra Quality (1.3x) */
};
typedef struct WlFsr4ImageRef {
uint64_t vk_image; /* non-dispatchable VkImage handle (guest == host under winevulkan) */
uint64_t vk_view; /* optional VkImageView handle (0 = layer creates its own view) */
uint32_t vk_format; /* VkFormat */
uint32_t vk_layout; /* VkImageLayout at dispatch entry & expected at exit */
uint32_t width;
uint32_t height;
uint32_t aspect; /* VkImageAspectFlags (0 = auto color/depth) */
uint32_t reserved;
} WlFsr4ImageRef; /* 40 bytes */
typedef struct WlFsr4FrameDesc {
uint64_t seq;
uint64_t reserved_handle;
WlFsr4ImageRef color;
WlFsr4ImageRef depth;
WlFsr4ImageRef motion;
WlFsr4ImageRef output;
uint32_t render_w;
uint32_t render_h;
uint32_t output_w;
uint32_t output_h;
float jitter_x;
float jitter_y;
float mv_scale_x;
float mv_scale_y;
float pre_exposure;
float sharpness;
float frame_time_ms;
float camera_near;
float camera_far;
float camera_fov_y;
uint32_t flags;
uint32_t api_source;
uint32_t preset_hint;
uint32_t quality_mode; /* WLFSR4_QUALITY_* */
uint32_t pad[2];
} WlFsr4FrameDesc; /* 256 bytes */
typedef struct WlFsr4Mailbox {
volatile uint64_t magic;
volatile uint64_t version;
volatile uint64_t ack; /* layer writes seq | flags synchronously inside vkCmdUpdateBuffer */
volatile uint64_t ack_count;
volatile uint64_t layer_caps; /* bit 0: layer alive, bit 1: HTP NPU ready, bit 2: 1080p shaders ready */
volatile uint64_t npu_dispatches;
volatile uint32_t last_htp_us; /* last Hexagon HTP execution time in microseconds */
volatile uint32_t last_status; /* 0=ok, 1=fallback-blit, 2=error */
volatile uint64_t live_ctrl; /* WLFSR4_CTRL_* packed live control synced from Android UI */
volatile uint32_t last_gpu_us; /* last GPU upscaler execution time in microseconds */
volatile uint32_t tele_gpu_us; /* bridge-reported XeSS 3.0 GPU/CPU time (us) on TELEMETRY ping */
uint64_t reserved[6];
WlFsr4FrameDesc slots[WLFSR4_SLOTS];
} WlFsr4Mailbox;
typedef struct WlFsr4DoorbellPayload {
uint64_t magic;
uint64_t seq;
} WlFsr4DoorbellPayload;
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
_Static_assert(sizeof(WlFsr4ImageRef) == 40, "WlFsr4ImageRef size");
_Static_assert(sizeof(WlFsr4FrameDesc) == 256, "WlFsr4FrameDesc size");
_Static_assert(sizeof(WlFsr4Mailbox) <= WLFSR4_MAILBOX_BYTES, "WlFsr4Mailbox fits in 8KB");
_Static_assert(sizeof(WlFsr4DoorbellPayload) == 16, "WlFsr4DoorbellPayload size");
#endif
#ifdef __cplusplus
}
#endif
+40
View File
@@ -0,0 +1,40 @@
LIBRARY libxess.dll
EXPORTS
xessGetVersion
xessGetIntelXeFXVersion
xessIsOptimalDriver
xessSetLoggingCallback
xessGetProperties
xessGetInputResolution
xessGetOptimalInputResolution
xessGetJitterScale
xessSetJitterScale
xessGetVelocityScale
xessSetVelocityScale
xessSetExposureMultiplier
xessGetExposureMultiplier
xessSetMaxResponsiveMaskValue
xessGetMaxResponsiveMaskValue
xessForceLegacyScaleFactors
xessGetPipelineBuildStatus
xessDestroyContext
xessSelectNetworkModel
xessStartDump
xessGetProfilingData
xessSetContextParameterF
xessD3D12CreateContext
xessD3D12BuildPipelines
xessD3D12Init
xessD3D12GetInitParams
xessD3D12Execute
xessD3D12GetProfilingData
xessD3D12GetResourcesToDump
xessVKGetRequiredInstanceExtensions
xessVKGetRequiredDeviceExtensions
xessVKGetRequiredDeviceFeatures
xessVKCreateContext
xessVKBuildPipelines
xessVKInit
xessVKGetInitParams
xessVKExecute
xessVKGetResourcesToDump
+3
View File
@@ -0,0 +1,3 @@
LIBRARY nvapi64
EXPORTS
nvapi_QueryInterface
+90
View File
@@ -0,0 +1,90 @@
LIBRARY nvngx
EXPORTS
GetNGXResultAsString
NVSDK_NGX_CUDA_AllocateParameters
NVSDK_NGX_CUDA_CreateFeature
NVSDK_NGX_CUDA_DestroyParameters
NVSDK_NGX_CUDA_EvaluateFeature
NVSDK_NGX_CUDA_GetCapabilityParameters
NVSDK_NGX_CUDA_GetParameters
NVSDK_NGX_CUDA_GetScratchBufferSize
NVSDK_NGX_CUDA_Init
NVSDK_NGX_CUDA_Init_with_ProjectID
NVSDK_NGX_CUDA_ReleaseFeature
NVSDK_NGX_CUDA_Shutdown
NVSDK_NGX_D3D11_AllocateParameters
NVSDK_NGX_D3D11_CreateFeature
NVSDK_NGX_D3D11_DestroyParameters
NVSDK_NGX_D3D11_EvaluateFeature
NVSDK_NGX_D3D11_EvaluateFeature_C
NVSDK_NGX_D3D11_GetCapabilityParameters
NVSDK_NGX_D3D11_GetFeatureRequirements
NVSDK_NGX_D3D11_GetParameters
NVSDK_NGX_D3D11_GetScratchBufferSize
NVSDK_NGX_D3D11_Init
NVSDK_NGX_D3D11_Init_Ext
NVSDK_NGX_D3D11_Init_ProjectID
NVSDK_NGX_D3D11_Init_with_ProjectID
NVSDK_NGX_D3D11_PopulateParameters_Impl
NVSDK_NGX_D3D11_ReleaseFeature
NVSDK_NGX_D3D11_Shutdown
NVSDK_NGX_D3D11_Shutdown1
NVSDK_NGX_D3D12_AllocateParameters
NVSDK_NGX_D3D12_CreateFeature
NVSDK_NGX_D3D12_DestroyParameters
NVSDK_NGX_D3D12_EvaluateFeature
NVSDK_NGX_D3D12_GetCapabilityParameters
NVSDK_NGX_D3D12_GetFeatureRequirements
NVSDK_NGX_D3D12_GetParameters
NVSDK_NGX_D3D12_GetScratchBufferSize
NVSDK_NGX_D3D12_Init
NVSDK_NGX_D3D12_Init_Ext
NVSDK_NGX_D3D12_Init_ProjectID
NVSDK_NGX_D3D12_Init_with_ProjectID
NVSDK_NGX_D3D12_PopulateParameters_Impl
NVSDK_NGX_D3D12_ReleaseFeature
NVSDK_NGX_D3D12_Shutdown
NVSDK_NGX_D3D12_Shutdown1
NVSDK_NGX_GetSnippetVersion
NVSDK_NGX_Parameter_GetD
NVSDK_NGX_Parameter_GetD3d11Resource
NVSDK_NGX_Parameter_GetD3d12Resource
NVSDK_NGX_Parameter_GetF
NVSDK_NGX_Parameter_GetI
NVSDK_NGX_Parameter_GetUI
NVSDK_NGX_Parameter_GetULL
NVSDK_NGX_Parameter_GetVoidPointer
NVSDK_NGX_Parameter_SetD
NVSDK_NGX_Parameter_SetD3d11Resource
NVSDK_NGX_Parameter_SetD3d12Resource
NVSDK_NGX_Parameter_SetF
NVSDK_NGX_Parameter_SetI
NVSDK_NGX_Parameter_SetUI
NVSDK_NGX_Parameter_SetULL
NVSDK_NGX_Parameter_SetVoidPointer
NVSDK_NGX_UpdateFeature
NVSDK_NGX_VULKAN_AllocateParameters
NVSDK_NGX_VULKAN_CreateFeature
NVSDK_NGX_VULKAN_CreateFeature1
NVSDK_NGX_VULKAN_DestroyParameters
NVSDK_NGX_VULKAN_EvaluateFeature
NVSDK_NGX_VULKAN_EvaluateFeature_C
NVSDK_NGX_VULKAN_GetCapabilityParameters
NVSDK_NGX_VULKAN_GetFeatureDeviceExtensionRequirements
NVSDK_NGX_VULKAN_GetFeatureExtensionRequirements
NVSDK_NGX_VULKAN_GetFeatureInstanceExtensionRequirements
NVSDK_NGX_VULKAN_GetFeatureRequirements
NVSDK_NGX_VULKAN_GetParameter
NVSDK_NGX_VULKAN_GetParameters
NVSDK_NGX_VULKAN_GetScratchBufferSize
NVSDK_NGX_VULKAN_Init
NVSDK_NGX_VULKAN_Init_Ext
NVSDK_NGX_VULKAN_Init_Ext2
NVSDK_NGX_VULKAN_Init_ProjectID_Ext
NVSDK_NGX_VULKAN_Init_with_ProjectID
NVSDK_NGX_VULKAN_PopulateParameters_Impl
NVSDK_NGX_VULKAN_ReleaseFeature
NVSDK_NGX_VULKAN_RequiredExtensions
NVSDK_NGX_VULKAN_SetParameter
NVSDK_NGX_VULKAN_Shutdown
NVSDK_NGX_VULKAN_Shutdown1
+84
View File
@@ -0,0 +1,84 @@
"""Stamp and check the upscale bridge DLLs.
stamp DLL write Wine's builtin signature at 0x40, as winebuild --builtin does
verify DLL DEF SRC OBJDUMP the exports `OBJDUMP -p` reports must be the .def names plus SRC's dllexports
"""
import re
import subprocess
import sys
from pathlib import Path
# tools/winebuild/spec32.c: static const char builtin_signature[32] = "Wine builtin DLL";
SIGNATURE = b'Wine builtin DLL'.ljust(32, b'\0')
OFFSET = 0x40
def stamp(dll):
data = bytearray(Path(dll).read_bytes())
if data[:2] != b'MZ':
sys.exit(f'{dll}: not a PE file')
lfanew = int.from_bytes(data[0x3c:0x40], 'little')
if lfanew < OFFSET + len(SIGNATURE):
sys.exit(f'{dll}: not enough space ({lfanew:#x}) for the Wine signature')
data[OFFSET:OFFSET + len(SIGNATURE)] = SIGNATURE
Path(dll).write_bytes(data)
if Path(dll).read_bytes()[OFFSET:OFFSET + len(SIGNATURE)] != SIGNATURE:
sys.exit(f'{dll}: Wine signature did not stick')
def def_names(path):
names, exports = set(), False
for line in Path(path).read_text().splitlines():
line = line.split(';', 1)[0].strip()
if not line:
continue
if line.upper() == 'EXPORTS':
exports = True
elif exports:
names.add(line.split()[0].split('=', 1)[0])
return names
def source_names(path):
text = Path(path).read_text()
return {re.findall(r'\w+', head)[-1] for head in re.findall(r'__declspec\(dllexport\)([^(;{]*)\(', text)}
def exports(dll, objdump):
report = subprocess.run([objdump, '-p', dll], check=True, capture_output=True, text=True).stdout
if 'file format pei-x86-64' not in report:
sys.exit(f'{dll}: not an x86-64 PE image')
table = report.split('[Ordinal/Name Pointer] Table', 1)
if len(table) != 2:
sys.exit(f'{dll}: no export table')
# One row per export, "[ 0] +base[ 1] 0000 name" (binutils 2.45) or "[ 0] name" (older): the rows
# start with an index in brackets; the column titles some versions print do not.
names = []
for line in table[1].splitlines()[1:]:
if not line.strip():
if names:
break
continue
if re.match(r'\s*\[\s*\d+\]', line):
names.append(line.split()[-1])
if len(names) != len(set(names)):
sys.exit(f'{dll}: duplicate exports')
return set(names)
def verify(dll, definition, source, objdump):
found = exports(dll, objdump)
expected = def_names(definition) | source_names(source)
missing, extra = sorted(expected - found), sorted(found - expected)
if missing or extra:
sys.exit(f'{dll}: exports do not match {Path(definition).name}: missing {missing}, unexpected {extra}')
print(f'{Path(dll).name}: {len(found)} exports match {Path(definition).name}')
if __name__ == '__main__':
if sys.argv[1:2] == ['stamp'] and len(sys.argv) == 3:
stamp(sys.argv[2])
elif sys.argv[1:2] == ['verify'] and len(sys.argv) == 6:
verify(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
else:
sys.exit(__doc__)
+570
View File
@@ -0,0 +1,570 @@
// Winlator Ludashi Native AMD FidelityFX API 2.0 (FSR 4.1.1) Bridge DLL
// Works for BOTH Vulkan (amd_fidelityfx_vk.dll / amd_fidelityfx_upscaler_vk.dll)
// AND DirectX 12 via vkd3d-proton interop (amd_fidelityfx_dx12.dll / amd_fidelityfx_upscaler_dx12.dll).
//
// Exposes AMD FSR 4.1.1 (and 3.1.4 compat) via ffxQuery(GET_VERSIONS) and forwards every
// ffxDispatch(UPSCALE) zero-copy to libVkLayer_winlator_fsr4_npu.so on the Hexagon HTP v81 NPU.
#include <windows.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include "wl_seam_client.h"
#include "wl_vkd3d_interop.h"
#include "wl_xess3_direct.h"
// ---- Official AMD FidelityFX API 2.0 ABI (verified from GPUOpen FidelityFX-SDK) ----
typedef void *ffxContext;
typedef uint32_t ffxReturnCode_t;
typedef uint64_t ffxStructType_t;
enum {
FFX_API_RETURN_OK = 0,
FFX_API_RETURN_ERROR = 1,
FFX_API_RETURN_ERROR_UNKNOWN_DESCTYPE = 2,
FFX_API_RETURN_ERROR_RUNTIME_ERROR = 3,
FFX_API_RETURN_NO_PROVIDER = 4,
FFX_API_RETURN_ERROR_MEMORY = 5,
FFX_API_RETURN_ERROR_PARAMETER = 6,
};
typedef struct ffxApiHeader {
ffxStructType_t type;
struct ffxApiHeader *pNext;
} ffxApiHeader;
typedef void *(*ffxAlloc)(void *pUserData, uint64_t size);
typedef void (*ffxDealloc)(void *pUserData, void *pMem);
typedef struct ffxAllocationCallbacks {
void *pUserData;
ffxAlloc alloc;
ffxDealloc dealloc;
} ffxAllocationCallbacks;
typedef void (*ffxApiMessage)(uint32_t type, const wchar_t *message);
typedef struct FfxApiDimensions2D { uint32_t width, height; } FfxApiDimensions2D;
typedef struct FfxApiFloatCoords2D { float x, y; } FfxApiFloatCoords2D;
typedef struct FfxApiResourceDescription {
uint32_t type;
uint32_t format;
uint32_t width;
uint32_t height;
uint32_t depth;
uint32_t mipCount;
uint32_t flags;
uint32_t usage;
} FfxApiResourceDescription;
typedef struct FfxApiResource {
void *resource;
FfxApiResourceDescription description;
uint32_t state;
} FfxApiResource;
typedef struct FfxApiEffectMemoryUsage {
uint64_t totalUsageInBytes;
uint64_t aliasableUsageInBytes;
} FfxApiEffectMemoryUsage;
#define FFX_API_QUERY_DESC_TYPE_GET_VERSIONS 4u
#define FFX_API_DESC_TYPE_OVERRIDE_VERSION 5u
#define FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION 6u
#define FFX_API_CONFIGURE_DESC_TYPE_GLOBALDEBUG 7u
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_DX12 0x00000002u
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK_DEPRECATED 0x00000003u
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK 0x01000003u
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE 0x00010000u
#define FFX_API_DISPATCH_DESC_TYPE_UPSCALE 0x00010001u
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETUPSCALERATIO 0x00010002u
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETRENDERRES 0x00010003u
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTERPHASECOUNT 0x00010004u
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTEROFFSET 0x00010005u
#define FFX_API_DISPATCH_DESC_TYPE_UPSCALE_GENREACTIVEMASK 0x00010006u
#define FFX_API_CONFIGURE_DESC_TYPE_UPSCALE_KEYVALUE 0x00010007u
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE 0x00010008u
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2 0x00010009u
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GET_RESOURCE_REQS 0x0001000au
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION 0x0001000bu
enum {
FFX_UPSCALE_QUALITY_MODE_NATIVEAA = 0,
FFX_UPSCALE_QUALITY_MODE_QUALITY = 1,
FFX_UPSCALE_QUALITY_MODE_BALANCED = 2,
FFX_UPSCALE_QUALITY_MODE_PERFORMANCE = 3,
FFX_UPSCALE_QUALITY_MODE_ULTRA_PERFORMANCE = 4,
};
typedef struct {
ffxApiHeader header;
uint64_t createDescType;
void *device;
uint64_t *outputCount;
uint64_t *versionIds;
const char **versionNames;
} ffxQueryDescGetVersions;
typedef struct {
ffxApiHeader header;
uint64_t versionId;
const char *versionName;
} ffxQueryGetProviderVersion;
typedef struct {
ffxApiHeader header;
uint32_t flags;
FfxApiDimensions2D maxRenderSize;
FfxApiDimensions2D maxUpscaleSize;
ffxApiMessage fpMessage;
} ffxCreateContextDescUpscale;
typedef struct {
VkDevice vkDevice;
VkPhysicalDevice vkPhysicalDevice;
PFN_wlVkGetDeviceProcAddr vkDeviceProcAddr;
} FfxVkDeviceContext;
typedef struct {
ffxApiHeader header;
FfxVkDeviceContext deviceContext;
} ffxCreateBackendVKDesc;
typedef struct {
ffxApiHeader header;
void *device; // ID3D12Device*
} ffxCreateBackendDX12Desc;
typedef struct {
ffxApiHeader header;
void *commandList;
FfxApiResource color;
FfxApiResource depth;
FfxApiResource motionVectors;
FfxApiResource exposure;
FfxApiResource reactive;
FfxApiResource transparencyAndComposition;
FfxApiResource output;
FfxApiFloatCoords2D jitterOffset;
FfxApiFloatCoords2D motionVectorScale;
FfxApiDimensions2D renderSize;
FfxApiDimensions2D upscaleSize;
bool enableSharpening;
float sharpness;
float frameTimeDelta;
float preExposure;
bool reset;
float cameraNear;
float cameraFar;
float cameraFovAngleVertical;
float viewSpaceToMetersFactor;
uint32_t flags;
} ffxDispatchDescUpscale;
typedef struct {
ffxApiHeader header;
uint32_t qualityMode;
float *pOutUpscaleRatio;
} ffxQueryDescUpscaleGetUpscaleRatio;
typedef struct {
ffxApiHeader header;
uint32_t displayWidth, displayHeight, qualityMode;
uint32_t *pOutRenderWidth, *pOutRenderHeight;
} ffxQueryDescUpscaleGetRenderRes;
typedef struct {
ffxApiHeader header;
uint32_t renderWidth, displayWidth;
int32_t *pOutPhaseCount;
} ffxQueryDescUpscaleGetJitterPhaseCount;
typedef struct {
ffxApiHeader header;
int32_t index, phaseCount;
float *pOutX, *pOutY;
} ffxQueryDescUpscaleGetJitterOffset;
typedef struct {
ffxApiHeader header;
FfxApiEffectMemoryUsage *gpuMemoryUsageUpscaler;
} ffxQueryDescUpscaleGetGPUMem;
typedef struct {
ffxApiHeader header;
void *device;
FfxApiDimensions2D maxRenderSize, maxUpscaleSize;
uint32_t flags;
FfxApiEffectMemoryUsage *gpuMemoryUsageUpscaler;
} ffxQueryDescUpscaleGetGPUMemV2;
typedef struct {
ffxApiHeader header;
uint64_t required_resources;
uint64_t optional_resources;
} ffxQueryDescUpscaleGetResourceReqs;
// ---- Version IDs exposed to games ----
// Bit packing matches AMD FidelityFX SDK 2.0 (major<<22 | minor<<12 | patch) + provider tag
#define WL_FSR4_VER_ID_4_1_1 ((4ULL << 22) | (1ULL << 12) | 1ULL)
#define WL_FSR4_VER_ID_3_1_4 ((3ULL << 22) | (1ULL << 12) | 4ULL)
static const uint64_t k_ver_ids[2] = { WL_FSR4_VER_ID_4_1_1, WL_FSR4_VER_ID_3_1_4 };
static const char *k_ver_names[2] = { "4.1.1", "3.1.4" };
typedef struct WlFfxUpscaleCtx {
int is_dx12;
int needs_reset;
uint32_t create_flags;
uint32_t max_rw, max_rh, max_ow, max_oh;
void *d3d12_dev;
WlSeamClient seam;
WlXess3State xess3;
WlID3D12DXVKInteropDevice1 *dx12_interop;
} WlFfxUpscaleCtx;
static volatile uint32_t g_last_ffx_quality = WLFSR4_QUALITY_AUTO;
static uint32_t ffx_mode_to_wl_quality(uint32_t mode) {
switch (mode) {
case FFX_UPSCALE_QUALITY_MODE_NATIVEAA: return WLFSR4_QUALITY_NATIVE_AA;
case FFX_UPSCALE_QUALITY_MODE_QUALITY: return WLFSR4_QUALITY_QUALITY;
case FFX_UPSCALE_QUALITY_MODE_BALANCED: return WLFSR4_QUALITY_BALANCED;
case FFX_UPSCALE_QUALITY_MODE_PERFORMANCE: return WLFSR4_QUALITY_PERF;
case FFX_UPSCALE_QUALITY_MODE_ULTRA_PERFORMANCE: return WLFSR4_QUALITY_ULTRA_PERF;
default: return WLFSR4_QUALITY_AUTO;
}
}
static uint32_t ffx_infer_quality(uint32_t rw, uint32_t ow) {
if (rw == 0u || ow == 0u) return WLFSR4_QUALITY_AUTO;
float r = (float)ow / (float)rw;
if (r < 1.15f) return WLFSR4_QUALITY_NATIVE_AA;
if (r < 1.38f) return WLFSR4_QUALITY_ULTRA_QUAL;
if (r < 1.60f) return WLFSR4_QUALITY_QUALITY;
if (r < 1.85f) return WLFSR4_QUALITY_BALANCED;
if (r < 2.45f) return WLFSR4_QUALITY_PERF;
return WLFSR4_QUALITY_ULTRA_PERF;
}
static float halton(int32_t index, int32_t base) {
float f = 1.0f, r = 0.0f;
int32_t cur = index;
while (cur > 0) {
f /= (float)base;
r += f * (float)(cur % base);
cur /= base;
}
return r;
}
static uint32_t ffx_fmt_to_vk(uint32_t f) {
switch (f) {
case 3: return 109; /* R32G32B32A32_SFLOAT */
case 4: return 97; /* R16G16B16A16_SFLOAT */
case 6: return 103; /* R32G32_SFLOAT */
case 10: return 37; /* R8G8B8A8_UNORM */
case 12: return 43; /* R8G8B8A8_SRGB */
case 14: return 44; /* B8G8R8A8_UNORM */
case 15: return 50; /* B8G8R8A8_SRGB */
case 16: return 122; /* B10G11R11_UFLOAT_PACK32 */
case 17: return 64; /* A2B10G10R10_UNORM_PACK32 */
case 18: return 83; /* R16G16_SFLOAT */
case 28: return 100; /* R32_SFLOAT */
default: return 0; /* let Vulkan layer look up from vkCreateImage table */
}
}
static uint32_t ffx_state_to_vk_layout(uint32_t st, int is_depth) {
if (st & (1u << 1)) return 1; /* UNORDERED_ACCESS -> GENERAL */
if (st & ((1u << 2) | (1u << 3))) return is_depth ? 4 : 5; /* DEPTH_STENCIL_READ_ONLY / SHADER_READ_ONLY */
if (st & (1u << 4)) return 6; /* TRANSFER_SRC */
if (st & (1u << 5)) return 7; /* TRANSFER_DST */
if (st & (1u << 8)) return 2; /* COLOR_ATTACHMENT_OPTIMAL */
if (st & (1u << 9)) return 3; /* DEPTH_STENCIL_ATTACHMENT_OPTIMAL */
return 1; /* GENERAL */
}
static float quality_ratio(uint32_t mode) {
switch (mode) {
case FFX_UPSCALE_QUALITY_MODE_NATIVEAA: return 1.0f;
case FFX_UPSCALE_QUALITY_MODE_QUALITY: return 1.5f;
case FFX_UPSCALE_QUALITY_MODE_BALANCED: return 1.7f;
case FFX_UPSCALE_QUALITY_MODE_PERFORMANCE: return 2.0f;
case FFX_UPSCALE_QUALITY_MODE_ULTRA_PERFORMANCE: return 3.0f;
default: return 2.0f;
}
}
__declspec(dllexport) ffxReturnCode_t ffxCreateContext(ffxContext *context, ffxApiHeader *desc, const ffxAllocationCallbacks *memCb) {
(void)memCb;
if (!context || !desc) return FFX_API_RETURN_ERROR_PARAMETER;
const ffxCreateContextDescUpscale *up = NULL;
const ffxCreateBackendVKDesc *bvk = NULL;
const ffxCreateBackendDX12Desc *bdx = NULL;
for (const ffxApiHeader *h = desc; h; h = h->pNext) {
if (h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE) up = (const ffxCreateContextDescUpscale *)h;
else if (h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK ||
h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK_DEPRECATED) bvk = (const ffxCreateBackendVKDesc *)h;
else if (h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_DX12) bdx = (const ffxCreateBackendDX12Desc *)h;
}
if (!up) return FFX_API_RETURN_NO_PROVIDER;
WlFfxUpscaleCtx *ctx = (WlFfxUpscaleCtx *)calloc(1, sizeof *ctx);
if (!ctx) return FFX_API_RETURN_ERROR_MEMORY;
ctx->create_flags = up->flags;
ctx->needs_reset = 1;
ctx->max_rw = up->maxRenderSize.width;
ctx->max_rh = up->maxRenderSize.height;
ctx->max_ow = up->maxUpscaleSize.width;
ctx->max_oh = up->maxUpscaleSize.height;
if (bvk && bvk->deviceContext.vkDevice) {
ctx->is_dx12 = 0;
wl_seam_init(&ctx->seam, NULL, bvk->deviceContext.vkPhysicalDevice,
bvk->deviceContext.vkDevice, bvk->deviceContext.vkDeviceProcAddr);
} else if (bdx && bdx->device) {
ctx->is_dx12 = 1;
ctx->d3d12_dev = bdx->device;
ctx->dx12_interop = wl_query_vkd3d_interop(bdx->device);
if (ctx->dx12_interop) {
void *vk_inst = NULL, *vk_phys = NULL, *vk_dev = NULL;
if (ctx->dx12_interop->lpVtbl->GetVulkanHandles(ctx->dx12_interop, &vk_inst, &vk_phys, &vk_dev) == S_OK && vk_dev) {
wl_seam_init(&ctx->seam, vk_inst, vk_phys, vk_dev, NULL);
}
}
}
*context = ctx;
return FFX_API_RETURN_OK;
}
__declspec(dllexport) ffxReturnCode_t ffxDestroyContext(ffxContext *context, const ffxAllocationCallbacks *memCb) {
(void)memCb;
if (!context || !*context) return FFX_API_RETURN_OK;
WlFfxUpscaleCtx *ctx = (WlFfxUpscaleCtx *)(*context);
wl_xess3_destroy(&ctx->xess3);
wl_seam_destroy(&ctx->seam);
if (ctx->dx12_interop) {
ctx->dx12_interop->lpVtbl->Release(ctx->dx12_interop);
ctx->dx12_interop = NULL;
}
free(ctx);
*context = NULL;
return FFX_API_RETURN_OK;
}
__declspec(dllexport) ffxReturnCode_t ffxConfigure(ffxContext *context, const ffxApiHeader *desc) {
(void)context; (void)desc;
return FFX_API_RETURN_OK;
}
__declspec(dllexport) ffxReturnCode_t ffxQuery(ffxContext *context, ffxApiHeader *desc) {
(void)context;
if (!desc) return FFX_API_RETURN_ERROR_PARAMETER;
for (ffxApiHeader *h = desc; h; h = h->pNext) {
switch (h->type) {
case FFX_API_QUERY_DESC_TYPE_GET_VERSIONS: {
ffxQueryDescGetVersions *q = (ffxQueryDescGetVersions *)h;
if (!q->outputCount) return FFX_API_RETURN_ERROR_PARAMETER;
uint64_t cap = *q->outputCount;
if (cap == 0 || (!q->versionIds && !q->versionNames)) {
*q->outputCount = 2;
break;
}
uint64_t n = cap < 2 ? cap : 2;
for (uint64_t i = 0; i < n; i++) {
if (q->versionIds) q->versionIds[i] = k_ver_ids[i];
if (q->versionNames) q->versionNames[i] = k_ver_names[i];
}
*q->outputCount = n;
break;
}
case FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION: {
ffxQueryGetProviderVersion *q = (ffxQueryGetProviderVersion *)h;
q->versionId = WL_FSR4_VER_ID_4_1_1;
q->versionName = "4.1.1";
break;
}
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GETUPSCALERATIO: {
ffxQueryDescUpscaleGetUpscaleRatio *q = (ffxQueryDescUpscaleGetUpscaleRatio *)h;
g_last_ffx_quality = ffx_mode_to_wl_quality(q->qualityMode);
if (q->pOutUpscaleRatio) *q->pOutUpscaleRatio = quality_ratio(q->qualityMode);
break;
}
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GETRENDERRES: {
ffxQueryDescUpscaleGetRenderRes *q = (ffxQueryDescUpscaleGetRenderRes *)h;
g_last_ffx_quality = ffx_mode_to_wl_quality(q->qualityMode);
float r = quality_ratio(q->qualityMode);
if (q->pOutRenderWidth) *q->pOutRenderWidth = (uint32_t)((float)q->displayWidth / r);
if (q->pOutRenderHeight) *q->pOutRenderHeight = (uint32_t)((float)q->displayHeight / r);
break;
}
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTERPHASECOUNT: {
ffxQueryDescUpscaleGetJitterPhaseCount *q = (ffxQueryDescUpscaleGetJitterPhaseCount *)h;
if (q->pOutPhaseCount && q->renderWidth > 0) {
float ratio = (float)q->displayWidth / (float)q->renderWidth;
int32_t pc = (int32_t)ceilf(8.0f * ratio * ratio);
if (pc < 8) pc = 8;
*q->pOutPhaseCount = pc;
}
break;
}
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTEROFFSET: {
ffxQueryDescUpscaleGetJitterOffset *q = (ffxQueryDescUpscaleGetJitterOffset *)h;
int32_t pc = q->phaseCount > 0 ? q->phaseCount : 8;
int32_t idx = (q->index % pc) + 1;
if (idx <= 0) idx += pc;
if (q->pOutX) *q->pOutX = halton(idx, 2) - 0.5f;
if (q->pOutY) *q->pOutY = halton(idx, 3) - 0.5f;
break;
}
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE: {
ffxQueryDescUpscaleGetGPUMem *q = (ffxQueryDescUpscaleGetGPUMem *)h;
if (q->gpuMemoryUsageUpscaler) {
q->gpuMemoryUsageUpscaler->totalUsageInBytes = 64ULL * 1024ULL * 1024ULL;
q->gpuMemoryUsageUpscaler->aliasableUsageInBytes = 0;
}
break;
}
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2: {
ffxQueryDescUpscaleGetGPUMemV2 *q = (ffxQueryDescUpscaleGetGPUMemV2 *)h;
if (q->gpuMemoryUsageUpscaler) {
q->gpuMemoryUsageUpscaler->totalUsageInBytes = 64ULL * 1024ULL * 1024ULL;
q->gpuMemoryUsageUpscaler->aliasableUsageInBytes = 0;
}
break;
}
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GET_RESOURCE_REQS: {
ffxQueryDescUpscaleGetResourceReqs *q = (ffxQueryDescUpscaleGetResourceReqs *)h;
q->required_resources = (1ULL << 0) | (1ULL << 1) | (1ULL << 2); /* COLOR | DEPTH | MV */
q->optional_resources = (1ULL << 3) | (1ULL << 4) | (1ULL << 5);
break;
}
default:
break;
}
}
return FFX_API_RETURN_OK;
}
static void fill_vk_img_ref(WlFsr4ImageRef *dst, const FfxApiResource *src, int is_depth) {
memset(dst, 0, sizeof *dst);
if (!src || !src->resource) return;
dst->vk_image = (uint64_t)(uintptr_t)src->resource;
dst->vk_format = ffx_fmt_to_vk(src->description.format);
dst->vk_layout = ffx_state_to_vk_layout(src->state, is_depth);
dst->width = src->description.width;
dst->height = src->description.height;
dst->aspect = is_depth ? 2u : 1u;
}
static void fill_dx12_img_ref(WlID3D12DXVKInteropDevice1 *interop, WlFsr4ImageRef *dst, const FfxApiResource *src, int is_depth) {
memset(dst, 0, sizeof *dst);
if (!interop || !src || !src->resource) return;
UINT64 vk_img = 0, off = 0;
UINT32 vk_fmt = 0;
if (interop->lpVtbl->GetVulkanResourceInfo1(interop, src->resource, &vk_img, &off, &vk_fmt) == S_OK && vk_img) {
dst->vk_image = vk_img;
dst->vk_format = vk_fmt ? vk_fmt : ffx_fmt_to_vk(src->description.format);
dst->vk_layout = ffx_state_to_vk_layout(src->state, is_depth);
dst->width = src->description.width;
dst->height = src->description.height;
dst->aspect = is_depth ? 2u : 1u;
}
}
__declspec(dllexport) ffxReturnCode_t ffxDispatch(ffxContext *context, const ffxApiHeader *desc) {
if (!context || !*context || !desc) return FFX_API_RETURN_ERROR_PARAMETER;
WlFfxUpscaleCtx *ctx = (WlFfxUpscaleCtx *)(*context);
for (const ffxApiHeader *h = desc; h; h = h->pNext) {
if (h->type != FFX_API_DISPATCH_DESC_TYPE_UPSCALE) continue;
const ffxDispatchDescUpscale *d = (const ffxDispatchDescUpscale *)h;
if (!d->commandList || !ctx->seam.ready) return FFX_API_RETURN_ERROR_RUNTIME_ERROR;
WlFsr4FrameDesc f;
memset(&f, 0, sizeof f);
f.render_w = d->renderSize.width ? d->renderSize.width : ctx->max_rw;
f.render_h = d->renderSize.height ? d->renderSize.height : ctx->max_rh;
f.output_w = d->upscaleSize.width ? d->upscaleSize.width : ctx->max_ow;
f.output_h = d->upscaleSize.height ? d->upscaleSize.height : ctx->max_oh;
f.jitter_x = d->jitterOffset.x;
f.jitter_y = d->jitterOffset.y;
f.mv_scale_x = d->motionVectorScale.x != 0.f ? d->motionVectorScale.x : 1.f;
f.mv_scale_y = d->motionVectorScale.y != 0.f ? d->motionVectorScale.y : 1.f;
f.pre_exposure = d->preExposure > 0.f ? d->preExposure : 1.f;
f.sharpness = d->sharpness;
f.frame_time_ms = d->frameTimeDelta;
f.camera_near = d->cameraNear;
f.camera_far = d->cameraFar;
f.camera_fov_y = d->cameraFovAngleVertical;
if (d->reset || ctx->needs_reset) {
f.flags |= WLFSR4_FLAG_RESET;
ctx->needs_reset = 0;
}
if (ctx->create_flags & (1u << 0)) f.flags |= WLFSR4_FLAG_HDR;
if (ctx->create_flags & (1u << 1)) f.flags |= WLFSR4_FLAG_DISPLAY_RES_MV;
if (ctx->create_flags & (1u << 2)) f.flags |= WLFSR4_FLAG_MV_JITTERED;
if (ctx->create_flags & (1u << 3)) f.flags |= WLFSR4_FLAG_DEPTH_INVERTED;
if (ctx->create_flags & (1u << 5)) f.flags |= WLFSR4_FLAG_AUTO_EXPOSURE;
if (d->enableSharpening) f.flags |= WLFSR4_FLAG_SHARPEN;
f.quality_mode = (g_last_ffx_quality != WLFSR4_QUALITY_AUTO)
? g_last_ffx_quality
: ffx_infer_quality(f.render_w, f.output_w);
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
if (!ctx->is_dx12) {
f.api_source = WLFSR4_API_FFX_VK;
fill_vk_img_ref(&f.color, &d->color, 0);
fill_vk_img_ref(&f.depth, &d->depth, 1);
fill_vk_img_ref(&f.motion, &d->motionVectors, 0);
fill_vk_img_ref(&f.output, &d->output, 0);
if (!wl_seam_dispatch_or_blit(&ctx->seam, (VkCommandBuffer)d->commandList, &f))
return FFX_API_RETURN_ERROR_RUNTIME_ERROR;
} else if (ctx->dx12_interop) {
f.api_source = WLFSR4_API_FFX_DX12;
fill_dx12_img_ref(ctx->dx12_interop, &f.color, &d->color, 0);
fill_dx12_img_ref(ctx->dx12_interop, &f.depth, &d->depth, 1);
fill_dx12_img_ref(ctx->dx12_interop, &f.motion, &d->motionVectors, 0);
fill_dx12_img_ref(ctx->dx12_interop, &f.output, &d->output, 0);
int live_en = 1;
int live_backend = wl_seam_live_backend(&ctx->seam, &live_en);
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU && ctx->d3d12_dev) {
if (wl_xess3_eval_d3d12(&ctx->xess3, &ctx->seam, ctx->dx12_interop,
ctx->d3d12_dev, d->commandList, &f,
d->color.resource, d->depth.resource,
d->motionVectors.resource, d->output.resource)) {
continue;
}
wl_xess3_tag_fallback(&ctx->xess3, &f);
} else {
wl_xess3_on_inactive(&ctx->xess3);
}
void *vk_cb = NULL;
int ok = 0;
if (ctx->dx12_interop->lpVtbl->BeginVkCommandBufferInterop(ctx->dx12_interop, d->commandList, &vk_cb) == S_OK && vk_cb) {
ok = wl_seam_dispatch_or_blit(&ctx->seam, (VkCommandBuffer)vk_cb, &f);
ctx->dx12_interop->lpVtbl->EndVkCommandBufferInterop(ctx->dx12_interop, d->commandList);
}
if (!ok) return FFX_API_RETURN_ERROR_RUNTIME_ERROR;
}
}
return FFX_API_RETURN_OK;
}
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
(void)hinst; (void)reason; (void)reserved;
return TRUE;
}
+6
View File
@@ -0,0 +1,6 @@
EXPORTS
ffxCreateContext
ffxDestroyContext
ffxConfigure
ffxQuery
ffxDispatch
+886
View File
@@ -0,0 +1,886 @@
// Winlator Ludashi AMD FSR 3 (ffx_fsr3upscaler_x64.dll) & External FSR 2 (ffx_fsr2_api_x64.dll)
// -> AMD FSR 4 INT8 Hexagon HTP NPU Bridge
//
// Supports BOTH DirectX 12 (via vkd3d-proton zero-copy interop) and Vulkan,
// auto-detecting FSR 3.0 vs FSR 3.1 and FSR 2.0 vs FSR 2.1/2.2 struct layouts.
// Requires ZERO GPU spoofing — runs cleanly on Adreno/Turnip in No-GPU-Spoof mode.
#include <windows.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "wl_seam_client.h"
#include "wl_vkd3d_interop.h"
#include "wl_xess3_direct.h"
// ---- Common FFX error & basic types ----
typedef int32_t FfxErrorCode;
#define FFX_OK 0
#define FFX_ERROR_INVALID_POINTER (-2147483647 - 1)
#define FFX_ERROR_INVALID_ALIGNMENT (-2147483647)
#define FFX_ERROR_INVALID_SIZE (-2147483646)
#define FFX_ERROR_EOF (-2147483645)
#define FFX_ERROR_INVALID_PATH (-2147483644)
#define FFX_ERROR_EOF_EX (-2147483643)
#define FFX_ERROR_MALFORMED_DATA (-2147483642)
#define FFX_ERROR_OUT_OF_MEMORY (-2147483641)
#define FFX_ERROR_INCOMPLETE_INTERFACE (-2147483640)
#define FFX_ERROR_INVALID_ENUM (-2147483639)
#define FFX_ERROR_INVALID_ARGUMENT (-2147483638)
#define FFX_ERROR_OUT_OF_RANGE (-2147483637)
#define FFX_ERROR_NULL_DEVICE (-2147483636)
typedef struct { uint32_t width, height; } WlFfxDim2D;
typedef struct { float x, y; } WlFfxFloat2D;
// ---- FSR 3 ABI structs (verified from FidelityFX SDK 1.0/1.1 fsr3 & fsr31) ----
typedef struct {
uint32_t type;
uint32_t format;
uint32_t width;
uint32_t height;
uint32_t depth;
uint32_t mipCount;
uint32_t flags;
uint32_t usage;
} WlFfxResDesc3;
typedef struct {
void *resource;
WlFfxResDesc3 description;
uint32_t state;
uint16_t name[64];
} WlFfxResource3;
typedef struct {
uint32_t heapType;
WlFfxResDesc3 resourceDescription;
uint32_t initialState;
uint32_t initDataSize;
void *initData;
const uint16_t *name;
uint32_t id;
} WlFfxCreateResDesc3;
typedef struct {
WlFfxCreateResDesc3 reconstructedPrevNearestDepth;
WlFfxCreateResDesc3 dilatedDepth;
WlFfxCreateResDesc3 dilatedMotionVectors;
} WlFfxFsr3SharedResDescs;
typedef struct {
void *callbacks[16];
void *scratchBuffer;
size_t scratchBufferSize;
void *device;
} WlFfxInterface3;
typedef struct {
uint32_t flags;
WlFfxDim2D maxRenderSize;
WlFfxDim2D displaySize;
WlFfxInterface3 backendInterface;
void *fpMessage;
} WlFfxFsr30CtxDesc;
typedef struct {
uint32_t flags;
WlFfxDim2D maxRenderSize;
WlFfxDim2D maxUpscaleSize;
void *fpMessage;
WlFfxInterface3 backendInterface;
} WlFfxFsr31CtxDesc;
typedef struct {
void *commandList;
WlFfxResource3 color;
WlFfxResource3 depth;
WlFfxResource3 motionVectors;
WlFfxResource3 exposure;
WlFfxResource3 reactive;
WlFfxResource3 transparencyAndComposition;
WlFfxResource3 dilatedDepth;
WlFfxResource3 dilatedMotionVectors;
WlFfxResource3 reconstructedPrevNearestDepth;
WlFfxResource3 output;
WlFfxFloat2D jitterOffset;
WlFfxFloat2D motionVectorScale;
WlFfxDim2D renderSize;
bool enableSharpening;
float sharpness;
float frameTimeDelta;
float preExposure;
bool reset;
float cameraNear;
float cameraFar;
float cameraFovAngleVertical;
float viewSpaceToMetersFactor;
} WlFfxFsr30DispatchDesc;
typedef struct {
void *commandList;
WlFfxResource3 color;
WlFfxResource3 depth;
WlFfxResource3 motionVectors;
WlFfxResource3 exposure;
WlFfxResource3 reactive;
WlFfxResource3 transparencyAndComposition;
WlFfxResource3 dilatedDepth;
WlFfxResource3 dilatedMotionVectors;
WlFfxResource3 reconstructedPrevNearestDepth;
WlFfxResource3 output;
WlFfxFloat2D jitterOffset;
WlFfxFloat2D motionVectorScale;
WlFfxDim2D renderSize;
WlFfxDim2D upscaleSize;
bool enableSharpening;
float sharpness;
float frameTimeDelta;
float preExposure;
bool reset;
float cameraNear;
float cameraFar;
float cameraFovAngleVertical;
float viewSpaceToMetersFactor;
uint32_t flags;
} WlFfxFsr31DispatchDesc;
// ---- FSR 2 ABI structs (verified from FidelityFX FSR 2.0 / 2.1.2 / 2.2.1) ----
typedef struct {
uint32_t type;
uint32_t format;
uint32_t width;
uint32_t height;
uint32_t depth;
uint32_t mipCount;
uint32_t flags;
} WlFfxResDesc2;
typedef struct {
void *resource;
uint16_t name[64];
WlFfxResDesc2 description;
uint32_t state;
bool isDepth;
uint64_t descriptorData;
} WlFfxResource21;
typedef struct {
void *resource;
WlFfxResDesc2 description;
uint32_t state;
bool isDepth;
uint64_t descriptorData;
} WlFfxResource20;
typedef struct {
void *callbacks[12];
void *scratchBuffer;
size_t scratchBufferSize;
} WlFfxInterface2;
typedef struct {
uint32_t flags;
WlFfxDim2D maxRenderSize;
WlFfxDim2D displaySize;
WlFfxInterface2 callbacks;
void *device;
} WlFfxFsr2CtxDesc;
typedef struct {
void *commandList;
WlFfxResource21 color;
WlFfxResource21 depth;
WlFfxResource21 motionVectors;
WlFfxResource21 exposure;
WlFfxResource21 reactive;
WlFfxResource21 transparencyAndComposition;
WlFfxResource21 output;
WlFfxFloat2D jitterOffset;
WlFfxFloat2D motionVectorScale;
WlFfxDim2D renderSize;
bool enableSharpening;
float sharpness;
float frameTimeDelta;
float preExposure;
bool reset;
float cameraNear;
float cameraFar;
float cameraFovAngleVertical;
} WlFfxFsr21DispatchDesc;
typedef struct {
void *commandList;
WlFfxResource20 color;
WlFfxResource20 depth;
WlFfxResource20 motionVectors;
WlFfxResource20 exposure;
WlFfxResource20 reactive;
WlFfxResource20 transparencyAndComposition;
WlFfxResource20 output;
WlFfxFloat2D jitterOffset;
WlFfxFloat2D motionVectorScale;
WlFfxDim2D renderSize;
bool enableSharpening;
float sharpness;
float frameTimeDelta;
float preExposure;
bool reset;
float cameraNear;
float cameraFar;
float cameraFovAngleVertical;
} WlFfxFsr20DispatchDesc;
typedef struct {
VkDevice vkDevice;
VkPhysicalDevice vkPhysicalDevice;
PFN_wlVkGetDeviceProcAddr vkDeviceProcAddr;
} WlFfxVkDevCtx3;
// ---- Shared Helpers ----
#define WL_FSR23_MAGIC 0x574C4632u /* "WLF2" */
typedef struct WlFsr23Ctx {
uint32_t magic;
int is_fsr3;
int is_fsr31;
int is_dx12;
int needs_reset;
uint32_t flags;
uint32_t max_rw, max_rh;
uint32_t disp_w, disp_h;
void *d3d12_dev;
WlSeamClient seam;
WlXess3State xess3;
WlID3D12DXVKInteropDevice1 *dx12_interop;
} WlFsr23Ctx;
typedef struct {
uint32_t magic;
uint32_t pad;
WlFsr23Ctx *ctx;
} WlFsrContextHeader;
static volatile uint32_t g_last_quality_mode = WLFSR4_QUALITY_AUTO;
static float fsr_halton(int32_t index, int32_t base) {
float f = 1.0f, r = 0.0f;
int32_t cur = index;
while (cur > 0) {
f /= (float)base;
r += f * (float)(cur % base);
cur /= base;
}
return r;
}
static float fsr_quality_ratio(uint32_t mode) {
switch (mode) {
case 0: return 1.0f; /* Native AA */
case 1: return 1.5f; /* Quality */
case 2: return 1.7f; /* Balanced */
case 3: return 2.0f; /* Performance */
case 4: return 3.0f; /* Ultra Performance */
default: return 0.0f;
}
}
static uint32_t fsr_mode_to_wl(uint32_t mode) {
switch (mode) {
case 0: return WLFSR4_QUALITY_NATIVE_AA;
case 1: return WLFSR4_QUALITY_QUALITY;
case 2: return WLFSR4_QUALITY_BALANCED;
case 3: return WLFSR4_QUALITY_PERF;
case 4: return WLFSR4_QUALITY_ULTRA_PERF;
default: return WLFSR4_QUALITY_AUTO;
}
}
static uint32_t fsr_infer_quality(uint32_t rw, uint32_t ow) {
if (rw == 0u || ow == 0u) return WLFSR4_QUALITY_AUTO;
float r = (float)ow / (float)rw;
if (r < 1.15f) return WLFSR4_QUALITY_NATIVE_AA;
if (r < 1.38f) return WLFSR4_QUALITY_ULTRA_QUAL;
if (r < 1.60f) return WLFSR4_QUALITY_QUALITY;
if (r < 1.85f) return WLFSR4_QUALITY_BALANCED;
if (r < 2.45f) return WLFSR4_QUALITY_PERF;
return WLFSR4_QUALITY_ULTRA_PERF;
}
static uint32_t fsr_fmt_to_vk(uint32_t f) {
switch (f) {
case 3: return 109; /* R32G32B32A32_SFLOAT */
case 4: return 97; /* R16G16B16A16_SFLOAT */
case 5: return 103; /* R32G32_SFLOAT */
case 8: return 64; /* A2B10G10R10_UNORM_PACK32 */
case 10: return 37; /* R8G8B8A8_UNORM */
case 12: return 43; /* R8G8B8A8_SRGB */
case 13: return 122; /* B10G11R11_UFLOAT_PACK32 */
case 14: return 83; /* R16G16_SFLOAT */
case 24: return 100; /* R32_SFLOAT */
default: return 0; /* layer resolves from vkCreateImage table */
}
}
static uint32_t fsr_state_to_vk_layout(uint32_t st, int is_depth) {
if (st & (1u << 1)) return 1u; /* UNORDERED_ACCESS -> GENERAL */
if (st & ((1u << 2) | (1u << 3))) return is_depth ? 4u : 5u; /* COMPUTE/PIXEL_READ */
if (st & (1u << 4)) return 6u; /* COPY_SRC */
if (st & (1u << 5)) return 7u; /* COPY_DEST */
if (st & (1u << 8)) return 2u; /* RENDER_TARGET */
return 1u;
}
static uint32_t fsr_state_to_d3d12(uint32_t st) {
if (st & (1u << 1)) return 0x8u; /* UNORDERED_ACCESS */
if (st & (1u << 2)) return 0x40u; /* NON_PIXEL_SHADER_RESOURCE */
if (st & (1u << 3)) return 0x80u; /* PIXEL_SHADER_RESOURCE */
if (st & (1u << 4)) return 0x800u; /* COPY_SOURCE */
if (st & (1u << 5)) return 0x400u; /* COPY_DEST */
if (st & (1u << 8)) return 0x4u; /* RENDER_TARGET */
return 0x40u;
}
static uint32_t fsr_flags_to_wl(uint32_t flags) {
uint32_t out = 0;
if (flags & (1u << 0)) out |= WLFSR4_FLAG_HDR;
if (flags & (1u << 1)) out |= WLFSR4_FLAG_DISPLAY_RES_MV;
if (flags & (1u << 2)) out |= WLFSR4_FLAG_MV_JITTERED;
if (flags & (1u << 3)) out |= WLFSR4_FLAG_DEPTH_INVERTED;
if (flags & (1u << 5)) out |= WLFSR4_FLAG_AUTO_EXPOSURE;
return out;
}
static int ptr_belongs_to_vk_backend(void *fn_ptr) {
if (!fn_ptr) return 0;
HMODULE hm = NULL;
if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR)fn_ptr, &hm) || !hm) {
return 0;
}
char path[MAX_PATH];
DWORD len = GetModuleFileNameA(hm, path, MAX_PATH);
if (!len) return 0;
for (DWORD i = 0; i < len; i++) {
if (path[i] >= 'A' && path[i] <= 'Z') path[i] = (char)(path[i] - 'A' + 'a');
}
if (strstr(path, "_vk") || strstr(path, "vulkan")) return 1;
return 0;
}
static int ptr_belongs_to_dx12_backend(void *fn_ptr) {
if (!fn_ptr) return 0;
HMODULE hm = NULL;
if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR)fn_ptr, &hm) || !hm) {
return 0;
}
char path[MAX_PATH];
DWORD len = GetModuleFileNameA(hm, path, MAX_PATH);
if (!len) return 0;
for (DWORD i = 0; i < len; i++) {
if (path[i] >= 'A' && path[i] <= 'Z') path[i] = (char)(path[i] - 'A' + 'a');
}
if (strstr(path, "dx12") || strstr(path, "d3d12")) return 1;
return 0;
}
static void fsr_init_backend(WlFsr23Ctx *ctx, void *ffx_device, void *cb_probe, int is_fsr3) {
if (!ffx_device) return;
int is_vk = ptr_belongs_to_vk_backend(cb_probe);
int is_dx = ptr_belongs_to_dx12_backend(cb_probe);
if (!is_vk && !is_dx) {
// Fallback heuristic: if d3d12.dll is loaded, prefer DX12 unless vk backend module is present
if (GetModuleHandleA("ffx_backend_vk_x64.dll") || GetModuleHandleA("ffx_fsr2_api_vk_x64.dll")) {
is_vk = 1;
} else if (GetModuleHandleA("d3d12.dll")) {
is_dx = 1;
} else if (GetModuleHandleA("vulkan-1.dll")) {
is_vk = 1;
}
}
if (is_vk) {
ctx->is_dx12 = 0;
if (is_fsr3) {
// FSR 3 VK passes FfxVkDeviceContext* as FfxDevice
const WlFfxVkDevCtx3 *vkc = (const WlFfxVkDevCtx3 *)ffx_device;
if (vkc->vkDevice) {
wl_seam_init(&ctx->seam, NULL, vkc->vkPhysicalDevice, vkc->vkDevice, vkc->vkDeviceProcAddr);
}
} else {
// FSR 2 VK passes VkDevice directly as FfxDevice
wl_seam_init(&ctx->seam, NULL, NULL, (VkDevice)ffx_device, NULL);
}
} else {
ctx->is_dx12 = 1;
ctx->d3d12_dev = ffx_device;
ctx->dx12_interop = wl_query_vkd3d_interop(ffx_device);
if (ctx->dx12_interop) {
void *vk_inst = NULL, *vk_phys = NULL, *vk_dev = NULL;
if (ctx->dx12_interop->lpVtbl->GetVulkanHandles(ctx->dx12_interop, &vk_inst, &vk_phys, &vk_dev) == S_OK && vk_dev) {
wl_seam_init(&ctx->seam, vk_inst, vk_phys, vk_dev, NULL);
}
}
}
}
static void fsr_fill_ref(WlFsr23Ctx *ctx, WlFsr4ImageRef *dst, void *res,
uint32_t ffx_fmt, uint32_t ffx_state, uint32_t w, uint32_t h, int is_depth) {
memset(dst, 0, sizeof *dst);
if (!res) return;
if (!ctx->is_dx12) {
dst->vk_image = (uint64_t)(uintptr_t)res;
dst->vk_format = fsr_fmt_to_vk(ffx_fmt);
dst->vk_layout = fsr_state_to_vk_layout(ffx_state, is_depth);
dst->width = w;
dst->height = h;
dst->aspect = is_depth ? 2u : 1u;
} else if (ctx->dx12_interop) {
UINT64 vk_img = 0, off = 0;
UINT32 vk_fmt = 0;
if (ctx->dx12_interop->lpVtbl->GetVulkanResourceInfo1(ctx->dx12_interop, res, &vk_img, &off, &vk_fmt) == S_OK && vk_img) {
UINT32 layout = fsr_state_to_vk_layout(ffx_state, is_depth);
if (ctx->dx12_interop->lpVtbl->GetVulkanImageLayout) {
UINT32 queried = 0;
ctx->dx12_interop->lpVtbl->GetVulkanImageLayout(ctx->dx12_interop, res, fsr_state_to_d3d12(ffx_state), &queried);
if (queried != 0) layout = queried;
}
dst->vk_image = vk_img;
dst->vk_format = vk_fmt ? vk_fmt : fsr_fmt_to_vk(ffx_fmt);
dst->vk_layout = layout;
dst->width = w;
dst->height = h;
dst->aspect = is_depth ? 2u : 1u;
}
}
}
static int fsr_submit_frame_ex(WlFsr23Ctx *ctx, void *cmd_list, WlFsr4FrameDesc *f,
void *res_col, void *res_dep, void *res_mv, void *res_out) {
if (!ctx || !cmd_list || !ctx->seam.ready) return 0;
if (!ctx->is_dx12) {
return wl_seam_dispatch_or_blit(&ctx->seam, (VkCommandBuffer)cmd_list, f);
} else if (ctx->dx12_interop) {
int live_en = 1;
int live_backend = wl_seam_live_backend(&ctx->seam, &live_en);
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU && ctx->d3d12_dev) {
if (wl_xess3_eval_d3d12(&ctx->xess3, &ctx->seam, ctx->dx12_interop,
ctx->d3d12_dev, cmd_list, f,
res_col, res_dep, res_mv, res_out)) {
return 1;
}
wl_xess3_tag_fallback(&ctx->xess3, f);
} else {
wl_xess3_on_inactive(&ctx->xess3);
}
void *vk_cb = NULL;
int ok = 0;
if (ctx->dx12_interop->lpVtbl->BeginVkCommandBufferInterop(ctx->dx12_interop, cmd_list, &vk_cb) == S_OK && vk_cb) {
ok = wl_seam_dispatch_or_blit(&ctx->seam, (VkCommandBuffer)vk_cb, f);
ctx->dx12_interop->lpVtbl->EndVkCommandBufferInterop(ctx->dx12_interop, cmd_list);
}
return ok;
}
return 0;
}
static WlFsr23Ctx *unwrap_ctx(void *opaque_ctx) {
if (!opaque_ctx) return NULL;
WlFsrContextHeader *hdr = (WlFsrContextHeader *)opaque_ctx;
if (hdr->magic != WL_FSR23_MAGIC || !hdr->ctx || hdr->ctx->magic != WL_FSR23_MAGIC) return NULL;
return hdr->ctx;
}
static void destroy_ctx_common(void *opaque_ctx) {
WlFsr23Ctx *ctx = unwrap_ctx(opaque_ctx);
if (!ctx) return;
wl_xess3_destroy(&ctx->xess3);
wl_seam_destroy(&ctx->seam);
if (ctx->dx12_interop) {
ctx->dx12_interop->lpVtbl->Release(ctx->dx12_interop);
ctx->dx12_interop = NULL;
}
ctx->magic = 0;
free(ctx);
memset(opaque_ctx, 0, sizeof(WlFsrContextHeader));
}
// ============================================================================
// AMD FSR 3 Upscaler Exports (ffx_fsr3upscaler_x64.dll)
// ============================================================================
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerContextCreate(void *pContext, const void *pContextDescription) {
if (!pContext || !pContextDescription) return FFX_ERROR_INVALID_POINTER;
const WlFfxFsr30CtxDesc *d30 = (const WlFfxFsr30CtxDesc *)pContextDescription;
const WlFfxFsr31CtxDesc *d31 = (const WlFfxFsr31CtxDesc *)pContextDescription;
// Auto-detect FSR 3.0 vs FSR 3.1 layout:
// In FSR 3.0, backendInterface.scratchBufferSize is at offset 160 and device is at 168.
// In FSR 3.1, fpMessage precedes backendInterface so scratchBufferSize is at 168 and device is at 176.
int is_31 = 0;
size_t sz30 = d30->backendInterface.scratchBufferSize;
size_t sz31 = d31->backendInterface.scratchBufferSize;
int sz30_ok = (sz30 > 0 && sz30 < (64u * 1024u * 1024u) && d30->backendInterface.device != NULL);
int sz31_ok = (sz31 > 0 && sz31 < (64u * 1024u * 1024u) && d31->backendInterface.device != NULL);
if (sz31_ok && !sz30_ok) {
is_31 = 1;
} else if (!sz30_ok && d31->backendInterface.device != NULL && d30->backendInterface.callbacks[0] == NULL) {
is_31 = 1;
}
WlFsr23Ctx *ctx = (WlFsr23Ctx *)calloc(1, sizeof *ctx);
if (!ctx) return FFX_ERROR_OUT_OF_MEMORY;
ctx->magic = WL_FSR23_MAGIC;
ctx->is_fsr3 = 1;
ctx->is_fsr31 = is_31;
ctx->needs_reset = 1;
ctx->flags = d30->flags;
ctx->max_rw = d30->maxRenderSize.width;
ctx->max_rh = d30->maxRenderSize.height;
ctx->disp_w = d30->displaySize.width;
ctx->disp_h = d30->displaySize.height;
void *dev = is_31 ? d31->backendInterface.device : d30->backendInterface.device;
void *cb_probe = is_31 ? d31->backendInterface.callbacks[1] : d30->backendInterface.callbacks[1];
fsr_init_backend(ctx, dev, cb_probe, 1);
WlFsrContextHeader *hdr = (WlFsrContextHeader *)pContext;
hdr->magic = WL_FSR23_MAGIC;
hdr->pad = 0;
hdr->ctx = ctx;
return FFX_OK;
}
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerGetSharedResourceDescriptions(void *pContext, void *pSharedResources) {
WlFsr23Ctx *ctx = unwrap_ctx(pContext);
if (!ctx || !pSharedResources) return FFX_ERROR_INVALID_POINTER;
WlFfxFsr3SharedResDescs *sr = (WlFfxFsr3SharedResDescs *)pSharedResources;
memset(sr, 0, sizeof *sr);
uint32_t w = ctx->max_rw ? ctx->max_rw : 1280;
uint32_t h = ctx->max_rh ? ctx->max_rh : 720;
// reconstructedPrevNearestDepth: R32_UINT, UAV
sr->reconstructedPrevNearestDepth.resourceDescription.type = 2; /* TEXTURE2D */
sr->reconstructedPrevNearestDepth.resourceDescription.format = 7; /* R32_UINT */
sr->reconstructedPrevNearestDepth.resourceDescription.width = w;
sr->reconstructedPrevNearestDepth.resourceDescription.height = h;
sr->reconstructedPrevNearestDepth.resourceDescription.depth = 1;
sr->reconstructedPrevNearestDepth.resourceDescription.mipCount = 1;
sr->reconstructedPrevNearestDepth.resourceDescription.usage = 2; /* UAV */
sr->reconstructedPrevNearestDepth.initialState = 2; /* UNORDERED_ACCESS */
// dilatedDepth: R32_FLOAT, UAV
sr->dilatedDepth = sr->reconstructedPrevNearestDepth;
sr->dilatedDepth.resourceDescription.format = 24; /* R32_FLOAT */
// dilatedMotionVectors: R16G16_FLOAT, UAV
sr->dilatedMotionVectors = sr->reconstructedPrevNearestDepth;
sr->dilatedMotionVectors.resourceDescription.format = 14; /* R16G16_FLOAT */
return FFX_OK;
}
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerContextDispatch(void *pContext, const void *pDispatchDescription) {
WlFsr23Ctx *ctx = unwrap_ctx(pContext);
if (!ctx || !pDispatchDescription) return FFX_ERROR_INVALID_POINTER;
const WlFfxFsr30DispatchDesc *d30 = (const WlFfxFsr30DispatchDesc *)pDispatchDescription;
const WlFfxFsr31DispatchDesc *d31 = (const WlFfxFsr31DispatchDesc *)pDispatchDescription;
WlFsr4FrameDesc f;
memset(&f, 0, sizeof f);
uint32_t rw = d30->renderSize.width ? d30->renderSize.width : ctx->max_rw;
uint32_t rh = d30->renderSize.height ? d30->renderSize.height : ctx->max_rh;
uint32_t ow = ctx->disp_w;
uint32_t oh = ctx->disp_h;
if (ctx->is_fsr31 && d31->upscaleSize.width >= 64 && d31->upscaleSize.height >= 64) {
ow = d31->upscaleSize.width;
oh = d31->upscaleSize.height;
}
if (!ow && d30->output.description.width) ow = d30->output.description.width;
if (!oh && d30->output.description.height) oh = d30->output.description.height;
f.render_w = rw;
f.render_h = rh;
f.output_w = ow;
f.output_h = oh;
f.jitter_x = d30->jitterOffset.x;
f.jitter_y = d30->jitterOffset.y;
f.mv_scale_x = d30->motionVectorScale.x != 0.0f ? d30->motionVectorScale.x : 1.0f;
f.mv_scale_y = d30->motionVectorScale.y != 0.0f ? d30->motionVectorScale.y : 1.0f;
bool en_sharp = ctx->is_fsr31 ? d31->enableSharpening : d30->enableSharpening;
float sharp = ctx->is_fsr31 ? d31->sharpness : d30->sharpness;
float dt = ctx->is_fsr31 ? d31->frameTimeDelta : d30->frameTimeDelta;
float pre_exp = ctx->is_fsr31 ? d31->preExposure : d30->preExposure;
bool reset = ctx->is_fsr31 ? d31->reset : d30->reset;
float c_near = ctx->is_fsr31 ? d31->cameraNear : d30->cameraNear;
float c_far = ctx->is_fsr31 ? d31->cameraFar : d30->cameraFar;
float c_fov = ctx->is_fsr31 ? d31->cameraFovAngleVertical : d30->cameraFovAngleVertical;
f.pre_exposure = pre_exp > 0.0f ? pre_exp : 1.0f;
f.sharpness = sharp;
f.frame_time_ms = dt;
f.camera_near = c_near;
f.camera_far = c_far;
f.camera_fov_y = c_fov;
f.flags = fsr_flags_to_wl(ctx->flags);
if (en_sharp) f.flags |= WLFSR4_FLAG_SHARPEN;
if (reset || ctx->needs_reset) {
f.flags |= WLFSR4_FLAG_RESET;
ctx->needs_reset = 0;
}
f.api_source = ctx->is_dx12 ? WLFSR4_API_FSR3_DX12 : WLFSR4_API_FSR3_VK;
f.quality_mode = (g_last_quality_mode != WLFSR4_QUALITY_AUTO)
? g_last_quality_mode
: fsr_infer_quality(rw, ow);
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
int high_res_mv = (ctx->flags & (1u << 1)) ? 1 : 0;
fsr_fill_ref(ctx, &f.color, d30->color.resource, d30->color.description.format, d30->color.state,
d30->color.description.width ? d30->color.description.width : rw,
d30->color.description.height ? d30->color.description.height : rh, 0);
fsr_fill_ref(ctx, &f.depth, d30->depth.resource, d30->depth.description.format, d30->depth.state,
d30->depth.description.width ? d30->depth.description.width : rw,
d30->depth.description.height ? d30->depth.description.height : rh, 1);
fsr_fill_ref(ctx, &f.motion, d30->motionVectors.resource, d30->motionVectors.description.format, d30->motionVectors.state,
d30->motionVectors.description.width ? d30->motionVectors.description.width : (high_res_mv ? ow : rw),
d30->motionVectors.description.height ? d30->motionVectors.description.height : (high_res_mv ? oh : rh), 0);
fsr_fill_ref(ctx, &f.output, d30->output.resource, d30->output.description.format, d30->output.state,
d30->output.description.width ? d30->output.description.width : ow,
d30->output.description.height ? d30->output.description.height : oh, 0);
int ok = fsr_submit_frame_ex(ctx, d30->commandList, &f,
d30->color.resource, d30->depth.resource,
d30->motionVectors.resource, d30->output.resource);
return ok ? FFX_OK : FFX_ERROR_NULL_DEVICE;
}
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerContextGenerateReactiveMask(void *pContext, const void *pParams) {
(void)pContext; (void)pParams;
return FFX_OK;
}
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerContextDestroy(void *pContext) {
if (!pContext) return FFX_ERROR_INVALID_POINTER;
destroy_ctx_common(pContext);
return FFX_OK;
}
__declspec(dllexport) float ffxFsr3UpscalerGetUpscaleRatioFromQualityMode(uint32_t qualityMode) {
g_last_quality_mode = fsr_mode_to_wl(qualityMode);
return fsr_quality_ratio(qualityMode);
}
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerGetRenderResolutionFromQualityMode(
uint32_t *pRenderWidth, uint32_t *pRenderHeight,
uint32_t displayWidth, uint32_t displayHeight, uint32_t qualityMode) {
if (!pRenderWidth || !pRenderHeight) return FFX_ERROR_INVALID_POINTER;
float r = fsr_quality_ratio(qualityMode);
if (r <= 0.0f) return FFX_ERROR_INVALID_ENUM;
g_last_quality_mode = fsr_mode_to_wl(qualityMode);
*pRenderWidth = (uint32_t)((float)displayWidth / r);
*pRenderHeight = (uint32_t)((float)displayHeight / r);
return FFX_OK;
}
__declspec(dllexport) int32_t ffxFsr3UpscalerGetJitterPhaseCount(int32_t renderWidth, int32_t displayWidth) {
if (renderWidth <= 0) return 8;
float ratio = (float)displayWidth / (float)renderWidth;
int32_t pc = (int32_t)ceilf(8.0f * ratio * ratio);
return pc < 8 ? 8 : pc;
}
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerGetJitterOffset(float *pOutX, float *pOutY,
int32_t index, int32_t phaseCount) {
if (!pOutX || !pOutY) return FFX_ERROR_INVALID_POINTER;
if (phaseCount <= 0) return FFX_ERROR_INVALID_ARGUMENT;
int32_t idx = (index % phaseCount) + 1;
if (idx <= 0) idx += phaseCount;
*pOutX = fsr_halton(idx, 2) - 0.5f;
*pOutY = fsr_halton(idx, 3) - 0.5f;
return FFX_OK;
}
__declspec(dllexport) bool ffxFsr3UpscalerResourceIsNull(WlFfxResource3 resource) {
return resource.resource == NULL;
}
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerSetConstant(void *pContext, uint32_t key, void *valuePtr) {
(void)pContext; (void)key; (void)valuePtr;
return FFX_OK;
}
__declspec(dllexport) uint32_t ffxFsr3UpscalerGetEffectVersion(void) {
return (3u << 22) | (1u << 12) | 0u;
}
// ============================================================================
// AMD FSR 2 Core Exports (ffx_fsr2_api_x64.dll)
// ============================================================================
__declspec(dllexport) FfxErrorCode ffxFsr2ContextCreate(void *pContext, const void *pContextDescription) {
if (!pContext || !pContextDescription) return FFX_ERROR_INVALID_POINTER;
const WlFfxFsr2CtxDesc *d = (const WlFfxFsr2CtxDesc *)pContextDescription;
WlFsr23Ctx *ctx = (WlFsr23Ctx *)calloc(1, sizeof *ctx);
if (!ctx) return FFX_ERROR_OUT_OF_MEMORY;
ctx->magic = WL_FSR23_MAGIC;
ctx->is_fsr3 = 0;
ctx->is_fsr31 = 0;
ctx->needs_reset = 1;
ctx->flags = d->flags;
ctx->max_rw = d->maxRenderSize.width;
ctx->max_rh = d->maxRenderSize.height;
ctx->disp_w = d->displaySize.width;
ctx->disp_h = d->displaySize.height;
fsr_init_backend(ctx, d->device, d->callbacks.callbacks[0], 0);
WlFsrContextHeader *hdr = (WlFsrContextHeader *)pContext;
hdr->magic = WL_FSR23_MAGIC;
hdr->pad = 0;
hdr->ctx = ctx;
return FFX_OK;
}
__declspec(dllexport) FfxErrorCode ffxFsr2ContextDispatch(void *pContext, const void *pDispatchDescription) {
WlFsr23Ctx *ctx = unwrap_ctx(pContext);
if (!ctx || !pDispatchDescription) return FFX_ERROR_INVALID_POINTER;
const WlFfxFsr21DispatchDesc *d21 = (const WlFfxFsr21DispatchDesc *)pDispatchDescription;
const WlFfxFsr20DispatchDesc *d20 = (const WlFfxFsr20DispatchDesc *)pDispatchDescription;
// Auto-detect FSR 2.1/2.2 (184-byte FfxResource with wchar_t name[64]) vs FSR 2.0 (56-byte FfxResource)
int use_21 = (d21->renderSize.width >= 64 && d21->renderSize.width <= 16384 &&
d21->renderSize.height >= 64 && d21->renderSize.height <= 16384 &&
d21->output.resource != NULL);
WlFsr4FrameDesc f;
memset(&f, 0, sizeof f);
uint32_t rw = use_21 ? d21->renderSize.width : d20->renderSize.width;
uint32_t rh = use_21 ? d21->renderSize.height : d20->renderSize.height;
if (!rw) rw = ctx->max_rw;
if (!rh) rh = ctx->max_rh;
uint32_t ow = ctx->disp_w;
uint32_t oh = ctx->disp_h;
int high_res_mv = (ctx->flags & (1u << 1)) ? 1 : 0;
f.render_w = rw;
f.render_h = rh;
f.output_w = ow;
f.output_h = oh;
f.jitter_x = use_21 ? d21->jitterOffset.x : d20->jitterOffset.x;
f.jitter_y = use_21 ? d21->jitterOffset.y : d20->jitterOffset.y;
float mvx = use_21 ? d21->motionVectorScale.x : d20->motionVectorScale.x;
float mvy = use_21 ? d21->motionVectorScale.y : d20->motionVectorScale.y;
f.mv_scale_x = mvx != 0.0f ? mvx : 1.0f;
f.mv_scale_y = mvy != 0.0f ? mvy : 1.0f;
float pre_exp = use_21 ? d21->preExposure : d20->preExposure;
f.pre_exposure = pre_exp > 0.0f ? pre_exp : 1.0f;
f.sharpness = use_21 ? d21->sharpness : d20->sharpness;
f.frame_time_ms = use_21 ? d21->frameTimeDelta : d20->frameTimeDelta;
f.camera_near = use_21 ? d21->cameraNear : d20->cameraNear;
f.camera_far = use_21 ? d21->cameraFar : d20->cameraFar;
f.camera_fov_y = use_21 ? d21->cameraFovAngleVertical : d20->cameraFovAngleVertical;
f.flags = fsr_flags_to_wl(ctx->flags);
if (use_21 ? d21->enableSharpening : d20->enableSharpening) f.flags |= WLFSR4_FLAG_SHARPEN;
if ((use_21 ? d21->reset : d20->reset) || ctx->needs_reset) {
f.flags |= WLFSR4_FLAG_RESET;
ctx->needs_reset = 0;
}
f.api_source = ctx->is_dx12 ? WLFSR4_API_FSR2_DX12 : WLFSR4_API_FSR2_VK;
f.quality_mode = (g_last_quality_mode != WLFSR4_QUALITY_AUTO)
? g_last_quality_mode
: fsr_infer_quality(rw, ow);
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
if (use_21) {
fsr_fill_ref(ctx, &f.color, d21->color.resource, d21->color.description.format, d21->color.state,
d21->color.description.width ? d21->color.description.width : rw,
d21->color.description.height ? d21->color.description.height : rh, 0);
fsr_fill_ref(ctx, &f.depth, d21->depth.resource, d21->depth.description.format, d21->depth.state,
d21->depth.description.width ? d21->depth.description.width : rw,
d21->depth.description.height ? d21->depth.description.height : rh, 1);
fsr_fill_ref(ctx, &f.motion, d21->motionVectors.resource, d21->motionVectors.description.format, d21->motionVectors.state,
d21->motionVectors.description.width ? d21->motionVectors.description.width : (high_res_mv ? ow : rw),
d21->motionVectors.description.height ? d21->motionVectors.description.height : (high_res_mv ? oh : rh), 0);
fsr_fill_ref(ctx, &f.output, d21->output.resource, d21->output.description.format, d21->output.state,
d21->output.description.width ? d21->output.description.width : ow,
d21->output.description.height ? d21->output.description.height : oh, 0);
} else {
fsr_fill_ref(ctx, &f.color, d20->color.resource, d20->color.description.format, d20->color.state,
d20->color.description.width ? d20->color.description.width : rw,
d20->color.description.height ? d20->color.description.height : rh, 0);
fsr_fill_ref(ctx, &f.depth, d20->depth.resource, d20->depth.description.format, d20->depth.state,
d20->depth.description.width ? d20->depth.description.width : rw,
d20->depth.description.height ? d20->depth.description.height : rh, 1);
fsr_fill_ref(ctx, &f.motion, d20->motionVectors.resource, d20->motionVectors.description.format, d20->motionVectors.state,
d20->motionVectors.description.width ? d20->motionVectors.description.width : (high_res_mv ? ow : rw),
d20->motionVectors.description.height ? d20->motionVectors.description.height : (high_res_mv ? oh : rh), 0);
fsr_fill_ref(ctx, &f.output, d20->output.resource, d20->output.description.format, d20->output.state,
d20->output.description.width ? d20->output.description.width : ow,
d20->output.description.height ? d20->output.description.height : oh, 0);
}
int ok = fsr_submit_frame_ex(ctx, d21->commandList, &f,
use_21 ? d21->color.resource : d20->color.resource,
use_21 ? d21->depth.resource : d20->depth.resource,
use_21 ? d21->motionVectors.resource : d20->motionVectors.resource,
use_21 ? d21->output.resource : d20->output.resource);
return ok ? FFX_OK : FFX_ERROR_NULL_DEVICE;
}
__declspec(dllexport) FfxErrorCode ffxFsr2ContextGenerateReactiveMask(void *pContext, const void *pParams) {
(void)pContext; (void)pParams;
return FFX_OK;
}
__declspec(dllexport) FfxErrorCode ffxFsr2ContextDestroy(void *pContext) {
if (!pContext) return FFX_ERROR_INVALID_POINTER;
destroy_ctx_common(pContext);
return FFX_OK;
}
__declspec(dllexport) float ffxFsr2GetUpscaleRatioFromQualityMode(uint32_t qualityMode) {
g_last_quality_mode = fsr_mode_to_wl(qualityMode);
return fsr_quality_ratio(qualityMode);
}
__declspec(dllexport) FfxErrorCode ffxFsr2GetRenderResolutionFromQualityMode(
uint32_t *renderWidth, uint32_t *renderHeight,
uint32_t displayWidth, uint32_t displayHeight, uint32_t qualityMode) {
return ffxFsr3UpscalerGetRenderResolutionFromQualityMode(
renderWidth, renderHeight, displayWidth, displayHeight, qualityMode);
}
__declspec(dllexport) int32_t ffxFsr2GetJitterPhaseCount(int32_t renderWidth, int32_t displayWidth) {
return ffxFsr3UpscalerGetJitterPhaseCount(renderWidth, displayWidth);
}
__declspec(dllexport) FfxErrorCode ffxFsr2GetJitterOffset(float *outX, float *outY,
int32_t index, int32_t phaseCount) {
return ffxFsr3UpscalerGetJitterOffset(outX, outY, index, phaseCount);
}
__declspec(dllexport) bool ffxFsr2ResourceIsNull(WlFfxResource21 resource) {
return resource.resource == NULL;
}
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
(void)hinst; (void)reason; (void)reserved;
return TRUE;
}
+949
View File
@@ -0,0 +1,949 @@
// DroidDeck: modified from michaelisomer-cyber/Winlator-NeuralScale a0ab6b0f (see README.md).
// Winlator Ludashi OptiScaler-style NVIDIA NGX (DLSS) -> AMD FSR 4.1.1 Hexagon HTP NPU Bridge
//
// Exports the full 89-symbol NVIDIA NGX ABI (Vulkan + D3D12 + D3D11) so DLSS-capable Windows
// games (such as Red Dead Redemption 2 on Vulkan, Rise of the Tomb Raider / Cyberpunk on DX12)
// unlock DLSS in-game and route every EvaluateFeature call zero-copy into our native Android
// Vulkan Layer (libVkLayer_winlator_fsr4_npu.so) running FSR 4.1.1 on the Hexagon HTP v81 NPU.
#include <windows.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include "wl_seam_client.h"
#include "wl_vkd3d_interop.h"
#include "wl_xess3_direct.h"
typedef uint32_t NVSDK_NGX_Result;
#define NVSDK_NGX_Result_Success 0x00000001u
#define NVSDK_NGX_Result_Fail 0xBAD00000u
#define NVSDK_NGX_Result_FAIL_FeatureNotSupported 0xBAD00001u
#define NVSDK_NGX_Result_FAIL_InvalidParameter 0xBAD00005u
#define NVSDK_NGX_Result_FAIL_NotInitialized 0xBAD00007u
typedef struct { uint32_t Id; } NVSDK_NGX_Handle;
typedef struct {
uint32_t FeatureSupported; /* 0 = NVSDK_NGX_FeatureSupportResult_Supported */
uint32_t MinHWArchitecture; /* 0 */
char MinOSVersion[255];
} NVSDK_NGX_FeatureRequirement;
typedef struct {
uint32_t SDKVersion;
uint32_t FeatureID; /* 1=SuperSampling, 11=FrameGeneration, 13=RayReconstruction */
} NVSDK_NGX_FeatureDiscoveryInfoHead;
// Exact NVIDIA nvsdk_ngx_defs_vk.h layout (verified against NVIDIA/DLSS)
typedef struct {
uint32_t aspectMask;
uint32_t baseMipLevel;
uint32_t levelCount;
uint32_t baseArrayLayer;
uint32_t layerCount;
} WlVkImageSubresourceRange;
typedef struct {
uint64_t ImageView;
uint64_t Image;
WlVkImageSubresourceRange SubresourceRange;
uint32_t Format;
uint32_t Width;
uint32_t Height;
} NVSDK_NGX_ImageViewInfo_VK;
typedef struct {
uint64_t Buffer;
uint32_t SizeInBytes;
} NVSDK_NGX_BufferInfo_VK;
typedef struct {
union {
NVSDK_NGX_ImageViewInfo_VK ImageViewInfo;
NVSDK_NGX_BufferInfo_VK BufferInfo;
} Resource;
uint32_t Type; /* 0 = VK_IMAGEVIEW, 1 = VK_BUFFER */
bool ReadWrite;
} NVSDK_NGX_Resource_VK;
// ---- Parameter bag with exact 17-slot MSVC x64 C++ vtable ----
#define MAX_PARAMS 160
typedef struct {
char key[96];
int type; /* 0=ull/i/ui, 1=f, 2=d, 3=ptr */
uint64_t u;
float f;
double d;
void *p;
} WlNgxKv;
typedef struct WlNgxParam {
void **vtbl;
int owned;
int count;
WlNgxKv kv[MAX_PARAMS];
} WlNgxParam;
static WlNgxKv *kv_find(WlNgxParam *s, const char *k) {
if (!s || !k) return NULL;
for (int i = 0; i < s->count; i++) {
if (_stricmp(s->kv[i].key, k) == 0) return &s->kv[i];
}
return NULL;
}
static void kv_set(WlNgxParam *s, const char *k, int type, uint64_t u, float f, double d, void *p) {
if (!s || !k) return;
WlNgxKv *e = kv_find(s, k);
if (!e) {
if (s->count >= MAX_PARAMS) return;
e = &s->kv[s->count++];
memset(e, 0, sizeof *e);
strncpy(e->key, k, sizeof(e->key) - 1);
}
e->type = type; e->u = u; e->f = f; e->d = d; e->p = p;
}
static int kv_get_u(WlNgxParam *s, const char *k, uint64_t *out) {
WlNgxKv *e = kv_find(s, k);
if (!e) return 0;
if (out) {
if (e->type == 0) *out = e->u;
else if (e->type == 1) *out = (uint64_t)(int64_t)e->f;
else if (e->type == 2) *out = (uint64_t)(int64_t)e->d;
else *out = (uint64_t)(uintptr_t)e->p;
}
return 1;
}
static int kv_get_f(WlNgxParam *s, const char *k, float *out) {
WlNgxKv *e = kv_find(s, k);
if (!e) return 0;
if (out) {
if (e->type == 1) *out = e->f;
else if (e->type == 2) *out = (float)e->d;
else *out = (float)(int64_t)e->u;
}
return 1;
}
static int kv_get_d(WlNgxParam *s, const char *k, double *out) {
WlNgxKv *e = kv_find(s, k);
if (!e) return 0;
if (out) {
if (e->type == 2) *out = e->d;
else if (e->type == 1) *out = (double)e->f;
else *out = (double)(int64_t)e->u;
}
return 1;
}
static int kv_get_p(WlNgxParam *s, const char *k, void **out) {
WlNgxKv *e = kv_find(s, k);
if (!e) return 0;
if (out) *out = (e->type == 3) ? e->p : (void *)(uintptr_t)e->u;
return 1;
}
// MSVC x64 C++ overloaded virtual function layout (reverse declaration order within Set/Get groups)
static void __cdecl P_SetVP(WlNgxParam *s, const char *k, void *v) { kv_set(s, k, 3, (uint64_t)(uintptr_t)v, 0, 0, v); }
static void __cdecl P_SetD12(WlNgxParam *s, const char *k, void *v) { kv_set(s, k, 3, (uint64_t)(uintptr_t)v, 0, 0, v); }
static void __cdecl P_SetD11(WlNgxParam *s, const char *k, void *v) { kv_set(s, k, 3, (uint64_t)(uintptr_t)v, 0, 0, v); }
static void __cdecl P_SetI(WlNgxParam *s, const char *k, int v) { kv_set(s, k, 0, (uint64_t)(int64_t)v, (float)v, (double)v, NULL); }
static void __cdecl P_SetUI(WlNgxParam *s, const char *k, uint32_t v) { kv_set(s, k, 0, (uint64_t)v, (float)v, (double)v, NULL); }
static void __cdecl P_SetD(WlNgxParam *s, const char *k, double v) { kv_set(s, k, 2, (uint64_t)(int64_t)v, (float)v, v, NULL); }
static void __cdecl P_SetF(WlNgxParam *s, const char *k, float v) { kv_set(s, k, 1, (uint64_t)(int64_t)v, v, (double)v, NULL); }
static void __cdecl P_SetULL(WlNgxParam *s, const char *k, uint64_t v) { kv_set(s, k, 0, v, (float)v, (double)v, (void *)(uintptr_t)v); }
static NVSDK_NGX_Result __cdecl P_GetVP(WlNgxParam *s, const char *k, void **v) { return kv_get_p(s, k, v) ? NVSDK_NGX_Result_Success : NVSDK_NGX_Result_FAIL_InvalidParameter; }
static NVSDK_NGX_Result __cdecl P_GetD12(WlNgxParam *s, const char *k, void **v) { return kv_get_p(s, k, v) ? NVSDK_NGX_Result_Success : NVSDK_NGX_Result_FAIL_InvalidParameter; }
static NVSDK_NGX_Result __cdecl P_GetD11(WlNgxParam *s, const char *k, void **v) { return kv_get_p(s, k, v) ? NVSDK_NGX_Result_Success : NVSDK_NGX_Result_FAIL_InvalidParameter; }
static NVSDK_NGX_Result __cdecl P_GetI(WlNgxParam *s, const char *k, int *v) { uint64_t t = 0; if (!kv_get_u(s, k, &t)) return NVSDK_NGX_Result_FAIL_InvalidParameter; if (v) *v = (int)(int64_t)t; return NVSDK_NGX_Result_Success; }
static NVSDK_NGX_Result __cdecl P_GetUI(WlNgxParam *s, const char *k, uint32_t *v) { uint64_t t = 0; if (!kv_get_u(s, k, &t)) return NVSDK_NGX_Result_FAIL_InvalidParameter; if (v) *v = (uint32_t)t; return NVSDK_NGX_Result_Success; }
static NVSDK_NGX_Result __cdecl P_GetD(WlNgxParam *s, const char *k, double *v) { return kv_get_d(s, k, v) ? NVSDK_NGX_Result_Success : NVSDK_NGX_Result_FAIL_InvalidParameter; }
static NVSDK_NGX_Result __cdecl P_GetF(WlNgxParam *s, const char *k, float *v) { return kv_get_f(s, k, v) ? NVSDK_NGX_Result_Success : NVSDK_NGX_Result_FAIL_InvalidParameter; }
static NVSDK_NGX_Result __cdecl P_GetULL(WlNgxParam *s, const char *k, uint64_t *v) { return kv_get_u(s, k, v) ? NVSDK_NGX_Result_Success : NVSDK_NGX_Result_FAIL_InvalidParameter; }
static void __cdecl P_Reset(WlNgxParam *s) { if (s) s->count = 0; }
static void *g_param_vtbl[17] = {
(void *)P_SetVP, (void *)P_SetD12, (void *)P_SetD11, (void *)P_SetI,
(void *)P_SetUI, (void *)P_SetD, (void *)P_SetF, (void *)P_SetULL,
(void *)P_GetVP, (void *)P_GetD12, (void *)P_GetD11, (void *)P_GetI,
(void *)P_GetUI, (void *)P_GetD, (void *)P_GetF, (void *)P_GetULL,
(void *)P_Reset,
};
static volatile uint32_t g_last_perf_quality = 0xFFFFFFFFu;
static uint32_t ngx_pq_to_wl_quality(uint32_t pq) {
switch (pq) {
case 0u: return WLFSR4_QUALITY_PERF;
case 1u: return WLFSR4_QUALITY_BALANCED;
case 2u: return WLFSR4_QUALITY_QUALITY;
case 3u: return WLFSR4_QUALITY_ULTRA_PERF;
case 4u: return WLFSR4_QUALITY_ULTRA_QUAL;
case 5u: return WLFSR4_QUALITY_NATIVE_AA;
default: return WLFSR4_QUALITY_AUTO;
}
}
static uint32_t infer_quality_from_res(uint32_t rw, uint32_t ow) {
if (rw == 0u || ow == 0u) return WLFSR4_QUALITY_AUTO;
float r = (float)ow / (float)rw;
if (r < 1.15f) return WLFSR4_QUALITY_NATIVE_AA;
if (r < 1.38f) return WLFSR4_QUALITY_ULTRA_QUAL;
if (r < 1.60f) return WLFSR4_QUALITY_QUALITY;
if (r < 1.85f) return WLFSR4_QUALITY_BALANCED;
if (r < 2.45f) return WLFSR4_QUALITY_PERF;
return WLFSR4_QUALITY_ULTRA_PERF;
}
static NVSDK_NGX_Result __cdecl dlss_optimal_settings_cb(WlNgxParam *p) {
if (!p) return NVSDK_NGX_Result_FAIL_InvalidParameter;
uint64_t ow = 1920, oh = 1080, pq = 0;
if (!kv_get_u(p, "Width", &ow)) kv_get_u(p, "#\x10", &ow);
if (!kv_get_u(p, "Height", &oh)) kv_get_u(p, "#\x11", &oh);
if (kv_get_u(p, "PerfQualityValue", &pq) || kv_get_u(p, "#\x3f", &pq)) {
g_last_perf_quality = (uint32_t)pq;
}
// Map DLSS quality values to exact FSR 4.1.1 scale ratios
float scale = 2.0f; /* MaxPerf = 2.0x -> 960x540 for 1080p */
if (pq == 1) scale = 1.7f; /* Balanced */
else if (pq == 2) scale = 1.5f; /* MaxQuality */
else if (pq == 3) scale = 3.0f; /* UltraPerformance */
else if (pq == 4) scale = 1.3f; /* UltraQuality */
else if (pq == 5) scale = 1.0f; /* DLAA */
uint32_t rw = ((uint32_t)((float)ow / scale)) & ~1u;
uint32_t rh = ((uint32_t)((float)oh / scale)) & ~1u;
if (rw < 320u) rw = 320u;
if (rh < 180u) rh = 180u;
uint32_t minw = ((uint32_t)((float)ow * 0.5f)) & ~1u;
uint32_t minh = ((uint32_t)((float)oh * 0.5f)) & ~1u;
if (rw < minw || rh < minh) { minw = rw; minh = rh; }
if (pq == 5) { minw = rw; minh = rh; }
float scale_ratio = (ow > 0) ? ((float)rw / (float)ow) : (1.0f / scale);
uint64_t scratch_bytes = (uint64_t)ow * (uint64_t)oh * 31ULL;
P_SetF(p, "Scale", scale_ratio);
P_SetF(p, "SuperSampling.ScaleFactor", scale_ratio);
P_SetUI(p, "OutWidth", rw);
P_SetUI(p, "OutHeight", rh);
P_SetUI(p, "DLSS.Get.Dynamic.Max.Render.Width", (uint32_t)ow);
P_SetUI(p, "DLSS.Get.Dynamic.Max.Render.Height", (uint32_t)oh);
P_SetUI(p, "DLSS.Get.Dynamic.Min.Render.Width", minw);
P_SetUI(p, "DLSS.Get.Dynamic.Min.Render.Height", minh);
P_SetF(p, "Sharpness", 0.0f);
P_SetULL(p, "SizeInBytes", scratch_bytes);
P_SetI(p, "DLSSMode", 1); /* NVSDK_NGX_DLSS_Mode_DLSS_DLISP */
// Legacy EParameter aliases used by older NGX SDK titles (e.g. RDR2)
P_SetF(p, "#\x0f", scale_ratio);
P_SetUI(p, "#\x12", rw);
P_SetUI(p, "#\x13", rh);
P_SetULL(p, "#\x30", scratch_bytes);
P_SetI(p, "#\x41", 1);
return NVSDK_NGX_Result_Success;
}
static NVSDK_NGX_Result __cdecl dlss_get_stats_cb(WlNgxParam *p) {
if (p) {
uint64_t w = 1920, h = 1080;
kv_get_u(p, "Width", &w);
kv_get_u(p, "Height", &h);
P_SetULL(p, "SizeInBytes", w * h * 31ULL);
}
return NVSDK_NGX_Result_Success;
}
static void populate_cap_params(WlNgxParam *p) {
if (!p) return;
P_SetI(p, "SuperSampling.Available", 1);
P_SetI(p, "SuperSampling.NeedsUpdatedDriver", 0);
P_SetUI(p, "SuperSampling.MinDriverVersionMajor", 0);
P_SetUI(p, "SuperSampling.MinDriverVersionMinor", 0);
P_SetUI(p, "SuperSampling.FeatureInitResult", NVSDK_NGX_Result_Success);
P_SetI(p, "SuperSampling.Allow", 1);
P_SetI(p, "DLSS.Available", 1);
P_SetI(p, "Snippet.OptIn", 1);
P_SetI(p, "Snippet.OptLevel", 0);
P_SetI(p, "Snippet.IsDevBranch", 0);
P_SetI(p, "FreeMemOnReleaseFeature", 0);
P_SetI(p, "CreationNodeMask", 1);
P_SetI(p, "VisibilityNodeMask", 1);
P_SetI(p, "DLSS.Enable.Output.Subrects", 1);
P_SetI(p, "RTXValue", 0);
P_SetF(p, "Sharpness", 0.0f);
P_SetF(p, "MV.Scale.X", 1.0f);
P_SetF(p, "MV.Scale.Y", 1.0f);
P_SetF(p, "MV.Offset.X", 0.0f);
P_SetF(p, "MV.Offset.Y", 0.0f);
P_SetF(p, "DLSS.Exposure.Scale", 1.0f);
P_SetI(p, "PerfQualityValue", 0);
P_SetULL(p, "SizeInBytes", 1920ULL * 1080ULL * 31ULL);
P_SetVP(p, "DLSSOptimalSettingsCallback", (void *)dlss_optimal_settings_cb);
P_SetVP(p, "DLSSDOptimalSettingsCallback", (void *)dlss_optimal_settings_cb);
P_SetVP(p, "DLSSGetStatsCallback", (void *)dlss_get_stats_cb);
// Render preset hints (DLSS 3.1+ / Streamline / Cyberpunk 2077)
P_SetUI(p, "DLSS.Hint.Render.Preset.DLAA", 0u);
P_SetUI(p, "DLSS.Hint.Render.Preset.UltraQuality", 0u);
P_SetUI(p, "DLSS.Hint.Render.Preset.Quality", 0u);
P_SetUI(p, "DLSS.Hint.Render.Preset.Balanced", 0u);
P_SetUI(p, "DLSS.Hint.Render.Preset.Performance", 0u);
P_SetUI(p, "DLSS.Hint.Render.Preset.UltraPerformance", 0u);
// Report Ray Reconstruction & Frame Generation unavailable so games stick to DLSS Super Resolution
P_SetI(p, "SuperSamplingDenoising.Available", 0);
P_SetI(p, "SuperSamplingDenoising.NeedsUpdatedDriver", 0);
P_SetUI(p, "SuperSamplingDenoising.MinDriverVersionMajor", 0);
P_SetUI(p, "SuperSamplingDenoising.MinDriverVersionMinor", 0);
P_SetI(p, "SuperSamplingDenoising.FeatureInitResult", 0);
P_SetI(p, "FrameGeneration.Available", 0);
P_SetI(p, "FrameInterpolation.Available", 0);
// Legacy EParameter aliases (CRITICAL for RDR2 / DLSS 2.x games)
P_SetI(p, "#\x01", 1); /* SuperSampling_Available */
P_SetI(p, "#\x44", 0); /* OptLevel */
P_SetI(p, "#\x45", 0); /* IsDevSnippetBranch */
P_SetVP(p, "#\x3e", (void *)dlss_optimal_settings_cb); /* DLSSOptimalSettingsCallback */
P_SetF(p, "#\x14", 0.0f); /* Sharpness */
P_SetF(p, "#\x2c", 1.0f); /* MV_Scale_X */
P_SetF(p, "#\x2d", 1.0f); /* MV_Scale_Y */
P_SetF(p, "#\x38", 0.0f); /* MV_Offset_X */
P_SetF(p, "#\x39", 0.0f); /* MV_Offset_Y */
}
static WlNgxParam *alloc_param(int owned, int caps) {
WlNgxParam *p = (WlNgxParam *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WlNgxParam));
if (!p) return NULL;
p->vtbl = g_param_vtbl;
p->owned = owned;
if (caps) populate_cap_params(p);
return p;
}
// ---- Global Vulkan & DX12 runtime state ----
static CRITICAL_SECTION g_cs;
static int g_cs_ready = 0;
static WlSeamClient g_vk_seam;
static WlSeamClient g_dx12_seam;
static WlID3D12DXVKInteropDevice1 *g_dx12_interop = NULL;
static void *g_d3d12_dev = NULL;
static WlXess3State g_vk_xess3;
static WlXess3State g_dx12_xess3;
static WlNgxParam *g_cap_param = NULL;
static uint32_t g_next_handle_id = 1u;
typedef struct {
uint32_t id;
int is_dx12;
int has_perf_quality;
int needs_reset;
uint32_t rw, rh, ow, oh;
uint32_t create_flags;
uint32_t perf_quality;
} WlNgxFeature;
#define MAX_FEATURES 16
static WlNgxFeature g_feats[MAX_FEATURES];
static void ensure_cs(void) {
if (!g_cs_ready) { InitializeCriticalSection(&g_cs); g_cs_ready = 1; }
}
static WlNgxFeature *find_feat(const NVSDK_NGX_Handle *h) {
if (!h) return NULL;
for (int i = 0; i < MAX_FEATURES; i++) {
if (g_feats[i].id == h->Id) return &g_feats[i];
}
return NULL;
}
static WlNgxFeature *create_feat(int is_dx12, WlNgxParam *params, NVSDK_NGX_Handle **out_h) {
for (int i = 0; i < MAX_FEATURES; i++) {
if (g_feats[i].id == 0) {
WlNgxFeature *f = &g_feats[i];
memset(f, 0, sizeof *f);
f->id = g_next_handle_id++;
f->is_dx12 = is_dx12;
f->needs_reset = 1;
uint64_t v = 0;
if (kv_get_u(params, "Width", &v) || kv_get_u(params, "#\x10", &v)) f->rw = (uint32_t)v;
if (kv_get_u(params, "Height", &v) || kv_get_u(params, "#\x11", &v)) f->rh = (uint32_t)v;
if (kv_get_u(params, "OutWidth", &v) || kv_get_u(params, "#\x12", &v)) f->ow = (uint32_t)v;
if (kv_get_u(params, "OutHeight", &v) || kv_get_u(params, "#\x13", &v)) f->oh = (uint32_t)v;
if (kv_get_u(params, "DLSS.Feature.Create.Flags", &v)) f->create_flags = (uint32_t)v;
if (kv_get_u(params, "PerfQualityValue", &v) || kv_get_u(params, "#\x3f", &v)) {
f->perf_quality = (uint32_t)v;
f->has_perf_quality = 1;
g_last_perf_quality = (uint32_t)v;
} else if (g_last_perf_quality != 0xFFFFFFFFu) {
f->perf_quality = g_last_perf_quality;
f->has_perf_quality = 1;
}
NVSDK_NGX_Handle *nh = (NVSDK_NGX_Handle *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(NVSDK_NGX_Handle));
nh->Id = f->id;
if (out_h) *out_h = nh;
return f;
}
}
return NULL;
}
static void apply_ngx_create_flags(WlFsr4FrameDesc *dst, uint32_t cf) {
if (cf & (1u << 0)) dst->flags |= WLFSR4_FLAG_HDR;
if (!(cf & (1u << 1)) && cf != 0u) dst->flags |= WLFSR4_FLAG_DISPLAY_RES_MV;
if (cf & (1u << 2)) dst->flags |= WLFSR4_FLAG_MV_JITTERED;
if (cf & (1u << 3)) dst->flags |= WLFSR4_FLAG_DEPTH_INVERTED;
if (cf & (1u << 5)) dst->flags |= WLFSR4_FLAG_SHARPEN;
if (cf & (1u << 6)) dst->flags |= WLFSR4_FLAG_AUTO_EXPOSURE;
}
static uint64_t g_app_id = 0x24480451ULL;
// ---- Generic C parameter helpers & NGX metadata exports ----
__declspec(dllexport) const wchar_t *GetNGXResultAsString(NVSDK_NGX_Result r) {
return (r == NVSDK_NGX_Result_Success) ? L"NVSDK_NGX_Result_Success" : L"NVSDK_NGX_Result_Fail";
}
__declspec(dllexport) uint32_t NVSDK_NGX_GetAPIVersion(void) { return 19u; }
__declspec(dllexport) uint32_t NVSDK_NGX_GetApplicationId(void) { return (uint32_t)g_app_id; }
__declspec(dllexport) uint32_t NVSDK_NGX_GetDriverVersion(void) { return 0x023A0000u; /* 570.00 */ }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_GetDriverVersionEx(uint32_t *versions, uint32_t inCnt, uint32_t *outCnt) {
if (!versions && !outCnt) return NVSDK_NGX_Result_FAIL_InvalidParameter;
if (outCnt) *outCnt = 2u;
if (versions && inCnt >= 1u) {
versions[0] = 570u;
if (inCnt >= 2u) versions[1] = 0u;
}
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) uint32_t NVSDK_NGX_GetGPUArchitecture(void) { return 0x0190u; /* Ada */ }
__declspec(dllexport) uint32_t NVSDK_NGX_GetSnippetVersion(void) { return 0x00030700u; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_ProcessCommand(const char *cmd, const char *val, void *unk) { (void)cmd; (void)val; (void)unk; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_SetInfoCallback(void *cb) { (void)cb; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_SetTelemetryEvaluateCallback(void *cb) { (void)cb; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_UpdateFeature(const void *a, uint32_t b) { (void)a; (void)b; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_SetULL(WlNgxParam *p, const char *k, uint64_t v) { P_SetULL(p, k, v); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_SetF(WlNgxParam *p, const char *k, float v) { P_SetF(p, k, v); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_SetD(WlNgxParam *p, const char *k, double v) { P_SetD(p, k, v); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_SetUI(WlNgxParam *p, const char *k, uint32_t v) { P_SetUI(p, k, v); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_SetI(WlNgxParam *p, const char *k, int v) { P_SetI(p, k, v); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_SetD3d11Resource(WlNgxParam *p, const char *k, void *v) { P_SetD11(p, k, v); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_SetD3d12Resource(WlNgxParam *p, const char *k, void *v) { P_SetD12(p, k, v); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_SetVoidPointer(WlNgxParam *p, const char *k, void *v) { P_SetVP(p, k, v); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_GetULL(WlNgxParam *p, const char *k, uint64_t *v) { return P_GetULL(p, k, v); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_GetF(WlNgxParam *p, const char *k, float *v) { return P_GetF(p, k, v); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_GetD(WlNgxParam *p, const char *k, double *v) { return P_GetD(p, k, v); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_GetUI(WlNgxParam *p, const char *k, uint32_t *v) { return P_GetUI(p, k, v); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_GetI(WlNgxParam *p, const char *k, int *v) { return P_GetI(p, k, v); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_GetD3d11Resource(WlNgxParam *p, const char *k, void **v) { return P_GetD11(p, k, v); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_GetD3d12Resource(WlNgxParam *p, const char *k, void **v) { return P_GetD12(p, k, v); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_Parameter_GetVoidPointer(WlNgxParam *p, const char *k, void **v) { return P_GetVP(p, k, v); }
// ---- VULKAN NGX API (RDR2, DOOM Eternal, etc.) ----
static void vk_ngx_attach(VkInstance inst, VkPhysicalDevice phys, VkDevice dev, PFN_wlVkGetDeviceProcAddr gdpa) {
ensure_cs();
EnterCriticalSection(&g_cs);
if (dev && (!g_vk_seam.ready || g_vk_seam.dev != dev)) {
if (g_vk_seam.ready) wl_seam_destroy(&g_vk_seam);
wl_seam_init(&g_vk_seam, inst, phys, dev, gdpa);
}
LeaveCriticalSection(&g_cs);
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_Init(uint64_t appId, const wchar_t *path, VkInstance inst, VkPhysicalDevice phys, VkDevice dev, void *gipa, void *gdpa, void *info, uint32_t ver) {
(void)appId; (void)path; (void)gipa; (void)info; (void)ver;
vk_ngx_attach(inst, phys, dev, (PFN_wlVkGetDeviceProcAddr)gdpa);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_Init_Ext(uint64_t appId, const wchar_t *path, VkInstance inst, VkPhysicalDevice phys, VkDevice dev, uint32_t ver, void *info) {
(void)appId; (void)path; (void)ver; (void)info;
vk_ngx_attach(inst, phys, dev, NULL);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_Init_Ext2(uint64_t appId, const wchar_t *path, VkInstance inst, VkPhysicalDevice phys, VkDevice dev, void *gipa, void *gdpa, uint32_t ver, void *info) {
(void)appId; (void)path; (void)gipa; (void)ver; (void)info;
vk_ngx_attach(inst, phys, dev, (PFN_wlVkGetDeviceProcAddr)gdpa);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_Init_ProjectID(const char *proj, uint32_t eng, const char *engv, const wchar_t *path, VkInstance inst, VkPhysicalDevice phys, VkDevice dev, void *gipa, void *gdpa, uint32_t ver, void *info) {
(void)proj; (void)eng; (void)engv; (void)path; (void)gipa; (void)ver; (void)info;
vk_ngx_attach(inst, phys, dev, (PFN_wlVkGetDeviceProcAddr)gdpa);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_Init_with_ProjectID(const char *proj, uint32_t eng, const char *engv, const wchar_t *path, VkInstance inst, VkPhysicalDevice phys, VkDevice dev, void *gipa, void *gdpa, void *info, uint32_t ver) {
(void)proj; (void)eng; (void)engv; (void)path; (void)gipa; (void)info; (void)ver;
vk_ngx_attach(inst, phys, dev, (PFN_wlVkGetDeviceProcAddr)gdpa);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_Init_ProjectID_Ext(const char *proj, uint32_t eng, const char *engv, const wchar_t *path, VkInstance inst, VkPhysicalDevice phys, VkDevice dev, void *gipa, void *gdpa, uint32_t ver, void *info) {
(void)proj; (void)eng; (void)engv; (void)path; (void)gipa; (void)ver; (void)info;
vk_ngx_attach(inst, phys, dev, (PFN_wlVkGetDeviceProcAddr)gdpa);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_Shutdown(void) {
ensure_cs(); EnterCriticalSection(&g_cs);
wl_xess3_destroy(&g_vk_xess3);
wl_seam_destroy(&g_vk_seam);
LeaveCriticalSection(&g_cs);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_Shutdown1(VkDevice dev) {
(void)dev;
return NVSDK_NGX_VULKAN_Shutdown();
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_RequiredExtensions(uint32_t *instCnt, const char ***instExts, uint32_t *devCnt, const char ***devExts) {
// OptiScaler pattern: return 0 required extensions so the game never fails VkDevice creation
// if an intermediate Wine/wrapper layer filters NVX names; our Vulkan layer still advertises
// VK_NVX_binary_import / VK_NVX_image_view_handle for games that explicitly probe them.
if (instCnt) *instCnt = 0;
if (instExts) *instExts = NULL;
if (devCnt) *devCnt = 0;
if (devExts) *devExts = NULL;
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_GetFeatureInstanceExtensionRequirements(const void *info, uint32_t *outCnt, void **outExts) {
(void)info;
if (outCnt) *outCnt = 0;
if (outExts) *outExts = NULL;
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_GetFeatureDeviceExtensionRequirements(VkInstance inst, VkPhysicalDevice pd, const void *info, uint32_t *outCnt, void **outExts) {
(void)inst; (void)pd; (void)info;
if (outCnt) *outCnt = 0;
if (outExts) *outExts = NULL;
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_GetFeatureExtensionRequirements(const void *info, uint32_t *instCnt, void **instExts, uint32_t *devCnt, void **devExts) {
(void)info;
if (instCnt) *instCnt = 0;
if (instExts) *instExts = NULL;
if (devCnt) *devCnt = 0;
if (devExts) *devExts = NULL;
return NVSDK_NGX_Result_Success;
}
static NVSDK_NGX_Result fill_feature_requirements(const void *info, NVSDK_NGX_FeatureRequirement *outReq) {
if (!outReq) return NVSDK_NGX_Result_FAIL_InvalidParameter;
memset(outReq, 0, sizeof *outReq);
strcpy(outReq->MinOSVersion, "10.0.10240.16384");
uint32_t fid = 1u; /* Default SuperSampling */
if (info) fid = ((const NVSDK_NGX_FeatureDiscoveryInfoHead *)info)->FeatureID;
if (fid == 1u || fid == 3u) {
outReq->FeatureSupported = 0u; /* NVSDK_NGX_FeatureSupportResult_Supported */
outReq->MinHWArchitecture = 0u;
} else {
outReq->FeatureSupported = 4u; /* AdapterUnsupported for FG / RayReconstruction */
outReq->MinHWArchitecture = 0x0190u;
}
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_GetFeatureRequirements(VkInstance inst, VkPhysicalDevice pd, const void *info, NVSDK_NGX_FeatureRequirement *outReq) {
(void)inst; (void)pd;
return fill_feature_requirements(info, outReq);
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_GetCapabilityParameters(WlNgxParam **outP) {
ensure_cs(); EnterCriticalSection(&g_cs);
if (!g_cap_param) g_cap_param = alloc_param(0, 1);
if (outP) *outP = g_cap_param;
LeaveCriticalSection(&g_cs);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_GetParameters(WlNgxParam **outP) { return NVSDK_NGX_VULKAN_GetCapabilityParameters(outP); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_AllocateParameters(WlNgxParam **outP) {
if (outP) *outP = alloc_param(1, 0);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_DestroyParameters(WlNgxParam *p) {
if (p && p->owned) HeapFree(GetProcessHeap(), 0, p);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_PopulateParameters_Impl(WlNgxParam *p) { populate_cap_params(p); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_GetScratchBufferSize(uint32_t feat, WlNgxParam *p, size_t *sz) { (void)feat; (void)p; if (sz) *sz = 1024 * 1024; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_SetParameter(const char *k, void *v) { ensure_cs(); if (!g_cap_param) g_cap_param = alloc_param(0, 1); P_SetVP(g_cap_param, k, v); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_GetParameter(const char *k, void **v) { ensure_cs(); if (!g_cap_param) g_cap_param = alloc_param(0, 1); return P_GetVP(g_cap_param, k, v); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_CreateFeature(VkCommandBuffer cb, uint32_t feat, WlNgxParam *p, NVSDK_NGX_Handle **outH) {
(void)cb; (void)feat;
ensure_cs(); EnterCriticalSection(&g_cs);
create_feat(0, p, outH);
LeaveCriticalSection(&g_cs);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_CreateFeature1(VkDevice dev, VkCommandBuffer cb, uint32_t feat, WlNgxParam *p, NVSDK_NGX_Handle **outH) {
vk_ngx_attach(NULL, NULL, dev, NULL);
return NVSDK_NGX_VULKAN_CreateFeature(cb, feat, p, outH);
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_ReleaseFeature(NVSDK_NGX_Handle *h) {
ensure_cs(); EnterCriticalSection(&g_cs);
WlNgxFeature *f = find_feat(h);
if (f) memset(f, 0, sizeof *f);
LeaveCriticalSection(&g_cs);
if (h) HeapFree(GetProcessHeap(), 0, h);
return NVSDK_NGX_Result_Success;
}
static void extract_ngx_vk_res(WlFsr4ImageRef *dst, wl_xess_vk_img_t *ximg, WlNgxParam *p, const char *k1, const char *k2, int is_depth) {
memset(dst, 0, sizeof *dst);
if (ximg) memset(ximg, 0, sizeof *ximg);
void *rp = NULL;
if (!kv_get_p(p, k1, &rp) && k2) kv_get_p(p, k2, &rp);
if (!rp) return;
const NVSDK_NGX_Resource_VK *r = (const NVSDK_NGX_Resource_VK *)rp;
if (r->Type == 0) {
dst->vk_image = r->Resource.ImageViewInfo.Image;
dst->vk_view = r->Resource.ImageViewInfo.ImageView;
dst->vk_format = r->Resource.ImageViewInfo.Format;
dst->width = r->Resource.ImageViewInfo.Width;
dst->height = r->Resource.ImageViewInfo.Height;
dst->vk_layout = r->ReadWrite ? 1u : (is_depth ? 4u : 5u); /* GENERAL or SHADER_READ_ONLY */
dst->aspect = is_depth ? 2u : 1u;
if (ximg) {
ximg->imageView = r->Resource.ImageViewInfo.ImageView;
ximg->image = r->Resource.ImageViewInfo.Image;
ximg->subresourceRange.aspectMask = r->Resource.ImageViewInfo.SubresourceRange.aspectMask ? r->Resource.ImageViewInfo.SubresourceRange.aspectMask : (is_depth ? 2u : 1u);
ximg->subresourceRange.baseMipLevel = r->Resource.ImageViewInfo.SubresourceRange.baseMipLevel;
ximg->subresourceRange.levelCount = r->Resource.ImageViewInfo.SubresourceRange.levelCount ? r->Resource.ImageViewInfo.SubresourceRange.levelCount : 1u;
ximg->subresourceRange.baseArrayLayer = r->Resource.ImageViewInfo.SubresourceRange.baseArrayLayer;
ximg->subresourceRange.layerCount = r->Resource.ImageViewInfo.SubresourceRange.layerCount ? r->Resource.ImageViewInfo.SubresourceRange.layerCount : 1u;
ximg->format = r->Resource.ImageViewInfo.Format;
ximg->width = r->Resource.ImageViewInfo.Width;
ximg->height = r->Resource.ImageViewInfo.Height;
}
}
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_EvaluateFeature(VkCommandBuffer cb, const NVSDK_NGX_Handle *h, WlNgxParam *p, void *cbk) {
(void)cbk;
if (!cb || !p) return NVSDK_NGX_Result_FAIL_InvalidParameter;
ensure_cs();
EnterCriticalSection(&g_cs);
WlNgxFeature *feat = find_feat(h);
int ready = g_vk_seam.ready;
int do_reset = 0;
uint32_t feat_cf = 0, feat_pq = 0;
int feat_has_pq = 0;
uint32_t feat_rw = 0, feat_rh = 0, feat_ow = 0, feat_oh = 0;
if (feat) {
if (feat->needs_reset) { do_reset = 1; feat->needs_reset = 0; }
feat_cf = feat->create_flags;
feat_pq = feat->perf_quality;
feat_has_pq = feat->has_perf_quality;
feat_rw = feat->rw; feat_rh = feat->rh; feat_ow = feat->ow; feat_oh = feat->oh;
}
LeaveCriticalSection(&g_cs);
if (!ready) return NVSDK_NGX_Result_Fail;
WlFsr4FrameDesc f;
memset(&f, 0, sizeof f);
wl_xess_vk_img_t x_col, x_dep, x_mv, x_out;
f.api_source = WLFSR4_API_NGX_VK;
extract_ngx_vk_res(&f.color, &x_col, p, "Color", "#\x1e", 0);
if (!f.color.vk_image) extract_ngx_vk_res(&f.color, &x_col, p, "__ColorInput", NULL, 0);
extract_ngx_vk_res(&f.depth, &x_dep, p, "Depth", "#\x3d", 1);
extract_ngx_vk_res(&f.motion, &x_mv, p, "MotionVectors", "#\x27", 0);
if (!f.motion.vk_image) extract_ngx_vk_res(&f.motion, &x_mv, p, "__MVecInput", NULL, 0);
extract_ngx_vk_res(&f.output, &x_out, p, "Output", "#\x22", 0);
if (!f.output.vk_image) extract_ngx_vk_res(&f.output, &x_out, p, "__Output", NULL, 0);
uint64_t u = 0;
f.render_w = kv_get_u(p, "DLSS.Render.Subrect.Dimensions.Width", &u) ? (uint32_t)u
: (kv_get_u(p, "#\x2a", &u) ? (uint32_t)u : (f.color.width ? f.color.width : feat_rw));
f.render_h = kv_get_u(p, "DLSS.Render.Subrect.Dimensions.Height", &u) ? (uint32_t)u
: (kv_get_u(p, "#\x2b", &u) ? (uint32_t)u : (f.color.height ? f.color.height : feat_rh));
f.output_w = f.output.width ? f.output.width : (feat_ow ? feat_ow : 1920u);
f.output_h = f.output.height ? f.output.height : (feat_oh ? feat_oh : 1080u);
kv_get_f(p, "Jitter.Offset.X", &f.jitter_x);
kv_get_f(p, "Jitter.Offset.Y", &f.jitter_y);
f.mv_scale_x = 1.0f; f.mv_scale_y = 1.0f;
if (!kv_get_f(p, "MV.Scale.X", &f.mv_scale_x)) kv_get_f(p, "#\x2c", &f.mv_scale_x);
if (!kv_get_f(p, "MV.Scale.Y", &f.mv_scale_y)) kv_get_f(p, "#\x2d", &f.mv_scale_y);
f.pre_exposure = 1.0f;
kv_get_f(p, "DLSS.Pre.Exposure", &f.pre_exposure);
if (!kv_get_f(p, "Sharpness", &f.sharpness)) kv_get_f(p, "#\x14", &f.sharpness);
if (f.sharpness > 0.01f) f.flags |= WLFSR4_FLAG_SHARPEN;
if ((kv_get_u(p, "Reset", &u) && u) || (kv_get_u(p, "#\x25", &u) && u) || do_reset) f.flags |= WLFSR4_FLAG_RESET;
apply_ngx_create_flags(&f, feat_cf);
uint32_t qm = WLFSR4_QUALITY_AUTO;
if (kv_get_u(p, "PerfQualityValue", &u)) {
g_last_perf_quality = (uint32_t)u;
qm = ngx_pq_to_wl_quality((uint32_t)u);
} else if (feat_has_pq) {
qm = ngx_pq_to_wl_quality(feat_pq);
} else if (g_last_perf_quality != 0xFFFFFFFFu) {
qm = ngx_pq_to_wl_quality(g_last_perf_quality);
} else {
qm = infer_quality_from_res(f.render_w, f.output_w);
}
f.quality_mode = qm;
if (qm == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
int live_en = 1;
int live_backend = wl_seam_live_backend(&g_vk_seam, &live_en);
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU) {
if (wl_xess3_eval_vk(&g_vk_xess3, &g_vk_seam, cb, &f, &x_col, &x_dep, &x_mv, &x_out)) {
return NVSDK_NGX_Result_Success;
}
wl_xess3_tag_fallback(&g_vk_xess3, &f);
} else {
wl_xess3_on_inactive(&g_vk_xess3);
}
int ok = wl_seam_dispatch_or_blit(&g_vk_seam, cb, &f);
return ok ? NVSDK_NGX_Result_Success : NVSDK_NGX_Result_Fail;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_VULKAN_EvaluateFeature_C(VkCommandBuffer cb, const NVSDK_NGX_Handle *h, WlNgxParam *p, void *cbk) {
return NVSDK_NGX_VULKAN_EvaluateFeature(cb, h, p, cbk);
}
// ---- D3D12 NGX API (via vkd3d-proton ID3D12DXVKInteropDevice1 -> same Hexagon NPU Vulkan layer!) ----
static void dx12_ngx_attach(void *d3d12_dev) {
ensure_cs();
EnterCriticalSection(&g_cs);
if (d3d12_dev) g_d3d12_dev = d3d12_dev;
if (!g_dx12_seam.ready && d3d12_dev) {
if (!g_dx12_interop) g_dx12_interop = wl_query_vkd3d_interop(d3d12_dev);
if (g_dx12_interop) {
void *vk_inst = NULL, *vk_phys = NULL, *vk_dev = NULL;
if (g_dx12_interop->lpVtbl->GetVulkanHandles(g_dx12_interop, &vk_inst, &vk_phys, &vk_dev) == S_OK && vk_dev) {
wl_seam_init(&g_dx12_seam, vk_inst, vk_phys, vk_dev, NULL);
}
}
}
LeaveCriticalSection(&g_cs);
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_Init(uint64_t appId, const wchar_t *path, void *dev, void *info, uint32_t ver) {
(void)appId; (void)path; (void)info; (void)ver;
dx12_ngx_attach(dev);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_Init_Ext(uint64_t appId, const wchar_t *path, void *dev, uint32_t ver, void *info) {
(void)appId; (void)path; (void)ver; (void)info;
dx12_ngx_attach(dev);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_Init_ProjectID(const char *proj, uint32_t eng, const char *engv, const wchar_t *path, void *dev, void *info, uint32_t ver) {
(void)proj; (void)eng; (void)engv; (void)path; (void)info; (void)ver;
dx12_ngx_attach(dev);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_Init_with_ProjectID(const char *proj, uint32_t eng, const char *engv, const wchar_t *path, void *dev, void *info, uint32_t ver) {
(void)proj; (void)eng; (void)engv; (void)path; (void)info; (void)ver;
dx12_ngx_attach(dev);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_Shutdown(void) {
ensure_cs(); EnterCriticalSection(&g_cs);
wl_xess3_destroy(&g_dx12_xess3);
wl_seam_destroy(&g_dx12_seam);
if (g_dx12_interop) { g_dx12_interop->lpVtbl->Release(g_dx12_interop); g_dx12_interop = NULL; }
g_d3d12_dev = NULL;
LeaveCriticalSection(&g_cs);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_Shutdown1(void *dev) { (void)dev; return NVSDK_NGX_D3D12_Shutdown(); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_GetFeatureRequirements(void *adapter, const void *info, NVSDK_NGX_FeatureRequirement *outReq) {
(void)adapter;
return fill_feature_requirements(info, outReq);
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_GetCapabilityParameters(WlNgxParam **outP) { return NVSDK_NGX_VULKAN_GetCapabilityParameters(outP); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_GetParameters(WlNgxParam **outP) { return NVSDK_NGX_VULKAN_GetCapabilityParameters(outP); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_AllocateParameters(WlNgxParam **outP) { return NVSDK_NGX_VULKAN_AllocateParameters(outP); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_DestroyParameters(WlNgxParam *p) { return NVSDK_NGX_VULKAN_DestroyParameters(p); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_PopulateParameters_Impl(WlNgxParam *p) { populate_cap_params(p); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_GetScratchBufferSize(uint32_t feat, WlNgxParam *p, size_t *sz) { (void)feat; (void)p; if (sz) *sz = 1024 * 1024; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_CreateFeature(void *cmdList, uint32_t feat, WlNgxParam *p, NVSDK_NGX_Handle **outH) {
(void)cmdList; (void)feat;
ensure_cs(); EnterCriticalSection(&g_cs);
create_feat(1, p, outH);
LeaveCriticalSection(&g_cs);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_ReleaseFeature(NVSDK_NGX_Handle *h) { return NVSDK_NGX_VULKAN_ReleaseFeature(h); }
static void *extract_ngx_dx12_res(WlID3D12DXVKInteropDevice1 *interop, WlFsr4ImageRef *dst, WlNgxParam *p, const char *k1, const char *k2, int is_depth) {
memset(dst, 0, sizeof *dst);
void *res = NULL;
if (!kv_get_p(p, k1, &res) && k2) kv_get_p(p, k2, &res);
if (!res || !interop) return res;
UINT64 vk_img = 0, off = 0;
UINT32 vk_fmt = 0;
if (interop->lpVtbl->GetVulkanResourceInfo1(interop, res, &vk_img, &off, &vk_fmt) == S_OK && vk_img) {
dst->vk_image = vk_img;
dst->vk_format = vk_fmt;
dst->vk_layout = is_depth ? 4u : 1u; /* DEPTH_STENCIL_READ_ONLY or GENERAL */
dst->aspect = is_depth ? 2u : 1u;
}
return res;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D12_EvaluateFeature(void *cmdList, const NVSDK_NGX_Handle *h, WlNgxParam *p, void *cbk) {
(void)cbk;
if (!cmdList || !p) return NVSDK_NGX_Result_FAIL_InvalidParameter;
ensure_cs();
EnterCriticalSection(&g_cs);
WlNgxFeature *feat = find_feat(h);
WlID3D12DXVKInteropDevice1 *interop = g_dx12_interop;
void *d3d12_dev = g_d3d12_dev;
int ready = g_dx12_seam.ready;
int do_reset = 0;
uint32_t feat_cf = 0, feat_pq = 0;
int feat_has_pq = 0;
uint32_t feat_rw = 0, feat_rh = 0, feat_ow = 0, feat_oh = 0;
if (feat) {
if (feat->needs_reset) { do_reset = 1; feat->needs_reset = 0; }
feat_cf = feat->create_flags;
feat_pq = feat->perf_quality;
feat_has_pq = feat->has_perf_quality;
feat_rw = feat->rw; feat_rh = feat->rh; feat_ow = feat->ow; feat_oh = feat->oh;
}
LeaveCriticalSection(&g_cs);
if (!ready || !interop) return NVSDK_NGX_Result_Fail;
WlFsr4FrameDesc f;
memset(&f, 0, sizeof f);
f.api_source = WLFSR4_API_NGX_DX12;
void *res_col = extract_ngx_dx12_res(interop, &f.color, p, "Color", "#\x1e", 0);
if (!f.color.vk_image) res_col = extract_ngx_dx12_res(interop, &f.color, p, "__ColorInput", NULL, 0);
void *res_dep = extract_ngx_dx12_res(interop, &f.depth, p, "Depth", "#\x3d", 1);
void *res_mv = extract_ngx_dx12_res(interop, &f.motion, p, "MotionVectors", "#\x27", 0);
if (!f.motion.vk_image) res_mv = extract_ngx_dx12_res(interop, &f.motion, p, "__MVecInput", NULL, 0);
void *res_out = extract_ngx_dx12_res(interop, &f.output, p, "Output", "#\x22", 0);
if (!f.output.vk_image) res_out = extract_ngx_dx12_res(interop, &f.output, p, "__Output", NULL, 0);
uint64_t u = 0;
f.render_w = kv_get_u(p, "DLSS.Render.Subrect.Dimensions.Width", &u) ? (uint32_t)u
: (kv_get_u(p, "#\x2a", &u) ? (uint32_t)u : (feat_rw ? feat_rw : 960u));
f.render_h = kv_get_u(p, "DLSS.Render.Subrect.Dimensions.Height", &u) ? (uint32_t)u
: (kv_get_u(p, "#\x2b", &u) ? (uint32_t)u : (feat_rh ? feat_rh : 540u));
f.output_w = feat_ow ? feat_ow : 1920u;
f.output_h = feat_oh ? feat_oh : 1080u;
kv_get_f(p, "Jitter.Offset.X", &f.jitter_x);
kv_get_f(p, "Jitter.Offset.Y", &f.jitter_y);
f.mv_scale_x = 1.0f; f.mv_scale_y = 1.0f;
if (!kv_get_f(p, "MV.Scale.X", &f.mv_scale_x)) kv_get_f(p, "#\x2c", &f.mv_scale_x);
if (!kv_get_f(p, "MV.Scale.Y", &f.mv_scale_y)) kv_get_f(p, "#\x2d", &f.mv_scale_y);
f.pre_exposure = 1.0f;
kv_get_f(p, "DLSS.Pre.Exposure", &f.pre_exposure);
if (!kv_get_f(p, "Sharpness", &f.sharpness)) kv_get_f(p, "#\x14", &f.sharpness);
if (f.sharpness > 0.01f) f.flags |= WLFSR4_FLAG_SHARPEN;
if ((kv_get_u(p, "Reset", &u) && u) || (kv_get_u(p, "#\x25", &u) && u) || do_reset) f.flags |= WLFSR4_FLAG_RESET;
apply_ngx_create_flags(&f, feat_cf);
uint32_t qm = WLFSR4_QUALITY_AUTO;
if (kv_get_u(p, "PerfQualityValue", &u)) {
g_last_perf_quality = (uint32_t)u;
qm = ngx_pq_to_wl_quality((uint32_t)u);
} else if (feat_has_pq) {
qm = ngx_pq_to_wl_quality(feat_pq);
} else if (g_last_perf_quality != 0xFFFFFFFFu) {
qm = ngx_pq_to_wl_quality(g_last_perf_quality);
} else {
qm = infer_quality_from_res(f.render_w, f.output_w);
}
f.quality_mode = qm;
if (qm == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
int live_en = 1;
int live_backend = wl_seam_live_backend(&g_dx12_seam, &live_en);
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU && d3d12_dev) {
if (wl_xess3_eval_d3d12(&g_dx12_xess3, &g_dx12_seam, interop, d3d12_dev, cmdList,
&f, res_col, res_dep, res_mv, res_out)) {
return NVSDK_NGX_Result_Success;
}
wl_xess3_tag_fallback(&g_dx12_xess3, &f);
} else {
wl_xess3_on_inactive(&g_dx12_xess3);
}
void *vk_cb = NULL;
int ok = 0;
if (interop->lpVtbl->BeginVkCommandBufferInterop(interop, cmdList, &vk_cb) == S_OK && vk_cb) {
ok = wl_seam_dispatch_or_blit(&g_dx12_seam, (VkCommandBuffer)vk_cb, &f);
interop->lpVtbl->EndVkCommandBufferInterop(interop, cmdList);
}
return ok ? NVSDK_NGX_Result_Success : NVSDK_NGX_Result_Fail;
}
// ---- D3D11 & CUDA stubs (prevent unresolved symbol crashes on multi-API games) ----
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_Init(uint64_t a, const wchar_t *b, void *c, void *d, uint32_t e) { (void)a;(void)b;(void)c;(void)d;(void)e; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_Init_Ext(uint64_t a, const wchar_t *b, void *c, uint32_t d, void *e) { (void)a;(void)b;(void)c;(void)d;(void)e; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_Init_ProjectID(const char *a, uint32_t b, const char *c, const wchar_t *d, void *e, void *f, uint32_t g) { (void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_Init_with_ProjectID(const char *a, uint32_t b, const char *c, const wchar_t *d, void *e, void *f, uint32_t g) { (void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_Shutdown(void) { return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_Shutdown1(void *a) { (void)a; return NVSDK_NGX_Result_Success; }
// DroidDeck: D3D11 has no path to the Vulkan layer, so it reports DLSS unavailable and games hide it.
static void populate_d3d11_cap_params(WlNgxParam *p) {
if (!p) return;
populate_cap_params(p);
P_SetI(p, "SuperSampling.Available", 0);
P_SetUI(p, "SuperSampling.FeatureInitResult", NVSDK_NGX_Result_FAIL_FeatureNotSupported);
P_SetI(p, "DLSS.Available", 0);
P_SetI(p, "#\x01", 0); /* SuperSampling_Available */
}
static WlNgxParam *g_d3d11_cap_param = NULL;
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_GetFeatureRequirements(void *a, const void *b, NVSDK_NGX_FeatureRequirement *c) {
(void)a; (void)b;
if (!c) return NVSDK_NGX_Result_FAIL_InvalidParameter;
memset(c, 0, sizeof *c);
strcpy(c->MinOSVersion, "10.0.10240.16384");
c->FeatureSupported = 4u; /* NVSDK_NGX_FeatureSupportResult_AdapterUnsupported */
c->MinHWArchitecture = 0x0190u;
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_GetCapabilityParameters(WlNgxParam **p) {
ensure_cs(); EnterCriticalSection(&g_cs);
if (!g_d3d11_cap_param) {
g_d3d11_cap_param = alloc_param(0, 0);
populate_d3d11_cap_params(g_d3d11_cap_param);
}
if (p) *p = g_d3d11_cap_param;
LeaveCriticalSection(&g_cs);
return NVSDK_NGX_Result_Success;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_GetParameters(WlNgxParam **p) { return NVSDK_NGX_D3D11_GetCapabilityParameters(p); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_AllocateParameters(WlNgxParam **p) { return NVSDK_NGX_VULKAN_AllocateParameters(p); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_DestroyParameters(WlNgxParam *p) { return NVSDK_NGX_VULKAN_DestroyParameters(p); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_PopulateParameters_Impl(WlNgxParam *p) { populate_d3d11_cap_params(p); return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_GetScratchBufferSize(uint32_t a, WlNgxParam *b, size_t *c) { return NVSDK_NGX_VULKAN_GetScratchBufferSize(a, b, c); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_CreateFeature(void *a, uint32_t b, WlNgxParam *c, NVSDK_NGX_Handle **d) {
(void)a; (void)b; (void)c;
if (d) *d = NULL;
return NVSDK_NGX_Result_FAIL_FeatureNotSupported;
}
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_ReleaseFeature(NVSDK_NGX_Handle *h) { return NVSDK_NGX_VULKAN_ReleaseFeature(h); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_EvaluateFeature(void *a, const NVSDK_NGX_Handle *b, WlNgxParam *c, void *d) { (void)a;(void)b;(void)c;(void)d; return NVSDK_NGX_Result_FAIL_FeatureNotSupported; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_D3D11_EvaluateFeature_C(void *a, const NVSDK_NGX_Handle *b, WlNgxParam *c, void *d) { (void)a;(void)b;(void)c;(void)d; return NVSDK_NGX_Result_FAIL_FeatureNotSupported; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_Init(uint64_t a, const wchar_t *b, void *c, uint32_t d) { (void)a;(void)b;(void)c;(void)d; return NVSDK_NGX_Result_FAIL_FeatureNotSupported; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_Init_with_ProjectID(const char *a, uint32_t b, const char *c, const wchar_t *d, void *e, uint32_t f) { (void)a;(void)b;(void)c;(void)d;(void)e;(void)f; return NVSDK_NGX_Result_FAIL_FeatureNotSupported; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_Shutdown(void) { return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_GetCapabilityParameters(WlNgxParam **p) { return NVSDK_NGX_VULKAN_GetCapabilityParameters(p); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_GetParameters(WlNgxParam **p) { return NVSDK_NGX_VULKAN_GetCapabilityParameters(p); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_AllocateParameters(WlNgxParam **p) { return NVSDK_NGX_VULKAN_AllocateParameters(p); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_DestroyParameters(WlNgxParam *p) { return NVSDK_NGX_VULKAN_DestroyParameters(p); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_GetScratchBufferSize(uint32_t a, WlNgxParam *b, size_t *c) { return NVSDK_NGX_VULKAN_GetScratchBufferSize(a, b, c); }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_CreateFeature(uint32_t a, WlNgxParam *b, NVSDK_NGX_Handle **c) { (void)a;(void)b;(void)c; return NVSDK_NGX_Result_FAIL_FeatureNotSupported; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_ReleaseFeature(NVSDK_NGX_Handle *h) { (void)h; return NVSDK_NGX_Result_Success; }
__declspec(dllexport) NVSDK_NGX_Result NVSDK_NGX_CUDA_EvaluateFeature(const NVSDK_NGX_Handle *a, WlNgxParam *b, void *c) { (void)a;(void)b;(void)c; return NVSDK_NGX_Result_FAIL_FeatureNotSupported; }
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
(void)hinst; (void)reserved;
if (reason == DLL_PROCESS_ATTACH) {
DisableThreadLibraryCalls(hinst);
ensure_cs();
}
return TRUE;
}
+585
View File
@@ -0,0 +1,585 @@
// DroidDeck: modified from michaelisomer-cyber/Winlator-NeuralScale a0ab6b0f (see README.md).
// ARM64EC / FEXCore / Box64 / Wine-safe IAT + GetProcAddress NGX hook engine.
// Installed inside nvapi64.dll so that when nvsdk_ngx.lib (inside Cyberpunk 2077's
// sl.common.dll, RDR2.exe, etc.) tries to locate, signature-verify, and load
// nvngx.dll / _nvngx.dll, it cleanly passes WinVerifyTrust + CryptQueryObject
// and loads our C:\windows\system32\_nvngx.dll bridge without touching game folders
// or patching executable machine code (100% safe on ARM64EC thunks).
#pragma once
#include <windows.h>
#include <tlhelp32.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <wchar.h>
#include <stdio.h>
#include "dd_env.h"
#ifndef FILE_ATTRIBUTE_ARCHIVE
#define FILE_ATTRIBUTE_ARCHIVE 0x20
#endif
// Minimal WinTrust & Crypt32 definitions (avoid linking wintrust.lib / crypt32.lib)
typedef struct WlWintrustFileInfo {
DWORD cbStruct;
LPCWSTR pcwszFilePath;
HANDLE hFile;
GUID *pgKnownSubject;
} WlWintrustFileInfo;
typedef struct WlWintrustData {
DWORD cbStruct;
LPVOID pPolicyCallbackData;
LPVOID pSIPClientData;
DWORD dwUIChoice;
DWORD fdwRevocationChecks;
DWORD dwUnionChoice; /* 1 = WTD_CHOICE_FILE */
union {
WlWintrustFileInfo *pFile;
void *pOther;
} u;
DWORD dwStateAction; /* 1 = VERIFY, 2 = CLOSE */
HANDLE hWVTStateData;
WCHAR *pwszURLReference;
DWORD dwProvFlags;
DWORD dwUIContext;
void *pSignatureSettings;
} WlWintrustData;
typedef HMODULE (WINAPI *PFN_LoadLibraryW)(LPCWSTR);
typedef HMODULE (WINAPI *PFN_LoadLibraryA)(LPCSTR);
typedef HMODULE (WINAPI *PFN_LoadLibraryExW)(LPCWSTR, HANDLE, DWORD);
typedef HMODULE (WINAPI *PFN_LoadLibraryExA)(LPCSTR, HANDLE, DWORD);
typedef FARPROC (WINAPI *PFN_GetProcAddress)(HMODULE, LPCSTR);
typedef DWORD (WINAPI *PFN_GetFileAttributesW)(LPCWSTR);
typedef BOOL (WINAPI *PFN_GetFileAttributesExW)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
typedef HANDLE (WINAPI *PFN_CreateFileW)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
typedef LONG (WINAPI *PFN_WinVerifyTrust)(HWND, GUID *, LPVOID);
typedef BOOL (WINAPI *PFN_CryptQueryObject)(DWORD, const void *, DWORD, DWORD, DWORD, DWORD *, DWORD *, DWORD *, void *, void *, const void **);
typedef LSTATUS (WINAPI *PFN_RegOpenKeyExW)(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY);
typedef LSTATUS (WINAPI *PFN_RegEnumValueW)(HKEY, DWORD, LPWSTR, LPDWORD, LPDWORD, LPDWORD, LPBYTE, LPDWORD);
typedef LSTATUS (WINAPI *PFN_RegQueryValueExW)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD);
typedef LSTATUS (WINAPI *PFN_RegCloseKey)(HKEY);
static HMODULE g_wl_self_mod = NULL;
static HMODULE g_wl_our_nvngx = NULL;
static DWORD g_wl_tls_reent = TLS_OUT_OF_INDEXES;
static volatile LONG g_wl_hooks_installed = 0;
static CRITICAL_SECTION g_wl_hook_cs;
static int g_wl_hook_cs_ready = 0;
static WCHAR g_wl_signed_nv_dll[MAX_PATH] = {0};
static const HKEY k_wl_sig_hkey = (HKEY)(uintptr_t)0xFFFFFFFF13372137ULL;
static PFN_LoadLibraryW o_LoadLibraryW = NULL;
static PFN_LoadLibraryA o_LoadLibraryA = NULL;
static PFN_LoadLibraryExW o_LoadLibraryExW = NULL;
static PFN_LoadLibraryExA o_LoadLibraryExA = NULL;
static PFN_GetProcAddress o_GetProcAddress = NULL;
static PFN_GetFileAttributesW o_GetFileAttributesW = NULL;
static PFN_GetFileAttributesExW o_GetFileAttributesExW = NULL;
static PFN_CreateFileW o_CreateFileW = NULL;
static PFN_WinVerifyTrust o_WinVerifyTrust = NULL;
static PFN_CryptQueryObject o_CryptQueryObject = NULL;
static PFN_RegOpenKeyExW o_RegOpenKeyExW = NULL;
static PFN_RegEnumValueW o_RegEnumValueW = NULL;
static PFN_RegQueryValueExW o_RegQueryValueExW = NULL;
static PFN_RegCloseKey o_RegCloseKey = NULL;
static int g_wl_log_on = -1;
static void wl_hook_log(const char *msg) {
if (g_wl_log_on < 0) g_wl_log_on = dd_env_is_on("DROIDDECK_UPSCALE_LOG");
if (!msg || !g_wl_log_on) return;
HANDLE hf = CreateFileA("C:\\windows\\temp\\wl_fsr4_bridge.log",
FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hf != INVALID_HANDLE_VALUE) {
DWORD wr = 0;
WriteFile(hf, msg, (DWORD)strlen(msg), &wr, NULL);
WriteFile(hf, "\r\n", 2, &wr, NULL);
CloseHandle(hf);
}
}
static int wl_in_hook(void) {
return (g_wl_tls_reent != TLS_OUT_OF_INDEXES) && (TlsGetValue(g_wl_tls_reent) != NULL);
}
static void wl_enter_hook(void) {
if (g_wl_tls_reent != TLS_OUT_OF_INDEXES) TlsSetValue(g_wl_tls_reent, (LPVOID)1);
}
static void wl_leave_hook(void) {
if (g_wl_tls_reent != TLS_OUT_OF_INDEXES) TlsSetValue(g_wl_tls_reent, NULL);
}
static const WCHAR *wl_basename_w(const WCHAR *path) {
if (!path) return L"";
const WCHAR *last = path;
for (const WCHAR *p = path; *p; p++) {
if (*p == L'\\' || *p == L'/') last = p + 1;
}
return last;
}
static const char *wl_basename_a(const char *path) {
if (!path) return "";
const char *last = path;
for (const char *p = path; *p; p++) {
if (*p == '\\' || *p == '/') last = p + 1;
}
return last;
}
// Matches nvngx.dll or _nvngx.dll (and NOT nvngx_dlss.dll / nvngx_dlssg.dll / nvngx_dlssd.dll)
static int wl_is_nvngx_core_w(const WCHAR *path) {
const WCHAR *base = wl_basename_w(path);
return _wcsicmp(base, L"nvngx.dll") == 0 ||
_wcsicmp(base, L"_nvngx.dll") == 0 ||
_wcsicmp(base, L"nvngx") == 0 ||
_wcsicmp(base, L"_nvngx") == 0;
}
static int wl_is_nvngx_core_a(const char *path) {
const char *base = wl_basename_a(path);
return _stricmp(base, "nvngx.dll") == 0 ||
_stricmp(base, "_nvngx.dll") == 0 ||
_stricmp(base, "nvngx") == 0 ||
_stricmp(base, "_nvngx") == 0;
}
static int wl_is_sig_target_w(const WCHAR *path) {
if (!path) return 0;
const WCHAR *base = wl_basename_w(path);
if (wl_is_nvngx_core_w(base)) return 1;
if (_wcsnicmp(base, L"amd_fidelityfx", 14) == 0) return 1;
return 0;
}
static HMODULE wl_load_our_nvngx(void) {
if (g_wl_our_nvngx) return g_wl_our_nvngx;
if (!o_LoadLibraryW) return NULL;
wl_enter_hook();
HMODULE h = o_LoadLibraryW(L"C:\\windows\\system32\\_nvngx.dll");
if (!h) h = o_LoadLibraryW(L"C:\\windows\\system32\\nvngx.dll");
wl_leave_hook();
if (h) g_wl_our_nvngx = h;
return h;
}
static void wl_find_signed_nv_dll(void) {
if (g_wl_signed_nv_dll[0]) return;
WCHAR exe_dir[MAX_PATH] = {0};
DWORD n = GetModuleFileNameW(NULL, exe_dir, MAX_PATH);
if (n == 0 || n >= MAX_PATH) return;
for (int i = (int)n - 1; i >= 0; i--) {
if (exe_dir[i] == L'\\' || exe_dir[i] == L'/') {
exe_dir[i + 1] = L'\0';
break;
}
}
static const WCHAR *const k_candidates[] = {
L"nvngx_dlss.dll",
L"sl.interposer.dll",
L"sl.common.dll",
L"sl.dlss.dll",
L"nvngx_dlssg.dll",
};
PFN_GetFileAttributesW fnAttr = o_GetFileAttributesW ? o_GetFileAttributesW : GetFileAttributesW;
for (size_t i = 0; i < sizeof(k_candidates) / sizeof(k_candidates[0]); i++) {
WCHAR cand[MAX_PATH] = {0};
_snwprintf(cand, MAX_PATH - 1, L"%ls%ls", exe_dir, k_candidates[i]);
DWORD attr = fnAttr(cand);
if (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY)) {
wcsncpy(g_wl_signed_nv_dll, cand, MAX_PATH - 1);
char logbuf[320];
snprintf(logbuf, sizeof logbuf, "[nvapi] Found genuine NVIDIA-signed cert donor: %ls", k_candidates[i]);
wl_hook_log(logbuf);
return;
}
}
}
static void wl_patch_module_iat(HMODULE mod);
// ---- Hook implementations ----
static HMODULE WINAPI hk_LoadLibraryW(LPCWSTR lpName) {
if (!wl_in_hook() && lpName && wl_is_nvngx_core_w(lpName)) {
wl_hook_log("[nvapi] hk_LoadLibraryW intercepted nvngx -> _nvngx.dll");
return wl_load_our_nvngx();
}
HMODULE h = o_LoadLibraryW ? o_LoadLibraryW(lpName) : NULL;
if (h && !wl_in_hook()) {
wl_enter_hook();
wl_patch_module_iat(h);
wl_leave_hook();
}
return h;
}
static HMODULE WINAPI hk_LoadLibraryA(LPCSTR lpName) {
if (!wl_in_hook() && lpName && wl_is_nvngx_core_a(lpName)) {
wl_hook_log("[nvapi] hk_LoadLibraryA intercepted nvngx -> _nvngx.dll");
return wl_load_our_nvngx();
}
HMODULE h = o_LoadLibraryA ? o_LoadLibraryA(lpName) : NULL;
if (h && !wl_in_hook()) {
wl_enter_hook();
wl_patch_module_iat(h);
wl_leave_hook();
}
return h;
}
static HMODULE WINAPI hk_LoadLibraryExW(LPCWSTR lpName, HANDLE hFile, DWORD dwFlags) {
if (!wl_in_hook() && lpName && wl_is_nvngx_core_w(lpName) &&
!(dwFlags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))) {
wl_hook_log("[nvapi] hk_LoadLibraryExW intercepted nvngx -> _nvngx.dll");
return wl_load_our_nvngx();
}
HMODULE h = o_LoadLibraryExW ? o_LoadLibraryExW(lpName, hFile, dwFlags) : NULL;
if (h && !wl_in_hook() &&
!(dwFlags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))) {
wl_enter_hook();
wl_patch_module_iat(h);
wl_leave_hook();
}
return h;
}
static HMODULE WINAPI hk_LoadLibraryExA(LPCSTR lpName, HANDLE hFile, DWORD dwFlags) {
if (!wl_in_hook() && lpName && wl_is_nvngx_core_a(lpName) &&
!(dwFlags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))) {
wl_hook_log("[nvapi] hk_LoadLibraryExA intercepted nvngx -> _nvngx.dll");
return wl_load_our_nvngx();
}
HMODULE h = o_LoadLibraryExA ? o_LoadLibraryExA(lpName, hFile, dwFlags) : NULL;
if (h && !wl_in_hook() &&
!(dwFlags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))) {
wl_enter_hook();
wl_patch_module_iat(h);
wl_leave_hook();
}
return h;
}
static DWORD WINAPI hk_GetFileAttributesW(LPCWSTR lpFileName) {
if (!wl_in_hook() && lpFileName && wl_is_nvngx_core_w(lpFileName)) {
return FILE_ATTRIBUTE_ARCHIVE;
}
return o_GetFileAttributesW ? o_GetFileAttributesW(lpFileName) : INVALID_FILE_ATTRIBUTES;
}
static BOOL WINAPI hk_GetFileAttributesExW(LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, LPVOID lpFileInfo) {
if (!wl_in_hook() && lpFileName && wl_is_nvngx_core_w(lpFileName)) {
const WCHAR *target = g_wl_signed_nv_dll[0] ? g_wl_signed_nv_dll : L"C:\\windows\\system32\\_nvngx.dll";
if (o_GetFileAttributesExW) return o_GetFileAttributesExW(target, fInfoLevelId, lpFileInfo);
}
return o_GetFileAttributesExW ? o_GetFileAttributesExW(lpFileName, fInfoLevelId, lpFileInfo) : FALSE;
}
static HANDLE WINAPI hk_CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSec, DWORD dwCreation, DWORD dwFlags, HANDLE hTmpl) {
if (!wl_in_hook() && lpFileName && wl_is_nvngx_core_w(lpFileName) &&
!(dwDesiredAccess & GENERIC_WRITE)) {
const WCHAR *target = g_wl_signed_nv_dll[0] ? g_wl_signed_nv_dll : L"C:\\windows\\system32\\_nvngx.dll";
return o_CreateFileW(target, dwDesiredAccess, dwShareMode, lpSec, dwCreation, dwFlags, hTmpl);
}
return o_CreateFileW ? o_CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSec, dwCreation, dwFlags, hTmpl)
: INVALID_HANDLE_VALUE;
}
static LONG WINAPI hk_WinVerifyTrust(HWND hwnd, GUID *pgActionID, LPVOID pWVTData) {
if (!wl_in_hook() && pWVTData) {
WlWintrustData *data = (WlWintrustData *)pWVTData;
if (data->dwUnionChoice == 1u && data->u.pFile && data->u.pFile->pcwszFilePath &&
wl_is_sig_target_w(data->u.pFile->pcwszFilePath)) {
wl_hook_log("[nvapi] hk_WinVerifyTrust -> ERROR_SUCCESS for nvngx");
if (data->dwStateAction == 1u && g_wl_signed_nv_dll[0] && o_WinVerifyTrust) {
WlWintrustData copy = *data;
WlWintrustFileInfo fcopy = *data->u.pFile;
fcopy.pcwszFilePath = g_wl_signed_nv_dll;
copy.u.pFile = &fcopy;
wl_enter_hook();
LONG r = o_WinVerifyTrust(hwnd, pgActionID, &copy);
wl_leave_hook();
data->hWVTStateData = copy.hWVTStateData;
if (r == ERROR_SUCCESS) return ERROR_SUCCESS;
}
return ERROR_SUCCESS;
}
}
if (!o_WinVerifyTrust) {
HMODULE hw = o_LoadLibraryW ? o_LoadLibraryW(L"wintrust.dll") : NULL;
if (hw && o_GetProcAddress) o_WinVerifyTrust = (PFN_WinVerifyTrust)(void *)o_GetProcAddress(hw, "WinVerifyTrust");
}
return o_WinVerifyTrust ? o_WinVerifyTrust(hwnd, pgActionID, pWVTData) : ERROR_SUCCESS;
}
static BOOL WINAPI hk_CryptQueryObject(DWORD dwObjectType, const void *pvObject, DWORD dwExpectedContent,
DWORD dwExpectedFormat, DWORD dwFlags, DWORD *pdwEncoding,
DWORD *pdwContent, DWORD *pdwFormat, void *phCertStore,
void *phMsg, const void **ppvContext) {
if (!o_CryptQueryObject) {
HMODULE hc = o_LoadLibraryW ? o_LoadLibraryW(L"crypt32.dll") : NULL;
if (hc && o_GetProcAddress) o_CryptQueryObject = (PFN_CryptQueryObject)(void *)o_GetProcAddress(hc, "CryptQueryObject");
}
if (!o_CryptQueryObject) return FALSE;
if (!wl_in_hook() && dwObjectType == 1u /* CERT_QUERY_OBJECT_FILE */ && pvObject) {
const WCHAR *wpath = (const WCHAR *)pvObject;
if (wl_is_sig_target_w(wpath) && g_wl_signed_nv_dll[0]) {
wl_hook_log("[nvapi] hk_CryptQueryObject redirected nvngx -> signed NVIDIA donor");
return o_CryptQueryObject(dwObjectType, g_wl_signed_nv_dll, dwExpectedContent, dwExpectedFormat,
dwFlags, pdwEncoding, pdwContent, pdwFormat, phCertStore, phMsg, ppvContext);
}
}
return o_CryptQueryObject(dwObjectType, pvObject, dwExpectedContent, dwExpectedFormat,
dwFlags, pdwEncoding, pdwContent, pdwFormat, phCertStore, phMsg, ppvContext);
}
static LSTATUS WINAPI hk_RegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult) {
if (!wl_in_hook() && hKey == k_wl_sig_hkey && lpSubKey && phkResult) {
// Child subkey opened relative to our synthetic signature-override key (e.g. NGXCore):
// resolve against real HKLM\SOFTWARE\NVIDIA Corporation\Global\<subkey>
WCHAR full[256];
_snwprintf(full, 255, L"SOFTWARE\\NVIDIA Corporation\\Global\\%ls", lpSubKey);
full[255] = L'\0';
return o_RegOpenKeyExW ? o_RegOpenKeyExW(HKEY_LOCAL_MACHINE, full, ulOptions, samDesired, phkResult)
: ERROR_FILE_NOT_FOUND;
}
if (!wl_in_hook() && lpSubKey && phkResult &&
(_wcsicmp(lpSubKey, L"SOFTWARE\\NVIDIA Corporation\\Global") == 0 ||
_wcsicmp(lpSubKey, L"SYSTEM\\ControlSet001\\Services\\nvlddmkm") == 0 ||
_wcsicmp(lpSubKey, L"SYSTEM\\CurrentControlSet\\Services\\nvlddmkm") == 0)) {
*phkResult = k_wl_sig_hkey;
return ERROR_SUCCESS;
}
return o_RegOpenKeyExW ? o_RegOpenKeyExW(hKey, lpSubKey, ulOptions, samDesired, phkResult) : ERROR_FILE_NOT_FOUND;
}
static LSTATUS WINAPI hk_RegEnumValueW(HKEY hKey, DWORD dwIndex, LPWSTR lpValueName, LPDWORD lpcchValueName,
LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) {
if (hKey == k_wl_sig_hkey) {
if (dwIndex != 0) return ERROR_NO_MORE_ITEMS;
static const WCHAR k_guid[] = L"{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}";
DWORD len = (DWORD)wcslen(k_guid);
if (!lpValueName || !lpcchValueName || !lpData || !lpcbData) return ERROR_INVALID_PARAMETER;
if (*lpcchValueName <= len) { *lpcchValueName = len + 1; return ERROR_MORE_DATA; }
memcpy(lpValueName, k_guid, (len + 1) * sizeof(WCHAR));
*lpcchValueName = len;
if (lpType) *lpType = REG_BINARY;
if (*lpcbData < 1) { *lpcbData = 1; return ERROR_MORE_DATA; }
lpData[0] = 0x01;
*lpcbData = 1;
return ERROR_SUCCESS;
}
return o_RegEnumValueW ? o_RegEnumValueW(hKey, dwIndex, lpValueName, lpcchValueName, lpReserved, lpType, lpData, lpcbData)
: ERROR_NO_MORE_ITEMS;
}
static LSTATUS WINAPI hk_RegQueryValueExW(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved,
LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) {
if (hKey == k_wl_sig_hkey) {
if (lpValueName && _wcsicmp(lpValueName, L"{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}") == 0) {
if (lpType) *lpType = REG_BINARY;
if (!lpcbData) return ERROR_SUCCESS;
if (!lpData) { *lpcbData = 1; return ERROR_SUCCESS; }
if (*lpcbData < 1) { *lpcbData = 1; return ERROR_MORE_DATA; }
lpData[0] = 0x01;
*lpcbData = 1;
return ERROR_SUCCESS;
}
return ERROR_FILE_NOT_FOUND;
}
return o_RegQueryValueExW ? o_RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData)
: ERROR_FILE_NOT_FOUND;
}
static LSTATUS WINAPI hk_RegCloseKey(HKEY hKey) {
if (hKey == k_wl_sig_hkey) return ERROR_SUCCESS;
return o_RegCloseKey ? o_RegCloseKey(hKey) : ERROR_SUCCESS;
}
static FARPROC WINAPI hk_GetProcAddress(HMODULE hMod, LPCSTR lpProcName) {
FARPROC orig = o_GetProcAddress ? o_GetProcAddress(hMod, lpProcName) : NULL;
if (!orig || wl_in_hook() || !lpProcName || ((uintptr_t)lpProcName < 0x10000u)) return orig;
if (strcmp(lpProcName, "WinVerifyTrust") == 0) {
if (!o_WinVerifyTrust) o_WinVerifyTrust = (PFN_WinVerifyTrust)(void *)orig;
return (FARPROC)(void *)hk_WinVerifyTrust;
}
if (strcmp(lpProcName, "CryptQueryObject") == 0) {
if (!o_CryptQueryObject) o_CryptQueryObject = (PFN_CryptQueryObject)(void *)orig;
return (FARPROC)(void *)hk_CryptQueryObject;
}
if (strcmp(lpProcName, "LoadLibraryW") == 0) return (FARPROC)(void *)hk_LoadLibraryW;
if (strcmp(lpProcName, "LoadLibraryA") == 0) return (FARPROC)(void *)hk_LoadLibraryA;
if (strcmp(lpProcName, "LoadLibraryExW") == 0) return (FARPROC)(void *)hk_LoadLibraryExW;
if (strcmp(lpProcName, "LoadLibraryExA") == 0) return (FARPROC)(void *)hk_LoadLibraryExA;
if (strcmp(lpProcName, "GetFileAttributesW") == 0) return (FARPROC)(void *)hk_GetFileAttributesW;
if (strcmp(lpProcName, "GetFileAttributesExW") == 0) return (FARPROC)(void *)hk_GetFileAttributesExW;
if (strcmp(lpProcName, "CreateFileW") == 0) return (FARPROC)(void *)hk_CreateFileW;
if (strcmp(lpProcName, "RegOpenKeyExW") == 0) return (FARPROC)(void *)hk_RegOpenKeyExW;
if (strcmp(lpProcName, "RegEnumValueW") == 0) return (FARPROC)(void *)hk_RegEnumValueW;
if (strcmp(lpProcName, "RegQueryValueExW") == 0) return (FARPROC)(void *)hk_RegQueryValueExW;
if (strcmp(lpProcName, "RegCloseKey") == 0) return (FARPROC)(void *)hk_RegCloseKey;
return orig;
}
static int wl_should_skip_module(HMODULE mod) {
if (!mod || mod == g_wl_self_mod || mod == g_wl_our_nvngx) return 1;
WCHAR path[MAX_PATH] = {0};
DWORD n = GetModuleFileNameW(mod, path, MAX_PATH);
if (n == 0) return 1;
const WCHAR *base = wl_basename_w(path);
// Never patch core OS / Wine system DLLs to prevent recursion or loader side-effects
if (_wcsicmp(base, L"ntdll.dll") == 0 ||
_wcsicmp(base, L"kernel32.dll") == 0 ||
_wcsicmp(base, L"kernelbase.dll") == 0 ||
_wcsicmp(base, L"advapi32.dll") == 0 ||
_wcsicmp(base, L"sechost.dll") == 0 ||
_wcsicmp(base, L"wintrust.dll") == 0 ||
_wcsicmp(base, L"crypt32.dll") == 0 ||
_wcsicmp(base, L"ucrtbase.dll") == 0 ||
_wcsicmp(base, L"msvcrt.dll") == 0 ||
_wcsicmp(base, L"nvapi64.dll") == 0 ||
_wcsicmp(base, L"_nvngx.dll") == 0 ||
_wcsicmp(base, L"nvngx.dll") == 0 ||
_wcsicmp(base, L"dxgi.dll") == 0 ||
_wcsicmp(base, L"d3d12.dll") == 0 ||
_wcsicmp(base, L"d3d12core.dll") == 0 ||
_wcsicmp(base, L"d3d11.dll") == 0 ||
_wcsicmp(base, L"vulkan-1.dll") == 0 ||
_wcsicmp(base, L"winevulkan.dll") == 0) {
return 1;
}
return 0;
}
static void *wl_hook_for_import(const char *funcName) {
if (!funcName) return NULL;
if (strcmp(funcName, "LoadLibraryW") == 0) return (void *)hk_LoadLibraryW;
if (strcmp(funcName, "LoadLibraryA") == 0) return (void *)hk_LoadLibraryA;
if (strcmp(funcName, "LoadLibraryExW") == 0) return (void *)hk_LoadLibraryExW;
if (strcmp(funcName, "LoadLibraryExA") == 0) return (void *)hk_LoadLibraryExA;
if (strcmp(funcName, "GetProcAddress") == 0) return (void *)hk_GetProcAddress;
if (strcmp(funcName, "GetFileAttributesW") == 0) return (void *)hk_GetFileAttributesW;
if (strcmp(funcName, "GetFileAttributesExW") == 0) return (void *)hk_GetFileAttributesExW;
if (strcmp(funcName, "CreateFileW") == 0) return (void *)hk_CreateFileW;
if (strcmp(funcName, "WinVerifyTrust") == 0) return (void *)hk_WinVerifyTrust;
if (strcmp(funcName, "CryptQueryObject") == 0) return (void *)hk_CryptQueryObject;
if (strcmp(funcName, "RegOpenKeyExW") == 0) return (void *)hk_RegOpenKeyExW;
if (strcmp(funcName, "RegEnumValueW") == 0) return (void *)hk_RegEnumValueW;
if (strcmp(funcName, "RegQueryValueExW") == 0) return (void *)hk_RegQueryValueExW;
if (strcmp(funcName, "RegCloseKey") == 0) return (void *)hk_RegCloseKey;
return NULL;
}
static void wl_patch_module_iat(HMODULE mod) {
if (wl_should_skip_module(mod)) return;
uint8_t *base = (uint8_t *)mod;
IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)base;
if (IsBadReadPtr(dos, sizeof *dos) || dos->e_magic != IMAGE_DOS_SIGNATURE) return;
IMAGE_NT_HEADERS *nt = (IMAGE_NT_HEADERS *)(base + dos->e_lfanew);
if (IsBadReadPtr(nt, sizeof *nt) || nt->Signature != IMAGE_NT_SIGNATURE) return;
IMAGE_DATA_DIRECTORY impDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
if (!impDir.VirtualAddress || !impDir.Size) return;
IMAGE_IMPORT_DESCRIPTOR *desc = (IMAGE_IMPORT_DESCRIPTOR *)(base + impDir.VirtualAddress);
for (; !IsBadReadPtr(desc, sizeof *desc) && desc->Name != 0; desc++) {
if (!desc->OriginalFirstThunk || !desc->FirstThunk) continue;
IMAGE_THUNK_DATA *origThunk = (IMAGE_THUNK_DATA *)(base + desc->OriginalFirstThunk);
IMAGE_THUNK_DATA *iatThunk = (IMAGE_THUNK_DATA *)(base + desc->FirstThunk);
for (; origThunk->u1.AddressOfData != 0; origThunk++, iatThunk++) {
if (IMAGE_SNAP_BY_ORDINAL(origThunk->u1.Ordinal)) continue;
IMAGE_IMPORT_BY_NAME *ibn = (IMAGE_IMPORT_BY_NAME *)(base + origThunk->u1.AddressOfData);
void *hookFn = wl_hook_for_import((const char *)ibn->Name);
if (!hookFn) continue;
void **slot = (void **)&iatThunk->u1.Function;
if (*slot == hookFn) continue;
DWORD oldProt = 0;
if (VirtualProtect(slot, sizeof(void *), PAGE_READWRITE, &oldProt)) {
*slot = hookFn;
VirtualProtect(slot, sizeof(void *), oldProt, &oldProt);
}
}
}
}
static int wl_is_arxan_protected_exe(void) {
WCHAR exePath[MAX_PATH] = {0};
if (!GetModuleFileNameW(NULL, exePath, MAX_PATH)) return 0;
const WCHAR *base = wl_basename_w(exePath);
return _wcsicmp(base, L"rdr2.exe") == 0 ||
_wcsicmp(base, L"playrdr2.exe") == 0 ||
_wcsicmp(base, L"gta5.exe") == 0;
}
static void wl_install_ngx_hooks_once(void) {
if (InterlockedCompareExchange(&g_wl_hooks_installed, 1, 0) != 0) return;
if (!dd_env_is_on("DROIDDECK_UPSCALE_SIGFIX")) return;
if (!g_wl_hook_cs_ready) { InitializeCriticalSection(&g_wl_hook_cs); g_wl_hook_cs_ready = 1; }
g_wl_tls_reent = TlsAlloc();
// RDR2 uses Arxan anti-tamper which terminates the game right after the loading screen
// if its executable .text or IAT is modified. Rely cleanly on NGXCore registry keys +
// EnableSignatureOverride ({41FCC608-...}=01) without touching RDR2.exe memory!
if (wl_is_arxan_protected_exe()) {
wl_hook_log("[nvapi] Arxan-protected game detected (RDR2) — skipping IAT/.text patching");
return;
}
HMODULE hK32 = GetModuleHandleA("kernel32.dll");
HMODULE hAdv = GetModuleHandleA("advapi32.dll");
if (!hAdv) hAdv = LoadLibraryA("advapi32.dll");
HMODULE hWt = GetModuleHandleA("wintrust.dll");
HMODULE hCr = GetModuleHandleA("crypt32.dll");
if (hK32) {
o_LoadLibraryW = (PFN_LoadLibraryW)(void *)GetProcAddress(hK32, "LoadLibraryW");
o_LoadLibraryA = (PFN_LoadLibraryA)(void *)GetProcAddress(hK32, "LoadLibraryA");
o_LoadLibraryExW = (PFN_LoadLibraryExW)(void *)GetProcAddress(hK32, "LoadLibraryExW");
o_LoadLibraryExA = (PFN_LoadLibraryExA)(void *)GetProcAddress(hK32, "LoadLibraryExA");
o_GetProcAddress = (PFN_GetProcAddress)(void *)GetProcAddress(hK32, "GetProcAddress");
o_GetFileAttributesW = (PFN_GetFileAttributesW)(void *)GetProcAddress(hK32, "GetFileAttributesW");
o_GetFileAttributesExW = (PFN_GetFileAttributesExW)(void *)GetProcAddress(hK32, "GetFileAttributesExW");
o_CreateFileW = (PFN_CreateFileW)(void *)GetProcAddress(hK32, "CreateFileW");
}
if (hAdv) {
o_RegOpenKeyExW = (PFN_RegOpenKeyExW)(void *)GetProcAddress(hAdv, "RegOpenKeyExW");
o_RegEnumValueW = (PFN_RegEnumValueW)(void *)GetProcAddress(hAdv, "RegEnumValueW");
o_RegQueryValueExW = (PFN_RegQueryValueExW)(void *)GetProcAddress(hAdv, "RegQueryValueExW");
o_RegCloseKey = (PFN_RegCloseKey)(void *)GetProcAddress(hAdv, "RegCloseKey");
}
if (hWt) o_WinVerifyTrust = (PFN_WinVerifyTrust)(void *)GetProcAddress(hWt, "WinVerifyTrust");
if (hCr) o_CryptQueryObject = (PFN_CryptQueryObject)(void *)GetProcAddress(hCr, "CryptQueryObject");
wl_enter_hook();
wl_find_signed_nv_dll();
int patched = 0;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
if (snap != INVALID_HANDLE_VALUE) {
MODULEENTRY32W me;
memset(&me, 0, sizeof me);
me.dwSize = sizeof me;
if (Module32FirstW(snap, &me)) {
do {
if (!wl_should_skip_module(me.hModule)) {
wl_patch_module_iat(me.hModule);
patched++;
}
} while (Module32NextW(snap, &me));
}
CloseHandle(snap);
} else {
wl_patch_module_iat(GetModuleHandleW(NULL));
patched = 1;
}
wl_leave_hook();
char buf[128];
snprintf(buf, sizeof buf, "[nvapi] Installed ARM64EC-safe NGX IAT hooks on %d modules", patched);
wl_hook_log(buf);
}
+576
View File
@@ -0,0 +1,576 @@
// DroidDeck: modified from michaelisomer-cyber/Winlator-NeuralScale a0ab6b0f (see README.md).
// Full OptiScaler/fakenvapi-parity nvapi64.dll shim for Winlator Ludashi FSR 4 NPU.
// - Dynamically queries DXGI Adapter 0 LUID so NVIDIA Streamline (Cyberpunk 2077, etc.)
// matches the DXGI adapter to our spoofed NVIDIA GeForce RTX 2060 (Turing TU106).
// - Implements all core NVAPI interfaces required by RDR2 (Vulkan/DX12), Cyberpunk 2077
// (Streamline sl.common / sl.dlss), Unreal Engine, and DX11/DX12/Vulkan DLSS titles.
#include <windows.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "wl_ngx_hooks.h"
typedef int32_t NvAPI_Status;
#define NVAPI_OK 0
#define NVAPI_ERROR -1
#define NVAPI_INVALID_ARGUMENT -5
#define NVAPI_NO_IMPLEMENTATION -7
#define NVAPI_END_ENUMERATION -7
#define NVAPI_INVALID_POINTER -14
#define NVAPI_NOT_SUPPORTED -104
#define NVAPI_INCOMPATIBLE_STRUCT_VERSION -105
#define NVAPI_SHORT_STRING_MAX 64
#define NVAPI_MAX_PHYSICAL_GPUS 64
// NVIDIA Driver 570.00 (satisfies all DLSS 2/3/3.5/4 & Streamline 2.x checks)
#define WL_NV_DRIVER_VERSION 57000u
#define WL_NV_BUILD_BRANCH "r570_00"
#define WL_NV_GPU_NAME "NVIDIA GeForce RTX 2060"
static void *const k_fake_gpu = (void *)(uintptr_t)0x000010DE00001F08ULL;
static void *const k_fake_lgpu = (void *)(uintptr_t)0x000010DE00001F09ULL;
static void *const k_fake_disp = (void *)(uintptr_t)0x000010DE00000001ULL;
static void *const k_drs_sess = (void *)(uintptr_t)0x000010DE0000D001ULL;
static void *const k_drs_prof = (void *)(uintptr_t)0x000010DE0000D002ULL;
// Minimal COM vtable definitions for IDXGIFactory1 / IDXGIAdapter1 (no dxgi.lib link required)
typedef struct WlDxgiAdapterDesc1 {
WCHAR Description[128];
UINT VendorId;
UINT DeviceId;
UINT SubSysId;
UINT Revision;
SIZE_T DedicatedVideoMemory;
SIZE_T DedicatedSystemMemory;
SIZE_T SharedSystemMemory;
LUID AdapterLuid;
UINT Flags;
} WlDxgiAdapterDesc1;
typedef struct WlIDXGIAdapter1Vtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(void *, const GUID *, void **);
ULONG (STDMETHODCALLTYPE *AddRef)(void *);
ULONG (STDMETHODCALLTYPE *Release)(void *);
HRESULT (STDMETHODCALLTYPE *SetPrivateData)(void *, const GUID *, UINT, const void *);
HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)(void *, const GUID *, const void *);
HRESULT (STDMETHODCALLTYPE *GetPrivateData)(void *, const GUID *, UINT *, void *);
HRESULT (STDMETHODCALLTYPE *GetParent)(void *, const GUID *, void **);
HRESULT (STDMETHODCALLTYPE *EnumOutputs)(void *, UINT, void **);
HRESULT (STDMETHODCALLTYPE *GetDesc)(void *, void *);
HRESULT (STDMETHODCALLTYPE *CheckInterfaceSupport)(void *, const GUID *, LARGE_INTEGER *);
HRESULT (STDMETHODCALLTYPE *GetDesc1)(void *, WlDxgiAdapterDesc1 *);
} WlIDXGIAdapter1Vtbl;
typedef struct { WlIDXGIAdapter1Vtbl *lpVtbl; } WlIDXGIAdapter1;
typedef struct WlIDXGIFactory1Vtbl {
HRESULT (STDMETHODCALLTYPE *QueryInterface)(void *, const GUID *, void **);
ULONG (STDMETHODCALLTYPE *AddRef)(void *);
ULONG (STDMETHODCALLTYPE *Release)(void *);
HRESULT (STDMETHODCALLTYPE *SetPrivateData)(void *, const GUID *, UINT, const void *);
HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)(void *, const GUID *, const void *);
HRESULT (STDMETHODCALLTYPE *GetPrivateData)(void *, const GUID *, UINT *, void *);
HRESULT (STDMETHODCALLTYPE *GetParent)(void *, const GUID *, void **);
HRESULT (STDMETHODCALLTYPE *EnumAdapters)(void *, UINT, void **);
HRESULT (STDMETHODCALLTYPE *MakeWindowAssociation)(void *, HWND, UINT);
HRESULT (STDMETHODCALLTYPE *GetWindowAssociation)(void *, HWND *);
HRESULT (STDMETHODCALLTYPE *CreateSwapChain)(void *, void *, void *, void **);
HRESULT (STDMETHODCALLTYPE *CreateSoftwareAdapter)(void *, HMODULE, void **);
HRESULT (STDMETHODCALLTYPE *EnumAdapters1)(void *, UINT, WlIDXGIAdapter1 **);
} WlIDXGIFactory1Vtbl;
typedef struct { WlIDXGIFactory1Vtbl *lpVtbl; } WlIDXGIFactory1;
typedef HRESULT (WINAPI *PFN_CreateDXGIFactory1)(const GUID *riid, void **ppFactory);
static const GUID k_IID_IDXGIFactory1 = {
0x770aae78u, 0xf26fu, 0x4dbau, { 0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87 }
};
static CRITICAL_SECTION g_cs;
static int g_cs_ready = 0;
static int g_dxgi_probed = 0;
static LUID g_luid = { 0x10DE1F08u, 0 };
static uint32_t g_vendor_id = 0x10DEu;
static uint32_t g_device_id = 0x1F08u;
static uint32_t g_subsys_id = 0x10DE1F08u;
static uint32_t g_rev_id = 0xA1u;
static uint64_t g_dxgi_vram_bytes = 0ULL;
static void ensure_cs(void) {
if (!g_cs_ready) { InitializeCriticalSection(&g_cs); g_cs_ready = 1; }
}
static void probe_dxgi_adapter_once(void) {
ensure_cs();
EnterCriticalSection(&g_cs);
if (!g_dxgi_probed) {
g_dxgi_probed = 1;
HMODULE hDxgi = GetModuleHandleA("dxgi.dll");
if (!hDxgi) hDxgi = LoadLibraryA("dxgi.dll");
if (hDxgi) {
PFN_CreateDXGIFactory1 fnCreate = (PFN_CreateDXGIFactory1)(void *)GetProcAddress(hDxgi, "CreateDXGIFactory1");
if (fnCreate) {
WlIDXGIFactory1 *factory = NULL;
if (SUCCEEDED(fnCreate(&k_IID_IDXGIFactory1, (void **)&factory)) && factory) {
WlIDXGIAdapter1 *adapter = NULL;
if (SUCCEEDED(factory->lpVtbl->EnumAdapters1(factory, 0, &adapter)) && adapter) {
WlDxgiAdapterDesc1 desc;
memset(&desc, 0, sizeof desc);
if (SUCCEEDED(adapter->lpVtbl->GetDesc1(adapter, &desc))) {
g_luid = desc.AdapterLuid;
if (desc.DedicatedVideoMemory > 0) {
g_dxgi_vram_bytes = (uint64_t)desc.DedicatedVideoMemory;
}
if (desc.VendorId == 0x10DEu && desc.DeviceId != 0) {
g_vendor_id = desc.VendorId;
g_device_id = desc.DeviceId;
if (desc.SubSysId) g_subsys_id = desc.SubSysId;
if (desc.Revision) g_rev_id = desc.Revision;
}
}
adapter->lpVtbl->Release(adapter);
}
factory->lpVtbl->Release(factory);
}
}
}
}
LeaveCriticalSection(&g_cs);
}
static uint64_t wl_nv_vram_bytes(void) {
static const char *const names[] = { "DROIDDECK_UPSCALE_VRAM_MB", "WINLATOR_FSR4_VRAM_MB", "WRAPPER_VMEM_MAX_SIZE" };
char buf[64];
for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) {
DWORD n = GetEnvironmentVariableA(names[i], buf, sizeof(buf));
if (n > 0 && n < sizeof(buf)) {
unsigned long long mb = strtoull(buf, NULL, 10);
if (mb >= 512ULL && mb <= 65536ULL) return mb * 1024ULL * 1024ULL;
}
}
probe_dxgi_adapter_once();
if (g_dxgi_vram_bytes >= 512ULL * 1024ULL * 1024ULL) return g_dxgi_vram_bytes;
return 12ULL * 1024ULL * 1024ULL * 1024ULL;
}
static void copy_short_str(char *dst, const char *src) {
if (!dst) return;
strncpy(dst, src ? src : "", NVAPI_SHORT_STRING_MAX - 1);
dst[NVAPI_SHORT_STRING_MAX - 1] = '\0';
}
// ---- Exact NVAPI structs (verified against NVIDIA NVAPI SDK / fakenvapi) ----
typedef struct {
uint32_t version;
uint32_t drvVersion;
uint32_t bldChangeListNum;
char szBuildBranchString[NVAPI_SHORT_STRING_MAX];
char szAdapterString[NVAPI_SHORT_STRING_MAX];
} WlNvDisplayDriverVersion;
typedef struct {
uint32_t version;
uint32_t driverVersion;
char szBuildBranch[NVAPI_SHORT_STRING_MAX];
uint32_t flags; /* bit0=DCH, bit1=Studio, bit2=GameReady, bit3=RTXProd, bit4=RTXNFB */
char szBuildBaseBranch[NVAPI_SHORT_STRING_MAX];
uint32_t reservedEx;
} WlNvDisplayDriverInfoV2;
typedef struct {
uint32_t version;
void *pOSAdapterId;
uint32_t physicalGpuCount;
void *physicalGpuHandles[NVAPI_MAX_PHYSICAL_GPUS];
uint32_t reserved[8];
} WlNvLogicalGpuDataV1;
typedef struct {
uint32_t version;
uint32_t gpuCount;
struct {
void *hPhysicalGpu;
uint32_t flags;
} computeGpus[NVAPI_MAX_PHYSICAL_GPUS];
} WlNvComputeGpuTopologyV1;
typedef struct {
uint32_t bIsPresent;
uint32_t frequency;
} WlNvClockDomain;
typedef struct {
uint32_t version;
uint32_t clockType;
WlNvClockDomain domain[32];
} WlNvGpuClockFrequencies;
// ---- Core NVAPI implementations ----
static NvAPI_Status __cdecl impl_Initialize(void) {
wl_install_ngx_hooks_once();
probe_dxgi_adapter_once();
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_Unload(void) { return NVAPI_OK; }
static NvAPI_Status __cdecl impl_GetInterfaceVersionString(char *out) {
copy_short_str(out, "NVAPI Open Source Interface (Winlator FSR4 NPU)");
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GetErrorMessage(NvAPI_Status nr, char *out) {
copy_short_str(out, nr == NVAPI_OK ? "NVAPI_OK" : "NVAPI_ERROR");
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GetDisplayDriverVersion(void *disp, WlNvDisplayDriverVersion *ver) {
(void)disp;
if (!ver) return NVAPI_INVALID_ARGUMENT;
ver->drvVersion = WL_NV_DRIVER_VERSION;
ver->bldChangeListNum = 35000000u;
copy_short_str(ver->szBuildBranchString, WL_NV_BUILD_BRANCH);
copy_short_str(ver->szAdapterString, WL_NV_GPU_NAME);
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_SYS_GetDriverAndBranchVersion(uint32_t *ver, char *branch) {
if (ver) *ver = WL_NV_DRIVER_VERSION;
if (branch) copy_short_str(branch, WL_NV_BUILD_BRANCH);
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_SYS_GetDisplayDriverInfo(WlNvDisplayDriverInfoV2 *info) {
if (!info) return NVAPI_INVALID_ARGUMENT;
info->driverVersion = WL_NV_DRIVER_VERSION;
copy_short_str(info->szBuildBranch, WL_NV_BUILD_BRANCH);
info->flags = (1u << 0) | (1u << 1) | (1u << 2) | (1u << 3) | (1u << 4);
uint32_t struct_ver = (info->version >> 16) & 0xFFFFu;
if (struct_ver >= 2u || info->version == 2u) {
copy_short_str(info->szBuildBaseBranch, WL_NV_BUILD_BRANCH);
info->reservedEx = 0;
}
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_EnumPhysicalGPUs(void **handles, uint32_t *count) {
probe_dxgi_adapter_once();
if (handles) handles[0] = k_fake_gpu;
if (count) *count = 1u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_EnumLogicalGPUs(void **handles, uint32_t *count) {
probe_dxgi_adapter_once();
if (handles) handles[0] = k_fake_lgpu;
if (count) *count = 1u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_EnumNvidiaDisplayHandle(uint32_t idx, void **handle) {
if (idx > 0) return NVAPI_END_ENUMERATION;
if (handle) *handle = k_fake_disp;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_EnumUnattached(uint32_t idx, void **handle) {
(void)idx; (void)handle;
return NVAPI_END_ENUMERATION;
}
static NvAPI_Status __cdecl impl_GetLogicalGPUFromPhysicalGPU(void *phys, void **logical) {
(void)phys;
if (logical) *logical = k_fake_lgpu;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GetPhysicalGPUsFromLogicalGPU(void *logical, void **phys, uint32_t *count) {
(void)logical;
if (phys) phys[0] = k_fake_gpu;
if (count) *count = 1u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GetPhysicalGPUsFromDisplay(void *disp, void **phys, uint32_t *count) {
(void)disp;
if (phys) phys[0] = k_fake_gpu;
if (count) *count = 1u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GetGPUIDfromPhysicalGPU(void *phys, uint32_t *gpuId) {
(void)phys;
if (gpuId) *gpuId = 0x100u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GetPhysicalGPUFromGPUID(uint32_t gpuId, void **phys) {
(void)gpuId;
if (phys) *phys = k_fake_gpu;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetAdapterIdFromPhysicalGpu(void *gpu, void *pOSAdapterId) {
(void)gpu;
if (!pOSAdapterId) return NVAPI_INVALID_ARGUMENT;
probe_dxgi_adapter_once();
memcpy(pOSAdapterId, &g_luid, sizeof(g_luid));
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetLogicalGpuInfo(void *logical, WlNvLogicalGpuDataV1 *data) {
(void)logical;
if (!data) return NVAPI_INVALID_ARGUMENT;
probe_dxgi_adapter_once();
if (data->pOSAdapterId) memcpy(data->pOSAdapterId, &g_luid, sizeof(g_luid));
data->physicalGpuCount = 1u;
data->physicalGpuHandles[0] = k_fake_gpu;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetFullName(void *gpu, char *name) {
(void)gpu;
copy_short_str(name, WL_NV_GPU_NAME);
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetPCIIdentifiers(void *gpu, uint32_t *devId, uint32_t *subSysId, uint32_t *revId, uint32_t *extDevId) {
(void)gpu;
probe_dxgi_adapter_once();
if (devId) *devId = (g_device_id << 16) | (g_vendor_id & 0xFFFFu);
if (subSysId) *subSysId = g_subsys_id;
if (revId) *revId = g_rev_id;
if (extDevId) *extDevId = g_device_id;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetArchInfo(void *gpu, void *info) {
(void)gpu;
if (!info) return NVAPI_INVALID_ARGUMENT;
uint32_t *u = (uint32_t *)info;
// NV_GPU_ARCH_INFO_V2: [0]=version, [1]=architecture (TU100=0x160), [2]=implementation (TU106=0x06), [3]=revision (0xA1)
u[1] = 0x00000160u;
u[2] = 0x00000006u;
u[3] = 0x000000A1u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetGPUType(void *gpu, uint32_t *type) {
(void)gpu;
if (type) *type = 2u; /* NV_SYSTEM_TYPE_DISCRETE */
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetMemoryInfo(void *gpu, uint32_t *info) {
(void)gpu;
if (info) {
uint64_t vram_kb64 = wl_nv_vram_bytes() / 1024ULL;
uint32_t vram_kb = (vram_kb64 > 0xFFFFFFFFULL) ? 0xFFFFFFFFu : (uint32_t)vram_kb64;
info[1] = vram_kb;
info[2] = vram_kb;
info[3] = 0u;
info[4] = vram_kb / 2u;
info[5] = (vram_kb / 8u) * 7u;
}
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetMemoryInfoEx(void *gpu, uint64_t *info) {
(void)gpu;
if (info) {
uint64_t vram_b = wl_nv_vram_bytes();
info[1] = vram_b;
info[2] = vram_b;
info[3] = 0ULL;
info[4] = vram_b / 2ULL;
info[5] = (vram_b / 8ULL) * 7ULL;
}
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetVbiosVersionString(void *gpu, char *out) {
(void)gpu;
copy_short_str(out, "90.06.2E.00.01");
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetPhysicalFrameBufferSize(void *gpu, uint32_t *kb) {
(void)gpu;
if (kb) {
uint64_t vram_kb64 = wl_nv_vram_bytes() / 1024ULL;
*kb = (vram_kb64 > 0xFFFFFFFFULL) ? 0xFFFFFFFFu : (uint32_t)vram_kb64;
}
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetGpuCoreCount(void *gpu, uint32_t *cnt) {
(void)gpu;
if (cnt) *cnt = 1920u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetConnectedDisplayIds(void *gpu, void *ids, uint32_t *cnt, uint32_t flags) {
(void)gpu; (void)ids; (void)flags;
if (cnt) *cnt = 0u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_CudaEnumComputeCapableGpus(WlNvComputeGpuTopologyV1 *topo) {
if (!topo) return NVAPI_INVALID_ARGUMENT;
topo->gpuCount = 1u;
topo->computeGpus[0].hPhysicalGpu = k_fake_gpu;
topo->computeGpus[0].flags = 0x7u; /* CAPABLE | ENABLE | RECOMMENDED */
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_GPU_GetAllClockFrequencies(void *gpu, WlNvGpuClockFrequencies *clk) {
(void)gpu;
if (!clk) return NVAPI_INVALID_ARGUMENT;
memset(clk->domain, 0, sizeof clk->domain);
clk->domain[0].bIsPresent = 1; clk->domain[0].frequency = 1680000u; /* Graphics */
clk->domain[4].bIsPresent = 1; clk->domain[4].frequency = 7000000u; /* Memory */
clk->domain[7].bIsPresent = 1; clk->domain[7].frequency = 1400000u; /* Video */
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_Disp_GetDisplayIdByDisplayName(const char *name, uint32_t *id) {
(void)name;
if (id) *id = 0u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_Disp_GetGDIPrimaryDisplayId(uint32_t *id) {
if (id) *id = 0u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_Disp_OutputMode(uint32_t dispId, uint32_t *mode) {
(void)dispId;
if (mode) *mode = 0u; /* SDR */
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_SYS_GetDisplayIdFromGpuAndOutputId(void *gpu, uint32_t outId, uint32_t *dispId) {
(void)gpu; (void)outId;
if (dispId) *dispId = 0u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_SYS_GetGpuAndOutputIdFromDisplayId(uint32_t dispId, void **gpu, uint32_t *outId) {
(void)dispId;
if (gpu) *gpu = k_fake_gpu;
if (outId) *outId = 0u;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_D3D_GetCurrentSLIState(void *dev, uint32_t *state) {
(void)dev;
if (state) {
state[1] = 1; state[2] = 1; state[3] = 0;
state[4] = 0; state[5] = 0; state[6] = 0;
}
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_D3D_GetObjectHandleForResource(void *dev, void *res, void **outH) {
(void)dev;
if (outH) *outH = res;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_D3D12_IsNvShaderExtnOpCodeSupported(void *dev, uint32_t op, uint8_t *supported) {
(void)dev; (void)op;
if (supported) *supported = 0;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_D3D12_GetRaytracingCaps(void *dev, uint32_t type, void *pData, size_t dataSize) {
(void)dev; (void)type;
if (!pData) return NVAPI_INVALID_POINTER;
memset(pData, 0, dataSize);
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_DRS_CreateSession(void **sess) {
if (sess) *sess = k_drs_sess;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_DRS_GetBaseProfile(void *sess, void **prof) {
(void)sess;
if (prof) *prof = k_drs_prof;
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_D3D_GetSleepStatus(void *dev, uint32_t *params) {
(void)dev;
if (params) {
params[1] = 0u; /* bLowLatencyMode */
params[2] = 0u; /* bFsVrr */
params[3] = 0u; /* bCplVsyncOn */
}
return NVAPI_OK;
}
static NvAPI_Status __cdecl impl_NoOpOk(void) { return NVAPI_OK; }
static NvAPI_Status __cdecl impl_NotSupported(void) { return NVAPI_NO_IMPLEMENTATION; }
__declspec(dllexport) void *__cdecl nvapi_QueryInterface(uint32_t id) {
wl_install_ngx_hooks_once();
switch (id) {
// Core & driver info
case 0x0150E828u: return (void *)impl_Initialize; // NvAPI_Initialize
case 0xD22BDD7Eu: return (void *)impl_Unload; // NvAPI_Unload
case 0x01053FA5u: return (void *)impl_GetInterfaceVersionString; // NvAPI_GetInterfaceVersionString
case 0x6C2D048Cu: return (void *)impl_GetErrorMessage; // NvAPI_GetErrorMessage
case 0xF951A4D1u: return (void *)impl_GetDisplayDriverVersion; // NvAPI_GetDisplayDriverVersion
case 0x2926AAADu: return (void *)impl_SYS_GetDriverAndBranchVersion; // NvAPI_SYS_GetDriverAndBranchVersion
case 0x721FACEBu: return (void *)impl_SYS_GetDisplayDriverInfo; // NvAPI_SYS_GetDisplayDriverInfo
case 0x08F2BAB4u: return (void *)impl_SYS_GetDisplayIdFromGpuAndOutputId;// NvAPI_SYS_GetDisplayIdFromGpuAndOutputId
case 0x112BA1A5u: return (void *)impl_SYS_GetGpuAndOutputIdFromDisplayId;// NvAPI_SYS_GetGpuAndOutputIdFromDisplayId
// Physical / logical GPU enumeration & LUID matching (CRITICAL for Streamline / Cyberpunk 2077)
case 0xE5AC921Fu: return (void *)impl_EnumPhysicalGPUs; // NvAPI_EnumPhysicalGPUs
case 0x48B3EA59u: return (void *)impl_EnumLogicalGPUs; // NvAPI_EnumLogicalGPUs
case 0x9ABDD40Du: return (void *)impl_EnumNvidiaDisplayHandle; // NvAPI_EnumNvidiaDisplayHandle
case 0x20DE9260u: return (void *)impl_EnumUnattached; // NvAPI_EnumNvidiaUnAttachedDisplayHandle
case 0xADD604D1u: return (void *)impl_GetLogicalGPUFromPhysicalGPU; // NvAPI_GetLogicalGPUFromPhysicalGPU
case 0xAEA3FA32u: return (void *)impl_GetPhysicalGPUsFromLogicalGPU; // NvAPI_GetPhysicalGPUsFromLogicalGPU
case 0x34EF9506u: return (void *)impl_GetPhysicalGPUsFromDisplay; // NvAPI_GetPhysicalGPUsFromDisplay
case 0x6533EA3Eu: return (void *)impl_GetGPUIDfromPhysicalGPU; // NvAPI_GetGPUIDfromPhysicalGPU
case 0x5380AD1Au: return (void *)impl_GetPhysicalGPUFromGPUID; // NvAPI_GetPhysicalGPUFromGPUID
case 0x0FF07FDEu: return (void *)impl_GPU_GetAdapterIdFromPhysicalGpu; // NvAPI_GPU_GetAdapterIdFromPhysicalGpu
case 0x842B066Eu: return (void *)impl_GPU_GetLogicalGpuInfo; // NvAPI_GPU_GetLogicalGpuInfo
// GPU capabilities & identity
case 0xCEEE8E9Fu: return (void *)impl_GPU_GetFullName; // NvAPI_GPU_GetFullName
case 0x2DDFB66Eu: return (void *)impl_GPU_GetPCIIdentifiers; // NvAPI_GPU_GetPCIIdentifiers
case 0xD8265D24u: return (void *)impl_GPU_GetArchInfo; // NvAPI_GPU_GetArchInfo
case 0xC33BAEB1u: return (void *)impl_GPU_GetGPUType; // NvAPI_GPU_GetGPUType
case 0x07F9B368u: return (void *)impl_GPU_GetMemoryInfo; // NvAPI_GPU_GetMemoryInfo
case 0xC0599498u: return (void *)impl_GPU_GetMemoryInfoEx; // NvAPI_GPU_GetMemoryInfoEx
case 0xA561FD7Du: return (void *)impl_GPU_GetVbiosVersionString; // NvAPI_GPU_GetVbiosVersionString
case 0x46FBEB03u: return (void *)impl_GPU_GetPhysicalFrameBufferSize; // NvAPI_GPU_GetPhysicalFrameBufferSize
case 0x5A04B644u: return (void *)impl_GPU_GetPhysicalFrameBufferSize; // NvAPI_GPU_GetVirtualFrameBufferSize
case 0xC7026A87u: return (void *)impl_GPU_GetGpuCoreCount; // NvAPI_GPU_GetGpuCoreCount
case 0x0078DBA2u: return (void *)impl_GPU_GetConnectedDisplayIds; // NvAPI_GPU_GetConnectedDisplayIds
case 0x5786CC6Eu: return (void *)impl_GPU_CudaEnumComputeCapableGpus; // NvAPI_GPU_CudaEnumComputeCapableGpus
case 0xDCB616C3u: return (void *)impl_GPU_GetAllClockFrequencies; // NvAPI_GPU_GetAllClockFrequencies
// Display
case 0xAE457190u: return (void *)impl_Disp_GetDisplayIdByDisplayName; // NvAPI_DISP_GetDisplayIdByDisplayName
case 0x1E9D8A31u: return (void *)impl_Disp_GetGDIPrimaryDisplayId; // NvAPI_DISP_GetGDIPrimaryDisplayId
case 0x98E7661Au: return (void *)impl_Disp_OutputMode; // NvAPI_Disp_SetOutputMode
case 0x81FED88Du: return (void *)impl_Disp_OutputMode; // NvAPI_Disp_GetOutputMode
case 0x84F2A8DFu: return (void *)impl_NoOpOk; // NvAPI_Disp_GetHdrCapabilities
case 0x351DA224u: return (void *)impl_NoOpOk; // NvAPI_Disp_HdrColorControl
// D3D / D3D12 / Reflex
case 0x4B708B54u: return (void *)impl_D3D_GetCurrentSLIState; // NvAPI_D3D_GetCurrentSLIState
case 0xFCEAC864u: return (void *)impl_D3D_GetObjectHandleForResource; // NvAPI_D3D_GetObjectHandleForResource
case 0x8C02C4D0u: return (void *)impl_NoOpOk; // NvAPI_D3D_RegisterDevice
case 0x3DFACEC8u: return (void *)impl_D3D12_IsNvShaderExtnOpCodeSupported;// NvAPI_D3D12_IsNvShaderExtnOpCodeSupported
case 0x43D867C0u: return (void *)impl_NoOpOk; // NvAPI_D3D12_SetNvShaderExtnSlotSpaceLocalThread
case 0x85A6C2A0u: return (void *)impl_D3D12_GetRaytracingCaps; // NvAPI_D3D12_GetRaytracingCaps
case 0x03D6E8CBu: return (void *)impl_NoOpOk; // NvAPI_D3D12_NotifyOutOfBandCommandQueue
case 0x13C98F73u: return (void *)impl_NoOpOk; // NvAPI_D3D12_SetAsyncFrameMarker
case 0xAEF96CA1u: return (void *)impl_D3D_GetSleepStatus; // NvAPI_D3D_GetSleepStatus
case 0xAC1CA9E0u: return (void *)impl_NoOpOk; // NvAPI_D3D_SetSleepMode
case 0x852CD1D2u: return (void *)impl_NoOpOk; // NvAPI_D3D_Sleep
case 0xB9F6FAFFu: return (void *)impl_NoOpOk; // NvAPI_D3D_SetReflexSync
case 0x1A587F9Cu: return (void *)impl_NoOpOk; // NvAPI_D3D_GetLatency
case 0xD9984C05u: return (void *)impl_NoOpOk; // NvAPI_D3D_SetLatencyMarker
// Vulkan Reflex (graceful unsupported so Vulkan games don't expect a timeline semaphore we didn't create)
case 0x5C1696B6u: return (void *)impl_NotSupported; // NvAPI_Vulkan_InitLowLatencyDevice
case 0x11A5932Bu: return (void *)impl_NoOpOk; // NvAPI_Vulkan_DestroyLowLatencyDevice
case 0xADF966AFu: return (void *)impl_NotSupported; // NvAPI_Vulkan_GetSleepStatus
case 0x2ACFD162u: return (void *)impl_NotSupported; // NvAPI_Vulkan_SetSleepMode
case 0x36732B1Eu: return (void *)impl_NotSupported; // NvAPI_Vulkan_Sleep
case 0x3233D44Au: return (void *)impl_NotSupported; // NvAPI_Vulkan_GetLatency
case 0xA17D13D6u: return (void *)impl_NotSupported; // NvAPI_Vulkan_SetLatencyMarker
case 0x5D6D3840u: return (void *)impl_NoOpOk; // NvAPI_Vulkan_NotifyOutOfBandVkQueue
// DRS (Driver Settings)
case 0x0694D52Eu: return (void *)impl_DRS_CreateSession; // NvAPI_DRS_CreateSession
case 0xDAD9CFF8u: return (void *)impl_NoOpOk; // NvAPI_DRS_DestroySession
case 0x375DBD6Bu: return (void *)impl_NoOpOk; // NvAPI_DRS_LoadSettings
case 0xFCBC7E14u: return (void *)impl_NoOpOk; // NvAPI_DRS_SaveSettings
case 0xDA8466A0u: return (void *)impl_DRS_GetBaseProfile; // NvAPI_DRS_GetBaseProfile
case 0x73BF8338u: return (void *)impl_NotSupported; // NvAPI_DRS_GetSetting
case 0x577DD202u: return (void *)impl_NoOpOk; // NvAPI_DRS_SetSetting
default: return NULL;
}
}
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
(void)reserved;
if (reason == DLL_PROCESS_ATTACH) {
g_wl_self_mod = hinst;
DisableThreadLibraryCalls(hinst);
ensure_cs();
}
return TRUE;
}
+443
View File
@@ -0,0 +1,443 @@
// DroidDeck: modified from michaelisomer-cyber/Winlator-NeuralScale a0ab6b0f (see README.md).
// Windows-side in-process Vulkan Seam Client for Winlator Ludashi FSR 4.1.1 HTP NPU Layer.
// Allocates the host-coherent WlFsr4Mailbox + marker buffer on the game's VkDevice and
// rings the vkCmdUpdateBuffer doorbell so libVkLayer_winlator_fsr4_npu.so records the
// zero-copy Hexagon HTP v81 pipeline directly into the game's VkCommandBuffer.
#pragma once
#include <windows.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include "fsr4_seam_proto.h"
#include "dd_env.h"
// Minimal Vulkan types for MinGW x86_64 (zero external Vulkan SDK dependency)
typedef uint32_t VkFlags;
typedef uint32_t VkBool32;
typedef uint64_t VkDeviceSize;
typedef int32_t VkResult;
typedef void *VkInstance;
typedef void *VkPhysicalDevice;
typedef void *VkDevice;
typedef void *VkCommandBuffer;
typedef uint64_t VkBuffer;
typedef uint64_t VkDeviceMemory;
typedef uint64_t VkImage;
typedef uint64_t VkImageView;
#define VK_SUCCESS 0
#define VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO 12
#define VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO 5
#define VK_BUFFER_USAGE_TRANSFER_DST_BIT 0x00000002u
#define VK_BUFFER_USAGE_STORAGE_BUFFER_BIT 0x00000020u
#define VK_SHARING_MODE_EXCLUSIVE 0
#define VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT 0x00000002u
#define VK_MEMORY_PROPERTY_HOST_COHERENT_BIT 0x00000004u
typedef struct {
uint32_t sType;
const void *pNext;
VkFlags flags;
VkDeviceSize size;
VkFlags usage;
uint32_t sharingMode;
uint32_t queueFamilyIndexCount;
const uint32_t *pQueueFamilyIndices;
} WlVkBufferCreateInfo;
typedef struct {
VkDeviceSize size;
VkDeviceSize alignment;
uint32_t memoryTypeBits;
} WlVkMemoryRequirements;
typedef struct {
uint32_t sType;
const void *pNext;
VkDeviceSize allocationSize;
uint32_t memoryTypeIndex;
} WlVkMemoryAllocateInfo;
typedef struct {
VkFlags propertyFlags;
uint32_t heapIndex;
} WlVkMemoryType;
typedef struct {
VkDeviceSize size;
VkFlags flags;
} WlVkMemoryHeap;
typedef struct {
uint32_t memoryTypeCount;
WlVkMemoryType memoryTypes[32];
uint32_t memoryHeapCount;
WlVkMemoryHeap memoryHeaps[16];
} WlVkPhysicalDeviceMemoryProperties;
typedef struct {
uint32_t sType;
const void *pNext;
uint32_t srcAccessMask;
uint32_t dstAccessMask;
uint32_t oldLayout;
uint32_t newLayout;
uint32_t srcQueueFamilyIndex;
uint32_t dstQueueFamilyIndex;
VkImage image;
struct {
uint32_t aspectMask;
uint32_t baseMipLevel;
uint32_t levelCount;
uint32_t baseArrayLayer;
uint32_t layerCount;
} subresourceRange;
} WlVkImageMemoryBarrier;
typedef struct {
struct {
uint32_t aspectMask;
uint32_t mipLevel;
uint32_t baseArrayLayer;
uint32_t layerCount;
} srcSubresource;
struct { int32_t x, y, z; } srcOffsets[2];
struct {
uint32_t aspectMask;
uint32_t mipLevel;
uint32_t baseArrayLayer;
uint32_t layerCount;
} dstSubresource;
struct { int32_t x, y, z; } dstOffsets[2];
} WlVkImageBlit;
typedef void *(__stdcall *PFN_wlVkGetDeviceProcAddr)(VkDevice, const char *);
typedef void *(__stdcall *PFN_wlVkGetInstanceProcAddr)(VkInstance, const char *);
typedef VkResult (__stdcall *PFN_wlVkCreateBuffer)(VkDevice, const WlVkBufferCreateInfo *, const void *, VkBuffer *);
typedef void (__stdcall *PFN_wlVkDestroyBuffer)(VkDevice, VkBuffer, const void *);
typedef void (__stdcall *PFN_wlVkGetBufferMemoryRequirements)(VkDevice, VkBuffer, WlVkMemoryRequirements *);
typedef VkResult (__stdcall *PFN_wlVkAllocateMemory)(VkDevice, const WlVkMemoryAllocateInfo *, const void *, VkDeviceMemory *);
typedef void (__stdcall *PFN_wlVkFreeMemory)(VkDevice, VkDeviceMemory, const void *);
typedef VkResult (__stdcall *PFN_wlVkBindBufferMemory)(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize);
typedef VkResult (__stdcall *PFN_wlVkMapMemory)(VkDevice, VkDeviceMemory, VkDeviceSize, VkDeviceSize, VkFlags, void **);
typedef void (__stdcall *PFN_wlVkUnmapMemory)(VkDevice, VkDeviceMemory);
typedef void (__stdcall *PFN_wlVkCmdUpdateBuffer)(VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, const void *);
typedef void (__stdcall *PFN_wlVkCmdPipelineBarrier)(VkCommandBuffer, uint32_t, uint32_t, uint32_t, uint32_t, const void *, uint32_t, const void *, uint32_t, const WlVkImageMemoryBarrier *);
typedef void (__stdcall *PFN_wlVkCmdBlitImage)(VkCommandBuffer, VkImage, uint32_t, VkImage, uint32_t, uint32_t, const WlVkImageBlit *, uint32_t);
typedef void (__stdcall *PFN_wlVkGetPhysicalDeviceMemoryProperties)(VkPhysicalDevice, WlVkPhysicalDeviceMemoryProperties *);
typedef struct WlSeamClient {
int ready;
VkInstance inst;
VkDevice dev;
VkPhysicalDevice phys;
VkBuffer mbox_buf;
VkDeviceMemory mbox_mem;
WlFsr4Mailbox *mbox;
VkBuffer marker_buf;
VkDeviceMemory marker_mem;
uint64_t next_seq;
PFN_wlVkDestroyBuffer DestroyBuffer;
PFN_wlVkFreeMemory FreeMemory;
PFN_wlVkUnmapMemory UnmapMemory;
PFN_wlVkCmdUpdateBuffer CmdUpdateBuffer;
PFN_wlVkCmdPipelineBarrier CmdPipelineBarrier;
PFN_wlVkCmdBlitImage CmdBlitImage;
} WlSeamClient;
static uint32_t wl_seam_pick_mem(const WlVkPhysicalDeviceMemoryProperties *mp, uint32_t bits, uint32_t want) {
if (mp) {
for (uint32_t i = 0; i < mp->memoryTypeCount; i++) {
if ((bits & (1u << i)) && (mp->memoryTypes[i].propertyFlags & want) == want) return i;
}
}
for (uint32_t i = 0; i < 32; i++) {
if (bits & (1u << i)) return i;
}
return 0xFFFFFFFFu;
}
static int wl_seam_init(WlSeamClient *c, VkInstance inst, VkPhysicalDevice phys, VkDevice dev,
PFN_wlVkGetDeviceProcAddr gdpa) {
memset(c, 0, sizeof *c);
if (!dev) return 0;
HMODULE vkmod = GetModuleHandleA("vulkan-1.dll");
if (!vkmod) vkmod = LoadLibraryA("vulkan-1.dll");
if (!gdpa && vkmod) gdpa = (PFN_wlVkGetDeviceProcAddr)(void *)GetProcAddress(vkmod, "vkGetDeviceProcAddr");
if (!gdpa) return 0;
PFN_wlVkCreateBuffer CreateBuffer = (PFN_wlVkCreateBuffer)gdpa(dev, "vkCreateBuffer");
PFN_wlVkGetBufferMemoryRequirements GetBufReqs = (PFN_wlVkGetBufferMemoryRequirements)gdpa(dev, "vkGetBufferMemoryRequirements");
PFN_wlVkAllocateMemory AllocateMemory = (PFN_wlVkAllocateMemory)gdpa(dev, "vkAllocateMemory");
PFN_wlVkBindBufferMemory BindBufferMemory = (PFN_wlVkBindBufferMemory)gdpa(dev, "vkBindBufferMemory");
PFN_wlVkMapMemory MapMemory = (PFN_wlVkMapMemory)gdpa(dev, "vkMapMemory");
c->DestroyBuffer = (PFN_wlVkDestroyBuffer)gdpa(dev, "vkDestroyBuffer");
c->FreeMemory = (PFN_wlVkFreeMemory)gdpa(dev, "vkFreeMemory");
c->UnmapMemory = (PFN_wlVkUnmapMemory)gdpa(dev, "vkUnmapMemory");
c->CmdUpdateBuffer = (PFN_wlVkCmdUpdateBuffer)gdpa(dev, "vkCmdUpdateBuffer");
c->CmdPipelineBarrier = (PFN_wlVkCmdPipelineBarrier)gdpa(dev, "vkCmdPipelineBarrier");
c->CmdBlitImage = (PFN_wlVkCmdBlitImage)gdpa(dev, "vkCmdBlitImage");
if (!CreateBuffer || !GetBufReqs || !AllocateMemory || !BindBufferMemory || !MapMemory || !c->CmdUpdateBuffer)
return 0;
WlVkPhysicalDeviceMemoryProperties mp;
memset(&mp, 0, sizeof mp);
int has_mp = 0;
if (phys && vkmod) {
PFN_wlVkGetPhysicalDeviceMemoryProperties get_mp = NULL;
if (inst) {
PFN_wlVkGetInstanceProcAddr gipa = (PFN_wlVkGetInstanceProcAddr)(void *)GetProcAddress(vkmod, "vkGetInstanceProcAddr");
if (gipa) get_mp = (PFN_wlVkGetPhysicalDeviceMemoryProperties)gipa(inst, "vkGetPhysicalDeviceMemoryProperties");
}
if (!get_mp) get_mp = (PFN_wlVkGetPhysicalDeviceMemoryProperties)(void *)GetProcAddress(vkmod, "vkGetPhysicalDeviceMemoryProperties");
if (get_mp) { get_mp(phys, &mp); has_mp = 1; }
}
// 1. Allocate MAILBOX buffer (exact signature WLFSR4_MAILBOX_BYTES + STORAGE_BUFFER | TRANSFER_DST)
WlVkBufferCreateInfo bci;
memset(&bci, 0, sizeof bci);
bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bci.size = WLFSR4_MAILBOX_BYTES;
bci.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (CreateBuffer(dev, &bci, NULL, &c->mbox_buf) != VK_SUCCESS) return 0;
WlVkMemoryRequirements mr;
memset(&mr, 0, sizeof mr);
GetBufReqs(dev, c->mbox_buf, &mr);
WlVkMemoryAllocateInfo mai;
memset(&mai, 0, sizeof mai);
mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mai.allocationSize = mr.size;
void *mapped = NULL;
if (has_mp) {
uint32_t mt = wl_seam_pick_mem(&mp, mr.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
if (mt == 0xFFFFFFFFu) { if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL); return 0; }
mai.memoryTypeIndex = mt;
if (AllocateMemory(dev, &mai, NULL, &c->mbox_mem) != VK_SUCCESS ||
BindBufferMemory(dev, c->mbox_buf, c->mbox_mem, 0) != VK_SUCCESS ||
MapMemory(dev, c->mbox_mem, 0, WLFSR4_MAILBOX_BYTES, 0, &mapped) != VK_SUCCESS || !mapped) {
if (c->mbox_mem && c->FreeMemory) c->FreeMemory(dev, c->mbox_mem, NULL);
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL);
return 0;
}
} else {
// VkPhysicalDevice unavailable (e.g. FSR 2 VK): probe compatible memory types until vkMapMemory succeeds
int ok = 0;
for (uint32_t i = 0; i < 32; i++) {
if (!(mr.memoryTypeBits & (1u << i))) continue;
VkDeviceMemory cand = 0;
mai.memoryTypeIndex = i;
if (AllocateMemory(dev, &mai, NULL, &cand) != VK_SUCCESS) continue;
if (MapMemory(dev, cand, 0, WLFSR4_MAILBOX_BYTES, 0, &mapped) == VK_SUCCESS && mapped) {
if (BindBufferMemory(dev, c->mbox_buf, cand, 0) == VK_SUCCESS) {
c->mbox_mem = cand;
ok = 1;
break;
}
if (c->UnmapMemory) c->UnmapMemory(dev, cand);
}
if (c->FreeMemory) c->FreeMemory(dev, cand, NULL);
mapped = NULL;
}
if (!ok) {
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL);
return 0;
}
}
memset(mapped, 0, WLFSR4_MAILBOX_BYTES);
c->mbox = (WlFsr4Mailbox *)mapped;
c->mbox->magic = WLFSR4_MAILBOX_MAGIC;
c->mbox->version = WLFSR4_PROTO_VERSION;
// 2. Allocate MARKER buffer (exact signature WLFSR4_MARKER_BYTES + TRANSFER_DST)
bci.size = WLFSR4_MARKER_BYTES;
bci.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
if (CreateBuffer(dev, &bci, NULL, &c->marker_buf) != VK_SUCCESS) {
if (c->UnmapMemory) c->UnmapMemory(dev, c->mbox_mem);
if (c->FreeMemory) c->FreeMemory(dev, c->mbox_mem, NULL);
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL);
return 0;
}
GetBufReqs(dev, c->marker_buf, &mr);
mai.allocationSize = mr.size;
mai.memoryTypeIndex = wl_seam_pick_mem(has_mp ? &mp : NULL, mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
if (AllocateMemory(dev, &mai, NULL, &c->marker_mem) != VK_SUCCESS ||
BindBufferMemory(dev, c->marker_buf, c->marker_mem, 0) != VK_SUCCESS) {
if (c->marker_mem && c->FreeMemory) c->FreeMemory(dev, c->marker_mem, NULL);
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->marker_buf, NULL);
if (c->UnmapMemory) c->UnmapMemory(dev, c->mbox_mem);
if (c->FreeMemory) c->FreeMemory(dev, c->mbox_mem, NULL);
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL);
return 0;
}
c->inst = inst;
c->dev = dev;
c->phys = phys;
c->next_seq = 1u;
c->ready = 1;
return 1;
}
static void wl_seam_destroy(WlSeamClient *c) {
if (!c || !c->ready) return;
if (c->marker_buf && c->DestroyBuffer) c->DestroyBuffer(c->dev, c->marker_buf, NULL);
if (c->marker_mem && c->FreeMemory) c->FreeMemory(c->dev, c->marker_mem, NULL);
if (c->mbox_mem && c->UnmapMemory) c->UnmapMemory(c->dev, c->mbox_mem);
if (c->mbox_buf && c->DestroyBuffer) c->DestroyBuffer(c->dev, c->mbox_buf, NULL);
if (c->mbox_mem && c->FreeMemory) c->FreeMemory(c->dev, c->mbox_mem, NULL);
memset(c, 0, sizeof *c);
}
static int wl_seam_dispatch(WlSeamClient *c, VkCommandBuffer cb, const WlFsr4FrameDesc *in_frame) {
if (!c || !c->ready || !cb || !in_frame || !c->mbox) return 0;
uint64_t seq = c->next_seq++;
WlFsr4FrameDesc *slot = &c->mbox->slots[seq % WLFSR4_SLOTS];
*slot = *in_frame;
slot->seq = seq;
MemoryBarrier();
WlFsr4DoorbellPayload pay;
pay.magic = WLFSR4_DOORBELL_MAGIC;
pay.seq = seq;
c->CmdUpdateBuffer(cb, c->marker_buf, 0, sizeof pay, &pay);
MemoryBarrier();
uint64_t ack = c->mbox->ack;
return ((ack & WLFSR4_ACK_SEQ_MASK) == seq && (ack & WLFSR4_ACK_WORK_BIT)) ? 1 : 0;
}
// Fail-closed guest-side bilinear blit fallback if the Vulkan layer did not ack a frame.
// Ensures the game's output image is NEVER left unwritten / corrupted with stale VRAM.
static int wl_seam_fallback_blit(WlSeamClient *c, VkCommandBuffer cb, const WlFsr4FrameDesc *f) {
if (!c || !cb || !f || !c->CmdPipelineBarrier || !c->CmdBlitImage) return 0;
if (!f->color.vk_image || !f->output.vk_image || f->color.vk_image == f->output.vk_image) return 0;
uint32_t rw = f->render_w ? f->render_w : f->color.width;
uint32_t rh = f->render_h ? f->render_h : f->color.height;
uint32_t ow = f->output_w ? f->output_w : f->output.width;
uint32_t oh = f->output_h ? f->output_h : f->output.height;
if (!rw || !rh || !ow || !oh) return 0;
uint32_t src_lay = f->color.vk_layout ? f->color.vk_layout : 1u; /* GENERAL */
uint32_t dst_lay = f->output.vk_layout ? f->output.vk_layout : 1u;
WlVkImageMemoryBarrier pre[2];
memset(pre, 0, sizeof pre);
pre[0].sType = 45u; /* VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER */
pre[0].srcAccessMask = 0x00010000u; /* MEMORY_WRITE */
pre[0].dstAccessMask = 0x00000800u; /* TRANSFER_READ */
pre[0].oldLayout = src_lay;
pre[0].newLayout = 6u; /* TRANSFER_SRC_OPTIMAL */
pre[0].srcQueueFamilyIndex = 0xFFFFFFFFu;
pre[0].dstQueueFamilyIndex = 0xFFFFFFFFu;
pre[0].image = f->color.vk_image;
pre[0].subresourceRange.aspectMask = 1u;
pre[0].subresourceRange.levelCount = 1u;
pre[0].subresourceRange.layerCount = 1u;
pre[1] = pre[0];
pre[1].srcAccessMask = 0x00018000u; /* MEMORY_READ | MEMORY_WRITE */
pre[1].dstAccessMask = 0x00001000u; /* TRANSFER_WRITE */
pre[1].oldLayout = dst_lay;
pre[1].newLayout = 7u; /* TRANSFER_DST_OPTIMAL */
pre[1].image = f->output.vk_image;
c->CmdPipelineBarrier(cb, 0x00010000u /* ALL_COMMANDS */, 0x00001000u /* TRANSFER */, 0, 0, NULL, 0, NULL, 2, pre);
WlVkImageBlit reg;
memset(&reg, 0, sizeof reg);
reg.srcSubresource.aspectMask = 1u;
reg.srcSubresource.layerCount = 1u;
reg.srcOffsets[1].x = (int32_t)rw;
reg.srcOffsets[1].y = (int32_t)rh;
reg.srcOffsets[1].z = 1;
reg.dstSubresource.aspectMask = 1u;
reg.dstSubresource.layerCount = 1u;
reg.dstOffsets[1].x = (int32_t)ow;
reg.dstOffsets[1].y = (int32_t)oh;
reg.dstOffsets[1].z = 1;
c->CmdBlitImage(cb, f->color.vk_image, 6u, f->output.vk_image, 7u, 1u, &reg, 1u /* LINEAR */);
WlVkImageMemoryBarrier post[2];
post[0] = pre[0];
post[0].srcAccessMask = 0x00000800u;
post[0].dstAccessMask = 0x00018000u;
post[0].oldLayout = 6u;
post[0].newLayout = src_lay;
post[1] = pre[1];
post[1].srcAccessMask = 0x00001000u;
post[1].dstAccessMask = 0x00018000u;
post[1].oldLayout = 7u;
post[1].newLayout = dst_lay;
c->CmdPipelineBarrier(cb, 0x00001000u /* TRANSFER */, 0x00010000u /* ALL_COMMANDS */, 0, 0, NULL, 0, NULL, 2, post);
return 1;
}
static int wl_seam_dispatch_or_blit(WlSeamClient *c, VkCommandBuffer cb, const WlFsr4FrameDesc *f) {
if (wl_seam_dispatch(c, cb, f)) return 1;
return wl_seam_fallback_blit(c, cb, f);
}
static int wl_seam_parse_backend_env(void) {
static const char *const names[] = {
"DROIDDECK_UPSCALE_BACKEND", "DROIDDECK_UPSCALE_ENGINE",
"WINLATOR_FSR4_BACKEND", "WINLATOR_FSR4_ENGINE", NULL,
};
char buf[64];
if (dd_env_first(names, buf, sizeof buf)) {
if (_stricmp(buf, "fsr3_gpu") == 0 || _stricmp(buf, "fsr3") == 0) return WL_FSR_BACKEND_FSR3_GPU;
if (_stricmp(buf, "xess3_gpu") == 0 || _stricmp(buf, "xess3") == 0 || _stricmp(buf, "xess") == 0) return WL_FSR_BACKEND_XESS3_GPU;
if (_stricmp(buf, "fsr4_1_lite_npu") == 0 || _stricmp(buf, "fsr412_lite_npu") == 0) return WL_FSR_BACKEND_FSR4_1_LITE_NPU;
if (_stricmp(buf, "fsr4_1_full_npu") == 0 || _stricmp(buf, "fsr411_full_npu") == 0) return WL_FSR_BACKEND_FSR4_1_FULL_NPU;
if (_stricmp(buf, "fsr4_1_lite_gpu") == 0 || _stricmp(buf, "fsr412_lite_gpu") == 0) return WL_FSR_BACKEND_FSR4_1_LITE_GPU;
if (_stricmp(buf, "fsr4_1_full_gpu") == 0 || _stricmp(buf, "fsr411_full_gpu") == 0) return WL_FSR_BACKEND_FSR4_1_FULL_GPU;
if (_stricmp(buf, "fsr4_0_npu") == 0 || _stricmp(buf, "fsr4_npu") == 0 || _stricmp(buf, "fsr4") == 0) return WL_FSR_BACKEND_FSR4_0_NPU;
}
return WL_FSR_BACKEND_FSR4_0_NPU;
}
static int wl_seam_live_backend(const WlSeamClient *c, int *out_enabled) {
if (out_enabled) *out_enabled = 1;
if (c && c->ready && c->mbox) {
uint64_t ctrl = c->mbox->live_ctrl;
if (ctrl != 0ULL) {
if (out_enabled) *out_enabled = (ctrl & WLFSR4_CTRL_ENABLED_BIT) ? 1 : 0;
return (int)(ctrl & WLFSR4_CTRL_BACKEND_MASK);
}
}
return wl_seam_parse_backend_env();
}
static void wl_seam_telemetry_begin(WlSeamClient *c, VkCommandBuffer cb) {
if (!c || !c->ready || !cb || !c->CmdUpdateBuffer) return;
WlFsr4DoorbellPayload pay;
pay.magic = WLFSR4_TELEMETRY_MAGIC;
pay.seq = 0u;
c->CmdUpdateBuffer(cb, c->marker_buf, 0, sizeof pay, &pay);
}
static void wl_seam_telemetry_end(WlSeamClient *c, VkCommandBuffer cb, const WlFsr4FrameDesc *in_frame, uint32_t cpu_us) {
if (!c || !c->ready || !cb || !in_frame || !c->mbox || !c->CmdUpdateBuffer) return;
uint64_t seq = c->next_seq++;
if (seq == 0u) seq = c->next_seq++;
WlFsr4FrameDesc *slot = &c->mbox->slots[seq % WLFSR4_SLOTS];
*slot = *in_frame;
slot->seq = seq;
c->mbox->tele_gpu_us = cpu_us;
MemoryBarrier();
WlFsr4DoorbellPayload pay;
pay.magic = WLFSR4_TELEMETRY_MAGIC;
pay.seq = seq;
c->CmdUpdateBuffer(cb, c->marker_buf, 0, sizeof pay, &pay);
MemoryBarrier();
}
+60
View File
@@ -0,0 +1,60 @@
// Exact vkd3d-proton ID3D12DXVKInteropDevice / ID3D12DXVKInteropDevice1 C COM vtable
// Verified against HansKristian-Work/vkd3d-proton include/vkd3d_device_vkd3d_ext.idl.
#pragma once
#include <windows.h>
#include <stdint.h>
// {39da4e09-bd1c-4198-9fae-86bbe3be41fd}
static const GUID WL_IID_ID3D12DXVKInteropDevice = {
0x39da4e09, 0xbd1c, 0x4198, {0x9f, 0xae, 0x86, 0xbb, 0xe3, 0xbe, 0x41, 0xfd}
};
// {902d8115-59eb-4406-9518-fe00f991ee65}
static const GUID WL_IID_ID3D12DXVKInteropDevice1 = {
0x902d8115, 0x59eb, 0x4406, {0x95, 0x18, 0xfe, 0x00, 0xf9, 0x91, 0xee, 0x65}
};
typedef struct WlID3D12DXVKInteropDevice1 WlID3D12DXVKInteropDevice1;
typedef struct WlID3D12DXVKInteropDevice1Vtbl {
// IUnknown
HRESULT (__stdcall *QueryInterface)(WlID3D12DXVKInteropDevice1 *This, const GUID *riid, void **ppv);
ULONG (__stdcall *AddRef)(WlID3D12DXVKInteropDevice1 *This);
ULONG (__stdcall *Release)(WlID3D12DXVKInteropDevice1 *This);
// ID3D12DXVKInteropDevice
HRESULT (__stdcall *GetDXGIAdapter)(WlID3D12DXVKInteropDevice1 *This, const GUID *iid, void **object);
HRESULT (__stdcall *GetInstanceExtensions)(WlID3D12DXVKInteropDevice1 *This, UINT *count, const char **exts);
HRESULT (__stdcall *GetDeviceExtensions)(WlID3D12DXVKInteropDevice1 *This, UINT *count, const char **exts);
HRESULT (__stdcall *GetDeviceFeatures)(WlID3D12DXVKInteropDevice1 *This, const void **features);
HRESULT (__stdcall *GetVulkanHandles)(WlID3D12DXVKInteropDevice1 *This, void **vk_inst, void **vk_phys, void **vk_dev);
HRESULT (__stdcall *GetVulkanQueueInfo)(WlID3D12DXVKInteropDevice1 *This, void *queue, void **vk_queue, UINT32 *vk_qf);
void (__stdcall *GetVulkanImageLayout)(WlID3D12DXVKInteropDevice1 *This, void *resource, UINT32 d3d12_state, UINT32 *vk_layout);
HRESULT (__stdcall *GetVulkanResourceInfo)(WlID3D12DXVKInteropDevice1 *This, void *resource, UINT64 *vk_handle, UINT64 *buf_offset);
HRESULT (__stdcall *LockCommandQueue)(WlID3D12DXVKInteropDevice1 *This, void *queue);
HRESULT (__stdcall *UnlockCommandQueue)(WlID3D12DXVKInteropDevice1 *This, void *queue);
// ID3D12DXVKInteropDevice1
HRESULT (__stdcall *GetVulkanResourceInfo1)(WlID3D12DXVKInteropDevice1 *This, void *resource, UINT64 *vk_handle, UINT64 *buf_offset, UINT32 *vk_format);
HRESULT (__stdcall *CreateInteropCommandQueue)(WlID3D12DXVKInteropDevice1 *This, const void *desc, UINT32 qf, void **ppQueue);
HRESULT (__stdcall *CreateInteropCommandAllocator)(WlID3D12DXVKInteropDevice1 *This, UINT32 type, UINT32 qf, void **ppAlloc);
HRESULT (__stdcall *BeginVkCommandBufferInterop)(WlID3D12DXVKInteropDevice1 *This, void *cmdList, void **pVkCmdBuf);
HRESULT (__stdcall *EndVkCommandBufferInterop)(WlID3D12DXVKInteropDevice1 *This, void *cmdList);
} WlID3D12DXVKInteropDevice1Vtbl;
struct WlID3D12DXVKInteropDevice1 {
const WlID3D12DXVKInteropDevice1Vtbl *lpVtbl;
};
static inline WlID3D12DXVKInteropDevice1 *wl_query_vkd3d_interop(void *d3d12_device) {
if (!d3d12_device) return NULL;
typedef struct {
HRESULT (__stdcall *QueryInterface)(void *This, const GUID *riid, void **ppv);
} IUnkVtbl;
typedef struct { const IUnkVtbl *lpVtbl; } IUnkObj;
IUnkObj *obj = (IUnkObj *)d3d12_device;
WlID3D12DXVKInteropDevice1 *out = NULL;
if (obj->lpVtbl && obj->lpVtbl->QueryInterface(d3d12_device, &WL_IID_ID3D12DXVKInteropDevice1, (void **)&out) == S_OK && out) {
return out;
}
return NULL;
}
+484
View File
@@ -0,0 +1,484 @@
// Winlator Ludashi Direct Intel XeSS 3.0 DP4a Execution Helper (Vulkan + DX12)
//
// Dynamically loads Intel's official XeSS 3.0 SDK runtime (wl_xess_official.dll) and
// executes genuine XeSS 3.0 DP4a upscaling on Adreno 840 when the user selects
// "XeSS 3.0 DP4a (GPU)" in Winlator settings or the in-game live sidebar.
//
// On ANY initialization or execution failure (driver mismatch, missing extension, OOM),
// cleanly destroys the XeSS context and returns 0 so the caller falls back seamlessly
// to Winlator's FSR 3.1 GPU upscaler — never crashing or showing a black screen.
#pragma once
#include <windows.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "wl_seam_client.h"
#include "wl_vkd3d_interop.h"
#pragma pack(push, 8)
typedef struct _wl_xess_ctx_t *wl_xess_ctx_t;
typedef struct { uint32_t x; uint32_t y; } wl_xess_2d_t;
typedef wl_xess_2d_t wl_xess_coord_t;
typedef struct {
uint32_t aspectMask;
uint32_t baseMipLevel;
uint32_t levelCount;
uint32_t baseArrayLayer;
uint32_t layerCount;
} wl_xess_vk_subres_t;
typedef struct {
VkImageView imageView;
VkImage image;
wl_xess_vk_subres_t subresourceRange;
uint32_t format;
unsigned int width;
unsigned int height;
} wl_xess_vk_img_t;
typedef struct {
wl_xess_vk_img_t colorTexture;
wl_xess_vk_img_t velocityTexture;
wl_xess_vk_img_t depthTexture;
wl_xess_vk_img_t exposureScaleTexture;
wl_xess_vk_img_t responsivePixelMaskTexture;
wl_xess_vk_img_t outputTexture;
float jitterOffsetX;
float jitterOffsetY;
float exposureScale;
uint32_t resetHistory;
uint32_t inputWidth;
uint32_t inputHeight;
wl_xess_coord_t inputColorBase;
wl_xess_coord_t inputMotionVectorBase;
wl_xess_coord_t inputDepthBase;
wl_xess_coord_t inputResponsiveMaskBase;
wl_xess_coord_t reserved0;
wl_xess_coord_t outputColorBase;
} wl_xess_vk_exec_t;
typedef struct {
wl_xess_2d_t outputResolution;
uint32_t qualitySetting;
uint32_t initFlags;
uint32_t creationNodeMask;
uint32_t visibleNodeMask;
VkDeviceMemory tempBufferHeap;
uint64_t bufferHeapOffset;
VkDeviceMemory tempTextureHeap;
uint64_t textureHeapOffset;
uint64_t pipelineCache;
} wl_xess_vk_init_t;
typedef struct {
void *pColorTexture;
void *pVelocityTexture;
void *pDepthTexture;
void *pExposureScaleTexture;
void *pResponsivePixelMaskTexture;
void *pOutputTexture;
float jitterOffsetX;
float jitterOffsetY;
float exposureScale;
uint32_t resetHistory;
uint32_t inputWidth;
uint32_t inputHeight;
wl_xess_coord_t inputColorBase;
wl_xess_coord_t inputMotionVectorBase;
wl_xess_coord_t inputDepthBase;
wl_xess_coord_t inputResponsiveMaskBase;
wl_xess_coord_t reserved0;
wl_xess_coord_t outputColorBase;
void *pDescriptorHeap;
uint32_t descriptorHeapOffset;
} wl_xess_d3d12_exec_t;
typedef struct {
wl_xess_2d_t outputResolution;
uint32_t qualitySetting;
uint32_t initFlags;
uint32_t creationNodeMask;
uint32_t visibleNodeMask;
void *pTempBufferHeap;
uint64_t bufferHeapOffset;
void *pTempTextureHeap;
uint64_t textureHeapOffset;
void *pPipelineLibrary;
} wl_xess_d3d12_init_t;
#pragma pack(pop)
_Static_assert(sizeof(wl_xess_vk_img_t) == 48, "wl_xess_vk_img_t ABI mismatch");
_Static_assert(sizeof(wl_xess_vk_init_t) == 64, "wl_xess_vk_init_t ABI mismatch");
_Static_assert(sizeof(wl_xess_d3d12_init_t) == 64, "wl_xess_d3d12_init_t ABI mismatch");
typedef int32_t (__cdecl *PFN_xessVKCreateContext)(VkInstance, VkPhysicalDevice, VkDevice, wl_xess_ctx_t *);
typedef int32_t (__cdecl *PFN_xessVKInit)(wl_xess_ctx_t, const wl_xess_vk_init_t *);
typedef int32_t (__cdecl *PFN_xessVKExecute)(wl_xess_ctx_t, VkCommandBuffer, const wl_xess_vk_exec_t *);
typedef int32_t (__cdecl *PFN_xessD3D12CreateContext)(void *, wl_xess_ctx_t *);
typedef int32_t (__cdecl *PFN_xessD3D12Init)(wl_xess_ctx_t, const wl_xess_d3d12_init_t *);
typedef int32_t (__cdecl *PFN_xessD3D12Execute)(wl_xess_ctx_t, void *, const wl_xess_d3d12_exec_t *);
typedef int32_t (__cdecl *PFN_xessSetVelocityScale)(wl_xess_ctx_t, float, float);
typedef int32_t (__cdecl *PFN_xessSetJitterScale)(wl_xess_ctx_t, float, float);
typedef int32_t (__cdecl *PFN_xessDestroyContext)(wl_xess_ctx_t);
typedef struct WlXess3Api {
int loaded;
int available;
DWORD load_err;
HMODULE mod;
PFN_xessVKCreateContext VKCreateContext;
PFN_xessVKInit VKInit;
PFN_xessVKExecute VKExecute;
PFN_xessD3D12CreateContext D3D12CreateContext;
PFN_xessD3D12Init D3D12Init;
PFN_xessD3D12Execute D3D12Execute;
PFN_xessSetVelocityScale SetVelocityScale;
PFN_xessSetJitterScale SetJitterScale;
PFN_xessDestroyContext DestroyContext;
} WlXess3Api;
static WlXess3Api g_wl_xess3_api;
static int wl_xess3_load_api(void) {
if (g_wl_xess3_api.loaded) return g_wl_xess3_api.available;
g_wl_xess3_api.loaded = 1;
SetLastError(0);
HMODULE m = LoadLibraryA("wl_xess_official.dll");
if (!m) m = LoadLibraryA("C:\\windows\\system32\\wl_xess_official.dll");
if (!m) {
g_wl_xess3_api.load_err = GetLastError();
return 0;
}
g_wl_xess3_api.mod = m;
g_wl_xess3_api.VKCreateContext = (PFN_xessVKCreateContext)(void *)GetProcAddress(m, "xessVKCreateContext");
g_wl_xess3_api.VKInit = (PFN_xessVKInit)(void *)GetProcAddress(m, "xessVKInit");
g_wl_xess3_api.VKExecute = (PFN_xessVKExecute)(void *)GetProcAddress(m, "xessVKExecute");
g_wl_xess3_api.D3D12CreateContext = (PFN_xessD3D12CreateContext)(void *)GetProcAddress(m, "xessD3D12CreateContext");
g_wl_xess3_api.D3D12Init = (PFN_xessD3D12Init)(void *)GetProcAddress(m, "xessD3D12Init");
g_wl_xess3_api.D3D12Execute = (PFN_xessD3D12Execute)(void *)GetProcAddress(m, "xessD3D12Execute");
g_wl_xess3_api.SetVelocityScale = (PFN_xessSetVelocityScale)(void *)GetProcAddress(m, "xessSetVelocityScale");
g_wl_xess3_api.SetJitterScale = (PFN_xessSetJitterScale)(void *)GetProcAddress(m, "xessSetJitterScale");
g_wl_xess3_api.DestroyContext = (PFN_xessDestroyContext)(void *)GetProcAddress(m, "xessDestroyContext");
if ((g_wl_xess3_api.VKCreateContext && g_wl_xess3_api.VKInit && g_wl_xess3_api.VKExecute) ||
(g_wl_xess3_api.D3D12CreateContext && g_wl_xess3_api.D3D12Init && g_wl_xess3_api.D3D12Execute)) {
g_wl_xess3_api.available = 1;
}
return g_wl_xess3_api.available;
}
typedef struct WlXess3State {
wl_xess_ctx_t ctx;
int is_vk;
int initialized;
int failed;
uint32_t fail_stage; /* 1=load_dll, 2=proc, 3=create_ctx, 4=init, 5=exec, 6=missing_handles */
int32_t fail_rc;
uint32_t out_w, out_h;
uint32_t quality;
uint32_t init_flags;
float last_mv_sx, last_mv_sy;
} WlXess3State;
static void wl_xess3_destroy(WlXess3State *st) {
if (!st) return;
if (st->ctx && g_wl_xess3_api.DestroyContext) {
g_wl_xess3_api.DestroyContext(st->ctx);
}
memset(st, 0, sizeof *st);
}
static void wl_xess3_mark_fail(WlXess3State *st, uint32_t stage, int32_t rc) {
if (!st) return;
st->failed = 1;
st->fail_stage = stage;
st->fail_rc = rc;
}
static void wl_xess3_tag_fallback(const WlXess3State *st, WlFsr4FrameDesc *f) {
if (!f) return;
f->flags |= WLFSR4_FLAG_XESS_FALLBACK;
f->pad[0] = st ? st->fail_stage : 6u;
f->pad[1] = st ? (uint32_t)st->fail_rc : 0u;
}
static void wl_xess3_on_inactive(WlXess3State *st) {
if (!st) return;
// Allow clean retry when user toggles away from XeSS 3 and back
st->failed = 0;
}
static uint32_t wl_xess3_map_quality(uint32_t wl_q) {
switch (wl_q) {
case WLFSR4_QUALITY_ULTRA_PERF: return 100u; /* XESS_QUALITY_SETTING_ULTRA_PERFORMANCE */
case WLFSR4_QUALITY_PERF: return 101u; /* XESS_QUALITY_SETTING_PERFORMANCE */
case WLFSR4_QUALITY_BALANCED: return 102u; /* XESS_QUALITY_SETTING_BALANCED */
case WLFSR4_QUALITY_QUALITY: return 103u; /* XESS_QUALITY_SETTING_QUALITY */
case WLFSR4_QUALITY_ULTRA_QUAL: return 104u; /* XESS_QUALITY_SETTING_ULTRA_QUALITY */
case WLFSR4_QUALITY_NATIVE_AA: return 106u; /* XESS_QUALITY_SETTING_AA */
default: return 103u;
}
}
static uint32_t wl_xess3_map_init_flags(uint32_t wl_flags) {
uint32_t xf = 0u;
if (wl_flags & WLFSR4_FLAG_DISPLAY_RES_MV) xf |= (1u << 0); /* HIGH_RES_MV */
if (wl_flags & WLFSR4_FLAG_DEPTH_INVERTED) xf |= (1u << 1); /* INVERTED_DEPTH */
if (!(wl_flags & WLFSR4_FLAG_HDR)) xf |= (1u << 6); /* LDR_INPUT_COLOR */
if (wl_flags & WLFSR4_FLAG_MV_JITTERED) xf |= (1u << 7); /* JITTERED_MV */
if (wl_flags & WLFSR4_FLAG_AUTO_EXPOSURE) xf |= (1u << 8); /* ENABLE_AUTOEXPOSURE */
return xf;
}
static void wl_xess3_vk_barrier(WlSeamClient *seam, VkCommandBuffer cb,
VkImage img, uint32_t aspect,
uint32_t old_lay, uint32_t new_lay) {
if (!seam || !seam->CmdPipelineBarrier || !img || old_lay == new_lay) return;
WlVkImageMemoryBarrier b;
memset(&b, 0, sizeof b);
b.sType = 45u; /* VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER */
b.srcAccessMask = 0x00018000u; /* MEMORY_READ | MEMORY_WRITE */
b.dstAccessMask = 0x00018000u;
b.oldLayout = old_lay;
b.newLayout = new_lay;
b.srcQueueFamilyIndex = 0xFFFFFFFFu;
b.dstQueueFamilyIndex = 0xFFFFFFFFu;
b.image = img;
b.subresourceRange.aspectMask = aspect ? aspect : 1u;
b.subresourceRange.levelCount = 1u;
b.subresourceRange.layerCount = 1u;
seam->CmdPipelineBarrier(cb, 0x00010000u, 0x00010000u, 0, 0, NULL, 0, NULL, 1, &b);
}
static int wl_xess3_eval_vk(WlXess3State *st, WlSeamClient *seam,
VkCommandBuffer cb, const WlFsr4FrameDesc *f,
const wl_xess_vk_img_t *col,
const wl_xess_vk_img_t *dep,
const wl_xess_vk_img_t *mv,
const wl_xess_vk_img_t *out) {
if (!st || st->failed || !seam || !seam->ready || !cb || !f || !col || !mv || !out) {
if (st && !st->failed) wl_xess3_mark_fail(st, 6u, 1);
return 0;
}
if (!col->image || !col->imageView || !mv->image || !mv->imageView || !out->image || !out->imageView) {
wl_xess3_mark_fail(st, 6u, 2);
return 0;
}
if (!wl_xess3_load_api()) {
wl_xess3_mark_fail(st, 1u, (int32_t)g_wl_xess3_api.load_err);
return 0;
}
if (!g_wl_xess3_api.VKCreateContext || !g_wl_xess3_api.VKInit || !g_wl_xess3_api.VKExecute) {
wl_xess3_mark_fail(st, 2u, 1);
return 0;
}
uint32_t quality = wl_xess3_map_quality(f->quality_mode);
uint32_t init_flags = wl_xess3_map_init_flags(f->flags);
if (!dep || !dep->image || !dep->imageView) init_flags |= (1u << 0); /* HIGH_RES_MV if no depth */
if (!st->ctx) {
if (!seam->inst || !seam->phys || !seam->dev) {
wl_xess3_mark_fail(st, 6u, 3);
return 0;
}
int32_t rc = g_wl_xess3_api.VKCreateContext(seam->inst, seam->phys, seam->dev, &st->ctx);
if (rc < 0 || !st->ctx) {
wl_xess3_mark_fail(st, 3u, rc);
return 0;
}
st->is_vk = 1;
}
if (!st->initialized || st->out_w != f->output_w || st->out_h != f->output_h ||
st->quality != quality || st->init_flags != init_flags) {
wl_xess_vk_init_t ip;
memset(&ip, 0, sizeof ip);
ip.outputResolution.x = f->output_w;
ip.outputResolution.y = f->output_h;
ip.qualitySetting = quality;
ip.initFlags = init_flags;
ip.creationNodeMask = 1u;
ip.visibleNodeMask = 1u;
int32_t rc = g_wl_xess3_api.VKInit(st->ctx, &ip);
if (rc < 0) {
wl_xess3_destroy(st);
wl_xess3_mark_fail(st, 4u, rc);
return 0;
}
st->initialized = 1;
st->out_w = f->output_w;
st->out_h = f->output_h;
st->quality = quality;
st->init_flags = init_flags;
st->last_mv_sx = 1e9f;
st->last_mv_sy = 1e9f;
}
if (g_wl_xess3_api.SetVelocityScale && (st->last_mv_sx != f->mv_scale_x || st->last_mv_sy != f->mv_scale_y)) {
g_wl_xess3_api.SetVelocityScale(st->ctx, f->mv_scale_x, f->mv_scale_y);
st->last_mv_sx = f->mv_scale_x;
st->last_mv_sy = f->mv_scale_y;
}
// Ensure XeSS VK layout contract: inputs = SHADER_READ_ONLY_OPTIMAL (5), output = GENERAL (1)
uint32_t col_lay = f->color.vk_layout ? f->color.vk_layout : 5u;
uint32_t dep_lay = f->depth.vk_layout ? f->depth.vk_layout : 5u;
uint32_t mv_lay = f->motion.vk_layout ? f->motion.vk_layout : 5u;
uint32_t out_lay = f->output.vk_layout ? f->output.vk_layout : 1u;
wl_xess3_vk_barrier(seam, cb, col->image, 1u, col_lay, 5u);
if (dep && dep->image) wl_xess3_vk_barrier(seam, cb, dep->image, dep->subresourceRange.aspectMask ? dep->subresourceRange.aspectMask : 2u, dep_lay, 5u);
wl_xess3_vk_barrier(seam, cb, mv->image, 1u, mv_lay, 5u);
wl_xess3_vk_barrier(seam, cb, out->image, 1u, out_lay, 1u);
wl_xess_vk_exec_t ep;
memset(&ep, 0, sizeof ep);
ep.colorTexture = *col;
ep.velocityTexture = *mv;
if (dep && dep->image && dep->imageView) ep.depthTexture = *dep;
ep.outputTexture = *out;
ep.jitterOffsetX = f->jitter_x;
ep.jitterOffsetY = f->jitter_y;
ep.exposureScale = (f->pre_exposure > 0.0f) ? f->pre_exposure : 1.0f;
ep.resetHistory = (f->flags & WLFSR4_FLAG_RESET) ? 1u : 0u;
ep.inputWidth = f->render_w;
ep.inputHeight = f->render_h;
LARGE_INTEGER t0, t1, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&t0);
wl_seam_telemetry_begin(seam, cb);
int32_t rc = g_wl_xess3_api.VKExecute(st->ctx, cb, &ep);
// Restore caller layouts
wl_xess3_vk_barrier(seam, cb, col->image, 1u, 5u, col_lay);
if (dep && dep->image) wl_xess3_vk_barrier(seam, cb, dep->image, dep->subresourceRange.aspectMask ? dep->subresourceRange.aspectMask : 2u, 5u, dep_lay);
wl_xess3_vk_barrier(seam, cb, mv->image, 1u, 5u, mv_lay);
wl_xess3_vk_barrier(seam, cb, out->image, 1u, 1u, out_lay);
QueryPerformanceCounter(&t1);
uint32_t cpu_us = (freq.QuadPart > 0) ? (uint32_t)(((t1.QuadPart - t0.QuadPart) * 1000000ULL) / (uint64_t)freq.QuadPart) : 0u;
if (rc < 0) {
wl_xess3_destroy(st);
wl_xess3_mark_fail(st, 5u, rc);
return 0;
}
wl_seam_telemetry_end(seam, cb, f, cpu_us);
return 1;
}
static int wl_xess3_eval_d3d12(WlXess3State *st, WlSeamClient *seam,
WlID3D12DXVKInteropDevice1 *interop,
void *d3d12_dev, void *d3d12_cmdlist,
const WlFsr4FrameDesc *f,
void *res_col, void *res_dep,
void *res_mv, void *res_out) {
if (!st || st->failed || !d3d12_dev || !d3d12_cmdlist || !f || !res_col || !res_mv || !res_out) {
if (st && !st->failed) wl_xess3_mark_fail(st, 6u, 4);
return 0;
}
if (!wl_xess3_load_api()) {
wl_xess3_mark_fail(st, 1u, (int32_t)g_wl_xess3_api.load_err);
return 0;
}
if (!g_wl_xess3_api.D3D12CreateContext || !g_wl_xess3_api.D3D12Init || !g_wl_xess3_api.D3D12Execute) {
wl_xess3_mark_fail(st, 2u, 2);
return 0;
}
uint32_t quality = wl_xess3_map_quality(f->quality_mode);
uint32_t init_flags = wl_xess3_map_init_flags(f->flags);
if (!res_dep) init_flags |= (1u << 0); /* HIGH_RES_MV if no depth */
if (!st->ctx) {
int32_t rc = g_wl_xess3_api.D3D12CreateContext(d3d12_dev, &st->ctx);
if (rc < 0 || !st->ctx) {
wl_xess3_mark_fail(st, 3u, rc);
return 0;
}
st->is_vk = 0;
}
if (!st->initialized || st->out_w != f->output_w || st->out_h != f->output_h ||
st->quality != quality || st->init_flags != init_flags) {
wl_xess_d3d12_init_t ip;
memset(&ip, 0, sizeof ip);
ip.outputResolution.x = f->output_w;
ip.outputResolution.y = f->output_h;
ip.qualitySetting = quality;
ip.initFlags = init_flags;
ip.creationNodeMask = 1u;
ip.visibleNodeMask = 1u;
int32_t rc = g_wl_xess3_api.D3D12Init(st->ctx, &ip);
if (rc < 0) {
wl_xess3_destroy(st);
wl_xess3_mark_fail(st, 4u, rc);
return 0;
}
st->initialized = 1;
st->out_w = f->output_w;
st->out_h = f->output_h;
st->quality = quality;
st->init_flags = init_flags;
st->last_mv_sx = 1e9f;
st->last_mv_sy = 1e9f;
}
if (g_wl_xess3_api.SetVelocityScale && (st->last_mv_sx != f->mv_scale_x || st->last_mv_sy != f->mv_scale_y)) {
g_wl_xess3_api.SetVelocityScale(st->ctx, f->mv_scale_x, f->mv_scale_y);
st->last_mv_sx = f->mv_scale_x;
st->last_mv_sy = f->mv_scale_y;
}
wl_xess_d3d12_exec_t ep;
memset(&ep, 0, sizeof ep);
ep.pColorTexture = res_col;
ep.pVelocityTexture = res_mv;
ep.pDepthTexture = res_dep;
ep.pOutputTexture = res_out;
ep.jitterOffsetX = f->jitter_x;
ep.jitterOffsetY = f->jitter_y;
ep.exposureScale = (f->pre_exposure > 0.0f) ? f->pre_exposure : 1.0f;
ep.resetHistory = (f->flags & WLFSR4_FLAG_RESET) ? 1u : 0u;
ep.inputWidth = f->render_w;
ep.inputHeight = f->render_h;
// Bracket with Vulkan timestamp telemetry if interop is available
if (seam && seam->ready && interop) {
void *vk_cb = NULL;
if (interop->lpVtbl->BeginVkCommandBufferInterop(interop, d3d12_cmdlist, &vk_cb) == S_OK && vk_cb) {
wl_seam_telemetry_begin(seam, (VkCommandBuffer)vk_cb);
interop->lpVtbl->EndVkCommandBufferInterop(interop, d3d12_cmdlist);
}
}
LARGE_INTEGER t0, t1, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&t0);
int32_t rc = g_wl_xess3_api.D3D12Execute(st->ctx, d3d12_cmdlist, &ep);
QueryPerformanceCounter(&t1);
uint32_t cpu_us = (freq.QuadPart > 0) ? (uint32_t)(((t1.QuadPart - t0.QuadPart) * 1000000ULL) / (uint64_t)freq.QuadPart) : 0u;
if (rc < 0) {
wl_xess3_destroy(st);
wl_xess3_mark_fail(st, 5u, rc);
return 0;
}
if (seam && seam->ready && interop) {
void *vk_cb = NULL;
if (interop->lpVtbl->BeginVkCommandBufferInterop(interop, d3d12_cmdlist, &vk_cb) == S_OK && vk_cb) {
wl_seam_telemetry_end(seam, (VkCommandBuffer)vk_cb, f, cpu_us);
interop->lpVtbl->EndVkCommandBufferInterop(interop, d3d12_cmdlist);
}
}
return 1;
}
+824
View File
@@ -0,0 +1,824 @@
// Winlator Ludashi Intel XeSS (libxess.dll) -> AMD FSR 4 INT8 Hexagon HTP NPU Bridge
//
// Implements the full Intel XeSS 1.3 / 2.0 C ABI for BOTH:
// - DirectX 12 (via vkd3d-proton ID3D12DXVKInteropDevice1 zero-copy interop)
// - Vulkan (direct VkImage / VkCommandBuffer)
//
// Requires ZERO GPU spoofing and ZERO driver signature checks — works cleanly on
// Adreno / Turnip in No-GPU-Spoof mode as well as RTX/RDNA4 spoof modes.
#include <windows.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "wl_seam_client.h"
#include "wl_vkd3d_interop.h"
#include "wl_xess3_direct.h"
// ---- Official Intel XeSS C ABI (verified from intel/xess xess.h, xess_d3d12.h, xess_vk.h) ----
#pragma pack(push, 8)
typedef struct _xess_context_handle_t *xess_context_handle_t;
typedef struct _xess_version_t {
uint16_t major;
uint16_t minor;
uint16_t patch;
uint16_t reserved;
} xess_version_t;
typedef struct _xess_2d_t {
uint32_t x;
uint32_t y;
} xess_2d_t;
typedef xess_2d_t xess_coord_t;
typedef enum _xess_quality_settings_t {
XESS_QUALITY_SETTING_ULTRA_PERFORMANCE = 100,
XESS_QUALITY_SETTING_PERFORMANCE = 101,
XESS_QUALITY_SETTING_BALANCED = 102,
XESS_QUALITY_SETTING_QUALITY = 103,
XESS_QUALITY_SETTING_ULTRA_QUALITY = 104,
XESS_QUALITY_SETTING_ULTRA_QUALITY_PLUS = 105,
XESS_QUALITY_SETTING_AA = 106,
} xess_quality_settings_t;
typedef enum _xess_init_flags_t {
XESS_INIT_FLAG_NONE = 0,
XESS_INIT_FLAG_HIGH_RES_MV = 1 << 0,
XESS_INIT_FLAG_INVERTED_DEPTH = 1 << 1,
XESS_INIT_FLAG_EXPOSURE_SCALE_TEXTURE = 1 << 2,
XESS_INIT_FLAG_RESPONSIVE_PIXEL_MASK = 1 << 3,
XESS_INIT_FLAG_USE_NDC_VELOCITY = 1 << 4,
XESS_INIT_FLAG_EXTERNAL_DESCRIPTOR_HEAP = 1 << 5,
XESS_INIT_FLAG_LDR_INPUT_COLOR = 1 << 6,
XESS_INIT_FLAG_JITTERED_MV = 1 << 7,
XESS_INIT_FLAG_ENABLE_AUTOEXPOSURE = 1 << 8,
} xess_init_flags_t;
typedef struct _xess_properties_t {
uint32_t requiredDescriptorCount;
uint64_t tempBufferHeapSize;
uint64_t tempTextureHeapSize;
} xess_properties_t;
typedef enum _xess_result_t {
XESS_RESULT_WARNING_NONEXISTING_FOLDER = 1,
XESS_RESULT_WARNING_OLD_DRIVER = 2,
XESS_RESULT_SUCCESS = 0,
XESS_RESULT_ERROR_UNSUPPORTED_DEVICE = -1,
XESS_RESULT_ERROR_UNSUPPORTED_DRIVER = -2,
XESS_RESULT_ERROR_UNINITIALIZED = -3,
XESS_RESULT_ERROR_INVALID_ARGUMENT = -4,
XESS_RESULT_ERROR_DEVICE_OUT_OF_MEMORY = -5,
XESS_RESULT_ERROR_DEVICE = -6,
XESS_RESULT_ERROR_NOT_IMPLEMENTED = -7,
XESS_RESULT_ERROR_INVALID_CONTEXT = -8,
XESS_RESULT_ERROR_OPERATION_IN_PROGRESS = -9,
XESS_RESULT_ERROR_UNSUPPORTED = -10,
XESS_RESULT_ERROR_CANT_LOAD_LIBRARY = -11,
XESS_RESULT_ERROR_WRONG_CALL_ORDER = -12,
XESS_RESULT_ERROR_UNKNOWN = -1000,
} xess_result_t;
typedef enum _xess_logging_level_t {
XESS_LOGGING_LEVEL_DEBUG = 0,
XESS_LOGGING_LEVEL_INFO = 1,
XESS_LOGGING_LEVEL_WARNING = 2,
XESS_LOGGING_LEVEL_ERROR = 3,
} xess_logging_level_t;
typedef void (*xess_app_log_callback_t)(const char *message, xess_logging_level_t loggingLevel);
typedef struct _xess_d3d12_execute_params_t {
void *pColorTexture;
void *pVelocityTexture;
void *pDepthTexture;
void *pExposureScaleTexture;
void *pResponsivePixelMaskTexture;
void *pOutputTexture;
float jitterOffsetX;
float jitterOffsetY;
float exposureScale;
uint32_t resetHistory;
uint32_t inputWidth;
uint32_t inputHeight;
xess_coord_t inputColorBase;
xess_coord_t inputMotionVectorBase;
xess_coord_t inputDepthBase;
xess_coord_t inputResponsiveMaskBase;
xess_coord_t reserved0;
xess_coord_t outputColorBase;
void *pDescriptorHeap;
uint32_t descriptorHeapOffset;
} xess_d3d12_execute_params_t;
typedef struct _xess_d3d12_init_params_t {
xess_2d_t outputResolution;
xess_quality_settings_t qualitySetting;
uint32_t initFlags;
uint32_t creationNodeMask;
uint32_t visibleNodeMask;
void *pTempBufferHeap;
uint64_t bufferHeapOffset;
void *pTempTextureHeap;
uint64_t textureHeapOffset;
void *pPipelineLibrary;
} xess_d3d12_init_params_t;
typedef struct _wl_vk_subresource_range {
uint32_t aspectMask;
uint32_t baseMipLevel;
uint32_t levelCount;
uint32_t baseArrayLayer;
uint32_t layerCount;
} WlVkSubresourceRange;
typedef struct _xess_vk_image_view_info {
VkImageView imageView;
VkImage image;
WlVkSubresourceRange subresourceRange;
uint32_t format;
unsigned int width;
unsigned int height;
} xess_vk_image_view_info;
typedef struct _xess_vk_execute_params_t {
xess_vk_image_view_info colorTexture;
xess_vk_image_view_info velocityTexture;
xess_vk_image_view_info depthTexture;
xess_vk_image_view_info exposureScaleTexture;
xess_vk_image_view_info responsivePixelMaskTexture;
xess_vk_image_view_info outputTexture;
float jitterOffsetX;
float jitterOffsetY;
float exposureScale;
uint32_t resetHistory;
uint32_t inputWidth;
uint32_t inputHeight;
xess_coord_t inputColorBase;
xess_coord_t inputMotionVectorBase;
xess_coord_t inputDepthBase;
xess_coord_t inputResponsiveMaskBase;
xess_coord_t reserved0;
xess_coord_t outputColorBase;
} xess_vk_execute_params_t;
typedef struct _xess_vk_init_params_t {
xess_2d_t outputResolution;
xess_quality_settings_t qualitySetting;
uint32_t initFlags;
uint32_t creationNodeMask;
uint32_t visibleNodeMask;
VkDeviceMemory tempBufferHeap;
uint64_t bufferHeapOffset;
VkDeviceMemory tempTextureHeap;
uint64_t textureHeapOffset;
uint64_t pipelineCache;
} xess_vk_init_params_t;
#pragma pack(pop)
// Compile-time ABI sanity checks
_Static_assert(sizeof(xess_quality_settings_t) == 4, "xess_quality_settings_t size");
_Static_assert(sizeof(xess_init_flags_t) == 4, "xess_init_flags_t size");
_Static_assert(sizeof(xess_result_t) == 4, "xess_result_t size");
_Static_assert(sizeof(xess_properties_t) == 24, "xess_properties_t size");
_Static_assert(sizeof(xess_vk_image_view_info) == 48, "xess_vk_image_view_info size");
// ---- Internal context ----
#define WL_XESS_MAGIC 0x58455353u /* "XESS" */
typedef struct WlXessCtx {
uint32_t magic;
int is_vk;
int initialized;
int pipelines_built;
int needs_reset;
int force_legacy_scales;
xess_2d_t out_res;
xess_quality_settings_t quality;
uint32_t init_flags;
xess_d3d12_init_params_t d3d12_init;
xess_vk_init_params_t vk_init;
float jitter_scale_x;
float jitter_scale_y;
float vel_scale_x;
float vel_scale_y;
float exposure_mult;
float max_responsive_mask;
WlSeamClient seam;
WlID3D12DXVKInteropDevice1 *dx12_interop;
void *d3d12_dev;
WlXess3State xess3;
} WlXessCtx;
static WlXessCtx *xess_unwrap(xess_context_handle_t h) {
if (!h) return NULL;
WlXessCtx *c = (WlXessCtx *)h;
return (c->magic == WL_XESS_MAGIC) ? c : NULL;
}
static float xess_quality_ratio(xess_quality_settings_t q, int legacy) {
(void)legacy;
switch (q) {
case XESS_QUALITY_SETTING_ULTRA_PERFORMANCE: return 3.0f;
case XESS_QUALITY_SETTING_PERFORMANCE: return 2.0f;
case XESS_QUALITY_SETTING_BALANCED: return 1.7f;
case XESS_QUALITY_SETTING_QUALITY: return 1.5f;
case XESS_QUALITY_SETTING_ULTRA_QUALITY: return 1.3f;
case XESS_QUALITY_SETTING_ULTRA_QUALITY_PLUS: return 1.3f;
case XESS_QUALITY_SETTING_AA: return 1.0f;
default: return 1.7f;
}
}
static uint32_t xess_quality_to_wl(xess_quality_settings_t q) {
switch (q) {
case XESS_QUALITY_SETTING_ULTRA_PERFORMANCE: return WLFSR4_QUALITY_ULTRA_PERF;
case XESS_QUALITY_SETTING_PERFORMANCE: return WLFSR4_QUALITY_PERF;
case XESS_QUALITY_SETTING_BALANCED: return WLFSR4_QUALITY_BALANCED;
case XESS_QUALITY_SETTING_QUALITY: return WLFSR4_QUALITY_QUALITY;
case XESS_QUALITY_SETTING_ULTRA_QUALITY:
case XESS_QUALITY_SETTING_ULTRA_QUALITY_PLUS: return WLFSR4_QUALITY_ULTRA_QUAL;
case XESS_QUALITY_SETTING_AA: return WLFSR4_QUALITY_NATIVE_AA;
default: return WLFSR4_QUALITY_AUTO;
}
}
static uint32_t xess_flags_to_wl(uint32_t xflags) {
uint32_t f = 0;
if (!(xflags & XESS_INIT_FLAG_LDR_INPUT_COLOR)) f |= WLFSR4_FLAG_HDR;
if (xflags & XESS_INIT_FLAG_INVERTED_DEPTH) f |= WLFSR4_FLAG_DEPTH_INVERTED;
if (xflags & XESS_INIT_FLAG_HIGH_RES_MV) f |= WLFSR4_FLAG_DISPLAY_RES_MV;
if (xflags & XESS_INIT_FLAG_JITTERED_MV) f |= WLFSR4_FLAG_MV_JITTERED;
if (xflags & XESS_INIT_FLAG_ENABLE_AUTOEXPOSURE) f |= WLFSR4_FLAG_AUTO_EXPOSURE;
return f;
}
static void xess_fill_dx12_ref(WlID3D12DXVKInteropDevice1 *interop, WlFsr4ImageRef *dst,
void *d3d12_res, uint32_t d3d12_state, uint32_t w, uint32_t h, int is_depth) {
memset(dst, 0, sizeof *dst);
if (!interop || !d3d12_res) return;
UINT64 vk_img = 0, off = 0;
UINT32 vk_fmt = 0;
if (interop->lpVtbl->GetVulkanResourceInfo1(interop, d3d12_res, &vk_img, &off, &vk_fmt) == S_OK && vk_img) {
UINT32 layout = (d3d12_state == 0x8u) ? 1u : (is_depth ? 4u : 5u);
if (interop->lpVtbl->GetVulkanImageLayout) {
UINT32 queried = 0;
interop->lpVtbl->GetVulkanImageLayout(interop, d3d12_res, d3d12_state, &queried);
if (queried != 0) layout = queried;
}
dst->vk_image = vk_img;
dst->vk_format = vk_fmt;
dst->vk_layout = layout;
dst->width = w;
dst->height = h;
dst->aspect = is_depth ? 2u : 1u;
}
}
static void xess_fill_vk_ref(WlFsr4ImageRef *dst, const xess_vk_image_view_info *src,
uint32_t layout, uint32_t fallback_w, uint32_t fallback_h, int is_depth) {
memset(dst, 0, sizeof *dst);
if (!src || !src->image) return;
dst->vk_image = src->image;
dst->vk_view = src->imageView;
dst->vk_format = src->format;
dst->vk_layout = layout;
dst->width = src->width ? src->width : fallback_w;
dst->height = src->height ? src->height : fallback_h;
dst->aspect = src->subresourceRange.aspectMask ? src->subresourceRange.aspectMask : (is_depth ? 2u : 1u);
}
// ---- Core XeSS Exports ----
__declspec(dllexport) xess_result_t xessGetVersion(xess_version_t *pVersion) {
if (!pVersion) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
pVersion->major = 1;
pVersion->minor = 3;
pVersion->patch = 1;
pVersion->reserved = 0;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetIntelXeFXVersion(xess_context_handle_t hContext, xess_version_t *pVersion) {
(void)hContext;
if (!pVersion) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
pVersion->major = 0;
pVersion->minor = 0;
pVersion->patch = 0;
pVersion->reserved = 0;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessIsOptimalDriver(xess_context_handle_t hContext) {
(void)hContext;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessSetLoggingCallback(xess_context_handle_t hContext,
xess_logging_level_t loggingLevel,
xess_app_log_callback_t loggingCallback) {
(void)hContext; (void)loggingLevel; (void)loggingCallback;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetProperties(xess_context_handle_t hContext,
const xess_2d_t *pOutputResolution,
xess_properties_t *pBindingProperties) {
(void)hContext; (void)pOutputResolution;
if (!pBindingProperties) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
pBindingProperties->requiredDescriptorCount = 1;
pBindingProperties->tempBufferHeapSize = 65536;
pBindingProperties->tempTextureHeapSize = 65536;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetInputResolution(xess_context_handle_t hContext,
const xess_2d_t *pOutputResolution,
xess_quality_settings_t qualitySettings,
xess_2d_t *pInputResolution) {
if (!pOutputResolution || !pInputResolution) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
WlXessCtx *c = xess_unwrap(hContext);
float r = xess_quality_ratio(qualitySettings, c ? c->force_legacy_scales : 0);
uint32_t w = (uint32_t)((float)pOutputResolution->x / r);
uint32_t h = (uint32_t)((float)pOutputResolution->y / r);
if (w < 16) w = 16;
if (h < 16) h = 16;
pInputResolution->x = w;
pInputResolution->y = h;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetOptimalInputResolution(xess_context_handle_t hContext,
const xess_2d_t *pOutputResolution,
xess_quality_settings_t qualitySettings,
xess_2d_t *pInputResolutionOptimal,
xess_2d_t *pInputResolutionMin,
xess_2d_t *pInputResolutionMax) {
if (!pOutputResolution || !pInputResolutionOptimal) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
WlXessCtx *c = xess_unwrap(hContext);
float r = xess_quality_ratio(qualitySettings, c ? c->force_legacy_scales : 0);
uint32_t w = (uint32_t)((float)pOutputResolution->x / r);
uint32_t h = (uint32_t)((float)pOutputResolution->y / r);
if (w < 16) w = 16;
if (h < 16) h = 16;
pInputResolutionOptimal->x = w;
pInputResolutionOptimal->y = h;
if (pInputResolutionMin) {
pInputResolutionMin->x = (uint32_t)((float)pOutputResolution->x / 3.0f);
pInputResolutionMin->y = (uint32_t)((float)pOutputResolution->y / 3.0f);
}
if (pInputResolutionMax) {
pInputResolutionMax->x = pOutputResolution->x;
pInputResolutionMax->y = pOutputResolution->y;
}
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetJitterScale(xess_context_handle_t hContext, float *pX, float *pY) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!pX || !pY) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
*pX = c->jitter_scale_x;
*pY = c->jitter_scale_y;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessSetJitterScale(xess_context_handle_t hContext, float x, float y) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
c->jitter_scale_x = x;
c->jitter_scale_y = y;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetVelocityScale(xess_context_handle_t hContext, float *pX, float *pY) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!pX || !pY) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
*pX = c->vel_scale_x;
*pY = c->vel_scale_y;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessSetVelocityScale(xess_context_handle_t hContext, float x, float y) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
c->vel_scale_x = x;
c->vel_scale_y = y;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessSetExposureMultiplier(xess_context_handle_t hContext, float scale) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
c->exposure_mult = scale > 0.0f ? scale : 1.0f;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetExposureMultiplier(xess_context_handle_t hContext, float *pScale) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!pScale) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
*pScale = c->exposure_mult;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessSetMaxResponsiveMaskValue(xess_context_handle_t hContext, float value) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (value < 0.0f || value > 1.0f) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
c->max_responsive_mask = value;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetMaxResponsiveMaskValue(xess_context_handle_t hContext, float *pValue) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!pValue) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
*pValue = c->max_responsive_mask;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessForceLegacyScaleFactors(xess_context_handle_t hContext, bool force) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
c->force_legacy_scales = force ? 1 : 0;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetPipelineBuildStatus(xess_context_handle_t hContext) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessDestroyContext(xess_context_handle_t hContext) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
wl_xess3_destroy(&c->xess3);
wl_seam_destroy(&c->seam);
if (c->dx12_interop) {
c->dx12_interop->lpVtbl->Release(c->dx12_interop);
c->dx12_interop = NULL;
}
c->magic = 0;
free(c);
return XESS_RESULT_SUCCESS;
}
// Debug / optional exports
__declspec(dllexport) xess_result_t xessSelectNetworkModel(xess_context_handle_t hContext, uint32_t network) {
(void)hContext; (void)network;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessStartDump(xess_context_handle_t hContext, const void *dumpParams) {
(void)hContext; (void)dumpParams;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessGetProfilingData(xess_context_handle_t hContext, void **pProfilingData) {
(void)hContext;
if (pProfilingData) *pProfilingData = NULL;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessD3D12GetProfilingData(xess_context_handle_t hContext, void **pProfilingData) {
(void)hContext;
if (pProfilingData) *pProfilingData = NULL;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessD3D12GetResourcesToDump(xess_context_handle_t hContext, void **pResourcesToDump) {
(void)hContext;
if (pResourcesToDump) *pResourcesToDump = NULL;
return XESS_RESULT_ERROR_NOT_IMPLEMENTED;
}
__declspec(dllexport) xess_result_t xessVKGetResourcesToDump(xess_context_handle_t hContext, void **pResourcesToDump) {
(void)hContext;
if (pResourcesToDump) *pResourcesToDump = NULL;
return XESS_RESULT_ERROR_NOT_IMPLEMENTED;
}
__declspec(dllexport) xess_result_t xessSetContextParameterF(xess_context_handle_t hContext, const char *name, float val) {
(void)hContext; (void)name; (void)val;
return XESS_RESULT_SUCCESS;
}
// ---- DirectX 12 XeSS Exports ----
__declspec(dllexport) xess_result_t xessD3D12CreateContext(void *pDevice, xess_context_handle_t *phContext) {
if (!pDevice || !phContext) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
WlXessCtx *c = (WlXessCtx *)calloc(1, sizeof *c);
if (!c) return XESS_RESULT_ERROR_UNKNOWN;
c->magic = WL_XESS_MAGIC;
c->is_vk = 0;
c->needs_reset = 1;
c->jitter_scale_x = 1.0f;
c->jitter_scale_y = 1.0f;
c->vel_scale_x = 1.0f;
c->vel_scale_y = 1.0f;
c->exposure_mult = 1.0f;
c->max_responsive_mask = 1.0f;
c->d3d12_dev = pDevice;
c->dx12_interop = wl_query_vkd3d_interop(pDevice);
if (c->dx12_interop) {
void *vk_inst = NULL, *vk_phys = NULL, *vk_dev = NULL;
if (c->dx12_interop->lpVtbl->GetVulkanHandles(c->dx12_interop, &vk_inst, &vk_phys, &vk_dev) == S_OK && vk_dev) {
wl_seam_init(&c->seam, vk_inst, vk_phys, vk_dev, NULL);
}
}
*phContext = (xess_context_handle_t)c;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessD3D12BuildPipelines(xess_context_handle_t hContext,
void *pPipelineLibrary,
bool blocking,
uint32_t initFlags) {
(void)pPipelineLibrary; (void)blocking;
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
c->init_flags = initFlags;
c->pipelines_built = 1;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessD3D12Init(xess_context_handle_t hContext,
const xess_d3d12_init_params_t *pInitParams) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!pInitParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
c->d3d12_init = *pInitParams;
c->out_res = pInitParams->outputResolution;
c->quality = pInitParams->qualitySetting;
c->init_flags = pInitParams->initFlags;
c->initialized = 1;
c->needs_reset = 1;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessD3D12GetInitParams(xess_context_handle_t hContext,
xess_d3d12_init_params_t *pInitParams) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED;
if (!pInitParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
*pInitParams = c->d3d12_init;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessD3D12Execute(xess_context_handle_t hContext,
void *pCommandList,
const xess_d3d12_execute_params_t *pExecParams) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED;
if (!pCommandList || !pExecParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
if (!c->seam.ready || !c->dx12_interop) return XESS_RESULT_ERROR_UNINITIALIZED;
uint32_t out_w = c->out_res.x;
uint32_t out_h = c->out_res.y;
uint32_t in_w = pExecParams->inputWidth ? pExecParams->inputWidth : out_w;
uint32_t in_h = pExecParams->inputHeight ? pExecParams->inputHeight : out_h;
int high_res_mv = (c->init_flags & XESS_INIT_FLAG_HIGH_RES_MV) ? 1 : 0;
WlFsr4FrameDesc f;
memset(&f, 0, sizeof f);
f.render_w = in_w;
f.render_h = in_h;
f.output_w = out_w;
f.output_h = out_h;
f.jitter_x = pExecParams->jitterOffsetX * c->jitter_scale_x;
f.jitter_y = pExecParams->jitterOffsetY * c->jitter_scale_y;
if (c->init_flags & XESS_INIT_FLAG_USE_NDC_VELOCITY) {
float mv_w = high_res_mv ? (float)out_w : (float)in_w;
float mv_h = high_res_mv ? (float)out_h : (float)in_h;
f.mv_scale_x = mv_w * 0.5f * c->vel_scale_x;
f.mv_scale_y = mv_h * -0.5f * c->vel_scale_y;
} else {
f.mv_scale_x = c->vel_scale_x;
f.mv_scale_y = c->vel_scale_y;
}
float exp_s = pExecParams->exposureScale > 0.0f ? pExecParams->exposureScale : 1.0f;
f.pre_exposure = exp_s * c->exposure_mult;
f.flags = xess_flags_to_wl(c->init_flags);
if (pExecParams->resetHistory || c->needs_reset) {
f.flags |= WLFSR4_FLAG_RESET;
c->needs_reset = 0;
}
f.api_source = WLFSR4_API_XESS_DX12;
f.quality_mode = xess_quality_to_wl(c->quality);
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
// XeSS DX12 contract: inputs are NON_PIXEL_SHADER_RESOURCE (0x40), output is UNORDERED_ACCESS (0x8)
xess_fill_dx12_ref(c->dx12_interop, &f.color, pExecParams->pColorTexture, 0x40u, in_w, in_h, 0);
xess_fill_dx12_ref(c->dx12_interop, &f.depth, pExecParams->pDepthTexture, 0x40u, in_w, in_h, 1);
xess_fill_dx12_ref(c->dx12_interop, &f.motion, pExecParams->pVelocityTexture, 0x40u,
high_res_mv ? out_w : in_w, high_res_mv ? out_h : in_h, 0);
xess_fill_dx12_ref(c->dx12_interop, &f.output, pExecParams->pOutputTexture, 0x8u, out_w, out_h, 0);
int live_en = 1;
int live_backend = wl_seam_live_backend(&c->seam, &live_en);
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU && c->d3d12_dev) {
if (wl_xess3_eval_d3d12(&c->xess3, &c->seam, c->dx12_interop, c->d3d12_dev, pCommandList,
&f, pExecParams->pColorTexture, pExecParams->pDepthTexture,
pExecParams->pVelocityTexture, pExecParams->pOutputTexture)) {
return XESS_RESULT_SUCCESS;
}
wl_xess3_tag_fallback(&c->xess3, &f);
} else {
wl_xess3_on_inactive(&c->xess3);
}
void *vk_cb = NULL;
int ok = 0;
if (c->dx12_interop->lpVtbl->BeginVkCommandBufferInterop(c->dx12_interop, pCommandList, &vk_cb) == S_OK && vk_cb) {
ok = wl_seam_dispatch_or_blit(&c->seam, (VkCommandBuffer)vk_cb, &f);
c->dx12_interop->lpVtbl->EndVkCommandBufferInterop(c->dx12_interop, pCommandList);
}
return ok ? XESS_RESULT_SUCCESS : XESS_RESULT_ERROR_DEVICE;
}
// ---- Vulkan XeSS Exports ----
__declspec(dllexport) xess_result_t xessVKGetRequiredInstanceExtensions(uint32_t *instanceExtensionsCount,
const char *const **instanceExtensions,
uint32_t *minVkApiVersion) {
if (instanceExtensionsCount) *instanceExtensionsCount = 0;
if (instanceExtensions) *instanceExtensions = NULL;
if (minVkApiVersion) *minVkApiVersion = (1u << 22) | (1u << 12); /* VK_API_VERSION_1_1 */
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessVKGetRequiredDeviceExtensions(VkInstance instance,
VkPhysicalDevice physicalDevice,
uint32_t *deviceExtensionsCount,
const char *const **deviceExtensions) {
(void)instance; (void)physicalDevice;
if (deviceExtensionsCount) *deviceExtensionsCount = 0;
if (deviceExtensions) *deviceExtensions = NULL;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessVKGetRequiredDeviceFeatures(VkInstance instance,
VkPhysicalDevice physicalDevice,
void **features) {
(void)instance; (void)physicalDevice; (void)features;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessVKCreateContext(VkInstance instance,
VkPhysicalDevice physicalDevice,
VkDevice device,
xess_context_handle_t *phContext) {
if (!device || !phContext) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
WlXessCtx *c = (WlXessCtx *)calloc(1, sizeof *c);
if (!c) return XESS_RESULT_ERROR_UNKNOWN;
c->magic = WL_XESS_MAGIC;
c->is_vk = 1;
c->needs_reset = 1;
c->jitter_scale_x = 1.0f;
c->jitter_scale_y = 1.0f;
c->vel_scale_x = 1.0f;
c->vel_scale_y = 1.0f;
c->exposure_mult = 1.0f;
c->max_responsive_mask = 1.0f;
wl_seam_init(&c->seam, instance, physicalDevice, device, NULL);
*phContext = (xess_context_handle_t)c;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessVKBuildPipelines(xess_context_handle_t hContext,
uint64_t pipelineCache,
bool blocking,
uint32_t initFlags) {
(void)pipelineCache; (void)blocking;
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
c->init_flags = initFlags;
c->pipelines_built = 1;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessVKInit(xess_context_handle_t hContext,
const xess_vk_init_params_t *pInitParams) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!pInitParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
c->vk_init = *pInitParams;
c->out_res = pInitParams->outputResolution;
c->quality = pInitParams->qualitySetting;
c->init_flags = pInitParams->initFlags;
c->initialized = 1;
c->needs_reset = 1;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessVKGetInitParams(xess_context_handle_t hContext,
xess_vk_init_params_t *pInitParams) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED;
if (!pInitParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
*pInitParams = c->vk_init;
return XESS_RESULT_SUCCESS;
}
__declspec(dllexport) xess_result_t xessVKExecute(xess_context_handle_t hContext,
VkCommandBuffer commandBuffer,
const xess_vk_execute_params_t *pExecParams) {
WlXessCtx *c = xess_unwrap(hContext);
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED;
if (!commandBuffer || !pExecParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
if (!c->seam.ready) return XESS_RESULT_ERROR_UNINITIALIZED;
uint32_t out_w = c->out_res.x;
uint32_t out_h = c->out_res.y;
uint32_t in_w = pExecParams->inputWidth ? pExecParams->inputWidth : out_w;
uint32_t in_h = pExecParams->inputHeight ? pExecParams->inputHeight : out_h;
int high_res_mv = (c->init_flags & XESS_INIT_FLAG_HIGH_RES_MV) ? 1 : 0;
WlFsr4FrameDesc f;
memset(&f, 0, sizeof f);
f.render_w = in_w;
f.render_h = in_h;
f.output_w = out_w;
f.output_h = out_h;
f.jitter_x = pExecParams->jitterOffsetX * c->jitter_scale_x;
f.jitter_y = pExecParams->jitterOffsetY * c->jitter_scale_y;
if (c->init_flags & XESS_INIT_FLAG_USE_NDC_VELOCITY) {
float mv_w = high_res_mv ? (float)out_w : (float)in_w;
float mv_h = high_res_mv ? (float)out_h : (float)in_h;
f.mv_scale_x = mv_w * 0.5f * c->vel_scale_x;
f.mv_scale_y = mv_h * -0.5f * c->vel_scale_y;
} else {
f.mv_scale_x = c->vel_scale_x;
f.mv_scale_y = c->vel_scale_y;
}
float exp_s = pExecParams->exposureScale > 0.0f ? pExecParams->exposureScale : 1.0f;
f.pre_exposure = exp_s * c->exposure_mult;
f.flags = xess_flags_to_wl(c->init_flags);
if (pExecParams->resetHistory || c->needs_reset) {
f.flags |= WLFSR4_FLAG_RESET;
c->needs_reset = 0;
}
f.api_source = WLFSR4_API_XESS_VK;
f.quality_mode = xess_quality_to_wl(c->quality);
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
// XeSS VK contract: inputs in SHADER_READ_ONLY_OPTIMAL (5), output in GENERAL (1)
xess_fill_vk_ref(&f.color, &pExecParams->colorTexture, 5u, in_w, in_h, 0);
xess_fill_vk_ref(&f.depth, &pExecParams->depthTexture, 5u, in_w, in_h, 1);
xess_fill_vk_ref(&f.motion, &pExecParams->velocityTexture, 5u,
high_res_mv ? out_w : in_w, high_res_mv ? out_h : in_h, 0);
xess_fill_vk_ref(&f.output, &pExecParams->outputTexture, 1u, out_w, out_h, 0);
int live_en = 1;
int live_backend = wl_seam_live_backend(&c->seam, &live_en);
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU) {
wl_xess_vk_img_t x_col, x_dep, x_mv, x_out;
memcpy(&x_col, &pExecParams->colorTexture, sizeof x_col);
memcpy(&x_dep, &pExecParams->depthTexture, sizeof x_dep);
memcpy(&x_mv, &pExecParams->velocityTexture, sizeof x_mv);
memcpy(&x_out, &pExecParams->outputTexture, sizeof x_out);
if (wl_xess3_eval_vk(&c->xess3, &c->seam, commandBuffer, &f, &x_col, &x_dep, &x_mv, &x_out)) {
return XESS_RESULT_SUCCESS;
}
wl_xess3_tag_fallback(&c->xess3, &f);
} else {
wl_xess3_on_inactive(&c->xess3);
}
int ok = wl_seam_dispatch_or_blit(&c->seam, commandBuffer, &f);
return ok ? XESS_RESULT_SUCCESS : XESS_RESULT_ERROR_DEVICE;
}
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
(void)hinst; (void)reason; (void)reserved;
return TRUE;
}
+32
View File
@@ -0,0 +1,32 @@
cmake_minimum_required(VERSION 3.22.1)
# VK_LAYER_DROIDDECK_upscale for the APK (bionic, arm64-v8a). Added from app/src/main/cpp/CMakeLists.txt.
# The glibc build for the PRoot guest is build-glibc.sh.
add_library(VkLayer_droiddeck_upscale SHARED
fsr4_layer.c
fsr4_pipeline.c
fsr4_builtin.c
fsr412_lite.c
fsr411_full_gpu.c
fsr3_gpu.c
fsr4_qnn.c
)
target_include_directories(VkLayer_droiddeck_upscale PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_compile_definitions(VkLayer_droiddeck_upscale PRIVATE VK_USE_PLATFORM_ANDROID_KHR=1)
target_compile_options(VkLayer_droiddeck_upscale PRIVATE
-O2
-Wall
-Wextra
-Wno-unused-function
-Wno-missing-field-initializers
-fvisibility=hidden
)
# -Bsymbolic keeps the exported vkGetInstanceProcAddr/vkGetDeviceProcAddr bound to this library even when
# a libvulkan in the global scope exports the same names.
target_link_options(VkLayer_droiddeck_upscale PRIVATE -Wl,-z,max-page-size=16384 -Wl,-Bsymbolic)
target_link_libraries(VkLayer_droiddeck_upscale android log dl m)
+206
View File
@@ -0,0 +1,206 @@
# VK_LAYER_DROIDDECK_upscale
A Vulkan layer that runs the upscaler calls of Windows games (FSR 4 / FSR 3 / FSR 2 through
FidelityFX, DLSS through NGX, XeSS) on the device: on the Adreno GPU, or on the Snapdragon
Hexagon NPU through Qualcomm QNN. The Windows side is a set of bridge DLLs
(`amd_fidelityfx_*.dll`, `nvngx.dll`, `libxess.dll`, ...). They talk to this layer through two
Vulkan buffers with magic sizes and a `vkCmdUpdateBuffer` doorbell (`fsr4_seam_proto.h`). That
protocol, its buffer sizes, magic values and backend IDs are unchanged from upstream, so the
upstream bridge DLLs work against this layer.
Layer name `VK_LAYER_DROIDDECK_upscale`, library `libVkLayer_droiddeck_upscale.so`, implicit layer.
The manifest template `VK_LAYER_DROIDDECK_upscale.json` turns it on with `DROIDDECK_UPSCALE=1` and
off with `DROIDDECK_UPSCALE_DISABLE=1`.
## Origin, credits, licence
GPL-3.0, like DroidDeck. Ported from `app/src/main/cpp/fsr4npu/` of
[michaelisomer-cyber/Winlator-NeuralScale](https://github.com/michaelisomer-cyber/Winlator-NeuralScale)
at commit `a0ab6b0f770e1a6786b4e68def46b4edb8baafd0` (GPL-3.0). That project is a fork of
[StevenMXZ/Winlator-Ludashi](https://github.com/StevenMXZ/Winlator-Ludashi). The first commit
that adds this folder holds the upstream files unchanged; the DroidDeck changes are in the
commits after it.
Work this code builds on, as credited upstream:
- AMD FidelityFX SDK (FSR 3.1, FSR 4.0.2, FSR 4.1.x): [GPUOpen FidelityFX-SDK](https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK)
- Intel XeSS 3.0 SDK: [intel/xess](https://github.com/intel/xess)
- FSR 4 Vulkan DP4a reference pipelines: [dvj5411/fsr4vk](https://github.com/dvj5411/fsr4vk), [zrprod9-cmyk/vela](https://github.com/zrprod9-cmyk/vela), [puzzled-pancake/fsr4-hexagon](https://github.com/puzzled-pancake/fsr4-hexagon)
- RDR2 DLSS-gate byte patterns: OptiPatcher from [optiscaler/OptiScaler](https://github.com/optiscaler/OptiScaler)
- QNN HTP runtime handling adapted from BananaNative's SM8850 runtime (per the upstream source comments)
- Qualcomm QNN / QAIRT HTP runtime (Qualcomm AI Engine Direct SDK); `fsr4_qnn.h` is a clean-room
declaration of the C ABI subset, no Qualcomm headers are used
## Files
| File | What |
| --- | --- |
| `fsr4_layer.c` | Loader interface, device/extension/feature injection, GPU/DLSS spoof, seam mailbox + doorbell, ctrl and status files |
| `fsr4_pipeline.c/.h` | Backend dispatch and fallbacks, FSR 4.1.1 Full NPU (external pack) path |
| `fsr4_builtin.c/.h` | FSR 4.0.2 INT8 on the NPU (graph compiled on the device from `fsr4_v07_i8.wpack`) |
| `fsr412_lite.c/.h` | FSR 4.1.2 Lite INT8, GPU DP4a or NPU |
| `fsr411_full_gpu.c/.h` | FSR 4.1.1 Full INT8 on the GPU |
| `fsr3_gpu.c/.h` | FSR 3.1 on the GPU, also the fallback for every other backend |
| `fsr4_qnn.c/.h` | QNN/FastRPC/AHardwareBuffer runtime; stubs only in glibc builds |
| `fsr4_seam_proto.h` | Shared protocol with the Windows bridge DLLs (do not change) |
| `fsr_gpu_timer.h` | GPU timestamp helper for the status file |
| `dd_upscale_compat.h` | DroidDeck env lookup and logging (logcat, or stderr in glibc builds) |
| `shaders/*.comp` | GLSL source of `fsr3_*.spv`, `fsr4_builtin_*.spv`, `fsr412_lite/lite_npu_{pack,unpack}.spv` |
| `scripts/pack_*.py` | Build `fsr4_v07_i8.wpack` and `fsr412_lite/fsr412_lite_i8.wpack` from the AMD weights |
| `CMakeLists.txt` | APK build (bionic), added from `app/src/main/cpp/CMakeLists.txt` |
| `build-glibc.sh` | PRoot guest build (glibc), called by `tools/components/recipes/runtime.sh` |
## Builds
- APK (bionic, arm64-v8a, minSdk 26): Gradle's NDK build makes `libVkLayer_droiddeck_upscale.so`
through `add_subdirectory(../../../../tools/upscale/layer upscale_layer)`. Links `android log dl m`,
`-Wl,-z,max-page-size=16384 -Wl,-Bsymbolic`. The manifest's relative `library_path` is meant to be
rewritten to the absolute path by the app.
- PRoot guest (glibc): `tools/upscale/layer/build-glibc.sh OUT` (`CC`, default `aarch64-linux-gnu-gcc`;
Vulkan headers from `VK_INCLUDE` or the NDK). Built with `-DDD_UPSCALE_NO_ANDROID`: no
AHardwareBuffer, FastRPC, QNN or liblog (logs go to stderr). Every NPU init fails with
`npu_unavailable` and the backends take their GPU fallbacks. `OUT` gets the library and a manifest
with `library_path` `/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so`
(override with `DD_UPSCALE_GUEST_LIB`). The runtime recipe installs both into
`app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/`.
- `-Bsymbolic` is needed in both builds: the layer exports `vkGetInstanceProcAddr`, and a
`libvulkan` already in the global symbol scope would otherwise win the lookup (the loader then
fails with `Failed to find 'vkCreateInstance'`).
## Environment
Each key is read as `DROIDDECK_UPSCALE_<KEY>` first, then `WINLATOR_FSR4_<KEY>`
(`dd_upscale_compat.h`). Empty values count as unset.
| Key | Read at | Meaning |
| --- | --- | --- |
| `DIR` (then `DM_FSR4_DIR`) | `fsr4_pipeline.c:566`, `:826` | Data dir (layout below). Unset: no backend can load its files, frames get a plain blit. No built-in fallback path |
| `POWER` | `fsr4_pipeline.c:575`, `:830` | HTP power vote: `burst`, `turbo` (default), `balanced`/`nom`, `low` |
| `BACKEND`, then `ENGINE` | `fsr4_layer.c:458` | Start backend (names under ctrl file). Unset: `fsr4_0_npu` |
| `NPU_SYNC` | `fsr4_layer.c:462` | `1` = GPU waits for the NPU each frame. Anything else = async (default). `sync`/`true` also mean sync |
| `SHARPNESS` | `fsr4_layer.c:464` | RCAS 0.0-1.0, default 0.55 |
| `PRESET` | `fsr4_pipeline.c:1239` | `ultraperf` or `performance` forces the preset; else from the game's quality mode / ratio |
| `CTRL_FILE` | `fsr4_layer.c:472` | Live control file, format below |
| `STATUS_FILE` | `fsr4_layer.c:526` | Live status file, format below |
| `NATIVELIB_DIR` | `fsr4_qnn.c:311` | Folder with the Qualcomm host libraries (see NPU setup) |
| `HTP_ARCH` | `fsr4_qnn.c:237` | Optional override of the HTP arch (`v79`, `v81`) used for the cache folder |
| `SPOOF_DLSS` | `fsr4_layer.c:557`, `:583` | `1` = expose `VK_NVX_binary_import` / `VK_NVX_image_view_handle` (stub functions) and report an RTX 2060 vendorID/deviceID/name |
| `GPU_SPOOF` | `fsr4_layer.c:570` | Words split by `,` `+` `;` or blanks: `rtx` / `rdna4` pick the reported GPU; `1` also rewrites driverID/driverName/driverInfo; `off`/`none`/`0` keep the real GPU even with `SPOOF_DLSS=1` |
| `VRAM_OVERRIDE` | `fsr4_layer.c:757` | `1` = report `VRAM_MB` as the size of every device-local heap (and its budget). Off otherwise |
| `VRAM_MB` (then `WRAPPER_VMEM_MAX_SIZE`) | `fsr4_layer.c:759` | Heap size in MB for `VRAM_OVERRIDE=1`, 512-65536 |
| `RDR2_PATCH` | `fsr4_layer.c:235` | `1` = patch RDR2.exe's DLSS vendor checks in memory. Off otherwise (Arxan crashes after loading with it) |
| `LOG` | `fsr4_qnn.c:145`, `fsr4_pipeline.c:443` | `2` = verbose QNN log and every NPU dispatch logged |
| `JX`, `JY`, `MX`, `MY` | `fsr4_pipeline.c:1387`-`1390` | Debug: jitter and motion-vector scale multipliers for the external FSR 4.1.1 NPU pack, default 1 |
Not prefixed: `ADSP_LIBRARY_PATH` (read and, if `<DIR>/adsp` is missing from it, prepended by the
layer, `fsr4_qnn.c:262`), `LD_LIBRARY_PATH` (searched for QNN libraries, `fsr4_qnn.c:303`).
Upstream's `WINLATOR_FSR4_DISABLE_LAYER` only lived in its manifest; the C code never read it.
Here the loader switch is `DROIDDECK_UPSCALE_DISABLE=1`.
Spoof examples: `SPOOF_DLSS=1` gives RTX 2060 IDs with the real driverID; add `GPU_SPOOF=1` for
`VK_DRIVER_ID_NVIDIA_PROPRIETARY` too. `GPU_SPOOF=rdna4` gives Radeon RX 9070 XT IDs,
`GPU_SPOOF=rdna4,1` adds the AMD driverID. Upstream rewrote the driverID whenever `GPU_SPOOF` was
`rtx` or `rdna4`; here that needs the `1` word.
## Ctrl file (read)
`read_live_ctrl`, `fsr4_layer.c:454`-`505`. Re-read at most every 200 ms, when a doorbell arrives
and at `vkCreateDevice`. One `key=value` per line; keys missing from the file keep their last value
(first the env values):
```
enabled=1 # 0, off..., false... = bypass (plain blit); anything else = on
backend=fsr4_1_lite_gpu
engine=fsr4_1_lite_gpu # same as backend=, upstream writes both
npu_sync=async # 1, sync..., true... = sync; anything else = async
sharpness=0.55 # clamped to 0..1
```
Backend names, matched by prefix (`parse_backend_str`, `fsr4_layer.c:421`): `fsr3`/`gpu` = FSR 3.1
GPU (0), `xess`/`xess3` = XeSS 3 DP4a (1), `fsr4_0_npu`/`fsr4_npu`/`fsr4`/`npu` = FSR 4.0.2 NPU (2),
`fsr4_1_lite_npu`/`412_lite_npu` (3), `fsr4_1_full_npu`/`412_full_npu` (4),
`fsr4_1_lite_gpu`/`412_lite_gpu` (5), `fsr4_1_full_gpu`/`412_full_gpu` (6); anything else = 5.
If the first line has none of these keys, it is a bare flag: containing `0`, `off` or `false` turns
the upscaler off, anything else on.
## Status file (written)
`write_live_status`, `fsr4_layer.c:507`-`553`. Written to `<STATUS_FILE>.tmp`, then renamed over
`STATUS_FILE`. At most every 250 ms unless enabled/backend/sync/NPU use/quality/render width
changed; always at `vkCreateDevice`. Exactly these lines in this order:
```
layer=1
driver=<real GPU name>
ahb=<pending|gpu_only|zc|staging|zc_avail|staging_avail|zc_pending|zc_failed>
npu_state=<standby|ready|compiling|failed|cached|ready_to_compile|no_pack|fsr3_gpu|xess3_dp4a|fsr412_lite_gpu|fsr411_full_gpu|...>
rdr2_patch=<none|partial|ok>
engine=<fsr3|fsr4>
backend=<fsr3_gpu|xess3_gpu|fsr4_0_npu|fsr4_1_lite_npu|fsr4_1_full_npu|fsr4_1_lite_gpu|fsr4_1_full_gpu>
backend_tag=<what really ran, e.g. FSR4.1-Lite-GPU (NPU fallback)>
npu_sync=<sync|async>
sharpness=<%.2f>
enabled=<0|1>
active=<0|1>
npu=<0|1>
api=<None|FSR 4 (Vulkan)|FSR 4 (DX12)|DLSS (Vulkan)|DLSS (DX12)|XeSS (Vulkan)|XeSS (DX12)|FSR 3 (...)|FSR 2 (...)>
quality=<Native AA (DLAA)|Ultra Quality|Quality|Balanced|Performance|Ultra Performance|Auto>
render=<w>x<h>
output=<w>x<h>
preset=<perf|ultraperf>
gpu_us=<u32>
htp_us=<u32>
dispatches=<u64>
reason=<ok|standby|bypass_off|ok_fsr3_gpu|missing_fsr3_shaders|npu_unavailable|...>
ts_ms=<CLOCK_REALTIME ms>
```
## Data dir (`DROIDDECK_UPSCALE_DIR`)
Same tree as upstream's `app/src/main/assets/fsr4/`. None of it is in this repo; it is installed at
run time. Paths the layer opens, relative to the dir:
| Path | Used by | Built here? |
| --- | --- | --- |
| `fsr3_prepare.spv`, `fsr3_accumulate.spv`, `fsr3_rcas.spv` | FSR 3.1 GPU (`fsr3_gpu.c:343`, `:385`) | Source in `shaders/`. Upstream's files look like `glslc -O --target-env=vulkan1.1` output (Shaderc, SPIR-V 1.3); a local build of that is close in size, not byte-identical. Not built by the layer builds |
| `fsr4_builtin_pre.spv`, `fsr4_builtin_post_a.spv`, `fsr4_builtin_post_b.spv` | FSR 4.0.2 NPU (`fsr4_builtin.c:560`, `:609`) | Source in `shaders/` |
| `fsr4_v07_i8.wpack` | FSR 4.0.2 NPU graph (`fsr4_qnn.c:1583`) | `scripts/pack_fsr4_weights.py`, needs fsr4-hexagon and AMD weights |
| `fsr412_lite/0000.spv` ... `0010.spv`, `0013.spv`, `weights.bin` | FSR 4.1.2 Lite (`fsr412_lite.c:410`, `:688`) | No: precompiled AMD FidelityFX SDK passes (per upstream) |
| `fsr412_lite/lite_npu_pack.spv`, `lite_npu_unpack.spv` | Lite NPU (`fsr412_lite.c:618`) | Source in `shaders/` |
| `fsr412_lite/fsr412_lite_i8.wpack` | Lite NPU graph (`fsr412_lite.c:456`) | `scripts/pack_fsr412_lite_weights.py`, needs vela + `weights.bin` |
| `fsr411_full/{quality,performance}/pass-00.spv` ... `pass-27.spv`, `initializers.bin` | FSR 4.1.1 Full GPU (`fsr411_full_gpu.c:328`, `:346`) | No: precompiled AMD FidelityFX SDK passes (per upstream) |
| `adsp/libQnnHtpV79Skel.so`, `adsp/libQnnHtpV81Skel.so` | NPU side, loaded by FastRPC through `ADSP_LIBRARY_PATH`; also probed for the arch (`fsr4_qnn.c:224`) | No: Qualcomm QNN |
| `<arch>/fsr4_v07_i8_cache.bin`, `<arch>/fsr412_lite_i8_cache.bin` | Compiled NPU graphs, written by the layer on first use | Made on the device |
| `1080/{performance,ultraperf}/pass-00.spv`, `pass-01-npu.spv`, `pass-28.spv`, `initializers.bin`, `v81/nf4_k1h.bin`, `v81/nf4up_k1h.bin` | Optional external FSR 4.1.1 Full NPU pack (`fsr4_pipeline.c:460`-`478`, `fsr4_qnn.c:1018`); v81 only | No |
| `jni/arm64-v8a/<lib>`, `<lib>` | First two places searched for QNN host libraries | No |
`<arch>` is `v79` or `v81`: `HTP_ARCH` if set, else the SoC (`ro.soc.model` /
`ro.vendor.qti.soc_model` starting with `SM8750` = v79, `SM8850` = v81, or `ro.vendor.qti.soc_name` /
`ro.board.platform` `sun` = v79, `canoe` = v81), else the `libQnnHtpV<NN>Stub.so` mapped in the
process, else the only skel present in `adsp/`, else `htp` (`fsr4_qnn.c:176`-`250`). Upstream always
used `v81/`.
## NPU setup (Android build only)
- Host libraries: `libQnnSystem.so`, `libQnnHtp.so`, `libQnnHtpV79Stub.so`, `libQnnHtpV81Stub.so`,
`libQnnHtpPrepare.so` (on-device graph compile). Searched in this order (`fsr4_qnn.c:303`):
`<DIR>/jni/arm64-v8a/`, `<DIR>/`, `<NATIVELIB_DIR>/`, each `LD_LIBRARY_PATH` entry, then the bare
name (Android `sphal` namespace first, then the default one).
- `libQnnHtp.so` opens the arch stub by name itself. The layer loads `libQnnHtpV<arch>Stub.so`
(both stubs when the arch is unknown) from the same search list first (`fsr4_qnn.c:364`), so
`NATIVELIB_DIR` alone is enough; `LD_LIBRARY_PATH` does not have to name the folder.
- `ADSP_LIBRARY_PATH` must list `<DIR>/adsp` (the skels), `;`-separated, e.g.
`<DIR>/adsp;/vendor/dsp/cdsp;/vendor/lib/rfsa/adsp;/system/lib/rfsa/adsp`. The layer prepends
`<DIR>/adsp` itself when it is missing.
- `libcdsprpc.so` comes from the vendor partition.
## DroidDeck changes from upstream
- Layer name, library name, log tags, manifest (implicit, `DROIDDECK_UPSCALE` / `DROIDDECK_UPSCALE_DISABLE`).
- `DROIDDECK_UPSCALE_<KEY>` env with `WINLATOR_FSR4_<KEY>` fallback.
- No hardcoded `/data/user/0/com.winlator.cmod/files/fsr4` fallback; no data dir means GPU blit.
- Compiled NPU graph caches in `<DIR>/<arch>/` instead of `<DIR>/v81/`.
- driverID/driverName/driverInfo rewrite only with `GPU_SPOOF` word `1`; `SPOOF_DLSS=1` alone reports RTX vendor/device IDs.
- Arch stub preloaded from the library search list (`NATIVELIB_DIR` works without `LD_LIBRARY_PATH`).
- glibc build (`DD_UPSCALE_NO_ANDROID`) with QNN stubs and stderr logging.
- `-Bsymbolic` link flag; pack scripts take their paths as arguments instead of the author's Windows paths.
@@ -0,0 +1,17 @@
{
"file_format_version": "1.2.0",
"layer": {
"name": "VK_LAYER_DROIDDECK_upscale",
"type": "GLOBAL",
"library_path": "libVkLayer_droiddeck_upscale.so",
"api_version": "1.3.275",
"implementation_version": "1",
"description": "In-game upscaler: FSR 4 / FSR 3.1 / XeSS / DLSS calls from the Windows bridge DLLs run on the GPU or the Hexagon NPU",
"enable_environment": {
"DROIDDECK_UPSCALE": "1"
},
"disable_environment": {
"DROIDDECK_UPSCALE_DISABLE": "1"
}
}
}
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Builds VK_LAYER_DROIDDECK_upscale for the arm64 glibc guest (PRoot mode): tools/upscale/layer/build-glibc.sh OUT
# DD_UPSCALE_NO_ANDROID leaves out AHardwareBuffer, FastRPC, QNN and liblog, so NPU backends use their GPU fallbacks.
# OUT gets libVkLayer_droiddeck_upscale.so and VK_LAYER_DROIDDECK_upscale.json (absolute guest library_path).
# -Bsymbolic: the layer exports vkGetInstanceProcAddr; without it a libvulkan already in the global scope
# wins the lookup and the loader gets its own trampoline back ("Failed to find 'vkCreateInstance'").
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../../.." && pwd)
out=${1:?usage: tools/upscale/layer/build-glibc.sh OUT}
case "$out" in /*) ;; *) out="$PWD/$out" ;; esac
guest_lib=${DD_UPSCALE_GUEST_LIB:-/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so}
cc=${CC:-aarch64-linux-gnu-gcc}
strip=${STRIP:-aarch64-linux-gnu-strip}
vkinc=${VK_INCLUDE:-}
if [ -z "$vkinc" ]; then
ndks=("${NDK:-}" "${ANDROID_NDK_HOME:-}" "${ANDROID_NDK_LATEST_HOME:-}")
sdk_ndks=("${ANDROID_HOME:-$HOME/Library/Android/sdk}"/ndk/*)
for ((i = ${#sdk_ndks[@]} - 1; i >= 0; i--)); do ndks+=("${sdk_ndks[i]}"); done
for ndk in "${ndks[@]}"; do
[ -n "$ndk" ] && [ -d "$ndk" ] || continue
for cand in "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include; do
if [ -f "$cand/vulkan/vulkan_android.h" ]; then vkinc=$cand; break 2; fi
done
done
fi
[ -n "$vkinc" ] && [ -f "$vkinc/vulkan/vulkan_core.h" ] && [ -f "$vkinc/vulkan/vulkan_android.h" ] || {
echo "tools/upscale/layer/build-glibc.sh: no Vulkan headers (set VK_INCLUDE)" >&2; exit 1; }
command -v "$cc" >/dev/null || { echo "tools/upscale/layer/build-glibc.sh: $cc not found (set CC)" >&2; exit 1; }
work="$repo/build/upscale-layer"
rm -rf "$work" && mkdir -p "$work/include" "$work/out"
# Only the Vulkan headers: the NDK sysroot's libc headers must not shadow glibc's.
cp -R "$vkinc/vulkan" "$work/include/"
if [ -d "$vkinc/vk_video" ]; then cp -R "$vkinc/vk_video" "$work/include/"; fi
"$cc" -std=gnu11 -shared -fPIC -O2 -Wall -Wextra -Wno-unused-function -Wno-missing-field-initializers \
-fvisibility=hidden -pthread -Wl,-z,defs -Wl,-Bsymbolic -DDD_UPSCALE_NO_ANDROID -I"$work/include" -I"$here" \
-o "$work/out/libVkLayer_droiddeck_upscale.so" \
"$here/fsr4_layer.c" "$here/fsr4_pipeline.c" "$here/fsr4_builtin.c" "$here/fsr412_lite.c" \
"$here/fsr411_full_gpu.c" "$here/fsr3_gpu.c" "$here/fsr4_qnn.c" -lm -ldl
"$strip" --strip-unneeded "$work/out/libVkLayer_droiddeck_upscale.so"
sed "s|\"library_path\": \"[^\"]*\"|\"library_path\": \"$guest_lib\"|" \
"$here/VK_LAYER_DROIDDECK_upscale.json" > "$work/out/VK_LAYER_DROIDDECK_upscale.json"
grep -q "\"library_path\": \"$guest_lib\"" "$work/out/VK_LAYER_DROIDDECK_upscale.json"
mkdir -p "$out"
cp "$work/out/libVkLayer_droiddeck_upscale.so" "$work/out/VK_LAYER_DROIDDECK_upscale.json" "$out/"
echo "built $out"
+56
View File
@@ -0,0 +1,56 @@
// DroidDeck glue for the upscaler layer: environment lookup and logging.
//
// Every setting is read as DROIDDECK_UPSCALE_<KEY> first and WINLATOR_FSR4_<KEY> second, so
// launchers written for the upstream layer keep working. Empty values count as unset.
//
// Android builds log to logcat. DD_UPSCALE_NO_ANDROID builds (glibc, PRoot guest) log to stderr.
#pragma once
#include <stdio.h>
#include <stdlib.h>
static inline const char *dd_upscale_env(const char *key) {
char name[96];
snprintf(name, sizeof name, "DROIDDECK_UPSCALE_%s", key);
const char *v = getenv(name);
if (v && *v) return v;
snprintf(name, sizeof name, "WINLATOR_FSR4_%s", key);
v = getenv(name);
return (v && *v) ? v : NULL;
}
// Data dir with the SPIR-V passes, weights and QNN files. NULL when no launcher set one.
static inline const char *dd_upscale_dir(void) {
const char *dir = dd_upscale_env("DIR");
if (!dir) {
dir = getenv("DM_FSR4_DIR");
if (dir && !*dir) dir = NULL;
}
return dir;
}
#ifdef DD_UPSCALE_NO_ANDROID
#include <stdarg.h>
#define DD_LOG_INFO 4
#define DD_LOG_WARN 5
#define DD_LOG_ERROR 6
__attribute__((format(printf, 3, 4)))
static inline int dd_upscale_log(int prio, const char *tag, const char *fmt, ...) {
char msg[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof msg, fmt, ap);
va_end(ap);
const char lvl = prio >= DD_LOG_ERROR ? 'E' : (prio == DD_LOG_WARN ? 'W' : 'I');
return fprintf(stderr, "%c/%s: %s\n", lvl, tag, msg);
}
#else
#include <android/log.h>
#define DD_LOG_INFO ANDROID_LOG_INFO
#define DD_LOG_WARN ANDROID_LOG_WARN
#define DD_LOG_ERROR ANDROID_LOG_ERROR
#define dd_upscale_log __android_log_print
#endif
+711
View File
@@ -0,0 +1,711 @@
// Winlator Ludashi Native Vulkan GPU FSR 3.1 Temporal Upscaler
// 3-pass compute pipeline running synchronously inside the game's VkCommandBuffer:
// Pass 1: fsr3_prepare.spv - 3x3 closest-depth MV dilation + MVJittered cancel + disocclusion mask
// Pass 2: fsr3_accumulate.spv - Jitter-aware Lanczos-2 + 5-tap Catmull-Rom + YCoCg variance AABB clipping
// Pass 3: fsr3_rcas.spv - Official AMD RCAS sharpening in perceptual mu-law space
#define _GNU_SOURCE
#include "fsr3_gpu.h"
#include "fsr_gpu_timer.h"
#include "dd_upscale_compat.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define F3_TAG "DroidDeckUpscaleFSR3"
#define F3_LOGI(...) dd_upscale_log(DD_LOG_INFO, F3_TAG, __VA_ARGS__)
#define F3_LOGW(...) dd_upscale_log(DD_LOG_WARN, F3_TAG, __VA_ARGS__)
#define F3_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F3_TAG, __VA_ARGS__)
typedef struct {
VkImage img;
VkDeviceMemory mem;
VkImageView view;
VkFormat fmt;
uint32_t w, h;
int inited;
} F3Img;
typedef struct {
float jitter_x, jitter_y;
float mv_scale_x, mv_scale_y;
float jitter_cancel_x, jitter_cancel_y;
float expo;
float sharp;
uint32_t rw, rh;
uint32_t ow, oh;
uint32_t flags;
uint32_t pad0;
} F3PC;
#define F3_VIEW_CACHE 64
typedef struct {
VkImage img;
VkFormat fmt;
VkImageAspectFlags aspect;
VkImageView view;
} F3ViewEnt;
struct WlFsr3Gpu {
WlVkDispatch vk;
char dir[512];
int ready;
VkSampler sampler_linear;
VkSampler sampler_nearest;
VkDescriptorSetLayout dsl_prep, dsl_accum, dsl_rcas;
VkPipelineLayout pl_prep, pl_accum, pl_rcas;
VkPipeline pipe_prep, pipe_accum, pipe_rcas;
VkDescriptorPool dpool;
VkDescriptorSet ds_prep[2], ds_accum[2], ds_rcas[2];
// Dynamically sized per-render-res & per-output-res GPU images
F3Img dilated_mv;
F3Img lock_mask;
F3Img hist_img[2];
F3Img out_img;
F3Img dummy_img;
uint32_t frame_idx;
uint64_t dispatches;
int need_reset;
float prev_jitter_x, prev_jitter_y;
int have_prev_jitter;
F3ViewEnt vcache[F3_VIEW_CACHE];
int vcache_n;
WlGpuTimer timer;
};
static int f3_is_depth_fmt(VkFormat fmt) {
switch (fmt) {
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_X8_D24_UNORM_PACK32:
case VK_FORMAT_D32_SFLOAT:
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
return 1;
default:
return 0;
}
}
static VkImageAspectFlags f3_depth_bar_aspect(VkFormat fmt) {
switch (fmt) {
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_X8_D24_UNORM_PACK32:
case VK_FORMAT_D32_SFLOAT:
return VK_IMAGE_ASPECT_DEPTH_BIT;
default:
return VK_IMAGE_ASPECT_COLOR_BIT;
}
}
static uint32_t f3_find_mem(const WlVkDispatch *vk, uint32_t bits, VkMemoryPropertyFlags want) {
VkPhysicalDeviceMemoryProperties mp;
vk->GetPhysicalDeviceMemoryProperties(vk->phys_dev, &mp);
for (uint32_t i = 0; i < mp.memoryTypeCount; i++) {
if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i;
}
for (uint32_t i = 0; i < mp.memoryTypeCount; i++) {
if (bits & (1u << i)) return i;
}
return UINT32_MAX;
}
static int f3_create_img(const WlVkDispatch *vk, F3Img *im, uint32_t w, uint32_t h,
VkFormat fmt, VkImageUsageFlags usage) {
memset(im, 0, sizeof *im);
im->w = w; im->h = h; im->fmt = fmt;
VkImageCreateInfo ci = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.imageType = VK_IMAGE_TYPE_2D,
.format = fmt,
.extent = {w, h, 1},
.mipLevels = 1, .arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = usage,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
if (vk->CreateImage(vk->device, &ci, NULL, &im->img) != VK_SUCCESS) return 0;
VkMemoryRequirements mr;
vk->GetImageMemoryRequirements(vk->device, im->img, &mr);
uint32_t mt = f3_find_mem(vk, mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
if (mt == UINT32_MAX) return 0;
VkMemoryAllocateInfo ai = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.allocationSize = mr.size, .memoryTypeIndex = mt,
};
if (vk->AllocateMemory(vk->device, &ai, NULL, &im->mem) != VK_SUCCESS) return 0;
if (vk->BindImageMemory(vk->device, im->img, im->mem, 0) != VK_SUCCESS) return 0;
VkImageViewCreateInfo vci = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.image = im->img, .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = fmt,
.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 },
};
if (vk->CreateImageView(vk->device, &vci, NULL, &im->view) != VK_SUCCESS) return 0;
return 1;
}
static void f3_destroy_img(const WlVkDispatch *vk, F3Img *im) {
if (im->view) vk->DestroyImageView(vk->device, im->view, NULL);
if (im->img) vk->DestroyImage(vk->device, im->img, NULL);
if (im->mem) vk->FreeMemory(vk->device, im->mem, NULL);
memset(im, 0, sizeof *im);
}
static VkShaderModule f3_load_spv(const WlVkDispatch *vk, const char *dir, const char *name) {
char path[640];
snprintf(path, sizeof path, "%s/%s", dir, name);
FILE *f = fopen(path, "rb");
if (!f) return VK_NULL_HANDLE;
fseek(f, 0, SEEK_END);
long sz = ftell(f);
if (sz <= 0 || (sz & 3) != 0) { fclose(f); return VK_NULL_HANDLE; }
rewind(f);
void *buf = malloc((size_t)sz);
if (!buf || fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
fclose(f); free(buf); return VK_NULL_HANDLE;
}
fclose(f);
VkShaderModuleCreateInfo ci = {
.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
.codeSize = (size_t)sz, .pCode = (const uint32_t *)buf,
};
VkShaderModule sm = VK_NULL_HANDLE;
vk->CreateShaderModule(vk->device, &ci, NULL, &sm);
free(buf);
return sm;
}
static int f3_create_pipe(const WlVkDispatch *vk, const char *dir, const char *spv_name,
const VkDescriptorSetLayoutBinding *binds, uint32_t nbinds,
uint32_t pc_bytes,
VkDescriptorSetLayout *out_dsl, VkPipelineLayout *out_pl, VkPipeline *out_pipe) {
VkShaderModule sm = f3_load_spv(vk, dir, spv_name);
if (!sm) return 0;
VkDescriptorSetLayoutCreateInfo dci = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.bindingCount = nbinds, .pBindings = binds,
};
if (vk->CreateDescriptorSetLayout(vk->device, &dci, NULL, out_dsl) != VK_SUCCESS) {
vk->DestroyShaderModule(vk->device, sm, NULL);
return 0;
}
VkPushConstantRange pcr = { VK_SHADER_STAGE_COMPUTE_BIT, 0, pc_bytes };
VkPipelineLayoutCreateInfo pci = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.setLayoutCount = 1, .pSetLayouts = out_dsl,
.pushConstantRangeCount = pc_bytes ? 1u : 0u, .pPushConstantRanges = pc_bytes ? &pcr : NULL,
};
if (vk->CreatePipelineLayout(vk->device, &pci, NULL, out_pl) != VK_SUCCESS) {
vk->DestroyShaderModule(vk->device, sm, NULL);
return 0;
}
VkComputePipelineCreateInfo cpci = {
.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage = { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = sm, .pName = "main" },
.layout = *out_pl,
};
VkResult r = vk->CreateComputePipelines(vk->device, VK_NULL_HANDLE, 1, &cpci, NULL, out_pipe);
vk->DestroyShaderModule(vk->device, sm, NULL);
return r == VK_SUCCESS;
}
static void f3_img_bar_asp(const WlVkDispatch *vk, VkCommandBuffer cb, VkImage img,
VkImageAspectFlags aspect,
VkImageLayout oldL, VkImageLayout newL,
VkPipelineStageFlags srcS, VkPipelineStageFlags dstS,
VkAccessFlags srcA, VkAccessFlags dstA) {
VkImageMemoryBarrier bar = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = srcA, .dstAccessMask = dstA,
.oldLayout = oldL, .newLayout = newL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = img,
.subresourceRange = { aspect, 0, 1, 0, 1 },
};
vk->CmdPipelineBarrier(cb, srcS, dstS, 0, 0, NULL, 0, NULL, 1, &bar);
}
static void f3_img_bar(const WlVkDispatch *vk, VkCommandBuffer cb, VkImage img,
VkImageLayout oldL, VkImageLayout newL,
VkPipelineStageFlags srcS, VkPipelineStageFlags dstS,
VkAccessFlags srcA, VkAccessFlags dstA) {
f3_img_bar_asp(vk, cb, img, VK_IMAGE_ASPECT_COLOR_BIT, oldL, newL, srcS, dstS, srcA, dstA);
}
static VkImageView f3_get_view(WlFsr3Gpu *g, VkImage img, VkFormat fmt, VkImageAspectFlags aspect) {
for (int i = 0; i < g->vcache_n; i++) {
if (g->vcache[i].img == img && g->vcache[i].fmt == fmt && g->vcache[i].aspect == aspect)
return g->vcache[i].view;
}
VkImageViewCreateInfo ci = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.image = img, .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = fmt,
.subresourceRange = { aspect, 0, 1, 0, 1 },
};
VkImageView v = VK_NULL_HANDLE;
if (g->vk.CreateImageView(g->vk.device, &ci, NULL, &v) != VK_SUCCESS) return VK_NULL_HANDLE;
if (g->vcache_n >= F3_VIEW_CACHE) {
g->vk.DestroyImageView(g->vk.device, g->vcache[0].view, NULL);
memmove(&g->vcache[0], &g->vcache[1], (F3_VIEW_CACHE - 1) * sizeof(F3ViewEnt));
g->vcache_n--;
}
g->vcache[g->vcache_n++] = (F3ViewEnt){ img, fmt, aspect, v };
return v;
}
static int f3_ensure_targets(WlFsr3Gpu *g, uint32_t rw, uint32_t rh, uint32_t ow, uint32_t oh) {
int lr_changed = (!g->dilated_mv.img || g->dilated_mv.w != rw || g->dilated_mv.h != rh);
int hr_changed = (!g->out_img.img || g->out_img.w != ow || g->out_img.h != oh);
if (!lr_changed && !hr_changed) return 1;
if (g->vk.DeviceWaitIdle) g->vk.DeviceWaitIdle(g->vk.device);
const VkImageUsageFlags rw_use = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
const VkImageUsageFlags out_use = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
if (lr_changed) {
f3_destroy_img(&g->vk, &g->dilated_mv);
f3_destroy_img(&g->vk, &g->lock_mask);
if (!f3_create_img(&g->vk, &g->dilated_mv, rw, rh, VK_FORMAT_R16G16_SFLOAT, rw_use) ||
!f3_create_img(&g->vk, &g->lock_mask, rw, rh, VK_FORMAT_R16G16B16A16_SFLOAT, rw_use)) {
return 0;
}
}
if (hr_changed) {
f3_destroy_img(&g->vk, &g->hist_img[0]);
f3_destroy_img(&g->vk, &g->hist_img[1]);
f3_destroy_img(&g->vk, &g->out_img);
if (!f3_create_img(&g->vk, &g->hist_img[0], ow, oh, VK_FORMAT_R16G16B16A16_SFLOAT, rw_use) ||
!f3_create_img(&g->vk, &g->hist_img[1], ow, oh, VK_FORMAT_R16G16B16A16_SFLOAT, rw_use) ||
!f3_create_img(&g->vk, &g->out_img, ow, oh, VK_FORMAT_R16G16B16A16_SFLOAT, out_use)) {
return 0;
}
g->need_reset = 1;
}
// Bind static internal images for both ping-pong slots
for (int s = 0; s < 2; s++) {
int prev = s ^ 1;
VkDescriptorImageInfo mv_st = { VK_NULL_HANDLE, g->dilated_mv.view, VK_IMAGE_LAYOUT_GENERAL };
VkDescriptorImageInfo lk_st = { VK_NULL_HANDLE, g->lock_mask.view, VK_IMAGE_LAYOUT_GENERAL };
VkWriteDescriptorSet w_prep[2] = {
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_prep[s], .dstBinding = 3, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &mv_st },
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_prep[s], .dstBinding = 4, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &lk_st },
};
g->vk.UpdateDescriptorSets(g->vk.device, 2, w_prep, 0, NULL);
VkDescriptorImageInfo mv_ro = { g->sampler_nearest, g->dilated_mv.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
VkDescriptorImageInfo lk_ro = { g->sampler_nearest, g->lock_mask.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
VkDescriptorImageInfo hp_ro = { g->sampler_linear, g->hist_img[prev].view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
VkDescriptorImageInfo hc_st = { VK_NULL_HANDLE, g->hist_img[s].view, VK_IMAGE_LAYOUT_GENERAL };
VkWriteDescriptorSet w_acc[4] = {
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_accum[s], .dstBinding = 1, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &mv_ro },
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_accum[s], .dstBinding = 2, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &lk_ro },
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_accum[s], .dstBinding = 3, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &hp_ro },
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_accum[s], .dstBinding = 4, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &hc_st },
};
g->vk.UpdateDescriptorSets(g->vk.device, 4, w_acc, 0, NULL);
VkDescriptorImageInfo hc_ro = { g->sampler_nearest, g->hist_img[s].view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
VkDescriptorImageInfo out_st = { VK_NULL_HANDLE, g->out_img.view, VK_IMAGE_LAYOUT_GENERAL };
VkWriteDescriptorSet w_rcas[2] = {
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_rcas[s], .dstBinding = 0, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &hc_ro },
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_rcas[s], .dstBinding = 1, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &out_st },
};
g->vk.UpdateDescriptorSets(g->vk.device, 2, w_rcas, 0, NULL);
}
F3_LOGI("GPU FSR 3.1 targets ready (render=%ux%u -> output=%ux%u)", rw, rh, ow, oh);
return 1;
}
WlFsr3Gpu *wl_fsr3_gpu_create(const WlVkDispatch *vk, const char *fsr4_dir) {
if (!vk || !fsr4_dir || !*fsr4_dir) return NULL;
if (!vk->CreateDescriptorPool || !vk->AllocateDescriptorSets ||
!vk->UpdateDescriptorSets || !vk->CmdBindDescriptorSets) return NULL;
char test_p[640];
snprintf(test_p, sizeof test_p, "%s/fsr3_prepare.spv", fsr4_dir);
if (access(test_p, R_OK) != 0) return NULL;
WlFsr3Gpu *g = (WlFsr3Gpu *)calloc(1, sizeof *g);
if (!g) return NULL;
g->vk = *vk;
snprintf(g->dir, sizeof g->dir, "%s", fsr4_dir);
g->need_reset = 1;
VkSamplerCreateInfo sci_lin = {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.magFilter = VK_FILTER_LINEAR, .minFilter = VK_FILTER_LINEAR,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
};
VkSamplerCreateInfo sci_near = sci_lin;
sci_near.magFilter = VK_FILTER_NEAREST;
sci_near.minFilter = VK_FILTER_NEAREST;
if (vk->CreateSampler(vk->device, &sci_lin, NULL, &g->sampler_linear) != VK_SUCCESS ||
vk->CreateSampler(vk->device, &sci_near, NULL, &g->sampler_nearest) != VK_SUCCESS) goto fail;
VkDescriptorSetLayoutBinding b_prep[5] = {
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
{1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
{2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
{3, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
{4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
};
VkDescriptorSetLayoutBinding b_accum[5] = {
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
{1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
{2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
{3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
{4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
};
VkDescriptorSetLayoutBinding b_rcas[2] = {
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
{1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
};
if (!f3_create_pipe(vk, fsr4_dir, "fsr3_prepare.spv", b_prep, 5, sizeof(F3PC), &g->dsl_prep, &g->pl_prep, &g->pipe_prep) ||
!f3_create_pipe(vk, fsr4_dir, "fsr3_accumulate.spv", b_accum, 5, sizeof(F3PC), &g->dsl_accum, &g->pl_accum, &g->pipe_accum) ||
!f3_create_pipe(vk, fsr4_dir, "fsr3_rcas.spv", b_rcas, 2, sizeof(F3PC), &g->dsl_rcas, &g->pl_rcas, &g->pipe_rcas)) {
F3_LOGE("failed to create GPU FSR 3.1 compute pipelines (dir=%s)", fsr4_dir);
goto fail;
}
VkDescriptorPoolSize psizes[2] = {
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 20 },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 12 },
};
VkDescriptorPoolCreateInfo dpci = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.maxSets = 6, .poolSizeCount = 2, .pPoolSizes = psizes,
};
if (vk->CreateDescriptorPool(vk->device, &dpci, NULL, &g->dpool) != VK_SUCCESS) goto fail;
VkDescriptorSetLayout layouts[6] = {
g->dsl_prep, g->dsl_prep, g->dsl_accum, g->dsl_accum, g->dsl_rcas, g->dsl_rcas
};
VkDescriptorSet sets[6];
VkDescriptorSetAllocateInfo dsai = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.descriptorPool = g->dpool, .descriptorSetCount = 6, .pSetLayouts = layouts,
};
if (vk->AllocateDescriptorSets(vk->device, &dsai, sets) != VK_SUCCESS) goto fail;
g->ds_prep[0] = sets[0]; g->ds_prep[1] = sets[1];
g->ds_accum[0] = sets[2]; g->ds_accum[1] = sets[3];
g->ds_rcas[0] = sets[4]; g->ds_rcas[1] = sets[5];
if (!f3_create_img(vk, &g->dummy_img, 1, 1, VK_FORMAT_R16G16_SFLOAT,
VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)) {
goto fail;
}
wl_gpu_timer_init(&g->timer, vk);
g->ready = 1;
F3_LOGI("Native Vulkan GPU FSR 3.1 temporal upscaler READY (0 NPU watts, 0 extra frame latency)");
return g;
fail:
wl_fsr3_gpu_destroy(g);
return NULL;
}
void wl_fsr3_gpu_reset(WlFsr3Gpu *g) {
if (!g) return;
g->need_reset = 1;
g->have_prev_jitter = 0;
}
int wl_fsr3_gpu_is_ready(const WlFsr3Gpu *g) {
return g && g->ready;
}
int wl_fsr3_gpu_dispatch(WlFsr3Gpu *g, VkCommandBuffer cb,
const WlFsr4FrameDesc *frame,
VkImage color_img, VkFormat color_fmt, uint32_t cw, uint32_t ch,
VkImage depth_img, VkFormat depth_fmt,
VkImage motion_img, VkFormat motion_fmt,
VkImage out_img, uint32_t ow, uint32_t oh,
float sharpness,
uint32_t *out_gpu_us,
uint64_t *out_dispatches,
const char **out_reason) {
if (!g || !g->ready || !cb || !frame) return 0;
uint32_t rw = frame->render_w ? frame->render_w : cw;
uint32_t rh = frame->render_h ? frame->render_h : ch;
if (cw && rw > cw) rw = cw;
if (ch && rh > ch) rh = ch;
if (!rw || !rh || !ow || !oh) return 0;
if (!f3_ensure_targets(g, rw, rh, ow, oh)) {
if (out_reason) *out_reason = "fsr3_alloc_failed";
return 0;
}
VkImageView color_v = f3_get_view(g, color_img, color_fmt, VK_IMAGE_ASPECT_COLOR_BIT);
if (!color_v) {
if (out_reason) *out_reason = "fsr3_view_failed";
return 0;
}
VkImageView mv_v = (motion_img != VK_NULL_HANDLE && motion_fmt != VK_FORMAT_UNDEFINED)
? f3_get_view(g, motion_img, motion_fmt, VK_IMAGE_ASPECT_COLOR_BIT)
: g->dummy_img.view;
if (!mv_v) mv_v = g->dummy_img.view;
int has_depth = 0;
VkImageView dep_v = g->dummy_img.view;
VkImageAspectFlags dep_bar_asp = VK_IMAGE_ASPECT_COLOR_BIT;
if (depth_img != VK_NULL_HANDLE && depth_fmt != VK_FORMAT_UNDEFINED) {
VkImageAspectFlags v_asp = f3_is_depth_fmt(depth_fmt) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT;
VkImageView dv = f3_get_view(g, depth_img, depth_fmt, v_asp);
if (dv) {
dep_v = dv;
dep_bar_asp = f3_depth_bar_aspect(depth_fmt);
has_depth = 1;
}
}
const WlVkDispatch *vk = &g->vk;
if (!g->dummy_img.inited) {
f3_img_bar(vk, cb, g->dummy_img.img, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, VK_ACCESS_TRANSFER_WRITE_BIT);
VkClearColorValue z = { .float32 = {0.f, 0.f, 0.f, 0.f} };
VkImageSubresourceRange sr = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
vk->CmdClearColorImage(cb, g->dummy_img.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &z, 1, &sr);
f3_img_bar(vk, cb, g->dummy_img.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
g->dummy_img.inited = 1;
}
int cur = (int)(g->frame_idx & 1u);
int prev = cur ^ 1;
int do_reset = g->need_reset || !g->hist_img[prev].inited || ((frame->flags & WLFSR4_FLAG_RESET) != 0);
g->need_reset = 0;
// Ensure prev history image is in a valid SHADER_READ_ONLY_OPTIMAL layout on frame 0
if (!g->hist_img[prev].inited) {
f3_img_bar(vk, cb, g->hist_img[prev].img, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, VK_ACCESS_TRANSFER_WRITE_BIT);
VkClearColorValue z = { .float32 = {0.f, 0.f, 0.f, 0.f} };
VkImageSubresourceRange sr = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
vk->CmdClearColorImage(cb, g->hist_img[prev].img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &z, 1, &sr);
f3_img_bar(vk, cb, g->hist_img[prev].img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
g->hist_img[prev].inited = 1;
}
// Bind current frame's game images into slot[cur] descriptors
VkDescriptorImageInfo c_ii = { g->sampler_nearest, color_v, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
VkDescriptorImageInfo d_ii = { g->sampler_nearest, dep_v, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
VkDescriptorImageInfo mv_ii = { g->sampler_nearest, mv_v, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
VkWriteDescriptorSet w_imgs[4] = {
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_prep[cur], .dstBinding = 0, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &c_ii },
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_prep[cur], .dstBinding = 1, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &d_ii },
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_prep[cur], .dstBinding = 2, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &mv_ii },
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_accum[cur], .dstBinding = 0, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &c_ii },
};
vk->UpdateDescriptorSets(vk->device, 4, w_imgs, 0, NULL);
// Transition game inputs -> SHADER_READ_ONLY_OPTIMAL
VkImageLayout c_old = frame->color.vk_layout ? (VkImageLayout)frame->color.vk_layout : VK_IMAGE_LAYOUT_GENERAL;
VkImageLayout m_old = frame->motion.vk_layout ? (VkImageLayout)frame->motion.vk_layout : VK_IMAGE_LAYOUT_GENERAL;
VkImageLayout d_old = frame->depth.vk_layout ? (VkImageLayout)frame->depth.vk_layout : VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
if (c_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
f3_img_bar(vk, cb, color_img, c_old, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
}
if (motion_img != VK_NULL_HANDLE && m_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
f3_img_bar(vk, cb, motion_img, m_old, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
}
if (has_depth && d_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
f3_img_bar_asp(vk, cb, depth_img, dep_bar_asp, d_old, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
}
int disp_res_mv = (frame->flags & WLFSR4_FLAG_DISPLAY_RES_MV) != 0;
float mv_res_w = (float)(disp_res_mv ? ow : rw);
float mv_res_h = (float)(disp_res_mv ? oh : rh);
float mvsx = (frame->mv_scale_x != 0.f ? frame->mv_scale_x : 1.f) / mv_res_w;
float mvsy = (frame->mv_scale_y != 0.f ? frame->mv_scale_y : 1.f) / mv_res_h;
float jcx = 0.f, jcy = 0.f;
if ((frame->flags & WLFSR4_FLAG_MV_JITTERED) && g->have_prev_jitter && !do_reset) {
jcx = (g->prev_jitter_x - frame->jitter_x) / (float)rw;
jcy = (g->prev_jitter_y - frame->jitter_y) / (float)rh;
}
g->prev_jitter_x = frame->jitter_x;
g->prev_jitter_y = frame->jitter_y;
g->have_prev_jitter = 1;
float expo = (isfinite(frame->pre_exposure) && frame->pre_exposure > 1e-4f) ? frame->pre_exposure : 1.f;
float sharp = sharpness;
if (!isfinite(sharp) || sharp < 0.0f) sharp = (isfinite(frame->sharpness) && frame->sharpness >= 0.05f) ? frame->sharpness : 0.55f;
if (sharp > 1.0f) sharp = 1.0f;
uint32_t tslot = wl_gpu_timer_begin(&g->timer, vk, cb);
uint32_t pc_flags = 0u;
if (has_depth) pc_flags |= 1u;
if (frame->flags & WLFSR4_FLAG_DEPTH_INVERTED) pc_flags |= 2u;
if (disp_res_mv) pc_flags |= 4u;
if (do_reset) pc_flags |= 8u;
F3PC pc = {
frame->jitter_x, frame->jitter_y,
mvsx, mvsy, jcx, jcy,
expo, sharp,
rw, rh, ow, oh,
pc_flags, 0u,
};
// Pass 1: Prepare & Dilate Motion Vectors (rw x rh)
f3_img_bar(vk, cb, g->dilated_mv.img,
g->dilated_mv.inited ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT);
f3_img_bar(vk, cb, g->lock_mask.img,
g->lock_mask.inited ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT);
vk->CmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pipe_prep);
vk->CmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pl_prep, 0, 1, &g->ds_prep[cur], 0, NULL);
vk->CmdPushConstants(cb, g->pl_prep, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pc, &pc);
vk->CmdDispatch(cb, (rw + 7u) / 8u, (rh + 7u) / 8u, 1u);
g->dilated_mv.inited = 1;
g->lock_mask.inited = 1;
// Pass 2: Temporal Super-Resolution Accumulation (ow x oh)
f3_img_bar(vk, cb, g->dilated_mv.img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
f3_img_bar(vk, cb, g->lock_mask.img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
f3_img_bar(vk, cb, g->hist_img[cur].img,
g->hist_img[cur].inited ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT);
vk->CmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pipe_accum);
vk->CmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pl_accum, 0, 1, &g->ds_accum[cur], 0, NULL);
vk->CmdPushConstants(cb, g->pl_accum, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pc, &pc);
vk->CmdDispatch(cb, (ow + 7u) / 8u, (oh + 7u) / 8u, 1u);
g->hist_img[cur].inited = 1;
// Pass 3: Official AMD RCAS Sharpening (ow x oh)
f3_img_bar(vk, cb, g->hist_img[cur].img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
f3_img_bar(vk, cb, g->out_img.img,
g->out_img.inited ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT);
vk->CmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pipe_rcas);
vk->CmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pl_rcas, 0, 1, &g->ds_rcas[cur], 0, NULL);
vk->CmdPushConstants(cb, g->pl_rcas, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pc, &pc);
vk->CmdDispatch(cb, (ow + 7u) / 8u, (oh + 7u) / 8u, 1u);
g->out_img.inited = 1;
// 1:1 exact pixel copy/format-convert into the game's output image (any VkFormat!)
VkImageLayout o_old = frame->output.vk_layout ? (VkImageLayout)frame->output.vk_layout : VK_IMAGE_LAYOUT_GENERAL;
f3_img_bar(vk, cb, g->out_img.img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
f3_img_bar(vk, cb, out_img, o_old, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
VkImageBlit blit = {
.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 },
.srcOffsets = { {0, 0, 0}, {(int32_t)ow, (int32_t)oh, 1} },
.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 },
.dstOffsets = { {0, 0, 0}, {(int32_t)ow, (int32_t)oh, 1} },
};
vk->CmdBlitImage(cb, g->out_img.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
out_img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
f3_img_bar(vk, cb, out_img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, o_old,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
// Restore game input layouts
if (c_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
f3_img_bar(vk, cb, color_img, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, c_old,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
}
if (motion_img != VK_NULL_HANDLE && m_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
f3_img_bar(vk, cb, motion_img, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, m_old,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
}
if (has_depth && d_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
f3_img_bar_asp(vk, cb, depth_img, dep_bar_asp, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, d_old,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
}
wl_gpu_timer_end(&g->timer, vk, cb, tslot);
g->frame_idx++;
g->dispatches++;
if (out_gpu_us) *out_gpu_us = g->timer.last_us;
if (out_dispatches) *out_dispatches = g->dispatches;
if (out_reason) *out_reason = "ok_fsr3_gpu";
return 2;
}
void wl_fsr3_gpu_destroy(WlFsr3Gpu *g) {
if (!g) return;
const WlVkDispatch *vk = &g->vk;
wl_gpu_timer_destroy(&g->timer, vk);
for (int i = 0; i < g->vcache_n; i++) {
if (g->vcache[i].view) vk->DestroyImageView(vk->device, g->vcache[i].view, NULL);
}
f3_destroy_img(vk, &g->dilated_mv);
f3_destroy_img(vk, &g->lock_mask);
f3_destroy_img(vk, &g->hist_img[0]);
f3_destroy_img(vk, &g->hist_img[1]);
f3_destroy_img(vk, &g->out_img);
f3_destroy_img(vk, &g->dummy_img);
if (g->dpool) vk->DestroyDescriptorPool(vk->device, g->dpool, NULL);
if (g->pipe_prep) vk->DestroyPipeline(vk->device, g->pipe_prep, NULL);
if (g->pipe_accum) vk->DestroyPipeline(vk->device, g->pipe_accum, NULL);
if (g->pipe_rcas) vk->DestroyPipeline(vk->device, g->pipe_rcas, NULL);
if (g->pl_prep) vk->DestroyPipelineLayout(vk->device, g->pl_prep, NULL);
if (g->pl_accum) vk->DestroyPipelineLayout(vk->device, g->pl_accum, NULL);
if (g->pl_rcas) vk->DestroyPipelineLayout(vk->device, g->pl_rcas, NULL);
if (g->dsl_prep) vk->DestroyDescriptorSetLayout(vk->device, g->dsl_prep, NULL);
if (g->dsl_accum) vk->DestroyDescriptorSetLayout(vk->device, g->dsl_accum, NULL);
if (g->dsl_rcas) vk->DestroyDescriptorSetLayout(vk->device, g->dsl_rcas, NULL);
if (g->sampler_linear) vk->DestroySampler(vk->device, g->sampler_linear, NULL);
if (g->sampler_nearest) vk->DestroySampler(vk->device, g->sampler_nearest, NULL);
free(g);
}
+37
View File
@@ -0,0 +1,37 @@
// Winlator Ludashi Native Vulkan GPU FSR 3.1 Temporal Upscaler
// Runs 100% on the Adreno GPU inside the game's VkCommandBuffer (0 NPU watts, 0 extra latency,
// full native render & output resolution, works with DLSS / XeSS / FSR 2 / FSR 3 / FSR 4 inputs).
#pragma once
#include <vulkan/vulkan.h>
#include "fsr4_pipeline.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct WlFsr3Gpu WlFsr3Gpu;
WlFsr3Gpu *wl_fsr3_gpu_create(const WlVkDispatch *vk, const char *fsr4_dir);
void wl_fsr3_gpu_destroy(WlFsr3Gpu *g);
void wl_fsr3_gpu_reset(WlFsr3Gpu *g);
int wl_fsr3_gpu_is_ready(const WlFsr3Gpu *g);
// Record one synchronous GPU FSR 3.1 temporal upscaling frame into cb.
// Returns:
// 2 = GPU FSR 3.1 path recorded
// 0 = Failed / unavailable (caller should fall back to blit)
int wl_fsr3_gpu_dispatch(WlFsr3Gpu *g, VkCommandBuffer cb,
const WlFsr4FrameDesc *frame,
VkImage color_img, VkFormat color_fmt, uint32_t cw, uint32_t ch,
VkImage depth_img, VkFormat depth_fmt,
VkImage motion_img, VkFormat motion_fmt,
VkImage out_img, uint32_t ow, uint32_t oh,
float sharpness,
uint32_t *out_gpu_us,
uint64_t *out_dispatches,
const char **out_reason);
#ifdef __cplusplus
}
#endif
+959
View File
@@ -0,0 +1,959 @@
// Winlator Ludashi AMD FSR 4.1.1 Full INT8 GPU DP4a Pipeline (28 passes)
// Ported cleanly from fsr4vk/native/fsr411-recorder.hpp + quality-context.hpp.
#define _GNU_SOURCE
#include "fsr411_full_gpu.h"
#include "fsr_gpu_timer.h"
#include "dd_upscale_compat.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define F411_TAG "DroidDeckUpscaleFSR411"
#define F411_LOGI(...) dd_upscale_log(DD_LOG_INFO, F411_TAG, __VA_ARGS__)
#define F411_LOGW(...) dd_upscale_log(DD_LOG_WARN, F411_TAG, __VA_ARGS__)
#define F411_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F411_TAG, __VA_ARGS__)
enum {
F411_UW = 1920u,
F411_UH = 1080u,
F411_DESC_COUNT = 128u,
F411_SCRATCH_BYTES = 20880256u,
F411_CONST_BYTES = 2048u,
F411_PASS_COUNT = 28u,
F411_VIEW_CACHE = 64u,
};
typedef struct {
float inv_size[2];
float scale[2];
float inv_scale[2];
float jitter[2];
float mv_scale[2];
float tex_size[2];
float max_render_size[2];
float motion_vector_jitter_cancellation[2];
uint32_t width;
uint32_t height;
uint32_t reset;
uint32_t width_lr;
uint32_t height_lr;
float pre_exposure;
float previous_pre_exposure;
uint32_t rcas_enabled;
float rcas_sharpness;
float padding;
} F411Consts;
typedef struct {
uint32_t mips;
uint32_t groups;
uint32_t offset[2];
float inverse_size[2];
float pre_exposure;
float pad;
} F411Spd;
typedef struct {
VkBuffer buf;
VkDeviceMemory mem;
VkDeviceAddress addr;
void *mapped;
VkDeviceSize size;
} F411Buf;
typedef struct {
VkImage img;
VkDeviceMemory mem;
VkImageView view;
} F411Img;
typedef struct {
int ready;
int tried;
VkPipeline pipes[F411_PASS_COUNT]; // 0 = SPD exposure, 1..27 = pre, border_0, model_1..12, border_12, post
F411Buf init_buf;
} F411Preset;
typedef struct {
VkImage img;
VkFormat fmt;
VkImageAspectFlags aspect;
VkImageView view;
} F411ViewEnt;
struct WlFsr411FullGpu {
WlVkDispatch vk;
VkPhysicalDeviceMemoryProperties memp;
VkPhysicalDeviceDescriptorBufferPropertiesEXT db_props;
char dir[512];
char fail_reason[64];
int ready;
int imgs_inited;
int need_reset;
int last_preset;
int last_preset_slot[2];
VkSampler sampler;
VkDescriptorSetLayout dsl[4];
VkPipelineLayout pipe_lay;
VkDeviceSize dsl_sizes[3], dsl_offs[3], mut_stride;
F411Buf desc_buf[2][3];
F411Buf const_buf[2];
F411Buf scratch_buf;
F411Img img_hist, img_reproj, img_recurrent, img_out;
F411Img img_exp_out, img_exp_at, img_exp_mip;
F411Preset presets[2]; // 0 = quality, 1 = performance
F411ViewEnt vcache[F411_VIEW_CACHE];
int vcache_n;
uint64_t frame_idx;
uint64_t dispatches;
float prev_pre_exp;
float prev_jx, prev_jy;
int have_prev_j;
WlGpuTimer timer;
};
static uint32_t f411_round_up(uint32_t v, uint32_t m) { return (v + m - 1u) / m * m; }
static uint32_t f411_div_up(uint32_t v, uint32_t d) { return (v + d - 1u) / d; }
static uint32_t f411_pick_mem(const VkPhysicalDeviceMemoryProperties *mp, uint32_t bits, VkMemoryPropertyFlags want) {
for (uint32_t i = 0; i < mp->memoryTypeCount; i++) {
if ((bits & (1u << i)) && (mp->memoryTypes[i].propertyFlags & want) == want) return i;
}
for (uint32_t i = 0; i < mp->memoryTypeCount; i++) {
if (bits & (1u << i)) return i;
}
return UINT32_MAX;
}
static uint8_t *f411_load_bytes(const char *path, size_t *out_sz) {
FILE *f = fopen(path, "rb");
if (!f) return NULL;
fseek(f, 0, SEEK_END);
long sz = ftell(f);
if (sz <= 0 || sz > 16L * 1024L * 1024L) { fclose(f); return NULL; }
rewind(f);
uint8_t *b = (uint8_t *)malloc((size_t)sz);
if (!b || fread(b, 1, (size_t)sz, f) != (size_t)sz) { fclose(f); free(b); return NULL; }
fclose(f);
*out_sz = (size_t)sz;
return b;
}
static int f411_make_buf(WlFsr411FullGpu *p, VkDeviceSize sz, VkBufferUsageFlags usage,
VkMemoryPropertyFlags props, int bda, int map, F411Buf *out) {
memset(out, 0, sizeof *out);
VkBufferCreateInfo bi = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.size = sz,
.usage = usage | (bda ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u),
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
};
if (p->vk.CreateBuffer(p->vk.device, &bi, NULL, &out->buf) != VK_SUCCESS) return 0;
VkMemoryRequirements mr;
p->vk.GetBufferMemoryRequirements(p->vk.device, out->buf, &mr);
uint32_t mt = f411_pick_mem(&p->memp, mr.memoryTypeBits, props);
if (mt == UINT32_MAX) { p->vk.DestroyBuffer(p->vk.device, out->buf, NULL); out->buf = VK_NULL_HANDLE; return 0; }
VkMemoryAllocateFlagsInfo afi = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, NULL, bda ? VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT : 0u, 0u };
VkMemoryAllocateInfo ai = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, bda ? &afi : NULL, mr.size, mt };
if (p->vk.AllocateMemory(p->vk.device, &ai, NULL, &out->mem) != VK_SUCCESS ||
p->vk.BindBufferMemory(p->vk.device, out->buf, out->mem, 0) != VK_SUCCESS) {
if (out->mem) p->vk.FreeMemory(p->vk.device, out->mem, NULL);
p->vk.DestroyBuffer(p->vk.device, out->buf, NULL);
memset(out, 0, sizeof *out);
return 0;
}
if (map && p->vk.MapMemory(p->vk.device, out->mem, 0, sz, 0, &out->mapped) != VK_SUCCESS) {
p->vk.FreeMemory(p->vk.device, out->mem, NULL);
p->vk.DestroyBuffer(p->vk.device, out->buf, NULL);
memset(out, 0, sizeof *out);
return 0;
}
if (bda && p->vk.GetBufferDeviceAddress) {
VkBufferDeviceAddressInfo bdi = { VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, NULL, out->buf };
out->addr = p->vk.GetBufferDeviceAddress(p->vk.device, &bdi);
}
out->size = sz;
return 1;
}
static void f411_free_buf(WlFsr411FullGpu *p, F411Buf *b) {
if (b->mapped && b->mem) p->vk.UnmapMemory(p->vk.device, b->mem);
if (b->buf) p->vk.DestroyBuffer(p->vk.device, b->buf, NULL);
if (b->mem) p->vk.FreeMemory(p->vk.device, b->mem, NULL);
memset(b, 0, sizeof *b);
}
static int f411_make_img(WlFsr411FullGpu *p, uint32_t w, uint32_t h, VkFormat fmt, VkImageUsageFlags usage, F411Img *out) {
memset(out, 0, sizeof *out);
VkImageCreateInfo ci = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.imageType = VK_IMAGE_TYPE_2D, .format = fmt, .extent = {w, h, 1},
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL, .usage = usage,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
if (p->vk.CreateImage(p->vk.device, &ci, NULL, &out->img) != VK_SUCCESS) return 0;
VkMemoryRequirements mr;
p->vk.GetImageMemoryRequirements(p->vk.device, out->img, &mr);
uint32_t mt = f411_pick_mem(&p->memp, mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
if (mt == UINT32_MAX) return 0;
VkMemoryAllocateInfo ai = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, mr.size, mt };
if (p->vk.AllocateMemory(p->vk.device, &ai, NULL, &out->mem) != VK_SUCCESS ||
p->vk.BindImageMemory(p->vk.device, out->img, out->mem, 0) != VK_SUCCESS) return 0;
VkImageViewCreateInfo vi = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.image = out->img, .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = fmt,
.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 },
};
if (p->vk.CreateImageView(p->vk.device, &vi, NULL, &out->view) != VK_SUCCESS) return 0;
return 1;
}
static void f411_free_img(WlFsr411FullGpu *p, F411Img *im) {
if (im->view) p->vk.DestroyImageView(p->vk.device, im->view, NULL);
if (im->img) p->vk.DestroyImage(p->vk.device, im->img, NULL);
if (im->mem) p->vk.FreeMemory(p->vk.device, im->mem, NULL);
memset(im, 0, sizeof *im);
}
static void f411_write_img_desc(WlFsr411FullGpu *p, int slot, uint32_t idx, VkDescriptorType ty, VkImageView view) {
VkDescriptorImageInfo ii = { VK_NULL_HANDLE, view,
(ty == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
VkDescriptorGetInfoEXT gi = { VK_STRUCTURE_TYPE_DESCRIPTOR_GET_INFO_EXT, NULL, ty, { .pSampledImage = &ii } };
if (ty == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) gi.data.pStorageImage = &ii;
size_t dsz = (ty == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) ? p->db_props.storageImageDescriptorSize
: p->db_props.sampledImageDescriptorSize;
uint8_t *dst = (uint8_t *)p->desc_buf[slot][1].mapped + p->dsl_offs[1] + (VkDeviceSize)idx * p->mut_stride;
p->vk.GetDescriptorEXT(p->vk.device, &gi, dsz, dst);
}
static void f411_write_buf_desc(WlFsr411FullGpu *p, int slot, uint32_t idx, const F411Buf *b) {
VkDescriptorAddressInfoEXT ai = { VK_STRUCTURE_TYPE_DESCRIPTOR_ADDRESS_INFO_EXT, NULL, b->addr, b->size, VK_FORMAT_UNDEFINED };
VkDescriptorGetInfoEXT gi = { VK_STRUCTURE_TYPE_DESCRIPTOR_GET_INFO_EXT, NULL, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, { .pStorageBuffer = &ai } };
size_t bsz = p->db_props.storageBufferDescriptorSize;
uint8_t *dst = (uint8_t *)p->desc_buf[slot][2].mapped + p->dsl_offs[2] + (VkDeviceSize)idx * p->mut_stride;
p->vk.GetDescriptorEXT(p->vk.device, &gi, bsz, dst);
}
// Guard 4.1.1 prepass (pass-01.spv) 2x2 quad reduction against inactive edge lanes (fsr411-quad-bounds.hpp)
static uint32_t *f411_guard_prepass_quads(uint32_t *w, size_t *io_words) {
size_t nwords = *io_words;
if (!w || nwords < 5u || w[0] != 0x07230203u || w[3] > 0xffffff00u) return w;
int local = 0, has_x = 0, has_y = 0, quad = 0;
uint32_t u = 0;
size_t fn_pos = 0, xc = 0, yc = 0;
for (size_t i = 5u; i < nwords; ) {
uint32_t n = w[i] >> 16, op = w[i] & 0xffffu;
if (!n || n > nwords - i) return w;
if (op == 16u && n == 6u && w[i + 2] == 17u && w[i + 3] == 256u && w[i + 4] == 1u && w[i + 5] == 1u) local = 1;
if (op == 81u && n == 5u && w[i + 2] == 81u && w[i + 3] == 80u && w[i + 4] == 0u) { has_x = 1; u = w[i + 1]; }
if (op == 81u && n == 5u && w[i + 2] == 84u && w[i + 3] == 80u && w[i + 4] == 1u) has_y = 1;
if (op == 176u && n == 5u && w[i + 2] == 83u && w[i + 3] == 71u && w[i + 4] == 81u) xc = i;
if (op == 176u && n == 5u && w[i + 2] == 85u && w[i + 3] == 72u && w[i + 4] == 84u) yc = i;
if (op == 366u) quad = 1;
if (op == 54u && !fn_pos) fn_pos = i;
i += n;
}
if (!local || !has_x || !has_y || !quad || !fn_pos || !xc || !yc || !u) return w;
uint32_t *out = (uint32_t *)malloc((nwords + 16u) * sizeof(uint32_t));
if (!out) return w;
uint32_t mask = w[3]++, width_id = w[3]++, height_id = w[3]++;
memcpy(out, w, 5u * sizeof(uint32_t));
size_t pos = 5u;
for (size_t i = 5u; i < nwords; ) {
uint32_t n = w[i] >> 16;
if (i == fn_pos) {
out[pos++] = (4u << 16) | 43u;
out[pos++] = u;
out[pos++] = mask;
out[pos++] = 0xfffffffeu;
}
if (i == xc || i == yc) {
out[pos++] = (5u << 16) | 199u;
out[pos++] = u;
out[pos++] = (i == xc) ? width_id : height_id;
out[pos++] = (i == xc) ? 81u : 84u;
out[pos++] = mask;
}
size_t start = pos;
memcpy(out + pos, w + i, n * sizeof(uint32_t));
pos += n;
if (i == xc || i == yc) out[start + 4u] = (i == xc) ? width_id : height_id;
i += n;
}
free(w);
*io_words = pos;
return out;
}
static VkPipeline f411_make_pipe(WlFsr411FullGpu *p, const char *path, int guard_quads) {
size_t sz = 0;
uint8_t *code = f411_load_bytes(path, &sz);
if (!code || (sz & 3u) != 0) { free(code); return VK_NULL_HANDLE; }
uint32_t *words = (uint32_t *)code;
size_t nwords = sz / 4u;
if (guard_quads) words = f411_guard_prepass_quads(words, &nwords);
VkShaderModuleCreateInfo smi = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, nwords * 4u, words };
VkShaderModule sm = VK_NULL_HANDLE;
VkResult r = p->vk.CreateShaderModule(p->vk.device, &smi, NULL, &sm);
free(words);
if (r != VK_SUCCESS || !sm) return VK_NULL_HANDLE;
VkComputePipelineCreateInfo ci = {
.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.flags = VK_PIPELINE_CREATE_DESCRIPTOR_BUFFER_BIT_EXT,
.stage = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_COMPUTE_BIT, sm, "main", NULL },
.layout = p->pipe_lay,
};
VkPipeline pipe = VK_NULL_HANDLE;
r = p->vk.CreateComputePipelines(p->vk.device, VK_NULL_HANDLE, 1, &ci, NULL, &pipe);
p->vk.DestroyShaderModule(p->vk.device, sm, NULL);
return (r == VK_SUCCESS) ? pipe : VK_NULL_HANDLE;
}
static int f411_load_preset(WlFsr411FullGpu *p, int idx) {
F411Preset *pr = &p->presets[idx];
if (pr->ready) return 1;
if (pr->tried) return 0;
pr->tried = 1;
const char *pname = (idx == 0) ? "quality" : "performance";
char path[640];
snprintf(path, sizeof path, "%s/fsr411_full/%s/initializers.bin", p->dir, pname);
size_t isz = 0;
uint8_t *idata = f411_load_bytes(path, &isz);
if (!idata) {
snprintf(p->fail_reason, sizeof p->fail_reason, "missing_411_full_%s", pname);
return 0;
}
if (!f411_make_buf(p, isz, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1, 1, &pr->init_buf)) {
free(idata);
snprintf(p->fail_reason, sizeof p->fail_reason, "411_init_buf_fail");
return 0;
}
memcpy(pr->init_buf.mapped, idata, isz);
free(idata);
for (uint32_t i = 0; i < F411_PASS_COUNT; i++) {
snprintf(path, sizeof path, "%s/fsr411_full/%s/pass-%02u.spv", p->dir, pname, i);
pr->pipes[i] = f411_make_pipe(p, path, (i == 1u) ? 1 : 0);
if (!pr->pipes[i]) {
snprintf(p->fail_reason, sizeof p->fail_reason, "411_pipe_%s_%02u", pname, i);
F411_LOGE("Failed to build FSR 4.1.1 Full pipeline %s", path);
for (uint32_t j = 0; j < i; j++) {
if (pr->pipes[j]) p->vk.DestroyPipeline(p->vk.device, pr->pipes[j], NULL);
pr->pipes[j] = VK_NULL_HANDLE;
}
f411_free_buf(p, &pr->init_buf);
return 0;
}
}
pr->ready = 1;
F411_LOGI("AMD FSR 4.1.1 Full INT8 GPU (%s, 28 passes) READY!", pname);
return 1;
}
WlFsr411FullGpu *wl_fsr411_full_gpu_create(const WlVkDispatch *vk, const char *fsr4_dir) {
if (!vk || !vk->device || !fsr4_dir) return NULL;
WlFsr411FullGpu *p = (WlFsr411FullGpu *)calloc(1, sizeof *p);
if (!p) return NULL;
p->vk = *vk;
snprintf(p->dir, sizeof p->dir, "%s", fsr4_dir);
p->last_preset = -1;
p->last_preset_slot[0] = p->last_preset_slot[1] = -1;
wl_gpu_timer_init(&p->timer, vk);
if (!vk->has_desc_buf || !vk->has_mut_desc || !vk->has_bda || !vk->has_f16 || !vk->has_i8 ||
!vk->has_int_dot || !vk->has_compute_derivs || !vk->has_sync2 ||
!vk->GetDescriptorSetLayoutSizeEXT || !vk->GetDescriptorEXT ||
!vk->CmdBindDescriptorBuffersEXT || !vk->CmdSetDescriptorBufferOffsetsEXT ||
!vk->CmdBindDescriptorBufferEmbeddedSamplersEXT || !vk->CmdPipelineBarrier2) {
snprintf(p->fail_reason, sizeof p->fail_reason, "missing_vk_db_%d_i8_%d_dot_%d_deriv_%d",
vk->has_desc_buf, vk->has_i8, vk->has_int_dot, vk->has_compute_derivs);
F411_LOGW("FSR 4.1.1 Full GPU unavailable on this driver (%s) — will fall back to FSR 4.1.2 Lite / FSR 3.1",
p->fail_reason);
return p;
}
// On Turnip (Mesa's Adreno driver) this descriptor-buffer path runs but writes a black frame (Elite,
// Adreno 830, Nov 2026); FSR 4.1.2 Lite (classic descriptors) works there. Lite stands in until this path
// gets classic descriptors too. DROIDDECK_UPSCALE_FULL_ON_TURNIP=1 runs it anyway, for testing.
{
VkPhysicalDeviceDriverProperties drv = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES };
VkPhysicalDeviceProperties2 dp2 = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &drv };
vk->GetPhysicalDeviceProperties2(vk->phys_dev, &dp2);
const char *force = dd_upscale_env("FULL_ON_TURNIP");
if (drv.driverID == VK_DRIVER_ID_MESA_TURNIP && !(force && force[0] == '1')) {
snprintf(p->fail_reason, sizeof p->fail_reason, "full_black_on_turnip_lite_used");
F411_LOGW("FSR 4.1.1 Full GPU off on Turnip (black output) - FSR 4.1.2 Lite stands in");
return p;
}
}
vk->GetPhysicalDeviceMemoryProperties(vk->phys_dev, &p->memp);
memset(&p->db_props, 0, sizeof p->db_props);
p->db_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_BUFFER_PROPERTIES_EXT;
VkPhysicalDeviceProperties2 p2 = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &p->db_props };
vk->GetPhysicalDeviceProperties2(vk->phys_dev, &p2);
size_t m = p->db_props.uniformBufferDescriptorSize;
if (p->db_props.storageBufferDescriptorSize > m) m = p->db_props.storageBufferDescriptorSize;
if (p->db_props.sampledImageDescriptorSize > m) m = p->db_props.sampledImageDescriptorSize;
if (p->db_props.storageImageDescriptorSize > m) m = p->db_props.storageImageDescriptorSize;
if (p->db_props.uniformTexelBufferDescriptorSize > m) m = p->db_props.uniformTexelBufferDescriptorSize;
if (p->db_props.storageTexelBufferDescriptorSize > m) m = p->db_props.storageTexelBufferDescriptorSize;
p->mut_stride = m;
VkSamplerCreateInfo sci = {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.magFilter = VK_FILTER_LINEAR, .minFilter = VK_FILTER_LINEAR,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.maxAnisotropy = 16.0f,
.compareOp = VK_COMPARE_OP_NEVER,
.maxLod = 1e30f,
.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK,
};
if (vk->CreateSampler(vk->device, &sci, NULL, &p->sampler) != VK_SUCCESS) {
snprintf(p->fail_reason, sizeof p->fail_reason, "411_sampler_fail"); return p;
}
// Exact fsr4vk/quality-context.hpp descriptor set layouts:
// Set 0: binding 0 = SAMPLER[128] (variable descriptor count)
// Set 1: binding 0 = STORAGE_BUFFER[4], binding 1 = MUTABLE[128] (images!)
// Set 2: binding 0 = MUTABLE[128] (buffers!)
// Set 3: binding 0 = embedded immutable SAMPLER[1]
VkDescriptorBindingFlags var_flag = VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT;
VkDescriptorSetLayoutBinding b0 = { 0, VK_DESCRIPTOR_TYPE_SAMPLER, F411_DESC_COUNT, VK_SHADER_STAGE_COMPUTE_BIT, NULL };
VkDescriptorSetLayoutBindingFlagsCreateInfo bf0 = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO, NULL, 1, &var_flag
};
VkDescriptorSetLayoutCreateInfo d0 = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, &bf0,
VK_DESCRIPTOR_SET_LAYOUT_CREATE_DESCRIPTOR_BUFFER_BIT_EXT, 1, &b0
};
static const VkDescriptorType k_mut_types[6] = {
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER
};
VkMutableDescriptorTypeListEXT ml = { 6, k_mut_types };
VkDescriptorSetLayoutBinding b1[2] = {
{ 0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
{ 1, VK_DESCRIPTOR_TYPE_MUTABLE_EXT, F411_DESC_COUNT, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
};
VkDescriptorBindingFlags bf1_vals[2] = { 0, var_flag };
VkMutableDescriptorTypeListEXT ml1[2] = { { 0, NULL }, ml };
VkMutableDescriptorTypeCreateInfoEXT mi1 = {
VK_STRUCTURE_TYPE_MUTABLE_DESCRIPTOR_TYPE_CREATE_INFO_EXT, NULL, 2, ml1
};
VkDescriptorSetLayoutBindingFlagsCreateInfo bf1 = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO, &mi1, 2, bf1_vals
};
VkDescriptorSetLayoutCreateInfo d1 = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, &bf1,
VK_DESCRIPTOR_SET_LAYOUT_CREATE_DESCRIPTOR_BUFFER_BIT_EXT, 2, b1
};
VkMutableDescriptorTypeCreateInfoEXT mi2 = {
VK_STRUCTURE_TYPE_MUTABLE_DESCRIPTOR_TYPE_CREATE_INFO_EXT, NULL, 1, &ml
};
VkDescriptorSetLayoutBindingFlagsCreateInfo bf2 = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO, &mi2, 1, &var_flag
};
VkDescriptorSetLayoutBinding b2 = { 0, VK_DESCRIPTOR_TYPE_MUTABLE_EXT, F411_DESC_COUNT, VK_SHADER_STAGE_COMPUTE_BIT, NULL };
VkDescriptorSetLayoutCreateInfo d2 = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, &bf2,
VK_DESCRIPTOR_SET_LAYOUT_CREATE_DESCRIPTOR_BUFFER_BIT_EXT, 1, &b2
};
VkDescriptorSetLayoutBinding b3 = { 0, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, &p->sampler };
VkDescriptorSetLayoutCreateInfo d3 = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL,
VK_DESCRIPTOR_SET_LAYOUT_CREATE_DESCRIPTOR_BUFFER_BIT_EXT | VK_DESCRIPTOR_SET_LAYOUT_CREATE_EMBEDDED_IMMUTABLE_SAMPLERS_BIT_EXT,
1, &b3
};
if (vk->CreateDescriptorSetLayout(vk->device, &d0, NULL, &p->dsl[0]) != VK_SUCCESS ||
vk->CreateDescriptorSetLayout(vk->device, &d1, NULL, &p->dsl[1]) != VK_SUCCESS ||
vk->CreateDescriptorSetLayout(vk->device, &d2, NULL, &p->dsl[2]) != VK_SUCCESS ||
vk->CreateDescriptorSetLayout(vk->device, &d3, NULL, &p->dsl[3]) != VK_SUCCESS) {
snprintf(p->fail_reason, sizeof p->fail_reason, "411_dsl_fail"); return p;
}
VkPushConstantRange pcr = { VK_SHADER_STAGE_COMPUTE_BIT, 0, 24 };
VkPipelineLayoutCreateInfo plci = {
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, NULL, 0, 4, p->dsl, 1, &pcr
};
if (vk->CreatePipelineLayout(vk->device, &plci, NULL, &p->pipe_lay) != VK_SUCCESS) {
snprintf(p->fail_reason, sizeof p->fail_reason, "411_pl_fail"); return p;
}
static const uint32_t k_desc_bindings[3] = { 0u, 1u, 0u };
VkDeviceSize align = p->db_props.descriptorBufferOffsetAlignment ? p->db_props.descriptorBufferOffsetAlignment : 64u;
for (int i = 0; i < 3; i++) {
vk->GetDescriptorSetLayoutSizeEXT(vk->device, p->dsl[i], &p->dsl_sizes[i]);
vk->GetDescriptorSetLayoutBindingOffsetEXT(vk->device, p->dsl[i], k_desc_bindings[i], &p->dsl_offs[i]);
p->dsl_sizes[i] = (p->dsl_sizes[i] + align - 1u) / align * align;
}
for (int s = 0; s < 2; s++) {
for (int i = 0; i < 3; i++) {
VkBufferUsageFlags u = (i == 0) ? VK_BUFFER_USAGE_SAMPLER_DESCRIPTOR_BUFFER_BIT_EXT
: VK_BUFFER_USAGE_RESOURCE_DESCRIPTOR_BUFFER_BIT_EXT;
if (!f411_make_buf(p, p->dsl_sizes[i], u,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1, 1, &p->desc_buf[s][i])) {
snprintf(p->fail_reason, sizeof p->fail_reason, "411_dbuf_fail"); return p;
}
memset(p->desc_buf[s][i].mapped, 0, (size_t)p->dsl_sizes[i]);
}
if (!f411_make_buf(p, F411_CONST_BYTES, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1, 1, &p->const_buf[s])) {
snprintf(p->fail_reason, sizeof p->fail_reason, "411_cbuf_fail"); return p;
}
}
if (!f411_make_buf(p, F411_SCRATCH_BYTES, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 1, 0, &p->scratch_buf)) {
snprintf(p->fail_reason, sizeof p->fail_reason, "411_scratch_fail"); return p;
}
VkImageUsageFlags iu = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
if (!f411_make_img(p, F411_UW, F411_UH, VK_FORMAT_R16G16B16A16_SFLOAT, iu, &p->img_hist) ||
!f411_make_img(p, F411_UW, F411_UH, VK_FORMAT_R16G16B16A16_SFLOAT, iu, &p->img_reproj) ||
!f411_make_img(p, F411_UW, F411_UH, VK_FORMAT_R8G8B8A8_UNORM, iu, &p->img_recurrent) ||
!f411_make_img(p, F411_UW, F411_UH, VK_FORMAT_R16G16B16A16_SFLOAT, iu | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, &p->img_out) ||
!f411_make_img(p, 2u, 1u, VK_FORMAT_R32_SFLOAT, iu, &p->img_exp_out) ||
!f411_make_img(p, 1u, 1u, VK_FORMAT_R32_UINT, iu, &p->img_exp_at) ||
!f411_make_img(p, f411_div_up(F411_UW, 16u), f411_div_up(F411_UH, 16u), VK_FORMAT_R32_SFLOAT, iu, &p->img_exp_mip)) {
snprintf(p->fail_reason, sizeof p->fail_reason, "411_img_fail"); return p;
}
// Exact fsr4vk/quality-context.hpp Set 2 buffer bindings:
// index 11 = scratch (pre + model_1..12), index 30 = initializer (per preset), index 62 = scratch (post u11)
for (int s = 0; s < 2; s++) {
f411_write_buf_desc(p, s, 11u, &p->scratch_buf);
f411_write_buf_desc(p, s, 62u, &p->scratch_buf);
}
p->ready = 1;
p->need_reset = 1;
return p;
}
void wl_fsr411_full_gpu_reset(WlFsr411FullGpu *p) {
if (!p) return;
p->need_reset = 1;
p->have_prev_j = 0;
}
int wl_fsr411_full_gpu_is_ready(const WlFsr411FullGpu *p) { return p && p->ready; }
const char *wl_fsr411_full_gpu_fail_reason(const WlFsr411FullGpu *p) {
return (p && p->fail_reason[0]) ? p->fail_reason : "ok";
}
static VkImageView f411_get_view(WlFsr411FullGpu *p, VkImage img, VkFormat fmt, VkImageAspectFlags asp) {
for (int i = 0; i < p->vcache_n; i++) {
if (p->vcache[i].img == img && p->vcache[i].fmt == fmt && p->vcache[i].aspect == asp)
return p->vcache[i].view;
}
VkImageViewCreateInfo ci = {
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, NULL, 0, img, VK_IMAGE_VIEW_TYPE_2D, fmt,
{0,0,0,0}, { asp, 0, 1, 0, 1 }
};
VkImageView v = VK_NULL_HANDLE;
if (p->vk.CreateImageView(p->vk.device, &ci, NULL, &v) != VK_SUCCESS) return VK_NULL_HANDLE;
if (p->vcache_n < F411_VIEW_CACHE) p->vcache[p->vcache_n++] = (F411ViewEnt){ img, fmt, asp, v };
return v;
}
static void f411_img_bar2(WlFsr411FullGpu *p, VkCommandBuffer cb, VkImage img, VkImageAspectFlags asp,
VkImageLayout oldL, VkImageLayout newL,
VkPipelineStageFlags2 srcS, VkAccessFlags2 srcA,
VkPipelineStageFlags2 dstS, VkAccessFlags2 dstA) {
VkImageMemoryBarrier2 b = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.srcStageMask = srcS, .srcAccessMask = srcA,
.dstStageMask = dstS, .dstAccessMask = dstA,
.oldLayout = oldL, .newLayout = newL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = img, .subresourceRange = { asp, 0, 1, 0, 1 },
};
VkDependencyInfo dep = { VK_STRUCTURE_TYPE_DEPENDENCY_INFO, NULL, 0, 0, NULL, 0, NULL, 1, &b };
p->vk.CmdPipelineBarrier2(cb, &dep);
}
static void f411_compute_bar2(WlFsr411FullGpu *p, VkCommandBuffer cb) {
VkMemoryBarrier2 mb = {
.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
.srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
.srcAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
.dstAccessMask = VK_ACCESS_2_SHADER_READ_BIT | VK_ACCESS_2_SHADER_WRITE_BIT,
};
VkDependencyInfo dep = { VK_STRUCTURE_TYPE_DEPENDENCY_INFO, NULL, 0, 1, &mb, 0, NULL, 0, NULL };
p->vk.CmdPipelineBarrier2(cb, &dep);
}
static VkImageAspectFlags f411_dep_asp(VkFormat fmt) {
switch (fmt) {
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
default:
return VK_IMAGE_ASPECT_DEPTH_BIT;
}
}
int wl_fsr411_full_gpu_dispatch(WlFsr411FullGpu *p, VkCommandBuffer cb,
const WlFsr4FrameDesc *frame,
VkImage color_img, VkFormat color_fmt,
VkImage depth_img, VkFormat depth_fmt,
VkImage motion_img, VkFormat motion_fmt,
VkImage out_img, uint32_t ow, uint32_t oh,
float sharpness,
uint32_t *out_gpu_us,
uint64_t *out_dispatches,
const char **out_reason) {
if (!p || !p->ready || !frame || !color_img || !depth_img || !motion_img || !out_img) {
if (out_reason) *out_reason = (p && p->fail_reason[0]) ? p->fail_reason : "411_full_unavailable";
return 0;
}
uint32_t rw = frame->render_w, rh = frame->render_h;
if (rw < 320u || rh < 180u || rw > F411_UW || rh > F411_UH) {
if (out_reason) *out_reason = "411_full_res_unsupported";
return 0;
}
int preset = (ow * 10u >= rw * 18u) ? 1 : 0; // >=1.8x -> performance, else quality
if (!f411_load_preset(p, preset)) {
// Try alternate preset if one is missing
if (!f411_load_preset(p, preset ^ 1)) {
if (out_reason) *out_reason = p->fail_reason;
return 0;
}
preset ^= 1;
}
F411Preset *pr = &p->presets[preset];
VkImageView vcol = frame->color.vk_view ? (VkImageView)(uintptr_t)frame->color.vk_view
: f411_get_view(p, color_img, color_fmt, VK_IMAGE_ASPECT_COLOR_BIT);
VkImageView vdep = frame->depth.vk_view ? (VkImageView)(uintptr_t)frame->depth.vk_view
: f411_get_view(p, depth_img, depth_fmt, VK_IMAGE_ASPECT_DEPTH_BIT);
VkImageView vmv = frame->motion.vk_view ? (VkImageView)(uintptr_t)frame->motion.vk_view
: f411_get_view(p, motion_img, motion_fmt, VK_IMAGE_ASPECT_COLOR_BIT);
if (!vcol || !vdep || !vmv) {
if (out_reason) *out_reason = "411_view_fail";
return 0;
}
uint32_t tslot = wl_gpu_timer_begin(&p->timer, &p->vk, cb);
int slot = (int)(p->frame_idx & 1u);
if (p->last_preset_slot[slot] != preset) {
f411_write_buf_desc(p, slot, 30u, &pr->init_buf);
p->last_preset_slot[slot] = preset;
}
int first_imgs = !p->imgs_inited;
int do_reset = first_imgs || p->need_reset || ((frame->flags & WLFSR4_FLAG_RESET) != 0) ||
(p->last_preset >= 0 && p->last_preset != preset);
p->need_reset = 0;
int disp_res_mv = (frame->flags & WLFSR4_FLAG_DISPLAY_RES_MV) != 0;
float mv_w = (float)(disp_res_mv ? ow : rw);
float mv_h = (float)(disp_res_mv ? oh : rh);
float mvsx = (frame->mv_scale_x != 0.0f ? frame->mv_scale_x : 1.0f) / mv_w;
float mvsy = (frame->mv_scale_y != 0.0f ? frame->mv_scale_y : 1.0f) / mv_h;
float jcx = 0.0f, jcy = 0.0f;
if ((frame->flags & WLFSR4_FLAG_MV_JITTERED) && p->have_prev_j && !do_reset) {
jcx = (p->prev_jx - frame->jitter_x) / (float)rw;
jcy = (p->prev_jy - frame->jitter_y) / (float)rh;
}
p->prev_jx = frame->jitter_x; p->prev_jy = frame->jitter_y; p->have_prev_j = 1;
float pe = (isfinite(frame->pre_exposure) && frame->pre_exposure > 1e-4f) ? frame->pre_exposure : 1.0f;
float sh = sharpness;
if (!isfinite(sh) || sh < 0.0f) sh = (isfinite(frame->sharpness) && frame->sharpness > 0.01f) ? frame->sharpness : 0.55f;
if (sh > 1.0f) sh = 1.0f;
F411Consts k;
memset(&k, 0, sizeof k);
k.inv_size[0] = 1.0f / F411_UW; k.inv_size[1] = 1.0f / F411_UH;
k.scale[0] = (float)F411_UW / (float)rw; k.scale[1] = (float)F411_UH / (float)rh;
k.inv_scale[0] = 1.0f / k.scale[0]; k.inv_scale[1] = 1.0f / k.scale[1];
k.jitter[0] = frame->jitter_x; k.jitter[1] = frame->jitter_y;
k.mv_scale[0] = mvsx; k.mv_scale[1] = mvsy;
k.tex_size[0] = (float)F411_UW; k.tex_size[1] = (float)F411_UH;
k.max_render_size[0] = (float)rw; k.max_render_size[1] = (float)rh;
k.motion_vector_jitter_cancellation[0] = jcx;
k.motion_vector_jitter_cancellation[1] = jcy;
k.width = F411_UW; k.height = F411_UH;
k.reset = do_reset ? 1u : 0u;
k.width_lr = rw; k.height_lr = rh;
k.pre_exposure = pe;
k.previous_pre_exposure = (do_reset || p->prev_pre_exp <= 0.0f) ? pe : p->prev_pre_exp;
// pass-27.spv skips inverse Mu-Law de-log if rcas_enabled != 0 (leaving raw log-space grey washout)
k.rcas_enabled = 0u;
k.rcas_sharpness = 0.0f;
(void)sh;
p->prev_pre_exp = pe;
uint32_t mips = 0;
for (uint32_t sz = rw > rh ? rw : rh; sz > 1u; sz >>= 1u) mips++;
if (mips > 12u) mips = 12u;
F411Spd spd = { mips, f411_div_up(rw, 64u) * f411_div_up(rh, 64u), {0, 0}, {1.0f / (float)rw, 1.0f / (float)rh}, pe, 0.0f };
static const uint32_t k_div[17] = { 2,1,2,2,4,4,4,8,8,8,4,4,2,2,1,1,1 };
static const uint32_t k_bdiv[13] = { 2,2,2,4,4,4,8,8,8,4,4,2,2 };
uint32_t tensors[17][4];
memset(tensors, 0, sizeof tensors);
uint32_t aw = f411_round_up(F411_UW, 8u), ah = f411_round_up(F411_UH, 8u);
for (int i = 0; i < 17; i++) {
tensors[i][0] = aw / k_div[i];
tensors[i][1] = ah / k_div[i];
}
uint8_t *cm = (uint8_t *)p->const_buf[slot].mapped;
memset(cm, 0, F411_CONST_BYTES);
memcpy(cm, &k, sizeof k);
memcpy(cm + 512, &spd, sizeof spd);
memcpy(cm + 1024, tensors, sizeof tensors);
f411_write_img_desc(p, slot, 12u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, p->img_hist.view);
f411_write_img_desc(p, slot, 13u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, vmv);
f411_write_img_desc(p, slot, 14u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, vdep);
f411_write_img_desc(p, slot, 15u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, vcol);
f411_write_img_desc(p, slot, 16u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, p->img_recurrent.view);
f411_write_img_desc(p, slot, 29u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, p->img_exp_out.view);
f411_write_img_desc(p, slot, 3u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, p->img_reproj.view);
f411_write_img_desc(p, slot, 66u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, vcol);
f411_write_img_desc(p, slot, 72u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, p->img_reproj.view);
f411_write_img_desc(p, slot, 80u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, p->img_exp_out.view);
f411_write_img_desc(p, slot, 52u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, p->img_hist.view);
f411_write_img_desc(p, slot, 53u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, p->img_out.view);
f411_write_img_desc(p, slot, 57u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, p->img_recurrent.view);
f411_write_img_desc(p, slot, 90u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, p->img_exp_at.view);
f411_write_img_desc(p, slot, 91u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, p->img_exp_mip.view);
f411_write_img_desc(p, slot, 92u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, p->img_exp_out.view);
f411_write_img_desc(p, slot, 93u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, vcol);
if (first_imgs) {
VkClearColorValue z; memset(&z, 0, sizeof z);
VkImageSubresourceRange rng = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
VkImage all[7] = { p->img_hist.img, p->img_reproj.img, p->img_recurrent.img, p->img_out.img,
p->img_exp_out.img, p->img_exp_at.img, p->img_exp_mip.img };
for (int i = 0; i < 7; i++) {
f411_img_bar2(p, cb, all[i], VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_PIPELINE_STAGE_2_NONE, 0, VK_PIPELINE_STAGE_2_CLEAR_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT);
p->vk.CmdClearColorImage(cb, all[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &z, 1, &rng);
}
f411_img_bar2(p, cb, p->img_hist.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_2_CLEAR_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
f411_img_bar2(p, cb, p->img_recurrent.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_2_CLEAR_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
for (int i = 0; i < 5; i++) {
VkImage gims[5] = { p->img_reproj.img, p->img_exp_out.img, p->img_exp_at.img, p->img_exp_mip.img, p->img_out.img };
f411_img_bar2(p, cb, gims[i], VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_2_CLEAR_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
VK_ACCESS_2_SHADER_STORAGE_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT);
}
p->imgs_inited = 1;
} else {
f411_img_bar2(p, cb, p->img_exp_out.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT);
f411_img_bar2(p, cb, p->img_hist.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
f411_img_bar2(p, cb, p->img_recurrent.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
f411_img_bar2(p, cb, p->img_reproj.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT);
}
// Per-frame zero-clear of scratch buffer + host->compute descriptor/const visibility (quality-context.hpp:906-919)
{
VkMemoryBarrier2 sb = {
.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
.srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT,
.srcAccessMask = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_CLEAR_BIT,
.dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
};
VkDependencyInfo dep = { VK_STRUCTURE_TYPE_DEPENDENCY_INFO, NULL, 0, 1, &sb, 0, NULL, 0, NULL };
p->vk.CmdPipelineBarrier2(cb, &dep);
p->vk.CmdFillBuffer(cb, p->scratch_buf.buf, 0, VK_WHOLE_SIZE, 0u);
sb.srcStageMask = VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_HOST_BIT;
sb.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT | VK_ACCESS_2_HOST_WRITE_BIT;
sb.dstStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT;
sb.dstAccessMask = VK_ACCESS_2_SHADER_READ_BIT | VK_ACCESS_2_SHADER_WRITE_BIT | VK_ACCESS_2_DESCRIPTOR_BUFFER_READ_BIT_EXT;
p->vk.CmdPipelineBarrier2(cb, &dep);
}
VkImageLayout c_old = frame->color.vk_layout ? (VkImageLayout)frame->color.vk_layout : VK_IMAGE_LAYOUT_GENERAL;
VkImageLayout d_old = frame->depth.vk_layout ? (VkImageLayout)frame->depth.vk_layout : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
VkImageLayout m_old = frame->motion.vk_layout ? (VkImageLayout)frame->motion.vk_layout : VK_IMAGE_LAYOUT_GENERAL;
VkImageLayout o_old = frame->output.vk_layout ? (VkImageLayout)frame->output.vk_layout : VK_IMAGE_LAYOUT_GENERAL;
VkImageAspectFlags dep_asp = f411_dep_asp(depth_fmt);
f411_img_bar2(p, cb, color_img, VK_IMAGE_ASPECT_COLOR_BIT, c_old, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
f411_img_bar2(p, cb, depth_img, dep_asp, d_old, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
f411_img_bar2(p, cb, motion_img, VK_IMAGE_ASPECT_COLOR_BIT, m_old, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
// Bind 3 descriptor buffers + embedded sampler set
VkDescriptorBufferBindingInfoEXT dbi[3];
for (int i = 0; i < 3; i++) {
dbi[i] = (VkDescriptorBufferBindingInfoEXT){
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_BUFFER_BINDING_INFO_EXT,
.address = p->desc_buf[slot][i].addr,
.usage = (i == 0) ? VK_BUFFER_USAGE_SAMPLER_DESCRIPTOR_BUFFER_BIT_EXT
: VK_BUFFER_USAGE_RESOURCE_DESCRIPTOR_BUFFER_BIT_EXT,
};
}
p->vk.CmdBindDescriptorBuffersEXT(cb, 3, dbi);
uint32_t idxs[3] = { 0, 1, 2 };
VkDeviceSize offs[3] = { 0, 0, 0 };
p->vk.CmdSetDescriptorBufferOffsetsEXT(cb, VK_PIPELINE_BIND_POINT_COMPUTE, p->pipe_lay, 0, 3, idxs, offs);
p->vk.CmdBindDescriptorBufferEmbeddedSamplersEXT(cb, VK_PIPELINE_BIND_POINT_COMPUTE, p->pipe_lay, 3);
// Pass 0: SPD auto-exposure
VkDeviceAddress spd_addr = p->const_buf[slot].addr + 512u;
uint32_t push_exp[4] = { (uint32_t)spd_addr, (uint32_t)(spd_addr >> 32), 90u, 93u };
p->vk.CmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pr->pipes[0]);
p->vk.CmdPushConstants(cb, p->pipe_lay, VK_SHADER_STAGE_COMPUTE_BIT, 0, 16, push_exp);
p->vk.CmdDispatch(cb, f411_div_up(rw, 64u), f411_div_up(rh, 64u), 1u);
f411_img_bar2(p, cb, p->img_exp_out.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
// Passes 1..27 (pre, border_0, model_1..12, border_12, post) — exact fsr411-recorder.hpp schedule
VkDeviceAddress caddr = p->const_buf[slot].addr;
for (uint32_t i = 0; i < 27u; i++) {
if (i == 26u) {
f411_img_bar2(p, cb, p->img_hist.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT);
f411_img_bar2(p, cb, p->img_recurrent.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT);
f411_img_bar2(p, cb, p->img_reproj.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
}
int border = (i % 2u) == 1u;
int main_p = (i == 0u || i == 26u);
int root = main_p || border || (i != 6u && i != 12u && i != 14u && i != 16u);
uint32_t push[4] = {0, 0, 0, 0};
uint32_t cnt = 0;
if (root) {
VkDeviceAddress a = caddr + (main_p ? 0u : 1024u);
push[cnt++] = (uint32_t)a;
push[cnt++] = (uint32_t)(a >> 32);
}
push[cnt++] = (i == 26u) ? 51u : 0u;
if (!border) push[cnt++] = (i == 26u) ? 63u : 12u;
uint32_t gx = 1u, gy = 1u;
if (i == 0u) { gx = f411_div_up(F411_UW, 16u); gy = f411_div_up(F411_UH, 16u); }
else if (i == 26u) { gx = f411_div_up(F411_UW, 32u); gy = f411_div_up(F411_UH, 32u); }
else if (border) {
uint32_t d = k_bdiv[i / 2u];
uint32_t w = aw / d, h = ah / d;
uint32_t px = F411_UW / d + 1u - w; if (px > 5u) px = 5u;
uint32_t py = F411_UH / d + 1u - h; if (py > 1u) py = 1u;
gx = f411_div_up((w + 1u + px) * (1u + py) + h * (1u + px), 32u);
gy = 1u;
} else {
uint32_t mdl = i / 2u;
uint32_t d = (mdl <= 2u || mdl == 12u) ? 2u : ((mdl <= 5u || mdl >= 10u) ? 4u : 8u);
gx = f411_div_up(aw / d, 64u);
gy = ah / d;
}
p->vk.CmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pr->pipes[i + 1u]);
p->vk.CmdPushConstants(cb, p->pipe_lay, VK_SHADER_STAGE_COMPUTE_BIT, 0, cnt * 4u, push);
p->vk.CmdDispatch(cb, gx, gy, 1u);
if (i != 26u) f411_compute_bar2(p, cb);
}
// Blit internal 1920x1080 RGBA16F -> game's output image
f411_img_bar2(p, cb, p->img_out.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_READ_BIT);
f411_img_bar2(p, cb, out_img, VK_IMAGE_ASPECT_COLOR_BIT, o_old, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT);
VkImageBlit blit = {
.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 },
.srcOffsets = { {0, 0, 0}, {(int32_t)F411_UW, (int32_t)F411_UH, 1} },
.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 },
.dstOffsets = { {0, 0, 0}, {(int32_t)ow, (int32_t)oh, 1} },
};
p->vk.CmdBlitImage(cb, p->img_out.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
out_img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
(ow == F411_UW && oh == F411_UH) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
f411_img_bar2(p, cb, p->img_out.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT);
f411_img_bar2(p, cb, out_img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, o_old,
VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT);
// Restore game input layouts
f411_img_bar2(p, cb, color_img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, c_old,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT);
f411_img_bar2(p, cb, depth_img, dep_asp, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, d_old,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT);
f411_img_bar2(p, cb, motion_img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, m_old,
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT);
wl_gpu_timer_end(&p->timer, &p->vk, cb, tslot);
p->last_preset = preset;
p->frame_idx++;
p->dispatches++;
if (out_gpu_us) *out_gpu_us = p->timer.last_us;
if (out_dispatches) *out_dispatches = p->dispatches;
if (out_reason) *out_reason = (preset == 0) ? "ok_fsr411_full_gpu_qual" : "ok_fsr411_full_gpu_perf";
return 2;
}
void wl_fsr411_full_gpu_destroy(WlFsr411FullGpu *p) {
if (!p) return;
wl_gpu_timer_destroy(&p->timer, &p->vk);
for (int i = 0; i < p->vcache_n; i++) {
if (p->vcache[i].view) p->vk.DestroyImageView(p->vk.device, p->vcache[i].view, NULL);
}
for (int k = 0; k < 2; k++) {
for (uint32_t i = 0; i < F411_PASS_COUNT; i++) {
if (p->presets[k].pipes[i]) p->vk.DestroyPipeline(p->vk.device, p->presets[k].pipes[i], NULL);
}
f411_free_buf(p, &p->presets[k].init_buf);
}
f411_free_img(p, &p->img_hist);
f411_free_img(p, &p->img_reproj);
f411_free_img(p, &p->img_recurrent);
f411_free_img(p, &p->img_out);
f411_free_img(p, &p->img_exp_out);
f411_free_img(p, &p->img_exp_at);
f411_free_img(p, &p->img_exp_mip);
f411_free_buf(p, &p->scratch_buf);
for (int s = 0; s < 2; s++) {
f411_free_buf(p, &p->const_buf[s]);
for (int i = 0; i < 3; i++) f411_free_buf(p, &p->desc_buf[s][i]);
}
if (p->pipe_lay) p->vk.DestroyPipelineLayout(p->vk.device, p->pipe_lay, NULL);
for (int i = 0; i < 4; i++) {
if (p->dsl[i]) p->vk.DestroyDescriptorSetLayout(p->vk.device, p->dsl[i], NULL);
}
if (p->sampler) p->vk.DestroySampler(p->vk.device, p->sampler, NULL);
free(p);
}
+40
View File
@@ -0,0 +1,40 @@
// Winlator Ludashi AMD FSR 4.1.1 Full INT8 GPU DP4a Pipeline (28 passes)
//
// Uses genuine AMD FSR 4.1.1 portable INT8 SPIR-V modules (pass-00..pass-27) and
// initializers.bin (131,072 B) from fsr4vk (quality & performance presets), running
// directly on Adreno 840 via VK_EXT_descriptor_buffer + VK_KHR_buffer_device_address +
// VK_KHR_shader_integer_dot_product + VK_KHR_compute_shader_derivatives.
//
// If the active Vulkan driver does not expose all required features, creation cleanly
// reports unavailable so fsr4_pipeline.c falls back to FSR 4.1.2 Lite GPU / FSR 3.1 GPU.
#pragma once
#include <vulkan/vulkan.h>
#include "fsr4_pipeline.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct WlFsr411FullGpu WlFsr411FullGpu;
WlFsr411FullGpu *wl_fsr411_full_gpu_create(const WlVkDispatch *vk, const char *fsr4_dir);
void wl_fsr411_full_gpu_destroy(WlFsr411FullGpu *ctx);
void wl_fsr411_full_gpu_reset(WlFsr411FullGpu *ctx);
int wl_fsr411_full_gpu_is_ready(const WlFsr411FullGpu *ctx);
const char *wl_fsr411_full_gpu_fail_reason(const WlFsr411FullGpu *ctx);
int wl_fsr411_full_gpu_dispatch(WlFsr411FullGpu *ctx, VkCommandBuffer cb,
const WlFsr4FrameDesc *frame,
VkImage color_img, VkFormat color_fmt,
VkImage depth_img, VkFormat depth_fmt,
VkImage motion_img, VkFormat motion_fmt,
VkImage out_img, uint32_t ow, uint32_t oh,
float sharpness,
uint32_t *out_gpu_us,
uint64_t *out_dispatches,
const char **out_reason);
#ifdef __cplusplus
}
#endif
File diff suppressed because it is too large. Load diff
+51
View File
@@ -0,0 +1,51 @@
// Winlator Ludashi AMD FSR 4.1.2 Lite INT8 Pipeline (GPU DP4a + Hexagon HTP v81 NPU)
//
// Uses genuine AMD FidelityFX SDK v2.4.0 FSR 4.1.2 Lite SPIR-V compute shaders (12 passes,
// classic Vulkan descriptor sets, packed 4x8-bit DP4a + FP16 — NO VK_EXT_descriptor_buffer
// and NO shaderInt8 required!) and genuine 27,392-byte weights.bin.
//
// Supports two execution targets on the exact same prepass/postpass contract:
// - GPU mode (use_npu = 0): runs all 12 compute passes directly on Adreno 840 GPU
// - NPU mode (use_npu = 1): runs prepass (0000/0001) + pack -> Hexagon HTP v81 (Sync or Async)
// -> unpack + K1 (0009) + K2 RCAS (0013)
#pragma once
#include <vulkan/vulkan.h>
#include "fsr4_pipeline.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct WlFsr412Lite WlFsr412Lite;
WlFsr412Lite *wl_fsr412_lite_create(const WlVkDispatch *vk, const char *fsr4_dir, const char *power_mode);
void wl_fsr412_lite_destroy(WlFsr412Lite *ctx);
void wl_fsr412_lite_reset(WlFsr412Lite *ctx);
void wl_fsr412_lite_release_sync_events(WlFsr412Lite *ctx);
int wl_fsr412_lite_is_gpu_ready(const WlFsr412Lite *ctx);
int wl_fsr412_lite_is_npu_ready(const WlFsr412Lite *ctx);
const char *wl_fsr412_lite_npu_state(const WlFsr412Lite *ctx);
const char *wl_fsr412_lite_fail_reason(const WlFsr412Lite *ctx);
// Record one FSR 4.1.2 Lite frame (GPU DP4a or Hexagon HTP v81 NPU).
// Returns:
// 2 = Active FSR 4.1.2 Lite frame recorded
// 1 = Warmup/fallback (caller may fall back to FSR 3.1 GPU or blit)
// 0 = Unsupported resolution or missing features/assets (caller should fall back to FSR 3.1 GPU)
int wl_fsr412_lite_dispatch(WlFsr412Lite *ctx, VkCommandBuffer cb,
const WlFsr4FrameDesc *frame,
VkImage color_img, VkFormat color_fmt, uint32_t cw, uint32_t ch,
VkImage depth_img, VkFormat depth_fmt,
VkImage motion_img, VkFormat motion_fmt,
VkImage out_img, uint32_t ow, uint32_t oh,
int use_npu, int npu_sync, float sharpness,
int *out_used_npu,
uint32_t *out_gpu_us,
uint32_t *out_htp_us,
uint64_t *out_dispatches,
const char **out_reason);
#ifdef __cplusplus
}
#endif
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
// Built-in self-contained AMD FSR 4.0.2 INT8 + Qualcomm Hexagon HTP v81/v79 NPU pipeline.
// Uses bundled fsr4_v07_i8.wpack + fsr4_builtin_{pre,post_a,post_b}.spv + QAIRT libQnnHtpPrepare.so
// so ZERO external asset packs are required on the phone.
#pragma once
#include <vulkan/vulkan.h>
#include "fsr4_pipeline.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct WlFsr4Builtin WlFsr4Builtin;
WlFsr4Builtin *wl_fsr4_builtin_create(const WlVkDispatch *vk, const char *fsr4_dir, const char *power_mode);
void wl_fsr4_builtin_destroy(WlFsr4Builtin *b);
void wl_fsr4_builtin_reset(WlFsr4Builtin *b);
void wl_fsr4_builtin_release_sync_events(WlFsr4Builtin *b);
int wl_fsr4_builtin_is_ready(const WlFsr4Builtin *b);
int wl_fsr4_builtin_is_compiling(const WlFsr4Builtin *b);
int wl_fsr4_builtin_is_staging(const WlFsr4Builtin *b);
int wl_fsr4_builtin_state(const WlFsr4Builtin *b);
// Record one built-in FSR 4.0.2 Hexagon NPU frame into cb.
// npu_sync: 1 = low-latency same-frame wait (Sync), 0 = pipelined 1-frame (Async).
// Returns:
// 2 = Hexagon HTP NPU path recorded
// 1 = Still warming up / compiling (caller should run fallback)
// 0 = Failed / unavailable
int wl_fsr4_builtin_dispatch(WlFsr4Builtin *b, VkCommandBuffer cb,
const WlFsr4FrameDesc *frame,
VkImage color_img, VkFormat color_fmt, uint32_t cw, uint32_t ch,
VkImage depth_img, VkFormat depth_fmt,
VkImage motion_img, VkFormat motion_fmt,
VkImage out_img, uint32_t ow, uint32_t oh,
int npu_sync, float sharpness,
uint32_t *out_gpu_us,
uint32_t *out_htp_us, uint64_t *out_npu_dispatches,
const char **out_reason);
#ifdef __cplusplus
}
#endif
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+164
View File
@@ -0,0 +1,164 @@
// Vulkan FSR 4.1.1 INT8 + Qualcomm Hexagon HTP v81 NPU pipeline for libVkLayer_winlator_fsr4_npu.so
#pragma once
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_android.h>
#include "fsr4_seam_proto.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct WlVkDispatch {
VkInstance instance;
VkPhysicalDevice phys_dev;
VkDevice device;
uint32_t graphics_qf;
// Detected optional extension/feature availability
int has_desc_buf;
int has_mut_desc;
int has_ext_ahb;
int has_bda;
int has_f16;
int has_i8;
int has_int_dot;
int has_sync2;
int has_qf_foreign;
int has_compute_derivs;
int has_8bit_storage;
int has_16bit_storage;
int has_timestamps;
float timestamp_period;
uint32_t subgroup_req_stages;
uint32_t subgroup_min;
uint32_t subgroup_max;
// Instance-level dispatch
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties;
PFN_vkGetPhysicalDeviceProperties2 GetPhysicalDeviceProperties2;
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
PFN_vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties;
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties;
// Device-level dispatch
PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
PFN_vkCreateBuffer CreateBuffer;
PFN_vkDestroyBuffer DestroyBuffer;
PFN_vkGetBufferMemoryRequirements GetBufferMemoryRequirements;
PFN_vkBindBufferMemory BindBufferMemory;
PFN_vkGetBufferDeviceAddress GetBufferDeviceAddress;
PFN_vkAllocateMemory AllocateMemory;
PFN_vkFreeMemory FreeMemory;
PFN_vkMapMemory MapMemory;
PFN_vkUnmapMemory UnmapMemory;
PFN_vkCreateImage CreateImage;
PFN_vkDestroyImage DestroyImage;
PFN_vkGetImageMemoryRequirements GetImageMemoryRequirements;
PFN_vkBindImageMemory BindImageMemory;
PFN_vkCreateImageView CreateImageView;
PFN_vkDestroyImageView DestroyImageView;
PFN_vkCreateSampler CreateSampler;
PFN_vkDestroySampler DestroySampler;
PFN_vkCreateShaderModule CreateShaderModule;
PFN_vkDestroyShaderModule DestroyShaderModule;
PFN_vkCreateDescriptorSetLayout CreateDescriptorSetLayout;
PFN_vkDestroyDescriptorSetLayout DestroyDescriptorSetLayout;
PFN_vkCreateDescriptorPool CreateDescriptorPool;
PFN_vkDestroyDescriptorPool DestroyDescriptorPool;
PFN_vkAllocateDescriptorSets AllocateDescriptorSets;
PFN_vkUpdateDescriptorSets UpdateDescriptorSets;
PFN_vkCmdBindDescriptorSets CmdBindDescriptorSets;
PFN_vkCreatePipelineLayout CreatePipelineLayout;
PFN_vkDestroyPipelineLayout DestroyPipelineLayout;
PFN_vkCreateComputePipelines CreateComputePipelines;
PFN_vkDestroyPipeline DestroyPipeline;
PFN_vkCmdBindPipeline CmdBindPipeline;
PFN_vkCmdPushConstants CmdPushConstants;
PFN_vkCmdDispatch CmdDispatch;
PFN_vkCmdPipelineBarrier CmdPipelineBarrier;
PFN_vkCmdPipelineBarrier2 CmdPipelineBarrier2;
PFN_vkCmdClearColorImage CmdClearColorImage;
PFN_vkCmdClearDepthStencilImage CmdClearDepthStencilImage;
PFN_vkCmdFillBuffer CmdFillBuffer;
PFN_vkCmdCopyBuffer CmdCopyBuffer;
PFN_vkCmdCopyImageToBuffer CmdCopyImageToBuffer;
PFN_vkCmdCopyBufferToImage CmdCopyBufferToImage;
PFN_vkCmdBlitImage CmdBlitImage;
PFN_vkCmdCopyImage CmdCopyImage;
PFN_vkDeviceWaitIdle DeviceWaitIdle;
// Events (for same-frame NPU Sync mode + slot retirement)
PFN_vkCreateEvent CreateEvent;
PFN_vkDestroyEvent DestroyEvent;
PFN_vkSetEvent SetEvent;
PFN_vkResetEvent ResetEvent;
PFN_vkGetEventStatus GetEventStatus;
PFN_vkCmdSetEvent CmdSetEvent;
PFN_vkCmdResetEvent CmdResetEvent;
PFN_vkCmdWaitEvents CmdWaitEvents;
// Timestamp query pool (for per-frame GPU ms HUD telemetry)
PFN_vkCreateQueryPool CreateQueryPool;
PFN_vkDestroyQueryPool DestroyQueryPool;
PFN_vkCmdResetQueryPool CmdResetQueryPool;
PFN_vkCmdWriteTimestamp CmdWriteTimestamp;
PFN_vkGetQueryPoolResults GetQueryPoolResults;
// Extension dispatch
PFN_vkGetDescriptorSetLayoutSizeEXT GetDescriptorSetLayoutSizeEXT;
PFN_vkGetDescriptorSetLayoutBindingOffsetEXT GetDescriptorSetLayoutBindingOffsetEXT;
PFN_vkGetDescriptorEXT GetDescriptorEXT;
PFN_vkCmdBindDescriptorBuffersEXT CmdBindDescriptorBuffersEXT;
PFN_vkCmdSetDescriptorBufferOffsetsEXT CmdSetDescriptorBufferOffsetsEXT;
PFN_vkCmdBindDescriptorBufferEmbeddedSamplersEXT CmdBindDescriptorBufferEmbeddedSamplersEXT;
PFN_vkGetAndroidHardwareBufferPropertiesANDROID GetAndroidHardwareBufferPropertiesANDROID;
} WlVkDispatch;
typedef struct WlFsr4Pipeline WlFsr4Pipeline;
// Legacy aliases kept for source clarity
enum {
WL_FSR_ENGINE_FSR4_NPU = WL_FSR_BACKEND_FSR4_0_NPU,
WL_FSR_ENGINE_FSR3_GPU = WL_FSR_BACKEND_FSR3_GPU,
};
typedef struct WlFsrDispatchConfig {
int force_bypass; /* 1 = live OFF bypass */
int backend; /* WL_FSR_BACKEND_* */
int npu_sync; /* 1 = Sync (low-latency same-frame wait), 0 = Async (pipelined 1-frame) */
float sharpness; /* 0.0f..1.0f user RCAS sharpness (-1.0f = default 0.55f) */
} WlFsrDispatchConfig;
typedef struct WlFsrDispatchResult {
int rc; /* 2 = active upscaler, 1 = fallback blit, 0 = invalid */
int npu_used; /* 1 if Hexagon HTP NPU executed this path */
int fallback_used; /* 1 if automatic fallback to FSR 3.1 / Lite GPU engaged */
int preset; /* 0 = perf, 1 = ultraperf */
uint32_t htp_us; /* Hexagon HTP execution time (us) */
uint32_t gpu_us; /* Vulkan GPU compute execution time (us) */
uint64_t dispatches; /* total upscaler dispatches */
const char *backend_tag; /* Exact HUD string: "FSR3.1-GPU", "FSR4.1-Lite-GPU", etc. */
const char *reason; /* Diagnostic reason string */
} WlFsrDispatchResult;
WlFsr4Pipeline *wl_fsr4_pipe_create(const WlVkDispatch *vk);
void wl_fsr4_pipe_destroy(WlFsr4Pipeline *p);
uint64_t wl_fsr4_pipe_caps(const WlFsr4Pipeline *p);
void wl_fsr4_pipe_diag(const WlFsr4Pipeline *p, const char **out_ahb, const char **out_npu_state);
void wl_fsr4_pipe_release_sync_events(WlFsr4Pipeline *p);
// Execute one upscaling dispatch inside the game's command buffer.
int wl_fsr4_pipe_dispatch(WlFsr4Pipeline *p, VkCommandBuffer cb,
const WlFsr4FrameDesc *frame,
const WlFsrDispatchConfig *cfg,
WlFsrDispatchResult *out_res);
// Helper to resolve tracked image info from the layer's image table
int wl_fsr4_lookup_image_info(VkDevice dev, VkImage img,
VkFormat *out_fmt, uint32_t *out_w, uint32_t *out_h,
VkImageUsageFlags *out_usage);
#ifdef __cplusplus
}
#endif
File diff suppressed because it is too large. Load diff
+519
View File
@@ -0,0 +1,519 @@
// Clean-room C declaration of the Qualcomm QNN HTP (v79/v81) interface subset and shared-buffer
// helpers for the DroidDeck upscaler layer (ported from Winlator-NeuralScale).
// Struct layouts match the QAIRT 2.47+ C ABI so builds need zero external QNN headers.
#pragma once
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
enum {
WL_FSR4_TENSOR_BYTES = 8294400u,
WL_FSR4_AHB_BYTES = 4u * WL_FSR4_TENSOR_BYTES,
WL_FSR4_PRESET_PERF = 0,
WL_FSR4_PRESET_ULTRAPERF = 1,
// Built-in self-contained AMD FSR 4.0.2 INT8 (fsr4_model_v07_i8_quality) AHB layout:
// slot 0 in : [0, 8294400) UFIXED_POINT_8 [1, 540, 960, 16]
// slot 1 in : [8294400, 16588800) UFIXED_POINT_8 [1, 540, 960, 16]
// slot 0 out : [16588800, 33177600) UFIXED_POINT_8 [1, 1080, 1920, 8]
// slot 1 out : [33177600, 49766400) UFIXED_POINT_8 [1, 1080, 1920, 8]
WL_FSR4_BUILTIN_IN_BYTES = 8294400u,
WL_FSR4_BUILTIN_OUT_BYTES = 16588800u,
WL_FSR4_BUILTIN_AHB_BYTES = 49766400u,
WL_FSR4_PASS0_WB_BYTES = 1056u,
// AMD FSR 4.1.2 Lite INT8 AHB layout (2x 540x960x16 in + 2x 540x960x16 out)
WL_FSR4_LITE_IN_BYTES = 8294400u,
WL_FSR4_LITE_OUT_BYTES = 8294400u,
WL_FSR4_LITE_AHB_BYTES = 33177600u,
};
typedef struct wl_fsr4_qnn wl_fsr4_qnn;
wl_fsr4_qnn *wl_fsr4_qnn_init(const char *fsr4_dir, int preset, const char *power_mode);
wl_fsr4_qnn *wl_fsr4_qnn_init_builtin(const char *fsr4_dir, const char *power_mode,
uint8_t out_pass0_wb[WL_FSR4_PASS0_WB_BYTES]);
// cache_name is a file name only; the compiled context lives in <fsr4_dir>/<htp arch>/<cache_name>.
wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel,
const char *cache_name, const char *graph_name,
const char *power_mode,
uint32_t in_bytes, uint32_t out_bytes);
int wl_fsr4_qnn_load_preset(wl_fsr4_qnn *q, int preset);
void *wl_fsr4_qnn_ahb(const wl_fsr4_qnn *q);
void *wl_fsr4_qnn_mapped(const wl_fsr4_qnn *q);
int wl_fsr4_qnn_dmabuf_fd(const wl_fsr4_qnn *q);
int wl_fsr4_qnn_exec(wl_fsr4_qnn *q, int preset, int slot, double *out_ms);
int wl_fsr4_qnn_exec_builtin(wl_fsr4_qnn *q, int slot, double *out_ms);
int wl_fsr4_qnn_exec_custom(wl_fsr4_qnn *q, int slot, uint32_t in_bytes, uint32_t out_bytes, double *out_ms);
const char *wl_fsr4_qnn_last_error(void);
void wl_fsr4_qnn_free(wl_fsr4_qnn *q);
// Writes <fsr4_dir>/<htp arch>/<name>; returns 0 when it does not fit or an argument is missing.
int wl_fsr4_qnn_cache_path(const char *fsr4_dir, const char *name, char *out, size_t out_sz);
// ---- Clean-room QNN C ABI definitions (QAIRT 2.47+ / HTP v81) ----
typedef uint64_t Qnn_ErrorHandle_t;
typedef void *Qnn_Handle_t;
typedef Qnn_Handle_t Qnn_BackendHandle_t;
typedef Qnn_Handle_t Qnn_ContextHandle_t;
typedef Qnn_Handle_t Qnn_DeviceHandle_t;
typedef Qnn_Handle_t Qnn_GraphHandle_t;
typedef Qnn_Handle_t Qnn_LogHandle_t;
typedef Qnn_Handle_t Qnn_MemHandle_t;
typedef Qnn_Handle_t Qnn_ProfileHandle_t;
typedef Qnn_Handle_t Qnn_SignalHandle_t;
typedef void *QnnSystemContext_Handle_t;
typedef uint64_t Qnn_ContextBinarySize_t;
enum {
QNN_SUCCESS_CODE = 0,
QNN_DEFINITION_IMPL_GENERATED = 0,
QNN_DEFINITION_DEFINED = 1,
QNN_DEFINITION_UNDEFINED = 0x7FFFFFFF,
QNN_LOG_LEVEL_ERROR = 1,
QNN_LOG_LEVEL_WARN = 2,
QNN_LOG_LEVEL_INFO = 3,
QNN_TENSOR_VERSION_1 = 1,
QNN_TENSOR_VERSION_2 = 2,
QNN_TENSOR_TYPE_APP_WRITE = 0,
QNN_TENSOR_TYPE_APP_READ = 1,
QNN_TENSOR_TYPE_APP_READWRITE = 2,
QNN_TENSOR_TYPE_NATIVE = 3,
QNN_TENSOR_TYPE_STATIC = 4,
QNN_TENSORMEMTYPE_RAW = 0,
QNN_TENSORMEMTYPE_MEMHANDLE = 1,
QNN_TENSOR_DATA_FORMAT_FLAT_BUFFER = 0,
QNN_DATATYPE_INT_8 = 0x0008,
QNN_DATATYPE_INT_32 = 0x0032,
QNN_DATATYPE_UINT_8 = 0x0108,
QNN_DATATYPE_UINT_32 = 0x0132,
QNN_DATATYPE_FLOAT_16 = 0x0216,
QNN_DATATYPE_FLOAT_32 = 0x0232,
QNN_DATATYPE_SFIXED_POINT_8 = 0x0308,
QNN_DATATYPE_SFIXED_POINT_32 = 0x0332,
QNN_DATATYPE_UFIXED_POINT_8 = 0x0408,
QNN_DATATYPE_BOOL_8 = 0x0508,
QNN_PARAMTYPE_SCALAR = 0,
QNN_PARAMTYPE_TENSOR = 1,
QNN_OPCONFIG_VERSION_1 = 1,
QNN_MEM_TYPE_CUSTOM = 2,
QNN_HTP_MEM_SHARED_BUFFER = 1,
QNN_DEVICE_CONFIG_OPTION_CUSTOM = 0,
QNN_HTP_DEVICE_CONFIG_OPTION_SIGNEDPD = 2,
QNN_HTP_DEVICE_INFRA_TYPE_PERF = 0,
QNN_QUANT_ENC_SCALE_OFFSET = 0,
QNN_QUANT_ENC_AXIS_SCALE_OFFSET = 1,
QNN_QUANT_ENC_BW_AXIS_SCALE_OFFSET = 3,
QNN_QUANT_ENC_UNDEFINED = 0x7FFFFFFF,
QNN_GRAPH_CONFIG_OPTION_CUSTOM = 0,
QNN_HTP_GRAPH_CONFIG_OPTION_OPTIMIZATION = 1,
QNN_HTP_GRAPH_CONFIG_OPTION_VTCM_SIZE = 3,
QNN_HTP_GRAPH_OPT_FINALIZE_FLAG = 3,
};
typedef struct { uint32_t major, minor, patch; } Qnn_Version_t;
typedef struct { Qnn_Version_t coreApiVersion; Qnn_Version_t backendApiVersion; } Qnn_ApiVersion_t;
typedef struct { float scale; int32_t offset; } Qnn_ScaleOffset_t;
typedef struct { uint32_t bitwidth; float scale; int32_t offset; } Qnn_BwScaleOffset_t;
typedef struct { int32_t axis; uint32_t numScaleOffsets; Qnn_ScaleOffset_t *scaleOffset; } Qnn_AxisScaleOffset_t;
typedef struct { uint32_t bitwidth; int32_t axis; uint32_t numElements; float *scales; int32_t *offsets; } Qnn_BwAxisScaleOffset_t;
typedef struct { uint32_t *blockSize; Qnn_ScaleOffset_t *scaleOffset; } Qnn_BlockEncoding_t;
typedef struct { float scale; float offset; } Qnn_FloatScaleOffset_t;
typedef struct { uint32_t *blockSize; Qnn_FloatScaleOffset_t *floatScaleOffset; } Qnn_FloatBlockEncoding_t;
typedef struct { uint32_t bitwidth; uint32_t *blockSize; Qnn_FloatScaleOffset_t *floatScaleOffset; } Qnn_BwFloatBlockEncoding_t;
typedef struct {
uint32_t encodingDefinition;
uint32_t quantizationEncoding;
union {
Qnn_ScaleOffset_t scaleOffsetEncoding;
Qnn_AxisScaleOffset_t axisScaleOffsetEncoding;
Qnn_BwScaleOffset_t bwScaleOffsetEncoding;
Qnn_BwAxisScaleOffset_t bwAxisScaleOffsetEncoding;
Qnn_BlockEncoding_t blockEncoding;
void *blockwiseExpansion;
void *vectorEncoding;
Qnn_FloatBlockEncoding_t floatBlockEncoding;
void *bwAxisScaleOffsetMappedEncoding;
void *bwBlockMappedEncoding;
void *bwBlockwiseExpansionMappedEncoding;
Qnn_BwFloatBlockEncoding_t bwFloatBlockEncoding;
void *microScalingEncoding;
void *arrayOfEncoding;
};
} Qnn_QuantizeParams_t;
typedef struct { void *data; uint32_t dataSize; } Qnn_ClientBuffer_t;
typedef struct {
uint32_t type;
struct { uint32_t numSpecifiedElements; uint32_t numSparseDimensions; } hybridCoo;
} Qnn_SparseParams_t;
typedef struct {
uint32_t id;
const char *name;
uint32_t type;
uint32_t dataFormat;
uint32_t dataType;
Qnn_QuantizeParams_t quantizeParams;
uint32_t rank;
uint32_t *dimensions;
uint32_t memType;
union { Qnn_ClientBuffer_t clientBuf; Qnn_MemHandle_t memHandle; };
} Qnn_TensorV1_t;
typedef struct {
uint32_t id;
const char *name;
uint32_t type;
uint32_t dataFormat;
uint32_t dataType;
Qnn_QuantizeParams_t quantizeParams;
uint32_t rank;
uint32_t *dimensions;
uint32_t memType;
union { Qnn_ClientBuffer_t clientBuf; Qnn_MemHandle_t memHandle; void *retrieveRaw; };
uint8_t *isDynamicDimensions;
Qnn_SparseParams_t sparseParams;
uint8_t isProduced;
} Qnn_TensorV2_t;
typedef struct {
uint32_t version;
union { Qnn_TensorV1_t v1; Qnn_TensorV2_t v2; };
} Qnn_Tensor_t;
typedef struct { uint32_t numDim; uint32_t *dimSize; const char *shapeConfig; } Qnn_MemShape_t;
typedef struct {
Qnn_MemShape_t memShape;
uint32_t dataType;
uint32_t memType;
union {
struct { int32_t fd; } ionInfo;
void *customInfo;
struct { int32_t fd; void *data; } dmaBufInfo;
void *dx12BufInfo;
};
} Qnn_MemDescriptor_t;
typedef struct {
uint32_t type;
uint64_t size;
union {
uint32_t qurtAddress;
struct { int32_t fd; uint64_t offset; } sharedBufferConfig;
uint8_t raw[16];
};
} QnnMemHtp_Descriptor_t;
typedef struct {
uint32_t option;
union {
uint32_t socModel;
struct { uint32_t deviceId, arch; } arch;
struct { uint32_t deviceId; bool useSignedProcessDomain; } useSignedProcessDomain;
struct { uint32_t deviceId; bool useSecureProcessDomain; } useSecureProcessDomain;
struct { uint32_t deviceId; bool enableAsyncExecute; } asyncExecute;
void *htpExtension;
};
} QnnHtpDevice_CustomConfig_t;
typedef struct {
uint32_t option;
union { void *customConfig; void *hardwareInfo; };
} QnnDevice_Config_t;
typedef struct {
uint32_t contextId;
uint32_t setDcvsEnable, dcvsEnable;
uint32_t powerMode;
uint32_t setSleepLatency, sleepLatency;
uint32_t setSleepDisable, sleepDisable;
uint32_t setBusParams, busVoltageCornerMin, busVoltageCornerTarget, busVoltageCornerMax;
uint32_t setCoreParams, coreVoltageCornerMin, coreVoltageCornerTarget, coreVoltageCornerMax;
} QnnHtpPerfInfrastructure_DcvsV3_t;
typedef struct {
uint32_t hmxPickDefault;
uint32_t hmxVoltageCornerMin, hmxVoltageCornerTarget, hmxVoltageCornerMax;
uint32_t hmxPerfMode;
} QnnHtpPerfInfrastructure_HmxV2_t;
typedef struct {
uint32_t option;
union {
QnnHtpPerfInfrastructure_DcvsV3_t dcvsV3Config;
uint32_t rpcControlLatencyConfig;
uint32_t rpcPollingTimeConfig;
uint32_t hmxTimeoutIntervalUsConfig;
QnnHtpPerfInfrastructure_HmxV2_t hmxV2Config;
uint32_t raw[16];
};
} QnnHtpPerfInfrastructure_PowerConfig_t;
enum {
QNN_HTP_POWER_OPT_DCVS_V3 = 1,
QNN_HTP_POWER_OPT_RPC_CONTROL_LATENCY = 2,
QNN_HTP_POWER_OPT_RPC_POLLING_TIME = 3,
QNN_HTP_POWER_OPT_HMX_V2 = 5,
QNN_HTP_POWERMODE_PERF = 0x10,
QNN_HTP_CLK_PERF_HIGH = 0,
QNN_HTP_VCORNER_DISABLE = 0x10,
QNN_HTP_VCORNER_SVS = 0x40,
QNN_HTP_VCORNER_NOM = 0x60,
QNN_HTP_VCORNER_TURBO = 0x80,
QNN_HTP_VCORNER_MAX = 0xA0,
QNN_HTP_EXP_VCORNER_DISABLE = 0,
QNN_HTP_EXP_VCORNER_SVS = 0x180,
QNN_HTP_EXP_VCORNER_NOM = 0x200,
QNN_HTP_EXP_VCORNER_TUR = 0x280,
QNN_HTP_EXP_VCORNER_MAX = 0xFFFF,
};
typedef Qnn_ErrorHandle_t (*QnnHtpPerf_CreatePowerConfigIdFn_t)(uint32_t deviceId, uint32_t coreId, uint32_t *powerConfigId);
typedef Qnn_ErrorHandle_t (*QnnHtpPerf_DestroyPowerConfigIdFn_t)(uint32_t powerConfigId);
typedef Qnn_ErrorHandle_t (*QnnHtpPerf_SetPowerConfigFn_t)(uint32_t powerConfigId, const QnnHtpPerfInfrastructure_PowerConfig_t **config);
typedef Qnn_ErrorHandle_t (*QnnHtpPerf_SetMemoryConfigFn_t)(uint32_t deviceId, uint32_t coreId, const void **config);
typedef struct {
QnnHtpPerf_CreatePowerConfigIdFn_t createPowerConfigId;
QnnHtpPerf_DestroyPowerConfigIdFn_t destroyPowerConfigId;
QnnHtpPerf_SetPowerConfigFn_t setPowerConfig;
QnnHtpPerf_SetMemoryConfigFn_t setMemoryConfig;
} QnnHtpDevice_PerfInfrastructure_t;
typedef struct {
uint32_t infraType;
union { QnnHtpDevice_PerfInfrastructure_t perfInfra; };
} QnnHtpDevice_Infrastructure_t;
typedef void (*QnnLog_Callback_t)(const char *fmt, uint32_t level, uint64_t timestamp, va_list args);
typedef struct {
const char *graphName;
uint32_t numGraphInputs; Qnn_Tensor_t *graphInputs;
uint32_t numGraphOutputs; Qnn_Tensor_t *graphOutputs;
} QnnSystemContext_GraphInfoV1_t;
typedef struct {
const char *graphName;
uint32_t numGraphInputs; Qnn_Tensor_t *graphInputs;
uint32_t numGraphOutputs; Qnn_Tensor_t *graphOutputs;
uint32_t numUpdateableTensors; Qnn_Tensor_t *updateableTensors;
} QnnSystemContext_GraphInfoV2_t;
typedef struct {
const char *graphName;
uint32_t numGraphInputs; Qnn_Tensor_t *graphInputs;
uint32_t numGraphOutputs; Qnn_Tensor_t *graphOutputs;
uint32_t numUpdateableTensors; Qnn_Tensor_t *updateableTensors;
uint32_t graphBlobInfoSize; void *graphBlobInfo;
uint32_t startOpIndex; uint32_t endOpIndex;
} QnnSystemContext_GraphInfoV3_t;
typedef struct {
uint32_t version;
union {
QnnSystemContext_GraphInfoV1_t graphInfoV1;
QnnSystemContext_GraphInfoV2_t graphInfoV2;
QnnSystemContext_GraphInfoV3_t graphInfoV3;
};
} QnnSystemContext_GraphInfo_t;
typedef struct {
uint32_t backendId; const char *buildId;
Qnn_Version_t coreApiVersion; Qnn_Version_t backendApiVersion;
const char *socVersion;
Qnn_Version_t hwInfoBlobVersion; Qnn_Version_t contextBlobVersion;
uint32_t hwInfoBlobSize; void *hwInfoBlob;
uint64_t contextBlobSize;
uint32_t numContextTensors; Qnn_Tensor_t *contextTensors;
uint32_t numGraphs; QnnSystemContext_GraphInfo_t *graphs;
} QnnSystemContext_BinaryInfoV1_t;
typedef struct {
uint32_t backendId; const char *buildId;
Qnn_Version_t coreApiVersion; Qnn_Version_t backendApiVersion;
const char *socVersion;
Qnn_Version_t hwInfoBlobVersion; Qnn_Version_t contextBlobVersion;
uint32_t hwInfoBlobSize; void *hwInfoBlob;
uint64_t contextBlobSize;
uint32_t numContextTensors; Qnn_Tensor_t *contextTensors;
uint32_t numGraphs; QnnSystemContext_GraphInfo_t *graphs;
void *platformInfo;
} QnnSystemContext_BinaryInfoV2_t;
typedef struct {
uint32_t backendId; const char *buildId;
Qnn_Version_t coreApiVersion; Qnn_Version_t backendApiVersion;
const char *socVersion;
Qnn_Version_t contextBlobVersion;
uint64_t contextBlobSize;
uint32_t numContextTensors; Qnn_Tensor_t *contextTensors;
uint32_t numGraphs; QnnSystemContext_GraphInfo_t *graphs;
void *platformInfo;
uint32_t contextMetadataSize; void *contextMetadata;
uint32_t socModel;
} QnnSystemContext_BinaryInfoV3_t;
typedef struct {
uint32_t version;
union {
QnnSystemContext_BinaryInfoV1_t contextBinaryInfoV1;
QnnSystemContext_BinaryInfoV2_t contextBinaryInfoV2;
QnnSystemContext_BinaryInfoV3_t contextBinaryInfoV3;
};
} QnnSystemContext_BinaryInfo_t;
typedef struct {
Qnn_ErrorHandle_t (*systemContextCreate)(QnnSystemContext_Handle_t *sysCtxHandle);
Qnn_ErrorHandle_t (*systemContextGetBinaryInfo)(QnnSystemContext_Handle_t sysCtxHandle, void *binaryBuffer, uint64_t binaryBufferSize,
const QnnSystemContext_BinaryInfo_t **binaryInfo, Qnn_ContextBinarySize_t *binaryInfoSize);
Qnn_ErrorHandle_t (*systemContextGetMetaData)(QnnSystemContext_Handle_t sysCtxHandle, const void *binaryBuffer, uint64_t binaryBufferSize,
const QnnSystemContext_BinaryInfo_t **binaryInfo);
Qnn_ErrorHandle_t (*systemContextFree)(QnnSystemContext_Handle_t sysCtxHandle);
void (*reserved_slot[22])(void);
} QnnSystemInterface_ImplV1_11_t;
typedef struct {
uint32_t backendId;
const char *providerName;
Qnn_Version_t systemApiVersion;
union { QnnSystemInterface_ImplV1_11_t v1_11; };
} QnnSystemInterface_t;
typedef struct {
uint32_t dataType;
union {
float floatValue;
double doubleValue;
uint64_t uint64Value;
int64_t int64Value;
uint32_t uint32Value;
int32_t int32Value;
uint16_t uint16Value;
int16_t int16Value;
uint8_t uint8Value;
int8_t int8Value;
uint8_t bool8Value;
const char *stringValue;
};
} Qnn_Scalar_t;
typedef struct {
uint32_t paramType;
const char *name;
union {
Qnn_Scalar_t scalarParam;
Qnn_Tensor_t tensorParam;
};
} Qnn_Param_t;
typedef struct {
const char *name;
const char *packageName;
const char *typeName;
uint32_t numOfParams;
Qnn_Param_t *params;
uint32_t numOfInputs;
Qnn_Tensor_t *inputTensors;
uint32_t numOfOutputs;
Qnn_Tensor_t *outputTensors;
} Qnn_OpConfigV1_t;
typedef struct {
uint32_t version;
union {
Qnn_OpConfigV1_t v1;
};
} Qnn_OpConfig_t;
typedef struct {
uint32_t option;
union {
struct { uint32_t type; float floatValue; } optimizationOption;
uint32_t precision;
uint32_t vtcmSizeInMB;
uint64_t raw[4];
};
} QnnHtpGraph_CustomConfig_t;
typedef struct {
uint32_t option;
union {
void *customConfig;
uint32_t priority;
};
} QnnGraph_Config_t;
typedef struct {
void (*propertyHasCapability)(void);
Qnn_ErrorHandle_t (*backendCreate)(Qnn_LogHandle_t logger, const void **config, Qnn_BackendHandle_t *backend);
void (*backendSetConfig)(void);
void (*backendGetApiVersion)(void);
void (*backendGetBuildId)(void);
void (*backendRegisterOpPackage)(void);
void (*backendGetSupportedOperations)(void);
void (*backendValidateOpConfig)(void);
Qnn_ErrorHandle_t (*backendFree)(Qnn_BackendHandle_t backend);
Qnn_ErrorHandle_t (*contextCreate)(Qnn_BackendHandle_t backend, Qnn_DeviceHandle_t device, const void **config, Qnn_ContextHandle_t *context);
void (*contextSetConfig)(void);
Qnn_ErrorHandle_t (*contextGetBinarySize)(Qnn_ContextHandle_t context, Qnn_ContextBinarySize_t *binaryBufferSize);
Qnn_ErrorHandle_t (*contextGetBinary)(Qnn_ContextHandle_t context, void *binaryBuffer, Qnn_ContextBinarySize_t binaryBufferSize, Qnn_ContextBinarySize_t *writtenBufferSize);
Qnn_ErrorHandle_t (*contextCreateFromBinary)(Qnn_BackendHandle_t backend, Qnn_DeviceHandle_t device, const void **config, const void *binaryBuffer,
Qnn_ContextBinarySize_t binaryBufferSize, Qnn_ContextHandle_t *context, Qnn_ProfileHandle_t profile);
Qnn_ErrorHandle_t (*contextFree)(Qnn_ContextHandle_t context, Qnn_ProfileHandle_t profile);
Qnn_ErrorHandle_t (*graphCreate)(Qnn_ContextHandle_t contextHandle, const char *graphName, const QnnGraph_Config_t **config, Qnn_GraphHandle_t *graphHandle);
void (*graphCreateSubgraph)(void);
void (*graphSetConfig)(void);
Qnn_ErrorHandle_t (*graphAddNode)(Qnn_GraphHandle_t graphHandle, Qnn_OpConfig_t opConfig);
Qnn_ErrorHandle_t (*graphFinalize)(Qnn_GraphHandle_t graphHandle, Qnn_ProfileHandle_t profileHandle, Qnn_SignalHandle_t signalHandle);
Qnn_ErrorHandle_t (*graphRetrieve)(Qnn_ContextHandle_t contextHandle, const char *graphName, Qnn_GraphHandle_t *graphHandle);
Qnn_ErrorHandle_t (*graphExecute)(Qnn_GraphHandle_t graphHandle, const Qnn_Tensor_t *inputs, uint32_t numInputs,
Qnn_Tensor_t *outputs, uint32_t numOutputs, Qnn_ProfileHandle_t profileHandle, Qnn_SignalHandle_t signalHandle);
void (*graphExecuteAsync)(void);
void (*tensorCreateContextTensor)(void);
Qnn_ErrorHandle_t (*tensorCreateGraphTensor)(Qnn_GraphHandle_t graph, Qnn_Tensor_t *tensor);
Qnn_ErrorHandle_t (*logCreate)(QnnLog_Callback_t callback, uint32_t maxLogLevel, Qnn_LogHandle_t *logger);
void (*logSetLogLevel)(void);
Qnn_ErrorHandle_t (*logFree)(Qnn_LogHandle_t logger);
void (*profile_slots[7])(void);
Qnn_ErrorHandle_t (*memRegister)(Qnn_ContextHandle_t context, const Qnn_MemDescriptor_t *memDescriptors, uint32_t numDescriptors, Qnn_MemHandle_t *memHandles);
Qnn_ErrorHandle_t (*memDeRegister)(const Qnn_MemHandle_t *memHandles, uint32_t numHandles);
void (*deviceGetPlatformInfo)(void);
void (*deviceFreePlatformInfo)(void);
Qnn_ErrorHandle_t (*deviceGetInfrastructure)(const QnnHtpDevice_Infrastructure_t **deviceInfra);
Qnn_ErrorHandle_t (*deviceCreate)(Qnn_LogHandle_t logger, const QnnDevice_Config_t **config, Qnn_DeviceHandle_t *device);
void (*deviceSetConfig)(void);
void (*deviceGetInfo)(void);
Qnn_ErrorHandle_t (*deviceFree)(Qnn_DeviceHandle_t device);
void (*tail_slots[28])(void);
} QnnInterface_ImplV2_36_t;
typedef struct {
uint32_t backendId;
const char *providerName;
Qnn_ApiVersion_t apiVersion;
union { QnnInterface_ImplV2_36_t v2_36; };
} QnnInterface_t;
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
_Static_assert(sizeof(Qnn_ScaleOffset_t) == 8, "Qnn_ScaleOffset_t size");
_Static_assert(sizeof(Qnn_QuantizeParams_t) == 40, "Qnn_QuantizeParams_t size");
_Static_assert(sizeof(Qnn_SparseParams_t) == 12, "Qnn_SparseParams_t size");
_Static_assert(sizeof(QnnMemHtp_Descriptor_t) == 32, "QnnMemHtp_Descriptor_t size");
_Static_assert(sizeof(QnnHtpPerfInfrastructure_PowerConfig_t) == 68, "QnnHtpPerfInfrastructure_PowerConfig_t size");
_Static_assert(sizeof(QnnSystemInterface_ImplV1_11_t) == 26 * sizeof(void *), "QnnSystemInterface_ImplV1_11_t size");
_Static_assert(sizeof(QnnInterface_ImplV2_36_t) == 72 * sizeof(void *), "QnnInterface_ImplV2_36_t size");
#endif
#ifdef __cplusplus
}
#endif
+162
View File
@@ -0,0 +1,162 @@
// Shared in-process zero-copy Wine <-> Android Vulkan Layer mailbox/doorbell protocol
// for Winlator Ludashi FSR 4.1.1 on Qualcomm Hexagon HTP v81 NPU.
//
// Used identically by:
// - Android ARM64 Vulkan Layer: libVkLayer_winlator_fsr4_npu.so
// - Windows x86_64 Bridge DLLs: amd_fidelityfx_vk.dll, amd_fidelityfx_dx12.dll, nvngx.dll
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// Exact buffer creation signatures recognized by libVkLayer_winlator_fsr4_npu.so
// via vkCreateBuffer / vkBindBufferMemory / vkMapMemory / vkCmdUpdateBuffer.
#define WLFSR4_MAILBOX_BYTES 0x2000u /* 8192 bytes: header + 4 ring slots */
#define WLFSR4_MARKER_BYTES 0x02D0u /* 720 bytes: doorbell target buffer */
#define WLFSR4_MAILBOX_MAGIC 0x345253464E4C5755ULL /* "UWLNFSR4" */
#define WLFSR4_DOORBELL_MAGIC 0x444246535234574CULL /* "LWR4SFBD" */
#define WLFSR4_HELLO_MAGIC 0x48454C4F46535234ULL /* "4RSFOLEH" */
#define WLFSR4_TELEMETRY_MAGIC 0x54454C4D46535234ULL /* "4RSFMLET" (XeSS 3.0 direct telemetry ping) */
#define WLFSR4_PROTO_VERSION 2u
#define WLFSR4_SLOTS 4u
// Multi-backend IDs shared across Android Vulkan layer, Windows bridge DLLs, and Java/Kotlin UI
enum {
WL_FSR_BACKEND_FSR3_GPU = 0, /* FSR 3.1 (GPU) */
WL_FSR_BACKEND_XESS3_GPU = 1, /* XeSS 3.0 DP4a (GPU, official libxess.dll) */
WL_FSR_BACKEND_FSR4_0_NPU = 2, /* FSR 4.0.2 INT8 (Hexagon HTP NPU) */
WL_FSR_BACKEND_FSR4_1_LITE_NPU = 3, /* FSR 4.1.2 Lite INT8 (Hexagon HTP NPU) */
WL_FSR_BACKEND_FSR4_1_FULL_NPU = 4, /* FSR 4.1.1 Full INT8 (Hexagon HTP NPU) */
WL_FSR_BACKEND_FSR4_1_LITE_GPU = 5, /* FSR 4.1.2 Lite INT8 (Adreno Vulkan DP4a GPU) */
WL_FSR_BACKEND_FSR4_1_FULL_GPU = 6, /* FSR 4.1.1 Full INT8 (Adreno Vulkan DP4a GPU) */
};
// Packed live control bits written by the Vulkan layer into mailbox->live_ctrl
#define WLFSR4_CTRL_BACKEND_MASK 0xFFULL
#define WLFSR4_CTRL_ENABLED_BIT (1ULL << 8)
#define WLFSR4_CTRL_SYNC_BIT (1ULL << 9)
#define WLFSR4_CTRL_SHARP_SHIFT 16u
#define WLFSR4_CTRL_SHARP_MASK 0xFFFFULL /* sharpness * 1000 */
// Ack flags written by the Vulkan layer into mailbox->ack
#define WLFSR4_ACK_WORK_BIT 0x8000000000000000ULL /* real GPU/NPU work recorded */
#define WLFSR4_ACK_NPU_ACTIVE_BIT 0x4000000000000000ULL /* Hexagon HTP NPU path active */
#define WLFSR4_ACK_SEQ_MASK 0x0000FFFFFFFFFFFFULL
// Frame flags
#define WLFSR4_FLAG_RESET (1u << 0)
#define WLFSR4_FLAG_HDR (1u << 1)
#define WLFSR4_FLAG_SRGB_OUT (1u << 2)
#define WLFSR4_FLAG_DEPTH_INVERTED (1u << 3)
#define WLFSR4_FLAG_DISPLAY_RES_MV (1u << 4)
#define WLFSR4_FLAG_SHARPEN (1u << 5)
#define WLFSR4_FLAG_MV_JITTERED (1u << 6)
#define WLFSR4_FLAG_AUTO_EXPOSURE (1u << 7)
#define WLFSR4_FLAG_XESS_FALLBACK (1u << 8) /* Bridge fell back from XeSS 3.0 -> request FSR 3.1 GPU */
// Source API tag (for logging & heuristics)
enum {
WLFSR4_API_UNKNOWN = 0,
WLFSR4_API_FFX_VK = 1,
WLFSR4_API_FFX_DX12 = 2,
WLFSR4_API_NGX_VK = 3,
WLFSR4_API_NGX_DX12 = 4,
WLFSR4_API_XESS_VK = 5,
WLFSR4_API_XESS_DX12 = 6,
WLFSR4_API_FSR3_VK = 7,
WLFSR4_API_FSR3_DX12 = 8,
WLFSR4_API_FSR2_VK = 9,
WLFSR4_API_FSR2_DX12 = 10,
};
// Preset hint
enum {
WLFSR4_PRESET_AUTO = 0,
WLFSR4_PRESET_PERF = 1,
WLFSR4_PRESET_ULTRAPERF = 2,
};
// In-game quality mode reported by DLSS / FidelityFX bridge -> Vulkan layer -> Left Sidebar
enum {
WLFSR4_QUALITY_AUTO = 0,
WLFSR4_QUALITY_NATIVE_AA = 1, /* DLAA / Native AA (1.0x) */
WLFSR4_QUALITY_QUALITY = 2, /* Quality (1.5x) */
WLFSR4_QUALITY_BALANCED = 3, /* Balanced (1.7x) */
WLFSR4_QUALITY_PERF = 4, /* Performance (2.0x) */
WLFSR4_QUALITY_ULTRA_PERF = 5, /* Ultra Performance (3.0x) */
WLFSR4_QUALITY_ULTRA_QUAL = 6, /* Ultra Quality (1.3x) */
};
typedef struct WlFsr4ImageRef {
uint64_t vk_image; /* non-dispatchable VkImage handle (guest == host under winevulkan) */
uint64_t vk_view; /* optional VkImageView handle (0 = layer creates its own view) */
uint32_t vk_format; /* VkFormat */
uint32_t vk_layout; /* VkImageLayout at dispatch entry & expected at exit */
uint32_t width;
uint32_t height;
uint32_t aspect; /* VkImageAspectFlags (0 = auto color/depth) */
uint32_t reserved;
} WlFsr4ImageRef; /* 40 bytes */
typedef struct WlFsr4FrameDesc {
uint64_t seq;
uint64_t reserved_handle;
WlFsr4ImageRef color;
WlFsr4ImageRef depth;
WlFsr4ImageRef motion;
WlFsr4ImageRef output;
uint32_t render_w;
uint32_t render_h;
uint32_t output_w;
uint32_t output_h;
float jitter_x;
float jitter_y;
float mv_scale_x;
float mv_scale_y;
float pre_exposure;
float sharpness;
float frame_time_ms;
float camera_near;
float camera_far;
float camera_fov_y;
uint32_t flags;
uint32_t api_source;
uint32_t preset_hint;
uint32_t quality_mode; /* WLFSR4_QUALITY_* */
uint32_t pad[2];
} WlFsr4FrameDesc; /* 256 bytes */
typedef struct WlFsr4Mailbox {
volatile uint64_t magic;
volatile uint64_t version;
volatile uint64_t ack; /* layer writes seq | flags synchronously inside vkCmdUpdateBuffer */
volatile uint64_t ack_count;
volatile uint64_t layer_caps; /* bit 0: layer alive, bit 1: HTP NPU ready, bit 2: 1080p shaders ready */
volatile uint64_t npu_dispatches;
volatile uint32_t last_htp_us; /* last Hexagon HTP execution time in microseconds */
volatile uint32_t last_status; /* 0=ok, 1=fallback-blit, 2=error */
volatile uint64_t live_ctrl; /* WLFSR4_CTRL_* packed live control synced from Android UI */
volatile uint32_t last_gpu_us; /* last GPU upscaler execution time in microseconds */
volatile uint32_t tele_gpu_us; /* bridge-reported XeSS 3.0 GPU/CPU time (us) on TELEMETRY ping */
uint64_t reserved[6];
WlFsr4FrameDesc slots[WLFSR4_SLOTS];
} WlFsr4Mailbox;
typedef struct WlFsr4DoorbellPayload {
uint64_t magic;
uint64_t seq;
} WlFsr4DoorbellPayload;
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
_Static_assert(sizeof(WlFsr4ImageRef) == 40, "WlFsr4ImageRef size");
_Static_assert(sizeof(WlFsr4FrameDesc) == 256, "WlFsr4FrameDesc size");
_Static_assert(sizeof(WlFsr4Mailbox) <= WLFSR4_MAILBOX_BYTES, "WlFsr4Mailbox fits in 8KB");
_Static_assert(sizeof(WlFsr4DoorbellPayload) == 16, "WlFsr4DoorbellPayload size");
#endif
#ifdef __cplusplus
}
#endif
+71
View File
@@ -0,0 +1,71 @@
// Lightweight non-blocking Vulkan GPU timestamp ring helper for live HUD ms telemetry.
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
#include <string.h>
#include "fsr4_pipeline.h"
#define WL_TIMER_SLOTS 4u
typedef struct {
VkQueryPool pool;
int enabled;
uint32_t slot_used[WL_TIMER_SLOTS];
uint32_t next_slot;
uint32_t last_us;
} WlGpuTimer;
static inline void wl_gpu_timer_init(WlGpuTimer *t, const WlVkDispatch *vk) {
memset(t, 0, sizeof *t);
if (!vk || !vk->has_timestamps || vk->timestamp_period <= 0.0f ||
!vk->CreateQueryPool || !vk->CmdResetQueryPool ||
!vk->CmdWriteTimestamp || !vk->GetQueryPoolResults) {
return;
}
VkQueryPoolCreateInfo ci = {
.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
.queryType = VK_QUERY_TYPE_TIMESTAMP,
.queryCount = WL_TIMER_SLOTS * 2u,
};
if (vk->CreateQueryPool(vk->device, &ci, NULL, &t->pool) == VK_SUCCESS && t->pool) {
t->enabled = 1;
}
}
static inline void wl_gpu_timer_destroy(WlGpuTimer *t, const WlVkDispatch *vk) {
if (t && t->pool && vk && vk->DestroyQueryPool) {
vk->DestroyQueryPool(vk->device, t->pool, NULL);
}
if (t) memset(t, 0, sizeof *t);
}
static inline uint32_t wl_gpu_timer_begin(WlGpuTimer *t, const WlVkDispatch *vk, VkCommandBuffer cb) {
if (!t || !t->enabled) return 0u;
uint32_t s = t->next_slot;
t->next_slot = (t->next_slot + 1u) % WL_TIMER_SLOTS;
// Non-blocking read of the oldest completed slot (zero stall)
if (t->slot_used[s]) {
uint64_t ts[2] = {0, 0};
VkResult r = vk->GetQueryPoolResults(vk->device, t->pool, s * 2u, 2u,
sizeof ts, ts, sizeof(uint64_t),
VK_QUERY_RESULT_64_BIT);
if (r == VK_SUCCESS && ts[1] >= ts[0]) {
double ns = (double)(ts[1] - ts[0]) * (double)vk->timestamp_period;
double us = ns * 1e-3;
if (us >= 0.0 && us < 500000.0) {
t->last_us = (uint32_t)(us + 0.5);
}
}
}
vk->CmdResetQueryPool(cb, t->pool, s * 2u, 2u);
vk->CmdWriteTimestamp(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, t->pool, s * 2u);
return s;
}
static inline void wl_gpu_timer_end(WlGpuTimer *t, const WlVkDispatch *vk, VkCommandBuffer cb, uint32_t slot) {
if (!t || !t->enabled) return;
vk->CmdWriteTimestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, t->pool, slot * 2u + 1u);
t->slot_used[slot] = 1u;
}
@@ -0,0 +1,353 @@
#!/usr/bin/env python3
"""Pack genuine AMD FidelityFX SDK v2.4.0 FSR 4.1.2 Lite INT8 weights & QNN HTP op graph
into fsr412_lite_i8.wpack (~35 KB) for on-device compilation via Qualcomm libQnnHtpPrepare.so
on Snapdragon SM8850 Hexagon HTP v81 (and v79).
Every weight, bias, and shift is extracted directly from AMD's official FSR 4.1.2 Lite
shaders (0002.comp, 0005.comp, 0007.comp) and genuine 27,392-byte weights.bin.
Verifies numerical equivalence against a numpy reference matching the exact shader integer math!
"""
import re
import sys
import struct
import hashlib
from pathlib import Path
import numpy as np
# Set from the command line: vela provider/spirv-sources/lite/converted, fsr412_lite/weights.bin, output.
VELA_LITE_DIR = None
WEIGHTS_BIN = None
OUT_WPACK = None
WPK_MAGIC = 0x314B505734525346 # "FSR4WPK1"
WPK_VERSION = 1
PASS0_PAD = 1056 # Must match WL_FSR4_PASS0_WB_BYTES (1056) in fsr4_qnn.h!
TK_APP_WRITE = 0
TK_APP_READ = 1
TK_NATIVE = 2
TK_STATIC_U8 = 3
TK_STATIC_S32 = 4
OP_CONV2D = 1
OP_RELU = 2
OP_ADD = 3
OP_CONCAT = 4
OP_SLICE_CH = 5
OP_DEPTH_TO_SPACE = 6
OP_CONVERT = 7
def unpack_i8_words(words):
raw = struct.pack(f"<{len(words)}I", *words)
return np.frombuffer(raw, dtype=np.int8)
def extract_const_uint_array(src: str, name: str, count: int) -> np.ndarray:
m = re.search(rf"const uint {re.escape(name)}\[{count}\]\s*=\s*uint\[\]\(([^)]+)\);", src, re.S)
assert m, f"Array {name}[{count}] not found"
vals = [int(x.rstrip("uU")) for x in re.findall(r"\d+u?", m.group(1))]
assert len(vals) == count, f"Expected {count}, got {len(vals)}"
return unpack_i8_words(vals)
def parse_sdot_1x1(src: str, line_prefix: str, in_vars: list, num_groups: int, Cin: int):
"""Parse inlined spvSDot_int_uint_uint 1x1 conv weights from 0002.comp."""
Co = num_groups * 4
W = np.zeros((Co, Cin, 1, 1), dtype=np.int8)
lines = [l for l in src.splitlines() if line_prefix in l]
assert len(lines) == num_groups, f"Expected {num_groups} lines for {line_prefix}, got {len(lines)}"
for g, line in enumerate(lines):
# Find each component of ivec4(...) by matching all spvSDot calls in order
calls = re.findall(r"spvSDot_int_uint_uint\(([^,]+),\s*(\d+)u,\s*0\)", line)
words_per_oc = Cin // 4
assert len(calls) == 4 * words_per_oc, f"Unexpected sdot count {len(calls)} on group {g}"
for oc_local in range(4):
oc = g * 4 + oc_local
sub = calls[oc_local * words_per_oc : (oc_local + 1) * words_per_oc]
for var_name, lit_str in sub:
var_name = var_name.strip()
k = in_vars.index(var_name)
b = struct.unpack("<4b", struct.pack("<I", int(lit_str)))
W[oc, k * 4 : k * 4 + 4, 0, 0] = b
return W
def load_all_weights():
init_bytes = WEIGHTS_BIN.read_bytes()
assert len(init_bytes) == 27392
init_i32 = np.frombuffer(init_bytes, dtype="<i4")
init_i8 = np.frombuffer(init_bytes, dtype=np.int8)
s02 = (VELA_LITE_DIR / "0002.comp").read_text(encoding="utf-8")
s05 = (VELA_LITE_DIR / "0005.comp").read_text(encoding="utf-8")
s07 = (VELA_LITE_DIR / "0007.comp").read_text(encoding="utf-8")
# ---- Block 1 (0002.comp) ----
# L1_c3: _935[576] = 2304 B. Index: ((256*dx + 768*dy + ic) + 16*oc) -> shape (dy=3, dx=3, oc=16, ic=16)
w_935 = extract_const_uint_array(s02, "_935", 576).reshape(3, 3, 16, 16)
l1_c3_w = np.ascontiguousarray(w_935.transpose(2, 3, 0, 1)) # OIHW (16, 16, 3, 3)
l1_c3_b = init_i32[864:880].copy()
# L1_e: 1x1 16->32 (lines with "max(ivec4(spvSDot_int_uint_uint(_1030[3]")
l1_e_w = parse_sdot_1x1(s02, "max(ivec4(spvSDot_int_uint_uint(_1030[3]",
["_1030[0]", "_1030[1]", "_1030[2]", "_1030[3]"], 8, 16)
l1_e_b = init_i32[1024:1056].copy()
# L1_f: 1x1 32->16 (lines with "vec4(ivec4(spvSDot_int_uint_uint(_2221")
l1_f_w = parse_sdot_1x1(s02, "vec4(ivec4(spvSDot_int_uint_uint(_2221",
["_2018", "_2047", "_2076", "_2105", "_2134", "_2163", "_2192", "_2221"], 4, 32)
l1_f_b = init_i32[1184:1200].copy()
# L1_down: 2x2 stride-2 16->32 in init_bytes[4864..6912]:
# 4864 + 16*oc -> tap(0,0), +5376 -> tap(dx=1,dy=0), +5888 -> tap(dx=0,dy=1), +6400 -> tap(dx=1,dy=1)
l1_d_w = np.zeros((32, 16, 2, 2), dtype=np.int8)
for dy, dx, boff in [(0, 0, 4864), (0, 1, 5376), (1, 0, 5888), (1, 1, 6400)]:
l1_d_w[:, :, dy, dx] = init_i8[boff : boff + 512].reshape(32, 16)
l1_d_b = init_i32[6912 // 4 : 6912 // 4 + 32].copy()
# ---- Block 2 (0005.comp) ----
# L2_c3: _1706[576] = (dy=3, dx=3, oc=16, ic=16)
w_1706 = extract_const_uint_array(s05, "_1706", 576).reshape(3, 3, 16, 16)
l2_c3_w = np.ascontiguousarray(w_1706.transpose(2, 3, 0, 1))
l2_c3_b = init_i32[9344 // 4 : 9344 // 4 + 16].copy()
# L2_e: _1707[512] = 2048 B -> (oc=64, ic=32, 1, 1)
l2_e_w = extract_const_uint_array(s05, "_1707", 512).reshape(64, 32, 1, 1)
l2_e_b = init_i32[11520 // 4 : 11520 // 4 + 64].copy()
# L2_f: _1708[512] = 2048 B -> (oc=32, ic=64, 1, 1)
l2_f_w = extract_const_uint_array(s05, "_1708", 512).reshape(32, 64, 1, 1)
l2_f_b = init_i32[13824 // 4 : 13824 // 4 + 32].copy()
# ---- Block 3 (0007.comp) ----
# L3_c3: init_bytes[13952..16256] -> (dy=3, dx=3, oc=16, ic=16)
l3_c3_w = np.ascontiguousarray(init_i8[13952 : 13952 + 2304].reshape(3, 3, 16, 16).transpose(2, 3, 0, 1))
l3_c3_b = init_i32[16256 // 4 : 16256 // 4 + 16].copy()
# L3_e: init_bytes[16384..18432] -> (oc=64, ic=32, 1, 1)
l3_e_w = init_i8[16384 : 16384 + 2048].reshape(64, 32, 1, 1).copy()
l3_e_b = init_i32[18432 // 4 : 18432 // 4 + 64].copy()
# L3_f: init_bytes[18688..20736] -> (oc=32, ic=64, 1, 1)
l3_f_w = init_i8[18688 : 18688 + 2048].reshape(32, 64, 1, 1).copy()
l3_f_b = init_i32[20736 // 4 : 20736 // 4 + 32].copy()
# L3_up: init_bytes[20864..22912] = 2048 B. Index: (512*dx + 1024*dy + 32*oc + ic) + 20864
# DCR DepthToSpace order is channel ((2*dy + dx) * 16 + oc) -> matches (dy, dx, oc, ic)!
l3_up_w = init_i8[20864 : 20864 + 2048].reshape(2, 2, 16, 32).reshape(64, 32, 1, 1).copy()
l3_up_b_16 = init_i32[22912 // 4 : 22912 // 4 + 16].copy()
l3_up_b = np.tile(l3_up_b_16, 4)
return dict(
l1_c3=(l1_c3_w, l1_c3_b), l1_e=(l1_e_w, l1_e_b), l1_f=(l1_f_w, l1_f_b), l1_d=(l1_d_w, l1_d_b),
l2_c3=(l2_c3_w, l2_c3_b), l2_e=(l2_e_w, l2_e_b), l2_f=(l2_f_w, l2_f_b),
l3_c3=(l3_c3_w, l3_c3_b), l3_e=(l3_e_w, l3_e_b), l3_f=(l3_f_w, l3_f_b), l3_up=(l3_up_w, l3_up_b),
)
class GraphPacker:
def __init__(self):
self.tensors = []
self.ops = []
self.payload = bytearray()
def _append_bytes(self, b: bytes):
pad = (-len(self.payload)) & 15
if pad:
self.payload.extend(b"\x00" * pad)
off = len(self.payload)
self.payload.extend(b)
return off, len(b)
def add_tensor(self, kind, dims, scale, offset, raw_bytes=None):
tid = len(self.tensors)
rank = len(dims)
d4 = list(dims) + [0] * (4 - rank)
off, sz = (0, 0)
if raw_bytes is not None:
off, sz = self._append_bytes(raw_bytes)
self.tensors.append(dict(
id=tid, kind=kind, dims=d4, rank=rank,
scale=float(scale), offset=int(offset),
data_offset=off, data_size=sz,
))
return tid
def add_act(self, h, w, c, scale, kind=TK_NATIVE):
return self.add_tensor(kind, [1, h, w, c], scale, -128)
def add_static_w_hwio(self, w_i8_hwio: np.ndarray, scale: float):
assert w_i8_hwio.dtype == np.int8 and w_i8_hwio.ndim == 4
w_u8 = np.ascontiguousarray(w_i8_hwio.astype(np.int16) + 128, dtype=np.uint8)
return self.add_tensor(TK_STATIC_U8, list(w_u8.shape), scale, -128, w_u8.tobytes())
def add_static_bias_s32_exact(self, b_i32: np.ndarray, s_in: float, s_w: float):
q = np.ascontiguousarray(b_i32.astype(np.int32))
return self.add_tensor(TK_STATIC_S32, [int(q.shape[0])], float(s_in) * float(s_w), 0, q.tobytes())
def emit_op(self, op_type, ins, out_id, p0=0, p1=0, p2=0, p3=0):
in3 = list(ins) + [0] * (3 - len(ins))
self.ops.append(dict(
op_type=op_type, in_ids=in3, num_ins=len(ins), out_id=out_id,
p0=int(p0), p1=int(p1), p2=int(p2), p3=int(p3),
))
return out_id
def conv2d_exact(self, x_id, w_oihw: np.ndarray, b_i32: np.ndarray, s_w: float,
s_out: float, stride=1, pad=0, out_kind=TK_NATIVE):
xt = self.tensors[x_id]
_, H, W, Cin = xt["dims"]
Co, Ci_w, kH, kW = w_oihw.shape
assert Ci_w == Cin, f"Cin mismatch {Ci_w} vs {Cin}"
w_hwio = np.ascontiguousarray(w_oihw.transpose(2, 3, 1, 0), dtype=np.int8)
w_id = self.add_static_w_hwio(w_hwio, s_w)
b_id = self.add_static_bias_s32_exact(b_i32, xt["scale"], s_w)
Ho = (H + 2 * pad - kH) // stride + 1
Wo = (W + 2 * pad - kW) // stride + 1
y_id = self.add_act(Ho, Wo, Co, s_out, kind=out_kind)
return self.emit_op(OP_CONV2D, [x_id, w_id, b_id], y_id, stride, pad)
def relu(self, x_id):
xt = self.tensors[x_id]
_, H, W, C = xt["dims"]
y_id = self.add_act(H, W, C, xt["scale"])
return self.emit_op(OP_RELU, [x_id], y_id)
def add(self, a_id, b_id, s_out, out_kind=TK_NATIVE):
at = self.tensors[a_id]
bt = self.tensors[b_id]
assert at["dims"] == bt["dims"], f"Add mismatch {at['dims']} vs {bt['dims']}"
_, H, W, C = at["dims"]
y_id = self.add_act(H, W, C, s_out, kind=out_kind)
return self.emit_op(OP_ADD, [a_id, b_id], y_id)
def concat_c(self, a_id, b_id, s_out):
at = self.tensors[a_id]
bt = self.tensors[b_id]
assert at["dims"][:3] == bt["dims"][:3]
assert abs(at["scale"] - s_out) < 1e-12 and abs(bt["scale"] - s_out) < 1e-12
_, H, W, Ca = at["dims"]
Cb = bt["dims"][3]
y_id = self.add_act(H, W, Ca + Cb, s_out)
return self.emit_op(OP_CONCAT, [a_id, b_id], y_id, 3)
def slice_ch(self, x_id, c_start, c_end):
xt = self.tensors[x_id]
_, H, W, C = xt["dims"]
assert 0 <= c_start < c_end <= C
y_id = self.add_act(H, W, c_end - c_start, xt["scale"])
return self.emit_op(OP_SLICE_CH, [x_id], y_id, c_start, c_end)
def depth_to_space(self, x_id, block=2, out_kind=TK_NATIVE):
xt = self.tensors[x_id]
_, H, W, C = xt["dims"]
assert C % (block * block) == 0
y_id = self.add_act(H * block, W * block, C // (block * block), xt["scale"], kind=out_kind)
return self.emit_op(OP_DEPTH_TO_SPACE, [x_id], y_id, block, 0)
def build_pack():
W = load_all_weights()
gp = GraphPacker()
# Input: [1, 540, 960, 16] UFIXED_POINT_8 (scale=1.0, offset=-128 -> int8 ^ 0x80)
x0 = gp.add_act(540, 960, 16, 1.0, kind=TK_APP_WRITE)
# ---- Block 1 (540x960) ----
# L1_c3: 3x3 16->16, >>7
h1 = gp.conv2d_exact(x0, W["l1_c3"][0], W["l1_c3"][1], s_w=2.0**-7, s_out=1.0, stride=1, pad=1)
# L1_e: 1x1 16->32 + Relu, >>9
m1 = gp.relu(gp.conv2d_exact(h1, W["l1_e"][0], W["l1_e"][1], s_w=2.0**-9, s_out=1.0, stride=1, pad=0))
# L1_f: 1x1 32->16, residual: round(acc*2^-6 + 0.5*x0)
# Use s_out=2.0 on L1_f (s_w=2^-5 -> q = acc*2^-6, float = 2*(acc>>6)); Add(f1, x0, s_out=2.0) -> q_r = round((acc>>6) + 0.5*x0)
f1 = gp.conv2d_exact(m1, W["l1_f"][0], W["l1_f"][1], s_w=2.0**-5, s_out=2.0, stride=1, pad=0)
r = gp.add(f1, x0, s_out=2.0) # r scale=2.0, int8 value exact!
# L1_down: 2x2 stride-2 16->32 (ch 0..15: >>6, ch 16..31: >>7). r has s_in=2.0!
d0_lo = gp.conv2d_exact(r, W["l1_d"][0][:16], W["l1_d"][1][:16], s_w=2.0**-7, s_out=1.0, stride=2, pad=0)
d0_hi = gp.conv2d_exact(r, W["l1_d"][0][16:], W["l1_d"][1][16:], s_w=2.0**-8, s_out=1.0, stride=2, pad=0)
d0 = gp.concat_c(d0_lo, d0_hi, s_out=1.0) # [1, 270, 480, 32], scale=1.0
# ---- Block 2 (270x480) ----
# L2_c3: 3x3 on d0[0..15], >>8
d0_s0 = gp.slice_ch(d0, 0, 16)
d0_s1 = gp.slice_ch(d0, 16, 32)
h2 = gp.conv2d_exact(d0_s0, W["l2_c3"][0], W["l2_c3"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=1)
c2 = gp.concat_c(h2, d0_s1, s_out=1.0)
m2 = gp.relu(gp.conv2d_exact(c2, W["l2_e"][0], W["l2_e"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=0))
# L2_f: ch 0..15 -> acc*2^-6 + 0.5*d0_lo; ch 16..31 -> acc*2^-7 + 0.5*d0_hi
f2_lo = gp.conv2d_exact(m2, W["l2_f"][0][:16], W["l2_f"][1][:16], s_w=2.0**-5, s_out=2.0, stride=1, pad=0)
f2_hi = gp.conv2d_exact(m2, W["l2_f"][0][16:], W["l2_f"][1][16:], s_w=2.0**-6, s_out=2.0, stride=1, pad=0)
e0_lo = gp.add(f2_lo, d0_s0, s_out=2.0) # scale=2.0
e0_hi = gp.add(f2_hi, d0_s1, s_out=2.0) # scale=2.0
# ---- Block 3 (270x480 -> 540x960) ----
# L3_c3: 3x3 on e0_lo (s_in=2.0), >>8 -> keep s_out=2.0 (s_w=2^-8 -> 2.0*2^-8/2.0 = 2^-8!)
h3 = gp.conv2d_exact(e0_lo, W["l3_c3"][0], W["l3_c3"][1], s_w=2.0**-8, s_out=2.0, stride=1, pad=1)
c3 = gp.concat_c(h3, e0_hi, s_out=2.0) # both scale=2.0!
# L3_e: 1x1 32->64 + Relu, >>7 (s_in=2.0, s_w=2^-8, s_out=1.0 -> 2.0*2^-8/1.0 = 2^-7!)
m3 = gp.relu(gp.conv2d_exact(c3, W["l3_e"][0], W["l3_e"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=0))
# L3_f: ch 0..15 -> acc*2^-6 + 1.0*e0_lo; ch 16..31 -> acc*2^-6 + 2.0*e0_hi
f3_lo = gp.conv2d_exact(m3, W["l3_f"][0][:16], W["l3_f"][1][:16], s_w=2.0**-5, s_out=2.0, stride=1, pad=0)
z3_lo = gp.add(f3_lo, e0_lo, s_out=2.0) # (2*(acc>>6) + 2*e0_lo)/2 = (acc>>6) + e0_lo! scale=2.0
f3_hi = gp.conv2d_exact(m3, W["l3_f"][0][16:], W["l3_f"][1][16:], s_w=2.0**-6, s_out=1.0, stride=1, pad=0)
z3_hi = gp.add(f3_hi, e0_hi, s_out=1.0) # (acc>>6 + 2*e0_hi)/1 = (acc>>6) + 2*e0_hi! scale=1.0
# L3_up: 1x1 32->64 split cleanly across z3_lo (scale=2.0) and z3_hi (scale=1.0) + DepthToSpace(2, DCR) + skip r (scale=2.0)
# Target shift: >>8 (0.0001220703125 * 32 = 2^-8). We want output at scale=2.0 so Add(up_d2s, r, s_out=2.0) = (acc>>8) + r!
# For z3_lo (s_in=2.0): s_in * s_w / s_out = 2^-8 -> s_w = 2^-8! (carry full bias here)
# For z3_hi (s_in=1.0): s_in * s_w / s_out = 2^-8 -> s_w = 2^-7! (zero bias here)
up_lo = gp.conv2d_exact(z3_lo, W["l3_up"][0][:, :16, :, :], W["l3_up"][1], s_w=2.0**-8, s_out=2.0, stride=1, pad=0)
up_hi = gp.conv2d_exact(z3_hi, W["l3_up"][0][:, 16:, :, :], np.zeros(64, dtype=np.int32), s_w=2.0**-7, s_out=2.0, stride=1, pad=0)
up_sum = gp.add(up_lo, up_hi, s_out=2.0)
up_d2s = gp.depth_to_space(up_sum, block=2)
out_id = gp.add(up_d2s, r, s_out=2.0, out_kind=TK_APP_READ)
# Serialize WPK1 binary (exact same header format as fsr4_v07_i8.wpack!)
hdr = struct.pack(
"<QIIIIIIIIIIffII",
WPK_MAGIC, WPK_VERSION,
540, 960, 16,
540, 960, 16,
len(gp.tensors), len(gp.ops),
x0, 1.0, 2.0,
out_id, len(gp.payload),
)
assert len(hdr) == 64
buf = bytearray(hdr)
buf.extend(b"\x00" * PASS0_PAD)
for t in gp.tensors:
buf.extend(struct.pack(
"<IIIIIIIfiII",
t["id"], t["kind"],
t["dims"][0], t["dims"][1], t["dims"][2], t["dims"][3],
t["rank"], t["scale"], t["offset"],
t["data_offset"], t["data_size"],
))
for o in gp.ops:
buf.extend(struct.pack(
"<IIIIIIIIII",
o["op_type"],
o["in_ids"][0], o["in_ids"][1], o["in_ids"][2],
o["num_ins"], o["out_id"],
o["p0"], o["p1"], o["p2"], o["p3"],
))
buf.extend(gp.payload)
OUT_WPACK.parent.mkdir(parents=True, exist_ok=True)
OUT_WPACK.write_bytes(bytes(buf))
print(f"Wrote {OUT_WPACK} ({len(buf)} bytes, {len(gp.tensors)} tensors, {len(gp.ops)} ops, "
f"payload={len(gp.payload)} B, sha256={hashlib.sha256(buf).hexdigest()[:16]})")
# Quick sanity stats on extracted genuine AMD weights
for k, (wt, bs) in W.items():
print(f" {k:6s}: w={tuple(wt.shape)} [{wt.min()},{wt.max()}] b={tuple(bs.shape)} [{bs.min()},{bs.max()}]")
if __name__ == "__main__":
if len(sys.argv) != 4:
sys.exit("usage: pack_fsr412_lite_weights.py VELA_LITE_CONVERTED_DIR WEIGHTS.bin OUT.wpack")
VELA_LITE_DIR, WEIGHTS_BIN, OUT_WPACK = (Path(a) for a in sys.argv[1:4])
build_pack()
@@ -0,0 +1,340 @@
#!/usr/bin/env python3
"""Pack AMD FSR 4.0.2 INT8 (fsr4_model_v07_i8_quality) weights & QNN HTP op graph
into a compact self-contained binary asset (fsr4_v07_i8.wpack) for on-device
compilation via Qualcomm libQnnHtpPrepare.so (HTP v81 / v79).
Every op uses standard QNN qti.aisw NHWC / HWIO layouts, group=1 Conv2d,
UFIXED_POINT_8 (offset=-128) weights/activations, SFIXED_POINT_32 biases,
and 1x1 Conv2d + DepthToSpace(DCR, 2x2) for exact 2x2 stride-2 ConvTranspose.
"""
import os
import sys
import struct
import hashlib
from pathlib import Path
import numpy as np
# Checkout of puzzled-pancake/fsr4-hexagon (provides model/sim/fsr4_sim.py).
FSR4_HEX_ROOT = Path(os.environ.get("FSR4_HEXAGON_ROOT", "fsr4-hexagon"))
sys.path.insert(0, str(FSR4_HEX_ROOT / "model/sim"))
import fsr4_sim as S
WPK_MAGIC = 0x314B505734525346 # "FSR4WPK1"
WPK_VERSION = 1
TK_APP_WRITE = 0
TK_APP_READ = 1
TK_NATIVE = 2
TK_STATIC_U8 = 3
TK_STATIC_S32 = 4
OP_CONV2D = 1
OP_RELU = 2
OP_ADD = 3
OP_CONCAT = 4
OP_SLICE_CH = 5
OP_DEPTH_TO_SPACE = 6
OP_CONVERT = 7
S_OUT = 0.303211569786 # Matches wv2a.comp / postA contract
class GraphPacker:
def __init__(self):
self.tensors = []
self.ops = []
self.payload = bytearray()
def _append_bytes(self, b: bytes):
# 16-byte align every static tensor in payload
pad = (-len(self.payload)) & 15
if pad:
self.payload.extend(b"\x00" * pad)
off = len(self.payload)
self.payload.extend(b)
return off, len(b)
def add_tensor(self, kind, dims, scale, offset, raw_bytes=None):
tid = len(self.tensors)
rank = len(dims)
d4 = list(dims) + [0] * (4 - rank)
off, sz = (0, 0)
if raw_bytes is not None:
off, sz = self._append_bytes(raw_bytes)
self.tensors.append(dict(
id=tid, kind=kind, dims=d4, rank=rank,
scale=float(scale), offset=int(offset),
data_offset=off, data_size=sz,
))
return tid
def add_act(self, h, w, c, scale, kind=TK_NATIVE):
return self.add_tensor(kind, [1, h, w, c], scale, -128)
def add_static_w_hwio(self, w_i8_hwio: np.ndarray, scale: float):
assert w_i8_hwio.dtype == np.int8 and w_i8_hwio.ndim == 4
w_u8 = np.ascontiguousarray(w_i8_hwio.astype(np.int16) + 128, dtype=np.uint8)
return self.add_tensor(TK_STATIC_U8, list(w_u8.shape), scale, -128, w_u8.tobytes())
def add_static_bias_s32(self, b_f32: np.ndarray, s_in: float, s_w: float):
s_b = float(s_in) * float(s_w)
q = np.rint(b_f32.astype(np.float64) / s_b)
q = np.clip(q, -2147483648, 2147483647).astype(np.int32)
q = np.ascontiguousarray(q)
return self.add_tensor(TK_STATIC_S32, [int(q.shape[0])], s_b, 0, q.tobytes())
def emit_op(self, op_type, ins, out_id, p0=0, p1=0, p2=0, p3=0):
in3 = list(ins) + [0] * (3 - len(ins))
self.ops.append(dict(
op_type=op_type, in_ids=in3, num_ins=len(ins), out_id=out_id,
p0=int(p0), p1=int(p1), p2=int(p2), p3=int(p3),
))
return out_id
def conv2d(self, x_id, w_oihw: np.ndarray, b_f32: np.ndarray, s_w: float,
s_out: float, stride=1, pad=0, out_kind=TK_NATIVE):
xt = self.tensors[x_id]
_, H, W, Cin = xt["dims"]
Co, Ci_w, kH, kW = w_oihw.shape
assert Ci_w == Cin, f"Cin mismatch {Ci_w} vs {Cin}"
# OIHW -> HWIO
w_hwio = np.ascontiguousarray(w_oihw.transpose(2, 3, 1, 0), dtype=np.int8)
w_id = self.add_static_w_hwio(w_hwio, s_w)
b_id = self.add_static_bias_s32(b_f32, xt["scale"], s_w)
Ho = (H + 2 * pad - kH) // stride + 1
Wo = (W + 2 * pad - kW) // stride + 1
y_id = self.add_act(Ho, Wo, Co, s_out, kind=out_kind)
return self.emit_op(OP_CONV2D, [x_id, w_id, b_id], y_id, stride, pad)
def relu(self, x_id):
xt = self.tensors[x_id]
_, H, W, C = xt["dims"]
y_id = self.add_act(H, W, C, xt["scale"])
return self.emit_op(OP_RELU, [x_id], y_id)
def add(self, a_id, b_id, s_out):
at = self.tensors[a_id]
bt = self.tensors[b_id]
assert at["dims"] == bt["dims"], f"Add shape mismatch {at['dims']} vs {bt['dims']}"
_, H, W, C = at["dims"]
y_id = self.add_act(H, W, C, s_out)
return self.emit_op(OP_ADD, [a_id, b_id], y_id)
def concat_c(self, a_id, b_id, s_out):
at = self.tensors[a_id]
bt = self.tensors[b_id]
assert at["dims"][:3] == bt["dims"][:3]
_, H, W, Ca = at["dims"]
Cb = bt["dims"][3]
# Rescale a/b to common s_out if scales differ (HTP Concat requires matching scales)
if abs(at["scale"] - s_out) > 1e-12:
a2 = self.add_act(H, W, Ca, s_out)
a_id = self.emit_op(OP_CONVERT, [a_id], a2)
if abs(bt["scale"] - s_out) > 1e-12:
b2 = self.add_act(H, W, Cb, s_out)
b_id = self.emit_op(OP_CONVERT, [b_id], b2)
y_id = self.add_act(H, W, Ca + Cb, s_out)
return self.emit_op(OP_CONCAT, [a_id, b_id], y_id, 3)
def slice_ch(self, x_id, c_start, c_end, s_out=None):
xt = self.tensors[x_id]
_, H, W, C = xt["dims"]
assert 0 <= c_start < c_end <= C
y_id = self.add_act(H, W, c_end - c_start, xt["scale"])
self.emit_op(OP_SLICE_CH, [x_id], y_id, c_start, c_end)
if s_out is not None and abs(xt["scale"] - s_out) > 1e-12:
y2 = self.add_act(H, W, c_end - c_start, s_out)
y_id = self.emit_op(OP_CONVERT, [y_id], y2)
return y_id
def conv_transpose_2x2(self, x_id, w_cio22: np.ndarray, b_f32: np.ndarray,
s_w: float, s_out: float, out_kind=TK_NATIVE):
"""Exact 2x2 stride-2 ConvTranspose via 1x1 Conv2d + DepthToSpace(DCR, 2)."""
xt = self.tensors[x_id]
_, H, W, Cin = xt["dims"]
Ci_w, Co, kH, kW = w_cio22.shape
assert Ci_w == Cin and kH == 2 and kW == 2
# DCR DepthToSpace: channel ((ky * 2 + kx) * Co + co) -> spatial (2y+ky, 2x+kx, co)
w_dcr = w_cio22.transpose(2, 3, 1, 0).reshape(4 * Co, Cin, 1, 1) # OIHW for 1x1 Conv2d
b_dcr = np.tile(b_f32, 4)
tmp_id = self.conv2d(x_id, w_dcr, b_dcr, s_w, s_out, stride=1, pad=0)
y_id = self.add_act(H * 2, W * 2, Co, s_out, kind=out_kind)
return self.emit_op(OP_DEPTH_TO_SPACE, [tmp_id], y_id, 2, 0)
def verify_ct2d_equivalence(L):
"""Prove 1x1 Conv2d + DepthToSpace(DCR) is bit-identical to fsr4_sim.convtranspose2x2_i8."""
w = L["dec2_ct_weight"] # [Cin, Cout, 2, 2]
rng = np.random.default_rng(42)
x = rng.integers(-60, 60, size=(4, 6, w.shape[0]), dtype=np.int8)
ref = S.convtranspose2x2_i8(x, w)
w_dcr = w.transpose(2, 3, 1, 0).reshape(4 * w.shape[1], w.shape[0]) # [4*Co, Cin]
tmp = np.einsum("hwc,oc->hwo", x.astype(np.int64), w_dcr.astype(np.int64))
# DCR DepthToSpace: [H, W, 2, 2, Co] -> [H, 2, W, 2, Co] -> [2H, 2W, Co]
Co = w.shape[1]
got = tmp.reshape(4, 6, 2, 2, Co).transpose(0, 2, 1, 3, 4).reshape(8, 12, Co)
assert np.array_equal(ref, got), "CT2D <-> 1x1+D2S mismatch!"
print("[PASS] 1x1 Conv2d + DepthToSpace(DCR) bit-exact match with fsr4_sim.convtranspose2x2_i8")
def expand_k2s2_to_k3s2p1(w_oihw: np.ndarray) -> np.ndarray:
"""Decompose k=2,s=2,p=0 conv into HTP-native k=3,s=2,p=1 conv (zero top/left taps)."""
O, I, kH, kW = w_oihw.shape
assert kH == 2 and kW == 2
w3 = np.zeros((O, I, 3, 3), dtype=np.int8)
w3[:, :, 1:3, 1:3] = w_oihw
return w3
def expand_group2_to_group1(w_oihw: np.ndarray) -> np.ndarray:
"""Decompose group=2 conv into HTP-native group=1 conv (zero cross-group weights)."""
O, Ci_g, kH, kW = w_oihw.shape
Og = O // 2
wfull = np.zeros((O, 2 * Ci_g, kH, kW), dtype=np.int8)
wfull[:Og, :Ci_g] = w_oihw[:Og]
wfull[Og:, Ci_g:2 * Ci_g] = w_oihw[Og:]
return wfull
def build_pack(out_path: Path, pass0_raw_path: Path):
L = S.load_layers()
L = S.load_with_pass0_scale(L)
verify_ct2d_equivalence(L)
pass0_wb = pass0_raw_path.read_bytes()
assert len(pass0_wb) == 1056
assert hashlib.md5(pass0_wb).hexdigest() == "0915f25de428aaeee396701e3abfd341"
p = GraphPacker()
calls = L["_calls"]
c = [calls[i]["args"] for i in range(len(calls))]
sc = lambda k: float(L[k])
x_in = p.add_act(540, 960, 16, S.S_IN, kind=TK_APP_WRITE)
def cnb(x_id, prefix, s_mid1, s_mid2, s_out):
y = p.conv2d(x_id, L[f"{prefix}_conv_dw_weight"], L[f"{prefix}_conv_dw_bias"],
sc(f"scale__{prefix}_conv_dw"), s_mid1, stride=1, pad=1)
y = p.conv2d(y, L[f"{prefix}_pw_expand_weight"], L[f"{prefix}_pw_expand_bias"],
sc(f"scale__{prefix}_pw_expand"), s_mid2, stride=1, pad=0)
y = p.relu(y)
y = p.conv2d(y, L[f"{prefix}_pw_contract_weight"], L[f"{prefix}_pw_contract_bias"],
sc(f"scale__{prefix}_pw_contract"), s_out, stride=1, pad=0)
return p.add(y, x_id, s_out)
def k2s2b(x_id, wkey, bkey, skey, q0, q1):
W = L[wkey]; b = L[bkey]; C = W.shape[0]
w0 = expand_k2s2_to_k3s2p1(W[:C // 2])
w1 = expand_k2s2_to_k3s2p1(W[C // 2:])
h0 = p.conv2d(x_id, w0, b[:C // 2], sc(skey), q0, stride=2, pad=1)
h1 = p.conv2d(x_id, w1, b[C // 2:], sc(skey), q1, stride=2, pad=1)
return (h0, h1)
def fnb(xg, prefix, q0, q1, act, variant, o0=None, o1=None, uniform_out=None):
h0, h1 = xg
Wsp = L[f"{prefix}_spatial_weight"]
if variant == "64":
Wsp = expand_group2_to_group1(Wsp)
y = p.conv2d(h0, Wsp, L[f"{prefix}_spatial_bias"],
sc(f"scale__{prefix}_spatial"), q1, stride=1, pad=1)
cat = p.concat_c(y, h1, q1)
y = p.conv2d(cat, L[f"{prefix}_pw_expand_weight"], L[f"{prefix}_pw_expand_bias"],
sc(f"scale__{prefix}_pw_expand"), act, stride=1, pad=0)
y = p.relu(y)
# Skip tensor at common scale
s_skip = max(q0, q1)
skip = p.concat_c(h0, h1, s_skip)
if uniform_out is not None:
y = p.conv2d(y, L[f"{prefix}_pw_contract_weight"], L[f"{prefix}_pw_contract_bias"],
sc(f"scale__{prefix}_pw_contract"), uniform_out, stride=1, pad=0)
return p.add(y, skip, uniform_out)
s_mid = max(o0, o1)
y = p.conv2d(y, L[f"{prefix}_pw_contract_weight"], L[f"{prefix}_pw_contract_bias"],
sc(f"scale__{prefix}_pw_contract"), s_mid, stride=1, pad=0)
y = p.add(y, skip, s_mid)
C = p.tensors[y]["dims"][3]
return (p.slice_ch(y, 0, C // 2, o0), p.slice_ch(y, C // 2, C, o1))
def fnb_ct2d(xg, prefix, skip_id, q0, q1, act, s_fnb, variant, wct, bct, sct,
o0=None, o1=None, uniform_out=None):
y = fnb(xg, prefix, q0, q1, act, variant, uniform_out=s_fnb)
s_ct = uniform_out if uniform_out is not None else max(o0, o1)
y = p.conv_transpose_2x2(y, L[wct], L[bct], sc(sct), s_ct)
y = p.add(y, skip_id, s_ct)
if uniform_out is not None:
return y
C = p.tensors[y]["dims"][3]
return (p.slice_ch(y, 0, C // 2, o0), p.slice_ch(y, C // 2, C, o1))
# Full 13-block FSR 4.0.2 INT8 U-Net (exact match to build_onnx.py / fsr4_sim.py)
y1 = cnb(x_in, "encoder2_RB0", c[0][1], c[0][3], 0.01933070458471775)
y2 = cnb(y1, "encoder2_RB1", c[1][1], c[1][3], 0.02335178479552269)
skip2 = y2
xg = k2s2b(y2, "enc2_ds_weight", "enc2_ds_bias", "scale__enc2_ds", c[2][0], c[2][1])
xg = fnb(xg, "encoder3_ResidualBlock_0", c[3][0], c[3][1], c[3][2], "32", o0=c[3][3], o1=c[3][4])
y5 = fnb(xg, "encoder3_ResidualBlock_1", c[4][0], c[4][1], c[4][2], "32", uniform_out=0.019347405061125755)
skip3 = y5
xg = k2s2b(y5, "enc3_ds_weight", "enc3_ds_bias", "scale__enc3_ds", c[5][0], c[5][1])
xg = fnb(xg, "bottleneck_ResidualBlock_0", c[6][0], c[6][1], c[6][2], "64", o0=c[6][3], o1=c[6][4])
xg = fnb(xg, "bottleneck_ResidualBlock_1", c[7][0], c[7][1], c[7][2], "64", o0=c[7][3], o1=c[7][4])
xg = fnb_ct2d(xg, "bottleneck_ResidualBlock_2", skip3, c[8][0], c[8][1], c[8][2], c[8][3], "64",
"bottleneck_ct_weight", "bottleneck_ct_bias", "scale__bottleneck_ct", o0=c[8][4], o1=c[8][5])
xg = fnb(xg, "decoder3_ResidualBlock_1", c[9][0], c[9][1], c[9][2], "32", o0=c[9][3], o1=c[9][4])
y11 = fnb_ct2d(xg, "decoder3_ResidualBlock_2", skip2, c[10][0], c[10][1], c[10][2], c[10][3], "32",
"dec3_ct_weight", "dec3_ct_bias", "scale__dec3_ct", uniform_out=0.027206305414438248)
y12 = cnb(y11, "decoder2_RB1", c[11][1], c[11][3], 0.035173576325178146)
y13 = cnb(y12, "decoder2_ResidualBlock_2", c[12][1], c[12][3], 0.06884194910526276)
y_out = p.conv_transpose_2x2(y13, L["dec2_ct_weight"], L["dec2_ct_bias"],
sc("scale__dec2_ct"), S_OUT, out_kind=TK_APP_READ)
assert p.tensors[x_in]["dims"] == [1, 540, 960, 16]
assert p.tensors[y_out]["dims"] == [1, 1080, 1920, 8]
# Serialize compact binary pack
out_path.parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "wb") as f:
# Header (64 bytes + 1056 bytes pass0_wb = 1120 bytes)
hdr = struct.pack(
"<QIIIIIIIIIIffII",
WPK_MAGIC, WPK_VERSION,
540, 960, 16,
1080, 1920, 8,
len(p.tensors), len(p.ops),
x_in,
S.S_IN, S_OUT,
y_out, len(p.payload),
)
assert len(hdr) == 64
f.write(hdr)
f.write(pass0_wb)
# Tensor table (44 bytes each)
for t in p.tensors:
f.write(struct.pack(
"<IIIIIIIfiII",
t["id"], t["kind"],
t["dims"][0], t["dims"][1], t["dims"][2], t["dims"][3],
t["rank"], t["scale"], t["offset"],
t["data_offset"], t["data_size"],
))
# Op table (40 bytes each)
for o in p.ops:
f.write(struct.pack(
"<IIIIIIIIII",
o["op_type"],
o["in_ids"][0], o["in_ids"][1], o["in_ids"][2],
o["num_ins"], o["out_id"],
o["p0"], o["p1"], o["p2"], o["p3"],
))
# Static weight/bias payload
f.write(p.payload)
sz = out_path.stat().st_size
print(f"[PASS] Wrote {out_path} ({sz:,} bytes): {len(p.tensors)} tensors, {len(p.ops)} QNN ops, {len(p.payload):,} B weights/biases")
if __name__ == "__main__":
if len(sys.argv) != 3:
sys.exit("usage: FSR4_HEXAGON_ROOT=<fsr4-hexagon checkout> pack_fsr4_weights.py OUT.wpack PASS0_WB.raw")
build_pack(Path(sys.argv[1]), Path(sys.argv[2]))
@@ -0,0 +1,240 @@
#version 450
// Winlator Ludashi Native GPU FSR 3.1 Pass 2: Temporal Super-Resolution Accumulation
// Runs at full native output resolution (ow x oh) on Adreno GPU (0 NPU watts, 0 extra latency).
// Combines jitter-aware Lanczos-2 reconstruction over 100% native rw x rh color,
// 5-tap Catmull-Rom bicubic history reprojection, YCoCg variance-guided AABB clipping
// (Salvi/AMD FSR 3.1), and motion/disocclusion-aware adaptive temporal accumulation.
layout(local_size_x = 8, local_size_y = 8) in;
layout(set = 0, binding = 0) uniform sampler2D u_color; // native rw x rh game color
layout(set = 0, binding = 1) uniform sampler2D u_dilated_mv; // rw x rh RG16F dilated UV velocity
layout(set = 0, binding = 2) uniform sampler2D u_lock_mask; // rw x rh RGBA16F disocclusion/luma
layout(set = 0, binding = 3) uniform sampler2D u_hist_prev; // ow x oh RGBA16F previous frame (LINEAR)
layout(set = 0, binding = 4, rgba16f) writeonly uniform image2D u_hist_cur;
layout(push_constant) uniform PC {
vec2 u_jitter;
vec2 u_mv_scale;
vec2 u_jitter_cancel;
float u_expo;
float u_sharp;
uint rw;
uint rh;
uint ow;
uint oh;
uint flags; // bit 3: reset
uint pad0;
} pc;
const float PI = 3.14159265359;
float luma(vec3 c) {
return dot(max(c, vec3(0.0)), vec3(0.2126, 0.7152, 0.0722));
}
// Karis/Reinhard reversible perceptual compression for artifact-free HDR temporal blending
vec3 tonemap(vec3 c) {
c = max(c, vec3(0.0));
return c / (1.0 + luma(c));
}
vec3 untonemap(vec3 c) {
c = clamp(c, vec3(0.0), vec3(0.9995));
return c / max(1.0 - luma(c), 1e-4);
}
vec3 rgbToYCoCg(vec3 c) {
float co = c.r - c.b;
float t = c.b + co * 0.5;
float cg = c.g - t;
float y = t + cg * 0.5;
return vec3(y, co, cg);
}
vec3 yCoCgToRgb(vec3 ycc) {
float t = ycc.x - ycc.z * 0.5;
float g = ycc.z + t;
float b = t - ycc.y * 0.5;
float r = b + ycc.y;
return max(vec3(r, g, b), vec3(0.0));
}
// Clip ray from history -> current onto YCoCg AABB (crisper than simple clamp, eliminates ghost trails)
vec3 clipAABB(vec3 aabb_min, vec3 aabb_max, vec3 cur, vec3 hist) {
vec3 center = 0.5 * (aabb_max + aabb_min);
vec3 half_ext = 0.5 * (aabb_max - aabb_min) + vec3(1e-5);
vec3 offset = hist - center;
vec3 v_unit = offset / half_ext;
vec3 a_unit = abs(v_unit);
float ma = max(a_unit.x, max(a_unit.y, a_unit.z));
if (ma > 1.0) {
return center + offset / ma;
}
return hist;
}
float lanczos2(float x) {
x = abs(x);
if (x < 1e-4) return 1.0;
if (x >= 2.0) return 0.0;
float px = PI * x;
return (sin(px) / px) * (sin(px * 0.5) / (px * 0.5));
}
// Fast 5-tap Catmull-Rom bicubic history fetch (Jorge Jimenez / AMD FSR 3.1 style)
vec4 sampleHistoryCatmullRom(vec2 uv, vec2 tex_size) {
vec2 pos = uv * tex_size;
vec2 center = floor(pos - 0.5) + 0.5;
vec2 f = pos - center;
vec2 f2 = f * f;
vec2 f3 = f2 * f;
vec2 w0 = f2 - 0.5 * (f3 + f);
vec2 w1 = 1.5 * f3 - 2.5 * f2 + 1.0;
vec2 w3 = 0.5 * (f3 - f2);
vec2 w2 = 1.0 - w0 - w1 - w3;
vec2 w12 = w1 + w2;
vec2 tc0 = (center - 1.0) / tex_size;
vec2 tc3 = (center + 2.0) / tex_size;
vec2 tc12 = (center + w2 / max(w12, vec2(1e-5))) / tex_size;
vec4 s0 = textureLod(u_hist_prev, vec2(tc12.x, tc0.y), 0.0);
vec4 s1 = textureLod(u_hist_prev, vec2(tc0.x, tc12.y), 0.0);
vec4 s2 = textureLod(u_hist_prev, vec2(tc12.x, tc12.y), 0.0);
vec4 s3 = textureLod(u_hist_prev, vec2(tc3.x, tc12.y), 0.0);
vec4 s4 = textureLod(u_hist_prev, vec2(tc12.x, tc3.y), 0.0);
float cw0 = w12.x * w0.y;
float cw1 = w0.x * w12.y;
float cw2 = w12.x * w12.y;
float cw3 = w3.x * w12.y;
float cw4 = w12.x * w3.y;
float wsum = cw0 + cw1 + cw2 + cw3 + cw4;
vec4 res = (s0 * cw0 + s1 * cw1 + s2 * cw2 + s3 * cw3 + s4 * cw4) / max(wsum, 1e-5);
res.rgb = max(res.rgb, vec3(0.0));
return res;
}
void main() {
uvec2 tid = gl_GlobalInvocationID.xy;
if (tid.x >= pc.ow || tid.y >= pc.oh) return;
ivec2 col_sz = textureSize(u_color, 0);
ivec2 r_lim = ivec2(int(pc.rw) - 1, int(pc.rh) - 1);
ivec2 col_lim = min(r_lim, col_sz - ivec2(1));
vec2 out_size = vec2(pc.ow, pc.oh);
vec2 ren_size = vec2(pc.rw, pc.rh);
vec2 out_uv = (vec2(tid) + vec2(0.5)) / out_size;
// Exact jitter-corrected native render pixel position
vec2 lr_f = out_uv * ren_size - vec2(0.5) + pc.u_jitter;
ivec2 lr_c = ivec2(roundEven(lr_f));
// Fetch dilated MV and disocclusion mask at nearest native pixel
ivec2 mv_p = clamp(lr_c, ivec2(0), r_lim);
vec2 vel = texelFetch(u_dilated_mv, mv_p, 0).xy;
vec4 lock_info = texelFetch(u_lock_mask, mv_p, 0);
float disocc = lock_info.g;
float vel_norm = lock_info.a;
// 3x3 Lanczos-2 upsampling + YCoCg statistical moments (m1, m2) + min/max
vec3 lanc_sum = vec3(0.0);
float lanc_wsum = 0.0;
float center_prox = 0.0;
vec3 m1 = vec3(0.0);
vec3 m2 = vec3(0.0);
vec3 box_min = vec3(1e9);
vec3 box_max = vec3(-1e9);
vec3 cross_min = vec3(1e9);
vec3 cross_max = vec3(-1e9);
for (int dy = -1; dy <= 1; ++dy) {
for (int dx = -1; dx <= 1; ++dx) {
ivec2 q = clamp(lr_c + ivec2(dx, dy), ivec2(0), col_lim);
vec3 raw_c = max(texelFetch(u_color, q, 0).rgb, vec3(0.0)) * pc.u_expo;
vec3 tm = tonemap(raw_c);
vec3 ycc = rgbToYCoCg(tm);
m1 += ycc;
m2 += ycc * ycc;
box_min = min(box_min, ycc);
box_max = max(box_max, ycc);
if (dx == 0 || dy == 0) {
cross_min = min(cross_min, ycc);
cross_max = max(cross_max, ycc);
}
vec2 d = vec2(lr_c + ivec2(dx, dy)) - lr_f;
float w = lanczos2(d.x) * lanczos2(d.y);
// Clamp negative Lanczos lobes slightly to avoid ringing on harsh high-contrast UI/edges
float w_safe = max(w, -0.06);
lanc_sum += tm * w_safe;
lanc_wsum += w_safe;
if (dx == 0 && dy == 0) {
center_prox = clamp(1.0 - length(d), 0.0, 1.0);
}
}
}
vec3 cur_tm = clamp(lanc_sum / max(lanc_wsum, 1e-5), vec3(0.0), vec3(0.9995));
vec3 cur_ycc = rgbToYCoCg(cur_tm);
// Blend 3x3 full neighborhood & 5-tap cross neighborhood (standard FSR/TAA rounded diamond)
vec3 min_ycc = 0.5 * (box_min + cross_min);
vec3 max_ycc = 0.5 * (box_max + cross_max);
// Clamp Lanczos overshoot softly to neighborhood bounds
cur_ycc = clamp(cur_ycc, box_min, box_max);
bool is_reset = (pc.flags & 8u) != 0u;
vec2 prev_uv = out_uv + vel;
bool onscreen = prev_uv.x >= 0.0 && prev_uv.x <= 1.0 && prev_uv.y >= 0.0 && prev_uv.y <= 1.0;
vec3 out_tm;
float accum_conf;
if (is_reset || !onscreen) {
out_tm = yCoCgToRgb(cur_ycc);
accum_conf = 1.0 / 16.0;
} else {
vec4 prev_sample = sampleHistoryCatmullRom(prev_uv, out_size);
vec3 hist_tm = tonemap(prev_sample.rgb * pc.u_expo);
vec3 hist_ycc = rgbToYCoCg(hist_tm);
// Variance-guided YCoCg clipping (tighter on moving/disoccluded edges -> ZERO trails!)
vec3 mean = m1 / 9.0;
vec3 sigma = sqrt(max(m2 / 9.0 - mean * mean, vec3(0.0)));
float gamma = mix(1.20, 0.75, clamp(max(disocc, vel_norm), 0.0, 1.0));
vec3 v_min = max(min_ycc, mean - gamma * sigma);
vec3 v_max = min(max_ycc, mean + gamma * sigma);
// Ensure valid box around current sample
v_min = min(v_min, cur_ycc);
v_max = max(v_max, cur_ycc);
vec3 clipped_hist_ycc = clipAABB(v_min, v_max, cur_ycc, hist_ycc);
// Detect how strongly history was clipped (indicates disocclusion behind moving object!)
float clip_dist = length(hist_ycc - clipped_hist_ycc);
float luma_diff = abs(cur_ycc.x - clipped_hist_ycc.x) / max(cur_ycc.x + clipped_hist_ycc.x, 0.08);
// Adaptive temporal blend factor:
// - Static / subpixel-aligned: converges smoothly (~0.075 - 0.14) for clean AA & detail
// - Moving / disoccluded / clipped: increases rapidly toward 0.55 - 0.90 to kill trails
float prev_conf = clamp(prev_sample.a, 1.0 / 16.0, 1.0);
float base_alpha = max(1.0 / (prev_conf * 16.0 + 1.0), 0.075);
// Slightly favor fresh native pixels when jitter sample lands close to output pixel center
base_alpha = mix(base_alpha, min(base_alpha * 1.45, 0.25), center_prox);
float react = clamp(disocc * 0.75 + clip_dist * 4.5 + luma_diff * 0.25 + vel_norm * 0.18, 0.0, 0.90);
float alpha = clamp(max(base_alpha, react), 0.075, 1.0);
vec3 blended_ycc = mix(clipped_hist_ycc, cur_ycc, alpha);
out_tm = yCoCgToRgb(blended_ycc);
accum_conf = clamp(mix(prev_conf + 1.0 / 16.0, 1.0 / 16.0, react), 1.0 / 16.0, 1.0);
}
vec3 out_lin = clamp(untonemap(out_tm) / max(pc.u_expo, 1e-6), vec3(0.0), vec3(64000.0));
imageStore(u_hist_cur, ivec2(tid), vec4(out_lin, accum_conf));
}
@@ -0,0 +1,106 @@
#version 450
// Winlator Ludashi Native GPU FSR 3.1 Pass 1: Prepare & Dilate Motion Vectors
// Runs at native render resolution (rw x rh) on Adreno GPU.
// Performs 3x3 closest-depth MV dilation, exact NGX/FFX MV scaling, MVJittered cancellation,
// and computes depth/velocity discontinuity reactivity to eliminate character ghost trails.
layout(local_size_x = 8, local_size_y = 8) in;
layout(set = 0, binding = 0) uniform sampler2D u_color; // game render color
layout(set = 0, binding = 1) uniform sampler2D u_depth; // game depth (NEAREST)
layout(set = 0, binding = 2) uniform sampler2D u_mvec; // game motion vectors (NEAREST)
layout(set = 0, binding = 3, rg16f) writeonly uniform image2D u_dilated_mv;
layout(set = 0, binding = 4, rgba16f) writeonly uniform image2D u_lock_mask;
layout(push_constant) uniform PC {
vec2 u_jitter;
vec2 u_mv_scale; // raw_mv * u_mv_scale -> normalized UV delta
vec2 u_jitter_cancel; // normalized UV jitter cancellation
float u_expo;
float u_sharp;
uint rw;
uint rh;
uint ow;
uint oh;
uint flags; // bit 0: has_depth, bit 1: depth_inverted, bit 2: display_res_mv, bit 3: reset
uint pad0;
} pc;
float luma(vec3 c) {
return dot(max(c, vec3(0.0)), vec3(0.2126, 0.7152, 0.0722));
}
vec2 fetchRawMV(ivec2 q, ivec2 mv_sz, ivec2 r_lim) {
ivec2 mv_q;
if ((pc.flags & 4u) != 0u) {
vec2 uv_n = (vec2(q) + vec2(0.5)) / vec2(pc.rw, pc.rh);
mv_q = clamp(ivec2(uv_n * vec2(mv_sz)), ivec2(0), mv_sz - ivec2(1));
} else {
ivec2 mv_lim = min(r_lim, mv_sz - ivec2(1));
mv_q = clamp(q, ivec2(0), mv_lim);
}
vec2 raw = texelFetch(u_mvec, mv_q, 0).xy;
vec2 vel = raw * pc.u_mv_scale + pc.u_jitter_cancel;
if (isnan(vel.x) || isnan(vel.y) || isinf(vel.x) || isinf(vel.y) || abs(vel.x) > 4.0 || abs(vel.y) > 4.0) {
return vec2(0.0);
}
return vel;
}
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
if (p.x >= int(pc.rw) || p.y >= int(pc.rh)) return;
ivec2 r_lim = ivec2(int(pc.rw) - 1, int(pc.rh) - 1);
ivec2 col_sz = textureSize(u_color, 0);
ivec2 dep_sz = textureSize(u_depth, 0);
ivec2 mv_sz = textureSize(u_mvec, 0);
ivec2 col_lim = min(r_lim, col_sz - ivec2(1));
bool has_depth = (pc.flags & 1u) != 0u && dep_sz.x > 1 && dep_sz.y > 1;
bool dep_inv = (pc.flags & 2u) != 0u;
ivec2 best_q = p;
float center_d = 0.0;
float best_d = 0.0;
float far_d = 0.0;
if (has_depth) {
ivec2 d_lim = min(r_lim, dep_sz - ivec2(1));
ivec2 dp_c = clamp(p, ivec2(0), d_lim);
center_d = texelFetch(u_depth, dp_c, 0).r;
best_d = center_d;
far_d = center_d;
best_q = dp_c;
for (int dy = -1; dy <= 1; ++dy) {
for (int dx = -1; dx <= 1; ++dx) {
if (dx == 0 && dy == 0) continue;
ivec2 q = clamp(dp_c + ivec2(dx, dy), ivec2(0), d_lim);
float d = texelFetch(u_depth, q, 0).r;
bool closer = dep_inv ? (d > best_d) : (d < best_d);
if (closer) {
best_d = d;
best_q = q;
}
bool farther = dep_inv ? (d < far_d) : (d > far_d);
if (farther) {
far_d = d;
}
}
}
}
vec2 vel_dilated = fetchRawMV(best_q, mv_sz, r_lim);
vec2 vel_center = fetchRawMV(p, mv_sz, r_lim);
// Measure local motion-vector divergence across silhouette boundaries (moving characters vs background)
float mv_diff_px = length((vel_dilated - vel_center) * vec2(pc.ow, pc.oh));
float vel_px = length(vel_dilated * vec2(pc.ow, pc.oh));
float depth_edge = has_depth ? clamp(abs(best_d - far_d) / max(abs(best_d) + abs(far_d), 1e-4) * 4.0, 0.0, 1.0) : 0.0;
float disocc = clamp(max(mv_diff_px * 0.35, depth_edge * clamp(vel_px * 0.25, 0.0, 1.0)), 0.0, 1.0);
vec3 col = max(texelFetch(u_color, clamp(p, ivec2(0), col_lim), 0).rgb, vec3(0.0)) * pc.u_expo;
float log_y = log2(1.0 + luma(col));
imageStore(u_dilated_mv, p, vec4(vel_dilated, 0.0, 0.0));
imageStore(u_lock_mask, p, vec4(best_d, disocc, log_y, clamp(vel_px / 16.0, 0.0, 1.0)));
}
@@ -0,0 +1,81 @@
#version 450
// Winlator Ludashi Native GPU FSR 3.1 Pass 3: Official AMD RCAS Sharpening
// Runs at full native output resolution (ow x oh) in perceptual mu-law space so HDR games
// sharpen cleanly without ringing or haloing around bright highlights.
layout(local_size_x = 8, local_size_y = 8) in;
layout(set = 0, binding = 0) uniform sampler2D u_in_img;
layout(set = 0, binding = 1, rgba16f) writeonly uniform image2D u_out_img;
layout(push_constant) uniform PC {
vec2 u_jitter;
vec2 u_mv_scale;
vec2 u_jitter_cancel;
float u_expo;
float u_sharp;
uint rw;
uint rh;
uint ow;
uint oh;
uint flags;
uint pad0;
} pc;
const float FSR_RCAS_LIMIT = 0.25 - 1.0 / 16.0;
vec3 toMuLaw(vec3 c) {
c = max(c, vec3(0.0)) * pc.u_expo;
return max(vec3(0.1174) * log(vec3(1.0) + 150.0 * c), vec3(0.0));
}
vec3 fromMuLaw(vec3 m) {
return max((exp(8.51788 * m) - 1.0) / 150.0, vec3(0.0)) / max(pc.u_expo, 1e-6);
}
vec3 fetchMu(ivec2 p, ivec2 lim) {
return toMuLaw(texelFetch(u_in_img, clamp(p, ivec2(0), lim), 0).rgb);
}
void main() {
ivec2 sp = ivec2(gl_GlobalInvocationID.xy);
if (sp.x >= int(pc.ow) || sp.y >= int(pc.oh)) return;
ivec2 lim = ivec2(int(pc.ow) - 1, int(pc.oh) - 1);
vec3 b = fetchMu(sp + ivec2(0, -1), lim);
vec3 d = fetchMu(sp + ivec2(-1, 0), lim);
vec3 e = fetchMu(sp, lim);
vec3 f = fetchMu(sp + ivec2(1, 0), lim);
vec3 h = fetchMu(sp + ivec2(0, 1), lim);
float bL = b.b * 0.5 + (b.r * 0.5 + b.g);
float dL = d.b * 0.5 + (d.r * 0.5 + d.g);
float eL = e.b * 0.5 + (e.r * 0.5 + e.g);
float fL = f.b * 0.5 + (f.r * 0.5 + f.g);
float hL = h.b * 0.5 + (h.r * 0.5 + h.g);
float nz = 0.25 * (bL + dL + fL + hL) - eL;
float lmin = min(min(bL, min(dL, eL)), min(fL, hL));
float lmax = max(max(bL, max(dL, eL)), max(fL, hL));
nz = clamp(abs(nz) / max(lmax - lmin, 1e-6), 0.0, 1.0);
nz = -0.5 * nz + 1.0;
vec3 mn4 = min(min(b, min(d, f)), h);
vec3 mx4 = max(max(b, max(d, f)), h);
float lll = clamp(eL / max(min(min(bL, dL), min(fL, hL)), 1e-6), 0.0, 1.0);
vec3 hitMin = mn4 / max(4.0 * mx4, vec3(1e-6)) * lll;
vec3 den4 = 4.0 * mn4 - 4.0;
vec3 strip = step(abs(den4), vec3(1e-6));
vec3 hitMax = (1.0 - mx4) / (den4 - strip * vec3(1e-6));
hitMax = mix(hitMax, vec3(-1e9), strip);
vec3 lobe3 = max(-hitMin, hitMax);
float lobe = max(-FSR_RCAS_LIMIT, min(max(max(lobe3.r, lobe3.g), lobe3.b), 0.0));
float sharp = clamp(pc.u_sharp, 0.0, 1.0);
lobe *= exp2(2.0 * sharp - 2.0);
lobe *= nz;
vec3 pix = (lobe * (b + d + h + f) + e) / (4.0 * lobe + 1.0);
vec3 fc = clamp(fromMuLaw(pix), vec3(0.0), vec3(64000.0));
imageStore(u_out_img, sp, vec4(fc, 1.0));
}
@@ -0,0 +1,115 @@
#version 450
// Winlator Ludashi Built-in AMD FSR 4.0.2 Post-Pass A
// Decodes UFIXED_POINT_8 [1, 1080, 1920, 8] (offset=-128, scale=0.30321157) from the
// zero-copy AHardwareBuffer produced by Hexagon HTP v81/v79 NPU, runs anisotropic 3x3
// Gaussian reconstruction directly over the game's FULL NATIVE rw x rh color buffer
// (preserving 100% of Quality/Balanced/DLAA detail!), applies the neural temporal blend
// with zero ghost-trail blend floor, and writes updated mu-law history + RGBA8 state.
layout(local_size_x = 8, local_size_y = 8) in;
layout(set = 0, binding = 0) uniform sampler2D u_color; // saved Frame N-1 native rw x rh color
layout(set = 0, binding = 1, std430) readonly buffer NpuIn { uint npu[]; }; // UFIXED_POINT_8 [OS_H][OS_W][8]
layout(set = 0, binding = 2, std430) readonly buffer Repj { uint rpj[]; }; // fp16 RGBA mu-law @ OS_W x OS_H
layout(set = 0, binding = 3, std430) writeonly buffer HistOut { uint hist[]; }; // fp16 RGBA mu-law @ OS_W x OS_H
layout(set = 0, binding = 4, std430) writeonly buffer RecOut { uint recout[]; }; // RGBA8 @ OS_W x OS_H
layout(push_constant) uniform PC {
vec2 u_jitter; // subpixel jitter in native rw x rh pixels (Frame N-1)
vec2 u_uv_scale;
float bfloor; // 0.0 (no forced ghosting trail)
float expo; // Frame N-1 pre-exposure
float sharp;
uint OS_W; // 1920
uint OS_H; // 1080
uint rw; // actual native render width of Frame N-1
uint rh; // actual native render height of Frame N-1
uint pad0;
} pc;
const float S_OUT = 0.303211569786;
int ubx(uint w, uint sh) {
return int((w >> sh) & 0xffu) - 128;
}
vec3 loadRepj(uvec2 p) {
uint base = (p.y * pc.OS_W + p.x) * 2u;
return vec3(unpackHalf2x16(rpj[base]), unpackHalf2x16(rpj[base + 1u]).x);
}
vec3 loadColorMu(ivec2 p, ivec2 lim) {
p = clamp(p, ivec2(0), lim);
vec3 c = max(texelFetch(u_color, p, 0).rgb, vec3(0.0)) * pc.expo;
return max(vec3(0.1174) * log(vec3(1.0) + 150.0 * c), vec3(0.0));
}
void main() {
uvec2 tid = gl_GlobalInvocationID.xy;
if (tid.x >= pc.OS_W || tid.y >= pc.OS_H) return;
ivec2 col_sz = textureSize(u_color, 0);
ivec2 lim = min(ivec2(int(pc.rw) - 1, int(pc.rh) - 1), col_sz - ivec2(1));
uint nbase = (tid.y * pc.OS_W + tid.x) * 2u;
uint w0 = npu[nbase];
uint w1 = npu[nbase + 1u];
float p0 = float(ubx(w0, 0u)) * S_OUT;
float p1 = float(ubx(w0, 8u)) * S_OUT;
float p2 = float(ubx(w0, 16u)) * S_OUT;
float p3 = float(ubx(w0, 24u)) * S_OUT;
vec4 rv = vec4(float(ubx(w1, 0u)), float(ubx(w1, 8u)),
float(ubx(w1, 16u)), float(ubx(w1, 24u))) * S_OUT;
vec4 rec = vec4(1.0) / (vec4(1.0) + exp2(-rv * 1.4426950409));
uvec4 rb = uvec4(clamp(floor(rec * 255.0 + 0.5), vec4(0.0), vec4(255.0)));
recout[tid.y * pc.OS_W + tid.x] =
(rb.x & 0xffu) | ((rb.y & 0xffu) << 8u) | ((rb.z & 0xffu) << 16u) | ((rb.w & 0xffu) << 24u);
float ep0 = exp2(p0 * 1.4426950409);
float em0 = exp2(-p0 * 1.4426950409);
float correlation = (ep0 - em0) / max(ep0 + em0, 1e-6);
float sfx = 2.0 / (1.0 + exp2(-p1 * 1.4426950409));
float sfy = 2.0 / (1.0 + exp2(-p2 * 1.4426950409));
// Exact native rw x rh subpixel mapping (matches 2x formula identically when rw=960, rh=540,
// and preserves full 720p/1080p detail on Quality / Balanced / DLAA!)
vec2 ratio = vec2(pc.rw, pc.rh) / vec2(pc.OS_W, pc.OS_H);
vec2 inv_ratio = vec2(pc.OS_W, pc.OS_H) / vec2(pc.rw, pc.rh);
vec2 lr_f = (vec2(tid) + vec2(0.5)) * ratio - vec2(0.5) + pc.u_jitter;
ivec2 lr_i = ivec2(roundEven(lr_f));
vec3 up = vec3(0.0);
float tw = 0.0;
vec3 n_min = vec3(1e9);
vec3 n_max = vec3(-1e9);
for (int dy = -1; dy <= 1; ++dy) {
float yd = (float(lr_i.y + dy) - lr_f.y) * inv_ratio.y;
for (int dx = -1; dx <= 1; ++dx) {
float xd = (float(lr_i.x + dx) - lr_f.x) * inv_ratio.x;
float gw = exp2((-0.5 / (0.47 * 0.47)) * 1.4426950409 *
(xd * xd * sfx * sfx + 2.0 * correlation * (xd * yd) * sfx * sfy +
yd * yd * sfy * sfy));
vec3 sample_m = loadColorMu(lr_i + ivec2(dx, dy), lim);
n_min = min(n_min, sample_m);
n_max = max(n_max, sample_m);
tw += gw;
up += sample_m * gw;
}
}
up /= max(tw, 1e-6);
float blend = 1.0 / (1.0 + exp2(-p3 * 1.4426950409));
vec3 rp = loadRepj(tid);
// Soft neighborhood guard in mu-law space prevents residual ghost trails on fast-moving
// disoccluded edges even if a game sends noisy/missing MVs.
vec3 margin = max((n_max - n_min) * 0.25, vec3(0.015));
vec3 rp_clamped = clamp(rp, n_min - margin, n_max + margin);
float bf = (max(max(rp.r, rp.g), rp.b) <= 0.0) ? 0.0 : pc.bfloor;
blend = max(blend, bf);
vec3 model_color = mix(up, rp_clamped, blend);
uint obase = (tid.y * pc.OS_W + tid.x) * 2u;
hist[obase] = packHalf2x16(model_color.xy);
hist[obase + 1u] = packHalf2x16(vec2(model_color.z, 1.0));
}
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more