use crossbeam_channel::{unbounded, Receiver, Sender}; use lru::LruCache; use std::collections::HashSet; use std::num::NonZeroUsize; use std::sync::Arc; use crate::engine::textures::TextureRegistry; use crate::engine::types::{Color, TextureId}; /// Hard minimum LRU cover cache capacity so even dense pages (Artist/Collection + sidebar + player) /// can never thrash or flicker visible avatars/covers. pub const MIN_COVER_CACHE_CAPACITY: usize = 128; const MAX_AUTO_GROW_CAPACITY: usize = 1024; pub struct CoverEntry { pub texture_id: TextureId, pub dominant_color: Color, pub hue: f32, pub last_used_frame: u64, } struct DecodedCover { key: String, width: u32, height: u32, rgba_unpremul: Vec, dominant_color: Color, hue: f32, } enum CoverFetchOutcome { Ok(DecodedCover), Failed(String), } /// Strictly bounded async LRU album-cover cache. /// Evicts least-recently-used GPU textures via `TextureRegistry` so VRAM & RAM stay flat. pub struct CoverCache { cache: LruCache, in_flight: HashSet, failed: HashSet, frame_id: u64, tx_done: Sender, rx_done: Receiver, http: reqwest::Client, runtime: tokio::runtime::Handle, } impl CoverCache { pub fn new(max_entries: usize, runtime: tokio::runtime::Handle) -> Self { let (tx_done, rx_done) = unbounded(); let http = reqwest::Client::builder() .user_agent("YandexMusicDesktop/5.129.0 (Windows NT 10.0; Win64; x64)") .timeout(std::time::Duration::from_secs(8)) .pool_max_idle_per_host(6) .build() .unwrap_or_default(); Self { cache: LruCache::new( NonZeroUsize::new(max_entries.max(MIN_COVER_CACHE_CAPACITY)).unwrap(), ), in_flight: HashSet::new(), failed: HashSet::new(), frame_id: 1, tx_done, rx_done, http, runtime, } } pub fn begin_frame(&mut self) { self.frame_id = self.frame_id.wrapping_add(1).max(1); } pub fn capacity(&self) -> usize { self.cache.cap().get() } pub fn set_capacity(&mut self, max_entries: usize) { self.cache .resize(NonZeroUsize::new(max_entries.max(MIN_COVER_CACHE_CAPACITY)).unwrap()); } pub fn clear(&mut self, textures: &mut TextureRegistry) { while let Some((_, entry)) = self.cache.pop_lru() { textures.free(entry.texture_id); } self.failed.clear(); } pub fn len(&self) -> usize { self.cache.len() } pub fn is_empty(&self) -> bool { self.cache.is_empty() } pub fn in_flight_count(&self) -> usize { self.in_flight.len() } pub fn failed_count(&self) -> usize { self.failed.len() } /// Insert an entry without evicting any entry actively rendered in the current frame. fn put_protected( &mut self, textures: &mut TextureRegistry, key: String, entry: CoverEntry, ) { let cap = self.cache.cap().get(); if self.cache.len() >= cap && !self.cache.contains(&key) { if let Some((_, lru_entry)) = self.cache.peek_lru() { if lru_entry.last_used_frame == self.frame_id && cap < MAX_AUTO_GROW_CAPACITY { let grown = (cap + 32).min(MAX_AUTO_GROW_CAPACITY); self.cache.resize(NonZeroUsize::new(grown).unwrap()); } } } if let Some((_, evicted)) = self.cache.push(key, entry) { textures.free(evicted.texture_id); } } /// Pre-populate a cover texture at one specific resolution (useful for testing mipmap reuse). pub fn insert_test_rgba_at_size( &mut self, textures: &mut TextureRegistry, uri: &str, size_px: u32, rgba: &[u8], width: usize, height: usize, ) -> TextureId { let (dom, hue) = analyze_dominant_color_rgba(rgba); let url = Self::format_url(uri, size_px); let tex_id = textures.create_rgba_unpremul(width as u32, height as u32, rgba); let frame_id = self.frame_id; self.put_protected( textures, url, CoverEntry { texture_id: tex_id, dominant_color: dom, hue, last_used_frame: frame_id, }, ); tex_id } /// Pre-populate a cover texture directly in memory for deterministic offline visual tests. pub fn insert_test_rgba( &mut self, textures: &mut TextureRegistry, uri: &str, rgba: &[u8], width: usize, height: usize, ) { let (dom, hue) = analyze_dominant_color_rgba(rgba); let frame_id = self.frame_id; for size_px in [100u32, 200u32, 400u32] { let url = Self::format_url(uri, size_px); let tex_id = textures.create_rgba_unpremul(width as u32, height as u32, rgba); self.put_protected( textures, url, CoverEntry { texture_id: tex_id, dominant_color: dom, hue, last_used_frame: frame_id, }, ); } } /// Drain newly decoded covers into `TextureRegistry` (called once per frame on UI thread). /// Returns true if any new cover arrived (triggers repaint). pub fn poll_uploads(&mut self, textures: &mut TextureRegistry) -> bool { let mut any = false; let mut uploaded = 0usize; let frame_id = self.frame_id; // Always drain failure notifications so `in_flight` can never stall; // cap texture uploads per frame to prevent frame-time spikes. while uploaded < 8 { let Ok(outcome) = self.rx_done.try_recv() else { break; }; match outcome { CoverFetchOutcome::Ok(done) => { self.in_flight.remove(&done.key); let tex_id = textures.create_rgba_unpremul( done.width, done.height, &done.rgba_unpremul, ); self.put_protected( textures, done.key, CoverEntry { texture_id: tex_id, dominant_color: done.dominant_color, hue: done.hue, last_used_frame: frame_id, }, ); any = true; uploaded += 1; } CoverFetchOutcome::Failed(key) => { self.in_flight.remove(&key); self.failed.insert(key); } } } self.begin_frame(); any } /// Normalize a Yandex cover URI (e.g. `avatars.yandex.net/get-music-content/.../%%`) /// to a full HTTPS URL at the exact needed resolution (`100x100`, `200x200`, `400x400`). pub fn format_url(uri: &str, size_px: u32) -> String { let size_str = if size_px <= 100 { "100x100" } else if size_px <= 200 { "200x200" } else { "400x400" }; let replaced = uri.replace("%%", size_str); if replaced.starts_with("http://") || replaced.starts_with("https://") { replaced } else { format!("https://{}", replaced.trim_start_matches('/')) } } /// Returns `(TextureId, dominant_color, hue)` if loaded, or triggers background fetch. /// Reuses an already-cached higher-resolution entry (`200x200` / `400x400`) when available /// because our Vulkan SDF renderer samples full hardware mipmap chains cleanly at any size! pub fn get_or_fetch(&mut self, uri: &str, size_px: u32) -> Option<(TextureId, Color, f32)> { if uri.is_empty() { return None; } let frame_id = self.frame_id; let url = Self::format_url(uri, size_px); if let Some(entry) = self.cache.get_mut(&url) { entry.last_used_frame = frame_id; return Some((entry.texture_id, entry.dominant_color, entry.hue)); } // Cross-resolution mipmap reuse: if a higher-resolution variant is already cached, // reuse it immediately (zero extra network fetch and zero duplicate LRU slot!). let higher_sizes: &[u32] = if size_px <= 100 { &[200, 400] } else if size_px <= 200 { &[400] } else { &[] }; for &hi in higher_sizes { let hi_url = Self::format_url(uri, hi); if hi_url == url { continue; } if let Some(entry) = self.cache.get_mut(&hi_url) { entry.last_used_frame = frame_id; return Some((entry.texture_id, entry.dominant_color, entry.hue)); } if self.in_flight.contains(&hi_url) { return None; } } if uri.starts_with("test.local/") { return None; } if self.in_flight.contains(&url) || self.failed.contains(&url) { return None; } // Cap concurrent cover downloads to keep memory & sockets minimal if self.in_flight.len() >= 16 { return None; } self.in_flight.insert(url.clone()); let http = self.http.clone(); let tx = self.tx_done.clone(); let key = url.clone(); let target_px = size_px.clamp(128, 400); self.runtime.spawn(async move { let Ok(resp) = http.get(&url).send().await else { let _ = tx.send(CoverFetchOutcome::Failed(key)); return; }; if !resp.status().is_success() { let _ = tx.send(CoverFetchOutcome::Failed(key)); return; } let Ok(bytes) = resp.bytes().await else { let _ = tx.send(CoverFetchOutcome::Failed(key)); return; }; // High-quality Lanczos3 downscale to target display resolution (matches Chromium anti-aliasing) let res = tokio::task::spawn_blocking(move || decode_and_analyze(&bytes, target_px)).await; if let Ok(Some((width, height, rgba_unpremul, dominant_color, hue))) = res { let _ = tx.send(CoverFetchOutcome::Ok(DecodedCover { key, width, height, rgba_unpremul, dominant_color, hue, })); } else { let _ = tx.send(CoverFetchOutcome::Failed(key)); } }); None } } fn decode_and_analyze(bytes: &[u8], target_px: u32) -> Option<(u32, u32, Vec, Color, f32)> { let mut dyn_img = image::load_from_memory(bytes).ok()?; let (ow, oh) = (dyn_img.width(), dyn_img.height()); let max_dim = target_px.max(128); if ow > max_dim || oh > max_dim { dyn_img = dyn_img.resize_exact(max_dim, max_dim, image::imageops::FilterType::Lanczos3); } let rgba = dyn_img.to_rgba8(); let (w, h) = rgba.dimensions(); let raw = rgba.into_raw(); let (dominant, hue) = analyze_dominant_color_rgba(&raw); Some((w, h, raw, dominant, hue)) } fn analyze_dominant_color_rgba(raw: &[u8]) -> (Color, f32) { let px_count = raw.len() / 4; if px_count == 0 { return (Color::rgb(255, 210, 40), 0.13); } let mut r_sum = 0u64; let mut g_sum = 0u64; let mut b_sum = 0u64; let mut weight_sum = 0u64; let stride = (px_count / 256).max(1); for px in raw.chunks_exact(4).step_by(stride) { let (r, g, b) = (px[0], px[1], px[2]); let max_c = r.max(g).max(b) as i32; let min_c = r.min(g).min(b) as i32; let sat = (max_c - min_c) as u64; let wgt = 1 + sat * 2; r_sum += r as u64 * wgt; g_sum += g as u64 * wgt; b_sum += b as u64 * wgt; weight_sum += wgt; } let (dr, dg, db) = if weight_sum > 0 { ( (r_sum / weight_sum) as u8, (g_sum / weight_sum) as u8, (b_sum / weight_sum) as u8, ) } else { (255, 210, 40) }; (Color::rgb(dr, dg, db), rgb_to_hue(dr, dg, db)) } pub fn rgb_to_hue(r: u8, g: u8, b: u8) -> f32 { let rf = r as f32 / 255.0; let gf = g as f32 / 255.0; let bf = b as f32 / 255.0; let max = rf.max(gf).max(bf); let min = rf.min(gf).min(bf); let delta = max - min; if delta < 0.001 { return 0.13; // Signature Yandex golden hue fallback } let h = if (max - rf).abs() < 1e-5 { ((gf - bf) / delta) % 6.0 } else if (max - gf).abs() < 1e-5 { (bf - rf) / delta + 2.0 } else { (rf - gf) / delta + 4.0 }; let mut hue = h / 6.0; if hue < 0.0 { hue += 1.0; } hue } /// Deterministic vibrant cover gradient colors for placeholders / offline items. pub fn deterministic_cover_palette(seed: &str) -> (Color, Color, f32) { let mut hash: u32 = 2166136261; for b in seed.bytes() { hash ^= b as u32; hash = hash.wrapping_mul(16777619); } const PALETTES: &[(Color, Color, f32)] = &[ (Color::rgb(255, 196, 0), Color::rgb(230, 72, 92), 0.12), (Color::rgb(131, 65, 239), Color::rgb(63, 104, 249), 0.72), (Color::rgb(255, 92, 77), Color::rgb(235, 70, 159), 0.94), (Color::rgb(38, 198, 154), Color::rgb(28, 118, 210), 0.48), (Color::rgb(245, 130, 32), Color::rgb(156, 39, 176), 0.07), (Color::rgb(55, 200, 79), Color::rgb(16, 120, 96), 0.36), (Color::rgb(236, 64, 122), Color::rgb(94, 53, 177), 0.88), (Color::rgb(41, 182, 246), Color::rgb(48, 63, 159), 0.56), ]; PALETTES[(hash as usize) % PALETTES.len()] } pub type SharedCoverPlaceholder = Arc;