use std::io::{Cursor, Read, Seek, SeekFrom}; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use std::time::{Duration, Instant}; use ringbuf::{HeapConsumer, HeapProducer, HeapRb}; use biquad::{Biquad, Coefficients, DirectForm2Transposed, ToHertz, Type as FilterType}; use rodio::{Sink, Source}; use rodio::source::UniformSourceIterator; use serde::Serialize; use symphonia::core::{ audio::{AudioBufferRef, SampleBuffer, SignalSpec}, codecs::{DecoderOptions, CODEC_TYPE_NULL}, formats::{FormatOptions, FormatReader, SeekMode, SeekTo}, io::{MediaSource, MediaSourceStream, MediaSourceStreamOptions}, meta::MetadataOptions, probe::Hint, units::{self, Time}, }; use futures_util::StreamExt; use tauri::{AppHandle, Emitter, State}; // ─── 10-Band Graphic Equalizer ──────────────────────────────────────────────── const EQ_BANDS_HZ: [f32; 10] = [31.0, 62.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]; const EQ_Q: f32 = 1.41; const EQ_CHECK_INTERVAL: usize = 1024; struct EqSource> { inner: S, sample_rate: u32, channels: u16, gains: Arc<[AtomicU32; 10]>, enabled: Arc, pre_gain: Arc, filters: [[DirectForm2Transposed; 2]; 10], current_gains: [f32; 10], sample_counter: usize, channel_idx: usize, } impl> EqSource { fn new(inner: S, gains: Arc<[AtomicU32; 10]>, enabled: Arc, pre_gain: Arc) -> Self { let sample_rate = inner.sample_rate(); let channels = inner.channels(); let filters = std::array::from_fn(|band| { let freq = EQ_BANDS_HZ[band].clamp(20.0, (sample_rate as f32 / 2.0) - 100.0); std::array::from_fn(|_| { let coeffs = Coefficients::::from_params( FilterType::PeakingEQ(0.0), (sample_rate as f32).hz(), freq.hz(), EQ_Q, ).unwrap_or_else(|_| Coefficients::::from_params( FilterType::PeakingEQ(0.0), (sample_rate as f32).hz(), 1000.0f32.hz(), EQ_Q, ).unwrap()); DirectForm2Transposed::::new(coeffs) }) }); Self { inner, sample_rate, channels, gains, enabled, pre_gain, filters, current_gains: [0.0; 10], sample_counter: 0, channel_idx: 0, } } fn refresh_if_needed(&mut self) { for band in 0..10 { let gain_db = f32::from_bits(self.gains[band].load(Ordering::Relaxed)); if (gain_db - self.current_gains[band]).abs() > 0.01 { self.current_gains[band] = gain_db; let freq = EQ_BANDS_HZ[band].clamp(20.0, (self.sample_rate as f32 / 2.0) - 100.0); if let Ok(coeffs) = Coefficients::::from_params( FilterType::PeakingEQ(gain_db), (self.sample_rate as f32).hz(), freq.hz(), EQ_Q, ) { for ch in 0..2 { self.filters[band][ch].update_coefficients(coeffs); } } } } } } impl> Iterator for EqSource { type Item = f32; fn next(&mut self) -> Option { let sample = self.inner.next()?; if self.sample_counter % EQ_CHECK_INTERVAL == 0 { self.refresh_if_needed(); } self.sample_counter = self.sample_counter.wrapping_add(1); if !self.enabled.load(Ordering::Relaxed) { self.channel_idx = (self.channel_idx + 1) % self.channels as usize; return Some(sample); } let ch = self.channel_idx.min(1); self.channel_idx = (self.channel_idx + 1) % self.channels as usize; let pre_gain_db = f32::from_bits(self.pre_gain.load(Ordering::Relaxed)); let pre_gain_factor = 10_f32.powf(pre_gain_db / 20.0); let mut s = sample * pre_gain_factor; for band in 0..10 { s = self.filters[band][ch].run(s); } Some(s.clamp(-1.0, 1.0)) } } impl> Source for EqSource { fn current_frame_len(&self) -> Option { self.inner.current_frame_len() } fn channels(&self) -> u16 { self.channels } fn sample_rate(&self) -> u32 { self.sample_rate } fn total_duration(&self) -> Option { self.inner.total_duration() } fn try_seek(&mut self, pos: Duration) -> Result<(), rodio::source::SeekError> { // Reset biquad filter state to avoid glitches after seek. for band in 0..10 { let gain_db = f32::from_bits(self.gains[band].load(Ordering::Relaxed)); self.current_gains[band] = gain_db; let freq = EQ_BANDS_HZ[band].clamp(20.0, (self.sample_rate as f32 / 2.0) - 100.0); if let Ok(coeffs) = Coefficients::::from_params( FilterType::PeakingEQ(gain_db), (self.sample_rate as f32).hz(), freq.hz(), EQ_Q, ) { for ch in 0..2 { self.filters[band][ch] = DirectForm2Transposed::::new(coeffs); } } } self.channel_idx = 0; self.sample_counter = 0; self.inner.try_seek(pos) } } // ─── DynSource — type-erased Source wrapper ─────────────────────────────────── // // Allows chaining differently-typed sources (with trimming applied) into a // single concrete type accepted by EqSource>. struct DynSource { inner: Box + Send>, channels: u16, sample_rate: u32, } impl DynSource { fn new(src: impl Source + Send + 'static) -> Self { let channels = src.channels(); let sample_rate = src.sample_rate(); Self { inner: Box::new(src), channels, sample_rate } } } impl Iterator for DynSource { type Item = f32; fn next(&mut self) -> Option { self.inner.next() } } impl Source for DynSource { fn current_frame_len(&self) -> Option { self.inner.current_frame_len() } fn channels(&self) -> u16 { self.channels } fn sample_rate(&self) -> u32 { self.sample_rate } fn total_duration(&self) -> Option { self.inner.total_duration() } fn try_seek(&mut self, pos: Duration) -> Result<(), rodio::source::SeekError> { self.inner.try_seek(pos) } } // ─── EqualPowerFadeIn — per-sample sin(t·π/2) fade-in envelope ─────────────── // // Applied to every new track: // • Crossfade: fade_dur = crossfade_secs → symmetric equal-power fade-in // • Hard cut: fade_dur = 5 ms → micro-fade eliminates DC-click // • Gapless: fade_dur = 0 → unity gain (no modification) // // gain(t) = sin(t · π/2), t ∈ [0, 1) // At t = 0 gain = 0, at t = 1 gain = 1. // Equal-power property: cos²+sin² = 1 → combined with cos fade-out on Track A // the total perceived loudness stays constant across the crossfade. struct EqualPowerFadeIn> { inner: S, sample_count: u64, fade_samples: u64, } impl> EqualPowerFadeIn { fn new(inner: S, fade_dur: Duration) -> Self { let sample_rate = inner.sample_rate(); let channels = inner.channels() as u64; let fade_samples = if fade_dur.is_zero() { 0 } else { (fade_dur.as_secs_f64() * sample_rate as f64 * channels as f64) as u64 }; Self { inner, sample_count: 0, fade_samples } } } impl> Iterator for EqualPowerFadeIn { type Item = f32; fn next(&mut self) -> Option { let sample = self.inner.next()?; let gain = if self.fade_samples == 0 || self.sample_count >= self.fade_samples { 1.0 } else { let t = self.sample_count as f32 / self.fade_samples as f32; (t * std::f32::consts::FRAC_PI_2).sin() }; self.sample_count += 1; Some((sample * gain).clamp(-1.0, 1.0)) } } impl> Source for EqualPowerFadeIn { fn current_frame_len(&self) -> Option { self.inner.current_frame_len() } fn channels(&self) -> u16 { self.inner.channels() } fn sample_rate(&self) -> u32 { self.inner.sample_rate() } fn total_duration(&self) -> Option { self.inner.total_duration() } fn try_seek(&mut self, pos: Duration) -> Result<(), rodio::source::SeekError> { // For mid-track seeks: skip straight to unity gain so the new position // plays at full volume immediately — no audible fade-in glitch. // For seeks to the very start (< 100 ms): keep the micro-fade to // suppress any DC-offset click from the fresh decode. if pos.as_millis() < 100 { self.sample_count = 0; } else { self.sample_count = self.fade_samples; } self.inner.try_seek(pos) } } // ─── TriggeredFadeOut — sample-level cos(t·π/2) fade-out triggered externally ─ // // Every track source is wrapped with this. It passes through at unity gain // until `trigger` is set to true, at which point it reads `fade_total_samples` // and applies a cos(t·π/2) envelope: // gain(t) = cos(t · π/2), t ∈ [0, 1] // At t = 0 gain = 1, at t = 1 gain = 0. // After the fade completes, returns None to exhaust the source. // // Combined with EqualPowerFadeIn (sin curve) on Track B, this gives a // symmetric constant-power crossfade: sin²+cos² = 1. struct TriggeredFadeOut> { inner: S, trigger: Arc, fade_total_samples: Arc, fade_progress: u64, fading: bool, cached_total: u64, } impl> TriggeredFadeOut { fn new(inner: S, trigger: Arc, fade_total_samples: Arc) -> Self { Self { inner, trigger, fade_total_samples, fade_progress: 0, fading: false, cached_total: 0, } } } impl> Iterator for TriggeredFadeOut { type Item = f32; fn next(&mut self) -> Option { // Check trigger on first fade sample only (avoid atomic load per sample). if !self.fading && self.trigger.load(Ordering::Relaxed) { self.fading = true; self.cached_total = self.fade_total_samples.load(Ordering::Relaxed).max(1); self.fade_progress = 0; } if self.fading { if self.fade_progress >= self.cached_total { // Fade complete — exhaust the source. return None; } let sample = self.inner.next()?; let t = self.fade_progress as f32 / self.cached_total as f32; let gain = (t * std::f32::consts::FRAC_PI_2).cos(); self.fade_progress += 1; Some((sample * gain).clamp(-1.0, 1.0)) } else { self.inner.next() } } } impl> Source for TriggeredFadeOut { fn current_frame_len(&self) -> Option { self.inner.current_frame_len() } fn channels(&self) -> u16 { self.inner.channels() } fn sample_rate(&self) -> u32 { self.inner.sample_rate() } fn total_duration(&self) -> Option { self.inner.total_duration() } fn try_seek(&mut self, pos: Duration) -> Result<(), rodio::source::SeekError> { // If we seek back during a fade, cancel the fade. if self.fading { self.fading = false; self.trigger.store(false, Ordering::Relaxed); } self.fade_progress = 0; self.inner.try_seek(pos) } } // ─── NotifyingSource — sets a flag when the inner iterator is exhausted ─────── // // This is the key mechanism for gapless: the progress task polls `done` to know // exactly when source N has finished inside the Sink, without relying on // wall-clock estimation or the unreliable `Sink::empty()`. struct NotifyingSource> { inner: S, done: Arc, signalled: bool, } impl> NotifyingSource { fn new(inner: S, done: Arc) -> Self { Self { inner, done, signalled: false } } } impl> Iterator for NotifyingSource { type Item = f32; fn next(&mut self) -> Option { let sample = self.inner.next(); if sample.is_none() && !self.signalled { self.signalled = true; self.done.store(true, Ordering::SeqCst); } sample } } impl> Source for NotifyingSource { fn current_frame_len(&self) -> Option { self.inner.current_frame_len() } fn channels(&self) -> u16 { self.inner.channels() } fn sample_rate(&self) -> u32 { self.inner.sample_rate() } fn total_duration(&self) -> Option { self.inner.total_duration() } fn try_seek(&mut self, pos: Duration) -> Result<(), rodio::source::SeekError> { // If we seek backwards the source is no longer exhausted. self.signalled = false; self.done.store(false, Ordering::SeqCst); self.inner.try_seek(pos) } } // ─── CountingSource — atomic sample counter for drift-free position tracking ─ // // Wraps the outermost source and increments a shared AtomicU64 on every sample. // The progress task reads this counter and divides by (sample_rate * channels) // to get the exact playback position — no wall-clock drift. struct CountingSource> { inner: S, counter: Arc, } impl> CountingSource { fn new(inner: S, counter: Arc) -> Self { Self { inner, counter } } } impl> Iterator for CountingSource { type Item = f32; fn next(&mut self) -> Option { let sample = self.inner.next(); if sample.is_some() { self.counter.fetch_add(1, Ordering::Relaxed); } sample } } impl> Source for CountingSource { fn current_frame_len(&self) -> Option { self.inner.current_frame_len() } fn channels(&self) -> u16 { self.inner.channels() } fn sample_rate(&self) -> u32 { self.inner.sample_rate() } fn total_duration(&self) -> Option { self.inner.total_duration() } fn try_seek(&mut self, pos: Duration) -> Result<(), rodio::source::SeekError> { // Reset counter only after confirming the inner seek succeeded. // If we reset first and the seek fails, the counter ends up at the // new position while the decoder is still at the old one — causing // a permanent desync between displayed time and actual audio. let result = self.inner.try_seek(pos); if result.is_ok() { let samples = (pos.as_secs_f64() * self.inner.sample_rate() as f64 * self.inner.channels() as f64) as u64; self.counter.store(samples, Ordering::Relaxed); } result } } // ─── Internet Radio v2 — Lock-Free SPSC + ICY Metadata + Hybrid Pause ──────── // // HTTP task (tokio) // └─[IcyInterceptor]─► HeapProducer // │ (4 MB HeapRb, lock-free) // HeapConsumer // │ // AudioStreamReader (Read + Seek + MediaSource) // │ // SizedDecoder (symphonia) // │ // rodio Sink // // Pause modes: // Logical pause — sink.pause(); download task keeps filling (time-shift). // Hard pause — buffer ≥ RADIO_HARD_PAUSE_THRESH full + paused ≥ 5 s // → TCP disconnect, is_hard_paused = true. // Resume (warm) — sink.play(); buffer drains seamlessly. // Resume (cold) — new HeapRb + new GET; consumer swapped in AudioStreamReader. // // New Tauri event: "radio:metadata" → String (ICY StreamTitle) /// 256 KB on the heap — ≈16 s at 128 kbps, ≈6 s at 320 kbps. /// Small enough that stale audio drains within a few seconds on reconnect; /// large enough to absorb brief network hiccups without stuttering. const RADIO_BUF_CAPACITY: usize = 256 * 1024; /// Seconds at stall threshold while paused before hard-disconnect. const RADIO_HARD_PAUSE_SECS: u64 = 5; /// AudioStreamReader timeout: if no audio bytes arrive for this long → EOF. const RADIO_READ_TIMEOUT_SECS: u64 = 15; /// Sleep interval when ring buffer is empty (prevents CPU spin). const RADIO_YIELD_MS: u64 = 2; // ── ICY Metadata State Machine ──────────────────────────────────────────────── // // Shoutcast/Icecast embed metadata every `metaint` audio bytes: // // ┌──────────────────────┬───┬─────────────┐ // │ audio × metaint │ N │ meta × N×16 │ (repeating) // └──────────────────────┴───┴─────────────┘ // // N = 0 → no metadata this block. Metadata bytes are stripped so only // pure audio reaches the ring buffer and Symphonia never sees text bytes. enum IcyState { /// Forwarding audio bytes; `remaining` counts down to the next boundary. ReadingAudio { remaining: usize }, /// Next byte is the metadata length multiplier N. ReadingLengthByte, /// Accumulating N×16 metadata bytes. ReadingMetadata { remaining: usize, buf: Vec }, } struct IcyInterceptor { state: IcyState, metaint: usize, } impl IcyInterceptor { fn new(metaint: usize) -> Self { Self { metaint, state: IcyState::ReadingAudio { remaining: metaint } } } /// Feed a raw HTTP chunk. /// Appends only audio bytes to `audio_out`. /// Returns `Some(IcyMeta)` when a StreamTitle is extracted. fn process(&mut self, input: &[u8], audio_out: &mut Vec) -> Option { let mut extracted: Option = None; let mut i = 0; while i < input.len() { match &mut self.state { IcyState::ReadingAudio { remaining } => { let n = (input.len() - i).min(*remaining); audio_out.extend_from_slice(&input[i..i + n]); i += n; *remaining -= n; if *remaining == 0 { self.state = IcyState::ReadingLengthByte; } } IcyState::ReadingLengthByte => { let len_n = input[i] as usize; i += 1; self.state = if len_n == 0 { IcyState::ReadingAudio { remaining: self.metaint } } else { IcyState::ReadingMetadata { remaining: len_n * 16, buf: Vec::with_capacity(len_n * 16), } }; } IcyState::ReadingMetadata { remaining, buf } => { let n = (input.len() - i).min(*remaining); buf.extend_from_slice(&input[i..i + n]); i += n; *remaining -= n; if *remaining == 0 { let bytes = std::mem::take(buf); extracted = parse_icy_meta(&bytes); self.state = IcyState::ReadingAudio { remaining: self.metaint }; } } } } extracted } } /// ICY metadata parsed from a raw metadata block. #[derive(serde::Serialize, Clone)] pub(crate) struct IcyMeta { pub title: String, /// `true` when `StreamUrl='0'` — indicates a CDN-injected ad/promo. pub is_ad: bool, } /// Extract `StreamTitle` and `StreamUrl` from a raw ICY metadata block. /// Tolerates null padding and non-UTF-8 bytes (lossy conversion). fn parse_icy_meta(raw: &[u8]) -> Option { let s = String::from_utf8_lossy(raw); let s = s.trim_end_matches('\0'); const TITLE_TAG: &str = "StreamTitle='"; let title_start = s.find(TITLE_TAG)? + TITLE_TAG.len(); let title_rest = &s[title_start..]; // find (not rfind) — rfind would skip past StreamUrl and corrupt the title let title_end = title_rest.find("';")?; let title = title_rest[..title_end].trim().to_string(); if title.is_empty() { return None; } const URL_TAG: &str = "StreamUrl='"; let stream_url = s.find(URL_TAG).map(|pos| { let rest = &s[pos + URL_TAG.len()..]; let end = rest.find("';").unwrap_or(rest.len()); rest[..end].trim().to_string() }).unwrap_or_default(); Some(IcyMeta { title, is_ad: stream_url == "0" }) } // ── AudioStreamReader — SPSC consumer → std::io::Read ──────────────────────── // // Bridges HeapConsumer (non-blocking) into the synchronous Read interface // that Symphonia requires. Designed to run inside tokio::task::spawn_blocking. // // Empty buffer: sleeps RADIO_YIELD_MS ms, retries. Never busy-spins. // Timeout: after RADIO_READ_TIMEOUT_SECS with no data → TimedOut. // Generation: if gen_arc != self.gen → Ok(0) (EOF; new track started). // Reconnect: audio_resume sends a fresh HeapConsumer via new_cons_rx. // On the next read() we drain the channel (keep latest) and swap. struct AudioStreamReader { cons: HeapConsumer, /// Delivers fresh consumers on hard-pause reconnect (unbounded; drain to latest). /// Wrapped in Mutex so AudioStreamReader is Sync (required by symphonia::MediaSource). /// No real contention: only the audio thread ever calls read(). new_cons_rx: Mutex>>, deadline: std::time::Instant, gen_arc: Arc, gen: u64, /// Monotonic byte offset for SeekFrom::Current(0) "tell" (Symphonia probe). pos: u64, } impl Read for AudioStreamReader { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { // EOF guard: new track started. if self.gen_arc.load(Ordering::SeqCst) != self.gen { return Ok(0); } // Drain reconnect channel; keep only the most recently delivered consumer // so a double-tap of resume doesn't leave stale data in place. let mut newest: Option> = None; while let Ok(c) = self.new_cons_rx.lock().unwrap().try_recv() { newest = Some(c); } if let Some(c) = newest { self.cons = c; self.deadline = std::time::Instant::now() + Duration::from_secs(RADIO_READ_TIMEOUT_SECS); } loop { if self.gen_arc.load(Ordering::SeqCst) != self.gen { return Ok(0); } let available = self.cons.len(); if available > 0 { let n = buf.len().min(available); let read = self.cons.pop_slice(&mut buf[..n]); self.pos += read as u64; // Reset deadline: data arrived, so connection is alive. self.deadline = std::time::Instant::now() + Duration::from_secs(RADIO_READ_TIMEOUT_SECS); return Ok(read); } if std::time::Instant::now() >= self.deadline { eprintln!( "[radio] AudioStreamReader: {}s without data → EOF", RADIO_READ_TIMEOUT_SECS ); return Err(std::io::Error::new( std::io::ErrorKind::TimedOut, "radio: no data received", )); } std::thread::sleep(Duration::from_millis(RADIO_YIELD_MS)); } } } impl Seek for AudioStreamReader { fn seek(&mut self, pos: SeekFrom) -> std::io::Result { match pos { SeekFrom::Current(0) => Ok(self.pos), _ => Err(std::io::Error::new( std::io::ErrorKind::Unsupported, "radio stream is not seekable", )), } } } impl MediaSource for AudioStreamReader { fn is_seekable(&self) -> bool { false } fn byte_len(&self) -> Option { None } } // ── Pause / Reconnect Coordination ─────────────────────────────────────────── pub(crate) struct RadioSharedFlags { /// Set by audio_pause; cleared by audio_resume. is_paused: AtomicBool, /// Set by download task on hard disconnect; cleared on resume-reconnect. is_hard_paused: AtomicBool, /// Delivers a fresh HeapConsumer to AudioStreamReader on reconnect. new_cons_tx: Mutex>>, } /// Live state for the current radio session, stored in AudioEngine. /// Dropping this struct aborts the HTTP download task immediately. pub(crate) struct RadioLiveState { pub url: String, pub gen: u64, pub task: tokio::task::JoinHandle<()>, pub flags: Arc, } impl Drop for RadioLiveState { fn drop(&mut self) { self.task.abort(); } } // ── HE-AAC / FDK-AAC Fallback ──────────────────────────────────────────────── // // Symphonia 0.5.x: AAC-LC only. HE-AAC (AAC+) and HE-AACv2 lack SBR/PS → // streams play at half speed with muffled audio. // // With Cargo feature "fdk-aac": FdkAacDecoder is tried first for CODEC_TYPE_AAC. // Enable in Cargo.toml: // symphonia-adapter-fdk-aac = { version = "0.1", optional = true } // [features] // fdk-aac = ["dep:symphonia-adapter-fdk-aac"] fn try_make_radio_decoder( params: &symphonia::core::codecs::CodecParameters, opts: &DecoderOptions, ) -> Result, symphonia::core::errors::Error> { symphonia::default::get_codecs().make(params, opts) } // ── Async HTTP Download Task ────────────────────────────────────────────────── // // Lifecycle: // 'outer loop — reconnect on TCP drop (up to MAX_RECONNECTS) // 'inner loop — read HTTP chunks → ICY interceptor → push audio to ring buffer // // Hard-pause detection: if push_slice() returns 0 (buffer full) AND sink is // paused AND that condition persists for RADIO_HARD_PAUSE_SECS → disconnect. // Sets is_hard_paused = true so audio_resume knows it must reconnect. async fn radio_download_task( gen: u64, gen_arc: Arc, mut initial_response: Option, http_client: reqwest::Client, url: String, mut prod: HeapProducer, flags: Arc, app: AppHandle, ) { let mut bytes_total: u64 = 0; // Counts consecutive failures (reset on each successful chunk). // laut.fm and similar CDNs force-reconnect every ~700 KB; this is normal. let mut reconnect_count: u32 = 0; const MAX_CONSECUTIVE_FAILURES: u32 = 5; let mut audio_scratch: Vec = Vec::with_capacity(65_536); 'outer: loop { if gen_arc.load(Ordering::SeqCst) != gen { return; } // ── Obtain response (initial or reconnect) ──────────────────────────── let response = match initial_response.take() { Some(r) => r, None => { if reconnect_count >= MAX_CONSECUTIVE_FAILURES { eprintln!("[radio] {MAX_CONSECUTIVE_FAILURES} consecutive failures — giving up"); break 'outer; } tokio::time::sleep(Duration::from_millis(500)).await; if gen_arc.load(Ordering::SeqCst) != gen { return; } match http_client .get(&url) .header("Icy-MetaData", "1") .send() .await { Ok(r) if r.status().is_success() => { eprintln!("[radio] reconnected ({bytes_total} B so far)"); r } Ok(r) => { eprintln!("[radio] reconnect: HTTP {} — giving up", r.status()); break 'outer; } Err(e) => { eprintln!("[radio] reconnect error: {e} — giving up"); break 'outer; } } } }; // Parse ICY metaint from each response (consistent across reconnects). let metaint: Option = response .headers() .get("icy-metaint") .and_then(|v| v.to_str().ok()) .and_then(|s| s.parse().ok()); let mut icy = metaint.map(IcyInterceptor::new); let mut byte_stream = response.bytes_stream(); // Stall timer: tracks how long push_slice() returns 0 while paused. let mut stall_since: Option = None; 'inner: loop { if gen_arc.load(Ordering::SeqCst) != gen { return; } // ── Back-pressure + hard-pause detection ────────────────────────── if prod.is_full() { if flags.is_paused.load(Ordering::Relaxed) { let since = stall_since.get_or_insert(std::time::Instant::now()); if since.elapsed() >= Duration::from_secs(RADIO_HARD_PAUSE_SECS) { let fill_pct = ((1.0 - prod.free_len() as f32 / RADIO_BUF_CAPACITY as f32) * 100.0) as u32; eprintln!( "[radio] hard pause: {fill_pct}% full, \ paused >{RADIO_HARD_PAUSE_SECS}s → disconnecting" ); flags.is_hard_paused.store(true, Ordering::Release); return; // Drop HeapProducer → TCP connection released. } } else { stall_since = None; } tokio::time::sleep(Duration::from_millis(50)).await; continue 'inner; } stall_since = None; // ── Read HTTP chunk ─────────────────────────────────────────────── match byte_stream.next().await { Some(Ok(chunk)) => { bytes_total += chunk.len() as u64; // Successful data → reset consecutive-failure counter. reconnect_count = 0; audio_scratch.clear(); if let Some(ref mut interceptor) = icy { if let Some(meta) = interceptor.process(&chunk, &mut audio_scratch) { let label = if meta.is_ad { "[Ad]" } else { "" }; eprintln!("[radio] ICY StreamTitle: {}{}", label, meta.title); let _ = app.emit("radio:metadata", &meta); } } else { audio_scratch.extend_from_slice(&chunk); } // Push with per-chunk back-pressure: yield 5 ms if full mid-chunk. let mut offset = 0; while offset < audio_scratch.len() { if gen_arc.load(Ordering::SeqCst) != gen { return; } let pushed = prod.push_slice(&audio_scratch[offset..]); if pushed == 0 { tokio::time::sleep(Duration::from_millis(5)).await; } else { offset += pushed; } } } Some(Err(e)) => { reconnect_count += 1; eprintln!("[radio] stream error: {e} → reconnecting (consecutive #{reconnect_count})"); break 'inner; } None => { reconnect_count += 1; eprintln!("[radio] stream ended cleanly → reconnecting (consecutive #{reconnect_count})"); break 'inner; } } } // 'inner // Do NOT swap the ring buffer here. The remaining bytes in the buffer // are still valid audio and will drain naturally during reconnect. // Clearing it would cause an immediate underrun/glitch. // The buffer is kept small (RADIO_BUF_CAPACITY) so stale audio drains // within a few seconds rather than minutes. } // 'outer eprintln!("[radio] download task done ({bytes_total} B total)"); } fn content_type_to_hint(ct: &str) -> Option { let ct = ct.to_ascii_lowercase(); if ct.contains("mpeg") || ct.contains("mp3") { Some("mp3".into()) } else if ct.contains("aac") || ct.contains("aacp") { Some("aac".into()) } else if ct.contains("ogg") { Some("ogg".into()) } else if ct.contains("flac") { Some("flac".into()) } else { None } } // ─── SizedCursorSource — correct byte_len for seekable in-memory sources ────── // // rodio's internal ReadSeekSource wraps Cursor> but hardcodes // byte_len() → None. This tells symphonia "stream length unknown", which // prevents the FLAC demuxer from seeking (it validates seek offsets against // the total stream length from byte_len). MP3 is unaffected because its // demuxer uses Xing/LAME headers instead. // // This wrapper provides the actual byte length, fixing seek for all formats. struct SizedCursorSource { inner: Cursor>, len: u64, } impl Read for SizedCursorSource { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { self.inner.read(buf) } } impl Seek for SizedCursorSource { fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { self.inner.seek(pos) } } impl MediaSource for SizedCursorSource { fn is_seekable(&self) -> bool { true } fn byte_len(&self) -> Option { Some(self.len) } } // ─── SizedDecoder — symphonia decoder with correct byte_len ─────────────────── // // Replaces rodio::Decoder::new() which wraps the source in ReadSeekSource // (byte_len = None). This constructs the symphonia pipeline directly, // providing the correct byte_len via SizedCursorSource. // // Implements Iterator + Source — identical interface to // rodio::Decoder, so the rest of the source chain is unchanged. /// Max retries for IO/packet-read errors (fatal — network drop, truncated file). const DECODE_MAX_RETRIES: usize = 3; /// Max *consecutive* DecodeErrors before giving up on a file. /// Non-fatal errors like "invalid main_data offset" are silently dropped up to /// this limit so a handful of corrupt MP3 frames never aborts an otherwise /// playable track (VLC-style frame dropping). const MAX_CONSECUTIVE_DECODE_ERRORS: usize = 100; struct SizedDecoder { decoder: Box, current_frame_offset: usize, format: Box, total_duration: Option