mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-26 16:22:53 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
17b578b7cf | ||
|
|
0d82557957 |
No files matched your search
@@ -171,6 +171,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var zramClient by mutableStateOf(true)
|
||||
private var vramCapMb by mutableStateOf(0)
|
||||
private var gpuClockPin by mutableStateOf(false)
|
||||
private var performanceBoost by mutableStateOf(false)
|
||||
private var boostCheck by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var prootFastPath by mutableStateOf(true)
|
||||
private var cursorComposite by mutableStateOf(false)
|
||||
@@ -2242,6 +2244,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
fsyncFirst = fsyncFirst,
|
||||
gamescopeRealtime = gamescopeRealtime,
|
||||
gpuClockPin = gpuClockPin,
|
||||
performanceBoost = performanceBoost, boostCheck = boostCheck,
|
||||
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient,
|
||||
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
|
||||
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
|
||||
@@ -2259,6 +2262,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
|
||||
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
|
||||
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
|
||||
onPerformanceBoost = { on -> SessionPrefs.setPerformanceBoost(this, on); performanceBoost = on },
|
||||
onBoostCheck = { on -> SessionPrefs.setBoostCheck(this, on); boostCheck = on },
|
||||
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
|
||||
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
|
||||
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
|
||||
@@ -2475,6 +2480,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
zramClient = SessionPrefs.zramClient(this)
|
||||
vramCapMb = SessionPrefs.vramCapMb(this)
|
||||
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
||||
performanceBoost = SessionPrefs.performanceBoost(this)
|
||||
boostCheck = SessionPrefs.boostCheck(this)
|
||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||
prootFastPath = SessionPrefs.prootFastPath(this)
|
||||
cursorComposite = SessionPrefs.cursorComposite(this)
|
||||
|
||||
@@ -0,0 +1,485 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.CpuCores
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* What the Performance boost did in a session, in boost.log in the session folder and in the app log:
|
||||
* whether each part (GameThreadHints, SamsungPerf) came on and can be seen working, a status line
|
||||
* every [STATUS_S] seconds of play with why a part is off, and a summary with a verdict when the
|
||||
* session ends. Play is time the game presents frames.
|
||||
*
|
||||
* With "Check the boost" on, the boost is on and paused in [WINDOW_S]-second windows of play in the
|
||||
* order on, paused, paused, on, so the frame rate with and without it is compared over the same
|
||||
* stretch of game, and a steady change such as the phone warming up favours neither side. The first
|
||||
* [WARMUP_S] seconds of play (loading, shader compiles) and the first [SETTLE_S] seconds after each
|
||||
* switch are not counted. Seconds the boost should be on but is held back for heat or battery saver
|
||||
* are counted as [Side.heldBack]; too many and there is no verdict. Seconds it is off because the
|
||||
* game keeps up without it are counted as [Side.idle]; if that is most of its turns, the boost is
|
||||
* not needed for the game.
|
||||
*/
|
||||
object BoostReport {
|
||||
private const val TAG = "BoostReport"
|
||||
private const val STATUS_S = 30
|
||||
internal const val WARMUP_S = 60
|
||||
internal const val WINDOW_S = 60
|
||||
internal const val SETTLE_S = 5
|
||||
internal const val CHECK_MIN_S = 120 // counted seconds on each side before there is a verdict
|
||||
internal const val TOO_HOT = "too hot"
|
||||
internal const val BATTERY_SAVER = "battery saver"
|
||||
internal const val KEEPS_UP = "game keeps up"
|
||||
private const val CONFIRM_S = 2 // held this long before the clocks are compared
|
||||
private const val SAMPLES = 5
|
||||
private const val SAMPLE_MS = 200L
|
||||
private const val RAISED = 1.1
|
||||
private val THERMAL = listOf("none", "light", "moderate", "severe", "critical", "emergency", "shutdown")
|
||||
private val GPU_MIN_FILES = listOf(
|
||||
"/sys/class/kgsl/kgsl-3d0/devfreq/min_freq",
|
||||
"/sys/class/kgsl/kgsl-3d0/min_clock_mhz",
|
||||
"/sys/kernel/gpu/gpu_min_clock",
|
||||
)
|
||||
|
||||
/** True while Check the boost has the boost paused; GameThreadHints and SamsungPerf let go meanwhile. */
|
||||
@Volatile var paused = false
|
||||
private set
|
||||
|
||||
/** Seconds of play on one side of a comparison. */
|
||||
internal class Side {
|
||||
val fps = ArrayList<Int>()
|
||||
val milliamps = ArrayList<Int>()
|
||||
var hottest = 0
|
||||
/** Seconds the boost should have been on but was held back for heat or battery saver. */
|
||||
var heldBack = 0
|
||||
/** Seconds the boost could have been on but was off because the game kept up without it. */
|
||||
var idle = 0
|
||||
val seconds get() = fps.size
|
||||
val average get() = if (fps.isEmpty()) 0.0 else fps.average()
|
||||
/** The frame rate of the slowest 5 % of seconds. */
|
||||
val low get() = if (fps.isEmpty()) 0 else fps.sorted()[fps.size / 20]
|
||||
val draw get() = if (milliamps.isEmpty()) null else milliamps.average()
|
||||
|
||||
fun add(f: Int, ma: Int?, thermal: Int, held: Boolean = false, idle: Boolean = false) {
|
||||
fps.add(f)
|
||||
ma?.let { milliamps.add(it) }
|
||||
hottest = maxOf(hottest, thermal)
|
||||
if (held) heldBack++
|
||||
if (idle) this.idle++
|
||||
}
|
||||
}
|
||||
|
||||
/** The CPU a thread last ran on: field 39 of /proc/<tid>/stat. */
|
||||
internal fun processorOf(stat: String): Int? =
|
||||
stat.substringAfterLast(')').trim().split(' ').getOrNull(36)?.toIntOrNull()
|
||||
|
||||
/** Each core's class by top speed: 2 the fastest, 0 the slowest, 1 between. */
|
||||
internal fun tiers(maxGhz: Map<Int, Double>): Map<Int, Int> {
|
||||
val top = maxGhz.values.maxOrNull() ?: return emptyMap()
|
||||
val bottom = maxGhz.values.minOrNull() ?: top
|
||||
return maxGhz.mapValues { (_, ghz) -> if (ghz >= top) 2 else if (ghz <= bottom) 0 else 1 }
|
||||
}
|
||||
|
||||
internal fun minutesForVerdict(): Int {
|
||||
val counted = IntArray(2)
|
||||
var played = 0
|
||||
while (counted.any { it < CHECK_MIN_S }) {
|
||||
val (pause, at) = checkWindow(++played) ?: continue
|
||||
if (at >= SETTLE_S) counted[if (pause) 1 else 0]++
|
||||
}
|
||||
return (played + 59) / 60
|
||||
}
|
||||
|
||||
/**
|
||||
* Where second [played] of play falls in the check: null in the warm-up, else whether the boost is
|
||||
* paused and the seconds since it last switched. One window on, then two paused, two on, and so on.
|
||||
*/
|
||||
internal fun checkWindow(played: Int): Pair<Boolean, Int>? {
|
||||
if (played <= WARMUP_S) return null
|
||||
val n = played - WARMUP_S - 1
|
||||
if (n < WINDOW_S) return false to n
|
||||
val m = n - WINDOW_S
|
||||
return (m / (2 * WINDOW_S) % 2 == 0) to m % (2 * WINDOW_S)
|
||||
}
|
||||
|
||||
/** Why neither part boosts now, from what each says (Samsung's only where the phone has its service). */
|
||||
internal fun offReasons(cores: String?, samsung: String?): String =
|
||||
listOfNotNull(cores, samsung).distinct().joinToString().ifEmpty { "no reason given" }
|
||||
|
||||
/** Seconds a part was off, by reason, most first. */
|
||||
internal fun offTimes(off: Map<String, Int>): String =
|
||||
off.entries.sortedByDescending { it.value }.joinToString { "${clock(it.value)} ${it.key}" }
|
||||
|
||||
/** From Check the boost: whether the boost made the game faster where it matters. */
|
||||
internal fun verdict(on: Side, off: Side): String {
|
||||
if (on.seconds > 0 && on.heldBack * 4 > on.seconds) {
|
||||
return "can't tell: the phone was too hot or saving battery for ${share(on.heldBack, on.seconds)} of the time " +
|
||||
"the boost should have been on, so it was off then; try again with the phone cool and not charging"
|
||||
}
|
||||
if (on.seconds < CHECK_MIN_S || off.seconds < CHECK_MIN_S) {
|
||||
return "too short to tell: play at least ${minutesForVerdict()} minutes with Check the boost on"
|
||||
}
|
||||
if (off.average < 1) return "unclear: the game showed no frames while the boost was paused"
|
||||
if (on.idle * 2 > on.seconds) {
|
||||
return "not needed for this game: it kept up without the boost for ${share(on.idle, on.seconds)} of the boost's turns, " +
|
||||
"so the boost was seldom on (${"%.1f".format(Locale.US, on.average)} fps in its turns, ${"%.1f".format(Locale.US, off.average)} fps paused)"
|
||||
}
|
||||
val gain = on.average / off.average - 1
|
||||
val lowGain = if (off.low > 0) on.low.toDouble() / off.low - 1 else 0.0
|
||||
val onDraw = on.draw
|
||||
val offDraw = off.draw
|
||||
val cost = if (onDraw != null && offDraw != null && offDraw > 0) ", for ${percent(onDraw / offDraw - 1)} battery draw" else ""
|
||||
val numbers = "${percent(gain)} fps on average, ${percent(lowGain)} in the slowest moments$cost"
|
||||
return when {
|
||||
gain >= 0.05 || lowGain >= 0.10 -> "worth keeping: $numbers"
|
||||
gain <= 0.02 && lowGain <= 0.05 -> "not worth keeping for this game: $numbers"
|
||||
else -> "unclear, a small gain: $numbers"
|
||||
}
|
||||
}
|
||||
|
||||
private fun percent(x: Double) = (if (x >= 0) "+" else "") + (x * 100).roundToInt() + " %"
|
||||
|
||||
private class Run(val file: File, val check: Boolean) {
|
||||
var started = false
|
||||
var played = 0
|
||||
var lastFrames = -1L
|
||||
val boosted = Side()
|
||||
val unboosted = Side()
|
||||
val checkOn = Side()
|
||||
val checkOff = Side()
|
||||
val recent = ArrayList<Int>()
|
||||
var coresBoosted = 0
|
||||
val onTier = IntArray(3)
|
||||
val recentTier = IntArray(3)
|
||||
var samsungHeld = 0
|
||||
val coresOff = LinkedHashMap<String, Int>()
|
||||
val samsungOff = LinkedHashMap<String, Int>()
|
||||
var heldFor = 0
|
||||
var cpuBefore = emptyMap<String, Long>()
|
||||
var gpuBefore: Long? = null
|
||||
var cpuRaised: Map<String, Pair<Long, Long>>? = null
|
||||
var gpuRaised = false
|
||||
var clocks: String? = null
|
||||
var fallen = false
|
||||
var drops = 0
|
||||
var batteryStart: Int? = null
|
||||
var batteryEnd: Int? = null
|
||||
var firstFrameMs = 0L
|
||||
var lastFrameMs = 0L
|
||||
var charging = false
|
||||
var hottest = 0
|
||||
val samsungTries = SamsungPerf.tries
|
||||
var samsungFailures = 0
|
||||
}
|
||||
|
||||
private val letGoCounts = LinkedHashMap<String, Int>()
|
||||
private var run: Run? = null
|
||||
private var worker: Thread? = null
|
||||
|
||||
/** SamsungPerf let go of its floors, and why. */
|
||||
fun letGo(why: String) {
|
||||
synchronized(letGoCounts) { letGoCounts[why] = (letGoCounts[why] ?: 0) + 1 }
|
||||
}
|
||||
|
||||
/** At a session's start, after the boost's parts. The line is for the log. */
|
||||
@Synchronized
|
||||
fun start(context: Context, dir: File): String {
|
||||
stop()
|
||||
synchronized(letGoCounts) { letGoCounts.clear() }
|
||||
if (!SessionPrefs.performanceBoost(context)) return "boost report: off"
|
||||
val r = Run(File(dir, "boost.log"), SessionPrefs.boostCheck(context))
|
||||
run = r
|
||||
val soc = if (Build.VERSION.SDK_INT >= 31) ", ${Build.SOC_MANUFACTURER} ${Build.SOC_MODEL}" else ""
|
||||
line(r, "Performance boost report: ${Build.MANUFACTURER} ${Build.MODEL}, Android ${Build.VERSION.RELEASE}$soc; " +
|
||||
"Check the boost ${if (r.check) "on" else "off"}. Play is time the game shows frames.")
|
||||
val app = context.applicationContext
|
||||
worker = Thread({ watch(app, r) }, "boost-report").apply { isDaemon = true; start() }
|
||||
return "boost report: ${r.file}"
|
||||
}
|
||||
|
||||
/** At a session's end: the summary. */
|
||||
@Synchronized
|
||||
fun stop() {
|
||||
val r = run ?: return
|
||||
run = null
|
||||
worker?.let { it.interrupt(); it.join(2000) }
|
||||
worker = null
|
||||
paused = false
|
||||
runCatching { summary(r) }.onFailure { Log.w(TAG, "summary", it) }
|
||||
}
|
||||
|
||||
private fun line(r: Run, text: String) {
|
||||
Log.i(TAG, text)
|
||||
val clock = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
|
||||
runCatching { r.file.appendText("$clock $text\n") }
|
||||
}
|
||||
|
||||
private fun watch(context: Context, r: Run) {
|
||||
val pm = context.getSystemService(PowerManager::class.java)
|
||||
val bm = context.getSystemService(BatteryManager::class.java)
|
||||
val tiers = tiers(CpuCores.all.associateWith { CpuCores.maxGhz(it) ?: 0.0 })
|
||||
val gpuFile = GPU_MIN_FILES.map(::File).firstOrNull { readLong(it) != null }
|
||||
try {
|
||||
while (!Thread.currentThread().isInterrupted) {
|
||||
Thread.sleep(1000)
|
||||
second(r, pm, bm, tiers, gpuFile)
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "stopped", t)
|
||||
} finally {
|
||||
paused = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun second(r: Run, pm: PowerManager, bm: BatteryManager?, tiers: Map<Int, Int>, gpuFile: File?) {
|
||||
val frames = WaylandCompositor.gameFrameCount()
|
||||
val fps = if (r.lastFrames < 0) 0 else (frames - r.lastFrames).toInt()
|
||||
r.lastFrames = frames
|
||||
watchClocks(r, gpuFile)
|
||||
val failed = r.samsungTries.failed
|
||||
while (r.samsungFailures < failed.size) {
|
||||
val n = ++r.samsungFailures
|
||||
line(r, "Samsung clocks: try $n of ${SamsungPerf.TRIES} to connect failed: ${failed[n - 1]}; ${SamsungPerf.retryNote(n)}")
|
||||
}
|
||||
if (fps < 1) return
|
||||
if (!r.started) {
|
||||
r.started = true
|
||||
r.batteryStart = battery(bm)
|
||||
r.firstFrameMs = System.currentTimeMillis()
|
||||
line(r, "the game shows frames; fastest cores: ${GameThreadHints.startLine.removePrefix("game thread hints: ")}; " +
|
||||
"Samsung clocks: ${SamsungPerf.state}")
|
||||
if (r.check) line(r, "check: starts after the first $WARMUP_S s of play, so loading is not counted")
|
||||
}
|
||||
r.played++
|
||||
val thermal = if (Build.VERSION.SDK_INT >= 29) pm.currentThermalStatus else 0
|
||||
r.hottest = maxOf(r.hottest, thermal)
|
||||
val ma = milliamps(bm)
|
||||
if (bm?.isCharging == true) r.charging = true
|
||||
r.batteryEnd = battery(bm)
|
||||
r.lastFrameMs = System.currentTimeMillis()
|
||||
|
||||
val threads = GameThreadHints.boostedThreads
|
||||
val samsung = SamsungPerf.holding
|
||||
(if (samsung || threads.isNotEmpty()) r.boosted else r.unboosted).add(fps, ma, thermal)
|
||||
if (samsung) r.samsungHeld++
|
||||
// A part switching on or off can be read between its two fields, with no reason yet: not counted.
|
||||
val coresWhy = GameThreadHints.offWhy
|
||||
val samsungWhy = SamsungPerf.offWhy.takeIf { SamsungPerf.connected }
|
||||
if (threads.isEmpty() && coresWhy != null) r.coresOff[coresWhy] = (r.coresOff[coresWhy] ?: 0) + 1
|
||||
if (!samsung && samsungWhy != null) r.samsungOff[samsungWhy] = (r.samsungOff[samsungWhy] ?: 0) + 1
|
||||
val off = if (samsung || threads.isNotEmpty()) null else offReasons(coresWhy, samsungWhy)
|
||||
val reasons = listOfNotNull(coresWhy, samsungWhy)
|
||||
val held = off != null && reasons.any { it == TOO_HOT || it == BATTERY_SAVER }
|
||||
val idle = off != null && !held && reasons.any { it == KEEPS_UP }
|
||||
|
||||
val window = if (r.check) checkWindow(r.played) else null
|
||||
if (window != null) {
|
||||
val (pause, at) = window
|
||||
if (at == 0) {
|
||||
paused = pause
|
||||
val span = if (r.played <= WARMUP_S + WINDOW_S) WINDOW_S else 2 * WINDOW_S
|
||||
line(r, "check: boost ${if (pause) "paused" else "on"} for $span s")
|
||||
}
|
||||
if (at >= SETTLE_S) (if (pause) r.checkOff else r.checkOn).add(fps, ma, thermal, held && !pause, idle && !pause)
|
||||
}
|
||||
if (threads.isNotEmpty()) {
|
||||
r.coresBoosted++
|
||||
for (tid in threads) {
|
||||
val tier = readText(File("/proc/$tid/stat"))?.let(::processorOf)?.let { tiers[it] } ?: continue
|
||||
r.onTier[tier]++
|
||||
r.recentTier[tier]++
|
||||
}
|
||||
}
|
||||
r.recent.add(fps)
|
||||
if (r.played % STATUS_S == 0) {
|
||||
status(r, threads.size, samsung, off, thermal, bm, ma)
|
||||
r.recent.clear()
|
||||
r.recentTier.fill(0)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether Samsung's floors show in the kernel's minimum speeds, and whether they stay there. */
|
||||
private fun watchClocks(r: Run, gpuFile: File?) {
|
||||
if (!SamsungPerf.holding) {
|
||||
r.heldFor = 0
|
||||
r.fallen = false
|
||||
r.cpuBefore = cpuMins()
|
||||
r.gpuBefore = gpuFile?.let(::readLong)
|
||||
return
|
||||
}
|
||||
r.heldFor++
|
||||
if (r.heldFor == CONFIRM_S && r.clocks == null) {
|
||||
val (now, gpuNow) = peakMins(gpuFile)
|
||||
val raised = now.filter { (policy, khz) -> r.cpuBefore[policy]?.let { khz > it * RAISED } == true }
|
||||
r.cpuRaised = raised.mapValues { (policy, khz) -> r.cpuBefore.getValue(policy) to khz }
|
||||
val cpu = when {
|
||||
now.isEmpty() -> "the CPU's minimum speed can't be read on this phone"
|
||||
raised.isEmpty() -> "the CPU's minimum speed did not change (${mhz(now)})"
|
||||
else -> "CPU minimum speed raised: " + r.cpuRaised!!.entries.joinToString { (policy, ba) ->
|
||||
"$policy ${ba.first / 1000} -> ${ba.second / 1000} MHz"
|
||||
}
|
||||
}
|
||||
val gpuThen = r.gpuBefore
|
||||
r.gpuRaised = gpuNow != null && gpuThen != null && gpuNow > gpuThen * RAISED
|
||||
val gpu = when {
|
||||
gpuNow == null || gpuThen == null -> "the GPU's minimum speed can't be read on this phone"
|
||||
r.gpuRaised -> "GPU minimum raised $gpuThen -> $gpuNow (${gpuFile?.path})"
|
||||
else -> "the GPU's minimum speed did not change ($gpuNow, ${gpuFile?.path})"
|
||||
}
|
||||
r.clocks = "$cpu; $gpu; the memory bus can't be seen from an app"
|
||||
line(r, "Samsung clocks held: library answered ${SamsungPerf.lastResults}; ${r.clocks}")
|
||||
}
|
||||
val raised = r.cpuRaised
|
||||
if (r.heldFor > CONFIRM_S && !raised.isNullOrEmpty()) {
|
||||
val now = cpuMins()
|
||||
val fell = raised.any { (policy, ba) -> now[policy]?.let { it < (ba.first + ba.second) / 2 } == true }
|
||||
if (fell && !r.fallen) {
|
||||
r.drops++
|
||||
line(r, "Samsung clocks let go early: the CPU minimum speed fell back (${mhz(now)}) while DroidDeck still asks for it")
|
||||
} else if (!fell && r.fallen) {
|
||||
line(r, "Samsung clocks: the CPU minimum speed is back up (${mhz(now)})")
|
||||
}
|
||||
r.fallen = fell
|
||||
}
|
||||
}
|
||||
|
||||
private fun status(r: Run, threads: Int, samsung: Boolean, off: String?, thermal: Int, bm: BatteryManager?, ma: Int?) {
|
||||
val state = when {
|
||||
paused -> "paused for the check"
|
||||
off == null -> "on"
|
||||
else -> "off now: $off"
|
||||
}
|
||||
val checks = r.recentTier.sum()
|
||||
val cores = if (threads == 0) "no threads" + because(GameThreadHints.offWhy) else "$threads threads" +
|
||||
if (checks > 0) ", on the fastest cores ${r.recentTier[2] * 100 / checks} % of checks" else ""
|
||||
val battery = battery(bm)?.let { "$it %" + (ma?.let { m -> ", $m mA" } ?: "") + if (bm?.isCharging == true) ", charging" else "" } ?: "unknown"
|
||||
line(r, "status: boost $state; fastest cores: $cores; Samsung clocks: ${if (samsung) "held" else "not held" + because(SamsungPerf.offWhy)}; " +
|
||||
"CPU minimum ${mhz(cpuMins())}; game ${r.recent.average().roundToInt()} fps, slowest second ${r.recent.minOrNull() ?: 0}; " +
|
||||
"heat ${THERMAL.getOrElse(thermal) { "$thermal" }}; battery $battery")
|
||||
}
|
||||
|
||||
private fun summary(r: Run) {
|
||||
if (!r.started) {
|
||||
line(r, "summary: the game never showed frames, nothing to report")
|
||||
return
|
||||
}
|
||||
val all = Side().apply { (r.boosted.fps + r.unboosted.fps).forEach { add(it, null, 0) } }
|
||||
line(r, "summary: ${clock(r.played)} of play")
|
||||
val checks = r.onTier.sum()
|
||||
line(r, "fastest cores: ${GameThreadHints.startLine.removePrefix("game thread hints: ")}; boosted ${share(r.coresBoosted, r.played)} of play" +
|
||||
(if (checks > 0) "; boosted threads were on the fastest cores in ${share(r.onTier[2], checks)} of checks, " +
|
||||
"middle ${share(r.onTier[1], checks)}, slowest ${share(r.onTier[0], checks)}" else "") +
|
||||
(if (GameThreadHints.refused > 0) "; Android refused a hint session ${GameThreadHints.refused} times" else "") +
|
||||
(if (r.coresOff.isNotEmpty()) "; off ${offTimes(r.coresOff)}" else ""))
|
||||
val counts = synchronized(letGoCounts) { letGoCounts.entries.joinToString { "${it.value}x ${it.key}" } }
|
||||
line(r, "Samsung clocks: ${SamsungPerf.state}; held ${share(r.samsungHeld, r.played)} of play; " +
|
||||
"${r.clocks ?: "never held long enough to look at the clocks"}; let go early ${r.drops} times" +
|
||||
(if (counts.isNotEmpty()) "; DroidDeck let go: $counts" else "") +
|
||||
(if (r.samsungOff.isNotEmpty()) "; off ${offTimes(r.samsungOff)}" else ""))
|
||||
val failed = r.samsungTries.failed
|
||||
if (failed.isNotEmpty()) {
|
||||
line(r, "Samsung clocks: ${failed.size} of ${SamsungPerf.TRIES} tries to connect failed: " +
|
||||
failed.mapIndexed { i, why -> "${i + 1}) $why" }.joinToString("; ") +
|
||||
if (SamsungPerf.connected) "; connected after that" else "")
|
||||
}
|
||||
line(r, "game: ${all.average.roundToInt()} fps average, slowest 5 % of seconds ${all.low}; " +
|
||||
"boosted ${r.boosted.average.roundToInt()} fps for ${clock(r.boosted.seconds)}, not boosted ${r.unboosted.average.roundToInt()} fps for ${clock(r.unboosted.seconds)} " +
|
||||
"(not a fair comparison: the boost runs when the game falls behind)")
|
||||
val start = r.batteryStart
|
||||
val end = r.batteryEnd
|
||||
val spanS = ((r.lastFrameMs - r.firstFrameMs) / 1000).toInt()
|
||||
val battery = when {
|
||||
r.charging -> "charging, not measured"
|
||||
start == null || end == null -> "unknown"
|
||||
else -> "$start % -> $end % over ${clock(spanS)}" + if (spanS >= 300) ", ${(start - end) * 3600 / spanS} % an hour" else ""
|
||||
}
|
||||
line(r, "heat: hottest ${THERMAL.getOrElse(r.hottest) { "${r.hottest}" }}; battery: $battery")
|
||||
if (r.check) {
|
||||
line(r, "check: counted ${clock(r.checkOn.seconds)} with the boost on and ${clock(r.checkOff.seconds)} paused (first $WARMUP_S s of play and first $SETTLE_S s after each switch skipped)")
|
||||
line(r, "check, boost on: ${side(r.checkOn)}")
|
||||
line(r, "check, paused: ${side(r.checkOff)}")
|
||||
line(r, "verdict: ${verdict(r.checkOn, r.checkOff)}")
|
||||
} else {
|
||||
line(r, "verdict: ${working(r)}. Turn on Check the boost for one game to see whether it is worth keeping.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun working(r: Run): String {
|
||||
val start = GameThreadHints.startLine
|
||||
val cores = when {
|
||||
start != "game thread hints: watching" -> "fastest cores not on (${start.removePrefix("game thread hints: ")})"
|
||||
r.coresBoosted == 0 && GameThreadHints.refused > 0 -> "fastest cores refused by Android"
|
||||
r.coresBoosted == 0 -> "fastest cores never on (${mostly(r.coresOff, r.played)})"
|
||||
else -> "fastest cores working"
|
||||
}
|
||||
val samsung = when {
|
||||
SamsungPerf.state.startsWith("not available") -> "Samsung clocks not available on this phone"
|
||||
!SamsungPerf.connected && r.samsungTries.failed.isNotEmpty() ->
|
||||
"Samsung clocks could not connect (${r.samsungTries.failed.last()})"
|
||||
r.samsungHeld == 0 -> "Samsung clocks never on (${mostly(r.samsungOff, r.played)})"
|
||||
r.drops > 0 -> "Samsung clocks working, but Samsung let go early ${r.drops} times"
|
||||
r.cpuRaised.isNullOrEmpty() && !r.gpuRaised -> "Samsung clocks asked for, but the phone shows no raised speed"
|
||||
else -> "Samsung clocks working and stayed on"
|
||||
}
|
||||
return "$cores; $samsung"
|
||||
}
|
||||
|
||||
private fun because(why: String?) = why?.let { " ($it)" } ?: ""
|
||||
|
||||
/** The reason a part was off longest, and for how long. */
|
||||
private fun mostly(off: Map<String, Int>, played: Int) =
|
||||
off.maxByOrNull { it.value }?.let { "${it.key} ${clock(it.value)} of ${clock(played)}" } ?: "no reason given"
|
||||
|
||||
private fun side(s: Side) = "${"%.1f".format(Locale.US, s.average)} fps, slowest 5 % ${s.low}" +
|
||||
(s.draw?.let { ", battery ${it.roundToInt()} mA" } ?: "") + ", hottest ${THERMAL.getOrElse(s.hottest) { "${s.hottest}" }}" +
|
||||
(if (s.heldBack > 0) ", held back for heat or battery saver ${share(s.heldBack, s.seconds)}" else "") +
|
||||
(if (s.idle > 0) ", off because the game kept up ${share(s.idle, s.seconds)}" else "")
|
||||
|
||||
private fun share(part: Int, whole: Int) = if (whole == 0) "0 %" else "${part * 100 / whole} %"
|
||||
|
||||
private fun clock(seconds: Int) = "%d:%02d".format(seconds / 60, seconds % 60)
|
||||
|
||||
private fun mhz(mins: Map<String, Long>) = if (mins.isEmpty()) "unknown" else mins.values.joinToString("/") { "${it / 1000}" } + " MHz"
|
||||
|
||||
/** The highest CPU and GPU minimums over [SAMPLES] readings [SAMPLE_MS] apart, so a floor between two renewals is still seen. */
|
||||
private fun peakMins(gpuFile: File?): Pair<Map<String, Long>, Long?> {
|
||||
val cpu = LinkedHashMap<String, Long>()
|
||||
var gpu: Long? = null
|
||||
repeat(SAMPLES) { i ->
|
||||
if (i > 0) Thread.sleep(SAMPLE_MS)
|
||||
cpuMins().forEach { (policy, khz) -> cpu[policy] = maxOf(cpu[policy] ?: 0L, khz) }
|
||||
gpuFile?.let(::readLong)?.let { g -> gpu = maxOf(gpu ?: 0L, g) }
|
||||
}
|
||||
return cpu to gpu
|
||||
}
|
||||
|
||||
/** Each CPU policy's minimum speed in kHz, as the kernel holds it now. */
|
||||
private fun cpuMins(): Map<String, Long> =
|
||||
File("/sys/devices/system/cpu/cpufreq").listFiles { f -> f.name.startsWith("policy") }.orEmpty()
|
||||
.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 }
|
||||
.mapNotNull { p -> readLong(File(p, "scaling_min_freq"))?.let { p.name to it } }
|
||||
.toMap()
|
||||
|
||||
private fun battery(bm: BatteryManager?): Int? =
|
||||
bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)?.takeIf { it in 0..100 }
|
||||
|
||||
private fun milliamps(bm: BatteryManager?): Int? {
|
||||
val raw = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW) ?: return null
|
||||
if (raw == 0L || raw == Long.MIN_VALUE) return null
|
||||
return (abs(BatteryComponent.toMicroamps(raw)) / 1000).toInt()
|
||||
}
|
||||
|
||||
private fun readText(f: File): String? = try { f.readText() } catch (_: Exception) { null }
|
||||
|
||||
private fun readLong(f: File): Long? = readText(f)?.trim()?.toLongOrNull()
|
||||
}
|
||||
@@ -36,6 +36,9 @@ import kotlin.math.abs
|
||||
* under 90 fps against 2-7% unboosted. A game with no frames (Factorio's benchmark, a loading screen)
|
||||
* or one falling behind the panel is boosted; one holding pace keeps what it has for [PACE_LEAVE_S]
|
||||
* seconds and is then let go.
|
||||
*
|
||||
* Part of the Performance boost switch, on by default only where it was measured ([measuredHere]).
|
||||
* Another phone's HAL may boost differently, or not at all.
|
||||
*/
|
||||
object GameThreadHints {
|
||||
private const val TAG = "GameThreadHints"
|
||||
@@ -46,21 +49,38 @@ object GameThreadHints {
|
||||
private const val LEAVE = 0.15 // a capped game's main thread idles to ~30% on a prime core; under 0.3 it hopped back and forth
|
||||
private const val MAX_THREADS = 2 // one per prime core; a third would be sped up in place instead
|
||||
private const val TOP_PROCESSES = 3
|
||||
private const val PACE_WINDOW_S = 3
|
||||
private const val PACE_LEAVE_S = 10
|
||||
internal const val PACE_WINDOW_S = 3
|
||||
internal const val PACE_LEAVE_S = 10
|
||||
private const val PACE_TOLERANCE = 0.08
|
||||
|
||||
/** Busy, but not the game: the app itself and the Steam client, whose UI would otherwise hold the prime cores. */
|
||||
private val NOT_GAMES = setOf("steam", "steamwebhelper")
|
||||
|
||||
/** The Odin 3 (CQ8725S), where the boost was measured. */
|
||||
val measuredHere: Boolean get() = Build.VERSION.SDK_INT >= 31 && Build.SOC_MODEL == "CQ8725S"
|
||||
|
||||
private var worker: Thread? = null
|
||||
|
||||
/** For BoostReport: the last start line, the threads boosted now, why none is, and hint sessions refused. */
|
||||
@Volatile internal var startLine = "game thread hints: off"
|
||||
@Volatile internal var boostedThreads = emptySet<Int>()
|
||||
@Volatile internal var offWhy: String? = null
|
||||
@Volatile internal var refused = 0
|
||||
|
||||
/** At a session's start. The line is for the log. */
|
||||
@Synchronized
|
||||
fun start(context: Context): String {
|
||||
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
|
||||
// Measured on the Odin 3 (CQ8725S) only; another HAL may boost differently, or not at all.
|
||||
if (Build.VERSION.SDK_INT < 31 || Build.SOC_MODEL != "CQ8725S") return "game thread hints: Odin 3 only"
|
||||
offWhy = "starting"
|
||||
return begin(context).also {
|
||||
startLine = it
|
||||
if (it != "game thread hints: watching") offWhy = it.removePrefix("game thread hints: ")
|
||||
}
|
||||
}
|
||||
|
||||
private fun begin(context: Context): String {
|
||||
refused = 0
|
||||
if (!SessionPrefs.performanceBoost(context)) return "game thread hints: off"
|
||||
if (Build.VERSION.SDK_INT < 31) return "game thread hints: needs Android 12"
|
||||
val hm = context.getSystemService(PerformanceHintManager::class.java)
|
||||
?: return "game thread hints: no PerformanceHintManager"
|
||||
val pm = context.getSystemService(PowerManager::class.java)
|
||||
@@ -92,10 +112,16 @@ object GameThreadHints {
|
||||
val fps = (frames.last() - frames.first()).toDouble() / (frames.size - 1).coerceAtLeast(1)
|
||||
val paced = frames.size > PACE_WINDOW_S && holdsPace(fps, SessionState.refreshHz.toDouble())
|
||||
pacedFor = if (paced) pacedFor + 1 else 0
|
||||
// Not SEVERE: the Odin 3 reports it once its skin reaches 50 C, a couple of minutes into any game.
|
||||
val spare = pm.isPowerSaveMode || pm.currentThermalStatus >= PowerManager.THERMAL_STATUS_CRITICAL
|
||||
val spare = when {
|
||||
BoostReport.paused -> "check pause"
|
||||
pm.isPowerSaveMode -> BoostReport.BATTERY_SAVER
|
||||
// Not SEVERE: the Odin 3 reports it once its skin reaches 50 C, a couple of minutes into any game.
|
||||
pm.currentThermalStatus >= PowerManager.THERMAL_STATUS_CRITICAL -> BoostReport.TOO_HOT
|
||||
pacedFor >= PACE_LEAVE_S -> BoostReport.KEEPS_UP
|
||||
else -> null
|
||||
}
|
||||
val next = when {
|
||||
spare || pacedFor >= PACE_LEAVE_S -> emptySet()
|
||||
spare != null -> emptySet()
|
||||
paced -> pick(boosted, busy.filterKeys { it in boosted })
|
||||
else -> pick(boosted, busy)
|
||||
}
|
||||
@@ -103,10 +129,12 @@ object GameThreadHints {
|
||||
session = update(hm, session, next)
|
||||
// No session means a thread exited in between: tried again next second.
|
||||
boosted = if (session == null) emptySet() else next
|
||||
boostedThreads = boosted
|
||||
Log.i(TAG, (if (session == null && next.isNotEmpty()) "no session for " else "boosting ") +
|
||||
next.joinToString { "${readName("/proc/$it/comm")}/$it ${((busy[it] ?: 0.0) * 100).toInt()}%" }.ifEmpty { "nothing" } +
|
||||
" (game ${fps.toInt()} fps${if (paced) ", holding pace" else ""})")
|
||||
}
|
||||
offWhy = offReason(spare, boosted, paced, next)
|
||||
}
|
||||
session?.reportActualWorkDuration(TARGET_NS * 3 / 2)
|
||||
Thread.sleep(REPORT_MS)
|
||||
@@ -116,17 +144,28 @@ object GameThreadHints {
|
||||
Log.w(TAG, "stopped", t)
|
||||
} finally {
|
||||
session?.close()
|
||||
boostedThreads = emptySet()
|
||||
}
|
||||
}
|
||||
|
||||
/** Why no thread is boosted, for the log; null while one is. [spare] is why the boost is held back, if it is. */
|
||||
internal fun offReason(spare: String?, boosted: Set<Int>, paced: Boolean, next: Set<Int>): String? = when {
|
||||
spare != null -> spare
|
||||
boosted.isNotEmpty() -> null
|
||||
paced -> BoostReport.KEEPS_UP
|
||||
next.isEmpty() -> "no thread busy enough"
|
||||
else -> "Android refused the hint"
|
||||
}
|
||||
|
||||
/** A new session over [tids] in place of [session]; null for none. The set changes seldom, so no setThreads. */
|
||||
private fun update(hm: PerformanceHintManager, session: PerformanceHintManager.Session?, tids: Set<Int>): PerformanceHintManager.Session? {
|
||||
session?.close()
|
||||
if (tids.isEmpty()) return null
|
||||
return try {
|
||||
hm.createHintSession(tids.toIntArray(), TARGET_NS)
|
||||
hm.createHintSession(tids.toIntArray(), TARGET_NS).also { if (it == null) refused++ }
|
||||
} catch (t: RuntimeException) {
|
||||
Log.w(TAG, "createHintSession", t)
|
||||
refused++
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.net.LocalServerSocket
|
||||
import android.net.LocalSocket
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.Parcel
|
||||
import android.os.PowerManager
|
||||
import android.system.Os
|
||||
import android.system.OsConstants
|
||||
import android.system.StructPollfd
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import com.samsung.sdk.sperf.Boost
|
||||
import java.io.DataInputStream
|
||||
import java.io.DataOutputStream
|
||||
import java.io.InputStream
|
||||
import java.lang.reflect.InvocationTargetException
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* Samsung's CPU, GPU and memory-bus clock floors, from the performance service in Samsung's firmware.
|
||||
* DroidDeck talks to it directly, the way Samsung's Galaxy Performance SDK 1.0.0 does, so the SDK is
|
||||
* not needed: the binder service [SERVICE] sends the phone's level table over a local socket, and the
|
||||
* firmware library [LIBRARY] ([Boost]) holds a level. Other phones have neither, and nothing happens.
|
||||
*
|
||||
* The floors are those of the SDK's CPU, GPU and bus presets (the middle of five levels, at least four
|
||||
* cores online), asked for with a timeout of at most [HOLD_MS], so Samsung lets go on its own if the
|
||||
* app dies. Samsung may hold a request for less than asked (1 s on an SM8850 Galaxy Z Fold), so they
|
||||
* are renewed every [renewMs].
|
||||
*
|
||||
* A phone without the firmware library is not asked again until the app restarts. Where the library
|
||||
* is there, a failed connection is tried again [TRIES] times a session, each failure with its reason
|
||||
* in [Tries.failed], and again at the next session.
|
||||
*/
|
||||
object SamsungPerf {
|
||||
private const val TAG = "SamsungPerf"
|
||||
private const val LIBRARY = "perfsdk.performance.samsung"
|
||||
private const val SERVICE = "perfsdkservice"
|
||||
private const val DESCRIPTOR = "com.samsung.android.perfsdkservice.IPerfSDKService"
|
||||
private const val CALL_INIT = IBinder.FIRST_CALL_TRANSACTION // initPerfSDK(socket name): Int
|
||||
private const val CALL_PACKAGE = IBinder.FIRST_CALL_TRANSACTION + 1 // getAllowedPkgName(): String
|
||||
private const val ASK_LEVELS = 10
|
||||
private const val SOCKET_TIMEOUT_MS = 3000
|
||||
|
||||
// Boost.requestBoost types
|
||||
internal const val CPU_MIN = 0
|
||||
internal const val GPU_MIN = 2
|
||||
internal const val BUS_MIN = 4
|
||||
internal const val CPU_CORES_MIN = 6
|
||||
private const val LEVEL = 2
|
||||
private const val CORES = 4
|
||||
internal const val HOLD_MS = 5000
|
||||
private const val SEEN_HOLD_MS = 1000
|
||||
internal const val TRIES = 4
|
||||
private val RETRY_S = intArrayOf(5, 15, 30)
|
||||
|
||||
/** Half the hold, and no later than half the shortest hold Samsung has been seen to use. */
|
||||
internal fun renewMs(holdMs: Int): Long = (minOf(holdMs, SEEN_HOLD_MS) / 2).coerceAtLeast(100).toLong()
|
||||
|
||||
/** The floors the phone offers, five values each from low to high, and the longest timeout (≤ 0: none). */
|
||||
internal class Levels(val cpu: IntArray, val gpu: IntArray, val bus: IntArray, val maxTimeoutMs: Int)
|
||||
|
||||
/** The service's answer to [ASK_LEVELS] in little-endian ints: the floors, then the ceilings, unused here. */
|
||||
internal fun readLevels(stream: InputStream): Levels {
|
||||
val input = DataInputStream(stream)
|
||||
fun next() = Integer.reverseBytes(input.readInt())
|
||||
fun five() = IntArray(5) { next() }
|
||||
repeat(3) { next() }
|
||||
val timeout = next()
|
||||
val levels = Levels(five(), five(), five(), timeout)
|
||||
repeat(3 + 1 + 15) { next() } // level counts, the ceilings' timeout, CPU, GPU and bus ceilings
|
||||
return levels
|
||||
}
|
||||
|
||||
/** One Boost.requestBoost call. */
|
||||
internal data class Floor(val type: Int, val value: Int, val timeoutMs: Int)
|
||||
|
||||
internal fun floors(levels: Levels): List<Floor> {
|
||||
val timeout = if (levels.maxTimeoutMs > 0) minOf(HOLD_MS, levels.maxTimeoutMs) else HOLD_MS
|
||||
return listOf(
|
||||
Floor(CPU_MIN, levels.cpu[LEVEL], timeout),
|
||||
Floor(CPU_CORES_MIN, CORES, timeout),
|
||||
Floor(GPU_MIN, levels.gpu[LEVEL], timeout),
|
||||
Floor(BUS_MIN, levels.bus[LEVEL], timeout),
|
||||
).filter { it.value > 0 }
|
||||
}
|
||||
|
||||
/** One session's tries to connect: why each failed, and whether all [TRIES] did. */
|
||||
internal class Tries {
|
||||
val failed = CopyOnWriteArrayList<String>()
|
||||
@Volatile var gaveUp = false
|
||||
}
|
||||
|
||||
/** What the log says after try [n] failed. */
|
||||
internal fun retryNote(n: Int): String =
|
||||
if (n < TRIES) "trying again in ${RETRY_S[n - 1]} s" else "no more tries until the next game"
|
||||
|
||||
/** A failed try's reason: the step it was on and what went wrong there. */
|
||||
internal fun failure(step: String, t: Throwable): String {
|
||||
val cause = (t as? InvocationTargetException)?.targetException ?: t
|
||||
return "failed while $step (${cause.javaClass.simpleName}${cause.message?.takeIf { it.isNotBlank() }?.let { ": $it" } ?: ""})"
|
||||
}
|
||||
|
||||
private val connectLock = Any()
|
||||
@Volatile private var floors: List<Floor>? = null
|
||||
@Volatile private var unavailable: String? = null
|
||||
private var socket: LocalSocket? = null // kept open for the process's life, as the SDK does
|
||||
@Volatile internal var tries = Tries()
|
||||
|
||||
private class Failed(val why: String) : Exception(why)
|
||||
|
||||
/** Null where there is no Samsung service (the reason in [unavailable]) or this try failed (the reason in [t]). */
|
||||
private fun connect(t: Tries): List<Floor>? = synchronized(connectLock) { connectLocked(t) }
|
||||
|
||||
private fun connectLocked(t: Tries): List<Floor>? {
|
||||
floors?.let { return it }
|
||||
if (unavailable != null) return null
|
||||
try {
|
||||
System.loadLibrary(LIBRARY)
|
||||
} catch (_: UnsatisfiedLinkError) {
|
||||
unavailable = "no Samsung performance library"
|
||||
offWhy = unavailable
|
||||
Log.i(TAG, "not available: $unavailable")
|
||||
return null
|
||||
}
|
||||
var step = "looking up Samsung's performance service"
|
||||
var client: LocalSocket? = null
|
||||
try {
|
||||
val service = Class.forName("android.os.ServiceManager").getMethod("getService", String::class.java)
|
||||
.invoke(null, SERVICE) as IBinder? ?: throw Failed("Samsung's performance service ($SERVICE) is not running")
|
||||
val name = "PERFSDK_SOC_" + Random.nextInt(36 * 36 * 36 * 36 * 36).toString(36).padStart(5, '0')
|
||||
step = "opening a socket for the service"
|
||||
val server = LocalServerSocket(name) // the service connects to it; Closeable only from Android 10
|
||||
val accepted = try {
|
||||
step = "asking the service to connect"
|
||||
val init = call(service, CALL_INIT, { writeString(name) }, { readInt() })
|
||||
step = "asking the service for the package name"
|
||||
val pkg = call(service, CALL_PACKAGE, {}, { readString() })
|
||||
if (!pkg.isNullOrEmpty()) Boost.setPkgName(pkg)
|
||||
Log.i(TAG, "service: init $init, package $pkg")
|
||||
step = "waiting for the service to connect"
|
||||
val poll = StructPollfd().apply { fd = server.fileDescriptor; events = OsConstants.POLLIN.toShort() }
|
||||
if (Os.poll(arrayOf(poll), SOCKET_TIMEOUT_MS) < 1) {
|
||||
throw Failed("the service did not connect within ${SOCKET_TIMEOUT_MS / 1000} s (it answered $init, package ${pkg ?: "none"})")
|
||||
}
|
||||
server.accept()
|
||||
} finally {
|
||||
server.close()
|
||||
}
|
||||
client = accepted
|
||||
step = "reading the service's level table"
|
||||
accepted.soTimeout = SOCKET_TIMEOUT_MS
|
||||
DataOutputStream(accepted.outputStream).apply { writeInt(Integer.reverseBytes(ASK_LEVELS)); flush() }
|
||||
val levels = readLevels(accepted.inputStream)
|
||||
Log.i(TAG, "levels: cpu ${levels.cpu.joinToString()} / gpu ${levels.gpu.joinToString()} / " +
|
||||
"bus ${levels.bus.joinToString()}, max ${levels.maxTimeoutMs} ms")
|
||||
val found = floors(levels)
|
||||
if (found.isEmpty()) {
|
||||
throw Failed("the level table has no usable floors (cpu ${levels.cpu.joinToString()} / gpu ${levels.gpu.joinToString()} / bus ${levels.bus.joinToString()})")
|
||||
}
|
||||
socket = accepted
|
||||
client = null
|
||||
floors = found
|
||||
return found
|
||||
} catch (e: Throwable) {
|
||||
val why = (e as? Failed)?.why ?: failure(step, e)
|
||||
t.failed.add(why)
|
||||
offWhy = "could not connect"
|
||||
Log.w(TAG, "try ${t.failed.size} of $TRIES failed: $why", e.takeIf { it !is Failed })
|
||||
return null
|
||||
} finally {
|
||||
client?.let { runCatching { it.close() } }
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T> call(service: IBinder, code: Int, write: Parcel.() -> Unit, read: Parcel.() -> T): T {
|
||||
val data = Parcel.obtain()
|
||||
val reply = Parcel.obtain()
|
||||
try {
|
||||
data.writeInterfaceToken(DESCRIPTOR)
|
||||
data.write()
|
||||
if (!service.transact(code, data, reply, 0)) throw Failed("the service does not take call $code")
|
||||
reply.readException()
|
||||
return reply.read()
|
||||
} finally {
|
||||
reply.recycle()
|
||||
data.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private var worker: Thread? = null
|
||||
|
||||
/** For BoostReport: whether the floors are held now, why not, and what the library answered when they were asked for. */
|
||||
@Volatile internal var holding = false
|
||||
@Volatile internal var offWhy: String? = null
|
||||
@Volatile internal var lastResults = emptyList<Int>()
|
||||
|
||||
internal val connected get() = floors != null
|
||||
|
||||
/** For BoostReport. */
|
||||
internal val state: String
|
||||
get() = unavailable?.let { "not available: $it" }
|
||||
?: floors?.let { f ->
|
||||
val hold = f.minOf { it.timeoutMs }
|
||||
"connected, floors " + f.joinToString { "${TYPE_NAMES[it.type]} ${it.value}" } +
|
||||
", asked for $hold ms at a time, renewed every ${renewMs(hold)} ms"
|
||||
}
|
||||
?: tries.let { t ->
|
||||
when {
|
||||
t.gaveUp -> "could not connect in $TRIES tries (last: ${t.failed.lastOrNull()})"
|
||||
t.failed.isNotEmpty() -> "connecting, try ${t.failed.size + 1} of $TRIES"
|
||||
else -> "connecting"
|
||||
}
|
||||
}
|
||||
|
||||
internal fun floorValue(type: Int): Int? = floors?.firstOrNull { it.type == type }?.value
|
||||
|
||||
private val TYPE_NAMES = mapOf(CPU_MIN to "CPU", GPU_MIN to "GPU", BUS_MIN to "bus", CPU_CORES_MIN to "cores")
|
||||
|
||||
/** At a session's start. The line is for the log. */
|
||||
@Synchronized
|
||||
fun start(context: Context): String {
|
||||
if (!SessionPrefs.performanceBoost(context)) return "samsung boost: off"
|
||||
unavailable?.let { return "samsung boost: $it" }
|
||||
val app = context.applicationContext
|
||||
worker?.interrupt()
|
||||
offWhy = "starting"
|
||||
val t = Tries()
|
||||
tries = t
|
||||
worker = Thread({ run(app, t) }, "samsung-boost").apply { isDaemon = true; start() }
|
||||
return "samsung boost: watching"
|
||||
}
|
||||
|
||||
/** At a session's end. */
|
||||
@Synchronized
|
||||
fun stop() {
|
||||
worker?.interrupt()
|
||||
worker = null
|
||||
}
|
||||
|
||||
private fun run(context: Context, t: Tries) {
|
||||
var boosting = false
|
||||
try {
|
||||
var found = connect(t)
|
||||
while (found == null && unavailable == null && t.failed.size < TRIES) {
|
||||
Thread.sleep(RETRY_S[t.failed.size - 1] * 1000L)
|
||||
found = connect(t)
|
||||
}
|
||||
if (found == null) {
|
||||
if (unavailable == null) {
|
||||
t.gaveUp = true
|
||||
offWhy = "could not connect in $TRIES tries"
|
||||
}
|
||||
return
|
||||
}
|
||||
val floors: List<Floor> = found
|
||||
val renew = renewMs(floors.minOf { it.timeoutMs })
|
||||
val pm = context.getSystemService(PowerManager::class.java)
|
||||
val frames = ArrayDeque<Long>()
|
||||
var pacedFor = 0
|
||||
while (!Thread.currentThread().isInterrupted) {
|
||||
frames.addLast(WaylandCompositor.gameFrameCount())
|
||||
if (frames.size > GameThreadHints.PACE_WINDOW_S + 1) frames.removeFirst()
|
||||
val fps = (frames.last() - frames.first()).toDouble() / (frames.size - 1).coerceAtLeast(1)
|
||||
val paced = frames.size > GameThreadHints.PACE_WINDOW_S && GameThreadHints.holdsPace(fps, SessionState.refreshHz.toDouble())
|
||||
pacedFor = if (paced) pacedFor + 1 else 0
|
||||
val hot = Build.VERSION.SDK_INT >= 29 && pm.currentThermalStatus >= PowerManager.THERMAL_STATUS_SEVERE
|
||||
val why = when {
|
||||
BoostReport.paused -> "check pause"
|
||||
fps < 1 -> "no frames"
|
||||
pm.isPowerSaveMode -> BoostReport.BATTERY_SAVER
|
||||
hot -> BoostReport.TOO_HOT
|
||||
pacedFor >= GameThreadHints.PACE_LEAVE_S -> BoostReport.KEEPS_UP
|
||||
else -> null
|
||||
}
|
||||
offWhy = why
|
||||
val want = why == null
|
||||
if (want) {
|
||||
val results = request(floors)
|
||||
holding = true
|
||||
if (!boosting) {
|
||||
lastResults = results
|
||||
Log.i(TAG, "boosting (game ${fps.toInt()} fps, results $results)")
|
||||
}
|
||||
} else if (boosting) {
|
||||
holding = false // first, so BoostReport does not read the release as Samsung letting go
|
||||
Boost.releaseBoost()
|
||||
BoostReport.letGo(why!!)
|
||||
Log.i(TAG, "let go ($why, game ${fps.toInt()} fps)")
|
||||
}
|
||||
boosting = want
|
||||
var slept = 0L
|
||||
while (slept + renew < 1000) {
|
||||
Thread.sleep(renew)
|
||||
slept += renew
|
||||
if (boosting) request(floors)
|
||||
}
|
||||
Thread.sleep(1000 - slept)
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "stopped", e)
|
||||
} finally {
|
||||
if (boosting) runCatching { Boost.releaseBoost() }
|
||||
holding = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun request(floors: List<Floor>) = floors.map { Boost.requestBoost(it.type, it.value, it.timeoutMs) }
|
||||
}
|
||||
@@ -615,8 +615,22 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("gpuClockPin", on).apply()
|
||||
}
|
||||
|
||||
/** Whether the game's busiest threads are named to the power HAL for a boost (GameThreadHints). */
|
||||
fun gameThreadHints(context: Context): Boolean = prefs(context).getBoolean("gameThreadHints", true)
|
||||
/**
|
||||
* The performance boost: the game's busiest threads named to the power HAL (GameThreadHints) and,
|
||||
* on a Samsung phone, Samsung's clock floors (SamsungPerf).
|
||||
*/
|
||||
fun performanceBoost(context: Context): Boolean = prefs(context).getBoolean("performanceBoost", GameThreadHints.measuredHere)
|
||||
|
||||
fun setPerformanceBoost(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("performanceBoost", on).apply()
|
||||
}
|
||||
|
||||
/** Check the boost: BoostReport pauses the boost every other minute of play and compares. */
|
||||
fun boostCheck(context: Context): Boolean = prefs(context).getBoolean("boostCheck", false)
|
||||
|
||||
fun setBoostCheck(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("boostCheck", on).apply()
|
||||
}
|
||||
|
||||
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
|
||||
|
||||
|
||||
@@ -499,6 +499,8 @@ class SessionService : Service() {
|
||||
|
||||
Log.i(TAG, GpuClockPin.start(this))
|
||||
Log.i(TAG, GameThreadHints.start(this))
|
||||
Log.i(TAG, SamsungPerf.start(this))
|
||||
Log.i(TAG, BoostReport.start(this, sessionDir))
|
||||
|
||||
val size = SessionState.outputSize
|
||||
val guest = ArrayList<String>()
|
||||
@@ -1810,7 +1812,9 @@ class SessionService : Service() {
|
||||
SessionState.program == NoSteamLaunch.BATTLENET
|
||||
SessionState.stopRequested = false
|
||||
GpuClockPin.stop(this)
|
||||
BoostReport.stop()
|
||||
GameThreadHints.stop()
|
||||
SamsungPerf.stop()
|
||||
suspendOperationPending = false
|
||||
freezePending = false
|
||||
launchWatcher?.stopWatching()
|
||||
@@ -1890,7 +1894,9 @@ class SessionService : Service() {
|
||||
|
||||
override fun onDestroy() {
|
||||
stopSession(0)
|
||||
BoostReport.stop()
|
||||
GameThreadHints.stop() // also when the session never got as far as running
|
||||
SamsungPerf.stop()
|
||||
if (screenReceiverRegistered) {
|
||||
unregisterReceiver(screenReceiver)
|
||||
screenReceiverRegistered = false
|
||||
|
||||
@@ -19,7 +19,7 @@ object SettingsReset {
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "picturePosition", "railLabels",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "performanceBoost", "boostCheck", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
|
||||
|
||||
@@ -46,6 +46,8 @@ fun PerformancePage(
|
||||
fsyncFirst: Boolean,
|
||||
gamescopeRealtime: Boolean,
|
||||
gpuClockPin: Boolean,
|
||||
performanceBoost: Boolean,
|
||||
boostCheck: Boolean,
|
||||
ramCapMb: Int,
|
||||
zramClient: Boolean,
|
||||
vramCapMb: Int,
|
||||
@@ -67,6 +69,8 @@ fun PerformancePage(
|
||||
onFsyncFirst: (Boolean) -> Unit,
|
||||
onGamescopeRealtime: (Boolean) -> Unit,
|
||||
onGpuClockPin: (Boolean) -> Unit,
|
||||
onPerformanceBoost: (Boolean) -> Unit,
|
||||
onBoostCheck: (Boolean) -> Unit,
|
||||
onRamCapMb: (Int) -> Unit,
|
||||
onZramClient: (Boolean) -> Unit,
|
||||
onVramCapMb: (Int) -> Unit,
|
||||
@@ -126,6 +130,18 @@ fun PerformancePage(
|
||||
gamescopeRealtime, onChange = onGamescopeRealtime,
|
||||
)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.perf_boost_group)) {
|
||||
ToggleRow(
|
||||
host, "boost", stringResource(R.string.perf_boost),
|
||||
stringResource(R.string.perf_boost_hint),
|
||||
performanceBoost, onChange = onPerformanceBoost,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "boostcheck", stringResource(R.string.perf_boost_check),
|
||||
stringResource(R.string.perf_boost_check_hint),
|
||||
boostCheck, enabled = performanceBoost, onChange = onBoostCheck,
|
||||
)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.perf_gpu)) {
|
||||
ToggleRow(
|
||||
host, "gpuclock", stringResource(R.string.perf_gpuclock),
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.samsung.sdk.sperf;
|
||||
|
||||
/**
|
||||
* Entry points of libperfsdk.performance.samsung.so, the performance library in Samsung's firmware.
|
||||
* The library binds them by this class name, so the name has to stay. Used by
|
||||
* com.droiddeck.launcher.session.SamsungPerf; on other phones the library is missing.
|
||||
*/
|
||||
public final class Boost {
|
||||
private Boost() {
|
||||
}
|
||||
|
||||
/** Holds a resource (CPU_MIN, GPU_MIN...) at a value from the service's level table. */
|
||||
public static native int requestBoost(int type, int value, int timeoutMs);
|
||||
|
||||
/** Lets go of everything this app holds. */
|
||||
public static native int releaseBoost();
|
||||
|
||||
/** The package name the service gives out; the library refuses requests until it is set. */
|
||||
public static native int setPkgName(String name);
|
||||
}
|
||||
@@ -597,6 +597,11 @@
|
||||
<string name="perf_noglerror_hint">Turns off per-call GL validation.</string>
|
||||
<string name="perf_gsrealtime">gamescope: realtime GPU queue</string>
|
||||
<string name="perf_gsrealtime_hint">Prioritizes the compositor\'s GPU work. Can smooth frame pacing at some cost to games.</string>
|
||||
<string name="perf_boost_group">Boost</string>
|
||||
<string name="perf_boost">Performance boost</string>
|
||||
<string name="perf_boost_hint">Asks the phone to run the game\'s busiest threads on its fastest cores while the game falls behind. Lets go when the game keeps up, the phone is hot or battery saver is on. Android 12 or newer. Samsung phones also raise their CPU, GPU and memory clocks. More battery use and heat. What it did is in boost.log in the session\'s logs.</string>
|
||||
<string name="perf_boost_check">Check the boost</string>
|
||||
<string name="perf_boost_check_hint">For testing: during a game the boost takes turns on and paused (one minute on, then two paused, two on, and so on), and boost.log ends with a fair comparison and a verdict. The first minute is not counted. Play at least 7 minutes, then turn this off. A phone that gets too hot gives no verdict. A game that runs well without the boost is marked as not needing it.</string>
|
||||
<string name="perf_gpu">GPU</string>
|
||||
<string name="perf_memory">Memory</string>
|
||||
<string name="perf_cap_off">Off</string>
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class BoostReportTest {
|
||||
private fun side(fps: Int, seconds: Int = 200, milliamps: Int? = null, slow: Int = fps) =
|
||||
BoostReport.Side().apply { repeat(seconds) { add(if (it < seconds / 10) slow else fps, milliamps, 0) } }
|
||||
|
||||
@Test fun `the CPU a thread ran on is field 39 of its stat, even with spaces in its name`() {
|
||||
val fields = (3..52).map { if (it == 39) "7" else "0" }
|
||||
assertEquals(7, BoostReport.processorOf("1234 (Main Thread) " + fields.joinToString(" ")))
|
||||
assertNull(BoostReport.processorOf("1234 (short) S 1"))
|
||||
}
|
||||
|
||||
@Test fun `cores are sorted into fastest, middle and slowest by top speed`() {
|
||||
val tiers = BoostReport.tiers(mapOf(0 to 2.0, 1 to 2.0, 2 to 3.2, 3 to 3.2, 4 to 4.3))
|
||||
assertEquals(mapOf(0 to 0, 1 to 0, 2 to 1, 3 to 1, 4 to 2), tiers)
|
||||
assertEquals(mapOf(0 to 2, 1 to 2), BoostReport.tiers(mapOf(0 to 2.0, 1 to 2.0)))
|
||||
}
|
||||
|
||||
@Test fun `the slowest 5 percent is the frame rate of the slowest seconds`() {
|
||||
val s = BoostReport.Side().apply { (1..100).forEach { add(it, null, 0) } }
|
||||
assertEquals(6, s.low)
|
||||
assertEquals(50.5, s.average, 1e-9)
|
||||
}
|
||||
|
||||
@Test fun `a clear gain is worth keeping`() {
|
||||
val v = BoostReport.verdict(side(60, milliamps = 1200), side(50, milliamps = 1000))
|
||||
assertTrue(v, v.startsWith("worth keeping: +20 % fps on average"))
|
||||
assertTrue(v, v.endsWith("for +20 % battery draw"))
|
||||
}
|
||||
|
||||
@Test fun `better slowest moments alone are worth keeping`() {
|
||||
val v = BoostReport.verdict(side(50, slow = 40), side(50, slow = 30))
|
||||
assertTrue(v, v.startsWith("worth keeping: +2 % fps on average, +33 % in the slowest moments"))
|
||||
}
|
||||
|
||||
@Test fun `no gain is not worth keeping`() {
|
||||
assertTrue(BoostReport.verdict(side(50), side(50)).startsWith("not worth keeping"))
|
||||
assertTrue(BoostReport.verdict(side(45), side(50)).startsWith("not worth keeping"))
|
||||
}
|
||||
|
||||
@Test fun `a small gain is unclear`() {
|
||||
assertTrue(BoostReport.verdict(side(52), side(50)).startsWith("unclear, a small gain"))
|
||||
}
|
||||
|
||||
@Test fun `a short check gives no verdict`() {
|
||||
val v = BoostReport.verdict(side(60, seconds = 100), side(50))
|
||||
assertEquals("too short to tell: play at least ${BoostReport.minutesForVerdict()} minutes with Check the boost on", v)
|
||||
}
|
||||
|
||||
@Test fun `the switch's hint asks for as many minutes as the verdict needs`() {
|
||||
assertEquals(7, BoostReport.minutesForVerdict())
|
||||
}
|
||||
|
||||
@Test fun `the check starts after the first minute of play, then goes on, paused, paused, on`() {
|
||||
(1..60).forEach { assertNull(BoostReport.checkWindow(it)) }
|
||||
assertEquals(false to 0, BoostReport.checkWindow(61))
|
||||
assertEquals(false to 59, BoostReport.checkWindow(120))
|
||||
assertEquals(true to 0, BoostReport.checkWindow(121))
|
||||
assertEquals(true to 119, BoostReport.checkWindow(240))
|
||||
assertEquals(false to 0, BoostReport.checkWindow(241))
|
||||
assertEquals(false to 119, BoostReport.checkWindow(360))
|
||||
assertEquals(true to 0, BoostReport.checkWindow(361))
|
||||
}
|
||||
|
||||
@Test fun `a game slowing down steadily as the phone warms favours neither side`() {
|
||||
val on = BoostReport.Side()
|
||||
val off = BoostReport.Side()
|
||||
for (s in 1..BoostReport.WARMUP_S + 8 * BoostReport.WINDOW_S) {
|
||||
val (pause, at) = BoostReport.checkWindow(s) ?: continue
|
||||
if (at >= BoostReport.SETTLE_S) (if (pause) off else on).add(150 - s / 6, null, 0)
|
||||
}
|
||||
assertEquals(on.average, off.average, 0.5)
|
||||
assertTrue(BoostReport.verdict(on, off).startsWith("not worth keeping"))
|
||||
}
|
||||
|
||||
@Test fun `no verdict when heat held the boost back for more than a quarter of its turns`() {
|
||||
val on = BoostReport.Side().apply { repeat(200) { add(80, null, 4, held = it < 60) } }
|
||||
val v = BoostReport.verdict(on, side(60))
|
||||
assertTrue(v, v.startsWith("can't tell: the phone was too hot or saving battery for 30 % of the time"))
|
||||
assertTrue(BoostReport.verdict(BoostReport.Side().apply { repeat(200) { add(80, null, 4, held = it < 40) } }, side(60))
|
||||
.startsWith("worth keeping"))
|
||||
}
|
||||
|
||||
@Test fun `a game that keeps up without the boost does not need it`() {
|
||||
val on = BoostReport.Side().apply { repeat(200) { add(58, null, 0, idle = it >= 12) } }
|
||||
val v = BoostReport.verdict(on, side(59))
|
||||
assertTrue(v, v.startsWith("not needed for this game: it kept up without the boost for 94 % of the boost's turns"))
|
||||
assertTrue(v, v.endsWith("(58.0 fps in its turns, 59.0 fps paused)"))
|
||||
val busy = BoostReport.Side().apply { repeat(200) { add(41, null, 0, idle = it < 96) } }
|
||||
assertTrue(BoostReport.verdict(busy, side(40)).startsWith("unclear, a small gain"))
|
||||
val short = BoostReport.Side().apply { repeat(100) { add(58, null, 0, idle = true) } }
|
||||
assertTrue(BoostReport.verdict(short, side(59)).startsWith("too short to tell"))
|
||||
}
|
||||
|
||||
@Test fun `the status names why the boost is off, once for a reason both parts give`() {
|
||||
assertEquals("too hot", BoostReport.offReasons("too hot", "too hot"))
|
||||
assertEquals("game keeps up, too hot", BoostReport.offReasons("game keeps up", "too hot"))
|
||||
assertEquals("battery saver", BoostReport.offReasons("battery saver", null))
|
||||
assertEquals("no reason given", BoostReport.offReasons(null, null))
|
||||
}
|
||||
|
||||
@Test fun `the summary gives how long each reason kept a part off, longest first`() {
|
||||
assertEquals("7:40 too hot, 0:20 game keeps up", BoostReport.offTimes(linkedMapOf("game keeps up" to 20, "too hot" to 460)))
|
||||
assertEquals("", BoostReport.offTimes(emptyMap()))
|
||||
}
|
||||
|
||||
@Test fun `the minutes asked for give both sides enough counted seconds`() {
|
||||
val seconds = IntArray(2)
|
||||
for (s in 1..BoostReport.minutesForVerdict() * 60) {
|
||||
val (pause, at) = BoostReport.checkWindow(s) ?: continue
|
||||
if (at >= BoostReport.SETTLE_S) seconds[if (pause) 1 else 0]++
|
||||
}
|
||||
assertTrue(seconds.joinToString(), seconds.all { it >= BoostReport.CHECK_MIN_S })
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,14 @@ class GameThreadHintsTest {
|
||||
assertEquals(setOf(2), GameThreadHints.pick(setOf(1, 2), mapOf(2 to 0.7)))
|
||||
}
|
||||
|
||||
@Test fun `the log is told why no thread is boosted`() {
|
||||
assertEquals("too hot", GameThreadHints.offReason("too hot", emptySet(), false, emptySet()))
|
||||
assertEquals(null, GameThreadHints.offReason(null, setOf(1), true, setOf(1)))
|
||||
assertEquals("game keeps up", GameThreadHints.offReason(null, emptySet(), true, emptySet()))
|
||||
assertEquals("no thread busy enough", GameThreadHints.offReason(null, emptySet(), false, emptySet()))
|
||||
assertEquals("Android refused the hint", GameThreadHints.offReason(null, emptySet(), false, setOf(1)))
|
||||
}
|
||||
|
||||
@Test fun `a game at the panel's rate or a fraction of it holds pace`() {
|
||||
assertTrue(GameThreadHints.holdsPace(119.0, 120.0))
|
||||
assertTrue(GameThreadHints.holdsPace(60.5, 120.0))
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.session.SamsungPerf.Floor
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.EOFException
|
||||
import java.lang.reflect.InvocationTargetException
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
class SamsungPerfTest {
|
||||
private val cpu = intArrayOf(300000, 691200, 1190400, 1555200, 2016000)
|
||||
private val gpu = intArrayOf(220000, 350000, 490000, 600000, 680000)
|
||||
private val bus = intArrayOf(547000, 1017000, 1555000, 2092000, 3196000)
|
||||
|
||||
/** A level table as Samsung's service sends it: 38 little-endian ints. */
|
||||
private fun table(maxTimeoutMs: Int, cpu: IntArray = this.cpu, gpu: IntArray = this.gpu, bus: IntArray = this.bus): ByteArray {
|
||||
val ints = intArrayOf(0, 0, 0, maxTimeoutMs) + cpu + gpu + bus + intArrayOf(5, 5, 5, maxTimeoutMs) + IntArray(15) { 3_000_000 }
|
||||
return ByteBuffer.allocate(ints.size * 4).order(ByteOrder.LITTLE_ENDIAN).apply { ints.forEach { putInt(it) } }.array()
|
||||
}
|
||||
|
||||
@Test fun `the floors are read from the table, and nothing past it`() {
|
||||
val stream = ByteArrayInputStream(table(10000) + byteArrayOf(7))
|
||||
val levels = SamsungPerf.readLevels(stream)
|
||||
assertArrayEquals(cpu, levels.cpu)
|
||||
assertArrayEquals(gpu, levels.gpu)
|
||||
assertArrayEquals(bus, levels.bus)
|
||||
assertEquals(10000, levels.maxTimeoutMs)
|
||||
assertEquals(1, stream.available())
|
||||
}
|
||||
|
||||
@Test fun `the middle level of each floor is held, with four cores online`() {
|
||||
val floors = SamsungPerf.floors(SamsungPerf.readLevels(ByteArrayInputStream(table(-1))))
|
||||
val hold = SamsungPerf.HOLD_MS
|
||||
assertEquals(
|
||||
listOf(
|
||||
Floor(SamsungPerf.CPU_MIN, 1190400, hold),
|
||||
Floor(SamsungPerf.CPU_CORES_MIN, 4, hold),
|
||||
Floor(SamsungPerf.GPU_MIN, 490000, hold),
|
||||
Floor(SamsungPerf.BUS_MIN, 1555000, hold),
|
||||
),
|
||||
floors,
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `a shorter limit from the phone shortens the hold`() {
|
||||
val floors = SamsungPerf.floors(SamsungPerf.readLevels(ByteArrayInputStream(table(3000))))
|
||||
assertEquals(setOf(3000), floors.map { it.timeoutMs }.toSet())
|
||||
}
|
||||
|
||||
@Test fun `a resource the phone does not offer is left alone`() {
|
||||
val floors = SamsungPerf.floors(SamsungPerf.readLevels(ByteArrayInputStream(table(-1, gpu = IntArray(5) { -1 }))))
|
||||
assertEquals(listOf(SamsungPerf.CPU_MIN, SamsungPerf.CPU_CORES_MIN, SamsungPerf.BUS_MIN), floors.map { it.type })
|
||||
}
|
||||
|
||||
@Test fun `the floors are renewed before Samsung's one-second hold runs out`() {
|
||||
assertEquals(500L, SamsungPerf.renewMs(SamsungPerf.HOLD_MS))
|
||||
assertEquals(500L, SamsungPerf.renewMs(1000))
|
||||
assertEquals(150L, SamsungPerf.renewMs(300))
|
||||
assertEquals(100L, SamsungPerf.renewMs(50))
|
||||
}
|
||||
|
||||
@Test fun `a failed connection is tried again a few times, then at the next game`() {
|
||||
assertEquals(4, SamsungPerf.TRIES)
|
||||
assertEquals("trying again in 5 s", SamsungPerf.retryNote(1))
|
||||
assertEquals("trying again in 15 s", SamsungPerf.retryNote(2))
|
||||
assertEquals("trying again in 30 s", SamsungPerf.retryNote(3))
|
||||
assertEquals("no more tries until the next game", SamsungPerf.retryNote(4))
|
||||
}
|
||||
|
||||
@Test fun `a failed try names the step it was on and the error`() {
|
||||
assertEquals(
|
||||
"failed while reading the service's level table (EOFException)",
|
||||
SamsungPerf.failure("reading the service's level table", EOFException()),
|
||||
)
|
||||
assertEquals(
|
||||
"failed while looking up Samsung's performance service (SecurityException: not allowed)",
|
||||
SamsungPerf.failure("looking up Samsung's performance service", InvocationTargetException(SecurityException("not allowed"))),
|
||||
)
|
||||
}
|
||||
|
||||
@Test(expected = EOFException::class) fun `a short answer is refused`() {
|
||||
SamsungPerf.readLevels(ByteArrayInputStream(table(-1).copyOf(100)))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user