Merge MaliBridge integration (feat/malibridge) into 0.6.7

This commit is contained in:
DroidDeck Merge committed 2026-10-31 19:01:40 +08:00
commit d4a6d95127
72 files changed
+1972 -52

No files matched your search

@@ -162,6 +162,10 @@ class FrontEndActivity : ComponentActivity() {
private var gameCores by mutableStateOf<Set<Int>>(emptySet())
private var tuSysmem by mutableStateOf(false)
private var zinkLazy by mutableStateOf(false)
private var vkBridge by mutableStateOf(false)
private var vkBridgeSafe by mutableStateOf(true)
private var bridgeProtonDxvk by mutableStateOf(false)
private val adrenoGpu by lazy { com.droiddeck.launcher.core.DeviceSupport.adreno() }
private var noXalia by mutableStateOf(true)
private var fastSync by mutableStateOf(false)
private var syncFallback by mutableStateOf(true)
@@ -1040,6 +1044,7 @@ class FrontEndActivity : ComponentActivity() {
FrontEndScreen(
FrontEndState(
installed = installed, ready = ready, available = available?.version, removalPending = removalPending, runtimeActionsBlocked = runtimeChangesBlocked(),
vkBridge = vkBridge, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
shortcutPicker = shortcutPicker,
shortcutLibraryScanning = shortcutLibraryScanning,
gameSyncFolder = gameSyncFolder,
@@ -1188,6 +1193,15 @@ class FrontEndActivity : ComponentActivity() {
onInstallPackage = { id -> installPackage(id) },
onRemovePackage = { id -> removePackage(id) },
onRuntime = { onRuntimeButton() },
onVkBridge = { on ->
SessionPrefs.setVkBridge(this, on); vkBridge = on
if (!on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
},
onVkBridgeSafe = { on -> SessionPrefs.setVkBridgeSafe(this, on); vkBridgeSafe = on },
onBridgeProtonDxvk = { on ->
SessionPrefs.setBridgeProtonDxvk(this, on); bridgeProtonDxvk = on
if (on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
},
onFrameGenPick = { mode ->
FrameGen.set(this, mode)
frameGenLabel = FrameGen.label(this)
@@ -2450,6 +2464,9 @@ class FrontEndActivity : ComponentActivity() {
gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() }
tuSysmem = SessionPrefs.tuSysmem(this)
zinkLazy = SessionPrefs.zinkLazy(this)
vkBridge = SessionPrefs.vkBridge(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
noXalia = SessionPrefs.noXalia(this)
fastSync = SessionPrefs.fastSync(this)
syncFallback = SessionPrefs.syncFallback(this)
@@ -2487,6 +2504,9 @@ class FrontEndActivity : ComponentActivity() {
offline = OfflineMode.enabled(this)
installed = LinuxRuntimeInstaller.installedVersion(this)
ready = LinuxRuntime.isInstalled(this)
vkBridge = SessionPrefs.vkBridge(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
ui.post { autoUpdateRuntime() }
frameGenLabel = FrameGen.label(this)
@@ -2591,7 +2611,7 @@ class FrontEndActivity : ComponentActivity() {
Thread({ checkCatalog() }, "catalog").start()
return
}
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()) { showNonAdreno = release; return }
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)) { showNonAdreno = release; return }
install(release)
}
@@ -2610,7 +2630,7 @@ class FrontEndActivity : ComponentActivity() {
showPhantomGate = true
return false
}
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)
if (warn && available != null) { showNonAdreno = available; return false }
startActivity(intent)
return true
@@ -6,8 +6,20 @@ import com.droiddeck.launcher.R
import java.io.File
object DeviceSupport {
fun adreno(): Boolean =
private val adrenoGpu by lazy {
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
}
private val maliGpu by lazy { !adrenoGpu && File("/dev/mali0").exists() }
fun adreno(): Boolean = adrenoGpu
fun mali(): Boolean = maliGpu
fun vkBridge(context: Context): Boolean =
!adreno() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
fun canDraw(context: Context): Boolean = adreno() || vkBridge(context)
fun gpuName(context: Context): String {
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
@@ -0,0 +1,73 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.FileUtils
import java.io.File
data class AppVulkan(
val major: Int,
val minor: Int,
val shaderInt64: Boolean?,
val maxPushConstants: Int?,
val source: String,
) {
fun atLeast(major: Int, minor: Int): Boolean = this.major > major || (this.major == major && this.minor >= minor)
val label: String
get() = "Vulkan $major.$minor, shaderInt64 ${shaderInt64?.let { if (it) "yes" else "no" } ?: "?"}, " +
"push constants ${maxPushConstants ?: "?"} ($source)"
companion object {
private const val TAG = "AppVulkan"
const val BRIDGE_FILE = "apps-vulkan"
fun detect(context: Context): AppVulkan? {
if (!DeviceSupport.vkBridge(context)) return null
val native = VulkanInfo.query()
val file = File(VkBridgeComponent.cacheDir(context), BRIDGE_FILE)
val fromBridge = FileUtils.readString(file)?.let { fromBridgeFile(it, native["device"], native["api"]) }
val found = fromBridge ?: fromDriver(native)
Log.i(TAG, found?.label ?: "unknown (driver query: ${native["error"] ?: "no api line"})")
return found
}
internal fun fromBridgeFile(text: String, driverDevice: String?, driverApi: String? = null): AppVulkan? {
val map = keyValues(text)
val device = map["device"]
if (device != null && driverDevice != null && device != driverDevice) return null
val fileDriver = version(map["driver_api"])
val native = version(driverApi)
if (fileDriver != null && native != null && fileDriver != native) return null
val promoted = map["promotion"]?.trim()?.lowercase() == "on"
val (major, minor) = (if (promoted) version(map["api"]) else fileDriver ?: version(map["api"])) ?: return null
return AppVulkan(major, minor, bool(map["shader_int64"]), map["max_push_constants"]?.toIntOrNull(),
if (promoted) "bridge, promoted" else "bridge")
}
internal fun fromDriver(map: Map<String, String>): AppVulkan? {
val (major, minor) = version(map["api"]) ?: return null
return AppVulkan(major, minor, bool(map["shader_int64"]), map["max_push_constants"]?.toIntOrNull(), "driver")
}
private fun keyValues(text: String): Map<String, String> = 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()
private fun version(v: String?): Pair<Int, Int>? {
val parts = v?.trim()?.split('.') ?: return null
if (parts.size < 2) return null
val major = parts[0].toIntOrNull() ?: return null
val minor = parts[1].toIntOrNull() ?: return null
return major to minor
}
private fun bool(v: String?): Boolean? = when (v?.trim()?.lowercase()) {
"1", "yes", "true" -> true
"0", "no", "false" -> false
else -> null
}
}
}
@@ -0,0 +1,108 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.os.Build
import android.os.PowerManager
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class ClockLogComponent(private val logFile: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
override fun start() {
running = true
thread = Thread({ run() }, "clock-log").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
}
private fun run() {
val policies = File("/sys/devices/system/cpu/cpufreq").listFiles { f -> f.name.startsWith("policy") }
?.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 } ?: emptyList()
val gpuCandidates = gpuSources()
val gpu = gpuCandidates.firstOrNull { !it.startsWith("/proc/") && firstNumber(it) != null }
val power = app().getSystemService(Context.POWER_SERVICE) as? PowerManager
val time = SimpleDateFormat("HH:mm:ss", Locale.US)
try {
FileWriter(logFile, true).use { w ->
w.write("== clocks: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.HARDWARE}), every ${PERIOD_MS / 1000}s\n")
w.write("cpu policies: ${policies.joinToString { p -> p.name + " " + (File(p, "related_cpus").readTextOrNull()?.trim() ?: "?") }}\n")
for (source in gpuCandidates) {
val f = File(source)
val state = when {
!f.exists() -> continue
firstNumber(source) != null -> "readable"
else -> "refused"
}
w.write("gpu source $source: $state\n")
}
w.write("gpu clock from: ${gpu ?: "nothing readable"}\n")
w.flush()
while (running && logFile.length() < MAX_BYTES) {
val line = StringBuilder(time.format(Date()))
for (p in policies) {
val cur = firstNumber(File(p, "scaling_cur_freq").path)
val max = firstNumber(File(p, "scaling_max_freq").path)
val hw = firstNumber(File(p, "cpuinfo_max_freq").path)
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
}
gpu?.let { line.append(" | gpu ${mhz(firstNumber(it))} MHz") }
if (power != null && Build.VERSION.SDK_INT >= 29) {
line.append(" | thermal ${power.currentThermalStatus}")
if (Build.VERSION.SDK_INT >= 30) {
val h = power.getThermalHeadroom(10)
if (!h.isNaN()) line.append(String.format(Locale.US, " headroom %.2f", h))
}
}
w.write(line.append('\n').toString())
w.flush()
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
}
}
} catch (e: Exception) {
Log.w(TAG, "clock log stopped: $e")
}
}
companion object {
private const val TAG = "SessionService"
private const val PERIOD_MS = 2000L
private const val MAX_BYTES = 4L shl 20
private fun gpuSources(): List<String> {
val list = mutableListOf(
"/sys/kernel/ged/hal/current_freqency", "/sys/kernel/ged/hal/current_frequency",
"/proc/gpufreqv2/gpufreq_status", "/proc/gpufreq/gpufreq_var_dump",
"/sys/kernel/gpu/gpu_clock", "/sys/class/misc/mali0/device/cur_freq",
"/sys/class/misc/mali0/device/clock",
)
File("/sys/class/devfreq").list()?.sorted()?.forEach { node ->
if (node.contains("mali", true) || node.contains("gpu", true)) list.add("/sys/class/devfreq/$node/cur_freq")
}
return list.distinct()
}
private fun File.readTextOrNull(): String? = runCatching { readText() }.getOrNull()
private fun firstNumber(path: String): Long? =
runCatching { Regex("\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
private fun mhz(raw: Long?): String = when {
raw == null -> "?"
raw > 10_000_000 -> (raw / 1_000_000).toString()
raw > 10_000 -> (raw / 1_000).toString()
else -> raw.toString()
}
}
}
@@ -291,6 +291,10 @@ public final class TurnipDriver {
}
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
if (quest != null) return quest;
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) {
Log.i(TAG, "Mali bridge: the compositor uses the system Vulkan driver");
return null;
}
GpuInfo gpu = gpuDetector.get();
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO) {
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
@@ -0,0 +1,102 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.core.SessionPart
import java.io.File
class VkBridgeComponent(private val socket: File, private val logFile: File) : SessionPart() {
@Volatile private var pid = -1
@Volatile private var exited = false
override fun start() {
stop()
val binary = File(app().applicationInfo.nativeLibraryDir, BINARY)
if (!binary.isFile) {
Log.e(TAG, "server missing at $binary; the session will have no Vulkan")
return
}
socket.parentFile?.mkdirs()
val cacheDir = cacheDir(app())
writeMode(cacheDir, com.droiddeck.launcher.session.SessionPrefs.vkBridgeMode(app()))
if (VkBridgeNative.start(app(), socket, logFile, cacheDir)) {
Log.i(TAG, "server ready in the app's process at $socket")
return
}
socket.delete()
exited = false
val cmd = listOf(binary.absolutePath, "--socket", socket.absolutePath, "--log", logFile.absolutePath,
"--cache-dir", cacheDir.absolutePath)
.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
val env = arrayOf("HOME=" + app().filesDir)
pid = HostProcess.start(cmd, env, app().filesDir, { status ->
exited = true
Log.w(TAG, "server exited with status $status")
runCatching { logFile.appendText("== vkbridge server exited with status $status\n") }
}, { line -> Log.i(TAG, line) })
val began = System.currentTimeMillis()
val deadline = began + 15_000L
while (!socket.exists() && !exited && System.currentTimeMillis() < deadline) {
try { Thread.sleep(50L) } catch (e: InterruptedException) { Thread.currentThread().interrupt(); break }
}
val waited = System.currentTimeMillis() - began
Log.i(TAG, if (socket.exists()) "server ready (pid $pid) at $socket after $waited ms"
else "server NOT ready (pid $pid, exited=$exited) after $waited ms; see $logFile")
if (!socket.exists() && VkBridgeNative.start(app(), socket, logFile, cacheDir)) Log.i(TAG, "server ready in the app's process at $socket")
}
override fun stop() {
if (pid > 0) {
Process.killProcess(pid)
pid = -1
}
if (!VkBridgeNative.serving) socket.delete()
}
override fun suspendPid(): Int = pid
companion object {
private const val TAG = "VkBridge"
private const val CACHE_DIR = "vkbridge-pipelines"
private const val MODE_FILE = "mode"
fun cacheDir(context: Context): File {
val dir = File(context.filesDir, CACHE_DIR)
val old = File(context.cacheDir, CACHE_DIR)
if (old.isDirectory) migrate(old, dir)
dir.mkdirs()
return dir
}
fun writeMode(dir: File, mode: String) {
val file = File(dir, MODE_FILE)
if (runCatching { file.readText().trim() }.getOrNull() == mode) return
val tmp = File(dir, "$MODE_FILE.tmp")
runCatching {
tmp.writeText(mode + "\n")
if (!tmp.renameTo(file)) error("rename failed")
Log.i(TAG, "bridge mode: $mode")
}.onFailure { Log.w(TAG, "could not write $file: $it"); tmp.delete() }
}
private fun migrate(old: File, dir: File) {
val moved = if (!dir.exists()) old.renameTo(dir) else false
if (!moved) {
dir.mkdirs()
old.listFiles()?.forEach { f ->
val to = File(dir, f.name)
if (to.exists()) return@forEach
if (!f.renameTo(to)) runCatching { f.copyRecursively(to, overwrite = false) }
}
old.deleteRecursively()
}
Log.i(TAG, "bridge cache moved from $old to $dir")
}
const val BINARY = "libvkbridge_server.so"
const val GUEST_ICD = "/usr/local/share/vkbridge/droidbridge_icd.json"
const val GUEST_LIB = "/usr/local/lib/vkbridge/libvulkan_droidbridge.so"
}
}
@@ -0,0 +1,49 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.content.pm.ApplicationInfo
import android.util.Log
import java.io.File
object VkBridgeNative {
private const val TAG = "VkBridge"
@Volatile private var loaded: Boolean? = null
private fun load(context: Context): Boolean {
loaded?.let { return it }
val ok = try {
val dev = File(context.filesDir, "vkbridge/dev/libvkbridge_jni.so")
val debuggable = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
if (debuggable && dev.isFile) {
Log.w(TAG, "in-app server from the development override $dev")
System.load(dev.absolutePath)
} else {
System.loadLibrary("vkbridge_jni")
}
true
} catch (e: Throwable) {
Log.w(TAG, "in-app server unavailable: $e")
false
}
loaded = ok
return ok
}
@Volatile var serving = false
private set
fun start(context: Context, socket: File, log: File, cacheDir: File): Boolean {
if (!load(context)) return false
val ok = try {
nativeStart(socket.absolutePath, log.absolutePath, cacheDir.absolutePath) == 1
} catch (e: Throwable) {
Log.w(TAG, "in-app server failed to start: $e")
false
}
if (ok) serving = true
return ok
}
@JvmStatic private external fun nativeStart(socket: String, log: String, cacheDir: String): Int
}
@@ -200,6 +200,7 @@ object BwrapSpawner {
LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() }
private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
if (driver == null || !File("/dev/kgsl-3d0").exists()) return null
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
@@ -222,6 +223,28 @@ object BwrapSpawner {
return binds
}
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<Bind>? {
val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so")
if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null }
val binds = ArrayList<Bind>()
binds.add(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_droidbridge.so"))
val sockDir = File(socket).parent ?: return null
binds.add(Bind(sockDir, sockDir))
val icd = File(root.parentFile, "vkbridge_icd.json")
val api = runCatching {
JSONObject(File(rootfs, "usr/local/share/vkbridge/droidbridge_icd.json").readText()).getJSONObject("ICD").getString("api_version")
}.getOrNull() ?: run { Log.w(TAG, "gpu: vkbridge session but the runtime's bridge manifest is unreadable"); return null }
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"$api\"}}\n")
binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json"))
env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json"
env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json"
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
env["MESA_LOADER_DRIVER_OVERRIDE"] = "zink"
env["GALLIUM_DRIVER"] = "zink"
}
return binds
}
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()
@@ -284,10 +284,32 @@ public final class LinuxRuntime {
return false;
}
private static final String MALI_DEVICE = "/dev/mali0";
public static String gpuStandIn(Context context) {
if (new File(KGSL_DEVICE).exists()) return KGSL_DEVICE;
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context) && new File(MALI_DEVICE).exists()) return MALI_DEVICE;
return null;
}
public static String deviceNumbers(String path) {
try {
long dev = Os.stat(path).st_rdev;
long major = ((dev >> 8) & 0xfff) | ((dev >> 32) & ~0xfffL);
long minor = (dev & 0xff) | ((dev >> 12) & ~0xffL);
return major + ":" + minor;
} catch (ErrnoException e) {
return null;
}
}
private static void bindGpuNode(Context context, List<String> cmd) {
String standIn = gpuStandIn(context);
if (standIn == null) return;
boolean kgsl = standIn.equals(KGSL_DEVICE);
StructStat st;
try {
st = Os.stat(KGSL_DEVICE);
st = Os.stat(standIn);
} catch (ErrnoException e) {
return;
}
@@ -307,13 +329,14 @@ public final class LinuxRuntime {
Files.write(new File(drm, "dev").toPath(),
(major + ":" + minor + "\n").getBytes(StandardCharsets.UTF_8));
Files.write(new File(device, "uevent").toPath(),
"DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n".getBytes(StandardCharsets.UTF_8));
(kgsl ? "DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n" : "DRIVER=mali\nMODALIAS=platform:mali\n")
.getBytes(StandardCharsets.UTF_8));
File subsystem = new File(device, "subsystem");
if (!Files.isSymbolicLink(subsystem.toPath())) {
Os.symlink("/sys/bus/platform", subsystem.getPath());
}
File driver = new File(device, "driver");
if (!Files.isSymbolicLink(driver.toPath())) {
if (kgsl && !Files.isSymbolicLink(driver.toPath())) {
Os.symlink("/sys/bus/platform/drivers/msm_drm", driver.getPath());
}
} catch (IOException | ErrnoException e) {
@@ -321,7 +344,7 @@ public final class LinuxRuntime {
}
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
bind(cmd, dri.getPath() + ":/dev/dri");
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
bind(cmd, standIn + ":/dev/dri/" + node);
bindDrmClass(base, cmd, node, major + ":" + minor);
}
@@ -7,6 +7,7 @@ import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.gpu.AppVulkan
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdInputStream
@@ -639,29 +640,31 @@ object ComponentsManager {
}
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
fun swap(context: Context, protonId: String, file: String, auto: Boolean = false): String = synchronized(lock) {
val p = proton(context, protonId)
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
.apply { if (auto) put("auto", true) })
saveState(context, state)
return context.getString(R.string.cmgr_swap_queued, LABEL[info.comp], info.version, p.name)
}
applyPackage(context, p, info, wcp, state)
applyPackage(context, p, info, wcp, state, auto)
state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
saveState(context, state)
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
}
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
ensureOriginal(context, p, info.comp, state)
val hashes = installFiles(context, p.dir, info.comp, wcp)
state.sub("active").sub(p.id).put(info.comp, JSONObject()
.put("file", wcp.name).put("label", info.version).put("protonVersion", p.version)
.put("files", JSONObject(hashes.filterKeys { owned(info.comp, it) } as Map<*, *>))
.put("at", System.currentTimeMillis() / 1000))
.put("at", System.currentTimeMillis() / 1000)
.apply { if (auto) put("auto", true) })
Log.i(TAG, "swapped ${info.comp} ${info.version} into ${p.name} ${p.version}")
}
@@ -709,7 +712,7 @@ object ComponentsManager {
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
} else {
val wcp = File(packagesDir(context), q.optString("file"))
applyPackage(context, p, packageInfo(context, wcp), wcp, state)
applyPackage(context, p, packageInfo(context, wcp), wcp, state, q.optBoolean("auto"))
}
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
@@ -1015,15 +1018,76 @@ object ComponentsManager {
internal fun forcedPackageWanted(activeFile: String?, protonVersionMatches: Boolean): Boolean =
activeFile.isNullOrEmpty() || !protonVersionMatches
internal fun bridgeDxvk(vk: AppVulkan?): ForcedPackage? = when {
vk == null -> null
!vk.atLeast(1, 1) -> null
!vk.atLeast(1, 3) -> ForcedPackage(emptySet(), "dxvk", DXVK_FOR_VULKAN_1_1, "Dxvk-Linux")
vk.shaderInt64 == false || (vk.maxPushConstants ?: 256) < 256 ->
ForcedPackage(emptySet(), "dxvk", DXVK_FOR_VULKAN_1_3_NO_INT64, "Dxvk-Linux")
else -> null
}
internal const val DXVK_FOR_VULKAN_1_1 = "dxvk-1.10.3-linux.wcp"
internal const val DXVK_FOR_VULKAN_1_3_NO_INT64 = "dxvk-2.6.2-linux.wcp"
internal fun autoDxvkUndoWanted(bridgeSession: Boolean, keepProtonDxvk: Boolean, vulkan: AppVulkan?, bridgeRule: ForcedPackage?): Boolean =
!bridgeSession || keepProtonDxvk || (vulkan != null && bridgeRule == null)
private fun dropQueuedAuto(context: Context, installed: List<Proton>) = synchronized(lock) {
val state = loadState(context)
var changed = false
for (p in installed) {
val q = state.optJSONObject("queued")?.optJSONObject(p.id) ?: continue
if (q.optJSONObject("dxvk")?.optBoolean("auto") == true) { q.remove("dxvk"); changed = true }
}
if (changed) saveState(context, state)
}
internal fun autoChoiceStale(entry: JSONObject?, wantedFile: String?): Boolean =
entry != null && entry.optBoolean("auto") && entry.optString("file") != wantedFile
internal fun catalogMatch(items: List<CatalogItem>, file: String, release: String): CatalogItem? =
items.firstOrNull { it.file == file && it.release == release }
fun ensureForcedPackages(context: Context): String? = ensureForcedPackages(
private val forcedLock = Any()
fun ensureForcedPackages(context: Context): String? = synchronized(forcedLock) { ensureForcedPackages(
context, GpuInfo.detect(),
{ file, release -> catalogItem(context, file, release) },
{ download(context, it) {} },
{ id, file -> swap(context, id, file) },
)
vulkan = AppVulkan.detect(context),
bridgeSession = com.droiddeck.launcher.core.DeviceSupport.vkBridge(context),
applyAuto = { id, file -> swap(context, id, file, auto = true) },
undoAuto = { id, comp -> undoAutoChoice(context, id, comp) },
keepProtonDxvk = SessionPrefs.bridgeProtonDxvk(context),
autoPossible = !com.droiddeck.launcher.core.DeviceSupport.adreno(),
) }
fun settleAutoDxvk(context: Context) {
val app = context.applicationContext
Thread({
runCatching { ensureForcedPackages(app) }
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "automatic DXVK", it) }
}, "auto-dxvk").start()
}
internal fun undoAutoChoice(context: Context, protonId: String, comp: String): String = synchronized(lock) {
val p = proton(context, protonId)
val state = loadState(context)
val entry = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
val sameProton = entry?.optString("protonVersion") == p.version
if (sameProton && originalFile(context, p, comp).isFile)
return restore(context, protonId, comp, safeName(p.version))
if (sameProton) {
Log.w(TAG, "${p.name}: its own ${LABEL[comp]} copy is gone; keeping ${entry?.optString("label")}")
return "${LABEL[comp]}: ${p.name} keeps ${entry?.optString("label")} (its own copy is gone)"
}
state.sub("active").optJSONObject(p.id)?.remove(comp)
saveState(context, state)
"${LABEL[comp]}: ${p.name} keeps its own copy"
}
internal fun ensureForcedPackages(
context: Context,
@@ -1031,16 +1095,35 @@ object ComponentsManager {
lookup: (file: String, release: String) -> CatalogItem?,
fetch: (CatalogItem) -> Unit,
apply: (protonId: String, file: String) -> String,
vulkan: AppVulkan? = null,
bridgeSession: Boolean = false,
applyAuto: (protonId: String, file: String) -> String = apply,
undoAuto: (protonId: String, comp: String) -> String = { _, _ -> "" },
keepProtonDxvk: Boolean = false,
autoPossible: Boolean = true,
): String? {
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }
if (rules.isEmpty()) return null
val chooseDxvk = bridgeSession && !keepProtonDxvk
val bridgeRule = if (chooseDxvk) bridgeDxvk(vulkan) else null
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }.map { it to false } + listOfNotNull(bridgeRule?.let { it to true })
if (rules.isEmpty() && !autoPossible) return null
val installed = protons(context)
val lines = mutableListOf<String>()
for (rule in rules) {
fun each(p: Proton, what: () -> String): String =
runCatching(what).getOrElse { e -> Log.w(TAG, "${p.name}: ${e.message}", e); "${p.name}: ${e.message ?: e.javaClass.simpleName}" }
if (autoPossible && autoDxvkUndoWanted(bridgeSession, keepProtonDxvk, vulkan, bridgeRule)) {
dropQueuedAuto(context, installed)
val state = loadState(context)
for (p in installed) {
val entry = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject("dxvk")
if (autoChoiceStale(entry, null)) lines.add(each(p) { undoAuto(p.id, "dxvk") })
}
}
for ((rule, auto) in rules) {
val state = loadState(context)
val targets = installed.filter { p ->
val active = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject(rule.comp)
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version)
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version) ||
(auto && autoChoiceStale(active, rule.file))
}
if (targets.isEmpty()) continue
val missing = missingPackage(context, rule, lookup, fetch)
@@ -1048,9 +1131,10 @@ object ComponentsManager {
lines.add(missing)
continue
}
lines.add(targets.joinToString("; ") { apply(it.id, rule.file) })
if (auto) lines.add("${vulkan?.label}: DXVK ${rule.file}")
lines.add(targets.joinToString("; ") { p -> if (auto) each(p) { applyAuto(p.id, rule.file) } else apply(p.id, rule.file) })
}
return lines.joinToString("; ").ifEmpty { null }
return lines.filter { it.isNotEmpty() }.joinToString("; ").ifEmpty { null }
}
private fun missingPackage(
@@ -167,6 +167,9 @@ object SessionFiles {
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
// The gamescope pack carries its own WSI layer (patch 0117); it replaces the runtime's stock copy.
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
"usr/local/lib/vkbridge/libvulkan_droidbridge.so" to "usr/local/lib/vkbridge/libvulkan_droidbridge.so",
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
"usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke",
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
@@ -694,6 +694,29 @@ object SessionPrefs {
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
@JvmStatic
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", com.droiddeck.launcher.core.DeviceSupport.mali())
fun setVkBridge(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("vkBridge", on).apply()
}
@JvmStatic
fun bridgeProtonDxvk(context: Context): Boolean = prefs(context).getBoolean("bridgeProtonDxvk", false)
fun setBridgeProtonDxvk(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("bridgeProtonDxvk", on).apply()
}
fun vkBridgeSafe(context: Context): Boolean = prefs(context).getBoolean("vkBridgeSafe", true)
fun setVkBridgeSafe(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("vkBridgeSafe", on).apply()
}
@JvmStatic
fun vkBridgeMode(context: Context): String = if (vkBridgeSafe(context)) "safe" else "performance"
fun setZinkLazy(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zinkLazy", on).apply()
}
@@ -522,6 +522,7 @@ class SessionService : Service() {
components.add(encoder)
guest.add("BL_VENC_SOCKET=" + encoder.socket.absolutePath)
}
startVkBridge(guest, sessionDir)
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
@@ -780,7 +781,7 @@ class SessionService : Service() {
?: SessionPrefs.androidDriver(this),
linuxDriverId,
)
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
val tuOverride = tuDebugOverride()
val tuDriver = sysmemDriver(linuxDriverId)
@@ -834,6 +835,27 @@ class SessionService : Service() {
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startVkBridge(guest: MutableList<String>, sessionDir: File) {
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) return
val socket = File(filesDir, "vkbridge/server.sock")
val bridge = com.droiddeck.launcher.gpu.VkBridgeComponent(socket, File(sessionDir, "vkbridge-server.log"))
bridge.attach(this)
components.add(bridge)
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "vkbridge-clocks.log")).let {
it.attach(this)
components.add(it)
}
guest.add("BL_VKBRIDGE=1")
guest.add("VKBRIDGE_SOCKET=" + socket.path)
guest.add("VKBRIDGE_CLIENT_LOG=" + File(sessionDir, "vkbridge-client.log").path)
guest.add("VKBRIDGE_MODE=" + SessionPrefs.vkBridgeMode(this))
LinuxRuntime.gpuStandIn(this)?.let { node ->
guest.add("BL_DRM_STANDIN=$node")
LinuxRuntime.deviceNumbers(node)?.let { guest.add("VKBRIDGE_DRM_RENDER=$it") }
}
Log.i(TAG, "vkbridge: on (${com.droiddeck.launcher.core.DeviceSupport.gpuName(this)}, ${SessionPrefs.vkBridgeMode(this)} mode), socket $socket")
}
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
val wantsDirectAudio = directAudioPack &&
(SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
@@ -149,6 +149,10 @@ class FrontEndState(
val oscMode: String = SessionPrefs.OSC_AUTO,
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val adreno: Boolean = true,
val vkBridge: Boolean = false,
val vkBridgeSafe: Boolean = true,
val bridgeProtonDxvk: Boolean = false,
val showPhantomGate: Boolean = false,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
@@ -205,6 +209,9 @@ class FrontEndActions(
val onInstallPackage: (String) -> Unit,
val onRemovePackage: (String) -> Unit,
val onRuntime: () -> Unit,
val onVkBridge: (Boolean) -> Unit = {},
val onVkBridgeSafe: (Boolean) -> Unit = {},
val onBridgeProtonDxvk: (Boolean) -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
val onImportLossless: () -> Unit,
val onProtons: () -> Unit,
@@ -244,9 +244,40 @@ internal fun SetupPanel(
when (gpu.support) {
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_detail, gpu.displayName(ctx), gpuName)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
else -> stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
else -> if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
else stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
},
divider = divider || (!s.adreno && s.vkBridge),
action = if (s.adreno) null else { {
SecondaryButton(
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
)
} },
)
if (!s.adreno && s.vkBridge) CheckRow(
CheckState.OK,
stringResource(R.string.setup_bridge_safe),
stringResource(if (s.vkBridgeSafe) R.string.setup_bridge_safe_on_detail else R.string.setup_bridge_safe_off_detail),
divider = divider,
action = {
SecondaryButton(
stringResource(if (s.vkBridgeSafe) R.string.setup_bridge_safe_on else R.string.setup_bridge_safe_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridgeSafe(!s.vkBridgeSafe) },
)
},
)
if (!s.adreno && s.vkBridge) CheckRow(
CheckState.OK,
stringResource(R.string.setup_bridge_dxvk),
stringResource(if (s.bridgeProtonDxvk) R.string.setup_bridge_dxvk_proton_detail else R.string.setup_bridge_dxvk_auto_detail),
divider = divider,
action = {
SecondaryButton(
stringResource(if (s.bridgeProtonDxvk) R.string.setup_bridge_dxvk_proton else R.string.setup_bridge_dxvk_auto),
enabled = !s.sessionRunning, compact = true, onClick = { a.onBridgeProtonDxvk(!s.bridgeProtonDxvk) },
)
},
)
}
val runtimeCheck: @Composable (Boolean) -> Unit = { divider ->