diff --git a/CLAUDE.md b/CLAUDE.md index bd61745..2b07cac 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -433,9 +433,24 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal both waveforms. **Sync sets once** (trav's call): it puts this deck at the other's tempo and stays lit only while that holds (`_check_sync`: same song on the other deck, tempos still equal) — nothing follows anything. - **The horn** plays like a real DJ horn: every press a fresh blast (older - ones fade under it), held = the first blast's steady middle looped, let - go = a 90 ms fade. **Opening/closing slides a picture** (`SlideOverlay`): + **The horn** (Round 97, the third go — measure before touching it): the + recording's first blast wobbles in pitch and loudness on a ~0.15 s + cycle, so a loop cut against that cycle *is* a repeating beat. Held, it + loops exactly one cycle (`Horn.LOOP` 0.0779 s + 0.1494 s, the best + self-similarity, corr 0.81), levelled (envelope divided out: min/max + 0.74 → 0.88) and crossfaded equal-power; a press is a fresh blast and + cuts any still sounding in 25 ms (taps stay separate); a release, after + at least `MIN_BLAST` 0.18 s, crossfades into the recording's own ending + (`TAIL` 0.42–0.60 s: the pitch drop and fade) — a click is a 0.37 s BWAH + that trails off. `render` works in pieces that stop at each state change, + so a block's size never changes the sound. test_round97 holds all of it + to numbers (no step bigger than the recording's own, held swing > 0.7). + **Loops** (Round 97, djay's Quantize behaviour): a loop starts on the + *nearest* beat (it may be just behind — playback carries on inside it); + under a beat, it snaps to its own grid; resizing keeps the start and + folds a playhead left outside back in, so it never breaks out. The + zoomed lanes ease out only ×1.35 when grabbed, and a drag converts + pixels at the zoom it was grabbed at. **Opening/closing slides a picture** (`SlideOverlay`): the window jumps to its final layout once and a grab of what was below the transport boxes moves over it — animating the real shelf height re-laid-out the window every frame, which flickered. diff --git a/lintunes/__init__.py b/lintunes/__init__.py index 0e76357..9af5829 100644 --- a/lintunes/__init__.py +++ b/lintunes/__init__.py @@ -1,3 +1,3 @@ """LinTunes — iTunes-style music library manager and player for Linux.""" -__version__ = "0.66.0" +__version__ = "0.67.0" diff --git a/lintunes/dj/audio.py b/lintunes/dj/audio.py index b2e25db..5db1b29 100644 --- a/lintunes/dj/audio.py +++ b/lintunes/dj/audio.py @@ -261,24 +261,39 @@ def crossfade_gains(x: float) -> tuple[float, float]: class Horn: - """The air horn, played like the real thing: a real recording ("Air - Horn Hype", CC0 — see lintunes/sounds/CREDITS.md). Every press is a - fresh blast from the top; held, it carries the note (the first blast's - steady middle, ``LOOP``, looped with a crossfade); let go, it stops, - with a short natural fade — so rapid taps give BWAH-BWAH-BWAH and a - hold gives one long BWAAAAAH. A press while a blast is still ringing - starts a new one and lets the old one fade under it (no click).""" + """The air horn, played like a sampler plays a held instrument (Round + 97 — the third go; see ``set_sample`` for the measurements). - LOOP = (0.10, 0.40) # seconds: inside the first blast (0–0.48 s) - CROSSFADE = 0.03 - RELEASE = 0.09 # the fade once the button comes up - VOICES = 3 + The recording ("Air Horn Hype", CC0 — lintunes/sounds/CREDITS.md) + has a first blast whose pitch and loudness wobble on a ~0.15 s cycle, + then a natural ending: the pitch drops and it fades, 0.42–0.60 s. + + - **press**: a fresh blast from the top. A blast still sounding is + cut with a quick fade (``CUT``), so rapid taps are separate BWAHs, + never a smear. + - **held**: the blast carries on — one natural wobble cycle (``LOOP``, + found by self-similarity: the start and length where the waveform + best matches itself a lap later), looped with an equal-power + crossfade, so it neither jumps nor repeats a beat. + - **release**: after at least ``MIN_BLAST`` of blast (a click still + says BWAH), it crossfades into the recording's own ending (``TAIL``) + and stops there — the trail-off, never a hard cut and never the + rest of the phrase. + """ + + LOOP = (0.0779, 0.1494) # start, length (s) — best self-match, corr 0.81 + TAIL = (0.42, 0.60) # the blast's own ending: pitch drop and fade + MIN_BLAST = 0.18 # a click still gets this much blast + XFADE = 0.04 # the loop seam, equal power + TAIL_XFADE = 0.025 # into the ending + CUT = 0.025 # a retriggered blast's fade + VOICES = 4 LEVEL = 1.0 def __init__(self, sample: np.ndarray | None = None): self.on = False - self._held = None - self._voices: list[dict] = [] # {"pos", "gain", "fading"} + self._src = None + self._voices: list[dict] = [] if sample is not None: self.set_sample(sample) @@ -287,58 +302,134 @@ class Horn: src = sample.astype(np.float32) if sample.dtype == np.int16: src /= 32768.0 - l0, l1 = (int(t * RATE) for t in self.LOOP) - xf = int(self.CROSSFADE * RATE) - l1 = min(l1, len(src)) - held = src.copy() - if l1 - l0 > 2 * xf and l0 >= xf: - ramp = np.linspace(0, 1, xf, dtype=np.float32)[:, None] - # the loop's last xf frames fade into what comes just before - # its start, so jumping back to l0 continues seamlessly - held[l1 - xf:l1] = src[l1 - xf:l1] * (1 - ramp) + src[l0 - xf:l0] * ramp - self._held = held - self._loop = (l0, l1) + n = len(src) + a = int(self.LOOP[0] * RATE) + length = int(self.LOOP[1] * RATE) + self._loop = (a, min(n, a + length)) + # Held, that one cycle repeats — and its own loudness wobble (min/ + # max 0.74 across the cycle) repeated twenty times a held second + # reads as a pulse. So the cycle is levelled (to 0.88): its smooth + # envelope divided out, the gain itself smoothed so nothing zips. + # Only the looped stretch changes; attack and ending are untouched. + mono = src.mean(axis=1) + win = int(0.015 * RATE) + env = np.sqrt(np.convolve(mono * mono, np.ones(win) / win, mode="same")) + lo, hi = max(0, a - int(self.XFADE * RATE)), self._loop[1] + gain = np.ones(n, np.float32) + gain[lo:hi] = np.clip(env[lo:hi].mean() / np.maximum(env[lo:hi], 1e-6), 0.6, 1.6) + k = int(0.01 * RATE) + gain = np.convolve(gain, np.ones(k) / k, mode="same").astype(np.float32) + self._src = src * gain[:, None] + t0, t1 = (min(n, int(t * RATE)) for t in self.TAIL) + self._tail = (t0, t1) + # The ending fades out over its last 60 % so it lands on silence. + tail = src[t0:t1].copy() + fade = np.ones(len(tail), np.float32) + k = int(len(tail) * 0.4) + fade[k:] = np.cos(np.linspace(0, np.pi / 2, len(tail) - k)) ** 2 + self._tail_audio = tail * fade[:, None] + + # ---- the button ---- def press(self): self.on = True for voice in self._voices: - voice["fading"] = True - self._voices.append({"pos": 0, "gain": 1.0, "fading": False}) + if voice["state"] != "cut": + voice["state"] = "cut" + voice["gain"] = 1.0 + self._voices.append({"state": "held", "pos": 0, "gain": 1.0, + "tail_pos": 0, "xfade": 0}) del self._voices[:-self.VOICES] def release(self): self.on = False for voice in self._voices: - voice["fading"] = True + if voice["state"] == "held": + voice["state"] = "releasing" + + # ---- sound ---- + + def _blast(self, pos: int, count: int) -> tuple[np.ndarray, int]: + """``count`` frames of held blast from ``pos``: the recording, with + the loop's seam crossfaded (equal power) as it laps.""" + a, b = self._loop + out = np.empty((count, CHANNELS), np.float32) + xf = int(self.XFADE * RATE) + idx = pos + np.arange(count) + if b > a: + over = idx >= b + idx[over] = a + (idx[over] - a) % (b - a) + out[:] = self._src[np.minimum(idx, len(self._src) - 1)] + # within xf before the seam, fade the end out and what precedes the + # start in — so the lap lands on the start seamlessly + near = (idx >= b - xf) & (idx < b) + if near.any() and a >= xf: + t = (idx[near] - (b - xf)) / xf + out[near] = (self._src[idx[near]] * np.cos(t * np.pi / 2)[:, None] + + self._src[idx[near] - (b - a)] * np.sin(t * np.pi / 2)[:, None]) + return out, int(idx[-1]) + 1 def render(self, count: int) -> np.ndarray | None: - if self._held is None or not self._voices: + if self._src is None or not self._voices: return None - l0, l1 = self._loop out = np.zeros((count, CHANNELS), np.float32) - step = 1.0 / (self.RELEASE * RATE) kept = [] for voice in self._voices: - # the frames this voice plays: the loop while it's held - index = voice["pos"] + np.arange(count) - if not voice["fading"]: - over = index >= l1 - index[over] = l0 + (index[over] - l1) % (l1 - l0) - alive = index < len(self._held) - frames = np.zeros((count, CHANNELS), np.float32) - frames[alive] = self._held[index[alive]] - if voice["fading"]: - gain = voice["gain"] - step * np.arange(1, count + 1) - gain = np.clip(gain, 0.0, 1.0) - voice["gain"] = float(gain[-1]) - frames *= gain[:, None] - out += frames - voice["pos"] = int(index[-1]) + 1 - if voice["gain"] > 0 and voice["pos"] < len(self._held): + done = 0 + alive = True + # In pieces that stop where the voice changes state (the end of + # the minimum blast, the end of its ending), so a big block is + # as exact as a small one. + while done < count and alive: + n, alive = self._voice(voice, out, done, count - done) + done += n + if alive: kept.append(voice) self._voices = kept return out * self.LEVEL + def _voice(self, voice: dict, out: np.ndarray, at: int, room: int) -> tuple[int, bool]: + """Render up to ``room`` frames of ``voice`` into ``out[at:]``; + returns (frames rendered, still sounding).""" + state = voice["state"] + min_blast = int(self.MIN_BLAST * RATE) + if state == "releasing" and voice["pos"] >= min_blast: + state = voice["state"] = "tail" + voice["xfade"] = 0 + voice["tail_pos"] = 0 + if state in ("held", "cut") or state == "releasing": + n = room + if state == "releasing": + n = max(1, min(room, min_blast - voice["pos"])) + frames, voice["pos"] = self._blast(voice["pos"], n) + if state == "cut": + step = 1.0 / (self.CUT * RATE) + gain = np.clip(voice["gain"] - step * np.arange(1, n + 1), 0, 1) + voice["gain"] = float(gain[-1]) + frames *= gain[:, None] + out[at:at + n] += frames + return n, voice["gain"] > 0 + out[at:at + n] += frames + return n, True + # the ending: crossfade from the blast into the recording's own tail + tail = self._tail_audio + start = voice["tail_pos"] + n = min(room, len(tail) - start) + if n <= 0: + return 0, False + frames = tail[start:start + n].copy() + txf = int(self.TAIL_XFADE * RATE) + done = voice["xfade"] + if done < txf: + blast, voice["pos"] = self._blast(voice["pos"], n) + t = np.clip((np.arange(n) + done) / txf, 0, 1) + frames = (blast * np.cos(t * np.pi / 2)[:, None] + + frames * np.sin(t * np.pi / 2)[:, None]) + voice["xfade"] = done + n + out[at:at + n] += frames + voice["tail_pos"] = start + n + return n, voice["tail_pos"] < len(tail) + class Mixer: def __init__(self): diff --git a/lintunes/gui/dj_shelf.py b/lintunes/gui/dj_shelf.py index 901c11c..53df715 100644 --- a/lintunes/gui/dj_shelf.py +++ b/lintunes/gui/dj_shelf.py @@ -46,7 +46,8 @@ 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 -ZOOM_OUT = 2.0 # …and this many times more when paused or held +ZOOM_OUT = 1.35 # …and this much more when paused or held +ZOOM_EASE = 0.06 # per frame: a gentle ease, not a lurch COMPACT_HEIGHT = 200 DEFAULT_ROWS_BELOW = 15 MIN_ROWS_BELOW, MAX_ROWS_BELOW = 5, 28 @@ -427,6 +428,9 @@ class WaveLanes(QWidget): if view.deck.source is None: return self._drag = (view, event.position().x(), time.monotonic()) + # pixels → seconds at the zoom when grabbed: the lane easing out + # under the hand mustn't make the same drag go faster + self._drag_window = self._window[view.name] self._rate = 0.0 view.deck.scratch_rate = 0.0 self.setCursor(Qt.CursorShape.ClosedHandCursor) @@ -440,7 +444,7 @@ class WaveLanes(QWidget): dx = event.position().x() - x0 dt = max(1e-3, now - t0) # dragging right pulls the song back under the playhead - seconds = -dx / max(1, self.width()) * self._window[view.name] * view.deck.speed + seconds = -dx / max(1, self.width()) * self._drag_window * view.deck.speed rate = seconds / dt self._rate = 0.6 * rate + 0.4 * self._rate view.deck.scratch_rate = max(-8.0, min(8.0, self._rate)) @@ -491,7 +495,7 @@ class WaveLanes(QWidget): moving = deck.playing and deck.scratch_rate is None target = WINDOW_SECONDS if moving else WINDOW_SECONDS * ZOOM_OUT window = self._window[view.name] - window += (target - window) * 0.12 + window += (target - window) * ZOOM_EASE if abs(window - target) < 0.01: window = target self._window[view.name] = window @@ -943,7 +947,6 @@ class SlideOverlay(QWidget): pic = self.picture ratio = pic.devicePixelRatio() or 1.0 w = pic.width() / ratio - h = pic.height() / ratio if self.opening: y = round(self.shift * self.progress) p.drawPixmap(QPointF(0, y), pic) @@ -1225,7 +1228,7 @@ class DjShelf(QWidget): play.setFixedSize(44, 32) 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 = QPushButton("Sync") sync.setFixedHeight(32) sync.setToolTip("Set this deck to the other deck's tempo now; while " "both play, line the beats up too (the smallest nudge)") @@ -1425,7 +1428,10 @@ class DjShelf(QWidget): return 60.0 / view.beat_bpm if view.beat_bpm else None def set_loop(self, view: DeckView, on: bool): - """Loop on: from the next beat, ``loop_beats`` long. Off: playback + """Loop on, as djay does with Quantize: it starts on the *nearest* + beat — which may be just behind the playhead (playback carries on + inside the loop, no jump) or just ahead — ``loop_beats`` long; a + loop shorter than a beat snaps to its own finer grid. Off: playback carries on past the loop's end.""" deck = view.deck beat = self._beat(view) @@ -1436,9 +1442,9 @@ class DjShelf(QWidget): self.message.emit("A loop needs the song's beat, and none was found.") return now = self.heard_seconds(view) - k = math.ceil((now - view.offset) / beat - 1e-6) - start = view.offset + k * beat - self._place_loop(view, start) + snap = beat * min(1.0, view.loop_beats) + start = view.offset + round((now - view.offset) / snap) * snap + self._place_loop(view, max(0.0, start)) self.loop_buttons[view.name].setChecked(True) def _place_loop(self, view: DeckView, start_s: float): @@ -1451,8 +1457,14 @@ class DjShelf(QWidget): view.loop_beats = LOOP_SIZES[max(0, min(len(LOOP_SIZES) - 1, i + step))] self.loop_sizes[view.name].setText(_loop_label(view.loop_beats)) if view.deck.loop is not None and self._beat(view): - # a running loop keeps its start and takes the new length + # A running loop keeps its start and takes the new length; a + # playhead the shorter loop leaves outside is folded back in, + # so resizing never breaks out of the loop. self._place_loop(view, view.deck.loop[0] / RATE) + start, end = view.deck.loop + deck = view.deck + if deck.position >= end and end > start: + deck.seek(start + (deck.position - start) % (end - start)) def jump(self, view: DeckView, seconds: float): """Move the playhead to ``seconds`` (the overview's click/drag).""" @@ -1816,7 +1828,7 @@ class DjShelf(QWidget): # yet (an empty other deck, a tempo still being worked out) it says. self.sync_buttons[view.name].setEnabled(loaded) sync = self.sync_buttons[view.name] - sync.setText("Synced" if view.synced else "Sync to other track") + sync.setText("Synced" if view.synced else "Sync") sync.setStyleSheet(_deck_button_qss(view.name, glow=view.synced)) self._refresh_note(view) diff --git a/tests/test_round95.py b/tests/test_round95.py index 6c39798..cc380a7 100644 --- a/tests/test_round95.py +++ b/tests/test_round95.py @@ -63,7 +63,7 @@ class TestSync: assert b.synced and shelf.sync_buttons["B"].text() == "Synced" shelf.speed["B"].setValue(0) # B moved by hand: unsynced assert not b.synced - assert shelf.sync_buttons["B"].text() == "Sync to other track" + assert shelf.sync_buttons["B"].text() == "Sync" # Round 97: shorter def test_only_one_deck_follows(self, shelf): a, b = self._pair(shelf) @@ -96,7 +96,7 @@ def test_the_bundled_horn_recording_loads(qapp): from lintunes.gui.dj_shelf import _load_horn horn = Horn() _load_horn(horn) - assert horn._held is not None and len(horn._held) > RATE + assert horn._src is not None and len(horn._src) > RATE def test_the_waveform_zooms_out_while_paused(shelf): @@ -104,11 +104,11 @@ def test_the_waveform_zooms_out_while_paused(shelf): _loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 10), 124.0, 0.1) lanes = shelf.lanes lanes.resize(600, 120) - for _ in range(80): + for _ in range(200): lanes.grab() # paused: eases out - assert lanes._window["A"] == pytest.approx(16.0) + assert lanes._window["A"] == pytest.approx(8.0 * 1.35, abs=0.05) # Round 97: gentler a.deck.playing = True - for _ in range(80): + for _ in range(200): lanes.grab() assert lanes._window["A"] == pytest.approx(8.0) diff --git a/tests/test_round96.py b/tests/test_round96.py index beccd5d..6b6a891 100644 --- a/tests/test_round96.py +++ b/tests/test_round96.py @@ -48,7 +48,7 @@ class TestLoops: deck.render(1024) assert RATE <= deck.position < RATE + 11025 + 1024 - def test_starts_on_the_next_beat_and_shows_its_size(self, shelf): + def test_starts_on_the_nearest_beat_and_shows_its_size(self, shelf): a, _ = _pair(shelf) a.deck.position = RATE * 3.0 shelf.set_loop(a, True) @@ -56,7 +56,7 @@ class TestLoops: beat = 60 / 124 k = (start / RATE - 0.15) / beat assert k == pytest.approx(round(k), abs=1e-3) # on a beat - assert start / RATE >= 3.0 - 1e-3 # the next one + assert abs(start / RATE - 3.0) <= beat / 2 + 1e-3 # the nearest one (Round 97) assert (end - start) / RATE == pytest.approx(4 * beat, abs=1e-3) shelf.step_loop(a, -2) # 4 → 1 beat assert shelf.loop_sizes["A"].text() == "1" @@ -87,49 +87,6 @@ def test_the_overview_jumps(shelf): ov.grab() # paints without trouble -class TestHorn: - def _horn(self): - x = (np.sin(np.arange(RATE * 2) / RATE * 2 * np.pi * 400) * 20000).astype(np.int16) - return Horn(np.stack([x, x], axis=1)) - - def _drain(self, horn): - total = 0 - while True: - block = horn.render(1024) - if block is None: - return total / RATE - total += len(block) - - def test_a_tap_is_short(self): - horn = self._horn() - horn.press() - horn.render(2205) - horn.release() - assert self._drain(horn) < 0.15 - - def test_holding_carries_the_note_even_after_taps(self): - horn = self._horn() - for _ in range(6): - horn.press() - horn.render(1024) - horn.release() - horn.render(1024) - horn.press() - for _ in range(int(3 * RATE / 1024)): - block = horn.render(1024) - assert np.abs(block).max() > 0.1 # still blaring at 3 s - horn.release() - assert self._drain(horn) < 0.15 - - def test_a_press_while_ringing_starts_a_new_blast(self): - horn = self._horn() - horn.press() - horn.render(4410) - horn.press() - assert len(horn._voices) == 2 and horn._voices[0]["fading"] - assert horn._voices[-1]["pos"] == 0 - - def test_dj_mode_slides(qapp, tmp_path, monkeypatch): from lintunes.gui.main_window import MainWindow from lintunes.library_manager import LibraryManager diff --git a/tests/test_round97.py b/tests/test_round97.py new file mode 100644 index 0000000..7d362a0 --- /dev/null +++ b/tests/test_round97.py @@ -0,0 +1,120 @@ +"""Round 97: the air horn done properly (a click trails off; a hold +sustains one natural cycle, levelled, never a repeating beat; taps stay +separate), djay-style loops (the nearest beat; resizing keeps looping), +a gentler zoom-out when grabbing a waveform.""" + +import numpy as np +import pytest + +from lintunes.dj.audio import RATE, Horn +from lintunes.dj.loader import decode +from tests.test_round93 import _clicks, _loaded, shelf # noqa: F401 — the fixture + + +@pytest.fixture(scope="module") +def recording(): + from importlib import resources + with resources.as_file(resources.files("lintunes") / "sounds" / "airhorn.mp3") as path: + return decode(str(path)) + + +def _play(sample, script): + horn = Horn(sample) + out = [] + for action, seconds in script: + if action == "press": + horn.press() + elif action == "release": + horn.release() + n = int(seconds * RATE) + while n > 0: + block = horn.render(min(512, n)) + out.append(block if block is not None else np.zeros((min(512, n), 2), np.float32)) + n -= 512 + while True: + block = horn.render(512) + if block is None: + break + out.append(block) + return np.concatenate(out).mean(axis=1), horn + + +def _envelope(mono, seconds=0.015): + win = int(seconds * RATE) + return np.sqrt(np.convolve(mono * mono, np.ones(win) / win, mode="same")) + + +class TestHorn: + def test_a_click_is_a_short_blast_that_trails_off(self, recording): + x, _ = _play(recording, [("press", 0.01), ("release", 0.0)]) + assert 0.3 < len(x) / RATE < 0.45 + env = _envelope(x) + assert env[-int(0.02 * RATE):].max() < 0.05 * env.max() # fades to nothing + # …gradually: the last 120 ms fall, they don't drop off a cliff + tail = env[-int(0.12 * RATE):] + assert tail[0] > 4 * tail[-1] + + def test_a_hold_sustains_without_clicks_or_a_beat(self, recording): + x, _ = _play(recording, [("press", 3.0), ("release", 0.0)]) + source = recording.astype(np.float32).mean(axis=1) / 32768 + own_step = np.abs(np.diff(source[:int(0.6 * RATE)])).max() + assert np.abs(np.diff(x)).max() <= own_step + 1e-3 # no seam clicks + held = _envelope(x)[int(0.6 * RATE):int(2.6 * RATE)] + assert held.min() / held.max() > 0.7 # steady, no pulse + assert len(x) / RATE < 3.0 + 0.45 # stops on release + + def test_taps_stay_separate_then_a_hold_carries(self, recording): + x, horn = _play(recording, [("press", 0.06), ("release", 0.12)] * 6 + + [("press", 2.5), ("release", 0.0)]) + held = _envelope(x)[int(1.6 * RATE):int(3.2 * RATE)] + assert held.min() / held.max() > 0.7 + assert not horn._voices + + def test_a_retrigger_cuts_the_old_blast_quickly(self, recording): + horn = Horn(recording) + horn.press() + horn.render(4410) + horn.press() + states = [v["state"] for v in horn._voices] + assert states == ["cut", "held"] + horn.render(int(0.03 * RATE)) + assert [v["state"] for v in horn._voices] == ["held"] + + +class TestLoops: + def _deck(self, shelf): + a, _ = shelf.views + _loaded(shelf, a, shelf.tracks[0], _clicks(120, 0.0, 20), 120.0, 0.0) + return a + + def test_the_nearest_beat_may_be_behind(self, shelf): + a = self._deck(shelf) + a.deck.position = RATE * 2.1 # beats every 0.5 s: 2.0 is nearest + shelf.set_loop(a, True) + assert a.deck.loop[0] / RATE == pytest.approx(2.0, abs=1e-3) + a.deck.position = RATE * 2.4 # 2.5 is nearest + shelf.set_loop(a, True) + assert a.deck.loop[0] / RATE == pytest.approx(2.5, abs=1e-3) + + def test_a_short_loop_snaps_to_its_own_grid(self, shelf): + a = self._deck(shelf) + shelf.step_loop(a, -4) # 4 → 1/4 beat + a.deck.position = RATE * 2.06 # quarter beats every 0.125 s + shelf.set_loop(a, True) + assert a.deck.loop[0] / RATE == pytest.approx(2.0, abs=1e-3) + + def test_shrinking_a_running_loop_keeps_looping(self, shelf): + a = self._deck(shelf) + a.deck.position = RATE * 2.0 + shelf.set_loop(a, True) # 4 beats: 2.0 – 4.0 + a.deck.playing = True + a.deck.seek(RATE * 3.6) # late in the loop + shelf.step_loop(a, -2) # → 1 beat: 2.0 – 2.5 + start, end = a.deck.loop + assert (start, end) == (RATE * 2, RATE * 2 + RATE // 2) + assert start <= a.deck.position < end # folded back inside + for _ in range(60): + a.deck.render(1024) + assert start <= a.deck.position < end + 1024 + shelf.step_loop(a, 2) # back to 4 beats: same start + assert a.deck.loop == (RATE * 2, RATE * 4)