forked from trav/lintunes
Preferences → Appearance → Visualizer picks Bars (as before), Radial dots (the EQ in a circle: angle is frequency, radius is volume, moving dots leave light-gray ghosts that fade over a set time), or Laser (a mirror on a speaker membrane bouncing a beam onto a screen: simulated membrane modes, D·tan(2θ) reflection, dwell-weighted brightness). Double-clicking the panel opens it big; a click closes it.
327 lines
12 KiB
Python
327 lines
12 KiB
Python
"""The transport bar's visualizer, fed by the player's decoded PCM tee.
|
|
|
|
The player's QAudioBufferOutput delivers buffers essentially in lockstep
|
|
with the audible position (verified: frames received ≈ frames played), so
|
|
no extra sync buffering is needed — we just FFT the newest samples. What a
|
|
frame turns into is the chosen style's business (``visualizer_styles``);
|
|
this widget owns intake, timing, on/dim/off and color.
|
|
"""
|
|
import numpy as np
|
|
|
|
from PyQt6.QtWidgets import QWidget
|
|
from PyQt6.QtCore import Qt, QTimer, QRectF, pyqtSignal
|
|
from PyQt6.QtGui import QPainter, QColor
|
|
from PyQt6.QtMultimedia import QAudioFormat
|
|
|
|
from lintunes import theme
|
|
from lintunes.gui.icons import transport_icon
|
|
from lintunes.gui.visualizer_styles import (
|
|
BANDS, STYLES, STYLE_BARS, Frame, make_renderer)
|
|
|
|
|
|
FFT_SIZE = 2048
|
|
FRAME_MS = 16 # ~60 fps
|
|
RADIUS = 8 # rounded corners, matching the transport button boxes
|
|
ICON_SIZE = 40 # the cast glyph shown in place of bars while casting
|
|
PENDING_S = 0.25 # most unconsumed audio kept for the laser
|
|
|
|
# Visualizer click cycles through these brightness modes in order.
|
|
MODE_ON = "on"
|
|
MODE_DIM = "dim"
|
|
MODE_OFF = "off"
|
|
_MODE_CYCLE = (MODE_ON, MODE_DIM, MODE_OFF)
|
|
|
|
_TOOLTIP = "Click to cycle: on / dim / off — double-click to enlarge"
|
|
|
|
_SAMPLE_DTYPES = {
|
|
QAudioFormat.SampleFormat.UInt8: (np.uint8, 127.5, 127.5),
|
|
QAudioFormat.SampleFormat.Int16: (np.int16, 0.0, 32768.0),
|
|
QAudioFormat.SampleFormat.Int32: (np.int32, 0.0, 2147483648.0),
|
|
QAudioFormat.SampleFormat.Float: (np.float32, 0.0, 1.0),
|
|
}
|
|
|
|
|
|
def _style(prefs) -> str:
|
|
saved = prefs.get("visualizer_style") if prefs is not None else None
|
|
return saved if saved in STYLES else STYLE_BARS
|
|
|
|
|
|
def _fade(prefs) -> float:
|
|
saved = prefs.get("visualizer_ghost_fade", 1.0) if prefs is not None else 1.0
|
|
try:
|
|
return max(0.0, float(saved))
|
|
except (TypeError, ValueError):
|
|
return 1.0
|
|
|
|
|
|
class VisualizerWidget(QWidget):
|
|
"""Animated visualizer; click to cycle brightness: on / dim / off, and
|
|
double-click to open it big (``VisualizerWindow``).
|
|
|
|
On = highlight-colored; dim = light gray just darker than the panel;
|
|
off = blank (the big window, if open, keeps going in color).
|
|
|
|
While casting there is no local PCM to analyze, so the panel doubles as the
|
|
cast indicator: it shows the device glyph and a click stops casting.
|
|
"""
|
|
|
|
cast_stop_requested = pyqtSignal()
|
|
|
|
def __init__(self, player, prefs=None, parent=None):
|
|
super().__init__(parent)
|
|
self._player = player
|
|
self._prefs = prefs
|
|
saved = prefs.get("visualizer_mode") if prefs is not None else None
|
|
self._mode = saved if saved in _MODE_CYCLE else MODE_ON
|
|
self._mode_before_press = self._mode
|
|
self._renderer = make_renderer(_style(prefs), _fade(prefs))
|
|
self._samples = np.zeros(FFT_SIZE, dtype=np.float32)
|
|
self._pending = [] # every sample since the last frame (the laser)
|
|
self._pending_len = 0
|
|
self._sample_rate = 44100
|
|
self._window = np.hanning(FFT_SIZE).astype(np.float32)
|
|
self._big = None # VisualizerWindow, made on first double-click
|
|
# True while audio is coming out of something other than this machine
|
|
# (a Chromecast), so there is no decoded PCM to draw.
|
|
self._no_pcm = False
|
|
self._device = ""
|
|
|
|
self.setFixedWidth(140)
|
|
self.setMinimumHeight(36)
|
|
self.setToolTip(_TOOLTIP)
|
|
|
|
self._timer = QTimer(self)
|
|
self._timer.setInterval(FRAME_MS)
|
|
self._timer.timeout.connect(self._advance_frame)
|
|
|
|
player.audio_buffer.connect(self._on_buffer)
|
|
player.playing_changed.connect(self._on_playing_changed)
|
|
player.track_changed.connect(self._on_track_changed)
|
|
if hasattr(player, "sink_changed"):
|
|
player.sink_changed.connect(self._on_sink_changed)
|
|
if prefs is not None:
|
|
prefs.changed.connect(self._on_prefs_changed)
|
|
|
|
# The bars' state, under the names the widget always had for it.
|
|
@property
|
|
def _bars(self):
|
|
return getattr(self._renderer, "bars", [0] * BANDS)
|
|
|
|
@_bars.setter
|
|
def _bars(self, bars):
|
|
self._renderer.bars = bars
|
|
|
|
@property
|
|
def _levels(self):
|
|
return self._renderer.levels
|
|
|
|
def _on_prefs_changed(self):
|
|
style = _style(self._prefs)
|
|
if style != self._renderer.name:
|
|
self._renderer = make_renderer(style, _fade(self._prefs))
|
|
self._repaint()
|
|
elif hasattr(self._renderer, "fade"):
|
|
self._renderer.fade = _fade(self._prefs)
|
|
|
|
def _on_sink_changed(self, sink):
|
|
"""Casting means no local decode, so there is nothing to draw. The
|
|
panel becomes the cast indicator instead: it shows where the audio
|
|
went, and clicking it stops casting."""
|
|
self._no_pcm = not getattr(sink, "provides_pcm", True)
|
|
if self._no_pcm:
|
|
self._device = getattr(sink, "name", "") or "a Chromecast"
|
|
self._clear()
|
|
self.setToolTip(f"Casting to {self._device} — click to stop")
|
|
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
|
else:
|
|
self._device = ""
|
|
self.setToolTip(_TOOLTIP)
|
|
self.setCursor(Qt.CursorShape.ArrowCursor)
|
|
self._sync_timer()
|
|
self.update()
|
|
|
|
# ---- audio intake ----
|
|
|
|
def _on_buffer(self, buf):
|
|
fmt = buf.format()
|
|
spec = _SAMPLE_DTYPES.get(fmt.sampleFormat())
|
|
if spec is None:
|
|
return
|
|
dtype, offset, scale = spec
|
|
pointer = buf.data()
|
|
pointer.setsize(buf.byteCount())
|
|
raw = np.frombuffer(pointer, dtype=dtype)
|
|
channels = max(1, fmt.channelCount())
|
|
if channels > 1:
|
|
usable = (len(raw) // channels) * channels
|
|
raw = raw[:usable].reshape(-1, channels).mean(axis=1)
|
|
mono = (raw.astype(np.float32) - offset) / scale
|
|
self._feed(mono, fmt.sampleRate() or 44100)
|
|
|
|
def _feed(self, mono, rate):
|
|
self._sample_rate = rate
|
|
if len(mono) >= FFT_SIZE:
|
|
self._samples = mono[-FFT_SIZE:].copy()
|
|
else:
|
|
self._samples = np.roll(self._samples, -len(mono))
|
|
self._samples[-len(mono):] = mono
|
|
# The laser needs every sample, once, not just the newest window.
|
|
self._pending.append(mono)
|
|
self._pending_len += len(mono)
|
|
cap = int(PENDING_S * rate)
|
|
while self._pending_len > cap and len(self._pending) > 1:
|
|
self._pending_len -= len(self._pending.pop(0))
|
|
|
|
def _take_pending(self):
|
|
pending = (np.concatenate(self._pending) if self._pending
|
|
else np.zeros(0, dtype=np.float32))
|
|
self._pending = []
|
|
self._pending_len = 0
|
|
return pending
|
|
|
|
# ---- state ----
|
|
|
|
def _big_visible(self):
|
|
return self._big is not None and self._big.isVisible()
|
|
|
|
def _sync_timer(self):
|
|
"""Animate while playing, unless nothing would show it."""
|
|
run = (not self._no_pcm and self._player.is_playing()
|
|
and (self._mode != MODE_OFF or self._big_visible()))
|
|
if run:
|
|
if not self._timer.isActive():
|
|
self._take_pending() # stale audio from while we were idle
|
|
self._timer.start()
|
|
else:
|
|
self._timer.stop()
|
|
|
|
def _on_playing_changed(self, playing):
|
|
if self._no_pcm:
|
|
return # nothing to animate; don't let play/pause restart the timer
|
|
self._sync_timer()
|
|
if not playing:
|
|
self._clear()
|
|
|
|
def _on_track_changed(self, track):
|
|
self._samples[:] = 0.0
|
|
self._take_pending()
|
|
if track is None:
|
|
self._timer.stop()
|
|
self._clear()
|
|
|
|
def _clear(self):
|
|
self._renderer.clear()
|
|
self._repaint()
|
|
|
|
def _repaint(self):
|
|
self.update()
|
|
if self._big_visible():
|
|
self._big.update()
|
|
|
|
def _set_mode(self, mode):
|
|
self._mode = mode
|
|
if self._prefs is not None:
|
|
self._prefs.set("visualizer_mode", self._mode)
|
|
if self._mode == MODE_OFF and not self._big_visible():
|
|
self._clear() # off = blank, not the last frame held in place
|
|
self._sync_timer()
|
|
self.update()
|
|
|
|
def mousePressEvent(self, event):
|
|
if self._no_pcm:
|
|
# While casting the panel is the cast indicator, not a spectrum:
|
|
# cycling its brightness would be meaningless, so a click stops
|
|
# casting instead.
|
|
self.cast_stop_requested.emit()
|
|
return
|
|
# Cycle on -> dim -> off -> on.
|
|
self._mode_before_press = self._mode
|
|
idx = _MODE_CYCLE.index(self._mode)
|
|
self._set_mode(_MODE_CYCLE[(idx + 1) % len(_MODE_CYCLE)])
|
|
|
|
def mouseDoubleClickEvent(self, event):
|
|
"""Qt sends press, release, *double-click*: the first press already
|
|
cycled the brightness, so put it back before opening big. A brief
|
|
flicker, in exchange for a single click that never waits to see
|
|
whether a second one is coming."""
|
|
if self._no_pcm:
|
|
return # the first click already stopped casting
|
|
self._set_mode(self._mode_before_press)
|
|
self.open_big()
|
|
|
|
def open_big(self):
|
|
from lintunes.gui.visualizer_window import VisualizerWindow
|
|
if self._big is None:
|
|
self._big = VisualizerWindow(self)
|
|
self._big.open(self.screen())
|
|
self._sync_timer()
|
|
|
|
def big_window_closed(self):
|
|
if self._mode == MODE_OFF:
|
|
self._clear()
|
|
self._sync_timer()
|
|
|
|
# ---- frame computation ----
|
|
|
|
def _advance_frame(self):
|
|
spectrum = np.abs(np.fft.rfft(self._samples * self._window))
|
|
# Normalize: full-scale sine -> ~1.0
|
|
spectrum /= (FFT_SIZE / 4)
|
|
freqs = np.fft.rfftfreq(FFT_SIZE, d=1.0 / self._sample_rate)
|
|
frame = Frame(spectrum, freqs, self._sample_rate,
|
|
self._take_pending(), FRAME_MS / 1000)
|
|
if self._renderer.advance(frame):
|
|
self._repaint()
|
|
|
|
# ---- painting ----
|
|
|
|
def _bar_color(self):
|
|
if self._mode == MODE_DIM:
|
|
return self._gray()
|
|
return QColor(self.palette().highlight().color())
|
|
|
|
def _gray(self):
|
|
"""Dim mode's color — and the radial's fading ghosts in any mode."""
|
|
if self._prefs is not None:
|
|
saved = self._prefs.get("color_visualizer_gray")
|
|
if saved is not None:
|
|
return theme.gray(saved)
|
|
# Light gray just darker than the panel: take alternateBase and
|
|
# drop its lightness ~12% so it tracks theme/scale changes.
|
|
base = QColor(self.palette().alternateBase().color())
|
|
h, s, l, a = base.getHslF()
|
|
base.setHslF(h, s, l * 0.88, a)
|
|
return base
|
|
|
|
def panel_color(self):
|
|
return self.palette().alternateBase().color()
|
|
|
|
def paint_renderer(self, painter, rect, big=False):
|
|
"""Paint the current frame into ``rect`` — the panel's, or the big
|
|
window's. The panel draws nothing when off; the big window draws
|
|
regardless (in color), since opening it is asking to see it."""
|
|
if self._no_pcm or (self._mode == MODE_OFF and not big):
|
|
return
|
|
self._renderer.paint(painter, rect, self._bar_color(), self._gray())
|
|
|
|
def paintEvent(self, event):
|
|
painter = QPainter(self)
|
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
# A rounded panel debossed as far as the transport buttons stand out:
|
|
# it shows things, it isn't pressed.
|
|
rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
|
panel = theme.paint_deboss(painter, rect, self.panel_color(), RADIUS)
|
|
painter.setClipPath(panel) # keep the drawing inside the rounded shape
|
|
if self._no_pcm:
|
|
# Casting: the audio never passes through this machine, so show
|
|
# where it went instead of pretending to analyze silence.
|
|
glyph = transport_icon(
|
|
"cast", self.palette().highlight().color(),
|
|
size=ICON_SIZE).pixmap(ICON_SIZE, ICON_SIZE)
|
|
painter.drawPixmap(
|
|
(self.width() - ICON_SIZE) // 2,
|
|
(self.height() - ICON_SIZE) // 2, glyph)
|
|
painter.end()
|
|
return
|
|
self.paint_renderer(painter, QRectF(self.rect()))
|