Files
lintunes/lintunes/gui/dj_shelf.py
T
trav f21c31940f
macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
v0.97.0: macOS port (Round 129): OS-aware paths, config and cookies; Mac now-playing, packaging (PyInstaller .app, dmg build, signing notes, CI workflow) and docs
2026-11-17 22:41:48 -08:00

2092 lines
86 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The DJ shelf (Round 93): two decks and a mixer, set into the window.
Laid out like the mockup trav approved: a speed fader on each outer edge, a
record with play/pause and "Sync to other track" beside it, the vocals
slider under it; in the middle the decks' titles and tempos, the two
waveforms stacked (A over B, zoomed to 8 s around one shared playhead, so
synced beats visibly line up) and the crossfader. Deck A is blue and Deck B
orange, every control of theirs included.
Manual, as DJ software is: a deck loads only when a song is dragged onto
its record, and a deck whose song ends just stops. Scratching is the hand
on the record: its angular speed is the playback rate (one turn is
``REV_SECONDS`` of music, a 33⅓ record's), and letting go is normal speed
again at once. Below ``COMPACT_HEIGHT`` the shelf is one strip: small
records (a click plays or pauses), titles, tempos, waveforms, crossfader.
The audio itself is ``lintunes.dj``; this module owns the decks' state as
the GUI shows it and polls the engine at 60 fps while visible.
"""
import math
import threading
import time
import numpy as np
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,
)
from PyQt6.QtWidgets import (
QCheckBox, QHBoxLayout, QLabel, QMessageBox, QPushButton, QSizePolicy,
QSlider, QToolButton, QVBoxLayout, QWidget,
)
from lintunes import bpm_detect, tagging
from lintunes.dj import analysis, stems
from lintunes.dj.audio import RATE, SPEED_RANGE, Mixer
from lintunes.dj.loader import DeckLoader, decode
from lintunes.gui.track_table import TRACKS_MIME, parse_tracks_mime
SHELF_BG = QColor("#2e2f31")
TEXT = "#e8e8e8"
DIM = "#9a9a9a"
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 = 1.35 # …and this much more when paused or held
ZOOM_EASE = 0.06 # per frame: a gentle ease, not a lurch
COMPACT_HEIGHT = 200
DEFAULT_ROWS_BELOW = 15
MIN_ROWS_BELOW, MAX_ROWS_BELOW = 5, 28
GRIP = 8
RECORD_SIZE = 170 # the records, top corners
CONTROLS_WIDTH = 236 # a deck's controls, beside its record
CROSSFADER_WIDTH = 280
WARN_GAIN = 0.5
class DeckView:
"""What the shelf knows about one deck beyond the engine's Deck."""
def __init__(self, name: str, deck):
self.name = name
self.deck = deck
self.track = None
self.peaks: np.ndarray | None = None
self.bpm: float | None = None
self.offset = 0.0
self.stem_note = ""
self.splitting = False # waiting for / running a split (the ✕ shows)
self.split_called_off = False # cancelled: grabbing the slider retries
self.engine = stems.HQ # which engine this deck's split is (or is to be)
self.using = None # the tier of the stems playing (stems.TIERS), or None
self.percent = None # the running split's progress
self.bpm_saved = False
self.counted = False
self.mult = 1.0 # the ½× / 1× / 2× switch
self.synced = False # set to the other deck's tempo, and still is
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
@property
def color(self) -> QColor:
return COLORS[self.name]
@property
def beat_bpm(self) -> float | None:
"""The tempo the beats are counted at: the song's, halved or doubled
by the switch (half-time / double-time)."""
return self.bpm * self.mult if self.bpm else None
# ---- small painted pieces ----
def _play_icon(playing: bool, size=16) -> QPixmap:
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
if playing:
p.drawRect(QRectF(3 * s, 2 * s, 3.5 * s, 12 * s))
p.drawRect(QRectF(9.5 * s, 2 * s, 3.5 * s, 12 * s))
else:
path = QPainterPath(QPointF(4 * s, 2 * s))
path.lineTo(14 * s, 8 * s)
path.lineTo(4 * s, 14 * s)
path.closeSubpath()
p.drawPath(path)
p.end()
return pix
_CHECK_SVG = None
def _check_svg() -> str:
"""A white checkmark for checked boxes, written once to the cache (a
style sheet's ``image:`` takes a file, not data)."""
global _CHECK_SVG
if _CHECK_SVG is None:
import os
import tempfile
from lintunes import paths
folder = str(paths.cache_dir())
try:
os.makedirs(folder, exist_ok=True)
except OSError:
folder = tempfile.gettempdir()
path = os.path.join(folder, "dj-check.svg")
with open(path, "w") as out:
out.write('<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" '
'viewBox="0 0 13 13"><path d="M2.5 6.8 L5.3 9.6 L10.6 3.6" '
'fill="none" stroke="white" stroke-width="2" '
'stroke-linecap="round" stroke-linejoin="round"/></svg>')
_CHECK_SVG = path.replace("\\", "/")
return _CHECK_SVG
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}); }}"
f"QPushButton:hover, QToolButton:hover {{ background: {QColor(bottom).name()}; }}"
f"QPushButton:pressed, QToolButton:pressed {{ background:"
f" {QColor(bottom).darker(125).name()}; }}"
f"QPushButton:disabled, QToolButton:disabled {{ color: #777;"
f" background: #3a3b3d; }}"
f"QCheckBox {{ color: {TEXT}; }}"
f"QCheckBox::indicator {{ width: 13px; height: 13px; border: 1px solid #111;"
f" border-radius: 3px; background: #1b1b1c; }}"
f"QCheckBox::indicator:checked {{ background: {color};"
f" image: url({_check_svg()}); }}")
def _slider_qss(name: str | None, vertical: bool) -> str:
color = COLORS[name] if name else QColor("#d8d8d8")
light, dark = color.lighter(125).name(), color.darker(130).name()
if vertical:
return ("QSlider::groove:vertical { background: #1b1b1c; width: 8px;"
" border-radius: 4px; }"
"QSlider::handle:vertical { height: 20px; margin: 0 -11px;"
f" border-radius: 4px; border: 1px solid #111; background:"
f" qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 {light}, stop:1 {dark}); }}")
return ("QSlider::groove:horizontal { background: #1b1b1c; height: 8px;"
" border-radius: 4px; }"
"QSlider::handle:horizontal { width: 18px; margin: -7px 0;"
f" border-radius: 4px; border: 1px solid #111; background:"
f" qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 {light}, stop:1 {dark}); }}")
class RecordWidget(QWidget):
"""A slightly skeuomorphic record: grooves, a sheen, the album art as its
label, spinning with the music. Scratchable, and a drop target."""
dropped = pyqtSignal(int) # track id
toggled = pyqtSignal() # a click (not a scratch)
def __init__(self, view: DeckView, shelf, parent=None):
super().__init__(parent)
self.view = view
self.shelf = shelf
self.angle = 0.0
self.label_art: QPixmap | None = None
self._grooves: QPixmap | None = None
self._hover_drop = False
self._press = None # (pos, time)
self._prev = None # (angle, time)
self._moved = 0.0
self._rate = 0.0
self.setAcceptDrops(True)
self.setMinimumSize(48, 48)
self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred)
self._still = QTimer(self)
self._still.setInterval(45)
self._still.timeout.connect(self._hand_still)
self.setToolTip("Drag a song here to load it · drag the record to scratch")
def sizeHint(self):
return QSize(180, 180)
def set_art(self, data: bytes | None):
self.label_art = None
if data:
image = QImage()
if image.loadFromData(data):
self.label_art = QPixmap.fromImage(image.scaled(
256, 256, Qt.AspectRatioMode.KeepAspectRatioByExpanding,
Qt.TransformationMode.SmoothTransformation))
self.update()
def _disc(self) -> QRectF:
side = min(self.width(), self.height()) - 4
return QRectF((self.width() - side) / 2, (self.height() - side) / 2, side, side)
def _groove_pixmap(self, side: int) -> QPixmap:
if self._grooves is not None and self._grooves.width() == side:
return self._grooves
pix = QPixmap(side, side)
pix.fill(Qt.GlobalColor.transparent)
p = QPainter(pix)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor("#151515"))
p.drawEllipse(QRectF(0, 0, side, side))
r = side / 2
ring = r - 2.0
dark = True
while ring > r * 0.36:
p.setPen(QPen(QColor("#1d1d1d" if dark else "#121212"), 1.2))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawEllipse(QPointF(r, r), ring, ring)
ring -= 1.6
dark = not dark
p.end()
self._grooves = pix
return pix
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
disc = self._disc()
side = int(disc.width())
if side <= 4:
return
center = disc.center()
# a soft shadow under the record
shadow = QRadialGradient(center + QPointF(0, 4), side / 2 + 6)
shadow.setColorAt(0.85, QColor(0, 0, 0, 120))
shadow.setColorAt(1.0, QColor(0, 0, 0, 0))
p.setBrush(QBrush(shadow))
p.setPen(Qt.PenStyle.NoPen)
p.drawEllipse(disc.adjusted(-6, -2, 6, 10))
p.drawPixmap(disc.toRect(), self._groove_pixmap(side))
# the label turns with the record
label_r = side * 0.18
p.save()
p.translate(center)
p.rotate(self.angle)
clip = QPainterPath()
clip.addEllipse(QPointF(0, 0), label_r, label_r)
p.setClipPath(clip)
box = QRectF(-label_r, -label_r, 2 * label_r, 2 * label_r)
if self.label_art is not None and self.view.track is not None:
p.drawPixmap(box, self.label_art, QRectF(self.label_art.rect()))
else:
p.fillRect(box, self.view.color.darker(170) if self.view.track
else QColor("#3a3b3d"))
# a mark on the label, so a plain label still visibly spins
p.setClipping(False)
p.setPen(QPen(QColor(255, 255, 255, 110), max(1.0, side / 120)))
p.drawLine(QPointF(0, -label_r * 0.92), QPointF(0, -label_r * 0.55))
p.restore()
# a still sheen (light doesn't turn with the record)
sheen = QLinearGradient(disc.topLeft(), disc.bottomRight())
sheen.setColorAt(0.0, QColor(255, 255, 255, 30))
sheen.setColorAt(0.4, QColor(255, 255, 255, 0))
sheen.setColorAt(0.6, QColor(255, 255, 255, 0))
sheen.setColorAt(1.0, QColor(255, 255, 255, 20))
p.setBrush(QBrush(sheen))
p.drawEllipse(disc)
p.setBrush(QColor("#d8d8d8"))
p.drawEllipse(center, max(2.0, side / 50), max(2.0, side / 50))
if self._hover_drop:
p.setBrush(QColor(0, 0, 0, 110))
p.drawEllipse(disc)
p.setBrush(Qt.BrushStyle.NoBrush)
p.setPen(QPen(self.view.color, 4))
p.drawEllipse(disc.adjusted(2, 2, -2, -2))
if self.view.track is None and not self._hover_drop:
p.setPen(QColor(DIM))
p.drawText(disc, int(Qt.AlignmentFlag.AlignCenter), "Drop a song")
# ---- drop ----
def dragEnterEvent(self, event):
if event.mimeData().hasFormat(TRACKS_MIME):
event.acceptProposedAction()
self._hover_drop = True
self.update()
def dragMoveEvent(self, event):
if event.mimeData().hasFormat(TRACKS_MIME):
event.acceptProposedAction()
def dragLeaveEvent(self, event):
self._hover_drop = False
self.update()
def dropEvent(self, event):
self._hover_drop = False
self.update()
payload = parse_tracks_mime(event.mimeData())
ids = (payload or {}).get("track_ids") or []
if ids:
event.acceptProposedAction()
self.dropped.emit(int(ids[0]))
# ---- scratching ----
def _angle_at(self, pos) -> float:
c = self._disc().center()
return math.atan2(pos.y() - c.y(), pos.x() - c.x())
def mousePressEvent(self, event):
if event.button() != Qt.MouseButton.LeftButton or self.view.deck.source is None:
return super().mousePressEvent(event)
now = time.monotonic()
self._press = (event.position(), now)
self._prev = (self._angle_at(event.position()), now)
self._moved = 0.0
self._rate = 0.0
self.view.deck.scratch_rate = 0.0 # a hand on the record holds it
self._still.start()
def mouseMoveEvent(self, event):
if self._prev is None:
return
now = time.monotonic()
a = self._angle_at(event.position())
d = (a - self._prev[0] + math.pi) % (2 * math.pi) - math.pi
dt = max(1e-3, now - self._prev[1])
self._moved += abs(d)
rate = (d / (2 * math.pi)) * REV_SECONDS / dt
self._rate = 0.6 * rate + 0.4 * self._rate
self.view.deck.scratch_rate = max(-6.0, min(6.0, self._rate))
self._prev = (a, now)
self._still.start()
def _hand_still(self):
if self._prev is not None:
self._rate = 0.0
self.view.deck.scratch_rate = 0.0
def mouseReleaseEvent(self, event):
if self._prev is None:
return super().mouseReleaseEvent(event)
self._still.stop()
press = self._press
self._prev = self._press = None
self.view.deck.scratch_rate = None # straight back to normal speed
if press and self._moved < 0.08 and time.monotonic() - press[1] < 0.35:
self.toggled.emit()
class WaveLanes(QWidget):
"""Deck A's waveform over Deck B's, both drawn in *heard* time around
one centre playhead: a deck sped up 6 % shows 6 % more of its song in
the same width, so beats that are in time sit exactly above each other.
Beat ticks along each lane's outer edge."""
def __init__(self, shelf, parent=None):
super().__init__(parent)
self.shelf = shelf
self.setMinimumHeight(40)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.setToolTip("Drag a waveform to move through its song — "
"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)
# Dragging a lane is a scratch along the waveform: the playhead plays
# whatever passes under it, at the speed (and direction) it passes.
def _view_at(self, y: float):
views = self.shelf.views
return views[0] if y < self.height() / 2 else views[1]
def mousePressEvent(self, event):
if event.button() != Qt.MouseButton.LeftButton:
return super().mousePressEvent(event)
view = self._view_at(event.position().y())
if view.deck.source is None:
return
self._drag = (view, event.position().x(), time.monotonic())
# pixels → seconds at the zoom when grabbed: the lane easing out
# under the hand mustn't make the same drag go faster
self._drag_window = self._window[view.name]
self._rate = 0.0
view.deck.scratch_rate = 0.0
self.setCursor(Qt.CursorShape.ClosedHandCursor)
self._still.start()
def mouseMoveEvent(self, event):
if self._drag is None:
return
view, x0, t0 = self._drag
now = time.monotonic()
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()) * self._drag_window * 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))
self._drag = (view, event.position().x(), now)
self._still.start()
def _hand_still(self):
if self._drag is not None:
self._rate = 0.0
self._drag[0].deck.scratch_rate = 0.0
def mouseReleaseEvent(self, event):
if self._drag is None:
return super().mouseReleaseEvent(event)
self._still.stop()
view = self._drag[0]
self._drag = None
view.deck.scratch_rate = None
self.unsetCursor()
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing, False)
w, h = self.width(), self.height()
gap = 4
lane_h = (h - gap) / 2
for i, view in enumerate(self.shelf.views):
top = 0 if i == 0 else lane_h + gap
lane = QRectF(0, top, w, lane_h)
path = QPainterPath()
path.addRoundedRect(lane, 5, 5)
p.fillPath(path, QColor("#1d1e20"))
self._lane(p, view, lane, ticks_on_top=(i == 0))
p.setPen(QPen(QColor("#ffffff"), 2))
p.drawLine(QPointF(w / 2, 0), QPointF(w / 2, h))
def _lane(self, p, view, lane: QRectF, ticks_on_top: bool):
peaks = view.peaks
deck = view.deck
if peaks is None or deck.source is None:
p.setPen(QColor("#5a5a5a"))
p.drawText(lane, int(Qt.AlignmentFlag.AlignCenter),
f"Deck {view.name}: drop a song on its record")
return
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) * ZOOM_EASE
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 * 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
mid = lane.center().y()
half = lane.height() / 2 - 6
played = view.color
ahead = QColor(view.color).lighter(105)
ahead.setAlpha(150)
centre = w // 2
for x0, x1, color in ((0, centre, played), (centre, w, ahead)):
lines = []
for x in range(x0, x1):
v = float(values[x])
if v <= 0:
continue
y = v * half
lines.append((x, mid - y, mid + y))
p.setPen(QPen(color, 1))
for x, a, b in lines:
p.drawLine(QPointF(x + 0.5, a), QPointF(x + 0.5, b))
loop = deck.loop
if loop is not None:
span_s = window * speed
x0 = (loop[0] / RATE - heard) / span_s * w + w / 2
x1 = (loop[1] / RATE - heard) / span_s * w + w / 2
band = QColor(view.color)
band.setAlpha(60)
p.fillRect(QRectF(x0, lane.top(), max(2.0, x1 - x0), lane.height()), band)
p.setPen(QPen(view.color.lighter(130), 1))
p.drawLine(QPointF(x0, lane.top()), QPointF(x0, lane.bottom()))
p.drawLine(QPointF(x1, lane.top()), QPointF(x1, lane.bottom()))
if view.beat_bpm:
beat = 60.0 / view.beat_bpm
first = math.ceil((edges[0] - view.offset) / beat)
last = math.floor((edges[-1] - view.offset) / beat)
p.setPen(QPen(QColor("#e8e8e8"), 1))
span = window * speed
for k in range(first, last + 1):
t = view.offset + k * beat
x = (t - heard) / span * w + w / 2
if ticks_on_top:
p.drawLine(QPointF(x, lane.top() + 1), QPointF(x, lane.top() + 6))
else:
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."""
def __init__(self, horn, parent=None):
super().__init__(parent)
self._horn = horn
self.setToolTip("Air horn — hold for a longer blast")
self.setFixedSize(44, 28)
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setIcon(QIcon(_horn_icon()))
self.setIconSize(QSize(26, 18))
self.setStyleSheet(
"QToolButton { border: 1px solid #111; border-radius: 6px;"
" 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(self._horn.press)
self.released.connect(self._horn.release)
def _horn_icon(w=26, h=18) -> QPixmap:
"""A little air horn: a canister and a flared bell."""
pix = QPixmap(w, h)
pix.fill(Qt.GlobalColor.transparent)
p = QPainter(pix)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor("#f0f0f0"))
p.drawRoundedRect(QRectF(1, 6, 7, 10), 2, 2) # the can
p.drawRect(QRectF(3, 3.5, 3, 2.5)) # its button
horn = QPainterPath(QPointF(8, 9.5)) # a thin neck…
horn.lineTo(15, 9.5)
horn.cubicTo(QPointF(19, 9), QPointF(22, 5), QPointF(25, 2.5)) # …flaring out
horn.lineTo(25, 15.5)
horn.cubicTo(QPointF(22, 13), QPointF(19, 11.5), QPointF(15, 11.5))
horn.lineTo(8, 11.5)
horn.closeSubpath()
p.drawPath(horn)
p.end()
return pix
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)
sliderPressed = pyqtSignal()
TRACK = 8
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.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.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(self.lo, min(self.hi, int(round(value))))
if value != self._value:
self._value = value
self.valueChanged.emit(value)
self.update()
def _snapped(self, value: int) -> int:
if self.snap and abs(value - self.centre) <= self.snap:
return int(self.centre)
return value
# ---- 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.sliderPressed.emit()
self.setValue(self._snapped(self._value_at(event.position())))
def mouseMoveEvent(self, event):
if self._dragging:
self.setValue(self._snapped(self._value_at(event.position())))
def mouseReleaseEvent(self, event):
self._dragging = False
self.setValue(self._snapped(self._value))
def mouseDoubleClickEvent(self, event):
self.setValue(self.home)
# ---- painting ----
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
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, t / 2, t / 2)
p.fillPath(path, QColor("#1b1b1c"))
mid = self._pos_of(self.centre)
p.setPen(QPen(QColor("#8a8a8a"), 2))
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(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(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 OverviewWave(QWidget):
"""A deck's whole song, start to end: the peaks, the part already
played shaded, the loop (if any), and the playhead moving along it.
Click to jump; drag to move the playhead through the song."""
def __init__(self, view: "DeckView", shelf, parent=None):
super().__init__(parent)
self.view = view
self.shelf = shelf
self._cache = None # (peaks id, width) -> values
self._dragging = False
self.setMinimumHeight(56)
self.setMaximumHeight(80)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setFixedHeight(64)
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
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)
self._cache = (key, _pixel_max(peaks, idx, widest=max(1, len(peaks) // max(1, w) + 1)))
return self._cache[1]
def _seconds_at(self, x: float) -> float:
src = self.view.deck.source
return max(0.0, min(1.0, x / max(1, self.width()))) * src.seconds
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton and self.view.deck.source is not None:
self._dragging = True
self.shelf.jump(self.view, self._seconds_at(event.position().x()))
def mouseMoveEvent(self, event):
if self._dragging:
self.shelf.jump(self.view, self._seconds_at(event.position().x()))
def mouseReleaseEvent(self, event):
self._dragging = False
def paintEvent(self, event):
p = QPainter(self)
rect = QRectF(self.rect())
path = QPainterPath()
path.addRoundedRect(rect, 6, 6)
p.fillPath(path, QColor("#1d1e20"))
view = self.view
src = view.deck.source
if src is None or view.peaks is None or len(view.peaks) == 0:
p.setPen(QColor("#5a5a5a"))
p.drawText(rect, int(Qt.AlignmentFlag.AlignCenter), f"Deck {view.name}")
return
w = max(1, self.width())
values = self._values(w)
mid = rect.center().y()
half = rect.height() / 2 - 6
heard = self.shelf.heard_seconds(view)
at = heard / max(src.seconds, 1e-6) * w
played, ahead = QColor(view.color), QColor(view.color).darker(150)
for x in range(w):
y = float(values[x]) * half
if y <= 0.4:
continue
p.setPen(played if x < at else ahead)
p.drawLine(QPointF(x + 0.5, mid - y), QPointF(x + 0.5, mid + y))
loop = view.deck.loop
if loop is not None:
x0 = loop[0] / RATE / src.seconds * w
x1 = loop[1] / RATE / src.seconds * w
band = QColor(view.color)
band.setAlpha(70)
p.fillRect(QRectF(x0, 0, max(2.0, x1 - x0), rect.height()), band)
p.setPen(QPen(QColor("white"), 2))
p.drawLine(QPointF(at, 0), QPointF(at, rect.height()))
p.setPen(QColor(view.color))
p.drawText(rect.adjusted(8, 3, -8, -3),
int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop),
f"{_clock(heard)}")
p.drawText(rect.adjusted(8, 3, -8, -3),
int(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop),
f"-{_clock(max(0.0, src.seconds - heard))}")
def _clock(seconds: float) -> str:
seconds = int(seconds)
return f"{seconds // 60}:{seconds % 60:02d}"
LOOP_SIZES = (1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8)
def _loop_label(beats: float) -> str:
return f"1/{round(1 / beats)}" if beats < 1 else f"{int(beats)}"
class SlideOverlay(QWidget):
"""The DJ shelf's open/close animation: a picture sliding over the real,
already-final window. Opening, the old lists picture slides down by
``shift``, uncovering the live decks above it. Closing, the picture's
top ``shift`` (the shelf) stays put while the rest (the lists) slides
up over it, uncovering the real lists below."""
def __init__(self, parent, picture, shift: int, opening: bool):
super().__init__(parent)
self.picture = picture
self.shift = shift
self.opening = opening
self.progress = 0.0
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
def set_progress(self, value):
self.progress = float(value)
self.update()
def paintEvent(self, event):
p = QPainter(self)
pic = self.picture
ratio = pic.devicePixelRatio() or 1.0
w = pic.width() / ratio
if self.opening:
y = round(self.shift * self.progress)
p.drawPixmap(QPointF(0, y), pic)
# the top half's shadow, cast on the decks as they appear
if y > 0:
shade = QLinearGradient(0, 0, 0, 12)
shade.setColorAt(0, QColor(0, 0, 0, 140))
shade.setColorAt(1, QColor(0, 0, 0, 0))
p.fillRect(QRectF(0, 0, w, min(12, y)), QBrush(shade))
else:
top = int(self.shift * ratio)
shelf = pic.copy(0, 0, pic.width(), top)
rest = pic.copy(0, top, pic.width(), pic.height() - top)
shelf.setDevicePixelRatio(ratio)
rest.setDevicePixelRatio(ratio)
y = round(self.shift * (1.0 - self.progress))
p.drawPixmap(QPointF(0, 0), shelf)
p.drawPixmap(QPointF(0, y), rest)
class Grip(QWidget):
"""The shelf's bottom edge: drag to resize, double-click for the default."""
dragged = pyqtSignal(int) # dy since the press
released = pyqtSignal()
reset = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedHeight(GRIP)
self.setCursor(Qt.CursorShape.SizeVerCursor)
self.setToolTip("Drag to resize · double-click for the default size")
self._y = None
def paintEvent(self, event):
p = QPainter(self)
p.setPen(QColor("#6a6a6a"))
cx, cy = self.width() // 2, self.height() // 2
p.drawLine(cx - 20, cy - 1, cx + 20, cy - 1)
p.drawLine(cx - 20, cy + 1, cx + 20, cy + 1)
def mousePressEvent(self, event):
self._y = event.globalPosition().y()
def mouseMoveEvent(self, event):
if self._y is not None:
self.dragged.emit(int(event.globalPosition().y() - self._y))
def mouseReleaseEvent(self, event):
if self._y is not None:
self._y = None
self.released.emit()
def mouseDoubleClickEvent(self, event):
self.reset.emit()
class DjVisualSource:
"""What the transport's visualizer reads in DJ mode: the mix's heard
position and whether anything is sounding (the player's two methods)."""
def __init__(self, shelf):
self.shelf = shelf
def position_ms(self) -> float:
out = self.shelf._output
latency = out.latency_frames if out is not None else 0
return (self.shelf.mixer.rendered - latency) * 1000.0 / RATE
def is_playing(self) -> bool:
m = self.shelf.mixer
return (m.a.playing or m.b.playing or m.a.scratch_rate is not None
or m.b.scratch_rate is not None or m.horn.on)
# ---- the shelf ----
class DjShelf(QWidget):
decks_changed = pyqtSignal(dict) # {"A": track id or None, "B": …}
message = pyqtSignal(str)
resize_requested = pyqtSignal(int) # dy from the grip
resize_finished = pyqtSignal()
resize_reset = pyqtSignal()
_stems_ready = pyqtSignal(str, object) # path, (vocals, instrumental, tier)
_stems_error = pyqtSignal(str, str)
def __init__(self, manager, prefs=None, parent=None):
super().__init__(parent)
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
# queues them onto this (the GUI) thread.
self._loaders = {v.name: DeckLoader(v.name, self) for v in self.views}
for loader in self._loaders.values():
loader.loaded.connect(self._on_loader_result)
loader.failed.connect(self._on_loader_failed)
self._stems_ready.connect(self._apply_stems)
self._stems_error.connect(lambda path, why: [self._on_stem_failed(path, why, e)
for e in (stems.HQ, stems.FAST)])
# One splitter per engine, so a swap to Instant never waits behind
# Demucs. ``_splitter`` is Demucs's.
self._splitter = stems.StemSplitter(
lambda: (stems.model_choice(self._prefs), stems.gentle_choice(self._prefs)), self)
self._instant = stems.StemSplitter(parent=self, engine=stems.FAST)
for engine, splitter in ((stems.HQ, self._splitter), (stems.FAST, self._instant)):
splitter.progress.connect(
lambda path, pct, e=engine: self._on_stem_progress(path, pct, e))
splitter.finished.connect(self._on_stems)
splitter.failed.connect(lambda path, why, e=engine: self._on_stem_failed(path, why, e))
splitter.cancelled.connect(lambda path, e=engine: self._on_stem_cancelled(path, e))
self.setAutoFillBackground(False)
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, False)
self._build()
self._timer = QTimer(self)
self._timer.setInterval(16)
self._timer.timeout.connect(self._tick)
self.visual = DjVisualSource(self)
self._visualizer = None
self._sounding = False
# ---- layout ----
def _build(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()
row.setSpacing(14)
outer.addLayout(row, stretch=1)
grip = Grip()
grip.dragged.connect(self.resize_requested)
grip.released.connect(self.resize_finished)
grip.reset.connect(self.resize_reset)
outer.addWidget(grip)
self.speed = {}
self.volume = {}
self.speed_label = {}
self.records = {}
self.play_buttons = {}
self.sync_buttons = {}
self.vocal_sliders = {}
self.stem_labels = {}
self.stem_cancel = {}
self.stem_swap = {}
self.titles = {}
self.states = {}
self.bpm_labels = {}
self.bpm_notes = {}
self.pitch_boxes = {}
self.mult_buttons = {}
self.start_buttons = {}
self.loop_buttons = {}
self.loop_sizes = {}
self._compact_hidden = []
self._big_records = {}
def fader_title(text, v):
label = QLabel(text)
label.setStyleSheet(f"color: {v.color.name()}; font-size: 9px;"
" font-weight: bold;")
return label
def volume_col(v):
col = QVBoxLayout()
col.setSpacing(4)
slider = QSlider(Qt.Orientation.Vertical)
slider.setRange(0, 100)
slider.setValue(100)
slider.setStyleSheet(_slider_qss(v.name, vertical=True))
slider.setToolTip(f"Deck {v.name} volume (double-click: full)")
slider.setFocusPolicy(Qt.FocusPolicy.NoFocus)
slider.mouseDoubleClickEvent = lambda e, s=slider: s.setValue(100)
label = QLabel("100%")
label.setStyleSheet(f"color: {v.color.name()}; font-size: 11px;")
label.setAlignment(Qt.AlignmentFlag.AlignCenter)
def changed(value, v=v, label=label):
# a fader's travel is perceptual, like the main volume slider
from PyQt6.QtMultimedia import QAudio
v.deck.volume = QAudio.convertVolume(
value / 100, QAudio.VolumeScale.LogarithmicVolumeScale,
QAudio.VolumeScale.LinearVolumeScale)
label.setText(f"{value}%")
slider.valueChanged.connect(changed)
col.addWidget(fader_title("VOLUME", v), alignment=Qt.AlignmentFlag.AlignHCenter)
col.addWidget(slider, stretch=1, alignment=Qt.AlignmentFlag.AlignHCenter)
col.addWidget(label, alignment=Qt.AlignmentFlag.AlignHCenter)
holder = QWidget()
holder.setLayout(col)
holder.setFixedWidth(58)
self.volume[v.name] = slider
self._compact_hidden.append(holder)
return holder
def speed_col(v):
col = QVBoxLayout()
col.setSpacing(4)
col.addWidget(fader_title("TEMPO", v), alignment=Qt.AlignmentFlag.AlignHCenter)
top = QLabel("+8%")
bottom = QLabel("−8%")
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))
label = QLabel("+0.0%")
label.setStyleSheet(f"color: {v.color.name()}; font-size: 11px;")
label.setAlignment(Qt.AlignmentFlag.AlignCenter)
label.setMinimumWidth(54)
for w in (top, bottom):
w.setStyleSheet(f"color: {DIM}; font-size: 10px;")
for w in (top, slider, bottom, label):
col.addWidget(w, alignment=Qt.AlignmentFlag.AlignHCenter)
col.setStretch(2, 1)
holder = QWidget()
holder.setLayout(col)
holder.setFixedWidth(58)
self.speed[v.name] = slider
self.speed_label[v.name] = label
self._compact_hidden.append(holder)
return holder
def record_col(v):
record = RecordWidget(v, self)
record.dropped.connect(lambda tid, v=v: self._on_drop(v, tid))
record.toggled.connect(lambda v=v: self.toggle(v))
self.records[v.name] = record
record.setFixedWidth(RECORD_SIZE)
self._big_records[v.name] = record
return record
def controls_col(v, right: bool):
"""Everything a deck has besides its record and faders, facing
the middle: what's loaded, its tempo, the transport, loops,
vocals."""
align = Qt.AlignmentFlag.AlignRight if right else Qt.AlignmentFlag.AlignLeft
holder = QWidget()
col = QVBoxLayout(holder)
col.setContentsMargins(0, 0, 0, 0)
col.setSpacing(5)
state = QLabel(f"DECK {v.name}")
state.setStyleSheet(f"color: {v.color.name()}; font-size: 10px; letter-spacing: 1px;")
title = QLabel("")
title.setStyleSheet(f"color: {TEXT}; font-size: 14px;")
title.setTextFormat(Qt.TextFormat.RichText)
for w in (state, title):
w.setAlignment(align)
col.addWidget(w)
nums = QHBoxLayout()
nums.setSpacing(8)
bpm = QLabel("–")
bpm.setStyleSheet(f"color: {v.color.name()}; font-size: 22px; font-weight: bold;")
note = QLabel("BPM")
note.setStyleSheet(f"color: {DIM}; font-size: 10px;")
note.setAlignment(Qt.AlignmentFlag.AlignBottom)
if right:
nums.addStretch(1)
nums.addWidget(note)
nums.addWidget(bpm)
else:
nums.addWidget(bpm)
nums.addWidget(note)
nums.addStretch(1)
col.addLayout(nums)
buttons = QHBoxLayout()
buttons.setSpacing(6)
back = QToolButton()
back.setIcon(QIcon(_start_icon()))
back.setIconSize(QSize(16, 16))
back.setFixedSize(34, 32)
back.setToolTip(f"Deck {v.name}: back to the beginning")
back.clicked.connect(lambda _=False, v=v: self.to_start(v))
play = QToolButton()
play.setIcon(QIcon(_play_icon(False)))
play.setIconSize(QSize(16, 16))
play.setFixedSize(44, 32)
play.setToolTip(f"Play / pause Deck {v.name}")
play.clicked.connect(lambda _=False, v=v: self.toggle(v))
sync = QPushButton("Sync")
sync.setFixedHeight(32)
sync.setToolTip("Set this deck to the other deck's tempo now; while "
"both play, line the beats up too (the smallest nudge)")
sync.clicked.connect(lambda _=False, v=v: self.sync(v))
for w in (back, play, sync):
w.setStyleSheet(_deck_button_qss(v.name))
w.setFocusPolicy(Qt.FocusPolicy.NoFocus) # Space/Return mean nothing here
row_widgets = [back, play, sync]
for w in (reversed(row_widgets) if right else row_widgets):
buttons.addWidget(w, stretch=1 if w is sync else 0)
col.addLayout(buttons)
extras = QHBoxLayout()
extras.setSpacing(8)
pitch = QCheckBox("Keep pitch")
pitch.setChecked(True)
pitch.setFocusPolicy(Qt.FocusPolicy.NoFocus)
pitch.setStyleSheet(_deck_button_qss(v.name))
pitch.setToolTip("On: a faster song stays in its key. Off: pitch "
"follows speed, like a turntable")
pitch.toggled.connect(lambda on, v=v: setattr(v.deck, "keep_pitch", on))
mult = self._mult_switch(v)
loop = self._loop_controls(v)
for line, parts in ((extras, [mult, pitch]), (QHBoxLayout(), [loop])):
line.setSpacing(8)
if right:
line.addStretch(1)
parts.reverse()
for w in parts:
line.addWidget(w)
if not right:
line.addStretch(1)
col.addLayout(line)
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))
col.addWidget(slider)
stem = QLabel("")
stem.setStyleSheet(f"color: {DIM}; font-size: 10px;")
stem.setAlignment(align)
# A tiny ✕ right after the note while Demucs is on this song.
stop = QToolButton()
stop.setText("✕")
stop.setToolTip("cancel vocals split")
stop.setFocusPolicy(Qt.FocusPolicy.NoFocus)
# Always a button: the horn's face, shrunk to the note's size.
stop.setStyleSheet(
"QToolButton { color: #e8e8e8; font-size: 10px; padding: 0 3px;"
" border: 1px solid #111; border-radius: 4px; background:"
" qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 #5a5c5f, stop:1 #3d3f42); }"
"QToolButton:hover { background: #4a4c4f; }"
"QToolButton:pressed { background: #2a2b2d; }")
stop.clicked.connect(lambda _=False, v=v: self.cancel_split(v))
stop.hide()
# Instant ⇄ HQ for this deck's song, once both engines are set up.
swap = QToolButton()
swap.setFocusPolicy(Qt.FocusPolicy.NoFocus)
swap.setStyleSheet(stop.styleSheet())
swap.clicked.connect(lambda _=False, v=v: self.swap_engine(v))
swap.hide()
note_line = QHBoxLayout()
note_line.setSpacing(2)
if right:
note_line.addStretch(1)
note_line.addWidget(stem)
note_line.addWidget(stop)
note_line.addWidget(swap)
if not right:
note_line.addStretch(1)
col.addLayout(note_line)
col.addStretch(1)
self.titles[v.name] = title
self.states[v.name] = state
self.bpm_labels[v.name] = bpm
self.bpm_notes[v.name] = note
self.pitch_boxes[v.name] = pitch
self.start_buttons[v.name] = back
self.play_buttons[v.name] = play
self.sync_buttons[v.name] = sync
self.vocal_sliders[v.name] = slider
self.stem_labels[v.name] = stem
self.stem_cancel[v.name] = stop
self.stem_swap[v.name] = swap
holder.setFixedWidth(CONTROLS_WIDTH)
self._compact_hidden.append(holder)
return holder
a, b = self.views
row.addWidget(volume_col(a))
row.addWidget(speed_col(a))
middle = QVBoxLayout()
middle.setSpacing(10)
top = QHBoxLayout()
top.setSpacing(14)
top.addWidget(record_col(a))
top.addWidget(controls_col(a, right=False))
centre = QVBoxLayout()
centre.setSpacing(6)
horn_row = QHBoxLayout()
horn_row.addStretch(1)
self.horn = HornButton(self.mixer.horn)
horn_row.addWidget(self.horn)
horn_row.addStretch(1)
centre.addLayout(horn_row)
self._compact_hidden.append(self.horn)
self.lanes = WaveLanes(self)
centre.addWidget(self.lanes, stretch=1)
top.addLayout(centre, stretch=1)
top.addWidget(controls_col(b, right=True))
top.addWidget(record_col(b))
middle.addLayout(top, stretch=1)
bottom = QHBoxLayout()
bottom.setSpacing(14)
self.overviews = {}
for v in (a, b):
ov = OverviewWave(v, self)
self.overviews[v.name] = ov
self._compact_hidden.append(ov)
bottom.addWidget(self.overviews["A"], stretch=1)
left = QLabel("A")
left.setStyleSheet(f"color: {COLORS['A'].name()}; font-weight: bold;")
right_label = QLabel("B")
right_label.setStyleSheet(f"color: {COLORS['B'].name()}; font-weight: bold;")
self.crossfader = Crossfader()
self.crossfader.setFixedWidth(CROSSFADER_WIDTH)
self.crossfader.valueChanged.connect(lambda value: setattr(self.mixer, "crossfader", value / 1000))
bottom.addWidget(left)
bottom.addWidget(self.crossfader)
bottom.addWidget(right_label)
bottom.addWidget(self.overviews["B"], stretch=1)
middle.addLayout(bottom)
row.addLayout(middle, stretch=1)
row.addWidget(speed_col(b))
row.addWidget(volume_col(b))
for v in self.views:
self._refresh_deck(v)
def _mult_switch(self, v):
"""½× · 1× · 2×: count this song's beats at half or double its
tempo (half-time / double-time) — for display, the beat ticks and
what Sync lines up."""
box = QWidget()
row = QHBoxLayout(box)
row.setContentsMargins(0, 0, 0, 0)
row.setSpacing(0)
group = []
for i, (label, mult, tip) in enumerate((
("½×", 0.5, "Half-time: count every other beat"),
("1×", 1.0, "The song's own tempo"),
("2×", 2.0, "Double-time: count twice as many beats"))):
b = QToolButton()
b.setText(label)
b.setCheckable(True)
b.setChecked(mult == 1.0)
b.setAutoExclusive(True)
b.setToolTip(tip)
b.setFocusPolicy(Qt.FocusPolicy.NoFocus)
b.setFixedSize(30, 24)
radius = ("border-top-right-radius: 0; border-bottom-right-radius: 0;" if i == 0
else "border-top-left-radius: 0; border-bottom-left-radius: 0;" if i == 2
else "border-radius: 0;")
left = "" if i == 0 else "border-left: none;"
top, bottom = FACES[v.name]
b.setStyleSheet(
f"QToolButton {{ color: #cfcfcf; border: 1px solid #111; border-radius: 5px;"
f" background: #3a3b3d; padding: 0; {radius} {left} }}"
f"QToolButton:hover {{ background: #46474a; }}"
f"QToolButton:pressed {{ background: #2a2b2d; }}"
f"QToolButton:checked {{ color: white; background: qlineargradient("
f"x1:0,y1:0,x2:0,y2:1, stop:0 {top}, stop:1 {bottom}); }}")
b.clicked.connect(lambda _=False, v=v, m=mult: self.set_mult(v, m))
row.addWidget(b)
group.append(b)
self.mult_buttons[v.name] = group
return box
def _loop_controls(self, v):
"""Loop (on/off) and ‹ size › in beats: 1/32 … 8."""
box = QWidget()
row = QHBoxLayout(box)
row.setContentsMargins(0, 0, 0, 0)
row.setSpacing(0)
loop = QToolButton()
loop.setText("Loop")
loop.setCheckable(True)
loop.setFocusPolicy(Qt.FocusPolicy.NoFocus)
loop.setToolTip("Loop from the next beat, for the length beside it; "
"click again to play on past it")
loop.setFixedHeight(24)
loop.setMinimumWidth(52)
loop.clicked.connect(lambda on, v=v: self.set_loop(v, on))
less = QToolButton()
less.setText("‹")
more = QToolButton()
more.setText("›")
size = QLabel(_loop_label(v.loop_beats))
size.setAlignment(Qt.AlignmentFlag.AlignCenter)
size.setFixedWidth(30)
size.setStyleSheet(f"color: {TEXT}; background: #1b1b1c; font-size: 11px;"
" border-top: 1px solid #111; border-bottom: 1px solid #111;")
size.setFixedHeight(24)
for b, step in ((less, -1), (more, 1)):
b.setFixedSize(18, 24)
b.setFocusPolicy(Qt.FocusPolicy.NoFocus)
b.clicked.connect(lambda _=False, v=v, step=step: self.step_loop(v, step))
top, bottom = FACES[v.name]
loop.setStyleSheet(
f"QToolButton {{ color: #e8e8e8; border: 1px solid #111; border-radius: 5px;"
f" background: #3a3b3d; padding: 0 8px; margin-right: 4px; }}"
f"QToolButton:hover {{ background: #46474a; }}"
f"QToolButton:checked {{ color: white; font-weight: bold; background: qlineargradient("
f"x1:0,y1:0,x2:0,y2:1, stop:0 {COLORS[v.name].name()}, stop:1 {bottom});"
f" border: 1px solid {COLORS[v.name].lighter(140).name()}; }}")
stepper = ("QToolButton {{ color: #cfcfcf; border: 1px solid #111; background: #3a3b3d;"
" padding: 0; {0} }} QToolButton:hover {{ background: #46474a; }}"
" QToolButton:pressed {{ background: #2a2b2d; }}")
less.setStyleSheet(stepper.format("border-top-left-radius: 5px; border-bottom-left-radius: 5px;"))
more.setStyleSheet(stepper.format("border-top-right-radius: 5px; border-bottom-right-radius: 5px;"))
for w in (loop, less, size, more):
row.addWidget(w)
self.loop_buttons[v.name] = loop
self.loop_sizes[v.name] = size
return box
def _beat(self, view: DeckView) -> float | None:
return 60.0 / view.beat_bpm if view.beat_bpm else None
def set_loop(self, view: DeckView, on: bool):
"""Loop on, as djay does with Quantize: it starts on the *nearest*
beat — which may be just behind the playhead (playback carries on
inside the loop, no jump) or just ahead — ``loop_beats`` long; a
loop shorter than a beat snaps to its own finer grid. Off: playback
carries on past the loop's end."""
deck = view.deck
beat = self._beat(view)
if not on or deck.source is None or beat is None:
deck.loop = None
self.loop_buttons[view.name].setChecked(False)
if on and beat is None and deck.source is not None:
self.message.emit("A loop needs the song's beat, and none was found.")
return
now = self.heard_seconds(view)
snap = beat * min(1.0, view.loop_beats)
start = view.offset + round((now - view.offset) / snap) * snap
self._place_loop(view, max(0.0, start))
self.loop_buttons[view.name].setChecked(True)
def _place_loop(self, view: DeckView, start_s: float):
beat = self._beat(view)
length = view.loop_beats * beat
view.deck.loop = (int(round(start_s * RATE)), int(round((start_s + length) * RATE)))
def step_loop(self, view: DeckView, step: int):
i = LOOP_SIZES.index(view.loop_beats) if view.loop_beats in LOOP_SIZES else 7
view.loop_beats = LOOP_SIZES[max(0, min(len(LOOP_SIZES) - 1, i + step))]
self.loop_sizes[view.name].setText(_loop_label(view.loop_beats))
if view.deck.loop is not None and self._beat(view):
# A running loop keeps its start and takes the new length; a
# playhead the shorter loop leaves outside is folded back in,
# so resizing never breaks out of the loop.
self._place_loop(view, view.deck.loop[0] / RATE)
start, end = view.deck.loop
deck = view.deck
if deck.position >= end and end > start:
deck.seek(start + (deck.position - start) % (end - start))
def jump(self, view: DeckView, seconds: float):
"""Move the playhead to ``seconds`` (the overview's click/drag)."""
deck = view.deck
if deck.source is None:
return
deck.seek(seconds * RATE)
deck.ended = False
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 record in self._big_records.values():
record.setFixedWidth(max(60, height - 30) if compact else RECORD_SIZE)
def resizeEvent(self, event):
super().resizeEvent(event)
self._place_body()
def paintEvent(self, event):
p = QPainter(self)
p.fillRect(self.rect(), SHELF_BG)
# the top half of the window casts a shadow onto the shelf
top = QLinearGradient(0, 0, 0, 14)
top.setColorAt(0, QColor(0, 0, 0, 150))
top.setColorAt(1, QColor(0, 0, 0, 0))
p.fillRect(QRectF(0, 0, self.width(), 14), QBrush(top))
bottom = QLinearGradient(0, self.height() - 8, 0, self.height())
bottom.setColorAt(0, QColor(0, 0, 0, 0))
bottom.setColorAt(1, QColor(0, 0, 0, 90))
p.fillRect(QRectF(0, self.height() - 8, self.width(), 8), QBrush(bottom))
# ---- audio on/off ----
def start(self):
"""DJ mode opened: the engine's sink starts, the shelf animates."""
if self._output is None:
from lintunes.dj.output import DjOutput
self._output = DjOutput(self.mixer, self)
self._output.failed.connect(lambda why: self.message.emit(f"DJ mode has no sound: {why}"))
self._output.start()
self._timer.start()
def stop(self):
"""DJ mode closed: both decks stop (kept loaded), the sink goes."""
for v in self.views:
v.handoff = None
v.deck.playing = False
v.deck.scratch_rate = None
if self._output is not None:
self._output.stop()
self._timer.stop()
for v in self.views:
self._refresh_deck(v)
def shutdown(self):
"""The window is closing: stopped, and the audio thread ends."""
self.stop()
if self._output is not None:
self._output.shutdown()
def set_visualizer(self, visualizer):
"""Feed the mix to the transport's visualizer (None: stop)."""
if self._visualizer is not None and visualizer is None:
self._visualizer.set_dj_source(None)
self._visualizer = visualizer
self.mixer.tap.clear()
if visualizer is not None:
visualizer.set_dj_source(self.visual)
def set_master(self, linear: float):
self.mixer.master = max(0.0, min(1.0, float(linear)))
# ---- decks ----
def other(self, view: DeckView) -> DeckView:
return self.views[1] if view is self.views[0] else self.views[0]
def heard_seconds(self, view: DeckView) -> float:
deck = view.deck
latency = self._output.latency_frames if self._output is not None else 0
speed = deck.scratch_rate if deck.scratch_rate is not None else (
deck.speed if deck.playing else 0.0)
return max(0.0, (deck.position - latency * speed) / RATE)
def deck_of(self, track_id: int) -> str | None:
for v in self.views:
if v.track is not None and v.track.track_id == track_id:
return v.name
return None
def toggle(self, view: DeckView):
deck = view.deck
if deck.source is None:
return
if not deck.playing and deck.ended:
deck.seek(0)
deck.ended = False
view.counted = False
deck.playing = not deck.playing
self._refresh_deck(view)
def _on_drop(self, view: DeckView, track_id: int):
track = self._manager.library.tracks.get(track_id)
if track is None or not track.location:
return
deck = view.deck
if deck.playing and self.mixer.deck_gain(deck) > WARN_GAIN and view.track is not None:
answer = QMessageBox.question(
self, f"Replace Deck {view.name}?",
f"“{view.track.name}” is playing on Deck {view.name} at "
f"{round(self.mixer.deck_gain(deck) * 100)}% volume.\n\n"
f"Loading “{track.name}” there will cut it off for everyone listening.",
QMessageBox.StandardButton.Cancel | QMessageBox.StandardButton.Yes,
QMessageBox.StandardButton.Cancel)
if answer != QMessageBox.StandardButton.Yes:
return
self.load(view, track)
def load(self, view: DeckView, track, handoff=None):
"""Load ``track`` on this deck; ``handoff(view)`` runs once it's
playable (``handoff(None)`` if it never will be)."""
view.deck.load(None)
view.track = track
view.handoff = handoff
view.peaks = None
view.bpm = None
view.offset = 0.0
view.counted = False
view.bpm_saved = False
view.stem_note = "Loading…"
view.splitting = view.split_called_off = False
view.using = view.percent = None
self.speed[view.name].setValue(0)
self.vocal_sliders[view.name].setValue(0)
self.set_mult(view, 1.0)
if view.name in self.loop_buttons:
self.loop_buttons[view.name].setChecked(False)
try:
art = tagging.read_embedded_artwork(track.location)
except Exception: # noqa: BLE001 — art is never worth a failure
art = None
self.records[view.name].set_art(art)
self._loaders[view.name].request(track.track_id, track.location, track.bpm or None)
self._refresh_deck(view)
self._emit_decks()
def latency_ms(self) -> int:
"""How far behind what's rendered the speakers are."""
frames = self._output.latency_frames if self._output is not None else 0
return int(round(frames * 1000 / RATE))
def cue(self, view: DeckView, seconds: float, play: bool):
"""Put a loaded deck where ``seconds`` will be *heard* — a playing
deck renders a latency ahead of the speakers — playing or not."""
deck = view.deck
if deck.source is None:
return
ahead = self.latency_ms() / 1000 if play else 0.0
deck.seek((seconds + ahead) * RATE)
deck.ended = False
deck.playing = play
self._refresh_deck(view)
def _view(self, name: str) -> DeckView:
return self.views[0] if name == "A" else self.views[1]
def _on_loader_result(self, name: str, result):
self._on_loaded(self._view(name), result)
def _on_loader_failed(self, name: str, track_id: int, why: str):
view = self._view(name)
if view.track is not None and view.track.track_id == track_id:
self._on_load_failed(view, why)
def _on_loaded(self, view: DeckView, result):
if view.track is None or view.track.track_id != result.track_id:
return
view.deck.load(result.source)
view.peaks = result.peaks
view.bpm = result.bpm
view.offset = result.offset
if result.detected and result.bpm and not view.track.bpm:
# "auto-calculate bpm and save it to the file if it wasn't there"
self._manager.set_tracks_bpm({view.track.track_id: bpm_detect.fold_bpm(result.bpm)})
view.bpm_saved = True
if stems.available() or stems.instant_available():
view.engine = stems.default_engine(self._prefs)
self._request_split(view, best=True)
else:
view.stem_note = "Vocals slider needs Demucs"
self.vocal_sliders[view.name].setToolTip(
"Set up Demucs to separate vocals:\n" + stems.setup_command())
self._refresh_deck(view)
handoff, view.handoff = view.handoff, None
if handoff is not None:
handoff(view)
def _on_load_failed(self, view: DeckView, why: str):
handoff, view.handoff = view.handoff, None
if handoff is not None:
handoff(None)
view.stem_note = ""
self.message.emit(f"Couldn't load “{view.track.name if view.track else ''}” on "
f"Deck {view.name}: {why}")
view.track = None
self.records[view.name].set_art(None)
self._refresh_deck(view)
self._emit_decks()
def _views_for(self, path: str):
return [v for v in self.views if v.track is not None and v.track.location == path]
def _splitter_for(self, engine: str) -> stems.StemSplitter:
return self._instant if engine == stems.FAST else self._splitter
def _views_on(self, path: str, engine: str):
return [v for v in self._views_for(path) if v.engine == engine]
def _split_note(self, view: DeckView, doing: str) -> str:
"""What a deck's note says while it waits or splits — short, the
note has ~30 characters beside the ✕ and the swap button. With
stems already playing, those come first: "Instant vocals · HQ
split 42%"."""
split = "Instant split" if view.engine == stems.FAST else "HQ split"
if view.using is not None:
return f"{self._using_note(view)} · {split} {doing}"
if view.engine == stems.HQ:
split = "Separating vocals"
if doing == "cancelled":
return "Vocals split cancelled · grab the slider to retry"
return f"{split}: {doing}" if not doing[0].isdigit() else f"{split}… {doing}"
def _using_note(self, view: DeckView) -> str:
return "Instant vocals" if view.using == stems.INSTANT else "HQ vocals"
def _request_split(self, view: DeckView, best: bool = False):
view.percent = None
view.stem_note = self._split_note(view, "waiting…")
view.splitting, view.split_called_off = True, False
if view.engine == stems.FAST:
self._instant.request(view.track.location, best=best)
else:
self._splitter.request(view.track.location)
def cancel_split(self, view: DeckView):
"""The ✕: stop this deck's split. Grabbing the vocals slider, or
loading the song again, starts it over."""
if view.track is not None and view.splitting:
self._splitter_for(view.engine).cancel(view.track.location)
def swap_engine(self, view: DeckView):
"""Instant ⇄ HQ for this deck's song. The stems playing keep playing
until the other split lands; a split still running on the old
engine is stopped (trav: "if you're impatient there's a button to
switch to spleeter")."""
if view.track is None or view.deck.source is None:
return
target = stems.HQ if view.engine == stems.FAST else stems.FAST
if not stems.engine_ready(target):
return
if view.splitting:
self._splitter_for(view.engine).cancel(view.track.location)
view.engine = target
if view.using is not None and stems.engine_of(view.using) == target:
view.splitting = False # already playing that engine's stems
view.stem_note = self._using_note(view)
else:
self._request_split(view)
self._refresh_note(view)
def _retry_split(self, view: DeckView):
if (view.split_called_off and view.track is not None
and stems.engine_ready(view.engine)):
self._request_split(view)
self._refresh_note(view)
def _on_stem_cancelled(self, path: str, engine: str = stems.HQ):
for v in self._views_on(path, engine):
if not v.splitting:
continue
v.splitting, v.split_called_off = False, True
v.stem_note = self._split_note(v, "cancelled")
self._refresh_note(v)
def _on_stem_progress(self, path: str, percent: int, engine: str = stems.HQ):
for v in self._views_on(path, engine):
if v.split_called_off or not v.splitting:
continue
v.percent = percent
v.stem_note = self._split_note(v, f"{percent}%")
self._refresh_note(v)
def _on_stems(self, path: str, files: dict):
tier = stems.model_of(files)
engine = stems.engine_of(tier)
# An Instant lookup at load may answer with a cached Demucs split:
# then this deck is on HQ.
views = [v for v in self._views_for(path)
if v.engine == engine or (v.engine == stems.FAST and v.using is None)]
if not views:
return
for v in views:
v.engine = engine
v.splitting = v.split_called_off = False
v.stem_note = self._split_note(v, "reading…") if v.using else "Vocals: reading…"
self._refresh_note(v)
def work():
try:
vocals = decode(str(files["vocals"]))
instrumental = decode(str(files["no_vocals"]))
except OSError as e:
self._stems_error.emit(path, str(e))
return
self._stems_ready.emit(path, (vocals, instrumental, tier))
threading.Thread(target=work, daemon=True, name="lintunes-dj-stems").start()
def _apply_stems(self, path: str, stem_set):
vocals, instrumental, tier = stem_set
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
v.using = tier
v.splitting = False
v.stem_note = self._using_note(v)
self._refresh_note(v)
def _on_stem_failed(self, path: str, why: str, engine: str = stems.HQ):
for v in self._views_on(path, engine):
v.splitting = False
note = f"couldn't separate vocals: {why}"
v.stem_note = (f"{self._using_note(v)} · {note}" if v.using
else note[0].upper() + note[1:])
self._refresh_note(v)
def sync(self, view: DeckView):
"""Tempo to the other deck's; while both play, the beats too."""
other = self.other(view)
if view.deck.source is None:
return
if other.deck.source is None:
self.message.emit(f"Load a song on Deck {other.name} to sync to it."
if other.track is None else
f"Deck {other.name} is still loading.")
return
if not view.bpm or not other.bpm:
missing = view if not view.bpm else other
self.message.emit(f"Can't sync: no beat was found in “{missing.track.name}”.")
return
target = other.beat_bpm * other.deck.speed
view.deck.speed = analysis.sync_speed(view.beat_bpm, target)
self._show_speed(view)
# Sync *sets* this deck to the other's tempo, once. It stays lit
# while that still holds; the other deck loading a new song, or
# either tempo moving, leaves this tempo where it is, unlit.
view.synced = True
view.synced_to = other.track.track_id if other.track else None
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)
shift = analysis.phase_shift(own, theirs, view.beat_bpm)
view.deck.seek(view.deck.position + shift * RATE)
self.message.emit(f"Deck {view.name} synced to Deck {other.name}: "
f"{target:.1f} BPM, beats lined up")
else:
self.message.emit(f"Deck {view.name} set to Deck {other.name}'s tempo, {target:.1f} BPM")
self._refresh_deck(view)
def _on_speed(self, view: DeckView, value: int):
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 _check_sync(self, view: DeckView):
"""Unlight Sync once it no longer holds: the other deck has another
song, or the tempos have drifted apart."""
if not view.synced:
return
other = self.other(view)
same_song = other.track is not None and other.track.track_id == view.synced_to
matches = (view.beat_bpm and other.beat_bpm and abs(
analysis.sync_speed(view.beat_bpm, other.beat_bpm * other.deck.speed)
- view.deck.speed) < 1e-4)
if not (same_song and matches):
view.synced = False
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):
"""The fader follows a speed set elsewhere (sync), pegged at its ends."""
self._setting_speed = True
try:
self.speed[view.name].setValue(int(round((view.deck.speed - 1.0) * 10000)))
finally:
self._setting_speed = False
# ---- showing it ----
def _emit_decks(self):
self.decks_changed.emit({v.name: v.track.track_id if v.track else None
for v in self.views})
def _refresh_note(self, view: DeckView):
self.stem_labels[view.name].setText(view.stem_note)
self.stem_cancel[view.name].setVisible(view.splitting and view.track is not None)
swap = self.stem_swap[view.name]
both = stems.available() and stems.instant_available()
swap.setVisible(both and view.track is not None and view.deck.source is not None)
if view.engine == stems.FAST:
swap.setText("HQ")
swap.setToolTip("Split this song with Demucs: much slower, cleaner vocals. "
"The instant split keeps playing until it's done.")
else:
swap.setText("Instant")
swap.setToolTip("Split this song with Spleeter instead: done in seconds, "
"rougher vocals. Stops the Demucs split.")
has = view.deck.source is not None and view.deck.source.has_stems()
# After a cancel the slider stays live: grabbing it splits again.
self.vocal_sliders[view.name].setEnabled(has or view.split_called_off)
def _refresh_deck(self, view: DeckView):
deck = view.deck
t = view.track
if t is None:
self.titles[view.name].setText("<span style='color:#6a6a6a'>Nothing loaded</span>")
else:
artist = f" <span style='color:#b9b9b9'>· {_esc(t.artist)}</span>" if t.artist else ""
self.titles[view.name].setText(f"<b>{_esc(t.name)}</b>{artist}")
state = ("PLAYING" if deck.playing else "ENDED" if deck.ended
else "LOADING" if t is not None and deck.source is None
else "CUED" if deck.source is not None else "EMPTY")
self.states[view.name].setText(f"DECK {view.name} · {state}")
speed = deck.speed
if view.beat_bpm:
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 ""
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")
self.speed_label[view.name].setText(f"{(speed - 1.0) * 100:+.1f}%")
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")
sync.setStyleSheet(_deck_button_qss(view.name, glow=view.synced))
self._refresh_note(view)
def _tick(self):
viz = self._visualizer
tap = self.mixer.tap
while tap:
start, mono = tap.popleft()
if viz is not None:
viz.feed_dj(mono, RATE, start * 1000.0 / RATE)
sounding = self.visual.is_playing()
if viz is not None and sounding != self._sounding:
viz.dj_playing_changed()
self._sounding = sounding
for v in self.views:
self._check_sync(v)
for v in self.views:
deck = v.deck
if deck.ended and not v.counted and v.track is not None:
v.counted = True
self._manager.record_play(v.track.track_id)
self._refresh_deck(v)
record = self.records[v.name]
record.angle = (self.heard_seconds(v) / REV_SECONDS * 360.0) % 360.0
record.update()
if deck.playing or deck.scratch_rate is not None:
self._refresh_bpm_only(v)
self.lanes.update()
for overview in self.overviews.values():
overview.update()
def _refresh_bpm_only(self, view: DeckView):
if view.beat_bpm:
self.bpm_labels[view.name].setText(f"{view.beat_bpm * view.deck.speed:.1f}")
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."""
w = len(idx) - 1
if len(peaks) == 0 or w <= 0:
return np.zeros(max(w, 0), np.float32)
lo = idx[:-1]
count = np.clip(idx[1:] - lo, 1, widest)
out = np.zeros(w, np.float32)
for k in range(widest):
take = count > k
if not take.any():
break
at = np.minimum(lo + k, len(peaks) - 1)
out = np.where(take, np.maximum(out, peaks[at]), out)
return out
def _esc(text: str) -> str:
return (text or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
FULL_HEIGHT = 380 # the whole layout, comfortably
def default_height(viewport_height: int, row_height: int, rows_below=DEFAULT_ROWS_BELOW) -> int:
"""The shelf height that leaves ``rows_below`` songs showing, given how
tall the track list's viewport is with the shelf closed — but never
less than the full layout while there's room for it (``height_bounds``
still keeps 5 songs showing)."""
return max(FULL_HEIGHT, viewport_height - rows_below * row_height)
def height_bounds(viewport_height: int, row_height: int) -> tuple[int, int]:
"""(smallest, biggest): ~28 songs below at the smallest, ~5 at the
biggest; never under a usable strip."""
low = max(84, viewport_height - MAX_ROWS_BELOW * row_height)
high = max(low, viewport_height - MIN_ROWS_BELOW * row_height)
return low, high