From 2783d8e3f7f5e3defc5b673bb45acdc706f3cd49 Mon Sep 17 00:00:00 2001 From: ajisth69 Date: Sat, 5 Dec 2026 20:44:54 +0530 Subject: [PATCH 1/2] feat(addons): adaptive multi-connection accelerator for direct addon streams --- .../integrations/addons/adaptive_stream.rs | 385 ++++++++++++++++++ .../integrations/addons/local_media_server.rs | 96 ++--- src-tauri/src/integrations/addons/mod.rs | 1 + 3 files changed, 436 insertions(+), 46 deletions(-) create mode 100644 src-tauri/src/integrations/addons/adaptive_stream.rs diff --git a/src-tauri/src/integrations/addons/adaptive_stream.rs b/src-tauri/src/integrations/addons/adaptive_stream.rs new file mode 100644 index 00000000..83aa81b2 --- /dev/null +++ b/src-tauri/src/integrations/addons/adaptive_stream.rs @@ -0,0 +1,385 @@ +//! Adaptive multi-connection fetcher for progressive addon streams. +//! +//! A direct addon URL is first read one bounded range at a time while throughput +//! is sampled. If it drops below real-time playback speed, a single range probe +//! confirms the server honours `Range` (matching `Content-Range`), then the rest +//! is fetched by 16..32 concurrent 256 KB range requests. Chunks land in a +//! bounded, ordered window and are written to the loopback session's `.part` +//! file as a contiguous prefix, so mpv never sees a gap and never waits on a +//! hole. A 429/503 halves concurrency; at one connection the fetch resumes +//! sequentially. `cancel` is checked by every worker and the writer. + +use std::collections::BTreeMap; +use std::io::SeekFrom; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use reqwest::header::{CONTENT_RANGE, RANGE}; +use reqwest::StatusCode; +use tokio::io::{AsyncSeekExt, AsyncWriteExt}; +use tokio::sync::{Mutex, Notify}; +use tokio::task::JoinSet; + +const CHUNK_SIZE: u64 = 256 * 1024; +const MIN_CONCURRENCY: usize = 16; +const MAX_CONCURRENCY: usize = 32; +const REALTIME_BYTES_PER_SEC: u64 = 250 * 1024; +const SAMPLE_BYTES: u64 = 256 * 1024; +const WINDOW_SLACK: usize = 4; +const FETCH_TIMEOUT_SECS: u64 = 30; + +#[derive(Clone, Copy)] +pub struct Config { + pub chunk_size: u64, + pub min_concurrency: usize, + pub max_concurrency: usize, + pub realtime_bytes_per_sec: u64, + pub sample_bytes: u64, +} + +impl Default for Config { + fn default() -> Self { + Self { + chunk_size: CHUNK_SIZE, + min_concurrency: MIN_CONCURRENCY, + max_concurrency: MAX_CONCURRENCY, + realtime_bytes_per_sec: REALTIME_BYTES_PER_SEC, + sample_bytes: SAMPLE_BYTES, + } + } +} + +enum ChunkResult { + Data(Vec, bool, Option), + Backpressure, + End, +} + +type OnTotal = Arc; + +enum ParallelExit { + Done(u64), + Fallback(u64), +} + +fn log(line: &str) { + crate::storage::trace_crumb::TraceCrumb::write(&format!("adaptive-addon {line}")); +} + +async fn fetch_range(client: &reqwest::Client, url: &str, start: u64, len: u64) -> Result { + let end = start.saturating_add(len).saturating_sub(1); + let response = client + .get(url) + .header(RANGE, format!("bytes={start}-{end}")) + .timeout(Duration::from_secs(FETCH_TIMEOUT_SECS)) + .send() + .await + .map_err(|e| format!("range request failed: {e}"))?; + match response.status() { + StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => return Ok(ChunkResult::Backpressure), + StatusCode::RANGE_NOT_SATISFIABLE => return Ok(ChunkResult::End), + status if !status.is_success() => return Err(format!("range request HTTP {status}")), + _ => {} + } + let content_range = response + .headers() + .get(CONTENT_RANGE) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let honored = content_range + .as_deref() + .map(|value| { + let prefix = format!("bytes {start}-"); + value.trim_start().to_ascii_lowercase().starts_with(&prefix) + }) + .unwrap_or(false); + // On a 206, Content-Length is only the range size; the file size is in + // Content-Range. On a plain 200 there is no Content-Range, so Content-Length + // is the full file size. + let total_hint = content_range + .as_deref() + .and_then(|value| value.rsplit('/').next()) + .and_then(|tail| tail.trim().parse::().ok()) + .or_else(|| response.content_length()); + let bytes = response + .bytes() + .await + .map_err(|e| format!("range body read failed: {e}"))?; + Ok(ChunkResult::Data(bytes.to_vec(), honored, total_hint)) +} + +async fn write_at(file: &Arc>, offset: u64, bytes: &[u8]) -> Result<(), String> { + let mut guard = file.lock().await; + guard + .seek(SeekFrom::Start(offset)) + .await + .map_err(|e| format!("seek failed: {e}"))?; + guard + .write_all(bytes) + .await + .map_err(|e| format!("write failed: {e}"))?; + Ok(()) +} + +/// Slow-path reader: bounded ranges until throughput recovers, Range is +/// refused, or the stream ends. Returns the number of bytes written. +async fn fetch_sequential( + client: &reqwest::Client, + url: &str, + file: &Arc>, + mut offset: u64, + total: Option, + cancel: &AtomicBool, + on_total: &OnTotal, + config: Config, + escalation_blocked: bool, +) -> Result { + let mut sample_start = Instant::now(); + let mut sample_bytes = 0u64; + let mut total_reported = false; + + loop { + if cancel.load(Ordering::Acquire) { + return Ok(SequentialExit::Done(offset)); + } + if let Some(total) = total { + if offset >= total { + return Ok(SequentialExit::Done(offset)); + } + } + let remaining = total.map(|t| t.saturating_sub(offset)).unwrap_or(config.chunk_size); + let len = config.chunk_size.min(remaining).max(1); + match fetch_range(client, url, offset, len).await? { + ChunkResult::End => return Ok(SequentialExit::Done(offset)), + ChunkResult::Backpressure => { + tokio::time::sleep(Duration::from_millis(200)).await; + continue; + } + ChunkResult::Data(bytes, honored, total_hint) => { + if !total_reported { + if let Some(len) = total_hint.filter(|&n| n > 0) { + on_total(len); + total_reported = true; + } + } + if bytes.is_empty() { + return Ok(SequentialExit::Done(offset)); + } + // A server that ignores Range answered the first bounded request + // with the whole file. Writing it from zero is a clean fallback. + if !honored && bytes.len() as u64 > len { + write_at(file, offset, &bytes).await?; + return Ok(SequentialExit::Done(offset + bytes.len() as u64)); + } + write_at(file, offset, &bytes).await?; + offset = offset.saturating_add(bytes.len() as u64); + sample_bytes = sample_bytes.saturating_add(bytes.len() as u64); + + let elapsed_ms = sample_start.elapsed().as_millis().max(1) as u64; + if sample_bytes >= config.sample_bytes || elapsed_ms >= 1_000 { + let rate = sample_bytes.saturating_mul(1_000) / elapsed_ms; + sample_bytes = 0; + sample_start = Instant::now(); + if rate < config.realtime_bytes_per_sec && honored && !escalation_blocked { + log(&format!( + "slow stream {rate}B/s, ramping from {base} with {} x {}KB ranges", + config.min_concurrency, + config.chunk_size / 1024, + base = offset + )); + return Ok(SequentialExit::Escalate(offset)); + } + } + if (bytes.len() as u64) < len { + return Ok(SequentialExit::Done(offset)); + } + } + } + } +} + +enum SequentialExit { + Done(u64), + Escalate(u64), +} + +/// Parallel phase. Chunks are fetched out of order but only ever written as a +/// contiguous prefix, which is all the loopback server's live reader needs. +async fn fetch_parallel( + client: &reqwest::Client, + url: &str, + file: &Arc>, + base: u64, + total: Option, + cancel: Arc, + on_total: OnTotal, + config: Config, +) -> Result { + let next_index = Arc::new(AtomicU64::new(0)); + let in_flight = Arc::new(AtomicUsize::new(0)); + let last_index = Arc::new(AtomicU64::new(u64::MAX)); + let concurrency = Arc::new(AtomicUsize::new(config.min_concurrency)); + let ready: Arc>>> = Arc::new(Mutex::new(BTreeMap::new())); + let notify = Arc::new(Notify::new()); + let mut jobs: JoinSet> = JoinSet::new(); + let mut ramp_done = false; + let mut total_reported = false; + let mut committed = base; + let mut sample_start = Instant::now(); + let mut sample_bytes = 0u64; + + loop { + if cancel.load(Ordering::Acquire) { + jobs.abort_all(); + return Ok(ParallelExit::Fallback(committed)); + } + if concurrency.load(Ordering::Acquire) == 1 && !jobs.is_empty() { + // Backoff path: let the running workers finish, then resume single. + while jobs.join_next().await.is_some() {} + return Ok(ParallelExit::Fallback(committed)); + } + + let window = concurrency.load(Ordering::Acquire) + WINDOW_SLACK; + while in_flight.load(Ordering::Acquire) < window + && ready.lock().await.len() + in_flight.load(Ordering::Acquire) < window + && next_index.load(Ordering::Acquire) <= last_index.load(Ordering::Acquire) + { + let index = next_index.fetch_add(1, Ordering::AcqRel); + if index > last_index.load(Ordering::Acquire) { + break; + } + let start = base.saturating_add(index.saturating_mul(config.chunk_size)); + if let Some(total) = total { + if start >= total { + last_index.store(index.saturating_sub(1), Ordering::Release); + break; + } + } + in_flight.fetch_add(1, Ordering::AcqRel); + let client = client.clone(); + let url = url.to_string(); + let cancel = Arc::clone(&cancel); + let len = config.chunk_size; + jobs.spawn(async move { + if cancel.load(Ordering::Acquire) { + return Ok((index, ChunkResult::End)); + } + fetch_range(&client, &url, start, len).await.map(|result| (index, result)) + }); + } + + // Write the longest contiguous prefix that has arrived. + loop { + let index = committed.saturating_sub(base) / config.chunk_size; + let chunk = ready.lock().await.remove(&index); + let Some(chunk) = chunk else { break }; + write_at(file, committed, &chunk).await?; + committed = committed.saturating_add(chunk.len() as u64); + sample_bytes = sample_bytes.saturating_add(chunk.len() as u64); + notify.notify_waiters(); + } + + let elapsed_ms = sample_start.elapsed().as_millis().max(1) as u64; + if sample_bytes >= config.sample_bytes || elapsed_ms >= 1_000 { + let rate = sample_bytes.saturating_mul(1_000) / elapsed_ms; + sample_bytes = 0; + sample_start = Instant::now(); + if rate < config.realtime_bytes_per_sec && !ramp_done { + let current = concurrency.load(Ordering::Acquire); + if current < config.max_concurrency { + let raised = (current * 2).min(config.max_concurrency); + concurrency.store(raised, Ordering::Release); + ramp_done = true; + log(&format!("still slow, raised concurrency to {raised}")); + } + } + } + + let finished = last_index.load(Ordering::Acquire) != u64::MAX + && next_index.load(Ordering::Acquire) > last_index.load(Ordering::Acquire) + && ready.lock().await.is_empty() + && in_flight.load(Ordering::Acquire) == 0; + if finished { + jobs.abort_all(); + return Ok(ParallelExit::Done(committed)); + } + if total.map(|t| committed >= t).unwrap_or(false) && in_flight.load(Ordering::Acquire) == 0 { + jobs.abort_all(); + return Ok(ParallelExit::Done(committed)); + } + + tokio::select! { + Some(result) = jobs.join_next(), if !jobs.is_empty() => { + in_flight.fetch_sub(1, Ordering::AcqRel); + match result { + Ok(Ok((index, ChunkResult::Data(bytes, _, hint)))) => { + if !total_reported { + if let Some(len) = hint.filter(|&n| n > 0) { + on_total(len); + total_reported = true; + } + } + if !bytes.is_empty() { + if (bytes.len() as u64) < config.chunk_size { + last_index.store(index, Ordering::Release); + } + ready.lock().await.insert(index, bytes); + } else { + last_index.store(index.saturating_sub(1), Ordering::Release); + } + notify.notify_waiters(); + } + Ok(Ok((index, ChunkResult::End))) => { + last_index.store(index.saturating_sub(1), Ordering::Release); + notify.notify_waiters(); + } + Ok(Ok((_, ChunkResult::Backpressure))) => { + let current = concurrency.load(Ordering::Acquire); + let reduced = (current / 2).max(1); + concurrency.store(reduced, Ordering::Release); + log(&format!("server backpressure, concurrency now {reduced}")); + } + Ok(Err(err)) => { + jobs.abort_all(); + return Err(err); + } + Err(err) => { + jobs.abort_all(); + return Err(format!("range worker failed: {err}")); + } + } + } + _ = tokio::time::sleep(Duration::from_millis(25)) => {} + } + } +} + +/// Fetches a direct addon URL into `file` and returns the total byte count. +/// Non-addon callers should keep the plain `fetch_bytes` path. +pub async fn fetch_adaptive( + client: &reqwest::Client, + url: &str, + file: Arc>, + total: Option, + cancel: Arc, + on_total: OnTotal, + config: Config, +) -> Result { + let mut offset = 0u64; + let mut escalation_blocked = false; + loop { + match fetch_sequential(client, url, &file, offset, total, &cancel, &on_total, config, escalation_blocked).await? { + SequentialExit::Done(written) => return Ok(written), + SequentialExit::Escalate(from) => { + match fetch_parallel(client, url, &file, from, total, Arc::clone(&cancel), Arc::clone(&on_total), config).await? { + ParallelExit::Done(written) => return Ok(written), + ParallelExit::Fallback(resumed) => { + escalation_blocked = true; + offset = resumed; + } + } + } + } + } +} diff --git a/src-tauri/src/integrations/addons/local_media_server.rs b/src-tauri/src/integrations/addons/local_media_server.rs index 4f385b17..8056ce3d 100644 --- a/src-tauri/src/integrations/addons/local_media_server.rs +++ b/src-tauri/src/integrations/addons/local_media_server.rs @@ -27,6 +27,7 @@ use tokio::sync::{Mutex, Notify}; use crate::storage::trace_crumb::TraceCrumb; +use super::adaptive_stream::{fetch_adaptive, Config as AdaptiveConfig}; use super::dash_assembler::{ assembled_dir, fetch_bytes, fetch_init, fetch_init_range, fetch_range_bytes, fetch_windowed, layout_dir, plan_for_manifest, prune_cache, segment_url_for, DashPlan, @@ -104,6 +105,8 @@ struct Session { total_ready: Notify, completion: Notify, open_readers: AtomicUsize, + /// Set on eviction / cache clear so every in-flight range worker stops. + cancel: Arc, } impl Session { @@ -129,6 +132,7 @@ impl Session { total_ready: Notify::new(), completion: Notify::new(), open_readers: AtomicUsize::new(0), + cancel: Arc::new(AtomicBool::new(false)), }) } @@ -171,6 +175,7 @@ impl Session { total_ready: Notify::new(), completion: Notify::new(), open_readers: AtomicUsize::new(0), + cancel: Arc::new(AtomicBool::new(false)), }) } @@ -275,54 +280,41 @@ impl Session { .map_err(|e| e.to_string())?; } - let resp = self - .client - .get(&url) - .timeout(Duration::from_secs(180)) - .send() - .await - .map_err(|e| format!("direct fetch failed: {e}"))?; - if !resp.status().is_success() { - return Err(format!("direct fetch HTTP {}", resp.status())); - } - - if let Some(len) = resp.content_length().filter(|&n| n > 0) { - self.total_bytes.store(len, Ordering::Release); - self.total_known.store(true, Ordering::Release); - self.total_ready.notify_waiters(); - } - - let mut file = tokio::fs::File::create(&part_path) + let file = tokio::fs::File::create(&part_path) .await .map_err(|e| e.to_string())?; - let mut stream = resp.bytes_stream(); - let mut written: u64 = 0; - let mut since_flush: usize = 0; - while let Some(chunk_res) = stream.next().await { - let chunk = chunk_res.map_err(|e| format!("direct stream read failed: {e}"))?; - if chunk.is_empty() { - continue; - } - file.write_all(&chunk).await.map_err(|e| e.to_string())?; - written = written.saturating_add(chunk.len() as u64); - since_flush = since_flush.saturating_add(chunk.len()); - if since_flush >= 64 * 1024 { - file.flush().await.map_err(|e| e.to_string())?; - since_flush = 0; - } + // Adaptive path: single range first, then 16..32 parallel 256 KB ranges + // when the stream is slower than real-time playback. Publish the total + // as soon as the first response reports it so mpv gets a Content-Range + // while the rest is still downloading. + let this = Arc::clone(self); + let on_total: Arc = Arc::new(move |len: u64| { + this.total_bytes.store(len, Ordering::Release); + this.total_known.store(true, Ordering::Release); + this.total_ready.notify_waiters(); + }); + let file = Arc::new(Mutex::new(file)); + let written = fetch_adaptive( + &self.client, + &url, + Arc::clone(&file), + None, + Arc::clone(&self.cancel), + on_total, + AdaptiveConfig::default(), + ) + .await?; + let _ = file.lock().await.flush().await; + if self.cancel.load(Ordering::Acquire) { + return Err("direct session cancelled".to_string()); } - file.flush().await.map_err(|e| e.to_string())?; - drop(file); - if written == 0 { let _ = tokio::fs::remove_file(&part_path).await; return Err("direct stream returned 0 bytes".to_string()); } - if !self.total_known.load(Ordering::Acquire) { - self.total_bytes.store(written, Ordering::Release); - self.total_known.store(true, Ordering::Release); - self.total_ready.notify_waiters(); - } + self.total_bytes.store(written, Ordering::Release); + self.total_known.store(true, Ordering::Release); + self.total_ready.notify_waiters(); if self.publish_part().await { self.done.store(true, Ordering::Release); self.completion.notify_waiters(); @@ -1679,7 +1671,9 @@ impl LocalMediaServer { pub async fn evict(&self, cache_name: &str) { let safe = sanitize_name(cache_name); - self.sessions.lock().await.remove(&safe); + if let Some(session) = self.sessions.lock().await.remove(&safe) { + session.cancel.store(true, Ordering::Release); + } let _ = tokio::fs::remove_file(assembled_path_with_ext(&safe, "m4a")).await; let _ = tokio::fs::remove_file(assembled_path_with_ext(&safe, "flac")).await; let _ = tokio::fs::remove_file(assembled_path_with_ext(&safe, "part")).await; @@ -1736,7 +1730,13 @@ impl LocalMediaServer { } pub async fn clear_all(&self) { - self.sessions.lock().await.clear(); + let sessions: Vec> = { + let mut guard = self.sessions.lock().await; + guard.drain().map(|(_, session)| session).collect() + }; + for session in sessions { + session.cancel.store(true, Ordering::Release); + } for dir in [assembled_dir(), layout_dir()] { let Ok(mut entries) = tokio::fs::read_dir(&dir).await else { continue; @@ -1757,9 +1757,13 @@ impl LocalMediaServer { if guard.len() <= 192 { break; } - if let Some(s) = guard.get(&k) { - if s.done.load(Ordering::Acquire) || s.failed.load(Ordering::Acquire) { - guard.remove(&k); + let stale = guard + .get(&k) + .map(|s| s.done.load(Ordering::Acquire) || s.failed.load(Ordering::Acquire)) + .unwrap_or(false); + if stale { + if let Some(removed) = guard.remove(&k) { + removed.cancel.store(true, Ordering::Release); } } } diff --git a/src-tauri/src/integrations/addons/mod.rs b/src-tauri/src/integrations/addons/mod.rs index 3ee73f69..a762e76c 100644 --- a/src-tauri/src/integrations/addons/mod.rs +++ b/src-tauri/src/integrations/addons/mod.rs @@ -1,6 +1,7 @@ //! Personal lossless addon client, DASH/hybrid assembler, CENC decryptor, //! and loopback media server. +pub mod adaptive_stream; pub mod addon_api; pub mod dash_assembler; pub mod hybrid_cenc; From 0815ac14899aa34877faf9ffe32f616dc66e7f9b Mon Sep 17 00:00:00 2001 From: ajisth69 Date: Sat, 5 Dec 2026 20:53:07 +0530 Subject: [PATCH 2/2] fix(test): update playback tests to current track/stream models --- src-tauri/src/audio/playback_service.rs | 36 ++++++++++++------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src-tauri/src/audio/playback_service.rs b/src-tauri/src/audio/playback_service.rs index f6c34536..cac46758 100644 --- a/src-tauri/src/audio/playback_service.rs +++ b/src-tauri/src/audio/playback_service.rs @@ -7718,7 +7718,7 @@ mod tests { std::fs::write(&file_path, b"ID3test").unwrap(); let mut track = PlayableTrack::new("Challa", "Artist"); - track.local_path = file_path.to_string_lossy().into_owned(); + track.playback_url = file_path.to_string_lossy().into_owned(); { let mut d = svc.data.lock().unwrap(); d.snapshot.volume = 0.8; @@ -7762,24 +7762,24 @@ mod tests { std::fs::write(&f2, b"ID3b").unwrap(); let mut t1 = PlayableTrack::new("Challa", "Artist 1"); - t1.local_path = f1.to_string_lossy().into_owned(); + t1.playback_url = f1.to_string_lossy().into_owned(); let mut t2 = PlayableTrack::new("Next Song", "Artist 2"); - t2.local_path = f2.to_string_lossy().into_owned(); - - let stream1 = ResolvedStream::new( - f1.to_string_lossy().into_owned(), - "local:t1", - "local", - "audio/mpeg", - Duration::from_secs(180), - ); - let stream2 = ResolvedStream::new( - f2.to_string_lossy().into_owned(), - "local:t2", - "local", - "audio/mpeg", - Duration::from_secs(180), - ); + t2.playback_url = f2.to_string_lossy().into_owned(); + + let stream1 = ResolvedStream { + url: f1.to_string_lossy().into_owned(), + mime_type: "audio/mpeg".to_string(), + audio_codec: "local".to_string(), + cache_key: "local:t1".to_string(), + ..Default::default() + }; + let stream2 = ResolvedStream { + url: f2.to_string_lossy().into_owned(), + mime_type: "audio/mpeg".to_string(), + audio_codec: "local".to_string(), + cache_key: "local:t2".to_string(), + ..Default::default() + }; assert!(svc.ensure_player().await); {