From 597462c88632bbb2e3e0bff4e04eec530760d955 Mon Sep 17 00:00:00 2001 From: Tomjerri1 <151880307+Tomjerri1@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:32:34 +0200 Subject: [PATCH 01/16] feat(cast): add mDNS device discovery crate --- Cargo.lock | 208 +++++++++++++++++++++- Cargo.toml | 1 + crates/cast/Cargo.toml | 13 ++ crates/cast/examples/discover.rs | 17 ++ crates/cast/examples/play.rs | 130 ++++++++++++++ crates/cast/src/discovery.rs | 156 +++++++++++++++++ crates/cast/src/lib.rs | 6 + crates/cast/src/session.rs | 287 +++++++++++++++++++++++++++++++ 8 files changed, 814 insertions(+), 4 deletions(-) create mode 100644 crates/cast/Cargo.toml create mode 100644 crates/cast/examples/discover.rs create mode 100644 crates/cast/examples/play.rs create mode 100644 crates/cast/src/discovery.rs create mode 100644 crates/cast/src/lib.rs create mode 100644 crates/cast/src/session.rs diff --git a/Cargo.lock b/Cargo.lock index 9a41a2230..abd3b5389 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -414,6 +414,29 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "az" version = "1.3.0" @@ -739,6 +762,18 @@ dependencies = [ "toml 0.9.12+spec-1.1.0", ] +[[package]] +name = "cast" +version = "1.4.0-rc.10" +dependencies = [ + "anyhow", + "mdns-sd", + "rust_cast", + "serde", + "tokio", + "tracing", +] + [[package]] name = "cc" version = "1.2.65" @@ -746,6 +781,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex 2.0.1", ] @@ -869,6 +906,15 @@ dependencies = [ "error-code", ] +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "cocoa" version = "0.24.1" @@ -1395,7 +1441,7 @@ dependencies = [ "percent-encoding", "serde", "thiserror 2.0.18", - "which", + "which 6.0.3", "winapi", ] @@ -2052,6 +2098,17 @@ dependencies = [ "miniz_oxide 0.8.9", ] +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + [[package]] name = "fnv" version = "1.0.7" @@ -2127,6 +2184,12 @@ version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb540cf7bc4fe6df9d8f7f0c974cfd0dce8ed4e9e8884e73433b503ee78b4e7d" +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "fsevent-sys" version = "4.1.0" @@ -3017,6 +3080,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "if-addrs" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "if_chain" version = "1.0.3" @@ -3287,6 +3360,16 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.103" @@ -3444,9 +3527,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.186" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libdbus-sys" @@ -3984,6 +4067,21 @@ dependencies = [ "digest", ] +[[package]] +name = "mdns-sd" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6743ed743ff2bada2b8651ef298d3f98addb0b74844f19cdd57137d8bd0219e" +dependencies = [ + "fastrand 2.4.1", + "flume", + "if-addrs", + "log", + "mio", + "socket-pktinfo", + "socket2 0.6.4", +] + [[package]] name = "memchr" version = "2.8.2" @@ -5103,6 +5201,57 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "protobuf" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d65a1d4ddae7d8b5de68153b48f6aa3bba8cb002b243dbdbc55a5afbc98f99f4" +dependencies = [ + "once_cell", + "protobuf-support", + "thiserror 1.0.69", +] + +[[package]] +name = "protobuf-codegen" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d3976825c0014bbd2f3b34f0001876604fe87e0c86cd8fa54251530f1544ace" +dependencies = [ + "anyhow", + "once_cell", + "protobuf", + "protobuf-parse", + "regex", + "tempfile", + "thiserror 1.0.69", +] + +[[package]] +name = "protobuf-parse" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4aeaa1f2460f1d348eeaeed86aea999ce98c1bded6f089ff8514c9d9dbdc973" +dependencies = [ + "anyhow", + "indexmap 2.14.0", + "log", + "protobuf", + "protobuf-support", + "tempfile", + "thiserror 1.0.69", + "which 4.4.2", +] + +[[package]] +name = "protobuf-support" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e36c2f31e0a47f9280fb347ef5e461ffcd2c52dd520d8e216b52f93b0b0d7d6" +dependencies = [ + "thiserror 1.0.69", +] + [[package]] name = "pxfm" version = "0.1.30" @@ -5562,6 +5711,23 @@ dependencies = [ "smallvec", ] +[[package]] +name = "rust_cast" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "235d09067a35143d271fdeaf28298b4f729b5da50abdbf3b9e6395262d8bc7a9" +dependencies = [ + "byteorder", + "log", + "protobuf", + "protobuf-codegen", + "rustls", + "rustls-native-certs", + "serde", + "serde_json", + "thiserror 2.0.18", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -5652,6 +5818,7 @@ version = "0.23.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" dependencies = [ + "aws-lc-rs", "log", "once_cell", "ring", @@ -5716,6 +5883,7 @@ version = "0.103.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -6235,6 +6403,17 @@ version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +[[package]] +name = "socket-pktinfo" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "512f5c35377cf69f350b106df2366c3a1df6bd01b047a7a58c8390b70d28838d" +dependencies = [ + "libc", + "socket2 0.6.4", + "windows-sys 0.61.2", +] + [[package]] name = "socket2" version = "0.4.10" @@ -6341,6 +6520,15 @@ dependencies = [ "zvariant 3.15.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -7950,7 +8138,7 @@ dependencies = [ "miniz_oxide 0.7.4", "once_cell", "paste", - "which", + "which 6.0.3", ] [[package]] @@ -8359,6 +8547,18 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + [[package]] name = "which" version = "6.0.3" diff --git a/Cargo.toml b/Cargo.toml index 46c789525..3c1b3de39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ members = [ "crates/listen-protocol", "crates/sync-server", "crates/karaoke", + "crates/cast", "src-tauri", ] diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml new file mode 100644 index 000000000..5ac54ba9a --- /dev/null +++ b/crates/cast/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "cast" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +mdns-sd = "0.21.7" +rust_cast = "0.21.0" +serde.workspace = true +tokio.workspace = true +tracing.workspace = true diff --git a/crates/cast/examples/discover.rs b/crates/cast/examples/discover.rs new file mode 100644 index 000000000..4eff27131 --- /dev/null +++ b/crates/cast/examples/discover.rs @@ -0,0 +1,17 @@ +use std::time::Duration; + +fn main() { + println!("Browsing for Chromecast devices for 5 seconds..."); + match cast::browse(Duration::from_secs(5)) { + Ok(devices) => { + println!("Found {} devices:", devices.len()); + for d in devices { + println!( + " - ID: {}, Name: {}, Model: {:?}, IP: {}:{}", + d.id, d.name, d.model, d.ip, d.port + ); + } + } + Err(e) => eprintln!("Error browsing for devices: {}", e), + } +} diff --git a/crates/cast/examples/play.rs b/crates/cast/examples/play.rs new file mode 100644 index 000000000..034c548d0 --- /dev/null +++ b/crates/cast/examples/play.rs @@ -0,0 +1,130 @@ +use cast::{CastEvent, CastSession, LoadRequest}; +use std::env; +use std::io::{self, Write}; +use std::net::IpAddr; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let args: Vec = env::args().collect(); + if args.len() < 3 { + eprintln!("Usage: cargo run --example play -- "); + std::process::exit(1); + } + + let ip: IpAddr = args[1].parse()?; + let media_url = args[2].clone(); + + println!("Connecting to Chromecast at {}...", ip); + let session = CastSession::connect(ip, 8009)?; + let mut events = session.events(); + + // Spawn task to print events from the session + tokio::spawn(async move { + while let Some(event) = events.recv().await { + match event { + CastEvent::Status { + state, + position_secs, + duration_secs, + idle_reason, + volume, + } => { + println!( + "[Status] State: {:?}, Position: {:.1}s, Duration: {:?}, IdleReason: {:?}, Volume: {:.0}%", + state, + position_secs, + duration_secs, + idle_reason, + volume * 100.0 + ); + } + CastEvent::Disconnected(reason) => { + println!("[Disconnected] {}", reason); + break; + } + } + } + }); + + println!("Loading media: {}...", media_url); + session.load(LoadRequest { + url: media_url, + content_type: "audio/mp3".to_string(), + title: Some("Limusic Track".to_string()), + artist: Some("Limusic".to_string()), + image_url: None, + start_secs: 0.0, + autoplay: true, + })?; + + println!("Commands:"); + println!(" p - Pause"); + println!(" r - Resume (Play)"); + println!(" s - Seek to seconds"); + println!(" v <0-100> - Set volume (0-100)"); + println!(" q - Quit"); + + let stdin = io::stdin(); + let mut line = String::new(); + + loop { + line.clear(); + print!("> "); + io::stdout().flush()?; + if stdin.read_line(&mut line)? == 0 { + break; + } + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + + let parts: Vec<&str> = trimmed.split_whitespace().collect(); + match parts[0] { + "p" => { + session.pause()?; + println!("Paused"); + } + "r" => { + session.play()?; + println!("Resumed"); + } + "s" => { + if parts.len() > 1 { + if let Ok(secs) = parts[1].parse::() { + session.seek(secs)?; + println!("Seeking to {:.1}s...", secs); + } else { + println!("Invalid seconds."); + } + } else { + println!("Usage: s "); + } + } + "v" => { + if parts.len() > 1 { + if let Ok(vol) = parts[1].parse::() { + let level = (vol / 100.0).clamp(0.0, 1.0); + session.set_volume(level)?; + println!("Volume set to {:.0}%", vol); + } else { + println!("Invalid volume."); + } + } else { + println!("Usage: v <0-100>"); + } + } + "q" => { + session.stop()?; + session.quit()?; + println!("Quitting..."); + break; + } + _ => { + println!("Unknown command. Use: p, r, s , v <0-100>, q"); + } + } + } + + Ok(()) +} diff --git a/crates/cast/src/discovery.rs b/crates/cast/src/discovery.rs new file mode 100644 index 000000000..c8f03c302 --- /dev/null +++ b/crates/cast/src/discovery.rs @@ -0,0 +1,156 @@ +use std::collections::HashMap; +use std::net::IpAddr; +use std::sync::mpsc; +use std::time::Duration; +use mdns_sd::{ResolvedService, ServiceDaemon, ServiceEvent}; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +pub struct CastDevice { + pub id: String, + pub name: String, + pub model: Option, + pub ip: IpAddr, + pub port: u16, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DiscoveryEvent { + Found(CastDevice), + Lost(String), +} + +pub struct WatchHandle { + daemon: ServiceDaemon, +} + +impl Drop for WatchHandle { + fn drop(&mut self) { + let _ = self.daemon.stop_browse("_googlecast._tcp.local."); + } +} + +/// Pure function to parse TXT properties into (id, friendly_name, model). +pub fn parse_txt_properties(get_val: impl Fn(&str) -> Option) -> (Option, Option, Option) { + let id = get_val("id"); + let name = get_val("fn"); + let model = get_val("md"); + (id, name, model) +} + +fn service_info_to_device(info: &ResolvedService) -> Option { + let (id_opt, name_opt, model_opt) = parse_txt_properties(|key| info.get_property_val_str(key).map(|s| s.to_string())); + let id = id_opt.or_else(|| { + Some(info.get_fullname().to_string()) + })?; + + let name = name_opt.unwrap_or_else(|| info.get_hostname().to_string()); + let port = info.get_port(); + + // Prefer an IPv4 address + let addresses = info.get_addresses(); + let mut chosen_ip = None; + for addr in addresses { + if let Ok(ip) = addr.to_string().parse::() { + if ip.is_ipv4() { + chosen_ip = Some(ip); + break; + } + } + } + let ip = chosen_ip.or_else(|| { + addresses.iter().find_map(|a| a.to_string().parse::().ok()) + })?; + + Some(CastDevice { + id, + name, + model: model_opt, + ip, + port, + }) +} + +pub fn browse(timeout: Duration) -> anyhow::Result> { + let mdns = ServiceDaemon::new()?; + let receiver = mdns.browse("_googlecast._tcp.local.")?; + + let deadline = std::time::Instant::now() + timeout; + let mut devices = HashMap::new(); + + while let Some(remaining) = deadline.checked_duration_since(std::time::Instant::now()) { + match receiver.recv_timeout(remaining) { + Ok(event) => match event { + ServiceEvent::ServiceResolved(info) => { + if let Some(device) = service_info_to_device(&info) { + tracing::debug!(device_id = %device.id, device_name = %device.name, "Discovered Cast device"); + devices.insert(device.id.clone(), device); + } + } + ServiceEvent::ServiceRemoved(_service_type, _fullname) => {} + _ => {} + }, + Err(_) => break, + } + } + + let _ = mdns.stop_browse("_googlecast._tcp.local."); + + Ok(devices.into_values().collect()) +} + +pub fn watch() -> (mpsc::Receiver, WatchHandle) { + let (tx, rx) = mpsc::channel(); + let mdns = ServiceDaemon::new().expect("failed to start mdns daemon"); + let receiver = mdns.browse("_googlecast._tcp.local.").expect("failed to browse mdns"); + + std::thread::spawn(move || { + let mut known_devices: HashMap = HashMap::new(); + while let Ok(event) = receiver.recv() { + match event { + ServiceEvent::ServiceResolved(info) => { + if let Some(device) = service_info_to_device(&info) { + tracing::debug!(device_id = %device.id, device_name = %device.name, "Watch: discovered Cast device"); + known_devices.insert(device.id.clone(), info.get_fullname().to_string()); + let _ = tx.send(DiscoveryEvent::Found(device)); + } + } + ServiceEvent::ServiceRemoved(_service_type, fullname) => { + let mut removed_id = None; + for (id, fn_str) in &known_devices { + if fn_str == &fullname { + removed_id = Some(id.clone()); + break; + } + } + if let Some(id) = removed_id { + tracing::debug!(device_id = %id, "Watch: lost Cast device"); + known_devices.remove(&id); + let _ = tx.send(DiscoveryEvent::Lost(id)); + } + } + _ => {} + } + } + }); + + (rx, WatchHandle { daemon: mdns }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_parse_txt_properties() { + let map = HashMap::from([ + ("id".to_string(), "12345".to_string()), + ("fn".to_string(), "Living Room TV".to_string()), + ("md".to_string(), "Chromecast Ultra".to_string()), + ]); + + let (id, name, model) = parse_txt_properties(|k| map.get(k).cloned()); + assert_eq!(id.as_deref(), Some("12345")); + assert_eq!(name.as_deref(), Some("Living Room TV")); + assert_eq!(model.as_deref(), Some("Chromecast Ultra")); + } +} diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs new file mode 100644 index 000000000..a24b5315e --- /dev/null +++ b/crates/cast/src/lib.rs @@ -0,0 +1,6 @@ +pub mod discovery; +pub mod session; + +pub use discovery::{browse, watch, CastDevice, DiscoveryEvent, WatchHandle}; +pub use session::{CastEvent, CastSession, LoadRequest}; + diff --git a/crates/cast/src/session.rs b/crates/cast/src/session.rs new file mode 100644 index 000000000..01c3907d5 --- /dev/null +++ b/crates/cast/src/session.rs @@ -0,0 +1,287 @@ +use std::net::IpAddr; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; + +use rust_cast::{ + channels::media::{ + IdleReason, Image, LoadOptions, Media, Metadata, MusicTrackMediaMetadata, PlayerState, + StatusEntry, StreamType, + }, + channels::receiver::CastDeviceApp, + CastDevice, ChannelMessage, +}; + +/// Request parameters for loading media onto the Chromecast. +#[derive(Clone, Debug)] +pub struct LoadRequest { + pub url: String, + pub content_type: String, + pub title: Option, + pub artist: Option, + pub image_url: Option, + pub start_secs: f64, + pub autoplay: bool, +} + +/// Events emitted by the Chromecast session. +#[derive(Clone, Debug, PartialEq)] +pub enum CastEvent { + Status { + state: PlayerState, + position_secs: f64, + duration_secs: Option, + idle_reason: Option, + volume: f64, + }, + Disconnected(String), +} + +#[derive(Debug)] +enum Command { + Load(LoadRequest), + Play, + Pause, + Seek(f64), + Stop, + SetVolume(f32), + SetMuted(bool), + Quit, +} + +/// Manages an active Chromecast session and its background control thread. +#[derive(Clone)] +pub struct CastSession { + cmd_tx: std::sync::mpsc::Sender, + event_rx: Arc>>>, +} + +impl CastSession { + /// Connects to a Chromecast device at the given IP and port. + pub fn connect(ip: IpAddr, port: u16) -> anyhow::Result { + let (cmd_tx, cmd_rx) = std::sync::mpsc::channel(); + let (event_tx, event_rx) = mpsc::unbounded_channel(); + + std::thread::spawn(move || { + if let Err(e) = run_worker(ip, port, cmd_rx, event_tx.clone()) { + let _ = event_tx.send(CastEvent::Disconnected(e.to_string())); + } + }); + + Ok(Self { + cmd_tx, + event_rx: Arc::new(Mutex::new(Some(event_rx))), + }) + } + + /// Returns the event receiver for streaming player status and disconnection events. + pub fn events(&self) -> UnboundedReceiver { + self.event_rx + .lock() + .unwrap() + .take() + .expect("events receiver already taken") + } + + pub fn load(&self, req: LoadRequest) -> anyhow::Result<()> { + self.cmd_tx.send(Command::Load(req))?; + Ok(()) + } + + pub fn play(&self) -> anyhow::Result<()> { + self.cmd_tx.send(Command::Play)?; + Ok(()) + } + + pub fn pause(&self) -> anyhow::Result<()> { + self.cmd_tx.send(Command::Pause)?; + Ok(()) + } + + pub fn seek(&self, secs: f64) -> anyhow::Result<()> { + self.cmd_tx.send(Command::Seek(secs))?; + Ok(()) + } + + pub fn stop(&self) -> anyhow::Result<()> { + self.cmd_tx.send(Command::Stop)?; + Ok(()) + } + + pub fn set_volume(&self, level: f32) -> anyhow::Result<()> { + self.cmd_tx.send(Command::SetVolume(level))?; + Ok(()) + } + + pub fn set_muted(&self, muted: bool) -> anyhow::Result<()> { + self.cmd_tx.send(Command::SetMuted(muted))?; + Ok(()) + } + + pub fn quit(&self) -> anyhow::Result<()> { + self.cmd_tx.send(Command::Quit)?; + Ok(()) + } +} + +fn run_worker( + ip: IpAddr, + port: u16, + cmd_rx: std::sync::mpsc::Receiver, + event_tx: UnboundedSender, +) -> anyhow::Result<()> { + let host = ip.to_string(); + // Connect without host verification because Chromecasts use self-signed certificates. + let device = CastDevice::connect_without_host_verification(&host, port)?; + device.connection.connect("receiver-0")?; + + // Attach to running Default Media Receiver if active, otherwise launch it. + let receiver_status = device.receiver.get_status()?; + let app = if let Some(app) = receiver_status + .applications + .into_iter() + .find(|a| a.app_id == "CC1AD845") + { + app + } else { + device.receiver.launch_app(&CastDeviceApp::DefaultMediaReceiver)? + }; + + device.connection.connect(&app.transport_id)?; + + let session_id = app.session_id; + let transport_id = app.transport_id; + let mut media_session_id: Option = None; + let mut current_volume = receiver_status.volume.level.unwrap_or(1.0) as f64; + + let mut last_status_poll = Instant::now(); + let mut last_heartbeat = Instant::now(); + + loop { + // Take a command with a 300 ms timeout to allow periodic polling and heartbeats. + match cmd_rx.recv_timeout(Duration::from_millis(300)) { + Ok(cmd) => match cmd { + Command::Load(req) => { + let images = req + .image_url + .map(|u| vec![Image::new(u)]) + .unwrap_or_default(); + let metadata = Metadata::MusicTrack(MusicTrackMediaMetadata { + title: req.title, + artist: req.artist, + images, + ..Default::default() + }); + let media = Media { + content_id: req.url, + stream_type: StreamType::Buffered, + content_type: req.content_type, + metadata: Some(metadata), + duration: None, + }; + let options = LoadOptions { + current_time: req.start_secs, + autoplay: req.autoplay, + }; + let status = device + .media + .load_with_opts(&transport_id, &session_id, &media, options)?; + if let Some(entry) = status.entries.first() { + media_session_id = Some(entry.media_session_id); + emit_status(&event_tx, entry, current_volume); + } + } + Command::Play => { + if let Some(msid) = media_session_id { + let entry = device.media.play(&transport_id, msid)?; + emit_status(&event_tx, &entry, current_volume); + } + } + Command::Pause => { + if let Some(msid) = media_session_id { + let entry = device.media.pause(&transport_id, msid)?; + emit_status(&event_tx, &entry, current_volume); + } + } + Command::Seek(secs) => { + if let Some(msid) = media_session_id { + let entry = device + .media + .seek(&transport_id, msid, Some(secs as f32), None)?; + emit_status(&event_tx, &entry, current_volume); + } + } + Command::Stop => { + if let Some(msid) = media_session_id { + let _ = device.media.stop(&transport_id, msid); + } + let _ = device.receiver.stop_app(&session_id); + } + Command::SetVolume(level) => { + let vol = device.receiver.set_volume(level)?; + if let Some(l) = vol.level { + current_volume = l as f64; + } + } + Command::SetMuted(muted) => { + let vol = device.receiver.set_volume(muted)?; + if let Some(l) = vol.level { + current_volume = l as f64; + } + } + Command::Quit => { + break; + } + }, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { + break; + } + } + + // Send heartbeat ping every 5 seconds to keep connection alive. + if last_heartbeat.elapsed() >= Duration::from_secs(5) { + device.heartbeat.ping()?; + last_heartbeat = Instant::now(); + } + + // Poll media status every ~1 second. + if last_status_poll.elapsed() >= Duration::from_secs(1) { + match device.media.get_status(&transport_id, media_session_id) { + Ok(status) => { + if let Some(entry) = status.entries.first() { + media_session_id = Some(entry.media_session_id); + emit_status(&event_tx, entry, current_volume); + } + } + Err(_) => { + // Try receiving incoming message (e.g. heartbeat ping) if get_status fails or times out. + if let Ok(msg) = device.receive() { + if let ChannelMessage::Heartbeat(rust_cast::channels::heartbeat::HeartbeatResponse::Ping) = msg { + let _ = device.heartbeat.pong(); + } + } + } + } + last_status_poll = Instant::now(); + } + } + + Ok(()) +} + +fn emit_status( + event_tx: &UnboundedSender, + entry: &StatusEntry, + volume: f64, +) { + let position_secs = entry.current_time.unwrap_or(0.0) as f64; + let duration_secs = entry.media.as_ref().and_then(|m| m.duration.map(|d| d as f64)); + let _ = event_tx.send(CastEvent::Status { + state: entry.player_state, + position_secs, + duration_secs, + idle_reason: entry.idle_reason, + volume, + }); +} From 75af1f69e058ddf321e117f04fe593e88fe2b435 Mon Sep 17 00:00:00 2001 From: Tomjerri1 <151880307+Tomjerri1@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:46:40 +0200 Subject: [PATCH 02/16] feat(audioproxy): add LAN proxy listener and register_lan for Chromecast --- src-tauri/src/audioproxy.rs | 202 +++++++++++++++++++++++++++++++++++- 1 file changed, 197 insertions(+), 5 deletions(-) diff --git a/src-tauri/src/audioproxy.rs b/src-tauri/src/audioproxy.rs index e55baf04a..13816157d 100644 --- a/src-tauri/src/audioproxy.rs +++ b/src-tauri/src/audioproxy.rs @@ -24,7 +24,7 @@ use std::collections::{HashMap, VecDeque}; use std::convert::Infallible; use std::io; -use std::net::{Ipv4Addr, TcpListener}; +use std::net::{IpAddr, Ipv4Addr, TcpListener, UdpSocket}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; @@ -167,7 +167,7 @@ pub fn register(url: &str, headers: &HashMap) -> Option meta: Mutex::new(None), }); { - let mut r = REGISTRY.get()?.lock().ok()?; + let mut r = REGISTRY.get_or_init(|| Mutex::new(Registry { map: HashMap::new(), order: VecDeque::new() })).lock().ok()?; while r.order.len() >= MAX_REGISTRATIONS { if let Some(old) = r.order.pop_front() { r.map.remove(&old); @@ -179,6 +179,152 @@ pub fn register(url: &str, headers: &HashMap) -> Option Some(format!("http://127.0.0.1:{port}/{token}/a/{id}")) } +struct LanServerState { + port: u16, + token: String, + stop_tx: tokio::sync::oneshot::Sender<()>, +} + +static LAN_STATE: OnceLock>> = OnceLock::new(); + +fn lan_state_lock() -> &'static Mutex> { + LAN_STATE.get_or_init(|| Mutex::new(None)) +} + +/// Start the second listener bound to 0.0.0.0 (ephemeral port) with its own random token, lazily and idempotent. +pub fn start_lan() -> Option { + let mut lock = lan_state_lock().lock().ok()?; + if let Some(state) = &*lock { + return Some(state.port); + } + let listener = match TcpListener::bind((Ipv4Addr::UNSPECIFIED, 0)) { + Ok(l) => l, + Err(e) => { + tracing::warn!(error = %e, "audio proxy lan: bind failed"); + return None; + } + }; + let port = match listener.local_addr() { + Ok(a) => a.port(), + Err(e) => { + tracing::warn!(error = %e, "audio proxy lan: local_addr failed"); + return None; + } + }; + if let Err(e) = listener.set_nonblocking(true) { + tracing::warn!(error = %e, "audio proxy lan: set_nonblocking failed"); + return None; + } + let token = format!("{:016x}{:016x}", rand::random::(), rand::random::()); + let (stop_tx, mut stop_rx) = tokio::sync::oneshot::channel::<()>(); + + let token_clone = token.clone(); + tauri::async_runtime::spawn(async move { + let Ok(listener) = tokio::net::TcpListener::from_std(listener) else { return }; + loop { + let accept_fut = listener.accept(); + tokio::select! { + _ = &mut stop_rx => { + break; + } + accepted = accept_fut => { + let (stream, peer_addr) = match accepted { + Ok(v) => v, + Err(e) => { + tracing::warn!(error = %e, "audio proxy lan: accept failed"); + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + }; + let token = token_clone.clone(); + tauri::async_runtime::spawn(async move { + let svc = service_fn(move |req| { + let token = token.clone(); + async move { handle_lan(req, peer_addr, &token).await } + }); + let _ = http1::Builder::new() + .timer(TokioTimer::new()) + .header_read_timeout(Duration::from_secs(15)) + .serve_connection(TokioIo::new(stream), svc) + .await; + }); + } + } + } + tracing::info!("audio proxy lan stopped"); + }); + + *lock = Some(LanServerState { port, token, stop_tx }); + tracing::info!(port, "audio proxy listening on LAN"); + Some(port) +} + +/// Stop the LAN proxy listener (called when casting ends). +pub fn stop_lan() { + if let Ok(mut lock) = lan_state_lock().lock() { + if let Some(state) = lock.take() { + let _ = state.stop_tx.send(()); + } + } +} + +/// Register one YouTube stream URL for LAN casting (e.g. Chromecast) and return the LAN URL +/// the device should be handed. Computes this PC's LAN IP toward `device_ip` by connecting a +/// UdpSocket to `device_ip:8009` and reading `local_addr()`. +pub fn register_lan( + url: &str, + headers: &HashMap, + device_ip: IpAddr, +) -> Option { + if !crate::orchestrator::is_youtube_stream(url) + || std::env::var_os("LIMUSIC_NO_AUDIO_PROXY").is_some() + { + return None; + } + let port = start_lan()?; + let token = { + let lock = lan_state_lock().lock().ok()?; + lock.as_ref()?.token.clone() + }; + let socket = UdpSocket::bind("0.0.0.0:0").ok()?; + socket.connect((device_ip, 8009)).ok()?; + let lan_ip = socket.local_addr().ok()?.ip(); + + let id = format!("{:016x}", rand::random::()); + let reg = Arc::new(Registration { + url: url.to_owned(), + headers: headers.clone(), + meta: Mutex::new(None), + }); + { + let mut r = REGISTRY.get_or_init(|| Mutex::new(Registry { map: HashMap::new(), order: VecDeque::new() })).lock().ok()?; + while r.order.len() >= MAX_REGISTRATIONS { + if let Some(old) = r.order.pop_front() { + r.map.remove(&old); + } + } + r.map.insert(id.clone(), reg); + r.order.push_back(id.clone()); + } + Some(format!("http://{lan_ip}:{port}/{token}/a/{id}")) +} + +fn is_private_ip(ip: IpAddr) -> bool { + if ip.is_loopback() { + return true; + } + match ip { + IpAddr::V4(v4) => { + let o = v4.octets(); + v4.is_private() || (o[0] == 169 && o[1] == 254) + } + IpAddr::V6(v6) => { + let s = v6.segments(); + (s[0] & 0xffc0 == 0xfe80) || (s[0] & 0xfe00 == 0xfc00) + } + } +} + /// `///` to `(kind, id)`, once the token matches this launch's. fn route<'a>(path: &'a str, token: &str) -> Option<(&'a str, &'a str)> { let (t, rest) = path.strip_prefix('/')?.split_once('/')?; @@ -312,6 +458,31 @@ async fn serve(req: Request) -> Result, Infallible Ok(handle(req).await.unwrap_or_else(empty)) } +async fn handle_lan( + req: Request, + peer_addr: std::net::SocketAddr, + token: &str, +) -> Result, Infallible> { + Ok(handle_lan_inner(req, peer_addr, token).await.unwrap_or_else(empty)) +} + +async fn handle_lan_inner( + req: Request, + peer_addr: std::net::SocketAddr, + token: &str, +) -> Result, StatusCode> { + if !matches!(*req.method(), Method::GET | Method::HEAD) { + return Err(StatusCode::METHOD_NOT_ALLOWED); + } + if !is_private_ip(peer_addr.ip()) { + return Err(StatusCode::FORBIDDEN); + } + let Some(("a", id)) = route(req.uri().path(), token) else { + return Err(StatusCode::NOT_FOUND); + }; + serve_audio_stream(&req, id).await +} + async fn handle(req: Request) -> Result, StatusCode> { if !matches!(*req.method(), Method::GET | Method::HEAD) { return Err(StatusCode::METHOD_NOT_ALLOWED); @@ -320,11 +491,19 @@ async fn handle(req: Request) -> Result, StatusCod if let Some(("k", id)) = route(req.uri().path(), token) { return serve_growing(&req, id).await; } - let id = id_from(req.uri().path(), token).ok_or(StatusCode::NOT_FOUND)?; + let Some(("a", id)) = route(req.uri().path(), token) else { + return Err(StatusCode::NOT_FOUND); + }; + serve_audio_stream(&req, id).await +} + +async fn serve_audio_stream( + req: &Request, + id: &str, +) -> Result, StatusCode> { let reg = { let r = REGISTRY - .get() - .ok_or(StatusCode::INTERNAL_SERVER_ERROR)? + .get_or_init(|| Mutex::new(Registry { map: HashMap::new(), order: VecDeque::new() })) .lock() .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; r.map.get(id).cloned() @@ -626,4 +805,17 @@ mod tests { assert_eq!(total_from_content_range("bytes 0-0/*"), None); assert_eq!(total_from_content_range("nonsense"), None); } + + #[test] + fn test_is_private_ip() { + assert!(is_private_ip("127.0.0.1".parse().unwrap())); + assert!(is_private_ip("::1".parse().unwrap())); + assert!(is_private_ip("10.0.0.1".parse().unwrap())); + assert!(is_private_ip("172.16.0.1".parse().unwrap())); + assert!(is_private_ip("192.168.1.1".parse().unwrap())); + assert!(is_private_ip("169.254.1.1".parse().unwrap())); + assert!(is_private_ip("fe80::1".parse().unwrap())); + assert!(!is_private_ip("8.8.8.8".parse().unwrap())); + assert!(!is_private_ip("1.1.1.1".parse().unwrap())); + } } From bda18416ca8946972206dc9d92f8779c8d69050d Mon Sep 17 00:00:00 2001 From: Tomjerri1 <151880307+Tomjerri1@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:53:14 +0200 Subject: [PATCH 03/16] feat(player): add set_muted and is_muted for Cast playback --- crates/player/src/lib.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/player/src/lib.rs b/crates/player/src/lib.rs index a3cddf3d3..fab7d0626 100644 --- a/crates/player/src/lib.rs +++ b/crates/player/src/lib.rs @@ -189,6 +189,7 @@ struct Decks { /// The volume slider's percent, so a fade can scale the user's own level instead of /// overwriting it. volume: AtomicI64, + muted: AtomicBool, /// A track is loaded and paused on the idle deck, waiting to be faded in. Published by the /// idle deck's own `FileLoaded`, never by `preload`: `loadfile` returns long before mpv has /// the stream open, and a fade into a deck that is still opening plays silence over the @@ -427,6 +428,7 @@ impl Player { active: AtomicUsize::new(0), crossfade_ms: AtomicU64::new(0), volume: AtomicI64::new(100), + muted: AtomicBool::new(false), preloaded: AtomicBool::new(false), preload_gen: AtomicU64::new(0), preload_armed: AtomicU64::new(0), @@ -758,6 +760,21 @@ impl Player { self.decks.volume.load(Ordering::Relaxed) } + /// Used while audio plays on a Cast device and mpv is only a silent clock. + pub fn set_muted(&self, muted: bool) -> Result<(), Error> { + self.mpv().set_property("mute", muted)?; + if let Some(other) = self.decks.mpv(1 - self.decks.active.load(Ordering::SeqCst)) { + let _ = other.set_property("mute", muted); + } + self.decks.muted.store(muted, Ordering::Relaxed); + Ok(()) + } + + /// Current mute state. + pub fn is_muted(&self) -> bool { + self.decks.muted.load(Ordering::Relaxed) + } + /// Route the audio bytes through a proxy (the app's `proxy` setting). Call before the first /// [`Self::load`]. /// @@ -1381,6 +1398,7 @@ fn preload(decks: &Decks, mpv: &Arc, url: &str) -> Result<(), Error> { } mpv.set_property("pause", true)?; mpv.set_property("volume", 0.0)?; + mpv.set_property("mute", decks.muted.load(Ordering::Relaxed))?; // Off the audio device until its fade starts (`start_crossfade` puts it back). A paused deck // with a file loaded still holds an output stream, so Linux mixers listed this one for the // whole track as a second app next to the one playing, with a volume slider of its own that From e35b1d01f59bbbb9f45ecb5ea676d9c9113e06f7 Mon Sep 17 00:00:00 2001 From: Tomjerri1 <151880307+Tomjerri1@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:39:41 +0200 Subject: [PATCH 04/16] feat(cast): add session control, LAN proxy, mute and initial backend wiring --- Cargo.lock | 1 + src-tauri/Cargo.toml | 1 + src-tauri/src/castout.rs | 220 ++++++++++++++++++++++++++++++++++++++ src-tauri/src/commands.rs | 31 ++++-- src-tauri/src/hotkeys.rs | 10 +- src-tauri/src/lib.rs | 13 +++ src-tauri/src/media.rs | 6 +- src-tauri/src/state.rs | 89 ++++++++++++++- 8 files changed, 351 insertions(+), 20 deletions(-) create mode 100644 src-tauri/src/castout.rs diff --git a/Cargo.lock b/Cargo.lock index abd3b5389..a32903dbc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3612,6 +3612,7 @@ dependencies = [ "any_ascii", "anyhow", "base64 0.22.1", + "cast", "csv", "discord-rich-presence", "futures-util", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4efa66789..c62afcf24 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -48,6 +48,7 @@ http-body-util = "0.1" innertube = { path = "../crates/innertube" } player = { path = "../crates/player" } karaoke = { path = "../crates/karaoke" } +cast = { path = "../crates/cast" } souvlaki = { version = "0.8.3", default-features = false, features = ["use_zbus"] } # Listen Together: shared wire types + WebSocket client (wss via rustls). context/19. listen-protocol = { workspace = true } diff --git a/src-tauri/src/castout.rs b/src-tauri/src/castout.rs new file mode 100644 index 000000000..c4853b410 --- /dev/null +++ b/src-tauri/src/castout.rs @@ -0,0 +1,220 @@ +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; +use tauri::{AppHandle, Emitter}; +use cast::{watch, CastDevice, CastEvent, CastSession, DiscoveryEvent, LoadRequest}; +use crate::orchestrator::PlaybackData; + +/// Manages Chromecast discovery, connection state, and session synchronization. +pub struct CastManager { + app: AppHandle, + devices: Arc>>, + active: Mutex>, + watcher_started: AtomicBool, + last_pos_info: Mutex>, +} + +struct ActiveCast { + device: CastDevice, + session: CastSession, +} + +impl CastManager { + pub fn new(app: AppHandle) -> Self { + Self { + app, + devices: Arc::new(Mutex::new(HashMap::new())), + active: Mutex::new(None), + watcher_started: AtomicBool::new(false), + last_pos_info: Mutex::new(None), + } + } + + /// Start background mDNS discovery watcher lazily. + pub fn ensure_discovery(&self) { + if self.watcher_started.load(Ordering::SeqCst) { + return; + } + if self.watcher_started.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_ok() { + let devices = self.devices.clone(); + let app = self.app.clone(); + std::thread::spawn(move || { + let (rx, _handle) = watch(); + while let Ok(event) = rx.recv() { + let mut map = match devices.lock() { + Ok(m) => m, + Err(_) => break, + }; + match event { + DiscoveryEvent::Found(device) => { + map.insert(device.id.clone(), device); + } + DiscoveryEvent::Lost(id) => { + map.remove(&id); + } + } + let list: Vec = map.values().cloned().collect(); + let _ = app.emit("cast-devices", &list); + } + }); + } + } + + pub fn list_devices(&self) -> Vec { + self.ensure_discovery(); + if let Ok(map) = self.devices.lock() { + if map.is_empty() { + if let Ok(browsed) = cast::browse(std::time::Duration::from_secs(1)) { + drop(map); + if let Ok(mut map) = self.devices.lock() { + for d in browsed { + map.insert(d.id.clone(), d); + } + return map.values().cloned().collect(); + } + } + } + map.values().cloned().collect() + } else { + Vec::new() + } + } + + pub fn status(&self) -> Option { + self.active.lock().ok()?.as_ref().map(|a| a.device.clone()) + } + + pub fn is_connected(&self) -> bool { + self.active.lock().ok().and_then(|a| a.as_ref().map(|_| true)).unwrap_or(false) + } + + pub async fn connect(&self, device_id: &str, state: &Arc) -> Result { + let device = { + let map = self.devices.lock().map_err(|e| e.to_string())?; + map.get(device_id).cloned().ok_or_else(|| format!("device not found: {device_id}"))? + }; + + let _ = self.disconnect(state).await; + + let session = CastSession::connect(device.ip, device.port).map_err(|e| e.to_string())?; + + crate::audioproxy::start_lan(); + let _ = state.player.set_muted(true); + + let mut events = session.events(); + let state_clone = state.clone(); + + tauri::async_runtime::spawn(async move { + while let Some(event) = events.recv().await { + match event { + CastEvent::Status { state: _, position_secs, duration_secs: _, idle_reason, volume: _ } => { + if let Ok(mut guard) = state_clone.cast.last_pos_info.lock() { + *guard = Some((Instant::now(), position_secs)); + } + if matches!(idle_reason, Some(cast::session::IdleReason::Error)) { + tracing::error!("Chromecast error idle reason encountered"); + let _ = state_clone.cast_disconnect().await; + state_clone.emit_notice("Chromecast playback error"); + break; + } + } + CastEvent::Disconnected(reason) => { + tracing::warn!(reason, "Chromecast session disconnected"); + let _ = state_clone.cast_disconnect().await; + state_clone.emit_notice(&format!("Chromecast disconnected: {reason}")); + break; + } + } + } + }); + + { + let mut active = self.active.lock().map_err(|e| e.to_string())?; + *active = Some(ActiveCast { + device: device.clone(), + session, + }); + } + + let _ = self.app.emit("cast-state", Some(&device)); + + if let Some(item) = state.current_item().await { + let pos = state.current_position(); + let _ = state.cast_follow_current(pos).await; + } + + Ok(device) + } + + pub async fn disconnect(&self, state: &Arc) -> Result<(), String> { + let old_active = { + let mut active = self.active.lock().map_err(|e| e.to_string())?; + active.take() + }; + + if let Some(active) = old_active { + let _ = active.session.quit(); + } + + crate::audioproxy::stop_lan(); + let _ = state.player.set_muted(false); + let _ = self.app.emit("cast-state", None::); + if let Ok(mut guard) = self.last_pos_info.lock() { + *guard = None; + } + Ok(()) + } + + pub fn set_volume(&self, level: f32) -> Result<(), String> { + if let Some(active) = self.active.lock().ok().and_then(|a| a.as_ref().map(|a| a.session.clone())) { + active.set_volume(level).map_err(|e| e.to_string())?; + } + Ok(()) + } + + pub fn play(&self) -> Result<(), String> { + if let Some(active) = self.active.lock().ok().and_then(|a| a.as_ref().map(|a| a.session.clone())) { + active.play().map_err(|e| e.to_string())?; + } + Ok(()) + } + + pub fn pause(&self) -> Result<(), String> { + if let Some(active) = self.active.lock().ok().and_then(|a| a.as_ref().map(|a| a.session.clone())) { + active.pause().map_err(|e| e.to_string())?; + } + Ok(()) + } + + pub fn seek(&self, secs: f64) -> Result<(), String> { + if let Some(active) = self.active.lock().ok().and_then(|a| a.as_ref().map(|a| a.session.clone())) { + active.seek(secs).map_err(|e| e.to_string())?; + } + Ok(()) + } + + pub fn session_load(&self, req: LoadRequest) -> Result<(), String> { + if let Some(active) = self.active.lock().ok().and_then(|a| a.as_ref().map(|a| a.session.clone())) { + active.load(req).map_err(|e| e.to_string())?; + } + Ok(()) + } + + pub fn check_drift(&self, mpv_pos: f64, is_playing: bool) { + if !is_playing { + return; + } + if let Ok(mut guard) = self.last_pos_info.lock() { + if let Some((instant, cast_pos)) = *guard { + let elapsed = instant.elapsed().as_secs_f64(); + let estimated_cast_pos = cast_pos + elapsed; + if (mpv_pos - estimated_cast_pos).abs() > 2.5 { + tracing::debug!(mpv_pos, estimated_cast_pos, "Chromecast drift correction triggered"); + let _ = self.seek(mpv_pos); + *guard = Some((Instant::now(), mpv_pos)); + } + } + } + } +} diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 29e90e347..74e7a9132 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -210,17 +210,32 @@ pub async fn seek(state: St<'_>, position: f64) -> Result<(), String> { #[tauri::command] pub async fn set_volume(state: St<'_>, volume: i64) -> Result<(), String> { - state.player.set_volume(volume).map_err(|e| e.to_string())?; - if volume > 0 { - crate::hotkeys::LAST_NONZERO_VOLUME.store(volume, std::sync::atomic::Ordering::Relaxed); - } - // There is one volume and there can be two windows (the mini player). Without this the one - // that didn't move the slider keeps showing the old level and lies about what you're hearing. - let _ = state.app.emit("volume", volume); - state.media_set_volume(volume); + state.set_output_volume(volume); Ok(()) } +#[tauri::command] +pub async fn cast_list_devices(state: St<'_>) -> Result, String> { + Ok(state.cast_list_devices()) +} + +#[tauri::command] +pub async fn cast_connect(state: St<'_>, id: String) -> Result { + let state = state.inner().clone(); + state.cast_connect(&id).await +} + +#[tauri::command] +pub async fn cast_disconnect(state: St<'_>) -> Result<(), String> { + let state = state.inner().clone(); + state.cast_disconnect().await.map_err(|e| e.to_string()) +} + +#[tauri::command] +pub async fn cast_status(state: St<'_>) -> Result, String> { + Ok(state.cast_status()) +} + /// A fresh position and when it was read (`AppState::playback_clock`). Async, so the read of mpv /// happens off the main thread. #[tauri::command] diff --git a/src-tauri/src/hotkeys.rs b/src-tauri/src/hotkeys.rs index 93cf9e8bb..1898dd274 100644 --- a/src-tauri/src/hotkeys.rs +++ b/src-tauri/src/hotkeys.rs @@ -226,14 +226,8 @@ pub(crate) fn change_volume(state: &AppState, app: &AppHandle, f: impl FnOnce(i6 static LOCK: Mutex<()> = Mutex::new(()); let _guard = LOCK.lock().unwrap(); let volume = f(state.player.volume()).clamp(0, 100); - if state.player.set_volume(volume).is_ok() { - if volume > 0 { - LAST_NONZERO_VOLUME.store(volume, Ordering::Relaxed); - } - state.db.set_setting("volume", &volume.to_string()); - let _ = app.emit("volume", volume); - state.media_set_volume(volume); - } + state.set_output_volume(volume); + state.db.set_setting("volume", &volume.to_string()); } pub fn load_config(db: &Db) -> HotkeysConfig { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 68e209b2d..f57f0e671 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,5 +1,6 @@ //! Limusic Tauri app. Wires transport + player + db + orchestrator behind the command boundary. +mod castout; mod appicon; mod audioproxy; mod autopause; @@ -1361,6 +1362,10 @@ pub fn run() { commands::seek, commands::playback_clock, commands::set_volume, + commands::cast_list_devices, + commands::cast_connect, + commands::cast_disconnect, + commands::cast_status, commands::set_playback_params, commands::set_karaoke, commands::get_queue, @@ -1602,6 +1607,7 @@ pub fn run() { if let tauri::RunEvent::Exit = &event { if let Some(state) = handle.try_state::>() { state.flush_position(); + let _ = tauri::async_runtime::block_on(async { state.cast_disconnect().await }); } mini::save_position(handle); } @@ -1702,6 +1708,13 @@ fn spawn_event_pump( } } state.media_set_playing(playing); + if state.cast.is_connected() { + if playing { + let _ = state.cast.play(); + } else { + let _ = state.cast.pause(); + } + } // Playing here ends showing another linked device; pausing may start it. state.link_remote_refresh().await; // Keep the tray's toggle label honest — this arm is the same chokepoint diff --git a/src-tauri/src/media.rs b/src-tauri/src/media.rs index 9e0f22fe5..0552d9f24 100644 --- a/src-tauri/src/media.rs +++ b/src-tauri/src/media.rs @@ -223,7 +223,7 @@ pub(crate) fn handle_event(app: &AppHandle, event: MediaControlEvent) { MediaControlEvent::Next => state.next_in_queue().await, MediaControlEvent::Previous => state.prev_in_queue().await, MediaControlEvent::SetPosition(MediaPosition(pos)) => { - let _ = state.player.seek(pos.as_secs_f64() * state.player.speed()); + let _ = state.user_seek(pos.as_secs_f64() * state.player.speed()).await; } MediaControlEvent::SeekBy(dir, by) => { let delta = if matches!(dir, SeekDirection::Forward) { @@ -232,12 +232,12 @@ pub(crate) fn handle_event(app: &AppHandle, event: MediaControlEvent) { -by.as_secs_f64() }; let delta = delta * state.player.speed(); - let _ = state.player.seek((state.current_position() + delta).max(0.0)); + let _ = state.user_seek((state.current_position() + delta).max(0.0)).await; } MediaControlEvent::Seek(dir) => { let delta = if matches!(dir, SeekDirection::Forward) { 10.0 } else { -10.0 }; let delta = delta * state.player.speed(); - let _ = state.player.seek((state.current_position() + delta).max(0.0)); + let _ = state.user_seek((state.current_position() + delta).max(0.0)).await; } // An MPRIS widget or KDE Connect (#220). Same path as a volume hotkey, which also // pushes the new level back: without that the widget snaps to the old one. diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index b33f10fb2..7b574426d 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -69,6 +69,7 @@ pub struct AppState { pub db: Arc, pub app: AppHandle, pub orchestrator: Arc, + pub cast: Arc, /// Listen Together session (context/19). Drives host broadcasts + guest gating. pub lt: Arc, // Serialize effect commands with the room's tempo reset, including requests already pending. @@ -549,8 +550,9 @@ impl AppState { clients, player, db, - app, + app: app.clone(), orchestrator, + cast: Arc::new(crate::castout::CastManager::new(app)), lt, link, cache_dir, @@ -586,6 +588,84 @@ impl AppState { } } + pub fn cast_list_devices(&self) -> Vec { + self.cast.list_devices() + } + + pub async fn cast_connect(self: &Arc, id: &str) -> Result { + self.cast.connect(id, self).await + } + + pub async fn cast_disconnect(self: &Arc) -> Result<(), String> { + self.cast.disconnect(self).await + } + + pub fn cast_status(&self) -> Option { + self.cast.status() + } + + pub fn set_output_volume(&self, volume: i64) { + if self.cast.is_connected() { + let _ = self.cast.set_volume(volume as f32 / 100.0); + } else { + let _ = self.player.set_volume(volume); + } + if volume > 0 { + crate::hotkeys::LAST_NONZERO_VOLUME.store(volume, std::sync::atomic::Ordering::Relaxed); + } + let _ = self.app.emit("volume", volume); + self.media_set_volume(volume); + } + + pub async fn cast_follow_load(&self, data: &PlaybackData, start_secs: f64, is_karaoke: bool) { + if !self.cast.is_connected() { + return; + } + let is_local = crate::local::song_path(&data.video_id).is_some(); + if is_local || data.live || is_karaoke { + let _ = self.player.set_muted(false); + return; + } + let device = match self.cast.status() { + Some(d) => d, + None => { + let _ = self.player.set_muted(false); + return; + } + }; + if let Some(lan_url) = crate::audioproxy::register_lan(&data.stream_url, &data.headers, device.ip) { + let _ = self.player.set_muted(true); + let content_type = if data.stream_url.contains("mimeType=audio/webm") || data.stream_url.contains("itag=251") || data.stream_url.contains("itag=250") || data.stream_url.contains("itag=249") { + "audio/webm".to_string() + } else { + "audio/mp4".to_string() + }; + let req = cast::LoadRequest { + url: lan_url, + content_type, + title: data.title.clone(), + artist: data.artists.clone(), + image_url: data.thumbnail.clone(), + start_secs, + autoplay: true, + }; + let _ = self.cast.session_load(req); + } else { + let _ = self.player.set_muted(false); + } + } + + pub async fn cast_follow_current(&self, start_secs: f64) { + if let Some(item) = self.current_item().await { + if let Ok(data) = self.resolve(&item.video_id, item.is_upload, parse_duration_ms(item.duration.as_deref()) / 1000).await { + let stream_url = mpv_stream_url(&data); + let play_u = self.play_url(PinSlot::Current, &item.video_id, &stream_url); + let is_karaoke = play_u != stream_url; + self.cast_follow_load(&data, start_secs, is_karaoke).await; + } + } + } + /// Remember where the loopback video proxy should fetch `id` from. pub fn put_video_url(&self, id: &str, url: String) { let Ok(mut map) = self.video_urls.lock() else { return }; @@ -2406,6 +2486,7 @@ impl AppState { self.emit_error(&item.video_id, &e.to_string()); return false; } + self.cast_follow_load(&data, seek.unwrap_or(0.0), is_karaoke).await; // Where mpv starts, from now on: its first tick comes after the unpause, and that pause // flag's Play (`lt_on_play_state`) reads this. Left at the last track's position, a Continue // here told the device link the music was back where this desktop last stopped, and the @@ -2877,6 +2958,7 @@ impl AppState { self.emit_error(&item.video_id, &e.to_string()); return; } + self.cast_follow_load(&data, pos, is_karaoke).await; // The picture is keyed by the file mpv plays, and that just changed. self.attach_video(&item.video_id, item.is_video && !data.live, &play_u); // A cached instrumental or the original: not a stream any more. @@ -3973,6 +4055,7 @@ impl AppState { /// watch-history ping, latched to happen exactly once per play. The ping is additionally /// gated on the `enable_history` setting + being logged in. Best-effort (errors logged). pub async fn on_position(&self, pos: f64) { + self.cast.check_drift(pos, self.is_playing.load(Ordering::Relaxed)); self.record_position(pos); self.hear(pos); // On a karaoke stream, the playhead must stay where it is written. Every seek lands here @@ -4673,6 +4756,7 @@ impl AppState { self.emit_error(&track.id, &e.to_string()); return; } + self.cast_follow_load(&data, pos, false).await; let _ = if playing { self.player.play() } else { self.player.pause() }; { let mut q = self.queue.lock().await; @@ -4906,6 +4990,9 @@ impl AppState { return Ok(()); } self.player.seek(position).map_err(|e| e.to_string())?; + if self.cast.is_connected() { + let _ = self.cast.seek(position); + } let p = Playback::at(PlaybackKind::Seek, (position * 1000.0) as i64); self.link.publish(p.clone()); if self.lt.is_host().await { From e54e367ad9038716a1f8b9a984d08a4b414f2424 Mon Sep 17 00:00:00 2001 From: Tomjerri1 <151880307+Tomjerri1@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:05:50 +0200 Subject: [PATCH 05/16] feat(cast): wire CastManager, Tauri commands and playback sync --- crates/cast/src/lib.rs | 2 +- crates/cast/src/session.rs | 4 +- src-tauri/src/castout.rs | 82 +++++++++++++++++++++++++++++--------- src-tauri/src/state.rs | 32 ++++++++------- 4 files changed, 85 insertions(+), 35 deletions(-) diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index a24b5315e..3ea2d768e 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -2,5 +2,5 @@ pub mod discovery; pub mod session; pub use discovery::{browse, watch, CastDevice, DiscoveryEvent, WatchHandle}; -pub use session::{CastEvent, CastSession, LoadRequest}; +pub use session::{CastEvent, CastSession, LoadRequest, IdleReason, PlayerState}; diff --git a/crates/cast/src/session.rs b/crates/cast/src/session.rs index 01c3907d5..1d7605b76 100644 --- a/crates/cast/src/session.rs +++ b/crates/cast/src/session.rs @@ -3,9 +3,11 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; +pub use rust_cast::channels::media::{IdleReason, PlayerState}; + use rust_cast::{ channels::media::{ - IdleReason, Image, LoadOptions, Media, Metadata, MusicTrackMediaMetadata, PlayerState, + Image, LoadOptions, Media, Metadata, MusicTrackMediaMetadata, StatusEntry, StreamType, }, channels::receiver::CastDeviceApp, diff --git a/src-tauri/src/castout.rs b/src-tauri/src/castout.rs index c4853b410..0148f13ee 100644 --- a/src-tauri/src/castout.rs +++ b/src-tauri/src/castout.rs @@ -3,8 +3,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Instant; use tauri::{AppHandle, Emitter}; -use cast::{watch, CastDevice, CastEvent, CastSession, DiscoveryEvent, LoadRequest}; -use crate::orchestrator::PlaybackData; +use cast::{watch, CastDevice, CastEvent, CastSession, DiscoveryEvent, LoadRequest, PlayerState}; /// Manages Chromecast discovery, connection state, and session synchronization. pub struct CastManager { @@ -12,7 +11,9 @@ pub struct CastManager { devices: Arc>>, active: Mutex>, watcher_started: AtomicBool, - last_pos_info: Mutex>, + last_pos_info: Mutex>, + loaded_at: Mutex>, + last_correction: Mutex>, } struct ActiveCast { @@ -28,6 +29,8 @@ impl CastManager { active: Mutex::new(None), watcher_started: AtomicBool::new(false), last_pos_info: Mutex::new(None), + loaded_at: Mutex::new(None), + last_correction: Mutex::new(None), } } @@ -63,18 +66,24 @@ impl CastManager { pub fn list_devices(&self) -> Vec { self.ensure_discovery(); - if let Ok(map) = self.devices.lock() { - if map.is_empty() { - if let Ok(browsed) = cast::browse(std::time::Duration::from_secs(1)) { - drop(map); - if let Ok(mut map) = self.devices.lock() { - for d in browsed { - map.insert(d.id.clone(), d); - } - return map.values().cloned().collect(); + let is_empty = if let Ok(map) = self.devices.lock() { + map.is_empty() + } else { + false + }; + + if is_empty { + if let Ok(browsed) = cast::browse(std::time::Duration::from_secs(1)) { + if let Ok(mut map) = self.devices.lock() { + for d in browsed { + map.insert(d.id.clone(), d); } + return map.values().cloned().collect(); } } + } + + if let Ok(map) = self.devices.lock() { map.values().cloned().collect() } else { Vec::new() @@ -101,6 +110,7 @@ impl CastManager { crate::audioproxy::start_lan(); let _ = state.player.set_muted(true); + let _ = session.set_volume(state.player.volume() as f32 / 100.0); let mut events = session.events(); let state_clone = state.clone(); @@ -108,9 +118,9 @@ impl CastManager { tauri::async_runtime::spawn(async move { while let Some(event) = events.recv().await { match event { - CastEvent::Status { state: _, position_secs, duration_secs: _, idle_reason, volume: _ } => { + CastEvent::Status { state, position_secs, duration_secs: _, idle_reason, volume: _ } => { if let Ok(mut guard) = state_clone.cast.last_pos_info.lock() { - *guard = Some((Instant::now(), position_secs)); + *guard = Some((Instant::now(), position_secs, state)); } if matches!(idle_reason, Some(cast::session::IdleReason::Error)) { tracing::error!("Chromecast error idle reason encountered"); @@ -139,7 +149,7 @@ impl CastManager { let _ = self.app.emit("cast-state", Some(&device)); - if let Some(item) = state.current_item().await { + if let Some(_item) = state.current_item().await { let pos = state.current_position(); let _ = state.cast_follow_current(pos).await; } @@ -154,6 +164,7 @@ impl CastManager { }; if let Some(active) = old_active { + let _ = active.session.stop(); let _ = active.session.quit(); } @@ -163,6 +174,12 @@ impl CastManager { if let Ok(mut guard) = self.last_pos_info.lock() { *guard = None; } + if let Ok(mut guard) = self.loaded_at.lock() { + *guard = None; + } + if let Ok(mut guard) = self.last_correction.lock() { + *guard = None; + } Ok(()) } @@ -195,6 +212,12 @@ impl CastManager { } pub fn session_load(&self, req: LoadRequest) -> Result<(), String> { + if let Ok(mut guard) = self.last_pos_info.lock() { + *guard = None; + } + if let Ok(mut guard) = self.loaded_at.lock() { + *guard = Some(Instant::now()); + } if let Some(active) = self.active.lock().ok().and_then(|a| a.as_ref().map(|a| a.session.clone())) { active.load(req).map_err(|e| e.to_string())?; } @@ -205,14 +228,37 @@ impl CastManager { if !is_playing { return; } + if let Ok(guard) = self.loaded_at.lock() { + if let Some(t) = *guard { + if t.elapsed().as_secs_f64() < 6.0 { + return; + } + } + } + if let Ok(guard) = self.last_correction.lock() { + if let Some(t) = *guard { + if t.elapsed().as_secs_f64() < 5.0 { + return; + } + } + } if let Ok(mut guard) = self.last_pos_info.lock() { - if let Some((instant, cast_pos)) = *guard { + if let Some((instant, cast_pos, player_state)) = *guard { + if !matches!(player_state, PlayerState::Playing) { + return; + } + if instant.elapsed().as_secs_f64() > 3.0 { + return; + } let elapsed = instant.elapsed().as_secs_f64(); let estimated_cast_pos = cast_pos + elapsed; - if (mpv_pos - estimated_cast_pos).abs() > 2.5 { + if (mpv_pos - estimated_cast_pos).abs() > 3.0 { tracing::debug!(mpv_pos, estimated_cast_pos, "Chromecast drift correction triggered"); let _ = self.seek(mpv_pos); - *guard = Some((Instant::now(), mpv_pos)); + *guard = Some((Instant::now(), mpv_pos, player_state)); + if let Ok(mut corr) = self.last_correction.lock() { + *corr = Some(Instant::now()); + } } } } diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 7b574426d..e70b1d63a 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -605,10 +605,9 @@ impl AppState { } pub fn set_output_volume(&self, volume: i64) { + let _ = self.player.set_volume(volume); if self.cast.is_connected() { let _ = self.cast.set_volume(volume as f32 / 100.0); - } else { - let _ = self.player.set_volume(volume); } if volume > 0 { crate::hotkeys::LAST_NONZERO_VOLUME.store(volume, std::sync::atomic::Ordering::Relaxed); @@ -617,7 +616,7 @@ impl AppState { self.media_set_volume(volume); } - pub async fn cast_follow_load(&self, data: &PlaybackData, start_secs: f64, is_karaoke: bool) { + pub async fn cast_follow_load(&self, data: &PlaybackData, start_secs: f64, is_karaoke: bool, autoplay: bool) { if !self.cast.is_connected() { return; } @@ -635,11 +634,14 @@ impl AppState { }; if let Some(lan_url) = crate::audioproxy::register_lan(&data.stream_url, &data.headers, device.ip) { let _ = self.player.set_muted(true); - let content_type = if data.stream_url.contains("mimeType=audio/webm") || data.stream_url.contains("itag=251") || data.stream_url.contains("itag=250") || data.stream_url.contains("itag=249") { - "audio/webm".to_string() - } else { - "audio/mp4".to_string() - }; + let content_type = reqwest::Url::parse(&data.stream_url) + .ok() + .and_then(|u| { + u.query_pairs() + .find(|(k, _)| k == "mime") + .map(|(_, v)| urlencoding::decode(&v).map(|s| s.into_owned()).unwrap_or_else(|_| v.into_owned())) + }) + .unwrap_or_else(|| "audio/mp4".to_string()); let req = cast::LoadRequest { url: lan_url, content_type, @@ -647,7 +649,7 @@ impl AppState { artist: data.artists.clone(), image_url: data.thumbnail.clone(), start_secs, - autoplay: true, + autoplay, }; let _ = self.cast.session_load(req); } else { @@ -661,7 +663,7 @@ impl AppState { let stream_url = mpv_stream_url(&data); let play_u = self.play_url(PinSlot::Current, &item.video_id, &stream_url); let is_karaoke = play_u != stream_url; - self.cast_follow_load(&data, start_secs, is_karaoke).await; + self.cast_follow_load(&data, start_secs, is_karaoke, self.is_playing.load(Ordering::Relaxed)).await; } } } @@ -2486,7 +2488,7 @@ impl AppState { self.emit_error(&item.video_id, &e.to_string()); return false; } - self.cast_follow_load(&data, seek.unwrap_or(0.0), is_karaoke).await; + self.cast_follow_load(&data, seek.unwrap_or(0.0), is_karaoke, self.is_playing.load(Ordering::Relaxed)).await; // Where mpv starts, from now on: its first tick comes after the unpause, and that pause // flag's Play (`lt_on_play_state`) reads this. Left at the last track's position, a Continue // here told the device link the music was back where this desktop last stopped, and the @@ -2798,7 +2800,7 @@ impl AppState { tracing::debug!(index = next_idx, "gapless lookahead primed"); } - async fn current_item(&self) -> Option { + pub(crate) async fn current_item(&self) -> Option { let q = self.queue.lock().await; q.items.get(q.current).cloned() } @@ -2958,7 +2960,7 @@ impl AppState { self.emit_error(&item.video_id, &e.to_string()); return; } - self.cast_follow_load(&data, pos, is_karaoke).await; + self.cast_follow_load(&data, pos, is_karaoke, was_playing).await; // The picture is keyed by the file mpv plays, and that just changed. self.attach_video(&item.video_id, item.is_video && !data.live, &play_u); // A cached instrumental or the original: not a stream any more. @@ -4016,7 +4018,7 @@ impl AppState { } /// A transient toast. Same channel as [`Self::emit_skip`], for messages that phrase themselves. - fn emit_notice(&self, message: &str) { + pub(crate) fn emit_notice(&self, message: &str) { tracing::info!(message, "playback notice"); let _ = self.app.emit("playback-notice", serde_json::json!({ "message": message })); } @@ -4756,7 +4758,7 @@ impl AppState { self.emit_error(&track.id, &e.to_string()); return; } - self.cast_follow_load(&data, pos, false).await; + self.cast_follow_load(&data, pos, false, playing).await; let _ = if playing { self.player.play() } else { self.player.pause() }; { let mut q = self.queue.lock().await; From 7d618b4de0f8f7d693438ab1de89c38852489af0 Mon Sep 17 00:00:00 2001 From: Tomjerri1 <151880307+Tomjerri1@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:19:55 +0200 Subject: [PATCH 06/16] feat(ui): add Chromecast devices to DevicePicker --- ui/src/lib/api.ts | 17 +++++++ ui/src/lib/cast.svelte.ts | 17 +++++++ ui/src/lib/components/DevicePicker.svelte | 62 +++++++++++++++++++++-- ui/src/lib/locales/en.json | 4 ++ ui/src/lib/player.svelte.ts | 7 ++- 5 files changed, 102 insertions(+), 5 deletions(-) create mode 100644 ui/src/lib/cast.svelte.ts diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 15608ed94..7781a3b6c 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -1721,3 +1721,20 @@ export const onMatugenThemeChanged = (cb: (css: string | null) => void): Promise listen('matugen-theme-changed', (event) => cb(event.payload)); export const startMatugenWatcher = () => invoke('start_matugen_watcher'); export const stopMatugenWatcher = () => invoke('stop_matugen_watcher'); + +export interface CastDevice { + id: string; + name: string; + model?: string | null; + ip: string; + port: number; +} + +export const castListDevices = () => invoke('cast_list_devices'); +export const castConnect = (id: string) => invoke('cast_connect', { id }); +export const castDisconnect = () => invoke('cast_disconnect'); +export const castStatus = () => invoke('cast_status'); +export const onCastDevices = (cb: (devices: CastDevice[]) => void): Promise => + listen('cast-devices', (e) => cb(e.payload)); +export const onCastState = (cb: (device: CastDevice | null) => void): Promise => + listen('cast-state', (e) => cb(e.payload)); diff --git a/ui/src/lib/cast.svelte.ts b/ui/src/lib/cast.svelte.ts new file mode 100644 index 000000000..7084789e9 --- /dev/null +++ b/ui/src/lib/cast.svelte.ts @@ -0,0 +1,17 @@ +import type { CastDevice } from './api'; + +export const cast = $state<{ + devices: CastDevice[]; + active: CastDevice | null; +}>({ + devices: [], + active: null +}); + +export function applyCastDevices(devices: CastDevice[]) { + cast.devices = devices; +} + +export function applyCastState(active: CastDevice | null) { + cast.active = active; +} diff --git a/ui/src/lib/components/DevicePicker.svelte b/ui/src/lib/components/DevicePicker.svelte index bb8f27102..e97d58712 100644 --- a/ui/src/lib/components/DevicePicker.svelte +++ b/ui/src/lib/components/DevicePicker.svelte @@ -3,6 +3,7 @@ // moves what plays there, where it is (src-tauri/src/devicelink.rs). import { HugeiconsIcon } from '@hugeicons/svelte'; import { + CastIcon, ComputerIcon, ComputerPhoneSyncIcon, PlusSignIcon, @@ -14,19 +15,26 @@ import { Button } from '$lib/components/ui/button'; import * as api from '$lib/api'; import { link } from '$lib/link.svelte'; + import { cast } from '$lib/cast.svelte'; import { playback, toast, ui } from '$lib/player.svelte'; import { t } from '$lib/i18n.svelte'; let open = $state(false); - const here = $derived(!link.remote); const remotePlayer = $derived(link.remote ? link.player : null); + const castActive = $derived(cast.active); + const activeDevice = $derived(remotePlayer ?? castActive); + const here = $derived(!link.remote && !castActive); const label = $derived( remotePlayer ? link.isPlaying ? t('player.link_playing_on', { name: remotePlayer.name }) : t('player.link_paused_on', { name: remotePlayer.name }) - : t('player.devices') + : castActive + ? playback.paused + ? t('player.link_paused_on', { name: castActive.name }) + : t('player.link_playing_on', { name: castActive.name }) + : t('player.devices') ); async function playOn(deviceId: string) { @@ -38,6 +46,32 @@ } } + async function selectCast(d: api.CastDevice) { + open = false; + try { + if (castActive?.id === d.id) { + await api.castDisconnect(); + } else { + await api.castConnect(d.id); + } + } catch (e) { + toast.error(String(e)); + } + } + + async function selectHere() { + open = false; + try { + if (castActive) { + await api.castDisconnect(); + } else if (link.remote) { + await api.linkPlayOn(''); + } + } catch (e) { + toast.error(String(e)); + } + } + function linkPhone() { open = false; ui.settingsFocus = 'devices'; @@ -49,6 +83,13 @@ if (link.player?.id === d.id) return link.isPlaying ? t('settings.devices.playing') : t('player.devices_paused'); return t('settings.devices.online'); }; + + const castDeviceStatus = (d: api.CastDevice) => { + if (castActive?.id === d.id) { + return playback.paused ? t('player.devices_paused') : t('player.cast_playing'); + } + return d.model ?? t('player.cast_online'); + }; {#snippet row(icon: typeof ComputerIcon, name: string, status: string, active: boolean, disabled: boolean, pick: () => void)} @@ -81,7 +122,7 @@ if/else: bits-ui keeps a single trigger node per popover, and the one unmounting on a handover clears it after the new one set it, so the popover stopped opening. --> {remotePlayer.name} + {:else if castActive} + + {castActive.name} {:else} {/if} @@ -129,7 +173,7 @@ : t('player.devices_this_computer_hint'), here, false, - () => (here ? (open = false) : playOn('')) + selectHere )} {#each link.devices as d (d.id)} {@render row( @@ -141,6 +185,16 @@ () => (!here && link.player?.id === d.id ? (open = false) : playOn(d.id)) )} {/each} + {#each cast.devices as d (d.id)} + {@render row( + CastIcon, + d.name, + castDeviceStatus(d), + castActive?.id === d.id, + false, + () => selectCast(d) + )} + {/each}
{/snippet} - + {remotePlayer.name} - {:else if castActive} - - {castActive.name} + {:else if casting} + + {casting.name} {:else} {/if} @@ -181,21 +203,32 @@ SmartPhone01Icon, d.name, deviceStatus(d), - !here && link.player?.id === d.id, + !!remotePlayer && link.player?.id === d.id, !d.online, - () => (!here && link.player?.id === d.id ? (open = false) : playOn(d.id)) + () => (remotePlayer && link.player?.id === d.id ? (open = false) : playOn(d.id)) )} {/each} {#each cast.devices as d (d.id)} {@render row( - CastIcon, + castIcon(d), d.name, - castDeviceStatus(d), - castActive?.id === d.id, - false, - () => selectCast(d) + castStatus(d), + casting?.id === d.id, + !!cast.connecting && cast.connecting !== d.id, + () => castTo(d), + cast.connecting === d.id )} {/each} + {#if cast.devices.length === 0} +

+ {#if searching} + + {t('cast.searching')} + {:else} + {t('cast.none_found')} + {/if} +

+ {/if}