mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd89f66077 | ||
|
|
cdd48e0aaa | ||
|
|
88d44b0dc6 | ||
|
|
73fac3723f |
No files matched your search
@@ -307,6 +307,9 @@ jobs:
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -o "$D/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-glprobe"
|
||||
|
||||
- name: Build the LSE atomics emulator for ARMv8.0 CPUs
|
||||
run: bash tools/linuxfs/lse-emu/build.sh app/src/main/assets/linuxfs
|
||||
|
||||
- name: Check the preloads
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -325,9 +328,6 @@ 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 upscale; do
|
||||
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic; 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', 'upscale'].collectEntries { name ->
|
||||
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].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>droiddeck-upscale:<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>directaudio:<dir>hybris'
|
||||
}
|
||||
|
||||
packagingOptions {
|
||||
|
||||
@@ -41,7 +41,6 @@ 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,9 +175,6 @@ 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,17 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import java.io.File
|
||||
|
||||
object CpuFeatures {
|
||||
internal fun lacksAtomics(cpuInfo: String): Boolean {
|
||||
val cores = cpuInfo.lineSequence()
|
||||
.filter { it.substringBefore(':').trim() == "Features" }
|
||||
.map { it.substringAfter(':').trim().split(Regex("\\s+")) }
|
||||
.toList()
|
||||
return cores.isNotEmpty() && cores.any { "atomics" !in it }
|
||||
}
|
||||
|
||||
val lacksAtomics: Boolean by lazy {
|
||||
runCatching { lacksAtomics(File("/proc/cpuinfo").readText()) }.getOrDefault(false)
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
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", "showUpscale" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
|
||||
"showProton" 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,9 +287,6 @@ 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,13 +74,12 @@ 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", "showUpscale",
|
||||
"showPower", "showLatency", "showAvg", "showLow1", "showLow01", "showLow001",
|
||||
),
|
||||
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,7 +114,6 @@ 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 = ""
|
||||
@@ -284,8 +283,6 @@ 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 ?: "" }
|
||||
|
||||
@@ -781,7 +778,6 @@ 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
|
||||
}
|
||||
@@ -819,7 +815,6 @@ 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))
|
||||
}
|
||||
|
||||
@@ -288,12 +288,26 @@ object BwrapSpawner {
|
||||
}
|
||||
|
||||
private fun preload(session: List<Bind>, rootfs: String, env: MutableMap<String, String>): List<Bind> {
|
||||
val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
|
||||
?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: return emptyList()
|
||||
if (libs.isEmpty()) return emptyList()
|
||||
val configured = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
|
||||
?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: emptyList()
|
||||
val lseDisabled = env["LSE_EMU"] == "0"
|
||||
val libs = configured.filterNot { lseDisabled && it.endsWith("/liblse_emu.so") }
|
||||
val inherited = env["LD_PRELOAD"]?.split(Regex("[\\s:]+"))
|
||||
?.filter { it.isNotEmpty() && !(lseDisabled && it.substringAfterLast('/') == "liblse_emu.so") }
|
||||
?: emptyList()
|
||||
if (libs.isEmpty()) {
|
||||
if (lseDisabled) {
|
||||
if (inherited.isEmpty()) env.remove("LD_PRELOAD")
|
||||
else env["LD_PRELOAD"] = inherited.joinToString(":")
|
||||
}
|
||||
return emptyList()
|
||||
}
|
||||
val binds = ArrayList<Bind>()
|
||||
val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } }
|
||||
env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":")
|
||||
env["LD_PRELOAD"] = (paths + inherited).joinToString(":")
|
||||
if (libs.any { it.endsWith("/liblse_emu.so") }) {
|
||||
env.putIfAbsent("LSE_EMU", "1")
|
||||
}
|
||||
File(rootfs, NET_LINK).takeIf { it.isFile }?.let { binds.add(Bind(it.path, "/$NET_LINK")) }
|
||||
env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev ->
|
||||
binds.addAll(bindsFor(session, rootfs, dev, dev))
|
||||
|
||||
@@ -104,8 +104,11 @@ object NativeGuest {
|
||||
private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/"))
|
||||
|
||||
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
|
||||
fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> {
|
||||
val preload = preloadList(root)
|
||||
fun sessionEnvironment(
|
||||
root: File, binds: List<String>, program: String, hostname: String? = null, lseEmu: String? = null,
|
||||
): Map<String, String> {
|
||||
val preload = preloadList(root).filterNot { lseEmu == "0" && it.substringAfterLast('/') == "liblse_emu.so" }
|
||||
val lse = lseEmu ?: "1".takeIf { preload.any { it.substringAfterLast('/') == "liblse_emu.so" } }
|
||||
return linkedMapOf(
|
||||
"DDNATV_ROOT" to root.path,
|
||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||
@@ -113,6 +116,7 @@ object NativeGuest {
|
||||
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
||||
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
||||
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
||||
"LSE_EMU" to lse.orEmpty(),
|
||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||
).filterValues { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
@@ -343,7 +343,8 @@ object BottomDesktop {
|
||||
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
||||
}
|
||||
val environment = if (current.nativeUserland) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
|
||||
val lseEmu = current.guest.lastOrNull { it.startsWith("LSE_EMU=") }?.substringAfter('=')
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context), lseEmu)
|
||||
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
} else current.hostEnvironment
|
||||
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||
|
||||
@@ -98,13 +98,6 @@ 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)
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.CpuFeatures
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.BwrapSpawner
|
||||
import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
@@ -22,6 +23,10 @@ object SessionFiles {
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
||||
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
|
||||
internal const val LSE_EMU = "usr/local/lib/droiddeck-lse/liblse_emu.so"
|
||||
|
||||
internal fun lsePreload(lacksAtomics: Boolean, staged: Boolean, lseEmu: String? = null): String =
|
||||
if (lacksAtomics && staged && lseEmu != "0") "/$LSE_EMU\n" else ""
|
||||
private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json"
|
||||
private const val IME_DEFAULT_MODE = 420
|
||||
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
|
||||
@@ -102,10 +107,23 @@ object SessionFiles {
|
||||
}
|
||||
|
||||
private val STAGE_LOCK = Any()
|
||||
@Volatile private var activeSessionLseEmu: String? = null
|
||||
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) =
|
||||
stage(context, root, startsSession, lseEmu = null)
|
||||
|
||||
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
|
||||
fun stage(context: Context, root: File, startsSession: Boolean, lseEmu: String?) =
|
||||
synchronized(STAGE_LOCK) {
|
||||
val selection = if (startsSession) {
|
||||
activeSessionLseEmu = lseEmu
|
||||
lseEmu
|
||||
} else {
|
||||
lseEmu ?: activeSessionLseEmu
|
||||
}
|
||||
stageNow(context, root, startsSession, selection)
|
||||
}
|
||||
|
||||
private fun stageNow(context: Context, root: File, startsSession: Boolean, lseEmu: String?) {
|
||||
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
||||
GameEnvironmentStore.publish(context)
|
||||
@@ -259,11 +277,6 @@ 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" }
|
||||
@@ -286,7 +299,8 @@ 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 + upscaleLayer + fexPreloads).filter { (asset, _) ->
|
||||
LSE_EMU to LSE_EMU,
|
||||
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
@@ -348,7 +362,8 @@ object SessionFiles {
|
||||
stageImeFiles(context, root, ledger)
|
||||
ledger.save()
|
||||
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
|
||||
val preload = StringBuilder("/usr/local/lib/libddsession.so\n")
|
||||
val preload = StringBuilder(lsePreload(CpuFeatures.lacksAtomics, File(root, LSE_EMU).isFile, lseEmu))
|
||||
preload.append("/usr/local/lib/libddsession.so\n")
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||
}
|
||||
|
||||
@@ -566,6 +566,7 @@ class SessionService : Service() {
|
||||
.onFailure { Log.w(TAG, "agent environment skipped", it) }
|
||||
val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList())
|
||||
val customEnvironment = extraEnv()
|
||||
val lseEmu = (customEnvironment + agentEnvironment).lastOrNull { it.startsWith("LSE_EMU=") }?.substringAfter('=')
|
||||
try {
|
||||
if (systemVulkan) {
|
||||
SystemVulkanDriver.prepare(this)
|
||||
@@ -575,7 +576,7 @@ class SessionService : Service() {
|
||||
}
|
||||
pruneSystemVulkanRuntime()
|
||||
}
|
||||
SessionFiles.stage(this, root, startsSession = true)
|
||||
SessionFiles.stage(this, root, startsSession = true, lseEmu = lseEmu)
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "Could not prepare the session graphics runtime", error)
|
||||
failSession(gen, "GRAPHICS_RUNTIME_FAILED", getString(R.string.session_graphics_runtime_failed), -1)
|
||||
@@ -830,7 +831,7 @@ class SessionService : Service() {
|
||||
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
|
||||
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
|
||||
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this))
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this), lseEmu)
|
||||
.forEach { (k, v) -> env[k] = v }
|
||||
} else prootEnv
|
||||
|
||||
@@ -1137,8 +1138,6 @@ 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)) }
|
||||
|
||||
@@ -1,444 +0,0 @@
|
||||
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,7 +211,6 @@ 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,39 +1134,6 @@ 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) {
|
||||
@@ -1198,37 +1165,6 @@ 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)) {
|
||||
@@ -1245,36 +1181,6 @@ 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,7 +1113,6 @@ 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,
|
||||
@@ -1918,52 +1917,6 @@ 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,28 +541,6 @@
|
||||
<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>
|
||||
@@ -797,7 +775,6 @@
|
||||
<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,48 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import com.droiddeck.launcher.session.SessionFiles
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class CpuFeaturesTest {
|
||||
@Test fun anArmv80CpuLacksAtomics() {
|
||||
val cpuInfo = """
|
||||
processor : 0
|
||||
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid
|
||||
processor : 1
|
||||
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid
|
||||
""".trimIndent()
|
||||
assertTrue(CpuFeatures.lacksAtomics(cpuInfo))
|
||||
}
|
||||
|
||||
@Test fun oneCoreWithoutAtomicsIsEnough() {
|
||||
val cpuInfo = """
|
||||
processor : 0
|
||||
Features : fp asimd atomics
|
||||
processor : 4
|
||||
Features : fp asimd
|
||||
""".trimIndent()
|
||||
assertTrue(CpuFeatures.lacksAtomics(cpuInfo))
|
||||
}
|
||||
|
||||
@Test fun anArmv82CpuHasAtomics() {
|
||||
val cpuInfo = """
|
||||
processor : 0
|
||||
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
|
||||
""".trimIndent()
|
||||
assertFalse(CpuFeatures.lacksAtomics(cpuInfo))
|
||||
}
|
||||
|
||||
@Test fun noFeatureLinesMeansNoEmulation() {
|
||||
assertFalse(CpuFeatures.lacksAtomics("processor : 0\n"))
|
||||
assertFalse(CpuFeatures.lacksAtomics(""))
|
||||
}
|
||||
|
||||
@Test fun theEmulatorIsPreloadedFirstOnlyWhenNeededAndStaged() {
|
||||
assertEquals("/usr/local/lib/droiddeck-lse/liblse_emu.so\n", SessionFiles.lsePreload(lacksAtomics = true, staged = true))
|
||||
assertEquals("", SessionFiles.lsePreload(lacksAtomics = true, staged = false))
|
||||
assertEquals("", SessionFiles.lsePreload(lacksAtomics = false, staged = true))
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
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"))
|
||||
}
|
||||
}
|
||||
@@ -251,6 +251,52 @@ class BwrapSpawnerPlanTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun sandboxesSwitchOnTheLseEmulatorWhenItIsPreloaded() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
val emu = File(rootfs, "usr/local/lib/droiddeck-lse/liblse_emu.so").apply { parentFile?.mkdirs(); writeText("") }
|
||||
val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/droiddeck-lse/liblse_emu.so\n") }
|
||||
try {
|
||||
val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir)
|
||||
assertEquals("/run/droiddeck-preload/liblse_emu.so", plan.env["LD_PRELOAD"])
|
||||
assertEquals("1", plan.env["LSE_EMU"])
|
||||
assertFalse(plan.env.containsKey("LSE_EMU_PATCH"))
|
||||
val chosen = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp"))
|
||||
.apply { getJSONObject("env").put("LSE_EMU_PATCH", "0") }, dir)
|
||||
assertEquals("0", chosen.env["LSE_EMU_PATCH"])
|
||||
assertEquals("1", chosen.env["LSE_EMU"])
|
||||
for (inherited in listOf(
|
||||
"/run/droiddeck-preload/liblse_emu.so /custom.so",
|
||||
"/custom.so:/run/droiddeck-preload/liblse_emu.so",
|
||||
)) {
|
||||
val disabled = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp"))
|
||||
.apply {
|
||||
getJSONObject("env").put("LSE_EMU", "0")
|
||||
getJSONObject("env").put("LD_PRELOAD", inherited)
|
||||
}, dir)
|
||||
assertEquals("0", disabled.env["LSE_EMU"])
|
||||
assertEquals("/custom.so", disabled.env["LD_PRELOAD"])
|
||||
assertFalse(disabled.binds.any { it.guest == "/run/droiddeck-preload/liblse_emu.so" })
|
||||
}
|
||||
} finally {
|
||||
listOf(emu, preload).forEach { it.delete() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun sandboxesLeaveTheLseSwitchesAloneWithoutTheEmulator() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
val lib = File(rootfs, "usr/local/lib/libddsession.so").apply { parentFile?.mkdirs(); writeText("") }
|
||||
val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libddsession.so\n") }
|
||||
try {
|
||||
val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir)
|
||||
assertFalse(plan.env.containsKey("LSE_EMU"))
|
||||
assertFalse(plan.env.containsKey("LSE_EMU_PATCH"))
|
||||
} finally {
|
||||
listOf(lib, preload).forEach { it.delete() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun zypakLaunchesTheBrowserWithoutItsSandbox() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val app = File(runtime, "app").apply { File(this, "bin").mkdirs() }
|
||||
|
||||
@@ -94,6 +94,27 @@ class NativeGuestTest {
|
||||
assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun disablingLseKeepsItOutOfTheLoaderAndItsDescendants() {
|
||||
val root = rootWithLoader()
|
||||
val emulator = "/usr/lib/liblse_emu.so"
|
||||
val session = "/usr/lib/libddsession.so"
|
||||
listOf(emulator, session).forEach { File(root, it.removePrefix("/")).writeText("") }
|
||||
File(root, "etc/droiddeck").mkdirs()
|
||||
File(root, "etc/droiddeck/native-preload").writeText("$emulator\n$session\n")
|
||||
|
||||
val enabled = NativeGuest.sessionEnvironment(root, emptyList(), "/usr/bin/env")
|
||||
assertEquals("1", enabled["LSE_EMU"])
|
||||
assertEquals("$emulator:$session", enabled["DDNATV_PRELOAD"])
|
||||
assertTrue(enabled.getValue("LD_PRELOAD").startsWith(File(root, emulator.removePrefix("/")).path + ":"))
|
||||
|
||||
val disabled = NativeGuest.sessionEnvironment(root, emptyList(), "/usr/bin/env", lseEmu = "0")
|
||||
assertEquals("0", disabled["LSE_EMU"])
|
||||
assertEquals(session, disabled["DDNATV_PRELOAD"])
|
||||
assertEquals(listOf(File(root, session.removePrefix("/")).path, NativeGuest.hook(root).path),
|
||||
disabled.getValue("LD_PRELOAD").split(':'))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theProgramTheLoaderRunsIsNamedInItsEnvironment() {
|
||||
val root = rootWithLoader()
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
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")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
# Steam client on ARMv8.0 CPUs
|
||||
|
||||
## The crash
|
||||
|
||||
Valve's native arm64 Steam client stopped starting on ARMv8.0 CPUs after the April 15 2026
|
||||
build (client version 1776387948). The process dies with SIGILL right away, the session log
|
||||
shows `"$steam_root/steamrtarm64/steam" ... Illegal instruction` and `steam exited rc=132`,
|
||||
and the screen stays black.
|
||||
|
||||
The faulting instruction is an ARMv8.1 LSE atomic. The GDB trace in
|
||||
[ValveSoftware/steam-for-linux#13288](https://github.com/ValveSoftware/steam-for-linux/issues/13288)
|
||||
stops on `ldaddal x1, x0, [x0]`, with `swpa` and `casal` next to it. Earlier builds were most
|
||||
likely compiled with `-moutline-atomics`, which picks LL/SC or LSE at run time. Newer builds
|
||||
inline LSE. Valve has not replied on that issue, so the cause comes from the reporter's
|
||||
disassembly, not from Valve.
|
||||
|
||||
Affected cores are the ARMv8.0 ones without LSE: Cortex-A35, A53, A57, A72 and A73. A55, A75
|
||||
and later have it. On Android that covers the Snapdragon 4xx/6xx parts built on A53/A73 (for example the
|
||||
Snapdragon 685 with Adreno 610 in
|
||||
[Droid-Deck/DroidDeck#380](https://github.com/Droid-Deck/DroidDeck/issues/380)), plus the
|
||||
Nintendo Switch, Raspberry Pi 4 and older, and the Jetson Nano outside Android.
|
||||
`/proc/cpuinfo` shows it: the `Features` line has no `atomics`.
|
||||
|
||||
LSE is an ARMv8.1 feature. LSE-Emu users report the current client running on a Cortex-A57,
|
||||
so nothing later than LSE seems to be required yet.
|
||||
|
||||
## What other projects do
|
||||
|
||||
- [SildurFX/Switchdeck](https://github.com/SildurFX/Switchdeck) (Switch, L4T Linux) lets the
|
||||
client update once, then overlays `linuxarm64`, `steamrtarm64`, `steamui` and a `steam.cfg`
|
||||
from the April build. It works there because the install script controls the whole system.
|
||||
For us a pinned client is replaced by the self updater on its next start, which is why #380
|
||||
was closed.
|
||||
- [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) is a preload library by the same
|
||||
author, written to run the current arm64 client on the Switch. A SIGILL handler performs
|
||||
each LSE instruction with an LL/SC loop. With `LSE_EMU_PATCH=1` the first trap at a site
|
||||
writes an LL/SC stub within branch range and replaces the instruction with a `b` to it, so
|
||||
the site runs natively after that. It covers the full LSE set plus `LDAPR`. The author
|
||||
reports Steam, FEX, Proton games and ARMSX2 running on a Cortex-A57, with ARMSX2 close to
|
||||
native ARMv8.0 speed once patched. GPL-3.0, same as this repo.
|
||||
- [Azkali/proton-arm64-a57](https://github.com/Azkali/proton-arm64-a57) rebuilds Proton 11
|
||||
arm64 (Wine, DXVK, vkd3d-proton, FEX's WoW64 and ARM64EC DLLs) with
|
||||
`-march=armv8-a -mtune=cortex-a57`. Stock Proton 11 arm64 also SIGILLs on ARMv8.0
|
||||
(`wineboot` rc=132), so the client is not the only problem for games.
|
||||
- Some installers fall back to Valve's x86-64 client under FEX on CPUs without LSE. We already
|
||||
have that path (`DD_STEAM_CLIENT_ARCH=x86_64`, `droiddeck-steam-x64`), but it is slower and
|
||||
FEX itself has to be built without LSE.
|
||||
- [FrankNat996/armor](https://github.com/FrankNat996/armor) notes a separate problem: the arm64
|
||||
client's ELF segments are 4K aligned, so it SIGSEGVs at once on 16K page kernels.
|
||||
|
||||
## This change
|
||||
|
||||
The session vendors LSE-Emu (`tools/linuxfs/lse-emu`, upstream commit `8bc9548`). CI and
|
||||
`tools/build_local.sh` build it as `usr/local/lib/droiddeck-lse/liblse_emu.so` with
|
||||
`-march=armv8-a -mno-outline-atomics`. The build fails if the library contains LSE
|
||||
instructions itself.
|
||||
|
||||
When `/proc/cpuinfo` reports any core without `atomics`, `SessionFiles` puts the library first
|
||||
in the rootfs `/etc/ld.so.preload`. `BwrapSpawner` already turns that file into `LD_PRELOAD`
|
||||
for sandboxed processes. On CPUs with LSE nothing changes: the file is staged but not
|
||||
preloaded, and the library would also stay idle on its own because it checks `HWCAP_ATOMICS`.
|
||||
|
||||
`droiddeck-session` sees the library in `ld.so.preload` and exports `LSE_EMU=1`. Runtime
|
||||
instruction rewriting is disabled by default (`LSE_EMU_PATCH=0`): the emulator uses the slower
|
||||
SIGILL path rather than rewriting executable code while other threads may be running it. To
|
||||
opt in to patching for testing, set `LSE_EMU_PATCH=1` explicitly. With a session debug folder,
|
||||
the script also sets `LSE_EMU_LOG=$DD_DEBUG_DIR/lse_emu.log`, and `session.log` gets a line
|
||||
starting with `== cpu: no LSE atomics`.
|
||||
|
||||
The test APK targets SDK 34. To verify the expected `mprotect` restriction, run a controlled
|
||||
test executable containing a known-patchable, file-backed LSE instruction with
|
||||
`LSE_EMU_PATCH=1` under this APK configuration, and confirm `mprotect-failed` for that site.
|
||||
A normal Steam run alone cannot establish the restriction.
|
||||
|
||||
## Tests
|
||||
|
||||
`tools/tests/test_lse_emu.py` builds the library and a program that uses every LSE family
|
||||
(`ldadd` in all four sizes, `ldclr`, `ldeor`, `ldset`, `swp`, `ldsmax`, `ldumin`, `casal`,
|
||||
`caspal`) from four threads, and runs it under `qemu-aarch64 -cpu cortex-a57`:
|
||||
|
||||
- without the library the program dies with SIGILL
|
||||
- trapping alone runs every form and keeps the threaded counters exact
|
||||
- patching runs every form twice, so the second run goes through the generated stubs, both
|
||||
single threaded and with four threads
|
||||
- condition flags survive a patched `ldumax`/`ldsmaxb`, and `caspal` returns the current pair
|
||||
on a mismatch
|
||||
- without `LSE_EMU=1`, and on `-cpu neoverse-n1`, the library stays out of the way
|
||||
- a SIGILL handler the program installs itself still runs for an unrelated `udf`
|
||||
|
||||
The patch tests cannot run on an Apple Silicon Mac in an amd64 Docker container: qemu-aarch64
|
||||
there segfaults whenever code is written to an executable page after code on it has run, even
|
||||
in a ten line program without the library. CI runs them on x86 hardware.
|
||||
|
||||
## Fixes over upstream
|
||||
|
||||
The vendored copy carries two fixes found in review, both in the patched stubs and the
|
||||
emulation path:
|
||||
|
||||
- `LDSMAX`/`LDSMIN`/`LDUMAX`/`LDUMIN` stubs used `cmp`/`csel` and overwrote NZCV. They now
|
||||
save and restore it.
|
||||
- `CASP` with a 64-bit pair returned the `ldxp` result on a mismatch without a store. A 128-bit
|
||||
`ldxp` is only single-copy atomic once a `stxp` succeeds, so a concurrent update could give
|
||||
one old and one new half. Both the trap path and the stub now store the loaded pair back on a
|
||||
mismatch and retry if that store fails, as libatomic does.
|
||||
|
||||
Patching replaces an LSE instruction with a `b` while other threads may be running it.
|
||||
The architecture does not guarantee safe concurrent replacement for every instruction (including
|
||||
`LDADD`), so patching is opt-in and defaults to `LSE_EMU_PATCH=0`. This avoids that specific
|
||||
self-modifying-code race by keeping sites on the SIGILL emulation path, at the cost of speed.
|
||||
It does not eliminate all signal-handler compatibility risks: direct raw `rt_sigaction` syscalls,
|
||||
complex signal masks/flags, and applications that depend on exact kernel signal semantics still
|
||||
need dedicated tests. The handler forwarding is not a complete substitute for kernel delivery.
|
||||
|
||||
## Testing on a device
|
||||
|
||||
On an ARMv8.0 phone or handheld (no `atomics` in `/proc/cpuinfo`):
|
||||
|
||||
1. Install the test APK and start a Steam session.
|
||||
2. `session.log` should have `== cpu: no LSE atomics` and no `steam exited rc=132`.
|
||||
3. In the default-mode run, check that `lse_emu.log` contains a `start` record for the
|
||||
affected PID and that the process remains on the trap path. While Steam is running, its
|
||||
`exit` record may not exist yet: either confirm a `no-patch` record for that PID, or exit
|
||||
Steam normally before checking that its `exit` record has a nonzero `traps=` value. Confirm
|
||||
there are no `patched` records. Summarise events with
|
||||
`cut -d' ' -f2 lse_emu.log | sort | uniq -c`.
|
||||
Then repeat with `LSE_EMU_PATCH=1` explicitly set in the session environment. Do not require
|
||||
`mprotect-failed` for a valid trap-path run: `no-arena` means arena allocation failed before
|
||||
`mprotect` was attempted, so it is inconclusive about the SDK restriction. Check that
|
||||
restriction separately using the controlled patchable site described above. `unhandled`
|
||||
means an instruction the library does not cover.
|
||||
4. Compare UI responsiveness against an ARMv8.2 device, and note any `lse_emu: unhandled`
|
||||
lines in `session.log`.
|
||||
|
||||
## Still open
|
||||
|
||||
- Games. Proton 11 arm64 and Valve's FEX build need the same treatment. The preload reaches
|
||||
them when they inherit `LD_PRELOAD`, but pressure-vessel and static binaries can drop it,
|
||||
and FEX installs its own signal handlers with raw syscalls. An ARMv8.0 Proton build like
|
||||
Azkali's is the cleaner fix.
|
||||
- In #380 the session first died with SIGILL in the app's own `wl-compositor` thread, inside
|
||||
`turnip-sdk36/vulkan.ad08XX.so`, which is the A8xx driver build loaded on an Adreno 610.
|
||||
Picking the 6xx/7xx Turnip fixed it, and Auto picks that build once the driver release list
|
||||
is loaded. Nobody has checked yet whether our bundled driver builds avoid LSE. The preload
|
||||
cannot help there because the compositor is a bionic thread in the app process.
|
||||
- JIT code (anonymous memory) is never patched and always traps.
|
||||
- If Valve starts requiring something past LSE, the library prints
|
||||
`lse_emu: unhandled pc=... insn=...` and the client crashes as before.
|
||||
+2
-1
@@ -14,7 +14,8 @@ after restarting. If no complete copy exists, the pack uses the checkout's pin.
|
||||
- `tools/agent/dd-lab-build` builds the checkout with Gradle on the device (`processReleaseResources`
|
||||
and `mergeDexRelease`), packs the linked resources and dex files into `overlay.apk`, writes
|
||||
`overlay.json`, and stages both in the app's `files/lab/next`. It then recompiles the app without
|
||||
an app image and restarts DroidDeck.
|
||||
an app image and restarts DroidDeck. The resource linker uses IDs from the installed APK so
|
||||
base and overlay code resolve the same resource names.
|
||||
- Run by the app's own agent (`DD_AGENT` set), it writes `files/agent/lab-request` instead, and the
|
||||
app runs the build in a process of its own, logging to `~/.cache/dd-lab-build.log`; the agent's
|
||||
copy follows that log and exits with the build. A turn's processes end with the turn, so a build
|
||||
|
||||
@@ -7,221 +7,6 @@ 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
|
||||
@@ -1659,11 +1444,6 @@ 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.
|
||||
|
||||
@@ -134,6 +134,54 @@ fi
|
||||
gradle=(./gradlew :app:processReleaseResources :app:mergeDexRelease --max-workers=2 -PskipRust=true -x buildVkBridgeServer
|
||||
-Pandroid.aapt2FromMavenOverride=$HOME/aapt2/aapt2 -Pkotlin.compiler.execution.strategy=daemon
|
||||
-Pkotlin.daemon.jvmargs=-Xmx${kotlin_heap}m -Dorg.gradle.jvmargs=-Xmx${gradle_heap}m --console=plain)
|
||||
# Release package aliases rewrite the manifest but keep the resource table under the linker package.
|
||||
resource_package=com.droiddeck.launcher
|
||||
resource_cache=$cache/dd-lab-resource-ids
|
||||
mkdir -p "$resource_cache"
|
||||
resource_key=$(printf '%s\n' "$pkg" "$base" "$apk" | sha256sum | cut -d ' ' -f1)
|
||||
stable_ids=$resource_cache/$resource_key.txt
|
||||
if [ ! -s "$stable_ids" ]; then
|
||||
progress checking 0 "reading the installed APK resource IDs"
|
||||
if ! (
|
||||
resource_work=$(mktemp -d "$resource_cache/.extract.XXXXXX") || exit 1
|
||||
trap 'rm -rf "$resource_work"' EXIT
|
||||
adb -s "$serial" pull "$apk" "$resource_work/base.apk" >/dev/null &&
|
||||
"$HOME/aapt2/aapt2" dump resources "$resource_work/base.apk" > "$resource_work/resources.txt" &&
|
||||
awk -v package="$resource_package" '
|
||||
$1 == "Package" { in_package = ($2 == "name=" package) }
|
||||
in_package && $1 == "resource" && $2 ~ /^0x[[:xdigit:]]+$/ {
|
||||
print package ":" $3 " = " $2
|
||||
count++
|
||||
}
|
||||
END { if (!count) exit 1 }
|
||||
' "$resource_work/resources.txt" > "$resource_work/ids.txt" &&
|
||||
mv "$resource_work/ids.txt" "$stable_ids"
|
||||
); then
|
||||
fail "could not read resource IDs from the installed APK"
|
||||
fi
|
||||
fi
|
||||
|
||||
resource_init=$resource_cache/link.gradle
|
||||
cat > "$resource_init.part.$$" <<'EOF'
|
||||
gradle.beforeProject { project ->
|
||||
if (project.path == ':app') {
|
||||
project.pluginManager.withPlugin('com.android.application') {
|
||||
project.androidComponents.finalizeDsl { android ->
|
||||
android.androidResources.additionalParameters.addAll([
|
||||
'--stable-ids', project.providers.gradleProperty('droiddeckLabStableIds').get()
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
if cmp -s "$resource_init.part.$$" "$resource_init"; then
|
||||
rm "$resource_init.part.$$"
|
||||
else
|
||||
mv "$resource_init.part.$$" "$resource_init"
|
||||
fi
|
||||
gradle+=(--init-script "$resource_init" "-PdroiddeckLabStableIds=$stable_ids")
|
||||
|
||||
progress planning
|
||||
plan_file=$cache/dd-lab-build-plan
|
||||
plan_key=$(
|
||||
|
||||
@@ -51,7 +51,6 @@ 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) ;;
|
||||
@@ -93,10 +92,7 @@ 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")
|
||||
# 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 VK_ADD_IMPLICIT_LAYER_PATH=$PACK/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,21 +103,6 @@ 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?}"; }
|
||||
|
||||
@@ -225,6 +225,7 @@ else
|
||||
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe"
|
||||
bash tools/linuxfs/lse-emu/build.sh "$d"
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
"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",
|
||||
@@ -30,9 +29,7 @@
|
||||
"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-upscale-layer/libVkLayer_droiddeck_upscale.so",
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/VK_LAYER_DROIDDECK_upscale.json"
|
||||
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so"
|
||||
],
|
||||
"ndk": true,
|
||||
"packages": [
|
||||
@@ -276,41 +273,5 @@
|
||||
"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,8 +6,6 @@ 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
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
bash tools/upscale/bridges/build.sh app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale/bridges
|
||||
@@ -23,8 +23,8 @@ import prepare # noqa: E402
|
||||
# CI records identities under its runner labels and pinned NDK, not this host's.
|
||||
RUNNER_ARCHITECTURES = ('X64', 'ARM64')
|
||||
# The components job builds these outside the recipe registry.
|
||||
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/venus/glprobe.c',
|
||||
'tools/quest']
|
||||
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/linuxfs/lse-emu',
|
||||
'tools/venus/glprobe.c', 'tools/quest']
|
||||
|
||||
|
||||
def ci_environment(architecture, root):
|
||||
|
||||
@@ -31,5 +31,9 @@ for sym in vkNegotiateLoaderLayerInterfaceVersion vkGetInstanceProcAddr vkGetDev
|
||||
grep -qx "$sym" <<<"$XCLIPSE" || { echo "::error::the Xclipse layer does not export $sym"; exit 1; }
|
||||
done
|
||||
test -f "$D/usr/local/lib/droiddeck-xclipse/VkLayer_droiddeck_xclipse.json"
|
||||
LSE=$(syms "$D/usr/local/lib/droiddeck-lse/liblse_emu.so")
|
||||
for sym in sigaction signal sigprocmask pthread_sigmask prctl syscall; do
|
||||
grep -qx "$sym" <<<"$LSE" || { echo "::error::liblse_emu.so does not export $sym"; exit 1; }
|
||||
done
|
||||
test -f "$D/usr/local/bin/droiddeck-session"
|
||||
test -f "$D/usr/local/bin/droiddeck-proton-extra"
|
||||
@@ -0,0 +1,23 @@
|
||||
# LSE-Emu
|
||||
|
||||
`lse_emu.c` is a copy of [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) at commit
|
||||
`8bc9548ac6fd24a8d506b266b17ba8d0e71a9b01` (GPL-3.0-or-later) with two fixes, listed in
|
||||
`docs/arm-v8.0-steam-client.md` under "Fixes over upstream": NZCV kept across the min/max
|
||||
stubs, and a store-back on `CASP` mismatches so the returned pair is atomic. Carry them forward
|
||||
until upstream has them.
|
||||
|
||||
It is an `LD_PRELOAD` library that emulates the ARMv8.1 LSE atomic instructions (and `LDAPR`)
|
||||
on ARMv8.0 CPUs. A SIGILL handler performs each trapped instruction with an LL/SC loop. A GNU
|
||||
IFUNC resolver installs a minimal early handler on CPUs without LSE before dependency
|
||||
constructors, covering LSE instructions executed before the preload constructor. The early handler
|
||||
is removed after initialization unless `LSE_EMU=1` is set. With `LSE_EMU_PATCH=1` the first trap at a site
|
||||
writes an LL/SC stub nearby and replaces the instruction with a branch to it, so later runs do not trap.
|
||||
Patching is off by default. It is restricted to private file-backed executable mappings whose
|
||||
live file and offset still match the original mapping. Leave patching off for programs that
|
||||
can remap executable pages concurrently: checking the mapping cannot lock it against a remap.
|
||||
|
||||
The session stages it as `/usr/local/lib/droiddeck-lse/liblse_emu.so` and only lists it in
|
||||
`/etc/ld.so.preload` when `/proc/cpuinfo` has no `atomics` flag. See
|
||||
`docs/arm-v8.0-steam-client.md` for why.
|
||||
|
||||
To update, copy `lse_emu.c` from a newer upstream commit and change the commit above.
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
D=${1:?asset directory}
|
||||
CC=${CC:-aarch64-linux-gnu-gcc}
|
||||
STRIP=${STRIP:-aarch64-linux-gnu-strip}
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
out="$D/usr/local/lib/droiddeck-lse/liblse_emu.so"
|
||||
mkdir -p "$(dirname "$out")"
|
||||
"$CC" -shared -fPIC -O2 -march=armv8-a -mno-outline-atomics -Wall -Wextra -Wno-unused-parameter \
|
||||
-Wl,-z,now,-z,max-page-size=65536 -o "$out" "$here/lse_emu.c" -ldl
|
||||
"$STRIP" --strip-unneeded "$out"
|
||||
disassembly=$("${OBJDUMP:-aarch64-linux-gnu-objdump}" -d "$out")
|
||||
if grep -qE $'\t((ld|st)(add|clr|eor|set|smax|smin|umax|umin)|swp|cas)[a-z]*\t' <<<"$disassembly"; then
|
||||
echo "::error::liblse_emu.so itself contains LSE instructions"; exit 1
|
||||
fi
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1152,228 +1152,6 @@ 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"
|
||||
@@ -2065,9 +1843,6 @@ 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:
|
||||
|
||||
Executable → Regular
+7
@@ -11,6 +11,12 @@ if [ "${DD_RAISE_NOFILE:-0}" = 1 ] && [ -z "${DD_INSIDE:-}" ]; then
|
||||
unset dd_nofile_was
|
||||
fi
|
||||
export HOME=${HOME:-/root}
|
||||
if grep -qs '/liblse_emu\.so$' /etc/ld.so.preload; then
|
||||
if [ "${LSE_EMU+x}" != x ]; then export LSE_EMU=1; fi
|
||||
# Runtime instruction rewriting is opt-in; the SIGILL emulation path remains available.
|
||||
export LSE_EMU_PATCH=${LSE_EMU_PATCH:-0}
|
||||
[ -n "${DD_DEBUG_DIR:-}" ] && export LSE_EMU_LOG=${LSE_EMU_LOG:-$DD_DEBUG_DIR/lse_emu.log}
|
||||
fi
|
||||
mode=${1:-desktop}
|
||||
shift || true
|
||||
|
||||
@@ -100,6 +106,7 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then
|
||||
echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
|
||||
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
||||
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
|
||||
[ "${LSE_EMU:-}" = 1 ] && echo "== cpu: no LSE atomics (ARMv8.0); liblse_emu.so emulates them (log: ${LSE_EMU_LOG:-off})"
|
||||
fi
|
||||
|
||||
start_diagnostic_inventory() {
|
||||
|
||||
@@ -56,27 +56,38 @@ static unsigned hash_of(const char *s, int kind, int mode, int flags) {
|
||||
return h;
|
||||
}
|
||||
|
||||
static struct entry *slot(unsigned h) {
|
||||
return &table[(h ^ (h >> 16)) % PATH_CACHE_SLOTS];
|
||||
}
|
||||
|
||||
static int cacheable(const char *path) {
|
||||
return path != NULL && path[0] == '/' && strlen(path) < PATH_CACHE_KEY_MAX && enabled();
|
||||
}
|
||||
|
||||
static struct entry *find(const char *path, int kind, int mode, int flags, unsigned h) {
|
||||
struct entry *e = slot(h);
|
||||
long long now = now_ns();
|
||||
|
||||
if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) return NULL;
|
||||
if (now_ns() - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) return NULL;
|
||||
return e;
|
||||
for (int i = 0; i < PATH_CACHE_SLOTS; i++) {
|
||||
struct entry *e = &table[i];
|
||||
if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) continue;
|
||||
if (now - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) continue;
|
||||
return e;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) {
|
||||
struct entry *e = slot(h);
|
||||
struct entry *e = find(path, kind, mode, flags, h);
|
||||
long long now = now_ns();
|
||||
char *copy = value != NULL ? strdup(value) : NULL;
|
||||
|
||||
if (value != NULL && copy == NULL) return;
|
||||
if (e == NULL) {
|
||||
e = &table[0];
|
||||
for (int i = 0; i < PATH_CACHE_SLOTS; i++) {
|
||||
if (table[i].stamp == 0 || now - table[i].stamp > PATH_CACHE_TTL_NS) {
|
||||
e = &table[i];
|
||||
break;
|
||||
}
|
||||
if (table[i].stamp < e->stamp) e = &table[i];
|
||||
}
|
||||
}
|
||||
free(e->value);
|
||||
e->value = copy;
|
||||
e->hash = h;
|
||||
@@ -84,7 +95,7 @@ static void store(const char *path, int kind, int mode, int flags, unsigned h, c
|
||||
e->mode = mode;
|
||||
e->flags = flags;
|
||||
memcpy(e->key, path, strlen(path) + 1);
|
||||
e->stamp = now_ns();
|
||||
e->stamp = now;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
|
||||
@@ -542,7 +542,35 @@ static int zr_start(void) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec")));
|
||||
static pthread_key_t zr_key;
|
||||
static int zr_key_ready;
|
||||
static pthread_mutex_t zr_key_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static unsigned char zr_idle;
|
||||
|
||||
static void zr_key_make(void) {
|
||||
if (__atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE)) return;
|
||||
pthread_mutex_lock(&zr_key_lock);
|
||||
if (!__atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE)) {
|
||||
pthread_key_t key;
|
||||
if (pthread_key_create(&key, NULL) == 0) {
|
||||
if (pthread_getspecific(key) == NULL) {
|
||||
zr_key = key;
|
||||
__atomic_store_n(&zr_key_ready, 1, __ATOMIC_RELEASE);
|
||||
} else {
|
||||
pthread_key_delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&zr_key_lock);
|
||||
}
|
||||
|
||||
static void zr_key_child(void) {
|
||||
pthread_mutex_init(&zr_key_lock, NULL);
|
||||
}
|
||||
|
||||
static volatile unsigned char *zr_selector(void) {
|
||||
return __atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE) ? (volatile unsigned char *)pthread_getspecific(zr_key) : NULL;
|
||||
}
|
||||
|
||||
int prctl(int option, ...) {
|
||||
va_list ap;
|
||||
@@ -552,16 +580,32 @@ int prctl(int option, ...) {
|
||||
unsigned long arg4 = va_arg(ap, unsigned long);
|
||||
unsigned long arg5 = va_arg(ap, unsigned long);
|
||||
va_end(ap);
|
||||
volatile unsigned char *dispatch = zr_dispatch;
|
||||
int arming = option == PR_SET_SYSCALL_USER_DISPATCH && arg2;
|
||||
if (arming) {
|
||||
zr_key_make();
|
||||
if (!__atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE)) {
|
||||
errno = EAGAIN;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
volatile unsigned char *dispatch = zr_selector();
|
||||
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
||||
if (selector) *dispatch = 0;
|
||||
if (arming && pthread_setspecific(zr_key, dispatch != NULL ? (void *)dispatch : (void *)&zr_idle) != 0) {
|
||||
if (selector) *dispatch = selector;
|
||||
errno = ENOMEM;
|
||||
return -1;
|
||||
}
|
||||
long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5);
|
||||
int failed = (unsigned long)result > -4096UL;
|
||||
if (arming) pthread_setspecific(zr_key, failed ? (void *)dispatch : (void *)arg5);
|
||||
if (selector) *dispatch = selector;
|
||||
if ((unsigned long)result > -4096UL) {
|
||||
int ready = __atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE);
|
||||
if (failed) {
|
||||
errno = (int)-result;
|
||||
return -1;
|
||||
}
|
||||
if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL;
|
||||
if (option == PR_SET_SYSCALL_USER_DISPATCH && !arg2 && ready) pthread_setspecific(zr_key, NULL);
|
||||
return (int)result;
|
||||
}
|
||||
|
||||
@@ -569,7 +613,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)context;
|
||||
if (info == NULL || info->si_code != SI_USER) return;
|
||||
volatile unsigned char *dispatch = zr_dispatch;
|
||||
volatile unsigned char *dispatch = zr_selector();
|
||||
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
||||
if (selector) *dispatch = 0;
|
||||
int saved = errno;
|
||||
@@ -598,6 +642,7 @@ static void zr_paths(void) {
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void zr_init(void) {
|
||||
pthread_atfork(NULL, NULL, zr_key_child);
|
||||
zr_paths();
|
||||
int fd = zr_open(zr_ctl);
|
||||
if (fd < 0) return;
|
||||
|
||||
+136
-16
@@ -41,9 +41,73 @@ static char **clean_env_for_system(char *const envp[]) {
|
||||
return new_env;
|
||||
}
|
||||
|
||||
static int preload_has_entry(const char *chain, const char *entry, size_t entry_len) {
|
||||
if (!chain || !entry_len) return 0;
|
||||
const char *p = chain;
|
||||
while (*p) {
|
||||
size_t len = strcspn(p, ": ");
|
||||
if (len == entry_len && memcmp(p, entry, len) == 0) return 1;
|
||||
p += len;
|
||||
if (*p) p++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static char *merge_preload_env(const char *host, const char *mapped) {
|
||||
size_t host_len = host ? strlen(host) : 0;
|
||||
char *out = malloc(11 + host_len + 1 + strlen(mapped) + 1);
|
||||
if (!out) return NULL;
|
||||
memcpy(out, "LD_PRELOAD=", 11);
|
||||
size_t used = 11;
|
||||
if (host_len) {
|
||||
memcpy(out + used, host, host_len);
|
||||
used += host_len;
|
||||
}
|
||||
for (const char *p = mapped; *p; ) {
|
||||
size_t n = strcspn(p, ": ");
|
||||
if (n && !preload_has_entry(host, p, n)) {
|
||||
if (used > 11) out[used++] = ':';
|
||||
memcpy(out + used, p, n);
|
||||
used += n;
|
||||
}
|
||||
p += n;
|
||||
if (*p) p++;
|
||||
}
|
||||
out[used] = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
// Filter the LSE emulator from colon/space-separated preload chains when explicitly disabled.
|
||||
static char *filter_lse_emu_preloads(const char *value, int lse_emu_disabled) {
|
||||
if (!value) return NULL;
|
||||
size_t len = strlen(value);
|
||||
char *out = malloc(len + 1);
|
||||
if (!out) return NULL;
|
||||
size_t used = 0;
|
||||
const char *p = value;
|
||||
while (*p) {
|
||||
size_t n = strcspn(p, ": ");
|
||||
if (n) {
|
||||
const char *base = p + n;
|
||||
while (base > p && base[-1] != '/' && base[-1] != ':' && base[-1] != ' ') base--;
|
||||
int is_lse_emu = n - (size_t)(base - p) == strlen("liblse_emu.so") &&
|
||||
memcmp(base, "liblse_emu.so", strlen("liblse_emu.so")) == 0;
|
||||
if (!(lse_emu_disabled && is_lse_emu)) {
|
||||
if (used) out[used++] = ':';
|
||||
memcpy(out + used, p, n);
|
||||
used += n;
|
||||
}
|
||||
}
|
||||
p += n;
|
||||
if (*p) p++;
|
||||
}
|
||||
out[used] = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
// LD_PRELOAD with every absolute path that is not in the rootfs yet mapped into it. Entries are
|
||||
// separated by ':' or ' '. free() the result.
|
||||
static char *map_preload_paths(const char *value) {
|
||||
static char *map_preload_paths(const char *value, int lse_emu_disabled) {
|
||||
if (!value) return NULL;
|
||||
size_t cap = strlen(value) + (g_ddnatv_root_len + 1) * 16 + 16;
|
||||
char *out = malloc(cap);
|
||||
@@ -57,6 +121,13 @@ static char *map_preload_paths(const char *value) {
|
||||
char entry[PATH_MAX];
|
||||
memcpy(entry, p, len);
|
||||
entry[len] = '\0';
|
||||
const char *base = strrchr(entry, '/');
|
||||
base = base ? base + 1 : entry;
|
||||
if (lse_emu_disabled && strcmp(base, "liblse_emu.so") == 0) {
|
||||
p += len;
|
||||
if (*p) p++;
|
||||
continue;
|
||||
}
|
||||
char buf[PATH_MAX];
|
||||
const char *mapped = entry[0] == '/' ? rewrite_path_in_root(entry, buf, sizeof(buf)) : entry;
|
||||
size_t mlen = strlen(mapped);
|
||||
@@ -72,10 +143,13 @@ static char *map_preload_paths(const char *value) {
|
||||
return out;
|
||||
}
|
||||
|
||||
static void free_modified_env(char **modified_env, char *const orig_env[]);
|
||||
|
||||
static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) {
|
||||
init_ddnatv_hook();
|
||||
int count = 0;
|
||||
int has_preload = 0;
|
||||
int lse_emu_disabled = 0;
|
||||
int has_root = 0;
|
||||
int has_tunables = 0;
|
||||
int has_path = 0;
|
||||
@@ -105,6 +179,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
||||
switch (e[0]) {
|
||||
case 'L':
|
||||
if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; }
|
||||
else if (strncmp(e, "LSE_EMU=0", 9) == 0 && e[9] == '\0') lse_emu_disabled = 1;
|
||||
break;
|
||||
case 'G':
|
||||
if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1;
|
||||
@@ -140,6 +215,12 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
||||
count++;
|
||||
}
|
||||
|
||||
char *filtered_host_chain = lse_emu_disabled ? filter_lse_emu_preloads(g_preload_host, 1) : NULL;
|
||||
if (lse_emu_disabled && g_preload_host && !filtered_host_chain) {
|
||||
errno = ENOMEM;
|
||||
return NULL;
|
||||
}
|
||||
const char *host_preload = lse_emu_disabled ? (filtered_host_chain ? filtered_host_chain : "") : g_preload_host;
|
||||
char **new_env = calloc(count + 26, sizeof(char *));
|
||||
int dst = 0;
|
||||
// The user the program runs as (hardlinks.c): this process's, whatever the environment it passes
|
||||
@@ -157,23 +238,45 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
||||
if (envp[i][0] == 'D' && (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)) {
|
||||
continue;
|
||||
}
|
||||
if (lse_emu_disabled && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_PRELOAD=", 15) == 0) {
|
||||
char *filtered = filter_lse_emu_preloads(envp[i] + 15, 1);
|
||||
if (!filtered) {
|
||||
free_modified_env(new_env, envp);
|
||||
free(filtered_host_chain);
|
||||
errno = ENOMEM;
|
||||
return NULL;
|
||||
}
|
||||
size_t len = 15 + strlen(filtered) + 1;
|
||||
char *str = malloc(len);
|
||||
if (!str) {
|
||||
free(filtered);
|
||||
free_modified_env(new_env, envp);
|
||||
free(filtered_host_chain);
|
||||
errno = ENOMEM;
|
||||
return NULL;
|
||||
}
|
||||
snprintf(str, len, "DDNATV_PRELOAD=%s", filtered);
|
||||
new_env[dst++] = str;
|
||||
free(filtered);
|
||||
continue;
|
||||
}
|
||||
if (has_preload && envp[i][0] == 'L' && strncmp(envp[i], "LD_PRELOAD=", 11) == 0) {
|
||||
// ld.so opens these itself: the guest's paths are mapped to the rootfs, and the libraries every
|
||||
// program loads (DDNATV_PRELOAD) come first
|
||||
char *mapped = map_preload_paths(preload_value);
|
||||
char *mapped = map_preload_paths(preload_value, lse_emu_disabled);
|
||||
if (mapped) {
|
||||
size_t chain = g_preload_host ? strlen(g_preload_host) : 0;
|
||||
int has_chain = chain > 0 && strstr(mapped, g_preload_host) != NULL;
|
||||
size_t len = 11 + chain + 1 + strlen(mapped) + 1;
|
||||
char *str = malloc(len);
|
||||
char *str = merge_preload_env(host_preload, mapped);
|
||||
free(mapped);
|
||||
if (str) {
|
||||
if (chain > 0 && !has_chain) snprintf(str, len, "LD_PRELOAD=%s:%s", g_preload_host, mapped);
|
||||
else snprintf(str, len, "LD_PRELOAD=%s", mapped);
|
||||
new_env[dst++] = str;
|
||||
free(mapped);
|
||||
continue;
|
||||
}
|
||||
free(mapped);
|
||||
}
|
||||
if (lse_emu_disabled) {
|
||||
free_modified_env(new_env, envp);
|
||||
free(filtered_host_chain);
|
||||
errno = ENOMEM;
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
// If we have an explicit real executable, drop the inherited entry to replace with the fresh target
|
||||
@@ -211,13 +314,13 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
||||
const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL;
|
||||
if (hook) {
|
||||
size_t hook_len = strlen(hook);
|
||||
size_t host_len = g_preload_host ? strlen(g_preload_host) + 1 : 0;
|
||||
size_t host_len = host_preload ? strlen(host_preload) + 1 : 0;
|
||||
size_t size = 11 + host_len + hook_len + 1;
|
||||
char *str = malloc(size);
|
||||
if (str) {
|
||||
size_t n = ddnatv_append(str, size, 0, "LD_PRELOAD=", 11);
|
||||
if (host_len) {
|
||||
n = ddnatv_append(str, size, n, g_preload_host, host_len - 1);
|
||||
n = ddnatv_append(str, size, n, host_preload, host_len - 1);
|
||||
n = ddnatv_append(str, size, n, ":", 1);
|
||||
}
|
||||
ddnatv_append(str, size, n, hook, hook_len);
|
||||
@@ -225,13 +328,29 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
||||
}
|
||||
}
|
||||
if (!has_preload_list && g_preload_guest) {
|
||||
size_t len = strlen(g_preload_guest);
|
||||
char *str = malloc(15 + len + 1);
|
||||
if (str) {
|
||||
char *filtered = lse_emu_disabled ? filter_lse_emu_preloads(g_preload_guest, 1) : NULL;
|
||||
if (lse_emu_disabled && !filtered) {
|
||||
free_modified_env(new_env, envp);
|
||||
free(filtered_host_chain);
|
||||
errno = ENOMEM;
|
||||
return NULL;
|
||||
}
|
||||
const char *guest_preload = lse_emu_disabled ? filtered : g_preload_guest;
|
||||
if (guest_preload) {
|
||||
size_t len = strlen(guest_preload);
|
||||
char *str = malloc(15 + len + 1);
|
||||
if (!str) {
|
||||
free(filtered);
|
||||
free_modified_env(new_env, envp);
|
||||
free(filtered_host_chain);
|
||||
errno = ENOMEM;
|
||||
return NULL;
|
||||
}
|
||||
memcpy(str, "DDNATV_PRELOAD=", 15);
|
||||
memcpy(str + 15, g_preload_guest, len + 1);
|
||||
memcpy(str + 15, guest_preload, len + 1);
|
||||
new_env[dst++] = str;
|
||||
}
|
||||
free(filtered);
|
||||
}
|
||||
if (!has_root && g_ddnatv_root[0] != '\0') {
|
||||
char *str = malloc(PATH_MAX + 16);
|
||||
@@ -319,6 +438,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
||||
new_env[dst++] = strdup("DEBCONF_NONINTERACTIVE_SEEN=true");
|
||||
}
|
||||
new_env[dst] = NULL;
|
||||
free(filtered_host_chain);
|
||||
return new_env;
|
||||
}
|
||||
|
||||
|
||||
@@ -483,6 +483,11 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
||||
return -1;
|
||||
}
|
||||
char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path);
|
||||
if (!new_env) {
|
||||
free(new_argv);
|
||||
errno = ENOMEM;
|
||||
return -1;
|
||||
}
|
||||
int ret = run_execve(orig_execve, ld_so, new_argv, new_env);
|
||||
if (errno == EACCES && chmod(ld_so, 0755) == 0) {
|
||||
// ld.so without its exec bit (an unusual restore): fix it once and retry
|
||||
@@ -507,6 +512,11 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
||||
if (new_argv) {
|
||||
prepare_static_program(static_elf); // ld.so is a static program itself
|
||||
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
|
||||
if (!ddnatv_env) {
|
||||
free(new_argv);
|
||||
errno = ENOMEM;
|
||||
return -1;
|
||||
}
|
||||
int ret = run_execve(orig_execve, target, new_argv, ddnatv_env);
|
||||
int saved_errno = errno;
|
||||
free_modified_env(ddnatv_env, envp);
|
||||
@@ -559,6 +569,10 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
||||
|
||||
if (static_elf) prepare_static_program(static_elf);
|
||||
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
|
||||
if (!ddnatv_env) {
|
||||
errno = ENOMEM;
|
||||
return -1;
|
||||
}
|
||||
int ret = run_execve(orig_execve, target, argv, ddnatv_env);
|
||||
int saved_errno = errno;
|
||||
free_modified_env(ddnatv_env, envp);
|
||||
@@ -1021,6 +1035,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
|
||||
build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path));
|
||||
char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL)
|
||||
: clean_env_for_system(orig_ep);
|
||||
if (in_root && !new_envp) return ENOMEM;
|
||||
|
||||
int ret = -1;
|
||||
if (via_ld_so) {
|
||||
|
||||
@@ -98,11 +98,6 @@ 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,19 +16,17 @@ 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',
|
||||
'upscale']
|
||||
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic']
|
||||
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/upscale', '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/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',
|
||||
@@ -112,6 +110,7 @@ def required():
|
||||
['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']]
|
||||
paths += ['assets/linuxfs/usr/local/lib/droiddeck-xclipse/' + name for name in
|
||||
['libVkLayer_droiddeck_xclipse.so', 'VkLayer_droiddeck_xclipse.json']]
|
||||
paths += ['assets/linuxfs/usr/local/lib/droiddeck-lse/liblse_emu.so']
|
||||
paths += ['assets/linuxfs/usr/local/lib/droiddeck-vr/' + name for name in
|
||||
['droiddeck/bin/linuxarm64/driver_droiddeck.so', 'droiddeck/bin/linuxarm64/xr-display-mode',
|
||||
'droiddeck/driver.vrdrivermanifest',
|
||||
@@ -259,7 +258,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', 'upscale') or (root / PACKS / (name + '.tar.zst')).is_file()}
|
||||
if name not in ('ubisoft', 'rockstar', 'dirt', 'epic') 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)
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#include <stdint.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static volatile uint64_t value;
|
||||
|
||||
__attribute__((constructor))
|
||||
static void use_lse_before_preload_init(void) {
|
||||
uint64_t old;
|
||||
uint64_t increment = 1;
|
||||
__asm__ volatile("ldaddal %x1, %x0, [%2]"
|
||||
: "=r"(old)
|
||||
: "r"(increment), "r"(&value)
|
||||
: "memory");
|
||||
if (old != 0 || value != 1) _exit(91);
|
||||
}
|
||||
|
||||
void lse_emu_early_dependency_anchor(void) {}
|
||||
@@ -0,0 +1,9 @@
|
||||
#include <stdio.h>
|
||||
|
||||
void lse_emu_early_dependency_anchor(void);
|
||||
|
||||
int main(void) {
|
||||
lse_emu_early_dependency_anchor();
|
||||
puts("early lse ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <errno.h>
|
||||
#include <sched.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ucontext.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define MAX_THREADS 8
|
||||
#define ROUNDS 20000
|
||||
|
||||
static uint64_t counter64;
|
||||
static uint32_t counter32;
|
||||
static uint16_t counter16;
|
||||
static uint8_t counter8;
|
||||
static uint64_t spin;
|
||||
|
||||
static void check(int ok, const char *what) {
|
||||
if (!ok) {
|
||||
printf("FAIL %s\n", what);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
static uint64_t ldaddal64(uint64_t *p, uint64_t v) {
|
||||
uint64_t old;
|
||||
__asm__ volatile("ldaddal %x1, %x0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
|
||||
return old;
|
||||
}
|
||||
|
||||
static uint32_t ldadd32(uint32_t *p, uint32_t v) {
|
||||
uint32_t old;
|
||||
__asm__ volatile("ldadd %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
|
||||
return old;
|
||||
}
|
||||
|
||||
static uint16_t ldaddlh(uint16_t *p, uint16_t v) {
|
||||
uint16_t old;
|
||||
__asm__ volatile("ldaddlh %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
|
||||
return old;
|
||||
}
|
||||
|
||||
static uint8_t ldaddab(uint8_t *p, uint8_t v) {
|
||||
uint8_t old;
|
||||
__asm__ volatile("ldaddab %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
|
||||
return old;
|
||||
}
|
||||
|
||||
static uint64_t casal64(uint64_t *p, uint64_t expected, uint64_t desired) {
|
||||
__asm__ volatile("casal %x0, %x2, [%1]" : "+r"(expected) : "r"(p), "r"(desired) : "memory");
|
||||
return expected;
|
||||
}
|
||||
|
||||
static void *worker(void *arg) {
|
||||
(void)arg;
|
||||
for (int i = 0; i < ROUNDS; i++) {
|
||||
ldaddal64(&counter64, 1);
|
||||
ldadd32(&counter32, 1);
|
||||
ldaddlh(&counter16, 1);
|
||||
ldaddab(&counter8, 1);
|
||||
uint64_t seen = __atomic_load_n(&spin, __ATOMIC_RELAXED);
|
||||
while (casal64(&spin, seen, seen + 1) != seen) seen = __atomic_load_n(&spin, __ATOMIC_RELAXED);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static volatile sig_atomic_t app_handler_ran;
|
||||
|
||||
static void app_sigill(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)info;
|
||||
app_handler_ran = 1;
|
||||
((ucontext_t *)context)->uc_mcontext.pc += 4;
|
||||
}
|
||||
|
||||
static void simple_sigill(int sig) { (void)sig; }
|
||||
|
||||
static volatile sig_atomic_t once_calls, persistent_calls, once_saw_default;
|
||||
static void persistent_sigill(int sig) { (void)sig; persistent_calls++; }
|
||||
|
||||
static void once_sigill(int sig) {
|
||||
struct sigaction previous, next = {0};
|
||||
once_calls++;
|
||||
if (sigaction(sig, NULL, &previous) == 0 && previous.sa_handler == SIG_DFL)
|
||||
once_saw_default = 1;
|
||||
next.sa_handler = persistent_sigill;
|
||||
sigemptyset(&next.sa_mask);
|
||||
if (sigaction(sig, &next, NULL) != 0) _Exit(2);
|
||||
}
|
||||
|
||||
static void check_one_shot_action(void) {
|
||||
struct sigaction action = {0};
|
||||
action.sa_handler = once_sigill;
|
||||
action.sa_flags = SA_RESETHAND;
|
||||
sigemptyset(&action.sa_mask);
|
||||
check(sigaction(SIGILL, &action, NULL) == 0, "install one-shot SIGILL");
|
||||
check(raise(SIGILL) == 0, "deliver one-shot SIGILL");
|
||||
check(once_calls == 1 && once_saw_default, "one-shot consumed before calling handler");
|
||||
check(raise(SIGILL) == 0, "deliver replacement SIGILL");
|
||||
check(once_calls == 1 && persistent_calls == 1, "replacement survives one-shot consumption");
|
||||
}
|
||||
|
||||
|
||||
static void set_test_action(int variant) {
|
||||
struct sigaction sa = {0};
|
||||
sigemptyset(&sa.sa_mask);
|
||||
if (variant == 0) {
|
||||
sa.sa_handler = simple_sigill;
|
||||
sigaddset(&sa.sa_mask, SIGUSR1);
|
||||
} else {
|
||||
sa.sa_sigaction = app_sigill;
|
||||
sa.sa_flags = SA_SIGINFO;
|
||||
sigaddset(&sa.sa_mask, SIGUSR2);
|
||||
}
|
||||
int attempt;
|
||||
for (attempt = 0; attempt < 10000; attempt++) {
|
||||
if (sigaction(SIGILL, &sa, NULL) == 0) return;
|
||||
check(errno == ENOMEM, "unexpected action publication failure");
|
||||
sched_yield();
|
||||
}
|
||||
check(0, "action slots stayed exhausted");
|
||||
}
|
||||
|
||||
static void *replace_test_action(void *unused) {
|
||||
(void)unused;
|
||||
for (int i = 0; i < 4096; i++) set_test_action(i & 1);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void *query_test_action(void *unused) {
|
||||
(void)unused;
|
||||
for (int i = 0; i < 4096; i++) {
|
||||
struct sigaction sa;
|
||||
check(sigaction(SIGILL, NULL, &sa) == 0, "query SIGILL action");
|
||||
int a = sigismember(&sa.sa_mask, SIGUSR1);
|
||||
int b = sigismember(&sa.sa_mask, SIGUSR2);
|
||||
if (sa.sa_flags & SA_SIGINFO)
|
||||
check(sa.sa_sigaction == app_sigill && !a && b, "coherent siginfo snapshot");
|
||||
else
|
||||
check(sa.sa_handler == simple_sigill && a && !b, "coherent simple snapshot");
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static unsigned int fork_readers_stop;
|
||||
|
||||
static void *read_during_fork(void *unused) {
|
||||
(void)unused;
|
||||
while (!__atomic_load_n(&fork_readers_stop, __ATOMIC_RELAXED)) {
|
||||
struct sigaction out;
|
||||
if (sigaction(SIGILL, NULL, &out) != 0) _Exit(4);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void check_forked_actions(void) {
|
||||
struct sigaction install = {0};
|
||||
install.sa_handler = simple_sigill;
|
||||
sigemptyset(&install.sa_mask);
|
||||
check(sigaction(SIGILL, &install, NULL) == 0, "install SIGILL before fork");
|
||||
pthread_t readers[4];
|
||||
for (int i = 0; i < 4; i++)
|
||||
check(pthread_create(&readers[i], NULL, read_during_fork, NULL) == 0, "start fork reader");
|
||||
for (int child = 0; child < 8; child++) {
|
||||
pid_t pid = fork();
|
||||
check(pid >= 0, "fork SIGILL snapshot child");
|
||||
if (pid == 0) {
|
||||
struct sigaction inherited;
|
||||
if (sigaction(SIGILL, NULL, &inherited) != 0 || inherited.sa_handler != simple_sigill) _Exit(2);
|
||||
for (int i = 0; i < 1024; i++)
|
||||
if (sigaction(SIGILL, &install, NULL) != 0) _Exit(3);
|
||||
_Exit(0);
|
||||
}
|
||||
int status = 0;
|
||||
check(waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0,
|
||||
"child keeps action and can recycle more than 256 slots");
|
||||
}
|
||||
__atomic_store_n(&fork_readers_stop, 1, __ATOMIC_RELAXED);
|
||||
for (int i = 0; i < 4; i++) check(pthread_join(readers[i], NULL) == 0, "join fork reader");
|
||||
}
|
||||
|
||||
static void check_reused_actions(void) {
|
||||
set_test_action(0);
|
||||
pthread_t threads[4];
|
||||
for (int i = 0; i < 4; i++)
|
||||
check(pthread_create(&threads[i], NULL, i < 2 ? replace_test_action : query_test_action, NULL) == 0,
|
||||
"start action worker");
|
||||
for (int i = 0; i < 4; i++) check(pthread_join(threads[i], NULL) == 0, "join action worker");
|
||||
}
|
||||
|
||||
static __attribute__((noinline)) void single_forms(void) {
|
||||
uint64_t v = 0xF0;
|
||||
uint64_t old;
|
||||
register uint64_t ldap_result __asm__("x0");
|
||||
register uintptr_t ldap_address __asm__("x1") = (uintptr_t)&v;
|
||||
__asm__ volatile(".inst 0xf8bfc020" : "=r"(ldap_result) : "r"(ldap_address) : "memory");
|
||||
check(ldap_result == v, "ldapr");
|
||||
__asm__ volatile("ldclral %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0x30), "r"(&v) : "memory");
|
||||
check(old == 0xF0 && v == 0xC0, "ldclral");
|
||||
__asm__ volatile("ldeora %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0xFF), "r"(&v) : "memory");
|
||||
check(old == 0xC0 && v == 0x3F, "ldeora");
|
||||
__asm__ volatile("ldsetl %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0x100), "r"(&v) : "memory");
|
||||
check(old == 0x3F && v == 0x13F, "ldsetl");
|
||||
__asm__ volatile("swpal %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)7), "r"(&v) : "memory");
|
||||
check(old == 0x13F && v == 7, "swpal");
|
||||
|
||||
int64_t s = -5;
|
||||
int64_t sold;
|
||||
__asm__ volatile("ldsmax %x1, %x0, [%2]" : "=r"(sold) : "r"((int64_t)-9), "r"(&s) : "memory");
|
||||
check(sold == -5 && s == -5, "ldsmax keeps the larger value");
|
||||
uint32_t u = 10;
|
||||
uint32_t uold;
|
||||
__asm__ volatile("ldumin %w1, %w0, [%2]" : "=r"(uold) : "r"((uint32_t)3), "r"(&u) : "memory");
|
||||
check(uold == 10 && u == 3, "ldumin");
|
||||
|
||||
uint64_t pair[2] __attribute__((aligned(16))) = {1, 2};
|
||||
register uint64_t e0 __asm__("x4") = 1, e1 __asm__("x5") = 2, d0 __asm__("x6") = 3, d1 __asm__("x7") = 4;
|
||||
__asm__ volatile("caspal x4, x5, x6, x7, [%4]" : "+r"(e0), "+r"(e1) : "r"(d0), "r"(d1), "r"(pair) : "memory");
|
||||
check(e0 == 1 && e1 == 2 && pair[0] == 3 && pair[1] == 4, "caspal");
|
||||
register uint64_t m0 __asm__("x4") = 8, m1 __asm__("x5") = 9, n0 __asm__("x6") = 5, n1 __asm__("x7") = 6;
|
||||
__asm__ volatile("caspal x4, x5, x6, x7, [%4]" : "+r"(m0), "+r"(m1) : "r"(n0), "r"(n1), "r"(pair) : "memory");
|
||||
check(m0 == 3 && m1 == 4 && pair[0] == 3 && pair[1] == 4, "caspal returns the current pair on a mismatch");
|
||||
|
||||
uint64_t missed = casal64(&v, 99, 1);
|
||||
check(missed == 7 && v == 7, "casal leaves memory alone on a mismatch");
|
||||
|
||||
uint32_t m = 1;
|
||||
uint32_t mold;
|
||||
uint64_t eq;
|
||||
__asm__ volatile("cmp %w3, %w3\n\tldumax %w2, %w0, [%4]\n\tcset %1, eq"
|
||||
: "=&r"(mold), "=&r"(eq) : "r"((uint32_t)5), "r"((uint32_t)0), "r"(&m) : "memory", "cc");
|
||||
check(mold == 1 && m == 5 && eq == 1, "ldumax leaves the condition flags alone");
|
||||
int8_t b = -3;
|
||||
int8_t bold;
|
||||
__asm__ volatile("cmp %w3, %w3\n\tldsmaxb %w2, %w0, [%4]\n\tcset %1, eq"
|
||||
: "=&r"(bold), "=&r"(eq) : "r"((int32_t)-7), "r"((uint32_t)0), "r"(&b) : "memory", "cc");
|
||||
check(bold == -3 && b == -3 && eq == 1, "ldsmaxb leaves the condition flags alone");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc == 2 && strcmp(argv[1], "sigill-fork") == 0) {
|
||||
check_forked_actions();
|
||||
puts("sigill fork ok");
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && strcmp(argv[1], "sigill-oneshot") == 0) {
|
||||
check_one_shot_action();
|
||||
puts("sigill one-shot ok");
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && strcmp(argv[1], "sigill-actions") == 0) {
|
||||
check_reused_actions();
|
||||
puts("sigill actions ok");
|
||||
return 0;
|
||||
}
|
||||
int threads_wanted = argc > 1 ? atoi(argv[1]) : 4;
|
||||
check(threads_wanted >= 1 && threads_wanted <= MAX_THREADS, "thread count");
|
||||
single_forms();
|
||||
single_forms();
|
||||
|
||||
pthread_t threads[MAX_THREADS];
|
||||
int started = 0;
|
||||
for (; started < threads_wanted; started++) {
|
||||
int err = pthread_create(&threads[started], NULL, worker, NULL);
|
||||
if (err != 0) {
|
||||
for (int i = 0; i < started; i++) pthread_join(threads[i], NULL);
|
||||
fprintf(stderr, "pthread_create failed: %s\n", strerror(err));
|
||||
return err;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < started; i++) {
|
||||
int err = pthread_join(threads[i], NULL);
|
||||
if (err != 0) {
|
||||
fprintf(stderr, "pthread_join failed: %s\n", strerror(err));
|
||||
return err;
|
||||
}
|
||||
}
|
||||
uint64_t total = (uint64_t)threads_wanted * ROUNDS;
|
||||
check(counter64 == total, "64-bit counter");
|
||||
check(counter32 == (uint32_t)total, "32-bit counter");
|
||||
check(counter16 == (uint16_t)total, "16-bit counter");
|
||||
check(counter8 == (uint8_t)total, "8-bit counter");
|
||||
check(spin == total, "casal loop");
|
||||
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof sa);
|
||||
sa.sa_sigaction = app_sigill;
|
||||
sa.sa_flags = SA_SIGINFO;
|
||||
sigaction(SIGILL, &sa, NULL);
|
||||
__asm__ volatile("udf #0");
|
||||
check(app_handler_ran, "the program's own SIGILL handler still runs");
|
||||
|
||||
printf("lse ok\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
@@ -25,142 +24,6 @@ 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,141 @@
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
SYSROOT = Path("/usr/aarch64-linux-gnu")
|
||||
|
||||
|
||||
def toolchain():
|
||||
if not (shutil.which("aarch64-linux-gnu-gcc") and shutil.which("qemu-aarch64") and SYSROOT.is_dir()):
|
||||
if os.environ.get("CI"):
|
||||
raise AssertionError("CI must install gcc-aarch64-linux-gnu, libc6-dev-arm64-cross and qemu-user")
|
||||
raise unittest.SkipTest("needs aarch64-linux-gnu-gcc, libc6-dev-arm64-cross and qemu-user")
|
||||
|
||||
|
||||
class LseEmuTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
toolchain()
|
||||
cls.tmp = tempfile.TemporaryDirectory(prefix="droiddeck-lse-")
|
||||
out = Path(cls.tmp.name)
|
||||
subprocess.run(["bash", str(TOOLS / "linuxfs/lse-emu/build.sh"), str(out)], check=True)
|
||||
cls.library = out / "usr/local/lib/droiddeck-lse/liblse_emu.so"
|
||||
cls.program = out / "lse-test"
|
||||
subprocess.run(["aarch64-linux-gnu-gcc", "-O1", "-march=armv8.1-a", "-Wall", "-Wextra", "-Werror", "-pthread",
|
||||
str(Path(__file__).with_name("lse_emu_test.c")), "-o", str(cls.program)], check=True)
|
||||
cls.early_library = out / "liblse_emu_early.so"
|
||||
subprocess.run(["aarch64-linux-gnu-gcc", "-shared", "-fPIC", "-O1", "-march=armv8.1-a", "-Wall", "-Wextra", "-Werror",
|
||||
str(Path(__file__).with_name("lse_emu_early_dependency.c")), "-o", str(cls.early_library)], check=True)
|
||||
cls.early_program = out / "lse-early-test"
|
||||
subprocess.run(["aarch64-linux-gnu-gcc", "-O1", "-Wall", "-Wextra", "-Werror",
|
||||
str(Path(__file__).with_name("lse_emu_early_main.c")), "-L", str(out),
|
||||
"-Wl,--no-as-needed", "-llse_emu_early", "-Wl,-rpath,$ORIGIN", "-o", str(cls.early_program)], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_on(self, cpu, *env, threads=4, program=None, program_args=None):
|
||||
command = ["qemu-aarch64",
|
||||
"-U", "LSE_EMU", "-U", "LSE_EMU_PATCH",
|
||||
"-U", "LSE_EMU_STATS", "-U", "LSE_EMU_LOG", "-U", "LSE_EMU_SKIP",
|
||||
"-cpu", cpu, "-L", str(SYSROOT)]
|
||||
for item in env:
|
||||
command += ["-E", item]
|
||||
args = [str(program or self.program)]
|
||||
if program_args is not None:
|
||||
args.extend(program_args)
|
||||
elif program is None:
|
||||
args.append(str(threads))
|
||||
return subprocess.run(command + args, capture_output=True, text=True, timeout=120)
|
||||
|
||||
def test_an_armv8_0_cpu_faults_without_the_emulator(self):
|
||||
result = self.run_on("cortex-a57")
|
||||
self.assertEqual(result.returncode, -4, result.stdout + result.stderr)
|
||||
|
||||
def test_dependency_constructor_can_execute_lse_before_preload_init(self):
|
||||
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", program=self.early_program)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("early lse ok", result.stdout)
|
||||
|
||||
def test_trapping_alone_runs_every_form_on_an_armv8_0_cpu(self):
|
||||
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_STATS=1")
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("lse ok", result.stdout)
|
||||
self.assertRegex(result.stderr, r"traps=[1-9]\d* patched=0 ")
|
||||
|
||||
def test_concurrent_sigill_registrations_keep_recycled_snapshots_coherent(self):
|
||||
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
|
||||
program_args=["sigill-actions"])
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("sigill actions ok", result.stdout)
|
||||
|
||||
def test_child_inherits_the_sigill_handler_but_not_other_threads_action_slots(self):
|
||||
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
|
||||
program_args=["sigill-fork"])
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("sigill fork ok", result.stdout)
|
||||
|
||||
def test_oneshot_sigill_is_consumed_before_dispatch_and_replacement_survives(self):
|
||||
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
|
||||
program_args=["sigill-oneshot"])
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("sigill one-shot ok", result.stdout)
|
||||
|
||||
def patched(self, threads):
|
||||
log = Path(self.tmp.name) / f"patched-{threads}.log"
|
||||
log.unlink(missing_ok=True)
|
||||
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_PATCH=1",
|
||||
"LSE_EMU_STATS=1", f"LSE_EMU_LOG={log}", threads=threads)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("lse ok", result.stdout)
|
||||
self.assertRegex(result.stderr, r"patched=[1-9]\d* failed=0",
|
||||
f"{result.stderr}\nLSE log:\n{log.read_text() if log.is_file() else '<missing>'}")
|
||||
self.assertTrue(log.is_file(), "patch log was not created")
|
||||
instructions = [
|
||||
int(match, 16)
|
||||
for match in re.findall(r"patched pc=0x[0-9a-f]+ insn=0x([0-9a-f]+)", log.read_text())
|
||||
]
|
||||
self.assertTrue(
|
||||
any((insn & 0x3FFFFC00) == 0x38BFC000 for insn in instructions),
|
||||
"LDAPR did not use a generated stub",
|
||||
)
|
||||
self.assertFalse(
|
||||
any((insn & 0xBFA07C00) == 0x08207C00 for insn in instructions),
|
||||
"CASP must remain on the stack-safe trap path",
|
||||
)
|
||||
self.assertFalse(
|
||||
any(
|
||||
(insn & 0x3F200C00) == 0x38200000
|
||||
and ((insn >> 15) & 1) == 0
|
||||
and ((insn >> 12) & 7) >= 4
|
||||
for insn in instructions
|
||||
),
|
||||
"min/max must remain on the stack-safe trap path",
|
||||
)
|
||||
self.assertNotRegex(result.stderr, r"unhandled pc=.*insn=0x(?!0000000000000000(?:\n|$))[0-9a-f]{16}")
|
||||
|
||||
def test_patching_runs_every_form_on_an_armv8_0_cpu(self):
|
||||
self.patched(threads=1)
|
||||
|
||||
def test_patching_stays_atomic_across_threads(self):
|
||||
self.patched(threads=4)
|
||||
|
||||
def test_it_stays_off_without_the_switch(self):
|
||||
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=0", "LSE_EMU_PATCH=0")
|
||||
self.assertEqual(result.returncode, -4, result.stdout + result.stderr)
|
||||
|
||||
def test_it_stays_off_on_a_cpu_with_lse(self):
|
||||
result = self.run_on("neoverse-n1", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_STATS=1")
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertNotIn("traps=", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,53 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ENV = Path(__file__).resolve().parents[1] / "nativeguest/hook/env.c"
|
||||
|
||||
|
||||
class NativeHookPreloadListTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.addClassCleanup(cls.tmp.cleanup)
|
||||
p = Path(cls.tmp.name)
|
||||
env = ENV.read_text()
|
||||
helpers = env[env.index("static int preload_has_entry("):env.index("// Filter the LSE")]
|
||||
(p / "probe.c").write_text("""
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
""" + helpers + """
|
||||
int main(int argc, char **argv) {
|
||||
(void)argc;
|
||||
char *out = merge_preload_env(argv[1], argv[2]);
|
||||
if (!out) return 2;
|
||||
puts(out);
|
||||
free(out);
|
||||
return 0;
|
||||
}
|
||||
""")
|
||||
cls.probe = p / "probe"
|
||||
subprocess.run([os.environ.get("CC", "cc"), "-Wall", "-Wextra", "-Werror",
|
||||
str(p / "probe.c"), "-o", str(cls.probe)], check=True)
|
||||
|
||||
def merge(self, host, inherited):
|
||||
return subprocess.check_output([self.probe, host, inherited], text=True).strip()
|
||||
|
||||
def test_nested_exec_keeps_the_same_multi_entry_chain(self):
|
||||
host = "/root/session.so:/root/hook.so"
|
||||
original = host + ":user.so"
|
||||
for _ in range(3):
|
||||
original = self.merge(host, original).removeprefix("LD_PRELOAD=")
|
||||
self.assertEqual(host + ":user.so", original)
|
||||
|
||||
def test_partial_chain_keeps_host_order_and_exact_matches(self):
|
||||
self.assertEqual("LD_PRELOAD=/root/session.so:/root/hook.so:/root/hook.so.extra:custom.so",
|
||||
self.merge("/root/session.so:/root/hook.so",
|
||||
"/root/hook.so.extra /root/session.so:custom.so"))
|
||||
|
||||
def test_empty_custom_chain_keeps_only_the_host_chain(self):
|
||||
self.assertEqual("LD_PRELOAD=host.so", self.merge("host.so", ""))
|
||||
@@ -555,6 +555,79 @@ def swap_total_kb():
|
||||
return 0
|
||||
|
||||
|
||||
CROSS_THREAD = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef PR_SET_SYSCALL_USER_DISPATCH
|
||||
#define PR_SET_SYSCALL_USER_DISPATCH 59
|
||||
#endif
|
||||
|
||||
extern void *__libc_malloc(size_t);
|
||||
extern void *__libc_calloc(size_t, size_t);
|
||||
extern void *__libc_realloc(void *, size_t);
|
||||
|
||||
static int watching;
|
||||
static pid_t victim;
|
||||
static int allocations;
|
||||
|
||||
static void count(void) {
|
||||
if (__atomic_load_n(&watching, __ATOMIC_ACQUIRE) && gettid() == __atomic_load_n(&victim, __ATOMIC_RELAXED)) __atomic_add_fetch(&allocations, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
void *malloc(size_t n) { count(); return __libc_malloc(n); }
|
||||
void *calloc(size_t a, size_t b) { count(); return __libc_calloc(a, b); }
|
||||
void *realloc(void *p, size_t n) { count(); return __libc_realloc(p, n); }
|
||||
|
||||
static void *idle(void *arg) {
|
||||
(void)arg;
|
||||
sigset_t none;
|
||||
sigemptyset(&none);
|
||||
__atomic_store_n(&victim, gettid(), __ATOMIC_RELAXED);
|
||||
__atomic_store_n(&watching, 1, __ATOMIC_RELEASE);
|
||||
sigsuspend(&none);
|
||||
__atomic_store_n(&watching, 0, __ATOMIC_RELEASE);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
sigset_t urg;
|
||||
sigemptyset(&urg);
|
||||
sigaddset(&urg, SIGURG);
|
||||
pthread_sigmask(SIG_BLOCK, &urg, NULL);
|
||||
void *lib = dlopen(argv[1], RTLD_LAZY);
|
||||
if (lib == NULL) { puts(dlerror()); return 1; }
|
||||
int (*control)(int, ...) = (int (*)(int, ...))dlsym(lib, "prctl");
|
||||
volatile char selector = 0;
|
||||
if (argc > 2) {
|
||||
pthread_key_t key, last = 0;
|
||||
while (pthread_key_create(&key, NULL) == 0) last = key;
|
||||
int r = control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector);
|
||||
printf("refused %d %s\n", r, r != 0 && errno == EAGAIN ? "again" : "other");
|
||||
pthread_key_delete(last);
|
||||
printf("retried %d\n", control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector));
|
||||
return 0;
|
||||
}
|
||||
if (control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector) != 0) { puts("nodispatch"); return 0; }
|
||||
pthread_t thread;
|
||||
pthread_create(&thread, NULL, idle, NULL);
|
||||
while (!__atomic_load_n(&watching, __ATOMIC_ACQUIRE)) usleep(1000);
|
||||
if (write(2, "signal\n", 7) != 7) return 1;
|
||||
kill(getpid(), SIGURG);
|
||||
pthread_join(thread, NULL);
|
||||
printf("allocations %d\n", allocations);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class ZramPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
@@ -773,6 +846,39 @@ class ZramPreloadTest(unittest.TestCase):
|
||||
self.assertEqual([1], out["trimmed"], out)
|
||||
self.assertEqual([1], out["named"], out)
|
||||
|
||||
def test_a_signal_on_another_thread_allocates_nothing_after_dispatch_was_armed(self):
|
||||
source = self.dir / "crossthread.c"
|
||||
program = self.dir / "crossthread"
|
||||
source.write_text(CROSS_THREAD)
|
||||
subprocess.run(["cc", "-O2", "-pthread", "-o", str(program), str(source), "-ldl"], check=True)
|
||||
environment = dict(os.environ, GLIBC_TUNABLES="glibc.rtld.optional_static_tls=0", LD_DEBUG="bindings")
|
||||
for name in ("LD_PRELOAD", "LD_BIND_NOW"):
|
||||
environment.pop(name, None)
|
||||
result = subprocess.run([str(program), str(self.lib)], env=environment, capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
if result.stdout.strip() == "nodispatch":
|
||||
self.skipTest("kernel lacks syscall user dispatch")
|
||||
self.assertEqual("allocations 0", result.stdout.strip())
|
||||
after = result.stderr.split("signal\n", 1)[1]
|
||||
self.assertNotIn("pthread_getspecific", after)
|
||||
refused = subprocess.run([str(program), str(self.lib), "exhaust"], env=environment, capture_output=True,
|
||||
text=True, timeout=60)
|
||||
self.assertEqual("refused -1 again\nretried 0", refused.stdout.strip())
|
||||
|
||||
def test_loads_at_runtime_without_spare_static_tls(self):
|
||||
loader = self.dir / "loader"
|
||||
source = self.dir / "loader.c"
|
||||
source.write_text("#include <dlfcn.h>\n#include <stdio.h>\n"
|
||||
"int main(int c, char **v) { (void)c; void *h = dlopen(v[1], RTLD_NOW);"
|
||||
" puts(h ? \"loaded\" : dlerror()); return h == NULL; }\n")
|
||||
subprocess.run(["cc", "-O2", "-o", str(loader), str(source), "-ldl"], check=True)
|
||||
environment = dict(os.environ, GLIBC_TUNABLES="glibc.rtld.optional_static_tls=0")
|
||||
environment.pop("LD_PRELOAD", None)
|
||||
result = subprocess.run([str(loader), str(self.lib)], env=environment, capture_output=True, text=True,
|
||||
timeout=60)
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertEqual("loaded", result.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,86 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,50 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,20 +0,0 @@
|
||||
// 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';
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
LIBRARY ffx_fsr2_api_x64.dll
|
||||
EXPORTS
|
||||
ffxFsr2ContextCreate
|
||||
ffxFsr2ContextDispatch
|
||||
ffxFsr2ContextGenerateReactiveMask
|
||||
ffxFsr2ContextDestroy
|
||||
ffxFsr2GetUpscaleRatioFromQualityMode
|
||||
ffxFsr2GetRenderResolutionFromQualityMode
|
||||
ffxFsr2GetJitterPhaseCount
|
||||
ffxFsr2GetJitterOffset
|
||||
ffxFsr2ResourceIsNull
|
||||
@@ -1,14 +0,0 @@
|
||||
LIBRARY ffx_fsr3upscaler_x64.dll
|
||||
EXPORTS
|
||||
ffxFsr3UpscalerContextCreate
|
||||
ffxFsr3UpscalerGetSharedResourceDescriptions
|
||||
ffxFsr3UpscalerContextDispatch
|
||||
ffxFsr3UpscalerContextGenerateReactiveMask
|
||||
ffxFsr3UpscalerContextDestroy
|
||||
ffxFsr3UpscalerGetUpscaleRatioFromQualityMode
|
||||
ffxFsr3UpscalerGetRenderResolutionFromQualityMode
|
||||
ffxFsr3UpscalerGetJitterPhaseCount
|
||||
ffxFsr3UpscalerGetJitterOffset
|
||||
ffxFsr3UpscalerResourceIsNull
|
||||
ffxFsr3UpscalerSetConstant
|
||||
ffxFsr3UpscalerGetEffectVersion
|
||||
@@ -1,168 +0,0 @@
|
||||
// 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
|
||||
@@ -1,40 +0,0 @@
|
||||
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
|
||||
@@ -1,3 +0,0 @@
|
||||
LIBRARY nvapi64
|
||||
EXPORTS
|
||||
nvapi_QueryInterface
|
||||
@@ -1,90 +0,0 @@
|
||||
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
|
||||
@@ -1,84 +0,0 @@
|
||||
"""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__)
|
||||
@@ -1,116 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,575 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
EXPORTS
|
||||
ffxCreateContext
|
||||
ffxDestroyContext
|
||||
ffxConfigure
|
||||
ffxQuery
|
||||
ffxDispatch
|
||||
@@ -1,895 +0,0 @@
|
||||
// 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
@@ -1,585 +0,0 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -1,576 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,444 +0,0 @@
|
||||
// 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();
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,486 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,825 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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)
|
||||
@@ -1,219 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
#!/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"
|
||||
@@ -1,64 +0,0 @@
|
||||
// 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
|
||||
@@ -1,784 +0,0 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// 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
@@ -1,49 +0,0 @@
|
||||
// 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
@@ -1,53 +0,0 @@
|
||||
// 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
@@ -1,43 +0,0 @@
|
||||
// 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
@@ -1,171 +0,0 @@
|
||||
// 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
@@ -1,557 +0,0 @@
|
||||
// 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
|
||||
@@ -1,168 +0,0 @@
|
||||
// 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
|
||||
@@ -1,97 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user