a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 1// Islands in a sea of chaos: the Poincaré section of the driven Duffing
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2// oscillator (js/duffing.js), filled in live, with tracks that sonify orbits
3// (js/voices.js).
5// - Seed orbits, started on the axes of the view at drive phase 0, fill the
6// section in the background, a few thousand points per frame.
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 7// - A track is an orbit (a start (x, x') picked on the plot, at drive phase
8// 0) and how it plays: rhythm, scale, key, tempo multiple, sustain,
9// volume, instrument and velocity. Its dots fill in fast and larger; while
10// it plays, a playhead walks it one drive period per tick, with a
11// live trail of the motion through the period, plucking notes whose pitch
12// is set by x (left to right over three octaves of its scale and key).
13// Tracks start paused; each can be played, paused and restarted from its
14// start.
15// - One global tempo (bpm) sets the beat; each track ticks at a multiple of
16// it (x1, x2, x3, ..., x1/2, x1/3, ..., or any value), on a grid aligned to
17// the beat, so x2 and x3 meet on every beat and x1/2 ticks on every other.
18// - Each setting but the instrument can be linked: the linked tracks share
19// one value (by default scale and key).
20// - Rhythm 'steady' plucks at the section point, once per beat; 'natural'
21// plays the motion in slowed time and plucks wherever x' crosses 0 upward
22// (the left turning point of each swing), at that x; 'both' at either
23// turning point.
24// - Changing a parameter or preset doesn't restart anything: the tracks
25// carry on from where they are under the new equation, their dots now
26// computed from there, and the old dots fade out as the new ones fill in.
27// Restart takes a track back to its start.
28// - Coupling (optional; off by default) joins the playing tracks with the
29// same tempo multiple into one system (one per multiple): a spring and
30// damper on each one's difference from their mean (duffing.js, stepMany),
31// so they pull together and, strong enough, fall into step. When such a
32// set of tracks or the coupling changes, they carry on from where they are
33// (their dots are recomputed from there, coupled as the playheads will
34// move).
36import { createStepper, physicsOf, X_MAX } from './js/duffing.js';
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 37import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, OCTAVES, pitchOf, SCALES, SUSTAIN, VOICES } from './js/voices.js';
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 38import { midiSupported, openMidi } from './js/midi.js';
39import { forgetSoundFont, loadSaved, makeInstrument, parseSF2, saveSoundFont } from './js/soundfont.js';
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 40import { PRESETS } from './js/presets.js';
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 41import { download, downloadBlob, FORMAT, forgetLocal, fromBase64, loadKnobs, loadLocal, saveKnobs, saveLocal, toBase64 } from './js/session.js';
43const SEEDS_X = 24; // seed orbits along x' = 0
44const SEEDS_V = 8; // and along x = 0
45const SEED_POINTS = 1500;
47const TRACK_PER_FRAME = 40; // so a track's orbit visibly grows
48const MAX_TRACKS = 8;
49const HIT_RADIUS = 9; // px: a press this close to a start ring picks its track
50const DRAG_START = 4; // px a press on a start ring moves before it drags
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 51const FRAME_BUDGET = 7; // ms of integration per frame
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 52const TAIL = 2; // trail length, in beats
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 53const LOOKAHEAD = 0.12; // s of notes scheduled ahead
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 54const FADE = 0.7; // s for replaced dots to fade out
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 55const RING = 0.35; // s a pluck's ring takes to fade (at most 3 beats)
56const MARGIN = { left: 56, right: 12, top: 12, bottom: 34 };
58const SLIDERS = [
59 { name: 'freq', label: 'f<sub>0</sub>', unit: 'Hz', min: -1000, max: 1000, step: 5, fmt: (v) => `${v < 0 ? '−' : ''}${Math.abs(v)} Hz` },
60 { name: 'alpha', label: 'α', min: -5, max: 10, step: 0.1, scale: 1e7, fmt: (v) => `${v.toFixed(1)}·10⁷` },
61 { name: 'delta', label: 'δ', min: 0, max: 50, step: 0.5, fmt: (v) => `${v.toFixed(1)} s⁻¹` },
62 { name: 'F', label: 'F', min: 0, max: 30, step: 0.1, scale: 1e4, fmt: (v) => `${v.toFixed(1)}·10⁴` },
63 { name: 'drive', label: 'Ω / 2π', min: 20, max: 2000, step: 5, fmt: (v) => `${v} Hz` },
64 { name: 'view', label: 'View ±x', min: 0.1, max: X_MAX, step: 0.05, fmt: (v) => v.toFixed(2) },
65];
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 67// ---- track settings ------------------------------------------------------------
69const RHYTHMS = [
70 { value: 'steady', name: 'Steady: each drive period', short: 'steady' },
71 { value: 'both', name: 'Natural: ẋ = 0 both ways', short: 'both ways' },
72 { value: 'natural', name: 'Natural: ẋ = 0 upward', short: 'upward' },
73];
74const SCALE_SHORT = {
75 'Major pentatonic': 'maj. pent.', 'Minor pentatonic': 'min. pent.', Major: 'major',
76 'Natural minor': 'minor', 'Harmonic minor': 'harm. minor', 'Whole tone': 'whole tone',
77 Chromatic: 'chromatic', Continuous: 'continuous',
78};
79// the settings that can be linked (shared by the linked tracks), and their defaults
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 80const SETTINGS = ['rhythm', 'scale', 'key', 'octave', 'rate', 'sustain', 'mono', 'volume', 'velocity'];
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 82 rhythm: 'steady', scale: SCALES.findIndex((s) => s.name === DEFAULT_SCALE), key: DEFAULT_KEY, octave: 0,
83 rate: '1', sustain: SUSTAIN.default, mono: false, volume: 1, velocity: 100,
85const LINKED_BY_DEFAULT = ['scale', 'key'];
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 86// a track's range: its octave, the shift (octaves) of everything it plays
87// (so the view's left edge is C3 shifted), and 'span', the number of octaves
88// across the view, linked along with the octave
89const OCTAVE_SHIFTS = [-3, -2, -1, 0, 1, 2, 3];
90const SPANS = [1, 2, 3, 4, 5, 6];
91DEFAULTS.span = OCTAVES;
92const octaveLabel = (o) => (o > 0 ? `+${o}` : o < 0 ? `−${-o}` : '0');
93const cName = (o) => `C${3 + o}`; // the note at the left edge, octave o
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 94// The 'Custom notes' scale (the scale setting's value CUSTOM): its notes are
95// in the setting 'notes', which is linked along with the scale: MIDI note
96// numbers (sorted), as entered in key `ref`, so a change of key transposes
97// them (the nearer way); every: their pitch classes in every octave (a scale
98// across the usual three octaves), rather than just those notes.
99const CUSTOM = 'custom';
100DEFAULTS.notes = { notes: [], ref: DEFAULT_KEY, every: true };
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 101const VALUES = [...SETTINGS, 'notes', 'span']; // a track's values (the settings, the custom notes, and the span)
102const COMPANIONS = { notes: 'scale', span: 'octave' };
103const linkOf = (p) => COMPANIONS[p] ?? p;
105const TEMPO = { min: 40, max: 240, default: 120 };
106// a track's tempo multiple: ticks (drive periods) per beat, as text ('3',
107// '1/2', '1.5'); the menu's choices, and the range of custom ones
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 108const RATES = ['64', '48', '32', '24', '16', '12', '8', '6', '4', '3', '2', '1', '1/2', '1/3', '1/4', '1/6', '1/8'];
109const RATE_RANGE = { min: 1 / 16, max: 128 };
111 sustain: { label: 'Sustain', min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, fmt: (v) => `${v.toFixed(1)} s`, title: 'How long each note rings (built-in instruments)' },
112 volume: { label: 'Volume', min: 0, max: 1, step: 0.01, fmt: (v) => `${Math.round(100 * v)}%` },
113 velocity: { label: 'Velocity', min: 1, max: 127, step: 1, fmt: (v) => `${v}`, title: 'MIDI velocity (SoundFont instruments)' },
114};
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 116const $ = (id) => document.getElementById(id);
117const canvas = $('plot');
118const ctx = canvas.getContext('2d');
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 119// the section points, accumulated: seed orbits, and the tracks' on top
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 120const dots = document.createElement('canvas');
121const top = document.createElement('canvas');
122const layers = [dots, top];
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 123// replaced dots, fading out (and a spare canvas to composite into)
124let ghost = document.createElement('canvas');
125let spare = document.createElement('canvas');
126let ghostStart = -Infinity;
128let params = { ...PRESETS[0].params };
129let stepper;
130let view; // { xr, vr }: half-ranges of x and x'
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 131let seeds = []; // the seed orbits
132let tracks = []; // see newTrack
133let selected = null; // the track whose controls are open, and whose start a click moves
134let shared = { ...DEFAULTS }; // the linked tracks' settings
135let tempo = TEMPO.default; // bpm
136let anchor = { time: 0, beat: 0 }; // the beat at a clock time (moved when the tempo changes)
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 137let synth = null;
138let soundOn = false;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 140let hueCounter = 0;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 141let coupling = 0; // r (s^-1) of the coupling; 0: off
142let groups = []; // the sets of coupled tracks, as last restarted
143let groupKey = '';
144let dirty = false; // the equation changed: reset at the next frame
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 146let soundfonts = []; // the loaded .sf2 files: { id, fileName, bytes, sf (parsed), insts: Map(preset -> instrument) }
147let nextFontId = 1;
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 148let recording = null; // while recording: { kind: 'video', recorder, chunks, mime, started } or { kind: 'audio', stop, chunks, frames, rate, started }
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 149let recorded = null; // { blob, mime, seconds, saved } once stopped
150let restored = false; // the saved state has been restored (until then, nothing is saved)
152// ---- tracks --------------------------------------------------------------------
154// a track's setting: its own, or the shared one if linked
155const val = (t, p) => (t.linked[linkOf(p)] ? shared : t.own)[p];
156// a tempo multiple's value from its text ('3', '1/2', '1.5'), or NaN
157function parseRate(text) {
158 const m = String(text).trim().match(/^(\d*\.?\d+)\s*(?:\/\s*(\d*\.?\d+))?$/);
159 const v = m ? Number(m[1]) / (m[2] ? Number(m[2]) : 1) : NaN;
160 return v >= RATE_RANGE.min && v <= RATE_RANGE.max ? v : NaN;
161}
162const rateOf = (t) => parseRate(val(t, 'rate')) || 1;
163const rateLabel = (t) => `×${val(t, 'rate')}`;
164// a track's tick: its length in beats, and in seconds (one drive period)
165const tickBeats = (t) => 1 / rateOf(t);
166const tickDt = (t) => 60 / (tempo * rateOf(t));
167// the beat at clock time `time`, and the clock time of beat b
168const beatAt = (time) => anchor.beat + ((time - anchor.time) * tempo) / 60;
169const timeAt = (b) => anchor.time + ((b - anchor.beat) * 60) / tempo;
170// the coupled set a track is in, if any
171const groupOf = (t) => groups.find((g) => g.includes(t));
173// a new track, paused, with the settings of `like` (a track) or the defaults
174function newTrack(like) {
175 const own = like ? Object.fromEntries(VALUES.map((p) => [p, val(like, p)])) : { ...DEFAULTS };
176 return {
177 id: nextId++,
178 hue: (0.08 + hueCounter++ * 0.382) % 1,
179 instrument: freeInstrument(),
180 start: null, // { x, v }
181 orbit: null, // its dots
182 ph: null, // its playhead
183 playing: false,
184 tick: null, // its next tick, as a number of ticks from beat 0 (null: from the next one due)
185 own,
186 linked: Object.fromEntries(SETTINGS.map((p) => [p, LINKED_BY_DEFAULT.includes(p)])),
187 escaped: false,
188 };
189}
191function addTrack() {
192 if (tracks.length >= MAX_TRACKS) return null;
193 const t = newTrack(selected);
194 tracks.push(t);
195 selected = t;
196 applyVolumes();
197 renderTracks();
198 return t;
199}
201function removeTrack(t) {
202 tracks = tracks.filter((q) => q !== t);
203 if (selected === t) selected = tracks[tracks.length - 1] ?? null;
204 synth?.removeTrack(t.id);
205 redrawTop();
206 renderTracks();
207}
209function setValue(t, p, v) {
210 (t.linked[linkOf(p)] ? shared : t.own)[p] = v;
211 if (p === 'volume') applyVolumes();
212 if (p === 'rate') for (const q of tracks) q.tick = null; // onto the new grid
213}
215// link or unlink a track's setting: linking adopts the shared value (or, if
216// no other track is linked, shares the track's own); unlinking keeps it
217function setLinked(t, p, on) {
218 if (on === t.linked[p]) return;
219 const ps = VALUES.filter((q) => linkOf(q) === p);
220 if (on) {
221 if (!tracks.some((q) => q !== t && q.linked[p])) for (const q of ps) shared[q] = t.own[q];
222 } else {
223 for (const q of ps) t.own[q] = shared[q];
224 }
225 t.linked[p] = on;
226 if (p === 'volume') applyVolumes();
227 if (p === 'rate') t.tick = null;
228}
230const applyVolumes = () => { for (const t of tracks) synth?.setTrackVolume(t.id, val(t, 'volume')); };
232const trackName = (t) => `${tracks.indexOf(t) + 1}`;
234// the sets of coupled tracks: the playing ones with the same tempo multiple,
235// two or more to a set
236function coupledGroups() {
237 if (!coupling) return [];
238 const by = new Map();
239 for (const t of tracks) {
240 if (!t.start || !t.playing) continue;
241 const k = rateOf(t).toPrecision(9);
242 if (!by.has(k)) by.set(k, []);
243 by.get(k).push(t);
244 }
245 return [...by.values()].filter((g) => g.length > 1);
246}
248// ---- physics ---------------------------------------------------------------
250// x' half-range: the speed at the bottom of the well of a free orbit that
251// just reaches x = +/-xr, so the view frames the motions of that size
252function speedRange(p, xr) {
253 const V = (x) => 0.5 * p.omega2 * x * x + 0.25 * p.alpha * x ** 4;
254 const vMin = p.omega2 < 0 && p.alpha > 0 ? -(p.omega2 ** 2) / (4 * p.alpha) : 0;
255 const v = Math.sqrt(Math.max(0, 2 * (V(xr) - vMin)));
256 return Math.max(v, 0.3 * xr * p.Omega, 1);
257}
259// skip: drive periods to run before recording (a seed's transient)
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 260function newOrbit(x, v, cap, hue, isTrack, skip = 0) {
261 return { x0: x, v0: v, s: { x, v, escaped: false }, pts: new Float32Array(2 * cap), n: 0, cap, hue, isTrack, skip };
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 264// a playhead: the orbit's state; its scheduled beats ({ time, dt, path,
265// last, notes }) still needed for the trail, notes: [{ t, x, v }]; and the
266// time its last scheduled beat ends
267const newPlayhead = (x, v) => ({ s: { x, v, escaped: false }, queue: [], until: 0 });
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 269function reset() {
270 const p = physicsOf(params);
271 stepper = createStepper(p);
272 view = { xr: params.view, vr: speedRange(p, params.view) };
273 // damped: the seeds settle onto the attractors before they are drawn,
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 274 // for about 5 / delta (the tracks show the way in)
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 275 const skip = p.delta > 0 ? Math.min(5000, Math.ceil((5 / p.delta) / stepper.T)) : 0;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 277 for (let i = 0; i < SEEDS_X; i++) {
278 const x = view.xr * (-1 + (2 * (i + 0.5)) / SEEDS_X);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 279 seeds.push(newOrbit(x, 0, SEED_POINTS, (i * 0.618) % 1, false, skip));
281 for (let i = 0; i < SEEDS_V; i++) {
282 const v = 0.9 * view.vr * (-1 + (2 * (i + 0.5)) / SEEDS_V);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 283 seeds.push(newOrbit(0, v, SEED_POINTS, ((i + SEEDS_X) * 0.618) % 1, false, skip));
286 clearDots([dots]);
287 reseed(tracks, false);
288}
290// recompute tracks' dots from where their playheads are (coupled as they
291// will move), the old ones fading out
292function reseed(ts, fade = true) {
293 if (fade) fadeOut([top]);
294 for (const t of ts) {
295 if (!t.ph) continue;
296 const { x, v, escaped } = t.ph.s;
297 t.orbit = newOrbit(x, v, TRACK_POINTS, t.hue, true);
298 t.orbit.s.escaped = escaped;
301}
303// restart tracks' playheads from their starts, and their dots too if they
304// weren't computed from there
305function restart(ts) {
306 let changed = false;
307 for (const t of ts) {
308 if (!t.start) continue;
309 t.ph = newPlayhead(t.start.x, t.start.v);
310 t.tick = null;
311 if (!t.orbit || t.orbit.x0 !== t.start.x || t.orbit.v0 !== t.start.v) {
312 t.orbit = newOrbit(t.start.x, t.start.v, TRACK_POINTS, t.hue, true);
313 changed = true;
314 }
315 }
316 if (changed) redrawTop();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 319// restart a track; if it is coupled, the others carry on, with it
320function restartTrack(t) {
321 restart([t]);
322 const g = groupOf(t);
323 if (g) reseed(g);
324}
e607771Optional coupling of the clicked orbitsJeremy Magland 325
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 326// When the coupled sets change (a track played, paused, added or removed,
327// its tempo multiple changed, or the coupling changed), the old and new
328// members carry on from where they are, their dots recomputed.
329function syncCoupling() {
330 const gs = coupledGroups();
331 const key = gs.length ? `${coupling}:${gs.map((g) => g.map((t) => t.id).join(',')).join(';')}` : '';
332 if (key === groupKey) return;
333 const was = groups.flat().filter((t) => tracks.includes(t));
334 groups = gs;
335 groupKey = key;
336 reseed([...new Set([...was, ...gs.flat()])]);
337}
e607771Optional coupling of the clicked orbitsJeremy Magland 338
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 339function setStart(t, x, v) {
340 const first = !t.start;
341 t.start = { x, v };
342 t.escaped = false;
343 restartTrack(t);
344 if (first) renderTracks();
345 else updateTrack(t);
346 renderHint();
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 349// ---- playhead and sound -----------------------------------------------------
351const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 352const ringTime = (dt) => Math.min(RING, 3 * dt);
31155f4Rhythm: pluck at both turning points by defaultJeremy Magland 354// The crossings of x' = 0 along a drive period's path (N + 1 points, evenly
355// spaced in time over dt from time t0), interpolated linearly: upward only
356// (from x' < 0 to x' >= 0), or both ways (also from x' > 0 to x' <= 0).
357function crossings(path, t0, dt, both) {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 358 const N = path.length / 2 - 1;
359 const notes = [];
360 for (let j = 1; j <= N; j++) {
361 const v0 = path[2 * j - 1];
362 const v1 = path[2 * j + 1];
31155f4Rhythm: pluck at both turning points by defaultJeremy Magland 363 if ((v0 < 0 && v1 >= 0) || (both && v0 > 0 && v1 <= 0)) {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 364 const f = v0 / (v0 - v1);
365 notes.push({ t: t0 + ((j - 1 + f) / N) * dt, x: path[2 * j - 2] + f * (path[2 * j] - path[2 * j - 2]), v: 0 });
366 }
367 }
368 return notes;
369}
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 371// ---- pitch ---------------------------------------------------------------------
373const midiHz = (m) => 440 * 2 ** ((m - 69) / 12);
374const noteName = (m) => `${KEYS[m % 12]}${Math.floor(m / 12) - 1}`;
375const pc = (n) => ((n % 12) + 12) % 12;
376// the shift (semitones) of custom notes c in key `key`: the nearer way from c.ref
377const shiftOf = (c, key) => { const d = pc(key - c.ref); return d > 6 ? d - 12 : d; };
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 378// the shift (semitones) from a track's custom notes as stored to as they
379// sound: its key's, and its octave's
380const offsetOf = (t) => shiftOf(val(t, 'notes'), val(t, 'key')) + 12 * val(t, 'octave');
381// a track's custom notes as they sound (in its key and octave)
382const soundingNotes = (t) => { const d = offsetOf(t); return val(t, 'notes').notes.map((n) => n + d); };
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 383const isCustom = (t) => val(t, 'scale') === CUSTOM;
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 384// custom notes played as they are (not as a scale), so the span is moot
385const exact = (t) => isCustom(t) && !val(t, 'notes').every;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 386
387// the pitch (Hz) a track plays at u in [0, 1] (the left to right edge of the
388// view), or null (custom notes, but none yet): custom notes spread evenly
389// over the view (or as a scale), or the scale's notes
390function pitchFor(t, u) {
391 const key = val(t, 'key');
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 392 const up = 2 ** val(t, 'octave');
393 if (!isCustom(t)) return up * pitchOf(u, SCALES[val(t, 'scale')], key, val(t, 'span'));
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 394 const c = val(t, 'notes');
395 if (!c.notes.length) return null;
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 396 if (c.every) return up * pitchOf(u, { steps: [...new Set(c.notes.map((n) => pc(n - c.ref)))] }, key, val(t, 'span'));
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 397 const ns = soundingNotes(t);
398 return midiHz(ns[Math.round(Math.min(1, Math.max(0, u)) * (ns.length - 1))]);
399}
401// MIDI velocity for SoundFont notes: the track's, jittered a little so
402// neighbouring velocity layers (or variations) alternate
403function velocity(t) {
404 const v = val(t, 'velocity') + Math.round((Math.random() * 2 - 1) * 6);
405 return Math.max(1, Math.min(127, v));
406}
408// One tick at time `time` (lasting dt) for tracks ts: each playhead advances
409// one drive period (together if coupled), keeping the path for the trail,
410// and plucks its notes (steady: one at the section point; natural: at each
411// upward x' = 0; both: at each x' = 0), at level gain.
412function beat(ts, time, dt, together, gain) {
413 const before = ts.map((t) => ({ ...t.ph.s }));
414 const paths = ts.map(() => new Float32Array(2 * (stepper.N + 1)));
415 if (together) stepper.stepMany(ts.map((t) => t.ph.s), coupling, paths);
416 else ts.forEach((t, k) => stepper.step(t.ph.s, paths[k]));
417 for (const [k, t] of ts.entries()) {
418 t.ph.until = time + dt;
419 if (before[k].escaped) continue;
420 const { x, v } = before[k];
421 const rhythm = val(t, 'rhythm');
422 // (at crossings: none in the period it escapes, whose path ends at rest)
423 const notes = rhythm === 'steady' ? [{ t: time, x, v }]
424 : t.ph.s.escaped ? [] : crossings(paths[k], time, dt, rhythm === 'both');
425 t.ph.queue.push({ time, dt, path: paths[k], last: t.ph.s.escaped, notes });
426 if (soundOn && synth) {
427 const voice = voiceOf(t);
428 for (const n of notes) {
429 const u = (n.x / view.xr + 1) / 2;
430 const freq = pitchFor(t, u);
431 if (freq == null) continue;
432 synth.play(t.id, voice, freq, n.t, {
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 433 pan: Math.max(-1, Math.min(1, 1.4 * u - 0.7)), gain, sustain: val(t, 'sustain'), vel: velocity(t), mono: val(t, 'mono'),
436 }
437 }
440// Run tracks ts (one, or a coupled set, sharing the tempo multiple) over
441// their ticks due within LOOKAHEAD. Ticks fall on a grid aligned to beat 0,
442// tickBeats apart; a track starting (or fallen behind: a stalled frame, a
443// hidden tab, a pause) picks up at the next tick after now, rather than
444// playing the missed ones in a burst.
445function runTicks(ts, now, gain) {
446 const lead = ts[0];
447 const step = tickBeats(lead);
448 const dt = tickDt(lead);
449 const until = Math.max(...ts.map((t) => t.ph.until));
450 if (lead.tick == null || timeAt(lead.tick * step) < now) {
451 lead.tick = Math.ceil(beatAt(Math.max(now + 0.02, until)) / step - 1e-6);
452 }
453 let k = lead.tick;
454 for (let time = timeAt(k * step); time < now + LOOKAHEAD; time = timeAt(++k * step)) {
455 // (after a tempo change, the ticks already played wait out)
456 if (time < until - 1e-6) continue;
457 beat(ts, time, dt, ts.length > 1, gain);
458 }
459 for (const t of ts) t.tick = k;
460}
462// schedule the ticks due within LOOKAHEAD, softer the more tracks play
463function schedule() {
464 const now = clock();
465 const playing = tracks.filter((t) => t.playing && t.ph);
466 const gain = 1 / Math.sqrt(Math.max(1, playing.length));
467 for (const g of groups) runTicks(g, now, gain);
468 for (const t of playing) if (!groupOf(t)) runTicks([t], now, gain);
469 for (const t of tracks) {
470 if (!t.ph) continue;
471 const dt = tickDt(t);
472 const keep = Math.max((TAIL + 1) * dt, ringTime(dt) + dt);
473 const q = t.ph.queue;
474 while (q.length > 1 && q[1].time < now - keep) q.shift();
476}
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 478// a new global tempo: the beat carries on from now
479function setTempo(bpm) {
480 const now = clock();
481 anchor = { time: now, beat: beatAt(now) };
482 tempo = bpm;
483}
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 485function setSound(on) {
486 soundOn = on;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 488 if (on && !synth) {
489 // the clock switches to the audio context's
490 synth = createSynth();
492 anchor = { time: clock(), beat: 0 };
493 for (const t of tracks) {
494 t.tick = null;
495 if (t.ph) { t.ph.queue = []; t.ph.until = 0; }
496 }
498 if (synth) {
499 synth.ctx.resume();
500 synth.setVolume(on ? Number($('volume').value) : 0);
501 }
502}
504// ---- drawing -----------------------------------------------------------------
506function readTheme() {
507 const cs = getComputedStyle(document.documentElement);
508 theme = {
509 bg: cs.getPropertyValue('--bg').trim(),
510 fg: cs.getPropertyValue('--fg').trim(),
511 muted: cs.getPropertyValue('--muted').trim(),
512 line: cs.getPropertyValue('--line').trim(),
513 accent: cs.getPropertyValue('--accent').trim(),
514 light: cs.getPropertyValue('--dot-light').trim(),
515 };
516}
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 518const orbitColor = (hue, isTrack, alpha = 1) =>
519 `hsla(${Math.round(hue * 360)}, ${isTrack ? 85 : 50}%, ${theme.light}, ${alpha})`;
521function plotRect() {
522 const dpr = devicePixelRatio || 1;
523 const w = canvas.width / dpr;
524 const h = canvas.height / dpr;
525 return { x: MARGIN.left, y: MARGIN.top, w: Math.max(10, w - MARGIN.left - MARGIN.right), h: Math.max(10, h - MARGIN.top - MARGIN.bottom) };
526}
528const toPx = (r, x, v) => [r.x + ((x / view.xr + 1) / 2) * r.w, r.y + ((1 - v / view.vr) / 2) * r.h];
530function drawPoints(o, from) {
531 const r = plotRect();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 532 const dctx = (o.isTrack ? top : dots).getContext('2d');
533 dctx.fillStyle = orbitColor(o.hue, o.isTrack, o.isTrack ? 0.95 : 0.7);
534 const size = o.isTrack ? 2.2 : 1.4;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 535 for (let i = from; i < o.n; i++) {
536 const [px, py] = toPx(r, o.pts[2 * i], o.pts[2 * i + 1]);
537 dctx.fillRect(px - size / 2, py - size / 2, size, size);
538 }
539}
541function clearDots(which = layers) {
542 const dpr = devicePixelRatio || 1;
543 for (const layer of which) {
544 const c = layer.getContext('2d');
545 c.setTransform(1, 0, 0, 1, 0, 0);
546 c.clearRect(0, 0, layer.width, layer.height);
547 c.setTransform(dpr, 0, 0, dpr, 0, 0);
548 }
549}
552function redrawTop() {
553 clearDots([top]);
554 for (const t of tracks) if (t.orbit) drawPoints(t.orbit, 0);
555}
557// the opacity of the fading dots
558const ghostAlpha = () => Math.max(0, 1 - (performance.now() / 1000 - ghostStart) / FADE);
560// start fading out what the given layers show (on top of what is fading already)
561function fadeOut(which) {
562 if (!canvas.width || !canvas.height) return;
563 const c = spare.getContext('2d');
564 c.setTransform(1, 0, 0, 1, 0, 0);
565 c.clearRect(0, 0, spare.width, spare.height);
566 const a = ghostAlpha();
567 if (a > 0) {
568 c.globalAlpha = a;
569 c.drawImage(ghost, 0, 0);
570 c.globalAlpha = 1;
571 }
572 for (const layer of which) c.drawImage(layer, 0, 0);
573 [ghost, spare] = [spare, ghost];
574 ghostStart = performance.now() / 1000;
575}
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 577function resize() {
578 const dpr = devicePixelRatio || 1;
579 const { width, height } = canvas.getBoundingClientRect();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 580 canvas.width = dots.width = top.width = ghost.width = spare.width = Math.round(width * dpr);
581 canvas.height = dots.height = top.height = ghost.height = spare.height = Math.round(height * dpr);
582 ghostStart = -Infinity;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 583 clearDots();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 584 for (const o of seeds) drawPoints(o, 0);
585 redrawTop();
588// advance the orbits within the frame's budget, drawing their new points
589function fill() {
590 const deadline = performance.now() + FRAME_BUDGET;
591 const advance = (o, count) => {
592 const from = o.n;
593 for (let k = 0; k < count && o.n < o.cap && !o.s.escaped; k++) {
594 stepper.step(o.s);
595 if (o.s.escaped) break;
596 if (o.skip > 0) { o.skip--; continue; }
597 o.pts[2 * o.n] = o.s.x;
598 o.pts[2 * o.n + 1] = o.s.v;
599 o.n++;
600 }
601 drawPoints(o, from);
602 };
604 // the coupled tracks together, as their playheads will move
605 const os = g.map((t) => t.orbit);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 607 for (let k = 0; k < TRACK_PER_FRAME && os.some((o) => o.n < o.cap && !o.s.escaped); k++) {
e607771Optional coupling of the clicked orbitsJeremy Magland 608 stepper.stepMany(os.map((o) => o.s), coupling);
609 for (const o of os) {
610 if (o.s.escaped || o.n >= o.cap) continue;
611 o.pts[2 * o.n] = o.s.x;
612 o.pts[2 * o.n + 1] = o.s.v;
613 o.n++;
614 }
615 }
616 os.forEach((o, k) => drawPoints(o, from[k]));
617 }
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 618 for (const t of tracks) if (t.orbit && !groupOf(t)) advance(t.orbit, TRACK_PER_FRAME);
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 619 let busy = true;
620 while (busy && performance.now() < deadline) {
621 busy = false;
623 if (o.n >= o.cap || o.s.escaped) continue;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 624 advance(o, 10);
625 busy = true;
626 }
627 }
628}
630function drawAxes(r) {
631 ctx.strokeStyle = theme.line;
632 ctx.lineWidth = 1;
633 ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1);
634 ctx.beginPath();
635 ctx.moveTo(r.x + r.w / 2, r.y);
636 ctx.lineTo(r.x + r.w / 2, r.y + r.h);
637 ctx.moveTo(r.x, r.y + r.h / 2);
638 ctx.lineTo(r.x + r.w, r.y + r.h / 2);
639 ctx.stroke();
640 ctx.fillStyle = theme.muted;
641 ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif';
642 ctx.textBaseline = 'top';
643 ctx.textAlign = 'left';
644 ctx.fillText(`−${view.xr.toFixed(2)}`, r.x, r.y + r.h + 6);
645 ctx.textAlign = 'right';
646 ctx.fillText(view.xr.toFixed(2), r.x + r.w, r.y + r.h + 6);
647 ctx.textAlign = 'center';
648 ctx.fillText('displacement x', r.x + r.w / 2, r.y + r.h + 6);
649 ctx.save();
650 ctx.translate(r.x - 8, r.y + r.h / 2);
651 ctx.rotate(-Math.PI / 2);
652 ctx.textBaseline = 'bottom';
653 ctx.fillText('velocity ẋ (s⁻¹)', 0, 0);
654 ctx.textAlign = 'right';
655 ctx.fillText(`${Math.round(view.vr)}`, r.h / 2, 0);
656 ctx.textAlign = 'left';
657 ctx.fillText(`−${Math.round(view.vr)}`, -r.h / 2, 0);
658 ctx.restore();
659}
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 661function drawPlayhead(c, r, t) {
662 const { ph, hue } = t;
663 if (!ph?.queue.length) return;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 664 const now = clock();
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 666 const q = ph.queue;
667 let cur = -1;
668 for (let k = 0; k < q.length; k++) if (q[k].time <= now) cur = k;
669 if (cur < 0) return;
671 c.beginPath();
672 c.rect(r.x, r.y, r.w, r.h);
673 c.clip();
674 c.lineWidth = 1.6;
675 c.lineCap = 'round';
676 c.lineJoin = 'round';
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 677 let head = null;
678 for (let k = 0; k <= cur; k++) {
679 const e = q[k];
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 680 // (N, the steps per period, as when the path was computed)
681 const N = e.path.length / 2 - 1;
682 const CHUNK = Math.max(4, Math.ceil(N / 24));
683 const span = e.dt;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 684 const f = Math.min(1, (now - e.time) / span);
685 const end = Math.floor(f * N);
686 for (let j0 = 0; j0 < end; j0 += CHUNK) {
687 const age = (now - (e.time + (j0 / N) * span)) / dt;
688 const alpha = 1 - age / TAIL;
689 if (alpha <= 0) continue;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 690 c.strokeStyle = orbitColor(hue, true, 0.85 * alpha);
691 c.beginPath();
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 692 for (let j = j0; j <= Math.min(end, j0 + CHUNK); j++) {
693 const [px, py] = toPx(r, e.path[2 * j], e.path[2 * j + 1]);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 694 if (j === j0) c.moveTo(px, py);
695 else c.lineTo(px, py);
699 if (k === cur) {
700 const j = Math.min(N, f * N);
701 const i0 = Math.floor(j);
702 const i1 = Math.min(N, i0 + 1);
703 const w = j - i0;
704 head = toPx(r, (1 - w) * e.path[2 * i0] + w * e.path[2 * i1], (1 - w) * e.path[2 * i0 + 1] + w * e.path[2 * i1 + 1]);
705 if (e.last) head = null;
706 }
707 // each pluck: a ring growing and fading where it was played
708 for (const n of e.notes) {
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 709 const g = (now - n.t) / ringTime(e.dt);
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 710 if (g < 0 || g >= 1) continue;
711 const [sx, sy] = toPx(r, n.x, n.v);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 712 c.strokeStyle = orbitColor(hue, true);
713 c.globalAlpha = 1 - g;
714 c.lineWidth = 2;
715 c.beginPath();
716 c.arc(sx, sy, 4 + 14 * g, 0, 2 * Math.PI);
717 c.stroke();
718 c.globalAlpha = 1;
720 }
721 if (head) {
723 c.arc(head[0], head[1], 4.5, 0, 2 * Math.PI);
724 if (t.playing) {
725 c.fillStyle = orbitColor(hue, true);
726 c.fill();
727 } else {
728 // paused: a hollow head
729 c.strokeStyle = orbitColor(hue, true);
730 c.lineWidth = 2;
731 c.stroke();
732 }
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 737// the tracks' start rings (a cross if escaped), and their numbers if `labels`
738function drawStarts(c, r, labels) {
739 for (const t of tracks) {
740 if (!t.start) continue;
741 const [px, py] = toPx(r, t.start.x, t.start.v);
742 const sel = t === selected;
743 c.strokeStyle = orbitColor(t.hue, true);
744 c.lineWidth = sel ? 2.5 : 1.5;
745 c.beginPath();
746 if (t.orbit?.s.escaped) {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 747 // escaped: a cross at its start
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 748 c.moveTo(px - 5, py - 5); c.lineTo(px + 5, py + 5);
749 c.moveTo(px + 5, py - 5); c.lineTo(px - 5, py + 5);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 751 c.arc(px, py, sel ? 7 : 5, 0, 2 * Math.PI);
754 if (!labels) continue;
755 // its number, beside the ring
756 c.fillStyle = orbitColor(t.hue, true);
757 c.font = `${sel ? 600 : 400} 12px "Hanken Grotesk", system-ui, sans-serif`;
758 c.textAlign = 'left';
759 c.textBaseline = 'bottom';
760 c.fillText(trackName(t), px + 7, py - 5);
761 }
762}
764// The phase space within plot rect r, on context c (set up so r is in CSS
765// px): the dots (and those fading out), then `under` (the axes, on screen),
766// the start rings (numbered if `labels`) and the playheads.
767function drawScene(c, r, { labels, under }) {
768 const dpr = devicePixelRatio || 1;
769 c.save();
770 c.beginPath();
771 c.rect(r.x, r.y, r.w, r.h);
772 c.clip();
773 c.fillStyle = theme.bg;
774 c.fillRect(r.x, r.y, r.w, r.h);
775 const w = canvas.width / dpr;
776 const h = canvas.height / dpr;
777 const a = ghostAlpha();
778 if (a > 0) {
779 c.globalAlpha = a;
780 c.drawImage(ghost, 0, 0, w, h);
781 c.globalAlpha = 1;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 783 c.drawImage(dots, 0, 0, w, h);
784 c.drawImage(top, 0, 0, w, h);
785 c.restore();
786 under?.();
787 drawStarts(c, r, labels);
788 for (const t of tracks) drawPlayhead(c, r, t);
791function frame() {
792 requestAnimationFrame(frame);
793 if (!canvas.width || !canvas.height) return;
795 dirty = false;
796 reset();
797 }
798 syncCoupling();
800 schedule();
802 const esc = !!t.orbit?.s.escaped;
803 if (esc !== t.escaped) { t.escaped = esc; updateTrack(t); }
804 }
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 805 const dpr = devicePixelRatio || 1;
806 const r = plotRect();
807 ctx.setTransform(1, 0, 0, 1, 0, 0);
808 ctx.fillStyle = theme.bg;
809 ctx.fillRect(0, 0, canvas.width, canvas.height);
810 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 811 drawScene(ctx, r, { labels: true, under: () => drawAxes(r) });
812 if (recording) drawRecordingFrame(r);
813}
815// ---- instruments ---------------------------------------------------------------
817// a track's instrument: 'b<i>' (VOICES[i]) or 's<id>:<i>' (preset i of the
818// loaded SoundFont with that id)
819const isSoundFont = (t) => t.instrument[0] === 's';
820const sfId = (font, preset) => `s${font.id}:${preset}`;
822// a SoundFont instrument's { font, preset }, or null
823function fontPreset(id) {
824 const m = /^s(\d+):(\d+)$/.exec(id);
825 const font = m && soundfonts.find((f) => f.id === Number(m[1]));
826 return font && Number(m[2]) < font.sf.presets.length ? { font, preset: Number(m[2]) } : null;
827}
829function voiceOf(t) {
830 if (!isSoundFont(t)) return Number(t.instrument.slice(1));
831 const { font, preset } = fontPreset(t.instrument);
832 if (!font.insts.has(preset)) font.insts.set(preset, makeInstrument(font.sf, preset));
833 return font.insts.get(preset);
834}
836function instrumentName(t) {
837 if (!isSoundFont(t)) return VOICES[Number(t.instrument.slice(1))].name;
838 const { font, preset } = fontPreset(t.instrument);
839 return font.sf.presets[preset].name;
840}
842// the first built-in voice no track is playing
843function freeInstrument() {
844 const i = VOICES.findIndex((_, k) => !tracks.some((t) => t.instrument === `b${k}`));
845 return `b${i < 0 ? 0 : i}`;
846}
848// ---- the tracks panel ------------------------------------------------------------
850const escapeHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
852const svg = (body, attrs = '') => `<svg viewBox="0 0 16 16" aria-hidden="true" ${attrs}>${body}</svg>`;
853const STROKE = 'fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"';
854const ICONS = {
855 play: svg('<path d="M4.5 2.8v10.4l8.5-5.2z" fill="currentColor"/>'),
856 pause: svg('<path d="M4 3h3v10H4zM9 3h3v10H9z" fill="currentColor"/>'),
857 restart: svg('<path d="M3.2 8.5a5 5 0 1 0 1.5-4.3"/><path d="M3.5 1.8v3.4h3.4"/>', STROKE),
858 remove: svg('<path d="M4 4l8 8M12 4l-8 8"/>', STROKE),
859 link: svg('<path d="M6.3 9.7l3.4-3.4"/><path d="M7.2 4.6l.9-.9a2.9 2.9 0 0 1 4.2 4.2l-.9.9"/><path d="M8.8 11.4l-.9.9a2.9 2.9 0 0 1-4.2-4.2l.9-.9"/>', STROKE),
860 unlink: svg('<path d="M7.2 4.6l.9-.9a2.9 2.9 0 0 1 4.2 4.2l-.9.9"/><path d="M8.8 11.4l-.9.9a2.9 2.9 0 0 1-4.2-4.2l.9-.9"/><path d="M2 5.5h1.6M5.5 2v1.6M14 10.5h-1.6M10.5 14v-1.6"/>', STROKE),
861 soundOn: svg('<path d="M2 6h2.5L8 3v10L4.5 10H2z" fill="currentColor"/><path d="M10.5 5.5a3.5 3.5 0 0 1 0 5M12.4 3.6a6.2 6.2 0 0 1 0 8.8"/>', 'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"'),
862 keyboard: svg('<rect x="1.5" y="3.5" width="13" height="9" rx="1"/><path d="M5 3.5v5M8 3.5v5M11 3.5v5M5 8.5v4M8 8.5v4M11 8.5v4"/>', STROKE),
863 soundOff: svg('<path d="M2 6h2.5L8 3v10L4.5 10H2z" fill="currentColor"/><path d="M10.5 6l4 4M14.5 6l-4 4"/>', 'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"'),
864};
866function scaleText(t) {
867 if (isCustom(t)) {
868 const c = val(t, 'notes');
869 if (!c.notes.length) return 'no notes yet';
870 const n = c.every ? new Set(c.notes.map(pc)).size : c.notes.length;
871 return c.every ? `custom, ${n} per octave` : `${n} custom note${n === 1 ? '' : 's'}`;
872 }
873 const s = SCALES[val(t, 'scale')];
874 return `${KEYS[val(t, 'key')]} ${SCALE_SHORT[s.name] ?? s.name}`;
875}
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 877// a track's range, for its summary, if not the usual: C2–C4, or (exact
878// custom notes) +1 oct
879function rangeText(t) {
880 const o = val(t, 'octave');
881 const span = val(t, 'span');
882 if (exact(t)) return o ? ` ${octaveLabel(o)} oct` : '';
883 return o || span !== OCTAVES ? ` ${cName(o)}–${cName(o + span)}` : '';
884}
887 if (!t.start) return 'No start yet: click the plot';
888 const r = RHYTHMS.find((q) => q.value === val(t, 'rhythm'));
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 889 const parts = [`${scaleText(t)}${rangeText(t)}`, rateLabel(t), r.short];
890 if (val(t, 'mono')) parts.push('mono');
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 891 if (t.escaped) parts.push('escaped');
892 return parts.join(' · ');
893}
895const fmtNum = (v) => (v < 0 ? '−' : '') + Math.abs(v);
896const coordsText = (t) => (t.start
897 ? `x = ${fmtNum(+t.start.x.toFixed(3))}, ẋ = ${fmtNum(Math.round(t.start.v))} s⁻¹`
898 : '<em>click the plot to place it</em>');
900function linkButton(t, p) {
901 const on = t.linked[p];
902 const title = on ? 'Linked: shared with the other linked tracks. Click to unlink.' : 'This track\'s own. Click to link it with the other tracks.';
903 return `<button class="link" data-act="link" data-p="${p}" aria-pressed="${on}" title="${title}" aria-label="Link ${p}">${on ? ICONS.link : ICONS.unlink}</button>`;
904}
906function rangeRow(t, p, disabled = false) {
907 const R = RANGES[p];
908 const v = val(t, p);
909 return `<div class="trow${t.linked[p] ? ' linked' : ''}${disabled ? ' na' : ''}"${R.title ? ` title="${R.title}"` : ''}>
910 ${linkButton(t, p)}<span class="lbl">${R.label}</span>
911 <input type="range" data-p="${p}" min="${R.min}" max="${R.max}" step="${R.step}" value="${v}"${disabled ? ' disabled' : ''} aria-label="${R.label}">
912 <output data-out="${p}">${R.fmt(v)}</output>
913 </div>`;
914}
916// the tempo multiple: a menu of the usual ones, or a custom value typed in
917function rateRow(t) {
918 const v = String(val(t, 'rate'));
919 const custom = !RATES.includes(v) || t.customRate;
920 const opts = RATES.map((r) => `<option value="${r}"${!custom && r === v ? ' selected' : ''}>×${r}</option>`).join('');
921 return `<div class="trow rate-row${t.linked.rate ? ' linked' : ''}${custom ? ' custom' : ''}" title="Ticks (drive periods) per beat of the tempo">
922 ${linkButton(t, 'rate')}<span class="lbl">Tempo</span>
923 <select data-rate aria-label="Tempo multiple">${opts}<option value="custom"${custom ? ' selected' : ''}>Custom…</option></select>
924 ${custom ? `<input data-rate-custom type="text" inputmode="decimal" value="${escapeHtml(v)}" aria-label="Custom tempo multiple" title="A number or a fraction from 1/16 to ${RATE_RANGE.max}, such as 3/2, 0.75 or 5">` : ''}
925 </div>`;
926}
928function instrumentOptions(t) {
929 const opt = (value, name) => `<option value="${value}"${value === t.instrument ? ' selected' : ''}>${escapeHtml(name)}</option>`;
930 let html = `<optgroup label="Built-in">${VOICES.map((v, i) => opt(`b${i}`, v.name)).join('')}</optgroup>`;
931 for (const f of soundfonts) {
932 const ps = f.sf.presets;
933 html += `<optgroup label="${escapeHtml(f.fileName)}">${ps.map((p, i) => opt(sfId(f, i), ps.length > 1 ? `${p.bank}:${p.program} ${p.name}` : p.name)).join('')}</optgroup>`;
934 }
935 return html;
936}
938// the custom notes' editor: a piano (the notes as they sound, in the track's
939// key; click a key, or press it on a MIDI keyboard, to add or remove it)
940const BLACK = [1, 3, 6, 8, 10];
941function notesEditor(t) {
942 const c = val(t, 'notes');
943 const sounding = soundingNotes(t);
944 const on = new Set(sounding);
945 const pcs = c.every ? new Set(sounding.map(pc)) : null;
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 946 // the range (every octave: the scale's, C3 to C6 shifted by the octave, or
947 // wider or narrower; else C3 to B5 shifted),
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 948 // widened by octaves to take in every note
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 949 const o = 12 * val(t, 'octave');
950 let lo = 48 + o;
951 let hi = (c.every ? 12 * val(t, 'span') : 35) + 48 + o;
953 lo = Math.min(lo, 12 * Math.floor(sounding[0] / 12));
954 hi = Math.max(hi, 12 * Math.ceil((sounding[sounding.length - 1] + 1) / 12) - 1);
955 }
956 const whites = [];
957 const blacks = [];
958 for (let m = lo; m <= hi; m++) (BLACK.includes(m % 12) ? blacks : whites).push({ m, at: whites.length });
959 const w = whites.length;
960 const key = ({ m, at }, black) => {
961 const lit = on.has(m);
962 const echo = !lit && pcs?.has(m % 12);
963 const cls = `${black ? 'bk' : 'wk'}${lit ? ' on' : ''}${echo ? ' echo' : ''}${midi.down.has(m) ? ' down' : ''}`;
964 return `<button class="${cls}" data-note="${m}" style="left: ${((100 * at) / w).toFixed(3)}%" title="${noteName(m)}" aria-label="${noteName(m)}" aria-pressed="${lit}">${!black && m % 12 === 0 ? `<span>${noteName(m)}</span>` : ''}</button>`;
965 };
966 const listening = midi.listening && t === selected;
967 const names = c.every
968 ? [...new Set(sounding.map(pc))].sort((a, b) => a - b).map((k) => KEYS[k]).join(' ')
969 : sounding.map(noteName).join(' ');
970 let status;
971 if (midi.error) status = `<span class="error">${midi.error}</span>`;
972 else if (listening) {
973 status = midi.inputs.length
974 ? `Listening to ${escapeHtml(midi.inputs.join(', '))}: hold down the notes you want, together or one after another without letting go (or with the sustain pedal down). Once you let go of everything, the next key starts a new set.`
975 : 'No MIDI keyboard found: plug one in (it is picked up when you do).';
976 } else status = 'Click keys to add or remove notes, or use a MIDI keyboard.';
977 return `<div class="notes-editor">
978 <div class="piano" style="--w: ${w}">${whites.map((k) => key(k, false)).join('')}${blacks.map((k) => key(k, true)).join('')}</div>
979 <div class="notes-bar">
980 <button class="midi-btn" data-act="midi" aria-pressed="${listening}" title="${listening ? 'Stop listening to the MIDI keyboard' : 'Take notes from a MIDI keyboard'}">${ICONS.keyboard}<span>${listening ? 'Listening…' : 'MIDI keyboard'}</span></button>
981 <label class="check" title="Play the notes' pitch classes in every octave, as a scale (rather than just these notes)"><input type="checkbox" data-every${c.every ? ' checked' : ''}> Every octave</label>
982 <button class="quiet" data-act="clear-notes"${c.notes.length ? '' : ' disabled'}>Clear</button>
983 </div>
984 <p class="notes-msg">${names ? `<span class="note-names">${names}</span>` : '<em>No notes yet: the track is silent.</em>'}<br>${status}</p>
985 </div>`;
986}
988// redraw the selected track's notes editor (if it is open)
989function refreshNotesEditor() {
990 const el = selected && trackEl(selected)?.querySelector('.notes-editor');
991 if (el) el.outerHTML = notesEditor(selected);
992}
994// add or remove sounding note m from a track's custom notes (every octave:
995// its pitch class); true if added
996function toggleNote(t, m) {
997 let c = val(t, 'notes');
998 if (!c.notes.length) c = { ...c, ref: val(t, 'key') };
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 999 const n = m - shiftOf(c, val(t, 'key')) - 12 * val(t, 'octave');
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1000 const has = c.every ? c.notes.some((q) => pc(q) === pc(n)) : c.notes.includes(n);
1001 const notes = has
1002 ? c.notes.filter((q) => (c.every ? pc(q) !== pc(n) : q !== n))
1003 : [...c.notes, n].sort((a, b) => a - b);
1004 setValue(t, 'notes', { ...c, notes });
1005 tracks.forEach(updateTrack);
1006 return !has;
1007}
1009// sound a note on a track's instrument now (to hear a key clicked)
1010function previewNote(t, m, vel = 100) {
1011 if (!soundOn || !synth) return;
1012 synth.play(t.id, voiceOf(t), midiHz(m), synth.ctx.currentTime + 0.01, { pan: 0, gain: 0.8, sustain: Math.min(1.5, val(t, 'sustain')), vel });
1013}
1015// ---- the MIDI keyboard -------------------------------------------------------------
1017// access: once granted; listening: its keys go to the selected track's
1018// custom notes; inputs: the devices' names; down: the keys held
1019// (held: a set of notes is being played: a key has gone down since all were
1020// up, and some key, or the sustain pedal, is still down)
1021const midi = { access: null, listening: false, inputs: [], error: '', down: new Set(), pedal: false, held: false };
1023// open MIDI (once): '' if open, or why not
1024async function openMidiOnce() {
1025 if (midi.access) return '';
1026 if (!midiSupported()) return 'This browser has no Web MIDI (Chrome, Edge and Firefox do).';
1027 try {
1028 midi.access = await openMidi({
1029 onNote: midiNote,
1030 onPedal: (down) => {
1031 midi.pedal = down;
1032 if (!down && !midi.down.size) midi.held = false;
1033 },
1034 onControl: midiControl,
1035 onInputs: (names) => { midi.inputs = names; refreshNotesEditor(); renderKnobs(); },
1036 });
1037 return '';
1038 } catch {
1039 return 'MIDI access was blocked: allow it for this page in the browser\'s site settings.';
1040 }
1041}
1043async function setListening(on) {
1044 midi.error = '';
1045 midi.listening = false;
1046 if (on) {
1047 const err = await openMidiOnce();
1048 if (err) midi.error = midiSupported() ? err : `${err} You can still click the keys.`;
1049 else midi.listening = true;
1050 }
1051 refreshNotesEditor();
1052}
1054// ---- MIDI knobs ------------------------------------------------------------------
1056// The sliders a knob (a MIDI controller's control change) can be assigned
1057// to: the equation's and the coupling. knobs: { [slider id]: { ch, cc,
1058// mode } }; learning: the slider waiting for a knob to be turned.
1059//
1060// mode: how the knob sends its turns. 'abs': its position, 0 to 127 (only
1061// when it changes); or relative, as endless encoders (the MiniLab's
1062// clickable browse knobs, say) send them: each message a step left or right,
1063// as 64 ± n ('rel64'), 16 ± n ('rel16') or n in two's complement ('rel2c').
1064// Told apart by repeats: a relative knob turned steadily sends the same
1065// value again and again, which an absolute one never does.
1066const KNOB_TARGETS = () => [...SLIDERS.map((sl) => `s-${sl.name}`), 'coupling'];
1067let knobs = {};
1068let knobsShown = false;
1069let learning = null;
1070let knobError = '';
1071let candidate = null; // while learning: { ch, cc, values, timer }, the knob being turned
1072const lastValue = new Map(); // the last value of each control ('ch:cc')
1073const flashTimers = new Map();
1074const MODES = ['abs', 'rel64', 'rel16', 'rel2c'];
1075const isRelative = (k) => k.mode !== 'abs' && k.mode !== 'auto';
1077// the relative mode values (repeats seen) suggest
1078function relativeMode(values) {
1079 if (values.every((v) => v >= 48 && v <= 80)) return 'rel64';
1080 if (values.every((v) => v >= 8 && v <= 24)) return 'rel16';
1081 return 'rel2c';
1082}
1084// a relative knob's message: the steps it turned (negative: to the left)
1085function relativeSteps(mode, v) {
1086 if (mode === 'rel64') return v - 64;
1087 if (mode === 'rel16') return v - 16;
1088 return v < 64 ? v : v - 128;
1089}
1091function readKnobs(o) {
1092 const r = {};
1093 for (const id of KNOB_TARGETS()) {
1094 const k = o?.[id];
1095 if (k && Number.isInteger(k.ch) && k.ch >= 0 && k.ch < 16 && Number.isInteger(k.cc) && k.cc >= 0 && k.cc < 128) {
1096 // (assigned before modes: 'auto', told by its next two values)
1097 r[id] = { ch: k.ch, cc: k.cc, mode: MODES.includes(k.mode) ? k.mode : 'auto' };
1098 }
1099 }
1100 return r;
1101}
1103const knobLabel = (k) => `CC${k.cc}${k.ch ? `/${k.ch + 1}` : ''}${isRelative(k) ? ' ↻' : ''}`;
1105function renderKnobs() {
1106 $('knobs').setAttribute('aria-pressed', knobsShown);
1107 document.querySelector('.eqn-panel').classList.toggle('knobs-on', knobsShown);
1108 for (const id of KNOB_TARGETS()) {
1109 const row = $(id).closest('.row');
1110 let chip = row.querySelector('.knob');
1111 if (!chip) {
1112 chip = document.createElement('button');
1113 chip.className = 'knob';
1114 chip.dataset.knob = id;
1115 chip.type = 'button';
1116 row.append(chip);
1117 }
1118 const k = knobs[id];
1119 const name = row.querySelector('span').textContent;
1120 chip.classList.toggle('learning', learning === id);
1121 chip.classList.toggle('set', !!k);
1122 chip.textContent = learning === id ? 'turn…' : k ? knobLabel(k) : '+';
1123 chip.title = learning === id ? 'Turn a knob to assign it (click to cancel)'
1124 : k ? `${knobLabel(k)} (${isRelative(k) ? 'relative' : 'absolute'}) controls ${name}: click to change or unassign it`
1125 : `Assign a knob to ${name}`;
1126 }
1127 const msg = $('knob-msg');
1128 msg.hidden = !knobsShown;
1129 msg.classList.toggle('error', !!knobError);
1130 const none = midi.access && !midi.inputs.length ? ' No MIDI device found: plug one in.' : '';
1131 if (knobError) msg.textContent = knobError;
1132 else if (learning) {
1133 const k = knobs[learning];
1134 const kind = k ? ` Its ${knobLabel(k)} is ${isRelative(k) ? '<b>relative</b> (endless)' : '<b>absolute</b> (0 to 127)'}: <button class="link-btn" data-mode>make it ${isRelative(k) ? 'absolute' : 'relative'}</button> · <button class="link-btn" data-unassign>unassign</button>` : '';
1135 msg.innerHTML = `Turn a knob on your controller to assign it.${none}${kind}`;
1136 } else msg.textContent = `Click a slider's + (or its knob's label), then turn a knob to assign it.${none}`;
1137}
1139async function learnKnob(id) {
1140 knobError = '';
1141 if (candidate) clearTimeout(candidate.timer);
1142 candidate = null;
1143 learning = learning === id ? null : id;
1144 if (learning) knobError = await openMidiOnce();
1145 if (knobError) learning = null;
1146 renderKnobs();
1147}
1149// the knob turned while learning: assigned once it has sent a few values
1150// (or paused), as relative if any repeated
1151function assignCandidate() {
1152 const { ch, cc, values, timer } = candidate;
1153 clearTimeout(timer);
1154 candidate = null;
1155 if (!learning) return;
1156 for (const [id, k] of Object.entries(knobs)) if (k.ch === ch && k.cc === cc) delete knobs[id];
1157 const repeats = values.some((v, i) => i && v === values[i - 1]);
1158 knobs[learning] = { ch, cc, mode: repeats ? relativeMode(values) : 'abs' };
1159 learning = null;
1160 saveKnobs(knobs);
1161 renderKnobs();
1162}
1164// a knob turned (or another control change)
1165function midiControl(ch, cc, value) {
1166 const key = `${ch}:${cc}`;
1167 const seen = lastValue.has(key);
1168 const repeat = lastValue.get(key) === value;
1169 lastValue.set(key, value);
1170 if (learning) {
1171 if (candidate && (candidate.ch !== ch || candidate.cc !== cc)) return;
1172 candidate ??= { ch, cc, values: [], timer: setTimeout(assignCandidate, 400) };
1173 candidate.values.push(value);
1174 if (candidate.values.length >= 5) assignCandidate();
1175 return;
1176 }
1177 for (const [id, k] of Object.entries(knobs)) {
1178 if (k.ch !== ch || k.cc !== cc) continue;
1179 // an absolute knob repeating itself is a relative one after all
1180 if (repeat && !isRelative(k)) {
1181 k.mode = relativeMode([value]);
1182 saveKnobs(knobs);
1183 renderKnobs();
1184 } else if (k.mode === 'auto') {
1185 // (not known yet: wait for a second value)
1186 if (!seen) continue;
1187 k.mode = 'abs';
1188 saveKnobs(knobs);
1189 }
1190 const input = $(id);
1191 const lo = Number(input.min);
1192 const hi = Number(input.max);
1193 // absolute: the slider's range, 0 to 127; relative: steps of a 256th of
1194 // it (at least the slider's step), more as the knob turns faster;
1195 // snapped to the slider's step by the input
1196 const v = isRelative(k)
1197 ? Number(input.value) + relativeSteps(k.mode, value) * Math.max(Number(input.step) || 0, (hi - lo) / 256)
1198 : lo + ((hi - lo) * value) / 127;
1199 const before = input.value;
1200 input.value = v;
1201 if (input.value === before) continue;
1202 input.dispatchEvent(new Event('input', { bubbles: true }));
1203 // (the row lights up a moment)
1204 const row = input.closest('.row');
1205 row.classList.add('turned');
1206 clearTimeout(flashTimers.get(id));
1207 flashTimers.set(id, setTimeout(() => row.classList.remove('turned'), 250));
1208 }
1209}
1211function buildKnobControls() {
1212 knobs = readKnobs(loadKnobs());
1213 $('knobs').addEventListener('click', () => {
1214 knobsShown = !knobsShown;
1215 if (!knobsShown) learning = null;
1216 knobError = '';
1217 renderKnobs();
1218 });
1219 document.querySelector('.eqn-panel').addEventListener('click', (e) => {
1220 if (e.target.closest('[data-mode]') && learning && knobs[learning]) {
1221 const k = knobs[learning];
1222 k.mode = isRelative(k) ? 'abs' : relativeMode([lastValue.get(`${k.ch}:${k.cc}`) ?? 64]);
1223 saveKnobs(knobs);
1224 renderKnobs();
1225 return;
1226 }
1227 if (e.target.closest('[data-unassign]') && learning) {
1228 delete knobs[learning];
1229 learning = null;
1230 saveKnobs(knobs);
1231 renderKnobs();
1232 return;
1233 }
1234 const chip = e.target.closest('.knob');
1235 if (!chip) return;
1236 e.preventDefault();
1237 learnKnob(chip.dataset.knob);
1238 });
1239 renderKnobs();
1240 // knobs assigned before: listen for them (MIDI access, if granted before,
1241 // is given without asking)
1242 if (Object.keys(knobs).length && midiSupported()) openMidiOnce();
1243}
1245// A key pressed on the MIDI keyboard: the keys pressed together (from the
1246// first one down until all are up, and the sustain pedal too) become the
1247// notes; the next press after that starts afresh.
1248function midiNote(m, on) {
1249 const fresh = on && !midi.held;
1250 if (on) {
1251 midi.down.add(m);
1252 midi.held = true;
1253 } else {
1254 midi.down.delete(m);
1255 if (!midi.down.size && !midi.pedal) midi.held = false;
1256 }
1257 const t = selected;
1258 // (not sounded: the keyboard makes its own sound, if any)
1259 if (midi.listening && t && isCustom(t) && on) addNote(t, m, fresh);
1260 refreshNotesEditor();
1261}
1263// add sounding note m to a track's custom notes, or (fresh) make it the only one
1264function addNote(t, m, fresh) {
1265 let c = val(t, 'notes');
1266 if (fresh || !c.notes.length) c = { ...c, notes: [], ref: val(t, 'key') };
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1267 const n = m - shiftOf(c, val(t, 'key')) - 12 * val(t, 'octave');
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1268 if (!c.notes.includes(n)) setValue(t, 'notes', { ...c, notes: [...c.notes, n].sort((a, b) => a - b) });
1269 else setValue(t, 'notes', c);
1270 tracks.forEach(updateTrack);
1271}
1273function trackBody(t) {
1274 const sf = isSoundFont(t);
1275 const lk = (p) => (t.linked[p] ? ' linked' : '');
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1276 const opt = (value, text, on) => `<option value="${value}"${on ? ' selected' : ''}>${text}</option>`;
1277 const ex = exact(t);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1278 return `<div class="track-body">
1279 <div class="trow start-row">
1280 <span></span><span class="lbl">Start</span>
1281 <span class="coords">${coordsText(t)}</span>
1282 </div>
1283 <div class="trow">
1284 <span></span><span class="lbl">Instrument</span>
1285 <select data-instrument aria-label="Instrument">${instrumentOptions(t)}</select>
1286 </div>
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1287 <div class="tgrid">
1288 <div class="trow${lk('rhythm')}">
1289 ${linkButton(t, 'rhythm')}<span class="lbl">Rhythm</span>
1290 <select data-p="rhythm" aria-label="Rhythm">${RHYTHMS.map((r) => opt(r.value, r.name, r.value === val(t, 'rhythm'))).join('')}</select>
1291 </div>
1292 ${rateRow(t)}
1293 <div class="trow${lk('scale')}">
1294 ${linkButton(t, 'scale')}<span class="lbl">Scale</span>
1295 <select data-p="scale" aria-label="Scale">${SCALES.map((s, i) => opt(i, s.name, i === val(t, 'scale'))).join('')}${opt(CUSTOM, 'Custom notes…', isCustom(t))}</select>
1296 </div>
1297 <div class="trow${lk('key')}">
1298 ${linkButton(t, 'key')}<span class="lbl">Key</span>
1299 <select data-p="key" aria-label="Key">${KEYS.map((k, i) => opt(i, k, i === val(t, 'key'))).join('')}</select>
1300 </div>
1301 ${isCustom(t) ? notesEditor(t) : ''}
1302 <div class="trow${lk('octave')}" title="${ex ? 'Shift the notes by whole octaves' : 'The note at the left edge of the plot, and the octaves across it'}">
1303 ${linkButton(t, 'octave')}<span class="lbl">Range</span>
1304 <div class="pair">
1305 <select data-p="octave" aria-label="${ex ? 'Octave shift' : 'Lowest note'}">${OCTAVE_SHIFTS.map((o) => opt(o, ex ? (o ? `${octaveLabel(o)} oct` : 'as played') : `from ${cName(o)}`, o === val(t, 'octave'))).join('')}</select>
1306 <select data-p="span" aria-label="Octaves across the plot"${ex ? ' disabled title="Exact custom notes: the notes set the range"' : ''}>${SPANS.map((n) => opt(n, `${n} oct`, n === val(t, 'span'))).join('')}</select>
1307 </div>
1308 </div>
1309 <div class="trow${lk('mono')}" title="Stop the note still ringing when the next one starts">
1310 ${linkButton(t, 'mono')}<span class="lbl">Mono</span>
1311 <label class="mono-check"><input type="checkbox" data-p="mono"${val(t, 'mono') ? ' checked' : ''}> one note at a time</label>
1312 </div>
1313 ${sf ? rangeRow(t, 'velocity') : rangeRow(t, 'sustain')}
1314 ${rangeRow(t, 'volume')}
1316 <p class="link-note">${ICONS.link} linked settings are shared by every track that links them</p>
1317 </div>`;
1318}
1320function trackItem(t) {
1321 const sel = t === selected;
1322 return `<li class="track${sel ? ' selected' : ''}" data-id="${t.id}" style="--h: ${Math.round(t.hue * 360)}">
1323 <div class="track-head" data-act="select" aria-expanded="${sel}">
1324 <button class="icon-btn play-btn" data-act="play" aria-pressed="${t.playing}" ${t.start ? '' : 'disabled'} aria-label="${t.playing ? 'Pause' : 'Play'} track ${trackName(t)}" title="${t.playing ? 'Pause' : 'Play'}">${t.playing ? ICONS.pause : ICONS.play}</button>
1325 <div class="track-title">
1326 <span class="track-name"><span class="num">${trackName(t)}</span>${escapeHtml(instrumentName(t))}</span>
1327 <span class="summary">${summary(t)}</span>
1328 </div>
1329 <button class="icon-btn" data-act="restart" ${t.start ? '' : 'disabled'} aria-label="Restart track ${trackName(t)}" title="Restart from its start">${ICONS.restart}</button>
1330 <button class="icon-btn" data-act="remove" aria-label="Remove track ${trackName(t)}" title="Remove the track">${ICONS.remove}</button>
1331 </div>
1332 ${sel ? trackBody(t) : ''}
1333 </li>`;
1334}
1336function renderTracks() {
1337 $('track-list').innerHTML = tracks.map(trackItem).join('');
1338 renderSoundFonts();
1339 $('add-track').disabled = tracks.length >= MAX_TRACKS;
1340 $('add-track').textContent = tracks.length >= MAX_TRACKS ? `${MAX_TRACKS} tracks at most` : '+ Add track';
1341 renderTransport();
1342 renderHint();
1343}
1345const trackEl = (t) => $('track-list').querySelector(`.track[data-id="${t.id}"]`);
1347// update a track's head (and its body's start) in place
1348function updateTrack(t) {
1349 const el = trackEl(t);
1350 if (!el) return;
1351 el.querySelector('.summary').textContent = summary(t);
1352 const play = el.querySelector('[data-act="play"]');
1353 play.setAttribute('aria-pressed', t.playing);
1354 play.title = t.playing ? 'Pause' : 'Play';
1355 play.setAttribute('aria-label', `${t.playing ? 'Pause' : 'Play'} track ${trackName(t)}`);
1356 play.innerHTML = t.playing ? ICONS.pause : ICONS.play;
1357 const coords = el.querySelector('.coords');
1358 if (coords) coords.innerHTML = coordsText(t);
1359}
1361function renderTransport() {
1362 const placed = tracks.filter((t) => t.start);
1363 $('play-all').disabled = !placed.some((t) => !t.playing);
1364 $('pause-all').disabled = !placed.some((t) => t.playing);
1365 $('restart-all').disabled = !placed.length;
1366}
1368function renderHint() {
1369 const t = selected;
1370 let s;
1371 if (!tracks.length) s = 'Click the plot to add a track';
1372 else if (!t) s = 'Click to add a track · click a start ring to pick its track';
1373 else if (!t.start) s = `Click to place track ${trackName(t)}'s start`;
1374 else s = `Click or drag to move track ${trackName(t)}'s start${tracks.length < MAX_TRACKS && !matchMedia('(pointer: coarse)').matches ? ' · shift-click for a new track' : ''}`;
1375 $('hint').textContent = s;
1376}
1378function renderSoundButton() {
1379 const btn = $('sound');
1380 btn.setAttribute('aria-pressed', soundOn);
1381 btn.innerHTML = `${soundOn ? ICONS.soundOn : ICONS.soundOff}<span>${soundOn ? 'Sound on' : 'Sound off'}</span>`;
1382 btn.title = soundOn ? 'Mute' : 'Turn the sound on';
1383 if (soundOn) btn.classList.remove('nudge');
1384}
1386function setPlaying(t, on) {
1387 if (!t.start || t.playing === on) return;
1388 t.playing = on;
1389 if (on && !t.ph) restart([t]);
1390 updateTrack(t);
1391 renderTransport();
1392 // playing, but muted: point at the sound button
1393 if (on && !soundOn) {
1394 const btn = $('sound');
1395 btn.classList.remove('nudge');
1396 void btn.offsetWidth;
1397 btn.classList.add('nudge');
1398 }
1399}
1401function buildTrackControls() {
1402 const list = $('track-list');
1403 const trackOf = (el) => {
1404 const li = el.closest('.track');
1405 return li && tracks.find((t) => String(t.id) === li.dataset.id);
1406 };
1407 list.addEventListener('click', (e) => {
1408 const t = trackOf(e.target);
1409 if (!t) return;
1410 const act = e.target.closest('[data-act]');
1411 const noteBtn = e.target.closest('button[data-note]');
1412 if (noteBtn) {
1413 const m = Number(noteBtn.dataset.note);
1414 if (toggleNote(t, m)) previewNote(t, m);
1415 refreshNotesEditor();
1416 return;
1417 }
1418 if (!act) return;
1419 switch (act.dataset.act) {
1420 case 'play': setPlaying(t, !t.playing); break;
1421 case 'restart': restartTrack(t); break;
1422 case 'remove': removeTrack(t); break;
1423 case 'midi': setListening(!midi.listening); break;
1424 case 'clear-notes':
1425 setValue(t, 'notes', { ...val(t, 'notes'), notes: [] });
1426 tracks.forEach(updateTrack);
1427 refreshNotesEditor();
1428 break;
1429 case 'link':
1430 setLinked(t, act.dataset.p, !t.linked[act.dataset.p]);
1431 renderTracks();
1432 break;
1433 case 'select':
1434 selected = selected === t ? null : t;
1435 renderTracks();
1436 break;
1437 default:
1438 }
1439 });
1440 list.addEventListener('input', (e) => {
1441 if (e.target.matches('input[data-rate-custom]')) {
1442 e.target.classList.toggle('invalid', Number.isNaN(parseRate(e.target.value.replace(/\s+/g, ''))));
1443 return;
1444 }
1445 const t = trackOf(e.target);
1446 const p = e.target.dataset?.p;
1447 if (!t || !RANGES[p]) return;
1448 const v = Number(e.target.value);
1449 setValue(t, p, v);
1450 e.target.closest('.trow').querySelector('output').textContent = RANGES[p].fmt(v);
1451 tracks.forEach(updateTrack);
1452 });
1453 list.addEventListener('change', (e) => {
1454 const t = trackOf(e.target);
1455 if (!t) return;
1456 if (e.target.matches('select[data-instrument]')) {
1457 t.instrument = e.target.value;
1458 renderTracks();
1459 } else if (e.target.matches('select[data-rate]')) {
1460 if (e.target.value === 'custom') {
1461 t.customRate = true;
1462 renderTracks();
1463 const input = trackEl(t)?.querySelector('[data-rate-custom]');
1464 input?.focus();
1465 input?.select();
1466 } else {
1467 t.customRate = false;
1468 setValue(t, 'rate', e.target.value);
1469 renderTracks();
1470 }
1471 } else if (e.target.matches('input[data-rate-custom]')) {
1472 const text = e.target.value.replace(/\s+/g, '');
1473 const ok = !Number.isNaN(parseRate(text));
1474 e.target.classList.toggle('invalid', !ok);
1475 if (ok) {
1476 setValue(t, 'rate', text);
1477 tracks.forEach(updateTrack);
1478 }
1479 } else if (e.target.matches('select[data-p="rhythm"]')) {
1480 setValue(t, 'rhythm', e.target.value);
1481 tracks.forEach(updateTrack);
1482 } else if (e.target.matches('select[data-p="scale"]')) {
1483 const custom = e.target.value === CUSTOM;
1484 setValue(t, 'scale', custom ? CUSTOM : Number(e.target.value));
1485 renderTracks();
1486 // (the keyboard's keys go to the notes from the start)
1487 if (custom && midiSupported() && !midi.listening) setListening(true);
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1488 } else if (e.target.matches('select[data-p="key"], select[data-p="octave"], select[data-p="span"]')) {
1489 setValue(t, e.target.dataset.p, Number(e.target.value));
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1490 tracks.forEach(updateTrack);
1491 refreshNotesEditor();
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1492 } else if (e.target.matches('input[data-p="mono"]')) {
1493 setValue(t, 'mono', e.target.checked);
1494 tracks.forEach(updateTrack);
1495 } else if (e.target.matches('input[data-every]')) {
1496 setValue(t, 'notes', { ...val(t, 'notes'), every: e.target.checked });
1497 renderTracks(); // (the range's menus change with it)
1499 });
1500 $('add-track').addEventListener('click', addTrack);
1501 $('play-all').addEventListener('click', () => tracks.forEach((t) => setPlaying(t, true)));
1502 $('pause-all').addEventListener('click', () => tracks.forEach((t) => setPlaying(t, false)));
1503 $('restart-all').addEventListener('click', () => {
1504 restart(tracks);
1505 for (const g of groups) reseed(g);
1506 });
1507}
1509// ---- the plot: picking and dragging starts ------------------------------------
1511function buildPlotControls() {
1512 let drag = null; // { t, px, py, moved }
1513 const at = (e) => {
1514 const rect = canvas.getBoundingClientRect();
1515 const r = plotRect();
1516 const px = e.clientX - rect.left;
1517 const py = e.clientY - rect.top;
1518 const inside = px >= r.x && px <= r.x + r.w && py >= r.y && py <= r.y + r.h;
1519 const cx = Math.min(r.x + r.w, Math.max(r.x, px));
1520 const cy = Math.min(r.y + r.h, Math.max(r.y, py));
1521 return { r, px, py, inside, x: ((cx - r.x) / r.w * 2 - 1) * view.xr, v: (1 - (cy - r.y) / r.h * 2) * view.vr };
1522 };
1523 canvas.addEventListener('pointerdown', (e) => {
1524 const p = at(e);
1525 if (!p.inside) return;
1526 // on a start ring: pick that track (and drag it, past a few px)
1527 const hit = !e.shiftKey && tracks.find((t) => {
1528 if (!t.start) return false;
1529 const [cx, cy] = toPx(p.r, t.start.x, t.start.v);
1530 return Math.hypot(cx - p.px, cy - p.py) <= HIT_RADIUS;
1531 });
1532 canvas.setPointerCapture(e.pointerId);
1533 if (hit) {
1534 if (selected !== hit) { selected = hit; renderTracks(); }
1535 drag = { t: hit, px: p.px, py: p.py, moved: false };
1536 return;
1537 }
1538 // elsewhere: move the selected track's start (shift, or none selected:
1539 // a new track's)
1540 let t = selected;
1541 if (e.shiftKey || !t) t = addTrack();
1542 if (!t) return;
1543 setStart(t, p.x, p.v);
1544 drag = { t, moved: true };
1545 });
1546 canvas.addEventListener('pointermove', (e) => {
1547 if (!drag) return;
1548 const p = at(e);
1549 if (!drag.moved && Math.hypot(p.px - drag.px, p.py - drag.py) < DRAG_START) return;
1550 drag.moved = true;
1551 setStart(drag.t, p.x, p.v);
1552 });
1553 const end = () => { drag = null; };
1554 canvas.addEventListener('pointerup', end);
1555 canvas.addEventListener('pointercancel', end);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1558// ---- the equation panel ----------------------------------------------------------
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1560function buildEquationControls() {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 1561 const presetSel = $('preset');
1562 presetSel.innerHTML = PRESETS.map((pr, i) => `<option value="${i}">${pr.name}</option>`).join('')
1563 + '<option value="custom" hidden>Custom</option>';
1565 $('sliders').innerHTML = SLIDERS.map((s) => `
1566 <label class="row">
1567 <span>${s.label}</span>
1568 <input type="range" id="s-${s.name}" min="${s.min}" max="${s.max}" step="${s.step}">
1569 <output id="o-${s.name}"></output>
1570 </label>`).join('');
1572 for (const s of SLIDERS) {
1573 $(`s-${s.name}`).addEventListener('input', (e) => {
1574 params[s.name] = Number(e.target.value) * (s.scale ?? 1);
1575 $(`o-${s.name}`).textContent = s.fmt(Number(e.target.value));
1576 presetSel.value = 'custom';
1579 }
1580 presetSel.addEventListener('change', () => {
1581 if (presetSel.value === 'custom') return;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1582 // the tracks carry on from where they are under the new parameters
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 1583 params = { ...PRESETS[presetSel.value].params };
1585 dirty = true;
1589 // coupling: off, then 1 to about 3000 s^-1 on a log scale (the coupled
1590 // tracks' dots are recomputed, in syncCoupling)
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1592 cpl.addEventListener('input', () => setCoupling(Number(cpl.value)));
1593 setCoupling(Number(cpl.value));
1594}
1596function showParams() {
1597 for (const s of SLIDERS) {
1598 const v = params[s.name] / (s.scale ?? 1);
1599 $(`s-${s.name}`).value = v;
1600 $(`o-${s.name}`).textContent = s.fmt(Number($(`s-${s.name}`).value));
1601 }
1602}
1604// u: the coupling slider, 0 (off), then 1 to about 3000 s^-1 on a log scale
1605function setCoupling(u) {
1606 $('coupling').value = u;
1607 coupling = u ? 10 ** (u / 20) : 0;
1608 $('coupling').nextElementSibling.textContent = coupling ? `${Math.round(coupling)} s⁻¹` : 'off';
1609}
1611function buildMasterControls() {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 1612 const vol = $('volume');
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1613 vol.addEventListener('input', () => setMasterVolume(Number(vol.value)));
1614 setMasterVolume(Number(vol.value));
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 1615 $('sound').addEventListener('click', () => setSound(!soundOn));
1617 Object.assign(tem, { min: TEMPO.min, max: TEMPO.max, step: 1, value: tempo });
1618 tem.addEventListener('input', () => {
1619 setTempo(Number(tem.value));
1620 showTempo();
1621 });
1622 showTempo();
1623 renderSoundButton();
1624}
1626const showTempo = () => {
1627 $('tempo').value = tempo;
1628 $('tempo').nextElementSibling.textContent = `${tempo} bpm`;
1629};
1631function setMasterVolume(v) {
1632 const vol = $('volume');
1633 vol.value = v;
1634 vol.nextElementSibling.textContent = `${Math.round(100 * v)}%`;
1635 if (synth && soundOn) synth.setVolume(v);
1636}
1638// ---- uploaded SoundFont -------------------------------------------------------
1640// add a .sf2 file's bytes (ArrayBuffer): its presets join the instruments.
1641// A file of the same name as one loaded replaces it (its tracks keep their
1642// presets, found by name). save: remember it in this browser; assign: the
1643// open track takes its first preset. Returns the font, or null if unreadable.
1644function addSoundFont(fileName, bytes, { save = true, assign = save } = {}) {
1645 let sf;
1646 try {
1647 sf = parseSF2(bytes);
1648 } catch (err) {
1649 sfMessage(`Can't read ${fileName}: ${err.message}`, true);
1650 return null;
1651 }
1652 const old = soundfonts.find((f) => f.fileName === fileName);
1653 const font = { id: old?.id ?? nextFontId++, fileName, bytes, sf, insts: new Map() };
1654 if (old) {
1655 // the tracks on it: their presets by name in the new file
1656 const names = new Map(tracks.filter((t) => fontPreset(t.instrument)?.font === old)
1657 .map((t) => [t, old.sf.presets[fontPreset(t.instrument).preset].name]));
1658 soundfonts[soundfonts.indexOf(old)] = font;
1659 for (const [t, name] of names) {
1660 const k = sf.presets.findIndex((p) => p.name === name);
1661 t.instrument = k >= 0 ? sfId(font, k) : freeInstrument();
1662 }
1663 } else {
1664 soundfonts.push(font);
1665 }
1666 if (save) saveSoundFont({ fileName, bytes });
1667 if (assign && selected) selected.instrument = sfId(font, 0);
1668 sfMessage('');
1669 renderSoundFonts();
1670 renderTracks();
1671 return font;
1672}
1674function removeSoundFont(font) {
1675 soundfonts = soundfonts.filter((f) => f !== font);
1676 forgetSoundFont(font.fileName);
1677 for (const t of tracks) if (isSoundFont(t) && !fontPreset(t.instrument)) t.instrument = freeInstrument();
1678 renderSoundFonts();
1679 renderTracks();
1680}
1682const sfMessage = (text, error = false) => {
1683 $('sf-msg').textContent = text;
1684 $('sf-msg').classList.toggle('error', error);
1685};
1687function renderSoundFonts() {
1688 $('sf-list').innerHTML = soundfonts.map((f) => {
1689 const n = f.sf.presets.length;
1690 const used = tracks.filter((t) => fontPreset(t.instrument)?.font === f).map(trackName);
1691 return `<li>
1692 <span class="sf-name" title="${escapeHtml(f.fileName)}">${escapeHtml(f.fileName)}</span>
1693 <span class="sf-info">${n} preset${n === 1 ? '' : 's'}${used.length ? ` · track${used.length > 1 ? 's' : ''} ${used.join(', ')}` : ''}</span>
1694 <button class="quiet small" data-font="${f.id}" aria-label="Remove ${escapeHtml(f.fileName)}" title="Remove it (its tracks go back to built-in instruments)">×</button>
1695 </li>`;
1696 }).join('');
1697 $('sf-empty').hidden = soundfonts.length > 0;
1698}
1700function buildSoundFontControls() {
1701 $('sf-load').addEventListener('click', () => $('sf-file').click());
1702 $('sf-file').addEventListener('change', async () => {
1703 const files = [...$('sf-file').files];
1704 $('sf-file').value = '';
1705 // (the open track takes the first one's first preset)
1706 let assign = true;
1707 for (const file of files) {
1708 if (addSoundFont(file.name, await file.arrayBuffer(), { assign })) assign = false;
1709 }
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1711 $('sf-list').addEventListener('click', (e) => {
1712 const btn = e.target.closest('button[data-font]');
1713 const font = btn && soundfonts.find((f) => String(f.id) === btn.dataset.font);
1714 if (font) removeSoundFont(font);
1717}
1719// ---- saving the state ------------------------------------------------------------
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1721const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
1722const finite = (v) => typeof v === 'number' && Number.isFinite(v);
1724// everything to save: the equation, the global settings and the tracks (each
1725// with where its playhead is), but not whether the sound is on
1726function captureState() {
1727 return {
1728 format: FORMAT,
1729 version: 1,
1730 preset: $('preset').value,
1731 params: { ...params },
1732 coupling: Number($('coupling').value),
1733 tempo,
1734 volume: Number($('volume').value),
1735 shared: { ...shared },
1736 hueCounter,
1737 selected: tracks.indexOf(selected),
1738 tracks: tracks.map((t) => ({
1739 hue: t.hue,
1740 instrument: isSoundFont(t) ? 's' : t.instrument,
1741 ...(isSoundFont(t) ? { soundfont: fontPreset(t.instrument).font.fileName, preset: fontPreset(t.instrument).preset } : {}),
1742 instrumentName: instrumentName(t),
1743 start: t.start,
1744 at: t.ph ? { x: t.ph.s.x, v: t.ph.s.v, escaped: t.ph.s.escaped } : null,
1745 playing: t.playing,
1746 own: { ...t.own },
1747 linked: { ...t.linked },
1748 customRate: !!t.customRate,
1749 })),
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1753// a track's settings from saved ones, each checked (or the default's)
1754function readSettings(o, base) {
1755 const r = { ...base };
1756 if (!o || typeof o !== 'object') return r;
1757 if (RHYTHMS.some((q) => q.value === o.rhythm)) r.rhythm = o.rhythm;
1758 if ((Number.isInteger(o.scale) && SCALES[o.scale]) || o.scale === CUSTOM) r.scale = o.scale;
1759 const c = o.notes;
1760 if (c && typeof c === 'object' && Array.isArray(c.notes)) {
1761 r.notes = {
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1762 notes: [...new Set(c.notes.filter((n) => Number.isInteger(n) && n >= -36 && n <= 163))].sort((a, b) => a - b),
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1763 ref: Number.isInteger(c.ref) && c.ref >= 0 && c.ref < 12 ? c.ref : DEFAULT_KEY,
1764 every: !!c.every,
1765 };
1766 }
1767 if (Number.isInteger(o.key) && o.key >= 0 && o.key < KEYS.length) r.key = o.key;
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1768 if (OCTAVE_SHIFTS.includes(o.octave)) r.octave = o.octave;
1769 if (SPANS.includes(o.span)) r.span = o.span;
1770 if (typeof o.mono === 'boolean') r.mono = o.mono;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1771 if (o.rate != null && !Number.isNaN(parseRate(o.rate))) r.rate = String(o.rate);
1772 for (const p of ['sustain', 'volume', 'velocity']) if (finite(o[p])) r[p] = clamp(o[p], RANGES[p].min, RANGES[p].max);
1773 return r;
1774}
1776// a saved track's instrument, if there is such a one: a built-in voice, or a
1777// SoundFont preset, in the file of that name by its number if the name
1778// matches, or else by name (in that file, then in any loaded)
1779function readInstrument(s) {
1780 const b = /^b(\d+)$/.exec(String(s.instrument));
1781 if (b) return Number(b[1]) < VOICES.length ? s.instrument : null;
1782 // (saved when only one SoundFont could be loaded: 's<preset>')
1783 const old = /^s(\d+)$/.exec(String(s.instrument));
1784 const font = soundfonts.find((f) => f.fileName === s.soundfont) ?? (old ? soundfonts[0] : null);
1785 const i = old ? Number(old[1]) : s.preset;
1786 const name = s.instrumentName;
1787 if (font) {
1788 const ps = font.sf.presets;
1789 if (Number.isInteger(i) && i >= 0 && i < ps.length && (name == null || ps[i].name === name)) return sfId(font, i);
1790 const k = ps.findIndex((p) => p.name === name);
1791 if (k >= 0) return sfId(font, k);
1792 }
1793 for (const f of soundfonts) {
1794 const k = f.sf.presets.findIndex((p) => p.name === name);
1795 if (k >= 0) return sfId(f, k);
1796 }
1797 return null;
1798}
1800const readPoint = (p) => (p && finite(p.x) && finite(p.v) ? { x: p.x, v: p.v } : null);
1802// replace everything with a saved state ({} for the defaults); the tracks
1803// carry on from where their playheads were
1804function applyState(st) {
1805 st = st && typeof st === 'object' ? st : {};
1806 params = { ...PRESETS[0].params };
1807 for (const sl of SLIDERS) if (finite(st.params?.[sl.name])) params[sl.name] = clamp(st.params[sl.name], sl.min * (sl.scale ?? 1), sl.max * (sl.scale ?? 1));
1808 const presets = [...$('preset').options].map((o) => o.value);
1809 $('preset').value = presets.includes(String(st.preset)) ? String(st.preset) : st.params ? 'custom' : '0';
1810 showParams();
1811 setCoupling(finite(st.coupling) ? Math.round(clamp(st.coupling, 0, 70)) : 0);
1812 setTempo(finite(st.tempo) ? Math.round(clamp(st.tempo, TEMPO.min, TEMPO.max)) : TEMPO.default);
1813 showTempo();
1814 setMasterVolume(finite(st.volume) ? clamp(st.volume, 0, 1) : 0.6);
1815 shared = readSettings(st.shared, DEFAULTS);
1817 for (const t of tracks) synth?.removeTrack(t.id);
1818 tracks = [];
1819 hueCounter = 0;
1820 for (const s of (Array.isArray(st.tracks) ? st.tracks : []).slice(0, MAX_TRACKS)) {
1821 if (!s || typeof s !== 'object') continue;
1822 const t = newTrack();
1823 if (finite(s.hue)) t.hue = s.hue;
1824 t.instrument = readInstrument(s) ?? t.instrument;
1825 t.own = readSettings(s.own, DEFAULTS);
1826 for (const p of SETTINGS) if (typeof s.linked?.[p] === 'boolean') t.linked[p] = s.linked[p];
1827 t.customRate = !!s.customRate;
1828 t.start = readPoint(s.start);
1829 if (t.start) {
1830 const at = readPoint(s.at) ?? t.start;
1831 t.ph = newPlayhead(at.x, at.v);
1832 t.ph.s.escaped = !!s.at?.escaped;
1833 t.orbit = newOrbit(t.start.x, t.start.v, TRACK_POINTS, t.hue, true);
1834 t.playing = !!s.playing;
1835 }
1836 tracks.push(t);
1837 }
1838 hueCounter = Math.max(tracks.length, finite(st.hueCounter) ? st.hueCounter : 0);
1839 selected = st.selected === -1 ? null : tracks[st.selected] ?? tracks[0] ?? null;
1840 groups = [];
1841 groupKey = '';
1842 dirty = true; // (reset at the next frame: the dots from where the playheads are)
1843 if (!tracks.length) addTrack();
1844 applyVolumes();
1845 renderTracks();
1846}
1848const sessionMessage = (text, error = false) => {
1849 $('session-msg').textContent = text;
1850 $('session-msg').classList.toggle('error', error);
1851};
1853function autosave() {
1854 if (restored && !saveLocal(captureState())) sessionMessage('Couldn\'t save in this browser (storage is blocked or full).', true);
1855}
1857function exportFile() {
1858 const st = captureState();
1859 st.soundfonts = soundfonts.map((f) => ({ fileName: f.fileName, data: toBase64(f.bytes) }));
1860 const d = new Date();
1861 const pad = (n) => String(n).padStart(2, '0');
1862 const name = `duffing-islands-${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}.json`;
1863 download(JSON.stringify(st, null, 1), name);
1864 const n = soundfonts.length;
1865 sessionMessage(`Saved ${name}${n ? `, with ${n === 1 ? soundfonts[0].fileName : `${n} SoundFonts`}` : ''}.`);
1866}
1868async function importFile(file) {
1869 let st;
1870 try {
1871 st = JSON.parse(await file.text());
1872 } catch {
1873 sessionMessage(`Can't read ${file.name}: not a JSON file.`, true);
1874 return;
1875 }
1876 if (st?.format !== FORMAT) {
1877 sessionMessage(`${file.name} isn't a Duffing Islands file.`, true);
1878 return;
1879 }
1880 // its SoundFonts first, so the tracks can find their instruments
1881 for (const sf of Array.isArray(st.soundfonts) ? st.soundfonts : []) {
1882 if (!sf?.data) continue;
1883 const fileName = String(sf.fileName ?? 'SoundFont.sf2');
1884 let bytes;
1885 try {
1886 bytes = fromBase64(sf.data);
1887 } catch {
1888 sfMessage(`Can't read ${fileName} in ${file.name}.`, true);
1889 continue;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1891 addSoundFont(fileName, bytes, { save: true, assign: false });
1892 }
1893 applyState(st);
1894 autosave();
1895 sessionMessage(`Opened ${file.name}.`);
1896}
1898function buildSessionControls() {
1899 $('export').addEventListener('click', exportFile);
1900 $('import').addEventListener('click', () => $('import-file').click());
1901 $('import-file').addEventListener('change', () => {
1902 const file = $('import-file').files[0];
1903 $('import-file').value = '';
1904 if (file) importFile(file);
1905 });
1906 $('start-over').addEventListener('click', () => {
1907 if (!confirm('Start over with the default settings and one empty track? (Save to a file first to keep this session.)')) return;
1908 forgetLocal();
1909 applyState({});
1910 sessionMessage('Started over.');
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1912 // save as you go, and on leaving
1913 setInterval(autosave, 2000);
1914 addEventListener('pagehide', autosave);
1915 document.addEventListener('visibilitychange', () => { if (document.hidden) autosave(); });
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1918// ---- recording -------------------------------------------------------------------
1919// A video: the phase space alone (no axes or labels), drawn each frame onto a
1920// canvas of its own at the plot's size when the recording started (its longer
1921// side at most REC_MAX px), with the sound as heard. Or just the sound, as
1922// heard, sample for sample, into a 16-bit stereo WAV file.
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1923
1924const REC_MAX = 1920;
1925const REC_FPS = 60;
1926const recCanvas = document.createElement('canvas');
1927const REC_TYPES = [
1928 'video/mp4;codecs=avc1.640028,mp4a.40.2',
1929 'video/mp4;codecs=avc1.4d002a,mp4a.40.2',
1930 'video/mp4',
1931 'video/webm;codecs=vp9,opus',
1932 'video/webm;codecs=vp8,opus',
1933 'video/webm',
1934];
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1935const canRecordVideo = () => typeof MediaRecorder !== 'undefined' && !!recCanvas.captureStream;
1936const canRecordAudio = () => typeof AudioWorkletNode !== 'undefined';
1937const REC_KIND_KEY = 'duffing-islands:rec-kind';
1938const recKind = () => $('rec-kind').value;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1939
1940// a frame of the video: the plot rect r of the screen, scaled to the canvas
1941function drawRecordingFrame(r) {
1942 const c = recCanvas.getContext('2d');
1943 const sx = recCanvas.width / r.w;
1944 const sy = recCanvas.height / r.h;
1945 c.setTransform(sx, 0, 0, sy, -r.x * sx, -r.y * sy);
1946 drawScene(c, r, { labels: false });
1947}
1949const fmtTime = (sec) => {
1950 const s = Math.floor(sec);
1951 const h = Math.floor(s / 3600);
1952 const mm = String(Math.floor((s % 3600) / 60)).padStart(h ? 2 : 1, '0');
1953 return `${h ? `${h}:` : ''}${mm}:${String(s % 60).padStart(2, '0')}`;
1954};
1955const fmtSize = (bytes) => (bytes < 1e9 ? `${(bytes / 1e6).toFixed(bytes < 1e7 ? 1 : 0)} MB` : `${(bytes / 1e9).toFixed(2)} GB`);
1957function startRecording() {
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1958 if (recKind() === 'audio') { startAudioRecording(); return; }
1959 if (!canRecordVideo()) return;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1960 // the audio is the sound as heard, so the sound goes on
1961 if (!soundOn) setSound(true);
1962 discardRecording();
1963 const r = plotRect();
1964 const dpr = devicePixelRatio || 1;
1965 const k = Math.min(1, REC_MAX / (Math.max(r.w, r.h) * dpr));
1966 recCanvas.width = 2 * Math.round((r.w * dpr * k) / 2);
1967 recCanvas.height = 2 * Math.round((r.h * dpr * k) / 2);
1968 drawRecordingFrame(r);
1969 const stream = recCanvas.captureStream(REC_FPS);
1970 for (const track of synth.stream().getAudioTracks()) stream.addTrack(track);
1971 const mime = REC_TYPES.find((t) => MediaRecorder.isTypeSupported(t)) ?? '';
1972 let recorder;
1973 try {
1974 recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 8e6, audioBitsPerSecond: 192e3 });
1975 } catch (err) {
1976 recMessage(`Can't record here: ${err.message}`);
1977 return;
1978 }
1979 const chunks = [];
1980 recorder.ondataavailable = (e) => { if (e.data.size) chunks.push(e.data); };
1981 recorder.onstop = () => {
1982 const rec = recording;
1983 recording = null;
1984 for (const track of stream.getVideoTracks()) track.stop();
1985 const type = rec.recorder.mimeType || rec.mime || 'video/webm';
1986 recorded = { blob: new Blob(rec.chunks, { type }), mime: type, seconds: (performance.now() - rec.started) / 1000, saved: false };
1987 renderRecording();
1988 };
1989 recorder.onerror = (e) => recMessage(`Recording failed: ${e.error?.message ?? 'unknown error'}`);
1990 // (in slices, so a long recording is collected as it goes)
1991 recorder.start(1000);
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1992 recording = { kind: 'video', recorder, chunks, mime, started: performance.now() };
1994}
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 1996// the sound alone: its frames, as they come, kept as 16-bit stereo
1997async function startAudioRecording() {
1998 if (!canRecordAudio()) return;
1999 if (!soundOn) setSound(true);
2000 discardRecording();
2001 const rec = { kind: 'audio', stop: null, chunks: [], frames: 0, rate: synth.ctx.sampleRate, started: performance.now() };
2002 recording = rec;
2003 renderRecording();
2004 try {
2005 rec.stop = await synth.capture((l, r) => {
2006 const out = new Int16Array(2 * l.length);
2007 for (let i = 0; i < l.length; i++) {
2008 out[2 * i] = Math.round(32767 * Math.max(-1, Math.min(1, l[i])));
2009 out[2 * i + 1] = Math.round(32767 * Math.max(-1, Math.min(1, r[i])));
2010 }
2011 rec.chunks.push(out);
2012 rec.frames += l.length;
2013 });
2014 } catch (err) {
2015 recording = null;
2016 renderRecording();
2017 recMessage(`Can't record here: ${err.message}`);
2018 return;
2019 }
2020 // (stopped while starting)
2021 if (rec.stopping) finishAudioRecording(rec);
2022}
2024async function finishAudioRecording(rec) {
2025 await rec.stop();
2026 recording = null;
2027 recorded = { blob: wavBlob(rec.chunks, rec.frames, rec.rate), mime: 'audio/wav', seconds: rec.frames / rec.rate, saved: false };
2028 renderRecording();
2029}
2031// a 16-bit stereo WAV file of interleaved samples
2032function wavBlob(chunks, frames, rate) {
2033 const h = new DataView(new ArrayBuffer(44));
2034 const str = (o, t) => { for (let i = 0; i < t.length; i++) h.setUint8(o + i, t.charCodeAt(i)); };
2035 const bytes = 4 * frames;
2036 str(0, 'RIFF'); h.setUint32(4, 36 + bytes, true); str(8, 'WAVE');
2037 str(12, 'fmt '); h.setUint32(16, 16, true); h.setUint16(20, 1, true); h.setUint16(22, 2, true);
2038 h.setUint32(24, rate, true); h.setUint32(28, 4 * rate, true); h.setUint16(32, 4, true); h.setUint16(34, 16, true);
2039 str(36, 'data'); h.setUint32(40, bytes, true);
2040 return new Blob([h, ...chunks], { type: 'audio/wav' });
2041}
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2043function stopRecording() {
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 2044 const rec = recording;
2045 if (!rec) return;
2046 if (rec.kind === 'audio') {
2047 if (rec.stopping) return;
2048 rec.stopping = true;
2049 if (rec.stop) finishAudioRecording(rec);
2050 } else if (rec.recorder.state !== 'inactive') rec.recorder.stop();
2053function discardRecording() {
2054 recorded = null;
2055 renderRecording();
2056}
2058function saveRecording() {
2059 if (!recorded) return;
2060 const d = new Date();
2061 const pad = (n) => String(n).padStart(2, '0');
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 2062 const ext = recorded.mime === 'audio/wav' ? 'wav' : recorded.mime.includes('mp4') ? 'mp4' : 'webm';
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2063 downloadBlob(recorded.blob, `duffing-islands-${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}.${ext}`);
2064 recorded.saved = true;
2065}
2067const recMessage = (text) => { $('rec-status').textContent = text; $('rec-status').hidden = !text; };
2069function renderRecording() {
2070 const btn = $('record');
2071 const on = !!recording;
2072 btn.setAttribute('aria-pressed', on);
2073 btn.querySelector('.rec-label').textContent = on ? 'Stop' : 'Record';
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 2074 const audio = recKind() === 'audio';
2075 btn.title = on ? 'Stop recording'
2076 : audio ? 'Record the sound as a WAV file (the sound goes on)' : 'Record a video of the phase space with the sound (the sound goes on)';
2077 btn.disabled = !(audio ? canRecordAudio() : canRecordVideo());
2078 if (btn.disabled) btn.title = `Recording ${audio ? 'audio' : 'video'} isn't supported in this browser`;
2079 $('rec-kind').disabled = on;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2080 $('rec-download').hidden = !recorded;
2081 $('rec-discard').hidden = !recorded;
2082 if (recorded) {
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 2083 $('rec-download').textContent = `Download ${recorded.mime === 'audio/wav' ? 'WAV' : 'video'} (${fmtTime(recorded.seconds)}, ${fmtSize(recorded.blob.size)})`;
2085 updateRecordingTime();
2086}
2088function updateRecordingTime() {
2089 if (!recording) {
2090 recMessage('');
2091 return;
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 2093 const bytes = recording.kind === 'audio' ? 44 + 4 * recording.frames : recording.chunks.reduce((n, c) => n + c.size, 0);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2094 recMessage(`${fmtTime((performance.now() - recording.started) / 1000)} · ${fmtSize(bytes)}`);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2097function buildRecordingControls() {
2098 const btn = $('record');
55bfe11Track octave, range and mono; faster tempos; audio-only WAV recordingJeremy Magland 2099 const kind = $('rec-kind');
2100 try { if (['video', 'audio'].includes(localStorage.getItem(REC_KIND_KEY))) kind.value = localStorage.getItem(REC_KIND_KEY); } catch { /* storage blocked */ }
2101 if (!canRecordVideo() && canRecordAudio()) kind.value = 'audio';
2102 kind.addEventListener('change', () => {
2103 try { localStorage.setItem(REC_KIND_KEY, kind.value); } catch { /* storage blocked */ }
2104 renderRecording();
2105 });
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2106 btn.addEventListener('click', () => (recording ? stopRecording() : startRecording()));
2107 $('rec-download').addEventListener('click', saveRecording);
2108 $('rec-discard').addEventListener('click', () => {
2109 if (recorded && !recorded.saved && !confirm('Discard the recording without downloading it?')) return;
2110 discardRecording();
2111 });
2112 setInterval(() => { if (recording) updateRecordingTime(); }, 500);
2113 // a recording in progress, or not yet downloaded: ask before leaving
2114 addEventListener('beforeunload', (e) => {
2115 if (recording || (recorded && !recorded.saved)) e.preventDefault();
2116 });
2117 renderRecording();
2120readTheme();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2121matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { readTheme(); resize(); });
2122buildEquationControls();
2123buildMasterControls();
2124buildTrackControls();
2125buildPlotControls();
2126buildSoundFontControls();
2127buildSessionControls();
2128buildRecordingControls();
2129buildKnobControls();
2131new ResizeObserver(resize).observe(canvas);
2132resize();
2133requestAnimationFrame(frame);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2134// the SoundFont and the state saved in this browser (or the defaults: one
2135// track, waiting for its start)
2136loadSaved()
2137 .then((recs) => { for (const rec of Array.isArray(recs) ? recs : []) addSoundFont(rec.fileName, rec.bytes, { save: false }); })
2138 .finally(() => {
2139 applyState(loadLocal() ?? {});
2140 restored = true;
2141 });