Files
lintunes/tests/test_round93.py
T
trav 279f51fba9 v0.66.0: DJ mode's djay layout, loops, a sync that sets once, a real horn, a smooth slide
- Records in the top corners, each deck's controls beside them facing the
  middle, the zoomed A-over-B waveforms in the centre, and a whole-song
  overview per deck below (click to jump, drag to move) with the
  crossfader between them.
- Loops per deck: Loop plus a 1/32 to 8 beat stepper; a loop starts on
  the next beat and shows on both waveforms.
- Sync sets this deck to the other's tempo once, and stays lit only while
  that still holds.
- The air horn plays like a real one: every press a fresh blast, held it
  carries the note, let go it stops.
- Opening and closing DJ mode slides a picture over the final layout
  instead of re-laying-out the window every frame (the flicker).
- Tests: garbage is collected on the main thread after each test, which
  stops a rare segfault in the full run.
2026-10-17 22:19:59 -07:00

347 lines
13 KiB
Python

"""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()
from PyQt6 import sip
sip.delete(made) # deleted here, never by a GC on some thread
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 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) == 380 # the full layout at least (Round 96)
# ---- 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()
# ---- Round 93 fixes: nothing starts the main player; sync always clickable ----
def test_a_suspended_player_cannot_be_started(qapp, tmp_path):
from tests.test_round29 import _FakeSink, _local_track, _player
tracks = [_local_track(tmp_path, i) for i in range(1, 4)]
player = _player(qapp, tracks)
sink = _FakeSink()
player.set_sink(sink)
player.set_suspended(True)
player.play_queue([1, 2, 3], 0)
player.toggle_play()
player.next()
assert player.current_track is None and not sink.loads
player.set_suspended(False)
player.play_queue([1, 2, 3], 0)
assert player.current_track.track_id == 1
def test_return_on_a_song_does_nothing_in_dj_mode(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.set_dj_mode(True)
assert window.player.suspended
window.set_dj_mode(False)
window._dj_anim.stop()
window._dj_closed()
assert not window.player.suspended
finally:
window.close()
def test_sync_is_clickable_with_one_deck_and_says_why(shelf):
a, _ = shelf.views
_loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 5), 124.0, 0.1)
assert shelf.sync_buttons["A"].isEnabled()
said = []
shelf.message.connect(said.append)
shelf.sync(a)
assert said and "Deck B" in said[0]
assert a.deck.speed == 1.0