Feat:Add per-game frame generation profiles (#2473)

This commit is contained in:
LunaDL authored and GitHub committed 2026-11-12 14:36:55 -05:00
1 parent b1b6ab7931
commit b52ce7e4c5
46 files changed
+598 -43

No files matched your search

@@ -452,6 +452,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var drawerDefaultProton by mutableStateOf<String?>(null)
private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) }
private var drawerGameProfileId by mutableStateOf<Long?>(null)
private var drawerGameProfileSelectionMade = false
private var fpsLimit by mutableStateOf(SessionState.fpsLimit)
private fun noSteamSession(): Boolean = (SessionState.mode == SessionService.MODE_RUN &&
@@ -460,7 +461,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET,
)) || SessionState.mode == SessionService.MODE_DESKTOP
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
private var drawerGameInventoryRevision = 0L
@Volatile private var drawerGameInventoryRevision = 0L
private var drawerGameFexPresetSaving by mutableStateOf(false)
private var drawerGameNoSteamSaving by mutableStateOf(false)
private val drawerGameProfileFollowState = GameProfileFollowState()
@@ -556,8 +557,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
private var frameGenActiveGameId by mutableStateOf<Long?>(null)
private var frameGenActiveGameName by mutableStateOf<String?>(null)
private var frameGenHasGameOverride by mutableStateOf(false)
private var frameGenPip = false
private val frameGenRequests = java.util.concurrent.atomic.AtomicInteger()
private val frameGenActivityGeneration = synchronized(frameGenGlobalLock) {
frameGenGlobalGeneration.incrementAndGet()
}
@Volatile private var frameGenActivityActive = true
private val frameGenForcePending = java.util.concurrent.atomic.AtomicBoolean()
@Volatile private var frameGenInventoryIds: Set<Long>? = null
@Volatile private var frameGenInventoryRevision = -1L
private val frameGenInventoryLock = Any()
@Volatile private var frameGenInventoryLastAttemptAt = 0L
private val frameGenInventoryRetryScheduled = java.util.concurrent.atomic.AtomicBoolean()
private val frameGenInventoryRefreshScheduled = java.util.concurrent.atomic.AtomicBoolean()
@Volatile private var appliedFrameGenMode: FrameGen.Mode? = null
@Volatile private var appliedFrameGenHz: Float? = null
private var fexPreset by mutableStateOf("")
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
@@ -859,7 +877,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
hud.attach(root, root.childCount)
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
hud.onPresentingWindowChanged = {
if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() }
CompositorHost.rearmFrameGen { applyFrameGen(force = true) }
}
if (SessionState.running && SessionState.firstFrameSeen) {
loading.visible = false
@@ -892,8 +910,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
glassesScope.launch { com.droiddeck.launcher.handtracking.HandTracking.settings.collect { updateHandCamera() } }
glassesScope.launch {
var lastRunGameId: String? = null
while (true) {
updateTrackingRecovery()
if (SessionState.mode == SessionService.MODE_RUN) {
val gameId = SessionState.gameId
?.takeIf { it.toLongOrNull() != null }
?: intent.getStringExtra(SessionService.EXTRA_GAME_ID)
?.takeIf { it.toLongOrNull() != null }
if (gameId != lastRunGameId) {
lastRunGameId = gameId
if (drawerGameProfileFollowState.followsSteam) {
loadFrameGenFor(gameId?.toLongOrNull())
}
applyFrameGen()
}
} else {
lastRunGameId = null
}
kotlinx.coroutines.delay(100)
}
}
@@ -956,7 +990,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
applyOutputPacing()
if (pipUi != frameGenPip) {
frameGenPip = pipUi
if (FrameGen.engine(this@SessionActivity) != FrameGen.ENGINE_OFF && ::surfaceView.isInitialized) applyFrameGen()
if (::surfaceView.isInitialized) applyFrameGen()
}
}
androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() }
@@ -1032,7 +1066,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
},
)
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty()) {
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty(), drawerGameInventoryRevision) {
val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" }
else {
@@ -1045,11 +1079,40 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
}
if (SessionState.mode == SessionService.MODE_STEAM) {
val target = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
val games = LibraryCache.load(this@SessionActivity)
val cachedIds = games.mapNotNull { it.profileKey.toLongOrNull() }.toSet()
val inventoryIds = synchronized(frameGenInventoryLock) {
frameGenInventoryIds
}.orEmpty()
val id = AgentGuest.activeSteamAppId(
this@SessionActivity, cachedIds + inventoryIds
)
val name = id?.let { activeId ->
games.firstOrNull { it.profileKey == activeId.toString() }?.name
}
id to name
}
if (target.first != frameGenActiveGameId) {
frameGenActiveGameId = target.first
if (drawerGameProfileFollowState.followsSteam) {
loadFrameGenFor(target.first)
}
}
frameGenActiveGameName = target.second
}
if (nextGame != gestureGame) {
if (nextGame != null) gameStarts++
gestureGame = nextGame
refreshGestureConfig()
}
if (
SessionState.mode == SessionService.MODE_STEAM &&
CompositorHost.isStarted
) {
applyFrameGen()
}
if (secondScreenDisplays.isNotEmpty()) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
}
@@ -1234,6 +1297,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
textureAnisotropy = if (drawerGameProfileId == null) textureAnisotropy else drawerTextureAnisotropy,
textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias,
frameGen = frameGen,
frameGenTargetGameId = frameGenTargetGameId()?.toString(),
frameGenTargetGameName = when {
!drawerGameProfileFollowState.followsSteam ->
drawerGameProfileRefresh.data?.profiles
?.firstOrNull { it.first == frameGenTargetGameId() }?.second
SessionState.mode == SessionService.MODE_STEAM -> frameGenActiveGameName
SessionState.mode == SessionService.MODE_RUN ->
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program)
else -> drawerGameProfileRefresh.data?.profiles
?.firstOrNull { it.first == frameGenTargetGameId() }?.second
},
hasGameOverride = frameGenHasGameOverride,
lossless = lossless,
oscMode = oscMode, suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground, touchMode = touchMode,
@@ -1293,9 +1368,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
applyOutputPacing()
},
onFrameGenPick = { mode ->
FrameGen.set(this@SessionActivity, mode)
val appId = frameGenTargetGameId()
if (appId == null) FrameGen.set(this@SessionActivity, mode)
else FrameGen.setForGame(this@SessionActivity, appId.toString(), mode)
loadFrameGenFor(appId)
readPrefs()
applyFrameGen()
applyFrameGen(force = true)
},
onFrameGenReset = {
val appId = frameGenTargetGameId()
if (appId == null) FrameGen.clearGlobal(this@SessionActivity)
else FrameGen.clearGame(this@SessionActivity, appId.toString())
loadFrameGenFor(appId)
readPrefs()
applyFrameGen(force = true)
},
onImportLossless = {
pickLossless.launch(InAppFilePicker.buildIntent(
@@ -1628,9 +1716,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}, "drawer-components").start()
}
private fun frameGenTargetGameId(): Long? {
if (!drawerGameProfileFollowState.followsSteam) {
return drawerGameProfileId
}
if (SessionState.mode == SessionService.MODE_RUN) {
return (
SessionState.gameId?.toLongOrNull()
?: intent.getStringExtra(SessionService.EXTRA_GAME_ID)?.toLongOrNull()
)
}
if (SessionState.mode == SessionService.MODE_STEAM) {
return frameGenActiveGameId
}
return drawerGameProfileId
}
private fun loadFrameGenFor(appId: Long?) {
val profileId = appId?.toString()
frameGen = FrameGen.mode(this, profileId)
frameGenHasGameOverride = appId?.let {
FrameGen.hasGameOverride(this, it.toString())
} == true
}
private fun selectDrawerGameProfile(appId: Long?) {
drawerGameProfileFollowState.selectManually()
drawerGameProfileSelectionMade = true
drawerGameProfileId = appId
loadFrameGenFor(frameGenTargetGameId())
drawerGameProfileRefresh = drawerGameProfileRefresh.retrying()
readDrawerTextureFiltering(appId)
refreshDrawerGameProfile()
@@ -1703,6 +1817,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (refresh.followsSteam) {
if (drawerGameProfileFollowState.followsSteam) {
drawerGameProfileId = result.selectedAppId
loadFrameGenFor(result.selectedAppId)
readDrawerTextureFiltering(result.selectedAppId)
}
}
@@ -1727,6 +1842,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
gameProtonId = ProtonDefault.gameSelectedId(this, game.profileKey, protons),
gameComponents = ComponentsManager.gameComponents(this, game.profileKey),
gameWindowsComponents = WinComponents.picks(this, game.profileKey),
frameGenMode = FrameGen.mode(this, game.profileKey),
frameGenInherited = !FrameGen.hasGameOverride(this, game.profileKey),
)
}
@@ -1970,7 +2087,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (routedTouchMode != nextRoutedTouchMode) gestureTouchStreamGate.reset()
routedTouchMode = nextRoutedTouchMode
requestRelativeMouse()
frameGen = FrameGen.mode(this)
loadFrameGenFor(frameGenTargetGameId())
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
@@ -2257,7 +2374,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (resized) {
cancelTouchGestures()
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
CompositorHost.resize(holder.surface) { applyFrameGen() }
CompositorHost.resize(holder.surface) { applyFrameGen(force = true) }
resizeOutputForWindow(width, height)
}
}
@@ -2398,17 +2515,161 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private fun applyFrameGen() {
private fun frameGenModeForActiveGame(request: Int): FrameGen.Mode {
if (SessionState.mode == SessionService.MODE_RUN) {
val activeAppId = (
SessionState.gameId?.takeIf { it.toLongOrNull() != null }
?: intent.getStringExtra(SessionService.EXTRA_GAME_ID)
)?.toLongOrNull()
return FrameGen.mode(this, activeAppId?.toString())
}
val cachedIds = LibraryCache.load(this)
.mapNotNull { it.profileKey.toLongOrNull() }
.toSet()
var inventoryRevision = drawerGameInventoryRevision
var ids = synchronized(frameGenInventoryLock) {
if (frameGenInventoryRevision != inventoryRevision) {
frameGenInventoryIds = null
frameGenInventoryRevision = inventoryRevision
frameGenInventoryLastAttemptAt = 0L
}
frameGenInventoryIds
}
if (ids == null) {
val now = SystemClock.elapsedRealtime()
val shouldScan = synchronized(frameGenInventoryLock) {
val currentRevision = drawerGameInventoryRevision
if (frameGenInventoryRevision != currentRevision) {
frameGenInventoryIds = null
frameGenInventoryRevision = currentRevision
frameGenInventoryLastAttemptAt = 0L
}
inventoryRevision = currentRevision
if (frameGenInventoryIds != null) {
false
} else if (
frameGenInventoryLastAttemptAt != 0L &&
now - frameGenInventoryLastAttemptAt < 15_000L
) {
false
} else {
frameGenInventoryLastAttemptAt = now
true
}
}
if (shouldScan) {
val currentIds = runCatching {
Library.launchableGames(this, strictRead = true)
.mapNotNull { it.profileKey.toLongOrNull() }
.toSet()
}.getOrNull()
if (currentIds == null) {
if (frameGenInventoryRetryScheduled.compareAndSet(false, true)) {
uiHandler.postDelayed({
frameGenInventoryRetryScheduled.set(false)
val retry = synchronized(frameGenInventoryLock) {
frameGenInventoryIds == null
}
if (retry && !isFinishing && !isDestroyed) {
applyFrameGen()
}
}, 15_000L)
}
} else {
var published = false
synchronized(frameGenInventoryLock) {
if (drawerGameInventoryRevision == inventoryRevision &&
frameGenInventoryRevision == inventoryRevision
) {
ids = cachedIds + currentIds
frameGenInventoryIds = ids
published = true
}
}
if (published) {
if (frameGenInventoryRefreshScheduled.compareAndSet(false, true)) {
uiHandler.postDelayed({
frameGenInventoryRefreshScheduled.set(false)
if (frameGenActivityActive && !isFinishing && !isDestroyed) {
synchronized(frameGenInventoryLock) {
frameGenInventoryIds = null
frameGenInventoryLastAttemptAt = 0L
}
applyFrameGen()
}
}, 15_000L)
}
if (frameGenRequests.get() != request) {
applyFrameGen()
}
}
}
}
if (ids == null) {
ids = synchronized(frameGenInventoryLock) {
frameGenInventoryIds
} ?: emptySet()
}
}
val activeAppId = AgentGuest.activeSteamAppId(
this, cachedIds + (ids ?: emptySet())
)
if (activeAppId == null) return FrameGen.Mode.OFF
return FrameGen.mode(this, activeAppId.toString())
}
private fun applyFrameGen(force: Boolean = false) {
val request = synchronized(frameGenGlobalLock) {
if (force) frameGenForcePending.set(true)
frameGenRequests.incrementAndGet()
}
val hz = refreshHz()
val pip = pipUi && mirrorRefreshLimit() <= 0
val request = frameGenRequests.incrementAndGet()
Thread({
val problem = synchronized(frameGenRequests) {
val mode = if (pip) FrameGen.Mode.OFF else frameGenModeForActiveGame(request)
val needsApply = synchronized(frameGenGlobalLock) {
if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@Thread
if (request != frameGenRequests.get()) return@Thread
if (pip) FrameGen.apply(this, FrameGen.Mode.OFF, hz) else FrameGen.apply(this, hz)
if (!frameGenActivityActive || isFinishing || isDestroyed) return@Thread
val lastAppliedHz = appliedFrameGenHz
frameGenForcePending.get() || appliedFrameGenMode == null ||
mode != appliedFrameGenMode || lastAppliedHz == null ||
kotlin.math.abs(lastAppliedHz - hz) > 0.1f
}
val prepared = if (needsApply) FrameGen.prepareApply(this, mode) else null
val problem = synchronized(frameGenGlobalLock) {
if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@Thread
if (request != frameGenRequests.get()) return@Thread
if (!frameGenActivityActive || isFinishing || isDestroyed) return@Thread
val forcePending = frameGenForcePending.get()
val lastAppliedHz = appliedFrameGenHz
if (!forcePending && appliedFrameGenMode != null && mode == appliedFrameGenMode &&
lastAppliedHz != null && kotlin.math.abs(lastAppliedHz - hz) <= 0.1f
) {
null
} else {
val ready = prepared ?: return@Thread
frameGenForcePending.set(false)
FrameGen.applyPrepared(this, ready, hz).also { problem ->
if (problem == null) {
appliedFrameGenMode = mode
appliedFrameGenHz = hz
} else {
appliedFrameGenMode = null
appliedFrameGenHz = null
}
}
}
}
val state = Lossless.state(this)
runOnUiThread {
if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@runOnUiThread
lossless = state
if (problem != null) Toast.makeText(this, problem, Toast.LENGTH_LONG).show()
}
@@ -2425,12 +2686,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun importLossless(dll: File) {
Thread({
val message = Lossless.message(this, Lossless.import(this, dll))
val result = Lossless.import(this, dll)
val message = Lossless.message(this, result)
val state = Lossless.state(this)
runOnUiThread {
lossless = state
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
if (FrameGen.engine(this) == FrameGen.ENGINE_LSFG) applyFrameGen()
applyFrameGen(force = result == Lossless.ImportResult.UPDATED)
}
}, "lossless-import").start()
}
@@ -4708,12 +4970,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onResume() {
super.onResume()
drawerGameInventoryRevision++
com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event ->
com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) }
}
if (refreshActivityDisplayId() && started) {
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
}
if (CompositorHost.isStarted) applyFrameGen(force = true)
applyFollowOrientation(resources.configuration)
if (runtimeRemovalBlocked) return
if (!SessionState.suspended) pausedFrame = null
@@ -5391,6 +5655,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onDestroy() {
synchronized(frameGenGlobalLock) {
frameGenActivityActive = false
frameGenRequests.incrementAndGet()
}
if (AgentGuest.readyListener === agentReadyListener) AgentGuest.readyListener = null
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
relativeMouseRequests.shutdownNow()
@@ -5505,6 +5773,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private const val BOTTOM_RECOVERY_MS = 1_000L
private const val BOTTOM_RECOVERY_TRIES = 3
private const val TAG = "SessionActivity"
private val frameGenGlobalLock = Any()
private val frameGenGlobalGeneration = java.util.concurrent.atomic.AtomicLong(0L)
private var startedScreens = 0
@Volatile private var activeInstallWorker: Any? = null
private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need"
@@ -126,6 +126,7 @@ object Library {
fun steamGames(
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
withShared: Boolean = true,
onlyAppIds: Set<Int>? = null,
): List<SteamGame> {
val root = SessionPrefs.steamRoot(context, arch)
val cache = File(root, "appcache/librarycache")
@@ -138,7 +139,9 @@ object Library {
if (strictRead && steamapps.isDirectory) check(manifests != null) { context.getString(R.string.game_sync_err_manifests) }
manifests?.sortedBy { it.name }?.forEach { manifest ->
val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach
if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach
if (appId in NOT_GAMES || out.containsKey(appId) ||
(onlyAppIds != null && appId !in onlyAppIds)
) return@forEach
val text = try { manifest.readText() } catch (e: Exception) { if (strictRead) throw e; return@forEach }
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
@@ -161,16 +164,41 @@ object Library {
}
if (withShared) {
val other = if (arch == "x86_64") "arm64" else "x86_64"
val shared = sharedApps(context, arch) - out.keys
if (shared.isNotEmpty()) runCatching { steamGames(context, arch = other, withShared = false) }.getOrDefault(emptyList())
.filter { it.appId in shared }.forEach { out[it.appId] = it }
val shared = try {
sharedApps(context, arch) - out.keys
} catch (e: IllegalStateException) {
if (strictRead) throw e
emptySet()
}
if (shared.isNotEmpty()) {
val otherGames = try {
steamGames(
context,
strictRead = strictRead,
arch = other,
withShared = false,
onlyAppIds = shared,
)
} catch (e: Exception) {
if (strictRead) throw e
emptyList()
}
otherGames.forEach { out[it.appId] = it }
}
}
return out.values.toList()
}
internal fun sharedApps(context: Context, arch: String): Set<Int> {
val view = File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/shared/${if (arch == "x86_64") "arm64" else "x86-64"}/steamapps")
return view.list().orEmpty().mapNotNull { Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }.toSet()
val entries = view.list()
if (entries == null) {
if (!view.exists()) return emptySet()
throw IllegalStateException("Unable to read the shared Steam library.")
}
return entries.mapNotNull {
Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull()
}.toSet()
}
fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
@@ -28,12 +28,38 @@ object FrameGen {
fun engine(context: Context): String = mode(context).engine
fun mode(context: Context): Mode {
fun mode(context: Context): Mode = mode(context, null)
fun mode(context: Context, appId: String?): Mode {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val engine = prefs.getString("engine", ENGINE_OFF).let { if (it == LEGACY_ENGINE_WINFG) ENGINE_DDFG else it ?: ENGINE_OFF }
val target = prefs.getInt("target", 0)
val gamePrefix = appId?.takeIf { it.isNotBlank() }?.let { "game.$it." }
?.takeIf { prefs.contains(it + "engine") } ?: ""
val engine = prefs.getString(gamePrefix + "engine", ENGINE_OFF)
.let { if (it == LEGACY_ENGINE_WINFG) ENGINE_DDFG else it ?: ENGINE_OFF }
val target = prefs.getInt(gamePrefix + "target", 0)
if (engine == ENGINE_LSFG && target in ADAPTIVE_TARGETS) return Mode(engine, target = target)
return Mode(engine, prefs.getInt("multiplier", 2).coerceIn(2, 4))
return Mode(engine, prefs.getInt(gamePrefix + "multiplier", 2).coerceIn(2, 4))
}
fun hasGameOverride(context: Context, appId: String): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).contains("game.$appId.engine")
fun setForGame(context: Context, appId: String, mode: Mode) {
val prefix = "game.$appId."
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(prefix + "engine", mode.engine)
.putInt(prefix + "multiplier", mode.multiplier)
.putInt(prefix + "target", mode.target)
.apply()
}
fun clearGame(context: Context, appId: String) {
val prefix = "game.$appId."
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove(prefix + "engine")
.remove(prefix + "multiplier")
.remove(prefix + "target")
.apply()
}
fun set(context: Context, mode: Mode) {
@@ -41,6 +67,11 @@ object FrameGen {
.putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply()
}
fun clearGlobal(context: Context) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove("engine").remove("multiplier").remove("target").apply()
}
fun label(context: Context): String = label(context, mode(context))
fun label(context: Context, mode: Mode): String = when {
@@ -50,14 +81,32 @@ object FrameGen {
else -> context.getString(R.string.frame_gen_off)
}
fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz)
data class PreparedApply internal constructor(
val mode: Mode,
internal val lsfgStatus: Int? = null,
internal val lsfgCachePath: String? = null,
)
fun apply(context: Context, mode: Mode, refreshHz: Float): String? {
fun prepareApply(context: Context, mode: Mode): PreparedApply {
if (mode.engine != ENGINE_LSFG) return PreparedApply(mode)
val status = Lossless.sync(context)
val cachePath = Lossless.cacheFile(context)?.absolutePath
return PreparedApply(mode, status, cachePath)
}
fun apply(context: Context, refreshHz: Float): String? =
apply(context, mode(context), refreshHz)
fun apply(context: Context, mode: Mode, refreshHz: Float): String? =
applyPrepared(context, prepareApply(context, mode), refreshHz)
fun applyPrepared(context: Context, prepared: PreparedApply, refreshHz: Float): String? {
val mode = prepared.mode
when (mode.engine) {
ENGINE_LSFG -> {
val status = Lossless.sync(context)
val cache = Lossless.cacheFile(context)
if (status != LsfgNative.STATUS_OK || cache == null) {
val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED
val cachePath = prepared.lsfgCachePath
if (status != LsfgNative.STATUS_OK || cachePath == null) {
WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
val problem = context.getString(
if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed,
@@ -66,7 +115,7 @@ object FrameGen {
return problem
}
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG)
WaylandCompositor.nativeSetLsfgCachePath(cache.absolutePath)
WaylandCompositor.nativeSetLsfgCachePath(cachePath)
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, mode.target)
}
@@ -10,7 +10,6 @@ import android.view.View
import android.view.animation.PathInterpolator
import android.view.ViewGroup
import android.widget.FrameLayout
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
@@ -238,8 +237,13 @@ class DroidDeckHudHost(context: Context) {
}
private fun presentedFps(): Float {
if (FrameGen.mode(context).engine == FrameGen.ENGINE_OFF) return 0f
val stats = runCatching { WaylandCompositor.nativeFrameGenStats() }.getOrNull() ?: return 0f
if (!runCatching { WaylandCompositor.nativeFrameGenActive() }
.getOrDefault(false)) return 0f
val stats = runCatching {
WaylandCompositor.nativeFrameGenStats()
}.getOrNull() ?: return 0f
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
}
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.gpu.FrameGen
data class ProfileValue(val value: String, val inherited: Boolean)
@@ -17,6 +18,8 @@ data class SelectedGameProfile(
val environmentOverrides: Int,
val windowsComponentNames: List<String>,
val startWithoutSteam: Boolean = false,
val frameGen: FrameGen.Mode = FrameGen.Mode.OFF,
val frameGenInherited: Boolean = true,
) {
val hasOverrides: Boolean
get() = !fexPreset.inherited ||
@@ -24,7 +27,8 @@ data class SelectedGameProfile(
components.values.any { !it.inherited } ||
environmentOverrides > 0 ||
windowsComponentNames.isNotEmpty() ||
startWithoutSteam
startWithoutSteam ||
!frameGenInherited
companion object {
fun resolve(
@@ -38,6 +42,8 @@ data class SelectedGameProfile(
gameProtonId: String?,
gameComponents: Map<String, String>,
gameWindowsComponents: List<String>,
frameGenMode: FrameGen.Mode = FrameGen.Mode.OFF,
frameGenInherited: Boolean = true,
): SelectedGameProfile? {
val game = games.firstOrNull { it.profileKey == selectedAppId.toString() } ?: return null
val fexOverride = GameEnvironment.gameFexPreset(environment, game.profileKey)
@@ -68,6 +74,8 @@ data class SelectedGameProfile(
environmentOverrides = otherEnvironment.size,
windowsComponentNames = gameWindowsComponents.map(WinComponentNames::of),
startWithoutSteam = GameEnvironment.gameNoSteam(environment, game.profileKey),
frameGen = frameGenMode,
frameGenInherited = frameGenInherited,
)
}
}
@@ -13,6 +13,9 @@ internal fun FrameGenMenu(
host: MenuHost, mode: FrameGen.Mode, lossless: Lossless.State,
onPick: (FrameGen.Mode) -> Unit,
onImportLossless: () -> Unit,
gameProfileId: String? = null,
hasGameOverride: Boolean = false,
onResetGame: () -> Unit = {},
) {
val context = LocalContext.current
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = stringResource(R.string.frame_gen_title)) { firstItemFocus ->
@@ -27,6 +30,12 @@ internal fun FrameGenMenu(
onPick(m); host.open = null
}
item(FrameGen.Mode.OFF, focus = firstItemFocus)
if (gameProfileId != null) {
MenuItem(stringResource(R.string.comp_game_use_general), checked = !hasGameOverride) {
onResetGame()
host.open = null
}
}
for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_DDFG, m))
val lsfg = (2..4).map { FrameGen.Mode(FrameGen.ENGINE_LSFG, it) } +
FrameGen.ADAPTIVE_TARGETS.map { FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it) }
@@ -749,6 +749,17 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val context = androidx.compose.ui.platform.LocalContext.current
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
val wincompKey = game?.takeIf { it.library == com.droiddeck.launcher.frontend.Library.ADDED || it.appId > 0 }?.profileKey
val frameGenProfileKey = game?.profileKey?.takeIf { it.isNotBlank() }
var gameFrameGenMode by remember(frameGenProfileKey) {
mutableStateOf(frameGenProfileKey?.let {
com.droiddeck.launcher.gpu.FrameGen.mode(context, it)
} ?: s.frameGen)
}
var gameFrameGenOverride by remember(frameGenProfileKey) {
mutableStateOf(frameGenProfileKey?.let {
com.droiddeck.launcher.gpu.FrameGen.hasGameOverride(context, it)
} ?: false)
}
var wincompOpen by remember(wincompKey) { mutableStateOf<Boolean?>(null) }
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
val steamScope = game?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) }
@@ -767,10 +778,42 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
add { m ->
Box(m) {
SettingCard(stringResource(R.string.frame_gen_title), s.frameGenLabel, "card:fg", Modifier.fillMaxSize()) {
SettingCard(
stringResource(R.string.frame_gen_title),
if (frameGenProfileKey != null)
com.droiddeck.launcher.gpu.FrameGen.label(context, gameFrameGenMode)
else s.frameGenLabel,
"card:fg", Modifier.fillMaxSize()
) {
host.open = if (host.open == "fg") null else "fg"
}
FrameGenMenu(s, a, host)
FrameGenMenu(
host = host,
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
lossless = s.lossless,
onPick = { mode ->
val key = frameGenProfileKey
if (key == null) {
a.onFrameGenPick(mode)
} else {
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
gameFrameGenMode = mode
gameFrameGenOverride = true
}
},
onImportLossless = a.onImportLossless,
gameProfileId = frameGenProfileKey,
hasGameOverride = gameFrameGenOverride,
onResetGame = {
val key = frameGenProfileKey
if (key != null) {
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
gameFrameGenMode =
com.droiddeck.launcher.gpu.FrameGen.mode(context)
gameFrameGenOverride = false
}
}
)
}
}
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
@@ -220,6 +220,9 @@ class DrawerActions(
val hudOn: Boolean,
val hudConfig: Map<String, String> = emptyMap(),
val frameGen: FrameGen.Mode,
val frameGenTargetGameId: String? = null,
val frameGenTargetGameName: String? = null,
val hasGameOverride: Boolean = false,
val lossless: Lossless.State,
val oscMode: String,
val suspendPolicy: String,
@@ -262,6 +265,7 @@ class DrawerActions(
val onHudReset: () -> Unit = {},
val onHudExport: () -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
val onFrameGenReset: () -> Unit = {},
val fpsLimit: Int = 0,
val onFpsLimit: (Int) -> Unit = {},
val onImportLossless: () -> Unit,
@@ -569,10 +573,21 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
val fgOpen = host.open == "fg"
val offLabel = stringResource(R.string.frame_gen_off)
val fgLabel = FrameGen.label(LocalContext.current, a.frameGen)
SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) {
SettingsRow(
stringResource(R.string.frame_gen_title),
if (a.frameGenTargetGameId != null)
"${stringResource(R.string.frame_gen_scope_game)} · ${a.frameGenTargetGameName ?: "ID ${a.frameGenTargetGameId}"}"
else stringResource(R.string.frame_gen_scope_global),
highlighted = fgOpen
) {
Box {
ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" }
FrameGenMenu(host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless)
FrameGenMenu(
host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless,
gameProfileId = a.frameGenTargetGameId,
hasGameOverride = a.hasGameOverride,
onResetGame = a.onFrameGenReset,
)
}
}
if (a.direct) SliderRow(
@@ -1352,6 +1367,12 @@ private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (S
if (!profile.fexPreset.inherited) {
ProfileSummaryRow(stringResource(R.string.comp_game_fex), fexProfileLabel(profile.fexPreset))
}
if (!profile.frameGenInherited) {
ProfileSummaryRow(
stringResource(R.string.frame_gen_title),
FrameGen.label(LocalContext.current, profile.frameGen),
)
}
if (!profile.proton.inherited) {
ProfileSummaryRow(stringResource(R.string.comp_proton), profileValueLabel(profile.proton))
}
@@ -340,6 +340,7 @@ public final class WaylandCompositor {
public static native int nativeFrameGenProblem();
public static native String nativeFrameGenCapsReason();
public static native boolean nativeFrameGenActive();
public static native float[] nativeFrameGenStats();
public static native long nativeHudFrameTimes(float[] out);