Mulberry/mulberry/nowplaying.py
Claude a0b83cd4e3
Mulberry 1.2.1: CD fixes, web links, lyrics priority, portable playlists
- Fix crash after CD ripping (running QThread was destroyed)
- Audio CDs always use mpv (bundled on Windows) even when Qt is the main engine
  — fixes 'several tracks failed to play' on Windows
- YouTube/SoundCloud/Bandcamp links resolved with bundled yt-dlp
- Lyrics: Auto prefers synced from any source (LRCLIB > NetEase > embedded >
  local); explicit choices no longer fall back; NetEase uses cloudsearch
  (search/get/web is encrypted outside China)
- Playlist export uses absolute paths by default; import remaps paths from
  other machines/OSes via the library
- HTTPS: certificate fallback (system bundles, certifi) for packaged builds;
  cover search shows real errors, more fallbacks, Last.fm covers
- MusicBrainz: retry without album, cleaner album artist, async genre
- CI self-tests require bundled libmpv (Windows), yt-dlp and TLS certs

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

339 lines
13 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
if s.is_cd:
# Burned / unknown discs have no ID: never search the web with
# "Track 3 / Audio CD" — show a CD placeholder instead.
if s.mb_albumid and settings.get("online/auto_covers"):
def cd_work():
data = online.download(f"https://coverartarchive.org/release/{s.mb_albumid}/front-500")
return T.store_cover(data, T.album_key(s.effective_albumartist(), s.album, s.mb_albumid))
def cd_done(path):
if self.song is s:
if path:
s.art = path
self._set_art_file(path)
else:
self._set_art_file(cd_placeholder())
self._set_art_file(cd_placeholder())
run_async(cd_work, on_done=cd_done, on_error=lambda e: None)
else:
self._set_art_file(cd_placeholder())
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 and s.stream_title:
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):
"""Lyrics sources.
Auto: synced lyrics always win. Order: LRCLIB synced → NetEase synced →
embedded synced → local .lrc synced, then the same order for plain text.
Any other choice uses only that source (no silent fallback), so what
you pick in the ⋮ menu is exactly what you see.
"""
source = settings.get("lyrics/source")
key = self.lyr_key(s)
ckey = 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 and not s.resolved:
self._emit_lyrics("", "", s)
return
if is_unknown_cd(s):
self._emit_lyrics("", "unknowncd", s)
return
synced = online.LRC_RE.search
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) if emb.strip() else self._emit_lyrics("", "noembedded", s)
return
if source in online.ONLINE_PROVIDERS: # one specific online service
label = online.ONLINE_PROVIDERS[source][0]
if not force_online:
txt, src = L.library.get_lyrics(ckey)
if txt is not None:
self._emit_lyrics(txt, label, s) if txt else self._emit_lyrics("", f"none:{label}", s)
return
self.lyrics_changed.emit("", "loading", s)
def done_one(res):
txt, _src = res
L.library.put_lyrics(ckey, txt or "", label)
if self.song is s and self._lyr_token == token:
self._emit_lyrics(txt, label, s) if txt else self._emit_lyrics("", f"none:{label}", s)
def fail_one(_e):
if self.song is s and self._lyr_token == token:
self._emit_lyrics("", "error", s)
run_async(online.fetch_lyrics, s, source, on_done=done_one, on_error=fail_one)
return
# ---- auto
utxt, usrc = L.library.get_lyrics(key)
if usrc == "user" and utxt and not force_online:
self._emit_lyrics(utxt, "Your lyrics", s)
return
def decide(online_txt, online_label):
cands = [(online_txt, online_label), (emb, "Embedded tags"), (local, "Local .lrc")]
for txt, label in cands: # synced first…
if txt and txt.strip() and (synced(txt) or txt == "[instrumental]"):
return self._emit_lyrics(txt, label, s)
for txt, label in cands: # …then plain
if txt and txt.strip():
return self._emit_lyrics(txt, label, s)
self._emit_lyrics("", "", s)
if not force_online:
txt, src = L.library.get_lyrics(ckey)
if txt is not None:
return decide(txt, src)
if not settings.get("online/auto_lyrics"):
return decide("", "")
self.lyrics_changed.emit("", "loading", s)
def done(res):
txt, src = res
L.library.put_lyrics(ckey, txt or "", src or "")
if self.song is s and self._lyr_token == token:
decide(txt, src)
def fail(_e):
if self.song is s and self._lyr_token == token:
if (emb or local).strip():
decide("", "")
else:
self._emit_lyrics("", "error", s)
run_async(online.fetch_lyrics, s, "auto", 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() or is_unknown_cd(s):
self.info_changed.emit("", "")
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)
def is_unknown_cd(s: Song) -> bool:
"""An audio CD track with no MusicBrainz match (e.g. a burned disc)."""
return bool(s and s.is_cd and not s.mb_trackid and not s.mb_albumid)
def cd_placeholder() -> str:
"""Render (once) a neutral 'Audio CD' disc image and return its path."""
from .config import CACHE_DIR
path = CACHE_DIR / "cd_placeholder_v1.png"
if path.exists():
return str(path)
from PyQt6.QtCore import QPointF, QRectF
from PyQt6.QtGui import QColor, QConicalGradient, QFont, QPainter, QRadialGradient
size = 640
img = QImage(size, size, QImage.Format.Format_ARGB32)
p = QPainter(img)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
bg = QRadialGradient(QPointF(size * 0.3, size * 0.25), size * 0.95)
bg.setColorAt(0, QColor("#3a3442"))
bg.setColorAt(1, QColor("#17141c"))
p.fillRect(img.rect(), bg)
c = QPointF(size / 2, size / 2)
R = size * 0.40
# iridescent disc surface
g = QConicalGradient(c, 35)
for t, col in ((0.0, "#d9dde6"), (0.12, "#f3c6e8"), (0.25, "#c9d6ff"), (0.38, "#e9f2f7"),
(0.5, "#cfe9d9"), (0.62, "#ffe6c4"), (0.75, "#d6c8ff"), (0.88, "#f2d0dc"), (1.0, "#d9dde6")):
g.setColorAt(t, QColor(col))
p.setPen(QColor(255, 255, 255, 70))
p.setBrush(g)
p.drawEllipse(c, R, R)
# subtle grooves
for i in range(14):
r = R * (0.42 + i * 0.04)
p.setPen(QColor(255, 255, 255, 18 if i % 2 else 30))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawEllipse(c, r, r)
# clear hub + hole
p.setPen(QColor(255, 255, 255, 90))
p.setBrush(QColor(235, 238, 245, 150))
p.drawEllipse(c, R * 0.34, R * 0.34)
p.setBrush(QColor("#17141c"))
p.setPen(QColor(255, 255, 255, 60))
p.drawEllipse(c, R * 0.12, R * 0.12)
f = QFont()
f.setPixelSize(int(size * 0.05))
f.setBold(True)
p.setFont(f)
p.setPen(QColor(255, 255, 255, 200))
p.drawText(QRectF(0, size * 0.885, size, size * 0.09), Qt.AlignmentFlag.AlignCenter, "AUDIO CD")
p.end()
img.save(str(path), "PNG")
return str(path)