Files
DroidDeck/tools/upscale/layer/fsr4_layer.c
T
The412Banner e5d7bddfdb upscale: DLSS frames reach the layer in Streamline/Unreal D3D12 games
Bright Memory: Infinite (Unreal Engine, D3D12, NVIDIA Streamline) now passed NGX's checks but no
frame reached the layer. Two causes, fixed here:

- The layer recognised the bridge's mailbox by size and the storage bit only, in a 128-entry table;
  the game's own 8 KB storage buffers filled it first, so the bridge's doorbells were ignored. It now
  matches the exact usage the bridges create them with (mailbox STORAGE|TRANSFER_DST, marker
  TRANSFER_DST), keeps 1024 entries and warns once if the table is ever full.
- Streamline (sl.interposer) wraps the devices and command lists it creates; vkd3d-proton and DXVK
  do not know the wrappers. wl_streamline.h asks a wrapper for StreamlineRetrieveBaseInterface
  (Streamline source/core/sl.interposer/d3d12/d3d12Device.cpp) and the interop calls retry on the
  wrapped object: device queries, BeginVkCommandBufferInterop/End, GetVulkanResourceInfo1.

DROIDDECK_UPSCALE_LOG=1 now also logs the NGX bridge's D3D12 attach and first evaluate (seam
ready, images found, command list accepted, dispatch result).
2026-12-05 02:40:10 -05:00

2182 lines
102 KiB
C

// DroidDeck in-game upscaler Vulkan layer: VK_LAYER_DROIDDECK_upscale
// Ported from VK_LAYER_WINLATOR_fsr4_npu (michaelisomer-cyber/Winlator-NeuralScale, GPL-3.0).
//
// Responsibilities:
// 1. Transparently enables required Vulkan extensions & features on Adreno 840 / Turnip
// for zero-copy AHardwareBuffer + VK_EXT_descriptor_buffer FSR 4.1.1 execution.
// 2. Optionally spoofs AMD RDNA 4 (RX 9070 XT) or NVIDIA RTX 2060 + VK_NVX_binary_import /
// VK_NVX_image_view_handle so both native FSR 4 games AND DLSS games (RDR2, etc.)
// unlock their upscaler options inside Wine/DXVK/VKD3D.
// 3. Tracks game VkImage formats/dimensions and listens on the in-process zero-copy
// Seam Mailbox / Doorbell (vkCmdUpdateBuffer) from our Windows bridge DLLs
// (amd_fidelityfx_vk.dll, amd_fidelityfx_dx12.dll, nvngx.dll).
#define _GNU_SOURCE
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_android.h>
#include "dd_upscale_compat.h"
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#include <sys/mman.h>
#include "fsr4_seam_proto.h"
#include "fsr4_pipeline.h"
#include "fsr_gpu_timer.h"
#ifndef VK_KHR_compute_shader_derivatives
typedef VkPhysicalDeviceComputeShaderDerivativesFeaturesNV VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR;
#define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_KHR \
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV
#endif
#define F4_TAG "DroidDeckUpscale"
#define F4_LOGI(...) dd_upscale_log(DD_LOG_INFO, F4_TAG, __VA_ARGS__)
#define F4_LOGW(...) dd_upscale_log(DD_LOG_WARN, F4_TAG, __VA_ARGS__)
#define F4_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F4_TAG, __VA_ARGS__)
#define LAYER_EXPORT __attribute__((visibility("default")))
#define WL_LAYER_NAME "VK_LAYER_DROIDDECK_upscale"
#define WL_LAYER_DESC "DroidDeck in-game upscaler (FSR 4 / FSR 3.1 / XeSS / DLSS bridge, GPU and Hexagon NPU)"
// ---- Khronos Loader-Layer Interface structs (self-contained, no vk_layer.h needed) ----
typedef enum {
WL_VK_LAYER_LINK_INFO = 0,
WL_VK_LOADER_DATA_CALLBACK = 1,
} WlVkLayerFunction;
typedef struct WlVkLayerInstanceLink {
struct WlVkLayerInstanceLink *pNext;
PFN_vkGetInstanceProcAddr pfnNextGetInstanceProcAddr;
PFN_vkGetInstanceProcAddr pfnNextGetPhysicalDeviceProcAddr;
} WlVkLayerInstanceLink;
typedef struct WlVkLayerInstanceCreateInfo {
VkStructureType sType;
const void *pNext;
WlVkLayerFunction function;
union {
WlVkLayerInstanceLink *pLayerInfo;
void *pfnSetInstanceLoaderData;
} u;
} WlVkLayerInstanceCreateInfo;
typedef struct WlVkLayerDeviceLink {
struct WlVkLayerDeviceLink *pNext;
PFN_vkGetInstanceProcAddr pfnNextGetInstanceProcAddr;
PFN_vkGetDeviceProcAddr pfnNextGetDeviceProcAddr;
} WlVkLayerDeviceLink;
typedef struct WlVkLayerDeviceCreateInfo {
VkStructureType sType;
const void *pNext;
WlVkLayerFunction function;
union {
WlVkLayerDeviceLink *pLayerInfo;
void *pfnSetDeviceLoaderData;
} u;
} WlVkLayerDeviceCreateInfo;
typedef struct WlVkNegotiateLayerInterface {
uint32_t sType; /* 0 = LAYER_NEGOTIATE_INTERFACE_STRUCT */
void *pNext;
uint32_t loaderLayerInterfaceVersion;
PFN_vkGetInstanceProcAddr pfnGetInstanceProcAddr;
PFN_vkGetDeviceProcAddr pfnGetDeviceProcAddr;
PFN_vkGetInstanceProcAddr pfnGetPhysicalDeviceProcAddr;
} WlVkNegotiateLayerInterface;
static inline void *dispatch_key(const void *obj) {
return obj ? *(void *const *)obj : NULL;
}
// ---- Instance & Device tables ----
#define MAX_INSTANCES 8
#define MAX_DEVICES 16
#define MAX_TRACK_BUF 1024
#define MAX_TRACK_IMG 4096
typedef struct {
void *key;
VkInstance instance;
PFN_vkGetInstanceProcAddr next_gipa;
PFN_vkDestroyInstance DestroyInstance;
PFN_vkEnumerateDeviceExtensionProperties EnumerateDeviceExtensionProperties;
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties;
PFN_vkGetPhysicalDeviceProperties2 GetPhysicalDeviceProperties2;
PFN_vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2;
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
PFN_vkGetPhysicalDeviceMemoryProperties2 GetPhysicalDeviceMemoryProperties2;
PFN_vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties;
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties;
} InstCtx;
typedef struct {
VkBuffer buf;
VkDeviceMemory mem;
void *mapped;
uint64_t size;
uint32_t usage;
int kind; // 1 = mailbox candidate, 2 = marker candidate
} SeamBufEnt;
typedef struct {
VkImage img;
VkFormat fmt;
uint32_t w, h;
VkImageUsageFlags usage;
} ImgEnt;
typedef struct {
pthread_mutex_t mu;
int mu_init;
VkFence fences[2];
int fence_armed[2];
uint32_t frame_idx;
int64_t next_target_ns;
int last_fps_limit;
} WlReflexPacer;
// Zero-root Android 12+ ADPF (APerformanceHint) per-frame Vulkan hint session
typedef struct {
void *session;
int32_t tid;
int64_t target_ns;
int64_t frame_start_ns;
int init_failed;
} WlAdpfHint;
typedef struct {
void *key;
VkDevice device;
VkPhysicalDevice phys_dev;
InstCtx *inst;
int pacer_only;
PFN_vkGetDeviceProcAddr next_gdpa;
PFN_vkDestroyDevice DestroyDevice;
PFN_vkCreateBuffer CreateBuffer;
PFN_vkDestroyBuffer DestroyBuffer;
PFN_vkBindBufferMemory BindBufferMemory;
PFN_vkMapMemory MapMemory;
PFN_vkUnmapMemory UnmapMemory;
PFN_vkCreateImage CreateImage;
PFN_vkDestroyImage DestroyImage;
PFN_vkCmdUpdateBuffer CmdUpdateBuffer;
PFN_vkQueuePresentKHR QueuePresentKHR;
PFN_vkQueueSubmit QueueSubmit;
PFN_vkCreateFence CreateFence;
PFN_vkDestroyFence DestroyFence;
PFN_vkWaitForFences WaitForFences;
PFN_vkResetFences ResetFences;
WlReflexPacer pacer;
WlAdpfHint adpf;
WlVkDispatch disp;
WlFsr4Pipeline *pipe;
int has_supported_npu;
int64_t last_present_ns;
WlGpuTimer xess_timer;
uint32_t xess_timer_slot;
SeamBufEnt bufs[MAX_TRACK_BUF];
int nbufs;
ImgEnt imgs[MAX_TRACK_IMG];
uint32_t img_count;
} DevCtx;
static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
static InstCtx g_insts[MAX_INSTANCES];
static DevCtx *g_devs[MAX_DEVICES];
static char g_real_gpu_name[128] = "Unknown";
static volatile int g_rdr2_patched = 0; /* 0=not rdr2, 1=partial, 2=full */
static volatile int g_rdr2_scan_done = 0;
// DroidDeck decides whether this phone's NPU can run (UpscaleComponent.npu(): the vendor's own QNN runtime or
// the bundled v79/v81 files) and passes DROIDDECK_UPSCALE_NPU=1; no SoC list here, so any HTP generation works.
static int detect_supported_npu(const char *gpu_name) {
(void)gpu_name;
const char *npu = dd_upscale_env("NPU");
return (npu && !strcmp(npu, "1")) ? 1 : 0;
}
static int has_external_banana_pack(void) {
const char *dir = dd_upscale_dir();
if (!dir) return 0;
char p[640];
snprintf(p, sizeof p, "%s/1080/performance/pass-01-npu.spv", dir);
return access(p, R_OK) == 0;
}
static uint8_t *scan_bytes_mask(uint8_t *base, size_t len, const uint8_t *pat, const uint8_t *mask, size_t plen) {
if (!base || len < plen || plen == 0) return NULL;
size_t limit = len - plen;
for (size_t i = 0; i <= limit; i++) {
size_t j = 0;
for (; j < plen; j++) {
if (mask[j] && base[i + j] != pat[j]) break;
}
if (j == plen) return base + i;
}
return NULL;
}
static int apply_code_patch(uint8_t *addr, const uint8_t *bytes, size_t n, int orig_prot) {
long ps = sysconf(_SC_PAGESIZE);
if (ps <= 0) ps = 4096;
uintptr_t p0 = (uintptr_t)addr & ~((uintptr_t)ps - 1u);
uintptr_t p1 = ((uintptr_t)addr + n + (uintptr_t)ps - 1u) & ~((uintptr_t)ps - 1u);
size_t span = (size_t)(p1 - p0);
if (mprotect((void *)p0, span, orig_prot | PROT_READ | PROT_WRITE) != 0) return 0;
memcpy(addr, bytes, n);
__builtin___clear_cache((char *)addr, (char *)(addr + n));
mprotect((void *)p0, span, orig_prot);
return 1;
}
static int str_ends_with_ci(const char *s, const char *suffix) {
if (!s || !suffix) return 0;
size_t sl = strlen(s), su = strlen(suffix);
if (sl < su) return 0;
const char *p = s + (sl - su);
for (size_t i = 0; i < su; i++) {
if (tolower((unsigned char)p[i]) != tolower((unsigned char)suffix[i])) return 0;
}
return 1;
}
static int str_contains_ci(const char *hay, const char *needle) {
if (!hay || !needle || !*needle) return 0;
size_t nl = strlen(needle);
for (const char *p = hay; *p; p++) {
size_t i = 0;
while (i < nl && p[i] && tolower((unsigned char)p[i]) == tolower((unsigned char)needle[i])) i++;
if (i == nl) return 1;
}
return 0;
}
static int proc_is_rdr2(void) {
FILE *f = fopen("/proc/self/cmdline", "rb");
if (!f) return 0;
char buf[2048];
size_t n = fread(buf, 1, sizeof(buf) - 1, f);
fclose(f);
for (size_t i = 0; i < n; i++) {
if (buf[i] == '\0') buf[i] = ' ';
}
buf[n] = '\0';
return str_contains_ci(buf, "rdr2.exe") || str_contains_ci(buf, "playrdr2.exe");
}
// Optional OptiPatcher for RDR2.exe — DISABLED by default because RDR2's Arxan anti-tamper
// crashes after the loading screen if RDR2.exe's .text pages are modified. Enable only via
// DROIDDECK_UPSCALE_RDR2_PATCH=1 on Arxan-free builds.
static void try_patch_rdr2_exe(void) {
if (__atomic_exchange_n(&g_rdr2_scan_done, 1, __ATOMIC_ACQ_REL)) return;
const char *en = dd_upscale_env("RDR2_PATCH");
if (!en || en[0] != '1') return;
if (!proc_is_rdr2()) return;
FILE *f = fopen("/proc/self/maps", "r");
if (!f) return;
// OptiPatcher verified patterns for RDR2.exe:
// 1. DLSS vendor gate before NGX init: cmp byte ptr [rax+1CD9h], 2 -> cmp al, al; nop*5
static const uint8_t pat_dlss[15] = { 0x48,0x85,0xC0,0x74,0x0A, 0x80,0xB8,0xD9,0x1C,0x00,0x00,0x02, 0x0F,0x94,0xC3 };
static const uint8_t msk_dlss[15] = { 1,1,1,1,1, 1,1,1,1,1,1,1, 1,1,1 };
// 2. Settings menu "is NVIDIA" condition: cmp byte ptr [rax+1CD9h], 2 -> cmp al, al; nop*5
static const uint8_t pat_menu[18] = { 0x33,0xC0, 0x80,0xB8,0xD9,0x1C,0x00,0x00,0x02, 0x0F,0x94,0xC0,0x48,0x83,0xC4,0x20,0x5B,0xC3 };
static const uint8_t msk_menu[18] = { 1,1, 1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1 };
static const uint8_t patch_cmp_al[7] = { 0x38,0xC0, 0x90,0x90,0x90,0x90,0x90 };
int hit_dlss = 0, hit_menu = 0;
char line[1024];
while (fgets(line, sizeof line, f)) {
unsigned long long lo = 0, hi = 0;
char perms[8] = {0};
char path[512] = {0};
int n = sscanf(line, "%llx-%llx %7s %*s %*s %*s %511[^\n]", &lo, &hi, perms, path);
if (n < 3) continue;
// On FEXCore/ARM64EC, emulated x86_64 PE .text sections may be mapped r-xp, r--p, or rw-p
// (without Linux PROT_EXEC), and either file-backed (.../RDR2.exe) or anonymous.
if (perms[0] != 'r' || perms[3] != 'p') continue;
if (hi <= lo) continue;
uint64_t span = hi - lo;
if (span < (8ULL * 1024ULL * 1024ULL) || span > (256ULL * 1024ULL * 1024ULL)) continue;
// Trim whitespace on optional path
size_t plen = strlen(path);
while (plen > 0 && (path[plen - 1] == '\r' || path[plen - 1] == '\n' || path[plen - 1] == ' ')) path[--plen] = '\0';
int is_candidate = 0;
if (str_ends_with_ci(path, "/rdr2.exe") || str_ends_with_ci(path, "\\rdr2.exe") ||
str_ends_with_ci(path, "/playrdr2.exe") || str_ends_with_ci(path, "\\playrdr2.exe")) {
is_candidate = 1;
} else if (plen == 0 || (path[0] == '[' && !str_contains_ci(path, "dalvik") && !str_contains_ci(path, "kgsl") && !str_contains_ci(path, "dmabuf"))) {
// Anonymous private mapping (Wine PE image loader) — only scan typical x64 PE image range
if (lo >= 0x0000000010000000ULL && hi <= 0x00007FFFFFFFFFFFULL) {
is_candidate = 1;
}
}
if (!is_candidate) continue;
int orig_prot = PROT_READ | (perms[1] == 'w' ? PROT_WRITE : 0) | (perms[2] == 'x' ? PROT_EXEC : 0);
uint8_t *base = (uint8_t *)(uintptr_t)lo;
size_t sz = (size_t)span;
if (!hit_dlss) {
uint8_t *m = scan_bytes_mask(base, sz, pat_dlss, msk_dlss, sizeof pat_dlss);
if (m && apply_code_patch(m + 5, patch_cmp_al, sizeof patch_cmp_al, orig_prot)) {
hit_dlss = 1;
F4_LOGI("RDR2 OptiPatcher: patched DLSS vendor gate at %p (seg=%llx-%llx perms=%s)", (void *)(m + 5), lo, hi, perms);
}
}
if (!hit_menu) {
uint8_t *m = scan_bytes_mask(base, sz, pat_menu, msk_menu, sizeof pat_menu);
if (m && apply_code_patch(m + 2, patch_cmp_al, sizeof patch_cmp_al, orig_prot)) {
hit_menu = 1;
F4_LOGI("RDR2 OptiPatcher: patched Graphics Menu vendor gate at %p (seg=%llx-%llx perms=%s)", (void *)(m + 2), lo, hi, perms);
}
}
if (hit_dlss && hit_menu) break;
}
fclose(f);
if (hit_dlss || hit_menu) {
g_rdr2_patched = (hit_dlss && hit_menu) ? 2 : 1;
F4_LOGI("RDR2 OptiPatcher complete (dlss=%d menu=%d) — select NVIDIA DLSS in RDR2 Graphics Settings!", hit_dlss, hit_menu);
} else {
F4_LOGW("RDR2 detected in cmdline, but OptiPatcher signatures not matched in executable maps");
}
}
static InstCtx *find_inst_locked(const void *obj) {
void *k = dispatch_key(obj);
for (int i = 0; i < MAX_INSTANCES; i++) {
if (g_insts[i].key && g_insts[i].key == k) return &g_insts[i];
}
return NULL;
}
static DevCtx *find_dev_locked(const void *obj) {
void *k = dispatch_key(obj);
for (int i = 0; i < MAX_DEVICES; i++) {
if (g_devs[i] && g_devs[i]->key == k) return g_devs[i];
}
return NULL;
}
int wl_fsr4_lookup_image_info(VkDevice dev, VkImage img,
VkFormat *out_fmt, uint32_t *out_w, uint32_t *out_h,
VkImageUsageFlags *out_usage) {
int found = 0;
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(dev);
if (d) {
for (uint32_t i = 0; i < d->img_count; i++) {
if (d->imgs[i].img == img) {
if (out_fmt) *out_fmt = d->imgs[i].fmt;
if (out_w) *out_w = d->imgs[i].w;
if (out_h) *out_h = d->imgs[i].h;
if (out_usage) *out_usage = d->imgs[i].usage;
found = 1;
break;
}
}
}
pthread_mutex_unlock(&g_mu);
return found;
}
// ---- Live sidebar control & telemetry helpers ----
static uint64_t layer_now_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)ts.tv_nsec / 1000000ULL;
}
static const char *api_source_name(uint32_t api) {
switch (api) {
case WLFSR4_API_FFX_VK: return "FSR 4 (Vulkan)";
case WLFSR4_API_FFX_DX12: return "FSR 4 (DX12)";
case WLFSR4_API_NGX_VK: return "DLSS (Vulkan)";
case WLFSR4_API_NGX_DX12: return "DLSS (DX12)";
case WLFSR4_API_NGX_DX11: return "DLSS (DX11)";
case WLFSR4_API_XESS_VK: return "XeSS (Vulkan)";
case WLFSR4_API_XESS_DX12: return "XeSS (DX12)";
case WLFSR4_API_FSR3_VK: return "FSR 3 (Vulkan)";
case WLFSR4_API_FSR3_DX12: return "FSR 3 (DX12)";
case WLFSR4_API_FSR2_VK: return "FSR 2 (Vulkan)";
case WLFSR4_API_FSR2_DX12: return "FSR 2 (DX12)";
default: return "None";
}
}
static const char *quality_mode_name(uint32_t qm, uint32_t rw, uint32_t ow) {
switch (qm) {
case WLFSR4_QUALITY_NATIVE_AA: return "Native AA (DLAA)";
case WLFSR4_QUALITY_ULTRA_QUAL: return "Ultra Quality";
case WLFSR4_QUALITY_QUALITY: return "Quality";
case WLFSR4_QUALITY_BALANCED: return "Balanced";
case WLFSR4_QUALITY_PERF: return "Performance";
case WLFSR4_QUALITY_ULTRA_PERF: return "Ultra Performance";
default: break;
}
if (rw > 0 && ow > 0) {
float r = (float)ow / (float)rw;
if (r < 1.15f) return "Native AA (DLAA)";
if (r < 1.38f) return "Ultra Quality";
if (r < 1.60f) return "Quality";
if (r < 1.85f) return "Balanced";
if (r < 2.45f) return "Performance";
return "Ultra Performance";
}
return "Auto";
}
static const char *backend_id_str(int backend) {
switch (backend) {
case WL_FSR_BACKEND_AUTO: return "auto";
case WL_FSR_BACKEND_FSR3_GPU: return "fsr3_gpu";
case WL_FSR_BACKEND_XESS3_GPU: return "xess3_gpu";
case WL_FSR_BACKEND_SGSR2_GPU: return "sgsr2_gpu";
case WL_FSR_BACKEND_FSR4_1_LITE_NPU: return "fsr4_1_lite_npu";
case WL_FSR_BACKEND_FSR4_1_LITE_GPU: return "fsr4_1_lite_gpu";
case WL_FSR_BACKEND_FSR4_1_FULL_NPU: return "fsr4_1_full_npu";
case WL_FSR_BACKEND_FSR4_1_FULL_GPU: return "fsr4_1_full_gpu";
default: return "auto";
}
}
static const char *backend_default_tag(int backend) {
switch (backend) {
case WL_FSR_BACKEND_AUTO: return "Auto";
case WL_FSR_BACKEND_FSR3_GPU: return "FSR3.1-GPU";
case WL_FSR_BACKEND_XESS3_GPU: return "XeSS3-DP4a";
case WL_FSR_BACKEND_SGSR2_GPU: return "SGSR2-Adreno";
case WL_FSR_BACKEND_FSR4_1_LITE_NPU: return "FSR4.1-Lite-NPU";
case WL_FSR_BACKEND_FSR4_1_LITE_GPU: return "FSR4.1-Lite-GPU";
case WL_FSR_BACKEND_FSR4_1_FULL_NPU: return "FSR4.1-Full-NPU";
case WL_FSR_BACKEND_FSR4_1_FULL_GPU: return "FSR4.1-Full-GPU";
default: return "Auto";
}
}
static int parse_backend_str(const char *v) {
if (!v || !*v) return WL_FSR_BACKEND_AUTO;
while (*v == ' ' || *v == '\t') v++;
if (!strncmp(v, "auto", 4)) return WL_FSR_BACKEND_AUTO;
// DroidDeck keeps Intel's XeSS 3 (the bridge runs the official runtime) and names FSR 4 on the NPU after the
// full model, which replaced FSR 4.0.2 there.
if (!strncmp(v, "xess", 4)) return WL_FSR_BACKEND_XESS3_GPU;
if (!strncmp(v, "fsr4_0_npu", 10) || !strncmp(v, "fsr4_npu", 8)) return WL_FSR_BACKEND_FSR4_1_FULL_NPU;
if (!strncmp(v, "sgsr2", 5) || !strncmp(v, "snapdragon", 10) || !strncmp(v, "gsr2", 4))
return WL_FSR_BACKEND_SGSR2_GPU;
if (!strncmp(v, "fsr4_1_full_npu", 15) || !strncmp(v, "411_full_npu", 12) || !strncmp(v, "412_full_npu", 12))
return WL_FSR_BACKEND_FSR4_1_FULL_NPU;
if (!strncmp(v, "fsr4_1_full_gpu", 15) || !strncmp(v, "411_full_gpu", 12) || !strncmp(v, "412_full_gpu", 12))
return WL_FSR_BACKEND_FSR4_1_FULL_GPU;
if (!strncmp(v, "fsr4_1_lite_gpu", 15) || !strncmp(v, "412_lite_gpu", 12))
return WL_FSR_BACKEND_FSR4_1_LITE_GPU;
if (!strncmp(v, "fsr4_1_lite_npu", 15) || !strncmp(v, "412_lite_npu", 12) ||
!strncmp(v, "fsr4_0_npu", 10) || !strncmp(v, "fsr4_npu", 8) ||
!strncmp(v, "fsr4", 4) || !strncmp(v, "npu", 3))
return WL_FSR_BACKEND_FSR4_1_LITE_NPU;
if (!strncmp(v, "fsr3", 4) || !strncmp(v, "xess", 4) || !strncmp(v, "gpu", 3))
return WL_FSR_BACKEND_FSR3_GPU;
return WL_FSR_BACKEND_AUTO;
}
typedef struct {
int enabled;
int backend;
int npu_sync;
float sharpness;
int fps_limit;
int anti_throttle;
float thermal_headroom;
float batt_temp_c;
} LiveCtrlState;
static int is_pacer_only_mode(void) {
const char *v = dd_upscale_env("PACER_ONLY");
return v && v[0] == '1';
}
static int64_t monotonic_now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)ts.tv_sec * 1000000000LL + (int64_t)ts.tv_nsec;
}
static void touch_pacer_heartbeat(void) {
static uint64_t last_hb_ms = 0;
uint64_t now = layer_now_ms();
if (now - last_hb_ms < 500ULL) return;
last_hb_ms = now;
const char *p = dd_upscale_env("PACER_HB_FILE");
if (!p || !*p) return;
int fd = open(p, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd >= 0) {
const char buf[2] = { '1', '\n' };
if (write(fd, buf, sizeof(buf)) != (ssize_t)sizeof(buf)) { /* heartbeat is best effort */ }
close(fd);
}
}
static uint64_t pack_live_ctrl(const LiveCtrlState *c) {
uint64_t v = ((uint64_t)(c->backend & 0xFF));
if (c->enabled) v |= WLFSR4_CTRL_ENABLED_BIT;
if (c->npu_sync) v |= WLFSR4_CTRL_SYNC_BIT;
float sh = c->sharpness;
if (sh < 0.0f) sh = 0.0f;
if (sh > 1.0f) sh = 1.0f;
uint32_t shu = (uint32_t)(sh * 1000.0f + 0.5f);
v |= ((uint64_t)(shu & 0xFFFFu) << WLFSR4_CTRL_SHARP_SHIFT);
return v;
}
static void read_live_ctrl(LiveCtrlState *out) {
static pthread_mutex_t ctrl_mu = PTHREAD_MUTEX_INITIALIZER;
static LiveCtrlState cached = { 1, -1, 0, -1.0f, 0, 0, -1.0f, 0.0f };
static uint64_t last_check_ms = 0;
pthread_mutex_lock(&ctrl_mu);
if (cached.backend < 0) {
const char *env_b = dd_upscale_env("BACKEND");
if (!env_b) env_b = dd_upscale_env("ENGINE");
cached.backend = env_b ? parse_backend_str(env_b) : WL_FSR_BACKEND_AUTO;
// Async NPU unless NPU_SYNC=1 ("sync" and "true" kept for upstream launchers).
const char *env_sync = dd_upscale_env("NPU_SYNC");
cached.npu_sync = (env_sync && (!strcmp(env_sync, "1") || !strcmp(env_sync, "sync") || !strcmp(env_sync, "true"))) ? 1 : 0;
const char *env_sh = dd_upscale_env("SHARPNESS");
cached.sharpness = (env_sh && *env_sh) ? (float)atof(env_sh) : 0.55f;
if (cached.sharpness < 0.0f) cached.sharpness = 0.0f;
if (cached.sharpness > 1.0f) cached.sharpness = 1.0f;
const char *env_fps = dd_upscale_env("FPS_LIMIT");
int fl = (env_fps && *env_fps) ? atoi(env_fps) : 0;
if (fl < 0) fl = 0;
if (fl > 1000) fl = 1000;
cached.fps_limit = fl;
const char *env_at = dd_upscale_env("ANTI_THROTTLE");
cached.anti_throttle = (env_at && (env_at[0] == '1' || !strcmp(env_at, "true") || !strcmp(env_at, "on"))) ? 1 : 0;
cached.thermal_headroom = -1.0f;
cached.batt_temp_c = 0.0f;
}
uint64_t now = layer_now_ms();
if (now - last_check_ms >= 100ULL) {
last_check_ms = now;
const char *p = dd_upscale_env("CTRL_FILE");
if (p) {
FILE *f = fopen(p, "r");
if (f) {
char buf[160];
int line_no = 0;
while (fgets(buf, sizeof buf, f)) {
if (strncmp(buf, "backend=", 8) == 0) {
cached.backend = parse_backend_str(buf + 8);
} else if (strncmp(buf, "engine=", 7) == 0) {
cached.backend = parse_backend_str(buf + 7);
} else if (strncmp(buf, "npu_sync=", 9) == 0) {
const char *v = buf + 9;
cached.npu_sync = (v[0] == '1' || strncmp(v, "sync", 4) == 0 || strncmp(v, "true", 4) == 0) ? 1 : 0;
} else if (strncmp(buf, "sharpness=", 10) == 0) {
float sh = (float)atof(buf + 10);
if (sh < 0.0f) sh = 0.0f;
if (sh > 1.0f) sh = 1.0f;
cached.sharpness = sh;
} else if (strncmp(buf, "fps_limit=", 10) == 0) {
int fl = atoi(buf + 10);
if (fl < 0) fl = 0;
if (fl > 1000) fl = 1000;
cached.fps_limit = fl;
} else if (strncmp(buf, "anti_throttle=", 14) == 0) {
const char *v = buf + 14;
cached.anti_throttle = (v[0] == '1' || strncmp(v, "true", 4) == 0 || strncmp(v, "on", 2) == 0) ? 1 : 0;
} else if (strncmp(buf, "thermal_headroom=", 17) == 0) {
cached.thermal_headroom = (float)atof(buf + 17);
} else if (strncmp(buf, "batt_temp_c=", 12) == 0) {
cached.batt_temp_c = (float)atof(buf + 12);
} else if (strncmp(buf, "enabled=", 8) == 0) {
const char *v = buf + 8;
cached.enabled = !(v[0] == '0' || strncmp(v, "off", 3) == 0 || strncmp(v, "false", 5) == 0);
} else if (line_no == 0) {
if (strstr(buf, "0") || strstr(buf, "off") || strstr(buf, "false")) cached.enabled = 0;
else cached.enabled = 1;
}
line_no++;
}
fclose(f);
}
}
}
if (out) *out = cached;
pthread_mutex_unlock(&ctrl_mu);
}
static void write_live_status(const WlFsr4Pipeline *pipe, const LiveCtrlState *ctrl,
int active, int npu, const char *backend_tag,
uint32_t api, uint32_t qm,
uint32_t rw, uint32_t rh, uint32_t ow, uint32_t oh,
int preset, uint32_t gpu_us, uint32_t htp_us,
uint64_t dispatches, const char *reason, int force) {
static uint64_t last_write_ms = 0;
static int last_enabled = -1, last_backend = -1, last_npu = -1, last_sync = -1;
static uint32_t last_qm = 0xFFFFFFFFu, last_rw = 0;
uint64_t now = layer_now_ms();
if (!force && (now - last_write_ms < 250ULL) &&
ctrl->enabled == last_enabled && ctrl->backend == last_backend &&
ctrl->npu_sync == last_sync && npu == last_npu && qm == last_qm && rw == last_rw) {
return;
}
last_write_ms = now;
last_enabled = ctrl->enabled; last_backend = ctrl->backend;
last_sync = ctrl->npu_sync; last_npu = npu; last_qm = qm; last_rw = rw;
const char *p = dd_upscale_env("STATUS_FILE");
if (!p) return;
const char *ahb_mode = "pending";
const char *npu_state = "standby";
wl_fsr4_pipe_diag(pipe, &ahb_mode, &npu_state);
const char *rdr2_str = (g_rdr2_patched >= 2) ? "ok" : (g_rdr2_patched == 1 ? "partial" : "none");
const char *b_id = backend_id_str(ctrl->backend);
const char *b_tag = (backend_tag && *backend_tag) ? backend_tag : backend_default_tag(ctrl->backend);
const char *eng_legacy = (ctrl->backend == WL_FSR_BACKEND_FSR3_GPU) ? "fsr3" : "fsr4";
char tmp[600];
snprintf(tmp, sizeof tmp, "%s.tmp", p);
FILE *f = fopen(tmp, "w");
if (!f) return;
fprintf(f,
"layer=1\ndriver=%s\nahb=%s\nnpu_state=%s\nrdr2_patch=%s\n"
"engine=%s\nbackend=%s\nbackend_tag=%s\nnpu_sync=%s\nsharpness=%.2f\n"
"enabled=%d\nactive=%d\nnpu=%d\napi=%s\nquality=%s\n"
"render=%ux%u\noutput=%ux%u\npreset=%s\ngpu_us=%u\nhtp_us=%u\ndispatches=%llu\nreason=%s\nts_ms=%llu\n",
g_real_gpu_name, ahb_mode, npu_state, rdr2_str,
eng_legacy, b_id, b_tag, ctrl->npu_sync ? "sync" : "async", ctrl->sharpness,
ctrl->enabled, active, npu, api_source_name(api), quality_mode_name(qm, rw, ow),
rw, rh, ow, oh, preset == 1 ? "ultraperf" : "perf",
gpu_us, htp_us, (unsigned long long)dispatches, reason ? reason : "ok",
(unsigned long long)now);
fclose(f);
rename(tmp, p);
}
// ---- GPU & DLSS spoof helpers ----
// vkd3d-proton binds its own descriptor buffers in the command buffers the upscaler records into; with that, Full
// FSR 4.1's descriptor-buffer passes write a black frame on Turnip (Red Magic 12 Pro A850, Dec 2026: XeSS DX12 sample
// black in 9/9 shots, picture back with VKD3D_DISABLE_EXTENSIONS=VK_EXT_descriptor_buffer). The layer hides the
// extension from the game, which then uses its classic descriptors, and still enables it for itself.
// DROIDDECK_UPSCALE_APP_DESCRIPTOR_BUFFER=1 shows it to the game again.
static int hide_app_descriptor_buffer(void) {
const char *v = dd_upscale_env("APP_DESCRIPTOR_BUFFER");
return !(v && v[0] == '1');
}
static int spoof_dlss_enabled(void) {
const char *v = dd_upscale_env("SPOOF_DLSS");
return (v && v[0] == '1') || (g_rdr2_patched > 0);
}
enum { GPU_SPOOF_NONE = 0, GPU_SPOOF_RTX = 1, GPU_SPOOF_RDNA4 = 2 };
// GPU_SPOOF holds words separated by ',', '+', ';' or blanks:
// rtx | rdna4 GPU reported in vendorID/deviceID/deviceName/deviceType/driverVersion
// 1 also report the matching driverID/driverName/driverInfo
// off|none|0 report the real GPU even when SPOOF_DLSS=1
// Without rtx/rdna4/off, SPOOF_DLSS=1 reports rtx. driverID is never changed without "1".
static void gpu_spoof_config(int *out_id, int *out_driver) {
int id = GPU_SPOOF_NONE, driver = 0, explicit_off = 0;
const char *mode = dd_upscale_env("GPU_SPOOF");
if (mode) {
char buf[64];
snprintf(buf, sizeof buf, "%s", mode);
char *save = NULL;
for (char *tok = strtok_r(buf, ",+; \t", &save); tok; tok = strtok_r(NULL, ",+; \t", &save)) {
if (!strcmp(tok, "rtx")) id = GPU_SPOOF_RTX;
else if (!strcmp(tok, "rdna4")) id = GPU_SPOOF_RDNA4;
else if (!strcmp(tok, "1")) driver = 1;
else if (!strcmp(tok, "off") || !strcmp(tok, "none") || !strcmp(tok, "0")) explicit_off = 1;
}
}
if (id == GPU_SPOOF_NONE && !explicit_off) {
const char *v = dd_upscale_env("SPOOF_DLSS");
if (v && v[0] == '1') id = GPU_SPOOF_RTX;
}
if (out_id) *out_id = id;
if (out_driver) *out_driver = (driver && id != GPU_SPOOF_NONE) ? 1 : 0;
}
static const char *gpu_spoof_name(int id) {
return id == GPU_SPOOF_RTX ? "rtx" : (id == GPU_SPOOF_RDNA4 ? "rdna4" : "off");
}
static void apply_gpu_spoof(VkPhysicalDeviceProperties *props) {
if (!props) return;
int id = GPU_SPOOF_NONE;
gpu_spoof_config(&id, NULL);
if (id == GPU_SPOOF_RDNA4) {
props->vendorID = 0x1002u;
props->deviceID = 0x7550u;
props->driverVersion = (2u << 22) | (0u << 12) | 310u;
props->deviceType = VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
snprintf(props->deviceName, sizeof props->deviceName, "AMD Radeon RX 9070 XT");
} else if (id == GPU_SPOOF_RTX) {
props->vendorID = 0x10DEu;
props->deviceID = 0x1F08u;
props->driverVersion = (570u << 22) | (0u << 14); /* NVIDIA 570.00 */
props->deviceType = VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
snprintf(props->deviceName, sizeof props->deviceName, "NVIDIA GeForce RTX 2060");
}
}
static void apply_gpu_spoof2(VkPhysicalDeviceProperties2 *props2) {
if (!props2) return;
apply_gpu_spoof(&props2->properties);
int id = GPU_SPOOF_NONE, driver = 0;
gpu_spoof_config(&id, &driver);
if (!driver) return;
int is_rtx = (id == GPU_SPOOF_RTX);
for (VkBaseOutStructure *n = (VkBaseOutStructure *)props2->pNext; n; n = n->pNext) {
if (n->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES) {
VkPhysicalDeviceDriverProperties *dp = (VkPhysicalDeviceDriverProperties *)n;
dp->driverID = is_rtx ? VK_DRIVER_ID_NVIDIA_PROPRIETARY : VK_DRIVER_ID_AMD_PROPRIETARY;
snprintf(dp->driverName, sizeof dp->driverName, "%s", is_rtx ? "NVIDIA" : "AMD proprietary driver");
snprintf(dp->driverInfo, sizeof dp->driverInfo, "%s", is_rtx ? "570.00" : "25.3.1");
} else if (n->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES) {
VkPhysicalDeviceVulkan12Properties *v12 = (VkPhysicalDeviceVulkan12Properties *)n;
v12->driverID = is_rtx ? VK_DRIVER_ID_NVIDIA_PROPRIETARY : VK_DRIVER_ID_AMD_PROPRIETARY;
snprintf(v12->driverName, sizeof v12->driverName, "%s", is_rtx ? "NVIDIA" : "AMD proprietary driver");
snprintf(v12->driverInfo, sizeof v12->driverInfo, "%s", is_rtx ? "570.00" : "25.3.1");
}
}
}
static int ext_in_list(const VkExtensionProperties *exts, uint32_t count, const char *name) {
for (uint32_t i = 0; i < count; i++) {
if (!strcmp(exts[i].extensionName, name)) return 1;
}
return 0;
}
static int name_in_array(const char *const *names, uint32_t count, const char *name) {
for (uint32_t i = 0; i < count; i++) {
if (names[i] && !strcmp(names[i], name)) return 1;
}
return 0;
}
static void *find_pnext(void *pnext, VkStructureType stype) {
VkBaseOutStructure *cur = (VkBaseOutStructure *)pnext;
while (cur) {
if (cur->sType == stype) return cur;
cur = cur->pNext;
}
return NULL;
}
// ---- NVX stub procs for Vulkan DLSS games (RDR2) ----
static VkResult VKAPI_CALL stub_vkCreateCuModuleNVX(VkDevice dev, const void *info, const VkAllocationCallbacks *alloc, uint64_t *mod) {
(void)dev; (void)info; (void)alloc;
if (mod) *mod = 0x1001ULL;
return VK_SUCCESS;
}
static VkResult VKAPI_CALL stub_vkCreateCuFunctionNVX(VkDevice dev, const void *info, const VkAllocationCallbacks *alloc, uint64_t *fn) {
(void)dev; (void)info; (void)alloc;
if (fn) *fn = 0x2001ULL;
return VK_SUCCESS;
}
static void VKAPI_CALL stub_vkDestroyCuModuleNVX(VkDevice dev, uint64_t mod, const VkAllocationCallbacks *alloc) {
(void)dev; (void)mod; (void)alloc;
}
static void VKAPI_CALL stub_vkDestroyCuFunctionNVX(VkDevice dev, uint64_t fn, const VkAllocationCallbacks *alloc) {
(void)dev; (void)fn; (void)alloc;
}
static void VKAPI_CALL stub_vkCmdCuLaunchKernelNVX(VkCommandBuffer cb, const void *info) {
(void)cb; (void)info;
}
static uint32_t VKAPI_CALL stub_vkGetImageViewHandleNVX(VkDevice dev, const void *info) {
(void)dev; (void)info;
return 1u;
}
static VkResult VKAPI_CALL stub_vkGetImageViewAddressNVX(VkDevice dev, VkImageView view, void *props) {
(void)dev; (void)view; (void)props;
return VK_SUCCESS;
}
// ---- Instance hooks ----
static VkResult VKAPI_CALL hook_vkCreateInstance(const VkInstanceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkInstance *pInstance) {
WlVkLayerInstanceCreateInfo *chain = (WlVkLayerInstanceCreateInfo *)pCreateInfo->pNext;
while (chain && !(chain->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && chain->function == WL_VK_LAYER_LINK_INFO)) {
chain = (WlVkLayerInstanceCreateInfo *)chain->pNext;
}
if (!chain || !chain->u.pLayerInfo) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr next_gipa = chain->u.pLayerInfo->pfnNextGetInstanceProcAddr;
chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
PFN_vkCreateInstance next_ci = (PFN_vkCreateInstance)next_gipa(VK_NULL_HANDLE, "vkCreateInstance");
if (!next_ci) return VK_ERROR_INITIALIZATION_FAILED;
VkResult r = next_ci(pCreateInfo, pAllocator, pInstance);
if (r != VK_SUCCESS) return r;
pthread_mutex_lock(&g_mu);
for (int i = 0; i < MAX_INSTANCES; i++) {
if (!g_insts[i].key) {
InstCtx *ic = &g_insts[i];
memset(ic, 0, sizeof *ic);
ic->key = dispatch_key(*pInstance);
ic->instance = *pInstance;
ic->next_gipa = next_gipa;
ic->DestroyInstance = (PFN_vkDestroyInstance)next_gipa(*pInstance, "vkDestroyInstance");
ic->EnumerateDeviceExtensionProperties = (PFN_vkEnumerateDeviceExtensionProperties)next_gipa(*pInstance, "vkEnumerateDeviceExtensionProperties");
ic->GetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)next_gipa(*pInstance, "vkGetPhysicalDeviceProperties");
ic->GetPhysicalDeviceProperties2 = (PFN_vkGetPhysicalDeviceProperties2)next_gipa(*pInstance, "vkGetPhysicalDeviceProperties2");
if (!ic->GetPhysicalDeviceProperties2) {
ic->GetPhysicalDeviceProperties2 = (PFN_vkGetPhysicalDeviceProperties2)next_gipa(*pInstance, "vkGetPhysicalDeviceProperties2KHR");
}
ic->GetPhysicalDeviceFeatures2 = (PFN_vkGetPhysicalDeviceFeatures2)next_gipa(*pInstance, "vkGetPhysicalDeviceFeatures2");
if (!ic->GetPhysicalDeviceFeatures2) {
ic->GetPhysicalDeviceFeatures2 = (PFN_vkGetPhysicalDeviceFeatures2)next_gipa(*pInstance, "vkGetPhysicalDeviceFeatures2KHR");
}
ic->GetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)next_gipa(*pInstance, "vkGetPhysicalDeviceMemoryProperties");
ic->GetPhysicalDeviceMemoryProperties2 = (PFN_vkGetPhysicalDeviceMemoryProperties2)next_gipa(*pInstance, "vkGetPhysicalDeviceMemoryProperties2");
if (!ic->GetPhysicalDeviceMemoryProperties2) {
ic->GetPhysicalDeviceMemoryProperties2 = (PFN_vkGetPhysicalDeviceMemoryProperties2)next_gipa(*pInstance, "vkGetPhysicalDeviceMemoryProperties2KHR");
}
ic->GetPhysicalDeviceFormatProperties = (PFN_vkGetPhysicalDeviceFormatProperties)next_gipa(*pInstance, "vkGetPhysicalDeviceFormatProperties");
ic->GetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties)next_gipa(*pInstance, "vkGetPhysicalDeviceQueueFamilyProperties");
break;
}
}
pthread_mutex_unlock(&g_mu);
try_patch_rdr2_exe();
int spoof_id = GPU_SPOOF_NONE, spoof_driver = 0;
gpu_spoof_config(&spoof_id, &spoof_driver);
F4_LOGI("vkCreateInstance attached (dlss_spoof=%d gpu_spoof=%s driver_spoof=%d rdr2_patch=%d)",
spoof_dlss_enabled(), gpu_spoof_name(spoof_id), spoof_driver, (int)g_rdr2_patched);
return VK_SUCCESS;
}
static void VKAPI_CALL hook_vkDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) {
PFN_vkDestroyInstance down = NULL;
pthread_mutex_lock(&g_mu);
InstCtx *ic = find_inst_locked(instance);
if (ic) {
down = ic->DestroyInstance;
memset(ic, 0, sizeof *ic);
}
pthread_mutex_unlock(&g_mu);
if (down) down(instance, pAllocator);
}
static uint64_t configured_vram_override_bytes(void) {
const char *ov = dd_upscale_env("VRAM_OVERRIDE");
if (!ov || strcmp(ov, "1") != 0) return 0ULL;
const char *v = dd_upscale_env("VRAM_MB");
if (!v) v = getenv("WRAPPER_VMEM_MAX_SIZE");
if (!v || !*v) return 0ULL;
unsigned long long mb = strtoull(v, NULL, 10);
if (mb < 512ULL || mb > 65536ULL) return 0ULL;
return (uint64_t)mb * 1024ULL * 1024ULL;
}
static void apply_vram_override_mp(VkPhysicalDeviceMemoryProperties *mp, VkPhysicalDeviceMemoryBudgetPropertiesEXT *budget) {
if (!mp) return;
uint64_t want = configured_vram_override_bytes();
if (want == 0ULL) return;
for (uint32_t i = 0; i < mp->memoryHeapCount && i < VK_MAX_MEMORY_HEAPS; i++) {
if (mp->memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
mp->memoryHeaps[i].size = (VkDeviceSize)want;
if (budget) {
budget->heapBudget[i] = (VkDeviceSize)want;
if (budget->heapUsage[i] > (VkDeviceSize)want) {
budget->heapUsage[i] = (VkDeviceSize)(want / 2ULL);
}
}
}
}
}
static void VKAPI_CALL hook_vkGetPhysicalDeviceMemoryProperties(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties *mp) {
pthread_mutex_lock(&g_mu);
InstCtx *ic = find_inst_locked(pd);
PFN_vkGetPhysicalDeviceMemoryProperties down = ic ? ic->GetPhysicalDeviceMemoryProperties : NULL;
pthread_mutex_unlock(&g_mu);
if (down) down(pd, mp);
apply_vram_override_mp(mp, NULL);
}
static void VKAPI_CALL hook_vkGetPhysicalDeviceMemoryProperties2(VkPhysicalDevice pd, VkPhysicalDeviceMemoryProperties2 *mp2) {
pthread_mutex_lock(&g_mu);
InstCtx *ic = find_inst_locked(pd);
PFN_vkGetPhysicalDeviceMemoryProperties2 down = ic ? ic->GetPhysicalDeviceMemoryProperties2 : NULL;
PFN_vkGetPhysicalDeviceMemoryProperties down1 = ic ? ic->GetPhysicalDeviceMemoryProperties : NULL;
pthread_mutex_unlock(&g_mu);
if (down) down(pd, mp2);
else if (down1 && mp2) down1(pd, &mp2->memoryProperties);
if (mp2) {
VkPhysicalDeviceMemoryBudgetPropertiesEXT *budget =
(VkPhysicalDeviceMemoryBudgetPropertiesEXT *)find_pnext(
mp2->pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT);
apply_vram_override_mp(&mp2->memoryProperties, budget);
}
}
static void VKAPI_CALL hook_vkGetPhysicalDeviceProperties(VkPhysicalDevice pd, VkPhysicalDeviceProperties *props) {
pthread_mutex_lock(&g_mu);
InstCtx *ic = find_inst_locked(pd);
PFN_vkGetPhysicalDeviceProperties down = ic ? ic->GetPhysicalDeviceProperties : NULL;
pthread_mutex_unlock(&g_mu);
if (down) down(pd, props);
apply_gpu_spoof(props);
}
static void VKAPI_CALL hook_vkGetPhysicalDeviceProperties2(VkPhysicalDevice pd, VkPhysicalDeviceProperties2 *props2) {
pthread_mutex_lock(&g_mu);
InstCtx *ic = find_inst_locked(pd);
PFN_vkGetPhysicalDeviceProperties2 down = ic ? ic->GetPhysicalDeviceProperties2 : NULL;
pthread_mutex_unlock(&g_mu);
if (down) down(pd, props2);
apply_gpu_spoof2(props2);
}
static VkResult VKAPI_CALL hook_vkEnumerateDeviceExtensionProperties(VkPhysicalDevice pd, const char *pLayerName,
uint32_t *pPropertyCount, VkExtensionProperties *pProperties) {
if (pLayerName && !strcmp(pLayerName, WL_LAYER_NAME)) {
if (pPropertyCount) *pPropertyCount = 0;
return VK_SUCCESS;
}
pthread_mutex_lock(&g_mu);
InstCtx *ic = find_inst_locked(pd);
PFN_vkEnumerateDeviceExtensionProperties down = ic ? ic->EnumerateDeviceExtensionProperties : NULL;
pthread_mutex_unlock(&g_mu);
if (!down) return VK_ERROR_INITIALIZATION_FAILED;
int spoof = spoof_dlss_enabled();
int hide_db = hide_app_descriptor_buffer();
if (pLayerName || (!spoof && !hide_db)) {
return down(pd, pLayerName, pPropertyCount, pProperties);
}
uint32_t real_count = 0;
VkResult r = down(pd, NULL, &real_count, NULL);
if (r != VK_SUCCESS) return r;
VkExtensionProperties *real_exts = (VkExtensionProperties *)calloc(real_count ? real_count : 1, sizeof *real_exts);
if (!real_exts) return VK_ERROR_OUT_OF_HOST_MEMORY;
r = down(pd, NULL, &real_count, real_exts);
if (r != VK_SUCCESS) { free(real_exts); return r; }
if (hide_db) {
uint32_t kept = 0;
for (uint32_t i = 0; i < real_count; i++) {
if (strcmp(real_exts[i].extensionName, "VK_EXT_descriptor_buffer")) real_exts[kept++] = real_exts[i];
}
real_count = kept;
}
static const char *const k_fake_nvx[] = {"VK_NVX_binary_import", "VK_NVX_image_view_handle"};
uint32_t extra = 0;
for (int i = 0; spoof && i < 2; i++) {
if (!ext_in_list(real_exts, real_count, k_fake_nvx[i])) extra++;
}
uint32_t total = real_count + extra;
if (!pProperties) {
*pPropertyCount = total;
free(real_exts);
return VK_SUCCESS;
}
uint32_t cap = *pPropertyCount;
uint32_t out_n = 0;
for (uint32_t i = 0; i < real_count && out_n < cap; i++) pProperties[out_n++] = real_exts[i];
for (int i = 0; spoof && i < 2 && out_n < cap; i++) {
if (!ext_in_list(real_exts, real_count, k_fake_nvx[i])) {
memset(&pProperties[out_n], 0, sizeof pProperties[out_n]);
snprintf(pProperties[out_n].extensionName, sizeof pProperties[out_n].extensionName, "%s", k_fake_nvx[i]);
pProperties[out_n].specVersion = 2;
out_n++;
}
}
*pPropertyCount = out_n;
free(real_exts);
return (out_n < total) ? VK_INCOMPLETE : VK_SUCCESS;
}
// ---- Device creation with transparent FSR 4 NPU extension & feature injection ----
static VkResult VKAPI_CALL hook_vkCreateDevice(VkPhysicalDevice pd,
const VkDeviceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDevice *pDevice) {
WlVkLayerDeviceCreateInfo *chain = (WlVkLayerDeviceCreateInfo *)pCreateInfo->pNext;
while (chain && !(chain->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && chain->function == WL_VK_LAYER_LINK_INFO)) {
chain = (WlVkLayerDeviceCreateInfo *)chain->pNext;
}
if (!chain || !chain->u.pLayerInfo) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr next_gipa = chain->u.pLayerInfo->pfnNextGetInstanceProcAddr;
PFN_vkGetDeviceProcAddr next_gdpa = chain->u.pLayerInfo->pfnNextGetDeviceProcAddr;
chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
PFN_vkCreateDevice next_cd = (PFN_vkCreateDevice)next_gipa(VK_NULL_HANDLE, "vkCreateDevice");
if (!next_cd) return VK_ERROR_INITIALIZATION_FAILED;
pthread_mutex_lock(&g_mu);
InstCtx *ic = find_inst_locked(pd);
pthread_mutex_unlock(&g_mu);
// Passive Pacer-Only Mode (Upscaler = Off): zero GPU spoof, zero extension/feature injection,
// zero FSR/NPU allocation — ONLY hooks vkQueuePresentKHR for Reflex-style low-latency FPS pacing.
if (is_pacer_only_mode()) {
VkResult r = next_cd(pd, pCreateInfo, pAllocator, pDevice);
if (r != VK_SUCCESS) return r;
DevCtx *d = (DevCtx *)calloc(1, sizeof *d);
if (!d) return VK_SUCCESS;
d->key = dispatch_key(*pDevice);
d->device = *pDevice;
d->phys_dev = pd;
d->inst = ic;
d->pacer_only = 1;
d->next_gdpa = next_gdpa;
d->DestroyDevice = (PFN_vkDestroyDevice)next_gdpa(*pDevice, "vkDestroyDevice");
d->QueuePresentKHR = (PFN_vkQueuePresentKHR)next_gdpa(*pDevice, "vkQueuePresentKHR");
d->QueueSubmit = (PFN_vkQueueSubmit)next_gdpa(*pDevice, "vkQueueSubmit");
d->CreateFence = (PFN_vkCreateFence)next_gdpa(*pDevice, "vkCreateFence");
d->DestroyFence = (PFN_vkDestroyFence)next_gdpa(*pDevice, "vkDestroyFence");
d->WaitForFences = (PFN_vkWaitForFences)next_gdpa(*pDevice, "vkWaitForFences");
d->ResetFences = (PFN_vkResetFences)next_gdpa(*pDevice, "vkResetFences");
pthread_mutex_init(&d->pacer.mu, NULL);
d->pacer.mu_init = 1;
pthread_mutex_lock(&g_mu);
for (int i = 0; i < MAX_DEVICES; i++) {
if (!g_devs[i]) { g_devs[i] = d; break; }
}
pthread_mutex_unlock(&g_mu);
F4_LOGI("vkCreateDevice attached (pacer-only low-latency mode, present=%d)", d->QueuePresentKHR != NULL);
return VK_SUCCESS;
}
// Capture real (unspoofed) GPU driver name & timestampPeriod for diagnostics and GPU HUD timing
float ts_period = 0.0f;
if (ic && ic->GetPhysicalDeviceProperties) {
VkPhysicalDeviceProperties rp;
memset(&rp, 0, sizeof rp);
ic->GetPhysicalDeviceProperties(pd, &rp);
if (rp.deviceName[0]) {
snprintf(g_real_gpu_name, sizeof g_real_gpu_name, "%.*s", (int)(sizeof g_real_gpu_name - 1), rp.deviceName);
}
ts_period = rp.limits.timestampPeriod;
}
// Query real device extensions & features so we transparently enable Adreno 840 / Turnip DP4a,
// FP16, INT8, compute derivatives, BDA, 8/16-bit storage, and descriptor_buffer whenever supported.
uint32_t avail_n = 0;
VkExtensionProperties *avail = NULL;
if (ic && ic->EnumerateDeviceExtensionProperties) {
if (ic->EnumerateDeviceExtensionProperties(pd, NULL, &avail_n, NULL) == VK_SUCCESS && avail_n > 0) {
avail = (VkExtensionProperties *)calloc(avail_n, sizeof *avail);
if (avail) ic->EnumerateDeviceExtensionProperties(pd, NULL, &avail_n, avail);
}
}
int can_db = avail && ext_in_list(avail, avail_n, "VK_EXT_descriptor_buffer");
int can_mut = avail && ext_in_list(avail, avail_n, "VK_EXT_mutable_descriptor_type");
int can_ahb = avail && ext_in_list(avail, avail_n, "VK_ANDROID_external_memory_android_hardware_buffer");
int can_dma = avail && ext_in_list(avail, avail_n, "VK_EXT_external_memory_dma_buf");
int can_qff = avail && ext_in_list(avail, avail_n, "VK_EXT_queue_family_foreign");
int can_extm = avail && ext_in_list(avail, avail_n, "VK_KHR_external_memory");
int can_sync2 = avail && ext_in_list(avail, avail_n, "VK_KHR_synchronization2");
int can_bda = avail && ext_in_list(avail, avail_n, "VK_KHR_buffer_device_address");
int can_f16i8 = avail && ext_in_list(avail, avail_n, "VK_KHR_shader_float16_int8");
int can_dot = avail && ext_in_list(avail, avail_n, "VK_KHR_shader_integer_dot_product");
int can_sg = avail && ext_in_list(avail, avail_n, "VK_EXT_subgroup_size_control");
int can_deriv = avail && ext_in_list(avail, avail_n, "VK_KHR_compute_shader_derivatives");
int can_deriv_nv = !can_deriv && avail && ext_in_list(avail, avail_n, "VK_NV_compute_shader_derivatives");
int can_8bit = avail && ext_in_list(avail, avail_n, "VK_KHR_8bit_storage");
int can_16bit = avail && ext_in_list(avail, avail_n, "VK_KHR_16bit_storage");
VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR q_deriv = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_KHR
};
VkPhysicalDeviceDescriptorBufferFeaturesEXT q_db = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_BUFFER_FEATURES_EXT,
.pNext = (can_deriv || can_deriv_nv) ? &q_deriv : NULL
};
VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT q_mut = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MUTABLE_DESCRIPTOR_TYPE_FEATURES_EXT, .pNext = &q_db
};
VkPhysicalDeviceVulkan11Features q_v11 = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, .pNext = &q_mut
};
VkPhysicalDeviceVulkan12Features q_v12 = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, .pNext = &q_v11
};
VkPhysicalDeviceVulkan13Features q_v13 = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, .pNext = &q_v12
};
VkPhysicalDeviceFeatures2 q_f2 = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &q_v13
};
if (ic && ic->GetPhysicalDeviceFeatures2) {
ic->GetPhysicalDeviceFeatures2(pd, &q_f2);
}
int want_db = can_db && q_db.descriptorBuffer;
int want_mut = can_mut && q_mut.mutableDescriptorType;
int want_bda = q_v12.bufferDeviceAddress ? 1 : 0;
int want_f16 = q_v12.shaderFloat16 ? 1 : 0;
int want_i8 = q_v12.shaderInt8 ? 1 : 0;
int want_8bit = q_v12.storageBuffer8BitAccess ? 1 : 0;
int want_16bit = q_v11.uniformAndStorageBuffer16BitAccess || q_v11.storageBuffer16BitAccess ? 1 : 0;
int want_dot = q_v13.shaderIntegerDotProduct ? 1 : 0;
int want_sync2 = q_v13.synchronization2 ? 1 : 0;
int want_deriv = (can_deriv || can_deriv_nv) && q_deriv.computeDerivativeGroupQuads;
// Build filtered + augmented extension list (strip fake VK_NVX_* if spoofed)
uint32_t max_exts = pCreateInfo->enabledExtensionCount + 20;
const char **exts = (const char **)calloc(max_exts, sizeof(char *));
uint32_t ext_n = 0;
int app_db = 0;
for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
const char *en = pCreateInfo->ppEnabledExtensionNames[i];
if (!en) continue;
if (!strcmp(en, "VK_EXT_descriptor_buffer")) app_db = 1;
if ((!strcmp(en, "VK_NVX_binary_import") || !strcmp(en, "VK_NVX_image_view_handle")) &&
!(avail && ext_in_list(avail, avail_n, en))) {
continue;
}
exts[ext_n++] = en;
}
const char *inject[] = {
want_db ? "VK_EXT_descriptor_buffer" : NULL,
want_mut ? "VK_EXT_mutable_descriptor_type" : NULL,
can_ahb ? "VK_ANDROID_external_memory_android_hardware_buffer" : NULL,
can_dma ? "VK_EXT_external_memory_dma_buf" : NULL,
can_qff ? "VK_EXT_queue_family_foreign" : NULL,
can_extm ? "VK_KHR_external_memory" : NULL,
(can_sync2 && want_sync2) ? "VK_KHR_synchronization2" : NULL,
(can_bda && want_bda) ? "VK_KHR_buffer_device_address" : NULL,
(can_f16i8 && (want_f16 || want_i8)) ? "VK_KHR_shader_float16_int8" : NULL,
(can_dot && want_dot) ? "VK_KHR_shader_integer_dot_product" : NULL,
can_sg ? "VK_EXT_subgroup_size_control" : NULL,
(can_deriv && want_deriv) ? "VK_KHR_compute_shader_derivatives" :
((can_deriv_nv && want_deriv) ? "VK_NV_compute_shader_derivatives" : NULL),
(can_8bit && want_8bit) ? "VK_KHR_8bit_storage" : NULL,
(can_16bit && want_16bit) ? "VK_KHR_16bit_storage" : NULL,
};
for (size_t i = 0; i < sizeof(inject) / sizeof(inject[0]); i++) {
if (inject[i] && !name_in_array(exts, ext_n, inject[i])) exts[ext_n++] = inject[i];
}
// Clone VkDeviceCreateInfo and patch/chain required feature structs without duplicates
VkDeviceCreateInfo mod_ci = *pCreateInfo;
mod_ci.enabledExtensionCount = ext_n;
mod_ci.ppEnabledExtensionNames = exts;
VkPhysicalDeviceDescriptorBufferFeaturesEXT add_db = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_BUFFER_FEATURES_EXT, .descriptorBuffer = VK_TRUE
};
VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT add_mut = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MUTABLE_DESCRIPTOR_TYPE_FEATURES_EXT, .mutableDescriptorType = VK_TRUE
};
VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR add_deriv = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_KHR,
.computeDerivativeGroupQuads = VK_TRUE
};
VkPhysicalDeviceBufferDeviceAddressFeatures add_bda = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES, .bufferDeviceAddress = VK_TRUE
};
VkPhysicalDeviceShaderFloat16Int8Features add_f16 = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES,
.shaderFloat16 = want_f16 ? VK_TRUE : VK_FALSE,
.shaderInt8 = want_i8 ? VK_TRUE : VK_FALSE
};
VkPhysicalDevice8BitStorageFeatures add_8bit = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES,
.storageBuffer8BitAccess = q_v12.storageBuffer8BitAccess,
.uniformAndStorageBuffer8BitAccess = q_v12.uniformAndStorageBuffer8BitAccess
};
VkPhysicalDevice16BitStorageFeatures add_16bit = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES,
.storageBuffer16BitAccess = q_v11.storageBuffer16BitAccess,
.uniformAndStorageBuffer16BitAccess = q_v11.uniformAndStorageBuffer16BitAccess
};
VkPhysicalDeviceSynchronization2Features add_sync2 = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES, .synchronization2 = VK_TRUE
};
VkPhysicalDeviceShaderIntegerDotProductFeatures add_dot = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES, .shaderIntegerDotProduct = VK_TRUE
};
VkPhysicalDeviceDescriptorIndexingFeatures add_di = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES,
.descriptorBindingVariableDescriptorCount = q_v12.descriptorBindingVariableDescriptorCount,
.runtimeDescriptorArray = q_v12.runtimeDescriptorArray
};
void *pnext_head = (void *)mod_ci.pNext;
if (want_db) {
VkPhysicalDeviceDescriptorBufferFeaturesEXT *ex = (VkPhysicalDeviceDescriptorBufferFeaturesEXT *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_BUFFER_FEATURES_EXT);
if (ex) ex->descriptorBuffer = VK_TRUE;
else { add_db.pNext = pnext_head; pnext_head = &add_db; }
}
if (want_mut) {
VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT *ex = (VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MUTABLE_DESCRIPTOR_TYPE_FEATURES_EXT);
if (ex) ex->mutableDescriptorType = VK_TRUE;
else { add_mut.pNext = pnext_head; pnext_head = &add_mut; }
}
if (want_deriv) {
VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR *ex = (VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_KHR);
if (ex) ex->computeDerivativeGroupQuads = VK_TRUE;
else { add_deriv.pNext = pnext_head; pnext_head = &add_deriv; }
}
VkPhysicalDeviceVulkan12Features *ex12 = (VkPhysicalDeviceVulkan12Features *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES);
if (ex12) {
if (want_bda) ex12->bufferDeviceAddress = VK_TRUE;
if (want_f16) ex12->shaderFloat16 = VK_TRUE;
if (want_i8) ex12->shaderInt8 = VK_TRUE;
if (q_v12.storageBuffer8BitAccess) ex12->storageBuffer8BitAccess = VK_TRUE;
if (q_v12.uniformAndStorageBuffer8BitAccess) ex12->uniformAndStorageBuffer8BitAccess = VK_TRUE;
if (q_v12.descriptorBindingVariableDescriptorCount) ex12->descriptorBindingVariableDescriptorCount = VK_TRUE;
if (q_v12.runtimeDescriptorArray) ex12->runtimeDescriptorArray = VK_TRUE;
} else {
if (want_bda) {
VkPhysicalDeviceBufferDeviceAddressFeatures *ex = (VkPhysicalDeviceBufferDeviceAddressFeatures *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES);
if (ex) ex->bufferDeviceAddress = VK_TRUE;
else { add_bda.pNext = pnext_head; pnext_head = &add_bda; }
}
if (want_f16 || want_i8) {
VkPhysicalDeviceShaderFloat16Int8Features *ex = (VkPhysicalDeviceShaderFloat16Int8Features *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES);
if (ex) {
if (want_f16) ex->shaderFloat16 = VK_TRUE;
if (want_i8) ex->shaderInt8 = VK_TRUE;
} else { add_f16.pNext = pnext_head; pnext_head = &add_f16; }
}
if (want_8bit) {
VkPhysicalDevice8BitStorageFeatures *ex = (VkPhysicalDevice8BitStorageFeatures *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES);
if (ex) {
if (q_v12.storageBuffer8BitAccess) ex->storageBuffer8BitAccess = VK_TRUE;
if (q_v12.uniformAndStorageBuffer8BitAccess) ex->uniformAndStorageBuffer8BitAccess = VK_TRUE;
} else { add_8bit.pNext = pnext_head; pnext_head = &add_8bit; }
}
if (q_v12.descriptorBindingVariableDescriptorCount || q_v12.runtimeDescriptorArray) {
VkPhysicalDeviceDescriptorIndexingFeatures *ex = (VkPhysicalDeviceDescriptorIndexingFeatures *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES);
if (ex) {
if (q_v12.descriptorBindingVariableDescriptorCount) ex->descriptorBindingVariableDescriptorCount = VK_TRUE;
if (q_v12.runtimeDescriptorArray) ex->runtimeDescriptorArray = VK_TRUE;
} else { add_di.pNext = pnext_head; pnext_head = &add_di; }
}
}
VkPhysicalDeviceVulkan11Features *ex11 = (VkPhysicalDeviceVulkan11Features *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
if (ex11) {
if (q_v11.storageBuffer16BitAccess) ex11->storageBuffer16BitAccess = VK_TRUE;
if (q_v11.uniformAndStorageBuffer16BitAccess) ex11->uniformAndStorageBuffer16BitAccess = VK_TRUE;
} else if (want_16bit) {
VkPhysicalDevice16BitStorageFeatures *ex = (VkPhysicalDevice16BitStorageFeatures *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES);
if (ex) {
if (q_v11.storageBuffer16BitAccess) ex->storageBuffer16BitAccess = VK_TRUE;
if (q_v11.uniformAndStorageBuffer16BitAccess) ex->uniformAndStorageBuffer16BitAccess = VK_TRUE;
} else { add_16bit.pNext = pnext_head; pnext_head = &add_16bit; }
}
VkPhysicalDeviceVulkan13Features *ex13 = (VkPhysicalDeviceVulkan13Features *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES);
if (ex13) {
if (want_sync2) ex13->synchronization2 = VK_TRUE;
if (want_dot) ex13->shaderIntegerDotProduct = VK_TRUE;
} else {
if (want_sync2) {
VkPhysicalDeviceSynchronization2Features *ex = (VkPhysicalDeviceSynchronization2Features *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES);
if (ex) ex->synchronization2 = VK_TRUE;
else { add_sync2.pNext = pnext_head; pnext_head = &add_sync2; }
}
if (want_dot) {
VkPhysicalDeviceShaderIntegerDotProductFeatures *ex = (VkPhysicalDeviceShaderIntegerDotProductFeatures *)find_pnext(pnext_head, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES);
if (ex) ex->shaderIntegerDotProduct = VK_TRUE;
else { add_dot.pNext = pnext_head; pnext_head = &add_dot; }
}
}
mod_ci.pNext = pnext_head;
VkResult r = next_cd(pd, &mod_ci, pAllocator, pDevice);
if (r != VK_SUCCESS) {
// Retry with unmodified pCreateInfo (except stripped fake NVX exts) so games never fail to boot
F4_LOGW("augmented vkCreateDevice failed (%d); retrying with game's original features", r);
VkDeviceCreateInfo fallback_ci = *pCreateInfo;
fallback_ci.enabledExtensionCount = 0;
const char **clean_exts = (const char **)calloc(pCreateInfo->enabledExtensionCount ? pCreateInfo->enabledExtensionCount : 1, sizeof(char *));
for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
const char *en = pCreateInfo->ppEnabledExtensionNames[i];
if (!en) continue;
if ((!strcmp(en, "VK_NVX_binary_import") || !strcmp(en, "VK_NVX_image_view_handle")) &&
!(avail && ext_in_list(avail, avail_n, en))) continue;
clean_exts[fallback_ci.enabledExtensionCount++] = en;
}
fallback_ci.ppEnabledExtensionNames = clean_exts;
r = next_cd(pd, &fallback_ci, pAllocator, pDevice);
free(clean_exts);
want_db = want_mut = want_deriv = want_dot = want_f16 = want_i8 = want_bda = can_ahb = 0;
}
free(exts);
free(avail);
if (r != VK_SUCCESS) return r;
DevCtx *d = (DevCtx *)calloc(1, sizeof *d);
if (!d) return VK_SUCCESS;
d->key = dispatch_key(*pDevice);
d->device = *pDevice;
d->phys_dev = pd;
d->inst = ic;
d->next_gdpa = next_gdpa;
#define LOAD_DEV(fn) d->fn = (PFN_vk##fn)next_gdpa(*pDevice, "vk" #fn)
LOAD_DEV(DestroyDevice);
LOAD_DEV(CreateBuffer);
LOAD_DEV(DestroyBuffer);
LOAD_DEV(BindBufferMemory);
LOAD_DEV(MapMemory);
LOAD_DEV(UnmapMemory);
LOAD_DEV(CreateImage);
LOAD_DEV(DestroyImage);
LOAD_DEV(CmdUpdateBuffer);
LOAD_DEV(QueuePresentKHR);
LOAD_DEV(QueueSubmit);
LOAD_DEV(CreateFence);
LOAD_DEV(DestroyFence);
LOAD_DEV(WaitForFences);
LOAD_DEV(ResetFences);
#undef LOAD_DEV
pthread_mutex_init(&d->pacer.mu, NULL);
d->pacer.mu_init = 1;
WlVkDispatch *v = &d->disp;
v->instance = ic ? ic->instance : VK_NULL_HANDLE;
v->phys_dev = pd;
v->device = *pDevice;
v->graphics_qf = pCreateInfo->queueCreateInfoCount > 0 ? pCreateInfo->pQueueCreateInfos[0].queueFamilyIndex : 0u;
v->has_desc_buf = want_db;
v->app_desc_buf = app_db;
v->has_mut_desc = want_mut;
v->has_ext_ahb = can_ahb;
v->has_bda = want_bda;
v->has_f16 = want_f16;
v->has_i8 = want_i8;
v->has_int_dot = want_dot;
v->has_sync2 = want_sync2;
v->has_qf_foreign = can_qff;
v->has_compute_derivs = want_deriv;
v->has_8bit_storage = want_8bit;
v->has_16bit_storage = want_16bit;
v->timestamp_period = ts_period;
v->has_timestamps = (ts_period > 0.0f) ? 1 : 0;
if (ic) {
v->GetPhysicalDeviceProperties = ic->GetPhysicalDeviceProperties;
v->GetPhysicalDeviceProperties2 = ic->GetPhysicalDeviceProperties2;
v->GetPhysicalDeviceMemoryProperties = ic->GetPhysicalDeviceMemoryProperties;
v->GetPhysicalDeviceFormatProperties = ic->GetPhysicalDeviceFormatProperties;
v->GetPhysicalDeviceQueueFamilyProperties = ic->GetPhysicalDeviceQueueFamilyProperties;
if (ic->GetPhysicalDeviceProperties2) {
VkPhysicalDeviceSubgroupSizeControlProperties sgp = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES };
VkPhysicalDeviceProperties2 p2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &sgp};
ic->GetPhysicalDeviceProperties2(pd, &p2);
v->subgroup_req_stages = sgp.requiredSubgroupSizeStages;
v->subgroup_min = sgp.minSubgroupSize;
v->subgroup_max = sgp.maxSubgroupSize;
}
if (ic->GetPhysicalDeviceQueueFamilyProperties) {
uint32_t qfc = 0;
ic->GetPhysicalDeviceQueueFamilyProperties(pd, &qfc, NULL);
if (qfc > v->graphics_qf && qfc <= 16u) {
VkQueueFamilyProperties qfp[16];
ic->GetPhysicalDeviceQueueFamilyProperties(pd, &qfc, qfp);
if (qfp[v->graphics_qf].timestampValidBits == 0u) v->has_timestamps = 0;
}
}
}
v->GetDeviceProcAddr = next_gdpa;
#define LOAD_V(fn) v->fn = (PFN_vk##fn)next_gdpa(*pDevice, "vk" #fn)
LOAD_V(CreateBuffer); LOAD_V(DestroyBuffer); LOAD_V(GetBufferMemoryRequirements); LOAD_V(BindBufferMemory);
LOAD_V(GetBufferDeviceAddress);
if (!v->GetBufferDeviceAddress) v->GetBufferDeviceAddress = (PFN_vkGetBufferDeviceAddress)next_gdpa(*pDevice, "vkGetBufferDeviceAddressKHR");
LOAD_V(AllocateMemory); LOAD_V(FreeMemory); LOAD_V(MapMemory); LOAD_V(UnmapMemory);
LOAD_V(CreateImage); LOAD_V(DestroyImage); LOAD_V(GetImageMemoryRequirements); LOAD_V(BindImageMemory);
LOAD_V(CreateImageView); LOAD_V(DestroyImageView);
LOAD_V(CreateSampler); LOAD_V(DestroySampler);
LOAD_V(CreateShaderModule); LOAD_V(DestroyShaderModule);
LOAD_V(CreateDescriptorSetLayout); LOAD_V(DestroyDescriptorSetLayout);
LOAD_V(CreateDescriptorPool); LOAD_V(DestroyDescriptorPool);
LOAD_V(AllocateDescriptorSets); LOAD_V(UpdateDescriptorSets); LOAD_V(CmdBindDescriptorSets);
LOAD_V(CreatePipelineLayout); LOAD_V(DestroyPipelineLayout);
LOAD_V(CreateComputePipelines); LOAD_V(DestroyPipeline);
LOAD_V(CmdBindPipeline); LOAD_V(CmdPushConstants); LOAD_V(CmdDispatch);
LOAD_V(CmdPipelineBarrier); LOAD_V(CmdPipelineBarrier2);
if (!v->CmdPipelineBarrier2) v->CmdPipelineBarrier2 = (PFN_vkCmdPipelineBarrier2)next_gdpa(*pDevice, "vkCmdPipelineBarrier2KHR");
LOAD_V(CmdClearColorImage); LOAD_V(CmdClearDepthStencilImage); LOAD_V(CmdFillBuffer);
LOAD_V(CmdCopyBuffer); LOAD_V(CmdCopyImageToBuffer); LOAD_V(CmdCopyBufferToImage);
LOAD_V(CmdBlitImage); LOAD_V(CmdCopyImage); LOAD_V(DeviceWaitIdle);
LOAD_V(CreateEvent); LOAD_V(DestroyEvent); LOAD_V(SetEvent); LOAD_V(ResetEvent); LOAD_V(GetEventStatus);
LOAD_V(CmdSetEvent); LOAD_V(CmdResetEvent); LOAD_V(CmdWaitEvents);
LOAD_V(CreateQueryPool); LOAD_V(DestroyQueryPool); LOAD_V(CmdResetQueryPool);
LOAD_V(CmdWriteTimestamp); LOAD_V(GetQueryPoolResults);
LOAD_V(GetDescriptorSetLayoutSizeEXT); LOAD_V(GetDescriptorSetLayoutBindingOffsetEXT); LOAD_V(GetDescriptorEXT);
LOAD_V(CmdBindDescriptorBuffersEXT); LOAD_V(CmdSetDescriptorBufferOffsetsEXT); LOAD_V(CmdBindDescriptorBufferEmbeddedSamplersEXT);
LOAD_V(GetAndroidHardwareBufferPropertiesANDROID);
#undef LOAD_V
d->pipe = wl_fsr4_pipe_create(v);
d->has_supported_npu = detect_supported_npu(g_real_gpu_name);
wl_gpu_timer_init(&d->xess_timer, v);
pthread_mutex_lock(&g_mu);
for (int i = 0; i < MAX_DEVICES; i++) {
if (!g_devs[i]) { g_devs[i] = d; break; }
}
pthread_mutex_unlock(&g_mu);
F4_LOGI("vkCreateDevice attached (gpu=%s db=%d mut=%d ahb=%d bda=%d f16=%d i8=%d dot=%d deriv=%d s8=%d s16=%d sync2=%d ts=%d sg=%u..%u)",
g_real_gpu_name, v->has_desc_buf, v->has_mut_desc, v->has_ext_ahb, v->has_bda,
v->has_f16, v->has_i8, v->has_int_dot, v->has_compute_derivs, v->has_8bit_storage,
v->has_16bit_storage, v->has_sync2, v->has_timestamps, v->subgroup_min, v->subgroup_max);
LiveCtrlState init_ctrl;
read_live_ctrl(&init_ctrl);
write_live_status(d->pipe, &init_ctrl, 0, 0, backend_default_tag(init_ctrl.backend),
WLFSR4_API_UNKNOWN, WLFSR4_QUALITY_AUTO, 0, 0, 0, 0, 0, 0, 0, 0, "standby", 1);
return VK_SUCCESS;
}
// ---- Zero-root Android 12+ ADPF (APerformanceHint) helper for Vulkan present thread ----
typedef void *(*pfn_adpf_get_mgr)(void);
typedef void *(*pfn_adpf_create_sess)(void *mgr, const int32_t *tids, size_t size, int64_t initial_target_ns);
typedef int (*pfn_adpf_update_target)(void *sess, int64_t target_ns);
typedef int (*pfn_adpf_report_actual)(void *sess, int64_t actual_ns);
typedef void (*pfn_adpf_close_sess)(void *sess);
typedef int (*pfn_adpf_set_threads)(void *sess, const int32_t *tids, size_t size);
static struct {
int probed;
int available;
pfn_adpf_get_mgr get_mgr;
pfn_adpf_create_sess create_sess;
pfn_adpf_update_target update_target;
pfn_adpf_report_actual report_actual;
pfn_adpf_close_sess close_sess;
pfn_adpf_set_threads set_threads;
} g_adpf_api;
static pthread_mutex_t g_adpf_mu = PTHREAD_MUTEX_INITIALIZER;
static int wl_adpf_load_api(void) {
pthread_mutex_lock(&g_adpf_mu);
if (!g_adpf_api.probed) {
g_adpf_api.probed = 1;
void *h = RTLD_DEFAULT;
g_adpf_api.get_mgr = (pfn_adpf_get_mgr)dlsym(h, "APerformanceHint_getManager");
if (!g_adpf_api.get_mgr) {
void *la = dlopen("libandroid.so", RTLD_NOW | RTLD_LOCAL);
if (la) h = la;
g_adpf_api.get_mgr = (pfn_adpf_get_mgr)dlsym(h, "APerformanceHint_getManager");
}
g_adpf_api.create_sess = (pfn_adpf_create_sess)dlsym(h, "APerformanceHint_createSession");
g_adpf_api.update_target = (pfn_adpf_update_target)dlsym(h, "APerformanceHint_updateTargetWorkDuration");
g_adpf_api.report_actual = (pfn_adpf_report_actual)dlsym(h, "APerformanceHint_reportActualWorkDuration");
g_adpf_api.close_sess = (pfn_adpf_close_sess)dlsym(h, "APerformanceHint_closeSession");
g_adpf_api.set_threads = (pfn_adpf_set_threads)dlsym(h, "APerformanceHint_setThreads");
g_adpf_api.available = (g_adpf_api.get_mgr && g_adpf_api.create_sess &&
g_adpf_api.update_target && g_adpf_api.report_actual &&
g_adpf_api.close_sess) ? 1 : 0;
}
int avail = g_adpf_api.available;
pthread_mutex_unlock(&g_adpf_mu);
return avail;
}
static void wl_adpf_close(WlAdpfHint *a) {
if (!a || !a->session) return;
if (g_adpf_api.close_sess) g_adpf_api.close_sess(a->session);
a->session = NULL;
a->tid = 0;
a->target_ns = 0;
}
static void wl_adpf_report_frame(WlAdpfHint *a, int64_t work_ns, int fps_limit) {
if (!a || a->init_failed) return;
// Ignore loading screens, pauses, and micro-duplicates (only hint during active 4..500 FPS rendering)
if (work_ns < 2000000LL || work_ns > 250000000LL) return;
if (!wl_adpf_load_api()) {
a->init_failed = 1;
return;
}
int64_t target_ns = 16666666LL; // 60 FPS target when uncapped
if (fps_limit > 0) {
int clamped = fps_limit;
if (clamped < 15) clamped = 15;
if (clamped > 144) clamped = 144;
target_ns = 1000000000LL / (int64_t)clamped;
}
int32_t tid = (int32_t)syscall(SYS_gettid);
if (tid <= 0) return;
if (!a->session) {
void *mgr = g_adpf_api.get_mgr();
if (!mgr) {
a->init_failed = 1;
return;
}
a->session = g_adpf_api.create_sess(mgr, &tid, 1u, target_ns);
if (!a->session) {
a->init_failed = 1;
return;
}
a->tid = tid;
a->target_ns = target_ns;
F4_LOGI("Vulkan ADPF PerformanceHintSession active (tid=%d, target=%.2fms)",
tid, (double)target_ns * 1e-6);
} else {
if (a->tid != tid) {
if (g_adpf_api.set_threads && g_adpf_api.set_threads(a->session, &tid, 1u) == 0) {
a->tid = tid;
}
}
if (a->target_ns != target_ns) {
if (g_adpf_api.update_target(a->session, target_ns) == 0) {
a->target_ns = target_ns;
}
}
}
int64_t clamped_work = work_ns;
if (clamped_work > 120000000LL) clamped_work = 120000000LL;
g_adpf_api.report_actual(a->session, clamped_work);
}
static void VKAPI_CALL hook_vkDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) {
DevCtx *d = NULL;
pthread_mutex_lock(&g_mu);
for (int i = 0; i < MAX_DEVICES; i++) {
if (g_devs[i] && g_devs[i]->device == device) {
d = g_devs[i];
g_devs[i] = NULL;
break;
}
}
pthread_mutex_unlock(&g_mu);
if (d) {
if (!d->pacer_only) {
wl_gpu_timer_destroy(&d->xess_timer, &d->disp);
if (d->pipe) wl_fsr4_pipe_destroy(d->pipe);
}
if (d->DestroyFence) {
for (int i = 0; i < 2; i++) {
if (d->pacer.fences[i] != VK_NULL_HANDLE) {
d->DestroyFence(device, d->pacer.fences[i], NULL);
d->pacer.fences[i] = VK_NULL_HANDLE;
}
}
}
if (d->pacer.mu_init) {
pthread_mutex_destroy(&d->pacer.mu);
d->pacer.mu_init = 0;
}
wl_adpf_close(&d->adpf);
if (d->DestroyDevice) d->DestroyDevice(device, pAllocator);
free(d);
}
}
// ---- Buffer / Memory / Image tracking + Seam Doorbell ----
static VkResult VKAPI_CALL hook_vkCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(device);
PFN_vkCreateBuffer down = d ? d->CreateBuffer : NULL;
pthread_mutex_unlock(&g_mu);
if (!down) return VK_ERROR_INITIALIZATION_FAILED;
VkResult r = down(device, pCreateInfo, pAllocator, pBuffer);
if (r == VK_SUCCESS && d && pCreateInfo && pBuffer) {
// The bridges create the mailbox with exactly STORAGE_BUFFER|TRANSFER_DST and the marker with exactly
// TRANSFER_DST (wl_seam_client.h). Matching any buffer with those bits let a game's own 8 KB storage buffers
// fill the table before the bridge's (Bright Memory: Infinite, D3D12: DLSS frames never reached the layer).
int kind = 0;
if (pCreateInfo->size == WLFSR4_MAILBOX_BYTES &&
pCreateInfo->usage == (VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT))
kind = 1;
else if (pCreateInfo->size == WLFSR4_MARKER_BYTES && pCreateInfo->usage == VK_BUFFER_USAGE_TRANSFER_DST_BIT)
kind = 2;
if (kind) {
static int full_logged = 0;
pthread_mutex_lock(&g_mu);
if (d->nbufs < MAX_TRACK_BUF) {
d->bufs[d->nbufs++] = (SeamBufEnt){*pBuffer, VK_NULL_HANDLE, NULL, pCreateInfo->size, pCreateInfo->usage, kind};
} else if (!full_logged) {
full_logged = 1;
F4_LOGW("seam buffer table full (%d): a bridge buffer is not tracked", MAX_TRACK_BUF);
}
pthread_mutex_unlock(&g_mu);
}
}
return r;
}
static void VKAPI_CALL hook_vkDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(device);
PFN_vkDestroyBuffer down = d ? d->DestroyBuffer : NULL;
if (d) {
for (int i = 0; i < d->nbufs; i++) {
if (d->bufs[i].buf == buffer) {
d->bufs[i] = d->bufs[--d->nbufs];
break;
}
}
}
pthread_mutex_unlock(&g_mu);
if (down) down(device, buffer, pAllocator);
}
static VkResult VKAPI_CALL hook_vkBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize offset) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(device);
PFN_vkBindBufferMemory down = d ? d->BindBufferMemory : NULL;
pthread_mutex_unlock(&g_mu);
if (!down) return VK_ERROR_INITIALIZATION_FAILED;
VkResult r = down(device, buffer, memory, offset);
if (r == VK_SUCCESS && d) {
pthread_mutex_lock(&g_mu);
for (int i = 0; i < d->nbufs; i++) {
if (d->bufs[i].buf == buffer) { d->bufs[i].mem = memory; break; }
}
pthread_mutex_unlock(&g_mu);
}
return r;
}
static VkResult VKAPI_CALL hook_vkMapMemory(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset,
VkDeviceSize size, VkMemoryMapFlags flags, void **ppData) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(device);
PFN_vkMapMemory down = d ? d->MapMemory : NULL;
pthread_mutex_unlock(&g_mu);
if (!down) return VK_ERROR_INITIALIZATION_FAILED;
VkResult r = down(device, memory, offset, size, flags, ppData);
if (r == VK_SUCCESS && d && ppData && *ppData) {
pthread_mutex_lock(&g_mu);
for (int i = 0; i < d->nbufs; i++) {
if (d->bufs[i].mem == memory && d->bufs[i].kind == 1) {
d->bufs[i].mapped = *ppData;
}
}
pthread_mutex_unlock(&g_mu);
}
return r;
}
static void VKAPI_CALL hook_vkUnmapMemory(VkDevice device, VkDeviceMemory memory) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(device);
PFN_vkUnmapMemory down = d ? d->UnmapMemory : NULL;
if (d) {
for (int i = 0; i < d->nbufs; i++) {
if (d->bufs[i].mem == memory) d->bufs[i].mapped = NULL;
}
}
pthread_mutex_unlock(&g_mu);
if (down) down(device, memory);
}
static VkResult VKAPI_CALL hook_vkCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkImage *pImage) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(device);
PFN_vkCreateImage down = d ? d->CreateImage : NULL;
pthread_mutex_unlock(&g_mu);
if (!down) return VK_ERROR_INITIALIZATION_FAILED;
VkResult r = down(device, pCreateInfo, pAllocator, pImage);
if (r == VK_SUCCESS && d && pCreateInfo && pImage) {
pthread_mutex_lock(&g_mu);
if (d->img_count < MAX_TRACK_IMG) {
d->imgs[d->img_count++] = (ImgEnt){*pImage, pCreateInfo->format, pCreateInfo->extent.width, pCreateInfo->extent.height, pCreateInfo->usage};
}
pthread_mutex_unlock(&g_mu);
}
return r;
}
static void VKAPI_CALL hook_vkDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(device);
PFN_vkDestroyImage down = d ? d->DestroyImage : NULL;
if (d) {
for (uint32_t i = 0; i < d->img_count; i++) {
if (d->imgs[i].img == image) {
d->imgs[i] = d->imgs[--d->img_count];
break;
}
}
}
pthread_mutex_unlock(&g_mu);
if (down) down(device, image, pAllocator);
}
static void VKAPI_CALL hook_vkCmdUpdateBuffer(VkCommandBuffer cb, VkBuffer dstBuffer,
VkDeviceSize dstOffset, VkDeviceSize dataSize, const void *pData) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(cb);
PFN_vkCmdUpdateBuffer down = d ? d->CmdUpdateBuffer : NULL;
WlFsr4Mailbox *mbox = NULL;
int is_marker = 0;
if (d && dstOffset == 0 && dataSize == sizeof(WlFsr4DoorbellPayload) && pData) {
const WlFsr4DoorbellPayload *pay = (const WlFsr4DoorbellPayload *)pData;
if (pay->magic == WLFSR4_DOORBELL_MAGIC || pay->magic == WLFSR4_HELLO_MAGIC || pay->magic == WLFSR4_TELEMETRY_MAGIC) {
for (int i = 0; i < d->nbufs; i++) {
if (d->bufs[i].buf == dstBuffer && d->bufs[i].kind == 2) is_marker = 1;
if (d->bufs[i].kind == 1 && d->bufs[i].mapped) {
WlFsr4Mailbox *cand = (WlFsr4Mailbox *)d->bufs[i].mapped;
if (cand->magic == WLFSR4_MAILBOX_MAGIC) mbox = cand;
}
}
}
}
pthread_mutex_unlock(&g_mu);
if (is_marker && mbox && d && d->pipe) {
const WlFsr4DoorbellPayload *pay = (const WlFsr4DoorbellPayload *)pData;
LiveCtrlState live_ctrl;
read_live_ctrl(&live_ctrl);
__atomic_store_n(&mbox->live_ctrl, pack_live_ctrl(&live_ctrl), __ATOMIC_RELEASE);
if (pay->magic == WLFSR4_HELLO_MAGIC) {
__atomic_store_n(&mbox->layer_caps, wl_fsr4_pipe_caps(d->pipe), __ATOMIC_RELEASE);
__atomic_store_n(&mbox->ack, pay->seq | WLFSR4_ACK_WORK_BIT, __ATOMIC_RELEASE);
__atomic_add_fetch(&mbox->ack_count, 1u, __ATOMIC_RELAXED);
F4_LOGI("Seam HELLO handshake OK (caps=0x%llx backend=%s)",
(unsigned long long)wl_fsr4_pipe_caps(d->pipe), backend_id_str(live_ctrl.backend));
return;
}
if (pay->magic == WLFSR4_TELEMETRY_MAGIC) {
// Direct XeSS 3.0 DP4a execution telemetry ping from Windows bridge.
// seq == 0: bracket start (record GPU timestamp begin before xess*Execute)
// seq > 0: bracket end (record GPU timestamp end + update live HUD status)
if (pay->seq == 0u) {
d->xess_timer_slot = wl_gpu_timer_begin(&d->xess_timer, &d->disp, cb);
return;
}
static uint64_t g_xess_dispatches = 0;
uint64_t seq = pay->seq;
WlFsr4FrameDesc frame = mbox->slots[seq % WLFSR4_SLOTS];
wl_gpu_timer_end(&d->xess_timer, &d->disp, cb, d->xess_timer_slot);
uint32_t gpu_us = d->xess_timer.last_us;
if (gpu_us == 0u) gpu_us = __atomic_load_n(&mbox->tele_gpu_us, __ATOMIC_RELAXED);
g_xess_dispatches++;
__atomic_store_n(&mbox->last_gpu_us, gpu_us, __ATOMIC_RELAXED);
__atomic_store_n(&mbox->last_htp_us, 0u, __ATOMIC_RELAXED);
__atomic_store_n(&mbox->last_status, 0u, __ATOMIC_RELAXED);
__atomic_store_n(&mbox->ack, (seq & WLFSR4_ACK_SEQ_MASK) | WLFSR4_ACK_WORK_BIT, __ATOMIC_RELEASE);
__atomic_add_fetch(&mbox->ack_count, 1u, __ATOMIC_RELAXED);
write_live_status(d->pipe, &live_ctrl, 1, 0, "XeSS3-DP4a",
frame.api_source, frame.quality_mode,
frame.render_w, frame.render_h, frame.output_w, frame.output_h,
0, gpu_us, 0u, g_xess_dispatches, "ok_xess3_dp4a", 0);
return;
}
uint64_t seq = pay->seq;
WlFsr4FrameDesc frame = mbox->slots[seq % WLFSR4_SLOTS];
WlFsrDispatchConfig dcfg;
dcfg.force_bypass = !live_ctrl.enabled;
dcfg.backend = live_ctrl.backend;
dcfg.npu_sync = live_ctrl.npu_sync;
dcfg.sharpness = live_ctrl.sharpness;
dcfg.fps_limit = live_ctrl.fps_limit;
dcfg.has_supported_npu = d->has_supported_npu;
dcfg.anti_throttle = live_ctrl.anti_throttle;
dcfg.thermal_headroom = live_ctrl.thermal_headroom;
dcfg.batt_temp_c = live_ctrl.batt_temp_c;
if (frame.flags & WLFSR4_FLAG_XESS_FALLBACK) {
dcfg.backend = WL_FSR_BACKEND_FSR3_GPU;
}
// Per-game OptiScaler Compatibility List runtime quirk overrides (cached once per process)
{
static int g_quirks_init = 0;
static int g_q_nonlinear = 0; // 1 = sRGB, 2 = PQ
static int g_q_auto_exp = 0;
static int g_q_no_disp_mv = 0;
static int g_q_avoid_fsr4 = 0;
if (!g_quirks_init) {
const char *nl = dd_upscale_env("NONLINEAR_COLOR");
if (nl && *nl) {
if (!strcasecmp(nl, "pq")) g_q_nonlinear = 2;
else if (strcasecmp(nl, "0") && strcasecmp(nl, "none") && strcasecmp(nl, "off")) g_q_nonlinear = 1;
}
const char *ae = dd_upscale_env("FORCE_AUTO_EXPOSURE");
if (ae && (*ae == '1' || !strcasecmp(ae, "true"))) g_q_auto_exp = 1;
const char *dmv = dd_upscale_env("DISABLE_DISPLAY_RES_MV");
if (dmv && (*dmv == '1' || !strcasecmp(dmv, "true"))) g_q_no_disp_mv = 1;
const char *af4 = dd_upscale_env("AVOID_FSR4");
if (af4 && (*af4 == '1' || !strcasecmp(af4, "true"))) g_q_avoid_fsr4 = 1;
g_quirks_init = 1;
if (g_q_nonlinear || g_q_auto_exp || g_q_no_disp_mv || g_q_avoid_fsr4) {
F4_LOGI("Active per-game quirks: nonlinear=%d autoExp=%d noDispMV=%d avoidFsr4=%d",
g_q_nonlinear, g_q_auto_exp, g_q_no_disp_mv, g_q_avoid_fsr4);
}
}
if (g_q_nonlinear == 1) {
frame.flags &= ~WLFSR4_FLAG_HDR;
frame.flags |= WLFSR4_FLAG_SRGB_OUT;
} else if (g_q_nonlinear == 2) {
frame.flags &= ~WLFSR4_FLAG_HDR;
}
if (g_q_auto_exp) {
frame.flags |= WLFSR4_FLAG_AUTO_EXPOSURE;
}
if (g_q_no_disp_mv) {
frame.flags &= ~WLFSR4_FLAG_DISPLAY_RES_MV;
}
if (g_q_avoid_fsr4 &&
(dcfg.backend == WL_FSR_BACKEND_AUTO ||
dcfg.backend == WL_FSR_BACKEND_FSR4_0_NPU ||
dcfg.backend == WL_FSR_BACKEND_FSR4_1_LITE_NPU ||
dcfg.backend == WL_FSR_BACKEND_FSR4_1_LITE_GPU ||
dcfg.backend == WL_FSR_BACKEND_FSR4_1_FULL_NPU ||
dcfg.backend == WL_FSR_BACKEND_FSR4_1_FULL_GPU)) {
dcfg.backend = WL_FSR_BACKEND_FSR3_GPU;
}
}
WlFsrDispatchResult dres;
memset(&dres, 0, sizeof dres);
int rc = wl_fsr4_pipe_dispatch(d->pipe, cb, &frame, &dcfg, &dres);
uint64_t ack_val = seq & WLFSR4_ACK_SEQ_MASK;
if (rc >= 1) ack_val |= WLFSR4_ACK_WORK_BIT;
if (rc == 2 && dres.npu_used) ack_val |= WLFSR4_ACK_NPU_ACTIVE_BIT;
__atomic_store_n(&mbox->layer_caps, wl_fsr4_pipe_caps(d->pipe), __ATOMIC_RELAXED);
__atomic_store_n(&mbox->npu_dispatches, dres.dispatches, __ATOMIC_RELAXED);
__atomic_store_n(&mbox->last_htp_us, dres.htp_us, __ATOMIC_RELAXED);
__atomic_store_n(&mbox->last_gpu_us, dres.gpu_us, __ATOMIC_RELAXED);
__atomic_store_n(&mbox->last_status, (uint32_t)(rc == 2 ? 0u : (rc == 1 ? 1u : 2u)), __ATOMIC_RELAXED);
__atomic_store_n(&mbox->ack, ack_val, __ATOMIC_RELEASE);
__atomic_add_fetch(&mbox->ack_count, 1u, __ATOMIC_RELAXED);
const char *tag = dres.backend_tag;
char xess_reason_buf[64];
const char *reason_out = dres.reason ? dres.reason : "ok";
if (frame.flags & WLFSR4_FLAG_XESS_FALLBACK) {
tag = "FSR3.1-GPU (XeSS fallback)";
uint32_t stg = frame.pad[0];
int32_t xrc = (int32_t)frame.pad[1];
static uint32_t g_last_xess_stg = 0u;
static int32_t g_last_xess_rc = 0;
switch (stg) {
case 1u: snprintf(xess_reason_buf, sizeof xess_reason_buf, "xess3_load_err_%d", xrc); break;
case 2u: snprintf(xess_reason_buf, sizeof xess_reason_buf, "xess3_proc_missing_%d", xrc); break;
case 3u: snprintf(xess_reason_buf, sizeof xess_reason_buf, "xess3_ctx_rc_%d", xrc); break;
case 4u: snprintf(xess_reason_buf, sizeof xess_reason_buf, "xess3_init_rc_%d", xrc); break;
case 5u: snprintf(xess_reason_buf, sizeof xess_reason_buf, "xess3_exec_rc_%d", xrc); break;
case 6u: snprintf(xess_reason_buf, sizeof xess_reason_buf, "xess3_handles_%d", xrc); break;
default: snprintf(xess_reason_buf, sizeof xess_reason_buf, "xess3_fallback_%u_%d", stg, xrc); break;
}
reason_out = xess_reason_buf;
if (stg != g_last_xess_stg || xrc != g_last_xess_rc) {
g_last_xess_stg = stg;
g_last_xess_rc = xrc;
F4_LOGW("XeSS 3.0 fallback -> FSR 3.1 GPU (%s)", xess_reason_buf);
}
}
write_live_status(d->pipe, &live_ctrl, rc >= 1 ? 1 : 0, (rc == 2 && dres.npu_used) ? 1 : 0,
tag, frame.api_source, frame.quality_mode,
frame.render_w, frame.render_h, frame.output_w, frame.output_h,
dres.preset, dres.gpu_us, dres.htp_us, dres.dispatches,
reason_out, 0);
return; // swallow synthetic doorbell so marker buffer stays untouched
}
if (down) down(cb, dstBuffer, dstOffset, dataSize, pData);
}
// ---- Reflex-style Low-Latency Early FPS Pacer ----
// Presents the completed frame immediately (zero added display delay), then:
// 1) Caps the GPU queue to max 1 frame in flight via lightweight completion fences
// (eliminating Winlator's 3-4 frame X11 PresentIdleNotify swapchain backlog!).
// 2) Sleeps the remaining frame-time slack BEFORE returning to the game so the next
// frame samples fresh controller/mouse input at the last possible instant.
static VkResult VKAPI_CALL hook_vkQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(queue);
PFN_vkQueuePresentKHR down = d ? d->QueuePresentKHR : NULL;
pthread_mutex_unlock(&g_mu);
if (!down) return VK_ERROR_DEVICE_LOST;
// 1. Hand the completed frame to the display immediately.
VkResult res = down(queue, pPresentInfo);
// 2. Heartbeat so XServerDisplayActivity hands off FPS limiting from X11 to this layer.
touch_pacer_heartbeat();
if (!d || (res != VK_SUCCESS && res != VK_SUBOPTIMAL_KHR)) {
return res;
}
// Feed real presented frame interval to Smart Automatic mode (30s rolling FPS window)
int64_t pres_now = monotonic_now_ns();
{
int64_t prev_pres = d->last_present_ns;
d->last_present_ns = pres_now;
if (prev_pres > 0 && d->pipe) {
wl_fsr4_pipe_record_present(d->pipe, pres_now - prev_pres);
}
}
LiveCtrlState ctrl;
read_live_ctrl(&ctrl);
int fps_limit = ctrl.fps_limit;
// Report active frame work duration (excluding pacer sleep!) to Android ADPF PowerHAL
if (d->adpf.frame_start_ns > 0) {
wl_adpf_report_frame(&d->adpf, pres_now - d->adpf.frame_start_ns, fps_limit);
}
if (fps_limit <= 0) {
if (d->pacer.last_fps_limit != 0 && d->pacer.mu_init) {
pthread_mutex_lock(&d->pacer.mu);
d->pacer.last_fps_limit = 0;
d->pacer.next_target_ns = 0;
pthread_mutex_unlock(&d->pacer.mu);
}
d->adpf.frame_start_ns = monotonic_now_ns();
return res;
}
if (fps_limit < 5) fps_limit = 5;
if (fps_limit > 1000) fps_limit = 1000;
int64_t sleep_target_ns = 0;
if (d->pacer.mu_init) {
pthread_mutex_lock(&d->pacer.mu);
WlReflexPacer *p = &d->pacer;
// Lazily create our 2 lightweight GPU pacing fences.
if (d->CreateFence && d->DestroyFence && d->QueueSubmit && d->WaitForFences && d->ResetFences) {
for (int i = 0; i < 2; i++) {
if (p->fences[i] == VK_NULL_HANDLE) {
VkFenceCreateInfo fci = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, NULL, 0 };
(void)d->CreateFence(d->device, &fci, NULL, &p->fences[i]);
}
}
uint32_t cur_slot = p->frame_idx & 1u;
uint32_t prev_slot = cur_slot ^ 1u;
p->frame_idx++;
// Clean cur_slot if left armed from an earlier off/on cycle
if (p->fence_armed[cur_slot] && p->fences[cur_slot] != VK_NULL_HANDLE) {
if (d->WaitForFences(d->device, 1, &p->fences[cur_slot], VK_TRUE, 200000000ULL) == VK_SUCCESS) {
d->ResetFences(d->device, 1, &p->fences[cur_slot]);
p->fence_armed[cur_slot] = 0;
}
}
// Signal cur_slot once all prior commands on this queue finish on the GPU
if (!p->fence_armed[cur_slot] && p->fences[cur_slot] != VK_NULL_HANDLE) {
if (d->QueueSubmit(queue, 0, NULL, p->fences[cur_slot]) == VK_SUCCESS) {
p->fence_armed[cur_slot] = 1;
}
}
// Wait for Frame N-1 to finish on the GPU -> guarantees MAX 1 frame in flight!
// (Preserves CPU/GPU pipelining in heavy scenes while eliminating 3-4 frame lag queues.)
if (p->fence_armed[prev_slot] && p->fences[prev_slot] != VK_NULL_HANDLE) {
if (d->WaitForFences(d->device, 1, &p->fences[prev_slot], VK_TRUE, 200000000ULL) == VK_SUCCESS) {
d->ResetFences(d->device, 1, &p->fences[prev_slot]);
p->fence_armed[prev_slot] = 0;
}
}
}
const int64_t period_ns = 1000000000LL / (int64_t)fps_limit;
int64_t now_ns = monotonic_now_ns();
if (p->last_fps_limit != fps_limit || p->next_target_ns == 0) {
p->last_fps_limit = fps_limit;
p->next_target_ns = now_ns + period_ns;
} else {
p->next_target_ns += period_ns;
if (p->next_target_ns < now_ns) {
// Frame overran target (hitch/load) — snap forward so we never catch-up burst.
p->next_target_ns = now_ns;
} else if (p->next_target_ns > now_ns + period_ns + (period_ns >> 2)) {
p->next_target_ns = now_ns + period_ns;
}
}
sleep_target_ns = p->next_target_ns;
pthread_mutex_unlock(&d->pacer.mu);
}
// 3. Precision early sleep: absolute clock_nanosleep + 1.2 ms hybrid yield spin
// to absorb Android kernel timer slack and deliver ±0.05 ms flat frame pacing.
if (sleep_target_ns > 0) {
const int64_t spin_margin_ns = 1200000LL;
int64_t now_ns = monotonic_now_ns();
if (sleep_target_ns - now_ns > spin_margin_ns) {
int64_t wake_ns = sleep_target_ns - spin_margin_ns;
struct timespec ts;
ts.tv_sec = (time_t)(wake_ns / 1000000000LL);
ts.tv_nsec = (long)(wake_ns % 1000000000LL);
while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR) {}
}
while (monotonic_now_ns() < sleep_target_ns) {
sched_yield();
}
}
d->adpf.frame_start_ns = monotonic_now_ns();
return res;
}
// ---- Standard layer enumeration & proc lookup ----
LAYER_EXPORT VkResult VKAPI_CALL vkEnumerateInstanceLayerProperties(uint32_t *pPropertyCount, VkLayerProperties *pProperties) {
if (!pPropertyCount) return VK_ERROR_INITIALIZATION_FAILED;
if (!pProperties) { *pPropertyCount = 1; return VK_SUCCESS; }
if (*pPropertyCount < 1) return VK_INCOMPLETE;
*pPropertyCount = 1;
memset(pProperties, 0, sizeof *pProperties);
snprintf(pProperties[0].layerName, sizeof pProperties[0].layerName, "%s", WL_LAYER_NAME);
snprintf(pProperties[0].description, sizeof pProperties[0].description, "%s", WL_LAYER_DESC);
pProperties[0].specVersion = VK_API_VERSION_1_3;
pProperties[0].implementationVersion = 1;
return VK_SUCCESS;
}
LAYER_EXPORT VkResult VKAPI_CALL vkEnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pPropertyCount, VkExtensionProperties *pProperties) {
(void)pProperties;
if (pLayerName && !strcmp(pLayerName, WL_LAYER_NAME)) {
if (pPropertyCount) *pPropertyCount = 0;
return VK_SUCCESS;
}
return VK_ERROR_LAYER_NOT_PRESENT;
}
LAYER_EXPORT VkResult VKAPI_CALL vkEnumerateDeviceLayerProperties(VkPhysicalDevice pd, uint32_t *pPropertyCount, VkLayerProperties *pProperties) {
(void)pd;
return vkEnumerateInstanceLayerProperties(pPropertyCount, pProperties);
}
LAYER_EXPORT VkResult VKAPI_CALL vkEnumerateDeviceExtensionProperties(VkPhysicalDevice pd, const char *pLayerName, uint32_t *pPropertyCount, VkExtensionProperties *pProperties) {
return hook_vkEnumerateDeviceExtensionProperties(pd, pLayerName, pPropertyCount, pProperties);
}
LAYER_EXPORT PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice device, const char *pName) {
if (!pName) return NULL;
if (!strcmp(pName, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
if (!strcmp(pName, "vkDestroyDevice")) return (PFN_vkVoidFunction)hook_vkDestroyDevice;
if (!strcmp(pName, "vkQueuePresentKHR")) {
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(device);
PFN_vkQueuePresentKHR real_p = d ? d->QueuePresentKHR : NULL;
PFN_vkGetDeviceProcAddr down = d ? d->next_gdpa : NULL;
pthread_mutex_unlock(&g_mu);
if (real_p) return (PFN_vkVoidFunction)hook_vkQueuePresentKHR;
return down ? down(device, pName) : NULL;
}
if (!is_pacer_only_mode()) {
if (!strcmp(pName, "vkCreateBuffer")) return (PFN_vkVoidFunction)hook_vkCreateBuffer;
if (!strcmp(pName, "vkDestroyBuffer")) return (PFN_vkVoidFunction)hook_vkDestroyBuffer;
if (!strcmp(pName, "vkBindBufferMemory")) return (PFN_vkVoidFunction)hook_vkBindBufferMemory;
if (!strcmp(pName, "vkMapMemory")) return (PFN_vkVoidFunction)hook_vkMapMemory;
if (!strcmp(pName, "vkUnmapMemory")) return (PFN_vkVoidFunction)hook_vkUnmapMemory;
if (!strcmp(pName, "vkCreateImage")) return (PFN_vkVoidFunction)hook_vkCreateImage;
if (!strcmp(pName, "vkDestroyImage")) return (PFN_vkVoidFunction)hook_vkDestroyImage;
if (!strcmp(pName, "vkCmdUpdateBuffer")) return (PFN_vkVoidFunction)hook_vkCmdUpdateBuffer;
if (spoof_dlss_enabled()) {
if (!strcmp(pName, "vkCreateCuModuleNVX")) return (PFN_vkVoidFunction)stub_vkCreateCuModuleNVX;
if (!strcmp(pName, "vkCreateCuFunctionNVX")) return (PFN_vkVoidFunction)stub_vkCreateCuFunctionNVX;
if (!strcmp(pName, "vkDestroyCuModuleNVX")) return (PFN_vkVoidFunction)stub_vkDestroyCuModuleNVX;
if (!strcmp(pName, "vkDestroyCuFunctionNVX")) return (PFN_vkVoidFunction)stub_vkDestroyCuFunctionNVX;
if (!strcmp(pName, "vkCmdCuLaunchKernelNVX")) return (PFN_vkVoidFunction)stub_vkCmdCuLaunchKernelNVX;
if (!strcmp(pName, "vkGetImageViewHandleNVX")) return (PFN_vkVoidFunction)stub_vkGetImageViewHandleNVX;
if (!strcmp(pName, "vkGetImageViewAddressNVX")) return (PFN_vkVoidFunction)stub_vkGetImageViewAddressNVX;
}
}
pthread_mutex_lock(&g_mu);
DevCtx *d = find_dev_locked(device);
PFN_vkGetDeviceProcAddr down = d ? d->next_gdpa : NULL;
pthread_mutex_unlock(&g_mu);
return down ? down(device, pName) : NULL;
}
LAYER_EXPORT PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char *pName) {
if (!pName) return NULL;
if (!strcmp(pName, "vkGetInstanceProcAddr")) return (PFN_vkVoidFunction)vkGetInstanceProcAddr;
if (!strcmp(pName, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
if (!strcmp(pName, "vkCreateInstance")) return (PFN_vkVoidFunction)hook_vkCreateInstance;
if (!strcmp(pName, "vkDestroyInstance")) return (PFN_vkVoidFunction)hook_vkDestroyInstance;
if (!strcmp(pName, "vkCreateDevice")) return (PFN_vkVoidFunction)hook_vkCreateDevice;
if (!strcmp(pName, "vkEnumerateInstanceLayerProperties")) return (PFN_vkVoidFunction)vkEnumerateInstanceLayerProperties;
if (!strcmp(pName, "vkEnumerateInstanceExtensionProperties")) return (PFN_vkVoidFunction)vkEnumerateInstanceExtensionProperties;
if (!strcmp(pName, "vkEnumerateDeviceLayerProperties")) return (PFN_vkVoidFunction)vkEnumerateDeviceLayerProperties;
// Device-level intercepted procs when queried via vkGetInstanceProcAddr
if (!strcmp(pName, "vkDestroyDevice")) return (PFN_vkVoidFunction)hook_vkDestroyDevice;
if (!strcmp(pName, "vkQueuePresentKHR")) return (PFN_vkVoidFunction)hook_vkQueuePresentKHR;
if (!is_pacer_only_mode()) {
if (!strcmp(pName, "vkGetPhysicalDeviceProperties")) return (PFN_vkVoidFunction)hook_vkGetPhysicalDeviceProperties;
if (!strcmp(pName, "vkGetPhysicalDeviceProperties2") || !strcmp(pName, "vkGetPhysicalDeviceProperties2KHR"))
return (PFN_vkVoidFunction)hook_vkGetPhysicalDeviceProperties2;
if (!strcmp(pName, "vkGetPhysicalDeviceMemoryProperties")) return (PFN_vkVoidFunction)hook_vkGetPhysicalDeviceMemoryProperties;
if (!strcmp(pName, "vkGetPhysicalDeviceMemoryProperties2") || !strcmp(pName, "vkGetPhysicalDeviceMemoryProperties2KHR"))
return (PFN_vkVoidFunction)hook_vkGetPhysicalDeviceMemoryProperties2;
if (!strcmp(pName, "vkEnumerateDeviceExtensionProperties")) return (PFN_vkVoidFunction)hook_vkEnumerateDeviceExtensionProperties;
if (!strcmp(pName, "vkCreateBuffer")) return (PFN_vkVoidFunction)hook_vkCreateBuffer;
if (!strcmp(pName, "vkDestroyBuffer")) return (PFN_vkVoidFunction)hook_vkDestroyBuffer;
if (!strcmp(pName, "vkBindBufferMemory")) return (PFN_vkVoidFunction)hook_vkBindBufferMemory;
if (!strcmp(pName, "vkMapMemory")) return (PFN_vkVoidFunction)hook_vkMapMemory;
if (!strcmp(pName, "vkUnmapMemory")) return (PFN_vkVoidFunction)hook_vkUnmapMemory;
if (!strcmp(pName, "vkCreateImage")) return (PFN_vkVoidFunction)hook_vkCreateImage;
if (!strcmp(pName, "vkDestroyImage")) return (PFN_vkVoidFunction)hook_vkDestroyImage;
if (!strcmp(pName, "vkCmdUpdateBuffer")) return (PFN_vkVoidFunction)hook_vkCmdUpdateBuffer;
if (spoof_dlss_enabled()) {
if (!strcmp(pName, "vkCreateCuModuleNVX")) return (PFN_vkVoidFunction)stub_vkCreateCuModuleNVX;
if (!strcmp(pName, "vkCreateCuFunctionNVX")) return (PFN_vkVoidFunction)stub_vkCreateCuFunctionNVX;
if (!strcmp(pName, "vkDestroyCuModuleNVX")) return (PFN_vkVoidFunction)stub_vkDestroyCuModuleNVX;
if (!strcmp(pName, "vkDestroyCuFunctionNVX")) return (PFN_vkVoidFunction)stub_vkDestroyCuFunctionNVX;
if (!strcmp(pName, "vkCmdCuLaunchKernelNVX")) return (PFN_vkVoidFunction)stub_vkCmdCuLaunchKernelNVX;
if (!strcmp(pName, "vkGetImageViewHandleNVX")) return (PFN_vkVoidFunction)stub_vkGetImageViewHandleNVX;
if (!strcmp(pName, "vkGetImageViewAddressNVX")) return (PFN_vkVoidFunction)stub_vkGetImageViewAddressNVX;
}
}
pthread_mutex_lock(&g_mu);
InstCtx *ic = find_inst_locked(instance);
PFN_vkGetInstanceProcAddr down = ic ? ic->next_gipa : NULL;
pthread_mutex_unlock(&g_mu);
return down ? down(instance, pName) : NULL;
}
LAYER_EXPORT VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(WlVkNegotiateLayerInterface *pVersionStruct) {
if (!pVersionStruct) return VK_ERROR_INITIALIZATION_FAILED;
if (pVersionStruct->loaderLayerInterfaceVersion > 2) pVersionStruct->loaderLayerInterfaceVersion = 2;
pVersionStruct->pfnGetInstanceProcAddr = vkGetInstanceProcAddr;
pVersionStruct->pfnGetDeviceProcAddr = vkGetDeviceProcAddr;
pVersionStruct->pfnGetPhysicalDeviceProcAddr = NULL;
return VK_SUCCESS;
}
__attribute__((destructor))
static void wl_layer_process_exit_guard(void) {
// Release any in-flight NPU Sync VkEvents so the GPU never waits past process exit
for (int i = 0; i < MAX_DEVICES; i++) {
if (g_devs[i] && g_devs[i]->pipe) {
wl_fsr4_pipe_release_sync_events(g_devs[i]->pipe);
}
}
}