Mulberry/mulberry/nowplaying.py
Mulberry 615b21d64a
Mulberry 1.1.0: Material You music player for Linux and Windows
- KDE/Windows accent-driven Material 3 theme, live updating
- Library, tabbed playlists, smart/saved lists, queue, ratings
- mpv and Qt Multimedia engines, EQ, ReplayGain, gapless
- Synced lyrics (LRCLIB, NetEase, local .lrc), covers, MusicBrainz tags
- Last.fm/ListenBrainz scrobbling, MPRIS, Windows media keys
- Audio CD playback and ripping
- PyInstaller, Inno Setup and AppImage builds via GitHub Actions

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
2026-10-09 23:00:48 -05:00

237 lines
9.3 KiB
Python

"""Tracks the current song's artwork and lyrics, loading them from tags,
folders, cache or the internet without blocking the UI."""
from __future__ import annotations
import os
from PyQt6.QtCore import QObject, Qt, pyqtSignal
from PyQt6.QtGui import QImage
from . import library as L
from . import online
from . import tags as T
from .config import run_async, settings
from .song import Song
class NowPlaying(QObject):
art_changed = pyqtSignal(object, str) # QImage|None, path
lyrics_changed = pyqtSignal(str, str, object) # text, source, song ('' + 'loading' while busy)
info_changed = pyqtSignal(str, str) # artist, bio text
def __init__(self, player):
super().__init__()
self.player = player
self.song: Song | None = None
self.image: QImage | None = None
self.art_path = ""
self.lyrics = ""
self.lyrics_source = ""
self._art_key = None
self._lyr_key = None
player.song_changed.connect(self.on_song)
# ------------------------------------------------------------------ art
def on_song(self, s: Song):
prev = self.song
self.song = s
self._load_art(s)
if prev is not s or s.is_stream:
self._load_lyrics(s)
def _art_ident(self, s: Song):
return (s.effective_albumartist().lower(), s.album.lower(), os.path.dirname(s.path) if s.is_local else s.url)
def _load_art(self, s: Song, force=False):
ident = self._art_ident(s)
if ident == self._art_key and not force and not s.is_stream:
return
self._art_key = ident
if s.art and os.path.exists(s.art):
self._set_art_file(s.art)
return
def work():
if s.is_local and os.path.exists(s.path):
d = os.path.dirname(s.path)
key = T.album_key(s.effective_albumartist(), s.album, d)
cached = T.COVER_DIR / f"{key}.jpg"
if cached.exists():
return str(cached)
src = T.find_folder_cover(d)
data = None if src else T.extract_embedded_cover(s.path)
if src or data:
return T.store_cover(src or data, key)
key = T.album_key(s.effective_albumartist(), s.album or s.display_title(), "")
cached = T.COVER_DIR / f"{key}.jpg"
if cached.exists():
return str(cached)
if settings.get("online/auto_covers") and (s.album or s.is_cd):
data = online.best_cover(s.effective_albumartist(), s.album)
if data:
path = T.store_cover(data, key)
if path and settings.get("online/save_covers_to_folder") and s.is_local:
try:
dst = os.path.join(os.path.dirname(s.path), "cover.jpg")
if not os.path.exists(dst):
with open(dst, "wb") as fh:
fh.write(data)
except OSError:
pass
return path
return None
def done(path):
if self.song is not s:
return
if path:
if s.id >= 0 and s.art != path:
L.library.set_album_art(s.effective_albumartist(), s.album, path)
s.art = path
self._set_art_file(path)
else:
self._set_art_none()
self._set_art_none()
run_async(work, on_done=done, on_error=lambda e: None)
def _set_art_file(self, path):
img = QImage(path)
if img.isNull():
self._set_art_none()
return
self.image, self.art_path = img, path
self.art_changed.emit(img, path)
def _set_art_none(self):
if self.image is None and not self.art_path:
self.art_changed.emit(None, "")
return
self.image, self.art_path = None, ""
self.art_changed.emit(None, "")
def set_cover(self, s: Song, img: QImage):
"""Called by the cover manager after the user picked/loaded a cover."""
d = os.path.dirname(s.path) if s.is_local else ""
key = T.album_key(s.effective_albumartist(), s.album, d)
path = T.store_cover(T.image_to_jpeg_bytes(img), key)
if path:
s.art = path
if s.album:
L.library.set_album_art(s.effective_albumartist(), s.album, path)
if self.song is not None and self._art_ident(self.song) == self._art_ident(s):
self.song.art = path
self._art_key = None
self._set_art_file(path)
return path
# ------------------------------------------------------------------ lyrics
def lyr_key(self, s: Song):
if s.is_stream:
return f"stream|{s.stream_title}".lower()
return f"{s.display_artist()}|{s.display_title()}|{s.album}".lower()
def _load_lyrics(self, s: Song, force_online=False):
"""Sources: auto (local .lrc → synced embedded → LRCLIB → NetEase →
plain embedded), or one specific provider chosen in the lyrics menu."""
source = settings.get("lyrics/source")
key = self.lyr_key(s)
ckey = key if source == "auto" else f"{key}|{source}"
if ckey == self._lyr_key and not force_online:
return
self._lyr_key = ckey
self._lyr_token = token = getattr(self, "_lyr_token", 0) + 1
if s.is_stream and not s.stream_title:
self._emit_lyrics("", "", s)
return
# lyrics the user typed/pasted always win
utxt, usrc = L.library.get_lyrics(key)
if usrc == "user" and utxt and not force_online and source == "auto":
self._emit_lyrics(utxt, "Your lyrics", s)
return
local = T.sidecar_lyrics(s.path) if s.is_local else ""
emb = T.read_embedded_lyrics(s.path) if s.is_local else ""
if source == "local":
self._emit_lyrics(local, "Local .lrc", s) if local.strip() else \
self._emit_lyrics("", "nolocal", s)
return
if source == "embedded":
self._emit_lyrics(emb, "Embedded tags", s)
return
if source == "auto" and not force_online:
if local.strip():
self._emit_lyrics(local, "Local .lrc", s)
return
if emb.strip() and online.LRC_RE.search(emb):
self._emit_lyrics(emb, "Embedded tags", s)
return
if not force_online:
txt, src = L.library.get_lyrics(ckey)
if txt is not None and (txt or src == "none"):
if txt:
self._emit_lyrics(txt, src or "cache", s)
else:
self._emit_lyrics(emb, "Embedded tags", s) if emb.strip() else self._emit_lyrics("", "", s)
return
if source == "auto" and not settings.get("online/auto_lyrics"):
self._emit_lyrics(emb, "Embedded tags" if emb else "", s)
return
self.lyrics_changed.emit("", "loading", s)
provider = source if source in online.ONLINE_PROVIDERS else "auto"
def done(res):
txt, src = res
L.library.put_lyrics(ckey, txt or "", src or "none")
if self.song is not s or self._lyr_token != token:
return
if txt:
self._emit_lyrics(txt, src, s)
elif emb.strip():
self._emit_lyrics(emb, "Embedded tags", s)
else:
self._emit_lyrics("", "", s)
def fail(_e):
if self.song is s and self._lyr_token == token:
self._emit_lyrics(emb, "Embedded tags", s) if emb.strip() else self._emit_lyrics("", "error", s)
run_async(online.fetch_lyrics, s, provider, on_done=done, on_error=fail)
def set_source(self, source: str):
settings.set("lyrics/source", source)
if self.song:
self._lyr_key = None
self._load_lyrics(self.song)
def _emit_lyrics(self, txt, src, s):
self.lyrics, self.lyrics_source = txt, src
self.lyrics_changed.emit(txt or "", src or "", s)
def refetch_lyrics(self):
if self.song:
self._lyr_key = None
self._load_lyrics(self.song, force_online=True)
def set_lyrics(self, text: str, save_to_file=False):
s = self.song
if not s:
return
self._lyr_token = getattr(self, "_lyr_token", 0) + 1
L.library.put_lyrics(self.lyr_key(s), text, "user")
if save_to_file and s.is_local:
try:
T.write_lyrics(s.path, text)
except Exception as e: # noqa: BLE001
print("write lyrics failed", e)
self._emit_lyrics(text, "Your lyrics", s)
def load_artist_info(self):
s = self.song
if not s or not s.display_artist():
return
artist = s.display_artist()
run_async(online.artist_info, artist, on_done=lambda t: self.info_changed.emit(artist, t or ""),
on_error=lambda e: self.info_changed.emit(artist, ""))
def scaled_cover(img: QImage, size: int) -> QImage:
return img.scaled(size, size, Qt.AspectRatioMode.KeepAspectRatioByExpanding,
Qt.TransformationMode.SmoothTransformation)