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';
37import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, 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
80const SETTINGS = ['rhythm', 'scale', 'key', 'rate', 'sustain', 'volume', 'velocity'];
81const DEFAULTS = {
82 rhythm: 'steady', scale: SCALES.findIndex((s) => s.name === DEFAULT_SCALE), key: DEFAULT_KEY,
83 rate: '1', sustain: SUSTAIN.default, volume: 1, velocity: 100,
84};
85const LINKED_BY_DEFAULT = ['scale', 'key'];
86// The 'Custom notes' scale (the scale setting's value CUSTOM): its notes are
87// in the setting 'notes', which is linked along with the scale: MIDI note
88// numbers (sorted), as entered in key `ref`, so a change of key transposes
89// them (the nearer way); every: their pitch classes in every octave (a scale
90// across the usual three octaves), rather than just those notes.
91const CUSTOM = 'custom';
92DEFAULTS.notes = { notes: [], ref: DEFAULT_KEY, every: true };
93const VALUES = [...SETTINGS, 'notes']; // a track's values (the settings, and the custom notes)
94const linkOf = (p) => (p === 'notes' ? 'scale' : p);
95// the global tempo (bpm)
96const TEMPO = { min: 40, max: 240, default: 120 };
97// a track's tempo multiple: ticks (drive periods) per beat, as text ('3',
98// '1/2', '1.5'); the menu's choices, and the range of custom ones
99const RATES = ['16', '12', '8', '6', '4', '3', '2', '1', '1/2', '1/3', '1/4', '1/6', '1/8'];
100const RATE_RANGE = { min: 1 / 16, max: 32 };
101const RANGES = {
102 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)' },
103 volume: { label: 'Volume', min: 0, max: 1, step: 0.01, fmt: (v) => `${Math.round(100 * v)}%` },
104 velocity: { label: 'Velocity', min: 1, max: 127, step: 1, fmt: (v) => `${v}`, title: 'MIDI velocity (SoundFont instruments)' },
105};
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 107const $ = (id) => document.getElementById(id);
108const canvas = $('plot');
109const ctx = canvas.getContext('2d');
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 110// the section points, accumulated: seed orbits, and the tracks' on top
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 111const dots = document.createElement('canvas');
112const top = document.createElement('canvas');
113const layers = [dots, top];
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 114// replaced dots, fading out (and a spare canvas to composite into)
115let ghost = document.createElement('canvas');
116let spare = document.createElement('canvas');
117let ghostStart = -Infinity;
119let params = { ...PRESETS[0].params };
120let stepper;
121let view; // { xr, vr }: half-ranges of x and x'
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 122let seeds = []; // the seed orbits
123let tracks = []; // see newTrack
124let selected = null; // the track whose controls are open, and whose start a click moves
125let shared = { ...DEFAULTS }; // the linked tracks' settings
126let tempo = TEMPO.default; // bpm
127let 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 128let synth = null;
129let soundOn = false;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 131let hueCounter = 0;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 132let coupling = 0; // r (s^-1) of the coupling; 0: off
133let groups = []; // the sets of coupled tracks, as last restarted
134let groupKey = '';
135let dirty = false; // the equation changed: reset at the next frame
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 137let soundfonts = []; // the loaded .sf2 files: { id, fileName, bytes, sf (parsed), insts: Map(preset -> instrument) }
138let nextFontId = 1;
139let recording = null; // { recorder, chunks, mime, started } while recording
140let recorded = null; // { blob, mime, seconds, saved } once stopped
141let restored = false; // the saved state has been restored (until then, nothing is saved)
143// ---- tracks --------------------------------------------------------------------
145// a track's setting: its own, or the shared one if linked
146const val = (t, p) => (t.linked[linkOf(p)] ? shared : t.own)[p];
147// a tempo multiple's value from its text ('3', '1/2', '1.5'), or NaN
148function parseRate(text) {
149 const m = String(text).trim().match(/^(\d*\.?\d+)\s*(?:\/\s*(\d*\.?\d+))?$/);
150 const v = m ? Number(m[1]) / (m[2] ? Number(m[2]) : 1) : NaN;
151 return v >= RATE_RANGE.min && v <= RATE_RANGE.max ? v : NaN;
152}
153const rateOf = (t) => parseRate(val(t, 'rate')) || 1;
154const rateLabel = (t) => `×${val(t, 'rate')}`;
155// a track's tick: its length in beats, and in seconds (one drive period)
156const tickBeats = (t) => 1 / rateOf(t);
157const tickDt = (t) => 60 / (tempo * rateOf(t));
158// the beat at clock time `time`, and the clock time of beat b
159const beatAt = (time) => anchor.beat + ((time - anchor.time) * tempo) / 60;
160const timeAt = (b) => anchor.time + ((b - anchor.beat) * 60) / tempo;
161// the coupled set a track is in, if any
162const groupOf = (t) => groups.find((g) => g.includes(t));
164// a new track, paused, with the settings of `like` (a track) or the defaults
165function newTrack(like) {
166 const own = like ? Object.fromEntries(VALUES.map((p) => [p, val(like, p)])) : { ...DEFAULTS };
167 return {
168 id: nextId++,
169 hue: (0.08 + hueCounter++ * 0.382) % 1,
170 instrument: freeInstrument(),
171 start: null, // { x, v }
172 orbit: null, // its dots
173 ph: null, // its playhead
174 playing: false,
175 tick: null, // its next tick, as a number of ticks from beat 0 (null: from the next one due)
176 own,
177 linked: Object.fromEntries(SETTINGS.map((p) => [p, LINKED_BY_DEFAULT.includes(p)])),
178 escaped: false,
179 };
180}
182function addTrack() {
183 if (tracks.length >= MAX_TRACKS) return null;
184 const t = newTrack(selected);
185 tracks.push(t);
186 selected = t;
187 applyVolumes();
188 renderTracks();
189 return t;
190}
192function removeTrack(t) {
193 tracks = tracks.filter((q) => q !== t);
194 if (selected === t) selected = tracks[tracks.length - 1] ?? null;
195 synth?.removeTrack(t.id);
196 redrawTop();
197 renderTracks();
198}
200function setValue(t, p, v) {
201 (t.linked[linkOf(p)] ? shared : t.own)[p] = v;
202 if (p === 'volume') applyVolumes();
203 if (p === 'rate') for (const q of tracks) q.tick = null; // onto the new grid
204}
206// link or unlink a track's setting: linking adopts the shared value (or, if
207// no other track is linked, shares the track's own); unlinking keeps it
208function setLinked(t, p, on) {
209 if (on === t.linked[p]) return;
210 const ps = VALUES.filter((q) => linkOf(q) === p);
211 if (on) {
212 if (!tracks.some((q) => q !== t && q.linked[p])) for (const q of ps) shared[q] = t.own[q];
213 } else {
214 for (const q of ps) t.own[q] = shared[q];
215 }
216 t.linked[p] = on;
217 if (p === 'volume') applyVolumes();
218 if (p === 'rate') t.tick = null;
219}
221const applyVolumes = () => { for (const t of tracks) synth?.setTrackVolume(t.id, val(t, 'volume')); };
223const trackName = (t) => `${tracks.indexOf(t) + 1}`;
225// the sets of coupled tracks: the playing ones with the same tempo multiple,
226// two or more to a set
227function coupledGroups() {
228 if (!coupling) return [];
229 const by = new Map();
230 for (const t of tracks) {
231 if (!t.start || !t.playing) continue;
232 const k = rateOf(t).toPrecision(9);
233 if (!by.has(k)) by.set(k, []);
234 by.get(k).push(t);
235 }
236 return [...by.values()].filter((g) => g.length > 1);
237}
239// ---- physics ---------------------------------------------------------------
241// x' half-range: the speed at the bottom of the well of a free orbit that
242// just reaches x = +/-xr, so the view frames the motions of that size
243function speedRange(p, xr) {
244 const V = (x) => 0.5 * p.omega2 * x * x + 0.25 * p.alpha * x ** 4;
245 const vMin = p.omega2 < 0 && p.alpha > 0 ? -(p.omega2 ** 2) / (4 * p.alpha) : 0;
246 const v = Math.sqrt(Math.max(0, 2 * (V(xr) - vMin)));
247 return Math.max(v, 0.3 * xr * p.Omega, 1);
248}
250// skip: drive periods to run before recording (a seed's transient)
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 251function newOrbit(x, v, cap, hue, isTrack, skip = 0) {
252 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 255// a playhead: the orbit's state; its scheduled beats ({ time, dt, path,
256// last, notes }) still needed for the trail, notes: [{ t, x, v }]; and the
257// time its last scheduled beat ends
258const newPlayhead = (x, v) => ({ s: { x, v, escaped: false }, queue: [], until: 0 });
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 260function reset() {
261 const p = physicsOf(params);
262 stepper = createStepper(p);
263 view = { xr: params.view, vr: speedRange(p, params.view) };
264 // damped: the seeds settle onto the attractors before they are drawn,
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 265 // for about 5 / delta (the tracks show the way in)
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 266 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 268 for (let i = 0; i < SEEDS_X; i++) {
269 const x = view.xr * (-1 + (2 * (i + 0.5)) / SEEDS_X);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 270 seeds.push(newOrbit(x, 0, SEED_POINTS, (i * 0.618) % 1, false, skip));
272 for (let i = 0; i < SEEDS_V; i++) {
273 const v = 0.9 * view.vr * (-1 + (2 * (i + 0.5)) / SEEDS_V);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 274 seeds.push(newOrbit(0, v, SEED_POINTS, ((i + SEEDS_X) * 0.618) % 1, false, skip));
277 clearDots([dots]);
278 reseed(tracks, false);
279}
281// recompute tracks' dots from where their playheads are (coupled as they
282// will move), the old ones fading out
283function reseed(ts, fade = true) {
284 if (fade) fadeOut([top]);
285 for (const t of ts) {
286 if (!t.ph) continue;
287 const { x, v, escaped } = t.ph.s;
288 t.orbit = newOrbit(x, v, TRACK_POINTS, t.hue, true);
289 t.orbit.s.escaped = escaped;
292}
294// restart tracks' playheads from their starts, and their dots too if they
295// weren't computed from there
296function restart(ts) {
297 let changed = false;
298 for (const t of ts) {
299 if (!t.start) continue;
300 t.ph = newPlayhead(t.start.x, t.start.v);
301 t.tick = null;
302 if (!t.orbit || t.orbit.x0 !== t.start.x || t.orbit.v0 !== t.start.v) {
303 t.orbit = newOrbit(t.start.x, t.start.v, TRACK_POINTS, t.hue, true);
304 changed = true;
305 }
306 }
307 if (changed) redrawTop();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 310// restart a track; if it is coupled, the others carry on, with it
311function restartTrack(t) {
312 restart([t]);
313 const g = groupOf(t);
314 if (g) reseed(g);
315}
e607771Optional coupling of the clicked orbitsJeremy Magland 316
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 317// When the coupled sets change (a track played, paused, added or removed,
318// its tempo multiple changed, or the coupling changed), the old and new
319// members carry on from where they are, their dots recomputed.
320function syncCoupling() {
321 const gs = coupledGroups();
322 const key = gs.length ? `${coupling}:${gs.map((g) => g.map((t) => t.id).join(',')).join(';')}` : '';
323 if (key === groupKey) return;
324 const was = groups.flat().filter((t) => tracks.includes(t));
325 groups = gs;
326 groupKey = key;
327 reseed([...new Set([...was, ...gs.flat()])]);
328}
e607771Optional coupling of the clicked orbitsJeremy Magland 329
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 330function setStart(t, x, v) {
331 const first = !t.start;
332 t.start = { x, v };
333 t.escaped = false;
334 restartTrack(t);
335 if (first) renderTracks();
336 else updateTrack(t);
337 renderHint();
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 340// ---- playhead and sound -----------------------------------------------------
342const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 343const ringTime = (dt) => Math.min(RING, 3 * dt);
31155f4Rhythm: pluck at both turning points by defaultJeremy Magland 345// The crossings of x' = 0 along a drive period's path (N + 1 points, evenly
346// spaced in time over dt from time t0), interpolated linearly: upward only
347// (from x' < 0 to x' >= 0), or both ways (also from x' > 0 to x' <= 0).
348function crossings(path, t0, dt, both) {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 349 const N = path.length / 2 - 1;
350 const notes = [];
351 for (let j = 1; j <= N; j++) {
352 const v0 = path[2 * j - 1];
353 const v1 = path[2 * j + 1];
31155f4Rhythm: pluck at both turning points by defaultJeremy Magland 354 if ((v0 < 0 && v1 >= 0) || (both && v0 > 0 && v1 <= 0)) {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 355 const f = v0 / (v0 - v1);
356 notes.push({ t: t0 + ((j - 1 + f) / N) * dt, x: path[2 * j - 2] + f * (path[2 * j] - path[2 * j - 2]), v: 0 });
357 }
358 }
359 return notes;
360}
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 362// ---- pitch ---------------------------------------------------------------------
364const midiHz = (m) => 440 * 2 ** ((m - 69) / 12);
365const noteName = (m) => `${KEYS[m % 12]}${Math.floor(m / 12) - 1}`;
366const pc = (n) => ((n % 12) + 12) % 12;
367// the shift (semitones) of custom notes c in key `key`: the nearer way from c.ref
368const shiftOf = (c, key) => { const d = pc(key - c.ref); return d > 6 ? d - 12 : d; };
369// a track's custom notes as they sound (in its key)
370const soundingNotes = (t) => { const c = val(t, 'notes'); const d = shiftOf(c, val(t, 'key')); return c.notes.map((n) => n + d); };
371const isCustom = (t) => val(t, 'scale') === CUSTOM;
373// the pitch (Hz) a track plays at u in [0, 1] (the left to right edge of the
374// view), or null (custom notes, but none yet): custom notes spread evenly
375// over the view (or as a scale), or the scale's notes
376function pitchFor(t, u) {
377 const key = val(t, 'key');
378 if (!isCustom(t)) return pitchOf(u, SCALES[val(t, 'scale')], key);
379 const c = val(t, 'notes');
380 if (!c.notes.length) return null;
381 if (c.every) return pitchOf(u, { steps: [...new Set(c.notes.map((n) => pc(n - c.ref)))] }, key);
382 const ns = soundingNotes(t);
383 return midiHz(ns[Math.round(Math.min(1, Math.max(0, u)) * (ns.length - 1))]);
384}
386// MIDI velocity for SoundFont notes: the track's, jittered a little so
387// neighbouring velocity layers (or variations) alternate
388function velocity(t) {
389 const v = val(t, 'velocity') + Math.round((Math.random() * 2 - 1) * 6);
390 return Math.max(1, Math.min(127, v));
391}
393// One tick at time `time` (lasting dt) for tracks ts: each playhead advances
394// one drive period (together if coupled), keeping the path for the trail,
395// and plucks its notes (steady: one at the section point; natural: at each
396// upward x' = 0; both: at each x' = 0), at level gain.
397function beat(ts, time, dt, together, gain) {
398 const before = ts.map((t) => ({ ...t.ph.s }));
399 const paths = ts.map(() => new Float32Array(2 * (stepper.N + 1)));
400 if (together) stepper.stepMany(ts.map((t) => t.ph.s), coupling, paths);
401 else ts.forEach((t, k) => stepper.step(t.ph.s, paths[k]));
402 for (const [k, t] of ts.entries()) {
403 t.ph.until = time + dt;
404 if (before[k].escaped) continue;
405 const { x, v } = before[k];
406 const rhythm = val(t, 'rhythm');
407 // (at crossings: none in the period it escapes, whose path ends at rest)
408 const notes = rhythm === 'steady' ? [{ t: time, x, v }]
409 : t.ph.s.escaped ? [] : crossings(paths[k], time, dt, rhythm === 'both');
410 t.ph.queue.push({ time, dt, path: paths[k], last: t.ph.s.escaped, notes });
411 if (soundOn && synth) {
412 const voice = voiceOf(t);
413 for (const n of notes) {
414 const u = (n.x / view.xr + 1) / 2;
415 const freq = pitchFor(t, u);
416 if (freq == null) continue;
417 synth.play(t.id, voice, freq, n.t, {
418 pan: Math.max(-1, Math.min(1, 1.4 * u - 0.7)), gain, sustain: val(t, 'sustain'), vel: velocity(t),
419 });
421 }
422 }
425// Run tracks ts (one, or a coupled set, sharing the tempo multiple) over
426// their ticks due within LOOKAHEAD. Ticks fall on a grid aligned to beat 0,
427// tickBeats apart; a track starting (or fallen behind: a stalled frame, a
428// hidden tab, a pause) picks up at the next tick after now, rather than
429// playing the missed ones in a burst.
430function runTicks(ts, now, gain) {
431 const lead = ts[0];
432 const step = tickBeats(lead);
433 const dt = tickDt(lead);
434 const until = Math.max(...ts.map((t) => t.ph.until));
435 if (lead.tick == null || timeAt(lead.tick * step) < now) {
436 lead.tick = Math.ceil(beatAt(Math.max(now + 0.02, until)) / step - 1e-6);
437 }
438 let k = lead.tick;
439 for (let time = timeAt(k * step); time < now + LOOKAHEAD; time = timeAt(++k * step)) {
440 // (after a tempo change, the ticks already played wait out)
441 if (time < until - 1e-6) continue;
442 beat(ts, time, dt, ts.length > 1, gain);
443 }
444 for (const t of ts) t.tick = k;
445}
447// schedule the ticks due within LOOKAHEAD, softer the more tracks play
448function schedule() {
449 const now = clock();
450 const playing = tracks.filter((t) => t.playing && t.ph);
451 const gain = 1 / Math.sqrt(Math.max(1, playing.length));
452 for (const g of groups) runTicks(g, now, gain);
453 for (const t of playing) if (!groupOf(t)) runTicks([t], now, gain);
454 for (const t of tracks) {
455 if (!t.ph) continue;
456 const dt = tickDt(t);
457 const keep = Math.max((TAIL + 1) * dt, ringTime(dt) + dt);
458 const q = t.ph.queue;
459 while (q.length > 1 && q[1].time < now - keep) q.shift();
461}
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 463// a new global tempo: the beat carries on from now
464function setTempo(bpm) {
465 const now = clock();
466 anchor = { time: now, beat: beatAt(now) };
467 tempo = bpm;
468}
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 470function setSound(on) {
471 soundOn = on;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 473 if (on && !synth) {
474 // the clock switches to the audio context's
475 synth = createSynth();
477 anchor = { time: clock(), beat: 0 };
478 for (const t of tracks) {
479 t.tick = null;
480 if (t.ph) { t.ph.queue = []; t.ph.until = 0; }
481 }
483 if (synth) {
484 synth.ctx.resume();
485 synth.setVolume(on ? Number($('volume').value) : 0);
486 }
487}
489// ---- drawing -----------------------------------------------------------------
491function readTheme() {
492 const cs = getComputedStyle(document.documentElement);
493 theme = {
494 bg: cs.getPropertyValue('--bg').trim(),
495 fg: cs.getPropertyValue('--fg').trim(),
496 muted: cs.getPropertyValue('--muted').trim(),
497 line: cs.getPropertyValue('--line').trim(),
498 accent: cs.getPropertyValue('--accent').trim(),
499 light: cs.getPropertyValue('--dot-light').trim(),
500 };
501}
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 503const orbitColor = (hue, isTrack, alpha = 1) =>
504 `hsla(${Math.round(hue * 360)}, ${isTrack ? 85 : 50}%, ${theme.light}, ${alpha})`;
506function plotRect() {
507 const dpr = devicePixelRatio || 1;
508 const w = canvas.width / dpr;
509 const h = canvas.height / dpr;
510 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) };
511}
513const toPx = (r, x, v) => [r.x + ((x / view.xr + 1) / 2) * r.w, r.y + ((1 - v / view.vr) / 2) * r.h];
515function drawPoints(o, from) {
516 const r = plotRect();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 517 const dctx = (o.isTrack ? top : dots).getContext('2d');
518 dctx.fillStyle = orbitColor(o.hue, o.isTrack, o.isTrack ? 0.95 : 0.7);
519 const size = o.isTrack ? 2.2 : 1.4;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 520 for (let i = from; i < o.n; i++) {
521 const [px, py] = toPx(r, o.pts[2 * i], o.pts[2 * i + 1]);
522 dctx.fillRect(px - size / 2, py - size / 2, size, size);
523 }
524}
526function clearDots(which = layers) {
527 const dpr = devicePixelRatio || 1;
528 for (const layer of which) {
529 const c = layer.getContext('2d');
530 c.setTransform(1, 0, 0, 1, 0, 0);
531 c.clearRect(0, 0, layer.width, layer.height);
532 c.setTransform(dpr, 0, 0, dpr, 0, 0);
533 }
534}
537function redrawTop() {
538 clearDots([top]);
539 for (const t of tracks) if (t.orbit) drawPoints(t.orbit, 0);
540}
542// the opacity of the fading dots
543const ghostAlpha = () => Math.max(0, 1 - (performance.now() / 1000 - ghostStart) / FADE);
545// start fading out what the given layers show (on top of what is fading already)
546function fadeOut(which) {
547 if (!canvas.width || !canvas.height) return;
548 const c = spare.getContext('2d');
549 c.setTransform(1, 0, 0, 1, 0, 0);
550 c.clearRect(0, 0, spare.width, spare.height);
551 const a = ghostAlpha();
552 if (a > 0) {
553 c.globalAlpha = a;
554 c.drawImage(ghost, 0, 0);
555 c.globalAlpha = 1;
556 }
557 for (const layer of which) c.drawImage(layer, 0, 0);
558 [ghost, spare] = [spare, ghost];
559 ghostStart = performance.now() / 1000;
560}
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 562function resize() {
563 const dpr = devicePixelRatio || 1;
564 const { width, height } = canvas.getBoundingClientRect();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 565 canvas.width = dots.width = top.width = ghost.width = spare.width = Math.round(width * dpr);
566 canvas.height = dots.height = top.height = ghost.height = spare.height = Math.round(height * dpr);
567 ghostStart = -Infinity;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 568 clearDots();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 569 for (const o of seeds) drawPoints(o, 0);
570 redrawTop();
573// advance the orbits within the frame's budget, drawing their new points
574function fill() {
575 const deadline = performance.now() + FRAME_BUDGET;
576 const advance = (o, count) => {
577 const from = o.n;
578 for (let k = 0; k < count && o.n < o.cap && !o.s.escaped; k++) {
579 stepper.step(o.s);
580 if (o.s.escaped) break;
581 if (o.skip > 0) { o.skip--; continue; }
582 o.pts[2 * o.n] = o.s.x;
583 o.pts[2 * o.n + 1] = o.s.v;
584 o.n++;
585 }
586 drawPoints(o, from);
587 };
589 // the coupled tracks together, as their playheads will move
590 const os = g.map((t) => t.orbit);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 592 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 593 stepper.stepMany(os.map((o) => o.s), coupling);
594 for (const o of os) {
595 if (o.s.escaped || o.n >= o.cap) continue;
596 o.pts[2 * o.n] = o.s.x;
597 o.pts[2 * o.n + 1] = o.s.v;
598 o.n++;
599 }
600 }
601 os.forEach((o, k) => drawPoints(o, from[k]));
602 }
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 603 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 604 let busy = true;
605 while (busy && performance.now() < deadline) {
606 busy = false;
608 if (o.n >= o.cap || o.s.escaped) continue;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 609 advance(o, 10);
610 busy = true;
611 }
612 }
613}
615function drawAxes(r) {
616 ctx.strokeStyle = theme.line;
617 ctx.lineWidth = 1;
618 ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1);
619 ctx.beginPath();
620 ctx.moveTo(r.x + r.w / 2, r.y);
621 ctx.lineTo(r.x + r.w / 2, r.y + r.h);
622 ctx.moveTo(r.x, r.y + r.h / 2);
623 ctx.lineTo(r.x + r.w, r.y + r.h / 2);
624 ctx.stroke();
625 ctx.fillStyle = theme.muted;
626 ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif';
627 ctx.textBaseline = 'top';
628 ctx.textAlign = 'left';
629 ctx.fillText(`−${view.xr.toFixed(2)}`, r.x, r.y + r.h + 6);
630 ctx.textAlign = 'right';
631 ctx.fillText(view.xr.toFixed(2), r.x + r.w, r.y + r.h + 6);
632 ctx.textAlign = 'center';
633 ctx.fillText('displacement x', r.x + r.w / 2, r.y + r.h + 6);
634 ctx.save();
635 ctx.translate(r.x - 8, r.y + r.h / 2);
636 ctx.rotate(-Math.PI / 2);
637 ctx.textBaseline = 'bottom';
638 ctx.fillText('velocity ẋ (s⁻¹)', 0, 0);
639 ctx.textAlign = 'right';
640 ctx.fillText(`${Math.round(view.vr)}`, r.h / 2, 0);
641 ctx.textAlign = 'left';
642 ctx.fillText(`−${Math.round(view.vr)}`, -r.h / 2, 0);
643 ctx.restore();
644}
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 646function drawPlayhead(c, r, t) {
647 const { ph, hue } = t;
648 if (!ph?.queue.length) return;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 649 const now = clock();
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 651 const q = ph.queue;
652 let cur = -1;
653 for (let k = 0; k < q.length; k++) if (q[k].time <= now) cur = k;
654 if (cur < 0) return;
656 c.beginPath();
657 c.rect(r.x, r.y, r.w, r.h);
658 c.clip();
659 c.lineWidth = 1.6;
660 c.lineCap = 'round';
661 c.lineJoin = 'round';
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 662 let head = null;
663 for (let k = 0; k <= cur; k++) {
664 const e = q[k];
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 665 // (N, the steps per period, as when the path was computed)
666 const N = e.path.length / 2 - 1;
667 const CHUNK = Math.max(4, Math.ceil(N / 24));
668 const span = e.dt;
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 669 const f = Math.min(1, (now - e.time) / span);
670 const end = Math.floor(f * N);
671 for (let j0 = 0; j0 < end; j0 += CHUNK) {
672 const age = (now - (e.time + (j0 / N) * span)) / dt;
673 const alpha = 1 - age / TAIL;
674 if (alpha <= 0) continue;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 675 c.strokeStyle = orbitColor(hue, true, 0.85 * alpha);
676 c.beginPath();
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 677 for (let j = j0; j <= Math.min(end, j0 + CHUNK); j++) {
678 const [px, py] = toPx(r, e.path[2 * j], e.path[2 * j + 1]);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 679 if (j === j0) c.moveTo(px, py);
680 else c.lineTo(px, py);
684 if (k === cur) {
685 const j = Math.min(N, f * N);
686 const i0 = Math.floor(j);
687 const i1 = Math.min(N, i0 + 1);
688 const w = j - i0;
689 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]);
690 if (e.last) head = null;
691 }
692 // each pluck: a ring growing and fading where it was played
693 for (const n of e.notes) {
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 694 const g = (now - n.t) / ringTime(e.dt);
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 695 if (g < 0 || g >= 1) continue;
696 const [sx, sy] = toPx(r, n.x, n.v);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 697 c.strokeStyle = orbitColor(hue, true);
698 c.globalAlpha = 1 - g;
699 c.lineWidth = 2;
700 c.beginPath();
701 c.arc(sx, sy, 4 + 14 * g, 0, 2 * Math.PI);
702 c.stroke();
703 c.globalAlpha = 1;
705 }
706 if (head) {
708 c.arc(head[0], head[1], 4.5, 0, 2 * Math.PI);
709 if (t.playing) {
710 c.fillStyle = orbitColor(hue, true);
711 c.fill();
712 } else {
713 // paused: a hollow head
714 c.strokeStyle = orbitColor(hue, true);
715 c.lineWidth = 2;
716 c.stroke();
717 }
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 722// the tracks' start rings (a cross if escaped), and their numbers if `labels`
723function drawStarts(c, r, labels) {
724 for (const t of tracks) {
725 if (!t.start) continue;
726 const [px, py] = toPx(r, t.start.x, t.start.v);
727 const sel = t === selected;
728 c.strokeStyle = orbitColor(t.hue, true);
729 c.lineWidth = sel ? 2.5 : 1.5;
730 c.beginPath();
731 if (t.orbit?.s.escaped) {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 732 // escaped: a cross at its start
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 733 c.moveTo(px - 5, py - 5); c.lineTo(px + 5, py + 5);
734 c.moveTo(px + 5, py - 5); c.lineTo(px - 5, py + 5);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 736 c.arc(px, py, sel ? 7 : 5, 0, 2 * Math.PI);
739 if (!labels) continue;
740 // its number, beside the ring
741 c.fillStyle = orbitColor(t.hue, true);
742 c.font = `${sel ? 600 : 400} 12px "Hanken Grotesk", system-ui, sans-serif`;
743 c.textAlign = 'left';
744 c.textBaseline = 'bottom';
745 c.fillText(trackName(t), px + 7, py - 5);
746 }
747}
749// The phase space within plot rect r, on context c (set up so r is in CSS
750// px): the dots (and those fading out), then `under` (the axes, on screen),
751// the start rings (numbered if `labels`) and the playheads.
752function drawScene(c, r, { labels, under }) {
753 const dpr = devicePixelRatio || 1;
754 c.save();
755 c.beginPath();
756 c.rect(r.x, r.y, r.w, r.h);
757 c.clip();
758 c.fillStyle = theme.bg;
759 c.fillRect(r.x, r.y, r.w, r.h);
760 const w = canvas.width / dpr;
761 const h = canvas.height / dpr;
762 const a = ghostAlpha();
763 if (a > 0) {
764 c.globalAlpha = a;
765 c.drawImage(ghost, 0, 0, w, h);
766 c.globalAlpha = 1;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 768 c.drawImage(dots, 0, 0, w, h);
769 c.drawImage(top, 0, 0, w, h);
770 c.restore();
771 under?.();
772 drawStarts(c, r, labels);
773 for (const t of tracks) drawPlayhead(c, r, t);
776function frame() {
777 requestAnimationFrame(frame);
778 if (!canvas.width || !canvas.height) return;
780 dirty = false;
781 reset();
782 }
783 syncCoupling();
785 schedule();
787 const esc = !!t.orbit?.s.escaped;
788 if (esc !== t.escaped) { t.escaped = esc; updateTrack(t); }
789 }
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 790 const dpr = devicePixelRatio || 1;
791 const r = plotRect();
792 ctx.setTransform(1, 0, 0, 1, 0, 0);
793 ctx.fillStyle = theme.bg;
794 ctx.fillRect(0, 0, canvas.width, canvas.height);
795 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 796 drawScene(ctx, r, { labels: true, under: () => drawAxes(r) });
797 if (recording) drawRecordingFrame(r);
798}
800// ---- instruments ---------------------------------------------------------------
802// a track's instrument: 'b<i>' (VOICES[i]) or 's<id>:<i>' (preset i of the
803// loaded SoundFont with that id)
804const isSoundFont = (t) => t.instrument[0] === 's';
805const sfId = (font, preset) => `s${font.id}:${preset}`;
807// a SoundFont instrument's { font, preset }, or null
808function fontPreset(id) {
809 const m = /^s(\d+):(\d+)$/.exec(id);
810 const font = m && soundfonts.find((f) => f.id === Number(m[1]));
811 return font && Number(m[2]) < font.sf.presets.length ? { font, preset: Number(m[2]) } : null;
812}
814function voiceOf(t) {
815 if (!isSoundFont(t)) return Number(t.instrument.slice(1));
816 const { font, preset } = fontPreset(t.instrument);
817 if (!font.insts.has(preset)) font.insts.set(preset, makeInstrument(font.sf, preset));
818 return font.insts.get(preset);
819}
821function instrumentName(t) {
822 if (!isSoundFont(t)) return VOICES[Number(t.instrument.slice(1))].name;
823 const { font, preset } = fontPreset(t.instrument);
824 return font.sf.presets[preset].name;
825}
827// the first built-in voice no track is playing
828function freeInstrument() {
829 const i = VOICES.findIndex((_, k) => !tracks.some((t) => t.instrument === `b${k}`));
830 return `b${i < 0 ? 0 : i}`;
831}
833// ---- the tracks panel ------------------------------------------------------------
835const escapeHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
837const svg = (body, attrs = '') => `<svg viewBox="0 0 16 16" aria-hidden="true" ${attrs}>${body}</svg>`;
838const STROKE = 'fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"';
839const ICONS = {
840 play: svg('<path d="M4.5 2.8v10.4l8.5-5.2z" fill="currentColor"/>'),
841 pause: svg('<path d="M4 3h3v10H4zM9 3h3v10H9z" fill="currentColor"/>'),
842 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),
843 remove: svg('<path d="M4 4l8 8M12 4l-8 8"/>', STROKE),
844 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),
845 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),
846 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"'),
847 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),
848 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"'),
849};
851function scaleText(t) {
852 if (isCustom(t)) {
853 const c = val(t, 'notes');
854 if (!c.notes.length) return 'no notes yet';
855 const n = c.every ? new Set(c.notes.map(pc)).size : c.notes.length;
856 return c.every ? `custom, ${n} per octave` : `${n} custom note${n === 1 ? '' : 's'}`;
857 }
858 const s = SCALES[val(t, 'scale')];
859 return `${KEYS[val(t, 'key')]} ${SCALE_SHORT[s.name] ?? s.name}`;
860}
862function summary(t) {
863 if (!t.start) return 'No start yet: click the plot';
864 const r = RHYTHMS.find((q) => q.value === val(t, 'rhythm'));
865 const parts = [scaleText(t), rateLabel(t), r.short];
866 if (t.escaped) parts.push('escaped');
867 return parts.join(' · ');
868}
870const fmtNum = (v) => (v < 0 ? '−' : '') + Math.abs(v);
871const coordsText = (t) => (t.start
872 ? `x = ${fmtNum(+t.start.x.toFixed(3))}, ẋ = ${fmtNum(Math.round(t.start.v))} s⁻¹`
873 : '<em>click the plot to place it</em>');
875function linkButton(t, p) {
876 const on = t.linked[p];
877 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.';
878 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>`;
879}
881function rangeRow(t, p, disabled = false) {
882 const R = RANGES[p];
883 const v = val(t, p);
884 return `<div class="trow${t.linked[p] ? ' linked' : ''}${disabled ? ' na' : ''}"${R.title ? ` title="${R.title}"` : ''}>
885 ${linkButton(t, p)}<span class="lbl">${R.label}</span>
886 <input type="range" data-p="${p}" min="${R.min}" max="${R.max}" step="${R.step}" value="${v}"${disabled ? ' disabled' : ''} aria-label="${R.label}">
887 <output data-out="${p}">${R.fmt(v)}</output>
888 </div>`;
889}
891// the tempo multiple: a menu of the usual ones, or a custom value typed in
892function rateRow(t) {
893 const v = String(val(t, 'rate'));
894 const custom = !RATES.includes(v) || t.customRate;
895 const opts = RATES.map((r) => `<option value="${r}"${!custom && r === v ? ' selected' : ''}>×${r}</option>`).join('');
896 return `<div class="trow rate-row${t.linked.rate ? ' linked' : ''}${custom ? ' custom' : ''}" title="Ticks (drive periods) per beat of the tempo">
897 ${linkButton(t, 'rate')}<span class="lbl">Tempo</span>
898 <select data-rate aria-label="Tempo multiple">${opts}<option value="custom"${custom ? ' selected' : ''}>Custom…</option></select>
899 ${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">` : ''}
900 </div>`;
901}
903function instrumentOptions(t) {
904 const opt = (value, name) => `<option value="${value}"${value === t.instrument ? ' selected' : ''}>${escapeHtml(name)}</option>`;
905 let html = `<optgroup label="Built-in">${VOICES.map((v, i) => opt(`b${i}`, v.name)).join('')}</optgroup>`;
906 for (const f of soundfonts) {
907 const ps = f.sf.presets;
908 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>`;
909 }
910 return html;
911}
913// the custom notes' editor: a piano (the notes as they sound, in the track's
914// key; click a key, or press it on a MIDI keyboard, to add or remove it)
915const BLACK = [1, 3, 6, 8, 10];
916function notesEditor(t) {
917 const c = val(t, 'notes');
918 const sounding = soundingNotes(t);
919 const on = new Set(sounding);
920 const pcs = c.every ? new Set(sounding.map(pc)) : null;
921 // C3 to B5 (or to C6, the top of the scale's range, in every octave),
922 // widened by octaves to take in every note
923 let lo = 48;
924 let hi = c.every ? 84 : 83;
925 if (sounding.length) {
926 lo = Math.min(lo, 12 * Math.floor(sounding[0] / 12));
927 hi = Math.max(hi, 12 * Math.ceil((sounding[sounding.length - 1] + 1) / 12) - 1);
928 }
929 const whites = [];
930 const blacks = [];
931 for (let m = lo; m <= hi; m++) (BLACK.includes(m % 12) ? blacks : whites).push({ m, at: whites.length });
932 const w = whites.length;
933 const key = ({ m, at }, black) => {
934 const lit = on.has(m);
935 const echo = !lit && pcs?.has(m % 12);
936 const cls = `${black ? 'bk' : 'wk'}${lit ? ' on' : ''}${echo ? ' echo' : ''}${midi.down.has(m) ? ' down' : ''}`;
937 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>`;
938 };
939 const listening = midi.listening && t === selected;
940 const names = c.every
941 ? [...new Set(sounding.map(pc))].sort((a, b) => a - b).map((k) => KEYS[k]).join(' ')
942 : sounding.map(noteName).join(' ');
943 let status;
944 if (midi.error) status = `<span class="error">${midi.error}</span>`;
945 else if (listening) {
946 status = midi.inputs.length
947 ? `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.`
948 : 'No MIDI keyboard found: plug one in (it is picked up when you do).';
949 } else status = 'Click keys to add or remove notes, or use a MIDI keyboard.';
950 return `<div class="notes-editor">
951 <div class="piano" style="--w: ${w}">${whites.map((k) => key(k, false)).join('')}${blacks.map((k) => key(k, true)).join('')}</div>
952 <div class="notes-bar">
953 <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>
954 <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>
955 <button class="quiet" data-act="clear-notes"${c.notes.length ? '' : ' disabled'}>Clear</button>
956 </div>
957 <p class="notes-msg">${names ? `<span class="note-names">${names}</span>` : '<em>No notes yet: the track is silent.</em>'}<br>${status}</p>
958 </div>`;
959}
961// redraw the selected track's notes editor (if it is open)
962function refreshNotesEditor() {
963 const el = selected && trackEl(selected)?.querySelector('.notes-editor');
964 if (el) el.outerHTML = notesEditor(selected);
965}
967// add or remove sounding note m from a track's custom notes (every octave:
968// its pitch class); true if added
969function toggleNote(t, m) {
970 let c = val(t, 'notes');
971 if (!c.notes.length) c = { ...c, ref: val(t, 'key') };
972 const n = m - shiftOf(c, val(t, 'key'));
973 const has = c.every ? c.notes.some((q) => pc(q) === pc(n)) : c.notes.includes(n);
974 const notes = has
975 ? c.notes.filter((q) => (c.every ? pc(q) !== pc(n) : q !== n))
976 : [...c.notes, n].sort((a, b) => a - b);
977 setValue(t, 'notes', { ...c, notes });
978 tracks.forEach(updateTrack);
979 return !has;
980}
982// sound a note on a track's instrument now (to hear a key clicked)
983function previewNote(t, m, vel = 100) {
984 if (!soundOn || !synth) return;
985 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 });
986}
988// ---- the MIDI keyboard -------------------------------------------------------------
990// access: once granted; listening: its keys go to the selected track's
991// custom notes; inputs: the devices' names; down: the keys held
992// (held: a set of notes is being played: a key has gone down since all were
993// up, and some key, or the sustain pedal, is still down)
994const midi = { access: null, listening: false, inputs: [], error: '', down: new Set(), pedal: false, held: false };
996// open MIDI (once): '' if open, or why not
997async function openMidiOnce() {
998 if (midi.access) return '';
999 if (!midiSupported()) return 'This browser has no Web MIDI (Chrome, Edge and Firefox do).';
1000 try {
1001 midi.access = await openMidi({
1002 onNote: midiNote,
1003 onPedal: (down) => {
1004 midi.pedal = down;
1005 if (!down && !midi.down.size) midi.held = false;
1006 },
1007 onControl: midiControl,
1008 onInputs: (names) => { midi.inputs = names; refreshNotesEditor(); renderKnobs(); },
1009 });
1010 return '';
1011 } catch {
1012 return 'MIDI access was blocked: allow it for this page in the browser\'s site settings.';
1013 }
1014}
1016async function setListening(on) {
1017 midi.error = '';
1018 midi.listening = false;
1019 if (on) {
1020 const err = await openMidiOnce();
1021 if (err) midi.error = midiSupported() ? err : `${err} You can still click the keys.`;
1022 else midi.listening = true;
1023 }
1024 refreshNotesEditor();
1025}
1027// ---- MIDI knobs ------------------------------------------------------------------
1029// The sliders a knob (a MIDI controller's control change) can be assigned
1030// to: the equation's and the coupling. knobs: { [slider id]: { ch, cc,
1031// mode } }; learning: the slider waiting for a knob to be turned.
1032//
1033// mode: how the knob sends its turns. 'abs': its position, 0 to 127 (only
1034// when it changes); or relative, as endless encoders (the MiniLab's
1035// clickable browse knobs, say) send them: each message a step left or right,
1036// as 64 ± n ('rel64'), 16 ± n ('rel16') or n in two's complement ('rel2c').
1037// Told apart by repeats: a relative knob turned steadily sends the same
1038// value again and again, which an absolute one never does.
1039const KNOB_TARGETS = () => [...SLIDERS.map((sl) => `s-${sl.name}`), 'coupling'];
1040let knobs = {};
1041let knobsShown = false;
1042let learning = null;
1043let knobError = '';
1044let candidate = null; // while learning: { ch, cc, values, timer }, the knob being turned
1045const lastValue = new Map(); // the last value of each control ('ch:cc')
1046const flashTimers = new Map();
1047const MODES = ['abs', 'rel64', 'rel16', 'rel2c'];
1048const isRelative = (k) => k.mode !== 'abs' && k.mode !== 'auto';
1050// the relative mode values (repeats seen) suggest
1051function relativeMode(values) {
1052 if (values.every((v) => v >= 48 && v <= 80)) return 'rel64';
1053 if (values.every((v) => v >= 8 && v <= 24)) return 'rel16';
1054 return 'rel2c';
1055}
1057// a relative knob's message: the steps it turned (negative: to the left)
1058function relativeSteps(mode, v) {
1059 if (mode === 'rel64') return v - 64;
1060 if (mode === 'rel16') return v - 16;
1061 return v < 64 ? v : v - 128;
1062}
1064function readKnobs(o) {
1065 const r = {};
1066 for (const id of KNOB_TARGETS()) {
1067 const k = o?.[id];
1068 if (k && Number.isInteger(k.ch) && k.ch >= 0 && k.ch < 16 && Number.isInteger(k.cc) && k.cc >= 0 && k.cc < 128) {
1069 // (assigned before modes: 'auto', told by its next two values)
1070 r[id] = { ch: k.ch, cc: k.cc, mode: MODES.includes(k.mode) ? k.mode : 'auto' };
1071 }
1072 }
1073 return r;
1074}
1076const knobLabel = (k) => `CC${k.cc}${k.ch ? `/${k.ch + 1}` : ''}${isRelative(k) ? ' ↻' : ''}`;
1078function renderKnobs() {
1079 $('knobs').setAttribute('aria-pressed', knobsShown);
1080 document.querySelector('.eqn-panel').classList.toggle('knobs-on', knobsShown);
1081 for (const id of KNOB_TARGETS()) {
1082 const row = $(id).closest('.row');
1083 let chip = row.querySelector('.knob');
1084 if (!chip) {
1085 chip = document.createElement('button');
1086 chip.className = 'knob';
1087 chip.dataset.knob = id;
1088 chip.type = 'button';
1089 row.append(chip);
1090 }
1091 const k = knobs[id];
1092 const name = row.querySelector('span').textContent;
1093 chip.classList.toggle('learning', learning === id);
1094 chip.classList.toggle('set', !!k);
1095 chip.textContent = learning === id ? 'turn…' : k ? knobLabel(k) : '+';
1096 chip.title = learning === id ? 'Turn a knob to assign it (click to cancel)'
1097 : k ? `${knobLabel(k)} (${isRelative(k) ? 'relative' : 'absolute'}) controls ${name}: click to change or unassign it`
1098 : `Assign a knob to ${name}`;
1099 }
1100 const msg = $('knob-msg');
1101 msg.hidden = !knobsShown;
1102 msg.classList.toggle('error', !!knobError);
1103 const none = midi.access && !midi.inputs.length ? ' No MIDI device found: plug one in.' : '';
1104 if (knobError) msg.textContent = knobError;
1105 else if (learning) {
1106 const k = knobs[learning];
1107 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>` : '';
1108 msg.innerHTML = `Turn a knob on your controller to assign it.${none}${kind}`;
1109 } else msg.textContent = `Click a slider's + (or its knob's label), then turn a knob to assign it.${none}`;
1110}
1112async function learnKnob(id) {
1113 knobError = '';
1114 if (candidate) clearTimeout(candidate.timer);
1115 candidate = null;
1116 learning = learning === id ? null : id;
1117 if (learning) knobError = await openMidiOnce();
1118 if (knobError) learning = null;
1119 renderKnobs();
1120}
1122// the knob turned while learning: assigned once it has sent a few values
1123// (or paused), as relative if any repeated
1124function assignCandidate() {
1125 const { ch, cc, values, timer } = candidate;
1126 clearTimeout(timer);
1127 candidate = null;
1128 if (!learning) return;
1129 for (const [id, k] of Object.entries(knobs)) if (k.ch === ch && k.cc === cc) delete knobs[id];
1130 const repeats = values.some((v, i) => i && v === values[i - 1]);
1131 knobs[learning] = { ch, cc, mode: repeats ? relativeMode(values) : 'abs' };
1132 learning = null;
1133 saveKnobs(knobs);
1134 renderKnobs();
1135}
1137// a knob turned (or another control change)
1138function midiControl(ch, cc, value) {
1139 const key = `${ch}:${cc}`;
1140 const seen = lastValue.has(key);
1141 const repeat = lastValue.get(key) === value;
1142 lastValue.set(key, value);
1143 if (learning) {
1144 if (candidate && (candidate.ch !== ch || candidate.cc !== cc)) return;
1145 candidate ??= { ch, cc, values: [], timer: setTimeout(assignCandidate, 400) };
1146 candidate.values.push(value);
1147 if (candidate.values.length >= 5) assignCandidate();
1148 return;
1149 }
1150 for (const [id, k] of Object.entries(knobs)) {
1151 if (k.ch !== ch || k.cc !== cc) continue;
1152 // an absolute knob repeating itself is a relative one after all
1153 if (repeat && !isRelative(k)) {
1154 k.mode = relativeMode([value]);
1155 saveKnobs(knobs);
1156 renderKnobs();
1157 } else if (k.mode === 'auto') {
1158 // (not known yet: wait for a second value)
1159 if (!seen) continue;
1160 k.mode = 'abs';
1161 saveKnobs(knobs);
1162 }
1163 const input = $(id);
1164 const lo = Number(input.min);
1165 const hi = Number(input.max);
1166 // absolute: the slider's range, 0 to 127; relative: steps of a 256th of
1167 // it (at least the slider's step), more as the knob turns faster;
1168 // snapped to the slider's step by the input
1169 const v = isRelative(k)
1170 ? Number(input.value) + relativeSteps(k.mode, value) * Math.max(Number(input.step) || 0, (hi - lo) / 256)
1171 : lo + ((hi - lo) * value) / 127;
1172 const before = input.value;
1173 input.value = v;
1174 if (input.value === before) continue;
1175 input.dispatchEvent(new Event('input', { bubbles: true }));
1176 // (the row lights up a moment)
1177 const row = input.closest('.row');
1178 row.classList.add('turned');
1179 clearTimeout(flashTimers.get(id));
1180 flashTimers.set(id, setTimeout(() => row.classList.remove('turned'), 250));
1181 }
1182}
1184function buildKnobControls() {
1185 knobs = readKnobs(loadKnobs());
1186 $('knobs').addEventListener('click', () => {
1187 knobsShown = !knobsShown;
1188 if (!knobsShown) learning = null;
1189 knobError = '';
1190 renderKnobs();
1191 });
1192 document.querySelector('.eqn-panel').addEventListener('click', (e) => {
1193 if (e.target.closest('[data-mode]') && learning && knobs[learning]) {
1194 const k = knobs[learning];
1195 k.mode = isRelative(k) ? 'abs' : relativeMode([lastValue.get(`${k.ch}:${k.cc}`) ?? 64]);
1196 saveKnobs(knobs);
1197 renderKnobs();
1198 return;
1199 }
1200 if (e.target.closest('[data-unassign]') && learning) {
1201 delete knobs[learning];
1202 learning = null;
1203 saveKnobs(knobs);
1204 renderKnobs();
1205 return;
1206 }
1207 const chip = e.target.closest('.knob');
1208 if (!chip) return;
1209 e.preventDefault();
1210 learnKnob(chip.dataset.knob);
1211 });
1212 renderKnobs();
1213 // knobs assigned before: listen for them (MIDI access, if granted before,
1214 // is given without asking)
1215 if (Object.keys(knobs).length && midiSupported()) openMidiOnce();
1216}
1218// A key pressed on the MIDI keyboard: the keys pressed together (from the
1219// first one down until all are up, and the sustain pedal too) become the
1220// notes; the next press after that starts afresh.
1221function midiNote(m, on) {
1222 const fresh = on && !midi.held;
1223 if (on) {
1224 midi.down.add(m);
1225 midi.held = true;
1226 } else {
1227 midi.down.delete(m);
1228 if (!midi.down.size && !midi.pedal) midi.held = false;
1229 }
1230 const t = selected;
1231 // (not sounded: the keyboard makes its own sound, if any)
1232 if (midi.listening && t && isCustom(t) && on) addNote(t, m, fresh);
1233 refreshNotesEditor();
1234}
1236// add sounding note m to a track's custom notes, or (fresh) make it the only one
1237function addNote(t, m, fresh) {
1238 let c = val(t, 'notes');
1239 if (fresh || !c.notes.length) c = { ...c, notes: [], ref: val(t, 'key') };
1240 const n = m - shiftOf(c, val(t, 'key'));
1241 if (!c.notes.includes(n)) setValue(t, 'notes', { ...c, notes: [...c.notes, n].sort((a, b) => a - b) });
1242 else setValue(t, 'notes', c);
1243 tracks.forEach(updateTrack);
1244}
1246function trackBody(t) {
1247 const sf = isSoundFont(t);
1248 const lk = (p) => (t.linked[p] ? ' linked' : '');
1249 return `<div class="track-body">
1250 <div class="trow start-row">
1251 <span></span><span class="lbl">Start</span>
1252 <span class="coords">${coordsText(t)}</span>
1253 </div>
1254 <div class="trow">
1255 <span></span><span class="lbl">Instrument</span>
1256 <select data-instrument aria-label="Instrument">${instrumentOptions(t)}</select>
1257 </div>
1258 <div class="trow${lk('rhythm')}">
1259 ${linkButton(t, 'rhythm')}<span class="lbl">Rhythm</span>
1260 <select data-p="rhythm" aria-label="Rhythm">${RHYTHMS.map((r) => `<option value="${r.value}"${r.value === val(t, 'rhythm') ? ' selected' : ''}>${r.name}</option>`).join('')}</select>
1261 </div>
1262 <div class="trow${lk('scale')}">
1263 ${linkButton(t, 'scale')}<span class="lbl">Scale</span>
1264 <select data-p="scale" aria-label="Scale">${SCALES.map((s, i) => `<option value="${i}"${i === val(t, 'scale') ? ' selected' : ''}>${s.name}</option>`).join('')}<option value="${CUSTOM}"${isCustom(t) ? ' selected' : ''}>Custom notes…</option></select>
1265 </div>
1266 ${isCustom(t) ? notesEditor(t) : ''}
1267 <div class="trow${lk('key')}">
1268 ${linkButton(t, 'key')}<span class="lbl">Key</span>
1269 <div class="keys" role="group" aria-label="Key">${KEYS.map((k, i) => `<button data-key="${i}" aria-pressed="${i === val(t, 'key')}">${k}</button>`).join('')}</div>
1270 </div>
1271 ${rateRow(t)}
1272 ${rangeRow(t, 'sustain', sf)}
1273 ${rangeRow(t, 'volume')}
1274 ${rangeRow(t, 'velocity', !sf)}
1275 <p class="link-note">${ICONS.link} linked settings are shared by every track that links them</p>
1276 </div>`;
1277}
1279function trackItem(t) {
1280 const sel = t === selected;
1281 return `<li class="track${sel ? ' selected' : ''}" data-id="${t.id}" style="--h: ${Math.round(t.hue * 360)}">
1282 <div class="track-head" data-act="select" aria-expanded="${sel}">
1283 <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>
1284 <div class="track-title">
1285 <span class="track-name"><span class="num">${trackName(t)}</span>${escapeHtml(instrumentName(t))}</span>
1286 <span class="summary">${summary(t)}</span>
1287 </div>
1288 <button class="icon-btn" data-act="restart" ${t.start ? '' : 'disabled'} aria-label="Restart track ${trackName(t)}" title="Restart from its start">${ICONS.restart}</button>
1289 <button class="icon-btn" data-act="remove" aria-label="Remove track ${trackName(t)}" title="Remove the track">${ICONS.remove}</button>
1290 </div>
1291 ${sel ? trackBody(t) : ''}
1292 </li>`;
1293}
1295function renderTracks() {
1296 $('track-list').innerHTML = tracks.map(trackItem).join('');
1297 renderSoundFonts();
1298 $('add-track').disabled = tracks.length >= MAX_TRACKS;
1299 $('add-track').textContent = tracks.length >= MAX_TRACKS ? `${MAX_TRACKS} tracks at most` : '+ Add track';
1300 renderTransport();
1301 renderHint();
1302}
1304const trackEl = (t) => $('track-list').querySelector(`.track[data-id="${t.id}"]`);
1306// update a track's head (and its body's start) in place
1307function updateTrack(t) {
1308 const el = trackEl(t);
1309 if (!el) return;
1310 el.querySelector('.summary').textContent = summary(t);
1311 const play = el.querySelector('[data-act="play"]');
1312 play.setAttribute('aria-pressed', t.playing);
1313 play.title = t.playing ? 'Pause' : 'Play';
1314 play.setAttribute('aria-label', `${t.playing ? 'Pause' : 'Play'} track ${trackName(t)}`);
1315 play.innerHTML = t.playing ? ICONS.pause : ICONS.play;
1316 const coords = el.querySelector('.coords');
1317 if (coords) coords.innerHTML = coordsText(t);
1318}
1320function renderTransport() {
1321 const placed = tracks.filter((t) => t.start);
1322 $('play-all').disabled = !placed.some((t) => !t.playing);
1323 $('pause-all').disabled = !placed.some((t) => t.playing);
1324 $('restart-all').disabled = !placed.length;
1325}
1327function renderHint() {
1328 const t = selected;
1329 let s;
1330 if (!tracks.length) s = 'Click the plot to add a track';
1331 else if (!t) s = 'Click to add a track · click a start ring to pick its track';
1332 else if (!t.start) s = `Click to place track ${trackName(t)}'s start`;
1333 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' : ''}`;
1334 $('hint').textContent = s;
1335}
1337function renderSoundButton() {
1338 const btn = $('sound');
1339 btn.setAttribute('aria-pressed', soundOn);
1340 btn.innerHTML = `${soundOn ? ICONS.soundOn : ICONS.soundOff}<span>${soundOn ? 'Sound on' : 'Sound off'}</span>`;
1341 btn.title = soundOn ? 'Mute' : 'Turn the sound on';
1342 if (soundOn) btn.classList.remove('nudge');
1343}
1345function setPlaying(t, on) {
1346 if (!t.start || t.playing === on) return;
1347 t.playing = on;
1348 if (on && !t.ph) restart([t]);
1349 updateTrack(t);
1350 renderTransport();
1351 // playing, but muted: point at the sound button
1352 if (on && !soundOn) {
1353 const btn = $('sound');
1354 btn.classList.remove('nudge');
1355 void btn.offsetWidth;
1356 btn.classList.add('nudge');
1357 }
1358}
1360function buildTrackControls() {
1361 const list = $('track-list');
1362 const trackOf = (el) => {
1363 const li = el.closest('.track');
1364 return li && tracks.find((t) => String(t.id) === li.dataset.id);
1365 };
1366 list.addEventListener('click', (e) => {
1367 const t = trackOf(e.target);
1368 if (!t) return;
1369 const act = e.target.closest('[data-act]');
1370 const noteBtn = e.target.closest('button[data-note]');
1371 if (noteBtn) {
1372 const m = Number(noteBtn.dataset.note);
1373 if (toggleNote(t, m)) previewNote(t, m);
1374 refreshNotesEditor();
1375 return;
1376 }
1377 const keyBtn = e.target.closest('button[data-key]');
1378 if (keyBtn) {
1379 setValue(t, 'key', Number(keyBtn.dataset.key));
1380 for (const b of keyBtn.parentElement.children) b.setAttribute('aria-pressed', b === keyBtn);
1381 tracks.forEach(updateTrack);
1382 refreshNotesEditor();
1383 return;
1384 }
1385 if (!act) return;
1386 switch (act.dataset.act) {
1387 case 'play': setPlaying(t, !t.playing); break;
1388 case 'restart': restartTrack(t); break;
1389 case 'remove': removeTrack(t); break;
1390 case 'midi': setListening(!midi.listening); break;
1391 case 'clear-notes':
1392 setValue(t, 'notes', { ...val(t, 'notes'), notes: [] });
1393 tracks.forEach(updateTrack);
1394 refreshNotesEditor();
1395 break;
1396 case 'link':
1397 setLinked(t, act.dataset.p, !t.linked[act.dataset.p]);
1398 renderTracks();
1399 break;
1400 case 'select':
1401 selected = selected === t ? null : t;
1402 renderTracks();
1403 break;
1404 default:
1405 }
1406 });
1407 list.addEventListener('input', (e) => {
1408 if (e.target.matches('input[data-rate-custom]')) {
1409 e.target.classList.toggle('invalid', Number.isNaN(parseRate(e.target.value.replace(/\s+/g, ''))));
1410 return;
1411 }
1412 const t = trackOf(e.target);
1413 const p = e.target.dataset?.p;
1414 if (!t || !RANGES[p]) return;
1415 const v = Number(e.target.value);
1416 setValue(t, p, v);
1417 e.target.closest('.trow').querySelector('output').textContent = RANGES[p].fmt(v);
1418 tracks.forEach(updateTrack);
1419 });
1420 list.addEventListener('change', (e) => {
1421 const t = trackOf(e.target);
1422 if (!t) return;
1423 if (e.target.matches('select[data-instrument]')) {
1424 t.instrument = e.target.value;
1425 renderTracks();
1426 } else if (e.target.matches('select[data-rate]')) {
1427 if (e.target.value === 'custom') {
1428 t.customRate = true;
1429 renderTracks();
1430 const input = trackEl(t)?.querySelector('[data-rate-custom]');
1431 input?.focus();
1432 input?.select();
1433 } else {
1434 t.customRate = false;
1435 setValue(t, 'rate', e.target.value);
1436 renderTracks();
1437 }
1438 } else if (e.target.matches('input[data-rate-custom]')) {
1439 const text = e.target.value.replace(/\s+/g, '');
1440 const ok = !Number.isNaN(parseRate(text));
1441 e.target.classList.toggle('invalid', !ok);
1442 if (ok) {
1443 setValue(t, 'rate', text);
1444 tracks.forEach(updateTrack);
1445 }
1446 } else if (e.target.matches('select[data-p="rhythm"]')) {
1447 setValue(t, 'rhythm', e.target.value);
1448 tracks.forEach(updateTrack);
1449 } else if (e.target.matches('select[data-p="scale"]')) {
1450 const custom = e.target.value === CUSTOM;
1451 setValue(t, 'scale', custom ? CUSTOM : Number(e.target.value));
1452 renderTracks();
1453 // (the keyboard's keys go to the notes from the start)
1454 if (custom && midiSupported() && !midi.listening) setListening(true);
1455 } else if (e.target.matches('input[data-every]')) {
1456 setValue(t, 'notes', { ...val(t, 'notes'), every: e.target.checked });
1457 tracks.forEach(updateTrack);
1458 refreshNotesEditor();
1459 }
1460 });
1461 $('add-track').addEventListener('click', addTrack);
1462 $('play-all').addEventListener('click', () => tracks.forEach((t) => setPlaying(t, true)));
1463 $('pause-all').addEventListener('click', () => tracks.forEach((t) => setPlaying(t, false)));
1464 $('restart-all').addEventListener('click', () => {
1465 restart(tracks);
1466 for (const g of groups) reseed(g);
1467 });
1468}
1470// ---- the plot: picking and dragging starts ------------------------------------
1472function buildPlotControls() {
1473 let drag = null; // { t, px, py, moved }
1474 const at = (e) => {
1475 const rect = canvas.getBoundingClientRect();
1476 const r = plotRect();
1477 const px = e.clientX - rect.left;
1478 const py = e.clientY - rect.top;
1479 const inside = px >= r.x && px <= r.x + r.w && py >= r.y && py <= r.y + r.h;
1480 const cx = Math.min(r.x + r.w, Math.max(r.x, px));
1481 const cy = Math.min(r.y + r.h, Math.max(r.y, py));
1482 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 };
1483 };
1484 canvas.addEventListener('pointerdown', (e) => {
1485 const p = at(e);
1486 if (!p.inside) return;
1487 // on a start ring: pick that track (and drag it, past a few px)
1488 const hit = !e.shiftKey && tracks.find((t) => {
1489 if (!t.start) return false;
1490 const [cx, cy] = toPx(p.r, t.start.x, t.start.v);
1491 return Math.hypot(cx - p.px, cy - p.py) <= HIT_RADIUS;
1492 });
1493 canvas.setPointerCapture(e.pointerId);
1494 if (hit) {
1495 if (selected !== hit) { selected = hit; renderTracks(); }
1496 drag = { t: hit, px: p.px, py: p.py, moved: false };
1497 return;
1498 }
1499 // elsewhere: move the selected track's start (shift, or none selected:
1500 // a new track's)
1501 let t = selected;
1502 if (e.shiftKey || !t) t = addTrack();
1503 if (!t) return;
1504 setStart(t, p.x, p.v);
1505 drag = { t, moved: true };
1506 });
1507 canvas.addEventListener('pointermove', (e) => {
1508 if (!drag) return;
1509 const p = at(e);
1510 if (!drag.moved && Math.hypot(p.px - drag.px, p.py - drag.py) < DRAG_START) return;
1511 drag.moved = true;
1512 setStart(drag.t, p.x, p.v);
1513 });
1514 const end = () => { drag = null; };
1515 canvas.addEventListener('pointerup', end);
1516 canvas.addEventListener('pointercancel', end);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1519// ---- the equation panel ----------------------------------------------------------
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1521function buildEquationControls() {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 1522 const presetSel = $('preset');
1523 presetSel.innerHTML = PRESETS.map((pr, i) => `<option value="${i}">${pr.name}</option>`).join('')
1524 + '<option value="custom" hidden>Custom</option>';
1526 $('sliders').innerHTML = SLIDERS.map((s) => `
1527 <label class="row">
1528 <span>${s.label}</span>
1529 <input type="range" id="s-${s.name}" min="${s.min}" max="${s.max}" step="${s.step}">
1530 <output id="o-${s.name}"></output>
1531 </label>`).join('');
1533 for (const s of SLIDERS) {
1534 $(`s-${s.name}`).addEventListener('input', (e) => {
1535 params[s.name] = Number(e.target.value) * (s.scale ?? 1);
1536 $(`o-${s.name}`).textContent = s.fmt(Number(e.target.value));
1537 presetSel.value = 'custom';
1540 }
1541 presetSel.addEventListener('change', () => {
1542 if (presetSel.value === 'custom') return;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1543 // the tracks carry on from where they are under the new parameters
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 1544 params = { ...PRESETS[presetSel.value].params };
1546 dirty = true;
1550 // coupling: off, then 1 to about 3000 s^-1 on a log scale (the coupled
1551 // tracks' dots are recomputed, in syncCoupling)
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1553 cpl.addEventListener('input', () => setCoupling(Number(cpl.value)));
1554 setCoupling(Number(cpl.value));
1555}
1557function showParams() {
1558 for (const s of SLIDERS) {
1559 const v = params[s.name] / (s.scale ?? 1);
1560 $(`s-${s.name}`).value = v;
1561 $(`o-${s.name}`).textContent = s.fmt(Number($(`s-${s.name}`).value));
1562 }
1563}
1565// u: the coupling slider, 0 (off), then 1 to about 3000 s^-1 on a log scale
1566function setCoupling(u) {
1567 $('coupling').value = u;
1568 coupling = u ? 10 ** (u / 20) : 0;
1569 $('coupling').nextElementSibling.textContent = coupling ? `${Math.round(coupling)} s⁻¹` : 'off';
1570}
1572function buildMasterControls() {
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 1573 const vol = $('volume');
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1574 vol.addEventListener('input', () => setMasterVolume(Number(vol.value)));
1575 setMasterVolume(Number(vol.value));
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 1576 $('sound').addEventListener('click', () => setSound(!soundOn));
1578 Object.assign(tem, { min: TEMPO.min, max: TEMPO.max, step: 1, value: tempo });
1579 tem.addEventListener('input', () => {
1580 setTempo(Number(tem.value));
1581 showTempo();
1582 });
1583 showTempo();
1584 renderSoundButton();
1585}
1587const showTempo = () => {
1588 $('tempo').value = tempo;
1589 $('tempo').nextElementSibling.textContent = `${tempo} bpm`;
1590};
1592function setMasterVolume(v) {
1593 const vol = $('volume');
1594 vol.value = v;
1595 vol.nextElementSibling.textContent = `${Math.round(100 * v)}%`;
1596 if (synth && soundOn) synth.setVolume(v);
1597}
1599// ---- uploaded SoundFont -------------------------------------------------------
1601// add a .sf2 file's bytes (ArrayBuffer): its presets join the instruments.
1602// A file of the same name as one loaded replaces it (its tracks keep their
1603// presets, found by name). save: remember it in this browser; assign: the
1604// open track takes its first preset. Returns the font, or null if unreadable.
1605function addSoundFont(fileName, bytes, { save = true, assign = save } = {}) {
1606 let sf;
1607 try {
1608 sf = parseSF2(bytes);
1609 } catch (err) {
1610 sfMessage(`Can't read ${fileName}: ${err.message}`, true);
1611 return null;
1612 }
1613 const old = soundfonts.find((f) => f.fileName === fileName);
1614 const font = { id: old?.id ?? nextFontId++, fileName, bytes, sf, insts: new Map() };
1615 if (old) {
1616 // the tracks on it: their presets by name in the new file
1617 const names = new Map(tracks.filter((t) => fontPreset(t.instrument)?.font === old)
1618 .map((t) => [t, old.sf.presets[fontPreset(t.instrument).preset].name]));
1619 soundfonts[soundfonts.indexOf(old)] = font;
1620 for (const [t, name] of names) {
1621 const k = sf.presets.findIndex((p) => p.name === name);
1622 t.instrument = k >= 0 ? sfId(font, k) : freeInstrument();
1623 }
1624 } else {
1625 soundfonts.push(font);
1626 }
1627 if (save) saveSoundFont({ fileName, bytes });
1628 if (assign && selected) selected.instrument = sfId(font, 0);
1629 sfMessage('');
1630 renderSoundFonts();
1631 renderTracks();
1632 return font;
1633}
1635function removeSoundFont(font) {
1636 soundfonts = soundfonts.filter((f) => f !== font);
1637 forgetSoundFont(font.fileName);
1638 for (const t of tracks) if (isSoundFont(t) && !fontPreset(t.instrument)) t.instrument = freeInstrument();
1639 renderSoundFonts();
1640 renderTracks();
1641}
1643const sfMessage = (text, error = false) => {
1644 $('sf-msg').textContent = text;
1645 $('sf-msg').classList.toggle('error', error);
1646};
1648function renderSoundFonts() {
1649 $('sf-list').innerHTML = soundfonts.map((f) => {
1650 const n = f.sf.presets.length;
1651 const used = tracks.filter((t) => fontPreset(t.instrument)?.font === f).map(trackName);
1652 return `<li>
1653 <span class="sf-name" title="${escapeHtml(f.fileName)}">${escapeHtml(f.fileName)}</span>
1654 <span class="sf-info">${n} preset${n === 1 ? '' : 's'}${used.length ? ` · track${used.length > 1 ? 's' : ''} ${used.join(', ')}` : ''}</span>
1655 <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>
1656 </li>`;
1657 }).join('');
1658 $('sf-empty').hidden = soundfonts.length > 0;
1659}
1661function buildSoundFontControls() {
1662 $('sf-load').addEventListener('click', () => $('sf-file').click());
1663 $('sf-file').addEventListener('change', async () => {
1664 const files = [...$('sf-file').files];
1665 $('sf-file').value = '';
1666 // (the open track takes the first one's first preset)
1667 let assign = true;
1668 for (const file of files) {
1669 if (addSoundFont(file.name, await file.arrayBuffer(), { assign })) assign = false;
1670 }
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1672 $('sf-list').addEventListener('click', (e) => {
1673 const btn = e.target.closest('button[data-font]');
1674 const font = btn && soundfonts.find((f) => String(f.id) === btn.dataset.font);
1675 if (font) removeSoundFont(font);
1678}
1680// ---- saving the state ------------------------------------------------------------
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1682const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
1683const finite = (v) => typeof v === 'number' && Number.isFinite(v);
1685// everything to save: the equation, the global settings and the tracks (each
1686// with where its playhead is), but not whether the sound is on
1687function captureState() {
1688 return {
1689 format: FORMAT,
1690 version: 1,
1691 preset: $('preset').value,
1692 params: { ...params },
1693 coupling: Number($('coupling').value),
1694 tempo,
1695 volume: Number($('volume').value),
1696 shared: { ...shared },
1697 hueCounter,
1698 selected: tracks.indexOf(selected),
1699 tracks: tracks.map((t) => ({
1700 hue: t.hue,
1701 instrument: isSoundFont(t) ? 's' : t.instrument,
1702 ...(isSoundFont(t) ? { soundfont: fontPreset(t.instrument).font.fileName, preset: fontPreset(t.instrument).preset } : {}),
1703 instrumentName: instrumentName(t),
1704 start: t.start,
1705 at: t.ph ? { x: t.ph.s.x, v: t.ph.s.v, escaped: t.ph.s.escaped } : null,
1706 playing: t.playing,
1707 own: { ...t.own },
1708 linked: { ...t.linked },
1709 customRate: !!t.customRate,
1710 })),
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1714// a track's settings from saved ones, each checked (or the default's)
1715function readSettings(o, base) {
1716 const r = { ...base };
1717 if (!o || typeof o !== 'object') return r;
1718 if (RHYTHMS.some((q) => q.value === o.rhythm)) r.rhythm = o.rhythm;
1719 if ((Number.isInteger(o.scale) && SCALES[o.scale]) || o.scale === CUSTOM) r.scale = o.scale;
1720 const c = o.notes;
1721 if (c && typeof c === 'object' && Array.isArray(c.notes)) {
1722 r.notes = {
1723 notes: [...new Set(c.notes.filter((n) => Number.isInteger(n) && n >= 0 && n <= 127))].sort((a, b) => a - b),
1724 ref: Number.isInteger(c.ref) && c.ref >= 0 && c.ref < 12 ? c.ref : DEFAULT_KEY,
1725 every: !!c.every,
1726 };
1727 }
1728 if (Number.isInteger(o.key) && o.key >= 0 && o.key < KEYS.length) r.key = o.key;
1729 if (o.rate != null && !Number.isNaN(parseRate(o.rate))) r.rate = String(o.rate);
1730 for (const p of ['sustain', 'volume', 'velocity']) if (finite(o[p])) r[p] = clamp(o[p], RANGES[p].min, RANGES[p].max);
1731 return r;
1732}
1734// a saved track's instrument, if there is such a one: a built-in voice, or a
1735// SoundFont preset, in the file of that name by its number if the name
1736// matches, or else by name (in that file, then in any loaded)
1737function readInstrument(s) {
1738 const b = /^b(\d+)$/.exec(String(s.instrument));
1739 if (b) return Number(b[1]) < VOICES.length ? s.instrument : null;
1740 // (saved when only one SoundFont could be loaded: 's<preset>')
1741 const old = /^s(\d+)$/.exec(String(s.instrument));
1742 const font = soundfonts.find((f) => f.fileName === s.soundfont) ?? (old ? soundfonts[0] : null);
1743 const i = old ? Number(old[1]) : s.preset;
1744 const name = s.instrumentName;
1745 if (font) {
1746 const ps = font.sf.presets;
1747 if (Number.isInteger(i) && i >= 0 && i < ps.length && (name == null || ps[i].name === name)) return sfId(font, i);
1748 const k = ps.findIndex((p) => p.name === name);
1749 if (k >= 0) return sfId(font, k);
1750 }
1751 for (const f of soundfonts) {
1752 const k = f.sf.presets.findIndex((p) => p.name === name);
1753 if (k >= 0) return sfId(f, k);
1754 }
1755 return null;
1756}
1758const readPoint = (p) => (p && finite(p.x) && finite(p.v) ? { x: p.x, v: p.v } : null);
1760// replace everything with a saved state ({} for the defaults); the tracks
1761// carry on from where their playheads were
1762function applyState(st) {
1763 st = st && typeof st === 'object' ? st : {};
1764 params = { ...PRESETS[0].params };
1765 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));
1766 const presets = [...$('preset').options].map((o) => o.value);
1767 $('preset').value = presets.includes(String(st.preset)) ? String(st.preset) : st.params ? 'custom' : '0';
1768 showParams();
1769 setCoupling(finite(st.coupling) ? Math.round(clamp(st.coupling, 0, 70)) : 0);
1770 setTempo(finite(st.tempo) ? Math.round(clamp(st.tempo, TEMPO.min, TEMPO.max)) : TEMPO.default);
1771 showTempo();
1772 setMasterVolume(finite(st.volume) ? clamp(st.volume, 0, 1) : 0.6);
1773 shared = readSettings(st.shared, DEFAULTS);
1775 for (const t of tracks) synth?.removeTrack(t.id);
1776 tracks = [];
1777 hueCounter = 0;
1778 for (const s of (Array.isArray(st.tracks) ? st.tracks : []).slice(0, MAX_TRACKS)) {
1779 if (!s || typeof s !== 'object') continue;
1780 const t = newTrack();
1781 if (finite(s.hue)) t.hue = s.hue;
1782 t.instrument = readInstrument(s) ?? t.instrument;
1783 t.own = readSettings(s.own, DEFAULTS);
1784 for (const p of SETTINGS) if (typeof s.linked?.[p] === 'boolean') t.linked[p] = s.linked[p];
1785 t.customRate = !!s.customRate;
1786 t.start = readPoint(s.start);
1787 if (t.start) {
1788 const at = readPoint(s.at) ?? t.start;
1789 t.ph = newPlayhead(at.x, at.v);
1790 t.ph.s.escaped = !!s.at?.escaped;
1791 t.orbit = newOrbit(t.start.x, t.start.v, TRACK_POINTS, t.hue, true);
1792 t.playing = !!s.playing;
1793 }
1794 tracks.push(t);
1795 }
1796 hueCounter = Math.max(tracks.length, finite(st.hueCounter) ? st.hueCounter : 0);
1797 selected = st.selected === -1 ? null : tracks[st.selected] ?? tracks[0] ?? null;
1798 groups = [];
1799 groupKey = '';
1800 dirty = true; // (reset at the next frame: the dots from where the playheads are)
1801 if (!tracks.length) addTrack();
1802 applyVolumes();
1803 renderTracks();
1804}
1806const sessionMessage = (text, error = false) => {
1807 $('session-msg').textContent = text;
1808 $('session-msg').classList.toggle('error', error);
1809};
1811function autosave() {
1812 if (restored && !saveLocal(captureState())) sessionMessage('Couldn\'t save in this browser (storage is blocked or full).', true);
1813}
1815function exportFile() {
1816 const st = captureState();
1817 st.soundfonts = soundfonts.map((f) => ({ fileName: f.fileName, data: toBase64(f.bytes) }));
1818 const d = new Date();
1819 const pad = (n) => String(n).padStart(2, '0');
1820 const name = `duffing-islands-${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}.json`;
1821 download(JSON.stringify(st, null, 1), name);
1822 const n = soundfonts.length;
1823 sessionMessage(`Saved ${name}${n ? `, with ${n === 1 ? soundfonts[0].fileName : `${n} SoundFonts`}` : ''}.`);
1824}
1826async function importFile(file) {
1827 let st;
1828 try {
1829 st = JSON.parse(await file.text());
1830 } catch {
1831 sessionMessage(`Can't read ${file.name}: not a JSON file.`, true);
1832 return;
1833 }
1834 if (st?.format !== FORMAT) {
1835 sessionMessage(`${file.name} isn't a Duffing Islands file.`, true);
1836 return;
1837 }
1838 // its SoundFonts first, so the tracks can find their instruments
1839 for (const sf of Array.isArray(st.soundfonts) ? st.soundfonts : []) {
1840 if (!sf?.data) continue;
1841 const fileName = String(sf.fileName ?? 'SoundFont.sf2');
1842 let bytes;
1843 try {
1844 bytes = fromBase64(sf.data);
1845 } catch {
1846 sfMessage(`Can't read ${fileName} in ${file.name}.`, true);
1847 continue;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1849 addSoundFont(fileName, bytes, { save: true, assign: false });
1850 }
1851 applyState(st);
1852 autosave();
1853 sessionMessage(`Opened ${file.name}.`);
1854}
1856function buildSessionControls() {
1857 $('export').addEventListener('click', exportFile);
1858 $('import').addEventListener('click', () => $('import-file').click());
1859 $('import-file').addEventListener('change', () => {
1860 const file = $('import-file').files[0];
1861 $('import-file').value = '';
1862 if (file) importFile(file);
1863 });
1864 $('start-over').addEventListener('click', () => {
1865 if (!confirm('Start over with the default settings and one empty track? (Save to a file first to keep this session.)')) return;
1866 forgetLocal();
1867 applyState({});
1868 sessionMessage('Started over.');
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1870 // save as you go, and on leaving
1871 setInterval(autosave, 2000);
1872 addEventListener('pagehide', autosave);
1873 document.addEventListener('visibilitychange', () => { if (document.hidden) autosave(); });
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1876// ---- recording a video ------------------------------------------------------------
1877// The video is the phase space alone (no axes or labels), drawn each frame
1878// onto a canvas of its own at the plot's size when the recording started
1879// (its longer side at most REC_MAX px); the audio is the sound as heard.
1881const REC_MAX = 1920;
1882const REC_FPS = 60;
1883const recCanvas = document.createElement('canvas');
1884const REC_TYPES = [
1885 'video/mp4;codecs=avc1.640028,mp4a.40.2',
1886 'video/mp4;codecs=avc1.4d002a,mp4a.40.2',
1887 'video/mp4',
1888 'video/webm;codecs=vp9,opus',
1889 'video/webm;codecs=vp8,opus',
1890 'video/webm',
1891];
1892const canRecord = () => typeof MediaRecorder !== 'undefined' && !!recCanvas.captureStream;
1894// a frame of the video: the plot rect r of the screen, scaled to the canvas
1895function drawRecordingFrame(r) {
1896 const c = recCanvas.getContext('2d');
1897 const sx = recCanvas.width / r.w;
1898 const sy = recCanvas.height / r.h;
1899 c.setTransform(sx, 0, 0, sy, -r.x * sx, -r.y * sy);
1900 drawScene(c, r, { labels: false });
1901}
1903const fmtTime = (sec) => {
1904 const s = Math.floor(sec);
1905 const h = Math.floor(s / 3600);
1906 const mm = String(Math.floor((s % 3600) / 60)).padStart(h ? 2 : 1, '0');
1907 return `${h ? `${h}:` : ''}${mm}:${String(s % 60).padStart(2, '0')}`;
1908};
1909const fmtSize = (bytes) => (bytes < 1e9 ? `${(bytes / 1e6).toFixed(bytes < 1e7 ? 1 : 0)} MB` : `${(bytes / 1e9).toFixed(2)} GB`);
1911function startRecording() {
1912 if (!canRecord()) return;
1913 // the audio is the sound as heard, so the sound goes on
1914 if (!soundOn) setSound(true);
1915 discardRecording();
1916 const r = plotRect();
1917 const dpr = devicePixelRatio || 1;
1918 const k = Math.min(1, REC_MAX / (Math.max(r.w, r.h) * dpr));
1919 recCanvas.width = 2 * Math.round((r.w * dpr * k) / 2);
1920 recCanvas.height = 2 * Math.round((r.h * dpr * k) / 2);
1921 drawRecordingFrame(r);
1922 const stream = recCanvas.captureStream(REC_FPS);
1923 for (const track of synth.stream().getAudioTracks()) stream.addTrack(track);
1924 const mime = REC_TYPES.find((t) => MediaRecorder.isTypeSupported(t)) ?? '';
1925 let recorder;
1926 try {
1927 recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 8e6, audioBitsPerSecond: 192e3 });
1928 } catch (err) {
1929 recMessage(`Can't record here: ${err.message}`);
1930 return;
1931 }
1932 const chunks = [];
1933 recorder.ondataavailable = (e) => { if (e.data.size) chunks.push(e.data); };
1934 recorder.onstop = () => {
1935 const rec = recording;
1936 recording = null;
1937 for (const track of stream.getVideoTracks()) track.stop();
1938 const type = rec.recorder.mimeType || rec.mime || 'video/webm';
1939 recorded = { blob: new Blob(rec.chunks, { type }), mime: type, seconds: (performance.now() - rec.started) / 1000, saved: false };
1940 renderRecording();
1941 };
1942 recorder.onerror = (e) => recMessage(`Recording failed: ${e.error?.message ?? 'unknown error'}`);
1943 // (in slices, so a long recording is collected as it goes)
1944 recorder.start(1000);
1945 recording = { recorder, chunks, mime, started: performance.now() };
1946 renderRecording();
1947}
1949function stopRecording() {
1950 if (recording?.recorder.state !== 'inactive') recording?.recorder.stop();
1951}
1953function discardRecording() {
1954 recorded = null;
1955 renderRecording();
1956}
1958function saveRecording() {
1959 if (!recorded) return;
1960 const d = new Date();
1961 const pad = (n) => String(n).padStart(2, '0');
1962 const ext = recorded.mime.includes('mp4') ? 'mp4' : 'webm';
1963 downloadBlob(recorded.blob, `duffing-islands-${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}.${ext}`);
1964 recorded.saved = true;
1965}
1967const recMessage = (text) => { $('rec-status').textContent = text; $('rec-status').hidden = !text; };
1969function renderRecording() {
1970 const btn = $('record');
1971 const on = !!recording;
1972 btn.setAttribute('aria-pressed', on);
1973 btn.querySelector('.rec-label').textContent = on ? 'Stop' : 'Record';
1974 btn.title = on ? 'Stop recording' : 'Record a video of the phase space with the sound (the sound goes on)';
1975 $('rec-download').hidden = !recorded;
1976 $('rec-discard').hidden = !recorded;
1977 if (recorded) {
1978 $('rec-download').textContent = `Download video (${fmtTime(recorded.seconds)}, ${fmtSize(recorded.blob.size)})`;
1979 }
1980 updateRecordingTime();
1981}
1983function updateRecordingTime() {
1984 if (!recording) {
1985 recMessage('');
1986 return;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1988 const bytes = recording.chunks.reduce((n, c) => n + c.size, 0);
1989 recMessage(`${fmtTime((performance.now() - recording.started) / 1000)} · ${fmtSize(bytes)}`);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 1992function buildRecordingControls() {
1993 const btn = $('record');
1994 if (!canRecord()) {
1995 btn.disabled = true;
1996 btn.title = 'Recording isn\'t supported in this browser';
1997 return;
1998 }
1999 btn.addEventListener('click', () => (recording ? stopRecording() : startRecording()));
2000 $('rec-download').addEventListener('click', saveRecording);
2001 $('rec-discard').addEventListener('click', () => {
2002 if (recorded && !recorded.saved && !confirm('Discard the recording without downloading it?')) return;
2003 discardRecording();
2004 });
2005 setInterval(() => { if (recording) updateRecordingTime(); }, 500);
2006 // a recording in progress, or not yet downloaded: ask before leaving
2007 addEventListener('beforeunload', (e) => {
2008 if (recording || (recorded && !recorded.saved)) e.preventDefault();
2009 });
2010 renderRecording();
2013readTheme();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2014matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { readTheme(); resize(); });
2015buildEquationControls();
2016buildMasterControls();
2017buildTrackControls();
2018buildPlotControls();
2019buildSoundFontControls();
2020buildSessionControls();
2021buildRecordingControls();
2022buildKnobControls();
2024new ResizeObserver(resize).observe(canvas);
2025resize();
2026requestAnimationFrame(frame);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 2027// the SoundFont and the state saved in this browser (or the defaults: one
2028// track, waiting for its start)
2029loadSaved()
2030 .then((recs) => { for (const rec of Array.isArray(recs) ? recs : []) addSoundFont(rec.fileName, rec.bytes, { save: false }); })
2031 .finally(() => {
2032 applyState(loadLocal() ?? {});
2033 restored = true;
2034 });