/ interactive_tutorials / duffing_islands
Sign in
interactive_tutorials / duffing_islands
Tracks, SoundFonts, sessions, recording and MIDI
- A list of tracks, each with its own orbit (a start picked on the plot), instrument, rhythm, scale, key, tempo multiple, sustain, volume and velocity; settings can be linked across tracks (scale and key by default). Tracks start paused and can be restarted. - A global tempo in bpm, with a per-track multiple (x1 by default). - Changing the equation, tempo or coupling carries the tracks on smoothly instead of restarting them. - Several .sf2 SoundFonts at once. - The session is saved in the browser and can be saved to and opened from a file that carries its SoundFonts. - Video recording (MP4 or WebM) of the phase space with the audio. - Custom notes per track (or shared by linked tracks) from a MIDI keyboard or an on-screen piano; MIDI knobs (absolute or relative) assignable to the equation's sliders and the coupling. - A no-cache dev server (npm run dev). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 574ea55bbf9a parent 4087941 Browse files
10 changed files+2628−415
README.mdmodified+18−7View file
@@ -5,7 +5,7 @@ A minimal lab for the driven Duffing oscillator's phase space, a companion to th
55 ẍ + δẋ ± (2πf₀)² x + αx³ = F cos Ωt
66
77 ```bash
8-npm run dev # serves app/ at http://127.0.0.1:8002
8+npm run dev # serves app/ at http://127.0.0.1:8002, caching off
99 npm run check # node --check on every module
1010 node scripts/section-png.mjs out.png -220 2e7 0 5.6e4 490 1500 0.5 # render a section (for choosing presets)
1111 ```
@@ -15,15 +15,26 @@ Static `index.html`, `style.css` and ES modules, no build step; fonts bundled un
1515 ## What's in it
1616
1717 - **Poincaré section**: (x, ẋ) once per drive period, at drive phase 0. Seed orbits from the axes of the view fill it in live. Undamped, regular orbits draw closed curves (islands, island chains) and chaotic ones scatter over the sea. Damped, the seeds settle onto the attractors first.
18-- **Click** to add an orbit from that point (up to 8; click its start ring to remove it; with *Clicks: replace the orbit*, each click starts a new orbit in place of the old ones, for quick exploring): its dots fill in (larger, brighter), and a playhead walks it one drive period per beat, with a fading trail of the continuous motion through each period and a ring at each return to the section. Changing a parameter or preset keeps them, restarted from the same (x, ẋ) under the new parameters. All the clicked orbits play together, on the same beat, each in its own voice (listed in the panel with its color; × removes it).
19-- **Sound**: each return to the section plays a note, its pitch set by x (left to right across the view: C3 to C6), on a selectable scale (minor pentatonic by default; major pentatonic, major, minors, whole tone, chromatic, or continuous) in a selectable key (A by default). The key buttons keep the register (C3 to C6) and change which notes x snaps to, so switching key while playing shifts the harmony like a chord change. An island orbit plays a repeating pattern; a chaotic one wanders. Tempo sets drive periods per second (default 16, up to 40; the motion is slowed down to that), independent of the drive frequency.
20-- **Voices**: the first orbit plays a harp; the next ones marimba, vibraphone, electric piano, music box, ocarina, pizzicato and kalimba (an orbit takes the first voice not in use). **Sustain** (0.1 to 4 s, default 2) sets how long every note rings, the same for all voices and pitches, so they differ only in timbre and attack, and all start equally loud.
21-- **Rhythm**: *natural, upward* plucks wherever ẋ crosses 0 upward (the left turning point of each swing), at that x and at that moment in the slowed-down motion, so each orbit makes its own rhythm: a lilting, nearly regular one on an island, an uneven one in the sea, and several orbits make polyrhythms. *Both ways* (the default) also plucks at the right turning point (ẋ crossing 0 downward), so each swing plays its low and high end. *Steady* plucks once per drive period, at the section point.
22-- **Coupling** (optional, off by default; 1 to about 3000 s⁻¹ on a log scale): joins the clicked orbits into one system, each pulled toward their mean by a spring and a damper on its difference (critically damped at rate r), leaving the mean motion as it was. Weakly coupled they nudge each other (and lose the energy of their mismatch, often settling into islands); strongly coupled they fall into step and play in unison, even in the chaotic sea. On the first preset, three sea orbits lock above about 900 s⁻¹. While coupled, adding or removing an orbit, or changing the coupling, restarts the clicked orbits from their starts.
18+- **Tempo and sound** (top right): the global tempo (40 to 240 bpm, default 120), the big sound on/off button, and the master volume. A track played while the sound is off makes the button pulse.
19+- **Tracks** (right panel, up to 8): each is an orbit and how it plays. Tracks start paused, so they can be set up first; each has play/pause, restart (from its start) and remove, and *Play all*, *Pause all*, *Restart all* act on every track. The open track shows its controls; click another track's header to open it.
20+- **Orbit**: click the plot to place (or move) the open track's start, or drag its ring; click any start ring to open its track; shift-click (or *+ Add track*, then click) for a new track. The orbit's dots fill in (larger, brighter), and while it plays a playhead walks it one drive period per beat, with a fading trail of the continuous motion through each period and a ring at each pluck. Changing a parameter or preset restarts nothing: the tracks carry on from where they are under the new equation, their dots recomputed from there, and the old dots (and the old section behind them) fade out as the new ones fill in. Restart takes a track back to its start.
21+- **Track settings**: instrument, rhythm, scale, key, tempo multiple, sustain, volume and velocity. Each but the instrument has a link toggle: linked tracks share one value (change it on any of them and all follow), unlinked ones have their own. By default scale and key are linked.
22+- **Tempo multiple**: each track advances one drive period per tick, at a multiple of the global tempo: ×1 (the default: 2 drive periods a second at 120 bpm), ×2, ×3, ×4, ×6, ×8, ×12, ×16, ×1/2, ×1/3, ×1/4, ×1/6, ×1/8, or a custom number or fraction (1/16 to 32, such as 3/2). Ticks fall on a grid aligned to the beat, so ×2 and ×3 meet on every beat and ×1/2 ticks on every other beat (polyrhythms); a track that starts playing joins at its next tick. Changing the tempo carries the beat on from where it is.
23+- **Notes**: each pluck's pitch is set by x (left to right across the view: C3 to C6), on the track's scale (minor pentatonic by default; major pentatonic, major, minors, whole tone, chromatic, or continuous) in its key (A by default). The key keeps the register and changes which notes x snaps to, so switching key while playing shifts the harmony like a chord change. An island orbit plays a repeating pattern; a chaotic one wanders.
24+- **Custom notes** (the last choice in the Scale menu): pick the notes yourself on a small piano in the track's card, by clicking keys or by pressing them on a MIDI keyboard (Web MIDI: Chrome, Edge or Firefox; the browser asks for permission the first time). Choosing Custom notes starts listening to the keyboard. The keys you hold down together become the notes: press them at once, or one after another without letting go of them all (or with the sustain pedal down); once every key is up, the next press starts a new set. Clicking a key on the piano adds or removes just that note (and, with the sound on, plays it on the track's instrument; keys pressed on the MIDI keyboard aren't played). Keys go to the open track's notes; *Listening…* toggles this, and *Clear* empties them. With *Every octave* (on by default) their pitch classes make a scale across the usual C3 to C6; turn it off and the notes themselves are spread across the view from left to right, lowest to highest, so x picks among exactly those notes. A key change transposes them (the nearer way). The notes go with the scale setting, so linked tracks share them; unlink a track's scale to give it its own. Switching to another scale and back keeps them.
25+- **Rhythm**: *natural, upward* plucks wherever ẋ crosses 0 upward (the left turning point of each swing), at that x and at that moment in the slowed-down motion, so each orbit makes its own rhythm: lilting and nearly regular on an island, uneven in the sea. *Both ways* also plucks at the right turning point. *Steady* (the default) plucks once per drive period, at the section point.
26+- **Instruments**: harp, marimba, vibraphone, electric piano, music box, ocarina, pizzicato and kalimba (a new track takes the first one not in use). **Sustain** (0.1 to 4 s, default 2) sets how long the notes ring, the same for every voice and pitch, so the voices differ only in timbre and attack, and all start equally loud. **Volume** is the track's level.
27+- **SoundFonts** (optional): *Load .sf2…* (bottom of the tracks panel) loads one or more files; each one's presets join every track's instrument menu (a group per file), and the open track takes the first file's first preset. The list shows each file, its number of presets and the tracks using it; × removes one (its tracks go back to built-in instruments). Loading a file with the name of one already loaded replaces it, its tracks keeping their presets by name. Samples play as recorded, so Sustain doesn't apply to them; *Velocity* (1 to 127, with a little random jitter per note) picks their velocity layers. Each preset is matched in loudness to the built-in voices at velocity 100 near middle C. The files are remembered in the browser until × removes them.
28+- **MIDI knobs** (optional): the *Knobs* button by the Equation heading puts a small chip on each equation slider and on the coupling. Click a slider's **+** and turn a knob on your controller (any MIDI control change, such as the knobs of an Arturia MiniLab); from then on that knob moves the slider, smoothly like dragging it. Knobs come in two kinds, told apart as you assign one (a relative knob turned steadily repeats itself, which an absolute one never does): an absolute knob sends its position, 0 to 127, and sweeps the slider's whole range; a relative (endless) one, such as the MiniLab's clickable browse knobs, sends steps left or right (64 ± n, 16 ± n or two's complement), and nudges the slider from where it is, by a 256th of its range a step (at least the slider's own step), more when turned faster. A chip shows its knob (CC number, channel if not 1, ↻ if relative); click it to assign another knob, switch its kind, or unassign it. A knob is assigned to one slider at a time. The assignments are kept in this browser (they belong to the controller, not the session, so they aren't in the session file or undone by Start over), and they work whether the chips are shown or not.
29+- **Coupling** (optional, off by default; 1 to about 3000 s⁻¹ on a log scale): joins the playing tracks with the same tempo multiple into one system (one system per multiple), each pulled toward their mean by a spring and a damper on its difference (critically damped at rate r), leaving the mean motion as it was. Weakly coupled they nudge each other (and lose the energy of their mismatch, often settling into islands); strongly coupled they fall into step and play in unison, even in the chaotic sea. On the first preset, three sea orbits lock above about 900 s⁻¹. Whenever such a set of tracks changes (one played, paused, moved or removed, or its multiple changed) or the coupling changes, they carry on from where they are; only their dots are recomputed, coupled from there.
30+- **Recording** (*Record* in the header): records a video of the phase space alone (the dots, orbits, trails, plucks and start rings; no axes, labels or track numbers) with the sound as heard (after the master volume), for as long as you like; it turns the sound on. While recording, the header shows the time and size so far; *Stop* ends it, and *Download video* saves it: MP4 (H.264 and AAC) where the browser can record it, else WebM. The video is the plot's size on screen when the recording started (its longer side at most 1920 px; resizing the window meanwhile stretches it), 60 fps at about 8 Mbit/s (some 3.6 GB an hour). Everything you do while recording is in it, parameter changes included. Keep the tab in view: a hidden tab stops drawing frames. The page asks before closing with a recording not yet downloaded.
31+- **Session** (bottom of the equation panel): everything (the equation, coupling, tempo, master volume, and every track's settings, start, play state and where its playhead is) is saved in the browser as you go and restored on reload; the sound starts off. *Save to file* downloads it all as JSON, every loaded SoundFont included (their bytes in base64), and *Open file…* restores such a file, adding its SoundFonts (replacing loaded ones of the same name). Each track remembers its SoundFont by file name and its preset by number and name, so it finds them again even if the files are loaded in another order or a file changed. *Start over* goes back to the defaults (the SoundFonts stay).
2332 - **Parameters**: f₀ (negative: a double well), α, δ, F, Ω/2π, and the view's half-width in x. Presets: double well (islands in a sea; gentle drive with a thin chaotic layer; strong drive), pure cubic, hardening resonance island, and a damped strange attractor.
2433
2534 ## Physics and sound
2635
36+- `app/js/midi.js`: the MIDI keyboard and controller (Web MIDI note-ons, note-offs, the sustain pedal and control changes from every input, including ones plugged in later).
37+- `app/js/session.js`: the browser save (localStorage; the SoundFonts themselves in IndexedDB, one record per file, `app/js/soundfont.js`), and the file's base64 and download helpers. Restoring checks every value and falls back to the default for anything missing or out of range.
2738 - `app/js/duffing.js`: each drive period in N equal steps of a 4th-order Yoshida composition of a damping/kick/drift/kick/damping leapfrog (symplectic when undamped, so islands keep their shape over long runs), with the drive tabulated at the kick times. ω h ≤ 0.08 for the stiffest local frequency up to |x| = 1, past which an orbit has escaped.
2839 - Coupling (`stepMany` in `duffing.js`): each oscillator gets r² (x̄ − xₖ) + 2r (v̄ − vₖ), x̄ and v̄ the means of those not escaped. The damper part is solved exactly (the mean velocity is kept, differences decay by e^(−2rt)) in half steps around the kicks, the spring part joins the kicks. A damper alone would lock velocities but not positions (two orbits can glide along together in different wells), hence the spring.
29-- `app/js/voices.js`: notes rendered once per voice, pitch and sustain into AudioBuffers, each ringing for the sustain (the fundamental's 60 dB decay time) and matched in loudness by the K-weighted RMS (ITU-R BS.1770's filter: +4 dB above about 1.7 kHz, high-pass at 38 Hz) over its first 0.3 s. Strings (harp, pizzicato) are Karplus-Strong. The string starts in a rounded triangle (plucked at 0.15 of its length, so harmonics 2 to 4 sit about 8, 14 and 21 dB below the fundamental), loops through a [¼, ½, ¼] low-pass (highs die away first) with an all-pass for fractional-delay tuning, and gets a 4 ms soft attack. Bars, tines and the ocarina are a few decaying sinusoids at the instrument's partial ratios (marimba 1 : 3.93 : 9.2; vibraphone 1 : 4 : 10 with tremolo); the electric piano is two-operator FM with a fading index. Then a gentle 3.5 kHz low-pass, a dark synthetic reverb and a limiter. Notes are scheduled on the audio clock a little ahead of time, softer the more orbits play; each orbit keeps at most 64 notes sounding (the oldest fades out in 40 ms), so fast tempos with long sustains stay light.
40+- `app/js/voices.js`: notes rendered once per voice, pitch and sustain into AudioBuffers, each ringing for the sustain (the fundamental's 60 dB decay time) and matched in loudness by the K-weighted RMS (ITU-R BS.1770's filter: +4 dB above about 1.7 kHz, high-pass at 38 Hz) over its first 0.3 s. Strings (harp, pizzicato) are Karplus-Strong. The string starts in a rounded triangle (plucked at 0.15 of its length, so harmonics 2 to 4 sit about 8, 14 and 21 dB below the fundamental), loops through a [¼, ½, ¼] low-pass (highs die away first) with an all-pass for fractional-delay tuning, and gets a 4 ms soft attack. Bars, tines and the ocarina are a few decaying sinusoids at the instrument's partial ratios (marimba 1 : 3.93 : 9.2; vibraphone 1 : 4 : 10 with tremolo); the electric piano is two-operator FM with a fading index. SoundFonts (`app/js/soundfont.js`) are parsed into regions (key and velocity ranges, root key, tuning, attenuation, loop, attack and release), preset and instrument levels combined as in the SF2 spec; modulators, filters and LFOs are not modelled except the velocity-to-attenuation curve. Unlooped samples play to their end; looped ones loop for 1.5 s, then fade over their release. Then a gentle 3.5 kHz low-pass, a dark synthetic reverb and a limiter. Notes are scheduled on the audio clock a little ahead of time, softer the more tracks play, through each track's gain (its volume); each track keeps at most 64 notes sounding (the oldest fades out in 40 ms), so fast tempos with long sustains stay light.
app/index.htmlmodified+71−54View file
@@ -7,74 +7,91 @@
77 <link rel="stylesheet" href="style.css">
88 </head>
99 <body>
10- <header>
11- <h1>Islands in a sea of chaos</h1>
12- <p class="eq">
13- <i>ẍ</i> + <i>δ</i><i>ẋ</i> ± (2π<i>f</i><sub>0</sub>)<sup>2</sup><i>x</i> + <i>α</i><i>x</i><sup>3</sup> = <i>F</i> cos <i>Ωt</i>
14- </p>
10+ <header class="top">
11+ <div class="title">
12+ <h1>Islands in a sea of chaos</h1>
13+ <p class="eq">
14+ <i>ẍ</i> + <i>δ</i><i>ẋ</i> ± (2π<i>f</i><sub>0</sub>)<sup>2</sup><i>x</i> + <i>α</i><i>x</i><sup>3</sup> = <i>F</i> cos <i>Ωt</i>
15+ </p>
16+ </div>
17+ <div class="master">
18+ <label class="master-tempo" title="The global tempo: every track ticks at a multiple of it">
19+ <span>Tempo</span>
20+ <input id="tempo" type="range">
21+ <output></output>
22+ </label>
23+ <div class="rec">
24+ <button id="record" class="rec-btn" aria-pressed="false"><span class="rec-dot" aria-hidden="true"></span><span class="rec-label">Record</span></button>
25+ <span id="rec-status" class="rec-status" aria-live="polite" hidden></span>
26+ <button id="rec-download" class="small" hidden></button>
27+ <button id="rec-discard" class="quiet small" aria-label="Discard the recording" title="Discard the recording" hidden>×</button>
28+ </div>
29+ <button id="sound" class="sound-btn" aria-pressed="false"></button>
30+ <label class="master-vol" title="Master volume">
31+ <span class="sr">Master volume</span>
32+ <input id="volume" type="range" min="0" max="1" step="0.01" value="0.6">
33+ <output></output>
34+ </label>
35+ </div>
1536 </header>
1637
1738 <div class="layout">
18- <aside class="panel">
39+ <aside class="panel eqn-panel">
40+ <div class="eqn-head">
41+ <h2>Equation</h2>
42+ <button id="knobs" class="small quiet" aria-pressed="false" title="Control the sliders with the knobs of a MIDI controller">Knobs</button>
43+ </div>
44+ <p id="knob-msg" class="note knob-msg" hidden></p>
1945 <select id="preset" aria-label="Preset"></select>
20-
2146 <div id="sliders" class="sliders"></div>
22- <label class="row">
23- <span>Coupling</span>
24- <input id="coupling" type="range" min="0" max="70" step="1" value="0">
25- <output></output>
26- </label>
27-
28- <div class="sound">
29- <button id="sound" class="toggle" aria-pressed="false">♪ Sound off</button>
30- <label class="row">
31- <span>Rhythm</span>
32- <select id="rhythm">
33- <option value="both" selected>Natural: ẋ crosses 0 both ways</option>
34- <option value="natural">Natural: ẋ crosses 0 upward</option>
35- <option value="steady">Steady: each drive period</option>
36- </select>
37- </label>
38- <label class="row">
39- <span>Scale</span>
40- <select id="scale"></select>
41- </label>
42- <div class="row">
43- <span>Key</span>
44- <div id="keys" class="keys" role="group" aria-label="Key"></div>
45- </div>
46- <label class="row">
47- <span>Tempo</span>
48- <input id="tempo" type="range" min="1" max="40" step="1" value="16">
49- <output id="tempo-out"></output>
50- </label>
51- <label class="row">
52- <span>Sustain</span>
53- <input id="sustain" type="range">
54- <output></output>
55- </label>
47+ <div class="coupling">
5648 <label class="row">
57- <span>Volume</span>
58- <input id="volume" type="range" min="0" max="1" step="0.01" value="0.6">
49+ <span>Coupling</span>
50+ <input id="coupling" type="range" min="0" max="70" step="1" value="0">
5951 <output></output>
6052 </label>
53+ <p class="note">Joins the playing tracks with the same tempo multiple into one system.</p>
54+ </div>
55+ <div class="session">
56+ <h2>Session</h2>
57+ <p class="note">Saved in this browser as you go. A file keeps everything, SoundFonts included.</p>
58+ <div class="session-btns">
59+ <button id="export" class="small" title="Download the session (with its SoundFonts) as a file">Save to file</button>
60+ <button id="import" class="small" title="Open a session file">Open file…</button>
61+ <button id="start-over" class="small quiet" title="Back to the defaults">Start over</button>
62+ <input id="import-file" type="file" accept=".json,application/json" hidden>
63+ </div>
64+ <p id="session-msg" class="note" aria-live="polite"></p>
6165 </div>
62-
63- <label class="row click-mode">
64- <span>Clicks</span>
65- <select id="click-mode">
66- <option value="add" selected>Add an orbit</option>
67- <option value="replace">Replace the orbit</option>
68- </select>
69- </label>
70- <ul id="orbit-list" class="orbit-list"></ul>
71- <button id="clear" class="quiet">Clear orbits</button>
7266 </aside>
7367
7468 <div class="plot-wrap">
7569 <canvas id="plot"></canvas>
76- <p id="hint" class="hint">Click to add orbits · click a start ring to remove it</p>
70+ <p id="hint" class="hint"></p>
7771 </div>
72+
73+ <aside class="panel tracks-panel">
74+ <div class="tracks-head">
75+ <h2>Tracks</h2>
76+ <div class="transport">
77+ <button id="play-all" class="small" title="Play every track">Play all</button>
78+ <button id="pause-all" class="small" title="Pause every track">Pause all</button>
79+ <button id="restart-all" class="small" title="Restart every track from its start">Restart all</button>
80+ </div>
81+ </div>
82+ <ol id="track-list" class="track-list"></ol>
83+ <button id="add-track" class="add-track">+ Add track</button>
84+ <div class="sf-lib">
85+ <div class="sf-head">
86+ <span class="sf-label">SoundFonts</span>
87+ <button id="sf-load" class="small" title="Load one or more .sf2 files: their presets join every track's instrument menu">Load .sf2…</button>
88+ <input id="sf-file" type="file" accept=".sf2" multiple hidden>
89+ </div>
90+ <p id="sf-empty" class="note">None loaded: a .sf2 file's presets join the instruments.</p>
91+ <ul id="sf-list" class="sf-list"></ul>
92+ <p id="sf-msg" class="note" aria-live="polite"></p>
93+ </div>
94+ </aside>
7895 </div>
7996
8097 <script type="module" src="main.js"></script>
app/js/midi.jsadded+31−0View file
@@ -0,0 +1,31 @@
1+// A MIDI keyboard, through Web MIDI: note-ons and note-offs from every
2+// connected input (and ones plugged in later).
3+
4+export const midiSupported = () => typeof navigator !== 'undefined' && !!navigator.requestMIDIAccess;
5+
6+// Ask for MIDI access (the browser may ask the user), then call
7+// onNote(note, on) for each key pressed (on) or released,
8+// onPedal(down) when the sustain pedal goes down or up, onControl(channel,
9+// controller, value) for every control change (a knob turned: value 0 to
10+// 127), and onInputs(names) now and whenever a device is plugged in or out.
11+export async function openMidi({ onNote, onPedal, onControl, onInputs }) {
12+ const access = await navigator.requestMIDIAccess();
13+ const handle = (e) => {
14+ const [status, note, vel] = e.data;
15+ const type = status & 0xf0;
16+ if (type === 0x90 && vel > 0) onNote(note, true);
17+ else if (type === 0x80 || type === 0x90) onNote(note, false);
18+ else if (type === 0xb0) {
19+ if (note === 64) onPedal(vel >= 64);
20+ onControl(status & 0x0f, note, vel);
21+ }
22+ };
23+ const hook = () => {
24+ const inputs = [...access.inputs.values()].filter((i) => i.state !== 'disconnected');
25+ for (const input of inputs) input.onmidimessage = handle;
26+ onInputs(inputs.map((i) => i.name || 'MIDI input'));
27+ };
28+ access.onstatechange = hook;
29+ hook();
30+ return access;
31+}
app/js/session.jsadded+80−0View file
@@ -0,0 +1,80 @@
1+// Saving the page's state: in the browser (localStorage, as you go), and to
2+// a file to download and open again. The file is JSON: the state, plus any
3+// SoundFont, its bytes in base64, so a file brings its instruments with it.
4+
5+export const FORMAT = 'duffing-islands';
6+const STORAGE_KEY = 'duffing-islands:state';
7+
8+// the state saved in this browser, or null
9+export function loadLocal() {
10+ try {
11+ return JSON.parse(localStorage.getItem(STORAGE_KEY));
12+ } catch {
13+ return null;
14+ }
15+}
16+
17+let lastSaved = '';
18+// save the state in this browser (if it changed); false if storage failed
19+export function saveLocal(state) {
20+ try {
21+ const text = JSON.stringify(state);
22+ if (text !== lastSaved) {
23+ localStorage.setItem(STORAGE_KEY, text);
24+ lastSaved = text;
25+ }
26+ return true;
27+ } catch {
28+ return false;
29+ }
30+}
31+
32+// the MIDI knobs assigned to controls, kept in this browser (they belong to
33+// the controller, not the session): { [control id]: { ch, cc } }
34+const KNOBS_KEY = 'duffing-islands:knobs';
35+export function loadKnobs() {
36+ try {
37+ const o = JSON.parse(localStorage.getItem(KNOBS_KEY));
38+ return o && typeof o === 'object' ? o : {};
39+ } catch {
40+ return {};
41+ }
42+}
43+export function saveKnobs(knobs) {
44+ try { localStorage.setItem(KNOBS_KEY, JSON.stringify(knobs)); } catch { /* storage blocked */ }
45+}
46+
47+export function forgetLocal() {
48+ try { localStorage.removeItem(STORAGE_KEY); } catch { /* storage blocked */ }
49+ lastSaved = '';
50+}
51+
52+export function toBase64(buffer) {
53+ const bytes = new Uint8Array(buffer);
54+ let s = '';
55+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
56+ return btoa(s);
57+}
58+
59+export function fromBase64(text) {
60+ const s = atob(text);
61+ const bytes = new Uint8Array(s.length);
62+ for (let i = 0; i < s.length; i++) bytes[i] = s.charCodeAt(i);
63+ return bytes.buffer;
64+}
65+
66+// offer `text` as a file to save
67+export const download = (text, fileName) => downloadBlob(new Blob([text], { type: 'application/json' }), fileName);
68+
69+// offer a Blob as a file to save
70+export function downloadBlob(blob, fileName) {
71+ const url = URL.createObjectURL(blob);
72+ const a = document.createElement('a');
73+ a.href = url;
74+ a.download = fileName;
75+ document.body.append(a);
76+ a.click();
77+ a.remove();
78+ // (kept a while: a large file may take time to start saving)
79+ setTimeout(() => URL.revokeObjectURL(url), 60000);
80+}
app/js/soundfont.jsadded+302−0View file
@@ -0,0 +1,302 @@
1+// SoundFont 2 (.sf2) instruments, for an uploaded voice.
2+//
3+// parseSF2 reads the file into presets, each a flat list of regions (key and
4+// velocity range, sample, root key, tuning, attenuation, loop, envelope
5+// times), with the preset and instrument levels and their global zones
6+// combined as the SF2 spec says (ranges intersect, tunings, attenuation and
7+// envelope times add, the rest from the instrument). Modulators, filters and
8+// LFOs are not modelled, except the velocity-to-attenuation curve: the
9+// default (velocity squared, -96 dB at most) unless the file overrides it.
10+//
11+// Notes play the sample as recorded (Sustain doesn't apply): unlooped samples
12+// to their end; looped ones loop for HOLD s, then fade over their release.
13+
14+const HOLD = 1.5; // s, how long a looped sample is held before its release
15+
16+const GEN = {
17+ startAddrsOffset: 0, endAddrsOffset: 1, startloopAddrsOffset: 2, endloopAddrsOffset: 3,
18+ startAddrsCoarseOffset: 4, endAddrsCoarseOffset: 12, pan: 17, attackVolEnv: 34,
19+ releaseVolEnv: 38, instrument: 41, keyRange: 43, velRange: 44, startloopAddrsCoarseOffset: 45,
20+ initialAttenuation: 48, endloopAddrsCoarseOffset: 50, coarseTune: 51, fineTune: 52,
21+ sampleID: 53, sampleModes: 54, scaleTuning: 56, overridingRootKey: 58,
22+};
23+// summed over the preset and instrument levels (the rest come from the instrument)
24+const ADDITIVE = [GEN.pan, GEN.attackVolEnv, GEN.releaseVolEnv, GEN.initialAttenuation, GEN.coarseTune, GEN.fineTune];
25+const DEFAULTS = { [GEN.attackVolEnv]: -12000, [GEN.releaseVolEnv]: -12000, [GEN.scaleTuning]: 100 };
26+const VEL_MOD_SRC = 0x0502; // note-on velocity, unipolar, negative, concave
27+
28+function readChunks(dv, start, end) {
29+ const out = [];
30+ let o = start;
31+ while (o + 8 <= end) {
32+ const id = String.fromCharCode(dv.getUint8(o), dv.getUint8(o + 1), dv.getUint8(o + 2), dv.getUint8(o + 3));
33+ const size = dv.getUint32(o + 4, true);
34+ out.push({ id, start: o + 8, size, type: id === 'LIST' || id === 'RIFF' ? readStr(dv, o + 8, 4) : null });
35+ o += 8 + size + (size & 1);
36+ }
37+ return out;
38+}
39+
40+function readStr(dv, o, n) {
41+ let s = '';
42+ for (let i = 0; i < n; i++) {
43+ const c = dv.getUint8(o + i);
44+ if (!c) break;
45+ s += String.fromCharCode(c);
46+ }
47+ return s.trim();
48+}
49+
50+// Parse an .sf2 file (ArrayBuffer). Throws on files it can't read.
51+export function parseSF2(buffer) {
52+ const dv = new DataView(buffer);
53+ const [riff] = readChunks(dv, 0, 12 + 8);
54+ if (!riff || riff.id !== 'RIFF' || riff.type !== 'sfbk') throw new Error('not a SoundFont 2 file');
55+ const lists = {};
56+ for (const c of readChunks(dv, 12, Math.min(buffer.byteLength, 8 + riff.size))) {
57+ if (c.id !== 'LIST') continue;
58+ lists[c.type] = Object.fromEntries(readChunks(dv, c.start + 4, c.start + c.size).map((s) => [s.id, s]));
59+ }
60+ if (!lists.sdta?.smpl || !lists.pdta) throw new Error('missing sample or preset data');
61+ const name = lists.INFO?.INAM ? readStr(dv, lists.INFO.INAM.start, lists.INFO.INAM.size) : '';
62+ const smpl = lists.sdta.smpl;
63+ const data = new Int16Array(buffer.slice(smpl.start, smpl.start + (smpl.size & ~1)));
64+
65+ const pd = lists.pdta;
66+ const recs = (id, size, read) => {
67+ const c = pd[id];
68+ if (!c) throw new Error(`missing ${id}`);
69+ const out = [];
70+ for (let o = c.start; o + size <= c.start + c.size; o += size) out.push(read(o));
71+ return out;
72+ };
73+ const phdr = recs('phdr', 38, (o) => ({ name: readStr(dv, o, 20), program: dv.getUint16(o + 20, true), bank: dv.getUint16(o + 22, true), bag: dv.getUint16(o + 24, true) }));
74+ const bag = (o) => ({ gen: dv.getUint16(o, true), mod: dv.getUint16(o + 2, true) });
75+ const gen = (o) => ({ op: dv.getUint16(o, true), s: dv.getInt16(o + 2, true), lo: dv.getUint8(o + 2), hi: dv.getUint8(o + 3) });
76+ const mod = (o) => ({ src: dv.getUint16(o, true), dst: dv.getUint16(o + 2, true), amt: dv.getInt16(o + 4, true) });
77+ const pbag = recs('pbag', 4, bag), pgen = recs('pgen', 4, gen), pmod = recs('pmod', 10, mod);
78+ const inst = recs('inst', 22, (o) => ({ name: readStr(dv, o, 20), bag: dv.getUint16(o + 20, true) }));
79+ const ibag = recs('ibag', 4, bag), igen = recs('igen', 4, gen), imod = recs('imod', 10, mod);
80+ const shdr = recs('shdr', 46, (o) => ({
81+ name: readStr(dv, o, 20), start: dv.getUint32(o + 20, true), end: dv.getUint32(o + 24, true),
82+ loopStart: dv.getUint32(o + 28, true), loopEnd: dv.getUint32(o + 32, true), rate: dv.getUint32(o + 36, true),
83+ root: dv.getUint8(o + 40), correction: dv.getInt8(o + 41), type: dv.getUint16(o + 44, true),
84+ }));
85+
86+ // zones of a preset or instrument: { gens: Map(op -> gen), velAtten?: cB }
87+ const zonesOf = (bags, gens, mods, b0, b1) => {
88+ const zones = [];
89+ for (let b = b0; b < b1; b++) {
90+ const gs = new Map();
91+ for (let g = bags[b].gen; g < bags[b + 1].gen; g++) gs.set(gens[g].op, gens[g]);
92+ let velAtten;
93+ for (let m = bags[b].mod; m < bags[b + 1].mod; m++) {
94+ if (mods[m].src === VEL_MOD_SRC && mods[m].dst === GEN.initialAttenuation) velAtten = mods[m].amt;
95+ }
96+ zones.push({ gens: gs, velAtten });
97+ }
98+ return zones;
99+ };
100+ // the first zone is global if it lacks the terminal generator
101+ const split = (zones, terminal) => (zones.length && !zones[0].gens.has(terminal)
102+ ? { global: zones[0], zones: zones.slice(1) } : { global: { gens: new Map() }, zones });
103+
104+ const range = (z, g, op) => {
105+ const r = z.gens.get(op) ?? g.gens.get(op);
106+ return r ? [r.lo, r.hi] : [0, 127];
107+ };
108+ const val = (z, g, op, dflt = 0) => (z.gens.get(op) ?? g.gens.get(op))?.s ?? dflt;
109+
110+ const presets = [];
111+ for (let p = 0; p < phdr.length - 1; p++) {
112+ const pz = split(zonesOf(pbag, pgen, pmod, phdr[p].bag, phdr[p + 1].bag), GEN.instrument);
113+ const regions = [];
114+ for (const z of pz.zones) {
115+ const ii = z.gens.get(GEN.instrument)?.s;
116+ if (ii == null || ii >= inst.length - 1) continue;
117+ const iz = split(zonesOf(ibag, igen, imod, inst[ii].bag, inst[ii + 1].bag), GEN.sampleID);
118+ const [pk0, pk1] = range(z, pz.global, GEN.keyRange), [pv0, pv1] = range(z, pz.global, GEN.velRange);
119+ for (const q of iz.zones) {
120+ const si = q.gens.get(GEN.sampleID).s & 0xffff;
121+ const s = shdr[si];
122+ if (!s || si >= shdr.length - 1 || s.type & 0x8000) continue; // ROM samples: skip
123+ const [ik0, ik1] = range(q, iz.global, GEN.keyRange), [iv0, iv1] = range(q, iz.global, GEN.velRange);
124+ const keyLo = Math.max(pk0, ik0), keyHi = Math.min(pk1, ik1);
125+ const velLo = Math.max(pv0, iv0), velHi = Math.min(pv1, iv1);
126+ if (keyLo > keyHi || velLo > velHi) continue;
127+ const g = (op) => val(q, iz.global, op, DEFAULTS[op] ?? 0) + (ADDITIVE.includes(op) ? val(z, pz.global, op, 0) : 0);
128+ const off = (fine, coarse) => g(fine) + 32768 * g(coarse);
129+ const start = s.start + off(GEN.startAddrsOffset, GEN.startAddrsCoarseOffset);
130+ const end = s.end + off(GEN.endAddrsOffset, GEN.endAddrsCoarseOffset);
131+ const root = g(GEN.overridingRootKey) > 0 ? g(GEN.overridingRootKey) : s.root;
132+ regions.push({
133+ keyLo, keyHi, velLo, velHi, sample: si, start, end,
134+ loopStart: s.loopStart + off(GEN.startloopAddrsOffset, GEN.startloopAddrsCoarseOffset) - start,
135+ loopEnd: s.loopEnd + off(GEN.endloopAddrsOffset, GEN.endloopAddrsCoarseOffset) - start,
136+ loop: (g(GEN.sampleModes) & 1) === 1,
137+ rate: s.rate, root: root > 127 ? 60 : root,
138+ tune: 100 * g(GEN.coarseTune) + g(GEN.fineTune) + s.correction, // cents
139+ scaleTuning: g(GEN.scaleTuning),
140+ atten: Math.max(0, g(GEN.initialAttenuation)), // cB
141+ velAtten: q.velAtten ?? iz.global.velAtten ?? 960, // cB at velocity 0
142+ attack: 2 ** (g(GEN.attackVolEnv) / 1200), // s
143+ release: 2 ** (g(GEN.releaseVolEnv) / 1200), // s
144+ pan: Math.max(-1, Math.min(1, g(GEN.pan) / 500)),
145+ });
146+ }
147+ }
148+ if (regions.length) presets.push({ name: phdr[p].name, bank: phdr[p].bank, program: phdr[p].program, regions });
149+ }
150+ if (!presets.length) throw new Error('no playable presets');
151+ presets.sort((a, b) => a.bank - b.bank || a.program - b.program);
152+ return { name, data, presets };
153+}
154+
155+// The regions sounding for MIDI key (rounded) at velocity vel.
156+function regionsFor(preset, key, vel) {
157+ const k = Math.round(key);
158+ return preset.regions.filter((r) => r.keyLo <= k && k <= r.keyHi && r.velLo <= vel && vel <= r.velHi);
159+}
160+
161+const gainOf = (r, vel) => 10 ** (-r.atten / 200) * (vel / 127) ** (2 * r.velAtten / 960);
162+
163+// A playable instrument: one preset of a parsed SoundFont, its samples made
164+// into AudioBuffers (per audio context) when first played.
165+export function makeInstrument(sf, presetIndex) {
166+ const preset = sf.presets[presetIndex];
167+ const buffers = new Map();
168+ const bufferFor = (ctx, r) => {
169+ const k = `${r.start}:${r.end}`;
170+ let b = buffers.get(k);
171+ if (!b) {
172+ const n = Math.max(1, r.end - r.start);
173+ const f = new Float32Array(n);
174+ for (let i = 0; i < n; i++) f[i] = (sf.data[r.start + i] ?? 0) / 32768;
175+ b = ctx.createBuffer(1, n, Math.min(192000, Math.max(8000, r.rate)));
176+ b.copyToChannel(f, 0);
177+ buffers.set(k, b);
178+ }
179+ return b;
180+ };
181+ return {
182+ name: preset.name,
183+ // a reference onset (first `seconds` s, as recorded, with its gain) near
184+ // middle C at velocity vel, for matching loudness to the other voices
185+ reference(vel, seconds) {
186+ let key = 60;
187+ if (!regionsFor(preset, key, vel).length) {
188+ const ks = preset.regions.map((r) => (r.keyLo + r.keyHi) / 2);
189+ key = ks.reduce((a, b) => (Math.abs(b - 60) < Math.abs(a - 60) ? b : a), ks[0]);
190+ }
191+ const rs = regionsFor(preset, key, vel);
192+ const r = rs[0] ?? preset.regions[0];
193+ const n = Math.min(r.end - r.start, Math.floor(seconds * r.rate));
194+ const x = new Float32Array(Math.max(1, n));
195+ const g = rs.reduce((a, q) => a + gainOf(q, vel), 0) || gainOf(r, vel);
196+ for (let i = 0; i < n; i++) x[i] = (g * sf.data[r.start + i]) / 32768;
197+ return { x, rate: r.rate };
198+ },
199+ // start a note of MIDI key (may be fractional) at velocity vel, at time t,
200+ // into node `out`; returns { stop(t), end } for the voice's note limit
201+ play(ctx, key, vel, t, out) {
202+ const nodes = [];
203+ let end = t;
204+ for (const r of regionsFor(preset, key, vel)) {
205+ const buf = bufferFor(ctx, r);
206+ const src = ctx.createBufferSource();
207+ src.buffer = buf;
208+ src.playbackRate.value = 2 ** (((key - r.root) * r.scaleTuning + r.tune) / 1200);
209+ const env = ctx.createGain();
210+ const g = gainOf(r, vel);
211+ const att = Math.max(0.001, Math.min(r.attack, 2));
212+ env.gain.setValueAtTime(0, t);
213+ env.gain.linearRampToValueAtTime(g, t + att);
214+ let stopAt = t + buf.duration / src.playbackRate.value;
215+ if (r.loop && r.loopEnd > r.loopStart + 8) {
216+ src.loop = true;
217+ src.loopStart = r.loopStart / buf.sampleRate;
218+ src.loopEnd = r.loopEnd / buf.sampleRate;
219+ const rel = Math.min(3, Math.max(0.05, r.release));
220+ env.gain.setValueAtTime(g, t + HOLD);
221+ env.gain.setTargetAtTime(0, t + HOLD, rel / 5);
222+ stopAt = t + HOLD + rel;
223+ }
224+ let node = src.connect(env);
225+ if (r.pan) {
226+ const p = ctx.createStereoPanner();
227+ p.pan.value = r.pan;
228+ node = node.connect(p);
229+ }
230+ node.connect(out);
231+ src.start(t);
232+ src.stop(stopAt);
233+ nodes.push({ src, env });
234+ end = Math.max(end, stopAt);
235+ }
236+ return {
237+ end,
238+ stop(at) {
239+ for (const { src, env } of nodes) {
240+ env.gain.cancelScheduledValues(at);
241+ env.gain.setValueAtTime(env.gain.value, at);
242+ env.gain.linearRampToValueAtTime(0, at + 0.04);
243+ src.stop(at + 0.05);
244+ }
245+ },
246+ };
247+ },
248+ };
249+}
250+
251+// ---- remembering the uploaded files (IndexedDB) ----------------------------
252+// One record per file, { fileName, bytes, added }, under 'sf:<fileName>'.
253+// (Before several could be loaded, the one file was kept under 'current'.)
254+
255+const DB = 'duffing-islands', STORE = 'soundfont';
256+
257+function db() {
258+ return new Promise((resolve, reject) => {
259+ const req = indexedDB.open(DB, 1);
260+ req.onupgradeneeded = () => req.result.createObjectStore(STORE);
261+ req.onsuccess = () => resolve(req.result);
262+ req.onerror = () => reject(req.error);
263+ });
264+}
265+async function tx(mode, fn) {
266+ const d = await db();
267+ return new Promise((resolve, reject) => {
268+ const t = d.transaction(STORE, mode);
269+ const req = fn(t.objectStore(STORE));
270+ t.oncomplete = () => resolve(req?.result);
271+ t.onerror = () => reject(t.error);
272+ });
273+}
274+const keyOf = (fileName) => `sf:${fileName}`;
275+
276+export const saveSoundFont = ({ fileName, bytes }) =>
277+ tx('readwrite', (s) => s.put({ fileName, bytes, added: Date.now() }, keyOf(fileName))).catch(() => {});
278+export const forgetSoundFont = (fileName) => tx('readwrite', (s) => s.delete(keyOf(fileName))).catch(() => {});
279+
280+// the saved files, [{ fileName, bytes }], in the order they were added
281+export async function loadSaved() {
282+ try {
283+ const keys = await tx('readonly', (s) => s.getAllKeys());
284+ const recs = await tx('readonly', (s) => s.getAll());
285+ const out = [];
286+ for (const [i, key] of keys.entries()) {
287+ const rec = recs[i];
288+ if (!rec?.bytes || !rec.fileName) continue;
289+ if (key === 'current') {
290+ // the old single file: kept under its own key from now on
291+ await saveSoundFont(rec);
292+ await tx('readwrite', (s) => s.delete('current')).catch(() => {});
293+ if (keys.includes(keyOf(rec.fileName))) continue;
294+ rec.added = 0;
295+ }
296+ out.push(rec);
297+ }
298+ return out.sort((a, b) => (a.added ?? 0) - (b.added ?? 0));
299+ } catch {
300+ return [];
301+ }
302+}
app/js/voices.jsmodified+85−37View file
@@ -4,8 +4,8 @@
44 // Each note is rendered once into an AudioBuffer (cached per voice, pitch
55 // and sustain), given a soft attack and a short fade at the end, and matched
66 // in loudness to all the others. Every voice and pitch rings for the same
7-// time: the sustain, the time for the fundamental to fade by 60 dB (set by
8-// the page). So the voices differ in timbre and attack, not in how long
7+// time: the sustain, the time for the fundamental to fade by 60 dB (set per
8+// track). So the voices differ in timbre and attack, not in how long
99 // they ring, and loudness is matched by the RMS over each note's onset (its
1010 // first LOUD_WINDOW s) after the K-weighting filter of ITU-R BS.1770 (a high
1111 // shelf of +4 dB above about 1.7 kHz, where the ear is most sensitive, and a
@@ -21,6 +21,10 @@
2121 // - The electric piano is two-operator FM with a fading modulation index.
2222 // Everything goes through a soft low-pass, a dark synthetic reverb and a
2323 // limiter.
24+// Each track has its own gain (its volume) and sustain. The presets of an
25+// uploaded SoundFont (js/soundfont.js) are more voices: their samples play
26+// as recorded (sustain doesn't apply), at a MIDI velocity set per track,
27+// matched in loudness to the others at velocity 100 near middle C.
2428
2529 export const DEFAULT_SCALE = 'Minor pentatonic';
2630 export const KEYS = ['C', 'C♯', 'D', 'E♭', 'E', 'F', 'F♯', 'G', 'A♭', 'A', 'B♭', 'B'];
@@ -255,54 +259,98 @@ export function createSynth() {
255259 dry.connect(master);
256260 dry.connect(reverb).connect(wet).connect(master);
257261 master.connect(limiter).connect(ctx.destination);
262+ // rendered notes, per voice, sustain and pitch
258263 const cache = new Map();
259- // per channel (an orbit's voice), its notes still sounding, oldest first;
260- // past MAX_SOUNDING the oldest is faded out, so fast tempos with long
261- // sustains stay light (at 16 notes/s, 64 notes is 4 s)
264+ // per track: its gain (the track's volume) and its notes still sounding,
265+ // oldest first; past MAX_SOUNDING the oldest is faded out, so fast tempos
266+ // with long sustains stay light (at 16 notes/s, 64 notes is 4 s)
262267 const MAX_SOUNDING = 64;
263- const sounding = new Map();
264- let sustain = SUSTAIN.default;
268+ const tracks = new Map();
269+ const track = (id) => {
270+ let tr = tracks.get(id);
271+ if (!tr) {
272+ const gain = ctx.createGain();
273+ gain.connect(tone);
274+ tr = { gain, sounding: [] };
275+ tracks.set(id, tr);
276+ }
277+ return tr;
278+ };
279+ // per SoundFont instrument, its loudness match (at velocity 100 near middle C)
280+ const sfGains = new WeakMap();
281+ const sfGain = (inst) => {
282+ if (!sfGains.has(inst)) {
283+ const { x, rate } = inst.reference(100, LOUD_WINDOW);
284+ sfGains.set(inst, LOUDNESS / (loudness(x, rate) + 1e-12));
285+ }
286+ return sfGains.get(inst);
287+ };
265288
266289 return {
267290 ctx,
291+ // the master volume
268292 setVolume(v) { master.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
269- // the time (s) for each note to fade by 60 dB, for the notes from now on
270- setSustain(s) {
271- if (s === sustain) return;
272- sustain = s;
273- cache.clear();
274- },
275- // a note of VOICES[voice] at freq, at time `when` (the context's clock),
276- // panned by pan in [-1, 1], at level gain
277- play(voice, freq, when, pan = 0, gain = 1) {
278- const key = `${voice}:${Math.round(freq * 10)}`;
279- let buf = cache.get(key);
280- if (!buf) {
281- buf = renderNote(ctx, VOICES[voice], freq, sustain);
282- if (cache.size > 400) cache.clear();
283- cache.set(key, buf);
293+ // the output as heard (after the master volume and limiter), as a
294+ // MediaStream, for recording
295+ stream() {
296+ if (!this.tap) {
297+ this.tap = ctx.createMediaStreamDestination();
298+ limiter.connect(this.tap);
284299 }
285- const src = ctx.createBufferSource();
286- src.buffer = buf;
300+ return this.tap.stream;
301+ },
302+ // a track's volume (its notes, sounding and to come)
303+ setTrackVolume(id, v) { track(id).gain.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
304+ // a track removed: its notes fade out
305+ removeTrack(id) {
306+ const tr = tracks.get(id);
307+ if (!tr) return;
308+ tracks.delete(id);
309+ for (const n of tr.sounding) n.stop(ctx.currentTime);
310+ setTimeout(() => tr.gain.disconnect(), 200);
311+ },
312+ // a note on track `id` of `voice` (an index into VOICES, or a SoundFont
313+ // instrument from makeInstrument, played at MIDI velocity vel) at freq,
314+ // at time `when` (the context's clock), panned by pan in [-1, 1], at
315+ // level gain; the built-in voices ring for `sustain` s
316+ play(id, voice, freq, when, { pan = 0, gain = 1, sustain = SUSTAIN.default, vel = 100 } = {}) {
317+ const tr = track(id);
287318 const level = ctx.createGain();
288- level.gain.value = gain;
289319 const panner = ctx.createStereoPanner();
290320 panner.pan.value = pan;
291- src.connect(level).connect(panner).connect(tone);
321+ level.connect(panner).connect(tr.gain);
292322 const t = Math.max(when, ctx.currentTime);
293- src.start(t);
294- const list = sounding.get(voice) ?? [];
295- const end = t + buf.duration;
296- list.push({ src, level, end });
323+ let note;
324+ if (typeof voice !== 'number') {
325+ level.gain.value = gain * sfGain(voice);
326+ note = voice.play(ctx, 69 + 12 * Math.log2(freq / 440), vel, t, level);
327+ } else {
328+ const key = `${voice}:${sustain.toFixed(2)}:${Math.round(freq * 10)}`;
329+ let buf = cache.get(key);
330+ if (!buf) {
331+ buf = renderNote(ctx, VOICES[voice], freq, sustain);
332+ if (cache.size > 800) cache.clear();
333+ cache.set(key, buf);
334+ }
335+ const src = ctx.createBufferSource();
336+ src.buffer = buf;
337+ level.gain.value = gain;
338+ src.connect(level);
339+ src.start(t);
340+ note = {
341+ end: t + buf.duration,
342+ stop(at) {
343+ level.gain.setValueAtTime(level.gain.value, at);
344+ level.gain.linearRampToValueAtTime(0, at + 0.04);
345+ src.stop(at + 0.05);
346+ },
347+ };
348+ }
349+ const list = tr.sounding;
350+ list.push(note);
297351 // drop those that have finished by now, then fade the excess
298352 while (list.length && list[0].end < ctx.currentTime) list.shift();
299- while (list.length > MAX_SOUNDING) {
300- const old = list.shift();
301- old.level.gain.setValueAtTime(old.level.gain.value, t);
302- old.level.gain.linearRampToValueAtTime(0, t + 0.04);
303- old.src.stop(t + 0.05);
304- }
305- sounding.set(voice, list);
353+ while (list.length > MAX_SOUNDING) list.shift().stop(t);
306354 },
307355 };
308356 }
app/main.jsmodified+1707−287View file
This diff is 2,225 lines long and is not shown.
app/style.cssmodified+311−29View file
@@ -9,6 +9,7 @@
99 --line: #dde1ea;
1010 --panel: #f5f6f9;
1111 --accent: #f6862d;
12+ --rec: #d0453a;
1213 --dot-light: 46%;
1314 --font-head: "Tiempos Headline", "Source Serif 4", Georgia, serif;
1415 --font-body: "Founders Grotesk", "Hanken Grotesk", system-ui, sans-serif;
@@ -27,6 +28,8 @@
2728
2829 * { box-sizing: border-box; }
2930
31+[hidden] { display: none !important; }
32+
3033 html, body { height: 100%; }
3134
3235 body {
@@ -39,7 +42,13 @@ body {
3942 font-size: 15px;
4043 }
4144
42-header { padding: 14px 20px 6px; }
45+header.top {
46+ display: flex;
47+ align-items: center;
48+ justify-content: space-between;
49+ gap: 16px;
50+ padding: 12px 20px 6px;
51+}
4352
4453 h1 {
4554 margin: 0;
@@ -48,42 +57,102 @@ h1 {
4857 font-size: 26px;
4958 }
5059
60+h2 {
61+ margin: 0;
62+ font-family: var(--font-head);
63+ font-weight: 300;
64+ font-size: 19px;
65+}
66+
5167 .eq { margin: 4px 0 0; font-family: var(--font-head); font-size: 17px; }
5268 .eq i { font-family: var(--font-head); }
5369
70+.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
71+
72+/* ---- master: sound on/off and volume ---- */
73+
74+.master { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; justify-content: flex-end; }
75+
76+.sound-btn {
77+ display: inline-flex;
78+ align-items: center;
79+ gap: 8px;
80+ padding: 9px 18px 9px 14px;
81+ border: 1.5px solid var(--line);
82+ border-radius: 999px;
83+ font-weight: 600;
84+ font-size: 15px;
85+ min-width: 140px;
86+ justify-content: center;
87+}
88+.sound-btn svg { width: 20px; height: 20px; }
89+.sound-btn[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: #fff; }
90+.sound-btn.nudge { border-color: var(--accent); color: var(--accent); animation: nudge 1.1s ease-out 3; }
91+@keyframes nudge {
92+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 55%, transparent); }
93+ 100% { box-shadow: 0 0 0 12px transparent; }
94+}
95+
96+.master-tempo { display: flex; align-items: center; gap: 8px; width: 230px; font-size: 14px; }
97+.master-tempo > span { color: var(--muted); }
98+.master-tempo output { font-size: 13px; font-variant-numeric: tabular-nums; min-width: 58px; text-align: right; }
99+.rec { display: flex; align-items: center; gap: 6px; }
100+.rec-btn {
101+ display: inline-flex;
102+ align-items: center;
103+ gap: 7px;
104+ padding: 7px 14px 7px 11px;
105+ border-radius: 999px;
106+ font-weight: 600;
107+ font-size: 14px;
108+}
109+.rec-dot { width: 11px; height: 11px; border-radius: 50%; background: var(--rec); }
110+.rec-btn[aria-pressed="true"] { border-color: var(--rec); color: var(--rec); }
111+.rec-btn[aria-pressed="true"] .rec-dot { border-radius: 2px; animation: rec-blink 1.2s steps(2, jump-none) infinite; }
112+@keyframes rec-blink { 50% { opacity: 0.35; } }
113+.rec-status { font-size: 13px; color: var(--rec); font-variant-numeric: tabular-nums; white-space: nowrap; }
114+.master-vol { display: flex; align-items: center; gap: 8px; width: 150px; }
115+.master-vol output { font-size: 13px; color: var(--muted); font-variant-numeric: tabular-nums; min-width: 34px; text-align: right; }
116+
117+/* ---- layout ---- */
118+
54119 .layout {
55120 flex: 1;
56121 min-height: 0;
57- display: flex;
58- gap: 16px;
122+ display: grid;
123+ grid-template-columns: 260px minmax(0, 1fr) 350px;
124+ gap: 18px;
59125 padding: 8px 20px 20px;
60126 }
61127
62128 .panel {
63- flex: 0 0 290px;
129+ min-height: 0;
64130 display: flex;
65131 flex-direction: column;
66- gap: 14px;
132+ gap: 12px;
67133 overflow-y: auto;
68134 }
69135
70-.sliders, .sound { display: flex; flex-direction: column; gap: 8px; }
71-
72-.sound, .click-mode { padding-top: 14px; border-top: 1px solid var(--line); }
136+.sliders, .coupling { display: flex; flex-direction: column; gap: 8px; }
137+.coupling { padding-top: 12px; border-top: 1px solid var(--line); }
138+.note { margin: 0; font-size: 12px; color: var(--muted); }
139+.session { display: flex; flex-direction: column; gap: 8px; margin-top: auto; padding-top: 12px; border-top: 1px solid var(--line); }
140+.session-btns { display: flex; flex-wrap: wrap; gap: 6px; }
141+.session .note:empty { display: none; }
142+.note.error { color: #d0453a; }
73143
74144 .row {
75145 display: grid;
76- grid-template-columns: 74px 1fr 64px;
146+ grid-template-columns: 64px 1fr 64px;
77147 align-items: center;
78148 gap: 8px;
79149 }
80150
81151 .row > span { color: var(--muted); font-size: 14px; }
82-.row > select { grid-column: 2 / 4; }
83152 .row output { font-variant-numeric: tabular-nums; font-size: 13px; text-align: right; }
84153 .row sub, .row sup { font-size: 0.7em; }
85154
86-input[type="range"] { width: 100%; accent-color: var(--accent); }
155+input[type="range"] { width: 100%; margin: 0; accent-color: var(--accent); }
87156
88157 select, button {
89158 font: inherit;
@@ -95,31 +164,152 @@ select, button {
95164 }
96165
97166 button { cursor: pointer; }
167+button:disabled { cursor: default; opacity: 0.45; }
168+
169+.small { padding: 3px 9px; font-size: 13px; }
170+.quiet { background: none; color: var(--muted); border-color: transparent; }
171+.error { color: #d0453a; }
172+
173+/* ---- tracks ---- */
98174
99-.keys { grid-column: 2 / 4; display: grid; grid-template-columns: repeat(6, 1fr); gap: 4px; }
100-.keys button { padding: 3px 0; font-size: 13px; }
175+.tracks-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
176+.transport { display: flex; gap: 4px; }
101177
102-.toggle[aria-pressed="true"], .keys button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: #fff; }
178+.track-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
103179
104-.quiet { background: none; color: var(--muted); align-self: flex-start; }
180+.track {
181+ --c: hsl(var(--h) 85% var(--dot-light));
182+ border: 1px solid var(--line);
183+ border-radius: 10px;
184+ background: var(--bg);
185+}
186+.track.selected { border-color: var(--c); box-shadow: 0 0 0 1px var(--c); }
105187
106-.orbit-list { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; }
107-.orbit-list:empty { display: none; }
108-.orbit-list li {
188+.track-head {
109189 display: flex;
110190 align-items: center;
111191 gap: 6px;
112- padding: 2px 2px 2px 8px;
192+ padding: 7px 6px 7px 8px;
193+ cursor: pointer;
194+ border-radius: 9px;
195+}
196+.track-head:hover { background: var(--panel); }
197+.track.selected .track-head { background: color-mix(in srgb, var(--c) 12%, transparent); border-radius: 9px 9px 0 0; }
198+
199+.track-title { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
200+.track-name, .summary { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
201+.track-name { font-weight: 600; font-size: 14px; }
202+.track-name .num { color: var(--c); margin-right: 6px; }
203+.summary { font-size: 12px; color: var(--muted); }
204+
205+.icon-btn {
206+ flex: none;
207+ width: 30px;
208+ height: 30px;
209+ padding: 0;
210+ display: inline-grid;
211+ place-items: center;
212+ border: 1px solid transparent;
213+ border-radius: 8px;
214+ background: none;
215+ color: var(--muted);
216+}
217+.icon-btn svg { width: 15px; height: 15px; }
218+.icon-btn:not(:disabled):hover { color: var(--fg); background: var(--panel); border-color: var(--line); }
219+.play-btn { width: 34px; height: 34px; border-radius: 50%; border-color: var(--c); color: var(--c); background: var(--bg); }
220+.play-btn svg { width: 14px; height: 14px; }
221+.play-btn:not(:disabled):hover { color: var(--c); border-color: var(--c); }
222+.play-btn[aria-pressed="true"], .play-btn[aria-pressed="true"]:not(:disabled):hover { background: var(--c); color: #fff; }
223+
224+.track-body {
225+ display: flex;
226+ flex-direction: column;
227+ gap: 7px;
228+ padding: 10px 10px 10px 6px;
229+ border-top: 1px solid var(--line);
230+}
231+
232+.trow {
233+ display: grid;
234+ grid-template-columns: 22px 66px minmax(0, 1fr) 58px;
235+ align-items: center;
236+ gap: 6px;
237+}
238+.trow > select, .trow > .keys, .trow > .coords { grid-column: 3 / 5; }
239+.trow .lbl { color: var(--muted); font-size: 13px; }
240+.rate-row.custom > select { grid-column: 3; }
241+.rate-row input[type="text"] {
242+ min-width: 0;
243+ font: inherit;
244+ font-size: 13px;
245+ padding: 3px 6px;
246+ color: var(--fg);
247+ background: var(--bg);
113248 border: 1px solid var(--line);
114- border-radius: 999px;
249+ border-radius: 6px;
250+ text-align: right;
251+}
252+.rate-row input.invalid { border-color: #d0453a; color: #d0453a; }
253+.trow output { font-size: 12px; text-align: right; font-variant-numeric: tabular-nums; }
254+.trow select { padding: 4px 6px; font-size: 13px; min-width: 0; }
255+.trow input[type="range"] { accent-color: var(--c); }
256+.trow.na > :not(.link) { opacity: 0.4; }
257+.coords { font-size: 13px; font-variant-numeric: tabular-nums; }
258+.coords em { color: var(--muted); }
259+
260+.link {
261+ width: 22px;
262+ height: 22px;
263+ padding: 0;
264+ display: grid;
265+ place-items: center;
266+ border: none;
267+ background: none;
268+ color: var(--muted);
269+ opacity: 0.6;
270+}
271+.link svg { width: 15px; height: 15px; }
272+.link:hover { opacity: 1; }
273+.link[aria-pressed="true"] { color: var(--accent); opacity: 1; }
274+
275+.keys { display: grid; grid-template-columns: repeat(6, 1fr); gap: 3px; }
276+.keys button { padding: 2px 0; font-size: 12px; }
277+.keys button[aria-pressed="true"] { background: var(--c); border-color: var(--c); color: #fff; }
278+
279+.link-note { display: flex; align-items: center; gap: 5px; margin: 2px 0 0; font-size: 12px; color: var(--muted); }
280+.link-note svg { width: 13px; height: 13px; flex: none; color: var(--accent); }
281+
282+.add-track {
283+ border: 1.5px dashed var(--line);
284+ border-radius: 10px;
285+ background: none;
286+ color: var(--muted);
287+ padding: 9px;
288+}
289+.add-track:not(:disabled):hover { border-color: var(--accent); color: var(--accent); }
290+
291+.sf-lib {
292+ display: flex;
293+ flex-direction: column;
294+ gap: 6px;
295+ margin-top: auto;
296+ padding-top: 12px;
297+ border-top: 1px solid var(--line);
115298 font-size: 13px;
116299 }
117-.orbit-list .swatch { width: 10px; height: 10px; border-radius: 50%; }
118-.orbit-list button { border: none; background: none; padding: 0 6px; color: var(--muted); line-height: 1; }
300+.sf-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
301+.sf-label { color: var(--muted); }
302+.sf-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
303+.sf-list:empty, .sf-lib .note:empty { display: none; }
304+.sf-list li { display: flex; align-items: center; gap: 8px; min-width: 0; padding: 2px 0 2px 2px; }
305+.sf-name { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
306+.sf-info { flex: 1 0 auto; color: var(--muted); font-size: 12px; white-space: nowrap; }
307+.sf-list .quiet { padding: 0 6px; }
308+
309+/* ---- plot ---- */
119310
120311 .plot-wrap {
121312 position: relative;
122- flex: 1;
123313 min-width: 0;
124314 min-height: 0;
125315 }
@@ -130,13 +320,15 @@ button { cursor: pointer; }
130320 width: 100%;
131321 height: 100%;
132322 cursor: crosshair;
133- touch-action: manipulation;
323+ touch-action: none;
134324 }
135325
136326 .hint {
137327 position: absolute;
138328 top: 8px;
139329 left: 60px;
330+ right: 16px;
331+ width: fit-content;
140332 margin: 0;
141333 padding: 4px 10px;
142334 border-radius: 6px;
@@ -146,11 +338,101 @@ button { cursor: pointer; }
146338 pointer-events: none;
147339 }
148340
341+@media (max-width: 1180px) {
342+ html, body { height: auto; }
343+ .layout { grid-template-columns: minmax(0, 1fr) minmax(0, 1.25fr); }
344+ .plot-wrap { grid-column: 1 / -1; order: -1; height: min(72vh, 680px); }
345+ .panel { overflow: visible; }
346+}
347+
149348 @media (max-width: 760px) {
150- header { padding: 12px 16px 4px; }
349+ header.top { flex-wrap: wrap; padding: 12px 16px 4px; }
151350 h1 { font-size: 22px; }
152- .layout { flex-direction: column; padding: 8px 16px 16px; }
153- .panel { flex: none; overflow: visible; }
154- .plot-wrap { flex: none; height: min(90vw, 70vh); order: -1; }
155- body { height: auto; }
351+ .layout { grid-template-columns: minmax(0, 1fr); padding: 8px 16px 16px; }
352+ .plot-wrap { height: min(90vw, 70vh); }
353+ .tracks-panel { order: -1; }
354+ .plot-wrap { order: -2; }
355+}
356+
357+/* ---- custom notes ---- */
358+
359+.notes-editor { display: flex; flex-direction: column; gap: 6px; padding-left: 28px; }
360+.piano {
361+ position: relative;
362+ height: 46px;
363+ border: 1px solid var(--line);
364+ border-radius: 4px;
365+ overflow: hidden;
366+ background: var(--bg);
367+}
368+.piano button {
369+ position: absolute;
370+ top: 0;
371+ padding: 0;
372+ border-radius: 0 0 3px 3px;
373+ cursor: pointer;
374+}
375+.piano .wk {
376+ width: calc(100% / var(--w));
377+ height: 100%;
378+ background: #fff;
379+ border: none;
380+ border-right: 1px solid #c9ced9;
381+ display: flex;
382+ align-items: flex-end;
383+ justify-content: center;
384+}
385+.piano .wk span { font-size: 8px; color: #8a90a2; padding-bottom: 2px; pointer-events: none; }
386+.piano .bk {
387+ z-index: 1;
388+ width: calc(100% / var(--w) * 0.62);
389+ height: 60%;
390+ transform: translateX(-50%);
391+ background: #2b2f38;
392+ border: 1px solid #1a1d23;
393+}
394+.piano .wk:hover { background: color-mix(in srgb, var(--c) 18%, #fff); }
395+.piano .bk:hover { background: color-mix(in srgb, var(--c) 35%, #2b2f38); }
396+.piano .echo.wk { background: color-mix(in srgb, var(--c) 30%, #fff); }
397+.piano .echo.bk { background: color-mix(in srgb, var(--c) 45%, #2b2f38); }
398+.piano .on { background: var(--c) !important; }
399+.piano .on span { color: #fff; }
400+.piano .down { box-shadow: inset 0 -5px 0 rgb(0 0 0 / 0.35); }
401+
402+.notes-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
403+.notes-bar button { padding: 3px 8px; font-size: 12px; }
404+.midi-btn { display: inline-flex; align-items: center; gap: 5px; }
405+.midi-btn svg { width: 15px; height: 15px; }
406+.midi-btn[aria-pressed="true"] { background: var(--c); border-color: var(--c); color: #fff; }
407+.notes-bar .check { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; color: var(--muted); cursor: pointer; }
408+.notes-bar .check input { accent-color: var(--c); margin: 0; }
409+.notes-bar .quiet { margin-left: auto; }
410+.notes-msg { margin: 0; font-size: 12px; color: var(--muted); line-height: 1.45; }
411+.notes-msg .note-names { color: var(--fg); font-variant-numeric: tabular-nums; }
412+.piano .wk.on { border-right-color: rgb(0 0 0 / 0.3); }
413+
414+/* ---- MIDI knobs ---- */
415+
416+.eqn-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
417+#knobs[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: #fff; }
418+.knob-msg { line-height: 1.45; }
419+.link-btn { padding: 0; border: none; background: none; color: var(--accent); font-size: inherit; text-decoration: underline; cursor: pointer; }
420+.knob { display: none; }
421+.knobs-on .row { grid-template-columns: 56px minmax(0, 1fr) 56px 44px; }
422+.knobs-on .knob {
423+ display: block;
424+ padding: 2px 0;
425+ font-size: 11px;
426+ font-variant-numeric: tabular-nums;
427+ color: var(--muted);
428+ border: 1px dashed var(--line);
429+ border-radius: 6px;
430+ background: none;
431+ white-space: nowrap;
156432 }
433+.knobs-on .knob:hover { color: var(--accent); border-color: var(--accent); }
434+.knobs-on .knob.set { color: var(--fg); border-style: solid; background: var(--panel); }
435+.knobs-on .knob.learning { color: #fff; background: var(--accent); border: 1px solid var(--accent); animation: knob-pulse 1s ease-in-out infinite; }
436+@keyframes knob-pulse { 50% { opacity: 0.55; } }
437+.row.turned input[type="range"] { filter: brightness(1.25) saturate(1.3); }
438+.row.turned .knob.set { border-color: var(--accent); color: var(--accent); }
package.jsonmodified+1−1View file
@@ -3,7 +3,7 @@
33 "private": true,
44 "type": "module",
55 "scripts": {
6- "dev": "python3 -m http.server 8002 --bind 127.0.0.1 --directory app",
6+ "dev": "python3 scripts/serve.py",
77 "check": "for f in app/*.js app/js/*.js scripts/*.mjs; do node --check \"$f\" || exit 1; done"
88 }
99 }
scripts/serve.pyadded+22−0View file
@@ -0,0 +1,22 @@
1+# The dev server: app/ at http://127.0.0.1:8002, with caching off, so a
2+# reload always gets the current modules (a browser mixing cached old ones
3+# with new ones breaks the page).
4+import functools
5+import http.server
6+import os
7+
8+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'app')
9+
10+
11+class NoCache(http.server.SimpleHTTPRequestHandler):
12+ def end_headers(self):
13+ self.send_header('Cache-Control', 'no-store')
14+ super().end_headers()
15+
16+
17+if __name__ == '__main__':
18+ handler = functools.partial(NoCache, directory=ROOT)
19+ port = int(os.environ.get('PORT', 8002))
20+ with http.server.ThreadingHTTPServer(('127.0.0.1', port), handler) as server:
21+ print(f'Serving app/ at http://127.0.0.1:{port} (no caching)')
22+ server.serve_forever()
↑↓ move↵openescclose