From d94906bd9c384355acc97c6e6da90d4894eab918 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Wed, 18 Nov 2026 12:55:25 -0500 Subject: [PATCH] fix(audio): hold host restarts until an in-flight sink guard command finishes (#2821) * fix(audio): hold host restarts until an in-flight sink guard command finishes * fix(audio): judge sink guard commands by exit status and reap timed-out pactl * test(audio): hold the sink guard command until the test has checked the queued restart * test(audio): bound the stop check so a blocking stop fails instead of hanging * test(audio): bound the exit check while the sink guard command is paused --- .../launcher/audio/PulseAudioComponent.java | 87 +++++++++++++------ .../launcher/audio/PulseAudioComponentTest.kt | 74 ++++++++++++++++ 2 files changed, 134 insertions(+), 27 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java index 6aa7d13456..53a0a6aacf 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java @@ -16,8 +16,10 @@ import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.IntConsumer; import java.util.function.IntSupplier; +import java.util.function.Supplier; public class PulseAudioComponent extends SessionPart { private static final String TAG = "PulseAudio"; @@ -38,6 +40,7 @@ public class PulseAudioComponent extends SessionPart { private long generation; private long launches; private final IntConsumer terminate; + final ReentrantReadWriteLock commands = new ReentrantReadWriteLock(); HostLifecycle(IntConsumer terminate) { this.terminate = terminate; @@ -54,11 +57,27 @@ public class PulseAudioComponent extends SessionPart { pid = -1; } - synchronized boolean launch(long expected, IntSupplier launch) { - if (expected != generation) return false; - launches++; - pid = launch.getAsInt(); - return true; + boolean launch(long expected, IntSupplier launch) { + commands.writeLock().lock(); + try { + synchronized (this) { + if (expected != generation) return false; + launches++; + pid = launch.getAsInt(); + return true; + } + } finally { + commands.writeLock().unlock(); + } + } + + T command(long token, Supplier command) { + commands.readLock().lock(); + try { + return live(token) ? command.get() : null; + } finally { + commands.readLock().unlock(); + } } synchronized boolean current(long expected) { @@ -218,13 +237,13 @@ public class PulseAudioComponent extends SessionPart { String loadedAs = null; for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) { try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } - if (pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1", - "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null - && pactlFor(token, "set-default-sink", "DirectAudio") != null) { + if (pactlOk(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1", + "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) + && pactlOk(token, "set-default-sink", "DirectAudio")) { loadedAs = "DirectAudio on attempt " + attempt; - } else if (pactlFor(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink", - "performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null - && pactlFor(token, "set-default-sink", "AAudioSink") != null) { + } else if (pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink", + "performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) + && pactlOk(token, "set-default-sink", "AAudioSink")) { loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt; } } @@ -248,14 +267,24 @@ public class PulseAudioComponent extends SessionPart { } private String pactlFor(long token, String... args) { - return host.live(token) ? pactl(args) : null; + return host.command(token, () -> pactl(true, args)); } - /** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */ - private String pactl(String... args) { + private boolean pactlOk(long token, String... args) { + return host.command(token, () -> pactl(false, args)) != null; + } + + private static void reap(java.lang.Process process) throws InterruptedException { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + } + + /** Runs pactl against this daemon; its stdout when captured (empty otherwise), or null when it failed or timed out. */ + private String pactl(boolean capture, String... args) { File pactl = new File(workingDir, "pactl"); if (!pactl.isFile() || host.pid <= 1) return null; java.lang.Process process = null; + File output = null; try { File modules = new File(workingDir, "modules/arm64"); ArrayList cmd = new ArrayList<>(); @@ -268,29 +297,33 @@ public class PulseAudioComponent extends SessionPart { builder.environment().put("HOME", workingDir.getAbsolutePath()); builder.environment().put("TMPDIR", workingDir.getAbsolutePath()); builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath()); - process = builder.start(); - String output; - try (InputStream in = process.getInputStream(); - java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream()) { - byte[] buf = new byte[4096]; - int n; - while ((n = in.read(buf)) != -1) { - outStream.write(buf, 0, n); - } - output = outStream.toString(java.nio.charset.StandardCharsets.UTF_8.name()); + if (capture) { + output = File.createTempFile("pactl", ".out", workingDir); + builder.redirectOutput(output); + } else { + builder.redirectOutput(new File("/dev/null")); } + process = builder.start(); if (!process.waitFor(5, TimeUnit.SECONDS)) { - process.destroyForcibly(); + reap(process); return null; } - return process.exitValue() == 0 ? output : null; + if (process.exitValue() != 0) return null; + return capture ? new String(Files.readAllBytes(output.toPath()), java.nio.charset.StandardCharsets.UTF_8) : ""; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } catch (Throwable t) { return null; } finally { - if (process != null && process.isAlive()) process.destroyForcibly(); + if (process != null && process.isAlive()) { + try { + reap(process); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + if (output != null) output.delete(); } } diff --git a/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt index d06cc52d03..63c1003b4f 100644 --- a/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt @@ -68,6 +68,80 @@ class PulseAudioComponentTest { assertFalse(host.live(host.token())) } + @Test + fun aRestartWaitsForAnInFlightSinkGuardCommand() { + val killed = mutableListOf() + val host = PulseAudioComponent.HostLifecycle { killed.add(it) } + val generation = host.begin() + host.launch(generation) { 31463 } + val first = host.token() + val checked = CountDownLatch(1) + val resume = CountDownLatch(1) + val pool = Executors.newFixedThreadPool(2) + try { + val command = pool.submit { + host.command(first) { + checked.countDown() + resume.await() + "old host" + } + } + assertTrue(checked.await(5, TimeUnit.SECONDS)) + assertTrue(pool.submit { host.exited(generation) }.get(5, TimeUnit.SECONDS)) + val launched = CountDownLatch(1) + val restart = pool.submit { + host.launch(generation) { + launched.countDown() + 31464 + } + } + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (!host.commands.hasQueuedThreads() && !restart.isDone && System.nanoTime() < deadline) Thread.yield() + assertTrue(host.commands.hasQueuedThreads()) + assertEquals(1L, launched.count) + assertFalse(restart.isDone) + resume.countDown() + assertEquals("old host", command.get(5, TimeUnit.SECONDS)) + assertTrue(restart.get(5, TimeUnit.SECONDS)) + assertEquals(31464, host.pid) + assertEquals(null, host.command(first) { error("stale guard reached the replacement host") }) + assertEquals("new host", host.command(host.token()) { "new host" }) + assertTrue(killed.isEmpty()) + } finally { + resume.countDown() + pool.shutdownNow() + } + } + + @Test + fun stopIsNotHeldUpByAnInFlightSinkGuardCommand() { + val killed = mutableListOf() + val host = PulseAudioComponent.HostLifecycle { killed.add(it) } + host.launch(host.begin()) { 31463 } + val token = host.token() + val checked = CountDownLatch(1) + val resume = CountDownLatch(1) + val pool = Executors.newFixedThreadPool(2) + try { + val command = pool.submit { + host.command(token) { + checked.countDown() + resume.await() + "done" + } + } + assertTrue(checked.await(5, TimeUnit.SECONDS)) + pool.submit { host.stop() }.get(5, TimeUnit.SECONDS) + assertEquals(listOf(31463), killed) + assertFalse(host.live(token)) + resume.countDown() + assertEquals("done", command.get(5, TimeUnit.SECONDS)) + } finally { + resume.countDown() + pool.shutdownNow() + } + } + @Test fun failedLaunchDoesNotRestartOrTerminateAnInvalidPid() { val host = PulseAudioComponent.HostLifecycle { error("invalid pid terminated") }