use anyhow::{Context, Result, bail}; use serde_json::{Value, json}; use std::{ fs, io::{BufRead, BufReader, Write}, os::unix::{fs::DirBuilderExt, net::UnixStream}, path::PathBuf, process::{Child, Command, Stdio}, sync::mpsc::{self, Receiver}, time::{Duration, Instant}, }; #[derive(Debug)] pub enum PlayerEvent { Loaded, Position(f64), Duration(f64), Paused(bool), Finished, Error(String), } /// Keep the mpv transport boundary replaceable in tests without an audio device. pub trait Playback { fn command(&mut self, command: Value) -> Result<()>; fn drain_events(&self) -> Vec; } pub struct Player { child: Child, socket: UnixStream, directory: PathBuf, pub events: Receiver, } impl Player { /// A private IPC directory keeps stream authentication out of process arguments. pub fn start(volume: u8) -> Result { let directory = std::env::temp_dir().join(format!( "octo-tui-{}-{:x}", std::process::id(), rand::random::() )); fs::DirBuilder::new().mode(0o700).create(&directory)?; let path = directory.join("mpv.sock"); let spawned = Command::new("mpv") .args([ "--idle=yes", "--no-video", "--no-terminal", "--audio-display=no", "--input-terminal=no", ]) .arg(format!("--volume={volume}")) .arg(format!("--input-ipc-server={}", path.display())) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn(); let mut child = match spawned { Ok(child) => child, Err(_) => { let _ = fs::remove_dir_all(&directory); bail!("Install mpv to enable playback; browsing remains available"); } }; let deadline = Instant::now() + Duration::from_secs(3); let socket = loop { if let Ok(socket) = UnixStream::connect(&path) { break socket; } if Instant::now() > deadline || child.try_wait()?.is_some() { let _ = child.kill(); let _ = child.wait(); let _ = fs::remove_dir_all(&directory); bail!("mpv could not start its playback socket"); } std::thread::sleep(Duration::from_millis(20)); }; socket.set_write_timeout(Some(Duration::from_millis(200)))?; let reader = BufReader::new(socket.try_clone()?); let (tx, events) = mpsc::channel(); std::thread::spawn(move || { for line in reader.lines() { let Ok(line) = line else { break }; let Ok(v) = serde_json::from_str::(&line) else { continue; }; let event = player_event(&v); if let Some(event) = event && tx.send(event).is_err() { break; } } }); let mut player = Self { child, socket, directory, events, }; for (id, property) in ["time-pos", "duration", "pause"].iter().enumerate() { player.command(json!(["observe_property", id, property]))?; } Ok(player) } pub fn command(&mut self, command: Value) -> Result<()> { let mut request = json!({"command":command}); if request["command"][0] == "loadfile" { request["request_id"] = json!(1); } let message = serde_json::to_string(&request)?; writeln!(self.socket, "{message}").context("Cannot communicate with mpv") } } /// Use structured mpv errors only; never echo logs or URLs that can contain authentication. fn player_event(v: &Value) -> Option { if v["request_id"] == 1 && v["error"].as_str().is_some_and(|error| error != "success") { return Some(PlayerEvent::Error( "Playback failed: mpv rejected the loadfile command. Check the installed mpv version." .into(), )); } match v["event"].as_str() { Some("file-loaded") => Some(PlayerEvent::Loaded), Some("property-change") => match v["name"].as_str() { Some("time-pos") => v["data"].as_f64().map(PlayerEvent::Position), Some("duration") => v["data"].as_f64().map(PlayerEvent::Duration), Some("pause") => v["data"].as_bool().map(PlayerEvent::Paused), _ => None, }, Some("end-file") if v["reason"] == "eof" => Some(PlayerEvent::Finished), Some("end-file") if v["reason"] == "error" => { let reason = match v["file_error"].as_str().or_else(|| v["error"].as_str()) { Some("audio output initialization failed") => { "mpv cannot initialize audio output. Check its configured audio device." } Some("loading failed") | Some("error opening file") => { "mpv could not open the server stream. Check HTTP/TLS access, authentication, and song availability." } Some("unrecognized file format") => { "the server response is not a supported audio stream; it may be a sign-in page or server error." } Some("audio decoder initialization failed") | Some("decoding failed") => { "mpv could not decode the audio stream." } Some("no audio or video data played") => "the stream contained no playable audio.", _ => "mpv reported an unknown stream/output error.", }; Some(PlayerEvent::Error(format!("Playback failed: {reason}"))) } _ => None, } } impl Playback for Player { fn command(&mut self, command: Value) -> Result<()> { Player::command(self, command) } fn drain_events(&self) -> Vec { self.events.try_iter().collect() } } impl Drop for Player { fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); let _ = fs::remove_dir_all(&self.directory); } } #[cfg(test)] mod tests { use super::*; #[test] fn playback_failures_distinguish_stream_format_and_audio_output() { for (error, expected) in [ ("loading failed", "could not open the server stream"), ("unrecognized file format", "not a supported audio stream"), ( "audio output initialization failed", "cannot initialize audio output", ), ] { let event = player_event(&json!({"event":"end-file","reason":"error","file_error":error})); assert!( matches!(event, Some(PlayerEvent::Error(message)) if message.contains(expected)) ); } } #[test] fn errors_never_echo_unknown_server_text_or_signed_urls() { let secret = "https://example.invalid/stream?apiKey=private"; for reply in [ json!({"event":"end-file","reason":"error","file_error":secret}), json!({"request_id":1,"error":secret}), ] { let Some(PlayerEvent::Error(message)) = player_event(&reply) else { panic!("missing error") }; assert!(!message.contains(secret)); assert!(!message.contains("private")); } assert!(player_event(&json!({"request_id":1,"error":"success"})).is_none()); assert!(matches!( player_event(&json!({"event":"end-file","reason":"eof"})), Some(PlayerEvent::Finished) )); assert!(player_event(&json!({"event":"end-file","reason":"stop"})).is_none()); } }