v0.53.0: Kaleidostrobe, the 2002 iTunes visualizer, as the fourth style

Reverse-engineered from its PowerPC binary and checked against the original
running under emulation: textures byte for byte and every triangle, over
3,600 frames. 25 fps like the plugin; its colour maps and wave images are
extracted from its own code; tests/kaleidostrobe_golden.npz was recorded
from the original.
This commit is contained in:
2026-10-14 12:02:22 -07:00
parent 6178f5d0f7
commit e38c751e39
21 changed files with 2109 additions and 3 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.52.0"
__version__ = "0.53.0"
+12
View File
@@ -79,6 +79,7 @@ _VISUALIZER_STYLES = {
"bars": "Bars",
"radial": "Radial dots",
"laser": "Laser",
"kaleidostrobe": "Kaleidostrobe",
}
@@ -599,6 +600,17 @@ class PreferencesDialog(QDialog):
form.addRow("", square)
self._viz_pages.addWidget(laser)
kaleido = QWidget()
form = self._viz_form(kaleido)
about = QLabel(
"The 2002 iTunes visualizer by Shehryar Lasi, rebuilt from its "
"original code. It has no settings: the Color and Flash boxes "
"it once showed were never connected to anything.")
about.setWordWrap(True)
about.setEnabled(False)
form.addRow(about)
self._viz_pages.addWidget(kaleido)
self._viz_pages.setCurrentIndex(list(_VISUALIZER_STYLES).index(current))
column.addWidget(self._viz_pages)
+3
View File
@@ -348,6 +348,9 @@ class VisualizerWidget(QWidget):
regardless (in color), since opening it is asking to see it."""
if self._no_pcm or (self._mode == MODE_OFF and not big):
return
# A style with colours of its own (Kaleidostrobe) can't take the
# gray as its colour; it is told instead.
self._renderer.dimmed = self._mode == MODE_DIM
self._renderer.paint(painter, rect, self._bar_color(), self._grid_gray())
def paintEvent(self, event):
+198
View File
@@ -0,0 +1,198 @@
"""Kaleidostrobe as a visualizer style: the 2002 iTunes plugin's simulation
(``lintunes.kaleidostrobe.engine``), fed what iTunes fed it and painted the
way its OpenGL did.
Two things are this file's business, the rest is the engine's:
- **Time.** The plugin rendered only when more than 40 ms had passed since
its last frame, so it ran at 25 fps however often iTunes asked, and its
rotation and pattern switching count *frames*. The renderer keeps its own
25 Hz clock and steps the engine on it, never on the widget's 60 Hz timer
— otherwise everything would spin 2.4× too fast. TickCount (1/60 s) is
derived from the same clock.
- **Input.** iTunes handed plugins 512 spectrum bins per channel as bytes.
How iTunes scaled them was never documented; ``itunes_spectrum`` is a
calibrated stand-in (``SPECTRUM_GAIN``). Kaleidostrobe divides everything by
running peaks, so it is the *shape* over time that matters, not the units.
Painting: every GL triangle is planar, so its texture → screen mapping is a
homography; each one is filled with the texture as a tiled brush under that
projective transform (GL_REPEAT, GL_LINEAR via smooth transforms). The top
layer's depth is always in front of the bottom one's, so painter's order is
the depth test.
"""
import math
import time
import numpy as np
from PyQt6.QtCore import Qt, QPointF
from PyQt6.QtGui import QBrush, QColor, QImage, QPainter, QPolygonF, QTransform
from lintunes.kaleidostrobe import engine as ks
STYLE = "kaleidostrobe"
STEP_S = ks.FRAME_US / 1e6 # one plugin frame
MAX_CATCH_UP = 3 # frames run at once after a stall, at most
FFT_AT_44K = 1024 # iTunes' 512 bins are a 1024-point FFT's half
SPECTRUM_GAIN = 320.0 # byte = √magnitude × this (full-scale sine = 1)
_PROJ_F = 1.0 / math.tan(math.radians(ks.FOVY) / 2)
_WINDOWS = {}
def itunes_spectrum(samples: np.ndarray, rate: float) -> np.ndarray:
"""2×512 bytes shaped like iTunes' ``spectrumData``: linear bins 43 Hz
apart (a 1024-point FFT at 44.1 kHz, whatever the real rate). Mono audio
fills both channels alike.
The byte scale is ours. Measured against synthetic songs, a log (dB)
scale pins all three of the plugin's band levels near 1, so the cone
height and colour scaling stop moving; linear magnitude starves the
mids. √magnitude keeps all three alive. Beat detection barely cares —
it hears a 90 BPM backbeat on every scale, and on none can it pick a
kick out of a constant sub-bass, which is the original's own limit."""
n = max(64, int(round(FFT_AT_44K * rate / 44100.0)))
window = _WINDOWS.get(n)
if window is None:
window = _WINDOWS[n] = np.hanning(n).astype(np.float32)
seg = samples[-n:]
if len(seg) < n:
seg = np.concatenate([np.zeros(n - len(seg), np.float32), seg])
mag = np.abs(np.fft.rfft(seg * window))[:512] / (n / 4)
if len(mag) < 512:
mag = np.concatenate([mag, np.zeros(512 - len(mag))])
row = np.clip(np.sqrt(mag) * SPECTRUM_GAIN, 0, 255).astype(np.uint8)
return np.stack([row, row])
def _rotz(deg):
r = math.radians(deg)
c, s = math.cos(r), math.sin(r)
return np.array([[c, -s, 0, 0], [s, c, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
def _lift(z):
m = np.eye(4)
m[2, 3] = z
return m
class KaleidostrobeRenderer:
name = STYLE
dimmed = False # set by the widget: paint in dim mode's gray
def __init__(self, config=None):
self._engine = None
self._clock = 0.0 # simulated seconds since the engine began
self._behind = 0.0 # time owed to the 25 Hz clock
self._frame = None # the last FrameOut, or None = blank
self._images = [None, None]
# ---- the renderer contract ----
def configure(self, config):
pass # the original's two settings were never read by its code
def clear(self):
"""Paused or stopped: blank, but the plugin keeps its state, as it
did across iTunes' pause."""
self._frame = None
def advance(self, frame) -> bool:
if self._engine is None:
# srand(TickCount()) at 'init': any clock reading will do
seed = int(time.monotonic() * ks.TICKS_PER_S) & 0x7fffffff
self._engine = ks.Kaleidostrobe(seed, self._ticks())
self._behind = min(self._behind + max(0.0, frame.dt),
STEP_S * MAX_CATCH_UP)
stepped = False
while self._behind >= STEP_S:
self._behind -= STEP_S
self._clock += STEP_S
spectrum = itunes_spectrum(frame.samples, frame.rate)
self._frame = self._engine.step(spectrum, self._ticks())
self._images = [None, None]
stepped = True
return stepped
def _ticks(self):
return 1000 + int(self._clock * ks.TICKS_PER_S)
# ---- painting ----
def _texture(self, i, dim):
img = self._images[i]
if img is None:
rgba = np.ascontiguousarray(self._frame.textures[i])
img = QImage(rgba.data, ks.SIZE, ks.SIZE, ks.SIZE * 4,
QImage.Format.Format_RGBA8888).copy()
self._images[i] = img
if dim is not None:
img = _dimmed(img, dim)
return img
def paint(self, painter, rect, color: QColor, gray: QColor = None):
if self._frame is None or rect.width() < 2 or rect.height() < 2:
return
# In colour mode the highlight goes unused — Kaleidostrobe brought
# its own palettes. Dim mode tints the picture with its gray.
dim = color if self.dimmed else None
painter.save()
painter.setClipRect(rect, Qt.ClipOperation.IntersectClip)
painter.fillRect(rect, QColor(0, 0, 0)) # glClearColor(0, 0, 0, 0)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, False)
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True)
painter.setPen(Qt.PenStyle.NoPen)
w, h = rect.width(), rect.height()
aspect = w / h
proj = np.array([[_PROJ_F / aspect, 0, 0, 0],
[0, _PROJ_F, 0, 0],
[0, 0, -1.0, 0]]) # rows: x_c, y_c, w_c
screen = np.array([[w / 2, 0, rect.left() + w / 2],
[0, -h / 2, rect.top() + h / 2],
[0, 0, 1.0]])
# The rim reaches this rect's corners (reshape's gFarHalfWidth).
engine_fhw = self._engine.far_half_width
half = ks.f32(ks.FAR_HALF_HEIGHT * aspect)
rim = math.sqrt(2 * half * half) / engine_fhw if engine_fhw else 1.0
view = _lift(-ks.EYE_Z)
world = painter.worldTransform()
for layer in self._frame.layers:
painter.setBrush(QBrush(self._texture(layer.texture, dim)))
painter.setOpacity(layer.alpha)
base = view @ _lift(layer.lift) @ _rotz(layer.turn)
for tri in layer.triangles:
m = screen @ proj @ (base @ _rotz(tri.turn))
pts = np.array([(x * rim, y * rim, z, 1.0) if z == 0.0
else (x, y, z, 1.0) for x, y, z in tri.xyz])
st = np.array([(s, t, 1.0) for s, t in tri.st])
to_xyz = pts.T @ np.linalg.inv(st.T) # (s, t, 1) → object
hom = m @ to_xyz @ np.diag([1 / ks.SIZE, 1 / ks.SIZE, 1.0])
# Scale so w is 1 at the first vertex: every vertex is in
# front of the eye, so w stays positive across the triangle.
hom = hom / (m @ pts[0])[2]
# Draw the triangle in texture space through the homography:
# Qt's raster engine is exact for a projective *world*
# transform, not for a projective brush transform.
painter.setWorldTransform(QTransform(
hom[0, 0], hom[1, 0], hom[2, 0],
hom[0, 1], hom[1, 1], hom[2, 1],
hom[0, 2], hom[1, 2], hom[2, 2]) * world)
painter.drawPolygon(QPolygonF(
[QPointF(s * ks.SIZE, t * ks.SIZE) for s, t in tri.st]))
painter.restore()
def _dimmed(img: QImage, tint: QColor) -> QImage:
"""Dim mode: the picture's luminance in the panel's gray."""
a = np.frombuffer(img.constBits().asstring(img.sizeInBytes()), np.uint8)
a = a.reshape(ks.SIZE, ks.SIZE, 4).astype(np.float32)
luma = (a[..., 0] * 0.299 + a[..., 1] * 0.587 + a[..., 2] * 0.114) / 255.0
out = np.empty((ks.SIZE, ks.SIZE, 4), np.uint8)
for i, c in enumerate((tint.red(), tint.green(), tint.blue())):
out[..., i] = (luma * c).astype(np.uint8)
out[..., 3] = 255
return QImage(out.data, ks.SIZE, ks.SIZE, ks.SIZE * 4,
QImage.Format.Format_RGBA8888).copy()
+7 -1
View File
@@ -10,6 +10,8 @@ audio intake, the timer, on/dim/off, the color. Pure numpy + QPainter.
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).
- ``KaleidostrobeRenderer`` (``visualizer_kaleido``) — the 2002 iTunes
plugin, ported from its PowerPC binary.
Every tunable lives in preferences.json under a ``visualizer_*`` key;
``settings(prefs)`` reads them clamped to ``LIMITS``, and a renderer takes
@@ -29,7 +31,8 @@ from lintunes.preferences import DEFAULTS
STYLE_BARS = "bars"
STYLE_RADIAL = "radial"
STYLE_LASER = "laser"
STYLES = (STYLE_BARS, STYLE_RADIAL, STYLE_LASER)
STYLE_KALEIDOSTROBE = "kaleidostrobe"
STYLES = (STYLE_BARS, STYLE_RADIAL, STYLE_LASER, STYLE_KALEIDOSTROBE)
BANDS = 20
STEPS = 20 # vertical granularity per bar
@@ -995,4 +998,7 @@ def make_renderer(style: str, config=None):
return RadialRenderer(config)
if style == STYLE_LASER:
return LaserRenderer(config)
if style == STYLE_KALEIDOSTROBE:
from lintunes.gui.visualizer_kaleido import KaleidostrobeRenderer
return KaleidostrobeRenderer(config)
return BarsRenderer(config)
+2
View File
@@ -0,0 +1,2 @@
"""Kaleidostrobe, the 2002 iTunes visualizer by Shehryar Lasi, ported from
its PowerPC binary. See ``engine`` for the simulation."""
+706
View File
@@ -0,0 +1,706 @@
"""Kaleidostrobe's per-frame simulation, ported from the PowerPC original.
Every function here is a translation of the routine named in its docstring
(the bundle kept its symbols). Where the original rounded to single
precision, ``f32`` does too; where it used a fused multiply-add, so does
``math.fma``: an index that lands on ``x.5`` decides a palette entry, so the
rounding has to be the original's, not merely close to it.
The engine is Qt-free. ``step()`` advances one frame and returns what the
original handed OpenGL: two 128×128 RGBA textures and, per layer, the
triangles to draw (object-space vertices, texture coordinates, and the
modelview that places them). ``visualizer_kaleido`` paints that.
"""
import math
import struct
from dataclasses import dataclass, field
from importlib import resources
import numpy as np
SIZE = 128 # the index images and textures are 128×128
TICKS_PER_S = 60 # Mac OS TickCount()
FRAME_US = 40_000 # 'vrnd' renders only after more than 39,999 µs
FOVY = 36.8698976458 # reshape(): gluPerspective(fovy, w/h, 5, 25)
EYE_Z = 15.0 # display(): gluLookAt(0,0,15, 0,0,0, 0,1,0)
NEAR, FAR = 5.0, 25.0
FAR_HALF_HEIGHT = 5.0 # gFarHalfHeight
ROTATION_STEPS = 1080 # rotation = (rotation + 1) % 1080, drawn /3
# Function tables, as the plugin's arrays name them (InitGL picks with
# rand() % len, DrawGL with newValue(…, len)).
MAP_TABLE = (0, 1, 2, 3, 21, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 0, 1, 3, 4, 20, 6, 7, 9, 10, 11, 12, 15, 17, 18, 19,
21)
WAVE_TABLE = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 31, 32, 33, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 31, 32, 33)
DELTA_TABLE = (0, 1, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18)
POLAR_WAVES = {31: 3, 32: 12, 33: 16} # initWaveShape03x: base, polar, transform
# ProcessRenderData's starting state (VisualPluginHandler 'show'/'vply').
BAND_PEAK_START = ((1225.0, 484.0, 900.0, 32761.0),
(1089.0, 441.0, 576.0, 24964.0))
MIN_MAX_BAND_POWER = (1157.0, 462.5, 738.0, 28862.5)
BASS_MAX_FLOOR = 12.788898
MID_MAX_FLOOR = 7.219702
TREBLE_MAX_FLOOR = 1.702842
PEAK_DECAY = 0.99383029715
# lowpass biquad shared by the three bands: b0, b1, b2, a1, a2
LP_B0, LP_B1, LP_A1, LP_A2 = 0.0023, 0.0045, 1.8614, 0.8704
BEAT_PERIOD_START = 45.0 # ticks, i.e. 80 BPM
def f32(x):
"""Round to single precision, as frsp / a float store did."""
return struct.unpack('f', struct.pack('f', x))[0]
def cmod(a, m):
"""C's %, which keeps the sign of the dividend."""
return np.fmod(a, m)
class ParkMiller:
"""Darwin 6 libc rand() (FreeBSD's Park–Miller): RAND_MAX 0x7fffffff."""
def __init__(self, seed=1):
self.x = seed & 0xffffffff
def rand(self) -> int:
x = self.x
if x == 0:
x = 123459876
hi, lo = divmod(x, 127773)
x = 16807 * lo - 2836 * hi
if x < 0:
x += 0x7fffffff
self.x = x
return x % 0x80000000
_RAND_SCALE = f32(4.656612873077393e-10) # 1 / 2^31, as the float it was
def _unit(rng) -> float:
return f32(f32(float(rng.rand())) * _RAND_SCALE)
# --------------------------------------------------------------------------
# Tables: extracted by running the original makeMap / initWaveShape code
# --------------------------------------------------------------------------
_TABLES = None
def tables():
global _TABLES
if _TABLES is None:
with resources.files(__package__).joinpath("tables.npz").open("rb") as f:
data = np.load(f)
_TABLES = {k: data[k] for k in data.files}
return _TABLES
def _norm_coord() -> np.ndarray:
"""initGlobals: normCoord[i] = i/127·2 − 1, in single precision."""
out = np.empty(SIZE, np.float32)
for i in range(SIZE):
q = f32(f32(float(i)) / f32(127.0))
out[i] = f32((q + q) + -1.0)
return out
def _polar_tables(nc):
"""initGlobals: radius = √(x² + y²) and theta = atan2(y, x) + π."""
radius = np.empty((SIZE, SIZE), np.float32)
theta = np.empty((SIZE, SIZE), np.float32)
for y in range(SIZE):
ny = float(nc[y])
for x in range(SIZE):
nx = float(nc[x])
radius[y, x] = f32(math.sqrt(f32(ny * ny + f32(nx * nx))))
if ny != 0.0 and nx != 0.0:
theta[y, x] = f32(math.atan2(ny, nx) + 3.1415926)
elif ny == 0.0:
theta[y, x] = 0.0 if nx >= 0.0 else f32(3.141592502593994)
else:
theta[y, x] = f32(1.570796251296997) if ny > 0.0 \
else f32(4.71238899230957)
return radius, theta
def _cos_index(nc):
"""The fishbowl remap of calcDelta014/016/017: int(cos(nc·π/2)·127 + ½)."""
return np.array([int(math.fma(math.cos(float(v) * 3.141592 * 0.5), 127.0, 0.5))
for v in nc], np.int64)
class _Geometry:
"""Per-process constants derived from initGlobals."""
def __init__(self):
nc = self.nc = _norm_coord()
self.radius, self.theta = _polar_tables(nc)
self.cos127 = _cos_index(nc)
c18 = np.empty(SIZE, np.int64)
for i in range(SIZE):
v = float(nc[i])
c = math.cos(v * 3.141592 * 0.5)
c18[i] = int(math.fma(c, 64.0, 0.5)) if v <= 0.0 \
else int((127.0 - c * 64.0) + 0.5)
self.cos18 = c18
# RectToPolar's sample points: column from the angle, row from the
# distance (both ≥ 0, so fctiwz's truncation is int()).
col = [int(math.fma(float(t) / 6.2831852, 127.0, 0.5))
for t in self.theta.ravel()]
row = [int(math.fma(float(r) / 1.41421356237, 127.0, 0.5))
for r in self.radius.ravel()]
self.polar_col = np.fmod(np.array(col, np.int64), SIZE).reshape(SIZE, SIZE)
self.polar_row = np.fmod(np.array(row, np.int64), SIZE).reshape(SIZE, SIZE)
_GEOMETRY = None
def geometry() -> _Geometry:
global _GEOMETRY
if _GEOMETRY is None:
_GEOMETRY = _Geometry()
return _GEOMETRY
# --------------------------------------------------------------------------
# Index-image operations (in place on one 128×128 uint8 buffer)
# --------------------------------------------------------------------------
def flip_diag(img):
"""flipDiag: a transpose that skips the cells beside the diagonal.
The loop runs x < y − 1 where a transpose wants x < y, so (y, y−1) and
(y−1, y) stay put. It shows as a faint seam along the diagonal; kept."""
for y in range(SIZE):
if y >= 2:
row = img[y, :y - 1].copy()
img[y, :y - 1] = img[:y - 1, y]
img[:y - 1, y] = row
def inside_out(img):
"""insideOut: each half of the image flipped top to bottom."""
img[0:64] = img[0:64][::-1].copy()
img[64:128] = img[64:128][::-1].copy()
def transform(img, rng):
"""transform: none, flipDiag, insideOut or both, at random."""
k = int(math.fma(_unit(rng), 4.999999, 1.0))
if k == 2:
flip_diag(img)
elif k == 3:
inside_out(img)
elif k == 4:
flip_diag(img)
inside_out(img)
elif k == 5:
inside_out(img)
flip_diag(img)
def rect_to_polar(img):
"""RectToPolar: column = angle, row = distance from the centre."""
g = geometry()
img[:] = img[g.polar_row, g.polar_col]
# --------------------------------------------------------------------------
# calcDelta*: buffer 1 = a warp of buffer 0, by each layer's own counter
# --------------------------------------------------------------------------
_Y, _X = np.mgrid[0:SIZE, 0:SIZE]
def _block_average(src, rows, s):
"""calcDelta005/011: 32-wide horizontal averages of a shifted image."""
out = np.empty((len(rows), SIZE), np.uint8)
for i, y in enumerate(rows):
line = src[(y + s) % SIZE]
for blk in range(0, SIZE, 32):
cols = (blk + s + np.arange(32)) % SIZE
out[i, blk:blk + 32] = int(int(line[cols].astype(np.int64).sum()) * 0.03125)
return out
def delta(n, src, state):
"""calcDelta<n>: returns the warped image; advances ``state`` (a dict of
that function's static counters for this layer)."""
S = SIZE
Y, X = _Y, _X
if n == 0:
s = state.get('h', 0)
out = src[Y, (X + s) % S]
state['h'] = s + 1
elif n == 1:
h, v = state.get('h', 0), state.get('v', 0)
out = src[(Y + v) % S, (X + h) % S]
state['h'], state['v'] = h + 1, v + 1
elif n == 3:
s = state.get('s', 0)
out = np.where(X < 64, src[Y, (X + s) % 64], src[Y, ((X - s) % 64) + 64])
state['s'] = (s + 1) % 64
elif n == 4:
s = state.get('s', 0)
q = src[(Y[:64, :64] + s) % 64, (X[:64, :64] + s) % 64]
out = np.empty((S, S), np.uint8)
out[:64, :64] = q
out[64:, :64] = q[::-1]
out[64:, 64:] = q[::-1, ::-1]
out[:64, 64:] = q[:, ::-1]
state['s'] = (s + 1) % 64
elif n == 5:
s = state.get('s', 0)
out = _block_average(src, range(S), s)
state['s'] = (s + 1) % S
elif n == 6:
s = state.get('s', 0)
out = np.empty((S, S), np.uint8)
full = src[(Y + s) % S, (X + s) % S]
y, x = np.nonzero(X[:64, :64] <= Y[:64, :64])
v = full[y, x]
for yy, xx in ((y, x), (y, 127 - x), (127 - y, x), (127 - y, 127 - x),
(x, y), (x, 127 - y), (127 - x, y), (127 - x, 127 - y)):
out[yy, xx] = v
state['s'] = (s + 1) % S
elif n == 8:
s = state.get('s', 0)
out = src[(Y + s) % S, X]
state['s'] = s + 1
elif n == 9:
s = state.get('s', 0)
row = (Y + s) % S
out = np.where(X < 32, src[row, (63 - X) % S],
np.where(X >= 96, src[row, (191 - X) % S], src))
state['s'] = s + 1
elif n == 10:
s = state.get('s', 0)
out = np.where(Y < 64, src[Y, (X + s) % S], src)
state['s'] = s + 1
elif n == 11:
s = state.get('s', 0)
out = np.empty((S, S), np.uint8)
out[:64] = _block_average(src, range(64), s)
out[64:] = src[(Y[64:] + s) % S, (X[64:] + s) % S]
state['s'] = (s + 1) % S
elif n == 12:
s = state.get('s', 0)
row, col = (Y + s) % S, (X + s) % S
out = src[row, col].copy()
top = src[row[:64, :64], 127 - col[:64, :64]]
out[:64, :64] = top
out[:64, 64:] = src[row[:64, :64], col[:64, :64]][:, ::-1]
state['s'] = s + 1
elif n == 13:
s = state.get('s', 0)
direct = src[(Y + s) % S, (X + s) % S]
swapped = src[(X + s) % S, (Y + s) % S]
out = np.where(Y + X >= 127, direct, swapped)
state['s'] = s + 1
elif n == 14:
s = state.get('s', 0)
c = geometry().cos127
out = src[(c[Y] + s) % S, (c[X] + s) % S]
state['s'] = s + 1
elif n == 16:
s = state.get('s', 0)
c = geometry().cos127
out = src[(c[Y] + s) % S, c[X]]
state['s'] = s + 1
elif n == 17:
s = state.get('s', 0)
c = geometry().cos127
out = src[(Y + s) % S, (c[X] + s) % S]
state['s'] = s + 1
elif n == 18:
s = state.get('s', 0)
c = geometry().cos18
out = src[(Y + s) % S, (c[X] + s) % S]
state['s'] = s + 1
else:
raise ValueError(f"calcDelta{n:03d} is not in the plugin's table")
return np.ascontiguousarray(out, np.uint8)
# --------------------------------------------------------------------------
# The plugin
# --------------------------------------------------------------------------
@dataclass
class Triangle:
st: tuple # ((s, t), …) × 3, texture coordinates
xyz: tuple # ((x, y, z), …) × 3, object space
turn: float # degrees about z applied after the layer's own turn
@dataclass
class Layer:
texture: int # 0 = bottom, 1 = top
alpha: float # glColor4f alpha (MODULATE with an opaque texture)
lift: float # glTranslatef(0, 0, lift)
turn: float # glRotatef(turn, 0, 0, 1)
triangles: list = field(default_factory=list)
@dataclass
class FrameOut:
textures: np.ndarray # (2, 128, 128, 4) uint8 RGBA
layers: list # [bottom Layer, top Layer]
beat: bool
class Kaleidostrobe:
"""One instance of the plugin: 'init' + 'show' + 'vply', then a
``step()`` per 'vrnd' the plugin accepted."""
def __init__(self, seed: int, ticks: int):
self.rng = ParkMiller(seed) # srand(TickCount())
self.width, self.height = 640, 480
t = tables()
self.maps = t['maps']
self.waves = t['waves']
self.wave_inc = t['wave_inc']
# ProcessRenderData state
self.band_peak = [list(map(f32, row)) for row in BAND_PEAK_START]
self.bass_max = f32(BASS_MAX_FLOOR)
self.mid_max = f32(MID_MAX_FLOOR)
self.treble_max = f32(TREBLE_MAX_FLOOR)
self.hold = 0.0
self.xn1 = self.xn2 = self.yn1 = self.yn2 = 0.0
self.lp = {b: [0.0, 0.0, 0.0, 0.0] for b in ('bass', 'mid', 'treble')}
self.signal = self.avg_signal = 0.0
self.bass = self.mid = self.treble = 0.0
# checkBeat
self.prev_signal = 0.0
self.prev_run_avg = 0.0
self.max_run_avg = f32(0.35)
self.beat_periods = [BEAT_PERIOD_START] * 16
self.next_cell = 0
self.beat = False
self.beat_count = 0
self.period_avg = BEAT_PERIOD_START
self.now = ticks
self.prev_tick = ticks - 1
self.last_beat = ticks - 46
self.start_tick = ticks
self.frame_count = 0
self.ticks_per_frame = 1.0
# DrawGL / display / updateTexture state
self.rotation = 0
self.top_object = self.bottom_object = -1
self.flip = [0, 0, 0]
self.index_offset = [0.0, 0.0]
self.cur_map = [0, 0]
self.cur_wave = [0, 0]
self.cur_delta = [0, 0]
self.buffers = np.zeros((2, 2, SIZE, SIZE), np.uint8)
self.palettes = np.zeros((2, 256, 4), np.uint8)
self.wave_scale = [0.0, 0.0]
# each calcDelta function's own static counters, per layer: a warp
# chosen again resumes where it left off, a new one starts at 0
self.delta_state = [dict(), dict()]
self.textures = np.zeros((2, SIZE, SIZE, 4), np.uint8)
self._init_gl()
# ---- InitGL ----
def _init_gl(self):
for tex in (0, 1):
self.cur_map[tex] = self.rng.rand() % len(MAP_TABLE)
self.cur_wave[tex] = self.rng.rand() % len(WAVE_TABLE)
self.cur_delta[tex] = self.rng.rand() % len(DELTA_TABLE)
self._make_map(tex)
self._init_wave(tex)
def _make_map(self, tex):
self.palettes[tex] = self.maps[MAP_TABLE[self.cur_map[tex]]]
def _init_wave(self, tex):
"""initWaveShape<n> into buffer 0 (currFrameIndex is set to 0 first)."""
n = WAVE_TABLE[self.cur_wave[tex]]
img = self.buffers[tex, 0]
base = POLAR_WAVES.get(n, n)
img[:] = self.waves[base]
transform(img, self.rng)
self.wave_scale[tex] = float(self.wave_inc[base])
if n in POLAR_WAVES:
rect_to_polar(img)
# RectToPolar also leaves its result in the other buffer, which
# calcDelta overwrites before anything reads it.
self.buffers[tex, 1] = img
transform(img, self.rng)
def set_size(self, width: int, height: int):
self.width, self.height = max(1, int(width)), max(1, int(height))
@property
def far_half_width(self) -> float:
"""reshape: the rim reaches the screen's corners."""
t = f32(FAR_HALF_HEIGHT * self.width / self.height)
return f32(math.sqrt(f32(f32(t * t) + f32(t * t))))
# ---- ProcessRenderData ----
def _process(self, spectrum, now):
self.ticks_per_frame = f32(f32(float((now - self.start_tick) & 0xffffffff))
/ f32(float(self.frame_count)))
self.now = now
if spectrum is None:
return
nch = len(spectrum)
mins = [0xff, 0xff]
for ch in range(nch):
mins[ch] = int(spectrum[ch][:256].min())
floor = f32(float(mins[0] if mins[0] < mins[1] else mins[1]))
norm = [[0.0] * 4 for _ in range(nch)]
for ch in range(nch):
for b in range(4):
v = f32(float(int(spectrum[ch][b]) ** 2 - mins[ch] ** 2))
if v > self.band_peak[ch][b]:
self.band_peak[ch][b] = v
p = self.band_peak[ch][b]
norm[ch][b] = f32(v / p) if p > 0.0 else 0.0
signal = 0.0
bass = mid = treble = 0.0
for ch in range(nch):
for b in range(4):
signal = f32(signal + norm[ch][b])
p = f32(self.band_peak[ch][b] * PEAK_DECAY)
self.band_peak[ch][b] = MIN_MAX_BAND_POWER[b] \
if p < MIN_MAX_BAND_POWER[b] else p
row = spectrum[ch]
for i in range(0, 32):
bass = f32(bass + float(row[i]))
for i in range(32, 176):
mid = f32(mid + float(row[i]))
for i in range(176, 256):
treble = f32(treble + float(row[i]))
signal = f32(signal / f32(float(nch * 4)))
if signal > self.hold:
self.hold = signal
else:
signal = self.hold
self.signal = signal
dt = float((now - self.prev_tick) & 0xffffffff)
self.hold = f32(self.hold - dt * 0.04444444)
if self.hold < 0.0:
self.hold = 0.0
avg = math.fma(signal, 0.5, self.xn1 * 0.5)
avg = avg + f32(self.xn2 * 0.0) + f32(self.yn1 * 0.0) - f32(self.yn2 * 0.0)
self.avg_signal = f32(avg)
self.yn2, self.xn2 = self.yn1, self.xn1
self.yn1, self.xn1 = self.avg_signal, signal
n = f32(float(nch))
self.bass, self.bass_max = self._band(
'bass', f32(f32(bass / (n * 32.0)) - floor), self.bass_max,
BASS_MAX_FLOOR, f32(12.788898468017578))
self.mid, self.mid_max = self._band(
'mid', f32(f32(mid / (n * 144.0)) - floor), self.mid_max,
MID_MAX_FLOOR, f32(7.219701766967773))
self.treble, self.treble_max = self._band(
'treble', f32(f32(treble / (n * 80.0)) - floor), self.treble_max,
TREBLE_MAX_FLOOR, f32(1.7028419971466064), clamp=True)
self._check_beat(now)
self.prev_tick = now
def _band(self, name, x, peak, floor_d, floor_f, clamp=False):
st = self.lp[name] # x1, x2, y1, y2
y = math.fma(x, LP_B0, st[0] * LP_B1)
y = math.fma(st[1], LP_B0, y)
y = math.fma(st[2], LP_A1, y)
y = f32(y - st[3] * LP_A2)
if y > peak:
peak = y
st[3], st[1] = st[2], st[0]
st[2], st[0] = y, x
level = f32(y / peak)
if clamp and level < 0.0:
level = 0.0
peak = f32(peak * PEAK_DECAY)
if peak < floor_d:
peak = floor_f
return level, peak
def _check_beat(self, now):
"""checkBeat: a rise in the bass-bin signal well above its recent
best, at least 16 ticks after the last beat."""
rav = f32(math.fma(self.prev_run_avg, 0.25,
f32(self.signal - self.prev_signal) * 0.75))
if rav > self.max_run_avg:
self.max_run_avg = rav
beat = rav > self.max_run_avg * 0.6
self.prev_signal = self.signal
self.prev_run_avg = rav
self.max_run_avg = f32(self.max_run_avg * PEAK_DECAY)
if self.max_run_avg < 0.35:
self.max_run_avg = f32(0.35)
since = (now - self.last_beat) & 0xffffffff
if beat and since > 15:
self.beat_count += 1
self.beat_periods[self.next_cell] = f32(float(since))
self.next_cell = (self.next_cell + 1) % 16
total = 0.0
for p in self.beat_periods:
total = f32(total + p)
self.period_avg = f32(total * 0.0625)
self.last_beat = now
self.beat = True
else:
self.beat = False
# ---- updateTexture ----
def _update_textures(self):
level = f32((f32(f32(self.bass + self.mid) + self.treble)) / 2.625 + 0.075)
if level < 0.0:
level = 0.0
lv = np.float32(level)
for tex in (0, 1):
if self.beat and (self.beat_count & 7) == 0:
self.index_offset[tex] = 0.0
n = DELTA_TABLE[self.cur_delta[tex]]
self.buffers[tex, 1] = delta(n, self.buffers[tex, 0],
self.delta_state[tex].setdefault(n, {}))
idx = self.buffers[tex, 1].astype(np.float32)
a = np.trunc((idx + np.float32(self.index_offset[tex])).astype(np.float64)
+ 0.5).astype(np.int64)
a = cmod(a, 256)
b = np.trunc((a.astype(np.float32) * lv).astype(np.float64)
+ 0.5).astype(np.int64)
b = cmod(b, 256)
self.textures[tex] = self.palettes[tex][b]
k = f32(48.0 / self.period_avg)
k = f32(k * k)
step = k * (level * 2.625 / 2.25) * self.wave_scale[tex]
tpf = self.ticks_per_frame / 1.825405
self.index_offset[tex] = f32(self.index_offset[tex]
+ math.fma(step, tpf, tpf))
# ---- display ----
def _pick_object(self) -> int:
return int(math.fma(_unit(self.rng), 17.999999, 1.0)) - 1
def _display(self) -> list:
height = f32(math.fma(self.mid, 0.5, 2.0))
if height < 2.0:
height = f32(2.0)
depth = f32(math.pow(self.avg_signal, 1.25)) if self.avg_signal >= 0 \
else float('nan')
if (self.beat and ((self.beat_count + 16) & 31) == 0) or self.bottom_object < 0:
self.bottom_object = self._pick_object()
if (self.beat and ((self.beat_count + 48) & 31) == 0) or self.top_object < 0:
self.top_object = self._pick_object()
spin = f32(self.rotation / 3.0)
bottom = Layer(0, 1.0, 0.0, spin, self._object(
self.bottom_object, f32(height / 1.5), f32(math.fma(depth, 10.0, -10.0))))
top = Layer(1, 0.5, 5.0, f32(-self.rotation / 3.0), self._object(
self.top_object, height, f32(depth * 5.0)))
self.rotation = (self.rotation + 1) % ROTATION_STEPS
return [bottom, top]
def _object(self, k, h, z):
if k == 0:
return self._draw8(h, z)
if k in (1, 2):
return self._draw12(h, z)
if k in (3, 4):
n = 6
elif k == 5:
n = 10
elif k <= 16:
n = 2 * k - 6
else:
n = 30
return self._draw_n(h, z, n)
def _draw_n(self, h, z, n):
"""drawNTriangles: n/2 mirrored pairs, each pair turned 720/n°."""
fhw = self.far_half_width
t = f32(math.tan((math.pi + math.pi) / n))
hx = f32(h * t)
half = f32(fhw * t)
tv = f32(h * 0.866)
ts = f32((hx + hx) * 0.866)
step = f32(720.0 / n)
tris = []
for i in range(n // 2):
turn = step * i
tris.append(Triangle(((0.0, tv), (-ts, -tv), (0.0, -tv)),
((0.0, 0.0, z), (-half, -fhw, 0.0), (0.0, -fhw, 0.0)), turn))
tris.append(Triangle(((0.0, tv), (0.0, -tv), (-ts, -tv)),
((0.0, 0.0, z), (0.0, -fhw, 0.0), (half, -fhw, 0.0)), turn))
return tris
def _draw12(self, h, z):
"""draw12Triangles: six mirrored pairs, 60° apart."""
fhw = self.far_half_width
wide = f32(fhw / 0.866)
tv = f32(h * 0.866)
tn = f32(-h * 0.866)
left = f32(-wide * 0.5)
right = f32(wide * 0.5)
tris = []
for i in range(6):
turn = 60.0 * i
tris.append(Triangle(((0.0, tv), (-h, tn), (0.0, tn)),
((0.0, 0.0, z), (left, -fhw, 0.0), (0.0, -fhw, 0.0)), turn))
tris.append(Triangle(((0.0, tv), (0.0, tn), (-h, tn)),
((0.0, 0.0, z), (0.0, -fhw, 0.0), (right, -fhw, 0.0)), turn))
return tris
def _draw8(self, h, z):
"""draw8Triangles: a square pyramid as one triangle fan."""
f = self.far_half_width
rim = ((-f, f), (-f, 0.0), (-f, -f), (0.0, -f), (f, -f), (f, 0.0),
(f, f), (0.0, f), (-f, f))
st = ((-h, h), (-h, -h))
tris = []
for i in range(8):
a, b = rim[i], rim[i + 1]
tris.append(Triangle(((h, -h), st[i % 2], st[(i + 1) % 2]),
((0.0, 0.0, z), (a[0], a[1], 0.0), (b[0], b[1], 0.0)), 0.0))
return tris
# ---- DrawGL ----
def _new_value(self, cur, n) -> int:
while True:
v = int(math.fma(_unit(self.rng), n - 1e-06, 1.0)) - 1
if v != cur:
return v
def _switch(self):
"""After a beat: every 8th swaps a layer's warp, 16th its colours,
32nd its pattern — alternating layers each time."""
if not self.beat:
return
c = self.beat_count
if (c & 0x1f) == 0:
tex = self.flip[0]
self.cur_wave[tex] = self._new_value(self.cur_wave[tex], 50.0)
self._init_wave(tex)
self.flip[0] = int(tex == 0)
elif (c & 0xf) == 0:
tex = self.flip[1]
self.cur_map[tex] = self._new_value(self.cur_map[tex], 37.0)
self._make_map(tex)
self.flip[1] = int(tex == 0)
elif (c & 7) == 0:
tex = self.flip[2]
self.cur_delta[tex] = self._new_value(self.cur_delta[tex], 16.0)
self.flip[2] = int(tex == 0)
def step(self, spectrum, ticks: int) -> FrameOut:
"""One accepted 'vrnd': ``spectrum`` is iTunes' 2×512 uint8 array
(or None for no data); ``ticks`` is TickCount() now."""
self.frame_count += 1
self._process(spectrum, ticks)
self._update_textures()
layers = self._display()
self._switch()
return FrameOut(self.textures.copy(), layers, self.beat)
Binary file not shown.
+1 -1
View File
@@ -14,7 +14,7 @@ DEFAULTS = {
"volume": 0.8, # logical 0..1 master output volume
"normalize_volume": False, # play every song at one loudness (loudness.py)
"visualizer_mode": "on", # on (color) | dim (gray) | off — click cycle
"visualizer_style": "bars", # bars | radial | laser (visualizer_styles)
"visualizer_style": "bars", # bars | radial | laser | kaleidostrobe
# The styles' tunables — ranges in visualizer_styles.LIMITS.
# Fade times in seconds, 0 = off: how long what a bar or dot left
# behind, or the laser's past sweeps, take to fade into the background.