SteamDeck: a standalone launcher for the native ARM64 Linux Steam client

Lifts Bannerlator's Linux/gamescope runtime out into an app of its own: the
Wayland compositor, the proot session, the runtime installer, the fake-evdev
controller path and the PulseAudio server, with none of the Wine, container or
store machinery around them.

One activity installs the runtime from the same winlator-contents catalog and a
second one runs the session: compositor on a SurfaceView, gamescope and Valve's
native arm64 client under proot, a physical pad republished into the fake-input
rings, and the session's milestones on screen until the first frame arrives.
This commit is contained in:
The412Banner committed 2026-09-19 13:39:17 -04:00
commit 4022351e22
210 files changed
+73587

No files matched your search

@@ -0,0 +1,154 @@
package com.the412banner.steamdeck
import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import com.the412banner.steamdeck.core.FileUtils
import com.the412banner.steamdeck.runtime.LinuxRuntime
import com.the412banner.steamdeck.runtime.LinuxRuntimeInstaller
/**
* The whole app outside a session: is the runtime installed, is there a newer one, and one button
* that starts Steam. Everything a Steam client can do — the library, the store, downloads,
* settings — is the client's own job once {@link SessionActivity} has it on screen.
*/
class MainActivity : Activity() {
private lateinit var status: TextView
private lateinit var detail: TextView
private lateinit var progress: ProgressBar
private lateinit var playButton: Button
private lateinit var runtimeButton: Button
private val ui = Handler(Looper.getMainLooper())
@Volatile private var busy = false
@Volatile private var available: LinuxRuntimeInstaller.Release? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
status = findViewById(R.id.status)
detail = findViewById(R.id.detail)
progress = findViewById(R.id.progress)
playButton = findViewById(R.id.play)
runtimeButton = findViewById(R.id.runtime)
playButton.setOnClickListener { startActivity(Intent(this, SessionActivity::class.java)) }
runtimeButton.setOnClickListener { onRuntimeButton() }
// The session's logs land in Downloads so a failed run can be handed over as a folder
// rather than dug out of app-private storage. targetSdk 28 means the old permission still
// grants exactly that.
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
}
}
override fun onResume() {
super.onResume()
render()
if (!busy) Thread({ checkCatalog() }, "catalog").start()
}
private fun onRuntimeButton() {
if (busy) return
val installed = LinuxRuntimeInstaller.installedVersion(this)
if (installed != null && available?.version == installed) {
// Nothing to install: offer the one destructive thing this screen can do.
AlertDialog.Builder(this)
.setTitle(R.string.remove_runtime)
.setMessage(R.string.remove_runtime_message)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.remove) { _, _ ->
Thread({
LinuxRuntimeInstaller.uninstall(this)
ui.post { render() }
}, "uninstall").start()
}
.show()
return
}
val release = available
if (release == null) {
Thread({ checkCatalog() }, "catalog").start()
return
}
install(release)
}
private fun install(release: LinuxRuntimeInstaller.Release) {
busy = true
render()
Thread({
val ok = LinuxRuntimeInstaller.install(this, release) { stage, percent ->
ui.post {
progress.isIndeterminate = percent < 0
if (percent >= 0) progress.progress = percent
detail.text = if (percent >= 0) "$stage $percent%" else stage
}
}
busy = false
ui.post {
if (!ok) detail.text = getString(R.string.install_failed)
render()
}
}, "install").start()
}
private fun checkCatalog() {
val release = LinuxRuntimeInstaller.fetchRelease()
if (release != null) available = release
Log.i(TAG, "catalog: " + (release?.version ?: "unreachable"))
ui.post { render() }
}
private fun render() {
val installed = LinuxRuntimeInstaller.installedVersion(this)
val ready = LinuxRuntime.isInstalled(this)
progress.visibility = if (busy) View.VISIBLE else View.GONE
playButton.isEnabled = ready && !busy
runtimeButton.isEnabled = !busy
val offered = available
when {
busy -> {
status.setText(R.string.working)
runtimeButton.setText(R.string.working)
}
!ready -> {
status.setText(R.string.runtime_missing)
runtimeButton.setText(R.string.install_runtime)
detail.text = if (offered != null) {
getString(R.string.runtime_download_size,
offered.version, FileUtils.sizeToString(offered.size))
} else {
getString(R.string.catalog_unreachable)
}
}
offered != null && offered.version != installed -> {
status.setText(R.string.ready)
runtimeButton.setText(R.string.update_runtime)
detail.text = getString(R.string.runtime_update, installed ?: "?", offered.version)
}
else -> {
status.setText(R.string.ready)
runtimeButton.setText(R.string.remove_runtime)
detail.text = getString(R.string.runtime_installed, installed ?: "?")
}
}
}
companion object {
private const val TAG = "MainActivity"
}
}
@@ -0,0 +1,450 @@
package com.the412banner.steamdeck
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Choreographer
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.FrameLayout
import com.the412banner.steamdeck.audio.PulseAudioComponent
import com.the412banner.steamdeck.core.EnvVars
import com.the412banner.steamdeck.core.EnvironmentComponent
import com.the412banner.steamdeck.core.FileUtils
import com.the412banner.steamdeck.core.ProcessHelper
import com.the412banner.steamdeck.gpu.TurnipDriver
import com.the412banner.steamdeck.input.FakeInputWriter
import com.the412banner.steamdeck.input.PadBridge
import com.the412banner.steamdeck.runtime.LinuxNetworkLinkComponent
import com.the412banner.steamdeck.runtime.LinuxRuntime
import com.the412banner.steamdeck.wayland.WaylandCompositor
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* The session: our Wayland compositor on this activity's Surface, and gamescope plus Valve's
* native arm64 Steam client running under proot inside the Linux runtime, presenting into it.
*
* Nothing here is Wine. proot and the session script are the whole of the guest side, and the
* activity's own job is three things: keep a Surface under the compositor, feed it input, and
* hold the session's host-side components (audio, the network link, the proot process) for as
* long as the client is up.
*
* Ported from Bannerlator's XServerDisplayActivity.setupLinuxSession, which in turn follows
* WinNative's gamescope runtime (GPL-3.0).
*/
class SessionActivity : Activity(), SurfaceHolder.Callback {
private lateinit var surfaceView: SurfaceView
private lateinit var statusView: TextView
private val components = ArrayList<EnvironmentComponent>()
private var padBridge: PadBridge? = null
private var compositorStarted = false
private var sessionStarted = false
private var finishing = false
private var sessionPid = -1
private var vsyncRunning = false
private lateinit var sessionLog: File
private val vsyncCallback = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
WaylandCompositor.nativeVsync(frameTimeNanos)
if (vsyncRunning) Choreographer.getInstance().postFrameCallback(this)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
goFullscreen()
if (!LinuxRuntime.isInstalled(this)) {
Log.e(TAG, "the Linux runtime is not installed")
finish()
return
}
val root = FrameLayout(this)
surfaceView = SurfaceView(this)
surfaceView.holder.addCallback(this)
root.addView(surfaceView)
// Until the client's first frame arrives there is nothing on screen for a minute or more
// on a first run, so the session's own milestones are shown instead of a black panel.
statusView = TextView(this).apply {
setPadding(48, 48, 48, 48)
setTextColor(0xFFDDDDDD.toInt())
textSize = 14f
text = getString(R.string.session_starting)
}
root.addView(statusView)
setContentView(root)
WaylandCompositor.setFirstFrameListener {
runOnUiThread { statusView.visibility = View.GONE }
}
}
// ── Compositor ──────────────────────────────────────────────────────────────────────────
override fun surfaceCreated(holder: SurfaceHolder) {
if (compositorStarted) {
WaylandCompositor.nativeSetSurface(holder.surface)
return
}
compositorStarted = true
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
// The compositor hands this keymap to wl_keyboard clients, which is how the guest reads
// the evdev codes we inject.
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
// Turnip, not the system Adreno driver: importing the dma-bufs gamescope commits needs
// VK_EXT_image_drm_format_modifier, which the system driver does not implement.
val turnip = TurnipDriver(this)
val driverId = turnip.install()
val driverPath = driverId?.let { turnip.driverPath(it) }
val libraryName = driverId?.let { turnip.libraryName(it) }
val size = outputSize()
WaylandCompositor.nativeSetOutputSize(size.first, size.second)
WaylandCompositor.nativeSetOutputRefreshRate(refreshHz())
WaylandCompositor.nativeStartWithSurface(
holder.surface, runtimeDir.path, driverPath, libraryName,
applicationInfo.nativeLibraryDir,
)
vsyncRunning = true
Choreographer.getInstance().postFrameCallback(vsyncCallback)
Thread({ startSession(runtimeDir, size) }, "session-start").start()
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
override fun surfaceDestroyed(holder: SurfaceHolder) {
WaylandCompositor.nativeSetSurface(null)
}
/**
* The size the session renders at. gamescope is told this and scales its output onto whatever
* the panel is, so a 1440p phone can run the client at 1080p without the client knowing.
*/
private fun outputSize(): Pair<Int, Int> {
val metrics = resources.displayMetrics
var width = maxOf(metrics.widthPixels, metrics.heightPixels)
var height = minOf(metrics.widthPixels, metrics.heightPixels)
// The client's CEF is the heaviest thing in the session; above 1080p it costs frames for
// nothing anyone can see on a phone panel.
if (height > 1080) {
width = width * 1080 / height
height = 1080
}
// Odd sizes upset the scaler; both dimensions even is what every mode here would be.
return Pair(width and 1.inv(), height and 1.inv())
}
private fun refreshHz(): Float {
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
val hz = display?.refreshRate ?: 60f
return if (hz > 1f) hz else 60f
}
// ── Session ─────────────────────────────────────────────────────────────────────────────
private fun startSession(runtimeDir: File, size: Pair<Int, Int>) {
try {
LinuxRuntime.writeAccounts(this)
} catch (e: Exception) {
Log.e(TAG, "could not write the guest's passwd/group", e)
endSession(-1)
return
}
val root = LinuxRuntime.rootDir(this)
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
stageSessionFiles(root)
val logDir = LinuxRuntime.debugLogDir().apply { mkdirs() }
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
sessionLog = File(logDir, "session-$stamp.log")
val guest = ArrayList<String>()
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("HOME=/root")
guest.add("USER=root")
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
guest.add("TERM=xterm-256color")
guest.add("LANG=C.UTF-8")
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
// Steam's CEF needs GL and the rootfs ships no native GL driver: route it through Zink.
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
val pulse = PulseAudioComponent(this)
pulse.setContext(this)
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
components.add(pulse)
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
guest.add("BL_FPS=0")
// What gamescope advertises as the refresh rate, and what a game reads as the display's.
// Left unset it says 60, and a 120 Hz panel then offers only 60 Hz in game settings.
guest.add("BL_REFRESH=" + Math.round(refreshHz()))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + File(logDir, "session-$stamp").path)
// Controllers. WinHandler is a Wine thing and there is none here, so the pad is published
// into the rings by PadBridge instead; the reader is the same interposer either way.
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
if (controllersOn) {
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path)
val rings = FakeInputWriter.getRingEnv(fakeInputDir)
if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings")
// SDL and Steam key their mapping database on bus+vendor+product: only a known
// identity gets the standard layout without the user configuring the pad by hand.
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
guest.add("FAKE_EVDEV_VIBRATION=1")
guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
// No udev runs in the runtime: SDL and hidapi scan /dev/input themselves, and the
// netlink monitor they open anyway is answered by the session shim's stand-in.
guest.add("SDL_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_JOYSTICK_HIDAPI=0")
if (File(Environment.getExternalStorageDirectory(), PAD_LOG_SWITCH).exists()) {
guest.add("FAKE_EVDEV_LOG=1")
}
padBridge = PadBridge(fakeInputDir).also { it.start() }
}
guest.add(LinuxRuntime.SESSION_SCRIPT)
guest.add(LinuxRuntime.MODE_STEAM)
// Android has no /dev/shm; the cache stands in for it and, unlike the real thing, keeps
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
FileUtils.clear(File(cacheDir, "shm"))
val binds = ArrayList<String>()
// Apps may not list /dev/input, so the fake nodes are bound in as the whole directory.
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
)
val hostEnv = EnvVars()
hostEnv.put("PROOT_LOADER", LinuxRuntime.prootLoader(this).path)
hostEnv.put("PROOT_TMP_DIR", cacheDir.path)
// proot links against a libtalloc beside it, and Android's linker does not search an
// executable's own directory: unnamed, the process dies before it starts and says so only
// in `logcat -b crash`.
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv.put("LD_LIBRARY_PATH", prootLibs)
val networkLink = LinuxNetworkLinkComponent(this, LinuxRuntime.rootDir(this))
networkLink.setContext(this)
networkLink.publish()
components.add(networkLink)
components.forEach { it.start() }
watchSessionLog()
val line = command.joinToString(" ") { it.replace(" ", "\\ ") }
sessionPid = ProcessHelper.exec(line, hostEnv.toStringArray(), root, { status ->
Log.i(TAG, "session ended: $status")
endSession(status)
}, null)
sessionStarted = true
Log.i(TAG, "session pid $sessionPid, log ${sessionLog.path}")
}
/**
* The libraries and scripts the session runs, refreshed from the apk at every launch.
*
* The runtime image carries its own copies, but a runtime installed months ago carries the
* copies of that day and a device has no way to replace them from outside the app. Staging
* them here is how a fix inside the session shim, the controller reader or one of the scripts
* reaches an already-installed runtime without a ~790 MB re-download. Each lands through a
* rename, so a session that still has one mapped keeps the file it opened.
*/
private fun stageSessionFiles(root: File) {
val files = arrayOf(
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
"usr/local/bin/bannerlator-steam-library" to "usr/local/bin/bannerlator-steam-library",
"usr/local/bin/bannerlator-seed-redists" to "usr/local/bin/bannerlator-seed-redists",
)
for ((asset, relative) in files) {
val target = File(root, relative)
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
assets.open("linuxfs/$asset").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage $relative", e)
} finally {
if (!installed) staged.delete()
}
if (!installed) Log.e(TAG, "$relative NOT staged")
}
// What every process in the session preloads. LD_PRELOAD in the environment would not
// survive: the Steam client rebuilds it for each process it starts and appends its own
// overlay entry without a separator, which silently drops whatever was there.
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
val etc = File(root, "etc").apply { mkdirs() }
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString()) || !staged.renameTo(File(etc, "ld.so.preload"))) {
staged.delete()
Log.e(TAG, "could not write ld.so.preload")
}
}
/** Mirrors the session script's "== STEP" milestones onto the screen while it starts. */
private fun watchSessionLog() {
val handler = Handler(Looper.getMainLooper())
Thread({
var shown = ""
while (!finishing) {
try {
Thread.sleep(500)
val text = FileUtils.readString(sessionLog) ?: continue
val step = text.lineSequence().lastOrNull { it.startsWith("== STEP") } ?: continue
val message = step.substringAfter("== STEP ").substringAfter(' ')
if (message != shown) {
shown = message
handler.post { if (statusView.visibility == View.VISIBLE) statusView.text = message }
}
} catch (e: InterruptedException) {
return@Thread
} catch (ignored: Exception) {
}
}
}, "session-log").start()
}
private fun endSession(status: Int) {
if (finishing) return
finishing = true
runOnUiThread {
if (status != 0) {
statusView.visibility = View.VISIBLE
statusView.text = getString(R.string.session_ended, status, sessionLogName())
}
// A moment on screen, so a failure is readable rather than a flash of black.
Handler(Looper.getMainLooper()).postDelayed({ finish() }, if (status == 0) 0 else 4000)
}
}
private fun sessionLogName(): String =
if (::sessionLog.isInitialized) "${LinuxRuntime.DEBUG_LOG_DIR}/${sessionLog.name}" else "-"
// ── Input ───────────────────────────────────────────────────────────────────────────────
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (padBridge?.onKeyEvent(event) == true) return true
return super.dispatchKeyEvent(event)
}
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (padBridge?.onMotionEvent(event) == true) return true
return super.dispatchGenericMotionEvent(event)
}
/**
* Touch as a mouse: where you touch is where the pointer goes, and a tap is a left click.
* The compositor's pointer space is a fixed 1920x1080 whatever the output size, so the view's
* coordinates are scaled into it.
*/
override fun onTouchEvent(event: MotionEvent): Boolean {
val width = surfaceView.width.takeIf { it > 0 } ?: return false
val height = surfaceView.height.takeIf { it > 0 } ?: return false
val action = when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> 0
MotionEvent.ACTION_MOVE -> 1
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> 2
else -> return false
}
val x = (event.x / width * 1920f).toInt().coerceIn(0, 1919)
val y = (event.y / height * 1080f).toInt().coerceIn(0, 1079)
WaylandCompositor.nativeSendPointer(action, x, y)
return true
}
// ── Lifecycle ───────────────────────────────────────────────────────────────────────────
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) goFullscreen()
}
private fun goFullscreen() {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
if (Build.VERSION.SDK_INT >= 28) {
window.attributes = window.attributes.apply {
layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
}
}
override fun onDestroy() {
finishing = true
vsyncRunning = false
padBridge?.stop()
// proot runs with --kill-on-exit, so killing it takes the whole guest tree with it.
if (sessionPid != -1) {
android.os.Process.killProcess(sessionPid)
sessionPid = -1
}
components.reversed().forEach {
try {
it.stop()
} catch (e: Exception) {
Log.w(TAG, "stopping ${it.javaClass.simpleName}", e)
}
}
components.clear()
FakeInputWriter.releaseAllRingSlots()
WaylandCompositor.setFirstFrameListener(null)
super.onDestroy()
}
companion object {
private const val TAG = "SessionActivity"
/** Turns the whole controller feature off, for a true baseline on a device we cannot reach. */
private const val NO_PAD_SWITCH = "Download/steamdeck-no-pad"
/** Traces every interposer call into the session log. */
private const val PAD_LOG_SWITCH = "Download/steamdeck-pad-log"
}
}
@@ -0,0 +1,111 @@
package com.the412banner.steamdeck.audio;
import android.content.Context;
import android.os.Process;
import android.util.Log;
import com.the412banner.steamdeck.core.FileUtils;
import com.the412banner.steamdeck.core.EnvironmentComponent;
import com.the412banner.steamdeck.core.ProcessHelper;
import com.the412banner.steamdeck.core.TarZst;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
/**
* PulseAudio 13.0 running in the app process, with Android's AAudio as its sink, so the guest's
* libpulse clients (Steam and everything it launches) have a server to talk to. The socket lives
* in the app's files directory and is bound into the session at its own path, so PULSE_SERVER
* needs no translating.
*
* <p>Ported down from Bannerlator's component: no sink suspend/resume and no route-change
* recreate — those need the pasink native client, and a session here is a foreground activity
* that does not background the way a game container does.
*/
public class PulseAudioComponent extends EnvironmentComponent {
private static final String TAG = "PulseAudio";
/** Where the guest reaches the daemon; the session exports PULSE_SERVER=unix:<this>. */
public static final String SOCKET_NAME = "PS0";
private final File workingDir;
private int pid = -1;
public PulseAudioComponent(Context context) {
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
}
public File socket() {
return new File(workingDir, SOCKET_NAME);
}
@Override
public void start() {
stop();
if (!workingDir.isDirectory()) {
//noinspection ResultOfMethodCallIgnored
workingDir.mkdirs();
FileUtils.chmod(workingDir, 0771);
}
// The loadable modules (module-aaudio-sink and the native protocol) ride in the apk; the
// daemon and its libraries come from the native library directory, the one place an app
// may execute a file from.
if (!new File(workingDir, "modules/arm64/module-aaudio-sink.so").isFile()) {
TarZst.extractAsset(context, "pulseaudio.tzst", workingDir);
}
copyFromLibraryDir();
//noinspection ResultOfMethodCallIgnored
socket().delete();
FileUtils.writeString(new File(workingDir, "default.pa"), String.join("\n",
"load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
+ socket().getAbsolutePath() + "\"",
// volume=1.0 is not optional: with no volume argument module-aaudio-sink defaults
// the sink to 0% and the session plays silence.
"load-module module-aaudio-sink performance_mode=1 adaptive=1 volume=1.0",
"set-default-sink AAudioSink"));
File modules = new File(workingDir, "modules/arm64");
ArrayList<String> env = new ArrayList<>();
env.add("LD_LIBRARY_PATH=/system/lib64:" + modules + ":" + workingDir.getAbsolutePath());
env.add("HOME=" + workingDir);
env.add("TMPDIR=" + workingDir);
String command = workingDir.getAbsolutePath() + "/libpulseaudio.so"
+ " --system=false --disable-shm=true --fail=false"
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1";
pid = ProcessHelper.exec(command, env.toArray(new String[0]), workingDir, null,
line -> Log.i(TAG, line));
}
@Override
public void stop() {
if (pid != -1) {
Process.killProcess(pid);
pid = -1;
}
}
private void copyFromLibraryDir() {
String[] libs = {"libltdl.so", "libpulseaudio.so", "libpulse.so",
"libpulsecommon-13.0.so", "libpulsecore-13.0.so"};
ClassLoader loader = PulseAudioComponent.class.getClassLoader();
for (String lib : libs) {
URL resource = loader != null ? loader.getResource("lib/arm64-v8a/" + lib) : null;
if (resource == null) {
Log.w(TAG, lib + " missing from the apk");
continue;
}
File destination = new File(workingDir, lib);
try (InputStream in = resource.openStream()) {
Files.copy(in, destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
FileUtils.chmod(destination, 0771);
} catch (Exception e) {
Log.w(TAG, "copy " + lib, e);
}
}
}
}
@@ -0,0 +1,6 @@
package com.the412banner.steamdeck.core;
/** One-argument callback, kept so the ported runtime classes read as they did in Bannerlator. */
public interface Callback<T> {
void call(T value);
}
@@ -0,0 +1,112 @@
package com.the412banner.steamdeck.core;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* The two fetches this app makes: the runtime catalog (a few hundred bytes of JSON) and the
* runtime tarball itself (~790 MB). Plain HttpURLConnection — nothing here needs a client library,
* and one fewer dependency is one fewer thing that can fail a release build.
*/
public final class Downloader {
private static final String TAG = "Downloader";
private static final int TIMEOUT_MS = 30_000;
private Downloader() {}
public static String downloadString(String url) {
HttpURLConnection connection = null;
try {
connection = open(url);
if (connection.getResponseCode() / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + connection.getResponseCode());
return null;
}
try (InputStream in = connection.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
FileUtils.copy(in, out);
return new String(out.toByteArray(), StandardCharsets.UTF_8);
}
} catch (Exception e) {
Log.w(TAG, "GET " + url, e);
return null;
} finally {
if (connection != null) connection.disconnect();
}
}
/**
* Downloads to {@code destination}, reporting a 0..1 fraction (or -1 when the server sends no
* length). {@code resume} continues a partial file with a Range request, which is what makes a
* 790 MB download survive a dropped connection instead of starting over.
*/
public static boolean downloadFile(String url, File destination, boolean resume,
Callback<Float> progress) {
HttpURLConnection connection = null;
long have = resume && destination.isFile() ? destination.length() : 0;
try {
connection = open(url);
if (have > 0) connection.setRequestProperty("Range", "bytes=" + have + "-");
int code = connection.getResponseCode();
boolean appending = code == HttpURLConnection.HTTP_PARTIAL;
if (code / 100 != 2) {
// The server ignored or refused the range: start the file again.
if (have > 0) {
connection.disconnect();
//noinspection ResultOfMethodCallIgnored
destination.delete();
return downloadFile(url, destination, false, progress);
}
Log.w(TAG, url + " -> HTTP " + code);
return false;
}
if (!appending) have = 0;
long length = connection.getContentLengthLong();
long total = length < 0 ? -1 : length + have;
File parent = destination.getParentFile();
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
parent.mkdirs();
long written = have;
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
OutputStream out = new FileOutputStream(destination, appending)) {
byte[] buffer = new byte[1 << 16];
long lastReport = 0;
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
out.write(buffer, 0, read);
written += read;
// A callback per 64 KB would be tens of thousands of UI hops; once per MB is
// enough to move a progress bar smoothly.
if (progress != null && written - lastReport > (1 << 20)) {
lastReport = written;
progress.call(total > 0 ? written / (float) total : -1f);
}
}
}
if (progress != null) progress.call(1f);
return total <= 0 || written >= total;
} catch (Exception e) {
Log.w(TAG, "download " + url, e);
return false;
} finally {
if (connection != null) connection.disconnect();
}
}
private static HttpURLConnection open(String url) throws java.io.IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(TIMEOUT_MS);
connection.setReadTimeout(TIMEOUT_MS);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("User-Agent", "SteamDeck-Android");
return connection;
}
}
@@ -0,0 +1,31 @@
package com.the412banner.steamdeck.core;
import java.util.LinkedHashMap;
import java.util.Map;
/** An ordered NAME=VALUE set, in the shape {@code ProcessBuilder} and proot want it. */
public class EnvVars {
private final Map<String, String> vars = new LinkedHashMap<>();
public EnvVars put(String name, String value) {
vars.put(name, value);
return this;
}
public void putAll(EnvVars other) {
if (other != null) vars.putAll(other.vars);
}
public String get(String name) { return vars.get(name); }
public boolean has(String name) { return vars.containsKey(name); }
public boolean isEmpty() { return vars.isEmpty(); }
public String[] toStringArray() {
String[] out = new String[vars.size()];
int i = 0;
for (Map.Entry<String, String> e : vars.entrySet()) out[i++] = e.getKey() + "=" + e.getValue();
return out;
}
}
@@ -0,0 +1,17 @@
package com.the412banner.steamdeck.core;
import android.content.Context;
/**
* One piece of a running session — the audio daemon, the network-link file, the session process
* itself. The session starts them in order and stops them in reverse.
*/
public abstract class EnvironmentComponent {
protected Context context;
public void setContext(Context context) { this.context = context; }
public abstract void start();
public abstract void stop();
}
@@ -0,0 +1,109 @@
package com.the412banner.steamdeck.core;
import android.content.Context;
import android.system.ErrnoException;
import android.system.Os;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
public final class FileUtils {
private static final String TAG = "FileUtils";
private FileUtils() {}
/** Recursive delete that does not follow symlinks — a rootfs is full of them. */
public static void delete(File file) {
if (file == null || !file.exists() && !isSymlink(file)) return;
if (file.isDirectory() && !isSymlink(file)) {
File[] children = file.listFiles();
if (children != null) for (File child : children) delete(child);
}
//noinspection ResultOfMethodCallIgnored
file.delete();
}
private static boolean isSymlink(File file) {
try {
return Files.isSymbolicLink(file.toPath());
} catch (Exception e) {
return false;
}
}
/** Empties a directory without removing it. */
public static void clear(File dir) {
if (dir == null || !dir.isDirectory()) return;
File[] children = dir.listFiles();
if (children != null) for (File child : children) delete(child);
}
public static boolean writeString(File file, String content) {
try {
File parent = file.getParentFile();
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
parent.mkdirs();
Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8));
return true;
} catch (IOException e) {
Log.w(TAG, "write " + file, e);
return false;
}
}
public static String readString(File file) {
try {
return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
return null;
}
}
public static void symlink(String target, String linkPath) {
try {
Os.symlink(target, linkPath);
} catch (ErrnoException e) {
Log.w(TAG, "symlink " + linkPath + " -> " + target + ": " + e.getMessage());
}
}
public static void chmod(File file, int mode) {
try {
Os.chmod(file.getAbsolutePath(), mode);
} catch (ErrnoException e) {
Log.w(TAG, "chmod " + file + ": " + e.getMessage());
}
}
/** Copies an asset out of the apk, creating the parent directory. */
public static boolean copyAsset(Context context, String assetPath, File destination) {
File parent = destination.getParentFile();
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
parent.mkdirs();
try (InputStream in = context.getAssets().open(assetPath);
OutputStream out = new FileOutputStream(destination)) {
copy(in, out);
return true;
} catch (IOException e) {
Log.w(TAG, "copy asset " + assetPath, e);
return false;
}
}
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1 << 16];
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) out.write(buffer, 0, read);
}
public static String sizeToString(long bytes) {
if (bytes >= 1L << 30) return String.format(java.util.Locale.US, "%.1f GB", bytes / (float) (1L << 30));
if (bytes >= 1L << 20) return String.format(java.util.Locale.US, "%.0f MB", bytes / (float) (1L << 20));
return bytes + " B";
}
}
@@ -0,0 +1,113 @@
package com.the412banner.steamdeck.core;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* Starts the session's host processes — proot and the audio daemon — and reports the exit status.
* The pid is read out of the hidden field on {@code java.lang.Process} because stopping a session
* means killing that exact process: proot runs with {@code --kill-on-exit}, so the whole guest
* tree goes with it.
*/
public final class ProcessHelper {
private static final String TAG = "ProcessHelper";
private ProcessHelper() {}
public static int exec(String command, String[] envp, File workingDir) {
return exec(command, envp, workingDir, null, null);
}
/**
* @param lineCallback receives stdout and stderr line by line, or null to discard both. The
* Linux session sends everything to its own log file, so nothing is passed
* here for it; the audio daemon is the one that benefits.
*/
public static int exec(String command, String[] envp, File workingDir,
Callback<Integer> terminationCallback, Callback<String> lineCallback) {
int pid = -1;
try {
ProcessBuilder builder = new ProcessBuilder(splitCommand(command));
if (workingDir != null) builder.directory(workingDir);
if (envp != null) {
builder.environment().clear();
for (String entry : envp) {
int eq = entry.indexOf('=');
if (eq > 0) builder.environment().put(entry.substring(0, eq), entry.substring(eq + 1));
}
}
builder.redirectErrorStream(true);
if (lineCallback == null) builder.redirectOutput(new File("/dev/null"));
Process process = builder.start();
Field pidField = process.getClass().getDeclaredField("pid");
pidField.setAccessible(true);
pid = pidField.getInt(process);
pidField.setAccessible(false);
Log.i(TAG, "started pid " + pid + ": " + command);
if (lineCallback != null) drain(process.getInputStream(), lineCallback);
if (terminationCallback != null) {
Thread waiter = new Thread(() -> {
int status = -1;
try {
status = process.waitFor();
} catch (InterruptedException ignored) {
} finally {
terminationCallback.call(status);
}
}, "proc-wait-" + pid);
waiter.setPriority(Thread.NORM_PRIORITY - 1);
waiter.start();
}
} catch (Exception e) {
Log.e(TAG, "exec " + command, e);
}
return pid;
}
private static void drain(InputStream stream, Callback<String> lineCallback) {
Thread thread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
lineCallback.call(line);
}
} catch (Exception ignored) {
}
}, "proc-out");
thread.setPriority(Thread.NORM_PRIORITY - 1);
thread.start();
}
/** Splits on spaces, honouring backslash-escaped spaces — paths under /data are full of them. */
public static String[] splitCommand(String command) {
List<String> parts = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean escaped = false;
for (int i = 0; i < command.length(); i++) {
char c = command.charAt(i);
if (escaped) {
current.append(c);
escaped = false;
} else if (c == '\\') {
escaped = true;
} else if (c == ' ') {
if (current.length() > 0) {
parts.add(current.toString());
current.setLength(0);
}
} else {
current.append(c);
}
}
if (current.length() > 0) parts.add(current.toString());
return parts.toArray(new String[0]);
}
}
@@ -0,0 +1,72 @@
package com.the412banner.steamdeck.core;
import android.content.Context;
import android.util.Log;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.zstandard.ZstdCompressorInputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The small zstd tarballs that ship inside the apk (the Turnip driver, the PulseAudio modules).
* The runtime rootfs is not one of these — it needs hard links and symlinks preserved, which
* {@link com.the412banner.steamdeck.runtime.LinuxRuntimeInstaller} handles itself.
*/
public final class TarZst {
private static final String TAG = "TarZst";
private TarZst() {}
public static boolean extractAsset(Context context, String assetPath, File destination) {
try (InputStream in = context.getAssets().open(assetPath)) {
return extract(in, destination);
} catch (Exception e) {
Log.e(TAG, "extract " + assetPath, e);
return false;
}
}
public static boolean extract(InputStream source, File destination) {
//noinspection ResultOfMethodCallIgnored
destination.mkdirs();
try (InputStream in = new ZstdCompressorInputStream(new BufferedInputStream(source, 1 << 16));
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
String base = destination.getCanonicalPath() + File.separator;
TarArchiveEntry entry;
while ((entry = tar.getNextTarEntry()) != null) {
File file = new File(destination, entry.getName());
if (!file.getCanonicalPath().startsWith(base)) continue;
if (entry.isDirectory()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
continue;
}
File parent = file.getParentFile();
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
parent.mkdirs();
if (entry.isSymbolicLink()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
FileUtils.symlink(entry.getLinkName(), file.getAbsolutePath());
continue;
}
if (!entry.isFile()) continue;
try (OutputStream out = new FileOutputStream(file)) {
FileUtils.copy(tar, out);
}
if ((entry.getMode() & 0111) != 0) //noinspection ResultOfMethodCallIgnored
file.setExecutable(true, false);
}
return true;
} catch (Exception e) {
Log.e(TAG, "extract into " + destination, e);
return false;
}
}
}
@@ -0,0 +1,118 @@
package com.the412banner.steamdeck.gpu;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.the412banner.steamdeck.core.FileUtils;
import com.the412banner.steamdeck.core.TarZst;
import org.json.JSONObject;
import java.io.File;
/**
* The Vulkan driver the in-app compositor runs on. It has to be Turnip: the system Adreno driver
* does not implement VK_EXT_image_drm_format_modifier, so importing the dma-bufs gamescope hands
* over fails and the session renders nothing. Two builds ship in the apk, one per Adreno
* generation, and the GPU decides which is unpacked.
*
* <p>The guest's own Turnip is a different copy entirely — a glibc build inside the rootfs, found
* through its ICD manifest. This one is the bionic build the app process loads through adrenotools.
*/
public final class TurnipDriver {
private static final String TAG = "TurnipDriver";
/** Adreno 7xx (8 Gen 2/3, e.g. the Pocket FIT's A750). */
private static final String DRIVER_A7XX = "turnip25.1.0";
/** Adreno 8xx (8 Elite, e.g. a Fold 8's A830). */
private static final String DRIVER_A8XX = "turnip-sdk36";
/** Overrides the pick, for a device we cannot reach: a7xx, a8xx or system. */
private static final String OVERRIDE_FILE = "Download/steamdeck-driver";
private final Context context;
private final File contentDir;
public TurnipDriver(Context context) {
this.context = context;
this.contentDir = new File(context.getFilesDir(), "graphics_driver");
}
/** Absolute directory holding the driver, with a trailing slash — adrenotools wants both. */
public String driverPath(String driverId) {
return new File(contentDir, driverId).getAbsolutePath() + "/";
}
public String libraryName(String driverId) {
File meta = new File(new File(contentDir, driverId), "meta.json");
String content = FileUtils.readString(meta);
if (content == null) return null;
try {
return new JSONObject(content).optString("libraryName", null);
} catch (Exception e) {
Log.w(TAG, "meta.json for " + driverId, e);
return null;
}
}
/**
* Unpacks the driver this device needs and returns its id, or null to fall back to the system
* Vulkan loader (which means a black session on Adreno, but is better than refusing to start
* on a GPU neither build covers).
*/
public String install() {
String id = choose();
if (id == null) return null;
File dir = new File(contentDir, id);
if (!new File(dir, "meta.json").isFile()) {
FileUtils.delete(dir);
if (!TarZst.extractAsset(context, "graphics_driver/adrenotools-" + id + ".tzst", dir)) {
Log.e(TAG, "could not unpack " + id);
FileUtils.delete(dir);
return null;
}
}
String library = libraryName(id);
if (library == null || !new File(dir, library).isFile()) {
Log.e(TAG, id + " unpacked without " + library);
return null;
}
Log.i(TAG, "graphics driver " + id + " (" + library + ")");
return id;
}
private String choose() {
File override = new File(Environment.getExternalStorageDirectory(), OVERRIDE_FILE);
String forced = override.isFile() ? FileUtils.readString(override) : null;
if (forced != null) {
forced = forced.trim().toLowerCase(java.util.Locale.US);
Log.i(TAG, "driver forced by " + override + ": " + forced);
if (forced.startsWith("system")) return null;
if (forced.startsWith("a8")) return DRIVER_A8XX;
if (forced.startsWith("a7")) return DRIVER_A7XX;
}
String model = gpuModel();
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
if (model != null) {
// "Adreno750", "adreno_830" — the generation is the first digit of the three.
java.util.regex.Matcher m = java.util.regex.Pattern.compile("(\\d)\\d\\d").matcher(model);
if (m.find()) {
char generation = m.group(1).charAt(0);
if (generation >= '8') return DRIVER_A8XX;
if (generation == '7') return DRIVER_A7XX;
}
}
// Nothing to go on: Android 16 shipped with the 8 Elite, so treat a new device as 8xx.
return android.os.Build.VERSION.SDK_INT >= 36 ? DRIVER_A8XX : DRIVER_A7XX;
}
/** KGSL names the GPU here, and this file is world-readable where /dev/kgsl-3d0 is not. */
private static String gpuModel() {
for (String path : new String[]{
"/sys/class/kgsl/kgsl-3d0/gpu_model",
"/sys/class/kgsl/kgsl-3d0/gpu_chipid"}) {
String value = FileUtils.readString(new File(path));
if (value != null && !value.trim().isEmpty()) return value.trim();
}
return null;
}
}
@@ -0,0 +1,689 @@
package com.the412banner.steamdeck.input;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
/**
* Fake evdev transport for the emulated Xbox 360 pads.
*
* <p>Replaces the old append-file transport (which desynced after ~15 min when an
* unlooped {@code channel.write} left a partial event in the file and the
* IOException was swallowed) with a fixed-size mmap RING BUFFER shared with the
* native reader in {@code fakeinput.cpp}. Delta events are published into the
* ring under a monotonic {@code write_seq}; an authoritative absolute-state
* snapshot is published alongside under a seqlock so the native reader can replay
* a full keyframe to heal any desync (open, ring overflow) without duplicate
* input. Ring layout (magic/version/offsets) is a paired ABI with the native
* {@code FakeInputRingHeader} — keep the two in lockstep.
*/
public class FakeInputWriter {
private static final String TAG = "FakeInputWriter";
// Event types
public static final short EV_SYN = 0x00;
public static final short EV_KEY = 0x01;
public static final short EV_ABS = 0x03;
public static final short EV_MSC = 0x04;
// Event codes
public static final short MSC_SCAN = 0x04;
public static final short SYN_REPORT = 0x00;
// Xbox 360 controller button codes
public static final short BTN_A = 0x130;
public static final short BTN_B = 0x131;
public static final short BTN_X = 0x133;
public static final short BTN_Y = 0x134;
public static final short BTN_TL = 0x136;
public static final short BTN_TR = 0x137;
public static final short BTN_SELECT = 0x13A;
public static final short BTN_START = 0x13B;
public static final short BTN_THUMBL = 0x13D;
public static final short BTN_MODE = 0x13C;
public static final short BTN_THUMBR = 0x13E;
// Absolute axis codes
public static final short ABS_X = 0x00;
public static final short ABS_Y = 0x01;
public static final short ABS_RX = 0x03;
public static final short ABS_RY = 0x04;
public static final short ABS_GAS = 0x09;
public static final short ABS_BRAKE = 0x0A;
public static final short ABS_HAT0X = 0x10;
public static final short ABS_HAT0Y = 0x11;
// Button mapping (bit i of the snapshot buttons word)
private static final short[] BUTTON_MAP = {
BTN_A, BTN_B, BTN_X, BTN_Y, BTN_TL, BTN_TR,
BTN_SELECT, BTN_START, BTN_THUMBL, BTN_THUMBR,
BTN_MODE
};
/** Bit 10 of the snapshot word. The first ten are GamepadState's own bit order; the Steam
* button is not, because GamepadState keeps 10 and 11 for the triggers. */
private static final int SNAPSHOT_IDX_MODE = 10;
private static final int EVENT_SIZE = 24;
static final int MAX_EVENTS_PER_UPDATE = 32;
private static final int BUFFER_SIZE = EVENT_SIZE * MAX_EVENTS_PER_UPDATE;
private static final int MAX_FAKE_INPUT_SLOTS = 4;
// Ring layout — MUST match FakeInputRingHeader in fakeinput.cpp.
private static final int RING_CAPACITY_EVENTS = 4096;
private static final int RING_HEADER_SIZE = 64;
private static final int RING_SIZE = RING_HEADER_SIZE + (RING_CAPACITY_EVENTS * EVENT_SIZE);
private static final int RING_MAGIC = 0x46494252; // FIBR
private static final int RING_VERSION = 2;
private static final int RING_MAGIC_OFFSET = 0;
private static final int RING_VERSION_OFFSET = 4;
private static final int RING_EVENT_SIZE_OFFSET = 8;
private static final int RING_CAPACITY_OFFSET = 12;
private static final int RING_WRITE_SEQ_OFFSET = 16;
private static final int RING_GENERATION_OFFSET = 24;
// Authoritative absolute-state snapshot the native reader replays as a full
// keyframe to heal any delta-stream desync. Written under a seqlock
// (RING_SNAPSHOT_SEQ_OFFSET: odd = write in progress).
private static final int RING_SNAPSHOT_SEQ_OFFSET = 32;
private static final int RING_SNAPSHOT_BUTTONS_OFFSET = 40;
private static final int RING_SNAPSHOT_AXES_OFFSET = 44; // short[8]
private static final String RING_DIR_NAME = "fakeinput-rings";
private static final Object RING_LOCK = new Object();
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
static {
System.loadLibrary("sdnative");
}
private static native void nativeStoreFence();
private final File eventFile;
private final int slot;
private final ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
private boolean isOpen = false;
private volatile boolean destroyed = false;
private final boolean[] prevButtonStates = new boolean[12];
private int prevThumbLX, prevThumbLY, prevThumbRX, prevThumbRY;
private int prevTriggerL, prevTriggerR;
private int prevHatX, prevHatY;
private boolean hasChanges = false;
// If a publish fails after prev* state has already advanced, the next frame
// must re-emit the whole state once; otherwise an unchanged control would stay
// silent and the ring snapshot would never catch up.
private boolean pendingFullResend = false;
private boolean forceResend = false;
public FakeInputWriter(String fakeInputPath, int slot) {
this.slot = slot;
this.eventFile = new File(fakeInputPath, "event" + slot);
this.buffer.order(ByteOrder.LITTLE_ENDIAN);
}
private static final class RingSlot {
ByteBuffer data;
File ringFile;
FileChannel ringChannel;
RandomAccessFile ringRaf;
String exportPath;
long generation;
boolean active;
boolean everActivated;
}
// ---- Static ring management (shared by all writers + the env exporter) ----
public static void prepareRingSlots(File fakeInputDir, int slotCount) {
int boundedSlotCount = Math.max(0, Math.min(slotCount, MAX_FAKE_INPUT_SLOTS));
synchronized (RING_LOCK) {
for (int slot = 0; slot < boundedSlotCount; slot++) {
ensureRingSlotLocked(slot, fakeInputDir);
}
}
}
/**
* Prepares every slot ring and returns the {@code slot=path;...} spec the native
* reader consumes via FAKE_EVDEV_MEMFD_PATHS.
*/
public static String getRingEnv(File fakeInputDir) {
synchronized (RING_LOCK) {
prepareRingSlotsLocked(fakeInputDir, MAX_FAKE_INPUT_SLOTS);
return buildRingEnvLocked();
}
}
public static void releaseAllRingSlots() {
synchronized (RING_LOCK) {
for (int slot = 0; slot < RING_SLOTS.length; slot++) {
releaseRingSlotLocked(slot);
}
}
}
private static String buildRingEnvLocked() {
StringBuilder builder = new StringBuilder();
for (int slot = 0; slot < RING_SLOTS.length; slot++) {
RingSlot ringSlot = RING_SLOTS[slot];
if (ringSlot == null || ringSlot.data == null || ringSlot.exportPath == null) {
continue;
}
if (builder.length() > 0) {
builder.append(';');
}
builder.append(slot).append('=').append(ringSlot.exportPath);
}
return builder.toString();
}
private static File getRingDir(File fakeInputDir) {
if (fakeInputDir == null) {
return null;
}
File inputDir = fakeInputDir.getAbsoluteFile();
File parent = inputDir.getParentFile();
return new File(parent != null ? parent : inputDir, RING_DIR_NAME);
}
private static File getRingFile(File fakeInputDir, int slot) {
File ringDir = getRingDir(fakeInputDir);
return ringDir != null ? new File(ringDir, "ring" + slot) : null;
}
private static String getCanonicalOrAbsolutePath(File file) {
try {
return file.getCanonicalPath();
} catch (IOException e) {
return file.getAbsolutePath();
}
}
private static void initializeRingHeader(ByteBuffer data) {
data.order(ByteOrder.LITTLE_ENDIAN);
data.putInt(RING_MAGIC_OFFSET, RING_MAGIC);
data.putInt(RING_VERSION_OFFSET, RING_VERSION);
data.putInt(RING_EVENT_SIZE_OFFSET, EVENT_SIZE);
data.putInt(RING_CAPACITY_OFFSET, RING_CAPACITY_EVENTS);
data.putLong(RING_WRITE_SEQ_OFFSET, 0L);
data.putLong(RING_GENERATION_OFFSET, 0L);
data.putLong(RING_SNAPSHOT_SEQ_OFFSET, 0L);
data.putInt(RING_SNAPSHOT_BUTTONS_OFFSET, 0);
for (int i = 0; i < 8; i++) {
data.putShort(RING_SNAPSHOT_AXES_OFFSET + (i * 2), (short) 0);
}
}
private static void releaseRingSlotLocked(int slot) {
RingSlot ringSlot = RING_SLOTS[slot];
if (ringSlot == null) {
return;
}
ringSlot.data = null;
if (ringSlot.ringChannel != null) {
try {
ringSlot.ringChannel.close();
} catch (IOException ignored) {
}
ringSlot.ringChannel = null;
}
if (ringSlot.ringRaf != null) {
try {
ringSlot.ringRaf.close();
} catch (IOException ignored) {
}
ringSlot.ringRaf = null;
}
if (ringSlot.ringFile != null && ringSlot.ringFile.exists()) {
ringSlot.ringFile.delete();
}
RING_SLOTS[slot] = null;
}
private static void prepareRingSlotsLocked(File fakeInputDir, int slotCount) {
int boundedSlotCount = Math.max(0, Math.min(slotCount, MAX_FAKE_INPUT_SLOTS));
for (int slot = 0; slot < boundedSlotCount; slot++) {
ensureRingSlotLocked(slot, fakeInputDir);
}
}
private static RingSlot ensureRingSlotLocked(int slot, File fakeInputDir) {
if (slot < 0 || slot >= MAX_FAKE_INPUT_SLOTS || fakeInputDir == null) {
return null;
}
File desiredRingFile = getRingFile(fakeInputDir, slot);
if (desiredRingFile == null) {
return null;
}
desiredRingFile = desiredRingFile.getAbsoluteFile();
RingSlot existing = RING_SLOTS[slot];
if (existing != null && existing.data != null) {
if (existing.ringFile != null && existing.ringFile.equals(desiredRingFile)) {
return existing;
}
releaseRingSlotLocked(slot);
}
RingSlot fileRingSlot = createFileRingSlotLocked(slot, desiredRingFile);
if (fileRingSlot != null) {
RING_SLOTS[slot] = fileRingSlot;
return fileRingSlot;
}
return null;
}
private static RingSlot createFileRingSlotLocked(int slot, File ringFile) {
File ringDir = ringFile.getParentFile();
if (ringDir == null || (!ringDir.exists() && !ringDir.mkdirs())) {
Log.e(TAG, "Failed to create fake input ring directory for slot " + slot);
return null;
}
RandomAccessFile raf = null;
FileChannel channel = null;
try {
raf = new RandomAccessFile(ringFile, "rw");
raf.setLength(RING_SIZE);
channel = raf.getChannel();
ByteBuffer data = channel.map(FileChannel.MapMode.READ_WRITE, 0, RING_SIZE);
initializeRingHeader(data);
RingSlot ringSlot = new RingSlot();
ringSlot.data = data;
ringSlot.ringFile = ringFile.getAbsoluteFile();
ringSlot.ringRaf = raf;
ringSlot.ringChannel = channel;
ringSlot.exportPath = getCanonicalOrAbsolutePath(ringFile);
Log.i(TAG, "Created fake input file ring for slot " + slot + ": " + ringSlot.exportPath);
return ringSlot;
} catch (IOException e) {
Log.e(TAG, "Failed to create fake input file ring for slot " + slot + ": " + e.getMessage());
if (channel != null) {
try {
channel.close();
} catch (IOException ignored) {
}
}
if (raf != null) {
try {
raf.close();
} catch (IOException ignored) {
}
}
return null;
}
}
private RingSlot ensureRingSlot() {
synchronized (RING_LOCK) {
return ensureRingSlotLocked(this.slot, this.eventFile.getParentFile());
}
}
private boolean activateRingSlot() {
RingSlot ringSlot = ensureRingSlot();
if (ringSlot == null || ringSlot.data == null) {
return false;
}
synchronized (ringSlot) {
if (!ringSlot.active) {
if (ringSlot.everActivated) {
ringSlot.generation++;
} else {
ringSlot.everActivated = true;
}
ringSlot.data.putLong(RING_WRITE_SEQ_OFFSET, 0L);
clearSnapshotLocked(ringSlot.data);
ringSlot.data.putLong(RING_GENERATION_OFFSET, ringSlot.generation);
ringSlot.active = true;
Log.d(TAG, "Activated fake input ring for slot " + this.slot
+ " generation=" + ringSlot.generation);
}
}
return true;
}
private void deactivateRingSlot() {
RingSlot ringSlot;
synchronized (RING_LOCK) {
ringSlot = this.slot >= 0 && this.slot < RING_SLOTS.length ? RING_SLOTS[this.slot] : null;
}
if (ringSlot == null) {
return;
}
synchronized (ringSlot) {
if (ringSlot.active && ringSlot.data != null) {
ringSlot.generation++;
ringSlot.data.putLong(RING_WRITE_SEQ_OFFSET, 0L);
clearSnapshotLocked(ringSlot.data);
ringSlot.data.putLong(RING_GENERATION_OFFSET, ringSlot.generation);
Log.i(TAG, "Deactivated fake input ring for slot " + this.slot
+ " generation=" + ringSlot.generation);
}
ringSlot.active = false;
}
}
private boolean flushBufferToRing() {
RingSlot ringSlot = ensureRingSlot();
if (ringSlot == null || ringSlot.data == null) {
return false;
}
// Raw byte copy: endianness is irrelevant since we never interpret
// multi-byte fields out of the source here.
ByteBuffer source = this.buffer.duplicate();
synchronized (ringSlot) {
ByteBuffer ring = ringSlot.data;
long writeSeq = ring.getLong(RING_WRITE_SEQ_OFFSET);
int sourceLimit = source.limit();
while (source.remaining() >= EVENT_SIZE) {
int eventIndex = (int) (writeSeq % RING_CAPACITY_EVENTS);
int targetOffset = RING_HEADER_SIZE + (eventIndex * EVENT_SIZE);
// Bulk-copy one event (EVENT_SIZE bytes) instead of byte-by-byte.
// Bound the source to a single event, position the ring at the slot,
// then let put(ByteBuffer) move the whole block. Mutating the ring's
// Java position is harmless: the native reader uses a raw pointer, not
// this position. API-26 safe (no JDK 13+ absolute bulk put).
source.limit(source.position() + EVENT_SIZE);
ring.position(targetOffset);
ring.put(source);
source.limit(sourceLimit);
writeSeq++;
}
// Publish the resulting absolute state. prev* now hold the post-update
// values, i.e. exactly the state the events just written transition to.
writeSnapshotLocked(ring);
nativeStoreFence();
ring.putLong(RING_WRITE_SEQ_OFFSET, writeSeq);
}
return true;
}
// Publishes the full absolute controller state for the native reader to replay
// as a keyframe. seqlock: bump to odd, write fields, bump to even, with
// store-store fences so the reader's acquire loads see consistent payloads.
private void writeSnapshotLocked(ByteBuffer ring) {
int buttons = 0;
for (int i = 0; i < BUTTON_MAP.length; i++) {
if (this.prevButtonStates[i]) {
buttons |= (1 << i);
}
}
long seq = ring.getLong(RING_SNAPSHOT_SEQ_OFFSET);
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 1); // odd: write in progress
nativeStoreFence();
ring.putInt(RING_SNAPSHOT_BUTTONS_OFFSET, buttons);
// Axis order must match the native kSnapshotAxisCodes:
// X, Y, RX, RY, GAS(=triggerR), BRAKE(=triggerL), HAT0X, HAT0Y.
ring.putShort(RING_SNAPSHOT_AXES_OFFSET, clampShort(this.prevThumbLX));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 2, clampShort(this.prevThumbLY));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 4, clampShort(this.prevThumbRX));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 6, clampShort(this.prevThumbRY));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 8, clampShort(this.prevTriggerR));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 10, clampShort(this.prevTriggerL));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 12, clampShort(this.prevHatX));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 14, clampShort(this.prevHatY));
nativeStoreFence();
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 2); // even: write complete
}
private static short clampShort(int value) {
if (value > Short.MAX_VALUE) {
return Short.MAX_VALUE;
}
if (value < Short.MIN_VALUE) {
return Short.MIN_VALUE;
}
return (short) value;
}
private static void clearSnapshotLocked(ByteBuffer ring) {
long seq = ring.getLong(RING_SNAPSHOT_SEQ_OFFSET);
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 1);
nativeStoreFence();
ring.putInt(RING_SNAPSHOT_BUTTONS_OFFSET, 0);
for (int i = 0; i < 8; i++) {
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + (i * 2), (short) 0);
}
nativeStoreFence();
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 2);
}
private boolean flushBuffer() {
return flushBufferToRing();
}
public synchronized boolean open() {
if (destroyed)
return false;
if (isOpen)
return true;
try {
eventFile.getParentFile().mkdirs();
if (!eventFile.exists()) {
eventFile.createNewFile();
}
if (!activateRingSlot()) {
if (eventFile.exists()) {
eventFile.delete();
}
Log.e(TAG, "Failed to open fake input mmap ring: " + eventFile.getAbsolutePath());
return false;
}
isOpen = true;
Log.i(TAG, "Opened fake input: " + eventFile.getAbsolutePath());
return true;
} catch (IOException e) {
Log.e(TAG, "Failed to open: " + e.getMessage());
return false;
}
}
public synchronized void close() {
isOpen = false;
}
/**
* Reset all input state to neutral (all buttons released, axes zeroed).
* This keeps the ring active so games that cache the file descriptor can still
* reconnect.
*/
public synchronized void reset() {
if (!isOpen && !open())
return;
buffer.clear();
hasChanges = false;
// Release all buttons
for (int i = 0; i < BUTTON_MAP.length; i++) {
if (prevButtonStates[i]) {
prevButtonStates[i] = false;
writeEvent(EV_MSC, MSC_SCAN, BUTTON_MAP[i]);
writeEvent(EV_KEY, BUTTON_MAP[i], 0);
}
}
// Zero all axes
if (prevThumbLX != 0) {
prevThumbLX = 0;
writeEvent(EV_ABS, ABS_X, 0);
}
if (prevThumbLY != 0) {
prevThumbLY = 0;
writeEvent(EV_ABS, ABS_Y, 0);
}
if (prevThumbRX != 0) {
prevThumbRX = 0;
writeEvent(EV_ABS, ABS_RX, 0);
}
if (prevThumbRY != 0) {
prevThumbRY = 0;
writeEvent(EV_ABS, ABS_RY, 0);
}
if (prevTriggerL != 0) {
prevTriggerL = 0;
writeEvent(EV_ABS, ABS_BRAKE, 0);
}
if (prevTriggerR != 0) {
prevTriggerR = 0;
writeEvent(EV_ABS, ABS_GAS, 0);
}
if (prevHatX != 0) {
prevHatX = 0;
writeEvent(EV_ABS, ABS_HAT0X, 0);
}
if (prevHatY != 0) {
prevHatY = 0;
writeEvent(EV_ABS, ABS_HAT0Y, 0);
}
if (hasChanges) {
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Reset write error: fake input mmap ring unavailable");
}
Log.i(TAG, "Reset fake input to neutral state: " + eventFile.getAbsolutePath());
}
public synchronized void softRelease() {
reset();
close();
Log.i(TAG, "Soft released fake input: " + eventFile.getAbsolutePath());
}
/**
* Full destroy - reset, tear the ring generation down, and delete the discovery node.
*/
public synchronized void destroy() {
destroyed = true;
reset();
close();
deactivateRingSlot();
if (eventFile != null && eventFile.exists()) {
boolean deleted = eventFile.delete();
Log.i(TAG, "Deleted fake input discovery node: " + eventFile.getAbsolutePath() + " (" + deleted + ")");
}
}
private void writeEvent(short type, short code, int value) {
long timeMs = System.currentTimeMillis();
buffer.putLong(timeMs / 1000);
buffer.putLong((timeMs % 1000) * 1000);
buffer.putShort(type);
buffer.putShort(code);
buffer.putInt(value);
hasChanges = true;
}
private void writeButton(int idx, boolean pressed) {
if (idx < 0 || idx >= BUTTON_MAP.length)
return;
if (!forceResend && prevButtonStates[idx] == pressed)
return;
prevButtonStates[idx] = pressed;
writeEvent(EV_MSC, MSC_SCAN, BUTTON_MAP[idx]);
writeEvent(EV_KEY, BUTTON_MAP[idx], pressed ? 1 : 0);
}
public synchronized void writeGamepadState(GamepadState state) {
if (!isOpen && !open())
return;
// Keep the ring delta-first for latency. Full event frames are only used as
// a one-shot repair after a failed publish; normal open/overflow recovery is
// handled by the native snapshot keyframe.
forceResend = pendingFullResend;
pendingFullResend = false;
if (forceResend) {
Log.d(TAG, "Re-emitting full gamepad state after failed publish for slot " + slot);
}
buffer.clear();
hasChanges = false;
// Buttons
for (int i = 0; i < 10; i++) {
writeButton(i, state.isPressed((byte) i));
}
// The Steam button. In a Linux session this is what opens the client's own in-game menu,
// and the client looks for it where an Xbox pad keeps it: evdev BTN_MODE, which SDL then
// reports as button 8 - exactly the "guide:b8" in the mapping Steam writes for this pad.
writeButton(SNAPSHOT_IDX_MODE,
state.isPressed(GamepadState.IDX_BUTTON_MODE));
// Sticks
int lx = (int) (state.thumbLX * 32767);
int ly = (int) (state.thumbLY * 32767);
int rx = (int) (state.thumbRX * 32767);
int ry = (int) (state.thumbRY * 32767);
// The fake evdev ring is event-queue semantics, so unchanged axes normally
// stay silent; forceResend overrides that to emit a complete keyframe.
if (forceResend || lx != prevThumbLX) {
prevThumbLX = lx;
writeEvent(EV_ABS, ABS_X, lx);
}
if (forceResend || ly != prevThumbLY) {
prevThumbLY = ly;
writeEvent(EV_ABS, ABS_Y, ly);
}
if (forceResend || rx != prevThumbRX) {
prevThumbRX = rx;
writeEvent(EV_ABS, ABS_RX, rx);
}
if (forceResend || ry != prevThumbRY) {
prevThumbRY = ry;
writeEvent(EV_ABS, ABS_RY, ry);
}
// L2 and R2 (Triggers)
int tl = (int) (state.triggerL * 255);
int tr = (int) (state.triggerR * 255);
if (forceResend || tl != prevTriggerL) {
prevTriggerL = tl;
writeEvent(EV_ABS, ABS_BRAKE, tl);
}
if (forceResend || tr != prevTriggerR) {
prevTriggerR = tr;
writeEvent(EV_ABS, ABS_GAS, tr);
}
// D-pad
int hatX = state.dpad[3] ? -1 : (state.dpad[1] ? 1 : 0);
int hatY = state.dpad[0] ? -1 : (state.dpad[2] ? 1 : 0);
if (forceResend || hatX != prevHatX) {
prevHatX = hatX;
writeEvent(EV_ABS, ABS_HAT0X, hatX);
}
if (forceResend || hatY != prevHatY) {
prevHatY = hatY;
writeEvent(EV_ABS, ABS_HAT0Y, hatY);
}
// Detect change else no need to write
if (hasChanges) {
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer()) {
Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable");
// Couldn't publish; re-assert the whole state on the next frame.
pendingFullResend = true;
}
}
forceResend = false;
}
public boolean isOpen() {
return isOpen;
}
}
@@ -0,0 +1,58 @@
package com.the412banner.steamdeck.input;
public class GamepadState {
/** Bit index of the Steam/Guide button; 0-9 are the face/shoulder/stick buttons. */
public static final byte IDX_BUTTON_MODE = 12;
public float thumbLX = 0;
public float thumbLY = 0;
public float thumbRX = 0;
public float thumbRY = 0;
public float triggerL = 0;
public float triggerR = 0;
public final boolean[] dpad = new boolean[4];
public short buttons = 0;
public void setPressed(int buttonIdx, boolean pressed) {
int flag = 1<<buttonIdx;
if (pressed) {
buttons |= flag;
}
else buttons &= ~flag;
}
public boolean isPressed(int buttonIdx) {
return (buttons & (1<<buttonIdx)) != 0;
}
public byte getDPadX() {
return (byte)(dpad[1] ? 1 : (dpad[3] ? -1 : 0));
}
public byte getDPadY() {
return (byte)(dpad[0] ? -1 : (dpad[2] ? 1 : 0));
}
public void copy(GamepadState other) {
thumbLX = other.thumbLX;
thumbLY = other.thumbLY;
thumbRX = other.thumbRX;
thumbRY = other.thumbRY;
triggerL = other.triggerL;
triggerR = other.triggerR;
buttons = other.buttons;
System.arraycopy(other.dpad, 0, dpad, 0, dpad.length);
}
public void reset() {
thumbLX = 0;
thumbLY = 0;
thumbRX = 0;
thumbRY = 0;
triggerL = 0;
triggerR = 0;
buttons = 0;
java.util.Arrays.fill(dpad, false);
}
}
@@ -0,0 +1,131 @@
package com.the412banner.steamdeck.input;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import java.io.File;
/**
* A physical controller, republished as a synthetic evdev device the Steam client can see.
*
* <p>Android hands a gamepad to the foreground activity as key and motion events; the Steam client
* inside the runtime never sees that. What it does scan is {@code /dev/input}, which the session's
* interposer (libfakeinput.so) serves out of the shared-memory rings written here. So the path is:
* Android event → {@link GamepadState} → {@link FakeInputWriter} ring → interposer → evdev node →
* SDL → Big Picture.
*
* <p>The identity the interposer reports is an Xbox 360 pad, which is what makes SDL apply a known
* mapping without the user configuring anything.
*/
public final class PadBridge {
private static final String TAG = "PadBridge";
/** Slot 0 is the one the session exports; extra slots would each show as another pad. */
private static final int SLOT = 0;
private static final float DEAD_ZONE = 0.12f;
private final FakeInputWriter writer;
private final GamepadState state = new GamepadState();
private boolean open;
public PadBridge(File fakeInputDir) {
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
}
/** Opens the ring; safe to call more than once. */
public synchronized boolean start() {
if (!open) {
open = writer.open();
Log.i(TAG, "ring slot " + SLOT + (open ? " open" : " NOT open"));
}
return open;
}
public synchronized void stop() {
if (open) {
state.reset();
writer.writeGamepadState(state);
writer.close();
open = false;
}
}
/** True when the device this event came from is a gamepad or joystick, not the touchscreen. */
public static boolean isFromController(InputDevice device) {
if (device == null) return false;
int sources = device.getSources();
return (sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD
|| (sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK;
}
/** @return true when the event was a pad button and has been consumed. */
public synchronized boolean onKeyEvent(KeyEvent event) {
if (!isFromController(event.getDevice())) return false;
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BUTTON_A: state.setPressed(0, pressed); break;
case KeyEvent.KEYCODE_BUTTON_B: state.setPressed(1, pressed); break;
case KeyEvent.KEYCODE_BUTTON_X: state.setPressed(2, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Y: state.setPressed(3, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L1: state.setPressed(4, pressed); break;
case KeyEvent.KEYCODE_BUTTON_R1: state.setPressed(5, pressed); break;
case KeyEvent.KEYCODE_BUTTON_SELECT:
case KeyEvent.KEYCODE_BACK: state.setPressed(6, pressed); break;
case KeyEvent.KEYCODE_BUTTON_START:
case KeyEvent.KEYCODE_MENU: state.setPressed(7, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: state.setPressed(8, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: state.setPressed(9, pressed); break;
// The client's own in-game menu is opened by this one; the interposer publishes it as
// BTN_MODE, which SDL reports as the "guide" button.
case KeyEvent.KEYCODE_BUTTON_MODE:
case KeyEvent.KEYCODE_HOME: state.setPressed(GamepadState.IDX_BUTTON_MODE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L2: state.triggerL = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_BUTTON_R2: state.triggerR = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_DPAD_UP: state.dpad[0] = pressed; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: state.dpad[1] = pressed; break;
case KeyEvent.KEYCODE_DPAD_DOWN: state.dpad[2] = pressed; break;
case KeyEvent.KEYCODE_DPAD_LEFT: state.dpad[3] = pressed; break;
default: return false;
}
publish();
return true;
}
/** @return true when the event was a pad's sticks/triggers and has been consumed. */
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isFromController(event.getDevice())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
state.thumbLX = axis(event, MotionEvent.AXIS_X);
// Android's Y axis grows downwards and evdev's ABS_Y does too, so no flip here: what the
// pad reports as "down" is what the client is told.
state.thumbLY = axis(event, MotionEvent.AXIS_Y);
state.thumbRX = axis(event, MotionEvent.AXIS_Z);
state.thumbRY = axis(event, MotionEvent.AXIS_RZ);
float lt = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
float rt = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
// Some pads only report the triggers on BRAKE/GAS.
if (lt == 0f) lt = event.getAxisValue(MotionEvent.AXIS_BRAKE);
if (rt == 0f) rt = event.getAxisValue(MotionEvent.AXIS_GAS);
state.triggerL = lt;
state.triggerR = rt;
float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
state.dpad[0] = hatY < -0.5f;
state.dpad[1] = hatX > 0.5f;
state.dpad[2] = hatY > 0.5f;
state.dpad[3] = hatX < -0.5f;
publish();
return true;
}
private void publish() {
if (!open && !start()) return;
writer.writeGamepadState(state);
}
private static float axis(MotionEvent event, int axis) {
float value = event.getAxisValue(axis);
return Math.abs(value) < DEAD_ZONE ? 0f : value;
}
}
@@ -0,0 +1,117 @@
package com.the412banner.steamdeck.runtime
import android.content.Context
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
import android.os.Build
import android.provider.Settings
import android.util.Log
import com.the412banner.steamdeck.core.EnvironmentComponent
import java.io.File
import java.io.IOException
import java.net.Inet4Address
import java.net.Inet6Address
/**
* The device's network link, published for the Linux runtime's processes.
*
* Android denies an app the rtnetlink dump behind getifaddrs() and if_nameindex(), the hardware
* address ioctl and every table under /proc/net. Wine builds its adapter, address, route and
* neighbour tables from those, so a game under the runtime saw no adapter, no address, no gateway
* and no MAC - and one that checks its adapters before going online waited for good. The link the
* app can see through ConnectivityManager is written here, kept current while the session runs,
* and the session shim answers whatever the kernel refuses from it (tools/linuxfs/preload/netif.c).
*
* Shape follows WinNative's LinuxNetworkLinkComponent (maxjivi05, f76a5c4a), GPL-3.0.
*/
class LinuxNetworkLinkComponent(
context: Context,
private val rootDir: File,
) : EnvironmentComponent() {
private val appContext = context.applicationContext
private val connectivity =
appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val lock = Any()
private var callback: ConnectivityManager.NetworkCallback? = null
/** Called before the session starts, so its first process already sees the link. */
fun publish() = write(connectivity.activeNetwork?.let(connectivity::getLinkProperties))
override fun start() {
val registered = object : ConnectivityManager.NetworkCallback() {
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) = write(properties)
override fun onLost(network: Network) = write(null)
}
synchronized(lock) { callback = registered }
connectivity.registerDefaultNetworkCallback(registered)
}
override fun stop() {
val registered = synchronized(lock) { callback.also { callback = null } } ?: return
try {
connectivity.unregisterNetworkCallback(registered)
} catch (e: IllegalArgumentException) {
Log.w(TAG, "Network callback was already gone", e)
}
}
private fun write(properties: LinkProperties?) {
val file = File(rootDir, LINK_FILE)
synchronized(lock) {
try {
file.parentFile?.mkdirs()
val staged = File(file.path + ".staged")
staged.writeText(describe(properties))
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
} catch (e: IOException) {
Log.w(TAG, "Could not publish the network link", e)
}
}
}
private fun describe(properties: LinkProperties?): String {
val addresses = properties?.linkAddresses.orEmpty()
.filter { it.address is Inet4Address || it.address is Inet6Address }
val name = properties?.interfaceName?.takeIf { addresses.isNotEmpty() } ?: OFFLINE_NAME
val mtu = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) properties?.mtu ?: 0 else 0
return buildString {
append("if $name $LINK_INDEX ${if (mtu > 0) mtu else DEFAULT_MTU}\n")
append("mac ${seededMac()}\n")
if (addresses.isEmpty()) {
append("addr $OFFLINE_ADDRESS\n")
return@buildString
}
for (address in addresses) {
append("addr ${address.address.hostAddress?.substringBefore('%')} ${address.prefixLength}\n")
}
for (family in listOf(Inet4Address::class.java, Inet6Address::class.java)) {
val gateway = properties?.routes.orEmpty()
.firstOrNull { it.isDefaultRoute && family.isInstance(it.gateway) && !it.gateway!!.isAnyLocalAddress }
?.gateway ?: continue
append("gw ${gateway.hostAddress?.substringBefore('%')}\n")
}
}
}
/**
* A stable, locally administered address for this device. Android hides the real one, and a
* title should see the same hardware identity every session.
*/
private fun seededMac(): String {
val id = Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) ?: "bannerlator"
val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray())
val b0 = (bytes[0].toInt() and 0xfc) or 0x02
return listOf(b0, bytes[1].toInt(), bytes[2].toInt(), bytes[3].toInt(), bytes[4].toInt(), bytes[5].toInt())
.joinToString(":") { "%02x".format(it and 0xff) }
}
companion object {
private const val TAG = "LinuxNetworkLink"
private const val LINK_FILE = "etc/bannerlator-net"
private const val LINK_INDEX = 2
private const val DEFAULT_MTU = 1500
private const val OFFLINE_NAME = "eth0"
private const val OFFLINE_ADDRESS = "10.0.0.2 24"
}
}
@@ -0,0 +1,242 @@
package com.the412banner.steamdeck.runtime;
import android.content.Context;
import android.os.Process;
import android.system.ErrnoException;
import android.system.Os;
import android.system.StructStat;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
/**
* The glibc arm64 rootfs at {@code files/linuxfs} and the proot invocation that runs a program in
* it as this app's own uid. It is a second runtime beside the Wine imagefs, not a container: no
* Wine, no box64, no FEX. proot is packaged as {@code libproot.so} so the installer places it, with
* its loader, in the native library directory — the only place an app on targetSdk 28 may execute
* a file from.
*
* <p>Ported from WinNative's gamescope runtime (GPL-3.0).
*/
public final class LinuxRuntime {
public static final String DIR = "linuxfs";
public static final String SESSION_SCRIPT = "/usr/local/bin/bannerlator-session";
public static final String MODE_DESKTOP = "desktop";
public static final String MODE_STEAM = "steam";
public static final String MODE_RUN = "run";
/** Shortcut extra naming which of the modes above a Linux entry launches. */
public static final String EXTRA_LINUX_MODE = "linux_mode";
private static final String KGSL_DEVICE = "/dev/kgsl-3d0";
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
public static final String DEBUG_LOG_DIR = "SteamDeck";
public static File debugLogDir() {
return new File(android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_DOWNLOADS), DEBUG_LOG_DIR);
}
private LinuxRuntime() {}
public static File rootDir(Context context) {
return new File(context.getFilesDir(), DIR);
}
/**
* The session's own small tree beside the rootfs: the fake evdev nodes and their rings. In
* Bannerlator these lived in the Wine imagefs; here there is no Wine, so the session owns them.
* Bound into the guest at its own host path, so nothing needs translating.
*/
public static File sessionRoot(Context context) {
return new File(context.getFilesDir(), "session");
}
/** Where the runtime carries the host-side proot; see tools/linuxfs/prebuilt/proot/README.md. */
private static final String HOST_DIR = "opt/android-host";
/**
* proot, preferred from the installed runtime and falling back to the copy in the apk.
*
* <p>It is an Android binary rather than part of the rootfs — it is what creates the rootfs —
* but it travels in the runtime tarball so that reinstalling the app cannot replace the one
* binary everything else depends on, and so a device with no working packaged proot can still
* run the runtime.
*/
public static File prootBinary(Context context) {
File shipped = new File(rootDir(context), HOST_DIR + "/proot");
if (shipped.isFile()) return shipped;
return new File(context.getApplicationInfo().nativeLibraryDir, "libproot.so");
}
public static File prootLoader(Context context) {
File shipped = new File(rootDir(context), HOST_DIR + "/loader");
if (shipped.isFile()) return shipped;
return new File(context.getApplicationInfo().nativeLibraryDir, "libproot-loader.so");
}
/** proot links against libtalloc, which sits beside it; empty when the apk copy is in use. */
public static String prootLibraryPath(Context context) {
File dir = new File(rootDir(context), HOST_DIR);
return new File(dir, "proot").isFile() ? dir.getPath() : "";
}
/** The rootfs is present with gamescope and the session script the launcher hands control to. */
public static boolean isInstalled(Context context) {
File root = rootDir(context);
return new File(root, "usr/bin/gamescope").isFile()
&& new File(root, SESSION_SCRIPT.substring(1)).isFile()
&& prootBinary(context).isFile()
&& prootLoader(context).isFile();
}
/** The Vulkan ICD manifest the rootfs ships for the device GPU, or null when it has none. */
public static File vulkanIcd(Context context) {
File icdDir = new File(rootDir(context), "usr/share/vulkan/icd.d");
File[] manifests = icdDir.listFiles((dir, name) -> name.endsWith(".json"));
if (manifests == null) return null;
for (File manifest : manifests) {
if (manifest.getName().contains("freedreno")) return manifest;
}
return manifests.length > 0 ? manifests[0] : null;
}
/**
* The proot command line running {@code guestCommand} inside the rootfs. Host paths the session
* needs — the app's files directory for the compositor and audio sockets, external storage for
* the user's games — are bound at their own paths, so nothing on either side needs translating
* and proot never touches the fds a dma-buf travels in. Android has no /dev/shm; a directory
* under the cache stands in, which glibc's shm_open and Chromium's shared memory accept.
*/
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
File externalStorage, List<String> guestCommand) {
return command(context, sessionRoot, runtimeDir, externalStorage, null, guestCommand);
}
/** As above, plus {@code host:guest} bind specs — the installed games handed to Steam. */
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
File externalStorage, List<String> extraBinds,
List<String> guestCommand) {
File root = rootDir(context);
List<String> cmd = new ArrayList<>();
cmd.add(prootBinary(context).getPath());
cmd.add("--kill-on-exit");
// Android's app seccomp policy traps the whole set*id family. Xwayland's Popen() calls
// setgid()/setuid() before it execs xkbcomp and _exit(127)s when they fail, so without
// this the keymap never compiles and Xwayland dies. -i makes proot answer those calls
// itself while still reporting our real ids, so nothing inside sees a different user.
int uid = Process.myUid();
cmd.add("-i");
cmd.add(uid + ":" + uid);
cmd.add("-r");
cmd.add(root.getPath());
cmd.add("-w");
cmd.add("/root");
bind(cmd, "/dev");
bind(cmd, "/proc");
bind(cmd, "/sys");
bind(cmd, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd");
bind(cmd, "/proc/self/fd/0:/dev/stdin");
bind(cmd, "/proc/self/fd/1:/dev/stdout");
bind(cmd, "/proc/self/fd/2:/dev/stderr");
bind(cmd, new File(root, "etc/bannerlator/empty").getPath() + ":/sys/fs/selinux");
bind(cmd, context.getFilesDir().getPath());
bind(cmd, context.getCacheDir().getPath());
bind(cmd, runtimeDir.getPath());
if (sessionRoot != null) bind(cmd, sessionRoot.getPath());
if (externalStorage != null && externalStorage.isDirectory()) {
bind(cmd, externalStorage.getPath());
}
File shm = new File(context.getCacheDir(), "shm");
shm.mkdirs();
bind(cmd, shm.getPath() + ":/dev/shm");
// Android denies apps these; glibc, Steam and libcap read them at startup.
File fakeProc = new File(root, "etc/bannerlator/proc");
String[][] procFiles = {
{"stat", "/proc/stat"},
{"version", "/proc/version"},
{"loadavg", "/proc/loadavg"},
{"uptime", "/proc/uptime"},
{"vmstat", "/proc/vmstat"},
{"cap_last_cap", "/proc/sys/kernel/cap_last_cap"},
{"overflowuid", "/proc/sys/kernel/overflowuid"},
{"overflowgid", "/proc/sys/kernel/overflowgid"},
};
for (String[] entry : procFiles) {
File fake = new File(fakeProc, entry[0]);
if (fake.isFile() && !new File(entry[1]).canRead()) {
bind(cmd, fake.getPath() + ":" + entry[1]);
}
}
bindGpuNode(context, cmd);
if (extraBinds != null) {
for (String spec : extraBinds) bind(cmd, spec);
}
cmd.addAll(guestCommand);
return cmd;
}
/**
* An app process may not open {@code /dev/dri} — the nodes exist but are labelled
* {@code graphics_device}, which stock policy grants surfaceflinger and not us — yet libdrm and
* everything built on it identify a GPU by its render node, and gamescope refuses to offer
* linux-dmabuf without one. The KGSL device Turnip actually drives ({@code gpu_device}, which we
* may open) stands in: it appears as a render node with the sysfs entries libdrm reads, and our
* Turnip build reports the same device numbers for it.
*/
private static void bindGpuNode(Context context, List<String> cmd) {
StructStat st;
try {
st = Os.stat(KGSL_DEVICE);
} catch (ErrnoException e) {
return;
}
long dev = st.st_rdev;
long major = ((dev >> 8) & 0xfff) | ((dev >> 32) & ~0xfffL);
long minor = (dev & 0xff) | ((dev >> 12) & ~0xffL);
String node = "renderD" + minor;
File base = new File(context.getCacheDir(), "drm");
File dri = new File(base, "dri");
File device = new File(base, "sys/" + major + ":" + minor + "/device");
File drm = new File(device, "drm/" + node);
try {
if ((!dri.isDirectory() && !dri.mkdirs()) || (!drm.isDirectory() && !drm.mkdirs())) {
return;
}
new File(dri, node).createNewFile();
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));
File subsystem = new File(device, "subsystem");
if (!Files.isSymbolicLink(subsystem.toPath())) {
Os.symlink("/sys/bus/platform", subsystem.getPath());
}
} catch (IOException | ErrnoException e) {
return;
}
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
bind(cmd, dri.getPath() + ":/dev/dri");
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
}
private static void bind(List<String> cmd, String spec) {
cmd.add("-b");
cmd.add(spec);
}
/** X access control and Steam look the session user up by uid: the app uid is root inside. */
public static void writeAccounts(Context context) throws IOException {
File root = rootDir(context);
int uid = Process.myUid();
Files.write(new File(root, "etc/passwd").toPath(),
("root:x:" + uid + ":" + uid + ":root:/root:/bin/bash\n").getBytes(StandardCharsets.UTF_8));
Files.write(new File(root, "etc/group").toPath(),
("root:x:" + uid + ":\n").getBytes(StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,258 @@
package com.the412banner.steamdeck.runtime;
import android.content.Context;
import android.util.Log;
import com.the412banner.steamdeck.core.FileUtils;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.zstandard.ZstdCompressorInputStream;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
/**
* Downloads and unpacks the Linux runtime rootfs into {@code files/linuxfs}. It is opt-in: nothing
* fetches it until the user asks for it, and a gamescope session refuses to start without it.
*
* <p>The catalog row names the build, its URL and its sha256, so an interrupted or corrupted
* download is caught before anything is written into the app's files directory.
*/
public final class LinuxRuntimeInstaller {
private static final String TAG = "LinuxRuntimeInstaller";
/** Catalog row, beside the other component catalogs in winlator-contents. */
public static final String CATALOG_URL =
"https://raw.githubusercontent.com/The412Banner/winlator-contents/main/linuxfs.json";
private static final String VERSION_FILE = ".version";
public interface ProgressListener {
/** {@code percent} is -1 while the size is unknown. */
void onProgress(String stage, int percent);
}
public static final class Release {
public final String version;
public final String url;
public final String sha256;
public final long size;
Release(String version, String url, String sha256, long size) {
this.version = version;
this.url = url;
this.sha256 = sha256;
this.size = size;
}
}
private LinuxRuntimeInstaller() {}
/** The build currently unpacked, or null when the runtime is not installed. */
public static String installedVersion(Context context) {
File marker = new File(LinuxRuntime.rootDir(context), VERSION_FILE);
if (!marker.isFile() || !LinuxRuntime.isInstalled(context)) return null;
String v = FileUtils.readString(marker);
return v == null ? null : v.trim();
}
/** The catalog's current build, or null when it cannot be reached or read. */
public static Release fetchRelease() {
String body = Downloader.downloadString(CATALOG_URL);
if (body == null || body.isEmpty()) return null;
try {
JSONObject json = new JSONObject(body);
String version = json.optString("version", "");
String url = json.optString("url", "");
String sha256 = json.optString("sha256", "");
if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) return null;
return new Release(version, url, sha256, json.optLong("size", 0L));
} catch (Exception e) {
Log.w(TAG, "catalog: " + e);
return null;
}
}
/**
* The guest's home directory, carried across an update rather than replaced with the tarball's
* empty one. Steam installs itself here - the client, the signed-in account and every
* downloaded game - so replacing the rootfs wholesale used to delete all three and leave the
* user re-downloading Steam and signing in again, with their library gone.
*/
private static final String USER_DATA = "root";
/**
* Downloads {@code release} and replaces whatever is installed with it. Returns false and
* leaves the existing runtime alone if the download or the checksum fails; the new rootfs is
* only moved into place once it has been unpacked whole.
*
* <p>{@link #USER_DATA} survives the swap: the system is replaced, what the user put in it is
* not. An update therefore keeps Steam, the login and the installed games.
*/
public static boolean install(Context context, Release release, ProgressListener listener) {
File archive = new File(context.getCacheDir(), "linuxfs.tar.zst");
try {
if (listener != null) listener.onProgress("Downloading", 0);
// Downloader reports a 0..1 fraction, or -1 while the total size is unknown.
boolean ok = Downloader.downloadFile(release.url, archive, true, (fraction) -> {
if (listener != null) {
listener.onProgress("Downloading",
fraction < 0 ? -1 : Math.round(fraction * 100f));
}
});
if (!ok) {
Log.w(TAG, "download failed");
return false;
}
if (listener != null) listener.onProgress("Verifying", -1);
String actual = sha256(archive);
if (!release.sha256.equalsIgnoreCase(actual)) {
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
return false;
}
// Unpack beside the live rootfs and swap, so a failure here cannot leave a half
// runtime that isInstalled() would happily launch.
File root = LinuxRuntime.rootDir(context);
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
FileUtils.delete(staging);
if (!staging.mkdirs()) return false;
if (listener != null) listener.onProgress("Extracting", -1);
if (!extract(archive, staging, listener)) {
FileUtils.delete(staging);
return false;
}
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
FileUtils.delete(old);
if (root.isDirectory() && !root.renameTo(old)) {
FileUtils.delete(staging);
return false;
}
// Carry the user's home over before the new rootfs takes the name. A rename inside the
// same filesystem, so a 30 GB library costs nothing and cannot half-copy; the tarball's
// own empty /root is dropped first so the rename has somewhere to land. If this fails
// the update is abandoned and the previous runtime is put back untouched - shipping a
// working system with the user's games gone is the worse outcome.
File keptFrom = new File(old, USER_DATA);
if (keptFrom.isDirectory()) {
File keptTo = new File(staging, USER_DATA);
FileUtils.delete(keptTo);
if (!keptFrom.renameTo(keptTo)) {
Log.w(TAG, "could not carry " + USER_DATA + " across the update; rolling back");
FileUtils.delete(staging);
old.renameTo(root);
return false;
}
}
if (!staging.renameTo(root)) {
if (old.isDirectory()) old.renameTo(root);
return false;
}
FileUtils.delete(old);
return LinuxRuntime.isInstalled(context);
} catch (Exception e) {
Log.e(TAG, "install", e);
return false;
} finally {
archive.delete();
}
}
public static void uninstall(Context context) {
FileUtils.delete(LinuxRuntime.rootDir(context));
}
/**
* A whole-rootfs tar, which is not the shape the shared extractor handles: a distribution
* rootfs is full of hard links (one binary under several names), and an entry written as an
* empty file instead of its link target is a rootfs that boots to nothing. Symlinks, hard
* links and the executable bit are all carried over here.
*/
private static boolean extract(File archive, File destination, ProgressListener listener) {
long entries = 0;
try (InputStream in = new ZstdCompressorInputStream(
new BufferedInputStream(new FileInputStream(archive), 1 << 16));
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
TarArchiveEntry entry;
String base = destination.getCanonicalPath() + File.separator;
while ((entry = tar.getNextTarEntry()) != null) {
File file = new File(destination, entry.getName());
// Refuse anything that would land outside the runtime directory.
if (!(file.getCanonicalPath() + (entry.isDirectory() ? File.separator : "")).startsWith(base)
&& !file.getCanonicalPath().equals(destination.getCanonicalPath())) {
Log.w(TAG, "skipping entry outside the rootfs: " + entry.getName());
continue;
}
if (entry.isDirectory()) {
file.mkdirs();
continue;
}
File parent = file.getParentFile();
if (parent != null && !parent.isDirectory()) parent.mkdirs();
if (entry.isSymbolicLink()) {
file.delete();
FileUtils.symlink(entry.getLinkName(), file.getAbsolutePath());
} else if (entry.isLink()) {
// A hard link to an earlier entry. Link where the filesystem allows it and
// fall back to a copy, which costs space but always works.
File target = new File(destination, entry.getLinkName());
file.delete();
try {
Files.createLink(file.toPath(), target.toPath());
} catch (IOException | UnsupportedOperationException e) {
if (target.isFile()) {
Files.copy(target.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
} else if (entry.isFile()) {
try (OutputStream out = new FileOutputStream(file)) {
byte[] buffer = new byte[1 << 16];
int read;
while ((read = tar.read(buffer)) != -1) out.write(buffer, 0, read);
}
if ((entry.getMode() & 0111) != 0) file.setExecutable(true, false);
} else {
continue; // device nodes and fifos: the runtime binds the real ones
}
if (++entries % 2000 == 0 && listener != null) {
listener.onProgress("Extracting", -1);
}
}
return true;
} catch (Exception e) {
Log.e(TAG, "extract", e);
return false;
}
}
private static String sha256(File file) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
try (InputStream in = new BufferedInputStream(new FileInputStream(file), 1 << 16)) {
byte[] buffer = new byte[1 << 16];
int read;
while ((read = in.read(buffer)) != -1) digest.update(buffer, 0, read);
}
StringBuilder sb = new StringBuilder();
for (byte b : digest.digest()) sb.append(String.format("%02x", b));
return sb.toString();
}
}
@@ -0,0 +1,422 @@
package com.the412banner.steamdeck.wayland;
import android.view.Surface;
/**
* Embedded Wayland compositor (experimental parallel display runtime).
*
* Brings up a libwayland-server compositor in-process so games launched through
* Wine's winewayland.drv can present into it (companion to the winewayland Proton
* build). Committed frames (dmabufs from winewayland's Vulkan WSI) are composited
* onto the given Surface via the native Vulkan present backend. Not on the default
* X11 path.
*/
public final class WaylandCompositor {
static {
System.loadLibrary("bannerwayland");
}
private WaylandCompositor() {}
private static volatile Runnable firstFrameListener;
/** Register a callback fired once, when the compositor presents the first client
* frame to the output Surface. Used to dismiss the launch overlay in wayland mode
* (there is no XServer window-content hook). Runs on the compositor thread — the
* listener must marshal to the UI thread itself. */
public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; }
/** Invoked from native (banner_on_first_frame) on the first present. */
@SuppressWarnings("unused")
static void onFirstFramePresented() {
Runnable r = firstFrameListener;
if (r != null) r.run();
}
/** The in-game performance HUD's feed in wayland mode (X11 binds the HUD to the window
* carrying _MESA_DRV and counts X presents; there is no X server here). */
public interface GameListener {
/** A window started presenting GPU frames ({@code window} describes it; {@code gpuName} is the
* compositor's GPU), or {@code window == null} when that window closed. Compositor thread. */
void onGameSurface(String window, String gpuName);
/** One GPU frame from that window. Compositor thread — keep it cheap. */
void onGameFrame();
/** The program behind that window, right after {@link #onGameSurface}: its Linux pid (the
* Wayland client's credentials) and executable name ({@code ""} when unknown). The app arms its
* launch-time CPU affinity on it — on X11 that comes from window events, which a Wayland session
* has none of. Compositor thread — marshal to the UI thread. */
default void onGameProgram(int pid, String program) {}
}
private static volatile GameListener gameListener;
public static void setGameListener(GameListener l) { gameListener = l; }
/** Invoked from native (banner_on_game_surface). */
@SuppressWarnings("unused")
static void onGameSurface(String window, String gpuName) {
GameListener l = gameListener;
if (l != null) l.onGameSurface(window, gpuName);
}
/** Invoked from native (banner_on_game_frame) for every frame of the HUD's window. */
@SuppressWarnings("unused")
static void onGameFrame() {
GameListener l = gameListener;
if (l != null) l.onGameFrame();
}
/** Invoked from native (banner_on_game_program) once per game window that starts presenting. */
@SuppressWarnings("unused")
static void onGameProgram(int pid, String program) {
GameListener l = gameListener;
if (l != null) l.onGameProgram(pid, program != null ? program : "");
}
/** Pointer lock (zwp_pointer_constraints_v1) state, for the app's input path. */
public interface PointerLockListener {
/** A program locked the pointer ({@code locked}): the app must feed the compositor deltas
* (scene input type 6) instead of absolute positions. When the lock ends, {@code x,y} is
* where the pointer now is (scene = virtual-desktop coordinates) for the app to re-sync
* its own pointer to. Compositor thread. */
void onPointerLock(boolean locked, int x, int y);
}
private static volatile PointerLockListener pointerLockListener;
public static void setPointerLockListener(PointerLockListener l) { pointerLockListener = l; }
/** Invoked from native (banner_on_pointer_lock). */
@SuppressWarnings("unused")
static void onPointerLock(boolean locked, int x, int y) {
PointerLockListener l = pointerLockListener;
if (l != null) l.onPointerLock(locked, x, y);
}
/** Clipboard text a program in the guest copied (wl_data_device / zwlr_data_control). */
public interface ClipboardListener {
/** {@code text} is what the guest put on its clipboard. Compositor thread. */
void onGuestClipboardText(String text);
}
private static volatile ClipboardListener clipboardListener;
public static void setClipboardListener(ClipboardListener l) { clipboardListener = l; }
/** Invoked from native (banner_on_clipboard_text) with UTF-8 bytes. */
@SuppressWarnings("unused")
static void onClipboardText(byte[] utf8) {
ClipboardListener l = clipboardListener;
if (l != null && utf8 != null) l.onGuestClipboardText(new String(utf8, java.nio.charset.StandardCharsets.UTF_8));
}
/** Text input (zwp_text_input_v3) state: a program accepts IME text, or stopped. */
public interface TextInputListener {
/** {@code enabled}: {@code program} (its exe name) accepts IME text; {@code x,y,w,h} is its caret
* rectangle in scene (virtual desktop) pixels, all 0 until the program positions one. Compositor
* thread. */
void onTextInput(boolean enabled, String program, int x, int y, int w, int h);
}
private static volatile TextInputListener textInputListener;
public static void setTextInputListener(TextInputListener l) { textInputListener = l; }
/** Invoked from native (banner_on_text_input). */
@SuppressWarnings("unused")
static void onTextInput(boolean enabled, String program, int x, int y, int w, int h) {
TextInputListener l = textInputListener;
if (l != null) l.onTextInput(enabled, program, x, y, w, h);
}
private static byte[] utf8(String s) {
return s == null ? new byte[0] : s.getBytes(java.nio.charset.StandardCharsets.UTF_8);
}
/** Android's clipboard text becomes the guest's selection ({@code null}/empty clears it). Any thread. */
public static void setClipboardText(String text) { nativeSetClipboardText(utf8(text)); }
/** Commit soft-keyboard text to the program accepting text input. Any thread. */
public static void textInputCommit(String text) { if (text != null && !text.isEmpty()) nativeTextInputCommit(utf8(text)); }
/** Composing (pre-edit) text with the caret at character index {@code cursor} (-1 = end); empty clears. */
public static void textInputPreedit(String text, int cursor) { nativeTextInputPreedit(utf8(text), cursor, cursor); }
/** The IME deleted {@code before} characters before and {@code after} after the caret. */
public static void textInputDelete(int before, int after) { nativeTextInputDelete(before, after); }
private static native void nativeSetClipboardText(byte[] utf8);
private static native void nativeTextInputCommit(byte[] utf8);
private static native void nativeTextInputPreedit(byte[] utf8, int cursorBegin, int cursorEnd);
private static native void nativeTextInputDelete(int before, int after);
/** Start the compositor headless (no output window) — bring-up tests only. */
public static native void nativeStart(String xdgRuntimeDir);
/** Start the compositor rendering to {@code surface}. XDG_RUNTIME_DIR = an
* app-writable dir for the wayland socket (e.g. context.getFilesDir()).
* driverPath/libraryName/nativeLibDir select the Turnip driver via adrenotools
* (all null -> system libvulkan, which can't do dmabuf import). */
public static native void nativeStartWithSurface(Surface surface, String xdgRuntimeDir,
String driverPath, String libraryName,
String nativeLibDir);
/** Replace/clear the output window when the SurfaceView is (re)created/destroyed. */
public static native void nativeSetSurface(Surface surface);
/** Inject a pointer event into the compositor (from the SurfaceView touch listener).
* action: 0=down, 1=move, 2=up. x/y in compositor output space (0..1919, 0..1079). */
public static native void nativeSendPointer(int action, int x, int y);
/** Inject a key event. evdev = Linux input keycode (KEY_A=30…); state: 1=down, 0=up. */
public static native void nativeSendKey(int evdev, int state);
/** One screen refresh (Choreographer frame callback). The compositor draws the newest state
* once per tick, so games run unthrottled and the screen shows their latest frame. */
public static native void nativeVsync(long frameTimeNanos);
/** 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);
/** The panel's refresh rate in Hz, advertised on the Wayland output so Wine's display modes
* carry the real rate (games that insist on their saved 144 Hz mode find it, as on X11).
* Set before the compositor starts. */
public static native void nativeSetOutputRefreshRate(float hz);
/** Show a single fullscreen window on its own Android layer (SurfaceControl) instead of blitting
* it into the compositor's swapchain. BANNER_WAYLAND_ZERO_COPY=1 in the container's environment
* variables is the launch default; see waylandcomp/ZERO_COPY_SPIKE.md.
*
* Live and thread-safe: before the compositor starts this is the initial state, and afterwards
* the call is marshalled onto the compositor thread, which flips the state, tells every bound
* game over banner_ahb_v1.mode to rebuild its swapchain for it, and redraws. The switch is one
* frame's worth of latency; the picture never goes black, because the old swapchain's buffers
* keep being shown until the game has replaced them. */
public static native void nativeSetZeroCopy(boolean on);
/** Zero-copy frames the compositor presented in its LAST completed 10 s stats window (the
* "| N zero-copy frames" figure of its session-log stats line); 0 while zero-copy is off or
* before the first window closes. Read-only, any thread — the in-game drawer polls it. */
public static native int nativeZeroCopyFrames();
/** Milliseconds since the compositor last put a game frame on the display layer without a copy;
* -1 if it never has this session. Unlike nativeZeroCopyFrames this updates on every such frame
* rather than once per 10 s window, so the drawer can tell "switching..." from "running" within
* a frame or two of the live toggle. Read-only, any thread. */
public static native int nativeZeroCopyLastFrameAgeMs();
/** Compressed (UBWC) game buffers: the compositor advertises DRM_FORMAT_MOD_QCOM_COMPRESSED next to
* LINEAR on zwp_linux_dmabuf_v1 for every format its driver can import that way, so the game's
* Turnip allocates compressed swapchain images instead of resolving every frame to a linear copy.
* Default on; BANNER_WAYLAND_UBWC=0 in the container's environment variables turns it off (A/B).
* Set before the compositor starts. */
public static native void nativeSetUbwc(boolean on);
/** Debug: advertise no DRM device (main device 0:0) in the dma-buf feedback, as a phone that
* exposes no /dev/dri node to apps does. BANNER_WAYLAND_NO_RENDER_NODE=1 in the container's or
* shortcut's environment variables. Set before the compositor starts. */
public static native void nativeSetNoRenderNode(boolean on);
/** VRR / refresh-rate matching: mirror the panel refresh-rate vote the activity puts on the
* compositor's SurfaceView onto the game's own SurfaceControl layer. Under zero-copy the game's
* frames go straight onto that layer and never reach the app's surface, so the surface vote alone
* does not tell SurfaceFlinger the game's cadence. Same rate and compatibility as
* {@code Surface.setFrameRate}; {@code 0} clears the vote. Callable any time from any thread; the
* compositor applies it on its next layer transaction and writes one `layer` line per change to
* the session log. A no-op on Android versions without {@code ASurfaceTransaction_setFrameRate}. */
public static native void nativeSetLayerFrameRate(float hz);
/** Write one line into the compositor's session log (Download/Wayland-logs) under the "display"
* area, from Java. Used for facts the platform knows and the native side does not — the panel's
* HDR capability, which lives behind android.view.Display. Safe before the compositor thread is
* up (the line then only reaches logcat) and safe after it has gone. */
public static native void nativeLogDisplay(String message);
/** The same under the "perf" area (e.g. the CPU cores Prefer Big Cores picked). Same safety. */
public static native void nativeLogPerf(String message);
/** The container's screen size, advertised as the Wayland output's mode so Wine's display-mode
* list stops at the desktop size, as the X server's does on X11. Set before the compositor starts. */
public static native void nativeSetOutputSize(int width, int height);
// ── HDR10 output, round 1 (waylandcomp/src/banner_color.h, wl_color_mgmt.c) ─────────────────
// Opt-in: BANNER_WAYLAND_HDR=1 in the container's or shortcut's env vars. The compositor offers
// games HDR10 (wp_color_manager_v1 + 10-bit buffers, frames tagged BT2020_PQ on the game's own
// display layer) only when the game's display lists HDR10 as well; otherwise nothing changes and
// the session log says why. Not the drawer's "HDR" effect, which is an SDR bloom/contrast filter.
/** HDR_MODE_OFF / HDR_MODE_ON (BANNER_WAYLAND_HDR=1) / HDR_MODE_FORCE (=force: skip the display
* check, for testing the negotiation on an SDR panel). */
public static final int HDR_MODE_OFF = 0, HDR_MODE_ON = 1, HDR_MODE_FORCE = 2;
/** The opt-in: mode, where it came from ("container env" / "shortcut env"), whether DXVK_HDR=1 is
* in the game's environment, and whether the app turned zero-copy on for this session because HDR
* needs it. Set before the compositor starts. */
public static native void nativeSetHdrRequest(int mode, String source, boolean dxvkHdr, boolean zeroCopyForced);
/** The game's display as {@code android.view.Display} reports it. Before the compositor starts (it
* feeds the gate) and again whenever it changes (logged; the gate is decided once per session). */
public static native void nativeSetHdrDisplay(int displayId, String name, String formats, boolean hdr10,
float maxLuminance, float maxAverageLuminance, float minLuminance,
boolean hdrSdrRatioAvailable, float hdrSdrRatio, int apiLevel);
/** One {@code Display.getHdrSdrRatio()} reading ({@code < 0} = not available); {@code listener} = it
* came from the display's ratio listener rather than the periodic sampler. Any thread. */
public static native void nativeHdrSdrRatioSample(float ratio, boolean listener);
/** Milliseconds since an HDR frame last reached a display layer; -1 = none this session. Any thread. */
public static native int nativeHdrLastFrameAgeMs();
/** -1 = the compositor has not decided the HDR gate yet, 0 = closed, 1 = open. Any thread. */
public static native int nativeHdrGateState();
/** The session is ending: the compositor writes its "HDR on screen: …" summary line. Once. */
public static native void nativeHdrSessionEnd();
/** True while HDR frames are really on screen: frames tagged BT2020_PQ reached the display in the
* last 1.5 s and, where the display reports an HDR/SDR ratio, it is above 1 (the HUD's badge). */
public static native boolean nativeHdrOnScreen();
/** One "color" line in the session log, from Java (the HDR environment, the DXVK warning). */
public static native void nativeLogColor(String message);
/** One line in the session log under {@code area} (the log's 9-character column: "gpu", "nvapi"),
* from Java: launch facts the app decides (the GPU name spoof, the Unreal Engine HDR mode). Like
* {@link #nativeLogDisplay}, safe before the session file exists (the line is written when it
* opens) and after it has gone. */
public static native void nativeLog(String area, String message);
/** Nits at which SDR content is placed when the compositor composes an HDR picture (a window over
* an HDR game, the desktop around a windowed one). Default 203 (BT.2408). Before the start. */
public static native void nativeSetHdrSdrWhite(float nits);
/** The in-game drawer's HDR output switch (only meaningful while the HDR gate is open; per session,
* starts on). On = the game's HDR frames go to the display as HDR; off = the same frames are shown
* tone-mapped to SDR. Live, any thread (queued to the compositor, which logs the flip); the game is
* told nothing - DXVK_HDR and the colour-manager offer were decided at launch. */
public static native void nativeSetHdrOutput(boolean on);
/** The HDR output switch's current state (any thread). */
public static native boolean nativeHdrOutput();
/** True while an HDR game's frames are being shown tone-mapped to SDR (the last one under 1.5 s ago). */
public static native boolean nativeHdrToneMappedOnScreen();
/** 0 = no HDR frames on screen (or not confirmed yet), 1 = HDR frames on screen with HDR headroom,
* 2 = HDR frames on screen but the display has given them no headroom (HDR/SDR ratio 1.00) for 5 s
* or more - the brightness slider at maximum, or a screen recording (Android turns HDR headroom off
* while the screen is recorded). The HUD badge and the drawer's HDR row. */
public static native int nativeHdrState();
/** Device evidence beside the HDR/SDR headroom, HDR sessions only (any thread): PowerManager thermal
* status (0..6, -1 unknown) and getThermalHeadroom(10) (NaN / negative = not available), and
* Settings.System SCREEN_BRIGHTNESS (0..255, -1 unknown) + SCREEN_BRIGHTNESS_MODE (1 auto, 0 manual,
* -1 unknown). The compositor logs changes of status and brightness and puts the values on every
* no-headroom line, the 10 s HDR line and the verdict. */
public static native void nativeHdrEnvSample(int thermalStatus, float thermalHeadroom, int brightness,
int brightnessMode);
/** Display.getHighestHdrSdrRatio() (Android 16+), <= 0 = not reported: the display's own ceiling, capped
* into the headroom request and logged in the verdict. Any thread. */
public static native void nativeSetHdrHighestRatio(float ratio);
/** The HDR headroom the SCREEN surface should ask for while HDR frames go through the HDR10 swapchain
* (frame generation), 0 = none; the app applies it (SurfaceView.setDesiredHdrHeadroom, API 35). */
public static native float nativeHdrScreenHeadroom();
/** Why that value ("content peak 1207 nits (max CLL) / SDR 203 ..."), for the log line. */
public static native String nativeHdrScreenHeadroomWhy();
/** What the app asked for on the screen surface: > 0 the ratio, 0 cleared, -1 not possible (< Android 15). */
public static native void nativeHdrNoteHeadroomRequest(float ratio);
/** Fullscreen mode ({@code Container.FULLSCREEN_OFF/FIT/STRETCH/FILL/INTEGER}) and screen alignment
* ({@code Container.ALIGN_CENTER/TOP/BOTTOM}): how the compositor fits the desktop onto the screen,
* with the same arithmetic as {@code ViewTransformation} (which maps touch input), so the picture and
* the pointer agree. OFF and FIT both letterbox. Callable any time; the next frame uses it. */
public static native void nativeSetScaleMode(int fullscreenMode, int screenAlignment);
// ---- Screen effects: the X11 Vulkan renderer's post chain, run by the compositor between the
// composited scene and the output blit (waylandcomp/src/effects_chain.c). Same modes, ranges and
// pass order as VulkanRenderer's setters, so a saved preset looks the same on both backends.
// Callable any time from any thread; the compositor applies them on its next frame and writes
// one `effects` line to the session log per change. While any effect is on, a zero-copy
// (layer-mode) game is presented through the compositor pass instead.
/** Scaling mode: 0=None 1=Linear 2=Nearest 3=SGSR 4=FSR 5=FSR Fit 6=Sharpen 7=NIS 8=SGSR HQ.
* Resizes the scene to its mapped output size (there is no render scale on Wayland). */
public static native void nativeSetUpscaler(int mode);
/** The upscaler's own sharpness slider 0..100 (RCAS lobe scale, SGSR edge 0.5..4.5, NIS). */
public static native void nativeSetUpscaleSharpness(int sharpness);
/** AMD CAS sharpen toggle + level 0..100 (0 = the pass is off). */
public static native void nativeSetCas(boolean enabled, int sharpness);
/** Fake-HDR toggle. */
public static native void nativeSetHdr(boolean enabled);
/** Terminal debanding toggle + strength 0..200 (100 = 1 LSB). */
public static native void nativeSetDeband(boolean enabled, int strength);
/** Colour grade in the drawer's slider units (brightness/contrast -100..100, gamma 0.5..3.0,
* saturation 0..200 percent; 0/0/1/100 = neutral, pass off) plus the FXAA / Toon / CRT / NTSC
* toggles — the same signature as {@code VulkanRenderer.setScreenEffects}. */
public static native void nativeSetScreenEffects(float brightness, float contrast, float gamma, float saturation,
boolean fxaa, boolean toon, boolean crt, boolean ntsc);
/** The Look the controls currently match ({@code null} = Custom); only named in the log line. */
public static native void nativeSetLookName(String name);
/** The in-game FPS limiter: frames per second, 0 = unlimited. Paces when replaced buffers go
* back to the game, like the X11 IdleNotify pacer, so the game itself slows to the cap. */
public static native void nativeSetFpsLimit(int fps);
/** Inject the app's X-server input in scene (virtual desktop) pixels. type 2 = move to a,b;
* 3 = evdev button a (BTN_LEFT=0x110…) pressed (b=1) or released (b=0); 4 = a wheel steps,
* negative = up. */
public static native void nativeSendSceneInput(int type, int a, int b);
// ── Frame generation (waylandcomp/src/framegen_bridge.c) ─────────────────────────────────
// LSFG Native and Win-FG Native run inside the compositor's Turnip device, the same engines
// the X11 VulkanRenderer hosts. Every setter only stores a value; the compositor thread applies
// it on its next frame, so they are safe from any thread and before the compositor starts.
// bionic-fg (the guest-side win-fg layer) is X11-only and has no Wayland counterpart.
public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_WINFG = 1;
/** Which native engine generates: {@link #FG_ENGINE_LSFG} or {@link #FG_ENGINE_WINFG}. */
public static native void nativeSetFrameGenEngine(int kind);
/** Arm (multiplier 2..4: one real frame plus multiplier-1 interpolated ones per game frame) or
* disarm. Generated frames are presented ahead of the real frame on consecutive vblanks. */
public static native void nativeSetFrameGenArmed(boolean armed, int multiplier);
/** LSFG Native: the SPIR-V cache built from the user's Lossless.dll ({@code LsfgNative.cacheFile}). */
public static native void nativeSetLsfgCachePath(String path);
/** Flow scale (0.25-1.0) and the panel's real refresh rate (the pacer never generates above it). */
public static native void nativeSetFrameGenTuning(float flowScale, float refreshHz);
/** Win-FG Native only: interpolation model (3/4) and performance preset (0..2). */
public static native void nativeSetWinFgTuning(int model, int perfPreset);
/** Same codes as {@code VulkanRenderer.getFrameGenProblem()}: -1 not known yet (the compositor's
* device is not up), 0 fine, 1 the driver lacks what the selected engine needs
* ({@link #nativeFrameGenCapsReason()} says what), 2 the engine failed to start. */
public static native int nativeFrameGenProblem();
public static native String nativeFrameGenCapsReason();
/** Same shape as {@code VulkanRenderer.getFrameGenStats()}: {generations trusted, generations
* planned, real fps, presented fps (generated frames included), thermal (-1 = none),
* GPU ms per generated frame (-1 = unknown)}. */
public static native float[] nativeFrameGenStats();
/** Relative pointer motion by dx,dy scene pixels (the Relative Mouse / captured-mouse path):
* while a program holds a pointer lock this is what it receives as relative_motion; otherwise
* the compositor moves its pointer by the delta. */
public static void sendPointerDelta(int dx, int dy) {
if (dx == 0 && dy == 0) return;
nativeSendSceneInput(6, dx * 256, dy * 256);
}
}