From af307549a8f22527ae71ac7c6d968bdba98a248e Mon Sep 17 00:00:00 2001 From: Ansho Rei Date: Wed, 4 Nov 2026 02:19:07 +0100 Subject: [PATCH] feat: play through GStreamer instead of mpv A Flatpak cannot run the host's mpv, and SteamOS does not ship one. GStreamer comes with the Flatpak runtime, so the player now drives playbin in-process. The next track is handed over in about-to-finish, which keeps playback gapless as it was with mpv. GStreamer's HTTP errors quote the stream URL, so its query string, which carries the auth token, is stripped before logging. --- Cargo.lock | 185 +++++++++++++++++++++- Cargo.toml | 2 +- README.md | 3 +- src/app.rs | 10 +- src/player.rs | 416 +++++++++++++++++++++++++++++++++++--------------- 5 files changed, 484 insertions(+), 132 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44cd83b..63ede86 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -728,6 +728,16 @@ dependencies = [ "nom 7.1.3", ] +[[package]] +name = "cfg-expr" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f" +dependencies = [ + "smallvec", + "target-lexicon", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -1735,6 +1745,19 @@ dependencies = [ "windows", ] +[[package]] +name = "gio-sys" +version = "0.22.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "windows-sys 0.61.2", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -1746,6 +1769,49 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glib" +version = "0.22.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "smallvec", +] + +[[package]] +name = "glib-macros" +version = "0.22.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "glib-sys" +version = "0.22.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295" +dependencies = [ + "libc", + "system-deps", +] + [[package]] name = "glob" version = "0.3.4" @@ -1830,6 +1896,17 @@ dependencies = [ "gl_generator", ] +[[package]] +name = "gobject-sys" +version = "0.22.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + [[package]] name = "gpu-allocator" version = "0.28.0" @@ -1850,6 +1927,44 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5" +[[package]] +name = "gstreamer" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4237e2066a25ecb7e54be6c066409e30615920265b9799b8d560ef8ac9857c6" +dependencies = [ + "cfg-if", + "futures-channel", + "futures-core", + "futures-util", + "glib", + "gstreamer-sys", + "itertools 0.15.0", + "kstring", + "libc", + "muldiv", + "num-integer", + "num-rational", + "option-operations", + "pastey", + "pin-project-lite", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "gstreamer-sys" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436d9532847489a8285d57b8c3670762c12a18f777fdc2ab159b52e0e6f521b9" +dependencies = [ + "cfg-if", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + [[package]] name = "half" version = "2.7.1" @@ -2835,6 +2950,15 @@ dependencies = [ "zbus", ] +[[package]] +name = "kstring" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a09b82a7f771ed02dc0dd9b27130a0fa5499fa15ed3027116c1e5e4e591bd9e" +dependencies = [ + "static_assertions", +] + [[package]] name = "kurbo" version = "0.13.1" @@ -3120,6 +3244,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "muldiv" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0" + [[package]] name = "naga" version = "30.0.1" @@ -3225,6 +3355,25 @@ dependencies = [ "memchr", ] +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -3619,6 +3768,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "option-operations" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754" +dependencies = [ + "pastey", +] + [[package]] name = "orbclient" version = "0.3.55" @@ -4234,8 +4392,8 @@ dependencies = [ "env_logger", "fontique", "gilrs", + "gstreamer", "image", - "libc", "log", "lru", "md5", @@ -5048,6 +5206,19 @@ dependencies = [ "web-sys", ] +[[package]] +name = "system-deps" +version = "9.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml", + "version-compare", +] + [[package]] name = "taffy" version = "0.10.1" @@ -5071,6 +5242,12 @@ dependencies = [ "xattr", ] +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "task-local" version = "0.1.1" @@ -5585,6 +5762,12 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" diff --git a/Cargo.toml b/Cargo.toml index 8a68bbd..9d7644b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,8 +10,8 @@ directories = "6.0.0" env_logger = "0.11.11" fontique = { version = "0.11", default-features = false, features = ["fontconfig-dlopen"] } gilrs = "0.11.2" +gstreamer = "0.25.4" image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp"] } -libc = "0.2.191" log = "0.4.35" lru = "0.19.0" md5 = "0.8.1" diff --git a/README.md b/README.md index b80f370..76d8eb7 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,8 @@ It opens fullscreen. Its UI is sized from the window's physical height, not from ## Requirements -- `mpv` on the PATH. remus runs it as a child process and controls it over its JSON IPC socket. +- GStreamer 1.24 or newer with the base and good plugins, for playback. The Flatpak brings its own. +- To build outside the Flatpak: `libgstreamer1.0-dev` and `libgstreamer-plugins-base1.0-dev` (Debian/Ubuntu names). - A Subsonic or OpenSubsonic server (Navidrome, Gonic, Airsonic...). ## Run diff --git a/src/app.rs b/src/app.rs index 6e7597c..99eef98 100644 --- a/src/app.rs +++ b/src/app.rs @@ -56,7 +56,7 @@ pub fn install(ui: &AppWindow, rt: Handle) { with_app(|app| app.start()); } -/// Drops the app, which stops mpv. +/// Drops the app, which stops playback. pub fn shutdown() { let app = APP.with(|cell| cell.borrow_mut().take()); drop(app); @@ -1290,7 +1290,7 @@ impl App { fn play_songs(&mut self, songs: Vec, start: usize) { let Some(client) = &self.client else { return }; let Some(player) = &self.player else { - self.toast("Playback is unavailable: mpv is not running".into()); + self.toast("Playback is unavailable: GStreamer could not start".into()); return; }; let urls: Vec = songs.iter().map(|s| client.stream_url(&s.id)).collect(); @@ -1304,7 +1304,7 @@ impl App { fn enqueue(&mut self, songs: Vec, what: String) { let Some(client) = &self.client else { return }; let Some(player) = &self.player else { - self.toast("Playback is unavailable: mpv is not running".into()); + self.toast("Playback is unavailable: GStreamer could not start".into()); return; }; if songs.is_empty() { @@ -1396,10 +1396,6 @@ impl App { self.sync_items(true); self.sync_queue(true); } - PlayerEvent::Exited => { - self.player = None; - self.toast("Playback stopped: mpv exited".into()); - } } } diff --git a/src/player.rs b/src/player.rs index 02d883b..2df9bc5 100644 --- a/src/player.rs +++ b/src/player.rs @@ -1,186 +1,358 @@ -//! Playback through an mpv child process, controlled over its JSON IPC socket. +//! Playback through GStreamer's playbin. The queue lives here so the next +//! track can be handed to playbin in `about-to-finish`, which keeps playback +//! gapless. -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 std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; -use anyhow::{Context, Result, bail}; -use serde_json::{Value, json}; +use anyhow::{Context, Result}; +use gstreamer as gst; +use gstreamer::prelude::*; #[derive(Debug, Clone, Copy)] pub enum PlayerEvent { Position(f64), Duration(f64), Paused(bool), - /// Index into the mpv playlist, None when nothing is loaded. + /// Index into the queue, None when playback has stopped. Track(Option), - Exited, } -const OBSERVED: [&str; 4] = ["time-pos", "duration", "pause", "playlist-pos"]; +#[derive(Default)] +struct Queue { + urls: Vec, + current: Option, + /// Handed to playbin, becomes `current` at its stream-start. + pending: Option, +} pub struct Player { - writer: Mutex, - child: Mutex, - socket: PathBuf, + playbin: gst::Element, + queue: Arc>, + stop: Arc, + bus_thread: Option>, } +const TICK: Duration = Duration::from_millis(250); + impl Player { pub fn spawn(on_event: impl Fn(PlayerEvent) + Send + 'static) -> Result { - 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(()) - }); + gst::init().context("could not initialise GStreamer")?; + let playbin = gst::ElementFactory::make("playbin") + .build() + .context("GStreamer's playbin is missing (gst-plugins-base)")?; + if let Ok(sink) = gst::ElementFactory::make("fakesink").build() { + playbin.set_property("video-sink", &sink); + } + // Tests and headless runs: REMUS_AUDIO_SINK=fakesink plays in real time without a device. + if let Ok(name) = std::env::var("REMUS_AUDIO_SINK") + && let Ok(sink) = gst::ElementFactory::make(&name).property("sync", true).build() + { + playbin.set_property("audio-sink", &sink); } - 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); - } + let queue = Arc::new(Mutex::new(Queue::default())); + let q = queue.clone(); + playbin.connect("about-to-finish", false, move |args| { + let playbin = args[0].get::().ok()?; + let mut q = lock(&q); + let next = q.current.map_or(0, |c| c + 1); + if let Some(url) = q.urls.get(next).cloned() { + q.pending = Some(next); + playbin.set_property("uri", url); } - on_event(PlayerEvent::Exited); + None + }); + + let stop = Arc::new(AtomicBool::new(false)); + let bus_thread = std::thread::Builder::new().name("gst-bus".into()).spawn({ + let (playbin, queue, stop) = (playbin.clone(), queue.clone(), stop.clone()); + move || watch_bus(&playbin, &queue, &stop, &on_event) })?; - 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) + Ok(Player { + playbin, + queue, + stop, + bus_thread: Some(bus_thread), + }) } - 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`. + /// Replaces the queue 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"])); + { + let mut q = lock(&self.queue); + q.urls = urls.to_vec(); + q.current = None; + q.pending = None; } - self.command(json!(["playlist-play-index", start])); - self.command(json!(["set_property", "pause", false])); + self.play_index(start); } + /// Adds to the end of the queue, starting playback if it had stopped. pub fn append(&self, url: &str) { - self.command(json!(["loadfile", url, "append-play"])); + let start = { + let mut q = lock(&self.queue); + q.urls.push(url.to_string()); + (q.current.is_none() && q.pending.is_none()).then(|| q.urls.len() - 1) + }; + if let Some(i) = start { + self.play_index(i); + } } pub fn play_index(&self, index: usize) { - self.command(json!(["playlist-play-index", index])); - self.command(json!(["set_property", "pause", false])); + let url = { + let mut q = lock(&self.queue); + let Some(url) = q.urls.get(index).cloned() else { return }; + q.pending = Some(index); + url + }; + // Not under the lock: a state change waits for the streaming threads, + // and about-to-finish runs on one of them and takes the lock. + start(&self.playbin, &url); } pub fn toggle_pause(&self) { - self.command(json!(["cycle", "pause"])); + let target = match self.playbin.current_state() { + gst::State::Playing => gst::State::Paused, + gst::State::Paused => gst::State::Playing, + _ => return, + }; + let _ = self.playbin.set_state(target); } pub fn next(&self) { - self.command(json!(["playlist-next"])); + let next = lock(&self.queue).current.map(|c| c + 1); + if let Some(i) = next { + self.play_index(i); + } } pub fn prev(&self) { - self.command(json!(["playlist-prev"])); + let prev = lock(&self.queue).current.map(|c| c.saturating_sub(1)); + if let Some(i) = prev { + self.play_index(i); + } } pub fn seek(&self, seconds: f64) { - self.command(json!(["seek", seconds, "relative"])); + let Some(pos) = self.playbin.query_position::() else { + return; + }; + let mut target = (pos.seconds_f64() + seconds).max(0.0); + if let Some(dur) = self.playbin.query_duration::() { + target = target.min((dur.seconds_f64() - 1.0).max(0.0)); + } + let flags = gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT; + if let Err(e) = self + .playbin + .seek_simple(flags, gst::ClockTime::from_seconds_f64(target)) + { + log::debug!("seek failed: {e}"); + } } } 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(); + self.stop.store(true, Ordering::Relaxed); + let _ = self.playbin.set_state(gst::State::Null); + if let Some(t) = self.bus_thread.take() { + let _ = t.join(); } - let _ = std::fs::remove_file(&self.socket); } } -fn parse_event(line: &str) -> Option { - let v: Value = serde_json::from_str(line).ok()?; - if v.get("event")?.as_str()? != "property-change" { - return None; +fn lock(q: &Mutex) -> MutexGuard<'_, Queue> { + q.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn start(playbin: &gst::Element, url: &str) { + let _ = playbin.set_state(gst::State::Ready); + playbin.set_property("uri", url); + if let Err(e) = playbin.set_state(gst::State::Playing) { + log::warn!("could not start playback: {e}"); } - 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, +} + +fn watch_bus(playbin: &gst::Element, queue: &Mutex, stop: &AtomicBool, emit: &dyn Fn(PlayerEvent)) { + let Some(bus) = playbin.bus() else { return }; + let mut last_tick = Instant::now(); + let mut duration = 0.0; + // playbin can post stream-start more than once for one track. + let mut last_track: Option> = None; + let mut report_track = |t: Option| { + if last_track != Some(t) { + last_track = Some(t); + emit(PlayerEvent::Track(t)); + emit(PlayerEvent::Position(0.0)); + } + }; + while !stop.load(Ordering::Relaxed) { + if let Some(msg) = bus.timed_pop(gst::ClockTime::from_mseconds(TICK.as_millis() as u64)) { + use gst::MessageView; + match msg.view() { + MessageView::StreamStart(_) => { + let current = { + let mut q = lock(queue); + if let Some(p) = q.pending.take() { + q.current = Some(p); + } + q.current + }; + duration = 0.0; + report_track(current); + } + MessageView::StateChanged(s) if s.src() == Some(playbin.upcast_ref()) => match s.current() { + gst::State::Playing => emit(PlayerEvent::Paused(false)), + gst::State::Paused if s.pending() == gst::State::VoidPending => emit(PlayerEvent::Paused(true)), + _ => {} + }, + MessageView::Eos(_) => { + { + let mut q = lock(queue); + q.current = None; + q.pending = None; + } + let _ = playbin.set_state(gst::State::Ready); + report_track(None); + } + MessageView::Error(err) => { + let detail = err.debug().map(|d| d.to_string()).unwrap_or_default(); + log::warn!("playback error: {} ({})", err.error(), strip_queries(&detail)); + // Skip the track that failed rather than stopping the queue. + let (next, len) = { + let mut q = lock(queue); + let failed = q.pending.take().or(q.current); + q.current = None; + (failed.map_or(usize::MAX, |i| i + 1), q.urls.len()) + }; + if next < len { + let url = { + let mut q = lock(queue); + q.pending = Some(next); + q.urls[next].clone() + }; + start(playbin, &url); + } else { + let _ = playbin.set_state(gst::State::Ready); + report_track(None); + } + } + _ => {} + } + } + if last_tick.elapsed() >= TICK { + last_tick = Instant::now(); + if playbin.current_state() == gst::State::Playing { + if let Some(p) = playbin.query_position::() { + emit(PlayerEvent::Position(p.seconds_f64())); + } + if let Some(d) = playbin.query_duration::() + && (d.seconds_f64() - duration).abs() > 0.5 + { + duration = d.seconds_f64(); + emit(PlayerEvent::Duration(duration)); + } + } + } } } +/// Removes the query string from any URL in `text`. Stream URLs carry the +/// Subsonic auth token, and GStreamer's HTTP errors quote the URL. +fn strip_queries(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut in_query = false; + let mut in_url = false; + for (i, c) in text.char_indices() { + let ends_url = c.is_whitespace() + || matches!(c, '"' | '\'' | ')' | '>') + // "…?a=b, next" in prose: the comma closes the URL. + || (c == ',' && text[i + 1..].starts_with(char::is_whitespace)); + if ends_url { + in_url = false; + in_query = false; + } else if !in_url && (text[i..].starts_with("http://") || text[i..].starts_with("https://")) { + in_url = true; + } else if in_url && c == '?' { + in_query = true; + out.push_str("?…"); + continue; + } + if !in_query { + out.push(c); + } + } + out +} + #[cfg(test)] mod tests { use super::*; + use std::sync::mpsc; #[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()); + fn queries_are_stripped_from_urls() { + let s = strip_queries("Not Found (404), URL: https://h/rest/stream?u=a&t=secret&s=salt, Redirect to: (NULL)"); + assert_eq!(s, "Not Found (404), URL: https://h/rest/stream?…, Redirect to: (NULL)"); + assert!(!strip_queries("\"http://x/y?t=secret\" next").contains("secret")); + assert_eq!(strip_queries("what? no url here"), "what? no url here"); + } + + /// Writes `secs` of silence as a 16-bit mono WAV and returns its file:// URI. + fn silent_wav(dir: &std::path::Path, name: &str, secs: f32) -> String { + let rate = 8000u32; + let samples = (rate as f32 * secs) as u32; + let data_len = samples * 2; + let mut b = Vec::new(); + b.extend_from_slice(b"RIFF"); + b.extend_from_slice(&(36 + data_len).to_le_bytes()); + b.extend_from_slice(b"WAVEfmt "); + b.extend_from_slice(&16u32.to_le_bytes()); + b.extend_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&rate.to_le_bytes()); + b.extend_from_slice(&(rate * 2).to_le_bytes()); + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&16u16.to_le_bytes()); + b.extend_from_slice(b"data"); + b.extend_from_slice(&data_len.to_le_bytes()); + b.resize(b.len() + data_len as usize, 0); + let path = dir.join(name); + std::fs::write(&path, b).unwrap(); + format!("file://{}", path.display()) + } + + #[test] + fn plays_a_queue_through_to_the_end() { + // SAFETY: set before any thread reads the environment in this test. + unsafe { std::env::set_var("REMUS_AUDIO_SINK", "fakesink") }; + let dir = std::env::temp_dir().join(format!("remus-player-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let urls = vec![silent_wav(&dir, "a.wav", 0.6), silent_wav(&dir, "b.wav", 0.6)]; + + let (tx, rx) = mpsc::channel(); + let player = Player::spawn(move |ev| { + if let PlayerEvent::Track(t) = ev { + let _ = tx.send(t); + } + }) + .unwrap(); + player.play_list(&urls, 0); + + let mut tracks = Vec::new(); + while let Ok(t) = rx.recv_timeout(Duration::from_secs(5)) { + tracks.push(t); + if t.is_none() { + break; + } + } + drop(player); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(tracks, vec![Some(0), Some(1), None]); } }