From 827ab2d4856305f81a26e767d62e280f52c844e7 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:18:39 -0500 Subject: [PATCH] fix(hud): FPS and clocks read right after sleep and wake (#2552) * fix(hud): frame times follow the paused session's clock shift * fix(hud): core clocks show their average over each sample --- .../launcher/hud/DroidDeckHudHost.kt | 2 +- .../com/droiddeck/launcher/hud/GameFrames.kt | 27 +++++++- .../droiddeck/launcher/hud/HudMetrics.java | 66 ++++++++++++++----- .../com/droiddeck/launcher/ui/BottomStrip.kt | 3 +- .../launcher/ui/BottomTelemetryPage.kt | 3 +- .../launcher/hud/CoreClockAverageTest.kt | 26 ++++++++ .../droiddeck/launcher/hud/FrameStatsTest.kt | 15 +++++ 7 files changed, 120 insertions(+), 22 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/hud/CoreClockAverageTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt index 492d626c5b..e2ddefc692 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt @@ -22,7 +22,7 @@ import kotlin.math.roundToInt class DroidDeckHudHost(context: Context) { private val context = context.applicationContext private val handler = Handler(Looper.getMainLooper()) - private val feed = GameFrameFeed(File(LinuxRuntime.rootDir(this.context), HudFrames.PATH)) + private val feed = GameFrameFeed.forRoot(LinuxRuntime.rootDir(this.context)) private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context)) private var view: DroidDeckHudView? = null private var parent: ViewGroup? = null diff --git a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt index 2aba209ded..db5f74e4cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.hud import java.io.File +import java.io.RandomAccessFile import kotlin.math.roundToInt internal class FrameStats { @@ -159,7 +160,11 @@ internal class FrameStats { } } -internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) { +internal class GameFrameFeed( + private val file: File, + val stats: FrameStats = FrameStats(), + private val clockControl: File? = null, +) { private var handle = 0L private var nextOpenNs = 0L private var lastRingFrameNs = 0L @@ -171,6 +176,8 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra private var lastCompositorNs = 0L @Volatile private var compositorFrames = 0L private var seenCompositorFrames = 0L + private var clockShiftNs = 0L + private var clockShiftReadNs = Long.MIN_VALUE @Volatile var engine = "" private set @@ -199,6 +206,9 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra } val n = HudFrames.nativePoll(handle, frametimes, times) if (n > 0) { + var shift = guestClockShift(nowNs, SHIFT_NS) + if (nowNs - (times[n - 1] + shift) > LIVE_NS) shift = guestClockShift(nowNs, SHIFT_RECHECK_NS) + for (i in 0 until n) times[i] += shift if (!fromGamescope) { stats.reset() fromGamescope = true @@ -216,6 +226,16 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra return n > 0 || compositorAdded } + internal fun guestClockShift(nowNs: Long, maxAgeNs: Long): Long { + val control = clockControl ?: return 0L + if (clockShiftReadNs != Long.MIN_VALUE && nowNs - clockShiftReadNs < maxAgeNs) return clockShiftNs + clockShiftReadNs = nowNs + clockShiftNs = runCatching { + RandomAccessFile(control, "r").use { if (it.length() < Long.SIZE_BYTES) 0L else java.lang.Long.reverseBytes(it.readLong()) } + }.getOrDefault(0L).coerceAtLeast(0L) + return clockShiftNs + } + fun onCompositorFrame(nowNs: Long) { if (fromGamescope) { lastCompositorNs = 0L @@ -253,6 +273,11 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra private const val LIVE_NS = 2_000_000_000L private const val STALE_NS = 5_000_000_000L private const val INFO_NS = 500_000_000L + private const val SHIFT_NS = 1_000_000_000L + private const val SHIFT_RECHECK_NS = 100_000_000L + private const val CLOCK_CONTROL_PATH = "tmp/.bl-clock" + + fun forRoot(root: File) = GameFrameFeed(File(root, HudFrames.PATH), clockControl = File(root, CLOCK_CONTROL_PATH)) fun engineLabel(name: String): String = when (name) { "DXVK" -> "DXVK" diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java b/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java index 51a4e42608..1dc5a39bcd 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java +++ b/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java @@ -651,15 +651,10 @@ public class HudMetrics { return currentRawToAmps(raw); } - public Integer getCpuClockMhz() { - int cores = Runtime.getRuntime().availableProcessors(); - long maxKhz = 0; - for (int i = 0; i < cores; i++) { - Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); - if (cur != null && cur > maxKhz) maxKhz = cur; - } - if (maxKhz <= 0) return null; - return (int) (maxKhz / 1000L); + static Integer fastestCoreMhz(int[] perCoreMhz) { + int max = 0; + for (int mhz : perCoreMhz) max = Math.max(max, mhz); + return max > 0 ? max : null; } private List gpuClockPathsCache = null; @@ -809,7 +804,8 @@ public class HudMetrics { if (mango != null) return mangoSnapshot(mango); Integer cpu = getCpuUsagePercent(); Integer gpu = getGpuUsagePercent(); - Integer cpuClk = getCpuClockMhz(); + int[] perCoreClk = getPerCoreClockMhz(); + Integer cpuClk = fastestCoreMhz(perCoreClk); Integer gpuClk = getGpuClockMhz(); Integer cpuTemp = getCpuTempC(); Integer gpuTemp = getGpuTempC(); @@ -829,7 +825,6 @@ public class HudMetrics { Battery battery = collectBattery(); int[] perCorePct = readPerCorePercent(); - int[] perCoreClk = getPerCoreClockMhz(); long[] swap = getSwapBytes(); long[] net = readNetRateBps(); @@ -850,24 +845,63 @@ public class HudMetrics { Battery battery = bat == null ? android : new Battery(bat.getWatts(), bat.getCharging(), bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, android.runtimeText); long[] net = readNetRateBps(); - return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), getCpuClockMhz(), m.gpuClockMhz(), + int[] perCoreClk = getPerCoreClockMhz(); + return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), fastestCoreMhz(perCoreClk), m.gpuClockMhz(), m.cpuTempC(), m.gpuTempC(), used, total, total > 0 ? used * 100f / total : 0f, m.vramBytes(), battery, - cpu != null ? cpu.getPerCore() : new int[0], getPerCoreClockMhz(), + cpu != null ? cpu.getPerCore() : new int[0], perCoreClk, mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapUsedBytes() : null, mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapTotalBytes() : null, net == null ? null : net[0], net == null ? null : net[1]); } - public int[] getPerCoreClockMhz() { + private final java.util.Map lastTimeInState = new java.util.HashMap<>(); + + public synchronized int[] getPerCoreClockMhz() { int cores = Runtime.getRuntime().availableProcessors(); int[] out = new int[Math.max(0, cores)]; for (int i = 0; i < out.length; i++) { - Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); - out[i] = (cur != null && cur > 0) ? (int) (cur / 1000L) : 0; + long[][] table = readTimeInState("/sys/devices/system/cpu/cpu" + i + "/cpufreq/stats/time_in_state"); + long khz = table == null ? -1L : averageKhz(lastTimeInState.put(i, table), table); + if (khz <= 0L) { + Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); + khz = cur != null ? cur : 0L; + } + out[i] = khz > 0L ? (int) (khz / 1000L) : 0; } return out; } + static long averageKhz(long[][] before, long[][] after) { + if (before == null || after == null || !java.util.Arrays.equals(before[0], after[0])) return -1L; + long weighted = 0L, time = 0L; + for (int i = 0; i < after[0].length; i++) { + long dt = after[1][i] - before[1][i]; + if (dt <= 0L) continue; + weighted += after[0][i] * dt; + time += dt; + } + return time > 0L ? weighted / time : -1L; + } + + private static long[][] readTimeInState(String path) { + List rows = new ArrayList<>(); + try (BufferedReader r = new BufferedReader(new FileReader(path))) { + String line; + while ((line = r.readLine()) != null) { + String[] parts = line.trim().split("\\s+"); + if (parts.length < 2) continue; + try { rows.add(new long[] { Long.parseLong(parts[0]), Long.parseLong(parts[1]) }); } + catch (NumberFormatException ignored) {} + } + } catch (Exception e) { + return null; + } + if (rows.isEmpty()) return null; + long[][] table = new long[2][rows.size()]; + for (int i = 0; i < rows.size(); i++) { table[0][i] = rows.get(i)[0]; table[1][i] = rows.get(i)[1]; } + return table; + } + private long[] lastCoreTotal = null; private long[] lastCoreIdle = null; private static final int PER_CORE_STAT = 1, PER_CORE_ESTIMATE = 2; diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomStrip.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomStrip.kt index 3df2090bc4..60844df4de 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomStrip.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomStrip.kt @@ -14,7 +14,6 @@ import androidx.compose.ui.platform.LocalContext import com.droiddeck.launcher.hud.DroidDeckHudConfig import com.droiddeck.launcher.hud.FrameStats import com.droiddeck.launcher.hud.GameFrameFeed -import com.droiddeck.launcher.hud.HudFrames import com.droiddeck.launcher.hud.HudMetrics import com.droiddeck.launcher.hud.KeyValueSet import com.droiddeck.launcher.hud.MangoReadings @@ -34,7 +33,7 @@ private const val STRIP_TEMP_PLAIN = 0xFFF2F5F9.toInt() @Composable internal fun SessionBottomStrip(pageId: String?, fps: () -> Float?) { val context = LocalContext.current - val frames = remember { GameFrameFeed(File(LinuxRuntime.rootDir(context), HudFrames.PATH)) } + val frames = remember { GameFrameFeed.forRoot(LinuxRuntime.rootDir(context)) } DisposableEffect(frames) { onDispose { frames.close() } } val page by rememberUpdatedState(pageId) var frameTick by remember { mutableIntStateOf(0) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt index 08b4ae8ada..4c454b52d1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt @@ -55,7 +55,6 @@ import com.droiddeck.launcher.hud.DroidDeckHudConfig import com.droiddeck.launcher.hud.DroidDeckHudHost import com.droiddeck.launcher.hud.FrameStats import com.droiddeck.launcher.hud.GameFrameFeed -import com.droiddeck.launcher.hud.HudFrames import com.droiddeck.launcher.hud.HudMetrics import com.droiddeck.launcher.hud.KeyValueSet import com.droiddeck.launcher.hud.MangoReadings @@ -144,7 +143,7 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null } var perfTick by remember { mutableIntStateOf(0) } var traceTick by remember { mutableIntStateOf(0) } var clock by remember { mutableStateOf("") } - val frames = remember { GameFrameFeed(File(LinuxRuntime.rootDir(context), HudFrames.PATH)) } + val frames = remember { GameFrameFeed.forRoot(LinuxRuntime.rootDir(context)) } DisposableEffect(frames) { onDispose { frames.close() } } val currentFps = { if (frames.live) frames.stats.fps else fps() } var hud by remember { mutableStateOf(StatsHud.from(SessionPrefs.statsHud(context))) } diff --git a/app/src/test/java/com/droiddeck/launcher/hud/CoreClockAverageTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/CoreClockAverageTest.kt new file mode 100644 index 0000000000..80c1c7121c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/hud/CoreClockAverageTest.kt @@ -0,0 +1,26 @@ +package com.droiddeck.launcher.hud + +import org.junit.Assert.assertEquals +import org.junit.Test + +class CoreClockAverageTest { + private val freqs = longArrayOf(902_400L, 1_459_200L, 2_803_200L) + + @Test fun aCoreShowsTheClockItRanAtThroughTheSample() { + val before = arrayOf(freqs, longArrayOf(100L, 50L, 10L)) + val after = arrayOf(freqs, longArrayOf(125L, 50L, 35L)) + assertEquals(1_852_800L, HudMetrics.averageKhz(before, after)) + } + + @Test fun theFirstSampleOrAChangedTableFallsBack() { + val after = arrayOf(freqs, longArrayOf(1L, 2L, 3L)) + assertEquals(-1L, HudMetrics.averageKhz(null, after)) + assertEquals(-1L, HudMetrics.averageKhz(arrayOf(longArrayOf(1L), longArrayOf(0L)), after)) + assertEquals(-1L, HudMetrics.averageKhz(after, after)) + } + + @Test fun theCpuClockIsTheFastestCore() { + assertEquals(2_803, HudMetrics.fastestCoreMhz(intArrayOf(902, 2_803, 1_459))) + assertEquals(null, HudMetrics.fastestCoreMhz(intArrayOf(0, 0))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt index 724275fd35..20e83499e8 100644 --- a/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt @@ -81,6 +81,21 @@ class FrameStatsTest { assertEquals(0, stats.slowFrames(now, 60_000_000_000L)) } + @Test fun guestFrameTimesMoveByThePausedSessionsClockShift() { + val control = java.io.File.createTempFile("bl-clock", null) + try { + control.writeBytes(java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.LITTLE_ENDIAN).putLong(62_283_930_706L).array()) + val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames"), clockControl = control) + assertEquals(62_283_930_706L, feed.guestClockShift(1_000_000_000L, 1_000_000_000L)) + control.writeBytes(java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.LITTLE_ENDIAN).putLong(70_000_000_000L).array()) + assertEquals(62_283_930_706L, feed.guestClockShift(1_050_000_000L, 1_000_000_000L)) + assertEquals(70_000_000_000L, feed.guestClockShift(1_200_000_000L, 100_000_000L)) + assertEquals(0L, GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames")).guestClockShift(0L, 0L)) + } finally { + control.delete() + } + } + @Test fun compositorFramesDoNotCountAsLiveGamescopeFrames() { val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames")) var now = 1_000_000_000L