feat: Mali Vulkan support through MaliBridge (#1950)

This commit is contained in:
张先生 authored and GitHub committed 2026-11-02 20:16:48 -05:00
1 parent c43a493ad8
commit 1f91283f40
83 files changed
+2331 -80

No files matched your search

@@ -65,7 +65,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
fun state() = GpuDriversState(
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity),
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)),
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
autoStatus = autoStatus, releaseStatus = releaseStatus.ifEmpty { activity.getString(R.string.drivers_not_checked) }, checking = releaseChecking,
@@ -264,7 +264,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
return
}
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity).lowercase())
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
return
}
releaseChecking = true
@@ -163,6 +163,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)
@@ -1076,6 +1080,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,
@@ -1224,6 +1229,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)
@@ -2534,6 +2548,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)
@@ -2570,6 +2587,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)
@@ -2674,7 +2694,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)
}
@@ -2693,7 +2713,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
@@ -208,7 +208,7 @@ object DeviceReport {
h("Drivers")
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText(SessionPrefs.vkBridge(context))}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
if (gpu.model == 740) {
val hint = com.droiddeck.launcher.gpu.TpUbwcHint
k("TP UBWC hint", hint.forThisDevice(context) ?: "driver default")
@@ -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()
}
}
}
@@ -16,7 +16,7 @@ object DeviceInfo {
val vk = VulkanInfo.query()
val gpu = GpuInfo.detect()
return listOf(
chip(), gpu(gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
chip(), gpu(context, gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
).filter { it.rows.isNotEmpty() }
}
@@ -51,7 +51,7 @@ object DeviceInfo {
add("Family", read("/sys/devices/soc0/family"))
})
private fun gpu(gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
private fun gpu(context: Context, gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
add("GPU", gpu.name)
add("Family", gpu.family.label)
add("Model found from", when (gpu.modelSource) {
@@ -66,7 +66,7 @@ object DeviceInfo {
add("Clock range", gpuRange())
add("Load", read("$kgsl/gpu_busy_percentage")?.let { if (it.endsWith("%")) it else "$it %" })
add("Temperature", read("$kgsl/temp")?.toLongOrNull()?.let { if (it > 1000) "${it / 1000} °C" else "$it °C" })
add("Support", gpu.supportText)
add("Support", gpu.supportText(SessionPrefs.vkBridge(context)))
})
private fun cpu() = Section("CPU", buildList<Pair<String, String>> {
@@ -53,6 +53,18 @@ data class GpuInfo(
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
}
fun supportText(bridge: Boolean): String = when {
support != Support.UNSUPPORTED -> supportText
bridge -> "Runs through the Mali bridge, on the phone's own Vulkan driver"
else -> "Not supported with the Mali bridge off: Turnip needs an Adreno (Snapdragon) GPU"
}
fun supportText(context: Context, bridge: Boolean): String = when {
support != Support.UNSUPPORTED -> supportText(context)
bridge -> context.getString(R.string.gpuinfo_bridge)
else -> context.getString(R.string.gpuinfo_bridge_off)
}
fun supportText(context: Context): String = context.getString(when (support) {
Support.TESTED -> R.string.gpuinfo_supported
Support.UNTESTED -> when {
@@ -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
}
@@ -14,6 +14,8 @@ import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.ui.Motion
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
@@ -56,7 +58,10 @@ class DroidDeckHudHost(context: Context) {
if (!gpuName.isNullOrBlank()) handler.post { this@DroidDeckHudHost.gpuName = cleanGpuName(gpuName) }
if (window != null && window != lastWindow) {
lastWindow = window
handler.post { onPresentingWindowChanged?.invoke() }
handler.post {
onPresentingWindowChanged?.invoke()
applyShown()
}
}
}
@@ -174,8 +179,9 @@ class DroidDeckHudHost(context: Context) {
private fun applyShown() {
if (!running) return
val show = !hidden && !backgrounded
view?.visibility = if (show) View.VISIBLE else View.GONE
showing = show
val visible = show && SessionState.mode != SessionService.MODE_DESKTOP
view?.visibility = if (visible) View.VISIBLE else View.GONE
showing = visible
if (show != polling) {
polling = show
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
@@ -208,14 +214,20 @@ class DroidDeckHudHost(context: Context) {
file
}.getOrNull()
private fun sessionResolution(): String {
val (width, height) = SessionState.outputSize
return "${width}x${height}"
}
private fun refreshLabels(hud: DroidDeckHudView) {
if (feed.engine.isNotBlank() && !feed.steamFocused) engine = feed.engine
hud.setEngineLabel(engine)
if (gpuName.isNotBlank()) hud.setGpuModel(gpuName)
hud.setResolution(if (feed.outputWidth > 0 && feed.outputHeight > 0) buildString {
val feedResolution = if (feed.outputWidth > 0 && feed.outputHeight > 0) buildString {
append(feed.outputWidth).append('x').append(feed.outputHeight)
if (feed.refreshMilliHz > 0) append(" @ ").append((feed.refreshMilliHz + 499) / 1000).append("Hz")
} else "")
} else ""
hud.setResolution(feedResolution.ifBlank { sessionResolution() })
val pid = feed.pid
if (pid > 0 && pid != protonPid) {
protonPid = pid
@@ -698,6 +698,9 @@ class DroidDeckHudView(context: Context) : View(context) {
contentW = max(contentW, pad + w + pad)
}
private fun hasGpuStats(s: HudMetrics.Snapshot): Boolean =
s.gpuPercent != null || s.gpuTempC != null || s.gpuClockMhz != null
private fun buildFull(s: HudMetrics.Snapshot) {
val rowPx = sp(12f); val unitPx = rowPx * 0.62f
val pad = sp(10f); val lineGap = sp(4f); val lvGap = sp(8f)
@@ -709,7 +712,7 @@ class DroidDeckHudView(context: Context) : View(context) {
rows.add(HudRow(Span("DISP", colDisp, rowPx), listOf(Span(displayServer, colValue, rowPx))))
if (hdrState != DroidDeckHudHdr.NONE)
rows.add(HudRow(Span("HDR", colHdr, rowPx), hdrValue(rowPx)))
if (showGPU) {
if (showGPU && hasGpuStats(s)) {
val v = ArrayList<Span>()
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
@@ -720,9 +723,9 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showCPU) {
val v = ArrayList<Span>()
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
rows.add(HudRow(Span("CPU", colCpu, rowPx), v))
}
if (showVram && s.vramText() != null)
@@ -799,12 +802,13 @@ class DroidDeckHudView(context: Context) : View(context) {
"${fmt1(fpsAvg)} avg · ${lowText(lows.low1Fps) ?: "—"} 1%", false))
if (showFPS) tiles.add(Tile("FRAME", colDim, numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valPx, unitPx),
"${fmt1(graphMinMs)} – ${fmt1(graphMaxMs)}", false))
if (showGPU) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
if (showGPU && hasGpuStats(s)) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
if (showGpuTemp && s.gpuTempC != null) HudMetrics.formatTemp(s.gpuTempC.toFloat(), tempDisplay, false)
else s.gpuClockMhz?.let { "${it}MHz" }, false))
if (showCPU) tiles.add(Tile("CPU", colCpu, numUnit(s.cpuPercent?.toString(), "%", valPx, unitPx),
listOfNotNull(if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null,
s.cpuClockMhz?.toString()).joinToString(" · ").ifBlank { null }, false))
listOfNotNull(s.cpuClockMhz?.let { "${it}MHz" },
if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null)
.joinToString(" · ").ifBlank { null }, false))
if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false))
if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx),
"${s.ramUsedText()} / ${s.ramTotalText()}", false))
@@ -881,7 +885,7 @@ class DroidDeckHudView(context: Context) : View(context) {
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
run {
val l = ArrayList<Span>()
if (showGPU) { l += Span("GPU ${s.gpuPercent ?: "—"}%", colGpu, stkPx) }
if (showGPU && s.gpuPercent != null) { l += Span("GPU ${s.gpuPercent}%", colGpu, stkPx) }
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
if (l.isNotEmpty()) stack.add(l)
}
@@ -1137,7 +1141,7 @@ class DroidDeckHudView(context: Context) : View(context) {
val left = ArrayList<HudRow>()
if (showGpuModel && gpuNameText().isNotBlank())
left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
if (showGPU) {
if (showGPU && hasGpuStats(s)) {
val v = ArrayList<Span>()
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
@@ -1148,9 +1152,9 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showCPU) {
val v = ArrayList<Span>()
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
left.add(HudRow(Span("CPU", colCpu, rowPx), v))
}
if (showPerCore) {
@@ -1,7 +1,9 @@
package com.droiddeck.launcher.hud
import android.os.Environment
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import kotlin.math.roundToInt
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
class Cpu(val percent: Int, val perCore: IntArray)
@@ -48,6 +50,7 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
}
fun cpuTempC(): Int? {
externalCpuTemp()?.let { return it }
var sum = 0f
var count = 0
for (zone in LinuxRuntime.cpuTempZones()) {
@@ -58,6 +61,13 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return if (count == 0) null else (sum / count).toInt()
}
/** Optional ADB helper feed: /sdcard/DroidDeck/cpu-temp, written from the host while a session runs. */
private fun externalCpuTemp(): Int? {
val file = File(Environment.getExternalStorageDirectory(), "DroidDeck/cpu-temp")
if (!file.isFile || System.currentTimeMillis() - file.lastModified() > CPU_TEMP_FRESH_MS) return null
return readFloat(file)?.takeIf { it.isFinite() && it in -20f..150f }?.roundToInt()
}
fun gpuPercent(): Int? {
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/perf_now"))
val source = feed ?: LinuxRuntime.gpuLoadSource()?.let(::File) ?: return null
@@ -92,7 +102,8 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return Memory((total - available) * 1024, total * 1024, (swapTotal - swapFree) * 1024, swapTotal * 1024)
}
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)
/** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
@@ -132,6 +143,7 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
const val VRAM_FILE = "run/droiddeck-hud/gpu-mem"
private const val FEED_FRESH_MS = 10_000L
private const val VRAM_FRESH_MS = 15_000L
private const val CPU_TEMP_FRESH_MS = 10_000L
private val WHITESPACE = Regex("\\s+")
private fun readLong(file: File): Long? = runCatching { file.readText().trim().toLong() }.getOrNull()
@@ -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()
@@ -251,12 +251,36 @@ class LinuxNetworkLinkComponent(
}
}
private fun localDnsServers(): Pair<List<String>, List<String>> {
val active = connectivity.activeNetwork?.let { connectivity.getNetworkCapabilities(it) }
if (active?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true) return Pair(emptyList(), emptyList())
val servers = LinkedHashSet<String>()
val gateways = LinkedHashSet<String>()
for (network in connectivity.allNetworks) {
val capabilities = connectivity.getNetworkCapabilities(network) ?: continue
if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) continue
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) continue
val link = connectivity.getLinkProperties(network) ?: continue
for (address in link.dnsServers) {
if (address.isLinkLocalAddress || address.isLoopbackAddress || address.isAnyLocalAddress) continue
address.hostAddress?.substringBefore('%')?.let { servers.add(it) }
}
link.routes.firstOrNull {
it.isDefaultRoute && (it.gateway as? Inet4Address)?.let { g -> !g.isLoopbackAddress && !g.isAnyLocalAddress } == true
}?.gateway?.hostAddress?.substringBefore('%')?.let { gateways.add(it) }
}
val order = compareBy<String>({ if (it.contains(':')) 1 else 0 })
return Pair(servers.sortedWith(order), gateways.sortedWith(order))
}
private fun writeResolver(properties: LinkProperties?) {
val own = properties?.dnsServers.orEmpty()
.filter { !it.isLinkLocalAddress && !it.isLoopbackAddress && !it.isAnyLocalAddress }
.sortedBy { if (it is Inet4Address) 0 else 1 }
.mapNotNull { it.hostAddress?.substringBefore('%') }
val servers = (own + listOf("8.8.8.8", "1.1.1.1", "2001:4860:4860::8888")).distinct().take(6)
val (discovered, gateways) = localDnsServers()
val servers = (own + discovered + listOf("8.8.8.8", "1.1.1.1", "2001:4860:4860::8888") + gateways).distinct().take(6)
val text = buildString {
append("# Written by the app from the device's active network; edits are overwritten.\n")
for (server in servers) append("nameserver $server\n")
@@ -278,10 +278,42 @@ public final class LinuxRuntime {
return false;
}
static final String MALI_DEVICE = "/dev/mali0";
static final String[] DRM_RENDER_NODES = {
"/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/renderD130", "/dev/dri/renderD131",
};
public static String gpuStandIn(Context context) {
if (new File(KGSL_DEVICE).exists()) return KGSL_DEVICE;
if (!com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) return null;
return bridgeStandIn(path -> new File(path).exists());
}
static String bridgeStandIn(java.util.function.Predicate<String> exists) {
if (exists.test(MALI_DEVICE)) return MALI_DEVICE;
for (String node : DRM_RENDER_NODES) if (exists.test(node)) return node;
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;
}
@@ -301,13 +333,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) {
@@ -315,7 +348,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
@@ -638,29 +639,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}")
}
@@ -708,7 +711,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) }
@@ -1011,15 +1014,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,
@@ -1027,16 +1091,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)
@@ -1044,9 +1127,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(
@@ -171,6 +171,9 @@ object SessionFiles {
val optional = (arrayOf(
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
"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",
@@ -746,6 +746,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()
}
@@ -523,6 +523,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)
@@ -812,7 +813,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)
@@ -867,6 +868,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,
@@ -171,7 +171,7 @@ internal fun SetupPanel(
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val gpu = remember { com.droiddeck.launcher.gpu.GpuInfo.detect() }
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED || s.vkBridge
val gpuName = remember { DeviceSupport.gpuName(ctx) }
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val signedIn = s.offlineAccount != null
@@ -232,7 +232,7 @@ internal fun SetupPanel(
val runtimeOk = s.ready && !s.busy && !s.removalPending
val checks = listOf(gpuOk, runtimeOk, !limitBlocks, signedIn)
val passing = checks.count { it }
var showChecks by rememberSaveable { mutableStateOf(false) }
var showChecks by rememberSaveable { mutableStateOf(s.vkBridge) }
Rise(0, Modifier.fillMaxSize()) {
Column(
modifier = Modifier.fillMaxSize().bumpers(
@@ -249,17 +249,49 @@ internal fun SetupPanel(
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
CheckRow(
if (gpuOk) CheckState.OK else CheckState.WARN,
when (gpu.support) {
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_supported)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested)
when {
gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_supported)
gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested)
s.vkBridge -> stringResource(R.string.setup_gpu_bridged)
else -> stringResource(R.string.setup_gpu_unsupported)
},
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 ->