Files
lintunes/tests/test_round94.py
T
trav 6d6a0c2385 v0.64.0: DJ mode round two — vocals models, Prepare for DJ, deck volumes, ½×/2×, scrubbing, air horn
- 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.
2026-10-17 03:13:59 -07:00

210 lines
8.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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()