Compare commits

..
Author SHA1 Message Date
The412Banner 5c8a54ef95 fix(agent): keep replies with tables still while the theme color cycles
The Markdown renderer baked the link and code colors into its spans and
was rebuilt on every color step, so each step parsed the reply again and
reset its table rows, which measure one line high until drawn. Link and
code colors now come from the TextView and a live code theme, so a color
step only recolors the reply.
2026-11-29 15:52:51 +00:00
8 changed files with 149 additions and 300 deletions

No files matched your search

@@ -18,18 +18,15 @@ public class DirectAudioRelayComponent extends SessionPart {
private File logFile;
private final File micFifoPath;
private volatile int pid = -1;
private final Object stateLock = new Object();
private final Object micLock = new Object();
private boolean micHot;
private boolean outputStopped;
private final File micControl;
private final File outputControl;
public java.util.function.Consumer<Boolean> onMicEnabled;
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
this.socketPath = socketPath;
this.micFifoPath = micFifoPath;
this.micControl = micFifoPath == null ? null : new File(micFifoPath.getParentFile(), "mic-enabled");
this.outputControl = new File(socketPath.getParentFile(), "output-enabled");
}
public void setLogFile(File file) {
@@ -39,11 +36,9 @@ public class DirectAudioRelayComponent extends SessionPart {
@Override
public void start() {
stop();
synchronized (stateLock) {
synchronized (micLock) {
micHot = false;
outputStopped = false;
}
outputControl.delete();
File binary = new File(app().getApplicationInfo().nativeLibraryDir, BINARY);
if (!binary.isFile()) {
Log.w(TAG, "helper missing at " + binary + "; DirectAudio will report itself unavailable");
@@ -72,7 +67,6 @@ public class DirectAudioRelayComponent extends SessionPart {
StringBuilder command = new StringBuilder(binary.getAbsolutePath());
command.append(" --socket ").append(socketPath.getAbsolutePath());
command.append(" --log");
command.append(" --output-control ").append(outputControl.getAbsolutePath());
final boolean withMic = micFifoPath != null && setMicEnabled(true);
if (withMic) {
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
@@ -99,7 +93,6 @@ public class DirectAudioRelayComponent extends SessionPart {
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
trackOutput(line);
if (withMic) trackMic(line);
if (log != null) synchronized (log) { log.println(line); log.flush(); }
});
@@ -108,27 +101,9 @@ public class DirectAudioRelayComponent extends SessionPart {
}
public synchronized boolean setMicEnabled(boolean enabled) {
return micControl != null && writeControl(micControl, enabled);
}
public boolean setOutputEnabled(boolean enabled) {
synchronized (stateLock) {
outputStopped = false;
}
return writeControl(outputControl, enabled);
}
private static boolean writeControl(File control, boolean enabled) {
File next = new File(control.getPath() + ".new");
return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(control);
}
private void trackOutput(String line) {
if (!line.equals("DA-Relay: output enabled=0")) return;
synchronized (stateLock) {
outputStopped = true;
stateLock.notifyAll();
}
if (micControl == null) return false;
File next = new File(micControl.getPath() + ".new");
return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(micControl);
}
private void trackMic(String line) {
@@ -137,28 +112,20 @@ public class DirectAudioRelayComponent extends SessionPart {
}
boolean start = line.startsWith("DA-Relay: mic start ");
if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
synchronized (stateLock) {
synchronized (micLock) {
micHot = start;
stateLock.notifyAll();
micLock.notifyAll();
}
}
public boolean awaitMicReleased(long timeoutMs) {
return await(() -> !micHot, timeoutMs);
}
public boolean awaitOutputStopped(long timeoutMs) {
return pid == -1 || await(() -> outputStopped, timeoutMs);
}
private boolean await(java.util.function.BooleanSupplier done, long timeoutMs) {
long deadline = System.currentTimeMillis() + timeoutMs;
synchronized (stateLock) {
while (!done.getAsBoolean()) {
synchronized (micLock) {
while (micHot) {
long left = deadline - System.currentTimeMillis();
if (left <= 0) return false;
try {
stateLock.wait(left);
micLock.wait(left);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
@@ -903,23 +903,16 @@ class SessionService : Service() {
listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 })
},
suspendAudio = {
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
val relayOutputStopping = relay?.setOutputEnabled(false)
if (relayOutputStopping == false) Log.w(TAG, "could not stop DirectAudio output")
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
if (!pulse.setMicSuspended(true)) Log.w(TAG, "could not suspend microphone source")
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
if (relay != null && !relay.awaitMicReleased(MIC_RELEASE_TIMEOUT_MS)) {
Log.w(TAG, "microphone still open after ${MIC_RELEASE_TIMEOUT_MS} ms; suspending anyway")
}
if (relay != null && relayOutputStopping == true && !relay.awaitOutputStopped(OUTPUT_RELEASE_TIMEOUT_MS)) {
Log.w(TAG, "DirectAudio output still started after ${OUTPUT_RELEASE_TIMEOUT_MS} ms; suspending anyway")
}
},
resumeAudio = {
if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink")
if (!pulse.setMicSuspended(false)) Log.w(TAG, "could not resume microphone source")
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
if (relay?.setOutputEnabled(true) == false) Log.w(TAG, "could not resume DirectAudio output")
},
zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.dd-zram"),
clockControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.dd-clock"),
@@ -2658,7 +2651,6 @@ class SessionService : Service() {
private const val TAG = "SessionService"
private const val TRACER_NICE = -6
private const val MIC_RELEASE_TIMEOUT_MS = 5_000L
private const val OUTPUT_RELEASE_TIMEOUT_MS = 2_000L
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
private const val GAME_PREFIX = "DROIDDECK_GAME_"
private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env"
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.ui
import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.net.Uri
import android.text.Selection
import android.text.Spannable
@@ -22,8 +23,11 @@ import com.droiddeck.launcher.R
import io.noties.markwon.AbstractMarkwonPlugin
import io.noties.markwon.Markwon
import io.noties.markwon.MarkwonConfiguration
import io.noties.markwon.MarkwonSpansFactory
import io.noties.markwon.MarkwonVisitor
import io.noties.markwon.core.MarkwonTheme
import io.noties.markwon.core.spans.CodeBlockSpan
import io.noties.markwon.core.spans.CodeSpan
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin
import io.noties.markwon.ext.tables.TableAwareMovementMethod
import io.noties.markwon.ext.tables.TablePlugin
@@ -35,7 +39,10 @@ import org.commonmark.ext.gfm.tables.TableCell
import org.commonmark.ext.gfm.tables.TableHead
import org.commonmark.ext.gfm.tables.TableRow
import org.commonmark.node.AbstractVisitor
import org.commonmark.node.Code
import org.commonmark.node.CustomNode
import org.commonmark.node.FencedCodeBlock
import org.commonmark.node.IndentedCodeBlock
import org.commonmark.node.Node
@Composable
@@ -46,9 +53,8 @@ internal fun AgentMarkdown(text: String, modifier: Modifier) {
val density = LocalDensity.current
val textSize = with(density) { 15.sp.toPx() }
val lineSpacing = with(density) { 3.sp.toPx() }
val renderer = remember(context, pal.primary2, pal.surfaceVariant, density) {
agentMarkdownRenderer(context, pal.primary2.toArgb(), pal.surfaceVariant.toArgb())
}
val theme = remember(context, pal.id, density) { AgentMarkdownTheme(context) }
val renderer = remember(theme) { agentMarkdownRenderer(context, theme) }
val rendered = remember(renderer, text) { renderer.toMarkdown(text) }
AndroidView(
modifier = modifier,
@@ -62,12 +68,25 @@ internal fun AgentMarkdown(text: String, modifier: Modifier) {
view.setLinkTextColor(pal.primary2.toArgb())
view.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, textSize)
view.setLineSpacing(lineSpacing, 1f)
val codeBackground = pal.surfaceVariant.toArgb()
if (theme.codeBackground != codeBackground) {
theme.codeBackground = codeBackground
view.invalidate()
}
setAgentMarkdown(view, renderer, rendered)
},
)
}
internal fun agentMarkdownRenderer(context: Context, linkColor: Int, codeBackground: Int): Markwon =
internal class AgentMarkdownTheme(context: Context) : MarkwonTheme(MarkwonTheme.builderWithDefaults(context)) {
var codeBackground = 0
override fun getCodeBackgroundColor(paint: Paint) = codeBackground
override fun getCodeBlockBackgroundColor(paint: Paint) = codeBackground
}
internal fun agentMarkdownRenderer(context: Context, theme: AgentMarkdownTheme): Markwon =
Markwon.builder(context)
.usePlugin(StrikethroughPlugin.create())
.usePlugin(TablePlugin.create(context))
@@ -104,8 +123,10 @@ internal fun agentMarkdownRenderer(context: Context, linkColor: Int, codeBackgro
builder.append(text)
}
override fun configureTheme(builder: MarkwonTheme.Builder) {
builder.linkColor(linkColor).codeBackgroundColor(codeBackground)
override fun configureSpansFactory(builder: MarkwonSpansFactory.Builder) {
builder.setFactory(Code::class.java) { _, _ -> CodeSpan(theme) }
builder.setFactory(FencedCodeBlock::class.java) { _, _ -> CodeBlockSpan(theme) }
builder.setFactory(IndentedCodeBlock::class.java) { _, _ -> CodeBlockSpan(theme) }
}
override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
@@ -1,109 +0,0 @@
package com.droiddeck.launcher.audio
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class DirectAudioOutputTest {
@get:Rule val folder = TemporaryFolder()
@Test fun outputControlIsWrittenWithAndWithoutTheMicrophone() {
for (fifo in listOf(null, File(folder.root, "mic.fifo"))) {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), fifo)
val control = File(folder.root, "output-enabled")
assertTrue(relay.setOutputEnabled(false))
assertEquals("0", control.readText())
assertTrue(relay.setOutputEnabled(true))
assertEquals("1", control.readText())
}
}
@Test fun suspendWaitsForTheRelayToStopItsOutput() {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), File(folder.root, "mic.fifo"))
ReflectionHelpers.setField(relay, "pid", 4242)
assertTrue(relay.setOutputEnabled(false))
assertFalse(relay.awaitOutputStopped(0))
output(relay, "DA-Relay: mic stop (session toggle)")
output(relay, "DA-Relay: output enabled=1")
assertFalse(relay.awaitOutputStopped(0))
output(relay, "DA-Relay: output enabled=0")
assertTrue(relay.awaitOutputStopped(0))
assertTrue(relay.setOutputEnabled(true))
assertFalse(relay.awaitOutputStopped(0))
}
@Test fun lateAcknowledgementReleasesAWaitingSuspend() {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), null)
ReflectionHelpers.setField(relay, "pid", 4242)
assertTrue(relay.setOutputEnabled(false))
val ack = Thread {
Thread.sleep(100)
output(relay, "DA-Relay: output enabled=0")
}
ack.start()
assertTrue(relay.awaitOutputStopped(5_000))
ack.join()
}
@Test fun outputAcknowledgementLeavesTheMicrophoneWait() {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), File(folder.root, "mic.fifo"))
ReflectionHelpers.setField(relay, "pid", 4242)
mic(relay, "DA-Relay: mic start (game wants it, 1 consumer(s))")
output(relay, "DA-Relay: output enabled=0")
assertFalse(relay.awaitMicReleased(0))
mic(relay, "DA-Relay: mic stop (game)")
assertTrue(relay.awaitMicReleased(0))
}
@Test fun relayThatIsNotRunningDoesNotDelaySuspend() {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), null)
assertTrue(relay.setOutputEnabled(false))
assertTrue(relay.awaitOutputStopped(5_000))
}
@Test fun startClearsAStaleStopAndPassesTheOutputControl() {
val context = RuntimeEnvironment.getApplication()
val info = context.applicationInfo
val previous = info.nativeLibraryDir
val nativeDir = folder.newFolder("native")
val args = File(folder.root, "arguments")
File(nativeDir, DirectAudioRelayComponent.BINARY).apply {
writeText("#!/bin/sh\nprintf '%s\\n' \"\$@\" > '${args.path}.new'\nmv '${args.path}.new' '${args.path}'\n")
setExecutable(true)
}
val control = File(folder.root, "output-enabled").apply { writeText("0") }
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), null)
relay.attach(context)
try {
info.nativeLibraryDir = nativeDir.path
relay.start()
val deadline = System.nanoTime() + 3_000_000_000L
while (!args.isFile && System.nanoTime() < deadline) Thread.sleep(10)
assertTrue("Playback helper did not start", args.isFile)
assertFalse(control.exists())
val command = args.readLines()
val at = command.indexOf("--output-control")
assertTrue(at >= 0)
assertEquals(control.absolutePath, command[at + 1])
assertFalse(command.contains("--mic-fifo"))
} finally {
info.nativeLibraryDir = previous
}
}
private fun output(relay: DirectAudioRelayComponent, line: String) = call(relay, "trackOutput", line)
private fun mic(relay: DirectAudioRelayComponent, line: String) = call(relay, "trackMic", line)
private fun call(relay: DirectAudioRelayComponent, method: String, line: String) =
ReflectionHelpers.callInstanceMethod<Unit>(relay, method, ReflectionHelpers.ClassParameter.from(String::class.java, line))
}
@@ -0,0 +1,84 @@
package com.droiddeck.launcher.ui
import android.text.Spanned
import android.text.TextPaint
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
import io.noties.markwon.core.spans.CodeSpan
import io.noties.markwon.ext.tables.TableRowSpan
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.ConscryptMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], application = android.app.Application::class)
@ConscryptMode(ConscryptMode.Mode.OFF)
class AgentMarkdownPaletteTest {
@get:Rule val compose = createRobolectricComposeRule()
private val reply = "Run `build` first\n\n| Step | Result |\n| --- | --- |\n| Build | [PR](https://github.com/owner/repo/pull/1) |\n\nDone"
private var palette by mutableStateOf(Themes.innerGamer(0f))
private fun View.markdownView(): TextView? = when (this) {
is TextView -> this
is ViewGroup -> (0 until childCount).firstNotNullOfOrNull { getChildAt(it).markdownView() }
else -> null
}
private fun showReply(): TextView {
lateinit var root: View
compose.setContent {
root = LocalView.current
CompositionLocalProvider(LocalPalette provides palette) { AgentMarkdown(reply, Modifier) }
}
compose.waitForIdle()
return requireNotNull(root.markdownView())
}
private fun assertColors(view: TextView, expected: Palette) {
assertEquals(expected.primary2.toArgb(), view.paint.linkColor)
val code = TextPaint()
(view.text as Spanned).getSpans(0, view.text.length, CodeSpan::class.java).single().updateDrawState(code)
assertEquals(expected.surfaceVariant.toArgb(), code.bgColor)
}
@Test fun innerGamerHueStepsRecolorTheReplyWithoutRenderingItAgain() {
val view = showReply()
val rendered = view.tag as Spanned
val rows = rendered.getSpans(0, rendered.length, TableRowSpan::class.java).toSet()
assertTrue(rows.isNotEmpty())
for (hue in listOf(3f, 90f, 180f, 357f)) {
palette = Themes.innerGamer(hue)
compose.waitForIdle()
assertSame(rendered, view.tag)
val current = view.text as Spanned
assertEquals(rows, current.getSpans(0, current.length, TableRowSpan::class.java).toSet())
assertColors(view, palette)
}
}
@Test fun switchingThemesRendersTheReplyInTheNewColors() {
val view = showReply()
for (id in listOf(Themes.GRAPHITE, Themes.WHITE_RED, Themes.INNER_GAMER)) {
val before = view.tag
palette = Themes.byId(id)
compose.waitForIdle()
assertNotSame(before, view.tag)
assertColors(view, palette)
}
}
}
@@ -4,6 +4,8 @@ import android.content.Intent
import android.content.ClipboardManager
import android.text.Selection
import android.text.Spannable
import io.noties.markwon.core.spans.CodeBlockSpan
import io.noties.markwon.core.spans.CodeSpan
import io.noties.markwon.ext.tables.TableRowSpan
import android.graphics.Color
import android.text.Spanned
@@ -23,7 +25,7 @@ import org.robolectric.annotation.Config
@ConscryptMode(ConscryptMode.Mode.OFF)
class AgentMarkdownTest {
private val context get() = RuntimeEnvironment.getApplication()
private val renderer get() = agentMarkdownRenderer(context, Color.BLUE, Color.DKGRAY)
private val renderer get() = agentMarkdownRenderer(context, AgentMarkdownTheme(context).apply { codeBackground = Color.DKGRAY })
private fun Spanned.links() = getSpans(0, length, ClickableSpan::class.java).toList()
@Test fun namedPullRequestLinksKeepTheirLabelsAndOpenAnExternalBrowser() {
@@ -85,27 +87,47 @@ class AgentMarkdownTest {
renderer.render(root)
}
@Test fun colorChangesPreserveSelectionAndRefreshLinkSpans() {
@Test fun rendererChangesPreserveSelectionAndLinksFollowTheViewLinkColor() {
val source = "Read [the PR](https://github.com/owner/repo/pull/1)"
val view = TextView(context).apply { setTextIsSelectable(true) }
val original = renderer
setAgentMarkdown(view, original, original.toMarkdown(source))
Selection.setSelection(view.text as Spannable, 5, 11)
val updated = agentMarkdownRenderer(context, Color.RED, Color.LTGRAY)
val updated = agentMarkdownRenderer(context, AgentMarkdownTheme(context).apply { codeBackground = Color.LTGRAY })
val rendered = updated.toMarkdown(source)
setAgentMarkdown(view, updated, rendered)
assertEquals(5, view.selectionStart)
assertEquals(11, view.selectionEnd)
assertSame(rendered, view.tag)
val paint = android.text.TextPaint()
view.setLinkTextColor(Color.RED)
val paint = android.text.TextPaint().apply { set(view.paint) }
(view.text as Spanned).links().single().updateDrawState(paint)
assertEquals(Color.RED, paint.color)
}
@Test fun codeBackgroundsFollowTheThemeWithoutRenderingAgain() {
val theme = AgentMarkdownTheme(context).apply { codeBackground = Color.DKGRAY }
val rendered = agentMarkdownRenderer(context, theme).toMarkdown("Run `inline`\n\n~~~\nblock\n~~~\n\n indented")
theme.codeBackground = Color.RED
val inline = android.text.TextPaint()
rendered.getSpans(0, rendered.length, CodeSpan::class.java).single().updateDrawState(inline)
assertEquals(Color.RED, inline.bgColor)
val blocks = rendered.getSpans(0, rendered.length, CodeBlockSpan::class.java)
assertEquals(2, blocks.size)
for (block in blocks) {
var filled = 0
val canvas = object : android.graphics.Canvas(android.graphics.Bitmap.createBitmap(10, 10, android.graphics.Bitmap.Config.ARGB_8888)) {
override fun drawRect(rect: android.graphics.Rect, paint: android.graphics.Paint) { filled = paint.color }
}
block.drawLeadingMargin(canvas, android.graphics.Paint(), 0, 1, 0, 5, 10, rendered, 0, 1, true, null)
assertEquals(Color.RED, filled)
}
}
@Test fun reversedSelectionsAndCursorsSurviveColorChangesButNotContentChanges() {
val view = TextView(context).apply { setTextIsSelectable(true) }
val original = renderer
val updated = agentMarkdownRenderer(context, Color.RED, Color.LTGRAY)
val updated = agentMarkdownRenderer(context, AgentMarkdownTheme(context).apply { codeBackground = Color.LTGRAY })
setAgentMarkdown(view, original, original.toMarkdown("A long reply"))
for ((start, end) in listOf(8 to 2, 4 to 4)) {
Selection.setSelection(view.text as Spannable, start, end)
-1
View File
@@ -11,7 +11,6 @@ case "$(uname -s)" in
esac
toolchain="$NDK/toolchains/llvm/prebuilt/$host/bin"
patch -d "$source_dir" -p1 < "$repo_root/tools/directaudio/microphone-toggle.patch"
patch -d "$source_dir" -p1 < "$repo_root/tools/directaudio/output-pause.patch"
"$toolchain/aarch64-linux-android28-clang" -O2 -Wl,-z,max-page-size=16384 \
"$source_dir/directaudio-relay.c" -o "$repo_root/app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so" \
-laaudio -llog -pthread
-127
View File
@@ -1,127 +0,0 @@
--- a/directaudio-relay.c
+++ b/directaudio-relay.c
@@ -73,6 +73,9 @@
static const char *g_mic_control;
static int g_mic_enabled = 1;
static pthread_mutex_t g_mic_operations = PTHREAD_MUTEX_INITIALIZER;
+static const char *g_output_control;
+static int g_output_enabled = 1;
+static pthread_mutex_t g_output_operations = PTHREAD_MUTEX_INITIALIZER;
static void rlog(const char *fmt, ...)
{
@@ -495,8 +498,11 @@
AAudioStream_getPerformanceMode(aq), c->share, AAudioStream_getSharingMode(aq),
c->out->target_frames);
- r = AAudioStream_requestStart(aq);
- if (r != AAUDIO_OK) { AAudioStream_close(aq); return r; }
+ if (__atomic_load_n(&g_output_enabled, __ATOMIC_ACQUIRE))
+ {
+ r = AAudioStream_requestStart(aq);
+ if (r != AAUDIO_OK) { AAudioStream_close(aq); return r; }
+ }
__atomic_store_n(&c->last_cb_ns, now_ns(), __ATOMIC_SEQ_CST);
c->wd_last_tick_ns = 0;
@@ -517,6 +523,7 @@
__atomic_store_n(&c->reopen_redo, 0, __ATOMIC_SEQ_CST);
if (c->dead) break;
+ pthread_mutex_lock(&g_output_operations);
if (open_output(c, &neu) == AAUDIO_OK)
{
pthread_mutex_lock(&c->lock);
@@ -532,6 +539,7 @@
AAudioStream_close(old);
RLOG("[%d] reopened output", c->pid);
}
+ pthread_mutex_unlock(&g_output_operations);
if (__atomic_load_n(&c->reopen_redo, __ATOMIC_SEQ_CST)) { usleep(20000); continue; }
__atomic_store_n(&c->reopen_running, 0, __ATOMIC_SEQ_CST);
@@ -570,6 +578,7 @@
if (!c->watchdog) return;
if (!__atomic_load_n(&c->aq, __ATOMIC_SEQ_CST)) return;
+ if (!__atomic_load_n(&g_output_enabled, __ATOMIC_ACQUIRE)) return;
prev_tick = c->wd_last_tick_ns;
c->wd_last_tick_ns = now;
@@ -882,6 +891,39 @@
REVENT("mic enabled=%d", enabled);
}
+static void output_control_update(void)
+{
+ FILE *f;
+ int enabled;
+ struct client *c;
+ if (!g_output_control) return;
+ f = fopen(g_output_control, "r");
+ enabled = !f || fgetc(f) != '0';
+ if (f) fclose(f);
+ if (enabled == __atomic_load_n(&g_output_enabled, __ATOMIC_ACQUIRE)) return;
+ pthread_mutex_lock(&g_output_operations);
+ __atomic_store_n(&g_output_enabled, enabled, __ATOMIC_RELEASE);
+ pthread_mutex_lock(&g_clients_lock);
+ for (c = g_clients; c; c = c->next)
+ {
+ AAudioStream *aq;
+ if (c->dead) continue;
+ pthread_mutex_lock(&c->lock);
+ aq = c->aq;
+ if (aq && enabled)
+ {
+ c->wd_last_tick_ns = 0;
+ __atomic_store_n(&c->last_cb_ns, now_ns(), __ATOMIC_SEQ_CST);
+ if (AAudioStream_requestStart(aq) != AAUDIO_OK) request_reopen(c, "restart failed");
+ }
+ else if (aq) AAudioStream_requestStop(aq);
+ pthread_mutex_unlock(&c->lock);
+ }
+ pthread_mutex_unlock(&g_clients_lock);
+ pthread_mutex_unlock(&g_output_operations);
+ REVENT("output enabled=%d", enabled);
+}
+
static void *mic_reopen_thread(void *unused)
{
(void)unused;
@@ -1313,7 +1355,9 @@
ack.status = AAUDIO_ERROR_NO_MEMORY;
goto reply;
}
+ pthread_mutex_lock(&g_output_operations);
r = open_output(c, &c->aq);
+ pthread_mutex_unlock(&g_output_operations);
if (r != AAUDIO_OK)
{
REVENT("[%d] output open failed: %d", c->pid, r);
@@ -1383,6 +1427,7 @@
nanosleep(&iv, NULL);
mic_control_update();
+ output_control_update();
if (++tick % 10) continue;
if (g_rt_path[0])
@@ -1430,8 +1475,9 @@
if (!strcmp(argv[i], "--socket") && i + 1 < argc) path = argv[++i];
else if (!strcmp(argv[i], "--mic-fifo") && i + 1 < argc) fifo_path = argv[++i];
else if (!strcmp(argv[i], "--mic-control") && i + 1 < argc) g_mic_control = argv[++i];
+ else if (!strcmp(argv[i], "--output-control") && i + 1 < argc) g_output_control = argv[++i];
else if (!strcmp(argv[i], "--log")) g_verbose = 1;
- else { fprintf(stderr, "usage: directaudio-relay --socket <path> [--mic-fifo <path>] [--mic-control <path>] [--log]\n"); return 2; }
+ else { fprintf(stderr, "usage: directaudio-relay --socket <path> [--mic-fifo <path>] [--mic-control <path>] [--output-control <path>] [--log]\n"); return 2; }
}
if (!path)
{
@@ -1459,6 +1505,7 @@
mic_control_update();
REVENT("mic enabled=%d", __atomic_load_n(&g_mic_enabled, __ATOMIC_ACQUIRE));
+ output_control_update();
if (pthread_create(&th, NULL, housekeeping_thread, NULL) == 0) pthread_detach(th);
if (fifo_path && fifo_setup(fifo_path) != 0)
REVENT("mic-fifo: disabled");