From 4f8a7c559667a9c9b63198058184494b4e74e9d0 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:43:09 -0400 Subject: [PATCH] fix: let the device sleep while a session is suspended (#1220) * fix: stop the DirectAudio output while the sink is suspended * fix: verify every session thread before reporting suspension * fix: freeze PRoot first and stop each guest thread on suspend --------- Co-authored-by: Detinator10 <8469261+Detinator10@users.noreply.github.com> --- app/src/main/cpp/sdnative/sdnative.c | 10 + .../session/SessionSuspendController.kt | 285 ++++++++----- .../launcher/session/ThreadSignals.kt | 9 + .../session/SessionSuspendControllerTest.kt | 379 ++++++++++++++++++ .../sink/module-directaudio-native-sink.c | 39 +- 5 files changed, 611 insertions(+), 111 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/ThreadSignals.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt diff --git a/app/src/main/cpp/sdnative/sdnative.c b/app/src/main/cpp/sdnative/sdnative.c index c7ec580abb..85e0793b10 100644 --- a/app/src/main/cpp/sdnative/sdnative.c +++ b/app/src/main/cpp/sdnative/sdnative.c @@ -1,5 +1,8 @@ +#include #include #include +#include +#include JNIEXPORT void JNICALL Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env, jclass clazz) { @@ -7,3 +10,10 @@ Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env, (void)clazz; atomic_thread_fence(memory_order_release); } + +JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass clazz, jint tgid, jint tid, jint signal) { + (void)env; + (void)clazz; + return syscall(SYS_tgkill, tgid, tid, signal) == 0 ? 0 : errno; +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt index fbe9084083..d694d67862 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt @@ -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, 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() 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, 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? = 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, ProcessRecord>, root: Int, helpers: List, - 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 = - 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, 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 { + 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, root: ProcessRecord): Map? { + // PRoot can leave the leader stopped while native worker threads keep running. + val tasks = LinkedHashMap() + 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) { + 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): 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 } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/ThreadSignals.kt b/app/src/main/java/com/droiddeck/launcher/session/ThreadSignals.kt new file mode 100644 index 0000000000..e3323ce951 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/ThreadSignals.kt @@ -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 +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt new file mode 100644 index 0000000000..61e95da495 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt @@ -0,0 +1,379 @@ +package com.droiddeck.launcher.session + +import java.io.File +import java.util.concurrent.AbstractExecutorService +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.TimeUnit +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class SessionSuspendControllerTest { + @get:Rule val temporary = TemporaryFolder() + + @Test fun everyWorkerThreadIsStoppedAfterTheRoot() { + for (count in listOf(17, 68)) { + val fixture = fixture(count) + fixture.controller.freeze { assertTrue(it) } + assertTrue(fixture.game.threads.all { it.state == 't' }) + assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= count) + assertEquals(ROOT, fixture.signals.first { it.signal == STOP }.pid) + assertTrue(fixture.now < 1000) + assertEquals(1, fixture.audioSuspends) + } + } + + @Test fun cpuMustBeStableAcrossTwoCompleteSnapshots() { + val fixture = fixture(17) + var changes = 0 + fixture.afterSleep = { + if (fixture.game.threads.all { it.state == 't' } && changes < 3) { + fixture.game.threads.last().cpu++ + changes++ + } + } + fixture.controller.freeze { assertTrue(it) } + assertEquals(3, changes) + assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= 17) + } + + @Test fun reusedTidAndNewThreadMustJoinTheStableInventory() { + val fixture = fixture(17) + var changed = false + fixture.afterSleep = { + if (!changed && fixture.game.threads.all { it.state == 't' }) { + changed = true + fixture.game.threads.last().apply { started++; state = 'S'; cpu = 0 } + fixture.game.threads += Task(500, 9000, 'S') + } + } + fixture.controller.freeze { assertTrue(it) } + assertTrue(changed) + assertTrue(fixture.game.threads.all { it.state == 't' }) + assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= 19) + } + + @Test fun zombieLeaderDoesNotHideRunningWorkers() { + val fixture = fixture(17) + fixture.game.threads.first().state = 'Z' + fixture.sync() + fixture.controller.freeze { assertTrue(it) } + assertEquals('Z', fixture.game.threads.first().state) + assertTrue(fixture.game.threads.drop(1).all { it.state == 't' }) + assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= 16) + } + + @Test fun lateReparentedTraceeIsDiscoveredAndResumed() { + val fixture = fixture(17) + val late = Group(600, 1, ROOT, mutableListOf(Task(600, 6000, 'S'))) + fixture.afterSleep = { + if (fixture.root.threads.first().state == 'T' && late !in fixture.groups) fixture.groups += late + } + fixture.controller.freeze { assertTrue(it) } + assertEquals('t', late.threads.first().state) + fixture.controller.resume { assertTrue(it) } + assertEquals('S', late.threads.first().state) + } + + @Test fun descendantHelperKeepsRootStopAndResumeOrdering() { + val fixture = fixture(17) + val helper = Group(700, ROOT, 0, mutableListOf(Task(700, 7000, 'S'))) + fixture.groups += helper + fixture.helpers += helper.pid + fixture.sync() + fixture.controller.freeze { assertTrue(it) } + val stops = fixture.signals.filter { it.signal == STOP } + assertTrue(stops.indexOfFirst { it.pid == ROOT } < stops.indexOfFirst { it.pid == helper.pid }) + val before = fixture.signals.size + fixture.controller.resume { assertTrue(it) } + assertEquals(listOf(ROOT, helper.pid, GAME), fixture.signals.drop(before).take(3).map { it.pid }) + } + + @Test fun retainedHelperDoesNotAdoptAReusedPidOnRefreeze() { + val fixture = fixture(17) + val helper = Group(700, 9000, 0, mutableListOf(Task(700, 7000, 'S'))) + fixture.groups += helper + fixture.helpers += helper.pid + fixture.sync() + fixture.controller.freeze { assertTrue(it) } + fixture.blockGameContinue = true + fixture.controller.resume { assertFalse(it) } + helper.threads.first().apply { started++; state = 'S' } + fixture.sync() + val before = fixture.signals.size + fixture.controller.freeze { assertTrue(it) } + assertFalse(fixture.signals.drop(before).any { it.pid == helper.pid }) + } + + @Test fun timeoutRollsBackAllKnownProcessesAndAudio() { + val fixture = fixture(17) + fixture.neverStop = true + fixture.controller.freeze { assertFalse(it) } + assertTrue(fixture.now <= 8100) + assertEquals(ROOT, fixture.signals.first { it.signal == CONT }.pid) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + assertEquals(1, fixture.audioResumes) + } + + @Test fun missingKnownStatCannotBeMistakenForAnExitedProcess() { + val fixture = fixture(17) + fixture.afterSleep = { + if (fixture.root.threads.first().state == 'T') fixture.missingGameStat = true + } + fixture.controller.freeze { assertFalse(it) } + assertEquals(1, fixture.audioResumes) + fixture.missingGameStat = false + fixture.sync() + fixture.controller.resume { assertTrue(it) } + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + + @Test fun unavailableOrEmptyThreadInventoryCannotReportSuccess() { + for (empty in listOf(false, true)) { + val fixture = fixture(17) + fixture.emptyGameTasks = empty + fixture.missingGameTasks = !empty + fixture.sync() + fixture.controller.freeze { assertFalse(it) } + assertEquals(1, fixture.audioResumes) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + } + + @Test fun disappearingRootFailsAndStillResumesKnownChildren() { + val fixture = fixture(17) + fixture.afterSleep = { + if (fixture.root.threads.first().state == 'T') fixture.rootGone = true + } + fixture.controller.freeze { assertFalse(it) } + assertTrue(fixture.game.threads.all { it.state == 'S' }) + assertEquals(1, fixture.audioResumes) + } + + @Test fun replacementRootIsNeverStoppedOrContinued() { + val fixture = fixture(17) + var atReplacement = -1 + fixture.afterSleep = { + if (atReplacement < 0 && fixture.root.threads.first().state == 'T') { + atReplacement = fixture.signals.size + fixture.root.threads.first().apply { started++; state = 'S' } + } + } + fixture.controller.freeze { assertFalse(it) } + assertTrue(atReplacement > 0) + assertFalse(fixture.signals.drop(atReplacement).any { it.pid == ROOT }) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + + @Test fun reusedChildPidIsNotContinuedDuringResume() { + val fixture = fixture(17) + fixture.controller.freeze { assertTrue(it) } + fixture.game.threads.first().apply { started++; state = 'S' } + fixture.game.parent = 1 + fixture.game.tracer = 0 + fixture.sync() + val before = fixture.signals.size + fixture.controller.resume { assertTrue(it) } + assertFalse(fixture.signals.drop(before).any { it.pid == GAME }) + } + + @Test fun closeCancelsFreezeAndRestoresSavedRootAfterServiceClearsIt() { + val executor = QueueExecutor() + val fixture = fixture(68, executor) + var closed = false + var requested = false + fixture.afterSleep = { + if (!requested && fixture.root.threads.first().state == 'T') { + requested = true + fixture.rootPid = -1 + fixture.controller.closeAndResume { closed = true } + } + } + fixture.controller.freeze { assertFalse(it) } + executor.drain() + assertTrue(closed) + assertTrue(executor.isShutdown) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + assertEquals(1, fixture.audioResumes) + } + + @Test fun successfulFreezeIsRecheckedAndAudioIsReassertedAfterFailedResume() { + val fixture = fixture(17) + fixture.controller.freeze { assertTrue(it) } + fixture.blockGameContinue = true + fixture.controller.resume { assertFalse(it) } + assertEquals(1, fixture.audioResumes) + fixture.blockGameContinue = false + fixture.game.threads.last().state = 'S' + fixture.sync() + fixture.controller.freeze { assertTrue(it) } + assertTrue(fixture.game.threads.all { it.state == 't' }) + assertEquals(2, fixture.audioSuspends) + } + + @Test fun failedRollbackCanBeRefrozenAndAudioIsSuspendedAgain() { + val fixture = fixture(17) + fixture.neverStop = true + fixture.blockGameContinue = true + fixture.controller.freeze { assertFalse(it) } + fixture.neverStop = false + fixture.blockGameContinue = false + fixture.controller.freeze { assertTrue(it) } + assertTrue(fixture.game.threads.all { it.state == 't' }) + assertEquals(2, fixture.audioSuspends) + assertEquals(1, fixture.audioResumes) + } + + @Test fun repeatedFreezeResumeKeepsOriginalRootFirstOrdering() { + val fixture = fixture(17) + repeat(2) { + fixture.controller.freeze { assertTrue(it) } + val before = fixture.signals.size + fixture.controller.resume { assertTrue(it) } + assertEquals(ROOT, fixture.signals.drop(before).first().pid) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + fixture.controller.freeze { assertTrue(it) } + fixture.rootPid = -1 + var closed = false + fixture.controller.closeAndResume { closed = true } + assertTrue(closed) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + + @Test fun rejectedExecutorDoesNotFreezeOnTheCallingThread() { + val executor = QueueExecutor().apply { shutdown() } + val fixture = fixture(17, executor) + fixture.controller.freeze { assertFalse(it) } + assertTrue(fixture.signals.isEmpty()) + assertEquals(0, fixture.audioSuspends) + } + + private fun fixture(count: Int, executor: QueueExecutor = InlineExecutor()) = + Fixture(temporary.newFolder(), count, executor) + + private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0) + private data class Group(val pid: Int, var parent: Int, var tracer: Int, val threads: MutableList) + private data class SentSignal(val pid: Int, val signal: Int) + + private class Fixture(val proc: File, count: Int, executor: QueueExecutor) { + val root = Group(ROOT, 9000, 0, mutableListOf(Task(ROOT, 1000, 'S'))) + val game = Group(GAME, ROOT, ROOT, MutableList(count) { Task(GAME + it, 2000L + it, 'S') }) + val groups = mutableListOf(root, game) + val helpers = mutableListOf() + val signals = mutableListOf() + var rootPid = ROOT + var now = 0L + var audioSuspends = 0 + var audioResumes = 0 + var neverStop = false + var blockGameContinue = false + var missingGameStat = false + var missingGameTasks = false + var emptyGameTasks = false + var rootGone = false + var afterSleep: (() -> Unit)? = null + private var continuing = false + val controller = SessionSuspendController( + { rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ }, + proc, ::signal, ::threadSignal, ::sleep, { now }, executor, + ) + + init { sync() } + + private fun signal(pid: Int, signal: Int) { + signals += SentSignal(pid, signal) + val group = groups.first { it.pid == pid } + if (signal == STOP) { + continuing = false + if (pid == ROOT) group.threads.forEach { it.state = 'T' } + else group.threads.firstOrNull { + it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last()) + }?.state = 't' + } else if (signal == CONT) { + continuing = true + if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' } + } + sync() + } + + private fun threadSignal(pid: Int, tid: Int, signal: Int) { + signals += SentSignal(pid, signal) + val task = groups.first { it.pid == pid }.threads.first { it.tid == tid } + if (signal == STOP && task.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && task == game.threads.last())) { + task.state = 't' + } + sync() + } + + private fun sleep(millis: Long) { + now += millis + if (root.threads.first().state != 'T' && !continuing) game.threads.forEach { + if (it.state != 'Z') { it.state = 'S'; it.cpu++ } + } + afterSleep?.invoke() + sync() + } + + fun sync() { + for (group in groups) { + val dir = File(proc, group.pid.toString()) + if (group == root && rootGone) { dir.deleteRecursively(); continue } + dir.mkdirs() + val stat = File(dir, "stat") + if (group == game && missingGameStat) stat.delete() + else stat.writeText(stat(group, group.threads.first())) + File(dir, "status").writeText("TracerPid: ${group.tracer}\n") + val taskDir = File(dir, "task") + if (group == game && missingGameTasks) { taskDir.deleteRecursively(); continue } + taskDir.mkdirs() + if (group == game && emptyGameTasks) { taskDir.listFiles().orEmpty().forEach { it.deleteRecursively() }; continue } + for (task in group.threads) { + val entry = File(taskDir, task.tid.toString()).apply { mkdirs() } + File(entry, "stat").writeText(stat(group, task)) + } + } + } + + private fun stat(group: Group, task: Task): String { + val fields = MutableList(20) { "0" } + fields[0] = task.state.toString() + fields[1] = group.parent.toString() + fields[11] = task.cpu.toString() + fields[19] = task.started.toString() + return "${task.tid} (fixture (worker)) ${fields.joinToString(" ")}" + } + } + + private open class QueueExecutor : AbstractExecutorService() { + private val queue = ArrayDeque() + private var stopped = false + override fun execute(command: Runnable) { + if (stopped) throw RejectedExecutionException() + queue.add(command) + } + fun drain() { while (queue.isNotEmpty()) queue.removeFirst().run() } + override fun shutdown() { stopped = true } + override fun shutdownNow(): MutableList { + stopped = true + return queue.toMutableList().also { queue.clear() } + } + override fun isShutdown() = stopped + override fun isTerminated() = stopped && queue.isEmpty() + override fun awaitTermination(timeout: Long, unit: TimeUnit) = isTerminated + } + + private class InlineExecutor : QueueExecutor() { + override fun execute(command: Runnable) { super.execute(command); drain() } + } + + private companion object { + const val ROOT = 100 + const val GAME = 200 + const val STOP = 19 + const val CONT = 18 + } +} diff --git a/tools/directaudio/sink/module-directaudio-native-sink.c b/tools/directaudio/sink/module-directaudio-native-sink.c index 208dac9ac5..ca3eb01cc5 100644 --- a/tools/directaudio/sink/module-directaudio-native-sink.c +++ b/tools/directaudio/sink/module-directaudio-native-sink.c @@ -126,6 +126,7 @@ struct userdata { unsigned int decay_backoff, cb_count, wd_last_cb; int reopen_running, reopen_redo; int consuming, primed, starved; + int suspended; volatile int dead; /* what the IO thread last logged, so engine changes made on the AAudio thread get a line */ @@ -302,6 +303,7 @@ static void out_error_cb(AAudioStream *aq, void *user, aaudio_result_t error) { struct userdata *u = user; if (aq != __atomic_load_n(&u->aq, __ATOMIC_SEQ_CST)) return; + if (__atomic_load_n(&u->suspended, __ATOMIC_SEQ_CST)) return; /* A disconnected stream (headphones plugged or unplugged, a Bluetooth route coming or going) * can never be restarted: it has to be closed and a new one opened on the current route. */ if (error != AAUDIO_ERROR_DISCONNECTED && @@ -400,6 +402,8 @@ static void *reopen_thread(void *user) { pthread_mutex_lock(&u->lock); old = u->aq; __atomic_store_n(&u->aq, neu, __ATOMIC_SEQ_CST); + if (__atomic_load_n(&u->suspended, __ATOMIC_SEQ_CST)) + AAudioStream_requestStop(neu); pthread_mutex_unlock(&u->lock); } else pa_log("directaudio-native-sink: reopen failed; keeping the old stream"); @@ -575,6 +579,34 @@ static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offse return pa_sink_process_msg(o, code, data, offset, chunk); } +/* A started AAudio stream keeps audioserver's AudioMix wake lock held, so the device never + * suspends while the session sleeps: stop it, and the IO thread's timer, until the sink reopens. */ +static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) { + struct userdata *u = s->userdata; + aaudio_result_t res = AAUDIO_OK; + + if (new_state == PA_SINK_SUSPENDED && !u->suspended) { + pthread_mutex_lock(&u->lock); + __atomic_store_n(&u->suspended, 1, __ATOMIC_SEQ_CST); + if (u->aq) AAudioStream_requestStop(u->aq); + pthread_mutex_unlock(&u->lock); + pa_rtpoll_set_timer_disabled(u->rtpoll); + pa_log("directaudio-native-sink: suspended; output stopped"); + } else if (PA_SINK_IS_OPENED(new_state) && u->suspended) { + pthread_mutex_lock(&u->lock); + __atomic_store_n(&u->suspended, 0, __ATOMIC_SEQ_CST); + u->primed = 0; + __atomic_store_n(&u->last_cb_ns, now_ns(), __ATOMIC_SEQ_CST); + u->wd_last_tick_ns = 0; + if (u->aq) res = AAudioStream_requestStart(u->aq); + pthread_mutex_unlock(&u->lock); + if (res != AAUDIO_OK || !u->aq) request_reopen(u, "resume"); + pa_rtpoll_set_timer_relative(u->rtpoll, 0); + pa_log("directaudio-native-sink: resumed"); + } + return 0; +} + static void thread_func(void *userdata) { struct userdata *u = userdata; @@ -592,8 +624,10 @@ static void thread_func(void *userdata) { /* Half a burst between visits, never blocking on the stream: clients' audio reaches this * thread as messages pa_rtpoll_run handles, and a thread stuck in a write or a wait lets * them run dry (the crackle #338 fixed). */ - service_ring(u); - pa_rtpoll_set_timer_relative(u->rtpoll, PA_MAX(frames_to_usec(u, u->burst) / 2, PA_USEC_PER_MSEC)); + if (!u->suspended) { + service_ring(u); + pa_rtpoll_set_timer_relative(u->rtpoll, PA_MAX(frames_to_usec(u, u->burst) / 2, PA_USEC_PER_MSEC)); + } if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) goto fail; @@ -727,6 +761,7 @@ int pa__init(pa_module *m) { goto fail; } u->sink->parent.process_msg = sink_process_msg; + u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb; u->sink->userdata = u; pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq); pa_sink_set_rtpoll(u->sink, u->rtpoll);