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.
This commit is contained in:
The412Banner committed 2026-11-29 22:18:41 -05:00
1 parent 57055be6fb
commit 7972c18e50
25 files changed
+11845

No files matched your search

+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 <android/log.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define F3_TAG "WinlatorFSR3GPU"
#define F3_LOGI(...) __android_log_print(ANDROID_LOG_INFO, F3_TAG, __VA_ARGS__)
#define F3_LOGW(...) __android_log_print(ANDROID_LOG_WARN, F3_TAG, __VA_ARGS__)
#define F3_LOGE(...) __android_log_print(ANDROID_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
+944
View File
@@ -0,0 +1,944 @@
// 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 <android/log.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define F411_TAG "WinlatorFSR411FullGPU"
#define F411_LOGI(...) __android_log_print(ANDROID_LOG_INFO, F411_TAG, __VA_ARGS__)
#define F411_LOGW(...) __android_log_print(ANDROID_LOG_WARN, F411_TAG, __VA_ARGS__)
#define F411_LOGE(...) __android_log_print(ANDROID_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;
}
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
+163
View File
@@ -0,0 +1,163 @@
// 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_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
+516
View File
@@ -0,0 +1,516 @@
// Clean-room C declaration of the Qualcomm QNN HTP v81 interface subset and shared-buffer
// helpers for Winlator Ludashi FSR 4.1.1 NPU upscaling.
// 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]);
wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel,
const char *cache_rel, 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);
// ---- 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,348 @@
#!/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 struct
import hashlib
from pathlib import Path
import numpy as np
VELA_LITE_DIR = Path(r"c:\Users\omeru\OneDrive\Desktop\print\refs\vela\provider\spirv-sources\lite\converted")
WEIGHTS_BIN = Path(r"c:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr412_lite\weights.bin")
OUT_WPACK = Path(r"c:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr412_lite\fsr412_lite_i8.wpack")
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__":
build_pack()
@@ -0,0 +1,338 @@
#!/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 sys
import struct
import hashlib
from pathlib import Path
import numpy as np
FSR4_HEX_ROOT = Path(r"C:\Users\omeru\OneDrive\Desktop\print\fsr4-hexagon-master")
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__":
out_file = Path(r"C:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr4_v07_i8.wpack")
pass0_raw = Path(r"C:\Users\omeru\.gemini\antigravity\brain\d95b54c2-7fc5-4d0c-85a5-442132a5aeab\scratch\fsr4_seeds\pass0_wb.raw")
build_pack(out_file, pass0_raw)
@@ -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));
}
@@ -0,0 +1,92 @@
#version 450
// Winlator Ludashi Built-in AMD FSR 4.0.2 Post-Pass B (RCAS + inverse mu-law -> RGBA16F image)
layout(local_size_x = 8, local_size_y = 8) in;
layout(set = 0, binding = 0, std430) readonly buffer InC { uint inc[]; };
layout(set = 0, binding = 1, rgba16f) writeonly uniform image2D u_out_img;
layout(push_constant) uniform PC {
vec2 u_jitter;
vec2 u_uv_scale;
float bfloor;
float expo;
float sharp;
uint OS_W;
uint OS_H;
uint rw;
uint rh;
uint pad0;
} pc;
const float FSR_RCAS_LIMIT = 0.25 - 1.0 / 16.0;
vec3 removeMuLaw(vec3 rgb) {
return max((exp(8.51788 * rgb) - 1.0) / 150.0, vec3(0.0));
}
shared uint s_t[10 * 10 * 2];
vec3 load3T(ivec2 p, ivec2 base) {
int lx = clamp(clamp(p.x, 0, int(pc.OS_W) - 1) - base.x, 0, 9);
int ly = clamp(clamp(p.y, 0, int(pc.OS_H) - 1) - base.y, 0, 9);
uint idx = (uint(ly) * 10u + uint(lx)) * 2u;
return max(vec3(unpackHalf2x16(s_t[idx]), unpackHalf2x16(s_t[idx + 1u]).x), vec3(0.0));
}
float rcpMed(float x) {
float b = intBitsToFloat(0x7ef19fff - floatBitsToInt(x));
return b * (-b * x + 2.0);
}
void main() {
ivec2 base = ivec2(gl_WorkGroupID.xy) * 8 - 1;
for (uint i = gl_LocalInvocationIndex; i < 200u; i += 64u) {
uint t = i >> 1; uint w = i & 1u;
ivec2 p = ivec2(clamp(base.x + int(t % 10u), 0, int(pc.OS_W) - 1),
clamp(base.y + int(t / 10u), 0, int(pc.OS_H) - 1));
s_t[i] = inc[(uint(p.y) * pc.OS_W + uint(p.x)) * 2u + w];
}
barrier();
uvec2 tid = gl_GlobalInvocationID.xy;
if (tid.x >= pc.OS_W || tid.y >= pc.OS_H) return;
ivec2 sp = ivec2(tid);
vec3 b = load3T(sp + ivec2(0, -1), base);
vec3 d = load3T(sp + ivec2(-1, 0), base);
vec3 e = load3T(sp, base);
vec3 f = load3T(sp + ivec2(1, 0), base);
vec3 h = load3T(sp + ivec2(0, 1), base);
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 + 0.25 * dL + 0.25 * fL + 0.25 * 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) * rcpMed(max(lmax - lmin, 1e-9)), 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-9), 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(0.0));
vec3 hitMax = (1.0 - mx4) / (den4 - strip * vec3(1e-9));
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));
lobe *= exp2(2.0 * pc.sharp - 2.0);
lobe *= nz;
float rcpL = rcpMed(4.0 * lobe + 1.0);
vec3 pix = (lobe * (b + d + h + f) + e) * rcpL;
vec3 fc = clamp(removeMuLaw(pix) / max(pc.expo, 1e-6), vec3(0.0), vec3(64000.0));
imageStore(u_out_img, sp, vec4(fc, 1.0));
}
@@ -0,0 +1,297 @@
#version 450
// Winlator Ludashi Built-in AMD FSR 4.0.2 Pre-Pass (Pass 0 + Feature Extraction)
// Samples game color at native rw x rh, dilates motion vectors across 3x3 closest depth
// with nearest filtering + MVJittered cancellation, runs AMD FSR 4 mu-law temporal
// reprojection + Pass-0 2x2 strided conv, and emits UFIXED_POINT_8 [1, 540, 960, 16]
// (offset=-128, scale=0.014884727) into the zero-copy AHardwareBuffer for Hexagon HTP.
layout(local_size_x = 8, local_size_y = 8) in;
layout(set = 0, binding = 0) uniform sampler2D u_color; // native color (linear)
layout(set = 0, binding = 1) uniform sampler2D u_mvec; // motion vectors (NEAREST)
layout(set = 0, binding = 2, std430) readonly buffer Weights { uint wb[]; }; // 256 weight words + 8 bias words
layout(set = 0, binding = 3, std430) readonly buffer RecPrev { uint recp[]; }; // RGBA8 @ OS_W x OS_H
layout(set = 0, binding = 4, std430) readonly buffer HistIn { uint hst[]; }; // fp16 RGBA mu-law @ OS_W x OS_H
layout(set = 0, binding = 5, std430) writeonly buffer OutQ { uint outq[]; }; // UFIXED_POINT_8 [LR_H][LR_W][16]
layout(set = 0, binding = 6, std430) writeonly buffer Repj { uint rpj[]; }; // fp16 RGBA mu-law @ OS_W x OS_H
layout(set = 0, binding = 7) uniform sampler2D u_depth; // depth buffer (NEAREST)
layout(push_constant) uniform PC {
vec2 u_jitter; // subpixel jitter in native rw x rh pixels
vec2 u_mv_scale; // scale applied to raw MV texel -> normalized UV delta
vec2 u_uv_scale; // (rw / color_tex_w, rh / color_tex_h)
vec2 u_jitter_cancel; // normalized UV jitter cancellation (0 if !MV_JITTERED)
float u_reset; // 1.0 on reset / first frame
float u_expo; // pre-exposure
uint OS_W; // 1920
uint OS_H; // 1080
uint LR_W; // 960
uint LR_H; // 540
uint rw; // native render width
uint rh; // native render height
uint flags; // bit 0: has_depth, bit 1: depth_inverted, bit 2: display_res_mv
uint pad0;
} pc;
vec3 loadHistRaw(uint x, uint y) {
uint base = (y * pc.OS_W + x) * 2u;
return vec3(unpackHalf2x16(hst[base]), unpackHalf2x16(hst[base + 1u]).x);
}
vec3 loadMulr(ivec2 p, ivec2 col_lim) {
p = clamp(p, ivec2(0), col_lim);
vec3 c = max(texelFetch(u_color, p, 0).rgb, vec3(0.0)) * pc.u_expo;
return max(vec3(0.1174) * log(vec3(1.0) + 150.0 * c), vec3(0.0));
}
float catmull(float f, uint k) {
if (k == 0u) return f * (-0.5 + f * (1.0 - 0.5 * f));
if (k == 1u) return 1.0 + f * f * (-2.5 + 1.5 * f);
if (k == 2u) return f * (0.5 + f * (2.0 - 1.5 * f));
return f * f * (-0.5 + 0.5 * f);
}
vec4 upscaled_current(uvec2 tid, ivec2 col_lim) {
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 pos_f = (vec2(tid) + vec2(0.5)) * ratio - vec2(0.5) + pc.u_jitter;
ivec2 pos_i = ivec2(floor(pos_f));
vec3 acc = vec3(0.0);
float wsum = 0.0;
float wmax = 0.0;
for (int dy = 0; dy < 2; ++dy) {
for (int dx = 0; dx < 2; ++dx) {
ivec2 pi = pos_i + ivec2(dx, dy);
vec2 d = (vec2(pi) - pos_f) * inv_ratio;
float w = exp2((dot(d, d) * (-0.5 / (0.47 * 0.47))) * 1.4426950409);
vec3 c = loadMulr(pi, col_lim);
acc += c * w;
wsum += w;
wmax = max(wmax, w);
}
}
return vec4(acc / max(wsum, 1e-6), wmax);
}
void gather_prep(float hx, float hy, out float wx[4], out float wy[4]) {
float sx = hx + 0.5; float sy = hy + 0.5;
float tx0 = floor(sx - 0.5); float ty0 = floor(sy - 0.5);
float fx = sx - (tx0 + 0.5); float fy = sy - (ty0 + 0.5);
for (int j = 0; j < 4; ++j) wx[j] = catmull(fx, uint(j));
for (int k = 0; k < 4; ++k) wy[k] = catmull(fy, uint(k));
}
vec4 recAt(ivec2 p) {
uint w = recp[uint(p.y) * pc.OS_W + uint(p.x)];
return vec4(float(w & 0xffu), float((w >> 8u) & 0xffu),
float((w >> 16u) & 0xffu), float(w >> 24u)) / 255.0;
}
vec4 recBilinear(float hx, float hy) {
float rx = clamp(hx, 0.0, float(pc.OS_W - 1u));
float ry = clamp(hy, 0.0, float(pc.OS_H - 1u));
int x0 = int(floor(rx)); int y0 = int(floor(ry));
float fx = rx - float(x0); float fy = ry - float(y0);
int x1 = min(x0 + 1, int(pc.OS_W) - 1);
int y1 = min(y0 + 1, int(pc.OS_H) - 1);
vec4 top = mix(recAt(ivec2(x0, y0)), recAt(ivec2(x1, y0)), fx);
vec4 bot = mix(recAt(ivec2(x0, y1)), recAt(ivec2(x1, y1)), fx);
return mix(top, bot, fy);
}
vec2 sampleDilatedVelocity(uvec2 p) {
ivec2 mv_sz = textureSize(u_mvec, 0);
ivec2 dep_sz = textureSize(u_depth, 0);
ivec2 r_lim = ivec2(int(pc.rw) - 1, int(pc.rh) - 1);
ivec2 np = clamp(ivec2((vec2(p) + vec2(0.5)) * vec2(pc.rw, pc.rh) / vec2(pc.LR_W, pc.LR_H)), ivec2(0), r_lim);
ivec2 best_q = np;
bool has_depth = (pc.flags & 1u) != 0u && dep_sz.x > 1 && dep_sz.y > 1;
bool dep_inv = (pc.flags & 2u) != 0u;
if (has_depth) {
ivec2 d_lim = min(r_lim, dep_sz - ivec2(1));
ivec2 dp_c = clamp(np, ivec2(0), d_lim);
float best_d = texelFetch(u_depth, dp_c, 0).r;
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;
}
}
}
}
ivec2 mv_q;
if ((pc.flags & 4u) != 0u) {
// Display-resolution MVs
vec2 uv_n = (vec2(best_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(best_q, ivec2(0), mv_lim);
}
vec2 raw = texelFetch(u_mvec, mv_q, 0).xy;
return raw * pc.u_mv_scale + pc.u_jitter_cancel;
}
void feat_px(uvec2 tid, ivec2 col_lim, vec2 vel, bool mv_ok, bool onscreen, vec3 history,
out uint o0, out uint o1, out uint o2, out uint o3) {
vec4 upsc = upscaled_current(tid, col_lim);
vec3 cur = upsc.rgb;
float center_w = upsc.a;
float hx = float(tid.x) + vel.x * float(pc.OS_W);
float hy = float(tid.y) + vel.y * float(pc.OS_H);
vec4 rec = vec4(0.0);
if (pc.u_reset > 0.5) {
history = cur;
} else if (onscreen) {
rec = recBilinear(hx, hy);
}
float tsw = 0.1 * center_w;
vec3 rect = (pc.u_reset > 0.5) ? cur
: (mv_ok && onscreen ? (tsw * cur + (1.0 - tsw) * history) : cur);
float yin = cur.r * 0.2126 + cur.g * 0.7152 + cur.b * 0.0722;
float yh = rect.r * 0.2126 + rect.g * 0.7152 + rect.b * 0.0722;
float cb_in = (cur.b - yin) / 1.8556; float cr_in = (cur.r - yin) / 1.5748;
float cb_h = (rect.b - yh) / 1.8556; float cr_h = (rect.r - yh) / 1.5748;
float dist = sqrt((cb_in - cb_h) * (cb_in - cb_h) + (cr_in - cr_h) * (cr_in - cr_h) + 1e-6);
float n0 = 2.0 * yin - 1.0;
float n1 = 2.0 * yh - 1.0;
vec4 rn = 2.0 * rec - 1.0;
o0 = packHalf2x16(vec2(n0, n1));
o1 = packHalf2x16(vec2(dist, rn.x));
o2 = packHalf2x16(vec2(rn.y, rn.z));
o3 = packHalf2x16(vec2(rn.w, 0.0));
uint rbase = (tid.y * pc.OS_W + tid.x) * 2u;
rpj[rbase] = packHalf2x16(rect.xy);
rpj[rbase + 1u] = packHalf2x16(vec2(rect.z, 1.0));
}
vec2 w2(uint f, uint ky, uint kx, uint c2) {
return unpackHalf2x16(wb[f * 16u + (ky * 2u + kx) * 4u + c2]);
}
float biasAt(uint f) {
vec2 v = unpackHalf2x16(wb[256u + (f >> 1u)]);
return (f & 1u) == 0u ? v.x : v.y;
}
uint pack4u(int b0, int b1, int b2, int b3) {
return (uint(b0) & 0xffu)
| ((uint(b1) & 0xffu) << 8u)
| ((uint(b2) & 0xffu) << 16u)
| ((uint(b3) & 0xffu) << 24u);
}
// UFIXED_POINT_8 with offset = -128, scale = S_IN = 0.014884727075695992
const float RCP_S_IN = 67.18295843885989;
int quant1u(float acc, float bias) {
float v = (acc + bias) * RCP_S_IN + 128.0;
return int(clamp(roundEven(v), 0.0, 255.0));
}
void main() {
uvec2 p = gl_GlobalInvocationID.xy;
if (p.x >= pc.LR_W || p.y >= pc.LR_H) return;
ivec2 col_sz = textureSize(u_color, 0);
ivec2 col_lim = min(ivec2(int(pc.rw) - 1, int(pc.rh) - 1), col_sz - ivec2(1));
uint x0 = 2u * p.x, x1 = 2u * p.x + 1u;
uint y0 = 2u * p.y, y1 = 2u * p.y + 1u;
vec2 vel = sampleDilatedVelocity(p);
bool mv_ok = !isnan(vel.x) && !isnan(vel.y) && !isinf(vel.x) && !isinf(vel.y)
&& abs(vel.x) < 4.0 && abs(vel.y) < 4.0;
vec3 histA = vec3(0.0), histB = vec3(0.0), histC = vec3(0.0), histD = vec3(0.0);
bool onsA = false, onsB = false, onsC = false, onsD = false;
if (pc.u_reset <= 0.5 && mv_ok) {
float hxA = float(x0) + vel.x * float(pc.OS_W);
float hyA = float(y0) + vel.y * float(pc.OS_H);
float hxB = float(x1) + vel.x * float(pc.OS_W);
float hyB = float(y0) + vel.y * float(pc.OS_H);
float hxC = float(x0) + vel.x * float(pc.OS_W);
float hyC = float(y1) + vel.y * float(pc.OS_H);
float hxD = float(x1) + vel.x * float(pc.OS_W);
float hyD = float(y1) + vel.y * float(pc.OS_H);
onsA = hxA >= 0.0 && hxA <= float(pc.OS_W - 1u) && hyA >= 0.0 && hyA <= float(pc.OS_H - 1u);
onsB = hxB >= 0.0 && hxB <= float(pc.OS_W - 1u) && hyB >= 0.0 && hyB <= float(pc.OS_H - 1u);
onsC = hxC >= 0.0 && hxC <= float(pc.OS_W - 1u) && hyC >= 0.0 && hyC <= float(pc.OS_H - 1u);
onsD = hxD >= 0.0 && hxD <= float(pc.OS_W - 1u) && hyD >= 0.0 && hyD <= float(pc.OS_H - 1u);
if (onsA || onsB || onsC || onsD) {
float wxA[4], wyA[4], wxB[4], wyB[4], wxC[4], wyC[4], wxD[4], wyD[4];
gather_prep(hxA, hyA, wxA, wyA);
gather_prep(hxB, hyB, wxB, wyB);
gather_prep(hxC, hyC, wxC, wyC);
gather_prep(hxD, hyD, wxD, wyD);
int bx = int(floor(hxA)) - 1;
int by = int(floor(hyA)) - 1;
vec3 hA = vec3(0.0), hB = vec3(0.0), hC = vec3(0.0), hD = vec3(0.0);
float tA = 0.0, tB = 0.0, tC = 0.0, tD = 0.0;
for (int r = 0; r < 5; ++r) {
uint cy = uint(clamp(by + r, 0, int(pc.OS_H) - 1));
for (int c = 0; c < 5; ++c) {
vec3 v = loadHistRaw(uint(clamp(bx + c, 0, int(pc.OS_W) - 1)), cy);
if (r < 4 && c < 4 && onsA) { float w = wyA[r] * wxA[c]; tA += w; hA += v * w; }
if (r < 4 && c > 0 && onsB) { float w = wyB[r] * wxB[c - 1]; tB += w; hB += v * w; }
if (r > 0 && c < 4 && onsC) { float w = wyC[r - 1] * wxC[c]; tC += w; hC += v * w; }
if (r > 0 && c > 0 && onsD) { float w = wyD[r - 1] * wxD[c - 1]; tD += w; hD += v * w; }
}
}
if (onsA && abs(tA) > 1e-6) histA = max(hA / tA, vec3(0.0));
if (onsB && abs(tB) > 1e-6) histB = max(hB / tB, vec3(0.0));
if (onsC && abs(tC) > 1e-6) histC = max(hC / tC, vec3(0.0));
if (onsD && abs(tD) > 1e-6) histD = max(hD / tD, vec3(0.0));
}
}
uint A0, A1, A2, A3, B0, B1, B2, B3, C0, C1, C2, C3, D0, D1, D2, D3;
feat_px(uvec2(x0, y0), col_lim, vel, mv_ok, onsA, histA, A0, A1, A2, A3);
feat_px(uvec2(x1, y0), col_lim, vel, mv_ok, onsB, histB, B0, B1, B2, B3);
feat_px(uvec2(x0, y1), col_lim, vel, mv_ok, onsC, histC, C0, C1, C2, C3);
feat_px(uvec2(x1, y1), col_lim, vel, mv_ok, onsD, histD, D0, D1, D2, D3);
vec2 c00[4], c10[4], c01[4], c11[4];
c00[0] = unpackHalf2x16(A0); c00[1] = unpackHalf2x16(A1);
c00[2] = unpackHalf2x16(A2); c00[3] = unpackHalf2x16(A3);
c10[0] = unpackHalf2x16(B0); c10[1] = unpackHalf2x16(B1);
c10[2] = unpackHalf2x16(B2); c10[3] = unpackHalf2x16(B3);
c01[0] = unpackHalf2x16(C0); c01[1] = unpackHalf2x16(C1);
c01[2] = unpackHalf2x16(C2); c01[3] = unpackHalf2x16(C3);
c11[0] = unpackHalf2x16(D0); c11[1] = unpackHalf2x16(D1);
c11[2] = unpackHalf2x16(D2); c11[3] = unpackHalf2x16(D3);
int q[16];
for (uint f = 0u; f < 16u; ++f) {
vec2 acc = vec2(0.0);
acc += w2(f, 0u, 0u, 0u) * c00[0] + w2(f, 0u, 0u, 1u) * c00[1]
+ w2(f, 0u, 0u, 2u) * c00[2] + w2(f, 0u, 0u, 3u) * c00[3];
acc += w2(f, 1u, 0u, 0u) * c10[0] + w2(f, 1u, 0u, 1u) * c10[1]
+ w2(f, 1u, 0u, 2u) * c10[2] + w2(f, 1u, 0u, 3u) * c10[3];
acc += w2(f, 0u, 1u, 0u) * c01[0] + w2(f, 0u, 1u, 1u) * c01[1]
+ w2(f, 0u, 1u, 2u) * c01[2] + w2(f, 0u, 1u, 3u) * c01[3];
acc += w2(f, 1u, 1u, 0u) * c11[0] + w2(f, 1u, 1u, 1u) * c11[1]
+ w2(f, 1u, 1u, 2u) * c11[2] + w2(f, 1u, 1u, 3u) * c11[3];
q[f] = quant1u(acc.x + acc.y, biasAt(f));
}
uint base = (p.y * pc.LR_W + p.x) * 4u;
outq[base + 0u] = pack4u(q[0], q[1], q[2], q[3]);
outq[base + 1u] = pack4u(q[4], q[5], q[6], q[7]);
outq[base + 2u] = pack4u(q[8], q[9], q[10], q[11]);
outq[base + 3u] = pack4u(q[12], q[13], q[14], q[15]);
}
@@ -0,0 +1,14 @@
#version 450
// Pack AMD FSR 4.1.2 Lite scratch (+0, 962x542x16 int8 with 1-px halo) ->
// dense 960x540x16 uint8 (int8 ^ 0x80) in zero-copy AHB slot for Hexagon HTP v81.
layout(local_size_x = 64) in;
layout(set = 0, binding = 0, std430) readonly buffer ScratchBuf { uvec4 q[]; } scr;
layout(set = 0, binding = 1, std430) writeonly buffer AhbBuf { uvec4 q[]; } ahb;
layout(push_constant) uniform PC { uint base_q; uint p1; uint p2; uint p3; } pc;
void main() {
uint p = gl_GlobalInvocationID.x;
if (p >= 518400u) return;
uint x = p % 960u;
uint y = p / 960u;
ahb.q[pc.base_q + p] = scr.q[(x + 1u) + 962u * (y + 1u)] ^ uvec4(0x80808080u);
}
@@ -0,0 +1,19 @@
#version 450
// Unpack Hexagon HTP v81 output (dense 960x540x16 uint8 = int8 ^ 0x80) ->
// AMD FSR 4.1.2 Lite scratch (+16684928 B = q[1042808], 962x542x16 int8 with zero halo) for K1 (0009.spv).
layout(local_size_x = 64) in;
layout(set = 0, binding = 0, std430) writeonly buffer ScratchBuf { uvec4 q[]; } scr;
layout(set = 0, binding = 1, std430) readonly buffer AhbBuf { uvec4 q[]; } ahb;
layout(push_constant) uniform PC { uint base_q; uint p1; uint p2; uint p3; } pc;
void main() {
uint p = gl_GlobalInvocationID.x;
if (p >= 521404u) return;
uint hx = p % 962u;
uint hy = p / 962u;
uvec4 v = uvec4(0u);
if (hx >= 1u && hx <= 960u && hy >= 1u && hy <= 540u) {
uint idx = (hy - 1u) * 960u + (hx - 1u);
v = ahb.q[pc.base_q + idx] ^ uvec4(0x80808080u);
}
scr.q[1042808u + p] = v;
}