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

feat([issue-1025]): color-match playback grading sung notes against the score

Adam Eivy5e51c9e78649
diff --git a/client/src/components/songs/ColorMatch.jsx b/client/src/components/songs/ColorMatch.jsx
new file mode 100644
index 0000000000..6b3eb99b55
--- /dev/null
+++ b/client/src/components/songs/ColorMatch.jsx
@@ -0,0 +1,93 @@
+/**
+ * ColorMatch — sing the written melody and watch the score grade you in real
+ * time. While a vocal take is recording, this panel walks the notated score in
+ * tempo (after a one-bar metronome count-in) and colors each notehead by how
+ * accurately it was sung — green (in tune), yellow (close), red (off or missed)
+ * — then shows a per-take accuracy score for training.
+ *
+ * It is a thin shell over `useColorMatch` (which owns the timing/grading) and
+ * the pure <ScoreSheet> renderer (which just paints the `noteColors` it's
+ * handed). The grading mic is the SAME stream the recorder opened — no second
+ * getUserMedia. With no live take, the panel shows a hint to start recording.
+ *
+ * Colors and copy use `--port-*` theme tokens only; the layout is
+ * mobile-responsive (the controls wrap above the staff).
+ */
+
+import { useEffect, useMemo } from 'react';
+import { Target } from 'lucide-react';
+import { parseScore, scoreHasMusic } from '../../lib/scoreNotation.js';
+import useColorMatch from '../../hooks/useColorMatch.js';
+import ScoreSheet from './ScoreSheet.jsx';
+
+// Summary bucket → readout color token, matching the notehead grades.
+const BUCKET_TONE = {
+ 'in-tune': 'text-port-success',
+ close: 'text-port-warning',
+ off: 'text-port-error',
+ missed: 'text-port-error',
+};
+
+export default function ColorMatch({ score = '', stream = null, tempo = null }) {
+ const hasMusic = useMemo(() => scoreHasMusic(score), [score]);
+ const parsed = useMemo(() => parseScore(score), [score]);
+ const bpm = Number.isFinite(tempo) && tempo > 0 ? tempo : null;
+
+ const { running, countingIn, noteColors, summary, activeIndex, start } = useColorMatch({
+ score: parsed,
+ stream,
+ bpm,
+ });
+
+ // Auto-arm: the moment a take starts (stream appears) and the score has notes,
+ // begin a color-match run so the singer is graded as they record. Stop when the
+ // take ends. The hook also stops itself when the stream vanishes mid-run.
+ useEffect(() => {
+ if (stream && hasMusic && !running) start();
+ // start/stop are stable from the hook; we only react to stream/hasMusic.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [stream, hasMusic]);
+
+ if (!hasMusic) return null;
+
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center justify-between gap-2 flex-wrap mb-2">
+ <h3 className="flex items-center gap-2 text-sm font-semibold text-white">
+ <Target size={15} className="text-port-accent" /> Color-match
+ {countingIn && <span className="text-xs font-normal text-port-warning">● counting in…</span>}
+ {running && !countingIn && <span className="text-xs font-normal text-port-error">● grading</span>}
+ </h3>
+ {summary && !running && (
+ <span className="text-xs text-gray-300" aria-live="polite">
+ <span className={`font-semibold ${summary.percentInTune >= 80 ? 'text-port-success' : summary.percentInTune >= 50 ? 'text-port-warning' : 'text-port-error'}`}>
+ {summary.percentInTune}%
+ </span>{' '}
+ in tune
+ <span className="text-gray-500"> · {summary.graded} {summary.graded === 1 ? 'note' : 'notes'} sung</span>
+ </span>
+ )}
+ </div>
+
+ {!stream && !summary && (
+ <p className="text-xs text-gray-500 mb-2">
+ Press “Record take” above and sing along — each note lights up green, yellow, or red as you hit it.
+ </p>
+ )}
+
+ <ScoreSheet text={score} controls={false} noteColors={noteColors} activeNoteIndex={activeIndex} />
+
+ {summary && !running && summary.graded > 0 && (
+ <div className="flex flex-wrap gap-x-4 gap-y-1 mt-2 text-xs">
+ {['in-tune', 'close', 'off', 'missed'].map((b) => (
+ summary.counts[b] > 0 && (
+ <span key={b} className={BUCKET_TONE[b]}>
+ {summary.counts[b]} {b === 'in-tune' ? 'in tune' : b}
+ </span>
+ )
+ ))}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/songs/ScoreSheet.jsx b/client/src/components/songs/ScoreSheet.jsx
index 74996ee8d3..c1e25adace 100644
--- a/client/src/components/songs/ScoreSheet.jsx
+++ b/client/src/components/songs/ScoreSheet.jsx
@@ -63,6 +63,16 @@ const INK = 'rgb(var(--port-text))';
// The currently-sounding note (playhead) is painted in the theme accent so it
// reads as the foreground against the neutral-ink staff, in both day and dark.
const ACTIVE = 'rgb(var(--port-accent))';
+// Color-match grade → notehead ink (theme tokens only). The grading lib
+// (colorMatch.js) emits these level strings; the renderer stays pure by just
+// mapping a passed grade to its color. Absent / `pending` grades fall through to
+// the default ink so an un-sung note looks normal.
+const GRADE_INK = {
+ 'in-tune': 'rgb(var(--port-success))',
+ close: 'rgb(var(--port-warning))',
+ off: 'rgb(var(--port-error))',
+ missed: 'rgb(var(--port-error))',
+};
const STAFF = 'rgb(var(--port-text-muted) / 0.55)';
const CHORD = 'rgb(var(--port-accent))';
const LYRIC = 'rgb(var(--port-text-muted))';
@@ -135,7 +145,7 @@ const rowLyricOffset = (row, bottomLineStep) => {
return Math.max(LYRIC_MIN_BELOW_STAFF, belowStaffPx + LYRIC_BELOW_NOTE);
};
-export default function ScoreSheet({ text, className = '', controls = true, activeNoteIndex = null }) {
+export default function ScoreSheet({ text, className = '', controls = true, activeNoteIndex = null, noteColors = null }) {
const score = useMemo(() => parseScore(text), [text]);
// --- Reference-tone playback (synthesize the written melody) ---------------
@@ -285,7 +295,13 @@ export default function ScoreSheet({ text, className = '', controls = true, acti
const cx = cursor + slot / 2;
cursor += slot;
const key = `m${index}-n${ni}`;
- const ink = noteCounter === highlight ? ACTIVE : INK;
+ // Ink precedence: the live playhead (accent) wins on the active note;
+ // otherwise a color-match grade (green/yellow/red) paints the head; else
+ // default ink. `noteColors` is keyed by the same global note index.
+ const grade = noteColors?.[noteCounter];
+ const ink = noteCounter === highlight
+ ? ACTIVE
+ : (GRADE_INK[grade] || INK);
noteCounter += 1;
if (note.rest) {
els.push(...renderRest(note, cx, yForStep, bottomLineStep, key, ink));
diff --git a/client/src/components/songs/ScoreSheet.test.jsx b/client/src/components/songs/ScoreSheet.test.jsx
index 5afb7cb1d9..e0a2e4fda2 100644
--- a/client/src/components/songs/ScoreSheet.test.jsx
+++ b/client/src/components/songs/ScoreSheet.test.jsx
@@ -127,4 +127,41 @@ describe('ScoreSheet renderer', () => {
);
expect(lit).toMatch(/<ellipse[^>]*fill:rgb\(var\(--port-accent\)\)/);
});
+
+ it('paints color-match grades on noteheads via theme success/warning/error tokens', () => {
+ // noteColors maps global note index → grade. Index 0 in tune (green),
+ // index 1 close (yellow), index 2 off (red).
+ const graded = renderToStaticMarkup(
+ <ScoreSheet
+ text={FIVE_HUNDRED_MILES}
+ controls={false}
+ noteColors={{ 0: 'in-tune', 1: 'close', 2: 'off' }}
+ />,
+ );
+ expect(graded).toMatch(/<ellipse[^>]*fill:rgb\(var\(--port-success\)\)/);
+ expect(graded).toMatch(/<ellipse[^>]*fill:rgb\(var\(--port-warning\)\)/);
+ expect(graded).toMatch(/<ellipse[^>]*fill:rgb\(var\(--port-error\)\)/);
+ // Still only theme tokens — no hardcoded hex sneaks in via grading.
+ expect(graded).not.toMatch(/#[0-9a-fA-F]{6}/);
+ });
+
+ it('does not paint grade colours when noteColors is absent', () => {
+ const plain = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} controls={false} />);
+ expect(plain).not.toMatch(/<ellipse[^>]*fill:rgb\(var\(--port-success\)\)/);
+ expect(plain).not.toMatch(/<ellipse[^>]*fill:rgb\(var\(--port-warning\)\)/);
+ });
+
+ it('lets the live playhead (accent) win over a grade on the active note', () => {
+ // Note 0 is both graded in-tune AND the active playhead — accent wins so the
+ // singer can still see where they are in the score.
+ const html = renderToStaticMarkup(
+ <ScoreSheet
+ text={FIVE_HUNDRED_MILES}
+ controls={false}
+ noteColors={{ 0: 'in-tune' }}
+ activeNoteIndex={0}
+ />,
+ );
+ expect(html).toMatch(/<ellipse[^>]*fill:rgb\(var\(--port-accent\)\)/);
+ });
});
diff --git a/client/src/components/songs/SongRecordings.jsx b/client/src/components/songs/SongRecordings.jsx
index b523a3fcdf..7b7da46671 100644
--- a/client/src/components/songs/SongRecordings.jsx
+++ b/client/src/components/songs/SongRecordings.jsx
@@ -22,6 +22,7 @@ import { uploadFile, getUploadUrl } from '../../services/api';
import { formatDurationMs } from '../../utils/formatters';
import Metronome from './Metronome';
import PitchTuner from './PitchTuner';
+import ColorMatch from './ColorMatch';
// Lower bound peak amplitude — below this the take is effectively silence
// (dead mic / muted input), worth warning about before it joins the stack.
@@ -190,6 +191,13 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
<PitchTuner stream={liveStream} />
</div>
+ {/* Color-match — walks the written score in tempo while recording and
+ grades each note by sung accuracy. Only shows when the song has a
+ notated melody to sing against. */}
+ <div className="mb-3">
+ <ColorMatch score={score} stream={liveStream} tempo={tempo} />
+ </div>
+
{/* Layer the next take targets (optional) */}
{layers.length > 0 && !recording && (
<div className="mb-3">
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index f13b70301c..05682de4db 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -113,6 +113,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useCityData` | CyberCity environment data + physics. | CyberCity only. |
| `useCityPlayback` | Timeline-scrubber transport: loads the snapshot series, steps a frame index, play/pause/speed. | CyberCity playback (history) mode only. |
| `useCitySettings` | CyberCity quality presets + persistence. | CyberCity only. |
+| `useColorMatch` | Drives a song color-match run: counts the singer in with the metronome, walks the notated score in tempo, grades each note against the live mic pitch (#1022 tracker + colorMatch lib), and exposes `{ running, countingIn, noteColors, summary, activeIndex, start, stop }` for the `<ScoreSheet>` + an accuracy readout. Taps the passed recording stream (no second mic); tears down on stop/unmount. | The Song editor's color-match panel. Don't re-wire the metronome + tracker + grading loop by hand. |
| `useCodeReviewDefaults` | Global Code Review Defaults (Review Loop reviewer chain + per-backend local-LLM model) via a small Provider/hook pair. | TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. |
| `useCatalogTypes` | Catalog ingredient type registry (system + user-defined) merged with the static fallback via a Provider/hook pair; synchronous fallback to the built-in six so first render never blanks. | Catalog list/picker/editor; anywhere the catalog type list/lookup is needed. |
| `useDeathClock` | 1-second countdown for death-clock display. | Mortality / death-clock surfaces. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index a536051e79..bc564dc027 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -10,6 +10,7 @@
// === Default-exporting hooks (re-exported as named) ===
export { default as useCityAudio } from './useCityAudio.js';
export { default as useClickOutside } from './useClickOutside.js';
+export { default as useColorMatch } from './useColorMatch.js';
export { default as useContainerWidth } from './useContainerWidth.js';
export { default as useEscapeKey } from './useEscapeKey.js';
export { default as useFieldDraft } from './useFieldDraft.js';
diff --git a/client/src/hooks/useColorMatch.js b/client/src/hooks/useColorMatch.js
new file mode 100644
index 0000000000..1ccee08f09
--- /dev/null
+++ b/client/src/hooks/useColorMatch.js
@@ -0,0 +1,176 @@
+// useColorMatch — drives a color-match session: count the singer in with the
+// metronome, walk the notated score in tempo, grade each note against the live
+// mic pitch, and expose `noteColors` for the <ScoreSheet> plus a per-take
+// accuracy summary for training mode.
+//
+// It composes the three song-system primitives without re-implementing any of
+// them: the metronome (#1024) for the count-in + a shared audio clock, the pitch
+// tracker (#1022) for live frequency, and the pure colorMatch lib (#1025) for the
+// timeline + grading math. The component owns only React state + lifecycle here;
+// all the timing math is in colorMatch.js so it stays testable.
+//
+// Lifecycle: `start()` builds the timeline, opens an analyser off the passed
+// stream, starts the metronome with a one-bar count-in, and — at the count-in's
+// downbeat — kicks a rAF loop that reads elapsed audio time, finds the active
+// note, grades it, and accumulates the best grade per note (a note "wins" its
+// best attempt across the frames it's active). Everything tears down on stop and
+// on unmount (the deferred-work teardown rule in CLAUDE.md).
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { createStreamAnalyser } from '../lib/audioRecorder.js';
+import { createPitchTracker } from '../lib/pitchDetect.js';
+import { createMetronome, timeSignatureFromScore } from '../lib/metronome.js';
+import {
+ buildColorMatchTimeline,
+ noteAtTime,
+ gradeNote,
+ summarizeAccuracy,
+ GRADE,
+} from '../lib/colorMatch.js';
+import useMounted from './useMounted.js';
+
+// Rank grades so a note keeps the BEST attempt it was hit with across the frames
+// it's active — a singer who slides into pitch shouldn't be graded on the wobble
+// they started with. Higher rank = better.
+const GRADE_RANK = { [GRADE.MISSED]: 0, [GRADE.OFF]: 1, [GRADE.CLOSE]: 2, [GRADE.IN_TUNE]: 3 };
+const bestGrade = (a, b) => ((GRADE_RANK[b] ?? 0) > (GRADE_RANK[a] ?? -1) ? b : a);
+
+/**
+ * @param {object} args
+ * @param {object} args.score — parsed score (parseScore output).
+ * @param {MediaStream|null} args.stream — live mic stream to grade against.
+ * @param {number} [args.bpm] — tempo override (else score.tempo).
+ * @param {number} [args.countInBars=1] — lead-in bars before grading starts.
+ * @param {number} [args.a4=440] — reference pitch.
+ * @returns {{ running, countingIn, beat, noteColors, summary, activeIndex, start, stop }}
+ */
+export default function useColorMatch({ score, stream, bpm = null, countInBars = 1, a4 = 440 }) {
+ const [running, setRunning] = useState(false);
+ const [countingIn, setCountingIn] = useState(false);
+ const [beat, setBeat] = useState(null); // latest beat descriptor (count-in pulse)
+ const [noteColors, setNoteColors] = useState({}); // noteIndex → GRADE (drives the staff)
+ const [activeIndex, setActiveIndex] = useState(null);
+ const [summary, setSummary] = useState(null);
+
+ const mountedRef = useMounted();
+ const metronomeRef = useRef(null);
+ const trackerRef = useRef(null);
+ const analyserRef = useRef(null);
+ const timelineRef = useRef(null);
+ const startAudioTimeRef = useRef(null); // metronome audio time of the first music beat
+ const pitchRef = useRef({ hz: null }); // latest tracked pitch, read each rAF frame
+ const gradesRef = useRef({}); // mutable accumulator; flushed to state
+ const cursorRef = useRef(0); // lower-bound index hint for noteAtTime
+ const rafRef = useRef(null);
+
+ // Tear down the audio graph, tracker, metronome, and rAF loop. Idempotent.
+ const teardown = useCallback(() => {
+ if (rafRef.current != null && typeof cancelAnimationFrame === 'function') {
+ cancelAnimationFrame(rafRef.current);
+ }
+ rafRef.current = null;
+ if (metronomeRef.current) { metronomeRef.current.stop(); metronomeRef.current = null; }
+ if (trackerRef.current) { trackerRef.current.stop(); trackerRef.current = null; }
+ if (analyserRef.current) { analyserRef.current.close(); analyserRef.current = null; }
+ startAudioTimeRef.current = null;
+ pitchRef.current = { hz: null };
+ cursorRef.current = 0;
+ }, []);
+
+ // Stop a session: finalize the accuracy summary from whatever was graded, then
+ // tear the audio graph down. Keeps the painted `noteColors` so the singer sees
+ // their last result.
+ const stop = useCallback(() => {
+ teardown();
+ if (!mountedRef.current) return;
+ setSummary(summarizeAccuracy(gradesRef.current));
+ setRunning(false);
+ setCountingIn(false);
+ setActiveIndex(null);
+ }, [teardown, mountedRef]);
+
+ // One animation frame while grading: read elapsed time off the metronome's
+ // audio clock, find the active note, grade the live pitch against it, keep the
+ // best grade for that note, and flush colors to state. Ends the session when
+ // the timeline is exhausted.
+ const grade = useCallback(() => {
+ const timeline = timelineRef.current;
+ const ctx = analyserRef.current?.context;
+ if (!timeline || !ctx || startAudioTimeRef.current == null) return;
+
+ const elapsedMs = (ctx.currentTime - startAudioTimeRef.current) * 1000;
+ if (elapsedMs >= timeline.totalMs) { stop(); return; }
+
+ const hit = noteAtTime(timeline, elapsedMs, cursorRef.current);
+ if (hit) {
+ cursorRef.current = hit.idx;
+ const g = gradeNote(pitchRef.current.hz, hit.note.targetHz);
+ const prev = gradesRef.current[hit.note.index] ?? GRADE.MISSED;
+ const next = bestGrade(prev, g);
+ if (next !== prev) {
+ gradesRef.current = { ...gradesRef.current, [hit.note.index]: next };
+ setNoteColors(gradesRef.current);
+ }
+ setActiveIndex((cur) => (cur === hit.note.index ? cur : hit.note.index));
+ } else {
+ setActiveIndex((cur) => (cur === null ? cur : null));
+ }
+ rafRef.current = requestAnimationFrame(grade);
+ }, [stop]);
+
+ // Start a session: requires a live mic stream and a score with notes.
+ const start = useCallback(() => {
+ if (!stream || running) return;
+ const timeline = buildColorMatchTimeline(score, { bpm, a4 });
+ if (!timeline.notes.length) return;
+
+ teardown();
+ gradesRef.current = {};
+ cursorRef.current = 0;
+ timelineRef.current = timeline;
+ setNoteColors({});
+ setSummary(null);
+ setActiveIndex(null);
+ setRunning(true);
+ setCountingIn(countInBars > 0);
+
+ // Tap the SAME recording stream (no second getUserMedia) and start the live
+ // pitch tracker; it writes the latest pitch into a ref the rAF loop reads.
+ const graph = createStreamAnalyser(stream);
+ analyserRef.current = graph;
+ trackerRef.current = createPitchTracker(graph.analyser, {
+ a4,
+ onUpdate: (u) => { pitchRef.current = { hz: u.hz }; },
+ });
+
+ const ts = timeSignatureFromScore(score);
+ const metro = createMetronome({
+ bpm: timeline.bpm, // same resolved tempo the timeline was built at
+ beatsPerBar: ts.beats,
+ beatValue: ts.beatValue,
+ countInBars,
+ onBeat: (info) => { if (mountedRef.current) setBeat(info); },
+ onCountInComplete: (info) => {
+ // The first music downbeat — anchor the grading clock to this audio time
+ // and start the rAF loop. Use the same AudioContext the analyser reads so
+ // `currentTime` is on one clock.
+ if (!mountedRef.current) return;
+ setCountingIn(false);
+ startAudioTimeRef.current = info.whenAudioTime;
+ rafRef.current = requestAnimationFrame(grade);
+ },
+ });
+ metronomeRef.current = metro;
+ Promise.resolve(metro.start()).catch(() => { if (mountedRef.current) stop(); });
+ }, [stream, running, score, bpm, a4, countInBars, teardown, grade, stop, mountedRef]);
+
+ // A vanished stream (recording stopped) or score change ends an active session.
+ useEffect(() => {
+ if (running && !stream) stop();
+ }, [stream, running, stop]);
+
+ // Tear everything down on unmount.
+ useEffect(() => () => teardown(), [teardown]);
+
+ return { running, countingIn, beat, noteColors, summary, activeIndex, start, stop };
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 58a6d8dabe..d2336a37ed 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -87,6 +87,7 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
+| `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune }` per-take summary; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. |
| `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. |
| `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). |
| `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`. |
diff --git a/client/src/lib/colorMatch.js b/client/src/lib/colorMatch.js
new file mode 100644
index 0000000000..0ce3e7ed7b
--- /dev/null
+++ b/client/src/lib/colorMatch.js
@@ -0,0 +1,138 @@
+// Color-match — the grading core for the song system's "sing-to-the-score"
+// training mode. It walks the notated melody in tempo and judges how well a
+// singer hit each note, so the <ScoreSheet> can paint each notehead green
+// (in tune), yellow (close), or red (off / missed).
+//
+// This module is deliberately PURE (no React, no Web Audio): it builds the
+// note timeline from a parsed score + tempo, classifies a detected pitch
+// against a target note, and aggregates a per-take accuracy summary. The hook
+// (`useColorMatch`) owns the metronome clock + pitch tracker and feeds grades
+// in here; the renderer only consumes the resulting `noteColors` array. Keeping
+// the math here is what makes the grading unit-testable without a microphone.
+//
+// Timing mirrors `scorePlayback.buildSchedule` exactly (same global note index,
+// same `(60/bpm)·(beatValue/4)` quarter-beat duration) so a color-match cursor
+// lines up note-for-note with both the rendered staff and the reference-tone
+// playhead.
+
+import { noteToFrequency } from './scorePlayback.js';
+
+// Grade levels — the same three buckets the tuner uses (`pitchDetect.tuningQuality`),
+// plus `missed` (no clear pitch detected while the note was active). Exported so
+// the renderer and tests share one vocabulary instead of magic strings. `pending`
+// is the pre-grade state (note not yet sung) and carries no color.
+export const GRADE = {
+ IN_TUNE: 'in-tune',
+ CLOSE: 'close',
+ OFF: 'off',
+ MISSED: 'missed',
+ PENDING: 'pending',
+};
+
+// Cents-deviation thresholds for grading a sung note against its target. Wider
+// than the live tuner's (`pitchDetect.IN_TUNE_CENTS` = 5) because a sustained
+// sung note wobbles — a singer holding within ±25¢ is hitting the note for
+// training purposes, and ±50¢ (a quartertone) is the "close but flat/sharp"
+// band before it reads as the wrong note entirely.
+export const MATCH_IN_TUNE_CENTS = 25;
+export const MATCH_CLOSE_CENTS = 50;
+
+// Cents between two frequencies: 1200·log2(f/target). Positive = the sung pitch
+// is sharp of the target. Returns null when either frequency is missing.
+export const centsBetween = (hz, targetHz) => {
+ if (!Number.isFinite(hz) || hz <= 0 || !Number.isFinite(targetHz) || targetHz <= 0) return null;
+ return 1200 * Math.log2(hz / targetHz);
+};
+
+// Classify a detected frequency against a target note's frequency into a GRADE.
+// Folds octave errors onto the nearest octave first (`% 1200` distance) so a
+// singer an octave low still grades on pitch-class accuracy — common for vocal
+// ranges that don't reach the written octave. A null/absent detected pitch is
+// `MISSED`. Pure + side-effect-free so the thresholds are unit-testable.
+export const gradeNote = (hz, targetHz) => {
+ const rawCents = centsBetween(hz, targetHz);
+ if (rawCents == null) return GRADE.MISSED;
+ // Fold onto [-600, 600] so an octave (or N octaves) off collapses to its
+ // pitch-class deviation — singing C3 against a written C5 is "in tune".
+ let cents = ((rawCents % 1200) + 1200) % 1200;
+ if (cents > 600) cents -= 1200;
+ const abs = Math.abs(cents);
+ if (abs <= MATCH_IN_TUNE_CENTS) return GRADE.IN_TUNE;
+ if (abs <= MATCH_CLOSE_CENTS) return GRADE.CLOSE;
+ return GRADE.OFF;
+};
+
+// Build the color-match timeline from a parsed score (parseScore output) + tempo.
+// Walks the score in the SAME order scorePlayback.buildSchedule does, assigning
+// each NON-rest note a global note index (matching the renderer's flatten order),
+// a target frequency, and an onset/offset window in milliseconds. Rests advance
+// the clock but produce no timeline entry — the singer isn't graded on silence.
+//
+// `beatValue` from the time signature makes a quarter-beat last
+// (60000/bpm)·(beatValue/4) ms, so 4/4 reads quarter=bpm and 6/8 reads
+// eighth=bpm — the same interpretation as scorePlayback.
+//
+// Returns `{ notes, totalMs, msPerQuarter, bpm }` where each note is
+// `{ index, targetHz, startMs, endMs, durBeats }`. `index` is the GLOBAL note
+// index (rests included in the count) so it indexes the renderer's notehead
+// array directly. `bpm` is the resolved tempo (override → score.tempo → 90) so
+// the metronome and the timeline share one clock.
+export const buildColorMatchTimeline = (score, { bpm, a4 = 440 } = {}) => {
+ const beatValue = score?.time?.beatValue || 4;
+ const tempo = Number.isFinite(bpm) && bpm > 0
+ ? bpm
+ : (Number.isFinite(score?.tempo) && score.tempo > 0 ? score.tempo : 90);
+ const msPerQuarter = (60000 / tempo) * (beatValue / 4);
+
+ const notes = [];
+ let beat = 0;
+ let index = 0;
+ for (const measure of score?.measures || []) {
+ for (const note of measure?.notes || []) {
+ const durBeats = note.duration?.beats || 0;
+ if (!note.rest) {
+ notes.push({
+ index,
+ targetHz: noteToFrequency(note.pitch, { a4 }),
+ startMs: beat * msPerQuarter,
+ endMs: (beat + durBeats) * msPerQuarter,
+ durBeats,
+ });
+ }
+ beat += durBeats;
+ index += 1;
+ }
+ }
+ return { notes, totalMs: beat * msPerQuarter, msPerQuarter, bpm: tempo };
+};
+
+// Find the timeline note active at elapsed time `tMs` (its window contains tMs),
+// or null in a rest / past the end. The timeline is ordered, so a small linear
+// scan from a hint index keeps this cheap inside a rAF loop without re-scanning
+// from 0 each frame. `fromIdx` is a lower bound the caller can advance.
+export const noteAtTime = (timeline, tMs, fromIdx = 0) => {
+ const notes = timeline?.notes || [];
+ for (let i = Math.max(0, fromIdx); i < notes.length; i += 1) {
+ const n = notes[i];
+ if (tMs < n.startMs) return null; // in a gap/rest before this note
+ if (tMs < n.endMs) return { note: n, idx: i };
+ }
+ return null;
+};
+
+// Aggregate per-note grades into a take summary for training mode. `grades` is a
+// map (or array) of noteIndex → GRADE for the notes that were walked. Counts a
+// note "in tune" only for GRADE.IN_TUNE; `percentInTune` is over the GRADED
+// notes (PENDING/un-sung notes are excluded so a stopped-early take isn't
+// penalized for notes it never reached). Returns counts per bucket + the
+// percentage, all derived — no side effects.
+export const summarizeAccuracy = (grades) => {
+ const values = Array.isArray(grades)
+ ? grades.filter((g) => g && g !== GRADE.PENDING)
+ : Object.values(grades || {}).filter((g) => g && g !== GRADE.PENDING);
+ const counts = { 'in-tune': 0, close: 0, off: 0, missed: 0 };
+ for (const g of values) if (g in counts) counts[g] += 1;
+ const graded = values.length;
+ const percentInTune = graded > 0 ? Math.round((counts['in-tune'] / graded) * 100) : 0;
+ return { graded, counts, percentInTune };
+};
diff --git a/client/src/lib/colorMatch.test.js b/client/src/lib/colorMatch.test.js
new file mode 100644
index 0000000000..a4317c622a
--- /dev/null
+++ b/client/src/lib/colorMatch.test.js
@@ -0,0 +1,157 @@
+import { describe, it, expect } from 'vitest';
+import { parseScore } from './scoreNotation.js';
+import { noteToFrequency } from './scorePlayback.js';
+import {
+ buildColorMatchTimeline,
+ noteAtTime,
+ gradeNote,
+ centsBetween,
+ summarizeAccuracy,
+ GRADE,
+ MATCH_IN_TUNE_CENTS,
+ MATCH_CLOSE_CENTS,
+} from './colorMatch.js';
+
+// A short, known score: four quarter notes in 4/4 at 120 BPM. At 120 BPM a
+// quarter beat is 500 ms, so onsets land at 0/500/1000/1500 ms and the take is
+// 2000 ms long.
+const FOUR_QUARTERS = ['time: 4/4', 'tempo: 120', '| C4q D4q E4q F4q |'].join('\n');
+
+describe('buildColorMatchTimeline', () => {
+ it('converts note durations to onset/offset windows in ms at the score tempo', () => {
+ const tl = buildColorMatchTimeline(parseScore(FOUR_QUARTERS));
+ expect(tl.bpm).toBe(120);
+ expect(tl.msPerQuarter).toBe(500);
+ expect(tl.totalMs).toBe(2000);
+ expect(tl.notes.map((n) => [n.startMs, n.endMs])).toEqual([
+ [0, 500], [500, 1000], [1000, 1500], [1500, 2000],
+ ]);
+ });
+
+ it('honors a bpm override over the score tempo', () => {
+ const tl = buildColorMatchTimeline(parseScore(FOUR_QUARTERS), { bpm: 60 });
+ expect(tl.bpm).toBe(60);
+ expect(tl.msPerQuarter).toBe(1000); // half the speed → double the ms
+ expect(tl.totalMs).toBe(4000);
+ });
+
+ it('honors the time-signature denominator (6/8 → eighth = bpm)', () => {
+ // 6/8 at 120 BPM: a quarter-beat lasts (60000/120)·(8/4) = 1000 ms.
+ const tl = buildColorMatchTimeline(parseScore('time: 6/8\ntempo: 120\n| C4q |'));
+ expect(tl.msPerQuarter).toBe(1000);
+ });
+
+ it('skips rests but keeps the GLOBAL note index so it lines up with the renderer', () => {
+ // index 0 = C4q, index 1 = rq (rest, no timeline entry), index 2 = D4q.
+ const tl = buildColorMatchTimeline(parseScore('time: 4/4\ntempo: 120\n| C4q rq D4q |'));
+ expect(tl.notes.map((n) => n.index)).toEqual([0, 2]);
+ // The rest still advanced the clock, so D4 starts at 1000 ms (2 quarters in).
+ expect(tl.notes[1].startMs).toBe(1000);
+ });
+
+ it('assigns each note its target frequency', () => {
+ const tl = buildColorMatchTimeline(parseScore(FOUR_QUARTERS));
+ const c4 = noteToFrequency({ letter: 'C', accidental: '', octave: 4 });
+ expect(tl.notes[0].targetHz).toBeCloseTo(c4, 5);
+ });
+});
+
+describe('centsBetween', () => {
+ it('is 0 at unison, +100 a semitone up, −100 a semitone down', () => {
+ expect(centsBetween(440, 440)).toBeCloseTo(0, 5);
+ expect(centsBetween(440 * Math.pow(2, 1 / 12), 440)).toBeCloseTo(100, 2);
+ expect(centsBetween(440 / Math.pow(2, 1 / 12), 440)).toBeCloseTo(-100, 2);
+ });
+
+ it('returns null for missing/invalid frequencies', () => {
+ expect(centsBetween(null, 440)).toBeNull();
+ expect(centsBetween(440, 0)).toBeNull();
+ expect(centsBetween(NaN, 440)).toBeNull();
+ });
+});
+
+describe('gradeNote', () => {
+ const target = 440; // A4
+
+ it('grades dead-on as in-tune', () => {
+ expect(gradeNote(440, target)).toBe(GRADE.IN_TUNE);
+ });
+
+ it('grades just inside the in-tune threshold as in-tune', () => {
+ const hz = target * Math.pow(2, (MATCH_IN_TUNE_CENTS - 1) / 1200);
+ expect(gradeNote(hz, target)).toBe(GRADE.IN_TUNE);
+ });
+
+ it('grades between the in-tune and close thresholds as close', () => {
+ const hz = target * Math.pow(2, ((MATCH_IN_TUNE_CENTS + MATCH_CLOSE_CENTS) / 2) / 1200);
+ expect(gradeNote(hz, target)).toBe(GRADE.CLOSE);
+ });
+
+ it('grades well past the close threshold as off', () => {
+ const hz = target * Math.pow(2, (MATCH_CLOSE_CENTS + 80) / 1200);
+ expect(gradeNote(hz, target)).toBe(GRADE.OFF);
+ });
+
+ it('grades a missing detected pitch as missed', () => {
+ expect(gradeNote(null, target)).toBe(GRADE.MISSED);
+ });
+
+ it('folds octave errors onto the nearest octave (singing an octave low still in tune)', () => {
+ expect(gradeNote(target / 2, target)).toBe(GRADE.IN_TUNE); // one octave down
+ expect(gradeNote(target * 2, target)).toBe(GRADE.IN_TUNE); // one octave up
+ expect(gradeNote(target / 4, target)).toBe(GRADE.IN_TUNE); // two octaves down
+ });
+});
+
+describe('noteAtTime', () => {
+ const tl = buildColorMatchTimeline(parseScore(FOUR_QUARTERS));
+
+ it('finds the note whose window contains the time', () => {
+ expect(noteAtTime(tl, 250)?.note.index).toBe(0);
+ expect(noteAtTime(tl, 700)?.note.index).toBe(1);
+ expect(noteAtTime(tl, 1999)?.note.index).toBe(3);
+ });
+
+ it('returns null past the end of the timeline', () => {
+ expect(noteAtTime(tl, 2500)).toBeNull();
+ });
+
+ it('returns null in a rest gap before a note (cursor hint respected)', () => {
+ const gapTl = buildColorMatchTimeline(parseScore('time: 4/4\ntempo: 120\n| C4q rq D4q |'));
+ // 700 ms is inside the rest (500–1000) — no note active.
+ expect(noteAtTime(gapTl, 700)).toBeNull();
+ });
+
+ it('respects the fromIdx lower-bound hint', () => {
+ // Starting the scan past note 0 won't re-find an earlier note.
+ expect(noteAtTime(tl, 250, 1)).toBeNull();
+ });
+});
+
+describe('summarizeAccuracy', () => {
+ it('computes percent in tune over graded notes, excluding pending', () => {
+ const grades = { 0: GRADE.IN_TUNE, 1: GRADE.IN_TUNE, 2: GRADE.CLOSE, 3: GRADE.OFF };
+ const s = summarizeAccuracy(grades);
+ expect(s.graded).toBe(4);
+ expect(s.counts).toEqual({ 'in-tune': 2, close: 1, off: 1, missed: 0 });
+ expect(s.percentInTune).toBe(50);
+ });
+
+ it('excludes pending (un-sung) notes from the denominator', () => {
+ const grades = { 0: GRADE.IN_TUNE, 1: GRADE.PENDING, 2: GRADE.PENDING };
+ const s = summarizeAccuracy(grades);
+ expect(s.graded).toBe(1);
+ expect(s.percentInTune).toBe(100);
+ });
+
+ it('accepts an array of grades too', () => {
+ const s = summarizeAccuracy([GRADE.IN_TUNE, GRADE.OFF]);
+ expect(s.graded).toBe(2);
+ expect(s.percentInTune).toBe(50);
+ });
+
+ it('returns 0% with no graded notes (avoids divide-by-zero)', () => {
+ expect(summarizeAccuracy({}).percentInTune).toBe(0);
+ expect(summarizeAccuracy([]).percentInTune).toBe(0);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 52403b01aa..cfebb05f62 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -55,6 +55,7 @@ export * from './voiceLabel.js';
// === Page-scoped pure helpers ===
export * from './cityPlaybackFrame.js';
+export * from './colorMatch.js';
export * from './metronome.js';
export * from './pitchDetect.js';
export * from './scoreNotation.js';