feat: add a controller-driven Subsonic player for SteamOS

Browses a Subsonic library and plays it through mpv, driven by a
gamepad or keyboard. The UI scales from the window's physical height
rather than the compositor's scale factor, so it keeps its proportions
on a Steam Deck and on a 4K TV, where other players open small or
scale badly.
This commit is contained in:
Ansho Rei
2026-11-04 01:17:29 +01:00
commit 4105554f68
14 changed files with 10825 additions and 0 deletions
+186
View File
@@ -0,0 +1,186 @@
//! Playback through an mpv child process, controlled over its JSON IPC socket.
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
#[derive(Debug, Clone, Copy)]
pub enum PlayerEvent {
Position(f64),
Duration(f64),
Paused(bool),
/// Index into the mpv playlist, None when nothing is loaded.
Track(Option<usize>),
Exited,
}
const OBSERVED: [&str; 4] = ["time-pos", "duration", "pause", "playlist-pos"];
pub struct Player {
writer: Mutex<UnixStream>,
child: Mutex<Child>,
socket: PathBuf,
}
impl Player {
pub fn spawn(on_event: impl Fn(PlayerEvent) + Send + 'static) -> Result<Player> {
let dir = std::env::var_os("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.unwrap_or_else(std::env::temp_dir);
let socket = dir.join(format!("remus-mpv-{}.sock", std::process::id()));
let _ = std::fs::remove_file(&socket);
let mut cmd = Command::new("mpv");
cmd.args([
"--idle=yes",
"--config=no",
"--no-video",
"--no-terminal",
"--audio-display=no",
"--prefetch-playlist=yes",
"--cache=yes",
"--volume=100",
])
.arg(format!("--input-ipc-server={}", socket.display()))
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
// Take mpv down with us if we crash, so it never keeps playing orphaned.
unsafe {
cmd.pre_exec(|| {
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
Ok(())
});
}
let mut child = cmd.spawn().context("could not start mpv (is it installed?)")?;
let stream = (0..50).find_map(|_| {
UnixStream::connect(&socket).ok().or_else(|| {
std::thread::sleep(Duration::from_millis(100));
None
})
});
let Some(stream) = stream else {
let _ = child.kill();
bail!("mpv did not open its IPC socket at {}", socket.display());
};
let reader = BufReader::new(stream.try_clone()?);
std::thread::Builder::new().name("mpv-ipc".into()).spawn(move || {
for line in reader.lines() {
let Ok(line) = line else { break };
if let Some(ev) = parse_event(&line) {
on_event(ev);
}
}
on_event(PlayerEvent::Exited);
})?;
let player = Player {
writer: Mutex::new(stream),
child: Mutex::new(child),
socket,
};
for (i, name) in OBSERVED.iter().enumerate() {
player.command(json!(["observe_property", i + 1, name]));
}
Ok(player)
}
fn command(&self, args: Value) {
let mut line = json!({ "command": args }).to_string();
line.push('\n');
if let Ok(mut w) = self.writer.lock()
&& let Err(e) = w.write_all(line.as_bytes())
{
log::warn!("mpv ipc write failed: {e}");
}
}
/// Replaces the playlist with `urls` and starts at `start`.
pub fn play_list(&self, urls: &[String], start: usize) {
self.command(json!(["stop"]));
for url in urls {
self.command(json!(["loadfile", url, "append"]));
}
self.command(json!(["playlist-play-index", start]));
self.command(json!(["set_property", "pause", false]));
}
pub fn append(&self, url: &str) {
self.command(json!(["loadfile", url, "append-play"]));
}
pub fn play_index(&self, index: usize) {
self.command(json!(["playlist-play-index", index]));
self.command(json!(["set_property", "pause", false]));
}
pub fn toggle_pause(&self) {
self.command(json!(["cycle", "pause"]));
}
pub fn next(&self) {
self.command(json!(["playlist-next"]));
}
pub fn prev(&self) {
self.command(json!(["playlist-prev"]));
}
pub fn seek(&self, seconds: f64) {
self.command(json!(["seek", seconds, "relative"]));
}
}
impl Drop for Player {
fn drop(&mut self) {
self.command(json!(["quit"]));
if let Ok(mut child) = self.child.lock() {
std::thread::sleep(Duration::from_millis(50));
let _ = child.kill();
let _ = child.wait();
}
let _ = std::fs::remove_file(&self.socket);
}
}
fn parse_event(line: &str) -> Option<PlayerEvent> {
let v: Value = serde_json::from_str(line).ok()?;
if v.get("event")?.as_str()? != "property-change" {
return None;
}
let data = v.get("data");
match v.get("name")?.as_str()? {
"time-pos" => Some(PlayerEvent::Position(data.and_then(Value::as_f64).unwrap_or(0.0))),
"duration" => Some(PlayerEvent::Duration(data.and_then(Value::as_f64).unwrap_or(0.0))),
"pause" => Some(PlayerEvent::Paused(data.and_then(Value::as_bool).unwrap_or(false))),
"playlist-pos" => Some(PlayerEvent::Track(
data.and_then(Value::as_i64).filter(|&i| i >= 0).map(|i| i as usize),
)),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_property_changes() {
let ev = parse_event(r#"{"event":"property-change","id":4,"name":"playlist-pos","data":2}"#);
assert!(matches!(ev, Some(PlayerEvent::Track(Some(2)))));
let ev = parse_event(r#"{"event":"property-change","id":4,"name":"playlist-pos","data":-1}"#);
assert!(matches!(ev, Some(PlayerEvent::Track(None))));
let ev = parse_event(r#"{"event":"property-change","id":1,"name":"time-pos"}"#);
assert!(matches!(ev, Some(PlayerEvent::Position(p)) if p == 0.0));
assert!(parse_event(r#"{"request_id":0,"error":"success"}"#).is_none());
}
}