diff --git a/lintunes/__init__.py b/lintunes/__init__.py index 1a7372d..a890aef 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.102.1" +__version__ = "0.103.0" diff --git a/lintunes/gui/dj_shelf.py b/lintunes/gui/dj_shelf.py index 73401e1..d120d2d 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, QRect, QRectF, QSize, Qt, QTimer, pyqtSignal +from PyQt6.QtCore import QEvent, QPointF, QRect, QRectF, QSize, Qt, QTimer, pyqtSignal from PyQt6.QtGui import ( QBrush, QColor, QIcon, QImage, QLinearGradient, QPainter, QPainterPath, QPen, QPixmap, QRadialGradient, @@ -81,6 +81,17 @@ class DeckView: self.synced_to = None # …the track it was set to self.loop_beats = 4.0 self.handoff = None # called with this view (None: failed) once loaded + self.stem_peaks = None # {"vocals": peaks, "instrumental": peaks} once split + self.preview = None # the stem whose waveform is shown while its icon is held + + @property + def shown_peaks(self) -> np.ndarray | None: + """The peaks the waveforms draw: the whole song's, or one stem's + while its icon on the vocals slider is held (a look only — what + plays doesn't change).""" + if self.preview and self.stem_peaks: + return self.stem_peaks.get(self.preview, self.peaks) + return self.peaks @property def color(self) -> QColor: @@ -488,7 +499,7 @@ class WaveLanes(QWidget): p.drawLine(QPointF(w / 2, 0), QPointF(w / 2, h)) def _lane(self, p, view, lane: QRectF, ticks_on_top: bool): - peaks = view.peaks + peaks = view.shown_peaks deck = view.deck if peaks is None or deck.source is None: p.setPen(QColor("#5a5a5a")) @@ -762,76 +773,126 @@ class Crossfader(SnapSlider): self.setToolTip("Crossfader (double-click: centre)") +PREVIEW_GREEN = QColor("#4cd964") + + 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) + """mic (vocals only), note (instrumental only).""" + pix = QPixmap(size, size) pix.fill(Qt.GlobalColor.transparent) p = QPainter(pix) p.setRenderHint(QPainter.RenderHint.Antialiasing) s = size / 14 - - def mic(x): + if kind == "vocals": 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.drawRoundedRect(QRectF(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.drawArc(QRectF(2.5 * s, 3.5 * s, 9 * s, 8 * s), 200 * 16, 140 * 16) + p.drawLine(QPointF(7 * s, 11.5 * s), QPointF(7 * s, 13 * s)) + else: 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) + p.drawEllipse(QRectF(2 * s, 9 * s, 5 * s, 4 * s)) + p.drawRect(QRectF(6 * s, 1.5 * s, 1.4 * s, 9.5 * s)) + flag = QPainterPath(QPointF(7.4 * s, 1.5 * s)) + flag.cubicTo(QPointF(10 * s, 3 * s), QPointF(12 * s, 5 * s), + QPointF(10.5 * s, 8 * s)) + flag.lineTo(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.""" + """Vocals only (−100) · both (0) · instrumental only (+100): a mic over + the left end, a note over the right and a small line over the middle. + Holding the mic or the note lights it green and emits ``preview`` with + "vocals" / "instrumental" (``None`` on release) — the slider doesn't + move, so what plays doesn't change.""" ICONS = 16 + preview = pyqtSignal(object) 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)") + self.held = None # "vocals" / "instrumental" while held + self.setToolTip("Vocals only · both · instrumental only (double-click: both)\n" + "Hold the mic or the note to see just that part's waveform") def _band(self) -> QRectF: return QRectF(self.rect()).adjusted(0, self.ICONS, 0, 0) + def _icon_rect(self, kind: str) -> QRectF: + value = self.lo if kind == "vocals" else self.hi + x = self._pos_of(value) - self.ICONS / 2 + x = max(0.0, min(self.width() - self.ICONS, x)) + return QRectF(x, 0, self.ICONS, self.ICONS) + + def _icon_at(self, point) -> str | None: + for kind in ("vocals", "instrumental"): + # a little slack around the icon, but only in the icon row + if (point.y() < self.ICONS + and self._icon_rect(kind).adjusted(-4, 0, 4, 0).contains(point)): + return kind + return None + + def mousePressEvent(self, event): + if event.button() == Qt.MouseButton.LeftButton: + kind = self._icon_at(event.position()) + if kind is not None: + self.held = kind + self.preview.emit(kind) + self.update() + return + super().mousePressEvent(event) + + def mouseMoveEvent(self, event): + if self.held is None: + super().mouseMoveEvent(event) + + def mouseReleaseEvent(self, event): + if self.held is not None: + self.held = None + self.preview.emit(None) + self.update() + return + super().mouseReleaseEvent(event) + + def mouseDoubleClickEvent(self, event): + if event is not None and self._icon_at(event.position()) is not None: + # the second press of a double-click on an icon is another hold + self.mousePressEvent(event) + return + super().mouseDoubleClickEvent(event) + 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")}) + key = color.name() + if self._icons is None or self._icons[0] != key: + self._icons = (key, {(k, lit): _vocal_icon(k, PREVIEW_GREEN if lit else color) + for k in ("vocals", "instrumental") for lit in (False, True)}) 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) + for kind in ("vocals", "instrumental"): + p.drawPixmap(self._icon_rect(kind).topLeft(), icons[(kind, self.held == kind)]) + mid = self._pos_of(0) + p.setPen(QPen(color, 1.5)) + p.drawLine(QPointF(mid, 4), QPointF(mid, self.ICONS - 3)) + + def changeEvent(self, event): + if (event.type() == QEvent.Type.EnabledChange and not self.isEnabled() + and self.held is not None): + self.held = None + self.preview.emit(None) + super().changeEvent(event) class OverviewWave(QWidget): @@ -852,7 +913,7 @@ class OverviewWave(QWidget): self.setToolTip(f"Deck {view.name}: the whole song — click to jump, drag to move") def _values(self, w: int) -> np.ndarray: - peaks = self.view.peaks + peaks = self.view.shown_peaks key = (id(peaks), w) if self._cache is None or self._cache[0] != key: idx = np.linspace(0, len(peaks), w + 1).astype(np.int64) @@ -1282,6 +1343,7 @@ class DjShelf(QWidget): slider = VocalSlider(v.color) slider.valueChanged.connect(lambda value, v=v: setattr(v.deck, "vocal_mix", value / 100)) slider.sliderPressed.connect(lambda v=v: self._retry_split(v)) + slider.preview.connect(lambda kind, v=v: self.set_preview(v, kind)) col.addWidget(slider) stem = QLabel("") stem.setStyleSheet(f"color: {DIM}; font-size: 10px;") @@ -1669,6 +1731,7 @@ class DjShelf(QWidget): view.track = track view.handoff = handoff view.peaks = None + view.stem_peaks = None view.bpm = None view.offset = 0.0 view.counted = False @@ -1858,22 +1921,34 @@ class DjShelf(QWidget): except OSError as e: self._stems_error.emit(path, str(e)) return - self._stems_ready.emit(path, (vocals, instrumental, tier)) + self._stems_ready.emit(path, (vocals, instrumental, tier, + _stem_peaks(vocals, instrumental))) threading.Thread(target=work, daemon=True, name="lintunes-dj-stems").start() def _apply_stems(self, path: str, stem_set): - vocals, instrumental, tier = stem_set + vocals, instrumental, tier, *rest = stem_set + peaks = rest[0] if rest else None for v in self._views_for(path): src = v.deck.source if src is None or v.engine != stems.engine_of(tier): continue # swapped away while it decoded src.vocals, src.instrumental = vocals, instrumental + if peaks is None: + peaks = _stem_peaks(vocals, instrumental) + v.stem_peaks = peaks v.using = tier v.splitting = False v.stem_note = self._using_note(v) self._refresh_note(v) + def set_preview(self, view: DeckView, kind: str | None): + """Show one stem's waveform for this deck (``None``: the whole + song's again). Only the drawing changes, never the sound.""" + view.preview = kind + self.lanes.update() + self.overviews[view.name].update() + def _on_stem_failed(self, path: str, why: str, engine: str = stems.HQ): for v in self._views_on(path, engine): v.splitting = False @@ -2050,6 +2125,12 @@ class DjShelf(QWidget): self.bpm_labels[view.name].setText(f"{view.beat_bpm * view.deck.speed:.1f}") +def _stem_peaks(vocals: np.ndarray, instrumental: np.ndarray) -> dict: + """Each stem's peaks, on the same scale as the whole song's.""" + return {"vocals": analysis.peaks(vocals, RATE), + "instrumental": analysis.peaks(instrumental, RATE)} + + def _pixel_max(peaks: np.ndarray, idx: np.ndarray, widest: int = 8) -> np.ndarray: """The loudest peak between each pair of neighbouring ``idx`` (pixel edges as peak indices), looking at most ``widest`` peaks per pixel.""" diff --git a/tests/test_round135.py b/tests/test_round135.py new file mode 100644 index 0000000..2694947 --- /dev/null +++ b/tests/test_round135.py @@ -0,0 +1,73 @@ +"""Round 135: the DJ vocals slider's middle is a small line, and holding its +mic or note shows just that stem's waveform — without moving the slider.""" +import numpy as np +from PyQt6.QtCore import QPoint, Qt +from PyQt6.QtGui import QColor +from PyQt6.QtTest import QTest + +from lintunes.dj import analysis, stems +from tests.test_round93 import RATE, _clicks, _loaded, shelf # noqa: F401 — fixture + + +def _slider(qapp): + from lintunes.gui.dj_shelf import VocalSlider + slider = VocalSlider(QColor("#5a9be0")) + slider.resize(220, slider.height()) + return slider + + +def test_holding_an_icon_previews_and_leaves_the_value(qapp): + slider = _slider(qapp) + seen = [] + slider.preview.connect(seen.append) + for kind in ("vocals", "instrumental"): + at = slider._icon_rect(kind).center().toPoint() + QTest.mousePress(slider, Qt.MouseButton.LeftButton, pos=at) + assert slider.held == kind + QTest.mouseRelease(slider, Qt.MouseButton.LeftButton, pos=at) + assert slider.held is None + assert slider.value() == 0 # the sound never changes + assert seen == ["vocals", None, "instrumental", None] + + +def test_the_middle_is_not_a_preview_and_the_track_still_slides(qapp): + slider = _slider(qapp) + seen = [] + slider.preview.connect(seen.append) + mid = QPoint(int(slider._pos_of(0)), 4) + QTest.mousePress(slider, Qt.MouseButton.LeftButton, pos=mid) + QTest.mouseRelease(slider, Qt.MouseButton.LeftButton, pos=mid) + assert seen == [] + lo, _ = slider._span() + end = QPoint(int(lo), slider.height() - 6) # on the track, not the icons + QTest.mousePress(slider, Qt.MouseButton.LeftButton, pos=end) + QTest.mouseRelease(slider, Qt.MouseButton.LeftButton, pos=end) + assert slider.value() == -100 + + +def test_the_waveforms_show_the_held_stem(shelf): + a, _ = shelf.views + _loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 5), 124.0, 0.1) + n = a.deck.source.frames + vocals = np.zeros((n, 2), np.int16) + vocals[: n // 2] = 8000 + instrumental = np.full((n, 2), 4000, np.int16) + shelf._apply_stems("/x.mp3", (vocals, instrumental, "htdemucs")) + full = a.peaks + assert a.shown_peaks is full + shelf.vocal_sliders["A"].preview.emit("vocals") + np.testing.assert_allclose(a.shown_peaks, analysis.peaks(vocals, RATE)) + shelf.vocal_sliders["A"].preview.emit("instrumental") + np.testing.assert_allclose(a.shown_peaks, analysis.peaks(instrumental, RATE)) + shelf.vocal_sliders["A"].preview.emit(None) + assert a.shown_peaks is full + assert a.deck.vocal_mix == 0 # what plays is untouched + shelf.overviews["A"].grab() # paints with the stem's peaks + shelf.lanes.grab() + + +def test_no_split_yet_shows_the_whole_song(shelf): + a, _ = shelf.views + _loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 5), 124.0, 0.1) + shelf.set_preview(a, "vocals") + assert a.shown_peaks is a.peaks