Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-2493]): extract shared lookahead-transport for the three synth players

[._.]/ Adam Eivyc0c37a252480
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 025552b414..23175e7e98 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -56,6 +56,8 @@
## Internal
+- **[issue-2493] Extracted a shared lookahead-transport factory for the three synth players.** The two lead-sheet score players (`createScorePlayer`/`createMultiScorePlayer`) and the MIDI preview player (`createMidiPlayer`) carried three near-verbatim copies of the same lookahead-scheduler state machine — the suspended-context resume with its `playToken` teardown-race guard, `stopNodes`/`clearTick` teardown, the `onended`-pruning node tracking, and the `pause`/`stop`/`finish`/`seek`/unclamped-`position` sequences — so a fix to the token-guard race or teardown semantics needed three application sites across two files. That machinery now lives once in `createLookaheadTransport` (`client/src/lib/lookaheadTransport.js`), which owns the clock and node lifecycle; each player supplies only its scheduling + playhead callbacks (`scheduleWindow`, `prepare`, `seekCursors`, `onStop`/`onEnded`/`onTeardown`) and stays a thin scheduler over it. The shared `SYNTH_TIMING` lookahead constants moved there too (single source, no circular import). Behavior is unchanged — all existing `scorePlayback`/`midiPlayback`/`metronome` suites stay green — and the two score/race test files were retrofitted onto the shared `fakeAudioContext.js` helper (extended with a suspended-resume mode) to drop their hand-rolled Web Audio fakes. (`client/src/lib/lookaheadTransport.js`, `client/src/lib/scorePlayback.js`, `client/src/lib/midiPlayback.js`, `client/src/test/fakeAudioContext.js`)
+
- **[issue-1893] Decided and documented `atomicWrite`'s symlink semantics.** Settled the design question deferred from the #1837 review: when `atomicWrite`'s target is a symlink, the temp+rename deliberately REPLACES the link with a regular file rather than following it to the backing file — the standard atomic-write contract (git, dpkg, rsync, `os.replace` all replace the link), and following it would reintroduce the non-atomic in-place truncate the helper exists to eliminate. The decision (and the reasoning behind not following or rejecting) is now recorded in the helper's JSDoc, and a test pins the replace-not-follow behavior so it can't silently regress. No runtime behavior changed — PortOS ships no symlinked data files — this closes the open question rather than altering the writer. (`server/lib/fileUtils.js`, `server/lib/fileUtils.test.js`)
- **[issue-725] Brain entity stores split to per-record `collectionStore` layout.** Every Brain store (people, projects, ideas, admin, memories, links, buckets, journals, inbox, songs) moved off its monolithic `data/brain/<type>.json` file — where every create/update/delete rewrote the whole file and every read parsed all records behind a 2s cache and one global write mutex — onto the per-record `collectionStore` shape (`data/brain/<type>/<id>/index.json`), read through to disk with per-id write queues so writes to different records no longer serialize. This is proactive scale headroom: PortOS is distributed and a user's federated peers accumulate Brain data on their own schedule, so stores are prepared for size before any one install hits the whole-file-rewrite cliff. Federation is untouched — Brain federates strictly per-record through the storage API seams, so the on-disk container shape is orthogonal to the wire format (no schema-version bump, no wire-category change), and in-place tombstones are preserved through the split so no last-writer-wins delete marker is lost. Migration 200 splits existing installs (legacy files renamed to `.bak-200`, never deleted; idempotent and recovery-safe), and the shared split skeleton (`makeSplitMigration`) gained a `map` mode for the object-keyed `{ records: { <id>: rec } }` shape alongside the existing array mode. Every exported `brainStorage` function keeps its signature and behavior, so all runtime consumers and the whole reconcile/anti-entropy path are unchanged. (`server/services/brainStorage.js`, `scripts/migrations/200-split-brain-stores-to-per-record.js`, `scripts/migrations/_lib.js`)
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 6171a86cef..7eb2f66b88 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -119,6 +119,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
| `editorialChecks.js` | Pure helpers for the Editorial Checks page (`/pipeline/editorial-checks`, #1285): `groupChecksByScope(checks)` buckets catalog rows into ordered Noun/Scene/Issue/Series sections; `groupFindingsByCheck(comments, rowsById)` groups check-sourced review comments per check with open/total + severity counts; `openFindingsTotal(groups)` sums open findings; `findingManuscriptLink(seriesId, comment)` builds the `?comment=` deep-link into the manuscript editor; the triage filter/sort helpers (#1600) `deriveFindingFacets(groups)` (enumerate present severities/statuses/scopes/checks/issues), `applyFindingsView(groups, filters, sort)` (filter + recount + sort findings and groups), `normalizeFindingSort`, `findingIssueKey`, and the `FINDING_SORT_OPTIONS` table; the per-check maturity/quality helpers (#1629) `checkDismissalRate(group)` and `checkMaturity(group)` (→ `{ findings, dismissalRate, falsePositiveRate, level }`, `level` ∈ new/unproven/noisy/reliable) plus the `CHECK_MATURITY_MIN_SAMPLE`/`CHECK_NOISY_DISMISSAL_RATE` thresholds; plus `scopeLabel` and the `CHECK_SCOPE_ORDER`/`CHECK_SCOPE_LABELS` tables. No React/window — the page and its tests share them. |
| `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; `orderedChecks(openByCheck, labelFor)` sorts the per-check breakdown resolving each id to its catalog label (#1597); `checkCountSeries(points, checkId)` extracts one check's count series across the trend points; `countSparklineGeometry(values, box)` projects a non-negative count series into SVG polyline coords normalized to its own max (per-check finding-count sparkline); `diffCountMaps(current, previous)` lists the buckets whose open-finding count changed between two snapshots (#1630); `snapshotDiff(point, previous)` builds a trend snapshot's drill-down (its own breakdown + per-severity/category/check diff vs the prior revision, null-aware for pre-#1597 per-check telemetry, #1630); plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. |
+| `lookaheadTransport.js` | Shared lookahead-transport state machine for the synth players (#2493) — `createLookaheadTransport({ getTotalSec, scheduleWindow, prepare?, seekCursors?, resetCursors?, onFinish?, onStop?, onTeardown? })` owns the Web Audio clock + live-node lifecycle (playing / interval / startTime / offsetSec / nodes / playToken, the suspended-context resume with the teardown-race guard, `track()` node pruning, and the play / pause / stop / seek / position transitions); each player supplies only the scheduling + notify callbacks and stays a thin scheduler over it, so a fix to the token-guard race or teardown lands in one place. Also the single source of the `SYNTH_TIMING` lookahead constants (`LEAD`/`LOOKAHEAD_MS`/`SCHEDULE_AHEAD`) `scorePlayback`/`midiPlayback` share. No React, no score/MIDI concepts — imports only the shared `AudioContext`. |
| `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. |
| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |
| `midiChords.js` | Chord detection for the MIDI visualization UI (#2477). `detectChordWindows(notes, { minWindowSec })` sweeps the normalized note list for maximal spans where ≥2 distinct pitch classes sound simultaneously → `[{ startSec, endSec, label, midis }]` (adjacent same-label windows merged); `nameChord(pcs, bassPc)` maps a pitch-class set to a compact symbol (maj/min/dim/aug triads, maj7/7/m7/m7b5/dim7, sus2/sus4/add9, slash-chord inversions) and falls back to sorted pitch-class names (`C E G#`) rather than guessing wrong; `chordNoteNames(midis)` for tooltips. Pure — no canvas/React. |
@@ -127,7 +128,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `pianoKeyboard.js` | Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (`<PianoRoll>`). Pure math, no canvas/React. `keyboardRange(midis, { minSemitones })` → `{ lowMidi, highMidi }` padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; `buildKeyboardLayout({ lowMidi, highMidi, width })` → `{ keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth }` (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus `isBlackKey(midi)`, `midiNoteName(midi)` (sharps spelling), `pitchClass(midi)` (positive modulo), the canonical `PITCH_CLASS_NAMES` table (re-exported by `referenceAnalysis.js`, consumed by `midiChords.js` — single source for note/chord spelling), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. |
| `referenceAnalysis.js` | Reference-audio analysis for the Rounds workbench (#2106) — pure DSP + diff helpers behind the "analyze a reference's attached audio" view. `extractPitchTrack(samples, sampleRate, { startMs, endMs, hopMs })` frames decoded PCM through `detectFrequency` offline (faster than realtime) into the `[{ tMs, hz, clarity }]` shape `singToScore` consumes; `proposeSegmentScore(samples, sampleRate, { startMs, endMs, bpm, key })` runs the solo-segment pipeline (extract → `transcribePitchTrack` on the round's tempo/key grid) → `{ track, body, text }`; `buildScoreText({ key, tempo, body })` wraps a transcribed body in a lead-sheet header; `barPitchClasses(scoreText)` / `diffScoreBars(proposed, existing)` compare a proposed part against a stored scorePart per bar by octave-collapsed pitch-class sequence (drives the review diff highlighting). Stacked-mix extraction (#2121, spectral diff v2): `magnitudeSpectrum(frame, { fftSize })` (hand-rolled radix-2 FFT, Hann-windowed) / `averageMagnitudeSpectrum(samples, sampleRate, { startMs, endMs })` build a backing profile; `estimateSpectralF0(mag, sampleRate, fftSize)` picks the fundamental by weighted (1/k) harmonic sum (octave-robust); `extractSpectralDiffTrack(samples, sampleRate, { startMs, endMs, bgStartMs, bgEndMs })` subtracts the backing profile per frame and estimates f0 on the residual to recover a voice that never plays solo; `proposeStackedSegmentScore(...)` is its `proposeSegmentScore` counterpart. Zero LLM calls — pure local DSP. |
| `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. |
-| `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ midi, freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature; `midi` feeds the `<PianoRoll>` key mapping); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead; `createMultiScorePlayer(parts, { bpm, onNote, onEnded })` synthesizes several parts (melody + checked harmony) together on one master bus (level backs off as voices stack) with a per-part `onNote(partId, index)` playhead, plus `position()`/`duration()` (score-seconds) for the continuous piano-roll visualizer. Also exports the pieces `midiPlayback.js` shares: `scheduleTone` (attack/release envelope), `makeSafeCall(label)` (interval-callback guard), and the `SYNTH_TIMING` lookahead constants. |
+| `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ midi, freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature; `midi` feeds the `<PianoRoll>` key mapping); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead; `createMultiScorePlayer(parts, { bpm, onNote, onEnded })` synthesizes several parts (melody + checked harmony) together on one master bus (level backs off as voices stack) with a per-part `onNote(partId, index)` playhead, plus `position()`/`duration()` (score-seconds) for the continuous piano-roll visualizer. Both players are thin schedulers over the shared `lookaheadTransport.js`. Also exports the pieces `midiPlayback.js` shares: `scheduleTone` (attack/release envelope) and `makeSafeCall(label)` (interval-callback guard); the `SYNTH_TIMING` lookahead constants now live in `lookaheadTransport.js`. |
| `singToScore.js` | Sing-to-score transcription for the song system — turns a sung pitch track into lead-sheet notation. `segmentPitchTrack(track, opts)` groups `[{ tMs, hz, clarity }]` frames into note/rest segments (median pitch per stable span, rests where clarity drops, sub-threshold note/rest filtering); `quantizeSegments(segments, { bpm, beatValue })` snaps each duration to the nearest grid value (w/h/q/e/s) at the song tempo; `segmentsToScoreDsl(quantized, { keySig, beatsPerBar, beatValue })` spells notes enharmonically from the key signature and emits measure-grouped `\| … \|` body text; `transcribePitchTrack(track, { bpm, key, beatsPerBar, beatValue })` runs all three. Round-trips cleanly back through `parseScore`. Reuses `frequencyToNote` (pitchDetect) + the duration/key tables (scoreNotation) — no DSP/notation library. |
| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. |
| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 86ced3fec2..e87b6414e4 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -86,6 +86,7 @@ export * from './chordShapes.js';
export * from './colorMatch.js';
export * from './editorialChecks.js';
export * from './editorialHealth.js';
+export * from './lookaheadTransport.js';
export * from './lossSparkline.js';
export * from './metronome.js';
export * from './midiChords.js';
diff --git a/client/src/lib/lookaheadTransport.js b/client/src/lib/lookaheadTransport.js
new file mode 100644
index 0000000000..f15c150193
--- /dev/null
+++ b/client/src/lib/lookaheadTransport.js
@@ -0,0 +1,188 @@
+// Shared lookahead-transport for the synth players (#2493). The three players —
+// createScorePlayer + createMultiScorePlayer (scorePlayback.js) and
+// createMidiPlayer (midiPlayback.js) — all drive a Web Audio OscillatorNode
+// graph through the same lookahead-scheduler state machine: a suspended-context
+// resume with a teardown-race guard, an interval that hands due tones to the
+// audio clock, live-node teardown, and pause/stop/finish/seek sequences that
+// only differ in WHAT they schedule and WHAT the UI is told. This module owns
+// that transport (the clock + node lifecycle); each player supplies the
+// scheduling/notify callbacks below and stays a thin scheduler over it, so a fix
+// to the token-guard race or teardown semantics lands in exactly one place.
+//
+// Pure of any player specifics — no React, no score/MIDI concepts. Imports only
+// the shared AudioContext; players import createLookaheadTransport from here.
+
+import { getAudioContext as ctx } from './audioContext.js';
+
+// Shared lookahead-scheduler timing — one definition so every synth player
+// can't drift apart on feel. Lives here (not in scorePlayback.js) so the
+// transport and its players share it without a circular import.
+export const SYNTH_TIMING = {
+ LEAD: 0.08, // seconds of lead-in before beat 0 / t=0 sounds
+ LOOKAHEAD_MS: 25, // how often the scheduler wakes
+ SCHEDULE_AHEAD: 0.12, // seconds of audio scheduled past "now"
+};
+const { LEAD, LOOKAHEAD_MS } = SYNTH_TIMING;
+
+/**
+ * Build a lookahead transport that owns the clock and live-node lifecycle for a
+ * synth player. The player supplies the pieces that differ between players; the
+ * transport owns playing / interval / startTime / offsetSec / nodes / playToken
+ * and the play / pause / stop / seek / position transitions.
+ *
+ * @param {object} hooks
+ * @param {() => number} hooks.getTotalSec — current total length in seconds,
+ * re-read every tick and on seek/position (players whose length changes with
+ * tempo return the freshest value).
+ * @param {(now:number, startTime:number, track:Function) => void}
+ * hooks.scheduleWindow — one scheduler tick: hand any tones due within
+ * SCHEDULE_AHEAD to the audio clock (via `track(scheduleTone(...))`, `track`
+ * passed in so the player never reaches back into the transport) and fire any
+ * UI/playhead callbacks. Called with the current audio time and startTime.
+ * @param {() => boolean} [hooks.prepare] — called in play() AFTER the resume
+ * await + stale-token recheck, BEFORE the transport arms. Rebuild schedules /
+ * create the per-play master bus here. Return false to abort as an empty
+ * schedule (fire onEnded inside); anything else proceeds.
+ * @param {(offsetSec:number, soundTails:boolean, startTime:number, track:Function) => void}
+ * [hooks.seekCursors] — position the scheduler/notify cursors at a resume/seek
+ * offset (and, when soundTails, sound notes sustaining across it via `track`).
+ * Called after startTime is set so tails can anchor to the transport clock;
+ * also called with offset 0 by stop/finish to reset the cursors to the top.
+ * @param {() => void} [hooks.onStop] — clear-the-playhead notify, fired after the
+ * cursors reset on BOTH stop and natural end (onEnded runs after it on end).
+ * @param {() => void} [hooks.onEnded] — natural-end notify, fired once after the
+ * playhead clears when playback reaches the end.
+ * @param {() => void} [hooks.onTeardown] — extra teardown after the live nodes
+ * are stopped on pause/stop/finish (e.g. drop the master-bus ref). NOT called
+ * on seek, which reuses the same bus to keep scheduling.
+ * @returns {{ play, pause, stop, seek, position, isPlaying, track }}
+ */
+export const createLookaheadTransport = ({
+ getTotalSec,
+ scheduleWindow,
+ prepare,
+ seekCursors,
+ onStop,
+ onEnded,
+ onTeardown,
+}) => {
+ const noop = () => {};
+ const doPrepare = prepare || (() => true);
+ const doSeekCursors = seekCursors || noop;
+ const doStop = onStop || noop;
+ const doEnded = onEnded || noop;
+ const doTeardown = onTeardown || noop;
+
+ let playing = false;
+ let interval = null;
+ let startTime = 0; // ctx time at which the schedule origin (beat 0 / t=0) plays
+ let offsetSec = 0; // resume position (seconds into the piece)
+ let nodes = []; // live { osc, gain } for teardown
+ // Bumped on every stop/pause; play() captures it before its `await ctx.resume()`
+ // and bails if a teardown landed during that await, so a stop/change/unmount
+ // mid–first-play can't re-arm an orphaned interval after the await resolves.
+ let playToken = 0;
+
+ // Track a scheduled { osc, gain } for teardown, pruning it from the live set
+ // when its oscillator ends. Players call this from scheduleWindow/seekCursors
+ // instead of hand-rolling the onended prune.
+ const track = (entry) => {
+ entry.osc.onended = () => { nodes = nodes.filter((n) => n !== entry); };
+ nodes.push(entry);
+ return entry;
+ };
+
+ const stopNodes = () => {
+ for (const n of nodes) {
+ n.osc.onended = null;
+ try { n.osc.stop(); } catch { /* already stopped */ }
+ }
+ nodes = [];
+ };
+
+ const clearTick = () => {
+ if (interval != null) { clearInterval(interval); interval = null; }
+ };
+
+ // One scheduler tick: let the player schedule its due window, then finish at
+ // the end. Kept minimal — everything player-specific lives in scheduleWindow.
+ const tick = () => {
+ const now = ctx().currentTime;
+ scheduleWindow(now, startTime, track);
+ if (now - startTime >= getTotalSec()) finish();
+ };
+
+ // Natural end — full teardown back to the top, clear the playhead, notify. The
+ // cursor reset is just a seek to the top (offset 0), shared with stop().
+ function finish() {
+ clearTick();
+ stopNodes();
+ doTeardown();
+ playing = false;
+ offsetSec = 0;
+ doSeekCursors(0, false, startTime, track);
+ doStop();
+ doEnded();
+ }
+
+ const play = async () => {
+ if (playing) return;
+ const c = ctx();
+ const token = ++playToken;
+ if (c.state === 'suspended' && c.resume) await c.resume();
+ if (token !== playToken) return; // a stop/pause landed during the resume await
+ if (doPrepare() === false) return; // empty schedule — prepare fired onEnded
+ playing = true;
+ startTime = c.currentTime + LEAD - offsetSec;
+ doSeekCursors(offsetSec, offsetSec > 0, startTime, track);
+ tick(); // schedule the immediate window so playback starts promptly
+ interval = setInterval(tick, LOOKAHEAD_MS);
+ };
+
+ // Pause — stop sounding, remember position, keep the cursor for resume.
+ const pause = () => {
+ playToken++; // abort an in-flight play() still awaiting ctx.resume()
+ if (!playing) return;
+ offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), getTotalSec());
+ clearTick();
+ stopNodes();
+ doTeardown();
+ playing = false;
+ };
+
+ // Stop — full teardown back to the top, clears the playhead.
+ const stop = () => {
+ playToken++; // abort an in-flight play() still awaiting ctx.resume()
+ clearTick();
+ stopNodes();
+ doTeardown();
+ playing = false;
+ offsetSec = 0;
+ doSeekCursors(0, false, startTime, track);
+ doStop();
+ };
+
+ // Jump to a position. While playing this re-anchors the running transport
+ // (silences what's sounding, re-schedules from the new point, keeping the same
+ // master bus — hence no onTeardown); while idle it just moves the resume
+ // offset so the next play() starts there.
+ const seek = (sec) => {
+ const clamped = Math.min(Math.max(0, Number.isFinite(sec) ? sec : 0), getTotalSec());
+ if (!playing) { offsetSec = clamped; return; }
+ stopNodes();
+ startTime = ctx().currentTime - clamped;
+ doSeekCursors(clamped, true, startTime, track);
+ tick();
+ };
+
+ // Current playback head in piece-seconds. While playing it's the live audio
+ // clock (capped at the length); paused/stopped it's the remembered offset.
+ // During the LEAD-in before the origin sounds this is NEGATIVE (down to −LEAD)
+ // — intentionally NOT clamped to 0, so a visualizer keeps the first note above
+ // the hit line until its oscillator actually starts rather than lighting early.
+ const position = () => (playing
+ ? Math.min(ctx().currentTime - startTime, getTotalSec())
+ : offsetSec);
+
+ return { play, pause, stop, seek, position, isPlaying: () => playing, track };
+};
diff --git a/client/src/lib/midiPlayback.js b/client/src/lib/midiPlayback.js
index 306a6bce7a..47c84a88ad 100644
--- a/client/src/lib/midiPlayback.js
+++ b/client/src/lib/midiPlayback.js
@@ -7,10 +7,13 @@
// Pure (no React) — useMidiPlayer wraps it in a hook.
import { getAudioContext as ctx } from './audioContext.js';
-import { scheduleTone, midiToFreq, makeSafeCall, SYNTH_TIMING } from './scorePlayback.js';
+import { createLookaheadTransport, SYNTH_TIMING } from './lookaheadTransport.js';
+import { scheduleTone, midiToFreq, makeSafeCall } from './scorePlayback.js';
const safeCall = makeSafeCall('MIDI playback');
-const { LEAD, LOOKAHEAD_MS, SCHEDULE_AHEAD } = SYNTH_TIMING;
+// Lead-window slack for the scheduler tick — the rest of the lookahead timing
+// (LEAD, LOOKAHEAD_MS) is owned by the shared transport (lookaheadTransport.js).
+const { SCHEDULE_AHEAD } = SYNTH_TIMING;
const MIN_TONE_SEC = 0.05; // floor so zero/near-zero-length notes still tick
const TONE_PEAK = 0.16; // per-voice peak at full velocity (polyphonic sum)
@@ -53,47 +56,26 @@ export const createMidiPlayer = (data, options = {}) => {
const totalSec = Math.max(data?.durationSec || 0, 0);
const masterLevel = masterLevelFor(peakPolyphony(notes));
- let playing = false;
- let interval = null;
- let startTime = 0; // ctx time at which t=0 plays
- let offsetSec = 0; // resume position (seconds into the file)
let nextIdx = 0; // next note to hand to the oscillator scheduler
let master = null; // per-play master bus GainNode
- let nodes = []; // live { osc, gain } for teardown
- // Bumped on every stop/pause; play() captures it before its `await ctx.resume()`
- // and bails if a teardown landed during that await (same guard as scorePlayback).
- let playToken = 0;
- const stopNodes = () => {
- for (const n of nodes) {
- n.osc.onended = null;
- try { n.osc.stop(); } catch { /* already stopped */ }
- }
- nodes = [];
- };
-
- const clearTick = () => {
- if (interval != null) { clearInterval(interval); interval = null; }
- };
-
- const playTone = (midi, startAt, durSec, velocity) => {
+ const playTone = (track, midi, startAt, durSec, velocity) => {
const freq = midiToFreq(midi);
if (!freq) return;
- const entry = scheduleTone(ctx(), freq, startAt, Math.max(durSec, MIN_TONE_SEC), master, peakFor(velocity));
- entry.osc.onended = () => { nodes = nodes.filter((n) => n !== entry); };
- nodes.push(entry);
+ track(scheduleTone(ctx(), freq, startAt, Math.max(durSec, MIN_TONE_SEC), master, peakFor(velocity)));
};
- // Position the scheduler cursor at the first note starting at/after `offset`,
- // and (with soundTails) immediately sound the tails of notes already
- // sustaining across it — seeking into a held chord should be audible, not
- // silent until the next onset. Tails anchor to the transport clock
- // (startTime + offset — callers set startTime first), NOT bare currentTime:
- // the play() path re-anchors with a LEAD of pre-roll, and a tail started at
- // "now" would run LEAD early relative to every newly scheduled onset. Notes
- // are start-sorted, so the tail scan can't early-break; it's a one-time
- // O(n) pass per seek/play, not per tick.
- const seekCursors = (offset, soundTails = false) => {
+ // Position the scheduler cursor at the first note starting at/after `offset`
+ // (0 resets to the top for stop/finish), and — with soundTails — immediately
+ // sound the tails of notes already sustaining across it (via the
+ // transport-supplied `track`): seeking into a held chord should be audible,
+ // not silent until the next onset. Tails anchor to the transport clock
+ // (`startTime` passed in — the transport sets it before calling us), NOT bare
+ // currentTime: the play() path re-anchors with a LEAD of pre-roll, and a tail
+ // started at "now" would run LEAD early relative to every newly scheduled
+ // onset. Notes are start-sorted, so the tail scan can't early-break; it's a
+ // one-time O(n) pass per seek/play, not per tick.
+ const seekCursors = (offset, soundTails = false, startTime = 0, track) => {
let idx = notes.findIndex((n) => n.startSec >= offset - 1e-6);
if (idx < 0) idx = notes.length;
nextIdx = idx;
@@ -102,100 +84,48 @@ export const createMidiPlayer = (data, options = {}) => {
for (let i = 0; i < idx; i += 1) {
const n = notes[i];
const remaining = n.startSec + n.durationSec - offset;
- if (remaining > 1e-3) playTone(n.midi, at, remaining, n.velocity);
+ if (remaining > 1e-3) playTone(track, n.midi, at, remaining, n.velocity);
}
};
- // One scheduler tick: hand any due tones to the audio clock, finish at the end.
- const tick = () => {
- const now = ctx().currentTime;
+ // One scheduler tick: hand any due tones to the audio clock. (The transport
+ // handles the end-of-file finish.)
+ const scheduleWindow = (now, startTime, track) => {
while (nextIdx < notes.length) {
const n = notes[nextIdx];
const at = startTime + n.startSec;
if (at > now + SCHEDULE_AHEAD) break;
- playTone(n.midi, Math.max(at, now), n.durationSec, n.velocity);
+ playTone(track, n.midi, Math.max(at, now), n.durationSec, n.velocity);
nextIdx += 1;
}
- if (now - startTime >= totalSec) finish();
};
- // Natural end — reset to the top and notify.
- function finish() {
- clearTick();
- stopNodes();
- master = null;
- playing = false;
- offsetSec = 0;
- nextIdx = 0;
- safeCall(onEnded);
- }
-
- const play = async () => {
- if (playing) return;
+ // Bail (as ended) on an empty view-model, then stand up the per-play master
+ // bus scaled to the file's peak polyphony so a dense chord can't clip.
+ const prepare = () => {
+ if (!notes.length || totalSec <= 0) { safeCall(onEnded); return false; }
const c = ctx();
- const token = ++playToken;
- if (c.state === 'suspended' && c.resume) await c.resume();
- if (token !== playToken) return; // a stop/pause landed during the resume await
- if (!notes.length || totalSec <= 0) { safeCall(onEnded); return; }
-
master = c.createGain();
master.gain.setValueAtTime(masterLevel, c.currentTime);
master.connect(c.destination);
-
- playing = true;
- startTime = c.currentTime + LEAD - offsetSec;
- seekCursors(offsetSec, offsetSec > 0);
- tick(); // schedule the immediate window now so playback starts promptly
- interval = setInterval(tick, LOOKAHEAD_MS);
- };
-
- // Pause — stop sounding, remember position for resume.
- const pause = () => {
- playToken++; // abort an in-flight play() still awaiting ctx.resume()
- if (!playing) return;
- offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), totalSec);
- clearTick();
- stopNodes();
- master = null;
- playing = false;
- };
-
- // Stop — full teardown back to the top.
- const stop = () => {
- playToken++; // abort an in-flight play() still awaiting ctx.resume()
- clearTick();
- stopNodes();
- master = null;
- playing = false;
- offsetSec = 0;
- nextIdx = 0;
- };
-
- // Jump to a position. While playing this re-anchors the running transport
- // (silences what's sounding, re-schedules from the new point); while idle it
- // just moves the resume offset so the next play() starts there.
- const seek = (sec) => {
- const clamped = Math.min(Math.max(0, Number.isFinite(sec) ? sec : 0), totalSec);
- if (!playing) { offsetSec = clamped; return; }
- stopNodes();
- startTime = ctx().currentTime - clamped;
- seekCursors(clamped, true);
- tick();
+ return true;
};
- // Current playback head in file-seconds, for the moving playhead. During the
- // LEAD-in before t=0 sounds this is negative (down to −LEAD) — intentionally
- // not clamped, so the playhead doesn't jump ahead of the first audible note.
- const position = () => (playing
- ? Math.min(ctx().currentTime - startTime, totalSec)
- : offsetSec);
+ const transport = createLookaheadTransport({
+ getTotalSec: () => totalSec,
+ scheduleWindow,
+ prepare,
+ seekCursors,
+ onEnded: () => { safeCall(onEnded); },
+ onTeardown: () => { master = null; },
+ });
return {
- play,
- pause,
- stop,
- seek,
- isPlaying: () => playing,
- position,
+ play: transport.play,
+ pause: transport.pause,
+ stop: transport.stop,
+ seek: transport.seek,
+ isPlaying: transport.isPlaying,
+ position: transport.position,
};
};
diff --git a/client/src/lib/scorePlayback.js b/client/src/lib/scorePlayback.js
index 35f3289ac1..18322226d4 100644
--- a/client/src/lib/scorePlayback.js
+++ b/client/src/lib/scorePlayback.js
@@ -12,6 +12,7 @@
// the UI can move a playhead. Pure (no React) — ScoreSheet wraps it in a hook.
import { getAudioContext as ctx } from './audioContext.js';
+import { createLookaheadTransport, SYNTH_TIMING } from './lookaheadTransport.js';
// --- Pitch → frequency ------------------------------------------------------
// Equal-tempered, A4 = 440 Hz. MIDI 69 == A4, so f = 440 · 2^((midi−69)/12).
@@ -97,14 +98,9 @@ export const makeSafeCall = (label) => (cb, ...args) => {
};
const safeCall = makeSafeCall('score playback');
-// Shared lookahead-scheduler timing — one export so the score synth and the
-// MIDI preview (midiPlayback.js) can't drift apart on feel.
-export const SYNTH_TIMING = {
- LEAD: 0.08, // seconds of lead-in before beat 0 sounds
- LOOKAHEAD_MS: 25, // how often the scheduler wakes
- SCHEDULE_AHEAD: 0.12, // seconds of audio scheduled past "now"
-};
-const { LEAD, LOOKAHEAD_MS, SCHEDULE_AHEAD } = SYNTH_TIMING;
+// Lead-window slack for the scheduler tick — the rest of the lookahead timing
+// (LEAD, LOOKAHEAD_MS) is owned by the shared transport (lookaheadTransport.js).
+const { SCHEDULE_AHEAD } = SYNTH_TIMING;
const TONE_PEAK = 0.18; // per-voice gain peak for a single sounding tone
// Schedule one tone with a short attack/release gain envelope so it doesn't
@@ -151,49 +147,23 @@ export const createScorePlayer = (score, options = {}) => {
let bpm = Number.isFinite(options.bpm) && options.bpm > 0 ? options.bpm : null;
let schedule = buildSchedule(score, bpm);
- let playing = false;
- let interval = null;
- let startTime = 0; // ctx time at which beat 0 plays
- let offsetSec = 0; // resume position (seconds into the score)
let nextScheduleIdx = 0; // next event to hand to the oscillator scheduler
let nextNotifyIdx = 0; // next event to fire onNote for
let lastNotified = -1;
- let nodes = []; // live { osc, gain } for teardown
- // Bumped on every stop/pause; play() captures it before its `await ctx.resume()`
- // and bails if a teardown landed during that await, so a stop/score-change/unmount
- // mid–first-play can't re-arm an orphaned interval after the await resolves.
- let playToken = 0;
-
- const stopNodes = () => {
- for (const n of nodes) {
- n.osc.onended = null;
- try { n.osc.stop(); } catch { /* already stopped */ }
- }
- nodes = [];
- };
-
- const clearTick = () => {
- if (interval != null) { clearInterval(interval); interval = null; }
- };
- // Hand one due tone to the audio clock and track it for teardown.
- const playTone = (freq, startAt, durSec) => {
- const entry = scheduleTone(ctx(), freq, startAt, durSec, ctx().destination);
- entry.osc.onended = () => { nodes = nodes.filter((n) => n !== entry); };
- nodes.push(entry);
- };
-
- // One scheduler tick: hand any due tones to the audio clock, fire the playhead
- // callback for the latest note that has started, and finish at the end.
- const tick = () => {
- const now = ctx().currentTime;
+ // One scheduler tick: hand any due tones to the audio clock (via the
+ // transport-supplied `track`) and fire the playhead callback for the latest
+ // note that has started. (The transport handles the end-of-piece finish.)
+ const scheduleWindow = (now, startTime, track) => {
const events = schedule.events;
while (nextScheduleIdx < events.length) {
const ev = events[nextScheduleIdx];
const at = startTime + ev.startSec;
if (at > now + SCHEDULE_AHEAD) break;
- if (!ev.rest && ev.freq) playTone(ev.freq, Math.max(at, now), ev.durSec);
+ if (!ev.rest && ev.freq) {
+ track(scheduleTone(ctx(), ev.freq, Math.max(at, now), ev.durSec, ctx().destination));
+ }
nextScheduleIdx += 1;
}
@@ -206,85 +176,50 @@ export const createScorePlayer = (score, options = {}) => {
lastNotified = newest;
safeCall(onNote, newest);
}
-
- if (now - startTime >= schedule.totalSec) finish();
};
- // Natural end — reset to the top and notify.
- function finish() {
- clearTick();
- stopNodes();
- playing = false;
- offsetSec = 0;
- nextScheduleIdx = 0;
- nextNotifyIdx = 0;
- lastNotified = -1;
- safeCall(onNote, null);
- safeCall(onEnded);
- }
-
// Position the schedule/notify cursors at a resume offset — the first event
// still sounding at (or starting after) `offset`. Both cursors share this
// point so the note under the playhead at resume is (re)scheduled AND
- // (re)notified, and a fresh play from 0 still notifies note 0.
+ // (re)notified, and a fresh play from 0 still notifies note 0 (stop/finish
+ // call this with offset 0 to reset to the top). No tails, so it ignores the
+ // transport's soundTails/startTime/track args.
const seekCursors = (offset) => {
const events = schedule.events;
let idx = events.findIndex((e) => e.startSec + e.durSec > offset + 1e-6);
if (idx < 0) idx = events.length;
nextScheduleIdx = idx;
nextNotifyIdx = idx;
- };
-
- const play = async () => {
- if (playing) return;
- const c = ctx();
- const token = ++playToken;
- if (c.state === 'suspended' && c.resume) await c.resume();
- if (token !== playToken) return; // a stop/pause landed during the resume await
- if (!schedule.events.length || schedule.totalSec <= 0) { safeCall(onEnded); return; }
-
- schedule = buildSchedule(score, bpm); // pick up a tempo change made while idle
- playing = true;
lastNotified = -1;
- startTime = c.currentTime + LEAD - offsetSec;
- seekCursors(offsetSec);
- tick(); // schedule the immediate window now so playback starts promptly
- interval = setInterval(tick, LOOKAHEAD_MS);
};
- // Pause — stop sounding, remember position, keep the cursor for resume.
- const pause = () => {
- playToken++; // abort an in-flight play() still awaiting ctx.resume()
- if (!playing) return;
- offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), schedule.totalSec);
- clearTick();
- stopNodes();
- playing = false;
+ // Rebuild to pick up a tempo change made while idle, then bail (as ended) on
+ // an empty score. Runs after the transport's resume/token recheck.
+ const prepare = () => {
+ schedule = buildSchedule(score, bpm);
+ if (!schedule.events.length || schedule.totalSec <= 0) { safeCall(onEnded); return false; }
+ return true;
};
- // Stop — full teardown back to the top, clears the playhead.
- const stop = () => {
- playToken++; // abort an in-flight play() still awaiting ctx.resume()
- clearTick();
- stopNodes();
- playing = false;
- offsetSec = 0;
- nextScheduleIdx = 0;
- nextNotifyIdx = 0;
- lastNotified = -1;
- safeCall(onNote, null);
- };
+ const transport = createLookaheadTransport({
+ getTotalSec: () => schedule.totalSec,
+ scheduleWindow,
+ prepare,
+ seekCursors,
+ onStop: () => { safeCall(onNote, null); },
+ onEnded: () => { safeCall(onEnded); },
+ });
const setTempo = (nextBpm) => {
bpm = Number.isFinite(nextBpm) && nextBpm > 0 ? nextBpm : null;
- if (!playing) schedule = buildSchedule(score, bpm);
+ if (!transport.isPlaying()) schedule = buildSchedule(score, bpm);
};
return {
- play,
- pause,
- stop,
- isPlaying: () => playing,
+ play: transport.play,
+ pause: transport.pause,
+ stop: transport.stop,
+ isPlaying: transport.isPlaying,
setTempo,
schedule: () => schedule,
};
@@ -339,32 +274,12 @@ export const createMultiScorePlayer = (parts, options = {}) => {
};
rebuild();
- let playing = false;
- let interval = null;
- let startTime = 0; // ctx time at which beat 0 plays
- let offsetSec = 0; // resume position (seconds into the score)
let master = null; // shared bus GainNode (created per play)
- let nodes = []; // live { osc, gain } across all voices, for teardown
- // Bumped on every stop/pause; play() captures it before its `await ctx.resume()`
- // and bails if a teardown landed during that await — otherwise a checkbox toggle
- // (which tears the player down) mid–first-play re-arms an orphaned, un-stoppable
- // interval after the await resolves.
- let playToken = 0;
-
- const stopNodes = () => {
- for (const n of nodes) {
- n.osc.onended = null;
- try { n.osc.stop(); } catch { /* already stopped */ }
- }
- nodes = [];
- master = null;
- };
-
- const clearTick = () => {
- if (interval != null) { clearInterval(interval); interval = null; }
- };
- const resetCursors = (offset = 0) => {
+ // Position every voice's cursors at `offset` (0 resets to the top for
+ // stop/finish). No tails, so it ignores the transport's soundTails/startTime/
+ // track args.
+ const seekCursors = (offset = 0) => {
for (const v of voices) {
const events = v.schedule.events;
let idx = events.findIndex((e) => e.startSec + e.durSec > offset + 1e-6);
@@ -376,21 +291,16 @@ export const createMultiScorePlayer = (parts, options = {}) => {
}
};
- const playTone = (freq, startAt, durSec) => {
- const entry = scheduleTone(ctx(), freq, startAt, durSec, master);
- entry.osc.onended = () => { nodes = nodes.filter((n) => n !== entry); };
- nodes.push(entry);
- };
-
- const tick = () => {
- const now = ctx().currentTime;
+ const scheduleWindow = (now, startTime, track) => {
for (const v of voices) {
const events = v.schedule.events;
while (v.nextScheduleIdx < events.length) {
const ev = events[v.nextScheduleIdx];
const at = startTime + ev.startSec;
if (at > now + SCHEDULE_AHEAD) break;
- if (!ev.rest && ev.freq) playTone(ev.freq, Math.max(at, now), ev.durSec);
+ if (!ev.rest && ev.freq) {
+ track(scheduleTone(ctx(), ev.freq, Math.max(at, now), ev.durSec, master));
+ }
v.nextScheduleIdx += 1;
}
@@ -411,81 +321,42 @@ export const createMultiScorePlayer = (parts, options = {}) => {
safeCall(onNote, v.id, null);
}
}
-
- if (now - startTime >= totalSec) finish();
};
- function finish() {
- clearTick();
- stopNodes();
- playing = false;
- offsetSec = 0;
- resetCursors(0);
- for (const v of voices) safeCall(onNote, v.id, null);
- safeCall(onEnded);
- }
-
- const play = async () => {
- if (playing) return;
+ // Rebuild to pick up a tempo change made while idle, bail (as ended) on an
+ // empty selection, then stand up the per-play master bus.
+ const prepare = () => {
+ rebuild();
+ if (!totalSec) { safeCall(onEnded); return false; }
const c = ctx();
- const token = ++playToken;
- if (c.state === 'suspended' && c.resume) await c.resume();
- if (token !== playToken) return; // a stop/pause landed during the resume await
- rebuild(); // pick up a tempo change made while idle
- if (!totalSec) { safeCall(onEnded); return; }
-
master = c.createGain();
master.gain.setValueAtTime(masterGainFor(voices.length), c.currentTime);
master.connect(c.destination);
-
- playing = true;
- startTime = c.currentTime + LEAD - offsetSec;
- resetCursors(offsetSec);
- tick(); // schedule the immediate window now so playback starts promptly
- interval = setInterval(tick, LOOKAHEAD_MS);
+ return true;
};
- const pause = () => {
- playToken++; // abort an in-flight play() still awaiting ctx.resume()
- if (!playing) return;
- offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), totalSec);
- clearTick();
- stopNodes();
- playing = false;
- };
-
- const stop = () => {
- playToken++; // abort an in-flight play() still awaiting ctx.resume()
- clearTick();
- stopNodes();
- playing = false;
- offsetSec = 0;
- resetCursors(0);
- for (const v of voices) safeCall(onNote, v.id, null);
- };
+ const transport = createLookaheadTransport({
+ getTotalSec: () => totalSec,
+ scheduleWindow,
+ prepare,
+ seekCursors,
+ onStop: () => { for (const v of voices) safeCall(onNote, v.id, null); },
+ onEnded: () => { safeCall(onEnded); },
+ onTeardown: () => { master = null; },
+ });
const setTempo = (nextBpm) => {
bpm = Number.isFinite(nextBpm) && nextBpm > 0 ? nextBpm : null;
- if (!playing) rebuild();
+ if (!transport.isPlaying()) rebuild();
};
- // Current playback head in score-seconds, for a continuous visualizer (the
- // piano-roll). While playing it's the live audio clock (capped at the score
- // length); paused/stopped it's the remembered resume offset. During the LEAD-in
- // before beat 0 sounds this is NEGATIVE (down to −LEAD) — intentionally NOT
- // clamped to 0, so the visualizer keeps the first note above the hit line until
- // its oscillator actually starts rather than lighting the key early.
- const position = () => (playing
- ? Math.min(ctx().currentTime - startTime, totalSec)
- : offsetSec);
-
return {
- play,
- pause,
- stop,
- isPlaying: () => playing,
+ play: transport.play,
+ pause: transport.pause,
+ stop: transport.stop,
+ isPlaying: transport.isPlaying,
setTempo,
- position,
+ position: transport.position,
duration: () => totalSec,
};
};
diff --git a/client/src/lib/scorePlayback.race.test.js b/client/src/lib/scorePlayback.race.test.js
index e36ffc89bd..87b9b71460 100644
--- a/client/src/lib/scorePlayback.race.test.js
+++ b/client/src/lib/scorePlayback.race.test.js
@@ -6,36 +6,19 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { parseScore } from './scoreNotation.js';
import { createScorePlayer, createMultiScorePlayer } from './scorePlayback.js';
+import { createFakeAudio } from '../test/fakeAudioContext.js';
-const audio = { now: 0, oscillators: [] };
-const fakeParam = () => ({ setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} });
-
-// A context that starts suspended and only resumes when we resolve the deferred
-// returned by resume() — so a test can interleave a stop()/pause() between play()'s
-// `await ctx.resume()` and its continuation.
-let resolveResume;
-function SuspendedAudioContext() {
- return {
- state: 'suspended',
- resume() { return new Promise((r) => { resolveResume = r; }); },
- get currentTime() { return audio.now; },
- destination: { id: 'destination' },
- createOscillator() {
- const osc = { type: '', frequency: fakeParam(), onended: null, started: null, stopped: null,
- connect: (t) => t, start(t) { this.started = t; }, stop(t) { this.stopped = t; } };
- audio.oscillators.push(osc);
- return osc;
- },
- createGain() { return { gain: fakeParam(), connect: (t) => t }; },
- };
-}
+// The shared fake in suspended mode starts the context suspended and only
+// resolves resume() when we call audio.flushResume() — so a test can interleave
+// a stop()/pause() between play()'s `await ctx.resume()` and its continuation,
+// reproducing the teardown-during-await race the playToken guard fixes. One
+// pair for the whole file (lib/audioContext.js caches the context).
+const { FakeAudioContext, audio } = createFakeAudio({ suspended: true });
describe('resume-window teardown race', () => {
beforeEach(() => {
- audio.now = 0;
- audio.oscillators = [];
- resolveResume = undefined;
- vi.stubGlobal('AudioContext', SuspendedAudioContext);
+ audio.reset();
+ vi.stubGlobal('AudioContext', FakeAudioContext);
vi.useFakeTimers();
});
afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });
@@ -46,7 +29,7 @@ describe('resume-window teardown race', () => {
const player = createScorePlayer(SCORE, { bpm: 120 });
const playing = player.play(); // suspends on ctx.resume()
player.stop(); // teardown lands mid-await — bumps the token
- resolveResume(); // resume resolves; play() must see the stale token and bail
+ audio.flushResume(); // resume resolves; play() must see the stale token and bail
await playing;
audio.now = 5; vi.advanceTimersByTime(5000); // no interval should be running
expect(player.isPlaying()).toBe(false);
@@ -57,7 +40,7 @@ describe('resume-window teardown race', () => {
const player = createMultiScorePlayer([{ id: 'melody', score: SCORE }], { bpm: 120 });
const playing = player.play();
player.stop();
- resolveResume();
+ audio.flushResume();
await playing;
audio.now = 5; vi.advanceTimersByTime(5000);
expect(player.isPlaying()).toBe(false);
diff --git a/client/src/lib/scorePlayback.test.js b/client/src/lib/scorePlayback.test.js
index c9657ce4c4..214c95a665 100644
--- a/client/src/lib/scorePlayback.test.js
+++ b/client/src/lib/scorePlayback.test.js
@@ -9,6 +9,7 @@ import {
createMultiScorePlayer,
DEFAULT_BPM,
} from './scorePlayback.js';
+import { createFakeAudio } from '../test/fakeAudioContext.js';
// --- Pitch → frequency ------------------------------------------------------
describe('pitch → frequency', () => {
@@ -94,28 +95,11 @@ describe('buildSchedule', () => {
});
// --- Player (stubbed Web Audio) --------------------------------------------
-// jsdom has no Web Audio. A minimal fake AudioContext records created
+// jsdom has no Web Audio. The shared fake AudioContext records created
// oscillators and exposes a controllable clock so we can drive the lookahead
-// scheduler deterministically with fake timers.
-const audio = { now: 0, oscillators: [] };
-const fakeParam = () => ({ setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} });
-function FakeAudioContext() {
- return {
- state: 'running',
- resume: () => Promise.resolve(),
- get currentTime() { return audio.now; },
- destination: { id: 'destination' },
- createOscillator() {
- const osc = {
- type: '', frequency: fakeParam(), onended: null, started: null, stopped: null,
- connect: (t) => t, start(t) { this.started = t; }, stop(t) { this.stopped = t; },
- };
- audio.oscillators.push(osc);
- return osc;
- },
- createGain() { return { gain: fakeParam(), connect: (t) => t }; },
- };
-}
+// scheduler deterministically with fake timers. One pair for the whole file —
+// lib/audioContext.js caches the context.
+const { FakeAudioContext, audio } = createFakeAudio();
const drive = (toSec) => {
for (let t = 0; t <= toSec; t += 0.1) { audio.now = Number(t.toFixed(3)); vi.advanceTimersByTime(100); }
@@ -123,8 +107,7 @@ const drive = (toSec) => {
describe('createScorePlayer', () => {
beforeEach(() => {
- audio.now = 0;
- audio.oscillators = [];
+ audio.reset();
vi.stubGlobal('AudioContext', FakeAudioContext);
vi.useFakeTimers();
});
@@ -177,8 +160,7 @@ describe('createScorePlayer', () => {
// --- Multi-part player (layered MIDI) --------------------------------------
describe('createMultiScorePlayer', () => {
beforeEach(() => {
- audio.now = 0;
- audio.oscillators = [];
+ audio.reset();
vi.stubGlobal('AudioContext', FakeAudioContext);
vi.useFakeTimers();
});
diff --git a/client/src/test/fakeAudioContext.js b/client/src/test/fakeAudioContext.js
index 23fa803de3..910806868b 100644
--- a/client/src/test/fakeAudioContext.js
+++ b/client/src/test/fakeAudioContext.js
@@ -4,10 +4,19 @@
// `audio.now` to move the context clock; every created oscillator/gain is
// recorded on `audio` for assertions (gain envelopes land in `param.values`).
// Same shape the pre-existing hand-rolled fakes in scorePlayback.test.js /
-// metronome.test.js use — new audio tests should import this instead of
-// copying another one.
+// scorePlayback.race.test.js use — new audio tests should import this instead
+// of copying another one.
+//
+// Pass { suspended: true } to model a context that starts suspended and only
+// resumes when the test calls `audio.flushResume()` — this reproduces the
+// teardown-during-await race the players' playToken guard fixes, letting a test
+// interleave a stop()/pause() between play()'s `await ctx.resume()` and its
+// continuation.
-export const createFakeAudio = () => {
+export const createFakeAudio = ({ suspended = false } = {}) => {
+ // Pending resolver for a suspended context's in-flight resume() (null until
+ // a resume() is awaiting, cleared once flushed).
+ let resolveResume = null;
const audio = {
now: 0,
oscillators: [],
@@ -16,7 +25,9 @@ export const createFakeAudio = () => {
// test file, so create ONE pair per file and reset the recorders per
// test — a fresh pair mid-file would record into an object the cached
// context no longer points at.
- reset() { this.now = 0; this.oscillators.length = 0; this.gains.length = 0; },
+ reset() { this.now = 0; this.oscillators.length = 0; this.gains.length = 0; resolveResume = null; },
+ // Resolve a suspended context's pending resume() so play()'s await continues.
+ flushResume() { const r = resolveResume; resolveResume = null; if (r) r(); },
};
const fakeParam = () => {
const values = [];
@@ -28,8 +39,10 @@ export const createFakeAudio = () => {
};
function FakeAudioContext() {
return {
- state: 'running',
- resume: () => Promise.resolve(),
+ state: suspended ? 'suspended' : 'running',
+ resume: suspended
+ ? () => new Promise((r) => { resolveResume = r; })
+ : () => Promise.resolve(),
get currentTime() { return audio.now; },
destination: { id: 'destination' },
createOscillator() {