diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a2892c17d8..a46c5d946c 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -33,7 +33,16 @@ android:theme="@style/AppTheme" android:hardwareAccelerated="true" android:largeHeap="true" - android:extractNativeLibs="true"> + android:extractNativeLibs="true" + android:appCategory="game" + android:isGame="true"> + + + diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 59e0e17bbf..440eae30a1 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -5,6 +5,13 @@ project(steamdeck C CXX) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O2 -Wno-unused-function -Wimplicit-function-declaration") +# Every library the app builds is linked with 16 KB-aligned LOAD segments. A 16 KB-page kernel +# (Android 15+ devices) refuses to load a 4 KB-only ELF; a 4 KB kernel loads a 16 KB-aligned one +# unchanged (the alignment is a multiple of its page), so this costs nothing on today's devices +# but a little padding in the file. Prebuilt libraries under jniLibs/ carry their own alignment. +set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,max-page-size=16384") +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,max-page-size=16384") + add_subdirectory(adrenotools) # DXVK's DXBC->SPIR-V translator (zlib licence), vendored under thirdparty/dxbc from the same diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 00684b07ed..8e2801848e 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -38,6 +38,7 @@ extern volatile int g_output_w, g_output_h; #define TAG "BannerWayland" static JavaVM *g_jvm; +static volatile pid_t g_comp_tid; /* the compositor thread, for the app's ADPF hint session */ static jclass g_compositor_cls; /* global ref */ static jmethodID g_on_first_frame; /* static void onFirstFramePresented() */ static jmethodID g_on_game_surface; /* static void onGameSurface(String, String) */ @@ -183,6 +184,7 @@ static void *comp_thread(void *arg) { * thread that started it had. Never lowered: a thread that already runs hotter keeps its value. */ pthread_setname_np(pthread_self(), "wl-compositor"); const id_t tid = (id_t)gettid(); + g_comp_tid = (pid_t)tid; errno = 0; const int before = getpriority(PRIO_PROCESS, tid); int refused = 0; @@ -217,6 +219,14 @@ static void start_thread(void) { __android_log_print(ANDROID_LOG_ERROR, TAG, "pthread_create failed"); } +/* The compositor thread's tid, or 0 before it starts. The app opens a PerformanceHintManager session + * on it and reports each presented frame's interval, so the governor sees a frame that ran long. */ +JNIEXPORT jint JNICALL +Java_com_steamdeck_launcher_wayland_WaylandCompositor_nativeCompositorTid(JNIEnv *env, jclass clazz) { + (void)env; (void)clazz; + return (jint)g_comp_tid; +} + /* Headless start (no output window) — used for bring-up tests. */ JNIEXPORT void JNICALL Java_com_steamdeck_launcher_wayland_WaylandCompositor_nativeStart(JNIEnv *env, jclass clazz, diff --git a/app/src/main/java/com/steamdeck/launcher/SessionActivity.kt b/app/src/main/java/com/steamdeck/launcher/SessionActivity.kt index c830dc189a..a3e5a87730 100644 --- a/app/src/main/java/com/steamdeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/steamdeck/launcher/SessionActivity.kt @@ -33,7 +33,9 @@ import com.steamdeck.launcher.input.PointerGestures import com.steamdeck.launcher.input.TouchpadGestures import com.steamdeck.launcher.runtime.LinuxRuntime import com.steamdeck.launcher.session.LoadingState +import com.steamdeck.launcher.session.PerfHints import com.steamdeck.launcher.session.PerfHud +import com.steamdeck.launcher.session.PerfMode import com.steamdeck.launcher.session.ProtonExtras import com.steamdeck.launcher.session.SessionPrefs import com.steamdeck.launcher.session.SessionPaths @@ -104,6 +106,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) 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. + Log.i(TAG, "perf: " + PerfMode.apply(this)) goFullscreen() // The device's volume keys change the stream the session plays on (the relay and // PulseAudio are media playback); they are never forwarded to the guest. @@ -329,6 +334,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), ) + // 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, diff --git a/app/src/main/java/com/steamdeck/launcher/session/PerfHints.kt b/app/src/main/java/com/steamdeck/launcher/session/PerfHints.kt new file mode 100644 index 0000000000..161c978908 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/session/PerfHints.kt @@ -0,0 +1,87 @@ +package com.steamdeck.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.steamdeck.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 } + } + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/session/PerfMode.kt b/app/src/main/java/com/steamdeck/launcher/session/PerfMode.kt new file mode 100644 index 0000000000..bd04696b33 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/session/PerfMode.kt @@ -0,0 +1,74 @@ +package com.steamdeck.launcher.session + +import android.app.Activity +import android.app.GameManager +import android.app.GameState +import android.os.Build +import android.os.PowerManager +import android.util.Log + +/** + * What a session tells Android about itself so the SoC is run for a game, not for an app. + * + * 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; + * - 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 + * its boost on loading screens or menus keeps it up. + * + * Every step is version-guarded and skipped silently below its API; the returned line is what + * the session log shows, which is the first thing to read on a device that feels slow. + */ +object PerfMode { + private const val TAG = "PerfMode" + + fun apply(a: Activity): String { + val parts = ArrayList(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" + + // The fastest display mode at the panel's current size. + parts += try { + val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay + if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else { + val cur = display.mode + val best = display.supportedModes + .filter { it.physicalWidth == cur.physicalWidth && it.physicalHeight == cur.physicalHeight } + .maxByOrNull { it.refreshRate } + if (best != null && best.modeId != cur.modeId && best.refreshRate > cur.refreshRate + 0.5f) { + a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = best.modeId } + "display ${cur.refreshRate.toInt()} → ${best.refreshRate.toInt()} Hz (mode ${best.modeId})" + } else "display ${cur.refreshRate.toInt()} Hz" + } + } catch (t: Throwable) { Log.w(TAG, "display mode", t); "display mode failed" } + + // GameManager: what mode the OS put us in, and that we are playing. + parts += if (Build.VERSION.SDK_INT >= 31) { + val gm = a.getSystemService(GameManager::class.java) + if (gm == null) "no GameManager" else { + val mode = when (gm.gameMode) { + GameManager.GAME_MODE_PERFORMANCE -> "performance" + GameManager.GAME_MODE_BATTERY -> "battery" + GameManager.GAME_MODE_STANDARD -> "standard" + else -> "unsupported" + } + if (Build.VERSION.SDK_INT >= 33) { + try { gm.setGameState(GameState(false, GameState.MODE_GAMEPLAY_INTERRUPTIBLE)) } catch (t: Throwable) { Log.w(TAG, "game state", t) } + } + "game mode $mode" + } + } else "game mode needs Android 12" + + return parts.joinToString(" · ") + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/steamdeck/launcher/wayland/WaylandCompositor.java index 75053fc6cb..30cbfb9455 100644 --- a/app/src/main/java/com/steamdeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/steamdeck/launcher/wayland/WaylandCompositor.java @@ -62,6 +62,7 @@ public final class WaylandCompositor { /** Invoked from native (banner_on_game_frame) for every frame of the HUD's window. */ @SuppressWarnings("unused") static void onGameFrame() { + com.steamdeck.launcher.session.PerfHints.onFrame(); GameListener l = gameListener; if (l != null) l.onGameFrame(); } @@ -175,6 +176,9 @@ 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). */ + public static native int nativeCompositorTid(); + /** Shortcut launches: don't draw explorer's windows (desktop, taskbar, Start menu), matching the * X11 renderer's unviewable "explorer.exe". Set before the compositor starts. */ public static native void nativeSetHideShell(boolean hide); diff --git a/app/src/main/res/xml/game_mode_config.xml b/app/src/main/res/xml/game_mode_config.xml new file mode 100644 index 0000000000..ccb1c380a6 --- /dev/null +++ b/app/src/main/res/xml/game_mode_config.xml @@ -0,0 +1,15 @@ + + +