v0.67.0: the air horn done properly; djay-style loops; a gentler grab zoom

Air horn: the recording's first blast wobbles on a ~0.15 s cycle, so the
old 0.30 s loop jumped every lap (the repeating beat). Held, it now loops
exactly one cycle (found by self-similarity), levelled and crossfaded;
a release crossfades into the recording's own ending, so a click is a
short blast that trails off; each press cuts a still-sounding blast in
25 ms, so taps stay separate. Exact at any block size.

Loops start on the nearest beat (djay's Quantize), and resizing a running
loop keeps its start and keeps looping. Grabbing a waveform zooms out
only a little, gently, and drags at the zoom it was grabbed at. The sync
button just says Sync.
This commit is contained in:
2026-10-17 22:44:45 -07:00
parent 279f51fba9
commit 0f535a4ca3
7 changed files with 306 additions and 111 deletions
+18 -3
View File
@@ -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 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 other's tempo and stays lit only while that holds (`_check_sync`: same
song on the other deck, tempos still equal) — nothing follows anything. 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 **The horn** (Round 97, the third go — measure before touching it): the
ones fade under it), held = the first blast's steady middle looped, let recording's first blast wobbles in pitch and loudness on a ~0.15 s
go = a 90 ms fade. **Opening/closing slides a picture** (`SlideOverlay`): 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 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 the transport boxes moves over it — animating the real shelf height
re-laid-out the window every frame, which flickered. re-laid-out the window every frame, which flickered.
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux.""" """LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.66.0" __version__ = "0.67.0"
+137 -46
View File
@@ -261,24 +261,39 @@ def crossfade_gains(x: float) -> tuple[float, float]:
class Horn: class Horn:
"""The air horn, played like the real thing: a real recording ("Air """The air horn, played like a sampler plays a held instrument (Round
Horn Hype", CC0 — see lintunes/sounds/CREDITS.md). Every press is a 97 — the third go; see ``set_sample`` for the measurements).
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)."""
LOOP = (0.10, 0.40) # seconds: inside the first blast (0–0.48 s) The recording ("Air Horn Hype", CC0 — lintunes/sounds/CREDITS.md)
CROSSFADE = 0.03 has a first blast whose pitch and loudness wobble on a ~0.15 s cycle,
RELEASE = 0.09 # the fade once the button comes up then a natural ending: the pitch drops and it fades, 0.42–0.60 s.
VOICES = 3
- **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 LEVEL = 1.0
def __init__(self, sample: np.ndarray | None = None): def __init__(self, sample: np.ndarray | None = None):
self.on = False self.on = False
self._held = None self._src = None
self._voices: list[dict] = [] # {"pos", "gain", "fading"} self._voices: list[dict] = []
if sample is not None: if sample is not None:
self.set_sample(sample) self.set_sample(sample)
@@ -287,58 +302,134 @@ class Horn:
src = sample.astype(np.float32) src = sample.astype(np.float32)
if sample.dtype == np.int16: if sample.dtype == np.int16:
src /= 32768.0 src /= 32768.0
l0, l1 = (int(t * RATE) for t in self.LOOP) n = len(src)
xf = int(self.CROSSFADE * RATE) a = int(self.LOOP[0] * RATE)
l1 = min(l1, len(src)) length = int(self.LOOP[1] * RATE)
held = src.copy() self._loop = (a, min(n, a + length))
if l1 - l0 > 2 * xf and l0 >= xf: # Held, that one cycle repeats — and its own loudness wobble (min/
ramp = np.linspace(0, 1, xf, dtype=np.float32)[:, None] # max 0.74 across the cycle) repeated twenty times a held second
# the loop's last xf frames fade into what comes just before # reads as a pulse. So the cycle is levelled (to 0.88): its smooth
# its start, so jumping back to l0 continues seamlessly # envelope divided out, the gain itself smoothed so nothing zips.
held[l1 - xf:l1] = src[l1 - xf:l1] * (1 - ramp) + src[l0 - xf:l0] * ramp # Only the looped stretch changes; attack and ending are untouched.
self._held = held mono = src.mean(axis=1)
self._loop = (l0, l1) 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): def press(self):
self.on = True self.on = True
for voice in self._voices: for voice in self._voices:
voice["fading"] = True if voice["state"] != "cut":
self._voices.append({"pos": 0, "gain": 1.0, "fading": False}) 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] del self._voices[:-self.VOICES]
def release(self): def release(self):
self.on = False self.on = False
for voice in self._voices: 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: 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 return None
l0, l1 = self._loop
out = np.zeros((count, CHANNELS), np.float32) out = np.zeros((count, CHANNELS), np.float32)
step = 1.0 / (self.RELEASE * RATE)
kept = [] kept = []
for voice in self._voices: for voice in self._voices:
# the frames this voice plays: the loop while it's held done = 0
index = voice["pos"] + np.arange(count) alive = True
if not voice["fading"]: # In pieces that stop where the voice changes state (the end of
over = index >= l1 # the minimum blast, the end of its ending), so a big block is
index[over] = l0 + (index[over] - l1) % (l1 - l0) # as exact as a small one.
alive = index < len(self._held) while done < count and alive:
frames = np.zeros((count, CHANNELS), np.float32) n, alive = self._voice(voice, out, done, count - done)
frames[alive] = self._held[index[alive]] done += n
if voice["fading"]: if alive:
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):
kept.append(voice) kept.append(voice)
self._voices = kept self._voices = kept
return out * self.LEVEL 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: class Mixer:
def __init__(self): def __init__(self):
+23 -11
View File
@@ -46,7 +46,8 @@ COLORS = {"A": QColor("#5a9be0"), "B": QColor("#e8a35a")}
FACES = {"A": ("#3c6896", "#2b4c70"), "B": ("#93652f", "#6e4a20")} FACES = {"A": ("#3c6896", "#2b4c70"), "B": ("#93652f", "#6e4a20")}
REV_SECONDS = 1.8 # a 33⅓ rpm record: one turn every 1.8 s REV_SECONDS = 1.8 # a 33⅓ rpm record: one turn every 1.8 s
WINDOW_SECONDS = 8.0 # the waveforms show this much, centred 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 COMPACT_HEIGHT = 200
DEFAULT_ROWS_BELOW = 15 DEFAULT_ROWS_BELOW = 15
MIN_ROWS_BELOW, MAX_ROWS_BELOW = 5, 28 MIN_ROWS_BELOW, MAX_ROWS_BELOW = 5, 28
@@ -427,6 +428,9 @@ class WaveLanes(QWidget):
if view.deck.source is None: if view.deck.source is None:
return return
self._drag = (view, event.position().x(), time.monotonic()) 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 self._rate = 0.0
view.deck.scratch_rate = 0.0 view.deck.scratch_rate = 0.0
self.setCursor(Qt.CursorShape.ClosedHandCursor) self.setCursor(Qt.CursorShape.ClosedHandCursor)
@@ -440,7 +444,7 @@ class WaveLanes(QWidget):
dx = event.position().x() - x0 dx = event.position().x() - x0
dt = max(1e-3, now - t0) dt = max(1e-3, now - t0)
# dragging right pulls the song back under the playhead # 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 rate = seconds / dt
self._rate = 0.6 * rate + 0.4 * self._rate self._rate = 0.6 * rate + 0.4 * self._rate
view.deck.scratch_rate = max(-8.0, min(8.0, 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 moving = deck.playing and deck.scratch_rate is None
target = WINDOW_SECONDS if moving else WINDOW_SECONDS * ZOOM_OUT target = WINDOW_SECONDS if moving else WINDOW_SECONDS * ZOOM_OUT
window = self._window[view.name] window = self._window[view.name]
window += (target - window) * 0.12 window += (target - window) * ZOOM_EASE
if abs(window - target) < 0.01: if abs(window - target) < 0.01:
window = target window = target
self._window[view.name] = window self._window[view.name] = window
@@ -943,7 +947,6 @@ class SlideOverlay(QWidget):
pic = self.picture pic = self.picture
ratio = pic.devicePixelRatio() or 1.0 ratio = pic.devicePixelRatio() or 1.0
w = pic.width() / ratio w = pic.width() / ratio
h = pic.height() / ratio
if self.opening: if self.opening:
y = round(self.shift * self.progress) y = round(self.shift * self.progress)
p.drawPixmap(QPointF(0, y), pic) p.drawPixmap(QPointF(0, y), pic)
@@ -1225,7 +1228,7 @@ class DjShelf(QWidget):
play.setFixedSize(44, 32) play.setFixedSize(44, 32)
play.setToolTip(f"Play / pause Deck {v.name}") play.setToolTip(f"Play / pause Deck {v.name}")
play.clicked.connect(lambda _=False, v=v: self.toggle(v)) play.clicked.connect(lambda _=False, v=v: self.toggle(v))
sync = QPushButton("Sync to other track") sync = QPushButton("Sync")
sync.setFixedHeight(32) sync.setFixedHeight(32)
sync.setToolTip("Set this deck to the other deck's tempo now; while " sync.setToolTip("Set this deck to the other deck's tempo now; while "
"both play, line the beats up too (the smallest nudge)") "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 return 60.0 / view.beat_bpm if view.beat_bpm else None
def set_loop(self, view: DeckView, on: bool): 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.""" carries on past the loop's end."""
deck = view.deck deck = view.deck
beat = self._beat(view) 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.") self.message.emit("A loop needs the song's beat, and none was found.")
return return
now = self.heard_seconds(view) now = self.heard_seconds(view)
k = math.ceil((now - view.offset) / beat - 1e-6) snap = beat * min(1.0, view.loop_beats)
start = view.offset + k * beat start = view.offset + round((now - view.offset) / snap) * snap
self._place_loop(view, start) self._place_loop(view, max(0.0, start))
self.loop_buttons[view.name].setChecked(True) self.loop_buttons[view.name].setChecked(True)
def _place_loop(self, view: DeckView, start_s: float): 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))] 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)) self.loop_sizes[view.name].setText(_loop_label(view.loop_beats))
if view.deck.loop is not None and self._beat(view): 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) 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): def jump(self, view: DeckView, seconds: float):
"""Move the playhead to ``seconds`` (the overview's click/drag).""" """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. # yet (an empty other deck, a tempo still being worked out) it says.
self.sync_buttons[view.name].setEnabled(loaded) self.sync_buttons[view.name].setEnabled(loaded)
sync = self.sync_buttons[view.name] 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)) sync.setStyleSheet(_deck_button_qss(view.name, glow=view.synced))
self._refresh_note(view) self._refresh_note(view)
+5 -5
View File
@@ -63,7 +63,7 @@ class TestSync:
assert b.synced and shelf.sync_buttons["B"].text() == "Synced" assert b.synced and shelf.sync_buttons["B"].text() == "Synced"
shelf.speed["B"].setValue(0) # B moved by hand: unsynced shelf.speed["B"].setValue(0) # B moved by hand: unsynced
assert not b.synced 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): def test_only_one_deck_follows(self, shelf):
a, b = self._pair(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 from lintunes.gui.dj_shelf import _load_horn
horn = Horn() horn = Horn()
_load_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): 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) _loaded(shelf, a, shelf.tracks[0], _clicks(124, 0.1, 10), 124.0, 0.1)
lanes = shelf.lanes lanes = shelf.lanes
lanes.resize(600, 120) lanes.resize(600, 120)
for _ in range(80): for _ in range(200):
lanes.grab() # paused: eases out 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 a.deck.playing = True
for _ in range(80): for _ in range(200):
lanes.grab() lanes.grab()
assert lanes._window["A"] == pytest.approx(8.0) assert lanes._window["A"] == pytest.approx(8.0)
+2 -45
View File
@@ -48,7 +48,7 @@ class TestLoops:
deck.render(1024) deck.render(1024)
assert RATE <= deck.position < RATE + 11025 + 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, _ = _pair(shelf)
a.deck.position = RATE * 3.0 a.deck.position = RATE * 3.0
shelf.set_loop(a, True) shelf.set_loop(a, True)
@@ -56,7 +56,7 @@ class TestLoops:
beat = 60 / 124 beat = 60 / 124
k = (start / RATE - 0.15) / beat k = (start / RATE - 0.15) / beat
assert k == pytest.approx(round(k), abs=1e-3) # on a 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) assert (end - start) / RATE == pytest.approx(4 * beat, abs=1e-3)
shelf.step_loop(a, -2) # 4 → 1 beat shelf.step_loop(a, -2) # 4 → 1 beat
assert shelf.loop_sizes["A"].text() == "1" assert shelf.loop_sizes["A"].text() == "1"
@@ -87,49 +87,6 @@ def test_the_overview_jumps(shelf):
ov.grab() # paints without trouble 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): def test_dj_mode_slides(qapp, tmp_path, monkeypatch):
from lintunes.gui.main_window import MainWindow from lintunes.gui.main_window import MainWindow
from lintunes.library_manager import LibraryManager from lintunes.library_manager import LibraryManager
+120
View File
@@ -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)