mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0657930e68 | ||
|
|
bfc5417dfa | ||
|
|
e213e47fcd | ||
|
|
7137f80780 | ||
|
|
173dcbbcfe | ||
|
|
dc76d1a65f | ||
|
|
69f4d4addb | ||
|
|
babf97222f | ||
|
|
0cde5ce565 | ||
|
|
898b637648 | ||
|
|
18102ef58f | ||
|
|
4f06ea814f | ||
|
|
35fc6e3d69 | ||
|
|
13968e722f | ||
|
|
18469cbc4c | ||
|
|
0cb6afbff6 | ||
|
|
e422ab68a7 | ||
|
|
04a67aa765 | ||
|
|
e5d7bddfdb | ||
|
|
772f83cf95 | ||
|
|
d47ed325fd | ||
|
|
d83c18417d | ||
|
|
bb5c53a793 | ||
|
|
73442ad3e0 | ||
|
|
bba89b7c11 | ||
|
|
ffe46fe53b | ||
|
|
4626cb309d | ||
|
|
0750f2d0f5 | ||
|
|
aa4997b306 | ||
|
|
7aa54ab9c7 | ||
|
|
d32433d995 | ||
|
|
85bfb69306 | ||
|
|
83de9e38b4 | ||
|
|
a23f402724 | ||
|
|
aabacc106d | ||
|
|
537b52585a | ||
|
|
379198e4e6 | ||
|
|
971b74b594 | ||
|
|
9b21ea2e90 | ||
|
|
1a621bcffa | ||
|
|
01d7338610 | ||
|
|
74ece6c854 | ||
|
|
db5a03039e | ||
|
|
94754fea04 | ||
|
|
c18aa23ac2 | ||
|
|
94bcfca5c0 | ||
|
|
b9a535170e | ||
|
|
b6457b0cf7 | ||
|
|
217817fa83 | ||
|
|
d78ff7ddc7 | ||
|
|
f2309c8a09 | ||
|
|
491106ac3c | ||
|
|
c0af05f103 | ||
|
|
02d57b2a78 | ||
|
|
b4210b5a67 | ||
|
|
63311bdeaf | ||
|
|
7972c18e50 |
No files matched your search
@@ -325,6 +325,9 @@ jobs:
|
||||
- name: Build the DiRT 3 / DiRT Showdown ws2_32 stand-in
|
||||
run: python3 tools/components/prepare.py dirt-ws2
|
||||
|
||||
- name: Build the DLSS / FSR / XeSS upscale bridges
|
||||
run: python3 tools/components/prepare.py upscale-bridges
|
||||
|
||||
- name: Cache graphics driver inputs
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
|
||||
@@ -55,7 +55,7 @@ jobs:
|
||||
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
|
||||
}
|
||||
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
|
||||
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic; do
|
||||
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic upscale; do
|
||||
file="packs/$name.tar.zst"
|
||||
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
|
||||
sha=$(sha256sum "$file" | cut -d' ' -f1)
|
||||
|
||||
+2
-2
@@ -95,7 +95,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine
|
||||
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
|
||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name ->
|
||||
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic', 'upscale'].collectEntries { name ->
|
||||
def pack = file("build/packs/${name}.tar.zst")
|
||||
if (!pack.isFile()) {
|
||||
if (ciBuild && !unitTestsOnly) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
|
||||
@@ -207,7 +207,7 @@ android {
|
||||
}
|
||||
|
||||
androidResources {
|
||||
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>droiddeck-ubisoft:<dir>droiddeck-rockstar:<dir>droiddeck-dirt:<dir>droiddeck-epic:<dir>directaudio:<dir>hybris'
|
||||
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>droiddeck-ubisoft:<dir>droiddeck-rockstar:<dir>droiddeck-dirt:<dir>droiddeck-epic:<dir>droiddeck-upscale:<dir>directaudio:<dir>hybris'
|
||||
}
|
||||
|
||||
packagingOptions {
|
||||
|
||||
@@ -41,6 +41,7 @@ message(STATUS "dd-fg chain: win-fg ${DDFG_UPSTREAM} (src ${DDFG_CHAIN_HASH})")
|
||||
|
||||
add_subdirectory(waylandcomp)
|
||||
add_subdirectory(questxr)
|
||||
add_subdirectory(../../../../tools/upscale/layer upscale_layer)
|
||||
add_library(sdnative SHARED sdnative/sdnative.c)
|
||||
target_link_libraries(sdnative log)
|
||||
|
||||
|
||||
@@ -175,6 +175,9 @@ internal class AddonPack(
|
||||
val ROCKSTAR = AddonPack("rockstar", BuildConfig.PACK_ROCKSTAR_SHA256, BuildConfig.PACK_ROCKSTAR_SIZE,
|
||||
listOf("Launcher32.exe", "Launcher64.exe"))
|
||||
val DIRT = AddonPack("dirt", BuildConfig.PACK_DIRT_SHA256, BuildConfig.PACK_DIRT_SIZE, listOf("ws2_32.dll"))
|
||||
/** The in-game upscaler's bridge DLLs (tools/upscale/bridges), staged by UpscaleComponent. */
|
||||
val UPSCALE = AddonPack("upscale", BuildConfig.PACK_UPSCALE_SHA256, BuildConfig.PACK_UPSCALE_SIZE,
|
||||
listOf("bridges/x86_64-windows/libxess.dll", "bridges/x86_64-windows/nvngx.dll"))
|
||||
val EPIC = AddonPack("epic", BuildConfig.PACK_EPIC_SHA256, BuildConfig.PACK_EPIC_SIZE, listOf("EpicGamesLauncher.exe"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
/**
|
||||
* The in-game upscaler (tools/upscale): bridge DLLs stand in for a game's own DLSS / FidelityFX / FSR 2/3 /
|
||||
* XeSS DLLs and hand each frame to the VK_LAYER_DROIDDECK_upscale layer, which runs FSR 4 (GPU or Hexagon NPU),
|
||||
* XeSS 3 DP4a or a basic temporal upscaler in its place. Ported from Winlator-NeuralScale
|
||||
* (michaelisomer-cyber, GPL-3.0, a fork of StevenMXZ/Winlator-Ludashi).
|
||||
*
|
||||
* Per game it is a few entries of the game environment; droiddeck-game-env turns them into the DLL overrides,
|
||||
* the bridge folder, the layer switch and the files the layer reads.
|
||||
*/
|
||||
object GameUpscaler {
|
||||
const val MODE = "DROIDDECK_UPSCALE_MODE"
|
||||
const val ENGINE = "DROIDDECK_UPSCALE_ENGINE"
|
||||
const val SHARPNESS = "DROIDDECK_UPSCALE_SHARPNESS"
|
||||
const val NPU_SYNC = "DROIDDECK_UPSCALE_NPU_SYNC"
|
||||
const val SIGFIX = "DROIDDECK_UPSCALE_SIGFIX"
|
||||
|
||||
val keys = listOf(MODE, ENGINE, SHARPNESS, NPU_SYNC, SIGFIX)
|
||||
|
||||
/** Which of the game's upscalers are replaced, and what GPU the game is shown. */
|
||||
enum class Mode(val id: String) {
|
||||
/** FidelityFX (FSR 4 API), FSR 2/3 and XeSS games; the real GPU is reported. */
|
||||
FSR_XESS("fsr"),
|
||||
/** DLSS games: also nvngx + nvapi64, and the game sees an RTX 2060. */
|
||||
DLSS("dlss"),
|
||||
/** Games whose FSR 4 path wants an RDNA 4 card: the game sees a Radeon RX 9070 XT, shader model 6.8. */
|
||||
NATIVE_FSR4("native");
|
||||
|
||||
companion object {
|
||||
fun byId(id: String?): Mode? = entries.firstOrNull { it.id == id?.trim()?.lowercase() }
|
||||
}
|
||||
}
|
||||
|
||||
/** What runs in the game's upscaler's place. Ids are the layer's backend names (fsr4_layer.c parse_backend_str). */
|
||||
enum class Engine(val id: String, val npu: Boolean) {
|
||||
FSR4_LITE_GPU("fsr4_1_lite_gpu", false),
|
||||
FSR4_FULL_GPU("fsr4_1_full_gpu", false),
|
||||
XESS("xess3_gpu", false),
|
||||
BASIC("fsr3_gpu", false),
|
||||
SGSR2("sgsr2_gpu", false),
|
||||
FSR4_NPU("fsr4_1_full_npu", true),
|
||||
FSR4_LITE_NPU("fsr4_1_lite_npu", true);
|
||||
|
||||
companion object {
|
||||
/** Saved before full FSR 4.1 replaced FSR 4.0 on the NPU (NeuralScale r5). */
|
||||
private const val LEGACY_FSR4_NPU = "fsr4_0_npu"
|
||||
|
||||
fun byId(id: String?): Engine? {
|
||||
val key = id?.trim()?.lowercase()
|
||||
return if (key == LEGACY_FSR4_NPU) FSR4_NPU else entries.firstOrNull { it.id == key }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val DEFAULT_ENGINE = Engine.FSR4_LITE_GPU
|
||||
const val DEFAULT_SHARPNESS = 55
|
||||
val sharpnessSteps = listOf(0, 25, 40, 55, 70, 85, 100)
|
||||
|
||||
data class Choice(
|
||||
val mode: Mode,
|
||||
val engine: Engine = DEFAULT_ENGINE,
|
||||
val sharpness: Int = DEFAULT_SHARPNESS,
|
||||
val npuSync: Boolean = false,
|
||||
val signatureFix: Boolean = true,
|
||||
)
|
||||
|
||||
fun choice(config: GameEnvironment.Config, scope: String): Choice? {
|
||||
if (scope.isEmpty()) return null
|
||||
val entries = config.games[scope].orEmpty()
|
||||
val mode = Mode.byId(entries[MODE]) ?: return null
|
||||
return Choice(
|
||||
mode = mode,
|
||||
engine = Engine.byId(entries[ENGINE]) ?: DEFAULT_ENGINE,
|
||||
sharpness = entries[SHARPNESS]?.toIntOrNull()?.coerceIn(0, 100) ?: DEFAULT_SHARPNESS,
|
||||
npuSync = entries[NPU_SYNC] == "1",
|
||||
signatureFix = entries[SIGFIX] != "0",
|
||||
)
|
||||
}
|
||||
|
||||
fun entries(choice: Choice?): Map<String, String> = if (choice == null) emptyMap() else buildMap {
|
||||
put(MODE, choice.mode.id)
|
||||
put(ENGINE, choice.engine.id)
|
||||
put(SHARPNESS, choice.sharpness.coerceIn(0, 100).toString())
|
||||
if (choice.npuSync) put(NPU_SYNC, "1")
|
||||
// DLSS games need NGX to accept the bridge DLLs; on unless the player switched it off (stored as "0").
|
||||
if (choice.mode == Mode.DLSS) put(SIGFIX, if (choice.signatureFix) "1" else "0")
|
||||
}
|
||||
|
||||
fun withChoice(config: GameEnvironment.Config, scope: String, choice: Choice?): GameEnvironment.Config {
|
||||
require(scope.isNotEmpty() && GameEnvironment.validScope(scope))
|
||||
val kept = config.entries(scope).filterKeys { it !in keys }
|
||||
return config.withEntries(scope, kept + entries(choice))
|
||||
}
|
||||
|
||||
/** NPU engines on a device without a usable Hexagon NPU run the matching GPU engine instead. */
|
||||
fun effectiveEngine(engine: Engine, npuAvailable: Boolean): Engine = when {
|
||||
!engine.npu || npuAvailable -> engine
|
||||
engine == Engine.FSR4_NPU -> Engine.FSR4_FULL_GPU
|
||||
else -> Engine.FSR4_LITE_GPU
|
||||
}
|
||||
|
||||
/** The control file the layer polls (fsr4_layer.c read_live_ctrl): backend, sharpness 0..1, NPU sync, on/off. */
|
||||
fun controlText(engine: Engine, sharpness: Int, npuSync: Boolean, enabled: Boolean): String =
|
||||
"enabled=${if (enabled) 1 else 0}\nbackend=${engine.id}\nsharpness=" +
|
||||
String.format(java.util.Locale.ROOT, "%.2f", sharpness.coerceIn(0, 100) / 100f) +
|
||||
"\nnpu_sync=${if (npuSync) 1 else 0}\n"
|
||||
|
||||
/** One status file the layer writes (fsr4_layer.c write_live_status): key=value lines. */
|
||||
data class Status(
|
||||
val active: Boolean,
|
||||
val npu: Boolean,
|
||||
val backendTag: String,
|
||||
val render: String,
|
||||
val output: String,
|
||||
val gpuMs: Float,
|
||||
val npuMs: Float,
|
||||
val reason: String,
|
||||
val timestampMs: Long,
|
||||
)
|
||||
|
||||
fun parseStatus(text: String): Status? {
|
||||
val values = text.lineSequence().mapNotNull { line ->
|
||||
val eq = line.indexOf('=')
|
||||
if (eq <= 0) null else line.substring(0, eq).trim() to line.substring(eq + 1).trim()
|
||||
}.toMap()
|
||||
if (values["layer"] != "1") return null
|
||||
return Status(
|
||||
active = values["active"] == "1",
|
||||
npu = values["npu"] == "1",
|
||||
backendTag = values["backend_tag"].orEmpty().ifEmpty { values["backend"].orEmpty() },
|
||||
render = values["render"].orEmpty(),
|
||||
output = values["output"].orEmpty(),
|
||||
gpuMs = (values["gpu_us"]?.toLongOrNull() ?: 0L) / 1000f,
|
||||
npuMs = (values["htp_us"]?.toLongOrNull() ?: 0L) / 1000f,
|
||||
reason = values["reason"].orEmpty(),
|
||||
timestampMs = values["ts_ms"]?.toLongOrNull() ?: 0L,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ internal object DroidDeckHudConfig {
|
||||
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "0", "showLow001" to "0",
|
||||
"showEngine" to "1", "showRenderer" to "1",
|
||||
"showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1",
|
||||
"showProton" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
|
||||
"showProton" to "1", "showUpscale" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
|
||||
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
|
||||
)
|
||||
|
||||
|
||||
@@ -287,6 +287,9 @@ class DroidDeckHudHost(context: Context) {
|
||||
proton = protonName(pid) ?: proton
|
||||
}
|
||||
hud.setWineVersion(proton)
|
||||
hud.setUpscale(com.droiddeck.launcher.session.UpscaleComponent.status(context)?.takeIf { it.active }?.let {
|
||||
it.backendTag + " " + String.format(java.util.Locale.ROOT, "%.1fms", if (it.npu) it.npuMs else it.gpuMs)
|
||||
})
|
||||
hud.setPresentedFps(presentedFps())
|
||||
}
|
||||
|
||||
|
||||
@@ -74,12 +74,13 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
FULL to listOf(
|
||||
"showFPS", "showFPSGraph", "showGpuModel", "showDisplay", "showHdr", "showGPULoad", "showGpuTemp",
|
||||
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||
"showPower", "showLatency", "showAvg", "showLow1", "showLow01", "showLow001",
|
||||
"showPower", "showLatency", "showAvg", "showLow1", "showLow01", "showLow001", "showUpscale",
|
||||
),
|
||||
TILES to listOf(
|
||||
"showFPS", "showFPSGraph", "showLatency", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
|
||||
"showVram", "showRAM", "showEngine", "showDisplay", "showHdr", "showAvg", "showLow1",
|
||||
"showLow01", "showLow001", "showGpuModel", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower",
|
||||
"showUpscale",
|
||||
),
|
||||
PILL to listOf(
|
||||
"showFPS", "showFPSGraph", "showGpuModel", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
|
||||
|
||||
@@ -114,6 +114,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private var gpuModel = ""
|
||||
private var gpuSpoofName = ""
|
||||
private var wineVersion = ""
|
||||
private var upscaleText = ""
|
||||
private var graphicsWrapper = ""
|
||||
private var dxvkVersion = ""
|
||||
private var vkd3dVersion = ""
|
||||
@@ -283,6 +284,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
fun setEngineLabel(s: String?) { if ((s ?: "") != engineLabel) { engineLabel = s ?: ""; post { rebuildAndInvalidate() } } }
|
||||
fun setGpuModel(s: String?) { if ((s ?: "") != gpuModel) { gpuModel = s ?: ""; post { rebuildAndInvalidate() } } }
|
||||
fun setWineVersion(s: String?) { if ((s ?: "") != wineVersion) { wineVersion = s ?: ""; post { rebuildAndInvalidate() } } }
|
||||
/** The in-game upscaler's backend and its time per frame (empty: not running). */
|
||||
fun setUpscale(s: String?) { if ((s ?: "") != upscaleText) { upscaleText = s ?: ""; post { rebuildAndInvalidate() } } }
|
||||
|
||||
fun setResolution(s: String?) { resolution = s ?: "" }
|
||||
|
||||
@@ -778,6 +781,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
"showHdr" -> "HDR" to colHdr
|
||||
"showResolution" -> "RES" to colDim
|
||||
"showProton" -> "PROTON" to colVram
|
||||
"showUpscale" -> "UPSCALE" to colFps
|
||||
"showSession" -> "TIME" to colDim
|
||||
else -> key.removePrefix("show") to colDim
|
||||
}
|
||||
@@ -815,6 +819,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
"showHdr" -> if (showHdrLine()) hdrValue(valuePx) else listOf(Span("off", colDim, valuePx))
|
||||
"showResolution" -> listOf(Span(resolutionString(), colValue, valuePx))
|
||||
"showProton" -> listOf(Span(wineVersion.ifBlank { "—" }, colVram, valuePx))
|
||||
"showUpscale" -> listOf(Span(upscaleText.ifBlank { "—" }, colValue, valuePx))
|
||||
"showSession" -> listOf(Span(elapsedString(), colValue, valuePx))
|
||||
else -> listOf(Span("—", colDim, valuePx))
|
||||
}
|
||||
|
||||
@@ -98,6 +98,13 @@ object GameEnvironmentStore {
|
||||
return config
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setGameUpscaler(context: Context, scope: String, choice: com.droiddeck.launcher.core.GameUpscaler.Choice?): GameEnvironment.Config {
|
||||
val config = com.droiddeck.launcher.core.GameUpscaler.withChoice(read(context), scope, choice)
|
||||
save(context, config)
|
||||
return config
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setDefault(context: Context, scope: String, name: String, value: String): Boolean {
|
||||
val config = read(context)
|
||||
|
||||
@@ -259,6 +259,11 @@ object SessionFiles {
|
||||
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
|
||||
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_gpu_load.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_gpu_load.json",
|
||||
)
|
||||
// The in-game upscaler's layer for PRoot games (UpscaleComponent; off unless DROIDDECK_UPSCALE=1).
|
||||
val upscaleLayer = listOf(
|
||||
"usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so" to "usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so",
|
||||
"usr/local/lib/droiddeck-upscale-layer/VK_LAYER_DROIDDECK_upscale.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_upscale.json",
|
||||
)
|
||||
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
|
||||
listOf("libddsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
|
||||
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
|
||||
@@ -281,7 +286,7 @@ object SessionFiles {
|
||||
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
|
||||
"usr/local/share/licenses/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
|
||||
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + upscaleLayer + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -1137,6 +1137,8 @@ class SessionService : Service() {
|
||||
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
|
||||
guest.add("MESA_DISK_CACHE_DATABASE=1")
|
||||
guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this)))
|
||||
guest.addAll(UpscaleComponent.guestEnv(this))
|
||||
UpscaleComponent.prepare(this)
|
||||
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("DD_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
||||
SessionPaths.current()?.let { SessionArtifacts.markRpcs3Log(it, LinuxRuntime.rootDir(this)) }
|
||||
|
||||
@@ -0,0 +1,444 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.core.GameUpscaler
|
||||
import com.droiddeck.launcher.gpu.SocNames
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
|
||||
/**
|
||||
* The in-game upscaler's files on the device (see [GameUpscaler]):
|
||||
* - the bridge DLLs, built from tools/upscale/bridges, come in the "upscale" add-on pack;
|
||||
* - the Vulkan layer is in the APK (bionic games) and in the Linux runtime (PRoot games);
|
||||
* - the parts with no source to build from (AMD's FSR 4 SPIR-V and weights, Intel's XeSS 3 runtime, Qualcomm's
|
||||
* QNN libraries for the Hexagon NPU) are fetched from Winlator-NeuralScale at a pinned commit and checked against
|
||||
* the SHA-256 listed here, or copied from a folder of the same files under Download.
|
||||
* Everything lands under [GUEST_ROOT] in the rootfs, where both PRoot and bionic games read it.
|
||||
*/
|
||||
object UpscaleComponent {
|
||||
private const val TAG = "UpscaleComponent"
|
||||
const val UPSTREAM = "michaelisomer-cyber/Winlator-NeuralScale"
|
||||
const val UPSTREAM_COMMIT = "71c140d9e5586f659251c3ebc602f2d21923655c"
|
||||
const val XESS_COMMIT = "a0ab6b0f770e1a6786b4e68def46b4edb8baafd0"
|
||||
const val GUEST_ROOT = "/usr/local/lib/droiddeck-upscale"
|
||||
const val GUEST_RUN = "/run/droiddeck-hud/upscale"
|
||||
private const val LOCAL_COPY = "droiddeck-upscale"
|
||||
private const val LAYER_LIBRARY = "libVkLayer_droiddeck_upscale.so"
|
||||
private const val BRIDGES_STAMP = ".pack"
|
||||
|
||||
enum class Group { CORE, XESS, NPU }
|
||||
|
||||
data class DataFile(
|
||||
val group: Group, val relative: String, val upstreamPath: String, val sha256: String, val size: Long,
|
||||
val commit: String = UPSTREAM_COMMIT,
|
||||
) {
|
||||
val url get() = "https://raw.githubusercontent.com/$UPSTREAM/$commit/$upstreamPath"
|
||||
}
|
||||
|
||||
val FILES = listOf(
|
||||
DataFile(Group.CORE, "fsr4/fsr3_accumulate.spv", "app/src/main/assets/fsr4/fsr3_accumulate.spv", "98054410f4d3b6fad3020b174982a5e68d2fc5a4d546a90f9e13ea646b32c180", 23840L),
|
||||
DataFile(Group.CORE, "fsr4/fsr3_prepare.spv", "app/src/main/assets/fsr4/fsr3_prepare.spv", "86e99b0e7e83e74729b016c3089deafdc9c2dc09b27305d009a8942dd0fe19da", 15036L),
|
||||
DataFile(Group.CORE, "fsr4/fsr3_rcas.spv", "app/src/main/assets/fsr4/fsr3_rcas.spv", "13e276049ecc18eb7b53f6de1f76f58eb1a60c6f4251870f3647b20478b05710", 11644L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/fsr411_full_zc_i8.wpack", "app/src/main/assets/fsr4/fsr411_full/performance/fsr411_full_zc_i8.wpack", "8d36bb959d23ede5bb409959736c0d0b718bae58b363779126c0235b0fd10f7c", 137424L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/fsr411_full_zc_s8.wpack", "app/src/main/assets/fsr4/fsr411_full/performance/fsr411_full_zc_s8.wpack", "ef445437e3d48c64f993a60407183f675d05aadd82c7c29b93e61c53308ab28e", 137256L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/initializers.bin", "app/src/main/assets/fsr4/fsr411_full/performance/initializers.bin", "a54e552ff69a3f7199861417f7ae461d1f67f636ab532c6ec9d8ea5d2963735a", 131072L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-00.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-00.spv", "d6a01100a56327713d2f7c1a768e41f8a31f2cadce5f37b7dac81630722ff5a2", 33116L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-01.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-01.spv", "759396dc2eccd731bebac13e8818568c8cc410150d24ed4cc01aa8b5ea873fbb", 58172L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-02.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-02.spv", "bdabc7c28f18c31ac8574856a386a268ae4d866f68a65e72b59bf3bad2235132", 3208L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-03.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-03.spv", "bcb4d1d01e33114c68bb13059577c280bb05b5a3af7218fdbc38e99883e0632d", 108840L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-04.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-04.spv", "d85b605d066d89178994ba835b6c3b267ed771de530117a5b9e6103d49e866e7", 3244L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-05.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-05.spv", "e44f0ccd272e4a85ad38894a38db7adae019d18660b166e6c28e82b328d7cc84", 109048L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-06.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-06.spv", "df469b6481234bf7b964a7c0ecf8a5829d84d1bc34fdb7c72e87014f82e31326", 3208L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-07.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-07.spv", "a873b766b2b8923aeb7d325a61cbea251cbac6450e708a23a7714c553ce577ff", 132572L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-08.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-08.spv", "c4aba5b9cd11100308aa2e3d8a4d39e66713c46c35edbe6496552764459a2228", 3580L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-09.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-09.spv", "d757fd28efbd09259f82918de5d3765784933d5b26eea56babe45fd6fefc5cfa", 190032L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-10.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-10.spv", "295873b3ecbd9db40cc4c50ecf15a72964d5846b96642d2e4743a9333382b557", 3580L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-11.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-11.spv", "73e05c6727408d5b1f472112c5d68060e9db9aaf918e892055e6619d5f0e4edc", 190032L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-12.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-12.spv", "007315c42072370919ac393b63a04a0ac025a802f927b490a6749bd6034c15fd", 3596L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-13.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-13.spv", "020929f63d8a70f90bd628a92c50b4049db89155d5e062bf03eb1e8cb8ee7c60", 497604L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-14.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-14.spv", "f26dc72bbe9ccc70e2cc2dc1f4b2a868baf3c2e470b4e76994f98c50674ec3d8", 4268L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-15.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-15.spv", "9487c52cec7e259f4cb212335e84db43c52902b4e3243afcd34305b95ad1b83b", 79128L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-16.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-16.spv", "55c48a8b7627343d996f7818ee6055e143d3b956b8f65911d6b6c337bd8f72ca", 4268L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-17.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-17.spv", "810636645f52d5b8c019206deb046e954af730fc13edaa6a00ebf66e686c3ac0", 79128L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-18.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-18.spv", "a3d130ad8fc6438766f3cdeb7e062d03291a25f6a5e439f71b905795cfc856ec", 4268L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-19.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-19.spv", "e1b576f7e8cedc46615a90f5d2026a43a525a2e43cfc66b62def8e700f55688a", 84476L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-20.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-20.spv", "70c2b7b4e55d665591b2dca3efddb6e99e6d393020722cec635fb8df3bd81bf1", 3596L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-21.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-21.spv", "bb1798794d6c8b0ad3760059bf36e2c396594226c0835202040a4a515a8beb01", 189952L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-22.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-22.spv", "b0545fc4c1886fa0a6252029eb6e3a2f999974bc0bc89539c8d6005c184d8a6f", 3580L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-23.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-23.spv", "e9aee05cec78f0659fa570bfc0f495a51d00d2bc80c4e99cde4106a3df51c35e", 61308L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-24.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-24.spv", "1e93b681a9264afc07f0ab41086474b3afaa2ff8d37b5b75c9ceae005e21e558", 3260L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-25.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-25.spv", "6292dd68a4da9370c7dabb3b192fe6958b1a12daffd92b7fa80ed6fe231e1e5d", 109064L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-26.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-26.spv", "abc2426ff739d25cba4d271cad08ec9f25056ae197a9727b7b7e72467ba49d28", 3224L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/performance/pass-27.spv", "app/src/main/assets/fsr4/fsr411_full/performance/pass-27.spv", "fa5fc1de4625915c25a637b091f26f32c398f4985a14392a48505cfac111aaea", 125196L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/initializers.bin", "app/src/main/assets/fsr4/fsr411_full/quality/initializers.bin", "a54e552ff69a3f7199861417f7ae461d1f67f636ab532c6ec9d8ea5d2963735a", 131072L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-00.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-00.spv", "d6a01100a56327713d2f7c1a768e41f8a31f2cadce5f37b7dac81630722ff5a2", 33116L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-01.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-01.spv", "759396dc2eccd731bebac13e8818568c8cc410150d24ed4cc01aa8b5ea873fbb", 58172L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-02.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-02.spv", "bdabc7c28f18c31ac8574856a386a268ae4d866f68a65e72b59bf3bad2235132", 3208L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-03.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-03.spv", "bcb4d1d01e33114c68bb13059577c280bb05b5a3af7218fdbc38e99883e0632d", 108840L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-04.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-04.spv", "d85b605d066d89178994ba835b6c3b267ed771de530117a5b9e6103d49e866e7", 3244L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-05.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-05.spv", "e44f0ccd272e4a85ad38894a38db7adae019d18660b166e6c28e82b328d7cc84", 109048L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-06.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-06.spv", "df469b6481234bf7b964a7c0ecf8a5829d84d1bc34fdb7c72e87014f82e31326", 3208L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-07.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-07.spv", "a873b766b2b8923aeb7d325a61cbea251cbac6450e708a23a7714c553ce577ff", 132572L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-08.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-08.spv", "c4aba5b9cd11100308aa2e3d8a4d39e66713c46c35edbe6496552764459a2228", 3580L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-09.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-09.spv", "d757fd28efbd09259f82918de5d3765784933d5b26eea56babe45fd6fefc5cfa", 190032L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-10.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-10.spv", "295873b3ecbd9db40cc4c50ecf15a72964d5846b96642d2e4743a9333382b557", 3580L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-11.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-11.spv", "73e05c6727408d5b1f472112c5d68060e9db9aaf918e892055e6619d5f0e4edc", 190032L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-12.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-12.spv", "007315c42072370919ac393b63a04a0ac025a802f927b490a6749bd6034c15fd", 3596L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-13.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-13.spv", "020929f63d8a70f90bd628a92c50b4049db89155d5e062bf03eb1e8cb8ee7c60", 497604L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-14.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-14.spv", "f26dc72bbe9ccc70e2cc2dc1f4b2a868baf3c2e470b4e76994f98c50674ec3d8", 4268L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-15.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-15.spv", "9487c52cec7e259f4cb212335e84db43c52902b4e3243afcd34305b95ad1b83b", 79128L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-16.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-16.spv", "55c48a8b7627343d996f7818ee6055e143d3b956b8f65911d6b6c337bd8f72ca", 4268L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-17.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-17.spv", "810636645f52d5b8c019206deb046e954af730fc13edaa6a00ebf66e686c3ac0", 79128L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-18.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-18.spv", "a3d130ad8fc6438766f3cdeb7e062d03291a25f6a5e439f71b905795cfc856ec", 4268L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-19.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-19.spv", "e1b576f7e8cedc46615a90f5d2026a43a525a2e43cfc66b62def8e700f55688a", 84476L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-20.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-20.spv", "70c2b7b4e55d665591b2dca3efddb6e99e6d393020722cec635fb8df3bd81bf1", 3596L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-21.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-21.spv", "bb1798794d6c8b0ad3760059bf36e2c396594226c0835202040a4a515a8beb01", 189952L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-22.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-22.spv", "b0545fc4c1886fa0a6252029eb6e3a2f999974bc0bc89539c8d6005c184d8a6f", 3580L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-23.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-23.spv", "e9aee05cec78f0659fa570bfc0f495a51d00d2bc80c4e99cde4106a3df51c35e", 61308L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-24.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-24.spv", "1e93b681a9264afc07f0ab41086474b3afaa2ff8d37b5b75c9ceae005e21e558", 3260L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-25.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-25.spv", "6292dd68a4da9370c7dabb3b192fe6958b1a12daffd92b7fa80ed6fe231e1e5d", 109064L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-26.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-26.spv", "abc2426ff739d25cba4d271cad08ec9f25056ae197a9727b7b7e72467ba49d28", 3224L),
|
||||
DataFile(Group.CORE, "fsr4/fsr411_full/quality/pass-27.spv", "app/src/main/assets/fsr4/fsr411_full/quality/pass-27.spv", "fa5fc1de4625915c25a637b091f26f32c398f4985a14392a48505cfac111aaea", 125196L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0000.spv", "app/src/main/assets/fsr4/fsr412_lite/0000.spv", "2ec08c00ba47d5812078073c68622101158762b2e885ae965afee39596243840", 97808L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0001.spv", "app/src/main/assets/fsr4/fsr412_lite/0001.spv", "ff1270ab046cd190e9edf0d76cc5d5fda34a27a2de719e8352b4dcaeeed3e3bb", 3456L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0002.spv", "app/src/main/assets/fsr4/fsr412_lite/0002.spv", "c47c6282830916e9314f0153c4abd782736b6cee3992e8db301937b42ec44141", 120964L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0003.spv", "app/src/main/assets/fsr4/fsr412_lite/0003.spv", "0797d2053df579930c2907a3f1e91c8a39c44cae4e471eca4c243075a787d572", 3492L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0004.spv", "app/src/main/assets/fsr4/fsr412_lite/0004.spv", "e7d3651fb730c8b543aaae332f760d352d555e3f8e5899c055b46fc007c80bbc", 3928L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0005.spv", "app/src/main/assets/fsr4/fsr412_lite/0005.spv", "0bacdbf39bead28f5012ca09a6d8243e501b3328065e29c2b5bdfc93f5ae3ffa", 201880L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0006.spv", "app/src/main/assets/fsr4/fsr412_lite/0006.spv", "f58da749701f226994560878cad3b98f01db0557feea4d9445ae84ed6b2049a2", 3892L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0007.spv", "app/src/main/assets/fsr4/fsr412_lite/0007.spv", "c8088556c624f601cb9adf280ba0a4b6fa54068c1f60a0ebc26c11dad81a44c3", 279304L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0008.spv", "app/src/main/assets/fsr4/fsr412_lite/0008.spv", "9e5f48d397020f1fd8706f554adce0adb88641cd06dd054252f1f2f58f1566e5", 3508L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0009.spv", "app/src/main/assets/fsr4/fsr412_lite/0009.spv", "23cc6f3c09546cbca7c70130de931324f9262d13a5f894ebedac78d0e94ef43f", 104052L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0010.spv", "app/src/main/assets/fsr4/fsr412_lite/0010.spv", "a60c0492e22ae608ba9b7e9d479db03ad198a8d9523edb7b65cc0eaef5829a29", 28988L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/0013.spv", "app/src/main/assets/fsr4/fsr412_lite/0013.spv", "05bbe60c6a0310044df99f2e7fe6af0b6644780305c98bc6fd6287de7b954cf0", 57232L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/fsr412_lite_zc_i8.wpack", "app/src/main/assets/fsr4/fsr412_lite/fsr412_lite_zc_i8.wpack", "5a00ff5e9a444708ce66b17a12fa8ffc2a3bdbd798399a0d26807de121ab2140", 27440L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/fsr412_lite_zc_s8.wpack", "app/src/main/assets/fsr4/fsr412_lite/fsr412_lite_zc_s8.wpack", "f45ab49039ad27041ebc6edd76de54d14246693445e53362d94b4a9514ae65a7", 27272L),
|
||||
DataFile(Group.CORE, "fsr4/fsr412_lite/weights.bin", "app/src/main/assets/fsr4/fsr412_lite/weights.bin", "4b9898da719dc2dca5dc45fd71dec5f80bdb9886a580fe3038af59efe637d55e", 27392L),
|
||||
DataFile(Group.CORE, "fsr4/sgsr2_activate.spv", "app/src/main/assets/fsr4/sgsr2_activate.spv", "45aabce377d4cc9522ea9d954d9f069e1618ac0c9656ef2be6fd317369ae3140", 13456L),
|
||||
DataFile(Group.CORE, "fsr4/sgsr2_convert.spv", "app/src/main/assets/fsr4/sgsr2_convert.spv", "71afffb95978f0dc61d3f39f266eb61e5c803b17574a3595726e4c55bb581872", 14600L),
|
||||
DataFile(Group.CORE, "fsr4/sgsr2_upscale.spv", "app/src/main/assets/fsr4/sgsr2_upscale.spv", "bf7fe1247894919349fef91f8fa41ee256cb58dd7cf87f682db43108f9dcd1ec", 29748L),
|
||||
// Upstream dropped Intel's XeSS runtime in cb3ae04e (v5.0-r2); DroidDeck keeps fetching it from a0ab6b0f.
|
||||
DataFile(Group.XESS, "xess/wl_xess_official.dll", "app/src/main/assets/fsr4_bridge/wl_xess_official.dll", "251659dd84a3e84de67c886a4186e01f3eca49b00641906fe38bb6b807e5d5b7", 77795704L, XESS_COMMIT),
|
||||
DataFile(Group.NPU, "fsr4/adsp/libQnnHtpV79Skel.so", "app/src/main/assets/fsr4/adsp/libQnnHtpV79Skel.so", "974583f0cdc3d42de7a0633c9b987b160ad033a4cd53be30f9b5480b7e5a3213", 11702104L),
|
||||
DataFile(Group.NPU, "fsr4/adsp/libQnnHtpV81Skel.so", "app/src/main/assets/fsr4/adsp/libQnnHtpV81Skel.so", "a0b9750d900a0afbba240e3506ba63ba91ec0e7f1b3a44de9afbb6818a665a32", 12606648L),
|
||||
DataFile(Group.NPU, "jni/libQnnHtp.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtp.so", "6e6da5284060ca4369bb6fd3c6f2b661a9cebabb2cf4cf695cd77f558082265f", 3760136L),
|
||||
DataFile(Group.NPU, "jni/libQnnHtpNetRunExtensions.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtpNetRunExtensions.so", "9776e906cff859504e9e5fd5f9cbb0ec592d9ae6be312ef0650cb95eb8e3aef6", 1383928L),
|
||||
DataFile(Group.NPU, "jni/libQnnHtpPrepare.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtpPrepare.so", "cd31f94ae79ad402312e75262297d1e1073f85927d95f7905357a10b1d32a263", 87913152L),
|
||||
DataFile(Group.NPU, "jni/libQnnHtpV79Stub.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtpV79Stub.so", "b3b4cca02e1f2cb5778ef9f18850814358d62a0b90123b25bb2806731a6af8b3", 754480L),
|
||||
DataFile(Group.NPU, "jni/libQnnHtpV81Stub.so", "app/src/main/jniLibs/arm64-v8a/libQnnHtpV81Stub.so", "16188365d86ef09a9067e8e04b7fa1c604729d1870219b1bbf04ee904e6c3ffa", 777848L),
|
||||
DataFile(Group.NPU, "jni/libQnnSystem.so", "app/src/main/jniLibs/arm64-v8a/libQnnSystem.so", "4cd077547a939b131c4733391545d64bdc4f9d0c86de78793335ddd18348789e", 4052904L),
|
||||
)
|
||||
|
||||
sealed interface State {
|
||||
data object Missing : State
|
||||
data class Downloading(val progress: Float) : State
|
||||
data object Ready : State
|
||||
data class Failed(val message: String) : State
|
||||
}
|
||||
|
||||
private val mutableState = MutableStateFlow<State>(State.Missing)
|
||||
val state: StateFlow<State> = mutableState.asStateFlow()
|
||||
private val lock = Any()
|
||||
@Volatile private var busy = false
|
||||
|
||||
fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_ROOT.removePrefix("/"))
|
||||
fun dataDir(context: Context) = File(root(context), "data")
|
||||
fun bridgesDir(context: Context) = File(root(context), "bridges")
|
||||
fun runDir(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_RUN.removePrefix("/"))
|
||||
|
||||
/** The NPU this phone has: its Hexagon HTP generation and whether its own QNN libraries run it. */
|
||||
data class Npu(val arch: String, val systemLibs: Boolean)
|
||||
|
||||
private val SYSTEM_QNN = listOf("libQnnHtp.so", "libQnnHtpPrepare.so", "libQnnSystem.so")
|
||||
private val SYSTEM_STUB = Regex("libQnnHtpV(\\d{2,3})Stub\\.so")
|
||||
|
||||
/**
|
||||
* The HTP generation of the phone's own QNN runtime, when the vendor offers it to apps (listed in
|
||||
* public.libraries.txt): named by its one libQnnHtpV<NN>Stub.so. Null when absent or ambiguous.
|
||||
*/
|
||||
internal fun systemNpuArch(libDir: File = File("/vendor/lib64"), publicList: File = File("/vendor/etc/public.libraries.txt")): String? {
|
||||
val listed = runCatching {
|
||||
publicList.readLines().map { it.trim() }.filter { it.isNotEmpty() && !it.startsWith("#") }.map { it.substringBefore(' ') }.toSet()
|
||||
}.getOrNull() ?: return null
|
||||
if (!SYSTEM_QNN.all { it in listed && File(libDir, it).isFile }) return null
|
||||
val archs = libDir.list().orEmpty().filter { it in listed }.mapNotNull { SYSTEM_STUB.matchEntire(it)?.groupValues?.get(1) }.distinct()
|
||||
return archs.singleOrNull()?.let { "v$it" }
|
||||
}
|
||||
|
||||
private val systemNpu: String? by lazy { runCatching { systemNpuArch() }.getOrNull() }
|
||||
|
||||
/**
|
||||
* This phone's NPU, or null. The phone's own QNN runtime first (any HTP generation, nothing to download);
|
||||
* else the bundled QNN files: v79 on the Snapdragon 8 Elite, v81 on the 8 Elite Gen 5.
|
||||
*/
|
||||
fun npu(model: String = SocNames.model()): Npu? {
|
||||
systemNpu?.let { return Npu(it, systemLibs = true) }
|
||||
val soc = SocNames.normalizedModel(model)
|
||||
val arch = when {
|
||||
soc.startsWith("SM8750") -> "v79"
|
||||
soc.startsWith("SM8850") || soc.startsWith("SM8845") -> "v81"
|
||||
else -> null
|
||||
} ?: return null
|
||||
val fastrpc = listOf("/dev/fastrpc-cdsp", "/dev/fastrpc-cdsp-secure", "/dev/adsprpc-smd").any { File(it).exists() }
|
||||
return Npu(arch, systemLibs = false).takeIf { fastrpc }
|
||||
}
|
||||
|
||||
fun npuArch(model: String = SocNames.model()): String? = npu(model)?.arch
|
||||
|
||||
fun groups(engine: GameUpscaler.Engine, npu: Boolean = npuArch() != null): Set<Group> = buildSet {
|
||||
add(Group.CORE)
|
||||
if (engine == GameUpscaler.Engine.XESS) add(Group.XESS)
|
||||
if (engine.npu && npu && UpscaleComponent.npu()?.systemLibs != true) add(Group.NPU)
|
||||
}
|
||||
|
||||
/** The bridge DLLs (tools/upscale/bridges/build.sh), each in both Wine PE folders. */
|
||||
private val BRIDGE_NAMES = listOf(
|
||||
"_nvngx.dll", "amd_fidelityfx_dx12.dll", "amd_fidelityfx_loader_dx12.dll", "amd_fidelityfx_upscaler_dx12.dll",
|
||||
"amd_fidelityfx_upscaler_vk.dll", "amd_fidelityfx_vk.dll", "ffx_fsr2_api_x64.dll", "ffx_fsr3upscaler_x64.dll",
|
||||
"libxess.dll", "nvapi64.dll", "nvngx.dll", "nvngx_dlss.dll",
|
||||
)
|
||||
internal val BRIDGE_FILES = listOf("x86_64-windows", "aarch64-windows").flatMap { arch -> BRIDGE_NAMES.map { "$arch/$it" } }
|
||||
|
||||
fun filesReady(context: Context, groups: Set<Group>): Boolean =
|
||||
FILES.filter { it.group in groups }.all { f -> File(dataDir(context), f.relative).let { it.isFile && it.length() == f.size } }
|
||||
|
||||
fun bridgesReady(context: Context): Boolean =
|
||||
BRIDGE_FILES.all { File(bridgesDir(context), it).let { f -> f.isFile && f.length() > 0 } }
|
||||
|
||||
/** Everything a game with [groups] needs: the data files and the bridge DLLs. */
|
||||
fun ready(context: Context, groups: Set<Group>): Boolean = filesReady(context, groups) && bridgesReady(context)
|
||||
|
||||
/** Fetches what [groups] still lack (data files, then the bridge DLLs) in the background. */
|
||||
fun ensure(context: Context, groups: Set<Group>, onDone: (Boolean) -> Unit = {}) {
|
||||
val app = context.applicationContext
|
||||
if (ready(app, groups)) {
|
||||
mutableState.value = State.Ready
|
||||
onDone(true)
|
||||
return
|
||||
}
|
||||
synchronized(lock) {
|
||||
if (busy) return
|
||||
busy = true
|
||||
}
|
||||
Thread({
|
||||
val ok = try {
|
||||
val files = filesReady(app, groups) || download(app, groups)
|
||||
// Staged DLLs are refreshed when the pack or local copy changed; a download only when none are staged.
|
||||
val bridges = files && (if (bridgesReady(app)) stageBridges(app) else fetchBridges(app))
|
||||
when {
|
||||
bridges -> mutableState.value = State.Ready
|
||||
files -> mutableState.value = State.Failed("upscaler DLLs not installed")
|
||||
}
|
||||
bridges
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "upscaler files not fetched", e)
|
||||
mutableState.value = State.Failed(e.message ?: e.javaClass.simpleName)
|
||||
false
|
||||
} finally {
|
||||
synchronized(lock) { busy = false }
|
||||
}
|
||||
onDone(ok)
|
||||
}, "upscale-files").start()
|
||||
}
|
||||
|
||||
private fun download(context: Context, groups: Set<Group>): Boolean {
|
||||
val wanted = FILES.filter { it.group in groups }
|
||||
val missing = wanted.filter { f -> File(dataDir(context), f.relative).let { !it.isFile || it.length() != f.size } }
|
||||
val total = missing.sumOf { it.size }.coerceAtLeast(1L)
|
||||
var done = 0L
|
||||
mutableState.value = State.Downloading(0f)
|
||||
for (f in missing) {
|
||||
val target = File(dataDir(context), f.relative)
|
||||
target.parentFile?.mkdirs()
|
||||
val part = File(target.path + ".part")
|
||||
val ok = copyLocal(context, f, part) || Downloader.downloadFile(f.url, part, true, f.sha256) { p ->
|
||||
mutableState.value = State.Downloading(((done + p * f.size) / total).coerceIn(0f, 1f))
|
||||
}
|
||||
if (!ok || !part.renameTo(target)) {
|
||||
part.delete()
|
||||
val reason = Downloader.lastFailure() ?: "could not fetch ${f.relative}"
|
||||
mutableState.value = State.Failed(reason)
|
||||
Log.w(TAG, "upscaler file ${f.relative} not fetched: $reason")
|
||||
return false
|
||||
}
|
||||
if (f.group == Group.NPU) {
|
||||
target.setReadable(true, false)
|
||||
target.setExecutable(true, false)
|
||||
}
|
||||
done += f.size
|
||||
mutableState.value = State.Downloading((done.toFloat() / total).coerceIn(0f, 1f))
|
||||
}
|
||||
Log.i(TAG, "upscaler files ready (${wanted.size} files, groups $groups)")
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Folders that may hold a local copy (same layout as the upstream tree): the app's own external
|
||||
* files folders, readable without any storage permission, then Download/droiddeck-upscale.
|
||||
*/
|
||||
@Suppress("DEPRECATION")
|
||||
private fun localRoots(context: Context): List<File> =
|
||||
context.getExternalFilesDirs(null).orEmpty().filterNotNull().map { File(it, LOCAL_COPY) } +
|
||||
File(Environment.getExternalStorageDirectory(), "Download/$LOCAL_COPY")
|
||||
|
||||
/** A local copy of [f] (see [localRoots]), used when its SHA-256 matches. */
|
||||
private fun copyLocal(context: Context, f: DataFile, part: File): Boolean = localRoots(context).any { root ->
|
||||
runCatching {
|
||||
val local = File(root, f.relative)
|
||||
if (!local.isFile || !local.canRead() || local.length() != f.size || sha256(local) != f.sha256) return@runCatching false
|
||||
local.inputStream().use { input -> part.outputStream().use { output -> input.copyTo(output, 1 shl 20) } }
|
||||
sha256(part) == f.sha256
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun sha256(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
file.inputStream().use { input ->
|
||||
val buffer = ByteArray(1 shl 20)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
digest.update(buffer, 0, n)
|
||||
}
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/** The add-on pack's bridges/ (fetched now when there is no local copy), staged into the rootfs. */
|
||||
private fun fetchBridges(context: Context): Boolean {
|
||||
val pack = AddonPack.UPSCALE
|
||||
if (!pack.installed(context) && localBridges(context) == null && pack.available) pack.await(context)
|
||||
return stageBridges(context)
|
||||
}
|
||||
|
||||
/** Content hash of a local bridges/ tree: CI builds every DLL with the same date, and sizes often stay the same. */
|
||||
internal fun localVersion(source: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
for (name in BRIDGE_FILES) {
|
||||
digest.update(name.toByteArray())
|
||||
digest.update(sha256(File(source, name)).toByteArray())
|
||||
}
|
||||
return digest.digest().take(8).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/** A complete, readable bridges/ tree in one of [localRoots]: builds without a published pack. */
|
||||
private fun localBridges(context: Context): File? = localRoots(context).map { File(it, "bridges") }.firstOrNull { dir ->
|
||||
runCatching { BRIDGE_FILES.all { File(dir, it).let { f -> f.isFile && f.canRead() && f.length() > 0 } } }.getOrDefault(false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the bridge DLLs from the add-on pack (or the local tree) into the rootfs, once per version. True only
|
||||
* when every one of [BRIDGE_FILES] is in place afterwards.
|
||||
*/
|
||||
@Synchronized
|
||||
fun stageBridges(context: Context): Boolean {
|
||||
val packDir = AddonPack.UPSCALE.takeIf { it.installed(context) }?.dir(context)
|
||||
val pack = packDir?.let { File(it, "bridges") }
|
||||
val source = pack?.takeIf { dir -> BRIDGE_FILES.all { File(dir, it).isFile } } ?: localBridges(context)
|
||||
if (source == null) {
|
||||
val ready = bridgesReady(context)
|
||||
if (!ready) Log.w(TAG, "upscaler bridges: no add-on pack and no readable local copy")
|
||||
return ready
|
||||
}
|
||||
val version = if (packDir != null && source == pack) packDir.name else "local-" + localVersion(source)
|
||||
val target = bridgesDir(context)
|
||||
val stamp = File(target, BRIDGES_STAMP)
|
||||
if (bridgesReady(context) && runCatching { stamp.readText() }.getOrNull() == version) return true
|
||||
var copied = 0
|
||||
for (name in BRIDGE_FILES) {
|
||||
val from = File(source, name)
|
||||
val out = File(target, name)
|
||||
out.parentFile?.mkdirs()
|
||||
val staged = File(out.path + ".staged")
|
||||
val ok = runCatching {
|
||||
from.inputStream().use { input -> staged.outputStream().use { output -> input.copyTo(output) } }
|
||||
staged.length() == from.length() && staged.renameTo(out)
|
||||
}.getOrDefault(false)
|
||||
staged.delete()
|
||||
if (ok) copied++ else Log.w(TAG, "upscaler bridge $name not staged from $source")
|
||||
}
|
||||
val ok = copied == BRIDGE_FILES.size && bridgesReady(context)
|
||||
if (ok) runCatching { stamp.writeText(version) }
|
||||
Log.i(TAG, "upscaler bridges staged from $version: $copied/${BRIDGE_FILES.size} files")
|
||||
return ok
|
||||
}
|
||||
|
||||
/** The bionic layer's manifest (the layer itself is the APK's native library). */
|
||||
fun bionicLayerDir(context: Context): File {
|
||||
val dir = File(context.filesDir, "upscale/layer")
|
||||
val library = File(context.applicationInfo.nativeLibraryDir, LAYER_LIBRARY)
|
||||
val manifest = """{
|
||||
"file_format_version": "1.0.0",
|
||||
"layer": {
|
||||
"name": "VK_LAYER_DROIDDECK_upscale",
|
||||
"type": "GLOBAL",
|
||||
"library_path": "${library.absolutePath}",
|
||||
"api_version": "1.3.275",
|
||||
"implementation_version": "1",
|
||||
"description": "DroidDeck in-game upscaler (FSR 4, XeSS 3, Hexagon NPU)",
|
||||
"enable_environment": { "DROIDDECK_UPSCALE": "1" },
|
||||
"disable_environment": { "DROIDDECK_UPSCALE_DISABLE": "1" }
|
||||
}
|
||||
}
|
||||
"""
|
||||
runCatching {
|
||||
dir.mkdirs()
|
||||
val file = File(dir, "VK_LAYER_DROIDDECK_upscale.json")
|
||||
if (!file.isFile || file.readText() != manifest) file.writeText(manifest)
|
||||
}.onFailure { Log.w(TAG, "could not write the upscaler layer manifest", it) }
|
||||
return dir
|
||||
}
|
||||
|
||||
/** Session-wide guest variables: whether NPU engines can run here (and its HTP generation), and the bionic layer's manifest folder. */
|
||||
fun guestEnv(context: Context): List<String> {
|
||||
runCatching { runDir(context).mkdirs() }
|
||||
val here = npu()
|
||||
return listOfNotNull(
|
||||
"DROIDDECK_UPSCALE_NPU=" + (if (here != null) "1" else "0"),
|
||||
here?.let { "DROIDDECK_UPSCALE_HTP_ARCH=${it.arch}" },
|
||||
"DROIDDECK_UPSCALE_LAYER=" + bionicLayerDir(context).absolutePath,
|
||||
)
|
||||
}
|
||||
|
||||
/** Fetches what the games set to use the upscaler need, at session start. */
|
||||
fun prepare(context: Context) {
|
||||
val config = runCatching { GameEnvironmentStore.read(context) }.getOrNull() ?: return
|
||||
val choices = config.games.keys.mapNotNull { GameUpscaler.choice(config, it) }
|
||||
if (choices.isEmpty()) return
|
||||
// Runs on the session-start thread, before the game copies the DLLs: ensure() returns at once when DLLs are
|
||||
// staged, so a newer pack or local copy is staged here.
|
||||
if (bridgesReady(context)) runCatching { stageBridges(context) }.onFailure { Log.w(TAG, "upscaler DLLs not refreshed", it) }
|
||||
val npu = npuArch() != null
|
||||
ensure(context, choices.flatMap { groups(it.engine, npu) }.toSet())
|
||||
}
|
||||
|
||||
/** Live switch while a game runs: the layer polls this file (fsr4_layer.c read_live_ctrl). */
|
||||
fun writeControl(context: Context, engine: GameUpscaler.Engine, sharpness: Int, npuSync: Boolean, enabled: Boolean = true) {
|
||||
runCatching {
|
||||
val dir = runDir(context).apply { mkdirs() }
|
||||
val ctrl = File(dir, "ctrl")
|
||||
val staged = File(dir, "ctrl.tmp")
|
||||
val effective = GameUpscaler.effectiveEngine(engine, npuArch() != null)
|
||||
staged.writeText(GameUpscaler.controlText(effective, sharpness, npuSync, enabled))
|
||||
staged.renameTo(ctrl)
|
||||
}.onFailure { Log.w(TAG, "could not write the upscaler control file", it) }
|
||||
}
|
||||
|
||||
/** What the layer reports, if it wrote in the last few seconds. */
|
||||
fun status(context: Context, nowMs: Long = System.currentTimeMillis()): GameUpscaler.Status? {
|
||||
val file = File(runDir(context), "status")
|
||||
if (!file.isFile || nowMs - file.lastModified() > 5000) return null
|
||||
return runCatching { GameUpscaler.parseStatus(file.readText()) }.getOrNull()
|
||||
}
|
||||
|
||||
fun anyGame(config: GameEnvironment.Config): Boolean = config.games.keys.any { GameUpscaler.choice(config, it) != null }
|
||||
}
|
||||
@@ -211,6 +211,7 @@ private val METRICS = listOf(
|
||||
HudMetric("showNet", R.string.hud_metric_network),
|
||||
HudMetric("showResolution", R.string.hud_metric_resolution),
|
||||
HudMetric("showProton", R.string.hud_metric_proton),
|
||||
HudMetric("showUpscale", R.string.hud_metric_upscale),
|
||||
HudMetric("showSession", R.string.hud_metric_session),
|
||||
HudMetric("showClock", R.string.hud_metric_clock),
|
||||
)
|
||||
|
||||
@@ -1134,6 +1134,39 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameResolution(it, scope, choice) }
|
||||
}
|
||||
var editResolution by remember(scope) { mutableStateOf(false) }
|
||||
val upKey = "game-settings-upscale"
|
||||
val upEngineKey = "game-settings-upscale-engine"
|
||||
val upSharpKey = "game-settings-upscale-sharp"
|
||||
val upscale = current?.let { com.droiddeck.launcher.core.GameUpscaler.choice(it, scope) }
|
||||
val npuHere = remember { com.droiddeck.launcher.session.UpscaleComponent.npuArch() != null }
|
||||
val upFiles by com.droiddeck.launcher.session.UpscaleComponent.state.collectAsState()
|
||||
val modeLabels = mapOf(
|
||||
com.droiddeck.launcher.core.GameUpscaler.Mode.FSR_XESS to stringResource(R.string.game_upscaler_mode_fsr),
|
||||
com.droiddeck.launcher.core.GameUpscaler.Mode.DLSS to stringResource(R.string.game_upscaler_mode_dlss),
|
||||
com.droiddeck.launcher.core.GameUpscaler.Mode.NATIVE_FSR4 to stringResource(R.string.game_upscaler_mode_native),
|
||||
)
|
||||
val engineLabels = mapOf(
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_LITE_GPU to stringResource(R.string.game_upscaler_engine_fsr4_lite),
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_FULL_GPU to stringResource(R.string.game_upscaler_engine_fsr4_full),
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.XESS to stringResource(R.string.game_upscaler_engine_xess),
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.BASIC to stringResource(R.string.game_upscaler_engine_basic),
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.SGSR2 to stringResource(R.string.game_upscaler_engine_sgsr2),
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_NPU to stringResource(R.string.game_upscaler_engine_fsr4_npu),
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_LITE_NPU to stringResource(R.string.game_upscaler_engine_fsr4_lite_npu),
|
||||
)
|
||||
val upOff = stringResource(R.string.game_upscaler_off)
|
||||
val filesLabel = when (val f = upFiles) {
|
||||
is com.droiddeck.launcher.session.UpscaleComponent.State.Downloading -> stringResource(R.string.game_upscaler_files_downloading, (f.progress * 100).toInt())
|
||||
is com.droiddeck.launcher.session.UpscaleComponent.State.Failed -> stringResource(R.string.game_upscaler_files_failed, f.message)
|
||||
else -> if (upscale != null && com.droiddeck.launcher.session.UpscaleComponent.ready(appContext,
|
||||
com.droiddeck.launcher.session.UpscaleComponent.groups(upscale.engine, npuHere)))
|
||||
stringResource(R.string.game_upscaler_files_ready) else stringResource(R.string.game_upscaler_files_missing)
|
||||
}
|
||||
fun pickUpscale(choice: com.droiddeck.launcher.core.GameUpscaler.Choice?) {
|
||||
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameUpscaler(it, scope, choice) }
|
||||
if (choice != null) com.droiddeck.launcher.session.UpscaleComponent.ensure(appContext,
|
||||
com.droiddeck.launcher.session.UpscaleComponent.groups(choice.engine, npuHere))
|
||||
}
|
||||
AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = stringResource(R.string.game_settings_menu_title, game.name)) { first ->
|
||||
MenuItem(stringResource(R.string.game_no_steam_title), checked = noSteam, enabled = ready,
|
||||
detail = stringResource(R.string.game_no_steam_detail), focusRequester = first) {
|
||||
@@ -1165,6 +1198,37 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
},
|
||||
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
|
||||
) { host.open = syncKey }
|
||||
MenuItem(
|
||||
stringResource(R.string.game_upscaler_title), checked = false, enabled = ready,
|
||||
detail = upscale?.let { modeLabels[it.mode] } ?: upOff,
|
||||
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
|
||||
) { host.open = upKey }
|
||||
if (upscale != null) {
|
||||
MenuItem(
|
||||
stringResource(R.string.game_upscaler_engine), checked = false, enabled = ready,
|
||||
detail = engineLabels[com.droiddeck.launcher.core.GameUpscaler.effectiveEngine(upscale.engine, npuHere)],
|
||||
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
|
||||
) { host.open = upEngineKey }
|
||||
MenuItem(
|
||||
stringResource(R.string.game_upscaler_sharpness), checked = false, enabled = ready,
|
||||
detail = stringResource(R.string.game_upscaler_sharpness_value, upscale.sharpness),
|
||||
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
|
||||
) { host.open = upSharpKey }
|
||||
if (upscale.mode == com.droiddeck.launcher.core.GameUpscaler.Mode.DLSS) {
|
||||
MenuItem(stringResource(R.string.game_upscaler_sigfix), checked = upscale.signatureFix, enabled = ready) {
|
||||
pickUpscale(upscale.copy(signatureFix = !upscale.signatureFix))
|
||||
}
|
||||
}
|
||||
if (upscale.engine.npu && npuHere) {
|
||||
MenuItem(stringResource(R.string.game_upscaler_npu_sync), checked = upscale.npuSync, enabled = ready) {
|
||||
pickUpscale(upscale.copy(npuSync = !upscale.npuSync))
|
||||
}
|
||||
}
|
||||
MenuItem(stringResource(R.string.game_upscaler_files), checked = false, enabled = ready, detail = filesLabel) {
|
||||
com.droiddeck.launcher.session.UpscaleComponent.ensure(appContext,
|
||||
com.droiddeck.launcher.session.UpscaleComponent.groups(upscale.engine, npuHere))
|
||||
}
|
||||
}
|
||||
}
|
||||
MenuItem(stringResource(R.string.game_settings_default), checked = false, enabled = ready,
|
||||
detail = stringResource(R.string.game_settings_default_detail)) {
|
||||
@@ -1181,6 +1245,36 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
}
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == upKey, onDismiss = { if (host.open == upKey) host.open = null }, title = stringResource(R.string.game_upscaler_title)) { first ->
|
||||
MenuItem(upOff, checked = upscale == null, enabled = ready, focusRequester = first) {
|
||||
host.open = key
|
||||
pickUpscale(null)
|
||||
}
|
||||
com.droiddeck.launcher.core.GameUpscaler.Mode.entries.forEach { mode ->
|
||||
MenuItem(modeLabels.getValue(mode), checked = upscale?.mode == mode, enabled = ready) {
|
||||
host.open = key
|
||||
pickUpscale((upscale ?: com.droiddeck.launcher.core.GameUpscaler.Choice(mode)).copy(mode = mode))
|
||||
}
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == upEngineKey, onDismiss = { if (host.open == upEngineKey) host.open = null }, title = stringResource(R.string.game_upscaler_engine)) { first ->
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.entries.filter { !it.npu || npuHere }.forEachIndexed { index, engine ->
|
||||
MenuItem(engineLabels.getValue(engine), checked = upscale?.engine == engine, enabled = ready && upscale != null,
|
||||
focusRequester = if (index == 0) first else null) {
|
||||
host.open = key
|
||||
upscale?.let { pickUpscale(it.copy(engine = engine)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == upSharpKey, onDismiss = { if (host.open == upSharpKey) host.open = null }, title = stringResource(R.string.game_upscaler_sharpness)) { first ->
|
||||
com.droiddeck.launcher.core.GameUpscaler.sharpnessSteps.forEachIndexed { index, value ->
|
||||
MenuItem(stringResource(R.string.game_upscaler_sharpness_value, value), checked = upscale?.sharpness == value,
|
||||
enabled = ready && upscale != null, focusRequester = if (index == 0) first else null) {
|
||||
host.open = key
|
||||
upscale?.let { pickUpscale(it.copy(sharpness = value)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == resKey, onDismiss = { if (host.open == resKey) host.open = null }, title = stringResource(R.string.game_res_title)) { first ->
|
||||
MenuItem(matchScreen, checked = resolution == null, enabled = ready, focusRequester = first) { pickResolution(null) }
|
||||
com.droiddeck.launcher.core.GameResolution.scales.forEach { scale ->
|
||||
|
||||
@@ -1113,6 +1113,7 @@ private fun DrawerGamePage(host: MenuHost, a: DrawerActions, track: (String) ->
|
||||
color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp))
|
||||
}
|
||||
TextureFilteringGroup(host, a, track)
|
||||
if (a.steam || a.direct) DrawerUpscalerGroup(host, a, track)
|
||||
ComponentsDrawerPage(host, a, track)
|
||||
ComponentDownloadsDrawerGroup(
|
||||
host = host,
|
||||
@@ -1917,6 +1918,52 @@ private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (Stri
|
||||
}
|
||||
}
|
||||
|
||||
/** The selected game's in-game upscaler: engine and sharpness switch live (the layer polls its control file). */
|
||||
@Composable
|
||||
private fun DrawerUpscalerGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val appId = a.selectedGameProfileId ?: return
|
||||
val context = LocalContext.current.applicationContext
|
||||
val scope = appId.toString()
|
||||
var choice by remember(scope) {
|
||||
mutableStateOf(runCatching { com.droiddeck.launcher.core.GameUpscaler.choice(com.droiddeck.launcher.session.GameEnvironmentStore.read(context), scope) }.getOrNull())
|
||||
}
|
||||
val current = choice ?: return
|
||||
val npuHere = remember { com.droiddeck.launcher.session.UpscaleComponent.npuArch() != null }
|
||||
var status by remember { mutableStateOf<com.droiddeck.launcher.core.GameUpscaler.Status?>(null) }
|
||||
LaunchedEffect(scope) {
|
||||
while (true) {
|
||||
status = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.droiddeck.launcher.session.UpscaleComponent.status(context) }
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
val engines = com.droiddeck.launcher.core.GameUpscaler.Engine.entries.filter { !it.npu || npuHere }.map { engine ->
|
||||
engine to stringResource(when (engine) {
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_LITE_GPU -> R.string.game_upscaler_engine_fsr4_lite
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_FULL_GPU -> R.string.game_upscaler_engine_fsr4_full
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.XESS -> R.string.game_upscaler_engine_xess
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.BASIC -> R.string.game_upscaler_engine_basic
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.SGSR2 -> R.string.game_upscaler_engine_sgsr2
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_NPU -> R.string.game_upscaler_engine_fsr4_npu
|
||||
com.droiddeck.launcher.core.GameUpscaler.Engine.FSR4_LITE_NPU -> R.string.game_upscaler_engine_fsr4_lite_npu
|
||||
})
|
||||
}
|
||||
val sharpness = com.droiddeck.launcher.core.GameUpscaler.sharpnessSteps.map { it to stringResource(R.string.game_upscaler_sharpness_value, it) }
|
||||
fun applyChoice(next: com.droiddeck.launcher.core.GameUpscaler.Choice) {
|
||||
choice = next
|
||||
Thread({
|
||||
com.droiddeck.launcher.session.UpscaleComponent.writeControl(context, next.engine, next.sharpness, next.npuSync)
|
||||
runCatching { com.droiddeck.launcher.session.GameEnvironmentStore.setGameUpscaler(context, scope, next) }
|
||||
}, "upscale-live").start()
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.game_upscaler_title)) {
|
||||
ChoiceRow(host, "upscale-engine", stringResource(R.string.game_upscaler_engine),
|
||||
status?.let { "${it.backendTag} · ${it.render} → ${it.output} · " + String.format(java.util.Locale.ROOT, "%.1f ms", if (it.npu) it.npuMs else it.gpuMs) },
|
||||
engines, current.engine, chipModifier = track("upscale-engine")) { engine -> applyChoice(current.copy(engine = engine)) }
|
||||
ChoiceRow(host, "upscale-sharpness", stringResource(R.string.game_upscaler_sharpness), null,
|
||||
sharpness, current.sharpness, chipModifier = track("upscale-sharpness")) { value -> applyChoice(current.copy(sharpness = value)) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun signed(v: Int) = if (v > 0) "+$v" else "$v"
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -541,6 +541,28 @@
|
||||
<string name="game_steam_with">Starts with Steam</string>
|
||||
<string name="game_steam_without">Starts without Steam</string>
|
||||
<string name="game_res_title">Game resolution</string>
|
||||
<string name="game_upscaler_title">In-game upscaler</string>
|
||||
<string name="game_upscaler_off">Off</string>
|
||||
<string name="game_upscaler_mode_fsr">FSR and XeSS games</string>
|
||||
<string name="game_upscaler_mode_dlss">DLSS games</string>
|
||||
<string name="game_upscaler_mode_native">Native FSR 4</string>
|
||||
<string name="game_upscaler_engine">Upscaler</string>
|
||||
<string name="game_upscaler_engine_fsr4_lite">FSR 4 Lite</string>
|
||||
<string name="game_upscaler_engine_fsr4_full">FSR 4</string>
|
||||
<string name="game_upscaler_engine_xess">XeSS 3</string>
|
||||
<string name="game_upscaler_engine_basic">Basic temporal</string>
|
||||
<string name="game_upscaler_engine_sgsr2">Snapdragon GSR 2</string>
|
||||
<string name="game_upscaler_engine_fsr4_npu">FSR 4 on NPU</string>
|
||||
<string name="game_upscaler_engine_fsr4_lite_npu">FSR 4 Lite on NPU</string>
|
||||
<string name="game_upscaler_sharpness">Sharpness</string>
|
||||
<string name="game_upscaler_sharpness_value">%1$d%%</string>
|
||||
<string name="game_upscaler_sigfix">DLSS signature fix</string>
|
||||
<string name="game_upscaler_npu_sync">NPU sync</string>
|
||||
<string name="game_upscaler_files">Upscaler files</string>
|
||||
<string name="game_upscaler_files_ready">Ready</string>
|
||||
<string name="game_upscaler_files_missing">Not downloaded</string>
|
||||
<string name="game_upscaler_files_downloading">Downloading %1$d%%</string>
|
||||
<string name="game_upscaler_files_failed">Failed: %1$s</string>
|
||||
<string name="game_settings_card">Settings</string>
|
||||
<string name="game_settings_menu_title">%1$s Settings</string>
|
||||
<string name="game_settings_default">Default</string>
|
||||
@@ -775,6 +797,7 @@
|
||||
<string name="hud_metric_network">Network</string>
|
||||
<string name="hud_metric_resolution">Resolution</string>
|
||||
<string name="hud_metric_proton">Proton version</string>
|
||||
<string name="hud_metric_upscale">In-game upscaler</string>
|
||||
<string name="hud_metric_session">Session time</string>
|
||||
<string name="hud_metric_clock">Clock</string>
|
||||
<string name="hud_group_temps">Temperatures</string>
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class GameUpscalerTest {
|
||||
@Test fun aChoiceRoundTripsThroughTheGameEnvironment() {
|
||||
val choice = GameUpscaler.Choice(GameUpscaler.Mode.DLSS, GameUpscaler.Engine.XESS, 70, npuSync = true, signatureFix = true)
|
||||
val config = GameUpscaler.withChoice(GameEnvironment.Config(), "42", choice)
|
||||
assertEquals(choice, GameUpscaler.choice(config, "42"))
|
||||
assertNull(GameUpscaler.choice(config, "43"))
|
||||
}
|
||||
|
||||
@Test fun offRemovesOnlyTheUpscalerEntries() {
|
||||
val start = GameEnvironment.Config().withEntries("42", mapOf("FEX_MULTIBLOCK" to "0"))
|
||||
val on = GameUpscaler.withChoice(start, "42", GameUpscaler.Choice(GameUpscaler.Mode.FSR_XESS))
|
||||
val off = GameUpscaler.withChoice(on, "42", null)
|
||||
assertEquals(mapOf("FEX_MULTIBLOCK" to "0"), off.games["42"])
|
||||
}
|
||||
|
||||
@Test fun theSignatureFixIsOnlyKeptForDlss() {
|
||||
val fsr = GameUpscaler.entries(GameUpscaler.Choice(GameUpscaler.Mode.FSR_XESS, signatureFix = true))
|
||||
assertFalse(fsr.containsKey(GameUpscaler.SIGFIX))
|
||||
val dlss = GameUpscaler.entries(GameUpscaler.Choice(GameUpscaler.Mode.DLSS, signatureFix = true))
|
||||
assertEquals("1", dlss[GameUpscaler.SIGFIX])
|
||||
}
|
||||
|
||||
@Test fun unknownValuesFallBackToDefaults() {
|
||||
val config = GameEnvironment.Config().withEntries("7", mapOf(
|
||||
GameUpscaler.MODE to "fsr", GameUpscaler.ENGINE to "bogus", GameUpscaler.SHARPNESS to "250"))
|
||||
val choice = GameUpscaler.choice(config, "7")!!
|
||||
assertEquals(GameUpscaler.DEFAULT_ENGINE, choice.engine)
|
||||
assertEquals(100, choice.sharpness)
|
||||
assertNull(GameUpscaler.choice(GameEnvironment.Config().withEntries("7", mapOf(GameUpscaler.MODE to "x")), "7"))
|
||||
}
|
||||
|
||||
@Test fun npuEnginesRunOnTheGpuWithoutAnNpu() {
|
||||
assertEquals(GameUpscaler.Engine.FSR4_FULL_GPU, GameUpscaler.effectiveEngine(GameUpscaler.Engine.FSR4_NPU, false))
|
||||
assertEquals(GameUpscaler.Engine.FSR4_LITE_GPU, GameUpscaler.effectiveEngine(GameUpscaler.Engine.FSR4_LITE_NPU, false))
|
||||
assertEquals(GameUpscaler.Engine.FSR4_NPU, GameUpscaler.effectiveEngine(GameUpscaler.Engine.FSR4_NPU, true))
|
||||
assertEquals(GameUpscaler.Engine.XESS, GameUpscaler.effectiveEngine(GameUpscaler.Engine.XESS, false))
|
||||
}
|
||||
|
||||
@Test fun fsr40NpuChoicesSavedEarlierRunFullFsr4OnTheNpu() {
|
||||
val config = GameEnvironment.Config().withEntries("7", mapOf(
|
||||
GameUpscaler.MODE to "fsr", GameUpscaler.ENGINE to "fsr4_0_npu"))
|
||||
assertEquals(GameUpscaler.Engine.FSR4_NPU, GameUpscaler.choice(config, "7")!!.engine)
|
||||
assertEquals("fsr4_1_full_npu", GameUpscaler.Engine.FSR4_NPU.id)
|
||||
assertEquals(GameUpscaler.Engine.SGSR2, GameUpscaler.Engine.byId("sgsr2_gpu"))
|
||||
}
|
||||
|
||||
@Test fun dlssGamesHaveTheSignatureFixOnUnlessSwitchedOff() {
|
||||
val saved = GameEnvironment.Config().withEntries("7", mapOf(GameUpscaler.MODE to "dlss"))
|
||||
assertTrue(GameUpscaler.choice(saved, "7")!!.signatureFix)
|
||||
assertEquals("1", GameUpscaler.entries(GameUpscaler.Choice(GameUpscaler.Mode.DLSS))[GameUpscaler.SIGFIX])
|
||||
val off = GameUpscaler.entries(GameUpscaler.Choice(GameUpscaler.Mode.DLSS, signatureFix = false))
|
||||
assertEquals("0", off[GameUpscaler.SIGFIX])
|
||||
val reread = GameUpscaler.choice(GameEnvironment.Config().withEntries("7", off), "7")!!
|
||||
assertFalse(reread.signatureFix)
|
||||
}
|
||||
|
||||
@Test fun theControlFileUsesTheLayersKeys() {
|
||||
assertEquals("enabled=1\nbackend=fsr4_1_lite_gpu\nsharpness=0.55\nnpu_sync=0\n",
|
||||
GameUpscaler.controlText(GameUpscaler.Engine.FSR4_LITE_GPU, 55, npuSync = false, enabled = true))
|
||||
}
|
||||
|
||||
@Test fun theLayersStatusFileParses() {
|
||||
val status = GameUpscaler.parseStatus(
|
||||
"layer=1\nengine=fsr4\nbackend=fsr4_1_lite_gpu\nbackend_tag=FSR4.1-Lite-GPU\nactive=1\nnpu=0\n" +
|
||||
"render=960x540\noutput=1920x1080\ngpu_us=3250\nhtp_us=0\nreason=ok\nts_ms=99\n")!!
|
||||
assertTrue(status.active)
|
||||
assertEquals("FSR4.1-Lite-GPU", status.backendTag)
|
||||
assertEquals(3.25f, status.gpuMs, 0.001f)
|
||||
assertEquals("1920x1080", status.output)
|
||||
assertNull(GameUpscaler.parseStatus("active=1\n"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class UpscaleBridgeVersionTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun tree(name: String, nvngx: String): File {
|
||||
val dir = tmp.newFolder(name)
|
||||
for (file in UpscaleComponent.BRIDGE_FILES) {
|
||||
File(dir, file).apply { parentFile?.mkdirs() }.writeText(if (file.endsWith("/nvngx.dll")) nvngx else file)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
@Test fun aChangedDllWithTheSameSizeAndDateIsANewVersion() {
|
||||
val old = tree("old", "aaaa")
|
||||
val new = tree("new", "bbbb")
|
||||
for (file in UpscaleComponent.BRIDGE_FILES) {
|
||||
File(old, file).setLastModified(0)
|
||||
File(new, file).setLastModified(0)
|
||||
}
|
||||
assertNotEquals(UpscaleComponent.localVersion(old), UpscaleComponent.localVersion(new))
|
||||
}
|
||||
|
||||
@Test fun theSameFilesWithOtherDatesAreTheSameVersion() {
|
||||
val a = tree("a", "same")
|
||||
val b = tree("b", "same")
|
||||
File(b, UpscaleComponent.BRIDGE_FILES.first()).setLastModified(1_000_000)
|
||||
assertEquals(UpscaleComponent.localVersion(a), UpscaleComponent.localVersion(b))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class UpscaleComponentNpuTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private val runtime = listOf("libQnnHtp.so", "libQnnHtpPrepare.so", "libQnnSystem.so")
|
||||
|
||||
private fun vendor(libs: List<String>, listed: List<String> = libs): Pair<File, File> {
|
||||
val dir = tmp.newFolder("lib64")
|
||||
libs.forEach { File(dir, it).writeText("") }
|
||||
val list = tmp.newFile("public.libraries.txt")
|
||||
list.writeText("# vendor libraries apps may load\n" + listed.joinToString("\n") { "$it 64" } + "\n")
|
||||
return dir to list
|
||||
}
|
||||
|
||||
@Test fun thePhonesOwnRuntimeNamesItsHtpGeneration() {
|
||||
val (dir, list) = vendor(runtime + listOf("libQnnHtpV85Stub.so", "libcdsprpc.so"))
|
||||
assertEquals("v85", UpscaleComponent.systemNpuArch(dir, list))
|
||||
}
|
||||
|
||||
@Test fun librariesTheVendorDoesNotOfferToAppsDoNotCount() {
|
||||
val libs = runtime + "libQnnHtpV85Stub.so"
|
||||
val (dir, list) = vendor(libs, listed = libs - "libQnnHtpPrepare.so")
|
||||
assertNull(UpscaleComponent.systemNpuArch(dir, list))
|
||||
}
|
||||
|
||||
@Test fun twoStubGenerationsAreAmbiguous() {
|
||||
val (dir, list) = vendor(runtime + listOf("libQnnHtpV79Stub.so", "libQnnHtpV81Stub.so"))
|
||||
assertNull(UpscaleComponent.systemNpuArch(dir, list))
|
||||
}
|
||||
|
||||
@Test fun noPublicLibraryListMeansNoSystemRuntime() {
|
||||
assertNull(UpscaleComponent.systemNpuArch(tmp.newFolder("empty"), File(tmp.root, "missing.txt")))
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,221 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d
|
||||
|
||||
---
|
||||
|
||||
## 2026-12-05 - `feat/neural-upscaler`: brought up to main, stall fix device-proven in Hellblade (+10-12 %)
|
||||
|
||||
- **Why:** user 12-05 ~17:4x EST: "bring our npu upscaling branch up to main and install it". The branch was 56
|
||||
commits behind main. The phone's DroidDeck had been moved to the Preview build of main `423f600d` at 17:45 EST
|
||||
through DroidDeck's own Updates screen, so the earlier test build (`97188d37`) was no longer installed.
|
||||
- **Built:** backup ref `refs/backup/20261205/feat-neural-upscaler-before-main-sync` (= `18102ef5`); merge of main
|
||||
`423f600d` = `898b6376`, no conflicts. Files changed on both sides: SessionService.kt, FrontEndSetup.kt,
|
||||
SessionOverlay.kt, strings.xml, droiddeck-game-env, test_game_environment.py (234 tests OK locally, isolated
|
||||
env). Main did not touch `tools/bionic-runtime/tool`, so the bionic patch script still applies. Test branch
|
||||
`test/neural-upscaler-rm12` = `f80d581e` (merge + the debuggable commit, never merge).
|
||||
- **CI:** Build APK 47579062115 (headSha `f80d581e`) green, all jobs (skips = the usual cached / PR-only steps);
|
||||
Unit tests 47579064807 (headSha `898b6376`) green.
|
||||
- **Installed (Red Magic, 12-05 18:02 EST):** `/sdcard/Download/DroidDeck-upscale-rm12-f80d581e-pubg.apk`, sha256
|
||||
`79242728...`, signer b241ea7d, debuggable; installed base.apk hash == staged; `run-as` works; crash buffer empty
|
||||
after install. DroidDeck-Bionic r104 `proton` + `bionic/launch.sh` on the phone == branch (`edb9c6c6` /
|
||||
`e8890a4f`), 24 bridge DLLs present. Proof level: installed, app not opened, no game run yet.
|
||||
- **Stall fix:** committed `69f4d4ad` (GPU waits on a host-set event in the next frame; Full + Lite NPU paths;
|
||||
`DROIDDECK_UPSCALE_NPU_CPU_WAIT=1` = old wait). Compiles clean (glibc build + Android-target clang syntax check).
|
||||
Test branch `test/neural-upscaler-rm12-gpuwait` = `9aa10e10`, Build APK 47579674322 green (both layer copies carry
|
||||
the change). Installed on the Red Magic 12-05 18:30 EST (user: "install it"): `DroidDeck-upscale-rm12-9aa10e10-pubg.apk`,
|
||||
sha256 `26d315a4...`, installed hash == staged, debuggable, crash buffer empty. No game run yet (user: "no
|
||||
cyberpunk yet"). Proof level: installed, not device-tested.
|
||||
- **Test games + engine round (user 12-05 ~19:5x EST: "test each upscale, record metrics and acquire screenshots"):**
|
||||
user installed Hi-Fi RUSH (DLSS + XeSS files) and Hellblade: Senua's Sacrifice (DLSS file) from DroidDeck's Xbox
|
||||
store and ran both on DroidDeck-Bionic r104 (upscaler was off then). Set: Hellblade (game id 3789431815) mode
|
||||
`dlss`, Hi-Fi RUSH (3167215550) mode `fsr` (XeSS route), engine `fsr4_1_full_npu`, log on; settings backup
|
||||
`/root/src/npu-rm/game-environment.json.bak-1205e`. Plan per game: enable DLSS/XeSS in the game's options, then
|
||||
`engine-round.sh` (live switch: off, fsr3_gpu, xess3_gpu, sgsr2_gpu, Lite GPU/NPU, Full GPU/NPU, NPU sync) with fps,
|
||||
GPU/NPU ms, GPU load, temperatures and 2 screenshots per engine (phone Download/upscaler-test-20261205), then a
|
||||
relaunch with `DROIDDECK_UPSCALE_NPU_CPU_WAIT=1` for the NPU engines. Resume: rerun the round on a running game;
|
||||
restore settings from the backup at the end.
|
||||
- **Hi-Fi RUSH round 1 (20:00-20:09 EST, build `9aa10e10`, XeSS Performance 795x360 -> 1590x720, main-menu scene, GPU
|
||||
96-99 %):** fps / GPU ms / NPU ms: stretch ~108; FSR 3.1 ~87 / 3.0; XeSS 3 ~58 / 11.0; SGSR 2 ~88 / 1.4; Lite GPU
|
||||
~51-57 / 9.8; Lite NPU async ~57 / 6.6 / 5.9, sync ~52; Full GPU ~21 / 36.1; Full NPU async ~53-56 / 6.3 / 6.4, sync
|
||||
~49. Stretch at the end 81 fps (battery 48 C, thermal drift). Game input stopped reaching the game after the round;
|
||||
closed by ending the process (no leftovers, no crash). Next: same scene with `DROIDDECK_UPSCALE_NPU_CPU_WAIT=1`.
|
||||
- **Hi-Fi RUSH old vs new NPU wait (20:13-20:25 EST, same scene, 2 cycles each, phone hot 48-50 C):** old
|
||||
(`NPU_CPU_WAIT=1`): stretch 56-58, Full NPU 41-42, Lite NPU 40-43; new (default): stretch 60-61, Full NPU 40-41,
|
||||
Lite NPU 42-44. No measurable difference: this scene is GPU-bound (GPU ~96 % in both modes), and FSR 4.1 NPU costs
|
||||
6.3-7.6 ms of GPU passes here (FSR 3.1: 3.0 ms, SGSR 2: 1.4 ms). The stall seen in Cyberpunk (GPU 90-93 % with FSR
|
||||
4.1) is not tested with the fix yet. No crash or GPU hang in 3 launches. Next: Hellblade (DLSS route).
|
||||
- **Hellblade (DLSS route, DX12, DLSS Performance 640x360 -> 1280x720), 20:30-21:21 EST:** DLSS selectable with the RTX
|
||||
spoof; round 1 on the menu face scene, GPU 99 %, no drift: stretch ~104; FSR 3.1 ~90 / 1.4 ms; XeSS 3 ~61.5 / 6.8;
|
||||
SGSR 2 ~94 / 1.1; Lite GPU ~53 / 9.7; Lite NPU async ~57, sync ~52; Full GPU ~22 / 35.6; Full NPU async ~53.7, sync ~48.
|
||||
**Old vs new NPU wait, paired, same main-menu scene, stretch ~122 in both:** old: Full NPU 53-55 fps at GPU 84-87 %,
|
||||
Lite NPU 59-61 at GPU 88-90 %; new: Full NPU 60.6-61.3 at GPU 98-99 %, Lite NPU ~66 at GPU 98-99 %. **The fix works
|
||||
here: +12 % Full, +10 % Lite, GPU no longer idles.** (Hi-Fi RUSH showed no change: its GPU was already ~96 % busy.)
|
||||
Device-proven on the Red Magic, build `9aa10e10`. Two Hellblade starts failed right after a killed session (guest
|
||||
exits after 2 s, Xwayland "Broken pipe"); a later start worked (transient, cause unproven). In both games the game
|
||||
stopped taking pad input after a while (Steam re-sets the virtual Deck controller features; cause unproven), so
|
||||
games were closed by ending the process. Game settings changed for the tests: Hi-Fi RUSH V-Sync off, frame limit
|
||||
120, Intel XeSS Performance; Hellblade V-Sync off, DLSS Performance. DroidDeck HUD went to the strip layout by an
|
||||
on-screen Menu-button tap.
|
||||
- **Resume point:** if the session dies, check the two runs above; `bash /root/src/npu-rm/sign-stage.sh <build run>
|
||||
f80d581e` (temp key dir must exist; delete it after signing). Rollback = `/sdcard/Download/DroidDeck-0.7.11-pubg-rollback.apk`
|
||||
or the pulled Preview APK `/root/src/npu-rm/installed/now-1745.apk` (`adb install -r`).
|
||||
- **Also 12-05:** frame-stall cause found in code (not fixed yet): in the default async NPU mode the layer's
|
||||
recording thread waits on the CPU for the previous frame's NPU result (`fsr411_full_gpu.c` and `fsr412_lite.c`,
|
||||
up to 200 ms), and that result needs the GPU to finish the previous frame first, so CPU and GPU take turns.
|
||||
Planned fix: the next frame's command buffer waits on the GPU for a host-set event instead (switch to go back:
|
||||
`DROIDDECK_UPSCALE_NPU_CPU_WAIT=1`).
|
||||
|
||||
---
|
||||
|
||||
## 2026-12-04 - `feat/neural-upscaler`: Winlator-NeuralScale r5 ported, non-root parts only (CI running)
|
||||
|
||||
- **Why:** upstream r5 (`71c140d9`) adds full FSR 4.1 on the NPU, a ghosting fix, S8/U8 Lite graphs, Snapdragon GSR 2
|
||||
and D3D11 DLSS. The user asked for those five and nothing that needs root.
|
||||
- **Built:** `74ece6c8` = three-way merge of layer + bridges (base `a0ab6b0f`), new `sgsr2_gpu.c` + shaders,
|
||||
`wl_dxvk_interop.h`; data files re-pinned to `71c140d9` (89 files, sha256); new engine `sgsr2_gpu`, NPU engine id
|
||||
`fsr4_1_full_npu` (saved `fsr4_0_npu` maps to it: FSR 4.0 is gone upstream); XeSS 3 kept (upstream maps `xess` to
|
||||
FSR 3 and dropped Intel's runtime in `cb3ae04e`; we still fetch it from `a0ab6b0f`); NPU detection stays ours
|
||||
(`DROIDDECK_UPSCALE_NPU`), upstream's SoC list removed; full-FSR-4-on-Turnip guard now opt-in
|
||||
(`DROIDDECK_UPSCALE_FULL_OFF_ON_TURNIP=1`). Not ported: RootPerfManager, RootThermal*, GPU clock floor, bypass charging.
|
||||
- **Checked locally:** all 8 layer files compile and link for Android (clang, Khronos headers, -Wall clean); the
|
||||
glibc stub variant compiles; `tools/tests/test_game_environment.py` 231 OK (isolated HOME). Bridge DLLs: CI only.
|
||||
- **CI:** Build APK 47450218949 (`d6f8736e`) FAILED in "Prepare verified components": the glibc layer build has no
|
||||
`sys/system_properties.h` (upstream r5 include; my local check compiled with Android headers, so it missed it).
|
||||
Fix `1a621bcf` (include dropped, heartbeat write checked); `build-glibc.sh` now run locally with the container's gcc
|
||||
= builds, 0 warnings. Rerun Build APK 47450693166 (`23621838`) FAILED at the bridges: `nvngx.dll` did not link
|
||||
(merge kept our old D3D11 `PopulateParameters` line calling the removed "DLSS unavailable" helper). I had wrongly
|
||||
read a cache-hash line in run 1 as "bridges built". Fix in the next commit; all six DLLs now built locally with
|
||||
mingw-w64 13.2 (`tools/upscale/bridges/build.sh`), exports match.
|
||||
- **CI run 3:** Build APK 47451847785 GREEN on `e67bd76e` (= `379198e4` code + the debuggable-only commit): layer glibc
|
||||
built, 6 bridges match their exports, APK compiled. App unit tests (separate workflow) 47452868772 on `379198e4`:
|
||||
5512 tests, 0 failures (GameUpscalerTest 8, UpscaleComponentNpuTest 4).
|
||||
- **Installed (user yes, 19:23 EST):** Red Magic 12 Pro, pubg variant signed b241ea7d, installed sha256 `65e09d96`;
|
||||
the 24 new bridge DLLs copied to the app's external `droiddeck-upscale/bridges`.
|
||||
- **Bug found while staging:** the local-copy bridge stamp is `local-<libxess size>-<mtime>`; CI DLLs have mtime 0 and
|
||||
libxess.dll kept its size (31232), so the app would keep the old DLLs. Test worked around by removing the staged
|
||||
`.pack` (backup `.pack.bak-r5`); fix = stamp from the files' contents.
|
||||
- **First run (XeSS DX12 demo, 19:27 EST):** menu lists Snapdragon GSR 2 and FSR 4 on NPU; Full FSR 4.1 S8 graph compiled
|
||||
on the phone's V85 NPU in 2.65 s and ran zero-copy (GPU 6.5 ms + NPU 5.4 ms, 960x540 to 1080p); the depth stand-in
|
||||
for depth-less games logged. Most status rows were junk: the game still loaded the OLD bridge DLLs, because
|
||||
`ensure()` staged only when no DLLs were staged. Fix `aabacc10` (re-stage when present, content-hash stamp, test).
|
||||
For this test the 24 new DLLs were copied into the rootfs by hand (run-as), hashes == CI.
|
||||
- **CI:** Build APK 47455548997 (`50864970` = `aabacc10` + debuggable commit), unit tests 47455552638.
|
||||
- **Device results (19:37-19:58 EST, new DLLs):** XeSS DX12 round: every engine runs (Full NPU sync 4.6+3.3 ms,
|
||||
Full GPU 27.1 ms, Lite NPU 5.0+4.9, Lite GPU 7.2, SGSR 2 1.8, FSR 3 3.3, XeSS 11.6), BUT Full FSR 4.1 shows a black
|
||||
picture in DX12: 0 coloured pixels in 9/9 shots (`/root/src/npu-rm/tools/pngstat.py`), others 28-32k. XeSS Vulkan
|
||||
sample: Full shows the picture (GPU and NPU). DLSS sample with `-d3d11`: same NGX GetFeatureRequirements
|
||||
PlatformError as D3D12, raised before our bridge (D3D11 DLSS untested).
|
||||
- **Fixes:** `83de9e38` guard at dispatch: D3D12 frames on Turnip -> Lite (`FULL_ON_TURNIP=1` forces Full);
|
||||
`2446d48e` test switches `FULL_DIRECT_OUT=0` / `FULL_AUTO_EXPOSURE=0`. Prime suspect: the Tier 1.1 direct write
|
||||
into the game's output, which only D3D12 frames take (exactly 1920x1080 output). Upstream validated DX12 only with
|
||||
Cyberpunk 2077 (README).
|
||||
- **CI:** 47457143185 failed (flaky test_dircache_preload + IME download reset), cancelled; 47459802031 (`2446d48e`)
|
||||
green after a rerun of the IME download step. Staged APK sha256 `6f267e61`; user said "device is yours".
|
||||
- **Picture tests on `2446d48e` (installed 20:36 EST, `/root/src/npu-rm/fulltest.sh`):** A direct write off -> black
|
||||
0/6; C direct write + exposure pass off -> black 0/6 (hdr=1); E `VKD3D_DISABLE_EXTENSIONS=VK_EXT_descriptor_buffer`
|
||||
with the direct write on -> picture 5/6. Root cause: vkd3d-proton's own descriptor buffers in the command buffers
|
||||
the upscaler records into break Full's descriptor-buffer passes on Turnip.
|
||||
- **Fix `7aa54ab9`:** the layer hides `VK_EXT_descriptor_buffer` from games (still uses it itself;
|
||||
`APP_DESCRIPTOR_BUFFER=1` shows it); Lite fallback only when a game enables it anyway; test switches removed.
|
||||
CI Build APK 47463181144 (`26811a77`).
|
||||
- **12-05 device results (builds `26811a77`, then `3bd1d6f9`):** fix device-proven: XeSS DX12 sample Full GPU/NPU show the
|
||||
picture; measured all-engine rounds (4 shots each) DX12 + Vulkan: every engine shows the picture. Staging fix
|
||||
`0750f2d0` proven ("upscaler bridges staged from local-<hash>: 24/24", and again after a real DLL change).
|
||||
- **Cyberpunk 2077 (DX12, XeSS route):** Full FSR 4.1 NPU runs on the title scene, 795x360 -> 1590x720, GPU 6.0 ms +
|
||||
NPU 5.8 ms, picture correct. Gotcha: UserSettings.json options are read by `index`, not `value`.
|
||||
- **vkd3d descriptor buffers hidden vs shown (Cyberpunk title, Lite NPU):** ~135 vs ~126 fps (noise) -> the fix costs
|
||||
nothing.
|
||||
- **DLSS:** the NGX "PlatformError" was NGX's signature check; with `DROIDDECK_UPSCALE_SIGFIX=1` the DLSS sample passes it.
|
||||
D3D11 then failed in EvaluateFeature: upstream's `extract_ngx_dx11_res` zeroed VkImageCreateInfo, DXVK returns
|
||||
E_INVALIDARG unless sType is IMAGE_CREATE_INFO. Fix `ffe46fe5`. DLSS sample now runs Full FSR 4.1 NPU in D3D11
|
||||
(1280x720 -> 2560x1440, GPU 5.1 + NPU 4.6 ms, ~52 fps) and in D3D12 (GPU 5.1 + NPU 4.4-6.0 ms, ~49 fps).
|
||||
SIGFIX stays opt-in (default = user decision).
|
||||
- **CI:** Build APK 47488918399 (`5546b35e` = `ffe46fe5` + the debuggable-only commit), green; installed on the phone
|
||||
12-05 02:1x EST (sha256 `cfbc4be0`) with its CI-built bridge DLLs. Final device check with exactly these files is
|
||||
still owed (phone screen locked at 02:03 EST).
|
||||
- **Real-game DLSS still open:** Bright Memory: Infinite (UE4, D3D12) never loads the bridge's nvapi64.dll ("Failed to
|
||||
initialize NVAPI", no bridge log), so the signature-fix hooks do not run and NGX's own loader rejects the core
|
||||
("failed to load C:\windows\system32\_nvngx.dll", D3D12_Init FeatureNotSupported). Putting the DLLs into system32
|
||||
did not help (`73442ad3`, reverted in `bb5c53a7`). The game also picks its upscaler from its own menu.
|
||||
- **Not used:** a Deep Rock Galactic copy that carries a DRM-bypass DLL.
|
||||
- **Real-game DLSS (Bright Memory: Infinite), 12-05 02:2x-03:0x EST:** with nvapi64.dll + NGX DLLs in its system32
|
||||
(`04a67aa7` now does this in DLSS mode) the signature-fix hooks install and NGX reports "DLSS supported 1"; the game
|
||||
creates DLSS features (795x360 -> 1590x720, title 5 -> 20 fps). The bridge's new log shows attach ok, seam ready,
|
||||
images found, dispatch 1, yet the layer upscaled nothing (status reason ok, api None, 0x0). `e5d7bddf` guessed a
|
||||
full buffer table (not confirmed); cause found after: the layer read doorbells from the last mailbox (the XeSS
|
||||
bridge's), fixed by pairing markers with their mailbox (`e422ab68`).
|
||||
- **Device-proven 12-05 03:09-03:31 EST, Red Magic 12 Pro, signed test build 97188d37 (= feat 0cb6afbf + test
|
||||
marker, CI 47496699289 green; unit tests 47495215764: 5515 tests, 0 failures):**
|
||||
- Bright Memory: Infinite (D3D12, Unreal, Streamline): status `api=DLSS (DX12) 640x360 -> 1280x720`,
|
||||
FSR 4.1 Full on the NPU, GPU 4.7 ms + NPU 4-6 ms, HUD "FSR4.1-Full-NPU 4.4ms", picture correct, no crash.
|
||||
Its system32 holds the CI copies of nvapi64/_nvngx (placed by game-env `04a67aa7`).
|
||||
- DLSS demo with NO signature-fix entry in its settings (default on, `d47ed325`): bridge log shows the hooks
|
||||
(WinVerifyTrust/CryptQueryObject/nvngx redirect); D3D12 46.8-48.7 fps, D3D11 38.5-50.0 fps,
|
||||
1280x720 -> 2560x1440, no crash.
|
||||
- All-engine rounds (XeSS samples DX12 + Vulkan, 9 engine/sync specs each): every engine active with its own
|
||||
tag, picture present, same flicker pattern as the rounds before this change, no crash.
|
||||
- Open: Deep Rock Galactic not tested (the installed copy is a cracked build; not worked around).
|
||||
- **Cyberpunk A/B on the phone (12-05 04:33-05:06 EST, unplugged, build 97188d37):** game's own benchmark via launch
|
||||
option `-benchmark -skipStartScreen` (writes summary.json + frames.csv, exits); window 1590x720, upscaler runs on the
|
||||
game's XeSS Performance (795x360). One run each, native repeated last (same 11.41 avg = no heat drift).
|
||||
| setup | avg | 1% low | W (battery, benchmark only) | fps/W | GPU load (HUD) |
|
||||
|---|---|---|---|---|---|
|
||||
| native | 11.41 | 7.9 | 10.09 (repeat 9.67) | 1.13 | 99 % |
|
||||
| FSR 4.1 Full NPU | 12.25 | 8.5 | 9.71 | 1.26 | 92-93 % |
|
||||
| SGSR 2 | 15.89 | 10.0 | 12.79 | 1.24 | 99 % |
|
||||
| plain stretch (upscaler off live) | 15.67 | 9.6 | 10.39 | 1.51 | 99 % |
|
||||
Findings: (1) FSR 4.1 Full NPU costs ~18 ms per frame vs the plain stretch (81.6 vs 63.8 ms) while the status reports
|
||||
GPU 8.2 + NPU 6.2 ms and the GPU sits partly idle: the async NPU path still stalls each frame (same pattern as Bright
|
||||
Memory: 15 vs 20 fps). Open, not investigated. (2) With FSR 4.1 Full NPU on, Cyberpunk hangs on exit after the
|
||||
benchmark (black, GPU 0 %, process alive 6+ min); SGSR 2, stretch, native exit normally. Open. (3) Picture (zoomed
|
||||
crops at the same spot): FSR 4.1 close to native; SGSR 2 looks nearly as blocky as the plain stretch.
|
||||
The benchmark moves its camera at most 66 ms per frame: every run = 64.2 s of path (used to match screenshots).
|
||||
Report: /sdcard/Download/Cyberpunk-upscaler-test-RM12-20261205.html (phone).
|
||||
- **Correction (12-05 13:0x EST):** the report's "same spot" screenshot rows were NOT the same spot (e.g. native = a
|
||||
close-up of a woman, FSR 4.1 = the pool table, SGSR 2 = a man in smoke, stretch = the bar), and the zoomed crops
|
||||
were taken at different distances. The 66 ms route model itself holds (64.15-64.19 s in all five runs); the error
|
||||
was mapping screenshot clock times onto the benchmark. Finding (3) above is therefore not reliable.
|
||||
- **Fair test (12-05 13:2x EST, running):** same DroidDeck 720p (1590x720) and game settings for every setup; 7
|
||||
numbers runs (native, FSR 4.1 NPU and SGSR 2 at XeSS Performance 795x360 and Quality 1060x480, plain stretch,
|
||||
native repeat), then 6 picture runs with back-to-back raw screenshots, matched across runs by image. Phone on
|
||||
the charger: no watts this round. Scripts: npu-rm `cp-ab3.sh` / `cp-ab3-all.sh` (local test kit).
|
||||
Result at 1590x720 (one run each): native 11.25 fps, FSR 4.1 NPU Quality 10.33 (-8 %), Performance 11.67 (+4 %),
|
||||
SGSR 2 Quality 12.91 (+15 %), Performance 14.28 (+27 %), plain stretch 15.01 (+33 %); GPU load (HUD) 89-93 % with
|
||||
FSR 4.1, 98-99 % otherwise. Same-spot pictures: FSR 4.1 close to native at both settings; SGSR 2 shows a blocky
|
||||
mosaic on moving people and edges (our shader uses Qualcomm's 9-tap filter, so this looks like a setup problem;
|
||||
not checked yet); plain stretch is soft, not blocky. FSR 4.1 exit hang seen again in all 4 FSR 4.1 runs.
|
||||
- **Rerun at 1280x720 (user, 12-05 14:34-15:24 EST, done):** same plan with the game at 1280x720
|
||||
(`DROIDDECK_GAME_RESOLUTION`) on DroidDeck's 720p output; XeSS Quality 853x480, Performance 640x360. Phone
|
||||
unplugged. Warm native (battery 41-42 C) 13.23 / 13.44 fps (the first native run started at 36 C: 16.02, not
|
||||
used). FSR 4.1 NPU Quality 11.83 (-12 %), Performance 13.54 (+1 %); SGSR 2 Quality 14.91 (+11 %), Performance
|
||||
17.16 (+28 %); plain stretch 17.45 (+30 %). GPU load (HUD) 90-93 % with FSR 4.1, 98-99 % otherwise. Pictures at
|
||||
the same spots: same verdict as at 1590x720. Report replaced in the phone's Download
|
||||
(Cyberpunk-upscaler-test-RM12-20261205.html, 8 MB). Test-kit fixes: close Wine services left after the game
|
||||
(they kept a session open once), route start = after the last run of 5+ black frames. Cyberpunk restored
|
||||
(no DroidDeck entry, original UserSettings, launch option empty).
|
||||
- Lesson: phone temperature moves fps by ~20 % here (cool start 16.0 vs warm 13.4 fps, same setup); every
|
||||
numbers run must start at the same warmth, and a native repeat at the end is needed to see it.
|
||||
- **User decisions 12-05:** (1) signature fix ON by default in DLSS mode (switch stays, off is stored as `0`);
|
||||
(2) no PR yet: keep testing and fixing on the branch.
|
||||
|
||||
---
|
||||
|
||||
## 2026-12-04 - `feat/neural-upscaler`: NPU engines on the phone's own QNN runtime (Red Magic 12 Pro, no root)
|
||||
|
||||
- **Why:** the upscaler's NPU engines only knew the bundled QNN files for HTP v79/v81. The Red Magic 12 Pro (SM8975,
|
||||
HTP V85) ships Qualcomm's QNN runtime and lists it for apps in `/vendor/etc/public.libraries.txt`.
|
||||
- **Built:** main merged in (`94bcfca5`); `c18aa23a` + `94754fea`: the app takes the HTP generation from the vendor's
|
||||
`libQnnHtpV<NN>Stub.so` and passes `DROIDDECK_UPSCALE_HTP_ARCH`; the layer uses the bundled QNN files only for an
|
||||
arch whose skel came with them, else the vendor libraries by name; no NPU download group on such phones.
|
||||
- **CI:** Build APK 47341155158 green (test branch `test/neural-upscaler-rm12` = this + a debuggable-only commit,
|
||||
never merged; 47338667435 failed on a Maven 429 and on my `this.npu()` inside `buildSet`).
|
||||
- **Device test (Red Magic 12 Pro, DroidDeck-Bionic r104 with this branch's tool lines):** the NPU engines are offered
|
||||
in the game menu; XeSS SDK demos (DX12, Vulkan), 960x540 to 1080p: FSR 4 Lite on the NPU = NPU 1.3-1.6 ms per frame
|
||||
and 2-2.5 ms less GPU time than FSR 4 Lite on the GPU, picture correct; FSR 4.0 on the NPU (3.5-3.7 ms), XeSS 3
|
||||
(10 ms) and the basic upscaler run; the NPU graph compiles on the phone in about 2 s and loads from cache after.
|
||||
- **Open:** XeSS runtime missing on a game's first launch (staged before the prefix exists); DLSS demo stops at NGX
|
||||
GetFeatureRequirements (PlatformError) after the VC++ 14 component; FSR 4.1.2 log text names v81 on every arch.
|
||||
|
||||
---
|
||||
|
||||
## 2026-10-16/17 - `feat/x86-64-steam-client`: web helper on the GPU, org main, review rounds
|
||||
|
||||
- **x86-64 web helper on the GPU** (`f603a085`): the client's own steamwebhelper runs ANGLE's GL backend
|
||||
@@ -1444,6 +1659,11 @@ State: **main = `90c7574`** (PR #14 merge), main build run 35895701784. No tag,
|
||||
- `app/src/main/cpp/waylandcomp/` - the compositor (shared lineage with Bannerlator).
|
||||
|
||||
## Lessons learned (don't repeat these)
|
||||
|
||||
- Check the PRoot layer with `tools/upscale/layer/build-glibc.sh` and a real glibc gcc (`CC=/usr/bin/gcc` in the
|
||||
container), not clang with an Android target: Android headers hide glibc-only breaks (2026-12-04, r5 port).
|
||||
- Build the bridge DLLs locally (`apt install gcc-mingw-w64-x86-64`, `tools/upscale/bridges/build.sh <dir>`) before CI
|
||||
after any merge touching them; read the CI step's own output lines, not a hash line, before saying a step passed.
|
||||
- Nothing in teardown may do bulk filesystem work on the main thread (0.1.1's ANR).
|
||||
- A CI closure check on a multi-line variable must flatten it first (`libaaudio.so` refusal).
|
||||
- A runtime script must be named `bannerlator-*` or CI never packages it.
|
||||
|
||||
@@ -51,6 +51,7 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
DXVK_LOG_PATH|VKD3D_LOG_FILE|MESA_LOG_FILE) ;;
|
||||
DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;;
|
||||
DROIDDECK_GUEST_ROOT) ;;
|
||||
DROIDDECK_UPSCALE|DROIDDECK_UPSCALE_*|WINEDLLPATH|ADSP_LIBRARY_PATH|PROTON_ENABLE_NVAPI|DXVK_ENABLE_NVAPI|WINE_HIDE_NVIDIA_GPU) ;;
|
||||
VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;;
|
||||
# droiddeck-game-env's original Xbox switches for this layer's Wine and the Xbox VKD3D-Proton build
|
||||
WINE_SPECIAL_APC_INTERRUPT|WINE_MF_DISPLAY_APERTURE|WINE_PRECISE_SLEEP) ;;
|
||||
@@ -92,7 +93,10 @@ echo "driver $DRVDIR"
|
||||
RTD=$APP/.wayland-rt
|
||||
export VK_ICD_FILENAMES=$PACK/adapter/icd.json ADRENOTOOLS_DRIVER_PATH=$DRVDIR/ ADRENOTOOLS_HOOKS_PATH=$PACK/lib
|
||||
export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR")
|
||||
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
|
||||
# The in-game upscaler's layer is in the APK; DroidDeck writes its manifest to DROIDDECK_UPSCALE_LAYER.
|
||||
UPSCALE_LAYER=""
|
||||
[ -n "${DROIDDECK_UPSCALE:-}" ] && [ -n "${DROIDDECK_UPSCALE_LAYER:-}" ] && [ -d "$DROIDDECK_UPSCALE_LAYER" ] && UPSCALE_LAYER=":$DROIDDECK_UPSCALE_LAYER"
|
||||
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer$UPSCALE_LAYER ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
|
||||
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=0
|
||||
echo "WSI forced XWayland bypass disabled (GAMESCOPE_WSI_FORCE_BYPASS=$GAMESCOPE_WSI_FORCE_BYPASS)"
|
||||
[ -e "$RTD/droiddeck-gamescope-limiter" ] && export GAMESCOPE_LIMITER_FILE=$RTD/droiddeck-gamescope-limiter
|
||||
|
||||
@@ -103,6 +103,21 @@ case "$verb" in
|
||||
done
|
||||
# The HUD's GPU-load folder is a guest path; the bionic game writes to it by its Android path.
|
||||
[ -n "${DROIDDECK_GPU_LOAD_DIR:-}" ] && { DROIDDECK_GPU_LOAD_DIR=$(real "$DROIDDECK_GPU_LOAD_DIR"); export DROIDDECK_GPU_LOAD_DIR; }
|
||||
# The in-game upscaler's folders and files (droiddeck-game-env sets them as guest paths); the bridge folder on
|
||||
# WINEDLLPATH and the NPU skeleton folder at the head of ADSP_LIBRARY_PATH as well.
|
||||
for v in DROIDDECK_UPSCALE_DIR DROIDDECK_UPSCALE_CTRL_FILE DROIDDECK_UPSCALE_STATUS_FILE DROIDDECK_UPSCALE_NATIVELIB_DIR; do
|
||||
[ -n "${!v:-}" ] && { printf -v "$v" '%s' "$(real "${!v}")"; export "${v?}"; }
|
||||
done
|
||||
if [ -n "${DROIDDECK_UPSCALE:-}" ] && [ -n "${WINEDLLPATH:-}" ]; then
|
||||
out=""
|
||||
IFS=: read -r -a parts <<< "$WINEDLLPATH"
|
||||
for part in "${parts[@]}"; do [ -n "$part" ] && out="${out:+$out:}$(real "$part")"; done
|
||||
WINEDLLPATH=$out; export WINEDLLPATH
|
||||
fi
|
||||
if [ -n "${DROIDDECK_UPSCALE:-}" ] && [ -n "${ADSP_LIBRARY_PATH:-}" ]; then
|
||||
head=${ADSP_LIBRARY_PATH%%;*}
|
||||
ADSP_LIBRARY_PATH="$(real "$head")${ADSP_LIBRARY_PATH#"$head"}"; export ADSP_LIBRARY_PATH
|
||||
fi
|
||||
# So are the graphics log locations Detailed graphics logs or game debugging set for this launch.
|
||||
for v in DXVK_LOG_PATH VKD3D_LOG_FILE MESA_LOG_FILE; do
|
||||
[ -n "${!v:-}" ] && { printf -v "$v" '%s' "$(real "${!v}")"; export "${v?}"; }
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"tools/vr",
|
||||
"tools/ime",
|
||||
"tools/gpuload",
|
||||
"tools/upscale/layer",
|
||||
"app/src/main/cpp/waylandcomp/generated",
|
||||
"app/src/main/cpp/waylandcomp/src/headpose_shm.h",
|
||||
"app/src/main/cpp/waylandcomp/src/spatialpose_shm.h",
|
||||
@@ -29,7 +30,9 @@
|
||||
"app/src/main/assets/linuxfs/usr/local/share/droiddeck/ibus.profile",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ime/ibus-engine-pinyin",
|
||||
"app/src/main/assets/linuxfs/usr/share/pyzy/db/android.db",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so"
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/VK_LAYER_DROIDDECK_upscale.json"
|
||||
],
|
||||
"ndk": true,
|
||||
"packages": [
|
||||
@@ -273,5 +276,41 @@
|
||||
"lld",
|
||||
"llvm"
|
||||
]
|
||||
},
|
||||
"upscale-bridges": {
|
||||
"script": "tools/components/recipes/upscale-bridges.sh",
|
||||
"inputs": [
|
||||
"tools/upscale/bridges",
|
||||
"tools/components/recipes/upscale-bridges.sh"
|
||||
],
|
||||
"outputs": [
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/_nvngx.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_dx12.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_loader_dx12.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_upscaler_dx12.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_upscaler_vk.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/amd_fidelityfx_vk.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/ffx_fsr2_api_x64.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/ffx_fsr3upscaler_x64.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/libxess.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/nvapi64.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/nvngx.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/x86_64-windows/nvngx_dlss.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/_nvngx.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_dx12.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_loader_dx12.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_upscaler_dx12.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_upscaler_vk.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/amd_fidelityfx_vk.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/ffx_fsr2_api_x64.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/ffx_fsr3upscaler_x64.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/libxess.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/nvapi64.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/nvngx.dll",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/aarch64-windows/nvngx_dlss.dll"
|
||||
],
|
||||
"packages": [
|
||||
"gcc-mingw-w64-x86-64"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_
|
||||
tools/vr/build.sh --native "$D/usr/local/lib/droiddeck-vr"
|
||||
VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
|
||||
tools/gpuload/build.sh --native "$D/usr/local/lib/droiddeck-gpuload"
|
||||
VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
|
||||
tools/upscale/layer/build-glibc.sh "$D/usr/local/lib/droiddeck-upscale-layer"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
bash tools/upscale/bridges/build.sh app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges
|
||||
@@ -1152,6 +1152,228 @@ def directaudio_settings(env):
|
||||
return env
|
||||
|
||||
|
||||
# The in-game upscaler (tools/upscale, ported from Winlator-NeuralScale, GPL-3.0): bridge DLLs stand in for the
|
||||
# game's DLSS / FidelityFX / FSR 2/3 / XeSS DLLs and hand each frame to VK_LAYER_DROIDDECK_upscale. The app keeps
|
||||
# the game's choice in DROIDDECK_UPSCALE_MODE (fsr, dlss, native) and DROIDDECK_UPSCALE_ENGINE/_SHARPNESS/_NPU_SYNC.
|
||||
UPSCALE_ROOT = "/usr/local/lib/droiddeck-upscale"
|
||||
UPSCALE_RUN = "/run/droiddeck-hud/upscale"
|
||||
UPSCALE_MODES = ("fsr", "dlss", "native")
|
||||
UPSCALE_ENGINES = ("fsr4_1_lite_gpu", "fsr4_1_full_gpu", "xess3_gpu", "fsr3_gpu", "sgsr2_gpu", "fsr4_1_full_npu",
|
||||
"fsr4_1_lite_npu")
|
||||
# fsr4_0_npu: saved before full FSR 4.1 replaced FSR 4.0 on the NPU.
|
||||
UPSCALE_ENGINE_ALIASES = {"fsr4_0_npu": "fsr4_1_full_npu"}
|
||||
UPSCALE_NPU_FALLBACK = {"fsr4_1_full_npu": "fsr4_1_full_gpu", "fsr4_1_lite_npu": "fsr4_1_lite_gpu"}
|
||||
UPSCALE_FSR_DLLS = ("libxess", "ffx_fsr3upscaler_x64", "ffx_fsr2_api_x64", "amd_fidelityfx_vk", "amd_fidelityfx_dx12",
|
||||
"amd_fidelityfx_upscaler_vk", "amd_fidelityfx_upscaler_dx12", "amd_fidelityfx_loader_dx12")
|
||||
UPSCALE_DLSS_DLLS = ("nvngx", "_nvngx", "nvngx_dlss", "nvapi64")
|
||||
UPSCALE_XESS = "wl_xess_official.dll"
|
||||
NV_SIGNATURE_OVERRIDE = "{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}"
|
||||
# CurrentControlSet is a link to ControlSet001 in Wine's registry, so only ControlSet001 is written.
|
||||
NGX_KEYS = ("Software\\NVIDIA Corporation\\Global\\NGXCore",
|
||||
"System\\ControlSet001\\Services\\nvlddmkm\\NGXCore")
|
||||
NGX_SIGNATURE_KEYS = ("Software\\NVIDIA Corporation\\Global",
|
||||
"System\\ControlSet001\\Services\\nvlddmkm")
|
||||
|
||||
|
||||
def upscale_registry(prefix):
|
||||
"""NVIDIA's NGX core location and its signature override, which DLSS games read to load nvngx.dll (DLSS mode only)."""
|
||||
path = os.path.join(prefix, "pfx", "system.reg")
|
||||
if not os.path.isfile(path):
|
||||
return False
|
||||
with open(path, encoding="utf-8", errors="replace") as reg:
|
||||
text = reg.read()
|
||||
# Section names in Wine's registry files double their backslashes.
|
||||
present = {line[1:line.find("]")].replace("\\\\", "\\").lower()
|
||||
for line in text.splitlines() if line.startswith("[") and "]" in line}
|
||||
stamp = int(time_now())
|
||||
added = []
|
||||
for key in NGX_KEYS:
|
||||
if key.lower() not in present:
|
||||
added.append("[%s] %d\n\"Enable\"=dword:00000001\n\"FullPath\"=\"C:\\\\windows\\\\system32\"\n"
|
||||
"\"NGXPath\"=\"C:\\\\windows\\\\system32\"\n" % (key.replace("\\", "\\\\"), stamp))
|
||||
for key in NGX_SIGNATURE_KEYS:
|
||||
if key.lower() not in present:
|
||||
added.append("[%s] %d\n\"%s\"=hex:01\n" % (key.replace("\\", "\\\\"), stamp, NV_SIGNATURE_OVERRIDE))
|
||||
if not added:
|
||||
return False
|
||||
with open(path, "a", encoding="utf-8") as reg:
|
||||
reg.write("\n" + "\n".join(added))
|
||||
return True
|
||||
|
||||
|
||||
def time_now():
|
||||
import time
|
||||
return time.time()
|
||||
|
||||
|
||||
def upscale_link(source, target, hard_link=True):
|
||||
"""target = source's bytes: a hard link when both are on one file system (and hard_link), else a copy. Kept when
|
||||
equal."""
|
||||
if os.path.isfile(target) and os.path.getsize(target) == os.path.getsize(source):
|
||||
with open(source, "rb") as a, open(target, "rb") as b:
|
||||
if a.read() == b.read():
|
||||
return
|
||||
staged = target + ".droiddeck-tmp"
|
||||
if os.path.lexists(staged):
|
||||
os.unlink(staged)
|
||||
try:
|
||||
if not hard_link:
|
||||
raise OSError("copy wanted")
|
||||
os.link(source, staged)
|
||||
except OSError:
|
||||
with open(source, "rb") as src, open(staged, "wb") as dst:
|
||||
while True:
|
||||
chunk = src.read(1 << 20)
|
||||
if not chunk:
|
||||
break
|
||||
dst.write(chunk)
|
||||
os.replace(staged, target)
|
||||
|
||||
|
||||
# DLSS games load nvapi64.dll and NGX's core from system32 only (NGXCore FullPath is C:\windows\system32), which
|
||||
# the bridge folder on WINEDLLPATH does not answer. Wine copies the bridges there only when a prefix is created with
|
||||
# the upscaler already on; Bright Memory: Infinite's prefix predates it: "Failed to initialize NVAPI", then NGX
|
||||
# "failed to load C:\windows\system32\_nvngx.dll". With these four in system32 NGX reports "DLSS supported 1".
|
||||
UPSCALE_NGX_FILES = ("nvapi64.dll", "_nvngx.dll", "nvngx.dll", "nvngx_dlss.dll")
|
||||
|
||||
|
||||
def upscale_ngx_files(prefix, bridges, dlss):
|
||||
"""DLSS mode: the bridge's NVAPI and NGX DLLs as files in the prefix's system32. Other modes: our copies go,
|
||||
so a game taken out of DLSS mode no longer sees the NVIDIA stand-in (other files there are left alone)."""
|
||||
system32 = os.path.join(prefix, "pfx", "drive_c", "windows", "system32")
|
||||
if not os.path.isdir(system32):
|
||||
return False
|
||||
for name in UPSCALE_NGX_FILES:
|
||||
source = os.path.join(bridges, "x86_64-windows", name)
|
||||
target = os.path.join(system32, name)
|
||||
if not os.path.isfile(source):
|
||||
continue
|
||||
if dlss:
|
||||
# A copy, not a hard link: something writing over the prefix's nvapi64.dll in place must not change
|
||||
# DroidDeck's staged bridge.
|
||||
upscale_link(source, target, hard_link=False)
|
||||
elif os.path.isfile(target) and os.path.getsize(target) == os.path.getsize(source):
|
||||
with open(source, "rb") as a, open(target, "rb") as b:
|
||||
if a.read() == b.read():
|
||||
os.unlink(target)
|
||||
return True
|
||||
|
||||
|
||||
def upscale_xess(prefix, data):
|
||||
"""Intel's XeSS runtime beside the bridge: libxess.dll loads wl_xess_official.dll from system32. A hard link
|
||||
when the prefix is on the same file system as the data, else a copy."""
|
||||
source = os.path.join(data, "xess", UPSCALE_XESS)
|
||||
if not os.path.isfile(source):
|
||||
return "XeSS runtime not downloaded"
|
||||
upscale_link(source, os.path.join(prefix, "pfx", "drive_c", "windows", "system32", UPSCALE_XESS))
|
||||
return None
|
||||
|
||||
|
||||
def upscale_control(engine, sharpness, npu_sync, run=None):
|
||||
"""The live switch file the layer polls, written from this game's settings at every launch: a file left by the
|
||||
previous game (or the in-game menu) would otherwise win over them."""
|
||||
run = run or UPSCALE_RUN
|
||||
os.makedirs(run, exist_ok=True)
|
||||
staged = os.path.join(run, "ctrl.%d" % os.getpid())
|
||||
with open(staged, "w") as f:
|
||||
f.write("enabled=1\nbackend=%s\nsharpness=%.2f\nnpu_sync=%d\n" % (engine, sharpness / 100.0, 1 if npu_sync else 0))
|
||||
os.replace(staged, os.path.join(run, "ctrl"))
|
||||
|
||||
|
||||
def upscale_settings(env, prefix):
|
||||
"""The game's upscaler choice -> DLL overrides, bridge folder, layer switch and the files the layer reads."""
|
||||
mode = (env.get("DROIDDECK_UPSCALE_MODE") or "").strip().lower()
|
||||
if mode not in UPSCALE_MODES:
|
||||
return env, []
|
||||
notes = []
|
||||
bridges = UPSCALE_ROOT + "/bridges"
|
||||
data = UPSCALE_ROOT + "/data"
|
||||
if not os.path.isfile(os.path.join(bridges, "x86_64-windows", "libxess.dll")):
|
||||
return env, ["in-game upscaler chosen but its bridge pack is not installed; launched without it"]
|
||||
result = dict(env)
|
||||
engine = (env.get("DROIDDECK_UPSCALE_ENGINE") or "").strip().lower()
|
||||
engine = UPSCALE_ENGINE_ALIASES.get(engine, engine)
|
||||
if engine not in UPSCALE_ENGINES:
|
||||
engine = "fsr4_1_lite_gpu"
|
||||
if engine in UPSCALE_NPU_FALLBACK and env.get("DROIDDECK_UPSCALE_NPU") != "1":
|
||||
notes.append("no usable NPU on this device: %s runs as %s" % (engine, UPSCALE_NPU_FALLBACK[engine]))
|
||||
engine = UPSCALE_NPU_FALLBACK[engine]
|
||||
try:
|
||||
sharpness = min(100, max(0, int(env.get("DROIDDECK_UPSCALE_SHARPNESS") or "55")))
|
||||
except ValueError:
|
||||
sharpness = 55
|
||||
result["DROIDDECK_UPSCALE"] = "1"
|
||||
result["DROIDDECK_UPSCALE_DIR"] = data + "/fsr4"
|
||||
result["DROIDDECK_UPSCALE_BACKEND"] = engine
|
||||
result["DROIDDECK_UPSCALE_ENGINE"] = engine
|
||||
result["DROIDDECK_UPSCALE_SHARPNESS"] = "%.2f" % (sharpness / 100.0)
|
||||
result["DROIDDECK_UPSCALE_NPU_SYNC"] = "sync" if env.get("DROIDDECK_UPSCALE_NPU_SYNC") == "1" else "async"
|
||||
result["DROIDDECK_UPSCALE_PRESET"] = "auto"
|
||||
result["DROIDDECK_UPSCALE_POWER"] = env.get("DROIDDECK_UPSCALE_POWER") or "balanced"
|
||||
result["DROIDDECK_UPSCALE_CTRL_FILE"] = UPSCALE_RUN + "/ctrl"
|
||||
result["DROIDDECK_UPSCALE_STATUS_FILE"] = UPSCALE_RUN + "/status"
|
||||
result["DROIDDECK_UPSCALE_NATIVELIB_DIR"] = data + "/jni"
|
||||
result["DROIDDECK_UPSCALE_VRAM_OVERRIDE"] = "0"
|
||||
result["ADSP_LIBRARY_PATH"] = data + "/fsr4/adsp;/vendor/dsp/cdsp;/vendor/lib/rfsa/adsp;/system/lib/rfsa/adsp"
|
||||
own = result.get("WINEDLLPATH")
|
||||
result["WINEDLLPATH"] = bridges + (":" + own if own else "")
|
||||
overrides = ["%s=b,n" % name for name in UPSCALE_FSR_DLLS] + ["wl_xess_official=n"]
|
||||
dxvk = None
|
||||
if mode == "dlss":
|
||||
overrides += ["%s=b,n" % name for name in UPSCALE_DLSS_DLLS]
|
||||
result["DROIDDECK_UPSCALE_SPOOF_DLSS"] = "1"
|
||||
result["DROIDDECK_UPSCALE_GPU_SPOOF"] = "rtx"
|
||||
result["PROTON_ENABLE_NVAPI"] = "1"
|
||||
result["DXVK_ENABLE_NVAPI"] = "1"
|
||||
result["WINE_HIDE_NVIDIA_GPU"] = "0"
|
||||
dxvk = 'dxgi.hideNvidiaGpu = False; dxgi.customVendorId = 10de; dxgi.customDeviceId = 1f08; dxgi.customDeviceDesc = "NVIDIA GeForce RTX 2060"'
|
||||
# NGX rejects the bridge DLLs without the signature fix; on unless this game switched it off ("0").
|
||||
result["DROIDDECK_UPSCALE_SIGFIX"] = "0" if env.get("DROIDDECK_UPSCALE_SIGFIX") == "0" else "1"
|
||||
try:
|
||||
if prefix and upscale_registry(prefix):
|
||||
notes.append("NVIDIA NGX registry entries added to the prefix (DLSS mode)")
|
||||
except OSError as error:
|
||||
notes.append("NGX registry entries not written (%s)" % error)
|
||||
try:
|
||||
if prefix:
|
||||
upscale_ngx_files(prefix, bridges, True)
|
||||
except OSError as error:
|
||||
notes.append("NVAPI/NGX DLLs not placed in system32 (%s)" % error)
|
||||
elif mode == "native":
|
||||
result["DROIDDECK_UPSCALE_SPOOF_DLSS"] = "0"
|
||||
result["DROIDDECK_UPSCALE_GPU_SPOOF"] = "rdna4"
|
||||
result.setdefault("VKD3D_SHADER_MODEL", "6_8")
|
||||
dxvk = 'dxgi.customVendorId = 1002; dxgi.customDeviceId = 7550; dxgi.customDeviceDesc = "AMD Radeon RX 9070 XT"'
|
||||
else:
|
||||
result["DROIDDECK_UPSCALE_SPOOF_DLSS"] = "0"
|
||||
result["DROIDDECK_UPSCALE_GPU_SPOOF"] = "off"
|
||||
if prefix and mode != "dlss":
|
||||
try:
|
||||
upscale_ngx_files(prefix, bridges, False)
|
||||
except OSError:
|
||||
pass
|
||||
if dxvk:
|
||||
current = result.get("DXVK_CONFIG", "").strip().rstrip(";").strip()
|
||||
result["DXVK_CONFIG"] = current + "; " + dxvk if current else dxvk
|
||||
own = result.get("WINEDLLOVERRIDES")
|
||||
result["WINEDLLOVERRIDES"] = (own + ";" if own else "") + ";".join(overrides)
|
||||
# Intel's runtime goes into every upscaler game once it is downloaded, so XeSS 3 also works when it is
|
||||
# picked in the in-game menu; a game started on XeSS 3 without it falls back to FSR.
|
||||
if prefix and (engine == "xess3_gpu" or os.path.isfile(os.path.join(data, "xess", UPSCALE_XESS))):
|
||||
try:
|
||||
problem = upscale_xess(prefix, data)
|
||||
except OSError as error:
|
||||
problem = str(error)
|
||||
if problem and engine == "xess3_gpu":
|
||||
notes.append("XeSS: %s; the layer falls back to FSR" % problem)
|
||||
try:
|
||||
upscale_control(engine, sharpness, env.get("DROIDDECK_UPSCALE_NPU_SYNC") == "1")
|
||||
except OSError as error:
|
||||
notes.append("upscaler control file not written (%s)" % error)
|
||||
notes.append("in-game upscaler: mode %s, engine %s, sharpness %d%%" % (mode, engine, sharpness))
|
||||
return result, notes
|
||||
|
||||
|
||||
DIRT_GAMES = {"dirt3_game": "dirt3", "showdown": "dirtshowdown", "showdown_avx": "dirtshowdown"}
|
||||
DIRT_WS2 = "/usr/local/lib/droiddeck-dirt/ws2_32.dll"
|
||||
DIRT_MARKER = b"droiddeck-dirt-ws2_32"
|
||||
@@ -1843,6 +2065,9 @@ def main():
|
||||
env = dict(env, **installer)
|
||||
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
|
||||
if waiting:
|
||||
env, upscale_notes = upscale_settings(env, prefix_path)
|
||||
for note in upscale_notes:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
before_debug = env
|
||||
env = apply_game_debug_logs(env, config, debug_dir)
|
||||
if env is not before_debug:
|
||||
|
||||
@@ -98,6 +98,11 @@ pack powervr "$repo/app/src/main/assets/hybris" runtime.tzst version.txt
|
||||
[ ! -f "$linuxfs/droiddeck-ubisoft/droiddeck-upc.exe" ] || pack ubisoft "$linuxfs/droiddeck-ubisoft" droiddeck-upc.exe
|
||||
[ ! -f "$linuxfs/droiddeck-rockstar/Launcher64.exe" ] || pack rockstar "$linuxfs/droiddeck-rockstar" Launcher32.exe Launcher64.exe
|
||||
[ ! -f "$linuxfs/droiddeck-dirt/ws2_32.dll" ] || pack dirt "$linuxfs/droiddeck-dirt" ws2_32.dll
|
||||
upscale=(_nvngx.dll amd_fidelityfx_dx12.dll amd_fidelityfx_loader_dx12.dll amd_fidelityfx_upscaler_dx12.dll
|
||||
amd_fidelityfx_upscaler_vk.dll amd_fidelityfx_vk.dll ffx_fsr2_api_x64.dll ffx_fsr3upscaler_x64.dll
|
||||
libxess.dll nvapi64.dll nvngx.dll nvngx_dlss.dll)
|
||||
[ ! -f "$linuxfs/droiddeck-upscale/bridges/x86_64-windows/nvngx.dll" ] || pack upscale "$linuxfs/droiddeck-upscale" \
|
||||
"${upscale[@]/#/bridges/x86_64-windows/}" "${upscale[@]/#/bridges/aarch64-windows/}"
|
||||
[ ! -f "$linuxfs/droiddeck-epic/EpicGamesLauncher.exe" ] || pack epic "$linuxfs/droiddeck-epic" EpicGamesLauncher.exe
|
||||
|
||||
mkdir "$work/butler"
|
||||
|
||||
@@ -16,17 +16,19 @@ PACKS = Path('app/build/packs')
|
||||
PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet',
|
||||
'assets/linuxfs/usr/local/lib/droiddeck-ubisoft/': 'ubisoft', 'assets/linuxfs/usr/local/lib/droiddeck-rockstar/': 'rockstar',
|
||||
'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt', 'assets/linuxfs/usr/local/lib/droiddeck-epic/': 'epic',
|
||||
'assets/linuxfs/usr/local/lib/droiddeck-upscale/': 'upscale',
|
||||
'assets/directaudio/': 'directaudio', 'assets/hybris/': 'powervr'}
|
||||
# DrWeb flags proot itself as Tool.Linux.Proot; the app runs the pack's copy through Android's linker.
|
||||
PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so')}
|
||||
# The loader is execve'd, which targetSdk 29+ allows only from the APK's native library directory.
|
||||
PROOT_LOADER = {'lib/arm64-v8a/libproot-loader.so': 'libproot-loader.so'}
|
||||
PACKED_LIBRARIES = ['lib/arm64-v8a/libopencv_java4.so', 'lib/arm64-v8a/libmediapipe_tasks_jni.so']
|
||||
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic']
|
||||
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic',
|
||||
'upscale']
|
||||
SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst',
|
||||
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs',
|
||||
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
|
||||
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
|
||||
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/upscale', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
|
||||
'tools/ime', 'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
|
||||
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
|
||||
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
|
||||
@@ -257,7 +259,7 @@ def windows_binaries(package):
|
||||
def check_apk(apk, root=ROOT):
|
||||
data = verify(root)
|
||||
packs = {name: pack_digests(root, name) for name in PACK_NAMES
|
||||
if name not in ('ubisoft', 'rockstar', 'dirt', 'epic') or (root / PACKS / (name + '.tar.zst')).is_file()}
|
||||
if name not in ('ubisoft', 'rockstar', 'dirt', 'epic', 'upscale') or (root / PACKS / (name + '.tar.zst')).is_file()}
|
||||
for name, rel in PROOT_LOADER.items():
|
||||
if packs['proot'].get(rel) != data['outputs'][name]['sha256']:
|
||||
raise ValueError('Add-on pack proot is missing or has a stale ' + rel)
|
||||
|
||||
@@ -4,6 +4,7 @@ import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
@@ -24,6 +25,142 @@ STATE = tempfile.TemporaryDirectory()
|
||||
COMPAT["main"].__globals__["COMPAT_DIR"] = STATE.name
|
||||
|
||||
|
||||
class UpscalerSettingsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.root = tempfile.mkdtemp()
|
||||
Path(self.root, "bridges/x86_64-windows").mkdir(parents=True)
|
||||
Path(self.root, "bridges/x86_64-windows/libxess.dll").write_bytes(b"MZ")
|
||||
self.run = os.path.join(self.root, "run")
|
||||
self.patch = patch.dict(MODULE["upscale_settings"].__globals__, {"UPSCALE_ROOT": self.root, "UPSCALE_RUN": self.run})
|
||||
self.patch.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.patch.stop()
|
||||
shutil.rmtree(self.root)
|
||||
|
||||
def test_off_leaves_the_environment_alone(self):
|
||||
env = {"DROIDDECK_UPSCALE_MODE": "off", "WINEDLLOVERRIDES": "dxgi=n"}
|
||||
self.assertEqual((env, []), MODULE["upscale_settings"](env, None))
|
||||
|
||||
def test_fsr_mode_overrides_the_upscaler_dlls_without_spoofing(self):
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "WINEDLLOVERRIDES": "dxgi=n"}, None)
|
||||
self.assertEqual("1", env["DROIDDECK_UPSCALE"])
|
||||
self.assertTrue(env["WINEDLLOVERRIDES"].startswith("dxgi=n;libxess=b,n;"))
|
||||
self.assertNotIn("nvapi64", env["WINEDLLOVERRIDES"])
|
||||
self.assertNotIn("DXVK_CONFIG", env)
|
||||
self.assertEqual(self.root + "/bridges", env["WINEDLLPATH"])
|
||||
self.assertEqual("off", env["DROIDDECK_UPSCALE_GPU_SPOOF"])
|
||||
|
||||
def test_dlss_mode_spoofs_an_nvidia_gpu(self):
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "dlss", "DXVK_CONFIG": "a = 1"}, None)
|
||||
self.assertIn("nvngx=b,n", env["WINEDLLOVERRIDES"])
|
||||
self.assertIn("nvapi64=b,n", env["WINEDLLOVERRIDES"])
|
||||
self.assertEqual("1", env["PROTON_ENABLE_NVAPI"])
|
||||
self.assertTrue(env["DXVK_CONFIG"].startswith("a = 1; dxgi.hideNvidiaGpu = False; dxgi.customVendorId = 10de"))
|
||||
|
||||
def test_upscale_old_fsr4_npu_runs_full_fsr4_and_sgsr2_passes(self):
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "fsr4_0_npu",
|
||||
"DROIDDECK_UPSCALE_NPU": "1"}, None)
|
||||
self.assertEqual("fsr4_1_full_npu", env["DROIDDECK_UPSCALE_BACKEND"])
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "fsr4_1_full_npu"}, None)
|
||||
self.assertEqual("fsr4_1_full_gpu", env["DROIDDECK_UPSCALE_BACKEND"])
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "sgsr2_gpu"}, None)
|
||||
self.assertEqual("sgsr2_gpu", env["DROIDDECK_UPSCALE_BACKEND"])
|
||||
|
||||
def test_npu_engines_fall_back_to_the_gpu_without_an_npu(self):
|
||||
env, notes = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "fsr4_1_lite_npu"}, None)
|
||||
self.assertEqual("fsr4_1_lite_gpu", env["DROIDDECK_UPSCALE_BACKEND"])
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "fsr4_1_lite_npu",
|
||||
"DROIDDECK_UPSCALE_NPU": "1"}, None)
|
||||
self.assertEqual("fsr4_1_lite_npu", env["DROIDDECK_UPSCALE_BACKEND"])
|
||||
|
||||
def test_without_the_bridge_pack_the_game_starts_without_the_upscaler(self):
|
||||
os.unlink(os.path.join(self.root, "bridges/x86_64-windows/libxess.dll"))
|
||||
env = {"DROIDDECK_UPSCALE_MODE": "fsr"}
|
||||
result, notes = MODULE["upscale_settings"](env, None)
|
||||
self.assertEqual(env, result)
|
||||
self.assertTrue(notes)
|
||||
|
||||
def test_the_control_file_follows_this_games_settings(self):
|
||||
Path(self.run).mkdir()
|
||||
Path(self.run, "ctrl").write_text("enabled=0\nbackend=fsr4_1_lite_gpu\nsharpness=0.55\nnpu_sync=0\n")
|
||||
_, notes = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "xess3_gpu",
|
||||
"DROIDDECK_UPSCALE_SHARPNESS": "40"}, None)
|
||||
self.assertEqual("enabled=1\nbackend=xess3_gpu\nsharpness=0.40\nnpu_sync=0\n", Path(self.run, "ctrl").read_text())
|
||||
self.assertFalse([n for n in notes if "control file" in n])
|
||||
|
||||
def test_the_xess_runtime_goes_into_any_upscaler_game_once_downloaded(self):
|
||||
prefix = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, prefix, True)
|
||||
Path(prefix, "pfx/drive_c/windows/system32").mkdir(parents=True)
|
||||
source = Path(self.root, "data/xess", MODULE["UPSCALE_XESS"])
|
||||
source.parent.mkdir(parents=True)
|
||||
source.write_bytes(b"MZ-xess")
|
||||
MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "fsr4_1_lite_gpu"}, prefix)
|
||||
target = Path(prefix, "pfx/drive_c/windows/system32", MODULE["UPSCALE_XESS"])
|
||||
self.assertEqual(b"MZ-xess", target.read_bytes())
|
||||
self.assertEqual(source.stat().st_ino, target.stat().st_ino)
|
||||
|
||||
def test_dlss_mode_turns_the_signature_fix_on_unless_switched_off(self):
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "dlss"}, None)
|
||||
self.assertEqual("1", env["DROIDDECK_UPSCALE_SIGFIX"])
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "dlss", "DROIDDECK_UPSCALE_SIGFIX": "0"}, None)
|
||||
self.assertEqual("0", env["DROIDDECK_UPSCALE_SIGFIX"])
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr"}, None)
|
||||
self.assertNotIn("DROIDDECK_UPSCALE_SIGFIX", env)
|
||||
def test_dlss_mode_puts_nvapi_and_ngx_in_system32_and_other_modes_take_ours_out(self):
|
||||
prefix = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, prefix, True)
|
||||
system32 = Path(prefix, "pfx/drive_c/windows/system32")
|
||||
system32.mkdir(parents=True)
|
||||
for name in ("nvapi64.dll", "_nvngx.dll", "nvngx.dll", "nvngx_dlss.dll"):
|
||||
Path(self.root, "bridges/x86_64-windows", name).write_bytes(b"MZ-v1-" + name.encode())
|
||||
MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "dlss"}, prefix)
|
||||
self.assertEqual(b"MZ-v1-nvapi64.dll", (system32 / "nvapi64.dll").read_bytes())
|
||||
self.assertEqual(b"MZ-v1-_nvngx.dll", (system32 / "_nvngx.dll").read_bytes())
|
||||
Path(self.root, "bridges/x86_64-windows/_nvngx.dll").unlink()
|
||||
Path(self.root, "bridges/x86_64-windows/_nvngx.dll").write_bytes(b"MZ-v2-_nvngx.dll")
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "dlss"}, prefix)
|
||||
self.assertEqual(b"MZ-v2-_nvngx.dll", (system32 / "_nvngx.dll").read_bytes())
|
||||
self.assertEqual("rtx", env["DROIDDECK_UPSCALE_GPU_SPOOF"])
|
||||
(system32 / "nvngx.dll").write_bytes(b"someone else's nvngx")
|
||||
env, _ = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr"}, prefix)
|
||||
self.assertEqual("off", env["DROIDDECK_UPSCALE_GPU_SPOOF"])
|
||||
self.assertFalse((system32 / "nvapi64.dll").exists())
|
||||
self.assertFalse((system32 / "_nvngx.dll").exists())
|
||||
self.assertEqual(b"someone else's nvngx", (system32 / "nvngx.dll").read_bytes())
|
||||
|
||||
|
||||
def test_a_game_started_on_xess_without_the_runtime_says_so(self):
|
||||
prefix = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, prefix, True)
|
||||
Path(prefix, "pfx/drive_c/windows/system32").mkdir(parents=True)
|
||||
_, notes = MODULE["upscale_settings"]({"DROIDDECK_UPSCALE_MODE": "fsr", "DROIDDECK_UPSCALE_ENGINE": "xess3_gpu"}, prefix)
|
||||
self.assertTrue([n for n in notes if "XeSS runtime not downloaded" in n])
|
||||
|
||||
def test_the_app_stages_every_dll_the_bridge_build_makes(self):
|
||||
repo = Path(__file__).resolve().parents[2]
|
||||
build = (repo / "tools/upscale/bridges/build.sh").read_text()
|
||||
built = set(re.search(r"names=\(([^)]*)\)", build).group(1).split())
|
||||
kotlin = (repo / "app/src/main/java/com/droiddeck/launcher/session/UpscaleComponent.kt").read_text()
|
||||
staged = set(re.findall(r'"([A-Za-z0-9_]+\.dll)"', kotlin[kotlin.index("BRIDGE_NAMES"):kotlin.index("BRIDGE_FILES")]))
|
||||
self.assertEqual(built, staged)
|
||||
|
||||
def test_ngx_registry_entries_are_added_once(self):
|
||||
prefix = tempfile.mkdtemp()
|
||||
try:
|
||||
Path(prefix, "pfx").mkdir()
|
||||
Path(prefix, "pfx/system.reg").write_text("WINE REGISTRY Version 2\n\n[Software\\\\Wine] 1\n")
|
||||
self.assertTrue(MODULE["upscale_registry"](prefix))
|
||||
self.assertFalse(MODULE["upscale_registry"](prefix))
|
||||
text = Path(prefix, "pfx/system.reg").read_text()
|
||||
self.assertIn("[Software\\\\NVIDIA Corporation\\\\Global\\\\NGXCore]", text)
|
||||
self.assertIn('"FullPath"="C:\\\\windows\\\\system32"', text)
|
||||
self.assertNotIn("CurrentControlSet", text)
|
||||
finally:
|
||||
shutil.rmtree(prefix)
|
||||
|
||||
|
||||
class ProducerAcquireGameEnvironmentTest(unittest.TestCase):
|
||||
def test_prefixed_opt_in_enters_only_the_game_environment(self):
|
||||
key = "DROIDDECK_GAME_FRAME_ACQUIRE"
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# Upscale bridge DLLs
|
||||
|
||||
Windows x86-64 DLLs that stand in for a game's DLSS, FidelityFX (FSR 2, FSR 3, FidelityFX API) and
|
||||
XeSS libraries inside Wine. They do not upscale anything themselves: each frame's colour, depth,
|
||||
motion-vector and output images are written into a host-visible Vulkan mailbox buffer, and a
|
||||
`vkCmdUpdateBuffer` "doorbell" on a marker buffer tells the Android Vulkan layer to record the
|
||||
upscaler into the game's command buffer. The layer finds both buffers by their sizes and magic
|
||||
numbers. `fsr4_seam_proto.h` is that contract and is a verbatim copy of the fork's
|
||||
`app/src/main/cpp/fsr4npu/fsr4_seam_proto.h` (sha256 `a9f614c53ae9209edf0fa9c5acb0a27fdf923c08026362b23f60e1bcb39acd15`).
|
||||
It must stay byte-identical to the layer's copy. If the layer does not acknowledge a frame,
|
||||
the bridge blits the render-resolution image to the output (bilinear) so the game never shows
|
||||
stale memory. D3D12 games reach Vulkan through vkd3d-proton's `ID3D12DXVKInteropDevice1`.
|
||||
|
||||
| DLL | Source | Export list | Replaces |
|
||||
| --- | --- | --- | --- |
|
||||
| `amd_fidelityfx_vk.dll` | `wl_ffx_bridge.c` | `wl_ffx_bridge.def` | FidelityFX API (`ffxCreateContext`, `ffxDispatch`, ...) |
|
||||
| `amd_fidelityfx_dx12.dll`, `amd_fidelityfx_upscaler_vk.dll`, `amd_fidelityfx_upscaler_dx12.dll`, `amd_fidelityfx_loader_dx12.dll` | copies of `amd_fidelityfx_vk.dll` | | the same API under the other SDK file names |
|
||||
| `ffx_fsr3upscaler_x64.dll` | `wl_fsr23_bridge.c` | `ffx_fsr3upscaler_x64.def` | FSR 3.0 / 3.1 upscaler |
|
||||
| `ffx_fsr2_api_x64.dll` | `wl_fsr23_bridge.c` | `ffx_fsr2_api_x64.def` | FSR 2.0 / 2.1 / 2.2 |
|
||||
| `libxess.dll` | `wl_xess_bridge.c` | `libxess.def` | Intel XeSS 1.3 / 2.0 (D3D12 + Vulkan) |
|
||||
| `nvngx.dll` | `wl_ngx_bridge.c` | `nvngx.def` | NVIDIA NGX / DLSS Super Resolution (Vulkan + D3D12) |
|
||||
| `_nvngx.dll`, `nvngx_dlss.dll` | copies of `nvngx.dll` | | the names games and Streamline load NGX by |
|
||||
| `nvapi64.dll` | `wl_nvapi_shim.c` (+ `wl_ngx_hooks.h`) | `nvapi64.def` | NVAPI, reporting an RTX 2060 so games offer DLSS |
|
||||
|
||||
`wl_fsr23_bridge.c` exports both the FSR 2 and FSR 3 entry points, so both DLLs carry all 21.
|
||||
`nvngx.dll` exports the 88 `.def` names plus 9 that only its source marks `__declspec(dllexport)`. `build.sh`
|
||||
fails when a DLL's exports (from `x86_64-w64-mingw32-objdump -p`) differ from its `.def` plus
|
||||
its source's `dllexport` names.
|
||||
|
||||
When the XeSS 3.0 backend is selected, `wl_xess3_direct.h` loads Intel's XeSS SDK runtime as
|
||||
`wl_xess_official.dll` (from the DLL search path, then `C:\windows\system32`). When it is missing or
|
||||
fails, the frame goes to the layer flagged `WLFSR4_FLAG_XESS_FALLBACK` (FSR 3.1 on the GPU). That DLL is Intel's prebuilt binary and is not built here.
|
||||
|
||||
## Build
|
||||
|
||||
```sh
|
||||
bash tools/upscale/bridges/build.sh OUT
|
||||
```
|
||||
|
||||
Needs `x86_64-w64-mingw32-gcc` (Ubuntu `gcc-mingw-w64-x86-64`) and `python3`. The output is
|
||||
deterministic (`-s`, `-Wl,--no-insert-timestamp`, linked under the bare DLL name because `ld`
|
||||
derives the image base from the output path). Every DLL is stamped as a Wine builtin the way
|
||||
`winebuild --builtin` does it: the 32-byte `"Wine builtin DLL"` signature, zero-padded, at file
|
||||
offset 0x40 (`pe.py stamp`). Wine then loads them from `WINEDLLPATH` when the override is
|
||||
`builtin`. The same x86-64 files are installed to `OUT/x86_64-windows/` and
|
||||
`OUT/aarch64-windows/`, because the ARM64EC Wine loads x86-64 builtins from the latter.
|
||||
|
||||
CI builds them with the `upscale-bridges` component recipe into
|
||||
`app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges/`. The APK may not carry
|
||||
Windows executables (`tools/release/runtime_inputs.py`), so they ship in the `upscale` add-on
|
||||
pack (`tools/packs/build.sh`), whose entries are `bridges/{x86_64,aarch64}-windows/<dll>`.
|
||||
|
||||
## Environment
|
||||
|
||||
| Variable | Default | Effect |
|
||||
| --- | --- | --- |
|
||||
| `DROIDDECK_UPSCALE_BACKEND` (then `DROIDDECK_UPSCALE_ENGINE`, `WINLATOR_FSR4_BACKEND`, `WINLATOR_FSR4_ENGINE`) | `fsr4_1_full_npu` | Backend the bridges assume until the layer writes its live control word: `fsr3_gpu`, `xess3_gpu`, `sgsr2_gpu`, `fsr4_1_lite_npu`, `fsr4_1_full_npu`, `fsr4_1_lite_gpu`, `fsr4_1_full_gpu` (`fsr4_0_npu` = `fsr4_1_full_npu`) |
|
||||
| `DROIDDECK_UPSCALE_VRAM_MB` (then `WINLATOR_FSR4_VRAM_MB`, `WRAPPER_VMEM_MAX_SIZE`) | DXGI adapter 0, else 12 GB | VRAM `nvapi64.dll` reports (512-65536 MB) |
|
||||
| `DROIDDECK_UPSCALE_SIGFIX=1` | on in DLSS mode (`droiddeck-game-env` sets `1` unless the game stores `0`) | `nvapi64.dll` patches the import tables of loaded modules (LoadLibrary*, GetProcAddress, GetFileAttributes*, CreateFileW, Reg*), redirects `nvngx`/`_nvngx` loads to `C:\windows\system32\_nvngx.dll`, fakes the NVIDIA signature-override registry keys, forces `WinVerifyTrust` success and redirects `CryptQueryObject` for `nvngx`/`amd_fidelityfx*`, so games that signature-check NGX load the bridge. Never applied to rdr2.exe, playrdr2.exe or gta5.exe |
|
||||
| `DROIDDECK_UPSCALE_LOG=1` | off | Hook messages appended to `C:\windows\temp\wl_fsr4_bridge.log` |
|
||||
|
||||
## Changes from the fork
|
||||
|
||||
- Until upstream r5, D3D11 NGX reported DLSS unavailable here (the fork returned success and rendered
|
||||
nothing). Since r5 the D3D11 entry points reach the Vulkan layer through DXVK's interop
|
||||
(`wl_dxvk_interop.h`), as upstream does.
|
||||
- The `nvapi64.dll` hooks follow `DROIDDECK_UPSCALE_SIGFIX`, which DLSS games get as `1` unless switched off (the fork
|
||||
always installed them). Without them NGX rejects the bridges (DLSS sample: `GetFeatureRequirements` PlatformError).
|
||||
- Logging is off unless `DROIDDECK_UPSCALE_LOG=1`; the fork always wrote the log.
|
||||
- `DROIDDECK_UPSCALE_*` variables are read first, the fork's names after them (`dd_env.h`).
|
||||
- `fsr4_seam_proto.h` is included from this folder instead of `../fsr4npu/`.
|
||||
- Built with Ubuntu's MinGW-w64 GCC (msvcrt) instead of the fork's PowerShell script; flags as in
|
||||
its `build_win_dlls.ps1` plus `-s` and `-Wl,--no-insert-timestamp`. The fork stamped the
|
||||
signature at install time; here it is stamped at build time.
|
||||
|
||||
Seam protocol, struct layouts, magics and backend IDs are unchanged.
|
||||
|
||||
## Credits and licence
|
||||
|
||||
Ported from [michaelisomer-cyber/Winlator-NeuralScale](https://github.com/michaelisomer-cyber/Winlator-NeuralScale)
|
||||
at `a0ab6b0f770e1a6786b4e68def46b4edb8baafd0`, updated to `71c140d9e5586f659251c3ebc602f2d21923655c` (r5: D3D11
|
||||
DLSS through DXVK's interop, `wl_dxvk_interop.h`) (`app/src/main/cpp/fsr4npu_win/`), GPL-3.0. That fork
|
||||
builds on [StevenMXZ/Winlator-Ludashi](https://github.com/StevenMXZ/Winlator-Ludashi). The NGX
|
||||
and NVAPI shims follow OptiScaler's approach (and fakenvapi's NVAPI interface). These files stay
|
||||
under the GPL-3.0, the licence of this repository (`LICENSE`); modified files say so in their
|
||||
first line.
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
mkdir -p "${1:?usage: build.sh <out-dir>}"
|
||||
out=$(cd "$1" && pwd)
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
cc=x86_64-w64-mingw32-gcc
|
||||
objdump=x86_64-w64-mingw32-objdump
|
||||
for tool in "$cc" "$objdump"; do
|
||||
command -v "$tool" >/dev/null || { echo "upscale-bridges: $tool not found (apt install gcc-mingw-w64-x86-64)" >&2; exit 1; }
|
||||
done
|
||||
cflags=(-O2 -fno-ipa-icf -shared -s -Wall -Wextra -Wno-unused-function -static-libgcc -I"$here"
|
||||
-ffile-prefix-map="$here"=. -Wl,--no-insert-timestamp)
|
||||
|
||||
build() {
|
||||
local name=$1 source=$2 definition=$3
|
||||
shift 3
|
||||
# ld derives the DLL's image base from the -o path, so link in $work under the bare name.
|
||||
(cd "$work" && "$cc" "${cflags[@]}" "$here/$source" "$here/$definition" "$@" -o "$name")
|
||||
python3 -I "$here/pe.py" verify "$work/$name" "$here/$definition" "$here/$source" "$objdump"
|
||||
python3 -I "$here/pe.py" stamp "$work/$name"
|
||||
}
|
||||
|
||||
build amd_fidelityfx_vk.dll wl_ffx_bridge.c wl_ffx_bridge.def -lm
|
||||
for name in amd_fidelityfx_dx12.dll amd_fidelityfx_upscaler_vk.dll amd_fidelityfx_upscaler_dx12.dll amd_fidelityfx_loader_dx12.dll; do
|
||||
cp "$work/amd_fidelityfx_vk.dll" "$work/$name"
|
||||
done
|
||||
build libxess.dll wl_xess_bridge.c libxess.def -lm
|
||||
build ffx_fsr3upscaler_x64.dll wl_fsr23_bridge.c ffx_fsr3upscaler_x64.def -lm
|
||||
build ffx_fsr2_api_x64.dll wl_fsr23_bridge.c ffx_fsr2_api_x64.def -lm
|
||||
build nvngx.dll wl_ngx_bridge.c nvngx.def -lm
|
||||
for name in _nvngx.dll nvngx_dlss.dll; do
|
||||
cp "$work/nvngx.dll" "$work/$name"
|
||||
done
|
||||
build nvapi64.dll wl_nvapi_shim.c nvapi64.def
|
||||
|
||||
names=(_nvngx.dll amd_fidelityfx_dx12.dll amd_fidelityfx_loader_dx12.dll amd_fidelityfx_upscaler_dx12.dll
|
||||
amd_fidelityfx_upscaler_vk.dll amd_fidelityfx_vk.dll ffx_fsr2_api_x64.dll ffx_fsr3upscaler_x64.dll
|
||||
libxess.dll nvapi64.dll nvngx.dll nvngx_dlss.dll)
|
||||
[ "$(ls "$work" | sort)" = "$(printf '%s\n' "${names[@]}" | sort)" ] || { echo "upscale-bridges: unexpected outputs" >&2; exit 1; }
|
||||
# The ARM64EC Wine loads x86-64 builtins from aarch64-windows as well.
|
||||
for arch in x86_64-windows aarch64-windows; do
|
||||
rm -rf "${out:?}/$arch"
|
||||
mkdir -p "$out/$arch"
|
||||
for name in "${names[@]}"; do
|
||||
install -m 644 "$work/$name" "$out/$arch/$name"
|
||||
done
|
||||
done
|
||||
@@ -0,0 +1,20 @@
|
||||
// DroidDeck: environment lookups shared by the upscale bridges.
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
// Copies the first variable in the NULL-terminated list that is set and fits into buf.
|
||||
static DWORD dd_env_first(const char *const *names, char *buf, DWORD size) {
|
||||
for (; *names; names++) {
|
||||
DWORD n = GetEnvironmentVariableA(*names, buf, size);
|
||||
if (n > 0 && n < size) return n;
|
||||
}
|
||||
if (size) buf[0] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int dd_env_is_on(const char *name) {
|
||||
char buf[8];
|
||||
DWORD n = GetEnvironmentVariableA(name, buf, sizeof buf);
|
||||
return n == 1 && buf[0] == '1';
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
LIBRARY ffx_fsr2_api_x64.dll
|
||||
EXPORTS
|
||||
ffxFsr2ContextCreate
|
||||
ffxFsr2ContextDispatch
|
||||
ffxFsr2ContextGenerateReactiveMask
|
||||
ffxFsr2ContextDestroy
|
||||
ffxFsr2GetUpscaleRatioFromQualityMode
|
||||
ffxFsr2GetRenderResolutionFromQualityMode
|
||||
ffxFsr2GetJitterPhaseCount
|
||||
ffxFsr2GetJitterOffset
|
||||
ffxFsr2ResourceIsNull
|
||||
@@ -0,0 +1,14 @@
|
||||
LIBRARY ffx_fsr3upscaler_x64.dll
|
||||
EXPORTS
|
||||
ffxFsr3UpscalerContextCreate
|
||||
ffxFsr3UpscalerGetSharedResourceDescriptions
|
||||
ffxFsr3UpscalerContextDispatch
|
||||
ffxFsr3UpscalerContextGenerateReactiveMask
|
||||
ffxFsr3UpscalerContextDestroy
|
||||
ffxFsr3UpscalerGetUpscaleRatioFromQualityMode
|
||||
ffxFsr3UpscalerGetRenderResolutionFromQualityMode
|
||||
ffxFsr3UpscalerGetJitterPhaseCount
|
||||
ffxFsr3UpscalerGetJitterOffset
|
||||
ffxFsr3UpscalerResourceIsNull
|
||||
ffxFsr3UpscalerSetConstant
|
||||
ffxFsr3UpscalerGetEffectVersion
|
||||
@@ -0,0 +1,168 @@
|
||||
// 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 3u
|
||||
#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) */
|
||||
WL_FSR_BACKEND_SGSR2_GPU = 7, /* Qualcomm Snapdragon GSR 2 (3-pass Adreno FP16 GPU) */
|
||||
WL_FSR_BACKEND_AUTO = 8, /* Smart Automatic (30s FPS/power/cap-aware + fault blacklist) */
|
||||
};
|
||||
|
||||
// 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,
|
||||
WLFSR4_API_NGX_DX11 = 11,
|
||||
};
|
||||
|
||||
// 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) */
|
||||
uint16_t subrect_x; /* optional subrect origin X (pixels, e.g. RDR2 DLSS subrect) */
|
||||
uint16_t subrect_y; /* optional subrect origin Y (pixels) */
|
||||
} 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];
|
||||
WlFsr4ImageRef reactive; /* optional reactive / DLSS BiasCurrentColorMask */
|
||||
WlFsr4ImageRef exposure; /* optional 1x1 ExposureTexture */
|
||||
} WlFsr4FrameDesc; /* 336 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) == 336, "WlFsr4FrameDesc size");
|
||||
_Static_assert(sizeof(WlFsr4Mailbox) <= WLFSR4_MAILBOX_BYTES, "WlFsr4Mailbox fits in 8KB");
|
||||
_Static_assert(sizeof(WlFsr4DoorbellPayload) == 16, "WlFsr4DoorbellPayload size");
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,40 @@
|
||||
LIBRARY libxess.dll
|
||||
EXPORTS
|
||||
xessGetVersion
|
||||
xessGetIntelXeFXVersion
|
||||
xessIsOptimalDriver
|
||||
xessSetLoggingCallback
|
||||
xessGetProperties
|
||||
xessGetInputResolution
|
||||
xessGetOptimalInputResolution
|
||||
xessGetJitterScale
|
||||
xessSetJitterScale
|
||||
xessGetVelocityScale
|
||||
xessSetVelocityScale
|
||||
xessSetExposureMultiplier
|
||||
xessGetExposureMultiplier
|
||||
xessSetMaxResponsiveMaskValue
|
||||
xessGetMaxResponsiveMaskValue
|
||||
xessForceLegacyScaleFactors
|
||||
xessGetPipelineBuildStatus
|
||||
xessDestroyContext
|
||||
xessSelectNetworkModel
|
||||
xessStartDump
|
||||
xessGetProfilingData
|
||||
xessSetContextParameterF
|
||||
xessD3D12CreateContext
|
||||
xessD3D12BuildPipelines
|
||||
xessD3D12Init
|
||||
xessD3D12GetInitParams
|
||||
xessD3D12Execute
|
||||
xessD3D12GetProfilingData
|
||||
xessD3D12GetResourcesToDump
|
||||
xessVKGetRequiredInstanceExtensions
|
||||
xessVKGetRequiredDeviceExtensions
|
||||
xessVKGetRequiredDeviceFeatures
|
||||
xessVKCreateContext
|
||||
xessVKBuildPipelines
|
||||
xessVKInit
|
||||
xessVKGetInitParams
|
||||
xessVKExecute
|
||||
xessVKGetResourcesToDump
|
||||
@@ -0,0 +1,3 @@
|
||||
LIBRARY nvapi64
|
||||
EXPORTS
|
||||
nvapi_QueryInterface
|
||||
@@ -0,0 +1,90 @@
|
||||
LIBRARY nvngx
|
||||
EXPORTS
|
||||
GetNGXResultAsString
|
||||
NVSDK_NGX_CUDA_AllocateParameters
|
||||
NVSDK_NGX_CUDA_CreateFeature
|
||||
NVSDK_NGX_CUDA_DestroyParameters
|
||||
NVSDK_NGX_CUDA_EvaluateFeature
|
||||
NVSDK_NGX_CUDA_GetCapabilityParameters
|
||||
NVSDK_NGX_CUDA_GetParameters
|
||||
NVSDK_NGX_CUDA_GetScratchBufferSize
|
||||
NVSDK_NGX_CUDA_Init
|
||||
NVSDK_NGX_CUDA_Init_with_ProjectID
|
||||
NVSDK_NGX_CUDA_ReleaseFeature
|
||||
NVSDK_NGX_CUDA_Shutdown
|
||||
NVSDK_NGX_D3D11_AllocateParameters
|
||||
NVSDK_NGX_D3D11_CreateFeature
|
||||
NVSDK_NGX_D3D11_DestroyParameters
|
||||
NVSDK_NGX_D3D11_EvaluateFeature
|
||||
NVSDK_NGX_D3D11_EvaluateFeature_C
|
||||
NVSDK_NGX_D3D11_GetCapabilityParameters
|
||||
NVSDK_NGX_D3D11_GetFeatureRequirements
|
||||
NVSDK_NGX_D3D11_GetParameters
|
||||
NVSDK_NGX_D3D11_GetScratchBufferSize
|
||||
NVSDK_NGX_D3D11_Init
|
||||
NVSDK_NGX_D3D11_Init_Ext
|
||||
NVSDK_NGX_D3D11_Init_ProjectID
|
||||
NVSDK_NGX_D3D11_Init_with_ProjectID
|
||||
NVSDK_NGX_D3D11_PopulateParameters_Impl
|
||||
NVSDK_NGX_D3D11_ReleaseFeature
|
||||
NVSDK_NGX_D3D11_Shutdown
|
||||
NVSDK_NGX_D3D11_Shutdown1
|
||||
NVSDK_NGX_D3D12_AllocateParameters
|
||||
NVSDK_NGX_D3D12_CreateFeature
|
||||
NVSDK_NGX_D3D12_DestroyParameters
|
||||
NVSDK_NGX_D3D12_EvaluateFeature
|
||||
NVSDK_NGX_D3D12_GetCapabilityParameters
|
||||
NVSDK_NGX_D3D12_GetFeatureRequirements
|
||||
NVSDK_NGX_D3D12_GetParameters
|
||||
NVSDK_NGX_D3D12_GetScratchBufferSize
|
||||
NVSDK_NGX_D3D12_Init
|
||||
NVSDK_NGX_D3D12_Init_Ext
|
||||
NVSDK_NGX_D3D12_Init_ProjectID
|
||||
NVSDK_NGX_D3D12_Init_with_ProjectID
|
||||
NVSDK_NGX_D3D12_PopulateParameters_Impl
|
||||
NVSDK_NGX_D3D12_ReleaseFeature
|
||||
NVSDK_NGX_D3D12_Shutdown
|
||||
NVSDK_NGX_D3D12_Shutdown1
|
||||
NVSDK_NGX_GetSnippetVersion
|
||||
NVSDK_NGX_Parameter_GetD
|
||||
NVSDK_NGX_Parameter_GetD3d11Resource
|
||||
NVSDK_NGX_Parameter_GetD3d12Resource
|
||||
NVSDK_NGX_Parameter_GetF
|
||||
NVSDK_NGX_Parameter_GetI
|
||||
NVSDK_NGX_Parameter_GetUI
|
||||
NVSDK_NGX_Parameter_GetULL
|
||||
NVSDK_NGX_Parameter_GetVoidPointer
|
||||
NVSDK_NGX_Parameter_SetD
|
||||
NVSDK_NGX_Parameter_SetD3d11Resource
|
||||
NVSDK_NGX_Parameter_SetD3d12Resource
|
||||
NVSDK_NGX_Parameter_SetF
|
||||
NVSDK_NGX_Parameter_SetI
|
||||
NVSDK_NGX_Parameter_SetUI
|
||||
NVSDK_NGX_Parameter_SetULL
|
||||
NVSDK_NGX_Parameter_SetVoidPointer
|
||||
NVSDK_NGX_UpdateFeature
|
||||
NVSDK_NGX_VULKAN_AllocateParameters
|
||||
NVSDK_NGX_VULKAN_CreateFeature
|
||||
NVSDK_NGX_VULKAN_CreateFeature1
|
||||
NVSDK_NGX_VULKAN_DestroyParameters
|
||||
NVSDK_NGX_VULKAN_EvaluateFeature
|
||||
NVSDK_NGX_VULKAN_EvaluateFeature_C
|
||||
NVSDK_NGX_VULKAN_GetCapabilityParameters
|
||||
NVSDK_NGX_VULKAN_GetFeatureDeviceExtensionRequirements
|
||||
NVSDK_NGX_VULKAN_GetFeatureExtensionRequirements
|
||||
NVSDK_NGX_VULKAN_GetFeatureInstanceExtensionRequirements
|
||||
NVSDK_NGX_VULKAN_GetFeatureRequirements
|
||||
NVSDK_NGX_VULKAN_GetParameter
|
||||
NVSDK_NGX_VULKAN_GetParameters
|
||||
NVSDK_NGX_VULKAN_GetScratchBufferSize
|
||||
NVSDK_NGX_VULKAN_Init
|
||||
NVSDK_NGX_VULKAN_Init_Ext
|
||||
NVSDK_NGX_VULKAN_Init_Ext2
|
||||
NVSDK_NGX_VULKAN_Init_ProjectID_Ext
|
||||
NVSDK_NGX_VULKAN_Init_with_ProjectID
|
||||
NVSDK_NGX_VULKAN_PopulateParameters_Impl
|
||||
NVSDK_NGX_VULKAN_ReleaseFeature
|
||||
NVSDK_NGX_VULKAN_RequiredExtensions
|
||||
NVSDK_NGX_VULKAN_SetParameter
|
||||
NVSDK_NGX_VULKAN_Shutdown
|
||||
NVSDK_NGX_VULKAN_Shutdown1
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Stamp and check the upscale bridge DLLs.
|
||||
|
||||
stamp DLL write Wine's builtin signature at 0x40, as winebuild --builtin does
|
||||
verify DLL DEF SRC OBJDUMP the exports `OBJDUMP -p` reports must be the .def names plus SRC's dllexports
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# tools/winebuild/spec32.c: static const char builtin_signature[32] = "Wine builtin DLL";
|
||||
SIGNATURE = b'Wine builtin DLL'.ljust(32, b'\0')
|
||||
OFFSET = 0x40
|
||||
|
||||
|
||||
def stamp(dll):
|
||||
data = bytearray(Path(dll).read_bytes())
|
||||
if data[:2] != b'MZ':
|
||||
sys.exit(f'{dll}: not a PE file')
|
||||
lfanew = int.from_bytes(data[0x3c:0x40], 'little')
|
||||
if lfanew < OFFSET + len(SIGNATURE):
|
||||
sys.exit(f'{dll}: not enough space ({lfanew:#x}) for the Wine signature')
|
||||
data[OFFSET:OFFSET + len(SIGNATURE)] = SIGNATURE
|
||||
Path(dll).write_bytes(data)
|
||||
if Path(dll).read_bytes()[OFFSET:OFFSET + len(SIGNATURE)] != SIGNATURE:
|
||||
sys.exit(f'{dll}: Wine signature did not stick')
|
||||
|
||||
|
||||
def def_names(path):
|
||||
names, exports = set(), False
|
||||
for line in Path(path).read_text().splitlines():
|
||||
line = line.split(';', 1)[0].strip()
|
||||
if not line:
|
||||
continue
|
||||
if line.upper() == 'EXPORTS':
|
||||
exports = True
|
||||
elif exports:
|
||||
names.add(line.split()[0].split('=', 1)[0])
|
||||
return names
|
||||
|
||||
|
||||
def source_names(path):
|
||||
text = Path(path).read_text()
|
||||
return {re.findall(r'\w+', head)[-1] for head in re.findall(r'__declspec\(dllexport\)([^(;{]*)\(', text)}
|
||||
|
||||
|
||||
def exports(dll, objdump):
|
||||
report = subprocess.run([objdump, '-p', dll], check=True, capture_output=True, text=True).stdout
|
||||
if 'file format pei-x86-64' not in report:
|
||||
sys.exit(f'{dll}: not an x86-64 PE image')
|
||||
table = report.split('[Ordinal/Name Pointer] Table', 1)
|
||||
if len(table) != 2:
|
||||
sys.exit(f'{dll}: no export table')
|
||||
# One row per export, "[ 0] +base[ 1] 0000 name" (binutils 2.45) or "[ 0] name" (older): the rows
|
||||
# start with an index in brackets; the column titles some versions print do not.
|
||||
names = []
|
||||
for line in table[1].splitlines()[1:]:
|
||||
if not line.strip():
|
||||
if names:
|
||||
break
|
||||
continue
|
||||
if re.match(r'\s*\[\s*\d+\]', line):
|
||||
names.append(line.split()[-1])
|
||||
if len(names) != len(set(names)):
|
||||
sys.exit(f'{dll}: duplicate exports')
|
||||
return set(names)
|
||||
|
||||
|
||||
def verify(dll, definition, source, objdump):
|
||||
found = exports(dll, objdump)
|
||||
expected = def_names(definition) | source_names(source)
|
||||
missing, extra = sorted(expected - found), sorted(found - expected)
|
||||
if missing or extra:
|
||||
sys.exit(f'{dll}: exports do not match {Path(definition).name}: missing {missing}, unexpected {extra}')
|
||||
print(f'{Path(dll).name}: {len(found)} exports match {Path(definition).name}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if sys.argv[1:2] == ['stamp'] and len(sys.argv) == 3:
|
||||
stamp(sys.argv[2])
|
||||
elif sys.argv[1:2] == ['verify'] and len(sys.argv) == 6:
|
||||
verify(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
|
||||
else:
|
||||
sys.exit(__doc__)
|
||||
@@ -0,0 +1,116 @@
|
||||
// Exact DXVK IDXGIVkInteropDevice / IDXGIVkInteropSurface C COM vtable
|
||||
// Verified against doitsujin/dxvk src/dxgi/dxgi_interfaces.h.
|
||||
// Enables D3D11 DLSS / Luma Framework mods (DX11 -> DXVK -> Vulkan) to route
|
||||
// directly into Winlator's zero-copy FSR 4 / FSR 3.1 / SGSR 2 Vulkan layer.
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include "wl_streamline.h"
|
||||
|
||||
// {e2ef5fa5-dc21-4af7-90c4-f67ef6a09323}
|
||||
static const GUID WL_IID_IDXGIVkInteropDevice = {
|
||||
0xe2ef5fa5, 0xdc21, 0x4af7, {0x90, 0xc4, 0xf6, 0x7e, 0xf6, 0xa0, 0x93, 0x23}
|
||||
};
|
||||
|
||||
// {5546cf8c-77e7-4341-b05d-8d4d5000e77d}
|
||||
static const GUID WL_IID_IDXGIVkInteropSurface = {
|
||||
0x5546cf8c, 0x77e7, 0x4341, {0xb0, 0x5d, 0x8d, 0x4d, 0x50, 0x00, 0xe7, 0x7d}
|
||||
};
|
||||
|
||||
typedef struct WlVkImageCreateInfo {
|
||||
uint32_t sType;
|
||||
const void *pNext;
|
||||
uint32_t flags;
|
||||
uint32_t imageType;
|
||||
uint32_t format;
|
||||
uint32_t extentWidth;
|
||||
uint32_t extentHeight;
|
||||
uint32_t extentDepth;
|
||||
uint32_t mipLevels;
|
||||
uint32_t arrayLayers;
|
||||
uint32_t samples;
|
||||
uint32_t tiling;
|
||||
uint32_t usage;
|
||||
uint32_t sharingMode;
|
||||
uint32_t queueFamilyIndexCount;
|
||||
const uint32_t *pQueueFamilyIndices;
|
||||
uint32_t initialLayout;
|
||||
} WlVkImageCreateInfo;
|
||||
|
||||
typedef struct WlIDXGIVkInteropDevice WlIDXGIVkInteropDevice;
|
||||
typedef struct WlIDXGIVkInteropSurface WlIDXGIVkInteropSurface;
|
||||
|
||||
typedef struct WlIDXGIVkInteropDeviceVtbl {
|
||||
// IUnknown
|
||||
HRESULT (__stdcall *QueryInterface)(WlIDXGIVkInteropDevice *This, const GUID *riid, void **ppv);
|
||||
ULONG (__stdcall *AddRef)(WlIDXGIVkInteropDevice *This);
|
||||
ULONG (__stdcall *Release)(WlIDXGIVkInteropDevice *This);
|
||||
// IDXGIVkInteropDevice
|
||||
void (__stdcall *GetVulkanHandles)(WlIDXGIVkInteropDevice *This, void **pInstance, void **pPhysDev, void **pDevice);
|
||||
void (__stdcall *GetSubmissionQueue)(WlIDXGIVkInteropDevice *This, void **pQueue, uint32_t *pQueueIndex, uint32_t *pQueueFamilyIndex);
|
||||
void (__stdcall *TransitionSurfaceLayout)(WlIDXGIVkInteropDevice *This, WlIDXGIVkInteropSurface *pSurface, const void *pSubresources, uint32_t OldLayout, uint32_t NewLayout);
|
||||
void (__stdcall *FlushRenderingCommands)(WlIDXGIVkInteropDevice *This);
|
||||
void (__stdcall *LockSubmissionQueue)(WlIDXGIVkInteropDevice *This);
|
||||
void (__stdcall *ReleaseSubmissionQueue)(WlIDXGIVkInteropDevice *This);
|
||||
} WlIDXGIVkInteropDeviceVtbl;
|
||||
|
||||
struct WlIDXGIVkInteropDevice {
|
||||
const WlIDXGIVkInteropDeviceVtbl *lpVtbl;
|
||||
};
|
||||
|
||||
typedef struct WlIDXGIVkInteropSurfaceVtbl {
|
||||
// IUnknown
|
||||
HRESULT (__stdcall *QueryInterface)(WlIDXGIVkInteropSurface *This, const GUID *riid, void **ppv);
|
||||
ULONG (__stdcall *AddRef)(WlIDXGIVkInteropSurface *This);
|
||||
ULONG (__stdcall *Release)(WlIDXGIVkInteropSurface *This);
|
||||
// IDXGIVkInteropSurface
|
||||
HRESULT (__stdcall *GetDevice)(WlIDXGIVkInteropSurface *This, WlIDXGIVkInteropDevice **ppDevice);
|
||||
HRESULT (__stdcall *GetVulkanImageInfo)(WlIDXGIVkInteropSurface *This, uint64_t *pHandle, uint32_t *pLayout, WlVkImageCreateInfo *pInfo);
|
||||
} WlIDXGIVkInteropSurfaceVtbl;
|
||||
|
||||
struct WlIDXGIVkInteropSurface {
|
||||
const WlIDXGIVkInteropSurfaceVtbl *lpVtbl;
|
||||
};
|
||||
|
||||
static inline WlIDXGIVkInteropDevice *wl_query_dxvk_interop_device(void *d3d11_device) {
|
||||
if (!d3d11_device) return NULL;
|
||||
typedef struct {
|
||||
HRESULT (__stdcall *QueryInterface)(void *This, const GUID *riid, void **ppv);
|
||||
} IUnkVtbl;
|
||||
typedef struct { const IUnkVtbl *lpVtbl; } IUnkObj;
|
||||
IUnkObj *obj = (IUnkObj *)d3d11_device;
|
||||
WlIDXGIVkInteropDevice *out = NULL;
|
||||
if (obj->lpVtbl && obj->lpVtbl->QueryInterface(d3d11_device, &WL_IID_IDXGIVkInteropDevice, (void **)&out) == S_OK && out) {
|
||||
return out;
|
||||
}
|
||||
void *base = wl_sl_base(d3d11_device);
|
||||
if (base) {
|
||||
IUnkObj *b = (IUnkObj *)base;
|
||||
if (b->lpVtbl->QueryInterface(base, &WL_IID_IDXGIVkInteropDevice, (void **)&out) != S_OK) out = NULL;
|
||||
wl_com_release(base);
|
||||
return out;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static inline WlIDXGIVkInteropSurface *wl_query_dxvk_interop_surface(void *d3d11_res) {
|
||||
if (!d3d11_res) return NULL;
|
||||
typedef struct {
|
||||
HRESULT (__stdcall *QueryInterface)(void *This, const GUID *riid, void **ppv);
|
||||
} IUnkVtbl;
|
||||
typedef struct { const IUnkVtbl *lpVtbl; } IUnkObj;
|
||||
IUnkObj *obj = (IUnkObj *)d3d11_res;
|
||||
WlIDXGIVkInteropSurface *out = NULL;
|
||||
if (obj->lpVtbl && obj->lpVtbl->QueryInterface(d3d11_res, &WL_IID_IDXGIVkInteropSurface, (void **)&out) == S_OK && out) {
|
||||
return out;
|
||||
}
|
||||
void *base = wl_sl_base(d3d11_res);
|
||||
if (base) {
|
||||
IUnkObj *b = (IUnkObj *)base;
|
||||
if (b->lpVtbl->QueryInterface(base, &WL_IID_IDXGIVkInteropSurface, (void **)&out) != S_OK) out = NULL;
|
||||
wl_com_release(base);
|
||||
return out;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
@@ -0,0 +1,575 @@
|
||||
// Winlator Ludashi Native AMD FidelityFX API 2.0 (FSR 4.1.1) Bridge DLL
|
||||
// Works for BOTH Vulkan (amd_fidelityfx_vk.dll / amd_fidelityfx_upscaler_vk.dll)
|
||||
// AND DirectX 12 via vkd3d-proton interop (amd_fidelityfx_dx12.dll / amd_fidelityfx_upscaler_dx12.dll).
|
||||
//
|
||||
// Exposes AMD FSR 4.1.1 (and 3.1.4 compat) via ffxQuery(GET_VERSIONS) and forwards every
|
||||
// ffxDispatch(UPSCALE) zero-copy to libVkLayer_winlator_fsr4_npu.so on the Hexagon HTP v81 NPU.
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "wl_seam_client.h"
|
||||
#include "wl_vkd3d_interop.h"
|
||||
#include "wl_xess3_direct.h"
|
||||
|
||||
// ---- Official AMD FidelityFX API 2.0 ABI (verified from GPUOpen FidelityFX-SDK) ----
|
||||
typedef void *ffxContext;
|
||||
typedef uint32_t ffxReturnCode_t;
|
||||
typedef uint64_t ffxStructType_t;
|
||||
|
||||
enum {
|
||||
FFX_API_RETURN_OK = 0,
|
||||
FFX_API_RETURN_ERROR = 1,
|
||||
FFX_API_RETURN_ERROR_UNKNOWN_DESCTYPE = 2,
|
||||
FFX_API_RETURN_ERROR_RUNTIME_ERROR = 3,
|
||||
FFX_API_RETURN_NO_PROVIDER = 4,
|
||||
FFX_API_RETURN_ERROR_MEMORY = 5,
|
||||
FFX_API_RETURN_ERROR_PARAMETER = 6,
|
||||
};
|
||||
|
||||
typedef struct ffxApiHeader {
|
||||
ffxStructType_t type;
|
||||
struct ffxApiHeader *pNext;
|
||||
} ffxApiHeader;
|
||||
|
||||
typedef void *(*ffxAlloc)(void *pUserData, uint64_t size);
|
||||
typedef void (*ffxDealloc)(void *pUserData, void *pMem);
|
||||
typedef struct ffxAllocationCallbacks {
|
||||
void *pUserData;
|
||||
ffxAlloc alloc;
|
||||
ffxDealloc dealloc;
|
||||
} ffxAllocationCallbacks;
|
||||
|
||||
typedef void (*ffxApiMessage)(uint32_t type, const wchar_t *message);
|
||||
|
||||
typedef struct FfxApiDimensions2D { uint32_t width, height; } FfxApiDimensions2D;
|
||||
typedef struct FfxApiFloatCoords2D { float x, y; } FfxApiFloatCoords2D;
|
||||
|
||||
typedef struct FfxApiResourceDescription {
|
||||
uint32_t type;
|
||||
uint32_t format;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
uint32_t depth;
|
||||
uint32_t mipCount;
|
||||
uint32_t flags;
|
||||
uint32_t usage;
|
||||
} FfxApiResourceDescription;
|
||||
|
||||
typedef struct FfxApiResource {
|
||||
void *resource;
|
||||
FfxApiResourceDescription description;
|
||||
uint32_t state;
|
||||
} FfxApiResource;
|
||||
|
||||
typedef struct FfxApiEffectMemoryUsage {
|
||||
uint64_t totalUsageInBytes;
|
||||
uint64_t aliasableUsageInBytes;
|
||||
} FfxApiEffectMemoryUsage;
|
||||
|
||||
#define FFX_API_QUERY_DESC_TYPE_GET_VERSIONS 4u
|
||||
#define FFX_API_DESC_TYPE_OVERRIDE_VERSION 5u
|
||||
#define FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION 6u
|
||||
#define FFX_API_CONFIGURE_DESC_TYPE_GLOBALDEBUG 7u
|
||||
|
||||
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_DX12 0x00000002u
|
||||
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK_DEPRECATED 0x00000003u
|
||||
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK 0x01000003u
|
||||
|
||||
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE 0x00010000u
|
||||
#define FFX_API_DISPATCH_DESC_TYPE_UPSCALE 0x00010001u
|
||||
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETUPSCALERATIO 0x00010002u
|
||||
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETRENDERRES 0x00010003u
|
||||
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTERPHASECOUNT 0x00010004u
|
||||
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTEROFFSET 0x00010005u
|
||||
#define FFX_API_DISPATCH_DESC_TYPE_UPSCALE_GENREACTIVEMASK 0x00010006u
|
||||
#define FFX_API_CONFIGURE_DESC_TYPE_UPSCALE_KEYVALUE 0x00010007u
|
||||
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE 0x00010008u
|
||||
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2 0x00010009u
|
||||
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GET_RESOURCE_REQS 0x0001000au
|
||||
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION 0x0001000bu
|
||||
|
||||
enum {
|
||||
FFX_UPSCALE_QUALITY_MODE_NATIVEAA = 0,
|
||||
FFX_UPSCALE_QUALITY_MODE_QUALITY = 1,
|
||||
FFX_UPSCALE_QUALITY_MODE_BALANCED = 2,
|
||||
FFX_UPSCALE_QUALITY_MODE_PERFORMANCE = 3,
|
||||
FFX_UPSCALE_QUALITY_MODE_ULTRA_PERFORMANCE = 4,
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
uint64_t createDescType;
|
||||
void *device;
|
||||
uint64_t *outputCount;
|
||||
uint64_t *versionIds;
|
||||
const char **versionNames;
|
||||
} ffxQueryDescGetVersions;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
uint64_t versionId;
|
||||
const char *versionName;
|
||||
} ffxQueryGetProviderVersion;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
uint32_t flags;
|
||||
FfxApiDimensions2D maxRenderSize;
|
||||
FfxApiDimensions2D maxUpscaleSize;
|
||||
ffxApiMessage fpMessage;
|
||||
} ffxCreateContextDescUpscale;
|
||||
|
||||
typedef struct {
|
||||
VkDevice vkDevice;
|
||||
VkPhysicalDevice vkPhysicalDevice;
|
||||
PFN_wlVkGetDeviceProcAddr vkDeviceProcAddr;
|
||||
} FfxVkDeviceContext;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
FfxVkDeviceContext deviceContext;
|
||||
} ffxCreateBackendVKDesc;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
void *device; // ID3D12Device*
|
||||
} ffxCreateBackendDX12Desc;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
void *commandList;
|
||||
FfxApiResource color;
|
||||
FfxApiResource depth;
|
||||
FfxApiResource motionVectors;
|
||||
FfxApiResource exposure;
|
||||
FfxApiResource reactive;
|
||||
FfxApiResource transparencyAndComposition;
|
||||
FfxApiResource output;
|
||||
FfxApiFloatCoords2D jitterOffset;
|
||||
FfxApiFloatCoords2D motionVectorScale;
|
||||
FfxApiDimensions2D renderSize;
|
||||
FfxApiDimensions2D upscaleSize;
|
||||
bool enableSharpening;
|
||||
float sharpness;
|
||||
float frameTimeDelta;
|
||||
float preExposure;
|
||||
bool reset;
|
||||
float cameraNear;
|
||||
float cameraFar;
|
||||
float cameraFovAngleVertical;
|
||||
float viewSpaceToMetersFactor;
|
||||
uint32_t flags;
|
||||
} ffxDispatchDescUpscale;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
uint32_t qualityMode;
|
||||
float *pOutUpscaleRatio;
|
||||
} ffxQueryDescUpscaleGetUpscaleRatio;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
uint32_t displayWidth, displayHeight, qualityMode;
|
||||
uint32_t *pOutRenderWidth, *pOutRenderHeight;
|
||||
} ffxQueryDescUpscaleGetRenderRes;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
uint32_t renderWidth, displayWidth;
|
||||
int32_t *pOutPhaseCount;
|
||||
} ffxQueryDescUpscaleGetJitterPhaseCount;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
int32_t index, phaseCount;
|
||||
float *pOutX, *pOutY;
|
||||
} ffxQueryDescUpscaleGetJitterOffset;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
FfxApiEffectMemoryUsage *gpuMemoryUsageUpscaler;
|
||||
} ffxQueryDescUpscaleGetGPUMem;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
void *device;
|
||||
FfxApiDimensions2D maxRenderSize, maxUpscaleSize;
|
||||
uint32_t flags;
|
||||
FfxApiEffectMemoryUsage *gpuMemoryUsageUpscaler;
|
||||
} ffxQueryDescUpscaleGetGPUMemV2;
|
||||
|
||||
typedef struct {
|
||||
ffxApiHeader header;
|
||||
uint64_t required_resources;
|
||||
uint64_t optional_resources;
|
||||
} ffxQueryDescUpscaleGetResourceReqs;
|
||||
|
||||
// ---- Version IDs exposed to games ----
|
||||
// Bit packing matches AMD FidelityFX SDK 2.0 (major<<22 | minor<<12 | patch) + provider tag
|
||||
#define WL_FSR4_VER_ID_4_1_1 ((4ULL << 22) | (1ULL << 12) | 1ULL)
|
||||
#define WL_FSR4_VER_ID_3_1_4 ((3ULL << 22) | (1ULL << 12) | 4ULL)
|
||||
|
||||
static const uint64_t k_ver_ids[2] = { WL_FSR4_VER_ID_4_1_1, WL_FSR4_VER_ID_3_1_4 };
|
||||
static const char *k_ver_names[2] = { "4.1.1", "3.1.4" };
|
||||
|
||||
typedef struct WlFfxUpscaleCtx {
|
||||
int is_dx12;
|
||||
int needs_reset;
|
||||
uint32_t create_flags;
|
||||
uint32_t max_rw, max_rh, max_ow, max_oh;
|
||||
void *d3d12_dev;
|
||||
WlSeamClient seam;
|
||||
WlXess3State xess3;
|
||||
WlID3D12DXVKInteropDevice1 *dx12_interop;
|
||||
} WlFfxUpscaleCtx;
|
||||
|
||||
static volatile uint32_t g_last_ffx_quality = WLFSR4_QUALITY_AUTO;
|
||||
|
||||
static uint32_t ffx_mode_to_wl_quality(uint32_t mode) {
|
||||
switch (mode) {
|
||||
case FFX_UPSCALE_QUALITY_MODE_NATIVEAA: return WLFSR4_QUALITY_NATIVE_AA;
|
||||
case FFX_UPSCALE_QUALITY_MODE_QUALITY: return WLFSR4_QUALITY_QUALITY;
|
||||
case FFX_UPSCALE_QUALITY_MODE_BALANCED: return WLFSR4_QUALITY_BALANCED;
|
||||
case FFX_UPSCALE_QUALITY_MODE_PERFORMANCE: return WLFSR4_QUALITY_PERF;
|
||||
case FFX_UPSCALE_QUALITY_MODE_ULTRA_PERFORMANCE: return WLFSR4_QUALITY_ULTRA_PERF;
|
||||
default: return WLFSR4_QUALITY_AUTO;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t ffx_infer_quality(uint32_t rw, uint32_t ow) {
|
||||
if (rw == 0u || ow == 0u) return WLFSR4_QUALITY_AUTO;
|
||||
float r = (float)ow / (float)rw;
|
||||
if (r < 1.15f) return WLFSR4_QUALITY_NATIVE_AA;
|
||||
if (r < 1.38f) return WLFSR4_QUALITY_ULTRA_QUAL;
|
||||
if (r < 1.60f) return WLFSR4_QUALITY_QUALITY;
|
||||
if (r < 1.85f) return WLFSR4_QUALITY_BALANCED;
|
||||
if (r < 2.45f) return WLFSR4_QUALITY_PERF;
|
||||
return WLFSR4_QUALITY_ULTRA_PERF;
|
||||
}
|
||||
|
||||
static float halton(int32_t index, int32_t base) {
|
||||
float f = 1.0f, r = 0.0f;
|
||||
int32_t cur = index;
|
||||
while (cur > 0) {
|
||||
f /= (float)base;
|
||||
r += f * (float)(cur % base);
|
||||
cur /= base;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
static uint32_t ffx_fmt_to_vk(uint32_t f) {
|
||||
switch (f) {
|
||||
case 3: return 109; /* R32G32B32A32_SFLOAT */
|
||||
case 4: return 97; /* R16G16B16A16_SFLOAT */
|
||||
case 6: return 103; /* R32G32_SFLOAT */
|
||||
case 10: return 37; /* R8G8B8A8_UNORM */
|
||||
case 12: return 43; /* R8G8B8A8_SRGB */
|
||||
case 14: return 44; /* B8G8R8A8_UNORM */
|
||||
case 15: return 50; /* B8G8R8A8_SRGB */
|
||||
case 16: return 122; /* B10G11R11_UFLOAT_PACK32 */
|
||||
case 17: return 64; /* A2B10G10R10_UNORM_PACK32 */
|
||||
case 18: return 83; /* R16G16_SFLOAT */
|
||||
case 28: return 100; /* R32_SFLOAT */
|
||||
default: return 0; /* let Vulkan layer look up from vkCreateImage table */
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t ffx_state_to_vk_layout(uint32_t st, int is_depth) {
|
||||
if (st & (1u << 1)) return 1; /* UNORDERED_ACCESS -> GENERAL */
|
||||
if (st & ((1u << 2) | (1u << 3))) return is_depth ? 4 : 5; /* DEPTH_STENCIL_READ_ONLY / SHADER_READ_ONLY */
|
||||
if (st & (1u << 4)) return 6; /* TRANSFER_SRC */
|
||||
if (st & (1u << 5)) return 7; /* TRANSFER_DST */
|
||||
if (st & (1u << 8)) return 2; /* COLOR_ATTACHMENT_OPTIMAL */
|
||||
if (st & (1u << 9)) return 3; /* DEPTH_STENCIL_ATTACHMENT_OPTIMAL */
|
||||
return 1; /* GENERAL */
|
||||
}
|
||||
|
||||
static float quality_ratio(uint32_t mode) {
|
||||
switch (mode) {
|
||||
case FFX_UPSCALE_QUALITY_MODE_NATIVEAA: return 1.0f;
|
||||
case FFX_UPSCALE_QUALITY_MODE_QUALITY: return 1.5f;
|
||||
case FFX_UPSCALE_QUALITY_MODE_BALANCED: return 1.7f;
|
||||
case FFX_UPSCALE_QUALITY_MODE_PERFORMANCE: return 2.0f;
|
||||
case FFX_UPSCALE_QUALITY_MODE_ULTRA_PERFORMANCE: return 3.0f;
|
||||
default: return 2.0f;
|
||||
}
|
||||
}
|
||||
|
||||
__declspec(dllexport) ffxReturnCode_t ffxCreateContext(ffxContext *context, ffxApiHeader *desc, const ffxAllocationCallbacks *memCb) {
|
||||
(void)memCb;
|
||||
if (!context || !desc) return FFX_API_RETURN_ERROR_PARAMETER;
|
||||
|
||||
const ffxCreateContextDescUpscale *up = NULL;
|
||||
const ffxCreateBackendVKDesc *bvk = NULL;
|
||||
const ffxCreateBackendDX12Desc *bdx = NULL;
|
||||
|
||||
for (const ffxApiHeader *h = desc; h; h = h->pNext) {
|
||||
if (h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE) up = (const ffxCreateContextDescUpscale *)h;
|
||||
else if (h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK ||
|
||||
h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK_DEPRECATED) bvk = (const ffxCreateBackendVKDesc *)h;
|
||||
else if (h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_DX12) bdx = (const ffxCreateBackendDX12Desc *)h;
|
||||
}
|
||||
if (!up) return FFX_API_RETURN_NO_PROVIDER;
|
||||
|
||||
WlFfxUpscaleCtx *ctx = (WlFfxUpscaleCtx *)calloc(1, sizeof *ctx);
|
||||
if (!ctx) return FFX_API_RETURN_ERROR_MEMORY;
|
||||
|
||||
ctx->create_flags = up->flags;
|
||||
ctx->needs_reset = 1;
|
||||
ctx->max_rw = up->maxRenderSize.width;
|
||||
ctx->max_rh = up->maxRenderSize.height;
|
||||
ctx->max_ow = up->maxUpscaleSize.width;
|
||||
ctx->max_oh = up->maxUpscaleSize.height;
|
||||
|
||||
if (bvk && bvk->deviceContext.vkDevice) {
|
||||
ctx->is_dx12 = 0;
|
||||
wl_seam_init(&ctx->seam, NULL, bvk->deviceContext.vkPhysicalDevice,
|
||||
bvk->deviceContext.vkDevice, bvk->deviceContext.vkDeviceProcAddr);
|
||||
} else if (bdx && bdx->device) {
|
||||
ctx->is_dx12 = 1;
|
||||
ctx->d3d12_dev = bdx->device;
|
||||
ctx->dx12_interop = wl_query_vkd3d_interop(bdx->device);
|
||||
if (ctx->dx12_interop) {
|
||||
void *vk_inst = NULL, *vk_phys = NULL, *vk_dev = NULL;
|
||||
if (ctx->dx12_interop->lpVtbl->GetVulkanHandles(ctx->dx12_interop, &vk_inst, &vk_phys, &vk_dev) == S_OK && vk_dev) {
|
||||
wl_seam_init(&ctx->seam, vk_inst, vk_phys, vk_dev, NULL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
*context = ctx;
|
||||
return FFX_API_RETURN_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) ffxReturnCode_t ffxDestroyContext(ffxContext *context, const ffxAllocationCallbacks *memCb) {
|
||||
(void)memCb;
|
||||
if (!context || !*context) return FFX_API_RETURN_OK;
|
||||
WlFfxUpscaleCtx *ctx = (WlFfxUpscaleCtx *)(*context);
|
||||
wl_xess3_destroy(&ctx->xess3);
|
||||
wl_seam_destroy(&ctx->seam);
|
||||
if (ctx->dx12_interop) {
|
||||
ctx->dx12_interop->lpVtbl->Release(ctx->dx12_interop);
|
||||
ctx->dx12_interop = NULL;
|
||||
}
|
||||
free(ctx);
|
||||
*context = NULL;
|
||||
return FFX_API_RETURN_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) ffxReturnCode_t ffxConfigure(ffxContext *context, const ffxApiHeader *desc) {
|
||||
(void)context; (void)desc;
|
||||
return FFX_API_RETURN_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) ffxReturnCode_t ffxQuery(ffxContext *context, ffxApiHeader *desc) {
|
||||
(void)context;
|
||||
if (!desc) return FFX_API_RETURN_ERROR_PARAMETER;
|
||||
|
||||
for (ffxApiHeader *h = desc; h; h = h->pNext) {
|
||||
switch (h->type) {
|
||||
case FFX_API_QUERY_DESC_TYPE_GET_VERSIONS: {
|
||||
ffxQueryDescGetVersions *q = (ffxQueryDescGetVersions *)h;
|
||||
if (!q->outputCount) return FFX_API_RETURN_ERROR_PARAMETER;
|
||||
uint64_t cap = *q->outputCount;
|
||||
if (cap == 0 || (!q->versionIds && !q->versionNames)) {
|
||||
*q->outputCount = 2;
|
||||
break;
|
||||
}
|
||||
uint64_t n = cap < 2 ? cap : 2;
|
||||
for (uint64_t i = 0; i < n; i++) {
|
||||
if (q->versionIds) q->versionIds[i] = k_ver_ids[i];
|
||||
if (q->versionNames) q->versionNames[i] = k_ver_names[i];
|
||||
}
|
||||
*q->outputCount = n;
|
||||
break;
|
||||
}
|
||||
case FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION: {
|
||||
ffxQueryGetProviderVersion *q = (ffxQueryGetProviderVersion *)h;
|
||||
q->versionId = WL_FSR4_VER_ID_4_1_1;
|
||||
q->versionName = "4.1.1";
|
||||
break;
|
||||
}
|
||||
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GETUPSCALERATIO: {
|
||||
ffxQueryDescUpscaleGetUpscaleRatio *q = (ffxQueryDescUpscaleGetUpscaleRatio *)h;
|
||||
g_last_ffx_quality = ffx_mode_to_wl_quality(q->qualityMode);
|
||||
if (q->pOutUpscaleRatio) *q->pOutUpscaleRatio = quality_ratio(q->qualityMode);
|
||||
break;
|
||||
}
|
||||
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GETRENDERRES: {
|
||||
ffxQueryDescUpscaleGetRenderRes *q = (ffxQueryDescUpscaleGetRenderRes *)h;
|
||||
g_last_ffx_quality = ffx_mode_to_wl_quality(q->qualityMode);
|
||||
float r = quality_ratio(q->qualityMode);
|
||||
if (q->pOutRenderWidth) *q->pOutRenderWidth = (uint32_t)((float)q->displayWidth / r);
|
||||
if (q->pOutRenderHeight) *q->pOutRenderHeight = (uint32_t)((float)q->displayHeight / r);
|
||||
break;
|
||||
}
|
||||
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTERPHASECOUNT: {
|
||||
ffxQueryDescUpscaleGetJitterPhaseCount *q = (ffxQueryDescUpscaleGetJitterPhaseCount *)h;
|
||||
if (q->pOutPhaseCount && q->renderWidth > 0) {
|
||||
float ratio = (float)q->displayWidth / (float)q->renderWidth;
|
||||
int32_t pc = (int32_t)ceilf(8.0f * ratio * ratio);
|
||||
if (pc < 8) pc = 8;
|
||||
*q->pOutPhaseCount = pc;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTEROFFSET: {
|
||||
ffxQueryDescUpscaleGetJitterOffset *q = (ffxQueryDescUpscaleGetJitterOffset *)h;
|
||||
int32_t pc = q->phaseCount > 0 ? q->phaseCount : 8;
|
||||
int32_t idx = (q->index % pc) + 1;
|
||||
if (idx <= 0) idx += pc;
|
||||
if (q->pOutX) *q->pOutX = halton(idx, 2) - 0.5f;
|
||||
if (q->pOutY) *q->pOutY = halton(idx, 3) - 0.5f;
|
||||
break;
|
||||
}
|
||||
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE: {
|
||||
ffxQueryDescUpscaleGetGPUMem *q = (ffxQueryDescUpscaleGetGPUMem *)h;
|
||||
if (q->gpuMemoryUsageUpscaler) {
|
||||
q->gpuMemoryUsageUpscaler->totalUsageInBytes = 64ULL * 1024ULL * 1024ULL;
|
||||
q->gpuMemoryUsageUpscaler->aliasableUsageInBytes = 0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2: {
|
||||
ffxQueryDescUpscaleGetGPUMemV2 *q = (ffxQueryDescUpscaleGetGPUMemV2 *)h;
|
||||
if (q->gpuMemoryUsageUpscaler) {
|
||||
q->gpuMemoryUsageUpscaler->totalUsageInBytes = 64ULL * 1024ULL * 1024ULL;
|
||||
q->gpuMemoryUsageUpscaler->aliasableUsageInBytes = 0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case FFX_API_QUERY_DESC_TYPE_UPSCALE_GET_RESOURCE_REQS: {
|
||||
ffxQueryDescUpscaleGetResourceReqs *q = (ffxQueryDescUpscaleGetResourceReqs *)h;
|
||||
q->required_resources = (1ULL << 0) | (1ULL << 1) | (1ULL << 2); /* COLOR | DEPTH | MV */
|
||||
q->optional_resources = (1ULL << 3) | (1ULL << 4) | (1ULL << 5);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return FFX_API_RETURN_OK;
|
||||
}
|
||||
|
||||
static void fill_vk_img_ref(WlFsr4ImageRef *dst, const FfxApiResource *src, int is_depth) {
|
||||
memset(dst, 0, sizeof *dst);
|
||||
if (!src || !src->resource) return;
|
||||
dst->vk_image = (uint64_t)(uintptr_t)src->resource;
|
||||
dst->vk_format = ffx_fmt_to_vk(src->description.format);
|
||||
dst->vk_layout = ffx_state_to_vk_layout(src->state, is_depth);
|
||||
dst->width = src->description.width;
|
||||
dst->height = src->description.height;
|
||||
dst->aspect = is_depth ? 2u : 1u;
|
||||
}
|
||||
|
||||
static void fill_dx12_img_ref(WlID3D12DXVKInteropDevice1 *interop, WlFsr4ImageRef *dst, const FfxApiResource *src, int is_depth) {
|
||||
memset(dst, 0, sizeof *dst);
|
||||
if (!interop || !src || !src->resource) return;
|
||||
UINT64 vk_img = 0, off = 0;
|
||||
UINT32 vk_fmt = 0;
|
||||
if (wl_vkd3d_resource_info(interop, src->resource, &vk_img, &off, &vk_fmt) == S_OK && vk_img) {
|
||||
dst->vk_image = vk_img;
|
||||
dst->vk_format = vk_fmt ? vk_fmt : ffx_fmt_to_vk(src->description.format);
|
||||
dst->vk_layout = ffx_state_to_vk_layout(src->state, is_depth);
|
||||
dst->width = src->description.width;
|
||||
dst->height = src->description.height;
|
||||
dst->aspect = is_depth ? 2u : 1u;
|
||||
}
|
||||
}
|
||||
|
||||
__declspec(dllexport) ffxReturnCode_t ffxDispatch(ffxContext *context, const ffxApiHeader *desc) {
|
||||
if (!context || !*context || !desc) return FFX_API_RETURN_ERROR_PARAMETER;
|
||||
WlFfxUpscaleCtx *ctx = (WlFfxUpscaleCtx *)(*context);
|
||||
|
||||
for (const ffxApiHeader *h = desc; h; h = h->pNext) {
|
||||
if (h->type != FFX_API_DISPATCH_DESC_TYPE_UPSCALE) continue;
|
||||
const ffxDispatchDescUpscale *d = (const ffxDispatchDescUpscale *)h;
|
||||
if (!d->commandList || !ctx->seam.ready) return FFX_API_RETURN_ERROR_RUNTIME_ERROR;
|
||||
|
||||
WlFsr4FrameDesc f;
|
||||
memset(&f, 0, sizeof f);
|
||||
f.render_w = d->renderSize.width ? d->renderSize.width : ctx->max_rw;
|
||||
f.render_h = d->renderSize.height ? d->renderSize.height : ctx->max_rh;
|
||||
f.output_w = d->upscaleSize.width ? d->upscaleSize.width : ctx->max_ow;
|
||||
f.output_h = d->upscaleSize.height ? d->upscaleSize.height : ctx->max_oh;
|
||||
f.jitter_x = d->jitterOffset.x;
|
||||
f.jitter_y = d->jitterOffset.y;
|
||||
f.mv_scale_x = d->motionVectorScale.x != 0.f ? d->motionVectorScale.x : 1.f;
|
||||
f.mv_scale_y = d->motionVectorScale.y != 0.f ? d->motionVectorScale.y : 1.f;
|
||||
f.pre_exposure = d->preExposure > 0.f ? d->preExposure : 1.f;
|
||||
f.sharpness = d->sharpness;
|
||||
f.frame_time_ms = d->frameTimeDelta;
|
||||
f.camera_near = d->cameraNear;
|
||||
f.camera_far = d->cameraFar;
|
||||
f.camera_fov_y = d->cameraFovAngleVertical;
|
||||
if (d->reset || ctx->needs_reset) {
|
||||
f.flags |= WLFSR4_FLAG_RESET;
|
||||
ctx->needs_reset = 0;
|
||||
}
|
||||
if (ctx->create_flags & (1u << 0)) f.flags |= WLFSR4_FLAG_HDR;
|
||||
if (ctx->create_flags & (1u << 1)) f.flags |= WLFSR4_FLAG_DISPLAY_RES_MV;
|
||||
if (ctx->create_flags & (1u << 2)) f.flags |= WLFSR4_FLAG_MV_JITTERED;
|
||||
if (ctx->create_flags & (1u << 3)) f.flags |= WLFSR4_FLAG_DEPTH_INVERTED;
|
||||
if (ctx->create_flags & (1u << 5)) f.flags |= WLFSR4_FLAG_AUTO_EXPOSURE;
|
||||
if (d->enableSharpening) f.flags |= WLFSR4_FLAG_SHARPEN;
|
||||
f.quality_mode = (g_last_ffx_quality != WLFSR4_QUALITY_AUTO)
|
||||
? g_last_ffx_quality
|
||||
: ffx_infer_quality(f.render_w, f.output_w);
|
||||
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
|
||||
|
||||
if (!ctx->is_dx12) {
|
||||
f.api_source = WLFSR4_API_FFX_VK;
|
||||
fill_vk_img_ref(&f.color, &d->color, 0);
|
||||
fill_vk_img_ref(&f.depth, &d->depth, 1);
|
||||
fill_vk_img_ref(&f.motion, &d->motionVectors, 0);
|
||||
fill_vk_img_ref(&f.output, &d->output, 0);
|
||||
fill_vk_img_ref(&f.reactive, &d->reactive, 0);
|
||||
fill_vk_img_ref(&f.exposure, &d->exposure, 0);
|
||||
if (!wl_seam_dispatch_or_blit(&ctx->seam, (VkCommandBuffer)d->commandList, &f))
|
||||
return FFX_API_RETURN_ERROR_RUNTIME_ERROR;
|
||||
} else if (ctx->dx12_interop) {
|
||||
f.api_source = WLFSR4_API_FFX_DX12;
|
||||
fill_dx12_img_ref(ctx->dx12_interop, &f.color, &d->color, 0);
|
||||
fill_dx12_img_ref(ctx->dx12_interop, &f.depth, &d->depth, 1);
|
||||
fill_dx12_img_ref(ctx->dx12_interop, &f.motion, &d->motionVectors, 0);
|
||||
fill_dx12_img_ref(ctx->dx12_interop, &f.output, &d->output, 0);
|
||||
fill_dx12_img_ref(ctx->dx12_interop, &f.reactive, &d->reactive, 0);
|
||||
fill_dx12_img_ref(ctx->dx12_interop, &f.exposure, &d->exposure, 0);
|
||||
|
||||
int live_en = 1;
|
||||
int live_backend = wl_seam_live_backend(&ctx->seam, &live_en);
|
||||
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU && ctx->d3d12_dev) {
|
||||
if (wl_xess3_eval_d3d12(&ctx->xess3, &ctx->seam, ctx->dx12_interop,
|
||||
ctx->d3d12_dev, d->commandList, &f,
|
||||
d->color.resource, d->depth.resource,
|
||||
d->motionVectors.resource, d->output.resource)) {
|
||||
continue;
|
||||
}
|
||||
wl_xess3_tag_fallback(&ctx->xess3, &f);
|
||||
} else {
|
||||
wl_xess3_on_inactive(&ctx->xess3);
|
||||
}
|
||||
|
||||
void *vk_cb = NULL;
|
||||
int ok = 0;
|
||||
void *cl_used = NULL;
|
||||
if (wl_vkd3d_begin_cb(ctx->dx12_interop, d->commandList, &vk_cb, &cl_used)) {
|
||||
ok = wl_seam_dispatch_or_blit(&ctx->seam, (VkCommandBuffer)vk_cb, &f);
|
||||
wl_vkd3d_end_cb(ctx->dx12_interop, d->commandList, cl_used);
|
||||
}
|
||||
if (!ok) return FFX_API_RETURN_ERROR_RUNTIME_ERROR;
|
||||
}
|
||||
}
|
||||
return FFX_API_RETURN_OK;
|
||||
}
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
|
||||
(void)hinst; (void)reason; (void)reserved;
|
||||
return TRUE;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
EXPORTS
|
||||
ffxCreateContext
|
||||
ffxDestroyContext
|
||||
ffxConfigure
|
||||
ffxQuery
|
||||
ffxDispatch
|
||||
@@ -0,0 +1,895 @@
|
||||
// Winlator Ludashi AMD FSR 3 (ffx_fsr3upscaler_x64.dll) & External FSR 2 (ffx_fsr2_api_x64.dll)
|
||||
// -> AMD FSR 4 INT8 Hexagon HTP NPU Bridge
|
||||
//
|
||||
// Supports BOTH DirectX 12 (via vkd3d-proton zero-copy interop) and Vulkan,
|
||||
// auto-detecting FSR 3.0 vs FSR 3.1 and FSR 2.0 vs FSR 2.1/2.2 struct layouts.
|
||||
// Requires ZERO GPU spoofing — runs cleanly on Adreno/Turnip in No-GPU-Spoof mode.
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "wl_seam_client.h"
|
||||
#include "wl_vkd3d_interop.h"
|
||||
#include "wl_xess3_direct.h"
|
||||
|
||||
// ---- Common FFX error & basic types ----
|
||||
typedef int32_t FfxErrorCode;
|
||||
#define FFX_OK 0
|
||||
#define FFX_ERROR_INVALID_POINTER (-2147483647 - 1)
|
||||
#define FFX_ERROR_INVALID_ALIGNMENT (-2147483647)
|
||||
#define FFX_ERROR_INVALID_SIZE (-2147483646)
|
||||
#define FFX_ERROR_EOF (-2147483645)
|
||||
#define FFX_ERROR_INVALID_PATH (-2147483644)
|
||||
#define FFX_ERROR_EOF_EX (-2147483643)
|
||||
#define FFX_ERROR_MALFORMED_DATA (-2147483642)
|
||||
#define FFX_ERROR_OUT_OF_MEMORY (-2147483641)
|
||||
#define FFX_ERROR_INCOMPLETE_INTERFACE (-2147483640)
|
||||
#define FFX_ERROR_INVALID_ENUM (-2147483639)
|
||||
#define FFX_ERROR_INVALID_ARGUMENT (-2147483638)
|
||||
#define FFX_ERROR_OUT_OF_RANGE (-2147483637)
|
||||
#define FFX_ERROR_NULL_DEVICE (-2147483636)
|
||||
|
||||
typedef struct { uint32_t width, height; } WlFfxDim2D;
|
||||
typedef struct { float x, y; } WlFfxFloat2D;
|
||||
|
||||
// ---- FSR 3 ABI structs (verified from FidelityFX SDK 1.0/1.1 fsr3 & fsr31) ----
|
||||
typedef struct {
|
||||
uint32_t type;
|
||||
uint32_t format;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
uint32_t depth;
|
||||
uint32_t mipCount;
|
||||
uint32_t flags;
|
||||
uint32_t usage;
|
||||
} WlFfxResDesc3;
|
||||
|
||||
typedef struct {
|
||||
void *resource;
|
||||
WlFfxResDesc3 description;
|
||||
uint32_t state;
|
||||
uint16_t name[64];
|
||||
} WlFfxResource3;
|
||||
|
||||
typedef struct {
|
||||
uint32_t heapType;
|
||||
WlFfxResDesc3 resourceDescription;
|
||||
uint32_t initialState;
|
||||
uint32_t initDataSize;
|
||||
void *initData;
|
||||
const uint16_t *name;
|
||||
uint32_t id;
|
||||
} WlFfxCreateResDesc3;
|
||||
|
||||
typedef struct {
|
||||
WlFfxCreateResDesc3 reconstructedPrevNearestDepth;
|
||||
WlFfxCreateResDesc3 dilatedDepth;
|
||||
WlFfxCreateResDesc3 dilatedMotionVectors;
|
||||
} WlFfxFsr3SharedResDescs;
|
||||
|
||||
typedef struct {
|
||||
void *callbacks[16];
|
||||
void *scratchBuffer;
|
||||
size_t scratchBufferSize;
|
||||
void *device;
|
||||
} WlFfxInterface3;
|
||||
|
||||
typedef struct {
|
||||
uint32_t flags;
|
||||
WlFfxDim2D maxRenderSize;
|
||||
WlFfxDim2D displaySize;
|
||||
WlFfxInterface3 backendInterface;
|
||||
void *fpMessage;
|
||||
} WlFfxFsr30CtxDesc;
|
||||
|
||||
typedef struct {
|
||||
uint32_t flags;
|
||||
WlFfxDim2D maxRenderSize;
|
||||
WlFfxDim2D maxUpscaleSize;
|
||||
void *fpMessage;
|
||||
WlFfxInterface3 backendInterface;
|
||||
} WlFfxFsr31CtxDesc;
|
||||
|
||||
typedef struct {
|
||||
void *commandList;
|
||||
WlFfxResource3 color;
|
||||
WlFfxResource3 depth;
|
||||
WlFfxResource3 motionVectors;
|
||||
WlFfxResource3 exposure;
|
||||
WlFfxResource3 reactive;
|
||||
WlFfxResource3 transparencyAndComposition;
|
||||
WlFfxResource3 dilatedDepth;
|
||||
WlFfxResource3 dilatedMotionVectors;
|
||||
WlFfxResource3 reconstructedPrevNearestDepth;
|
||||
WlFfxResource3 output;
|
||||
WlFfxFloat2D jitterOffset;
|
||||
WlFfxFloat2D motionVectorScale;
|
||||
WlFfxDim2D renderSize;
|
||||
bool enableSharpening;
|
||||
float sharpness;
|
||||
float frameTimeDelta;
|
||||
float preExposure;
|
||||
bool reset;
|
||||
float cameraNear;
|
||||
float cameraFar;
|
||||
float cameraFovAngleVertical;
|
||||
float viewSpaceToMetersFactor;
|
||||
} WlFfxFsr30DispatchDesc;
|
||||
|
||||
typedef struct {
|
||||
void *commandList;
|
||||
WlFfxResource3 color;
|
||||
WlFfxResource3 depth;
|
||||
WlFfxResource3 motionVectors;
|
||||
WlFfxResource3 exposure;
|
||||
WlFfxResource3 reactive;
|
||||
WlFfxResource3 transparencyAndComposition;
|
||||
WlFfxResource3 dilatedDepth;
|
||||
WlFfxResource3 dilatedMotionVectors;
|
||||
WlFfxResource3 reconstructedPrevNearestDepth;
|
||||
WlFfxResource3 output;
|
||||
WlFfxFloat2D jitterOffset;
|
||||
WlFfxFloat2D motionVectorScale;
|
||||
WlFfxDim2D renderSize;
|
||||
WlFfxDim2D upscaleSize;
|
||||
bool enableSharpening;
|
||||
float sharpness;
|
||||
float frameTimeDelta;
|
||||
float preExposure;
|
||||
bool reset;
|
||||
float cameraNear;
|
||||
float cameraFar;
|
||||
float cameraFovAngleVertical;
|
||||
float viewSpaceToMetersFactor;
|
||||
uint32_t flags;
|
||||
} WlFfxFsr31DispatchDesc;
|
||||
|
||||
// ---- FSR 2 ABI structs (verified from FidelityFX FSR 2.0 / 2.1.2 / 2.2.1) ----
|
||||
typedef struct {
|
||||
uint32_t type;
|
||||
uint32_t format;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
uint32_t depth;
|
||||
uint32_t mipCount;
|
||||
uint32_t flags;
|
||||
} WlFfxResDesc2;
|
||||
|
||||
typedef struct {
|
||||
void *resource;
|
||||
uint16_t name[64];
|
||||
WlFfxResDesc2 description;
|
||||
uint32_t state;
|
||||
bool isDepth;
|
||||
uint64_t descriptorData;
|
||||
} WlFfxResource21;
|
||||
|
||||
typedef struct {
|
||||
void *resource;
|
||||
WlFfxResDesc2 description;
|
||||
uint32_t state;
|
||||
bool isDepth;
|
||||
uint64_t descriptorData;
|
||||
} WlFfxResource20;
|
||||
|
||||
typedef struct {
|
||||
void *callbacks[12];
|
||||
void *scratchBuffer;
|
||||
size_t scratchBufferSize;
|
||||
} WlFfxInterface2;
|
||||
|
||||
typedef struct {
|
||||
uint32_t flags;
|
||||
WlFfxDim2D maxRenderSize;
|
||||
WlFfxDim2D displaySize;
|
||||
WlFfxInterface2 callbacks;
|
||||
void *device;
|
||||
} WlFfxFsr2CtxDesc;
|
||||
|
||||
typedef struct {
|
||||
void *commandList;
|
||||
WlFfxResource21 color;
|
||||
WlFfxResource21 depth;
|
||||
WlFfxResource21 motionVectors;
|
||||
WlFfxResource21 exposure;
|
||||
WlFfxResource21 reactive;
|
||||
WlFfxResource21 transparencyAndComposition;
|
||||
WlFfxResource21 output;
|
||||
WlFfxFloat2D jitterOffset;
|
||||
WlFfxFloat2D motionVectorScale;
|
||||
WlFfxDim2D renderSize;
|
||||
bool enableSharpening;
|
||||
float sharpness;
|
||||
float frameTimeDelta;
|
||||
float preExposure;
|
||||
bool reset;
|
||||
float cameraNear;
|
||||
float cameraFar;
|
||||
float cameraFovAngleVertical;
|
||||
} WlFfxFsr21DispatchDesc;
|
||||
|
||||
typedef struct {
|
||||
void *commandList;
|
||||
WlFfxResource20 color;
|
||||
WlFfxResource20 depth;
|
||||
WlFfxResource20 motionVectors;
|
||||
WlFfxResource20 exposure;
|
||||
WlFfxResource20 reactive;
|
||||
WlFfxResource20 transparencyAndComposition;
|
||||
WlFfxResource20 output;
|
||||
WlFfxFloat2D jitterOffset;
|
||||
WlFfxFloat2D motionVectorScale;
|
||||
WlFfxDim2D renderSize;
|
||||
bool enableSharpening;
|
||||
float sharpness;
|
||||
float frameTimeDelta;
|
||||
float preExposure;
|
||||
bool reset;
|
||||
float cameraNear;
|
||||
float cameraFar;
|
||||
float cameraFovAngleVertical;
|
||||
} WlFfxFsr20DispatchDesc;
|
||||
|
||||
typedef struct {
|
||||
VkDevice vkDevice;
|
||||
VkPhysicalDevice vkPhysicalDevice;
|
||||
PFN_wlVkGetDeviceProcAddr vkDeviceProcAddr;
|
||||
} WlFfxVkDevCtx3;
|
||||
|
||||
// ---- Shared Helpers ----
|
||||
#define WL_FSR23_MAGIC 0x574C4632u /* "WLF2" */
|
||||
|
||||
typedef struct WlFsr23Ctx {
|
||||
uint32_t magic;
|
||||
int is_fsr3;
|
||||
int is_fsr31;
|
||||
int is_dx12;
|
||||
int needs_reset;
|
||||
uint32_t flags;
|
||||
uint32_t max_rw, max_rh;
|
||||
uint32_t disp_w, disp_h;
|
||||
void *d3d12_dev;
|
||||
WlSeamClient seam;
|
||||
WlXess3State xess3;
|
||||
WlID3D12DXVKInteropDevice1 *dx12_interop;
|
||||
} WlFsr23Ctx;
|
||||
|
||||
typedef struct {
|
||||
uint32_t magic;
|
||||
uint32_t pad;
|
||||
WlFsr23Ctx *ctx;
|
||||
} WlFsrContextHeader;
|
||||
|
||||
static volatile uint32_t g_last_quality_mode = WLFSR4_QUALITY_AUTO;
|
||||
|
||||
static float fsr_halton(int32_t index, int32_t base) {
|
||||
float f = 1.0f, r = 0.0f;
|
||||
int32_t cur = index;
|
||||
while (cur > 0) {
|
||||
f /= (float)base;
|
||||
r += f * (float)(cur % base);
|
||||
cur /= base;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
static float fsr_quality_ratio(uint32_t mode) {
|
||||
switch (mode) {
|
||||
case 0: return 1.0f; /* Native AA */
|
||||
case 1: return 1.5f; /* Quality */
|
||||
case 2: return 1.7f; /* Balanced */
|
||||
case 3: return 2.0f; /* Performance */
|
||||
case 4: return 3.0f; /* Ultra Performance */
|
||||
default: return 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t fsr_mode_to_wl(uint32_t mode) {
|
||||
switch (mode) {
|
||||
case 0: return WLFSR4_QUALITY_NATIVE_AA;
|
||||
case 1: return WLFSR4_QUALITY_QUALITY;
|
||||
case 2: return WLFSR4_QUALITY_BALANCED;
|
||||
case 3: return WLFSR4_QUALITY_PERF;
|
||||
case 4: return WLFSR4_QUALITY_ULTRA_PERF;
|
||||
default: return WLFSR4_QUALITY_AUTO;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t fsr_infer_quality(uint32_t rw, uint32_t ow) {
|
||||
if (rw == 0u || ow == 0u) return WLFSR4_QUALITY_AUTO;
|
||||
float r = (float)ow / (float)rw;
|
||||
if (r < 1.15f) return WLFSR4_QUALITY_NATIVE_AA;
|
||||
if (r < 1.38f) return WLFSR4_QUALITY_ULTRA_QUAL;
|
||||
if (r < 1.60f) return WLFSR4_QUALITY_QUALITY;
|
||||
if (r < 1.85f) return WLFSR4_QUALITY_BALANCED;
|
||||
if (r < 2.45f) return WLFSR4_QUALITY_PERF;
|
||||
return WLFSR4_QUALITY_ULTRA_PERF;
|
||||
}
|
||||
|
||||
static uint32_t fsr_fmt_to_vk(uint32_t f) {
|
||||
switch (f) {
|
||||
case 3: return 109; /* R32G32B32A32_SFLOAT */
|
||||
case 4: return 97; /* R16G16B16A16_SFLOAT */
|
||||
case 5: return 103; /* R32G32_SFLOAT */
|
||||
case 8: return 64; /* A2B10G10R10_UNORM_PACK32 */
|
||||
case 10: return 37; /* R8G8B8A8_UNORM */
|
||||
case 12: return 43; /* R8G8B8A8_SRGB */
|
||||
case 13: return 122; /* B10G11R11_UFLOAT_PACK32 */
|
||||
case 14: return 83; /* R16G16_SFLOAT */
|
||||
case 24: return 100; /* R32_SFLOAT */
|
||||
default: return 0; /* layer resolves from vkCreateImage table */
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t fsr_state_to_vk_layout(uint32_t st, int is_depth) {
|
||||
if (st & (1u << 1)) return 1u; /* UNORDERED_ACCESS -> GENERAL */
|
||||
if (st & ((1u << 2) | (1u << 3))) return is_depth ? 4u : 5u; /* COMPUTE/PIXEL_READ */
|
||||
if (st & (1u << 4)) return 6u; /* COPY_SRC */
|
||||
if (st & (1u << 5)) return 7u; /* COPY_DEST */
|
||||
if (st & (1u << 8)) return 2u; /* RENDER_TARGET */
|
||||
return 1u;
|
||||
}
|
||||
|
||||
static uint32_t fsr_state_to_d3d12(uint32_t st) {
|
||||
if (st & (1u << 1)) return 0x8u; /* UNORDERED_ACCESS */
|
||||
if (st & (1u << 2)) return 0x40u; /* NON_PIXEL_SHADER_RESOURCE */
|
||||
if (st & (1u << 3)) return 0x80u; /* PIXEL_SHADER_RESOURCE */
|
||||
if (st & (1u << 4)) return 0x800u; /* COPY_SOURCE */
|
||||
if (st & (1u << 5)) return 0x400u; /* COPY_DEST */
|
||||
if (st & (1u << 8)) return 0x4u; /* RENDER_TARGET */
|
||||
return 0x40u;
|
||||
}
|
||||
|
||||
static uint32_t fsr_flags_to_wl(uint32_t flags) {
|
||||
uint32_t out = 0;
|
||||
if (flags & (1u << 0)) out |= WLFSR4_FLAG_HDR;
|
||||
if (flags & (1u << 1)) out |= WLFSR4_FLAG_DISPLAY_RES_MV;
|
||||
if (flags & (1u << 2)) out |= WLFSR4_FLAG_MV_JITTERED;
|
||||
if (flags & (1u << 3)) out |= WLFSR4_FLAG_DEPTH_INVERTED;
|
||||
if (flags & (1u << 5)) out |= WLFSR4_FLAG_AUTO_EXPOSURE;
|
||||
return out;
|
||||
}
|
||||
|
||||
static int ptr_belongs_to_vk_backend(void *fn_ptr) {
|
||||
if (!fn_ptr) return 0;
|
||||
HMODULE hm = NULL;
|
||||
if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
|
||||
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
(LPCSTR)fn_ptr, &hm) || !hm) {
|
||||
return 0;
|
||||
}
|
||||
char path[MAX_PATH];
|
||||
DWORD len = GetModuleFileNameA(hm, path, MAX_PATH);
|
||||
if (!len) return 0;
|
||||
for (DWORD i = 0; i < len; i++) {
|
||||
if (path[i] >= 'A' && path[i] <= 'Z') path[i] = (char)(path[i] - 'A' + 'a');
|
||||
}
|
||||
if (strstr(path, "_vk") || strstr(path, "vulkan")) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int ptr_belongs_to_dx12_backend(void *fn_ptr) {
|
||||
if (!fn_ptr) return 0;
|
||||
HMODULE hm = NULL;
|
||||
if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
|
||||
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
(LPCSTR)fn_ptr, &hm) || !hm) {
|
||||
return 0;
|
||||
}
|
||||
char path[MAX_PATH];
|
||||
DWORD len = GetModuleFileNameA(hm, path, MAX_PATH);
|
||||
if (!len) return 0;
|
||||
for (DWORD i = 0; i < len; i++) {
|
||||
if (path[i] >= 'A' && path[i] <= 'Z') path[i] = (char)(path[i] - 'A' + 'a');
|
||||
}
|
||||
if (strstr(path, "dx12") || strstr(path, "d3d12")) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void fsr_init_backend(WlFsr23Ctx *ctx, void *ffx_device, void *cb_probe, int is_fsr3) {
|
||||
if (!ffx_device) return;
|
||||
int is_vk = ptr_belongs_to_vk_backend(cb_probe);
|
||||
int is_dx = ptr_belongs_to_dx12_backend(cb_probe);
|
||||
|
||||
if (!is_vk && !is_dx) {
|
||||
// Fallback heuristic: if d3d12.dll is loaded, prefer DX12 unless vk backend module is present
|
||||
if (GetModuleHandleA("ffx_backend_vk_x64.dll") || GetModuleHandleA("ffx_fsr2_api_vk_x64.dll")) {
|
||||
is_vk = 1;
|
||||
} else if (GetModuleHandleA("d3d12.dll")) {
|
||||
is_dx = 1;
|
||||
} else if (GetModuleHandleA("vulkan-1.dll")) {
|
||||
is_vk = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (is_vk) {
|
||||
ctx->is_dx12 = 0;
|
||||
if (is_fsr3) {
|
||||
// FSR 3 VK passes FfxVkDeviceContext* as FfxDevice
|
||||
const WlFfxVkDevCtx3 *vkc = (const WlFfxVkDevCtx3 *)ffx_device;
|
||||
if (vkc->vkDevice) {
|
||||
wl_seam_init(&ctx->seam, NULL, vkc->vkPhysicalDevice, vkc->vkDevice, vkc->vkDeviceProcAddr);
|
||||
}
|
||||
} else {
|
||||
// FSR 2 VK passes VkDevice directly as FfxDevice
|
||||
wl_seam_init(&ctx->seam, NULL, NULL, (VkDevice)ffx_device, NULL);
|
||||
}
|
||||
} else {
|
||||
ctx->is_dx12 = 1;
|
||||
ctx->d3d12_dev = ffx_device;
|
||||
ctx->dx12_interop = wl_query_vkd3d_interop(ffx_device);
|
||||
if (ctx->dx12_interop) {
|
||||
void *vk_inst = NULL, *vk_phys = NULL, *vk_dev = NULL;
|
||||
if (ctx->dx12_interop->lpVtbl->GetVulkanHandles(ctx->dx12_interop, &vk_inst, &vk_phys, &vk_dev) == S_OK && vk_dev) {
|
||||
wl_seam_init(&ctx->seam, vk_inst, vk_phys, vk_dev, NULL);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void fsr_fill_ref(WlFsr23Ctx *ctx, WlFsr4ImageRef *dst, void *res,
|
||||
uint32_t ffx_fmt, uint32_t ffx_state, uint32_t w, uint32_t h, int is_depth) {
|
||||
memset(dst, 0, sizeof *dst);
|
||||
if (!res) return;
|
||||
if (!ctx->is_dx12) {
|
||||
dst->vk_image = (uint64_t)(uintptr_t)res;
|
||||
dst->vk_format = fsr_fmt_to_vk(ffx_fmt);
|
||||
dst->vk_layout = fsr_state_to_vk_layout(ffx_state, is_depth);
|
||||
dst->width = w;
|
||||
dst->height = h;
|
||||
dst->aspect = is_depth ? 2u : 1u;
|
||||
} else if (ctx->dx12_interop) {
|
||||
UINT64 vk_img = 0, off = 0;
|
||||
UINT32 vk_fmt = 0;
|
||||
if (wl_vkd3d_resource_info(ctx->dx12_interop, res, &vk_img, &off, &vk_fmt) == S_OK && vk_img) {
|
||||
UINT32 layout = fsr_state_to_vk_layout(ffx_state, is_depth);
|
||||
if (ctx->dx12_interop->lpVtbl->GetVulkanImageLayout) {
|
||||
UINT32 queried = 0;
|
||||
ctx->dx12_interop->lpVtbl->GetVulkanImageLayout(ctx->dx12_interop, res, fsr_state_to_d3d12(ffx_state), &queried);
|
||||
if (queried != 0) layout = queried;
|
||||
}
|
||||
dst->vk_image = vk_img;
|
||||
dst->vk_format = vk_fmt ? vk_fmt : fsr_fmt_to_vk(ffx_fmt);
|
||||
dst->vk_layout = layout;
|
||||
dst->width = w;
|
||||
dst->height = h;
|
||||
dst->aspect = is_depth ? 2u : 1u;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int fsr_submit_frame_ex(WlFsr23Ctx *ctx, void *cmd_list, WlFsr4FrameDesc *f,
|
||||
void *res_col, void *res_dep, void *res_mv, void *res_out) {
|
||||
if (!ctx || !cmd_list || !ctx->seam.ready) return 0;
|
||||
if (!ctx->is_dx12) {
|
||||
return wl_seam_dispatch_or_blit(&ctx->seam, (VkCommandBuffer)cmd_list, f);
|
||||
} else if (ctx->dx12_interop) {
|
||||
int live_en = 1;
|
||||
int live_backend = wl_seam_live_backend(&ctx->seam, &live_en);
|
||||
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU && ctx->d3d12_dev) {
|
||||
if (wl_xess3_eval_d3d12(&ctx->xess3, &ctx->seam, ctx->dx12_interop,
|
||||
ctx->d3d12_dev, cmd_list, f,
|
||||
res_col, res_dep, res_mv, res_out)) {
|
||||
return 1;
|
||||
}
|
||||
wl_xess3_tag_fallback(&ctx->xess3, f);
|
||||
} else {
|
||||
wl_xess3_on_inactive(&ctx->xess3);
|
||||
}
|
||||
void *vk_cb = NULL;
|
||||
int ok = 0;
|
||||
void *cl_used = NULL;
|
||||
if (wl_vkd3d_begin_cb(ctx->dx12_interop, cmd_list, &vk_cb, &cl_used)) {
|
||||
ok = wl_seam_dispatch_or_blit(&ctx->seam, (VkCommandBuffer)vk_cb, f);
|
||||
wl_vkd3d_end_cb(ctx->dx12_interop, cmd_list, cl_used);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static WlFsr23Ctx *unwrap_ctx(void *opaque_ctx) {
|
||||
if (!opaque_ctx) return NULL;
|
||||
WlFsrContextHeader *hdr = (WlFsrContextHeader *)opaque_ctx;
|
||||
if (hdr->magic != WL_FSR23_MAGIC || !hdr->ctx || hdr->ctx->magic != WL_FSR23_MAGIC) return NULL;
|
||||
return hdr->ctx;
|
||||
}
|
||||
|
||||
static void destroy_ctx_common(void *opaque_ctx) {
|
||||
WlFsr23Ctx *ctx = unwrap_ctx(opaque_ctx);
|
||||
if (!ctx) return;
|
||||
wl_xess3_destroy(&ctx->xess3);
|
||||
wl_seam_destroy(&ctx->seam);
|
||||
if (ctx->dx12_interop) {
|
||||
ctx->dx12_interop->lpVtbl->Release(ctx->dx12_interop);
|
||||
ctx->dx12_interop = NULL;
|
||||
}
|
||||
ctx->magic = 0;
|
||||
free(ctx);
|
||||
memset(opaque_ctx, 0, sizeof(WlFsrContextHeader));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// AMD FSR 3 Upscaler Exports (ffx_fsr3upscaler_x64.dll)
|
||||
// ============================================================================
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerContextCreate(void *pContext, const void *pContextDescription) {
|
||||
if (!pContext || !pContextDescription) return FFX_ERROR_INVALID_POINTER;
|
||||
|
||||
const WlFfxFsr30CtxDesc *d30 = (const WlFfxFsr30CtxDesc *)pContextDescription;
|
||||
const WlFfxFsr31CtxDesc *d31 = (const WlFfxFsr31CtxDesc *)pContextDescription;
|
||||
|
||||
// Auto-detect FSR 3.0 vs FSR 3.1 layout:
|
||||
// In FSR 3.0, backendInterface.scratchBufferSize is at offset 160 and device is at 168.
|
||||
// In FSR 3.1, fpMessage precedes backendInterface so scratchBufferSize is at 168 and device is at 176.
|
||||
int is_31 = 0;
|
||||
size_t sz30 = d30->backendInterface.scratchBufferSize;
|
||||
size_t sz31 = d31->backendInterface.scratchBufferSize;
|
||||
int sz30_ok = (sz30 > 0 && sz30 < (64u * 1024u * 1024u) && d30->backendInterface.device != NULL);
|
||||
int sz31_ok = (sz31 > 0 && sz31 < (64u * 1024u * 1024u) && d31->backendInterface.device != NULL);
|
||||
if (sz31_ok && !sz30_ok) {
|
||||
is_31 = 1;
|
||||
} else if (!sz30_ok && d31->backendInterface.device != NULL && d30->backendInterface.callbacks[0] == NULL) {
|
||||
is_31 = 1;
|
||||
}
|
||||
|
||||
WlFsr23Ctx *ctx = (WlFsr23Ctx *)calloc(1, sizeof *ctx);
|
||||
if (!ctx) return FFX_ERROR_OUT_OF_MEMORY;
|
||||
|
||||
ctx->magic = WL_FSR23_MAGIC;
|
||||
ctx->is_fsr3 = 1;
|
||||
ctx->is_fsr31 = is_31;
|
||||
ctx->needs_reset = 1;
|
||||
ctx->flags = d30->flags;
|
||||
ctx->max_rw = d30->maxRenderSize.width;
|
||||
ctx->max_rh = d30->maxRenderSize.height;
|
||||
ctx->disp_w = d30->displaySize.width;
|
||||
ctx->disp_h = d30->displaySize.height;
|
||||
|
||||
void *dev = is_31 ? d31->backendInterface.device : d30->backendInterface.device;
|
||||
void *cb_probe = is_31 ? d31->backendInterface.callbacks[1] : d30->backendInterface.callbacks[1];
|
||||
fsr_init_backend(ctx, dev, cb_probe, 1);
|
||||
|
||||
WlFsrContextHeader *hdr = (WlFsrContextHeader *)pContext;
|
||||
hdr->magic = WL_FSR23_MAGIC;
|
||||
hdr->pad = 0;
|
||||
hdr->ctx = ctx;
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerGetSharedResourceDescriptions(void *pContext, void *pSharedResources) {
|
||||
WlFsr23Ctx *ctx = unwrap_ctx(pContext);
|
||||
if (!ctx || !pSharedResources) return FFX_ERROR_INVALID_POINTER;
|
||||
|
||||
WlFfxFsr3SharedResDescs *sr = (WlFfxFsr3SharedResDescs *)pSharedResources;
|
||||
memset(sr, 0, sizeof *sr);
|
||||
uint32_t w = ctx->max_rw ? ctx->max_rw : 1280;
|
||||
uint32_t h = ctx->max_rh ? ctx->max_rh : 720;
|
||||
|
||||
// reconstructedPrevNearestDepth: R32_UINT, UAV
|
||||
sr->reconstructedPrevNearestDepth.resourceDescription.type = 2; /* TEXTURE2D */
|
||||
sr->reconstructedPrevNearestDepth.resourceDescription.format = 7; /* R32_UINT */
|
||||
sr->reconstructedPrevNearestDepth.resourceDescription.width = w;
|
||||
sr->reconstructedPrevNearestDepth.resourceDescription.height = h;
|
||||
sr->reconstructedPrevNearestDepth.resourceDescription.depth = 1;
|
||||
sr->reconstructedPrevNearestDepth.resourceDescription.mipCount = 1;
|
||||
sr->reconstructedPrevNearestDepth.resourceDescription.usage = 2; /* UAV */
|
||||
sr->reconstructedPrevNearestDepth.initialState = 2; /* UNORDERED_ACCESS */
|
||||
|
||||
// dilatedDepth: R32_FLOAT, UAV
|
||||
sr->dilatedDepth = sr->reconstructedPrevNearestDepth;
|
||||
sr->dilatedDepth.resourceDescription.format = 24; /* R32_FLOAT */
|
||||
|
||||
// dilatedMotionVectors: R16G16_FLOAT, UAV
|
||||
sr->dilatedMotionVectors = sr->reconstructedPrevNearestDepth;
|
||||
sr->dilatedMotionVectors.resourceDescription.format = 14; /* R16G16_FLOAT */
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerContextDispatch(void *pContext, const void *pDispatchDescription) {
|
||||
WlFsr23Ctx *ctx = unwrap_ctx(pContext);
|
||||
if (!ctx || !pDispatchDescription) return FFX_ERROR_INVALID_POINTER;
|
||||
|
||||
const WlFfxFsr30DispatchDesc *d30 = (const WlFfxFsr30DispatchDesc *)pDispatchDescription;
|
||||
const WlFfxFsr31DispatchDesc *d31 = (const WlFfxFsr31DispatchDesc *)pDispatchDescription;
|
||||
|
||||
WlFsr4FrameDesc f;
|
||||
memset(&f, 0, sizeof f);
|
||||
|
||||
uint32_t rw = d30->renderSize.width ? d30->renderSize.width : ctx->max_rw;
|
||||
uint32_t rh = d30->renderSize.height ? d30->renderSize.height : ctx->max_rh;
|
||||
uint32_t ow = ctx->disp_w;
|
||||
uint32_t oh = ctx->disp_h;
|
||||
if (ctx->is_fsr31 && d31->upscaleSize.width >= 64 && d31->upscaleSize.height >= 64) {
|
||||
ow = d31->upscaleSize.width;
|
||||
oh = d31->upscaleSize.height;
|
||||
}
|
||||
if (!ow && d30->output.description.width) ow = d30->output.description.width;
|
||||
if (!oh && d30->output.description.height) oh = d30->output.description.height;
|
||||
|
||||
f.render_w = rw;
|
||||
f.render_h = rh;
|
||||
f.output_w = ow;
|
||||
f.output_h = oh;
|
||||
f.jitter_x = d30->jitterOffset.x;
|
||||
f.jitter_y = d30->jitterOffset.y;
|
||||
f.mv_scale_x = d30->motionVectorScale.x != 0.0f ? d30->motionVectorScale.x : 1.0f;
|
||||
f.mv_scale_y = d30->motionVectorScale.y != 0.0f ? d30->motionVectorScale.y : 1.0f;
|
||||
|
||||
bool en_sharp = ctx->is_fsr31 ? d31->enableSharpening : d30->enableSharpening;
|
||||
float sharp = ctx->is_fsr31 ? d31->sharpness : d30->sharpness;
|
||||
float dt = ctx->is_fsr31 ? d31->frameTimeDelta : d30->frameTimeDelta;
|
||||
float pre_exp = ctx->is_fsr31 ? d31->preExposure : d30->preExposure;
|
||||
bool reset = ctx->is_fsr31 ? d31->reset : d30->reset;
|
||||
float c_near = ctx->is_fsr31 ? d31->cameraNear : d30->cameraNear;
|
||||
float c_far = ctx->is_fsr31 ? d31->cameraFar : d30->cameraFar;
|
||||
float c_fov = ctx->is_fsr31 ? d31->cameraFovAngleVertical : d30->cameraFovAngleVertical;
|
||||
|
||||
f.pre_exposure = pre_exp > 0.0f ? pre_exp : 1.0f;
|
||||
f.sharpness = sharp;
|
||||
f.frame_time_ms = dt;
|
||||
f.camera_near = c_near;
|
||||
f.camera_far = c_far;
|
||||
f.camera_fov_y = c_fov;
|
||||
f.flags = fsr_flags_to_wl(ctx->flags);
|
||||
if (en_sharp) f.flags |= WLFSR4_FLAG_SHARPEN;
|
||||
if (reset || ctx->needs_reset) {
|
||||
f.flags |= WLFSR4_FLAG_RESET;
|
||||
ctx->needs_reset = 0;
|
||||
}
|
||||
|
||||
f.api_source = ctx->is_dx12 ? WLFSR4_API_FSR3_DX12 : WLFSR4_API_FSR3_VK;
|
||||
f.quality_mode = (g_last_quality_mode != WLFSR4_QUALITY_AUTO)
|
||||
? g_last_quality_mode
|
||||
: fsr_infer_quality(rw, ow);
|
||||
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
|
||||
|
||||
int high_res_mv = (ctx->flags & (1u << 1)) ? 1 : 0;
|
||||
fsr_fill_ref(ctx, &f.color, d30->color.resource, d30->color.description.format, d30->color.state,
|
||||
d30->color.description.width ? d30->color.description.width : rw,
|
||||
d30->color.description.height ? d30->color.description.height : rh, 0);
|
||||
fsr_fill_ref(ctx, &f.depth, d30->depth.resource, d30->depth.description.format, d30->depth.state,
|
||||
d30->depth.description.width ? d30->depth.description.width : rw,
|
||||
d30->depth.description.height ? d30->depth.description.height : rh, 1);
|
||||
fsr_fill_ref(ctx, &f.motion, d30->motionVectors.resource, d30->motionVectors.description.format, d30->motionVectors.state,
|
||||
d30->motionVectors.description.width ? d30->motionVectors.description.width : (high_res_mv ? ow : rw),
|
||||
d30->motionVectors.description.height ? d30->motionVectors.description.height : (high_res_mv ? oh : rh), 0);
|
||||
fsr_fill_ref(ctx, &f.output, d30->output.resource, d30->output.description.format, d30->output.state,
|
||||
d30->output.description.width ? d30->output.description.width : ow,
|
||||
d30->output.description.height ? d30->output.description.height : oh, 0);
|
||||
fsr_fill_ref(ctx, &f.reactive, d30->reactive.resource, d30->reactive.description.format, d30->reactive.state,
|
||||
d30->reactive.description.width ? d30->reactive.description.width : rw,
|
||||
d30->reactive.description.height ? d30->reactive.description.height : rh, 0);
|
||||
fsr_fill_ref(ctx, &f.exposure, d30->exposure.resource, d30->exposure.description.format, d30->exposure.state, 1u, 1u, 0);
|
||||
|
||||
int ok = fsr_submit_frame_ex(ctx, d30->commandList, &f,
|
||||
d30->color.resource, d30->depth.resource,
|
||||
d30->motionVectors.resource, d30->output.resource);
|
||||
return ok ? FFX_OK : FFX_ERROR_NULL_DEVICE;
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerContextGenerateReactiveMask(void *pContext, const void *pParams) {
|
||||
(void)pContext; (void)pParams;
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerContextDestroy(void *pContext) {
|
||||
if (!pContext) return FFX_ERROR_INVALID_POINTER;
|
||||
destroy_ctx_common(pContext);
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) float ffxFsr3UpscalerGetUpscaleRatioFromQualityMode(uint32_t qualityMode) {
|
||||
g_last_quality_mode = fsr_mode_to_wl(qualityMode);
|
||||
return fsr_quality_ratio(qualityMode);
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerGetRenderResolutionFromQualityMode(
|
||||
uint32_t *pRenderWidth, uint32_t *pRenderHeight,
|
||||
uint32_t displayWidth, uint32_t displayHeight, uint32_t qualityMode) {
|
||||
if (!pRenderWidth || !pRenderHeight) return FFX_ERROR_INVALID_POINTER;
|
||||
float r = fsr_quality_ratio(qualityMode);
|
||||
if (r <= 0.0f) return FFX_ERROR_INVALID_ENUM;
|
||||
g_last_quality_mode = fsr_mode_to_wl(qualityMode);
|
||||
*pRenderWidth = (uint32_t)((float)displayWidth / r);
|
||||
*pRenderHeight = (uint32_t)((float)displayHeight / r);
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) int32_t ffxFsr3UpscalerGetJitterPhaseCount(int32_t renderWidth, int32_t displayWidth) {
|
||||
if (renderWidth <= 0) return 8;
|
||||
float ratio = (float)displayWidth / (float)renderWidth;
|
||||
int32_t pc = (int32_t)ceilf(8.0f * ratio * ratio);
|
||||
return pc < 8 ? 8 : pc;
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerGetJitterOffset(float *pOutX, float *pOutY,
|
||||
int32_t index, int32_t phaseCount) {
|
||||
if (!pOutX || !pOutY) return FFX_ERROR_INVALID_POINTER;
|
||||
if (phaseCount <= 0) return FFX_ERROR_INVALID_ARGUMENT;
|
||||
int32_t idx = (index % phaseCount) + 1;
|
||||
if (idx <= 0) idx += phaseCount;
|
||||
*pOutX = fsr_halton(idx, 2) - 0.5f;
|
||||
*pOutY = fsr_halton(idx, 3) - 0.5f;
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) bool ffxFsr3UpscalerResourceIsNull(WlFfxResource3 resource) {
|
||||
return resource.resource == NULL;
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr3UpscalerSetConstant(void *pContext, uint32_t key, void *valuePtr) {
|
||||
(void)pContext; (void)key; (void)valuePtr;
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) uint32_t ffxFsr3UpscalerGetEffectVersion(void) {
|
||||
return (3u << 22) | (1u << 12) | 0u;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// AMD FSR 2 Core Exports (ffx_fsr2_api_x64.dll)
|
||||
// ============================================================================
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr2ContextCreate(void *pContext, const void *pContextDescription) {
|
||||
if (!pContext || !pContextDescription) return FFX_ERROR_INVALID_POINTER;
|
||||
|
||||
const WlFfxFsr2CtxDesc *d = (const WlFfxFsr2CtxDesc *)pContextDescription;
|
||||
WlFsr23Ctx *ctx = (WlFsr23Ctx *)calloc(1, sizeof *ctx);
|
||||
if (!ctx) return FFX_ERROR_OUT_OF_MEMORY;
|
||||
|
||||
ctx->magic = WL_FSR23_MAGIC;
|
||||
ctx->is_fsr3 = 0;
|
||||
ctx->is_fsr31 = 0;
|
||||
ctx->needs_reset = 1;
|
||||
ctx->flags = d->flags;
|
||||
ctx->max_rw = d->maxRenderSize.width;
|
||||
ctx->max_rh = d->maxRenderSize.height;
|
||||
ctx->disp_w = d->displaySize.width;
|
||||
ctx->disp_h = d->displaySize.height;
|
||||
|
||||
fsr_init_backend(ctx, d->device, d->callbacks.callbacks[0], 0);
|
||||
|
||||
WlFsrContextHeader *hdr = (WlFsrContextHeader *)pContext;
|
||||
hdr->magic = WL_FSR23_MAGIC;
|
||||
hdr->pad = 0;
|
||||
hdr->ctx = ctx;
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr2ContextDispatch(void *pContext, const void *pDispatchDescription) {
|
||||
WlFsr23Ctx *ctx = unwrap_ctx(pContext);
|
||||
if (!ctx || !pDispatchDescription) return FFX_ERROR_INVALID_POINTER;
|
||||
|
||||
const WlFfxFsr21DispatchDesc *d21 = (const WlFfxFsr21DispatchDesc *)pDispatchDescription;
|
||||
const WlFfxFsr20DispatchDesc *d20 = (const WlFfxFsr20DispatchDesc *)pDispatchDescription;
|
||||
|
||||
// Auto-detect FSR 2.1/2.2 (184-byte FfxResource with wchar_t name[64]) vs FSR 2.0 (56-byte FfxResource)
|
||||
int use_21 = (d21->renderSize.width >= 64 && d21->renderSize.width <= 16384 &&
|
||||
d21->renderSize.height >= 64 && d21->renderSize.height <= 16384 &&
|
||||
d21->output.resource != NULL);
|
||||
|
||||
WlFsr4FrameDesc f;
|
||||
memset(&f, 0, sizeof f);
|
||||
|
||||
uint32_t rw = use_21 ? d21->renderSize.width : d20->renderSize.width;
|
||||
uint32_t rh = use_21 ? d21->renderSize.height : d20->renderSize.height;
|
||||
if (!rw) rw = ctx->max_rw;
|
||||
if (!rh) rh = ctx->max_rh;
|
||||
uint32_t ow = ctx->disp_w;
|
||||
uint32_t oh = ctx->disp_h;
|
||||
int high_res_mv = (ctx->flags & (1u << 1)) ? 1 : 0;
|
||||
|
||||
f.render_w = rw;
|
||||
f.render_h = rh;
|
||||
f.output_w = ow;
|
||||
f.output_h = oh;
|
||||
f.jitter_x = use_21 ? d21->jitterOffset.x : d20->jitterOffset.x;
|
||||
f.jitter_y = use_21 ? d21->jitterOffset.y : d20->jitterOffset.y;
|
||||
float mvx = use_21 ? d21->motionVectorScale.x : d20->motionVectorScale.x;
|
||||
float mvy = use_21 ? d21->motionVectorScale.y : d20->motionVectorScale.y;
|
||||
f.mv_scale_x = mvx != 0.0f ? mvx : 1.0f;
|
||||
f.mv_scale_y = mvy != 0.0f ? mvy : 1.0f;
|
||||
float pre_exp = use_21 ? d21->preExposure : d20->preExposure;
|
||||
f.pre_exposure = pre_exp > 0.0f ? pre_exp : 1.0f;
|
||||
f.sharpness = use_21 ? d21->sharpness : d20->sharpness;
|
||||
f.frame_time_ms = use_21 ? d21->frameTimeDelta : d20->frameTimeDelta;
|
||||
f.camera_near = use_21 ? d21->cameraNear : d20->cameraNear;
|
||||
f.camera_far = use_21 ? d21->cameraFar : d20->cameraFar;
|
||||
f.camera_fov_y = use_21 ? d21->cameraFovAngleVertical : d20->cameraFovAngleVertical;
|
||||
f.flags = fsr_flags_to_wl(ctx->flags);
|
||||
if (use_21 ? d21->enableSharpening : d20->enableSharpening) f.flags |= WLFSR4_FLAG_SHARPEN;
|
||||
if ((use_21 ? d21->reset : d20->reset) || ctx->needs_reset) {
|
||||
f.flags |= WLFSR4_FLAG_RESET;
|
||||
ctx->needs_reset = 0;
|
||||
}
|
||||
|
||||
f.api_source = ctx->is_dx12 ? WLFSR4_API_FSR2_DX12 : WLFSR4_API_FSR2_VK;
|
||||
f.quality_mode = (g_last_quality_mode != WLFSR4_QUALITY_AUTO)
|
||||
? g_last_quality_mode
|
||||
: fsr_infer_quality(rw, ow);
|
||||
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
|
||||
|
||||
if (use_21) {
|
||||
fsr_fill_ref(ctx, &f.color, d21->color.resource, d21->color.description.format, d21->color.state,
|
||||
d21->color.description.width ? d21->color.description.width : rw,
|
||||
d21->color.description.height ? d21->color.description.height : rh, 0);
|
||||
fsr_fill_ref(ctx, &f.depth, d21->depth.resource, d21->depth.description.format, d21->depth.state,
|
||||
d21->depth.description.width ? d21->depth.description.width : rw,
|
||||
d21->depth.description.height ? d21->depth.description.height : rh, 1);
|
||||
fsr_fill_ref(ctx, &f.motion, d21->motionVectors.resource, d21->motionVectors.description.format, d21->motionVectors.state,
|
||||
d21->motionVectors.description.width ? d21->motionVectors.description.width : (high_res_mv ? ow : rw),
|
||||
d21->motionVectors.description.height ? d21->motionVectors.description.height : (high_res_mv ? oh : rh), 0);
|
||||
fsr_fill_ref(ctx, &f.output, d21->output.resource, d21->output.description.format, d21->output.state,
|
||||
d21->output.description.width ? d21->output.description.width : ow,
|
||||
d21->output.description.height ? d21->output.description.height : oh, 0);
|
||||
fsr_fill_ref(ctx, &f.reactive, d21->reactive.resource, d21->reactive.description.format, d21->reactive.state, rw, rh, 0);
|
||||
fsr_fill_ref(ctx, &f.exposure, d21->exposure.resource, d21->exposure.description.format, d21->exposure.state, 1u, 1u, 0);
|
||||
} else {
|
||||
fsr_fill_ref(ctx, &f.color, d20->color.resource, d20->color.description.format, d20->color.state,
|
||||
d20->color.description.width ? d20->color.description.width : rw,
|
||||
d20->color.description.height ? d20->color.description.height : rh, 0);
|
||||
fsr_fill_ref(ctx, &f.depth, d20->depth.resource, d20->depth.description.format, d20->depth.state,
|
||||
d20->depth.description.width ? d20->depth.description.width : rw,
|
||||
d20->depth.description.height ? d20->depth.description.height : rh, 1);
|
||||
fsr_fill_ref(ctx, &f.motion, d20->motionVectors.resource, d20->motionVectors.description.format, d20->motionVectors.state,
|
||||
d20->motionVectors.description.width ? d20->motionVectors.description.width : (high_res_mv ? ow : rw),
|
||||
d20->motionVectors.description.height ? d20->motionVectors.description.height : (high_res_mv ? oh : rh), 0);
|
||||
fsr_fill_ref(ctx, &f.output, d20->output.resource, d20->output.description.format, d20->output.state,
|
||||
d20->output.description.width ? d20->output.description.width : ow,
|
||||
d20->output.description.height ? d20->output.description.height : oh, 0);
|
||||
fsr_fill_ref(ctx, &f.reactive, d20->reactive.resource, d20->reactive.description.format, d20->reactive.state, rw, rh, 0);
|
||||
fsr_fill_ref(ctx, &f.exposure, d20->exposure.resource, d20->exposure.description.format, d20->exposure.state, 1u, 1u, 0);
|
||||
}
|
||||
|
||||
int ok = fsr_submit_frame_ex(ctx, d21->commandList, &f,
|
||||
use_21 ? d21->color.resource : d20->color.resource,
|
||||
use_21 ? d21->depth.resource : d20->depth.resource,
|
||||
use_21 ? d21->motionVectors.resource : d20->motionVectors.resource,
|
||||
use_21 ? d21->output.resource : d20->output.resource);
|
||||
return ok ? FFX_OK : FFX_ERROR_NULL_DEVICE;
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr2ContextGenerateReactiveMask(void *pContext, const void *pParams) {
|
||||
(void)pContext; (void)pParams;
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr2ContextDestroy(void *pContext) {
|
||||
if (!pContext) return FFX_ERROR_INVALID_POINTER;
|
||||
destroy_ctx_common(pContext);
|
||||
return FFX_OK;
|
||||
}
|
||||
|
||||
__declspec(dllexport) float ffxFsr2GetUpscaleRatioFromQualityMode(uint32_t qualityMode) {
|
||||
g_last_quality_mode = fsr_mode_to_wl(qualityMode);
|
||||
return fsr_quality_ratio(qualityMode);
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr2GetRenderResolutionFromQualityMode(
|
||||
uint32_t *renderWidth, uint32_t *renderHeight,
|
||||
uint32_t displayWidth, uint32_t displayHeight, uint32_t qualityMode) {
|
||||
return ffxFsr3UpscalerGetRenderResolutionFromQualityMode(
|
||||
renderWidth, renderHeight, displayWidth, displayHeight, qualityMode);
|
||||
}
|
||||
|
||||
__declspec(dllexport) int32_t ffxFsr2GetJitterPhaseCount(int32_t renderWidth, int32_t displayWidth) {
|
||||
return ffxFsr3UpscalerGetJitterPhaseCount(renderWidth, displayWidth);
|
||||
}
|
||||
|
||||
__declspec(dllexport) FfxErrorCode ffxFsr2GetJitterOffset(float *outX, float *outY,
|
||||
int32_t index, int32_t phaseCount) {
|
||||
return ffxFsr3UpscalerGetJitterOffset(outX, outY, index, phaseCount);
|
||||
}
|
||||
|
||||
__declspec(dllexport) bool ffxFsr2ResourceIsNull(WlFfxResource21 resource) {
|
||||
return resource.resource == NULL;
|
||||
}
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
|
||||
(void)hinst; (void)reason; (void)reserved;
|
||||
return TRUE;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,585 @@
|
||||
// DroidDeck: modified from michaelisomer-cyber/Winlator-NeuralScale 71c140d9 (see README.md).
|
||||
// ARM64EC / FEXCore / Box64 / Wine-safe IAT + GetProcAddress NGX hook engine.
|
||||
// Installed inside nvapi64.dll so that when nvsdk_ngx.lib (inside Cyberpunk 2077's
|
||||
// sl.common.dll, RDR2.exe, etc.) tries to locate, signature-verify, and load
|
||||
// nvngx.dll / _nvngx.dll, it cleanly passes WinVerifyTrust + CryptQueryObject
|
||||
// and loads our C:\windows\system32\_nvngx.dll bridge without touching game folders
|
||||
// or patching executable machine code (100% safe on ARM64EC thunks).
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
#include <wchar.h>
|
||||
#include <stdio.h>
|
||||
#include "dd_env.h"
|
||||
|
||||
#ifndef FILE_ATTRIBUTE_ARCHIVE
|
||||
#define FILE_ATTRIBUTE_ARCHIVE 0x20
|
||||
#endif
|
||||
|
||||
// Minimal WinTrust & Crypt32 definitions (avoid linking wintrust.lib / crypt32.lib)
|
||||
typedef struct WlWintrustFileInfo {
|
||||
DWORD cbStruct;
|
||||
LPCWSTR pcwszFilePath;
|
||||
HANDLE hFile;
|
||||
GUID *pgKnownSubject;
|
||||
} WlWintrustFileInfo;
|
||||
|
||||
typedef struct WlWintrustData {
|
||||
DWORD cbStruct;
|
||||
LPVOID pPolicyCallbackData;
|
||||
LPVOID pSIPClientData;
|
||||
DWORD dwUIChoice;
|
||||
DWORD fdwRevocationChecks;
|
||||
DWORD dwUnionChoice; /* 1 = WTD_CHOICE_FILE */
|
||||
union {
|
||||
WlWintrustFileInfo *pFile;
|
||||
void *pOther;
|
||||
} u;
|
||||
DWORD dwStateAction; /* 1 = VERIFY, 2 = CLOSE */
|
||||
HANDLE hWVTStateData;
|
||||
WCHAR *pwszURLReference;
|
||||
DWORD dwProvFlags;
|
||||
DWORD dwUIContext;
|
||||
void *pSignatureSettings;
|
||||
} WlWintrustData;
|
||||
|
||||
typedef HMODULE (WINAPI *PFN_LoadLibraryW)(LPCWSTR);
|
||||
typedef HMODULE (WINAPI *PFN_LoadLibraryA)(LPCSTR);
|
||||
typedef HMODULE (WINAPI *PFN_LoadLibraryExW)(LPCWSTR, HANDLE, DWORD);
|
||||
typedef HMODULE (WINAPI *PFN_LoadLibraryExA)(LPCSTR, HANDLE, DWORD);
|
||||
typedef FARPROC (WINAPI *PFN_GetProcAddress)(HMODULE, LPCSTR);
|
||||
typedef DWORD (WINAPI *PFN_GetFileAttributesW)(LPCWSTR);
|
||||
typedef BOOL (WINAPI *PFN_GetFileAttributesExW)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
|
||||
typedef HANDLE (WINAPI *PFN_CreateFileW)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
|
||||
typedef LONG (WINAPI *PFN_WinVerifyTrust)(HWND, GUID *, LPVOID);
|
||||
typedef BOOL (WINAPI *PFN_CryptQueryObject)(DWORD, const void *, DWORD, DWORD, DWORD, DWORD *, DWORD *, DWORD *, void *, void *, const void **);
|
||||
typedef LSTATUS (WINAPI *PFN_RegOpenKeyExW)(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY);
|
||||
typedef LSTATUS (WINAPI *PFN_RegEnumValueW)(HKEY, DWORD, LPWSTR, LPDWORD, LPDWORD, LPDWORD, LPBYTE, LPDWORD);
|
||||
typedef LSTATUS (WINAPI *PFN_RegQueryValueExW)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD);
|
||||
typedef LSTATUS (WINAPI *PFN_RegCloseKey)(HKEY);
|
||||
|
||||
static HMODULE g_wl_self_mod = NULL;
|
||||
static HMODULE g_wl_our_nvngx = NULL;
|
||||
static DWORD g_wl_tls_reent = TLS_OUT_OF_INDEXES;
|
||||
static volatile LONG g_wl_hooks_installed = 0;
|
||||
static CRITICAL_SECTION g_wl_hook_cs;
|
||||
static int g_wl_hook_cs_ready = 0;
|
||||
static WCHAR g_wl_signed_nv_dll[MAX_PATH] = {0};
|
||||
|
||||
static const HKEY k_wl_sig_hkey = (HKEY)(uintptr_t)0xFFFFFFFF13372137ULL;
|
||||
|
||||
static PFN_LoadLibraryW o_LoadLibraryW = NULL;
|
||||
static PFN_LoadLibraryA o_LoadLibraryA = NULL;
|
||||
static PFN_LoadLibraryExW o_LoadLibraryExW = NULL;
|
||||
static PFN_LoadLibraryExA o_LoadLibraryExA = NULL;
|
||||
static PFN_GetProcAddress o_GetProcAddress = NULL;
|
||||
static PFN_GetFileAttributesW o_GetFileAttributesW = NULL;
|
||||
static PFN_GetFileAttributesExW o_GetFileAttributesExW = NULL;
|
||||
static PFN_CreateFileW o_CreateFileW = NULL;
|
||||
static PFN_WinVerifyTrust o_WinVerifyTrust = NULL;
|
||||
static PFN_CryptQueryObject o_CryptQueryObject = NULL;
|
||||
static PFN_RegOpenKeyExW o_RegOpenKeyExW = NULL;
|
||||
static PFN_RegEnumValueW o_RegEnumValueW = NULL;
|
||||
static PFN_RegQueryValueExW o_RegQueryValueExW = NULL;
|
||||
static PFN_RegCloseKey o_RegCloseKey = NULL;
|
||||
|
||||
static int g_wl_log_on = -1;
|
||||
|
||||
static void wl_hook_log(const char *msg) {
|
||||
if (g_wl_log_on < 0) g_wl_log_on = dd_env_is_on("DROIDDECK_UPSCALE_LOG");
|
||||
if (!msg || !g_wl_log_on) return;
|
||||
HANDLE hf = CreateFileA("C:\\windows\\temp\\wl_fsr4_bridge.log",
|
||||
FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
if (hf != INVALID_HANDLE_VALUE) {
|
||||
DWORD wr = 0;
|
||||
WriteFile(hf, msg, (DWORD)strlen(msg), &wr, NULL);
|
||||
WriteFile(hf, "\r\n", 2, &wr, NULL);
|
||||
CloseHandle(hf);
|
||||
}
|
||||
}
|
||||
|
||||
static int wl_in_hook(void) {
|
||||
return (g_wl_tls_reent != TLS_OUT_OF_INDEXES) && (TlsGetValue(g_wl_tls_reent) != NULL);
|
||||
}
|
||||
static void wl_enter_hook(void) {
|
||||
if (g_wl_tls_reent != TLS_OUT_OF_INDEXES) TlsSetValue(g_wl_tls_reent, (LPVOID)1);
|
||||
}
|
||||
static void wl_leave_hook(void) {
|
||||
if (g_wl_tls_reent != TLS_OUT_OF_INDEXES) TlsSetValue(g_wl_tls_reent, NULL);
|
||||
}
|
||||
|
||||
static const WCHAR *wl_basename_w(const WCHAR *path) {
|
||||
if (!path) return L"";
|
||||
const WCHAR *last = path;
|
||||
for (const WCHAR *p = path; *p; p++) {
|
||||
if (*p == L'\\' || *p == L'/') last = p + 1;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
static const char *wl_basename_a(const char *path) {
|
||||
if (!path) return "";
|
||||
const char *last = path;
|
||||
for (const char *p = path; *p; p++) {
|
||||
if (*p == '\\' || *p == '/') last = p + 1;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
// Matches nvngx.dll or _nvngx.dll (and NOT nvngx_dlss.dll / nvngx_dlssg.dll / nvngx_dlssd.dll)
|
||||
static int wl_is_nvngx_core_w(const WCHAR *path) {
|
||||
const WCHAR *base = wl_basename_w(path);
|
||||
return _wcsicmp(base, L"nvngx.dll") == 0 ||
|
||||
_wcsicmp(base, L"_nvngx.dll") == 0 ||
|
||||
_wcsicmp(base, L"nvngx") == 0 ||
|
||||
_wcsicmp(base, L"_nvngx") == 0;
|
||||
}
|
||||
|
||||
static int wl_is_nvngx_core_a(const char *path) {
|
||||
const char *base = wl_basename_a(path);
|
||||
return _stricmp(base, "nvngx.dll") == 0 ||
|
||||
_stricmp(base, "_nvngx.dll") == 0 ||
|
||||
_stricmp(base, "nvngx") == 0 ||
|
||||
_stricmp(base, "_nvngx") == 0;
|
||||
}
|
||||
|
||||
static int wl_is_sig_target_w(const WCHAR *path) {
|
||||
if (!path) return 0;
|
||||
const WCHAR *base = wl_basename_w(path);
|
||||
if (wl_is_nvngx_core_w(base)) return 1;
|
||||
if (_wcsnicmp(base, L"amd_fidelityfx", 14) == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static HMODULE wl_load_our_nvngx(void) {
|
||||
if (g_wl_our_nvngx) return g_wl_our_nvngx;
|
||||
if (!o_LoadLibraryW) return NULL;
|
||||
wl_enter_hook();
|
||||
HMODULE h = o_LoadLibraryW(L"C:\\windows\\system32\\_nvngx.dll");
|
||||
if (!h) h = o_LoadLibraryW(L"C:\\windows\\system32\\nvngx.dll");
|
||||
wl_leave_hook();
|
||||
if (h) g_wl_our_nvngx = h;
|
||||
return h;
|
||||
}
|
||||
|
||||
static void wl_find_signed_nv_dll(void) {
|
||||
if (g_wl_signed_nv_dll[0]) return;
|
||||
WCHAR exe_dir[MAX_PATH] = {0};
|
||||
DWORD n = GetModuleFileNameW(NULL, exe_dir, MAX_PATH);
|
||||
if (n == 0 || n >= MAX_PATH) return;
|
||||
for (int i = (int)n - 1; i >= 0; i--) {
|
||||
if (exe_dir[i] == L'\\' || exe_dir[i] == L'/') {
|
||||
exe_dir[i + 1] = L'\0';
|
||||
break;
|
||||
}
|
||||
}
|
||||
static const WCHAR *const k_candidates[] = {
|
||||
L"nvngx_dlss.dll",
|
||||
L"sl.interposer.dll",
|
||||
L"sl.common.dll",
|
||||
L"sl.dlss.dll",
|
||||
L"nvngx_dlssg.dll",
|
||||
};
|
||||
PFN_GetFileAttributesW fnAttr = o_GetFileAttributesW ? o_GetFileAttributesW : GetFileAttributesW;
|
||||
for (size_t i = 0; i < sizeof(k_candidates) / sizeof(k_candidates[0]); i++) {
|
||||
WCHAR cand[MAX_PATH] = {0};
|
||||
_snwprintf(cand, MAX_PATH - 1, L"%ls%ls", exe_dir, k_candidates[i]);
|
||||
DWORD attr = fnAttr(cand);
|
||||
if (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY)) {
|
||||
wcsncpy(g_wl_signed_nv_dll, cand, MAX_PATH - 1);
|
||||
char logbuf[320];
|
||||
snprintf(logbuf, sizeof logbuf, "[nvapi] Found genuine NVIDIA-signed cert donor: %ls", k_candidates[i]);
|
||||
wl_hook_log(logbuf);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void wl_patch_module_iat(HMODULE mod);
|
||||
|
||||
// ---- Hook implementations ----
|
||||
static HMODULE WINAPI hk_LoadLibraryW(LPCWSTR lpName) {
|
||||
if (!wl_in_hook() && lpName && wl_is_nvngx_core_w(lpName)) {
|
||||
wl_hook_log("[nvapi] hk_LoadLibraryW intercepted nvngx -> _nvngx.dll");
|
||||
return wl_load_our_nvngx();
|
||||
}
|
||||
HMODULE h = o_LoadLibraryW ? o_LoadLibraryW(lpName) : NULL;
|
||||
if (h && !wl_in_hook()) {
|
||||
wl_enter_hook();
|
||||
wl_patch_module_iat(h);
|
||||
wl_leave_hook();
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
static HMODULE WINAPI hk_LoadLibraryA(LPCSTR lpName) {
|
||||
if (!wl_in_hook() && lpName && wl_is_nvngx_core_a(lpName)) {
|
||||
wl_hook_log("[nvapi] hk_LoadLibraryA intercepted nvngx -> _nvngx.dll");
|
||||
return wl_load_our_nvngx();
|
||||
}
|
||||
HMODULE h = o_LoadLibraryA ? o_LoadLibraryA(lpName) : NULL;
|
||||
if (h && !wl_in_hook()) {
|
||||
wl_enter_hook();
|
||||
wl_patch_module_iat(h);
|
||||
wl_leave_hook();
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
static HMODULE WINAPI hk_LoadLibraryExW(LPCWSTR lpName, HANDLE hFile, DWORD dwFlags) {
|
||||
if (!wl_in_hook() && lpName && wl_is_nvngx_core_w(lpName) &&
|
||||
!(dwFlags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))) {
|
||||
wl_hook_log("[nvapi] hk_LoadLibraryExW intercepted nvngx -> _nvngx.dll");
|
||||
return wl_load_our_nvngx();
|
||||
}
|
||||
HMODULE h = o_LoadLibraryExW ? o_LoadLibraryExW(lpName, hFile, dwFlags) : NULL;
|
||||
if (h && !wl_in_hook() &&
|
||||
!(dwFlags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))) {
|
||||
wl_enter_hook();
|
||||
wl_patch_module_iat(h);
|
||||
wl_leave_hook();
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
static HMODULE WINAPI hk_LoadLibraryExA(LPCSTR lpName, HANDLE hFile, DWORD dwFlags) {
|
||||
if (!wl_in_hook() && lpName && wl_is_nvngx_core_a(lpName) &&
|
||||
!(dwFlags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))) {
|
||||
wl_hook_log("[nvapi] hk_LoadLibraryExA intercepted nvngx -> _nvngx.dll");
|
||||
return wl_load_our_nvngx();
|
||||
}
|
||||
HMODULE h = o_LoadLibraryExA ? o_LoadLibraryExA(lpName, hFile, dwFlags) : NULL;
|
||||
if (h && !wl_in_hook() &&
|
||||
!(dwFlags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))) {
|
||||
wl_enter_hook();
|
||||
wl_patch_module_iat(h);
|
||||
wl_leave_hook();
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
static DWORD WINAPI hk_GetFileAttributesW(LPCWSTR lpFileName) {
|
||||
if (!wl_in_hook() && lpFileName && wl_is_nvngx_core_w(lpFileName)) {
|
||||
return FILE_ATTRIBUTE_ARCHIVE;
|
||||
}
|
||||
return o_GetFileAttributesW ? o_GetFileAttributesW(lpFileName) : INVALID_FILE_ATTRIBUTES;
|
||||
}
|
||||
|
||||
static BOOL WINAPI hk_GetFileAttributesExW(LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, LPVOID lpFileInfo) {
|
||||
if (!wl_in_hook() && lpFileName && wl_is_nvngx_core_w(lpFileName)) {
|
||||
const WCHAR *target = g_wl_signed_nv_dll[0] ? g_wl_signed_nv_dll : L"C:\\windows\\system32\\_nvngx.dll";
|
||||
if (o_GetFileAttributesExW) return o_GetFileAttributesExW(target, fInfoLevelId, lpFileInfo);
|
||||
}
|
||||
return o_GetFileAttributesExW ? o_GetFileAttributesExW(lpFileName, fInfoLevelId, lpFileInfo) : FALSE;
|
||||
}
|
||||
|
||||
static HANDLE WINAPI hk_CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
|
||||
LPSECURITY_ATTRIBUTES lpSec, DWORD dwCreation, DWORD dwFlags, HANDLE hTmpl) {
|
||||
if (!wl_in_hook() && lpFileName && wl_is_nvngx_core_w(lpFileName) &&
|
||||
!(dwDesiredAccess & GENERIC_WRITE)) {
|
||||
const WCHAR *target = g_wl_signed_nv_dll[0] ? g_wl_signed_nv_dll : L"C:\\windows\\system32\\_nvngx.dll";
|
||||
return o_CreateFileW(target, dwDesiredAccess, dwShareMode, lpSec, dwCreation, dwFlags, hTmpl);
|
||||
}
|
||||
return o_CreateFileW ? o_CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSec, dwCreation, dwFlags, hTmpl)
|
||||
: INVALID_HANDLE_VALUE;
|
||||
}
|
||||
|
||||
static LONG WINAPI hk_WinVerifyTrust(HWND hwnd, GUID *pgActionID, LPVOID pWVTData) {
|
||||
if (!wl_in_hook() && pWVTData) {
|
||||
WlWintrustData *data = (WlWintrustData *)pWVTData;
|
||||
if (data->dwUnionChoice == 1u && data->u.pFile && data->u.pFile->pcwszFilePath &&
|
||||
wl_is_sig_target_w(data->u.pFile->pcwszFilePath)) {
|
||||
wl_hook_log("[nvapi] hk_WinVerifyTrust -> ERROR_SUCCESS for nvngx");
|
||||
if (data->dwStateAction == 1u && g_wl_signed_nv_dll[0] && o_WinVerifyTrust) {
|
||||
WlWintrustData copy = *data;
|
||||
WlWintrustFileInfo fcopy = *data->u.pFile;
|
||||
fcopy.pcwszFilePath = g_wl_signed_nv_dll;
|
||||
copy.u.pFile = &fcopy;
|
||||
wl_enter_hook();
|
||||
LONG r = o_WinVerifyTrust(hwnd, pgActionID, ©);
|
||||
wl_leave_hook();
|
||||
data->hWVTStateData = copy.hWVTStateData;
|
||||
if (r == ERROR_SUCCESS) return ERROR_SUCCESS;
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
}
|
||||
if (!o_WinVerifyTrust) {
|
||||
HMODULE hw = o_LoadLibraryW ? o_LoadLibraryW(L"wintrust.dll") : NULL;
|
||||
if (hw && o_GetProcAddress) o_WinVerifyTrust = (PFN_WinVerifyTrust)(void *)o_GetProcAddress(hw, "WinVerifyTrust");
|
||||
}
|
||||
return o_WinVerifyTrust ? o_WinVerifyTrust(hwnd, pgActionID, pWVTData) : ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
static BOOL WINAPI hk_CryptQueryObject(DWORD dwObjectType, const void *pvObject, DWORD dwExpectedContent,
|
||||
DWORD dwExpectedFormat, DWORD dwFlags, DWORD *pdwEncoding,
|
||||
DWORD *pdwContent, DWORD *pdwFormat, void *phCertStore,
|
||||
void *phMsg, const void **ppvContext) {
|
||||
if (!o_CryptQueryObject) {
|
||||
HMODULE hc = o_LoadLibraryW ? o_LoadLibraryW(L"crypt32.dll") : NULL;
|
||||
if (hc && o_GetProcAddress) o_CryptQueryObject = (PFN_CryptQueryObject)(void *)o_GetProcAddress(hc, "CryptQueryObject");
|
||||
}
|
||||
if (!o_CryptQueryObject) return FALSE;
|
||||
if (!wl_in_hook() && dwObjectType == 1u /* CERT_QUERY_OBJECT_FILE */ && pvObject) {
|
||||
const WCHAR *wpath = (const WCHAR *)pvObject;
|
||||
if (wl_is_sig_target_w(wpath) && g_wl_signed_nv_dll[0]) {
|
||||
wl_hook_log("[nvapi] hk_CryptQueryObject redirected nvngx -> signed NVIDIA donor");
|
||||
return o_CryptQueryObject(dwObjectType, g_wl_signed_nv_dll, dwExpectedContent, dwExpectedFormat,
|
||||
dwFlags, pdwEncoding, pdwContent, pdwFormat, phCertStore, phMsg, ppvContext);
|
||||
}
|
||||
}
|
||||
return o_CryptQueryObject(dwObjectType, pvObject, dwExpectedContent, dwExpectedFormat,
|
||||
dwFlags, pdwEncoding, pdwContent, pdwFormat, phCertStore, phMsg, ppvContext);
|
||||
}
|
||||
|
||||
static LSTATUS WINAPI hk_RegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult) {
|
||||
if (!wl_in_hook() && hKey == k_wl_sig_hkey && lpSubKey && phkResult) {
|
||||
// Child subkey opened relative to our synthetic signature-override key (e.g. NGXCore):
|
||||
// resolve against real HKLM\SOFTWARE\NVIDIA Corporation\Global\<subkey>
|
||||
WCHAR full[256];
|
||||
_snwprintf(full, 255, L"SOFTWARE\\NVIDIA Corporation\\Global\\%ls", lpSubKey);
|
||||
full[255] = L'\0';
|
||||
return o_RegOpenKeyExW ? o_RegOpenKeyExW(HKEY_LOCAL_MACHINE, full, ulOptions, samDesired, phkResult)
|
||||
: ERROR_FILE_NOT_FOUND;
|
||||
}
|
||||
if (!wl_in_hook() && lpSubKey && phkResult &&
|
||||
(_wcsicmp(lpSubKey, L"SOFTWARE\\NVIDIA Corporation\\Global") == 0 ||
|
||||
_wcsicmp(lpSubKey, L"SYSTEM\\ControlSet001\\Services\\nvlddmkm") == 0 ||
|
||||
_wcsicmp(lpSubKey, L"SYSTEM\\CurrentControlSet\\Services\\nvlddmkm") == 0)) {
|
||||
*phkResult = k_wl_sig_hkey;
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
return o_RegOpenKeyExW ? o_RegOpenKeyExW(hKey, lpSubKey, ulOptions, samDesired, phkResult) : ERROR_FILE_NOT_FOUND;
|
||||
}
|
||||
|
||||
static LSTATUS WINAPI hk_RegEnumValueW(HKEY hKey, DWORD dwIndex, LPWSTR lpValueName, LPDWORD lpcchValueName,
|
||||
LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) {
|
||||
if (hKey == k_wl_sig_hkey) {
|
||||
if (dwIndex != 0) return ERROR_NO_MORE_ITEMS;
|
||||
static const WCHAR k_guid[] = L"{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}";
|
||||
DWORD len = (DWORD)wcslen(k_guid);
|
||||
if (!lpValueName || !lpcchValueName || !lpData || !lpcbData) return ERROR_INVALID_PARAMETER;
|
||||
if (*lpcchValueName <= len) { *lpcchValueName = len + 1; return ERROR_MORE_DATA; }
|
||||
memcpy(lpValueName, k_guid, (len + 1) * sizeof(WCHAR));
|
||||
*lpcchValueName = len;
|
||||
if (lpType) *lpType = REG_BINARY;
|
||||
if (*lpcbData < 1) { *lpcbData = 1; return ERROR_MORE_DATA; }
|
||||
lpData[0] = 0x01;
|
||||
*lpcbData = 1;
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
return o_RegEnumValueW ? o_RegEnumValueW(hKey, dwIndex, lpValueName, lpcchValueName, lpReserved, lpType, lpData, lpcbData)
|
||||
: ERROR_NO_MORE_ITEMS;
|
||||
}
|
||||
|
||||
static LSTATUS WINAPI hk_RegQueryValueExW(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved,
|
||||
LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) {
|
||||
if (hKey == k_wl_sig_hkey) {
|
||||
if (lpValueName && _wcsicmp(lpValueName, L"{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}") == 0) {
|
||||
if (lpType) *lpType = REG_BINARY;
|
||||
if (!lpcbData) return ERROR_SUCCESS;
|
||||
if (!lpData) { *lpcbData = 1; return ERROR_SUCCESS; }
|
||||
if (*lpcbData < 1) { *lpcbData = 1; return ERROR_MORE_DATA; }
|
||||
lpData[0] = 0x01;
|
||||
*lpcbData = 1;
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
return ERROR_FILE_NOT_FOUND;
|
||||
}
|
||||
return o_RegQueryValueExW ? o_RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData)
|
||||
: ERROR_FILE_NOT_FOUND;
|
||||
}
|
||||
|
||||
static LSTATUS WINAPI hk_RegCloseKey(HKEY hKey) {
|
||||
if (hKey == k_wl_sig_hkey) return ERROR_SUCCESS;
|
||||
return o_RegCloseKey ? o_RegCloseKey(hKey) : ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
static FARPROC WINAPI hk_GetProcAddress(HMODULE hMod, LPCSTR lpProcName) {
|
||||
FARPROC orig = o_GetProcAddress ? o_GetProcAddress(hMod, lpProcName) : NULL;
|
||||
if (!orig || wl_in_hook() || !lpProcName || ((uintptr_t)lpProcName < 0x10000u)) return orig;
|
||||
|
||||
if (strcmp(lpProcName, "WinVerifyTrust") == 0) {
|
||||
if (!o_WinVerifyTrust) o_WinVerifyTrust = (PFN_WinVerifyTrust)(void *)orig;
|
||||
return (FARPROC)(void *)hk_WinVerifyTrust;
|
||||
}
|
||||
if (strcmp(lpProcName, "CryptQueryObject") == 0) {
|
||||
if (!o_CryptQueryObject) o_CryptQueryObject = (PFN_CryptQueryObject)(void *)orig;
|
||||
return (FARPROC)(void *)hk_CryptQueryObject;
|
||||
}
|
||||
if (strcmp(lpProcName, "LoadLibraryW") == 0) return (FARPROC)(void *)hk_LoadLibraryW;
|
||||
if (strcmp(lpProcName, "LoadLibraryA") == 0) return (FARPROC)(void *)hk_LoadLibraryA;
|
||||
if (strcmp(lpProcName, "LoadLibraryExW") == 0) return (FARPROC)(void *)hk_LoadLibraryExW;
|
||||
if (strcmp(lpProcName, "LoadLibraryExA") == 0) return (FARPROC)(void *)hk_LoadLibraryExA;
|
||||
if (strcmp(lpProcName, "GetFileAttributesW") == 0) return (FARPROC)(void *)hk_GetFileAttributesW;
|
||||
if (strcmp(lpProcName, "GetFileAttributesExW") == 0) return (FARPROC)(void *)hk_GetFileAttributesExW;
|
||||
if (strcmp(lpProcName, "CreateFileW") == 0) return (FARPROC)(void *)hk_CreateFileW;
|
||||
if (strcmp(lpProcName, "RegOpenKeyExW") == 0) return (FARPROC)(void *)hk_RegOpenKeyExW;
|
||||
if (strcmp(lpProcName, "RegEnumValueW") == 0) return (FARPROC)(void *)hk_RegEnumValueW;
|
||||
if (strcmp(lpProcName, "RegQueryValueExW") == 0) return (FARPROC)(void *)hk_RegQueryValueExW;
|
||||
if (strcmp(lpProcName, "RegCloseKey") == 0) return (FARPROC)(void *)hk_RegCloseKey;
|
||||
return orig;
|
||||
}
|
||||
|
||||
static int wl_should_skip_module(HMODULE mod) {
|
||||
if (!mod || mod == g_wl_self_mod || mod == g_wl_our_nvngx) return 1;
|
||||
WCHAR path[MAX_PATH] = {0};
|
||||
DWORD n = GetModuleFileNameW(mod, path, MAX_PATH);
|
||||
if (n == 0) return 1;
|
||||
const WCHAR *base = wl_basename_w(path);
|
||||
// Never patch core OS / Wine system DLLs to prevent recursion or loader side-effects
|
||||
if (_wcsicmp(base, L"ntdll.dll") == 0 ||
|
||||
_wcsicmp(base, L"kernel32.dll") == 0 ||
|
||||
_wcsicmp(base, L"kernelbase.dll") == 0 ||
|
||||
_wcsicmp(base, L"advapi32.dll") == 0 ||
|
||||
_wcsicmp(base, L"sechost.dll") == 0 ||
|
||||
_wcsicmp(base, L"wintrust.dll") == 0 ||
|
||||
_wcsicmp(base, L"crypt32.dll") == 0 ||
|
||||
_wcsicmp(base, L"ucrtbase.dll") == 0 ||
|
||||
_wcsicmp(base, L"msvcrt.dll") == 0 ||
|
||||
_wcsicmp(base, L"nvapi64.dll") == 0 ||
|
||||
_wcsicmp(base, L"_nvngx.dll") == 0 ||
|
||||
_wcsicmp(base, L"nvngx.dll") == 0 ||
|
||||
_wcsicmp(base, L"dxgi.dll") == 0 ||
|
||||
_wcsicmp(base, L"d3d12.dll") == 0 ||
|
||||
_wcsicmp(base, L"d3d12core.dll") == 0 ||
|
||||
_wcsicmp(base, L"d3d11.dll") == 0 ||
|
||||
_wcsicmp(base, L"vulkan-1.dll") == 0 ||
|
||||
_wcsicmp(base, L"winevulkan.dll") == 0) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void *wl_hook_for_import(const char *funcName) {
|
||||
if (!funcName) return NULL;
|
||||
if (strcmp(funcName, "LoadLibraryW") == 0) return (void *)hk_LoadLibraryW;
|
||||
if (strcmp(funcName, "LoadLibraryA") == 0) return (void *)hk_LoadLibraryA;
|
||||
if (strcmp(funcName, "LoadLibraryExW") == 0) return (void *)hk_LoadLibraryExW;
|
||||
if (strcmp(funcName, "LoadLibraryExA") == 0) return (void *)hk_LoadLibraryExA;
|
||||
if (strcmp(funcName, "GetProcAddress") == 0) return (void *)hk_GetProcAddress;
|
||||
if (strcmp(funcName, "GetFileAttributesW") == 0) return (void *)hk_GetFileAttributesW;
|
||||
if (strcmp(funcName, "GetFileAttributesExW") == 0) return (void *)hk_GetFileAttributesExW;
|
||||
if (strcmp(funcName, "CreateFileW") == 0) return (void *)hk_CreateFileW;
|
||||
if (strcmp(funcName, "WinVerifyTrust") == 0) return (void *)hk_WinVerifyTrust;
|
||||
if (strcmp(funcName, "CryptQueryObject") == 0) return (void *)hk_CryptQueryObject;
|
||||
if (strcmp(funcName, "RegOpenKeyExW") == 0) return (void *)hk_RegOpenKeyExW;
|
||||
if (strcmp(funcName, "RegEnumValueW") == 0) return (void *)hk_RegEnumValueW;
|
||||
if (strcmp(funcName, "RegQueryValueExW") == 0) return (void *)hk_RegQueryValueExW;
|
||||
if (strcmp(funcName, "RegCloseKey") == 0) return (void *)hk_RegCloseKey;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void wl_patch_module_iat(HMODULE mod) {
|
||||
if (wl_should_skip_module(mod)) return;
|
||||
uint8_t *base = (uint8_t *)mod;
|
||||
IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)base;
|
||||
if (IsBadReadPtr(dos, sizeof *dos) || dos->e_magic != IMAGE_DOS_SIGNATURE) return;
|
||||
IMAGE_NT_HEADERS *nt = (IMAGE_NT_HEADERS *)(base + dos->e_lfanew);
|
||||
if (IsBadReadPtr(nt, sizeof *nt) || nt->Signature != IMAGE_NT_SIGNATURE) return;
|
||||
|
||||
IMAGE_DATA_DIRECTORY impDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
|
||||
if (!impDir.VirtualAddress || !impDir.Size) return;
|
||||
IMAGE_IMPORT_DESCRIPTOR *desc = (IMAGE_IMPORT_DESCRIPTOR *)(base + impDir.VirtualAddress);
|
||||
|
||||
for (; !IsBadReadPtr(desc, sizeof *desc) && desc->Name != 0; desc++) {
|
||||
if (!desc->OriginalFirstThunk || !desc->FirstThunk) continue;
|
||||
IMAGE_THUNK_DATA *origThunk = (IMAGE_THUNK_DATA *)(base + desc->OriginalFirstThunk);
|
||||
IMAGE_THUNK_DATA *iatThunk = (IMAGE_THUNK_DATA *)(base + desc->FirstThunk);
|
||||
for (; origThunk->u1.AddressOfData != 0; origThunk++, iatThunk++) {
|
||||
if (IMAGE_SNAP_BY_ORDINAL(origThunk->u1.Ordinal)) continue;
|
||||
IMAGE_IMPORT_BY_NAME *ibn = (IMAGE_IMPORT_BY_NAME *)(base + origThunk->u1.AddressOfData);
|
||||
void *hookFn = wl_hook_for_import((const char *)ibn->Name);
|
||||
if (!hookFn) continue;
|
||||
void **slot = (void **)&iatThunk->u1.Function;
|
||||
if (*slot == hookFn) continue;
|
||||
DWORD oldProt = 0;
|
||||
if (VirtualProtect(slot, sizeof(void *), PAGE_READWRITE, &oldProt)) {
|
||||
*slot = hookFn;
|
||||
VirtualProtect(slot, sizeof(void *), oldProt, &oldProt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int wl_is_arxan_protected_exe(void) {
|
||||
WCHAR exePath[MAX_PATH] = {0};
|
||||
if (!GetModuleFileNameW(NULL, exePath, MAX_PATH)) return 0;
|
||||
const WCHAR *base = wl_basename_w(exePath);
|
||||
return _wcsicmp(base, L"rdr2.exe") == 0 ||
|
||||
_wcsicmp(base, L"playrdr2.exe") == 0 ||
|
||||
_wcsicmp(base, L"gta5.exe") == 0;
|
||||
}
|
||||
|
||||
static void wl_install_ngx_hooks_once(void) {
|
||||
if (InterlockedCompareExchange(&g_wl_hooks_installed, 1, 0) != 0) return;
|
||||
if (!dd_env_is_on("DROIDDECK_UPSCALE_SIGFIX")) return;
|
||||
if (!g_wl_hook_cs_ready) { InitializeCriticalSection(&g_wl_hook_cs); g_wl_hook_cs_ready = 1; }
|
||||
g_wl_tls_reent = TlsAlloc();
|
||||
|
||||
// RDR2 uses Arxan anti-tamper which terminates the game right after the loading screen
|
||||
// if its executable .text or IAT is modified. Rely cleanly on NGXCore registry keys +
|
||||
// EnableSignatureOverride ({41FCC608-...}=01) without touching RDR2.exe memory!
|
||||
if (wl_is_arxan_protected_exe()) {
|
||||
wl_hook_log("[nvapi] Arxan-protected game detected (RDR2) — skipping IAT/.text patching");
|
||||
return;
|
||||
}
|
||||
|
||||
HMODULE hK32 = GetModuleHandleA("kernel32.dll");
|
||||
HMODULE hAdv = GetModuleHandleA("advapi32.dll");
|
||||
if (!hAdv) hAdv = LoadLibraryA("advapi32.dll");
|
||||
HMODULE hWt = GetModuleHandleA("wintrust.dll");
|
||||
HMODULE hCr = GetModuleHandleA("crypt32.dll");
|
||||
|
||||
if (hK32) {
|
||||
o_LoadLibraryW = (PFN_LoadLibraryW)(void *)GetProcAddress(hK32, "LoadLibraryW");
|
||||
o_LoadLibraryA = (PFN_LoadLibraryA)(void *)GetProcAddress(hK32, "LoadLibraryA");
|
||||
o_LoadLibraryExW = (PFN_LoadLibraryExW)(void *)GetProcAddress(hK32, "LoadLibraryExW");
|
||||
o_LoadLibraryExA = (PFN_LoadLibraryExA)(void *)GetProcAddress(hK32, "LoadLibraryExA");
|
||||
o_GetProcAddress = (PFN_GetProcAddress)(void *)GetProcAddress(hK32, "GetProcAddress");
|
||||
o_GetFileAttributesW = (PFN_GetFileAttributesW)(void *)GetProcAddress(hK32, "GetFileAttributesW");
|
||||
o_GetFileAttributesExW = (PFN_GetFileAttributesExW)(void *)GetProcAddress(hK32, "GetFileAttributesExW");
|
||||
o_CreateFileW = (PFN_CreateFileW)(void *)GetProcAddress(hK32, "CreateFileW");
|
||||
}
|
||||
if (hAdv) {
|
||||
o_RegOpenKeyExW = (PFN_RegOpenKeyExW)(void *)GetProcAddress(hAdv, "RegOpenKeyExW");
|
||||
o_RegEnumValueW = (PFN_RegEnumValueW)(void *)GetProcAddress(hAdv, "RegEnumValueW");
|
||||
o_RegQueryValueExW = (PFN_RegQueryValueExW)(void *)GetProcAddress(hAdv, "RegQueryValueExW");
|
||||
o_RegCloseKey = (PFN_RegCloseKey)(void *)GetProcAddress(hAdv, "RegCloseKey");
|
||||
}
|
||||
if (hWt) o_WinVerifyTrust = (PFN_WinVerifyTrust)(void *)GetProcAddress(hWt, "WinVerifyTrust");
|
||||
if (hCr) o_CryptQueryObject = (PFN_CryptQueryObject)(void *)GetProcAddress(hCr, "CryptQueryObject");
|
||||
|
||||
wl_enter_hook();
|
||||
wl_find_signed_nv_dll();
|
||||
|
||||
int patched = 0;
|
||||
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
|
||||
if (snap != INVALID_HANDLE_VALUE) {
|
||||
MODULEENTRY32W me;
|
||||
memset(&me, 0, sizeof me);
|
||||
me.dwSize = sizeof me;
|
||||
if (Module32FirstW(snap, &me)) {
|
||||
do {
|
||||
if (!wl_should_skip_module(me.hModule)) {
|
||||
wl_patch_module_iat(me.hModule);
|
||||
patched++;
|
||||
}
|
||||
} while (Module32NextW(snap, &me));
|
||||
}
|
||||
CloseHandle(snap);
|
||||
} else {
|
||||
wl_patch_module_iat(GetModuleHandleW(NULL));
|
||||
patched = 1;
|
||||
}
|
||||
wl_leave_hook();
|
||||
|
||||
char buf[128];
|
||||
snprintf(buf, sizeof buf, "[nvapi] Installed ARM64EC-safe NGX IAT hooks on %d modules", patched);
|
||||
wl_hook_log(buf);
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
// DroidDeck: modified from michaelisomer-cyber/Winlator-NeuralScale 71c140d9 (see README.md).
|
||||
// Full OptiScaler/fakenvapi-parity nvapi64.dll shim for Winlator Ludashi FSR 4 NPU.
|
||||
// - Dynamically queries DXGI Adapter 0 LUID so NVIDIA Streamline (Cyberpunk 2077, etc.)
|
||||
// matches the DXGI adapter to our spoofed NVIDIA GeForce RTX 2060 (Turing TU106).
|
||||
// - Implements all core NVAPI interfaces required by RDR2 (Vulkan/DX12), Cyberpunk 2077
|
||||
// (Streamline sl.common / sl.dlss), Unreal Engine, and DX11/DX12/Vulkan DLSS titles.
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include "wl_ngx_hooks.h"
|
||||
|
||||
typedef int32_t NvAPI_Status;
|
||||
#define NVAPI_OK 0
|
||||
#define NVAPI_ERROR -1
|
||||
#define NVAPI_INVALID_ARGUMENT -5
|
||||
#define NVAPI_NO_IMPLEMENTATION -7
|
||||
#define NVAPI_END_ENUMERATION -7
|
||||
#define NVAPI_INVALID_POINTER -14
|
||||
#define NVAPI_NOT_SUPPORTED -104
|
||||
#define NVAPI_INCOMPATIBLE_STRUCT_VERSION -105
|
||||
|
||||
#define NVAPI_SHORT_STRING_MAX 64
|
||||
#define NVAPI_MAX_PHYSICAL_GPUS 64
|
||||
|
||||
// NVIDIA Driver 570.00 (satisfies all DLSS 2/3/3.5/4 & Streamline 2.x checks)
|
||||
#define WL_NV_DRIVER_VERSION 57000u
|
||||
#define WL_NV_BUILD_BRANCH "r570_00"
|
||||
#define WL_NV_GPU_NAME "NVIDIA GeForce RTX 2060"
|
||||
|
||||
static void *const k_fake_gpu = (void *)(uintptr_t)0x000010DE00001F08ULL;
|
||||
static void *const k_fake_lgpu = (void *)(uintptr_t)0x000010DE00001F09ULL;
|
||||
static void *const k_fake_disp = (void *)(uintptr_t)0x000010DE00000001ULL;
|
||||
static void *const k_drs_sess = (void *)(uintptr_t)0x000010DE0000D001ULL;
|
||||
static void *const k_drs_prof = (void *)(uintptr_t)0x000010DE0000D002ULL;
|
||||
|
||||
// Minimal COM vtable definitions for IDXGIFactory1 / IDXGIAdapter1 (no dxgi.lib link required)
|
||||
typedef struct WlDxgiAdapterDesc1 {
|
||||
WCHAR Description[128];
|
||||
UINT VendorId;
|
||||
UINT DeviceId;
|
||||
UINT SubSysId;
|
||||
UINT Revision;
|
||||
SIZE_T DedicatedVideoMemory;
|
||||
SIZE_T DedicatedSystemMemory;
|
||||
SIZE_T SharedSystemMemory;
|
||||
LUID AdapterLuid;
|
||||
UINT Flags;
|
||||
} WlDxgiAdapterDesc1;
|
||||
|
||||
typedef struct WlIDXGIAdapter1Vtbl {
|
||||
HRESULT (STDMETHODCALLTYPE *QueryInterface)(void *, const GUID *, void **);
|
||||
ULONG (STDMETHODCALLTYPE *AddRef)(void *);
|
||||
ULONG (STDMETHODCALLTYPE *Release)(void *);
|
||||
HRESULT (STDMETHODCALLTYPE *SetPrivateData)(void *, const GUID *, UINT, const void *);
|
||||
HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)(void *, const GUID *, const void *);
|
||||
HRESULT (STDMETHODCALLTYPE *GetPrivateData)(void *, const GUID *, UINT *, void *);
|
||||
HRESULT (STDMETHODCALLTYPE *GetParent)(void *, const GUID *, void **);
|
||||
HRESULT (STDMETHODCALLTYPE *EnumOutputs)(void *, UINT, void **);
|
||||
HRESULT (STDMETHODCALLTYPE *GetDesc)(void *, void *);
|
||||
HRESULT (STDMETHODCALLTYPE *CheckInterfaceSupport)(void *, const GUID *, LARGE_INTEGER *);
|
||||
HRESULT (STDMETHODCALLTYPE *GetDesc1)(void *, WlDxgiAdapterDesc1 *);
|
||||
} WlIDXGIAdapter1Vtbl;
|
||||
|
||||
typedef struct { WlIDXGIAdapter1Vtbl *lpVtbl; } WlIDXGIAdapter1;
|
||||
|
||||
typedef struct WlIDXGIFactory1Vtbl {
|
||||
HRESULT (STDMETHODCALLTYPE *QueryInterface)(void *, const GUID *, void **);
|
||||
ULONG (STDMETHODCALLTYPE *AddRef)(void *);
|
||||
ULONG (STDMETHODCALLTYPE *Release)(void *);
|
||||
HRESULT (STDMETHODCALLTYPE *SetPrivateData)(void *, const GUID *, UINT, const void *);
|
||||
HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)(void *, const GUID *, const void *);
|
||||
HRESULT (STDMETHODCALLTYPE *GetPrivateData)(void *, const GUID *, UINT *, void *);
|
||||
HRESULT (STDMETHODCALLTYPE *GetParent)(void *, const GUID *, void **);
|
||||
HRESULT (STDMETHODCALLTYPE *EnumAdapters)(void *, UINT, void **);
|
||||
HRESULT (STDMETHODCALLTYPE *MakeWindowAssociation)(void *, HWND, UINT);
|
||||
HRESULT (STDMETHODCALLTYPE *GetWindowAssociation)(void *, HWND *);
|
||||
HRESULT (STDMETHODCALLTYPE *CreateSwapChain)(void *, void *, void *, void **);
|
||||
HRESULT (STDMETHODCALLTYPE *CreateSoftwareAdapter)(void *, HMODULE, void **);
|
||||
HRESULT (STDMETHODCALLTYPE *EnumAdapters1)(void *, UINT, WlIDXGIAdapter1 **);
|
||||
} WlIDXGIFactory1Vtbl;
|
||||
|
||||
typedef struct { WlIDXGIFactory1Vtbl *lpVtbl; } WlIDXGIFactory1;
|
||||
|
||||
typedef HRESULT (WINAPI *PFN_CreateDXGIFactory1)(const GUID *riid, void **ppFactory);
|
||||
static const GUID k_IID_IDXGIFactory1 = {
|
||||
0x770aae78u, 0xf26fu, 0x4dbau, { 0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87 }
|
||||
};
|
||||
|
||||
static CRITICAL_SECTION g_cs;
|
||||
static int g_cs_ready = 0;
|
||||
static int g_dxgi_probed = 0;
|
||||
static LUID g_luid = { 0x10DE1F08u, 0 };
|
||||
static uint32_t g_vendor_id = 0x10DEu;
|
||||
static uint32_t g_device_id = 0x1F08u;
|
||||
static uint32_t g_subsys_id = 0x10DE1F08u;
|
||||
static uint32_t g_rev_id = 0xA1u;
|
||||
static uint64_t g_dxgi_vram_bytes = 0ULL;
|
||||
|
||||
static void ensure_cs(void) {
|
||||
if (!g_cs_ready) { InitializeCriticalSection(&g_cs); g_cs_ready = 1; }
|
||||
}
|
||||
|
||||
static void probe_dxgi_adapter_once(void) {
|
||||
ensure_cs();
|
||||
EnterCriticalSection(&g_cs);
|
||||
if (!g_dxgi_probed) {
|
||||
g_dxgi_probed = 1;
|
||||
HMODULE hDxgi = GetModuleHandleA("dxgi.dll");
|
||||
if (!hDxgi) hDxgi = LoadLibraryA("dxgi.dll");
|
||||
if (hDxgi) {
|
||||
PFN_CreateDXGIFactory1 fnCreate = (PFN_CreateDXGIFactory1)(void *)GetProcAddress(hDxgi, "CreateDXGIFactory1");
|
||||
if (fnCreate) {
|
||||
WlIDXGIFactory1 *factory = NULL;
|
||||
if (SUCCEEDED(fnCreate(&k_IID_IDXGIFactory1, (void **)&factory)) && factory) {
|
||||
WlIDXGIAdapter1 *adapter = NULL;
|
||||
if (SUCCEEDED(factory->lpVtbl->EnumAdapters1(factory, 0, &adapter)) && adapter) {
|
||||
WlDxgiAdapterDesc1 desc;
|
||||
memset(&desc, 0, sizeof desc);
|
||||
if (SUCCEEDED(adapter->lpVtbl->GetDesc1(adapter, &desc))) {
|
||||
g_luid = desc.AdapterLuid;
|
||||
if (desc.DedicatedVideoMemory > 0) {
|
||||
g_dxgi_vram_bytes = (uint64_t)desc.DedicatedVideoMemory;
|
||||
}
|
||||
if (desc.VendorId == 0x10DEu && desc.DeviceId != 0) {
|
||||
g_vendor_id = desc.VendorId;
|
||||
g_device_id = desc.DeviceId;
|
||||
if (desc.SubSysId) g_subsys_id = desc.SubSysId;
|
||||
if (desc.Revision) g_rev_id = desc.Revision;
|
||||
}
|
||||
}
|
||||
adapter->lpVtbl->Release(adapter);
|
||||
}
|
||||
factory->lpVtbl->Release(factory);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
LeaveCriticalSection(&g_cs);
|
||||
}
|
||||
|
||||
static uint64_t wl_nv_vram_bytes(void) {
|
||||
static const char *const names[] = { "DROIDDECK_UPSCALE_VRAM_MB", "WINLATOR_FSR4_VRAM_MB", "WRAPPER_VMEM_MAX_SIZE" };
|
||||
char buf[64];
|
||||
for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) {
|
||||
DWORD n = GetEnvironmentVariableA(names[i], buf, sizeof(buf));
|
||||
if (n > 0 && n < sizeof(buf)) {
|
||||
unsigned long long mb = strtoull(buf, NULL, 10);
|
||||
if (mb >= 512ULL && mb <= 65536ULL) return mb * 1024ULL * 1024ULL;
|
||||
}
|
||||
}
|
||||
probe_dxgi_adapter_once();
|
||||
if (g_dxgi_vram_bytes >= 512ULL * 1024ULL * 1024ULL) return g_dxgi_vram_bytes;
|
||||
return 12ULL * 1024ULL * 1024ULL * 1024ULL;
|
||||
}
|
||||
|
||||
static void copy_short_str(char *dst, const char *src) {
|
||||
if (!dst) return;
|
||||
strncpy(dst, src ? src : "", NVAPI_SHORT_STRING_MAX - 1);
|
||||
dst[NVAPI_SHORT_STRING_MAX - 1] = '\0';
|
||||
}
|
||||
|
||||
// ---- Exact NVAPI structs (verified against NVIDIA NVAPI SDK / fakenvapi) ----
|
||||
typedef struct {
|
||||
uint32_t version;
|
||||
uint32_t drvVersion;
|
||||
uint32_t bldChangeListNum;
|
||||
char szBuildBranchString[NVAPI_SHORT_STRING_MAX];
|
||||
char szAdapterString[NVAPI_SHORT_STRING_MAX];
|
||||
} WlNvDisplayDriverVersion;
|
||||
|
||||
typedef struct {
|
||||
uint32_t version;
|
||||
uint32_t driverVersion;
|
||||
char szBuildBranch[NVAPI_SHORT_STRING_MAX];
|
||||
uint32_t flags; /* bit0=DCH, bit1=Studio, bit2=GameReady, bit3=RTXProd, bit4=RTXNFB */
|
||||
char szBuildBaseBranch[NVAPI_SHORT_STRING_MAX];
|
||||
uint32_t reservedEx;
|
||||
} WlNvDisplayDriverInfoV2;
|
||||
|
||||
typedef struct {
|
||||
uint32_t version;
|
||||
void *pOSAdapterId;
|
||||
uint32_t physicalGpuCount;
|
||||
void *physicalGpuHandles[NVAPI_MAX_PHYSICAL_GPUS];
|
||||
uint32_t reserved[8];
|
||||
} WlNvLogicalGpuDataV1;
|
||||
|
||||
typedef struct {
|
||||
uint32_t version;
|
||||
uint32_t gpuCount;
|
||||
struct {
|
||||
void *hPhysicalGpu;
|
||||
uint32_t flags;
|
||||
} computeGpus[NVAPI_MAX_PHYSICAL_GPUS];
|
||||
} WlNvComputeGpuTopologyV1;
|
||||
|
||||
typedef struct {
|
||||
uint32_t bIsPresent;
|
||||
uint32_t frequency;
|
||||
} WlNvClockDomain;
|
||||
|
||||
typedef struct {
|
||||
uint32_t version;
|
||||
uint32_t clockType;
|
||||
WlNvClockDomain domain[32];
|
||||
} WlNvGpuClockFrequencies;
|
||||
|
||||
// ---- Core NVAPI implementations ----
|
||||
static NvAPI_Status __cdecl impl_Initialize(void) {
|
||||
wl_install_ngx_hooks_once();
|
||||
probe_dxgi_adapter_once();
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_Unload(void) { return NVAPI_OK; }
|
||||
static NvAPI_Status __cdecl impl_GetInterfaceVersionString(char *out) {
|
||||
copy_short_str(out, "NVAPI Open Source Interface (Winlator FSR4 NPU)");
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GetErrorMessage(NvAPI_Status nr, char *out) {
|
||||
copy_short_str(out, nr == NVAPI_OK ? "NVAPI_OK" : "NVAPI_ERROR");
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GetDisplayDriverVersion(void *disp, WlNvDisplayDriverVersion *ver) {
|
||||
(void)disp;
|
||||
if (!ver) return NVAPI_INVALID_ARGUMENT;
|
||||
ver->drvVersion = WL_NV_DRIVER_VERSION;
|
||||
ver->bldChangeListNum = 35000000u;
|
||||
copy_short_str(ver->szBuildBranchString, WL_NV_BUILD_BRANCH);
|
||||
copy_short_str(ver->szAdapterString, WL_NV_GPU_NAME);
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_SYS_GetDriverAndBranchVersion(uint32_t *ver, char *branch) {
|
||||
if (ver) *ver = WL_NV_DRIVER_VERSION;
|
||||
if (branch) copy_short_str(branch, WL_NV_BUILD_BRANCH);
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_SYS_GetDisplayDriverInfo(WlNvDisplayDriverInfoV2 *info) {
|
||||
if (!info) return NVAPI_INVALID_ARGUMENT;
|
||||
info->driverVersion = WL_NV_DRIVER_VERSION;
|
||||
copy_short_str(info->szBuildBranch, WL_NV_BUILD_BRANCH);
|
||||
info->flags = (1u << 0) | (1u << 1) | (1u << 2) | (1u << 3) | (1u << 4);
|
||||
uint32_t struct_ver = (info->version >> 16) & 0xFFFFu;
|
||||
if (struct_ver >= 2u || info->version == 2u) {
|
||||
copy_short_str(info->szBuildBaseBranch, WL_NV_BUILD_BRANCH);
|
||||
info->reservedEx = 0;
|
||||
}
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_EnumPhysicalGPUs(void **handles, uint32_t *count) {
|
||||
probe_dxgi_adapter_once();
|
||||
if (handles) handles[0] = k_fake_gpu;
|
||||
if (count) *count = 1u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_EnumLogicalGPUs(void **handles, uint32_t *count) {
|
||||
probe_dxgi_adapter_once();
|
||||
if (handles) handles[0] = k_fake_lgpu;
|
||||
if (count) *count = 1u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_EnumNvidiaDisplayHandle(uint32_t idx, void **handle) {
|
||||
if (idx > 0) return NVAPI_END_ENUMERATION;
|
||||
if (handle) *handle = k_fake_disp;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_EnumUnattached(uint32_t idx, void **handle) {
|
||||
(void)idx; (void)handle;
|
||||
return NVAPI_END_ENUMERATION;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GetLogicalGPUFromPhysicalGPU(void *phys, void **logical) {
|
||||
(void)phys;
|
||||
if (logical) *logical = k_fake_lgpu;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GetPhysicalGPUsFromLogicalGPU(void *logical, void **phys, uint32_t *count) {
|
||||
(void)logical;
|
||||
if (phys) phys[0] = k_fake_gpu;
|
||||
if (count) *count = 1u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GetPhysicalGPUsFromDisplay(void *disp, void **phys, uint32_t *count) {
|
||||
(void)disp;
|
||||
if (phys) phys[0] = k_fake_gpu;
|
||||
if (count) *count = 1u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GetGPUIDfromPhysicalGPU(void *phys, uint32_t *gpuId) {
|
||||
(void)phys;
|
||||
if (gpuId) *gpuId = 0x100u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GetPhysicalGPUFromGPUID(uint32_t gpuId, void **phys) {
|
||||
(void)gpuId;
|
||||
if (phys) *phys = k_fake_gpu;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetAdapterIdFromPhysicalGpu(void *gpu, void *pOSAdapterId) {
|
||||
(void)gpu;
|
||||
if (!pOSAdapterId) return NVAPI_INVALID_ARGUMENT;
|
||||
probe_dxgi_adapter_once();
|
||||
memcpy(pOSAdapterId, &g_luid, sizeof(g_luid));
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetLogicalGpuInfo(void *logical, WlNvLogicalGpuDataV1 *data) {
|
||||
(void)logical;
|
||||
if (!data) return NVAPI_INVALID_ARGUMENT;
|
||||
probe_dxgi_adapter_once();
|
||||
if (data->pOSAdapterId) memcpy(data->pOSAdapterId, &g_luid, sizeof(g_luid));
|
||||
data->physicalGpuCount = 1u;
|
||||
data->physicalGpuHandles[0] = k_fake_gpu;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetFullName(void *gpu, char *name) {
|
||||
(void)gpu;
|
||||
copy_short_str(name, WL_NV_GPU_NAME);
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetPCIIdentifiers(void *gpu, uint32_t *devId, uint32_t *subSysId, uint32_t *revId, uint32_t *extDevId) {
|
||||
(void)gpu;
|
||||
probe_dxgi_adapter_once();
|
||||
if (devId) *devId = (g_device_id << 16) | (g_vendor_id & 0xFFFFu);
|
||||
if (subSysId) *subSysId = g_subsys_id;
|
||||
if (revId) *revId = g_rev_id;
|
||||
if (extDevId) *extDevId = g_device_id;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetArchInfo(void *gpu, void *info) {
|
||||
(void)gpu;
|
||||
if (!info) return NVAPI_INVALID_ARGUMENT;
|
||||
uint32_t *u = (uint32_t *)info;
|
||||
// NV_GPU_ARCH_INFO_V2: [0]=version, [1]=architecture (TU100=0x160), [2]=implementation (TU106=0x06), [3]=revision (0xA1)
|
||||
u[1] = 0x00000160u;
|
||||
u[2] = 0x00000006u;
|
||||
u[3] = 0x000000A1u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetGPUType(void *gpu, uint32_t *type) {
|
||||
(void)gpu;
|
||||
if (type) *type = 2u; /* NV_SYSTEM_TYPE_DISCRETE */
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetMemoryInfo(void *gpu, uint32_t *info) {
|
||||
(void)gpu;
|
||||
if (info) {
|
||||
uint64_t vram_kb64 = wl_nv_vram_bytes() / 1024ULL;
|
||||
uint32_t vram_kb = (vram_kb64 > 0xFFFFFFFFULL) ? 0xFFFFFFFFu : (uint32_t)vram_kb64;
|
||||
info[1] = vram_kb;
|
||||
info[2] = vram_kb;
|
||||
info[3] = 0u;
|
||||
info[4] = vram_kb / 2u;
|
||||
info[5] = (vram_kb / 8u) * 7u;
|
||||
}
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetMemoryInfoEx(void *gpu, uint64_t *info) {
|
||||
(void)gpu;
|
||||
if (info) {
|
||||
uint64_t vram_b = wl_nv_vram_bytes();
|
||||
info[1] = vram_b;
|
||||
info[2] = vram_b;
|
||||
info[3] = 0ULL;
|
||||
info[4] = vram_b / 2ULL;
|
||||
info[5] = (vram_b / 8ULL) * 7ULL;
|
||||
}
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetVbiosVersionString(void *gpu, char *out) {
|
||||
(void)gpu;
|
||||
copy_short_str(out, "90.06.2E.00.01");
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetPhysicalFrameBufferSize(void *gpu, uint32_t *kb) {
|
||||
(void)gpu;
|
||||
if (kb) {
|
||||
uint64_t vram_kb64 = wl_nv_vram_bytes() / 1024ULL;
|
||||
*kb = (vram_kb64 > 0xFFFFFFFFULL) ? 0xFFFFFFFFu : (uint32_t)vram_kb64;
|
||||
}
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetGpuCoreCount(void *gpu, uint32_t *cnt) {
|
||||
(void)gpu;
|
||||
if (cnt) *cnt = 1920u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetConnectedDisplayIds(void *gpu, void *ids, uint32_t *cnt, uint32_t flags) {
|
||||
(void)gpu; (void)ids; (void)flags;
|
||||
if (cnt) *cnt = 0u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_CudaEnumComputeCapableGpus(WlNvComputeGpuTopologyV1 *topo) {
|
||||
if (!topo) return NVAPI_INVALID_ARGUMENT;
|
||||
topo->gpuCount = 1u;
|
||||
topo->computeGpus[0].hPhysicalGpu = k_fake_gpu;
|
||||
topo->computeGpus[0].flags = 0x7u; /* CAPABLE | ENABLE | RECOMMENDED */
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_GPU_GetAllClockFrequencies(void *gpu, WlNvGpuClockFrequencies *clk) {
|
||||
(void)gpu;
|
||||
if (!clk) return NVAPI_INVALID_ARGUMENT;
|
||||
memset(clk->domain, 0, sizeof clk->domain);
|
||||
clk->domain[0].bIsPresent = 1; clk->domain[0].frequency = 1680000u; /* Graphics */
|
||||
clk->domain[4].bIsPresent = 1; clk->domain[4].frequency = 7000000u; /* Memory */
|
||||
clk->domain[7].bIsPresent = 1; clk->domain[7].frequency = 1400000u; /* Video */
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_Disp_GetDisplayIdByDisplayName(const char *name, uint32_t *id) {
|
||||
(void)name;
|
||||
if (id) *id = 0u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_Disp_GetGDIPrimaryDisplayId(uint32_t *id) {
|
||||
if (id) *id = 0u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_Disp_OutputMode(uint32_t dispId, uint32_t *mode) {
|
||||
(void)dispId;
|
||||
if (mode) *mode = 0u; /* SDR */
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_SYS_GetDisplayIdFromGpuAndOutputId(void *gpu, uint32_t outId, uint32_t *dispId) {
|
||||
(void)gpu; (void)outId;
|
||||
if (dispId) *dispId = 0u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_SYS_GetGpuAndOutputIdFromDisplayId(uint32_t dispId, void **gpu, uint32_t *outId) {
|
||||
(void)dispId;
|
||||
if (gpu) *gpu = k_fake_gpu;
|
||||
if (outId) *outId = 0u;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_D3D_GetCurrentSLIState(void *dev, uint32_t *state) {
|
||||
(void)dev;
|
||||
if (state) {
|
||||
state[1] = 1; state[2] = 1; state[3] = 0;
|
||||
state[4] = 0; state[5] = 0; state[6] = 0;
|
||||
}
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_D3D_GetObjectHandleForResource(void *dev, void *res, void **outH) {
|
||||
(void)dev;
|
||||
if (outH) *outH = res;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_D3D12_IsNvShaderExtnOpCodeSupported(void *dev, uint32_t op, uint8_t *supported) {
|
||||
(void)dev; (void)op;
|
||||
if (supported) *supported = 0;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_D3D12_GetRaytracingCaps(void *dev, uint32_t type, void *pData, size_t dataSize) {
|
||||
(void)dev; (void)type;
|
||||
if (!pData) return NVAPI_INVALID_POINTER;
|
||||
memset(pData, 0, dataSize);
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_DRS_CreateSession(void **sess) {
|
||||
if (sess) *sess = k_drs_sess;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_DRS_GetBaseProfile(void *sess, void **prof) {
|
||||
(void)sess;
|
||||
if (prof) *prof = k_drs_prof;
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_D3D_GetSleepStatus(void *dev, uint32_t *params) {
|
||||
(void)dev;
|
||||
if (params) {
|
||||
params[1] = 0u; /* bLowLatencyMode */
|
||||
params[2] = 0u; /* bFsVrr */
|
||||
params[3] = 0u; /* bCplVsyncOn */
|
||||
}
|
||||
return NVAPI_OK;
|
||||
}
|
||||
static NvAPI_Status __cdecl impl_NoOpOk(void) { return NVAPI_OK; }
|
||||
static NvAPI_Status __cdecl impl_NotSupported(void) { return NVAPI_NO_IMPLEMENTATION; }
|
||||
|
||||
__declspec(dllexport) void *__cdecl nvapi_QueryInterface(uint32_t id) {
|
||||
wl_install_ngx_hooks_once();
|
||||
switch (id) {
|
||||
// Core & driver info
|
||||
case 0x0150E828u: return (void *)impl_Initialize; // NvAPI_Initialize
|
||||
case 0xD22BDD7Eu: return (void *)impl_Unload; // NvAPI_Unload
|
||||
case 0x01053FA5u: return (void *)impl_GetInterfaceVersionString; // NvAPI_GetInterfaceVersionString
|
||||
case 0x6C2D048Cu: return (void *)impl_GetErrorMessage; // NvAPI_GetErrorMessage
|
||||
case 0xF951A4D1u: return (void *)impl_GetDisplayDriverVersion; // NvAPI_GetDisplayDriverVersion
|
||||
case 0x2926AAADu: return (void *)impl_SYS_GetDriverAndBranchVersion; // NvAPI_SYS_GetDriverAndBranchVersion
|
||||
case 0x721FACEBu: return (void *)impl_SYS_GetDisplayDriverInfo; // NvAPI_SYS_GetDisplayDriverInfo
|
||||
case 0x08F2BAB4u: return (void *)impl_SYS_GetDisplayIdFromGpuAndOutputId;// NvAPI_SYS_GetDisplayIdFromGpuAndOutputId
|
||||
case 0x112BA1A5u: return (void *)impl_SYS_GetGpuAndOutputIdFromDisplayId;// NvAPI_SYS_GetGpuAndOutputIdFromDisplayId
|
||||
|
||||
// Physical / logical GPU enumeration & LUID matching (CRITICAL for Streamline / Cyberpunk 2077)
|
||||
case 0xE5AC921Fu: return (void *)impl_EnumPhysicalGPUs; // NvAPI_EnumPhysicalGPUs
|
||||
case 0x48B3EA59u: return (void *)impl_EnumLogicalGPUs; // NvAPI_EnumLogicalGPUs
|
||||
case 0x9ABDD40Du: return (void *)impl_EnumNvidiaDisplayHandle; // NvAPI_EnumNvidiaDisplayHandle
|
||||
case 0x20DE9260u: return (void *)impl_EnumUnattached; // NvAPI_EnumNvidiaUnAttachedDisplayHandle
|
||||
case 0xADD604D1u: return (void *)impl_GetLogicalGPUFromPhysicalGPU; // NvAPI_GetLogicalGPUFromPhysicalGPU
|
||||
case 0xAEA3FA32u: return (void *)impl_GetPhysicalGPUsFromLogicalGPU; // NvAPI_GetPhysicalGPUsFromLogicalGPU
|
||||
case 0x34EF9506u: return (void *)impl_GetPhysicalGPUsFromDisplay; // NvAPI_GetPhysicalGPUsFromDisplay
|
||||
case 0x6533EA3Eu: return (void *)impl_GetGPUIDfromPhysicalGPU; // NvAPI_GetGPUIDfromPhysicalGPU
|
||||
case 0x5380AD1Au: return (void *)impl_GetPhysicalGPUFromGPUID; // NvAPI_GetPhysicalGPUFromGPUID
|
||||
case 0x0FF07FDEu: return (void *)impl_GPU_GetAdapterIdFromPhysicalGpu; // NvAPI_GPU_GetAdapterIdFromPhysicalGpu
|
||||
case 0x842B066Eu: return (void *)impl_GPU_GetLogicalGpuInfo; // NvAPI_GPU_GetLogicalGpuInfo
|
||||
|
||||
// GPU capabilities & identity
|
||||
case 0xCEEE8E9Fu: return (void *)impl_GPU_GetFullName; // NvAPI_GPU_GetFullName
|
||||
case 0x2DDFB66Eu: return (void *)impl_GPU_GetPCIIdentifiers; // NvAPI_GPU_GetPCIIdentifiers
|
||||
case 0xD8265D24u: return (void *)impl_GPU_GetArchInfo; // NvAPI_GPU_GetArchInfo
|
||||
case 0xC33BAEB1u: return (void *)impl_GPU_GetGPUType; // NvAPI_GPU_GetGPUType
|
||||
case 0x07F9B368u: return (void *)impl_GPU_GetMemoryInfo; // NvAPI_GPU_GetMemoryInfo
|
||||
case 0xC0599498u: return (void *)impl_GPU_GetMemoryInfoEx; // NvAPI_GPU_GetMemoryInfoEx
|
||||
case 0xA561FD7Du: return (void *)impl_GPU_GetVbiosVersionString; // NvAPI_GPU_GetVbiosVersionString
|
||||
case 0x46FBEB03u: return (void *)impl_GPU_GetPhysicalFrameBufferSize; // NvAPI_GPU_GetPhysicalFrameBufferSize
|
||||
case 0x5A04B644u: return (void *)impl_GPU_GetPhysicalFrameBufferSize; // NvAPI_GPU_GetVirtualFrameBufferSize
|
||||
case 0xC7026A87u: return (void *)impl_GPU_GetGpuCoreCount; // NvAPI_GPU_GetGpuCoreCount
|
||||
case 0x0078DBA2u: return (void *)impl_GPU_GetConnectedDisplayIds; // NvAPI_GPU_GetConnectedDisplayIds
|
||||
case 0x5786CC6Eu: return (void *)impl_GPU_CudaEnumComputeCapableGpus; // NvAPI_GPU_CudaEnumComputeCapableGpus
|
||||
case 0xDCB616C3u: return (void *)impl_GPU_GetAllClockFrequencies; // NvAPI_GPU_GetAllClockFrequencies
|
||||
|
||||
// Display
|
||||
case 0xAE457190u: return (void *)impl_Disp_GetDisplayIdByDisplayName; // NvAPI_DISP_GetDisplayIdByDisplayName
|
||||
case 0x1E9D8A31u: return (void *)impl_Disp_GetGDIPrimaryDisplayId; // NvAPI_DISP_GetGDIPrimaryDisplayId
|
||||
case 0x98E7661Au: return (void *)impl_Disp_OutputMode; // NvAPI_Disp_SetOutputMode
|
||||
case 0x81FED88Du: return (void *)impl_Disp_OutputMode; // NvAPI_Disp_GetOutputMode
|
||||
case 0x84F2A8DFu: return (void *)impl_NoOpOk; // NvAPI_Disp_GetHdrCapabilities
|
||||
case 0x351DA224u: return (void *)impl_NoOpOk; // NvAPI_Disp_HdrColorControl
|
||||
|
||||
// D3D / D3D12 / Reflex
|
||||
case 0x4B708B54u: return (void *)impl_D3D_GetCurrentSLIState; // NvAPI_D3D_GetCurrentSLIState
|
||||
case 0xFCEAC864u: return (void *)impl_D3D_GetObjectHandleForResource; // NvAPI_D3D_GetObjectHandleForResource
|
||||
case 0x8C02C4D0u: return (void *)impl_NoOpOk; // NvAPI_D3D_RegisterDevice
|
||||
case 0x3DFACEC8u: return (void *)impl_D3D12_IsNvShaderExtnOpCodeSupported;// NvAPI_D3D12_IsNvShaderExtnOpCodeSupported
|
||||
case 0x43D867C0u: return (void *)impl_NoOpOk; // NvAPI_D3D12_SetNvShaderExtnSlotSpaceLocalThread
|
||||
case 0x85A6C2A0u: return (void *)impl_D3D12_GetRaytracingCaps; // NvAPI_D3D12_GetRaytracingCaps
|
||||
case 0x03D6E8CBu: return (void *)impl_NoOpOk; // NvAPI_D3D12_NotifyOutOfBandCommandQueue
|
||||
case 0x13C98F73u: return (void *)impl_NoOpOk; // NvAPI_D3D12_SetAsyncFrameMarker
|
||||
case 0xAEF96CA1u: return (void *)impl_D3D_GetSleepStatus; // NvAPI_D3D_GetSleepStatus
|
||||
case 0xAC1CA9E0u: return (void *)impl_NoOpOk; // NvAPI_D3D_SetSleepMode
|
||||
case 0x852CD1D2u: return (void *)impl_NoOpOk; // NvAPI_D3D_Sleep
|
||||
case 0xB9F6FAFFu: return (void *)impl_NoOpOk; // NvAPI_D3D_SetReflexSync
|
||||
case 0x1A587F9Cu: return (void *)impl_NoOpOk; // NvAPI_D3D_GetLatency
|
||||
case 0xD9984C05u: return (void *)impl_NoOpOk; // NvAPI_D3D_SetLatencyMarker
|
||||
|
||||
// Vulkan Reflex (graceful unsupported so Vulkan games don't expect a timeline semaphore we didn't create)
|
||||
case 0x5C1696B6u: return (void *)impl_NotSupported; // NvAPI_Vulkan_InitLowLatencyDevice
|
||||
case 0x11A5932Bu: return (void *)impl_NoOpOk; // NvAPI_Vulkan_DestroyLowLatencyDevice
|
||||
case 0xADF966AFu: return (void *)impl_NotSupported; // NvAPI_Vulkan_GetSleepStatus
|
||||
case 0x2ACFD162u: return (void *)impl_NotSupported; // NvAPI_Vulkan_SetSleepMode
|
||||
case 0x36732B1Eu: return (void *)impl_NotSupported; // NvAPI_Vulkan_Sleep
|
||||
case 0x3233D44Au: return (void *)impl_NotSupported; // NvAPI_Vulkan_GetLatency
|
||||
case 0xA17D13D6u: return (void *)impl_NotSupported; // NvAPI_Vulkan_SetLatencyMarker
|
||||
case 0x5D6D3840u: return (void *)impl_NoOpOk; // NvAPI_Vulkan_NotifyOutOfBandVkQueue
|
||||
|
||||
// DRS (Driver Settings)
|
||||
case 0x0694D52Eu: return (void *)impl_DRS_CreateSession; // NvAPI_DRS_CreateSession
|
||||
case 0xDAD9CFF8u: return (void *)impl_NoOpOk; // NvAPI_DRS_DestroySession
|
||||
case 0x375DBD6Bu: return (void *)impl_NoOpOk; // NvAPI_DRS_LoadSettings
|
||||
case 0xFCBC7E14u: return (void *)impl_NoOpOk; // NvAPI_DRS_SaveSettings
|
||||
case 0xDA8466A0u: return (void *)impl_DRS_GetBaseProfile; // NvAPI_DRS_GetBaseProfile
|
||||
case 0x73BF8338u: return (void *)impl_NotSupported; // NvAPI_DRS_GetSetting
|
||||
case 0x577DD202u: return (void *)impl_NoOpOk; // NvAPI_DRS_SetSetting
|
||||
|
||||
default: return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
|
||||
(void)reserved;
|
||||
if (reason == DLL_PROCESS_ATTACH) {
|
||||
g_wl_self_mod = hinst;
|
||||
DisableThreadLibraryCalls(hinst);
|
||||
ensure_cs();
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
// DroidDeck: modified from michaelisomer-cyber/Winlator-NeuralScale 71c140d9 (see README.md).
|
||||
// Windows-side in-process Vulkan Seam Client for Winlator Ludashi FSR 4.1.1 HTP NPU Layer.
|
||||
// Allocates the host-coherent WlFsr4Mailbox + marker buffer on the game's VkDevice and
|
||||
// rings the vkCmdUpdateBuffer doorbell so libVkLayer_winlator_fsr4_npu.so records the
|
||||
// zero-copy Hexagon HTP v81 pipeline directly into the game's VkCommandBuffer.
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include "fsr4_seam_proto.h"
|
||||
#include "dd_env.h"
|
||||
|
||||
// Minimal Vulkan types for MinGW x86_64 (zero external Vulkan SDK dependency)
|
||||
typedef uint32_t VkFlags;
|
||||
typedef uint32_t VkBool32;
|
||||
typedef uint64_t VkDeviceSize;
|
||||
typedef int32_t VkResult;
|
||||
typedef void *VkInstance;
|
||||
typedef void *VkPhysicalDevice;
|
||||
typedef void *VkDevice;
|
||||
typedef void *VkCommandBuffer;
|
||||
typedef uint64_t VkBuffer;
|
||||
typedef uint64_t VkDeviceMemory;
|
||||
typedef uint64_t VkImage;
|
||||
typedef uint64_t VkImageView;
|
||||
|
||||
#define VK_SUCCESS 0
|
||||
#define VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO 12
|
||||
#define VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO 5
|
||||
#define VK_BUFFER_USAGE_TRANSFER_DST_BIT 0x00000002u
|
||||
#define VK_BUFFER_USAGE_STORAGE_BUFFER_BIT 0x00000020u
|
||||
#define VK_SHARING_MODE_EXCLUSIVE 0
|
||||
#define VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT 0x00000002u
|
||||
#define VK_MEMORY_PROPERTY_HOST_COHERENT_BIT 0x00000004u
|
||||
|
||||
typedef struct {
|
||||
uint32_t sType;
|
||||
const void *pNext;
|
||||
VkFlags flags;
|
||||
VkDeviceSize size;
|
||||
VkFlags usage;
|
||||
uint32_t sharingMode;
|
||||
uint32_t queueFamilyIndexCount;
|
||||
const uint32_t *pQueueFamilyIndices;
|
||||
} WlVkBufferCreateInfo;
|
||||
|
||||
typedef struct {
|
||||
VkDeviceSize size;
|
||||
VkDeviceSize alignment;
|
||||
uint32_t memoryTypeBits;
|
||||
} WlVkMemoryRequirements;
|
||||
|
||||
typedef struct {
|
||||
uint32_t sType;
|
||||
const void *pNext;
|
||||
VkDeviceSize allocationSize;
|
||||
uint32_t memoryTypeIndex;
|
||||
} WlVkMemoryAllocateInfo;
|
||||
|
||||
typedef struct {
|
||||
VkFlags propertyFlags;
|
||||
uint32_t heapIndex;
|
||||
} WlVkMemoryType;
|
||||
|
||||
typedef struct {
|
||||
VkDeviceSize size;
|
||||
VkFlags flags;
|
||||
} WlVkMemoryHeap;
|
||||
|
||||
typedef struct {
|
||||
uint32_t memoryTypeCount;
|
||||
WlVkMemoryType memoryTypes[32];
|
||||
uint32_t memoryHeapCount;
|
||||
WlVkMemoryHeap memoryHeaps[16];
|
||||
} WlVkPhysicalDeviceMemoryProperties;
|
||||
|
||||
typedef struct {
|
||||
uint32_t sType;
|
||||
const void *pNext;
|
||||
uint32_t srcAccessMask;
|
||||
uint32_t dstAccessMask;
|
||||
uint32_t oldLayout;
|
||||
uint32_t newLayout;
|
||||
uint32_t srcQueueFamilyIndex;
|
||||
uint32_t dstQueueFamilyIndex;
|
||||
VkImage image;
|
||||
struct {
|
||||
uint32_t aspectMask;
|
||||
uint32_t baseMipLevel;
|
||||
uint32_t levelCount;
|
||||
uint32_t baseArrayLayer;
|
||||
uint32_t layerCount;
|
||||
} subresourceRange;
|
||||
} WlVkImageMemoryBarrier;
|
||||
|
||||
typedef struct {
|
||||
struct {
|
||||
uint32_t aspectMask;
|
||||
uint32_t mipLevel;
|
||||
uint32_t baseArrayLayer;
|
||||
uint32_t layerCount;
|
||||
} srcSubresource;
|
||||
struct { int32_t x, y, z; } srcOffsets[2];
|
||||
struct {
|
||||
uint32_t aspectMask;
|
||||
uint32_t mipLevel;
|
||||
uint32_t baseArrayLayer;
|
||||
uint32_t layerCount;
|
||||
} dstSubresource;
|
||||
struct { int32_t x, y, z; } dstOffsets[2];
|
||||
} WlVkImageBlit;
|
||||
|
||||
typedef void *(__stdcall *PFN_wlVkGetDeviceProcAddr)(VkDevice, const char *);
|
||||
typedef void *(__stdcall *PFN_wlVkGetInstanceProcAddr)(VkInstance, const char *);
|
||||
typedef VkResult (__stdcall *PFN_wlVkCreateBuffer)(VkDevice, const WlVkBufferCreateInfo *, const void *, VkBuffer *);
|
||||
typedef void (__stdcall *PFN_wlVkDestroyBuffer)(VkDevice, VkBuffer, const void *);
|
||||
typedef void (__stdcall *PFN_wlVkGetBufferMemoryRequirements)(VkDevice, VkBuffer, WlVkMemoryRequirements *);
|
||||
typedef VkResult (__stdcall *PFN_wlVkAllocateMemory)(VkDevice, const WlVkMemoryAllocateInfo *, const void *, VkDeviceMemory *);
|
||||
typedef void (__stdcall *PFN_wlVkFreeMemory)(VkDevice, VkDeviceMemory, const void *);
|
||||
typedef VkResult (__stdcall *PFN_wlVkBindBufferMemory)(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize);
|
||||
typedef VkResult (__stdcall *PFN_wlVkMapMemory)(VkDevice, VkDeviceMemory, VkDeviceSize, VkDeviceSize, VkFlags, void **);
|
||||
typedef void (__stdcall *PFN_wlVkUnmapMemory)(VkDevice, VkDeviceMemory);
|
||||
typedef void (__stdcall *PFN_wlVkCmdUpdateBuffer)(VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, const void *);
|
||||
typedef void (__stdcall *PFN_wlVkCmdPipelineBarrier)(VkCommandBuffer, uint32_t, uint32_t, uint32_t, uint32_t, const void *, uint32_t, const void *, uint32_t, const WlVkImageMemoryBarrier *);
|
||||
typedef void (__stdcall *PFN_wlVkCmdBlitImage)(VkCommandBuffer, VkImage, uint32_t, VkImage, uint32_t, uint32_t, const WlVkImageBlit *, uint32_t);
|
||||
typedef void (__stdcall *PFN_wlVkGetPhysicalDeviceMemoryProperties)(VkPhysicalDevice, WlVkPhysicalDeviceMemoryProperties *);
|
||||
|
||||
typedef struct WlSeamClient {
|
||||
int ready;
|
||||
VkInstance inst;
|
||||
VkDevice dev;
|
||||
VkPhysicalDevice phys;
|
||||
VkBuffer mbox_buf;
|
||||
VkDeviceMemory mbox_mem;
|
||||
WlFsr4Mailbox *mbox;
|
||||
VkBuffer marker_buf;
|
||||
VkDeviceMemory marker_mem;
|
||||
uint64_t next_seq;
|
||||
PFN_wlVkDestroyBuffer DestroyBuffer;
|
||||
PFN_wlVkFreeMemory FreeMemory;
|
||||
PFN_wlVkUnmapMemory UnmapMemory;
|
||||
PFN_wlVkCmdUpdateBuffer CmdUpdateBuffer;
|
||||
PFN_wlVkCmdPipelineBarrier CmdPipelineBarrier;
|
||||
PFN_wlVkCmdBlitImage CmdBlitImage;
|
||||
} WlSeamClient;
|
||||
|
||||
static uint32_t wl_seam_pick_mem(const WlVkPhysicalDeviceMemoryProperties *mp, uint32_t bits, uint32_t want) {
|
||||
if (mp) {
|
||||
for (uint32_t i = 0; i < mp->memoryTypeCount; i++) {
|
||||
if ((bits & (1u << i)) && (mp->memoryTypes[i].propertyFlags & want) == want) return i;
|
||||
}
|
||||
}
|
||||
for (uint32_t i = 0; i < 32; i++) {
|
||||
if (bits & (1u << i)) return i;
|
||||
}
|
||||
return 0xFFFFFFFFu;
|
||||
}
|
||||
|
||||
static int wl_seam_init(WlSeamClient *c, VkInstance inst, VkPhysicalDevice phys, VkDevice dev,
|
||||
PFN_wlVkGetDeviceProcAddr gdpa) {
|
||||
memset(c, 0, sizeof *c);
|
||||
if (!dev) return 0;
|
||||
|
||||
HMODULE vkmod = GetModuleHandleA("vulkan-1.dll");
|
||||
if (!vkmod) vkmod = LoadLibraryA("vulkan-1.dll");
|
||||
if (!gdpa && vkmod) gdpa = (PFN_wlVkGetDeviceProcAddr)(void *)GetProcAddress(vkmod, "vkGetDeviceProcAddr");
|
||||
if (!gdpa) return 0;
|
||||
|
||||
PFN_wlVkCreateBuffer CreateBuffer = (PFN_wlVkCreateBuffer)gdpa(dev, "vkCreateBuffer");
|
||||
PFN_wlVkGetBufferMemoryRequirements GetBufReqs = (PFN_wlVkGetBufferMemoryRequirements)gdpa(dev, "vkGetBufferMemoryRequirements");
|
||||
PFN_wlVkAllocateMemory AllocateMemory = (PFN_wlVkAllocateMemory)gdpa(dev, "vkAllocateMemory");
|
||||
PFN_wlVkBindBufferMemory BindBufferMemory = (PFN_wlVkBindBufferMemory)gdpa(dev, "vkBindBufferMemory");
|
||||
PFN_wlVkMapMemory MapMemory = (PFN_wlVkMapMemory)gdpa(dev, "vkMapMemory");
|
||||
c->DestroyBuffer = (PFN_wlVkDestroyBuffer)gdpa(dev, "vkDestroyBuffer");
|
||||
c->FreeMemory = (PFN_wlVkFreeMemory)gdpa(dev, "vkFreeMemory");
|
||||
c->UnmapMemory = (PFN_wlVkUnmapMemory)gdpa(dev, "vkUnmapMemory");
|
||||
c->CmdUpdateBuffer = (PFN_wlVkCmdUpdateBuffer)gdpa(dev, "vkCmdUpdateBuffer");
|
||||
c->CmdPipelineBarrier = (PFN_wlVkCmdPipelineBarrier)gdpa(dev, "vkCmdPipelineBarrier");
|
||||
c->CmdBlitImage = (PFN_wlVkCmdBlitImage)gdpa(dev, "vkCmdBlitImage");
|
||||
|
||||
if (!CreateBuffer || !GetBufReqs || !AllocateMemory || !BindBufferMemory || !MapMemory || !c->CmdUpdateBuffer)
|
||||
return 0;
|
||||
|
||||
WlVkPhysicalDeviceMemoryProperties mp;
|
||||
memset(&mp, 0, sizeof mp);
|
||||
int has_mp = 0;
|
||||
if (phys && vkmod) {
|
||||
PFN_wlVkGetPhysicalDeviceMemoryProperties get_mp = NULL;
|
||||
if (inst) {
|
||||
PFN_wlVkGetInstanceProcAddr gipa = (PFN_wlVkGetInstanceProcAddr)(void *)GetProcAddress(vkmod, "vkGetInstanceProcAddr");
|
||||
if (gipa) get_mp = (PFN_wlVkGetPhysicalDeviceMemoryProperties)gipa(inst, "vkGetPhysicalDeviceMemoryProperties");
|
||||
}
|
||||
if (!get_mp) get_mp = (PFN_wlVkGetPhysicalDeviceMemoryProperties)(void *)GetProcAddress(vkmod, "vkGetPhysicalDeviceMemoryProperties");
|
||||
if (get_mp) { get_mp(phys, &mp); has_mp = 1; }
|
||||
}
|
||||
|
||||
// 1. Allocate MAILBOX buffer (exact signature WLFSR4_MAILBOX_BYTES + STORAGE_BUFFER | TRANSFER_DST)
|
||||
WlVkBufferCreateInfo bci;
|
||||
memset(&bci, 0, sizeof bci);
|
||||
bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
bci.size = WLFSR4_MAILBOX_BYTES;
|
||||
bci.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
|
||||
bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
if (CreateBuffer(dev, &bci, NULL, &c->mbox_buf) != VK_SUCCESS) return 0;
|
||||
|
||||
WlVkMemoryRequirements mr;
|
||||
memset(&mr, 0, sizeof mr);
|
||||
GetBufReqs(dev, c->mbox_buf, &mr);
|
||||
|
||||
WlVkMemoryAllocateInfo mai;
|
||||
memset(&mai, 0, sizeof mai);
|
||||
mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
mai.allocationSize = mr.size;
|
||||
|
||||
void *mapped = NULL;
|
||||
if (has_mp) {
|
||||
uint32_t mt = wl_seam_pick_mem(&mp, mr.memoryTypeBits,
|
||||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
if (mt == 0xFFFFFFFFu) { if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL); return 0; }
|
||||
mai.memoryTypeIndex = mt;
|
||||
if (AllocateMemory(dev, &mai, NULL, &c->mbox_mem) != VK_SUCCESS ||
|
||||
BindBufferMemory(dev, c->mbox_buf, c->mbox_mem, 0) != VK_SUCCESS ||
|
||||
MapMemory(dev, c->mbox_mem, 0, WLFSR4_MAILBOX_BYTES, 0, &mapped) != VK_SUCCESS || !mapped) {
|
||||
if (c->mbox_mem && c->FreeMemory) c->FreeMemory(dev, c->mbox_mem, NULL);
|
||||
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
} else {
|
||||
// VkPhysicalDevice unavailable (e.g. FSR 2 VK): probe compatible memory types until vkMapMemory succeeds
|
||||
int ok = 0;
|
||||
for (uint32_t i = 0; i < 32; i++) {
|
||||
if (!(mr.memoryTypeBits & (1u << i))) continue;
|
||||
VkDeviceMemory cand = 0;
|
||||
mai.memoryTypeIndex = i;
|
||||
if (AllocateMemory(dev, &mai, NULL, &cand) != VK_SUCCESS) continue;
|
||||
if (MapMemory(dev, cand, 0, WLFSR4_MAILBOX_BYTES, 0, &mapped) == VK_SUCCESS && mapped) {
|
||||
if (BindBufferMemory(dev, c->mbox_buf, cand, 0) == VK_SUCCESS) {
|
||||
c->mbox_mem = cand;
|
||||
ok = 1;
|
||||
break;
|
||||
}
|
||||
if (c->UnmapMemory) c->UnmapMemory(dev, cand);
|
||||
}
|
||||
if (c->FreeMemory) c->FreeMemory(dev, cand, NULL);
|
||||
mapped = NULL;
|
||||
}
|
||||
if (!ok) {
|
||||
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
memset(mapped, 0, WLFSR4_MAILBOX_BYTES);
|
||||
c->mbox = (WlFsr4Mailbox *)mapped;
|
||||
c->mbox->magic = WLFSR4_MAILBOX_MAGIC;
|
||||
c->mbox->version = WLFSR4_PROTO_VERSION;
|
||||
|
||||
// 2. Allocate MARKER buffer (exact signature WLFSR4_MARKER_BYTES + TRANSFER_DST)
|
||||
bci.size = WLFSR4_MARKER_BYTES;
|
||||
bci.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
|
||||
if (CreateBuffer(dev, &bci, NULL, &c->marker_buf) != VK_SUCCESS) {
|
||||
if (c->UnmapMemory) c->UnmapMemory(dev, c->mbox_mem);
|
||||
if (c->FreeMemory) c->FreeMemory(dev, c->mbox_mem, NULL);
|
||||
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
GetBufReqs(dev, c->marker_buf, &mr);
|
||||
mai.allocationSize = mr.size;
|
||||
mai.memoryTypeIndex = wl_seam_pick_mem(has_mp ? &mp : NULL, mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
|
||||
if (AllocateMemory(dev, &mai, NULL, &c->marker_mem) != VK_SUCCESS ||
|
||||
BindBufferMemory(dev, c->marker_buf, c->marker_mem, 0) != VK_SUCCESS) {
|
||||
if (c->marker_mem && c->FreeMemory) c->FreeMemory(dev, c->marker_mem, NULL);
|
||||
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->marker_buf, NULL);
|
||||
if (c->UnmapMemory) c->UnmapMemory(dev, c->mbox_mem);
|
||||
if (c->FreeMemory) c->FreeMemory(dev, c->mbox_mem, NULL);
|
||||
if (c->DestroyBuffer) c->DestroyBuffer(dev, c->mbox_buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
|
||||
c->inst = inst;
|
||||
c->dev = dev;
|
||||
c->phys = phys;
|
||||
c->next_seq = 1u;
|
||||
c->ready = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void wl_seam_destroy(WlSeamClient *c) {
|
||||
if (!c || !c->ready) return;
|
||||
if (c->marker_buf && c->DestroyBuffer) c->DestroyBuffer(c->dev, c->marker_buf, NULL);
|
||||
if (c->marker_mem && c->FreeMemory) c->FreeMemory(c->dev, c->marker_mem, NULL);
|
||||
if (c->mbox_mem && c->UnmapMemory) c->UnmapMemory(c->dev, c->mbox_mem);
|
||||
if (c->mbox_buf && c->DestroyBuffer) c->DestroyBuffer(c->dev, c->mbox_buf, NULL);
|
||||
if (c->mbox_mem && c->FreeMemory) c->FreeMemory(c->dev, c->mbox_mem, NULL);
|
||||
memset(c, 0, sizeof *c);
|
||||
}
|
||||
|
||||
static int wl_seam_dispatch(WlSeamClient *c, VkCommandBuffer cb, const WlFsr4FrameDesc *in_frame) {
|
||||
if (!c || !c->ready || !cb || !in_frame || !c->mbox) return 0;
|
||||
uint64_t seq = c->next_seq++;
|
||||
WlFsr4FrameDesc *slot = &c->mbox->slots[seq % WLFSR4_SLOTS];
|
||||
*slot = *in_frame;
|
||||
slot->seq = seq;
|
||||
MemoryBarrier();
|
||||
|
||||
WlFsr4DoorbellPayload pay;
|
||||
pay.magic = WLFSR4_DOORBELL_MAGIC;
|
||||
pay.seq = seq;
|
||||
c->CmdUpdateBuffer(cb, c->marker_buf, 0, sizeof pay, &pay);
|
||||
MemoryBarrier();
|
||||
|
||||
uint64_t ack = c->mbox->ack;
|
||||
return ((ack & WLFSR4_ACK_SEQ_MASK) == seq && (ack & WLFSR4_ACK_WORK_BIT)) ? 1 : 0;
|
||||
}
|
||||
|
||||
// Fail-closed guest-side bilinear blit fallback if the Vulkan layer did not ack a frame.
|
||||
// Ensures the game's output image is NEVER left unwritten / corrupted with stale VRAM.
|
||||
static int wl_seam_fallback_blit(WlSeamClient *c, VkCommandBuffer cb, const WlFsr4FrameDesc *f) {
|
||||
if (!c || !cb || !f || !c->CmdPipelineBarrier || !c->CmdBlitImage) return 0;
|
||||
if (!f->color.vk_image || !f->output.vk_image || f->color.vk_image == f->output.vk_image) return 0;
|
||||
uint32_t rw = f->render_w ? f->render_w : f->color.width;
|
||||
uint32_t rh = f->render_h ? f->render_h : f->color.height;
|
||||
uint32_t ow = f->output_w ? f->output_w : f->output.width;
|
||||
uint32_t oh = f->output_h ? f->output_h : f->output.height;
|
||||
if (!rw || !rh || !ow || !oh) return 0;
|
||||
|
||||
uint32_t src_lay = f->color.vk_layout ? f->color.vk_layout : 1u; /* GENERAL */
|
||||
uint32_t dst_lay = f->output.vk_layout ? f->output.vk_layout : 1u;
|
||||
|
||||
WlVkImageMemoryBarrier pre[2];
|
||||
memset(pre, 0, sizeof pre);
|
||||
pre[0].sType = 45u; /* VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER */
|
||||
pre[0].srcAccessMask = 0x00010000u; /* MEMORY_WRITE */
|
||||
pre[0].dstAccessMask = 0x00000800u; /* TRANSFER_READ */
|
||||
pre[0].oldLayout = src_lay;
|
||||
pre[0].newLayout = 6u; /* TRANSFER_SRC_OPTIMAL */
|
||||
pre[0].srcQueueFamilyIndex = 0xFFFFFFFFu;
|
||||
pre[0].dstQueueFamilyIndex = 0xFFFFFFFFu;
|
||||
pre[0].image = f->color.vk_image;
|
||||
pre[0].subresourceRange.aspectMask = 1u;
|
||||
pre[0].subresourceRange.levelCount = 1u;
|
||||
pre[0].subresourceRange.layerCount = 1u;
|
||||
|
||||
pre[1] = pre[0];
|
||||
pre[1].srcAccessMask = 0x00018000u; /* MEMORY_READ | MEMORY_WRITE */
|
||||
pre[1].dstAccessMask = 0x00001000u; /* TRANSFER_WRITE */
|
||||
pre[1].oldLayout = dst_lay;
|
||||
pre[1].newLayout = 7u; /* TRANSFER_DST_OPTIMAL */
|
||||
pre[1].image = f->output.vk_image;
|
||||
|
||||
c->CmdPipelineBarrier(cb, 0x00010000u /* ALL_COMMANDS */, 0x00001000u /* TRANSFER */, 0, 0, NULL, 0, NULL, 2, pre);
|
||||
|
||||
WlVkImageBlit reg;
|
||||
memset(®, 0, sizeof reg);
|
||||
reg.srcSubresource.aspectMask = 1u;
|
||||
reg.srcSubresource.layerCount = 1u;
|
||||
reg.srcOffsets[1].x = (int32_t)rw;
|
||||
reg.srcOffsets[1].y = (int32_t)rh;
|
||||
reg.srcOffsets[1].z = 1;
|
||||
reg.dstSubresource.aspectMask = 1u;
|
||||
reg.dstSubresource.layerCount = 1u;
|
||||
reg.dstOffsets[1].x = (int32_t)ow;
|
||||
reg.dstOffsets[1].y = (int32_t)oh;
|
||||
reg.dstOffsets[1].z = 1;
|
||||
c->CmdBlitImage(cb, f->color.vk_image, 6u, f->output.vk_image, 7u, 1u, ®, 1u /* LINEAR */);
|
||||
|
||||
WlVkImageMemoryBarrier post[2];
|
||||
post[0] = pre[0];
|
||||
post[0].srcAccessMask = 0x00000800u;
|
||||
post[0].dstAccessMask = 0x00018000u;
|
||||
post[0].oldLayout = 6u;
|
||||
post[0].newLayout = src_lay;
|
||||
|
||||
post[1] = pre[1];
|
||||
post[1].srcAccessMask = 0x00001000u;
|
||||
post[1].dstAccessMask = 0x00018000u;
|
||||
post[1].oldLayout = 7u;
|
||||
post[1].newLayout = dst_lay;
|
||||
|
||||
c->CmdPipelineBarrier(cb, 0x00001000u /* TRANSFER */, 0x00010000u /* ALL_COMMANDS */, 0, 0, NULL, 0, NULL, 2, post);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int wl_seam_dispatch_or_blit(WlSeamClient *c, VkCommandBuffer cb, const WlFsr4FrameDesc *f) {
|
||||
if (wl_seam_dispatch(c, cb, f)) return 1;
|
||||
return wl_seam_fallback_blit(c, cb, f);
|
||||
}
|
||||
|
||||
static int wl_seam_parse_backend_env(void) {
|
||||
static const char *const names[] = {
|
||||
"DROIDDECK_UPSCALE_BACKEND", "DROIDDECK_UPSCALE_ENGINE",
|
||||
"WINLATOR_FSR4_BACKEND", "WINLATOR_FSR4_ENGINE", NULL,
|
||||
};
|
||||
char buf[64];
|
||||
if (dd_env_first(names, buf, sizeof buf)) {
|
||||
if (_stricmp(buf, "fsr3_gpu") == 0 || _stricmp(buf, "fsr3") == 0) return WL_FSR_BACKEND_FSR3_GPU;
|
||||
if (_stricmp(buf, "sgsr2_gpu") == 0 || _stricmp(buf, "sgsr2") == 0 || _stricmp(buf, "snapdragon") == 0) return WL_FSR_BACKEND_SGSR2_GPU;
|
||||
if (_stricmp(buf, "xess3_gpu") == 0 || _stricmp(buf, "xess3") == 0 || _stricmp(buf, "xess") == 0) return WL_FSR_BACKEND_XESS3_GPU;
|
||||
if (_stricmp(buf, "fsr4_1_lite_npu") == 0 || _stricmp(buf, "fsr412_lite_npu") == 0) return WL_FSR_BACKEND_FSR4_1_LITE_NPU;
|
||||
if (_stricmp(buf, "fsr4_1_full_npu") == 0 || _stricmp(buf, "fsr411_full_npu") == 0) return WL_FSR_BACKEND_FSR4_1_FULL_NPU;
|
||||
if (_stricmp(buf, "fsr4_1_lite_gpu") == 0 || _stricmp(buf, "fsr412_lite_gpu") == 0) return WL_FSR_BACKEND_FSR4_1_LITE_GPU;
|
||||
if (_stricmp(buf, "fsr4_1_full_gpu") == 0 || _stricmp(buf, "fsr411_full_gpu") == 0) return WL_FSR_BACKEND_FSR4_1_FULL_GPU;
|
||||
if (_stricmp(buf, "fsr4_0_npu") == 0 || _stricmp(buf, "fsr4_npu") == 0 || _stricmp(buf, "fsr4") == 0) return WL_FSR_BACKEND_FSR4_1_FULL_NPU;
|
||||
}
|
||||
return WL_FSR_BACKEND_FSR4_1_FULL_NPU;
|
||||
}
|
||||
|
||||
static int wl_seam_live_backend(const WlSeamClient *c, int *out_enabled) {
|
||||
if (out_enabled) *out_enabled = 1;
|
||||
if (c && c->ready && c->mbox) {
|
||||
uint64_t ctrl = c->mbox->live_ctrl;
|
||||
if (ctrl != 0ULL) {
|
||||
if (out_enabled) *out_enabled = (ctrl & WLFSR4_CTRL_ENABLED_BIT) ? 1 : 0;
|
||||
return (int)(ctrl & WLFSR4_CTRL_BACKEND_MASK);
|
||||
}
|
||||
}
|
||||
return wl_seam_parse_backend_env();
|
||||
}
|
||||
|
||||
static void wl_seam_telemetry_begin(WlSeamClient *c, VkCommandBuffer cb) {
|
||||
if (!c || !c->ready || !cb || !c->CmdUpdateBuffer) return;
|
||||
WlFsr4DoorbellPayload pay;
|
||||
pay.magic = WLFSR4_TELEMETRY_MAGIC;
|
||||
pay.seq = 0u;
|
||||
c->CmdUpdateBuffer(cb, c->marker_buf, 0, sizeof pay, &pay);
|
||||
}
|
||||
|
||||
static void wl_seam_telemetry_end(WlSeamClient *c, VkCommandBuffer cb, const WlFsr4FrameDesc *in_frame, uint32_t cpu_us) {
|
||||
if (!c || !c->ready || !cb || !in_frame || !c->mbox || !c->CmdUpdateBuffer) return;
|
||||
uint64_t seq = c->next_seq++;
|
||||
if (seq == 0u) seq = c->next_seq++;
|
||||
WlFsr4FrameDesc *slot = &c->mbox->slots[seq % WLFSR4_SLOTS];
|
||||
*slot = *in_frame;
|
||||
slot->seq = seq;
|
||||
c->mbox->tele_gpu_us = cpu_us;
|
||||
MemoryBarrier();
|
||||
|
||||
WlFsr4DoorbellPayload pay;
|
||||
pay.magic = WLFSR4_TELEMETRY_MAGIC;
|
||||
pay.seq = seq;
|
||||
c->CmdUpdateBuffer(cb, c->marker_buf, 0, sizeof pay, &pay);
|
||||
MemoryBarrier();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// DroidDeck: NVIDIA Streamline (sl.interposer) wraps the D3D11/D3D12 devices and D3D12 command lists it creates
|
||||
// (Unreal Engine games create their device through it). vkd3d-proton and DXVK do not know the wrappers, so their
|
||||
// interop calls fail on them. QueryInterface(StreamlineRetrieveBaseInterface) on a wrapper returns the wrapped object,
|
||||
// AddRef'd (Streamline source/core/sl.interposer/d3d12/d3d12Device.cpp); anything else answers E_NOINTERFACE.
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
static const GUID WL_IID_StreamlineRetrieveBaseInterface = {
|
||||
0xadec44e2, 0x61f0, 0x45c3, { 0xad, 0x9f, 0x1b, 0x37, 0x37, 0x92, 0x84, 0xff }
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
HRESULT (__stdcall *QueryInterface)(void *This, const GUID *riid, void **ppv);
|
||||
ULONG (__stdcall *AddRef)(void *This);
|
||||
ULONG (__stdcall *Release)(void *This);
|
||||
} WlUnknownVtbl;
|
||||
typedef struct { const WlUnknownVtbl *lpVtbl; } WlUnknown;
|
||||
|
||||
/* The object a Streamline wrapper stands for, AddRef'd; NULL when obj is not a wrapper. */
|
||||
static inline void *wl_sl_base(void *obj) {
|
||||
WlUnknown *u = (WlUnknown *)obj;
|
||||
void *base = NULL;
|
||||
if (!u || !u->lpVtbl) return NULL;
|
||||
if (u->lpVtbl->QueryInterface(obj, &WL_IID_StreamlineRetrieveBaseInterface, &base) != S_OK) return NULL;
|
||||
return base;
|
||||
}
|
||||
|
||||
static inline void wl_com_release(void *obj) {
|
||||
WlUnknown *u = (WlUnknown *)obj;
|
||||
if (u && u->lpVtbl) u->lpVtbl->Release(obj);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Exact vkd3d-proton ID3D12DXVKInteropDevice / ID3D12DXVKInteropDevice1 C COM vtable
|
||||
// Verified against HansKristian-Work/vkd3d-proton include/vkd3d_device_vkd3d_ext.idl.
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include "wl_streamline.h"
|
||||
|
||||
// {39da4e09-bd1c-4198-9fae-86bbe3be41fd}
|
||||
static const GUID WL_IID_ID3D12DXVKInteropDevice = {
|
||||
0x39da4e09, 0xbd1c, 0x4198, {0x9f, 0xae, 0x86, 0xbb, 0xe3, 0xbe, 0x41, 0xfd}
|
||||
};
|
||||
|
||||
// {902d8115-59eb-4406-9518-fe00f991ee65}
|
||||
static const GUID WL_IID_ID3D12DXVKInteropDevice1 = {
|
||||
0x902d8115, 0x59eb, 0x4406, {0x95, 0x18, 0xfe, 0x00, 0xf9, 0x91, 0xee, 0x65}
|
||||
};
|
||||
|
||||
typedef struct WlID3D12DXVKInteropDevice1 WlID3D12DXVKInteropDevice1;
|
||||
|
||||
typedef struct WlID3D12DXVKInteropDevice1Vtbl {
|
||||
// IUnknown
|
||||
HRESULT (__stdcall *QueryInterface)(WlID3D12DXVKInteropDevice1 *This, const GUID *riid, void **ppv);
|
||||
ULONG (__stdcall *AddRef)(WlID3D12DXVKInteropDevice1 *This);
|
||||
ULONG (__stdcall *Release)(WlID3D12DXVKInteropDevice1 *This);
|
||||
// ID3D12DXVKInteropDevice
|
||||
HRESULT (__stdcall *GetDXGIAdapter)(WlID3D12DXVKInteropDevice1 *This, const GUID *iid, void **object);
|
||||
HRESULT (__stdcall *GetInstanceExtensions)(WlID3D12DXVKInteropDevice1 *This, UINT *count, const char **exts);
|
||||
HRESULT (__stdcall *GetDeviceExtensions)(WlID3D12DXVKInteropDevice1 *This, UINT *count, const char **exts);
|
||||
HRESULT (__stdcall *GetDeviceFeatures)(WlID3D12DXVKInteropDevice1 *This, const void **features);
|
||||
HRESULT (__stdcall *GetVulkanHandles)(WlID3D12DXVKInteropDevice1 *This, void **vk_inst, void **vk_phys, void **vk_dev);
|
||||
HRESULT (__stdcall *GetVulkanQueueInfo)(WlID3D12DXVKInteropDevice1 *This, void *queue, void **vk_queue, UINT32 *vk_qf);
|
||||
void (__stdcall *GetVulkanImageLayout)(WlID3D12DXVKInteropDevice1 *This, void *resource, UINT32 d3d12_state, UINT32 *vk_layout);
|
||||
HRESULT (__stdcall *GetVulkanResourceInfo)(WlID3D12DXVKInteropDevice1 *This, void *resource, UINT64 *vk_handle, UINT64 *buf_offset);
|
||||
HRESULT (__stdcall *LockCommandQueue)(WlID3D12DXVKInteropDevice1 *This, void *queue);
|
||||
HRESULT (__stdcall *UnlockCommandQueue)(WlID3D12DXVKInteropDevice1 *This, void *queue);
|
||||
// ID3D12DXVKInteropDevice1
|
||||
HRESULT (__stdcall *GetVulkanResourceInfo1)(WlID3D12DXVKInteropDevice1 *This, void *resource, UINT64 *vk_handle, UINT64 *buf_offset, UINT32 *vk_format);
|
||||
HRESULT (__stdcall *CreateInteropCommandQueue)(WlID3D12DXVKInteropDevice1 *This, const void *desc, UINT32 qf, void **ppQueue);
|
||||
HRESULT (__stdcall *CreateInteropCommandAllocator)(WlID3D12DXVKInteropDevice1 *This, UINT32 type, UINT32 qf, void **ppAlloc);
|
||||
HRESULT (__stdcall *BeginVkCommandBufferInterop)(WlID3D12DXVKInteropDevice1 *This, void *cmdList, void **pVkCmdBuf);
|
||||
HRESULT (__stdcall *EndVkCommandBufferInterop)(WlID3D12DXVKInteropDevice1 *This, void *cmdList);
|
||||
} WlID3D12DXVKInteropDevice1Vtbl;
|
||||
|
||||
struct WlID3D12DXVKInteropDevice1 {
|
||||
const WlID3D12DXVKInteropDevice1Vtbl *lpVtbl;
|
||||
};
|
||||
|
||||
static inline WlID3D12DXVKInteropDevice1 *wl_query_vkd3d_interop(void *d3d12_device) {
|
||||
if (!d3d12_device) return NULL;
|
||||
typedef struct {
|
||||
HRESULT (__stdcall *QueryInterface)(void *This, const GUID *riid, void **ppv);
|
||||
} IUnkVtbl;
|
||||
typedef struct { const IUnkVtbl *lpVtbl; } IUnkObj;
|
||||
IUnkObj *obj = (IUnkObj *)d3d12_device;
|
||||
WlID3D12DXVKInteropDevice1 *out = NULL;
|
||||
if (obj->lpVtbl && obj->lpVtbl->QueryInterface(d3d12_device, &WL_IID_ID3D12DXVKInteropDevice1, (void **)&out) == S_OK && out) {
|
||||
return out;
|
||||
}
|
||||
void *base = wl_sl_base(d3d12_device);
|
||||
if (base) {
|
||||
IUnkObj *b = (IUnkObj *)base;
|
||||
if (b->lpVtbl->QueryInterface(base, &WL_IID_ID3D12DXVKInteropDevice1, (void **)&out) != S_OK) out = NULL;
|
||||
wl_com_release(base);
|
||||
return out;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* BeginVkCommandBufferInterop on the command list vkd3d knows (a Streamline wrapper is unwrapped). On success *used is
|
||||
* the list to pass to wl_vkd3d_end_cb, which also drops the unwrapped reference. */
|
||||
static inline int wl_vkd3d_begin_cb(WlID3D12DXVKInteropDevice1 *interop, void *cmd_list, void **vk_cb, void **used) {
|
||||
void *base = wl_sl_base(cmd_list);
|
||||
void *target = base ? base : cmd_list;
|
||||
*vk_cb = NULL;
|
||||
*used = NULL;
|
||||
if (interop->lpVtbl->BeginVkCommandBufferInterop(interop, target, vk_cb) == S_OK && *vk_cb) {
|
||||
*used = target;
|
||||
return 1;
|
||||
}
|
||||
if (base) wl_com_release(base);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static inline void wl_vkd3d_end_cb(WlID3D12DXVKInteropDevice1 *interop, void *cmd_list, void *used) {
|
||||
interop->lpVtbl->EndVkCommandBufferInterop(interop, used);
|
||||
if (used != cmd_list) wl_com_release(used);
|
||||
}
|
||||
|
||||
/* GetVulkanResourceInfo1, retried on the wrapped object when res is a Streamline wrapper. */
|
||||
static inline HRESULT wl_vkd3d_resource_info(WlID3D12DXVKInteropDevice1 *interop, void *res, UINT64 *vk_handle,
|
||||
UINT64 *buf_offset, UINT32 *vk_format) {
|
||||
HRESULT hr = interop->lpVtbl->GetVulkanResourceInfo1(interop, res, vk_handle, buf_offset, vk_format);
|
||||
if (hr == S_OK && *vk_handle) return hr;
|
||||
void *base = wl_sl_base(res);
|
||||
if (!base) return hr;
|
||||
hr = interop->lpVtbl->GetVulkanResourceInfo1(interop, base, vk_handle, buf_offset, vk_format);
|
||||
wl_com_release(base);
|
||||
return hr;
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
// Winlator Ludashi Direct Intel XeSS 3.0 DP4a Execution Helper (Vulkan + DX12)
|
||||
//
|
||||
// Dynamically loads Intel's official XeSS 3.0 SDK runtime (wl_xess_official.dll) and
|
||||
// executes genuine XeSS 3.0 DP4a upscaling on Adreno 840 when the user selects
|
||||
// "XeSS 3.0 DP4a (GPU)" in Winlator settings or the in-game live sidebar.
|
||||
//
|
||||
// On ANY initialization or execution failure (driver mismatch, missing extension, OOM),
|
||||
// cleanly destroys the XeSS context and returns 0 so the caller falls back seamlessly
|
||||
// to Winlator's FSR 3.1 GPU upscaler — never crashing or showing a black screen.
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
#include "wl_seam_client.h"
|
||||
#include "wl_vkd3d_interop.h"
|
||||
|
||||
#pragma pack(push, 8)
|
||||
typedef struct _wl_xess_ctx_t *wl_xess_ctx_t;
|
||||
|
||||
typedef struct { uint32_t x; uint32_t y; } wl_xess_2d_t;
|
||||
typedef wl_xess_2d_t wl_xess_coord_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t aspectMask;
|
||||
uint32_t baseMipLevel;
|
||||
uint32_t levelCount;
|
||||
uint32_t baseArrayLayer;
|
||||
uint32_t layerCount;
|
||||
} wl_xess_vk_subres_t;
|
||||
|
||||
typedef struct {
|
||||
VkImageView imageView;
|
||||
VkImage image;
|
||||
wl_xess_vk_subres_t subresourceRange;
|
||||
uint32_t format;
|
||||
unsigned int width;
|
||||
unsigned int height;
|
||||
} wl_xess_vk_img_t;
|
||||
|
||||
typedef struct {
|
||||
wl_xess_vk_img_t colorTexture;
|
||||
wl_xess_vk_img_t velocityTexture;
|
||||
wl_xess_vk_img_t depthTexture;
|
||||
wl_xess_vk_img_t exposureScaleTexture;
|
||||
wl_xess_vk_img_t responsivePixelMaskTexture;
|
||||
wl_xess_vk_img_t outputTexture;
|
||||
float jitterOffsetX;
|
||||
float jitterOffsetY;
|
||||
float exposureScale;
|
||||
uint32_t resetHistory;
|
||||
uint32_t inputWidth;
|
||||
uint32_t inputHeight;
|
||||
wl_xess_coord_t inputColorBase;
|
||||
wl_xess_coord_t inputMotionVectorBase;
|
||||
wl_xess_coord_t inputDepthBase;
|
||||
wl_xess_coord_t inputResponsiveMaskBase;
|
||||
wl_xess_coord_t reserved0;
|
||||
wl_xess_coord_t outputColorBase;
|
||||
} wl_xess_vk_exec_t;
|
||||
|
||||
typedef struct {
|
||||
wl_xess_2d_t outputResolution;
|
||||
uint32_t qualitySetting;
|
||||
uint32_t initFlags;
|
||||
uint32_t creationNodeMask;
|
||||
uint32_t visibleNodeMask;
|
||||
VkDeviceMemory tempBufferHeap;
|
||||
uint64_t bufferHeapOffset;
|
||||
VkDeviceMemory tempTextureHeap;
|
||||
uint64_t textureHeapOffset;
|
||||
uint64_t pipelineCache;
|
||||
} wl_xess_vk_init_t;
|
||||
|
||||
typedef struct {
|
||||
void *pColorTexture;
|
||||
void *pVelocityTexture;
|
||||
void *pDepthTexture;
|
||||
void *pExposureScaleTexture;
|
||||
void *pResponsivePixelMaskTexture;
|
||||
void *pOutputTexture;
|
||||
float jitterOffsetX;
|
||||
float jitterOffsetY;
|
||||
float exposureScale;
|
||||
uint32_t resetHistory;
|
||||
uint32_t inputWidth;
|
||||
uint32_t inputHeight;
|
||||
wl_xess_coord_t inputColorBase;
|
||||
wl_xess_coord_t inputMotionVectorBase;
|
||||
wl_xess_coord_t inputDepthBase;
|
||||
wl_xess_coord_t inputResponsiveMaskBase;
|
||||
wl_xess_coord_t reserved0;
|
||||
wl_xess_coord_t outputColorBase;
|
||||
void *pDescriptorHeap;
|
||||
uint32_t descriptorHeapOffset;
|
||||
} wl_xess_d3d12_exec_t;
|
||||
|
||||
typedef struct {
|
||||
wl_xess_2d_t outputResolution;
|
||||
uint32_t qualitySetting;
|
||||
uint32_t initFlags;
|
||||
uint32_t creationNodeMask;
|
||||
uint32_t visibleNodeMask;
|
||||
void *pTempBufferHeap;
|
||||
uint64_t bufferHeapOffset;
|
||||
void *pTempTextureHeap;
|
||||
uint64_t textureHeapOffset;
|
||||
void *pPipelineLibrary;
|
||||
} wl_xess_d3d12_init_t;
|
||||
#pragma pack(pop)
|
||||
|
||||
_Static_assert(sizeof(wl_xess_vk_img_t) == 48, "wl_xess_vk_img_t ABI mismatch");
|
||||
_Static_assert(sizeof(wl_xess_vk_init_t) == 64, "wl_xess_vk_init_t ABI mismatch");
|
||||
_Static_assert(sizeof(wl_xess_d3d12_init_t) == 64, "wl_xess_d3d12_init_t ABI mismatch");
|
||||
|
||||
typedef int32_t (__cdecl *PFN_xessVKCreateContext)(VkInstance, VkPhysicalDevice, VkDevice, wl_xess_ctx_t *);
|
||||
typedef int32_t (__cdecl *PFN_xessVKInit)(wl_xess_ctx_t, const wl_xess_vk_init_t *);
|
||||
typedef int32_t (__cdecl *PFN_xessVKExecute)(wl_xess_ctx_t, VkCommandBuffer, const wl_xess_vk_exec_t *);
|
||||
typedef int32_t (__cdecl *PFN_xessD3D12CreateContext)(void *, wl_xess_ctx_t *);
|
||||
typedef int32_t (__cdecl *PFN_xessD3D12Init)(wl_xess_ctx_t, const wl_xess_d3d12_init_t *);
|
||||
typedef int32_t (__cdecl *PFN_xessD3D12Execute)(wl_xess_ctx_t, void *, const wl_xess_d3d12_exec_t *);
|
||||
typedef int32_t (__cdecl *PFN_xessSetVelocityScale)(wl_xess_ctx_t, float, float);
|
||||
typedef int32_t (__cdecl *PFN_xessSetJitterScale)(wl_xess_ctx_t, float, float);
|
||||
typedef int32_t (__cdecl *PFN_xessDestroyContext)(wl_xess_ctx_t);
|
||||
|
||||
typedef struct WlXess3Api {
|
||||
int loaded;
|
||||
int available;
|
||||
DWORD load_err;
|
||||
HMODULE mod;
|
||||
PFN_xessVKCreateContext VKCreateContext;
|
||||
PFN_xessVKInit VKInit;
|
||||
PFN_xessVKExecute VKExecute;
|
||||
PFN_xessD3D12CreateContext D3D12CreateContext;
|
||||
PFN_xessD3D12Init D3D12Init;
|
||||
PFN_xessD3D12Execute D3D12Execute;
|
||||
PFN_xessSetVelocityScale SetVelocityScale;
|
||||
PFN_xessSetJitterScale SetJitterScale;
|
||||
PFN_xessDestroyContext DestroyContext;
|
||||
} WlXess3Api;
|
||||
|
||||
static WlXess3Api g_wl_xess3_api;
|
||||
|
||||
static int wl_xess3_load_api(void) {
|
||||
if (g_wl_xess3_api.loaded) return g_wl_xess3_api.available;
|
||||
g_wl_xess3_api.loaded = 1;
|
||||
SetLastError(0);
|
||||
HMODULE m = LoadLibraryA("wl_xess_official.dll");
|
||||
if (!m) m = LoadLibraryA("C:\\windows\\system32\\wl_xess_official.dll");
|
||||
if (!m) {
|
||||
g_wl_xess3_api.load_err = GetLastError();
|
||||
return 0;
|
||||
}
|
||||
g_wl_xess3_api.mod = m;
|
||||
g_wl_xess3_api.VKCreateContext = (PFN_xessVKCreateContext)(void *)GetProcAddress(m, "xessVKCreateContext");
|
||||
g_wl_xess3_api.VKInit = (PFN_xessVKInit)(void *)GetProcAddress(m, "xessVKInit");
|
||||
g_wl_xess3_api.VKExecute = (PFN_xessVKExecute)(void *)GetProcAddress(m, "xessVKExecute");
|
||||
g_wl_xess3_api.D3D12CreateContext = (PFN_xessD3D12CreateContext)(void *)GetProcAddress(m, "xessD3D12CreateContext");
|
||||
g_wl_xess3_api.D3D12Init = (PFN_xessD3D12Init)(void *)GetProcAddress(m, "xessD3D12Init");
|
||||
g_wl_xess3_api.D3D12Execute = (PFN_xessD3D12Execute)(void *)GetProcAddress(m, "xessD3D12Execute");
|
||||
g_wl_xess3_api.SetVelocityScale = (PFN_xessSetVelocityScale)(void *)GetProcAddress(m, "xessSetVelocityScale");
|
||||
g_wl_xess3_api.SetJitterScale = (PFN_xessSetJitterScale)(void *)GetProcAddress(m, "xessSetJitterScale");
|
||||
g_wl_xess3_api.DestroyContext = (PFN_xessDestroyContext)(void *)GetProcAddress(m, "xessDestroyContext");
|
||||
if ((g_wl_xess3_api.VKCreateContext && g_wl_xess3_api.VKInit && g_wl_xess3_api.VKExecute) ||
|
||||
(g_wl_xess3_api.D3D12CreateContext && g_wl_xess3_api.D3D12Init && g_wl_xess3_api.D3D12Execute)) {
|
||||
g_wl_xess3_api.available = 1;
|
||||
}
|
||||
return g_wl_xess3_api.available;
|
||||
}
|
||||
|
||||
typedef struct WlXess3State {
|
||||
wl_xess_ctx_t ctx;
|
||||
int is_vk;
|
||||
int initialized;
|
||||
int failed;
|
||||
uint32_t fail_stage; /* 1=load_dll, 2=proc, 3=create_ctx, 4=init, 5=exec, 6=missing_handles */
|
||||
int32_t fail_rc;
|
||||
uint32_t out_w, out_h;
|
||||
uint32_t quality;
|
||||
uint32_t init_flags;
|
||||
float last_mv_sx, last_mv_sy;
|
||||
} WlXess3State;
|
||||
|
||||
static void wl_xess3_destroy(WlXess3State *st) {
|
||||
if (!st) return;
|
||||
if (st->ctx && g_wl_xess3_api.DestroyContext) {
|
||||
g_wl_xess3_api.DestroyContext(st->ctx);
|
||||
}
|
||||
memset(st, 0, sizeof *st);
|
||||
}
|
||||
|
||||
static void wl_xess3_mark_fail(WlXess3State *st, uint32_t stage, int32_t rc) {
|
||||
if (!st) return;
|
||||
st->failed = 1;
|
||||
st->fail_stage = stage;
|
||||
st->fail_rc = rc;
|
||||
}
|
||||
|
||||
static void wl_xess3_tag_fallback(const WlXess3State *st, WlFsr4FrameDesc *f) {
|
||||
if (!f) return;
|
||||
f->flags |= WLFSR4_FLAG_XESS_FALLBACK;
|
||||
f->pad[0] = st ? st->fail_stage : 6u;
|
||||
f->pad[1] = st ? (uint32_t)st->fail_rc : 0u;
|
||||
}
|
||||
|
||||
static void wl_xess3_on_inactive(WlXess3State *st) {
|
||||
if (!st) return;
|
||||
// Allow clean retry when user toggles away from XeSS 3 and back
|
||||
st->failed = 0;
|
||||
}
|
||||
|
||||
static uint32_t wl_xess3_map_quality(uint32_t wl_q) {
|
||||
switch (wl_q) {
|
||||
case WLFSR4_QUALITY_ULTRA_PERF: return 100u; /* XESS_QUALITY_SETTING_ULTRA_PERFORMANCE */
|
||||
case WLFSR4_QUALITY_PERF: return 101u; /* XESS_QUALITY_SETTING_PERFORMANCE */
|
||||
case WLFSR4_QUALITY_BALANCED: return 102u; /* XESS_QUALITY_SETTING_BALANCED */
|
||||
case WLFSR4_QUALITY_QUALITY: return 103u; /* XESS_QUALITY_SETTING_QUALITY */
|
||||
case WLFSR4_QUALITY_ULTRA_QUAL: return 104u; /* XESS_QUALITY_SETTING_ULTRA_QUALITY */
|
||||
case WLFSR4_QUALITY_NATIVE_AA: return 106u; /* XESS_QUALITY_SETTING_AA */
|
||||
default: return 103u;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t wl_xess3_map_init_flags(uint32_t wl_flags) {
|
||||
uint32_t xf = 0u;
|
||||
if (wl_flags & WLFSR4_FLAG_DISPLAY_RES_MV) xf |= (1u << 0); /* HIGH_RES_MV */
|
||||
if (wl_flags & WLFSR4_FLAG_DEPTH_INVERTED) xf |= (1u << 1); /* INVERTED_DEPTH */
|
||||
if (!(wl_flags & WLFSR4_FLAG_HDR)) xf |= (1u << 6); /* LDR_INPUT_COLOR */
|
||||
if (wl_flags & WLFSR4_FLAG_MV_JITTERED) xf |= (1u << 7); /* JITTERED_MV */
|
||||
if (wl_flags & WLFSR4_FLAG_AUTO_EXPOSURE) xf |= (1u << 8); /* ENABLE_AUTOEXPOSURE */
|
||||
return xf;
|
||||
}
|
||||
|
||||
static void wl_xess3_vk_barrier(WlSeamClient *seam, VkCommandBuffer cb,
|
||||
VkImage img, uint32_t aspect,
|
||||
uint32_t old_lay, uint32_t new_lay) {
|
||||
if (!seam || !seam->CmdPipelineBarrier || !img || old_lay == new_lay) return;
|
||||
WlVkImageMemoryBarrier b;
|
||||
memset(&b, 0, sizeof b);
|
||||
b.sType = 45u; /* VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER */
|
||||
b.srcAccessMask = 0x00018000u; /* MEMORY_READ | MEMORY_WRITE */
|
||||
b.dstAccessMask = 0x00018000u;
|
||||
b.oldLayout = old_lay;
|
||||
b.newLayout = new_lay;
|
||||
b.srcQueueFamilyIndex = 0xFFFFFFFFu;
|
||||
b.dstQueueFamilyIndex = 0xFFFFFFFFu;
|
||||
b.image = img;
|
||||
b.subresourceRange.aspectMask = aspect ? aspect : 1u;
|
||||
b.subresourceRange.levelCount = 1u;
|
||||
b.subresourceRange.layerCount = 1u;
|
||||
seam->CmdPipelineBarrier(cb, 0x00010000u, 0x00010000u, 0, 0, NULL, 0, NULL, 1, &b);
|
||||
}
|
||||
|
||||
static int wl_xess3_eval_vk(WlXess3State *st, WlSeamClient *seam,
|
||||
VkCommandBuffer cb, const WlFsr4FrameDesc *f,
|
||||
const wl_xess_vk_img_t *col,
|
||||
const wl_xess_vk_img_t *dep,
|
||||
const wl_xess_vk_img_t *mv,
|
||||
const wl_xess_vk_img_t *out) {
|
||||
if (!st || st->failed || !seam || !seam->ready || !cb || !f || !col || !mv || !out) {
|
||||
if (st && !st->failed) wl_xess3_mark_fail(st, 6u, 1);
|
||||
return 0;
|
||||
}
|
||||
if (!col->image || !col->imageView || !mv->image || !mv->imageView || !out->image || !out->imageView) {
|
||||
wl_xess3_mark_fail(st, 6u, 2);
|
||||
return 0;
|
||||
}
|
||||
if (!wl_xess3_load_api()) {
|
||||
wl_xess3_mark_fail(st, 1u, (int32_t)g_wl_xess3_api.load_err);
|
||||
return 0;
|
||||
}
|
||||
if (!g_wl_xess3_api.VKCreateContext || !g_wl_xess3_api.VKInit || !g_wl_xess3_api.VKExecute) {
|
||||
wl_xess3_mark_fail(st, 2u, 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint32_t quality = wl_xess3_map_quality(f->quality_mode);
|
||||
uint32_t init_flags = wl_xess3_map_init_flags(f->flags);
|
||||
if (!dep || !dep->image || !dep->imageView) init_flags |= (1u << 0); /* HIGH_RES_MV if no depth */
|
||||
|
||||
if (!st->ctx) {
|
||||
if (!seam->inst || !seam->phys || !seam->dev) {
|
||||
wl_xess3_mark_fail(st, 6u, 3);
|
||||
return 0;
|
||||
}
|
||||
int32_t rc = g_wl_xess3_api.VKCreateContext(seam->inst, seam->phys, seam->dev, &st->ctx);
|
||||
if (rc < 0 || !st->ctx) {
|
||||
wl_xess3_mark_fail(st, 3u, rc);
|
||||
return 0;
|
||||
}
|
||||
st->is_vk = 1;
|
||||
}
|
||||
|
||||
if (!st->initialized || st->out_w != f->output_w || st->out_h != f->output_h ||
|
||||
st->quality != quality || st->init_flags != init_flags) {
|
||||
wl_xess_vk_init_t ip;
|
||||
memset(&ip, 0, sizeof ip);
|
||||
ip.outputResolution.x = f->output_w;
|
||||
ip.outputResolution.y = f->output_h;
|
||||
ip.qualitySetting = quality;
|
||||
ip.initFlags = init_flags;
|
||||
ip.creationNodeMask = 1u;
|
||||
ip.visibleNodeMask = 1u;
|
||||
int32_t rc = g_wl_xess3_api.VKInit(st->ctx, &ip);
|
||||
if (rc < 0) {
|
||||
wl_xess3_destroy(st);
|
||||
wl_xess3_mark_fail(st, 4u, rc);
|
||||
return 0;
|
||||
}
|
||||
st->initialized = 1;
|
||||
st->out_w = f->output_w;
|
||||
st->out_h = f->output_h;
|
||||
st->quality = quality;
|
||||
st->init_flags = init_flags;
|
||||
st->last_mv_sx = 1e9f;
|
||||
st->last_mv_sy = 1e9f;
|
||||
}
|
||||
|
||||
if (g_wl_xess3_api.SetVelocityScale && (st->last_mv_sx != f->mv_scale_x || st->last_mv_sy != f->mv_scale_y)) {
|
||||
g_wl_xess3_api.SetVelocityScale(st->ctx, f->mv_scale_x, f->mv_scale_y);
|
||||
st->last_mv_sx = f->mv_scale_x;
|
||||
st->last_mv_sy = f->mv_scale_y;
|
||||
}
|
||||
|
||||
// Ensure XeSS VK layout contract: inputs = SHADER_READ_ONLY_OPTIMAL (5), output = GENERAL (1)
|
||||
uint32_t col_lay = f->color.vk_layout ? f->color.vk_layout : 5u;
|
||||
uint32_t dep_lay = f->depth.vk_layout ? f->depth.vk_layout : 5u;
|
||||
uint32_t mv_lay = f->motion.vk_layout ? f->motion.vk_layout : 5u;
|
||||
uint32_t out_lay = f->output.vk_layout ? f->output.vk_layout : 1u;
|
||||
|
||||
wl_xess3_vk_barrier(seam, cb, col->image, 1u, col_lay, 5u);
|
||||
if (dep && dep->image) wl_xess3_vk_barrier(seam, cb, dep->image, dep->subresourceRange.aspectMask ? dep->subresourceRange.aspectMask : 2u, dep_lay, 5u);
|
||||
wl_xess3_vk_barrier(seam, cb, mv->image, 1u, mv_lay, 5u);
|
||||
wl_xess3_vk_barrier(seam, cb, out->image, 1u, out_lay, 1u);
|
||||
|
||||
wl_xess_vk_exec_t ep;
|
||||
memset(&ep, 0, sizeof ep);
|
||||
ep.colorTexture = *col;
|
||||
ep.velocityTexture = *mv;
|
||||
if (dep && dep->image && dep->imageView) ep.depthTexture = *dep;
|
||||
ep.outputTexture = *out;
|
||||
ep.jitterOffsetX = f->jitter_x;
|
||||
ep.jitterOffsetY = f->jitter_y;
|
||||
ep.exposureScale = (f->pre_exposure > 0.0f) ? f->pre_exposure : 1.0f;
|
||||
ep.resetHistory = (f->flags & WLFSR4_FLAG_RESET) ? 1u : 0u;
|
||||
ep.inputWidth = f->render_w;
|
||||
ep.inputHeight = f->render_h;
|
||||
|
||||
LARGE_INTEGER t0, t1, freq;
|
||||
QueryPerformanceFrequency(&freq);
|
||||
QueryPerformanceCounter(&t0);
|
||||
|
||||
wl_seam_telemetry_begin(seam, cb);
|
||||
int32_t rc = g_wl_xess3_api.VKExecute(st->ctx, cb, &ep);
|
||||
|
||||
// Restore caller layouts
|
||||
wl_xess3_vk_barrier(seam, cb, col->image, 1u, 5u, col_lay);
|
||||
if (dep && dep->image) wl_xess3_vk_barrier(seam, cb, dep->image, dep->subresourceRange.aspectMask ? dep->subresourceRange.aspectMask : 2u, 5u, dep_lay);
|
||||
wl_xess3_vk_barrier(seam, cb, mv->image, 1u, 5u, mv_lay);
|
||||
wl_xess3_vk_barrier(seam, cb, out->image, 1u, 1u, out_lay);
|
||||
|
||||
QueryPerformanceCounter(&t1);
|
||||
uint32_t cpu_us = (freq.QuadPart > 0) ? (uint32_t)(((t1.QuadPart - t0.QuadPart) * 1000000ULL) / (uint64_t)freq.QuadPart) : 0u;
|
||||
|
||||
if (rc < 0) {
|
||||
wl_xess3_destroy(st);
|
||||
wl_xess3_mark_fail(st, 5u, rc);
|
||||
return 0;
|
||||
}
|
||||
|
||||
wl_seam_telemetry_end(seam, cb, f, cpu_us);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int wl_xess3_eval_d3d12(WlXess3State *st, WlSeamClient *seam,
|
||||
WlID3D12DXVKInteropDevice1 *interop,
|
||||
void *d3d12_dev, void *d3d12_cmdlist,
|
||||
const WlFsr4FrameDesc *f,
|
||||
void *res_col, void *res_dep,
|
||||
void *res_mv, void *res_out) {
|
||||
if (!st || st->failed || !d3d12_dev || !d3d12_cmdlist || !f || !res_col || !res_mv || !res_out) {
|
||||
if (st && !st->failed) wl_xess3_mark_fail(st, 6u, 4);
|
||||
return 0;
|
||||
}
|
||||
if (!wl_xess3_load_api()) {
|
||||
wl_xess3_mark_fail(st, 1u, (int32_t)g_wl_xess3_api.load_err);
|
||||
return 0;
|
||||
}
|
||||
if (!g_wl_xess3_api.D3D12CreateContext || !g_wl_xess3_api.D3D12Init || !g_wl_xess3_api.D3D12Execute) {
|
||||
wl_xess3_mark_fail(st, 2u, 2);
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint32_t quality = wl_xess3_map_quality(f->quality_mode);
|
||||
uint32_t init_flags = wl_xess3_map_init_flags(f->flags);
|
||||
if (!res_dep) init_flags |= (1u << 0); /* HIGH_RES_MV if no depth */
|
||||
|
||||
if (!st->ctx) {
|
||||
int32_t rc = g_wl_xess3_api.D3D12CreateContext(d3d12_dev, &st->ctx);
|
||||
if (rc < 0 || !st->ctx) {
|
||||
wl_xess3_mark_fail(st, 3u, rc);
|
||||
return 0;
|
||||
}
|
||||
st->is_vk = 0;
|
||||
}
|
||||
|
||||
if (!st->initialized || st->out_w != f->output_w || st->out_h != f->output_h ||
|
||||
st->quality != quality || st->init_flags != init_flags) {
|
||||
wl_xess_d3d12_init_t ip;
|
||||
memset(&ip, 0, sizeof ip);
|
||||
ip.outputResolution.x = f->output_w;
|
||||
ip.outputResolution.y = f->output_h;
|
||||
ip.qualitySetting = quality;
|
||||
ip.initFlags = init_flags;
|
||||
ip.creationNodeMask = 1u;
|
||||
ip.visibleNodeMask = 1u;
|
||||
int32_t rc = g_wl_xess3_api.D3D12Init(st->ctx, &ip);
|
||||
if (rc < 0) {
|
||||
wl_xess3_destroy(st);
|
||||
wl_xess3_mark_fail(st, 4u, rc);
|
||||
return 0;
|
||||
}
|
||||
st->initialized = 1;
|
||||
st->out_w = f->output_w;
|
||||
st->out_h = f->output_h;
|
||||
st->quality = quality;
|
||||
st->init_flags = init_flags;
|
||||
st->last_mv_sx = 1e9f;
|
||||
st->last_mv_sy = 1e9f;
|
||||
}
|
||||
|
||||
if (g_wl_xess3_api.SetVelocityScale && (st->last_mv_sx != f->mv_scale_x || st->last_mv_sy != f->mv_scale_y)) {
|
||||
g_wl_xess3_api.SetVelocityScale(st->ctx, f->mv_scale_x, f->mv_scale_y);
|
||||
st->last_mv_sx = f->mv_scale_x;
|
||||
st->last_mv_sy = f->mv_scale_y;
|
||||
}
|
||||
|
||||
wl_xess_d3d12_exec_t ep;
|
||||
memset(&ep, 0, sizeof ep);
|
||||
ep.pColorTexture = res_col;
|
||||
ep.pVelocityTexture = res_mv;
|
||||
ep.pDepthTexture = res_dep;
|
||||
ep.pOutputTexture = res_out;
|
||||
ep.jitterOffsetX = f->jitter_x;
|
||||
ep.jitterOffsetY = f->jitter_y;
|
||||
ep.exposureScale = (f->pre_exposure > 0.0f) ? f->pre_exposure : 1.0f;
|
||||
ep.resetHistory = (f->flags & WLFSR4_FLAG_RESET) ? 1u : 0u;
|
||||
ep.inputWidth = f->render_w;
|
||||
ep.inputHeight = f->render_h;
|
||||
|
||||
// Bracket with Vulkan timestamp telemetry if interop is available
|
||||
if (seam && seam->ready && interop) {
|
||||
void *vk_cb = NULL;
|
||||
void *cl_used = NULL;
|
||||
if (wl_vkd3d_begin_cb(interop, d3d12_cmdlist, &vk_cb, &cl_used)) {
|
||||
wl_seam_telemetry_begin(seam, (VkCommandBuffer)vk_cb);
|
||||
wl_vkd3d_end_cb(interop, d3d12_cmdlist, cl_used);
|
||||
}
|
||||
}
|
||||
|
||||
LARGE_INTEGER t0, t1, freq;
|
||||
QueryPerformanceFrequency(&freq);
|
||||
QueryPerformanceCounter(&t0);
|
||||
|
||||
int32_t rc = g_wl_xess3_api.D3D12Execute(st->ctx, d3d12_cmdlist, &ep);
|
||||
|
||||
QueryPerformanceCounter(&t1);
|
||||
uint32_t cpu_us = (freq.QuadPart > 0) ? (uint32_t)(((t1.QuadPart - t0.QuadPart) * 1000000ULL) / (uint64_t)freq.QuadPart) : 0u;
|
||||
|
||||
if (rc < 0) {
|
||||
wl_xess3_destroy(st);
|
||||
wl_xess3_mark_fail(st, 5u, rc);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (seam && seam->ready && interop) {
|
||||
void *vk_cb = NULL;
|
||||
void *cl_used = NULL;
|
||||
if (wl_vkd3d_begin_cb(interop, d3d12_cmdlist, &vk_cb, &cl_used)) {
|
||||
wl_seam_telemetry_end(seam, (VkCommandBuffer)vk_cb, f, cpu_us);
|
||||
wl_vkd3d_end_cb(interop, d3d12_cmdlist, cl_used);
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,825 @@
|
||||
// Winlator Ludashi Intel XeSS (libxess.dll) -> AMD FSR 4 INT8 Hexagon HTP NPU Bridge
|
||||
//
|
||||
// Implements the full Intel XeSS 1.3 / 2.0 C ABI for BOTH:
|
||||
// - DirectX 12 (via vkd3d-proton ID3D12DXVKInteropDevice1 zero-copy interop)
|
||||
// - Vulkan (direct VkImage / VkCommandBuffer)
|
||||
//
|
||||
// Requires ZERO GPU spoofing and ZERO driver signature checks — works cleanly on
|
||||
// Adreno / Turnip in No-GPU-Spoof mode as well as RTX/RDNA4 spoof modes.
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "wl_seam_client.h"
|
||||
#include "wl_vkd3d_interop.h"
|
||||
#include "wl_xess3_direct.h"
|
||||
|
||||
// ---- Official Intel XeSS C ABI (verified from intel/xess xess.h, xess_d3d12.h, xess_vk.h) ----
|
||||
#pragma pack(push, 8)
|
||||
|
||||
typedef struct _xess_context_handle_t *xess_context_handle_t;
|
||||
|
||||
typedef struct _xess_version_t {
|
||||
uint16_t major;
|
||||
uint16_t minor;
|
||||
uint16_t patch;
|
||||
uint16_t reserved;
|
||||
} xess_version_t;
|
||||
|
||||
typedef struct _xess_2d_t {
|
||||
uint32_t x;
|
||||
uint32_t y;
|
||||
} xess_2d_t;
|
||||
|
||||
typedef xess_2d_t xess_coord_t;
|
||||
|
||||
typedef enum _xess_quality_settings_t {
|
||||
XESS_QUALITY_SETTING_ULTRA_PERFORMANCE = 100,
|
||||
XESS_QUALITY_SETTING_PERFORMANCE = 101,
|
||||
XESS_QUALITY_SETTING_BALANCED = 102,
|
||||
XESS_QUALITY_SETTING_QUALITY = 103,
|
||||
XESS_QUALITY_SETTING_ULTRA_QUALITY = 104,
|
||||
XESS_QUALITY_SETTING_ULTRA_QUALITY_PLUS = 105,
|
||||
XESS_QUALITY_SETTING_AA = 106,
|
||||
} xess_quality_settings_t;
|
||||
|
||||
typedef enum _xess_init_flags_t {
|
||||
XESS_INIT_FLAG_NONE = 0,
|
||||
XESS_INIT_FLAG_HIGH_RES_MV = 1 << 0,
|
||||
XESS_INIT_FLAG_INVERTED_DEPTH = 1 << 1,
|
||||
XESS_INIT_FLAG_EXPOSURE_SCALE_TEXTURE = 1 << 2,
|
||||
XESS_INIT_FLAG_RESPONSIVE_PIXEL_MASK = 1 << 3,
|
||||
XESS_INIT_FLAG_USE_NDC_VELOCITY = 1 << 4,
|
||||
XESS_INIT_FLAG_EXTERNAL_DESCRIPTOR_HEAP = 1 << 5,
|
||||
XESS_INIT_FLAG_LDR_INPUT_COLOR = 1 << 6,
|
||||
XESS_INIT_FLAG_JITTERED_MV = 1 << 7,
|
||||
XESS_INIT_FLAG_ENABLE_AUTOEXPOSURE = 1 << 8,
|
||||
} xess_init_flags_t;
|
||||
|
||||
typedef struct _xess_properties_t {
|
||||
uint32_t requiredDescriptorCount;
|
||||
uint64_t tempBufferHeapSize;
|
||||
uint64_t tempTextureHeapSize;
|
||||
} xess_properties_t;
|
||||
|
||||
typedef enum _xess_result_t {
|
||||
XESS_RESULT_WARNING_NONEXISTING_FOLDER = 1,
|
||||
XESS_RESULT_WARNING_OLD_DRIVER = 2,
|
||||
XESS_RESULT_SUCCESS = 0,
|
||||
XESS_RESULT_ERROR_UNSUPPORTED_DEVICE = -1,
|
||||
XESS_RESULT_ERROR_UNSUPPORTED_DRIVER = -2,
|
||||
XESS_RESULT_ERROR_UNINITIALIZED = -3,
|
||||
XESS_RESULT_ERROR_INVALID_ARGUMENT = -4,
|
||||
XESS_RESULT_ERROR_DEVICE_OUT_OF_MEMORY = -5,
|
||||
XESS_RESULT_ERROR_DEVICE = -6,
|
||||
XESS_RESULT_ERROR_NOT_IMPLEMENTED = -7,
|
||||
XESS_RESULT_ERROR_INVALID_CONTEXT = -8,
|
||||
XESS_RESULT_ERROR_OPERATION_IN_PROGRESS = -9,
|
||||
XESS_RESULT_ERROR_UNSUPPORTED = -10,
|
||||
XESS_RESULT_ERROR_CANT_LOAD_LIBRARY = -11,
|
||||
XESS_RESULT_ERROR_WRONG_CALL_ORDER = -12,
|
||||
XESS_RESULT_ERROR_UNKNOWN = -1000,
|
||||
} xess_result_t;
|
||||
|
||||
typedef enum _xess_logging_level_t {
|
||||
XESS_LOGGING_LEVEL_DEBUG = 0,
|
||||
XESS_LOGGING_LEVEL_INFO = 1,
|
||||
XESS_LOGGING_LEVEL_WARNING = 2,
|
||||
XESS_LOGGING_LEVEL_ERROR = 3,
|
||||
} xess_logging_level_t;
|
||||
|
||||
typedef void (*xess_app_log_callback_t)(const char *message, xess_logging_level_t loggingLevel);
|
||||
|
||||
typedef struct _xess_d3d12_execute_params_t {
|
||||
void *pColorTexture;
|
||||
void *pVelocityTexture;
|
||||
void *pDepthTexture;
|
||||
void *pExposureScaleTexture;
|
||||
void *pResponsivePixelMaskTexture;
|
||||
void *pOutputTexture;
|
||||
float jitterOffsetX;
|
||||
float jitterOffsetY;
|
||||
float exposureScale;
|
||||
uint32_t resetHistory;
|
||||
uint32_t inputWidth;
|
||||
uint32_t inputHeight;
|
||||
xess_coord_t inputColorBase;
|
||||
xess_coord_t inputMotionVectorBase;
|
||||
xess_coord_t inputDepthBase;
|
||||
xess_coord_t inputResponsiveMaskBase;
|
||||
xess_coord_t reserved0;
|
||||
xess_coord_t outputColorBase;
|
||||
void *pDescriptorHeap;
|
||||
uint32_t descriptorHeapOffset;
|
||||
} xess_d3d12_execute_params_t;
|
||||
|
||||
typedef struct _xess_d3d12_init_params_t {
|
||||
xess_2d_t outputResolution;
|
||||
xess_quality_settings_t qualitySetting;
|
||||
uint32_t initFlags;
|
||||
uint32_t creationNodeMask;
|
||||
uint32_t visibleNodeMask;
|
||||
void *pTempBufferHeap;
|
||||
uint64_t bufferHeapOffset;
|
||||
void *pTempTextureHeap;
|
||||
uint64_t textureHeapOffset;
|
||||
void *pPipelineLibrary;
|
||||
} xess_d3d12_init_params_t;
|
||||
|
||||
typedef struct _wl_vk_subresource_range {
|
||||
uint32_t aspectMask;
|
||||
uint32_t baseMipLevel;
|
||||
uint32_t levelCount;
|
||||
uint32_t baseArrayLayer;
|
||||
uint32_t layerCount;
|
||||
} WlVkSubresourceRange;
|
||||
|
||||
typedef struct _xess_vk_image_view_info {
|
||||
VkImageView imageView;
|
||||
VkImage image;
|
||||
WlVkSubresourceRange subresourceRange;
|
||||
uint32_t format;
|
||||
unsigned int width;
|
||||
unsigned int height;
|
||||
} xess_vk_image_view_info;
|
||||
|
||||
typedef struct _xess_vk_execute_params_t {
|
||||
xess_vk_image_view_info colorTexture;
|
||||
xess_vk_image_view_info velocityTexture;
|
||||
xess_vk_image_view_info depthTexture;
|
||||
xess_vk_image_view_info exposureScaleTexture;
|
||||
xess_vk_image_view_info responsivePixelMaskTexture;
|
||||
xess_vk_image_view_info outputTexture;
|
||||
float jitterOffsetX;
|
||||
float jitterOffsetY;
|
||||
float exposureScale;
|
||||
uint32_t resetHistory;
|
||||
uint32_t inputWidth;
|
||||
uint32_t inputHeight;
|
||||
xess_coord_t inputColorBase;
|
||||
xess_coord_t inputMotionVectorBase;
|
||||
xess_coord_t inputDepthBase;
|
||||
xess_coord_t inputResponsiveMaskBase;
|
||||
xess_coord_t reserved0;
|
||||
xess_coord_t outputColorBase;
|
||||
} xess_vk_execute_params_t;
|
||||
|
||||
typedef struct _xess_vk_init_params_t {
|
||||
xess_2d_t outputResolution;
|
||||
xess_quality_settings_t qualitySetting;
|
||||
uint32_t initFlags;
|
||||
uint32_t creationNodeMask;
|
||||
uint32_t visibleNodeMask;
|
||||
VkDeviceMemory tempBufferHeap;
|
||||
uint64_t bufferHeapOffset;
|
||||
VkDeviceMemory tempTextureHeap;
|
||||
uint64_t textureHeapOffset;
|
||||
uint64_t pipelineCache;
|
||||
} xess_vk_init_params_t;
|
||||
|
||||
#pragma pack(pop)
|
||||
|
||||
// Compile-time ABI sanity checks
|
||||
_Static_assert(sizeof(xess_quality_settings_t) == 4, "xess_quality_settings_t size");
|
||||
_Static_assert(sizeof(xess_init_flags_t) == 4, "xess_init_flags_t size");
|
||||
_Static_assert(sizeof(xess_result_t) == 4, "xess_result_t size");
|
||||
_Static_assert(sizeof(xess_properties_t) == 24, "xess_properties_t size");
|
||||
_Static_assert(sizeof(xess_vk_image_view_info) == 48, "xess_vk_image_view_info size");
|
||||
|
||||
// ---- Internal context ----
|
||||
#define WL_XESS_MAGIC 0x58455353u /* "XESS" */
|
||||
|
||||
typedef struct WlXessCtx {
|
||||
uint32_t magic;
|
||||
int is_vk;
|
||||
int initialized;
|
||||
int pipelines_built;
|
||||
int needs_reset;
|
||||
int force_legacy_scales;
|
||||
|
||||
xess_2d_t out_res;
|
||||
xess_quality_settings_t quality;
|
||||
uint32_t init_flags;
|
||||
xess_d3d12_init_params_t d3d12_init;
|
||||
xess_vk_init_params_t vk_init;
|
||||
|
||||
float jitter_scale_x;
|
||||
float jitter_scale_y;
|
||||
float vel_scale_x;
|
||||
float vel_scale_y;
|
||||
float exposure_mult;
|
||||
float max_responsive_mask;
|
||||
|
||||
WlSeamClient seam;
|
||||
WlID3D12DXVKInteropDevice1 *dx12_interop;
|
||||
void *d3d12_dev;
|
||||
WlXess3State xess3;
|
||||
} WlXessCtx;
|
||||
|
||||
static WlXessCtx *xess_unwrap(xess_context_handle_t h) {
|
||||
if (!h) return NULL;
|
||||
WlXessCtx *c = (WlXessCtx *)h;
|
||||
return (c->magic == WL_XESS_MAGIC) ? c : NULL;
|
||||
}
|
||||
|
||||
static float xess_quality_ratio(xess_quality_settings_t q, int legacy) {
|
||||
(void)legacy;
|
||||
switch (q) {
|
||||
case XESS_QUALITY_SETTING_ULTRA_PERFORMANCE: return 3.0f;
|
||||
case XESS_QUALITY_SETTING_PERFORMANCE: return 2.0f;
|
||||
case XESS_QUALITY_SETTING_BALANCED: return 1.7f;
|
||||
case XESS_QUALITY_SETTING_QUALITY: return 1.5f;
|
||||
case XESS_QUALITY_SETTING_ULTRA_QUALITY: return 1.3f;
|
||||
case XESS_QUALITY_SETTING_ULTRA_QUALITY_PLUS: return 1.3f;
|
||||
case XESS_QUALITY_SETTING_AA: return 1.0f;
|
||||
default: return 1.7f;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t xess_quality_to_wl(xess_quality_settings_t q) {
|
||||
switch (q) {
|
||||
case XESS_QUALITY_SETTING_ULTRA_PERFORMANCE: return WLFSR4_QUALITY_ULTRA_PERF;
|
||||
case XESS_QUALITY_SETTING_PERFORMANCE: return WLFSR4_QUALITY_PERF;
|
||||
case XESS_QUALITY_SETTING_BALANCED: return WLFSR4_QUALITY_BALANCED;
|
||||
case XESS_QUALITY_SETTING_QUALITY: return WLFSR4_QUALITY_QUALITY;
|
||||
case XESS_QUALITY_SETTING_ULTRA_QUALITY:
|
||||
case XESS_QUALITY_SETTING_ULTRA_QUALITY_PLUS: return WLFSR4_QUALITY_ULTRA_QUAL;
|
||||
case XESS_QUALITY_SETTING_AA: return WLFSR4_QUALITY_NATIVE_AA;
|
||||
default: return WLFSR4_QUALITY_AUTO;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t xess_flags_to_wl(uint32_t xflags) {
|
||||
uint32_t f = 0;
|
||||
if (!(xflags & XESS_INIT_FLAG_LDR_INPUT_COLOR)) f |= WLFSR4_FLAG_HDR;
|
||||
if (xflags & XESS_INIT_FLAG_INVERTED_DEPTH) f |= WLFSR4_FLAG_DEPTH_INVERTED;
|
||||
if (xflags & XESS_INIT_FLAG_HIGH_RES_MV) f |= WLFSR4_FLAG_DISPLAY_RES_MV;
|
||||
if (xflags & XESS_INIT_FLAG_JITTERED_MV) f |= WLFSR4_FLAG_MV_JITTERED;
|
||||
if (xflags & XESS_INIT_FLAG_ENABLE_AUTOEXPOSURE) f |= WLFSR4_FLAG_AUTO_EXPOSURE;
|
||||
return f;
|
||||
}
|
||||
|
||||
static void xess_fill_dx12_ref(WlID3D12DXVKInteropDevice1 *interop, WlFsr4ImageRef *dst,
|
||||
void *d3d12_res, uint32_t d3d12_state, uint32_t w, uint32_t h, int is_depth) {
|
||||
memset(dst, 0, sizeof *dst);
|
||||
if (!interop || !d3d12_res) return;
|
||||
UINT64 vk_img = 0, off = 0;
|
||||
UINT32 vk_fmt = 0;
|
||||
if (wl_vkd3d_resource_info(interop, d3d12_res, &vk_img, &off, &vk_fmt) == S_OK && vk_img) {
|
||||
UINT32 layout = (d3d12_state == 0x8u) ? 1u : (is_depth ? 4u : 5u);
|
||||
if (interop->lpVtbl->GetVulkanImageLayout) {
|
||||
UINT32 queried = 0;
|
||||
interop->lpVtbl->GetVulkanImageLayout(interop, d3d12_res, d3d12_state, &queried);
|
||||
if (queried != 0) layout = queried;
|
||||
}
|
||||
dst->vk_image = vk_img;
|
||||
dst->vk_format = vk_fmt;
|
||||
dst->vk_layout = layout;
|
||||
dst->width = w;
|
||||
dst->height = h;
|
||||
dst->aspect = is_depth ? 2u : 1u;
|
||||
}
|
||||
}
|
||||
|
||||
static void xess_fill_vk_ref(WlFsr4ImageRef *dst, const xess_vk_image_view_info *src,
|
||||
uint32_t layout, uint32_t fallback_w, uint32_t fallback_h, int is_depth) {
|
||||
memset(dst, 0, sizeof *dst);
|
||||
if (!src || !src->image) return;
|
||||
dst->vk_image = src->image;
|
||||
dst->vk_view = src->imageView;
|
||||
dst->vk_format = src->format;
|
||||
dst->vk_layout = layout;
|
||||
dst->width = src->width ? src->width : fallback_w;
|
||||
dst->height = src->height ? src->height : fallback_h;
|
||||
dst->aspect = src->subresourceRange.aspectMask ? src->subresourceRange.aspectMask : (is_depth ? 2u : 1u);
|
||||
}
|
||||
|
||||
// ---- Core XeSS Exports ----
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetVersion(xess_version_t *pVersion) {
|
||||
if (!pVersion) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
pVersion->major = 1;
|
||||
pVersion->minor = 3;
|
||||
pVersion->patch = 1;
|
||||
pVersion->reserved = 0;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetIntelXeFXVersion(xess_context_handle_t hContext, xess_version_t *pVersion) {
|
||||
(void)hContext;
|
||||
if (!pVersion) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
pVersion->major = 0;
|
||||
pVersion->minor = 0;
|
||||
pVersion->patch = 0;
|
||||
pVersion->reserved = 0;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessIsOptimalDriver(xess_context_handle_t hContext) {
|
||||
(void)hContext;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessSetLoggingCallback(xess_context_handle_t hContext,
|
||||
xess_logging_level_t loggingLevel,
|
||||
xess_app_log_callback_t loggingCallback) {
|
||||
(void)hContext; (void)loggingLevel; (void)loggingCallback;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetProperties(xess_context_handle_t hContext,
|
||||
const xess_2d_t *pOutputResolution,
|
||||
xess_properties_t *pBindingProperties) {
|
||||
(void)hContext; (void)pOutputResolution;
|
||||
if (!pBindingProperties) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
pBindingProperties->requiredDescriptorCount = 1;
|
||||
pBindingProperties->tempBufferHeapSize = 65536;
|
||||
pBindingProperties->tempTextureHeapSize = 65536;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetInputResolution(xess_context_handle_t hContext,
|
||||
const xess_2d_t *pOutputResolution,
|
||||
xess_quality_settings_t qualitySettings,
|
||||
xess_2d_t *pInputResolution) {
|
||||
if (!pOutputResolution || !pInputResolution) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
float r = xess_quality_ratio(qualitySettings, c ? c->force_legacy_scales : 0);
|
||||
uint32_t w = (uint32_t)((float)pOutputResolution->x / r);
|
||||
uint32_t h = (uint32_t)((float)pOutputResolution->y / r);
|
||||
if (w < 16) w = 16;
|
||||
if (h < 16) h = 16;
|
||||
pInputResolution->x = w;
|
||||
pInputResolution->y = h;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetOptimalInputResolution(xess_context_handle_t hContext,
|
||||
const xess_2d_t *pOutputResolution,
|
||||
xess_quality_settings_t qualitySettings,
|
||||
xess_2d_t *pInputResolutionOptimal,
|
||||
xess_2d_t *pInputResolutionMin,
|
||||
xess_2d_t *pInputResolutionMax) {
|
||||
if (!pOutputResolution || !pInputResolutionOptimal) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
float r = xess_quality_ratio(qualitySettings, c ? c->force_legacy_scales : 0);
|
||||
uint32_t w = (uint32_t)((float)pOutputResolution->x / r);
|
||||
uint32_t h = (uint32_t)((float)pOutputResolution->y / r);
|
||||
if (w < 16) w = 16;
|
||||
if (h < 16) h = 16;
|
||||
pInputResolutionOptimal->x = w;
|
||||
pInputResolutionOptimal->y = h;
|
||||
if (pInputResolutionMin) {
|
||||
pInputResolutionMin->x = (uint32_t)((float)pOutputResolution->x / 3.0f);
|
||||
pInputResolutionMin->y = (uint32_t)((float)pOutputResolution->y / 3.0f);
|
||||
}
|
||||
if (pInputResolutionMax) {
|
||||
pInputResolutionMax->x = pOutputResolution->x;
|
||||
pInputResolutionMax->y = pOutputResolution->y;
|
||||
}
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetJitterScale(xess_context_handle_t hContext, float *pX, float *pY) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!pX || !pY) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
*pX = c->jitter_scale_x;
|
||||
*pY = c->jitter_scale_y;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessSetJitterScale(xess_context_handle_t hContext, float x, float y) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
c->jitter_scale_x = x;
|
||||
c->jitter_scale_y = y;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetVelocityScale(xess_context_handle_t hContext, float *pX, float *pY) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!pX || !pY) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
*pX = c->vel_scale_x;
|
||||
*pY = c->vel_scale_y;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessSetVelocityScale(xess_context_handle_t hContext, float x, float y) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
c->vel_scale_x = x;
|
||||
c->vel_scale_y = y;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessSetExposureMultiplier(xess_context_handle_t hContext, float scale) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
c->exposure_mult = scale > 0.0f ? scale : 1.0f;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetExposureMultiplier(xess_context_handle_t hContext, float *pScale) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!pScale) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
*pScale = c->exposure_mult;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessSetMaxResponsiveMaskValue(xess_context_handle_t hContext, float value) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (value < 0.0f || value > 1.0f) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
c->max_responsive_mask = value;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetMaxResponsiveMaskValue(xess_context_handle_t hContext, float *pValue) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!pValue) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
*pValue = c->max_responsive_mask;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessForceLegacyScaleFactors(xess_context_handle_t hContext, bool force) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
c->force_legacy_scales = force ? 1 : 0;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetPipelineBuildStatus(xess_context_handle_t hContext) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessDestroyContext(xess_context_handle_t hContext) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
wl_xess3_destroy(&c->xess3);
|
||||
wl_seam_destroy(&c->seam);
|
||||
if (c->dx12_interop) {
|
||||
c->dx12_interop->lpVtbl->Release(c->dx12_interop);
|
||||
c->dx12_interop = NULL;
|
||||
}
|
||||
c->magic = 0;
|
||||
free(c);
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
// Debug / optional exports
|
||||
__declspec(dllexport) xess_result_t xessSelectNetworkModel(xess_context_handle_t hContext, uint32_t network) {
|
||||
(void)hContext; (void)network;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessStartDump(xess_context_handle_t hContext, const void *dumpParams) {
|
||||
(void)hContext; (void)dumpParams;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessGetProfilingData(xess_context_handle_t hContext, void **pProfilingData) {
|
||||
(void)hContext;
|
||||
if (pProfilingData) *pProfilingData = NULL;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessD3D12GetProfilingData(xess_context_handle_t hContext, void **pProfilingData) {
|
||||
(void)hContext;
|
||||
if (pProfilingData) *pProfilingData = NULL;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessD3D12GetResourcesToDump(xess_context_handle_t hContext, void **pResourcesToDump) {
|
||||
(void)hContext;
|
||||
if (pResourcesToDump) *pResourcesToDump = NULL;
|
||||
return XESS_RESULT_ERROR_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessVKGetResourcesToDump(xess_context_handle_t hContext, void **pResourcesToDump) {
|
||||
(void)hContext;
|
||||
if (pResourcesToDump) *pResourcesToDump = NULL;
|
||||
return XESS_RESULT_ERROR_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessSetContextParameterF(xess_context_handle_t hContext, const char *name, float val) {
|
||||
(void)hContext; (void)name; (void)val;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
// ---- DirectX 12 XeSS Exports ----
|
||||
|
||||
__declspec(dllexport) xess_result_t xessD3D12CreateContext(void *pDevice, xess_context_handle_t *phContext) {
|
||||
if (!pDevice || !phContext) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
|
||||
WlXessCtx *c = (WlXessCtx *)calloc(1, sizeof *c);
|
||||
if (!c) return XESS_RESULT_ERROR_UNKNOWN;
|
||||
|
||||
c->magic = WL_XESS_MAGIC;
|
||||
c->is_vk = 0;
|
||||
c->needs_reset = 1;
|
||||
c->jitter_scale_x = 1.0f;
|
||||
c->jitter_scale_y = 1.0f;
|
||||
c->vel_scale_x = 1.0f;
|
||||
c->vel_scale_y = 1.0f;
|
||||
c->exposure_mult = 1.0f;
|
||||
c->max_responsive_mask = 1.0f;
|
||||
|
||||
c->d3d12_dev = pDevice;
|
||||
c->dx12_interop = wl_query_vkd3d_interop(pDevice);
|
||||
if (c->dx12_interop) {
|
||||
void *vk_inst = NULL, *vk_phys = NULL, *vk_dev = NULL;
|
||||
if (c->dx12_interop->lpVtbl->GetVulkanHandles(c->dx12_interop, &vk_inst, &vk_phys, &vk_dev) == S_OK && vk_dev) {
|
||||
wl_seam_init(&c->seam, vk_inst, vk_phys, vk_dev, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
*phContext = (xess_context_handle_t)c;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessD3D12BuildPipelines(xess_context_handle_t hContext,
|
||||
void *pPipelineLibrary,
|
||||
bool blocking,
|
||||
uint32_t initFlags) {
|
||||
(void)pPipelineLibrary; (void)blocking;
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
c->init_flags = initFlags;
|
||||
c->pipelines_built = 1;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessD3D12Init(xess_context_handle_t hContext,
|
||||
const xess_d3d12_init_params_t *pInitParams) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!pInitParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
c->d3d12_init = *pInitParams;
|
||||
c->out_res = pInitParams->outputResolution;
|
||||
c->quality = pInitParams->qualitySetting;
|
||||
c->init_flags = pInitParams->initFlags;
|
||||
c->initialized = 1;
|
||||
c->needs_reset = 1;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessD3D12GetInitParams(xess_context_handle_t hContext,
|
||||
xess_d3d12_init_params_t *pInitParams) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED;
|
||||
if (!pInitParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
*pInitParams = c->d3d12_init;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessD3D12Execute(xess_context_handle_t hContext,
|
||||
void *pCommandList,
|
||||
const xess_d3d12_execute_params_t *pExecParams) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED;
|
||||
if (!pCommandList || !pExecParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
if (!c->seam.ready || !c->dx12_interop) return XESS_RESULT_ERROR_UNINITIALIZED;
|
||||
|
||||
uint32_t out_w = c->out_res.x;
|
||||
uint32_t out_h = c->out_res.y;
|
||||
uint32_t in_w = pExecParams->inputWidth ? pExecParams->inputWidth : out_w;
|
||||
uint32_t in_h = pExecParams->inputHeight ? pExecParams->inputHeight : out_h;
|
||||
int high_res_mv = (c->init_flags & XESS_INIT_FLAG_HIGH_RES_MV) ? 1 : 0;
|
||||
|
||||
WlFsr4FrameDesc f;
|
||||
memset(&f, 0, sizeof f);
|
||||
f.render_w = in_w;
|
||||
f.render_h = in_h;
|
||||
f.output_w = out_w;
|
||||
f.output_h = out_h;
|
||||
f.jitter_x = pExecParams->jitterOffsetX * c->jitter_scale_x;
|
||||
f.jitter_y = pExecParams->jitterOffsetY * c->jitter_scale_y;
|
||||
|
||||
if (c->init_flags & XESS_INIT_FLAG_USE_NDC_VELOCITY) {
|
||||
float mv_w = high_res_mv ? (float)out_w : (float)in_w;
|
||||
float mv_h = high_res_mv ? (float)out_h : (float)in_h;
|
||||
f.mv_scale_x = mv_w * 0.5f * c->vel_scale_x;
|
||||
f.mv_scale_y = mv_h * -0.5f * c->vel_scale_y;
|
||||
} else {
|
||||
f.mv_scale_x = c->vel_scale_x;
|
||||
f.mv_scale_y = c->vel_scale_y;
|
||||
}
|
||||
|
||||
float exp_s = pExecParams->exposureScale > 0.0f ? pExecParams->exposureScale : 1.0f;
|
||||
f.pre_exposure = exp_s * c->exposure_mult;
|
||||
f.flags = xess_flags_to_wl(c->init_flags);
|
||||
if (pExecParams->resetHistory || c->needs_reset) {
|
||||
f.flags |= WLFSR4_FLAG_RESET;
|
||||
c->needs_reset = 0;
|
||||
}
|
||||
f.api_source = WLFSR4_API_XESS_DX12;
|
||||
f.quality_mode = xess_quality_to_wl(c->quality);
|
||||
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
|
||||
|
||||
// XeSS DX12 contract: inputs are NON_PIXEL_SHADER_RESOURCE (0x40), output is UNORDERED_ACCESS (0x8)
|
||||
xess_fill_dx12_ref(c->dx12_interop, &f.color, pExecParams->pColorTexture, 0x40u, in_w, in_h, 0);
|
||||
xess_fill_dx12_ref(c->dx12_interop, &f.depth, pExecParams->pDepthTexture, 0x40u, in_w, in_h, 1);
|
||||
xess_fill_dx12_ref(c->dx12_interop, &f.motion, pExecParams->pVelocityTexture, 0x40u,
|
||||
high_res_mv ? out_w : in_w, high_res_mv ? out_h : in_h, 0);
|
||||
xess_fill_dx12_ref(c->dx12_interop, &f.output, pExecParams->pOutputTexture, 0x8u, out_w, out_h, 0);
|
||||
|
||||
int live_en = 1;
|
||||
int live_backend = wl_seam_live_backend(&c->seam, &live_en);
|
||||
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU && c->d3d12_dev) {
|
||||
if (wl_xess3_eval_d3d12(&c->xess3, &c->seam, c->dx12_interop, c->d3d12_dev, pCommandList,
|
||||
&f, pExecParams->pColorTexture, pExecParams->pDepthTexture,
|
||||
pExecParams->pVelocityTexture, pExecParams->pOutputTexture)) {
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
wl_xess3_tag_fallback(&c->xess3, &f);
|
||||
} else {
|
||||
wl_xess3_on_inactive(&c->xess3);
|
||||
}
|
||||
|
||||
void *vk_cb = NULL;
|
||||
int ok = 0;
|
||||
void *cl_used = NULL;
|
||||
if (wl_vkd3d_begin_cb(c->dx12_interop, pCommandList, &vk_cb, &cl_used)) {
|
||||
ok = wl_seam_dispatch_or_blit(&c->seam, (VkCommandBuffer)vk_cb, &f);
|
||||
wl_vkd3d_end_cb(c->dx12_interop, pCommandList, cl_used);
|
||||
}
|
||||
|
||||
return ok ? XESS_RESULT_SUCCESS : XESS_RESULT_ERROR_DEVICE;
|
||||
}
|
||||
|
||||
// ---- Vulkan XeSS Exports ----
|
||||
|
||||
__declspec(dllexport) xess_result_t xessVKGetRequiredInstanceExtensions(uint32_t *instanceExtensionsCount,
|
||||
const char *const **instanceExtensions,
|
||||
uint32_t *minVkApiVersion) {
|
||||
if (instanceExtensionsCount) *instanceExtensionsCount = 0;
|
||||
if (instanceExtensions) *instanceExtensions = NULL;
|
||||
if (minVkApiVersion) *minVkApiVersion = (1u << 22) | (1u << 12); /* VK_API_VERSION_1_1 */
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessVKGetRequiredDeviceExtensions(VkInstance instance,
|
||||
VkPhysicalDevice physicalDevice,
|
||||
uint32_t *deviceExtensionsCount,
|
||||
const char *const **deviceExtensions) {
|
||||
(void)instance; (void)physicalDevice;
|
||||
if (deviceExtensionsCount) *deviceExtensionsCount = 0;
|
||||
if (deviceExtensions) *deviceExtensions = NULL;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessVKGetRequiredDeviceFeatures(VkInstance instance,
|
||||
VkPhysicalDevice physicalDevice,
|
||||
void **features) {
|
||||
(void)instance; (void)physicalDevice; (void)features;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessVKCreateContext(VkInstance instance,
|
||||
VkPhysicalDevice physicalDevice,
|
||||
VkDevice device,
|
||||
xess_context_handle_t *phContext) {
|
||||
if (!device || !phContext) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
|
||||
WlXessCtx *c = (WlXessCtx *)calloc(1, sizeof *c);
|
||||
if (!c) return XESS_RESULT_ERROR_UNKNOWN;
|
||||
|
||||
c->magic = WL_XESS_MAGIC;
|
||||
c->is_vk = 1;
|
||||
c->needs_reset = 1;
|
||||
c->jitter_scale_x = 1.0f;
|
||||
c->jitter_scale_y = 1.0f;
|
||||
c->vel_scale_x = 1.0f;
|
||||
c->vel_scale_y = 1.0f;
|
||||
c->exposure_mult = 1.0f;
|
||||
c->max_responsive_mask = 1.0f;
|
||||
|
||||
wl_seam_init(&c->seam, instance, physicalDevice, device, NULL);
|
||||
|
||||
*phContext = (xess_context_handle_t)c;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessVKBuildPipelines(xess_context_handle_t hContext,
|
||||
uint64_t pipelineCache,
|
||||
bool blocking,
|
||||
uint32_t initFlags) {
|
||||
(void)pipelineCache; (void)blocking;
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
c->init_flags = initFlags;
|
||||
c->pipelines_built = 1;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessVKInit(xess_context_handle_t hContext,
|
||||
const xess_vk_init_params_t *pInitParams) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!pInitParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
c->vk_init = *pInitParams;
|
||||
c->out_res = pInitParams->outputResolution;
|
||||
c->quality = pInitParams->qualitySetting;
|
||||
c->init_flags = pInitParams->initFlags;
|
||||
c->initialized = 1;
|
||||
c->needs_reset = 1;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessVKGetInitParams(xess_context_handle_t hContext,
|
||||
xess_vk_init_params_t *pInitParams) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED;
|
||||
if (!pInitParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
*pInitParams = c->vk_init;
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
__declspec(dllexport) xess_result_t xessVKExecute(xess_context_handle_t hContext,
|
||||
VkCommandBuffer commandBuffer,
|
||||
const xess_vk_execute_params_t *pExecParams) {
|
||||
WlXessCtx *c = xess_unwrap(hContext);
|
||||
if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT;
|
||||
if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED;
|
||||
if (!commandBuffer || !pExecParams) return XESS_RESULT_ERROR_INVALID_ARGUMENT;
|
||||
if (!c->seam.ready) return XESS_RESULT_ERROR_UNINITIALIZED;
|
||||
|
||||
uint32_t out_w = c->out_res.x;
|
||||
uint32_t out_h = c->out_res.y;
|
||||
uint32_t in_w = pExecParams->inputWidth ? pExecParams->inputWidth : out_w;
|
||||
uint32_t in_h = pExecParams->inputHeight ? pExecParams->inputHeight : out_h;
|
||||
int high_res_mv = (c->init_flags & XESS_INIT_FLAG_HIGH_RES_MV) ? 1 : 0;
|
||||
|
||||
WlFsr4FrameDesc f;
|
||||
memset(&f, 0, sizeof f);
|
||||
f.render_w = in_w;
|
||||
f.render_h = in_h;
|
||||
f.output_w = out_w;
|
||||
f.output_h = out_h;
|
||||
f.jitter_x = pExecParams->jitterOffsetX * c->jitter_scale_x;
|
||||
f.jitter_y = pExecParams->jitterOffsetY * c->jitter_scale_y;
|
||||
|
||||
if (c->init_flags & XESS_INIT_FLAG_USE_NDC_VELOCITY) {
|
||||
float mv_w = high_res_mv ? (float)out_w : (float)in_w;
|
||||
float mv_h = high_res_mv ? (float)out_h : (float)in_h;
|
||||
f.mv_scale_x = mv_w * 0.5f * c->vel_scale_x;
|
||||
f.mv_scale_y = mv_h * -0.5f * c->vel_scale_y;
|
||||
} else {
|
||||
f.mv_scale_x = c->vel_scale_x;
|
||||
f.mv_scale_y = c->vel_scale_y;
|
||||
}
|
||||
|
||||
float exp_s = pExecParams->exposureScale > 0.0f ? pExecParams->exposureScale : 1.0f;
|
||||
f.pre_exposure = exp_s * c->exposure_mult;
|
||||
f.flags = xess_flags_to_wl(c->init_flags);
|
||||
if (pExecParams->resetHistory || c->needs_reset) {
|
||||
f.flags |= WLFSR4_FLAG_RESET;
|
||||
c->needs_reset = 0;
|
||||
}
|
||||
f.api_source = WLFSR4_API_XESS_VK;
|
||||
f.quality_mode = xess_quality_to_wl(c->quality);
|
||||
if (f.quality_mode == WLFSR4_QUALITY_ULTRA_PERF) f.preset_hint = WLFSR4_PRESET_ULTRAPERF;
|
||||
|
||||
// XeSS VK contract: inputs in SHADER_READ_ONLY_OPTIMAL (5), output in GENERAL (1)
|
||||
xess_fill_vk_ref(&f.color, &pExecParams->colorTexture, 5u, in_w, in_h, 0);
|
||||
xess_fill_vk_ref(&f.depth, &pExecParams->depthTexture, 5u, in_w, in_h, 1);
|
||||
xess_fill_vk_ref(&f.motion, &pExecParams->velocityTexture, 5u,
|
||||
high_res_mv ? out_w : in_w, high_res_mv ? out_h : in_h, 0);
|
||||
xess_fill_vk_ref(&f.output, &pExecParams->outputTexture, 1u, out_w, out_h, 0);
|
||||
|
||||
int live_en = 1;
|
||||
int live_backend = wl_seam_live_backend(&c->seam, &live_en);
|
||||
if (live_en && live_backend == WL_FSR_BACKEND_XESS3_GPU) {
|
||||
wl_xess_vk_img_t x_col, x_dep, x_mv, x_out;
|
||||
memcpy(&x_col, &pExecParams->colorTexture, sizeof x_col);
|
||||
memcpy(&x_dep, &pExecParams->depthTexture, sizeof x_dep);
|
||||
memcpy(&x_mv, &pExecParams->velocityTexture, sizeof x_mv);
|
||||
memcpy(&x_out, &pExecParams->outputTexture, sizeof x_out);
|
||||
if (wl_xess3_eval_vk(&c->xess3, &c->seam, commandBuffer, &f, &x_col, &x_dep, &x_mv, &x_out)) {
|
||||
return XESS_RESULT_SUCCESS;
|
||||
}
|
||||
wl_xess3_tag_fallback(&c->xess3, &f);
|
||||
} else {
|
||||
wl_xess3_on_inactive(&c->xess3);
|
||||
}
|
||||
|
||||
int ok = wl_seam_dispatch_or_blit(&c->seam, commandBuffer, &f);
|
||||
return ok ? XESS_RESULT_SUCCESS : XESS_RESULT_ERROR_DEVICE;
|
||||
}
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
|
||||
(void)hinst; (void)reason; (void)reserved;
|
||||
return TRUE;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
|
||||
# VK_LAYER_DROIDDECK_upscale for the APK (bionic, arm64-v8a). Added from app/src/main/cpp/CMakeLists.txt.
|
||||
# The glibc build for the PRoot guest is build-glibc.sh.
|
||||
add_library(VkLayer_droiddeck_upscale SHARED
|
||||
fsr4_layer.c
|
||||
fsr4_pipeline.c
|
||||
fsr4_builtin.c
|
||||
fsr412_lite.c
|
||||
fsr411_full_gpu.c
|
||||
fsr3_gpu.c
|
||||
sgsr2_gpu.c
|
||||
fsr4_qnn.c
|
||||
)
|
||||
|
||||
target_include_directories(VkLayer_droiddeck_upscale PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
target_compile_definitions(VkLayer_droiddeck_upscale PRIVATE VK_USE_PLATFORM_ANDROID_KHR=1)
|
||||
|
||||
target_compile_options(VkLayer_droiddeck_upscale PRIVATE
|
||||
-O2
|
||||
-Wall
|
||||
-Wextra
|
||||
-Wno-unused-function
|
||||
-Wno-missing-field-initializers
|
||||
-fvisibility=hidden
|
||||
)
|
||||
|
||||
# -Bsymbolic keeps the exported vkGetInstanceProcAddr/vkGetDeviceProcAddr bound to this library even when
|
||||
# a libvulkan in the global scope exports the same names.
|
||||
target_link_options(VkLayer_droiddeck_upscale PRIVATE -Wl,-z,max-page-size=16384 -Wl,-Bsymbolic)
|
||||
|
||||
target_link_libraries(VkLayer_droiddeck_upscale android log dl m)
|
||||
@@ -0,0 +1,219 @@
|
||||
# VK_LAYER_DROIDDECK_upscale
|
||||
|
||||
A Vulkan layer that runs the upscaler calls of Windows games (FSR 4 / FSR 3 / FSR 2 through
|
||||
FidelityFX, DLSS through NGX, XeSS) on the device: on the Adreno GPU, or on the Snapdragon
|
||||
Hexagon NPU through Qualcomm QNN. The Windows side is a set of bridge DLLs
|
||||
(`amd_fidelityfx_*.dll`, `nvngx.dll`, `libxess.dll`, ...). They talk to this layer through two
|
||||
Vulkan buffers with magic sizes and a `vkCmdUpdateBuffer` doorbell (`fsr4_seam_proto.h`). That
|
||||
protocol, its buffer sizes, magic values and backend IDs are unchanged from upstream, so the
|
||||
upstream bridge DLLs work against this layer.
|
||||
|
||||
Layer name `VK_LAYER_DROIDDECK_upscale`, library `libVkLayer_droiddeck_upscale.so`, implicit layer.
|
||||
The manifest template `VK_LAYER_DROIDDECK_upscale.json` turns it on with `DROIDDECK_UPSCALE=1` and
|
||||
off with `DROIDDECK_UPSCALE_DISABLE=1`.
|
||||
|
||||
## Origin, credits, licence
|
||||
|
||||
GPL-3.0, like DroidDeck. Ported from `app/src/main/cpp/fsr4npu/` of
|
||||
[michaelisomer-cyber/Winlator-NeuralScale](https://github.com/michaelisomer-cyber/Winlator-NeuralScale)
|
||||
at commit `a0ab6b0f770e1a6786b4e68def46b4edb8baafd0`, updated to `71c140d9e5586f659251c3ebc602f2d21923655c`
|
||||
(upstream r5: full FSR 4.1 on the NPU, ghosting fix, S8/U8 Lite graphs, SGSR 2, D3D11 DLSS) (GPL-3.0).
|
||||
From r5 DroidDeck leaves out upstream's root-only parts (performance/thermal manager, GPU clock floor, bypass
|
||||
charging) and keeps its own NPU detection (`DROIDDECK_UPSCALE_NPU`, set by the app for any HTP generation it
|
||||
finds, including the phone's own QNN libraries) and Intel's XeSS 3. That project is a fork of
|
||||
[StevenMXZ/Winlator-Ludashi](https://github.com/StevenMXZ/Winlator-Ludashi). The first commit
|
||||
that adds this folder holds the upstream files unchanged; the DroidDeck changes are in the
|
||||
commits after it.
|
||||
|
||||
Work this code builds on, as credited upstream:
|
||||
|
||||
- AMD FidelityFX SDK (FSR 3.1, FSR 4.0.2, FSR 4.1.x): [GPUOpen FidelityFX-SDK](https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK)
|
||||
- Intel XeSS 3.0 SDK: [intel/xess](https://github.com/intel/xess)
|
||||
- FSR 4 Vulkan DP4a reference pipelines: [dvj5411/fsr4vk](https://github.com/dvj5411/fsr4vk), [zrprod9-cmyk/vela](https://github.com/zrprod9-cmyk/vela), [puzzled-pancake/fsr4-hexagon](https://github.com/puzzled-pancake/fsr4-hexagon)
|
||||
- RDR2 DLSS-gate byte patterns: OptiPatcher from [optiscaler/OptiScaler](https://github.com/optiscaler/OptiScaler)
|
||||
- QNN HTP runtime handling adapted from BananaNative's SM8850 runtime (per the upstream source comments)
|
||||
- Qualcomm QNN / QAIRT HTP runtime (Qualcomm AI Engine Direct SDK); `fsr4_qnn.h` is a clean-room
|
||||
declaration of the C ABI subset, no Qualcomm headers are used
|
||||
|
||||
## Files
|
||||
|
||||
| File | What |
|
||||
| --- | --- |
|
||||
| `fsr4_layer.c` | Loader interface, device/extension/feature injection, GPU/DLSS spoof, seam mailbox + doorbell, ctrl and status files |
|
||||
| `fsr4_pipeline.c/.h` | Backend dispatch and fallbacks, FSR 4.1.1 Full NPU (external pack) path |
|
||||
| `fsr4_builtin.c/.h` | FSR 4.0.2 INT8 on the NPU; no longer dispatched since r5 (full FSR 4.1 runs on the NPU instead) |
|
||||
| `fsr412_lite.c/.h` | FSR 4.1.2 Lite INT8, GPU DP4a or NPU |
|
||||
| `fsr411_full_gpu.c/.h` | FSR 4.1.1 Full INT8 on the GPU |
|
||||
| `fsr3_gpu.c/.h` | FSR 3.1 on the GPU, also the fallback for every other backend |
|
||||
| `sgsr2_gpu.c/.h` | Snapdragon Game Super Resolution 2 on the GPU (`sgsr2_*.spv`) |
|
||||
| `fsr4_qnn.c/.h` | QNN/FastRPC/AHardwareBuffer runtime; stubs only in glibc builds |
|
||||
| `fsr4_seam_proto.h` | Shared protocol with the Windows bridge DLLs (do not change) |
|
||||
| `fsr_gpu_timer.h` | GPU timestamp helper for the status file |
|
||||
| `dd_upscale_compat.h` | DroidDeck env lookup and logging (logcat, or stderr in glibc builds) |
|
||||
| `shaders/*.comp` | GLSL source of `fsr3_*.spv`, `fsr4_builtin_*.spv`, `fsr412_lite/lite_npu_{pack,unpack}.spv` |
|
||||
| `scripts/pack_*.py` | Build `fsr4_v07_i8.wpack` and `fsr412_lite/fsr412_lite_i8.wpack` from the AMD weights |
|
||||
| `CMakeLists.txt` | APK build (bionic), added from `app/src/main/cpp/CMakeLists.txt` |
|
||||
| `build-glibc.sh` | PRoot guest build (glibc), called by `tools/components/recipes/runtime.sh` |
|
||||
|
||||
## Builds
|
||||
|
||||
- APK (bionic, arm64-v8a, minSdk 26): Gradle's NDK build makes `libVkLayer_droiddeck_upscale.so`
|
||||
through `add_subdirectory(../../../../tools/upscale/layer upscale_layer)`. Links `android log dl m`,
|
||||
`-Wl,-z,max-page-size=16384 -Wl,-Bsymbolic`. The manifest's relative `library_path` is meant to be
|
||||
rewritten to the absolute path by the app.
|
||||
- PRoot guest (glibc): `tools/upscale/layer/build-glibc.sh OUT` (`CC`, default `aarch64-linux-gnu-gcc`;
|
||||
Vulkan headers from `VK_INCLUDE` or the NDK). Built with `-DDD_UPSCALE_NO_ANDROID`: no
|
||||
AHardwareBuffer, FastRPC, QNN or liblog (logs go to stderr). Every NPU init fails with
|
||||
`npu_unavailable` and the backends take their GPU fallbacks. `OUT` gets the library and a manifest
|
||||
with `library_path` `/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so`
|
||||
(override with `DD_UPSCALE_GUEST_LIB`). The runtime recipe installs both into
|
||||
`app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/`.
|
||||
- `-Bsymbolic` is needed in both builds: the layer exports `vkGetInstanceProcAddr`, and a
|
||||
`libvulkan` already in the global symbol scope would otherwise win the lookup (the loader then
|
||||
fails with `Failed to find 'vkCreateInstance'`).
|
||||
|
||||
## Environment
|
||||
|
||||
Each key is read as `DROIDDECK_UPSCALE_<KEY>` first, then `WINLATOR_FSR4_<KEY>`
|
||||
(`dd_upscale_compat.h`). Empty values count as unset.
|
||||
|
||||
| Key | Read at | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `DIR` (then `DM_FSR4_DIR`) | `fsr4_pipeline.c:566`, `:826` | Data dir (layout below). Unset: no backend can load its files, frames get a plain blit. No built-in fallback path |
|
||||
| `POWER` | `fsr4_pipeline.c:575`, `:830` | HTP power vote: `burst`, `turbo` (default), `balanced`/`nom`, `low` |
|
||||
| `BACKEND`, then `ENGINE` | `fsr4_layer.c:458` | Start backend (names under ctrl file). Unset: Auto |
|
||||
| `APP_DESCRIPTOR_BUFFER` | `fsr4_layer.c` `hide_app_descriptor_buffer` | `1` = let the game see `VK_EXT_descriptor_buffer`. Default: hidden from the game (the layer still uses it), because vkd3d-proton's own descriptor buffers make FSR 4.1.1 Full write a black frame on Turnip |
|
||||
| `FULL_ON_TURNIP` | `fsr4_pipeline.c` `full_black_here` | `1` = run FSR 4.1.1 Full on Turnip even when the game enabled descriptor buffers itself. Default: Lite stands in then |
|
||||
| `NPU_SYNC` | `fsr4_layer.c:462` | `1` = GPU waits for the NPU each frame. Anything else = async (default). `sync`/`true` also mean sync |
|
||||
| `NPU_CPU_WAIT` | `dd_upscale_compat.h` `dd_upscale_npu_gpu_wait` | Async only. `1`/`true` = the game's recording thread waits for the previous frame's NPU result (old behaviour). Default: the next frame's command buffer waits for it on the GPU, so recording never blocks |
|
||||
| `SHARPNESS` | `fsr4_layer.c:464` | RCAS 0.0-1.0, default 0.55 |
|
||||
| `PRESET` | `fsr4_pipeline.c:1239` | `ultraperf` or `performance` forces the preset; else from the game's quality mode / ratio |
|
||||
| `CTRL_FILE` | `fsr4_layer.c:472` | Live control file, format below |
|
||||
| `STATUS_FILE` | `fsr4_layer.c:526` | Live status file, format below |
|
||||
| `NATIVELIB_DIR` | `fsr4_qnn.c:311` | Folder with the Qualcomm host libraries (see NPU setup) |
|
||||
| `HTP_ARCH` | `fsr4_qnn.c:237` | Optional override of the HTP arch (`v79`, `v81`) used for the cache folder |
|
||||
| `SPOOF_DLSS` | `fsr4_layer.c:557`, `:583` | `1` = expose `VK_NVX_binary_import` / `VK_NVX_image_view_handle` (stub functions) and report an RTX 2060 vendorID/deviceID/name |
|
||||
| `GPU_SPOOF` | `fsr4_layer.c:570` | Words split by `,` `+` `;` or blanks: `rtx` / `rdna4` pick the reported GPU; `1` also rewrites driverID/driverName/driverInfo; `off`/`none`/`0` keep the real GPU even with `SPOOF_DLSS=1` |
|
||||
| `VRAM_OVERRIDE` | `fsr4_layer.c:757` | `1` = report `VRAM_MB` as the size of every device-local heap (and its budget). Off otherwise |
|
||||
| `VRAM_MB` (then `WRAPPER_VMEM_MAX_SIZE`) | `fsr4_layer.c:759` | Heap size in MB for `VRAM_OVERRIDE=1`, 512-65536 |
|
||||
| `RDR2_PATCH` | `fsr4_layer.c:235` | `1` = patch RDR2.exe's DLSS vendor checks in memory. Off otherwise (Arxan crashes after loading with it) |
|
||||
| `LOG` | `fsr4_qnn.c:145`, `fsr4_pipeline.c:443` | `2` = verbose QNN log and every NPU dispatch logged |
|
||||
| `JX`, `JY`, `MX`, `MY` | `fsr4_pipeline.c:1387`-`1390` | Debug: jitter and motion-vector scale multipliers for the external FSR 4.1.1 NPU pack, default 1 |
|
||||
|
||||
Not prefixed: `ADSP_LIBRARY_PATH` (read and, if `<DIR>/adsp` is missing from it, prepended by the
|
||||
layer, `fsr4_qnn.c:262`), `LD_LIBRARY_PATH` (searched for QNN libraries, `fsr4_qnn.c:303`).
|
||||
Upstream's `WINLATOR_FSR4_DISABLE_LAYER` only lived in its manifest; the C code never read it.
|
||||
Here the loader switch is `DROIDDECK_UPSCALE_DISABLE=1`.
|
||||
|
||||
Spoof examples: `SPOOF_DLSS=1` gives RTX 2060 IDs with the real driverID; add `GPU_SPOOF=1` for
|
||||
`VK_DRIVER_ID_NVIDIA_PROPRIETARY` too. `GPU_SPOOF=rdna4` gives Radeon RX 9070 XT IDs,
|
||||
`GPU_SPOOF=rdna4,1` adds the AMD driverID. Upstream rewrote the driverID whenever `GPU_SPOOF` was
|
||||
`rtx` or `rdna4`; here that needs the `1` word.
|
||||
|
||||
## Ctrl file (read)
|
||||
|
||||
`read_live_ctrl`, `fsr4_layer.c:454`-`505`. Re-read at most every 200 ms, when a doorbell arrives
|
||||
and at `vkCreateDevice`. One `key=value` per line; keys missing from the file keep their last value
|
||||
(first the env values):
|
||||
|
||||
```
|
||||
enabled=1 # 0, off..., false... = bypass (plain blit); anything else = on
|
||||
backend=fsr4_1_lite_gpu
|
||||
engine=fsr4_1_lite_gpu # same as backend=, upstream writes both
|
||||
npu_sync=async # 1, sync..., true... = sync; anything else = async
|
||||
sharpness=0.55 # clamped to 0..1
|
||||
```
|
||||
|
||||
Backend names, matched by prefix (`parse_backend_str` in `fsr4_layer.c`): `xess`/`xess3` = XeSS 3 DP4a (1,
|
||||
runs in the bridge), `fsr4_0_npu`/`fsr4_npu` = FSR 4.1 Full NPU (4; FSR 4.0.2 is gone since r5),
|
||||
`sgsr2`/`snapdragon`/`gsr2` = SGSR 2 (7), `fsr4_1_full_npu`/`412_full_npu` (4),
|
||||
`fsr4_1_full_gpu`/`412_full_gpu` (6), `fsr4_1_lite_gpu`/`412_lite_gpu` (5),
|
||||
`fsr4_1_lite_npu`/`412_lite_npu`/`fsr4`/`npu` (3), `fsr3`/`gpu` = FSR 3.1 GPU (0), `auto` or anything else =
|
||||
Auto (8).
|
||||
If the first line has none of these keys, it is a bare flag: containing `0`, `off` or `false` turns
|
||||
the upscaler off, anything else on.
|
||||
|
||||
## Status file (written)
|
||||
|
||||
`write_live_status`, `fsr4_layer.c:507`-`553`. Written to `<STATUS_FILE>.tmp`, then renamed over
|
||||
`STATUS_FILE`. At most every 250 ms unless enabled/backend/sync/NPU use/quality/render width
|
||||
changed; always at `vkCreateDevice`. Exactly these lines in this order:
|
||||
|
||||
```
|
||||
layer=1
|
||||
driver=<real GPU name>
|
||||
ahb=<pending|gpu_only|zc|staging|zc_avail|staging_avail|zc_pending|zc_failed>
|
||||
npu_state=<standby|ready|compiling|failed|cached|ready_to_compile|no_pack|fsr3_gpu|xess3_dp4a|fsr412_lite_gpu|fsr411_full_gpu|...>
|
||||
rdr2_patch=<none|partial|ok>
|
||||
engine=<fsr3|fsr4>
|
||||
backend=<fsr3_gpu|xess3_gpu|sgsr2_gpu|fsr4_1_lite_npu|fsr4_1_full_npu|fsr4_1_lite_gpu|fsr4_1_full_gpu|auto>
|
||||
backend_tag=<what really ran, e.g. FSR4.1-Lite-GPU (NPU fallback)>
|
||||
npu_sync=<sync|async>
|
||||
sharpness=<%.2f>
|
||||
enabled=<0|1>
|
||||
active=<0|1>
|
||||
npu=<0|1>
|
||||
api=<None|FSR 4 (Vulkan)|FSR 4 (DX12)|DLSS (Vulkan)|DLSS (DX12)|XeSS (Vulkan)|XeSS (DX12)|FSR 3 (...)|FSR 2 (...)>
|
||||
quality=<Native AA (DLAA)|Ultra Quality|Quality|Balanced|Performance|Ultra Performance|Auto>
|
||||
render=<w>x<h>
|
||||
output=<w>x<h>
|
||||
preset=<perf|ultraperf>
|
||||
gpu_us=<u32>
|
||||
htp_us=<u32>
|
||||
dispatches=<u64>
|
||||
reason=<ok|standby|bypass_off|ok_fsr3_gpu|missing_fsr3_shaders|npu_unavailable|...>
|
||||
ts_ms=<CLOCK_REALTIME ms>
|
||||
```
|
||||
|
||||
## Data dir (`DROIDDECK_UPSCALE_DIR`)
|
||||
|
||||
Same tree as upstream's `app/src/main/assets/fsr4/`. None of it is in this repo; it is installed at
|
||||
run time. Paths the layer opens, relative to the dir:
|
||||
|
||||
| Path | Used by | Built here? |
|
||||
| --- | --- | --- |
|
||||
| `fsr3_prepare.spv`, `fsr3_accumulate.spv`, `fsr3_rcas.spv` | FSR 3.1 GPU (`fsr3_gpu.c:343`, `:385`) | Source in `shaders/`. Upstream's files look like `glslc -O --target-env=vulkan1.1` output (Shaderc, SPIR-V 1.3); a local build of that is close in size, not byte-identical. Not built by the layer builds |
|
||||
| `fsr4_builtin_pre.spv`, `fsr4_builtin_post_a.spv`, `fsr4_builtin_post_b.spv` | FSR 4.0.2 NPU (`fsr4_builtin.c:560`, `:609`) | Source in `shaders/` |
|
||||
| `fsr4_v07_i8.wpack` | FSR 4.0.2 NPU graph (`fsr4_qnn.c:1583`) | `scripts/pack_fsr4_weights.py`, needs fsr4-hexagon and AMD weights |
|
||||
| `fsr412_lite/0000.spv` ... `0010.spv`, `0013.spv`, `weights.bin` | FSR 4.1.2 Lite (`fsr412_lite.c:410`, `:688`) | No: precompiled AMD FidelityFX SDK passes (per upstream) |
|
||||
| `fsr412_lite/lite_npu_pack.spv`, `lite_npu_unpack.spv` | Lite NPU (`fsr412_lite.c:618`) | Source in `shaders/` |
|
||||
| `fsr412_lite/fsr412_lite_i8.wpack` | Lite NPU graph (`fsr412_lite.c:456`) | `scripts/pack_fsr412_lite_weights.py`, needs vela + `weights.bin` |
|
||||
| `fsr411_full/{quality,performance}/pass-00.spv` ... `pass-27.spv`, `initializers.bin` | FSR 4.1.1 Full GPU (`fsr411_full_gpu.c:328`, `:346`) | No: precompiled AMD FidelityFX SDK passes (per upstream) |
|
||||
| `fsr411_full/performance/fsr411_full_zc_{s8,i8}.wpack` | FSR 4.1.1 Full NPU graph, S8 first then U8 (r5) | No (upstream `scripts/pack_fsr411_full_npu.py`) |
|
||||
| `fsr412_lite/fsr412_lite_zc_{s8,i8}.wpack` | FSR 4.1.2 Lite NPU graph, S8 first then U8 (r5) | No (upstream `scripts/build_fsr412_lite_tiers.py`) |
|
||||
| `sgsr2_convert.spv`, `sgsr2_activate.spv`, `sgsr2_upscale.spv` | SGSR 2 (`sgsr2_gpu.c`) | Source in `shaders/` |
|
||||
| `adsp/libQnnHtpV79Skel.so`, `adsp/libQnnHtpV81Skel.so` | NPU side, loaded by FastRPC through `ADSP_LIBRARY_PATH`; also probed for the arch (`fsr4_qnn.c:224`) | No: Qualcomm QNN |
|
||||
| `<arch>/fsr4_v07_i8_cache.bin`, `<arch>/fsr412_lite_i8_cache.bin` | Compiled NPU graphs, written by the layer on first use | Made on the device |
|
||||
| `1080/{performance,ultraperf}/pass-00.spv`, `pass-01-npu.spv`, `pass-28.spv`, `initializers.bin`, `v81/nf4_k1h.bin`, `v81/nf4up_k1h.bin` | Optional external FSR 4.1.1 Full NPU pack (`fsr4_pipeline.c:460`-`478`, `fsr4_qnn.c:1018`); v81 only | No |
|
||||
| `jni/arm64-v8a/<lib>`, `<lib>` | First two places searched for QNN host libraries | No |
|
||||
|
||||
`<arch>` is `v79` or `v81`: `HTP_ARCH` if set, else the SoC (`ro.soc.model` /
|
||||
`ro.vendor.qti.soc_model` starting with `SM8750` = v79, `SM8850` = v81, or `ro.vendor.qti.soc_name` /
|
||||
`ro.board.platform` `sun` = v79, `canoe` = v81), else the `libQnnHtpV<NN>Stub.so` mapped in the
|
||||
process, else the only skel present in `adsp/`, else `htp` (`fsr4_qnn.c:176`-`250`). Upstream always
|
||||
used `v81/`.
|
||||
|
||||
## NPU setup (Android build only)
|
||||
|
||||
- Host libraries: `libQnnSystem.so`, `libQnnHtp.so`, `libQnnHtpV79Stub.so`, `libQnnHtpV81Stub.so`,
|
||||
`libQnnHtpPrepare.so` (on-device graph compile). Searched in this order (`fsr4_qnn.c:303`):
|
||||
`<DIR>/jni/arm64-v8a/`, `<DIR>/`, `<NATIVELIB_DIR>/`, each `LD_LIBRARY_PATH` entry, then the bare
|
||||
name (Android `sphal` namespace first, then the default one).
|
||||
- `libQnnHtp.so` opens the arch stub by name itself. The layer loads `libQnnHtpV<arch>Stub.so`
|
||||
(both stubs when the arch is unknown) from the same search list first (`fsr4_qnn.c:364`), so
|
||||
`NATIVELIB_DIR` alone is enough; `LD_LIBRARY_PATH` does not have to name the folder.
|
||||
- `ADSP_LIBRARY_PATH` must list `<DIR>/adsp` (the skels), `;`-separated, e.g.
|
||||
`<DIR>/adsp;/vendor/dsp/cdsp;/vendor/lib/rfsa/adsp;/system/lib/rfsa/adsp`. The layer prepends
|
||||
`<DIR>/adsp` itself when it is missing.
|
||||
- `libcdsprpc.so` comes from the vendor partition.
|
||||
|
||||
## DroidDeck changes from upstream
|
||||
|
||||
- Layer name, library name, log tags, manifest (implicit, `DROIDDECK_UPSCALE` / `DROIDDECK_UPSCALE_DISABLE`).
|
||||
- `DROIDDECK_UPSCALE_<KEY>` env with `WINLATOR_FSR4_<KEY>` fallback.
|
||||
- No hardcoded `/data/user/0/com.winlator.cmod/files/fsr4` fallback; no data dir means GPU blit.
|
||||
- Compiled NPU graph caches in `<DIR>/<arch>/` instead of `<DIR>/v81/`.
|
||||
- driverID/driverName/driverInfo rewrite only with `GPU_SPOOF` word `1`; `SPOOF_DLSS=1` alone reports RTX vendor/device IDs.
|
||||
- Arch stub preloaded from the library search list (`NATIVELIB_DIR` works without `LD_LIBRARY_PATH`).
|
||||
- glibc build (`DD_UPSCALE_NO_ANDROID`) with QNN stubs and stderr logging.
|
||||
- `-Bsymbolic` link flag; pack scripts take their paths as arguments instead of the author's Windows paths.
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"file_format_version": "1.2.0",
|
||||
"layer": {
|
||||
"name": "VK_LAYER_DROIDDECK_upscale",
|
||||
"type": "GLOBAL",
|
||||
"library_path": "libVkLayer_droiddeck_upscale.so",
|
||||
"api_version": "1.3.275",
|
||||
"implementation_version": "1",
|
||||
"description": "In-game upscaler: FSR 4 / FSR 3.1 / XeSS / DLSS calls from the Windows bridge DLLs run on the GPU or the Hexagon NPU",
|
||||
"enable_environment": {
|
||||
"DROIDDECK_UPSCALE": "1"
|
||||
},
|
||||
"disable_environment": {
|
||||
"DROIDDECK_UPSCALE_DISABLE": "1"
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+52
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds VK_LAYER_DROIDDECK_upscale for the arm64 glibc guest (PRoot mode): tools/upscale/layer/build-glibc.sh OUT
|
||||
# DD_UPSCALE_NO_ANDROID leaves out AHardwareBuffer, FastRPC, QNN and liblog, so NPU backends use their GPU fallbacks.
|
||||
# OUT gets libVkLayer_droiddeck_upscale.so and VK_LAYER_DROIDDECK_upscale.json (absolute guest library_path).
|
||||
# -Bsymbolic: the layer exports vkGetInstanceProcAddr; without it a libvulkan already in the global scope
|
||||
# wins the lookup and the loader gets its own trampoline back ("Failed to find 'vkCreateInstance'").
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
repo=$(cd "$here/../../.." && pwd)
|
||||
|
||||
out=${1:?usage: tools/upscale/layer/build-glibc.sh OUT}
|
||||
case "$out" in /*) ;; *) out="$PWD/$out" ;; esac
|
||||
guest_lib=${DD_UPSCALE_GUEST_LIB:-/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so}
|
||||
cc=${CC:-aarch64-linux-gnu-gcc}
|
||||
strip=${STRIP:-aarch64-linux-gnu-strip}
|
||||
|
||||
vkinc=${VK_INCLUDE:-}
|
||||
if [ -z "$vkinc" ]; then
|
||||
ndks=("${NDK:-}" "${ANDROID_NDK_HOME:-}" "${ANDROID_NDK_LATEST_HOME:-}")
|
||||
sdk_ndks=("${ANDROID_HOME:-$HOME/Library/Android/sdk}"/ndk/*)
|
||||
for ((i = ${#sdk_ndks[@]} - 1; i >= 0; i--)); do ndks+=("${sdk_ndks[i]}"); done
|
||||
for ndk in "${ndks[@]}"; do
|
||||
[ -n "$ndk" ] && [ -d "$ndk" ] || continue
|
||||
for cand in "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include; do
|
||||
if [ -f "$cand/vulkan/vulkan_android.h" ]; then vkinc=$cand; break 2; fi
|
||||
done
|
||||
done
|
||||
fi
|
||||
[ -n "$vkinc" ] && [ -f "$vkinc/vulkan/vulkan_core.h" ] && [ -f "$vkinc/vulkan/vulkan_android.h" ] || {
|
||||
echo "tools/upscale/layer/build-glibc.sh: no Vulkan headers (set VK_INCLUDE)" >&2; exit 1; }
|
||||
command -v "$cc" >/dev/null || { echo "tools/upscale/layer/build-glibc.sh: $cc not found (set CC)" >&2; exit 1; }
|
||||
|
||||
work="$repo/build/upscale-layer"
|
||||
rm -rf "$work" && mkdir -p "$work/include" "$work/out"
|
||||
# Only the Vulkan headers: the NDK sysroot's libc headers must not shadow glibc's.
|
||||
cp -R "$vkinc/vulkan" "$work/include/"
|
||||
if [ -d "$vkinc/vk_video" ]; then cp -R "$vkinc/vk_video" "$work/include/"; fi
|
||||
|
||||
"$cc" -std=gnu11 -shared -fPIC -O2 -Wall -Wextra -Wno-unused-function -Wno-missing-field-initializers \
|
||||
-fvisibility=hidden -pthread -Wl,-z,defs -Wl,-Bsymbolic -DDD_UPSCALE_NO_ANDROID -I"$work/include" -I"$here" \
|
||||
-o "$work/out/libVkLayer_droiddeck_upscale.so" \
|
||||
"$here/fsr4_layer.c" "$here/fsr4_pipeline.c" "$here/fsr4_builtin.c" "$here/fsr412_lite.c" \
|
||||
"$here/fsr411_full_gpu.c" "$here/fsr3_gpu.c" "$here/sgsr2_gpu.c" "$here/fsr4_qnn.c" -lm -ldl
|
||||
"$strip" --strip-unneeded "$work/out/libVkLayer_droiddeck_upscale.so"
|
||||
|
||||
sed "s|\"library_path\": \"[^\"]*\"|\"library_path\": \"$guest_lib\"|" \
|
||||
"$here/VK_LAYER_DROIDDECK_upscale.json" > "$work/out/VK_LAYER_DROIDDECK_upscale.json"
|
||||
grep -q "\"library_path\": \"$guest_lib\"" "$work/out/VK_LAYER_DROIDDECK_upscale.json"
|
||||
|
||||
mkdir -p "$out"
|
||||
cp "$work/out/libVkLayer_droiddeck_upscale.so" "$work/out/VK_LAYER_DROIDDECK_upscale.json" "$out/"
|
||||
echo "built $out"
|
||||
@@ -0,0 +1,64 @@
|
||||
// DroidDeck glue for the upscaler layer: environment lookup and logging.
|
||||
//
|
||||
// Every setting is read as DROIDDECK_UPSCALE_<KEY> first and WINLATOR_FSR4_<KEY> second, so
|
||||
// launchers written for the upstream layer keep working. Empty values count as unset.
|
||||
//
|
||||
// Android builds log to logcat. DD_UPSCALE_NO_ANDROID builds (glibc, PRoot guest) log to stderr.
|
||||
#pragma once
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static inline const char *dd_upscale_env(const char *key) {
|
||||
char name[96];
|
||||
snprintf(name, sizeof name, "DROIDDECK_UPSCALE_%s", key);
|
||||
const char *v = getenv(name);
|
||||
if (v && *v) return v;
|
||||
snprintf(name, sizeof name, "WINLATOR_FSR4_%s", key);
|
||||
v = getenv(name);
|
||||
return (v && *v) ? v : NULL;
|
||||
}
|
||||
|
||||
// Async NPU: the next frame's command buffer waits on the GPU for the NPU result, so the game's recording thread never
|
||||
// blocks on the NPU. DROIDDECK_UPSCALE_NPU_CPU_WAIT=1 brings back the old wait on the recording thread.
|
||||
static inline int dd_upscale_npu_gpu_wait(void) {
|
||||
const char *v = dd_upscale_env("NPU_CPU_WAIT");
|
||||
return !(v && (!strcmp(v, "1") || !strcmp(v, "true")));
|
||||
}
|
||||
|
||||
// Data dir with the SPIR-V passes, weights and QNN files. NULL when no launcher set one.
|
||||
static inline const char *dd_upscale_dir(void) {
|
||||
const char *dir = dd_upscale_env("DIR");
|
||||
if (!dir) {
|
||||
dir = getenv("DM_FSR4_DIR");
|
||||
if (dir && !*dir) dir = NULL;
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
#ifdef DD_UPSCALE_NO_ANDROID
|
||||
#include <stdarg.h>
|
||||
|
||||
#define DD_LOG_INFO 4
|
||||
#define DD_LOG_WARN 5
|
||||
#define DD_LOG_ERROR 6
|
||||
|
||||
__attribute__((format(printf, 3, 4)))
|
||||
static inline int dd_upscale_log(int prio, const char *tag, const char *fmt, ...) {
|
||||
char msg[1024];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(msg, sizeof msg, fmt, ap);
|
||||
va_end(ap);
|
||||
const char lvl = prio >= DD_LOG_ERROR ? 'E' : (prio == DD_LOG_WARN ? 'W' : 'I');
|
||||
return fprintf(stderr, "%c/%s: %s\n", lvl, tag, msg);
|
||||
}
|
||||
#else
|
||||
#include <android/log.h>
|
||||
|
||||
#define DD_LOG_INFO ANDROID_LOG_INFO
|
||||
#define DD_LOG_WARN ANDROID_LOG_WARN
|
||||
#define DD_LOG_ERROR ANDROID_LOG_ERROR
|
||||
#define dd_upscale_log __android_log_print
|
||||
#endif
|
||||
@@ -0,0 +1,784 @@
|
||||
// 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 "fsr4_pipeline.h"
|
||||
#include "fsr_gpu_timer.h"
|
||||
|
||||
#include "dd_upscale_compat.h"
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define F3_TAG "DroidDeckUpscaleFSR3"
|
||||
#define F3_LOGI(...) dd_upscale_log(DD_LOG_INFO, F3_TAG, __VA_ARGS__)
|
||||
#define F3_LOGW(...) dd_upscale_log(DD_LOG_WARN, F3_TAG, __VA_ARGS__)
|
||||
#define F3_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F3_TAG, __VA_ARGS__)
|
||||
|
||||
typedef struct {
|
||||
VkImage img;
|
||||
VkDeviceMemory mem;
|
||||
VkImageView view;
|
||||
VkFormat fmt;
|
||||
uint32_t w, h;
|
||||
int inited;
|
||||
} F3Img;
|
||||
|
||||
typedef struct {
|
||||
float jitter_x, jitter_y;
|
||||
float mv_scale_x, mv_scale_y;
|
||||
float jitter_cancel_x, jitter_cancel_y;
|
||||
float expo;
|
||||
float sharp;
|
||||
uint32_t rw, rh;
|
||||
uint32_t ow, oh;
|
||||
uint32_t flags;
|
||||
uint32_t col_base;
|
||||
uint32_t dep_base;
|
||||
uint32_t mv_base;
|
||||
uint32_t react_base;
|
||||
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[7] = {
|
||||
{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},
|
||||
{5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
{6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
};
|
||||
VkDescriptorSetLayoutBinding b_accum[6] = {
|
||||
{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},
|
||||
{5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
};
|
||||
VkDescriptorSetLayoutBinding b_rcas[3] = {
|
||||
{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},
|
||||
{2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
};
|
||||
|
||||
if (!f3_create_pipe(vk, fsr4_dir, "fsr3_prepare.spv", b_prep, 7, sizeof(F3PC), &g->dsl_prep, &g->pl_prep, &g->pipe_prep) ||
|
||||
!f3_create_pipe(vk, fsr4_dir, "fsr3_accumulate.spv", b_accum, 6, sizeof(F3PC), &g->dsl_accum, &g->pl_accum, &g->pipe_accum) ||
|
||||
!f3_create_pipe(vk, fsr4_dir, "fsr3_rcas.spv", b_rcas, 3, 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, 32 },
|
||||
{ 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;
|
||||
}
|
||||
}
|
||||
|
||||
// Optional Reactive / DLSS BiasCurrentColorMask + 1x1 ExposureTexture (eliminates RDR2 DLSS artifacts!)
|
||||
int has_reactive = 0;
|
||||
VkImage react_img = (VkImage)(uintptr_t)frame->reactive.vk_image;
|
||||
VkFormat react_fmt = (VkFormat)frame->reactive.vk_format;
|
||||
VkImageView react_v = g->dummy_img.view;
|
||||
if (react_img != VK_NULL_HANDLE) {
|
||||
if (react_fmt == VK_FORMAT_UNDEFINED) {
|
||||
wl_fsr4_lookup_image_info(g->vk.device, react_img, &react_fmt, NULL, NULL, NULL);
|
||||
}
|
||||
VkImageView rv = frame->reactive.vk_view ? (VkImageView)(uintptr_t)frame->reactive.vk_view
|
||||
: (react_fmt != VK_FORMAT_UNDEFINED ? f3_get_view(g, react_img, react_fmt, VK_IMAGE_ASPECT_COLOR_BIT) : VK_NULL_HANDLE);
|
||||
if (rv) { react_v = rv; has_reactive = 1; }
|
||||
}
|
||||
|
||||
int has_expo_tex = 0;
|
||||
VkImage expo_img = (VkImage)(uintptr_t)frame->exposure.vk_image;
|
||||
VkFormat expo_fmt = (VkFormat)frame->exposure.vk_format;
|
||||
VkImageView expo_v = g->dummy_img.view;
|
||||
if (expo_img != VK_NULL_HANDLE) {
|
||||
if (expo_fmt == VK_FORMAT_UNDEFINED) {
|
||||
wl_fsr4_lookup_image_info(g->vk.device, expo_img, &expo_fmt, NULL, NULL, NULL);
|
||||
}
|
||||
VkImageView ev = frame->exposure.vk_view ? (VkImageView)(uintptr_t)frame->exposure.vk_view
|
||||
: (expo_fmt != VK_FORMAT_UNDEFINED ? f3_get_view(g, expo_img, expo_fmt, VK_IMAGE_ASPECT_COLOR_BIT) : VK_NULL_HANDLE);
|
||||
if (ev) { expo_v = ev; has_expo_tex = 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 };
|
||||
VkDescriptorImageInfo re_ii = { g->sampler_nearest, react_v, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkDescriptorImageInfo ex_ii = { g->sampler_nearest, expo_v, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkWriteDescriptorSet w_imgs[8] = {
|
||||
{ .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_prep[cur], .dstBinding = 5, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &re_ii },
|
||||
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_prep[cur], .dstBinding = 6, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &ex_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 },
|
||||
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_accum[cur], .dstBinding = 5, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &ex_ii },
|
||||
{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g->ds_rcas[cur], .dstBinding = 2, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &ex_ii },
|
||||
};
|
||||
vk->UpdateDescriptorSets(vk->device, 8, 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;
|
||||
VkImageLayout re_old = frame->reactive.vk_layout ? (VkImageLayout)frame->reactive.vk_layout : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||||
VkImageLayout ex_old = frame->exposure.vk_layout ? (VkImageLayout)frame->exposure.vk_layout : VK_IMAGE_LAYOUT_SHADER_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);
|
||||
}
|
||||
if (has_reactive && re_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
|
||||
f3_img_bar(vk, cb, react_img, re_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_expo_tex && ex_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
|
||||
f3_img_bar(vk, cb, expo_img, ex_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;
|
||||
if (has_reactive) pc_flags |= 16u;
|
||||
if (has_expo_tex) pc_flags |= 32u;
|
||||
|
||||
uint32_t col_base = (uint32_t)frame->color.subrect_x | ((uint32_t)frame->color.subrect_y << 16);
|
||||
uint32_t dep_base = (uint32_t)frame->depth.subrect_x | ((uint32_t)frame->depth.subrect_y << 16);
|
||||
uint32_t mv_base = (uint32_t)frame->motion.subrect_x | ((uint32_t)frame->motion.subrect_y << 16);
|
||||
uint32_t react_base = (uint32_t)frame->reactive.subrect_x | ((uint32_t)frame->reactive.subrect_y << 16);
|
||||
|
||||
F3PC pc = {
|
||||
frame->jitter_x, frame->jitter_y,
|
||||
mvsx, mvsy, jcx, jcy,
|
||||
expo, sharp,
|
||||
rw, rh, ow, oh,
|
||||
pc_flags, col_base, dep_base, mv_base, react_base, 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);
|
||||
|
||||
int32_t ox = (int32_t)frame->output.subrect_x;
|
||||
int32_t oy = (int32_t)frame->output.subrect_y;
|
||||
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 = { {ox, oy, 0}, {ox + (int32_t)ow, oy + (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);
|
||||
}
|
||||
if (has_reactive && re_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
|
||||
f3_img_bar(vk, cb, react_img, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, re_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_expo_tex && ex_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
|
||||
f3_img_bar(vk, cb, expo_img, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, ex_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);
|
||||
}
|
||||
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,49 @@
|
||||
// Winlator NeuralScale AMD FSR 4.1.1 Full INT8 Pipeline (Hexagon HTP NPU + Optimized Adreno GPU)
|
||||
//
|
||||
// Uses genuine AMD FSR 4.1.1 Full INT8 SPIR-V modules (pass-00..pass-27) and 131 KB initializers.bin:
|
||||
// - NPU Mode (Snapdragon 8 Elite / 8 Elite Gen 5):
|
||||
// Runs ONLY 2-3 lightweight GPU passes (optional pass-00 SPD, pass-01 prepass, pass-27 postpass)
|
||||
// while offloading ALL 12 deep neural U-Net blocks (pass-02..pass-26, 109 ops) to Hexagon HTP
|
||||
// via zero-copy AHardwareBuffer + native symmetric SFIXED_POINT_8 (0 pack/unpack/Convert passes,
|
||||
// 0 CPU cache flushes, inter-frame micro-sleep, Sync & Async support, honest Sync GPU timer!).
|
||||
// - GPU Mode (Optimized DP4a):
|
||||
// Full 28-pass pipeline with Tier 1.1 direct output write (0 CmdBlitImage) and Tier 1.2
|
||||
// conditional Auto-Exposure SPD skip.
|
||||
#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, const char *power_mode);
|
||||
void wl_fsr411_full_gpu_destroy(WlFsr411FullGpu *ctx);
|
||||
void wl_fsr411_full_gpu_reset(WlFsr411FullGpu *ctx);
|
||||
void wl_fsr411_full_gpu_release_sync_events(WlFsr411FullGpu *ctx);
|
||||
int wl_fsr411_full_gpu_is_ready(const WlFsr411FullGpu *ctx);
|
||||
int wl_fsr411_full_gpu_is_npu_ready(const WlFsr411FullGpu *ctx);
|
||||
const char *wl_fsr411_full_gpu_npu_state(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 exp_img, VkFormat exp_fmt,
|
||||
VkImage out_img, VkFormat out_fmt, VkImageUsageFlags out_usage,
|
||||
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
@@ -0,0 +1,53 @@
|
||||
// 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 exp_img, VkFormat exp_fmt,
|
||||
VkImage out_img, VkFormat out_fmt, VkImageUsageFlags out_usage,
|
||||
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
@@ -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
@@ -0,0 +1,171 @@
|
||||
// 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 app_desc_buf; // the game itself enabled VK_EXT_descriptor_buffer
|
||||
int has_mut_desc;
|
||||
int has_ext_ahb;
|
||||
int has_bda;
|
||||
int has_f16;
|
||||
int has_i8;
|
||||
int has_int_dot;
|
||||
int has_sync2;
|
||||
int has_qf_foreign;
|
||||
int has_compute_derivs;
|
||||
int has_8bit_storage;
|
||||
int has_16bit_storage;
|
||||
int has_timestamps;
|
||||
float timestamp_period;
|
||||
uint32_t subgroup_req_stages;
|
||||
uint32_t subgroup_min;
|
||||
uint32_t subgroup_max;
|
||||
|
||||
// Instance-level dispatch
|
||||
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties;
|
||||
PFN_vkGetPhysicalDeviceProperties2 GetPhysicalDeviceProperties2;
|
||||
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
|
||||
PFN_vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties;
|
||||
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties;
|
||||
|
||||
// Device-level dispatch
|
||||
PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
|
||||
PFN_vkCreateBuffer CreateBuffer;
|
||||
PFN_vkDestroyBuffer DestroyBuffer;
|
||||
PFN_vkGetBufferMemoryRequirements GetBufferMemoryRequirements;
|
||||
PFN_vkBindBufferMemory BindBufferMemory;
|
||||
PFN_vkGetBufferDeviceAddress GetBufferDeviceAddress;
|
||||
PFN_vkAllocateMemory AllocateMemory;
|
||||
PFN_vkFreeMemory FreeMemory;
|
||||
PFN_vkMapMemory MapMemory;
|
||||
PFN_vkUnmapMemory UnmapMemory;
|
||||
PFN_vkCreateImage CreateImage;
|
||||
PFN_vkDestroyImage DestroyImage;
|
||||
PFN_vkGetImageMemoryRequirements GetImageMemoryRequirements;
|
||||
PFN_vkBindImageMemory BindImageMemory;
|
||||
PFN_vkCreateImageView CreateImageView;
|
||||
PFN_vkDestroyImageView DestroyImageView;
|
||||
PFN_vkCreateSampler CreateSampler;
|
||||
PFN_vkDestroySampler DestroySampler;
|
||||
PFN_vkCreateShaderModule CreateShaderModule;
|
||||
PFN_vkDestroyShaderModule DestroyShaderModule;
|
||||
PFN_vkCreateDescriptorSetLayout CreateDescriptorSetLayout;
|
||||
PFN_vkDestroyDescriptorSetLayout DestroyDescriptorSetLayout;
|
||||
PFN_vkCreateDescriptorPool CreateDescriptorPool;
|
||||
PFN_vkDestroyDescriptorPool DestroyDescriptorPool;
|
||||
PFN_vkAllocateDescriptorSets AllocateDescriptorSets;
|
||||
PFN_vkUpdateDescriptorSets UpdateDescriptorSets;
|
||||
PFN_vkCmdBindDescriptorSets CmdBindDescriptorSets;
|
||||
PFN_vkCreatePipelineLayout CreatePipelineLayout;
|
||||
PFN_vkDestroyPipelineLayout DestroyPipelineLayout;
|
||||
PFN_vkCreateComputePipelines CreateComputePipelines;
|
||||
PFN_vkDestroyPipeline DestroyPipeline;
|
||||
PFN_vkCmdBindPipeline CmdBindPipeline;
|
||||
PFN_vkCmdPushConstants CmdPushConstants;
|
||||
PFN_vkCmdDispatch CmdDispatch;
|
||||
PFN_vkCmdPipelineBarrier CmdPipelineBarrier;
|
||||
PFN_vkCmdPipelineBarrier2 CmdPipelineBarrier2;
|
||||
PFN_vkCmdClearColorImage CmdClearColorImage;
|
||||
PFN_vkCmdClearDepthStencilImage CmdClearDepthStencilImage;
|
||||
PFN_vkCmdFillBuffer CmdFillBuffer;
|
||||
PFN_vkCmdCopyBuffer CmdCopyBuffer;
|
||||
PFN_vkCmdCopyImageToBuffer CmdCopyImageToBuffer;
|
||||
PFN_vkCmdCopyBufferToImage CmdCopyBufferToImage;
|
||||
PFN_vkCmdBlitImage CmdBlitImage;
|
||||
PFN_vkCmdCopyImage CmdCopyImage;
|
||||
PFN_vkDeviceWaitIdle DeviceWaitIdle;
|
||||
|
||||
// Events (for same-frame NPU Sync mode + slot retirement)
|
||||
PFN_vkCreateEvent CreateEvent;
|
||||
PFN_vkDestroyEvent DestroyEvent;
|
||||
PFN_vkSetEvent SetEvent;
|
||||
PFN_vkResetEvent ResetEvent;
|
||||
PFN_vkGetEventStatus GetEventStatus;
|
||||
PFN_vkCmdSetEvent CmdSetEvent;
|
||||
PFN_vkCmdResetEvent CmdResetEvent;
|
||||
PFN_vkCmdWaitEvents CmdWaitEvents;
|
||||
|
||||
// Timestamp query pool (for per-frame GPU ms HUD telemetry)
|
||||
PFN_vkCreateQueryPool CreateQueryPool;
|
||||
PFN_vkDestroyQueryPool DestroyQueryPool;
|
||||
PFN_vkCmdResetQueryPool CmdResetQueryPool;
|
||||
PFN_vkCmdWriteTimestamp CmdWriteTimestamp;
|
||||
PFN_vkGetQueryPoolResults GetQueryPoolResults;
|
||||
|
||||
// Extension dispatch
|
||||
PFN_vkGetDescriptorSetLayoutSizeEXT GetDescriptorSetLayoutSizeEXT;
|
||||
PFN_vkGetDescriptorSetLayoutBindingOffsetEXT GetDescriptorSetLayoutBindingOffsetEXT;
|
||||
PFN_vkGetDescriptorEXT GetDescriptorEXT;
|
||||
PFN_vkCmdBindDescriptorBuffersEXT CmdBindDescriptorBuffersEXT;
|
||||
PFN_vkCmdSetDescriptorBufferOffsetsEXT CmdSetDescriptorBufferOffsetsEXT;
|
||||
PFN_vkCmdBindDescriptorBufferEmbeddedSamplersEXT CmdBindDescriptorBufferEmbeddedSamplersEXT;
|
||||
PFN_vkGetAndroidHardwareBufferPropertiesANDROID GetAndroidHardwareBufferPropertiesANDROID;
|
||||
} WlVkDispatch;
|
||||
|
||||
typedef struct WlFsr4Pipeline WlFsr4Pipeline;
|
||||
|
||||
// Legacy aliases kept for source clarity
|
||||
enum {
|
||||
WL_FSR_ENGINE_FSR4_NPU = WL_FSR_BACKEND_FSR4_1_LITE_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_* (including WL_FSR_BACKEND_AUTO) */
|
||||
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) */
|
||||
int fps_limit; /* 0 = uncapped, >0 = active FPS limit */
|
||||
int has_supported_npu; /* 1 = Snapdragon 8 Elite / 8 Elite Gen 5 with bundled HTP v79/v81 pack */
|
||||
int anti_throttle; /* 1 = proactive anti-throttling enabled (Auto mode + capped FPS ONLY) */
|
||||
float thermal_headroom; /* Android PowerManager.getThermalHeadroom(10); < 0 if unavailable/NaN */
|
||||
float batt_temp_c; /* Battery temperature in C (fallback if thermal_headroom < 0); <= 0 if unknown */
|
||||
} 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);
|
||||
void wl_fsr4_pipe_record_present(WlFsr4Pipeline *p, int64_t dt_ns);
|
||||
|
||||
// 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
@@ -0,0 +1,557 @@
|
||||
// Clean-room C declaration of the Qualcomm QNN HTP (v79/v81) interface subset and shared-buffer
|
||||
// helpers for the DroidDeck upscaler layer (ported from Winlator-NeuralScale).
|
||||
// Struct layouts match the QAIRT 2.47+ C ABI so builds need zero external QNN headers.
|
||||
#pragma once
|
||||
|
||||
#include <stdarg.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
enum {
|
||||
WL_FSR4_TENSOR_BYTES = 8294400u,
|
||||
WL_FSR4_AHB_BYTES = 4u * WL_FSR4_TENSOR_BYTES,
|
||||
WL_FSR4_PRESET_PERF = 0,
|
||||
WL_FSR4_PRESET_ULTRAPERF = 1,
|
||||
|
||||
// Built-in self-contained AMD FSR 4.0.2 INT8 (fsr4_model_v07_i8_quality) AHB layout:
|
||||
// slot 0 in : [0, 8294400) UFIXED_POINT_8 [1, 540, 960, 16]
|
||||
// slot 1 in : [8294400, 16588800) UFIXED_POINT_8 [1, 540, 960, 16]
|
||||
// slot 0 out : [16588800, 33177600) UFIXED_POINT_8 [1, 1080, 1920, 8]
|
||||
// slot 1 out : [33177600, 49766400) UFIXED_POINT_8 [1, 1080, 1920, 8]
|
||||
WL_FSR4_BUILTIN_IN_BYTES = 8294400u,
|
||||
WL_FSR4_BUILTIN_OUT_BYTES = 16588800u,
|
||||
WL_FSR4_BUILTIN_AHB_BYTES = 49766400u,
|
||||
WL_FSR4_PASS0_WB_BYTES = 1056u,
|
||||
|
||||
// AMD FSR 4.1.2 Lite INT8 zero-copy AHB-backed scratch layout (4096-byte page-aligned!):
|
||||
// slot 0 scratch: [0, 25030656) -> in at +0 (8342464 B), out at +16687104 (8342464 B)
|
||||
// slot 1 scratch: [25030656, 50061312) -> in at +25030656, out at +41717760
|
||||
WL_FSR4_LITE_IN_BYTES = 8342464u,
|
||||
WL_FSR4_LITE_OUT_BYTES = 8342464u,
|
||||
WL_FSR4_LITE_OUT_OFFSET = 16687104u,
|
||||
WL_FSR4_LITE_SLOT_STRIDE = 25030656u,
|
||||
WL_FSR4_LITE_AHB_BYTES = 2u * WL_FSR4_LITE_SLOT_STRIDE,
|
||||
|
||||
// AMD FSR 4.1.1 Full INT8 zero-copy AHB layout (4096-byte page-aligned!):
|
||||
// slot 0: in at +0 (8342464 B), out at +8343552 (8342464 B)
|
||||
// slot 1: in at +16687104, out at +25030656
|
||||
WL_FSR411_FULL_IN_BYTES = 8342464u,
|
||||
WL_FSR411_FULL_OUT_BYTES = 8342464u,
|
||||
WL_FSR411_FULL_OUT_OFFSET = 8343552u,
|
||||
WL_FSR411_FULL_SLOT_STRIDE = 16687104u,
|
||||
WL_FSR411_FULL_AHB_BYTES = 2u * WL_FSR411_FULL_SLOT_STRIDE,
|
||||
};
|
||||
|
||||
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]);
|
||||
// The compiled context lives in <fsr4_dir>/<this device's htp arch>/<file>; a "<arch>/" prefix the caller
|
||||
// writes (upstream writes v81/) is replaced by this device's arch.
|
||||
wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel,
|
||||
const char *cache_name, const char *graph_name,
|
||||
const char *power_mode,
|
||||
uint32_t in_bytes, uint32_t out_bytes);
|
||||
wl_fsr4_qnn *wl_fsr4_qnn_init_wpack_layout(const char *fsr4_dir, const char *wpack_rel,
|
||||
const char *cache_rel, const char *graph_name,
|
||||
const char *power_mode,
|
||||
size_t total_ahb_bytes,
|
||||
const uint64_t in_offs[2], const uint64_t out_offs[2]);
|
||||
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);
|
||||
int wl_fsr4_qnn_exec_offsets(wl_fsr4_qnn *q, int slot,
|
||||
uint64_t in_off, uint32_t in_bytes,
|
||||
uint64_t out_off, uint32_t out_bytes,
|
||||
double *out_ms);
|
||||
int wl_fsr4_qnn_exec_offsets_zc(wl_fsr4_qnn *q, int slot,
|
||||
uint64_t in_off, uint32_t in_bytes,
|
||||
uint64_t out_off, uint32_t out_bytes,
|
||||
int zero_copy, double *out_ms);
|
||||
int wl_fsr4_qnn_set_power_mode(const char *power_mode);
|
||||
const char *wl_fsr4_qnn_get_power_mode(void);
|
||||
void wl_fsr4_pin_worker_non_prime(const char *worker_name);
|
||||
const char *wl_fsr4_qnn_last_error(void);
|
||||
void wl_fsr4_qnn_free(wl_fsr4_qnn *q);
|
||||
// Writes <fsr4_dir>/<htp arch>/<name>; returns 0 when it does not fit or an argument is missing.
|
||||
int wl_fsr4_qnn_cache_path(const char *fsr4_dir, const char *name, char *out, size_t out_sz);
|
||||
|
||||
// ---- Clean-room QNN C ABI definitions (QAIRT 2.47+ / HTP v81) ----
|
||||
|
||||
typedef uint64_t Qnn_ErrorHandle_t;
|
||||
typedef void *Qnn_Handle_t;
|
||||
typedef Qnn_Handle_t Qnn_BackendHandle_t;
|
||||
typedef Qnn_Handle_t Qnn_ContextHandle_t;
|
||||
typedef Qnn_Handle_t Qnn_DeviceHandle_t;
|
||||
typedef Qnn_Handle_t Qnn_GraphHandle_t;
|
||||
typedef Qnn_Handle_t Qnn_LogHandle_t;
|
||||
typedef Qnn_Handle_t Qnn_MemHandle_t;
|
||||
typedef Qnn_Handle_t Qnn_ProfileHandle_t;
|
||||
typedef Qnn_Handle_t Qnn_SignalHandle_t;
|
||||
typedef void *QnnSystemContext_Handle_t;
|
||||
typedef uint64_t Qnn_ContextBinarySize_t;
|
||||
|
||||
enum {
|
||||
QNN_SUCCESS_CODE = 0,
|
||||
QNN_DEFINITION_IMPL_GENERATED = 0,
|
||||
QNN_DEFINITION_DEFINED = 1,
|
||||
QNN_DEFINITION_UNDEFINED = 0x7FFFFFFF,
|
||||
QNN_LOG_LEVEL_ERROR = 1,
|
||||
QNN_LOG_LEVEL_WARN = 2,
|
||||
QNN_LOG_LEVEL_INFO = 3,
|
||||
QNN_TENSOR_VERSION_1 = 1,
|
||||
QNN_TENSOR_VERSION_2 = 2,
|
||||
QNN_TENSOR_TYPE_APP_WRITE = 0,
|
||||
QNN_TENSOR_TYPE_APP_READ = 1,
|
||||
QNN_TENSOR_TYPE_APP_READWRITE = 2,
|
||||
QNN_TENSOR_TYPE_NATIVE = 3,
|
||||
QNN_TENSOR_TYPE_STATIC = 4,
|
||||
QNN_TENSORMEMTYPE_RAW = 0,
|
||||
QNN_TENSORMEMTYPE_MEMHANDLE = 1,
|
||||
QNN_TENSOR_DATA_FORMAT_FLAT_BUFFER = 0,
|
||||
QNN_DATATYPE_INT_8 = 0x0008,
|
||||
QNN_DATATYPE_INT_32 = 0x0032,
|
||||
QNN_DATATYPE_UINT_8 = 0x0108,
|
||||
QNN_DATATYPE_UINT_32 = 0x0132,
|
||||
QNN_DATATYPE_FLOAT_16 = 0x0216,
|
||||
QNN_DATATYPE_FLOAT_32 = 0x0232,
|
||||
QNN_DATATYPE_SFIXED_POINT_8 = 0x0308,
|
||||
QNN_DATATYPE_SFIXED_POINT_32 = 0x0332,
|
||||
QNN_DATATYPE_UFIXED_POINT_8 = 0x0408,
|
||||
QNN_DATATYPE_BOOL_8 = 0x0508,
|
||||
QNN_PARAMTYPE_SCALAR = 0,
|
||||
QNN_PARAMTYPE_TENSOR = 1,
|
||||
QNN_OPCONFIG_VERSION_1 = 1,
|
||||
QNN_MEM_TYPE_CUSTOM = 2,
|
||||
QNN_HTP_MEM_SHARED_BUFFER = 1,
|
||||
QNN_DEVICE_CONFIG_OPTION_CUSTOM = 0,
|
||||
QNN_HTP_DEVICE_CONFIG_OPTION_SIGNEDPD = 2,
|
||||
QNN_HTP_DEVICE_INFRA_TYPE_PERF = 0,
|
||||
QNN_QUANT_ENC_SCALE_OFFSET = 0,
|
||||
QNN_QUANT_ENC_AXIS_SCALE_OFFSET = 1,
|
||||
QNN_QUANT_ENC_BW_AXIS_SCALE_OFFSET = 3,
|
||||
QNN_QUANT_ENC_UNDEFINED = 0x7FFFFFFF,
|
||||
QNN_GRAPH_CONFIG_OPTION_CUSTOM = 0,
|
||||
QNN_HTP_GRAPH_CONFIG_OPTION_OPTIMIZATION = 1,
|
||||
QNN_HTP_GRAPH_CONFIG_OPTION_VTCM_SIZE = 3,
|
||||
QNN_HTP_GRAPH_OPT_FINALIZE_FLAG = 3,
|
||||
};
|
||||
|
||||
typedef struct { uint32_t major, minor, patch; } Qnn_Version_t;
|
||||
typedef struct { Qnn_Version_t coreApiVersion; Qnn_Version_t backendApiVersion; } Qnn_ApiVersion_t;
|
||||
typedef struct { float scale; int32_t offset; } Qnn_ScaleOffset_t;
|
||||
typedef struct { uint32_t bitwidth; float scale; int32_t offset; } Qnn_BwScaleOffset_t;
|
||||
typedef struct { int32_t axis; uint32_t numScaleOffsets; Qnn_ScaleOffset_t *scaleOffset; } Qnn_AxisScaleOffset_t;
|
||||
typedef struct { uint32_t bitwidth; int32_t axis; uint32_t numElements; float *scales; int32_t *offsets; } Qnn_BwAxisScaleOffset_t;
|
||||
typedef struct { uint32_t *blockSize; Qnn_ScaleOffset_t *scaleOffset; } Qnn_BlockEncoding_t;
|
||||
typedef struct { float scale; float offset; } Qnn_FloatScaleOffset_t;
|
||||
typedef struct { uint32_t *blockSize; Qnn_FloatScaleOffset_t *floatScaleOffset; } Qnn_FloatBlockEncoding_t;
|
||||
typedef struct { uint32_t bitwidth; uint32_t *blockSize; Qnn_FloatScaleOffset_t *floatScaleOffset; } Qnn_BwFloatBlockEncoding_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t encodingDefinition;
|
||||
uint32_t quantizationEncoding;
|
||||
union {
|
||||
Qnn_ScaleOffset_t scaleOffsetEncoding;
|
||||
Qnn_AxisScaleOffset_t axisScaleOffsetEncoding;
|
||||
Qnn_BwScaleOffset_t bwScaleOffsetEncoding;
|
||||
Qnn_BwAxisScaleOffset_t bwAxisScaleOffsetEncoding;
|
||||
Qnn_BlockEncoding_t blockEncoding;
|
||||
void *blockwiseExpansion;
|
||||
void *vectorEncoding;
|
||||
Qnn_FloatBlockEncoding_t floatBlockEncoding;
|
||||
void *bwAxisScaleOffsetMappedEncoding;
|
||||
void *bwBlockMappedEncoding;
|
||||
void *bwBlockwiseExpansionMappedEncoding;
|
||||
Qnn_BwFloatBlockEncoding_t bwFloatBlockEncoding;
|
||||
void *microScalingEncoding;
|
||||
void *arrayOfEncoding;
|
||||
};
|
||||
} Qnn_QuantizeParams_t;
|
||||
|
||||
typedef struct { void *data; uint32_t dataSize; } Qnn_ClientBuffer_t;
|
||||
typedef struct {
|
||||
uint32_t type;
|
||||
struct { uint32_t numSpecifiedElements; uint32_t numSparseDimensions; } hybridCoo;
|
||||
} Qnn_SparseParams_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t id;
|
||||
const char *name;
|
||||
uint32_t type;
|
||||
uint32_t dataFormat;
|
||||
uint32_t dataType;
|
||||
Qnn_QuantizeParams_t quantizeParams;
|
||||
uint32_t rank;
|
||||
uint32_t *dimensions;
|
||||
uint32_t memType;
|
||||
union { Qnn_ClientBuffer_t clientBuf; Qnn_MemHandle_t memHandle; };
|
||||
} Qnn_TensorV1_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t id;
|
||||
const char *name;
|
||||
uint32_t type;
|
||||
uint32_t dataFormat;
|
||||
uint32_t dataType;
|
||||
Qnn_QuantizeParams_t quantizeParams;
|
||||
uint32_t rank;
|
||||
uint32_t *dimensions;
|
||||
uint32_t memType;
|
||||
union { Qnn_ClientBuffer_t clientBuf; Qnn_MemHandle_t memHandle; void *retrieveRaw; };
|
||||
uint8_t *isDynamicDimensions;
|
||||
Qnn_SparseParams_t sparseParams;
|
||||
uint8_t isProduced;
|
||||
} Qnn_TensorV2_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t version;
|
||||
union { Qnn_TensorV1_t v1; Qnn_TensorV2_t v2; };
|
||||
} Qnn_Tensor_t;
|
||||
|
||||
typedef struct { uint32_t numDim; uint32_t *dimSize; const char *shapeConfig; } Qnn_MemShape_t;
|
||||
|
||||
typedef struct {
|
||||
Qnn_MemShape_t memShape;
|
||||
uint32_t dataType;
|
||||
uint32_t memType;
|
||||
union {
|
||||
struct { int32_t fd; } ionInfo;
|
||||
void *customInfo;
|
||||
struct { int32_t fd; void *data; } dmaBufInfo;
|
||||
void *dx12BufInfo;
|
||||
};
|
||||
} Qnn_MemDescriptor_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t type;
|
||||
uint64_t size;
|
||||
union {
|
||||
uint32_t qurtAddress;
|
||||
struct { int32_t fd; uint64_t offset; } sharedBufferConfig;
|
||||
uint8_t raw[16];
|
||||
};
|
||||
} QnnMemHtp_Descriptor_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t option;
|
||||
union {
|
||||
uint32_t socModel;
|
||||
struct { uint32_t deviceId, arch; } arch;
|
||||
struct { uint32_t deviceId; bool useSignedProcessDomain; } useSignedProcessDomain;
|
||||
struct { uint32_t deviceId; bool useSecureProcessDomain; } useSecureProcessDomain;
|
||||
struct { uint32_t deviceId; bool enableAsyncExecute; } asyncExecute;
|
||||
void *htpExtension;
|
||||
};
|
||||
} QnnHtpDevice_CustomConfig_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t option;
|
||||
union { void *customConfig; void *hardwareInfo; };
|
||||
} QnnDevice_Config_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t contextId;
|
||||
uint32_t setDcvsEnable, dcvsEnable;
|
||||
uint32_t powerMode;
|
||||
uint32_t setSleepLatency, sleepLatency;
|
||||
uint32_t setSleepDisable, sleepDisable;
|
||||
uint32_t setBusParams, busVoltageCornerMin, busVoltageCornerTarget, busVoltageCornerMax;
|
||||
uint32_t setCoreParams, coreVoltageCornerMin, coreVoltageCornerTarget, coreVoltageCornerMax;
|
||||
} QnnHtpPerfInfrastructure_DcvsV3_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t hmxPickDefault;
|
||||
uint32_t hmxVoltageCornerMin, hmxVoltageCornerTarget, hmxVoltageCornerMax;
|
||||
uint32_t hmxPerfMode;
|
||||
} QnnHtpPerfInfrastructure_HmxV2_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t option;
|
||||
union {
|
||||
QnnHtpPerfInfrastructure_DcvsV3_t dcvsV3Config;
|
||||
uint32_t rpcControlLatencyConfig;
|
||||
uint32_t rpcPollingTimeConfig;
|
||||
uint32_t hmxTimeoutIntervalUsConfig;
|
||||
QnnHtpPerfInfrastructure_HmxV2_t hmxV2Config;
|
||||
uint32_t raw[16];
|
||||
};
|
||||
} QnnHtpPerfInfrastructure_PowerConfig_t;
|
||||
|
||||
enum {
|
||||
QNN_HTP_POWER_OPT_DCVS_V3 = 1,
|
||||
QNN_HTP_POWER_OPT_RPC_CONTROL_LATENCY = 2,
|
||||
QNN_HTP_POWER_OPT_RPC_POLLING_TIME = 3,
|
||||
QNN_HTP_POWER_OPT_HMX_TIMEOUT_INTERVAL_US = 4,
|
||||
QNN_HTP_POWER_OPT_HMX_V2 = 5,
|
||||
QNN_HTP_POWERMODE_ADJUST_UPDOWN = 0x01,
|
||||
QNN_HTP_POWERMODE_POWER_SAVER = 0x04,
|
||||
QNN_HTP_POWERMODE_PERF = 0x10,
|
||||
QNN_HTP_CLK_PERF_HIGH = 0,
|
||||
QNN_HTP_CLK_PERF_LOW = 1,
|
||||
QNN_HTP_VCORNER_DISABLE = 0x10,
|
||||
QNN_HTP_VCORNER_MIN = 0x20,
|
||||
QNN_HTP_VCORNER_SVS2 = 0x30,
|
||||
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_MIN = 0x100,
|
||||
QNN_HTP_EXP_VCORNER_LOW_SVS = 0x140,
|
||||
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
|
||||
@@ -0,0 +1,168 @@
|
||||
// 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 3u
|
||||
#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) */
|
||||
WL_FSR_BACKEND_SGSR2_GPU = 7, /* Qualcomm Snapdragon GSR 2 (3-pass Adreno FP16 GPU) */
|
||||
WL_FSR_BACKEND_AUTO = 8, /* Smart Automatic (30s FPS/power/cap-aware + fault blacklist) */
|
||||
};
|
||||
|
||||
// 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,
|
||||
WLFSR4_API_NGX_DX11 = 11,
|
||||
};
|
||||
|
||||
// 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) */
|
||||
uint16_t subrect_x; /* optional subrect origin X (pixels, e.g. RDR2 DLSS subrect) */
|
||||
uint16_t subrect_y; /* optional subrect origin Y (pixels) */
|
||||
} 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];
|
||||
WlFsr4ImageRef reactive; /* optional reactive / DLSS BiasCurrentColorMask */
|
||||
WlFsr4ImageRef exposure; /* optional 1x1 ExposureTexture */
|
||||
} WlFsr4FrameDesc; /* 336 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) == 336, "WlFsr4FrameDesc size");
|
||||
_Static_assert(sizeof(WlFsr4Mailbox) <= WLFSR4_MAILBOX_BYTES, "WlFsr4Mailbox fits in 8KB");
|
||||
_Static_assert(sizeof(WlFsr4DoorbellPayload) == 16, "WlFsr4DoorbellPayload size");
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,97 @@
|
||||
// Lightweight non-blocking Vulkan GPU timestamp ring helper for live HUD ms telemetry.
|
||||
// Supports optional pause/resume around Sync vkCmdWaitEvents so GPU ms reports active
|
||||
// GPU shader time cleanly without counting NPU wait time inside GPU ms.
|
||||
#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]; /* 0 = unused, 1 = single (2 ts), 2 = split (4 ts) */
|
||||
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 * 4u,
|
||||
};
|
||||
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)
|
||||
uint32_t mode = t->slot_used[s];
|
||||
if (mode == 1u) {
|
||||
uint64_t ts[2] = {0, 0};
|
||||
VkResult r = vk->GetQueryPoolResults(vk->device, t->pool, s * 4u, 2u,
|
||||
sizeof ts, ts, sizeof(uint64_t),
|
||||
VK_QUERY_RESULT_64_BIT);
|
||||
if (r == VK_SUCCESS && ts[1] >= ts[0]) {
|
||||
double us = (double)(ts[1] - ts[0]) * (double)vk->timestamp_period * 1e-3;
|
||||
if (us >= 0.0 && us < 500000.0) t->last_us = (uint32_t)(us + 0.5);
|
||||
}
|
||||
} else if (mode == 2u) {
|
||||
uint64_t ts[4] = {0, 0, 0, 0};
|
||||
VkResult r = vk->GetQueryPoolResults(vk->device, t->pool, s * 4u, 4u,
|
||||
sizeof ts, ts, sizeof(uint64_t),
|
||||
VK_QUERY_RESULT_64_BIT);
|
||||
if (r == VK_SUCCESS && ts[1] >= ts[0] && ts[3] >= ts[2]) {
|
||||
double ticks = (double)(ts[1] - ts[0]) + (double)(ts[3] - ts[2]);
|
||||
double us = ticks * (double)vk->timestamp_period * 1e-3;
|
||||
if (us >= 0.0 && us < 500000.0) t->last_us = (uint32_t)(us + 0.5);
|
||||
}
|
||||
}
|
||||
t->slot_used[s] = 0u;
|
||||
vk->CmdResetQueryPool(cb, t->pool, s * 4u, 4u);
|
||||
vk->CmdWriteTimestamp(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, t->pool, s * 4u);
|
||||
return s;
|
||||
}
|
||||
|
||||
static inline void wl_gpu_timer_pause(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 * 4u + 1u);
|
||||
}
|
||||
|
||||
static inline void wl_gpu_timer_resume(WlGpuTimer *t, const WlVkDispatch *vk, VkCommandBuffer cb, uint32_t slot) {
|
||||
if (!t || !t->enabled) return;
|
||||
vk->CmdWriteTimestamp(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, t->pool, slot * 4u + 2u);
|
||||
t->slot_used[slot] = 2u;
|
||||
}
|
||||
|
||||
static inline void wl_gpu_timer_end(WlGpuTimer *t, const WlVkDispatch *vk, VkCommandBuffer cb, uint32_t slot) {
|
||||
if (!t || !t->enabled) return;
|
||||
if (t->slot_used[slot] == 2u) {
|
||||
vk->CmdWriteTimestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, t->pool, slot * 4u + 3u);
|
||||
} else {
|
||||
vk->CmdWriteTimestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, t->pool, slot * 4u + 1u);
|
||||
t->slot_used[slot] = 1u;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate verified native 1080p, 900p, and 720p AMD FSR 4.1.2 Lite SPIR-V shaders
|
||||
and zero-copy halo-aware QNN HTP v81 .wpack graphs.
|
||||
|
||||
Every generated SPIR-V shader is assembled with spirv-as and validated with
|
||||
spirv-val --target-env vulkan1.1. Only exact audited geometry/scratch OpConstant
|
||||
definitions are rewritten; all neural network weights, biases, and math stay
|
||||
100% bit-for-bit identical to AMD FidelityFX SDK v2.4.0.
|
||||
|
||||
Zero-copy HTP graph layout (per tier):
|
||||
- All 4 tensor offsets (slot 0 in/out, slot 1 in/out) are 4096-byte page-aligned
|
||||
inside a single shared AHardwareBuffer backing scratch[0] and scratch[1].
|
||||
- Input tensor: SFIXED_POINT_8 [1, Nh+2, Nw+2, 16] (scale=1.0, offset=0) at +0
|
||||
- HTP Entry ops: StridedSlice [1:Nh+1, 1:Nw+1] -> Convert(S8 -> U8, offset=-128)
|
||||
- Core network : Exact genuine AMD FSR 4.1.2 Lite INT8 U-Net
|
||||
- HTP Exit ops : Pad [1,1],[1,1] (constant 0.0f) -> Convert(U8 -> S8, offset=0)
|
||||
- Output tensor: SFIXED_POINT_8 [1, Nh+2, Nw+2, 16] (scale=2.0, offset=0) at +out_b_hi
|
||||
-> Eliminates 0001.spv, lite_npu_pack.spv, and lite_npu_unpack.spv completely!
|
||||
"""
|
||||
import hashlib
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
|
||||
# Import genuine weight loader from existing pack_fsr412_lite_weights.py
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
from pack_fsr412_lite_weights import load_all_weights, WPK_MAGIC, WPK_VERSION, PASS0_PAD
|
||||
|
||||
SPIRV_DIS = Path(r"C:\msys64\ucrt64\bin\spirv-dis.exe")
|
||||
SPIRV_AS = Path(r"C:\msys64\ucrt64\bin\spirv-as.exe")
|
||||
SPIRV_VAL = Path(r"C:\msys64\ucrt64\bin\spirv-val.exe")
|
||||
|
||||
ASSETS_LITE = Path(r"c:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr412_lite")
|
||||
|
||||
# Extended WPK1 tensor kinds & op types (backwards-compatible with fsr4_v07_i8.wpack!)
|
||||
TK_APP_WRITE = 0
|
||||
TK_APP_READ = 1
|
||||
TK_NATIVE = 2
|
||||
TK_STATIC_U8 = 3
|
||||
TK_STATIC_S32 = 4
|
||||
TK_APP_WRITE_S8 = 5
|
||||
TK_APP_READ_S8 = 6
|
||||
TK_NATIVE_S8 = 7
|
||||
TK_STATIC_S8 = 8
|
||||
|
||||
OP_CONV2D = 1
|
||||
OP_RELU = 2
|
||||
OP_ADD = 3
|
||||
OP_CONCAT = 4
|
||||
OP_SLICE_CH = 5
|
||||
OP_DEPTH_TO_SPACE = 6
|
||||
OP_CONVERT = 7
|
||||
OP_SLICE_HW = 8
|
||||
OP_PAD_HW = 9
|
||||
|
||||
|
||||
def align_up(v: int, a: int) -> int:
|
||||
return ((v + a - 1) // a) * a
|
||||
|
||||
|
||||
def tier_geometry(name: str, out_w: int, out_h: int) -> dict:
|
||||
assert out_w % 4 == 0 and out_h % 4 == 0
|
||||
nw, nh = out_w // 2, out_h // 2
|
||||
hw, hh = out_w // 4, out_h // 4
|
||||
nw1, nh1 = nw + 1, nh + 1
|
||||
nw2, nh2 = nw + 2, nh + 2
|
||||
hw1, hh1 = hw + 1, hh + 1
|
||||
hw2, hh2 = hw + 2, hh + 2
|
||||
row_b_hi = nw2 * 16
|
||||
plane_q_hi = nw2 * nh2
|
||||
plane_b_hi = plane_q_hi * 16
|
||||
# Page-align output buffer offset to 4096 B (and 16 B exact multiple!) for QNN zero-copy AHB
|
||||
out_b_hi = align_up(2 * plane_b_hi, 4096)
|
||||
assert out_b_hi % 16 == 0
|
||||
out_q_hi = out_b_hi // 16
|
||||
row_b_lo = hw2 * 16
|
||||
plane_q_lo = hw2 * hh2
|
||||
half_b_lo = plane_q_lo * 16
|
||||
full_b_lo = plane_q_lo * 32
|
||||
out_q_hi_plus_lo = out_q_hi + plane_q_lo
|
||||
slot_stride = align_up(out_b_hi + plane_b_hi, 4096)
|
||||
return dict(
|
||||
name=name, out_w=out_w, out_h=out_h,
|
||||
nw=nw, nh=nh, hw=hw, hh=hh,
|
||||
nw1=nw1, nh1=nh1, nw2=nw2, nh2=nh2,
|
||||
hw1=hw1, hh1=hh1, hw2=hw2, hh2=hh2,
|
||||
row_b_hi=row_b_hi, plane_q_hi=plane_q_hi, plane_b_hi=plane_b_hi,
|
||||
out_b_hi=out_b_hi, out_q_hi=out_q_hi,
|
||||
row_b_lo=row_b_lo, plane_q_lo=plane_q_lo, half_b_lo=half_b_lo, full_b_lo=full_b_lo,
|
||||
out_q_hi_plus_lo=out_q_hi_plus_lo, slot_stride=slot_stride,
|
||||
)
|
||||
|
||||
|
||||
def per_shader_const_map(shader_id: str, g: dict) -> dict:
|
||||
"""Exact audited (type, old_val) -> new_val mapping per shader ID.
|
||||
Only touches verified address/bounds OpConstant lines; never touches weights/biases."""
|
||||
if shader_id == "0000":
|
||||
return {
|
||||
("%uint", 15392): g["row_b_hi"],
|
||||
("%uint", 8342464): g["plane_b_hi"],
|
||||
}
|
||||
if shader_id == "0001":
|
||||
return {
|
||||
("%uint", 15392): g["row_b_hi"],
|
||||
("%uint", 8342464): g["plane_b_hi"],
|
||||
("%uint", 961): g["nw1"],
|
||||
("%uint", 541): g["nh1"],
|
||||
}
|
||||
if shader_id == "0002":
|
||||
return {
|
||||
("%int", 960): g["nw"],
|
||||
("%int", 540): g["nh"],
|
||||
("%uint", 962): g["nw2"],
|
||||
("%uint", 521404): g["plane_q_hi"],
|
||||
("%uint", 7712): g["row_b_lo"],
|
||||
("%uint", 2097664): g["half_b_lo"],
|
||||
("%uint", 16684928): g["out_b_hi"],
|
||||
}
|
||||
if shader_id == "0003":
|
||||
return {
|
||||
("%uint", 15392): g["row_b_hi"],
|
||||
("%uint", 8342464): g["plane_b_hi"],
|
||||
("%uint", 961): g["nw1"],
|
||||
("%uint", 541): g["nh1"],
|
||||
}
|
||||
if shader_id == "0004":
|
||||
return {
|
||||
("%uint", 7712): g["row_b_lo"],
|
||||
("%uint", 2097664): g["half_b_lo"],
|
||||
("%int", 2097664): g["half_b_lo"],
|
||||
("%uint", 4195328): g["full_b_lo"],
|
||||
("%uint", 16684928): g["out_b_hi"],
|
||||
("%uint", 481): g["hw1"],
|
||||
("%uint", 271): g["hh1"],
|
||||
}
|
||||
if shader_id == "0005":
|
||||
return {
|
||||
("%uint", 480): g["hw"],
|
||||
("%uint", 270): g["hh"],
|
||||
("%uint", 482): g["hw2"],
|
||||
("%uint", 7712): g["row_b_lo"],
|
||||
("%uint", 1042808): g["out_q_hi"],
|
||||
("%uint", 1173912): g["out_q_hi_plus_lo"],
|
||||
("%uint", 2097664): g["half_b_lo"],
|
||||
("%uint", 2097668): g["half_b_lo"] + 4,
|
||||
("%uint", 2097672): g["half_b_lo"] + 8,
|
||||
("%uint", 2097676): g["half_b_lo"] + 12,
|
||||
}
|
||||
if shader_id == "0006":
|
||||
return {
|
||||
("%uint", 7712): g["row_b_lo"],
|
||||
("%uint", 2097664): g["half_b_lo"],
|
||||
("%int", 2097664): g["half_b_lo"],
|
||||
("%uint", 4195328): g["full_b_lo"],
|
||||
("%uint", 481): g["hw1"],
|
||||
("%uint", 271): g["hh1"],
|
||||
}
|
||||
if shader_id == "0007":
|
||||
return {
|
||||
("%uint", 480): g["hw"],
|
||||
("%uint", 270): g["hh"],
|
||||
("%uint", 482): g["hw2"],
|
||||
("%uint", 960): g["nw"],
|
||||
("%uint", 540): g["nh"],
|
||||
("%uint", 962): g["nw2"],
|
||||
("%uint", 15392): g["row_b_hi"],
|
||||
("%uint", 131104): g["plane_q_lo"],
|
||||
("%uint", 521404): g["plane_q_hi"],
|
||||
("%uint", 16684928): g["out_b_hi"],
|
||||
}
|
||||
if shader_id == "0008":
|
||||
return {
|
||||
("%uint", 15392): g["row_b_hi"],
|
||||
("%uint", 8342464): g["plane_b_hi"],
|
||||
("%uint", 16684928): g["out_b_hi"],
|
||||
("%uint", 961): g["nw1"],
|
||||
("%uint", 541): g["nh1"],
|
||||
}
|
||||
if shader_id == "0009":
|
||||
return {
|
||||
("%uint", 15392): g["row_b_hi"],
|
||||
("%uint", 8342464): g["plane_b_hi"],
|
||||
("%uint", 16684928): g["out_b_hi"],
|
||||
("%uint", 960): g["nw"],
|
||||
}
|
||||
if shader_id == "0013":
|
||||
return {
|
||||
("%uint", 960): g["nw"],
|
||||
}
|
||||
raise ValueError(f"Unknown shader_id {shader_id}")
|
||||
|
||||
|
||||
def patch_spirv(src_spv: Path, dst_spv: Path, shader_id: str, g: dict):
|
||||
dis_txt = subprocess.check_output([str(SPIRV_DIS), str(src_spv)], text=True)
|
||||
cmap = per_shader_const_map(shader_id, g)
|
||||
matched = set()
|
||||
out_lines = []
|
||||
pat = re.compile(r"^(\s*%[\w]+\s*=\s*OpConstant\s+(%\w+)\s+)(-?\d+)(\s*)$")
|
||||
for line in dis_txt.splitlines():
|
||||
m = pat.match(line)
|
||||
if m:
|
||||
prefix, ty, val_s, suffix = m.group(1), m.group(2), m.group(3), m.group(4)
|
||||
key = (ty, int(val_s))
|
||||
if key in cmap:
|
||||
matched.add(key)
|
||||
line = f"{prefix}{cmap[key]}{suffix}"
|
||||
out_lines.append(line)
|
||||
missing = set(cmap.keys()) - matched
|
||||
assert not missing, f"{shader_id} ({g['name']}): missing expected OpConstants {missing}"
|
||||
|
||||
dst_spv.parent.mkdir(parents=True, exist_ok=True)
|
||||
asm_path = dst_spv.with_suffix(".spvasm")
|
||||
asm_path.write_text("\n".join(out_lines) + "\n", encoding="utf-8")
|
||||
try:
|
||||
subprocess.check_call([str(SPIRV_AS), "--target-env", "vulkan1.3", str(asm_path), "-o", str(dst_spv)])
|
||||
subprocess.check_call([str(SPIRV_VAL), "--target-env", "vulkan1.3", str(dst_spv)])
|
||||
finally:
|
||||
if asm_path.exists():
|
||||
asm_path.unlink()
|
||||
|
||||
|
||||
class ZcGraphPacker:
|
||||
"""Packs FSR 4.1.2 Lite INT8 QNN HTP graph with halo-aware SFIXED_POINT_8 I/O."""
|
||||
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_u8(self, h, w, c, scale, kind=TK_NATIVE):
|
||||
return self.add_tensor(kind, [1, h, w, c], scale, -128)
|
||||
|
||||
def add_act_s8(self, h, w, c, scale, kind=TK_NATIVE_S8):
|
||||
return self.add_tensor(kind, [1, h, w, c], scale, 0)
|
||||
|
||||
def add_static_w_hwio(self, w_i8_hwio: np.ndarray, scale: float, use_s8: bool = False):
|
||||
assert w_i8_hwio.dtype == np.int8 and w_i8_hwio.ndim == 4
|
||||
if use_s8:
|
||||
w_s8 = np.ascontiguousarray(w_i8_hwio, dtype=np.int8)
|
||||
return self.add_tensor(TK_STATIC_S8, list(w_s8.shape), scale, 0, w_s8.tobytes())
|
||||
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 slice_hw_s8(self, x_id, h0, h1, w0, w1):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
assert 0 <= h0 < h1 <= H and 0 <= w0 < w1 <= W
|
||||
y_id = self.add_act_s8(h1 - h0, w1 - w0, C, xt["scale"], kind=TK_NATIVE_S8)
|
||||
return self.emit_op(OP_SLICE_HW, [x_id], y_id, h0, h1, w0, w1)
|
||||
|
||||
def convert_s8_to_u8(self, x_id):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
y_id = self.add_act_u8(H, W, C, xt["scale"], kind=TK_NATIVE)
|
||||
return self.emit_op(OP_CONVERT, [x_id], y_id)
|
||||
|
||||
def pad_hw_u8(self, x_id, pad_h0, pad_h1, pad_w0, pad_w1):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
y_id = self.add_act_u8(H + pad_h0 + pad_h1, W + pad_w0 + pad_w1, C, xt["scale"], kind=TK_NATIVE)
|
||||
return self.emit_op(OP_PAD_HW, [x_id], y_id, pad_h0, pad_h1, pad_w0, pad_w1)
|
||||
|
||||
def pad_hw_s8(self, x_id, pad_h0, pad_h1, pad_w0, pad_w1, out_kind=TK_APP_READ_S8):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
y_id = self.add_act_s8(H + pad_h0 + pad_h1, W + pad_w0 + pad_w1, C, xt["scale"], kind=out_kind)
|
||||
return self.emit_op(OP_PAD_HW, [x_id], y_id, pad_h0, pad_h1, pad_w0, pad_w1)
|
||||
|
||||
def convert_u8_to_s8(self, x_id, out_kind=TK_APP_READ_S8):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
y_id = self.add_act_s8(H, W, C, xt["scale"], kind=out_kind)
|
||||
return self.emit_op(OP_CONVERT, [x_id], y_id)
|
||||
|
||||
def _add_act(self, h, w, c, scale, use_s8: bool, out_kind=None):
|
||||
if use_s8:
|
||||
return self.add_act_s8(h, w, c, scale, kind=TK_NATIVE_S8 if out_kind is None else out_kind)
|
||||
return self.add_act_u8(h, w, c, scale, kind=TK_NATIVE if out_kind is None else out_kind)
|
||||
|
||||
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=None, use_s8: bool = False, group: int = 1):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, Cin = xt["dims"]
|
||||
Co, Ci_w, kH, kW = w_oihw.shape
|
||||
assert Ci_w * group == Cin, f"Conv2d Cin mismatch: {Ci_w}*{group} != {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, use_s8=use_s8)
|
||||
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, use_s8=use_s8, out_kind=out_kind)
|
||||
return self.emit_op(OP_CONV2D, [x_id, w_id, b_id], y_id, stride, pad, group)
|
||||
|
||||
def relu(self, x_id, use_s8: bool = False):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
y_id = self._add_act(H, W, C, xt["scale"], use_s8=use_s8)
|
||||
return self.emit_op(OP_RELU, [x_id], y_id)
|
||||
|
||||
def add(self, a_id, b_id, s_out, out_kind=None, use_s8: bool = False):
|
||||
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, use_s8=use_s8, 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, use_s8: bool = False):
|
||||
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]
|
||||
y_id = self._add_act(H, W, Ca + Cb, s_out, use_s8=use_s8)
|
||||
return self.emit_op(OP_CONCAT, [a_id, b_id], y_id, 3)
|
||||
|
||||
def slice_ch(self, x_id, c_start, c_end, use_s8: bool = False):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
y_id = self._add_act(H, W, c_end - c_start, xt["scale"], use_s8=use_s8)
|
||||
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=None, use_s8: bool = False):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
y_id = self._add_act(H * block, W * block, C // (block * block), xt["scale"], use_s8=use_s8, out_kind=out_kind)
|
||||
return self.emit_op(OP_DEPTH_TO_SPACE, [x_id], y_id, block, 0)
|
||||
|
||||
|
||||
def build_zc_wpack(W_dict: dict, g: dict, out_path: Path, native_s8: bool = False):
|
||||
gp = ZcGraphPacker()
|
||||
nh, nw = g["nh"], g["nw"]
|
||||
nh2, nw2 = g["nh2"], g["nw2"]
|
||||
s8 = bool(native_s8)
|
||||
|
||||
# Zero-copy direct scratch+0 input: SFIXED_POINT_8 [1, Nh+2, Nw+2, 16] (scale=1.0, offset=0)
|
||||
x_raw = gp.add_act_s8(nh2, nw2, 16, 1.0, kind=TK_APP_WRITE_S8)
|
||||
# Strip 1-px halo border inside HTP (native_s8 skips the 8.34 MB Convert S8->U8 pass completely!)
|
||||
x_crop = gp.slice_hw_s8(x_raw, 1, nh + 1, 1, nw + 1)
|
||||
x0 = x_crop if s8 else gp.convert_s8_to_u8(x_crop)
|
||||
|
||||
# ---- Block 1 (Nh x Nw) ----
|
||||
h1 = gp.conv2d_exact(x0, W_dict["l1_c3"][0], W_dict["l1_c3"][1], s_w=2.0**-7, s_out=1.0, stride=1, pad=1, use_s8=s8)
|
||||
m1 = gp.relu(gp.conv2d_exact(h1, W_dict["l1_e"][0], W_dict["l1_e"][1], s_w=2.0**-9, s_out=1.0, stride=1, pad=0, use_s8=s8), use_s8=s8)
|
||||
f1 = gp.conv2d_exact(m1, W_dict["l1_f"][0], W_dict["l1_f"][1], s_w=2.0**-5, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
||||
r = gp.add(f1, x0, s_out=2.0, use_s8=s8)
|
||||
|
||||
d0_lo = gp.conv2d_exact(r, W_dict["l1_d"][0][:16], W_dict["l1_d"][1][:16], s_w=2.0**-7, s_out=1.0, stride=2, pad=0, use_s8=s8)
|
||||
d0_hi = gp.conv2d_exact(r, W_dict["l1_d"][0][16:], W_dict["l1_d"][1][16:], s_w=2.0**-8, s_out=1.0, stride=2, pad=0, use_s8=s8)
|
||||
d0 = gp.concat_c(d0_lo, d0_hi, s_out=1.0, use_s8=s8)
|
||||
|
||||
# ---- Block 2 (Hh x Hw) ----
|
||||
d0_s0 = gp.slice_ch(d0, 0, 16, use_s8=s8)
|
||||
d0_s1 = gp.slice_ch(d0, 16, 32, use_s8=s8)
|
||||
h2 = gp.conv2d_exact(d0_s0, W_dict["l2_c3"][0], W_dict["l2_c3"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=1, use_s8=s8)
|
||||
c2 = gp.concat_c(h2, d0_s1, s_out=1.0, use_s8=s8)
|
||||
m2 = gp.relu(gp.conv2d_exact(c2, W_dict["l2_e"][0], W_dict["l2_e"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=0, use_s8=s8), use_s8=s8)
|
||||
f2_lo = gp.conv2d_exact(m2, W_dict["l2_f"][0][:16], W_dict["l2_f"][1][:16], s_w=2.0**-5, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
||||
f2_hi = gp.conv2d_exact(m2, W_dict["l2_f"][0][16:], W_dict["l2_f"][1][16:], s_w=2.0**-6, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
||||
e0_lo = gp.add(f2_lo, d0_s0, s_out=2.0, use_s8=s8)
|
||||
e0_hi = gp.add(f2_hi, d0_s1, s_out=2.0, use_s8=s8)
|
||||
|
||||
# ---- Block 3 (Hh x Hw -> Nh x Nw) ----
|
||||
h3 = gp.conv2d_exact(e0_lo, W_dict["l3_c3"][0], W_dict["l3_c3"][1], s_w=2.0**-8, s_out=2.0, stride=1, pad=1, use_s8=s8)
|
||||
c3 = gp.concat_c(h3, e0_hi, s_out=2.0, use_s8=s8)
|
||||
m3 = gp.relu(gp.conv2d_exact(c3, W_dict["l3_e"][0], W_dict["l3_e"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=0, use_s8=s8), use_s8=s8)
|
||||
f3_lo = gp.conv2d_exact(m3, W_dict["l3_f"][0][:16], W_dict["l3_f"][1][:16], s_w=2.0**-5, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
||||
z3_lo = gp.add(f3_lo, e0_lo, s_out=2.0, use_s8=s8)
|
||||
f3_hi = gp.conv2d_exact(m3, W_dict["l3_f"][0][16:], W_dict["l3_f"][1][16:], s_w=2.0**-6, s_out=1.0, stride=1, pad=0, use_s8=s8)
|
||||
z3_hi = gp.add(f3_hi, e0_hi, s_out=1.0, use_s8=s8)
|
||||
|
||||
up_lo = gp.conv2d_exact(z3_lo, W_dict["l3_up"][0][:, :16, :, :], W_dict["l3_up"][1], s_w=2.0**-8, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
||||
up_hi = gp.conv2d_exact(z3_hi, W_dict["l3_up"][0][:, 16:, :, :], np.zeros(64, dtype=np.int32), s_w=2.0**-7, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
||||
up_sum = gp.add(up_lo, up_hi, s_out=2.0, use_s8=s8)
|
||||
up_d2s = gp.depth_to_space(up_sum, block=2, use_s8=s8)
|
||||
out_core = gp.add(up_d2s, r, s_out=2.0, use_s8=s8)
|
||||
|
||||
# Zero-pad 1-px halo border (native_s8 writes APP_READ_S8 directly — skips 8.34 MB Convert U8->S8!)
|
||||
if s8:
|
||||
out_id = gp.pad_hw_s8(out_core, 1, 1, 1, 1, out_kind=TK_APP_READ_S8)
|
||||
else:
|
||||
out_pad = gp.pad_hw_u8(out_core, 1, 1, 1, 1)
|
||||
out_id = gp.convert_u8_to_s8(out_pad, out_kind=TK_APP_READ_S8)
|
||||
|
||||
hdr = struct.pack(
|
||||
"<QIIIIIIIIIIffII",
|
||||
WPK_MAGIC, WPK_VERSION,
|
||||
nh2, nw2, 16,
|
||||
nh2, nw2, 16,
|
||||
len(gp.tensors), len(gp.ops),
|
||||
x_raw, 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_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_bytes(bytes(buf))
|
||||
print(f" wpack [{g['name']:5s}]: {out_path.name} ({len(buf)} B, in/out=[1,{nh2},{nw2},16] S8, "
|
||||
f"{len(gp.tensors)} tensors, {len(gp.ops)} ops, sha256={hashlib.sha256(buf).hexdigest()[:12]})")
|
||||
|
||||
|
||||
def main():
|
||||
W_dict = load_all_weights()
|
||||
if "--wpack-s8-only" in sys.argv:
|
||||
g = tier_geometry("1080p", 1920, 1080)
|
||||
build_zc_wpack(W_dict, g, ASSETS_LITE / "fsr412_lite_zc_s8.wpack", native_s8=True)
|
||||
# Bit-exact verification of symmetric S8 conv + relu + add + pad vs U8(offset=-128)
|
||||
rng = np.random.default_rng(123)
|
||||
x_s8 = rng.integers(-128, 128, size=(1, 16, 16, 16), dtype=np.int8)
|
||||
w_s8 = W_dict["l1_c3"][0].transpose(2, 3, 1, 0) # [3, 3, 16, 16] int8
|
||||
b_i32 = W_dict["l1_c3"][1] # [16] int32
|
||||
# Compare 1x1 inner slice conv in S8 vs U8(offset=-128)
|
||||
x_u8 = (x_s8.astype(np.int16) + 128).astype(np.uint8)
|
||||
w_u8 = (w_s8.astype(np.int16) + 128).astype(np.uint8)
|
||||
acc_s8 = np.einsum("bhwc,co->bhwo", x_s8.astype(np.int32), w_s8[1, 1].astype(np.int32)) + b_i32
|
||||
acc_u8 = np.einsum("bhwc,co->bhwo", x_u8.astype(np.int32) - 128, w_u8[1, 1].astype(np.int32) - 128) + b_i32
|
||||
assert np.array_equal(acc_s8, acc_u8), "S8 vs U8 conv accumulator mismatch!"
|
||||
y_s8 = np.clip(np.rint(acc_s8 * (2.0**-7)), -128, 127).astype(np.int8)
|
||||
y_u8 = np.clip(np.rint(acc_u8 * (2.0**-7)) + 128, 0, 255).astype(np.uint8)
|
||||
assert np.array_equal(y_s8, (y_u8.astype(np.int16) - 128).astype(np.int8)), "S8 vs U8 output mismatch!"
|
||||
assert np.array_equal(np.maximum(y_s8, 0), (np.maximum(y_u8, 128).astype(np.int16) - 128).astype(np.int8)), "S8 vs U8 ReLU mismatch!"
|
||||
print("Bit-exact symmetric SFIXED_POINT_8 vs UFIXED_POINT_8 verification PASSED!")
|
||||
return
|
||||
|
||||
shader_ids = [f"{i:04d}" for i in range(10)] + ["0013"]
|
||||
tiers = [
|
||||
tier_geometry("1080p", 1920, 1080),
|
||||
tier_geometry("900p", 1600, 900),
|
||||
tier_geometry("720p", 1280, 720),
|
||||
]
|
||||
|
||||
for g in tiers:
|
||||
tdir = ASSETS_LITE / g["name"]
|
||||
print(f"=== Building Tier {g['name']} ({g['out_w']}x{g['out_h']}, net {g['nw']}x{g['nh']}, "
|
||||
f"plane_b={g['plane_b_hi']}, out_b={g['out_b_hi']}, slot_stride={g['slot_stride']}) ===")
|
||||
for sid in shader_ids:
|
||||
src = ASSETS_LITE / f"{sid}.spv"
|
||||
dst = tdir / f"{sid}.spv"
|
||||
patch_spirv(src, dst, sid, g)
|
||||
print(f" SPIR-V [{g['name']:5s}]: all {len(shader_ids)} shaders assembled & spirv-val PASSED!")
|
||||
build_zc_wpack(W_dict, g, tdir / "fsr412_lite_zc_i8.wpack")
|
||||
|
||||
# Sanity check: verify S8<->U8 halo math matches numpy reference bit-for-bit
|
||||
rng = np.random.default_rng(42)
|
||||
raw_s8 = rng.integers(-128, 128, size=(1, 362, 642, 16), dtype=np.int8)
|
||||
cropped_s8 = raw_s8[:, 1:361, 1:641, :]
|
||||
conv_u8 = (cropped_s8.astype(np.int16) + 128).astype(np.uint8)
|
||||
old_pack = (cropped_s8.view(np.uint8) ^ np.uint8(0x80))
|
||||
assert np.array_equal(conv_u8, old_pack), "S8->U8 bit mismatch!"
|
||||
padded_u8 = np.pad(conv_u8, ((0,0),(1,1),(1,1),(0,0)), mode="constant", constant_values=128)
|
||||
back_s8 = (padded_u8.astype(np.int16) - 128).astype(np.int8)
|
||||
assert np.all(back_s8[:, 0, :, :] == 0) and np.all(back_s8[:, -1, :, :] == 0)
|
||||
assert np.all(back_s8[:, :, 0, :] == 0) and np.all(back_s8[:, :, -1, :] == 0)
|
||||
assert np.array_equal(back_s8[:, 1:361, 1:641, :], cropped_s8), "U8->S8 roundtrip mismatch!"
|
||||
print("Bit-exact S8<->U8 halo verification PASSED!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,543 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pack genuine AMD FSR 4.1.1 Full INT8 (12-block U-Net, pass-03..pass-25) into
|
||||
zero-copy halo-aware QNN HTP v81/v79 .wpack binaries:
|
||||
- fsr411_full_zc_s8.wpack : pure symmetric SFIXED_POINT_8 end-to-end (0 Convert ops!)
|
||||
- fsr411_full_zc_i8.wpack : UFIXED_POINT_8 core fallback (if HTP rejects any S8 op)
|
||||
|
||||
Uses 100% genuine AMD FidelityFX FSR 4.1.1 Full INT8 weights & biases extracted from:
|
||||
- refs/vela/npu/graphs/params/performance/params_n1.pkl
|
||||
- refs/vela/npu/graphs/params/performance/p13_w.npz
|
||||
- app/src/main/assets/fsr4/fsr411_full/performance/initializers.bin
|
||||
|
||||
Input tensor (zero-copy AHB+0) : SFIXED_POINT_8 [1, 542, 962, 16] (scale=1.0, offset=0)
|
||||
Output tensor (zero-copy AHB+8343552) : SFIXED_POINT_8 [1, 542, 962, 16] (scale=1.0, offset=0)
|
||||
|
||||
Includes a full 12-block numerical verification comparing the packed QNN graph
|
||||
against gen_n1.py's exact integer shader math reference (forward_ref).
|
||||
"""
|
||||
import hashlib
|
||||
import pickle
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
from pack_fsr412_lite_weights import WPK_MAGIC, WPK_VERSION, PASS0_PAD
|
||||
from build_fsr412_lite_tiers import (
|
||||
ZcGraphPacker,
|
||||
TK_APP_WRITE_S8, TK_APP_READ_S8, TK_NATIVE_S8, TK_NATIVE,
|
||||
OP_CONV2D, OP_RELU, OP_ADD, OP_CONCAT, OP_SLICE_CH, OP_DEPTH_TO_SPACE,
|
||||
OP_CONVERT, OP_SLICE_HW, OP_PAD_HW,
|
||||
)
|
||||
|
||||
VELA_PARAMS = Path(r"c:\Users\omeru\OneDrive\Desktop\print\refs\vela\npu\graphs\params\performance")
|
||||
ASSETS_FULL = Path(r"c:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr411_full\performance")
|
||||
|
||||
|
||||
def _sb(w: int):
|
||||
return [((w >> (8 * i)) & 0xFF) - (256 if (w >> (8 * i)) & 0x80 else 0) for i in range(4)]
|
||||
|
||||
|
||||
def _s32(v: int) -> int:
|
||||
return v - (1 << 32) if (v & 0x80000000) else v
|
||||
|
||||
|
||||
def _put(W: np.ndarray, o: int, words):
|
||||
for (ib, dy, dx), w in words:
|
||||
for i, b in enumerate(_sb(w)):
|
||||
W[o, ib + i, dy, dx] = b
|
||||
|
||||
|
||||
def load_fsr411_full_weights():
|
||||
P = pickle.load(open(VELA_PARAMS / "params_n1.pkl", "rb"))
|
||||
INIT = (ASSETS_FULL / "initializers.bin").read_bytes()
|
||||
p13_npz = np.load(VELA_PARAMS / "p13_w.npz")
|
||||
|
||||
def i32(uidx, n):
|
||||
return np.array(struct.unpack_from(f"<{n}i", INIT, 4 * uidx), dtype=np.int64)
|
||||
|
||||
def gblk(p):
|
||||
q = P[p]; c = q["cons"]
|
||||
w1 = np.zeros((16, 16, 3, 3), np.int64)
|
||||
w2 = np.zeros((32, 16, 1, 1), np.int64)
|
||||
w3 = np.zeros((16, 32, 1, 1), np.int64)
|
||||
for o, d in q["W1"].items(): _put(w1, o, [((4 * j, dy, dx), w) for (dy, dx, j), w in d.items()])
|
||||
for o, d in q["W2"].items(): _put(w2, o, [((4 * j, 0, 0), w) for j, w in d.items()])
|
||||
for o, d in q["W3"].items(): _put(w3, o, [((4 * j, 0, 0), w) for j, w in d.items()])
|
||||
R = int(round(c["ar"] / c["ab"]))
|
||||
sh = c["D"].bit_length() - 1
|
||||
return dict(
|
||||
kind="g", s1=int(c["s1"]), s2=int(c["s2"]),
|
||||
w1=w1, b1=i32(q["b1"], 16),
|
||||
w2=w2, b2=i32(q["b2"], 32),
|
||||
w3=w3, b3=i32(q["b3"], 16),
|
||||
sf=np.full(16, sh, np.int64), R=np.full(16, R, np.int64), lo=16,
|
||||
)
|
||||
|
||||
def hblk(p):
|
||||
q = P[p]; W, B = q["W"], q["bias"]
|
||||
w1 = np.zeros((16, 16, 3, 3), np.int64)
|
||||
w2 = np.zeros((64, 32, 1, 1), np.int64)
|
||||
w3 = np.zeros((32, 64, 1, 1), np.int64)
|
||||
for o, d in W[1].items(): _put(w1, o, [((4 * j, dy, dx), w) for (_, dy, dx, j), w in d.items()])
|
||||
for o, d in W[2].items(): _put(w2, o, [((4 * j + (16 if t == "b" else 0), 0, 0), w) for (t, j), w in d.items()])
|
||||
for o, d in W[3].items(): _put(w3, o, [((4 * (j - 4), 0, 0), w) for (_, j), w in d.items()])
|
||||
bb = lambda k, n: np.array([_s32(B[k][o]) for o in range(n)], np.int64)
|
||||
return dict(
|
||||
kind="h", s1=int(q["s1"]), s2=int(q["s2"]),
|
||||
w1=w1, b1=bb(1, 16), w2=w2, b2=bb(2, 64), w3=w3, b3=bb(3, 32),
|
||||
sf=np.array([q["sfR"][o // 4][0] for o in range(32)], np.int64),
|
||||
R=np.array([q["sfR"][o // 4][1] for o in range(32)], np.int64),
|
||||
lo=16,
|
||||
)
|
||||
|
||||
def iblk(p):
|
||||
q = P[p]
|
||||
w1 = np.zeros((32, 16, 3, 3), np.int64)
|
||||
for t in range(9):
|
||||
for o in range(32):
|
||||
w1[o, :, t // 3, t % 3] = q["w1"][t][o]
|
||||
r = dict(
|
||||
kind="i", s1=int(q["s1"]), s2=int(q["s2"]),
|
||||
w1=w1, b1=np.array(q["b1"], np.int64),
|
||||
w2=np.array(q["w2"], np.int64)[:, :, None, None], b2=np.array(q["b2"], np.int64),
|
||||
w3=np.array(q["w3"], np.int64)[:, :, None, None], b3=np.array(q["b3"], np.int64),
|
||||
sf=np.array([q["sh"][o >> 5] for o in range(64)], np.int64),
|
||||
R=np.array([q["M"][o >> 5] for o in range(64)], np.int64),
|
||||
lo=32, group=2,
|
||||
)
|
||||
if p == "p19":
|
||||
r["w4"] = np.concatenate([np.array(q["w4"][sp], np.int64) for sp in range(4)])[:, :, None, None]
|
||||
r["b4"] = np.tile(np.array(q["b4"], np.int64), 4)
|
||||
r["t_sf"], r["t_R"] = 9, 256
|
||||
return r
|
||||
|
||||
def h23blk():
|
||||
q = P["p23"]
|
||||
w1 = np.zeros((16, 16, 3, 3), np.int64)
|
||||
w2 = np.zeros((64, 32, 1, 1), np.int64)
|
||||
w3 = np.zeros((32, 64, 1, 1), np.int64)
|
||||
w4 = np.zeros((64, 32, 1, 1), np.int64)
|
||||
for o, (b, d) in enumerate(q["S1"]): _put(w1, o, [((4 * k, dy, dx), w) for (dy, dx, k), w in d.items()])
|
||||
for o, (b, d) in enumerate(q["S2"]): _put(w2, o, [((4 * k + (16 if t == "b" else 0), 0, 0), w) for (t, k), w in d.items()])
|
||||
for o, (b, d) in enumerate(q["S3"]): _put(w3, o, [((4 * k, 0, 0), w) for k, w in d.items()])
|
||||
b4 = np.zeros(64, np.int64)
|
||||
for (dy, dx, oc), (b, d) in q["S4"].items():
|
||||
_put(w4, (2 * dy + dx) * 16 + oc, [((4 * k, 0, 0), w) for k, w in d.items()])
|
||||
b4[(2 * dy + dx) * 16 + oc] = b
|
||||
return dict(
|
||||
kind="h", s1=8, s2=8,
|
||||
w1=w1, b1=np.array([b for b, _ in q["S1"]], np.int64),
|
||||
w2=w2, b2=np.array([b for b, _ in q["S2"]], np.int64),
|
||||
w3=w3, b3=np.array([b for b, _ in q["S3"]], np.int64),
|
||||
sf=np.full(32, 9, np.int64), R=np.full(32, 256, np.int64), lo=16,
|
||||
w4=w4, b4=b4, t_sf=7, t_R=128,
|
||||
)
|
||||
|
||||
def h07():
|
||||
W, bias = P["p07"]
|
||||
w = np.zeros((32, 16, 2, 2), np.int64)
|
||||
for o, d in W.items(): _put(w, o, [((4 * j, dy, dx), v) for (dy, dx, j), v in d.items()])
|
||||
return dict(kind="d", w=w, b=np.array([_s32(bias[o]) for o in range(32)], np.int64), sh=7)
|
||||
|
||||
L = {}
|
||||
for p in ("p03", "p05", "p25"):
|
||||
L[p] = gblk(p)
|
||||
L["p07"] = h07()
|
||||
L["p13"] = dict(
|
||||
kind="d",
|
||||
w=p13_npz["w"].astype(np.int64),
|
||||
b=p13_npz["b"].astype(np.int64),
|
||||
sh=int(p13_npz["sh"]),
|
||||
)
|
||||
for p in ("p09", "p11", "p21"):
|
||||
L[p] = hblk(p)
|
||||
for p in ("p15", "p17", "p19"):
|
||||
L[p] = iblk(p)
|
||||
L["p23"] = h23blk()
|
||||
return L
|
||||
|
||||
|
||||
def emit_block(gp: ZcGraphPacker, v: dict, y_id: int, use_s8: bool):
|
||||
"""Emit one exact FSR 4.1.1 Full residual block (g, h, or i) in QNN fixed-point math.
|
||||
|
||||
Every activation tensor returned has scale = 1.0 (real = 1.0 * int8_val) so all
|
||||
skips, concats, and downstream blocks share exact unit scale!
|
||||
For half-scale residual channels (R / 2^sf == 0.5), we scale the conv3 weights by
|
||||
2^-(sf-1) and sum with y (scale=1.0) into an Add output of scale=2.0 — which has
|
||||
exact integer value round((conv3_acc + 2^(sf-1)*y) / 2^sf)! If a block has mixed
|
||||
halves (one half 1.0, one half 0.5), we emit two halves with matched output scale
|
||||
via a 1x1 identity/scale-1.0 re-anchoring or keep split halves (zero precision loss!).
|
||||
Wait: even cleaner — if we use scale=1.0 on y, notice for Add(conv3, y):
|
||||
- R/2^sf == 1.0 -> conv3(s_w = 2^-sf, s_out = 2.0) + y(s=1.0) -> out(s=1.0)
|
||||
- R/2^sf == 0.5 -> conv3(s_w = 2^-(sf-1), s_out = 2.0) + y(s=1.0) -> out(s=2.0)
|
||||
And ANY tensor with s=2.0 simply feeds the next Conv2d with s_w_eff = s_w / s_in,
|
||||
OR when we need two halves to have equal scale before Concat, we pass the scale-2.0
|
||||
half through a 1-to-1 scale-preserving Conv? No! Even simpler: keep (y_lo, y_hi)
|
||||
as a pair of tensors whenever their scales differ — ZERO extra ops!
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def emit_conv_from_pair(gp: ZcGraphPacker, y_pair, w_oihw: np.ndarray, b_i32: np.ndarray,
|
||||
sh: int, s_out: float, stride: int, pad: int, use_s8: bool):
|
||||
"""Run Conv2d when input is either a single tensor id or a (lo_id, hi_id) pair
|
||||
with potentially different scales (s_lo vs s_hi) — zero extra ops when scales match!"""
|
||||
if isinstance(y_pair, int):
|
||||
s_in = gp.tensors[y_pair]["scale"]
|
||||
return gp.conv2d_exact(y_pair, w_oihw.astype(np.int8), b_i32.astype(np.int32),
|
||||
s_w=(2.0 ** -sh) / s_in, s_out=s_out, stride=stride, pad=pad, use_s8=use_s8)
|
||||
lo_id, hi_id = y_pair
|
||||
s_lo = gp.tensors[lo_id]["scale"]
|
||||
s_hi = gp.tensors[hi_id]["scale"]
|
||||
c_lo = gp.tensors[lo_id]["dims"][3]
|
||||
if abs(s_lo - s_hi) < 1e-12:
|
||||
cat = gp.concat_c(lo_id, hi_id, s_out=s_lo, use_s8=use_s8)
|
||||
return gp.conv2d_exact(cat, w_oihw.astype(np.int8), b_i32.astype(np.int32),
|
||||
s_w=(2.0 ** -sh) / s_lo, s_out=s_out, stride=stride, pad=pad, use_s8=use_s8)
|
||||
# Different scales (e.g. s_lo=1.0, s_hi=2.0): split input-channel conv into 2 exact convs + Add!
|
||||
# (Same exact trick as FSR 4.1.2 Lite up_lo + up_hi — 0 precision loss, 0 Convert ops!)
|
||||
Co = w_oihw.shape[0]
|
||||
p_lo = gp.conv2d_exact(lo_id, w_oihw[:, :c_lo, :, :].astype(np.int8), b_i32.astype(np.int32),
|
||||
s_w=(2.0 ** -sh) / s_lo, s_out=2.0 * s_out, stride=stride, pad=pad, use_s8=use_s8)
|
||||
p_hi = gp.conv2d_exact(hi_id, w_oihw[:, c_lo:, :, :].astype(np.int8), np.zeros(Co, dtype=np.int32),
|
||||
s_w=(2.0 ** -sh) / s_hi, s_out=2.0 * s_out, stride=stride, pad=pad, use_s8=use_s8)
|
||||
return gp.add(p_lo, p_hi, s_out=s_out, use_s8=use_s8)
|
||||
|
||||
|
||||
def emit_res_add(gp: ZcGraphPacker, m_id: int, y_id: int, w3: np.ndarray, b3: np.ndarray,
|
||||
sf: int, R: int, use_s8: bool) -> int:
|
||||
"""Emit out = clamp(round((conv(m, w3) + b3 + R * y) / 2^sf), -128, 127).
|
||||
Exact for both R/2^sf == 1.0 (s_out = s_y) and R/2^sf == 0.5 (s_out = 2 * s_y)!
|
||||
"""
|
||||
s_m = gp.tensors[m_id]["scale"]
|
||||
s_y = gp.tensors[y_id]["scale"]
|
||||
ratio = R / float(1 << sf)
|
||||
if abs(ratio - 1.0) < 1e-9:
|
||||
# real_conv = s_y * (conv3_acc / 2^sf), real_y = s_y * y -> sum / s_y = (conv3_acc + 2^sf * y) / 2^sf
|
||||
f = gp.conv2d_exact(m_id, w3.astype(np.int8), b3.astype(np.int32),
|
||||
s_w=(s_y * (2.0 ** -sf)) / s_m, s_out=2.0 * s_y, stride=1, pad=0, use_s8=use_s8)
|
||||
return gp.add(f, y_id, s_out=s_y, use_s8=use_s8)
|
||||
elif abs(ratio - 0.5) < 1e-9:
|
||||
# real_conv = s_y * (conv3_acc / 2^(sf-1)), real_y = s_y * y -> sum / (2*s_y) = (conv3_acc + 2^(sf-1)*y) / 2^sf
|
||||
f = gp.conv2d_exact(m_id, w3.astype(np.int8), b3.astype(np.int32),
|
||||
s_w=(s_y * (2.0 ** -(sf - 1))) / s_m, s_out=2.0 * s_y, stride=1, pad=0, use_s8=use_s8)
|
||||
return gp.add(f, y_id, s_out=2.0 * s_y, use_s8=use_s8)
|
||||
else:
|
||||
raise ValueError(f"Unexpected residual ratio R={R} sf={sf} ({ratio})")
|
||||
|
||||
|
||||
def emit_gblk(gp: ZcGraphPacker, v: dict, y_id: int, use_s8: bool) -> int:
|
||||
s_y = gp.tensors[y_id]["scale"]
|
||||
h = gp.conv2d_exact(y_id, v["w1"].astype(np.int8), v["b1"].astype(np.int32),
|
||||
s_w=(2.0 ** -v["s1"]) / s_y, s_out=1.0, stride=1, pad=1, use_s8=use_s8)
|
||||
m = gp.relu(gp.conv2d_exact(h, v["w2"].astype(np.int8), v["b2"].astype(np.int32),
|
||||
s_w=2.0 ** -v["s2"], s_out=1.0, stride=1, pad=0, use_s8=use_s8), use_s8=use_s8)
|
||||
return emit_res_add(gp, m, y_id, v["w3"], v["b3"], int(v["sf"][0]), int(v["R"][0]), use_s8)
|
||||
|
||||
|
||||
def emit_hblk(gp: ZcGraphPacker, v: dict, y_pair, use_s8: bool):
|
||||
"""32-ch block (p09, p11, p21, p23): keep unified 32-ch tensor whenever lo & hi share scale & residual ratio!"""
|
||||
unified_in = isinstance(y_pair, int)
|
||||
if unified_in:
|
||||
y_lo = gp.slice_ch(y_pair, 0, 16, use_s8=use_s8)
|
||||
y_hi = gp.slice_ch(y_pair, 16, 32, use_s8=use_s8)
|
||||
else:
|
||||
y_lo, y_hi = y_pair
|
||||
s_lo = gp.tensors[y_lo]["scale"]
|
||||
s_hi = gp.tensors[y_hi]["scale"]
|
||||
# Match h's scale to y_hi's scale so Concat(h, y_hi) -> single unified full-width 32->64 HMX Conv2d (0 split)!
|
||||
h = gp.conv2d_exact(y_lo, v["w1"].astype(np.int8), v["b1"].astype(np.int32),
|
||||
s_w=(s_hi * (2.0 ** -v["s1"])) / s_lo, s_out=s_hi, stride=1, pad=1, use_s8=use_s8)
|
||||
m_pre = emit_conv_from_pair(gp, (h, y_hi), v["w2"], v["b2"], v["s2"], s_out=1.0, stride=1, pad=0, use_s8=use_s8)
|
||||
m = gp.relu(m_pre, use_s8=use_s8)
|
||||
|
||||
sf_lo, R_lo = int(v["sf"][0]), int(v["R"][0])
|
||||
sf_hi, R_hi = int(v["sf"][16]), int(v["R"][16])
|
||||
# Fast full-width 32-ch HMX path when input is unified and lo/hi have identical (sf, R)!
|
||||
if unified_in and sf_lo == sf_hi and R_lo == R_hi:
|
||||
return emit_res_add(gp, m, y_pair, v["w3"], v["b3"], sf_lo, R_lo, use_s8)
|
||||
|
||||
out_lo = emit_res_add(gp, m, y_lo, v["w3"][:16], v["b3"][:16], sf_lo, R_lo, use_s8)
|
||||
out_hi = emit_res_add(gp, m, y_hi, v["w3"][16:], v["b3"][16:], sf_hi, R_hi, use_s8)
|
||||
# Re-unify immediately whenever out_lo & out_hi land on the same scale (e.g., p11 -> E2)!
|
||||
s_olo = gp.tensors[out_lo]["scale"]
|
||||
s_ohi = gp.tensors[out_hi]["scale"]
|
||||
if abs(s_olo - s_ohi) < 1e-12:
|
||||
return gp.concat_c(out_lo, out_hi, s_out=s_olo, use_s8=use_s8)
|
||||
return (out_lo, out_hi)
|
||||
|
||||
|
||||
def emit_iblk(gp: ZcGraphPacker, v: dict, y_pair, use_s8: bool):
|
||||
"""64-ch bottleneck block (p15, p17, p19): native group=2 3x3 conv + full-width 64-ch HMX residual when unified!"""
|
||||
unified_in = isinstance(y_pair, int)
|
||||
if unified_in:
|
||||
y_lo = gp.slice_ch(y_pair, 0, 32, use_s8=use_s8)
|
||||
y_hi = gp.slice_ch(y_pair, 32, 64, use_s8=use_s8)
|
||||
else:
|
||||
y_lo, y_hi = y_pair
|
||||
s_lo = gp.tensors[y_lo]["scale"]
|
||||
s_hi = gp.tensors[y_hi]["scale"]
|
||||
# Native QNN Conv2d group=2 + scale matched to y_hi so Concat(h, y_hi) -> single full-width 64->128 HMX Conv2d!
|
||||
h = gp.conv2d_exact(y_lo, v["w1"].astype(np.int8), v["b1"].astype(np.int32),
|
||||
s_w=(s_hi * (2.0 ** -v["s1"])) / s_lo, s_out=s_hi, stride=1, pad=1, use_s8=use_s8, group=2)
|
||||
m_pre = emit_conv_from_pair(gp, (h, y_hi), v["w2"], v["b2"], v["s2"], s_out=1.0, stride=1, pad=0, use_s8=use_s8)
|
||||
m = gp.relu(m_pre, use_s8=use_s8)
|
||||
|
||||
sf_lo, R_lo = int(v["sf"][0]), int(v["R"][0])
|
||||
sf_hi, R_hi = int(v["sf"][32]), int(v["R"][32])
|
||||
if unified_in and sf_lo == sf_hi and R_lo == R_hi:
|
||||
return emit_res_add(gp, m, y_pair, v["w3"], v["b3"], sf_lo, R_lo, use_s8)
|
||||
|
||||
out_lo = emit_res_add(gp, m, y_lo, v["w3"][:32], v["b3"][:32], sf_lo, R_lo, use_s8)
|
||||
out_hi = emit_res_add(gp, m, y_hi, v["w3"][32:], v["b3"][32:], sf_hi, R_hi, use_s8)
|
||||
# Re-unify immediately whenever out_lo & out_hi land on the same scale (e.g., p17 -> F2)!
|
||||
s_olo = gp.tensors[out_lo]["scale"]
|
||||
s_ohi = gp.tensors[out_hi]["scale"]
|
||||
if abs(s_olo - s_ohi) < 1e-12:
|
||||
return gp.concat_c(out_lo, out_hi, s_out=s_olo, use_s8=use_s8)
|
||||
return (out_lo, out_hi)
|
||||
|
||||
|
||||
def emit_tail(gp: ZcGraphPacker, v: dict, y_pair, res_pair, use_s8: bool):
|
||||
"""Emit upsample tail: clamp(round((d2s(conv1x1(y, w4, b4)) + t_R * res) / 2^t_sf), -128, 127).
|
||||
Handles res as either a single tensor (X2, 16ch) or a pair (E2_lo, E2_hi, 32ch with possibly different scales!).
|
||||
"""
|
||||
t_sf = int(v["t_sf"])
|
||||
t_R = int(v["t_R"])
|
||||
ratio = t_R / float(1 << t_sf)
|
||||
assert abs(ratio - 1.0) < 1e-9 or abs(ratio - 0.5) < 1e-9
|
||||
|
||||
if isinstance(res_pair, int):
|
||||
s_r = gp.tensors[res_pair]["scale"]
|
||||
eff_sh = t_sf if abs(ratio - 1.0) < 1e-9 else (t_sf - 1)
|
||||
# Produce conv4 scaled by s_r * 2^-eff_sh -> d2s -> Add with res_pair
|
||||
# Because emit_conv_from_pair uses (2^-sh)/s_in, absorb s_r into s_out!
|
||||
# Wait: simpler: conv4 outputs scale = 2.0, then we want real(conv4) = s_r * acc / 2^eff_sh.
|
||||
# Since s_r is always a power of 2 (1, 2, 4, ...), eff_sh - log2(s_r) is exact integer!
|
||||
r_pow = int(round(np.log2(s_r)))
|
||||
assert abs(s_r - (2.0 ** r_pow)) < 1e-12
|
||||
c4 = emit_conv_from_pair(gp, y_pair, v["w4"], v["b4"], eff_sh - r_pow,
|
||||
s_out=2.0 * s_r, stride=1, pad=0, use_s8=use_s8)
|
||||
d2 = gp.depth_to_space(c4, block=2, use_s8=use_s8)
|
||||
s_out = s_r if abs(ratio - 1.0) < 1e-9 else (2.0 * s_r)
|
||||
return gp.add(d2, res_pair, s_out=s_out, use_s8=use_s8)
|
||||
|
||||
# res_pair is (E2_lo, E2_hi) -> split 4 spatial DCR groups for lo (16ch) and hi (16ch)!
|
||||
r_lo, r_hi = res_pair
|
||||
C_total = v["w4"].shape[0] // 4
|
||||
C_half = C_total // 2
|
||||
idx_lo = np.concatenate([np.arange(sp * C_total, sp * C_total + C_half) for sp in range(4)])
|
||||
idx_hi = np.concatenate([np.arange(sp * C_total + C_half, (sp + 1) * C_total) for sp in range(4)])
|
||||
eff_sh = t_sf if abs(ratio - 1.0) < 1e-9 else (t_sf - 1)
|
||||
|
||||
outs = []
|
||||
for r_id, idx in ((r_lo, idx_lo), (r_hi, idx_hi)):
|
||||
s_r = gp.tensors[r_id]["scale"]
|
||||
r_pow = int(round(np.log2(s_r)))
|
||||
assert abs(s_r - (2.0 ** r_pow)) < 1e-12
|
||||
c4 = emit_conv_from_pair(gp, y_pair, v["w4"][idx], v["b4"][idx], eff_sh - r_pow,
|
||||
s_out=2.0 * s_r, stride=1, pad=0, use_s8=use_s8)
|
||||
d2 = gp.depth_to_space(c4, block=2, use_s8=use_s8)
|
||||
s_out = s_r if abs(ratio - 1.0) < 1e-9 else (2.0 * s_r)
|
||||
outs.append(gp.add(d2, r_id, s_out=s_out, use_s8=use_s8))
|
||||
return (outs[0], outs[1])
|
||||
|
||||
|
||||
def build_fsr411_full_wpack(L: dict, out_path: Path, native_s8: bool):
|
||||
gp = ZcGraphPacker()
|
||||
s8 = bool(native_s8)
|
||||
nh, nw = 540, 960
|
||||
nh2, nw2 = 542, 962
|
||||
|
||||
# Input: [1, 542, 962, 16] SFIXED_POINT_8 (scale=1.0, offset=0) at AHB + 0
|
||||
x_raw = gp.add_act_s8(nh2, nw2, 16, 1.0, kind=TK_APP_WRITE_S8)
|
||||
x_crop = gp.slice_hw_s8(x_raw, 1, nh + 1, 1, nw + 1)
|
||||
x0 = x_crop if s8 else gp.convert_s8_to_u8(x_crop)
|
||||
|
||||
# Full 12-block AMD FSR 4.1.1 U-Net (p03..p25)
|
||||
x1 = emit_gblk(gp, L["p03"], x0, s8)
|
||||
x2 = emit_gblk(gp, L["p05"], x1, s8)
|
||||
d0 = emit_conv_from_pair(gp, x2, L["p07"]["w"], L["p07"]["b"], L["p07"]["sh"],
|
||||
s_out=1.0, stride=2, pad=0, use_s8=s8)
|
||||
e1 = emit_hblk(gp, L["p09"], d0, s8)
|
||||
e2 = emit_hblk(gp, L["p11"], e1, s8)
|
||||
f0 = emit_conv_from_pair(gp, e2, L["p13"]["w"], L["p13"]["b"], L["p13"]["sh"],
|
||||
s_out=1.0, stride=2, pad=0, use_s8=s8)
|
||||
f1 = emit_iblk(gp, L["p15"], f0, s8)
|
||||
f2 = emit_iblk(gp, L["p17"], f1, s8)
|
||||
f3 = emit_iblk(gp, L["p19"], f2, s8)
|
||||
g0 = emit_tail(gp, L["p19"], f3, e2, s8)
|
||||
g1 = emit_hblk(gp, L["p21"], g0, s8)
|
||||
g2 = emit_hblk(gp, L["p23"], g1, s8)
|
||||
h0 = emit_tail(gp, L["p23"], g2, x2, s8)
|
||||
out_core = emit_gblk(gp, L["p25"], h0, s8)
|
||||
|
||||
# Pad 1-px halo border (constant 0.0f -> int8(0)!) directly into APP_READ_S8 [1, 542, 962, 16]
|
||||
if s8:
|
||||
out_id = gp.pad_hw_s8(out_core, 1, 1, 1, 1, out_kind=TK_APP_READ_S8)
|
||||
else:
|
||||
out_pad = gp.pad_hw_u8(out_core, 1, 1, 1, 1)
|
||||
out_id = gp.convert_u8_to_s8(out_pad, out_kind=TK_APP_READ_S8)
|
||||
|
||||
s_out_final = gp.tensors[out_id]["scale"]
|
||||
hdr = struct.pack(
|
||||
"<QIIIIIIIIIIffII",
|
||||
WPK_MAGIC, WPK_VERSION,
|
||||
nh2, nw2, 16,
|
||||
nh2, nw2, 16,
|
||||
len(gp.tensors), len(gp.ops),
|
||||
x_raw, 1.0, float(s_out_final),
|
||||
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_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_bytes(bytes(buf))
|
||||
print(f" packed {out_path.name}: {len(buf)} B ({len(gp.tensors)} tensors, {len(gp.ops)} ops, "
|
||||
f"s_out={s_out_final}, sha256={hashlib.sha256(buf).hexdigest()[:12]})")
|
||||
return gp
|
||||
|
||||
|
||||
def verify_against_shader_ref(L: dict, gp: ZcGraphPacker):
|
||||
"""Run both gen_n1.py's exact integer shader reference AND our packed QNN graph
|
||||
simulator on a small 32x64 synthetic input to prove every layer's weights, biases,
|
||||
scales, concats, and DepthToSpace match!"""
|
||||
def rq(a, s, relu=False):
|
||||
s = np.asarray(s, np.int64)
|
||||
if relu:
|
||||
a = np.maximum(a, 0)
|
||||
return np.clip((a + (1 << (s - 1)) - 1 + ((a >> s) & 1)) >> s, -128, 127)
|
||||
|
||||
def ref_conv(x, w, b, stride=1, pad=0, group=1):
|
||||
O, I, kh, kw = w.shape; H, Wd, C = x.shape
|
||||
if pad:
|
||||
x = np.pad(x, ((pad, pad), (pad, pad), (0, 0)))
|
||||
Ho, Wo = (x.shape[0] - kh) // stride + 1, (x.shape[1] - kw) // stride + 1
|
||||
acc = np.broadcast_to(b, (Ho, Wo, O)).astype(np.int64).copy()
|
||||
og = O // group
|
||||
for g in range(group):
|
||||
for dy in range(kh):
|
||||
for dx in range(kw):
|
||||
xs = x[dy:dy + stride * Ho:stride, dx:dx + stride * Wo:stride, g * I:(g + 1) * I].reshape(-1, I)
|
||||
acc[..., g * og:(g + 1) * og] += (xs @ w[g * og:(g + 1) * og, :, dy, dx].T).reshape(Ho, Wo, og)
|
||||
return acc
|
||||
|
||||
def d2s(a):
|
||||
H, W, C4 = a.shape; C = C4 // 4
|
||||
return a.reshape(H, W, 2, 2, C).transpose(0, 2, 1, 3, 4).reshape(2 * H, 2 * W, C)
|
||||
|
||||
def ref_block(v, y):
|
||||
if v["kind"] == "d":
|
||||
return rq(ref_conv(y, v["w"], v["b"], 2), v["sh"])
|
||||
lo = v["lo"]; xin = y if v["kind"] == "g" else y[..., :lo]
|
||||
h = rq(ref_conv(xin, v["w1"], v["b1"], 1, 1, v.get("group", 1)), v["s1"])
|
||||
cat = h if v["kind"] == "g" else np.concatenate([h, y[..., lo:]], -1)
|
||||
m = rq(ref_conv(cat, v["w2"], v["b2"]), v["s2"], relu=True)
|
||||
return rq(ref_conv(m, v["w3"], v["b3"]) + v["R"] * y, v["sf"])
|
||||
|
||||
def ref_tail(v, y, res):
|
||||
return rq(d2s(ref_conv(y, v["w4"], v["b4"])) + v["t_R"] * res, v["t_sf"])
|
||||
|
||||
rng = np.random.default_rng(7)
|
||||
x0 = rng.integers(-64, 64, size=(32, 64, 16), dtype=np.int8).astype(np.int64)
|
||||
# Exact shader reference
|
||||
X1 = ref_block(L["p03"], x0)
|
||||
X2 = ref_block(L["p05"], X1)
|
||||
D0 = ref_block(L["p07"], X2)
|
||||
E1 = ref_block(L["p09"], D0)
|
||||
E2 = ref_block(L["p11"], E1)
|
||||
F0 = ref_block(L["p13"], E2)
|
||||
F1 = ref_block(L["p15"], F0)
|
||||
F2 = ref_block(L["p17"], F1)
|
||||
G0 = ref_tail(L["p19"], ref_block(L["p19"], F2), E2)
|
||||
G1 = ref_block(L["p21"], G0)
|
||||
H0 = ref_tail(L["p23"], ref_block(L["p23"], G1), X2)
|
||||
OUT_ref = ref_block(L["p25"], H0)
|
||||
|
||||
# Simulate our packed S8 QNN graph on the exact same 32x64 input (with 1-px halo)
|
||||
vals = {}
|
||||
vals[0] = np.pad(x0.astype(np.int8), ((1, 1), (1, 1), (0, 0)))[None, ...]
|
||||
for t in gp.tensors:
|
||||
if t["data_size"] > 0:
|
||||
raw = bytes(gp.payload[t["data_offset"]:t["data_offset"] + t["data_size"]])
|
||||
if t["kind"] == 8: # TK_STATIC_S8
|
||||
vals[t["id"]] = np.frombuffer(raw, dtype=np.int8).reshape(t["dims"][:t["rank"]])
|
||||
elif t["kind"] == 4: # TK_STATIC_S32
|
||||
vals[t["id"]] = np.frombuffer(raw, dtype=np.int32).reshape(t["dims"][:t["rank"]])
|
||||
|
||||
for o in gp.ops:
|
||||
ot = o["op_type"]
|
||||
ins = [vals[o["in_ids"][k]] for k in range(o["num_ins"])]
|
||||
out_t = gp.tensors[o["out_id"]]
|
||||
s_out = out_t["scale"]
|
||||
if ot == OP_SLICE_HW:
|
||||
# Map full 540x960 slice to 32x64 test size
|
||||
vals[o["out_id"]] = ins[0][:, 1:-1, 1:-1, :]
|
||||
elif ot == OP_PAD_HW:
|
||||
vals[o["out_id"]] = np.pad(ins[0], ((0, 0), (1, 1), (1, 1), (0, 0)), mode="constant", constant_values=0)
|
||||
elif ot == OP_SLICE_CH:
|
||||
vals[o["out_id"]] = ins[0][..., o["p0"]:o["p1"]]
|
||||
elif ot == OP_CONCAT:
|
||||
vals[o["out_id"]] = np.concatenate(ins, axis=o["p0"])
|
||||
elif ot == OP_RELU:
|
||||
vals[o["out_id"]] = np.maximum(ins[0], 0).astype(np.int8)
|
||||
elif ot == OP_DEPTH_TO_SPACE:
|
||||
vals[o["out_id"]] = d2s(ins[0][0])[None, ...]
|
||||
elif ot == OP_CONV2D:
|
||||
x, w, b = ins[0][0].astype(np.int64), ins[1].transpose(3, 2, 0, 1).astype(np.int64), ins[2].astype(np.int64)
|
||||
s_x = gp.tensors[o["in_ids"][0]]["scale"]
|
||||
s_w = gp.tensors[o["in_ids"][1]]["scale"]
|
||||
grp = o["p2"] if o["p2"] > 0 else 1
|
||||
acc = ref_conv(x, w, b, stride=o["p0"], pad=o["p1"], group=grp)
|
||||
real = acc * (s_x * s_w)
|
||||
vals[o["out_id"]] = np.clip(np.rint(real / s_out), -128, 127).astype(np.int8)[None, ...]
|
||||
elif ot == OP_ADD:
|
||||
s_a = gp.tensors[o["in_ids"][0]]["scale"]
|
||||
s_b = gp.tensors[o["in_ids"][1]]["scale"]
|
||||
real = ins[0].astype(np.float64) * s_a + ins[1].astype(np.float64) * s_b
|
||||
vals[o["out_id"]] = np.clip(np.rint(real / s_out), -128, 127).astype(np.int8)
|
||||
else:
|
||||
raise ValueError(f"Unexpected op {ot}")
|
||||
|
||||
out_sim = vals[gp.ops[-1]["out_id"]][0, 1:-1, 1:-1, :].astype(np.int64)
|
||||
diff = np.abs(out_sim - OUT_ref)
|
||||
print(f" 12-block FSR 4.1.1 Full verification (32x64x16): "
|
||||
f"mean_abs_diff={diff.mean():.3f}, p95={np.percentile(diff, 95):.1f}, max={diff.max()}, "
|
||||
f"corr={np.corrcoef(out_sim.ravel(), OUT_ref.ravel())[0,1]:.6f}")
|
||||
assert np.corrcoef(out_sim.ravel(), OUT_ref.ravel())[0, 1] > 0.998, "Correlation too low — check graph!"
|
||||
|
||||
|
||||
def main():
|
||||
L = load_fsr411_full_weights()
|
||||
print("=== Packing Genuine AMD FSR 4.1.1 Full INT8 (12 blocks, 540x960) ===")
|
||||
gp_s8 = build_fsr411_full_wpack(L, ASSETS_FULL / "fsr411_full_zc_s8.wpack", native_s8=True)
|
||||
build_fsr411_full_wpack(L, ASSETS_FULL / "fsr411_full_zc_i8.wpack", native_s8=False)
|
||||
verify_against_shader_ref(L, gp_s8)
|
||||
print("FSR 4.1.1 Full INT8 NPU wpack verification PASSED!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,353 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pack genuine AMD FidelityFX SDK v2.4.0 FSR 4.1.2 Lite INT8 weights & QNN HTP op graph
|
||||
into fsr412_lite_i8.wpack (~35 KB) for on-device compilation via Qualcomm libQnnHtpPrepare.so
|
||||
on Snapdragon SM8850 Hexagon HTP v81 (and v79).
|
||||
|
||||
Every weight, bias, and shift is extracted directly from AMD's official FSR 4.1.2 Lite
|
||||
shaders (0002.comp, 0005.comp, 0007.comp) and genuine 27,392-byte weights.bin.
|
||||
Verifies numerical equivalence against a numpy reference matching the exact shader integer math!
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
import struct
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
|
||||
# Set from the command line: vela provider/spirv-sources/lite/converted, fsr412_lite/weights.bin, output.
|
||||
VELA_LITE_DIR = None
|
||||
WEIGHTS_BIN = None
|
||||
OUT_WPACK = None
|
||||
|
||||
WPK_MAGIC = 0x314B505734525346 # "FSR4WPK1"
|
||||
WPK_VERSION = 1
|
||||
PASS0_PAD = 1056 # Must match WL_FSR4_PASS0_WB_BYTES (1056) in fsr4_qnn.h!
|
||||
|
||||
TK_APP_WRITE = 0
|
||||
TK_APP_READ = 1
|
||||
TK_NATIVE = 2
|
||||
TK_STATIC_U8 = 3
|
||||
TK_STATIC_S32 = 4
|
||||
|
||||
OP_CONV2D = 1
|
||||
OP_RELU = 2
|
||||
OP_ADD = 3
|
||||
OP_CONCAT = 4
|
||||
OP_SLICE_CH = 5
|
||||
OP_DEPTH_TO_SPACE = 6
|
||||
OP_CONVERT = 7
|
||||
|
||||
|
||||
def unpack_i8_words(words):
|
||||
raw = struct.pack(f"<{len(words)}I", *words)
|
||||
return np.frombuffer(raw, dtype=np.int8)
|
||||
|
||||
|
||||
def extract_const_uint_array(src: str, name: str, count: int) -> np.ndarray:
|
||||
m = re.search(rf"const uint {re.escape(name)}\[{count}\]\s*=\s*uint\[\]\(([^)]+)\);", src, re.S)
|
||||
assert m, f"Array {name}[{count}] not found"
|
||||
vals = [int(x.rstrip("uU")) for x in re.findall(r"\d+u?", m.group(1))]
|
||||
assert len(vals) == count, f"Expected {count}, got {len(vals)}"
|
||||
return unpack_i8_words(vals)
|
||||
|
||||
|
||||
def parse_sdot_1x1(src: str, line_prefix: str, in_vars: list, num_groups: int, Cin: int):
|
||||
"""Parse inlined spvSDot_int_uint_uint 1x1 conv weights from 0002.comp."""
|
||||
Co = num_groups * 4
|
||||
W = np.zeros((Co, Cin, 1, 1), dtype=np.int8)
|
||||
lines = [l for l in src.splitlines() if line_prefix in l]
|
||||
assert len(lines) == num_groups, f"Expected {num_groups} lines for {line_prefix}, got {len(lines)}"
|
||||
for g, line in enumerate(lines):
|
||||
# Find each component of ivec4(...) by matching all spvSDot calls in order
|
||||
calls = re.findall(r"spvSDot_int_uint_uint\(([^,]+),\s*(\d+)u,\s*0\)", line)
|
||||
words_per_oc = Cin // 4
|
||||
assert len(calls) == 4 * words_per_oc, f"Unexpected sdot count {len(calls)} on group {g}"
|
||||
for oc_local in range(4):
|
||||
oc = g * 4 + oc_local
|
||||
sub = calls[oc_local * words_per_oc : (oc_local + 1) * words_per_oc]
|
||||
for var_name, lit_str in sub:
|
||||
var_name = var_name.strip()
|
||||
k = in_vars.index(var_name)
|
||||
b = struct.unpack("<4b", struct.pack("<I", int(lit_str)))
|
||||
W[oc, k * 4 : k * 4 + 4, 0, 0] = b
|
||||
return W
|
||||
|
||||
|
||||
def load_all_weights():
|
||||
init_bytes = WEIGHTS_BIN.read_bytes()
|
||||
assert len(init_bytes) == 27392
|
||||
init_i32 = np.frombuffer(init_bytes, dtype="<i4")
|
||||
init_i8 = np.frombuffer(init_bytes, dtype=np.int8)
|
||||
|
||||
s02 = (VELA_LITE_DIR / "0002.comp").read_text(encoding="utf-8")
|
||||
s05 = (VELA_LITE_DIR / "0005.comp").read_text(encoding="utf-8")
|
||||
s07 = (VELA_LITE_DIR / "0007.comp").read_text(encoding="utf-8")
|
||||
|
||||
# ---- Block 1 (0002.comp) ----
|
||||
# L1_c3: _935[576] = 2304 B. Index: ((256*dx + 768*dy + ic) + 16*oc) -> shape (dy=3, dx=3, oc=16, ic=16)
|
||||
w_935 = extract_const_uint_array(s02, "_935", 576).reshape(3, 3, 16, 16)
|
||||
l1_c3_w = np.ascontiguousarray(w_935.transpose(2, 3, 0, 1)) # OIHW (16, 16, 3, 3)
|
||||
l1_c3_b = init_i32[864:880].copy()
|
||||
|
||||
# L1_e: 1x1 16->32 (lines with "max(ivec4(spvSDot_int_uint_uint(_1030[3]")
|
||||
l1_e_w = parse_sdot_1x1(s02, "max(ivec4(spvSDot_int_uint_uint(_1030[3]",
|
||||
["_1030[0]", "_1030[1]", "_1030[2]", "_1030[3]"], 8, 16)
|
||||
l1_e_b = init_i32[1024:1056].copy()
|
||||
|
||||
# L1_f: 1x1 32->16 (lines with "vec4(ivec4(spvSDot_int_uint_uint(_2221")
|
||||
l1_f_w = parse_sdot_1x1(s02, "vec4(ivec4(spvSDot_int_uint_uint(_2221",
|
||||
["_2018", "_2047", "_2076", "_2105", "_2134", "_2163", "_2192", "_2221"], 4, 32)
|
||||
l1_f_b = init_i32[1184:1200].copy()
|
||||
|
||||
# L1_down: 2x2 stride-2 16->32 in init_bytes[4864..6912]:
|
||||
# 4864 + 16*oc -> tap(0,0), +5376 -> tap(dx=1,dy=0), +5888 -> tap(dx=0,dy=1), +6400 -> tap(dx=1,dy=1)
|
||||
l1_d_w = np.zeros((32, 16, 2, 2), dtype=np.int8)
|
||||
for dy, dx, boff in [(0, 0, 4864), (0, 1, 5376), (1, 0, 5888), (1, 1, 6400)]:
|
||||
l1_d_w[:, :, dy, dx] = init_i8[boff : boff + 512].reshape(32, 16)
|
||||
l1_d_b = init_i32[6912 // 4 : 6912 // 4 + 32].copy()
|
||||
|
||||
# ---- Block 2 (0005.comp) ----
|
||||
# L2_c3: _1706[576] = (dy=3, dx=3, oc=16, ic=16)
|
||||
w_1706 = extract_const_uint_array(s05, "_1706", 576).reshape(3, 3, 16, 16)
|
||||
l2_c3_w = np.ascontiguousarray(w_1706.transpose(2, 3, 0, 1))
|
||||
l2_c3_b = init_i32[9344 // 4 : 9344 // 4 + 16].copy()
|
||||
|
||||
# L2_e: _1707[512] = 2048 B -> (oc=64, ic=32, 1, 1)
|
||||
l2_e_w = extract_const_uint_array(s05, "_1707", 512).reshape(64, 32, 1, 1)
|
||||
l2_e_b = init_i32[11520 // 4 : 11520 // 4 + 64].copy()
|
||||
|
||||
# L2_f: _1708[512] = 2048 B -> (oc=32, ic=64, 1, 1)
|
||||
l2_f_w = extract_const_uint_array(s05, "_1708", 512).reshape(32, 64, 1, 1)
|
||||
l2_f_b = init_i32[13824 // 4 : 13824 // 4 + 32].copy()
|
||||
|
||||
# ---- Block 3 (0007.comp) ----
|
||||
# L3_c3: init_bytes[13952..16256] -> (dy=3, dx=3, oc=16, ic=16)
|
||||
l3_c3_w = np.ascontiguousarray(init_i8[13952 : 13952 + 2304].reshape(3, 3, 16, 16).transpose(2, 3, 0, 1))
|
||||
l3_c3_b = init_i32[16256 // 4 : 16256 // 4 + 16].copy()
|
||||
|
||||
# L3_e: init_bytes[16384..18432] -> (oc=64, ic=32, 1, 1)
|
||||
l3_e_w = init_i8[16384 : 16384 + 2048].reshape(64, 32, 1, 1).copy()
|
||||
l3_e_b = init_i32[18432 // 4 : 18432 // 4 + 64].copy()
|
||||
|
||||
# L3_f: init_bytes[18688..20736] -> (oc=32, ic=64, 1, 1)
|
||||
l3_f_w = init_i8[18688 : 18688 + 2048].reshape(32, 64, 1, 1).copy()
|
||||
l3_f_b = init_i32[20736 // 4 : 20736 // 4 + 32].copy()
|
||||
|
||||
# L3_up: init_bytes[20864..22912] = 2048 B. Index: (512*dx + 1024*dy + 32*oc + ic) + 20864
|
||||
# DCR DepthToSpace order is channel ((2*dy + dx) * 16 + oc) -> matches (dy, dx, oc, ic)!
|
||||
l3_up_w = init_i8[20864 : 20864 + 2048].reshape(2, 2, 16, 32).reshape(64, 32, 1, 1).copy()
|
||||
l3_up_b_16 = init_i32[22912 // 4 : 22912 // 4 + 16].copy()
|
||||
l3_up_b = np.tile(l3_up_b_16, 4)
|
||||
|
||||
return dict(
|
||||
l1_c3=(l1_c3_w, l1_c3_b), l1_e=(l1_e_w, l1_e_b), l1_f=(l1_f_w, l1_f_b), l1_d=(l1_d_w, l1_d_b),
|
||||
l2_c3=(l2_c3_w, l2_c3_b), l2_e=(l2_e_w, l2_e_b), l2_f=(l2_f_w, l2_f_b),
|
||||
l3_c3=(l3_c3_w, l3_c3_b), l3_e=(l3_e_w, l3_e_b), l3_f=(l3_f_w, l3_f_b), l3_up=(l3_up_w, l3_up_b),
|
||||
)
|
||||
|
||||
|
||||
class GraphPacker:
|
||||
def __init__(self):
|
||||
self.tensors = []
|
||||
self.ops = []
|
||||
self.payload = bytearray()
|
||||
|
||||
def _append_bytes(self, b: bytes):
|
||||
pad = (-len(self.payload)) & 15
|
||||
if pad:
|
||||
self.payload.extend(b"\x00" * pad)
|
||||
off = len(self.payload)
|
||||
self.payload.extend(b)
|
||||
return off, len(b)
|
||||
|
||||
def add_tensor(self, kind, dims, scale, offset, raw_bytes=None):
|
||||
tid = len(self.tensors)
|
||||
rank = len(dims)
|
||||
d4 = list(dims) + [0] * (4 - rank)
|
||||
off, sz = (0, 0)
|
||||
if raw_bytes is not None:
|
||||
off, sz = self._append_bytes(raw_bytes)
|
||||
self.tensors.append(dict(
|
||||
id=tid, kind=kind, dims=d4, rank=rank,
|
||||
scale=float(scale), offset=int(offset),
|
||||
data_offset=off, data_size=sz,
|
||||
))
|
||||
return tid
|
||||
|
||||
def add_act(self, h, w, c, scale, kind=TK_NATIVE):
|
||||
return self.add_tensor(kind, [1, h, w, c], scale, -128)
|
||||
|
||||
def add_static_w_hwio(self, w_i8_hwio: np.ndarray, scale: float):
|
||||
assert w_i8_hwio.dtype == np.int8 and w_i8_hwio.ndim == 4
|
||||
w_u8 = np.ascontiguousarray(w_i8_hwio.astype(np.int16) + 128, dtype=np.uint8)
|
||||
return self.add_tensor(TK_STATIC_U8, list(w_u8.shape), scale, -128, w_u8.tobytes())
|
||||
|
||||
def add_static_bias_s32_exact(self, b_i32: np.ndarray, s_in: float, s_w: float):
|
||||
q = np.ascontiguousarray(b_i32.astype(np.int32))
|
||||
return self.add_tensor(TK_STATIC_S32, [int(q.shape[0])], float(s_in) * float(s_w), 0, q.tobytes())
|
||||
|
||||
def emit_op(self, op_type, ins, out_id, p0=0, p1=0, p2=0, p3=0):
|
||||
in3 = list(ins) + [0] * (3 - len(ins))
|
||||
self.ops.append(dict(
|
||||
op_type=op_type, in_ids=in3, num_ins=len(ins), out_id=out_id,
|
||||
p0=int(p0), p1=int(p1), p2=int(p2), p3=int(p3),
|
||||
))
|
||||
return out_id
|
||||
|
||||
def conv2d_exact(self, x_id, w_oihw: np.ndarray, b_i32: np.ndarray, s_w: float,
|
||||
s_out: float, stride=1, pad=0, out_kind=TK_NATIVE):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, Cin = xt["dims"]
|
||||
Co, Ci_w, kH, kW = w_oihw.shape
|
||||
assert Ci_w == Cin, f"Cin mismatch {Ci_w} vs {Cin}"
|
||||
w_hwio = np.ascontiguousarray(w_oihw.transpose(2, 3, 1, 0), dtype=np.int8)
|
||||
w_id = self.add_static_w_hwio(w_hwio, s_w)
|
||||
b_id = self.add_static_bias_s32_exact(b_i32, xt["scale"], s_w)
|
||||
Ho = (H + 2 * pad - kH) // stride + 1
|
||||
Wo = (W + 2 * pad - kW) // stride + 1
|
||||
y_id = self.add_act(Ho, Wo, Co, s_out, kind=out_kind)
|
||||
return self.emit_op(OP_CONV2D, [x_id, w_id, b_id], y_id, stride, pad)
|
||||
|
||||
def relu(self, x_id):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
y_id = self.add_act(H, W, C, xt["scale"])
|
||||
return self.emit_op(OP_RELU, [x_id], y_id)
|
||||
|
||||
def add(self, a_id, b_id, s_out, out_kind=TK_NATIVE):
|
||||
at = self.tensors[a_id]
|
||||
bt = self.tensors[b_id]
|
||||
assert at["dims"] == bt["dims"], f"Add mismatch {at['dims']} vs {bt['dims']}"
|
||||
_, H, W, C = at["dims"]
|
||||
y_id = self.add_act(H, W, C, s_out, kind=out_kind)
|
||||
return self.emit_op(OP_ADD, [a_id, b_id], y_id)
|
||||
|
||||
def concat_c(self, a_id, b_id, s_out):
|
||||
at = self.tensors[a_id]
|
||||
bt = self.tensors[b_id]
|
||||
assert at["dims"][:3] == bt["dims"][:3]
|
||||
assert abs(at["scale"] - s_out) < 1e-12 and abs(bt["scale"] - s_out) < 1e-12
|
||||
_, H, W, Ca = at["dims"]
|
||||
Cb = bt["dims"][3]
|
||||
y_id = self.add_act(H, W, Ca + Cb, s_out)
|
||||
return self.emit_op(OP_CONCAT, [a_id, b_id], y_id, 3)
|
||||
|
||||
def slice_ch(self, x_id, c_start, c_end):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
assert 0 <= c_start < c_end <= C
|
||||
y_id = self.add_act(H, W, c_end - c_start, xt["scale"])
|
||||
return self.emit_op(OP_SLICE_CH, [x_id], y_id, c_start, c_end)
|
||||
|
||||
def depth_to_space(self, x_id, block=2, out_kind=TK_NATIVE):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
assert C % (block * block) == 0
|
||||
y_id = self.add_act(H * block, W * block, C // (block * block), xt["scale"], kind=out_kind)
|
||||
return self.emit_op(OP_DEPTH_TO_SPACE, [x_id], y_id, block, 0)
|
||||
|
||||
|
||||
def build_pack():
|
||||
W = load_all_weights()
|
||||
gp = GraphPacker()
|
||||
|
||||
# Input: [1, 540, 960, 16] UFIXED_POINT_8 (scale=1.0, offset=-128 -> int8 ^ 0x80)
|
||||
x0 = gp.add_act(540, 960, 16, 1.0, kind=TK_APP_WRITE)
|
||||
|
||||
# ---- Block 1 (540x960) ----
|
||||
# L1_c3: 3x3 16->16, >>7
|
||||
h1 = gp.conv2d_exact(x0, W["l1_c3"][0], W["l1_c3"][1], s_w=2.0**-7, s_out=1.0, stride=1, pad=1)
|
||||
# L1_e: 1x1 16->32 + Relu, >>9
|
||||
m1 = gp.relu(gp.conv2d_exact(h1, W["l1_e"][0], W["l1_e"][1], s_w=2.0**-9, s_out=1.0, stride=1, pad=0))
|
||||
# L1_f: 1x1 32->16, residual: round(acc*2^-6 + 0.5*x0)
|
||||
# Use s_out=2.0 on L1_f (s_w=2^-5 -> q = acc*2^-6, float = 2*(acc>>6)); Add(f1, x0, s_out=2.0) -> q_r = round((acc>>6) + 0.5*x0)
|
||||
f1 = gp.conv2d_exact(m1, W["l1_f"][0], W["l1_f"][1], s_w=2.0**-5, s_out=2.0, stride=1, pad=0)
|
||||
r = gp.add(f1, x0, s_out=2.0) # r scale=2.0, int8 value exact!
|
||||
|
||||
# L1_down: 2x2 stride-2 16->32 (ch 0..15: >>6, ch 16..31: >>7). r has s_in=2.0!
|
||||
d0_lo = gp.conv2d_exact(r, W["l1_d"][0][:16], W["l1_d"][1][:16], s_w=2.0**-7, s_out=1.0, stride=2, pad=0)
|
||||
d0_hi = gp.conv2d_exact(r, W["l1_d"][0][16:], W["l1_d"][1][16:], s_w=2.0**-8, s_out=1.0, stride=2, pad=0)
|
||||
d0 = gp.concat_c(d0_lo, d0_hi, s_out=1.0) # [1, 270, 480, 32], scale=1.0
|
||||
|
||||
# ---- Block 2 (270x480) ----
|
||||
# L2_c3: 3x3 on d0[0..15], >>8
|
||||
d0_s0 = gp.slice_ch(d0, 0, 16)
|
||||
d0_s1 = gp.slice_ch(d0, 16, 32)
|
||||
h2 = gp.conv2d_exact(d0_s0, W["l2_c3"][0], W["l2_c3"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=1)
|
||||
c2 = gp.concat_c(h2, d0_s1, s_out=1.0)
|
||||
m2 = gp.relu(gp.conv2d_exact(c2, W["l2_e"][0], W["l2_e"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=0))
|
||||
# L2_f: ch 0..15 -> acc*2^-6 + 0.5*d0_lo; ch 16..31 -> acc*2^-7 + 0.5*d0_hi
|
||||
f2_lo = gp.conv2d_exact(m2, W["l2_f"][0][:16], W["l2_f"][1][:16], s_w=2.0**-5, s_out=2.0, stride=1, pad=0)
|
||||
f2_hi = gp.conv2d_exact(m2, W["l2_f"][0][16:], W["l2_f"][1][16:], s_w=2.0**-6, s_out=2.0, stride=1, pad=0)
|
||||
e0_lo = gp.add(f2_lo, d0_s0, s_out=2.0) # scale=2.0
|
||||
e0_hi = gp.add(f2_hi, d0_s1, s_out=2.0) # scale=2.0
|
||||
|
||||
# ---- Block 3 (270x480 -> 540x960) ----
|
||||
# L3_c3: 3x3 on e0_lo (s_in=2.0), >>8 -> keep s_out=2.0 (s_w=2^-8 -> 2.0*2^-8/2.0 = 2^-8!)
|
||||
h3 = gp.conv2d_exact(e0_lo, W["l3_c3"][0], W["l3_c3"][1], s_w=2.0**-8, s_out=2.0, stride=1, pad=1)
|
||||
c3 = gp.concat_c(h3, e0_hi, s_out=2.0) # both scale=2.0!
|
||||
# L3_e: 1x1 32->64 + Relu, >>7 (s_in=2.0, s_w=2^-8, s_out=1.0 -> 2.0*2^-8/1.0 = 2^-7!)
|
||||
m3 = gp.relu(gp.conv2d_exact(c3, W["l3_e"][0], W["l3_e"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=0))
|
||||
# L3_f: ch 0..15 -> acc*2^-6 + 1.0*e0_lo; ch 16..31 -> acc*2^-6 + 2.0*e0_hi
|
||||
f3_lo = gp.conv2d_exact(m3, W["l3_f"][0][:16], W["l3_f"][1][:16], s_w=2.0**-5, s_out=2.0, stride=1, pad=0)
|
||||
z3_lo = gp.add(f3_lo, e0_lo, s_out=2.0) # (2*(acc>>6) + 2*e0_lo)/2 = (acc>>6) + e0_lo! scale=2.0
|
||||
f3_hi = gp.conv2d_exact(m3, W["l3_f"][0][16:], W["l3_f"][1][16:], s_w=2.0**-6, s_out=1.0, stride=1, pad=0)
|
||||
z3_hi = gp.add(f3_hi, e0_hi, s_out=1.0) # (acc>>6 + 2*e0_hi)/1 = (acc>>6) + 2*e0_hi! scale=1.0
|
||||
|
||||
# L3_up: 1x1 32->64 split cleanly across z3_lo (scale=2.0) and z3_hi (scale=1.0) + DepthToSpace(2, DCR) + skip r (scale=2.0)
|
||||
# Target shift: >>8 (0.0001220703125 * 32 = 2^-8). We want output at scale=2.0 so Add(up_d2s, r, s_out=2.0) = (acc>>8) + r!
|
||||
# For z3_lo (s_in=2.0): s_in * s_w / s_out = 2^-8 -> s_w = 2^-8! (carry full bias here)
|
||||
# For z3_hi (s_in=1.0): s_in * s_w / s_out = 2^-8 -> s_w = 2^-7! (zero bias here)
|
||||
up_lo = gp.conv2d_exact(z3_lo, W["l3_up"][0][:, :16, :, :], W["l3_up"][1], s_w=2.0**-8, s_out=2.0, stride=1, pad=0)
|
||||
up_hi = gp.conv2d_exact(z3_hi, W["l3_up"][0][:, 16:, :, :], np.zeros(64, dtype=np.int32), s_w=2.0**-7, s_out=2.0, stride=1, pad=0)
|
||||
up_sum = gp.add(up_lo, up_hi, s_out=2.0)
|
||||
up_d2s = gp.depth_to_space(up_sum, block=2)
|
||||
out_id = gp.add(up_d2s, r, s_out=2.0, out_kind=TK_APP_READ)
|
||||
|
||||
# Serialize WPK1 binary (exact same header format as fsr4_v07_i8.wpack!)
|
||||
hdr = struct.pack(
|
||||
"<QIIIIIIIIIIffII",
|
||||
WPK_MAGIC, WPK_VERSION,
|
||||
540, 960, 16,
|
||||
540, 960, 16,
|
||||
len(gp.tensors), len(gp.ops),
|
||||
x0, 1.0, 2.0,
|
||||
out_id, len(gp.payload),
|
||||
)
|
||||
assert len(hdr) == 64
|
||||
|
||||
buf = bytearray(hdr)
|
||||
buf.extend(b"\x00" * PASS0_PAD)
|
||||
for t in gp.tensors:
|
||||
buf.extend(struct.pack(
|
||||
"<IIIIIIIfiII",
|
||||
t["id"], t["kind"],
|
||||
t["dims"][0], t["dims"][1], t["dims"][2], t["dims"][3],
|
||||
t["rank"], t["scale"], t["offset"],
|
||||
t["data_offset"], t["data_size"],
|
||||
))
|
||||
for o in gp.ops:
|
||||
buf.extend(struct.pack(
|
||||
"<IIIIIIIIII",
|
||||
o["op_type"],
|
||||
o["in_ids"][0], o["in_ids"][1], o["in_ids"][2],
|
||||
o["num_ins"], o["out_id"],
|
||||
o["p0"], o["p1"], o["p2"], o["p3"],
|
||||
))
|
||||
buf.extend(gp.payload)
|
||||
|
||||
OUT_WPACK.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUT_WPACK.write_bytes(bytes(buf))
|
||||
print(f"Wrote {OUT_WPACK} ({len(buf)} bytes, {len(gp.tensors)} tensors, {len(gp.ops)} ops, "
|
||||
f"payload={len(gp.payload)} B, sha256={hashlib.sha256(buf).hexdigest()[:16]})")
|
||||
|
||||
# Quick sanity stats on extracted genuine AMD weights
|
||||
for k, (wt, bs) in W.items():
|
||||
print(f" {k:6s}: w={tuple(wt.shape)} [{wt.min()},{wt.max()}] b={tuple(bs.shape)} [{bs.min()},{bs.max()}]")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 4:
|
||||
sys.exit("usage: pack_fsr412_lite_weights.py VELA_LITE_CONVERTED_DIR WEIGHTS.bin OUT.wpack")
|
||||
VELA_LITE_DIR, WEIGHTS_BIN, OUT_WPACK = (Path(a) for a in sys.argv[1:4])
|
||||
build_pack()
|
||||
@@ -0,0 +1,340 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pack AMD FSR 4.0.2 INT8 (fsr4_model_v07_i8_quality) weights & QNN HTP op graph
|
||||
into a compact self-contained binary asset (fsr4_v07_i8.wpack) for on-device
|
||||
compilation via Qualcomm libQnnHtpPrepare.so (HTP v81 / v79).
|
||||
|
||||
Every op uses standard QNN qti.aisw NHWC / HWIO layouts, group=1 Conv2d,
|
||||
UFIXED_POINT_8 (offset=-128) weights/activations, SFIXED_POINT_32 biases,
|
||||
and 1x1 Conv2d + DepthToSpace(DCR, 2x2) for exact 2x2 stride-2 ConvTranspose.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import struct
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
|
||||
# Checkout of puzzled-pancake/fsr4-hexagon (provides model/sim/fsr4_sim.py).
|
||||
FSR4_HEX_ROOT = Path(os.environ.get("FSR4_HEXAGON_ROOT", "fsr4-hexagon"))
|
||||
sys.path.insert(0, str(FSR4_HEX_ROOT / "model/sim"))
|
||||
import fsr4_sim as S
|
||||
|
||||
WPK_MAGIC = 0x314B505734525346 # "FSR4WPK1"
|
||||
WPK_VERSION = 1
|
||||
|
||||
TK_APP_WRITE = 0
|
||||
TK_APP_READ = 1
|
||||
TK_NATIVE = 2
|
||||
TK_STATIC_U8 = 3
|
||||
TK_STATIC_S32 = 4
|
||||
|
||||
OP_CONV2D = 1
|
||||
OP_RELU = 2
|
||||
OP_ADD = 3
|
||||
OP_CONCAT = 4
|
||||
OP_SLICE_CH = 5
|
||||
OP_DEPTH_TO_SPACE = 6
|
||||
OP_CONVERT = 7
|
||||
|
||||
S_OUT = 0.303211569786 # Matches wv2a.comp / postA contract
|
||||
|
||||
|
||||
class GraphPacker:
|
||||
def __init__(self):
|
||||
self.tensors = []
|
||||
self.ops = []
|
||||
self.payload = bytearray()
|
||||
|
||||
def _append_bytes(self, b: bytes):
|
||||
# 16-byte align every static tensor in payload
|
||||
pad = (-len(self.payload)) & 15
|
||||
if pad:
|
||||
self.payload.extend(b"\x00" * pad)
|
||||
off = len(self.payload)
|
||||
self.payload.extend(b)
|
||||
return off, len(b)
|
||||
|
||||
def add_tensor(self, kind, dims, scale, offset, raw_bytes=None):
|
||||
tid = len(self.tensors)
|
||||
rank = len(dims)
|
||||
d4 = list(dims) + [0] * (4 - rank)
|
||||
off, sz = (0, 0)
|
||||
if raw_bytes is not None:
|
||||
off, sz = self._append_bytes(raw_bytes)
|
||||
self.tensors.append(dict(
|
||||
id=tid, kind=kind, dims=d4, rank=rank,
|
||||
scale=float(scale), offset=int(offset),
|
||||
data_offset=off, data_size=sz,
|
||||
))
|
||||
return tid
|
||||
|
||||
def add_act(self, h, w, c, scale, kind=TK_NATIVE):
|
||||
return self.add_tensor(kind, [1, h, w, c], scale, -128)
|
||||
|
||||
def add_static_w_hwio(self, w_i8_hwio: np.ndarray, scale: float):
|
||||
assert w_i8_hwio.dtype == np.int8 and w_i8_hwio.ndim == 4
|
||||
w_u8 = np.ascontiguousarray(w_i8_hwio.astype(np.int16) + 128, dtype=np.uint8)
|
||||
return self.add_tensor(TK_STATIC_U8, list(w_u8.shape), scale, -128, w_u8.tobytes())
|
||||
|
||||
def add_static_bias_s32(self, b_f32: np.ndarray, s_in: float, s_w: float):
|
||||
s_b = float(s_in) * float(s_w)
|
||||
q = np.rint(b_f32.astype(np.float64) / s_b)
|
||||
q = np.clip(q, -2147483648, 2147483647).astype(np.int32)
|
||||
q = np.ascontiguousarray(q)
|
||||
return self.add_tensor(TK_STATIC_S32, [int(q.shape[0])], s_b, 0, q.tobytes())
|
||||
|
||||
def emit_op(self, op_type, ins, out_id, p0=0, p1=0, p2=0, p3=0):
|
||||
in3 = list(ins) + [0] * (3 - len(ins))
|
||||
self.ops.append(dict(
|
||||
op_type=op_type, in_ids=in3, num_ins=len(ins), out_id=out_id,
|
||||
p0=int(p0), p1=int(p1), p2=int(p2), p3=int(p3),
|
||||
))
|
||||
return out_id
|
||||
|
||||
def conv2d(self, x_id, w_oihw: np.ndarray, b_f32: np.ndarray, s_w: float,
|
||||
s_out: float, stride=1, pad=0, out_kind=TK_NATIVE):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, Cin = xt["dims"]
|
||||
Co, Ci_w, kH, kW = w_oihw.shape
|
||||
assert Ci_w == Cin, f"Cin mismatch {Ci_w} vs {Cin}"
|
||||
# OIHW -> HWIO
|
||||
w_hwio = np.ascontiguousarray(w_oihw.transpose(2, 3, 1, 0), dtype=np.int8)
|
||||
w_id = self.add_static_w_hwio(w_hwio, s_w)
|
||||
b_id = self.add_static_bias_s32(b_f32, xt["scale"], s_w)
|
||||
Ho = (H + 2 * pad - kH) // stride + 1
|
||||
Wo = (W + 2 * pad - kW) // stride + 1
|
||||
y_id = self.add_act(Ho, Wo, Co, s_out, kind=out_kind)
|
||||
return self.emit_op(OP_CONV2D, [x_id, w_id, b_id], y_id, stride, pad)
|
||||
|
||||
def relu(self, x_id):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
y_id = self.add_act(H, W, C, xt["scale"])
|
||||
return self.emit_op(OP_RELU, [x_id], y_id)
|
||||
|
||||
def add(self, a_id, b_id, s_out):
|
||||
at = self.tensors[a_id]
|
||||
bt = self.tensors[b_id]
|
||||
assert at["dims"] == bt["dims"], f"Add shape mismatch {at['dims']} vs {bt['dims']}"
|
||||
_, H, W, C = at["dims"]
|
||||
y_id = self.add_act(H, W, C, s_out)
|
||||
return self.emit_op(OP_ADD, [a_id, b_id], y_id)
|
||||
|
||||
def concat_c(self, a_id, b_id, s_out):
|
||||
at = self.tensors[a_id]
|
||||
bt = self.tensors[b_id]
|
||||
assert at["dims"][:3] == bt["dims"][:3]
|
||||
_, H, W, Ca = at["dims"]
|
||||
Cb = bt["dims"][3]
|
||||
# Rescale a/b to common s_out if scales differ (HTP Concat requires matching scales)
|
||||
if abs(at["scale"] - s_out) > 1e-12:
|
||||
a2 = self.add_act(H, W, Ca, s_out)
|
||||
a_id = self.emit_op(OP_CONVERT, [a_id], a2)
|
||||
if abs(bt["scale"] - s_out) > 1e-12:
|
||||
b2 = self.add_act(H, W, Cb, s_out)
|
||||
b_id = self.emit_op(OP_CONVERT, [b_id], b2)
|
||||
y_id = self.add_act(H, W, Ca + Cb, s_out)
|
||||
return self.emit_op(OP_CONCAT, [a_id, b_id], y_id, 3)
|
||||
|
||||
def slice_ch(self, x_id, c_start, c_end, s_out=None):
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, C = xt["dims"]
|
||||
assert 0 <= c_start < c_end <= C
|
||||
y_id = self.add_act(H, W, c_end - c_start, xt["scale"])
|
||||
self.emit_op(OP_SLICE_CH, [x_id], y_id, c_start, c_end)
|
||||
if s_out is not None and abs(xt["scale"] - s_out) > 1e-12:
|
||||
y2 = self.add_act(H, W, c_end - c_start, s_out)
|
||||
y_id = self.emit_op(OP_CONVERT, [y_id], y2)
|
||||
return y_id
|
||||
|
||||
def conv_transpose_2x2(self, x_id, w_cio22: np.ndarray, b_f32: np.ndarray,
|
||||
s_w: float, s_out: float, out_kind=TK_NATIVE):
|
||||
"""Exact 2x2 stride-2 ConvTranspose via 1x1 Conv2d + DepthToSpace(DCR, 2)."""
|
||||
xt = self.tensors[x_id]
|
||||
_, H, W, Cin = xt["dims"]
|
||||
Ci_w, Co, kH, kW = w_cio22.shape
|
||||
assert Ci_w == Cin and kH == 2 and kW == 2
|
||||
# DCR DepthToSpace: channel ((ky * 2 + kx) * Co + co) -> spatial (2y+ky, 2x+kx, co)
|
||||
w_dcr = w_cio22.transpose(2, 3, 1, 0).reshape(4 * Co, Cin, 1, 1) # OIHW for 1x1 Conv2d
|
||||
b_dcr = np.tile(b_f32, 4)
|
||||
tmp_id = self.conv2d(x_id, w_dcr, b_dcr, s_w, s_out, stride=1, pad=0)
|
||||
y_id = self.add_act(H * 2, W * 2, Co, s_out, kind=out_kind)
|
||||
return self.emit_op(OP_DEPTH_TO_SPACE, [tmp_id], y_id, 2, 0)
|
||||
|
||||
|
||||
def verify_ct2d_equivalence(L):
|
||||
"""Prove 1x1 Conv2d + DepthToSpace(DCR) is bit-identical to fsr4_sim.convtranspose2x2_i8."""
|
||||
w = L["dec2_ct_weight"] # [Cin, Cout, 2, 2]
|
||||
rng = np.random.default_rng(42)
|
||||
x = rng.integers(-60, 60, size=(4, 6, w.shape[0]), dtype=np.int8)
|
||||
ref = S.convtranspose2x2_i8(x, w)
|
||||
w_dcr = w.transpose(2, 3, 1, 0).reshape(4 * w.shape[1], w.shape[0]) # [4*Co, Cin]
|
||||
tmp = np.einsum("hwc,oc->hwo", x.astype(np.int64), w_dcr.astype(np.int64))
|
||||
# DCR DepthToSpace: [H, W, 2, 2, Co] -> [H, 2, W, 2, Co] -> [2H, 2W, Co]
|
||||
Co = w.shape[1]
|
||||
got = tmp.reshape(4, 6, 2, 2, Co).transpose(0, 2, 1, 3, 4).reshape(8, 12, Co)
|
||||
assert np.array_equal(ref, got), "CT2D <-> 1x1+D2S mismatch!"
|
||||
print("[PASS] 1x1 Conv2d + DepthToSpace(DCR) bit-exact match with fsr4_sim.convtranspose2x2_i8")
|
||||
|
||||
|
||||
def expand_k2s2_to_k3s2p1(w_oihw: np.ndarray) -> np.ndarray:
|
||||
"""Decompose k=2,s=2,p=0 conv into HTP-native k=3,s=2,p=1 conv (zero top/left taps)."""
|
||||
O, I, kH, kW = w_oihw.shape
|
||||
assert kH == 2 and kW == 2
|
||||
w3 = np.zeros((O, I, 3, 3), dtype=np.int8)
|
||||
w3[:, :, 1:3, 1:3] = w_oihw
|
||||
return w3
|
||||
|
||||
|
||||
def expand_group2_to_group1(w_oihw: np.ndarray) -> np.ndarray:
|
||||
"""Decompose group=2 conv into HTP-native group=1 conv (zero cross-group weights)."""
|
||||
O, Ci_g, kH, kW = w_oihw.shape
|
||||
Og = O // 2
|
||||
wfull = np.zeros((O, 2 * Ci_g, kH, kW), dtype=np.int8)
|
||||
wfull[:Og, :Ci_g] = w_oihw[:Og]
|
||||
wfull[Og:, Ci_g:2 * Ci_g] = w_oihw[Og:]
|
||||
return wfull
|
||||
|
||||
|
||||
def build_pack(out_path: Path, pass0_raw_path: Path):
|
||||
L = S.load_layers()
|
||||
L = S.load_with_pass0_scale(L)
|
||||
verify_ct2d_equivalence(L)
|
||||
|
||||
pass0_wb = pass0_raw_path.read_bytes()
|
||||
assert len(pass0_wb) == 1056
|
||||
assert hashlib.md5(pass0_wb).hexdigest() == "0915f25de428aaeee396701e3abfd341"
|
||||
|
||||
p = GraphPacker()
|
||||
calls = L["_calls"]
|
||||
c = [calls[i]["args"] for i in range(len(calls))]
|
||||
sc = lambda k: float(L[k])
|
||||
|
||||
x_in = p.add_act(540, 960, 16, S.S_IN, kind=TK_APP_WRITE)
|
||||
|
||||
def cnb(x_id, prefix, s_mid1, s_mid2, s_out):
|
||||
y = p.conv2d(x_id, L[f"{prefix}_conv_dw_weight"], L[f"{prefix}_conv_dw_bias"],
|
||||
sc(f"scale__{prefix}_conv_dw"), s_mid1, stride=1, pad=1)
|
||||
y = p.conv2d(y, L[f"{prefix}_pw_expand_weight"], L[f"{prefix}_pw_expand_bias"],
|
||||
sc(f"scale__{prefix}_pw_expand"), s_mid2, stride=1, pad=0)
|
||||
y = p.relu(y)
|
||||
y = p.conv2d(y, L[f"{prefix}_pw_contract_weight"], L[f"{prefix}_pw_contract_bias"],
|
||||
sc(f"scale__{prefix}_pw_contract"), s_out, stride=1, pad=0)
|
||||
return p.add(y, x_id, s_out)
|
||||
|
||||
def k2s2b(x_id, wkey, bkey, skey, q0, q1):
|
||||
W = L[wkey]; b = L[bkey]; C = W.shape[0]
|
||||
w0 = expand_k2s2_to_k3s2p1(W[:C // 2])
|
||||
w1 = expand_k2s2_to_k3s2p1(W[C // 2:])
|
||||
h0 = p.conv2d(x_id, w0, b[:C // 2], sc(skey), q0, stride=2, pad=1)
|
||||
h1 = p.conv2d(x_id, w1, b[C // 2:], sc(skey), q1, stride=2, pad=1)
|
||||
return (h0, h1)
|
||||
|
||||
def fnb(xg, prefix, q0, q1, act, variant, o0=None, o1=None, uniform_out=None):
|
||||
h0, h1 = xg
|
||||
Wsp = L[f"{prefix}_spatial_weight"]
|
||||
if variant == "64":
|
||||
Wsp = expand_group2_to_group1(Wsp)
|
||||
y = p.conv2d(h0, Wsp, L[f"{prefix}_spatial_bias"],
|
||||
sc(f"scale__{prefix}_spatial"), q1, stride=1, pad=1)
|
||||
cat = p.concat_c(y, h1, q1)
|
||||
y = p.conv2d(cat, L[f"{prefix}_pw_expand_weight"], L[f"{prefix}_pw_expand_bias"],
|
||||
sc(f"scale__{prefix}_pw_expand"), act, stride=1, pad=0)
|
||||
y = p.relu(y)
|
||||
# Skip tensor at common scale
|
||||
s_skip = max(q0, q1)
|
||||
skip = p.concat_c(h0, h1, s_skip)
|
||||
if uniform_out is not None:
|
||||
y = p.conv2d(y, L[f"{prefix}_pw_contract_weight"], L[f"{prefix}_pw_contract_bias"],
|
||||
sc(f"scale__{prefix}_pw_contract"), uniform_out, stride=1, pad=0)
|
||||
return p.add(y, skip, uniform_out)
|
||||
s_mid = max(o0, o1)
|
||||
y = p.conv2d(y, L[f"{prefix}_pw_contract_weight"], L[f"{prefix}_pw_contract_bias"],
|
||||
sc(f"scale__{prefix}_pw_contract"), s_mid, stride=1, pad=0)
|
||||
y = p.add(y, skip, s_mid)
|
||||
C = p.tensors[y]["dims"][3]
|
||||
return (p.slice_ch(y, 0, C // 2, o0), p.slice_ch(y, C // 2, C, o1))
|
||||
|
||||
def fnb_ct2d(xg, prefix, skip_id, q0, q1, act, s_fnb, variant, wct, bct, sct,
|
||||
o0=None, o1=None, uniform_out=None):
|
||||
y = fnb(xg, prefix, q0, q1, act, variant, uniform_out=s_fnb)
|
||||
s_ct = uniform_out if uniform_out is not None else max(o0, o1)
|
||||
y = p.conv_transpose_2x2(y, L[wct], L[bct], sc(sct), s_ct)
|
||||
y = p.add(y, skip_id, s_ct)
|
||||
if uniform_out is not None:
|
||||
return y
|
||||
C = p.tensors[y]["dims"][3]
|
||||
return (p.slice_ch(y, 0, C // 2, o0), p.slice_ch(y, C // 2, C, o1))
|
||||
|
||||
# Full 13-block FSR 4.0.2 INT8 U-Net (exact match to build_onnx.py / fsr4_sim.py)
|
||||
y1 = cnb(x_in, "encoder2_RB0", c[0][1], c[0][3], 0.01933070458471775)
|
||||
y2 = cnb(y1, "encoder2_RB1", c[1][1], c[1][3], 0.02335178479552269)
|
||||
skip2 = y2
|
||||
|
||||
xg = k2s2b(y2, "enc2_ds_weight", "enc2_ds_bias", "scale__enc2_ds", c[2][0], c[2][1])
|
||||
xg = fnb(xg, "encoder3_ResidualBlock_0", c[3][0], c[3][1], c[3][2], "32", o0=c[3][3], o1=c[3][4])
|
||||
y5 = fnb(xg, "encoder3_ResidualBlock_1", c[4][0], c[4][1], c[4][2], "32", uniform_out=0.019347405061125755)
|
||||
skip3 = y5
|
||||
|
||||
xg = k2s2b(y5, "enc3_ds_weight", "enc3_ds_bias", "scale__enc3_ds", c[5][0], c[5][1])
|
||||
xg = fnb(xg, "bottleneck_ResidualBlock_0", c[6][0], c[6][1], c[6][2], "64", o0=c[6][3], o1=c[6][4])
|
||||
xg = fnb(xg, "bottleneck_ResidualBlock_1", c[7][0], c[7][1], c[7][2], "64", o0=c[7][3], o1=c[7][4])
|
||||
xg = fnb_ct2d(xg, "bottleneck_ResidualBlock_2", skip3, c[8][0], c[8][1], c[8][2], c[8][3], "64",
|
||||
"bottleneck_ct_weight", "bottleneck_ct_bias", "scale__bottleneck_ct", o0=c[8][4], o1=c[8][5])
|
||||
xg = fnb(xg, "decoder3_ResidualBlock_1", c[9][0], c[9][1], c[9][2], "32", o0=c[9][3], o1=c[9][4])
|
||||
y11 = fnb_ct2d(xg, "decoder3_ResidualBlock_2", skip2, c[10][0], c[10][1], c[10][2], c[10][3], "32",
|
||||
"dec3_ct_weight", "dec3_ct_bias", "scale__dec3_ct", uniform_out=0.027206305414438248)
|
||||
y12 = cnb(y11, "decoder2_RB1", c[11][1], c[11][3], 0.035173576325178146)
|
||||
y13 = cnb(y12, "decoder2_ResidualBlock_2", c[12][1], c[12][3], 0.06884194910526276)
|
||||
y_out = p.conv_transpose_2x2(y13, L["dec2_ct_weight"], L["dec2_ct_bias"],
|
||||
sc("scale__dec2_ct"), S_OUT, out_kind=TK_APP_READ)
|
||||
|
||||
assert p.tensors[x_in]["dims"] == [1, 540, 960, 16]
|
||||
assert p.tensors[y_out]["dims"] == [1, 1080, 1920, 8]
|
||||
|
||||
# Serialize compact binary pack
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(out_path, "wb") as f:
|
||||
# Header (64 bytes + 1056 bytes pass0_wb = 1120 bytes)
|
||||
hdr = struct.pack(
|
||||
"<QIIIIIIIIIIffII",
|
||||
WPK_MAGIC, WPK_VERSION,
|
||||
540, 960, 16,
|
||||
1080, 1920, 8,
|
||||
len(p.tensors), len(p.ops),
|
||||
x_in,
|
||||
S.S_IN, S_OUT,
|
||||
y_out, len(p.payload),
|
||||
)
|
||||
assert len(hdr) == 64
|
||||
f.write(hdr)
|
||||
f.write(pass0_wb)
|
||||
# Tensor table (44 bytes each)
|
||||
for t in p.tensors:
|
||||
f.write(struct.pack(
|
||||
"<IIIIIIIfiII",
|
||||
t["id"], t["kind"],
|
||||
t["dims"][0], t["dims"][1], t["dims"][2], t["dims"][3],
|
||||
t["rank"], t["scale"], t["offset"],
|
||||
t["data_offset"], t["data_size"],
|
||||
))
|
||||
# Op table (40 bytes each)
|
||||
for o in p.ops:
|
||||
f.write(struct.pack(
|
||||
"<IIIIIIIIII",
|
||||
o["op_type"],
|
||||
o["in_ids"][0], o["in_ids"][1], o["in_ids"][2],
|
||||
o["num_ins"], o["out_id"],
|
||||
o["p0"], o["p1"], o["p2"], o["p3"],
|
||||
))
|
||||
# Static weight/bias payload
|
||||
f.write(p.payload)
|
||||
|
||||
sz = out_path.stat().st_size
|
||||
print(f"[PASS] Wrote {out_path} ({sz:,} bytes): {len(p.tensors)} tensors, {len(p.ops)} QNN ops, {len(p.payload):,} B weights/biases")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 3:
|
||||
sys.exit("usage: FSR4_HEXAGON_ROOT=<fsr4-hexagon checkout> pack_fsr4_weights.py OUT.wpack PASS0_WB.raw")
|
||||
build_pack(Path(sys.argv[1]), Path(sys.argv[2]))
|
||||
@@ -0,0 +1,919 @@
|
||||
// Winlator Ludashi Native Vulkan Qualcomm Snapdragon Game Super Resolution 2 (SGSR 2)
|
||||
// Official 3-pass Adreno-optimized compute pipeline (quic/snapdragon-gsr):
|
||||
// Pass 1: sgsr2_convert.spv - 3x3 depth dilation, MV decode, max-RGB tonemap + R32UI 11-11-10 YCoCg pack
|
||||
// Pass 2: sgsr2_activate.spv - Bilinear depthclip + packed FP16 luma history instability tracking
|
||||
// Pass 3: sgsr2_upscale.spv - 9-tap FastLanczos R32UI textureGather + adaptive variance clamping + blend
|
||||
// Pass 4 (optional, only if sharpness >= 0.01): fsr3_rcas.spv sharpening
|
||||
#define _GNU_SOURCE
|
||||
#include "sgsr2_gpu.h"
|
||||
#include "fsr_gpu_timer.h"
|
||||
|
||||
#include "dd_upscale_compat.h"
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define S2_TAG "DroidDeckUpscaleSGSR2"
|
||||
#define S2_LOGI(...) dd_upscale_log(DD_LOG_INFO, S2_TAG, __VA_ARGS__)
|
||||
#define S2_LOGW(...) dd_upscale_log(DD_LOG_WARN, S2_TAG, __VA_ARGS__)
|
||||
#define S2_LOGE(...) dd_upscale_log(DD_LOG_ERROR, S2_TAG, __VA_ARGS__)
|
||||
|
||||
typedef struct {
|
||||
uint32_t renderSize[2];
|
||||
uint32_t displaySize[2];
|
||||
float renderSizeRcp[2];
|
||||
float displaySizeRcp[2];
|
||||
float jitterOffset[2];
|
||||
float mvScale[2];
|
||||
float jitterCancel[2];
|
||||
float preExposure;
|
||||
float cameraFovAngleHor;
|
||||
uint32_t flags;
|
||||
uint32_t col_base;
|
||||
uint32_t dep_base;
|
||||
uint32_t mv_base;
|
||||
uint32_t react_base;
|
||||
float sharpness;
|
||||
float pad0[2];
|
||||
} S2Ubo; /* 96 bytes, exact std140 match */
|
||||
|
||||
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 col_base;
|
||||
uint32_t dep_base;
|
||||
uint32_t mv_base;
|
||||
uint32_t react_base;
|
||||
uint32_t pad0;
|
||||
} S2RcasPC;
|
||||
|
||||
typedef struct {
|
||||
VkBuffer buf;
|
||||
VkDeviceMemory mem;
|
||||
void *mapped;
|
||||
} S2Buf;
|
||||
|
||||
typedef struct {
|
||||
VkImage img;
|
||||
VkDeviceMemory mem;
|
||||
VkImageView view;
|
||||
VkFormat fmt;
|
||||
uint32_t w, h;
|
||||
int inited;
|
||||
} S2Img;
|
||||
|
||||
#define S2_VIEW_CACHE 64
|
||||
typedef struct {
|
||||
VkImage img;
|
||||
VkFormat fmt;
|
||||
VkImageAspectFlags aspect;
|
||||
VkImageView view;
|
||||
} S2ViewEnt;
|
||||
|
||||
struct WlSgsr2Gpu {
|
||||
WlVkDispatch vk;
|
||||
char dir[512];
|
||||
int ready;
|
||||
|
||||
VkSampler sampler_linear;
|
||||
VkSampler sampler_nearest;
|
||||
|
||||
VkDescriptorSetLayout dsl_conv, dsl_act, dsl_up, dsl_rcas;
|
||||
VkPipelineLayout pl_conv, pl_act, pl_up, pl_rcas;
|
||||
VkPipeline pipe_conv, pipe_act, pipe_up, pipe_rcas;
|
||||
|
||||
VkDescriptorPool dpool;
|
||||
VkDescriptorSet ds_conv[2], ds_act[2], ds_up[2], ds_rcas[2];
|
||||
|
||||
S2Buf ubo[2];
|
||||
S2Img ycocg;
|
||||
S2Img mda;
|
||||
S2Img mdca;
|
||||
S2Img luma_hist[2];
|
||||
S2Img hist[2];
|
||||
S2Img scene_out;
|
||||
S2Img rcas_out;
|
||||
S2Img dummy_img;
|
||||
|
||||
uint32_t frame_idx;
|
||||
uint64_t dispatches;
|
||||
int need_reset;
|
||||
float prev_jitter_x, prev_jitter_y;
|
||||
int have_prev_jitter;
|
||||
|
||||
S2ViewEnt vcache[S2_VIEW_CACHE];
|
||||
int vcache_n;
|
||||
WlGpuTimer timer;
|
||||
};
|
||||
|
||||
static int s2_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 s2_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 s2_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 s2_create_buf(const WlVkDispatch *vk, S2Buf *b, VkDeviceSize sz) {
|
||||
memset(b, 0, sizeof *b);
|
||||
VkBufferCreateInfo ci = {
|
||||
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
|
||||
.size = sz, .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
};
|
||||
if (vk->CreateBuffer(vk->device, &ci, NULL, &b->buf) != VK_SUCCESS) return 0;
|
||||
VkMemoryRequirements mr;
|
||||
vk->GetBufferMemoryRequirements(vk->device, b->buf, &mr);
|
||||
uint32_t mt = s2_find_mem(vk, mr.memoryTypeBits,
|
||||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
if (mt == UINT32_MAX) return 0;
|
||||
VkMemoryAllocateInfo ai = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, mr.size, mt };
|
||||
if (vk->AllocateMemory(vk->device, &ai, NULL, &b->mem) != VK_SUCCESS ||
|
||||
vk->BindBufferMemory(vk->device, b->buf, b->mem, 0) != VK_SUCCESS ||
|
||||
vk->MapMemory(vk->device, b->mem, 0, sz, 0, &b->mapped) != VK_SUCCESS) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void s2_destroy_buf(const WlVkDispatch *vk, S2Buf *b) {
|
||||
if (b->mapped && b->mem) vk->UnmapMemory(vk->device, b->mem);
|
||||
if (b->buf) vk->DestroyBuffer(vk->device, b->buf, NULL);
|
||||
if (b->mem) vk->FreeMemory(vk->device, b->mem, NULL);
|
||||
memset(b, 0, sizeof *b);
|
||||
}
|
||||
|
||||
static int s2_create_img(const WlVkDispatch *vk, S2Img *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 = s2_find_mem(vk, 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 (vk->AllocateMemory(vk->device, &ai, NULL, &im->mem) != VK_SUCCESS ||
|
||||
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 s2_destroy_img(const WlVkDispatch *vk, S2Img *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 s2_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 = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, (size_t)sz, (const uint32_t *)buf };
|
||||
VkShaderModule sm = VK_NULL_HANDLE;
|
||||
vk->CreateShaderModule(vk->device, &ci, NULL, &sm);
|
||||
free(buf);
|
||||
return sm;
|
||||
}
|
||||
|
||||
static int s2_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 = s2_load_spv(vk, dir, spv_name);
|
||||
if (!sm) return 0;
|
||||
VkDescriptorSetLayoutCreateInfo dci = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, nbinds, 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 = {
|
||||
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, NULL, 0, 1, out_dsl,
|
||||
pc_bytes ? 1u : 0u, 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 = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_COMPUTE_BIT, sm, "main", NULL },
|
||||
.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 s2_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 s2_img_bar(const WlVkDispatch *vk, VkCommandBuffer cb, VkImage img,
|
||||
VkImageLayout oldL, VkImageLayout newL,
|
||||
VkPipelineStageFlags srcS, VkPipelineStageFlags dstS,
|
||||
VkAccessFlags srcA, VkAccessFlags dstA) {
|
||||
s2_img_bar_asp(vk, cb, img, VK_IMAGE_ASPECT_COLOR_BIT, oldL, newL, srcS, dstS, srcA, dstA);
|
||||
}
|
||||
|
||||
static VkImageView s2_get_view(WlSgsr2Gpu *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 >= S2_VIEW_CACHE) {
|
||||
g->vk.DestroyImageView(g->vk.device, g->vcache[0].view, NULL);
|
||||
memmove(&g->vcache[0], &g->vcache[1], (S2_VIEW_CACHE - 1) * sizeof(S2ViewEnt));
|
||||
g->vcache_n--;
|
||||
}
|
||||
g->vcache[g->vcache_n++] = (S2ViewEnt){ img, fmt, aspect, v };
|
||||
return v;
|
||||
}
|
||||
|
||||
static int s2_ensure_targets(WlSgsr2Gpu *g, uint32_t rw, uint32_t rh, uint32_t ow, uint32_t oh) {
|
||||
int lr_ch = (!g->ycocg.img || g->ycocg.w != rw || g->ycocg.h != rh);
|
||||
int hr_ch = (!g->scene_out.img || g->scene_out.w != ow || g->scene_out.h != oh);
|
||||
if (!lr_ch && !hr_ch) 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_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||
|
||||
if (lr_ch) {
|
||||
s2_destroy_img(&g->vk, &g->ycocg);
|
||||
s2_destroy_img(&g->vk, &g->mda);
|
||||
s2_destroy_img(&g->vk, &g->mdca);
|
||||
s2_destroy_img(&g->vk, &g->luma_hist[0]);
|
||||
s2_destroy_img(&g->vk, &g->luma_hist[1]);
|
||||
if (!s2_create_img(&g->vk, &g->ycocg, rw, rh, VK_FORMAT_R32_UINT, rw_use) ||
|
||||
!s2_create_img(&g->vk, &g->mda, rw, rh, VK_FORMAT_R16G16B16A16_SFLOAT, rw_use) ||
|
||||
!s2_create_img(&g->vk, &g->mdca, rw, rh, VK_FORMAT_R16G16B16A16_SFLOAT, rw_use) ||
|
||||
!s2_create_img(&g->vk, &g->luma_hist[0], rw, rh, VK_FORMAT_R32_UINT, rw_use) ||
|
||||
!s2_create_img(&g->vk, &g->luma_hist[1], rw, rh, VK_FORMAT_R32_UINT, rw_use)) {
|
||||
return 0;
|
||||
}
|
||||
g->need_reset = 1;
|
||||
}
|
||||
if (hr_ch) {
|
||||
s2_destroy_img(&g->vk, &g->hist[0]);
|
||||
s2_destroy_img(&g->vk, &g->hist[1]);
|
||||
s2_destroy_img(&g->vk, &g->scene_out);
|
||||
s2_destroy_img(&g->vk, &g->rcas_out);
|
||||
if (!s2_create_img(&g->vk, &g->hist[0], ow, oh, VK_FORMAT_R16G16B16A16_SFLOAT, rw_use) ||
|
||||
!s2_create_img(&g->vk, &g->hist[1], ow, oh, VK_FORMAT_R16G16B16A16_SFLOAT, rw_use) ||
|
||||
!s2_create_img(&g->vk, &g->scene_out, ow, oh, VK_FORMAT_R16G16B16A16_SFLOAT, out_use) ||
|
||||
!s2_create_img(&g->vk, &g->rcas_out, ow, oh, VK_FORMAT_R16G16B16A16_SFLOAT, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) {
|
||||
return 0;
|
||||
}
|
||||
g->need_reset = 1;
|
||||
}
|
||||
|
||||
// Bind static internal resources for both ping-pong slots
|
||||
for (int s = 0; s < 2; s++) {
|
||||
int prev = s ^ 1;
|
||||
VkDescriptorBufferInfo bi = { g->ubo[s].buf, 0, sizeof(S2Ubo) };
|
||||
|
||||
VkDescriptorImageInfo yc_st = { VK_NULL_HANDLE, g->ycocg.view, VK_IMAGE_LAYOUT_GENERAL };
|
||||
VkDescriptorImageInfo mda_st = { VK_NULL_HANDLE, g->mda.view, VK_IMAGE_LAYOUT_GENERAL };
|
||||
VkWriteDescriptorSet w_conv[3] = {
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_conv[s], 0, 0, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, NULL, &bi, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_conv[s], 6, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &yc_st, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_conv[s], 7, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &mda_st, NULL, NULL },
|
||||
};
|
||||
g->vk.UpdateDescriptorSets(g->vk.device, 3, w_conv, 0, NULL);
|
||||
|
||||
VkDescriptorImageInfo plh_ro = { g->sampler_nearest, g->luma_hist[prev].view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkDescriptorImageInfo mda_ro = { g->sampler_nearest, g->mda.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkDescriptorImageInfo yc_ro = { g->sampler_nearest, g->ycocg.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkDescriptorImageInfo mdca_st = { VK_NULL_HANDLE, g->mdca.view, VK_IMAGE_LAYOUT_GENERAL };
|
||||
VkDescriptorImageInfo lh_st = { VK_NULL_HANDLE, g->luma_hist[s].view, VK_IMAGE_LAYOUT_GENERAL };
|
||||
VkWriteDescriptorSet w_act[6] = {
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_act[s], 0, 0, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, NULL, &bi, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_act[s], 1, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &plh_ro, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_act[s], 2, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &mda_ro, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_act[s], 3, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &yc_ro, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_act[s], 4, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &mdca_st, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_act[s], 5, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &lh_st, NULL, NULL },
|
||||
};
|
||||
g->vk.UpdateDescriptorSets(g->vk.device, 6, w_act, 0, NULL);
|
||||
|
||||
VkDescriptorImageInfo ph_ro = { g->sampler_linear, g->hist[prev].view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkDescriptorImageInfo mdca_ro = { g->sampler_linear, g->mdca.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkDescriptorImageInfo h_st = { VK_NULL_HANDLE, g->hist[s].view, VK_IMAGE_LAYOUT_GENERAL };
|
||||
VkDescriptorImageInfo sc_st = { VK_NULL_HANDLE, g->scene_out.view, VK_IMAGE_LAYOUT_GENERAL };
|
||||
VkWriteDescriptorSet w_up[6] = {
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_up[s], 0, 0, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, NULL, &bi, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_up[s], 1, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &ph_ro, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_up[s], 2, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &mdca_ro, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_up[s], 3, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &yc_ro, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_up[s], 4, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &h_st, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_up[s], 5, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &sc_st, NULL, NULL },
|
||||
};
|
||||
g->vk.UpdateDescriptorSets(g->vk.device, 6, w_up, 0, NULL);
|
||||
|
||||
if (g->pipe_rcas) {
|
||||
VkDescriptorImageInfo sc_ro = { g->sampler_nearest, g->scene_out.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkDescriptorImageInfo rc_st = { VK_NULL_HANDLE, g->rcas_out.view, VK_IMAGE_LAYOUT_GENERAL };
|
||||
VkWriteDescriptorSet w_rc[2] = {
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_rcas[s], 0, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &sc_ro, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_rcas[s], 1, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &rc_st, NULL, NULL },
|
||||
};
|
||||
g->vk.UpdateDescriptorSets(g->vk.device, 2, w_rc, 0, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
S2_LOGI("Qualcomm SGSR 2 (3-pass CS) targets ready (render=%ux%u -> output=%ux%u)", rw, rh, ow, oh);
|
||||
return 1;
|
||||
}
|
||||
|
||||
WlSgsr2Gpu *wl_sgsr2_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/sgsr2_convert.spv", fsr4_dir);
|
||||
if (access(test_p, R_OK) != 0) return NULL;
|
||||
|
||||
WlSgsr2Gpu *g = (WlSgsr2Gpu *)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_conv[8] = {
|
||||
{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 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_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
{5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
{6, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
{7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
};
|
||||
VkDescriptorSetLayoutBinding b_act[6] = {
|
||||
{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 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},
|
||||
{5, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
};
|
||||
VkDescriptorSetLayoutBinding b_up[7] = {
|
||||
{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 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},
|
||||
{5, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
{6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
};
|
||||
VkDescriptorSetLayoutBinding b_rcas[3] = {
|
||||
{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},
|
||||
{2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
};
|
||||
|
||||
if (!s2_create_pipe(vk, fsr4_dir, "sgsr2_convert.spv", b_conv, 8, 0, &g->dsl_conv, &g->pl_conv, &g->pipe_conv) ||
|
||||
!s2_create_pipe(vk, fsr4_dir, "sgsr2_activate.spv", b_act, 6, 0, &g->dsl_act, &g->pl_act, &g->pipe_act) ||
|
||||
!s2_create_pipe(vk, fsr4_dir, "sgsr2_upscale.spv", b_up, 7, 0, &g->dsl_up, &g->pl_up, &g->pipe_up)) {
|
||||
S2_LOGE("Failed to create Qualcomm SGSR 2 compute pipelines (dir=%s)", fsr4_dir);
|
||||
goto fail;
|
||||
}
|
||||
// Optional RCAS sharpening pass (reuses fsr3_rcas.spv when user sharpness > 0%)
|
||||
s2_create_pipe(vk, fsr4_dir, "fsr3_rcas.spv", b_rcas, 3, sizeof(S2RcasPC), &g->dsl_rcas, &g->pl_rcas, &g->pipe_rcas);
|
||||
|
||||
VkDescriptorPoolSize psizes[3] = {
|
||||
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 12 },
|
||||
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 36 },
|
||||
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 20 },
|
||||
};
|
||||
VkDescriptorPoolCreateInfo dpci = {
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
|
||||
.maxSets = 8, .poolSizeCount = 3, .pPoolSizes = psizes,
|
||||
};
|
||||
if (vk->CreateDescriptorPool(vk->device, &dpci, NULL, &g->dpool) != VK_SUCCESS) goto fail;
|
||||
|
||||
VkDescriptorSetLayout layouts[8] = {
|
||||
g->dsl_conv, g->dsl_conv, g->dsl_act, g->dsl_act, g->dsl_up, g->dsl_up,
|
||||
g->dsl_rcas ? g->dsl_rcas : g->dsl_up, g->dsl_rcas ? g->dsl_rcas : g->dsl_up
|
||||
};
|
||||
VkDescriptorSet sets[8];
|
||||
uint32_t nsets = g->dsl_rcas ? 8u : 6u;
|
||||
VkDescriptorSetAllocateInfo dsai = {
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
|
||||
.descriptorPool = g->dpool, .descriptorSetCount = nsets, .pSetLayouts = layouts,
|
||||
};
|
||||
if (vk->AllocateDescriptorSets(vk->device, &dsai, sets) != VK_SUCCESS) goto fail;
|
||||
g->ds_conv[0] = sets[0]; g->ds_conv[1] = sets[1];
|
||||
g->ds_act[0] = sets[2]; g->ds_act[1] = sets[3];
|
||||
g->ds_up[0] = sets[4]; g->ds_up[1] = sets[5];
|
||||
if (g->dsl_rcas) { g->ds_rcas[0] = sets[6]; g->ds_rcas[1] = sets[7]; }
|
||||
|
||||
if (!s2_create_buf(vk, &g->ubo[0], sizeof(S2Ubo)) ||
|
||||
!s2_create_buf(vk, &g->ubo[1], sizeof(S2Ubo)) ||
|
||||
!s2_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;
|
||||
S2_LOGI("Native Vulkan Qualcomm Snapdragon GSR 2 (3-pass CS) READY!");
|
||||
return g;
|
||||
|
||||
fail:
|
||||
wl_sgsr2_gpu_destroy(g);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void wl_sgsr2_gpu_reset(WlSgsr2Gpu *g) {
|
||||
if (!g) return;
|
||||
g->need_reset = 1;
|
||||
g->have_prev_jitter = 0;
|
||||
}
|
||||
|
||||
int wl_sgsr2_gpu_is_ready(const WlSgsr2Gpu *g) {
|
||||
return g && g->ready;
|
||||
}
|
||||
|
||||
int wl_sgsr2_gpu_dispatch(WlSgsr2Gpu *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 (!s2_ensure_targets(g, rw, rh, ow, oh)) {
|
||||
if (out_reason) *out_reason = "sgsr2_alloc_failed";
|
||||
return 0;
|
||||
}
|
||||
|
||||
VkImageView color_v = s2_get_view(g, color_img, color_fmt, VK_IMAGE_ASPECT_COLOR_BIT);
|
||||
if (!color_v) {
|
||||
if (out_reason) *out_reason = "sgsr2_view_failed";
|
||||
return 0;
|
||||
}
|
||||
VkImageView mv_v = (motion_img != VK_NULL_HANDLE && motion_fmt != VK_FORMAT_UNDEFINED)
|
||||
? s2_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 = s2_is_depth_fmt(depth_fmt) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
VkImageView dv = s2_get_view(g, depth_img, depth_fmt, v_asp);
|
||||
if (dv) { dep_v = dv; dep_bar_asp = s2_depth_bar_aspect(depth_fmt); has_depth = 1; }
|
||||
}
|
||||
|
||||
int has_reactive = 0;
|
||||
VkImage react_img = (VkImage)(uintptr_t)frame->reactive.vk_image;
|
||||
VkFormat react_fmt = (VkFormat)frame->reactive.vk_format;
|
||||
VkImageView react_v = g->dummy_img.view;
|
||||
if (react_img != VK_NULL_HANDLE) {
|
||||
if (react_fmt == VK_FORMAT_UNDEFINED) wl_fsr4_lookup_image_info(g->vk.device, react_img, &react_fmt, NULL, NULL, NULL);
|
||||
VkImageView rv = frame->reactive.vk_view ? (VkImageView)(uintptr_t)frame->reactive.vk_view
|
||||
: (react_fmt != VK_FORMAT_UNDEFINED ? s2_get_view(g, react_img, react_fmt, VK_IMAGE_ASPECT_COLOR_BIT) : VK_NULL_HANDLE);
|
||||
if (rv) { react_v = rv; has_reactive = 1; }
|
||||
}
|
||||
|
||||
int has_expo_tex = 0;
|
||||
VkImage expo_img = (VkImage)(uintptr_t)frame->exposure.vk_image;
|
||||
VkFormat expo_fmt = (VkFormat)frame->exposure.vk_format;
|
||||
VkImageView expo_v = g->dummy_img.view;
|
||||
if (expo_img != VK_NULL_HANDLE) {
|
||||
if (expo_fmt == VK_FORMAT_UNDEFINED) wl_fsr4_lookup_image_info(g->vk.device, expo_img, &expo_fmt, NULL, NULL, NULL);
|
||||
VkImageView ev = frame->exposure.vk_view ? (VkImageView)(uintptr_t)frame->exposure.vk_view
|
||||
: (expo_fmt != VK_FORMAT_UNDEFINED ? s2_get_view(g, expo_img, expo_fmt, VK_IMAGE_ASPECT_COLOR_BIT) : VK_NULL_HANDLE);
|
||||
if (ev) { expo_v = ev; has_expo_tex = 1; }
|
||||
}
|
||||
|
||||
const WlVkDispatch *vk = &g->vk;
|
||||
VkClearColorValue zclr; memset(&zclr, 0, sizeof zclr);
|
||||
VkImageSubresourceRange rng = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
|
||||
|
||||
if (!g->dummy_img.inited) {
|
||||
s2_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);
|
||||
vk->CmdClearColorImage(cb, g->dummy_img.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &zclr, 1, &rng);
|
||||
s2_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[prev].inited || !g->luma_hist[prev].inited || ((frame->flags & WLFSR4_FLAG_RESET) != 0);
|
||||
g->need_reset = 0;
|
||||
|
||||
if (!g->luma_hist[prev].inited) {
|
||||
s2_img_bar(vk, cb, g->luma_hist[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);
|
||||
vk->CmdClearColorImage(cb, g->luma_hist[prev].img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &zclr, 1, &rng);
|
||||
s2_img_bar(vk, cb, g->luma_hist[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->luma_hist[prev].inited = 1;
|
||||
}
|
||||
if (!g->hist[prev].inited) {
|
||||
s2_img_bar(vk, cb, g->hist[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);
|
||||
vk->CmdClearColorImage(cb, g->hist[prev].img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &zclr, 1, &rng);
|
||||
s2_img_bar(vk, cb, g->hist[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[prev].inited = 1;
|
||||
}
|
||||
|
||||
// Update per-frame input 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 };
|
||||
VkDescriptorImageInfo re_ii = { g->sampler_nearest, react_v, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkDescriptorImageInfo ex_ii = { g->sampler_nearest, expo_v, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
VkWriteDescriptorSet ws[7] = {
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_conv[cur], 1, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &c_ii, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_conv[cur], 2, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &d_ii, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_conv[cur], 3, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &mv_ii, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_conv[cur], 4, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &re_ii, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_conv[cur], 5, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &ex_ii, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_up[cur], 6, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &ex_ii, NULL, NULL },
|
||||
{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, g->ds_rcas[cur], 2, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &ex_ii, NULL, NULL },
|
||||
};
|
||||
vk->UpdateDescriptorSets(vk->device, g->pipe_rcas ? 7u : 6u, ws, 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;
|
||||
VkImageLayout re_old = frame->reactive.vk_layout ? (VkImageLayout)frame->reactive.vk_layout : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||||
VkImageLayout ex_old = frame->exposure.vk_layout ? (VkImageLayout)frame->exposure.vk_layout : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||||
if (c_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
|
||||
s2_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) {
|
||||
s2_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) {
|
||||
s2_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);
|
||||
}
|
||||
if (has_reactive && re_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
|
||||
s2_img_bar(vk, cb, react_img, re_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_expo_tex && ex_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
|
||||
s2_img_bar(vk, cb, expo_img, ex_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_w = (float)(disp_res_mv ? ow : rw);
|
||||
float mv_h = (float)(disp_res_mv ? oh : rh);
|
||||
float mvsx = (frame->mv_scale_x != 0.f ? frame->mv_scale_x : 1.f) / mv_w;
|
||||
float mvsy = (frame->mv_scale_y != 0.f ? frame->mv_scale_y : 1.f) / mv_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 = 0.0f;
|
||||
if (sharp > 1.0f) sharp = 1.0f;
|
||||
float vfov = (isfinite(frame->camera_fov_y) && frame->camera_fov_y > 0.05f && frame->camera_fov_y < 3.0f)
|
||||
? frame->camera_fov_y : (60.0f * 3.14159265f / 180.0f);
|
||||
float hfov_tan = tanf(vfov * 0.5f) * ((float)rw / (float)rh);
|
||||
|
||||
uint32_t uflags = 0u;
|
||||
if (has_depth) uflags |= 1u;
|
||||
if (frame->flags & WLFSR4_FLAG_DEPTH_INVERTED) uflags |= 2u;
|
||||
if (disp_res_mv) uflags |= 4u;
|
||||
if (do_reset) uflags |= 8u;
|
||||
if (has_reactive) uflags |= 16u;
|
||||
if (has_expo_tex) uflags |= 32u;
|
||||
|
||||
uint32_t col_base = (uint32_t)frame->color.subrect_x | ((uint32_t)frame->color.subrect_y << 16);
|
||||
uint32_t dep_base = (uint32_t)frame->depth.subrect_x | ((uint32_t)frame->depth.subrect_y << 16);
|
||||
uint32_t mv_base = (uint32_t)frame->motion.subrect_x | ((uint32_t)frame->motion.subrect_y << 16);
|
||||
uint32_t react_base = (uint32_t)frame->reactive.subrect_x | ((uint32_t)frame->reactive.subrect_y << 16);
|
||||
|
||||
S2Ubo ubo_data = {
|
||||
.renderSize = { rw, rh },
|
||||
.displaySize = { ow, oh },
|
||||
.renderSizeRcp = { 1.0f / (float)rw, 1.0f / (float)rh },
|
||||
.displaySizeRcp = { 1.0f / (float)ow, 1.0f / (float)oh },
|
||||
.jitterOffset = { frame->jitter_x, frame->jitter_y },
|
||||
.mvScale = { mvsx, mvsy },
|
||||
.jitterCancel = { jcx, jcy },
|
||||
.preExposure = expo,
|
||||
.cameraFovAngleHor = hfov_tan,
|
||||
.flags = uflags,
|
||||
.col_base = col_base,
|
||||
.dep_base = dep_base,
|
||||
.mv_base = mv_base,
|
||||
.react_base = react_base,
|
||||
.sharpness = sharp,
|
||||
.pad0 = { 0.f, 0.f },
|
||||
};
|
||||
memcpy(g->ubo[cur].mapped, &ubo_data, sizeof ubo_data);
|
||||
|
||||
uint32_t tslot = wl_gpu_timer_begin(&g->timer, vk, cb);
|
||||
|
||||
// ---- Pass 1: SGSR 2 Convert (rw x rh) ----
|
||||
s2_img_bar(vk, cb, g->ycocg.img, g->ycocg.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);
|
||||
s2_img_bar(vk, cb, g->mda.img, g->mda.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_conv);
|
||||
vk->CmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pl_conv, 0, 1, &g->ds_conv[cur], 0, NULL);
|
||||
vk->CmdDispatch(cb, (rw + 7u) / 8u, (rh + 7u) / 8u, 1u);
|
||||
g->ycocg.inited = 1;
|
||||
g->mda.inited = 1;
|
||||
|
||||
// ---- Pass 2: SGSR 2 Activate (rw x rh) ----
|
||||
s2_img_bar(vk, cb, g->ycocg.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);
|
||||
s2_img_bar(vk, cb, g->mda.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);
|
||||
s2_img_bar(vk, cb, g->mdca.img, g->mdca.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);
|
||||
s2_img_bar(vk, cb, g->luma_hist[cur].img, g->luma_hist[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_act);
|
||||
vk->CmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pl_act, 0, 1, &g->ds_act[cur], 0, NULL);
|
||||
vk->CmdDispatch(cb, (rw + 7u) / 8u, (rh + 7u) / 8u, 1u);
|
||||
g->mdca.inited = 1;
|
||||
g->luma_hist[cur].inited = 1;
|
||||
|
||||
// ---- Pass 3: SGSR 2 Upscale (ow x oh) ----
|
||||
s2_img_bar(vk, cb, g->mdca.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);
|
||||
s2_img_bar(vk, cb, g->luma_hist[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);
|
||||
s2_img_bar(vk, cb, g->hist[cur].img, g->hist[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);
|
||||
s2_img_bar(vk, cb, g->scene_out.img,
|
||||
g->scene_out.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_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT,
|
||||
VK_ACCESS_SHADER_WRITE_BIT);
|
||||
vk->CmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pipe_up);
|
||||
vk->CmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pl_up, 0, 1, &g->ds_up[cur], 0, NULL);
|
||||
vk->CmdDispatch(cb, (ow + 7u) / 8u, (oh + 7u) / 8u, 1u);
|
||||
g->hist[cur].inited = 1;
|
||||
g->scene_out.inited = 1;
|
||||
|
||||
// Transition hist[cur] ready for next frame's PrevHistoryOutput
|
||||
s2_img_bar(vk, cb, g->hist[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);
|
||||
|
||||
// ---- Optional Pass 4: RCAS Sharpening (skipped completely if sharpness < 0.01 for max Adreno speed!) ----
|
||||
VkImage final_src = g->scene_out.img;
|
||||
if (g->pipe_rcas && sharp >= 0.01f) {
|
||||
s2_img_bar(vk, cb, g->scene_out.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);
|
||||
s2_img_bar(vk, cb, g->rcas_out.img,
|
||||
g->rcas_out.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);
|
||||
S2RcasPC rpc = {
|
||||
frame->jitter_x, frame->jitter_y, mvsx, mvsy, jcx, jcy,
|
||||
expo, sharp, rw, rh, ow, oh, uflags, col_base, dep_base, mv_base, react_base, 0u,
|
||||
};
|
||||
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 rpc, &rpc);
|
||||
vk->CmdDispatch(cb, (ow + 7u) / 8u, (oh + 7u) / 8u, 1u);
|
||||
g->rcas_out.inited = 1;
|
||||
// Put scene_out back into TRANSFER_SRC_OPTIMAL sentinel state for next frame's barrier consistency
|
||||
s2_img_bar(vk, cb, g->scene_out.img, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_TRANSFER_READ_BIT);
|
||||
final_src = g->rcas_out.img;
|
||||
}
|
||||
|
||||
// 1:1 exact pixel blit/format-convert -> game's output image (respecting output subrect!)
|
||||
VkImageLayout o_old = frame->output.vk_layout ? (VkImageLayout)frame->output.vk_layout : VK_IMAGE_LAYOUT_GENERAL;
|
||||
s2_img_bar(vk, cb, final_src, 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);
|
||||
s2_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);
|
||||
|
||||
int32_t ox = (int32_t)frame->output.subrect_x;
|
||||
int32_t oy = (int32_t)frame->output.subrect_y;
|
||||
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 = { {ox, oy, 0}, {ox + (int32_t)ow, oy + (int32_t)oh, 1} },
|
||||
};
|
||||
vk->CmdBlitImage(cb, final_src, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
out_img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
|
||||
|
||||
s2_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) {
|
||||
s2_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) {
|
||||
s2_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) {
|
||||
s2_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);
|
||||
}
|
||||
if (has_reactive && re_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
|
||||
s2_img_bar(vk, cb, react_img, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, re_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_expo_tex && ex_old != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
|
||||
s2_img_bar(vk, cb, expo_img, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, ex_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 = (g->pipe_rcas && sharp >= 0.01f) ? "ok_sgsr2_rcas" : "ok_sgsr2_3pass";
|
||||
return 2;
|
||||
}
|
||||
|
||||
void wl_sgsr2_gpu_destroy(WlSgsr2Gpu *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);
|
||||
}
|
||||
s2_destroy_img(vk, &g->ycocg);
|
||||
s2_destroy_img(vk, &g->mda);
|
||||
s2_destroy_img(vk, &g->mdca);
|
||||
s2_destroy_img(vk, &g->luma_hist[0]);
|
||||
s2_destroy_img(vk, &g->luma_hist[1]);
|
||||
s2_destroy_img(vk, &g->hist[0]);
|
||||
s2_destroy_img(vk, &g->hist[1]);
|
||||
s2_destroy_img(vk, &g->scene_out);
|
||||
s2_destroy_img(vk, &g->rcas_out);
|
||||
s2_destroy_img(vk, &g->dummy_img);
|
||||
s2_destroy_buf(vk, &g->ubo[0]);
|
||||
s2_destroy_buf(vk, &g->ubo[1]);
|
||||
if (g->dpool) vk->DestroyDescriptorPool(vk->device, g->dpool, NULL);
|
||||
if (g->pipe_conv) vk->DestroyPipeline(vk->device, g->pipe_conv, NULL);
|
||||
if (g->pipe_act) vk->DestroyPipeline(vk->device, g->pipe_act, NULL);
|
||||
if (g->pipe_up) vk->DestroyPipeline(vk->device, g->pipe_up, NULL);
|
||||
if (g->pipe_rcas) vk->DestroyPipeline(vk->device, g->pipe_rcas, NULL);
|
||||
if (g->pl_conv) vk->DestroyPipelineLayout(vk->device, g->pl_conv, NULL);
|
||||
if (g->pl_act) vk->DestroyPipelineLayout(vk->device, g->pl_act, NULL);
|
||||
if (g->pl_up) vk->DestroyPipelineLayout(vk->device, g->pl_up, NULL);
|
||||
if (g->pl_rcas) vk->DestroyPipelineLayout(vk->device, g->pl_rcas, NULL);
|
||||
if (g->dsl_conv) vk->DestroyDescriptorSetLayout(vk->device, g->dsl_conv, NULL);
|
||||
if (g->dsl_act) vk->DestroyDescriptorSetLayout(vk->device, g->dsl_act, NULL);
|
||||
if (g->dsl_up) vk->DestroyDescriptorSetLayout(vk->device, g->dsl_up, 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);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Winlator Ludashi Native Vulkan Qualcomm Snapdragon GSR 2 (SGSR 2) 3-Pass Compute Backend
|
||||
#pragma once
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <stdint.h>
|
||||
#include "fsr4_seam_proto.h"
|
||||
#include "fsr4_pipeline.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct WlSgsr2Gpu WlSgsr2Gpu;
|
||||
|
||||
WlSgsr2Gpu *wl_sgsr2_gpu_create(const WlVkDispatch *vk, const char *fsr4_dir);
|
||||
void wl_sgsr2_gpu_reset(WlSgsr2Gpu *g);
|
||||
int wl_sgsr2_gpu_is_ready(const WlSgsr2Gpu *g);
|
||||
|
||||
// Returns: 2 = real SGSR 2 recorded, 0 = failed (caller falls back to FSR 3.1)
|
||||
int wl_sgsr2_gpu_dispatch(WlSgsr2Gpu *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);
|
||||
|
||||
void wl_sgsr2_gpu_destroy(WlSgsr2Gpu *g);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,268 @@
|
||||
#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(set = 0, binding = 5) uniform sampler2D u_exposure; // optional 1x1 ExposureTexture
|
||||
|
||||
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, bit 5: has_exposure_tex
|
||||
uint col_base;
|
||||
uint dep_base;
|
||||
uint mv_base;
|
||||
uint react_base;
|
||||
uint pad0;
|
||||
} pc;
|
||||
|
||||
ivec2 unpackBase(uint b) {
|
||||
return ivec2(int(b & 0xFFFFu), int(b >> 16u));
|
||||
}
|
||||
|
||||
float getExposure() {
|
||||
float e = pc.u_expo;
|
||||
if ((pc.flags & 32u) != 0u) {
|
||||
float te = texelFetch(u_exposure, ivec2(0), 0).r;
|
||||
if (!isnan(te) && !isinf(te) && te > 1e-4 && te < 1e4) {
|
||||
e *= te;
|
||||
}
|
||||
}
|
||||
return clamp(e, 1e-4, 1e4);
|
||||
}
|
||||
|
||||
vec3 safeColor(vec3 c) {
|
||||
if (any(isnan(c)) || any(isinf(c))) return vec3(0.0);
|
||||
return clamp(c, vec3(0.0), vec3(64000.0));
|
||||
}
|
||||
|
||||
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 c_base = unpackBase(pc.col_base);
|
||||
ivec2 c_max = col_sz - ivec2(1);
|
||||
ivec2 r_lim = ivec2(int(pc.rw) - 1, int(pc.rh) - 1);
|
||||
float eff_expo = getExposure();
|
||||
|
||||
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 pq = clamp(lr_c + ivec2(dx, dy), ivec2(0), r_lim);
|
||||
ivec2 q = clamp(c_base + pq, ivec2(0), c_max);
|
||||
vec3 raw_c = safeColor(texelFetch(u_color, q, 0).rgb) * eff_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(safeColor(prev_sample.rgb) * eff_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(eff_expo, 1e-6), vec3(0.0), vec3(64000.0));
|
||||
imageStore(u_hist_cur, ivec2(tid), vec4(out_lin, accum_conf));
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
#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(set = 0, binding = 5) uniform sampler2D u_reactive; // optional reactive / DLSS BiasCurrentColorMask
|
||||
layout(set = 0, binding = 6) uniform sampler2D u_exposure; // optional 1x1 ExposureTexture
|
||||
|
||||
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, 1: depth_inv, 2: disp_res_mv, 3: reset, 4: has_reactive, 5: has_exposure_tex
|
||||
uint col_base; // subrect_x | (subrect_y << 16)
|
||||
uint dep_base;
|
||||
uint mv_base;
|
||||
uint react_base;
|
||||
uint pad0;
|
||||
} pc;
|
||||
|
||||
ivec2 unpackBase(uint b) {
|
||||
return ivec2(int(b & 0xFFFFu), int(b >> 16u));
|
||||
}
|
||||
|
||||
float getExposure() {
|
||||
float e = pc.u_expo;
|
||||
if ((pc.flags & 32u) != 0u) {
|
||||
float te = texelFetch(u_exposure, ivec2(0), 0).r;
|
||||
if (!isnan(te) && !isinf(te) && te > 1e-4 && te < 1e4) {
|
||||
e *= te;
|
||||
}
|
||||
}
|
||||
return clamp(e, 1e-4, 1e4);
|
||||
}
|
||||
|
||||
vec3 safeColor(vec3 c) {
|
||||
if (any(isnan(c)) || any(isinf(c))) return vec3(0.0);
|
||||
return clamp(c, vec3(0.0), vec3(64000.0));
|
||||
}
|
||||
|
||||
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 mv_base, 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(mv_base + ivec2(uv_n * vec2(pc.ow, pc.oh)), ivec2(0), mv_sz - ivec2(1));
|
||||
} else {
|
||||
mv_q = clamp(mv_base + clamp(q, ivec2(0), r_lim), ivec2(0), mv_sz - ivec2(1));
|
||||
}
|
||||
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 c_base = unpackBase(pc.col_base);
|
||||
ivec2 d_base = unpackBase(pc.dep_base);
|
||||
ivec2 m_base = unpackBase(pc.mv_base);
|
||||
ivec2 re_base = unpackBase(pc.react_base);
|
||||
|
||||
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_max = dep_sz - ivec2(1);
|
||||
ivec2 dp_c = clamp(d_base + p, ivec2(0), d_max);
|
||||
center_d = texelFetch(u_depth, dp_c, 0).r;
|
||||
best_d = center_d;
|
||||
far_d = center_d;
|
||||
best_q = p;
|
||||
for (int dy = -1; dy <= 1; ++dy) {
|
||||
for (int dx = -1; dx <= 1; ++dx) {
|
||||
if (dx == 0 && dy == 0) continue;
|
||||
ivec2 pq = clamp(p + ivec2(dx, dy), ivec2(0), r_lim);
|
||||
ivec2 q = clamp(d_base + pq, ivec2(0), d_max);
|
||||
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 = pq;
|
||||
}
|
||||
bool farther = dep_inv ? (d < far_d) : (d > far_d);
|
||||
if (farther) {
|
||||
far_d = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vec2 vel_dilated = fetchRawMV(best_q, mv_sz, m_base, r_lim);
|
||||
vec2 vel_center = fetchRawMV(p, mv_sz, m_base, 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);
|
||||
|
||||
// Incorporate game-supplied Reactive / DLSS BiasCurrentColorMask (kills RDR2 hair/foliage/water ghosting!)
|
||||
if ((pc.flags & 16u) != 0u) {
|
||||
ivec2 re_sz = textureSize(u_reactive, 0);
|
||||
if (re_sz.x > 1 && re_sz.y > 1) {
|
||||
ivec2 rq = clamp(re_base + p, ivec2(0), re_sz - ivec2(1));
|
||||
float react_m = clamp(texelFetch(u_reactive, rq, 0).r, 0.0, 1.0);
|
||||
disocc = clamp(max(disocc, react_m), 0.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
float eff_expo = getExposure();
|
||||
ivec2 col_q = clamp(c_base + p, ivec2(0), col_sz - ivec2(1));
|
||||
vec3 col = safeColor(texelFetch(u_color, col_q, 0).rgb) * eff_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,101 @@
|
||||
#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(set = 0, binding = 2) uniform sampler2D u_exposure;
|
||||
|
||||
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 col_base;
|
||||
uint dep_base;
|
||||
uint mv_base;
|
||||
uint react_base;
|
||||
uint pad0;
|
||||
} pc;
|
||||
|
||||
const float FSR_RCAS_LIMIT = 0.25 - 1.0 / 16.0;
|
||||
|
||||
float getExposure() {
|
||||
float e = pc.u_expo;
|
||||
if ((pc.flags & 32u) != 0u) {
|
||||
float te = texelFetch(u_exposure, ivec2(0), 0).r;
|
||||
if (!isnan(te) && !isinf(te) && te > 1e-4 && te < 1e4) e *= te;
|
||||
}
|
||||
return clamp(e, 1e-4, 1e4);
|
||||
}
|
||||
|
||||
vec3 toMuLaw(vec3 c, float e) {
|
||||
c = max(c, vec3(0.0)) * e;
|
||||
return max(vec3(0.1174) * log(vec3(1.0) + 150.0 * c), vec3(0.0));
|
||||
}
|
||||
|
||||
vec3 fromMuLaw(vec3 m, float e) {
|
||||
return max((exp(8.51788 * m) - 1.0) / 150.0, vec3(0.0)) / max(e, 1e-6);
|
||||
}
|
||||
|
||||
vec3 fetchMu(ivec2 p, ivec2 lim, float e) {
|
||||
return toMuLaw(texelFetch(u_in_img, clamp(p, ivec2(0), lim), 0).rgb, e);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
float sharp = clamp(pc.u_sharp, 0.0, 1.0);
|
||||
if (sharp < 0.01) {
|
||||
imageStore(u_out_img, sp, vec4(clamp(texelFetch(u_in_img, sp, 0).rgb, vec3(0.0), vec3(64000.0)), 1.0));
|
||||
return;
|
||||
}
|
||||
|
||||
float eff_expo = getExposure();
|
||||
vec3 b = fetchMu(sp + ivec2(0, -1), lim, eff_expo);
|
||||
vec3 d = fetchMu(sp + ivec2(-1, 0), lim, eff_expo);
|
||||
vec3 e = fetchMu(sp, lim, eff_expo);
|
||||
vec3 f = fetchMu(sp + ivec2(1, 0), lim, eff_expo);
|
||||
vec3 h = fetchMu(sp + ivec2(0, 1), lim, eff_expo);
|
||||
|
||||
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));
|
||||
|
||||
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, eff_expo), 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;
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
#version 450
|
||||
// Qualcomm Snapdragon Game Super Resolution 2 (SGSR 2) — 3-Pass Compute: Pass 2 (Activate)
|
||||
// Based directly on official quic/snapdragon-gsr sgsr/v2/include/glsl_3_pass_cs/sgsr2_activate.comp
|
||||
// (Copyright (c) 2024, Qualcomm Innovation Center, Inc. SPDX-License-Identifier: BSD-3-Clause)
|
||||
#define EPSILON 1.19e-07
|
||||
|
||||
float DecodeColorY(uint sample32) {
|
||||
uint x11 = sample32 >> 21u;
|
||||
return float(x11) * (1.0 / 2047.5);
|
||||
}
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
|
||||
|
||||
layout(std140, set = 0, binding = 0) uniform Params {
|
||||
uvec2 renderSize;
|
||||
uvec2 displaySize;
|
||||
vec2 InViewportSizeInverse;
|
||||
vec2 displaySizeRcp;
|
||||
vec2 jitterOffset;
|
||||
vec2 mvScale;
|
||||
vec2 jitterCancel;
|
||||
float preExposure;
|
||||
float cameraFovAngleHor;
|
||||
uint flags; // bit0: has_depth, 1: depth_inv, 2: disp_res_mv, 3: reset, 4: has_reactive, 5: has_expo_tex
|
||||
uint col_base;
|
||||
uint dep_base;
|
||||
uint mv_base;
|
||||
uint react_base;
|
||||
float sharpness;
|
||||
vec2 pad0;
|
||||
} params;
|
||||
|
||||
layout(set = 0, binding = 1) uniform usampler2D PrevLumaHistory;
|
||||
layout(set = 0, binding = 2) uniform sampler2D MotionDepthAlphaBuffer;
|
||||
layout(set = 0, binding = 3) uniform usampler2D YCoCgColor;
|
||||
layout(set = 0, binding = 4, rgba16f) writeonly uniform image2D MotionDepthClipAlphaBuffer;
|
||||
layout(set = 0, binding = 5, r32ui) writeonly uniform uimage2D LumaHistory;
|
||||
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (p.x >= int(params.renderSize.x) || p.y >= int(params.renderSize.y)) return;
|
||||
|
||||
const ivec2 sampleOffset[4] = ivec2[4](
|
||||
ivec2(-1, -1),
|
||||
ivec2(-1, +0),
|
||||
ivec2(+0, -1),
|
||||
ivec2(+0, +0)
|
||||
);
|
||||
|
||||
bool has_depth = (params.flags & 1u) != 0u;
|
||||
bool dep_inv = (params.flags & 2u) != 0u;
|
||||
bool is_reset = (params.flags & 8u) != 0u;
|
||||
|
||||
vec2 ViewportUV = (vec2(p) + vec2(0.5)) * params.InViewportSizeInverse;
|
||||
uint luma_reference32 = texelFetch(YCoCgColor, p, 0).x;
|
||||
float luma_reference = DecodeColorY(luma_reference32);
|
||||
|
||||
vec4 mda = texelFetch(MotionDepthAlphaBuffer, p, 0);
|
||||
float depth = mda.z;
|
||||
float alphamask = mda.w;
|
||||
vec2 motion = mda.xy;
|
||||
|
||||
vec2 PrevUV = vec2(-0.5 * motion.x + ViewportUV.x, -0.5 * motion.y + ViewportUV.y);
|
||||
float depthclip = 0.0;
|
||||
|
||||
bool depth_valid = has_depth && (dep_inv ? (depth > 1.0e-05) : (depth < 1.0 - 1.0e-05));
|
||||
if (depth_valid) {
|
||||
vec2 Prevf_sample = PrevUV * vec2(params.renderSize) - 0.5;
|
||||
vec2 Prevfrac = Prevf_sample - floor(Prevf_sample);
|
||||
float OneMinusPrevfacx = 1.0 - Prevfrac.x;
|
||||
|
||||
float Bilinweights[4] = float[4](
|
||||
OneMinusPrevfacx - OneMinusPrevfacx * Prevfrac.y,
|
||||
Prevfrac.x - Prevfrac.x * Prevfrac.y,
|
||||
OneMinusPrevfacx * Prevfrac.y,
|
||||
Prevfrac.x * Prevfrac.y
|
||||
);
|
||||
|
||||
float diagonal_length = length(vec2(params.renderSize));
|
||||
float Wdepth = 0.0;
|
||||
float Ksep = 1.37e-05;
|
||||
float Kfov = max(params.cameraFovAngleHor, 0.25);
|
||||
float Ksep_Kfov_diagonal = Ksep * Kfov * diagonal_length;
|
||||
|
||||
for (int index = 0; index < 4; index += 2) {
|
||||
vec4 gPrevdepth = textureGatherOffset(MotionDepthAlphaBuffer, PrevUV, sampleOffset[index], 2);
|
||||
float tdepth1 = dep_inv ? max(gPrevdepth.x, gPrevdepth.y) : min(gPrevdepth.x, gPrevdepth.y);
|
||||
float tdepth2 = dep_inv ? max(gPrevdepth.z, gPrevdepth.w) : min(gPrevdepth.z, gPrevdepth.w);
|
||||
float fPrevdepth = dep_inv ? max(tdepth1, tdepth2) : min(tdepth1, tdepth2);
|
||||
|
||||
float near_ref = dep_inv ? max(fPrevdepth, depth) : (1.0 - min(fPrevdepth, depth));
|
||||
float Depthsep = Ksep_Kfov_diagonal * max(near_ref, 1e-4);
|
||||
float weight = Bilinweights[index];
|
||||
Wdepth += clamp(Depthsep / (abs(fPrevdepth - depth) + EPSILON), 0.0, 1.0) * weight;
|
||||
|
||||
vec2 gPrevdepth2 = textureGatherOffset(MotionDepthAlphaBuffer, PrevUV, sampleOffset[index + 1], 2).zw;
|
||||
fPrevdepth = dep_inv ? max(max(gPrevdepth2.x, gPrevdepth2.y), tdepth2)
|
||||
: min(min(gPrevdepth2.x, gPrevdepth2.y), tdepth2);
|
||||
near_ref = dep_inv ? max(fPrevdepth, depth) : (1.0 - min(fPrevdepth, depth));
|
||||
Depthsep = Ksep_Kfov_diagonal * max(near_ref, 1e-4);
|
||||
weight = Bilinweights[index + 1];
|
||||
Wdepth += clamp(Depthsep / (abs(fPrevdepth - depth) + EPSILON), 0.0, 1.0) * weight;
|
||||
}
|
||||
depthclip = clamp(1.0 - Wdepth, 0.0, 1.0);
|
||||
}
|
||||
|
||||
vec2 current_luma_diff;
|
||||
uint prev_luma_diff_pack = textureGather(PrevLumaHistory, clamp(PrevUV, vec2(0.0), vec2(1.0)), 0).w;
|
||||
vec2 prev_luma_diff;
|
||||
prev_luma_diff.x = unpackHalf2x16(prev_luma_diff_pack >> 16u).x;
|
||||
prev_luma_diff.y = unpackHalf2x16(prev_luma_diff_pack & 0xFFFFu).x;
|
||||
|
||||
bool enable = false;
|
||||
if (depthclip + float(is_reset ? 1u : 0u) < 0.1) {
|
||||
enable = (all(greaterThanEqual(PrevUV, vec2(0.0))) && all(lessThanEqual(PrevUV, vec2(1.0))));
|
||||
}
|
||||
float luma_diff = luma_reference - prev_luma_diff.x;
|
||||
if (!enable) {
|
||||
current_luma_diff = vec2(0.0);
|
||||
} else {
|
||||
current_luma_diff.x = luma_reference;
|
||||
current_luma_diff.y = (prev_luma_diff.y != 0.0)
|
||||
? ((sign(luma_diff) == sign(prev_luma_diff.y)) ? (sign(luma_diff) * min(abs(prev_luma_diff.y), abs(luma_diff))) : prev_luma_diff.y)
|
||||
: luma_diff;
|
||||
}
|
||||
|
||||
alphamask = floor(alphamask) + 0.5 * float((current_luma_diff.x != 0.0) && (abs(current_luma_diff.y) != abs(luma_diff)));
|
||||
uint pack = (packHalf2x16(vec2(current_luma_diff.x, 0.0)) << 16u) | packHalf2x16(vec2(current_luma_diff.y, 0.0));
|
||||
imageStore(LumaHistory, p, uvec4(pack));
|
||||
imageStore(MotionDepthClipAlphaBuffer, p, vec4(motion, depthclip, alphamask));
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#version 450
|
||||
// Qualcomm Snapdragon Game Super Resolution 2 (SGSR 2) — 3-Pass Compute: Pass 1 (Convert)
|
||||
// Based directly on official quic/snapdragon-gsr sgsr/v2/include/glsl_3_pass_cs/sgsr2_convert.comp
|
||||
// (Copyright (c) 2024, Qualcomm Innovation Center, Inc. SPDX-License-Identifier: BSD-3-Clause)
|
||||
// Adapted for Winlator Vulkan 1.3 PC-game DLSS/FSR inputs (full-screen MVs, reverse-Z, reactive mask, exposure, subrects).
|
||||
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
|
||||
|
||||
layout(std140, set = 0, binding = 0) uniform Params {
|
||||
uvec2 renderSize;
|
||||
uvec2 displaySize;
|
||||
vec2 renderSizeRcp;
|
||||
vec2 displaySizeRcp;
|
||||
vec2 jitterOffset;
|
||||
vec2 mvScale;
|
||||
vec2 jitterCancel;
|
||||
float preExposure;
|
||||
float cameraFovAngleHor;
|
||||
uint flags; // bit0: has_depth, 1: depth_inv, 2: disp_res_mv, 3: reset, 4: has_reactive, 5: has_expo_tex
|
||||
uint col_base; // subrect_x | (subrect_y << 16)
|
||||
uint dep_base;
|
||||
uint mv_base;
|
||||
uint react_base;
|
||||
float sharpness;
|
||||
vec2 pad0;
|
||||
} params;
|
||||
|
||||
layout(set = 0, binding = 1) uniform sampler2D InputColor;
|
||||
layout(set = 0, binding = 2) uniform sampler2D InputDepth;
|
||||
layout(set = 0, binding = 3) uniform sampler2D InputVelocity;
|
||||
layout(set = 0, binding = 4) uniform sampler2D InputReactive;
|
||||
layout(set = 0, binding = 5) uniform sampler2D InputExposure;
|
||||
layout(set = 0, binding = 6, r32ui) writeonly uniform uimage2D YCoCgColor;
|
||||
layout(set = 0, binding = 7, rgba16f) writeonly uniform image2D MotionDepthAlphaBuffer;
|
||||
|
||||
ivec2 unpackBase(uint b) {
|
||||
return ivec2(int(b & 0xFFFFu), int(b >> 16u));
|
||||
}
|
||||
|
||||
float getExposure() {
|
||||
float e = params.preExposure;
|
||||
if ((params.flags & 32u) != 0u) {
|
||||
float te = texelFetch(InputExposure, ivec2(0), 0).r;
|
||||
if (!isnan(te) && !isinf(te) && te > 1e-4 && te < 1e4) e *= te;
|
||||
}
|
||||
return clamp(e, 1e-4, 1e4);
|
||||
}
|
||||
|
||||
vec3 safeColor(vec3 c) {
|
||||
if (any(isnan(c)) || any(isinf(c))) return vec3(0.0);
|
||||
return clamp(c, vec3(0.0), vec3(64000.0));
|
||||
}
|
||||
|
||||
vec2 fetchUVVelocity(ivec2 q, ivec2 mv_sz, ivec2 mv_base, ivec2 r_lim) {
|
||||
ivec2 mv_q;
|
||||
if ((params.flags & 4u) != 0u) {
|
||||
vec2 uv_n = (vec2(q) + vec2(0.5)) * params.renderSizeRcp;
|
||||
mv_q = clamp(mv_base + ivec2(uv_n * vec2(params.displaySize)), ivec2(0), mv_sz - ivec2(1));
|
||||
} else {
|
||||
mv_q = clamp(mv_base + clamp(q, ivec2(0), r_lim), ivec2(0), mv_sz - ivec2(1));
|
||||
}
|
||||
vec2 raw = texelFetch(InputVelocity, mv_q, 0).xy;
|
||||
vec2 vel = raw * params.mvScale + params.jitterCancel;
|
||||
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(params.renderSize.x) || p.y >= int(params.renderSize.y)) return;
|
||||
|
||||
ivec2 r_lim = ivec2(params.renderSize) - ivec2(1);
|
||||
ivec2 col_sz = textureSize(InputColor, 0);
|
||||
ivec2 dep_sz = textureSize(InputDepth, 0);
|
||||
ivec2 mv_sz = textureSize(InputVelocity, 0);
|
||||
ivec2 c_base = unpackBase(params.col_base);
|
||||
ivec2 d_base = unpackBase(params.dep_base);
|
||||
ivec2 m_base = unpackBase(params.mv_base);
|
||||
ivec2 re_base = unpackBase(params.react_base);
|
||||
|
||||
bool has_depth = (params.flags & 1u) != 0u && dep_sz.x > 1 && dep_sz.y > 1;
|
||||
bool dep_inv = (params.flags & 2u) != 0u;
|
||||
|
||||
// 3x3 nearest-depth dilation (supports both standard-Z and reverse-Z)
|
||||
ivec2 best_q = p;
|
||||
float NearestZ = dep_inv ? 0.0 : 1.0;
|
||||
if (has_depth) {
|
||||
ivec2 d_max = dep_sz - ivec2(1);
|
||||
NearestZ = texelFetch(InputDepth, clamp(d_base + p, ivec2(0), d_max), 0).x;
|
||||
for (int dy = -1; dy <= 1; ++dy) {
|
||||
for (int dx = -1; dx <= 1; ++dx) {
|
||||
if (dx == 0 && dy == 0) continue;
|
||||
ivec2 pq = clamp(p + ivec2(dx, dy), ivec2(0), r_lim);
|
||||
float d = texelFetch(InputDepth, clamp(d_base + pq, ivec2(0), d_max), 0).x;
|
||||
bool closer = dep_inv ? (d > NearestZ) : (d < NearestZ);
|
||||
if (closer) {
|
||||
NearestZ = d;
|
||||
best_q = pq;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dilated UV velocity -> SGSR 2 NDC motion convention: PrevUV = ViewportUV - 0.5 * motion = ViewportUV + vel
|
||||
vec2 vel_dilated = fetchUVVelocity(best_q, mv_sz, m_base, r_lim);
|
||||
vec2 vel_center = fetchUVVelocity(p, mv_sz, m_base, r_lim);
|
||||
vec2 motion = -2.0 * vel_dilated;
|
||||
|
||||
// Qualcomm SGSR 2 reversible max-RGB tonemap + 11-11-10 YCoCg packing into R32UI
|
||||
float eff_expo = getExposure();
|
||||
vec3 Colorrgb = safeColor(texelFetch(InputColor, clamp(c_base + p, ivec2(0), col_sz - ivec2(1)), 0).xyz) * eff_expo;
|
||||
Colorrgb /= vec3(max(max(Colorrgb.x, Colorrgb.y), Colorrgb.z) + 1.0);
|
||||
|
||||
vec3 Colorycocg;
|
||||
Colorycocg.x = 0.25 * (Colorrgb.x + 2.0 * Colorrgb.y + Colorrgb.z);
|
||||
Colorycocg.y = clamp(0.5 * Colorrgb.x + 0.5 - 0.5 * Colorrgb.z, 0.0, 1.0);
|
||||
Colorycocg.z = clamp(Colorycocg.x + Colorycocg.y - Colorrgb.x, 0.0, 1.0);
|
||||
|
||||
uint x11 = uint(clamp(Colorycocg.x, 0.0, 1.0) * 2047.5);
|
||||
uint y11 = uint(clamp(Colorycocg.y, 0.0, 1.0) * 2047.5);
|
||||
uint z10 = uint(clamp(Colorycocg.z, 0.0, 1.0) * 1023.5);
|
||||
imageStore(YCoCgColor, p, uvec4((x11 << 21u) | (y11 << 10u) | z10));
|
||||
|
||||
// Reactive / translucency alpha_mask in Qualcomm's [0..1000] encoding (unpacked by * 0.001 in upscale)
|
||||
float react_m = 0.0;
|
||||
if ((params.flags & 16u) != 0u) {
|
||||
ivec2 re_sz = textureSize(InputReactive, 0);
|
||||
if (re_sz.x > 1 && re_sz.y > 1) {
|
||||
react_m = clamp(texelFetch(InputReactive, clamp(re_base + p, ivec2(0), re_sz - ivec2(1)), 0).r, 0.0, 1.0);
|
||||
}
|
||||
}
|
||||
// Also react mildly on sharp silhouette MV jumps to prevent trailing behind fast-moving characters
|
||||
float mv_diff_px = length((vel_dilated - vel_center) * vec2(params.displaySize));
|
||||
float alpha_mask = clamp(max(react_m * 0.85, clamp((mv_diff_px - 1.5) * 0.12, 0.0, 0.5)), 0.0, 1.0) * 1000.0;
|
||||
|
||||
imageStore(MotionDepthAlphaBuffer, p, vec4(motion, NearestZ, alpha_mask));
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
#version 450
|
||||
// Qualcomm Snapdragon Game Super Resolution 2 (SGSR 2) — 3-Pass Compute: Pass 3 (Upscale)
|
||||
// Based directly on official quic/snapdragon-gsr sgsr/v2/include/glsl_3_pass_cs/sgsr2_upscale.comp
|
||||
// (Copyright (c) 2024, Qualcomm Innovation Center, Inc. SPDX-License-Identifier: BSD-3-Clause)
|
||||
float FastLanczos(float base) {
|
||||
float y = base - 1.0;
|
||||
float y2 = y * y;
|
||||
float y_temp = 0.75 * y + y2;
|
||||
return y_temp * y2;
|
||||
}
|
||||
|
||||
vec3 DecodeColor(uint sample32) {
|
||||
uint x11 = sample32 >> 21u;
|
||||
uint y11 = sample32 & (2047u << 10u);
|
||||
uint z10 = sample32 & 1023u;
|
||||
vec3 samplecolor;
|
||||
samplecolor.x = (float(x11) * (1.0 / 2047.5));
|
||||
samplecolor.y = (float(y11) * (4.76953602e-7)) - 0.5;
|
||||
samplecolor.z = (float(z10) * (1.0 / 1023.5)) - 0.5;
|
||||
return samplecolor;
|
||||
}
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
|
||||
|
||||
layout(std140, set = 0, binding = 0) uniform Params {
|
||||
uvec2 renderSize;
|
||||
uvec2 displaySize;
|
||||
vec2 renderSizeRcp;
|
||||
vec2 displaySizeRcp;
|
||||
vec2 jitterOffset;
|
||||
vec2 mvScale;
|
||||
vec2 jitterCancel;
|
||||
float preExposure;
|
||||
float cameraFovAngleHor;
|
||||
uint flags; // bit0: has_depth, 1: depth_inv, 2: disp_res_mv, 3: reset, 4: has_reactive, 5: has_expo_tex
|
||||
uint col_base;
|
||||
uint dep_base;
|
||||
uint mv_base;
|
||||
uint react_base;
|
||||
float sharpness;
|
||||
vec2 pad0;
|
||||
} params;
|
||||
|
||||
layout(set = 0, binding = 1) uniform sampler2D PrevHistoryOutput;
|
||||
layout(set = 0, binding = 2) uniform sampler2D MotionDepthClipAlphaBuffer;
|
||||
layout(set = 0, binding = 3) uniform usampler2D YCoCgColor;
|
||||
layout(set = 0, binding = 4, rgba16f) writeonly uniform image2D HistoryOutput;
|
||||
layout(set = 0, binding = 5, rgba16f) writeonly uniform image2D SceneColorOutput;
|
||||
layout(set = 0, binding = 6) uniform sampler2D InputExposure;
|
||||
|
||||
float getExposure() {
|
||||
float e = params.preExposure;
|
||||
if ((params.flags & 32u) != 0u) {
|
||||
float te = texelFetch(InputExposure, ivec2(0), 0).r;
|
||||
if (!isnan(te) && !isinf(te) && te > 1e-4 && te < 1e4) e *= te;
|
||||
}
|
||||
return clamp(e, 1e-4, 1e4);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 gid = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (gid.x >= int(params.displaySize.x) || gid.y >= int(params.displaySize.y)) return;
|
||||
|
||||
float resetF = ((params.flags & 8u) != 0u) ? 1.0 : 0.0;
|
||||
float Biasmax_viewportXScale = min(float(params.displaySize.x) / float(params.renderSize.x), 1.99);
|
||||
float scalefactor = min(20.0, pow((float(params.displaySize.x) / float(params.renderSize.x)) *
|
||||
(float(params.displaySize.y) / float(params.renderSize.y)), 3.0));
|
||||
vec2 HistoryInfoViewportSizeInverse = params.displaySizeRcp;
|
||||
vec2 HistoryInfoViewportSize = vec2(params.displaySize);
|
||||
vec2 InputJitter = params.jitterOffset;
|
||||
vec2 InputInfoViewportSize = vec2(params.renderSize);
|
||||
vec2 Hruv = (vec2(gid) + vec2(0.5)) * HistoryInfoViewportSizeInverse;
|
||||
|
||||
vec2 Jitteruv;
|
||||
Jitteruv.x = clamp(Hruv.x + (InputJitter.x * params.renderSizeRcp.x), 0.0, 1.0);
|
||||
Jitteruv.y = clamp(Hruv.y + (InputJitter.y * params.renderSizeRcp.y), 0.0, 1.0);
|
||||
|
||||
ivec2 r_lim = ivec2(params.renderSize) - ivec2(1);
|
||||
ivec2 InputPos = clamp(ivec2(Jitteruv * InputInfoViewportSize), ivec2(0), r_lim);
|
||||
|
||||
float alphab = texelFetch(MotionDepthClipAlphaBuffer, InputPos, 0).w;
|
||||
vec3 mda = textureLod(MotionDepthClipAlphaBuffer, Jitteruv, 0.0).xyz;
|
||||
vec2 Motion = mda.xy;
|
||||
|
||||
vec2 PrevUV_raw = vec2(-0.5 * Motion.x + Hruv.x, -0.5 * Motion.y + Hruv.y);
|
||||
bool offscreen = (PrevUV_raw.x < 0.0 || PrevUV_raw.x > 1.0 || PrevUV_raw.y < 0.0 || PrevUV_raw.y > 1.0);
|
||||
vec2 PrevUV = clamp(PrevUV_raw, vec2(0.0), vec2(1.0));
|
||||
|
||||
float depthfactor = mda.z;
|
||||
float history_value = fract(alphab);
|
||||
float alphamask = clamp((alphab - history_value) * 0.001, 0.0, 1.0);
|
||||
history_value *= 2.0;
|
||||
|
||||
vec4 History = textureLod(PrevHistoryOutput, PrevUV, 0.0);
|
||||
vec3 HistoryColor = History.xyz;
|
||||
float Historyw = History.w;
|
||||
float Wfactor = max(clamp(abs(Historyw), 0.0, 1.0), alphamask);
|
||||
|
||||
// Upsample and compute variance bounding box (Qualcomm SGSR 2 9-tap FastLanczos on R32UI YCoCg)
|
||||
vec4 Upsampledcw = vec4(0.0);
|
||||
float kernelfactor = clamp(Wfactor + resetF, 0.0, 1.0);
|
||||
float biasmax = Biasmax_viewportXScale - Biasmax_viewportXScale * kernelfactor;
|
||||
float biasmin = max(1.0, 0.3 + 0.3 * biasmax);
|
||||
float biasfactor = max(0.25 * depthfactor, kernelfactor);
|
||||
float kernelbias = mix(biasmax, biasmin, biasfactor);
|
||||
float motion_viewport_len = length(Motion * HistoryInfoViewportSize);
|
||||
float curvebias = mix(-2.0, -3.0, clamp(motion_viewport_len * 0.02, 0.0, 1.0));
|
||||
|
||||
vec3 rectboxcenter = vec3(0.0);
|
||||
vec3 rectboxvar = vec3(0.0);
|
||||
float rectboxweight = 0.0;
|
||||
vec2 srcpos = vec2(InputPos) + vec2(0.5) - InputJitter;
|
||||
vec2 srcOutputPos = Hruv * InputInfoViewportSize;
|
||||
|
||||
kernelbias *= 0.5;
|
||||
float kernelbias2 = kernelbias * kernelbias;
|
||||
vec2 srcpos_srcOutputPos = srcpos - srcOutputPos;
|
||||
|
||||
ivec2 InputPosBtmRight = min(ivec2(1) + InputPos, r_lim);
|
||||
vec2 gatherCoord = vec2(InputPos) * params.renderSizeRcp;
|
||||
uint btmRight = texelFetch(YCoCgColor, InputPosBtmRight, 0).x;
|
||||
uvec4 topleft = textureGather(YCoCgColor, gatherCoord);
|
||||
uvec2 topRight = textureGather(YCoCgColor, gatherCoord + vec2(params.renderSizeRcp.x, 0.0)).yz;
|
||||
uvec2 bottomLeft = textureGather(YCoCgColor, gatherCoord + vec2(0.0, params.renderSizeRcp.y)).xy;
|
||||
|
||||
vec3 rectboxmin;
|
||||
vec3 rectboxmax;
|
||||
{
|
||||
rectboxmin = DecodeColor(btmRight);
|
||||
vec2 baseoffset = srcpos_srcOutputPos + vec2(1.0, 1.0);
|
||||
float baseoffset_dot = dot(baseoffset, baseoffset);
|
||||
float weight = FastLanczos(clamp(baseoffset_dot * kernelbias2, 0.0, 1.0));
|
||||
Upsampledcw += vec4(rectboxmin * weight, weight);
|
||||
float boxweight = exp(baseoffset_dot * curvebias);
|
||||
rectboxmax = rectboxmin;
|
||||
vec3 wsample = rectboxmin * boxweight;
|
||||
rectboxcenter = wsample;
|
||||
rectboxvar = rectboxmin * wsample;
|
||||
rectboxweight = boxweight;
|
||||
}
|
||||
{
|
||||
vec3 samplecolor = DecodeColor(bottomLeft.x);
|
||||
vec2 baseoffset = srcpos_srcOutputPos + vec2(-1.0, 1.0);
|
||||
float baseoffset_dot = dot(baseoffset, baseoffset);
|
||||
float weight = FastLanczos(clamp(baseoffset_dot * kernelbias2, 0.0, 1.0));
|
||||
Upsampledcw += vec4(samplecolor * weight, weight);
|
||||
float boxweight = exp(baseoffset_dot * curvebias);
|
||||
rectboxmin = min(rectboxmin, samplecolor);
|
||||
rectboxmax = max(rectboxmax, samplecolor);
|
||||
vec3 wsample = samplecolor * boxweight;
|
||||
rectboxcenter += wsample;
|
||||
rectboxvar += samplecolor * wsample;
|
||||
rectboxweight += boxweight;
|
||||
}
|
||||
{
|
||||
vec3 samplecolor = DecodeColor(bottomLeft.y);
|
||||
vec2 baseoffset = srcpos_srcOutputPos + vec2(0.0, 1.0);
|
||||
float baseoffset_dot = dot(baseoffset, baseoffset);
|
||||
float weight = FastLanczos(clamp(baseoffset_dot * kernelbias2, 0.0, 1.0));
|
||||
Upsampledcw += vec4(samplecolor * weight, weight);
|
||||
float boxweight = exp(baseoffset_dot * curvebias);
|
||||
rectboxmin = min(rectboxmin, samplecolor);
|
||||
rectboxmax = max(rectboxmax, samplecolor);
|
||||
vec3 wsample = samplecolor * boxweight;
|
||||
rectboxcenter += wsample;
|
||||
rectboxvar += samplecolor * wsample;
|
||||
rectboxweight += boxweight;
|
||||
}
|
||||
{
|
||||
vec3 samplecolor = DecodeColor(topRight.x);
|
||||
vec2 baseoffset = srcpos_srcOutputPos + vec2(1.0, 0.0);
|
||||
float baseoffset_dot = dot(baseoffset, baseoffset);
|
||||
float weight = FastLanczos(clamp(baseoffset_dot * kernelbias2, 0.0, 1.0));
|
||||
Upsampledcw += vec4(samplecolor * weight, weight);
|
||||
float boxweight = exp(baseoffset_dot * curvebias);
|
||||
rectboxmin = min(rectboxmin, samplecolor);
|
||||
rectboxmax = max(rectboxmax, samplecolor);
|
||||
vec3 wsample = samplecolor * boxweight;
|
||||
rectboxcenter += wsample;
|
||||
rectboxvar += samplecolor * wsample;
|
||||
rectboxweight += boxweight;
|
||||
}
|
||||
{
|
||||
vec3 samplecolor = DecodeColor(topRight.y);
|
||||
vec2 baseoffset = srcpos_srcOutputPos + vec2(1.0, -1.0);
|
||||
float baseoffset_dot = dot(baseoffset, baseoffset);
|
||||
float weight = FastLanczos(clamp(baseoffset_dot * kernelbias2, 0.0, 1.0));
|
||||
Upsampledcw += vec4(samplecolor * weight, weight);
|
||||
float boxweight = exp(baseoffset_dot * curvebias);
|
||||
rectboxmin = min(rectboxmin, samplecolor);
|
||||
rectboxmax = max(rectboxmax, samplecolor);
|
||||
vec3 wsample = samplecolor * boxweight;
|
||||
rectboxcenter += wsample;
|
||||
rectboxvar += samplecolor * wsample;
|
||||
rectboxweight += boxweight;
|
||||
}
|
||||
{
|
||||
vec3 samplecolor = DecodeColor(topleft.x);
|
||||
vec2 baseoffset = srcpos_srcOutputPos + vec2(-1.0, 0.0);
|
||||
float baseoffset_dot = dot(baseoffset, baseoffset);
|
||||
float weight = FastLanczos(clamp(baseoffset_dot * kernelbias2, 0.0, 1.0));
|
||||
Upsampledcw += vec4(samplecolor * weight, weight);
|
||||
float boxweight = exp(baseoffset_dot * curvebias);
|
||||
rectboxmin = min(rectboxmin, samplecolor);
|
||||
rectboxmax = max(rectboxmax, samplecolor);
|
||||
vec3 wsample = samplecolor * boxweight;
|
||||
rectboxcenter += wsample;
|
||||
rectboxvar += samplecolor * wsample;
|
||||
rectboxweight += boxweight;
|
||||
}
|
||||
{
|
||||
vec3 samplecolor = DecodeColor(topleft.y);
|
||||
vec2 baseoffset = srcpos_srcOutputPos;
|
||||
float baseoffset_dot = dot(baseoffset, baseoffset);
|
||||
float weight = FastLanczos(clamp(baseoffset_dot * kernelbias2, 0.0, 1.0));
|
||||
Upsampledcw += vec4(samplecolor * weight, weight);
|
||||
float boxweight = exp(baseoffset_dot * curvebias);
|
||||
rectboxmin = min(rectboxmin, samplecolor);
|
||||
rectboxmax = max(rectboxmax, samplecolor);
|
||||
vec3 wsample = samplecolor * boxweight;
|
||||
rectboxcenter += wsample;
|
||||
rectboxvar += samplecolor * wsample;
|
||||
rectboxweight += boxweight;
|
||||
}
|
||||
{
|
||||
vec3 samplecolor = DecodeColor(topleft.z);
|
||||
vec2 baseoffset = srcpos_srcOutputPos + vec2(0.0, -1.0);
|
||||
float baseoffset_dot = dot(baseoffset, baseoffset);
|
||||
float weight = FastLanczos(clamp(baseoffset_dot * kernelbias2, 0.0, 1.0));
|
||||
Upsampledcw += vec4(samplecolor * weight, weight);
|
||||
float boxweight = exp(baseoffset_dot * curvebias);
|
||||
rectboxmin = min(rectboxmin, samplecolor);
|
||||
rectboxmax = max(rectboxmax, samplecolor);
|
||||
vec3 wsample = samplecolor * boxweight;
|
||||
rectboxcenter += wsample;
|
||||
rectboxvar += samplecolor * wsample;
|
||||
rectboxweight += boxweight;
|
||||
}
|
||||
{
|
||||
vec3 samplecolor = DecodeColor(topleft.w);
|
||||
vec2 baseoffset = srcpos_srcOutputPos + vec2(-1.0, -1.0);
|
||||
float baseoffset_dot = dot(baseoffset, baseoffset);
|
||||
float weight = FastLanczos(clamp(baseoffset_dot * kernelbias2, 0.0, 1.0));
|
||||
Upsampledcw += vec4(samplecolor * weight, weight);
|
||||
float boxweight = exp(baseoffset_dot * curvebias);
|
||||
rectboxmin = min(rectboxmin, samplecolor);
|
||||
rectboxmax = max(rectboxmax, samplecolor);
|
||||
vec3 wsample = samplecolor * boxweight;
|
||||
rectboxcenter += wsample;
|
||||
rectboxvar += samplecolor * wsample;
|
||||
rectboxweight += boxweight;
|
||||
}
|
||||
|
||||
rectboxweight = 1.0 / max(rectboxweight, 1e-6);
|
||||
rectboxcenter *= rectboxweight;
|
||||
rectboxvar *= rectboxweight;
|
||||
rectboxvar = sqrt(abs(rectboxvar - rectboxcenter * rectboxcenter));
|
||||
|
||||
Upsampledcw.xyz = clamp(Upsampledcw.xyz / max(Upsampledcw.w, 1e-5), rectboxmin - vec3(0.05), rectboxmax + vec3(0.05));
|
||||
Upsampledcw.w = Upsampledcw.w * (1.0 / 3.0);
|
||||
|
||||
float tcontribute = history_value * clamp(rectboxvar.x * 10.0, 0.0, 1.0);
|
||||
float OneMinusWfactor = 1.0 - Wfactor;
|
||||
tcontribute = tcontribute * OneMinusWfactor;
|
||||
|
||||
float baseupdate = OneMinusWfactor - OneMinusWfactor * depthfactor;
|
||||
baseupdate = min(baseupdate, mix(baseupdate, Upsampledcw.w * 10.0, clamp(10.0 * motion_viewport_len, 0.0, 1.0)));
|
||||
baseupdate = min(baseupdate, mix(baseupdate, Upsampledcw.w, clamp(motion_viewport_len * 0.05, 0.0, 1.0)));
|
||||
float basealpha = baseupdate;
|
||||
|
||||
const float EPSILON = 1.192e-07;
|
||||
float boxscale = max(depthfactor, clamp(motion_viewport_len * 0.05, 0.0, 1.0));
|
||||
float boxsize = mix(scalefactor, 1.0, boxscale);
|
||||
vec3 sboxvar = rectboxvar * boxsize;
|
||||
vec3 boxmin = rectboxcenter - sboxvar;
|
||||
vec3 boxmax = rectboxcenter + sboxvar;
|
||||
rectboxmax = min(rectboxmax, boxmax);
|
||||
rectboxmin = max(rectboxmin, boxmin);
|
||||
|
||||
vec3 clampedcolor = clamp(HistoryColor, rectboxmin, rectboxmax);
|
||||
float lerpcontribution = (any(greaterThan(rectboxmin, HistoryColor)) || any(greaterThan(HistoryColor, rectboxmax))) ? tcontribute : 1.0;
|
||||
lerpcontribution = lerpcontribution - lerpcontribution * sqrt(alphamask);
|
||||
HistoryColor = mix(clampedcolor, HistoryColor, clamp(lerpcontribution, 0.0, 1.0));
|
||||
float basemin = min(basealpha, 0.1);
|
||||
basealpha = mix(basemin, basealpha, clamp(lerpcontribution, 0.0, 1.0));
|
||||
|
||||
float alphasum = max(EPSILON, basealpha + Upsampledcw.w);
|
||||
float alpha = clamp(Upsampledcw.w / alphasum + resetF + (offscreen ? 1.0 : 0.0), 0.0, 1.0);
|
||||
Upsampledcw.xyz = mix(HistoryColor, Upsampledcw.xyz, alpha);
|
||||
|
||||
imageStore(HistoryOutput, gid, vec4(Upsampledcw.xyz, Wfactor));
|
||||
|
||||
// YCoCg -> RGB
|
||||
float x_z = Upsampledcw.x - Upsampledcw.z;
|
||||
vec3 rgb = max(vec3(x_z + Upsampledcw.y, Upsampledcw.x + Upsampledcw.z, x_z - Upsampledcw.y), vec3(0.0));
|
||||
|
||||
// Exact inverse of Qualcomm's reversible max-RGB tonemap + exposure undo
|
||||
float compMax = min(max(rgb.x, max(rgb.y, rgb.z)), 0.9999);
|
||||
float inv_expo = 1.0 / getExposure();
|
||||
float scale = inv_expo / ((1.0 + 1.0 / 65504.0) - compMax);
|
||||
vec3 out_lin = clamp(rgb * scale, vec3(0.0), vec3(64000.0));
|
||||
imageStore(SceneColorOutput, gid, vec4(out_lin, 1.0));
|
||||
}
|
||||
Reference in new issue
Block a user