diff --git a/CLAUDE.md b/CLAUDE.md index 2724688..c88365d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -406,6 +406,22 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal air-horn button (held = longer; `audio.Horn`, synthesised). The transport's visualizer draws the mix in DJ mode (`Mixer.tap` → `VisualizerWidget.set_dj_source/feed_dj`). The sidebar art hides. + **Round 95**: the shelf is laid out at its full height on a body + (`set_layout_height`) and only *revealed* by the opening — the decks + never squeeze. The DJ button is the top row's last box (it swapped with + bpm, which is under it in the header row), so it doesn't move when the + window parts. `dj_shelf.SnapSlider` is every DJ slider with a middle + (tempo, vocals — `VocalSlider`, icons over its ends and middle — + crossfader): a centre line and a snap. Sync is **sticky**: a synced deck + follows the other's tempo every tick (`_follow`), glows and says + "Synced", until its own tempo fader moves; only one deck follows; the + ½×/1×/2× switch re-syncs a synced pair (`sync_ratio` folds any number of + octaves). |◀ per deck. The air horn is a real recording + (`sounds/airhorn.mp3`, CC0, see `sounds/CREDITS.md`): a tap plays the + phrase, holding loops its first blast. The zoomed lanes ease out ×2 + while a deck is paused or held. The sink reopens when the system's + default output changes (`output._Pump`: `audioOutputsChanged`, a device + id check, an error check) — it used to go silent until DJ mode reopened. - **`lintunes/importers/itunes_importer.py`** — parses the iTunes XML plist. Remaps Mac `file:///Volumes/...` paths to the local `--music-root` with diff --git a/lintunes/__init__.py b/lintunes/__init__.py index cfb4d28..2d87f54 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.64.0" +__version__ = "0.65.0" diff --git a/lintunes/dj/analysis.py b/lintunes/dj/analysis.py index bbf4c26..015ea16 100644 --- a/lintunes/dj/analysis.py +++ b/lintunes/dj/analysis.py @@ -134,7 +134,12 @@ def sync_ratio(own_bpm: float, target_bpm: float) -> float: if not own_bpm or not target_bpm: return 1.0 ratio = target_bpm / own_bpm - return min((ratio, ratio * 2, ratio / 2), key=lambda r: abs(np.log2(r))) + # as many octaves as it takes (½× against 2× is two apart) + while ratio > 2 ** 0.5: + ratio /= 2 + while ratio < 2 ** -0.5: + ratio *= 2 + return ratio def sync_speed(own_beat_bpm: float, target_beat_bpm: float, diff --git a/lintunes/dj/audio.py b/lintunes/dj/audio.py index 13c3d5f..b677ffd 100644 --- a/lintunes/dj/audio.py +++ b/lintunes/dj/audio.py @@ -231,39 +231,79 @@ def crossfade_gains(x: float) -> tuple[float, float]: class Horn: - """The rap air horn, synthesised: three detuned, brassy sawtooths a - rough major chord apart, through a soft clip, blaring for as long as - ``on`` is held (15 ms attack, 120 ms tail when let go).""" + """The air horn: a real recording ("Air Horn Hype", CC0 — see + lintunes/sounds/CREDITS.md), the classic BWAAH-bwah-bwah-BWAAAH. + Pressed, it plays from the top; *held*, the first long blast is + stretched for as long as the button stays down (its steady middle, + ``LOOP``, looped with a crossfade so the seam can't be heard); let go, + the rest of the phrase plays out. A tap is simply the whole phrase.""" - FREQS = (369.99, 466.16, 554.37) # F#4, A#4, C#5 - ATTACK, RELEASE = 0.015, 0.12 - LEVEL = 0.32 + LOOP = (0.10, 0.40) # seconds: inside the first blast (0–0.48 s) + CROSSFADE = 0.03 + LEVEL = 1.0 - def __init__(self): + def __init__(self, sample: np.ndarray | None = None): + self.on = False + self._src = None + self._held = None + self._pos = None # None = silent + if sample is not None: + self.set_sample(sample) + + def set_sample(self, sample: np.ndarray): + """``sample``: (frames, 2) int16 or float.""" + src = sample.astype(np.float32) + if sample.dtype == np.int16: + src /= 32768.0 + self._src = src + l0, l1 = (int(t * RATE) for t in self.LOOP) + xf = int(self.CROSSFADE * RATE) + l1 = min(l1, len(src)) + held = src.copy() + if l1 - l0 > 2 * xf and l0 >= xf: + ramp = np.linspace(0, 1, xf, dtype=np.float32)[:, None] + # the loop's last xf frames fade into what comes just before + # its start, so jumping back to l0 continues seamlessly + held[l1 - xf:l1] = src[l1 - xf:l1] * (1 - ramp) + src[l0 - xf:l0] * ramp + self._held = held + self._loop = (l0, l1, xf) + + def press(self): + self.on = True + self._pos = 0 + + def release(self): self.on = False - self._phase = np.zeros(len(self.FREQS)) - self._env = 0.0 def render(self, count: int) -> np.ndarray | None: - if not self.on and self._env <= 1e-4: - self._env = 0.0 + if self._src is None or self._pos is None: return None - t = np.arange(count) / RATE - target = 1.0 if self.on else 0.0 - step = 1.0 / ((self.ATTACK if self.on else self.RELEASE) * RATE) - env = np.clip(self._env + (step if self.on else -step) * np.arange(1, count + 1), - 0.0, 1.0) if target != self._env else np.full(count, self._env) - self._env = float(env[-1]) - wave = np.zeros(count) - for i, f in enumerate(self.FREQS): - for detune in (0.997, 1.0, 1.004): - phase = (self._phase[i] * detune + f * detune * t) % 1.0 - wave += 2.0 * phase - 1.0 - self._phase[i] = (self._phase[i] + f * count / RATE) % 1.0 - # a little flutter, like air through a reed - wave *= 1.0 + 0.08 * np.sin(2 * np.pi * 7.0 * t) - sound = np.tanh(wave / 3.0 * 1.8) * self.LEVEL * env - return np.repeat(sound[:, None].astype(np.float32), CHANNELS, axis=1) + l0, l1, xf = self._loop + out = np.zeros((count, CHANNELS), np.float32) + made = 0 + while made < count: + pos = self._pos + if pos >= len(self._src): + self._pos = None + break + if self.on or l1 - xf <= pos < l1 and pos >= l0: + # held (or finishing the crossfade lap): play the looped + # version, wrapping at the loop's end + take = min(count - made, (l1 - pos) if pos < l1 else len(self._src) - pos) + if pos < l1: + out[made:made + take] = self._held[pos:pos + take] + self._pos = pos + take + if self._pos >= l1 and self.on: + self._pos = l0 + else: + out[made:made + take] = self._src[pos:pos + take] + self._pos = pos + take + else: + take = min(count - made, len(self._src) - pos) + out[made:made + take] = self._src[pos:pos + take] + self._pos = pos + take + made += take + return out * self.LEVEL class Mixer: diff --git a/lintunes/dj/output.py b/lintunes/dj/output.py index b00e06f..be46fdb 100644 --- a/lintunes/dj/output.py +++ b/lintunes/dj/output.py @@ -11,7 +11,7 @@ here should exist for someone who never opens it). import numpy as np from PyQt6.QtCore import QObject, QThread, QTimer, pyqtSignal, pyqtSlot -from PyQt6.QtMultimedia import QAudioFormat, QAudioSink, QMediaDevices +from PyQt6.QtMultimedia import QAudio, QAudioFormat, QAudioSink, QMediaDevices from lintunes.dj.audio import CHANNELS, RATE @@ -30,9 +30,22 @@ class _Pump(QObject): self.io = None self.timer = None self.queued_frames = 0 + self.device_id = b"" @pyqtSlot() def start(self): + # Follow the system's output: a sink is opened on one device, and + # when that goes (headphones in, Bluetooth on) Qt doesn't move it — + # it just stops, and the decks went silent until DJ mode reopened. + self.devices = QMediaDevices() + self.devices.audioOutputsChanged.connect(self._reopen) + self.timer = QTimer() + self.timer.setInterval(TICK_MS) + self.timer.timeout.connect(self._fill) + self._open() + self.timer.start() + + def _open(self) -> bool: fmt = QAudioFormat() fmt.setSampleRate(RATE) fmt.setChannelCount(CHANNELS) @@ -40,17 +53,38 @@ class _Pump(QObject): device = QMediaDevices.defaultAudioOutput() if device.isNull() or not device.isFormatSupported(fmt): self.failed.emit("this computer's sound output can't play 44.1 kHz stereo") - return + return False self.sink = QAudioSink(device, fmt) self.sink.setBufferSize(int(RATE * BUFFER_MS / 1000) * BYTES_PER_FRAME) self.io = self.sink.start() - self.timer = QTimer() - self.timer.setInterval(TICK_MS) - self.timer.timeout.connect(self._fill) - self.timer.start() + self.device_id = bytes(device.id()) + return True + + def _close(self): + if self.sink is not None: + self.sink.stop() + self.sink = self.io = None + + @pyqtSlot() + def _reopen(self): + """The default output changed (or this one broke): reopen on it.""" + self._close() + self._open() def _fill(self): if self.sink is None or self.io is None: + # No device a moment ago; try again about once a second. + self._retry = getattr(self, "_retry", 0) + 1 + if self._retry * TICK_MS >= 1000: + self._retry = 0 + self._open() + return + if self.sink.error() != QAudio.Error.NoError: + self._reopen() + return + current = QMediaDevices.defaultAudioOutput() + if not current.isNull() and bytes(current.id()) != self.device_id: + self._reopen() # the default moved without telling us return free = self.sink.bytesFree() // BYTES_PER_FRAME frames = free - free % 64 @@ -65,9 +99,8 @@ class _Pump(QObject): def stop(self): if self.timer is not None: self.timer.stop() - if self.sink is not None: - self.sink.stop() - self.sink = self.io = self.timer = None + self._close() + self.timer = None class DjOutput(QObject): diff --git a/lintunes/gui/dj_shelf.py b/lintunes/gui/dj_shelf.py index 15d64c1..8a23a85 100644 --- a/lintunes/gui/dj_shelf.py +++ b/lintunes/gui/dj_shelf.py @@ -23,7 +23,7 @@ import threading import time import numpy as np -from PyQt6.QtCore import QPointF, QRectF, QSize, Qt, QTimer, pyqtSignal +from PyQt6.QtCore import QPointF, QRect, QRectF, QSize, Qt, QTimer, pyqtSignal from PyQt6.QtGui import ( QBrush, QColor, QIcon, QImage, QLinearGradient, QPainter, QPainterPath, QPen, QPixmap, QRadialGradient, @@ -46,10 +46,12 @@ COLORS = {"A": QColor("#5a9be0"), "B": QColor("#e8a35a")} FACES = {"A": ("#3c6896", "#2b4c70"), "B": ("#93652f", "#6e4a20")} REV_SECONDS = 1.8 # a 33⅓ rpm record: one turn every 1.8 s WINDOW_SECONDS = 8.0 # the waveforms show this much, centred +ZOOM_OUT = 2.0 # …and this many times more when paused or held COMPACT_HEIGHT = 200 DEFAULT_ROWS_BELOW = 15 MIN_ROWS_BELOW, MAX_ROWS_BELOW = 5, 28 GRIP = 8 +DECK_WIDTH = 250 # a record's column: |◀ ⏯ and "Sync to other track" fit WARN_GAIN = 0.5 @@ -67,6 +69,7 @@ class DeckView: self.bpm_saved = False self.counted = False self.mult = 1.0 # the ½× / 1× / 2× switch + self.synced = False # following the other deck's tempo @property def color(self) -> QColor: @@ -128,9 +131,36 @@ def _check_svg() -> str: return _CHECK_SVG -def _deck_button_qss(name: str) -> str: +def _start_icon(size=16) -> QPixmap: + """|◀ : a bar and a left-pointing triangle.""" + pix = QPixmap(size, size) + pix.fill(Qt.GlobalColor.transparent) + p = QPainter(pix) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(QColor("#f4f4f4")) + s = size / 16 + p.drawRect(QRectF(2 * s, 2 * s, 2.2 * s, 12 * s)) + path = QPainterPath(QPointF(14 * s, 2 * s)) + path.lineTo(5 * s, 8 * s) + path.lineTo(14 * s, 14 * s) + path.closeSubpath() + p.drawPath(path) + p.end() + return pix + + +def _deck_button_qss(name: str, glow: bool = False) -> str: top, bottom = FACES[name] color = COLORS[name].name() + if glow: + # Synced: lit in the deck's colour, with a bright rim. + top, bottom = COLORS[name].name(), COLORS[name].darker(140).name() + return (f"QPushButton {{ color: white; font-weight: bold;" + f" border: 2px solid {COLORS[name].lighter(150).name()};" + f" border-radius: 6px; padding: 3px 9px;" + f" background: qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 {top}, stop:1 {bottom}); }}" + f"QPushButton:pressed {{ background: {COLORS[name].darker(160).name()}; }}") return (f"QPushButton, QToolButton {{ color: #f4f4f4; border: 1px solid #111;" f" border-radius: 6px; padding: 4px 10px;" f" background: qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 {top}, stop:1 {bottom}); }}" @@ -371,6 +401,10 @@ class WaveLanes(QWidget): "it plays what passes the playhead, backwards too") self._drag = None # (view, x, time) self._rate = 0.0 + # Seconds of heard time across each lane: WINDOW_SECONDS while the + # deck plays, zoomed out (×ZOOM_OUT) while it's paused or held — + # easing between the two, as djay does. + self._window = {"A": WINDOW_SECONDS, "B": WINDOW_SECONDS} self._still = QTimer(self) self._still.setInterval(45) self._still.timeout.connect(self._hand_still) @@ -402,7 +436,7 @@ class WaveLanes(QWidget): dx = event.position().x() - x0 dt = max(1e-3, now - t0) # dragging right pulls the song back under the playhead - seconds = -dx / max(1, self.width()) * WINDOW_SECONDS * view.deck.speed + seconds = -dx / max(1, self.width()) * self._window[view.name] * view.deck.speed rate = seconds / dt self._rate = 0.6 * rate + 0.4 * self._rate view.deck.scratch_rate = max(-8.0, min(8.0, self._rate)) @@ -450,8 +484,15 @@ class WaveLanes(QWidget): w = int(lane.width()) speed = deck.speed if deck.scratch_rate is None else 1.0 heard = self.shelf.heard_seconds(view) + moving = deck.playing and deck.scratch_rate is None + target = WINDOW_SECONDS if moving else WINDOW_SECONDS * ZOOM_OUT + window = self._window[view.name] + window += (target - window) * 0.12 + if abs(window - target) < 0.01: + window = target + self._window[view.name] = window # source seconds at each pixel edge - edges = heard + (np.arange(w + 1) / w - 0.5) * WINDOW_SECONDS * speed + edges = heard + (np.arange(w + 1) / w - 0.5) * window * speed idx = np.clip((edges * analysis.PEAKS_PER_SECOND).astype(np.int64), 0, len(peaks)) values = _pixel_max(peaks, idx) values[(edges[:-1] < 0) | (edges[:-1] >= len(peaks) / analysis.PEAKS_PER_SECOND)] = 0 @@ -477,7 +518,7 @@ class WaveLanes(QWidget): first = math.ceil((edges[0] - view.offset) / beat) last = math.floor((edges[-1] - view.offset) / beat) p.setPen(QPen(QColor("#e8e8e8"), 1)) - span = WINDOW_SECONDS * speed + span = window * speed for k in range(first, last + 1): t = view.offset + k * beat x = (t - heard) / span * w + w / 2 @@ -487,6 +528,18 @@ class WaveLanes(QWidget): p.drawLine(QPointF(x, lane.bottom() - 6), QPointF(x, lane.bottom() - 1)) +def _load_horn(horn): + """The bundled air-horn recording into the mixer's horn (best effort: + no ffmpeg, no horn — the button just stays silent).""" + from importlib import resources + try: + path = resources.files("lintunes") / "sounds" / "airhorn.mp3" + with resources.as_file(path) as real: + horn.set_sample(decode(str(real))) + except Exception: # noqa: BLE001 — a missing horn is no failure + pass + + class HornButton(QToolButton): """The air horn: it blares for as long as it's held.""" @@ -503,8 +556,8 @@ class HornButton(QToolButton): " background: qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 #5a5c5f, stop:1 #3d3f42); }" "QToolButton:hover { background: #4a4c4f; }" "QToolButton:pressed { background: #2a2b2d; }") - self.pressed.connect(lambda: setattr(self._horn, "on", True)) - self.released.connect(lambda: setattr(self._horn, "on", False)) + self.pressed.connect(self._horn.press) + self.released.connect(self._horn.release) def _horn_icon(w=26, h=18) -> QPixmap: @@ -529,89 +582,229 @@ def _horn_icon(w=26, h=18) -> QPixmap: return pix -class Crossfader(QWidget): - """The crossfader: a big handle on a slim track, a line at the middle, - and a gentle snap to the middle when the handle is let go close to it. - 0..1000, like a QSlider's value; double-click centres it.""" +class SnapSlider(QWidget): + """A DJ slider: a slim track, a line at its middle, a big handle, and a + gentle snap — let it go (or drag it) within ``snap`` of the middle and + it sits exactly there. Integer ``lo``..``hi`` like a QSlider; a vertical + one runs bottom (``lo``) to top (``hi``). Double-click returns it to + ``home``. ``tint`` colours the handle (a deck's colour), None is grey.""" valueChanged = pyqtSignal(int) - SNAP = 30 # within 3 % of the middle → the middle - HANDLE = QSize(28, 44) TRACK = 8 - def __init__(self, parent=None): + def __init__(self, vertical: bool, lo: int, hi: int, *, home: int = 0, + snap: int = 0, handle=QSize(28, 44), tint: QColor | None = None, + parent=None): super().__init__(parent) - self._value = 500 + self.vertical = vertical + self.lo, self.hi = lo, hi + self.home = home + self.snap = snap + self.handle = handle + self.tint = tint + self._value = home self._dragging = False - self.setFixedHeight(self.HANDLE.height() + 4) - self.setMinimumWidth(160) - self.setToolTip("Crossfader (double-click: centre)") + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) + if vertical: + self.setFixedWidth(handle.width() + 4) + self.setMinimumHeight(handle.height() * 2) + else: + self.setFixedHeight(handle.height() + 4) + self.setMinimumWidth(handle.width() * 3) + + @property + def centre(self) -> float: + return (self.lo + self.hi) / 2 def value(self) -> int: return self._value def setValue(self, value: int): - value = max(0, min(1000, int(value))) + value = max(self.lo, min(self.hi, int(round(value)))) if value != self._value: self._value = value self.valueChanged.emit(value) self.update() - def _span(self) -> tuple[float, float]: - half = self.HANDLE.width() / 2 - return half, self.width() - half + def _snapped(self, value: int) -> int: + if self.snap and abs(value - self.centre) <= self.snap: + return int(self.centre) + return value - def _value_at(self, x: float) -> int: - lo, hi = self._span() - return round((x - lo) / max(1.0, hi - lo) * 1000) + # ---- geometry ---- + + def _band(self) -> QRectF: + """Where the track runs (the widget less anything drawn beside it).""" + return QRectF(self.rect()) + + def _span(self) -> tuple[float, float]: + band = self._band() + if self.vertical: + half = self.handle.height() / 2 + return band.bottom() - half, band.top() + half + half = self.handle.width() / 2 + return band.left() + half, band.right() - half + + def _pos_of(self, value: float) -> float: + a, b = self._span() + return a + (b - a) * (value - self.lo) / max(1, self.hi - self.lo) + + def _value_at(self, point) -> int: + a, b = self._span() + coord = point.y() if self.vertical else point.x() + return round(self.lo + (coord - a) / (b - a or 1) * (self.hi - self.lo)) + + # ---- mouse ---- def mousePressEvent(self, event): if event.button() == Qt.MouseButton.LeftButton: self._dragging = True - self.setValue(self._value_at(event.position().x())) + self.setValue(self._snapped(self._value_at(event.position()))) def mouseMoveEvent(self, event): if self._dragging: - value = self._value_at(event.position().x()) - if abs(value - 500) <= self.SNAP: - value = 500 # a little detent at the middle - self.setValue(value) + self.setValue(self._snapped(self._value_at(event.position()))) def mouseReleaseEvent(self, event): self._dragging = False - if abs(self._value - 500) <= self.SNAP: - self.setValue(500) + self.setValue(self._snapped(self._value)) def mouseDoubleClickEvent(self, event): - self.setValue(500) + self.setValue(self.home) + + # ---- painting ---- def paintEvent(self, event): p = QPainter(self) p.setRenderHint(QPainter.RenderHint.Antialiasing) - lo, hi = self._span() - mid_y = self.height() / 2 - track = QRectF(lo - 4, mid_y - self.TRACK / 2, hi - lo + 8, self.TRACK) + band = self._band() + a, b = self._span() + t = self.TRACK + if self.vertical: + cx = band.center().x() + track = QRectF(cx - t / 2, min(a, b) - 4, t, abs(b - a) + 8) + else: + cy = band.center().y() + track = QRectF(min(a, b) - 4, cy - t / 2, abs(b - a) + 8, t) path = QPainterPath() - path.addRoundedRect(track, self.TRACK / 2, self.TRACK / 2) + path.addRoundedRect(track, t / 2, t / 2) p.fillPath(path, QColor("#1b1b1c")) - # the middle - cx = (lo + hi) / 2 + mid = self._pos_of(self.centre) p.setPen(QPen(QColor("#8a8a8a"), 2)) - p.drawLine(QPointF(cx, 2), QPointF(cx, self.height() - 2)) - x = lo + (hi - lo) * self._value / 1000 - handle = QRectF(x - self.HANDLE.width() / 2, mid_y - self.HANDLE.height() / 2, - self.HANDLE.width(), self.HANDLE.height()) + if self.vertical: + p.drawLine(QPointF(band.left() + 2, mid), QPointF(band.right() - 2, mid)) + else: + p.drawLine(QPointF(mid, band.top() + 2), QPointF(mid, band.bottom() - 2)) + at = self._pos_of(self._value) + w, h = self.handle.width(), self.handle.height() + if self.vertical: + # a vertical fader's cap lies across the track + w, h = h, w + box = QRectF(band.center().x() - w / 2, at - h / 2, w, h) + else: + box = QRectF(at - w / 2, band.center().y() - h / 2, w, h) p.setPen(Qt.PenStyle.NoPen) p.setBrush(QColor(0, 0, 0, 110)) - p.drawRoundedRect(handle.translated(0, 2), 5, 5) - face = QLinearGradient(handle.topLeft(), handle.bottomLeft()) - face.setColorAt(0, QColor("#f2f2f2")) - face.setColorAt(1, QColor("#b2b2b2")) + p.drawRoundedRect(box.translated(0, 2), 5, 5) + light = self.tint.lighter(125) if self.tint else QColor("#f2f2f2") + dark = self.tint.darker(130) if self.tint else QColor("#b2b2b2") + face = QLinearGradient(box.topLeft(), box.bottomLeft()) + face.setColorAt(0, light) + face.setColorAt(1, dark) p.setBrush(QBrush(face)) p.setPen(QPen(QColor("#111"), 1)) - p.drawRoundedRect(handle, 5, 5) - p.setPen(QPen(QColor("#555"), 2)) - p.drawLine(QPointF(x, handle.top() + 8), QPointF(x, handle.bottom() - 8)) + p.drawRoundedRect(box, 5, 5) + p.setPen(QPen(QColor(0, 0, 0, 120), 2)) + if self.vertical: + p.drawLine(QPointF(box.left() + 6, at), QPointF(box.right() - 6, at)) + else: + p.drawLine(QPointF(at, box.top() + 8), QPointF(at, box.bottom() - 8)) + + +class Crossfader(SnapSlider): + """The crossfader: 0 (all A) … 1000 (all B), a snap within 3 % of the + middle, a handle twice the old one's height.""" + + SNAP = 30 + HANDLE = QSize(28, 44) + + def __init__(self, parent=None): + super().__init__(False, 0, 1000, home=500, snap=self.SNAP, + handle=self.HANDLE, parent=parent) + self.setMinimumWidth(160) + self.setToolTip("Crossfader (double-click: centre)") + + +def _vocal_icon(kind: str, color: QColor, size: int = 14) -> QPixmap: + """mic (vocals only), mic + note (both), note (instrumental only).""" + pix = QPixmap(size * 2 if kind == "both" else size, size) + pix.fill(Qt.GlobalColor.transparent) + p = QPainter(pix) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + s = size / 14 + + def mic(x): + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(color) + p.drawRoundedRect(QRectF(x + 4 * s, 1 * s, 6 * s, 8 * s), 3 * s, 3 * s) + p.setPen(QPen(color, 1.3 * s)) + p.setBrush(Qt.BrushStyle.NoBrush) + p.drawArc(QRectF(x + 2.5 * s, 3.5 * s, 9 * s, 8 * s), 200 * 16, 140 * 16) + p.drawLine(QPointF(x + 7 * s, 11.5 * s), QPointF(x + 7 * s, 13 * s)) + + def note(x): + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(color) + p.drawEllipse(QRectF(x + 2 * s, 9 * s, 5 * s, 4 * s)) + p.drawRect(QRectF(x + 6 * s, 1.5 * s, 1.4 * s, 9.5 * s)) + flag = QPainterPath(QPointF(x + 7.4 * s, 1.5 * s)) + flag.cubicTo(QPointF(x + 10 * s, 3 * s), QPointF(x + 12 * s, 5 * s), + QPointF(x + 10.5 * s, 8 * s)) + flag.lineTo(x + 7.4 * s, 4.5 * s) + flag.closeSubpath() + p.drawPath(flag) + + if kind == "vocals": + mic(0) + elif kind == "instrumental": + note(0) + else: + mic(0) + note(size) + p.end() + return pix + + +class VocalSlider(SnapSlider): + """Vocals only (−100) · both (0) · instrumental only (+100), with its + three icons drawn exactly over the ends and the middle of the travel.""" + + ICONS = 16 + + def __init__(self, tint: QColor, parent=None): + super().__init__(False, -100, 100, home=0, snap=8, + handle=QSize(16, 22), tint=tint, parent=parent) + self.setFixedHeight(self.handle.height() + 4 + self.ICONS) + self._icons = None + self.setToolTip("Vocals only · both · instrumental only (double-click: both)") + + def _band(self) -> QRectF: + return QRectF(self.rect()).adjusted(0, self.ICONS, 0, 0) + + def paintEvent(self, event): + super().paintEvent(event) + enabled = self.isEnabled() + color = QColor("#b8b8b8" if enabled else "#5a5a5a") + if self._icons is None or self._icons[0] != color.name(): + self._icons = (color.name(), {k: _vocal_icon(k, color) + for k in ("vocals", "both", "instrumental")}) + icons = self._icons[1] + p = QPainter(self) + for kind, value in (("vocals", self.lo), ("both", 0), ("instrumental", self.hi)): + pix = icons[kind] + x = self._pos_of(value) - pix.width() / 2 + x = max(0.0, min(self.width() - pix.width(), x)) + p.drawPixmap(QPointF(x, 0), pix) class Grip(QWidget): @@ -685,6 +878,7 @@ class DjShelf(QWidget): self._manager = manager self._prefs = prefs self.mixer = Mixer() + _load_horn(self.mixer.horn) self.views = [DeckView("A", self.mixer.a), DeckView("B", self.mixer.b)] self._output = None # Worker threads report through signals into bound methods, so Qt @@ -713,7 +907,12 @@ class DjShelf(QWidget): # ---- layout ---- def _build(self): - outer = QVBoxLayout(self) + # Everything sits on a body as tall as the shelf is *meant* to be; + # opening and closing only changes how much of it shows, so the + # decks are revealed in place rather than squeezed (Round 94). + self._body = QWidget(self) + self._layout_height = None + outer = QVBoxLayout(self._body) outer.setContentsMargins(16, 16, 16, 0) outer.setSpacing(0) row = QHBoxLayout() @@ -739,6 +938,7 @@ class DjShelf(QWidget): self.bpm_notes = {} self.pitch_boxes = {} self.mult_buttons = {} + self.start_buttons = {} self._compact_hidden = [] self._big_records = {} @@ -786,20 +986,18 @@ class DjShelf(QWidget): col.addWidget(fader_title("TEMPO", v), alignment=Qt.AlignmentFlag.AlignHCenter) top = QLabel("+8%") bottom = QLabel("−8%") - slider = QSlider(Qt.Orientation.Vertical) - slider.setRange(-int(SPEED_RANGE * 10000), int(SPEED_RANGE * 10000)) - slider.setValue(0) - slider.setStyleSheet(_slider_qss(v.name, vertical=True)) - slider.setToolTip(f"Deck {v.name} speed (double-click: back to 0)") + span = int(SPEED_RANGE * 10000) + # a light snap at 0: within 0.3 % it's exactly the song's tempo + slider = SnapSlider(True, -span, span, home=0, snap=30, + handle=QSize(20, 30), tint=v.color) + slider.setToolTip(f"Deck {v.name} tempo (double-click: back to 0)") slider.valueChanged.connect(lambda value, v=v: self._on_speed(v, value)) - slider.mouseDoubleClickEvent = lambda e, s=slider: s.setValue(0) label = QLabel("+0.0%") label.setStyleSheet(f"color: {v.color.name()}; font-size: 11px;") label.setAlignment(Qt.AlignmentFlag.AlignCenter) label.setMinimumWidth(60) for w in (top, bottom): w.setStyleSheet(f"color: {DIM}; font-size: 10px;") - slider.setFocusPolicy(Qt.FocusPolicy.NoFocus) for w in (top, slider, bottom, label): col.addWidget(w, alignment=Qt.AlignmentFlag.AlignHCenter) col.setStretch(2, 1) @@ -825,10 +1023,20 @@ class DjShelf(QWidget): buttons = QHBoxLayout(controls) buttons.setContentsMargins(0, 0, 0, 0) buttons.setSpacing(8) + back = QToolButton() + back.setIcon(QIcon(_start_icon())) + back.setIconSize(QSize(16, 16)) + back.setFixedSize(34, 34) + back.setToolTip(f"Deck {v.name}: back to the beginning") + back.clicked.connect(lambda _=False, v=v: self.to_start(v)) + back.setStyleSheet(_deck_button_qss(v.name)) + back.setFocusPolicy(Qt.FocusPolicy.NoFocus) + buttons.addWidget(back) + self.start_buttons[v.name] = back play = QToolButton() play.setIcon(QIcon(_play_icon(False))) play.setIconSize(QSize(16, 16)) - play.setFixedSize(56, 34) + play.setFixedSize(46, 34) play.setToolTip(f"Play / pause Deck {v.name}") play.clicked.connect(lambda _=False, v=v: self.toggle(v)) sync = QPushButton("Sync to other track") @@ -848,20 +1056,8 @@ class DjShelf(QWidget): vcol = QVBoxLayout(vocals) vcol.setContentsMargins(0, 0, 0, 0) vcol.setSpacing(2) - ends = QHBoxLayout() - for text in ("Vocals", "Both", "Instrumental"): - lab = QLabel(text) - lab.setStyleSheet(f"color: {DIM}; font-size: 10px;") - ends.addWidget(lab) - if text != "Instrumental": - ends.addStretch() - vcol.addLayout(ends) - slider = QSlider(Qt.Orientation.Horizontal) - slider.setRange(-100, 100) - slider.setValue(0) - slider.setStyleSheet(_slider_qss(v.name, vertical=False)) + slider = VocalSlider(v.color) slider.valueChanged.connect(lambda value, v=v: setattr(v.deck, "vocal_mix", value / 100)) - slider.mouseDoubleClickEvent = lambda e, s=slider: s.setValue(0) vcol.addWidget(slider) note = QLabel("") note.setStyleSheet(f"color: {DIM}; font-size: 10px;") @@ -870,7 +1066,7 @@ class DjShelf(QWidget): self.stem_labels[v.name] = note col.addWidget(vocals) self._compact_hidden += [controls, vocals] - holder.setFixedWidth(220) + holder.setFixedWidth(DECK_WIDTH) self._big_records[v.name] = holder return holder @@ -994,18 +1190,44 @@ class DjShelf(QWidget): return box def set_mult(self, view: DeckView, mult: float): + changed = mult != view.mult view.mult = mult for b, m in zip(self.mult_buttons[view.name], (0.5, 1.0, 2.0)): b.setChecked(m == mult) self._refresh_deck(view) + if changed: + # Counting the beats differently moves where they line up: a + # synced pair re-syncs at once, whichever side follows. + other = self.other(view) + if view.synced: + self.sync(view) + elif other.synced: + self.sync(other) + + def set_layout_height(self, height: int | None): + """How tall the decks are laid out, whatever height shows (None: + as tall as the shelf).""" + self._layout_height = height + self._place_body() + + def layout_height(self) -> int: + return self._layout_height or self.height() + + def _place_body(self): + height = self.layout_height() + if self._body.geometry() != QRect(0, 0, self.width(), height): + self._body.setGeometry(0, 0, self.width(), height) + compact = height < COMPACT_HEIGHT + if compact != getattr(self, "_compact", None): + self._compact = compact + for w in self._compact_hidden: + w.setVisible(not compact) + for holder in self._big_records.values(): + holder.setFixedWidth(max(60, height - 30) if compact else DECK_WIDTH) def resizeEvent(self, event): super().resizeEvent(event) - compact = self.height() < COMPACT_HEIGHT - for w in self._compact_hidden: - w.setVisible(not compact) - for holder in self._big_records.values(): - holder.setFixedWidth(max(60, self.height() - 30) if compact else 220) + self._place_body() def paintEvent(self, event): p = QPainter(self) @@ -1218,6 +1440,12 @@ class DjShelf(QWidget): target = other.beat_bpm * other.deck.speed view.deck.speed = analysis.sync_speed(view.beat_bpm, target) self._show_speed(view) + # Sync stays on: this deck follows the other's tempo until its own + # tempo fader is moved. Only one deck follows the other. + view.synced = True + if other.synced: + other.synced = False + self._refresh_deck(other) if view.deck.playing and other.deck.playing: own = analysis.beat_phase(self.heard_seconds(view), view.offset, view.beat_bpm) theirs = analysis.beat_phase(self.heard_seconds(other), other.offset, other.beat_bpm) @@ -1233,6 +1461,28 @@ class DjShelf(QWidget): if getattr(self, "_setting_speed", False): return view.deck.speed = 1.0 + value / 10000.0 + view.synced = False # taken out of sync by hand + self._refresh_deck(view) + + def _follow(self, view: DeckView): + """A synced deck keeps the other's tempo as that one changes.""" + other = self.other(view) + if not view.synced or not view.beat_bpm or not other.beat_bpm: + return + speed = analysis.sync_speed(view.beat_bpm, other.beat_bpm * other.deck.speed) + if abs(speed - view.deck.speed) > 1e-5: + view.deck.speed = speed + self._show_speed(view) + self._refresh_deck(view) + + def to_start(self, view: DeckView): + """|◀: back to the very beginning of the song.""" + deck = view.deck + if deck.source is None: + return + deck.seek(0) + deck.ended = False + view.counted = False self._refresh_deck(view) def _show_speed(self, view: DeckView): @@ -1271,7 +1521,9 @@ class DjShelf(QWidget): self.bpm_labels[view.name].setText(f"{view.beat_bpm * speed:.1f}") pct = (speed - 1.0) * 100 change = f" · {pct:+.1f}%" if abs(pct) >= 0.05 else "" - self.bpm_notes[view.name].setText(f"BPM · original {view.beat_bpm:.1f}{change}") + counted = {0.5: " · counted ½×", 2.0: " · counted 2×"}.get(view.mult, "") + self.bpm_notes[view.name].setText( + f"BPM{counted} · original {view.beat_bpm:.1f}{change}") else: self.bpm_labels[view.name].setText("–") self.bpm_notes[view.name].setText("BPM") @@ -1279,9 +1531,13 @@ class DjShelf(QWidget): self.play_buttons[view.name].setIcon(QIcon(_play_icon(deck.playing))) loaded = deck.source is not None self.play_buttons[view.name].setEnabled(loaded) + self.start_buttons[view.name].setEnabled(loaded) # Always clickable once this deck has a song: whatever sync can't do # yet (an empty other deck, a tempo still being worked out) it says. self.sync_buttons[view.name].setEnabled(loaded) + sync = self.sync_buttons[view.name] + sync.setText("Synced" if view.synced else "Sync to other track") + sync.setStyleSheet(_deck_button_qss(view.name, glow=view.synced)) self._refresh_note(view) def _tick(self): @@ -1295,6 +1551,8 @@ class DjShelf(QWidget): if viz is not None and sounding != self._sounding: viz.dj_playing_changed() self._sounding = sounding + for v in self.views: + self._follow(v) for v in self.views: deck = v.deck if deck.ended and not v.counted and v.track is not None: diff --git a/lintunes/gui/main_window.py b/lintunes/gui/main_window.py index 2ff93e1..55e55bf 100644 --- a/lintunes/gui/main_window.py +++ b/lintunes/gui/main_window.py @@ -448,7 +448,7 @@ class MainWindow(QMainWindow): self._add_action(file_menu, "New Smart Playlist", "Ctrl+Alt+N", lambda: self._sidebar.tree.create_smart_playlist_interactive()) self._add_action(file_menu, "New Playlist Folder", "Ctrl+Shift+N", - lambda: self._manager.create_folder("untitled folder")) + lambda: self._sidebar.tree.create_folder_interactive()) file_menu.addSeparator() self._add_action(file_menu, "Add Files to Library…", "Ctrl+O", self._open_files_dialog) @@ -2398,6 +2398,7 @@ class MainWindow(QMainWindow): self._transport.set_dj_mode(True, self._dj_titles()) track_table.deck_tag = self._deck_tag shelf.set_master(self._dj_master()) + shelf.set_layout_height(target) # laid out full size, revealed shelf.setFixedHeight(0) shelf.show() shelf.start() @@ -2407,6 +2408,7 @@ class MainWindow(QMainWindow): else: shelf = self._dj track_table.deck_tag = None + shelf.set_layout_height(shelf.height()) # covered, not squeezed self._animate_shelf(shelf.height(), 0, done=self._dj_closed) self._refresh_tables() @@ -2487,7 +2489,9 @@ class MainWindow(QMainWindow): if self._dj_resize_from is None: self._dj_resize_from = self._dj.height() low, high = self._dj_bounds() - self._dj.setFixedHeight(max(low, min(high, self._dj_resize_from + dy))) + height = max(low, min(high, self._dj_resize_from + dy)) + self._dj.set_layout_height(height) + self._dj.setFixedHeight(height) def _on_dj_resize_done(self): self._dj_resize_from = None @@ -2502,8 +2506,9 @@ class MainWindow(QMainWindow): config = load_config() config.pop("dj_shelf_height", None) save_config(config) - self._animate_shelf(self._dj.height(), - max(low, min(high, default_height(viewport, row)))) + target = max(low, min(high, default_height(viewport, row))) + self._dj.set_layout_height(target) + self._animate_shelf(self._dj.height(), target) def _deck_tag(self, track_id: int): if self._dj is None: diff --git a/lintunes/gui/preferences_dialog.py b/lintunes/gui/preferences_dialog.py index 63053b6..669eb72 100644 --- a/lintunes/gui/preferences_dialog.py +++ b/lintunes/gui/preferences_dialog.py @@ -548,6 +548,10 @@ class PreferencesDialog(QDialog): bars = QWidget() form = self._viz_form(bars) self._preset_row(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 " + "it's one bar per pixel, SoundJam style") self._bars_fade_slider, _ = self._viz_slider( form, "Fade:", "visualizer_bars_fade", config, scale=20, fmt=_fade_text, tip=fade_tip) diff --git a/lintunes/gui/sidebar.py b/lintunes/gui/sidebar.py index e5345be..5b5debc 100644 --- a/lintunes/gui/sidebar.py +++ b/lintunes/gui/sidebar.py @@ -1,6 +1,6 @@ from PyQt6.QtWidgets import ( QWidget, QVBoxLayout, QPushButton, QTreeWidget, QTreeWidgetItem, QMenu, - QInputDialog, QMessageBox, QAbstractItemView, QLineEdit, QApplication, + QMessageBox, QAbstractItemView, QLineEdit, QApplication, QHBoxLayout, QListWidget, QListWidgetItem, QStackedWidget, QSizePolicy, QFrame, ) @@ -761,6 +761,21 @@ class PlaylistTree(QTreeWidget): self._select_all_next_edit = True self.editItem(item, 0) # live inline rename; editor selects all + def create_folder_interactive(self, parent_pid: str = ""): + """Create a folder, scroll to it and open its name for editing, + all selected: type and it's named (Enter commits, Escape keeps + "untitled folder") — the same as a new playlist (Round 94).""" + folder = self._manager.create_folder("untitled folder", parent_pid) + item = self._find_item(folder.persistent_id) + if item is not None: + parent = item.parent() + if parent is not None: + parent.setExpanded(True) + self.scrollToItem(item, QAbstractItemView.ScrollHint.EnsureVisible) + self.setCurrentItem(item) + self._select_all_next_edit = True + self.editItem(item, 0) + def create_smart_playlist_interactive(self, parent_pid: str = ""): """Open the criteria editor; on accept, create the smart playlist and drop into inline rename (mirrors create_playlist_interactive).""" @@ -871,10 +886,7 @@ class PlaylistTree(QTreeWidget): elif edit_smart is not None and chosen is edit_smart: self.edit_smart_playlist(pid) elif chosen is new_folder: - name, ok = QInputDialog.getText(self, "New Playlist Folder", "Name:", - text="untitled folder") - if ok and name.strip(): - self._manager.create_folder(name.strip(), parent_pid) + self.create_folder_interactive(parent_pid) elif export is not None and chosen is export: self.export_requested.emit(pid) elif dj_prepare is not None and chosen is dj_prepare: diff --git a/lintunes/gui/transport.py b/lintunes/gui/transport.py index 18257f2..6fa0843 100644 --- a/lintunes/gui/transport.py +++ b/lintunes/gui/transport.py @@ -488,6 +488,7 @@ class TransportBar(QWidget): # between the visualizer and the timeline. The HBox centers it # vertically, so nothing stacks above or below it (iTunes-style). self._volume_slider = ClickJumpSlider() + self._volume_slider.setProperty("tall", True) # the scrubber's height self._volume_slider.setRange(0, 100) self._volume_slider.setFixedWidth(96) # As tall as the boxes, so its groove (drawn centered) sits on the @@ -573,18 +574,28 @@ class TransportBar(QWidget): self._now_playing.installEventFilter(self) gap() - # bpm tap button lives on the far right as its own box, top-aligned - # with the now-playing panel like the transport boxes — kept out of - # the seek row so it doesn't drive the timeline row's height. - self._bpm_button = BpmButton(player, manager) - # The whole box is the tap target, so it darkens (and taps) as one. - bpm_box = _box(self._bpm_button, bg=box_bg, margins=(3, 3, 3, 3), - hug=True, height=CONTROL_HEIGHT, split=True) - self._boxes.append(bpm_box) - layout.addWidget(bpm_box, alignment=TOP) + # DJ mode's button is the far-right box (Round 94: it swapped with + # bpm, so it stays put while the window parts under it); the bpm + # tap button sits under it, in the header row. + self.dj_button = QToolButton() + self.dj_button.setObjectName("djButton") + self.dj_button.setCheckable(True) + self.dj_button.setToolTip("DJ mode") + self.dj_button.setIcon(turntable_icon(QColor(ICON_GRAY), 22)) + self.dj_button.setIconSize(QSize(30, 22)) + self.dj_button.setFocusPolicy(Qt.FocusPolicy.NoFocus) + self.dj_button.setFixedWidth(52) + self.dj_button.toggled.connect(self._on_dj_button) + dj_box = _box(self.dj_button, bg=box_bg, margins=(3, 3, 3, 3), + hug=True, height=CONTROL_HEIGHT, split=True) + self._boxes.append(dj_box) + layout.addWidget(dj_box, alignment=TOP) self._fixed_controls = (transport_box, shuffle_box, repeat_box, self._visualizer, - self._volume_slider, bpm_box) + self._volume_slider, dj_box) + self._bpm_button = BpmButton(player, manager) + self._bpm_button.setObjectName("bpmHeader") + self._bpm_button.setFlat(False) # Library button · the current view's header · seek row. MainWindow # hands over the first two (see set_sidebar_header / set_view_header) @@ -594,16 +605,7 @@ class TransportBar(QWidget): self.set_header_height(34) outer.addWidget(self._header_row) - # DJ mode's button: under the bpm box, in the header row. - self.dj_button = QToolButton() - self.dj_button.setObjectName("djButton") - self.dj_button.setCheckable(True) - self.dj_button.setToolTip("DJ mode") - self.dj_button.setIcon(turntable_icon(QColor(ICON_GRAY))) - self.dj_button.setIconSize(QSize(24, 18)) - self.dj_button.setFocusPolicy(Qt.FocusPolicy.NoFocus) - self.dj_button.toggled.connect(self._on_dj_button) - self._dj_bpm_box = bpm_box + self._dj_box = dj_box self._apply_dj_button_style() self._split_widgets: tuple = () @@ -631,10 +633,12 @@ class TransportBar(QWidget): # ---- DJ mode ---- def _apply_dj_button_style(self): + """The bpm button under the DJ box wears the shared face (radius 8); + the DJ button is styled by its box like shuffle and repeat.""" bg = theme.gray(theme.gray_value(self._prefs, "color_button")) - self.dj_button.setStyleSheet(theme.button_face_qss( - "QToolButton#djButton", bg, radius=8, extra="padding: 0;", - checked_color=bg.darker(theme.CHECKED_DARKER))) + self._bpm_button.setStyleSheet(theme.button_face_qss( + "QPushButton#bpmHeader", bg, radius=8, + extra="padding: 0; color: black;")) def _on_dj_button(self, on: bool): self._on_dj_button_icon(on) @@ -668,7 +672,7 @@ class TransportBar(QWidget): def _on_dj_button_icon(self, on: bool): color = self.palette().highlight().color() if on else QColor(ICON_GRAY) - self.dj_button.setIcon(turntable_icon(color)) + self.dj_button.setIcon(turntable_icon(color, 22)) def volume_level(self) -> float: """The volume slider, 0..1 (perceptual, as Player takes it).""" @@ -769,8 +773,8 @@ class TransportBar(QWidget): row.set_panel(QRect(x_of(self._now_playing), 0, self._now_playing.width(), row.height())) - box = self._dj_bpm_box - row.set_right(self.dj_button, QRect(x_of(box), 0, box.width(), row.height())) + box = self._dj_box + row.set_right(self._bpm_button, QRect(x_of(box), 0, box.width(), row.height())) if self._split_widgets: lists, content = self._split_widgets row.set_split(x_of(lists), x_of(lists, lists.width()), diff --git a/lintunes/gui/visualizer_presets.py b/lintunes/gui/visualizer_presets.py index 87aa064..f3e8702 100644 --- a/lintunes/gui/visualizer_presets.py +++ b/lintunes/gui/visualizer_presets.py @@ -24,7 +24,7 @@ PRESETS_KEY = "visualizer_presets" DEFAULT_NAME = "Default" STYLE_KEYS = { - "bars": ("visualizer_bars_fade",), + "bars": ("visualizer_bars_fade", "visualizer_bars_count"), "radial": ("visualizer_ghost_fade", "visualizer_radial_spokes", "visualizer_radial_levels", "visualizer_radial_dot", "visualizer_radial_normalize"), diff --git a/lintunes/gui/visualizer_styles.py b/lintunes/gui/visualizer_styles.py index 81df234..6b1175a 100644 --- a/lintunes/gui/visualizer_styles.py +++ b/lintunes/gui/visualizer_styles.py @@ -55,6 +55,9 @@ HISTORY = RADIAL_FFT # samples the widget keeps for the FFTs # use the same numbers, so a hand-edited file can't go past what they offer. LIMITS = { "visualizer_bars_fade": (0.0, 3.0), # seconds; 0 = off + # SoundJam's look at the top: one bar per pixel. Past the drawing's + # width bars are merged pixel by pixel, so a big number costs nothing. + "visualizer_bars_count": (1, 1024), "visualizer_ghost_fade": (0.0, 3.0), "visualizer_laser_afterimage": (0.0, 3.0), "visualizer_laser_width": (1.0, 8.0), # pixels @@ -73,6 +76,7 @@ LIMITS = { _FLAGS = ("visualizer_radial_normalize", "visualizer_laser_head", "visualizer_laser_glow", "visualizer_laser_grid") _INTEGER = ("visualizer_radial_spokes", "visualizer_radial_levels", + "visualizer_bars_count", "visualizer_laser_low_hz", "visualizer_laser_high_hz") SPEAKER_MIN_RATIO = 2 ** (1 / 3) # the narrowest speaker: a third-octave @@ -225,28 +229,39 @@ def _faded(color: QColor, alpha: float) -> QColor: # -------------------------------------------------------------------------- class BarsRenderer: - """The 20-band graphic EQ. With a fade time, the steps a falling bar - leaves behind fade from its color into the background, rather than - vanishing — the radial's ghosts, as blocks.""" + """The graphic EQ: ``visualizer_bars_count`` log-spaced bands (20 by + default, 1 to 1024). With a fade time, the steps a falling bar leaves + behind fade from its color into the background, rather than vanishing — + the radial's ghosts, as blocks. More bars than pixels are drawn one per + pixel column (each the loudest of the bars it covers); past ~40 bars the + FFT doubles to 4096 points so the narrow bass bands have bins to read.""" name = STYLE_BARS def __init__(self, config=None): - self.levels = np.zeros(BANDS) - self.bars = [0] * BANDS # quantized 0..STEPS - # (band, step) → when the bar last fell past it; -inf = never. - self.ghosts = np.full((BANDS, STEPS + 1), -np.inf) + self.count = BANDS + self._size(BANDS) self.clock = 0.0 self.configure(config or settings(None)) + def _size(self, count: int): + self.count = count + self.levels = np.zeros(count) + self.bars = [0] * count # quantized 0..STEPS + # (band, step) → when the bar last fell past it; -inf = never. + self.ghosts = np.full((count, STEPS + 1), -np.inf) + def configure(self, config): self.fade = config["visualizer_bars_fade"] + count = int(config.get("visualizer_bars_count", BANDS)) + if count != self.count: + self._size(count) if self.fade <= 0: self.ghosts[:] = -np.inf def clear(self): self.levels[:] = 0.0 - self.bars = [0] * BANDS + self.bars = [0] * self.count self.ghosts[:] = -np.inf def ghost_alpha(self) -> np.ndarray: @@ -256,11 +271,12 @@ class BarsRenderer: def advance(self, frame: Frame) -> bool: self.clock += frame.dt - spectrum, freqs = spectrum_of(frame.samples, BARS_FFT, frame.rate) - new_levels = band_levels(spectrum, freqs, band_edges(BANDS, frame.rate)) + fft = BARS_FFT if self.count <= 40 else RADIAL_FFT + spectrum, freqs = spectrum_of(frame.samples, fft, frame.rate) + new_levels = band_levels(spectrum, freqs, band_edges(self.count, frame.rate)) # Instant attack, slow decay self.levels = np.maximum(new_levels, self.levels * DECAY) - bars = [int(round(level * STEPS)) for level in self.levels] + bars = np.rint(self.levels * STEPS).astype(int).tolist() if self.fade > 0: old, new = np.array(self.bars), np.array(bars) k = np.arange(STEPS + 1)[None, :] @@ -279,26 +295,35 @@ class BarsRenderer: avail_h = rect.height() - 2 * INSET left = int(rect.x()) + INSET baseline = int(rect.y() + rect.height()) - INSET - bar_width = avail_w / BANDS step_height = avail_h / STEPS + bars = np.asarray(self.bars) + alpha = self.ghost_alpha() + columns = self.count + if columns > avail_w >= 1: + # More bars than pixels: one per pixel, the loudest it covers. + columns = int(avail_w) + starts = (np.arange(columns) * self.count / columns).astype(int) + bars = np.maximum.reduceat(bars, starts) + alpha = np.maximum.reduceat(alpha, starts, axis=0) if alpha.size else alpha + bar_width = avail_w / max(1, columns) + gap_px = 1 if bar_width >= 3 else 0 # thin bars touch def column(i): x = left + int(i * bar_width) end = left + int((i + 1) * bar_width) - gap = 1 if i < BANDS - 1 else 0 # 1px between bars, none at edge + gap = gap_px if i < columns - 1 else 0 return x, max(1, end - x - gap) - alpha = self.ghost_alpha() if alpha.any(): for i, k in zip(*np.nonzero(alpha)): - if k <= self.bars[i]: + if k <= bars[i]: continue # under the bar itself x, w = column(i) top = baseline - int(k * step_height) bottom = baseline - int((k - 1) * step_height) painter.fillRect(x, top, w, bottom - top, _faded(color, GHOST_ALPHA * alpha[i, k])) - for i, bar in enumerate(self.bars): + for i, bar in enumerate(bars.tolist()): if bar <= 0: continue x, w = column(i) diff --git a/lintunes/preferences.py b/lintunes/preferences.py index 80da4a1..e09baa8 100644 --- a/lintunes/preferences.py +++ b/lintunes/preferences.py @@ -19,6 +19,7 @@ DEFAULTS = { # 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. "visualizer_bars_fade": 0.0, + "visualizer_bars_count": 20, # 1 … 1024 (one per pixel, at most) "visualizer_ghost_fade": 1.0, # the radial's "visualizer_laser_afterimage": 0.1, "visualizer_laser_width": 1.5, # pixels diff --git a/lintunes/sounds/CREDITS.md b/lintunes/sounds/CREDITS.md new file mode 100644 index 0000000..f3961e6 --- /dev/null +++ b/lintunes/sounds/CREDITS.md @@ -0,0 +1,7 @@ +# Sound credits + +- `tink.wav` — LinTunes' own. +- `airhorn.mp3` — "Air Horn Hype" by zar.265 on Freesound + (https://freesound.org/people/zar.265/sounds/581334/), released under + Creative Commons 0 (public domain). The DJ shelf's air horn plays its + first blast, sustained for as long as the button is held. diff --git a/lintunes/sounds/airhorn.mp3 b/lintunes/sounds/airhorn.mp3 new file mode 100644 index 0000000..eca31f0 Binary files /dev/null and b/lintunes/sounds/airhorn.mp3 differ diff --git a/setup.py b/setup.py index 4701b83..c1f2123 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ setup( # The andTunes APK LinTunes installs, and the default button artwork # sync ships to the device. package_data={ - "lintunes": ["sounds/*.wav"], + "lintunes": ["sounds/*.wav", "sounds/*.mp3", "sounds/*.md"], "lintunes.export": ["templates/*"], "lintunes.android": ["andTunes.apk", "andTunes.json"], "lintunes.andtunes": ["buttons/*.png"], diff --git a/tests/test_round62.py b/tests/test_round62.py index 4028af6..56aebfd 100644 --- a/tests/test_round62.py +++ b/tests/test_round62.py @@ -16,7 +16,7 @@ def test_every_control_shares_the_now_playing_row(qapp, tmp_path): assert panel.height() == CONTROL_HEIGHT for widget in (bar._prev_btn.parentWidget(), bar._shuffle_btn.parentWidget(), bar._visualizer, bar._volume_slider, - bar._bpm_button.parentWidget()): + bar.dj_button.parentWidget()): g = widget.geometry() assert (g.top(), g.bottom()) == (panel.top(), panel.bottom()) diff --git a/tests/test_round69.py b/tests/test_round69.py index 7614bbd..4788f58 100644 --- a/tests/test_round69.py +++ b/tests/test_round69.py @@ -125,7 +125,7 @@ def test_panel_fills_what_the_gaps_leave(qapp, tmp_path): window.resize(bar.minimumSizeHint().width() + 16, 500) qapp.processEvents() assert bar._now_playing.width() >= NOW_PLAYING_MIN - bpm = bar._bpm_button.parentWidget() + bpm = bar.dj_button.parentWidget() assert bar._now_playing.geometry().right() < bpm.geometry().left() assert bpm.geometry().right() < bar.width() @@ -166,7 +166,7 @@ def test_row_is_knolled_with_equal_gaps_and_ends(qapp, tmp_path): qapp.processEvents() row = [bar._prev_btn.parentWidget(), bar._shuffle_btn.parentWidget(), bar._repeat_btn.parentWidget(), bar._visualizer, bar._volume_slider, bar._now_playing, - bar._bpm_button.parentWidget()] + bar.dj_button.parentWidget()] edges = [(w.geometry().left(), w.geometry().right()) for w in row] gaps = [b[0] - a[1] - 1 for a, b in zip(edges, edges[1:])] # The same GAP everywhere, ends included, at every width. diff --git a/tests/test_round78.py b/tests/test_round78.py index dd70f8e..16c4b38 100644 --- a/tests/test_round78.py +++ b/tests/test_round78.py @@ -963,7 +963,8 @@ class TestPresets: def test_a_preset_only_holds_its_own_style(self, qapp, tmp_path): prefs = Preferences(tmp_path) presets.save(prefs, "bars", "x") - assert set(presets.presets(prefs, "bars")["x"]) == {"visualizer_bars_fade"} + assert set(presets.presets(prefs, "bars")["x"]) == {"visualizer_bars_fade", + "visualizer_bars_count"} assert "visualizer_sync_delay_ms" not in presets.STYLE_KEYS["laser"] def test_an_old_preset_takes_new_settings_defaults(self, qapp, tmp_path): diff --git a/tests/test_round94.py b/tests/test_round94.py index a5f73a1..9de95b9 100644 --- a/tests/test_round94.py +++ b/tests/test_round94.py @@ -78,13 +78,15 @@ def test_deck_volume_and_horn(): mixer.crossfader = 0.0 mixer.a.volume = 0.5 assert mixer.deck_gain(mixer.a) == pytest.approx(0.5) - mixer.horn.on = True + tone = (np.sin(np.arange(RATE) / RATE * 2 * np.pi * 400) * 20000).astype(np.int16) + mixer.horn.set_sample(np.stack([tone, tone], axis=1)) # a 1 s "horn" + mixer.horn.press() loud = mixer.render(4410) assert np.abs(loud).max() > 0.1 - mixer.horn.on = False - mixer.render(RATE // 2) - assert mixer.horn.render(64) is None # it has died away - assert len(mixer.tap) == 2 and mixer.rendered == 4410 + RATE // 2 + mixer.horn.release() + mixer.render(RATE) + assert mixer.horn.render(64) is None # it has played out + assert len(mixer.tap) == 2 and mixer.rendered == 4410 + RATE def test_the_visualizer_draws_the_mix(shelf, qapp): diff --git a/tests/test_round95.py b/tests/test_round95.py new file mode 100644 index 0000000..f027307 --- /dev/null +++ b/tests/test_round95.py @@ -0,0 +1,215 @@ +"""Round 95: DJ mode, round three — the shelf revealed in place, the DJ +button where bpm was, snapping sliders (tempo, vocals, crossfader), sticky +sync that glows and re-syncs on ½×/2×, back to the start, the real air +horn, zoom-out when paused or held, a sink that follows the system's output +— and outside DJ mode: a new folder named in place, the bars' count, a +taller volume slider.""" + +from unittest.mock import MagicMock + +import numpy as np +import pytest +from PyQt6.QtCore import QEvent, QPointF, Qt +from PyQt6.QtGui import QMouseEvent + +from lintunes.dj.audio import RATE, Horn +from tests.test_round93 import _clicks, _loaded, shelf # noqa: F401 — the fixture + + +def _mouse(kind, x, y): + return QMouseEvent(kind, QPointF(x, y), QPointF(x, y), Qt.MouseButton.LeftButton, + Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier) + + +class TestSnapSlider: + def test_vertical_tempo_snaps_to_zero(self, qapp): + from lintunes.gui.dj_shelf import SnapSlider + slider = SnapSlider(True, -800, 800, snap=30) + slider.resize(slider.width(), 400) + a, b = slider._span() # bottom, top + y_near = a + (b - a) * (830 / 1600) # +30 → snaps + slider.mousePressEvent(_mouse(QEvent.Type.MouseButtonPress, 10, y_near)) + assert slider.value() == 0 + slider.mouseMoveEvent(_mouse(QEvent.Type.MouseMove, 10, b)) + assert slider.value() == 800 # top is +8 % + slider.mouseReleaseEvent(_mouse(QEvent.Type.MouseButtonRelease, 10, b)) + slider.mouseDoubleClickEvent(None) + assert slider.value() == 0 + + def test_vocals_icons_sit_on_the_ends_and_middle(self, qapp): + from PyQt6.QtGui import QColor + from lintunes.gui.dj_shelf import VocalSlider + slider = VocalSlider(QColor("#5a9be0")) + slider.resize(220, slider.height()) + lo, hi = slider._span() + assert slider._pos_of(-100) == pytest.approx(lo) + assert slider._pos_of(0) == pytest.approx((lo + hi) / 2) + assert slider._pos_of(100) == pytest.approx(hi) + slider.setValue(5) + slider.mouseReleaseEvent(None) + assert slider.value() == 0 # within the snap + + +class TestSync: + def _pair(self, shelf): + a, b = shelf.views + _loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.15, 20), 124.0, 0.15) + _loaded(shelf, b, shelf.tracks[1], _clicks(118, 0.05, 20), 118.0, 0.05) + return a, b + + def test_sync_sticks_glows_and_follows(self, shelf): + a, b = self._pair(shelf) + shelf.sync(b) + assert b.synced and shelf.sync_buttons["B"].text() == "Synced" + shelf.speed["A"].setValue(200) # A +2 %: B follows + shelf._tick() + assert b.deck.speed == pytest.approx(124 * 1.02 / 118) + shelf.speed["B"].setValue(0) # B moved by hand: unsynced + assert not b.synced + assert shelf.sync_buttons["B"].text() == "Sync to other track" + + def test_only_one_deck_follows(self, shelf): + a, b = self._pair(shelf) + shelf.sync(b) + shelf.sync(a) + assert a.synced and not b.synced + + def test_half_time_resyncs_a_playing_pair(self, shelf): + a, b = self._pair(shelf) + a.deck.playing = b.deck.playing = True + a.deck.position, b.deck.position = RATE * 3.0, RATE * 7.31 + shelf.sync(b) + before = b.deck.position + shelf.set_mult(b, 0.5) + assert "counted ½×" in shelf.bpm_notes["B"].text() + assert b.synced and b.deck.speed == pytest.approx(124 / 118) + assert b.deck.position != before # re-lined up on the new grid + + def test_back_to_the_start(self, shelf): + a, _ = self._pair(shelf) + a.deck.seek(RATE * 5) + a.deck.ended = True + shelf.to_start(a) + assert a.deck.position == 0 and not a.deck.ended + + +class TestHorn: + def _horn(self): + x = (np.sin(np.arange(RATE * 2) / RATE * 2 * np.pi * 400) * 20000).astype(np.int16) + return Horn(np.stack([x, x], axis=1)) + + def _drain(self, horn): + total = 0 + while True: + block = horn.render(4096) + if block is None: + return total / RATE + total += len(block) + + def test_a_tap_plays_the_whole_recording(self): + horn = self._horn() + horn.press() + horn.render(441) + horn.release() + assert 0.01 + self._drain(horn) == pytest.approx(2.0, abs=0.1) + + def test_holding_stretches_it(self): + horn = self._horn() + horn.press() + held = sum(len(horn.render(4096)) for _ in range(int(4 * RATE / 4096))) / RATE + horn.release() + assert held > 3.9 + assert self._drain(horn) <= 2.0 # then the rest plays out + + def test_the_bundled_recording_loads(self, qapp): + from lintunes.gui.dj_shelf import _load_horn + horn = Horn() + _load_horn(horn) + assert horn._src is not None and len(horn._src) > RATE + + +def test_the_waveform_zooms_out_while_paused(shelf): + a, _ = shelf.views + _loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 10), 124.0, 0.1) + lanes = shelf.lanes + lanes.resize(600, 120) + for _ in range(80): + lanes.grab() # paused: eases out + assert lanes._window["A"] == pytest.approx(16.0) + a.deck.playing = True + for _ in range(80): + lanes.grab() + assert lanes._window["A"] == pytest.approx(8.0) + + +def test_revealed_in_place(shelf): + shelf.set_layout_height(330) + shelf.setFixedHeight(40) # mid-animation + assert shelf._body.height() == 330 + assert shelf.sync_buttons["A"].isVisibleTo(shelf) # laid out full, not compact + + +def test_the_sink_follows_the_default_output(monkeypatch): + from lintunes.dj import output + pump = output._Pump(MagicMock()) + opened = [] + pump._open = lambda: opened.append(1) or True + pump.sink = MagicMock() + pump.sink.error.return_value = output.QAudio.Error.NoError + pump.io = MagicMock() + pump.device_id = b"old" + other = MagicMock() + other.isNull.return_value = False + other.id.return_value = b"new" + monkeypatch.setattr(output.QMediaDevices, "defaultAudioOutput", lambda: other) + pump._fill() + assert opened == [1] + + +def test_bars_count_and_one_per_pixel(qapp): + from PyQt6.QtCore import QRectF + from PyQt6.QtGui import QColor, QImage, QPainter + from lintunes.gui.visualizer_styles import BarsRenderer, Frame, settings + config = settings(None) + config["visualizer_bars_count"] = 1024 + renderer = BarsRenderer(config) + x = (np.random.default_rng(1).standard_normal(4096) * 0.3).astype(np.float32) + renderer.advance(Frame(x, 44100, x[:735], 1 / 60)) + assert len(renderer.bars) == 1024 + image = QImage(206, 60, QImage.Format.Format_RGB32) + image.fill(QColor("black")) + painter = QPainter(image) + renderer.paint(painter, QRectF(0, 0, 206, 60), QColor("white")) + painter.end() + renderer.configure(dict(config, visualizer_bars_count=1)) + assert len(renderer.bars) == 1 + + +def test_new_folder_is_named_in_place(qapp, tmp_path): + from lintunes.gui.sidebar import PlaylistTree + from lintunes.library_manager import LibraryManager + from lintunes.models.library import Library + manager = LibraryManager(Library(), tmp_path) + tree = PlaylistTree(manager) + tree.show() + tree.create_folder_interactive() + item = tree.currentItem() + assert item is not None and item.text(0) == "untitled folder" + assert tree.state() == tree.State.EditingState + tree.close() + + +def test_dj_button_up_top_bpm_below_and_a_tall_volume(qapp, tmp_path): + import tempfile + from pathlib import Path + from lintunes.gui.transport import TransportBar + from lintunes.preferences import Preferences + player = MagicMock() + player.repeat_mode.return_value = "off" + with tempfile.TemporaryDirectory() as d: + bar = TransportBar(player, MagicMock(), Preferences(Path(d))) + assert bar.dj_button.parentWidget() is bar._dj_box + assert bar._dj_box in bar._fixed_controls + bar._place_header() # what a resize does + assert bar._header_row.right is bar._bpm_button + assert bar._volume_slider.property("tall") is True