mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 05:16:01 +00:00
feat(steam): sync QAM brightness and volume with Android
This commit is contained in:
1 parent
da127d1b4c
commit
6a5dfe1486
11 files changed
+575
-7
No files matched your search
@@ -0,0 +1,96 @@
|
||||
/* SPDX-License-Identifier: LGPL-2.1-or-later */
|
||||
#include <stdio.h>
|
||||
#include <pulsecore/core-rtclock.h>
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -42,6 +42,7 @@ PA_MODULE_USAGE(
|
||||
"channels=<number of channels> "
|
||||
"channel_map=<channel map> "
|
||||
"volume=<initial volume, linear, 1.0 = full> "
|
||||
"control_dir=<Android media volume bridge directory> "
|
||||
"performance_mode=<0 none, 1 low latency, 2 power saving> "
|
||||
"adaptive=<grow the buffer after underruns: 0 or 1> "
|
||||
"buffer_frames=<initial buffer size in frames, 0 = two bursts> "
|
||||
@@ -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) {
|
||||
|
||||
@@ -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=<Android media volume bridge directory> "
|
||||
"sink_name=<name for the sink> "
|
||||
"sink_properties=<properties for the sink> "
|
||||
"volume=<initial volume, linear, 1.0 = full> "
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user