duskfm 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- duskfm/__init__.py +3 -0
- duskfm/__main__.py +3 -0
- duskfm/cli.py +200 -0
- duskfm/compose.py +313 -0
- duskfm/engine.py +104 -0
- duskfm/fx.py +186 -0
- duskfm/player.py +127 -0
- duskfm/synth.py +205 -0
- duskfm-0.1.0.dist-info/METADATA +102 -0
- duskfm-0.1.0.dist-info/RECORD +13 -0
- duskfm-0.1.0.dist-info/WHEEL +4 -0
- duskfm-0.1.0.dist-info/entry_points.txt +3 -0
- duskfm-0.1.0.dist-info/licenses/LICENSE +21 -0
duskfm/__init__.py
ADDED
duskfm/__main__.py
ADDED
duskfm/cli.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""duskfm: endless, never-repeating music from lo-fi to synthwave, made on the spot.
|
|
2
|
+
|
|
3
|
+
duskfm lo-fi
|
|
4
|
+
duskfm synthwave a preset: lofi, chillhop, chillwave, synthwave, nightdrive, ambient
|
|
5
|
+
duskfm --style 0.3 --energy 0.6 --drift
|
|
6
|
+
duskfm --boost 9 --rain 0.5 louder than the volume alone goes; a rain bed that covers voices
|
|
7
|
+
duskfm --render 2h -o work.wav to a file instead (e.g. to play somewhere without Python)
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import select
|
|
15
|
+
import shutil
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
import wave
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
from . import __version__
|
|
23
|
+
from .compose import PRESETS, Composer, style_name
|
|
24
|
+
from .engine import Engine
|
|
25
|
+
from .player import Player, backends
|
|
26
|
+
from .synth import SR
|
|
27
|
+
|
|
28
|
+
KEYS_HELP = ("keys: ←/→ style (lo-fi ↔ synthwave) ↑/↓ energy +/- volume ]/[ boost r rain d drift n next "
|
|
29
|
+
"1-6 presets space pause q quit")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def duration(text: str) -> float:
|
|
33
|
+
"""'90m', '2h', '1h30m', '45s', '30' (minutes) -> seconds."""
|
|
34
|
+
if re.fullmatch(r"\d+(\.\d+)?", text):
|
|
35
|
+
return float(text) * 60
|
|
36
|
+
parts = re.findall(r"(\d+(?:\.\d+)?)\s*([hms])", text.lower())
|
|
37
|
+
if not parts or "".join(a + b for a, b in parts) != re.sub(r"\s", "", text.lower()):
|
|
38
|
+
raise argparse.ArgumentTypeError(f"not a length: {text!r} (try 90m, 2h, 1h30m)")
|
|
39
|
+
return sum(float(n) * {"h": 3600, "m": 60, "s": 1}[u] for n, u in parts)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def unit(text: str) -> float:
|
|
43
|
+
v = float(text)
|
|
44
|
+
if not 0 <= v <= 1:
|
|
45
|
+
raise argparse.ArgumentTypeError("between 0 and 1")
|
|
46
|
+
return v
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def parse(argv):
|
|
50
|
+
p = argparse.ArgumentParser(prog="duskfm", description=__doc__.split("\n")[0],
|
|
51
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
52
|
+
epilog="presets: " + ", ".join(f"{k} (style {s}, energy {e})" for k, (s, e) in PRESETS.items())
|
|
53
|
+
+ "\n\n" + KEYS_HELP)
|
|
54
|
+
p.add_argument("preset", nargs="?", choices=list(PRESETS), help="where to start (default lofi)")
|
|
55
|
+
p.add_argument("--style", type=unit, help="0 lo-fi .. 0.5 chillwave .. 1 synthwave")
|
|
56
|
+
p.add_argument("--energy", type=unit, help="0 ambient (no drums) .. 1 driving")
|
|
57
|
+
p.add_argument("--drift", action="store_true", help="let the style and energy wander slowly on their own")
|
|
58
|
+
p.add_argument("--volume", type=float, default=80, help="0-100 (default 80)")
|
|
59
|
+
p.add_argument("--boost", type=float, default=0, help="dB of extra loudness, 0-18: compressed and limited, "
|
|
60
|
+
"so it gets louder without clipping (default 0)")
|
|
61
|
+
p.add_argument("--rain", type=unit, default=0, help="a rain bed shaped to cover voices, 0-1 (default 0)")
|
|
62
|
+
p.add_argument("--seed", type=int, help="replay a session (it's shown when you quit)")
|
|
63
|
+
p.add_argument("--minutes", type=duration, metavar="LENGTH", help="play this long, then fade out (e.g. 90m, 2h)")
|
|
64
|
+
p.add_argument("--backend", help="paplay, pw-cat, aplay or sounddevice (default: the first that's here)")
|
|
65
|
+
p.add_argument("--render", type=duration, metavar="LENGTH", help="write LENGTH of music to a WAV file instead")
|
|
66
|
+
p.add_argument("-o", "--output", default="duskfm.wav", help="the file for --render (default duskfm.wav)")
|
|
67
|
+
p.add_argument("--version", action="version", version=f"duskfm {__version__}")
|
|
68
|
+
a = p.parse_args(argv)
|
|
69
|
+
s, e = PRESETS[a.preset or "lofi"]
|
|
70
|
+
a.style = s if a.style is None else a.style
|
|
71
|
+
a.energy = e if a.energy is None else a.energy
|
|
72
|
+
a.boost = max(0.0, min(18.0, a.boost))
|
|
73
|
+
a.volume = max(0.0, min(100.0, a.volume))
|
|
74
|
+
return a
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def render_file(a) -> int:
|
|
78
|
+
comp = Composer(seed=a.seed, style=a.style, energy=a.energy, drift=a.drift)
|
|
79
|
+
eng = Engine(comp, rain=a.rain, boost=a.boost)
|
|
80
|
+
total, done, fade = int(a.render * SR), 0, int(min(10, a.render / 4) * SR)
|
|
81
|
+
with wave.open(a.output, "wb") as w:
|
|
82
|
+
w.setnchannels(2)
|
|
83
|
+
w.setsampwidth(2)
|
|
84
|
+
w.setframerate(SR)
|
|
85
|
+
while done < total:
|
|
86
|
+
block = eng.render_bar()[: total - done] * (a.volume / 100)
|
|
87
|
+
k = np.clip((total - done - np.arange(len(block))) / fade, 0, 1) # fade out at the end
|
|
88
|
+
w.writeframes((np.clip(block * k[:, None], -1, 1) * 32767).astype("<i2").tobytes())
|
|
89
|
+
done += len(block)
|
|
90
|
+
print(f"\r{a.output}: {done / SR / 60:5.1f} of {total / SR / 60:.1f} min {eng.label} ", end="", flush=True)
|
|
91
|
+
print(f"\ndone (seed {comp.seed})")
|
|
92
|
+
return 0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Keys:
|
|
96
|
+
"""Single keypresses from the terminal, without Enter (and without echoing them)."""
|
|
97
|
+
|
|
98
|
+
def __init__(self):
|
|
99
|
+
import termios
|
|
100
|
+
import tty
|
|
101
|
+
self.fd = sys.stdin.fileno()
|
|
102
|
+
self.old = termios.tcgetattr(self.fd)
|
|
103
|
+
tty.setcbreak(self.fd)
|
|
104
|
+
|
|
105
|
+
def read(self, timeout: float) -> str | None:
|
|
106
|
+
if not select.select([sys.stdin], [], [], timeout)[0]:
|
|
107
|
+
return None
|
|
108
|
+
ch = os.read(self.fd, 1).decode(errors="ignore")
|
|
109
|
+
if ch == "\x1b" and select.select([sys.stdin], [], [], 0.02)[0]:
|
|
110
|
+
ch += os.read(self.fd, 2).decode(errors="ignore")
|
|
111
|
+
return ch
|
|
112
|
+
|
|
113
|
+
def close(self):
|
|
114
|
+
import termios
|
|
115
|
+
termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def meter(v: float) -> str:
|
|
119
|
+
n = round(v * 8)
|
|
120
|
+
return "▮" * n + "▯" * (8 - n)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def play(a) -> int:
|
|
124
|
+
comp = Composer(seed=a.seed, style=a.style, energy=a.energy, drift=a.drift)
|
|
125
|
+
eng = Engine(comp, rain=a.rain, boost=a.boost)
|
|
126
|
+
player = Player(eng.render_bar, backend=a.backend)
|
|
127
|
+
player.volume = a.volume / 100
|
|
128
|
+
player.start()
|
|
129
|
+
interactive = sys.stdin.isatty() and sys.stdout.isatty()
|
|
130
|
+
keys = Keys() if interactive else None
|
|
131
|
+
started, rain_levels = time.time(), [0.0, 0.35, 0.7]
|
|
132
|
+
print(f"duskfm {__version__} · playing through {player.backend}" + (f"\n{KEYS_HELP}" if interactive else ""))
|
|
133
|
+
try:
|
|
134
|
+
while not player.stopping.is_set():
|
|
135
|
+
if a.minutes and time.time() - started > a.minutes and not player.fade:
|
|
136
|
+
player.fade_out(30)
|
|
137
|
+
k = keys.read(0.25) if keys else (time.sleep(0.5) or None)
|
|
138
|
+
if k in ("q", "Q", "\x03"):
|
|
139
|
+
player.fade_out(1.5)
|
|
140
|
+
elif k == "\x1b[C":
|
|
141
|
+
comp.style = min(1.0, comp.style + 0.1)
|
|
142
|
+
elif k == "\x1b[D":
|
|
143
|
+
comp.style = max(0.0, comp.style - 0.1)
|
|
144
|
+
elif k == "\x1b[A":
|
|
145
|
+
comp.energy = min(1.0, comp.energy + 0.1)
|
|
146
|
+
elif k == "\x1b[B":
|
|
147
|
+
comp.energy = max(0.0, comp.energy - 0.1)
|
|
148
|
+
elif k in ("+", "="):
|
|
149
|
+
player.volume = min(1.0, player.volume + 0.05)
|
|
150
|
+
elif k in ("-", "_"):
|
|
151
|
+
player.volume = max(0.0, player.volume - 0.05)
|
|
152
|
+
elif k == "]":
|
|
153
|
+
eng.boost = min(18.0, eng.boost + 3)
|
|
154
|
+
elif k == "[":
|
|
155
|
+
eng.boost = max(0.0, eng.boost - 3)
|
|
156
|
+
elif k == "r":
|
|
157
|
+
eng.rain = rain_levels[(rain_levels.index(min(rain_levels, key=lambda v: abs(v - eng.rain))) + 1) % 3]
|
|
158
|
+
elif k == "d":
|
|
159
|
+
comp.drift = not comp.drift
|
|
160
|
+
elif k == "n":
|
|
161
|
+
comp.skip = True
|
|
162
|
+
elif k == " ":
|
|
163
|
+
player.paused = not player.paused
|
|
164
|
+
elif k and k in "123456":
|
|
165
|
+
comp.style, comp.energy = list(PRESETS.values())[int(k) - 1]
|
|
166
|
+
comp.skip = True
|
|
167
|
+
if interactive:
|
|
168
|
+
status = (f"\r\x1b[2K{'❚❚ paused · ' if player.paused else ''}{eng.label or 'tuning in…'} "
|
|
169
|
+
f"style {meter(comp.style)} energy {meter(comp.energy)} vol {round(player.volume * 100)}%"
|
|
170
|
+
f" boost +{eng.boost:g} dB rain {'off' if not eng.rain else f'{eng.rain:g}'}"
|
|
171
|
+
f"{' drift' if comp.drift else ''}")
|
|
172
|
+
cols = shutil.get_terminal_size((100, 24)).columns or 100
|
|
173
|
+
print(status[: cols + 4], end="", flush=True) # +4: the line-clearing code isn't seen
|
|
174
|
+
except KeyboardInterrupt:
|
|
175
|
+
pass
|
|
176
|
+
finally:
|
|
177
|
+
player.stop()
|
|
178
|
+
if keys:
|
|
179
|
+
keys.close()
|
|
180
|
+
print(f"\n{'error: ' + str(player.error) if player.error else 'goodnight'} (seed {comp.seed}: duskfm --seed {comp.seed} "
|
|
181
|
+
f"--style {comp.style:.2f} --energy {comp.energy:.2f} replays it)")
|
|
182
|
+
return 1 if player.error else 0
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def main(argv=None) -> int:
|
|
186
|
+
a = parse(sys.argv[1:] if argv is None else argv)
|
|
187
|
+
if a.render:
|
|
188
|
+
return render_file(a)
|
|
189
|
+
try:
|
|
190
|
+
return play(a)
|
|
191
|
+
except RuntimeError as e:
|
|
192
|
+
print(f"duskfm: {e}", file=sys.stderr)
|
|
193
|
+
return 1
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def cli():
|
|
197
|
+
sys.exit(main())
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
__all__ = ["main", "cli", "backends", "style_name"]
|
duskfm/compose.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""The composer: what to play, bar by bar, from two dials.
|
|
2
|
+
|
|
3
|
+
style: 0 = lo-fi (jazzy 7ths and 9ths, swung, dusty) ... 0.5 = chillwave ... 1 = synthwave (minor, straight, neon)
|
|
4
|
+
energy: 0 = ambient (no drums, sparse) ... 1 = driving
|
|
5
|
+
|
|
6
|
+
Nothing here makes sound: it plans bars of events (who plays what, when, how hard) for the engine to render.
|
|
7
|
+
A seeded random generator drives every choice, so a seed replays a session and no seed never repeats.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import random
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
NOTE_NAMES = ["C", "D♭", "D", "E♭", "E", "F", "G♭", "G", "A♭", "A", "B♭", "B"]
|
|
15
|
+
MAJOR = [0, 2, 4, 5, 7, 9, 11]
|
|
16
|
+
MINOR = [0, 2, 3, 5, 7, 8, 10]
|
|
17
|
+
|
|
18
|
+
QUALITY = {
|
|
19
|
+
"maj": [0, 4, 7], "min": [0, 3, 7], "sus2": [0, 2, 7], "sus4": [0, 5, 7], "add9": [0, 4, 7, 14],
|
|
20
|
+
"madd9": [0, 3, 7, 14], "maj7": [0, 4, 7, 11], "m7": [0, 3, 7, 10], "7": [0, 4, 7, 10],
|
|
21
|
+
"maj9": [0, 4, 7, 11, 14], "m9": [0, 3, 7, 10, 14], "9": [0, 4, 7, 10, 14], "m11": [0, 3, 7, 10, 14, 17],
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
# Progressions: (semitones above the tonic, quality), one chord a bar, and the mode they're in.
|
|
25
|
+
FAMILIES = {
|
|
26
|
+
"lofi": [
|
|
27
|
+
("major", [(2, "m9"), (7, "9"), (0, "maj9"), (9, "m7")]), # ii V I vi
|
|
28
|
+
("major", [(5, "maj7"), (4, "m7"), (2, "m9"), (0, "maj7")]), # IV iii ii I
|
|
29
|
+
("major", [(0, "maj7"), (9, "m9"), (2, "m7"), (7, "9")]), # I vi ii V
|
|
30
|
+
("major", [(5, "maj9"), (7, "9"), (4, "m7"), (9, "m9")]), # IV V iii vi
|
|
31
|
+
("minor", [(0, "m9"), (5, "m9"), (10, "9"), (3, "maj7")]), # i iv VII III
|
|
32
|
+
("minor", [(0, "m11"), (8, "maj7"), (5, "m9"), (7, "m7")]), # i VI iv v
|
|
33
|
+
],
|
|
34
|
+
"chillwave": [
|
|
35
|
+
("major", [(0, "maj9"), (5, "maj9"), (0, "maj9"), (5, "maj9")]), # the drifting I-IV
|
|
36
|
+
("major", [(9, "m7"), (5, "maj7"), (0, "add9"), (7, "sus4")]), # vi IV I V
|
|
37
|
+
("major", [(0, "add9"), (4, "m7"), (5, "maj9"), (7, "sus2")]),
|
|
38
|
+
("minor", [(0, "madd9"), (8, "maj7"), (3, "maj7"), (10, "add9")]),
|
|
39
|
+
],
|
|
40
|
+
"synthwave": [
|
|
41
|
+
("minor", [(0, "min"), (8, "maj"), (3, "maj"), (10, "maj")]), # i VI III VII
|
|
42
|
+
("minor", [(0, "min"), (10, "maj"), (8, "maj"), (10, "maj")]), # i VII VI VII
|
|
43
|
+
("minor", [(8, "maj"), (10, "maj"), (0, "min"), (0, "min")]), # VI VII i
|
|
44
|
+
("minor", [(0, "min"), (5, "min"), (8, "maj"), (7, "maj")]), # i iv VI V
|
|
45
|
+
("minor", [(0, "sus2"), (8, "add9"), (3, "add9"), (10, "sus4")]),
|
|
46
|
+
],
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
PRESETS = { # name: (style, energy)
|
|
50
|
+
"lofi": (0.0, 0.45), "chillhop": (0.12, 0.65), "chillwave": (0.5, 0.45),
|
|
51
|
+
"synthwave": (0.92, 0.6), "nightdrive": (1.0, 0.85), "ambient": (0.45, 0.0),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def midi_hz(m: float) -> float:
|
|
56
|
+
return 440.0 * 2 ** ((m - 69) / 12)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class Event:
|
|
61
|
+
t: float # seconds from the bar's start
|
|
62
|
+
inst: str # keys, pad, poly, arp, lead, bass, kick, snare, hat, rim, shaker
|
|
63
|
+
note: float = 60 # MIDI note (drums ignore it)
|
|
64
|
+
dur: float = 0.25 # seconds
|
|
65
|
+
vel: float = 0.8
|
|
66
|
+
pan: float = 0.0 # -1 left .. 1 right
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class Bar:
|
|
71
|
+
events: list[Event]
|
|
72
|
+
seconds: float
|
|
73
|
+
tempo: float
|
|
74
|
+
style: float
|
|
75
|
+
energy: float
|
|
76
|
+
label: str # what's playing, for the status line
|
|
77
|
+
section: str
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class Section:
|
|
82
|
+
family: str
|
|
83
|
+
mode: str
|
|
84
|
+
prog: list
|
|
85
|
+
bars: int
|
|
86
|
+
kind: str # intro, groove, breakdown, lift
|
|
87
|
+
drums: bool
|
|
88
|
+
melody: bool
|
|
89
|
+
arp: bool
|
|
90
|
+
lead: bool
|
|
91
|
+
motif: list = field(default_factory=list)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def family_weights(style: float) -> dict[str, float]:
|
|
95
|
+
"""How likely each family is at this style: lo-fi fades out as synthwave fades in, chillwave peaks between."""
|
|
96
|
+
return {"lofi": max(0.0, 1 - style * 1.8) ** 1.2 + 0.02,
|
|
97
|
+
"chillwave": max(0.0, 1 - abs(style - 0.5) * 2.4) + 0.02,
|
|
98
|
+
"synthwave": max(0.0, style * 1.8 - 0.8) ** 1.2 + 0.02}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def style_name(style: float, energy: float) -> str:
|
|
102
|
+
if energy < 0.12:
|
|
103
|
+
return "ambient"
|
|
104
|
+
if style < 0.3:
|
|
105
|
+
return "chillhop" if energy > 0.6 else "lo-fi"
|
|
106
|
+
if style < 0.7:
|
|
107
|
+
return "chillwave"
|
|
108
|
+
return "night drive" if energy > 0.78 else "synthwave"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Composer:
|
|
112
|
+
def __init__(self, seed: int | None = None, style: float = 0.0, energy: float = 0.45, drift: bool = False):
|
|
113
|
+
self.seed = seed if seed is not None else random.SystemRandom().randrange(2 ** 31)
|
|
114
|
+
self.r = random.Random(self.seed)
|
|
115
|
+
self.style, self.energy, self.drift = style, energy, drift
|
|
116
|
+
self.tonic = self.r.randrange(12) # the major-key tonic; minor progressions use its relative minor
|
|
117
|
+
self.section: Section | None = None
|
|
118
|
+
self.bar_in_section = 0
|
|
119
|
+
self.sections_done = 0
|
|
120
|
+
self.voicing: list[int] = []
|
|
121
|
+
self.tempo = self.pick_tempo()
|
|
122
|
+
self.skip = False
|
|
123
|
+
|
|
124
|
+
# --- the dials
|
|
125
|
+
def pick_tempo(self) -> float:
|
|
126
|
+
lo, hi = 72 + self.style * 22, 84 + self.style * 26 # lo-fi 72-84 .. synthwave 94-110
|
|
127
|
+
return round(self.r.uniform(lo, hi) + self.energy * 4, 1)
|
|
128
|
+
|
|
129
|
+
def drift_step(self):
|
|
130
|
+
"""--drift: the dials wander slowly, a little each section."""
|
|
131
|
+
self.style = min(1.0, max(0.0, self.style + self.r.gauss(0, 0.07)))
|
|
132
|
+
self.energy = min(1.0, max(0.05, self.energy + self.r.gauss(0, 0.08)))
|
|
133
|
+
|
|
134
|
+
# --- sections
|
|
135
|
+
def new_section(self) -> Section:
|
|
136
|
+
r = self.r
|
|
137
|
+
if self.drift:
|
|
138
|
+
self.drift_step()
|
|
139
|
+
if self.sections_done and self.sections_done % r.choice([3, 4, 5]) == 0: # a new key now and then
|
|
140
|
+
self.tonic = (self.tonic + r.choice([5, 7, 2, 10, 3, 9])) % 12
|
|
141
|
+
self.tempo = self.pick_tempo()
|
|
142
|
+
w = family_weights(self.style)
|
|
143
|
+
family = r.choices(list(w), weights=list(w.values()))[0]
|
|
144
|
+
mode, prog = r.choice(FAMILIES[family])
|
|
145
|
+
e = self.energy
|
|
146
|
+
kinds = ["groove"] * 5 + ["breakdown"] * 2 + ["lift"] * 2 + (["intro"] if self.sections_done == 0 else [])
|
|
147
|
+
kind = "intro" if self.sections_done == 0 else r.choice(kinds)
|
|
148
|
+
drums = e > 0.12 and kind not in ("intro", "breakdown") and r.random() < 0.55 + e * 0.5
|
|
149
|
+
sec = Section(family=family, mode=mode, prog=prog, bars=r.choice([8, 8, 16]), kind=kind, drums=drums,
|
|
150
|
+
melody=r.random() < 0.45 + 0.3 * (kind != "intro"),
|
|
151
|
+
arp=self.style > 0.45 and e > 0.25 and r.random() < 0.3 + self.style * 0.5,
|
|
152
|
+
lead=self.style > 0.6 and kind == "lift" and r.random() < 0.7)
|
|
153
|
+
sec.motif = self.make_motif()
|
|
154
|
+
self.sections_done += 1
|
|
155
|
+
return sec
|
|
156
|
+
|
|
157
|
+
def make_motif(self) -> list[tuple[float, float, int]]:
|
|
158
|
+
"""Two bars of melody shape: (beat, length in beats, scale-step move). Fitted to each chord as it's played."""
|
|
159
|
+
r, out, beat = self.r, [], 0.0
|
|
160
|
+
sparse = 0.6 - self.energy * 0.3
|
|
161
|
+
while beat < 8:
|
|
162
|
+
if r.random() < sparse:
|
|
163
|
+
beat += r.choice([0.5, 1.0, 1.5])
|
|
164
|
+
continue
|
|
165
|
+
length = r.choice([0.5, 0.5, 1.0, 1.0, 1.5, 2.0] if self.style < 0.5 else [0.5, 0.5, 0.5, 1.0, 1.0])
|
|
166
|
+
out.append((beat, min(length, 8 - beat), r.choice([-2, -1, -1, 0, 1, 1, 2, 3, -3])))
|
|
167
|
+
beat += length
|
|
168
|
+
return out
|
|
169
|
+
|
|
170
|
+
# --- one bar
|
|
171
|
+
def next_bar(self) -> Bar:
|
|
172
|
+
if self.section is None or self.bar_in_section >= self.section.bars or self.skip:
|
|
173
|
+
self.section, self.bar_in_section, self.skip = self.new_section(), 0, False
|
|
174
|
+
s, i = self.section, self.bar_in_section
|
|
175
|
+
self.bar_in_section += 1
|
|
176
|
+
tonic = self.tonic if s.mode == "major" else (self.tonic + 9) % 12
|
|
177
|
+
degree, quality = s.prog[i % len(s.prog)]
|
|
178
|
+
root = tonic + degree
|
|
179
|
+
beat = 60.0 / self.tempo
|
|
180
|
+
st, e, r = self.style, self.energy, self.r
|
|
181
|
+
swing = 0.0 if st > 0.55 else (0.62 - 0.5) * (1 - st / 0.55) # lo-fi swings its 8ths
|
|
182
|
+
ev: list[Event] = []
|
|
183
|
+
|
|
184
|
+
def at(b: float) -> float: # beat -> seconds, swung and loose
|
|
185
|
+
frac = b % 1.0
|
|
186
|
+
if abs(frac - 0.5) < 1e-6:
|
|
187
|
+
b += swing
|
|
188
|
+
return max(0.0, b * beat + r.gauss(0, 0.008 * (1 - st)))
|
|
189
|
+
|
|
190
|
+
# chords: voiced close to the last chord, in the middle of the keyboard
|
|
191
|
+
tones = [root + q for q in QUALITY[quality]]
|
|
192
|
+
voicing = self.voice(tones)
|
|
193
|
+
keys_inst = "keys" if st < 0.62 else "poly"
|
|
194
|
+
fade_in = min(1.0, (i + 1) / 4) if s.kind == "intro" else 1.0
|
|
195
|
+
if st < 0.8 or r.random() < 0.5: # the keys: lo-fi's heart
|
|
196
|
+
hits = [0.0] if e < 0.4 or st > 0.62 else r.choice([[0.0], [0.0, 2.5], [0.0, 1.5], [0.0, 3.5]])
|
|
197
|
+
for k, hb in enumerate(hits):
|
|
198
|
+
length = (4 - hb if k == len(hits) - 1 else hits[k + 1] - hb) * beat
|
|
199
|
+
for n, note in enumerate(voicing): # a lazy roll on the keys
|
|
200
|
+
ev.append(Event(at(hb) + n * (0.018 if keys_inst == "keys" else 0.004), keys_inst, note,
|
|
201
|
+
length * 0.98, (0.55 + r.random() * 0.15) * fade_in * (0.85 if k else 1), pan=(n - 1.5) * 0.15))
|
|
202
|
+
if st > 0.25 or e < 0.2: # pads: the haze
|
|
203
|
+
for n, note in enumerate(voicing[:4]):
|
|
204
|
+
ev.append(Event(0.0, "pad", note + (12 if st > 0.7 and n == len(voicing[:4]) - 1 else 0), 4 * beat,
|
|
205
|
+
0.42 * fade_in * (0.5 + st * 0.7), pan=(n - 1.5) * 0.4))
|
|
206
|
+
# bass
|
|
207
|
+
bass_root = 36 + (root % 12)
|
|
208
|
+
if bass_root > 43:
|
|
209
|
+
bass_root -= 12
|
|
210
|
+
if e > 0.08:
|
|
211
|
+
if st > 0.7 and e > 0.35: # synthwave: driving 8ths
|
|
212
|
+
for k in range(8):
|
|
213
|
+
ev.append(Event(at(k * 0.5), "bass", bass_root + (12 if k % 4 == 3 and e > 0.7 else 0), beat * 0.42, 0.75 + 0.1 * (k % 2 == 0)))
|
|
214
|
+
else:
|
|
215
|
+
ev.append(Event(at(0), "bass", bass_root, beat * (2.5 if st < 0.4 else 3.5), 0.85))
|
|
216
|
+
if e > 0.3:
|
|
217
|
+
nxt = s.prog[(i + 1) % len(s.prog)][0] + tonic
|
|
218
|
+
approach = 36 + (nxt % 12) + r.choice([-1, 1, 0]) - (12 if 36 + (nxt % 12) > 43 else 0)
|
|
219
|
+
ev.append(Event(at(r.choice([2.5, 3.0, 3.5])), "bass", r.choice([bass_root + 7, approach]), beat * 0.9, 0.7))
|
|
220
|
+
# drums
|
|
221
|
+
if s.drums and not (s.kind == "lift" and i == s.bars - 1 and r.random() < 0.5):
|
|
222
|
+
ev += self.drums(at, beat, i, s)
|
|
223
|
+
# melody: the motif, fitted to this chord
|
|
224
|
+
if s.melody and e > 0.05:
|
|
225
|
+
scale = [(tonic + x) for x in (MAJOR if s.mode == "major" else MINOR)]
|
|
226
|
+
inst = "lead" if s.lead else ("keys" if st < 0.5 else "lead" if st > 0.8 else "keys")
|
|
227
|
+
if st > 0.4 and not s.lead:
|
|
228
|
+
inst = "bell"
|
|
229
|
+
ev += self.melody(at, beat, i, s, scale, tones, inst)
|
|
230
|
+
if s.arp:
|
|
231
|
+
ev += self.arp(beat, voicing, e)
|
|
232
|
+
label = f"{style_name(st, e)} · {round(self.tempo)} BPM · {NOTE_NAMES[tonic % 12]} {s.mode}"
|
|
233
|
+
return Bar(events=ev, seconds=4 * beat, tempo=self.tempo, style=st, energy=e, label=label, section=s.kind)
|
|
234
|
+
|
|
235
|
+
def voice(self, tones: list[int]) -> list[int]:
|
|
236
|
+
"""The chord's notes (four at most) placed near the last chord's, between E3 and E5: smooth voice leading."""
|
|
237
|
+
pcs = []
|
|
238
|
+
for t in tones: # root, 3rd, 7th and a colour tone first
|
|
239
|
+
if t % 12 not in [p % 12 for p in pcs]:
|
|
240
|
+
pcs.append(t)
|
|
241
|
+
pcs = pcs[:4] if len(pcs) > 4 else pcs
|
|
242
|
+
center = sum(self.voicing) / len(self.voicing) if self.voicing else 60
|
|
243
|
+
out = []
|
|
244
|
+
for t in pcs:
|
|
245
|
+
cands = [t % 12 + 12 * o for o in range(4, 7)]
|
|
246
|
+
out.append(min(cands, key=lambda c: abs(c - center) + (6 if c in out else 0)))
|
|
247
|
+
out.sort()
|
|
248
|
+
while out[-1] - out[0] > 16: # keep it a hand's width
|
|
249
|
+
out[-1] -= 12
|
|
250
|
+
out.sort()
|
|
251
|
+
self.voicing = out
|
|
252
|
+
return out
|
|
253
|
+
|
|
254
|
+
def drums(self, at, beat, i, s) -> list[Event]:
|
|
255
|
+
r, st, e, ev = self.r, self.style, self.energy, []
|
|
256
|
+
fill = i % 4 == 3 and e > 0.5 and r.random() < 0.5
|
|
257
|
+
if st < 0.35: # lo-fi boom-bap: lazy kick, snare on 2 and 4, swung hats
|
|
258
|
+
for b in [0, r.choice([1.5, 1.75, 2.5]), r.choice([2.5, 3.25])] if e > 0.4 else [0, 2.5]:
|
|
259
|
+
ev.append(Event(at(b), "kick", vel=0.85))
|
|
260
|
+
for b in (1, 3):
|
|
261
|
+
ev.append(Event(at(b) + 0.012, "snare", vel=0.7))
|
|
262
|
+
if e > 0.5 and r.random() < 0.4:
|
|
263
|
+
ev.append(Event(at(3.75), "snare", vel=0.25)) # a ghost note
|
|
264
|
+
step = 0.5 if e < 0.75 else 0.25
|
|
265
|
+
for k in range(int(4 / step)):
|
|
266
|
+
ev.append(Event(at(k * step), "hat", vel=(0.45 if k % 2 == 0 else 0.25) * (0.8 + r.random() * 0.4)))
|
|
267
|
+
elif st < 0.7: # chillwave: soft kick, rim, shaker
|
|
268
|
+
for b in (0, 2) if e < 0.6 else (0, 1.5, 2):
|
|
269
|
+
ev.append(Event(at(b), "kick", vel=0.65))
|
|
270
|
+
for b in (1, 3):
|
|
271
|
+
ev.append(Event(at(b), "rim", vel=0.5))
|
|
272
|
+
for k in range(16 if e > 0.35 else 8):
|
|
273
|
+
ev.append(Event(at(k * (0.25 if e > 0.35 else 0.5)), "shaker", vel=0.18 + 0.12 * (k % 2 == 0)))
|
|
274
|
+
else: # synthwave: punchy kick, big snare, straight hats
|
|
275
|
+
for b in (range(4) if e > 0.6 else (0, 2)):
|
|
276
|
+
ev.append(Event(at(b), "kick", vel=0.95))
|
|
277
|
+
for b in (1, 3):
|
|
278
|
+
ev.append(Event(at(b), "snare", vel=0.85))
|
|
279
|
+
for k in range(8 if e < 0.8 else 16):
|
|
280
|
+
ev.append(Event(at(k * (0.5 if e < 0.8 else 0.25)), "hat", vel=0.3 + 0.15 * (k % 2 == 1)))
|
|
281
|
+
if fill:
|
|
282
|
+
for b in (3.0, 3.25, 3.5, 3.75):
|
|
283
|
+
ev.append(Event(at(b), "snare", vel=0.35 + (b - 3) * 0.5))
|
|
284
|
+
return ev
|
|
285
|
+
|
|
286
|
+
def melody(self, at, beat, i, s, scale, chord, inst) -> list[Event]:
|
|
287
|
+
r, ev = self.r, []
|
|
288
|
+
half = (i % 2) * 4 # which bar of the two-bar motif
|
|
289
|
+
pitch = getattr(self, "_mel", 72)
|
|
290
|
+
chord_pcs = {c % 12 for c in chord}
|
|
291
|
+
pool = sorted({p + 12 * o for p in scale for o in range(4, 8) if 64 <= p + 12 * o <= 86})
|
|
292
|
+
for b, length, move in s.motif:
|
|
293
|
+
if not (half <= b < half + 4):
|
|
294
|
+
continue
|
|
295
|
+
idx = min(range(len(pool)), key=lambda k: abs(pool[k] - pitch))
|
|
296
|
+
idx = max(0, min(len(pool) - 1, idx + move))
|
|
297
|
+
note = pool[idx]
|
|
298
|
+
if b % 1 == 0: # on the beat: land on a chord tone
|
|
299
|
+
near = [p for p in pool if p % 12 in chord_pcs]
|
|
300
|
+
note = min(near, key=lambda p: abs(p - note)) if near else note
|
|
301
|
+
pitch = note
|
|
302
|
+
if r.random() < 0.12: # vary it: no repetition is quite the same
|
|
303
|
+
continue
|
|
304
|
+
ev.append(Event(at(b - half), inst, note, length * beat * 0.95, 0.5 + r.random() * 0.2, pan=r.uniform(-0.3, 0.3)))
|
|
305
|
+
self._mel = pitch
|
|
306
|
+
return ev
|
|
307
|
+
|
|
308
|
+
def arp(self, beat, voicing, e) -> list[Event]:
|
|
309
|
+
notes = voicing + [v + 12 for v in voicing]
|
|
310
|
+
step = 0.25 if e > 0.45 else 0.5
|
|
311
|
+
pattern = notes + notes[-2:0:-1]
|
|
312
|
+
return [Event(k * step * beat, "arp", pattern[k % len(pattern)], step * beat * 0.8, 0.32, pan=0.35 * (1 if k % 2 else -1))
|
|
313
|
+
for k in range(int(4 / step))]
|
duskfm/engine.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""The engine: the composer's bars rendered to audio, block by block, with the effects that make lo-fi lo-fi and
|
|
2
|
+
synthwave shine, both following the style dial.
|
|
3
|
+
"""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from . import synth
|
|
9
|
+
from .compose import Bar, Composer
|
|
10
|
+
from .fx import Chorus, Dust, Filter, Master, Rain, Reverb, Tape
|
|
11
|
+
from .synth import SR
|
|
12
|
+
|
|
13
|
+
BUS_OF = {"keys": "keys", "poly": "keys", "bell": "melo", "lead": "melo", "arp": "melo", "pad": "pad", "bass": "bass",
|
|
14
|
+
"kick": "drums", "snare": "drums", "hat": "drums", "rim": "drums", "shaker": "drums"}
|
|
15
|
+
SENDS = {"keys": .22, "pad": .5, "melo": .42, "drums": .06, "bass": 0.0} # reverb sends, before the style adds more
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Bus:
|
|
19
|
+
"""Notes land here at their times; what rings past the end of a bar carries into the next."""
|
|
20
|
+
|
|
21
|
+
def __init__(self):
|
|
22
|
+
self.buf = np.zeros((0, 2))
|
|
23
|
+
|
|
24
|
+
def add(self, mono: np.ndarray, at: int, pan: float, gain: float = 1.0):
|
|
25
|
+
end = at + len(mono)
|
|
26
|
+
if end > len(self.buf):
|
|
27
|
+
self.buf = np.concatenate([self.buf, np.zeros((end - len(self.buf), 2))])
|
|
28
|
+
ang = (np.clip(pan, -1, 1) + 1) * np.pi / 4 # equal-power panning
|
|
29
|
+
self.buf[at:end, 0] += mono * np.cos(ang) * gain
|
|
30
|
+
self.buf[at:end, 1] += mono * np.sin(ang) * gain
|
|
31
|
+
|
|
32
|
+
def take(self, n: int) -> np.ndarray:
|
|
33
|
+
if len(self.buf) < n:
|
|
34
|
+
self.buf = np.concatenate([self.buf, np.zeros((n - len(self.buf), 2))])
|
|
35
|
+
out, self.buf = self.buf[:n], self.buf[n:]
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Engine:
|
|
40
|
+
def __init__(self, composer: Composer, rain: float = 0.0, boost: float = 0.0, dust: float | None = None):
|
|
41
|
+
self.c = composer
|
|
42
|
+
rng = np.random.default_rng(composer.seed)
|
|
43
|
+
synth.seed_noise(composer.seed)
|
|
44
|
+
self.rain, self.boost, self.dust_override = rain, boost, dust
|
|
45
|
+
self.buses = {k: Bus() for k in ("keys", "pad", "melo", "drums", "bass")}
|
|
46
|
+
self.reverb, self.tape, self.chorus = Reverb(rng), Tape(rng), Chorus()
|
|
47
|
+
self.dust, self.rainbed, self.master = Dust(rng), Rain(rng), Master()
|
|
48
|
+
self.warm = Filter("low", 6000)
|
|
49
|
+
self.drum_tone = Filter("low", 9000)
|
|
50
|
+
self.lowcut = Filter("high", 28)
|
|
51
|
+
self.label, self.section = "", ""
|
|
52
|
+
self.level = 1.0 # the slow automatic level: every style about equally loud
|
|
53
|
+
|
|
54
|
+
def render_bar(self) -> np.ndarray:
|
|
55
|
+
bar: Bar = self.c.next_bar()
|
|
56
|
+
self.label, self.section = bar.label, bar.section
|
|
57
|
+
st = bar.style
|
|
58
|
+
n = int(round(bar.seconds * SR))
|
|
59
|
+
beat = bar.seconds / 4
|
|
60
|
+
for e in bar.events:
|
|
61
|
+
mono = synth.render(e.inst, e.note, e.dur, e.vel, st)
|
|
62
|
+
bus = self.buses[BUS_OF[e.inst]]
|
|
63
|
+
at = int(e.t * SR)
|
|
64
|
+
bus.add(mono, at, e.pan)
|
|
65
|
+
if e.inst in ("lead", "arp"): # dotted-8th echoes
|
|
66
|
+
for k, g in ((1, .32), (2, .15)):
|
|
67
|
+
bus.add(synth.lowpass(mono, 3000), at + int(k * 0.75 * beat * SR), -e.pan if k == 1 else e.pan, g)
|
|
68
|
+
mix = {k: b.take(n) for k, b in self.buses.items()}
|
|
69
|
+
# each bus, then the room
|
|
70
|
+
lofi = max(0.0, 1 - st / 0.45)
|
|
71
|
+
mix["drums"] = self.crush(self.drum_tone_for(st, mix["drums"]), lofi * 0.6)
|
|
72
|
+
mix["pad"] = self.chorus(mix["pad"] + mix["keys"] * 0.0, 0.3 + st * 0.5)
|
|
73
|
+
level = {"keys": 1.0, "pad": 0.8 + st * 0.3, "melo": 0.75, "drums": 0.9 - (0.15 if st < 0.3 else 0), "bass": 0.95}
|
|
74
|
+
dry = sum(mix[k] * level[k] for k in mix)
|
|
75
|
+
send = sum(mix[k] * level[k] * (SENDS[k] + st * 0.18 * (k != "bass")) for k in mix)
|
|
76
|
+
wet = self.reverb(send)
|
|
77
|
+
out = dry + wet * (0.6 + st * 0.5)
|
|
78
|
+
# the tape and the air: dark, warbly and dusty at the lo-fi end; clear and bright at the synthwave end
|
|
79
|
+
self.warm.set(min(19000, 4200 + (st ** 1.4) * 15000))
|
|
80
|
+
out = self.warm(out)
|
|
81
|
+
out = self.tape(out, 0.15 + lofi * 0.85)
|
|
82
|
+
out = np.tanh(out * (1.1 + lofi * 0.4)) * 0.9 # a little tape saturation
|
|
83
|
+
dust = self.dust_override if self.dust_override is not None else 0.25 + lofi * 0.75
|
|
84
|
+
out = out + self.dust(n, dust) + self.rainbed(n, self.rain)
|
|
85
|
+
out = self.lowcut(out) * 0.55
|
|
86
|
+
rms = float(np.sqrt((out ** 2).mean())) + 1e-9
|
|
87
|
+
want = float(np.clip(10 ** (-18 / 20) / rms, 0.5, 3.0)) # aim at -18 dBFS
|
|
88
|
+
start, self.level = self.level, self.level + (want - self.level) * 0.25 # a quarter of the way each bar
|
|
89
|
+
out = out * np.linspace(start, self.level, n)[:, None]
|
|
90
|
+
return self.master(out, self.boost)
|
|
91
|
+
|
|
92
|
+
def drum_tone_for(self, st: float, x: np.ndarray) -> np.ndarray:
|
|
93
|
+
self.drum_tone.set(6500 if st < 0.35 else 16000)
|
|
94
|
+
return self.drum_tone(x)
|
|
95
|
+
|
|
96
|
+
def crush(self, x: np.ndarray, amount: float) -> np.ndarray:
|
|
97
|
+
"""Lo-fi drums: fewer bits and a lower sample rate, blended in."""
|
|
98
|
+
if amount <= 0.01:
|
|
99
|
+
return x
|
|
100
|
+
hold = 3
|
|
101
|
+
held = np.repeat(x[::hold], hold, axis=0)[: len(x)]
|
|
102
|
+
bits = 2 ** 9
|
|
103
|
+
crushed = np.round(held * bits) / bits
|
|
104
|
+
return x * (1 - amount) + crushed * amount
|
duskfm/fx.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Effects that run as a stream: each keeps its state between blocks, so nothing clicks at a block's edge.
|
|
2
|
+
|
|
3
|
+
Tape (wow and flutter), chorus, reverb (a generated impulse response, FFT convolution with its tail carried),
|
|
4
|
+
a warm low-pass, vinyl crackle and hiss, a rain bed that masks voices, and the master: compression, boost and a
|
|
5
|
+
soft limiter.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from scipy.signal import butter, fftconvolve, lfilter, sosfilt, sosfilt_zi
|
|
11
|
+
|
|
12
|
+
from .synth import SR
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Filter:
|
|
16
|
+
"""A stereo Butterworth filter whose cutoff can change between blocks, its state carried across."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, kind: str, cutoff, order: int = 2):
|
|
19
|
+
self.kind, self.order, self.cutoff, self.zi = kind, order, None, None
|
|
20
|
+
self.set(cutoff)
|
|
21
|
+
|
|
22
|
+
def set(self, cutoff):
|
|
23
|
+
if cutoff == self.cutoff:
|
|
24
|
+
return
|
|
25
|
+
self.cutoff = cutoff
|
|
26
|
+
self.sos = butter(self.order, cutoff, self.kind, fs=SR, output="sos")
|
|
27
|
+
if self.zi is None:
|
|
28
|
+
z = sosfilt_zi(self.sos) * 0
|
|
29
|
+
self.zi = [z.copy(), z.copy()]
|
|
30
|
+
|
|
31
|
+
def __call__(self, x: np.ndarray) -> np.ndarray:
|
|
32
|
+
out = np.empty_like(x)
|
|
33
|
+
for c in range(2):
|
|
34
|
+
out[:, c], self.zi[c] = sosfilt(self.sos, x[:, c], zi=self.zi[c])
|
|
35
|
+
return out
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ModDelay:
|
|
39
|
+
"""A delay line read at a moving position (fractional, interpolated): chorus, and tape's wow and flutter."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, max_delay_s: float):
|
|
42
|
+
self.hist = np.zeros((int(max_delay_s * SR) + 4, 2))
|
|
43
|
+
|
|
44
|
+
def __call__(self, x: np.ndarray, delay: np.ndarray) -> np.ndarray:
|
|
45
|
+
"""delay: samples, one per frame (or per channel: shape (n, 2))."""
|
|
46
|
+
h = len(self.hist)
|
|
47
|
+
buf = np.concatenate([self.hist, x])
|
|
48
|
+
idx = np.arange(len(x))[:, None] + h - np.atleast_2d(delay.T).T
|
|
49
|
+
idx = np.clip(idx, 0, len(buf) - 2)
|
|
50
|
+
i0 = np.floor(idx).astype(int)
|
|
51
|
+
frac = idx - i0
|
|
52
|
+
chans = np.arange(2)[None, :]
|
|
53
|
+
out = buf[i0, chans] * (1 - frac) + buf[i0 + 1, chans] * frac
|
|
54
|
+
self.hist = buf[-h:]
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Tape:
|
|
59
|
+
"""Wow (slow pitch drift) and flutter (fast wobble): the warble of old tape."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, rng: np.random.Generator):
|
|
62
|
+
self.line, self.phase, self.rng = ModDelay(0.03), 0.0, rng
|
|
63
|
+
self.wow_rate = 0.35 + rng.random() * 0.3
|
|
64
|
+
|
|
65
|
+
def __call__(self, x: np.ndarray, depth: float) -> np.ndarray:
|
|
66
|
+
if depth <= 0.001:
|
|
67
|
+
return x
|
|
68
|
+
n = len(x)
|
|
69
|
+
t = self.phase + np.arange(n) / SR
|
|
70
|
+
self.phase = t[-1] + 1 / SR
|
|
71
|
+
d = (6 + depth * 10 * np.sin(2 * np.pi * self.wow_rate * t) + depth * 1.2 * np.sin(2 * np.pi * 7.3 * t)) * SR / 1000
|
|
72
|
+
return self.line(x, d)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Chorus:
|
|
76
|
+
def __init__(self):
|
|
77
|
+
self.line, self.phase = ModDelay(0.04), 0.0
|
|
78
|
+
|
|
79
|
+
def __call__(self, x: np.ndarray, mix: float) -> np.ndarray:
|
|
80
|
+
if mix <= 0.001:
|
|
81
|
+
return x
|
|
82
|
+
n = len(x)
|
|
83
|
+
t = self.phase + np.arange(n) / SR
|
|
84
|
+
self.phase = t[-1] + 1 / SR
|
|
85
|
+
lfo = np.stack([np.sin(2 * np.pi * 0.6 * t), np.sin(2 * np.pi * 0.6 * t + 1.7)], axis=1)
|
|
86
|
+
wet = self.line(x, (12 + 4 * lfo) * SR / 1000)
|
|
87
|
+
return x * (1 - mix * 0.5) + wet * mix * 0.7
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Reverb:
|
|
91
|
+
"""Convolution with a generated room: decaying noise, darker as it fades, different on each side."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, rng: np.random.Generator, seconds: float = 2.8, decay: float = 2.2):
|
|
94
|
+
n = int(seconds * SR)
|
|
95
|
+
t = np.arange(n) / SR
|
|
96
|
+
env = np.exp(-t * (6.9 / decay))
|
|
97
|
+
ir = rng.standard_normal((n, 2)) * env[:, None]
|
|
98
|
+
# high frequencies die first: a growing low-pass, done as a blend of a dark and a bright copy
|
|
99
|
+
dark = sosfilt(butter(1, 2500, "low", fs=SR, output="sos"), ir, axis=0)
|
|
100
|
+
k = np.exp(-t * 3)[:, None]
|
|
101
|
+
ir = ir * k + dark * (1 - k)
|
|
102
|
+
ir[: int(0.012 * SR)] = 0 # a short pre-delay
|
|
103
|
+
self.ir = ir / np.sqrt((ir ** 2).sum(axis=0)) * 0.5
|
|
104
|
+
self.tail = np.zeros((n - 1, 2))
|
|
105
|
+
|
|
106
|
+
def __call__(self, x: np.ndarray) -> np.ndarray:
|
|
107
|
+
n = len(x)
|
|
108
|
+
wet = np.stack([fftconvolve(x[:, c], self.ir[:, c]) for c in range(2)], axis=1)
|
|
109
|
+
wet[: len(self.tail)] += self.tail[: len(wet)]
|
|
110
|
+
if len(self.tail) > len(wet): # a block shorter than the tail: keep the rest
|
|
111
|
+
rest = self.tail[len(wet):]
|
|
112
|
+
wet_tail = wet[n:]
|
|
113
|
+
new_tail = np.zeros_like(self.tail)
|
|
114
|
+
new_tail[: len(wet_tail)] += wet_tail
|
|
115
|
+
new_tail[: len(rest)] += rest
|
|
116
|
+
self.tail = new_tail
|
|
117
|
+
else:
|
|
118
|
+
self.tail = wet[n:n + len(self.tail)].copy()
|
|
119
|
+
return wet[:n]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Dust:
|
|
123
|
+
"""Vinyl: hiss and crackle, a little uneven so it never loops."""
|
|
124
|
+
|
|
125
|
+
def __init__(self, rng: np.random.Generator):
|
|
126
|
+
self.rng = rng
|
|
127
|
+
self.hiss_f = Filter("band", [1500, 9000])
|
|
128
|
+
self.pop_f = Filter("high", 1200)
|
|
129
|
+
|
|
130
|
+
def __call__(self, n: int, amount: float) -> np.ndarray:
|
|
131
|
+
if amount <= 0.001:
|
|
132
|
+
return np.zeros((n, 2))
|
|
133
|
+
hiss = self.hiss_f(self.rng.standard_normal((n, 2))) * 0.012
|
|
134
|
+
pops = np.zeros((n, 2))
|
|
135
|
+
k = self.rng.poisson(n / SR * 9)
|
|
136
|
+
for _ in range(k):
|
|
137
|
+
i, length = self.rng.integers(0, n), self.rng.integers(10, 120)
|
|
138
|
+
seg = self.rng.standard_normal(length) * np.exp(-np.arange(length) / (length / 4)) * self.rng.uniform(.05, .35)
|
|
139
|
+
end = min(n, i + length)
|
|
140
|
+
pops[i:end, self.rng.integers(0, 2)] += seg[: end - i]
|
|
141
|
+
return (hiss + self.pop_f(pops) * 0.25) * amount
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class Rain:
|
|
145
|
+
"""A soft rain bed shaped to the band speech lives in: it covers voices better than turning the music up."""
|
|
146
|
+
|
|
147
|
+
def __init__(self, rng: np.random.Generator):
|
|
148
|
+
self.rng = rng
|
|
149
|
+
self.body = Filter("band", [250, 4500])
|
|
150
|
+
self.drops = Filter("high", 2500)
|
|
151
|
+
self.slow = 0.0
|
|
152
|
+
|
|
153
|
+
def __call__(self, n: int, amount: float) -> np.ndarray:
|
|
154
|
+
if amount <= 0.001:
|
|
155
|
+
return np.zeros((n, 2))
|
|
156
|
+
brown = np.cumsum(self.rng.standard_normal((n, 2)) * 0.02, axis=0)
|
|
157
|
+
brown -= np.linspace(0, 1, n)[:, None] * brown[-1] # keep it from wandering off
|
|
158
|
+
body = self.body(self.rng.standard_normal((n, 2)) * 0.6 + brown)
|
|
159
|
+
sparkle = np.zeros((n, 2))
|
|
160
|
+
for _ in range(self.rng.poisson(n / SR * 60)):
|
|
161
|
+
i = self.rng.integers(0, n - 40)
|
|
162
|
+
sparkle[i:i + 40, self.rng.integers(0, 2)] += self.rng.standard_normal(40) * np.exp(-np.arange(40) / 8) * 0.4
|
|
163
|
+
return (body * 0.07 + self.drops(sparkle) * 0.06) * amount
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class Master:
|
|
167
|
+
"""The last stage: the mix levelled, then `boost` (dB) driven into a compressor and a soft limiter, so it gets
|
|
168
|
+
much louder without clipping, like a maximizer behind the volume knob."""
|
|
169
|
+
|
|
170
|
+
def __init__(self):
|
|
171
|
+
self.alpha = np.exp(-1 / (0.08 * SR))
|
|
172
|
+
self.zi = np.zeros(1)
|
|
173
|
+
|
|
174
|
+
def __call__(self, x: np.ndarray, boost_db: float) -> np.ndarray:
|
|
175
|
+
g = 10 ** (boost_db / 20)
|
|
176
|
+
x = x * g
|
|
177
|
+
# compression: RMS over ~80 ms, 3:1 above -16 dBFS
|
|
178
|
+
sq = np.maximum(x[:, 0] ** 2, x[:, 1] ** 2)
|
|
179
|
+
env, self.zi = lfilter([1 - self.alpha], [1, -self.alpha], sq, zi=self.zi)
|
|
180
|
+
rms = np.sqrt(np.maximum(env, 1e-12))
|
|
181
|
+
thresh = 10 ** (-16 / 20)
|
|
182
|
+
gain = np.where(rms > thresh, (thresh / rms) ** (1 - 1 / 3), 1.0)
|
|
183
|
+
y = x * gain[:, None] * (1 + min(boost_db, 18) / 18 * 0.4) # make-up gain grows with the boost
|
|
184
|
+
# soft limiter: transparent below ~-3 dBFS, rounds off above, never past the ceiling
|
|
185
|
+
ceiling = 0.97
|
|
186
|
+
return ceiling * np.tanh(y / ceiling)
|
duskfm/player.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Getting sound out: pipe raw audio to whatever plays it on this machine.
|
|
2
|
+
|
|
3
|
+
On Linux that's paplay (PulseAudio, or PipeWire's pulse layer: the one xrdp's audio uses), pw-cat (PipeWire) or
|
|
4
|
+
aplay (ALSA): nothing to install. With the sounddevice extra (pip install "duskfm[sounddevice]"), PortAudio works
|
|
5
|
+
too, on any system. A renderer thread keeps a few seconds ready; the volume applies as the audio goes out, so it
|
|
6
|
+
answers at once.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import queue
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
import threading
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from .synth import SR
|
|
18
|
+
|
|
19
|
+
PIPES = {
|
|
20
|
+
"paplay": ["paplay", "--raw", f"--rate={SR}", "--channels=2", "--format=s16le", "--client-name=duskfm"],
|
|
21
|
+
"pw-cat": ["pw-cat", "--playback", f"--rate={SR}", "--channels=2", "--format=s16", "-"],
|
|
22
|
+
"aplay": ["aplay", "-q", "-t", "raw", "-f", "S16_LE", "-r", str(SR), "-c", "2", "-"],
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def backends() -> list[str]:
|
|
27
|
+
"""What can play here, best first."""
|
|
28
|
+
found = [b for b in PIPES if shutil.which(PIPES[b][0])]
|
|
29
|
+
try:
|
|
30
|
+
__import__("sounddevice") # it needs the PortAudio library too: importing it says whether that's here
|
|
31
|
+
found.append("sounddevice")
|
|
32
|
+
except Exception: # not installed, or no PortAudio library on this system
|
|
33
|
+
pass
|
|
34
|
+
return found
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Player:
|
|
38
|
+
"""Plays blocks from `source()` (float stereo arrays) until stopped. `volume` (0..1) can change any time."""
|
|
39
|
+
|
|
40
|
+
CHUNK = 2048
|
|
41
|
+
|
|
42
|
+
def __init__(self, source, backend: str | None = None, ahead_s: float = 3.0):
|
|
43
|
+
self.source, self.volume, self.paused = source, 0.8, False
|
|
44
|
+
self.queue: queue.Queue = queue.Queue(maxsize=max(2, int(ahead_s)))
|
|
45
|
+
self.stopping = threading.Event()
|
|
46
|
+
self.fade = None # (frames left, total frames): fading out to silence, then stopping
|
|
47
|
+
have = backends()
|
|
48
|
+
if not have:
|
|
49
|
+
raise RuntimeError("nothing here can play audio: install pulseaudio-utils (paplay), pipewire (pw-cat) or "
|
|
50
|
+
"alsa-utils (aplay), or pip install \"duskfm[sounddevice]\"; or use --render to a file")
|
|
51
|
+
self.backend = backend or have[0]
|
|
52
|
+
if self.backend not in have:
|
|
53
|
+
raise RuntimeError(f"{self.backend} isn't available here (found: {', '.join(have)})")
|
|
54
|
+
self.error = None
|
|
55
|
+
|
|
56
|
+
def start(self):
|
|
57
|
+
threading.Thread(target=self.render_ahead, daemon=True).start()
|
|
58
|
+
threading.Thread(target=self.play, daemon=True).start()
|
|
59
|
+
|
|
60
|
+
def render_ahead(self):
|
|
61
|
+
while not self.stopping.is_set():
|
|
62
|
+
try:
|
|
63
|
+
block = self.source()
|
|
64
|
+
except Exception as e: # never leave the player waiting forever
|
|
65
|
+
self.error = e
|
|
66
|
+
self.stopping.set()
|
|
67
|
+
return
|
|
68
|
+
for i in range(0, len(block), self.CHUNK):
|
|
69
|
+
while not self.stopping.is_set():
|
|
70
|
+
try:
|
|
71
|
+
self.queue.put(block[i:i + self.CHUNK], timeout=0.2)
|
|
72
|
+
break
|
|
73
|
+
except queue.Full:
|
|
74
|
+
continue
|
|
75
|
+
|
|
76
|
+
def next_chunk(self) -> np.ndarray:
|
|
77
|
+
if self.paused:
|
|
78
|
+
return np.zeros((self.CHUNK, 2))
|
|
79
|
+
try:
|
|
80
|
+
x = self.queue.get(timeout=1.0)
|
|
81
|
+
except queue.Empty:
|
|
82
|
+
return np.zeros((self.CHUNK, 2))
|
|
83
|
+
x = x * self.volume
|
|
84
|
+
if self.fade:
|
|
85
|
+
left, total = self.fade
|
|
86
|
+
k = np.clip((left - np.arange(len(x))) / total, 0, 1)
|
|
87
|
+
x = x * k[:, None]
|
|
88
|
+
self.fade = (left - len(x), total)
|
|
89
|
+
if left - len(x) <= 0:
|
|
90
|
+
self.stopping.set()
|
|
91
|
+
return x
|
|
92
|
+
|
|
93
|
+
def fade_out(self, seconds: float):
|
|
94
|
+
frames = int(seconds * SR)
|
|
95
|
+
self.fade = (frames, frames)
|
|
96
|
+
|
|
97
|
+
def play(self):
|
|
98
|
+
try:
|
|
99
|
+
if self.backend == "sounddevice":
|
|
100
|
+
self.play_sounddevice()
|
|
101
|
+
else:
|
|
102
|
+
self.play_pipe()
|
|
103
|
+
except Exception as e:
|
|
104
|
+
self.error = e
|
|
105
|
+
self.stopping.set()
|
|
106
|
+
|
|
107
|
+
def play_pipe(self):
|
|
108
|
+
proc = subprocess.Popen(PIPES[self.backend], stdin=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
109
|
+
try:
|
|
110
|
+
while not self.stopping.is_set():
|
|
111
|
+
x = self.next_chunk()
|
|
112
|
+
proc.stdin.write((np.clip(x, -1, 1) * 32767).astype("<i2").tobytes())
|
|
113
|
+
proc.stdin.close()
|
|
114
|
+
except BrokenPipeError:
|
|
115
|
+
err = proc.stderr.read().decode(errors="replace").strip()
|
|
116
|
+
raise RuntimeError(f"{self.backend} stopped: {err or 'no audio device?'}") from None
|
|
117
|
+
finally:
|
|
118
|
+
proc.terminate()
|
|
119
|
+
|
|
120
|
+
def play_sounddevice(self):
|
|
121
|
+
import sounddevice as sd
|
|
122
|
+
with sd.OutputStream(samplerate=SR, channels=2, dtype="float32", blocksize=self.CHUNK) as out:
|
|
123
|
+
while not self.stopping.is_set():
|
|
124
|
+
out.write(np.clip(self.next_chunk(), -1, 1).astype("float32"))
|
|
125
|
+
|
|
126
|
+
def stop(self):
|
|
127
|
+
self.stopping.set()
|
duskfm/synth.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""The instruments: every sound built from oscillators and noise, one note at a time (mono numpy arrays).
|
|
2
|
+
|
|
3
|
+
FM electric piano (the lo-fi keys), detuned-saw pads and a polysynth (the synthwave sheen), a bell, an arp pluck,
|
|
4
|
+
a lead, bass, and a drum kit synthesized from sweeps and filtered noise. No samples anywhere.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from scipy.signal import butter, fftconvolve, sosfilt
|
|
12
|
+
|
|
13
|
+
from .compose import midi_hz
|
|
14
|
+
|
|
15
|
+
SR = 44100
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def t_axis(seconds: float) -> np.ndarray:
|
|
19
|
+
return np.arange(max(1, int(seconds * SR))) / SR
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def adsr(n: int, a: float, d: float, s: float, r: float, hold: int) -> np.ndarray:
|
|
23
|
+
"""Attack, decay, sustain level, release (seconds); the note is held for `hold` samples, then released."""
|
|
24
|
+
env = np.zeros(n)
|
|
25
|
+
A, D, R = max(1, int(a * SR)), max(1, int(d * SR)), max(1, int(r * SR))
|
|
26
|
+
hold = max(1, min(hold, n))
|
|
27
|
+
seg = np.concatenate([np.linspace(0, 1, A, endpoint=False), 1 - (1 - s) * (1 - np.exp(-5 * np.arange(D) / D))])
|
|
28
|
+
k = min(hold, len(seg))
|
|
29
|
+
env[:k] = seg[:k]
|
|
30
|
+
if hold > len(seg):
|
|
31
|
+
env[len(seg):hold] = s
|
|
32
|
+
level = env[hold - 1]
|
|
33
|
+
tail = min(R, n - hold)
|
|
34
|
+
if tail > 0:
|
|
35
|
+
env[hold:hold + tail] = level * np.exp(-5 * np.arange(tail) / R)
|
|
36
|
+
return env
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
TABLE = 2048
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@lru_cache(maxsize=64)
|
|
43
|
+
def saw_table(harmonics: int) -> np.ndarray:
|
|
44
|
+
"""One cycle of a saw built from `harmonics` harmonics: band-limited, so no aliasing whistle."""
|
|
45
|
+
x = np.arange(TABLE) / TABLE
|
|
46
|
+
return sum(np.sin(2 * np.pi * k * x) / k for k in range(1, harmonics + 1)) * 0.55
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def saw(freq: float, t: np.ndarray, phase: float = 0.0) -> np.ndarray:
|
|
50
|
+
"""A saw with harmonics up to ~9 kHz, read from a cached one-cycle table (cheap, however long the note)."""
|
|
51
|
+
table = saw_table(max(1, min(40, int(9000 / freq))))
|
|
52
|
+
pos = ((freq * t + phase / (2 * np.pi)) % 1.0) * TABLE
|
|
53
|
+
i = pos.astype(int)
|
|
54
|
+
frac = pos - i
|
|
55
|
+
return table[i] * (1 - frac) + table[(i + 1) % TABLE] * frac
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def lowpass(x: np.ndarray, cutoff: float, order: int = 2) -> np.ndarray:
|
|
59
|
+
cutoff = min(cutoff, SR * 0.45)
|
|
60
|
+
return sosfilt(butter(order, cutoff, "low", fs=SR, output="sos"), x)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def highpass(x: np.ndarray, cutoff: float, order: int = 2) -> np.ndarray:
|
|
64
|
+
return sosfilt(butter(order, cutoff, "high", fs=SR, output="sos"), x)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def bandpass(x: np.ndarray, lo: float, hi: float, order: int = 2) -> np.ndarray:
|
|
68
|
+
return sosfilt(butter(order, [lo, min(hi, SR * 0.45)], "band", fs=SR, output="sos"), x)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
RNG = np.random.default_rng()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def seed_noise(seed: int):
|
|
75
|
+
global RNG
|
|
76
|
+
RNG = np.random.default_rng(seed)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def noise(n: int) -> np.ndarray:
|
|
80
|
+
return RNG.standard_normal(n)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# --- tonal instruments: (freq, seconds held, velocity) -> samples, tail included
|
|
84
|
+
|
|
85
|
+
def keys(f: float, dur: float, vel: float) -> np.ndarray:
|
|
86
|
+
"""FM electric piano: a sine carrier, a 1:1 modulator for warmth and a 14:1 one for the tine's bell, both fading."""
|
|
87
|
+
t = t_axis(dur + 1.2)
|
|
88
|
+
hold = int(dur * SR)
|
|
89
|
+
idx = (1.6 + vel) * np.exp(-t * 2.5)
|
|
90
|
+
bell = 0.9 * np.exp(-t * 18)
|
|
91
|
+
mod = idx * np.sin(2 * np.pi * f * t) + bell * np.sin(2 * np.pi * f * 14 * t)
|
|
92
|
+
tone = np.sin(2 * np.pi * f * t + mod)
|
|
93
|
+
tone *= 1 + 0.08 * np.sin(2 * np.pi * 4.5 * t) # a gentle tremolo
|
|
94
|
+
env = adsr(len(t), 0.004, 1.4, 0.35, 0.45, hold) * np.exp(-t * 0.35)
|
|
95
|
+
return tone * env * vel * 0.5
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def pad(f: float, dur: float, vel: float) -> np.ndarray:
|
|
99
|
+
"""Three slightly detuned saws, dark and slow: the haze."""
|
|
100
|
+
t = t_axis(dur + 2.0)
|
|
101
|
+
tone = sum(saw(f * d, t, p) for d, p in ((1.0, 0.0), (1.006, 1.3), (0.994, 2.6))) / 3
|
|
102
|
+
tone = lowpass(tone, 900 + 2.5 * f)
|
|
103
|
+
return tone * adsr(len(t), 0.9, 1.0, 0.8, 1.6, int(dur * SR)) * vel * 0.45
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def poly(f: float, dur: float, vel: float) -> np.ndarray:
|
|
107
|
+
"""The 80s polysynth: two saws and a square, brighter, with a quick swell."""
|
|
108
|
+
t = t_axis(dur + 0.9)
|
|
109
|
+
sq = np.sign(np.sin(2 * np.pi * f * t)) * 0.3
|
|
110
|
+
tone = (saw(f, t) + saw(f * 1.004, t, 1.0)) * 0.5 + lowpass(sq, 3000)
|
|
111
|
+
tone = lowpass(tone, 2200 + 3 * f)
|
|
112
|
+
return tone * adsr(len(t), 0.03, 0.4, 0.7, 0.7, int(dur * SR)) * vel * 0.38
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def bell(f: float, dur: float, vel: float) -> np.ndarray:
|
|
116
|
+
"""A soft glassy bell (FM at 3.5:1): the chillwave melody."""
|
|
117
|
+
t = t_axis(dur + 1.5)
|
|
118
|
+
tone = np.sin(2 * np.pi * f * t + 1.8 * np.exp(-t * 3) * np.sin(2 * np.pi * f * 3.5 * t))
|
|
119
|
+
return tone * adsr(len(t), 0.005, 1.2, 0.2, 0.9, int(dur * SR)) * vel * 0.42
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def arp(f: float, dur: float, vel: float) -> np.ndarray:
|
|
123
|
+
"""A plucky synth: saw through a closing filter."""
|
|
124
|
+
t = t_axis(dur + 0.25)
|
|
125
|
+
tone = saw(f, t)
|
|
126
|
+
bright = lowpass(tone, 5000)
|
|
127
|
+
dark = lowpass(tone, 900)
|
|
128
|
+
k = np.exp(-t * 14)
|
|
129
|
+
return (bright * k + dark * (1 - k)) * adsr(len(t), 0.002, 0.15, 0.3, 0.2, int(dur * SR)) * vel * 0.5
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def lead(f: float, dur: float, vel: float) -> np.ndarray:
|
|
133
|
+
"""A singing lead: square and saw with a delayed vibrato."""
|
|
134
|
+
t = t_axis(dur + 0.6)
|
|
135
|
+
vib = 1 + 0.006 * np.sin(2 * np.pi * 5.2 * t) * np.clip(t / 0.35, 0, 1)
|
|
136
|
+
phase = 2 * np.pi * np.cumsum(f * vib) / SR
|
|
137
|
+
tone = 0.6 * np.sign(np.sin(phase)) + 0.5 * np.sin(phase) + 0.3 * np.sin(2 * phase)
|
|
138
|
+
tone = lowpass(tone, 2800)
|
|
139
|
+
return tone * adsr(len(t), 0.02, 0.3, 0.75, 0.4, int(dur * SR)) * vel * 0.3
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def bass(f: float, dur: float, vel: float, style: float = 0.0) -> np.ndarray:
|
|
143
|
+
"""Lo-fi: a round sine with a touch of grit. Synthwave: a plucked saw."""
|
|
144
|
+
t = t_axis(dur + 0.15)
|
|
145
|
+
hold = int(dur * SR)
|
|
146
|
+
soft = np.sin(2 * np.pi * f * t) + 0.12 * np.tanh(3 * np.sin(2 * np.pi * f * t))
|
|
147
|
+
if style > 0.6:
|
|
148
|
+
tone = saw(f, t)
|
|
149
|
+
k = np.exp(-t * 10)
|
|
150
|
+
tone = lowpass(tone, 2400) * k + lowpass(tone, 500) * (1 - k)
|
|
151
|
+
tone = (1 - (style - 0.6) * 2.5) * soft + (style - 0.6) * 2.5 * tone * 1.3
|
|
152
|
+
else:
|
|
153
|
+
tone = soft
|
|
154
|
+
return tone * adsr(len(t), 0.006, 0.3, 0.8, 0.12, hold) * vel * 0.6
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# --- drums: (velocity, style) -> samples
|
|
158
|
+
|
|
159
|
+
def kick(vel: float, style: float) -> np.ndarray:
|
|
160
|
+
t = t_axis(0.55)
|
|
161
|
+
f = 45 + (110 + style * 60) * np.exp(-t * 28) # the pitch drops fast: thump
|
|
162
|
+
body = np.sin(2 * np.pi * np.cumsum(f) / SR) * np.exp(-t * (7 - style * 2))
|
|
163
|
+
click = highpass(noise(len(t)), 2000) * np.exp(-t * 300) * (0.15 + style * 0.25)
|
|
164
|
+
return np.tanh((body + click) * (1.2 + style)) * vel * 0.9
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def snare(vel: float, style: float) -> np.ndarray:
|
|
168
|
+
t = t_axis(0.35 if style < 0.7 else 0.8)
|
|
169
|
+
tone = np.sin(2 * np.pi * 185 * t) * np.exp(-t * 25)
|
|
170
|
+
rattle = bandpass(noise(len(t)), 1200, 7000 if style < 0.4 else 10000) * np.exp(-t * (18 if style < 0.7 else 12))
|
|
171
|
+
hit = tone * 0.6 + rattle * 0.8
|
|
172
|
+
if style > 0.7: # the 80s: a big room, then cut short
|
|
173
|
+
ir = noise(int(0.5 * SR)) * np.exp(-np.arange(int(0.5 * SR)) / SR * 6)
|
|
174
|
+
room = fftconvolve(hit, ir)[: len(hit)] * 0.06
|
|
175
|
+
gate = np.clip(1 - (t - 0.28) / 0.05, 0, 1)
|
|
176
|
+
hit = (hit + room) * gate
|
|
177
|
+
return hit * vel * (0.55 if style < 0.4 else 0.65)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def hat(vel: float, style: float) -> np.ndarray:
|
|
181
|
+
t = t_axis(0.09)
|
|
182
|
+
return highpass(noise(len(t)), 7000 if style > 0.5 else 6000) * np.exp(-t * (60 if style > 0.5 else 45)) * vel * 0.35
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def rim(vel: float, style: float) -> np.ndarray:
|
|
186
|
+
t = t_axis(0.08)
|
|
187
|
+
return (np.sin(2 * np.pi * 1700 * t) * 0.5 + bandpass(noise(len(t)), 2000, 6000) * 0.4) * np.exp(-t * 70) * vel * 0.5
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def shaker(vel: float, style: float) -> np.ndarray:
|
|
191
|
+
t = t_axis(0.11)
|
|
192
|
+
env = np.minimum(t / 0.02, 1) * np.exp(-t * 35)
|
|
193
|
+
return bandpass(noise(len(t)), 4000, 12000) * env * vel * 0.4
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
TONAL = {"keys": keys, "pad": pad, "poly": poly, "bell": bell, "arp": arp, "lead": lead}
|
|
197
|
+
DRUMS = {"kick": kick, "snare": snare, "hat": hat, "rim": rim, "shaker": shaker}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def render(inst: str, note: float, dur: float, vel: float, style: float) -> np.ndarray:
|
|
201
|
+
if inst in DRUMS:
|
|
202
|
+
return DRUMS[inst](vel, style)
|
|
203
|
+
if inst == "bass":
|
|
204
|
+
return bass(midi_hz(note), dur, vel, style)
|
|
205
|
+
return TONAL[inst](midi_hz(note), dur, vel)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: duskfm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Endless, never-repeating music from lo-fi to synthwave, synthesized on the spot: no samples, nothing recorded.
|
|
5
|
+
Keywords: lofi,lo-fi,synthwave,chillwave,generative,music,focus,ambient,synthesizer
|
|
6
|
+
Author: Frank Lynam
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
13
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Sound Synthesis
|
|
17
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Players
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: numpy>=1.22
|
|
20
|
+
Requires-Dist: scipy>=1.8
|
|
21
|
+
Requires-Dist: sounddevice>=0.4 ; extra == "sounddevice"
|
|
22
|
+
Project-URL: Homepage, https://github.com/frank-lynam/duskfm
|
|
23
|
+
Project-URL: Issues, https://github.com/frank-lynam/duskfm/issues
|
|
24
|
+
Provides-Extra: sounddevice
|
|
25
|
+
|
|
26
|
+
# duskfm
|
|
27
|
+
|
|
28
|
+
Endless music from lo-fi to synthwave, made on the spot: never the same twice, all day long.
|
|
29
|
+
|
|
30
|
+
Every sound is synthesized as it plays: an FM electric piano, detuned pads, a polysynth, bass, a drum kit made of
|
|
31
|
+
sweeps and noise, tape wobble, vinyl dust. No samples and nothing recorded, so the package is a few files of Python.
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install duskfm
|
|
35
|
+
duskfm # lo-fi
|
|
36
|
+
duskfm synthwave # or: lofi, chillhop, chillwave, synthwave, nightdrive, ambient
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## One dial from lo-fi to synthwave
|
|
40
|
+
|
|
41
|
+
`--style` runs from 0 (lo-fi) to 1 (synthwave), and everything blends along it:
|
|
42
|
+
|
|
43
|
+
| | lo-fi (0) | chillwave (0.5) | synthwave (1) |
|
|
44
|
+
|---|---|---|---|
|
|
45
|
+
| tempo | 72–84, swung | ~85–97 | 94–110, straight |
|
|
46
|
+
| harmony | jazzy 7ths and 9ths (ii–V–I) | dreamy maj9 and sus | minor: i–VI–III–VII |
|
|
47
|
+
| keys | FM electric piano | piano, pads, a glassy bell | polysynth, arpeggios, a lead |
|
|
48
|
+
| drums | dusty boom-bap, lazy | soft kick, rim, shaker | punchy, 80s gated snare |
|
|
49
|
+
| texture | crackle, tape wobble, dark | haze, chorus | bright, wide, big reverb |
|
|
50
|
+
|
|
51
|
+
`--energy` runs from 0 (ambient: no drums, sparse) to 1 (driving). `--drift` lets both wander slowly on their own,
|
|
52
|
+
so a long session moves through moods. The presets are points on the two dials (`duskfm --help` lists them).
|
|
53
|
+
|
|
54
|
+
It composes as it goes: chord progressions voiced smoothly from one to the next, melodies grown from short motifs and
|
|
55
|
+
varied each time, sections that thin out and build back, a new key and tempo every few minutes. `--seed` replays
|
|
56
|
+
a session you liked (the seed is shown when you quit).
|
|
57
|
+
|
|
58
|
+
## While it plays
|
|
59
|
+
|
|
60
|
+
| key | |
|
|
61
|
+
|---|---|
|
|
62
|
+
| ← → | style: toward lo-fi, toward synthwave |
|
|
63
|
+
| ↑ ↓ | energy |
|
|
64
|
+
| + − | volume |
|
|
65
|
+
| ] [ | boost (3 dB a press) |
|
|
66
|
+
| r | rain: off, light, heavy |
|
|
67
|
+
| d | drift on or off |
|
|
68
|
+
| n | on to the next section |
|
|
69
|
+
| 1–6 | the presets |
|
|
70
|
+
| space | pause |
|
|
71
|
+
| q | quit (it fades out) |
|
|
72
|
+
|
|
73
|
+
## Loud enough to drown out the room
|
|
74
|
+
|
|
75
|
+
- `--volume` (0–100) is the ordinary level.
|
|
76
|
+
- `--boost DB` (up to 18) is the maximizer behind it: the music is compressed and driven into a soft limiter, so it
|
|
77
|
+
gets much louder without ever clipping. Your speakers' own limit still applies; this gets more out of it.
|
|
78
|
+
- `--rain` adds a soft rain bed shaped to the frequencies speech lives in. Lo-fi is mellow and dark, which is
|
|
79
|
+
lovely and also poor at covering voices; a little rain covers chatter better than a lot more volume, and spares
|
|
80
|
+
your ears. A whole day at high volume is hard on hearing: reach for the rain first.
|
|
81
|
+
|
|
82
|
+
## Playing it
|
|
83
|
+
|
|
84
|
+
On Linux it plays through `paplay` (PulseAudio, or PipeWire's pulse layer), `pw-cat` or `aplay`, whichever is
|
|
85
|
+
there: nothing else to install. Over remote desktop (xrdp), sound comes through when the session has xrdp's
|
|
86
|
+
PulseAudio or PipeWire module; if `paplay` works there, duskfm does. Elsewhere, `pip install "duskfm[sounddevice]"`
|
|
87
|
+
uses PortAudio.
|
|
88
|
+
|
|
89
|
+
No sound where you are? Make a file and play it anywhere:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
duskfm chillwave --render 3h -o afternoon.wav
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`--minutes 90` plays for a while and then fades out.
|
|
96
|
+
|
|
97
|
+
## Development
|
|
98
|
+
|
|
99
|
+
`python3 tests/test_duskfm.py`: every preset renders clean audio at a steady level, a seed replays exactly, nothing
|
|
100
|
+
loops, boost gets louder without clipping, and the player and command line work (no sound card needed). A GitHub
|
|
101
|
+
release `vX.Y.Z` matching `__version__` publishes to PyPI.
|
|
102
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
duskfm/__init__.py,sha256=jQVXEtEdFKtxlCLy2E-P4iFzealGnz05HSthqyGWEEg,90
|
|
2
|
+
duskfm/__main__.py,sha256=Huz0dExiaH0XTMLhfe3skkFD9-VH7ZUiWMbDR_J8TIY,28
|
|
3
|
+
duskfm/cli.py,sha256=l6Iis-td2cmRDQx-MItvX9m87nZadn0VP15Hmyh-HrA,8727
|
|
4
|
+
duskfm/compose.py,sha256=NmTBsv1p_ao5W2eaoLCfASj4HuHuYsaIr_bA8iFxG2M,15693
|
|
5
|
+
duskfm/engine.py,sha256=1XqV2Xxj6eMlqzZ0u6RoE3ZE585k20zpisyUKVyQE5M,5163
|
|
6
|
+
duskfm/fx.py,sha256=oRbaiHL7UEVba_imZ1OIW3vxUV46xyYiyUNDsgHVs28,7663
|
|
7
|
+
duskfm/player.py,sha256=wGe6LknexAFOD5o7A1oW-a4fzppI1QkefA3rodDoaM8,4926
|
|
8
|
+
duskfm/synth.py,sha256=tBD0tNU8erilb6k34pj63e1vzzoNnkWIILkP5Kwp0Hw,8139
|
|
9
|
+
duskfm-0.1.0.dist-info/entry_points.txt,sha256=bI5aNdNzLVHi_7Y02GsbSDfepv2wNOnFbE90-I7KajY,41
|
|
10
|
+
duskfm-0.1.0.dist-info/licenses/LICENSE,sha256=kS2xaDPY2aH4QtYsz220wwci9CFGNufXDQLxsTS2uLE,1068
|
|
11
|
+
duskfm-0.1.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
|
|
12
|
+
duskfm-0.1.0.dist-info/METADATA,sha256=0dCGjAVFqOUq_dODLwUoCnxCjdr_j7pa2HHCpmR-d20,4439
|
|
13
|
+
duskfm-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Frank Lynam
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|