diff --git a/README.md b/README.md index c46b06d..bdcbd5e 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,8 @@ There is no telemetry. refryt connects to YouTube, [LRCLIB](https://lrclib.net) The project is before 1.0 and changes quickly. Only the Linux builds see daily use; the Windows builds are cross-compiled with limited testing on real hardware, and the macOS build has been tested by hand. Podcasts are not supported. A change to YouTube's internal API can break playback or a page until a fix is released. +If an assigned YouTube stream host is unreachable, refryt retries alternate nodes listed in the stream URL. + Bugs go to the [issue tracker](https://github.com/gridoe/refryt/issues); [CONTRIBUTING.md](CONTRIBUTING.md) says what to include. ## Build from source diff --git a/crates/refryt-resolve/src/guest.rs b/crates/refryt-resolve/src/guest.rs index bca7692..d0763a1 100644 --- a/crates/refryt-resolve/src/guest.rs +++ b/crates/refryt-resolve/src/guest.rs @@ -68,7 +68,7 @@ pub struct GuestResolver { visitor: Mutex>, visitor_file: Option, quality: Mutex, - /// Ask the stream for its first byte before handing it on; see [`Self::probe`]. + /// Ask the stream for its first byte before handing it on; see [`crate::probe_first_byte`]. probe: bool, } @@ -128,26 +128,6 @@ impl GuestResolver { } } - /// Ask the stream for its first byte, as the proxy will ask for its ranges. The media server - /// now and then refuses a URL `player` has just handed out; found here, the chain still - /// falls through to yt-dlp, where found in mpv the song would simply fail. The connection it - /// opens is the one the proxy's first range then reuses, as for the `player` request. - async fn probe(&self, url: &Url) -> Result<()> { - let response = self - .http - .get(url.as_str()) - .header("Range", "bytes=0-0") - .header("User-Agent", GUEST_USER_AGENT) - .timeout(Duration::from_secs(10)) - .send() - .await - .context("the stream did not answer")?; - match response.status().as_u16() { - 200 | 206 => Ok(()), - status => bail!("the stream answered {status}"), - } - } - async fn player(&self, id: &VideoId, visitor: Option<&str>) -> Result { let mut request = self .http @@ -213,10 +193,17 @@ impl StreamResolver for GuestResolver { ); } let quality = self.quality.lock().map(|q| *q).unwrap_or_default(); - let stream = + let mut stream = pick(&response, quality).with_context(|| format!("no direct audio stream for {id}"))?; if self.probe { - self.probe(&stream.url) + // The media server now and then hands out a URL its own host will not serve, or + // on a node this machine cannot reach; found here, the chain still falls through + // to yt-dlp, where found in mpv the song would simply fail. A dead node is + // healed in place by the mirror failover inside the probe — not a resolver + // failure, so the breaker must not hear of it when a mirror answers. The + // connection the probe opens is the one the proxy's first range then reuses, as + // for the `player` request. + crate::probe_first_byte(&self.http, &mut stream.url) .await .with_context(|| format!("guest stream for {id}"))?; } diff --git a/crates/refryt-resolve/src/lib.rs b/crates/refryt-resolve/src/lib.rs index 154ff3a..a5d4fd9 100644 --- a/crates/refryt-resolve/src/lib.rs +++ b/crates/refryt-resolve/src/lib.rs @@ -257,10 +257,301 @@ pub async fn probe_throughput(stream: &AudioStream, want_bytes: u64) -> Result<( Ok((total, started.elapsed())) } +/// The mirror nodes a googlevideo URL offers instead of the one its host points at, in the +/// order `mn=` lists them. The node the host is on is the list's first entry — `mvi` is the +/// `rrN` host index, *not* a position in this list (measured 2026-11-16: a URL on +/// `rr1---sn-8pxuuxahv1-h2hz` with `mvi=1` and `mn=sn-8pxuuxahv1-h2hz,sn-8xgp1vo-ab5s`) — +/// so the mirrors are the entries the host's own node does not name. Empty when the URL +/// names no mirrors: localhost test servers, non-googlevideo hosts, a list of one. +fn mn_mirrors(url: &Url) -> Vec { + let Some(nodes) = url.query_pairs().find(|(k, _)| k == "mn").map(|(_, v)| v) else { + return Vec::new(); + }; + let on = url + .host_str() + .unwrap_or_default() + .split_once("---") + .map(|(_, node)| node.trim_end_matches(".googlevideo.com")); + nodes + .split(',') + .map(str::to_owned) + .filter(|node| Some(node.as_str()) != on) + .collect() +} + +/// Rebuild a googlevideo URL on `node`, one of the cache nodes its `mn=` names: same path, +/// query and `rrN` prefix, with only the node between the host's dashes swapped. The +/// signature travels in the query and is not tied to the host, so nothing else changes. +/// `None` when the host is not the `rrN---.googlevideo.com` shape. +fn mirror_url(url: &Url, node: &str) -> Option { + let host = url.host_str()?; + if !host.ends_with(".googlevideo.com") { + return None; + } + let (prefix, _) = host.split_once("---")?; + let mut mirrored = url.clone(); + mirrored + .set_host(Some(&format!("{prefix}---{node}.googlevideo.com"))) + .ok()?; + Some(mirrored) +} + +/// Ask a stream host for its first byte, and fail over to a mirror node when it will not +/// take the connection. +/// +/// YouTube's cache picker now and then assigns a node a client cannot reach at all — the +/// TCP connection neither answers nor refuses, for tens of seconds (measured 2026-11-16: +/// both `player` and yt-dlp kept handing out URLs on a node that did this from one +/// address). The URL itself names the nodes YouTube had in mind, so the fix needs no +/// second resolve: see [`mn_mirrors`] and [`mirror_url`]. The probe walks that list and +/// rewrites `url` in place onto the first node that answers, which the caller then plays; +/// the connection it opens is pooled in `http`, so the stream's first real range reuses it. +/// A host that *answers* is another matter — a 403 or 410 is the URL expiring, which no +/// node fixes — so an HTTP status is an error, never a failover. +pub async fn probe_first_byte(http: &reqwest::Client, url: &mut Url) -> Result<()> { + let get = |url: &Url| { + http.get(url.as_str()) + .header("Range", "bytes=0-0") + .header("User-Agent", guest::GUEST_USER_AGENT) + // Short, so a dead node costs seconds: the mirrors are tried while the caller + // is still waiting for a URL worth playing. + .timeout(Duration::from_secs(5)) + .send() + }; + let response = match get(url).await { + Ok(response) => response, + Err(lost) => { + for node in mn_mirrors(url) { + let Some(mirrored) = mirror_url(url, &node) else { + continue; + }; + match get(&mirrored).await { + Ok(answered) if matches!(answered.status().as_u16(), 200 | 206) => { + tracing::info!( + host = mirrored.host_str().unwrap_or_default(), + "stream host unreachable; playing from a mirror" + ); + *url = mirrored; + return Ok(()); + } + // A mirror that refuses the URL or will not answer is no better than + // the node we came from; try the next. + Ok(_) | Err(_) => continue, + } + } + return Err(lost).context("the stream did not answer"); + } + }; + match response.status().as_u16() { + 200 | 206 => Ok(()), + status => bail!("the stream answered {status}"), + } +} + #[cfg(test)] mod tests { use super::*; + /// Local upstreams keep googlevideo hostnames without changing process-wide DNS or proxies. + pub(crate) mod mirror_fixture { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use url::Url; + + pub(crate) const PRIMARY: &str = "rr1---sn-primary.googlevideo.com"; + pub(crate) const FAILED: &str = "rr1---sn-failed.googlevideo.com"; + pub(crate) const REFUSED: &str = "rr1---sn-refused.googlevideo.com"; + pub(crate) const LIVE: &str = "rr1---sn-live.googlevideo.com"; + pub(crate) const FRESH: &str = "rr1---sn-fresh.googlevideo.com"; + + #[derive(Debug)] + pub(crate) struct Request { + pub(crate) host: String, + pub(crate) target: String, + } + + pub(crate) struct MirrorHost { + addr: std::net::SocketAddr, + pub(crate) http: reqwest::Client, + held: Arc>>, + stop: Option>, + task: tokio::task::JoinHandle>, + } + + impl MirrorHost { + /// `None` closes after reading the request, before sending any HTTP response. + pub(crate) async fn start( + routes: &[(&'static str, Option)], + data: Arc>, + ) -> Self { + Self::start_inner(routes, data, false).await + } + + /// Keep primary sockets open without headers while serving the live mirror normally. + pub(crate) async fn start_hanging_primary(data: Arc>) -> Self { + Self::start_inner(&[(PRIMARY, None), (LIVE, Some(206))], data, true).await + } + + async fn start_inner( + routes: &[(&'static str, Option)], + data: Arc>, + hold_primary: bool, + ) -> Self { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let mut client = reqwest::Client::builder().no_proxy(); + for (host, _) in routes { + client = client.resolve(host, addr); + } + let http = client.build().unwrap(); + let routes: HashMap<_, _> = routes.iter().copied().collect(); + let (stop, mut stopped) = tokio::sync::oneshot::channel(); + let held = Arc::new(Mutex::new(Vec::new())); + let held_by_task = Arc::clone(&held); + let task = tokio::spawn(async move { + let mut seen = Vec::new(); + loop { + let (mut socket, _) = tokio::select! { + _ = &mut stopped => break, + accepted = listener.accept() => accepted.unwrap(), + }; + let mut bytes = Vec::new(); + let mut buf = [0u8; 1024]; + while !bytes.windows(4).any(|w| w == b"\r\n\r\n") { + let n = socket.read(&mut buf).await.unwrap(); + assert_ne!(n, 0, "upstream request ended before its headers"); + bytes.extend_from_slice(&buf[..n]); + assert!(bytes.len() <= 16 * 1024, "upstream headers too large"); + } + let text = String::from_utf8(bytes).unwrap(); + let header = |name: &str| { + text.lines() + .find_map(|line| { + let (key, value) = line.split_once(':')?; + key.eq_ignore_ascii_case(name) + .then(|| value.trim().to_owned()) + }) + .unwrap() + }; + let host = header("host").split(':').next().unwrap().to_owned(); + let range = header("range"); + let target = text.split_whitespace().nth(1).unwrap().to_owned(); + let status = *routes.get(host.as_str()).expect("unexpected upstream host"); + let hold = hold_primary && host == PRIMARY; + seen.push(Request { host, target }); + if hold { + // Do not await this socket: mirrors must be accepted while it hangs. + held_by_task.lock().unwrap().push(socket); + continue; + } + let Some(status) = status else { + continue; + }; + let body = if status == 206 { + let (start, end) = range + .strip_prefix("bytes=") + .unwrap() + .split_once('-') + .unwrap(); + &data[start.parse::().unwrap()..=end.parse::().unwrap()] + } else { + &[][..] + }; + let mut reply = format!( + "HTTP/1.1 {status} Test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ).into_bytes(); + reply.extend_from_slice(body); + socket.write_all(&reply).await.unwrap(); + } + seen + }); + Self { + addr, + http, + held, + stop: Some(stop), + task, + } + } + + pub(crate) fn url(&self, host: &str, query: &str) -> Url { + Url::parse(&format!( + "http://{host}:{}/videoplayback?{query}", + self.addr.port() + )) + .unwrap() + } + + pub(crate) fn held_connections(&self) -> usize { + self.held.lock().unwrap().len() + } + + pub(crate) async fn finish(mut self) -> Vec { + self.stop.take().unwrap().send(()).unwrap(); + (&mut self.task).await.unwrap() + } + } + + impl Drop for MirrorHost { + fn drop(&mut self) { + // Also clean up when a test panics or its outer timeout cancels finish(). + self.task.abort(); + self.held.lock().unwrap().clear(); + } + } + } + + #[tokio::test] + async fn probe_recovers_on_a_live_mirror_without_changing_the_signed_query() { + use mirror_fixture::{LIVE, MirrorHost, PRIMARY, REFUSED}; + tokio::time::timeout(Duration::from_secs(10), async { + let host = MirrorHost::start( + &[(PRIMARY, None), (REFUSED, Some(403)), (LIVE, Some(206))], + std::sync::Arc::new(vec![42]), + ).await; + let query = "itag=251&mn=sn-primary%2Csn-refused%2Csn-live&mvi=1&sig=A%2fb%2BC%3D&n=a+b&dup=1&dup=2"; + let mut url = host.url(PRIMARY, query); + probe_first_byte(&host.http, &mut url).await.unwrap(); + assert_eq!(url, host.url(LIVE, query)); + + let seen = host.finish().await; + assert_eq!( + seen.iter().map(|r| r.host.as_str()).collect::>(), + [PRIMARY, REFUSED, LIVE] + ); + for request in seen { + assert_eq!(request.target, format!("/videoplayback?{query}")); + } + }).await.expect("mirror probe did not finish"); + } + + #[tokio::test] + async fn probe_does_not_hide_primary_expiry_by_trying_a_mirror() { + use mirror_fixture::{LIVE, MirrorHost, PRIMARY}; + tokio::time::timeout(Duration::from_secs(10), async { + for status in [403, 410] { + let host = MirrorHost::start( + &[(PRIMARY, Some(status)), (LIVE, Some(206))], + std::sync::Arc::new(vec![42]), + ) + .await; + let original = host.url(PRIMARY, "mn=sn-primary,sn-live&sig=expired"); + let mut url = original.clone(); + let error = probe_first_byte(&host.http, &mut url).await.unwrap_err(); + assert!(error.to_string().contains(&status.to_string()), "{error:#}"); + assert_eq!(url, original); + let seen = host.finish().await; + assert_eq!(seen.len(), 1, "{seen:?}"); + assert_eq!(seen[0].host, PRIMARY); + } + }) + .await + .expect("expiry probe did not finish"); + } + #[test] fn video_id_validates() { assert!(VideoId::new("dQw4w9WgXcQ").is_ok()); @@ -269,6 +560,36 @@ mod tests { assert!(VideoId::new("waytoolongvideoid").is_err()); } + /// A mirror is the same URL on the next node in `mn=` — host rebuilt, everything else + /// (path, query, signature) intact — and a URL with no `mn=` has no mirror to rebuild on. + #[test] + fn a_mirror_is_the_same_url_on_the_next_node() { + let primary = Url::parse( + "https://rr1---sn-8pxuuxahv1-h2hz.googlevideo.com/videoplayback?\ + itag=251&mn=sn-8pxuuxahv1-h2hz,sn-8xgp1vo-ab56&mvi=0&sig=ABCD", + ) + .unwrap(); + let mirrored = mirror_url(&primary, "sn-8xgp1vo-ab56").unwrap(); + assert_eq!( + mirrored.host_str(), + Some("rr1---sn-8xgp1vo-ab56.googlevideo.com") + ); + assert_eq!(mirrored.path(), "/videoplayback"); + assert_eq!(mirrored.query(), primary.query()); + assert_eq!(mn_mirrors(&primary), vec!["sn-8xgp1vo-ab56".to_owned()]); + // A URL already playing from the second node mirrors back to the first, whichever + // way `mvi` points. + let on_second = mirror_url(&primary, "sn-8xgp1vo-ab56").unwrap(); + assert_eq!( + mn_mirrors(&on_second), + vec!["sn-8pxuuxahv1-h2hz".to_owned()] + ); + + let plain = Url::parse("https://rr1.googlevideo.com/videoplayback?itag=251").unwrap(); + assert_eq!(mn_mirrors(&plain), Vec::::new()); + assert!(mirror_url(&plain, "sn-8xgp1vo-ab56").is_none()); + } + #[test] fn opus_outranks_aac_even_at_lower_bitrate() { assert!(score(Codec::Opus, 128) > score(Codec::Aac, 128)); diff --git a/crates/refryt-resolve/src/proxy.rs b/crates/refryt-resolve/src/proxy.rs index f1b4aeb..97d6191 100644 --- a/crates/refryt-resolve/src/proxy.rs +++ b/crates/refryt-resolve/src/proxy.rs @@ -414,8 +414,11 @@ impl StreamProxy { } } -/// One upstream range. A refusal that means the URL has lapsed re-resolves the video and tries -/// the same range once more. +/// One upstream range. A refusal that means the URL has lapsed re-resolves the video and +/// tries the same range once more; a host that will not take the connection at all is +/// failover, not expiry, so the range is retried on the next node in `mn=` and the entry +/// kept on the one that answers — the remaining ranges then reuse that host without paying +/// for the dead node again. async fn fetch_range( http: &reqwest::Client, refresh: &Refresh, @@ -423,15 +426,55 @@ async fn fetch_range( start: u64, end: u64, ) -> Result> { - let get = |url: Url| { - http.get(url) - .header("Range", format!("bytes={start}-{end}")) - .header("User-Agent", GUEST_USER_AGENT) - .header("Accept-Encoding", "identity") - .send() + // Bound each attempt through response headers, including DNS/TCP/TLS and pooled + // connections. Leave body reads unbounded: a healthy 1 MiB range can take over 5 s. + let get = |url: Url| async move { + Ok::<_, anyhow::Error>( + tokio::time::timeout( + std::time::Duration::from_secs(5), + http.get(url) + .header("Range", format!("bytes={start}-{end}")) + .header("User-Agent", GUEST_USER_AGENT) + .header("Accept-Encoding", "identity") + .send(), + ) + .await + .context("the stream host did not answer within 5 seconds")??, + ) }; let url = entry.url.lock().unwrap().clone(); - let mut response = get(url).await.context("cannot reach the stream host")?; + let mut response = match get(url.clone()).await { + Ok(response) => response, + Err(e) => { + // Transport failures and the header deadline try mirrors; HTTP refusals are + // handled below. + let mut reached = Err(e); + for node in crate::mn_mirrors(&url) { + let Some(mirrored) = crate::mirror_url(&url, &node) else { + continue; + }; + // A mirror that answers 5xx is no better than the dead node; 403/410 stay + // usable so the expiry path below still re-resolves. + if let Ok(answered) = get(mirrored.clone()).await + && (answered.status().is_success() + || matches!(answered.status().as_u16(), 403 | 410)) + { + tracing::info!( + id = %entry.id, + host = mirrored.host_str().unwrap_or_default(), + "stream proxy: host unreachable; reading from a mirror" + ); + *entry.url.lock().unwrap() = mirrored; + reached = Ok(answered); + break; + } + } + match reached { + Ok(response) => response, + Err(lost) => return Err(lost).context("cannot reach the stream host"), + } + } + }; if matches!(response.status().as_u16(), 403 | 410) { tracing::info!(id = %entry.id, status = %response.status(), "stream proxy: URL lapsed; resolving again"); let fresh = refresh(entry.id.clone()).await?; @@ -737,6 +780,176 @@ mod tests { assert!(paths[1..].iter().all(|p| p == "/fresh"), "{paths:?}"); } + #[tokio::test] + async fn proxy_skips_broken_mirrors_and_keeps_the_working_mirror_for_later_ranges() { + use crate::tests::mirror_fixture::{FAILED, LIVE, MirrorHost, PRIMARY, REFUSED}; + use std::time::Duration; + + tokio::time::timeout(Duration::from_secs(10), async { + let body = data(300_000); + let host = MirrorHost::start( + &[ + (PRIMARY, None), + (FAILED, None), + (REFUSED, Some(503)), + (LIVE, Some(206)), + ], + Arc::clone(&body), + ) + .await; + let http = host.http.clone(); + let proxy = StreamProxy::start( + &tokio::runtime::Handle::current(), + http.clone(), + no_refresh(), + ) + .unwrap(); + let upstream = host.url( + PRIMARY, + "mn=sn-primary,sn-failed,sn-refused,sn-live&sig=A%2Fb%2BC", + ); + let url = proxy + .url_for(&id(), &stream(upstream.as_str(), body.len())) + .unwrap(); + + // The first seek spans several upstream reads; the second is a new player request. + for (start, end) in [(17_001, 180_019), (210_013, 220_091)] { + let response = http + .get(url.clone()) + .header("Range", format!("bytes={start}-{end}")) + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), 206); + assert_eq!( + response.headers()["content-range"].to_str().unwrap(), + format!("bytes {start}-{end}/{}", body.len()) + ); + assert_eq!(response.bytes().await.unwrap().as_ref(), &body[start..=end]); + } + + let seen = host.finish().await; + let hosts: Vec<_> = seen.iter().map(|r| r.host.as_str()).collect(); + assert!(hosts.starts_with(&[PRIMARY, FAILED, REFUSED]), "{hosts:?}"); + assert!(hosts.len() > 3, "{hosts:?}"); + assert!(hosts[3..].iter().all(|host| *host == LIVE), "{hosts:?}"); + }) + .await + .expect("proxy mirror recovery did not finish"); + } + + /// Missing response headers must reach the mirror deadline, not a fixture-generated EOF. + #[tokio::test] + async fn proxy_recovers_when_the_primary_keeps_the_connection_open_without_headers() { + use crate::tests::mirror_fixture::{LIVE, MirrorHost, PRIMARY}; + use std::time::Duration; + + tokio::time::timeout(Duration::from_secs(15), async { + let body = data(200_000); + let host = MirrorHost::start_hanging_primary(Arc::clone(&body)).await; + let proxy = StreamProxy::start( + &tokio::runtime::Handle::current(), + host.http.clone(), + no_refresh(), + ) + .unwrap(); + let upstream = host.url(PRIMARY, "mn=sn-primary,sn-live&sig=held-open"); + let url = proxy + .url_for(&id(), &stream(upstream.as_str(), body.len())) + .unwrap(); + + let response = host + .http + .get(url) + .header("Range", "bytes=12345-16321") + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), 206); + assert_eq!( + response.bytes().await.unwrap().as_ref(), + &body[12_345..=16_321] + ); + assert_eq!( + host.held_connections(), + 1, + "the primary socket must stay open until explicit teardown" + ); + + let seen = host.finish().await; + assert_eq!( + seen.iter().map(|r| r.host.as_str()).collect::>(), + [PRIMARY, LIVE] + ); + }) + .await + .expect("proxy did not recover from missing primary headers"); + } + + #[tokio::test] + async fn an_expired_mirror_refreshes_once_and_retries_the_players_exact_range() { + use crate::tests::mirror_fixture::{FRESH, LIVE, MirrorHost, PRIMARY, REFUSED}; + use std::time::Duration; + + tokio::time::timeout(Duration::from_secs(10), async { + for status in [403, 410] { + let body = data(200_000); + let host = MirrorHost::start( + &[ + (PRIMARY, None), + (REFUSED, Some(status)), + (LIVE, Some(206)), + (FRESH, Some(206)), + ], + Arc::clone(&body), + ) + .await; + let refreshed = Arc::new(AtomicUsize::new(0)); + let calls = Arc::clone(&refreshed); + let fresh = host.url(FRESH, "sig=fresh").to_string(); + let length = body.len(); + let refresh: Refresh = Arc::new(move |_| { + calls.fetch_add(1, Ordering::SeqCst); + let fresh = fresh.clone(); + Box::pin(async move { Ok(stream(&fresh, length)) }) + }); + let http = host.http.clone(); + let proxy = + StreamProxy::start(&tokio::runtime::Handle::current(), http.clone(), refresh) + .unwrap(); + let upstream = host.url(PRIMARY, "mn=sn-primary,sn-refused,sn-live&sig=expired"); + let url = proxy + .url_for(&id(), &stream(upstream.as_str(), length)) + .unwrap(); + + let response = http + .get(url) + .header("Range", "bytes=12345-16321") + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), 206); + assert_eq!( + response.bytes().await.unwrap().as_ref(), + &body[12_345..=16_321] + ); + assert_eq!( + refreshed.load(Ordering::SeqCst), + 1, + "mirror status {status}" + ); + let seen = host.finish().await; + assert_eq!( + seen.iter().map(|r| r.host.as_str()).collect::>(), + [PRIMARY, REFUSED, FRESH], + "mirror status {status}" + ); + } + }) + .await + .expect("mirror expiry refresh did not finish"); + } + fn spans(list: &[(u64, u64)]) -> Vec<(u64, u64)> { let mut spans = Vec::new(); for &(s, e) in list { diff --git a/crates/refryt/src/backend.rs b/crates/refryt/src/backend.rs index 66e6489..6ba474f 100644 --- a/crates/refryt/src/backend.rs +++ b/crates/refryt/src/backend.rs @@ -1003,7 +1003,9 @@ impl Backend { let api = Arc::new(Api::new()?); // One pool for the guest `player` requests and the stream ranges after them, kept warm // between tracks: a new connection to the stream host costs ~1.3 s before the first byte, - // a pooled one ~0.7 s for a whole MiB (measured 2026-09-23). + // a pooled one ~0.7 s for a whole MiB (measured 2026-09-23). Media deadlines live in + // the first-byte probe and proxy sends, leaving guest player requests their own + // request allowance. let stream_http = reqwest::Client::builder() .pool_idle_timeout(std::time::Duration::from_secs(90)) .build() @@ -2485,11 +2487,12 @@ impl Backend { ) -> u64 { let downloads = Arc::clone(&self.downloads); let song_cache = Arc::clone(&self.song_cache); - let (resolver, api, tx, ctx) = ( + let (resolver, api, tx, ctx, http) = ( Arc::clone(&self.resolver), Arc::clone(&self.api), self.tx.clone(), self.ctx.clone(), + self.http.clone(), ); // A new play supersedes any scrobble task still running for the old track, and — via the // `generation` stamped on every event below — any `Resolving`/`Playing`/`PlaybackFailed` @@ -2619,8 +2622,28 @@ impl Backend { song_cache.note_alias(&track.video_id, id.as_str()); let event = match resolver.resolve(&id).await { - Ok(stream) => { + Ok(mut stream) => { song_cache.note_loudness(id.as_str(), stream.loudness_db); + // A ranged stream plays through the proxy, and was probed — and, if its + // host would not talk, mirrored — at resolve time. yt-dlp's URLs go to + // mpv directly, so they get the same first-byte check here: without it, + // a cache node that will not take a connection delays playback instead + // of being routed to a mirror up front. Probe and proxy sends have their + // own deadlines; mpv's optional curl cap covers connection setup only. + // When even the mirrors will not talk, mpv tries the URL anyway. + if !stream.needs_ranged + && let Err(e) = + refryt_resolve::probe_first_byte(&http, &mut stream.url).await + { + warn!( + video_id = %track.video_id, + error = %format!("{e:#}"), + "stream host unreachable; letting mpv try the URL anyway" + ); + } + if scrobble.generation.load(Ordering::SeqCst) != generation { + return; + } let url = playable_url(proxy.as_deref(), &id, &stream); match player::load( &mpv, diff --git a/crates/refryt/src/player.rs b/crates/refryt/src/player.rs index d8b4377..460bc0a 100644 --- a/crates/refryt/src/player.rs +++ b/crates/refryt/src/player.rs @@ -91,6 +91,9 @@ impl Player { // miss just re-reads from the network, which the forward cache already does past // its own edge. 4 MiB is a few minutes of Opus — plenty for a scrub-back. init.set_property("demuxer-max-back-bytes", "4MiB")?; + // Bound connection establishment only; body reads keep their normal tolerance + // for buffered proxy streams. Older mpv builds without curl lack this option. + let _ = init.set_property("curl-connect-timeout", "5"); // We resolve stream URLs ourselves via refryt-resolve, so mpv must not invoke // yt-dlp for them — direct `googlevideo.com` URLs never match ytdl_hook's // `youtube.com` patterns, so enabling the hook costs nothing there. The in-app