v0.77.0: the laser visualizer is the Oscilloscope — screen sliders and rig diagram gone, a graticule dot size, and a sync delay per style

This commit is contained in:
2026-10-23 00:21:32 -07:00
parent 5413263587
commit 5f41460cb6
13 changed files with 357 additions and 478 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.76.0"
__version__ = "0.77.0"
-222
View File
@@ -1,222 +0,0 @@
"""A small line drawing of the laser rig as the settings describe it — the
speaker with its mirror, the laser, the beam, and the screen at its distance
and angles — in the manner of an old electronics textbook: thin dark-gray
lines, a dimension line with arrowheads, small italic serif labels.
Schematic, not to scale: the distance moves the screen along the beam and
the angles turn it (through the same rotation the visualizer projects
with), but sizes are chosen to read, not measured.
"""
import math
import numpy as np
from PyQt6.QtWidgets import QWidget, QSizePolicy
from PyQt6.QtCore import Qt, QPointF, QRectF, QSize
from PyQt6.QtGui import QPainter, QPen, QColor, QFont, QPolygonF, QFontMetricsF
from lintunes.gui import visualizer_styles
# Oblique projection: the screen's width (across the beam) recedes up and to
# the right at this share of its true length — a cabinet drawing.
DEPTH = 0.5
DEPTH_ANGLE = math.radians(35)
INK = 0.72 # how far the line color is from the background to the text
class LaserDiagram(QWidget):
def __init__(self, config=None, parent=None):
super().__init__(parent)
self._config = config or visualizer_styles.settings(None)
self.setSizePolicy(QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding)
self.setMinimumSize(300, 150)
self.setToolTip("The rig your settings describe (not to scale)")
def sizeHint(self):
return QSize(420, 160)
def set_config(self, config: dict):
self._config = config
self.update()
# ---- drawing helpers ----
def _ink(self) -> QColor:
text = self.palette().windowText().color()
back = self.palette().window().color()
return QColor(*(round(b + (t - b) * INK) for t, b in (
(text.red(), back.red()), (text.green(), back.green()),
(text.blue(), back.blue()))))
def _label_font(self, caps=False) -> QFont:
font = QFont(self.font())
font.setFamilies(["Times New Roman", "Liberation Serif", "DejaVu Serif"])
font.setStyleHint(QFont.StyleHint.Serif)
font.setItalic(not caps)
font.setPointSizeF(max(7.0, font.pointSizeF() - (1.5 if caps else 0.5)))
if caps:
font.setLetterSpacing(QFont.SpacingType.PercentageSpacing, 112)
return font
@staticmethod
def _arrowhead(painter, tip: QPointF, toward: QPointF, size=6.0):
angle = math.atan2(tip.y() - toward.y(), tip.x() - toward.x())
wing = math.radians(18)
painter.drawPolygon(QPolygonF([
tip,
QPointF(tip.x() - size * math.cos(angle - wing),
tip.y() - size * math.sin(angle - wing)),
QPointF(tip.x() - size * math.cos(angle + wing),
tip.y() - size * math.sin(angle + wing))]))
def screen_corners(self, center: QPointF, half_height: float,
pitch=None, yaw=None, roll=None) -> list:
"""The screen's outline, projected: its own right/up axes turned by
the angles, then the across-the-beam axis drawn receding."""
c = self._config
rot = visualizer_styles._rotation(
c["visualizer_laser_pitch"] if pitch is None else pitch,
c["visualizer_laser_yaw"] if yaw is None else yaw,
c["visualizer_laser_roll"] if roll is None else roll)
half_width = half_height * 1.6
corners = []
for u, v in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
x, y, z = rot @ np.array([u * half_width, v * half_height, 0.0])
corners.append(QPointF(
center.x() + z + x * DEPTH * math.cos(DEPTH_ANGLE),
center.y() - y - x * DEPTH * math.sin(DEPTH_ANGLE)))
return corners
# ---- the drawing ----
def paintEvent(self, event):
c = self._config
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
ink = self._ink()
thin = QPen(ink, 1.0)
thin.setCapStyle(Qt.PenCapStyle.RoundCap)
thin.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
dashed = QPen(ink, 0.8, Qt.PenStyle.DashLine)
italic, caps = self._label_font(), self._label_font(caps=True)
w, h = self.width(), self.height()
axis_y = h * 0.42
mirror = QPointF(62, axis_y)
half = min(h * 0.24, 34) # the screen's half-height
angle_labels_w = QFontMetricsF(italic).horizontalAdvance("pitch −60°") + 14
near_x = mirror.x() + 105
far_x = max(near_x + 40, w - angle_labels_w - half * 1.0)
lo, hi = visualizer_styles.LIMITS["visualizer_laser_distance"]
distance = c["visualizer_laser_distance"]
screen = QPointF(near_x + (distance - lo) / (hi - lo) * (far_x - near_x),
axis_y)
# The laser, below and ahead of the speaker, aimed up at the mirror.
laser_at = QPointF(mirror.x() + 62, axis_y + 30)
incoming = math.atan2(laser_at.y() - mirror.y(), laser_at.x() - mirror.x())
painter.save()
painter.translate(laser_at)
painter.rotate(math.degrees(incoming))
painter.setPen(thin)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRect(QRectF(0, -5, 34, 10))
painter.drawLine(QPointF(34, -3), QPointF(38, -3)) # a cable stub
painter.restore()
painter.setFont(caps)
painter.drawText(QPointF(laser_at.x() + 2, laser_at.y() + 26), "LASER")
# The speaker: its axis halfway between the laser and the screen, so
# the mirror on its membrane sends the beam straight along the axis.
normal = incoming / 2
painter.save()
painter.translate(mirror)
painter.rotate(math.degrees(normal))
painter.setPen(thin)
cone = QPolygonF([QPointF(0, -26), QPointF(-22, -9), QPointF(-22, 9),
QPointF(0, 26)])
painter.drawPolyline(cone)
painter.drawLine(QPointF(0, -26), QPointF(0, 26)) # the membrane
painter.drawRect(QRectF(-34, -10, 12, 20)) # the magnet
painter.drawLine(QPointF(-3, -27), QPointF(-3, 27)) # the frame lip
mirror_pen = QPen(ink, 3.0)
painter.setPen(mirror_pen)
painter.drawLine(QPointF(1.5, -6), QPointF(1.5, 6)) # the mirror
painter.restore()
painter.setPen(thin)
painter.setFont(caps)
painter.drawText(QPointF(mirror.x() - 52, axis_y + 46), "SPEAKER")
# The beam: in from the laser, out to the screen.
painter.drawLine(laser_at, mirror)
painter.setBrush(ink)
self._arrowhead(painter, QPointF((laser_at.x() + mirror.x()) / 2,
(laser_at.y() + mirror.y()) / 2), laser_at)
corners = self.screen_corners(screen, half)
painter.drawLine(mirror, screen)
mid = QPointF((mirror.x() + screen.x()) / 2, axis_y)
self._arrowhead(painter, mid, mirror)
painter.setBrush(Qt.BrushStyle.NoBrush)
# Where a screen facing the beam squarely would be, if this one isn't.
turned = any(c[k] for k in ("visualizer_laser_pitch",
"visualizer_laser_yaw", "visualizer_laser_roll"))
if turned:
painter.setPen(dashed)
painter.drawPolygon(QPolygonF(self.screen_corners(screen, half, 0, 0, 0)))
painter.setPen(thin)
painter.drawPolygon(QPolygonF(corners))
painter.setFont(caps)
top = min(p.y() for p in corners)
painter.drawText(QPointF(screen.x() - 22, max(10.0, top - 6)), "SCREEN")
# The dot, where the beam lands, at its size.
radius = max(1.0, min(9.0, c["visualizer_laser_dot"] / 2))
painter.setBrush(ink)
painter.setPen(Qt.PenStyle.NoPen)
painter.drawEllipse(screen, radius, radius)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.setPen(thin)
right = max(p.x() for p in corners)
lead_from = QPointF(screen.x() + radius + 1, screen.y() + radius + 1)
lead_to = QPointF(right + 10, axis_y + half * 0.9)
painter.drawLine(lead_from, lead_to)
painter.setFont(italic)
dot = c["visualizer_laser_dot"]
dot_text = f"dot {dot:g} px" + ("" if c["visualizer_laser_head"] else
" (at rest)")
painter.drawText(QPointF(lead_to.x() + 3, lead_to.y() + 4), dot_text)
# The angles, beside the screen.
lines = [f"pitch {_deg(c['visualizer_laser_pitch'])}",
f"yaw {_deg(c['visualizer_laser_yaw'])}",
f"roll {_deg(c['visualizer_laser_roll'])}"]
metrics = QFontMetricsF(italic)
y = axis_y - half - 2
for line in lines:
painter.drawText(QPointF(right + 10, y), line)
y += metrics.height()
# The distance: a dimension line under it all, mirror to screen.
dim_y = h - 12
painter.setPen(thin)
for x in (mirror.x(), screen.x()):
painter.drawLine(QPointF(x, dim_y - 6), QPointF(x, dim_y + 4))
left, right_end = QPointF(mirror.x(), dim_y), QPointF(screen.x(), dim_y)
text = f"D = {distance:.1f} m"
text_w = metrics.horizontalAdvance(text) + 10
centre = (left.x() + right_end.x()) / 2
painter.drawLine(left, QPointF(centre - text_w / 2, dim_y))
painter.drawLine(QPointF(centre + text_w / 2, dim_y), right_end)
painter.setBrush(ink)
self._arrowhead(painter, left, right_end, 5)
self._arrowhead(painter, right_end, left, 5)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawText(QPointF(centre - text_w / 2 + 5, dim_y + 4), text)
painter.end()
def _deg(value) -> str:
value = round(value)
return f"{value:+d}°".replace("-", "−") if value else "0°"
+42 -59
View File
@@ -17,7 +17,7 @@ from lintunes.config import load_config, save_config
from lintunes.export import upload
from lintunes.gui import visualizer_styles
from lintunes.gui.range_slider import RangeSlider
from lintunes.gui.laser_diagram import LaserDiagram
from lintunes.gui.scope_drawing import ScopeDrawing
from lintunes.gui import visualizer_presets as presets
from lintunes.gui import sounds
from lintunes.theme import HIGHLIGHT_COLORS
@@ -37,7 +37,7 @@ _COLOR_ROWS = [
]
# Room for the widest value a visualizer slider shows ("−180°", "400 ms").
# Room for the widest value a visualizer slider shows ("400 ms").
_VALUE_WIDTH = 56
@@ -45,7 +45,7 @@ HEADING_EXTRA_PX = 2 # section headings: this much over the text
_EDIT_PRESETS = "\0edit" # the preset drop-down's last item
_SPEAKER_KEYS = ("visualizer_laser_low_hz", "visualizer_laser_high_hz")
# The laser's speaker range: 20 Hz – 20 kHz in log steps of 1/30 octave.
# The oscilloscope's frequency range: 20 Hz – 20 kHz in log steps of 1/30 octave.
SPEAKER_STEPS = 300
@@ -625,6 +625,11 @@ class PreferencesDialog(QDialog):
# Only the chosen style's settings are shown.
self._viz_pages = QStackedWidget()
self._viz_setters = {} # key → puts a value into its control
self._sync_sliders = {} # style → its sync delay slider
self._sync_save_timer = QTimer(self)
self._sync_save_timer.setSingleShot(True)
self._sync_save_timer.setInterval(300)
self._sync_save_timer.timeout.connect(self._save_sync_delay)
self._preset_combos = {} # style → its preset drop-down
fade_tip = ("How long what's left behind takes to fade into the "
"background — 0 is no trail")
@@ -632,6 +637,7 @@ class PreferencesDialog(QDialog):
bars = QWidget()
form = self._viz_form(bars)
self._preset_row(form, "bars")
self._sync_delay_slider(form, "bars")
self._bars_count_box = self._viz_spinbox(
form, "Bars:", "visualizer_bars_count", config, step=1, decimals=0,
suffix="", tip="How many bars, 1 to 1024. Past the drawing's width "
@@ -644,6 +650,7 @@ class PreferencesDialog(QDialog):
radial = QWidget()
form = self._viz_form(radial)
self._preset_row(form, "radial")
self._sync_delay_slider(form, "radial")
self._fade_slider, _ = self._viz_slider(
form, "Fade:", "visualizer_ghost_fade", config, scale=20,
fmt=_fade_text, tip=fade_tip)
@@ -667,14 +674,13 @@ class PreferencesDialog(QDialog):
laser = QWidget()
form = self._viz_form(laser)
self._preset_row(form, "laser")
self._sync_delay_slider(form, "laser")
self._laser_fade_box = self._viz_spinbox(
form, "Afterimage:", "visualizer_laser_afterimage", config,
step=0.05, decimals=2, suffix=" s", off_text="Off",
tip="How long past sweeps of the beam take to fade — 0 is none")
self._speaker = self._speaker_range(form, config)
# The look controls on the left, and beside them a drawing of the
# rig the settings describe — it labels the distance, the angles
# and the dot, so those sliders carry no number of their own.
# The look controls on the left, a still drawing of a scope beside.
looks = self._viz_form(None)
self._width_box = self._viz_spinbox(
looks, "Line width:", "visualizer_laser_width", config,
@@ -683,49 +689,32 @@ class PreferencesDialog(QDialog):
looks, "Glow", "visualizer_laser_glow", config,
tip="The haze around the beam")
self._grid = self._viz_check(
looks, "Oscilloscope grid", "visualizer_laser_grid", config,
tip="A graticule of gray dots painted under the beam")
looks, "Graticule", "visualizer_laser_grid", config,
tip="The grid of gray dots on an oscilloscope's screen, painted "
"under the beam")
self._head = self._viz_check(
looks, "Dot at the tip of the beam", "visualizer_laser_head",
config, tip="When the music is silent the beam rests as a dot "
"in the middle either way")
self._diagram = LaserDiagram(config)
self._prefs.changed.connect(lambda: self._diagram.set_config(
visualizer_styles.settings(self._prefs)))
beside = QHBoxLayout()
beside.addLayout(looks)
beside.addSpacing(12)
beside.addWidget(self._diagram, stretch=1)
beside.addStretch()
beside.addWidget(ScopeDrawing())
form.addRow(beside)
self._dot_slider, _ = self._viz_slider(
form, "Dot size:", "visualizer_laser_dot", config, scale=2,
show_value=False)
self._distance_slider, _ = self._viz_slider(
form, "Screen distance:", "visualizer_laser_distance", config,
scale=10, show_value=False,
tip="From the mirror to the middle of the screen")
degrees = lambda v: f"{v:+.0f}°" if v else "0°"
self._angle_sliders = {}
for key, label, tip in (
("visualizer_laser_pitch", "Screen pitch:",
"Tip the screen's top toward or away from the speaker — "
"stretches the figure up and down"),
("visualizer_laser_yaw", "Screen yaw:",
"Turn the screen left or right — stretches the figure "
"sideways"),
("visualizer_laser_roll", "Screen roll:",
"Spin the screen in its own plane — turns the figure")):
self._angle_sliders[key], _ = self._viz_slider(
form, label, key, config, fmt=degrees, tip=tip,
show_value=False)
square = QPushButton("Face Screen Square")
square.clicked.connect(
lambda: [s.setValue(0) for s in self._angle_sliders.values()])
form.addRow("", square)
form, "Tip dot size:", "visualizer_laser_dot", config, scale=2,
fmt=lambda v: f"{v:g} px",
tip="The dot at the beam's tip, and the resting dot in silence")
self._grid_dot_slider, _ = self._viz_slider(
form, "Graticule dot size:", "visualizer_laser_grid_dot", config,
scale=100, fmt=lambda v: f"{round(v * 100)}%",
tip="100% is the size that suits the screen's size")
self._viz_pages.addWidget(laser)
kaleido = QWidget()
form = self._viz_form(kaleido)
self._sync_delay_slider(form, "kaleidostrobe")
about = QLabel(
"The 2002 iTunes visualizer by Shehryar Lasi, rebuilt from its "
"original code. It has no settings: the Color and Flash boxes "
@@ -739,10 +728,6 @@ class PreferencesDialog(QDialog):
self._fit_viz_pages()
column.addWidget(self._viz_pages)
# For every style: this machine's speakers' latency (config.json).
form = QFormLayout()
self._sync_slider = self._sync_delay_slider(form)
column.addLayout(form)
note = QLabel("Click the visualizer to see it big.")
note.setEnabled(False)
column.addWidget(note)
@@ -880,11 +865,11 @@ class PreferencesDialog(QDialog):
QMessageBox.warning(self, "Save as Preset", text)
def _speaker_range(self, form, config) -> RangeSlider:
"""The speaker under the mirror: which frequencies it plays, on a
log scale (each slider step is the same musical interval)."""
"""Which frequencies drive the trace (the "speaker" in
visualizer_styles), on a log scale (each slider step is the same musical interval)."""
slider = RangeSlider(0, SPEAKER_STEPS, gap=_speaker_gap())
slider.setToolTip(
"What the speaker under the mirror plays. Bass makes the big "
"Which frequencies drive the trace. Bass makes the big "
"loops; treble is a fine shiver on them. Slide the low end up to "
"watch the treble on its own.")
slider.setValues(_hz_to_step(config["visualizer_laser_low_hz"]),
@@ -906,10 +891,12 @@ class PreferencesDialog(QDialog):
row.addWidget(slider, stretch=1)
row.addSpacing(8)
row.addWidget(text)
form.addRow("Speaker range:", row)
form.addRow("Frequency range:", row)
return slider
def _sync_delay_slider(self, form) -> QSlider:
def _sync_delay_slider(self, form, style: str) -> QSlider:
"""This style's sync delay — this machine's speakers' latency plus
the style's own lag, so one per style, in config.json."""
lo, hi = visualizer_styles.SYNC_DELAY_LIMITS
slider = QSlider(Qt.Orientation.Horizontal)
slider.setRange(lo, hi)
@@ -919,8 +906,9 @@ class PreferencesDialog(QDialog):
"If the visualizer runs ahead of what you hear — Bluetooth "
"headphones especially — hold it back this much. Below zero it "
"reacts sooner, by up to as much audio as the player has decoded "
"ahead (usually a few tens of ms). Set per computer.")
slider.setValue(visualizer_styles.sync_delay_ms(load_config()))
"ahead (usually a few tens of ms). Set per computer and per "
"style, since each style lags in its own way.")
slider.setValue(visualizer_styles.sync_delay_ms(load_config(), style))
text = QLabel(_sync_text(slider.value()))
text.setMinimumWidth(max(_VALUE_WIDTH, text.fontMetrics().horizontalAdvance(
_sync_text(visualizer_styles.SYNC_DELAY_LIMITS[0])) + 4))
@@ -930,10 +918,7 @@ class PreferencesDialog(QDialog):
self._sync_save_timer.start()
slider.valueChanged.connect(changed)
self._sync_save_timer = QTimer(self)
self._sync_save_timer.setSingleShot(True)
self._sync_save_timer.setInterval(300)
self._sync_save_timer.timeout.connect(self._save_sync_delay)
self._sync_sliders[style] = slider
row = QHBoxLayout()
row.addWidget(slider, stretch=1)
row.addSpacing(8)
@@ -943,7 +928,8 @@ class PreferencesDialog(QDialog):
def _save_sync_delay(self):
config = load_config()
config[visualizer_styles.SYNC_DELAY_KEY] = self._sync_slider.value()
config[visualizer_styles.SYNC_DELAYS_KEY] = {
style: slider.value() for style, slider in self._sync_sliders.items()}
save_config(config)
# config.json has no signal of its own; the visualizer re-reads it
# whenever preferences change.
@@ -959,7 +945,7 @@ class PreferencesDialog(QDialog):
return box
def _viz_slider(self, form, label, key, config, *, scale=1, fmt=str,
tip="", show_value=True):
tip=""):
"""A slider over ``visualizer_styles.LIMITS[key]`` that previews live
and saves once the drag settles, with its value beside it."""
lo, hi = visualizer_styles.LIMITS[key]
@@ -979,11 +965,8 @@ class PreferencesDialog(QDialog):
slider.valueChanged.connect(changed)
row = QHBoxLayout()
row.addWidget(slider, stretch=1)
if show_value:
row.addSpacing(8)
row.addWidget(text)
else:
text.hide() # shown elsewhere (the laser diagram)
row.addSpacing(8)
row.addWidget(text)
form.addRow(label, row)
self._viz_setters[key] = lambda value: slider.setValue(round(value * scale))
return slider, text
@@ -994,7 +977,7 @@ class PreferencesDialog(QDialog):
self._prefs.set("visualizer_style", key)
def _fit_viz_pages(self):
"""A stack is as tall as its tallest page (the laser's), which left
"""A stack is as tall as its tallest page (the oscilloscope's), which left
the other styles over a block of empty space; only the shown page
counts toward its size."""
stack = self._viz_pages
+87
View File
@@ -0,0 +1,87 @@
"""A small, still line drawing of an oscilloscope beside the Oscilloscope
style's settings, in the manner of an old electronics textbook: thin
dark-gray lines, the screen's dot graticule, a Lissajous loop on it and two
knobs underneath. It shows what the style is; it doesn't follow the settings.
"""
import math
from PyQt6.QtWidgets import QWidget, QSizePolicy
from PyQt6.QtCore import Qt, QPointF, QRectF, QSize
from PyQt6.QtGui import QPainter, QPen, QColor, QPolygonF
INK = 0.72 # how far the line color is from the background to the text
class ScopeDrawing(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Policy.Preferred,
QSizePolicy.Policy.Preferred)
self.setMinimumSize(150, 116)
def sizeHint(self):
return QSize(170, 128)
def _ink(self) -> QColor:
text = self.palette().windowText().color()
back = self.palette().window().color()
return QColor(*(round(b + (t - b) * INK) for t, b in (
(text.red(), back.red()), (text.green(), back.green()),
(text.blue(), back.blue()))))
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
ink = self._ink()
pen = QPen(ink, 1.0)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(pen)
painter.setBrush(Qt.BrushStyle.NoBrush)
# The case, 4:3, centered.
w, h = self.width() - 2, self.height() - 2
case_w = min(w, h * 4 / 3)
case = QRectF((self.width() - case_w) / 2, (self.height() - case_w * 3 / 4) / 2,
case_w, case_w * 3 / 4)
painter.drawRoundedRect(case, 6, 6)
# The screen: the left three quarters, with the knobs to its right.
pad = case.height() * 0.1
screen = QRectF(case.left() + pad, case.top() + pad,
case.width() * 0.68, case.height() - 2 * pad)
painter.drawRoundedRect(screen, 4, 4)
# The graticule: a dot at every division, 8 × 6.
dots = QPen(ink, 2.2)
dots.setCapStyle(Qt.PenCapStyle.RoundCap)
painter.setPen(dots)
inner = screen.adjusted(4, 4, -4, -4)
painter.drawPoints([QPointF(inner.left() + i * inner.width() / 8,
inner.top() + j * inner.height() / 6)
for i in range(1, 8) for j in range(1, 6)])
# A 3:2 Lissajous figure.
cx, cy = inner.center().x(), inner.center().y()
rx, ry = inner.width() * 0.38, inner.height() * 0.38
trace = QPen(ink, 1.3)
trace.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(trace)
steps = 240
painter.drawPolyline(QPolygonF([
QPointF(cx + rx * math.sin(3 * t + math.pi / 2),
cy + ry * math.sin(2 * t + math.pi / 4))
for t in (2 * math.pi * k / steps for k in range(steps + 1))]))
# Two knobs, each with a pointer.
painter.setPen(pen)
knob_x = (screen.right() + case.right()) / 2
radius = min(case.right() - screen.right(), case.height()) * 0.2
for share, turn in ((0.32, -40), (0.68, 70)):
center = QPointF(knob_x, case.top() + case.height() * share)
painter.drawEllipse(center, radius, radius)
angle = math.radians(turn - 90)
painter.drawLine(center, QPointF(
center.x() + radius * 0.8 * math.cos(angle),
center.y() + radius * 0.8 * math.sin(angle)))
painter.end()
+3 -3
View File
@@ -87,7 +87,7 @@ class VisualizerWidget(QWidget):
self._total = 0 # samples ever appended: the history's end index
self._drawn = None # index the laser has consumed up to
self._anchor = None # (position ms, monotonic s) of the last update
self._sync_delay = styles.sync_delay_ms(load_config())
self._sync_delay = styles.sync_delay_ms(load_config(), _style(prefs))
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.
@@ -130,8 +130,8 @@ class VisualizerWidget(QWidget):
return self._renderer.levels
def _on_prefs_changed(self):
self._sync_delay = styles.sync_delay_ms(load_config())
style = _style(self._prefs)
self._sync_delay = styles.sync_delay_ms(load_config(), style)
config = styles.settings(self._prefs)
if style != self._renderer.name:
self._renderer = make_renderer(style, config)
@@ -474,7 +474,7 @@ class VisualizerWidget(QWidget):
return QColor(self.palette().highlight().color())
def _grid_gray(self):
"""The laser's graticule: the gray, faded so the beam reads over it
"""The oscilloscope's graticule: the gray, faded so the beam reads over it
even when the beam is gray too."""
gray = self._gray().darker(115)
gray.setAlphaF(0.75)
+1 -2
View File
@@ -32,8 +32,7 @@ STYLE_KEYS = {
"visualizer_laser_high_hz", "visualizer_laser_width",
"visualizer_laser_glow", "visualizer_laser_grid",
"visualizer_laser_head", "visualizer_laser_dot",
"visualizer_laser_distance", "visualizer_laser_pitch",
"visualizer_laser_yaw", "visualizer_laser_roll"),
"visualizer_laser_grid_dot"),
}
+55 -73
View File
@@ -8,8 +8,9 @@ audio intake, the timer, on/dim/off, the color. Pure numpy + QPainter.
- ``BarsRenderer`` — the original 20-band graphic EQ.
- ``RadialRenderer`` — that EQ wrapped into a circle as dots: angle is
frequency, radius is volume, and a dot that moves leaves fading ghosts.
- ``LaserRenderer`` — a laser bounced off a mirror glued to a membrane
stretched over a speaker, projected onto a screen (Tame Impala's rig).
- ``LaserRenderer`` — the Oscilloscope: an X-Y trace of the bass, as a
laser off a mirror on a speaker membrane would draw it (Tame Impala's
rig). Named "laser" in code and prefs, which is what it started as.
- ``KaleidostrobeRenderer`` (``visualizer_kaleido``) — the 2002 iTunes
plugin, ported from its PowerPC binary.
@@ -36,7 +37,7 @@ STYLES = (STYLE_BARS, STYLE_RADIAL, STYLE_LASER, STYLE_KALEIDOSTROBE)
STYLE_NAMES = {
STYLE_BARS: "Bars",
STYLE_RADIAL: "Radial dots",
STYLE_LASER: "Laser",
STYLE_LASER: "Oscilloscope",
STYLE_KALEIDOSTROBE: "Kaleidostrobe",
}
@@ -62,16 +63,13 @@ LIMITS = {
"visualizer_laser_afterimage": (0.0, 3.0),
"visualizer_laser_width": (1.0, 8.0), # pixels
"visualizer_laser_dot": (1.0, 16.0), # pixels across
"visualizer_laser_grid_dot": (0.25, 3.0), # × the graticule's own size
# What the speaker under the mirror plays. At the ends, no filter.
"visualizer_laser_low_hz": (20, 20000),
"visualizer_laser_high_hz": (20, 20000),
"visualizer_radial_spokes": (12, 360),
"visualizer_radial_levels": (4, 40),
"visualizer_radial_dot": (0.2, 2.5), # × the automatic size
"visualizer_laser_distance": (1.0, 4.0), # metres, mirror → screen
"visualizer_laser_pitch": (-60, 60), # degrees
"visualizer_laser_yaw": (-60, 60),
"visualizer_laser_roll": (-180, 180),
}
_FLAGS = ("visualizer_radial_normalize", "visualizer_laser_head",
"visualizer_laser_glow", "visualizer_laser_grid")
@@ -82,7 +80,12 @@ SPEAKER_MIN_RATIO = 2 ** (1 / 3) # the narrowest speaker: a third-octave
# How much later than Qt's playback position the speakers really are —
# PipeWire's buffer, and far more over Bluetooth. That's this machine's
# audio hardware, so it lives in config.json, never the synced prefs.
# audio hardware, so it lives in config.json, never the synced prefs. One
# per style, {style: ms}: each adds its own lag on top (radial's 93 ms FFT
# window, the bars' fall, Kaleidostrobe's 25 fps, the scope's ringing).
SYNC_DELAYS_KEY = "visualizer_sync_delays"
# The single value every style shared before; a style not yet set starts
# from it.
SYNC_DELAY_KEY = "visualizer_sync_delay_ms"
# Negative = sooner: the frame is taken from audio decoded but not yet
# heard. The player decodes only a few tens of ms ahead (measured 0–30 ms),
@@ -90,9 +93,12 @@ SYNC_DELAY_KEY = "visualizer_sync_delay_ms"
SYNC_DELAY_LIMITS = (-50, 400)
def sync_delay_ms(config: dict) -> int:
def sync_delay_ms(config: dict, style: str) -> int:
delays = config.get(SYNC_DELAYS_KEY)
if not isinstance(delays, dict) or style not in delays:
delays = {style: config.get(SYNC_DELAY_KEY, 0)}
try:
value = int(config.get(SYNC_DELAY_KEY, 0))
value = int(delays[style])
except (TypeError, ValueError):
return 0
return min(SYNC_DELAY_LIMITS[1], max(SYNC_DELAY_LIMITS[0], value))
@@ -520,14 +526,19 @@ class RadialRenderer:
# Laser
# --------------------------------------------------------------------------
#
# The rig: a small mirror glued to a rubber membrane stretched over a
# speaker; a laser hits the mirror and the reflection lands on a big
# screen. What moves the beam is the *tilt* of the mirror, and a membrane
# doesn't just pump in and out — it vibrates in modes, each with its own
# resonance and its own shape. The mirror's tilt is the membrane's slope
# where the mirror sits, so every mode pushes the beam along one fixed
# direction on the screen, at a strength set by how near the music is to
# that mode's resonance.
# What this really is: an oscilloscope in X-Y mode. The audio, through the
# "speaker" (a band-pass), drives nine resonators, and each one pushes the
# trace along its own fixed direction; their sum is X and Y. Where those
# resonators sit and which way they push comes from modelling the rig it
# was first built as — a small mirror glued to a rubber membrane stretched
# over a speaker, a laser off the mirror onto a screen — because that model
# is what draws loops rather than strokes:
#
# What moves the beam is the *tilt* of the mirror, and a membrane doesn't
# just pump in and out — it vibrates in modes, each with its own resonance
# and its own shape. The mirror's tilt is the membrane's slope where the
# mirror sits, so every mode pushes the beam along one fixed direction, at
# a strength set by how near the music is to that mode's resonance.
#
# The modes of a circular membrane are J_m(j_mn·r)·cos(mθ), resonating at
# j_mn/j_01 times the fundamental. The m > 0 modes come in pairs at right
@@ -536,19 +547,16 @@ class RadialRenderer:
# same note up to 90° apart — the beam swings along one axis a quarter
# cycle behind the other, which is a circle. A mirror near the middle sits
# where that rocking pair dominates (the (0,1) "breathing" mode has no
# slope at the center, so it only draws lines), which is why the rig's
# figures are loops rather than strokes. A perfectly even push wouldn't
# excite the m > 0 modes at all; the mirror's own mass, off-center, is
# what couples them.
# slope at the center, so it only draws lines), which is why the figures
# are loops. A perfectly even push wouldn't excite the m > 0 modes at all;
# the mirror's own mass, off-center, is what couples them.
#
# Reflection doubles the angle: tilt θ turns the beam 2θ, and the spot is
# where that ray meets the screen. A screen square to the beam puts it at
# D·tan(2θ); a screen turned away (pitch, yaw) stretches the figure along
# the turn and spreads its far side wider (keystone); roll spins it. The
# spot moves far faster than an eye or a camera follows, so what anyone
# sees is the whole path traced in one glance, brightest where the beam
# moves slowest (it dwells there), with the haze and the screen's scatter
# blooming around it.
# D·tan(2θ) on a screen square to it. (Round 78 let the screen be moved and
# turned; that only stretched, keystoned or spun a tangle of loops, and
# Round 108 took it out.) The spot moves far faster than an eye follows, so
# what anyone sees is the whole path traced in one glance, brightest where
# the beam moves slowest (it dwells there), with a bloom around it.
MODE_ZEROS = ( # (m, j_mn) — Bessel zeros
(0, 2.40483), (1, 3.83171), (2, 5.13562), (0, 5.52008), (3, 6.38016),
@@ -564,11 +572,10 @@ SPLIT = (0.0, 0.30, 0.24, 0.0, 0.18)
MIRROR_AT = (0.15, 0.6) # the mirror's spot: radius (of 1), angle (rad)
SIM_RATE = 11025.0 # the membrane barely answers above a few hundred Hz
SCREEN_HALF = 1.0 # the screen's half-height, metres
FILL = 0.85 # at the farthest distance, the loudest swings fill this
# The auto-gain holds the beam's loudest swing at this angle, so distance
# is real: the figure grows as the screen moves back, filling it at the
# slider's far end.
BEAM_TARGET = math.atan(FILL * SCREEN_HALF / LIMITS["visualizer_laser_distance"][1])
SCREEN_DISTANCE = 3.5 # metres, mirror → screen
FILL = 0.75 # the share of the screen the loudest swings fill
# The auto-gain holds the beam's loudest swing at this angle.
BEAM_TARGET = math.atan(FILL * SCREEN_HALF / SCREEN_DISTANCE)
GAIN_RELEASE_S = 0.3 # how slowly the auto-gain turns back up after a peak
# Silence must stay a still dot, not amplified hiss: the auto-gain never
# turns up past what -60 dB hiss would swing, 22 dB over. Measured through
@@ -637,18 +644,6 @@ def _membrane_modes():
MODES = _membrane_modes()
def _rotation(pitch, yaw, roll) -> np.ndarray:
"""The screen's orientation: columns are its right, up and normal."""
p, y, r = (math.radians(a) for a in (pitch, yaw, roll))
rx = np.array([[1, 0, 0], [0, math.cos(p), -math.sin(p)],
[0, math.sin(p), math.cos(p)]])
ry = np.array([[math.cos(y), 0, math.sin(y)], [0, 1, 0],
[-math.sin(y), 0, math.cos(y)]])
rz = np.array([[math.cos(r), -math.sin(r), 0],
[math.sin(r), math.cos(r), 0], [0, 0, 1]])
return ry @ rx @ rz
class LaserRenderer:
name = STYLE_LASER
@@ -676,6 +671,7 @@ class LaserRenderer:
self.head = config["visualizer_laser_head"]
self.glow = config["visualizer_laser_glow"]
self.grid = config["visualizer_laser_grid"]
self.grid_dot = config["visualizer_laser_grid_dot"]
band = (config["visualizer_laser_low_hz"],
config["visualizer_laser_high_hz"])
if band != getattr(self, "band", None):
@@ -683,18 +679,9 @@ class LaserRenderer:
if self._rate:
self._setup(self._rate)
self._prune()
self.distance = config["visualizer_laser_distance"]
rot = _rotation(config["visualizer_laser_pitch"],
config["visualizer_laser_yaw"],
config["visualizer_laser_roll"])
self._right, self._up, self._normal = rot[:, 0], rot[:, 1], rot[:, 2]
# How far the loudest possible swing reaches on this screen, each
# way: what painting scales by so it always stays in view.
ring = np.linspace(0, 2 * math.pi, 96, endpoint=False)
edge = np.column_stack([np.cos(ring), np.sin(ring)]) * BEAM_TARGET
spots = self.on_screen(edge)
self.extent = (max(np.abs(spots[:, 0]).max(), 1e-6),
max(np.abs(spots[:, 1]).max(), 1e-6))
# How far the loudest possible swing reaches on the screen.
reach = SCREEN_DISTANCE * math.tan(BEAM_TARGET)
self.extent = (reach, reach)
def clear(self):
self._state = np.zeros(len(MODES), dtype=np.complex128)
@@ -796,17 +783,11 @@ class LaserRenderer:
# ---- the screen ----
def on_screen(self, beam: np.ndarray) -> np.ndarray:
@staticmethod
def on_screen(beam: np.ndarray) -> np.ndarray:
"""Beam angles (n, 2) from the rest direction → where the ray meets
the screen, metres from its center along its own right and up."""
ray = np.column_stack([np.tan(beam[:, 0]), np.tan(beam[:, 1]),
np.ones(len(beam))])
center = np.array([0.0, 0.0, self.distance])
# ray·t meets the plane through `center` with this normal at
# t = (n·c)/(n·ray). The angle limits keep n·ray well above 0.
t = (self._normal @ center) / np.maximum(ray @ self._normal, 1e-3)
offset = ray * t[:, None] - center
return np.column_stack([offset @ self._right, offset @ self._up])
the screen, metres from its center."""
return SCREEN_DISTANCE * np.tan(beam)
def project(self, tilt: np.ndarray, dt: float) -> np.ndarray:
"""Mirror tilt → spot on the screen (metres, y up)."""
@@ -847,8 +828,8 @@ class LaserRenderer:
def scale(self, rect) -> float:
"""Pixels per metre: the screen's half-height fills the rect's, and
shrinks only if the loudest swing would leave the rect (a steeply
turned screen) — so the figure is always on screen."""
shrinks only if the loudest swing would leave the rect — so the
figure is always on screen."""
half_w = rect.width() / 2 - INSET
half_h = rect.height() / 2 - INSET
unit = min(half_w, half_h) / SCREEN_HALF
@@ -896,7 +877,8 @@ class LaserRenderer:
def paint_grid(self, painter, rect, gray: QColor):
"""An oscilloscope's graticule: dots at every division crossing, and
finer ticks along the two center lines. Painted *on the glass*, so
it stays put in the window whatever the screen's angle or distance."""
it stays put in the window whatever the trace does. ``grid_dot``
scales the dots from their automatic size."""
cx, cy = rect.center().x(), rect.center().y()
division = (min(rect.width(), rect.height()) / 2 - INSET) / GRID_HALF
if division < 4:
@@ -914,10 +896,10 @@ class LaserRenderer:
if k % GRID_TICKS]
pen = QPen(gray)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setWidthF(max(1.5, division / 12))
pen.setWidthF(max(1.5, division / 12) * self.grid_dot)
painter.setPen(pen)
painter.drawPoints(major)
pen.setWidthF(max(1.0, division / 20))
pen.setWidthF(max(1.0, division / 20) * self.grid_dot)
painter.setPen(pen)
painter.drawPoints(ticks)
+1 -4
View File
@@ -27,6 +27,7 @@ DEFAULTS = {
"visualizer_laser_head": True, # a dot at the moving beam's tip
"visualizer_laser_glow": True, # the haze/scatter bloom
"visualizer_laser_grid": False, # an oscilloscope's dot graticule
"visualizer_laser_grid_dot": 1.0, # its dots, × their automatic size
"visualizer_presets": {}, # {style: {name: settings}}
"visualizer_laser_low_hz": 20, # the speaker under the mirror:
"visualizer_laser_high_hz": 20000, # what it plays (ends = no filter)
@@ -34,10 +35,6 @@ DEFAULTS = {
"visualizer_radial_levels": 20, # volume steps along each spoke
"visualizer_radial_dot": 1.0, # dot size, × the automatic size
"visualizer_radial_normalize": True, # even out bass vs treble
"visualizer_laser_distance": 3.5, # metres, mirror → screen center
"visualizer_laser_pitch": 0, # degrees the screen is turned
"visualizer_laser_yaw": 0,
"visualizer_laser_roll": 0,
# Per-area grayscale overrides (0=black .. 255=white). None = inherit the
# current/default look for that surface, so nothing changes until the user
# drags a slider in Preferences.