diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 129f89cfa..735fd0488 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -50,3 +50,7 @@ on Linux/macOS next to the library in `/runtime/onnxruntime-1.24.4
## Microsoft Visual C++ Redistributable (Windows)
- Limusic ships four Microsoft Visual C++ runtime DLLs in the Windows installer, in the `vcruntime` folder next to the app: vcruntime140.dll, vcruntime140_1.dll, msvcp140.dll and msvcp140_1.dll (under 1 MB in total, version 14.44 or newer), unmodified, copied from the Visual Studio redistributable folder that Microsoft's licence terms allow applications to redistribute. `onnxruntime.dll` needs them. They are only loaded when karaoke is turned on; the loader refuses a copy older than 14.44, and if the folder is missing it uses the system's copy instead (the Microsoft Visual C++ Redistributable 14.44 or newer), showing a message with Microsoft's download link when that is missing or older.
+
+## Casting (`mdns-sd`)
+
+- The [`mdns-sd`](https://github.com/keepsimple1/mdns-sd) crate (0.21.7, Apache-2.0 OR MIT) is used for finding Cast devices on the local network over mDNS.
diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml
new file mode 100644
index 000000000..11cf5b841
--- /dev/null
+++ b/crates/cast/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "cast"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
+mdns-sd = "0.21.7"
+serde.workspace = true
+serde_json.workspace = true
+tokio = { workspace = true, features = ["net", "io-util"] }
+# The device's control channel is TLS with a self-signed certificate. ring, like the rest of the
+# tree's rustls users, so no second crypto provider is built.
+tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
+tracing.workspace = true
diff --git a/crates/cast/src/channel.rs b/crates/cast/src/channel.rs
new file mode 100644
index 000000000..4611a9a0d
--- /dev/null
+++ b/crates/cast/src/channel.rs
@@ -0,0 +1,790 @@
+//! One connection to a Cast device, talking to Google's Default Media Receiver.
+//!
+//! A Cast device listens on TLS (port 8009 for a single device, another port for a speaker
+//! group) and speaks CastV2: a protobuf envelope ([`crate::proto`]) carrying JSON. Four
+//! namespaces are used:
+//!
+//! - `tp.connection`: CONNECT opens a virtual connection to the platform (`receiver-0`) or to the
+//! receiver app's transport; CLOSE ends one.
+//! - `tp.heartbeat`: PING/PONG. Both sides ping; a side that hears nothing drops the other.
+//! - `receiver`: LAUNCH the receiver app, GET_STATUS, the speaker's volume, STOP the app.
+//! - `media`: the queue and the transport.
+//!
+//! The socket is owned by one task. Commands go in over a channel, [`Event`]s come back over
+//! another. The device pings every 5 s, so 15 s without a single frame means it is gone, and the
+//! connection ends with [`Closed::Lost`] instead of waiting minutes for TCP to give up.
+
+use std::net::IpAddr;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use serde_json::{json, Value};
+use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, WriteHalf};
+use tokio::net::TcpStream;
+use tokio::sync::{mpsc, oneshot};
+use tokio_rustls::rustls;
+
+use crate::proto;
+
+const NS_CONNECTION: &str = "urn:x-cast:com.google.cast.tp.connection";
+const NS_HEARTBEAT: &str = "urn:x-cast:com.google.cast.tp.heartbeat";
+const NS_RECEIVER: &str = "urn:x-cast:com.google.cast.receiver";
+const NS_MEDIA: &str = "urn:x-cast:com.google.cast.media";
+
+/// The device itself, before any app runs on it.
+const PLATFORM: &str = "receiver-0";
+/// This end of every virtual connection.
+const SENDER: &str = "sender-0";
+
+/// Google's built-in receiver. Needs no registration, shows title, artist and cover.
+pub const DEFAULT_MEDIA_RECEIVER: &str = "CC1AD845";
+
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
+/// From the TLS handshake to the receiver app answering on its transport.
+const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(8);
+const HEARTBEAT: Duration = Duration::from_secs(5);
+/// No frame for this long and the device is gone. It pings every 5 s.
+const IDLE: Duration =
+ if cfg!(test) { Duration::from_millis(2000) } else { Duration::from_secs(15) };
+/// How long commands wait for the media session a load creates before they go out anyway.
+const GATE: Duration = Duration::from_secs(8);
+/// How long a queue edit waits for the item ids before it goes ahead with what it has.
+const IDS_WAIT: Duration = Duration::from_secs(3);
+/// A backstop for statuses the device didn't push.
+const STATUS_POLL: Duration = Duration::from_secs(5);
+/// How long the next song is buffered before the current one ends.
+const PRELOAD_SECS: f64 = 20.0;
+
+/// One track for the device.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Media {
+ /// Where the device fetches it from.
+ pub url: String,
+ pub content_type: String,
+ pub title: String,
+ pub artist: String,
+ pub album: Option,
+ /// Cover art. The device fetches it itself, so it must be reachable from the device.
+ pub image: Option,
+ pub duration: Option,
+}
+
+/// The receiver's repeat mode. Repeat-all is the app's business: it wraps its own queue.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Repeat {
+ Off,
+ One,
+}
+
+impl Repeat {
+ fn wire(self) -> &'static str {
+ match self {
+ Repeat::Off => "REPEAT_OFF",
+ Repeat::One => "REPEAT_SINGLE",
+ }
+ }
+}
+
+/// What the app asks of the device.
+#[derive(Debug)]
+pub enum Command {
+ /// Replace the device's queue. `start` is the position in the first item.
+ Load {
+ items: Vec,
+ start: f64,
+ autoplay: bool,
+ repeat: Repeat,
+ },
+ /// Add one item after the last one.
+ Append(Media),
+ /// Remove every item after the one playing.
+ DropNext,
+ /// Remove every item before the one playing.
+ TrimPlayed,
+ Repeat(Repeat),
+ /// Jump to the next item.
+ Next,
+ Play,
+ Pause,
+ Seek(f64),
+ /// The speaker's level, 0.0 to 1.0.
+ Volume(f64),
+ /// Stop the media and the receiver app, then close. The ack fires once it is written.
+ Close(oneshot::Sender<()>),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum State {
+ Idle,
+ Playing,
+ Paused,
+ Buffering,
+}
+
+/// The media status the device reports.
+#[derive(Debug, Clone, PartialEq)]
+pub struct MediaStatus {
+ pub session: i64,
+ pub state: State,
+ /// Why the device went idle: `FINISHED`, `ERROR`, `CANCELLED`, `INTERRUPTED`.
+ pub idle_reason: Option,
+ pub position: f64,
+ pub duration: Option,
+ /// The URL of the item playing. Each URL handed over is unique, so this names the item.
+ pub content_id: Option,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum Event {
+ /// The media status changed. `None`: the device has no media session.
+ Media(Option),
+ /// The speaker's volume, 0.0 to 1.0.
+ Volume { level: f64, muted: bool },
+ /// The device refused a load.
+ LoadFailed(String),
+ /// The connection ended. Always the last event.
+ Closed(Closed),
+}
+
+/// Why a connection ended or never started.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Closed {
+ /// It couldn't be reached at all.
+ Unreachable(String),
+ /// It refused to start the receiver.
+ Refused(String),
+ /// It stopped answering.
+ Lost,
+ /// Another sender started something else on it.
+ TakenOver,
+ /// The receiver app was stopped on the device (the Google Home app, a voice command).
+ Stopped,
+ /// The app closed it, or the socket ended.
+ Ended(String),
+}
+
+/// The app's end of a connection. Dropping every clone closes it without stopping the device.
+#[derive(Clone, Debug)]
+pub struct Sender(mpsc::UnboundedSender);
+
+impl Sender {
+ pub fn send(&self, cmd: Command) {
+ let _ = self.0.send(cmd);
+ }
+
+ /// Stop the device and close, waiting at most `limit` for the stop to be written.
+ pub async fn close(&self, limit: Duration) {
+ let (tx, rx) = oneshot::channel();
+ if self.0.send(Command::Close(tx)).is_ok() {
+ let _ = tokio::time::timeout(limit, rx).await;
+ }
+ }
+}
+
+/// Connect to a device and start (or join) the Default Media Receiver on it.
+pub async fn connect(
+ ip: IpAddr,
+ port: u16,
+) -> Result<(Sender, mpsc::UnboundedReceiver), Closed> {
+ let unreachable = |e: &dyn std::fmt::Display| Closed::Unreachable(e.to_string());
+ let tcp = tokio::time::timeout(CONNECT_TIMEOUT, TcpStream::connect((ip, port)))
+ .await
+ .map_err(|e| unreachable(&e))?
+ .map_err(|e| unreachable(&e))?;
+ let _ = tcp.set_nodelay(true);
+ let tls = tokio_rustls::TlsConnector::from(Arc::new(tls_config()));
+ let stream = tokio::time::timeout(CONNECT_TIMEOUT, tls.connect(ip.into(), tcp))
+ .await
+ .map_err(|e| unreachable(&e))?
+ .map_err(|e| unreachable(&e))?;
+ start(stream).await
+}
+
+/// Run the protocol over an open stream. Split from [`connect`] so tests can hand it any stream.
+async fn start(stream: S) -> Result<(Sender, mpsc::UnboundedReceiver), Closed>
+where
+ S: AsyncRead + AsyncWrite + Send + 'static,
+{
+ let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
+ let (ev_tx, ev_rx) = mpsc::unbounded_channel();
+ let (ready_tx, ready_rx) = oneshot::channel();
+ tokio::spawn(run(stream, cmd_rx, ev_tx, ready_tx));
+ match tokio::time::timeout(HANDSHAKE_TIMEOUT, ready_rx).await {
+ Ok(Ok(Ok(()))) => Ok((Sender(cmd_tx), ev_rx)),
+ Ok(Ok(Err(closed))) => Err(closed),
+ _ => Err(Closed::Unreachable("the receiver did not answer".into())),
+ }
+}
+
+/// What the socket task knows about the receiver.
+struct Link {
+ writer: WriteHalf,
+ request: i64,
+ /// The receiver app's session (named in payloads) and transport (the address of its
+ /// connection). Both `None` until the app answers.
+ session: Option,
+ transport: Option,
+ launched: bool,
+ /// The media session playing; transport commands name it. 0: none.
+ media_session: i64,
+ /// A load is in flight: until the device reports a session other than this one, commands
+ /// that name a session would name the old one, so they wait.
+ gate: Option<(Instant, i64)>,
+ /// The commands waiting, in order.
+ waiting: Vec,
+ /// The queue's item ids in order, and the one playing. Queue edits are by id.
+ ids: Vec,
+ current_item: Option,
+ /// The ids were asked for and haven't come back.
+ ids_asked: Option,
+ last_volume: Option<(f64, bool)>,
+}
+
+async fn run(
+ stream: S,
+ mut cmds: mpsc::UnboundedReceiver,
+ events: mpsc::UnboundedSender,
+ ready: oneshot::Sender>,
+) where
+ S: AsyncRead + AsyncWrite + Send + 'static,
+{
+ let (mut reader, writer) = tokio::io::split(stream);
+ // The reader is its own task: a read cancelled by `select!` would lose half a frame.
+ let (frame_tx, mut frames) = mpsc::unbounded_channel::>();
+ let reader_task = tokio::spawn(async move {
+ loop {
+ let mut len = [0u8; 4];
+ if let Err(e) = reader.read_exact(&mut len).await {
+ let _ = frame_tx.send(Err(e.to_string()));
+ return;
+ }
+ let len = u32::from_be_bytes(len) as usize;
+ if len > proto::MAX_FRAME {
+ let _ = frame_tx.send(Err("oversized frame".into()));
+ return;
+ }
+ let mut body = vec![0u8; len];
+ if let Err(e) = reader.read_exact(&mut body).await {
+ let _ = frame_tx.send(Err(e.to_string()));
+ return;
+ }
+ if let Some(frame) = proto::decode(&body) {
+ if frame_tx.send(Ok(frame)).is_err() {
+ return;
+ }
+ }
+ }
+ });
+
+ let mut link = Link {
+ writer,
+ request: 0,
+ session: None,
+ transport: None,
+ launched: false,
+ media_session: 0,
+ gate: None,
+ waiting: Vec::new(),
+ ids: Vec::new(),
+ current_item: None,
+ ids_asked: None,
+ last_volume: None,
+ };
+ let mut ready = Some(ready);
+ let mut last_heard = Instant::now();
+ let mut heartbeat = tokio::time::interval(HEARTBEAT);
+ let mut tick = tokio::time::interval(Duration::from_millis(200));
+ let mut poll = tokio::time::interval(STATUS_POLL);
+
+ let opened = async {
+ link.write(NS_CONNECTION, PLATFORM, connect_payload()).await?;
+ link.write_receiver(json!({ "type": "GET_STATUS" })).await
+ };
+ let closed = match opened.await {
+ Err(e) => e,
+ Ok(()) => loop {
+ let step = tokio::select! {
+ cmd = cmds.recv() => match cmd {
+ // Every sender dropped: close without stopping the device.
+ None => Err(Closed::Ended("closed by the app".into())),
+ Some(Command::Close(ack)) => {
+ link.close().await;
+ let _ = ack.send(());
+ Err(Closed::Ended("closed by the app".into()))
+ }
+ Some(cmd) => link.command(cmd).await,
+ },
+ frame = frames.recv() => match frame {
+ Some(Ok(frame)) => {
+ last_heard = Instant::now();
+ link.frame(frame, &events, &mut ready).await
+ }
+ Some(Err(e)) => Err(Closed::Ended(e)),
+ None => Err(Closed::Ended("the connection closed".into())),
+ },
+ _ = heartbeat.tick() => {
+ link.write(NS_HEARTBEAT, PLATFORM, json!({ "type": "PING" })).await
+ }
+ _ = tick.tick() => {
+ if last_heard.elapsed() > IDLE {
+ Err(Closed::Lost)
+ } else {
+ link.timers().await
+ }
+ }
+ _ = poll.tick() => link.poll().await,
+ };
+ if let Err(e) = step {
+ break e;
+ }
+ },
+ };
+ reader_task.abort();
+ match ready.take() {
+ Some(ready) => {
+ let _ = ready.send(Err(closed));
+ }
+ None => {
+ let _ = events.send(Event::Closed(closed));
+ }
+ }
+}
+
+type Step = Result<(), Closed>;
+
+impl Link {
+ async fn write(&mut self, ns: &str, to: &str, mut payload: Value) -> Step {
+ self.request += 1;
+ payload["requestId"] = json!(self.request);
+ let msg = proto::frame(ns, SENDER, to, &payload.to_string());
+ self.writer.write_all(&msg).await.map_err(|e| Closed::Ended(e.to_string()))
+ }
+
+ async fn write_receiver(&mut self, payload: Value) -> Step {
+ self.write(NS_RECEIVER, PLATFORM, payload).await
+ }
+
+ /// A media message to the receiver app. Dropped when there is no app yet.
+ async fn write_media(&mut self, payload: Value) -> Step {
+ let Some(to) = self.transport.clone() else { return Ok(()) };
+ self.write(NS_MEDIA, &to, payload).await
+ }
+
+ /// A transport command naming the media session playing.
+ async fn write_session(&mut self, mut payload: Value) -> Step {
+ payload["mediaSessionId"] = json!(self.media_session);
+ self.write_media(payload).await
+ }
+
+ async fn command(&mut self, cmd: Command) -> Step {
+ match cmd {
+ Command::Volume(level) => {
+ self.write_receiver(json!({
+ "type": "SET_VOLUME", "volume": { "level": level.clamp(0.0, 1.0) },
+ }))
+ .await
+ }
+ Command::Load { .. } if self.gate.is_some() || self.transport.is_none() => {
+ // The queue is the truth: whatever waited belongs to the queue this replaces.
+ self.waiting.clear();
+ self.waiting.push(cmd);
+ Ok(())
+ }
+ Command::Load { items, start, autoplay, repeat } => {
+ let items: Vec = items
+ .iter()
+ .enumerate()
+ .map(|(i, m)| queue_item(m, i > 0 || autoplay))
+ .collect();
+ let session = self.session.clone().unwrap_or_default();
+ self.write_media(json!({
+ "type": "QUEUE_LOAD", "sessionId": session, "items": items, "startIndex": 0,
+ "currentTime": start, "repeatMode": repeat.wire(),
+ }))
+ .await?;
+ self.gate = Some((Instant::now() + GATE, self.media_session));
+ self.ids.clear();
+ self.current_item = None;
+ if !autoplay {
+ // In case the receiver ignores the item's `autoplay`: a pause on a paused
+ // session changes nothing.
+ self.waiting.push(Command::Pause);
+ }
+ Ok(())
+ }
+ cmd if self.gate.is_some() => {
+ self.wait(cmd);
+ Ok(())
+ }
+ // Queue edits keep their order behind ones that wait for ids; the transport doesn't
+ // have to, or a pause would sit behind a reorder for seconds.
+ cmd if !self.waiting.is_empty() && !is_transport(&cmd) => {
+ self.wait(cmd);
+ Ok(())
+ }
+ // Nothing is loaded: there is nothing for a transport command to act on.
+ _ if self.media_session == 0 => Ok(()),
+ cmd @ (Command::DropNext | Command::TrimPlayed) if self.ids_asked.is_some() => {
+ self.wait(cmd);
+ Ok(())
+ }
+ Command::DropNext => {
+ let at = self.playing_index();
+ let after: Vec = at.map(|i| self.ids[i + 1..].to_vec()).unwrap_or_default();
+ self.remove(after).await
+ }
+ Command::TrimPlayed => {
+ let at = self.playing_index();
+ let before: Vec = at.map(|i| self.ids[..i].to_vec()).unwrap_or_default();
+ self.remove(before).await
+ }
+ Command::Append(media) => {
+ self.write_session(
+ json!({ "type": "QUEUE_INSERT", "items": [queue_item(&media, true)] }),
+ )
+ .await?;
+ self.ask_ids().await
+ }
+ Command::Repeat(repeat) => {
+ self.write_session(json!({ "type": "QUEUE_UPDATE", "repeatMode": repeat.wire() }))
+ .await
+ }
+ Command::Next => self.write_session(json!({ "type": "QUEUE_UPDATE", "jump": 1 })).await,
+ Command::Play => self.write_session(json!({ "type": "PLAY" })).await,
+ Command::Pause => self.write_session(json!({ "type": "PAUSE" })).await,
+ Command::Seek(at) => {
+ self.write_session(json!({ "type": "SEEK", "currentTime": at.max(0.0) })).await
+ }
+ Command::Close(_) => Ok(()), // handled by the loop
+ }
+ }
+
+ /// Hold a command, keeping only the latest of a kind where an older one means nothing.
+ fn wait(&mut self, cmd: Command) {
+ let same = |c: &Command| {
+ matches!(
+ (&cmd, c),
+ (Command::Play | Command::Pause, Command::Play | Command::Pause)
+ | (Command::Seek(_), Command::Seek(_))
+ | (Command::Repeat(_), Command::Repeat(_))
+ )
+ };
+ self.waiting.retain(|c| !same(c));
+ self.waiting.push(cmd);
+ }
+
+ fn playing_index(&self) -> Option {
+ let current = self.current_item?;
+ self.ids.iter().position(|id| *id == current)
+ }
+
+ async fn remove(&mut self, ids: Vec) -> Step {
+ if ids.is_empty() {
+ return Ok(());
+ }
+ self.write_session(json!({ "type": "QUEUE_REMOVE", "itemIds": ids })).await?;
+ self.ask_ids().await
+ }
+
+ async fn ask_ids(&mut self) -> Step {
+ self.ids_asked = Some(Instant::now());
+ self.write_session(json!({ "type": "QUEUE_GET_ITEM_IDS" })).await
+ }
+
+ /// Send what waited, in order, until something has to wait again.
+ async fn flush(&mut self) -> Step {
+ let waiting = std::mem::take(&mut self.waiting);
+ let mut rest = waiting.into_iter();
+ while let Some(cmd) = rest.next() {
+ let needs_ids = matches!(cmd, Command::DropNext | Command::TrimPlayed);
+ if self.gate.is_some() || (needs_ids && self.ids_asked.is_some()) {
+ // Keep the order: this and what follows wait behind what just went out.
+ self.waiting.push(cmd);
+ self.waiting.extend(rest);
+ break;
+ }
+ self.command(cmd).await?;
+ }
+ Ok(())
+ }
+
+ async fn timers(&mut self) -> Step {
+ let now = Instant::now();
+ if self.gate.is_some_and(|(until, _)| now >= until) {
+ tracing::debug!("cast: the device never reported the load's session");
+ self.gate = None;
+ }
+ if self.ids_asked.is_some_and(|at| now >= at + IDS_WAIT) {
+ self.ids_asked = None;
+ }
+ if self.gate.is_none() && self.ids_asked.is_none() && !self.waiting.is_empty() {
+ self.flush().await?;
+ }
+ Ok(())
+ }
+
+ async fn poll(&mut self) -> Step {
+ if self.transport.is_some() {
+ self.write_media(json!({ "type": "GET_STATUS" })).await?;
+ }
+ self.write_receiver(json!({ "type": "GET_STATUS" })).await
+ }
+
+ async fn close(&mut self) {
+ if self.media_session != 0 {
+ let _ = self.write_session(json!({ "type": "STOP" })).await;
+ }
+ if let Some(session) = self.session.clone() {
+ let _ = self.write_receiver(json!({ "type": "STOP", "sessionId": session })).await;
+ }
+ if let Some(to) = self.transport.clone() {
+ let _ = self.write(NS_CONNECTION, &to, json!({ "type": "CLOSE" })).await;
+ }
+ let _ = self.writer.flush().await;
+ }
+
+ async fn frame(
+ &mut self,
+ frame: proto::Frame,
+ events: &mpsc::UnboundedSender,
+ ready: &mut Option>>,
+ ) -> Step {
+ let Ok(msg) = serde_json::from_str::(&frame.payload) else { return Ok(()) };
+ let kind = msg.get("type").and_then(Value::as_str).unwrap_or_default();
+ match (frame.namespace.as_str(), kind) {
+ (NS_HEARTBEAT, "PING") => {
+ self.write(NS_HEARTBEAT, &frame.source, json!({ "type": "PONG" })).await
+ }
+ (NS_CONNECTION, "CLOSE") if Some(&frame.source) == self.transport.as_ref() => {
+ Err(Closed::TakenOver)
+ }
+ (NS_RECEIVER, "RECEIVER_STATUS") => self.receiver_status(&msg, events, ready).await,
+ (NS_RECEIVER, "LAUNCH_ERROR") => {
+ let reason = msg.get("reason").and_then(Value::as_str).unwrap_or("LAUNCH_ERROR");
+ Err(Closed::Refused(reason.to_owned()))
+ }
+ (NS_MEDIA, "MEDIA_STATUS") => {
+ let entry = msg.get("status").and_then(Value::as_array).and_then(|s| s.first());
+ let status = entry.and_then(media_status);
+ if let Some(entry) = entry {
+ self.current_item = entry.get("currentItemId").and_then(Value::as_i64);
+ // Only a fallback for a receiver that never answers QUEUE_GET_ITEM_IDS: the
+ // list in a status isn't promised to be the whole queue.
+ if self.ids.is_empty() {
+ if let Some(items) = entry.get("items").and_then(Value::as_array) {
+ self.ids = items.iter().filter_map(|i| i["itemId"].as_i64()).collect();
+ }
+ }
+ }
+ let session = status.as_ref().map_or(0, |s| s.session);
+ self.media_session = session;
+ if self.gate.is_some_and(|(_, old)| session != 0 && session != old) {
+ self.gate = None;
+ self.ask_ids().await?;
+ }
+ let _ = events.send(Event::Media(status));
+ Ok(())
+ }
+ (NS_MEDIA, "QUEUE_ITEM_IDS") => {
+ if let Some(ids) = msg.get("itemIds").and_then(Value::as_array) {
+ self.ids = ids.iter().filter_map(Value::as_i64).collect();
+ }
+ self.ids_asked = None;
+ if self.gate.is_none() {
+ self.flush().await?;
+ }
+ Ok(())
+ }
+ (NS_MEDIA, "QUEUE_CHANGE") => self.ask_ids().await,
+ (NS_MEDIA, "LOAD_FAILED" | "LOAD_CANCELLED" | "INVALID_REQUEST") => {
+ let reason = msg.get("reason").and_then(Value::as_str).unwrap_or(kind);
+ tracing::warn!(kind, reason, "cast: the device refused a request");
+ // A command against a session that just ended is answered this way and means
+ // nothing, and a cancelled load was replaced or stopped on purpose. A refusal
+ // while a load is in flight is that load.
+ let stale = reason == "INVALID_MEDIA_SESSION_ID" || kind == "LOAD_CANCELLED";
+ let was_loading = self.gate.take().is_some();
+ if !stale && (was_loading || kind == "LOAD_FAILED") {
+ self.waiting.retain(|c| matches!(c, Command::Load { .. }));
+ let _ = events.send(Event::LoadFailed(reason.to_owned()));
+ }
+ self.flush().await
+ }
+ _ => Ok(()),
+ }
+ }
+
+ async fn receiver_status(
+ &mut self,
+ msg: &Value,
+ events: &mpsc::UnboundedSender,
+ ready: &mut Option>>,
+ ) -> Step {
+ let status = &msg["status"];
+ if let Some(level) = status["volume"]["level"].as_f64() {
+ let muted = status["volume"]["muted"].as_bool().unwrap_or(false);
+ if self.last_volume != Some((level, muted)) {
+ self.last_volume = Some((level, muted));
+ let _ = events.send(Event::Volume { level, muted });
+ }
+ }
+ // No application list: nothing is running on the device.
+ let none = Vec::new();
+ let apps = status.get("applications").and_then(Value::as_array).unwrap_or(&none);
+ let ours = apps
+ .iter()
+ .find(|a| a["appId"].as_str() == Some(DEFAULT_MEDIA_RECEIVER))
+ .and_then(|a| Some((a["sessionId"].as_str()?, a["transportId"].as_str()?)));
+ match (ours, self.session.as_deref()) {
+ // Still running, the same session.
+ (Some((session, _)), Some(known)) if session == known => Ok(()),
+ // Stopped, with nothing in its place.
+ (None, Some(_)) if apps.is_empty() => Err(Closed::Stopped),
+ // Replaced by another app, or by another sender's session.
+ (_, Some(_)) => Err(Closed::TakenOver),
+ // Running before this connection (left from an earlier one, or another sender's):
+ // join it rather than launching it again.
+ (Some((session, transport)), None) => {
+ self.session = Some(session.to_owned());
+ self.transport = Some(transport.to_owned());
+ self.write(NS_CONNECTION, transport, connect_payload()).await?;
+ self.write_media(json!({ "type": "GET_STATUS" })).await?;
+ if let Some(ready) = ready.take() {
+ let _ = ready.send(Ok(()));
+ }
+ self.flush().await
+ }
+ (None, None) => self.launch().await,
+ }
+ }
+
+ async fn launch(&mut self) -> Step {
+ if self.launched {
+ return Ok(());
+ }
+ self.launched = true;
+ self.write_receiver(json!({ "type": "LAUNCH", "appId": DEFAULT_MEDIA_RECEIVER })).await
+ }
+}
+
+/// Commands that act on the playing session and not on the queue.
+fn is_transport(cmd: &Command) -> bool {
+ matches!(
+ cmd,
+ Command::Play | Command::Pause | Command::Seek(_) | Command::Repeat(_) | Command::Volume(_)
+ )
+}
+
+/// The CONNECT payload. `userAgent` names the sender; it can't rename the receiver app, which
+/// Google calls "Default Media Receiver".
+fn connect_payload() -> Value {
+ json!({
+ "type": "CONNECT",
+ "origin": {},
+ "userAgent": "Limusic",
+ "senderInfo": {
+ "sdkType": 2,
+ "version": env!("CARGO_PKG_VERSION"),
+ "browserVersion": "1.0.0",
+ "platform": 4,
+ "systemVersion": "Limusic",
+ "connectionType": 1,
+ },
+ })
+}
+
+fn queue_item(media: &Media, autoplay: bool) -> Value {
+ let mut metadata = json!({ "metadataType": 3, "title": media.title, "artist": media.artist });
+ if let Some(album) = &media.album {
+ metadata["albumName"] = json!(album);
+ }
+ if let Some(image) = &media.image {
+ metadata["images"] = json!([{ "url": image }]);
+ }
+ let mut info = json!({
+ "contentId": media.url,
+ "contentUrl": media.url,
+ "contentType": media.content_type,
+ "streamType": "BUFFERED",
+ "metadata": metadata,
+ });
+ // A null duration reads as zero on the receiver, which then thinks the track is over.
+ if let Some(d) = media.duration.filter(|d| *d > 0.0) {
+ info["duration"] = json!(d);
+ }
+ json!({ "media": info, "autoplay": autoplay, "preloadTime": PRELOAD_SECS })
+}
+
+/// One entry of a MEDIA_STATUS.
+fn media_status(entry: &Value) -> Option {
+ let state = match entry.get("playerState")?.as_str()? {
+ "PLAYING" => State::Playing,
+ "PAUSED" => State::Paused,
+ "BUFFERING" => State::Buffering,
+ _ => State::Idle,
+ };
+ Some(MediaStatus {
+ session: entry.get("mediaSessionId").and_then(Value::as_i64).unwrap_or(0),
+ state,
+ idle_reason: entry.get("idleReason").and_then(Value::as_str).map(str::to_owned),
+ position: entry.get("currentTime").and_then(Value::as_f64).unwrap_or(0.0),
+ duration: entry["media"]["duration"].as_f64(),
+ content_id: entry["media"]["contentId"].as_str().map(str::to_owned),
+ })
+}
+
+/// The device's certificate is self-signed, so there is nothing to check it against. The
+/// device is found on the local network and identified by its mDNS id.
+fn tls_config() -> rustls::ClientConfig {
+ use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
+ use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
+
+ #[derive(Debug)]
+ struct AnyCertificate(Arc);
+
+ impl ServerCertVerifier for AnyCertificate {
+ fn verify_server_cert(
+ &self,
+ _: &CertificateDer<'_>,
+ _: &[CertificateDer<'_>],
+ _: &ServerName<'_>,
+ _: &[u8],
+ _: UnixTime,
+ ) -> Result {
+ Ok(ServerCertVerified::assertion())
+ }
+
+ fn verify_tls12_signature(
+ &self,
+ _: &[u8],
+ _: &CertificateDer<'_>,
+ _: &rustls::DigitallySignedStruct,
+ ) -> Result {
+ Ok(HandshakeSignatureValid::assertion())
+ }
+
+ fn verify_tls13_signature(
+ &self,
+ _: &[u8],
+ _: &CertificateDer<'_>,
+ _: &rustls::DigitallySignedStruct,
+ ) -> Result {
+ Ok(HandshakeSignatureValid::assertion())
+ }
+
+ fn supported_verify_schemes(&self) -> Vec {
+ self.0.signature_verification_algorithms.supported_schemes()
+ }
+ }
+
+ let provider = Arc::new(rustls::crypto::ring::default_provider());
+ rustls::ClientConfig::builder_with_provider(provider.clone())
+ .with_safe_default_protocol_versions()
+ .expect("ring speaks TLS 1.2 and 1.3")
+ .dangerous()
+ .with_custom_certificate_verifier(Arc::new(AnyCertificate(provider)))
+ .with_no_client_auth()
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/cast/src/channel/tests.rs b/crates/cast/src/channel/tests.rs
new file mode 100644
index 000000000..aecd82289
--- /dev/null
+++ b/crates/cast/src/channel/tests.rs
@@ -0,0 +1,302 @@
+//! The channel against a fake receiver over real TLS: what it sends, in what order, and how it
+//! notices a device that goes away. The fake answers the way the Default Media Receiver does for
+//! the messages used here; it is not a replacement for a test on hardware.
+
+use super::*;
+use std::sync::Mutex;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer};
+
+/// How the fake behaves, and what it heard.
+#[derive(Default)]
+struct Fake {
+ /// The receiver app is already running when the sender connects.
+ running: bool,
+ /// Stop pinging and answering after the receiver app starts.
+ go_silent: bool,
+ /// Another app runs instead of the receiver (a phone cast YouTube).
+ other_app: bool,
+ /// The media messages it got, as `TYPE` or `TYPE(mediaSessionId)`.
+ heard: Vec,
+ session: i64,
+ ids: Vec,
+ next_id: i64,
+}
+
+type Shared = Arc>;
+
+async fn fake_receiver(fake: Shared) -> u16 {
+ let cert = CertificateDer::from(
+ include_bytes!("../../tests/fixtures/fake-receiver-cert.der").to_vec(),
+ );
+ let key = PrivateKeyDer::try_from(
+ include_bytes!("../../tests/fixtures/fake-receiver-key.der").to_vec(),
+ )
+ .unwrap();
+ let provider = Arc::new(rustls::crypto::ring::default_provider());
+ let config = rustls::ServerConfig::builder_with_provider(provider)
+ .with_safe_default_protocol_versions()
+ .unwrap()
+ .with_no_client_auth()
+ .with_single_cert(vec![cert], key)
+ .unwrap();
+ let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config));
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ let (tcp, _) = listener.accept().await.unwrap();
+ let tls = acceptor.accept(tcp).await.unwrap();
+ let (mut rd, wr) = tokio::io::split(tls);
+ let wr = Arc::new(tokio::sync::Mutex::new(wr));
+ let send =
+ |wr: Arc>>, ns: &'static str, from: &str, v: Value| {
+ let msg = proto::frame(ns, from, SENDER, &v.to_string());
+ async move {
+ let _ = wr.lock().await.write_all(&msg).await;
+ }
+ };
+ let pinger = {
+ let (wr, fake) = (wr.clone(), fake.clone());
+ tokio::spawn(async move {
+ loop {
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ if fake.lock().unwrap().go_silent && fake.lock().unwrap().session >= 0 {
+ let started = fake.lock().unwrap().running;
+ if started {
+ continue;
+ }
+ }
+ send(wr.clone(), NS_HEARTBEAT, PLATFORM, json!({ "type": "PING" })).await;
+ }
+ })
+ };
+ loop {
+ let mut len = [0u8; 4];
+ if rd.read_exact(&mut len).await.is_err() {
+ break;
+ }
+ let mut body = vec![0u8; u32::from_be_bytes(len) as usize];
+ if rd.read_exact(&mut body).await.is_err() {
+ break;
+ }
+ let frame = proto::decode(&body).unwrap();
+ let msg: Value = serde_json::from_str(&frame.payload).unwrap();
+ let kind = msg["type"].as_str().unwrap_or_default().to_owned();
+ if fake.lock().unwrap().go_silent && fake.lock().unwrap().running {
+ continue;
+ }
+ let apps = |f: &Fake| {
+ if f.other_app {
+ json!([{ "appId": "233637DE", "sessionId": "y1", "transportId": "y1" }])
+ } else if f.running {
+ json!([{ "appId": DEFAULT_MEDIA_RECEIVER, "sessionId": "s1", "transportId": "t1" }])
+ } else {
+ json!([])
+ }
+ };
+ let receiver_status = |f: &Fake| {
+ json!({ "type": "RECEIVER_STATUS", "status": {
+ "applications": apps(f), "volume": { "level": 0.3, "muted": false } } })
+ };
+ let media_status = |f: &Fake, state: &str| {
+ json!({ "type": "MEDIA_STATUS", "status": [{
+ "mediaSessionId": f.session, "playerState": state, "currentTime": 1.0,
+ "currentItemId": f.ids.first(), "media": { "contentId": "http://lan/a" } }] })
+ };
+ match (frame.namespace.as_str(), kind.as_str()) {
+ (NS_RECEIVER, "GET_STATUS") => {
+ let v = receiver_status(&fake.lock().unwrap());
+ send(wr.clone(), NS_RECEIVER, PLATFORM, v).await;
+ }
+ (NS_RECEIVER, "LAUNCH") => {
+ let v = {
+ let mut f = fake.lock().unwrap();
+ f.heard.push("LAUNCH".into());
+ f.running = true;
+ receiver_status(&f)
+ };
+ send(wr.clone(), NS_RECEIVER, PLATFORM, v).await;
+ }
+ (NS_MEDIA, _) => {
+ let reply = {
+ let mut f = fake.lock().unwrap();
+ let named = msg["mediaSessionId"].as_i64();
+ f.heard.push(match named {
+ Some(s) => format!("{kind}({s})"),
+ None => kind.clone(),
+ });
+ match kind.as_str() {
+ "QUEUE_LOAD" => {
+ f.session += 1;
+ f.ids.clear();
+ for _ in msg["items"].as_array().unwrap() {
+ f.next_id += 1;
+ let id = f.next_id;
+ f.ids.push(id);
+ }
+ Some(media_status(&f, "PLAYING"))
+ }
+ "QUEUE_INSERT" => {
+ f.next_id += 1;
+ let id = f.next_id;
+ f.ids.push(id);
+ None
+ }
+ "QUEUE_REMOVE" => {
+ let gone: Vec = msg["itemIds"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(Value::as_i64)
+ .collect();
+ f.ids.retain(|id| !gone.contains(id));
+ None
+ }
+ "QUEUE_GET_ITEM_IDS" => {
+ Some(json!({ "type": "QUEUE_ITEM_IDS", "itemIds": f.ids }))
+ }
+ "PAUSE" => Some(media_status(&f, "PAUSED")),
+ _ => None,
+ }
+ };
+ if let Some(v) = reply {
+ send(wr.clone(), NS_MEDIA, "t1", v).await;
+ }
+ }
+ _ => {}
+ }
+ }
+ pinger.abort();
+ });
+ port
+}
+
+fn track(url: &str) -> Media {
+ Media {
+ url: url.into(),
+ content_type: "audio/webm".into(),
+ title: "A song".into(),
+ artist: "Someone".into(),
+ album: None,
+ image: None,
+ duration: Some(200.0),
+ }
+}
+
+async fn open(fake: &Shared) -> (Sender, mpsc::UnboundedReceiver) {
+ let port = fake_receiver(fake.clone()).await;
+ connect("127.0.0.1".parse().unwrap(), port).await.expect("connects")
+}
+
+/// Wait for the fake to have heard `n` media messages.
+async fn heard(fake: &Shared, n: usize) -> Vec {
+ for _ in 0..250 {
+ let heard = fake.lock().unwrap().heard.clone();
+ if heard.len() >= n {
+ return heard;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ fake.lock().unwrap().heard.clone()
+}
+
+#[tokio::test]
+async fn a_cast_launches_the_receiver_and_reports_the_speakers_volume() {
+ let fake = Shared::default();
+ let (_tx, mut events) = open(&fake).await;
+ assert_eq!(heard(&fake, 1).await, vec!["LAUNCH"]);
+ assert_eq!(events.recv().await, Some(Event::Volume { level: 0.3, muted: false }));
+}
+
+#[tokio::test]
+async fn a_running_receiver_is_joined_not_launched_again() {
+ let fake = Shared::new(Mutex::new(Fake { running: true, ..Fake::default() }));
+ let (_tx, _events) = open(&fake).await;
+ // The join asks for the media status; nothing launches.
+ assert_eq!(heard(&fake, 1).await, vec!["GET_STATUS"]);
+}
+
+#[tokio::test]
+async fn commands_after_a_load_wait_for_the_session_it_makes() {
+ let fake = Shared::default();
+ let (tx, mut events) = open(&fake).await;
+ tx.send(Command::Load {
+ items: vec![track("http://lan/a")],
+ start: 12.0,
+ autoplay: true,
+ repeat: Repeat::Off,
+ });
+ tx.send(Command::Pause);
+ let heard = heard(&fake, 4).await;
+ // The pause names the session the load made (1), never the empty one before it (0).
+ let at = |m: &str| heard.iter().position(|h| h == m);
+ assert!(at("QUEUE_LOAD") < at("PAUSE(1)") && at("PAUSE(1)").is_some(), "{heard:?}");
+ assert!(!heard.iter().any(|h| h.ends_with("(0)")), "{heard:?}");
+ loop {
+ if let Some(Event::Media(Some(s))) = events.recv().await {
+ assert_eq!(s.content_id.as_deref(), Some("http://lan/a"));
+ break;
+ }
+ }
+}
+
+#[tokio::test]
+async fn dropping_the_next_item_removes_the_one_that_was_appended() {
+ let fake = Shared::default();
+ let (tx, _events) = open(&fake).await;
+ tx.send(Command::Load {
+ items: vec![track("http://lan/a")],
+ start: 0.0,
+ autoplay: true,
+ repeat: Repeat::Off,
+ });
+ tx.send(Command::Append(track("http://lan/b")));
+ tx.send(Command::DropNext);
+ let heard = heard(&fake, 6).await;
+ assert!(heard.contains(&"QUEUE_REMOVE(1)".to_owned()), "{heard:?}");
+ assert_eq!(fake.lock().unwrap().ids, vec![1], "only the playing item is left");
+}
+
+#[tokio::test]
+async fn a_device_that_goes_quiet_is_reported_lost() {
+ let fake = Shared::new(Mutex::new(Fake { go_silent: true, ..Fake::default() }));
+ let (_tx, mut events) = open(&fake).await;
+ let closed = tokio::time::timeout(Duration::from_secs(8), async {
+ loop {
+ if let Some(Event::Closed(c)) = events.recv().await {
+ return c;
+ }
+ }
+ })
+ .await
+ .expect("noticed within seconds");
+ assert_eq!(closed, Closed::Lost);
+}
+
+async fn closed_after(fake: &Shared, change: impl FnOnce(&mut Fake)) -> Closed {
+ let (_tx, mut events) = open(fake).await;
+ heard(fake, 1).await;
+ change(&mut fake.lock().unwrap());
+ tokio::time::timeout(Duration::from_secs(8), async {
+ loop {
+ if let Some(Event::Closed(c)) = events.recv().await {
+ return c;
+ }
+ }
+ })
+ .await
+ .expect("noticed on the next status poll")
+}
+
+#[tokio::test]
+async fn another_app_on_the_device_ends_the_cast_as_taken_over() {
+ let fake = Shared::default();
+ assert_eq!(closed_after(&fake, |f| f.other_app = true).await, Closed::TakenOver);
+}
+
+#[tokio::test]
+async fn a_receiver_stopped_on_the_device_ends_the_cast_as_stopped() {
+ let fake = Shared::default();
+ assert_eq!(closed_after(&fake, |f| f.running = false).await, Closed::Stopped);
+}
diff --git a/crates/cast/src/discovery.rs b/crates/cast/src/discovery.rs
new file mode 100644
index 000000000..e0443a814
--- /dev/null
+++ b/crates/cast/src/discovery.rs
@@ -0,0 +1,152 @@
+//! Finding Cast devices over mDNS (`_googlecast._tcp.local.`).
+//!
+//! Browsing only runs while someone could use it (the app decides when): the first multicast
+//! socket is what makes Windows Firewall and macOS's Local Network permission ask, and nobody
+//! should be asked at launch for a feature they never touch.
+
+use std::collections::HashMap;
+use std::net::IpAddr;
+
+use mdns_sd::{ResolvedService, ServiceDaemon, ServiceEvent};
+use tokio::sync::mpsc;
+
+const SERVICE: &str = "_googlecast._tcp.local.";
+
+/// What kind of device it is, for the icon.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Kind {
+ Speaker,
+ Tv,
+ Group,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CastDevice {
+ /// The device's own id (the TXT `id`), stable across renames and address changes.
+ pub id: String,
+ /// The name its owner gave it (`fn`).
+ pub name: String,
+ /// The model (`md`): "Chromecast", "Google Nest Mini", "Google Cast Group".
+ pub model: Option,
+ pub kind: Kind,
+ pub ip: IpAddr,
+ /// Always the announced one: a speaker group listens on a port of its own, not 8009.
+ pub port: u16,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum DiscoveryEvent {
+ Found(CastDevice),
+ Lost(String),
+}
+
+/// A running browse. Dropping it stops the browse and the daemon.
+pub struct Browser {
+ daemon: ServiceDaemon,
+}
+
+impl Drop for Browser {
+ fn drop(&mut self) {
+ let _ = self.daemon.stop_browse(SERVICE);
+ let _ = self.daemon.shutdown();
+ }
+}
+
+/// Start browsing. Each device found or gone arrives on the receiver.
+pub fn browse() -> Result<(mpsc::UnboundedReceiver, Browser), String> {
+ let daemon = ServiceDaemon::new().map_err(|e| e.to_string())?;
+ let events = daemon.browse(SERVICE).map_err(|e| e.to_string())?;
+ let (tx, rx) = mpsc::unbounded_channel();
+ tokio::spawn(async move {
+ // The removal names the mDNS instance, not the device id the app keys on.
+ let mut instances: HashMap = HashMap::new();
+ while let Ok(event) = events.recv_async().await {
+ let sent = match event {
+ ServiceEvent::ServiceResolved(info) => match device(&info) {
+ Some(d) => {
+ instances.insert(info.get_fullname().to_owned(), d.id.clone());
+ tx.send(DiscoveryEvent::Found(d))
+ }
+ None => Ok(()),
+ },
+ ServiceEvent::ServiceRemoved(_, fullname) => match instances.remove(&fullname) {
+ Some(id) => tx.send(DiscoveryEvent::Lost(id)),
+ None => Ok(()),
+ },
+ _ => Ok(()),
+ };
+ if sent.is_err() {
+ return;
+ }
+ }
+ });
+ Ok((rx, Browser { daemon }))
+}
+
+fn device(info: &ResolvedService) -> Option {
+ let txt = |key| info.get_property_val_str(key).map(str::to_owned);
+ // A device whose address record hasn't arrived yet is left for the next event.
+ let ip = IpAddr::V4(*info.get_addresses_v4().iter().min()?);
+ Some(device_from(txt("id")?, txt("fn"), txt("md"), txt("ca"), ip, info.get_port()))
+}
+
+/// The device a TXT record describes. Apart from the mDNS types so it can be tested.
+fn device_from(
+ id: String,
+ name: Option,
+ model: Option,
+ capabilities: Option,
+ ip: IpAddr,
+ port: u16,
+) -> CastDevice {
+ // `ca` is a capability bitmask; bit 0 is video out.
+ let video = capabilities.and_then(|c| c.parse::().ok()).is_some_and(|c| c & 1 == 1);
+ let group = model.as_deref().is_some_and(|m| m.contains("Group"));
+ let kind = if group {
+ Kind::Group
+ } else if video {
+ Kind::Tv
+ } else {
+ Kind::Speaker
+ };
+ let name = name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| id.clone());
+ CastDevice { id, name, model, kind, ip, port }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ip() -> IpAddr {
+ "192.168.1.20".parse().unwrap()
+ }
+
+ #[test]
+ fn the_txt_record_names_the_kind() {
+ let s = |v: &str| Some(v.to_owned());
+ let tv = device_from("a".into(), s("Office TV"), s("Chromecast"), s("4101"), ip(), 8009);
+ assert_eq!(tv.kind, Kind::Tv);
+ assert_eq!(tv.name, "Office TV");
+ let mini =
+ device_from("b".into(), s("Kitchen"), s("Google Nest Mini"), s("2052"), ip(), 8009);
+ assert_eq!(mini.kind, Kind::Speaker);
+ let group = device_from(
+ "c".into(),
+ s("Downstairs"),
+ s("Google Cast Group"),
+ s("2084"),
+ ip(),
+ 32187,
+ );
+ assert_eq!(group.kind, Kind::Group);
+ assert_eq!(group.port, 32187);
+ }
+
+ #[test]
+ fn a_device_without_a_name_is_shown_by_its_id() {
+ let d = device_from("abc".into(), Some(" ".into()), None, None, ip(), 8009);
+ assert_eq!(d.name, "abc");
+ assert_eq!(d.kind, Kind::Speaker);
+ }
+}
diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs
new file mode 100644
index 000000000..bbccc3807
--- /dev/null
+++ b/crates/cast/src/lib.rs
@@ -0,0 +1,11 @@
+//! Google Cast for Limusic: finding devices and talking to them.
+//!
+//! Speaks CastV2 directly to Google's Default Media Receiver: no Google SDK, no account, no key.
+//! Knows nothing about Tauri, YouTube or mpv; the app hands it URLs and metadata.
+
+pub mod channel;
+pub mod discovery;
+mod proto;
+
+pub use channel::{connect, Closed, Command, Event, Media, MediaStatus, Repeat, Sender, State};
+pub use discovery::{browse, Browser, CastDevice, DiscoveryEvent, Kind};
diff --git a/crates/cast/src/proto.rs b/crates/cast/src/proto.rs
new file mode 100644
index 000000000..fbb998d10
--- /dev/null
+++ b/crates/cast/src/proto.rs
@@ -0,0 +1,189 @@
+//! The CastV2 channel envelope.
+//!
+//! A CastV2 frame is a 4-byte big-endian length followed by a protobuf `CastMessage`
+//! (Chromium's `components/cast_channel/cast_channel.proto`):
+//!
+//! ```proto
+//! message CastMessage {
+//! enum ProtocolVersion { CASTV2_1_0 = 0; /* … */ }
+//! required ProtocolVersion protocol_version = 1;
+//! required string source_id = 2;
+//! required string destination_id = 3;
+//! required string namespace = 4;
+//! enum PayloadType { STRING = 0; BINARY = 1; }
+//! required PayloadType payload_type = 5;
+//! optional string payload_utf8 = 6;
+//! optional bytes payload_binary = 7;
+//! }
+//! ```
+//!
+//! Only the envelope is protobuf: every namespace used here carries JSON. So the protobuf is
+//! seven fields, of which three are read back; the rest are skipped by wire type.
+//!
+//! Ported from #717 (bosmak).
+
+/// The `STRING` payload type. Every message sent here is JSON.
+const PAYLOAD_TYPE_STRING: u64 = 0;
+
+/// Wire type 0: a varint.
+const WIRE_VARINT: u64 = 0;
+/// Wire type 2: length-delimited (strings, bytes, submessages).
+const WIRE_LEN: u64 = 2;
+
+/// The largest frame accepted from a device. Real ones are a few KB.
+pub const MAX_FRAME: usize = 1 << 20;
+
+/// A decoded frame: who sent it, the namespace it belongs to and its JSON payload.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Frame {
+ pub source: String,
+ pub namespace: String,
+ pub payload: String,
+}
+
+/// Frame one message: the length prefix, then the envelope.
+pub fn frame(namespace: &str, source: &str, destination: &str, payload: &str) -> Vec {
+ let mut body = Vec::with_capacity(payload.len() + namespace.len() + source.len() + 32);
+ put_varint_field(&mut body, 1, 0); // protocol_version: CASTV2_1_0
+ put_string_field(&mut body, 2, source);
+ put_string_field(&mut body, 3, destination);
+ put_string_field(&mut body, 4, namespace);
+ put_varint_field(&mut body, 5, PAYLOAD_TYPE_STRING);
+ put_string_field(&mut body, 6, payload);
+
+ let mut out = Vec::with_capacity(body.len() + 4);
+ out.extend_from_slice(&(body.len() as u32).to_be_bytes());
+ out.extend_from_slice(&body);
+ out
+}
+
+/// Read one frame body (without the length prefix) back.
+pub fn decode(body: &[u8]) -> Option {
+ let mut source = String::new();
+ let mut namespace = String::new();
+ let mut payload = String::new();
+ let mut at = 0usize;
+ while at < body.len() {
+ let (tag, next) = read_varint(body, at)?;
+ at = next;
+ let field = tag >> 3;
+ match tag & 0x7 {
+ WIRE_VARINT => at = read_varint(body, at)?.1,
+ WIRE_LEN => {
+ let (len, next) = read_varint(body, at)?;
+ let end = next.checked_add(len as usize)?;
+ let bytes = body.get(next..end)?;
+ let text = || String::from_utf8_lossy(bytes).into_owned();
+ match field {
+ 2 => source = text(),
+ 4 => namespace = text(),
+ 6 => payload = text(),
+ _ => {}
+ }
+ at = end;
+ }
+ // Fixed64 and fixed32: the envelope has neither, but a frame that can't be walked is
+ // a frame that is dropped.
+ 1 => at = at.checked_add(8)?,
+ 5 => at = at.checked_add(4)?,
+ _ => return None,
+ }
+ }
+ Some(Frame { source, namespace, payload })
+}
+
+fn put_tag(out: &mut Vec, field: u64, wire: u64) {
+ put_varint(out, (field << 3) | wire);
+}
+
+fn put_varint_field(out: &mut Vec, field: u64, value: u64) {
+ put_tag(out, field, WIRE_VARINT);
+ put_varint(out, value);
+}
+
+fn put_string_field(out: &mut Vec, field: u64, value: &str) {
+ put_tag(out, field, WIRE_LEN);
+ put_varint(out, value.len() as u64);
+ out.extend_from_slice(value.as_bytes());
+}
+
+fn put_varint(out: &mut Vec, mut value: u64) {
+ loop {
+ let byte = (value & 0x7f) as u8;
+ value >>= 7;
+ if value == 0 {
+ out.push(byte);
+ return;
+ }
+ out.push(byte | 0x80);
+ }
+}
+
+/// Read a varint, returning it and where it ended.
+fn read_varint(buf: &[u8], mut at: usize) -> Option<(u64, usize)> {
+ let mut value = 0u64;
+ let mut shift = 0u32;
+ loop {
+ let byte = *buf.get(at)?;
+ at += 1;
+ value |= ((byte & 0x7f) as u64) << shift;
+ if byte & 0x80 == 0 {
+ return Some((value, at));
+ }
+ shift += 7;
+ if shift > 63 {
+ return None;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_frame_round_trips() {
+ let body = frame(
+ "urn:x-cast:com.google.cast.media",
+ "sender-0",
+ "receiver-0",
+ r#"{"type":"LOAD"}"#,
+ );
+ assert_eq!(&body[..4], &(body.len() as u32 - 4).to_be_bytes());
+ let decoded = decode(&body[4..]).expect("decodes");
+ assert_eq!(decoded.source, "sender-0");
+ assert_eq!(decoded.namespace, "urn:x-cast:com.google.cast.media");
+ assert_eq!(decoded.payload, r#"{"type":"LOAD"}"#);
+ }
+
+ #[test]
+ fn varints_survive_the_boundaries() {
+ for value in [0u64, 1, 127, 128, 300, 16_383, 16_384, u32::MAX as u64] {
+ let mut buf = Vec::new();
+ put_varint(&mut buf, value);
+ let (read, at) = read_varint(&buf, 0).expect("reads back");
+ assert_eq!(read, value);
+ assert_eq!(at, buf.len());
+ }
+ }
+
+ #[test]
+ fn an_unknown_field_is_skipped_not_fatal() {
+ let mut body = Vec::new();
+ put_varint_field(&mut body, 1, 0);
+ put_string_field(&mut body, 4, "ns");
+ put_tag(&mut body, 7, WIRE_LEN);
+ put_varint(&mut body, 3);
+ body.extend_from_slice(&[1, 2, 3]);
+ put_string_field(&mut body, 6, "{}");
+ let decoded = decode(&body).expect("decodes");
+ assert_eq!(decoded.namespace, "ns");
+ assert_eq!(decoded.payload, "{}");
+ }
+
+ #[test]
+ fn a_truncated_frame_is_refused() {
+ let body = frame("ns", "s", "d", "{}");
+ assert!(decode(&body[4..body.len() - 2]).is_none());
+ }
+}
diff --git a/crates/cast/tests/fixtures/fake-receiver-cert.der b/crates/cast/tests/fixtures/fake-receiver-cert.der
new file mode 100644
index 000000000..66e4590a1
Binary files /dev/null and b/crates/cast/tests/fixtures/fake-receiver-cert.der differ
diff --git a/crates/cast/tests/fixtures/fake-receiver-key.der b/crates/cast/tests/fixtures/fake-receiver-key.der
new file mode 100644
index 000000000..b57f4f111
Binary files /dev/null and b/crates/cast/tests/fixtures/fake-receiver-key.der differ
diff --git a/docs/CASTING.md b/docs/CASTING.md
new file mode 100644
index 000000000..bd14e52cd
--- /dev/null
+++ b/docs/CASTING.md
@@ -0,0 +1,50 @@
+# Casting
+
+Limusic can play on a Chromecast, a Google Home or Nest speaker, a speaker group, or a TV with
+Google Cast built in. Open the device picker in the player bar (next to the queue button) and pick
+the device: the music moves there from where it is, and the bar, the media keys, the global
+hotkeys and the OS media controls now control the device. Pick "This computer" to bring it back.
+
+## How it works
+
+Limusic talks to the device directly over the local network, with no Google account and no app to
+install on it. The device runs Google's built-in Default Media Receiver, which shows the title, the
+artist and the cover. The device keeps time and plays the songs; Limusic keeps the queue and hands
+the device the next song before the current one ends, so they follow each other without a gap.
+
+The audio itself comes from this computer. YouTube's stream addresses only work for the address
+that asked for them, so the device fetches each song from Limusic, which fetches it from YouTube the
+same way it does for local playback. That is also why this computer has to stay awake and on the
+network while casting. Limusic keeps it from going to sleep while a cast is playing.
+
+Playing, pausing, skipping and changing the volume on the device itself (the Google Home app, a
+voice command, the device's buttons) all work, and Limusic follows along.
+
+## Troubleshooting
+
+- **No devices in the picker.** Your computer and the device have to be on the same network.
+ Guest networks and routers with "AP isolation" or "client isolation" turned on keep devices
+ from seeing each other. A VPN that routes all traffic can do the same.
+- **Windows asks about network access.** The first time the picker looks for devices, and the
+ first time you cast, Windows Defender Firewall asks whether Limusic may use the network. Allow
+ it. Windows marks new Wi-Fi networks as public, so if your home network is set to public, tick
+ that box too, or change the network to private in Settings > Network & internet. If you pressed
+ Cancel, open Windows Defender Firewall > Allow an app through firewall and allow Limusic there.
+- **macOS asks about the local network.** Allow it. You can change your answer later in System
+ Settings > Privacy & Security > Local Network.
+- **"couldn't get the music from Limusic".** The device can reach Limusic's controls but not the
+ audio: almost always a firewall on this computer, or a VPN between the two.
+- **Linux.** Fedora's default firewall allows it. If you turned on a firewall such as `ufw`,
+ allow incoming connections from your local network while casting.
+
+## Limitations
+
+- Local files, live broadcasts and karaoke play on this computer only. While casting, local files
+ and live broadcasts are skipped, and karaoke is switched off.
+- Music videos are not cast; the device plays the audio.
+- Tempo, pitch, reverb, the equalizer, crossfade and volume normalization are this computer's and
+ are hidden or skipped while casting.
+- Casting and Listen Together can't run at the same time.
+- With the Default Media Receiver, the Google Home app and Nest Hub screens show play, pause and
+ seek but no next or previous buttons. The device's notification on Android and voice commands
+ still skip.
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 4efa66789..f28f14f8f 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -48,6 +48,10 @@ http-body-util = "0.1"
innertube = { path = "../crates/innertube" }
player = { path = "../crates/player" }
karaoke = { path = "../crates/karaoke" }
+cast = { path = "../crates/cast" }
+# The cast LAN listener picks the interface on the device's network (audioproxy.rs). Already in
+# the tree through mdns-sd.
+if-addrs = "0.15"
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 }
@@ -101,6 +105,7 @@ windows = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Graphics_Gdi",
"Win32_System_Com",
+ "Win32_System_Power",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
diff --git a/src-tauri/Info.plist b/src-tauri/Info.plist
new file mode 100644
index 000000000..682da9114
--- /dev/null
+++ b/src-tauri/Info.plist
@@ -0,0 +1,14 @@
+
+
+
+
+
+ NSLocalNetworkUsageDescription
+ Limusic looks for Chromecast and Google Cast speakers on your network so it can play on them.
+ NSBonjourServices
+
+ _googlecast._tcp
+
+
+
diff --git a/src-tauri/src/audioproxy.rs b/src-tauri/src/audioproxy.rs
index e55baf04a..c7fbd5f55 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};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
@@ -89,6 +89,8 @@ struct Registration {
url: String,
headers: HashMap,
meta: Mutex