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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1026]): sing-to-score — transcribe a sung melody into the editor
Adam Eivy5a5a44610ae2
diff --git a/client/src/components/songs/SingToScore.jsx b/client/src/components/songs/SingToScore.jsxnew file mode 100644index 0000000000..dd11305bc0--- /dev/null+++ b/client/src/components/songs/SingToScore.jsx@@ -0,0 +1,133 @@+/**+ * SingToScore — sing a melody and draw the detected notes into the score editor.+ *+ * Workflow: press "Sing", get a one-bar count-in on the metronome (so you know+ * where beat 1 is), sing the phrase, press "Stop". The hook captures a pitch+ * track off the mic, segments it into notes, quantizes the durations to the song+ * tempo, spells the notes for the key, and emits lead-sheet notation. The result+ * renders in a live <ScoreSheet> preview (the same parser→renderer round-trip the+ * editor uses) so you can confirm it before inserting it — appended to the end of+ * the score, or replacing the current textarea selection.+ *+ * No notation/DSP library: it composes the existing pitch-detection core, the+ * metronome, the lead-sheet parser, and the ScoreSheet renderer.+ */++import { useMemo } from 'react';+import { Mic, Square, Plus, Replace, X } from 'lucide-react';+import ScoreSheet from './ScoreSheet.jsx';+import useSingToScore, { SING_IDLE, SING_COUNT_IN, SING_RECORDING } from '../../hooks/useSingToScore.js';+import { parseScore } from '../../lib/scoreNotation.js';++export default function SingToScore({ value = '', tempo = null, musicKey = 'C', hasSelection = false, onInsert }) {+ const { phase, beat, result, error, start, stop, reset } = useSingToScore({ tempo, score: value, musicKey });++ // The result is just the measure body; render it under the score's own header+ // (clef/key/time/tempo) so the preview staff matches what the inserted notes+ // will look like in context.+ const previewText = useMemo(() => {+ if (!result) return '';+ const parsed = parseScore(value || '');+ const header = [+ `clef: ${parsed.clef}`,+ `key: ${parsed.key}`,+ `time: ${parsed.time.beats}/${parsed.time.beatValue}`,+ parsed.tempo != null ? `tempo: ${parsed.tempo}` : null,+ ].filter(Boolean).join('\n');+ return `${header}\n\n${result}`;+ }, [result, value]);++ const previewHasMusic = useMemo(+ () => (previewText ? parseScore(previewText).measures.some((m) => m.notes.length > 0) : false),+ [previewText],+ );++ const recording = phase !== SING_IDLE;++ const insert = (mode) => {+ if (!result) return;+ onInsert?.(result, mode);+ reset();+ };++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-3">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <h3 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Mic size={15} className="text-port-accent" /> Sing to score+ {phase === SING_COUNT_IN && <span className="text-xs font-normal text-port-warning">● count-in {beat ?? ''}</span>}+ {phase === SING_RECORDING && <span className="text-xs font-normal text-port-error">● singing… beat {beat ?? ''}</span>}+ </h3>+ {recording ? (+ <button+ type="button"+ onClick={stop}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-error text-white hover:bg-port-error/90"+ >+ <Square size={14} /> Stop+ </button>+ ) : (+ <button+ type="button"+ onClick={start}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90"+ title="Count in, then sing a phrase — the notes are transcribed for review"+ >+ <Mic size={14} /> Sing+ </button>+ )}+ </div>++ <p className="text-xs text-gray-500 mt-2">+ {recording+ ? phase === SING_COUNT_IN+ ? 'Counting you in — start on beat 1.'+ : 'Sing your melody now, then press Stop.'+ : 'Records a melody and transcribes it at the song tempo. Review the staff below before inserting.'}+ </p>++ {error && <p className="mt-2 text-xs text-port-error">{error}</p>}++ {/* Transcribed result — live preview + insert controls. */}+ {result != null && !recording && (+ result && previewHasMusic ? (+ <div className="mt-3 space-y-2">+ <div className="bg-port-bg border border-port-border rounded-lg p-3 overflow-x-auto">+ <ScoreSheet text={previewText} />+ </div>+ <pre className="text-xs text-gray-400 font-mono whitespace-pre-wrap break-words bg-port-bg border border-port-border rounded-lg p-2">{result}</pre>+ <div className="flex items-center gap-2 flex-wrap">+ <button+ type="button"+ onClick={() => insert('append')}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90"+ >+ <Plus size={14} /> Append to score+ </button>+ <button+ type="button"+ onClick={() => insert('replace')}+ disabled={!hasSelection}+ title={hasSelection ? 'Replace the selected notation' : 'Select text in the editor to replace it'}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-40"+ >+ <Replace size={14} /> Replace selection+ </button>+ <button+ type="button"+ onClick={reset}+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg text-gray-400 hover:text-white"+ >+ <X size={14} /> Discard+ </button>+ </div>+ </div>+ ) : (+ <p className="mt-3 text-xs text-port-warning">+ No clear notes detected — sing a bit louder and steadier, then try again.+ </p>+ )+ )}+ </div>+ );+}diff --git a/client/src/components/songs/SingToScore.test.jsx b/client/src/components/songs/SingToScore.test.jsxnew file mode 100644index 0000000000..ea4dfd6db9--- /dev/null+++ b/client/src/components/songs/SingToScore.test.jsx@@ -0,0 +1,80 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';++// Drive the component off a mocked hook so we control phase/result without a+// real mic or AudioContext (neither exists in jsdom). The hook itself is tested+// separately in useSingToScore.test.jsx.+const start = vi.fn();+const stop = vi.fn();+const reset = vi.fn();+let hookState = { phase: 'idle', beat: null, result: null, error: null };++vi.mock('../../hooks/useSingToScore.js', () => ({+ __esModule: true,+ default: () => ({ ...hookState, start, stop, reset }),+ SING_IDLE: 'idle',+ SING_COUNT_IN: 'countIn',+ SING_RECORDING: 'recording',+}));++import SingToScore from './SingToScore.jsx';++describe('SingToScore', () => {+ beforeEach(() => {+ start.mockClear();+ stop.mockClear();+ reset.mockClear();+ hookState = { phase: 'idle', beat: null, result: null, error: null };+ });++ it('starts capture when Sing is pressed', () => {+ render(<SingToScore value="time: 4/4" tempo={120} />);+ fireEvent.click(screen.getByRole('button', { name: /sing/i }));+ expect(start).toHaveBeenCalled();+ });++ it('shows a Stop button and stops while recording', () => {+ hookState = { phase: 'recording', beat: 2, result: null, error: null };+ render(<SingToScore value="time: 4/4" tempo={120} />);+ const stopBtn = screen.getByRole('button', { name: /stop/i });+ fireEvent.click(stopBtn);+ expect(stop).toHaveBeenCalled();+ });++ it('previews and inserts a transcribed result (append)', () => {+ const onInsert = vi.fn();+ hookState = { phase: 'idle', beat: null, result: '| C4q D4q E4q F4q |', error: null };+ render(<SingToScore value={'clef: treble\nkey: C\ntime: 4/4'} tempo={120} onInsert={onInsert} />);+ // The transcribed DSL is shown for review.+ expect(screen.getByText('| C4q D4q E4q F4q |')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: /append to score/i }));+ expect(onInsert).toHaveBeenCalledWith('| C4q D4q E4q F4q |', 'append');+ expect(reset).toHaveBeenCalled();+ });++ it('disables Replace selection when nothing is selected', () => {+ hookState = { phase: 'idle', beat: null, result: '| C4q |', error: null };+ render(<SingToScore value={'time: 4/4'} tempo={120} hasSelection={false} onInsert={vi.fn()} />);+ expect(screen.getByRole('button', { name: /replace selection/i })).toBeDisabled();+ });++ it('replaces the selection when one exists', () => {+ const onInsert = vi.fn();+ hookState = { phase: 'idle', beat: null, result: '| G4q |', error: null };+ render(<SingToScore value={'time: 4/4'} tempo={120} hasSelection onInsert={onInsert} />);+ fireEvent.click(screen.getByRole('button', { name: /replace selection/i }));+ expect(onInsert).toHaveBeenCalledWith('| G4q |', 'replace');+ });++ it('shows a hint when no notes were detected', () => {+ hookState = { phase: 'idle', beat: null, result: '', error: null };+ render(<SingToScore value={'time: 4/4'} tempo={120} onInsert={vi.fn()} />);+ expect(screen.getByText(/no clear notes detected/i)).toBeInTheDocument();+ });++ it('surfaces a mic error', () => {+ hookState = { phase: 'idle', beat: null, result: null, error: 'Microphone access denied' };+ render(<SingToScore value={'time: 4/4'} tempo={120} />);+ expect(screen.getByText(/microphone access denied/i)).toBeInTheDocument();+ });+});diff --git a/client/src/components/songs/SongScoreEditor.jsx b/client/src/components/songs/SongScoreEditor.jsxindex 0d66fc7126..2dbe4f378f 100644--- a/client/src/components/songs/SongScoreEditor.jsx+++ b/client/src/components/songs/SongScoreEditor.jsx@@ -12,9 +12,10 @@* blocks rendering the rest.*/-import { useMemo, useState } from 'react';+import { useCallback, useMemo, useRef, useState } from 'react';import { Music, ChevronDown, ChevronRight, AlertTriangle } from 'lucide-react';import ScoreSheet from './ScoreSheet.jsx';+import SingToScore from './SingToScore.jsx';import { parseScore } from '../../lib/scoreNotation.js';const PLACEHOLDER = `clef: treble@@ -37,6 +38,31 @@ const LEGEND = [export default function SongScoreEditor({ value, onChange }) {const [showLegend, setShowLegend] = useState(false);const score = useMemo(() => parseScore(value || ''), [value]);+ const textareaRef = useRef(null);+ // Track the textarea's current selection so "Replace selection" knows whether+ // any text is selected and where. Updated on select/keyup/mouseup/blur.+ const [selection, setSelection] = useState({ start: 0, end: 0 });++ const syncSelection = useCallback(() => {+ const el = textareaRef.current;+ if (el) setSelection({ start: el.selectionStart, end: el.selectionEnd });+ }, []);++ // Insert transcribed notation from Sing-to-score: either append a new line of+ // measures to the end of the score, or replace the current selection in place.+ const insertNotation = useCallback((text, mode) => {+ const current = value || '';+ if (mode === 'replace' && selection.end > selection.start) {+ const next = current.slice(0, selection.start) + text + current.slice(selection.end);+ onChange(next);+ return;+ }+ // Append: ensure a newline before the new measures unless the score is empty.+ const sep = current.trim() ? `${current.replace(/\s+$/, '')}\n` : current;+ onChange(`${sep}${text}`);+ }, [value, selection, onChange]);++ const hasSelection = selection.end > selection.start;// Measures whose beat total doesn't match the time signature — a gentle nudge,// not an error (a pickup bar or a deliberate free bar is legitimate).@@ -77,14 +103,30 @@ export default function SongScoreEditor({ value, onChange }) {</label><textareaid="score"+ ref={textareaRef}value={value || ''}onChange={(e) => onChange(e.target.value)}+ onSelect={syncSelection}+ onKeyUp={syncSelection}+ onMouseUp={syncSelection}+ onBlur={syncSelection}placeholder={PLACEHOLDER}rows={8}spellCheck={false}className={`${inputCls} font-mono leading-relaxed`}/>+ {/* Sing a melody → transcribe it into the notation above. */}+ <div className="mt-3">+ <SingToScore+ value={value || ''}+ tempo={score.tempo}+ musicKey={score.key}+ hasSelection={hasSelection}+ onInsert={insertNotation}+ />+ </div>+{/* Parse feedback — beat mismatches and unrecognized tokens. */}{(beatWarnings.length > 0 || score.errors.length > 0) && (<div className="mt-2 space-y-1">diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex f13b70301c..116999f47c 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -123,6 +123,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. || `useLocalModels` | Live installed Ollama/LM Studio model ids per backend + the server's editorial recommendation. | Model pickers that must show currently-installed local models (not just a provider's stale stored `models`). Fold in via `mergeModelLists` + `localBackendForProvider`. || `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |+| `useSingToScore` | Capture a sung melody from the mic and transcribe it into lead-sheet notation. `start()` opens the mic, counts in on the shared metronome, then accumulates a pitch track relative to beat 1; `stop()` runs the `transcribePitchTrack` pipeline (segment → quantize at the song tempo → spell for the key) and returns the lead-sheet body. Exposes `{ phase, beat, result, error, start, stop, reset }`; tears down mic/analyser/tracker/metronome on stop and unmount. | The Song editor's Sing-to-score panel. || `useSyncIntegrity` | Fetches per-kind integrity diff from every eligible online peer; reduces to worst-case `statusById` + `byPeer` breakdown maps. | Federated media sync integrity UI — badges, drawers, peer breakdown. || `useUniverse` | Loads the universe record for a `universeId` with mount/cancel guards; returns `[universe, setUniverse, loading, error]` (setter exposed for optimistic post-mutation updates). | Any surface that loads a linked universe (pipeline stages, etc.) — use instead of re-rolling the getUniverse-on-mount effect. || `useUniverseAction` | LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex a536051e79..21baa15836 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -16,6 +16,8 @@ export { default as useFieldDraft } from './useFieldDraft.js';export { default as useImageGenQueue } from './useImageGenQueue.js';export { default as useImageRenderSettings } from './useImageRenderSettings.js';export { default as useSingleImageRender } from './useSingleImageRender.js';+export { default as useSingToScore } from './useSingToScore.js';+export * from './useSingToScore.js';export { default as useMediaPreviewActions } from './useMediaPreviewActions.js';export { default as useKeyboardControls } from './useKeyboardControls.js';export { default as useMediaJobProgress } from './useMediaJobProgress.js';diff --git a/client/src/hooks/useSingToScore.js b/client/src/hooks/useSingToScore.jsnew file mode 100644index 0000000000..b0632d2947--- /dev/null+++ b/client/src/hooks/useSingToScore.js@@ -0,0 +1,162 @@+// useSingToScore — capture a sung melody from the mic and transcribe it into+// PortOS lead-sheet notation.+//+// Lifecycle: `start()` opens the mic (its own getUserMedia — sing-to-score is a+// standalone capture, distinct from a recording take), counts in with the shared+// metronome so the singer knows where beat 1 is, then runs a pitch tracker that+// accumulates `{ tMs, hz, clarity }` frames relative to the first music beat.+// `stop()` ends capture and runs the pure `transcribePitchTrack` pipeline,+// returning the lead-sheet body for the UI to preview + insert.+//+// All Web Audio + rAF resources (mic stream, analyser graph, tracker loop,+// metronome) tear down on stop AND on unmount (the deferred-work teardown rule+// in CLAUDE.md) so nothing dangles after navigation-away.++import { useCallback, useEffect, useRef, useState } from 'react';+import { createStreamAnalyser } from '../lib/audioRecorder.js';+import { createPitchTracker } from '../lib/pitchDetect.js';+import { createMetronome, clampBpm, timeSignatureFromScore, DEFAULT_BPM } from '../lib/metronome.js';+import { transcribePitchTrack } from '../lib/singToScore.js';+import useMounted from './useMounted.js';++// Phases the UI renders distinct states for.+export const SING_IDLE = 'idle';+export const SING_COUNT_IN = 'countIn';+export const SING_RECORDING = 'recording';++// Pull a pitch frame this often during capture (ms). Faster than rAF-tied so the+// track density is stable across machines; the segmenter is timestamp-driven so+// the exact rate only affects resolution, not correctness.+const FRAME_INTERVAL_MS = 30;+// Count-in length before capture begins (bars). One bar is the conventional lead.+const COUNT_IN_BARS = 1;++/**+ * @param {object} opts+ * @param {number|string} [opts.tempo] — song BPM (defaults to 120 when absent).+ * @param {string} [opts.score] — current score text, for the time signature.+ * @param {string} [opts.musicKey] — key name for enharmonic spelling (e.g. "Eb").+ * @returns {{+ * phase: string, beat: number|null, result: string|null,+ * error: string|null, start: () => Promise<void>, stop: () => void,+ * reset: () => void,+ * }}+ */+export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {}) {+ const [phase, setPhase] = useState(SING_IDLE);+ const [beat, setBeat] = useState(null);+ const [result, setResult] = useState(null);+ const [error, setError] = useState(null);++ const mountedRef = useMounted();+ const streamRef = useRef(null); // mic stream we own + must stop+ const analyserRef = useRef(null); // { close } analyser graph+ const trackerRef = useRef(null); // { stop } pitch tracker loop+ const metronomeRef = useRef(null); // { stop } count-in metronome+ const trackRef = useRef([]); // accumulated { tMs, hz, clarity } frames+ const captureStartRef = useRef(0); // performance.now() at first music beat+ const capturingRef = useRef(false); // gate frames until the count-in completes++ const bpm = clampBpm(tempo) ?? DEFAULT_BPM;+ const timeSig = timeSignatureFromScore(score);++ // Tear down every live resource. Safe to call repeatedly (idempotent refs).+ const teardown = useCallback(() => {+ 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; }+ if (streamRef.current) { streamRef.current.getTracks().forEach((t) => t.stop()); streamRef.current = null; }+ capturingRef.current = false;+ }, []);++ // Finalize: stop everything, run the transcription over the captured track.+ const finish = useCallback(() => {+ teardown();+ const track = trackRef.current;+ const dsl = transcribePitchTrack(track, {+ bpm,+ key: musicKey,+ beatsPerBar: timeSig.beats,+ beatValue: timeSig.beatValue,+ });+ if (!mountedRef.current) return;+ setPhase(SING_IDLE);+ setBeat(null);+ setResult(dsl || '');+ }, [bpm, musicKey, timeSig.beats, timeSig.beatValue, teardown, mountedRef]);++ const stop = useCallback(() => {+ if (phase === SING_IDLE) return;+ finish();+ }, [phase, finish]);++ const start = useCallback(async () => {+ if (phase !== SING_IDLE) return;+ setError(null);+ setResult(null);+ trackRef.current = [];++ const src = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((err) => {+ if (mountedRef.current) setError(err?.message || 'Microphone access denied');+ return null;+ });+ if (!src) return;+ if (!mountedRef.current) { src.getTracks().forEach((t) => t.stop()); return; }+ streamRef.current = src;++ const graph = createStreamAnalyser(src);+ analyserRef.current = graph;++ // Accumulate frames only after the count-in. `capturingRef` flips on the+ // first music downbeat; `captureStartRef` anchors t=0 there so onsets are+ // relative to beat 1 of the bar.+ trackerRef.current = createPitchTracker(graph.analyser, {+ intervalMs: FRAME_INTERVAL_MS,+ onUpdate: (u) => {+ if (!capturingRef.current) return;+ const tMs = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - captureStartRef.current;+ trackRef.current.push({ tMs, hz: u.hz, clarity: u.clarity });+ },+ });++ setPhase(SING_COUNT_IN);+ const metro = createMetronome({+ bpm,+ beatsPerBar: timeSig.beats,+ beatValue: timeSig.beatValue,+ countInBars: COUNT_IN_BARS,+ onBeat: (info) => {+ if (!mountedRef.current) return;+ setBeat(info.beat);+ },+ onCountInComplete: () => {+ if (!mountedRef.current) return;+ captureStartRef.current = typeof performance !== 'undefined' ? performance.now() : Date.now();+ capturingRef.current = true;+ setPhase(SING_RECORDING);+ },+ });+ metronomeRef.current = metro;+ await metro.start().catch((err) => {+ if (mountedRef.current) setError(err?.message || 'Could not start audio');+ teardown();+ if (mountedRef.current) setPhase(SING_IDLE);+ });+ }, [phase, bpm, timeSig.beats, timeSig.beatValue, teardown, mountedRef]);++ // Clear a produced result (after the user inserts or discards it).+ const reset = useCallback(() => {+ setResult(null);+ setError(null);+ }, []);++ // Belt-and-suspenders: tear everything down on unmount so a navigation-away+ // mid-capture can't leave the mic open or a loop running. A ref keeps the+ // effect's dep list empty (run cleanup exactly once on unmount) while still+ // calling the latest `teardown`.+ const teardownRef = useRef(teardown);+ teardownRef.current = teardown;+ useEffect(() => () => teardownRef.current(), []);++ return { phase, beat, result, error, start, stop, reset };+}diff --git a/client/src/hooks/useSingToScore.test.js b/client/src/hooks/useSingToScore.test.jsnew file mode 100644index 0000000000..30e25474c9--- /dev/null+++ b/client/src/hooks/useSingToScore.test.js@@ -0,0 +1,104 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';++// Mock every Web Audio / mic seam the hook touches so it runs in jsdom. We+// capture the metronome + tracker callbacks so the test can drive the count-in+// → recording → transcribe lifecycle deterministically.+const analyserClose = vi.fn();+const trackerStop = vi.fn();+const metronomeStop = vi.fn();+const trackStop = vi.fn();+let trackerOnUpdate = null;+let metroOpts = null;+const { transcribeMock } = vi.hoisted(() => ({ transcribeMock: vi.fn(() => '| C4q |') }));++vi.mock('../lib/audioRecorder.js', () => ({+ createStreamAnalyser: vi.fn(() => ({ analyser: { fftSize: 2048 }, context: {}, close: analyserClose })),+}));++vi.mock('../lib/pitchDetect.js', () => ({+ createPitchTracker: vi.fn((analyser, opts) => { trackerOnUpdate = opts.onUpdate; return { stop: trackerStop }; }),+}));++vi.mock('../lib/metronome.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ createMetronome: vi.fn((opts) => {+ metroOpts = opts;+ return { start: vi.fn(async () => {}), stop: metronomeStop };+ }),+ };+});++vi.mock('../lib/singToScore.js', () => ({ transcribePitchTrack: transcribeMock }));++import useSingToScore, { SING_IDLE, SING_COUNT_IN, SING_RECORDING } from './useSingToScore.js';++const fakeStream = () => ({ getTracks: () => [{ stop: trackStop }] });++describe('useSingToScore', () => {+ beforeEach(() => {+ analyserClose.mockClear();+ trackerStop.mockClear();+ metronomeStop.mockClear();+ trackStop.mockClear();+ transcribeMock.mockClear();+ trackerOnUpdate = null;+ metroOpts = null;+ global.navigator.mediaDevices = { getUserMedia: vi.fn(async () => fakeStream()) };+ global.performance = { now: () => 1000 };+ });++ afterEach(() => { vi.clearAllMocks(); });++ it('walks idle → count-in → recording → idle and transcribes on stop', async () => {+ const { result } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4', musicKey: 'C' }));+ expect(result.current.phase).toBe(SING_IDLE);++ await act(async () => { await result.current.start(); });+ expect(result.current.phase).toBe(SING_COUNT_IN);++ // Count-in completes → recording starts and the capture clock anchors.+ act(() => { metroOpts.onCountInComplete({ beat: 1 }); });+ expect(result.current.phase).toBe(SING_RECORDING);++ // A clear frame is captured into the track.+ act(() => { trackerOnUpdate({ hz: 261.6, clarity: 0.95 }); });++ act(() => { result.current.stop(); });+ expect(result.current.phase).toBe(SING_IDLE);+ expect(transcribeMock).toHaveBeenCalledTimes(1);+ // The accumulated track (one frame) is passed to the transcriber.+ expect(transcribeMock.mock.calls[0][0]).toHaveLength(1);+ expect(result.current.result).toBe('| C4q |');+ });++ it('does not capture frames during the count-in', async () => {+ const { result } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));+ await act(async () => { await result.current.start(); });+ // Frame arrives before count-in completes — must be ignored.+ act(() => { trackerOnUpdate?.({ hz: 440, clarity: 0.95 }); });+ act(() => { metroOpts.onCountInComplete({ beat: 1 }); });+ act(() => { result.current.stop(); });+ expect(transcribeMock.mock.calls[0][0]).toHaveLength(0);+ });++ it('surfaces a mic-denied error and stays idle', async () => {+ global.navigator.mediaDevices.getUserMedia = vi.fn(async () => { throw new Error('Permission denied'); });+ const { result } = renderHook(() => useSingToScore({ tempo: 120 }));+ await act(async () => { await result.current.start(); });+ expect(result.current.phase).toBe(SING_IDLE);+ expect(result.current.error).toBe('Permission denied');+ });++ it('tears down mic, analyser, tracker, and metronome on unmount', async () => {+ const { result, unmount } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));+ await act(async () => { await result.current.start(); });+ unmount();+ expect(metronomeStop).toHaveBeenCalled();+ expect(trackerStop).toHaveBeenCalled();+ expect(analyserClose).toHaveBeenCalled();+ expect(trackStop).toHaveBeenCalled();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 58a6d8dabe..140809ce2f 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -92,6 +92,7 @@ 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`. || `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→`{ freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature); `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. |+| `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. || `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 52403b01aa..a18b40f5e9 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -59,6 +59,7 @@ export * from './metronome.js';export * from './pitchDetect.js';export * from './scoreNotation.js';export * from './scorePlayback.js';+export * from './singToScore.js';export * from './songCraft.js';export * from './songPlayback.js';export * from './universeBuilderExpand.js';diff --git a/client/src/lib/singToScore.js b/client/src/lib/singToScore.jsnew file mode 100644index 0000000000..d01e8acbce--- /dev/null+++ b/client/src/lib/singToScore.js@@ -0,0 +1,293 @@+// Sing-to-score transcription — turn a sung pitch track into PortOS lead-sheet+// notation. The pipeline is three pure stages, each independently unit-tested:+//+// 1. segmentPitchTrack — group a continuous `[{ tMs, hz, clarity }]` track+// into discrete note/rest segments (onset = pitch change or energy return,+// rest = a run of unclear/silent frames). Note pitch = median Hz over the+// stable span, which kills the per-frame octave jitter raw vocal detection+// produces.+// 2. quantizeSegments — snap each segment's onset and duration to the+// metronome grid at the song `tempo` (nearest whole/half/quarter/eighth/+// sixteenth), turning a wobbly human take into clean notation.+// 3. segmentsToScoreDsl — spell each note enharmonically from the key+// signature and emit the exact lead-sheet text the editor edits, so the+// user can review it and round-trips cleanly back through `parseScore`.+//+// `transcribePitchTrack` runs all three. Dependency-free: it reuses+// `frequencyToNote` from `pitchDetect.js` (the shared frequency↔note mapping)+// and the key tables / duration model from `scoreNotation.js` — no new DSP or+// notation library.++import { frequencyToNote } from './pitchDetect.js';+import { DURATIONS, durationBeats, keySignature } from './scoreNotation.js';++// === Tunables ==========================================================++// A frame whose clarity is below this is treated as silence/noise → a rest+// (matches the tuner's confidence gate; vocals settle well above this).+export const DEFAULT_CLARITY_THRESHOLD = 0.9;+// A new segment starts when the detected pitch jumps more than this many+// semitones from the running segment — below it we treat the wobble as the same+// sung note (vibrato / scoops don't split a note).+const NOTE_SPLIT_SEMITONES = 0.6;+// Drop a pitched segment shorter than this — a stray clear frame between rests+// is detection noise, not a sung note.+const MIN_NOTE_MS = 70;+// Drop a rest shorter than this — a momentary clarity dip mid-note (a breath+// catch) shouldn't punch a rest into a held note.+const MIN_REST_MS = 90;++// Duration codes the quantizer snaps to, longest → shortest. We deliberately+// stop at sixteenth (`s`): finer grids (32nds) over-fit human timing jitter.+const QUANTIZE_CODES = ['w', 'h', 'q', 'e', 's'];++// === Stage 1: segment the pitch track ==================================++// Median of a numeric array (the robust center of a segment's frequencies —+// immune to the lone octave-jump outliers a mean would smear in).+const median = (values) => {+ if (!values.length) return null;+ const sorted = [...values].sort((a, b) => a - b);+ const mid = sorted.length >> 1;+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+};++// Semitone distance between two frequencies (|Δ| in equal-tempered semitones).+const semitoneGap = (a, b) => Math.abs(12 * Math.log2(a / b));++// True for a frame that carries a usable pitch (clear enough + a positive Hz).+const isPitched = (f, clarityThreshold) =>+ f && Number.isFinite(f.hz) && f.hz > 0 && (f.clarity ?? 1) >= clarityThreshold;++/**+ * Group a pitch track into discrete note + rest segments.+ *+ * @param {Array<{tMs:number, hz:number, clarity?:number}>} track — time-ordered+ * frames. Frames below the clarity threshold (or with no/zero hz) read as+ * silence and accumulate into rests.+ * @param {object} [opts]+ * @param {number} [opts.clarityThreshold]+ * @param {number} [opts.minNoteMs] — pitched segments shorter than this are dropped.+ * @param {number} [opts.minRestMs] — rests shorter than this are dropped (the+ * surrounding note absorbs the gap).+ * @returns {Array<{rest:boolean, startMs:number, endMs:number, hz?:number}>} —+ * ordered segments; a note carries its median `hz`, a rest carries only timing.+ */+export const segmentPitchTrack = (track, opts = {}) => {+ const {+ clarityThreshold = DEFAULT_CLARITY_THRESHOLD,+ minNoteMs = MIN_NOTE_MS,+ minRestMs = MIN_REST_MS,+ } = opts;+ const frames = Array.isArray(track) ? track.filter((f) => f && Number.isFinite(f.tMs)) : [];+ if (frames.length < 2) return [];++ // Raw runs: alternating pitched-note runs (carrying their frequencies) and+ // rest runs, with no merging/dropping yet.+ const runs = [];+ let cur = null; // { rest, startMs, endMs, hzList }+ for (let i = 0; i < frames.length; i++) {+ const f = frames[i];+ const pitched = isPitched(f, clarityThreshold);+ if (pitched) {+ const runMedian = cur && !cur.rest && cur.hzList.length ? median(cur.hzList) : null;+ // Split into a new note when there's no open note, the open run is a rest,+ // or the pitch moved more than the split threshold from the run's center.+ const split = !cur || cur.rest || (runMedian != null && semitoneGap(f.hz, runMedian) > NOTE_SPLIT_SEMITONES);+ if (split) {+ cur = { rest: false, startMs: f.tMs, endMs: f.tMs, hzList: [f.hz] };+ runs.push(cur);+ } else {+ cur.hzList.push(f.hz);+ cur.endMs = f.tMs;+ }+ } else if (cur && cur.rest) {+ cur.endMs = f.tMs;+ } else {+ cur = { rest: true, startMs: f.tMs, endMs: f.tMs, hzList: null };+ runs.push(cur);+ }+ }++ // Extend each run's end to the next run's start so adjacent segments are+ // contiguous (a frame timestamp marks an onset, not a span — the gap to the+ // next onset is this segment's true duration).+ for (let i = 0; i < runs.length - 1; i++) runs[i].endMs = runs[i + 1].startMs;++ // Collapse: finalize note frequencies, drop sub-threshold notes (noise) and+ // sub-threshold rests (breath catches), merging a dropped segment into the+ // surrounding note where possible.+ const segments = [];+ for (const run of runs) {+ const durMs = run.endMs - run.startMs;+ if (run.rest) {+ if (durMs < minRestMs) {+ // Too short to be a rest — absorb into the preceding note if one exists.+ const prev = segments[segments.length - 1];+ if (prev && !prev.rest) prev.endMs = run.endMs;+ continue;+ }+ segments.push({ rest: true, startMs: run.startMs, endMs: run.endMs });+ } else {+ if (durMs < minNoteMs) continue; // stray clear frame — not a sung note+ segments.push({ rest: false, startMs: run.startMs, endMs: run.endMs, hz: median(run.hzList) });+ }+ }+ return segments;+};++// === Stage 2: quantize to the beat grid ================================++// Snap a beat-length to the nearest grid duration, returning the duration code+// (and how many such units, for callers that want it). We pick the code whose+// beat value is closest to the target; ties prefer the longer note.+const nearestDurationCode = (beats) => {+ let best = null;+ let bestErr = Infinity;+ for (const code of QUANTIZE_CODES) {+ const err = Math.abs(DURATIONS[code].beats - beats);+ if (err < bestErr - 1e-9) { bestErr = err; best = code; }+ }+ return best;+};++/**+ * Quantize note/rest segments to the metronome grid at a given tempo. Each+ * segment's *duration in ms* converts to quarter-note beats (`ms / msPerQuarter`,+ * where BPM is the conventional quarter-notes-per-minute — the same convention+ * `metronome.js` / `scorePlayback.js` use), then snaps to the nearest grid+ * duration. Onsets are implicitly snapped because durations are: consecutive+ * quantized durations lay the notes back on the grid.+ *+ * `beatValue` (the time-signature denominator) does NOT affect this conversion —+ * `DURATIONS` and BPM are both expressed in quarter-note units — but it's+ * accepted for call-site symmetry with the rest of the pipeline.+ *+ * @param {Array} segments — output of `segmentPitchTrack`.+ * @param {object} opts+ * @param {number} opts.bpm — beats per minute (the song tempo; quarter = 1 beat).+ * @returns {Array<{rest:boolean, hz?:number, code:string, dots:number, beats:number}>}+ * — each segment with a snapped duration (`beats` in quarter-note units);+ * zero-length snaps are dropped.+ */+export const quantizeSegments = (segments, { bpm } = {}) => {+ const safeBpm = Number.isFinite(bpm) && bpm > 0 ? bpm : 120;+ const msPerQuarter = 60000 / safeBpm;+ const out = [];+ for (const seg of Array.isArray(segments) ? segments : []) {+ const durMs = (seg.endMs ?? 0) - (seg.startMs ?? 0);+ if (durMs <= 0) continue;+ const quarterBeats = durMs / msPerQuarter;+ const code = nearestDurationCode(quarterBeats);+ if (!code) continue;+ const snappedBeats = durationBeats(code, 0);+ out.push({ rest: !!seg.rest, hz: seg.hz, code, dots: 0, beats: snappedBeats });+ }+ return out;+};++// === Stage 3: emit lead-sheet DSL ======================================++// Pitch-class → flat spelling, for keys that carry flats. The sharp spelling is+// `frequencyToNote`'s default; here we only need the alternate names for the+// black keys (1,3,6,8,10).+const FLAT_SPELLING = {+ 1: { letter: 'D', accidental: 'b' },+ 3: { letter: 'E', accidental: 'b' },+ 6: { letter: 'G', accidental: 'b' },+ 8: { letter: 'A', accidental: 'b' },+ 10: { letter: 'B', accidental: 'b' },+};++// Choose the enharmonic spelling for a detected note given the key signature.+// In a flat key we respell accidental notes with flats (a black key sung in Eb+// should read Ab, not G#); sharp keys and C keep the detector's sharp default.+// We adjust the octave for the flat respelling so the *pitch* is unchanged+// (e.g. C#5 → Db5 stays the same sounding note; only the name changes — same+// octave because Db and C# share octave boundaries above C).+const spellNote = (note, keySig) => {+ if (!note) return null;+ if (keySig?.type !== 'flat' || !note.accidental) return note;+ // Recover the pitch class from the detector's sharp spelling.+ const LETTER_PC = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };+ const pc = (LETTER_PC[note.letter] + (note.accidental === '#' ? 1 : 0) + 12) % 12;+ const flat = FLAT_SPELLING[pc];+ if (!flat) return note;+ return { ...note, letter: flat.letter, accidental: flat.accidental };+};++// One quantized segment → a single lead-sheet token (e.g. "E4q" or "rq").+const segmentToToken = (seg, keySig) => {+ const dur = seg.code + '.'.repeat(seg.dots || 0);+ if (seg.rest) return `r${dur}`;+ const note = spellNote(frequencyToNote(seg.hz), keySig);+ if (!note) return `r${dur}`; // unspellable → fall back to a rest so timing holds+ return `${note.letter}${note.accidental}${note.octave}${dur}`;+};++/**+ * Render quantized segments to lead-sheet body text, grouped into measures by+ * the time signature so the output parses into clean bars.+ *+ * @param {Array} quantized — output of `quantizeSegments`.+ * @param {object} [opts]+ * @param {object} [opts.keySig] — a `keySignature()` descriptor for enharmonic+ * spelling; defaults to C (no accidentals).+ * @param {number} [opts.beatsPerBar=4] — time-signature numerator (bar length in beats).+ * @param {number} [opts.beatValue=4] — time-signature denominator.+ * @returns {string} — the measure body (`| ... | ... |`), empty string when no notes.+ */+export const segmentsToScoreDsl = (quantized, { keySig, beatsPerBar = 4, beatValue = 4 } = {}) => {+ let segs = Array.isArray(quantized) ? quantized : [];+ // Trim leading/trailing rests — silence before the first sung note and after+ // the last carries no musical meaning (and an all-rest track is "nothing sung").+ let lo = 0;+ let hi = segs.length;+ while (lo < hi && segs[lo].rest) lo++;+ while (hi > lo && segs[hi - 1].rest) hi--;+ segs = segs.slice(lo, hi);+ if (!segs.length) return '';+ const sig = keySig || keySignature('C');+ // A bar holds `beatsPerBar` beats *of the denominator unit*; our `beats` are in+ // quarter units, so the bar capacity in quarter-beats is beatsPerBar*(4/beatValue).+ const barCapacity = beatsPerBar * (4 / beatValue);+ const measures = [];+ let bar = [];+ let acc = 0;+ for (const seg of segs) {+ bar.push(segmentToToken(seg, sig));+ acc += seg.beats;+ // Close the bar once it's full (within a sixteenth's slack so float drift+ // doesn't strand a bar a hair under capacity).+ if (acc >= barCapacity - 1e-6) {+ measures.push(bar.join(' '));+ bar = [];+ acc = 0;+ }+ }+ if (bar.length) measures.push(bar.join(' '));+ return measures.length ? `| ${measures.join(' | ')} |` : '';+};++/**+ * Full sing-to-score pipeline: pitch track → measure-grouped lead-sheet body.+ * Convenience wrapper over the three stages; the UI calls this and shows the+ * result in the editor preview.+ *+ * @param {Array} track — `[{ tMs, hz, clarity }]` frames.+ * @param {object} opts+ * @param {number} opts.bpm — song tempo.+ * @param {string|object} [opts.key] — key name ("Eb") or a `keySignature()`+ * descriptor, for enharmonic spelling.+ * @param {number} [opts.beatsPerBar=4]+ * @param {number} [opts.beatValue=4]+ * @param {object} [opts.segmentOpts] — passed through to `segmentPitchTrack`.+ * @returns {string} — lead-sheet measure body (empty when nothing was sung).+ */+export const transcribePitchTrack = (track, opts = {}) => {+ const { bpm, key, beatsPerBar = 4, beatValue = 4, segmentOpts } = opts;+ const segments = segmentPitchTrack(track, segmentOpts);+ const quantized = quantizeSegments(segments, { bpm });+ const keySig = key && typeof key === 'object' ? key : keySignature(key || 'C');+ return segmentsToScoreDsl(quantized, { keySig, beatsPerBar, beatValue });+};diff --git a/client/src/lib/singToScore.test.js b/client/src/lib/singToScore.test.jsnew file mode 100644index 0000000000..2c0ac38fbd--- /dev/null+++ b/client/src/lib/singToScore.test.js@@ -0,0 +1,213 @@+import { describe, it, expect } from 'vitest';+import { parseScore, keySignature } from './scoreNotation.js';+import { noteToFrequency, frequencyToNote } from './pitchDetect.js';+import {+ segmentPitchTrack,+ quantizeSegments,+ segmentsToScoreDsl,+ transcribePitchTrack,+} from './singToScore.js';++// Synthesize a clear pitch track from a sequence of { note, durMs } where note+// is a lead-sheet pitch string ("E4") or null for a rest. Frames are emitted at+// `stepMs` with full clarity (1) for notes and 0 for rests, matching what the+// tracker pushes during capture.+const synth = (seq, { stepMs = 30, clarity = 1 } = {}) => {+ const track = [];+ let t = 0;+ for (const { note, durMs } of seq) {+ const hz = note ? noteToFrequency(parsePitchLike(note)) : 0;+ const n = Math.round(durMs / stepMs);+ for (let i = 0; i < n; i++) {+ track.push({ tMs: t, hz, clarity: note ? clarity : 0 });+ t += stepMs;+ }+ }+ // A trailing frame so the last run's end extends to a real timestamp.+ track.push({ tMs: t, hz: 0, clarity: 0 });+ return track;+};++// Minimal pitch parse for the synth helper (the lib under test owns the real one).+const parsePitchLike = (str) => {+ const m = /^([A-G])(#|b)?(\d)$/.exec(str);+ return { letter: m[1], accidental: m[2] || '', octave: Number(m[3]) };+};++describe('segmentPitchTrack', () => {+ it('groups a held note into one segment with the median pitch', () => {+ const track = synth([{ note: 'A4', durMs: 600 }]);+ const segs = segmentPitchTrack(track);+ expect(segs).toHaveLength(1);+ expect(segs[0].rest).toBe(false);+ // Median Hz maps back to A4.+ const note = frequencyToNote(segs[0].hz);+ expect(note.letter).toBe('A');+ expect(note.octave).toBe(4);+ });++ it('splits on a pitch change into separate notes', () => {+ const track = synth([+ { note: 'C4', durMs: 400 },+ { note: 'G4', durMs: 400 },+ ]);+ const segs = segmentPitchTrack(track);+ const pitched = segs.filter((s) => !s.rest);+ expect(pitched).toHaveLength(2);+ expect(frequencyToNote(pitched[0].hz).letter).toBe('C');+ expect(frequencyToNote(pitched[1].hz).letter).toBe('G');+ });++ it('emits a rest where clarity drops', () => {+ const track = synth([+ { note: 'E4', durMs: 400 },+ { note: null, durMs: 400 },+ { note: 'E4', durMs: 400 },+ ]);+ const segs = segmentPitchTrack(track);+ expect(segs.map((s) => s.rest)).toEqual([false, true, false]);+ });++ it('drops a sub-threshold stray note (detection noise)', () => {+ const track = synth([+ { note: 'C4', durMs: 400 },+ { note: 'C5', durMs: 30 }, // one stray frame — below MIN_NOTE_MS+ { note: 'C4', durMs: 400 },+ ]);+ const segs = segmentPitchTrack(track);+ // The stray is dropped; the two C4 spans remain (a tiny gap may not become a rest).+ expect(segs.every((s) => s.rest || frequencyToNote(s.hz).letter === 'C')).toBe(true);+ expect(segs.filter((s) => !s.rest).length).toBeGreaterThanOrEqual(2);+ });++ it('returns empty for too-short or absent tracks', () => {+ expect(segmentPitchTrack([])).toEqual([]);+ expect(segmentPitchTrack(null)).toEqual([]);+ expect(segmentPitchTrack([{ tMs: 0, hz: 440, clarity: 1 }])).toEqual([]);+ });+});++describe('quantizeSegments', () => {+ it('snaps a one-second note to a quarter at 60 BPM', () => {+ // 60 BPM → 1000 ms/beat. A 1000ms note is exactly a quarter (1 beat).+ const segs = [{ rest: false, hz: 440, startMs: 0, endMs: 1000 }];+ const q = quantizeSegments(segs, { bpm: 60 });+ expect(q).toHaveLength(1);+ expect(q[0].code).toBe('q');+ expect(q[0].beats).toBe(1);+ });++ it('snaps a half-beat note to an eighth', () => {+ const segs = [{ rest: false, hz: 440, startMs: 0, endMs: 500 }];+ const q = quantizeSegments(segs, { bpm: 60 });+ expect(q[0].code).toBe('e');+ });++ it('snaps a 2-beat note to a half and a 4-beat to a whole', () => {+ const half = quantizeSegments([{ rest: false, hz: 440, startMs: 0, endMs: 2000 }], { bpm: 60 });+ const whole = quantizeSegments([{ rest: false, hz: 440, startMs: 0, endMs: 4000 }], { bpm: 60 });+ expect(half[0].code).toBe('h');+ expect(whole[0].code).toBe('w');+ });++ it('rounds an imperfect human duration to the nearest grid value', () => {+ // 1100ms at 60 BPM = 1.1 beats → nearest is a quarter (1 beat), not a half.+ const q = quantizeSegments([{ rest: false, hz: 440, startMs: 0, endMs: 1100 }], { bpm: 60 });+ expect(q[0].code).toBe('q');+ });++ it('uses quarter-note BPM semantics (independent of time signature)', () => {+ // BPM is quarter-notes-per-minute (same as metronome/scorePlayback). At+ // 120 BPM a quarter is 500ms; a 250ms note is half that → an eighth.+ const q = quantizeSegments([{ rest: false, hz: 440, startMs: 0, endMs: 250 }], { bpm: 120 });+ expect(q[0].code).toBe('e');+ expect(q[0].beats).toBeCloseTo(0.5, 5);+ });++ it('drops zero/negative-length segments', () => {+ expect(quantizeSegments([{ rest: false, hz: 440, startMs: 100, endMs: 100 }], { bpm: 60 })).toEqual([]);+ });+});++describe('segmentsToScoreDsl', () => {+ it('emits a parseable measure body', () => {+ const quantized = [+ { rest: false, hz: noteToFrequency(parsePitchLike('C4')), code: 'q', dots: 0, beats: 1 },+ { rest: false, hz: noteToFrequency(parsePitchLike('D4')), code: 'q', dots: 0, beats: 1 },+ { rest: false, hz: noteToFrequency(parsePitchLike('E4')), code: 'q', dots: 0, beats: 1 },+ { rest: false, hz: noteToFrequency(parsePitchLike('F4')), code: 'q', dots: 0, beats: 1 },+ ];+ const dsl = segmentsToScoreDsl(quantized, { beatsPerBar: 4, beatValue: 4 });+ expect(dsl).toBe('| C4q D4q E4q F4q |');+ const parsed = parseScore(`time: 4/4\n${dsl}`);+ expect(parsed.errors).toEqual([]);+ expect(parsed.measures).toHaveLength(1);+ expect(parsed.measures[0].notes).toHaveLength(4);+ });++ it('breaks notes into measures by the time signature', () => {+ const quantized = Array.from({ length: 6 }, () => ({+ rest: false, hz: noteToFrequency(parsePitchLike('C4')), code: 'q', dots: 0, beats: 1,+ }));+ const dsl = segmentsToScoreDsl(quantized, { beatsPerBar: 4, beatValue: 4 });+ const parsed = parseScore(`time: 4/4\n${dsl}`);+ // 6 quarters → a full 4-beat bar then a 2-beat partial bar.+ expect(parsed.measures).toHaveLength(2);+ expect(parsed.measures[0].notes).toHaveLength(4);+ expect(parsed.measures[1].notes).toHaveLength(2);+ });++ it('spells accidentals with flats in a flat key', () => {+ // A black key between A and B: sharp spelling A#, flat spelling Bb.+ const hz = noteToFrequency({ letter: 'A', accidental: '#', octave: 4 });+ const quantized = [{ rest: false, hz, code: 'q', dots: 0, beats: 1 }];+ const flat = segmentsToScoreDsl(quantized, { keySig: keySignature('Bb'), beatsPerBar: 4 });+ const sharp = segmentsToScoreDsl(quantized, { keySig: keySignature('C'), beatsPerBar: 4 });+ expect(flat).toContain('Bb4');+ expect(sharp).toContain('A#4');+ });++ it('renders an interior rest (and trims leading/trailing rests)', () => {+ const quantized = [+ { rest: true, code: 'q', dots: 0, beats: 1 }, // leading rest — trimmed+ { rest: false, hz: noteToFrequency(parsePitchLike('C4')), code: 'q', dots: 0, beats: 1 },+ { rest: true, code: 'h', dots: 0, beats: 2 }, // interior rest — kept+ { rest: false, hz: noteToFrequency(parsePitchLike('C4')), code: 'q', dots: 0, beats: 1 },+ { rest: true, code: 'q', dots: 0, beats: 1 }, // trailing rest — trimmed+ ];+ const dsl = segmentsToScoreDsl(quantized, { beatsPerBar: 4 });+ expect(dsl).toBe('| C4q rh C4q |');+ expect(parseScore(`time: 4/4\n${dsl}`).errors).toEqual([]);+ });++ it('returns empty string for no segments', () => {+ expect(segmentsToScoreDsl([])).toBe('');+ expect(segmentsToScoreDsl(null)).toBe('');+ });+});++describe('transcribePitchTrack (round-trip)', () => {+ it('transcribes a sung scale into notation that re-parses cleanly', () => {+ // Sing C-D-E-F-G as quarter notes at 60 BPM (1000ms each).+ const track = synth([+ { note: 'C4', durMs: 1000 },+ { note: 'D4', durMs: 1000 },+ { note: 'E4', durMs: 1000 },+ { note: 'F4', durMs: 1000 },+ { note: 'G4', durMs: 1000 },+ ]);+ const dsl = transcribePitchTrack(track, { bpm: 60, key: 'C', beatsPerBar: 4, beatValue: 4 });+ const parsed = parseScore(`clef: treble\nkey: C\ntime: 4/4\ntempo: 60\n${dsl}`);+ expect(parsed.errors).toEqual([]);+ const letters = parsed.measures.flatMap((m) => m.notes).filter((n) => !n.rest).map((n) => n.pitch.letter);+ expect(letters).toEqual(['C', 'D', 'E', 'F', 'G']);+ // All quarter notes.+ const codes = parsed.measures.flatMap((m) => m.notes).filter((n) => !n.rest).map((n) => n.duration.code);+ expect(codes.every((c) => c === 'q')).toBe(true);+ });++ it('returns empty string for an empty/silent track', () => {+ expect(transcribePitchTrack([], { bpm: 120 })).toBe('');+ expect(transcribePitchTrack(synth([{ note: null, durMs: 1000 }]), { bpm: 120 })).toBe('');+ });+});