perf: pace buffer releases to the screen, read the requested refresh, drop sustained mode and ADPF

A replaced buffer went straight back to a game with no frame limit, so a
MAILBOX/IMMEDIATE swapchain drew frames that were never shown; it now
comes back once per refresh as in WinNative. gamescope's -r and the
compositor read the rate of the mode the activity asked for rather than
the one the panel was still in, and the zero-copy layer votes it.
Sustained performance mode, which caps clocks on most power HALs, and
the ADPF session, which reported frame intervals as work, are gone.
This commit is contained in:
maxjivi05 committed 2026-09-29 18:44:32 -04:00
1 parent cc37cc8a4d
commit 62bb7a1e80
6 files changed
+30 -111

No files matched your search

@@ -47,7 +47,6 @@ import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.input.TouchpadGestures
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.PerfHints
import com.droiddeck.launcher.session.PerfHud
import com.droiddeck.launcher.session.PerfMode
import com.droiddeck.launcher.session.SessionPrefs
@@ -203,8 +202,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionEvents.record("agent.start_requested", mapOf("mode" to SessionState.mode))
}
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
// Game-tier power policy for the whole session: a sustained clock floor, the panel's
// fastest mode, and the OS told it is in gameplay. Logged so a slow device says why.
// Game-tier power policy for the whole session: the panel's fastest mode, and the OS told
// it is in gameplay. Logged so a slow device says why.
Log.i(TAG, "perf: " + PerfMode.apply(this))
goFullscreen()
// The device's volume keys change the stream the session plays on (the relay and
@@ -761,9 +760,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(),
)
if (!SessionState.running) SessionEvents.record("compositor.started")
// ADPF: the compositor thread's frame intervals go to the power HAL against the panel's
// period, so a long frame raises CPU clocks now rather than after the load averages up.
PerfHints.arm(this, refreshHz())
// The service owns everything below the compositor. It is started whenever no session is
// running - NOT only when the compositor was just started: the compositor lives for the
// whole process, so the second Play after a session ended used to re-attach the Surface,
@@ -849,9 +845,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return Pair(width and 1.inv(), height and 1.inv())
}
/**
* The rate of the mode PerfMode asked for, not the one the panel is still in: the switch lands
* some frames after onCreate, and read too early it gave gamescope `-r 60` on a 120 Hz panel -
* the client and every game then paced themselves to 60. (WinNative's requestedPanelRefreshRate.)
*/
private fun refreshHz(): Float {
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
val hz = display?.refreshRate ?: 60f
val wanted = window.attributes.preferredDisplayModeId
val hz = display?.supportedModes?.firstOrNull { wanted != 0 && it.modeId == wanted }?.refreshRate
?: display?.refreshRate ?: 60f
return if (hz > 1f) hz else 60f
}
@@ -1,87 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.PerformanceHintManager
import android.util.Log
import androidx.annotation.RequiresApi
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.util.concurrent.Executors
/**
* ADPF (Android 12+): a PerformanceHintManager session over the compositor thread, told the
* panel's frame period as its target and each presented frame's interval as the actual. When a
* frame runs long the power HAL raises CPU clocks for the next one at once, instead of the
* governor waiting for the load average to climb - the difference between a menu that stutters
* on the first scroll and one that does not.
*
* The session may only carry this process's threads, so the guest (gamescope, the Steam client
* under FEX) cannot join it; they are covered by the app-wide game category and sustained mode.
* Below API 31 nothing here runs; on a power HAL without hint sessions createHintSession returns
* null and the log says so.
*/
object PerfHints {
private const val TAG = "PerfHints"
@Volatile private var session: PerformanceHintManager.Session? = null
@Volatile private var target = 0L
/** Compositor thread only. */
private var last = 0L
private val main = Handler(Looper.getMainLooper())
/** Reports leave the compositor thread: each one is a binder call to the power HAL. */
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "adpf-report").apply { isDaemon = true } }
/** Opens the session once the compositor thread exists (it is started just before this). */
fun arm(context: Context, refreshHz: Float) {
if (Build.VERSION.SDK_INT < 31) { Log.i(TAG, "adpf: needs Android 12; this is API ${Build.VERSION.SDK_INT}"); return }
val wanted = (1_000_000_000.0 / refreshHz.coerceAtLeast(30f)).toLong()
val s = session
if (s != null) {
if (wanted != target) { target = wanted; try { s.updateTargetWorkDuration(wanted) } catch (t: Throwable) { Log.w(TAG, "adpf: retarget", t) } }
return
}
target = wanted
val app = context.applicationContext
var tries = 0
main.post(object : Runnable {
override fun run() {
if (session != null) return
val tid = try { WaylandCompositor.nativeCompositorTid() } catch (t: Throwable) { 0 }
if (tid == 0) {
if (++tries < 30) main.postDelayed(this, 100) else Log.w(TAG, "adpf: the compositor thread never reported its tid")
return
}
open(app, tid)
}
})
}
@RequiresApi(31)
private fun open(app: Context, tid: Int) {
val pm = app.getSystemService(PerformanceHintManager::class.java)
if (pm == null) { Log.i(TAG, "adpf: no PerformanceHintManager on this device"); return }
val s = try { pm.createHintSession(intArrayOf(tid), target) } catch (t: Throwable) { Log.w(TAG, "adpf: createHintSession", t); null }
if (s == null) { Log.i(TAG, "adpf: unsupported here (the power HAL has no hint sessions)"); return }
last = 0L
session = s
Log.i(TAG, "adpf: session on compositor thread $tid · target ${target / 1000} µs · HAL wants updates every ${pm.preferredUpdateRateNanos / 1000} µs")
}
/** Compositor thread, once per presented game frame; the interval since the last is the actual. */
@JvmStatic
fun onFrame() {
val s = session ?: return
val now = System.nanoTime()
val prev = last
last = now
if (prev == 0L) return
val dt = now - prev
// Under half a millisecond is a double present; over half a second is a pause, not a frame.
if (dt < 500_000L || dt > 500_000_000L) return
worker.execute {
try { s.reportActualWorkDuration(dt) } catch (t: Throwable) { Log.w(TAG, "adpf: report failed, session dropped", t); session = null }
}
}
}
@@ -4,7 +4,6 @@ import android.app.Activity
import android.app.GameManager
import android.app.GameState
import android.os.Build
import android.os.PowerManager
import android.util.Log
/**
@@ -13,8 +12,10 @@ import android.util.Log
* The manifest already makes the app a game (appCategory + game_mode_config); this is the
* per-window half, applied when the session activity is created:
*
* - sustained performance mode (Android 7+): a clock floor that does not throttle away after
* two minutes, which suits an hour in Big Picture better than a boost that fades;
* - NOT sustained performance mode: on Pixel and Qualcomm power HALs it caps the CPU and GPU at
* a level the device can hold indefinitely rather than holding a floor, which cost games and
* Big Picture their peak clocks. WinNative never asks for it; the thermal budget is left to
* the game;
* - the panel's fastest mode at its current size (Android 6+): a 120 Hz phone is switched to
* 120 Hz for the menu, not only when a game votes for it;
* - GameManager's game state (Android 13+): "in gameplay", so an OEM framework that releases
@@ -27,15 +28,7 @@ object PerfMode {
private const val TAG = "PerfMode"
fun apply(a: Activity): String {
val parts = ArrayList<String>(3)
// Sustained performance mode.
parts += if (Build.VERSION.SDK_INT >= 24) {
val pm = a.getSystemService(PowerManager::class.java)
if (pm?.isSustainedPerformanceModeSupported == true) {
try { a.window.setSustainedPerformanceMode(true); "sustained mode on" } catch (t: Throwable) { Log.w(TAG, "sustained mode", t); "sustained mode refused" }
} else "sustained mode unsupported"
} else "sustained mode needs Android 7"
val parts = ArrayList<String>(2)
// The fastest display mode at the panel's current size.
parts += try {
@@ -41,6 +41,10 @@ object CompositorHost {
}
WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight)
WaylandCompositor.nativeSetOutputRefreshRate(refreshHz)
// The cadence the zero-copy layer votes for. Left at 0 the system infers it from the rate
// already being achieved, and on a phone whose vendor picks clocks from that a session
// that has been slowed reads as one that wants to be. (WinNative, WaylandSession.)
WaylandCompositor.nativeSetLayerFrameRate(refreshHz)
WaylandCompositor.nativeStartWithSurface(
surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir,
)
@@ -91,7 +91,6 @@ public final class WaylandCompositor {
long smoothed = frameIntervalNanos;
frameIntervalNanos = smoothed == 0 ? interval : (smoothed * 3 + interval) / 4;
}
com.droiddeck.launcher.session.PerfHints.onFrame();
GameListener l = gameListener;
if (l != null) l.onGameFrame();
}
@@ -218,7 +217,7 @@ public final class WaylandCompositor {
* once per tick, so games run unthrottled and the screen shows their latest frame. */
public static native void nativeVsync(long frameTimeNanos);
/** The compositor thread's Linux tid, or 0 before it has started (see PerfHints). */
/** The compositor thread's Linux tid, or 0 before it has started. */
public static native int nativeCompositorTid();
/** Shortcut launches: don't draw explorer's windows (desktop, taskbar, Start menu), matching the