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-2490]): apply simplify-pass findings to the synth preview

[._.]/ Adam Eivyda6b7774c79c
diff --git a/client/src/components/songs/MidiPianoRoll.jsx b/client/src/components/songs/MidiPianoRoll.jsx
index 53e9f9ef5d..63e2b8baad 100644
--- a/client/src/components/songs/MidiPianoRoll.jsx
+++ b/client/src/components/songs/MidiPianoRoll.jsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { midiNoteName, isBlackKey } from '../../lib/pianoKeyboard';
import { chordNoteNames } from '../../lib/midiChords';
import { roundRect, layerColor } from '../../lib/canvasRoll.js';
@@ -44,6 +44,21 @@ const tickStep = (pps) => {
return steps.find((s) => s * pps >= 70) || 300;
};
+// First index in the start-sorted note list with startSec >= t. Subtracting
+// the file's longest note duration from a window edge before searching gives
+// the earliest index that can still overlap that edge — O(log n) instead of
+// skip-scanning from note 0, which matters once the rAF playback loop makes
+// drawing a 60fps hot path.
+const lowerBound = (notes, t) => {
+ let lo = 0;
+ let hi = notes.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (notes[mid].startSec < t) lo = mid + 1; else hi = mid;
+ }
+ return lo;
+};
+
const tooltipStyle = (x, y, width) => ({
left: `${Math.min(x + 10, Math.max(0, width - TOOLTIP_W))}px`,
top: `${Math.max(0, y - 24)}px`,
@@ -84,10 +99,16 @@ export default function MidiPianoRoll({
// the parent hands fresh closures each render; the rAF loop reads refs.
const getPositionRef = useRef(getPosition);
getPositionRef.current = getPosition;
- const playingRef = useRef(playing);
- playingRef.current = playing;
+ // Set of midis sounding this frame (null when idle) — written by the rAF
+ // playback loop, painted onto the pitch gutter by draw().
+ const soundingRef = useRef(null);
const duration = Math.max(data?.durationSec || 0, 0.001);
+ // Longest note in the file — the lookback window for lowerBound() scans.
+ const maxDurSec = useMemo(
+ () => (data?.notes || []).reduce((m, n) => Math.max(m, n.durationSec || 0), 0),
+ [data],
+ );
const chordLaneH = showChords && chords?.length ? CHORD_H : 0;
const multiTrack = (data?.tracks?.length || 1) > 1;
@@ -196,7 +217,7 @@ export default function MidiPianoRoll({
ctx.clip();
ctx.textAlign = 'left';
const notes = data?.notes || [];
- for (let i = 0; i < notes.length; i += 1) {
+ for (let i = lowerBound(notes, scroll - maxDurSec); i < notes.length; i += 1) {
const n = notes[i];
if (n.startSec > viewEnd) break;
const end = n.startSec + n.durationSec;
@@ -237,18 +258,9 @@ export default function MidiPianoRoll({
ctx.fillRect(px - 1, RULER_H, 2, height - RULER_H);
}
- // Sounding pitches (playing only) — light their gutter rows below. Notes
- // are start-sorted, so the scan early-breaks at the playhead.
- let soundingMidis = null;
- if (playingRef.current) {
- soundingMidis = new Set();
- const pos = playheadSecRef.current;
- for (let i = 0; i < notes.length; i += 1) {
- const n = notes[i];
- if (n.startSec > pos) break;
- if (pos < n.startSec + n.durationSec) soundingMidis.add(n.midi);
- }
- }
+ // Sounding pitches (playing only) — computed once per frame by the rAF
+ // playback loop (null when idle); draw just paints the gutter rows.
+ const soundingMidis = soundingRef.current;
// Pitch gutter on top (opaque, so notes pan "under" it).
ctx.fillStyle = GUTTER_BG;
@@ -279,7 +291,7 @@ export default function MidiPianoRoll({
ctx.fillStyle = 'rgba(255,255,255,0.15)';
ctx.fillRect(barX, height - 3, barW, 2);
}
- }, [data, chords, chordLaneH, geometry, height, highMidi, lowMidi, hover, multiTrack, duration]);
+ }, [data, chords, chordLaneH, geometry, height, highMidi, lowMidi, hover, multiTrack, duration, maxDurSec]);
const drawRef = useRef(draw);
drawRef.current = draw;
@@ -290,34 +302,59 @@ export default function MidiPianoRoll({
useEffect(() => { draw(); }, [draw, zoom]);
// Playback rAF loop: while playing, read the live audio position into the
- // playhead ref, page the view to keep it visible, and repaint each frame.
- // On pause/stop the loop tears down and one static frame pins the playhead
- // where the audio stopped (position() reports the resume offset).
+ // playhead ref, page the view to keep it visible, compute the sounding
+ // pitch set for the gutter, and repaint — but only when a frame is visually
+ // different (playhead pixel, sounding set, or a page turn). At fit zoom the
+ // playhead moves well under a pixel per frame, so most frames skip the full
+ // canvas repaint. On pause/stop the loop tears down and one static frame
+ // pins the playhead where the audio stopped.
+ const wasPlayingRef = useRef(false);
+ const lastFrameRef = useRef('');
useEffect(() => {
+ const notes = data?.notes || [];
if (!playing) {
- if (getPositionRef.current) {
- playheadSecRef.current = getPositionRef.current() ?? 0;
+ soundingRef.current = null;
+ if (wasPlayingRef.current) {
+ wasPlayingRef.current = false;
+ playheadSecRef.current = getPositionRef.current?.() ?? 0;
drawRef.current();
}
return undefined;
}
+ wasPlayingRef.current = true;
+ lastFrameRef.current = '';
let raf = 0;
const loop = () => {
- playheadSecRef.current = getPositionRef.current?.() ?? 0;
+ const pos = getPositionRef.current?.() ?? 0;
+ playheadSecRef.current = pos;
// Page-turn follow: when the playhead exits the visible window (or a
// seek lands outside it), snap the view so it re-enters near the left.
const { gridW, pps, maxScroll } = geometry();
const view = gridW / pps;
- const pos = playheadSecRef.current;
+ let paged = false;
if (pos < scrollSecRef.current || pos > scrollSecRef.current + view) {
scrollSecRef.current = Math.min(Math.max(0, pos - view * 0.1), maxScroll);
+ paged = true;
+ }
+ // Sounding set — scan only the slice that can overlap the playhead.
+ const sounding = new Set();
+ let sum = 0;
+ for (let i = lowerBound(notes, pos - maxDurSec); i < notes.length; i += 1) {
+ const n = notes[i];
+ if (n.startSec > pos) break;
+ if (pos < n.startSec + n.durationSec) { sounding.add(n.midi); sum += n.midi; }
+ }
+ const frame = `${Math.round((pos - scrollSecRef.current) * pps)}:${sounding.size}:${sum}`;
+ if (paged || frame !== lastFrameRef.current) {
+ lastFrameRef.current = frame;
+ soundingRef.current = sounding;
+ drawRef.current();
}
- drawRef.current();
raf = requestAnimationFrame(loop);
};
raf = requestAnimationFrame(loop);
return () => cancelAnimationFrame(raf);
- }, [playing, geometry]);
+ }, [playing, geometry, data, maxDurSec]);
// Coalesce pan-driven repaints to one per animation frame — wheel/pointer
// events can fire faster than the display presents.
diff --git a/client/src/components/songs/MidiVisualization.test.jsx b/client/src/components/songs/MidiVisualization.test.jsx
index 730478491a..af6968ea83 100644
--- a/client/src/components/songs/MidiVisualization.test.jsx
+++ b/client/src/components/songs/MidiVisualization.test.jsx
@@ -2,6 +2,10 @@ import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import MidiVisualization from './MidiVisualization.jsx';
import { __clearMidiNotesCache } from '../../hooks/useMidiNotes.js';
+import { createFakeAudio } from '../../test/fakeAudioContext.js';
+
+// One fake pair for the file — lib/audioContext.js caches the context.
+const { FakeAudioContext } = createFakeAudio();
// Tiny hand-built SMF fixture: a sustained C-major triad (C4 E4 G4) for one
// quarter at the default 120 BPM. Same builder approach as midiNotes.test.js.
@@ -32,22 +36,6 @@ const makeCtx = () => ({
fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: '', globalAlpha: 1,
});
-// jsdom has no Web Audio — minimal fake for the synth-preview player (same
-// shape as midiPlayback.test.js, static clock is enough for UI wiring tests).
-const fakeParam = () => ({ setValueAtTime: vi.fn(), exponentialRampToValueAtTime: vi.fn() });
-function FakeAudioContext() {
- return {
- state: 'running',
- resume: () => Promise.resolve(),
- currentTime: 0,
- destination: {},
- createOscillator: () => ({
- type: '', frequency: fakeParam(), onended: null,
- connect: (t) => t, start: vi.fn(), stop: vi.fn(),
- }),
- createGain: () => ({ gain: fakeParam(), connect: (t) => t }),
- };
-}
describe('<MidiVisualization>', () => {
let ctx;
@@ -56,6 +44,8 @@ describe('<MidiVisualization>', () => {
ctx = makeCtx();
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx);
vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
+ // jsdom has no Web Audio — shared fake for the synth-preview player (the
+ // static clock is enough for these UI-wiring tests).
vi.stubGlobal('AudioContext', FakeAudioContext);
Object.defineProperty(HTMLElement.prototype, 'clientWidth', { configurable: true, get() { return 800; } });
vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({
diff --git a/client/src/hooks/useMidiPlayer.js b/client/src/hooks/useMidiPlayer.js
index 0ca64a1316..5b8e805de9 100644
--- a/client/src/hooks/useMidiPlayer.js
+++ b/client/src/hooks/useMidiPlayer.js
@@ -23,7 +23,7 @@ export default function useMidiPlayer(data) {
playerRef.current = player;
return () => {
player.stop();
- if (playerRef.current === player) playerRef.current = null;
+ playerRef.current = null;
setPlaying(false);
};
}, [data]);
diff --git a/client/src/hooks/useMidiPlayer.test.jsx b/client/src/hooks/useMidiPlayer.test.jsx
index 0031e94b5e..a8cc02b0f3 100644
--- a/client/src/hooks/useMidiPlayer.test.jsx
+++ b/client/src/hooks/useMidiPlayer.test.jsx
@@ -14,7 +14,6 @@ const makeFakePlayer = () => {
stop: vi.fn(() => { playing = false; }),
seek: vi.fn(),
position: vi.fn(() => 1.25),
- duration: vi.fn(() => 10),
isPlaying: () => playing,
};
};
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 6e22fb439e..a25096a4d5 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -118,11 +118,11 @@ grep -i "what you want to do" client/src/lib/README.md
| `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. |
| `midiNotes.js` | Minimal Standard MIDI File parser + normalizer for the MIDI visualization UI (#2477) — in-tree, zero deps. `parseMidiFile(arrayBuffer)` parses SMF format 0/1 (running status, note-on vel-0-as-off, tempo map incl. mid-file changes, SMPTE division, track names) into the piano-roll view-model `{ durationSec, minMidi, maxMidi, notes:[{id,midi,startSec,durationSec,velocity,track,name}], tracks, tempos }`. Throws on non-MIDI bytes. Consumed by `useMidiNotes` → `<MidiPianoRoll>`. NOT the lead-sheet parser (`scoreNotation.js`). |
-| `midiPlayback.js` | Synth preview of a transcribed `.mid` (#2490) — `createMidiPlayer(data, { onEnded })` plays the `parseMidiFile` view-model as velocity-scaled oscillator tones through a per-play master bus on the shared `AudioContext`, with the same lookahead-scheduler idiom + tone envelope (`scheduleTone`) as `scorePlayback.js`. Transport: `play`/`pause`/`stop`/`seek(sec)` (seek re-anchors a running transport and sounds the tails of notes sustaining across the seek point), `position()`/`duration()` for the `<MidiPianoRoll>` moving playhead. Pure (no React) — `useMidiPlayer` wraps it. |
+| `midiPlayback.js` | Synth preview of a transcribed `.mid` (#2490) — `createMidiPlayer(data, { onEnded })` plays the `parseMidiFile` view-model as velocity-scaled oscillator tones through a per-play master bus on the shared `AudioContext`, with the same lookahead-scheduler idiom + tone envelope (`scheduleTone`) as `scorePlayback.js`. Transport: `play`/`pause`/`stop`/`seek(sec)` (seek re-anchors a running transport and sounds the tails of notes sustaining across the seek point) and `position()` for the `<MidiPianoRoll>` moving playhead. Pure (no React) — `useMidiPlayer` wraps it. |
| `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. |
+| `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. |
| `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/audioContext.js b/client/src/lib/audioContext.js
index b6eac24ea5..b155c1fd22 100644
--- a/client/src/lib/audioContext.js
+++ b/client/src/lib/audioContext.js
@@ -1,16 +1,20 @@
-// The ONE app-wide Web Audio AudioContext, created lazily on first use.
-// Browsers cap the number of live contexts (~6), and every playback feature
-// sharing a single context also shares a single sample clock — so features
-// that sound together (metronome + score synth, MIDI preview over a round)
-// stay aligned for free. Consumed by songPlayback.js, scorePlayback.js,
-// metronome.js, and midiPlayback.js — new audio features should import this
-// instead of growing another module-level singleton.
+// The shared lazy Web Audio AudioContext for the song-system playback stack
+// (songPlayback, scorePlayback, metronome, midiPlayback). Browsers cap the
+// number of live contexts (~6), and modules sharing one context also share
+// one sample clock — so features that sound together (metronome + score
+// synth, MIDI preview) stay aligned for free. New audio features should
+// import this instead of growing another module-level singleton.
//
-// The constructor is resolved lazily and never touches a bare `window` at
-// module load — the server's vitest run globs lib tests in the node
-// environment (no jsdom), where `window` is undefined. Tests inject a fake
-// via vi.stubGlobal('AudioContext', …) before the first call; the singleton
-// then caches that fake for the life of the test file's module registry.
+// Known holdouts, on purpose: components/city/audio/cityAudioEngine.js keeps
+// its own context (it owns a persistent gain graph and its own — differently
+// contracted — getAudioContext export), and MorseTrainer creates a per-mount
+// context it close()s on unmount, which would kill a shared one for everyone
+// else. Migrate those only with their graphs/lifecycles in mind.
+//
+// The constructor is resolved lazily so importing this module never touches
+// audio APIs at load time (node-env test runs import it cleanly). Tests
+// inject a fake via vi.stubGlobal('AudioContext', …) before the first call;
+// the singleton then caches that fake for the test file's module registry.
let sharedCtx = null;
@@ -20,10 +24,7 @@ let sharedCtx = null;
*/
export function getAudioContext() {
if (!sharedCtx) {
- const Ctor =
- (typeof window !== 'undefined' && (window.AudioContext || window.webkitAudioContext)) ||
- globalThis.AudioContext ||
- globalThis.webkitAudioContext;
+ const Ctor = globalThis.AudioContext || globalThis.webkitAudioContext;
sharedCtx = new Ctor();
}
return sharedCtx;
diff --git a/client/src/lib/midiPlayback.js b/client/src/lib/midiPlayback.js
index 706fa1a8cf..ef6f3ec4c4 100644
--- a/client/src/lib/midiPlayback.js
+++ b/client/src/lib/midiPlayback.js
@@ -7,20 +7,10 @@
// Pure (no React) — useMidiPlayer wraps it in a hook.
import { getAudioContext as ctx } from './audioContext.js';
-import { scheduleTone, midiToFreq } from './scorePlayback.js';
-
-// Guard a UI callback that fires from a setInterval tick — an uncaught throw
-// there has no request boundary to bubble to and would leave the scheduler
-// interval orphaned. (CLAUDE.md: wrap non-request-lifecycle callbacks.)
-const safeCall = (cb, ...args) => {
- if (typeof cb !== 'function') return;
- try { cb(...args); }
- catch (err) { console.error(`🎹 MIDI playback callback failed: ${err.message}`); }
-};
+import { scheduleTone, midiToFreq, makeSafeCall, SYNTH_TIMING } from './scorePlayback.js';
-const LEAD = 0.08; // seconds of lead-in before t=0 sounds
-const LOOKAHEAD_MS = 25; // how often the scheduler wakes
-const SCHEDULE_AHEAD = 0.12; // seconds of audio scheduled past "now"
+const safeCall = makeSafeCall('MIDI playback');
+const { LEAD, LOOKAHEAD_MS, 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)
@@ -36,7 +26,7 @@ const MASTER_GAIN = 0.9;
* notes are sorted by startSec, which the scheduler cursor relies on.
* @param {object} [options]
* @param {()=>void} [options.onEnded] — called once when playback reaches the end.
- * @returns {{ play, pause, stop, seek, isPlaying, position, duration }}
+ * @returns {{ play, pause, stop, seek, isPlaying, position }}
*/
export const createMidiPlayer = (data, options = {}) => {
const { onEnded } = options;
@@ -75,11 +65,11 @@ export const createMidiPlayer = (data, options = {}) => {
};
// Position the scheduler cursor at the first note starting at/after `offset`,
- // and immediately sound the tails of notes already sustaining across it —
- // seeking into a held chord should be audible, not silent until the next
- // 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 } = {}) => {
+ // 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. 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) => {
let idx = notes.findIndex((n) => n.startSec >= offset - 1e-6);
if (idx < 0) idx = notes.length;
nextIdx = idx;
@@ -130,7 +120,7 @@ export const createMidiPlayer = (data, options = {}) => {
playing = true;
startTime = c.currentTime + LEAD - offsetSec;
- seekCursors(offsetSec, { soundTails: offsetSec > 0 });
+ seekCursors(offsetSec, offsetSec > 0);
tick(); // schedule the immediate window now so playback starts promptly
interval = setInterval(tick, LOOKAHEAD_MS);
};
@@ -165,7 +155,7 @@ export const createMidiPlayer = (data, options = {}) => {
if (!playing) { offsetSec = clamped; return; }
stopNodes();
startTime = ctx().currentTime - clamped;
- seekCursors(clamped, { soundTails: true });
+ seekCursors(clamped, true);
tick();
};
@@ -183,6 +173,5 @@ export const createMidiPlayer = (data, options = {}) => {
seek,
isPlaying: () => playing,
position,
- duration: () => totalSec,
};
};
diff --git a/client/src/lib/midiPlayback.test.js b/client/src/lib/midiPlayback.test.js
index a18e05713f..68ff02c84f 100644
--- a/client/src/lib/midiPlayback.test.js
+++ b/client/src/lib/midiPlayback.test.js
@@ -1,39 +1,11 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createMidiPlayer } from './midiPlayback.js';
+import { createFakeAudio } from '../test/fakeAudioContext.js';
-// jsdom/node has no Web Audio. Same fake as scorePlayback.test.js: records
-// created oscillators + gain envelopes and exposes a controllable clock so the
-// lookahead scheduler can be driven deterministically with fake timers.
-const audio = { now: 0, oscillators: [], gains: [] };
-const fakeParam = () => {
- const values = [];
- return {
- values,
- setValueAtTime: (v) => values.push(v),
- exponentialRampToValueAtTime: (v) => values.push(v),
- };
-};
-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() {
- const gain = { gain: fakeParam(), connect: (t) => t };
- audio.gains.push(gain);
- return gain;
- },
- };
-}
+// Shared Web Audio fake (controllable clock + recorded oscillators/gains) so
+// the lookahead scheduler can be driven deterministically with fake timers.
+// One pair for the whole file — lib/audioContext.js caches the context.
+const { FakeAudioContext, audio } = createFakeAudio();
// Advance the audio clock RELATIVELY (unlike scorePlayback.test.js's absolute
// drive) — several cases here pause/seek and drive again, and an absolute
@@ -59,9 +31,7 @@ const DATA = {
describe('createMidiPlayer', () => {
beforeEach(() => {
- audio.now = 0;
- audio.oscillators = [];
- audio.gains = [];
+ audio.reset();
vi.stubGlobal('AudioContext', FakeAudioContext);
vi.useFakeTimers();
});
diff --git a/client/src/lib/scorePlayback.js b/client/src/lib/scorePlayback.js
index 53e6e8f95b..35f3289ac1 100644
--- a/client/src/lib/scorePlayback.js
+++ b/client/src/lib/scorePlayback.js
@@ -88,15 +88,23 @@ export const buildSchedule = (score, bpmOverride) => {
// Guard a UI callback that fires from a setInterval tick — an uncaught throw
// there has no request boundary to bubble to and would leave the scheduler
// interval orphaned. (CLAUDE.md: wrap non-request-lifecycle callbacks.)
-const safeCall = (cb, ...args) => {
+// Exported as a factory so midiPlayback.js shares the guard with its own
+// log prefix instead of duplicating the body.
+export const makeSafeCall = (label) => (cb, ...args) => {
if (typeof cb !== 'function') return;
try { cb(...args); }
- catch (err) { console.error(`🎹 score playback callback failed: ${err.message}`); }
+ catch (err) { console.error(`🎹 ${label} callback failed: ${err.message}`); }
};
-
-const LEAD = 0.08; // seconds of lead-in before beat 0 sounds
-const LOOKAHEAD_MS = 25; // how often the scheduler wakes
-const SCHEDULE_AHEAD = 0.12; // seconds of audio scheduled past "now"
+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;
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
diff --git a/client/src/test/fakeAudioContext.js b/client/src/test/fakeAudioContext.js
new file mode 100644
index 0000000000..23fa803de3
--- /dev/null
+++ b/client/src/test/fakeAudioContext.js
@@ -0,0 +1,51 @@
+// Minimal Web Audio fake for playback tests — jsdom/node have no Web Audio.
+// createFakeAudio() returns a fresh { FakeAudioContext, audio } pair: stub the
+// constructor with vi.stubGlobal('AudioContext', FakeAudioContext) and drive
+// `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.
+
+export const createFakeAudio = () => {
+ const audio = {
+ now: 0,
+ oscillators: [],
+ gains: [],
+ // Modules cache the shared AudioContext (lib/audioContext.js) across a
+ // 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; },
+ };
+ const fakeParam = () => {
+ const values = [];
+ return {
+ values,
+ setValueAtTime: (v) => values.push(v),
+ exponentialRampToValueAtTime: (v) => values.push(v),
+ };
+ };
+ 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() {
+ const gain = { gain: fakeParam(), connect: (t) => t };
+ audio.gains.push(gain);
+ return gain;
+ },
+ };
+ }
+ return { FakeAudioContext, audio };
+};