From 2cc0338156418455c689939455f31e59c22b07fa Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 00:04:21 -0500 Subject: [PATCH] Mulberry 1.2.0: fix packaged playback, track-synced visualizer, Last.fm login - Packaged builds: keep Qt6Quick/Qml (the FFmpeg media plugin links them); pruning them disabled all playback in the AppImage/tarball - Visualizer decodes each track ahead (QAudioDecoder) and follows the playback position: works with mpv and Qt, no PipeWire monitor needed for local files - Packaged Linux builds default to the self-contained Qt engine - Last.fm: built-in app key, browser login returns to a 127.0.0.1 callback; now-playing is re-sent on resume - Export all playlists (folder, file type, replace/skip/number) - Unknown/burned CDs: CD placeholder art, no online lookups - install.sh: --uninstall, --purge, requirement checks, launch log - CI self-tests now play a file and assert decoding + visualizer output Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq --- .github/workflows/build.yml | 14 ++- README.md | 20 ++-- install.sh | 138 +++++++++++++++++++----- mulberry/__main__.py | 6 ++ mulberry/config.py | 2 +- mulberry/lastfm_app.py | 12 +-- mulberry/mainwindow.py | 8 +- mulberry/nowplaying.py | 81 +++++++++++++- mulberry/player.py | 8 +- mulberry/scrobble.py | 72 ++++++++++++- mulberry/spectrum.py | 128 ++++++++++++++++++++-- mulberry/widgets/dialogs.py | 189 +++++++++++++++++++++++++++++++-- mulberry/widgets/hero.py | 9 +- mulberry/widgets/sidebar.py | 3 + packaging/make_test_audio.py | 17 +++ packaging/mulberry.spec | 6 +- packaging/windows/mulberry.iss | 4 +- packaging/windows/version.txt | 6 +- 18 files changed, 648 insertions(+), 75 deletions(-) create mode 100644 packaging/make_test_audio.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b01f153..cfdb6b9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -46,11 +46,17 @@ jobs: - name: Self-test (launch the built app, screenshot, quit) shell: pwsh run: | + python packaging/make_test_audio.py selftest.wav $env:MULBERRY_SELFTEST = "$PWD\selftest-windows" + $env:MULBERRY_SELFTEST_PLAY = "$PWD\selftest.wav" $p = Start-Process build/dist/Mulberry/Mulberry.exe -PassThru if (-not $p.WaitForExit(90000)) { Stop-Process $p.Id; throw "Mulberry did not finish the self-test" } if (-not (Test-Path selftest-windows.png)) { Write-Output "::error title=Windows self-test::no screenshot"; throw "no screenshot - the app failed to start" } + $r = @{}; Get-Content selftest-windows.txt | ForEach-Object { $k, $v = $_ -split '=', 2; $r[$k] = $v } 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 ([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: name: selftest-windows @@ -93,13 +99,19 @@ jobs: - name: Self-test (launch the built app, screenshot, quit) run: | set +e - QT_QPA_PLATFORM=offscreen MULBERRY_SELFTEST=$PWD/selftest-linux timeout 90 dbus-run-session -- build/dist/Mulberry/mulberry > selftest-linux.log 2>&1 + python packaging/make_test_audio.py selftest.wav + QT_QPA_PLATFORM=offscreen MULBERRY_SELFTEST=$PWD/selftest-linux MULBERRY_SELFTEST_PLAY=$PWD/selftest.wav \ + timeout 90 dbus-run-session -- build/dist/Mulberry/mulberry > selftest-linux.log 2>&1 rc=$? if [ ! -f selftest-linux.png ]; then echo "::error title=Linux self-test failed (rc=$rc)::$(tail -c 3000 selftest-linux.log | tr '\n' '|')" exit 1 fi cat selftest-linux.txt + 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; } + 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: name: selftest-linux diff --git a/README.md b/README.md index 762fda1..821f2cc 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,9 @@ git clone https://github.com/BeamStarTech/Mulberry.git cd Mulberry ``` - **Linux:** run `./install.sh`. It creates a virtual environment, a `mulberry` command and an app-menu entry with an icon. Or just `pip install -r requirements.txt && ./run.sh`. + - Update: `git pull && ./install.sh` + - Uninstall: `./install.sh --uninstall` (keeps your library and settings), or `./install.sh --purge` (removes everything) + - When started from the app menu, output is logged to `~/.cache/mulberry/launch.log` - **Windows:** run `py -m pip install -r requirements.txt` and then `run.bat`. ### Building the packages yourself @@ -93,7 +96,7 @@ The Windows installer is built with [Inno Setup](https://jrsoftware.org/isinfo.p **Look and feel** - Material 3 colour roles built from your system colours: the KDE accent and window colours (`~/.config/kdeglobals`) on Linux, the accent colour and light/dark mode on Windows. Change them and the player recolours instantly. - Other colour sources: dynamic colours taken from the album art, or a custom seed colour. Light/dark either follows the system or can be forced. -- Hero panel: a cookie-shaped cover with a slow-spinning radial spectrum, a wavy M3 Expressive progress bar, a play button that morphs shape, and a synced lyrics card where you can click a line to seek. +- Hero panel: a cookie-shaped cover with a slow-spinning radial spectrum (decoded from the track itself and synced to the playback position, so it works with any audio engine and needs no system-audio capture), a wavy M3 Expressive progress bar, a play button that morphs shape, and a synced lyrics card where you can click a line to seek. - Three layouts: Large, Compact bar, or Hidden (a mini transport moves to the bottom bar). F11 or clicking the cover gives a Focus mode with a big cover and lyrics. - An optional **floating bass shape** in the bottom-left corner (Settings › Appearance, or View menu). It morphs between Material shapes on bass hits, spins, pulses in size and cycles through your theme colours. Click it to play or pause. - The playing track gets a gradient pill, and the album art shows faintly behind the playlist. The bottom bar has a block spectrum analyzer. @@ -106,6 +109,7 @@ 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. - 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. @@ -120,6 +124,7 @@ The Windows installer is built with [Inno Setup](https://jrsoftware.org/isinfo.p **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). +- 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). **Desktop integration** @@ -132,17 +137,17 @@ The Windows installer is built with [Inno Setup](https://jrsoftware.org/isinfo.p | | Linux | Windows | |---|---|---| | Theme source | KDE colour scheme and accent, live (or the Qt palette on other desktops) | Accent colour and light/dark mode, live | -| Default engine | mpv (falls back to Qt) | Qt, so the visualizers work; mpv can be chosen in Settings for EQ and gapless playback | +| Default engine | mpv when run from source; built-in Qt engine in the AppImage/tarball | Qt; mpv (included) can be chosen in Settings for EQ and gapless playback | | OS media controls | MPRIS: Plasma, lock screen, KDE Connect, shells | Global media keys | | Notifications | Desktop notifications with cover art | Tray notifications | | CD ripping | cdparanoia + ffmpeg, or libmpv | Included libmpv | ## Last.fm setup -In **Settings › Scrobbling**, click **Log in with Last.fm**. Your browser opens Last.fm's authorisation page. Click *Yes, allow access* there, and Mulberry detects it within a few seconds; no further clicks are needed. +Open **Settings › Scrobbling** and click **Log in with Last.fm**. Your browser opens Last.fm; click *Yes, allow access*. Last.fm sends the browser back to Mulberry at `http://127.0.0.1:47823`, and you're logged in. Nothing to copy or paste. -Last.fm issues API keys per application, so the login button needs one key for this copy of Mulberry. You only have to add it once: -- **Simplest:** tick *Use my own API key*, create a free key at , paste the key and secret, then press Log in. -- **Or for everyone on the machine:** put the key in `mulberry/lastfm_app.py`, in `~/.config/mulberry/lastfm_app.json` (`{"key": "...", "secret": "..."}`), or in the `MULBERRY_LASTFM_KEY` and `MULBERRY_LASTFM_SECRET` environment variables. After that the login button works without anyone touching keys. +Once logged in, Mulberry sends **Now playing** as each track starts (and again when you resume), scrobbles tracks you listen to for at least half their length or 4 minutes, and syncs **Love**. Offline scrobbles are saved and sent later. ListenBrainz works the same way with a user token. + +Advanced: tick *Use my own API key* to use a personal key instead of Mulberry's built-in one. ## Keyboard shortcuts | Keys | Action | @@ -173,7 +178,8 @@ Last.fm issues API keys per application, so the login button needs one key for t ## Troubleshooting - **No sound, or "Playback error":** in *Settings → Playback*, try the other engine (Qt ↔ mpv) or another output device. -- **The visualizer doesn't move (Linux, mpv engine):** it listens to your speakers' monitor through PipeWire/PulseAudio. Switch the engine to Qt if your setup has no monitor source. +- **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. +- **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`. - **SmartScreen blocks the Windows installer:** click *More info → Run anyway*. The build is unsigned. diff --git a/install.sh b/install.sh index 9b76794..5e5a51c 100755 --- a/install.sh +++ b/install.sh @@ -1,50 +1,130 @@ #!/usr/bin/env bash -# Installs Mulberry for the current user (no root needed for the app itself). +# Mulberry installer for Linux (per-user, no root needed for the app itself). +# +# ./install.sh install or update +# ./install.sh --uninstall remove the app, launcher, menu entry and icon (keeps your library/settings) +# ./install.sh --purge uninstall AND delete your library, playlists, settings and caches +# ./install.sh --help set -euo pipefail -SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PREFIX="${XDG_DATA_HOME:-$HOME/.local/share}/mulberry-app" -BIN="$HOME/.local/bin" -echo "==> Checking system packages" +SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" +CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" +CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}" +PREFIX="$DATA_HOME/mulberry-app" +BIN="$HOME/.local/bin" +APPS="$DATA_HOME/applications" +ICON="$DATA_HOME/icons/hicolor/scalable/apps/mulberry.svg" + +bold() { printf '\033[1m%s\033[0m\n' "$*"; } +ok() { printf ' \033[32m✓\033[0m %s\n' "$*"; } +warn() { printf ' \033[33m!\033[0m %s\n' "$*"; } +die() { printf ' \033[31m✗ %s\033[0m\n' "$*" >&2; exit 1; } + +refresh_menus() { + command -v update-desktop-database >/dev/null && update-desktop-database "$APPS" 2>/dev/null || true + command -v kbuildsycoca6 >/dev/null && kbuildsycoca6 >/dev/null 2>&1 || true + command -v gtk-update-icon-cache >/dev/null && gtk-update-icon-cache -q "$DATA_HOME/icons/hicolor" 2>/dev/null || true +} + +uninstall() { + bold "==> Uninstalling Mulberry" + pkill -f "$PREFIX/venv/bin/python -m mulberry" 2>/dev/null || true + rm -rf "$PREFIX" && ok "removed $PREFIX" + rm -f "$BIN/mulberry" && ok "removed $BIN/mulberry" + rm -f "$APPS/mulberry.desktop" && ok "removed menu entry" + rm -f "$ICON" && ok "removed icon" + refresh_menus + if [[ "${1:-}" == "purge" ]]; then + rm -rf "$DATA_HOME/mulberry" "$CONFIG_HOME/mulberry" "$CACHE_HOME/mulberry" + ok "deleted library, playlists, settings and caches" + else + echo " Your library, playlists and settings were kept in:" + echo " $DATA_HOME/mulberry and $CONFIG_HOME/mulberry" + echo " (run ./install.sh --purge to delete them too)" + fi + bold "Done." +} + +case "${1:-}" in + -h|--help) + sed -n '2,7p' "$0" | sed 's/^# \{0,1\}//' + exit 0 ;; + --uninstall|uninstall) uninstall; exit 0 ;; + --purge|purge) uninstall purge; exit 0 ;; + ""|--install|install|--update|update) ;; + *) die "unknown option: $1 (try --help)" ;; +esac + +bold "==> Checking requirements" +PY="${PYTHON:-python3}" +command -v "$PY" >/dev/null || die "python3 not found — install Python 3.10 or newer" +"$PY" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' \ + || die "Python 3.10+ is required (found $("$PY" --version 2>&1))" +"$PY" -c 'import venv, ensurepip' 2>/dev/null \ + || die "Python's venv module is missing — install it (Debian/Ubuntu: sudo apt install python3-venv)" +ok "$("$PY" --version)" + missing=() -ldconfig -p 2>/dev/null | grep -q libmpv.so || missing+=("mpv / libmpv (gapless, EQ, ReplayGain, audio CD playback)") -command -v cdparanoia >/dev/null || missing+=("cdparanoia (CD ripping)") -command -v ffmpeg >/dev/null || missing+=("ffmpeg (CD rip encoding)") -command -v fpcalc >/dev/null || missing+=("chromaprint / fpcalc (optional: AcoustID fingerprints)") +ldconfig -p 2>/dev/null | grep -q 'libpulse.so.0' || missing+=("libpulse (pipewire-pulse / pulseaudio-libs) — needed by the Qt audio engine") +ldconfig -p 2>/dev/null | grep -q 'libmpv.so' || missing+=("mpv / libmpv — gapless, EQ, ReplayGain, audio CD playback") +command -v cdparanoia >/dev/null || missing+=("cdparanoia — best-quality CD ripping") +command -v ffmpeg >/dev/null || missing+=("ffmpeg — CD rip encoding") if ((${#missing[@]})); then - echo " Optional tools not found (install with your package manager):" + warn "Optional packages not found:" for m in "${missing[@]}"; do echo " - $m"; done - echo " e.g. Arch: sudo pacman -S mpv cdparanoia ffmpeg chromaprint libdiscid" - echo " Fedora: sudo dnf install mpv-libs cdparanoia ffmpeg chromaprint-tools libdiscid" - echo " Debian/Ubuntu/KDE neon: sudo apt install libmpv2 cdparanoia ffmpeg libchromaprint-tools libdiscid0" + echo " Arch: sudo pacman -S mpv cdparanoia ffmpeg libdiscid" + echo " Fedora: sudo dnf install mpv-libs cdparanoia ffmpeg libdiscid" + echo " Debian/Ubuntu: sudo apt install libmpv2 cdparanoia ffmpeg libdiscid0 libpulse0" fi -echo "==> Creating virtual environment in $PREFIX" +bold "==> Creating virtual environment in $PREFIX" mkdir -p "$PREFIX" -python3 -m venv "$PREFIX/venv" -"$PREFIX/venv/bin/pip" install --upgrade pip >/dev/null -"$PREFIX/venv/bin/pip" install -r "$SRC/requirements.txt" -"$PREFIX/venv/bin/pip" install discid >/dev/null 2>&1 || true # optional, uses libdiscid +if [[ ! -x "$PREFIX/venv/bin/python" ]]; then + "$PY" -m venv "$PREFIX/venv" || die "could not create the virtual environment" +fi +"$PREFIX/venv/bin/python" -m pip install --upgrade pip >/dev/null || die "pip upgrade failed" +"$PREFIX/venv/bin/python" -m pip install --upgrade -r "$SRC/requirements.txt" || die "installing Python packages failed" +"$PREFIX/venv/bin/python" -m pip install discid >/dev/null 2>&1 || true # optional (libdiscid) +ok "Python packages installed" -echo "==> Copying application" +bold "==> Copying application" rm -rf "$PREFIX/mulberry" cp -r "$SRC/mulberry" "$PREFIX/mulberry" +find "$PREFIX/mulberry" -name __pycache__ -prune -exec rm -rf {} + +( cd "$PREFIX" && "$PREFIX/venv/bin/python" -c "import mulberry.config, PyQt6.QtWidgets, mutagen, numpy" ) \ + || die "self-check failed: the app's Python modules don't import" +( cd "$PREFIX" && "$PREFIX/venv/bin/python" -c "import PyQt6.QtMultimedia" ) 2>/dev/null \ + || warn "Qt Multimedia couldn't load (usually missing libpulse) — Mulberry will use mpv if installed" +ok "installed to $PREFIX" -mkdir -p "$BIN" +mkdir -p "$BIN" "$CACHE_HOME/mulberry" cat > "$BIN/mulberry" <>"$CACHE_HOME/mulberry/launch.log" 2>&1 +fi LAUNCH chmod +x "$BIN/mulberry" +ok "launcher: $BIN/mulberry" -echo "==> Desktop integration" -APPS="${XDG_DATA_HOME:-$HOME/.local/share}/applications" -ICONS="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/scalable/apps" -mkdir -p "$APPS" "$ICONS" +bold "==> Desktop integration" +mkdir -p "$APPS" "$(dirname "$ICON")" sed "s|^Exec=mulberry|Exec=$BIN/mulberry|" "$SRC/mulberry.desktop" > "$APPS/mulberry.desktop" -cp "$SRC/mulberry/assets/mulberry.svg" "$ICONS/mulberry.svg" -command -v update-desktop-database >/dev/null && update-desktop-database "$APPS" || true -command -v kbuildsycoca6 >/dev/null && kbuildsycoca6 >/dev/null 2>&1 || true +cp "$SRC/mulberry/assets/mulberry.svg" "$ICON" +refresh_menus +ok "app-menu entry and icon" echo -echo "Done! Launch Mulberry from your app menu, or run: mulberry" +bold "Done! Start Mulberry from your app menu, or run: mulberry" +case ":$PATH:" in + *":$BIN:"*) ;; + *) warn "$BIN is not in your PATH — run it as $BIN/mulberry, or add this to your shell profile:" + echo " export PATH=\"\$HOME/.local/bin:\$PATH\"" ;; +esac +echo " Uninstall any time with: ./install.sh --uninstall" diff --git a/mulberry/__main__.py b/mulberry/__main__.py index 17eccb7..96d10c9 100644 --- a/mulberry/__main__.py +++ b/mulberry/__main__.py @@ -99,12 +99,18 @@ def main(): win.resize(1400, 860) win.grab().save(selftest + ".png") with open(selftest + ".txt", "w", encoding="utf-8") as fh: + sp = win.spectrum fh.write(f"engine={Player.instance.backend.name}\nmpv_available={mpv_available()}\n" + f"state={Player.instance.state}\nposition={Player.instance.pos:.2f}\n" + f"visualizer_peak={float(sp.peaks.max()):.3f}\nvisualizer_decoded_s={sp._tlen / 22050:.1f}\n" 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") finally: win.quit_app() + play = os.environ.get("MULBERRY_SELFTEST_PLAY") + if play: + QTimer.singleShot(1500, lambda: win.add_paths([play], "play")) QTimer.singleShot(int(os.environ.get("MULBERRY_SELFTEST_DELAY", "8000")), _report) if args: diff --git a/mulberry/config.py b/mulberry/config.py index 3a7dde8..c63f6c3 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.1.0" +VERSION = "1.2.0" USER_AGENT = f"{APP_NAME}/{VERSION} ( https://github.com/BeamStarTech/Mulberry )" IS_WIN = sys.platform == "win32" diff --git a/mulberry/lastfm_app.py b/mulberry/lastfm_app.py index 5eecd5e..1c1f814 100644 --- a/mulberry/lastfm_app.py +++ b/mulberry/lastfm_app.py @@ -1,13 +1,13 @@ """Application-wide Last.fm API credentials. -Last.fm gives every *application* its own API key. If you register Mulberry once -at https://www.last.fm/api/account/create (any name/description, callback URL can -be left empty) and paste the key + shared secret below, the "Log in with -Last.fm" button works for every user without them touching keys. +Mulberry's own Last.fm application key (registered for the Mulberry project). +Desktop apps ship their key like this; it identifies the app, not a user. +Users just press "Log in with Last.fm" and approve in the browser. They can also be supplied without editing code via the environment variables MULBERRY_LASTFM_KEY / MULBERRY_LASTFM_SECRET or the file ~/.config/mulberry/lastfm_app.json -> {"key": "...", "secret": "..."} """ -API_KEY = "" -API_SECRET = "" +API_KEY = "654be90d519a1688bb90661f8f493c0a" +API_SECRET = "df1f1a14348a083d9aef80820b274931" +CALLBACK_PORT = 47823 # registered callback: http://127.0.0.1:47823/lastfm diff --git a/mulberry/mainwindow.py b/mulberry/mainwindow.py index 0524bf9..8164622 100644 --- a/mulberry/mainwindow.py +++ b/mulberry/mainwindow.py @@ -26,7 +26,7 @@ from .scrobble import Scrobbler from .song import Song from .spectrum import Spectrum from .widgets.analyzer import Analyzer -from .widgets.dialogs import (AboutDialog, BatchTagFetch, CoverManager, EqualizerDialog, +from .widgets.dialogs import (AboutDialog, BatchTagFetch, CoverManager, EqualizerDialog, ExportAllDialog, MusicBrainzDialog, RipDialog, SettingsDialog, TagEditor) from .widgets.bassshape import BassShape from .widgets.hero import Hero @@ -51,6 +51,8 @@ class MainWindow(QMainWindow): self.spectrum = Spectrum(64) if self.player.backend.provides_pcm: self.player.backend.pcm.connect(self.spectrum.push) + self.player.song_changed.connect(self.spectrum.set_track) + self.player.position_changed.connect(lambda pos, _d: self.spectrum.set_position(pos)) self.np = NowPlaying(self.player) self.scrobbler = Scrobbler(self.player) self.scrobbler.status.connect(self.toast) @@ -223,6 +225,7 @@ class MainWindow(QMainWindow): A(p, "New playlist", lambda: self.mgr.new_playlist(), "Ctrl+T", "playlist_add") A(p, "Import playlist…", self.import_playlist, "Ctrl+I", "file_open") A(p, "Export playlist…", lambda: self.export_playlist(self.mgr.current), "Ctrl+S", "save") + A(p, "Export all playlists…", self.export_all, "Ctrl+Shift+S", "download") A(p, "Close playlist", lambda: self.mgr.close_playlist(self.mgr.current), "Ctrl+W", "close") p.addSeparator() A(p, "Undo", lambda: self.mgr.current.undo.undo(), "Ctrl+Z", "undo") @@ -480,6 +483,9 @@ class MainWindow(QMainWindow): pl = self.mgr.new_playlist(os.path.splitext(os.path.basename(f))[0]) self.mgr.add_paths([f], pl) + def export_all(self): + ExportAllDialog(self).exec() + def export_playlist(self, pl): if pl is None: return diff --git a/mulberry/nowplaying.py b/mulberry/nowplaying.py index 579ce09..18862bf 100644 --- a/mulberry/nowplaying.py +++ b/mulberry/nowplaying.py @@ -50,6 +50,26 @@ class NowPlaying(QObject): 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): @@ -143,6 +163,9 @@ class NowPlaying(QObject): if s.is_stream and not s.stream_title: 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": @@ -225,7 +248,8 @@ class NowPlaying(QObject): def load_artist_info(self): s = self.song - if not s or not s.display_artist(): + 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 ""), @@ -235,3 +259,58 @@ class NowPlaying(QObject): 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) diff --git a/mulberry/player.py b/mulberry/player.py index 393951e..a2f11f7 100644 --- a/mulberry/player.py +++ b/mulberry/player.py @@ -72,9 +72,15 @@ def preferred_backend() -> str: """auto → mpv on Linux (gapless, EQ, CD; visualizer via the sink monitor); Qt on Windows/macOS, where the visualizer needs Qt's own audio buffers.""" import sys + from .config import FROZEN want = settings.get("playback/backend") if want == "auto": - return "mpv" if sys.platform.startswith("linux") and mpv_available() else "qt" + # Packaged Linux builds (AppImage/tarball) ship Qt's own FFmpeg; loading + # the *system* libmpv next to it mixes two FFmpeg builds in one process, + # so they use the self-contained Qt engine unless mpv is chosen explicitly. + if sys.platform.startswith("linux") and not FROZEN and mpv_available(): + return "mpv" + return "qt" if want == "mpv" and mpv_available(): return "mpv" return "qt" diff --git a/mulberry/scrobble.py b/mulberry/scrobble.py index 6bc6777..59f921a 100644 --- a/mulberry/scrobble.py +++ b/mulberry/scrobble.py @@ -35,6 +35,53 @@ def app_credentials() -> tuple[str, str]: return key or "", sec or "" +class CallbackServer(QObject): + """Tiny one-shot HTTP server on 127.0.0.1 that receives Last.fm's + redirect (…/lastfm?token=XYZ) after the user approves in the browser.""" + token = pyqtSignal(str) + + PAGE = ("Mulberry" + "
" + "
🫐

Mulberry is connected to Last.fm

" + "

You can close this tab and go back to the app.

") + + def __init__(self, port: int): + super().__init__() + self.port = port + self.httpd = None + + def start(self) -> bool: + import http.server + outer = self + + class H(http.server.BaseHTTPRequestHandler): + def do_GET(self): + import urllib.parse + q = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query) + tok = (q.get("token") or [""])[0] + self.send_response(200 if tok else 404) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.end_headers() + self.wfile.write((outer.PAGE if tok else "Not found").encode()) + if tok: + outer.token.emit(tok) + + def log_message(self, *a): + pass + try: + self.httpd = http.server.HTTPServer(("127.0.0.1", self.port), H) + except OSError: + return False + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + return True + + def stop(self): + if self.httpd is not None: + threading.Thread(target=self.httpd.shutdown, daemon=True).start() + self.httpd = None + + class LastFM: @staticmethod def key(): @@ -87,6 +134,13 @@ class LastFM: res = cls.call("auth.getToken", {}, post=False, auth=False) return res["token"] + @classmethod + def web_auth_url(cls, port: int) -> str: + import urllib.parse + key, _ = cls.key() + cb = urllib.parse.quote(f"http://127.0.0.1:{port}/lastfm", safe="") + return f"https://www.last.fm/api/auth/?api_key={key}&cb={cb}" + @classmethod def auth_url(cls, token: str) -> str: key, _ = cls.key() @@ -128,6 +182,8 @@ class Scrobbler(QObject): self.lock = threading.Lock() self.cache: list[dict] = self._load_cache() player.track_started.connect(self._now_playing) + player.state_changed.connect(self._on_state) + self._announced = None # (id(song), monotonic) of last now-playing player.track_finished.connect(self._finished) self.flush_timer = QTimer(self, interval=5 * 60 * 1000) self.flush_timer.timeout.connect(self.flush) @@ -156,8 +212,22 @@ class Scrobbler(QObject): return settings.get("listenbrainz/enabled") and settings.get("listenbrainz/token") # ------------------------------------------------ events + def _on_state(self, st): + """Re-announce 'now playing' when playback (re)starts — e.g. resuming + the track restored at startup, or after a long pause (Last.fm drops + now-playing after a while).""" + s = self.player.song + if st != "playing" or s is None: + return + import time as _t + last = self._announced + if last is None or last[0] != id(s) or _t.monotonic() - last[1] > 240: + self._now_playing(s) + def _now_playing(self, s: Song): - if s.is_cd and not s.title: + import time as _t + self._announced = (id(s), _t.monotonic()) + if s.is_cd and (not s.title or s.title.startswith("Track ")) and not s.mb_trackid: return if self.lfm_on(): run_async(LastFM.call, "track.updateNowPlaying", LastFM.track_params(s), diff --git a/mulberry/spectrum.py b/mulberry/spectrum.py index 8fc5923..f0aa372 100644 --- a/mulberry/spectrum.py +++ b/mulberry/spectrum.py @@ -1,10 +1,13 @@ """Spectrum analysis for the radial visualizer, the bar analyzer and the floating bass shape. -PCM comes from the Qt backend (QAudioBufferOutput) or, with mpv, from the -PipeWire/PulseAudio monitor of the output device. Samples go into a ring -buffer and a *read cursor* advances at real time every frame, so the FFT -window slides smoothly even when audio arrives in big chunks. +Primary source (any engine, any OS): each local track is decoded ahead of +time with QAudioDecoder into a mono 22.05 kHz buffer, and every frame the FFT +window is centred on the *current playback position*. That keeps the visuals +exactly in sync (also after seeks) without capturing system audio. + +Fallback for streams / audio CDs: live PCM from the Qt engine +(QAudioBufferOutput) or, with mpv on Linux, the PipeWire/PulseAudio monitor. Levels are processed like cava: automatic sensitivity (so quiet and loud songs both use the full range), gravity fall-off (bars drop all the way down @@ -23,6 +26,8 @@ from .clock import FrameClock FFT_SIZE = 4096 RATE = 44100 RING = RATE * 2 +TRACK_RATE = 22050 # decode-ahead rate (same bin spacing with N=2048) +TRACK_FFT = 2048 class Spectrum(QObject): @@ -48,8 +53,9 @@ class Spectrum(QObject): self._bass_var = 0.0 self._last_beat = 0.0 self.window = np.hanning(FFT_SIZE).astype(np.float32) + self.twindow = np.hanning(TRACK_FFT).astype(np.float32) freqs = np.fft.rfftfreq(FFT_SIZE, 1 / RATE) - edges = np.geomspace(40, 15000, bands + 1) + edges = np.geomspace(40, 10500, bands + 1) # < 11.025 kHz Nyquist of the track buffer self.los = np.array([int(np.searchsorted(freqs, e)) for e in edges[:-1]], dtype=np.int64) self.los = np.maximum.accumulate(np.maximum(self.los, 1)) self.end_bin = int(np.searchsorted(freqs, edges[-1])) + 1 @@ -64,6 +70,15 @@ class Spectrum(QObject): self._io = None self._running = False self._last_push = 0.0 + # decode-ahead state + self.need_live = True # current song can't be decoded (stream/CD) + self._decoder = None + self._tbuf = np.zeros(0, dtype=np.float32) + self._tlen = 0 # decoded samples so far + self._tbegin = 0.0 # song.begin (cue/CD offset) in seconds + self._pos = 0.0 # last reported position (s, file time) + self._pos_t = 0.0 + self._song = None # ---------------------------------------------------------- input def push(self, data: np.ndarray): @@ -84,6 +99,95 @@ class Spectrum(QObject): self.written += n self._last_push = time.monotonic() + # ---------------------------------------------------------- decode-ahead + def set_track(self, song): + """Start decoding the new song's audio for the visualizer.""" + if song is self._song: + return + self._song = song + self._stop_decoder() + self._tlen = 0 + self._tbegin = float(getattr(song, "begin", 0.0) or 0.0) + local = song is not None and song.is_local and not song.is_cd + import os + self.need_live = not (local and os.path.exists(song.path)) + self._update_monitor() + if self.need_live: + return + try: + from PyQt6.QtCore import QUrl + from PyQt6.QtMultimedia import QAudioDecoder, QAudioFormat + except ImportError: + self.need_live = True + self._update_monitor() + return + est = int(((song.end or song.length or 300) + 5) * TRACK_RATE) + if self._tbuf.size < est: + self._tbuf = np.zeros(est, dtype=np.float32) + dec = QAudioDecoder(self) + fmt = QAudioFormat() + fmt.setSampleRate(TRACK_RATE) + fmt.setChannelCount(1) + fmt.setSampleFormat(QAudioFormat.SampleFormat.Float) + dec.setAudioFormat(fmt) + dec.setSource(QUrl.fromLocalFile(song.path)) + dec.bufferReady.connect(lambda d=dec: self._on_decoded(d)) + dec.error.connect(lambda *_a, d=dec: self._on_decode_error(d)) + self._decoder = dec + dec.start() + + def _stop_decoder(self): + d = self._decoder + self._decoder = None + if d is not None: + try: + d.bufferReady.disconnect() + d.stop() + except (TypeError, RuntimeError): + pass + d.deleteLater() + + def _on_decoded(self, dec): + if dec is not self._decoder: + return + buf = dec.read() + n = buf.byteCount() + if n <= 0: + return + data = np.frombuffer(buf.constData().asstring(n), dtype=np.float32) + start = int(buf.startTime() * TRACK_RATE / 1_000_000) + end = start + len(data) + if end > self._tbuf.size: + grown = np.zeros(max(end, int(self._tbuf.size * 1.5)), dtype=np.float32) + grown[: self._tlen] = self._tbuf[: self._tlen] + self._tbuf = grown + self._tbuf[start:end] = data + self._tlen = max(self._tlen, end) + + def _on_decode_error(self, dec): + if dec is self._decoder: + print("visualizer decode failed:", dec.errorString()) + self.need_live = True + self._update_monitor() + + def set_position(self, pos: float): + """Playback position (seconds, relative to the song start).""" + self._pos = pos + self._tbegin + self._pos_t = time.monotonic() + + def _track_window(self): + if self.need_live or self._tlen < TRACK_FFT: + return None + t = self._pos + if self.playing: + t += min(time.monotonic() - self._pos_t, 0.6) + centre = int(t * TRACK_RATE) + lo = centre - TRACK_FFT // 2 + hi = lo + TRACK_FFT + if lo < 0 or hi > self._tlen: + return None + return self._tbuf[lo:hi] + def start_monitor(self): """Capture the default sink monitor (used with the mpv backend).""" if self.source is not None: @@ -137,7 +241,7 @@ class Spectrum(QObject): if self.source is not None: self.stop_monitor() return - want = self.enabled and self.playing and self.consumers > 0 + want = self.enabled and self.playing and self.consumers > 0 and self.need_live if want and self.source is None: self.start_monitor() elif not want and self.source is not None: @@ -187,11 +291,17 @@ class Spectrum(QObject): return np.concatenate((self.ring[s:], self.ring[:FFT_SIZE - k])) def _tick(self, dt: float): - stale = time.monotonic() - self._last_push > 0.35 - buf = self._window(dt) if (self.playing and not stale) else None k60 = dt * 60.0 + buf, win, n = None, None, FFT_SIZE + if self.playing: + buf = self._track_window() + if buf is not None: + win, n = self.twindow, TRACK_FFT + elif time.monotonic() - self._last_push <= 0.35: + buf = self._window(dt) + win, n = self.window, FFT_SIZE if buf is not None: - mag = np.abs(np.fft.rfft(buf * self.window)) * (2.0 / FFT_SIZE) + mag = np.abs(np.fft.rfft(buf * win)) * (2.0 / n) raw = np.maximum.reduceat(mag[: self.end_bin], self.los)[: self.nbands] * self.weight energy = float(raw.mean()) v = (raw ** 0.62) * self.sens * 6.0 diff --git a/mulberry/widgets/dialogs.py b/mulberry/widgets/dialogs.py index 0066ae8..ce0db78 100644 --- a/mulberry/widgets/dialogs.py +++ b/mulberry/widgets/dialogs.py @@ -19,7 +19,7 @@ from .. import library as L from .. import online from .. import tags as T from .. import theme as Th -from ..config import APP_NAME, VERSION, fmt_time, run_async, settings +from ..config import APP_NAME, FROZEN, IS_LINUX, VERSION, fmt_time, run_async, settings from ..icons import icon from ..player import EQ_FREQS, EQ_PRESETS, Player, mpv_available from ..scrobble import LastFM @@ -121,7 +121,7 @@ class SettingsDialog(QDialog): g = QGroupBox("Engine") f = QFormLayout(g) self.backend = QComboBox() - self.backend.addItem("Automatic (mpv on Linux, Qt on Windows)", "auto") + self.backend.addItem("Automatic (mpv when run from source on Linux, otherwise Qt)", "auto") self.backend.addItem("mpv / libmpv — gapless, EQ, ReplayGain, CD", "mpv") self.backend.addItem("Qt Multimedia (FFmpeg)", "qt") self.backend.setCurrentIndex(max(0, self.backend.findData(settings.get("playback/backend")))) @@ -129,7 +129,9 @@ class SettingsDialog(QDialog): cur = Player.instance.backend.name note = QLabel(f"In use: {cur}" + ("" if mpv_available() else " — libmpv not found; install mpv for gapless, EQ and CD playback.") + - "
Backend changes apply after restart.") + "
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 "")) note.setObjectName("muted") note.setWordWrap(True) f.addRow("", note) @@ -248,7 +250,7 @@ class SettingsDialog(QDialog): self.lfm_on = QCheckBox("Scrobble what I play and send “now playing”") self.lfm_on.setChecked(settings.get("lastfm/enabled")) v.addWidget(self.lfm_on) - self.lfm_own = QCheckBox("Use my own API key (manual / advanced)") + self.lfm_own = QCheckBox("Use my own API key instead of Mulberry's (advanced)") self.lfm_own.setChecked(settings.get("lastfm/use_own_key")) v.addWidget(self.lfm_own) self.lfm_keys = QWidget() @@ -311,6 +313,10 @@ class SettingsDialog(QDialog): def _lfm_login_clicked(self): if self._lfm_poll.isActive(): self._lfm_poll.stop() + srv = getattr(self, "_lfm_server", None) + if srv is not None: + srv.stop() + self._lfm_server = None self._lfm_status() return if settings.get("lastfm/session"): @@ -332,10 +338,25 @@ class SettingsDialog(QDialog): "then press Log in again.") return + from PyQt6.QtCore import QUrl + from PyQt6.QtGui import QDesktopServices + import time as _t + from .. import lastfm_app + from ..scrobble import CallbackServer + # 1) preferred: browser redirects back to a local one-shot server + srv = CallbackServer(getattr(lastfm_app, "CALLBACK_PORT", 47823)) + if srv.start(): + self._lfm_server = srv + srv.token.connect(self._lfm_got_callback_token) + self._lfm_token = None + self._lfm_deadline = _t.monotonic() + 300 + QDesktopServices.openUrl(QUrl(LastFM.web_auth_url(srv.port))) + self._lfm_status(waiting=True) + self._lfm_poll.start() # only used as a timeout watchdog here + return + + # 2) fallback (port busy): desktop token flow, polled until approved def got_token(token): - from PyQt6.QtCore import QUrl - from PyQt6.QtGui import QDesktopServices - import time as _t self._lfm_token = token self._lfm_deadline = _t.monotonic() + 300 QDesktopServices.openUrl(QUrl(LastFM.auth_url(token))) @@ -344,11 +365,47 @@ class SettingsDialog(QDialog): run_async(LastFM.begin_auth, on_done=got_token, on_error=lambda e: QMessageBox.warning(self, "Last.fm", e)) - def _lfm_poll_tick(self): - import time as _t - if not self._lfm_token or _t.monotonic() > self._lfm_deadline: + def _lfm_got_callback_token(self, token): + srv = getattr(self, "_lfm_server", None) + if srv is not None: + srv.stop() + self._lfm_server = None + + def ok(res): + self._lfm_poll.stop() + sk, name = res + settings.set("lastfm/session", sk) + settings.set("lastfm/user", name) + settings.set("lastfm/enabled", True) + self.lfm_on.setChecked(True) + self._lfm_status() + self.w.toast(f"Logged in to Last.fm as {name}") + self.raise_() + self.activateWindow() + + def err(msg): self._lfm_poll.stop() self._lfm_status() + QMessageBox.warning(self, "Last.fm", msg) + run_async(LastFM.finish_auth, token, on_done=ok, on_error=err) + + def done(self, r): + srv = getattr(self, "_lfm_server", None) + if srv is not None: + srv.stop() + super().done(r) + + def _lfm_poll_tick(self): + import time as _t + if _t.monotonic() > self._lfm_deadline: + self._lfm_poll.stop() + srv = getattr(self, "_lfm_server", None) + if srv is not None: + srv.stop() + self._lfm_server = None + self._lfm_status() + return + if not self._lfm_token: # callback flow: nothing to poll, just the timeout return token = self._lfm_token @@ -1070,3 +1127,115 @@ class AboutDialog(QDialog): bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) bb.rejected.connect(self.accept) lay.addWidget(bb) + + +# ====================================================================== export all +class ExportAllDialog(QDialog): + """Export every playlist into one folder, Strawberry-style.""" + FORMATS = [("m3u8", "M3U8 (UTF-8, recommended)"), ("m3u", "M3U"), ("pls", "PLS"), + ("xspf", "XSPF"), ("wpl", "Windows Media (WPL)")] + + def __init__(self, window): + super().__init__(window) + self.w = window + self.setWindowTitle("Export all playlists") + self.resize(560, 330) + lay = QVBoxLayout(self) + f = QFormLayout() + row = QHBoxLayout() + self.folder = QLineEdit(settings.raw().value("export/folder", os.path.expanduser("~/Music/Playlists"))) + browse = QPushButton(icon("folder_open", "onSecondaryContainer"), " Choose…") + browse.clicked.connect(self._browse) + row.addWidget(self.folder, 1) + row.addWidget(browse) + f.addRow("Folder", row) + self.fmt = QComboBox() + for k, label in self.FORMATS: + self.fmt.addItem(label, k) + self.fmt.setCurrentIndex(max(0, self.fmt.findData(settings.raw().value("export/format", "m3u8")))) + f.addRow("File type", self.fmt) + self.exists = QComboBox() + self.exists.addItem("Replace the existing file", "replace") + self.exists.addItem("Skip that playlist", "skip") + self.exists.addItem("Keep both (add a number)", "number") + 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.closed = QCheckBox("Also export saved playlists that are currently closed") + self.closed.setChecked(True) + lay.addWidget(self.relative) + lay.addWidget(self.closed) + n = len(window.mgr.playlists) + info = QLabel(f"{n} open playlist{'s' if n != 1 else ''} will be exported.") + info.setObjectName("muted") + lay.addWidget(info) + lay.addStretch(1) + lay.addWidget(_buttons(self, "Export")) + + def _browse(self): + d = QFileDialog.getExistingDirectory(self, "Export playlists to", self.folder.text()) + if d: + self.folder.setText(d) + + def accept(self): + import json as _json + import re as _re + from pathlib import Path + from ..playlistio import export_playlist + folder = Path(self.folder.text().strip() or ".") + try: + folder.mkdir(parents=True, exist_ok=True) + except OSError as e: + QMessageBox.warning(self, "Export", str(e)) + return + ext, mode, rel = self.fmt.currentData(), self.exists.currentData(), self.relative.isChecked() + q = settings.raw() + q.setValue("export/folder", str(folder)) + q.setValue("export/format", ext) + q.setValue("export/exists", mode) + q.setValue("export/relative", 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} + for r in L.library.load_playlists(): + if r["id"] not in open_ids and r["favorite"]: + try: + lists.append((r["name"], [Song.from_dict(d) for d in _json.loads(r["items"] or "[]")])) + except ValueError: + pass + done = skipped = 0 + errors = [] + used = set() + for name, songs in lists: + base = _re.sub(r'[\\/:*?"<>|\x00-\x1f]', "_", name).strip(" .") or "Playlist" + stem = base + k = 2 + while stem.lower() in used: # two playlists with the same name + stem = f"{base} ({k})" + k += 1 + used.add(stem.lower()) + path = folder / f"{stem}.{ext}" + if path.exists(): + if mode == "skip": + skipped += 1 + continue + if mode == "number": + k = 2 + while path.exists(): + path = folder / f"{stem} ({k}).{ext}" + k += 1 + try: + export_playlist(str(path), songs, rel) + done += 1 + except Exception as e: # noqa: BLE001 + errors.append(f"{name}: {e}") + msg = f"Exported {done} playlist{'s' if done != 1 else ''} to {folder}" + if skipped: + msg += f" ({skipped} skipped because they already existed)" + if errors: + QMessageBox.warning(self, "Export", msg + "\n\nProblems:\n" + "\n".join(errors[:15])) + else: + self.w.toast(msg) + super().accept() diff --git a/mulberry/widgets/hero.py b/mulberry/widgets/hero.py index 699b84d..3dc4e17 100644 --- a/mulberry/widgets/hero.py +++ b/mulberry/widgets/hero.py @@ -618,6 +618,10 @@ class Hero(QWidget): 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) + elif s.is_cd and not s.mb_albumid: + self.title.setText(s.display_title()) + self.artist.setText(s.display_artist() or "Unknown artist") + self.album.setText(s.album or "Audio CD") else: self.title.setText(s.display_title()) self.artist.setText(s.display_artist()) @@ -673,6 +677,9 @@ class Hero(QWidget): self.lyrics.set_message("Searching for lyrics…", "loading") elif source == "error": self.lyrics.set_message("Couldn't reach the lyrics service") + 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 == "nolocal": self.lyrics.set_message("No .lrc file next to this song.\nUse LRCGET to download them, " "or pick another source in ⋮.") @@ -682,7 +689,7 @@ 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", "") else "" + shown = source if source not in ("loading", "error", "nolocal", "unknowncd", "") else "" if shown and settings.get("lyrics/plain"): shown += " · plain" self.l_src.setText(shown) diff --git a/mulberry/widgets/sidebar.py b/mulberry/widgets/sidebar.py index 92466f7..247ac10 100644 --- a/mulberry/widgets/sidebar.py +++ b/mulberry/widgets/sidebar.py @@ -436,6 +436,9 @@ class PlaylistsPanel(QWidget): self.saved.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.saved.customContextMenuRequested.connect(self._saved_menu) lay.addWidget(self.saved, 1) + exp = QPushButton(icon("download", "onSecondaryContainer"), " Export all playlists…") + exp.clicked.connect(lambda: self.window().export_all()) + lay.addWidget(exp) tip = QLabel("Click: jump to an open playlist · Double-click: reopen a closed one") tip.setObjectName("muted") tip.setWordWrap(True) diff --git a/packaging/make_test_audio.py b/packaging/make_test_audio.py new file mode 100644 index 0000000..717feb6 --- /dev/null +++ b/packaging/make_test_audio.py @@ -0,0 +1,17 @@ +"""Write a short WAV with kick drums + tones for CI playback self-tests.""" +import sys +import wave + +import numpy as np + +sr, secs = 44100, 12 +t = np.arange(sr * secs) / sr +kick = 0.9 * np.sin(2 * np.pi * 52 * t) * np.exp(-np.mod(t, 0.5) * 10) +pad = 0.25 * np.sin(2 * np.pi * 220 * t) + 0.15 * np.sin(2 * np.pi * 330 * t + 2 * np.sin(2 * np.pi * 3 * t)) +x = np.clip(kick + pad, -1, 1) +pcm = (x * 30000).astype(" 1 else "selftest.wav", "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(sr) + w.writeframes(pcm.tobytes()) diff --git a/packaging/mulberry.spec b/packaging/mulberry.spec index 19290ff..d4af203 100644 --- a/packaging/mulberry.spec +++ b/packaging/mulberry.spec @@ -61,8 +61,10 @@ if not IS_WIN: a.binaries = [b for b in a.binaries if not (unwanted(b[0]) and "PyQt6" not in b[1] and "numpy" not in b[1])] # Qt modules Mulberry never uses (pulled in by plugins) — keeps the bundle lean -_drop = re.compile(r"(Qt6(Quick|Qml|Pdf|VirtualKeyboard|ShaderTools|3D|WebEngine|Designer)|libqgtk3|qpdf|" - r"qmltooling|libgtk-3|libgdk-3)", re.I) if True else None +# Qt modules Mulberry never uses. NOTE: Qt6Quick/Qml/QmlModels must stay — +# the FFmpeg multimedia plugin links against them (dropping them silently +# disables all playback and decoding). +_drop = re.compile(r"(Qt6(Pdf|VirtualKeyboard|3D|WebEngine|Designer)|libqgtk3|qpdf|libgtk-3|libgdk-3)", re.I) a.binaries = [b for b in a.binaries if not _drop.search(b[0])] a.datas = [d for d in a.datas if not _drop.search(d[0])] diff --git a/packaging/windows/mulberry.iss b/packaging/windows/mulberry.iss index 8b71343..1dddc1d 100644 --- a/packaging/windows/mulberry.iss +++ b/packaging/windows/mulberry.iss @@ -1,6 +1,6 @@ -; Inno Setup script — built by CI: iscc /DAppVersion=1.1.0 packaging\windows\mulberry.iss +; Inno Setup script — built by CI: iscc /DAppVersion=1.2.0 packaging\windows\mulberry.iss #ifndef AppVersion - #define AppVersion "1.1.0" + #define AppVersion "1.2.0" #endif [Setup] diff --git a/packaging/windows/version.txt b/packaging/windows/version.txt index 88558a8..8c68f5a 100644 --- a/packaging/windows/version.txt +++ b/packaging/windows/version.txt @@ -1,15 +1,15 @@ VSVersionInfo( - ffi=FixedFileInfo(filevers=(1, 1, 0, 0), prodvers=(1, 1, 0, 0), mask=0x3f, flags=0x0, OS=0x40004, + ffi=FixedFileInfo(filevers=(1, 2, 0, 0), prodvers=(1, 2, 0, 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.1.0'), + StringStruct('FileVersion', '1.2.0'), StringStruct('InternalName', 'Mulberry'), StringStruct('OriginalFilename', 'Mulberry.exe'), StringStruct('ProductName', 'Mulberry'), - StringStruct('ProductVersion', '1.1.0')])]), + StringStruct('ProductVersion', '1.2.0')])]), VarFileInfo([VarStruct('Translation', [1033, 1200])]) ] )