From 976185912f0dd4298b93cf5c0f665def1d0b2777 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 10:27:31 -0600 Subject: [PATCH 1/4] fix(cast): serve arriving bytes, one thread per request, close the receiver app on disconnect MediaServer gains a RangeSource entry whose bytes may still be arriving (known final size, blocking reads) and serves every request on its own thread so a slow media body no longer stalls the HEAD probe or a seek's second Range request. Chromecast: play/pause/stop never launch the Default Media Receiver (an app launched with nothing loaded sat IDLE and read as "track ended"); disconnect stops the receiver app instead of leaving it on screen with the last item. cc --- crates/qbz-cast/src/chromecast/device.rs | 16 +++++- crates/qbz-cast/src/lib.rs | 2 +- crates/qbz-cast/src/media_server.rs | 71 +++++++++++++++++++++--- 3 files changed, 79 insertions(+), 10 deletions(-) diff --git a/crates/qbz-cast/src/chromecast/device.rs b/crates/qbz-cast/src/chromecast/device.rs index 682cdb809..a2f32c64a 100644 --- a/crates/qbz-cast/src/chromecast/device.rs +++ b/crates/qbz-cast/src/chromecast/device.rs @@ -91,7 +91,14 @@ impl CastDeviceConnection { /// Disconnect from device pub fn disconnect(&mut self) -> Result<(), CastError> { + // CLOSE the media receiver app, not just our transport to it. A bare + // transport disconnect leaves the Default Media Receiver running on + // the device with our last item on its screen (and, if it was + // playing, still playing) — the "remote queue never clears" symptom. + // Tearing the app down is what the official senders do on "stop + // casting". if let Some(session) = &self.session { + let _ = self.device.receiver.stop_app(session.session_id.as_str()); let _ = self .device .connection @@ -285,8 +292,15 @@ impl CastDeviceConnection { self.launch_media_app().map(|_| ()) } + /// Transport commands NEVER launch the receiver app: `play`/`pause`/ + /// `stop` on a receiver with nothing loaded used to launch the Default + /// Media Receiver just to ask it for a media session it could not have, + /// which then sat there IDLE — and an IDLE report is what the poll reads + /// as "track ended". Only `load_media` launches the app. fn ensure_media_session(&mut self) -> Result<(String, i32), CastError> { - self.ensure_session()?; + if self.session.is_none() { + return Err(CastError::NoMediaSession); + } let destination = self .session diff --git a/crates/qbz-cast/src/lib.rs b/crates/qbz-cast/src/lib.rs index f13c8b52b..93108b008 100644 --- a/crates/qbz-cast/src/lib.rs +++ b/crates/qbz-cast/src/lib.rs @@ -22,7 +22,7 @@ pub mod media_server; pub use errors::{CastError, DlnaError}; // Re-export media server -pub use media_server::MediaServer; +pub use media_server::{MediaServer, RangeSource}; // Re-export Chromecast types pub use chromecast::{ diff --git a/crates/qbz-cast/src/media_server.rs b/crates/qbz-cast/src/media_server.rs index 059e24a66..bd3bb974b 100644 --- a/crates/qbz-cast/src/media_server.rs +++ b/crates/qbz-cast/src/media_server.rs @@ -53,6 +53,20 @@ enum MediaSource { // that is still being served (#550). Data(std::sync::Arc>), File(PathBuf), + /// Bytes that are still ARRIVING while they are served: a Qobuz track + /// being downloaded, or a Plex/Jellyfin/Subsonic stream proxied from its + /// server. The total size is known up front (advertised as + /// Content-Length); reads past the buffered edge block until the bytes + /// exist. This is what turns "download 100 MB, then play" into "play + /// after the first segment". + Reader(Arc), +} + +/// A range-addressable byte source whose bytes may still be arriving. +/// `open` returns a reader positioned at `start` that yields at most `len` +/// bytes and BLOCKS (never errors) while a requested byte is not there yet. +pub trait RangeSource: Send + Sync { + fn open(&self, start: u64, len: u64) -> std::io::Result>; } /// Simple HTTP server for audio streaming to cast devices @@ -112,14 +126,25 @@ impl MediaServer { while !shutdown_clone.load(Ordering::SeqCst) { match server.recv_timeout(Duration::from_millis(250)) { Ok(Some(request)) => { - let response = handle_request( - request.method(), - request.url(), - &request, - &entries_clone, - &token_clone, - ); - let _ = request.respond(response); + // ONE THREAD PER REQUEST. A media body is written at + // the renderer's pace (a 100 MB track takes the whole + // song to drain, and a progressive source blocks on + // bytes that have not arrived), so serving inline + // stalled every other request — the HEAD probe strict + // renderers send before Play, a second Range request + // for a seek — for the duration of the track. + let entries = entries_clone.clone(); + let token = token_clone.clone(); + thread::spawn(move || { + let response = handle_request( + request.method(), + request.url(), + &request, + &entries, + &token, + ); + let _ = request.respond(response); + }); } Ok(None) => {} Err(e) => { @@ -188,6 +213,29 @@ impl MediaServer { self.audio_path(id) } + /// Register a range-addressable source whose bytes may still be arriving + /// (see [`RangeSource`]). `size` is the FINAL byte length — it is what the + /// renderer is told in Content-Length, so it must be exact. + pub fn register_reader( + &mut self, + id: u64, + size: u64, + content_type: &str, + source: Arc, + ) -> String { + let entry = MediaEntry { + content_type: content_type.to_string(), + size, + source: MediaSource::Reader(source), + }; + if let Ok(mut entries) = self.entries.lock() { + // Same eviction rule as register_audio (#550). + entries.retain(|k, _| *k == id); + entries.insert(id, entry); + } + self.audio_path(id) + } + /// Register a local file to serve, inferring the content type from the /// extension via [`content_type_for_path`]. pub fn register_file(&mut self, id: u64, file_path: &str) -> Result { @@ -444,6 +492,13 @@ fn open_range( content_range, )) } + MediaSource::Reader(source) => { + let end = end.min(entry.size.saturating_sub(1)); + let start = start.min(end); + let length = end - start + 1; + let reader = source.open(start, length)?; + Ok((reader, length as usize, status_code, content_range)) + } } } From abc125bcfead46b5ae19aaaecf00daed407bcd65 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 10:27:31 -0600 Subject: [PATCH 2/4] feat(player): progressive external stream for cast renderers Player::open_external_stream starts the CMAF download and returns a shared buffer (exact final FLAC size known from the segment table) once the first segments are in, instead of after the whole file. The finished download is cached like a played stream. Core exposes it as open_external_stream_resolved. cc --- crates/qbz-core/src/core.rs | 17 +++++ crates/qbz-player/src/lib.rs | 3 +- crates/qbz-player/src/player/mod.rs | 105 ++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+), 1 deletion(-) diff --git a/crates/qbz-core/src/core.rs b/crates/qbz-core/src/core.rs index 1d925871f..f7b2337c7 100644 --- a/crates/qbz-core/src/core.rs +++ b/crates/qbz-core/src/core.rs @@ -868,6 +868,23 @@ impl QbzCore { self.player.fetch_for_gapless(client, track_id, quality).await } + /// Progressive counterpart of `fetch_for_external_stream_resolved` for a + /// track that is NOT already cached: the bytes are served to the renderer + /// while they download (see `Player::open_external_stream`). + pub async fn open_external_stream_resolved( + &self, + track_id: u64, + quality: Quality, + ) -> Result { + let guard = self.client.read().await; + let client = guard + .as_ref() + .ok_or_else(|| "No Qobuz client available".to_string())?; + self.player + .open_external_stream(client, track_id, quality) + .await + } + /// Queue a cold Qobuz successor from its initial CMAF buffer instead of /// materializing the whole file. Used only by the Streaming-only gapless /// handoff; cached and offline successors keep the byte path above. diff --git a/crates/qbz-player/src/lib.rs b/crates/qbz-player/src/lib.rs index b904fa269..98324b87e 100644 --- a/crates/qbz-player/src/lib.rs +++ b/crates/qbz-player/src/lib.rs @@ -37,7 +37,8 @@ pub mod queue; // Re-export main types pub use player::{ - BufferWriter, BufferedMediaSource, IncrementalStreamingSource, PlaybackEvent, PlaybackState, + BufferWriter, BufferedMediaSource, ExternalStreamHandle, IncrementalStreamingSource, + PlaybackEvent, PlaybackState, Player, SharedState, StreamingConfig, }; pub use queue::QueueManager; diff --git a/crates/qbz-player/src/player/mod.rs b/crates/qbz-player/src/player/mod.rs index 8aa890afb..502974cfd 100644 --- a/crates/qbz-player/src/player/mod.rs +++ b/crates/qbz-player/src/player/mod.rs @@ -1111,6 +1111,18 @@ fn try_init_stream_with_backend( } } +/// A Qobuz track being downloaded WHILE an external renderer reads it +/// (`Player::open_external_stream`). Sending `cancel` aborts the download; +/// the buffer is shared with the media server's range readers. +pub struct ExternalStreamHandle { + pub source: Arc, + /// Exact final FLAC byte length (Content-Length for the renderer). + pub total_bytes: u64, + pub sample_rate: Option, + pub bit_depth: Option, + pub cancel: tokio::sync::watch::Sender, +} + /// Event payload for playback state updates #[derive(Debug, Clone, serde::Serialize)] pub struct PlaybackEvent { @@ -5464,6 +5476,99 @@ impl Player { /// not known here (no metadata stored with the bytes) — the caller derives /// the quality label from the track's catalog metadata; the network path /// returns the precise resolved tier. + /// Open a Qobuz track as a PROGRESSIVE byte source for an external + /// renderer (Chromecast / DLNA): the CMAF download starts immediately, + /// the returned buffer exposes the bytes as they land, and the exact + /// final FLAC size is known up front (header + segment table) so the + /// media server can advertise a truthful Content-Length. Returns once the + /// initial buffer (first segments) is in, i.e. within ~0.3-1 s instead of + /// after the whole file (5-6 s for a 100 MB Hi-Res track on a fast line, + /// measured 2026-08-30). The finished download is cached like a played + /// stream, so a replay / re-cast is served from memory. + /// + /// Cached tracks should NOT come through here — `fetch_for_external_stream` + /// answers them from L1/L2 with no network at all. + pub async fn open_external_stream( + &self, + client: &QobuzClient, + track_id: u64, + quality: Quality, + ) -> Result { + let cmaf_info = qbz_qobuz::cmaf::setup_streaming(client, track_id, quality).await?; + let total_bytes = cmaf_info.flac_header.len() as u64 + + cmaf_info + .segment_table + .iter() + .map(|segment| segment.byte_len as u64) + .sum::(); + let (source, writer) = + BufferedMediaSource::new(StreamingConfig::fast_start(), Some(total_bytes)); + let source = Arc::new(source); + let (cancel_tx, cancel_rx) = tokio::sync::watch::channel(false); + + let url_template = cmaf_info.url_template; + let content_key = cmaf_info.content_key; + let flac_header = cmaf_info.flac_header; + let n_segments = cmaf_info.n_segments; + let cache = self.audio_cache.clone(); + tokio::spawn(async move { + match Self::cmaf_stream_segments( + &url_template, + n_segments, + content_key, + flac_header, + writer, + track_id, + cache, + false, + total_bytes, + cancel_rx, + ) + .await + { + Ok(true) => log::info!("[CAST-STREAM] Track {track_id} fully downloaded"), + Ok(false) => {} + Err(error) => log::warn!("[CAST-STREAM] Track {track_id} feeder failed: {error}"), + } + }); + + // Hand the source over only once the renderer's first read can be + // answered without stalling on the network (header + first segment). + const INITIAL_BUFFER_TIMEOUT: Duration = Duration::from_secs(8); + let waiter = Arc::clone(&source); + let ready = tokio::time::timeout( + INITIAL_BUFFER_TIMEOUT, + tokio::task::spawn_blocking(move || waiter.wait_for_initial_buffer()), + ) + .await; + match ready { + Ok(Ok(Ok(()))) => {} + Ok(Ok(Err(error))) => { + let _ = cancel_tx.send(true); + return Err(format!("cast stream download failed: {error}")); + } + Ok(Err(join)) => { + let _ = cancel_tx.send(true); + return Err(format!("cast stream waiter failed: {join}")); + } + Err(_) => { + let _ = cancel_tx.send(true); + return Err("cast stream initial buffer timed out".to_string()); + } + } + log::info!( + "[CAST-STREAM] Track {track_id} progressive source ready ({} B buffered of {total_bytes})", + source.buffer_size() + ); + Ok(ExternalStreamHandle { + source, + total_bytes, + sample_rate: cmaf_info.sampling_rate, + bit_depth: cmaf_info.bit_depth, + cancel: cancel_tx, + }) + } + pub async fn fetch_for_external_stream( &self, client: &QobuzClient, From 0451000bf0e230ee86db1732ebb96b6bf606f876 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 10:50:46 -0600 Subject: [PATCH 3/4] test(cast): cover the RangeSource media entry cc --- crates/qbz-cast/src/media_server.rs | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/qbz-cast/src/media_server.rs b/crates/qbz-cast/src/media_server.rs index bd3bb974b..0b250146f 100644 --- a/crates/qbz-cast/src/media_server.rs +++ b/crates/qbz-cast/src/media_server.rs @@ -700,6 +700,43 @@ mod tests { assert!(red.contains("***/9")); } + struct SliceSource(Vec); + impl RangeSource for SliceSource { + fn open(&self, start: u64, len: u64) -> std::io::Result> { + let start = start as usize; + let end = (start + len as usize).min(self.0.len()); + Ok(Box::new(std::io::Cursor::new(self.0[start..end].to_vec()))) + } + } + + #[test] + fn open_range_serves_a_range_source_with_exact_lengths() { + let data: Vec = (0..=255u8).collect(); + let entry = MediaEntry { + content_type: "audio/flac".into(), + size: data.len() as u64, + source: MediaSource::Reader(Arc::new(SliceSource(data.clone()))), + }; + // Whole resource. + let (mut r, len, code, cr) = open_range(&entry, None).unwrap(); + let mut got = Vec::new(); + r.read_to_end(&mut got).unwrap(); + assert_eq!((len, code.0, cr), (256, 200, None)); + assert_eq!(got, data); + // A middle range, then one that overshoots the end (clamped). + let (mut r, len, code, cr) = open_range(&entry, Some((10, 19))).unwrap(); + let mut got = Vec::new(); + r.read_to_end(&mut got).unwrap(); + assert_eq!((len, code.0), (10, 206)); + assert_eq!(cr.as_deref(), Some("bytes 10-19/256")); + assert_eq!(got, data[10..=19]); + let (mut r, len, _, _) = open_range(&entry, Some((250, 999))).unwrap(); + let mut got = Vec::new(); + r.read_to_end(&mut got).unwrap(); + assert_eq!(len, 6); + assert_eq!(got, data[250..]); + } + #[test] fn open_range_streams_file_and_ranges() { // A File entry serves the requested range straight from disk with the From 657bd9757d82ca4b54ecc8344589cadd86bb8e68 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 10:50:47 -0600 Subject: [PATCH 4/4] fix(qt): cast the clicked track, serve cold tracks progressively, proxy server-streamed sources, stop on exit Four findings from the 2026-08-30 casting smoke, each with its cause: - A Local Library click while casting played the OLD queue's current track on the renderer: that funnel stages its queue after the audible step, and the gate routed "the current track". route_play_remote_track hands the renderer the clicked track itself. - Plex/Jellyfin/Subsonic rows were refused ("serves it over the network"). The media server now proxies the source url with the ticket's request headers (exact size from the probe), closing the TODO the Slint service carried. - A cold Qobuz track waited for the whole download before the renderer heard anything (5.5 s for 97 MB; every frontend did this). Uncached tracks are served progressively from the player's download buffer; cached ones keep the instant byte path. The download is cancelled when the track changes, on disconnect and on shutdown. - Closing the app could leave the renderer playing: the poll held the service lock across renderer round trips and the 2 s bounded shutdown timed out before sending Stop. The poll handle now lives outside that lock and is aborted first. Chromecast: a toggle with nothing loaded casts the current track instead of asking an empty receiver to play, and IDLE counts as "ended" only after the track was seen PLAYING (an idle receiver app auto-advanced the whole queue). cc --- crates/qbz-qt/src/cast_qt.rs | 350 ++++++++++++++++++++++++---- crates/qbz-qt/src/local_playback.rs | 2 +- crates/qbz-qt/src/playback_qt.rs | 21 ++ 3 files changed, 326 insertions(+), 47 deletions(-) diff --git a/crates/qbz-qt/src/cast_qt.rs b/crates/qbz-qt/src/cast_qt.rs index d9c10804b..5d5dfc2a3 100644 --- a/crates/qbz-qt/src/cast_qt.rs +++ b/crates/qbz-qt/src/cast_qt.rs @@ -60,6 +60,7 @@ use qbz_cast::{ CastError, CastPositionInfo, ChromecastHandle, DeviceDiscovery, DiscoveredDevice, DiscoveredDlnaDevice, DlnaConnection, DlnaDiscovery, DlnaMetadata, DlnaPositionInfo, MediaMetadata, MediaServer, + RangeSource, }; use qbz_core::LoggingAdapter; use qbz_models::{probe_streaminfo, AssetOrigin, AudioParams, Quality, QualityLimit, QueueTrack}; @@ -189,8 +190,10 @@ struct CastInner { // QConnect coexistence (§11.4): whether QConnect was on before casting, // so `disconnect` restores exactly the sessions `connect` suspended. qconnect_was_on_before_cast: bool, - // Position-poll task; aborted on disconnect. - poll_task: Option>, + // Cancel handle of the progressive Qobuz download feeding the media + // server for the current cast track (None for cached / local / proxied + // tracks). Fired when the track changes, on disconnect and on shutdown. + stream_cancel: Option>, // Device-refresh task (2 s loop while the picker is open). discovery_task: Option>, } @@ -198,6 +201,13 @@ struct CastInner { pub(crate) struct CastService { inner: Arc>, runtime: Runtime, + // Position-poll task. OUTSIDE the async `inner` lock on purpose: the + // poll holds that lock across renderer round trips (a DLNA + // GetPositionInfo can take seconds), and `shutdown` on app exit is + // bounded to 2 s — when it queued behind the poll for the lock it timed + // out before sending Stop, and the renderer kept playing after the app + // was gone. Aborting the poll FIRST, without the lock, frees it. + poll_task: std::sync::Mutex>>, } impl CastService { @@ -205,6 +215,14 @@ impl CastService { Self { inner: Arc::new(Mutex::new(CastInner::default())), runtime, + poll_task: std::sync::Mutex::new(None), + } + } + + /// Abort the position poll synchronously (no lock on `inner` needed). + fn abort_poll(&self) { + if let Some(task) = self.poll_task.lock().ok().and_then(|mut p| p.take()) { + task.abort(); } } @@ -478,11 +496,16 @@ impl CastService { /// Disconnect: stop the renderer, drop the connection, restore the /// QConnect session connect() suspended (§11.4), reset state. pub(crate) async fn disconnect(&self) { + // Free the `inner` lock from the poll before anything below waits on it. + self.abort_poll(); // Stop the renderer first (disconnect alone leaves it playing). let _ = self.stop_renderer().await; - let (poll, was_on) = { + let was_on = { let mut inner = self.inner.lock().await; + if let Some(cancel) = inner.stream_cancel.take() { + let _ = cancel.send(true); + } if let Some(h) = inner.chromecast.take() { let _ = h.disconnect(); } @@ -503,11 +526,8 @@ impl CastService { inner.is_playing = false; inner.track_end_detected = false; inner.lost_polls = 0; - (inner.poll_task.take(), inner.qconnect_was_on_before_cast) + inner.qconnect_was_on_before_cast }; - if let Some(task) = poll { - task.abort(); - } // Restore the QConnect session connect() suspended (best-effort), // then reset the latch (cast_service.rs:435-438). if was_on { @@ -580,28 +600,26 @@ impl CastService { track.source.as_deref().unwrap_or("qobuz") }; + // The previous track's progressive download (if any) is dead weight + // from here on: the renderer is about to be handed a new URI. + if let Some(cancel) = self.inner.lock().await.stream_cancel.take() { + let _ = cancel.send(true); + } + // Resolve + register per source. The fetch happens OUTSIDE the lock. + // Qobuz has its own tiers (cache / progressive download); every + // other source goes through the registry's playback ticket: a file on + // disk is served from disk, a server-streamed item (Plex / Jellyfin / + // Subsonic) is PROXIED to the renderer with the source's own request + // contract — the media-server arm the Slint service left as a TODO. let info = match source { - "local" | "ephemeral" => { - let path = resolve_castable_path(track).await?; - self.register_local(track.id, &path).await? - } "qobuz" | "qobuz_download" => self.register_qobuz(track.id).await?, - "plex" => { - // TODO(cast-plex): needs a proxy that re-serves the resolved - // part bytes to the renderer. `PlaybackTicket::Stream` now - // hands over the url that proxy would read, so what is missing - // is the media-server arm, not the resolve. The Slint service - // carries the same TODO. - // - // Kept as an EARLY refusal on purpose: `resolve_castable_path` - // would refuse it too — structurally, for every remote source, - // including ones that have no arm here — but only after paying - // a network round trip to build a url it is about to throw - // away. - return Err("Plex casting is not yet supported".to_string()); - } - other => return Err(format!("Unsupported cast source: {other}")), + _ => match resolve_castable(track).await? { + Castable::File(path) => self.register_local(track.id, &path).await?, + Castable::Stream { url, headers } => { + self.register_proxy(track.id, url, headers).await? + } + }, }; let content_type = info.content_type.clone(); @@ -696,9 +714,48 @@ impl CastService { // track so a Settings or cap change applies to the very next one. let cap_key = self.inner.lock().await.connected_cap_key.clone(); let (quality, request_cause) = effective_cast_quality(cap_key.as_deref()); - let asset = self - .runtime - .core() + + // COLD track: serve it PROGRESSIVELY. The whole-file fetch below made + // a Hi-Res click wait for the entire download before the renderer + // heard anything (5.5 s for 97 MB measured 2026-08-30, on a fast + // line; every frontend before this one did the same). The + // progressive source answers the renderer after the first segments + // and the finished download lands in the cache like a played stream. + let core = self.runtime.core(); + if !core.player().is_track_cached(track_id) { + match core.open_external_stream_resolved(track_id, quality).await { + Ok(handle) => { + let head = handle.source.get_buffered_data().unwrap_or_default(); + let probe = probe_streaminfo(&head); + let content_type = "audio/flac".to_string(); + self.ensure_media_server().await?; + let source: Arc = + Arc::new(BufferedRangeSource(Arc::clone(&handle.source))); + { + let mut inner = self.inner.lock().await; + let server = inner.media_server.as_mut().ok_or("Media server gone")?; + server.register_reader(track_id, handle.total_bytes, &content_type, source); + inner.stream_cancel = Some(handle.cancel); + } + log::info!( + "[qbz-qt][Cast] qobuz track {track_id} served progressively ({} B)", + handle.total_bytes + ); + return Ok(CastAssetInfo { + content_type, + probe, + origin: Some(AssetOrigin::Network), + requested: Some(quality), + request_cause, + }); + } + Err(e) => log::warn!( + "[qbz-qt][Cast] progressive stream for {track_id} failed: {e}; falling back to a full fetch" + ), + } + } + + let asset = core // No offline tier / cache sink: `OfflineCacheState` is not wired // in the Qt port (see the module header). .fetch_for_external_stream_resolved(track_id, quality, None, None) @@ -751,6 +808,61 @@ impl CastService { }) } + /// Server-streamed sources (Plex / Jellyfin / Subsonic): probe the item + /// for its exact size + container, then PROXY it — the media server + /// answers the renderer's Range requests by fetching the same ranges + /// from the source with the ticket's request headers. The renderer + /// never sees the source url (it embeds credentials). + async fn register_proxy( + &self, + track_id: u64, + url: String, + headers: Vec<(String, String)>, + ) -> Result { + let info = qbz_player::remote_stream::probe_remote_stream_info_with_headers(&url, &headers) + .await + .map_err(|e| format!("Cannot probe track {track_id} for casting: {e}"))?; + if info.content_length == 0 { + return Err(format!( + "Track {track_id} cannot be cast: its server did not report a size" + )); + } + let content_type = match info.format { + "FLAC" => "audio/flac", + "MP3" => "audio/mpeg", + _ => "application/octet-stream", + } + .to_string(); + let probe = Some(AudioParams { + sample_rate: info.sample_rate, + bits_per_sample: info.bit_depth, + channels: info.channels, + }); + self.ensure_media_server().await?; + let source: Arc = Arc::new(HttpRangeSource { + url, + headers, + handle: tokio::runtime::Handle::current(), + }); + { + let mut inner = self.inner.lock().await; + let server = inner.media_server.as_mut().ok_or("Media server gone")?; + server.register_reader(track_id, info.content_length, &content_type, source); + } + log::info!( + "[qbz-qt][Cast] track {track_id} proxied from its server ({} B, {})", + info.content_length, + info.format + ); + Ok(CastAssetInfo { + content_type, + probe, + origin: None, + requested: None, + request_cause: QualityLimit::None, + }) + } + async fn ensure_media_server(&self) -> Result<(), String> { let mut inner = self.inner.lock().await; if inner.media_server.is_none() { @@ -766,14 +878,24 @@ impl CastService { // Ok(true) = handled. Call sites live on the playback path — see the // report's GLUE NEEDED for `playback_qt.rs`. - pub(crate) async fn toggle_play_if_cast(&self) -> Result { - let (proto, playing) = { + pub(crate) async fn toggle_play_if_cast(self: &Arc) -> Result { + let (proto, playing, loaded) = { let inner = self.inner.lock().await; match inner.protocol { - Some(p) => (p, inner.is_playing), + Some(p) => (p, inner.is_playing, inner.current_track_id.is_some()), None => return Ok(false), } }; + // Connected with nothing handed to the renderer yet (connected while + // paused, or the last cast failed): play means "cast the current + // track", not "resume a media session that does not exist". + if !loaded { + match self.runtime.core().current_track().await { + Some(track) => self.cast_track(&track).await?, + None => return Err("Nothing to play".to_string()), + } + return Ok(true); + } if playing { self.pause_renderer(proto).await?; } else { @@ -982,13 +1104,11 @@ impl CastService { svc.poll_once().await; } }); - let svc2 = self.clone(); - crate::spawn(async move { - let mut inner = svc2.inner.lock().await; - if let Some(old) = inner.poll_task.replace(task) { + if let Ok(mut slot) = self.poll_task.lock() { + if let Some(old) = slot.replace(task) { old.abort(); } - }); + } } async fn poll_once(self: &Arc) { @@ -1128,7 +1248,13 @@ impl CastService { } max_position = inner.cast_max_position; let ended = match proto { - CastProtocol::Chromecast => state == "IDLE" && !inner.track_end_detected, + // IDLE counts as "ended" only after this track was seen + // PLAYING: a receiver app that is idle because nothing was + // ever loaded (or the load failed) reported IDLE too, and the + // poll auto-advanced through the whole queue on it. + CastProtocol::Chromecast => { + state == "IDLE" && inner.cast_saw_playing && !inner.track_end_detected + } CastProtocol::Dlna => { let stopped = matches!(state.as_str(), "STOPPED" | "NO_MEDIA_PRESENT"); // The guard only makes sense when the position signal is @@ -1214,10 +1340,12 @@ impl CastService { /// and the media server, so a cast device does not keep playing after /// logout or exit (Tauri parity, #32/#33). pub(crate) async fn shutdown(&self) { + // Poll first, without the lock — see `poll_task`. + self.abort_poll(); let _ = self.stop_renderer().await; let mut inner = self.inner.lock().await; - if let Some(task) = inner.poll_task.take() { - task.abort(); + if let Some(cancel) = inner.stream_cancel.take() { + let _ = cancel.send(true); } if let Some(task) = inner.discovery_task.take() { task.abort(); @@ -1542,6 +1670,23 @@ pub(crate) async fn is_casting() -> bool { service().is_casting().await } +/// Route THIS track to the connected renderer instead of opening a local +/// stream. false = not casting, take the local path. Used by the funnels +/// that hold the track before the queue cursor moves (the Local Library +/// stages its queue AFTER the audible step succeeds) — routing "the current +/// track" there cast whatever the previous queue was pointing at. +pub(crate) async fn play_track_if_cast(track: &QueueTrack) -> bool { + let svc = service(); + if !svc.is_casting().await { + return false; + } + if let Err(e) = svc.cast_track(track).await { + log::warn!("[qbz-qt][Cast] play track {} failed: {e}", track.id); + set_error(e); + } + true +} + /// Route the queue's CURRENT track to the connected renderer instead of /// opening a local stream. Ok(false) = not casting, take the local path. pub(crate) async fn play_current_if_cast(runtime: &Runtime) -> bool { @@ -1727,7 +1872,18 @@ fn cap_index_for_key(cap_key: &str) -> i32 { /// need a proxy this service does not have. That is the `TODO(cast-plex)` /// arm's actual content, and it now applies to every remote source by /// construction instead of to the one word somebody thought to list. -async fn resolve_castable_path(track: &QueueTrack) -> Result { +/// What a non-Qobuz track resolves to for the renderer. +enum Castable { + /// A file on disk — served straight from disk. + File(String), + /// Served by a media server — proxied with the source's request contract. + Stream { + url: String, + headers: Vec<(String, String)>, + }, +} + +async fn resolve_castable(track: &QueueTrack) -> Result { let ticket = qbz_source::registry() .playback(track) .await @@ -1735,21 +1891,123 @@ async fn resolve_castable_path(track: &QueueTrack) -> Result { match ticket { qbz_source::PlaybackTicket::File { path, .. } | qbz_source::PlaybackTicket::DsdFile { path, .. } => { - Ok(path.to_string_lossy().into_owned()) + Ok(Castable::File(path.to_string_lossy().into_owned())) } + qbz_source::PlaybackTicket::Stream { + url, + request_headers, + .. + } => Ok(Castable::Stream { + url, + headers: request_headers, + }), other => Err(format!( - "Track {} cannot be cast: its source serves it over the network, not as a file ({})", + "Track {} cannot be cast: its source hands it over as {}", track.id, match other { - qbz_source::PlaybackTicket::Stream { .. } => "streamed", qbz_source::PlaybackTicket::Bytes { .. } => "fetched bytes", - qbz_source::PlaybackTicket::Catalog { .. } => "catalog", - _ => "unsupported", + qbz_source::PlaybackTicket::Catalog { .. } => "a catalog id", + _ => "an unsupported ticket", } )), } } +/// Media-server adapter over the player's progressive download buffer: +/// every request gets its own cursor; a read past the buffered edge blocks +/// until the segment lands (the download is far faster than playback). +struct BufferedRangeSource(Arc); + +impl RangeSource for BufferedRangeSource { + fn open(&self, start: u64, len: u64) -> std::io::Result> { + use std::io::{Read, Seek, SeekFrom}; + let mut reader = self.0.create_reader(); + reader.seek(SeekFrom::Start(start))?; + Ok(Box::new(reader.take(len))) + } +} + +/// Media-server adapter that re-fetches a range from a source server +/// (Plex / Jellyfin / Subsonic) with the ticket's headers. Runs on the media +/// server's own thread, so it drives the async client through the tokio +/// handle and pulls the body chunk by chunk as the renderer reads. +struct HttpRangeSource { + url: String, + headers: Vec<(String, String)>, + handle: tokio::runtime::Handle, +} + +static PROXY_HTTP: OnceLock = OnceLock::new(); + +impl RangeSource for HttpRangeSource { + fn open(&self, start: u64, len: u64) -> std::io::Result> { + let end = start + len - 1; + let client = PROXY_HTTP.get_or_init(|| { + reqwest::Client::builder() + .connect_timeout(std::time::Duration::from_secs(10)) + .build() + .unwrap_or_default() + }); + let mut request = client + .get(&self.url) + .header("User-Agent", "Mozilla/5.0") + .header("Accept-Encoding", "identity") + .header("Range", format!("bytes={start}-{end}")); + for (name, value) in &self.headers { + request = request.header(name.as_str(), value.as_str()); + } + let response = self + .handle + .block_on(request.send()) + .map_err(|e| std::io::Error::other(e.to_string()))?; + if !response.status().is_success() { + return Err(std::io::Error::other(format!( + "source answered {} to a range request", + response.status() + ))); + } + struct BodyReader { + handle: tokio::runtime::Handle, + response: reqwest::Response, + pending: Vec, + offset: usize, + remaining: u64, + } + impl std::io::Read for BodyReader { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.remaining == 0 { + return Ok(0); + } + while self.offset >= self.pending.len() { + match self.handle.block_on(self.response.chunk()) { + Ok(Some(chunk)) => { + self.pending = chunk.to_vec(); + self.offset = 0; + } + Ok(None) => return Ok(0), + Err(e) => return Err(std::io::Error::other(e.to_string())), + } + } + let n = buf + .len() + .min(self.pending.len() - self.offset) + .min(self.remaining as usize); + buf[..n].copy_from_slice(&self.pending[self.offset..self.offset + n]); + self.offset += n; + self.remaining -= n as u64; + Ok(n) + } + } + Ok(Box::new(BodyReader { + handle: self.handle.clone(), + response, + pending: Vec::new(), + offset: 0, + remaining: len, + })) + } +} + /// Content type for a local file by extension (for the UI label; the SERVED /// MIME is set by the crate's own map in `register_file`). fn content_type_for_local(path: &str) -> String { diff --git a/crates/qbz-qt/src/local_playback.rs b/crates/qbz-qt/src/local_playback.rs index b692cde90..f6abd1864 100644 --- a/crates/qbz-qt/src/local_playback.rs +++ b/crates/qbz-qt/src/local_playback.rs @@ -392,7 +392,7 @@ pub(crate) async fn play_audible(runtime: &Runtime, track: &QueueTrack) -> bool // A connected renderer owns playback — the same gate every Qobuz entry // passes (`route_play_remote`). Cheap when nothing is connected; without // it a Local Library row played beside a DLNA renderer. - if crate::playback_qt::route_play_remote(runtime, track.id, "play_audible").await { + if crate::playback_qt::route_play_remote_track(runtime, track, "play_audible").await { return true; } if belongs_to_the_offline_tier(track) { diff --git a/crates/qbz-qt/src/playback_qt.rs b/crates/qbz-qt/src/playback_qt.rs index af7b84a66..ed3223ba8 100644 --- a/crates/qbz-qt/src/playback_qt.rs +++ b/crates/qbz-qt/src/playback_qt.rs @@ -1067,6 +1067,27 @@ pub(crate) async fn route_play_remote( false } +/// `route_play_remote` for a funnel that holds the TRACK before the queue +/// cursor moves (the Local Library stages its queue after the audible step): +/// the renderer gets this track, not whatever the old queue pointed at. +pub(crate) async fn route_play_remote_track( + runtime: &Arc>, + track: &QueueTrack, + entry: &'static str, +) -> bool { + if crate::cast_qt::play_track_if_cast(track).await { + log::info!("[play] entry={entry} track={} -> cast renderer", track.id); + crate::now_playing::clear_loading(); + return true; + } + if route_play_to_peer(runtime, track.id).await { + log::info!("[play] entry={entry} track={} -> qconnect peer", track.id); + return true; + } + log::debug!("[play] entry={entry} track={} -> local", track.id); + false +} + async fn route_play_to_peer( runtime: &Arc>, track_id: u64,