mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-02 20:21:59 -05:00
fix(audio): fall back to standard AAudio and bound startup restarts (#3514)
Fall back to standard audio mode after low-latency failures and cap consecutive startup restarts. On the Pocket Fit Elite, the exact locally signed PR build accepted playback in both DirectAudio modes. The Samsung-specific failure did not reproduce on that device.
This commit is contained in:
1 parent
ec281db0d1
commit
5d05c36033
2 files changed
+193
-18
No files matched your search
@@ -12,6 +12,7 @@ import com.droiddeck.launcher.core.TarZst;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
@@ -36,9 +37,15 @@ public class PulseAudioComponent extends SessionPart {
|
||||
private final HostLifecycle host = new HostLifecycle(Process::killProcess);
|
||||
|
||||
static final class HostLifecycle {
|
||||
static final int MAX_STARTUP_CRASH_RESTARTS = 4;
|
||||
private static final long[] STARTUP_RESTART_DELAYS_MS = {250L, 1000L, 2000L, 4000L};
|
||||
|
||||
volatile int pid = -1;
|
||||
private long generation;
|
||||
private long launches;
|
||||
private boolean preferStandardPerformanceMode;
|
||||
private boolean sinkReady;
|
||||
private int startupCrashRestarts;
|
||||
private final IntConsumer terminate;
|
||||
final ReentrantReadWriteLock commands = new ReentrantReadWriteLock();
|
||||
|
||||
@@ -48,6 +55,9 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
synchronized long begin() {
|
||||
stop();
|
||||
preferStandardPerformanceMode = false;
|
||||
sinkReady = false;
|
||||
startupCrashRestarts = 0;
|
||||
return generation;
|
||||
}
|
||||
|
||||
@@ -55,6 +65,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
generation++;
|
||||
if (pid > 1) terminate.accept(pid);
|
||||
pid = -1;
|
||||
sinkReady = false;
|
||||
}
|
||||
|
||||
boolean launch(long expected, IntSupplier launch) {
|
||||
@@ -63,6 +74,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
synchronized (this) {
|
||||
if (expected != generation) return false;
|
||||
launches++;
|
||||
sinkReady = false;
|
||||
pid = launch.getAsInt();
|
||||
return true;
|
||||
}
|
||||
@@ -93,11 +105,45 @@ public class PulseAudioComponent extends SessionPart {
|
||||
return token == launches && pid > 1;
|
||||
}
|
||||
|
||||
synchronized boolean preferStandardPerformanceMode() {
|
||||
return preferStandardPerformanceMode;
|
||||
}
|
||||
|
||||
synchronized void markLowLatencyFailed(long token) {
|
||||
if (token == launches && pid > 1) preferStandardPerformanceMode = true;
|
||||
}
|
||||
|
||||
synchronized void markSinkReady(long token) {
|
||||
if (token == launches && pid > 1) {
|
||||
sinkReady = true;
|
||||
startupCrashRestarts = 0;
|
||||
}
|
||||
}
|
||||
|
||||
synchronized boolean exited(long expected) {
|
||||
if (expected != generation || pid <= 1) return false;
|
||||
pid = -1;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether a dead host should be restarted and after how many milliseconds.
|
||||
* Returns 0 for immediate recovery of a host that had a working sink, a positive backoff
|
||||
* while falling back to standard AAudio mode after a startup crash, or -1 to stop retrying.
|
||||
*/
|
||||
synchronized long nextRestartDelayMs(long expected) {
|
||||
if (expected != generation) return -1L;
|
||||
if (sinkReady) {
|
||||
sinkReady = false;
|
||||
startupCrashRestarts = 0;
|
||||
return 0L;
|
||||
}
|
||||
preferStandardPerformanceMode = true;
|
||||
if (startupCrashRestarts >= MAX_STARTUP_CRASH_RESTARTS) return -1L;
|
||||
long delay = STARTUP_RESTART_DELAYS_MS[Math.min(startupCrashRestarts, STARTUP_RESTART_DELAYS_MS.length - 1)];
|
||||
startupCrashRestarts++;
|
||||
return delay;
|
||||
}
|
||||
}
|
||||
|
||||
public PulseAudioComponent(Context context) {
|
||||
@@ -167,11 +213,14 @@ public class PulseAudioComponent extends SessionPart {
|
||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||
new File(micFifoPath).delete();
|
||||
}
|
||||
boolean standardMode = host.preferStandardPerformanceMode();
|
||||
String initialPerformanceMode = standardMode ? "0" : "1";
|
||||
ArrayList<String> config = new ArrayList<>();
|
||||
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
|
||||
+ socket().getAbsolutePath() + "\"");
|
||||
config.add(".nofail");
|
||||
config.add("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);
|
||||
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode="
|
||||
+ initialPerformanceMode + " adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
|
||||
config.add("set-default-sink DirectAudio");
|
||||
config.add(".fail");
|
||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||
@@ -197,7 +246,25 @@ public class PulseAudioComponent extends SessionPart {
|
||||
final java.io.PrintWriter out = openLog();
|
||||
if (!host.launch(generation, () -> HostProcess.startUncounted(command, env.toArray(new String[0]), workingDir, status -> {
|
||||
if (host.exited(generation)) {
|
||||
Log.w(TAG, "audio host exited with status " + status + "; restarting");
|
||||
long delayMs = host.nextRestartDelayMs(generation);
|
||||
if (delayMs < 0) {
|
||||
String msg = "audio host exited with status " + status
|
||||
+ " before a client sink came up too many times; not restarting again in this session";
|
||||
Log.w(TAG, msg);
|
||||
note(out, msg);
|
||||
return;
|
||||
}
|
||||
Log.w(TAG, "audio host exited with status " + status + "; restarting"
|
||||
+ (host.preferStandardPerformanceMode() ? " with standard AAudio mode" : "")
|
||||
+ (delayMs > 0 ? " in " + delayMs + " ms" : ""));
|
||||
if (delayMs > 0) {
|
||||
try {
|
||||
Thread.sleep(delayMs);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
start(generation);
|
||||
}
|
||||
},
|
||||
@@ -211,6 +278,24 @@ public class PulseAudioComponent extends SessionPart {
|
||||
guard.start();
|
||||
}
|
||||
|
||||
private boolean loadDirectAudioSink(long token, String performanceMode) {
|
||||
if ("0".equals(performanceMode)) pactlOk(token, "unload-module", "module-directaudio-native-sink");
|
||||
String loaded = pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio",
|
||||
"performance_mode=" + performanceMode,
|
||||
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls);
|
||||
if (loaded == null) return false;
|
||||
if (pactlOk(token, "set-default-sink", "DirectAudio")) return true;
|
||||
String moduleId = loaded.trim();
|
||||
pactlOk(token, "unload-module", moduleId.matches("\\d+") ? moduleId : "module-directaudio-native-sink");
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean loadPlainAAudioSink(long token, String performanceMode) {
|
||||
return pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
|
||||
"performance_mode=" + performanceMode, "adaptive=1", "volume=1.0", "control_dir=" + deviceControls)
|
||||
&& pactlOk(token, "set-default-sink", "AAudioSink");
|
||||
}
|
||||
|
||||
private void ensureClientSink(java.io.PrintWriter out, long token) {
|
||||
try {
|
||||
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
|
||||
@@ -232,27 +317,42 @@ public class PulseAudioComponent extends SessionPart {
|
||||
if (sinks == null) {
|
||||
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
|
||||
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
|
||||
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
|
||||
host.markSinkReady(token);
|
||||
line = "== client sink: DirectAudio (module-directaudio-native-sink"
|
||||
+ (host.preferStandardPerformanceMode() ? ", standard mode" : "") + ")";
|
||||
} else {
|
||||
// AAudio can refuse the first open with AAUDIO_ERROR_DISCONNECTED while Android is
|
||||
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
|
||||
// try DirectAudio again, then the plain sink, a few times over ten seconds.
|
||||
// still switching the output route (Galaxy S24 FE) or when low-latency MMAP output
|
||||
// is rejected by the HAL (Samsung One UI). Retry low-latency once if it hasn't been
|
||||
// disqualified yet, then fall back to performance_mode=0 (non-MMAP) on DirectAudio
|
||||
// before trying the plain AAudio sink.
|
||||
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 (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 (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;
|
||||
if (!host.live(token)) break;
|
||||
if (attempt == 1 && !host.preferStandardPerformanceMode()) {
|
||||
if (loadDirectAudioSink(token, "1")) {
|
||||
loadedAs = "DirectAudio on attempt " + attempt;
|
||||
break;
|
||||
}
|
||||
if (!host.live(token)) break;
|
||||
host.markLowLatencyFailed(token);
|
||||
}
|
||||
if (loadDirectAudioSink(token, "0")) {
|
||||
loadedAs = "DirectAudio (standard mode) on attempt " + attempt;
|
||||
} else if (host.live(token) && loadPlainAAudioSink(token, "0")) {
|
||||
loadedAs = "the plain AAudio sink (AAudioSink, standard mode) on attempt " + attempt;
|
||||
}
|
||||
}
|
||||
line = loadedAs != null ? "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs
|
||||
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
|
||||
+ " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
|
||||
if (loadedAs != null) {
|
||||
host.markSinkReady(token);
|
||||
line = "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs;
|
||||
} else if (!host.live(token)) {
|
||||
line = "== client sink: audio host exited during sink recovery";
|
||||
} else {
|
||||
line = "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
|
||||
+ " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
|
||||
}
|
||||
Log.w(TAG, line);
|
||||
}
|
||||
Log.i(TAG, line);
|
||||
@@ -407,11 +507,22 @@ public class PulseAudioComponent extends SessionPart {
|
||||
continue;
|
||||
}
|
||||
File destination = new File(workingDir, lib);
|
||||
File temp = null;
|
||||
try (InputStream in = resource.openStream()) {
|
||||
Files.copy(in, destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
FileUtils.chmod(destination, 0771);
|
||||
temp = File.createTempFile(lib + ".", ".tmp", workingDir);
|
||||
Files.copy(in, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
FileUtils.chmod(temp, 0771);
|
||||
try {
|
||||
Files.move(temp.toPath(), destination.toPath(),
|
||||
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException e) {
|
||||
Files.move(temp.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
temp = null;
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "copy " + lib, e);
|
||||
} finally {
|
||||
if (temp != null) temp.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,4 +176,68 @@ class PulseAudioComponentTest {
|
||||
pool.shutdownNow()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun startupCrashDowngradesToStandardModeAndCapsRestartLoop() {
|
||||
val host = PulseAudioComponent.HostLifecycle { }
|
||||
val generation = host.begin()
|
||||
assertFalse(host.preferStandardPerformanceMode())
|
||||
|
||||
var pid = 31500
|
||||
for (i in 0 until PulseAudioComponent.HostLifecycle.MAX_STARTUP_CRASH_RESTARTS) {
|
||||
assertTrue(host.launch(generation) { pid++ })
|
||||
assertTrue(host.exited(generation))
|
||||
val delay = host.nextRestartDelayMs(generation)
|
||||
assertTrue("expected positive backoff on startup crash #$i, got $delay", delay > 0L)
|
||||
assertTrue(host.preferStandardPerformanceMode())
|
||||
}
|
||||
|
||||
// One more crash before any sink comes up must stop the hot crash-restart loop.
|
||||
assertTrue(host.launch(generation) { pid++ })
|
||||
assertTrue(host.exited(generation))
|
||||
assertEquals(-1L, host.nextRestartDelayMs(generation))
|
||||
|
||||
// A fresh session resets both the fallback preference and the crash counter.
|
||||
val next = host.begin()
|
||||
assertFalse(host.preferStandardPerformanceMode())
|
||||
assertTrue(host.launch(next) { pid++ })
|
||||
assertTrue(host.exited(next))
|
||||
assertTrue(host.nextRestartDelayMs(next) > 0L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun healthySinkResetsCrashCounterAndRestartsImmediately() {
|
||||
val host = PulseAudioComponent.HostLifecycle { }
|
||||
val generation = host.begin()
|
||||
|
||||
// First startup crashes -> switches to standard mode with backoff.
|
||||
assertTrue(host.launch(generation) { 31600 })
|
||||
assertTrue(host.exited(generation))
|
||||
assertTrue(host.nextRestartDelayMs(generation) > 0L)
|
||||
assertTrue(host.preferStandardPerformanceMode())
|
||||
|
||||
// Replacement host brings up a working sink -> later runtime exit restarts immediately.
|
||||
assertTrue(host.launch(generation) { 31601 })
|
||||
host.markSinkReady(host.token())
|
||||
assertTrue(host.exited(generation))
|
||||
assertEquals(0L, host.nextRestartDelayMs(generation))
|
||||
assertTrue(host.preferStandardPerformanceMode())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun markLowLatencyFailedIgnoresStaleTokens() {
|
||||
val host = PulseAudioComponent.HostLifecycle { }
|
||||
val generation = host.begin()
|
||||
assertTrue(host.launch(generation) { 31700 })
|
||||
val first = host.token()
|
||||
val next = host.begin()
|
||||
// Before the replacement launches, token still equals launches, but pid is stopped.
|
||||
host.markLowLatencyFailed(first)
|
||||
assertFalse(host.preferStandardPerformanceMode())
|
||||
assertTrue(host.launch(next) { 31701 })
|
||||
host.markLowLatencyFailed(first)
|
||||
assertFalse(host.preferStandardPerformanceMode())
|
||||
host.markLowLatencyFailed(host.token())
|
||||
assertTrue(host.preferStandardPerformanceMode())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user