Files
lintunes/tests/test_round94.py
T

213 lines
8.6 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)
tone = (np.sin(np.arange(RATE) / RATE * 2 * np.pi * 400) * 20000).astype(np.int16)
mixer.horn.set_sample(np.stack([tone, tone], axis=1)) # a 1 s "horn"
mixer.horn.press()
loud = mixer.render(4410)
assert np.abs(loud).max() > 0.1
mixer.horn.release()
mixer.render(RATE)
assert mixer.horn.render(64) is None # it has played out
assert len(mixer.tap) == 2 and mixer.rendered == 4410 + RATE
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)
monkeypatch.setattr(stems, "audio_hash", lambda path: None)
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()