diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 1ce7b0ac73..6336fb1325 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -27,6 +27,8 @@
+
+
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 3b73b6a3c9..32d5f5189e 100644
--- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java
+++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java
@@ -26,6 +26,7 @@ public class PulseAudioComponent extends SessionPart {
private final File workingDir;
+ private final File deviceControls;
private File logFile;
private final String micFifoPath;
private volatile int pid = -1;
@@ -36,6 +37,8 @@ public class PulseAudioComponent extends SessionPart {
public PulseAudioComponent(Context context, String micFifoPath) {
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
+ this.deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent.directory(
+ com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context));
this.micFifoPath = micFifoPath;
}
@@ -94,7 +97,7 @@ public class PulseAudioComponent extends SessionPart {
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");
+ 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("set-default-sink DirectAudio");
config.add(".fail");
if (micFifoPath != null && !micFifoPath.isEmpty()) {
@@ -139,7 +142,7 @@ public class PulseAudioComponent extends SessionPart {
} 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)";
} else {
- boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
+ boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "AAudioSink") != null;
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt
new file mode 100644
index 0000000000..c88666dfb5
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt
@@ -0,0 +1,177 @@
+package com.droiddeck.launcher.runtime
+
+import android.content.Context
+import android.content.Intent
+import android.database.ContentObserver
+import android.media.AudioManager
+import android.net.Uri
+import android.os.FileObserver
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import android.provider.Settings
+import android.util.Log
+import com.droiddeck.launcher.core.SessionPart
+import java.io.File
+import java.nio.file.Files
+import java.nio.file.StandardCopyOption
+import org.json.JSONObject
+import kotlin.math.roundToInt
+
+class DeviceControlsComponent(context: Context, root: File) : SessionPart() {
+ private val context = context.applicationContext
+ private val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ private val directory = directory(root)
+ private val handler = Handler(Looper.getMainLooper())
+ private var running = false
+ private var pendingBrightness: Pair? = null
+ private var permissionRequestAt = -5_000L
+ private var previous = ""
+ private var revision = 0L
+ init { prepareBacklight(context, root) }
+ private val observer = object : ContentObserver(handler) {
+ override fun onChange(selfChange: Boolean) { if (running) publish() }
+ }
+ private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) {
+ override fun onEvent(event: Int, path: String?) {
+ if (path in REQUESTS) handler.post { if (running) consume() }
+ }
+ }
+ private val refresh = object : Runnable {
+ override fun run() {
+ if (!running) return
+ consume()
+ pendingBrightness?.let { (value, time) ->
+ if (SystemClock.elapsedRealtime() - time > 120_000) pendingBrightness = null
+ else if (Settings.System.canWrite(context)) {
+ pendingBrightness = null
+ brightness(value)
+ }
+ }
+ publish()
+ handler.postDelayed(this, 250)
+ }
+ }
+
+ fun publish(force: Boolean = false) {
+ try {
+ directory.mkdirs()
+ val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
+ val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1)
+ val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC)
+ write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n")
+ val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
+ write("backlight/droiddeck/brightness", "$value\n")
+ write("backlight/droiddeck/actual_brightness", "$value\n")
+ val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0)
+ .put("brightnessWritable", Settings.System.canWrite(context)).toString()
+ if (force || state != previous) {
+ write("state.json", JSONObject(state).put("revision", ++revision).toString())
+ previous = state
+ }
+ } catch (e: Exception) {
+ Log.w(TAG, "Could not publish Android controls", e)
+ }
+ }
+
+ override fun start() {
+ handler.post {
+ REQUESTS.forEach {
+ File(directory, it).delete()
+ File(directory, "$it.processing").delete()
+ }
+ running = true
+ context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
+ requests.startWatching()
+ refresh.run()
+ }
+ }
+
+ override fun stop() {
+ handler.post {
+ running = false
+ handler.removeCallbacks(refresh)
+ requests.stopWatching()
+ context.contentResolver.unregisterContentObserver(observer)
+ pendingBrightness = null
+ }
+ }
+
+ private fun consume() {
+ for (name in REQUESTS) {
+ val file = File(directory, name)
+ if (!file.isFile) continue
+ val claimed = File(directory, "$name.processing")
+ try {
+ Files.move(file.toPath(), claimed.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
+ if (claimed.length() > 64) continue
+ val text = claimed.readText().trim()
+ when (name) {
+ "brightness.request" -> text.toFloatOrNull()?.takeIf { it.isFinite() && it in 0f..1f }?.let(::brightness)
+ "volume.request" -> text.toIntOrNull()?.let {
+ audio.setStreamVolume(AudioManager.STREAM_MUSIC,
+ it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0)
+ }
+ "mute.request" -> if (text == "0" || text == "1") {
+ audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
+ if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0)
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(TAG, "Could not apply $name", e)
+ } finally {
+ publish(force = true)
+ claimed.delete()
+ }
+ }
+ }
+
+ private fun brightness(value: Float) {
+ if (!Settings.System.canWrite(context)) {
+ pendingBrightness = value to SystemClock.elapsedRealtime()
+ val now = SystemClock.elapsedRealtime()
+ if (now - permissionRequestAt >= 5_000) {
+ permissionRequestAt = now
+ try {
+ context.startActivity(Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
+ Uri.parse("package:${context.packageName}")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ } catch (e: Exception) {
+ Log.w(TAG, "Could not open brightness permission", e)
+ }
+ }
+ return
+ }
+ val level = 1 + (value * 254).roundToInt()
+ try {
+ Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
+ Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
+ Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, level)
+ } catch (e: SecurityException) {
+ Log.w(TAG, "Brightness permission was revoked", e)
+ }
+ }
+
+ private fun write(name: String, text: String) {
+ val file = File(directory, name)
+ if (file.isFile && file.readText() == text) return
+ val staged = File(directory, "$name.tmp")
+ staged.writeText(text)
+ Files.move(staged.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
+ }
+
+ companion object {
+ private const val TAG = "DeviceControls"
+ private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request")
+ @JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls")
+ @JvmStatic fun prepareBacklight(context: Context, root: File): File {
+ val base = File(directory(root), "backlight")
+ val panel = File(base, "droiddeck").apply { mkdirs() }
+ val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
+ for ((name, text) in mapOf("type" to "raw", "max_brightness" to "255", "brightness" to "$value",
+ "actual_brightness" to "$value", "bl_power" to "0", "scale" to "linear")) {
+ File(panel, name).writeText("$text\n")
+ }
+ return base
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
index 6473197549..d02fdf0c2f 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
@@ -192,6 +192,7 @@ public final class LinuxRuntime {
bind(cmd, "/dev");
bind(cmd, "/proc");
bind(cmd, "/sys");
+ bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight");
bind(cmd, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd");
bind(cmd, "/proc/self/fd/0:/dev/stdin");
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
index b6f35f96a1..252f94103f 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
@@ -630,6 +630,10 @@ class SessionService : Service() {
networkLink.attach(this)
networkLink.publish()
components.add(networkLink)
+ val deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent(this, root)
+ deviceControls.attach(this)
+ deviceControls.publish()
+ components.add(deviceControls)
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while it was starting; not launching it")
if (gen == sessionGen) components.clear()
diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt
new file mode 100644
index 0000000000..9e0da30aa7
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt
@@ -0,0 +1,120 @@
+package com.droiddeck.launcher.runtime
+
+import android.app.Application
+import android.content.Context
+import android.media.AudioManager
+import android.os.Looper
+import android.provider.Settings
+import java.io.File
+import java.time.Duration
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+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.Shadows.shadowOf
+import org.robolectric.annotation.Config
+import org.robolectric.annotation.Implements
+import org.robolectric.annotation.Implementation
+import org.robolectric.shadows.ShadowSettings
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [28], manifest = Config.NONE, application = Application::class, shadows = [WriteSettingsShadow::class])
+class DeviceControlsComponentTest {
+ @get:Rule val tmp = TemporaryFolder()
+ private val context get() = RuntimeEnvironment.getApplication()
+ private val audio get() = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ private lateinit var component: DeviceControlsComponent
+ private lateinit var directory: File
+
+ @Before fun start() {
+ WriteSettingsShadow.writable = true
+ Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
+ val root = tmp.newFolder()
+ directory = DeviceControlsComponent.directory(root)
+ component = DeviceControlsComponent(context, root)
+ component.publish()
+ component.start()
+ shadowOf(Looper.getMainLooper()).idle()
+ }
+
+ @After fun stop() {
+ component.stop()
+ shadowOf(Looper.getMainLooper()).idle()
+ }
+
+ private fun tick() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(300))
+ private fun request(name: String, text: String) {
+ File(directory, "$name.request").writeText(text)
+ tick()
+ }
+
+ @Test fun androidChangesArePublishedAndRequestsUseDeviceVolumeSteps() {
+ request("volume", "999")
+ assertEquals(audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), audio.getStreamVolume(AudioManager.STREAM_MUSIC))
+ audio.setStreamVolume(AudioManager.STREAM_MUSIC, 3, 0)
+ tick()
+ assertEquals("3", File(directory, "volume.state").readText().split(" ").first())
+ request("volume", "invalid")
+ assertEquals(3, audio.getStreamVolume(AudioManager.STREAM_MUSIC))
+ }
+
+ @Test fun deniedBrightnessIsReadBackAndAppliedOnlyAfterPermission() {
+ WriteSettingsShadow.writable = false
+ request("brightness", "0.75")
+ assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
+ assertEquals(Settings.ACTION_MANAGE_WRITE_SETTINGS, shadowOf(context).nextStartedActivity.action)
+ assertFalse(JSONObject(File(directory, "state.json").readText()).getBoolean("brightnessWritable"))
+ WriteSettingsShadow.writable = true
+ tick()
+ assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
+ }
+
+ @Test fun brightnessIsBoundedAndExternalChangesAreReadBack() {
+ for (invalid in listOf("NaN", "Infinity", "-0.1", "1.1")) request("brightness", invalid)
+ assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
+ request("brightness", "0")
+ assertEquals(1, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
+ Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 255)
+ tick()
+ assertEquals(1.0, JSONObject(File(directory, "state.json").readText()).getDouble("brightness"), 0.0001)
+ }
+
+ @Test fun stoppedSessionsDoNotConsumeNewCommands() {
+ component.stop()
+ shadowOf(Looper.getMainLooper()).idle()
+ request("brightness", "0.2")
+ assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
+ }
+
+ @Test fun rejectedPermissionCanBeRequestedAgainWithoutOpeningRepeatedScreens() {
+ WriteSettingsShadow.writable = false
+ request("brightness", "0.75")
+ assertNotNull(shadowOf(context).nextStartedActivity)
+ request("brightness", "0.8")
+ assertNull(shadowOf(context).nextStartedActivity)
+ shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(5))
+ request("brightness", "0.8")
+ assertNotNull(shadowOf(context).nextStartedActivity)
+ }
+
+ @Test fun oversizedRequestsAreDiscardedAndDoNotBlockLaterCommands() {
+ request("brightness", "0".repeat(1000))
+ assertFalse(File(directory, "brightness.request.processing").exists())
+ request("brightness", "0.75")
+ assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
+ }
+}
+
+@Implements(Settings.System::class)
+class WriteSettingsShadow : ShadowSettings.ShadowSystem() {
+ companion object {
+ @JvmField var writable = true
+ @JvmStatic @Implementation fun canWrite(context: Context) = writable
+ }
+}
diff --git a/tools/aaudio-sink/android-volume.h b/tools/aaudio-sink/android-volume.h
new file mode 100644
index 0000000000..b7f4ec9d18
--- /dev/null
+++ b/tools/aaudio-sink/android-volume.h
@@ -0,0 +1,96 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+#include
+#include
+
+struct android_volume {
+ pa_sink *sink;
+ char *directory;
+ pa_time_event *timer;
+};
+
+static bool android_volume_read(const char *directory, unsigned *level, unsigned *maximum, unsigned *muted) {
+ char *path = pa_sprintf_malloc("%s/volume.state", directory);
+ FILE *file = fopen(path, "r");
+ pa_xfree(path);
+ if (!file) return false;
+ int fields = fscanf(file, "%u %u %u", level, maximum, muted);
+ fclose(file);
+ return fields == 3 && *maximum > 0 && *level <= *maximum && *muted <= 1;
+}
+
+static void android_volume_request(pa_sink *sink, const char *name, unsigned value) {
+ struct userdata *u = sink->userdata;
+ if (!u->android_volume || sink->state == PA_SINK_INIT) return;
+ char *path = pa_sprintf_malloc("%s/%s.request", u->android_volume->directory, name);
+ char *staged = pa_sprintf_malloc("%s.tmp", path);
+ FILE *file = fopen(staged, "w");
+ if (file) {
+ fprintf(file, "%u\n", value);
+ if (fclose(file) == 0 && rename(staged, path) < 0) pa_log_warn("Could not publish Android %s", name);
+ }
+ pa_xfree(staged);
+ pa_xfree(path);
+}
+
+static void android_volume_set(pa_sink *sink) {
+ struct userdata *u = sink->userdata;
+ unsigned level, maximum, muted;
+ if (!u->android_volume || !android_volume_read(u->android_volume->directory, &level, &maximum, &muted)) return;
+ unsigned requested = PA_MIN(pa_cvolume_max(&sink->real_volume), PA_VOLUME_NORM);
+ level = ((uint64_t)requested * maximum + PA_VOLUME_NORM / 2) / PA_VOLUME_NORM;
+ pa_cvolume_set(&sink->real_volume, sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum);
+ /* Android applies media gain to both PulseAudio and DirectAudio streams. */
+ pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels);
+ android_volume_request(sink, "volume", level);
+}
+
+static void android_volume_mute(pa_sink *sink) {
+ android_volume_request(sink, "mute", sink->muted ? 1 : 0);
+}
+
+static void android_volume_refresh(pa_mainloop_api *api, pa_time_event *event, const struct timeval *tv, void *userdata) {
+ struct android_volume *bridge = userdata;
+ unsigned level, maximum, muted;
+ char *request = pa_sprintf_malloc("%s/volume.request", bridge->directory);
+ char *mute_request = pa_sprintf_malloc("%s/mute.request", bridge->directory);
+ char *processing = pa_sprintf_malloc("%s.processing", request);
+ char *mute_processing = pa_sprintf_malloc("%s.processing", mute_request);
+ if (access(request, F_OK) != 0 && access(mute_request, F_OK) != 0 &&
+ access(processing, F_OK) != 0 && access(mute_processing, F_OK) != 0 &&
+ android_volume_read(bridge->directory, &level, &maximum, &muted)) {
+ pa_cvolume volume;
+ pa_cvolume_set(&volume, bridge->sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum);
+ if (!pa_cvolume_equal(&volume, &bridge->sink->real_volume)) pa_sink_volume_changed(bridge->sink, &volume);
+ if (bridge->sink->muted != !!muted) pa_sink_mute_changed(bridge->sink, !!muted);
+ }
+ pa_xfree(request);
+ pa_xfree(mute_request);
+ pa_xfree(processing);
+ pa_xfree(mute_processing);
+ pa_core_rttime_restart(bridge->sink->core, event, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC);
+}
+
+static struct android_volume *android_volume_new(pa_sink *sink, const char *directory) {
+ unsigned level, maximum, muted;
+ if (!directory || !android_volume_read(directory, &level, &maximum, &muted)) return NULL;
+ struct android_volume *bridge = pa_xnew0(struct android_volume, 1);
+ bridge->sink = sink;
+ bridge->directory = pa_xstrdup(directory);
+ pa_cvolume_set(&sink->real_volume, sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum);
+ sink->reference_volume = sink->real_volume;
+ sink->muted = !!muted;
+ sink->n_volume_steps = maximum + 1;
+ pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels);
+ pa_sink_set_set_volume_callback(sink, android_volume_set);
+ pa_sink_set_set_mute_callback(sink, android_volume_mute);
+ bridge->timer = pa_core_rttime_new(sink->core, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC,
+ android_volume_refresh, bridge);
+ return bridge;
+}
+
+static void android_volume_free(struct android_volume *bridge) {
+ if (!bridge) return;
+ bridge->sink->core->mainloop->time_free(bridge->timer);
+ pa_xfree(bridge->directory);
+ pa_xfree(bridge);
+}
diff --git a/tools/aaudio-sink/module-aaudio-sink.c b/tools/aaudio-sink/module-aaudio-sink.c
index 619bd26733..3c129ce4b6 100644
--- a/tools/aaudio-sink/module-aaudio-sink.c
+++ b/tools/aaudio-sink/module-aaudio-sink.c
@@ -42,6 +42,7 @@ PA_MODULE_USAGE(
"channels= "
"channel_map= "
"volume= "
+ "control_dir= "
"performance_mode=<0 none, 1 low latency, 2 power saving> "
"adaptive= "
"buffer_frames= "
@@ -56,6 +57,7 @@ PA_MODULE_USAGE(
#define STATS_EVERY_USEC (30 * PA_USEC_PER_SEC)
static const char* const valid_modargs[] = {
+ "control_dir",
"sink_name",
"sink_properties",
"format",
@@ -70,7 +72,10 @@ static const char* const valid_modargs[] = {
NULL
};
+struct android_volume;
+
struct userdata {
+ struct android_volume *android_volume;
pa_core *core;
pa_module *module;
pa_sink *sink;
@@ -100,6 +105,9 @@ struct userdata {
int32_t xruns_reported;
};
+#include "android-volume.h"
+
+
static pa_usec_t frames_to_usec(const struct userdata *u, int64_t frames) {
return (pa_usec_t) (frames * (int64_t) PA_USEC_PER_SEC / (int64_t) u->ss.rate);
}
@@ -472,6 +480,7 @@ int pa__init(pa_module *m) {
goto fail;
}
+ u->android_volume = android_volume_new(u->sink, pa_modargs_get_value(ma, "control_dir", NULL));
pa_sink_put(u->sink);
pa_modargs_free(ma);
return 0;
@@ -498,6 +507,7 @@ void pa__done(pa_module *m) {
if (!(u = m->userdata))
return;
+ android_volume_free(u->android_volume);
if (u->sink)
pa_sink_unlink(u->sink);
if (u->thread) {
diff --git a/tools/directaudio/sink/module-directaudio-native-sink.c b/tools/directaudio/sink/module-directaudio-native-sink.c
index ca3eb01cc5..4d03e6bd4d 100644
--- a/tools/directaudio/sink/module-directaudio-native-sink.c
+++ b/tools/directaudio/sink/module-directaudio-native-sink.c
@@ -59,6 +59,7 @@ PA_MODULE_DESCRIPTION("Android audio output: DirectAudio's AAudio engine, in-pro
PA_MODULE_VERSION(PACKAGE_VERSION);
PA_MODULE_LOAD_ONCE(false);
PA_MODULE_USAGE(
+ "control_dir= "
"sink_name= "
"sink_properties= "
"volume= "
@@ -91,11 +92,15 @@ PA_MODULE_USAGE(
#define DA_FADE_FRAMES 64
static const char* const valid_modargs[] = {
+ "control_dir",
"sink_name", "sink_properties", "volume", "performance_mode", "buffer_ms", "max_ms", "ring_ms",
"adaptive", "decay", "limiter", "watchdog", NULL
};
+struct android_volume;
+
struct userdata {
+ struct android_volume *android_volume;
pa_core *core;
pa_module *module;
pa_sink *sink;
@@ -136,6 +141,9 @@ struct userdata {
unsigned int opens;
};
+#include "../../aaudio-sink/android-volume.h"
+
+
static uint64_t now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
@@ -774,6 +782,7 @@ int pa__init(pa_module *m) {
pa_log("Failed to create thread.");
goto fail;
}
+ u->android_volume = android_volume_new(u->sink, pa_modargs_get_value(ma, "control_dir", NULL));
pa_sink_put(u->sink);
pa_modargs_free(ma);
return 0;
@@ -799,6 +808,7 @@ void pa__done(pa_module *m) {
pa_assert(m);
if (!(u = m->userdata))
return;
+ android_volume_free(u->android_volume);
if (u->sink)
pa_sink_unlink(u->sink);
if (u->thread) {
diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat
index ba739235b1..595563019b 100755
--- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat
+++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat
@@ -2,6 +2,7 @@
import base64
import ctypes
import json
+import math
import os
import runpy
import select
@@ -15,6 +16,48 @@ import time
HERE = os.path.dirname(os.path.realpath(__file__))
COMPAT = runpy.run_path(os.path.join(HERE, "steam-compatibility"))
BINDING = "droiddeckCompatChanged"
+BRIGHTNESS_BINDING = "droiddeckBrightnessChanged"
+CONTROLS_DIR = "/etc/droiddeck-device-controls"
+BRIGHTNESS_JS = r"""
+(() => {
+ if (window.__droiddeckBrightness) return "present";
+ const display = SteamClient.System?.Display;
+ if (!display?.RegisterForBrightnessChanges || !display?.SetBrightness) return "unavailable";
+ const self = { expected: null, updating: true };
+ self.set = value => {
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return;
+ if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return;
+ self.expected = value;
+ self.updating = true;
+ display.SetBrightness(value);
+ };
+ self.subscription = display.RegisterForBrightnessChanges(state => {
+ const value = state?.flBrightness;
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1 || self.expected === null) return;
+ if (Math.abs(value - self.expected) < 0.0001) { self.updating = false; return; }
+ if (self.updating) return;
+ self.expected = value;
+ if (typeof window.__BINDING__ === "function") window.__BINDING__(String(value));
+ });
+ window.__droiddeckBrightness = self;
+ return "installed";
+})()
+""".replace("__BINDING__", BRIGHTNESS_BINDING)
+
+
+def brightness_request(payload, directory=CONTROLS_DIR):
+ try:
+ value = float(payload)
+ if not math.isfinite(value) or not 0 <= value <= 1:
+ return
+ path = os.path.join(directory, "brightness.request")
+ with open(path + ".tmp", "w") as target:
+ target.write(str(value) + "\n")
+ os.replace(path + ".tmp", path)
+ except (ValueError, TypeError, OSError):
+ return
+
+
INSTALL_JS = r"""
(() => {
if (window.__droiddeckCompat) return "present";
@@ -633,6 +676,20 @@ class Helper:
self.tools_checked = None
self.vr_launch = None
self.chooser = None
+ self.controls_state = None
+
+ def sync_controls(self):
+ try:
+ with open(os.path.join(CONTROLS_DIR, "state.json")) as source:
+ state = json.load(source)
+ value = state.get("brightness")
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 1:
+ return
+ if state != self.controls_state:
+ self.page.evaluate("window.__droiddeckBrightness?.set(%s)" % json.dumps(value))
+ self.controls_state = state
+ except (OSError, ValueError, TypeError):
+ pass
def open_chooser(self, payload):
try:
@@ -705,6 +762,10 @@ class Helper:
try:
if page.evaluate("typeof SteamClient === 'object' && typeof SteamClient.WebUITransport === 'object'") is not True:
raise LookupError("SteamClient is not ready")
+ if os.path.isfile(os.path.join(CONTROLS_DIR, "state.json")):
+ page.call("Runtime.addBinding", {"name": BRIGHTNESS_BINDING})
+ page.evaluate(BRIGHTNESS_JS)
+ self.controls_state = None
if self.files_only:
page.call("Runtime.addBinding", {"name": FILE_BINDING})
page.evaluate(FILE_JS)
@@ -854,6 +915,8 @@ class Helper:
say("preparing SteamVR for library app(s): " + ", ".join(sorted(vr_games)))
self.vr_launch = launch_steamvr()
for e in events:
+ if called(e, BRIGHTNESS_BINDING):
+ brightness_request(e.get("params", {}).get("payload"))
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
self.open_chooser(e["params"]["payload"])
return events
@@ -861,15 +924,14 @@ class Helper:
def serve_files(self):
say("attached to the client on port %d for its file dialogs" % self.port)
while True:
+ self.sync_controls()
sources = [self.page.ws] + ([self.chooser[1].stdout] if self.chooser is not None else [])
queued = self.page.ws.pending() or bool(self.page.events)
- ready = [self.page.ws] if queued else select.select(sources, [], [], 30)[0]
+ ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0]
if self.chooser is not None and self.chooser[1].stdout in ready:
self.chooser_done()
if self.page.ws in ready or self.page.events:
- for e in self.page.drain():
- if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
- self.open_chooser(e["params"]["payload"])
+ self.drain()
def serve(self, watcher):
if self.files_only:
@@ -880,10 +942,11 @@ class Helper:
self.reconcile()
self.ensure_tools()
while True:
+ self.sync_controls()
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
if self.chooser is not None:
sources.append(self.chooser[1].stdout)
- ready = [self.page.ws] if self.page.ws.pending() else select.select(sources, [], [], 30 if watcher.fileno() >= 0 else 2)[0]
+ ready = [self.page.ws] if self.page.ws.pending() else select.select(sources, [], [], 0.25)[0]
if self.chooser is not None and self.chooser[1].stdout in ready:
self.chooser_done()
due = False
diff --git a/tools/tests/test_device_controls.py b/tools/tests/test_device_controls.py
new file mode 100644
index 0000000000..3a513a89fa
--- /dev/null
+++ b/tools/tests/test_device_controls.py
@@ -0,0 +1,82 @@
+import json
+from pathlib import Path
+import runpy
+import subprocess
+import tempfile
+import unittest
+
+BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
+LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
+
+
+class DeviceControlsTest(unittest.TestCase):
+ def test_native_brightness_notifications_do_not_echo_android_readback(self):
+ harness = r"""
+const assert = require('assert');
+globalThis.window = globalThis;
+const requests = [], callbacks = [];
+let current = 1;
+window.droiddeckBrightnessChanged = value => requests.push(Number(value));
+globalThis.SteamClient = { System: { Display: {
+ RegisterForBrightnessChanges(cb) { callbacks.push(cb); cb({ flBrightness: 1 }); return {}; },
+ SetBrightness(value) {
+ if (current === value) return;
+ current = value;
+ callbacks.forEach(cb => cb({ flBrightness: value }));
+ }
+} } };
+const script = require('fs').readFileSync(process.argv[2], 'utf8');
+assert.strictEqual(eval(script), 'installed');
+assert.strictEqual(eval(script), 'present');
+const bridge = window.__droiddeckBrightness;
+bridge.set(0.5);
+bridge.set(0.5);
+assert.deepStrictEqual(requests, []);
+callbacks.forEach(cb => cb({ flBrightness: 0.8 }));
+assert.deepStrictEqual(requests, [0.8]);
+bridge.set(0.7992126);
+assert.deepStrictEqual(requests, [0.8]);
+for (const value of [NaN, Infinity, -1, 2, '0.5']) callbacks.forEach(cb => cb({ flBrightness: value }));
+assert.deepStrictEqual(requests, [0.8]);
+assert.strictEqual(callbacks.length, 1);
+"""
+ with tempfile.TemporaryDirectory() as directory:
+ script = Path(directory) / "bridge.js"
+ script.write_text(LIVE["BRIGHTNESS_JS"])
+ test = Path(directory) / "test.js"
+ test.write_text(harness)
+ result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20)
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_requests_reject_nonfinite_and_out_of_range_values(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "brightness.request"
+ for value in ["NaN", "Infinity", "-0.1", "1.1", "invalid", None]:
+ LIVE["brightness_request"](value, directory)
+ self.assertFalse(path.exists())
+ LIVE["brightness_request"]("0.4", directory)
+ self.assertEqual(float(path.read_text()), 0.4)
+
+ def test_failed_request_revision_republishes_the_actual_brightness(self):
+ with tempfile.TemporaryDirectory() as directory:
+ globals_ = LIVE["Helper"].sync_controls.__globals__
+ previous = globals_["CONTROLS_DIR"]
+ try:
+ globals_["CONTROLS_DIR"] = directory
+ helper = LIVE["Helper"]("/steam", 0)
+ calls = []
+ helper.page = type("Page", (), {"evaluate": lambda self, expression: calls.append(expression)})()
+ path = Path(directory) / "state.json"
+ path.write_text(json.dumps({"brightness": 0.5, "revision": 1}))
+ helper.sync_controls()
+ helper.sync_controls()
+ self.assertEqual(len(calls), 1)
+ path.write_text(json.dumps({"brightness": 0.5, "revision": 2}))
+ helper.sync_controls()
+ self.assertEqual(len(calls), 2)
+ finally:
+ globals_["CONTROLS_DIR"] = previous
+
+
+if __name__ == "__main__":
+ unittest.main()