diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cfdb6b9..a58695d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -56,6 +56,9 @@ jobs: Get-Content selftest-windows.txt if ([double]$r['visualizer_decoded_s'] -lt 5) { Write-Output "::error title=Windows self-test::audio decoding failed ($($r['visualizer_decoded_s']) s)"; exit 1 } if ([double]$r['visualizer_peak'] -lt 0.05) { Write-Output "::error title=Windows self-test::visualizer silent"; exit 1 } + if ($r['mpv_available'] -ne 'True') { Write-Output "::error title=Windows self-test::bundled libmpv did not load (CD playback would fail)"; exit 1 } + if ($r['ytdlp'] -ne 'True') { Write-Output "::error title=Windows self-test::yt-dlp missing from the build"; exit 1 } + if ([int]$r['ssl_ca'] -lt 1) { Write-Output "::error title=Windows self-test::no TLS certificates"; exit 1 } if ([double]$r['position'] -lt 1) { Write-Output "::warning title=Windows self-test::playback position did not advance (runner has no audio device?) state=$($r['state'])" } - uses: actions/upload-artifact@v4 with: @@ -111,6 +114,8 @@ jobs: get() { grep "^$1=" selftest-linux.txt | cut -d= -f2; } awk "BEGIN{exit !($(get visualizer_decoded_s) >= 5)}" || { echo "::error title=Linux self-test::audio decoding failed::$(grep -i 'multimedia\|ffmpeg\|Failed' selftest-linux.log | head -5 | tr '\n' '|')"; exit 1; } awk "BEGIN{exit !($(get visualizer_peak) >= 0.05)}" || { echo "::error title=Linux self-test::visualizer silent"; exit 1; } + [ "$(get ytdlp)" = "True" ] || { echo "::error title=Linux self-test::yt-dlp missing from the build"; exit 1; } + [ "$(get ssl_ca)" -ge 1 ] || { echo "::error title=Linux self-test::no TLS certificates"; exit 1; } awk "BEGIN{exit !($(get position) >= 1)}" || echo "::warning title=Linux self-test::playback position did not advance (state=$(get state))" - uses: actions/upload-artifact@v4 with: diff --git a/README.md b/README.md index 821f2cc..cc1e6ed 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,9 @@ The Windows installer is built with [Inno Setup](https://jrsoftware.org/isinfo.p - Smart playlists: Recently added, Most played, Recently played, Loved & top rated, Never played, Random 100, Most skipped. - Play counts, skip counts and 0–5 star ratings. - Playlist import: M3U, M3U8, PLS, XSPF, WPL, ASX, CUE. Export: M3U, M3U8, PLS, XSPF, WPL, with relative or absolute paths. -- **Export all playlists** (Playlist menu, Ctrl+Shift+S, or the Lists tab): pick a folder and a file type, then choose whether existing files are replaced, skipped or kept with a number added. Closed saved playlists can be included too. +- **Export all playlists** (Playlist menu, Ctrl+Shift+S, or the Lists tab): pick a folder and a file type, then choose whether existing files are replaced, skipped or kept with a number added. Closed saved playlists can be included too. Playlists use full file paths by default; relative paths are optional. +- Importing finds your files even if the playlist was made on another computer or OS (different home folder, `C:\` paths, `\` vs `/`), by matching the album folder and file name against your library. +- Play **YouTube, SoundCloud, Bandcamp and other web links** (*Music › Open URL*, Ctrl+U, or the Radio tab). They're resolved with the bundled yt-dlp; title, artist, length and thumbnail are filled in, and seeking works. - Internet radio with ICY now-playing titles. A few SomaFM, Radio Paradise and KEXP stations are included, and you can add your own. - Output device selection, a 10-band equalizer with presets, ReplayGain (track or album, with pre-amp), and resume where you left off. @@ -119,11 +121,11 @@ The Windows installer is built with [Inno Setup](https://jrsoftware.org/isinfo.p - Tag editor for single files or many at once, with cover embedding for MP3, FLAC, Ogg, M4A and APE/WavPack. - MusicBrainz tag lookup, either picking a match or auto-applying it in batch, plus AcoustID fingerprinting. - Automatic cover fetching (iTunes, Deezer, Cover Art Archive, Last.fm) and a cover manager with a grid of candidates. -- Synced lyrics. In the lyrics card's ⋮ menu you can pick the source: **Auto** (local `.lrc` → embedded → LRCLIB → NetEase), **LRCLIB**, **NetEase Cloud Music**, **Local .lrc files** (such as those downloaded by LRCGET) or **Embedded tags**. You can also turn on **Show as plain text**. Click any synced line to jump there. You can also edit lyrics, nudge their timing, and switch the card to the artist bio. +- Synced lyrics. In the lyrics card's ⋮ menu you can pick the source. **Auto** always prefers synced lyrics: LRCLIB → NetEase → embedded → local `.lrc`, then the same order for plain text. Picking **LRCLIB**, **NetEase Cloud Music**, **Local .lrc files** (such as those downloaded by LRCGET) or **Embedded tags** uses only that source. You can also turn on **Show as plain text**. Click any synced line to jump there. You can also edit lyrics, nudge their timing, and switch the card to the artist bio. **Audio CD** - Detects drives, reads the TOC (built-in on Windows; libdiscid, cdparanoia or cd-info on Linux), looks the disc up on MusicBrainz and fetches its cover. -- Plays CD tracks (mpv engine; included in the Windows build). +- Plays CD tracks. CDs always use the mpv engine (bundled on Windows), even when your main engine is Qt. - Burned or unknown discs with no MusicBrainz match show a CD placeholder. Online cover, lyrics and artist lookups are switched off for them, so they never pull in wrong data. - Ripper: format, quality, folder and filename pattern are configurable. It tags the files, embeds the cover and adds the result to your library. It uses cdparanoia + ffmpeg when available, otherwise libmpv's built-in encoder (which is how it works on Windows). @@ -179,6 +181,7 @@ Advanced: tick *Use my own API key* to use a personal key instead of Mulberry's ## Troubleshooting - **No sound, or "Playback error":** in *Settings → Playback*, try the other engine (Qt ↔ mpv) or another output device. - **The visualizer doesn't move:** for local files it analyses the track directly, so it should always work. For internet radio and audio CDs with the mpv engine on Linux, it listens to the PipeWire/PulseAudio monitor instead. +- **"No covers found" / lyrics or Last.fm can't connect:** the cover dialog now shows the actual network error. Packaged builds include their own certificate bundle, so HTTPS works on every distro. - **Nothing plays in the AppImage/tarball:** they use the built-in Qt engine by default. If you switched the engine to mpv in Settings, switch it back to *Automatic*. - **No EQ or gapless option (Linux):** install `mpv` (see the table above) and restart. - **The AppImage won't start:** some distros need `libfuse2`. Or run it with `./Mulberry-x86_64.AppImage --appimage-extract-and-run`. diff --git a/mulberry/__main__.py b/mulberry/__main__.py index 96d10c9..7dc6baf 100644 --- a/mulberry/__main__.py +++ b/mulberry/__main__.py @@ -106,6 +106,13 @@ def main(): f"dark={Th.theme.dark}\nprimary={Th.theme['primary'].name()}\n" f"font={Th.theme.font_family}\nmedia_keys={getattr(win.media_keys, 'ok', None)}\n" f"mpris={win.mpris.ok}\n") + try: + import yt_dlp # noqa: F401 + yt = True + except Exception: # noqa: BLE001 + yt = False + from .online import ssl_context + fh.write(f"ytdlp={yt}\nssl_ca={ssl_context().cert_store_stats().get('x509_ca', 0)}\n") finally: win.quit_app() play = os.environ.get("MULBERRY_SELFTEST_PLAY") diff --git a/mulberry/config.py b/mulberry/config.py index c63f6c3..9c0ad8d 100644 --- a/mulberry/config.py +++ b/mulberry/config.py @@ -10,7 +10,7 @@ from PyQt6.QtCore import QObject, QRunnable, QSettings, QThreadPool, pyqtSignal APP_NAME = "Mulberry" APP_ID = "mulberry" -VERSION = "1.2.0" +VERSION = "1.2.1" USER_AGENT = f"{APP_NAME}/{VERSION} ( https://github.com/BeamStarTech/Mulberry )" IS_WIN = sys.platform == "win32" diff --git a/mulberry/mainwindow.py b/mulberry/mainwindow.py index 8164622..5636b98 100644 --- a/mulberry/mainwindow.py +++ b/mulberry/mainwindow.py @@ -463,7 +463,8 @@ class MainWindow(QMainWindow): self.add_paths([d], "play") def open_url(self): - url, ok = QInputDialog.getText(self, "Open stream", "URL:") + url, ok = QInputDialog.getText(self, "Open URL", + "Internet radio stream, or a YouTube / SoundCloud / Bandcamp link:") if ok and url.strip(): self.add_songs([Song(url=url.strip(), title=url.strip(), filetype="Stream")], "play") @@ -496,9 +497,9 @@ class MainWindow(QMainWindow): return if not os.path.splitext(path)[1]: path += "." + flt.split("*.")[1].rstrip(")") - rel = QMessageBox.question(self, "Export playlist", "Use paths relative to the playlist file?\n" - "(Recommended if you move the music folder with the playlist.)") \ - == QMessageBox.StandardButton.Yes + # absolute paths by default (works from anywhere); relative is opt-in + # in "Export all playlists…" + rel = settings.raw().value("export/relative_paths", "false") in (True, "true") try: export_playlist(path, pl.songs, rel) self.toast(f"Exported {len(pl.songs)} tracks to {os.path.basename(path)}") diff --git a/mulberry/nowplaying.py b/mulberry/nowplaying.py index 18862bf..be15b9a 100644 --- a/mulberry/nowplaying.py +++ b/mulberry/nowplaying.py @@ -146,77 +146,100 @@ class NowPlaying(QObject): # ------------------------------------------------------------------ lyrics def lyr_key(self, s: Song): - if s.is_stream: + 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): - """Sources: auto (local .lrc → synced embedded → LRCLIB → NetEase → - plain embedded), or one specific provider chosen in the lyrics menu.""" + """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 = key if source == "auto" else f"{key}|{source}" + 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: + 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 - # 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 + 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) + 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) + self._emit_lyrics(emb, "Embedded tags", s) if emb.strip() else self._emit_lyrics("", "noembedded", 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 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 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 + if txt is not None: + return decide(txt, src) + if not settings.get("online/auto_lyrics"): + return decide("", "") 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) + 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: - 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) + 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) diff --git a/mulberry/online.py b/mulberry/online.py index b25f90a..b78599d 100644 --- a/mulberry/online.py +++ b/mulberry/online.py @@ -20,12 +20,50 @@ _mb_lock = threading.Lock() _mb_last = [0.0] +_SSL_CTX = None + + +def ssl_context(): + """A TLS context that works everywhere. Packaged builds carry an OpenSSL + compiled for another distro whose default CA path may not exist here + (e.g. Ubuntu's /usr/lib/ssl on Arch), which silently broke every HTTPS + request. Fall back to known system bundles, then to certifi.""" + global _SSL_CTX + if _SSL_CTX is not None: + return _SSL_CTX + import os + import ssl + ctx = ssl.create_default_context() + try: + have = ctx.cert_store_stats().get("x509_ca", 0) + except Exception: # noqa: BLE001 + have = 0 + if not have: + for cand in ("/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", + "/etc/ssl/ca-bundle.pem", "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", + "/etc/ssl/cert.pem"): + if os.path.exists(cand): + try: + ctx.load_verify_locations(cafile=cand) + have = 1 + break + except Exception: # noqa: BLE001 + pass + if not have: + try: + import certifi + ctx.load_verify_locations(cafile=certifi.where()) + except Exception: # noqa: BLE001 + pass + _SSL_CTX = ctx + return ctx + + def http_get(url: str, params: dict | None = None, timeout=12, headers=None, raw=False): if params: url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) - req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json", - **(headers or {})}) - with urllib.request.urlopen(req, timeout=timeout) as r: + req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, **(headers or {})}) + with urllib.request.urlopen(req, timeout=timeout, context=ssl_context()) as r: data = r.read() if raw: return data @@ -36,7 +74,7 @@ def http_post(url: str, data: dict | bytes, timeout=12, headers=None): body = data if isinstance(data, bytes) else urllib.parse.urlencode(data).encode() req = urllib.request.Request(url, data=body, method="POST", headers={"User-Agent": USER_AGENT, **(headers or {})}) - with urllib.request.urlopen(req, timeout=timeout) as r: + with urllib.request.urlopen(req, timeout=timeout, context=ssl_context()) as r: return json.loads(r.read().decode("utf-8", "replace") or "{}") @@ -72,13 +110,18 @@ def musicbrainz_search(song: Song, limit=15) -> list[dict]: return [] res = mb_get("recording", {"query": " AND ".join(parts[:2]) + (f" AND ({parts[2]})" if len(parts) > 2 else ""), "limit": limit}) + if not res.get("recordings") and len(parts) > 2: + # album tag differs from MusicBrainz ("(Deluxe)", typos…): search without it + res = mb_get("recording", {"query": " AND ".join(parts[:2]), "limit": limit}) out = [] for rec in res.get("recordings", []): - artist = "".join(a.get("name", "") + a.get("joinphrase", "") for a in rec.get("artist-credit", [])) + credits = rec.get("artist-credit", []) + artist = "".join(a.get("name", "") + a.get("joinphrase", "") for a in credits) + main_artist = credits[0].get("name", artist) if credits else artist for rel in rec.get("releases", [])[:4] or [{}]: media = (rel.get("media") or [{}])[0] trk = (media.get("track") or [{}])[0] - ra = "".join(a.get("name", "") + a.get("joinphrase", "") for a in rel.get("artist-credit", [])) or artist + ra = "".join(a.get("name", "") + a.get("joinphrase", "") for a in rel.get("artist-credit", [])) or main_artist out.append({ "title": rec.get("title", ""), "artist": artist, "album": rel.get("title", ""), "albumartist": ra, "year": int((rel.get("date") or "0")[:4] or 0), @@ -142,6 +185,9 @@ def cover_candidates(artist: str, album: str, title: str = "") -> list[dict]: def itunes(): r = http_get("https://itunes.apple.com/search", {"term": term, "entity": "album" if album else "song", "limit": 8}) + if not r.get("results") and album: + r = http_get("https://itunes.apple.com/search", {"term": f"{artist} {title or album}", "entity": "song", + "limit": 8}) for it in r.get("results", []): u = it.get("artworkUrl100") if u: @@ -150,6 +196,8 @@ def cover_candidates(artist: str, album: str, title: str = "") -> list[dict]: def deezer(): r = http_get("https://api.deezer.com/search/album", {"q": f'artist:"{artist}" album:"{album or title}"'}) + if not r.get("data"): + r = http_get("https://api.deezer.com/search/album", {"q": term}) for it in (r.get("data") or [])[:8]: if it.get("cover_xl"): out.append({"url": it["cover_xl"], "thumb": it.get("cover_medium") or it["cover_xl"], @@ -172,7 +220,8 @@ def cover_candidates(artist: str, album: str, title: str = "") -> list[dict]: if not key or not album: return r = http_get("https://ws.audioscrobbler.com/2.0/", {"method": "album.getinfo", "api_key": key, - "artist": artist, "album": album, "format": "json"}) + "artist": artist, "album": album, "format": "json", + "autocorrect": 1}) imgs = r.get("album", {}).get("image", []) if imgs and imgs[-1].get("#text"): u = imgs[-1]["#text"] @@ -192,14 +241,22 @@ def cover_candidates(artist: str, album: str, title: str = "") -> list[dict]: t.join(20) order = {"Cover Art Archive": 0, "iTunes": 1, "Deezer": 2, "Last.fm": 3} out.sort(key=lambda c: order.get(c["source"], 9)) - return out + # de-duplicate identical image URLs + seen, uniq = set(), [] + for c in out: + if c["url"] not in seen: + seen.add(c["url"]) + uniq.append(c) + if not uniq and errors: + raise RuntimeError("Couldn't reach the cover services — " + errors[0][:160]) + return uniq def best_cover(artist: str, album: str, title: str = "") -> bytes | None: """Automatic fetch: try providers in order, return image bytes.""" if not artist and not album: return None - for fn in (_auto_itunes, _auto_deezer): + for fn in (_auto_itunes, _auto_deezer, _auto_lastfm): try: u = fn(artist, album, title) if u: @@ -229,6 +286,19 @@ def _auto_itunes(artist, album, title): return None +def _auto_lastfm(artist, album, title): + from .scrobble import LastFM + key = LastFM.key()[0] + if not key or not album: + return None + r = http_get("https://ws.audioscrobbler.com/2.0/", {"method": "album.getinfo", "api_key": key, + "artist": artist, "album": album, "format": "json", + "autocorrect": 1}) + imgs = (r.get("album") or {}).get("image") or [] + u = imgs[-1].get("#text") if imgs else "" + return re.sub(r"/\d+x\d+/", "/", u) if u else None + + def _auto_deezer(artist, album, title): r = http_get("https://api.deezer.com/search/album", {"q": f'artist:"{artist}" album:"{album or title}"'}) for it in r.get("data") or []: @@ -292,19 +362,22 @@ def lyrics_netease(song: Song) -> str: if not title: return "" q = f"{_clean(title)} {artist}".strip() - r = http_get("https://music.163.com/api/search/get/web", + # cloudsearch/pc returns plain JSON abroad (search/get/web is encrypted + # for non-Chinese IPs, which made NetEase silently return nothing) + r = http_get("https://music.163.com/api/cloudsearch/pc", {"s": q, "type": 1, "offset": 0, "limit": 10}, headers=_NE_HEADERS) songs = (r.get("result") or {}).get("songs") or [] best, best_score = None, -1e9 for it in songs: score = 0.0 - names = " ".join(a.get("name", "") for a in it.get("artists", [])) + names = " ".join(a.get("name", "") for a in (it.get("ar") or it.get("artists") or [])) if _norm(artist) and (_norm(artist) in _norm(names) or _norm(names) in _norm(artist)): score += 50 if _norm(_clean(title)) == _norm(_clean(it.get("name", ""))): score += 30 - if song.duration() and it.get("duration"): - score -= min(40, abs(it["duration"] / 1000 - song.duration()) * 4) + dur = it.get("dt") or it.get("duration") + if song.duration() and dur: + score -= min(40, abs(dur / 1000 - song.duration()) * 4) if score > best_score: best, best_score = it, score if not best or best_score < 0: @@ -397,3 +470,41 @@ def artist_info(artist: str) -> str: return r.get("extract", "") except Exception: # noqa: BLE001 return "" + + +# ------------------------------------------------------------------ web video/audio links +RESOLVE_HOSTS = ("youtube.com", "youtu.be", "music.youtube.com", "soundcloud.com", "bandcamp.com", + "vimeo.com", "mixcloud.com", "twitch.tv", "dailymotion.com", "audiomack.com", + "archive.org", "bilibili.com", "nicovideo.jp", "odysee.com", "rumble.com") + + +def needs_resolve(url: str) -> bool: + """Page links (YouTube, SoundCloud…) need yt-dlp; radio streams don't.""" + host = urllib.parse.urlparse(url).netloc.lower() + return any(host == h or host.endswith("." + h) for h in RESOLVE_HOSTS) + + +def resolve_stream(url: str) -> dict: + """Use yt-dlp (bundled as a Python module) to get a playable audio URL.""" + try: + import yt_dlp + except ImportError as e: + raise RuntimeError("Playing web links needs yt-dlp (pip install yt-dlp).") from e + opts = {"format": "bestaudio[acodec!=none]/bestaudio/best", "quiet": True, "no_warnings": True, + "noplaylist": True, "skip_download": True, "socket_timeout": 15, "extract_flat": False} + with yt_dlp.YoutubeDL(opts) as ydl: + info = ydl.extract_info(url, download=False) + if info.get("_type") == "playlist" and info.get("entries"): + info = next(e for e in info["entries"] if e) + direct = info.get("url") + if not direct and info.get("requested_formats"): + direct = info["requested_formats"][0].get("url") + if not direct: + raise RuntimeError("No playable audio found at that link.") + title = info.get("track") or info.get("title") or url + artist = info.get("artist") or info.get("uploader") or info.get("channel") or "" + thumbs = sorted(info.get("thumbnails") or [], key=lambda t: (t.get("preference") or 0, t.get("width") or 0)) + thumb = info.get("thumbnail") or (thumbs[-1]["url"] if thumbs else "") + return {"url": direct, "title": title, "artist": artist, "album": info.get("album") or "", + "duration": float(info.get("duration") or 0), "live": bool(info.get("is_live")), + "thumbnail": thumb, "headers": info.get("http_headers") or {}} diff --git a/mulberry/player.py b/mulberry/player.py index a2f11f7..70f25f6 100644 --- a/mulberry/player.py +++ b/mulberry/player.py @@ -205,7 +205,7 @@ class MpvBackend(Backend): def _url(song: Song): if song.is_cd: return "cdda://" - return song.path if song.is_local else song.url + return song.path if song.is_local else (song.resolved or song.url) def load(self, song, next_song=None, start=0.0, paused=False): self._has_next = False @@ -411,7 +411,7 @@ class QtBackend(Backend): self._song = song self._end_sent = False self._pending_seek = song.begin + start - url = QUrl.fromLocalFile(song.path) if song.is_local else QUrl(song.url) + url = QUrl.fromLocalFile(song.path) if song.is_local else QUrl(song.resolved or song.url) self.p.setSource(url) if paused: self.p.pause() @@ -495,14 +495,11 @@ class Player(QObject): self.backend_error = ("No audio engine could start.\n" + "\n".join(errors) + "\n\nInstall mpv, or PulseAudio/PipeWire's libpulse (pipewire-pulse).") b = self.backend - b.position.connect(self._on_pos) - b.duration.connect(self._on_dur) - b.state.connect(self._on_state) - b.ended.connect(self._on_ended) - b.advanced.connect(self._on_advanced) - b.error.connect(self._on_error) + self.main_backend = b + self._alt_mpv: Backend | None = None + self._resolve_token = None + self._wire(b) self._errors = 0 - b.stream_meta.connect(self._on_stream_meta) self.song: Song | None = None self.playlist: PlaylistModel | None = None self.state = "stopped" @@ -522,6 +519,48 @@ class Player(QObject): self.apply_audio_settings() manager.queue_changed.connect(self.refresh_next) + def _wire(self, b: Backend): + """Connect a backend; events from a backend that isn't active are ignored.""" + def guard(fn): + return lambda *a: fn(*a) if b is self.backend else None + b.position.connect(guard(self._on_pos)) + b.duration.connect(guard(self._on_dur)) + b.state.connect(guard(self._on_state)) + b.ended.connect(guard(self._on_ended)) + b.advanced.connect(guard(self._on_advanced)) + b.error.connect(guard(self._on_error)) + b.stream_meta.connect(guard(self._on_stream_meta)) + + def _backend_for(self, song: Song) -> Backend: + """Audio CDs need mpv. If the main engine is Qt (default on Windows and + in packaged Linux builds), use a second, mpv engine just for CD tracks.""" + if song.is_cd and self.main_backend.name != "mpv" and mpv_available(): + if self._alt_mpv is None: + try: + self._alt_mpv = MpvBackend() + self._wire(self._alt_mpv) + except Exception as e: # noqa: BLE001 + print("mpv for CD playback unavailable:", e) + self._alt_mpv = Backend() + self._alt_mpv.name = "none" + if self._alt_mpv.name == "mpv": + return self._alt_mpv + return self.main_backend + + def _switch_backend(self, target: Backend): + if target is self.backend: + return + try: + self.backend.stop() + except Exception: # noqa: BLE001 + pass + self.backend = target + target.set_volume(self.volume) + dev = settings.get("playback/device") + if dev and target is self.main_backend: + target.set_device(dev) + self.apply_audio_settings() + # ---------------------------------------------------------------- settings def apply_audio_settings(self): b = self.backend @@ -553,22 +592,89 @@ class Player(QObject): self._played_marked = False self._listen = 0.0 self._start_ts = int(time.time()) + self._resolve_token = None + from . import online + if song.is_stream and online.needs_resolve(song.url) and ( + not song.resolved or time.time() - song.resolved_at > 3600): + self._resolve_and_play(song, start, paused) + return + self._load_current(song, start, paused) + + def _load_current(self, song: Song, start=0.0, paused=False): + self._switch_backend(self._backend_for(song)) self._apply_rg() nxt = self.mgr.peek_next(auto=True) + # gapless pre-loading only makes sense within one engine and for files + if nxt and (self._backend_for(nxt[1]) is not self.backend or nxt[1].is_stream): + nxt_for_engine = None + else: + nxt_for_engine = nxt[1] if nxt else None self._next_planned = nxt - self.backend.load(song, nxt[1] if nxt else None, start, paused) + self.backend.load(song, nxt_for_engine, start, paused) self.song_changed.emit(song) if not paused: self.track_started.emit(song) self.mgr.schedule_save() + def _resolve_and_play(self, song: Song, start, paused): + """YouTube/SoundCloud/… links: ask yt-dlp for the audio stream first.""" + from . import online + from . import tags as T + from .config import run_async + token = object() + self._resolve_token = token + self.song_changed.emit(song) + self.state = "loading" + self.state_changed.emit("loading") + self.message.emit("Opening link…") + url = song.url + + def work(): + info = online.resolve_stream(url) + if info.get("thumbnail"): + try: + data = online.download(info["thumbnail"]) + info["art"] = T.store_cover(data, T.album_key("web", url)) or "" + except Exception: # noqa: BLE001 + info["art"] = "" + return info + + def done(info): + if self._resolve_token is not token or self.song is not song: + return + song.resolved, song.resolved_at = info["url"], time.time() + if not song.title or song.title == song.url or song.title.startswith(("http://", "https://")): + song.title = info["title"] + if not song.artist: + song.artist = info["artist"] + if info.get("album") and not song.album: + song.album = info["album"] + if info["duration"] and not info["live"]: + song.length = info["duration"] + self.dur = song.length + if info.get("art"): + song.art = info["art"] + song.filetype = song.filetype if song.filetype not in ("", "Stream") else "Web" + if self.playlist is not None: + self.playlist.refresh_song(song) + self.playlist.dirty = True + self._load_current(song, start, paused) + + def fail(msg): + if self._resolve_token is not token: + return + self.message.emit(f"Couldn't open that link: {msg}") + self.song_ended_stop() + run_async(work, on_done=done, on_error=fail) + def refresh_next(self): - if self.song is None or self.state == "stopped": + if self.song is None or self.state in ("stopped", "loading"): return nxt = self.mgr.peek_next(auto=True) if nxt != self._next_planned: self._next_planned = nxt - self.backend.set_next(nxt[1] if nxt else None) + ok = nxt and self._backend_for(nxt[1]) is self.backend and not nxt[1].is_stream + self.backend.set_next(nxt[1] if ok else None) def play(self): if self.state == "paused": @@ -593,6 +699,7 @@ class Player(QObject): self.play() def stop(self): + self._resolve_token = None self._finish_current(skipped=False) self.backend.stop() self.state = "stopped" @@ -740,7 +847,8 @@ class Player(QObject): self.track_started.emit(song) nxt = self.mgr.peek_next(auto=True) self._next_planned = nxt - self.backend.set_next(nxt[1] if nxt else None) + ok = nxt and self._backend_for(nxt[1]) is self.backend and not nxt[1].is_stream + self.backend.set_next(nxt[1] if ok else None) def _on_stream_meta(self, md): if self.song and self.song.is_stream: @@ -753,7 +861,9 @@ class Player(QObject): def shutdown(self): self._finish_current(skipped=False) - self.backend.shutdown() + self.main_backend.shutdown() + if self._alt_mpv is not None: + self._alt_mpv.shutdown() def db_to_lin(db): diff --git a/mulberry/playlist.py b/mulberry/playlist.py index 30bdc6a..88da0e1 100644 --- a/mulberry/playlist.py +++ b/mulberry/playlist.py @@ -679,8 +679,30 @@ class PlaylistManager(QObject): PLAYLIST_EXTS_SET = {"m3u", "m3u8", "pls", "xspf", "wpl", "asx", "cue"} +def _remap_missing(songs: list[Song]) -> None: + """Playlists made on another computer/OS (different home folder, drive + letters, / vs \\): find each missing file in the library by its last two + path parts (album folder + file name) and point the entry there.""" + missing = [s for s in songs if s.is_local and not os.path.exists(s.path)] + if not missing or L.library is None: + return + for s in missing: + parts = [p for p in s.path.replace("\\", "/").split("/") if p] + if not parts: + continue + tails = ["/".join(parts[-2:]), parts[-1]] if len(parts) > 1 else [parts[-1]] + for tail in tails: + rows = L.library.query( + "SELECT url FROM songs WHERE lower(replace(substr(url, -?), '\\', '/')) = lower(?) LIMIT 2", + (len(tail) + 1, "/" + tail)) + if len(rows) == 1: + s.url = rows[0]["url"] + break + + def enrich(songs: list[Song]) -> list[Song]: """Replace bare playlist entries with full tag info (library or file).""" + _remap_missing(songs) plain = [s for s in songs if s.is_local and not s.begin and not s.end] if not plain: return songs diff --git a/mulberry/playlistio.py b/mulberry/playlistio.py index 3bd5fe6..ba7f2b2 100644 --- a/mulberry/playlistio.py +++ b/mulberry/playlistio.py @@ -19,10 +19,13 @@ def _resolve(entry: str, base: Path) -> str: entry = entry.strip() if not entry: return "" - if entry.startswith("file://"): - return urllib.parse.unquote(urllib.parse.urlparse(entry).path) + if entry.startswith("file:"): + import urllib.request + return urllib.request.url2pathname(urllib.parse.unquote(urllib.parse.urlparse(entry).path)) if re.match(r"^[a-z][a-z0-9+.-]*://", entry, re.I): return entry + if re.match(r"^[A-Za-z]:[\\/]", entry) and os.name != "nt": + return entry # Windows path in a playlist read on Linux: remapped later via the library entry = entry.replace("\\", "/") p = Path(entry) if not p.is_absolute(): diff --git a/mulberry/song.py b/mulberry/song.py index 7459aba..399b4ff 100644 --- a/mulberry/song.py +++ b/mulberry/song.py @@ -42,6 +42,8 @@ class Song: cd_track: int = 0 cd_device: str = "" stream_title: str = field(default="", compare=False) + resolved: str = field(default="", compare=False) # direct media URL from yt-dlp (expires) + resolved_at: float = field(default=0.0, compare=False) # ---------------------------------------------------------------- helpers @property @@ -96,6 +98,8 @@ class Song: def to_dict(self) -> dict: d = asdict(self) # keep the stored json compact + d.pop("resolved", None) + d.pop("resolved_at", None) return {k: v for k, v in d.items() if v not in ("", 0, 0.0, None, -1) or k == "url"} @classmethod diff --git a/mulberry/widgets/dialogs.py b/mulberry/widgets/dialogs.py index ce0db78..eb724e5 100644 --- a/mulberry/widgets/dialogs.py +++ b/mulberry/widgets/dialogs.py @@ -127,8 +127,11 @@ class SettingsDialog(QDialog): self.backend.setCurrentIndex(max(0, self.backend.findData(settings.get("playback/backend")))) f.addRow("Backend", self.backend) cur = Player.instance.backend.name + from ..config import IS_WIN note = QLabel(f"In use: {cur}" + ("" if mpv_available() else - " — libmpv not found; install mpv for gapless, EQ and CD playback.") + + (" — the bundled libmpv failed to load." if IS_WIN else + " — libmpv not found; install mpv for gapless, EQ and CD playback.")) + + "
Audio CDs always use mpv automatically when it's available." + "
Backend changes apply after restart." + ("
AppImage/packaged build: mpv uses your system's libmpv; if songs don't " "start with it, switch back to Qt." if (FROZEN and IS_LINUX) else "")) @@ -759,10 +762,21 @@ class MusicBrainzDialog(QDialog): def accept(self): r = self.table.currentRow() - if 0 <= r < len(self.cands): - self.choice = dict(self.cands[r]) - if self.genre.isChecked() and self.choice.get("mb_albumid"): - self.choice["genre"] = online.musicbrainz_genre(self.choice["mb_albumid"]) + if not (0 <= r < len(self.cands)): + return + self.choice = dict(self.cands[r]) + if self.genre.isChecked() and self.choice.get("mb_albumid"): + self.status.setText("Fetching genre…") + self.setEnabled(False) + + def got(g): + if g: + self.choice["genre"] = g + self.setEnabled(True) + QDialog.accept(self) + run_async(online.musicbrainz_genre, self.choice["mb_albumid"], on_done=got, + on_error=lambda e: (self.setEnabled(True), QDialog.accept(self))) + return super().accept() @@ -996,6 +1010,8 @@ class EqualizerDialog(QDialog): # ====================================================================== ripper class RipDialog(QDialog): + _alive: set = set() # running Ripper threads (class-level, outlives the dialog) + def __init__(self, songs: list[Song], cover: bytes | None, parent): super().__init__(parent) self.songs, self.cover = songs, cover @@ -1048,6 +1064,11 @@ class RipDialog(QDialog): self.pat.text(), self.cover) self.ripper.progress.connect(lambda i, n, m: (self.bar.setValue(i), self.msg.setText(m))) self.ripper.finished_rip.connect(self._done) + # keep the QThread alive until run() has fully returned: destroying a + # running QThread aborts the whole app (the crash after ripping) + _keep = self.ripper + RipDialog._alive.add(_keep) + _keep.finished.connect(lambda: RipDialog._alive.discard(_keep)) self.start.setEnabled(False) self.cancel.setText("Cancel") self.ripper.start() @@ -1061,7 +1082,7 @@ class RipDialog(QDialog): d = self.dir.text() if not any(d.startswith(f) for f in folders): settings.set("library/folders", folders + [d]) - L.library.scan(False) + QTimer.singleShot(1500, lambda: L.library.scan(False)) self.ripper = None def _cancel(self): @@ -1073,9 +1094,15 @@ class RipDialog(QDialog): def closeEvent(self, e): if self.ripper is not None: self.ripper.cancel() - self.ripper.wait(3000) + self.ripper.wait(5000) super().closeEvent(e) + def reject(self): + if self.ripper is not None: + self.ripper.cancel() + self.ripper.wait(5000) + super().reject() + # ====================================================================== lyrics/about class LyricsEditor(QDialog): @@ -1161,8 +1188,8 @@ class ExportAllDialog(QDialog): self.exists.setCurrentIndex(max(0, self.exists.findData(settings.raw().value("export/exists", "replace")))) f.addRow("If a file already exists", self.exists) lay.addLayout(f) - self.relative = QCheckBox("Use paths relative to the playlist folder") - self.relative.setChecked(settings.raw().value("export/relative", "true") in (True, "true")) + self.relative = QCheckBox("Use paths relative to the playlist folder (only if you move music and playlists together)") + self.relative.setChecked(settings.raw().value("export/relative_paths", "false") in (True, "true")) self.closed = QCheckBox("Also export saved playlists that are currently closed") self.closed.setChecked(True) lay.addWidget(self.relative) @@ -1195,7 +1222,7 @@ class ExportAllDialog(QDialog): q.setValue("export/folder", str(folder)) q.setValue("export/format", ext) q.setValue("export/exists", mode) - q.setValue("export/relative", rel) + q.setValue("export/relative_paths", rel) lists = [(p.name, list(p.songs)) for p in self.w.mgr.playlists] if self.closed.isChecked(): open_ids = {p.pid for p in self.w.mgr.playlists} diff --git a/mulberry/widgets/hero.py b/mulberry/widgets/hero.py index 3dc4e17..3077a3e 100644 --- a/mulberry/widgets/hero.py +++ b/mulberry/widgets/hero.py @@ -614,10 +614,15 @@ class Hero(QWidget): a, t = st.split(" - ", 1) self.title.setText(t) self.artist.setText(a) + self.album.setText(s.title) + elif st: + self.title.setText(st) + self.artist.setText(s.title) + self.album.setText("") else: - self.title.setText(st or s.title or "Radio stream") - self.artist.setText(s.title if st else "") - self.album.setText(s.title if st else s.url) + self.title.setText(s.title or "Stream") + self.artist.setText(s.artist) + self.album.setText(s.album or (s.url if not s.resolved else "")) elif s.is_cd and not s.mb_albumid: self.title.setText(s.display_title()) self.artist.setText(s.display_artist() or "Unknown artist") @@ -641,7 +646,7 @@ class Hero(QWidget): self.love.setText("Loved" if loved else "Love") self.love.icon_name = "favorite_fill" if loved else "favorite" self.love.update() - self.dur_lbl.setText(fmt_time(s.duration()) if not s.is_stream else "LIVE") + self.dur_lbl.setText("LIVE" if (s.is_stream and not s.length) else fmt_time(s.duration())) if self._show_info: self.np.load_artist_info() @@ -680,6 +685,11 @@ class Hero(QWidget): elif source == "unknowncd": self.lyrics.set_message("This disc isn't in MusicBrainz, so there's nothing to look up.\n" "Lyrics, covers and artist info are off for it.") + elif source.startswith("none:"): + self.lyrics.set_message(f"{source[5:]} has no lyrics for this song.\n" + "Pick another source in ⋮, or Auto.") + elif source == "noembedded": + self.lyrics.set_message("No lyrics are embedded in this file.\nPick another source in ⋮.") elif source == "nolocal": self.lyrics.set_message("No .lrc file next to this song.\nUse LRCGET to download them, " "or pick another source in ⋮.") @@ -689,7 +699,8 @@ class Hero(QWidget): self.lyrics.set_text(text, plain_only=settings.get("lyrics/plain")) self.lyrics.set_position(self.player.pos) self.l_title.setText("Lyrics") - shown = source if source not in ("loading", "error", "nolocal", "unknowncd", "") else "" + shown = source if (source not in ("loading", "error", "nolocal", "noembedded", "unknowncd", "") + and not source.startswith("none:")) else "" if shown and settings.get("lyrics/plain"): shown += " · plain" self.l_src.setText(shown) @@ -712,7 +723,7 @@ class Hero(QWidget): m.addSeparator() src_menu = m.addMenu(icon("cloud_download"), "Lyrics source") cur = settings.get("lyrics/source") - for key, label in (("auto", "Auto (local → LRCLIB → NetEase)"), ("lrclib", "LRCLIB"), + for key, label in (("auto", "Auto (synced first: LRCLIB → NetEase → embedded → local)"), ("lrclib", "LRCLIB"), ("netease", "NetEase Cloud Music"), ("local", "Local .lrc files (LRCGET)"), ("embedded", "Embedded in the audio file")): a = src_menu.addAction(label) diff --git a/packaging/mulberry.spec b/packaging/mulberry.spec index d4af203..e1a2cda 100644 --- a/packaging/mulberry.spec +++ b/packaging/mulberry.spec @@ -16,7 +16,7 @@ if IS_WIN and mpv_dir.is_dir(): for f in mpv_dir.glob("*.dll"): binaries.append((str(f), ".")) -hidden = ["mulberry.winmedia", "mulberry.mpris", "mutagen", "numpy", "mpv", +hidden = ["mulberry.winmedia", "mulberry.mpris", "mutagen", "numpy", "mpv", "certifi", "yt_dlp", "PyQt6.QtMultimedia", "PyQt6.QtSvg", "PyQt6.QtNetwork"] if not IS_WIN: hidden.append("PyQt6.QtDBus") diff --git a/packaging/windows/mulberry.iss b/packaging/windows/mulberry.iss index 1dddc1d..a84e3a9 100644 --- a/packaging/windows/mulberry.iss +++ b/packaging/windows/mulberry.iss @@ -1,6 +1,6 @@ -; Inno Setup script — built by CI: iscc /DAppVersion=1.2.0 packaging\windows\mulberry.iss +; Inno Setup script — built by CI: iscc /DAppVersion=1.2.1 packaging\windows\mulberry.iss #ifndef AppVersion - #define AppVersion "1.2.0" + #define AppVersion "1.2.1" #endif [Setup] diff --git a/packaging/windows/version.txt b/packaging/windows/version.txt index 8c68f5a..23a2f8b 100644 --- a/packaging/windows/version.txt +++ b/packaging/windows/version.txt @@ -1,15 +1,15 @@ VSVersionInfo( - ffi=FixedFileInfo(filevers=(1, 2, 0, 0), prodvers=(1, 2, 0, 0), mask=0x3f, flags=0x0, OS=0x40004, + ffi=FixedFileInfo(filevers=(1, 2, 1, 0), prodvers=(1, 2, 1, 0), mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1, subtype=0x0, date=(0, 0)), kids=[ StringFileInfo([StringTable('040904B0', [ StringStruct('CompanyName', 'Mulberry'), StringStruct('FileDescription', 'Mulberry Music Player'), - StringStruct('FileVersion', '1.2.0'), + StringStruct('FileVersion', '1.2.1'), StringStruct('InternalName', 'Mulberry'), StringStruct('OriginalFilename', 'Mulberry.exe'), StringStruct('ProductName', 'Mulberry'), - StringStruct('ProductVersion', '1.2.0')])]), + StringStruct('ProductVersion', '1.2.1')])]), VarFileInfo([VarStruct('Translation', [1033, 1200])]) ] ) diff --git a/requirements.txt b/requirements.txt index 61b535e..812b252 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,5 @@ PyQt6>=6.6 mutagen>=1.47 numpy>=1.24 python-mpv>=1.0 +certifi>=2023.7 +yt-dlp>=2025.1