Compare commits

..
Author SHA1 Message Date
The412Banner c8f0f2ff2f fix(frontend): the app icon returns to a game started from a shortcut or front end 2026-12-06 01:56:46 +00:00
MaxsTechReview f2206893d0 fix: Share logs includes Easy Anti-Cheat launcher logs from game prefixes (#3760)
* fix: Share logs includes Easy Anti-Cheat launcher logs from game prefixes

Anti-cheat launch failures only show the real error code in anticheatlauncher.log inside the game's compatdata prefix, which Share logs never collected. Recent .log files under each prefix's EasyAntiCheat folder are now added under anticheat/<appid>/ with high share priority.

* Keep only the anti-cheat app ID readable and keep launcher logs from every library

A numeric folder name is readable only as the app ID right under anticheat/; elsewhere it is hashed as before. Prefixes for the same app ID in a second library go under anticheat/<appid>/library<N>/ so neither log is dropped.

* Keep signed compatdata prefixes and mark unreadable ones as partial in Share logs

* Keep discovery records inside the manifest limit

* fix(logs): keep both prefix folders when signed and unsigned app ids collide

* fix(logs): give each anti-cheat prefix its own sibling folder in the archive

* fix(logs): share the current session's game logs before anti-cheat logs

* fix(logs): order enhanced exports by share priority and record denied anti-cheat folders
2026-12-05 20:42:07 -05:00
MaxsTechReviewandKurt Himebauch ce64f5ade4 fix(gog): create ISI savePath folders on first launch (#3452)
* fix(gog): create ISI savePath folders on first launch

* Use the existing case of GOG save folder roots

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-12-05 20:29:55 -05:00
Kurt Himebauch c85e82683b Standardize native runtime defaults (#3779)
fix: standardize guest runtime defaults
2026-12-05 19:51:23 -05:00
LunaDLandKurt Himebauch 88d44b0dc6 Feat: Improve ARMv8.0 Steam compatibility with LSE emulation (#3720)
* feat: emulate LSE atomics so the Steam client starts on ARMv8.0 CPUs

* fix: keep NZCV across patched LSE min/max stubs and catch st* aliases

* fix: fail the LSE check when objdump fails

* fix: validate the CASP pair on a mismatch in the LSE emulator

* fix: sandboxes switch on the LSE emulator when it is preloaded

* fix: keep the MaliBridge pointer from main

* Handle LSE atomics before preload constructors

* Support early LSE handling in root guest processes

* Fix LSE-Emu signal and patching review findings

* Assert CASP and min/max sites use patched stubs

* Correct patch test statistics regexes

* Validate SIGILL syscall ABI and retain active state on restore failure

* Preserve the previous SIGILL disposition during early install

* Synchronize instruction fetch on generated LSE stubs

* Address LSE-Emu follow-up review findings

* Fix missing LSE signal handler state declarations

* Honor application signal mask when forwarding SIGILL

* Preserve SA_RESETHAND mask during handler forwarding

* Fix LSE opt-out after early handler install

* Avoid recursive SIGILL forwarding during LSE emulation

* Fix LSE SIGILL handler re-entry tracking

* Honor SA_NODEFER in forwarded SIGILL mask

* Preserve nested SIGILL delivery semantics

* Preserve explicit SIGILL mask with SA_NODEFER

* Reduce LSE patch contention across threads

* Guard nested faults before acquiring patch lock

* Fix early SIGILL restore and wake patch waiters

* Preserve libc restorer when restoring application SIGILL

* Wait for concurrent LSE patch instead of skipping

* Fix LSE patch lock release and fork recovery

* Avoid reinstalling the early SIGILL handler

* chore: retrigger CI

* Avoid proc maps reads in concurrent SIGILL patching

* Prevent late IFUNC handler install when emulation is disabled

* Clarify cached mapping lookup

* Move cached map declarations before find_gap

* Default LSE instruction patching to off

* Document conservative LSE emulation default

* Keep LSE instruction patching opt-in in sandbox preload

* Document default and opt-in LSE emulation checks

* Assert LSE patching remains opt-in in sandbox tests

* Align LSE device checks with SDK 34 patching behavior

* Check expected mprotect failures in opt-in device run

* Clarify LSE emulator device validation criteria

* Specify controlled SDK mprotect validation

* fix(lse-emu): publish SIGILL actions atomically

* fix(runtime): honor LSE_EMU=0 before preload

* test(runtime): keep LSE preload disabled when opted out

* fix(runtime): fully honor LSE_EMU=0 opt-out

* test(runtime): verify LSE opt-out removes inherited preload

* fix(runtime): filter inherited LSE preload without preload file

* fix(lse-emu): use bounded signal-safe action snapshots

* fix(runtime): split inherited preloads on spaces and colons

* test(runtime): cover both LSE preload entry orders

* fix(lse-emu): recycle displaced SIGILL snapshots

* fix(preload): preserve colliding path cache entries

* test(lse-emu): report patch failure details

* fix(lse-emu): serialize action snapshot publishers

* fix(lse-emu): fall back to reachable arena mapping

* fix(lse-emu): make signal action publication nonblocking

* refactor(lse-emu): remove obsolete publisher lock

* Fix SIGILL snapshot retirement and honor session LSE opt-out

* Preserve the Java staging API and isolate the SIGILL stress test

* fix(nativeguest): filter LSE preload when disabled

* fix(lse-emu): tighten seccomp and signal setup

* fix(session): preserve active LSE override while staging

* fix(lse-emu): return atomically displaced signal actions

* fix(lse-emu): stage raw signal masks safely

* fix(lse-emu): distinguish seccomp listener success

* fix(lse-emu): publish seccomp veto atomically

* fix(lse-emu): fail closed on RX restore errors

* fix(lse-emu): keep stack-using atomic stubs on trap path

* fix(lse-emu): allow patching with inherited seccomp

* test(lse-emu): cover LDAPR patch path

* test(lse-emu): assert LDAPR-only patching

* fix(nativeguest): filter disabled LSE from preload chains

* docs(lse-emu): define inherited seccomp patch policy

* fix(lse-emu): emulate LDAPR trap fallback

* refactor(lse-emu): remove unused seccomp query

* fix(nativeguest): release filtered preload chain in scope

* test(lse-emu): allow forwarded udf diagnostic

* fix(nativeguest): avoid unsafe preload fallback when disabled

* test(lse-emu): match full zero instruction field

* test(lse-emu): match complete instruction diagnostics

* Keep nested native preloads from duplicating host libraries

* fix(nativeguest): fail exec when disabled preload cannot map

* fix(nativeguest): stop exec when preload mapping fails

* fix(nativeguest): propagate preload filter allocation failures

* Consume only the selected one-shot SIGILL action

* Reclaim abandoned SIGILL action slots after fork

* Revalidate the live file mapping before optional LSE patching

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-12-05 19:09:28 -05:00
MaxsTechReview 73fac3723f fix: Games start again in proot sessions (session preload no longer needs spare static TLS) (#3765)
* Keep the session preload loadable when spare static TLS runs out

The syscall-dispatch selector pointer in the zram preload used the
initial-exec TLS model. That marks the whole libddsession TLS block
(about 1.8 KB) as static, so loading it at runtime needs that much spare
static TLS. Under proot there is not enough, and every guest program
failed with "cannot allocate memory in static TLS block". The default
model keeps the same per-thread behaviour without that requirement.

* Read the dispatch selector only once a thread has turned dispatch on

A thread's first read of the selector can allocate its TLS block when the
preload was loaded at runtime. The page-out handler and the prctl wrapper
now read it only after some thread in the process enabled syscall user
dispatch, so processes that never use it never touch the variable from a
signal handler.

* Keep the dispatch selector in a thread key so the signal handler never allocates

* Bind the selector lookup before the handler can run and refuse to arm dispatch without a selector slot

* fix(preload): retry selector key setup after key exhaustion

* fix(preload): publish the dispatch selector only after the kernel accepts it
2026-12-05 18:57:23 -05:00
138 changed files with 2968 additions and 25307 deletions

No files matched your search

+3 -3
View File
@@ -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:
+1 -1
View File
@@ -55,7 +55,7 @@ jobs:
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
}
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic 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
View File
@@ -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 {
-1
View File
@@ -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)
@@ -191,9 +191,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true)
private var desktopAsUser by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
@@ -1331,8 +1328,22 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
finish()
}
private fun ownsTask(): Boolean = runCatching {
getSystemService(android.app.ActivityManager::class.java)?.appTasks.orEmpty().any { task ->
val info = task.taskInfo
@Suppress("DEPRECATION")
val id = if (Build.VERSION.SDK_INT >= 29) info.taskId else info.persistentId
id == taskId
}
}.getOrDefault(false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (com.droiddeck.launcher.frontend.LauncherReopen.revealsTask(intent.action, intent.categories, isTaskRoot,
savedInstanceState != null, SessionState.pipActive, ::ownsTask)) {
finish()
return
}
drivers.restartBlocked = ::runtimeChangesBlocked
drivers.loadTpUbwcMode()
val handoff = if (savedInstanceState == null && intent.getBooleanExtra(EXTRA_RESTARTED, false)) LauncherHandoff.take() else null
@@ -3125,7 +3136,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
nativeDesktopAvailable = com.droiddeck.launcher.runtime.NativeGuest.nextSession(this), desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
@@ -3139,9 +3150,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
@@ -3464,9 +3472,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
nativeUserland = SessionPrefs.nativeUserland(this)
desktopAsUser = SessionPrefs.desktopAsUser(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
@@ -3862,7 +3862,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
presentationFaultHint()?.let { return it }
if (log == null || !log.isFile) return null
return try {
var enosys = 0
var fexMissing = false
val size = log.length()
val text = java.io.RandomAccessFile(log, "r").use { f ->
@@ -3873,7 +3872,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
String(bytes, Charsets.ISO_8859_1)
}
text.lineSequence().forEach { line ->
if (line.contains("Function not implemented")) enosys++
if (line.contains(FEX_MISSING)) fexMissing = true
}
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
@@ -3895,9 +3893,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else if (fexMissing) {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
} else if (enosys >= 8) {
EndHint(resources.getQuantityString(R.plurals.session_hint_enosys, enosys, enosys,
getString(R.string.perf_title), getString(R.string.perf_seccomp), getString(R.string.perf_xalia)))
} else null
} catch (e: Exception) {
null
@@ -571,7 +571,6 @@ object AgentHost {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -14,8 +14,6 @@ object AgentNative {
fun run(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
val root = LinuxRuntime.rootDir(context)
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
// with the setting off, staging leaves the rootfs as proot wants it
if (!com.droiddeck.launcher.session.SessionPrefs.nativeUserland(context)) NativeGuest.prepare(context, root)
if (!NativeGuest.available(root)) throw AgentException("NATIVE_UNAVAILABLE", "The rootfs has no native hook or glibc loader yet; start a session once")
val argvJson = request.optJSONArray("argv") ?: throw AgentException("INVALID_REQUEST", "argv is required")
val argv = (0 until argvJson.length()).map { argvJson.getString(it) }
@@ -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)
}
}
@@ -291,9 +291,12 @@ object DeviceReport {
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(context))
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("native userland (no proot)", SessionPrefs.nativeUserland(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
k("guest runtime policy", "native preferred with PRoot fallback")
k("guest runtime", when (com.droiddeck.launcher.runtime.NativeGuest.sessionMode) {
true -> "native"
false -> "PRoot"
null -> if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) "native available" else "native unavailable"
})
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
k("Guest host name", SessionPrefs.guestHostname(context))
@@ -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,
)
}
}
@@ -0,0 +1,15 @@
package com.droiddeck.launcher.frontend
import android.content.Intent
object LauncherReopen {
fun revealsTask(
action: String?,
categories: Set<String>?,
taskRoot: Boolean,
restored: Boolean,
pipActive: Boolean,
ownTask: () -> Boolean,
): Boolean = action == Intent.ACTION_MAIN && categories?.contains(Intent.CATEGORY_LAUNCHER) == true &&
!taskRoot && !restored && !pipActive && ownTask()
}
@@ -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))
@@ -563,12 +577,15 @@ object BwrapSpawner {
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
val nativeSession = NativeGuest.forSession(context)
val native = if (nativeSession) nativeLaunch(context, plan) else null
val builder = if (native != null) {
ProcessBuilder(native.first).redirectErrorStream(true)
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
} else {
val reason = if (nativeSession) "sandbox native launch unavailable" else "parent guest uses PRoot"
Log.i(TAG, "Flatpak: using PRoot ($reason)")
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
@@ -585,7 +602,6 @@ object BwrapSpawner {
putAll(prootEnvironment(plan, envTool))
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -6,7 +6,6 @@ import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionFiles
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
@@ -67,7 +66,6 @@ object GuestCommand {
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
@@ -22,15 +22,15 @@ object NativeGuest {
}
fun enabled(context: Context): Boolean =
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
available(LinuxRuntime.rootDir(context))
/**
* Whether the next session will start natively. The session stages the hook from the APK before
* it starts, so only the setting and the rootfs's loader decide, and a runtime still to be
* it starts, so the rootfs's loader decides, and a runtime still to be
* installed will have one.
*/
fun nextSession(context: Context): Boolean =
SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null
@@ -39,7 +39,7 @@ object NativeGuest {
/**
* Whether a session's helpers (root commands, Flatpak sandboxes, installers) run natively: the
* session's own mode while one runs, as the setting can change under it and the rootfs is only
* session's own mode while one runs, as the rootfs is only
* prepared for native programs at a session's start.
*/
fun forSession(context: Context): Boolean = sessionMode ?: enabled(context)
@@ -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() }
}
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.Build
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.MessageDigest
@@ -12,17 +11,14 @@ object ProotFastPath {
const val LIBRARY = "/usr/local/lib/libddfastpath.so"
const val MAX_BINDS = 256
fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
preference && !noSeccomp && !nativeUserland && source == LinuxRuntime.PROOT_PACK
internal fun allows(source: String, native: Boolean): Boolean =
!native && source == LinuxRuntime.PROOT_PACK
fun enabled(context: Context): Boolean {
val preference = SessionPrefs.prootFastPath(context)
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
val nativeUserland = SessionPrefs.nativeUserland(context)
fun enabled(context: Context, native: Boolean = NativeGuest.forSession(context)): Boolean {
if (native) return false
val source = LinuxRuntime.prootSource(context)
val on = allows(preference, noSeccomp, source, nativeUserland)
if (preference && !noSeccomp && !nativeUserland && !on)
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
val on = allows(source, native)
if (!on) Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
return on
}
@@ -8,7 +8,6 @@ import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.DataInputStream
import java.io.DataOutputStream
@@ -128,7 +127,6 @@ object RootSpawner {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -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(" ", "\\ ") }
@@ -5,6 +5,7 @@ import android.os.ParcelFileDescriptor
import android.system.Os
import android.system.OsConstants
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONArray
@@ -25,6 +26,7 @@ import java.nio.channels.SeekableByteChannel
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.StandardOpenOption
@@ -221,7 +223,7 @@ internal object EnhancedSessionLogShare {
Category.values().map { category ->
val budget = budgets.getValue(category)
val records = ArrayList<Record>()
val selected = candidates.filter { it.category == category }
val selected = candidates.filter { it.category == category }.sortedBy(::sharePriority)
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
val names = HashSet<String>()
@@ -616,7 +618,8 @@ internal object EnhancedSessionLogShare {
redactionLearningComplete: Boolean,
) {
val entries = JSONArray()
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
val (discovery, rest) = records.partition { it.origin == "discovery" }
(discovery + rest).take(MAX_MANIFEST_RECORDS).forEach { record ->
entries.put(JSONObject().apply {
put("entry", record.entry)
put("origin", record.origin)
@@ -680,6 +683,15 @@ internal object EnhancedSessionLogShare {
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
}
}
fun addRecentLogs(root: File, entryPrefix: String, origin: String) {
val scan = walk(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
val base = root.toPath().toAbsolutePath().normalize()
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }.forEach { file ->
add(file, root, "$entryPrefix/${base.relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")}", origin)
}
}
CRITICAL_SESSION_FILES.forEach { name ->
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
}
@@ -713,16 +725,7 @@ internal object EnhancedSessionLogShare {
add(source.file, source.root, source.entry, "battlenet")
}
} else {
battleNetRoots(context).forEach { (prefix, root) ->
val scan = walk(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }
.forEach { file ->
val relative = root.toPath().toAbsolutePath().normalize().relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")
add(file, root, "battlenet/$prefix/$relative", "battlenet")
}
}
battleNetRoots(context).forEach { (prefix, root) -> addRecentLogs(root, "battlenet/$prefix", "battlenet") }
}
val sessionScan = walk(folder, remaining(maxFiles, out.size))
truncated = truncated || sessionScan.truncated
@@ -733,6 +736,9 @@ internal object EnhancedSessionLogShare {
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
add(file, folder, "${folder.name}/$relative", "session")
}
val antiCheat = antiCheatRoots(context)
partial = partial || antiCheat.partial
antiCheat.roots.forEach { (appId, root) -> addRecentLogs(root, "anticheat/$appId", "anticheat") }
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
val scan = directFiles(steam, remaining(maxFiles, out.size))
@@ -748,7 +754,8 @@ internal object EnhancedSessionLogShare {
private fun sharePriority(candidate: Candidate): Int = when {
candidate.origin == "session-critical" -> 0
candidate.origin == "session" && candidate.category == Category.GAMES -> 1
else -> 2
candidate.origin == "anticheat" -> 2
else -> 3
}
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
@@ -822,6 +829,39 @@ internal object EnhancedSessionLogShare {
return ScanResult(files, truncated, partial)
}
private class AntiCheatRoots(val roots: List<Pair<String, File>>, val partial: Boolean)
private fun antiCheatRoots(context: Context): AntiCheatRoots {
var partial = false
val seen = HashSet<String>()
val dirs = runCatching { Library.compatdataDirs(context) }.getOrElse { partial = true; emptyList() }
val roots = dirs.flatMapIndexed { library, compatdata ->
val prefixes = compatdata.listFiles() ?: run { partial = true; emptyArray() }
prefixes.filter { !Files.isSymbolicLink(it.toPath()) }.mapNotNull { prefix ->
val appId = steamAppId(prefix.name) ?: return@mapNotNull null
val root = File(prefix, EAC_LOG_DIR)
val directory = try {
Files.readAttributes(root.toPath(), BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS).isDirectory
} catch (_: NoSuchFileException) {
false
} catch (_: Exception) {
partial = true
false
}
if (!directory) return@mapNotNull null
val base = "$appId/library${library + 1}"
val key = base.takeIf { seen.add(it) } ?: "$base-${prefix.name}".takeIf { seen.add(it) }
if (key != null) key to root else { partial = true; null }
}
}
return AntiCheatRoots(roots, partial)
}
private fun steamAppId(name: String): String? =
name.takeIf { SIGNED_APP_ID.matches(it) }?.toLongOrNull()
?.takeIf { it in Int.MIN_VALUE.toLong()..0xffffffffL }
?.let { (it and 0xffffffffL).toString() }
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
@@ -928,7 +968,9 @@ internal object EnhancedSessionLogShare {
val normalized = name.replace('\\', '/').trimStart('/')
val parts = normalized.split('/')
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
return parts.joinToString("/") { safeComponent(it) }
return parts.mapIndexed { index, part ->
if (index == 1 && parts[0] == "anticheat" && APP_ID.matches(part)) part else safeComponent(part)
}.joinToString("/")
}
private fun safeComponent(value: String): String {
@@ -941,7 +983,7 @@ internal object EnhancedSessionLogShare {
private fun category(entry: String): Category {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
if (value.startsWith("battlenet/") || value.startsWith("anticheat/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
@@ -950,7 +992,7 @@ internal object EnhancedSessionLogShare {
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
private val KNOWN_COMPONENTS = setOf(
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
"steam", "graphics", "games", "battlenet", "anticheat", "anticheatlauncher.log", "client", "agent", "setup", "stores", "tools",
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
@@ -961,11 +1003,15 @@ internal object EnhancedSessionLogShare {
private val KNOWN_COMPONENT_PATTERNS = listOf(
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
Regex("steam-[0-9]+\\.(?:log|txt)"),
Regex("library[0-9]+(?:--?[0-9]{1,10})?"),
Regex("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
Regex("library[0-9]{1,3}"),
Regex("entry-[0-9a-f]{16}(?:\\.[a-z0-9]{1,8})?"),
)
private val APP_ID = Regex("[0-9]{1,10}")
private val SIGNED_APP_ID = Regex("-?[0-9]{1,10}")
private val SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
private val CRITICAL_SESSION_FILES = listOf(
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
@@ -973,6 +1019,7 @@ internal object EnhancedSessionLogShare {
)
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val STORE_LOG_SCAN = 512
private const val EAC_LOG_DIR = "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat"
private const val COPY_BUFFER_BYTES = 64 * 1024
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
@@ -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,20 +362,22 @@ 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")
}
val nativeUserland = SessionPrefs.nativeUserland(context)
if (nativeUserland) com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
if (ProotFastPath.enabled(context)) {
com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
val native = com.droiddeck.launcher.runtime.NativeGuest.available(root)
val nativePreload = preload.toString()
if (ProotFastPath.enabled(context, native)) {
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
preload.append(library + "\n")
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
}
val etc = File(root, "etc").apply { mkdirs() }
File(etc, "droiddeck").mkdirs()
FileUtils.writeString(File(etc, "droiddeck/native-preload"), preload.toString())
FileUtils.writeString(File(etc, "droiddeck/native-preload"), nativePreload)
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString())
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
@@ -1181,21 +1181,9 @@ object SessionPrefs {
prefs(context).edit().putBoolean("mountSharedStorage", on).apply()
}
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
fun setProotNoSeccomp(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
}
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
@@ -1203,12 +1191,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
}
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("prootFastPath", on).apply()
}
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
fun setCursorComposite(context: Context, on: Boolean) {
@@ -47,6 +47,7 @@ import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.NativeGuest
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -566,6 +567,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 +577,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)
@@ -783,12 +785,13 @@ class SessionService : Service() {
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
val sharedStorage = LinuxRuntime.sharedStorage(this)
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage)
val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
val nativeUserland = NativeGuest.enabled(this)
val fastPath = ProotFastPath.enabled(this, nativeUserland)
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage, fastPath)
synchronized(stopLock) {
if (gen == sessionGen && SessionState.running) com.droiddeck.launcher.runtime.NativeGuest.sessionMode = nativeUserland
}
val fastPathKey = if (ProotFastPath.enabled(this)) {
val fastPathKey = if (fastPath) {
val prootBinds = LinuxRuntime.binds(
this, sessionRoot, runtimeDir, sharedStorage, binds,
)
@@ -809,16 +812,14 @@ class SessionService : Service() {
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
} else {
val reason = if (NativeGuest.loader(root) == null) "missing glibc loader" else "missing native hook"
Log.i(TAG, "guest runtime: using PRoot ($reason)")
LinuxRuntime.command(this, sessionRoot, runtimeDir, sharedStorage, binds, guest)
}
val prootEnv = HostEnvironment()
prootEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
prootEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(this).path
if (SessionPrefs.prootNoSeccomp(this)) {
prootEnv["PROOT_NO_SECCOMP"] = "1"
if (!nativeUserland) Log.i(TAG, "proot: seccomp acceleration off by request")
}
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> prootEnv[k] = v } }
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
@@ -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)) }
@@ -1314,6 +1313,7 @@ class SessionService : Service() {
sessionRoot: File,
runtimeDir: File,
sharedStorage: File?,
fastPath: Boolean,
): ArrayList<String> {
val binds = ArrayList<String>()
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
@@ -1447,7 +1447,7 @@ class SessionService : Service() {
if (storageDiagnosticLibrary != null && library != null) libraries.add(SecondaryLibrary.CARD_GUESTS[0] to library.label)
val gamesLibraries = GameStorage.gamesFolderLibraries(this)
if (gamesLibraries.isNotEmpty()) {
var room = if (ProotFastPath.enabled(this)) {
var room = if (fastPath) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
for (games in gamesLibraries) {
@@ -1489,7 +1489,7 @@ class SessionService : Service() {
continue
}
try {
val room = if (ProotFastPath.enabled(this)) {
val room = if (fastPath) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val content = SecondaryLibrary.contentPath(entry.host)
@@ -1518,7 +1518,7 @@ class SessionService : Service() {
if (problem != null) {
Log.w(TAG, "x86-64 steam library: $problem")
} else try {
val room = if (ProotFastPath.enabled(this)) {
val room = if (fastPath) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val extra = SecondaryLibrary.binds(filesDir, x64, listOf(GameStorage.X64_CARD_GUEST)).drop(1)
@@ -1540,7 +1540,7 @@ class SessionService : Service() {
continue
}
try {
val room = if (ProotFastPath.enabled(this)) {
val room = if (fastPath) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val extra = SecondaryLibrary.binds(filesDir, entry.x64Host, listOf(entry.x64Guest)).drop(1)
@@ -1576,7 +1576,7 @@ class SessionService : Service() {
try {
val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() }
val volumes = org.json.JSONArray()
var room = if (ProotFastPath.enabled(this)) {
var room = if (fastPath) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
for (root in com.droiddeck.launcher.files.StorageRoots.list(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 }
}
@@ -8,7 +8,6 @@ import androidx.compose.runtime.setValue
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.AchievementNotifications
@@ -149,7 +148,6 @@ object GogComet {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -5,7 +5,6 @@ import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.json.JSONObject
import java.io.Closeable
@@ -107,7 +106,6 @@ internal object Xodus {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (key, value) -> put(key, value) } }
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
@@ -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 ->
@@ -46,9 +46,7 @@ fun PerformancePage(
fsyncFirst: Boolean,
gamescopeRealtime: Boolean,
gpuClockPin: Boolean,
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
nativeDesktopAvailable: Boolean,
desktopAsUser: Boolean,
cursorComposite: Boolean,
guestHostname: String,
@@ -65,9 +63,6 @@ fun PerformancePage(
onFsyncFirst: (Boolean) -> Unit,
onGamescopeRealtime: (Boolean) -> Unit,
onGpuClockPin: (Boolean) -> Unit,
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
onDesktopAsUser: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
@@ -152,26 +147,6 @@ fun PerformancePage(
stringResource(R.string.perf_fastsync_hint),
fastSync, onChange = onFastSync,
)
ToggleRow(
host, "seccomp", stringResource(R.string.perf_seccomp),
stringResource(R.string.perf_seccomp_hint),
prootNoSeccomp, onChange = onProotNoSeccomp,
)
ToggleRow(
host, "fastpath", stringResource(R.string.perf_fastpath),
when {
nativeUserland -> stringResource(R.string.perf_fastpath_needs_proot)
prootNoSeccomp -> stringResource(R.string.perf_fastpath_needs_seccomp)
else -> stringResource(R.string.perf_fastpath_hint)
},
prootFastPath && !prootNoSeccomp && !nativeUserland, enabled = !prootNoSeccomp && !nativeUserland,
onChange = onProotFastPath,
)
ToggleRow(
host, "nativeuserland", stringResource(R.string.perf_native_userland),
stringResource(R.string.perf_native_userland_hint),
nativeUserland, onChange = onNativeUserland,
)
ToggleRow(
host, "cursorcomposite", stringResource(R.string.perf_cursor_composite),
stringResource(R.string.perf_cursor_composite_hint),
@@ -198,8 +173,8 @@ fun PerformancePage(
}
ToggleRow(
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
desktopAsUser && nativeUserland, enabled = nativeUserland,
stringResource(R.string.perf_desktop_as_user_hint),
desktopAsUser && nativeDesktopAvailable, enabled = nativeDesktopAvailable,
onChange = onDesktopAsUser,
)
}
@@ -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
@@ -85,9 +85,6 @@ internal object SettingsIndex {
s(SettingsSection.PERFORMANCE, R.string.perf_esync, "esync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_fsync, "fsync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_fastsync, "ntsync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_seccomp, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_fastpath, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"),
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
-23
View File
@@ -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"))
}
}
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.frontend
import android.content.Intent
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class LauncherReopenTest {
private val launcher = setOf(Intent.CATEGORY_LAUNCHER)
private fun reveals(
action: String? = Intent.ACTION_MAIN,
categories: Set<String>? = launcher,
taskRoot: Boolean = false,
restored: Boolean = false,
pipActive: Boolean = false,
ownTask: Boolean = true,
) = LauncherReopen.revealsTask(action, categories, taskRoot, restored, pipActive) { ownTask }
@Test fun launcherIconStackedOnAShortcutTaskShowsThatTask() {
assertTrue(reveals())
}
@Test fun launcherIconStartingTheTaskOpensTheMenu() {
assertFalse(reveals(taskRoot = true))
}
@Test fun shortcutsLinksAndInternalOpensStillOpenTheMenu() {
assertFalse(reveals(action = Intent.ACTION_VIEW, categories = null))
assertFalse(reveals(action = GameLaunchIntent.ACTION, categories = null))
assertFalse(reveals(categories = null))
assertFalse(reveals(categories = setOf(Intent.CATEGORY_HOME, Intent.CATEGORY_DEFAULT)))
}
@Test fun anotherAppsTaskRestoredMenuAndPictureInPictureKeepTheMenu() {
assertFalse(reveals(ownTask = false))
assertFalse(reveals(restored = true))
assertFalse(reveals(pipActive = true))
}
@Test fun taskOwnershipIsOnlyQueriedForAStackedLauncherOpen() {
var asked = false
LauncherReopen.revealsTask(Intent.ACTION_MAIN, launcher, true, false, false) { asked = true; true }
assertFalse(asked)
}
}
@@ -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() }
@@ -0,0 +1,38 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import java.io.File
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class NativeGuestDefaultsTest {
@Test fun savedRuntimeOverridesDoNotDisableNativeExecution() {
val context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putBoolean("nativeUserland", false)
.putBoolean("prootFastPath", false)
.putBoolean("prootNoSeccomp", true)
.apply()
val root = LinuxRuntime.rootDir(context)
val hook = NativeGuest.hook(root)
val loader = File(root, "usr/lib/ld-linux-aarch64.so.1")
hook.parentFile?.mkdirs()
loader.writeText("fixture")
try {
assertTrue(NativeGuest.nextSession(context))
assertFalse(NativeGuest.enabled(context))
hook.writeText("fixture")
assertTrue(NativeGuest.enabled(context))
assertFalse(ProotFastPath.enabled(context, native = true))
} finally {
hook.delete()
loader.delete()
}
}
}
@@ -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()
@@ -27,14 +27,12 @@ class ProotFastPathTest {
}
@Test fun fastPathStaysOffForTheRootfsProot() {
assertTrue(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_ROOTFS))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_MISSING))
assertFalse(ProotFastPath.allows(preference = false, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = true, source = LinuxRuntime.PROOT_PACK))
assertTrue(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = false))
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_ROOTFS, native = false))
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_MISSING, native = false))
}
@Test fun fastPathStaysOffWithoutProot() {
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK, nativeUserland = true))
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = true))
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.assumeFilePermissionsEnforced
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.text.SimpleDateFormat
@@ -8,6 +9,7 @@ import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit
import java.util.zip.ZipFile
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
@@ -144,6 +146,136 @@ class SessionLogShareZipTest {
}
}
@Test fun theEasyAntiCheatLauncherLogsFromGamePrefixesComeAlong() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-09-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat")
val prefix = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata/976730")
val second = File(app.getExternalFilesDir(null), "second-library-${UUID.randomUUID()}").apply { mkdirs() }
val library = SteamLibraries.add(app, second.path) as SteamLibraries.AddResult.Added
try {
File(session, "session.log").writeText("booted\n")
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/4815162342").apply { mkdirs() }
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 261\n")
File(eac, "old.log").apply {
writeText("stale\n")
setLastModified(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30))
}
val secondEac = File(second, "steamapps/compatdata/976730/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/b1d0a8c3").apply { mkdirs() }
File(secondEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n")
val signedEac = File(prefix.parentFile, "-1768546955/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
File(signedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30005\n")
val unsignedEac = File(prefix.parentFile, "2526420341/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
File(unsignedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30007\n")
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val logs = archive.entries().toList().filter { it.name.startsWith("anticheat/976730/") }
assertEquals(2, logs.size)
assertTrue(logs.all { it.name.endsWith("/anticheatlauncher.log") && !it.name.contains("4815162342") })
val texts = logs.map { archive.getInputStream(it).bufferedReader().readText() }
assertTrue(texts.any { it.contains("Launch Error: 261") })
assertTrue(texts.any { it.contains("Launch Error: 206") })
val aliases = archive.entries().toList().filter { it.name.startsWith("anticheat/2526420341/") }
assertEquals(2, aliases.size)
assertEquals(2, aliases.map { it.name.split('/')[2] }.filter { it.startsWith("library1") }.toSet().size)
val aliasTexts = aliases.map { archive.getInputStream(it).bufferedReader().readText() }
assertTrue(aliasTexts.any { it.contains("Launch Error: 30005") })
assertTrue(aliasTexts.any { it.contains("Launch Error: 30007") })
}
} finally {
SteamLibraries.remove(app, library.entry.id)
out.deleteRecursively()
session.deleteRecursively()
prefix.deleteRecursively()
File(prefix.parentFile, "-1768546955").deleteRecursively()
File(prefix.parentFile, "2526420341").deleteRecursively()
second.deleteRecursively()
}
}
@Test fun theSessionsGameLogComesAlongWhenManyAntiCheatLogsAreFound() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-11-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-flood")
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
val prefixes = (0 until 300).map { File(compatdata, "${900000 + it}") }
try {
File(session, "session.log").writeText("booted\n")
File(session, "steam-976730.log").writeText("proton: game started\n")
prefixes.forEach { prefix ->
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n" + "x".repeat(64 * 1024))
}
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val game = archive.entries().toList().single { it.name.endsWith("/steam-976730.log") }
assertTrue(archive.getInputStream(game).bufferedReader().readText().contains("game started"))
}
} finally {
out.deleteRecursively()
session.deleteRecursively()
prefixes.forEach { it.deleteRecursively() }
}
}
@Test fun aDiscoveryFailureStaysInTheManifestWhenRecordsPassTheLimit() {
assumeFilePermissionsEnforced()
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-10-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/manifest-limit")
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata").apply { mkdirs() }
try {
repeat(300) {
File(session, "part-$it.log").writeText("line $it\n")
File(session, "wayland-$it.log").writeText("line $it\n")
File(session, "proton-$it.log").writeText("line $it\n")
}
assertTrue(compatdata.setReadable(false, false))
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
val entries = manifest.getJSONArray("entries")
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
assertTrue(entries.length() > 512)
assertTrue(reasons.toString(), "filesystem-error" in reasons)
}
} finally {
compatdata.setReadable(true, false)
out.deleteRecursively()
session.deleteRecursively()
}
}
@Test fun aPrefixThatDeniesTheAntiCheatFolderIsRecordedAsADiscoveryFailure() {
assumeFilePermissionsEnforced()
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-12-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-denied")
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
val prefix = File(compatdata, "976731")
val users = File(prefix, "pfx/drive_c/users").apply { mkdirs() }
try {
File(session, "session.log").writeText("booted\n")
assertTrue(users.setExecutable(false, false))
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
val entries = manifest.getJSONArray("entries")
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
assertTrue(reasons.toString(), "filesystem-error" in reasons)
}
} finally {
users.setExecutable(true, false)
out.deleteRecursively()
session.deleteRecursively()
prefix.deleteRecursively()
}
}
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
val logs = LinuxRuntime.logDir(app)
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
@@ -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")))
}
}
+147
View File
@@ -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.
+8 -6
View File
@@ -252,13 +252,15 @@ self-extractor stops at "Path not found", so the values it installs are applied
`goggame-<id>.info`, and a script's own `setRegistry` entries always win over the built-in table.
The script's `supportData` actions run right after: files and folders from the game folder
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}` and
`{localappdata}` in the prefix, and `type: folder` without a source creates the folder. Mods such
as one-click editions ship their `Plugins.txt` and INI files this way. Paths match without regard
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}`,
`{localappdata}` or `{userappdata}` in the prefix, and `type: folder` without a source creates the
folder. Mods such as one-click editions ship their `Plugins.txt` and INI files this way. The
`savePath` action's `savePath` folder is created with the same path rules, including the common
case where a one-click edition names it again as a `supportData` folder. Paths match without regard
to case, links are copied as links, and a path outside those folders is refused. A file the
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` in
the prefix holds the actions' hash, so they run once per script revision and a player's later
edits stay.
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` and
`.droiddeck-gog-save-path` in the prefix hold the actions' hashes, so they run once per script
revision and a player's later edits stay.
A GOG game's exe comes from its own manifest first: `goggame-<id>.info`'s play task in category
`game` (`isPrimary` first), or a primary `launcher` task for launcher games, whose `path` stays
-220
View File
@@ -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.
-3
View File
@@ -27,9 +27,6 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc
| droiddeck-esync | Settings › Performance (`droiddeck://settings/performance`) | esync, sync, wine |
| droiddeck-fsync first | Settings › Performance (`droiddeck://settings/performance`) | fsync, sync, wine |
| droiddeck-ntsync | Settings › Performance (`droiddeck://settings/performance`) | ntsync, sync, wine |
| Run proot without seccomp | Settings › Performance (`droiddeck://settings/performance`) | proot |
| proot fast path | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor |
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |
+1 -5
View File
@@ -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
-15
View File
@@ -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?}"; }
+1
View File
@@ -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
+1 -40
View File
@@ -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"
]
}
}
-2
View File
@@ -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
+2 -2
View File
@@ -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):
+4
View File
@@ -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"
+23
View File
@@ -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.
+15
View File
@@ -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:
+7
View File
@@ -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() {
@@ -968,6 +968,7 @@ def prepare_gog(sidecar, compat_data, launch_dir):
GOG_SCRIPTS = "goggame-*.script"
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
GOG_SUPPORT_MARK = ".droiddeck-gog-support"
GOG_SAVE_PATH_MARK = ".droiddeck-gog-save-path"
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
@@ -1716,7 +1717,7 @@ def prepare_steam_ea(argv, compat_data, launch_dir):
return REPLACED
def gog_support_actions(folder):
def gog_script_actions(folder, name):
found = []
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
product = script.name[len("goggame-"):-len(".script")]
@@ -1726,17 +1727,34 @@ def gog_support_actions(folder):
continue
for action in actions if isinstance(actions, list) else []:
install = action.get("install") if isinstance(action, dict) else None
if isinstance(install, dict) and install.get("action") == "supportData" \
if isinstance(install, dict) and install.get("action") == name \
and isinstance(install.get("arguments"), dict):
found.append((product, install["arguments"]))
return found
def gog_support_actions(folder):
return gog_script_actions(folder, "supportData")
def gog_case_child(path, part):
exact = path / part
try:
if not exact.exists() and path.is_dir():
return next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
except OSError:
pass
return exact
def gog_support_bases(folder, product, pfx):
user = Path(pfx) / "drive_c" / "users" / "steamuser"
support = Path(folder) / "support" / product
appdata = gog_case_child(user, "AppData")
return {"app": Path(folder), "supportdir": support, "support": support,
"userdocs": user / "Documents", "localappdata": user / "AppData" / "Local"}
"userdocs": gog_case_child(user, "Documents"),
"localappdata": gog_case_child(appdata, "Local"),
"userappdata": gog_case_child(appdata, "Roaming")}
def gog_inside(path, base):
@@ -1755,10 +1773,7 @@ def gog_support_path(text, bases):
base = bases[match.group(1).lower()]
path = base
for part in parts:
exact = path / part
if not exact.exists() and path.is_dir():
exact = next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
path = exact
path = gog_case_child(path, part)
if path != base and not gog_inside(path.parent, base):
return None
return path, base
@@ -1830,6 +1845,44 @@ def gog_support_data(folder, compat_data, proton):
return "copied=%d%s" % (copied, note)
def gog_save_paths(folder, compat_data, proton):
actions = gog_script_actions(folder, "savePath")
if not actions:
return "none"
pfx = Path(compat_data) / "pfx" if compat_data else None
if not pfx or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
made = create_prefix(compat_data, proton)
if made not in ("present", "created") or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
return "no-prefix"
stamp = hashlib.sha256(json.dumps(actions, sort_keys=True).encode("utf-8")).hexdigest()
marker = pfx / GOG_SAVE_PATH_MARK
try:
if marker.is_file() and marker.read_text() == stamp:
return "ready"
except OSError:
pass
paths = skipped = 0
for product, arguments in actions:
bases = gog_support_bases(folder, product, pfx)
found = gog_support_path(arguments.get("savePath") or arguments.get("target"), bases)
if found is None:
skipped += 1
continue
target, _root = found
try:
target.mkdir(parents=True, exist_ok=True)
paths += 1
except OSError:
skipped += 1
note = " skipped=%d" % skipped if skipped else ""
if not skipped:
try:
marker.write_text(stamp)
except OSError:
pass
return "paths=%d%s" % (paths, note)
def main(argv):
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
return 0
@@ -1876,6 +1929,7 @@ def main(argv):
prepare_gog(sidecar, compat_data, launch_dir)
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
log("gog save paths: " + gog_save_paths(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
if store == "rockstar":
if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar):
if compat_data:
+21 -10
View File
@@ -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")))
+50 -5
View File
@@ -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
View File
@@ -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;
}
+15
View File
@@ -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) {
-5
View File
@@ -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"
+4 -5
View File
@@ -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)
+17
View File
@@ -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) {}
+9
View File
@@ -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;
}
+300
View File
@@ -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;
}
-137
View File
@@ -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"
+141
View File
@@ -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", ""))
+115
View File
@@ -667,6 +667,10 @@ def support_data(**arguments):
return {'install': {'action': 'supportData', 'arguments': arguments}, 'name': 'supportData'}
def save_path(**arguments):
return {'install': {'action': 'savePath', 'arguments': arguments}, 'name': 'saveFolders'}
class GogSupportData(unittest.TestCase):
def prefix(self, root):
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
@@ -850,6 +854,117 @@ class GogSupportData(unittest.TestCase):
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
class GogSavePaths(unittest.TestCase):
def prefix(self, root):
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
user.mkdir(parents=True)
return user
def test_the_london_script_creates_its_save_path_and_keeps_player_settings(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='1897848199')
user = self.prefix(root)
support = folder / 'support/1897848199'
(support / 'docs').mkdir(parents=True)
(folder / '__AppData').mkdir()
(folder / '__AppData/save.dat').write_text('save')
for name in ('Fallout4Prefs.ini', 'Fallout4.ini'):
(support / 'docs' / name).write_text('[Archive]\n')
for name in ('DLCList.txt', 'Plugins.txt', 'UserDownloadedContent.txt'):
(support / name).write_text('*LondonWorldSpace.esm\n')
gog_script(folder, '1897848199', [
save_path(savePath='{userdocs}/My Games/Fallout4', type='folder'),
set_registry(root='HKLM', subkey='Software\\Bethesda Softworks\\Fallout4',
valueName='Installed Path', valueData='{app}\\', valueType='string'),
support_data(type='folder', target='{userdocs}/My Games/Fallout4'),
support_data(type='folder', target='{localappdata}/Fallout4'),
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4Prefs.ini',
target='{userdocs}/My Games/Fallout4/Fallout4Prefs.ini'),
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4.ini',
target='{userdocs}/My Games/Fallout4/Fallout4.ini'),
support_data(type='file', overwrite=True, source='{supportDir}/DLCList.txt',
target='{localappdata}/Fallout4/DLCList.txt'),
support_data(type='file', overwrite=True, source='{supportDir}/Plugins.txt',
target='{localappdata}/Fallout4/Plugins.txt'),
support_data(type='file', overwrite=True, source='{supportDir}/UserDownloadedContent.txt',
target='{localappdata}/Fallout4/UserDownloadedContent.txt'),
support_data(type='folder', overwrite=True, source='{app}/__AppData', target='{localappdata}/Fallout4'),
])
with patch.object(store, 'create_prefix') as create:
self.assertEqual('copied=6', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
create.assert_not_called()
saves = user / 'Documents/My Games/Fallout4'
self.assertTrue(saves.is_dir())
self.assertEqual('[Archive]\n', (saves / 'Fallout4.ini').read_text())
self.assertEqual('*LondonWorldSpace.esm\n', (user / 'AppData/Local/Fallout4/Plugins.txt').read_text())
self.assertTrue((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).is_file())
(saves / 'my settings.ini').write_text('player')
self.assertEqual('ready', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertEqual('player', (saves / 'my settings.ini').read_text())
def test_existing_prefix_base_names_keep_their_actual_case(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
(user / 'documents' / 'fixture').mkdir(parents=True)
(user / 'aPPdATA' / 'roaming').mkdir(parents=True)
gog_script(folder, '9', [
save_path(savePath='{UserDocs}/Fixture/Saves'),
save_path(savePath='{UserAppData}/Fixture/Settings'),
])
self.assertEqual('paths=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertTrue((user / 'documents/fixture/Saves').is_dir())
self.assertTrue((user / 'aPPdATA/roaming/Fixture/Settings').is_dir())
self.assertEqual({'documents', 'aPPdATA'}, {p.name for p in user.iterdir()})
self.assertEqual({'roaming'}, {p.name for p in (user / 'aPPdATA').iterdir()})
def test_only_save_path_actions_create_known_folders(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
saves = user / 'Documents/My Games/Fallout4'
saves.mkdir(parents=True)
(saves / 'Fallout4Prefs.ini').write_text('player')
gog_script(folder, '9', [
set_registry(root='HKLM', subkey='Software\\Game', valueName='a', valueData='b', valueType='string'),
{'install': {'action': 'createFolder', 'arguments': {'savePath': '{userdocs}/Other'}}},
save_path(savePath='{windir}/evil'),
save_path(savePath='{userdocs}/../../escape'),
save_path(savePath='{userappdata}/Ubisoft/Anno1404/Config'),
])
self.assertEqual('paths=1 skipped=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertTrue((user / 'AppData/Roaming/Ubisoft/Anno1404/Config').is_dir())
self.assertFalse((user / 'Documents/Other').exists())
self.assertFalse((Path(root) / 'escape').exists())
self.assertEqual('player', (saves / 'Fallout4Prefs.ini').read_text())
self.assertFalse((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).exists())
def test_without_save_paths_no_prefix_is_made(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
gog_script(folder, '9', [set_registry(root='HKLM', subkey='Software\\Game', valueName='a',
valueData='b', valueType='string')])
with patch.object(store, 'create_prefix') as create:
self.assertEqual('none', store.gog_save_paths(folder, root + '/compat', '/proton'))
create.assert_not_called()
def test_a_missing_prefix_is_made_first(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
gog_script(folder, '9', [save_path(savePath='{userdocs}/My Games/G')])
with patch.object(store, 'create_prefix', return_value='failed') as create:
self.assertEqual('no-prefix', store.gog_save_paths(folder, root + '/compat', '/proton'))
create.assert_called_once_with(root + '/compat', '/proton')
def made(compat_data, proton):
self.prefix(root)
return 'created'
with patch.object(store, 'create_prefix', side_effect=made):
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
class GogRegistry(unittest.TestCase):
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
with tempfile.TemporaryDirectory() as root:
+106
View File
@@ -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()
-86
View File
@@ -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.
-50
View File
@@ -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
-20
View File
@@ -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
-168
View File
@@ -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
-40
View File
@@ -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
-3
View File
@@ -1,3 +0,0 @@
LIBRARY nvapi64
EXPORTS
nvapi_QueryInterface
-90
View File
@@ -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
-84
View File
@@ -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__)
-116
View File
@@ -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;
}
-575
View File
@@ -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;
}
-6
View File
@@ -1,6 +0,0 @@
EXPORTS
ffxCreateContext
ffxDestroyContext
ffxConfigure
ffxQuery
ffxDispatch
-895
View File
@@ -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
-585
View File
@@ -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, &copy);
wl_leave_hook();
data->hWVTStateData = copy.hWVTStateData;
if (r == ERROR_SUCCESS) return ERROR_SUCCESS;
}
return ERROR_SUCCESS;
}
}
if (!o_WinVerifyTrust) {
HMODULE hw = o_LoadLibraryW ? o_LoadLibraryW(L"wintrust.dll") : NULL;
if (hw && o_GetProcAddress) o_WinVerifyTrust = (PFN_WinVerifyTrust)(void *)o_GetProcAddress(hw, "WinVerifyTrust");
}
return o_WinVerifyTrust ? o_WinVerifyTrust(hwnd, pgActionID, pWVTData) : ERROR_SUCCESS;
}
static BOOL WINAPI hk_CryptQueryObject(DWORD dwObjectType, const void *pvObject, DWORD dwExpectedContent,
DWORD dwExpectedFormat, DWORD dwFlags, DWORD *pdwEncoding,
DWORD *pdwContent, DWORD *pdwFormat, void *phCertStore,
void *phMsg, const void **ppvContext) {
if (!o_CryptQueryObject) {
HMODULE hc = o_LoadLibraryW ? o_LoadLibraryW(L"crypt32.dll") : NULL;
if (hc && o_GetProcAddress) o_CryptQueryObject = (PFN_CryptQueryObject)(void *)o_GetProcAddress(hc, "CryptQueryObject");
}
if (!o_CryptQueryObject) return FALSE;
if (!wl_in_hook() && dwObjectType == 1u /* CERT_QUERY_OBJECT_FILE */ && pvObject) {
const WCHAR *wpath = (const WCHAR *)pvObject;
if (wl_is_sig_target_w(wpath) && g_wl_signed_nv_dll[0]) {
wl_hook_log("[nvapi] hk_CryptQueryObject redirected nvngx -> signed NVIDIA donor");
return o_CryptQueryObject(dwObjectType, g_wl_signed_nv_dll, dwExpectedContent, dwExpectedFormat,
dwFlags, pdwEncoding, pdwContent, pdwFormat, phCertStore, phMsg, ppvContext);
}
}
return o_CryptQueryObject(dwObjectType, pvObject, dwExpectedContent, dwExpectedFormat,
dwFlags, pdwEncoding, pdwContent, pdwFormat, phCertStore, phMsg, ppvContext);
}
static LSTATUS WINAPI hk_RegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult) {
if (!wl_in_hook() && hKey == k_wl_sig_hkey && lpSubKey && phkResult) {
// Child subkey opened relative to our synthetic signature-override key (e.g. NGXCore):
// resolve against real HKLM\SOFTWARE\NVIDIA Corporation\Global\<subkey>
WCHAR full[256];
_snwprintf(full, 255, L"SOFTWARE\\NVIDIA Corporation\\Global\\%ls", lpSubKey);
full[255] = L'\0';
return o_RegOpenKeyExW ? o_RegOpenKeyExW(HKEY_LOCAL_MACHINE, full, ulOptions, samDesired, phkResult)
: ERROR_FILE_NOT_FOUND;
}
if (!wl_in_hook() && lpSubKey && phkResult &&
(_wcsicmp(lpSubKey, L"SOFTWARE\\NVIDIA Corporation\\Global") == 0 ||
_wcsicmp(lpSubKey, L"SYSTEM\\ControlSet001\\Services\\nvlddmkm") == 0 ||
_wcsicmp(lpSubKey, L"SYSTEM\\CurrentControlSet\\Services\\nvlddmkm") == 0)) {
*phkResult = k_wl_sig_hkey;
return ERROR_SUCCESS;
}
return o_RegOpenKeyExW ? o_RegOpenKeyExW(hKey, lpSubKey, ulOptions, samDesired, phkResult) : ERROR_FILE_NOT_FOUND;
}
static LSTATUS WINAPI hk_RegEnumValueW(HKEY hKey, DWORD dwIndex, LPWSTR lpValueName, LPDWORD lpcchValueName,
LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) {
if (hKey == k_wl_sig_hkey) {
if (dwIndex != 0) return ERROR_NO_MORE_ITEMS;
static const WCHAR k_guid[] = L"{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}";
DWORD len = (DWORD)wcslen(k_guid);
if (!lpValueName || !lpcchValueName || !lpData || !lpcbData) return ERROR_INVALID_PARAMETER;
if (*lpcchValueName <= len) { *lpcchValueName = len + 1; return ERROR_MORE_DATA; }
memcpy(lpValueName, k_guid, (len + 1) * sizeof(WCHAR));
*lpcchValueName = len;
if (lpType) *lpType = REG_BINARY;
if (*lpcbData < 1) { *lpcbData = 1; return ERROR_MORE_DATA; }
lpData[0] = 0x01;
*lpcbData = 1;
return ERROR_SUCCESS;
}
return o_RegEnumValueW ? o_RegEnumValueW(hKey, dwIndex, lpValueName, lpcchValueName, lpReserved, lpType, lpData, lpcbData)
: ERROR_NO_MORE_ITEMS;
}
static LSTATUS WINAPI hk_RegQueryValueExW(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved,
LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) {
if (hKey == k_wl_sig_hkey) {
if (lpValueName && _wcsicmp(lpValueName, L"{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}") == 0) {
if (lpType) *lpType = REG_BINARY;
if (!lpcbData) return ERROR_SUCCESS;
if (!lpData) { *lpcbData = 1; return ERROR_SUCCESS; }
if (*lpcbData < 1) { *lpcbData = 1; return ERROR_MORE_DATA; }
lpData[0] = 0x01;
*lpcbData = 1;
return ERROR_SUCCESS;
}
return ERROR_FILE_NOT_FOUND;
}
return o_RegQueryValueExW ? o_RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData)
: ERROR_FILE_NOT_FOUND;
}
static LSTATUS WINAPI hk_RegCloseKey(HKEY hKey) {
if (hKey == k_wl_sig_hkey) return ERROR_SUCCESS;
return o_RegCloseKey ? o_RegCloseKey(hKey) : ERROR_SUCCESS;
}
static FARPROC WINAPI hk_GetProcAddress(HMODULE hMod, LPCSTR lpProcName) {
FARPROC orig = o_GetProcAddress ? o_GetProcAddress(hMod, lpProcName) : NULL;
if (!orig || wl_in_hook() || !lpProcName || ((uintptr_t)lpProcName < 0x10000u)) return orig;
if (strcmp(lpProcName, "WinVerifyTrust") == 0) {
if (!o_WinVerifyTrust) o_WinVerifyTrust = (PFN_WinVerifyTrust)(void *)orig;
return (FARPROC)(void *)hk_WinVerifyTrust;
}
if (strcmp(lpProcName, "CryptQueryObject") == 0) {
if (!o_CryptQueryObject) o_CryptQueryObject = (PFN_CryptQueryObject)(void *)orig;
return (FARPROC)(void *)hk_CryptQueryObject;
}
if (strcmp(lpProcName, "LoadLibraryW") == 0) return (FARPROC)(void *)hk_LoadLibraryW;
if (strcmp(lpProcName, "LoadLibraryA") == 0) return (FARPROC)(void *)hk_LoadLibraryA;
if (strcmp(lpProcName, "LoadLibraryExW") == 0) return (FARPROC)(void *)hk_LoadLibraryExW;
if (strcmp(lpProcName, "LoadLibraryExA") == 0) return (FARPROC)(void *)hk_LoadLibraryExA;
if (strcmp(lpProcName, "GetFileAttributesW") == 0) return (FARPROC)(void *)hk_GetFileAttributesW;
if (strcmp(lpProcName, "GetFileAttributesExW") == 0) return (FARPROC)(void *)hk_GetFileAttributesExW;
if (strcmp(lpProcName, "CreateFileW") == 0) return (FARPROC)(void *)hk_CreateFileW;
if (strcmp(lpProcName, "RegOpenKeyExW") == 0) return (FARPROC)(void *)hk_RegOpenKeyExW;
if (strcmp(lpProcName, "RegEnumValueW") == 0) return (FARPROC)(void *)hk_RegEnumValueW;
if (strcmp(lpProcName, "RegQueryValueExW") == 0) return (FARPROC)(void *)hk_RegQueryValueExW;
if (strcmp(lpProcName, "RegCloseKey") == 0) return (FARPROC)(void *)hk_RegCloseKey;
return orig;
}
static int wl_should_skip_module(HMODULE mod) {
if (!mod || mod == g_wl_self_mod || mod == g_wl_our_nvngx) return 1;
WCHAR path[MAX_PATH] = {0};
DWORD n = GetModuleFileNameW(mod, path, MAX_PATH);
if (n == 0) return 1;
const WCHAR *base = wl_basename_w(path);
// Never patch core OS / Wine system DLLs to prevent recursion or loader side-effects
if (_wcsicmp(base, L"ntdll.dll") == 0 ||
_wcsicmp(base, L"kernel32.dll") == 0 ||
_wcsicmp(base, L"kernelbase.dll") == 0 ||
_wcsicmp(base, L"advapi32.dll") == 0 ||
_wcsicmp(base, L"sechost.dll") == 0 ||
_wcsicmp(base, L"wintrust.dll") == 0 ||
_wcsicmp(base, L"crypt32.dll") == 0 ||
_wcsicmp(base, L"ucrtbase.dll") == 0 ||
_wcsicmp(base, L"msvcrt.dll") == 0 ||
_wcsicmp(base, L"nvapi64.dll") == 0 ||
_wcsicmp(base, L"_nvngx.dll") == 0 ||
_wcsicmp(base, L"nvngx.dll") == 0 ||
_wcsicmp(base, L"dxgi.dll") == 0 ||
_wcsicmp(base, L"d3d12.dll") == 0 ||
_wcsicmp(base, L"d3d12core.dll") == 0 ||
_wcsicmp(base, L"d3d11.dll") == 0 ||
_wcsicmp(base, L"vulkan-1.dll") == 0 ||
_wcsicmp(base, L"winevulkan.dll") == 0) {
return 1;
}
return 0;
}
static void *wl_hook_for_import(const char *funcName) {
if (!funcName) return NULL;
if (strcmp(funcName, "LoadLibraryW") == 0) return (void *)hk_LoadLibraryW;
if (strcmp(funcName, "LoadLibraryA") == 0) return (void *)hk_LoadLibraryA;
if (strcmp(funcName, "LoadLibraryExW") == 0) return (void *)hk_LoadLibraryExW;
if (strcmp(funcName, "LoadLibraryExA") == 0) return (void *)hk_LoadLibraryExA;
if (strcmp(funcName, "GetProcAddress") == 0) return (void *)hk_GetProcAddress;
if (strcmp(funcName, "GetFileAttributesW") == 0) return (void *)hk_GetFileAttributesW;
if (strcmp(funcName, "GetFileAttributesExW") == 0) return (void *)hk_GetFileAttributesExW;
if (strcmp(funcName, "CreateFileW") == 0) return (void *)hk_CreateFileW;
if (strcmp(funcName, "WinVerifyTrust") == 0) return (void *)hk_WinVerifyTrust;
if (strcmp(funcName, "CryptQueryObject") == 0) return (void *)hk_CryptQueryObject;
if (strcmp(funcName, "RegOpenKeyExW") == 0) return (void *)hk_RegOpenKeyExW;
if (strcmp(funcName, "RegEnumValueW") == 0) return (void *)hk_RegEnumValueW;
if (strcmp(funcName, "RegQueryValueExW") == 0) return (void *)hk_RegQueryValueExW;
if (strcmp(funcName, "RegCloseKey") == 0) return (void *)hk_RegCloseKey;
return NULL;
}
static void wl_patch_module_iat(HMODULE mod) {
if (wl_should_skip_module(mod)) return;
uint8_t *base = (uint8_t *)mod;
IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)base;
if (IsBadReadPtr(dos, sizeof *dos) || dos->e_magic != IMAGE_DOS_SIGNATURE) return;
IMAGE_NT_HEADERS *nt = (IMAGE_NT_HEADERS *)(base + dos->e_lfanew);
if (IsBadReadPtr(nt, sizeof *nt) || nt->Signature != IMAGE_NT_SIGNATURE) return;
IMAGE_DATA_DIRECTORY impDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
if (!impDir.VirtualAddress || !impDir.Size) return;
IMAGE_IMPORT_DESCRIPTOR *desc = (IMAGE_IMPORT_DESCRIPTOR *)(base + impDir.VirtualAddress);
for (; !IsBadReadPtr(desc, sizeof *desc) && desc->Name != 0; desc++) {
if (!desc->OriginalFirstThunk || !desc->FirstThunk) continue;
IMAGE_THUNK_DATA *origThunk = (IMAGE_THUNK_DATA *)(base + desc->OriginalFirstThunk);
IMAGE_THUNK_DATA *iatThunk = (IMAGE_THUNK_DATA *)(base + desc->FirstThunk);
for (; origThunk->u1.AddressOfData != 0; origThunk++, iatThunk++) {
if (IMAGE_SNAP_BY_ORDINAL(origThunk->u1.Ordinal)) continue;
IMAGE_IMPORT_BY_NAME *ibn = (IMAGE_IMPORT_BY_NAME *)(base + origThunk->u1.AddressOfData);
void *hookFn = wl_hook_for_import((const char *)ibn->Name);
if (!hookFn) continue;
void **slot = (void **)&iatThunk->u1.Function;
if (*slot == hookFn) continue;
DWORD oldProt = 0;
if (VirtualProtect(slot, sizeof(void *), PAGE_READWRITE, &oldProt)) {
*slot = hookFn;
VirtualProtect(slot, sizeof(void *), oldProt, &oldProt);
}
}
}
}
static int wl_is_arxan_protected_exe(void) {
WCHAR exePath[MAX_PATH] = {0};
if (!GetModuleFileNameW(NULL, exePath, MAX_PATH)) return 0;
const WCHAR *base = wl_basename_w(exePath);
return _wcsicmp(base, L"rdr2.exe") == 0 ||
_wcsicmp(base, L"playrdr2.exe") == 0 ||
_wcsicmp(base, L"gta5.exe") == 0;
}
static void wl_install_ngx_hooks_once(void) {
if (InterlockedCompareExchange(&g_wl_hooks_installed, 1, 0) != 0) return;
if (!dd_env_is_on("DROIDDECK_UPSCALE_SIGFIX")) return;
if (!g_wl_hook_cs_ready) { InitializeCriticalSection(&g_wl_hook_cs); g_wl_hook_cs_ready = 1; }
g_wl_tls_reent = TlsAlloc();
// RDR2 uses Arxan anti-tamper which terminates the game right after the loading screen
// if its executable .text or IAT is modified. Rely cleanly on NGXCore registry keys +
// EnableSignatureOverride ({41FCC608-...}=01) without touching RDR2.exe memory!
if (wl_is_arxan_protected_exe()) {
wl_hook_log("[nvapi] Arxan-protected game detected (RDR2) — skipping IAT/.text patching");
return;
}
HMODULE hK32 = GetModuleHandleA("kernel32.dll");
HMODULE hAdv = GetModuleHandleA("advapi32.dll");
if (!hAdv) hAdv = LoadLibraryA("advapi32.dll");
HMODULE hWt = GetModuleHandleA("wintrust.dll");
HMODULE hCr = GetModuleHandleA("crypt32.dll");
if (hK32) {
o_LoadLibraryW = (PFN_LoadLibraryW)(void *)GetProcAddress(hK32, "LoadLibraryW");
o_LoadLibraryA = (PFN_LoadLibraryA)(void *)GetProcAddress(hK32, "LoadLibraryA");
o_LoadLibraryExW = (PFN_LoadLibraryExW)(void *)GetProcAddress(hK32, "LoadLibraryExW");
o_LoadLibraryExA = (PFN_LoadLibraryExA)(void *)GetProcAddress(hK32, "LoadLibraryExA");
o_GetProcAddress = (PFN_GetProcAddress)(void *)GetProcAddress(hK32, "GetProcAddress");
o_GetFileAttributesW = (PFN_GetFileAttributesW)(void *)GetProcAddress(hK32, "GetFileAttributesW");
o_GetFileAttributesExW = (PFN_GetFileAttributesExW)(void *)GetProcAddress(hK32, "GetFileAttributesExW");
o_CreateFileW = (PFN_CreateFileW)(void *)GetProcAddress(hK32, "CreateFileW");
}
if (hAdv) {
o_RegOpenKeyExW = (PFN_RegOpenKeyExW)(void *)GetProcAddress(hAdv, "RegOpenKeyExW");
o_RegEnumValueW = (PFN_RegEnumValueW)(void *)GetProcAddress(hAdv, "RegEnumValueW");
o_RegQueryValueExW = (PFN_RegQueryValueExW)(void *)GetProcAddress(hAdv, "RegQueryValueExW");
o_RegCloseKey = (PFN_RegCloseKey)(void *)GetProcAddress(hAdv, "RegCloseKey");
}
if (hWt) o_WinVerifyTrust = (PFN_WinVerifyTrust)(void *)GetProcAddress(hWt, "WinVerifyTrust");
if (hCr) o_CryptQueryObject = (PFN_CryptQueryObject)(void *)GetProcAddress(hCr, "CryptQueryObject");
wl_enter_hook();
wl_find_signed_nv_dll();
int patched = 0;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
if (snap != INVALID_HANDLE_VALUE) {
MODULEENTRY32W me;
memset(&me, 0, sizeof me);
me.dwSize = sizeof me;
if (Module32FirstW(snap, &me)) {
do {
if (!wl_should_skip_module(me.hModule)) {
wl_patch_module_iat(me.hModule);
patched++;
}
} while (Module32NextW(snap, &me));
}
CloseHandle(snap);
} else {
wl_patch_module_iat(GetModuleHandleW(NULL));
patched = 1;
}
wl_leave_hook();
char buf[128];
snprintf(buf, sizeof buf, "[nvapi] Installed ARM64EC-safe NGX IAT hooks on %d modules", patched);
wl_hook_log(buf);
}
-576
View File
@@ -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;
}
-444
View File
@@ -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(&reg, 0, sizeof reg);
reg.srcSubresource.aspectMask = 1u;
reg.srcSubresource.layerCount = 1u;
reg.srcOffsets[1].x = (int32_t)rw;
reg.srcOffsets[1].y = (int32_t)rh;
reg.srcOffsets[1].z = 1;
reg.dstSubresource.aspectMask = 1u;
reg.dstSubresource.layerCount = 1u;
reg.dstOffsets[1].x = (int32_t)ow;
reg.dstOffsets[1].y = (int32_t)oh;
reg.dstOffsets[1].z = 1;
c->CmdBlitImage(cb, f->color.vk_image, 6u, f->output.vk_image, 7u, 1u, &reg, 1u /* LINEAR */);
WlVkImageMemoryBarrier post[2];
post[0] = pre[0];
post[0].srcAccessMask = 0x00000800u;
post[0].dstAccessMask = 0x00018000u;
post[0].oldLayout = 6u;
post[0].newLayout = src_lay;
post[1] = pre[1];
post[1].srcAccessMask = 0x00001000u;
post[1].dstAccessMask = 0x00018000u;
post[1].oldLayout = 7u;
post[1].newLayout = dst_lay;
c->CmdPipelineBarrier(cb, 0x00001000u /* TRANSFER */, 0x00010000u /* ALL_COMMANDS */, 0, 0, NULL, 0, NULL, 2, post);
return 1;
}
static int wl_seam_dispatch_or_blit(WlSeamClient *c, VkCommandBuffer cb, const WlFsr4FrameDesc *f) {
if (wl_seam_dispatch(c, cb, f)) return 1;
return wl_seam_fallback_blit(c, cb, f);
}
static int wl_seam_parse_backend_env(void) {
static const char *const names[] = {
"DROIDDECK_UPSCALE_BACKEND", "DROIDDECK_UPSCALE_ENGINE",
"WINLATOR_FSR4_BACKEND", "WINLATOR_FSR4_ENGINE", NULL,
};
char buf[64];
if (dd_env_first(names, buf, sizeof buf)) {
if (_stricmp(buf, "fsr3_gpu") == 0 || _stricmp(buf, "fsr3") == 0) return WL_FSR_BACKEND_FSR3_GPU;
if (_stricmp(buf, "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();
}
-32
View File
@@ -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);
}
-100
View File
@@ -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;
}
-486
View File
@@ -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;
}
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff. Show more