385 lines
15 KiB
Rust
385 lines
15 KiB
Rust
//! Tracks the current song's artwork and lyrics, loading them from tags, folders, cache
|
|
//! or the internet without blocking the UI.
|
|
|
|
use crate::bus::{ArtData, Bus, Msg};
|
|
use crate::config::{settings, PATHS};
|
|
use crate::library::Library;
|
|
use crate::song::Song;
|
|
use crate::{online, tags, theme};
|
|
use eframe::egui;
|
|
use std::path::Path;
|
|
use std::sync::Arc;
|
|
|
|
pub struct NowPlaying {
|
|
pub song: Option<Song>,
|
|
pub art_path: String,
|
|
pub cover_tex: Option<egui::TextureHandle>,
|
|
pub blur_tex: Option<egui::TextureHandle>,
|
|
pub accent: Option<egui::Color32>,
|
|
pub lyrics: String,
|
|
pub lyrics_source: String,
|
|
pub art_ident: String,
|
|
lyr_key: Option<String>,
|
|
pub lyr_token: u64,
|
|
art_token: u64,
|
|
lib: Arc<Library>,
|
|
bus: Bus,
|
|
}
|
|
|
|
pub fn is_unknown_cd(s: &Song) -> bool {
|
|
s.is_cd() && s.mb_trackid.is_empty() && s.mb_albumid.is_empty()
|
|
}
|
|
|
|
fn art_ident(s: &Song) -> String {
|
|
format!("{}|{}|{}", s.effective_albumartist().to_lowercase(), s.album.to_lowercase(), if s.is_local() { Path::new(&s.path()).parent().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default() } else { s.url.clone() })
|
|
}
|
|
|
|
/// Square-crop (keep aspect, expand) and scale for the GPU; also the tiny blurred background.
|
|
pub fn prepare_art(img: &image::DynamicImage) -> ArtData {
|
|
let rgba = img.to_rgba8();
|
|
let cover = img.resize_to_fill(512, 512, image::imageops::FilterType::Lanczos3).to_rgba8();
|
|
let small = image::imageops::resize(&rgba, 18, 18, image::imageops::FilterType::Triangle);
|
|
let mid = image::imageops::resize(&small, 64, 64, image::imageops::FilterType::CatmullRom);
|
|
let to_color = |im: &image::RgbaImage| egui::ColorImage::from_rgba_unmultiplied([im.width() as usize, im.height() as usize], im.as_raw());
|
|
ArtData { cover: to_color(&cover), blur: to_color(&mid), accent: theme::dominant_color(&rgba) }
|
|
}
|
|
|
|
impl NowPlaying {
|
|
pub fn new(lib: Arc<Library>, bus: Bus) -> NowPlaying {
|
|
NowPlaying {
|
|
song: None,
|
|
art_path: String::new(),
|
|
cover_tex: None,
|
|
blur_tex: None,
|
|
accent: None,
|
|
lyrics: String::new(),
|
|
lyrics_source: String::new(),
|
|
art_ident: String::new(),
|
|
lyr_key: None,
|
|
lyr_token: 0,
|
|
art_token: 0,
|
|
lib,
|
|
bus,
|
|
}
|
|
}
|
|
|
|
pub fn drop_textures(&mut self) {
|
|
self.cover_tex = None;
|
|
self.blur_tex = None;
|
|
self.art_ident.clear();
|
|
}
|
|
|
|
pub fn on_song(&mut self, s: &Song) {
|
|
let prev = self.song.take();
|
|
let same = prev.as_ref().map(|p| p.url == s.url && p.begin == s.begin).unwrap_or(false);
|
|
self.song = Some(s.clone());
|
|
self.load_art(s, false);
|
|
if !same || s.is_stream() {
|
|
self.load_lyrics(s, false);
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ art
|
|
pub fn load_art(&mut self, s: &Song, force: bool) {
|
|
let ident = art_ident(s);
|
|
if ident == self.art_ident && !force && !s.is_stream() {
|
|
return;
|
|
}
|
|
self.art_ident = ident.clone();
|
|
self.art_token += 1;
|
|
let s = s.clone();
|
|
let bus = self.bus.clone();
|
|
std::thread::spawn(move || {
|
|
let path = resolve_art_path(&s);
|
|
let art = path.as_ref().and_then(|p| image::open(p).ok()).map(|im| Box::new(prepare_art(&im)));
|
|
bus.send(Msg::Art { ident, art, path: path.unwrap_or_default() });
|
|
});
|
|
}
|
|
|
|
pub fn on_art(&mut self, ctx: &egui::Context, ident: &str, art: Option<Box<ArtData>>, path: String, lib: &Library) -> Option<egui::Color32> {
|
|
if ident != self.art_ident {
|
|
return None;
|
|
}
|
|
self.art_path = path.clone();
|
|
match art {
|
|
Some(a) => {
|
|
self.cover_tex = Some(ctx.load_texture("cover", a.cover, egui::TextureOptions::LINEAR));
|
|
self.blur_tex = Some(ctx.load_texture("cover-blur", a.blur, egui::TextureOptions::LINEAR));
|
|
self.accent = a.accent;
|
|
if let Some(s) = &self.song {
|
|
if s.id >= 0 && s.art != path {
|
|
lib.set_album_art(&s.effective_albumartist(), &s.album, &path);
|
|
}
|
|
}
|
|
}
|
|
None => {
|
|
self.cover_tex = None;
|
|
self.blur_tex = None;
|
|
self.accent = None;
|
|
}
|
|
}
|
|
self.accent
|
|
}
|
|
|
|
// ------------------------------------------------------------------ lyrics
|
|
pub fn lyr_key(s: &Song) -> String {
|
|
if s.is_stream() && !s.stream_title.is_empty() {
|
|
return format!("stream|{}", s.stream_title).to_lowercase();
|
|
}
|
|
format!("{}|{}|{}", s.display_artist(), s.display_title(), s.album).to_lowercase()
|
|
}
|
|
|
|
fn emit(&mut self, text: &str, source: &str) {
|
|
self.lyrics = text.to_string();
|
|
self.lyrics_source = source.to_string();
|
|
self.bus.send(Msg::Lyrics { token: self.lyr_token, text: text.into(), source: source.into() });
|
|
}
|
|
|
|
/// Lyrics sources. Auto: synced always wins (LRCLIB → NetEase → embedded → local .lrc), then
|
|
/// plain text in the same order. Any other choice uses only that source.
|
|
pub fn load_lyrics(&mut self, s: &Song, force_online: bool) {
|
|
let source = settings().get_str("lyrics/source");
|
|
let key = Self::lyr_key(s);
|
|
let ckey = format!("{key}|{source}");
|
|
if self.lyr_key.as_deref() == Some(&ckey) && !force_online {
|
|
return;
|
|
}
|
|
self.lyr_key = Some(ckey.clone());
|
|
self.lyr_token += 1;
|
|
let token = self.lyr_token;
|
|
if s.is_stream() && s.stream_title.is_empty() && s.resolved.is_empty() {
|
|
self.emit("", "");
|
|
return;
|
|
}
|
|
if is_unknown_cd(s) {
|
|
self.emit("", "unknowncd");
|
|
return;
|
|
}
|
|
let local = if s.is_local() { tags::sidecar_lyrics(&s.path()) } else { String::new() };
|
|
let emb = if s.is_local() { tags::read_embedded_lyrics(&s.path()) } else { String::new() };
|
|
match source.as_str() {
|
|
"local" => {
|
|
if local.trim().is_empty() { self.emit("", "nolocal") } else { self.emit(&local, "Local .lrc") }
|
|
return;
|
|
}
|
|
"embedded" => {
|
|
if emb.trim().is_empty() { self.emit("", "noembedded") } else { self.emit(&emb, "Embedded tags") }
|
|
return;
|
|
}
|
|
_ => {}
|
|
}
|
|
let bus = self.bus.clone();
|
|
let lib = self.lib.clone();
|
|
let song = s.clone();
|
|
if online::PROVIDERS.iter().any(|p| p.0 == source) {
|
|
let label = online::provider_label(&source).to_string();
|
|
if !force_online {
|
|
if let Some((txt, _)) = lib.get_lyrics(&ckey) {
|
|
if txt.is_empty() { self.emit("", &format!("none:{label}")) } else { self.emit(&txt, &label) }
|
|
return;
|
|
}
|
|
}
|
|
self.bus.send(Msg::Lyrics { token, text: String::new(), source: "loading".into() });
|
|
std::thread::spawn(move || match online::fetch_lyrics(&song, &source) {
|
|
Ok((txt, _)) => {
|
|
lib.put_lyrics(&ckey, &txt, &label);
|
|
if txt.is_empty() { bus.send(Msg::Lyrics { token, text: String::new(), source: format!("none:{label}") }) } else { bus.send(Msg::Lyrics { token, text: txt, source: label }) }
|
|
}
|
|
Err(_) => bus.send(Msg::Lyrics { token, text: String::new(), source: "error".into() }),
|
|
});
|
|
return;
|
|
}
|
|
// ---- auto
|
|
if let Some((utxt, usrc)) = lib.get_lyrics(&key) {
|
|
if usrc == "user" && !utxt.is_empty() && !force_online {
|
|
self.emit(&utxt, "Your lyrics");
|
|
return;
|
|
}
|
|
}
|
|
let decide = move |online_txt: String, online_label: String, bus: &Bus| {
|
|
let cands = [(online_txt, online_label), (emb.clone(), "Embedded tags".to_string()), (local.clone(), "Local .lrc".to_string())];
|
|
for (txt, label) in &cands {
|
|
if !txt.trim().is_empty() && (online::is_synced(txt) || txt == "[instrumental]") {
|
|
return bus.send(Msg::Lyrics { token, text: txt.clone(), source: label.clone() });
|
|
}
|
|
}
|
|
for (txt, label) in &cands {
|
|
if !txt.trim().is_empty() {
|
|
return bus.send(Msg::Lyrics { token, text: txt.clone(), source: label.clone() });
|
|
}
|
|
}
|
|
bus.send(Msg::Lyrics { token, text: String::new(), source: String::new() });
|
|
};
|
|
if !force_online {
|
|
if let Some((txt, src)) = lib.get_lyrics(&ckey) {
|
|
let b = self.bus.clone();
|
|
decide(txt.clone(), src.clone(), &b);
|
|
self.lyrics = txt;
|
|
self.lyrics_source = src;
|
|
return;
|
|
}
|
|
if !settings().get_bool("online/auto_lyrics") {
|
|
let b = self.bus.clone();
|
|
decide(String::new(), String::new(), &b);
|
|
return;
|
|
}
|
|
}
|
|
self.bus.send(Msg::Lyrics { token, text: String::new(), source: "loading".into() });
|
|
std::thread::spawn(move || match online::fetch_lyrics(&song, "auto") {
|
|
Ok((txt, src)) => {
|
|
lib.put_lyrics(&ckey, &txt, &src);
|
|
decide(txt, src, &bus);
|
|
}
|
|
Err(_) => decide(String::new(), "error".into(), &bus),
|
|
});
|
|
}
|
|
|
|
pub fn set_source(&mut self, source: &str) {
|
|
settings().set("lyrics/source", source);
|
|
if let Some(s) = self.song.clone() {
|
|
self.lyr_key = None;
|
|
self.load_lyrics(&s, false);
|
|
}
|
|
}
|
|
|
|
pub fn refetch_lyrics(&mut self) {
|
|
if let Some(s) = self.song.clone() {
|
|
self.lyr_key = None;
|
|
self.load_lyrics(&s, true);
|
|
}
|
|
}
|
|
|
|
pub fn set_lyrics(&mut self, text: &str, save_to_file: bool) {
|
|
let Some(s) = self.song.clone() else { return };
|
|
self.lyr_token += 1;
|
|
self.lib.put_lyrics(&Self::lyr_key(&s), text, "user");
|
|
if save_to_file && s.is_local() {
|
|
let _ = tags::write_lyrics(&s.path(), text);
|
|
}
|
|
self.emit(text, "Your lyrics");
|
|
}
|
|
|
|
pub fn load_artist_info(&self) {
|
|
let Some(s) = &self.song else { return };
|
|
if s.display_artist().is_empty() || is_unknown_cd(s) {
|
|
self.bus.send(Msg::ArtistInfo { artist: String::new(), text: String::new() });
|
|
return;
|
|
}
|
|
let artist = s.display_artist();
|
|
let bus = self.bus.clone();
|
|
std::thread::spawn(move || {
|
|
let text = online::artist_info(&artist);
|
|
bus.send(Msg::ArtistInfo { artist, text });
|
|
});
|
|
}
|
|
|
|
/// Replace the current cover with an image picked in the cover manager.
|
|
pub fn set_cover_image(&mut self, s: &Song, img: &image::DynamicImage) -> Option<String> {
|
|
let dir = if s.is_local() { Path::new(&s.path()).parent().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default() } else { String::new() };
|
|
let key = tags::album_key(&s.effective_albumartist(), &s.album, &dir);
|
|
let path = tags::store_cover(tags::CoverSrc::Data(&tags::jpeg_bytes(img, 92)), &key)?;
|
|
if !s.album.is_empty() {
|
|
self.lib.set_album_art(&s.effective_albumartist(), &s.album, &path);
|
|
}
|
|
if let Some(cur) = self.song.clone() {
|
|
if art_ident(&cur) == art_ident(s) {
|
|
self.art_ident.clear();
|
|
let mut c = cur;
|
|
c.art = path.clone();
|
|
self.load_art(&c, true);
|
|
}
|
|
}
|
|
Some(path)
|
|
}
|
|
}
|
|
|
|
fn resolve_art_path(s: &Song) -> Option<String> {
|
|
if !s.art.is_empty() && Path::new(&s.art).exists() {
|
|
return Some(s.art.clone());
|
|
}
|
|
if s.is_cd() {
|
|
if !s.mb_albumid.is_empty() && settings().get_bool("online/auto_covers") {
|
|
let key = tags::album_key(&s.effective_albumartist(), &s.album, &s.mb_albumid);
|
|
let cached = tags::cover_path(&key);
|
|
if cached.exists() {
|
|
return Some(cached.to_string_lossy().into_owned());
|
|
}
|
|
if let Ok(d) = online::http_get_bytes(&format!("https://coverartarchive.org/release/{}/front-500", s.mb_albumid)) {
|
|
return tags::store_cover(tags::CoverSrc::Data(&d), &key);
|
|
}
|
|
}
|
|
return Some(cd_placeholder());
|
|
}
|
|
if s.is_local() && Path::new(&s.path()).exists() {
|
|
let dir = Path::new(&s.path()).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default();
|
|
let key = tags::album_key(&s.effective_albumartist(), &s.album, &dir);
|
|
let cached = tags::cover_path(&key);
|
|
if cached.exists() {
|
|
return Some(cached.to_string_lossy().into_owned());
|
|
}
|
|
let src = tags::find_folder_cover(&dir);
|
|
let data = if src.is_none() { tags::extract_embedded_cover(&s.path()) } else { None };
|
|
if let Some(p) = src {
|
|
return tags::store_cover(tags::CoverSrc::Path(&p), &key);
|
|
}
|
|
if let Some(d) = data {
|
|
return tags::store_cover(tags::CoverSrc::Data(&d), &key);
|
|
}
|
|
}
|
|
let title = s.display_title();
|
|
let key = tags::album_key(&s.effective_albumartist(), if s.album.is_empty() { &title } else { &s.album }, "");
|
|
let cached = tags::cover_path(&key);
|
|
if cached.exists() {
|
|
return Some(cached.to_string_lossy().into_owned());
|
|
}
|
|
if settings().get_bool("online/auto_covers") && (!s.album.is_empty() || s.is_cd()) {
|
|
if let Some(d) = online::best_cover(&s.effective_albumartist(), &s.album, "") {
|
|
let path = tags::store_cover(tags::CoverSrc::Data(&d), &key);
|
|
if path.is_some() && settings().get_bool("online/save_covers_to_folder") && s.is_local() {
|
|
let dst = Path::new(&s.path()).with_file_name("cover.jpg");
|
|
if !dst.exists() {
|
|
let _ = std::fs::write(dst, &d);
|
|
}
|
|
}
|
|
return path;
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Render (once) a neutral "Audio CD" disc image.
|
|
pub fn cd_placeholder() -> String {
|
|
let path = PATHS.cache.join("cd_placeholder_v1.png");
|
|
if path.exists() {
|
|
return path.to_string_lossy().into_owned();
|
|
}
|
|
let size = 640u32;
|
|
let mut img = image::RgbaImage::new(size, size);
|
|
let c = size as f32 / 2.0;
|
|
let r = size as f32 * 0.40;
|
|
for (x, y, px) in img.enumerate_pixels_mut() {
|
|
let (dx, dy) = (x as f32 - c, y as f32 - c);
|
|
let d = (dx * dx + dy * dy).sqrt();
|
|
let (bx, by) = (x as f32 / size as f32, y as f32 / size as f32);
|
|
let bg = 0x17 as f32 + (0x3a - 0x17) as f32 * (1.0 - ((bx - 0.3).powi(2) + (by - 0.25).powi(2)).sqrt()).clamp(0.0, 1.0);
|
|
*px = image::Rgba([bg as u8, (bg * 0.95) as u8, (bg * 1.1).min(255.0) as u8, 255]);
|
|
if d < r {
|
|
let ang = dy.atan2(dx);
|
|
let hue = (ang / std::f32::consts::TAU + 0.5) * 360.0 + 35.0;
|
|
let col = theme::oklch_to_color(0.88, 0.035, hue as f64);
|
|
*px = image::Rgba([col.r(), col.g(), col.b(), 255]);
|
|
let groove = ((d / r * 40.0).sin() * 0.5 + 0.5) * 12.0;
|
|
for ch in 0..3 {
|
|
px[ch] = px[ch].saturating_sub(groove as u8);
|
|
}
|
|
if d < r * 0.34 {
|
|
*px = image::Rgba([235, 238, 245, 255]);
|
|
}
|
|
if d < r * 0.12 {
|
|
*px = image::Rgba([0x17, 0x14, 0x1c, 255]);
|
|
}
|
|
}
|
|
}
|
|
let _ = img.save(&path);
|
|
path.to_string_lossy().into_owned()
|
|
}
|