v0.63.0: DJ mode — two decks, sync, keep-pitch speed, scratching, vocal stems

View > DJ Mode (or the turntable button under BPM) parts the window under
the transport boxes and opens a dark shelf: a record per deck (drag a song
on to load it; drag the record to scratch), play/pause and Sync to other
track beside it, a ±8% speed fader on each edge, Keep pitch, the two
waveforms stacked around one playhead, a vocals/instrumental slider and
the crossfader. Deck A is blue, Deck B orange; loaded songs are tagged in
the lists.

Its own engine (lintunes/dj): whole-song decode, tempo refined to 0.01
BPM plus the first beat (exact on synthetic kicks), WSOLA time-stretch or
varispeed, a QAudioSink on its own thread. Sync matches tempo and, while
both play, nudges the beats into line. A missing BPM is calculated and
saved. Vocals come from Demucs, run once per song in the background and
cached; Demucs lives in its own venv.
This commit is contained in:
2026-10-17 02:06:45 -07:00
parent 7ad51ab4dc
commit 57cc5d5289
14 changed files with 2428 additions and 3 deletions
+43
View File
@@ -341,6 +341,49 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
`tests/kaleidostrobe_golden.npz` was recorded from the emulated original
and `test_round84` holds the port to it byte for byte.
- **`lintunes/dj/`** + **`gui/dj_shelf.py`** — DJ mode (Round 93; View ›
DJ Mode or the turntable button under BPM). The window parts **under the
row of transport boxes** (`TransportBar.insert_shelf`: the Library button's
header row slides down with the lists) and a dark shelf shows in the gap,
animated open and closed (`MainWindow.set_dj_mode`). Default height leaves
~15 songs below (at least the full 320 px layout), the grip resizes it
between ~28 and ~5 songs below (`height_bounds`), saved as config.json's
`dj_shelf_height`; under 200 px it's one compact strip. **Manual, like DJ
software**: a deck loads only by dragging a song onto its record (the
record darkens and gets the deck's rim; replacing a deck that's playing
above 50 % gain asks first), and a song that ends just stops — no queue,
so the main transport, seek bar, space and arrows are greyed/ignored, and
the main player pauses when DJ mode opens. Deck A is blue and Deck B
orange, every control included; loaded songs get a DECK A/B tag in every
track list (`track_table.deck_tag`). **Its own engine**, because Qt's
player can't change tempo without pitch or play backwards: `dj/loader.py`
decodes the whole song (ffmpeg CLI, int16 stereo 44.1 kHz, ~50 MB per 5
min) and analyses it — `bpm_detect`'s tempo, refined to 0.01 BPM by which
tempo folds the onsets sharpest (`analysis.beat_grid`; 0.1 BPM off smears
two minutes of beats by a fifth of a beat), and the first beat from a
~3 ms energy-rise onset (`onset_times`; bpm_detect's 1024-sample flux
smears *when* by tens of ms). Both measured exact on synthetic kicks. A
file with no BPM gets it saved (`set_tracks_bpm`). `dj/audio.py` is pure
numpy: keep pitch = WSOLA (1024/512, ±256 search), Keep pitch off =
varispeed, scratching = varispeed at the hand's angular rate (one turn =
1.8 s, a 33⅓ record; letting go is normal speed at once). The mixer is
constant-power crossfade × master (the volume slider through Qt's curve).
`dj/output.py` feeds a QAudioSink from **its own QThread** (100 ms
buffered), so GUI painting can't starve it; it must stop before Qt quits
(`aboutToQuit`, `closeEvent`), and **tests stub it** (conftest
`_no_dj_sound`) — the decks would otherwise play out loud. Sync ("Sync to
other track", per deck): tempo to the other deck's (the nearest octave);
if both are playing, then the shortest beat nudge (`phase_shift`, never
more than half a beat). The waveforms are drawn in *heard* time around one
shared playhead, so synced beats sit exactly above each other. **Vocals**:
Demucs (htdemucs, two stems) splits each loaded song once in the
background into `$XDG_CACHE_HOME/lintunes/stems/<key>/` (path+size+mtime);
the slider blends vocals/instrumental live. Demucs + CPU PyTorch (~1 GB)
live in their own venv, `$XDG_DATA_HOME/lintunes/demucs`
(`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.
- **`lintunes/importers/itunes_importer.py`** — parses the iTunes XML plist.
Remaps Mac `file:///Volumes/...` paths to the local `--music-root` with
case/Unicode-normalization fuzzy matching (macOS is case-insensitive + NFD vs
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.62.0"
__version__ = "0.63.0"
+8
View File
@@ -0,0 +1,8 @@
"""DJ mode (Round 93): two decks, a crossfader, tempo sync and vocal stems.
Its own little audio engine, separate from Player: Qt's player can neither
change tempo without changing pitch nor play backwards for a scratch, so a
deck holds its song decoded in memory and the mixer renders both decks into
one QAudioSink. Pure numpy in ``analysis`` and ``audio`` (tested offline);
Qt only in ``output`` (the sink's thread), ``loader`` and the GUI shelf.
"""
+153
View File
@@ -0,0 +1,153 @@
"""What a deck needs to know about its song: peaks to draw, its tempo to a
tenth of a BPM, where the beats fall, and how to sync to the other deck.
Tempo comes from ``bpm_detect`` (spectral flux + autocorrelation), but at its
full 0.1 BPM resolution rather than the whole number the library stores: an
integer can be 0.5 BPM out, which drifts a quarter beat in 30 seconds. The
file's own BPM, when there is one, only settles which octave the answer is
in (the detector can land on half or double).
"""
import numpy as np
from lintunes import bpm_detect
PEAKS_PER_SECOND = 200
def peaks(samples: np.ndarray, rate: int,
per_second: int = PEAKS_PER_SECOND) -> np.ndarray:
"""Loudest absolute sample (0..1) in each 1/per_second of a song.
``samples`` is (frames, channels) int16 or float."""
if len(samples) == 0:
return np.zeros(0, np.float32)
data = np.abs(samples.astype(np.float32)).max(axis=1)
if samples.dtype == np.int16:
data /= 32768.0
step = max(1, rate // per_second)
count = len(data) // step
if count == 0:
return np.array([data.max()], np.float32)
return data[:count * step].reshape(count, step).max(axis=1)
def mono_11k(samples: np.ndarray, rate: int = 44100) -> np.ndarray:
"""A mono float32 copy at ~11025 Hz (every 4th frame of a 4-frame
average), the rate bpm_detect works at."""
data = samples.astype(np.float32).mean(axis=1)
if samples.dtype == np.int16:
data /= 32768.0
factor = max(1, round(rate / bpm_detect.SAMPLE_RATE))
count = len(data) // factor
return data[:count * factor].reshape(count, factor).mean(axis=1)
def precise_bpm(mono: np.ndarray, file_bpm: int | None = None) -> float | None:
"""The tempo to 0.1 BPM, folded into the octave the file's BPM names
(when it has one) or into 70–180."""
bpm = bpm_detect.estimate_bpm(mono[:bpm_detect.SAMPLE_RATE
* bpm_detect.MAX_SECONDS])
if bpm is None:
return float(file_bpm) if file_bpm else None
target = float(file_bpm) if file_bpm else None
if target:
candidates = [bpm / 4, bpm / 2, bpm, bpm * 2, bpm * 4]
bpm = min(candidates, key=lambda b: abs(np.log2(b / target)))
else:
while bpm < 70:
bpm *= 2
while bpm > 180:
bpm /= 2
return round(bpm, 1)
def onset_times(mono: np.ndarray, sr: int = bpm_detect.SAMPLE_RATE,
window: int = 128, hop: int = 32) -> tuple[np.ndarray, np.ndarray]:
"""(strength, seconds): how sharply the log energy rises, every ~3 ms.
bpm_detect's spectral flux is right for *tempo* but its 1024-sample
window smears *when* a beat lands by tens of ms; this short energy
window places it within a few. A rise between two windows is timed at
the later window's middle, where an onset entering it peaks."""
data = np.asarray(mono, dtype=np.float64)
if len(data) <= window + hop:
return np.zeros(0), np.zeros(0)
total = np.concatenate([[0.0], np.cumsum(data * data)])
starts = np.arange(0, len(data) - window, hop)
energy = (total[starts + window] - total[starts]) / window
level = np.log1p(1e4 * energy)
rise = np.maximum(np.diff(level), 0.0)
times = (np.arange(len(rise)) + 1) * hop / sr + window / (2 * sr)
return rise, times
def _fold(rise, times, bpm: float, bins: int):
"""Onsets folded over one beat, smoothed around the circle."""
beat = 60.0 / bpm
phase = (times % beat) / beat
folded = np.bincount((phase * bins).astype(int) % bins, weights=rise,
minlength=bins)
kernel = np.array([0.25, 0.5, 1.0, 0.5, 0.25])
padded = np.concatenate([folded[-2:], folded, folded[:2]])
return np.convolve(padded, kernel, mode="valid")
def beat_grid(mono: np.ndarray, bpm: float, bins: int = 256,
search: float = 0.25, step: float = 0.01) -> tuple[float, float]:
"""(bpm, offset): the tempo refined to 0.01 BPM and the seconds from the
start to the first beat. A tempo 0.1 BPM out smears two minutes of beats
across a fifth of a beat, so of the tempos within ``search`` of the
estimate, the one whose folded onsets peak sharpest wins; the peak is
the first beat (within ~4 ms on a synthetic kick track)."""
if not bpm:
return bpm, 0.0
limit = bpm_detect.SAMPLE_RATE * bpm_detect.MAX_SECONDS
rise, times = onset_times(mono[:limit])
if len(rise) == 0 or not np.any(rise):
return bpm, 0.0
best = (-1.0, bpm, None)
for candidate in np.arange(bpm - search, bpm + search + step / 2, step):
smooth = _fold(rise, times, candidate, bins)
sharpness = smooth.max() / max(smooth.mean(), 1e-12)
if sharpness > best[0]:
best = (sharpness, float(candidate), smooth)
_, refined, smooth = best
offset = (int(np.argmax(smooth)) + 0.5) / bins * 60.0 / refined
return round(refined, 2), offset
def beat_offset(mono: np.ndarray, bpm: float) -> float:
"""Seconds to the first beat at exactly ``bpm`` (no refining)."""
if not bpm:
return 0.0
rise, times = onset_times(mono[:bpm_detect.SAMPLE_RATE * bpm_detect.MAX_SECONDS])
if len(rise) == 0:
return 0.0
smooth = _fold(rise, times, bpm, 256)
return (int(np.argmax(smooth)) + 0.5) / 256 * 60.0 / bpm
def sync_ratio(own_bpm: float, target_bpm: float) -> float:
"""The speed that makes ``own_bpm`` play at ``target_bpm``: of the
straight ratio and its half/double, the one nearest normal speed (a
70 BPM song syncs to a 140 BPM one at its own speed, beat on every
other beat)."""
if not own_bpm or not target_bpm:
return 1.0
ratio = target_bpm / own_bpm
return min((ratio, ratio * 2, ratio / 2), key=lambda r: abs(np.log2(r)))
def beat_phase(position_s: float, offset_s: float, bpm: float) -> float:
"""Where in its beat a song is, 0..1."""
if not bpm:
return 0.0
return ((position_s - offset_s) * bpm / 60.0) % 1.0
def phase_shift(own_phase: float, target_phase: float, own_bpm: float) -> float:
"""Seconds (of the song's own time) to move it so its beat lines up with
the target's, by the shortest way: never more than half a beat."""
if not own_bpm:
return 0.0
delta = (target_phase - own_phase + 0.5) % 1.0 - 0.5
return delta * 60.0 / own_bpm
+246
View File
@@ -0,0 +1,246 @@
"""The decks and the mix, as pure numpy: render N frames, get N frames.
A deck holds its song in memory as int16 stereo at 44.1 kHz (about 50 MB for
five minutes) — plus, once Demucs has split it, the vocals and the
instrumental, which the vocals slider blends. It plays three ways:
- **keep pitch** (the default): WSOLA time-stretch, so a sped-up song stays
in its key. 1024-frame windows, half overlapping; each next window is the
one within ±256 frames of where the tempo says to read that best continues
the last (normalised cross-correlation), so the seams don't click.
- **pitch follows tempo** (Keep pitch off): plain varispeed, read at the
speed with linear interpolation, like a turntable's pitch fader.
- **scratching**: varispeed at whatever rate the hand on the record gives,
backwards included; letting go goes straight back to normal speed.
The mixer adds both decks after the crossfader's constant-power curve and the
master volume, and clips. Everything here runs on the sink's thread; the GUI
only sets plain attributes (one assignment each, so never torn).
"""
import numpy as np
RATE = 44100
CHANNELS = 2
WINDOW = 1024
HOP = WINDOW // 2
SEARCH = 256
SPEED_RANGE = 0.08 # the speed faders' ±8 %
_HANN = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(WINDOW) / WINDOW)).astype(np.float32)
class Source:
"""A song in memory: the original, and the stems once they exist."""
def __init__(self, original: np.ndarray, rate: int = RATE):
self.original = original # (frames, 2) int16
self.rate = rate
self.vocals: np.ndarray | None = None
self.instrumental: np.ndarray | None = None
@property
def frames(self) -> int:
return len(self.original)
@property
def seconds(self) -> float:
return self.frames / self.rate
def has_stems(self) -> bool:
return self.vocals is not None and self.instrumental is not None
def read(self, start: int, count: int, vocal_mix: float) -> np.ndarray:
"""``count`` frames from ``start`` as float32, silence past either
end. ``vocal_mix`` −1 vocals only, 0 both, +1 instrumental only."""
out = np.zeros((count, CHANNELS), np.float32)
lo, hi = max(0, start), min(self.frames, start + count)
if hi <= lo:
return out
dest = slice(lo - start, hi - start)
if self.has_stems() and abs(vocal_mix) > 1e-3:
v_gain = min(1.0, 1.0 - vocal_mix)
i_gain = min(1.0, 1.0 + vocal_mix)
n = min(hi, len(self.vocals), len(self.instrumental))
if n > lo:
d = slice(lo - start, n - start)
out[d] = (self.vocals[lo:n].astype(np.float32) * v_gain
+ self.instrumental[lo:n].astype(np.float32) * i_gain)
else:
out[dest] = self.original[lo:hi]
out *= 1.0 / 32768.0
return out
class Deck:
"""One turntable. Attributes the GUI sets: ``playing``, ``speed``,
``keep_pitch``, ``vocal_mix``, ``scratch_rate`` (None when no hand is on
the record). ``position`` is in source frames (float)."""
def __init__(self, name: str):
self.name = name
self.source: Source | None = None
self.position = 0.0
self.playing = False
self.speed = 1.0
self.keep_pitch = True
self.vocal_mix = 0.0
self.scratch_rate: float | None = None
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
self._pending: np.ndarray | None = None # stretched, not yet emitted
self._mode = None
def load(self, source: Source | None):
self.playing = False
self.source = source
self.position = 0.0
self.ended = False
self.scratch_rate = None
self._reset()
def seek(self, frame: float):
if self.source is None:
return
self.position = float(max(0.0, min(frame, self.source.frames - 1)))
self._reset()
def _reset(self):
self._ola = None
self._last = None
self._pending = None
# ---- rendering ----
def render(self, count: int) -> np.ndarray:
src = self.source
if src is None:
return np.zeros((count, CHANNELS), np.float32)
if self.scratch_rate is not None:
return self._varispeed(count, self.scratch_rate, "scratch")
if not self.playing:
self._mode = None
return np.zeros((count, CHANNELS), np.float32)
if self.position >= src.frames:
self.playing = False
self.ended = True
return np.zeros((count, CHANNELS), np.float32)
if self.keep_pitch and abs(self.speed - 1.0) > 1e-4:
return self._stretch(count)
if abs(self.speed - 1.0) <= 1e-4:
return self._straight(count)
return self._varispeed(count, self.speed, "vari")
def _straight(self, count: int) -> np.ndarray:
if self._mode != "straight":
self._mode = "straight"
self._reset()
start = int(round(self.position))
out = self.source.read(start, count, self.vocal_mix)
self.position = start + count
return out
def _varispeed(self, count: int, rate: float, mode: str) -> np.ndarray:
if self._mode != mode:
self._mode = mode
self._reset()
src = self.source
steps = self.position + rate * np.arange(count, dtype=np.float64)
lo = int(np.floor(steps.min()))
hi = int(np.ceil(steps.max())) + 2
block = src.read(lo, hi - lo, self.vocal_mix)
idx = steps - lo
i0 = np.clip(np.floor(idx).astype(np.int64), 0, len(block) - 2)
frac = (idx - i0)[:, None].astype(np.float32)
out = block[i0] * (1 - frac) + block[i0 + 1] * frac
self.position = float(self.position + rate * count)
if self.position < 0:
self.position = 0.0
if mode == "vari" and self.position >= src.frames:
self.playing = False
self.ended = True
if mode == "scratch":
self.position = min(self.position, src.frames - 1.0)
return out
def _stretch(self, count: int) -> np.ndarray:
"""WSOLA: emit HOP frames per window until ``count`` are out."""
if self._mode != "stretch":
self._mode = "stretch"
self._reset()
src = self.source
pieces = []
made = 0
if self._pending is not None and len(self._pending):
pieces.append(self._pending)
made += len(self._pending)
while made < count:
nominal = int(round(self.position))
if self._last is None:
start = nominal
else:
natural = src.read(self._last + HOP, WINDOW, self.vocal_mix).mean(axis=1)
region = src.read(nominal - SEARCH, WINDOW + 2 * SEARCH,
self.vocal_mix).mean(axis=1)
start = nominal - SEARCH + _best_offset(region, natural)
frame = src.read(start, WINDOW, self.vocal_mix) * _HANN[:, None]
if self._ola is None:
self._ola = np.zeros((WINDOW, CHANNELS), np.float32)
self._ola += frame
pieces.append(self._ola[:HOP].copy())
made += HOP
self._ola = np.concatenate(
[self._ola[HOP:], np.zeros((HOP, CHANNELS), np.float32)])
self._last = start
self.position += HOP * self.speed
if self.position >= src.frames:
self.playing = False
self.ended = True
break
out = np.concatenate(pieces) if pieces else np.zeros((0, CHANNELS), np.float32)
if len(out) < count:
out = np.concatenate([out, np.zeros((count - len(out), CHANNELS), np.float32)])
self._pending = None
else:
self._pending = out[count:]
out = out[:count]
return out
def _best_offset(region: np.ndarray, natural: np.ndarray) -> int:
"""The offset into ``region`` where ``natural`` fits best (normalised
cross-correlation over the window's first half)."""
probe = natural[:HOP]
if not np.any(probe):
return SEARCH
corr = np.correlate(region[:len(region) - WINDOW + HOP], probe, mode="valid")
energy = np.convolve(region[:len(region) - WINDOW + HOP] ** 2,
np.ones(len(probe)), mode="valid")
score = corr / np.sqrt(np.maximum(energy, 1e-9))
return int(np.argmax(score))
def crossfade_gains(x: float) -> tuple[float, float]:
"""Constant power: 0 = all A, 1 = all B, the middle ~71 % each."""
x = min(1.0, max(0.0, x))
return float(np.cos(x * np.pi / 2)), float(np.sin(x * np.pi / 2))
class Mixer:
def __init__(self):
self.a = Deck("A")
self.b = Deck("B")
self.crossfader = 0.5
self.master = 1.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
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)
np.clip(out, -1.0, 1.0, out=out)
return out
+82
View File
@@ -0,0 +1,82 @@
"""Getting a song onto a deck: decode, analyse, report — off the GUI thread.
ffmpeg (the CLI, as everywhere else) decodes the whole file to int16 stereo
at 44.1 kHz; then the waveform's peaks, the tempo to 0.1 BPM and the first
beat's offset are worked out from that copy (no second decode). A five-
minute song takes about a second. The result arrives as one Qt signal.
"""
import subprocess
import threading
from dataclasses import dataclass
import numpy as np
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes.dj import analysis
from lintunes.dj.audio import CHANNELS, RATE, Source
@dataclass
class Loaded:
track_id: int
source: Source
peaks: np.ndarray
bpm: float | None # precise, what the deck syncs with
offset: float # seconds to the first beat
detected: bool # bpm came from the audio, not the file
def decode(path: str) -> np.ndarray:
"""The whole file as (frames, 2) int16 at 44.1 kHz. Raises OSError."""
cmd = ["ffmpeg", "-nostdin", "-v", "error", "-i", str(path), "-map", "0:a:0",
"-vn", "-ac", str(CHANNELS), "-ar", str(RATE), "-f", "s16le", "-"]
try:
result = subprocess.run(cmd, capture_output=True, timeout=300)
except (OSError, subprocess.TimeoutExpired) as e:
raise OSError(f"ffmpeg could not run: {e}") from e
if result.returncode != 0 or not result.stdout:
detail = result.stderr.decode(errors="replace").strip().splitlines()
raise OSError(detail[-1] if detail else "no audio")
data = np.frombuffer(result.stdout, dtype=np.int16)
return data[:len(data) - len(data) % CHANNELS].reshape(-1, CHANNELS)
def load(track_id: int, path: str, file_bpm: int | None) -> Loaded:
samples = decode(path)
mono = analysis.mono_11k(samples, RATE)
bpm = analysis.precise_bpm(mono, file_bpm)
offset = 0.0
if bpm:
bpm, offset = analysis.beat_grid(mono, bpm)
return Loaded(track_id=track_id, source=Source(samples), peaks=analysis.peaks(samples, RATE),
bpm=bpm, offset=offset, detected=not file_bpm and bpm is not None)
class DeckLoader(QObject):
"""One load at a time per deck; a newer request makes an older result
stale (``ticket``), so a fast second drag wins."""
loaded = pyqtSignal(str, object) # deck name, Loaded
failed = pyqtSignal(str, int, str) # deck name, track id, why
def __init__(self, name: str, parent=None):
super().__init__(parent)
self.name = name
self._ticket = 0
def request(self, track_id: int, path: str, file_bpm: int | None):
self._ticket += 1
ticket = self._ticket
def work():
try:
result = load(track_id, path, file_bpm)
except Exception as e: # noqa: BLE001 — reported, not raised
if ticket == self._ticket:
self.failed.emit(self.name, track_id, str(e) or type(e).__name__)
return
if ticket == self._ticket:
self.loaded.emit(self.name, result)
threading.Thread(target=work, daemon=True, name="lintunes-dj-load").start()
+115
View File
@@ -0,0 +1,115 @@
"""The mixer, heard: a QAudioSink fed from its own thread.
The sink lives in a QThread with its own event loop; a 5 ms timer there tops
its buffer up with whatever the mixer renders, so the GUI thread painting
records and waveforms at 60 fps can't starve it. About 100 ms is buffered:
enough to ride out a busy GUI, short enough that the crossfader and a hand
on a record still feel immediate. Created only when DJ mode opens (a
QAudioOutput made before the main window deadlocks Qt 6.10, and nothing
here should exist for someone who never opens it).
"""
import numpy as np
from PyQt6.QtCore import QObject, QThread, QTimer, pyqtSignal, pyqtSlot
from PyQt6.QtMultimedia import QAudioFormat, QAudioSink, QMediaDevices
from lintunes.dj.audio import CHANNELS, RATE
BUFFER_MS = 100
TICK_MS = 5
BYTES_PER_FRAME = 2 * CHANNELS
class _Pump(QObject):
failed = pyqtSignal(str)
def __init__(self, mixer):
super().__init__()
self.mixer = mixer
self.sink = None
self.io = None
self.timer = None
self.queued_frames = 0
@pyqtSlot()
def start(self):
fmt = QAudioFormat()
fmt.setSampleRate(RATE)
fmt.setChannelCount(CHANNELS)
fmt.setSampleFormat(QAudioFormat.SampleFormat.Int16)
device = QMediaDevices.defaultAudioOutput()
if device.isNull() or not device.isFormatSupported(fmt):
self.failed.emit("this computer's sound output can't play 44.1 kHz stereo")
return
self.sink = QAudioSink(device, fmt)
self.sink.setBufferSize(int(RATE * BUFFER_MS / 1000) * BYTES_PER_FRAME)
self.io = self.sink.start()
self.timer = QTimer()
self.timer.setInterval(TICK_MS)
self.timer.timeout.connect(self._fill)
self.timer.start()
def _fill(self):
if self.sink is None or self.io is None:
return
free = self.sink.bytesFree() // BYTES_PER_FRAME
frames = free - free % 64
if frames > 0:
pcm = self.mixer.render(frames)
data = (pcm * 32767.0).astype(np.int16).tobytes()
self.io.write(data)
size = self.sink.bufferSize() // BYTES_PER_FRAME
self.queued_frames = max(0, size - self.sink.bytesFree() // BYTES_PER_FRAME)
@pyqtSlot()
def stop(self):
if self.timer is not None:
self.timer.stop()
if self.sink is not None:
self.sink.stop()
self.sink = self.io = self.timer = None
class DjOutput(QObject):
"""Owns the thread; ``latency_frames`` is how far behind what has been
rendered the speakers are, for drawing what is *heard*."""
failed = pyqtSignal(str)
_go = pyqtSignal()
_halt = pyqtSignal()
def __init__(self, mixer, parent=None):
super().__init__(parent)
self._thread = QThread()
self._thread.setObjectName("lintunes-dj-audio")
self._pump = _Pump(mixer)
self._pump.moveToThread(self._thread)
self._go.connect(self._pump.start)
self._halt.connect(self._pump.stop)
self._pump.failed.connect(self.failed)
self._running = False
# However the app ends, the thread ends first (a QThread destroyed
# while running aborts the process).
from PyQt6.QtCore import QCoreApplication
app = QCoreApplication.instance()
if app is not None:
app.aboutToQuit.connect(self.stop)
@property
def latency_frames(self) -> int:
return self._pump.queued_frames
def start(self):
if self._running:
return
self._running = True
self._thread.start()
self._go.emit()
def stop(self):
if not self._running:
return
self._running = False
self._halt.emit()
self._thread.quit()
self._thread.wait(2000)
+163
View File
@@ -0,0 +1,163 @@
"""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/<key>/{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.
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 ``<venv>/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.
One split at a time: two would only halve each other's speed.
"""
import hashlib
import os
import re
import shutil
import subprocess
import tempfile
import threading
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
MODEL = "htdemucs"
STEMS = ("vocals", "no_vocals")
_PERCENT = re.compile(r"(\d{1,3})%\|")
def venv_dir() -> Path:
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
return Path(base) / "lintunes" / "demucs"
def python() -> Path:
return venv_dir() / "bin" / "python"
def available() -> bool:
return python().is_file()
def setup_command() -> str:
"""What makes the venv, for the "not set up" message."""
v = venv_dir()
return (f"python3 -m venv {v} && {v}/bin/pip install torch --index-url "
f"https://download.pytorch.org/whl/cpu && {v}/bin/pip install numpy demucs")
def cache_root() -> Path:
base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
return Path(base) / "lintunes" / "stems"
def cache_key(path: str) -> str | None:
try:
st = os.stat(path)
except OSError:
return None
raw = f"{os.path.abspath(path)}|{st.st_size}|{int(st.st_mtime)}"
return hashlib.sha1(raw.encode()).hexdigest()[:20]
def cached(path: str) -> dict[str, Path] | None:
"""{"vocals": …, "no_vocals": …} when this song was split already."""
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
def parse_progress(text: str) -> int | None:
found = _PERCENT.findall(text)
return int(found[-1]) if found else None
class StemSplitter(QObject):
"""A queue of songs to split, one Demucs run at a time."""
progress = pyqtSignal(str, int) # path, percent
finished = pyqtSignal(str, object) # path, {"vocals": Path, …}
failed = pyqtSignal(str, str) # path, why
def __init__(self, parent=None):
super().__init__(parent)
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)."""
hit = cached(path)
if hit is not None:
self.finished.emit(path, hit)
return
with self._lock:
if path in self._queue:
return
self._queue.append(path)
start = not self._busy
self._busy = True
if start:
threading.Thread(target=self._run, daemon=True,
name="lintunes-demucs").start()
def _run(self):
while True:
with self._lock:
if not self._queue:
self._busy = False
return
path = self._queue.pop(0)
try:
result = self._split(path)
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)
+991
View File
@@ -0,0 +1,991 @@
"""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, 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
COMPACT_HEIGHT = 200
DEFAULT_ROWS_BELOW = 15
MIN_ROWS_BELOW, MAX_ROWS_BELOW = 5, 28
GRIP = 8
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.bpm_saved = False
self.counted = False
@property
def color(self) -> QColor:
return COLORS[self.name]
# ---- 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
def _deck_button_qss(name: str) -> str:
top, bottom = FACES[name]
color = COLORS[name].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}; }}")
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)
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)
# source seconds at each pixel edge
edges = heard + (np.arange(w + 1) / w - 0.5) * WINDOW_SECONDS * 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))
if view.bpm:
beat = 60.0 / view.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_SECONDS * 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))
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()
# ---- 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)
_stems_error = pyqtSignal(str, str)
def __init__(self, manager, parent=None):
super().__init__(parent)
self._manager = manager
self.mixer = Mixer()
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(self._on_stem_failed)
self._splitter = stems.StemSplitter(self)
self._splitter.progress.connect(self._on_stem_progress)
self._splitter.finished.connect(self._on_stems)
self._splitter.failed.connect(self._on_stem_failed)
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)
# ---- layout ----
def _build(self):
outer = QVBoxLayout(self)
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.speed_label = {}
self.records = {}
self.play_buttons = {}
self.sync_buttons = {}
self.vocal_sliders = {}
self.stem_labels = {}
self.titles = {}
self.states = {}
self.bpm_labels = {}
self.bpm_notes = {}
self.pitch_boxes = {}
self._compact_hidden = []
self._big_records = {}
def speed_col(v):
col = QVBoxLayout()
col.setSpacing(4)
top = QLabel("+8%")
bottom = QLabel("−8%")
slider = QSlider(Qt.Orientation.Vertical)
slider.setRange(-int(SPEED_RANGE * 10000), int(SPEED_RANGE * 10000))
slider.setValue(0)
slider.setStyleSheet(_slider_qss(v.name, vertical=True))
slider.setToolTip(f"Deck {v.name} speed (double-click: back to 0)")
slider.valueChanged.connect(lambda value, v=v: self._on_speed(v, value))
slider.mouseDoubleClickEvent = lambda e, s=slider: s.setValue(0)
label = QLabel("0.0%")
label.setStyleSheet(f"color: {v.color.name()};")
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(1, 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 deck_col(v):
holder = QWidget()
col = QVBoxLayout(holder)
col.setContentsMargins(0, 0, 0, 0)
col.setSpacing(8)
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
col.addWidget(record, stretch=1)
controls = QWidget()
buttons = QHBoxLayout(controls)
buttons.setContentsMargins(0, 0, 0, 0)
buttons.setSpacing(8)
play = QToolButton()
play.setIcon(QIcon(_play_icon(False)))
play.setIconSize(QSize(16, 16))
play.setFixedSize(56, 34)
play.setToolTip(f"Play / pause Deck {v.name}")
play.clicked.connect(lambda _=False, v=v: self.toggle(v))
sync = QPushButton("Sync to other track")
sync.setFixedHeight(34)
sync.setToolTip("Match the other deck's tempo; while both play, "
"also line up the beats (the smallest nudge)")
sync.clicked.connect(lambda _=False, v=v: self.sync(v))
for w in (play, sync):
w.setStyleSheet(_deck_button_qss(v.name))
buttons.addWidget(play)
buttons.addWidget(sync, stretch=1)
self.play_buttons[v.name] = play
self.sync_buttons[v.name] = sync
col.addWidget(controls)
vocals = QWidget()
vcol = QVBoxLayout(vocals)
vcol.setContentsMargins(0, 0, 0, 0)
vcol.setSpacing(2)
ends = QHBoxLayout()
for text in ("Vocals", "Both", "Instrumental"):
lab = QLabel(text)
lab.setStyleSheet(f"color: {DIM}; font-size: 10px;")
ends.addWidget(lab)
if text != "Instrumental":
ends.addStretch()
vcol.addLayout(ends)
slider = QSlider(Qt.Orientation.Horizontal)
slider.setRange(-100, 100)
slider.setValue(0)
slider.setStyleSheet(_slider_qss(v.name, vertical=False))
slider.valueChanged.connect(lambda value, v=v: setattr(v.deck, "vocal_mix", value / 100))
slider.mouseDoubleClickEvent = lambda e, s=slider: s.setValue(0)
vcol.addWidget(slider)
note = QLabel("")
note.setStyleSheet(f"color: {DIM}; font-size: 10px;")
vcol.addWidget(note)
self.vocal_sliders[v.name] = slider
self.stem_labels[v.name] = note
col.addWidget(vocals)
self._compact_hidden += [controls, vocals]
holder.setFixedWidth(220)
self._big_records[v.name] = holder
return holder
def info_row(v):
line = QHBoxLayout()
line.setSpacing(12)
texts = QVBoxLayout()
texts.setSpacing(0)
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)
texts.addWidget(state)
texts.addWidget(title)
line.addLayout(texts, stretch=1)
nums = QVBoxLayout()
nums.setSpacing(0)
bpm = QLabel("–")
bpm.setAlignment(Qt.AlignmentFlag.AlignRight)
bpm.setStyleSheet(f"color: {v.color.name()}; font-size: 22px; font-weight: bold;")
note = QLabel("BPM")
note.setAlignment(Qt.AlignmentFlag.AlignRight)
note.setStyleSheet(f"color: {DIM}; font-size: 10px;")
nums.addWidget(bpm)
nums.addWidget(note)
line.addLayout(nums)
pitch = QCheckBox("Keep pitch")
pitch.setChecked(True)
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))
line.addWidget(pitch)
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._compact_hidden += [pitch, note]
return line
a, b = self.views
row.addWidget(speed_col(a))
row.addWidget(deck_col(a))
centre = QVBoxLayout()
centre.setSpacing(6)
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)
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.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(right)
centre.addLayout(fader)
row.addLayout(centre, stretch=1)
row.addWidget(deck_col(b))
row.addWidget(speed_col(b))
self._small_records = {}
for v in self.views:
self._refresh_deck(v)
def resizeEvent(self, event):
super().resizeEvent(event)
compact = self.height() < COMPACT_HEIGHT
for w in self._compact_hidden:
w.setVisible(not compact)
for holder in self._big_records.values():
holder.setFixedWidth(max(60, self.height() - 30) if compact else 220)
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.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 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):
view.deck.load(None)
view.track = track
view.peaks = None
view.bpm = None
view.offset = 0.0
view.counted = False
view.bpm_saved = False
view.stem_note = "Loading…"
self.speed[view.name].setValue(0)
self.vocal_sliders[view.name].setValue(0)
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 _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():
view.stem_note = "Vocals: waiting to separate…"
self._splitter.request(view.track.location)
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)
def _on_load_failed(self, view: DeckView, why: str):
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 _on_stem_progress(self, path: str, percent: int):
for v in self._views_for(path):
v.stem_note = f"Separating vocals… {percent}%"
self._refresh_note(v)
def _on_stems(self, path: str, files: dict):
views = self._views_for(path)
if not views:
return
for v in views:
v.stem_note = "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))
threading.Thread(target=work, daemon=True, name="lintunes-dj-stems").start()
def _apply_stems(self, path: str, pair):
for v in self._views_for(path):
src = v.deck.source
if src is not None:
src.vocals, src.instrumental = pair
v.stem_note = "Vocals separated"
self._refresh_note(v)
def _on_stem_failed(self, path: str, why: str):
for v in self._views_for(path):
v.stem_note = f"Couldn't separate vocals: {why}"
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 or other.deck.source is None:
self.message.emit("Sync needs a song on both decks.")
return
if not view.bpm or not other.bpm:
self.message.emit("Sync needs both songs' tempo, and one has no beat to find.")
return
target = other.bpm * other.deck.speed
view.deck.speed = analysis.sync_ratio(view.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)
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
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)
has = view.deck.source is not None and view.deck.source.has_stems()
self.vocal_sliders[view.name].setEnabled(has)
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.bpm:
self.bpm_labels[view.name].setText(f"{view.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}")
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.sync_buttons[view.name].setEnabled(loaded and self.other(view).deck.source is not None)
self._refresh_note(view)
def _tick(self):
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()
def _refresh_bpm_only(self, view: DeckView):
if view.bpm:
self.bpm_labels[view.name].setText(f"{view.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 = 320 # 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
+168
View File
@@ -158,6 +158,12 @@ class MainWindow(QMainWindow):
self._transport = TransportBar(self.player, manager, self._prefs,
cast=self._cast, airplay=self._airplay)
layout.addWidget(self._transport)
# DJ mode (Round 93): the shelf is made the first time it opens.
self._dj = None
self._dj_on = False
self._dj_anim = None
self._dj_resize_from = None
self._transport.dj_toggled.connect(self.set_dj_mode)
splitter = QSplitter(Qt.Orientation.Horizontal)
# The handle is the gap between the playlists and the songs: as wide
@@ -484,6 +490,11 @@ class MainWindow(QMainWindow):
view_menu = bar.addMenu("&View")
self._add_action(view_menu, "Toggle Column Browser", "Ctrl+B",
self._library_view.toggle_browser)
view_menu.addSeparator()
self._dj_action = QAction("DJ Mode", self)
self._dj_action.setCheckable(True)
self._dj_action.toggled.connect(self.set_dj_mode)
view_menu.addAction(self._dj_action)
track_menu = bar.addMenu("&Track")
self._add_action(track_menu, "Get Info", "Ctrl+I", self._info_for_current_view)
@@ -2272,6 +2283,8 @@ class MainWindow(QMainWindow):
def play_pause(self):
"""Play/pause like iTunes: with nothing cued, start the visible
view's tracks (from the selected row, else the top)."""
if getattr(self, "_dj_on", False):
return # each deck has its own play button
if self.player.current_track is not None:
self.player.toggle_play()
return
@@ -2283,6 +2296,157 @@ class MainWindow(QMainWindow):
start = selected[0].row() if selected else 0
self._play_from_view(view, ids, start)
# ---- DJ mode ----
ANIMATE_MS = 350
def set_dj_mode(self, on: bool):
"""Open or close the DJ shelf: the window parts under the row of
transport boxes and the shelf shows in the gap; closing plays the
same thing backwards. The main player pauses while it's open."""
on = bool(on)
if on == self._dj_on:
return
self._dj_on = on
if self._dj_action.isChecked() != on:
self._dj_action.blockSignals(True)
self._dj_action.setChecked(on)
self._dj_action.blockSignals(False)
from lintunes.gui import track_table
if on:
shelf = self._ensure_dj()
if self.player.is_playing():
self.player.pause()
target = self._dj_target_height()
self._transport.set_dj_mode(True, self._dj_titles())
track_table.deck_tag = self._deck_tag
shelf.set_master(self._dj_master())
shelf.setFixedHeight(0)
shelf.show()
shelf.start()
self._animate_shelf(0, target)
else:
shelf = self._dj
track_table.deck_tag = None
self._animate_shelf(shelf.height(), 0, done=self._dj_closed)
self._refresh_tables()
def _ensure_dj(self):
if self._dj is None:
from lintunes.gui.dj_shelf import DjShelf
shelf = DjShelf(self._manager)
shelf.hide()
shelf.message.connect(lambda msg: self.statusBar().showMessage(msg, 8000))
shelf.decks_changed.connect(self._on_decks_changed)
shelf.resize_requested.connect(self._on_dj_resize)
shelf.resize_finished.connect(self._on_dj_resize_done)
shelf.resize_reset.connect(self._on_dj_resize_reset)
self._transport.volume_level_changed.connect(
lambda _level: shelf.set_master(self._dj_master()))
self._transport.insert_shelf(shelf)
self._dj = shelf
return self._dj
def _dj_master(self) -> float:
"""The volume slider as linear gain, through Qt's curve, so a
position is as loud in DJ mode as out of it."""
from PyQt6.QtMultimedia import QAudio
return QAudio.convertVolume(
self._transport.volume_level(),
QAudio.VolumeScale.LogarithmicVolumeScale,
QAudio.VolumeScale.LinearVolumeScale)
def _dj_geometry(self) -> tuple[int, int, int]:
"""(viewport with the shelf closed, row height, current shelf)."""
table = self._content.currentWidget().table
row = table.verticalHeader().defaultSectionSize()
current = self._dj.height() if self._dj is not None and self._dj.isVisible() else 0
return table.viewport().height() + current, row, current
def _dj_bounds(self) -> tuple[int, int]:
from lintunes.gui.dj_shelf import height_bounds
viewport, row, _ = self._dj_geometry()
return height_bounds(viewport, row)
def _dj_target_height(self) -> int:
from lintunes.gui.dj_shelf import default_height
viewport, row, _ = self._dj_geometry()
low, high = self._dj_bounds()
saved = load_config().get("dj_shelf_height")
target = int(saved) if isinstance(saved, (int, float)) else default_height(viewport, row)
return max(low, min(high, target))
def _animate_shelf(self, start: int, end: int, done=None):
from PyQt6.QtCore import QEasingCurve, QVariantAnimation
if self._dj_anim is not None:
self._dj_anim.stop()
anim = QVariantAnimation(self)
anim.setStartValue(int(start))
anim.setEndValue(int(end))
anim.setDuration(self.ANIMATE_MS)
anim.setEasingCurve(QEasingCurve.Type.OutCubic if end > start
else QEasingCurve.Type.InCubic)
anim.valueChanged.connect(lambda v: self._dj.setFixedHeight(int(v)))
if done is not None:
anim.finished.connect(done)
self._dj_anim = anim
anim.start()
def _dj_closed(self):
if self._dj_on:
return # reopened mid-close
self._dj.stop()
self._dj.hide()
self._transport.set_dj_mode(False)
def _on_dj_resize(self, dy: int):
if self._dj_anim is not None and self._dj_anim.state() == self._dj_anim.State.Running:
return
if self._dj_resize_from is None:
self._dj_resize_from = self._dj.height()
low, high = self._dj_bounds()
self._dj.setFixedHeight(max(low, min(high, self._dj_resize_from + dy)))
def _on_dj_resize_done(self):
self._dj_resize_from = None
config = load_config()
config["dj_shelf_height"] = self._dj.height()
save_config(config)
def _on_dj_resize_reset(self):
from lintunes.gui.dj_shelf import default_height
viewport, row, _ = self._dj_geometry()
low, high = self._dj_bounds()
config = load_config()
config.pop("dj_shelf_height", None)
save_config(config)
self._animate_shelf(self._dj.height(),
max(low, min(high, default_height(viewport, row))))
def _deck_tag(self, track_id: int):
if self._dj is None:
return None
name = self._dj.deck_of(track_id)
if name is None:
return None
from lintunes.gui.dj_shelf import COLORS
return name, COLORS[name].darker(115)
def _dj_titles(self) -> str:
if self._dj is None:
return ""
names = [v.track.name for v in self._dj.views if v.track is not None]
return " × ".join(names)
def _on_decks_changed(self, _decks: dict):
if self._dj_on:
self._transport.set_dj_titles(self._dj_titles())
self._refresh_tables()
def _refresh_tables(self):
for view in (self._library_view, self._playlist_view):
view.table.viewport().update()
def _play_from_view(self, view, ids, start):
"""Start playback, recording which view it came from so the now-playing
icon (and Go to Current Song) can find the right context."""
@@ -2352,6 +2516,8 @@ class MainWindow(QMainWindow):
self._log_key(event, "space")
self.play_pause()
return True
if key in (Qt.Key.Key_Right, Qt.Key.Key_Left) and getattr(self, "_dj_on", False):
return True # no queue to step through in DJ mode
if key == Qt.Key.Key_Right:
self._log_key(event, "right")
self.player.next()
@@ -2423,6 +2589,8 @@ class MainWindow(QMainWindow):
self._cassette.shutdown()
self._cast.shutdown()
self._airplay.shutdown()
if self._dj is not None:
self._dj.stop() # its audio thread must end before Qt does
self.player.shutdown()
self.player.loudness.save()
self._manager.flush()
+31
View File
@@ -260,6 +260,32 @@ def rating_from_click(current: int, slot: int) -> int:
return 0 if new == current else new
# DJ mode's deck tags (Round 93): a callable track id -> ("A", QColor) or
# None, set by MainWindow while DJ mode is open. Every table reads it, so a
# song loaded on a deck says so wherever it is listed.
deck_tag = None
def _paint_deck_tag(painter, rect, label: str, color: QColor):
"""A small bold "DECK A" at the right end of a Name cell."""
font = painter.font()
font.setBold(True)
font.setPointSizeF(max(6.0, font.pointSizeF() * 0.8))
painter.save()
painter.setFont(font)
metrics = QFontMetrics(font)
text = f"DECK {label}"
width = metrics.horizontalAdvance(text) + 10
pill = QRect(rect.right() - width - 4, rect.top() + 3, width, rect.height() - 6)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(color)
painter.drawRoundedRect(QRectF(pill), 4, 4)
painter.setPen(QColor("white"))
painter.drawText(pill, int(Qt.AlignmentFlag.AlignCenter), text)
painter.restore()
class RatingDelegate(QStyledItemDelegate):
"""Paints the rating column as five fixed slots: ★ for each rated star
and, on the hovered cell, • for each empty slot — so the whole 1-5 range
@@ -278,6 +304,11 @@ class RatingDelegate(QStyledItemDelegate):
return
if field != "rating":
super().paint(painter, option, index)
if field == "name" and deck_tag is not None:
track = model.track_at(model.source_row(index.row()))
tag = deck_tag(track.track_id) if track is not None else None
if tag is not None:
_paint_deck_tag(painter, option.rect, *tag)
return
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
+121 -2
View File
@@ -4,8 +4,8 @@ from PyQt6.QtWidgets import (
QWidget, QFrame, QHBoxLayout, QVBoxLayout, QLabel, QToolButton, QSlider,
QPushButton, QSizePolicy, QStyle, QLayout, QSpacerItem,
)
from PyQt6.QtCore import Qt, QTimer, QEvent, QPoint, QRect, pyqtSignal
from PyQt6.QtGui import QColor, QFont
from PyQt6.QtCore import Qt, QTimer, QEvent, QPoint, QPointF, QRect, QSize, pyqtSignal
from PyQt6.QtGui import QColor, QFont, QIcon, QPainter, QPen, QPixmap
from lintunes.tap_tempo import TapTempo
from lintunes.gui.icons import transport_icon
@@ -50,6 +50,10 @@ def _box_style(bg: QColor) -> str:
for kind in ("QToolButton", "QPushButton"):
face += theme.button_face_qss(f"QFrame#transportBox > {kind}", bg,
radius=8)
# Greyed in DJ mode: flat and pale, so it reads as switched off.
for kind in ("QToolButton", "QPushButton"):
face += (f"QFrame#transportBox > {kind}:disabled {{ background:"
f" {bg.lighter(104).name()}; border-color: {bg.darker(112).name()}; }}")
return face + TILE_STYLE
@@ -86,6 +90,28 @@ def _clamp_volume(value) -> float:
return 0.8
def turntable_icon(color: QColor, size: int = 18) -> QIcon:
"""DJ mode's glyph: a small turntable — plinth, platter, tonearm."""
from PyQt6.QtCore import QRectF
pix = QPixmap(round(size * 4 / 3), size)
pix.fill(Qt.GlobalColor.transparent)
p = QPainter(pix)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
s = size / 18
pen = QPen(color, 1.5 * s)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRoundedRect(QRectF(1 * s, 1.5 * s, 22 * s, 15 * s), 2 * s, 2 * s)
p.drawEllipse(QRectF(5 * s, 4 * s, 10 * s, 10 * s))
p.setBrush(color)
p.drawEllipse(QRectF(9.2 * s, 8.2 * s, 1.6 * s, 1.6 * s))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawLine(QPointF(19.5 * s, 4 * s), QPointF(19.5 * s, 10.5 * s))
p.drawLine(QPointF(19.5 * s, 10.5 * s), QPointF(16 * s, 13 * s))
p.end()
return QIcon(pix)
class FlashButton(QToolButton):
"""Transport button: dark-gray glyph that shows the highlight color
while pressed (a quick flash on click, sustained while held). A checkable
@@ -109,9 +135,16 @@ class FlashButton(QToolButton):
def refresh_icons(self):
self._apply_icon(active=self.isDown())
def changeEvent(self, event):
super().changeEvent(event)
if event.type() == QEvent.Type.EnabledChange:
self._apply_icon()
def _apply_icon(self, active: bool = False):
show_active = active or (self.isCheckable() and self.isChecked())
color = self.palette().highlight().color() if show_active else ICON_GRAY
if not self.isEnabled():
color = QColor(ICON_GRAY).lighter(160)
self.setIcon(transport_icon(self._kind, color))
@@ -285,6 +318,8 @@ class HeaderRow(QWidget):
self.view_header: QWidget | None = None
self._split = (0, 0, 0) # list left, list right, content left
self._panel = QRect() # now-playing panel, in our coordinates
self.right: QWidget | None = None # the DJ button, under the bpm box
self._right = QRect()
def set_left(self, widget: QWidget):
self.left = widget
@@ -316,6 +351,15 @@ class HeaderRow(QWidget):
self._panel = rect
self.place()
def set_right(self, widget: QWidget, rect: QRect):
"""``widget`` sits under the bpm box, ``rect`` its column."""
if widget.parent() is not self:
widget.setParent(self)
widget.show()
self.right = widget
self._right = rect
self.place()
def resizeEvent(self, event):
super().resizeEvent(event)
self.place()
@@ -337,6 +381,9 @@ class HeaderRow(QWidget):
self.seek.setGeometry(seek_left, self.TOP_PAD,
max(0, panel.right() + 1 - seek_left),
box_h + drop - self.LIFT)
if self.right is not None and not self._right.isNull():
self.right.setGeometry(self._right.left(), self.TOP_PAD,
self._right.width(), box_h)
header = self.view_header
if header is not None:
width = max(0, seek_left - self.GAP - content_left)
@@ -359,6 +406,8 @@ class TransportBar(QWidget):
now-playing text, seek slider, boxed bpm tap button (right)."""
play_clicked = pyqtSignal() # MainWindow decides what "play" means
dj_toggled = pyqtSignal(bool)
volume_level_changed = pyqtSignal(float) # the slider, 0..1 perceptual
def __init__(self, player, manager, prefs, cast=None, airplay=None,
parent=None):
@@ -368,6 +417,7 @@ class TransportBar(QWidget):
self._cast = cast
self._scrubbing = False
self._current_track = None
self._dj_on = False
self.setMinimumHeight(BAR_HEIGHT)
outer = QVBoxLayout(self)
@@ -377,6 +427,7 @@ class TransportBar(QWidget):
# bar's minimum must not come from the panel's current width, or a
# window could never shrink past the width it last had.
outer.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)
self._outer = outer
layout = QHBoxLayout()
layout.setContentsMargins(GAP, 0, GAP, 0)
layout.setSpacing(0)
@@ -542,6 +593,18 @@ class TransportBar(QWidget):
self._header_strip = 34
self.set_header_height(34)
outer.addWidget(self._header_row)
# DJ mode's button: under the bpm box, in the header row.
self.dj_button = QToolButton()
self.dj_button.setObjectName("djButton")
self.dj_button.setCheckable(True)
self.dj_button.setToolTip("DJ mode")
self.dj_button.setIcon(turntable_icon(QColor(ICON_GRAY)))
self.dj_button.setIconSize(QSize(24, 18))
self.dj_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.dj_button.toggled.connect(self._on_dj_button)
self._dj_bpm_box = bpm_box
self._apply_dj_button_style()
self._split_widgets: tuple = ()
# Wiring
@@ -565,6 +628,56 @@ class TransportBar(QWidget):
lambda: (cast.disconnect(),
airplay is not None and airplay.disconnect()))
# ---- DJ mode ----
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;",
checked_color=bg.darker(theme.CHECKED_DARKER)))
def _on_dj_button(self, on: bool):
self._on_dj_button_icon(on)
self.dj_toggled.emit(on)
def insert_shelf(self, shelf: QWidget):
"""The DJ shelf goes between the row of boxes and the header row,
so the window parts there: the boxes stay, the Library button and
everything under it slides down."""
if self._outer.indexOf(shelf) < 0:
self._outer.insertWidget(1, shelf)
def set_dj_mode(self, on: bool, titles: str = ""):
"""Grey what DJ mode doesn't use: each deck has its own play and
position, so the main transport and seek bar would only mislead."""
for widget in (self._prev_btn, self._play_btn, self._next_btn,
self._shuffle_btn, self._repeat_btn, self._slider):
widget.setEnabled(not on)
for label in (self._elapsed_label, self._remaining_label):
label.setEnabled(not on)
if self.dj_button.isChecked() != on:
self.dj_button.blockSignals(True)
self.dj_button.setChecked(on)
self.dj_button.blockSignals(False)
self._on_dj_button_icon(on)
self._dj_on = on
if on:
self.set_dj_titles(titles)
else:
self._on_track_changed(self._current_track)
def _on_dj_button_icon(self, on: bool):
color = self.palette().highlight().color() if on else QColor(ICON_GRAY)
self.dj_button.setIcon(turntable_icon(color))
def volume_level(self) -> float:
"""The volume slider, 0..1 (perceptual, as Player takes it)."""
return self._volume_slider.value() / 100
def set_dj_titles(self, text: str):
self._title_label.setText(text or "DJ mode")
self._artist_label.setText("Drag songs onto the records" if not text else "DJ mode")
# ---- repeat ----
_REPEAT_TIPS = {"off": "Repeat: off", "all": "Repeat: all",
@@ -656,6 +769,8 @@ class TransportBar(QWidget):
row.set_panel(QRect(x_of(self._now_playing), 0,
self._now_playing.width(), row.height()))
box = self._dj_bpm_box
row.set_right(self.dj_button, QRect(x_of(box), 0, box.width(), row.height()))
if self._split_widgets:
lists, content = self._split_widgets
row.set_split(x_of(lists), x_of(lists, lists.width()),
@@ -673,6 +788,7 @@ class TransportBar(QWidget):
box.setStyleSheet(_box_style(box_bg))
self._apply_now_playing_bg()
self._apply_now_playing_font()
self._apply_dj_button_style()
self._visualizer.update() # dim-mode bar color may have changed
def _apply_now_playing_bg(self):
@@ -682,6 +798,7 @@ class TransportBar(QWidget):
def _on_volume_changed(self, value: int):
"""Slider moved: update audio live, defer the (theme-reapplying) save."""
self._player.set_volume(value / 100)
self.volume_level_changed.emit(value / 100)
self._volume_save_timer.start()
def _save_volume(self):
@@ -706,6 +823,8 @@ class TransportBar(QWidget):
def _on_track_changed(self, track):
self._current_track = track
if self._dj_on:
return # the panel names the decks' songs meanwhile
if track is None:
self._title_label.setText("")
self._artist_label.setText("")
+9
View File
@@ -26,6 +26,15 @@ def _no_real_device(monkeypatch):
monkeypatch.setattr(device_sync, "find_device", lambda: None)
@pytest.fixture(autouse=True)
def _no_dj_sound(monkeypatch):
"""DJ mode's sink never opens in a test: the mixer would play the decks
out of the real speakers (Round 93)."""
from lintunes.dj import output
monkeypatch.setattr(output.DjOutput, "start", lambda self: None)
monkeypatch.setattr(output.DjOutput, "stop", lambda self: None)
@pytest.fixture(autouse=True)
def _no_real_sound(monkeypatch):
"""No test may play the finish "tink" out loud: every test that runs an
+297
View File
@@ -0,0 +1,297 @@
"""Round 93: DJ mode — the engine (analysis, time-stretch, scratch, mix),
the shelf (loading, sync, the replace warning, deck tags) and the window
(the menu toggle, the greyed transport)."""
from types import SimpleNamespace
from unittest.mock import MagicMock
import numpy as np
import pytest
from lintunes.dj import analysis, stems
from lintunes.dj.audio import RATE, Deck, Mixer, Source, crossfade_gains
def _tone(freq=440.0, seconds=6.0, amp=12000):
t = np.arange(int(RATE * seconds)) / RATE
x = (np.sin(2 * np.pi * freq * t) * amp).astype(np.int16)
return np.stack([x, x], axis=1)
def _clicks(bpm, first, seconds=40.0):
"""A kick at every beat from ``first`` (a decaying 60 Hz thump)."""
t = np.arange(int(RATE * seconds)) / RATE
beat = 60.0 / bpm
since = np.mod(t - first, beat)
x = 0.8 * np.sin(2 * np.pi * 60 * t) * np.exp(-30 * since)
x[t < first] = 0
x = (x * 32767).astype(np.int16)
return np.stack([x, x], axis=1)
def _freq(block):
x = block[:, 0]
spectrum = np.abs(np.fft.rfft(x * np.hanning(len(x))))
return np.fft.rfftfreq(len(x), 1 / RATE)[spectrum.argmax()]
def _play(deck, seconds):
out = [deck.render(1024) for _ in range(int(seconds * RATE / 1024))]
return np.concatenate(out)
# ---- analysis ----
class TestAnalysis:
@pytest.mark.parametrize("bpm,first", [(124.0, 0.15), (118.0, 0.05)])
def test_tempo_and_first_beat(self, bpm, first):
samples = _clicks(bpm, first)
mono = analysis.mono_11k(samples)
estimate = analysis.precise_bpm(mono)
refined, offset = analysis.beat_grid(mono, estimate)
assert abs(refined - bpm) < 0.05
assert abs(offset - first) < 0.01
def test_file_bpm_picks_the_octave(self):
mono = analysis.mono_11k(_clicks(124.0, 0.1))
assert abs(analysis.precise_bpm(mono, file_bpm=62) - 62) < 0.5
def test_sync_ratio_takes_the_nearest_octave(self):
assert analysis.sync_ratio(118, 124) == pytest.approx(124 / 118)
assert analysis.sync_ratio(70, 140) == pytest.approx(1.0)
assert analysis.sync_ratio(0, 120) == 1.0
def test_phase_shift_is_the_shortest_way(self):
# 0.1 behind → forward a tenth of a beat; 0.9 behind → back 0.1
assert analysis.phase_shift(0.2, 0.3, 120) == pytest.approx(0.05)
assert analysis.phase_shift(0.95, 0.05, 120) == pytest.approx(0.05)
assert analysis.phase_shift(0.05, 0.95, 120) == pytest.approx(-0.05)
def test_peaks(self):
p = analysis.peaks(_tone(seconds=1.0), RATE)
assert len(p) == analysis.PEAKS_PER_SECOND
assert 0.3 < p.max() <= 1.0
# ---- the engine ----
class TestDeck:
def test_keep_pitch_changes_tempo_not_pitch(self):
deck = Deck("A")
deck.load(Source(_tone()))
deck.speed, deck.keep_pitch, deck.playing = 1.06, True, True
out = _play(deck, 3.0)
assert abs(_freq(out[RATE:2 * RATE]) - 440) < 3
assert deck.position / RATE == pytest.approx(3.0 * 1.06, abs=0.05)
# no clicks: no step bigger than the sine's own steepest
steepest = 2 * np.pi * 440 / RATE * 12000 / 32768
assert np.abs(np.diff(out[4096:, 0])).max() <= steepest * 1.1
def test_pitch_follows_speed_when_not_kept(self):
deck = Deck("A")
deck.load(Source(_tone()))
deck.speed, deck.keep_pitch, deck.playing = 1.06, False, True
out = _play(deck, 2.0)
assert abs(_freq(out[RATE // 2:RATE + RATE // 2]) - 440 * 1.06) < 3
def test_scratch_runs_backwards_and_holding_stops(self):
deck = Deck("A")
deck.load(Source(_tone()))
deck.seek(RATE * 2)
deck.scratch_rate = -1.0
deck.render(4410)
assert deck.position == pytest.approx(RATE * 2 - 4410)
deck.scratch_rate = 0.0
held = deck.render(1024)
assert deck.position == pytest.approx(RATE * 2 - 4410)
assert np.ptp(held) < 0.01
def test_a_song_that_ends_stops(self):
deck = Deck("A")
deck.load(Source(_tone(seconds=0.2)))
deck.playing = True
_play(deck, 0.5)
assert deck.ended and not deck.playing
def test_vocals_slider_blends_the_stems(self):
src = Source(_tone())
src.vocals = _tone(300.0)
src.instrumental = _tone(1000.0)
deck = Deck("A")
deck.load(src)
deck.playing = True
deck.vocal_mix = -1.0
assert abs(_freq(_play(deck, 0.5)) - 300) < 5
deck.vocal_mix = 1.0
assert abs(_freq(_play(deck, 0.5)) - 1000) < 5
def test_crossfader_is_constant_power():
a, b = crossfade_gains(0.5)
assert a == pytest.approx(b) and a * a + b * b == pytest.approx(1.0)
assert crossfade_gains(0.0) == pytest.approx((1.0, 0.0))
mixer = Mixer()
mixer.crossfader, mixer.master = 1.0, 0.5
assert mixer.deck_gain(mixer.a) == pytest.approx(0.0, abs=1e-9)
assert mixer.deck_gain(mixer.b) == pytest.approx(0.5)
def test_stems_progress_and_cache_key(tmp_path, monkeypatch):
assert stems.parse_progress(" 12%|██ | 3/25 [00:01] 47%|████") == 47
assert stems.parse_progress("loading") is None
song = tmp_path / "a.mp3"
song.write_bytes(b"x")
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
assert stems.cached(str(song)) is None
folder = stems.cache_root() / stems.cache_key(str(song))
folder.mkdir(parents=True)
for name in stems.STEMS:
(folder / f"{name}.flac").write_bytes(b"f")
assert set(stems.cached(str(song))) == set(stems.STEMS)
# ---- the shelf ----
def qapp_process():
from PyQt6.QtWidgets import QApplication
QApplication.processEvents()
def _manager(tracks):
manager = MagicMock()
manager.library.tracks = {t.track_id: t for t in tracks}
return manager
def _track(tid, name, bpm=0, location="/x.mp3"):
from lintunes.models import Track
return Track(track_id=tid, name=name, artist="Test", location=location, bpm=bpm)
def _loaded(shelf, view, track, samples, bpm, offset):
from lintunes.dj.loader import Loaded
shelf.load(view, track)
shelf._on_loader_result(view.name, Loaded(
track_id=track.track_id, source=Source(samples),
peaks=analysis.peaks(samples, RATE), bpm=bpm, offset=offset,
detected=not track.bpm))
@pytest.fixture
def shelf(qapp, monkeypatch):
from lintunes.gui import dj_shelf
monkeypatch.setattr(dj_shelf.DeckLoader, "request", lambda *a, **k: None)
monkeypatch.setattr(stems, "available", lambda: False)
monkeypatch.setattr(dj_shelf.tagging, "read_embedded_artwork", lambda p: None)
tracks = [_track(1, "One"), _track(2, "Two", bpm=118)]
made = dj_shelf.DjShelf(_manager(tracks))
made.resize(1300, 330)
made.tracks = tracks
yield made
made.stop()
class TestShelf:
def test_a_missing_bpm_is_calculated_and_saved(self, shelf):
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):
a, b = shelf.views
_loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.15, 20), 124.0, 0.15)
_loaded(shelf, b, shelf.tracks[1], _clicks(118, 0.05, 20), 118.0, 0.05)
shelf.sync(b) # B not playing: tempo only
assert b.deck.speed == pytest.approx(124 / 118)
assert b.deck.position == 0
assert shelf.bpm_labels["B"].text() == "124.0"
assert "+5.1%" in shelf.bpm_notes["B"].text()
a.deck.playing = b.deck.playing = True
a.deck.position, b.deck.position = RATE * 3.0, RATE * 7.31
shelf.sync(b)
pa = analysis.beat_phase(shelf.heard_seconds(a), a.offset, a.bpm)
pb = analysis.beat_phase(shelf.heard_seconds(b), b.offset, b.bpm)
assert pa == pytest.approx(pb, abs=1e-3)
assert abs(b.deck.position / RATE - 7.31) < 0.5 * 60 / 118 # a nudge
def test_the_fader_sets_speed_and_shows_it(self, shelf):
_, b = shelf.views
_loaded(shelf, b, shelf.tracks[1], _clicks(118, 0.05, 5), 118.0, 0.05)
shelf.speed["B"].setValue(300) # +3 %
assert b.deck.speed == pytest.approx(1.03)
assert shelf.bpm_labels["B"].text() == f"{118 * 1.03:.1f}"
assert shelf.speed_label["B"].text() == "+3.0%"
def test_replacing_a_loud_playing_deck_asks(self, shelf, monkeypatch):
from lintunes.gui import dj_shelf
a, _ = shelf.views
_loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 5), 124.0, 0.1)
asked = []
monkeypatch.setattr(dj_shelf.QMessageBox, "question",
lambda *args, **kw: asked.append(1)
or dj_shelf.QMessageBox.StandardButton.Cancel)
a.deck.playing = True
shelf.mixer.crossfader = 0.0 # A full: 100 %
shelf._on_drop(a, 2)
assert asked == [1] and a.track.track_id == 1 # cancelled
shelf.mixer.crossfader = 1.0 # A faded out: no question
shelf._on_drop(a, 2)
assert asked == [1] and a.track.track_id == 2
def test_deck_of_and_the_end_counts_a_play(self, shelf):
a, _ = shelf.views
_loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 5), 124.0, 0.1)
assert shelf.deck_of(1) == "A" and shelf.deck_of(2) is None
a.deck.ended = True
shelf._tick()
shelf._tick()
shelf._manager.record_play.assert_called_once_with(1)
def test_compact_hides_the_extras(self, shelf):
# MainWindow sizes the shelf with setFixedHeight, as here.
shelf.show()
shelf.setFixedHeight(120)
qapp_process()
assert not shelf.sync_buttons["A"].isVisible()
shelf.setFixedHeight(330)
qapp_process()
assert shelf.sync_buttons["A"].isVisible()
def test_height_bounds():
from lintunes.gui.dj_shelf import default_height, height_bounds
low, high = height_bounds(1000, 22)
assert (low, high) == (1000 - 28 * 22, 1000 - 5 * 22)
assert default_height(1000, 22) == 1000 - 15 * 22
assert default_height(400, 22) == 320 # the full layout at least
# ---- the window ----
def test_dj_mode_greys_the_transport_and_ignores_space(qapp, tmp_path, monkeypatch):
from lintunes.gui import track_table
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.set_dj_mode(True)
bar = window._transport
assert not bar._play_btn.isEnabled() and not bar._slider.isEnabled()
assert bar.dj_button.isChecked() and window._dj_action.isChecked()
assert track_table.deck_tag is not None
window.player.toggle_play = MagicMock()
window.play_pause()
window.player.toggle_play.assert_not_called()
window.set_dj_mode(False)
window._dj_anim.stop()
window._dj_closed()
assert bar._play_btn.isEnabled() and not bar.dj_button.isChecked()
assert track_table.deck_tag is None
finally:
window.close()