Mulberry/mulberry/spectrum.py
Claude 2cc0338156
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
2026-10-10 00:04:21 -05:00

364 lines
14 KiB
Python

"""Spectrum analysis for the radial visualizer, the bar analyzer and the
floating bass shape.
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
between hits) and light neighbour smoothing. A bass-onset detector emits
`beat` for the floating shape.
"""
from __future__ import annotations
import time
import numpy as np
from PyQt6.QtCore import QObject, pyqtSignal
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):
updated = pyqtSignal()
beat = pyqtSignal(float) # strength 0..1
use_monitor = False
def __init__(self, bands=64):
super().__init__()
self.nbands = bands
self.ring = np.zeros(RING, dtype=np.float32)
self.written = 0 # total samples written
self.cursor = 0.0 # read position (absolute samples)
self.levels = np.zeros(bands, dtype=np.float32)
self.peaks = np.zeros(bands, dtype=np.float32)
self._mem = np.zeros(bands, dtype=np.float32) # gravity peak memory
self._fall = np.zeros(bands, dtype=np.float32)
self.sens = 1.0
self.bass = 0.0 # smoothed processed bass 0..1
self.pulse = 0.0 # decaying beat envelope 0..1
self._bass_avg = 0.0
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, 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
# equaliser so highs aren't dwarfed by bass (pink-ish tilt)
centers = np.sqrt(edges[:-1] * edges[1:])
self.weight = (centers / 1000.0) ** 0.42
self.weight = (self.weight / self.weight.mean()).astype(np.float32)
self.consumers = 0
self.playing = False
self.enabled = True
self.source = None
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):
n = len(data)
if n == 0:
return
if n >= RING:
data = data[-RING:]
n = RING
start = self.written % RING
end = start + n
if end <= RING:
self.ring[start:end] = data
else:
k = RING - start
self.ring[start:] = data[:k]
self.ring[:n - k] = data[k:]
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:
return
try:
from PyQt6.QtMultimedia import QAudioFormat, QAudioSource, QMediaDevices
except ImportError:
return
outs = QMediaDevices.defaultAudioOutput().description().lower()
dev = None
for d in QMediaDevices.audioInputs():
desc = d.description().lower()
if "monitor" in desc and (outs in desc or dev is None):
dev = d
if dev is None:
return
fmt = QAudioFormat()
fmt.setSampleRate(RATE)
fmt.setChannelCount(1)
fmt.setSampleFormat(QAudioFormat.SampleFormat.Float)
self.source = QAudioSource(dev, fmt, self)
self.source.setBufferSize(2048 * 4)
self._io = self.source.start()
if self._io is None:
self.source = None
return
self._io.readyRead.connect(self._read_monitor)
def stop_monitor(self):
if self.source is not None:
self.source.stop()
self.source = None
self._io = None
def _read_monitor(self):
if self._io is None:
return
data = self._io.readAll()
if data.size():
self.push(np.frombuffer(bytes(data), dtype=np.float32))
# ---------------------------------------------------------- lifecycle
def set_playing(self, playing: bool):
self.playing = playing
self._update_monitor()
self._update_running()
def _update_monitor(self):
"""Only capture the monitor while playing (no permanent mic indicator)."""
if not self.use_monitor:
if self.source is not None:
self.stop_monitor()
return
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:
self.stop_monitor()
def acquire(self):
self.consumers += 1
self._update_monitor()
self._update_running()
def release(self):
self.consumers = max(0, self.consumers - 1)
self._update_monitor()
self._update_running()
@property
def active(self) -> bool:
return self._running
def _update_running(self):
want = self.enabled and self.consumers > 0 and (self.playing or self.levels.max() > 0.002)
if want and not self._running:
self._running = True
FrameClock.subscribe(self._tick, pre=True)
elif not want and self._running:
self._running = False
FrameClock.unsubscribe(self._tick)
# ---------------------------------------------------------- analysis
def _window(self, dt: float):
lag_target = 1536 # keep ~35 ms behind the newest sample
self.cursor += dt * RATE
newest = self.written - lag_target
# drift-correct toward the target lag; snap if far away
if abs(newest - self.cursor) > RATE * 0.4:
self.cursor = float(newest)
else:
self.cursor += (newest - self.cursor) * min(1.0, dt * 4)
self.cursor = min(self.cursor, float(self.written))
end = int(self.cursor)
if end < FFT_SIZE:
return None
s = (end - FFT_SIZE) % RING
if s + FFT_SIZE <= RING:
return self.ring[s:s + FFT_SIZE]
k = RING - s
return np.concatenate((self.ring[s:], self.ring[:FFT_SIZE - k]))
def _tick(self, dt: float):
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 * 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
# auto sensitivity (cava-like): shrink fast on overshoot, grow slowly
if v.max() > 1.0:
self.sens *= 0.985 ** k60
elif energy > 1e-5:
self.sens *= 1.0018 ** k60
self.sens = float(min(max(self.sens, 0.02), 60.0))
v = np.clip(v, 0.0, 1.0)
# light neighbour smoothing for a fluid silhouette
v = np.maximum(v, 0.55 * np.maximum(np.roll(v, 1), np.roll(v, -1)))
v[0] = max(v[0], v[1] * 0.8)
v[-1] = min(v[-1], 1.0)
# bass onset detection on unscaled low-band energy
b_raw = float(raw[: max(2, self.nbands // 10)].mean())
a = min(1.0, dt * 2.5)
self._bass_avg += (b_raw - self._bass_avg) * a
self._bass_var += ((b_raw - self._bass_avg) ** 2 - self._bass_var) * a
now = time.monotonic()
thr = self._bass_avg + 1.6 * (self._bass_var ** 0.5)
if b_raw > thr and b_raw > self._bass_avg * 1.25 and b_raw > 1e-4 and now - self._last_beat > 0.16:
self._last_beat = now
strength = float(min(1.0, (b_raw / max(self._bass_avg, 1e-6) - 1.0) / 1.5))
self.pulse = max(self.pulse, 0.45 + 0.55 * strength)
self.beat.emit(strength)
else:
v = np.zeros(self.nbands, dtype=np.float32)
# gravity: rise instantly, fall with accelerating speed down to zero
rise = v >= self._mem
self._fall = np.where(rise, 0.0, self._fall + dt).astype(np.float32)
self._mem = np.where(rise, v, self._mem).astype(np.float32)
grav = self._mem * (1.0 - (self._fall * 2.6) ** 2)
lv = np.maximum(v, np.maximum(grav, 0.0))
caught = grav <= v
self._mem = np.where(caught, v, self._mem).astype(np.float32)
self._fall = np.where(caught, 0.0, self._fall).astype(np.float32)
# a touch of attack smoothing so peaks don't flicker
self.levels = (self.levels + (lv - self.levels) * min(1.0, 0.75 * k60)).astype(np.float32)
self.peaks = np.maximum(self.peaks - 0.6 * dt, self.levels)
self.bass += (float(self.levels[: max(2, self.nbands // 10)].mean()) - self.bass) * min(1.0, 0.5 * k60)
self.pulse = max(0.0, self.pulse - dt * 2.4)
self.updated.emit()
if not self.playing and self.levels.max() < 0.002 and self.pulse <= 0:
self.levels[:] = 0
self.peaks[:] = 0
self.bass = 0.0
self.updated.emit()
self._update_running()
# ---------------------------------------------------------- helpers
def resample(self, n: int) -> np.ndarray:
if n == self.nbands:
return self.levels
x = np.linspace(0, self.nbands - 1, n)
return np.interp(x, np.arange(self.nbands), self.levels).astype(np.float32)
def resample_peaks(self, n: int) -> np.ndarray:
x = np.linspace(0, self.nbands - 1, n)
return np.interp(x, np.arange(self.nbands), self.peaks).astype(np.float32)