use std::cell::RefCell;
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::IpAddr;
use std::sync::mpsc;
use std::time::Duration;
use image::DynamicImage;
const MAX_CACHE_SIZE: usize = 20;
const FETCH_TIMEOUT: Duration = Duration::from_secs(3);
struct LoadRequest {
uri: String,
full_url: String,
}
struct LoadResult {
uri: String,
image: Option<DynamicImage>,
}
pub struct ImageLoader {
cache: HashMap<String, DynamicImage>,
insertion_order: VecDeque<String>,
pending: RefCell<HashSet<String>>,
result_rx: mpsc::Receiver<LoadResult>,
request_tx: mpsc::Sender<LoadRequest>,
}
impl Default for ImageLoader {
fn default() -> Self {
Self::new()
}
}
impl ImageLoader {
pub fn new() -> Self {
let (request_tx, request_rx) = mpsc::channel::<LoadRequest>();
let (result_tx, result_rx) = mpsc::channel::<LoadResult>();
std::thread::Builder::new()
.name("album-art-loader".into())
.spawn(move || {
worker_loop(request_rx, result_tx);
})
.expect("failed to spawn album art loader thread");
Self {
cache: HashMap::new(),
insertion_order: VecDeque::new(),
pending: RefCell::new(HashSet::new()),
result_rx,
request_tx,
}
}
pub fn request(&self, uri: &str, speaker_ip: IpAddr) {
if self.cache.contains_key(uri) {
return;
}
let mut pending = self.pending.borrow_mut();
if pending.contains(uri) {
return;
}
let full_url = build_url(uri, speaker_ip);
let req = LoadRequest {
uri: uri.to_string(),
full_url,
};
if self.request_tx.send(req).is_ok() {
pending.insert(uri.to_string());
}
}
pub fn poll(&mut self) -> bool {
let mut loaded = false;
while let Ok(result) = self.result_rx.try_recv() {
self.pending.borrow_mut().remove(&result.uri);
if let Some(img) = result.image {
self.evict_if_full();
self.insertion_order.push_back(result.uri.clone());
self.cache.insert(result.uri, img);
loaded = true;
}
}
loaded
}
pub fn get(&self, uri: &str) -> Option<&DynamicImage> {
self.cache.get(uri)
}
fn evict_if_full(&mut self) {
while self.cache.len() >= MAX_CACHE_SIZE {
if let Some(oldest) = self.insertion_order.pop_front() {
self.cache.remove(&oldest);
} else {
break;
}
}
}
}
fn build_url(uri: &str, speaker_ip: IpAddr) -> String {
if uri.starts_with("http://") || uri.starts_with("https://") {
uri.to_string()
} else {
format!("http://{speaker_ip}:1400{uri}")
}
}
fn worker_loop(rx: mpsc::Receiver<LoadRequest>, tx: mpsc::Sender<LoadResult>) {
let agent = ureq::Agent::config_builder()
.timeout_global(Some(FETCH_TIMEOUT))
.build()
.new_agent();
for req in rx {
let image = fetch_and_decode(&agent, &req.full_url);
let result = LoadResult {
uri: req.uri,
image,
};
if tx.send(result).is_err() {
break; }
}
}
fn fetch_and_decode(agent: &ureq::Agent, url: &str) -> Option<DynamicImage> {
let response = agent.get(url).call().ok()?;
let status = response.status();
if status != 200 {
tracing::debug!("Album art fetch returned {status} for {url}");
return None;
}
let body = response
.into_body()
.with_config()
.limit(5 * 1024 * 1024)
.read_to_vec()
.ok()?;
let img = image::load_from_memory(&body)
.map_err(|e| {
tracing::debug!("Album art decode failed for {url}: {e}");
e
})
.ok()?;
Some(crop_to_square(img))
}
fn crop_to_square(img: DynamicImage) -> DynamicImage {
let (w, h) = (img.width(), img.height());
if w == h {
return img;
}
let side = w.min(h);
let x = (w - side) / 2;
let y = (h - side) / 2;
img.crop_imm(x, y, side, side)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn build_url_relative_path() {
let ip: IpAddr = "192.168.1.100".parse().unwrap();
assert_eq!(
build_url("/getaa?s=1&u=test", ip),
"http://192.168.1.100:1400/getaa?s=1&u=test"
);
}
#[test]
fn build_url_absolute_http() {
let ip: IpAddr = "192.168.1.100".parse().unwrap();
let url = "http://example.com/art.jpg";
assert_eq!(build_url(url, ip), url);
}
#[test]
fn build_url_absolute_https() {
let ip: IpAddr = "192.168.1.100".parse().unwrap();
let url = "https://example.com/art.jpg";
assert_eq!(build_url(url, ip), url);
}
#[test]
fn crop_to_square_landscape() {
let img = DynamicImage::new_rgb8(160, 90);
let cropped = crop_to_square(img);
assert_eq!(cropped.width(), 90);
assert_eq!(cropped.height(), 90);
}
#[test]
fn crop_to_square_portrait() {
let img = DynamicImage::new_rgb8(90, 160);
let cropped = crop_to_square(img);
assert_eq!(cropped.width(), 90);
assert_eq!(cropped.height(), 90);
}
#[test]
fn crop_to_square_already_square() {
let img = DynamicImage::new_rgb8(100, 100);
let cropped = crop_to_square(img);
assert_eq!(cropped.width(), 100);
assert_eq!(cropped.height(), 100);
}
}