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

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

254 lines
10 KiB
Python

"""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.
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
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)
freqs = np.fft.rfftfreq(FFT_SIZE, 1 / RATE)
edges = np.geomspace(40, 15000, bands + 1)
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
# ---------------------------------------------------------- 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()
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
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):
stale = time.monotonic() - self._last_push > 0.35
buf = self._window(dt) if (self.playing and not stale) else None
k60 = dt * 60.0
if buf is not None:
mag = np.abs(np.fft.rfft(buf * self.window)) * (2.0 / FFT_SIZE)
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)