Compare commits

..
21 changed files with 183 additions and 376 deletions

No files matched your search

@@ -141,7 +141,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true)
private var returnAfterGame by mutableStateOf(true)
private var valveProtonOnDemand by mutableStateOf(true)
private var shaderPrecache by mutableStateOf<Boolean?>(null)
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
@@ -2385,7 +2384,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
defaultHomeLabel = HomeApp.defaultLabel(this)
com.droiddeck.launcher.ui.NavTabs.syncHomeApps(this, homeAppSelected)
refreshAndroidApps()
integrationState = readIntegration()
}
@@ -2786,7 +2784,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
returnAfterGame = if (mode == SessionService.MODE_STEAM) returnAfterGame else null,
shaderPrecache = if (mode == SessionService.MODE_STEAM) shaderPrecache else null,
valveProtonOnDemand = if (mode == SessionService.MODE_STEAM) valveProtonOnDemand else null,
steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
@@ -2894,7 +2891,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
onValveProtonOnDemand = { on -> SessionPrefs.setValveProtonOnDemand(this, on); valveProtonOnDemand = on },
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
onStartupSession = { id ->
SessionPrefs.setStartupSession(this, id)
@@ -3167,7 +3163,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this)
returnAfterGame = SessionPrefs.returnAfterGame(this)
valveProtonOnDemand = SessionPrefs.valveProtonOnDemand(this)
loadShaderPrecache(mode)
steamController = SessionPrefs.steamController(this)
startupSession = SessionPrefs.startupSession(this)
@@ -49,7 +49,7 @@ internal class ProtonMenu(
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, onProgress = progress) }
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
fun installProton(id: String, automatic: Boolean = false) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
@@ -2834,7 +2834,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun installProton(): String? {
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(this)) return installOwnProton()
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
SessionState.installCancellation = cancellation
@@ -2847,24 +2846,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
private fun installOwnProton(): String? {
val extras = com.droiddeck.launcher.session.ProtonExtras
while ((extras.prefetching || extras.installInProgress) && !SessionState.stopRequested) {
try { Thread.sleep(250) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return "interrupted" }
}
if (SessionState.stopRequested) return "cancelled"
if (!com.droiddeck.launcher.runtime.DesktopCatalog.ownProtonMissing(this)) return null
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
SessionState.installCancellation = cancellation
return try {
extras.install(this, extras.tools.first { it.id == extras.OWN }, cancellation) { label, percent ->
uiHandler.post { loading.percent = percent; loading.say(label, PROTON_LINES.topic, readable = true) }
}.also { if (it == null) com.droiddeck.launcher.session.Onboarding.recheck(this) }
} finally {
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
}
}
override fun surfaceCreated(holder: SurfaceHolder) {
if (holder !== outputHolder()) return
if (installingRuntime || SessionState.stopRequested || ended) return
@@ -293,7 +293,6 @@ object DeviceReport {
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
k("Avoid notch", SessionPrefs.avoidNotch(context))
k("Return to launcher after a game", SessionPrefs.returnAfterGame(context))
k("Valve Proton only when needed", SessionPrefs.valveProtonOnDemand(context))
k("Microphone", SessionPrefs.micEnabled(context))
k("On-screen controls", SessionPrefs.oscMode(context))
k("Touch mode", SessionPrefs.touchMode(context))
@@ -109,15 +109,9 @@ object DesktopCatalog {
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
fun protonSeedNeeded(context: Context): Boolean =
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(context)) ownProtonMissing(context)
else installed(context, PROTON_SEED_ID) == null &&
installed(context, PROTON_SEED_ID) == null &&
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
fun ownProtonMissing(context: Context): Boolean {
val extras = com.droiddeck.launcher.session.ProtonExtras
return extras.installedAll(context, extras.tools.first { it.id == extras.OWN }).isEmpty()
}
const val DESKTOP_ID = "desktop-kde"
const val EMULATORS_ID = "emulators"
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
@@ -22,7 +22,7 @@ class RuntimeInstallService : Service() {
if (intent?.action == ACTION_PACKAGE) return holdPackage(startId)
val removal = intent?.action == ACTION_REMOVE
val release = intent?.let(::releaseFrom)
val foreground = enterForeground(notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
startForeground(NOTIFICATION_ID, notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
if (release == null && !removal) {
stopSelf(startId)
return START_NOT_STICKY
@@ -31,7 +31,7 @@ class RuntimeInstallService : Service() {
val manager = getSystemService(NotificationManager::class.java)
var shown = ""
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
if (foreground && "$stage:$percent" != shown) {
if ("$stage:$percent" != shown) {
shown = "$stage:$percent"
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
}
@@ -46,10 +46,7 @@ class RuntimeInstallService : Service() {
}
private fun holdPackage(startId: Int): Int {
if (!enterForeground(notification(packageStage, packagePercent, packageTitle))) {
stopSelf(startId)
return START_NOT_STICKY
}
startForeground(NOTIFICATION_ID, notification(packageStage, packagePercent, packageTitle))
Thread({
val manager = getSystemService(NotificationManager::class.java)
var shown = ""
@@ -68,15 +65,6 @@ class RuntimeInstallService : Service() {
return START_NOT_STICKY
}
/** Android 12+ refuses a foreground start while the app is in the background; the work then goes on without the notification. */
private fun enterForeground(notification: Notification): Boolean = try {
startForeground(NOTIFICATION_ID, notification)
true
} catch (e: IllegalStateException) {
android.util.Log.w("RuntimeInstallService", "running without a foreground service: $e")
false
}
private fun notification(stage: String, percent: Int, title: String? = null): Notification {
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime),
@@ -249,24 +249,21 @@ object ProtonExtras {
}
@Synchronized
fun install(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier? = null,
onProgress: (String, Int) -> Unit): String? {
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
installInProgress = true
return try { installNow(context, tool, cancelled, onProgress) } finally { installInProgress = false }
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
}
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit,
cancelled: java.util.function.BooleanSupplier? = null): String? {
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
onProgress(downloading, 0)
var downloaded = false
for (attempt in 0 until 5) {
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256, cancelled) { fraction ->
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256) { fraction ->
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
}
if (downloaded) break
if (cancelled?.asBoolean == true) return context.getString(R.string.pextra_interrupted)
if (attempt < 4) {
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1)
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
@@ -300,8 +297,7 @@ object ProtonExtras {
return problem
}
private fun installNow(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier?,
onProgress: (String, Int) -> Unit): String? {
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
@@ -316,7 +312,7 @@ object ProtonExtras {
val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) &&
checkedDigest.equals(asset.sha256, ignoreCase = true)
if (!checked) fetchArchive(context, tool, asset, archive, onProgress, cancelled)?.let { return it }
if (!checked) fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
if (asset.size > 0 && archive.length() != asset.size) {
if (archive.length() > asset.size) {
archive.delete()
@@ -448,13 +448,6 @@ object SessionPrefs {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
fun appsTabHomeSeen(context: Context): Boolean? =
prefs(context).takeIf { it.contains("appsTabHomeSeen") }?.getBoolean("appsTabHomeSeen", false)
fun setAppsTabHomeSeen(context: Context, seen: Boolean) {
prefs(context).edit().putBoolean("appsTabHomeSeen", seen).apply()
}
private fun idList(raw: String?): List<String> = raw.orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() }
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
@@ -845,15 +838,6 @@ object SessionPrefs {
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
fun valveProtonOnDemand(context: Context): Boolean = prefs(context).getBoolean("valveProtonOnDemand", true)
fun setValveProtonOnDemand(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("valveProtonOnDemand", on).apply()
}
/** DroidDeck-Proton is the Proton placed before the client starts; Valve's ARM64 Proton waits for a title that needs it. */
fun ownProtonFirst(context: Context): Boolean = valveProtonOnDemand(context) && !ProtonExtras.declined(context)
fun setReturnAfterGame(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("returnAfterGame", on).apply()
}
@@ -1002,7 +1002,6 @@ class SessionService : Service() {
))
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
if (SessionState.mode == MODE_STEAM) SessionPrefs.pendingShaderPrecache(this)?.let { guest.add("DD_SHADER_PRECACHE=" + if (it) "1" else "0") }
guest.add("DD_VALVE_PROTON=" + if (SessionPrefs.ownProtonFirst(this)) "0" else "1")
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
@@ -93,7 +93,6 @@ class ModeSettings(
val steamClientArch: String? = null,
val returnAfterGame: Boolean? = null,
val shaderPrecache: Boolean? = null,
val valveProtonOnDemand: Boolean? = null,
val steamRepairQueued: Boolean = false,
val mangoapp: Boolean = true,
val steamController: String? = null,
@@ -159,7 +158,6 @@ class ModeSettingsActions(
val onMangoapp: (Boolean) -> Unit = {},
val onReturnAfterGame: (Boolean) -> Unit = {},
val onShaderPrecache: (Boolean) -> Unit = {},
val onValveProtonOnDemand: (Boolean) -> Unit = {},
val onSteamController: (String) -> Unit = {},
val onUnfoldedControls: (Boolean) -> Unit = {},
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
@@ -536,10 +534,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.mode_shader_precache_hint),
s.shaderPrecache, onChange = a.onShaderPrecache,
)
if (s.valveProtonOnDemand != null) ToggleRow(
host, "valveprotonondemand", stringResource(R.string.mode_valve_proton_on_demand), null,
s.valveProtonOnDemand, onChange = a.onValveProtonOnDemand,
)
SettingsRow(
stringResource(R.string.mode_steam_repair),
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
@@ -27,9 +27,9 @@ internal object DeveloperTools {
internal object NavTabs {
const val MORE = "more"
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "agent")
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "agent")
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync")
private const val LAYOUT_VERSION = 2
@@ -95,15 +95,6 @@ internal object NavTabs {
else -> true
}
// Apps only has content when DroidDeck is the home app, so it follows that state on each change and
// otherwise stays wherever the user put it.
fun syncHomeApps(context: Context, homeSelected: Boolean) {
val seen = SessionPrefs.appsTabHomeSeen(context)
SessionPrefs.setAppsTabHomeSeen(context, homeSelected)
if (seen == homeSelected || (seen == null && !homeSelected)) return
setHidden(context, "android-apps", !homeSelected)
}
fun hideable(key: String) = key != "setup"
fun place(s: FrontEndState, key: String): TabPlace = when {
-1
View File
@@ -383,7 +383,6 @@
<string name="mode_return_after_game">Return to DroidDeck after a game</string>
<string name="mode_return_after_game_hint">When a game you started from DroidDeck or another launcher closes, Steam exits cleanly (cloud saves finish first) and you go back there. Off: stay in Steam.</string>
<string name="mode_shader_precache">Shader pre-caching</string>
<string name="mode_valve_proton_on_demand">Valve Proton only when needed</string>
<string name="mode_shader_precache_hint">Steam downloads shaders prebuilt for your games and processes them in the background, so games stutter less. Off saves data, storage and battery; games build shaders as they play instead. The same setting as Steam’s Downloads > Shader Pre-Caching. Applies next session.</string>
<string name="mode_steam_repair">Repair Steam client</string>
<string name="mode_steam_repair_hint">Downloads the Steam client again the next time Steam starts. Use it if Steam stays on its loading screen. Games, sign-in and settings are kept.</string>
@@ -48,21 +48,6 @@ class NavTabsTest {
assertTrue(NavTabs.isDefault())
}
@Test fun appsFollowsTheHomeAppOnEachChangeAndOtherwiseKeepsTheUsersChoice() {
NavTabs.syncHomeApps(ctx, false)
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
NavTabs.syncHomeApps(ctx, true)
assertEquals(TabPlace.BAR, NavTabs.place(state(), "android-apps"))
NavTabs.setHidden(ctx, "android-apps", true)
NavTabs.syncHomeApps(ctx, true)
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
NavTabs.syncHomeApps(ctx, false)
NavTabs.syncHomeApps(ctx, true)
assertEquals(TabPlace.BAR, NavTabs.place(state(), "android-apps"))
NavTabs.syncHomeApps(ctx, false)
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
}
@Test fun showingMusicOnceKeepsItShownAfterReload() {
place("soundtracks", TabPlace.BAR)
NavTabs.load(ctx)
@@ -234,12 +219,12 @@ class NavTabsTest {
}
}
}
val last = NavTabs.listed(state()).last { it !in NavTabs.shelved }
val last = navigationKeys(state()).last { it != NavTabs.MORE }
compose.onNodeWithTag("tab-row-$last").requestFocus()
compose.onNodeWithTag("tab-row-$last").performKeyPress(pad(android.view.KeyEvent.KEYCODE_BUTTON_Y))
compose.onNodeWithTag("tab-row-$last").performKeyPress(pad(android.view.KeyEvent.KEYCODE_DPAD_DOWN))
compose.onNodeWithTag("tab-row-$last").performKeyPress(pad(android.view.KeyEvent.KEYCODE_BUTTON_Y))
compose.runOnIdle { assertTrue(last in NavTabs.shelved) }
compose.runOnIdle { assertEquals(last, NavTabs.more(state()).first()) }
compose.onNodeWithTag("tab-shown-desktop").performClick()
compose.runOnIdle { assertFalse("desktop" in navigationKeys(state())) }
compose.onNodeWithTag("tab-shown-setup").performClick()
@@ -1169,10 +1169,7 @@ case $mode in
"${DD_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam" &&
echo "$DD_SHADER_PRECACHE" > "$HOME/.dd-shader-precache-applied" || true
fi
if [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ] &&
! steam-compatibility "$steam_root" --valve-proton-needed; then
step "leaving Valve's ARM64 Proton until a title needs it"
elif [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
if [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
step "asking the client to fetch the ARM64 Proton"
set -- "$@" steam://install/4427310
(
@@ -966,7 +966,6 @@ class Helper:
self.fex_asked = set()
self.tools_asked = {}
self.tools_checked = None
self.valve_names = None
self.vr_launch = None
self.chooser = None
self.controls_state = None
@@ -1257,10 +1256,6 @@ class Helper:
page.compat("set(%d, %s)" % (int(app), json.dumps(tool if tool is not None else "")))
say("%s -> %s" % ("default" if app == "0" else "app %s" % app,
tool if tool is not None else "Steam native default"))
names = set(dict(current, **changes).values()) | {default}
if COMPAT["uses_valve_proton"](names) and not COMPAT["uses_valve_proton"](self.valve_names or ()):
self.tools_checked = None
self.valve_names = names
state.update(
auto={app: tool for app, tool in auto.items() if tool is not COMPAT["NATIVE_CHOICE"]},
native_choices=sorted(refused_native | {app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]}),
@@ -1281,8 +1276,7 @@ class Helper:
self.tools_checked = now
if COMPAT["game_running"]():
return
needed = COMPAT["valve_proton_needed"](self.steam_root, self.valve_names)
for app, action in COMPAT["tool_downloads"](self.steam_root, needed):
for app, action in COMPAT["tool_downloads"](self.steam_root):
if now - self.tools_asked.get(app, -TOOL_RETRY_SECONDS) < TOOL_RETRY_SECONDS:
continue
self.tools_asked[app] = now
@@ -26,9 +26,6 @@ SNIPER_APPID = "1628350"
SLR4_APPID = "4183110"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID)
REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES
# "0" = the app's "Valve Proton only when needed": Valve's ARM64 Proton is fetched only for a title or
# default set to a tool built from it, or while no own Proton build is installed.
VALVE_PROTON_ENV = "DD_VALVE_PROTON"
# Linux builds that bundle an arm64 binary their launcher starts; Steamworks offers no arm64
# launch-option architecture, so appinfo cannot say so (#1774).
FEX_DEFAULT_APPS = frozenset({"4385780"})
@@ -1011,33 +1008,11 @@ def manifest_flags(tokens):
return 0
def valve_proton_on_demand():
return os.environ.get(VALVE_PROTON_ENV) == "0"
def uses_valve_proton(names):
return any(name == TOOL or VALVE_DEPOTS.get(name) == SOURCES[0] for name in names if name)
def valve_proton_needed(steam_root, names=None):
if not valve_proton_on_demand():
return True
if not own_builds(tool_catalog(steam_root)):
return True
if names is None:
names = set((read_config_mapping(os.path.join(steam_root, "config", "config.vdf")) or {}).values())
names.add(read_json(state_path("state.json")).get("default"))
return uses_valve_proton(names)
def tool_downloads(steam_root, valve_needed=None):
def tool_downloads(steam_root):
wanted = []
for app in REQUIRED_TOOLS:
tokens = app_manifest(steam_root, app)
if tokens is None:
if app == PROTON_ARM64_APPID and not (
valve_proton_needed(steam_root) if valve_needed is None else valve_needed):
continue
wanted.append((app, "install"))
elif not manifest_flags(tokens) & FULLY_INSTALLED or manifest_flags(tokens) & UPDATE_REQUIRED:
wanted.append((app, "update"))
@@ -1780,8 +1755,6 @@ def x64_repoint(steam_root, tool, live=False):
def main():
steam_root = sys.argv[1]
if "--valve-proton-needed" in sys.argv[2:]:
sys.exit(0 if valve_proton_needed(steam_root) else 1)
if "--x64" in sys.argv[2:]:
x64_repoint(steam_root, os.environ.get("DD_COMPAT_TOOL"), "--live" in sys.argv[2:])
return
@@ -1800,7 +1773,6 @@ def main():
build_tool(os.path.join(tools, name), depot, sources, name)
print("steam-compatibility: registered %s (%s)" % (
name, "depot %s present" % os.path.basename(depot) if depot else
"no ARM64 Proton depot yet; fetched when a title needs it" if valve_proton_on_demand() else
"no ARM64 Proton depot yet; the session asks the client to fetch it"))
build_fex_tool(os.path.join(tools, FEX_TOOL))
print("steam-compatibility: registered %s" % FEX_TOOL)
+55 -3
View File
@@ -16,6 +16,7 @@
#include <limits.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/route.h>
#include <netpacket/packet.h>
#include <netinet/in.h>
#include <pthread.h>
@@ -533,6 +534,8 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
}
}
#define ROUTE_TABLE 0
#define IPV6_ROUTE_TABLE 1
#define CARRIER_TABLE 5
#define SOCKET_TABLES 6
@@ -606,6 +609,48 @@ static FILE *synthesize(int table) {
return out;
}
static int link_has_gateway(int family) {
struct link link;
if (!load_link(&link)) return 0;
for (int i = 0; i < link.gateway_count; i++) {
if (link.gateways[i].family == family) return 1;
}
return 0;
}
static int default_route_line(const char *line, int table) {
unsigned flags, prefix;
if (table == ROUTE_TABLE) {
unsigned destination, gateway, mask;
return sscanf(line, "%*s %x %x %x %*d %*d %*d %x", &destination, &gateway, &flags, &mask) == 4
&& destination == 0 && mask == 0 && (flags & RTF_UP);
}
char destination[33];
return sscanf(line, "%32s %x %*s %*x %*s %*x %*x %*x %x", destination, &prefix, &flags) == 3
&& prefix == 0 && strspn(destination, "0") == 32 && (flags & RTF_UP) && !(flags & RTF_REJECT);
}
static int misses_default_route(int fd, int table) {
if (table != ROUTE_TABLE && table != IPV6_ROUTE_TABLE) return 0;
if (!link_has_gateway(table == ROUTE_TABLE ? AF_INET : AF_INET6)) return 0;
size_t capacity = 65536, size = 0;
char *text = malloc(capacity + 1);
if (text == NULL) return 0;
ssize_t got = 1;
while (size < capacity && (got = pread(fd, text + size, capacity - size, (off_t) size)) > 0) size += (size_t) got;
int misses = got == 0;
text[size] = '\0';
for (char *line = text; misses && *line;) {
char *end = strchr(line, '\n');
if (end) *end = '\0';
if (default_route_line(line, table)) misses = 0;
if (end == NULL) break;
line = end + 1;
}
free(text);
return misses;
}
int dd_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
const char *dd_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden")));
@@ -623,6 +668,12 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
FILE *f;
if (table >= 0 && denied_recently(table, path) && (f = synthesize(table)) != NULL) return f;
f = real(path, mode);
if (f && table >= 0 && misses_default_route(fileno(f), table)) {
FILE *link_table = synthesize(table);
if (link_table == NULL) return f;
fclose(f);
return link_table;
}
if (f || table < 0) return f;
int saved = errno;
if ((f = synthesize(table)) != NULL) {
@@ -636,9 +687,9 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden")));
int dd_net_open(const char *path, int flags, int fd) {
if (fd >= 0 || path == NULL || (flags & O_ACCMODE) != O_RDONLY || (flags & O_DIRECTORY)) return fd;
if (path == NULL || (flags & O_ACCMODE) != O_RDONLY || (flags & O_DIRECTORY)) return fd;
int table = denied_table(path);
if (table < 0) return fd;
if (table < 0 || (fd >= 0 && !misses_default_route(fd, table))) return fd;
int saved = errno;
FILE *f = synthesize(table);
if (f == NULL) {
@@ -656,7 +707,8 @@ int dd_net_open(const char *path, int flags, int fd) {
errno = saved;
return fd;
}
if (saved == EACCES) remember_denial(table, path);
if (fd >= 0) close(fd);
else if (saved == EACCES) remember_denial(table, path);
return copy;
}
+7 -77
View File
@@ -40,35 +40,6 @@ struct vd_dma_heap_alloc {
};
#define VD_DMA_HEAP_IOCTL_ALLOC _IOWR('H', 0x0, struct vd_dma_heap_alloc)
struct vd_ion_alloc {
uint64_t len;
uint32_t heap_id_mask;
uint32_t flags;
uint32_t fd;
uint32_t unused;
};
struct vd_ion_legacy_alloc {
size_t len;
size_t align;
uint32_t heap_id_mask;
uint32_t flags;
int32_t handle;
};
struct vd_ion_fd {
int32_t handle;
int32_t fd;
};
struct vd_ion_handle {
int32_t handle;
};
#define VD_ION_IOC_ALLOC _IOWR('I', 0, struct vd_ion_alloc)
#define VD_ION_IOC_LEGACY_ALLOC _IOWR('I', 0, struct vd_ion_legacy_alloc)
#define VD_ION_IOC_FREE _IOWR('I', 1, struct vd_ion_handle)
#define VD_ION_IOC_SHARE _IOWR('I', 4, struct vd_ion_fd)
#define VD_ION_SYSTEM_HEAP_MASK (1u << 25)
enum { VD_HEAP_DMA, VD_HEAP_ION, VD_HEAP_ION_LEGACY };
struct vd_dma_buf_sync {
uint64_t flags;
};
@@ -201,7 +172,6 @@ static int vd_open_count;
static int vd_state;
static int vd_ffmpeg;
static int vd_heap = -1;
static int vd_heap_kind;
static int vd_dumb_fd[VDEC_DUMB];
static char vd_drm_handle;
@@ -256,54 +226,15 @@ static int vd_have_ffmpeg(void) {
__attribute__((visibility("hidden"))) int dd_venc_connect(void);
static int vd_open_heap(void) {
vd_heap = open("/dev/dma_heap/system", O_RDONLY | O_CLOEXEC);
if (vd_heap >= 0) {
vd_heap_kind = VD_HEAP_DMA;
return 1;
}
int heap_errno = errno;
vd_heap = open("/dev/ion", O_RDONLY | O_CLOEXEC);
if (vd_heap < 0) {
int ion_errno = errno;
vd_log("no /dev/dma_heap/system (%s) or /dev/ion (%s), Remote Play decoding stays off", strerror(heap_errno),
strerror(ion_errno));
return 0;
}
struct vd_ion_handle probe = { 0 };
vd_heap_kind = ioctl(vd_heap, VD_ION_IOC_FREE, &probe) >= 0 || errno != ENOTTY ? VD_HEAP_ION_LEGACY : VD_HEAP_ION;
vd_log("no /dev/dma_heap/system (%s), Remote Play buffers come from %s", strerror(heap_errno),
vd_heap_kind == VD_HEAP_ION ? "ION" : "legacy ION");
return 1;
}
static int vd_heap_alloc(uint64_t size) {
if (vd_heap_kind == VD_HEAP_DMA) {
struct vd_dma_heap_alloc a = { .len = size, .fd_flags = O_RDWR | O_CLOEXEC };
return ioctl(vd_heap, VD_DMA_HEAP_IOCTL_ALLOC, &a) == 0 ? (int)a.fd : -1;
}
if (vd_heap_kind == VD_HEAP_ION) {
struct vd_ion_alloc a = { .len = size, .heap_id_mask = VD_ION_SYSTEM_HEAP_MASK };
return ioctl(vd_heap, VD_ION_IOC_ALLOC, &a) == 0 ? (int)a.fd : -1;
}
struct vd_ion_legacy_alloc a = { .len = (size_t)size, .align = 4096, .heap_id_mask = VD_ION_SYSTEM_HEAP_MASK };
if (ioctl(vd_heap, VD_ION_IOC_LEGACY_ALLOC, &a) != 0) return -1;
struct vd_ion_fd share = { .handle = a.handle, .fd = -1 };
int shared = ioctl(vd_heap, VD_ION_IOC_SHARE, &share) == 0;
int share_errno = errno;
struct vd_ion_handle handle = { .handle = a.handle };
ioctl(vd_heap, VD_ION_IOC_FREE, &handle);
errno = share_errno;
return shared ? share.fd : -1;
}
static int vd_enabled(void) {
pthread_mutex_lock(&vd_lock);
if (vd_state == 0) {
const char *flag = getenv("DD_REMOTE_PLAY_DECODE"), *socket = getenv("DD_VENC_SOCKET");
vd_state = -1;
if (strcmp(program_invocation_short_name, "streaming_client") == 0 && (flag == NULL || strcmp(flag, "0") != 0)) {
if (vd_open_heap() && ((socket && *socket) || vd_have_ffmpeg())) vd_state = 1;
vd_heap = open("/dev/dma_heap/system", O_RDONLY | O_CLOEXEC);
if (vd_heap < 0) vd_log("no /dev/dma_heap/system (%s), Remote Play decoding stays off", strerror(errno));
else if ((socket && *socket) || vd_have_ffmpeg()) vd_state = 1;
for (int i = 0; i < VDEC_DUMB; i++) vd_dumb_fd[i] = -1;
}
}
@@ -1102,15 +1033,14 @@ static int drm_ioctl(int fd, unsigned long request, void *arg) {
uint64_t size = (pitch * c->height + 4095) & ~4095ull;
int slot = -1;
for (int i = 0; i < VDEC_DUMB && slot < 0; i++) if (vd_dumb_fd[i] < 0) slot = i;
int buf = -1;
struct vd_dma_heap_alloc a = { .len = size, .fd_flags = O_RDWR | O_CLOEXEC };
if (slot < 0 || size == 0 || size > (512ull << 20)) {
r = -ENOMEM;
} else if ((buf = vd_heap_alloc(size)) < 0) {
} else if (ioctl(vd_heap, VD_DMA_HEAP_IOCTL_ALLOC, &a) != 0) {
r = -errno;
vd_log("%s allocation of %llu bytes failed: %s", vd_heap_kind == VD_HEAP_DMA ? "dma-heap" : "ION",
(unsigned long long)size, strerror(errno));
vd_log("dma-heap allocation of %llu bytes failed: %s", (unsigned long long)size, strerror(errno));
} else {
vd_dumb_fd[slot] = buf;
vd_dumb_fd[slot] = (int)a.fd;
c->handle = (uint32_t)slot + 1;
c->pitch = (uint32_t)pitch;
c->size = size;
-37
View File
@@ -1430,43 +1430,6 @@ class AppInfoTest(unittest.TestCase):
self.manifest(steam, app)
self.assertEqual(downloads(str(steam)), [])
def test_valve_proton_on_demand_waits_for_a_title_that_uses_it(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
for app in ("3127680", "1628350", "4183110"):
self.manifest(steam, app)
downloads, needed, tool = self.COMPAT["tool_downloads"], self.COMPAT["valve_proton_needed"], self.COMPAT["TOOL"]
own = steam / "compatibilitytools.d/DroidDeck-Proton 11-14.1"
with mock.patch.dict(os.environ, {"DD_VALVE_PROTON": "0"}):
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
ge = steam / "compatibilitytools.d/GE-Proton10-25"
ge.mkdir(parents=True)
(ge / "droiddeck-proton-wrap").write_text("")
(ge / "compatibilitytool.vdf").write_text(
'"compatibilitytools" { "compat_tools" { "GE-Proton10-25" { "install_path" "." } } }')
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
own.mkdir(parents=True)
(own / "droiddeck-proton-wrap").write_text("")
(own / "compatibilitytool.vdf").write_text(
'"compatibilitytools" { "compat_tools" { "DroidDeck-Proton-11-14.1" { "install_path" "." } } }')
self.assertEqual(downloads(str(steam)), [])
self.assertFalse(needed(str(steam), {"DroidDeck-Proton-11-14.1", None}))
self.assertTrue(needed(str(steam), {"DroidDeck-Proton-11-14.1", tool}))
self.assertTrue(needed(str(steam), {"proton-experimental-arm64"}))
self.assertEqual(downloads(str(steam), True), [("4427310", "install")])
config = steam / "config/config.vdf"
config.parent.mkdir()
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { '
'"0" { "name" "DroidDeck-Proton-11-14.1" "config" "" "priority" "75" } '
'"10" { "name" "%s" "config" "" "priority" "250" } } } } } }' % tool)
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
config.unlink()
self.manifest(steam, "4427310", flags="6")
self.assertEqual(downloads(str(steam), False), [("4427310", "update")])
with mock.patch.dict(os.environ, {"DD_VALVE_PROTON": "1"}):
(steam / "steamapps/appmanifest_4427310.acf").unlink()
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
def test_titles_with_a_valve_pick_are_found_installed_or_not(self):
def deck(oslist, runtime, kind="game"):
common = {"type": kind, "oslist": oslist, "steam_deck_compatibility": {"configuration": {"recommended_runtime": runtime}}}
+82 -5
View File
@@ -87,12 +87,21 @@ int getsockopt(int fd, int level, int option, void *value, socklen_t *len) {
return real(fd, level, option, value, len);
}
static __thread char fixture_path[4096];
static const char *table_fixture(const char *path) {
const char *directory = getenv("NETLINK_TEST_TABLES");
if (!directory || !path || strncmp(path, "/proc/net/", 10)) return path;
snprintf(fixture_path, sizeof(fixture_path), "%s/%s", directory, path + 10);
return access(fixture_path, F_OK) == 0 ? fixture_path : path;
}
FILE *fopen(const char *path, const char *mode) {
static FILE *(*real)(const char *, const char *);
if (!real) real = dlsym(RTLD_NEXT, "fopen");
const char *snapshot = getenv("NETLINK_TEST_SNAPSHOT");
if (snapshot && !strcmp(path, "/etc/droiddeck-net")) path = snapshot;
return real(path, mode);
return real(table_fixture(path), mode);
}
static int denied(const char *path) {
@@ -116,13 +125,13 @@ int open(const char *path, int flags, ...) {
va_start(ap, flags);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
return denied(path) ? -1 : real(path, flags, mode);
return denied(path) ? -1 : real(table_fixture(path), flags, mode);
}
int __open_2(const char *path, int flags) {
static int (*real)(const char *, int);
if (!real) real = dlsym(RTLD_NEXT, "__open_2");
return denied(path) ? -1 : real(path, flags);
return denied(path) ? -1 : real(table_fixture(path), flags);
}
int openat(int dirfd, const char *path, int flags, ...) {
@@ -132,7 +141,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
va_start(ap, flags);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
return denied(path) ? -1 : real(dirfd, path, flags, mode);
return denied(path) ? -1 : real(dirfd, table_fixture(path), flags, mode);
}
int close_range(unsigned int first, unsigned int last, int flags) {
@@ -214,6 +223,37 @@ static void proc_net_test(int denied, int sealed) {
}
}
static const char *table_source(int descriptor) {
char link[64], target[4096];
snprintf(link, sizeof(link), "/proc/self/fd/%d", descriptor);
ssize_t length = readlink(link, target, sizeof(target) - 1);
require(length > 0, "route table target");
target[length] = 0;
return strncmp(target, "/memfd:droiddeck-net", 20) == 0 ? "link" : "real";
}
static void route_tables_test(void) {
static const char *const tables[] = {"/proc/net/route", "/proc/net/ipv6_route"};
static const char *const gateways[] = {"\t00000000\t0101A8C0\t0003\t", "20010db8000000000000000000000001 "};
char text[4096];
for (unsigned i = 0; i < 2; i++) {
FILE *stream = fopen(tables[i], "r");
require(stream != NULL, "route table fopen");
const char *source = table_source(fileno(stream));
size_t total = fread(text, 1, sizeof(text) - 1, stream);
text[total] = 0;
require(strcmp(source, "link") || strstr(text, gateways[i]), "link table lists the default gateway");
printf("%s ", source);
fclose(stream);
int descriptor = i ? openat(AT_FDCWD, tables[i], O_RDONLY | O_CLOEXEC) : open(tables[i], O_RDONLY | O_CLOEXEC);
require(descriptor >= 0, "route table open");
require(fcntl(descriptor, F_GETFD) & FD_CLOEXEC, "route table keeps close-on-exec");
printf("%s ", table_source(descriptor));
close(descriptor);
}
printf("\n");
}
static unsigned port_of(int descriptor) {
struct sockaddr_nl address;
socklen_t length = sizeof(address);
@@ -1209,6 +1249,7 @@ int main(int argc, char **argv) {
}
else if (!strcmp(argv[1], "range") || !strcmp(argv[1], "cloexec") || !strcmp(argv[1], "closefrom"))
close_range_test(argv[1]);
else if (!strcmp(argv[1], "route_tables")) route_tables_test();
else if (!strcmp(argv[1], "proc_net")) proc_net_test(argc > 2 && strcmp(argv[2], "allowed"), argc > 2 && !strcmp(argv[2], "sealed"));
else if (!strcmp(argv[1], "route")) {
require(argc >= 3, "route destination");
@@ -1218,6 +1259,21 @@ int main(int argc, char **argv) {
}
"""
ROUTE_HEADER = "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n"
ZERO_V6 = "0" * 32
ANDROID_ROUTE_TABLES = {
"route": ROUTE_HEADER + "wlan0\t0001A8C0\t00000000\t0001\t0\t0\t0\t00FFFFFF\t0\t0\t0\n",
"ipv6_route": f"fe800000000000000000000000000000 40 {ZERO_V6} 00 {ZERO_V6} 00000100 00000001 00000000 00000001 wlan0\n"
f"{ZERO_V6} 00 {ZERO_V6} 00 {ZERO_V6} ffffffff 00000001 00000000 00200200 lo\n",
}
DEFAULT_ROUTE_TABLES = {
"route": ANDROID_ROUTE_TABLES["route"] + "wlan0\t00000000\t0101A8C0\t0003\t0\t0\t600\t00000000\t0\t0\t0\n",
"ipv6_route": ANDROID_ROUTE_TABLES["ipv6_route"]
+ f"{ZERO_V6} 00 {ZERO_V6} 00 fe800000000000000000000000000001 00000400 00000001 00000000 00450003 wlan0\n",
}
SNAPSHOT = """if wlan0 2 1500
mac 02:11:22:33:44:55
addr 192.168.1.10 24
@@ -1257,12 +1313,14 @@ class NetlinkPreloadTest(unittest.TestCase):
def tearDownClass(cls):
cls.temp.cleanup()
def run_program(self, mode, *arguments, snapshot=None, denied=None):
def run_program(self, mode, *arguments, snapshot=None, denied=None, tables=None):
env = dict(os.environ, LD_PRELOAD=f"{self.preload}:{self.shim}",
NETLINK_TEST_SNAPSHOT=str(snapshot or self.snapshot),
DD_SYSV_DIR=str(self.directory / "sysv"))
if denied:
env["NETLINK_TEST_DENIED"] = denied
if tables:
env["NETLINK_TEST_TABLES"] = str(tables)
result = subprocess.run([str(self.program), mode, *arguments], env=env,
capture_output=True, text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
@@ -1391,6 +1449,25 @@ class NetlinkPreloadTest(unittest.TestCase):
def test_readable_socket_tables_stay_real(self):
self.run_program("proc_net")
def route_tables(self, name, contents):
directory = self.directory / name
directory.mkdir(exist_ok=True)
for table, text in contents.items():
(directory / table).write_text(text)
return directory
def test_route_tables_without_a_default_route_answer_from_the_link(self):
tables = self.route_tables("android-routes", ANDROID_ROUTE_TABLES)
self.assertEqual(["link"] * 4, self.run_program("route_tables", tables=tables))
def test_route_tables_with_a_default_route_stay_real(self):
tables = self.route_tables("default-routes", DEFAULT_ROUTE_TABLES)
self.assertEqual(["real"] * 4, self.run_program("route_tables", tables=tables))
def test_route_tables_stay_real_when_the_link_has_no_gateway(self):
tables = self.route_tables("android-routes", ANDROID_ROUTE_TABLES)
self.assertEqual(["real"] * 4, self.run_program("route_tables", tables=tables, snapshot=self.direct))
def test_loopback_and_own_addresses_are_local_routes(self):
for destination, source in (("127.0.0.2", "127.0.0.1"), ("::1", "::1"),
("192.168.1.10", "192.168.1.10"), ("2001:db8::10", "2001:db8::10")):
+21 -104
View File
@@ -39,19 +39,8 @@ struct create_dumb { uint32_t height, width, bpp, flags, handle, pitch; uint64_t
struct prime_handle { uint32_t handle, flags; int32_t fd; };
struct destroy_dumb { uint32_t handle; };
struct drm_device { char **nodes; int available_nodes; };
struct ion_alloc { uint64_t len; uint32_t heap_id_mask, flags, fd, unused; };
struct ion_legacy_alloc { size_t len, align; uint32_t heap_id_mask, flags; int32_t handle; };
struct ion_fd { int32_t handle, fd; };
struct ion_handle { int32_t handle; };
#define HEAP_DMA 0
#define HEAP_ION 1
#define HEAP_ION_LEGACY 2
#define HEAP_NONE 3
#define HEAP_PATH (HEAP_MODE == HEAP_DMA ? "/dev/dma_heap/system" : HEAP_MODE == HEAP_NONE ? "" : "/dev/ion")
static int heap = -1;
static int ion_handles[8];
int open(const char *path, int flags, ...) {
static int (*real)(const char *, int, ...);
@@ -60,62 +49,10 @@ int open(const char *path, int flags, ...) {
int mode = va_arg(ap, int);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "open");
if (strcmp(path, HEAP_PATH) == 0) return heap = memfd_create("heap", 0);
if (strcmp(path, "/dev/dma_heap/system") == 0 || strcmp(path, "/dev/ion") == 0) {
errno = ENOENT;
return -1;
}
if (strcmp(path, "/dev/dma_heap/system") == 0) return heap = memfd_create("heap", 0);
return real(path, flags, mode);
}
static int new_buffer(uint64_t len) {
int buf = memfd_create("dmabuf", MFD_CLOEXEC);
if (buf < 0 || ftruncate(buf, (off_t)len) != 0) return -1;
return buf;
}
static int heap_ioctl(unsigned long req, void *arg) {
if (HEAP_MODE == HEAP_DMA && req == _IOWR('H', 0, struct heap_alloc)) {
struct heap_alloc *a = arg;
int buf = new_buffer(a->len);
if (buf < 0) return -1;
a->fd = (uint32_t)buf;
return 0;
}
if (HEAP_MODE == HEAP_ION && req == _IOWR('I', 0, struct ion_alloc)) {
struct ion_alloc *a = arg;
int buf = a->heap_id_mask == 1u << 25 ? new_buffer(a->len) : (errno = ENODEV, -1);
if (buf < 0) return -1;
a->fd = (uint32_t)buf;
return 0;
}
if (HEAP_MODE == HEAP_ION_LEGACY && req == _IOWR('I', 0, struct ion_legacy_alloc)) {
struct ion_legacy_alloc *a = arg;
if (a->heap_id_mask != 1u << 25 || a->align != 4096) return errno = ENODEV, -1;
for (int i = 0; i < 8; i++) {
if (ion_handles[i] >= 0) continue;
if ((ion_handles[i] = new_buffer(a->len)) < 0) return -1;
a->handle = i + 1;
return 0;
}
return errno = ENOMEM, -1;
}
if (HEAP_MODE == HEAP_ION_LEGACY && req == _IOWR('I', 4, struct ion_fd)) {
struct ion_fd *s = arg;
if (s->handle < 1 || s->handle > 8 || ion_handles[s->handle - 1] < 0) return errno = EINVAL, -1;
s->fd = fcntl(ion_handles[s->handle - 1], F_DUPFD_CLOEXEC, 0);
return s->fd < 0 ? -1 : 0;
}
if (HEAP_MODE == HEAP_ION_LEGACY && req == _IOWR('I', 1, struct ion_handle)) {
struct ion_handle *h = arg;
if (h->handle < 1 || h->handle > 8 || ion_handles[h->handle - 1] < 0) return errno = EINVAL, -1;
close(ion_handles[h->handle - 1]);
ion_handles[h->handle - 1] = -1;
return 0;
}
return errno = ENOTTY, -1;
}
int ioctl(int fd, unsigned long req, ...) {
static int (*real)(int, unsigned long, ...);
va_list ap;
@@ -123,7 +60,13 @@ int ioctl(int fd, unsigned long req, ...) {
void *arg = va_arg(ap, void *);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "ioctl");
if (fd >= 0 && fd == heap) return heap_ioctl(req, arg);
if (fd == heap && req == _IOWR('H', 0, struct heap_alloc)) {
struct heap_alloc *a = arg;
int buf = memfd_create("dmabuf", 0);
if (ftruncate(buf, (off_t)a->len) != 0) return -1;
a->fd = (uint32_t)buf;
return 0;
}
if (req == _IOW('b', 0, uint64_t)) return 0;
return real(fd, req, arg);
}
@@ -136,7 +79,6 @@ static int call(unsigned long req, void *arg) {
}
int main(void) {
for (int i = 0; i < 8; i++) ion_handles[i] = -1;
if (dd_vdec_open("/dev/video0", O_RDWR) != -2) return 2;
void *drm = SDL_LoadObject("libdrm.so.2");
if (!drm) return 3;
@@ -243,7 +185,6 @@ int main(void) {
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0);
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)4096 * 2304]);
dd_vdec_closed(vfd);
for (int i = 0; i < 8; i++) if (ion_handles[i] >= 0) return 38;
return 0;
}
'''
@@ -301,27 +242,21 @@ class FakeDecoder(threading.Thread):
conn.send(RESULT.pack(9, 0, 1))
HEAP_DMA, HEAP_ION, HEAP_ION_LEGACY, HEAP_NONE = range(4)
class VdecEmulatorTest(unittest.TestCase):
def run_client(self, tmp, heap):
driver = tmp / 'driver.c'
driver.write_text(DRIVER)
binary = tmp / 'streaming_client'
subprocess.run(['cc', '-O1', '-pthread', '-DDD_VDEC_ANY_ARCH', f'-DHEAP_MODE={heap}', '-o', str(binary),
str(driver), str(VDEC), str(VENC), '-ldl'], check=True)
sock = tmp / 'venc.sock'
server = FakeDecoder(str(sock))
self.addCleanup(server.listener.close)
server.start()
done = subprocess.run([str(binary)], env=dict(os.environ, DD_VENC_SOCKET=str(sock)),
capture_output=True, text=True, timeout=20)
return done, server
def assert_decodes(self, heap):
def test_remote_play_client_decodes_through_the_app_socket(self):
with tempfile.TemporaryDirectory() as tmp:
done, server = self.run_client(Path(tmp), heap)
tmp = Path(tmp)
driver = tmp / 'driver.c'
driver.write_text(DRIVER)
binary = tmp / 'streaming_client'
subprocess.run(['cc', '-O1', '-pthread', '-DDD_VDEC_ANY_ARCH', '-o', str(binary), str(driver), str(VDEC),
str(VENC), '-ldl'], check=True)
sock = tmp / 'venc.sock'
server = FakeDecoder(str(sock))
self.addCleanup(server.listener.close)
server.start()
done = subprocess.run([str(binary)], env=dict(os.environ, DD_VENC_SOCKET=str(sock)),
capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
self.assertEqual(done.stdout.split('\n')[:6],
['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu'])
@@ -329,24 +264,6 @@ class VdecEmulatorTest(unittest.TestCase):
[(1, 1280, 720, 4096, 2304), (1, 1280, 720, 4096, 2304)])
self.assertEqual([p[:3] for p in server.packets],
[(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)])
return done.stderr
def test_remote_play_client_decodes_through_the_app_socket(self):
self.assertNotIn('ION', self.assert_decodes(HEAP_DMA))
def test_kernels_without_dma_heaps_decode_into_ion_buffers(self):
self.assertIn('Remote Play buffers come from ION', self.assert_decodes(HEAP_ION))
def test_kernels_with_legacy_ion_share_and_free_each_buffer(self):
self.assertIn('Remote Play buffers come from legacy ION', self.assert_decodes(HEAP_ION_LEGACY))
def test_decoding_stays_off_without_any_buffer_heap(self):
with tempfile.TemporaryDirectory() as tmp:
done, server = self.run_client(Path(tmp), HEAP_NONE)
self.assertEqual(done.returncode, 3, done.stdout + done.stderr)
self.assertIn('no /dev/dma_heap/system (No such file or directory) or /dev/ion (No such file or directory), '
'Remote Play decoding stays off', done.stderr)
self.assertEqual(server.configs, [])
def test_other_programs_keep_the_real_libdrm(self):
with tempfile.TemporaryDirectory() as tmp: