From 6d6a0c2385409cd58ca8c5c0410784e0c2a5af85 Mon Sep 17 00:00:00 2001 From: trav Date: Sat, 17 Oct 2026 03:13:59 -0700 Subject: [PATCH] =?UTF-8?q?v0.64.0:=20DJ=20mode=20round=20two=20=E2=80=94?= =?UTF-8?q?=20vocals=20models,=20Prepare=20for=20DJ,=20deck=20volumes,=20?= =?UTF-8?q?=C2=BD=C3=97/2=C3=97,=20scrubbing,=20air=20horn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Preferences › DJ: vocals model (Best / Balanced / Fast) and gentle CPU use (a quarter of the cores, lowest priority — measured only ~20% slower). Splits are cached per model; a deck uses the best one. - Prepare for DJ on a playlist or songs: BPM and vocals ahead of time. - Each deck: a volume fader on the outer edge, labelled beside Tempo; a ½×/1×/2× switch for half/double-time counting. - Drag a waveform to scrub (backwards too). - Crossfader: a handle twice as tall, a middle line, a snap to centre; narrower. "calculated, saved" is gone from the BPM line. - Keep pitch shows a checkmark. An air horn to hold. - The visualizer draws the mix; the sidebar art hides in DJ mode. - The Library button has the transport buttons' 8 px corners. --- CLAUDE.md | 19 ++ lintunes/__init__.py | 2 +- lintunes/dj/analysis.py | 14 + lintunes/dj/audio.py | 55 +++- lintunes/dj/prepare.py | 72 ++++++ lintunes/dj/stems.py | 187 +++++++++----- lintunes/gui/dj_shelf.py | 402 +++++++++++++++++++++++++++-- lintunes/gui/main_window.py | 86 +++++- lintunes/gui/preferences_dialog.py | 35 +++ lintunes/gui/sidebar.py | 12 +- lintunes/gui/track_table.py | 8 +- lintunes/gui/transport.py | 2 +- lintunes/gui/visualizer.py | 18 ++ tests/test_round70.py | 2 +- tests/test_round93.py | 3 +- tests/test_round94.py | 209 +++++++++++++++ 16 files changed, 1029 insertions(+), 97 deletions(-) create mode 100644 lintunes/dj/prepare.py create mode 100644 tests/test_round94.py diff --git a/CLAUDE.md b/CLAUDE.md index 0b7ab8e..2724688 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -387,6 +387,25 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal (`stems.setup_command()`; it needs numpy installed explicitly), never a pip dependency of LinTunes — without it the slider is disabled with that command in its tooltip. + **Round 94**: Demucs is the CPU hog (htdemucs: 29 s per 40 s of audio on + 8 cores, 35 s on 2 — so cores barely matter), so it always runs niced + and Preferences › DJ (its own page) picks the model (`stems.MODELS`: + Best = htdemucs_ft, Balanced = htdemucs, Fast = htdemucs at overlap 0.1, + ~25 % quicker; hdemucs_mmi 42 s and mdx 156 s were slower, no "fast" + model exists) and "gentle" (default: a quarter of the cores, nice 19). + Splits are cached per model (`//`; Round 93's sit in + `/` and count as htdemucs) and a deck takes the best one cached. + **Prepare for DJ** (a playlist's or songs' right-click; `dj/prepare.py`) + does the BPM + split ahead of time with the status-bar progress/cancel. + Each deck also has a volume fader (outer edge, perceptual), a ½×/1×/2× + switch (half/double-time: the BPM shown, the beat ticks and what Sync + matches — `analysis.sync_speed` takes the straight ratio unless it's + implausible, then the nearest octave), and its waveform lane scrubs when + dragged (a scratch at the drag's rate). The crossfader is + `dj_shelf.Crossfader` (big handle, a middle line, snaps within 3 %). An + 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. - **`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 ce75f2a..cfb4d28 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.63.1" +__version__ = "0.64.0" diff --git a/lintunes/dj/analysis.py b/lintunes/dj/analysis.py index a535b4d..bbf4c26 100644 --- a/lintunes/dj/analysis.py +++ b/lintunes/dj/analysis.py @@ -137,6 +137,20 @@ def sync_ratio(own_bpm: float, target_bpm: float) -> float: return min((ratio, ratio * 2, ratio / 2), key=lambda r: abs(np.log2(r))) +def sync_speed(own_beat_bpm: float, target_beat_bpm: float, + plausible: tuple[float, float] = (0.75, 1.34)) -> float: + """The speed that plays ``own`` at ``target``, both as the decks count + their beats (the ½×/1×/2× switch already applied). Taken straight when + it's a plausible change of speed; a ratio further out than that means + the two are counted an octave apart, so the nearest octave wins.""" + if not own_beat_bpm or not target_beat_bpm: + return 1.0 + ratio = target_beat_bpm / own_beat_bpm + if plausible[0] <= ratio <= plausible[1]: + return ratio + return sync_ratio(own_beat_bpm, target_beat_bpm) + + def beat_phase(position_s: float, offset_s: float, bpm: float) -> float: """Where in its beat a song is, 0..1.""" if not bpm: diff --git a/lintunes/dj/audio.py b/lintunes/dj/audio.py index e49626c..13c3d5f 100644 --- a/lintunes/dj/audio.py +++ b/lintunes/dj/audio.py @@ -18,6 +18,8 @@ master volume, and clips. Everything here runs on the sink's thread; the GUI only sets plain attributes (one assignment each, so never torn). """ +from collections import deque + import numpy as np RATE = 44100 @@ -86,6 +88,7 @@ class Deck: self.keep_pitch = True self.vocal_mix = 0.0 self.scratch_rate: float | None = None + self.volume = 1.0 # the deck's own fader, before the crossfader self.ended = False # reached the end by playing (GUI clears) self._ola: np.ndarray | None = None # overlap-add tail self._last: int | None = None # where the last window was read @@ -227,20 +230,66 @@ def crossfade_gains(x: float) -> tuple[float, float]: return float(np.cos(x * np.pi / 2)), float(np.sin(x * np.pi / 2)) +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).""" + + FREQS = (369.99, 466.16, 554.37) # F#4, A#4, C#5 + ATTACK, RELEASE = 0.015, 0.12 + LEVEL = 0.32 + + def __init__(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 + 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) + + class Mixer: def __init__(self): self.a = Deck("A") self.b = Deck("B") self.crossfader = 0.5 self.master = 1.0 + self.horn = Horn() + # What was rendered, for the visualizer: (first frame, mono) blocks, + # appended here (the sink's thread), drained by the GUI. + self.tap = deque(maxlen=128) + self.rendered = 0 def deck_gain(self, deck: Deck) -> float: a, b = crossfade_gains(self.crossfader) - return (a if deck is self.a else b) * self.master + return (a if deck is self.a else b) * deck.volume * self.master def render(self, count: int) -> np.ndarray: ga, gb = crossfade_gains(self.crossfader) - out = self.a.render(count) * (ga * self.master) - out += self.b.render(count) * (gb * self.master) + out = self.a.render(count) * (ga * self.a.volume * self.master) + out += self.b.render(count) * (gb * self.b.volume * self.master) + horn = self.horn.render(count) + if horn is not None: + out += horn * self.master np.clip(out, -1.0, 1.0, out=out) + self.tap.append((self.rendered, out.mean(axis=1))) + self.rendered += count return out diff --git a/lintunes/dj/prepare.py b/lintunes/dj/prepare.py new file mode 100644 index 0000000..c7078c3 --- /dev/null +++ b/lintunes/dj/prepare.py @@ -0,0 +1,72 @@ +"""Prepare for DJ: the slow part of a deck load, done ahead for many songs. + +For each song: its BPM, worked out and saved to the file when it has none +(the GUI applies it, as Calculate BPM does), and its vocals/instrumental +split with the vocals model set in Preferences › DJ — so a whole playlist +can be split with the slow, best model overnight and every deck load after +that is instant. One song at a time on a daemon thread, ExportWorker's +shape: ``progress``, ``bpm_found``, ``finished``; ``cancel`` stops between +songs and kills a split in progress. +""" + +import threading + +from PyQt6.QtCore import QObject, pyqtSignal + +from lintunes import bpm_detect +from lintunes.dj import stems + + +class DjPrepWorker(QObject): + progress = pyqtSignal(int, int, str) # done, total, what's happening + bpm_found = pyqtSignal(int, int) # track id, bpm + finished = pyqtSignal(dict) # {"done", "split", "bpm", "failed", "cancelled"} + + def __init__(self, items, model: str, gentle: bool, parent=None): + """``items``: (track id, path, label, has bpm).""" + super().__init__(parent) + self._items = list(items) + self._model = model + self._gentle = gentle + self._cancel = threading.Event() + self._thread = None + + def busy(self) -> bool: + return self._thread is not None and self._thread.is_alive() + + def cancel(self): + self._cancel.set() + + def start(self): + self._thread = threading.Thread(target=self._run, daemon=True, + name="lintunes-dj-prepare") + self._thread.start() + + def _run(self): + summary = {"done": 0, "split": 0, "bpm": 0, "failed": 0, "cancelled": False} + total = len(self._items) + for i, (track_id, path, label, has_bpm) in enumerate(self._items): + if self._cancel.is_set(): + summary["cancelled"] = True + break + try: + if not has_bpm: + self.progress.emit(i, total, f"BPM · {label}") + bpm = bpm_detect.detect_file(path) + if bpm is not None: + self.bpm_found.emit(track_id, bpm) + summary["bpm"] += 1 + if stems.available() and stems.cached(path, self._model) is None: + def tick(percent, i=i, label=label): + self.progress.emit(i, total, f"Vocals {percent}% · {label}") + self.progress.emit(i, total, f"Vocals · {label}") + stems.split(path, self._model, self._gentle, tick, self._cancel) + summary["split"] += 1 + summary["done"] += 1 + except stems.Cancelled: + summary["cancelled"] = True + break + except Exception: # noqa: BLE001 — counted, the batch goes on + summary["failed"] += 1 + self.progress.emit(total, total, "") + self.finished.emit(summary) diff --git a/lintunes/dj/stems.py b/lintunes/dj/stems.py index bc1317e..9da0285 100644 --- a/lintunes/dj/stems.py +++ b/lintunes/dj/stems.py @@ -1,16 +1,21 @@ """Vocals and instrumental, for the decks' vocals sliders: Demucs. Nothing separates a voice from a mix in real time on a laptop, so a song is -split once, in the background, when it lands on a deck, and kept: -``$XDG_CACHE_HOME/lintunes/stems//{vocals,no_vocals}.flac``, keyed by -path + size + mtime like the loudness cache (machine-local, never the -synced data dir). A cached song's slider works the moment it loads. +split once, in the background, and kept: +``$XDG_CACHE_HOME/lintunes/stems///{vocals,no_vocals}.flac``, +keyed by path + size + mtime like the loudness cache (machine-local, never +the synced data dir). A cached song's slider works the moment it loads, and +a deck uses the best split it finds whatever model made it. (Round 93's +first splits sit directly in ``/``; they were htdemucs.) -Demucs (Meta's htdemucs model, two-stem mode) runs as a runtime tool, never a -pip dependency of LinTunes: PyTorch is ~1 GB, so it lives in its own venv at -``$XDG_DATA_HOME/lintunes/demucs`` (``setup_command`` makes it), and -LinTunes runs ``/bin/python -m demucs``. On CPU a song takes about -as long as it plays, give or take; progress is read off its tqdm bar. +Demucs runs as a runtime tool, never a pip dependency of LinTunes: PyTorch is +~1 GB, so it lives in its own venv at ``$XDG_DATA_HOME/lintunes/demucs`` +(``setup_command`` makes it), and LinTunes runs ``/bin/python -m +demucs``. It is *the* CPU hog in LinTunes (Round 94: htdemucs took 29 s for +40 s of audio on all 8 cores — several hot minutes a song), so it always +runs niced, and "gentle" (Preferences › DJ, the default) caps it at a +quarter of the cores: measured only ~20 % slower, far cooler. Which model is +a Preferences choice too (``MODELS``). Progress is read off its tqdm bar. One split at a time: two would only halve each other's speed. """ @@ -25,11 +30,32 @@ from pathlib import Path from PyQt6.QtCore import QObject, pyqtSignal -MODEL = "htdemucs" +# id → (label, what it costs). Best first: a deck uses the best split it has. +# Measured on this laptop (Round 94, 40 s of audio, 2 threads): htdemucs +# 35 s, at overlap 0.1 27 s; hdemucs_mmi 42 s and mdx 156 s were slower, +# so no other Demucs model is a "fast" one — fewer overlapping windows is. +MODELS = { + "htdemucs_ft": ("Best", "4 fine-tuned models: cleanest, about 4× slower"), + "htdemucs": ("Balanced", "about as long as the song plays"), + "htdemucs_fast": ("Fast", "the same model, fewer overlapping windows: " + "~25 % quicker, very slightly rougher"), +} +# id → the demucs command-line arguments that make it +_ARGS = { + "htdemucs_ft": ["-n", "htdemucs_ft"], + "htdemucs": ["-n", "htdemucs"], + "htdemucs_fast": ["-n", "htdemucs", "--overlap", "0.1"], +} +DEFAULT_MODEL = "htdemucs" +LEGACY_MODEL = "htdemucs" # Round 93's splits, made before models had folders STEMS = ("vocals", "no_vocals") _PERCENT = re.compile(r"(\d{1,3})%\|") +class Cancelled(Exception): + pass + + def venv_dir() -> Path: base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share") return Path(base) / "lintunes" / "demucs" @@ -50,6 +76,20 @@ def setup_command() -> str: f"https://download.pytorch.org/whl/cpu && {v}/bin/pip install numpy demucs") +def model_choice(prefs) -> str: + value = prefs.get("dj_stem_model", DEFAULT_MODEL) if prefs is not None else DEFAULT_MODEL + return value if value in MODELS else DEFAULT_MODEL + + +def gentle_choice(prefs) -> bool: + return bool(prefs.get("dj_stem_gentle", True)) if prefs is not None else True + + +def threads(gentle: bool) -> int: + cores = os.cpu_count() or 4 + return max(1, cores // 4) if gentle else cores + + def cache_root() -> Path: base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache") return Path(base) / "lintunes" / "stems" @@ -64,14 +104,26 @@ def cache_key(path: str) -> str | None: return hashlib.sha1(raw.encode()).hexdigest()[:20] -def cached(path: str) -> dict[str, Path] | None: - """{"vocals": …, "no_vocals": …} when this song was split already.""" +def _files(folder: Path) -> dict[str, Path] | None: + files = {name: folder / f"{name}.flac" for name in STEMS} + return files if all(f.is_file() for f in files.values()) else None + + +def cached(path: str, model: str | None = None) -> dict[str, Path] | None: + """The stems of ``path``: ``model``'s when given, else the best there + are (``MODELS`` order). None when it hasn't been split.""" key = cache_key(path) if key is None: return None - folder = cache_root() / key - files = {name: folder / f"{name}.flac" for name in STEMS} - return files if all(f.is_file() for f in files.values()) else None + root = cache_root() / key + order = [model] if model else list(MODELS) + for name in order: + hit = _files(root / name) + if hit is None and name == LEGACY_MODEL: + hit = _files(root) + if hit is not None: + return hit + return None def parse_progress(text: str) -> int | None: @@ -79,21 +131,76 @@ def parse_progress(text: str) -> int | None: return int(found[-1]) if found else None +def split(path: str, model: str, gentle: bool, progress=None, + cancel: threading.Event | None = None) -> dict[str, Path]: + """Run Demucs on ``path`` (blocking) and cache the two stems. Raises + OSError on failure and Cancelled when ``cancel`` is set.""" + if not available(): + raise OSError("Demucs isn't set up on this computer") + key = cache_key(path) + if key is None: + raise OSError("the file is missing") + model = model if model in MODELS else DEFAULT_MODEL + work = Path(tempfile.mkdtemp(prefix="lintunes-stems-")) + count = str(threads(gentle)) + env = dict(os.environ, OMP_NUM_THREADS=count, MKL_NUM_THREADS=count) + niceness = 19 if gentle else 10 + try: + cmd = ([str(python()), "-m", "demucs", "--two-stems=vocals"] + _ARGS[model] + + ["--flac", "-o", str(work), path]) + process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + env=env, preexec_fn=lambda: os.nice(niceness)) + tail = b"" + last = -1 + while True: + if cancel is not None and cancel.is_set(): + process.kill() + process.wait() + raise Cancelled() + chunk = process.stderr.read(256) + if not chunk: + break + tail = (tail + chunk)[-4096:] + percent = parse_progress(tail.decode(errors="replace")) + if percent is not None and percent != last and progress is not None: + last = percent + progress(percent) + if process.wait() != 0: + lines = tail.decode(errors="replace").strip().splitlines() + raise OSError(lines[-1] if lines else "Demucs failed") + made = list(work.rglob("vocals.flac")) + if not made: + raise OSError("Demucs wrote nothing") + folder = cache_root() / key / model + folder.mkdir(parents=True, exist_ok=True) + out = {} + for name in STEMS: + target = folder / f"{name}.flac" + shutil.move(str(made[0].parent / f"{name}.flac"), target) + out[name] = target + return out + finally: + shutil.rmtree(work, ignore_errors=True) + + class StemSplitter(QObject): - """A queue of songs to split, one Demucs run at a time.""" + """A queue of songs to split for the decks, one Demucs run at a time. + ``settings`` returns (model, gentle) when each split starts, so a change + in Preferences applies to the next song.""" progress = pyqtSignal(str, int) # path, percent finished = pyqtSignal(str, object) # path, {"vocals": Path, …} failed = pyqtSignal(str, str) # path, why - def __init__(self, parent=None): + def __init__(self, settings=None, parent=None): super().__init__(parent) + self._settings = settings or (lambda: (DEFAULT_MODEL, True)) self._queue: list[str] = [] self._busy = False self._lock = threading.Lock() def request(self, path: str): - """Split ``path`` unless it's cached (then report it at once).""" + """Split ``path`` unless any split of it is cached (then report it).""" hit = cached(path) if hit is not None: self.finished.emit(path, hit) @@ -115,49 +222,11 @@ class StemSplitter(QObject): self._busy = False return path = self._queue.pop(0) + model, gentle = self._settings() try: - result = self._split(path) + result = split(path, model, gentle, + lambda percent, path=path: self.progress.emit(path, percent)) except Exception as e: # noqa: BLE001 — reported, never raised self.failed.emit(path, str(e) or type(e).__name__) continue self.finished.emit(path, result) - - def _split(self, path: str) -> dict[str, Path]: - if not available(): - raise OSError("Demucs isn't set up on this computer") - key = cache_key(path) - if key is None: - raise OSError("the file is missing") - work = Path(tempfile.mkdtemp(prefix="lintunes-stems-")) - try: - cmd = [str(python()), "-m", "demucs", "--two-stems=vocals", "-n", MODEL, - "--flac", "-o", str(work), path] - process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, - stderr=subprocess.PIPE) - tail = b"" - last = -1 - while True: - chunk = process.stderr.read(256) - if not chunk: - break - tail = (tail + chunk)[-4096:] - percent = parse_progress(tail.decode(errors="replace")) - if percent is not None and percent != last: - last = percent - self.progress.emit(path, percent) - if process.wait() != 0: - lines = tail.decode(errors="replace").strip().splitlines() - raise OSError(lines[-1] if lines else "Demucs failed") - made = list(work.rglob("vocals.flac")) - if not made: - raise OSError("Demucs wrote nothing") - folder = cache_root() / key - folder.mkdir(parents=True, exist_ok=True) - out = {} - for name in STEMS: - target = folder / f"{name}.flac" - shutil.move(str(made[0].parent / f"{name}.flac"), target) - out[name] = target - return out - finally: - shutil.rmtree(work, ignore_errors=True) diff --git a/lintunes/gui/dj_shelf.py b/lintunes/gui/dj_shelf.py index 595d048..15d64c1 100644 --- a/lintunes/gui/dj_shelf.py +++ b/lintunes/gui/dj_shelf.py @@ -66,11 +66,18 @@ class DeckView: self.stem_note = "" self.bpm_saved = False self.counted = False + self.mult = 1.0 # the ½× / 1× / 2× switch @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 ---- @@ -95,6 +102,32 @@ def _play_icon(playing: bool, size=16) -> QPixmap: 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 + base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache") + folder = os.path.join(base, "lintunes") + 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('') + _CHECK_SVG = path.replace("\\", "/") + return _CHECK_SVG + + def _deck_button_qss(name: str) -> str: top, bottom = FACES[name] color = COLORS[name].name() @@ -109,7 +142,8 @@ def _deck_button_qss(name: str) -> str: 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"QCheckBox::indicator:checked {{ background: {color};" + f" image: url({_check_svg()}); }}") def _slider_qss(name: str | None, vertical: bool) -> str: @@ -333,6 +367,61 @@ class WaveLanes(QWidget): 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 + 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()) + 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()) * WINDOW_SECONDS * 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) @@ -383,8 +472,8 @@ class WaveLanes(QWidget): p.setPen(QPen(color, 1)) for x, a, b in lines: p.drawLine(QPointF(x + 0.5, a), QPointF(x + 0.5, b)) - if view.bpm: - beat = 60.0 / view.bpm + 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)) @@ -398,6 +487,133 @@ class WaveLanes(QWidget): p.drawLine(QPointF(x, lane.bottom() - 6), QPointF(x, lane.bottom() - 1)) +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(lambda: setattr(self._horn, "on", True)) + self.released.connect(lambda: setattr(self._horn, "on", False)) + + +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 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.""" + + valueChanged = pyqtSignal(int) + SNAP = 30 # within 3 % of the middle → the middle + HANDLE = QSize(28, 44) + TRACK = 8 + + def __init__(self, parent=None): + super().__init__(parent) + self._value = 500 + self._dragging = False + self.setFixedHeight(self.HANDLE.height() + 4) + self.setMinimumWidth(160) + self.setToolTip("Crossfader (double-click: centre)") + + def value(self) -> int: + return self._value + + def setValue(self, value: int): + value = max(0, min(1000, int(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 _value_at(self, x: float) -> int: + lo, hi = self._span() + return round((x - lo) / max(1.0, hi - lo) * 1000) + + def mousePressEvent(self, event): + if event.button() == Qt.MouseButton.LeftButton: + self._dragging = True + self.setValue(self._value_at(event.position().x())) + + 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) + + def mouseReleaseEvent(self, event): + self._dragging = False + if abs(self._value - 500) <= self.SNAP: + self.setValue(500) + + def mouseDoubleClickEvent(self, event): + self.setValue(500) + + 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) + path = QPainterPath() + path.addRoundedRect(track, self.TRACK / 2, self.TRACK / 2) + p.fillPath(path, QColor("#1b1b1c")) + # the middle + cx = (lo + hi) / 2 + 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()) + 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.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)) + + class Grip(QWidget): """The shelf's bottom edge: drag to resize, double-click for the default.""" @@ -435,6 +651,24 @@ class Grip(QWidget): 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): @@ -446,9 +680,10 @@ class DjShelf(QWidget): _stems_ready = pyqtSignal(str, object) # path, (vocals, instrumental) _stems_error = pyqtSignal(str, str) - def __init__(self, manager, parent=None): + def __init__(self, manager, prefs=None, parent=None): super().__init__(parent) self._manager = manager + self._prefs = prefs self.mixer = Mixer() self.views = [DeckView("A", self.mixer.a), DeckView("B", self.mixer.b)] self._output = None @@ -460,7 +695,8 @@ class DjShelf(QWidget): loader.failed.connect(self._on_loader_failed) self._stems_ready.connect(self._apply_stems) self._stems_error.connect(self._on_stem_failed) - self._splitter = stems.StemSplitter(self) + self._splitter = stems.StemSplitter( + lambda: (stems.model_choice(self._prefs), stems.gentle_choice(self._prefs)), self) self._splitter.progress.connect(self._on_stem_progress) self._splitter.finished.connect(self._on_stems) self._splitter.failed.connect(self._on_stem_failed) @@ -470,6 +706,9 @@ class DjShelf(QWidget): 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 ---- @@ -487,6 +726,7 @@ class DjShelf(QWidget): outer.addWidget(grip) self.speed = {} + self.volume = {} self.speed_label = {} self.records = {} self.play_buttons = {} @@ -498,12 +738,52 @@ class DjShelf(QWidget): self.bpm_labels = {} self.bpm_notes = {} self.pitch_boxes = {} + self.mult_buttons = {} self._compact_hidden = [] self._big_records = {} + def fader_title(text, v): + label = QLabel(text) + label.setStyleSheet(f"color: {v.color.name()}; font-size: 10px;" + " font-weight: bold; letter-spacing: 1px;") + 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(64) + 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%") slider = QSlider(Qt.Orientation.Vertical) @@ -519,9 +799,10 @@ class DjShelf(QWidget): 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(1, 1) + col.setStretch(2, 1) holder = QWidget() holder.setLayout(col) holder.setFixedWidth(64) @@ -617,6 +898,7 @@ class DjShelf(QWidget): nums.addWidget(bpm) nums.addWidget(note) line.addLayout(nums) + line.addWidget(self._mult_switch(v)) pitch = QCheckBox("Keep pitch") pitch.setChecked(True) pitch.setFocusPolicy(Qt.FocusPolicy.NoFocus) @@ -634,38 +916,89 @@ class DjShelf(QWidget): return line a, b = self.views + row.addWidget(volume_col(a)) row.addWidget(speed_col(a)) row.addWidget(deck_col(a)) 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) centre.addLayout(info_row(a)) self.lanes = WaveLanes(self) centre.addWidget(self.lanes, stretch=1) centre.addLayout(info_row(b)) fader = QHBoxLayout() - fader.setContentsMargins(60, 2, 60, 6) + fader.setContentsMargins(0, 2, 0, 4) + fader.addStretch(1) left = QLabel("A") left.setStyleSheet(f"color: {COLORS['A'].name()}; font-weight: bold;") right = QLabel("B") right.setStyleSheet(f"color: {COLORS['B'].name()}; font-weight: bold;") - self.crossfader = QSlider(Qt.Orientation.Horizontal) - self.crossfader.setRange(0, 1000) - self.crossfader.setValue(500) - self.crossfader.setStyleSheet(_slider_qss(None, vertical=False)) - self.crossfader.setToolTip("Crossfader (double-click: centre)") + self.crossfader = Crossfader() self.crossfader.valueChanged.connect(lambda value: setattr(self.mixer, "crossfader", value / 1000)) - self.crossfader.mouseDoubleClickEvent = lambda e: self.crossfader.setValue(500) fader.addWidget(left) - fader.addWidget(self.crossfader, stretch=1) + fader.addWidget(self.crossfader, stretch=3) fader.addWidget(right) + fader.addStretch(1) centre.addLayout(fader) row.addLayout(centre, stretch=1) row.addWidget(deck_col(b)) row.addWidget(speed_col(b)) + row.addWidget(volume_col(b)) self._small_records = {} 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 set_mult(self, view: DeckView, mult: float): + 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) + def resizeEvent(self, event): super().resizeEvent(event) compact = self.height() < COMPACT_HEIGHT @@ -709,6 +1042,15 @@ class DjShelf(QWidget): for v in self.views: self._refresh_deck(v) + 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))) @@ -769,6 +1111,7 @@ class DjShelf(QWidget): view.stem_note = "Loading…" self.speed[view.name].setValue(0) self.vocal_sliders[view.name].setValue(0) + self.set_mult(view, 1.0) try: art = tagging.read_embedded_artwork(track.location) except Exception: # noqa: BLE001 — art is never worth a failure @@ -872,13 +1215,13 @@ class DjShelf(QWidget): 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.bpm * other.deck.speed - view.deck.speed = analysis.sync_ratio(view.bpm, target) + target = other.beat_bpm * other.deck.speed + view.deck.speed = analysis.sync_speed(view.beat_bpm, target) self._show_speed(view) if view.deck.playing and other.deck.playing: - own = analysis.beat_phase(self.heard_seconds(view), view.offset, view.bpm) - theirs = analysis.beat_phase(self.heard_seconds(other), other.offset, other.bpm) - shift = analysis.phase_shift(own, theirs, view.bpm) + 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") @@ -924,12 +1267,11 @@ class DjShelf(QWidget): 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.bpm: - self.bpm_labels[view.name].setText(f"{view.bpm * speed:.1f}") + 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 "" - saved = " · calculated, saved" if view.bpm_saved else "" - self.bpm_notes[view.name].setText(f"BPM · original {view.bpm:.1f}{change}{saved}") + self.bpm_notes[view.name].setText(f"BPM · original {view.beat_bpm:.1f}{change}") else: self.bpm_labels[view.name].setText("–") self.bpm_notes[view.name].setText("BPM") @@ -943,6 +1285,16 @@ class DjShelf(QWidget): 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: deck = v.deck if deck.ended and not v.counted and v.track is not None: @@ -957,8 +1309,8 @@ class DjShelf(QWidget): self.lanes.update() def _refresh_bpm_only(self, view: DeckView): - if view.bpm: - self.bpm_labels[view.name].setText(f"{view.bpm * view.deck.speed:.1f}") + 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: diff --git a/lintunes/gui/main_window.py b/lintunes/gui/main_window.py index 21a69e9..2ff93e1 100644 --- a/lintunes/gui/main_window.py +++ b/lintunes/gui/main_window.py @@ -160,6 +160,7 @@ class MainWindow(QMainWindow): layout.addWidget(self._transport) # DJ mode (Round 93): the shelf is made the first time it opens. self._dj = None + self._dj_prep_worker = None self._dj_on = False self._dj_anim = None self._dj_resize_from = None @@ -302,6 +303,7 @@ class MainWindow(QMainWindow): self._cassette.show_friend_menu) self._sidebar.playlist_selected.connect(self._show_playlist) self._sidebar.tree.export_requested.connect(self._export_playlist) + self._sidebar.tree.dj_prepare_requested.connect(self._prepare_playlist_for_dj) self._sidebar.art.download_art_requested.connect( lambda tid: self._download_album_art([tid])) self._content.currentChanged.connect(self._update_totals) @@ -314,6 +316,7 @@ class MainWindow(QMainWindow): view.table.download_art_requested.connect(self._download_album_art) view.table.identify_requested.connect(self._identify_tracks) view.table.bpm_requested.connect(self._calculate_bpm) + view.table.dj_prepare_requested.connect(self._prepare_for_dj) view.table.remove_from_library_requested.connect( lambda ids: self._delete_tracks(ids, delete_files=False)) view.table.delete_from_library_requested.connect( @@ -668,12 +671,16 @@ class MainWindow(QMainWindow): for worker in (self._andtunes_planner, self._andtunes_worker, self._export_worker, self._url_worker, self._bpm_worker, self._server_check, - self._upload_worker): + self._upload_worker, self._dj_prep_worker): if worker is not None and worker.busy(): return worker return None def _confirm_cancel_sync(self): + if self._dj_prep_worker is not None and self._dj_prep_worker.busy(): + # What's prepared is kept; the song being split is abandoned. + self._dj_prep_worker.cancel() + return if self._bpm_worker is not None and self._bpm_worker.busy(): # Nothing to lose: what's been measured is kept. self._bpm_worker.cancel() @@ -2077,6 +2084,77 @@ class MainWindow(QMainWindow): return self._enqueue_identify(tracks) + # ---- Prepare for DJ ---- + + def _prepare_playlist_for_dj(self, pid: str): + playlist = self._manager.library.playlists.get(pid) + if playlist is not None: + self._prepare_for_dj(list(playlist.track_ids)) + + def _prepare_for_dj(self, track_ids: list[int]): + """BPM and vocals for these songs now, so they load onto a deck + instantly — with the vocals model chosen in Preferences › DJ.""" + from lintunes.dj import stems + from lintunes.dj.prepare import DjPrepWorker + if self._busy_worker() is not None: + self.statusBar().showMessage( + "Wait for the current transfer to finish first", 6000) + return + if not stems.available(): + QMessageBox.information( + self, "Prepare for DJ", + "Separating vocals needs Demucs, which isn't set up on this " + "computer. It's a one-time ~1 GB download:\n\n" + stems.setup_command()) + return + items, seen = [], set() + for tid in track_ids: + track = self._manager.library.tracks.get(tid) + if track is None or not track.location or tid in seen: + continue + seen.add(tid) + label = (f"{track.artist} — {track.name}" if track.artist + else track.name) or Path(track.location).name + items.append((tid, track.location, label, bool(track.bpm))) + if not items: + return + model = stems.model_choice(self._prefs) + worker = DjPrepWorker(items, model, stems.gentle_choice(self._prefs), self) + self._dj_prep_bpm = {} + worker.bpm_found.connect(self._dj_prep_bpm.__setitem__) + worker.progress.connect(self._on_dj_prep_progress) + worker.finished.connect(self._on_dj_prep_finished) + self._dj_prep_worker = worker + self._sync_label.setText(f"Preparing for DJ ({stems.MODELS[model][0]})…") + self._sync_progress.setRange(0, len(items)) + self._sync_progress.setValue(0) + self._sync_cancel.show() + self._sync_label.show() + self._sync_progress.show() + worker.start() + + def _on_dj_prep_progress(self, done: int, total: int, label: str): + self._sync_progress.setRange(0, total) + self._sync_progress.setValue(done) + if label: + short = label if len(label) <= 48 else label[:47] + "…" + where = f"{done + 1} of {total} · " if total > 1 else "" + self._sync_label.setText(f"DJ {where}{short}") + + def _on_dj_prep_finished(self, summary: dict): + self._hide_sync_widgets() + found, self._dj_prep_bpm = self._dj_prep_bpm, {} + if found: + self._manager.set_tracks_bpm(found) + msg = (f"Prepared {summary['done']} song(s) for DJ" + f" · {summary['split']} vocals separated · {summary['bpm']} BPM found") + if summary["cancelled"]: + msg = "Prepare for DJ stopped — " + msg[0].lower() + msg[1:] + if summary["failed"]: + msg += f" · {summary['failed']} couldn't be done" + if not summary["cancelled"]: + sounds.play_done(self._prefs) + self.statusBar().showMessage(msg, 12000) + # ---- Calculate BPM ---- def _calculate_bpm(self, track_ids: list[int]): @@ -2323,6 +2401,8 @@ class MainWindow(QMainWindow): shelf.setFixedHeight(0) shelf.show() shelf.start() + shelf.set_visualizer(self._transport._visualizer) + self._sidebar.art.hide() # room for the lists instead self._animate_shelf(0, target) else: shelf = self._dj @@ -2333,7 +2413,7 @@ class MainWindow(QMainWindow): def _ensure_dj(self): if self._dj is None: from lintunes.gui.dj_shelf import DjShelf - shelf = DjShelf(self._manager) + shelf = DjShelf(self._manager, self._prefs) shelf.hide() shelf.message.connect(lambda msg: self.statusBar().showMessage(msg, 8000)) shelf.decks_changed.connect(self._on_decks_changed) @@ -2394,8 +2474,10 @@ class MainWindow(QMainWindow): def _dj_closed(self): if self._dj_on: return # reopened mid-close + self._dj.set_visualizer(None) self._dj.stop() self._dj.hide() + self._sidebar.art.show() self.player.set_suspended(False) self._transport.set_dj_mode(False) diff --git a/lintunes/gui/preferences_dialog.py b/lintunes/gui/preferences_dialog.py index a160db7..63053b6 100644 --- a/lintunes/gui/preferences_dialog.py +++ b/lintunes/gui/preferences_dialog.py @@ -125,6 +125,7 @@ class PreferencesDialog(QDialog): ("Appearance", [self._build_general_group(), self._build_visualizer_group(), self._build_colors_group()]), + ("DJ", [self._build_dj_group()]), ("Integrations", [self._build_lastfm_group(), self._build_acoustid_group(), self._build_web_server_group()])): @@ -252,6 +253,40 @@ class PreferencesDialog(QDialog): row.addWidget(preview) return group + # ---- DJ ---- + + def _build_dj_group(self) -> QGroupBox: + """Vocals separation (Demucs): which model, and how hard it may run + the CPU. Both apply to the next song split.""" + from lintunes.dj import stems + group = QGroupBox("Separating vocals") + form = QFormLayout(group) + model = QComboBox() + for key, (label, cost) in stems.MODELS.items(): + model.addItem(f"{label} — {cost}", key) + model.setCurrentIndex(max(0, model.findData(stems.model_choice(self._prefs)))) + model.currentIndexChanged.connect( + lambda _i: self._prefs.set("dj_stem_model", model.currentData())) + form.addRow("Model:", model) + gentle = QCheckBox("Gentle on the CPU: a quarter of the cores, lowest " + "priority (cooler, a little slower)") + gentle.setChecked(stems.gentle_choice(self._prefs)) + gentle.toggled.connect(lambda on: self._prefs.set("dj_stem_gentle", on)) + form.addRow("", gentle) + if stems.available(): + note = QLabel("Demucs is set up. Songs are split when they load onto " + "a deck, or ahead of time with a playlist's or " + "song's “Prepare for DJ”. Splits are kept.") + else: + note = QLabel("Demucs isn't set up on this computer (a one-time ~1 GB " + "download). In a terminal:\n" + stems.setup_command()) + note.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + note.setWordWrap(True) + form.addRow("", note) + self._dj_model_combo = model + self._dj_gentle_check = gentle + return group + # ---- Wrapped ---- def _build_wrapped_group(self) -> QGroupBox: diff --git a/lintunes/gui/sidebar.py b/lintunes/gui/sidebar.py index 5b11bfa..e5345be 100644 --- a/lintunes/gui/sidebar.py +++ b/lintunes/gui/sidebar.py @@ -182,13 +182,15 @@ class SidebarPanel(QWidget): split = not self.friend_button.isHidden() joint = ("border-top-right-radius: 0; border-bottom-right-radius: 0;" if split else "") + # The transport buttons' corners (8 px), not the dialogs' 4. self.library_button.setStyleSheet(theme.button_face_qss( - "QPushButton", base, extra=f"text-align: left; padding-left: 10px; {joint}", + "QPushButton", base, radius=8, + extra=f"text-align: left; padding-left: 10px; {joint}", checked_color=lit, checked_text=checked_text)) # The ▾ is the same button cut off at the end: same face, no left # border (it shares the Library button's), square where they meet. self.friend_button.setStyleSheet(theme.button_face_qss( - "QPushButton", base, + "QPushButton", base, radius=8, extra="padding: 0; border-left: none; border-top-left-radius: 0;" " border-bottom-left-radius: 0;")) @@ -474,6 +476,7 @@ class PlaylistTree(QTreeWidget): playlist_selected = pyqtSignal(str) # persistent_id export_requested = pyqtSignal(str) # persistent_id + dj_prepare_requested = pyqtSignal(str) # persistent_id # A friend's playlist I follow (key "cassette::"). followed_selected = pyqtSignal(str) unfollow_requested = pyqtSignal(str) @@ -846,7 +849,7 @@ class PlaylistTree(QTreeWidget): new_playlist = menu.addAction("New Playlist") new_smart = menu.addAction("New Smart Playlist") new_folder = menu.addAction("New Playlist Folder") - rename = delete = edit_smart = export = None + rename = delete = edit_smart = export = dj_prepare = None if kind in ("playlist", "folder", "smart"): menu.addSeparator() if kind == "smart": @@ -856,6 +859,7 @@ class PlaylistTree(QTreeWidget): if kind in ("playlist", "smart"): menu.addSeparator() export = menu.addAction("Export Playlist…") + dj_prepare = menu.addAction("Prepare for DJ") chosen = menu.exec(self.viewport().mapToGlobal(pos)) if chosen is None: @@ -873,6 +877,8 @@ class PlaylistTree(QTreeWidget): self._manager.create_folder(name.strip(), 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: + self.dj_prepare_requested.emit(pid) elif rename is not None and chosen is rename: self.editItem(item, 0) elif delete is not None and chosen is delete: diff --git a/lintunes/gui/track_table.py b/lintunes/gui/track_table.py index 1ff5df2..333131a 100644 --- a/lintunes/gui/track_table.py +++ b/lintunes/gui/track_table.py @@ -707,6 +707,7 @@ class TrackTableView(QTableView): download_art_requested = pyqtSignal(list) # selected track ids identify_requested = pyqtSignal(list) # selected track ids bpm_requested = pyqtSignal(list) # selected track ids + dj_prepare_requested = pyqtSignal(list) # selected track ids remove_from_library_requested = pyqtSignal(list) # track ids, file kept delete_from_library_requested = pyqtSignal(list) # track ids, file trashed @@ -1028,7 +1029,7 @@ class TrackTableView(QTableView): locations = self.selected_locations() reveal_action = copy_path_action = download_art_action = None - identify_action = bpm_action = None + identify_action = bpm_action = dj_action = None if locations: menu.addSeparator() reveal_action = menu.addAction("Reveal in File Browser") @@ -1037,6 +1038,9 @@ class TrackTableView(QTableView): # Fingerprinting reads the audio, so this needs a file on disk. identify_action = menu.addAction("Identify Track…") bpm_action = menu.addAction("Calculate BPM") + dj_action = menu.addAction("Prepare for DJ") + dj_action.setToolTip("Work out BPM and separate vocals now, so " + "these load instantly onto a deck") # Single track only: one click shouldn't open a browser tab per song. # Needs no file, so it's offered for a dangling location too. @@ -1092,6 +1096,8 @@ class TrackTableView(QTableView): self.identify_requested.emit(self.selected_track_ids()) elif bpm_action is not None and chosen is bpm_action: self.bpm_requested.emit(self.selected_track_ids()) + elif dj_action is not None and chosen is dj_action: + self.dj_prepare_requested.emit(self.selected_track_ids()) elif youtube_action is not None and chosen is youtube_action: track = self.model_.track_at(self.selected_source_rows()[0]) QDesktopServices.openUrl(youtube_search_url(track)) diff --git a/lintunes/gui/transport.py b/lintunes/gui/transport.py index 880765e..18257f2 100644 --- a/lintunes/gui/transport.py +++ b/lintunes/gui/transport.py @@ -633,7 +633,7 @@ class TransportBar(QWidget): def _apply_dj_button_style(self): bg = theme.gray(theme.gray_value(self._prefs, "color_button")) self.dj_button.setStyleSheet(theme.button_face_qss( - "QToolButton#djButton", bg, extra="padding: 0;", + "QToolButton#djButton", bg, radius=8, extra="padding: 0;", checked_color=bg.darker(theme.CHECKED_DARKER))) def _on_dj_button(self, on: bool): diff --git a/lintunes/gui/visualizer.py b/lintunes/gui/visualizer.py index 2160189..a40eeb4 100644 --- a/lintunes/gui/visualizer.py +++ b/lintunes/gui/visualizer.py @@ -107,6 +107,7 @@ class VisualizerWidget(QWidget): self._timer.setInterval(FRAME_MS) self._timer.timeout.connect(self._advance_frame) + self._own_player = player player.audio_buffer.connect(self._on_buffer) player.playing_changed.connect(self._on_playing_changed) player.track_changed.connect(self._on_track_changed) @@ -159,6 +160,23 @@ class VisualizerWidget(QWidget): self._sync_timer() self.update() + # ---- DJ mode ---- + + def set_dj_source(self, source): + """DJ mode (Round 94): draw the decks' mix instead of the player. + ``source`` answers ``position_ms()`` (what's heard) and + ``is_playing()``; its audio arrives through ``feed_dj``. None goes + back to the player.""" + self._player = source if source is not None else self._own_player + self._reset_stream() + self._sync_timer() + + def feed_dj(self, mono, rate, start_ms): + self._feed(mono, rate, start_ms) + + def dj_playing_changed(self): + self._sync_timer() + # ---- audio intake ---- def _on_buffer(self, buf): diff --git a/tests/test_round70.py b/tests/test_round70.py index d7f5641..5530d5a 100644 --- a/tests/test_round70.py +++ b/tests/test_round70.py @@ -239,7 +239,7 @@ class TestPreferencesPages: dialog = PreferencesDialog(Preferences(tmp_path), _FakeLastFm()) names = [dialog.pages_list.item(i).text() for i in range(dialog.pages_list.count())] - assert names == ["General", "Appearance", "Integrations"] + assert names == ["General", "Appearance", "DJ", "Integrations"] # DJ: Round 94 dialog.pages_list.setCurrentRow(2) assert dialog.pages.currentIndex() == 2 PreferencesDialog._last_page = 0 diff --git a/tests/test_round93.py b/tests/test_round93.py index 2488b73..f84e15c 100644 --- a/tests/test_round93.py +++ b/tests/test_round93.py @@ -189,6 +189,8 @@ def shelf(qapp, monkeypatch): made.tracks = tracks yield made made.stop() + from PyQt6 import sip + sip.delete(made) # deleted here, never by a GC on some thread class TestShelf: @@ -196,7 +198,6 @@ class TestShelf: a, _ = shelf.views _loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 10), 124.0, 0.1) shelf._manager.set_tracks_bpm.assert_called_once_with({1: 124}) - assert "calculated, saved" in shelf.bpm_notes["A"].text() assert shelf.bpm_labels["A"].text() == "124.0" def test_sync_matches_tempo_and_then_beats(self, shelf): diff --git a/tests/test_round94.py b/tests/test_round94.py new file mode 100644 index 0000000..a5f73a1 --- /dev/null +++ b/tests/test_round94.py @@ -0,0 +1,209 @@ +"""Round 94: DJ mode, round two — the crossfader (big handle, a middle line, +a snap to centre), ½×/1×/2× beat counting, scrubbing by the waveform, deck +volumes, the air horn, the visualizer fed by the mix, vocals models and +gentle CPU use, and Prepare for DJ.""" + +import threading +from types import SimpleNamespace +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 import analysis, stems +from lintunes.dj.audio import RATE, Mixer +from tests.test_round93 import _clicks, _loaded, shelf # noqa: F401 — the fixture + + +def _mouse(kind, x, y=20.0): + return QMouseEvent(kind, QPointF(x, y), QPointF(x, y), Qt.MouseButton.LeftButton, + Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier) + + +class TestCrossfader: + def test_snaps_to_the_middle_when_close(self, qapp): + from lintunes.gui.dj_shelf import Crossfader + fader = Crossfader() + fader.resize(428, fader.height()) # 400 px of travel + lo, hi = fader._span() + near = lo + (hi - lo) * 0.52 + fader.mousePressEvent(_mouse(QEvent.Type.MouseButtonPress, lo)) + fader.mouseMoveEvent(_mouse(QEvent.Type.MouseMove, near)) + assert fader.value() == 500 + fader.mouseMoveEvent(_mouse(QEvent.Type.MouseMove, lo + (hi - lo) * 0.6)) + assert fader.value() == 600 + fader.mouseReleaseEvent(_mouse(QEvent.Type.MouseButtonRelease, 0)) + assert fader.value() == 600 + + def test_handle_is_big(self, qapp): + from lintunes.gui.dj_shelf import Crossfader + assert Crossfader.HANDLE.height() >= 40 and Crossfader.HANDLE.width() > 20 + + +class TestBeatCounting: + def test_double_time_shows_and_syncs_at_twice(self, shelf): + a, b = shelf.views + _loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 5), 124.0, 0.1) + _loaded(shelf, b, shelf.tracks[1], _clicks(62, 0.1, 5), 62.0, 0.1) + shelf.set_mult(b, 2.0) + assert shelf.bpm_labels["B"].text() == "124.0" + shelf.sync(b) + assert b.deck.speed == pytest.approx(1.0) + shelf.set_mult(b, 0.5) + assert shelf.bpm_labels["B"].text() == "31.0" + + def test_sync_speed(self): + assert analysis.sync_speed(118, 124) == pytest.approx(124 / 118) + # 62 counted against 124 is an octave apart: speed stays near 1 + assert analysis.sync_speed(62, 124) == pytest.approx(1.0) + + +def test_dragging_a_waveform_scrubs(shelf): + a, _ = shelf.views + _loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 5), 124.0, 0.1) + lanes = shelf.lanes + lanes.resize(800, 100) + lanes.mousePressEvent(_mouse(QEvent.Type.MouseButtonPress, 400, 10)) + assert a.deck.scratch_rate == 0.0 + lanes.mouseMoveEvent(_mouse(QEvent.Type.MouseMove, 500, 10)) # drag right + assert a.deck.scratch_rate < 0 # → backwards + lanes.mouseReleaseEvent(_mouse(QEvent.Type.MouseButtonRelease, 500, 10)) + assert a.deck.scratch_rate is None + + +def test_deck_volume_and_horn(): + mixer = Mixer() + mixer.crossfader = 0.0 + mixer.a.volume = 0.5 + assert mixer.deck_gain(mixer.a) == pytest.approx(0.5) + mixer.horn.on = True + 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 + + +def test_the_visualizer_draws_the_mix(shelf, qapp): + from lintunes.gui.visualizer import VisualizerWidget + player = MagicMock() + viz = VisualizerWidget(player, MagicMock(get=lambda k, d=None: d)) + shelf.set_visualizer(viz) + assert viz._player is shelf.visual + shelf.mixer.render(2048) + shelf._tick() + assert viz._total == 2048 + shelf.set_visualizer(None) + assert viz._player is player + from PyQt6 import sip + sip.delete(viz) + + +def test_the_volume_fader_is_perceptual(shelf): + a, _ = shelf.views + shelf.volume["A"].setValue(50) + assert 0.0 < a.deck.volume < 0.5 # Qt's log curve: half travel is quieter + + +class TestStems: + def _song(self, tmp_path, monkeypatch): + song = tmp_path / "a.mp3" + song.write_bytes(b"x") + monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache")) + return str(song) + + def _make(self, folder): + folder.mkdir(parents=True, exist_ok=True) + for name in stems.STEMS: + (folder / f"{name}.flac").write_bytes(b"f") + + def test_the_best_split_wins_and_old_splits_count(self, tmp_path, monkeypatch): + song = self._song(tmp_path, monkeypatch) + root = stems.cache_root() / stems.cache_key(song) + self._make(root) # Round 93's layout + assert stems.cached(song)["vocals"].parent == root + assert stems.cached(song, "htdemucs") is not None + assert stems.cached(song, "htdemucs_ft") is None + self._make(root / "htdemucs_ft") + assert stems.cached(song)["vocals"].parent.name == "htdemucs_ft" + + def test_gentle_uses_a_quarter_and_lowest_priority(self, tmp_path, monkeypatch): + song = self._song(tmp_path, monkeypatch) + monkeypatch.setattr(stems, "available", lambda: True) + monkeypatch.setattr(stems.os, "cpu_count", lambda: 8) + seen = {} + + class Proc: + stderr = SimpleNamespace(read=lambda n: b"") + def wait(self): + return 1 + + def popen(cmd, **kw): + seen.update(cmd=cmd, env=kw["env"]) + return Proc() + monkeypatch.setattr(stems.subprocess, "Popen", popen) + with pytest.raises(OSError): + stems.split(song, "htdemucs_fast", True) + assert seen["env"]["OMP_NUM_THREADS"] == "2" + assert "--overlap" in seen["cmd"] and "0.1" in seen["cmd"] + assert stems.threads(False) == 8 + + def test_prefs_choices(self): + prefs = {"dj_stem_model": "htdemucs_ft"} + assert stems.model_choice(prefs) == "htdemucs_ft" + assert stems.model_choice({"dj_stem_model": "nonsense"}) == stems.DEFAULT_MODEL + assert stems.gentle_choice({}) is True + + +def test_prepare_for_dj(monkeypatch, qapp): + import gc + from lintunes.dj import prepare + # A worker thread that allocates can run the garbage collector *on + # that thread*, destroying earlier tests' leftover widgets off the GUI + # thread — a segfault later. Collect them here, on this one, first. + gc.collect() + monkeypatch.setattr(prepare.stems, "available", lambda: True) + monkeypatch.setattr(prepare.stems, "cached", lambda path, model=None: None) + split = [] + monkeypatch.setattr(prepare.stems, "split", + lambda path, model, gentle, tick, cancel: split.append((path, model, gentle)) or tick(50)) + monkeypatch.setattr(prepare.bpm_detect, "detect_file", lambda path: 120) + worker = prepare.DjPrepWorker([(1, "/a.mp3", "A", False), (2, "/b.mp3", "B", True)], + "htdemucs_ft", True) + found, done = [], threading.Event() + result = {} + worker.bpm_found.connect(lambda tid, bpm: found.append((tid, bpm))) + worker.finished.connect(lambda summary: (result.update(summary), done.set())) + worker.start() + for _ in range(200): + qapp.processEvents() + if done.wait(0.01): + break + worker._thread.join(5) # never let the worker go while its thread emits + qapp.processEvents() + assert found == [(1, 120)] + assert split == [("/a.mp3", "htdemucs_ft", True), ("/b.mp3", "htdemucs_ft", True)] + assert result["done"] == 2 and result["split"] == 2 and not result["cancelled"] + + +def test_dj_mode_hides_the_sidebar_art(qapp, tmp_path, monkeypatch): + from lintunes.gui.main_window import MainWindow + from lintunes.library_manager import LibraryManager + from lintunes.models.library import Library + from lintunes.preferences import Preferences + monkeypatch.setattr("lintunes.gui.main_window.load_config", lambda: {}) + monkeypatch.setattr("lintunes.gui.main_window.save_config", lambda c: None) + window = MainWindow(LibraryManager(Library(), tmp_path), Preferences(tmp_path)) + try: + window.show() + window.set_dj_mode(True) + assert window._sidebar.art.isHidden() + window.set_dj_mode(False) + window._dj_anim.stop() + window._dj_closed() + assert not window._sidebar.art.isHidden() + finally: + window.close()