mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
Merge main into Steam client download PR
This commit is contained in:
commit
c8cc17bf3a
491 files changed
+34864
-2441
No files matched your search
@@ -30,7 +30,7 @@ object BootMovie {
|
||||
internal val AUDIO_CODECS = setOf(MediaFormat.MIMETYPE_AUDIO_OPUS, MediaFormat.MIMETYPE_AUDIO_VORBIS)
|
||||
|
||||
sealed class Import {
|
||||
data class Done(val name: String, val audioDropped: Boolean) : Import()
|
||||
data class Done(val name: String, val audioDropped: Boolean, val id: String = "") : Import()
|
||||
object TooLong : Import()
|
||||
data class Unsupported(val codec: String?) : Import()
|
||||
object Failed : Import()
|
||||
@@ -39,6 +39,21 @@ object BootMovie {
|
||||
private fun dir(context: Context) = File(context.filesDir, "boot-movie")
|
||||
private fun customFile(context: Context) = File(dir(context), "custom.webm")
|
||||
|
||||
/** A movie imported before movies were kept in Steam's own folder. */
|
||||
internal fun legacyCustomFile(context: Context) = customFile(context)
|
||||
|
||||
/** Unpacks one of DroidDeck's own movies on demand; null for anything else. */
|
||||
internal fun assetFile(context: Context, id: String): File? = ASSETS[id]?.let { extractAsset(context, it) }
|
||||
|
||||
/** Picking a movie here makes it Steam's startup movie at the next session, over whatever Steam had picked. */
|
||||
fun select(context: Context, id: String) {
|
||||
SessionPrefs.setBootMovie(context, id)
|
||||
SessionPrefs.setBootMovieApplyNext(context, true)
|
||||
BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}")
|
||||
// Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later.
|
||||
SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
|
||||
}
|
||||
|
||||
fun customName(context: Context): String? =
|
||||
if (customFile(context).isFile) SessionPrefs.bootMovieCustomName(context) ?: "custom.webm" else null
|
||||
|
||||
@@ -46,21 +61,127 @@ object BootMovie {
|
||||
val chosen = SessionPrefs.bootMovie(context)
|
||||
return when {
|
||||
chosen == CUSTOM && customFile(context).isFile -> CUSTOM
|
||||
isLibraryId(chosen) && BootMovieLibrary.file(context, chosen) != null -> chosen
|
||||
chosen in ASSETS -> chosen
|
||||
else -> DROIDDECK_30
|
||||
}
|
||||
}
|
||||
|
||||
/** The file the current choice plays from, before any volume or length change. */
|
||||
fun currentFile(context: Context): File? = sourceOf(context, choice(context))
|
||||
|
||||
private fun sourceOf(context: Context, choice: String): File? = when {
|
||||
choice == CUSTOM -> customFile(context)
|
||||
isLibraryId(choice) -> BootMovieLibrary.file(context, choice)
|
||||
else -> ASSETS[choice]?.let { extractAsset(context, it) }
|
||||
}
|
||||
|
||||
private fun isLibraryId(id: String) = id.startsWith(BootMovieLibrary.PREFIX) || id.startsWith(BootMovieLibrary.STEAM_PREFIX)
|
||||
|
||||
fun prepare(context: Context): File? {
|
||||
val choice = choice(context)
|
||||
val source = if (choice == CUSTOM) customFile(context) else extractAsset(context, ASSETS.getValue(choice)) ?: return null
|
||||
if (SessionPrefs.bootMovieSound(context)) return source
|
||||
val muted = File(source.parentFile, source.nameWithoutExtension + "-muted.webm")
|
||||
if (muted.isFile && muted.lastModified() >= source.lastModified()) return muted
|
||||
if (remux(source, muted, audio = false)) return muted
|
||||
if (BootMovieTranscoder.transcode(source, muted, keepAudio = false) {} != null) return muted
|
||||
Log.e(TAG, "could not strip audio from ${source.name}; not staging it")
|
||||
return null
|
||||
BootMovieLibrary.restore(context)
|
||||
val source = sourceOf(context, choice(context)) ?: return null
|
||||
return variant(context, source)
|
||||
}
|
||||
|
||||
/** The movie as Steam should get it: with the chosen volume and cut off after the chosen number of seconds. */
|
||||
private fun variant(context: Context, source: File): File? {
|
||||
val volume = if (SessionPrefs.bootMovieSound(context)) SessionPrefs.bootMovieVolume(context) else 0
|
||||
val seconds = SessionPrefs.bootMovieSeconds(context)
|
||||
val folder = File(dir(context), "variants")
|
||||
val plan = if (isOversized(source)) oversizedPlan(volume) else plan(volume, seconds)
|
||||
if (plan.passthrough) {
|
||||
prune(folder, null)
|
||||
return source
|
||||
}
|
||||
folder.mkdirs()
|
||||
val limitUs = if (seconds > 0) seconds * 1_000_000L else Long.MAX_VALUE
|
||||
val out = File(folder, BootMovieLibrary.variantPrefix(source) + "v$volume-s$seconds.webm")
|
||||
if (out.isFile && out.length() > 0L && out.lastModified() >= source.lastModified()) {
|
||||
prune(folder, out.name)
|
||||
return out
|
||||
}
|
||||
val staged = File(folder, out.name + ".staged")
|
||||
val ok = runCatching {
|
||||
plan.steps.any { step ->
|
||||
when (step) {
|
||||
Step.REMUX_SILENT -> remux(source, staged, audio = false, limitUs)
|
||||
Step.REMUX_AUDIO -> remux(source, staged, audio = true, limitUs)
|
||||
Step.TRANSCODE_SILENT -> transcodeSilent(source, staged, limitUs)
|
||||
Step.TRANSCODE_AUDIO -> BootMovieTranscoder.transcode(source, staged, limitUs = limitUs, gain = volume / 100f) {} != null
|
||||
Step.REGAIN -> BootMovieTranscoder.regain(source, staged, volume / 100f, limitUs)
|
||||
}
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
if (ok && staged.renameTo(out)) {
|
||||
prune(folder, out.name)
|
||||
return out
|
||||
}
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not prepare ${source.name} (volume $volume, $seconds s)")
|
||||
return if (plan.sourceOnFailure) source else null
|
||||
}
|
||||
|
||||
internal enum class Step { REMUX_SILENT, REMUX_AUDIO, TRANSCODE_SILENT, TRANSCODE_AUDIO, REGAIN }
|
||||
|
||||
/**
|
||||
* How a movie is processed: the steps tried in order until one works, whether the source goes out untouched, and
|
||||
* whether it still plays as it is when every step fails.
|
||||
*/
|
||||
internal class Plan(val passthrough: Boolean, val steps: List<Step>, val sourceOnFailure: Boolean)
|
||||
|
||||
internal fun plan(volume: Int, seconds: Int): Plan = when {
|
||||
volume == 100 && seconds == 0 -> Plan(true, emptyList(), true)
|
||||
volume == 0 -> Plan(false, listOf(Step.REMUX_SILENT, Step.TRANSCODE_SILENT), false)
|
||||
// Only a length that could not be applied plays as it is; a volume that could not be applied plays no louder.
|
||||
volume == 100 -> Plan(false, listOf(Step.REMUX_AUDIO, Step.TRANSCODE_AUDIO), true)
|
||||
else -> Plan(false, listOf(Step.REGAIN, Step.REMUX_SILENT, Step.TRANSCODE_AUDIO), false)
|
||||
}
|
||||
|
||||
/** Frames beyond 1920x1080 (4K and the like) have made Steam crash while it starts, so such a movie is always scaled down. */
|
||||
internal const val MAX_LONG_SIDE = 1920
|
||||
internal const val MAX_SHORT_SIDE = 1080
|
||||
|
||||
internal fun oversized(width: Int, height: Int) = maxOf(width, height) > MAX_LONG_SIDE || minOf(width, height) > MAX_SHORT_SIDE
|
||||
|
||||
private fun oversized(format: MediaFormat) =
|
||||
format.containsKey(MediaFormat.KEY_WIDTH) && format.containsKey(MediaFormat.KEY_HEIGHT) &&
|
||||
oversized(format.getInteger(MediaFormat.KEY_WIDTH), format.getInteger(MediaFormat.KEY_HEIGHT))
|
||||
|
||||
private fun isOversized(source: File): Boolean = probe(source)?.first?.let { oversized(it) } == true
|
||||
|
||||
/** A movie that is too large never goes out as it is: it is converted at the chosen volume, and plays nothing if that fails. */
|
||||
internal fun oversizedPlan(volume: Int): Plan =
|
||||
Plan(false, listOf(if (volume == 0) Step.TRANSCODE_SILENT else Step.TRANSCODE_AUDIO), false)
|
||||
|
||||
private fun transcodeSilent(source: File, target: File, limitUs: Long) =
|
||||
BootMovieTranscoder.transcode(source, target, keepAudio = false, limitUs = limitUs) {} != null
|
||||
|
||||
/** Keeps at most the one processed copy in use, so trying settings never leaves movies piling up. */
|
||||
private fun prune(folder: File, keep: String?) {
|
||||
folder.listFiles()?.forEach { if (it.name != keep) it.delete() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes over a startup movie chosen in Steam's own settings: when Steam's config names a movie it did not name before,
|
||||
* that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed.
|
||||
*/
|
||||
fun syncFromSteam(context: Context): Boolean {
|
||||
val path = SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context)) ?: return false
|
||||
if (path == SessionPrefs.bootMovieSteamSeen(context)) return false
|
||||
SessionPrefs.setBootMovieSteamSeen(context, path)
|
||||
if (path == SessionFiles.BOOT_MOVIE_PATH) return false
|
||||
val prefix = "/uioverrides/movies/"
|
||||
// The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder.
|
||||
val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else {
|
||||
val listed = BootMovieLibrary.list(context).firstOrNull { it.id.startsWith(BootMovieLibrary.STEAM_PREFIX) && it.id.endsWith(path) }
|
||||
listed?.id ?: BootMovieLibrary.STEAM_PREFIX + path
|
||||
}
|
||||
if (BootMovieLibrary.file(context, id) == null) return false
|
||||
val changed = SessionPrefs.bootMovie(context) != id
|
||||
BootMovieReport.note(context, "Steam names $path, taken over as $id")
|
||||
SessionPrefs.setBootMovie(context, id)
|
||||
return changed
|
||||
}
|
||||
|
||||
private fun extractAsset(context: Context, name: String): File? {
|
||||
@@ -82,11 +203,15 @@ object BootMovie {
|
||||
}
|
||||
}
|
||||
|
||||
fun import(context: Context, file: File, onStart: () -> Unit = {}, onProgress: (Int) -> Unit = {}): Import {
|
||||
fun import(
|
||||
context: Context, file: File, onStart: () -> Unit = {}, onProgress: (Int) -> Unit = {},
|
||||
title: String? = null, source: String = BootMovieLibrary.SOURCE_IMPORT, repoId: String? = null,
|
||||
cover: ByteArray? = null, use: Boolean = true,
|
||||
): Import {
|
||||
val (format, audio) = probe(file) ?: return Import.Unsupported(null)
|
||||
val video = format.getString(MediaFormat.KEY_MIME)
|
||||
val audioPlayable = audio == null || audio in AUDIO_CODECS
|
||||
val playable = video in VIDEO_CODECS && file.length() <= MAX_BYTES
|
||||
val playable = video in VIDEO_CODECS && file.length() <= MAX_BYTES && !oversized(format)
|
||||
val copy = playable && audioPlayable && isWebm(file)
|
||||
val remux = !copy && playable && video in REMUX_CODECS
|
||||
if (!copy && !remux) {
|
||||
@@ -95,11 +220,12 @@ object BootMovie {
|
||||
if (durationUs > MAX_CONVERT_SECONDS * 1_000_000L) return Import.TooLong
|
||||
onStart()
|
||||
}
|
||||
val target = customFile(context)
|
||||
val staged = File(dir(context), "custom.webm.staged")
|
||||
val shown = title?.takeIf { it.isNotBlank() } ?: file.nameWithoutExtension
|
||||
val library = BootMovieLibrary.libraryDir(context)
|
||||
val staged = File(library, ".import-${System.nanoTime()}.staged")
|
||||
var audioDropped = remux && !audioPlayable
|
||||
return try {
|
||||
target.parentFile?.mkdirs()
|
||||
library.mkdirs()
|
||||
val ok = when {
|
||||
copy -> {
|
||||
file.inputStream().use { input -> staged.outputStream().use { output -> FileUtils.copy(input, output) } }
|
||||
@@ -108,11 +234,10 @@ object BootMovie {
|
||||
remux -> remux(file, staged, audio = true)
|
||||
else -> BootMovieTranscoder.transcode(file, staged, onProgress = onProgress)?.also { audioDropped = it.audioDropped } != null
|
||||
}
|
||||
if (!ok || !staged.renameTo(target)) return Import.Failed
|
||||
File(target.parentFile, "custom-muted.webm").delete()
|
||||
SessionPrefs.setBootMovieCustomName(context, file.name)
|
||||
SessionPrefs.setBootMovie(context, CUSTOM)
|
||||
Import.Done(file.name, audioDropped)
|
||||
if (!ok || !staged.setReadable(true, false)) return Import.Failed
|
||||
val name = BootMovieLibrary.commit(context, staged, shown, source, repoId, cover) ?: return Import.Failed
|
||||
if (use) select(context, BootMovieLibrary.idOf(name))
|
||||
Import.Done(shown, audioDropped, BootMovieLibrary.idOf(name))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not import ${file.name}", e)
|
||||
Import.Failed
|
||||
@@ -124,8 +249,9 @@ object BootMovie {
|
||||
fun removeCustom(context: Context) {
|
||||
customFile(context).delete()
|
||||
File(dir(context), "custom-muted.webm").delete()
|
||||
File(dir(context), "variants").listFiles { f -> f.name.startsWith(BootMovieLibrary.variantPrefix(customFile(context))) }?.forEach { it.delete() }
|
||||
SessionPrefs.setBootMovieCustomName(context, null)
|
||||
if (SessionPrefs.bootMovie(context) == CUSTOM) SessionPrefs.setBootMovie(context, DROIDDECK_30)
|
||||
if (SessionPrefs.bootMovie(context) == CUSTOM) select(context, DROIDDECK_30)
|
||||
}
|
||||
|
||||
private fun isWebm(file: File): Boolean {
|
||||
@@ -156,7 +282,7 @@ object BootMovie {
|
||||
}
|
||||
}
|
||||
|
||||
private fun remux(source: File, target: File, audio: Boolean): Boolean {
|
||||
private fun remux(source: File, target: File, audio: Boolean, limitUs: Long = Long.MAX_VALUE): Boolean {
|
||||
val staged = File(target.parentFile, target.name + ".remux")
|
||||
val extractor = MediaExtractor()
|
||||
var muxer: MediaMuxer? = null
|
||||
@@ -183,7 +309,7 @@ object BootMovie {
|
||||
val info = MediaCodec.BufferInfo()
|
||||
while (true) {
|
||||
val size = extractor.readSampleData(buffer, 0)
|
||||
if (size < 0) break
|
||||
if (size < 0 || extractor.sampleTime > limitUs) break
|
||||
val track = tracks[extractor.sampleTrackIndex]
|
||||
if (track != null) {
|
||||
val key = extractor.sampleFlags and MediaExtractor.SAMPLE_FLAG_SYNC != 0
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Bitmap.CompressFormat
|
||||
import android.media.MediaMetadataRetriever
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The boot movies a person can pick from: DroidDeck's own two, a movie imported before this list existed, every `.webm` in
|
||||
* Steam's custom movies folder (imports, SteamDeckRepo and movies put there by hand; all of them can be removed), Steam's own
|
||||
* three startup movies and the movies bought in Steam's points shop (neither can be removed).
|
||||
*/
|
||||
object BootMovieLibrary {
|
||||
private const val TAG = "BootMovieLibrary"
|
||||
const val PREFIX = "file:"
|
||||
|
||||
/** A movie Steam itself keeps outside its custom movies folder, such as one bought in its points shop: `steam:<path Steam names>`. */
|
||||
const val STEAM_PREFIX = "steam:"
|
||||
|
||||
/** Held while the movie list is read and changed, so two imports at once cannot overwrite each other's entries. */
|
||||
private val lock = Any()
|
||||
|
||||
/** Names DroidDeck stages the chosen movie under; they are copies, not movies of their own. */
|
||||
internal val STAGED = setOf("bigpicture_startup.webm", "steam_os_startup.webm", "droiddeck-startup.webm")
|
||||
|
||||
const val SOURCE_DROIDDECK = "droiddeck"
|
||||
const val SOURCE_IMPORT = "import"
|
||||
const val SOURCE_REPO = "repo"
|
||||
const val SOURCE_STEAM = "steam"
|
||||
const val SOURCE_POINTSHOP = "pointshop"
|
||||
|
||||
class Entry(val id: String, val title: String, val source: String, val file: File?, val removable: Boolean)
|
||||
|
||||
internal fun moviesDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/config/uioverrides/movies")
|
||||
|
||||
/**
|
||||
* The folders whose custom movies are listed, found and removed: [moviesDir], where imports are put and managed, then the
|
||||
* x86-64 client's. The order never depends on which client is running, so a saved choice keeps meaning the same file.
|
||||
*/
|
||||
internal fun customMovieDirs(context: Context): List<File> =
|
||||
listOf(moviesDir(context), File(SessionPrefs.steamRoot(context, "x86_64"), "config/uioverrides/movies")).distinctBy { it.path }
|
||||
|
||||
/** Where imported and installed movies are kept for good; Steam's folder holds a copy, which is put back if it goes missing. */
|
||||
internal fun libraryDir(context: Context) = File(context.filesDir, "boot-movie/library")
|
||||
|
||||
private fun metaFile(context: Context) = File(context.filesDir, "boot-movie/movies.json")
|
||||
|
||||
internal fun steamRoot(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||
|
||||
/** The running (else selected) Steam client's config, the one whose startup movie choice is read and recorded. */
|
||||
internal fun steamConfig(context: Context) = File(SessionPrefs.activeSteamRoot(context), "config/config.vdf")
|
||||
|
||||
private fun thumbsDir(context: Context) = File(context.filesDir, "boot-movie/thumbs")
|
||||
|
||||
fun idOf(name: String) = PREFIX + name
|
||||
|
||||
/** Every Steam client folder: the usual one and the x86-64 client's. */
|
||||
internal fun steamRoots(context: Context): List<File> = listOf(
|
||||
steamRoot(context), File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/.local/share/Steam"),
|
||||
).filter { it.isDirectory }
|
||||
|
||||
private fun steamFile(context: Context, id: String): File? {
|
||||
val path = id.removePrefix(STEAM_PREFIX)
|
||||
if (!path.startsWith("/") || path.contains("..") || path.contains('\\') || !path.endsWith(".webm", ignoreCase = true)) return null
|
||||
return steamRoots(context).firstNotNullOfOrNull { root ->
|
||||
listOf("config", "steamui", "").map { File(root, it + path) }.firstOrNull { it.isFile && it.length() > 0L }
|
||||
}
|
||||
}
|
||||
|
||||
fun file(context: Context, id: String): File? {
|
||||
if (id.startsWith(STEAM_PREFIX)) return steamFile(context, id)
|
||||
if (!id.startsWith(PREFIX)) return null
|
||||
val name = id.removePrefix(PREFIX)
|
||||
if (name.isEmpty() || name.contains('/') || name.contains('\\') || name in STAGED) return null
|
||||
return customMovieDirs(context).map { File(it, name) }.firstOrNull { it.isFile && it.length() > 0L }
|
||||
}
|
||||
|
||||
private fun isMovie(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) &&
|
||||
file.name !in STAGED && !file.name.startsWith(".")
|
||||
|
||||
private fun readMeta(context: Context): JSONObject =
|
||||
runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject())
|
||||
|
||||
/** Changes the movie list one writer at a time; [change] gets the list and returns whether to save it. */
|
||||
private fun editMeta(context: Context, change: (JSONObject) -> Boolean) = synchronized(lock) {
|
||||
val meta = readMeta(context)
|
||||
if (change(meta)) {
|
||||
val file = metaFile(context)
|
||||
file.parentFile?.mkdirs()
|
||||
val staged = File(file.parentFile, file.name + ".staged")
|
||||
runCatching {
|
||||
staged.writeText(meta.toString())
|
||||
if (!staged.renameTo(file)) staged.delete()
|
||||
}.onFailure { staged.delete(); Log.w(TAG, "could not write the movie list", it) }
|
||||
}
|
||||
}
|
||||
|
||||
/** The post a movie was installed from, if it came from SteamDeckRepo. */
|
||||
fun repoId(context: Context, name: String): String? =
|
||||
readMeta(context).optJSONObject(name)?.optString("repo")?.takeIf { it.isNotEmpty() }
|
||||
|
||||
fun installedRepoIds(context: Context): Set<String> {
|
||||
val meta = readMeta(context)
|
||||
return meta.keys().asSequence().filter { file(context, idOf(it)) != null }
|
||||
.mapNotNull { meta.optJSONObject(it)?.optString("repo")?.takeIf { id -> id.isNotEmpty() } }.toSet()
|
||||
}
|
||||
|
||||
fun nameForRepo(context: Context, repoId: String): String? {
|
||||
val meta = readMeta(context)
|
||||
return meta.keys().asSequence().firstOrNull { file(context, idOf(it)) != null && meta.optJSONObject(it)?.optString("repo") == repoId }
|
||||
}
|
||||
|
||||
fun list(context: Context): List<Entry> {
|
||||
val out = ArrayList<Entry>()
|
||||
out.add(Entry(BootMovie.DROIDDECK_30, "DroidDeck · 30 fps", SOURCE_DROIDDECK, null, removable = false))
|
||||
out.add(Entry(BootMovie.DROIDDECK_60, "DroidDeck · 60 fps", SOURCE_DROIDDECK, null, removable = false))
|
||||
BootMovie.customName(context)?.let { out.add(Entry(BootMovie.CUSTOM, it, SOURCE_IMPORT, BootMovie.legacyCustomFile(context), removable = true)) }
|
||||
restore(context)
|
||||
val meta = readMeta(context)
|
||||
val names = HashSet<String>()
|
||||
customMovieDirs(context).flatMap { dir -> dir.listFiles { f -> isMovie(f) }.orEmpty().toList() }
|
||||
.filter { names.add(it.name) }.sortedBy { it.name.lowercase() }.forEach { f ->
|
||||
val info = meta.optJSONObject(f.name)
|
||||
val source = info?.optString("source")?.takeIf { it.isNotEmpty() } ?: SOURCE_STEAM
|
||||
val title = info?.optString("title")?.takeIf { it.isNotEmpty() } ?: f.nameWithoutExtension
|
||||
// Everything in Steam's custom movies folder is the person's own (imported, from SteamDeckRepo or put there by hand).
|
||||
out.add(Entry(idOf(f.name), title, if (source == SOURCE_STEAM) SOURCE_IMPORT else source, f, removable = true))
|
||||
}
|
||||
val steam = LinkedHashMap<String, File>()
|
||||
SessionFiles.startupMoviePath(steamConfig(context))?.takeIf { !it.startsWith(OVERRIDES) }?.let { path ->
|
||||
steamFile(context, STEAM_PREFIX + path)?.let { steam[STEAM_PREFIX + path] = it }
|
||||
}
|
||||
val bought = HashMap<String, String>()
|
||||
for (root in steamRoots(context)) {
|
||||
File(root, "steamui/movies").listFiles { f -> isMovie(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty()
|
||||
.sortedBy { it.name.lowercase() }.forEach { steam.putIfAbsent(STEAM_PREFIX + "/movies/" + it.name, it) }
|
||||
val scan = pointShopMovies(root)
|
||||
bought.putAll(scan.titles)
|
||||
for (found in scan.files) steam.putIfAbsent(STEAM_PREFIX + "/" + found.relativeTo(root).invariantSeparatorsPath, found)
|
||||
}
|
||||
val seen = HashSet<String>()
|
||||
for ((id, file) in steam) {
|
||||
if (file.name in STAGED || !seen.add(file.canonicalPath)) continue
|
||||
val native = file.nameWithoutExtension.lowercase() in NATIVE
|
||||
// Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it.
|
||||
val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension
|
||||
out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The three startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
|
||||
private val NATIVE = mapOf("deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup")
|
||||
|
||||
private val skippedFolders = setOf("uioverrides", "steamapps", "librarycache", "httpcache", "logs", "compatdata", "shadercache")
|
||||
|
||||
private val scanLock = Any()
|
||||
private class Scan(val at: Long, val files: List<File>, val titles: Map<String, String>)
|
||||
|
||||
private val scans = HashMap<String, Scan>()
|
||||
|
||||
/** Forgets the last search for Steam's own movies. */
|
||||
internal fun forgetScan() = synchronized(scanLock) { scans.clear() }
|
||||
|
||||
/**
|
||||
* Movies Steam keeps outside its custom movies folder, such as ones bought in its points shop: every `.webm` below the
|
||||
* client's config, cache and user folders. The search is repeated at most every 15 seconds for each client folder.
|
||||
*/
|
||||
private fun pointShopMovies(root: File): Scan = synchronized(scanLock) {
|
||||
val now = System.currentTimeMillis()
|
||||
scans[root.path]?.let { if (now - it.at < 15_000L) return it }
|
||||
val found = listOf("config", "userdata", "appcache", "steamui").flatMap { top ->
|
||||
val base = File(root, top)
|
||||
if (!base.isDirectory) return@flatMap emptyList()
|
||||
base.walkTopDown().maxDepth(5)
|
||||
.onEnter { dir -> dir.name !in skippedFolders && !(top == "steamui" && dir.parentFile == base && dir.name == "movies") }
|
||||
.take(20_000).filter { isMovie(it) }.toList()
|
||||
}.sortedBy { it.path.lowercase() }
|
||||
val titles = HashMap<String, String>()
|
||||
for (file in found) boughtId(file)?.let { id -> boughtTitle(root, id)?.let { titles[file.path] = it } }
|
||||
val scan = Scan(now, found, titles)
|
||||
scans[root.path] = scan
|
||||
scan
|
||||
}
|
||||
|
||||
/** The item number in the name Steam gives a bought movie, `<item number>_<hash>.webm`; null for any other name. */
|
||||
private fun boughtId(file: File) = Regex("^(\\d+)_").find(file.nameWithoutExtension)?.groupValues?.get(1)
|
||||
|
||||
/** What the points shop calls a bought movie, from the list of startup movies Steam keeps in each user's local config. */
|
||||
private fun boughtTitle(root: File, id: String): String? {
|
||||
val key = "communityitemid\\\":\\\"$id\\\""
|
||||
val title = Regex("item_title\\\\\":\\\\\"([^\\\\\"]*)")
|
||||
for (user in File(root, "userdata").listFiles { f -> f.isDirectory }.orEmpty()) {
|
||||
val text = runCatching { File(user, "config/localconfig.vdf").readText() }.getOrNull() ?: continue
|
||||
val at = text.indexOf(key)
|
||||
if (at < 0) continue
|
||||
title.find(text.substring(at, (at + 3000).coerceAtMost(text.length)))?.groupValues?.get(1)?.takeIf { it.isNotBlank() }?.let { return it }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private const val OVERRIDES = "/uioverrides/movies/"
|
||||
|
||||
/** Puts back, in Steam's folder, any movie of DroidDeck's that went missing there, such as after the runtime was reset. */
|
||||
internal fun restore(context: Context) = synchronized(lock) {
|
||||
migrateLegacyMeta(context)
|
||||
val meta = readMeta(context)
|
||||
val library = libraryDir(context)
|
||||
meta.keys().asSequence().toList().forEach { name ->
|
||||
val kept = File(library, name)
|
||||
if (name.contains('/') || !kept.isFile || kept.length() == 0L) return@forEach
|
||||
val copy = File(moviesDir(context), name)
|
||||
if (!copy.isFile || copy.length() != kept.length()) mirror(kept, copy)
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes in the movie notes an earlier version kept inside Steam's movies folder, so those movies keep their title and source. */
|
||||
private fun migrateLegacyMeta(context: Context) {
|
||||
val legacy = File(moviesDir(context), ".droiddeck-movies.json")
|
||||
if (!legacy.isFile) return
|
||||
val old = runCatching { JSONObject(legacy.readText()) }.getOrNull() ?: return
|
||||
editMeta(context) { meta ->
|
||||
var changed = false
|
||||
old.keys().asSequence().toList().forEach { name ->
|
||||
val info = old.optJSONObject(name) ?: return@forEach
|
||||
if (meta.optJSONObject(name) == null && File(moviesDir(context), name).isFile) { meta.put(name, info); changed = true }
|
||||
}
|
||||
changed
|
||||
}
|
||||
legacy.delete()
|
||||
}
|
||||
|
||||
/** Copies [kept] to [copy] through a staging name, so Steam never sees half a movie. */
|
||||
private fun mirror(kept: File, copy: File): Boolean {
|
||||
val staged = File(copy.parentFile, copy.name + ".${System.nanoTime()}.staged")
|
||||
return try {
|
||||
copy.parentFile?.mkdirs()
|
||||
kept.inputStream().use { input -> staged.outputStream().use { output -> input.copyTo(output) } }
|
||||
staged.setReadable(true, false) && staged.renameTo(copy)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not copy ${kept.name} into Steam's movies", e)
|
||||
false
|
||||
} finally {
|
||||
staged.delete()
|
||||
}
|
||||
}
|
||||
|
||||
fun title(context: Context, id: String): String = list(context).firstOrNull { it.id == id }?.title ?: id
|
||||
|
||||
/** The file a movie id plays from; DroidDeck's own movies live in the app and are unpacked on demand. */
|
||||
fun fileOf(context: Context, entry: Entry): File? = entry.file ?: BootMovie.assetFile(context, entry.id)
|
||||
|
||||
/** A free `.webm` name for a movie called [title]; the same title twice gets " (2)", " (3)"… */
|
||||
fun freeName(context: Context, title: String): String {
|
||||
val base = title.replace(Regex("[^\\p{L}\\p{N} ._()\\-]"), "").replace(Regex("\\s+"), " ").trim().trim('.').take(60).ifEmpty { "movie" }
|
||||
val dirs = customMovieDirs(context)
|
||||
val library = libraryDir(context)
|
||||
var name = "$base.webm"
|
||||
var n = 2
|
||||
while (dirs.any { File(it, name).exists() } || File(library, name).exists() || name in STAGED) name = "$base ($n).webm".also { n++ }
|
||||
return name
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the finished movie [staged] (a file in [libraryDir]) under a free name, copies it into Steam's folder and notes its
|
||||
* title, source and cover. Returns the name, or null when it could not be kept. Runs one movie at a time.
|
||||
*/
|
||||
internal fun commit(context: Context, staged: File, title: String, source: String, repoId: String? = null, cover: ByteArray? = null): String? =
|
||||
synchronized(lock) {
|
||||
val name = freeName(context, title)
|
||||
val kept = File(libraryDir(context), name)
|
||||
if (!staged.renameTo(kept)) return null
|
||||
if (!mirror(kept, File(moviesDir(context), name))) { kept.delete(); return null }
|
||||
register(context, name, title, source, repoId, cover)
|
||||
name
|
||||
}
|
||||
|
||||
/** Notes a movie that was just put into Steam's folder: what to call it, where it came from and its cover. */
|
||||
fun register(context: Context, name: String, title: String, source: String, repoId: String? = null, cover: ByteArray? = null) {
|
||||
editMeta(context) { meta ->
|
||||
val info = JSONObject().put("title", title).put("source", source)
|
||||
if (repoId != null) info.put("repo", repoId)
|
||||
meta.put(name, info)
|
||||
true
|
||||
}
|
||||
if (cover != null) runCatching {
|
||||
thumbsDir(context).mkdirs()
|
||||
File(thumbsDir(context), coverName(name)).writeBytes(cover)
|
||||
}
|
||||
}
|
||||
|
||||
fun remove(context: Context, id: String): Boolean {
|
||||
val removed = when {
|
||||
id == BootMovie.CUSTOM -> { BootMovie.removeCustom(context); true }
|
||||
else -> {
|
||||
// Only movies in Steam's custom movies folder are ever deleted; Steam's own and points shop movies are left alone.
|
||||
if (!id.startsWith(PREFIX)) return false
|
||||
val name = id.removePrefix(PREFIX)
|
||||
if (name.isEmpty() || name.contains('/') || name.contains('\\') || name in STAGED) return false
|
||||
val copies = customMovieDirs(context).map { File(it, name) }
|
||||
// A name can exist in more than one client's folder; the entry is the first one found (see customMovieDirs), and only that file is deleted.
|
||||
val target = copies.firstOrNull { it.exists() }
|
||||
val managed = File(libraryDir(context), name)
|
||||
if (readMeta(context).optJSONObject(name) == null && target == null && !managed.isFile) return false
|
||||
synchronized(lock) {
|
||||
val main = File(moviesDir(context), name)
|
||||
val another = copies.any { it != target && it.exists() }
|
||||
val ownsRecord = target == null || target.path == main.path || (!another && !managed.isFile)
|
||||
var gone = target == null || target.delete()
|
||||
if (gone && ownsRecord) {
|
||||
gone = !managed.exists() || managed.delete()
|
||||
if (gone) {
|
||||
editMeta(context) { it.remove(name) != null }
|
||||
File(thumbsDir(context), coverName(name)).delete()
|
||||
thumbsDir(context).listFiles { f -> f.name.startsWith("frame-" + safe(name) + "-") }?.forEach { it.delete() }
|
||||
}
|
||||
}
|
||||
if (gone) {
|
||||
val prefixes = listOfNotNull(target, main.takeIf { ownsRecord }).map { variantPrefix(it) }
|
||||
File(context.filesDir, "boot-movie/variants").listFiles { f -> prefixes.any { f.name.startsWith(it) } }?.forEach { it.delete() }
|
||||
}
|
||||
gone
|
||||
}
|
||||
}
|
||||
}
|
||||
if (removed && SessionPrefs.bootMovie(context) == id) BootMovie.select(context, BootMovie.DROIDDECK_30)
|
||||
return removed
|
||||
}
|
||||
|
||||
/** What every processed copy of [source] starts with; the hash of its full path keeps same-named files in different places apart. */
|
||||
internal fun variantPrefix(source: File) = safe(source.name) + "." + Integer.toHexString(source.absolutePath.hashCode()) + "-"
|
||||
|
||||
private fun safe(name: String) = name.replace(Regex("[^A-Za-z0-9._-]"), "_")
|
||||
|
||||
private fun coverName(name: String) = "cover-" + safe(name)
|
||||
|
||||
/** How long a movie runs, in whole seconds; 0 when it cannot be read. */
|
||||
fun durationSeconds(file: File?): Int {
|
||||
if (file == null || !file.isFile) return 0
|
||||
val retriever = MediaMetadataRetriever()
|
||||
return try {
|
||||
retriever.setDataSource(file.path)
|
||||
val ms = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
|
||||
((ms + 500) / 1000).toInt()
|
||||
} catch (e: Exception) {
|
||||
0
|
||||
} finally {
|
||||
runCatching { retriever.release() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The first frame that is not nearly black out of several taken through the movie, else the brightest; a movie may open dark. */
|
||||
private fun brightestFrame(retriever: MediaMetadataRetriever, durationMs: Long): Bitmap? {
|
||||
var best: Bitmap? = null
|
||||
var bestLuma = -1
|
||||
for (fraction in doubleArrayOf(0.33, 0.5, 0.66, 0.2, 0.8, 0.1, 0.9)) {
|
||||
val frame = runCatching { retriever.getFrameAtTime((durationMs * 1000L * fraction).toLong(), MediaMetadataRetriever.OPTION_CLOSEST) }.getOrNull() ?: continue
|
||||
val luma = averageLuma(frame)
|
||||
if (luma >= MIN_COVER_LUMA) return frame
|
||||
if (luma > bestLuma) { best = frame; bestLuma = luma }
|
||||
}
|
||||
return best ?: runCatching { retriever.frameAtTime }.getOrNull()
|
||||
}
|
||||
|
||||
private fun averageLuma(bitmap: Bitmap): Int {
|
||||
val small = Bitmap.createScaledBitmap(bitmap, 16, 9, true)
|
||||
var sum = 0L
|
||||
for (y in 0 until small.height) for (x in 0 until small.width) {
|
||||
val c = small.getPixel(x, y)
|
||||
sum += (((c shr 16) and 0xFF) * 3 + ((c shr 8) and 0xFF) * 6 + (c and 0xFF)) / 10
|
||||
}
|
||||
return (sum / (small.width * small.height)).toInt()
|
||||
}
|
||||
|
||||
private const val MIN_COVER_LUMA = 24
|
||||
|
||||
/** A cover for a movie: the picture SteamDeckRepo gave it, or one frame taken from the video and remembered. */
|
||||
fun cover(context: Context, entry: Entry): File? {
|
||||
val file = fileOf(context, entry) ?: return null
|
||||
val name = if (entry.id.startsWith(PREFIX)) file.name else entry.id
|
||||
// Points Shop covers once kept a picture that was not always the movie's own; those files are not used.
|
||||
val given = File(thumbsDir(context), if (entry.source == SOURCE_POINTSHOP) "v2-" + coverName(name) else coverName(name))
|
||||
if (given.isFile && given.length() > 0L) return given
|
||||
val key = "frame-" + safe(name) + "-v2-" + file.length() + "-" + file.lastModified() + ".jpg"
|
||||
val frame = File(thumbsDir(context), key)
|
||||
if (frame.isFile && frame.length() > 0L) return frame
|
||||
val retriever = MediaMetadataRetriever()
|
||||
return try {
|
||||
retriever.setDataSource(file.path)
|
||||
val ms = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
|
||||
val bitmap = brightestFrame(retriever, ms) ?: return null
|
||||
val width = 480
|
||||
val scaled = if (bitmap.width > width) Bitmap.createScaledBitmap(bitmap, width, (bitmap.height * width / bitmap.width).coerceAtLeast(1), true) else bitmap
|
||||
thumbsDir(context).mkdirs()
|
||||
thumbsDir(context).listFiles { f -> f.name.startsWith("frame-" + safe(name) + "-") }?.forEach { it.delete() }
|
||||
val staged = File(thumbsDir(context), "$key.staged")
|
||||
staged.outputStream().use { scaled.compress(CompressFormat.JPEG, 82, it) }
|
||||
if (staged.renameTo(frame)) frame else null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "no cover for ${file.name}", e)
|
||||
null
|
||||
} finally {
|
||||
runCatching { retriever.release() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* What DroidDeck and Steam know about boot movies, in one text file: Steam's startup movie setting, every movie file and
|
||||
* where it lives, DroidDeck's own state, and a short trace of what each session start did to Steam's config.
|
||||
*/
|
||||
object BootMovieReport {
|
||||
private const val TAG = "BootMovieReport"
|
||||
private const val MAX_TRACE_LINES = 200
|
||||
private const val MAX_HITS = 60
|
||||
private val KNOWN_TITLES = listOf("Turret Factory")
|
||||
private val SKIPPED = setOf("steamapps", "compatdata", "shadercache", "logs")
|
||||
private val BINARY = setOf("webm", "jpg", "jpeg", "png", "ico", "mp4", "ogg", "mp3", "wav", "ttf", "woff", "woff2", "gif", "webp", "bin", "so", "dll", "exe", "zip", "pak")
|
||||
private val lock = Any()
|
||||
|
||||
private fun traceFile(context: Context) = File(context.filesDir, "boot-movie/apply.log")
|
||||
|
||||
/** Adds a line to the short trace kept for the report; only the latest lines are kept. */
|
||||
fun note(context: Context, line: String) {
|
||||
synchronized(lock) {
|
||||
runCatching {
|
||||
val file = traceFile(context)
|
||||
file.parentFile?.mkdirs()
|
||||
val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
val lines = (if (file.isFile) file.readLines() else emptyList()) + "$stamp $line"
|
||||
file.writeText(lines.takeLast(MAX_TRACE_LINES).joinToString("\n") + "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the report to Downloads/DroidDeck, or to the app's own folder when that is not possible; null when the report cannot be built or neither folder works. */
|
||||
fun write(context: Context): File? {
|
||||
val text = runCatching { build(context) }.getOrElse {
|
||||
Log.w(TAG, "could not build the report", it)
|
||||
return null
|
||||
}
|
||||
val folders = listOfNotNull(
|
||||
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck"),
|
||||
context.getExternalFilesDir(null),
|
||||
)
|
||||
for (folder in folders) {
|
||||
val file = File(folder, "boot-movie-report.txt")
|
||||
val saved = runCatching { folder.mkdirs(); file.writeText(text); true }.getOrDefault(false)
|
||||
if (saved) return file
|
||||
Log.w(TAG, "could not write the report to ${file.path}")
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun describe(file: File) =
|
||||
"${file.path} ${file.length()} bytes ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date(file.lastModified()))}"
|
||||
|
||||
internal fun build(context: Context): String {
|
||||
val out = StringBuilder()
|
||||
fun line(text: String = "") { out.append(text).append('\n') }
|
||||
fun listing(title: String, folder: File) {
|
||||
line("-- $title: ${folder.path}")
|
||||
val files = folder.listFiles()?.sortedBy { it.name.lowercase() }
|
||||
if (files == null) line(" (missing)") else if (files.isEmpty()) line(" (empty)")
|
||||
else files.forEach { line(" " + describe(it)) }
|
||||
}
|
||||
|
||||
line("DroidDeck boot movie report, ${Date()}")
|
||||
line()
|
||||
line("== DroidDeck state")
|
||||
line("choice=${BootMovie.choice(context)} saved choice=${SessionPrefs.bootMovie(context)} pending pick=${SessionPrefs.bootMovieApplyNext(context)}")
|
||||
line("last Steam path seen=${SessionPrefs.bootMovieSteamSeen(context)}")
|
||||
line("sound=${SessionPrefs.bootMovieSound(context)} volume=${SessionPrefs.bootMovieVolume(context)} seconds=${SessionPrefs.bootMovieSeconds(context)}")
|
||||
line("session running=${SessionState.running}")
|
||||
line()
|
||||
line("== The movie list as shown")
|
||||
BootMovieLibrary.list(context).forEach { line("${it.id} title=${it.title} source=${it.source} removable=${it.removable} file=${it.file?.path}") }
|
||||
line()
|
||||
line("== DroidDeck folders")
|
||||
listing("library", BootMovieLibrary.libraryDir(context))
|
||||
listing("processed copies", File(context.filesDir, "boot-movie/variants"))
|
||||
val meta = File(context.filesDir, "boot-movie/movies.json")
|
||||
line("-- movie list file: ${if (meta.isFile) meta.readText().take(8000) else "(missing)"}")
|
||||
|
||||
val roots = BootMovieLibrary.steamRoots(context)
|
||||
val movieIds = HashSet<String>()
|
||||
for (root in roots) {
|
||||
line()
|
||||
line("== Steam folder ${root.path}")
|
||||
val config = File(root, "config/config.vdf")
|
||||
line("config.vdf: ${if (config.isFile) describe(config) else "(missing)"}")
|
||||
val text = runCatching { config.readText() }.getOrNull()
|
||||
if (text != null) {
|
||||
line("-- StartupMovie block:")
|
||||
(SessionFiles.startupMovieBlock(config) ?: " (none)").lines().forEach { line(" $it") }
|
||||
line("-- Customization section with the lines before it:")
|
||||
(SessionFiles.customizationBlock(config) ?: " (none)").lines().forEach { line(" $it") }
|
||||
line("-- every line of config.vdf that mentions a movie:")
|
||||
text.lines().filter { it.contains("movie", ignoreCase = true) }.take(40).forEach { line(" ${it.trim()}") }
|
||||
Regex("\"MovieID\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)?.takeIf { it.isNotEmpty() && it != "0" }?.let { movieIds.add(it) }
|
||||
}
|
||||
listing("custom movies", File(root, "config/uioverrides/movies"))
|
||||
listing("Steam's own movies", File(root, "steamui/movies"))
|
||||
listing("config/movies", File(root, "config/movies"))
|
||||
line("-- every .webm below config, userdata, appcache and steamui:")
|
||||
var shown = 0
|
||||
for (top in listOf("config", "userdata", "appcache", "steamui")) {
|
||||
val base = File(root, top)
|
||||
if (!base.isDirectory) continue
|
||||
for (file in base.walkTopDown().maxDepth(8).onEnter { it.name !in SKIPPED }) {
|
||||
if (!file.isFile || !file.name.endsWith(".webm", ignoreCase = true)) continue
|
||||
if (shown++ >= 300) break
|
||||
line(" " + describe(file))
|
||||
Regex("^(\\d+)_[0-9a-fA-F]+").find(file.name)?.groupValues?.get(1)?.let { movieIds.add(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
line()
|
||||
line("== Where Steam keeps movie names (text found in Steam's files)")
|
||||
val needles = (KNOWN_TITLES + movieIds).distinct()
|
||||
line("looking for: ${needles.joinToString(", ")}")
|
||||
search(roots, needles) { line(" $it") }
|
||||
|
||||
line()
|
||||
line("== What each session start did to Steam's config (latest last)")
|
||||
val trace = traceFile(context)
|
||||
if (trace.isFile) trace.readLines().forEach { line(" $it") } else line(" (nothing yet: start a session after picking a movie)")
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
private fun search(roots: List<File>, needles: List<String>, report: (String) -> Unit) {
|
||||
if (needles.isEmpty()) return
|
||||
val deadline = System.currentTimeMillis() + 25_000L
|
||||
var scanned = 0
|
||||
var hits = 0
|
||||
outer@ for (root in roots) {
|
||||
for (top in listOf("config", "userdata", "appcache", "steamui")) {
|
||||
val base = File(root, top)
|
||||
if (!base.isDirectory) continue
|
||||
for (file in base.walkTopDown().maxDepth(8).onEnter { it.name !in SKIPPED }) {
|
||||
if (!file.isFile || file.length() > (2L shl 20) || file.extension.lowercase() in BINARY) continue
|
||||
if (++scanned > 20_000 || System.currentTimeMillis() > deadline || hits >= MAX_HITS) break@outer
|
||||
val text = runCatching { String(file.readBytes(), Charsets.ISO_8859_1) }.getOrNull() ?: continue
|
||||
for (needle in needles) {
|
||||
val at = text.indexOf(needle)
|
||||
if (at < 0) continue
|
||||
hits++
|
||||
val around = text.substring((at - 60).coerceAtLeast(0), (at + needle.length + 100).coerceAtMost(text.length))
|
||||
report("$needle in ${file.path}: " + around.map { if (it in ' '..'~') it else '.' }.joinToString(""))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
report("(searched $scanned files, $hits matches)")
|
||||
}
|
||||
}
|
||||
@@ -37,15 +37,77 @@ internal object BootMovieTranscoder {
|
||||
MediaCodecList(MediaCodecList.REGULAR_CODECS).findDecoderForFormat(format) != null
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun transcode(source: File, target: File, keepAudio: Boolean = true, onProgress: (Int) -> Unit): Result? {
|
||||
fun transcode(source: File, target: File, keepAudio: Boolean = true, limitUs: Long = Long.MAX_VALUE, gain: Float = 1f, onProgress: (Int) -> Unit): Result? {
|
||||
val hadAudio = keepAudio && trackFormat(source, "audio/") != null
|
||||
val audio = if (hadAudio) runCatching { encodeAudio(source) }
|
||||
val audio = if (hadAudio) runCatching { encodeAudio(source, gain, limitUs) }
|
||||
.onFailure { Log.w(TAG, "could not convert the audio of ${source.name}", it) }.getOrNull() else null
|
||||
val muxedAudio = runCatching { encodeVideo(source, target, audio, onProgress) }
|
||||
val muxedAudio = runCatching { encodeVideo(source, target, audio, limitUs, onProgress) }
|
||||
.onFailure { Log.w(TAG, "could not convert ${source.name}", it) }.getOrNull() ?: return null
|
||||
return Result(audioDropped = hadAudio && !muxedAudio)
|
||||
}
|
||||
|
||||
/** Copies the video of [source] untouched and gives it its sound again at [gain] of its level, cut to [limitUs]. */
|
||||
fun regain(source: File, target: File, gain: Float, limitUs: Long): Boolean {
|
||||
val audio = runCatching { encodeAudio(source, gain, limitUs) }
|
||||
.onFailure { Log.w(TAG, "could not change the volume of ${source.name}", it) }.getOrNull() ?: return false
|
||||
val extractor = MediaExtractor()
|
||||
var muxer: MediaMuxer? = null
|
||||
val staged = File(target.parentFile, target.name + ".regain")
|
||||
return try {
|
||||
extractor.setDataSource(source.path)
|
||||
var videoTrack = -1
|
||||
var videoFormat: MediaFormat? = null
|
||||
for (i in 0 until extractor.trackCount) {
|
||||
val format = extractor.getTrackFormat(i)
|
||||
val mime = format.getString(MediaFormat.KEY_MIME) ?: continue
|
||||
if (videoTrack < 0 && (mime == MediaFormat.MIMETYPE_VIDEO_VP8 || mime == MediaFormat.MIMETYPE_VIDEO_VP9)) {
|
||||
videoTrack = i
|
||||
videoFormat = format
|
||||
}
|
||||
}
|
||||
if (videoTrack < 0 || videoFormat == null) return false
|
||||
extractor.selectTrack(videoTrack)
|
||||
val mux = MediaMuxer(staged.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_WEBM).also { muxer = it }
|
||||
val outVideo = mux.addTrack(videoFormat)
|
||||
val outAudio = mux.addTrack(audio.format)
|
||||
mux.start()
|
||||
val info = MediaCodec.BufferInfo()
|
||||
var audioIndex = 0
|
||||
fun writeAudioUpTo(timeUs: Long) {
|
||||
while (audioIndex < audio.samples.size && audio.samples[audioIndex].timeUs <= timeUs) {
|
||||
val sample = audio.samples[audioIndex++]
|
||||
info.set(0, sample.data.size, sample.timeUs, 0)
|
||||
mux.writeSampleData(outAudio, ByteBuffer.wrap(sample.data), info)
|
||||
}
|
||||
}
|
||||
var bufferSize = 8 shl 20
|
||||
if (videoFormat.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) bufferSize = maxOf(bufferSize, videoFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE))
|
||||
val buffer = ByteBuffer.allocate(bufferSize)
|
||||
while (true) {
|
||||
val size = extractor.readSampleData(buffer, 0)
|
||||
if (size < 0 || extractor.sampleTime > limitUs) break
|
||||
val time = extractor.sampleTime
|
||||
writeAudioUpTo(time)
|
||||
val key = extractor.sampleFlags and MediaExtractor.SAMPLE_FLAG_SYNC != 0
|
||||
info.set(0, size, time, if (key) MediaCodec.BUFFER_FLAG_KEY_FRAME else 0)
|
||||
mux.writeSampleData(outVideo, buffer, info)
|
||||
extractor.advance()
|
||||
}
|
||||
writeAudioUpTo(Long.MAX_VALUE)
|
||||
mux.stop()
|
||||
mux.release()
|
||||
muxer = null
|
||||
staged.renameTo(target)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not change the volume of ${source.name}", e)
|
||||
false
|
||||
} finally {
|
||||
runCatching { muxer?.release() }
|
||||
extractor.release()
|
||||
staged.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun trackFormat(source: File, prefix: String): Pair<Int, MediaFormat>? {
|
||||
val extractor = MediaExtractor()
|
||||
return try {
|
||||
@@ -75,6 +137,14 @@ internal object BootMovieTranscoder {
|
||||
return Layout(canvas, ch, (canvas - cw) / 2, 0, cw, ch)
|
||||
}
|
||||
|
||||
/** [pcm] made quieter by [gain] and cut to its first [limitUs] microseconds. */
|
||||
internal fun scale(pcm: ShortArray, channels: Int, gain: Float, limitUs: Long): ShortArray {
|
||||
val frames = pcm.size / channels
|
||||
val kept = if (limitUs == Long.MAX_VALUE) frames else minOf(frames.toLong(), limitUs * OPUS_RATE / 1_000_000L).toInt()
|
||||
if (gain == 1f && kept == frames) return pcm
|
||||
return ShortArray(kept * channels) { (pcm[it] * gain).toInt().coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt()).toShort() }
|
||||
}
|
||||
|
||||
internal fun resample(pcm: ShortArray, channels: Int, rate: Int): ShortArray {
|
||||
if (rate == OPUS_RATE) return pcm
|
||||
val frames = pcm.size / channels
|
||||
@@ -94,7 +164,10 @@ internal object BootMovieTranscoder {
|
||||
return out
|
||||
}
|
||||
|
||||
private fun encodeAudio(source: File): Audio? {
|
||||
/** Most decoded audio held in memory at once: about six minutes of 48 kHz stereo. */
|
||||
private const val MAX_PCM_BYTES = 64 shl 20
|
||||
|
||||
private fun encodeAudio(source: File, gain: Float = 1f, limitUs: Long = Long.MAX_VALUE): Audio? {
|
||||
val (track, inFormat) = trackFormat(source, "audio/") ?: return null
|
||||
val extractor = MediaExtractor()
|
||||
var decoder: MediaCodec? = null
|
||||
@@ -139,13 +212,16 @@ internal object BootMovieTranscoder {
|
||||
}
|
||||
dec.releaseOutputBuffer(index, false)
|
||||
if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) break
|
||||
// Past the length that will be kept there is nothing more to decode; without a length, a track too big to hold is dropped.
|
||||
if (limitUs != Long.MAX_VALUE && info.presentationTimeUs > limitUs) break
|
||||
if (pcm.size() > MAX_PCM_BYTES) { if (limitUs == Long.MAX_VALUE) return null else break }
|
||||
}
|
||||
}
|
||||
if (channels !in 1..2) return null
|
||||
val raw = pcm.toByteArray()
|
||||
val shorts = ShortArray(raw.size / 2)
|
||||
ByteBuffer.wrap(raw).order(ByteOrder.nativeOrder()).asShortBuffer().get(shorts)
|
||||
val samples = resample(shorts, channels, rate)
|
||||
val samples = scale(resample(shorts, channels, rate), channels, gain, limitUs)
|
||||
|
||||
val format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_OPUS, OPUS_RATE, channels)
|
||||
format.setInteger(MediaFormat.KEY_BIT_RATE, 128_000)
|
||||
@@ -201,7 +277,7 @@ internal object BootMovieTranscoder {
|
||||
private fun MediaFormat.intOrNull(key: String): Int? = if (!containsKey(key)) null else
|
||||
runCatching { getInteger(key) }.getOrElse { runCatching { getFloat(key).toInt() }.getOrNull() }
|
||||
|
||||
private fun encodeVideo(source: File, target: File, audio: Audio?, onProgress: (Int) -> Unit): Boolean {
|
||||
private fun encodeVideo(source: File, target: File, audio: Audio?, limitUs: Long, onProgress: (Int) -> Unit): Boolean {
|
||||
val (track, inFormat) = trackFormat(source, "video/") ?: throw IllegalStateException("no video track")
|
||||
val rotation = (inFormat.intOrNull(MediaFormat.KEY_ROTATION) ?: 0).mod(360)
|
||||
val layout = layout(inFormat.getInteger(MediaFormat.KEY_WIDTH), inFormat.getInteger(MediaFormat.KEY_HEIGHT), rotation)
|
||||
@@ -278,7 +354,8 @@ internal object BootMovieTranscoder {
|
||||
val index = dec.dequeueOutputBuffer(decInfo, TIMEOUT_US)
|
||||
if (index >= 0) {
|
||||
val timeUs = decInfo.presentationTimeUs
|
||||
val keep = decInfo.size > 0 && (lastKept == Long.MIN_VALUE || timeUs - lastKept >= minIntervalUs)
|
||||
val pastLimit = timeUs > limitUs
|
||||
val keep = decInfo.size > 0 && !pastLimit && (lastKept == Long.MIN_VALUE || timeUs - lastKept >= minIntervalUs)
|
||||
dec.releaseOutputBuffer(index, keep)
|
||||
if (keep) {
|
||||
if (!frames.awaitFrame()) throw IllegalStateException("decoder frame timed out")
|
||||
@@ -290,9 +367,10 @@ internal object BootMovieTranscoder {
|
||||
if (percent != lastProgress) { lastProgress = percent; onProgress(percent) }
|
||||
}
|
||||
}
|
||||
if (decInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {
|
||||
if (pastLimit || decInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {
|
||||
enc.signalEndOfInputStream()
|
||||
decoderDone = true
|
||||
inputDone = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ import java.io.FileOutputStream
|
||||
object ComponentsManager {
|
||||
private const val TAG = "Components"
|
||||
private const val NIGHTLIES = "The412Banner/Nightlies"
|
||||
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
|
||||
internal const val DD_NIGHTLY = "linux-nightly"
|
||||
private val RELEASES = linkedMapOf(
|
||||
"FexCore-Linux" to "fex",
|
||||
"Dxvk-Linux" to "dxvk",
|
||||
@@ -32,6 +34,10 @@ object ComponentsManager {
|
||||
"Dxvk-gplasync-Linux" to "dxvk",
|
||||
"Vkd3d-proton-Linux" to "vkd3d",
|
||||
)
|
||||
// DD_NIGHTLY holds every component in one release; the file name says which.
|
||||
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
|
||||
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
|
||||
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
|
||||
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
|
||||
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
|
||||
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
||||
@@ -815,14 +821,15 @@ object ComponentsManager {
|
||||
if (!force && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) }
|
||||
if (!force) return Catalog(emptyList(), 0)
|
||||
val items = JSONArray()
|
||||
for ((tag, comp) in RELEASES) {
|
||||
val body = Downloader.downloadString("https://api.github.com/repos/$NIGHTLIES/releases/tags/$tag") ?: continue
|
||||
for ((repo, tag) in SOURCES) {
|
||||
val body = Downloader.downloadString("https://api.github.com/repos/$repo/releases/tags/$tag") ?: continue
|
||||
val assets = runCatching { JSONObject(body).optJSONArray("assets") }.getOrNull() ?: continue
|
||||
for (i in 0 until assets.length()) {
|
||||
val a = assets.getJSONObject(i)
|
||||
val name = a.optString("name")
|
||||
if (!name.endsWith(".wcp")) continue
|
||||
if (!Hashes.isGithubSha256(a.optString("digest"))) continue
|
||||
val comp = assetComp(tag, name) ?: continue
|
||||
items.put(JSONObject().put("file", name).put("comp", comp).put("release", tag)
|
||||
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
|
||||
}
|
||||
@@ -837,10 +844,32 @@ object ComponentsManager {
|
||||
val arr = o.optJSONArray("items") ?: JSONArray()
|
||||
val items = (0 until arr.length()).map { arr.getJSONObject(it) }.map {
|
||||
CatalogItem(it.optString("file"), it.optString("comp"), it.optString("release"), it.optString("url"), it.optLong("size"), it.optString("digest"))
|
||||
}.sortedWith(compareBy<CatalogItem> { it.comp }.then(newestFirst { it.file }))
|
||||
}.sortedWith(CATALOG_ORDER)
|
||||
return Catalog(items, o.optLong("fetchedAt"))
|
||||
}
|
||||
|
||||
internal fun assetComp(release: String, name: String): String? =
|
||||
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
|
||||
|
||||
// Per component: the stable packages newest first, then the nightlies.
|
||||
internal val CATALOG_ORDER: Comparator<CatalogItem> =
|
||||
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
|
||||
|
||||
// A nightly DD-<flavor>-<version>[+N]-nightly.wcp pairs with the newest stable <flavor>-<version>[-<rev>]-linux.wcp
|
||||
// in the same list, so the stable row can offer it behind a Stable/Nightly switch. Unpaired nightlies keep their own row.
|
||||
internal fun nightlyPairs(items: List<CatalogItem>): Map<CatalogItem, CatalogItem> {
|
||||
val stable = items.filter { it.release != DD_NIGHTLY }
|
||||
return items.filter { it.release == DD_NIGHTLY }.mapNotNull { n ->
|
||||
val base = n.file.removePrefix("DD-").removeSuffix("-nightly.wcp").substringBefore('+')
|
||||
val rev = Regex(Regex.escape(base) + "(-\\d+)?-linux\\.wcp")
|
||||
stable.filter { it.comp == n.comp && rev.matches(it.file) }
|
||||
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }?.let { it to n }
|
||||
}.groupBy({ it.first }, { it.second })
|
||||
.mapValues { (_, ns) -> ns.maxWith { a, b -> ProtonExtras.compareVersions(a.file, b.file) } }
|
||||
}
|
||||
|
||||
internal fun allowedDownload(url: String) = DOWNLOAD_REPOS.any { url.startsWith("https://github.com/$it/releases/download/") }
|
||||
|
||||
private fun <T> newestFirst(of: (T) -> String): Comparator<T> =
|
||||
Comparator { a, b -> ProtonExtras.compareVersions(of(b), of(a)) }
|
||||
|
||||
@@ -925,11 +954,13 @@ object ComponentsManager {
|
||||
): CatalogItem? = catalogMatch(cached(), file, release) ?: catalogMatch(refresh(), file, release)
|
||||
|
||||
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
|
||||
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { context.getString(R.string.cmgr_nightlies_only) }
|
||||
require(allowedDownload(item.url)) { context.getString(R.string.cmgr_nightlies_only) }
|
||||
require(Hashes.isGithubSha256(item.digest)) { context.getString(R.string.cmgr_list_predates_checksums) }
|
||||
val dest = File(packagesDir(context), safeName(item.file))
|
||||
val part = File(dest.parentFile, dest.name + ".part")
|
||||
check(Downloader.downloadFile(item.url, part, true, item.digest.substringAfter(':')) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { context.getString(R.string.user_apps_download_failed) }
|
||||
check(Downloader.downloadFile(item.url, part, true, item.digest.substringAfter(':')) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) {
|
||||
context.getString(if (item.release == DD_NIGHTLY) R.string.cmgr_nightly_replaced else R.string.user_apps_download_failed)
|
||||
}
|
||||
if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error(context.getString(R.string.cmgr_checksum_mismatch)) }
|
||||
val info = runCatching { packageInfo(context, part) }.getOrElse { part.delete(); throw it }
|
||||
synchronized(lock) { part.renameTo(dest) }
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.os.FileObserver
|
||||
import android.os.SystemClock
|
||||
import android.system.Os
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.input.FakeInputWriter
|
||||
import java.io.File
|
||||
|
||||
class InputSysfsComponent(
|
||||
private val nodes: File,
|
||||
base: File,
|
||||
private val udevData: File,
|
||||
private val deckPad: Boolean,
|
||||
private val steamVirtual: Boolean,
|
||||
) : SessionPart() {
|
||||
private val devices = File(base, "devices")
|
||||
private val classDir = File(base, "class")
|
||||
private val shown = HashSet<Int>()
|
||||
private var observer: FileObserver? = null
|
||||
private var running = false
|
||||
|
||||
fun prepare(): Boolean = try {
|
||||
FileUtils.clear(devices)
|
||||
FileUtils.clear(classDir)
|
||||
devices.mkdirs()
|
||||
classDir.mkdirs()
|
||||
udevData.mkdirs()
|
||||
udevData.listFiles()?.forEach { if (isPadRecord(it.name)) it.delete() }
|
||||
devices.isDirectory && classDir.isDirectory
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "pads: could not prepare the input sysfs: $e")
|
||||
false
|
||||
}
|
||||
|
||||
fun binds() = listOf(devices.path + ":" + GUEST_DEVICES, classDir.path + ":" + GUEST_CLASS)
|
||||
|
||||
override fun start() {
|
||||
synchronized(this) { running = true }
|
||||
active = this
|
||||
@Suppress("DEPRECATION")
|
||||
observer = object : FileObserver(nodes.path, CREATE or DELETE or MOVED_TO or MOVED_FROM or CLOSE_WRITE) {
|
||||
override fun onEvent(event: Int, path: String?) {
|
||||
if (path != null && NODE_FILE.matches(path)) sync()
|
||||
}
|
||||
}.also { it.startWatching() }
|
||||
sync()
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
observer?.stopWatching()
|
||||
observer = null
|
||||
if (active === this) active = null
|
||||
synchronized(this) {
|
||||
running = false
|
||||
for (node in shown.toList()) hide(node)
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun sync() {
|
||||
if (!running) return
|
||||
val wanted = (0 until NODE_LIMIT).filter { node ->
|
||||
File(nodes, "event$node").exists() && if (node >= FIRST_VIRTUAL) File(nodes, ".uinput-event$node.uevent").isFile
|
||||
else !ringWithdrawn(deckPad, padType)
|
||||
}.toSet()
|
||||
for (node in shown - wanted) hide(node)
|
||||
for (node in wanted - shown) show(node)
|
||||
}
|
||||
|
||||
private fun show(node: Int) {
|
||||
val pad = (if (node >= FIRST_VIRTUAL) runCatching { File(nodes, ".uinput-event$node.uevent").readText() }.getOrNull()?.let(::virtualPad)
|
||||
else ringPad(node, steamVirtual)) ?: return
|
||||
try {
|
||||
val input = File(devices, "input$node")
|
||||
val event = File(input, "event$node")
|
||||
event.mkdirs()
|
||||
File(input, "uevent").writeText(pad.uevent())
|
||||
File(input, "name").writeText(pad.name + "\n")
|
||||
File(input, "phys").writeText(pad.phys + "\n")
|
||||
File(input, "uniq").writeText(pad.uniq + "\n")
|
||||
File(input, "properties").writeText("0\n")
|
||||
File(input, "id").mkdirs()
|
||||
File(input, "id/bustype").writeText("%04x\n".format(pad.bus))
|
||||
File(input, "id/vendor").writeText("%04x\n".format(pad.vendor))
|
||||
File(input, "id/product").writeText("%04x\n".format(pad.product))
|
||||
File(input, "id/version").writeText("%04x\n".format(pad.version))
|
||||
File(input, "capabilities").mkdirs()
|
||||
for (name in CAPABILITIES) File(input, "capabilities/$name").writeText("0\n")
|
||||
link(File(input, "subsystem"), GUEST_CLASS)
|
||||
File(event, "uevent").writeText("MAJOR=$MAJOR\nMINOR=${MINOR_BASE + node}\nDEVNAME=input/event$node\n")
|
||||
File(event, "dev").writeText("$MAJOR:${MINOR_BASE + node}\n")
|
||||
link(File(event, "subsystem"), GUEST_CLASS)
|
||||
link(File(event, "device"), "$GUEST_DEVICES/input$node")
|
||||
val record = udevRecord(SystemClock.elapsedRealtimeNanos() / 1000)
|
||||
File(udevData, "+input:input$node").writeText(record)
|
||||
File(udevData, "c$MAJOR:${MINOR_BASE + node}").writeText(record)
|
||||
link(File(classDir, "input$node"), "$GUEST_DEVICES/input$node")
|
||||
link(File(classDir, "event$node"), "$GUEST_DEVICES/input$node/event$node")
|
||||
shown.add(node)
|
||||
Log.i(TAG, "pads: /dev/input/event$node listed for udev as \"${pad.name}\" (%04x:%04x)".format(pad.vendor, pad.product))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "pads: could not list /dev/input/event$node for udev: $e")
|
||||
hide(node)
|
||||
}
|
||||
}
|
||||
|
||||
private fun hide(node: Int) {
|
||||
File(classDir, "event$node").delete()
|
||||
File(classDir, "input$node").delete()
|
||||
File(udevData, "c$MAJOR:${MINOR_BASE + node}").delete()
|
||||
File(udevData, "+input:input$node").delete()
|
||||
File(devices, "input$node").let { FileUtils.clear(it); it.delete() }
|
||||
if (shown.remove(node)) Log.i(TAG, "pads: /dev/input/event$node no longer listed for udev")
|
||||
}
|
||||
|
||||
private fun link(file: File, target: String) {
|
||||
file.delete()
|
||||
Os.symlink(target, file.path)
|
||||
}
|
||||
|
||||
data class Pad(
|
||||
val bus: Int,
|
||||
val vendor: Int,
|
||||
val product: Int,
|
||||
val version: Int,
|
||||
val name: String,
|
||||
val phys: String,
|
||||
val uniq: String,
|
||||
) {
|
||||
fun uevent(): String =
|
||||
"PRODUCT=%x/%x/%x/%x\nNAME=\"$name\"\nPHYS=\"$phys\"\nUNIQ=\"$uniq\"\nPROP=0\n".format(bus, vendor, product, version)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
const val GUEST_DEVICES = "/sys/devices/virtual/input"
|
||||
const val GUEST_CLASS = "/sys/class/input"
|
||||
private const val MAJOR = 13
|
||||
private const val MINOR_BASE = 64
|
||||
private const val FIRST_VIRTUAL = 16
|
||||
private const val NODE_LIMIT = 64
|
||||
private val NODE_FILE = Regex("(\\.uinput-)?event\\d+(\\.uevent)?")
|
||||
private val CAPABILITIES = listOf("ev", "key", "rel", "abs", "msc", "sw", "led", "snd", "ff")
|
||||
|
||||
@Volatile private var active: InputSysfsComponent? = null
|
||||
@Volatile private var padType = -1
|
||||
|
||||
fun padTypeChanged(type: Int) {
|
||||
padType = type
|
||||
active?.let { Thread(it::sync, "input-sysfs").start() }
|
||||
}
|
||||
|
||||
internal fun ringWithdrawn(deckPad: Boolean, type: Int) = deckPad && type != FakeInputWriter.PAD_TYPE_XBOX
|
||||
|
||||
internal fun isPadRecord(name: String) =
|
||||
Regex("c$MAJOR:(\\d+)").matchEntire(name)?.groupValues?.get(1)?.toInt()?.let { it in MINOR_BASE until MINOR_BASE + NODE_LIMIT } == true ||
|
||||
Regex("\\+input:input(\\d+)").matchEntire(name)?.groupValues?.get(1)?.toInt()?.let { it < NODE_LIMIT } == true
|
||||
|
||||
internal fun udevRecord(initializedUs: Long) =
|
||||
"I:$initializedUs\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\nE:ID_SERIAL=noserial\nG:seat\nG:uaccess\nQ:seat\nQ:uaccess\nV:1\n"
|
||||
|
||||
internal fun ringPad(node: Int, steamVirtual: Boolean) = if (steamVirtual) {
|
||||
Pad(3, 0x28de, 0x11ff, 0x110, "Microsoft X-Box 360 pad $node", "usb-fakeinput/input$node", "0000000000%02d".format(node))
|
||||
} else {
|
||||
Pad(3, 0x045e, 0x028e, 0x110, "Xbox 360 Controller ($node)", "usb-fakeinput/input$node", "0000000000%02d".format(node))
|
||||
}
|
||||
|
||||
internal fun virtualPad(uevent: String): Pad? {
|
||||
val values = uevent.lines().mapNotNull { line ->
|
||||
line.indexOf('=').takeIf { it > 0 }?.let { line.substring(0, it) to line.substring(it + 1).trim('"') }
|
||||
}.toMap()
|
||||
val id = values["PRODUCT"]?.split('/')?.mapNotNull { it.toIntOrNull(16) }?.takeIf { it.size == 4 } ?: return null
|
||||
return Pad(id[0], id[1], id[2], id[3], values["NAME"] ?: return null, values["PHYS"].orEmpty(), values["UNIQ"].orEmpty())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.BatteryManager
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
@@ -15,21 +18,35 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
class PerfHud(context: Context) {
|
||||
var text by mutableStateOf("")
|
||||
private set
|
||||
var graph by mutableStateOf(FloatArray(0))
|
||||
private set
|
||||
|
||||
private val context = context.applicationContext
|
||||
private val frames = AtomicInteger()
|
||||
private var lastTick = 0L
|
||||
private var lastFps = 0f
|
||||
private var running = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val intervals = FloatArray(GRAPH)
|
||||
private val graphWrite = AtomicInteger()
|
||||
private val lastFrameNs = AtomicLong()
|
||||
|
||||
@Volatile private var showFps = true
|
||||
@Volatile private var showBattery = true
|
||||
@Volatile private var showGraph = true
|
||||
|
||||
private val enabled: Boolean
|
||||
get() = SessionPrefs.hudEnabled(context)
|
||||
&& !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
|
||||
|
||||
private val anyPart: Boolean
|
||||
get() = showFps || showBattery || showGraph
|
||||
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
private var lastWindow: String? = null
|
||||
|
||||
@@ -40,7 +57,17 @@ class PerfHud(context: Context) {
|
||||
handler.post { onPresentingWindowChanged?.invoke() }
|
||||
}
|
||||
}
|
||||
override fun onGameFrame() { frames.incrementAndGet() }
|
||||
override fun onGameFrame() {
|
||||
frames.incrementAndGet()
|
||||
if (!showGraph) return
|
||||
val now = System.nanoTime()
|
||||
val previous = lastFrameNs.getAndSet(now)
|
||||
if (previous == 0L) return
|
||||
val ms = ((now - previous) / 1_000_000f).coerceIn(0f, 50f)
|
||||
val slot = graphWrite.get()
|
||||
intervals[slot and (GRAPH - 1)] = ms
|
||||
graphWrite.compareAndSet(slot, slot + 1)
|
||||
}
|
||||
}
|
||||
|
||||
private val tick = object : Runnable {
|
||||
@@ -49,35 +76,89 @@ class PerfHud(context: Context) {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val dt = (now - lastTick).coerceAtLeast(1L) / 1000f
|
||||
lastTick = now
|
||||
text = line(frames.getAndSet(0) / dt)
|
||||
handler.postDelayed(this, 1000)
|
||||
lastFps = frames.getAndSet(0) / dt
|
||||
text = readout(lastFps)
|
||||
if (showGraph) publishGraph() else clearGraph()
|
||||
handler.postDelayed(this, TICK_MS)
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
if (enabled) start() else stop()
|
||||
readOptions()
|
||||
if (!enabled || !anyPart) {
|
||||
stop()
|
||||
return
|
||||
}
|
||||
if (!running) start() else {
|
||||
if (!showGraph) clearGraph() else publishGraph()
|
||||
text = readout(lastFps)
|
||||
}
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (!enabled || running) return
|
||||
readOptions()
|
||||
if (!enabled || !anyPart || running) return
|
||||
running = true
|
||||
lastTick = SystemClock.elapsedRealtime()
|
||||
lastFrameNs.set(0L)
|
||||
frames.set(0)
|
||||
graphWrite.set(0)
|
||||
WaylandCompositor.setGameListener(listener)
|
||||
handler.post(tick)
|
||||
handler.postDelayed(tick, TICK_MS)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
running = false
|
||||
handler.removeCallbacks(tick)
|
||||
WaylandCompositor.clearGameListener(listener)
|
||||
text = ""
|
||||
graph = FloatArray(0)
|
||||
}
|
||||
|
||||
private fun readOptions() {
|
||||
showFps = SessionPrefs.hudShowFps(context)
|
||||
showBattery = SessionPrefs.hudShowBattery(context)
|
||||
showGraph = SessionPrefs.hudShowGraph(context)
|
||||
}
|
||||
|
||||
private fun readout(fpsValue: Float): String {
|
||||
val parts = ArrayList<String>(2)
|
||||
if (showFps) parts.add(line(fpsValue))
|
||||
if (showBattery) batteryCelsius(readBatteryDeci())?.let { parts.add(it) }
|
||||
return parts.joinToString("\n")
|
||||
}
|
||||
|
||||
private fun readBatteryDeci(): Int {
|
||||
val sticky = runCatching {
|
||||
context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
}.getOrNull() ?: return 0
|
||||
return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
|
||||
}
|
||||
|
||||
private fun clearGraph() {
|
||||
lastFrameNs.set(0L)
|
||||
graphWrite.set(0)
|
||||
if (graph.isNotEmpty()) graph = FloatArray(0)
|
||||
}
|
||||
|
||||
private fun publishGraph() {
|
||||
val count = graphWrite.get()
|
||||
val shown = minOf(count, GRAPH)
|
||||
if (shown < 2) {
|
||||
graph = FloatArray(0)
|
||||
return
|
||||
}
|
||||
val out = FloatArray(shown)
|
||||
val start = count - shown
|
||||
for (i in 0 until shown) out[i] = intervals[(start + i) and (GRAPH - 1)]
|
||||
graph = out
|
||||
}
|
||||
|
||||
private fun line(base: Float): String {
|
||||
val mode = FrameGen.mode(context)
|
||||
if (mode.engine == FrameGen.ENGINE_OFF) return fps(base)
|
||||
val lsfg = mode.engine == FrameGen.ENGINE_LSFG
|
||||
val name = if (lsfg) "LSFG" else "Win-FG"
|
||||
val name = if (lsfg) "LSFG" else "DD-FG"
|
||||
val label = FrameGen.label(context, mode)
|
||||
if (lsfg && Lossless.cacheFile(context)?.isFile != true) return context.getString(R.string.hud_fg_needs_lossless, name)
|
||||
val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null }
|
||||
@@ -91,4 +172,12 @@ class PerfHud(context: Context) {
|
||||
}
|
||||
|
||||
private fun fps(value: Float) = String.format(Locale.US, "%.0f fps", value)
|
||||
|
||||
companion object {
|
||||
private const val TICK_MS = 1_000L
|
||||
private const val GRAPH = 128
|
||||
|
||||
internal fun batteryCelsius(deci: Int): String? =
|
||||
if (deci <= 0) null else String.format(Locale.US, "%.1f°C", deci / 10f)
|
||||
}
|
||||
}
|
||||
@@ -118,7 +118,9 @@ object SessionArtifacts {
|
||||
|
||||
private fun scrubFolder(dir: File, record: Record) {
|
||||
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f ->
|
||||
if (!LogRedactor.isText(f)) return@forEach
|
||||
if (LogRedactor.isBinary(f)) return@forEach
|
||||
// Too large to rewrite in memory: the folder must not be recorded as scrubbed.
|
||||
if (!LogRedactor.isText(f)) { record.failed = true; return@forEach }
|
||||
val done = scrubFile(dir, f)
|
||||
if (done == null) record.failed = true else record.files[f] = done
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.BwrapSpawner
|
||||
import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
import com.droiddeck.launcher.runtime.LegacyNames
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
@@ -15,6 +17,7 @@ object SessionFiles {
|
||||
private const val TAG = "SessionFiles"
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
||||
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
|
||||
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
|
||||
|
||||
internal val DESKTOP_FILES = arrayOf(
|
||||
@@ -27,7 +30,8 @@ object SessionFiles {
|
||||
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
|
||||
)
|
||||
|
||||
fun stage(context: Context, root: File) {
|
||||
/** Puts the session's files in place; [startsSession] is true only for the call that starts the Steam session. */
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) {
|
||||
if (DesktopCatalog.desktopInstalled(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
||||
GameEnvironmentStore.publish(context)
|
||||
@@ -66,6 +70,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
|
||||
"usr/local/bin/droiddeck-steam-shim" to "usr/local/bin/droiddeck-steam-shim",
|
||||
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
|
||||
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
|
||||
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
|
||||
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
|
||||
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
|
||||
@@ -77,8 +82,10 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-x64-arm-webhelper" to "usr/local/bin/droiddeck-x64-arm-webhelper",
|
||||
"usr/local/bin/droiddeck-x64-webhelper" to "usr/local/bin/droiddeck-x64-webhelper",
|
||||
"usr/local/bin/droiddeck-steamvr" to "usr/local/bin/droiddeck-steamvr",
|
||||
"usr/local/bin/droiddeck-pipewire" to "usr/local/bin/droiddeck-pipewire",
|
||||
"usr/local/bin/droiddeck-steamvr-settings" to "usr/local/bin/droiddeck-steamvr-settings",
|
||||
"usr/local/bin/droiddeck-steamvr-game" to "usr/local/bin/droiddeck-steamvr-game",
|
||||
"usr/local/bin/droiddeck-steamvr-flat" to "usr/local/bin/droiddeck-steamvr-flat",
|
||||
"usr/local/bin/droiddeck-bwrap" to "usr/local/bin/droiddeck-bwrap",
|
||||
"usr/local/bin/droiddeck-flatpak" to "usr/local/bin/droiddeck-flatpak",
|
||||
"usr/local/bin/droiddeck-flatpak-setup" to "usr/local/bin/droiddeck-flatpak-setup",
|
||||
@@ -132,14 +139,17 @@ object SessionFiles {
|
||||
val optional = (arrayOf(
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
|
||||
) + mangoapp + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
val all = (if (DesktopCatalog.desktopInstalled(root)) files + DESKTOP_FILES else files) + optional
|
||||
val ledger = StageLedger(File(root, STAGED_LEDGER), apkIdentity(context))
|
||||
for ((asset, relative) in all) {
|
||||
val target = File(root, relative)
|
||||
if (ledger.current(relative, target)) continue
|
||||
val staged = File(target.parentFile, target.name + ".staged")
|
||||
var installed = false
|
||||
try {
|
||||
@@ -153,7 +163,7 @@ object SessionFiles {
|
||||
} finally {
|
||||
if (!installed) staged.delete()
|
||||
}
|
||||
if (!installed) Log.e(TAG, "$relative NOT staged")
|
||||
if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
|
||||
}
|
||||
File(root, "usr/local/bin/bannerlator-steam-compat").delete()
|
||||
LegacyNames.migrateRootfs(root)
|
||||
@@ -165,13 +175,17 @@ object SessionFiles {
|
||||
"i386-windows/winedirectaudio.drv",
|
||||
"version.txt",
|
||||
)
|
||||
for (set in DIRECTAUDIO_SETS) for (relative in directAudio) {
|
||||
val target = File(root, "$DIRECTAUDIO_DIR/$set/lib/wine/$relative")
|
||||
val directAudioPack = AddonPack.DIRECTAUDIO.takeIf { it.installed(context) }?.dir(context)
|
||||
if (directAudioPack == null) Log.w(TAG, "DirectAudio pack is not installed; drivers not staged")
|
||||
if (directAudioPack != null) for (set in DIRECTAUDIO_SETS) for (relative in directAudio) {
|
||||
val key = "$DIRECTAUDIO_DIR/$set/lib/wine/$relative"
|
||||
val target = File(root, key)
|
||||
if (ledger.current(key, target)) continue
|
||||
val staged = File(target.parentFile, target.name + ".staged")
|
||||
var installed = false
|
||||
try {
|
||||
target.parentFile?.mkdirs()
|
||||
context.assets.open("directaudio/$set/$relative").use { input ->
|
||||
File(directAudioPack, "$set/$relative").inputStream().use { input ->
|
||||
staged.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
installed = staged.setReadable(true, false) && staged.renameTo(target)
|
||||
@@ -180,8 +194,9 @@ object SessionFiles {
|
||||
} finally {
|
||||
if (!installed) staged.delete()
|
||||
}
|
||||
if (!installed) Log.e(TAG, "DirectAudio $set/$relative NOT staged")
|
||||
if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged")
|
||||
}
|
||||
ledger.save()
|
||||
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
|
||||
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
@@ -198,20 +213,118 @@ object SessionFiles {
|
||||
if (!FileUtils.writeString(File(etc, "steam-compatibility-label"), context.getString(R.string.steam_compat_label))) {
|
||||
Log.e(TAG, "could not write steam-compatibility-label")
|
||||
}
|
||||
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
|
||||
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
|
||||
if (!FileUtils.writeString(stagedSocket, BwrapSpawner.socket(context) + "\n")
|
||||
|| !stagedSocket.renameTo(File(droiddeckEtc, "bwrap-socket"))) {
|
||||
stagedSocket.delete()
|
||||
Log.e(TAG, "could not write bwrap-socket")
|
||||
}
|
||||
|
||||
BootMovie.syncFromSteam(context)
|
||||
val startupMovie = BootMovie.prepare(context)
|
||||
// The x86-64 client's config is left alone until its first start creates it.
|
||||
val steamRoots = listOf(File(root, "root/.local/share/Steam"), File(root, "root/.droiddeck-x64/.local/share/Steam"))
|
||||
.filterIndexed { i, steam -> i == 0 || File(steam, "config").isDirectory }
|
||||
for (steam in steamRoots) {
|
||||
val startupMovieDir = File(steam, "config/uioverrides/movies")
|
||||
val bigPictureMovieInstalled = startupMovie != null &&
|
||||
stageStartupMovie(startupMovie, startupMovieDir, "bigpicture_startup.webm")
|
||||
if (startupMovie != null) stageStartupMovie(startupMovie, startupMovieDir, "steam_os_startup.webm")
|
||||
if (bigPictureMovieInstalled) {
|
||||
ensureStartupMovieDefault(File(steam, "config/config.vdf"))
|
||||
val force = SessionPrefs.bootMovieApplyNext(context)
|
||||
val steamHomes = listOf(File(root, "root/.local/share/Steam")) +
|
||||
listOf(File(root, "root/.droiddeck-x64/.local/share/Steam")).filter { File(it, "config").isDirectory }
|
||||
var allDone = true
|
||||
var allInstalled = true
|
||||
var seen: String? = null
|
||||
val activeIsX64 = SessionPrefs.activeSteamClientArch(context) == "x86_64"
|
||||
for (home in steamHomes) {
|
||||
val movieDir = File(home, "config/uioverrides/movies")
|
||||
val config = File(home, "config/config.vdf")
|
||||
if (startupMovie == null) {
|
||||
// Nothing to play (a movie whose volume could not be set is never played at another volume), so no earlier copy plays either.
|
||||
for (name in listOf("bigpicture_startup.webm", "steam_os_startup.webm")) {
|
||||
File(movieDir, name).delete()
|
||||
File(movieDir, ".$name.source").delete()
|
||||
}
|
||||
}
|
||||
val bigPictureMovieInstalled = startupMovie != null && stageStartupMovie(startupMovie, movieDir, "bigpicture_startup.webm")
|
||||
if (startupMovie != null) stageStartupMovie(startupMovie, movieDir, "steam_os_startup.webm")
|
||||
val before = startupMoviePath(config)
|
||||
val done = if (bigPictureMovieInstalled) ensureStartupMovieDefault(config, force) else resetMissingStartupMovie(config, force)
|
||||
BootMovieReport.note(
|
||||
context,
|
||||
"stage session=$startsSession pending=$force choice=${SessionPrefs.bootMovie(context)} movie=${startupMovie?.path} " +
|
||||
"staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}",
|
||||
)
|
||||
if (!done) allDone = false
|
||||
if (!bigPictureMovieInstalled) allInstalled = false
|
||||
if (done && home.path.contains(".droiddeck-x64") == activeIsX64) seen = if (bigPictureMovieInstalled) BOOT_MOVIE_PATH else ""
|
||||
}
|
||||
// A pick made in the app is done once a session started with every Steam client's config having it; guest commands run
|
||||
// before that, and a Steam that is already running writes its own choice back when it exits.
|
||||
if (force && allDone && allInstalled && startsSession) SessionPrefs.setBootMovieApplyNext(context, false)
|
||||
seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Points Steam's startup movie back at its own default when it names a movie that is gone: DroidDeck's staged copy that
|
||||
* could not be prepared, or (when a pick here is waiting) a movie removed from Steam's folder. True when Steam's config
|
||||
* no longer names a missing movie.
|
||||
*/
|
||||
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
|
||||
if (!config.isFile) return true
|
||||
val text = runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config to reset the startup movie", it)
|
||||
return false
|
||||
}
|
||||
val movie = activeStartupMovie(text) ?: return true
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
val path = scalar(block, "LocalPath").orEmpty()
|
||||
if (path.isEmpty()) return true
|
||||
val missing = File(config.parentFile, "uioverrides/movies/" + path.removePrefix(BOOT_MOVIES_DIR))
|
||||
val gone = path.startsWith(BOOT_MOVIES_DIR) && !missing.isFile && (force || path == BOOT_MOVIE_PATH)
|
||||
if (!gone) return false
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val updated = setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", "", newline)
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
staged.writeText(text.replaceRange(movie.keyStart, movie.close + 1, updated))
|
||||
(staged.renameTo(config)).also { if (!it) staged.delete() }
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not reset Steam startup movie selection", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun apkIdentity(context: Context): String {
|
||||
val apk = File(context.applicationInfo.sourceDir)
|
||||
return "${apk.path} ${apk.length()} ${apk.lastModified()}"
|
||||
}
|
||||
|
||||
private class StageLedger(private val file: File, private val identity: String) {
|
||||
private val before: Map<String, String> = FileUtils.readString(file)?.lines()
|
||||
?.takeIf { it.firstOrNull() == identity }
|
||||
?.drop(1)?.mapNotNull { line -> line.split('\t').takeIf { it.size == 2 }?.let { it[0] to it[1] } }?.toMap()
|
||||
.orEmpty()
|
||||
private val after = LinkedHashMap<String, String>()
|
||||
|
||||
fun current(relative: String, target: File): Boolean {
|
||||
val mark = mark(target) ?: return false
|
||||
if (before[relative] != mark) return false
|
||||
after[relative] = mark
|
||||
return true
|
||||
}
|
||||
|
||||
fun staged(relative: String, target: File) {
|
||||
mark(target)?.let { after[relative] = it }
|
||||
}
|
||||
|
||||
fun save() {
|
||||
if (after == before) return
|
||||
val text = (listOf(identity) + after.map { (relative, mark) -> "$relative\t$mark" }).joinToString("\n")
|
||||
val staged = File(file.parentFile, file.name + ".staged")
|
||||
if (!FileUtils.writeString(staged, text) || !staged.renameTo(file)) {
|
||||
staged.delete()
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun mark(target: File): String? =
|
||||
if (target.isFile) "${target.length()} ${target.lastModified()} ${target.canExecute()}" else null
|
||||
}
|
||||
|
||||
private fun stageStartupMovie(source: File, directory: File, name: String): Boolean {
|
||||
@@ -227,7 +340,11 @@ object SessionFiles {
|
||||
staged.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
installed = staged.setReadable(true, false) && staged.renameTo(movie)
|
||||
if (installed) FileUtils.writeString(stamp, identity)
|
||||
if (installed) {
|
||||
FileUtils.writeString(stamp, identity)
|
||||
// Steam's picker draws its preview from this picture and does not redraw it when the movie changes.
|
||||
File(directory, name.removeSuffix(".webm") + ".jpg").delete()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not stage Steam startup movie $name", e)
|
||||
} finally {
|
||||
@@ -239,43 +356,108 @@ object SessionFiles {
|
||||
|
||||
private data class VdfBlock(val keyStart: Int, val open: Int, val close: Int)
|
||||
|
||||
private fun ensureStartupMovieDefault(config: File) {
|
||||
val path = "/uioverrides/movies/bigpicture_startup.webm"
|
||||
internal const val BOOT_MOVIES_DIR = "/uioverrides/movies/"
|
||||
internal const val BOOT_MOVIE_PATH = "/uioverrides/movies/bigpicture_startup.webm"
|
||||
|
||||
/**
|
||||
* Steam's startup movie setting is the `StartupMovie` section inside its `Customization` section; the one under the Steam
|
||||
* settings is where older clients kept it, and DroidDeck still keeps it in step.
|
||||
*/
|
||||
private fun customizationMovie(text: String): VdfBlock? {
|
||||
var from = 0
|
||||
while (true) {
|
||||
val customization = findObject(text, "Customization", from, text.length) ?: return null
|
||||
findObject(text, "StartupMovie", customization.open + 1, customization.close)?.let { return it }
|
||||
from = customization.close + 1
|
||||
}
|
||||
}
|
||||
|
||||
/** The older `StartupMovie` section: the first one that is not inside `Customization`. */
|
||||
private fun olderMovie(text: String): VdfBlock? {
|
||||
val inside = customizationMovie(text)
|
||||
var from = 0
|
||||
while (true) {
|
||||
val movie = findObject(text, "StartupMovie", from, text.length) ?: return null
|
||||
if (inside == null || movie.keyStart != inside.keyStart) return movie
|
||||
from = movie.close + 1
|
||||
}
|
||||
}
|
||||
|
||||
/** The section Steam reads: the one under `Customization` when there is one. */
|
||||
private fun activeStartupMovie(text: String): VdfBlock? = customizationMovie(text) ?: olderMovie(text)
|
||||
|
||||
/** The movie Steam's config selects, as a path like `/uioverrides/movies/x.webm`; null when none is named. */
|
||||
internal fun startupMoviePath(config: File): String? {
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return null
|
||||
val movie = activeStartupMovie(text) ?: return null
|
||||
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
/** Both `StartupMovie` sections of Steam's config as written there, for the report; null when there is none. */
|
||||
internal fun startupMovieBlock(config: File): String? {
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return null
|
||||
val parts = listOfNotNull(
|
||||
customizationMovie(text)?.let { "under Customization:\n" + text.substring(it.keyStart, it.close + 1) },
|
||||
olderMovie(text)?.let { "older place:\n" + text.substring(it.keyStart, it.close + 1) },
|
||||
)
|
||||
return parts.takeIf { it.isNotEmpty() }?.joinToString("\n")
|
||||
}
|
||||
|
||||
/** The `Customization` section of Steam's config with the lines before it, for the report; null when there is none. */
|
||||
internal fun customizationBlock(config: File): String? {
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return null
|
||||
val customization = findObject(text, "Customization", 0, text.length) ?: return null
|
||||
val before = text.substring(0, customization.keyStart).lines().takeLast(4).joinToString("\n")
|
||||
return (before + "\n" + text.substring(customization.keyStart, customization.close + 1)).take(4000)
|
||||
}
|
||||
|
||||
private fun pointAt(text: String, movie: VdfBlock, path: String, newline: String): String {
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
return text.replaceRange(movie.keyStart, movie.close + 1, setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", path, newline))
|
||||
}
|
||||
|
||||
/** True when Steam's config selects DroidDeck's staged movie once this returns. */
|
||||
internal fun ensureStartupMovieDefault(config: File, force: Boolean = false): Boolean {
|
||||
val path = BOOT_MOVIE_PATH
|
||||
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
|
||||
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config for startup movie", it)
|
||||
return
|
||||
return false
|
||||
} else ""
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val movie = findObject(text, "StartupMovie", 0, text.length)
|
||||
if (movie != null) {
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
val custom = customizationMovie(text)
|
||||
val active = custom ?: olderMovie(text)
|
||||
if (active != null) {
|
||||
val block = text.substring(active.keyStart, active.close + 1)
|
||||
val selectedId = scalar(block, "MovieID")
|
||||
val selectedPath = scalar(block, "LocalPath")
|
||||
if (selectedPath == path) {
|
||||
if (selectedPath == path && custom != null) {
|
||||
Log.i(TAG, "Steam startup movie is set to DroidDeck")
|
||||
return
|
||||
return true
|
||||
}
|
||||
val legacyDefault = selectedId == "0" && selectedPath == legacyPath
|
||||
val hasExplicitSelection =
|
||||
(!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()
|
||||
if (!legacyDefault && hasExplicitSelection) {
|
||||
if (!force && !legacyDefault && hasExplicitSelection && selectedPath != path) {
|
||||
Log.i(TAG, "Steam startup movie selection preserved")
|
||||
return
|
||||
return false
|
||||
}
|
||||
val updated = setScalar(block, "MovieID", "0", newline)
|
||||
.let { setScalar(it, "LocalPath", path, newline) }
|
||||
text = text.replaceRange(movie.keyStart, movie.close + 1, updated)
|
||||
} else {
|
||||
}
|
||||
// Later sections first, so the positions of earlier ones stay valid.
|
||||
val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }
|
||||
for (target in targets) text = pointAt(text, target, path, newline)
|
||||
if (olderMovie(text) == null) {
|
||||
val steam = findSteamBlock(text)
|
||||
if (steam == null) {
|
||||
if (text.isNotBlank()) {
|
||||
if (text.isNotBlank() && customizationMovie(text) == null) {
|
||||
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
|
||||
return
|
||||
return false
|
||||
}
|
||||
if (text.isBlank()) {
|
||||
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
|
||||
val section = startupMovieSection("\t\t\t\t", path, newline)
|
||||
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
|
||||
}
|
||||
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
|
||||
val section = startupMovieSection("\t\t\t\t", path, newline)
|
||||
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
|
||||
@@ -283,22 +465,35 @@ object SessionFiles {
|
||||
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
|
||||
}
|
||||
}
|
||||
if (customizationMovie(text) == null) text = withCustomization(text, path, newline)
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
try {
|
||||
return try {
|
||||
config.parentFile?.mkdirs()
|
||||
staged.writeText(text)
|
||||
if (!staged.renameTo(config)) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write Steam startup movie selection")
|
||||
false
|
||||
} else {
|
||||
Log.i(TAG, "Steam startup movie default selected")
|
||||
true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not write Steam startup movie selection", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the `Customization` section Steam reads, next to the `Software` section, when the config has none. */
|
||||
private fun withCustomization(text: String, path: String, newline: String): String {
|
||||
val root = findObject(text, "InstallConfigStore", 0, text.length) ?: return text
|
||||
val lineStart = text.lastIndexOf('\n', root.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, root.close).takeWhile { it == '\t' || it == ' ' }
|
||||
val section = listOf(indent + "\t\"Customization\"", indent + "\t{", startupMovieSection(indent + "\t\t", path, newline), indent + "\t}").joinToString(newline)
|
||||
return text.substring(0, lineStart) + section + newline + text.substring(lineStart)
|
||||
}
|
||||
|
||||
private fun findSteamBlock(text: String): VdfBlock? {
|
||||
val install = findObject(text, "InstallConfigStore", 0, text.length) ?: return null
|
||||
val software = findObject(text, "Software", install.open + 1, install.close) ?: return null
|
||||
|
||||
@@ -66,15 +66,12 @@ object SessionLogShare {
|
||||
return zip
|
||||
}
|
||||
|
||||
/** Every entry is scrubbed line by line, whatever its size: a raw copy can carry tokens out of the device. */
|
||||
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
|
||||
z.putNextEntry(ZipEntry(name))
|
||||
if (LogRedactor.isText(f)) {
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubForShare(f, w)
|
||||
w.flush()
|
||||
} else {
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
}
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubForShare(f, w)
|
||||
w.flush()
|
||||
z.closeEntry()
|
||||
}
|
||||
|
||||
|
||||
@@ -21,12 +21,14 @@ object SessionPrefs {
|
||||
const val SUSPEND_NEVER = "never"
|
||||
private const val LEGACY_SUSPEND_DOWNLOADS = "downloads"
|
||||
private const val STEAM_DOWNLOADS_IN_BACKGROUND = "steamDownloadsInBackground"
|
||||
private const val DECKY_ZIP_WARNING_SEEN = "deckyZipWarningSeen"
|
||||
|
||||
const val CONTROLLER_DECK = "deck"
|
||||
const val CONTROLLER_XBOX360 = "xbox360"
|
||||
const val CONTROLLER_STEAM = "steamcontroller"
|
||||
const val CONTROLLER_DS4 = "dualshock4"
|
||||
const val CONTROLLER_DUALSENSE = "dualsense"
|
||||
const val CONTROLLER_NONE = "none"
|
||||
const val OSC_AUTO = "auto"
|
||||
const val OSC_ALWAYS = "always"
|
||||
const val OSC_STEAM_QAM = "steam-qam"
|
||||
@@ -49,9 +51,9 @@ object SessionPrefs {
|
||||
)
|
||||
|
||||
fun orientation(context: Context): Int =
|
||||
prefs(context).getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
||||
prefs(context).getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
|
||||
.takeIf { value -> orientationOptions.any { it.first == value } }
|
||||
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
|
||||
?: ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
|
||||
|
||||
fun setOrientation(context: Context, orientation: Int) {
|
||||
require(orientationOptions.any { it.first == orientation })
|
||||
@@ -118,8 +120,22 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
|
||||
}
|
||||
|
||||
fun storesTabOrder(context: Context): List<String> = idList(prefs(context).getString("storesTabOrder", null))
|
||||
|
||||
fun setStoresTabOrder(context: Context, order: List<String>) {
|
||||
prefs(context).edit().putString("storesTabOrder", order.joinToString(",")).apply()
|
||||
}
|
||||
|
||||
fun storesTabHidden(context: Context): Set<String> = idList(prefs(context).getString("storesTabHidden", null)).toSet()
|
||||
|
||||
fun setStoresTabHidden(context: Context, hidden: Set<String>) {
|
||||
prefs(context).edit().putString("storesTabHidden", hidden.joinToString(",")).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")
|
||||
val STORES_VIEWS = listOf("cards", "list")
|
||||
val STORES_VIEWS = listOf("cards", "capsules", "list")
|
||||
|
||||
const val STORES_OPEN_LIBRARY = "library"
|
||||
const val STORES_OPEN_STORE = "store"
|
||||
@@ -130,6 +146,13 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("storesInstallTarget", path).apply()
|
||||
}
|
||||
|
||||
/** Empty means follow the app/system language for GOG and Epic installs. */
|
||||
fun storesInstallLanguage(context: Context): String = prefs(context).getString("storesInstallLanguage", "") ?: ""
|
||||
|
||||
fun setStoresInstallLanguage(context: Context, code: String) {
|
||||
prefs(context).edit().putString("storesInstallLanguage", code).apply()
|
||||
}
|
||||
|
||||
fun gameStoresParallel(context: Context): Int = prefs(context).getInt("gameStoresParallel", 1).coerceIn(1, 3)
|
||||
|
||||
fun setGameStoresParallel(context: Context, count: Int) {
|
||||
@@ -142,6 +165,43 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean(hudKey(context), on).apply()
|
||||
}
|
||||
|
||||
fun hudShowFps(context: Context): Boolean = prefs(context).getBoolean("hudFps", true)
|
||||
|
||||
fun setHudShowFps(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("hudFps", on).apply()
|
||||
}
|
||||
|
||||
fun hudShowBattery(context: Context): Boolean = prefs(context).getBoolean("hudBattery", true)
|
||||
|
||||
fun setHudShowBattery(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("hudBattery", on).apply()
|
||||
}
|
||||
|
||||
fun hudShowGraph(context: Context): Boolean = prefs(context).getBoolean("hudGraph", true)
|
||||
|
||||
fun setHudShowGraph(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("hudGraph", on).apply()
|
||||
}
|
||||
|
||||
fun hudColor(context: Context): String =
|
||||
prefs(context).getString("hudColor", HUD_COLOR_MINT)?.takeIf { it in HUD_COLORS } ?: HUD_COLOR_MINT
|
||||
|
||||
fun setHudColor(context: Context, color: String) {
|
||||
if (color in HUD_COLORS) prefs(context).edit().putString("hudColor", color).apply()
|
||||
}
|
||||
|
||||
fun hudOpacity(context: Context): Int =
|
||||
prefs(context).getInt("hudOpacity", HUD_OPACITY_DEFAULT).takeIf { it in HUD_OPACITY_RANGE } ?: HUD_OPACITY_DEFAULT
|
||||
|
||||
fun setHudOpacity(context: Context, percent: Int) {
|
||||
prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply()
|
||||
}
|
||||
|
||||
const val HUD_COLOR_MINT = "mint"
|
||||
val HUD_COLORS = listOf(HUD_COLOR_MINT, "white", "sky", "amber", "violet")
|
||||
val HUD_OPACITY_RANGE = 30..100
|
||||
const val HUD_OPACITY_DEFAULT = 70
|
||||
|
||||
private fun hudKey(context: Context) = if (mangoappSession(context)) "hudDeck" else "hud"
|
||||
|
||||
private fun mangoappSession(context: Context) =
|
||||
@@ -168,6 +228,7 @@ object SessionPrefs {
|
||||
const val TOUCH_AUTO = "auto"
|
||||
const val TOUCH_PAD = "touchpad"
|
||||
const val TOUCH_DIRECT = "direct"
|
||||
const val TOUCH_GESTURES = "gestures"
|
||||
const val TOUCH_OFF = "off"
|
||||
|
||||
fun touchMode(context: Context): String = prefs(context).getString("touch", TOUCH_AUTO) ?: TOUCH_AUTO
|
||||
@@ -234,6 +295,16 @@ object SessionPrefs {
|
||||
position.takeIf { it in listOf("top", "bottom", "center") } ?: "center").apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* After a game launched from the front end (or another launcher's link) closes, the client
|
||||
* exits cleanly and the session returns there, instead of staying in Big Picture.
|
||||
*/
|
||||
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
|
||||
|
||||
fun setReturnAfterGame(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("returnAfterGame", on).apply()
|
||||
}
|
||||
|
||||
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
|
||||
|
||||
fun setStretch16x9(context: Context, on: Boolean) {
|
||||
@@ -405,6 +476,8 @@ object SessionPrefs {
|
||||
fun steamController(context: Context): String =
|
||||
prefs(context).getString("steamController", CONTROLLER_DECK) ?: CONTROLLER_DECK
|
||||
fun setSteamController(context: Context, id: String) { prefs(context).edit().putString("steamController", id).apply() }
|
||||
|
||||
fun builtinPad(context: Context): Boolean = steamController(context) != CONTROLLER_NONE
|
||||
fun padType(id: String): Int = when (id) {
|
||||
CONTROLLER_STEAM -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_STEAM
|
||||
CONTROLLER_XBOX360 -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_XBOX
|
||||
@@ -527,6 +600,17 @@ object SessionPrefs {
|
||||
fun setBootMovie(context: Context, id: String) { prefs(context).edit().putString("bootMovie", id).apply() }
|
||||
fun bootMovieSound(context: Context): Boolean = prefs(context).getBoolean("bootMovieSound", true)
|
||||
fun setBootMovieSound(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieSound", on).apply() }
|
||||
fun bootMovieVolume(context: Context): Int = prefs(context).getInt("bootMovieVolume", 100).coerceIn(0, 100)
|
||||
fun setBootMovieVolume(context: Context, percent: Int) { prefs(context).edit().putInt("bootMovieVolume", percent.coerceIn(0, 100)).apply() }
|
||||
/** How long the boot movie plays, in seconds; 0 plays all of it. */
|
||||
fun bootMovieSeconds(context: Context): Int = prefs(context).getInt("bootMovieSeconds", 0).coerceAtLeast(0)
|
||||
fun setBootMovieSeconds(context: Context, seconds: Int) { prefs(context).edit().putInt("bootMovieSeconds", seconds.coerceAtLeast(0)).apply() }
|
||||
/** Set when a movie was picked here, so the next session makes it Steam's startup movie even if Steam had another one. */
|
||||
fun bootMovieApplyNext(context: Context): Boolean = prefs(context).getBoolean("bootMovieApplyNext", false)
|
||||
fun setBootMovieApplyNext(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieApplyNext", on).apply() }
|
||||
/** The startup movie path Steam's config held when it was last looked at, so only a change made in Steam is taken over. */
|
||||
fun bootMovieSteamSeen(context: Context): String? = prefs(context).getString("bootMovieSteamSeen", null)
|
||||
fun setBootMovieSteamSeen(context: Context, path: String) { prefs(context).edit().putString("bootMovieSteamSeen", path).apply() }
|
||||
fun bootMovieCustomName(context: Context): String? = prefs(context).getString("bootMovieCustomName", null)
|
||||
fun setBootMovieCustomName(context: Context, name: String?) {
|
||||
prefs(context).edit().apply { if (name == null) remove("bootMovieCustomName") else putString("bootMovieCustomName", name) }.apply()
|
||||
@@ -878,6 +962,11 @@ object SessionPrefs {
|
||||
|
||||
fun prefMode(mode: String): String = if (mode == SessionService.MODE_RUN) SessionService.MODE_STEAM else mode
|
||||
|
||||
fun displayMode(context: Context, mode: String, program: String?): String =
|
||||
if (mode == SessionService.MODE_RUN && com.droiddeck.launcher.runtime.UserApps.launches(program) &&
|
||||
resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP
|
||||
else prefMode(mode)
|
||||
|
||||
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", false)
|
||||
|
||||
fun setPipAutoEnter(context: Context, enabled: Boolean) {
|
||||
@@ -922,6 +1011,12 @@ object SessionPrefs {
|
||||
}.apply()
|
||||
}
|
||||
|
||||
fun deckyZipWarningSeen(context: Context): Boolean = prefs(context).getBoolean(DECKY_ZIP_WARNING_SEEN, false)
|
||||
|
||||
fun setDeckyZipWarningSeen(context: Context) {
|
||||
prefs(context).edit().putBoolean(DECKY_ZIP_WARNING_SEEN, true).apply()
|
||||
}
|
||||
|
||||
fun steamDownloadsInBackground(context: Context): Boolean {
|
||||
val prefs = prefs(context)
|
||||
return prefs.getBoolean(STEAM_DOWNLOADS_IN_BACKGROUND, false) ||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
|
||||
@@ -21,6 +22,8 @@ import android.os.IBinder
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.PowerManager
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.view.Display
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
@@ -56,6 +59,7 @@ class SessionService : Service() {
|
||||
|
||||
private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>()
|
||||
private var deckBinds: List<String> = emptyList()
|
||||
private var inputSysfs: InputSysfsComponent? = null
|
||||
private val stopLock = Any()
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
private var wifiLock: WifiManager.WifiLock? = null
|
||||
@@ -73,6 +77,7 @@ class SessionService : Service() {
|
||||
* first run never gets as far as showing Steam.
|
||||
*/
|
||||
private var clientInstallActive = false
|
||||
@Volatile private var steamLibraryMounts = emptyMap<String, File>()
|
||||
private var suspendDownloadNow = false
|
||||
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
|
||||
private var steamDownloadsInBackground = false
|
||||
@@ -81,17 +86,21 @@ class SessionService : Service() {
|
||||
private var signInHold = false
|
||||
private val hasVisibleSurface get() = sessionHasVisibleSurface(activityVisible || signInHold, screenOn, xrActivityVisible)
|
||||
private var screenOn = true
|
||||
private var sessionDisplayId = Display.DEFAULT_DISPLAY
|
||||
private var manualPauseRequested = false
|
||||
private var steamSleepToken: String? = null
|
||||
private var nativeSleepToken: String? = null
|
||||
private var nativeSleepReady = false
|
||||
private var nativeSleepFallback = false
|
||||
private var nativeSleepIdle = false
|
||||
private var nativeSleepTimeout: Runnable? = null
|
||||
private var suspendOperationPending = false
|
||||
private var pipTask = false
|
||||
private var suspendAttemptFailed = false
|
||||
private var pendingSteamGameId: String? = null
|
||||
private var pendingSteamGameGeneration = -1
|
||||
// Bumped to cancel a running game-exit watch (a new launch, or the session ending).
|
||||
@Volatile private var gameExitWatchToken = 0
|
||||
private val flushSteamGame = object : Runnable {
|
||||
override fun run() = flushQueuedSteamGame()
|
||||
}
|
||||
@@ -99,8 +108,8 @@ class SessionService : Service() {
|
||||
private val screenReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
when (intent?.action) {
|
||||
Intent.ACTION_SCREEN_OFF -> screenOn = false
|
||||
Intent.ACTION_SCREEN_ON -> screenOn = true
|
||||
Intent.ACTION_SCREEN_OFF -> screenOn = readScreenOn(false)
|
||||
Intent.ACTION_SCREEN_ON -> screenOn = readScreenOn(true)
|
||||
else -> return
|
||||
}
|
||||
if (screenOn) resumeSteamSleepOnReturn()
|
||||
@@ -108,17 +117,49 @@ class SessionService : Service() {
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
}
|
||||
private var displayListenerRegistered = false
|
||||
private val displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) {}
|
||||
override fun onDisplayRemoved(displayId: Int) {
|
||||
if (displayId != sessionDisplayId) return
|
||||
sessionDisplayId = Display.DEFAULT_DISPLAY
|
||||
refreshScreenOn()
|
||||
}
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
if (displayId == sessionDisplayId && displayId != Display.DEFAULT_DISPLAY) refreshScreenOn()
|
||||
}
|
||||
}
|
||||
|
||||
private fun readScreenOn(interactive: Boolean? = null): Boolean {
|
||||
val id = sessionDisplayId
|
||||
val state = if (id == Display.DEFAULT_DISPLAY) null
|
||||
else (getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.getDisplay(id)?.state
|
||||
return sessionScreenOn(id == Display.DEFAULT_DISPLAY,
|
||||
interactive ?: (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true, state)
|
||||
}
|
||||
|
||||
private fun refreshScreenOn() {
|
||||
val on = readScreenOn()
|
||||
if (on == screenOn) return
|
||||
screenOn = on
|
||||
if (on) resumeSteamSleepOnReturn()
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
@Volatile private var sessionGen = 0
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
val power = getSystemService(Context.POWER_SERVICE) as? PowerManager
|
||||
screenOn = power?.isInteractive ?: true
|
||||
screenOn = readScreenOn()
|
||||
registerReceiver(screenReceiver, IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
})
|
||||
screenReceiverRegistered = true
|
||||
(getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.let {
|
||||
it.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
displayListenerRegistered = true
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
@@ -167,12 +208,19 @@ class SessionService : Service() {
|
||||
ACTION_ACTIVITY_VISIBLE -> {
|
||||
if (!SessionState.pipActive) pipTask = false
|
||||
activityVisible = true
|
||||
sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId)
|
||||
screenOn = readScreenOn()
|
||||
suspendDownloadNow = false
|
||||
resumeSteamSleepOnReturn()
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_ACTIVITY_DISPLAY -> {
|
||||
sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId)
|
||||
refreshScreenOn()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_ACTIVITY_HIDDEN -> {
|
||||
activityVisible = false
|
||||
suspendAttemptFailed = false
|
||||
@@ -236,7 +284,8 @@ class SessionService : Service() {
|
||||
activityVisible = true
|
||||
xrActivityVisible = false
|
||||
signInHold = false
|
||||
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true
|
||||
sessionDisplayId = intent?.getIntExtra(EXTRA_DISPLAY_ID, Display.DEFAULT_DISPLAY) ?: Display.DEFAULT_DISPLAY
|
||||
screenOn = readScreenOn()
|
||||
manualPauseRequested = false
|
||||
suspendDownloadNow = false
|
||||
steamDownloadMonitor.reset()
|
||||
@@ -270,6 +319,8 @@ class SessionService : Service() {
|
||||
val gen = ++sessionGen
|
||||
cancelQueuedSteamGame(clearMailbox = false)
|
||||
clearSteamGameMailbox()
|
||||
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl
|
||||
?.takeIf { it.startsWith(GAME_URL_PREFIX) }?.let { watchGameExit(it.removePrefix(GAME_URL_PREFIX), gen) }
|
||||
acquireLocks()
|
||||
Thread({
|
||||
OrphanReaper.reap("session starting")
|
||||
@@ -300,14 +351,13 @@ class SessionService : Service() {
|
||||
return lines
|
||||
}
|
||||
|
||||
private fun tuDebug(linuxDriverId: String): String? {
|
||||
val override = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH)
|
||||
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }
|
||||
if (!override.isNullOrEmpty()) return override
|
||||
if (SessionPrefs.tuSysmem(this)) return "sysmem"
|
||||
if (linuxDriverId.isEmpty()) return null
|
||||
private fun tuDebugOverride(): String? = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH)
|
||||
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }?.takeIf { it.isNotEmpty() }
|
||||
|
||||
private fun sysmemDriver(linuxDriverId: String): Boolean {
|
||||
if (linuxDriverId.isEmpty()) return false
|
||||
val name = LinuxVulkanDriverManager(this).getDriverName(linuxDriverId).lowercase()
|
||||
return if (name.contains("710-720") || name.contains("710_720")) "sysmem" else null
|
||||
return name.contains("710-720") || name.contains("710_720")
|
||||
}
|
||||
|
||||
|
||||
@@ -326,7 +376,9 @@ class SessionService : Service() {
|
||||
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
killStragglers()
|
||||
SessionFiles.stage(this, root)
|
||||
for (pack in listOf(AddonPack.PROOT, AddonPack.DIRECTAUDIO))
|
||||
if (!pack.await(this, { gen == sessionGen && SessionState.running })) Log.w(TAG, "${pack.name} pack unavailable")
|
||||
SessionFiles.stage(this, root, startsSession = true)
|
||||
// Earlier sessions' reports still read the Steam logs and VAC marker this session replaces.
|
||||
SessionArtifacts.awaitCollections()
|
||||
SessionArtifacts.finishAbandoned(this)
|
||||
@@ -354,6 +406,12 @@ class SessionService : Service() {
|
||||
val fastPathAt = guest.size
|
||||
|
||||
val pulse = startAudio(guest, sessionDir)
|
||||
if (steamHere) {
|
||||
val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock"))
|
||||
encoder.attach(this)
|
||||
components.add(encoder)
|
||||
guest.add("BL_VENC_SOCKET=" + encoder.socket.absolutePath)
|
||||
}
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
@@ -372,6 +430,7 @@ class SessionService : Service() {
|
||||
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
|
||||
SessionState.deckPad = false
|
||||
deckBinds = emptyList()
|
||||
inputSysfs = null
|
||||
if (controllersOn) {
|
||||
addControllerEnvironment(guest, fakeInputDir, sessionDir)
|
||||
SessionState.padBridge?.syncConnectedControllers()
|
||||
@@ -583,7 +642,9 @@ class SessionService : Service() {
|
||||
)
|
||||
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||
tuDebug(linuxDriverId)?.let { guest.add("TU_DEBUG=$it") }
|
||||
val tuOverride = tuDebugOverride()
|
||||
val tuDriver = sysmemDriver(linuxDriverId)
|
||||
(tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
|
||||
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice()?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") }
|
||||
if (SessionPrefs.zinkLazy(this)) {
|
||||
guest.add("ZINK_DESCRIPTORS=lazy")
|
||||
@@ -611,8 +672,9 @@ class SessionService : Service() {
|
||||
if (SessionState.mode == MODE_STEAM && SessionPrefs.zramCompression(this) &&
|
||||
com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
|
||||
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
|
||||
extraEnv().forEach { guest.add(it) }
|
||||
com.droiddeck.launcher.agent.AgentEnv.beginSession(this).forEach { guest.add(it) }
|
||||
val extra = extraEnv() + com.droiddeck.launcher.agent.AgentEnv.beginSession(this)
|
||||
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
|
||||
extra.forEach { guest.add(it) }
|
||||
val clientPinned = steamHere && SessionPrefs.clientCpusOverride(this)
|
||||
if (clientPinned) {
|
||||
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
|
||||
@@ -659,17 +721,23 @@ class SessionService : Service() {
|
||||
|
||||
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File, sessionDir: File) {
|
||||
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
|
||||
val builtinPad = SessionPrefs.builtinPad(this)
|
||||
val hiddenPad = SessionState.mode == MODE_STEAM && !builtinPad &&
|
||||
!com.droiddeck.launcher.input.PadBridge.anyControllerConnected()
|
||||
com.droiddeck.launcher.input.PadBridge.setFirstSlot(if (hiddenPad) 1 else 0)
|
||||
fakeInputDir.listFiles()?.forEach { file ->
|
||||
val node = Regex("event(\\d+)").matchEntire(file.name)?.groupValues?.get(1)?.toIntOrNull()
|
||||
if (file.name.startsWith(".uinput-") || (node != null && node >= FIRST_VIRTUAL_PAD)) file.delete()
|
||||
if (file.name.startsWith(".uinput-") || (node != null && node >= FIRST_VIRTUAL_PAD) ||
|
||||
(hiddenPad && node == 0)) file.delete()
|
||||
}
|
||||
guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path)
|
||||
val rings = FakeInputWriter.getRingEnv(fakeInputDir)
|
||||
if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings")
|
||||
val presented = if (hiddenPad) rings?.split(';')?.filterNot { it.startsWith("0=") }?.joinToString(";") else rings
|
||||
if (!presented.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$presented")
|
||||
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
|
||||
guest.add("FAKE_EVDEV_VIBRATION=1")
|
||||
val uinput = !File(Environment.getExternalStorageDirectory(), NO_UINPUT_SWITCH).exists()
|
||||
val wantsDeck = uinput && SessionState.mode == MODE_STEAM &&
|
||||
val wantsDeck = uinput && builtinPad && SessionState.mode == MODE_STEAM &&
|
||||
SessionState.steamUi != "desktop" &&
|
||||
!File(Environment.getExternalStorageDirectory(), NO_DECK_PAD_SWITCH).exists()
|
||||
val wantsTouch = wantsDeck && !File(Environment.getExternalStorageDirectory(), NO_STEAM_TOUCH_SWITCH).exists()
|
||||
@@ -688,6 +756,7 @@ class SessionService : Service() {
|
||||
val padType = SessionPrefs.steamController(this)
|
||||
guest.add("FAKE_EVDEV_PAD_TYPE=$padType")
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(padType))
|
||||
InputSysfsComponent.padTypeChanged(SessionPrefs.padType(padType))
|
||||
if (wantsTouch) com.droiddeck.launcher.input.SteamTouchDevice.prepare(fakeInputDir)?.let {
|
||||
guest.add("FAKE_TOUCHCTL_RING=" + it.path)
|
||||
}
|
||||
@@ -701,6 +770,9 @@ class SessionService : Service() {
|
||||
if (!SessionState.deckPad) guest.add("SDL_JOYSTICK_HIDAPI=0")
|
||||
guest.add("FAKE_EVDEV_LOG=1")
|
||||
guest.add("FAKE_EVDEV_LOG_FILE=" + File(sessionDir, "pad.log").path)
|
||||
inputSysfs = InputSysfsComponent(fakeInputDir, File(fakeInputDir.parentFile!!.parentFile!!, "sys/input"),
|
||||
File(LinuxRuntime.rootDir(this), "run/udev/data"), SessionState.deckPad, !uinput && SessionState.mode == MODE_STEAM)
|
||||
.takeIf { it.prepare() }
|
||||
SessionState.fakeInputDir = fakeInputDir
|
||||
}
|
||||
|
||||
@@ -715,6 +787,11 @@ class SessionService : Service() {
|
||||
val binds = ArrayList<String>()
|
||||
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
|
||||
if (controllersOn) binds.addAll(deckBinds)
|
||||
if (controllersOn) inputSysfs?.let {
|
||||
it.attach(this)
|
||||
components.add(it)
|
||||
binds.addAll(it.binds())
|
||||
}
|
||||
val battery = BatteryComponent(
|
||||
File(filesDir, "session/sys/power_supply"),
|
||||
File(LinuxRuntime.rootDir(this), "run/vpower"),
|
||||
@@ -750,6 +827,7 @@ class SessionService : Service() {
|
||||
File(home, "Storage").mkdirs()
|
||||
binds.add(Environment.getExternalStorageDirectory().path + ":/root/Storage")
|
||||
val library = GameStorage.effective(this)
|
||||
steamLibraryMounts = emptyMap()
|
||||
var storageDiagnosticLibrary: File? = null
|
||||
if (library != null) {
|
||||
val problem = GameStorage.prepare(this, library.path)
|
||||
@@ -761,6 +839,7 @@ class SessionService : Service() {
|
||||
val content = SecondaryLibrary.contentPath(configured)
|
||||
binds.addAll(SecondaryLibrary.binds(filesDir, configured, content = content))
|
||||
storageDiagnosticLibrary = content
|
||||
steamLibraryMounts = SecondaryLibrary.CARD_GUESTS.associateWith { content }
|
||||
val route = if (content === configured) "configured" else "verified-native"
|
||||
Log.i(TAG, "game storage: ${content.path} ($route) -> /mnt/droiddeck-sd (\"${library.label}\"); prefixes and native tools private")
|
||||
} catch (e: Exception) {
|
||||
@@ -1019,15 +1098,77 @@ class SessionService : Service() {
|
||||
pendingSteamGameId = null
|
||||
pendingSteamGameGeneration = -1
|
||||
SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen))
|
||||
watchGameExit(gameId, gen)
|
||||
Log.i(TAG, "queued Steam game $gameId for the running client")
|
||||
}
|
||||
|
||||
/**
|
||||
* A game launched from the front end (the Games tab, or another launcher's link): once it has
|
||||
* started and then been gone for [GAME_EXIT_GRACE_MS], ask the client to exit through the
|
||||
* session script's steam-stop request. The client quits cleanly, finishing its cloud sync, so
|
||||
* the session ends on its own and the activity returns to where the launch came from instead
|
||||
* of leaving the player in Big Picture. The grace covers launchers that restart the game.
|
||||
*/
|
||||
private fun watchGameExit(gameId: String, gen: Int) {
|
||||
if (!SessionPrefs.returnAfterGame(this)) return
|
||||
val token = ++gameExitWatchToken
|
||||
Thread({
|
||||
val startBy = android.os.SystemClock.elapsedRealtime() + GAME_START_TIMEOUT_MS
|
||||
var seen = false
|
||||
var goneSince = 0L
|
||||
while (token == gameExitWatchToken && gen == sessionGen && SessionState.running && !SessionState.stopRequested) {
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
if (steamGameRunning()) {
|
||||
if (!seen) Log.i(TAG, "game $gameId started; returning to the launcher when it closes")
|
||||
seen = true
|
||||
goneSince = 0L
|
||||
} else if (!seen) {
|
||||
// Never started (an install, an update or a failed launch): leave the session be.
|
||||
if (now > startBy) {
|
||||
Log.i(TAG, "game $gameId did not start; not watching for its exit")
|
||||
return@Thread
|
||||
}
|
||||
} else if (goneSince == 0L) {
|
||||
goneSince = now
|
||||
} else if (now - goneSince >= GAME_EXIT_GRACE_MS) {
|
||||
mainHandler.post { returnAfterGame(gameId, gen, token) }
|
||||
return@Thread
|
||||
}
|
||||
try { Thread.sleep(GAME_EXIT_POLL_MS) } catch (e: InterruptedException) { return@Thread }
|
||||
}
|
||||
}, "game-exit-watch").start()
|
||||
}
|
||||
|
||||
private fun returnAfterGame(gameId: String, gen: Int, token: Int) {
|
||||
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running ||
|
||||
SessionState.stopRequested || SessionState.mode != MODE_STEAM || !SessionPrefs.returnAfterGame(this)) return
|
||||
val written = runCatching { File(LinuxRuntime.sessionRoot(this), "steam-stop").writeText("") }
|
||||
.onFailure { Log.w(TAG, "could not ask the client to exit after game $gameId", it) }.isSuccess
|
||||
if (!written) return
|
||||
SessionEvents.record("steam.return_after_game", mapOf("gameId" to gameId))
|
||||
Log.i(TAG, "game $gameId closed: asking the client to exit and returning to the launcher")
|
||||
}
|
||||
|
||||
/** A Steam game is running: the client runs each one under its reaper, and Proton's script
|
||||
* waits on the game with waitforexitandrun. Read from the command lines, as ComponentsManager does. */
|
||||
private fun steamGameRunning(): Boolean {
|
||||
val procs = File("/proc").listFiles() ?: return false
|
||||
for (p in procs) {
|
||||
if (!p.name.all(Char::isDigit)) continue
|
||||
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
|
||||
if (cmd.isEmpty()) continue
|
||||
val text = String(cmd).replace('\u0000', ' ')
|
||||
if (text.contains("SteamLaunch AppId=") || text.contains("waitforexitandrun")) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun resumeSession(panelVisible: Boolean = true) {
|
||||
if (panelVisible) activityVisible = true
|
||||
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn
|
||||
screenOn = readScreenOn()
|
||||
manualPauseRequested = false
|
||||
suspendDownloadNow = false
|
||||
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback)) requestSteamWake()
|
||||
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
|
||||
completeNativeSleep()
|
||||
completeSteamSleep()
|
||||
suspendAttemptFailed = false
|
||||
@@ -1219,23 +1360,29 @@ class SessionService : Service() {
|
||||
|
||||
private fun updateSuspendPolicy() {
|
||||
if (!SessionState.running) return
|
||||
if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && !hasVisibleSurface) {
|
||||
val hidden = !hasVisibleSurface
|
||||
val downloadsBlockingSuspend = downloadsKeepAwake() && hidden && !suspendDownloadNow
|
||||
if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && hidden && !downloadsBlockingSuspend) {
|
||||
manualPauseRequested = true
|
||||
}
|
||||
val controller = suspendController ?: return
|
||||
val hidden = !hasVisibleSurface
|
||||
val downloadsBlockingSuspend = downloadsKeepAwake() && hidden && !suspendDownloadNow
|
||||
if (downloadsBlockingSuspend) acquireLocks()
|
||||
if (suspendPolicy != SessionPrefs.SUSPEND_NATIVE || !hidden || downloadsBlockingSuspend) {
|
||||
val steamPause = SessionState.mode == MODE_STEAM && !downloadsBlockingSuspend && when (suspendPolicy) {
|
||||
SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE -> hidden
|
||||
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested
|
||||
else -> false
|
||||
}
|
||||
if (!steamPause) {
|
||||
completeNativeSleep()
|
||||
} else if (nativeSleepToken == null && steamSleepToken == null &&
|
||||
!SessionState.suspended && !suspendAttemptFailed) {
|
||||
prepareNativeSleep()
|
||||
}
|
||||
val prepared = SessionState.mode != MODE_STEAM || nativeSleepReady
|
||||
val shouldSuspend = steamSleepToken != null || when (suspendPolicy) {
|
||||
SessionPrefs.SUSPEND_AUTO -> hidden && !downloadsBlockingSuspend
|
||||
SessionPrefs.SUSPEND_AUTO -> hidden && prepared && !downloadsBlockingSuspend
|
||||
SessionPrefs.SUSPEND_NATIVE -> hidden && nativeSleepReady && !downloadsBlockingSuspend
|
||||
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && !downloadsBlockingSuspend
|
||||
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && prepared && !downloadsBlockingSuspend
|
||||
else -> false
|
||||
}
|
||||
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
|
||||
@@ -1243,7 +1390,7 @@ class SessionService : Service() {
|
||||
suspendOperationPending = true
|
||||
SessionEvents.record(if (shouldSuspend) "session.suspend_requested" else "session.resume_requested", mapOf(
|
||||
"policy" to suspendPolicy, "activityVisible" to activityVisible,
|
||||
"screenOn" to screenOn, "steamSleep" to (steamSleepToken != null),
|
||||
"screenOn" to screenOn, "display" to sessionDisplayId, "steamSleep" to (steamSleepToken != null),
|
||||
"xrActivityVisible" to xrActivityVisible,
|
||||
"nativeSleep" to (nativeSleepToken != null),
|
||||
))
|
||||
@@ -1303,7 +1450,7 @@ class SessionService : Service() {
|
||||
|
||||
private fun resumeSteamSleepOnReturn() {
|
||||
if (suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) {
|
||||
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback)) requestSteamWake()
|
||||
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
|
||||
completeNativeSleep()
|
||||
completeSteamSleep()
|
||||
}
|
||||
@@ -1314,13 +1461,14 @@ class SessionService : Service() {
|
||||
nativeSleepToken = token
|
||||
nativeSleepReady = false
|
||||
nativeSleepFallback = false
|
||||
nativeSleepIdle = suspendPolicy != SessionPrefs.SUSPEND_NATIVE
|
||||
val dir = LinuxRuntime.sessionRoot(this)
|
||||
runCatching {
|
||||
val staged = File(dir, "steam-native-sleep.tmp")
|
||||
staged.writeText("$token\n")
|
||||
staged.writeText(if (nativeSleepIdle) "$token idle\n" else "$token\n")
|
||||
check(staged.renameTo(File(dir, "steam-native-sleep")))
|
||||
}.onFailure { Log.w(TAG, "could not request Native sleep; using timed pause", it) }
|
||||
SessionEvents.record("steam.native_sleep_requested")
|
||||
SessionEvents.record("steam.native_sleep_requested", mapOf("idle" to nativeSleepIdle))
|
||||
val gen = sessionGen
|
||||
val timeout = Runnable {
|
||||
if (gen != sessionGen || !SessionState.running || nativeSleepToken != token) return@Runnable
|
||||
@@ -1346,6 +1494,7 @@ class SessionService : Service() {
|
||||
nativeSleepToken = null
|
||||
nativeSleepReady = false
|
||||
nativeSleepFallback = false
|
||||
nativeSleepIdle = false
|
||||
}
|
||||
|
||||
private fun requestSteamWake() {
|
||||
@@ -1412,6 +1561,7 @@ class SessionService : Service() {
|
||||
|
||||
private fun stopSession(status: Int) {
|
||||
cancelQueuedSteamGame()
|
||||
gameExitWatchToken++
|
||||
completeNativeSleep()
|
||||
val (ended, endedArch) = synchronized(stopLock) {
|
||||
if (!SessionState.running) return
|
||||
@@ -1486,7 +1636,6 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
if (rootIntent?.component?.className == com.droiddeck.launcher.ui.SecondScreenActivity::class.java.name) return
|
||||
if (pipTask || xrActivityVisible) {
|
||||
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
|
||||
activityVisible = false
|
||||
@@ -1505,6 +1654,10 @@ class SessionService : Service() {
|
||||
unregisterReceiver(screenReceiver)
|
||||
screenReceiverRegistered = false
|
||||
}
|
||||
if (displayListenerRegistered) {
|
||||
(getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.unregisterDisplayListener(displayListener)
|
||||
displayListenerRegistered = false
|
||||
}
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -1662,6 +1815,7 @@ class SessionService : Service() {
|
||||
root,
|
||||
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
|
||||
client = SessionState.steamClientArch,
|
||||
mounts = steamLibraryMounts,
|
||||
)
|
||||
if (wasInstalling != clientInstallActive) {
|
||||
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
|
||||
@@ -1683,13 +1837,16 @@ class SessionService : Service() {
|
||||
pads.add(String.format(java.util.Locale.ROOT, "\"%s\" (%04x:%04x)", d.name, d.vendorId, d.productId))
|
||||
}
|
||||
Log.i(TAG, "controllers at start: " + (if (pads.isEmpty()) "none" else pads.joinToString(", ")) +
|
||||
"; presented to the guest as " + if (SessionState.deckPad) "switchable, starting as " + SessionPrefs.steamController(this) else "an Xbox 360 controller")
|
||||
"; presented to the guest as " + if (SessionState.deckPad) "switchable, starting as " + SessionPrefs.steamController(this)
|
||||
else if (SessionState.mode == MODE_STEAM && !SessionPrefs.builtinPad(this)) "one per connected controller, no built-in pad"
|
||||
else "an Xbox 360 controller")
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val TRACER_NICE = -6
|
||||
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
|
||||
private const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
|
||||
private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env"
|
||||
private const val ENV_SWITCH_NAME = "droiddeck-env"
|
||||
|
||||
@@ -1709,6 +1866,8 @@ class SessionService : Service() {
|
||||
private const val ACTION_SUSPEND_POLICY_CHANGED = "com.droiddeck.launcher.SUSPEND_POLICY_CHANGED"
|
||||
private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE"
|
||||
private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN"
|
||||
private const val ACTION_ACTIVITY_DISPLAY = "com.droiddeck.launcher.ACTIVITY_DISPLAY"
|
||||
private const val EXTRA_DISPLAY_ID = "displayId"
|
||||
private const val ACTION_XR_ACTIVITY_VISIBLE = "com.droiddeck.launcher.XR_ACTIVITY_VISIBLE"
|
||||
private const val ACTION_XR_ACTIVITY_HIDDEN = "com.droiddeck.launcher.XR_ACTIVITY_HIDDEN"
|
||||
private const val ACTION_SIGN_IN_HOLD = "com.droiddeck.launcher.SIGN_IN_HOLD"
|
||||
@@ -1725,6 +1884,12 @@ class SessionService : Service() {
|
||||
private const val GAME_LAUNCH_RETRY_MS = 250L
|
||||
private const val DOWNLOAD_POLL_MS = 2_000L
|
||||
private const val STEAM_GAME_REQUEST = "steam-game"
|
||||
private const val GAME_URL_PREFIX = "steam://rungameid/"
|
||||
/** How long a front-end launch may take to start (downloads, first-run installs) before the exit watch gives up. */
|
||||
private const val GAME_START_TIMEOUT_MS = 20 * 60_000L
|
||||
/** How long the game must stay gone before the client is asked to exit: launchers restart games. */
|
||||
private const val GAME_EXIT_GRACE_MS = 10_000L
|
||||
private const val GAME_EXIT_POLL_MS = 2_000L
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
private const val NO_UINPUT_SWITCH = "Download/droiddeck-no-uinput"
|
||||
private const val NO_DECK_PAD_SWITCH = "Download/droiddeck-no-deck-pad"
|
||||
@@ -1745,8 +1910,10 @@ class SessionService : Service() {
|
||||
fun start(
|
||||
context: Context, mode: String = MODE_STEAM, program: String? = null,
|
||||
steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null,
|
||||
displayId: Int = Display.DEFAULT_DISPLAY,
|
||||
) {
|
||||
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
|
||||
.putExtra(EXTRA_DISPLAY_ID, displayId)
|
||||
if (program != null) intent.putExtra(EXTRA_PROGRAM, program)
|
||||
if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs)
|
||||
if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi)
|
||||
@@ -1767,10 +1934,15 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PIP_BEGIN))
|
||||
}
|
||||
|
||||
fun setActivityVisible(context: Context, visible: Boolean) {
|
||||
fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = Display.DEFAULT_DISPLAY) {
|
||||
if (!SessionState.running) return
|
||||
val action = if (visible) ACTION_ACTIVITY_VISIBLE else ACTION_ACTIVITY_HIDDEN
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(action))
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(action).putExtra(EXTRA_DISPLAY_ID, displayId))
|
||||
}
|
||||
|
||||
fun setActivityDisplay(context: Context, displayId: Int) {
|
||||
if (!SessionState.running) return
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY).putExtra(EXTRA_DISPLAY_ID, displayId))
|
||||
}
|
||||
|
||||
fun setXrActivityVisible(context: Context, visible: Boolean) {
|
||||
|
||||
@@ -2,14 +2,22 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import android.os.Process
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
|
||||
internal class SessionSuspendController(
|
||||
private val sessionRoot: () -> Int,
|
||||
private val helperRoots: () -> List<Int>,
|
||||
private val suspendAudio: () -> Unit,
|
||||
private val resumeAudio: () -> Unit,
|
||||
private val procRoot: File = File("/proc"),
|
||||
private val signal: (Int, Int) -> Unit = Process::sendSignal,
|
||||
private val threadSignal: (Int, Int, Int) -> Unit = { pid, tid, signal -> ThreadSignals.tgkill(pid, tid, signal) },
|
||||
private val sleep: (Long) -> Unit = Thread::sleep,
|
||||
private val nowMillis: () -> Long = { System.nanoTime() / 1_000_000 },
|
||||
private val executor: ExecutorService = Executors.newSingleThreadExecutor(),
|
||||
) {
|
||||
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
|
||||
|
||||
@@ -24,96 +32,95 @@ internal class SessionSuspendController(
|
||||
val parent: Int,
|
||||
val started: Long,
|
||||
val state: Char,
|
||||
val tracer: Int,
|
||||
)
|
||||
|
||||
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
|
||||
private data class TaskIdentity(val process: ProcessRecord, val tid: Int, val started: Long)
|
||||
|
||||
@Volatile private var closing = false
|
||||
private var frozen = emptyList<ProcessRecord>()
|
||||
|
||||
fun freeze(completion: (Boolean) -> Unit) {
|
||||
submit {
|
||||
if (closing) {
|
||||
completion(false)
|
||||
return@submit
|
||||
}
|
||||
if (frozen.isNotEmpty()) {
|
||||
val fullyFrozen = frozen.any { it.role == Role.SESSION_ROOT } && frozen.all(::isStoppedOrGone)
|
||||
if (!fullyFrozen && restore(frozen)) frozen = emptyList()
|
||||
completion(fullyFrozen)
|
||||
return@submit
|
||||
}
|
||||
val records = LinkedHashMap<Pair<Int, Long>, ProcessRecord>()
|
||||
val root = sessionRoot()
|
||||
if (root <= 1) {
|
||||
completion(false)
|
||||
return@submit
|
||||
}
|
||||
runAudio(suspendAudio)
|
||||
val helpers = helperRoots().filter { it > 1 && it != root }.distinct()
|
||||
var stablePasses = 0
|
||||
submit({
|
||||
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
|
||||
var complete = false
|
||||
repeat(10) { pass ->
|
||||
if (closing) {
|
||||
restore(records.values.toList())
|
||||
runAudio(resumeAudio)
|
||||
completion(false)
|
||||
return@submit
|
||||
var interrupted = false
|
||||
try {
|
||||
val root = records.values.firstOrNull { it.role == Role.SESSION_ROOT }
|
||||
?: readProcess(sessionRoot())?.takeIf { it.pid > 1 }?.let {
|
||||
ProcessRecord(it.pid, it.started, Role.SESSION_ROOT)
|
||||
} ?: throw IOException("Session root is unavailable")
|
||||
records[root.pid to root.started] = root
|
||||
runAudio(suspendAudio)
|
||||
val helpers = helperRoots().filter { it > 1 && it != root.pid }.distinct()
|
||||
for (helper in helpers) {
|
||||
if (records.values.any { it.pid == helper && it.role == Role.HELPER_ROOT }) continue
|
||||
readProcess(helper)?.let {
|
||||
records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT)
|
||||
}
|
||||
}
|
||||
val includeRoots = pass >= 2
|
||||
addSnapshot(records, root, helpers, includeRoots)
|
||||
stop(records.values.toList(), includeRoots)
|
||||
Thread.sleep(if (pass == 0) 70L else 35L)
|
||||
val rootCaptured = records.values.any { it.role == Role.SESSION_ROOT }
|
||||
if (rootCaptured && records.isNotEmpty() && records.values.all(::isStoppedOrGone)) {
|
||||
stablePasses++
|
||||
if (stablePasses >= 2) complete = true
|
||||
} else {
|
||||
stablePasses = 0
|
||||
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
|
||||
var previous: Map<TaskIdentity, Long>? = null
|
||||
for (pass in 0 until FREEZE_MAX_PASSES) {
|
||||
if (closing || nowMillis() >= deadline) break
|
||||
try {
|
||||
if (readProcess(root.pid)?.started != root.started) break
|
||||
addSnapshot(records, root.pid, helpers)
|
||||
if (readProcess(root.pid)?.started != root.started) break
|
||||
stop(records.values.toList())
|
||||
sleep(if (pass == 0) 70L else 35L)
|
||||
if (closing || nowMillis() >= deadline) break
|
||||
val current = stoppedSnapshot(records.values.toList(), root)
|
||||
if (current != null && current == previous) {
|
||||
complete = true
|
||||
break
|
||||
}
|
||||
previous = current
|
||||
} catch (_: IOException) {
|
||||
previous = null
|
||||
sleep(35L)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (complete) {
|
||||
} catch (_: InterruptedException) {
|
||||
interrupted = true
|
||||
Thread.interrupted()
|
||||
} catch (_: Exception) {
|
||||
} finally {
|
||||
frozen = records.values.toList()
|
||||
completion(true)
|
||||
} else {
|
||||
val restored = restore(records.values.toList())
|
||||
runAudio(resumeAudio)
|
||||
if (!restored) frozen = records.values.toList()
|
||||
completion(false)
|
||||
if (!complete) {
|
||||
if (restoreSafely(frozen)) frozen = emptyList()
|
||||
runAudio(resumeAudio)
|
||||
}
|
||||
if (interrupted) Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
completion(complete)
|
||||
}, { completion(false) })
|
||||
}
|
||||
|
||||
fun resume(completion: (Boolean) -> Unit) {
|
||||
submit {
|
||||
submit({
|
||||
val records = frozen
|
||||
runAudio(resumeAudio)
|
||||
val resumed = restore(records)
|
||||
val resumed = restoreSafely(records)
|
||||
if (resumed) frozen = emptyList()
|
||||
completion(resumed)
|
||||
}
|
||||
}, { completion(false) })
|
||||
}
|
||||
|
||||
fun closeAndResume(completion: () -> Unit) {
|
||||
closing = true
|
||||
submit {
|
||||
restore(frozen)
|
||||
frozen = emptyList()
|
||||
submit({
|
||||
if (restoreSafely(frozen)) frozen = emptyList()
|
||||
completion()
|
||||
executor.shutdown()
|
||||
}
|
||||
}, completion)
|
||||
}
|
||||
|
||||
private fun submit(task: () -> Unit) {
|
||||
private fun submit(task: () -> Unit, rejected: () -> Unit) {
|
||||
try {
|
||||
executor.execute {
|
||||
try {
|
||||
task()
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
} catch (_: RuntimeException) {
|
||||
task()
|
||||
executor.execute(task)
|
||||
} catch (_: RejectedExecutionException) {
|
||||
rejected()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,23 +135,25 @@ internal class SessionSuspendController(
|
||||
records: MutableMap<Pair<Int, Long>, ProcessRecord>,
|
||||
root: Int,
|
||||
helpers: List<Int>,
|
||||
includeRoots: Boolean,
|
||||
) {
|
||||
val processes = readProcesses()
|
||||
val byPid = processes.associateBy { it.pid }
|
||||
for (process in descendants(root, processes, byPid)) {
|
||||
records[process.pid to process.started] = ProcessRecord(process.pid, process.started, Role.SESSION_CHILD)
|
||||
val rootRecord = records.values.first { it.role == Role.SESSION_ROOT }
|
||||
if (byPid[root]?.started != rootRecord.started) throw IOException("Session root exited or changed")
|
||||
val liveHelpers = helpers.filter { pid ->
|
||||
records.values.any { it.pid == pid && it.role == Role.HELPER_ROOT && it.started == byPid[pid]?.started }
|
||||
}
|
||||
for (helper in helpers) {
|
||||
for (process in descendants(root, processes, byPid) + processes.filter { it.tracer == root }) {
|
||||
records.putIfAbsent(process.pid to process.started, ProcessRecord(process.pid, process.started, Role.SESSION_CHILD))
|
||||
}
|
||||
for (helper in liveHelpers) {
|
||||
for (process in descendants(helper, processes, byPid)) {
|
||||
records[process.pid to process.started] = ProcessRecord(process.pid, process.started, Role.HELPER_CHILD)
|
||||
records.putIfAbsent(process.pid to process.started, ProcessRecord(process.pid, process.started, Role.HELPER_CHILD))
|
||||
}
|
||||
}
|
||||
if (includeRoots) {
|
||||
byPid[root]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.SESSION_ROOT) }
|
||||
for (helper in helpers) {
|
||||
byPid[helper]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT) }
|
||||
}
|
||||
byPid[root]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.SESSION_ROOT) }
|
||||
for (helper in liveHelpers) {
|
||||
byPid[helper]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,36 +177,84 @@ internal class SessionSuspendController(
|
||||
}
|
||||
|
||||
private fun readProcesses(): List<ProcessInfo> =
|
||||
File("/proc").listFiles().orEmpty().mapNotNull { entry ->
|
||||
(procRoot.listFiles() ?: throw IOException("Cannot enumerate processes")).mapNotNull { entry ->
|
||||
val pid = entry.name.toIntOrNull() ?: return@mapNotNull null
|
||||
readProcess(pid)
|
||||
try { readProcess(pid) } catch (_: IOException) { null }
|
||||
}
|
||||
|
||||
private fun readProcess(pid: Int): ProcessInfo? {
|
||||
val stat = try {
|
||||
File("/proc/$pid/stat").readText()
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
}
|
||||
val close = stat.lastIndexOf(')')
|
||||
if (close < 0 || close + 2 >= stat.length) return null
|
||||
val fields = stat.substring(close + 2).trim().split(Regex("\\s+"))
|
||||
if (fields.size < 20) return null
|
||||
return try {
|
||||
ProcessInfo(pid, fields[1].toInt(), fields[19].toLong(), fields[0].first())
|
||||
} catch (_: NumberFormatException) {
|
||||
null
|
||||
val base = File(procRoot, pid.toString())
|
||||
try {
|
||||
val fields = readStat(File(base, "stat"))
|
||||
val tracer = File(base, "status").useLines { lines ->
|
||||
lines.firstOrNull { it.startsWith("TracerPid:") }?.substringAfter(':')?.trim()?.toIntOrNull() ?: 0
|
||||
}
|
||||
return ProcessInfo(pid, fields[1].toInt(), fields[19].toLong(), fields[0].first(), tracer)
|
||||
} catch (error: IOException) {
|
||||
if (procRoot.list()?.contains(pid.toString()) == false) return null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private fun stop(records: List<ProcessRecord>, includeRoots: Boolean) {
|
||||
val descendants = records.filter { it.role == Role.SESSION_CHILD || it.role == Role.HELPER_CHILD }
|
||||
val session = records.filter { it.role == Role.SESSION_ROOT }
|
||||
val helpers = records.filter { it.role == Role.HELPER_ROOT }
|
||||
for (record in descendants) send(record, SIGSTOP)
|
||||
if (includeRoots) {
|
||||
for (record in session) send(record, SIGSTOP)
|
||||
for (record in helpers) send(record, SIGSTOP)
|
||||
private fun readStat(file: File): List<String> {
|
||||
val stat = file.readText()
|
||||
val close = stat.lastIndexOf(')')
|
||||
if (close < 0 || close + 2 >= stat.length) throw IOException("Invalid process stat: $file")
|
||||
val fields = stat.substring(close + 2).trim().split(Regex("\\s+"))
|
||||
if (fields.size < 20) throw IOException("Incomplete process stat: $file")
|
||||
return fields
|
||||
}
|
||||
|
||||
private fun stoppedSnapshot(records: List<ProcessRecord>, root: ProcessRecord): Map<TaskIdentity, Long>? {
|
||||
// PRoot can leave the leader stopped while native worker threads keep running.
|
||||
val tasks = LinkedHashMap<TaskIdentity, Long>()
|
||||
var stopped = true
|
||||
for (record in records) {
|
||||
val current = readProcess(record.pid)
|
||||
if (current == null || current.started != record.started) {
|
||||
if (record == root) throw IOException("Session root exited or changed")
|
||||
continue
|
||||
}
|
||||
val entries = File(procRoot, "${record.pid}/task").listFiles()
|
||||
?: throw IOException("Cannot enumerate threads: ${record.pid}")
|
||||
if (entries.none { it.name.toIntOrNull() != null }) throw IOException("Empty thread inventory: ${record.pid}")
|
||||
var liveRoot = false
|
||||
for (entry in entries) {
|
||||
val tid = entry.name.toIntOrNull() ?: continue
|
||||
val fields = readStat(File(entry, "stat"))
|
||||
val state = fields[0].first()
|
||||
if (state != 'Z' && state != 'X') liveRoot = true
|
||||
if (state != 'T' && state != 't' && state != 'Z' && state != 'X') stopped = false
|
||||
tasks[TaskIdentity(record, tid, fields[19].toLong())] = fields[11].toLong() + fields[12].toLong()
|
||||
}
|
||||
if (record == root && !liveRoot) throw IOException("Session root has no live threads")
|
||||
if (readProcess(record.pid)?.started != record.started) throw IOException("Process changed during inspection")
|
||||
}
|
||||
return tasks.takeIf { stopped && it.isNotEmpty() }
|
||||
}
|
||||
|
||||
// PRoot traces every guest. A stop sent while it runs becomes a group stop that it restarts
|
||||
// thread by thread; once it is stopped, each thread that takes a SIGSTOP stays parked in its
|
||||
// signal-delivery stop. So the roots stop first and every guest thread gets its own SIGSTOP.
|
||||
private fun stop(records: List<ProcessRecord>) {
|
||||
for (record in records.filter { it.role == Role.SESSION_ROOT }) send(record, SIGSTOP)
|
||||
for (record in records.filter { it.role == Role.HELPER_ROOT }) send(record, SIGSTOP)
|
||||
for (record in records.filter { it.role == Role.SESSION_CHILD || it.role == Role.HELPER_CHILD }) {
|
||||
stopThreads(record)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopThreads(record: ProcessRecord) {
|
||||
val current = try { readProcess(record.pid) } catch (_: Exception) { return }
|
||||
if (current == null || current.started != record.started) return
|
||||
for (entry in File(procRoot, "${record.pid}/task").listFiles().orEmpty()) {
|
||||
val tid = entry.name.toIntOrNull() ?: continue
|
||||
val state = try { readStat(File(entry, "stat"))[0].first() } catch (_: IOException) { continue }
|
||||
if (state == 'T' || state == 't' || state == 'Z' || state == 'X') continue
|
||||
try {
|
||||
threadSignal(record.pid, tid, SIGSTOP)
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,7 +270,7 @@ internal class SessionSuspendController(
|
||||
for (record in ordered) send(record, SIGCONT)
|
||||
val waiting = ordered.toMutableList()
|
||||
repeat(RESTORE_CHECKS) { check ->
|
||||
Thread.sleep(25L)
|
||||
sleep(25L)
|
||||
waiting.removeAll { isRunningOrGone(it) }
|
||||
if (waiting.isEmpty()) return true
|
||||
if (check % 8 == 7) for (record in waiting) send(record, SIGCONT)
|
||||
@@ -221,30 +278,40 @@ internal class SessionSuspendController(
|
||||
return false
|
||||
}
|
||||
|
||||
private fun restoreSafely(records: List<ProcessRecord>): Boolean = try {
|
||||
restore(records)
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
false
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
|
||||
private fun send(record: ProcessRecord, signal: Int) {
|
||||
val current = readProcess(record.pid) ?: return
|
||||
if (current.started != record.started) return
|
||||
val current = try { readProcess(record.pid) } catch (_: Exception) { return }
|
||||
if (current == null || current.started != record.started) return
|
||||
try {
|
||||
Process.sendSignal(record.pid, signal)
|
||||
this.signal(record.pid, signal)
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun isStoppedOrGone(record: ProcessRecord): Boolean {
|
||||
val current = readProcess(record.pid) ?: return true
|
||||
if (current.started != record.started) return true
|
||||
return current.state == 'T' || current.state == 't' || current.state == 'Z' || current.state == 'X'
|
||||
}
|
||||
|
||||
private fun isRunningOrGone(record: ProcessRecord): Boolean {
|
||||
val current = readProcess(record.pid) ?: return true
|
||||
if (current.started != record.started) return true
|
||||
return current.state != 'T' && current.state != 't'
|
||||
val current = try { readProcess(record.pid) } catch (_: Exception) { return false }
|
||||
if (current == null || current.started != record.started) return true
|
||||
if (current.state == 'T' || current.state == 't') return false
|
||||
// A traced worker in 't' is usually PRoot handling a system call; 'T' is a job-control stop.
|
||||
return File(procRoot, "${record.pid}/task").listFiles().orEmpty().none { entry ->
|
||||
entry.name.toIntOrNull() != null &&
|
||||
try { readStat(File(entry, "stat"))[0].first() == 'T' } catch (_: IOException) { false }
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SIGSTOP = 19
|
||||
const val SIGCONT = 18
|
||||
const val RESTORE_CHECKS = 80
|
||||
const val FREEZE_TIMEOUT_MS = 8_000L
|
||||
const val FREEZE_MAX_PASSES = 256
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.view.Display
|
||||
|
||||
internal fun sessionHasVisibleSurface(panelVisible: Boolean, screenOn: Boolean, xrVisible: Boolean): Boolean =
|
||||
xrVisible || (panelVisible && screenOn)
|
||||
|
||||
internal fun sessionScreenOn(onDefaultDisplay: Boolean, interactive: Boolean, displayState: Int?): Boolean =
|
||||
if (onDefaultDisplay || displayState == null || displayState == Display.STATE_UNKNOWN) interactive
|
||||
else displayState == Display.STATE_ON || displayState == Display.STATE_VR || displayState == Display.STATE_ON_SUSPEND
|
||||
@@ -13,7 +13,8 @@ object SettingsReset {
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"hud", "hudDeck", "backActionsInverted", "touch", "osc", "shape", "steamController",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "stretch16x9", "picturePosition",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime",
|
||||
@@ -21,7 +22,8 @@ object SettingsReset {
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
"questDefaultsV1",
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
class SteamClientSetupFailure(val curlError: String?) {
|
||||
val download get() = curlError != null
|
||||
|
||||
companion object {
|
||||
const val MARKER = "== steam: the Steam client could not be set up"
|
||||
private const val STEP = "checking the Steam client"
|
||||
private const val X64_STEP = "checking the x86-64 Steam client"
|
||||
private val CURL_ERROR = Regex("""curl: \(\d+\).*""")
|
||||
|
||||
fun find(lines: Sequence<String>): SteamClientSetupFailure? {
|
||||
var curlError: String? = null
|
||||
var found: SteamClientSetupFailure? = null
|
||||
lines.forEach { line ->
|
||||
when {
|
||||
line.contains(STEP) || line.contains(X64_STEP) -> {
|
||||
curlError = null
|
||||
found = null
|
||||
}
|
||||
line.contains(MARKER) -> found = SteamClientSetupFailure(curlError)
|
||||
else -> CURL_ERROR.find(line)?.let { curlError = it.value.trim() }
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
/** steamdeckrepo.com's public boot video list, the same one its website and its own manager app read. */
|
||||
object SteamDeckRepo {
|
||||
private const val TAG = "SteamDeckRepo"
|
||||
const val BASE = "https://steamdeckrepo.com"
|
||||
|
||||
/** The site shows twelve movies a page. */
|
||||
const val PAGE_SIZE = 12
|
||||
const val MAX_DOWNLOAD_BYTES = 120L shl 20
|
||||
private const val MAX_JSON_BYTES = 1 shl 20
|
||||
private const val USER_AGENT = "DroidDeck (+https://github.com/Droid-Deck/DroidDeck)"
|
||||
private const val CACHE_MS = 10 * 60 * 1000L
|
||||
|
||||
enum class Sort(val key: String) {
|
||||
TRENDING("trending"), DOWNLOADS("downloads-desc"), LIKES("likes-desc"), NEWEST("created_at-desc"),
|
||||
}
|
||||
|
||||
/** `null` is every device. */
|
||||
val DEVICES = listOf("steam_deck", "steam_machine")
|
||||
|
||||
class Post(
|
||||
val id: String, val title: String, val content: String, val author: String, val thumbnail: String, val video: String,
|
||||
val seconds: Int, val likes: Int, val downloads: Int, val devices: List<String>, val url: String,
|
||||
)
|
||||
|
||||
sealed class Page {
|
||||
class Ok(val posts: List<Post>) : Page()
|
||||
object Failed : Page()
|
||||
}
|
||||
|
||||
/** The text of [key], empty when it is missing or JSON null, which `optString` would turn into the word "null". */
|
||||
private fun JSONObject.text(key: String): String = if (isNull(key)) "" else optString(key)
|
||||
|
||||
fun parse(json: String): List<Post>? {
|
||||
val array = runCatching { JSONObject(json).optJSONArray("posts") }.getOrNull() ?: return null
|
||||
val out = ArrayList<Post>()
|
||||
for (i in 0 until array.length()) {
|
||||
val o = array.optJSONObject(i) ?: continue
|
||||
val id = o.text("id")
|
||||
val video = o.text("video")
|
||||
if (id.isEmpty() || !video.startsWith("https://")) continue
|
||||
val devices = o.optJSONArray("devices")?.let { d -> (0 until d.length()).map { d.optString(it) } }.orEmpty()
|
||||
out.add(
|
||||
Post(
|
||||
id = id, title = o.text("title").ifBlank { id }, content = o.text("content"),
|
||||
author = o.optJSONObject("user")?.text("steam_name").orEmpty(),
|
||||
thumbnail = o.text("thumbnail").takeIf { it.startsWith("https://") }.orEmpty(), video = video,
|
||||
seconds = o.optInt("video_duration"), likes = o.optInt("likes"), downloads = o.optInt("downloads"),
|
||||
devices = devices, url = o.text("url"),
|
||||
),
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun url(sort: Sort, device: String?, search: String, page: Int = 1): String {
|
||||
val query = StringBuilder("sort=").append(sort.key)
|
||||
if (device != null) query.append("&device=").append(URLEncoder.encode(device, "UTF-8"))
|
||||
val term = search.trim()
|
||||
if (term.isNotEmpty()) query.append("&search=").append(URLEncoder.encode(term, "UTF-8").replace("+", "%20"))
|
||||
if (page > 1) query.append("&page=").append(page)
|
||||
return "$BASE/api/posts?$query"
|
||||
}
|
||||
|
||||
private class Cached(val at: Long, val page: Page.Ok)
|
||||
private val cache = HashMap<String, Cached>()
|
||||
|
||||
fun fetch(sort: Sort, device: String?, search: String, page: Int = 1, now: Long = System.currentTimeMillis()): Page {
|
||||
val url = url(sort, device, search, page)
|
||||
synchronized(cache) { cache[url]?.takeIf { now - it.at < CACHE_MS }?.let { return it.page } }
|
||||
val body = get(url) ?: return Page.Failed
|
||||
val posts = parse(body) ?: return Page.Failed
|
||||
val result = Page.Ok(posts.take(PAGE_SIZE))
|
||||
synchronized(cache) { cache[url] = Cached(now, result) }
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of the last page for a search, found by asking for pages: the site does not say how many there are, but a
|
||||
* page past the end is empty and the last one is short. Null when the site cannot be reached.
|
||||
*/
|
||||
fun lastPage(sort: Sort, device: String?, search: String, cap: Int = 512, count: (Int) -> Int? = { p ->
|
||||
(fetch(sort, device, search, p) as? Page.Ok)?.posts?.size
|
||||
}): Int? {
|
||||
val first = count(1) ?: return null
|
||||
if (first < PAGE_SIZE) return 1
|
||||
var good = 1
|
||||
var bad = -1
|
||||
var probe = 2
|
||||
while (probe <= cap) {
|
||||
val n = count(probe) ?: return null
|
||||
if (n == 0) { bad = probe; break }
|
||||
if (n < PAGE_SIZE) return probe
|
||||
good = probe
|
||||
probe *= 2
|
||||
}
|
||||
if (bad < 0) return good
|
||||
while (bad - good > 1) {
|
||||
val mid = (good + bad) / 2
|
||||
val n = count(mid) ?: return null
|
||||
if (n == 0) bad = mid else if (n < PAGE_SIZE) return mid else good = mid
|
||||
}
|
||||
return good
|
||||
}
|
||||
|
||||
/** Reads [input] to its end, or null as soon as it holds more than [limit] bytes, so a huge answer is never kept whole. */
|
||||
internal fun readLimited(input: java.io.InputStream, limit: Int): ByteArray? {
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
if (out.size() + n > limit) return null
|
||||
out.write(buffer, 0, n)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
private fun get(url: String): String? {
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
connection = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 20_000
|
||||
setRequestProperty("User-Agent", USER_AGENT)
|
||||
setRequestProperty("Accept", "application/json")
|
||||
}
|
||||
if (connection.responseCode !in 200..299) null else connection.inputStream.use { readLimited(it, MAX_JSON_BYTES)?.toString(Charsets.UTF_8) }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "request failed: ${e.javaClass.simpleName}")
|
||||
null
|
||||
} finally {
|
||||
runCatching { connection?.disconnect() }
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetches a small picture such as a cover; null when it cannot be had. */
|
||||
fun bytes(url: String, limit: Int = 4 shl 20): ByteArray? {
|
||||
if (!url.startsWith("https://")) return null
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
connection = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 20_000
|
||||
setRequestProperty("User-Agent", USER_AGENT)
|
||||
}
|
||||
if (connection.responseCode !in 200..299 || connection.contentLengthLong > limit) null
|
||||
else connection.inputStream.use { input -> readLimited(input, limit)?.takeIf { it.isNotEmpty() } }
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
} finally {
|
||||
runCatching { connection?.disconnect() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads a movie to [target] through the site's own download address, so the site counts it like a download from
|
||||
* its website, and falls back to the video's address. True when a file was saved.
|
||||
*/
|
||||
fun download(post: Post, target: File, onProgress: (Int) -> Unit = {}): Boolean {
|
||||
for (url in listOf("$BASE/post/download/${post.id}", post.video)) {
|
||||
if (save(url, target, onProgress)) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun save(url: String, target: File, onProgress: (Int) -> Unit): Boolean {
|
||||
var connection: HttpURLConnection? = null
|
||||
val staged = File(target.parentFile, target.name + ".part")
|
||||
return try {
|
||||
target.parentFile?.mkdirs()
|
||||
connection = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 30_000
|
||||
instanceFollowRedirects = true
|
||||
setRequestProperty("User-Agent", USER_AGENT)
|
||||
}
|
||||
if (connection.responseCode !in 200..299) return false
|
||||
val type = connection.contentType.orEmpty().lowercase()
|
||||
if (type.startsWith("text/") || type.contains("json")) return false
|
||||
val total = connection.contentLengthLong
|
||||
if (total > MAX_DOWNLOAD_BYTES) return false
|
||||
var done = 0L
|
||||
var lastPercent = -1
|
||||
connection.inputStream.use { input ->
|
||||
staged.outputStream().use { output ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
done += n
|
||||
if (done > MAX_DOWNLOAD_BYTES) return false
|
||||
output.write(buffer, 0, n)
|
||||
if (total > 0) {
|
||||
val percent = (done * 100 / total).toInt()
|
||||
if (percent != lastPercent) { lastPercent = percent; onProgress(percent) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
done > 0 && (total <= 0 || done == total) && staged.renameTo(target)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "download failed: ${e.javaClass.simpleName}")
|
||||
false
|
||||
} finally {
|
||||
runCatching { connection?.disconnect() }
|
||||
staged.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,9 @@ internal class SteamDownloadMonitor {
|
||||
private var lastReceivedBytes = -1L
|
||||
private var lastReceivedAt = 0L
|
||||
|
||||
fun poll(runtimeRoot: File, now: Long = System.currentTimeMillis(), receivedBytes: Long = -1L, client: String? = null): Boolean {
|
||||
val current = manifests(runtimeRoot).associate { it.path to read(it) }
|
||||
fun poll(runtimeRoot: File, now: Long = System.currentTimeMillis(), receivedBytes: Long = -1L, client: String? = null,
|
||||
mounts: Map<String, File> = emptyMap()): Boolean {
|
||||
val current = manifests(runtimeRoot, mounts).associate { it.path to read(it) }
|
||||
val progressed = current.any { (path, state) ->
|
||||
state.incomplete && state.bytesDownloaded > (previous[path]?.bytesDownloaded ?: state.bytesDownloaded)
|
||||
}
|
||||
@@ -98,7 +99,7 @@ internal class SteamDownloadMonitor {
|
||||
now - lastContentActivityAt <= CONTENT_ACTIVITY_GRACE_MS
|
||||
}
|
||||
|
||||
private fun manifests(runtimeRoot: File): List<File> {
|
||||
private fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
|
||||
val steamRoots = linkedSetOf<File>()
|
||||
for (home in STEAM_HOMES) {
|
||||
val primary = File(runtimeRoot, home)
|
||||
@@ -106,7 +107,7 @@ internal class SteamDownloadMonitor {
|
||||
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
|
||||
runCatching {
|
||||
PATH.findAll(libraryFolders.readText()).forEach { match ->
|
||||
steamRoots += File(runtimeRoot, match.groupValues[1].removePrefix("/"))
|
||||
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,6 +118,15 @@ internal class SteamDownloadMonitor {
|
||||
}
|
||||
}
|
||||
|
||||
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
|
||||
val path = guest.trimEnd('/')
|
||||
for ((mount, host) in mounts) {
|
||||
if (path == mount) return host
|
||||
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
|
||||
}
|
||||
return File(runtimeRoot, path.removePrefix("/"))
|
||||
}
|
||||
|
||||
private fun read(file: File): ManifestState {
|
||||
val text = runCatching { file.readText() }.getOrDefault("")
|
||||
val flags = value(text, "StateFlags")?.toLongOrNull() ?: 0L
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
internal object ThreadSignals {
|
||||
init {
|
||||
System.loadLibrary("sdnative")
|
||||
}
|
||||
|
||||
@JvmStatic external fun tgkill(tgid: Int, tid: Int, signal: Int): Int
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
|
||||
/** Steam's Remote Play V4L2 encoder in the guest talks to this MediaCodec encoder (venc.c, venc_server.cpp). */
|
||||
class VideoEncodeBridge(val socket: File) : SessionPart() {
|
||||
override fun start() {
|
||||
socket.parentFile?.mkdirs()
|
||||
val ok = runCatching { System.loadLibrary("ddvenc"); nativeStart(socket.absolutePath) }
|
||||
.onFailure { Log.w(TAG, "hardware video encoding unavailable", it) }
|
||||
.getOrDefault(false)
|
||||
Log.i(TAG, if (ok) "Remote Play hardware encoding on at $socket" else "Remote Play hardware encoding off")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
runCatching { nativeStop() }
|
||||
socket.delete()
|
||||
}
|
||||
|
||||
private external fun nativeStart(path: String): Boolean
|
||||
private external fun nativeStop()
|
||||
|
||||
private companion object {
|
||||
const val TAG = "VideoEncodeBridge"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user