From ac469305f22b449548f20c9c209950540e1054db Mon Sep 17 00:00:00 2001 From: Junaid Irfan Date: Tue, 24 Nov 2026 00:56:44 -0500 Subject: [PATCH] No idle timer, less heap, a faster first frame, and lists that don't shrink on errors - No 15 s session health timer: a lost connection is noticed on the next key, event or second of playback. Idle wakeups drop from ~15 to ~3 a minute (what's left is Spotify's own keepalive), and paused from ~12 to ~3 a minute. - A fixed glibc mmap threshold: each decoded cover raised the trim threshold, leaving ~7 MB of free heap resident. PSS after a few song changes: 28.9 MB -> 20.8 MB. - Smart-shuffle picks live in their own list instead of a copy of the whole playing list (-1.6 MB of heap with Liked Songs playing). - Terminals that don't answer the image query (tmux, ConPTY) are remembered for a week, so the first frame doesn't wait the 0.5 s timeout: 542 ms -> ~50 ms in tmux. - A metadata request or page that still fails after librespot's retries fails the load, instead of dropping those songs and saving the shorter list over the good copy. A failed refresh says the saved copy is showing. - Offline at start: say so and keep the saved login, instead of opening a browser login. - opt-level "s": the binary goes from 9.1 MB to 6.5 MB and PSS by ~2 MB, with no measurable change in CPU, cover decoding or key-to-frame time. --- Cargo.toml | 2 +- src/api.rs | 88 +++++++++++++++++----------------- src/app.rs | 47 ++++++++++-------- src/app/extras.rs | 17 +++---- src/auth.rs | 6 ++- src/main.rs | 118 +++++++++++++++++++++++++++++++--------------- 6 files changed, 169 insertions(+), 109 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7724aed..9f3019c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,7 +49,7 @@ objc2-foundation = { version = "0.3", default-features = false, features = ["std objc2-media-player = { version = "0.3", default-features = false, features = ["std", "block2", "MPRemoteCommandCenter", "MPRemoteCommand", "MPRemoteCommandEvent", "MPNowPlayingInfoCenter", "MPMediaItem"] } [profile.release] -opt-level = 3 +opt-level = "s" lto = "fat" codegen-units = 1 panic = "abort" diff --git a/src/api.rs b/src/api.rs index c5d4d2f..a880ffb 100644 --- a/src/api.rs +++ b/src/api.rs @@ -270,12 +270,11 @@ pub async fn context_tracks(session: &Session, uri: &str) -> Res> if out.len() >= MAX_TRACKS { break; } + // A page that fails (librespot has retried it already) fails the whole list: a + // shortened one would replace the full copy on screen and on disk. if page.tracks.is_empty() && !page.page_url().is_empty() && fetched < MAX_PAGES { fetched += 1; - match fetch_page(session, page.page_url()).await { - Ok(p) => page = p, - Err(_) => continue, - } + page = fetch_page(session, page.page_url()).await?; } for t in &page.tracks { let u = t.uri(); @@ -291,9 +290,7 @@ pub async fn context_tracks(session: &Session, uri: &str) -> Res> } if !page.next_page_url().is_empty() && fetched < MAX_PAGES { fetched += 1; - if let Ok(p) = fetch_page(session, page.next_page_url()).await { - pages.push_front(p); - } + pages.push_front(fetch_page(session, page.next_page_url()).await?); } } out.truncate(MAX_TRACKS); @@ -346,7 +343,8 @@ fn track_row(uri: &str, t: &PTrack) -> Row { } /// Batched extended-metadata of one kind: the raw proto per uri (missing ones left out). -async fn ext_meta(session: &Session, uris: &[String], kind: ExtensionKind) -> HashMap> { +/// A failed request is an error, not an empty answer, so it can't quietly drop songs from a list. +async fn ext_meta(session: &Session, uris: &[String], kind: ExtensionKind) -> Res>> { let req = BatchedEntityRequest { entity_request: uris .iter() @@ -359,9 +357,7 @@ async fn ext_meta(session: &Session, uris: &[String], kind: ExtensionKind) -> Ha ..Default::default() }; let mut map = HashMap::with_capacity(uris.len()); - let Ok(resp) = session.spclient().get_extended_metadata(req).await else { - return map; - }; + let resp = session.spclient().get_extended_metadata(req).await.map_err(e)?; for arr in resp.extended_metadata { for d in arr.extension_data { if let Some(any) = d.extension_data.into_option() { @@ -369,7 +365,7 @@ async fn ext_meta(session: &Session, uris: &[String], kind: ExtensionKind) -> Ha } } } - map + Ok(map) } /// Spotify's web-player GraphQL ("pathfinder"), the only place play counts come from. @@ -452,18 +448,18 @@ fn set_plays(rows: &mut [Row], plays: &HashMap) { } } -async fn metadata_chunk(session: Session, uris: Vec) -> HashMap { - ext_meta(&session, &uris, ExtensionKind::TRACK_V4) - .await +async fn metadata_chunk(session: Session, uris: Vec) -> Res> { + Ok(ext_meta(&session, &uris, ExtensionKind::TRACK_V4) + .await? .into_iter() .filter_map(|(u, b)| PTrack::parse_from_bytes(&b).ok().map(|t| (u.clone(), track_row(&u, &t)))) - .collect() + .collect()) } /// Where a song lives: its album (uri, "Album — Artist") or, with `artist`, its first /// artist (uri, name). pub async fn track_home(session: &Session, uri: &str, artist: bool) -> Res<(String, String)> { - let bytes = ext_meta(session, &[uri.to_string()], ExtensionKind::TRACK_V4).await.remove(uri).ok_or("Spotify has no details for this song")?; + let bytes = ext_meta(session, &[uri.to_string()], ExtensionKind::TRACK_V4).await?.remove(uri).ok_or("Spotify has no details for this song")?; let t = PTrack::parse_from_bytes(&bytes).map_err(e)?; let first = t.artist.first(); if artist { @@ -482,8 +478,8 @@ fn gid_uri(kind: &str, gid: &[u8]) -> Option { } /// Metadata of one kind for many uris, 300 per request with 16 in flight; parsed in order. -async fn entities(session: &Session, uris: &[String], kind: ExtensionKind) -> Vec<(String, T)> { - let maps: Vec>> = +async fn entities(session: &Session, uris: &[String], kind: ExtensionKind) -> Res> { + let maps: Vec>>> = stream::iter(uris.chunks(META_CHUNK).map(<[String]>::to_vec)) .map(|c| { let s = session.clone(); @@ -492,8 +488,11 @@ async fn entities(session: &Session, uris: &[String], kind: Extensio .buffered(16) .collect() .await; - let mut all: HashMap> = maps.into_iter().flatten().collect(); - uris.iter().filter_map(|u| Some((u.clone(), T::parse_from_bytes(&all.remove(u)?).ok()?))).collect() + let mut all = HashMap::new(); + for m in maps { + all.extend(m?); + } + Ok(uris.iter().filter_map(|u| Some((u.clone(), T::parse_from_bytes(&all.remove(u)?).ok()?))).collect()) } fn album_row(uri: String, a: &PAlbum) -> Row { @@ -520,14 +519,14 @@ fn album_row(uri: String, a: &PAlbum) -> Row { } /// Album rows in the given order (name, artists, "2021 · single" in the album column). -pub async fn album_rows(session: &Session, uris: &[String]) -> Vec { - entities::(session, uris, ExtensionKind::ALBUM_V4).await.into_iter().map(|(u, a)| album_row(u, &a)).collect() +pub async fn album_rows(session: &Session, uris: &[String]) -> Res> { + Ok(entities::(session, uris, ExtensionKind::ALBUM_V4).await?.into_iter().map(|(u, a)| album_row(u, &a)).collect()) } /// An artist's page: top tracks, then albums, singles and compilations, newest first as /// Spotify lists them. Two metadata requests in parallel, after the artist's own. pub async fn artist_rows(session: &Session, uri: &str) -> Res> { - let raw = ext_meta(session, &[uri.to_string()], ExtensionKind::ARTIST_V4).await.remove(uri).ok_or("artist not found")?; + let raw = ext_meta(session, &[uri.to_string()], ExtensionKind::ARTIST_V4).await?.remove(uri).ok_or("artist not found")?; let a = PArtist::parse_from_bytes(&raw).map_err(e)?; let country = session.country(); let top: Vec = a @@ -544,24 +543,25 @@ pub async fn artist_rows(session: &Session, uri: &str) -> Res> { .filter_map(|g| g.album.first()) .filter_map(|al| gid_uri("album", al.gid())) .collect(); - let (mut rows, albums, plays) = tokio::join!(track_rows(session, top), album_rows(session, &releases), play_counts(session, uri)); + let (rows, albums, plays) = tokio::join!(track_rows(session, top), album_rows(session, &releases), play_counts(session, uri)); + let mut rows = rows?; set_plays(&mut rows, &plays); - rows.extend(albums); + rows.extend(albums?); Ok(rows) } /// Every track in a list, in order: tracks as they are, albums and playlists opened /// (8 at a time), duplicates dropped. Plays an artist's whole discography. -pub async fn expand(session: &Session, rows: &[Row]) -> Vec { +pub async fn expand(session: &Session, rows: &[Row]) -> Res> { let items: Vec<(Kind, String)> = rows.iter().map(|r| (r.kind, r.uri.clone())).collect(); - let lists: Vec> = stream::iter(items) + let lists: Vec>> = stream::iter(items) .map(|(kind, uri)| { let s = session.clone(); async move { match kind { - Kind::Track => vec![uri], - Kind::Album | Kind::Playlist => context_track_uris(&s, &uri).await.unwrap_or_default(), - Kind::Artist => Vec::new(), + Kind::Track => Ok(vec![uri]), + Kind::Album | Kind::Playlist => context_track_uris(&s, &uri).await, + Kind::Artist => Ok(Vec::new()), } } }) @@ -569,7 +569,11 @@ pub async fn expand(session: &Session, rows: &[Row]) -> Vec { .collect() .await; let mut seen = std::collections::HashSet::new(); - let uris: Vec = lists.into_iter().flatten().filter(|u| seen.insert(u.clone())).take(MAX_TRACKS).collect(); + let mut uris = Vec::new(); + for list in lists { + uris.extend(list?.into_iter().filter(|u| seen.insert(u.clone()))); + } + uris.truncate(MAX_TRACKS); track_rows(session, uris).await } @@ -577,7 +581,7 @@ pub async fn expand(session: &Session, rows: &[Row]) -> Vec { async fn followed_artist_rows(session: &Session) -> Res> { let uris = crate::library::collection(session, "artist").await?; Ok(entities::(session, &uris, ExtensionKind::ARTIST_V4) - .await + .await? .into_iter() .map(|(uri, a)| artist_row(uri, a.name())) .collect()) @@ -598,10 +602,10 @@ fn artist_row(uri: String, name: &str) -> Row { } } -/// Turn track URIs into display rows, keeping order. Batched + 4 requests in flight. -pub async fn track_rows(session: &Session, uris: Vec) -> Vec { +/// Turn track URIs into display rows, keeping order. Batched, 16 requests in flight. +pub async fn track_rows(session: &Session, uris: Vec) -> Res> { let chunks: Vec> = uris.chunks(META_CHUNK).map(<[String]>::to_vec).collect(); - let maps: Vec> = stream::iter(chunks) + let maps: Vec>> = stream::iter(chunks) .map(|c| metadata_chunk(session.clone(), c)) .buffered(16) .collect() @@ -609,7 +613,7 @@ pub async fn track_rows(session: &Session, uris: Vec) -> Vec { let mut rows = Vec::with_capacity(uris.len()); let mut maps = maps.into_iter(); for chunk in uris.chunks(META_CHUNK) { - let map = maps.next().unwrap_or_default(); + let map = maps.next().transpose()?.unwrap_or_default(); for u in chunk { // tracks with no metadata are region-locked/removed; drop them if let Some(r) = map.get(u) { @@ -617,7 +621,7 @@ pub async fn track_rows(session: &Session, uris: Vec) -> Vec { } } } - rows + Ok(rows) } /// Songs Spotify recommends for a list (its radio station), for smart shuffle. Seeded by @@ -635,7 +639,7 @@ pub async fn recommendations(session: &Session, list: &str, track: &str) -> Vec< if uris.is_empty() { uris = station(session, track).await; } - track_rows(session, uris).await + track_rows(session, uris).await.unwrap_or_default() } fn station_uris(v: &Value) -> Vec { @@ -655,7 +659,7 @@ pub async fn context_rows(session: &Session, uri: &str, known: &[Row]) -> Res = crate::library::collection(session, "collection").await?.into_iter().filter(|u| u.starts_with("spotify:album:")).collect(); - return Ok(album_rows(session, &uris).await); + return album_rows(session, &uris).await; } if uri == FOLLOWED_ARTISTS { return followed_artist_rows(session).await; @@ -668,7 +672,7 @@ pub async fn context_rows(session: &Session, uri: &str, known: &[Row]) -> Res = known.iter().filter(|r| r.kind == Kind::Track).map(|r| (r.uri.as_str(), r)).collect(); let mut missing: Vec = tracks.iter().filter(|t| !have.contains_key(t.uri.as_str())).map(|t| t.uri.clone()).collect(); missing.dedup(); - let fetched: HashMap = track_rows(session, missing).await.into_iter().map(|r| (r.uri.clone(), r)).collect(); + let fetched: HashMap = track_rows(session, missing).await?.into_iter().map(|r| (r.uri.clone(), r)).collect(); // tracks with no metadata are region-locked/removed; they stay dropped let mut rows: Vec = tracks .into_iter() @@ -921,7 +925,7 @@ async fn rich_search(session: &Session, own: Option>>, q: &s async fn basic_search(session: &Session, q: &str) -> Res> { let mut uris = context_track_uris(session, &format!("spotify:search:{}", pct(q))).await?; uris.truncate(50); - let tracks = entities::(session, &uris, ExtensionKind::TRACK_V4).await; + let tracks = entities::(session, &uris, ExtensionKind::TRACK_V4).await?; Ok(search_rows(&tracks)) } diff --git a/src/app.rs b/src/app.rs index f2a0346..db2932f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -33,7 +33,7 @@ pub enum Msg { /// Every liked track, saved album and followed artist (for the ♥ markers and `f`). Liked(Result, String>), /// `P`: every track in the open list, ready to play. - PlayAll(Vec), + PlayAll(Result, String>), LikeDone { row: Row, liked: bool, res: Result<(), String> }, Lyrics { uri: String, res: Result, String> }, Art { url: String, size: (u16, u16), res: Result<(ratatui_image::protocol::Protocol, bytes::Bytes), String> }, @@ -260,9 +260,10 @@ pub struct App { pub quit: bool, // playback + /// The list playing. `order` indexes `ctx` and then `recs` (see [`App::at`]). ctx: Rows, - /// ctx[..base] is the list; ctx[base..] are smart-shuffle recommendations. - base: usize, + /// Smart-shuffle recommendations, kept apart so a big list isn't copied to add them. + recs: Vec, /// The list the playing context came from (uri, title), for `w`. ctx_src: (String, String), /// `w` opened that list: select the playing song once it's shown. @@ -392,7 +393,7 @@ impl App { loading: false, quit: false, ctx: Arc::new(Vec::new()), - base: 0, + recs: Vec::new(), ctx_src: (String::new(), String::new()), jump: false, order: Vec::new(), @@ -528,7 +529,7 @@ impl App { return; } let (uri, title) = self.ctx_src.clone(); - if !self.now.as_ref().is_some_and(|n| self.ctx[..self.base].iter().any(|r| r.uri == n.uri)) { + if !self.now.as_ref().is_some_and(|n| self.ctx.iter().any(|r| r.uri == n.uri)) { // A recommendation, or a song started elsewhere: it's in no list we know of. self.show_now_in_queue(); return; @@ -622,7 +623,7 @@ impl App { } let start = if self.now.is_some() { self.cursor + 1 } else { self.cursor }; for p in start..(start + 100).min(self.order.len()) { - rows.push(self.ctx[self.order[p]].clone()); + rows.push(self.at(self.order[p]).clone()); self.queue_src.push(QSrc::Upcoming(p)); } self.show("trill:queue".into(), format!("Queue — {} manual, {} upcoming", self.queue.len(), rows.len().saturating_sub(self.queue.len() + self.now.is_some() as usize)), Arc::new(rows)); @@ -670,7 +671,9 @@ impl App { self.replace_view_rows(rows); } } - Err(e) if is_current => self.status = format!("Couldn't load {title}: {e}"), + Err(e) if is_current => self.status = format!("Couldn't load {title}: {e} (R to retry)"), + // the copy on screen came from disk and stays + Err(e) if self.view.uri == uri => self.status = format!("{title}: saved copy, couldn't refresh it: {e}"), Err(_) => {} } if is_current { @@ -734,7 +737,7 @@ impl App { /// Rebuild `order`, keeping the current track at the cursor. fn reorder(&mut self, keep: Option) { - self.order = (0..self.base).collect(); + self.order = (0..self.ctx.len()).collect(); if self.shuffle { for i in (1..self.order.len()).rev() { let j = (self.rand() % (i as u64 + 1)) as usize; @@ -754,13 +757,19 @@ impl App { /// Smart shuffle: one recommendation after every 3 songs still to come. fn weave(&mut self) { if self.smart { - weave(&mut self.order, self.cursor + 1, self.base..self.ctx.len()); + let n = self.ctx.len(); + weave(&mut self.order, self.cursor + 1, n..n + self.recs.len()); } } /// Whether `uri` is playing as a smart-shuffle recommendation (shown with ✦). pub fn is_rec(&self, uri: &str) -> bool { - self.ctx[self.base..].iter().any(|r| r.uri == uri) + self.recs.iter().any(|r| r.uri == uri) + } + + /// Entry `i` of the play order's index space: the list, then the recommendations. + fn at(&self, i: usize) -> &Row { + self.ctx.get(i).unwrap_or_else(|| &self.recs[i - self.ctx.len()]) } fn fetch_recs(&self) { @@ -795,10 +804,10 @@ impl App { let pos = if tracks.get(before).map(|r| &r.uri) == Some(target) { before } else { 0 }; self.ctx = if tracks.len() == rows.len() { rows.clone() } else { Arc::new(tracks) }; self.ctx_src = (self.view.uri.clone(), self.view.title.clone()); - self.base = self.ctx.len(); + self.recs.clear(); self.reorder(Some(pos)); self.skips = 0; - let row = self.ctx[self.order[self.cursor]].clone(); + let row = self.at(self.order[self.cursor]).clone(); self.load(row); if self.smart { self.fetch_recs(); @@ -814,9 +823,9 @@ impl App { } let p = self.cursor + 1; if p < self.order.len() { - Some(self.ctx[self.order[p]].clone()) + Some(self.at(self.order[p]).clone()) } else if self.repeat == Repeat::All && !self.order.is_empty() { - Some(self.ctx[self.order[0]].clone()) + Some(self.at(self.order[0]).clone()) } else { None } @@ -842,7 +851,7 @@ impl App { self.status = "End of list".into(); return None; } - Some(self.ctx[self.order[self.cursor]].clone()) + Some(self.at(self.order[self.cursor]).clone()) } fn next(&mut self, auto: bool) { @@ -872,7 +881,7 @@ impl App { } else if self.repeat == Repeat::All { self.cursor = self.order.len() - 1; } - let row = self.ctx[self.order[self.cursor]].clone(); + let row = self.at(self.order[self.cursor]).clone(); self.load(row); } @@ -1315,10 +1324,10 @@ impl App { (self.shuffle, self.smart) = (on, on && smart); self.save_prefs(); // A playing recommendation isn't in the list's order: carry on after the list song before it. - let cur = self.order.get(..=self.cursor).and_then(|o| o.iter().rev().find(|&&c| c < self.base).copied()); + let cur = self.order.get(..=self.cursor).and_then(|o| o.iter().rev().find(|&&c| c < self.ctx.len()).copied()); self.reorder(cur); self.weave(); - if self.smart && self.ctx.len() == self.base && !self.ctx.is_empty() { + if self.smart && self.recs.is_empty() && !self.ctx.is_empty() { self.fetch_recs(); } self.refresh_queue_view(); @@ -1345,7 +1354,7 @@ impl App { } Some(QSrc::Upcoming(p)) if p < self.order.len() => { self.cursor = p; - let r = self.ctx[self.order[p]].clone(); + let r = self.at(self.order[p]).clone(); self.load(r); } _ => {} diff --git a/src/app/extras.rs b/src/app/extras.rs index 6363db6..2c43216 100644 --- a/src/app/extras.rs +++ b/src/app/extras.rs @@ -392,7 +392,7 @@ impl App { } // A song playing outside its list (a recommendation, say) most likely belongs in that list. let mut c = Chooser { track, filter: String::new(), sel: 0, holding, checking }; - if !self.ctx[..self.base].iter().any(|r| r.uri == c.track.uri) + if !self.ctx.iter().any(|r| r.uri == c.track.uri) && let Some(i) = c.matches(self).iter().position(|(u, _)| *u == self.ctx_src.0) { c.sel = i; @@ -654,8 +654,9 @@ impl App { self.status = format!("Couldn't update your library: {e}"); } Msg::LikeDone { .. } => {} - Msg::PlayAll(rows) if rows.is_empty() => self.status = "Nothing to play here.".into(), - Msg::PlayAll(rows) => { + Msg::PlayAll(Ok(rows)) if rows.is_empty() => self.status = "Nothing to play here.".into(), + Msg::PlayAll(Err(e)) => self.status = format!("Couldn't load everything: {e}"), + Msg::PlayAll(Ok(rows)) => { let n = rows.len(); self.play_list(&Arc::new(rows), 0); self.status = format!("Playing all {n} tracks"); @@ -753,17 +754,17 @@ impl App { } }, Msg::Recs { list, rows } => { - if !self.smart || list != self.ctx_src.0 || self.ctx.len() != self.base { + if !self.smart || list != self.ctx_src.0 || !self.recs.is_empty() { return; } if rows.is_empty() { self.status = "Spotify has no recommendations for this list.".into(); return; } - let mut have: HashSet = self.ctx.iter().map(|r| r.uri.clone()).collect(); - let mut ctx: Vec = self.ctx.to_vec(); - ctx.extend(rows.into_iter().filter(|r| have.insert(r.uri.clone()))); - self.ctx = Arc::new(ctx); + let have: HashSet<&str> = self.ctx.iter().map(|r| r.uri.as_str()).collect(); + let mut seen = HashSet::new(); + let recs: Vec = rows.into_iter().filter(|r| !have.contains(r.uri.as_str()) && seen.insert(r.uri.clone())).collect(); + self.recs = recs; self.weave(); self.refresh_queue_view(); } diff --git a/src/auth.rs b/src/auth.rs index 0c030ff..a985e19 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -12,7 +12,7 @@ use std::{ time::Instant, }; -use librespot_core::{Session, SessionConfig, authentication::Credentials, cache::Cache}; +use librespot_core::{Session, SessionConfig, authentication::Credentials, cache::Cache, error::ErrorKind}; use librespot_oauth::{OAuthClient, OAuthClientBuilder}; const SESSION_REDIRECT: &str = "http://127.0.0.1:5588/login"; @@ -44,6 +44,10 @@ pub async fn connect(session: &Session, cache: &Cache) -> Result<(), String> { if let Some(creds) = cache.credentials() { match session.connect(creds, true).await { Ok(()) => return Ok(()), + // Offline or Spotify unreachable: the saved login is fine, so don't ask for a new one. + Err(e) if !matches!(e.kind, ErrorKind::PermissionDenied | ErrorKind::Unauthenticated) => { + return Err(format!("can't reach Spotify ({e}). Your saved login is kept; check the connection and start trill again.")); + } Err(e) => { if crossterm::terminal::is_raw_mode_enabled().unwrap_or(false) { ratatui::restore(); diff --git a/src/main.rs b/src/main.rs index 06f67d7..ca7cddd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -122,7 +122,7 @@ fn main() { // Hidden diagnostics: which image protocol / font size this terminal reports. if has("--debug-term") { let t0 = std::time::Instant::now(); - match query_terminal_images() { + match query_terminal_images(&cfg.cache_dir) { Some(p) => eprintln!("{:?} font {:?} in {} ms", p.protocol_type(), p.font_size(), t0.elapsed().as_millis()), None => eprintln!("no picker in {} ms", t0.elapsed().as_millis()), } @@ -131,10 +131,13 @@ fn main() { // Every helper thread gets its own malloc arena that is never handed back; with a few // short-lived DNS/file threads that's megabytes of RSS for nothing. Two arenas is plenty. + // A fixed mmap threshold also stops glibc raising it (and the trim threshold with it) after + // each decoded cover is freed, which left ~7 MB of free heap resident in the second arena. // SAFETY: called before any other threads exist. #[cfg(target_os = "linux")] unsafe { libc::mallopt(libc::M_ARENA_MAX, 2); + libc::mallopt(libc::M_MMAP_THRESHOLD, 256 * 1024); } let go = move || { let rt = tokio::runtime::Builder::new_current_thread() @@ -260,40 +263,79 @@ fn pair_soloist(cfg: &Config) -> i32 { } } +/// Which terminal this is, as far as the environment tells: the key under which a terminal that +/// didn't answer the image query is remembered. +fn terminal_id() -> String { + let get = |k: &str| env::var(k).unwrap_or_default(); + let has = |k: &'static str| if env::var_os(k).is_some_and(|v| !v.is_empty()) { k } else { "" }; + [get("TERM"), get("TERM_PROGRAM"), get("TERM_PROGRAM_VERSION"), get("LC_TERMINAL"), get("KONSOLE_VERSION"), get("VTE_VERSION")] + .into_iter() + .chain(["TMUX", "WT_SESSION", "KITTY_WINDOW_ID", "WEZTERM_EXECUTABLE", "ITERM_SESSION_ID", "GHOSTTY_RESOURCES_DIR"].map(|k| has(k).to_string())) + .collect::>() + .join("|") +} + +/// Terminals that didn't answer the image query, one `terminal_id` per line. Re-asked after a +/// week, in case one learns to answer (or tmux gets attached from a terminal that does). +fn silent_terminals(cache: &std::path::Path) -> (std::path::PathBuf, String) { + let file = cache.join("silent_terminals"); + let fresh = fs::metadata(&file).and_then(|m| m.modified()).is_ok_and(|t| t.elapsed().is_ok_and(|d| d < Duration::from_secs(7 * 86400))); + let text = if fresh { fs::read_to_string(&file).unwrap_or_default() } else { String::new() }; + (file, text) +} + /// Which image protocol the terminal supports. Terminals answer in a few ms; if one doesn't, /// ratatui-image gives up but leaves a thread blocked reading stdin, which would eat the /// first keypresses. A Device Status Report query (which every terminal, and tmux itself, /// answers) completes that read so the thread exits before we start reading keys. -fn query_terminal_images() -> Option { - use ratatui_image::picker::{Picker, cap_parser::QueryStdioOptions}; +/// A terminal that didn't answer is remembered, so the next start skips the ~0.5 s wait and +/// goes straight to what the timeout would have given. +fn query_terminal_images(cache: &std::path::Path) -> Option { + use ratatui_image::picker::{Picker, ProtocolType, cap_parser::QueryStdioOptions}; use std::io::Write; const TIMEOUT: Duration = Duration::from_millis(400); let t0 = std::time::Instant::now(); - let mut picker = Picker::from_query_stdio_with_options(QueryStdioOptions { timeout: TIMEOUT, ..Default::default() }).ok(); + let id = terminal_id(); + let (file, silent) = silent_terminals(cache); + let mut picker = if silent.lines().any(|l| l == id) { + // ratatui-image's own fallback: the font size from the window's pixel size, if known + #[allow(deprecated)] + Some(match crossterm::terminal::window_size() { + Ok(w) if w.width > 0 && w.height > 0 && w.columns > 0 && w.rows > 0 => { + Picker::from_fontsize(ratatui_image::FontSize::new(w.width / w.columns, w.height / w.rows)) + } + _ => Picker::halfblocks(), + }) + } else { + let p = Picker::from_query_stdio_with_options(QueryStdioOptions { timeout: TIMEOUT, ..Default::default() }).ok(); + if t0.elapsed() >= TIMEOUT { + let mut out = std::io::stdout(); + let _ = out.write_all(b"\x1b[5n"); + let _ = out.flush(); + std::thread::sleep(Duration::from_millis(100)); + let _ = fs::create_dir_all(cache); + let _ = fs::write(&file, format!("{silent}{id}\n")); + } + p + }; // Konsole draws iTerm2 inline images (its sixel/kitty support is buggy, so ratatui-image // rules those out) but has no env var announcing it, so ratatui-image falls back to // half-blocks. Use iTerm2 there (not through tmux, which would need passthrough). if let Some(p) = picker.as_mut() && env::var_os("KONSOLE_VERSION").is_some() && !p.tmux_detected() - && p.protocol_type() == ratatui_image::picker::ProtocolType::Halfblocks + && p.protocol_type() == ProtocolType::Halfblocks { - p.set_protocol_type(ratatui_image::picker::ProtocolType::Iterm2); + p.set_protocol_type(ProtocolType::Iterm2); } // VS Code is guessed to be iTerm2 from TERM_PROGRAM alone, but it only draws images with // `terminal.integrated.enableImages` on, and then it also answers the query with sixel. // A guess that the query didn't back up would draw nothing, so use half-blocks there. if let Some(p) = picker.as_mut() && env::var("TERM_PROGRAM").is_ok_and(|t| t == "vscode") - && p.protocol_type() == ratatui_image::picker::ProtocolType::Iterm2 + && p.protocol_type() == ProtocolType::Iterm2 { - p.set_protocol_type(ratatui_image::picker::ProtocolType::Halfblocks); - } - if t0.elapsed() >= TIMEOUT { - let mut out = std::io::stdout(); - let _ = out.write_all(b"\x1b[5n"); - let _ = out.flush(); - std::thread::sleep(Duration::from_millis(100)); + p.set_protocol_type(ProtocolType::Halfblocks); } picker } @@ -371,9 +413,8 @@ async fn run(cfg: Config) -> i32 { // Ask the terminal which image protocol it speaks (kitty / sixel / iTerm2, else // half-block characters) while we log in. Must finish before we read key events. let mut picker_query = (cfg.art && std::io::IsTerminal::is_terminal(&std::io::stdout())).then(|| { - std::thread::Builder::new() - .name("term-query".into()) - .spawn(query_terminal_images) + let dir = cfg.cache_dir.clone(); + std::thread::Builder::new().name("term-query".into()).spawn(move || query_terminal_images(&dir)) }); let session = Session::new(session_cfg.clone(), Some(cache.clone())); let cached_user = cache.credentials().and_then(|c| c.username); @@ -512,7 +553,7 @@ async fn run(cfg: Config) -> i32 { Some("pins") => library::pins(&session).await.map(|p| p.iter().for_each(|u| eprintln!("{u}"))), Some("all") => match api::context_rows(&session, &a[1], &[]).await { Ok(rows) => { - let all = api::expand(&session, &rows).await; + let all = api::expand(&session, &rows).await.unwrap_or_default(); eprintln!("{} tracks; first: {:?}", all.len(), all.iter().take(12).map(|r| r.title.as_str()).collect::>()); Ok(()) } @@ -648,7 +689,7 @@ async fn run(cfg: Config) -> i32 { { seek_end = false; // duration comes from our own metadata so it works on both engines - let rows = api::track_rows(&session, vec![uri.clone()]).await; + let rows = api::track_rows(&session, vec![uri.clone()]).await.unwrap_or_default(); if let Some(r) = rows.first() { tokio::time::sleep(Duration::from_secs(2)).await; let lead = seek_lead.unwrap_or(6000); @@ -704,7 +745,7 @@ async fn run(cfg: Config) -> i32 { let mut desktop = None; match &preview { Some(uri) => { - app.now = api::track_rows(&app.session, vec![uri.clone()]).await.into_iter().next(); + app.now = api::track_rows(&app.session, vec![uri.clone()]).await.ok().and_then(|r| r.into_iter().next()); // optional: a list to open, and its title (`--preview `) let mut rest = env::args().skip_while(|a| a != "--preview").skip(2); if let (Some(list), Some(title)) = (rest.next(), rest.next()) { @@ -738,8 +779,8 @@ async fn run(cfg: Config) -> i32 { let mut tick = interval(Duration::from_secs(1)); tick.set_missed_tick_behavior(MissedTickBehavior::Skip); - let mut health = interval(Duration::from_secs(15)); - health.set_missed_tick_behavior(MissedTickBehavior::Skip); + // When the last reconnect was tried (one try per 15 s at most). + let mut reconnect_at: Option<std::time::Instant> = None; let mut dirty = true; loop { @@ -815,25 +856,26 @@ async fn run(cfg: Config) -> i32 { app.check_resume(); dirty = true; } - _ = health.tick() => { - if app.session.is_invalid() { - app.status = "Connection lost, reconnecting…".into(); - let _ = term.draw(|f| ui::draw(f, &mut app)); - let s = Session::new(session_cfg.clone(), Some(cache.clone())); - match timeout(Duration::from_secs(10), auth::reconnect(&s, &cache)).await { - Ok(Ok(())) => { - if let Engine::Librespot { player, .. } = &app.engine { - player.set_session(s.clone()); - } - app.session = s; - app.status = "Reconnected.".into(); - } - Ok(Err(e)) => app.status = format!("Reconnect failed: {e} (retrying)"), - Err(_) => app.status = "Reconnect timed out (retrying)".into(), + } + // A lost connection is noticed on the next key, event or second of playback rather + // than by a timer, so an idle trill never wakes up just to check. + if !app.quit && app.session.is_invalid() && reconnect_at.is_none_or(|t| t.elapsed() >= Duration::from_secs(15)) { + reconnect_at = Some(std::time::Instant::now()); + app.status = "Connection lost, reconnecting…".into(); + let _ = term.draw(|f| ui::draw(f, &mut app)); + let s = Session::new(session_cfg.clone(), Some(cache.clone())); + match timeout(Duration::from_secs(10), auth::reconnect(&s, &cache)).await { + Ok(Ok(())) => { + if let Engine::Librespot { player, .. } = &app.engine { + player.set_session(s.clone()); } - dirty = true; + app.session = s; + app.status = "Reconnected.".into(); } + Ok(Err(e)) => app.status = format!("Reconnect failed: {e} (retrying)"), + Err(_) => app.status = "Reconnect timed out (retrying)".into(), } + dirty = true; } }