forked from trav/lintunes
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:
@@ -1,3 +1,3 @@
|
||||
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
||||
|
||||
__version__ = "0.66.0"
|
||||
__version__ = "0.67.0"
|
||||
|
||||
+137
-46
@@ -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):
|
||||
|
||||
+23
-11
@@ -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)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user