diff --git a/CLAUDE.md b/CLAUDE.md index 5d34f09..ec5ec3c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -412,6 +412,19 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal `tests/kaleidostrobe_golden.npz` was recorded from the emulated original and `test_round84` holds the port to it byte for byte. +- **`gui/visualizer_lint.py`** — Lint Oontz, the fifth style (Round 122, + `lint`): three line-drawn lint balls in big headphones (gray, the wheel's + colour, black) on the panel's gray. **Stop motion**: the renderer steps + at 8 fps on its own clock and `advance` is True only on a step; every + step re-rolls each line's wobble (seeded by step, so one step always + draws the same) and nothing is ever tweened. A bass onset (energy + `ONSET_RATIO` over its own average) dips the head and bends the knees; + the arms dance only when the onset tempo is ≥ `BUSY_BPM` *and* the + spectrum is full (`BUSY_FULLNESS`, calibrated on pink noise vs. sparse + tones), otherwise they hang. `SLEEP_AFTER_S` of quiet (or `clear()`, + i.e. stopped) lays them down with z's. No settings yet (no + `STYLE_KEYS` entry), only its sync delay. + - **`lintunes/dj/`** + **`gui/dj_shelf.py`** — DJ mode (Round 93; View › DJ Mode or the turntable button under BPM). The window parts **under the row of transport boxes** (`TransportBar.insert_shelf`: the Library button's diff --git a/lintunes/__init__.py b/lintunes/__init__.py index 302fd27..ecadbaf 100644 --- a/lintunes/__init__.py +++ b/lintunes/__init__.py @@ -1,3 +1,3 @@ """LinTunes — iTunes-style music library manager and player for Linux.""" -__version__ = "0.87.1" +__version__ = "0.88.0" diff --git a/lintunes/gui/preferences_dialog.py b/lintunes/gui/preferences_dialog.py index b78067a..7907ac9 100644 --- a/lintunes/gui/preferences_dialog.py +++ b/lintunes/gui/preferences_dialog.py @@ -871,6 +871,18 @@ class PreferencesDialog(QDialog): form.addRow(about) self._viz_pages.addWidget(kaleido) + lint = QWidget() + form = self._viz_form(lint) + self._sync_delay_slider(form, "lint") + about = QLabel( + "Three balls of lint in headphones: they bob to the bass, dance " + "when the music is fast and full, and fall asleep when it goes " + "quiet. No settings yet.") + about.setWordWrap(True) + about.setEnabled(False) + form.addRow(about) + self._viz_pages.addWidget(lint) + self._viz_pages.setCurrentIndex(list(_VISUALIZER_STYLES).index(current)) self._fit_viz_pages() column.addWidget(self._viz_pages) diff --git a/lintunes/gui/visualizer_lint.py b/lintunes/gui/visualizer_lint.py new file mode 100644 index 0000000..b15bbaf --- /dev/null +++ b/lintunes/gui/visualizer_lint.py @@ -0,0 +1,344 @@ +"""Lint Oontz: three balls of lint in headphones, dancing (Round 122). + +A very rough line drawing, animated like stop motion: the renderer steps at +``FPS`` (8) on its own clock and each step is a new pose with every line +re-wobbled, never an in-between — no tweening. Each step costs one repaint; +the widget's 60 Hz timer only feeds it audio. + +What the music does to them: + +- **bass** → the head bob. A bass onset (energy well over its own recent + average) dips the ball and bends the knees; between beats it springs back. +- **busy** → the arms. When the beats come fast (``BUSY_BPM`` or more, + counted from the onsets themselves) *and* the spectrum is full + (``BUSY_FULLNESS``), every beat throws a new arm pose and the feet step. + Otherwise the arms hang and only the head bobs. +- **quiet** for ``SLEEP_AFTER_S`` → they lie down and sleep (closed eyes, + rising z's) until the music comes back. Stopped/paused (``clear``) is + asleep too. + +Three of them, on the panel's gray: one in gray lines, one in the highlight +colour (the colour the wheel picks — in gray mode that is the gray too) and +one in black. Each has its own fuzz and is a beat out of step with the +others' arm poses, so they don't move as one. +""" +import math + +import numpy as np + +from PyQt6.QtCore import QPointF, QRectF, Qt +from PyQt6.QtGui import QColor, QPainterPath, QPen + +STYLE = "lint" +FPS = 8 # stop motion: a new drawing this often +STEP_S = 1.0 / FPS +INSET = 3 + +BASS_HZ = (40.0, 160.0) +FFT = 2048 +ONSET_RATIO = 1.45 # bass this far over its average is a beat +ONSET_GAP_S = 0.26 # no two beats closer than this (~230 BPM) +AVERAGE_S = 0.6 # how long the bass average remembers +TEMPO_WINDOW_S = 5.0 # beats counted over this long for the tempo +BUSY_BPM = 108 +BUSY_FULLNESS = 0.28 # mean band level (0..1) of a "full" spectrum: + # pink noise at -20 dB RMS reads 0.31, a sparse + # mix of a few tones 0.12-0.14 +CALM_AFTER_S = 2.0 # busy has to be gone this long to stop dancing +QUIET_DB = -48.0 # RMS under this is quiet +SLEEP_AFTER_S = 4.0 +WAKE_AFTER_S = 0.3 +FULLNESS_BANDS = 16 + +# Arm poses as (left, right) shoulder angles in degrees from straight down, +# outward positive, plus each elbow's extra bend. +HANG = ((18, 8), (18, 8)) +LYING = ((4, 0), (4, 0)) # asleep: arms along the body +DANCE = ( + ((150, -30), (30, 20)), # left up + ((140, -20), (140, -20)), # both up + ((30, 20), (150, -30)), # right up + ((90, 40), (90, 40)), # both out, bent +) + + +class _Figure: + """One lint ball: its fixed fuzz profile and its own pose.""" + + def __init__(self, index: int): + rng = np.random.default_rng(7919 * (index + 1)) + self.index = index + self.radii = 1.0 + rng.uniform(-0.09, 0.09, 26) + self.hairs = rng.uniform(0, 2 * math.pi, 9) + self.hair_len = rng.uniform(0.12, 0.3, 9) + self.pose = 0 + + +class LintRenderer: + name = STYLE + dimmed = False # set by the widget: gray mode + panel = QColor(200, 200, 200) # set by the widget: the background + + def __init__(self, config=None): + self._figures = [_Figure(i) for i in range(3)] + self._behind = 0.0 + self._clock = 0.0 + self.step = 0 + self._bass_avg = 0.0 + self._last_beat = -1.0 + self._beats = [] + self._beat_pending = False + self.bob = 0.0 + self.fullness = 0.0 + self.busy = False + self._calm_for = 0.0 + self.asleep = True + self._quiet_for = SLEEP_AFTER_S + self._loud_for = 0.0 + self.feet = 0 + + # ---- the renderer contract ---- + + def configure(self, config): + pass # no settings yet + + def clear(self): + """Stopped or paused: they lie down.""" + self.asleep = True + self._quiet_for = SLEEP_AFTER_S + self._loud_for = 0.0 + self.busy = False + self.bob = 0.0 + self._beats.clear() + self.step += 1 + + @property + def tempo(self) -> float: + """Beats per minute, from the onsets heard in the last few seconds.""" + recent = [t for t in self._beats if self._clock - t <= TEMPO_WINDOW_S] + if len(recent) < 3: + return 0.0 + return 60.0 * (len(recent) - 1) / max(1e-6, recent[-1] - recent[0]) + + def advance(self, frame) -> bool: + dt = max(0.0, frame.dt) + self._clock += dt + self._listen(frame, dt) + self._behind = min(self._behind + dt, STEP_S * 2) + if self._behind < STEP_S: + return False + self._behind -= STEP_S + self._pose() + return True + + # ---- listening (every tick) ---- + + def _listen(self, frame, dt): + pending = frame.pending if len(frame.pending) else frame.samples[-512:] + rms = float(np.sqrt(np.mean(np.square(pending, dtype=np.float64)))) + db = 20 * math.log10(rms + 1e-10) + if db < QUIET_DB: + self._quiet_for += dt + self._loud_for = 0.0 + else: + self._loud_for += dt + self._quiet_for = 0.0 + if self.asleep and self._loud_for >= WAKE_AFTER_S: + self.asleep = False + elif not self.asleep and self._quiet_for >= SLEEP_AFTER_S: + self.asleep = True + + from lintunes.gui.visualizer_styles import ( + band_edges, band_levels, spectrum_of) + spectrum, freqs = spectrum_of(frame.samples, FFT, frame.rate) + lo, hi = np.searchsorted(freqs, BASS_HZ) + bass = float(np.sum(np.square(spectrum[lo:hi]))) + keep = math.exp(-dt / AVERAGE_S) if dt > 0 else 1.0 + if (db >= QUIET_DB and bass > ONSET_RATIO * self._bass_avg + and bass > 1e-5 + and self._clock - self._last_beat >= ONSET_GAP_S): + self._last_beat = self._clock + self._beats.append(self._clock) + self._beat_pending = True + self._beats = [t for t in self._beats + if self._clock - t <= TEMPO_WINDOW_S] + self._bass_avg = keep * self._bass_avg + (1 - keep) * bass + levels = band_levels(spectrum, freqs, + band_edges(FULLNESS_BANDS, frame.rate)) + self.fullness = keep * self.fullness + (1 - keep) * float(levels.mean()) + + wants = self.tempo >= BUSY_BPM and self.fullness >= BUSY_FULLNESS + if wants: + self.busy = True + self._calm_for = 0.0 + elif self.busy: + self._calm_for += dt + if self._calm_for >= CALM_AFTER_S: + self.busy = False + + # ---- posing (every stop-motion step) ---- + + def _pose(self): + self.step += 1 + if self.asleep: + self.bob = 0.0 + return + if self._beat_pending: + self._beat_pending = False + self.bob = 1.0 + if self.busy: + self.feet ^= 1 + for f in self._figures: + f.pose = (f.pose + 1) % len(DANCE) + else: + self.bob = 0.35 if self.bob >= 1.0 else 0.0 + + # ---- drawing ---- + + def colors(self, color: QColor): + panel = QColor(self.panel) + gray = panel.darker(165) + black = QColor(0, 0, 0) + if self.dimmed: + return [panel.darker(135), QColor(color), panel.darker(230)] + return [gray, QColor(color), black] + + def paint(self, painter, rect, color: QColor, gray: QColor = None): + area = QRectF(rect).adjusted(INSET, INSET, -INSET, -INSET) + if area.width() < 6 or area.height() < 6: + return + cell_w = area.width() / 3 + painter.save() + painter.setRenderHint(painter.RenderHint.Antialiasing) + for fig, ink in zip(self._figures, self.colors(color)): + cell = QRectF(area.x() + fig.index * cell_w, area.y(), + cell_w, area.height()) + self._paint_figure(painter, cell, fig, ink) + painter.restore() + + def _paint_figure(self, painter, cell, fig, ink): + # The ball's radius: room for headphones either side and legs below, + # or (asleep) lying full length. + r = min(cell.width() / 3.9, cell.height() / 4.2) + if self.asleep: + r = min(r, cell.width() / 4.6, cell.height() / 2.8) + rng = np.random.default_rng(self.step * 31 + fig.index) + wob = max(0.4, r * 0.06) + + def j(x, y): + return QPointF(x + rng.uniform(-wob, wob), y + rng.uniform(-wob, wob)) + + pen = QPen(ink, max(1.0, r * 0.11)) + pen.setCapStyle(Qt.PenCapStyle.RoundCap) + pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) + painter.setPen(pen) + painter.setBrush(Qt.BrushStyle.NoBrush) + + ground = cell.bottom() - pen.widthF() + cx = cell.center().x() + painter.save() + if self.asleep: + # Lying on its back, feet to the right: the standing drawing + # turned a quarter (rotate(-90) sends "down" to "right"). + head = cx - r * 0.75 + painter.translate(head, ground - r * 1.4) + painter.rotate(-90) + self._body(painter, fig, r, 0.0, j, asleep=True) + painter.restore() + self._zzz(painter, head + r * 0.5, ground - r * 3.0, r, fig, j) + return + legs = r * 1.25 + dip = self.bob * r * 0.22 + painter.translate(cx, ground - legs - r + dip) + self._body(painter, fig, r, dip, j, asleep=False) + painter.restore() + + def _body(self, painter, fig, r, dip, j, asleep): + """The figure drawn around its ball's centre (0, 0), feet at +y.""" + # The fuzzy ball: a wobbly ring plus a few loose hairs. + n = len(fig.radii) + ring = QPainterPath() + for i in range(n + 1): + a = 2 * math.pi * (i % n) / n + p = j(math.cos(a) * r * fig.radii[i % n], + math.sin(a) * r * fig.radii[i % n]) + ring.moveTo(p) if i == 0 else ring.lineTo(p) + painter.drawPath(ring) + for a, length in zip(fig.hairs, fig.hair_len): + if abs(math.cos(a)) > 0.8: + continue # where the headphone cups sit + painter.drawLine(j(math.cos(a) * r, math.sin(a) * r), + j(math.cos(a) * r * (1 + length), + math.sin(a) * r * (1 + length))) + + # Face. + eye_y, eye_x = -r * 0.18, r * 0.32 + if asleep: + for s in (-1, 1): + painter.drawLine(j(s * eye_x - r * 0.13, eye_y), + j(s * eye_x + r * 0.13, eye_y)) + painter.drawLine(j(-r * 0.12, r * 0.32), j(r * 0.12, r * 0.32)) + else: + dot = max(0.8, r * 0.07) + for s in (-1, 1): + c = j(s * eye_x, eye_y) + painter.drawEllipse(c, dot, dot) + smile = QPainterPath(j(-r * 0.3, r * 0.22)) + depth = r * (0.5 if self.busy else 0.32) + smile.quadTo(j(0, r * 0.22 + depth), j(r * 0.3, r * 0.22)) + painter.drawPath(smile) + + # Big headphones: a band over the top, a cup over each side. + band = QPainterPath(j(-r * 1.12, -r * 0.1)) + band.cubicTo(j(-r * 1.25, -r * 1.75), j(r * 1.25, -r * 1.75), + j(r * 1.12, -r * 0.1)) + painter.drawPath(band) + for s in (-1, 1): + c = j(s * r * 1.08, 0) + painter.drawEllipse(c, r * 0.24, r * 0.42) + + # Arms from the shoulders, two sticks each. + if asleep: + pose = LYING + elif self.busy: + pose = DANCE[(fig.pose + fig.index) % len(DANCE)] + else: + pose = HANG + upper, lower = r * 0.75, r * 0.6 + for s, (shoulder, bend) in zip((-1, 1), pose): + if not self.busy and not asleep: + shoulder += 6 * self.bob # a hanging arm swings with the bob + start = (s * r * 0.92, r * 0.3) + a = math.radians(shoulder) + elbow = (start[0] + s * math.sin(a) * upper, + start[1] + math.cos(a) * upper) + b = math.radians(shoulder + bend) + hand = (elbow[0] + s * math.sin(b) * lower, + elbow[1] + math.cos(b) * lower) + painter.drawPolyline([j(*start), j(*elbow), j(*hand)]) + + # Legs: straight, or bent at the knee by the bob; the feet step + # apart when dancing. + legs = r * 1.25 + knee_out = dip * 0.9 + spread = r * (0.5 if (self.busy and self.feet) else 0.35) + for s in (-1, 1): + hip = (s * r * 0.35, r * 0.93) + foot_y = r + legs - dip + out = spread + (r * 0.15 if self.busy and self.feet == (s > 0) else 0) + foot = (s * out, foot_y) + knee = ((hip[0] + foot[0]) / 2 + s * knee_out, + (hip[1] + foot_y) / 2) + painter.drawPolyline([j(*hip), j(*knee), j(*foot), + j(foot[0] + s * r * 0.25, foot_y)]) + + def _zzz(self, painter, x, y, r, fig, j): + """Little z's rising, a new one every few frames.""" + phase = (self.step + fig.index * 3) % 12 + for k in range(3): + age = (phase / 4 + k) % 3 # 0..3, how far it has risen + size = r * (0.18 + 0.08 * age) + zx = x + age * r * 0.3 + zy = y - age * r * 0.4 + painter.drawPolyline([j(zx, zy), j(zx + size, zy), + j(zx, zy + size), j(zx + size, zy + size)]) diff --git a/lintunes/gui/visualizer_styles.py b/lintunes/gui/visualizer_styles.py index 09121cc..fb29a9b 100644 --- a/lintunes/gui/visualizer_styles.py +++ b/lintunes/gui/visualizer_styles.py @@ -13,6 +13,8 @@ audio intake, the timer, on/dim/off, the color. Pure numpy + QPainter. 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. +- ``LintRenderer`` (``visualizer_lint``) — Lint Oontz: three balls of lint + in headphones dancing, as 8 fps stop motion. Every tunable lives in preferences.json under a ``visualizer_*`` key; ``settings(prefs)`` reads them clamped to ``LIMITS``, and a renderer takes @@ -33,12 +35,15 @@ STYLE_BARS = "bars" STYLE_RADIAL = "radial" STYLE_LASER = "laser" STYLE_KALEIDOSTROBE = "kaleidostrobe" -STYLES = (STYLE_BARS, STYLE_RADIAL, STYLE_LASER, STYLE_KALEIDOSTROBE) +STYLE_LINT = "lint" +STYLES = (STYLE_BARS, STYLE_RADIAL, STYLE_LASER, STYLE_KALEIDOSTROBE, + STYLE_LINT) STYLE_NAMES = { STYLE_BARS: "Bars", STYLE_RADIAL: "Radial dots", STYLE_LASER: "Oscilloscope", STYLE_KALEIDOSTROBE: "Kaleidostrobe", + STYLE_LINT: "Lint Oontz", } BANDS = 20 @@ -1018,4 +1023,7 @@ def make_renderer(style: str, config=None): if style == STYLE_KALEIDOSTROBE: from lintunes.gui.visualizer_kaleido import KaleidostrobeRenderer return KaleidostrobeRenderer(config) + if style == STYLE_LINT: + from lintunes.gui.visualizer_lint import LintRenderer + return LintRenderer(config) return BarsRenderer(config) diff --git a/lintunes/preferences.py b/lintunes/preferences.py index 65070c1..c56f216 100644 --- a/lintunes/preferences.py +++ b/lintunes/preferences.py @@ -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 | kaleidostrobe + "visualizer_style": "bars", # bars | radial | laser | kaleidostrobe | lint # 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. diff --git a/tests/test_round122.py b/tests/test_round122.py new file mode 100644 index 0000000..6869ed8 --- /dev/null +++ b/tests/test_round122.py @@ -0,0 +1,114 @@ +"""Round 122: Lint Oontz, the stop-motion lint-ball visualizer.""" +import numpy as np +from PyQt6.QtCore import QRectF +from PyQt6.QtGui import QColor, QImage, QPainter + +from lintunes.gui import visualizer_styles as vs +from lintunes.gui.visualizer_lint import FPS, LintRenderer + +RATE = 44100 + + +def _song(bpm, seconds, full): + rng = np.random.default_rng(3) + t = np.arange(int(seconds * RATE)) / RATE + x = np.sin(2 * np.pi * 55 * t) * np.exp(-(t % (60 / bpm)) * 18) * 0.8 + if full: + x = x + rng.normal(0, 0.12, t.size) + 0.2 * np.sin(2 * np.pi * 440 * t) + else: + x = x + 0.05 * np.sin(2 * np.pi * 330 * t) + return x.astype(np.float32) + + +def _play(r, audio): + hist = np.zeros(vs.HISTORY, np.float32) + n = RATE // 60 + steps = 0 + for i in range(0, len(audio) - n, n): + chunk = audio[i:i + n] + hist = np.concatenate([hist, chunk])[-vs.HISTORY:] + steps += r.advance(vs.Frame(hist, RATE, chunk, 1 / 60)) + return steps + + +def test_registered(): + assert vs.STYLE_LINT in vs.STYLES + assert vs.STYLE_NAMES[vs.STYLE_LINT] == "Lint Oontz" + assert isinstance(vs.make_renderer(vs.STYLE_LINT), LintRenderer) + + +def test_stop_motion_frame_rate(): + r = LintRenderer() + steps = _play(r, _song(100, 3, False)) + assert abs(steps - 3 * FPS) <= 2 # 8 drawings a second, not 60 + + +def test_fast_full_music_dances(): + r = LintRenderer() + _play(r, _song(128, 6, True)) + assert not r.asleep and r.busy + assert 120 <= r.tempo <= 136 + + +def test_slow_sparse_music_only_bobs(): + r = LintRenderer() + _play(r, _song(80, 6, False)) + assert not r.asleep and not r.busy + assert 74 <= r.tempo <= 86 + + +def test_quiet_puts_them_to_sleep_and_music_wakes_them(): + r = LintRenderer() + _play(r, _song(128, 3, True)) + assert not r.asleep + _play(r, np.zeros(RATE * 2, np.float32)) + assert not r.asleep # a short break isn't sleep + _play(r, np.zeros(RATE * 3, np.float32)) + assert r.asleep + _play(r, _song(128, 1, True)) + assert not r.asleep + + +def test_cleared_is_asleep(): + r = LintRenderer() + _play(r, _song(128, 2, True)) + r.clear() + assert r.asleep + + +def test_three_balls_gray_highlight_black(qapp): + r = LintRenderer() + r.panel = QColor(205, 205, 205) + gray, highlight, black = r.colors(QColor(40, 110, 220)) + assert highlight == QColor(40, 110, 220) + assert black == QColor(0, 0, 0) + assert gray.red() == gray.green() == gray.blue() < 205 + for asleep in (False, True): + r.asleep = asleep + for w, h in ((110, 44), (900, 450)): + img = QImage(w, h, QImage.Format.Format_ARGB32) + img.fill(r.panel) + p = QPainter(img) + r.paint(p, QRectF(0, 0, w, h), highlight) + p.end() + blue = sum(img.pixelColor(x, y).blue() - img.pixelColor(x, y).red() > 80 + for x in range(w) for y in range(0, h, 2)) + assert blue > 0 + + +def test_every_frame_wobbles(qapp): + r = LintRenderer() + r.asleep = False + + def draw(): + img = QImage(200, 100, QImage.Format.Format_ARGB32) + img.fill(QColor(205, 205, 205)) + p = QPainter(img) + r.paint(p, QRectF(0, 0, 200, 100), QColor(40, 110, 220)) + p.end() + return img + + first = draw() + assert draw() == first # the same step draws the same + r.step += 1 + assert draw() != first # the next one is re-wobbled diff --git a/tests/test_round86.py b/tests/test_round86.py index 625d6df..a4ed667 100644 --- a/tests/test_round86.py +++ b/tests/test_round86.py @@ -105,7 +105,7 @@ class TestTile: assert seen == list(vs.STYLES[1:]) + [vs.STYLES[0]] _click(vis, up) # bars → the last one assert prefs.get("visualizer_style") == vs.STYLES[-1] - assert isinstance(vis._renderer, KaleidostrobeRenderer) + assert vis._renderer.name == vs.STYLES[-1] assert vis._big is None def test_a_double_click_does_nothing_special(self, qapp, tmp_path):