mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14762b07d4 | ||
|
|
80fc5dec07 |
No files matched your search
@@ -18,15 +18,18 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
private File logFile;
|
||||
private final File micFifoPath;
|
||||
private volatile int pid = -1;
|
||||
private final Object micLock = new Object();
|
||||
private final Object stateLock = 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) {
|
||||
@@ -36,9 +39,11 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
@Override
|
||||
public void start() {
|
||||
stop();
|
||||
synchronized (micLock) {
|
||||
synchronized (stateLock) {
|
||||
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");
|
||||
@@ -67,6 +72,7 @@ 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());
|
||||
@@ -93,6 +99,7 @@ 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(); }
|
||||
});
|
||||
@@ -101,9 +108,27 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
}
|
||||
|
||||
public synchronized boolean setMicEnabled(boolean enabled) {
|
||||
if (micControl == null) return false;
|
||||
File next = new File(micControl.getPath() + ".new");
|
||||
return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(micControl);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
private void trackMic(String line) {
|
||||
@@ -112,20 +137,28 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
}
|
||||
boolean start = line.startsWith("DA-Relay: mic start ");
|
||||
if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
|
||||
synchronized (micLock) {
|
||||
synchronized (stateLock) {
|
||||
micHot = start;
|
||||
micLock.notifyAll();
|
||||
stateLock.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 (micLock) {
|
||||
while (micHot) {
|
||||
synchronized (stateLock) {
|
||||
while (!done.getAsBoolean()) {
|
||||
long left = deadline - System.currentTimeMillis();
|
||||
if (left <= 0) return false;
|
||||
try {
|
||||
micLock.wait(left);
|
||||
stateLock.wait(left);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
|
||||
@@ -903,16 +903,23 @@ 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"),
|
||||
@@ -2651,6 +2658,7 @@ 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"
|
||||
|
||||
@@ -57,12 +57,17 @@ import com.droiddeck.launcher.stores.StoresState
|
||||
/** What the Library pretends while a developer previews it. Nothing here is saved: a restart always comes back to [OFF]. */
|
||||
internal enum class LibraryPreview { OFF, NOTHING_INSTALLED, SIGNED_OUT, SAMPLE }
|
||||
|
||||
/** How many games the Steam home pretends are installed. Nothing here is saved. */
|
||||
internal enum class SteamHomePreview(val games: Int) { OFF(-1), NONE(0), FEW(3), MANY(12) }
|
||||
|
||||
internal enum class DrawerPreview { STEAM, DESKTOP, GAME }
|
||||
|
||||
/** Developer tools' preview states: screens that are otherwise hard to reach, shown without changing anything real. */
|
||||
internal object DevPreview {
|
||||
var library by mutableStateOf(LibraryPreview.OFF)
|
||||
var drawer by mutableStateOf<DrawerPreview?>(null)
|
||||
var steamHome by mutableStateOf(SteamHomePreview.OFF)
|
||||
var openSteam by mutableStateOf(false)
|
||||
/** The UI zoo sheet: where previews are picked, one at a time, only when asked for. */
|
||||
var zoo by mutableStateOf(false)
|
||||
/** Opt-in: a preview button where its state lives (the Library's toolbar), for switching states without the zoo. */
|
||||
@@ -87,6 +92,41 @@ internal fun sampleOwned(store: Store): List<CatalogItem> =
|
||||
internal fun sampleInstalled(owned: Map<Store, List<CatalogItem>>): Set<String> =
|
||||
owned.values.flatMap { items -> items.take(SAMPLE_INSTALLED).map { it.key } }.toSet()
|
||||
|
||||
/** The Steam home's games while a developer previews it: this many invented titles, no art, nothing installed. */
|
||||
internal fun sampleSteamHomeGames(count: Int): List<com.droiddeck.launcher.frontend.Library.SteamGame> = listOf(
|
||||
"Portal 2", "Hades", "Celeste", "Stardew Valley", "Hollow Knight", "Balatro",
|
||||
"Dead Cells", "Terraria", "Vampire Survivors", "Slay the Spire", "Cuphead", "Inscryption",
|
||||
).take(count).mapIndexed { i, name ->
|
||||
com.droiddeck.launcher.frontend.Library.SteamGame(1000 + i, name, art = null, library = "steam", lastPlayed = 1_700_000_000_000L - i * 86_400_000L)
|
||||
}
|
||||
|
||||
/** The pill a previewed Steam home shows, so the fake state is never mistaken for the real one. */
|
||||
@Composable
|
||||
internal fun SteamHomePreviewPill(modifier: Modifier = Modifier) {
|
||||
val preview = DevPreview.steamHome
|
||||
if (preview == SteamHomePreview.OFF) return
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val label = stringResource(
|
||||
when (preview) {
|
||||
SteamHomePreview.NONE -> R.string.dev_preview_steam_none
|
||||
SteamHomePreview.FEW -> R.string.dev_preview_steam_few
|
||||
else -> R.string.dev_preview_steam_many
|
||||
},
|
||||
)
|
||||
val end = stringResource(R.string.dev_preview_end)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = modifier.background(colors.surface, CircleShape).border(1.dp, pal.signal, CircleShape)
|
||||
.clickable(role = Role.Button, onClickLabel = end) { DevPreview.steamHome = SteamHomePreview.OFF }
|
||||
.padding(start = 14.dp, end = 10.dp, top = 8.dp, bottom = 8.dp).testTag("dev-preview-steam-end"),
|
||||
) {
|
||||
Icon(Icons.Outlined.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp))
|
||||
Text(stringResource(R.string.dev_preview_banner, label), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Icon(Icons.Filled.Close, end, tint = colors.onSurfaceVariant, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** The pill a previewed Library shows, so the fake state is never mistaken for the real one. */
|
||||
@Composable
|
||||
internal fun LibraryPreviewPill(modifier: Modifier = Modifier) {
|
||||
@@ -215,6 +255,17 @@ internal fun UiZooSheet() {
|
||||
DrawerPreview.GAME to R.string.session_title_game,
|
||||
)) ActionRow(stringResource(label), null, show, onClick = { close(); DevPreview.drawer = mode }, modifier = Modifier.testTag("zoo-drawer-${mode.name.lowercase()}"))
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.dev_preview_steam_home)) {
|
||||
for ((mode, label) in listOf(
|
||||
SteamHomePreview.NONE to R.string.dev_preview_steam_none,
|
||||
SteamHomePreview.FEW to R.string.dev_preview_steam_few,
|
||||
SteamHomePreview.MANY to R.string.dev_preview_steam_many,
|
||||
)) ActionRow(
|
||||
stringResource(label), null, show,
|
||||
onClick = { close(); DevPreview.steamHome = mode; DevPreview.openSteam = true },
|
||||
modifier = Modifier.testTag("zoo-steam-${mode.name.lowercase()}"),
|
||||
)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.dev_preview_library)) {
|
||||
for ((mode, label) in listOf(
|
||||
LibraryPreview.NOTHING_INSTALLED to R.string.dev_preview_library_nothing_installed,
|
||||
|
||||
@@ -272,7 +272,10 @@ private fun Content(
|
||||
return
|
||||
}
|
||||
if (selected == "steam") {
|
||||
SteamHome(s, a, modifier)
|
||||
Box(modifier) {
|
||||
SteamHome(s, a, Modifier.fillMaxSize())
|
||||
SteamHomePreviewPill(Modifier.align(androidx.compose.ui.Alignment.BottomCenter).padding(bottom = 20.dp))
|
||||
}
|
||||
return
|
||||
}
|
||||
if (selected == "store") {
|
||||
|
||||
@@ -658,6 +658,11 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
LaunchedEffect(SetupTabs.openSection) {
|
||||
if (SetupTabs.openSection != null && (railSelection != "setup" || s.pageKey != null)) showRailPage("setup", true)
|
||||
}
|
||||
LaunchedEffect(DevPreview.openSteam) {
|
||||
if (!DevPreview.openSteam) return@LaunchedEffect
|
||||
DevPreview.openSteam = false
|
||||
showRailPage("steam", true)
|
||||
}
|
||||
LaunchedEffect(DevPreview.openLibrary) {
|
||||
if (!DevPreview.openLibrary) return@LaunchedEffect
|
||||
DevPreview.openLibrary = false
|
||||
|
||||
@@ -113,7 +113,8 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
}
|
||||
val owned = remember(ownedAll, concealed) { ownedAll.filter { it.first.toLong() !in concealed } }
|
||||
val featured = remember(featuredAll, concealed) { featuredAll.filter { it.appId.toLong() !in concealed } }
|
||||
val games = remember(s.steamGames, LibraryHidden.keys, LibraryHidden.steam) { s.steamGames.filterNot { LibraryHidden.isHidden(hideKey(it), it) }.sortedWith(compareByDescending<Library.SteamGame> { it.lastPlayed }.thenBy { it.gameId }) }
|
||||
val previewing = DevPreview.steamHome
|
||||
val games = remember(s.steamGames, previewing, LibraryHidden.keys, LibraryHidden.steam) { (if (previewing == SteamHomePreview.OFF) s.steamGames else sampleSteamHomeGames(previewing.games)).filterNot { LibraryHidden.isHidden(hideKey(it), it) }.sortedWith(compareByDescending<Library.SteamGame> { it.lastPlayed }.thenBy { it.gameId }) }
|
||||
val narrow = LocalNarrowPane.current
|
||||
var words by remember { mutableStateOf<Rect?>(null) }
|
||||
val mode = com.droiddeck.launcher.session.SessionService.MODE_STEAM
|
||||
@@ -163,12 +164,12 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
games.isEmpty() -> EmptyLibrary(
|
||||
avoid = words,
|
||||
wall = if (owned.isEmpty() && featured.isEmpty()) null else { { CapsuleWall(emptyList(), owned = owned, featured = featured) } },
|
||||
) { Box(Modifier.fillMaxSize().graphicsLayer { scaleX = 1.06f; scaleY = 1.06f }) { WallFade() } }
|
||||
) { Box(Modifier.fillMaxSize().graphicsLayer { scaleX = 1.06f; scaleY = 1.06f }) { WallFade(bottomWhenTall = true) } }
|
||||
games.size < WALL_MIN_GAMES -> CapsuleFan(games)
|
||||
else -> CapsuleWall(games, owned = owned, featured = featured)
|
||||
}
|
||||
},
|
||||
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
|
||||
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade(bottomWhenTall = true) },
|
||||
words = {
|
||||
val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
|
||||
val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
@@ -232,19 +233,35 @@ internal fun Modifier.overhang(by: androidx.compose.ui.unit.Dp = 4.dp): Modifier
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun WallFade(modifier: Modifier = Modifier.fillMaxSize().overhang()) {
|
||||
internal fun WallFade(modifier: Modifier = Modifier.fillMaxSize().overhang(), bottomWhenTall: Boolean = false) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Box(
|
||||
modifier.background(
|
||||
Brush.horizontalGradient(
|
||||
0f to colors.background.copy(alpha = 0.86f),
|
||||
0.34f to colors.background.copy(alpha = 0.6f),
|
||||
0.68f to colors.background.copy(alpha = 0.14f),
|
||||
1f to colors.background.copy(alpha = 0.04f),
|
||||
),
|
||||
),
|
||||
)
|
||||
Box(modifier.background(Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
|
||||
BoxWithConstraints(modifier) {
|
||||
if (bottomWhenTall && maxHeight > maxWidth) {
|
||||
// The words sit at the bottom of a tall page, so the art stays clear above them and darkens only behind them.
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(
|
||||
Brush.verticalGradient(
|
||||
0f to colors.background.copy(alpha = 0.12f),
|
||||
0.5f to colors.background.copy(alpha = 0.18f),
|
||||
0.72f to colors.background.copy(alpha = 0.72f),
|
||||
1f to colors.background.copy(alpha = 0.94f),
|
||||
),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(
|
||||
Brush.horizontalGradient(
|
||||
0f to colors.background.copy(alpha = 0.86f),
|
||||
0.34f to colors.background.copy(alpha = 0.6f),
|
||||
0.68f to colors.background.copy(alpha = 0.14f),
|
||||
1f to colors.background.copy(alpha = 0.04f),
|
||||
),
|
||||
),
|
||||
)
|
||||
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -387,31 +404,45 @@ private fun CapsuleFan(games: List<Library.SteamGame>) {
|
||||
transition.animateFloat(0f, 1f, infiniteRepeatable(tween(ms, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "float")
|
||||
}
|
||||
val still = Motion.scale == 0f
|
||||
val slots = listOf(
|
||||
val landscape = listOf(
|
||||
FanSlot(0.54f, 0.14f, 0.62f, -9f),
|
||||
FanSlot(0.70f, 0.24f, 0.56f, 5f),
|
||||
FanSlot(0.40f, 0.30f, 0.50f, -17f),
|
||||
)
|
||||
// A tall page sizes the cards from its width, so they fit any aspect; heights are fractions of the width.
|
||||
val portrait = listOf(
|
||||
FanSlot(0.27f, 0.11f, 0.70f, -9f),
|
||||
FanSlot(0.55f, 0.19f, 0.64f, 5f),
|
||||
FanSlot(0.04f, 0.26f, 0.56f, -17f),
|
||||
)
|
||||
BoxWithConstraints(
|
||||
Modifier.fillMaxSize().drawBehind {
|
||||
drawRect(
|
||||
Brush.radialGradient(
|
||||
listOf(pal.signal.copy(alpha = 0.14f), Color.Transparent),
|
||||
center = Offset(size.width * 0.68f, size.height * 0.45f), radius = size.height * 0.6f,
|
||||
center = if (size.height > size.width) Offset(size.width * 0.55f, size.height * 0.28f) else Offset(size.width * 0.68f, size.height * 0.45f),
|
||||
radius = if (size.height > size.width) size.width * 0.9f else size.height * 0.6f,
|
||||
),
|
||||
)
|
||||
},
|
||||
) {
|
||||
val radius = with(density) { 14.dp.toPx() }
|
||||
val tall = maxHeight > maxWidth
|
||||
val slots = if (tall) portrait else landscape
|
||||
for (i in games.indices.reversed()) {
|
||||
val slot = slots[i]
|
||||
val h = maxHeight * slot.height
|
||||
val h = if (tall) maxWidth * slot.height else maxHeight * slot.height
|
||||
val x = if (tall) {
|
||||
// The lean and the float swing the corners out by about h/2 * sin(angle).
|
||||
val swing = h * kotlin.math.sin(Math.toRadians(kotlin.math.abs(slot.lean) + 2.0)).toFloat() / 2f
|
||||
(maxWidth * slot.x).coerceIn(swing, (maxWidth - h * 2f / 3f - swing).coerceAtLeast(swing))
|
||||
} else maxWidth * slot.x
|
||||
val v: State<Float> = floats[i]
|
||||
val look = WallCapsule(artBrush(hueOf(games[i].name)), games[i].art)
|
||||
val art = look.art?.let { rememberCapsuleArt(it, with(density) { Size((h * 2f / 3f).toPx(), h.toPx()) }, radius) }
|
||||
Spacer(
|
||||
Modifier
|
||||
.offset(x = maxWidth * slot.x, y = maxHeight * slot.y)
|
||||
.offset(x = x, y = maxHeight * slot.y)
|
||||
.size(h * 2f / 3f, h)
|
||||
.graphicsLayer {
|
||||
val t = if (still) 0f else v.value
|
||||
|
||||
@@ -4376,6 +4376,10 @@
|
||||
<string name="dev_ui_zoo_open">Open</string>
|
||||
<string name="dev_ui_zoo_show">Show</string>
|
||||
<string name="dev_ui_zoo_note">Previews change nothing real: nothing is installed, removed or signed out, and the menu\'s switches save nothing. A Library preview stays until you end it from its pill or restart.</string>
|
||||
<string name="dev_preview_steam_home">Steam home</string>
|
||||
<string name="dev_preview_steam_none">No games installed</string>
|
||||
<string name="dev_preview_steam_few">3 games installed</string>
|
||||
<string name="dev_preview_steam_many">12 games installed</string>
|
||||
<string name="dev_preview_library">Library</string>
|
||||
<string name="dev_preview_library_nothing_installed">Nothing installed</string>
|
||||
<string name="dev_preview_library_signed_out">Signed out of every store</string>
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
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))
|
||||
}
|
||||
@@ -11,6 +11,7 @@ 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
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
--- 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");
|
||||
@@ -565,22 +565,7 @@ def online_cores():
|
||||
cores = parse_cores(f.read().strip())
|
||||
except OSError:
|
||||
cores = None
|
||||
return cores or allowed_cores() | set(range(os.cpu_count() or 0))
|
||||
|
||||
|
||||
def allowed_cores(status="/proc/self/status"):
|
||||
try:
|
||||
with open(status) as f:
|
||||
for line in f:
|
||||
key, _, value = line.partition(":")
|
||||
if key == "Cpus_allowed_list":
|
||||
cores = parse_cores(value.strip())
|
||||
if cores:
|
||||
return cores
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
return os.sched_getaffinity(0)
|
||||
return cores or os.sched_getaffinity(0) | set(range(os.cpu_count() or 0))
|
||||
|
||||
|
||||
def game_cores(env):
|
||||
@@ -649,11 +634,11 @@ def cpu_topology(env, command=()):
|
||||
fastest = env.get("DROIDDECK_FASTEST_CORES", "").strip() != "0" and game_id(env) is not None
|
||||
if not (picked or fastest):
|
||||
return
|
||||
online = online_cores()
|
||||
try:
|
||||
cores = sorted(allowed_cores() & online)
|
||||
cores = sorted(os.sched_getaffinity(0))
|
||||
except OSError:
|
||||
return
|
||||
online = online_cores()
|
||||
if not cores or cores[-1] >= len(online):
|
||||
return
|
||||
picked = picked and not set(cores) >= online
|
||||
|
||||
@@ -1872,7 +1872,6 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
for env, affinity, expected, proton in cases:
|
||||
env["DROIDDECK_FASTEST_CORES"] = "0"
|
||||
with mock.patch.dict(MODULE["cpu_topology"].__globals__, online), \
|
||||
mock.patch.object(MODULE["allowed_cores"], "__defaults__", ("/missing/status",)), \
|
||||
mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True):
|
||||
MODULE["cpu_topology"](env)
|
||||
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env)
|
||||
@@ -1987,7 +1986,6 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
env.setdefault("STEAM_COMPAT_DATA_PATH", "/steam/compatdata/3608888694")
|
||||
with mock.patch.dict(MODULE["cpu_topology"].__globals__, {"online_cores": lambda: every}), \
|
||||
mock.patch.dict(MODULE["fastest_first"].__globals__, {"core_speeds": lambda cores, speeds=speeds: speeds}), \
|
||||
mock.patch.object(MODULE["allowed_cores"], "__defaults__", ("/missing/status",)), \
|
||||
mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True):
|
||||
MODULE["cpu_topology"](env, command)
|
||||
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env)
|
||||
@@ -1997,46 +1995,6 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(MODULE["proton_cpu_limit"](command, {"SteamGameId": "1038250"}), "P")
|
||||
self.assertEqual(MODULE["proton_cpu_limit"](command, {"SteamGameId": "618970"}), 4)
|
||||
|
||||
def test_windows_sees_the_same_cores_while_android_pauses_some(self):
|
||||
os_mod = MODULE["os"]
|
||||
kalama = {0: 411, 1: 411, 2: 411, 3: 869, 4: 869, 5: 869, 6: 869, 7: 1024}
|
||||
every = set(range(8))
|
||||
cases = [
|
||||
({}, "0-7", {3, 4, 5, 6}, "8:7,3,4,5,6,0,1,2"),
|
||||
({}, "0-7", {0, 1, 2, 3, 4, 5, 7}, "8:7,3,4,5,6,0,1,2"),
|
||||
({}, "0-7", every, "8:7,3,4,5,6,0,1,2"),
|
||||
({"DD_GAME_CPUS": "6,7"}, "6-7", {6}, "2:7,6"),
|
||||
({"DROIDDECK_GAME_CORES": "3-7"}, "3-7", {3, 4, 5}, "5:7,3,4,5,6"),
|
||||
({}, "0-9", {3, 4}, "8:7,3,4,5,6,0,1,2"),
|
||||
({"DROIDDECK_FASTEST_CORES": "0"}, "0-7", {3, 4, 5, 6}, None),
|
||||
({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0"}, "0-7", {3, 4, 5, 6}, None),
|
||||
]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
status = Path(tmp) / "status"
|
||||
for env, allowed, active, expected in cases:
|
||||
env.setdefault("STEAM_COMPAT_DATA_PATH", "/steam/compatdata/1687950")
|
||||
status.write_text("Name:\tpython3\nCpus_allowed:\tff\nCpus_allowed_list:\t%s\n" % allowed)
|
||||
with mock.patch.dict(MODULE["cpu_topology"].__globals__, {"online_cores": lambda: every}), \
|
||||
mock.patch.dict(MODULE["fastest_first"].__globals__, {"core_speeds": lambda cores: kalama}), \
|
||||
mock.patch.object(MODULE["allowed_cores"], "__defaults__", (str(status),)), \
|
||||
mock.patch.object(os_mod, "sched_getaffinity", return_value=active, create=True):
|
||||
MODULE["cpu_topology"](env, ["/missing/proton", "waitforexitandrun", "/game/P5R.exe"])
|
||||
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, (env, allowed, active))
|
||||
self.assertEqual(env.get("PROTON_CPU_TOPOLOGY"), expected, (env, allowed, active))
|
||||
|
||||
def test_allowed_cores_read_the_tasks_mask_before_the_active_one(self):
|
||||
os_mod = MODULE["os"]
|
||||
allowed = MODULE["allowed_cores"]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
status = Path(tmp) / "status"
|
||||
with mock.patch.object(os_mod, "sched_getaffinity", return_value={3, 4}, create=True):
|
||||
status.write_text("Cpus_allowed_list:\t0-2,4,6-7\n")
|
||||
self.assertEqual(allowed(str(status)), {0, 1, 2, 4, 6, 7})
|
||||
for text in ("Name:\tpython3\n", "Cpus_allowed_list:\t\n", "Cpus_allowed_list:\tjunk\n"):
|
||||
status.write_text(text)
|
||||
self.assertEqual(allowed(str(status)), {3, 4}, text)
|
||||
self.assertEqual(allowed(str(Path(tmp) / "missing")), {3, 4})
|
||||
|
||||
def test_core_speeds_read_capacity_then_top_clock(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for core, capacity, clock in ((0, "379", "2265600"), (1, None, "3302400")):
|
||||
|
||||
Reference in new issue
Block a user