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
songs: add dependency-free pitch-detection core (frequency<->note, tracker)
[._.]/ Adam Eivye966f2e26aa6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex aa37deeda4..d81bf2deb2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **Songs: pitch-detection core (foundation for the upcoming vocal tuner & color-match)** — a new in-house, dependency-free DSP module estimates the fundamental frequency of sung audio (McLeod normalized-square-difference autocorrelation, with a clarity score that rejects silence and noise) and maps frequency↔note using the same diatonic staff math the sheet-music renderer already uses — so a detected pitch lands on exactly the note position the staff would draw. It also ships a live pitch tracker that reads a microphone analyser on an animation-frame loop and smooths the result (median + EMA) to suppress the octave jumps raw vocal detection produces. No new third-party library — like the rest of the song system's notation stack, the detector is hand-rolled in-tree. This is groundwork; the singer-facing tuner, color-match grading, and sing-to-score features build on it.- **Songs — an a cappella song workbench (Create → Songs)** — write, arrange, and learn songs like "500 Miles" by Peter, Paul and Mary. Each song tracks its key, tempo, and rhythm shape (slow 4/4 ballad, compound 6/8 dirge, free-time lament, and more), lyric sections, and the voice layers you're stacking — with per-layer learning notes. An "Add from ladder" picker seeds layers in the recommended foundation-first order (lead → bass → thirds → fifths → drone → counter-melody). A deep-linkable **Learning Guide** (Create → Songs → Learning Guide, or `/songs/guide`) covers dirge rhythm shapes with tempo bands, the layer-building ladder, a step-by-step practice sequence for learning a new song, and a plain-language musical-notation primer (staves, time signatures, note values, dynamics, reading a lead sheet). A worked "500 Miles" example is seeded on first visit. Reachable from `⌘K` and voice nav.- **Songs: AI generate, expand & evaluate** — like the manuscript and universe/series creators, the Songs workbench now drafts and critiques arrangements with AI. From the Songs list, **Generate** drafts a full arrangement (lyrics, voice layers, key/tempo/rhythm shape, notation, and learning notes) from the title/artist as a brief; inside the editor, **Generate draft** and **Expand current** rewrite or build on the open draft, and **Evaluate** scores the arrangement 0–100 for performance-readiness with concrete strengths, weaknesses, and suggestions. The model returns rhythm-shape and voice-layer ids the editor's pickers already understand. Generated drafts land in the editor for review and are never auto-saved.- **Songs: record & layer your own vocals** — record each part straight from the mic in the song editor (saved as a vocal take), assign takes to voice layers, then **Play layered** to start every unmuted take together — sample-aligned on one audio clock — so you can stack a lead, bass, and harmony and rehearse a cappella against yourself. Mute/solo individual takes, scrub each one with its own player, and the takes persist with the song.diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 19f796e202..b9e32269c4 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. |+| `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. || `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). || `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. || `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. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 261195d11b..1632684724 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 './pitchDetect.js';export * from './scoreNotation.js';export * from './songCraft.js';export * from './songPlayback.js';diff --git a/client/src/lib/pitchDetect.js b/client/src/lib/pitchDetect.jsnew file mode 100644index 0000000000..3504fd517b--- /dev/null+++ b/client/src/lib/pitchDetect.js@@ -0,0 +1,262 @@+// PortOS vocal pitch detection — a tiny, dependency-free DSP core for the song+// system's tuner / color-match / sing-to-score features. We estimate the+// fundamental frequency of a sung frame ourselves (autocorrelation, McLeod's+// normalized-square-difference flavor) rather than pulling in a DSP package, for+// the same reason `scoreNotation.js` hand-rolls notation: PortOS's audio stack+// stays library-free. This module is the single source of truth for the+// frequency↔note mapping every higher feature shares.+//+// The note model is deliberately the SAME diatonic `step` math the sheet-music+// renderer uses (`diatonicStep` is imported from scoreNotation.js, not+// re-derived) so a detected note lands on exactly the staff line/space the+// renderer would draw — that pixel-for-pixel alignment is what makes the+// color-match overlay line up with the score.+//+// Keep this module pure where it can be: the estimator and the two mappers are+// side-effect-free and unit-tested; only `createPitchTracker` touches Web Audio+// and a rAF loop, and it owns its own teardown.++import { diatonicStep } from './scoreNotation.js';++// === Note ↔ semitone tables ============================================++// Sharp spelling of each chromatic pitch class (0 = C). Matches the renderer's+// preference; enharmonic flat spelling (from the key signature) is a later+// concern for sing-to-score, not the raw detector.+const CHROMATIC = [+ { letter: 'C', accidental: '' }, { letter: 'C', accidental: '#' },+ { letter: 'D', accidental: '' }, { letter: 'D', accidental: '#' },+ { letter: 'E', accidental: '' },+ { letter: 'F', accidental: '' }, { letter: 'F', accidental: '#' },+ { letter: 'G', accidental: '' }, { letter: 'G', accidental: '#' },+ { letter: 'A', accidental: '' }, { letter: 'A', accidental: '#' },+ { letter: 'B', accidental: '' },+];++// Diatonic letter → its pitch class (semitones above C). The inverse direction+// of CHROMATIC, used to turn a notated note back into a frequency.+const LETTER_SEMITONE = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };++// Accidental glyph → chromatic shift in semitones. Mirrors the accidental set+// `parsePitch` produces ('', '#', '##', 'b', 'bb', 'n').+const ACCIDENTAL_SHIFT = { '': 0, n: 0, '#': 1, '##': 2, b: -1, bb: -2 };++// === Frequency ↔ note mapping ==========================================++// Convert a frequency (Hz) to the nearest equal-tempered note plus how far the+// pitch sits from that note's center, in cents. `a4` is the reference pitch+// (concert A, default 440) — a parameter now so an alternate tuning is a config+// change, not a refactor. Returns `{ letter, accidental, octave, step, cents }`+// where `step` is the diatonic staff position (C4 = 0) the renderer draws, and+// `cents` ∈ [-50, +50] with the conventional sign: **sharp is positive**.+export const frequencyToNote = (hz, { a4 = 440 } = {}) => {+ if (!Number.isFinite(hz) || hz <= 0) return null;+ // MIDI-style continuous pitch: 69 = A4. log2 turns the ratio into octaves,+ // ×12 into semitones. Rounding to the nearest integer picks the note; the+ // fractional remainder is the detune.+ const midiFloat = 69 + 12 * Math.log2(hz / a4);+ const midi = Math.round(midiFloat);+ const cents = Math.round((midiFloat - midi) * 100); // sharp → positive+ const octave = Math.floor(midi / 12) - 1; // MIDI 60 = C4+ const semitone = ((midi % 12) + 12) % 12;+ const { letter, accidental } = CHROMATIC[semitone];+ return { letter, accidental, octave, step: diatonicStep(letter, octave), cents };+};++// Inverse of `frequencyToNote`: the exact frequency of a notated note (the+// `{ letter, accidental, octave }` shape `parsePitch` / `frequencyToNote`+// produce). Used by color-match to compute each target note's frequency. Cents+// are intentionally ignored — this returns the note's ideal center pitch.+// Returns null for anything that isn't a recognizable note.+export const noteToFrequency = (note, { a4 = 440 } = {}) => {+ if (!note) return null;+ const base = LETTER_SEMITONE[String(note.letter || '').toUpperCase()];+ const shift = ACCIDENTAL_SHIFT[note.accidental || ''];+ if (base == null || shift == null || !Number.isFinite(note.octave)) return null;+ const midi = (note.octave + 1) * 12 + base + shift; // (octave+1)*12: C4 → 60+ return a4 * Math.pow(2, (midi - 69) / 12);+};++// === Fundamental-frequency estimation ==================================++// Estimate the fundamental frequency of a Float32 PCM frame via the McLeod+// Pitch Method: a normalized square-difference function (NSDF) plus+// first-tall-peak picking. The NSDF is bounded to [-1, 1] — a clean periodic+// signal peaks near 1 at its period, while noise stays near 0 — so its peak+// height doubles as a **clarity** (confidence) score that rejects noise and+// silence. Returns `{ hz, clarity }`, or null for silence / no clear pitch.+//+// `sampleRate` is required to convert lag → Hz; the rest bound the search to a+// vocal range and set the silence / clarity gates (the silence gate reuses the+// per-frame energy intuition behind `audioRecorder.js`'s peak warning).+export const detectFrequency = (frame, opts = {}) => {+ const {+ sampleRate = 44100,+ minHz = 55,+ maxHz = 1600,+ rmsFloor = 0.01,+ clarityFloor = 0.5,+ } = opts;+ const size = frame?.length || 0;+ if (size < 2) return null;++ // Silence gate: a frame quieter than the floor carries no pitch worth+ // reporting (a dead/near-silent mic), so bail before the O(N·lag) NSDF.+ let rms = 0;+ for (let i = 0; i < size; i++) rms += frame[i] * frame[i];+ rms = Math.sqrt(rms / size);+ if (rms < rmsFloor) return null;++ // Search lags spanning [maxHz, minHz]. A lag (period in samples) of τ maps to+ // sampleRate/τ Hz, so a higher frequency is a shorter lag.+ const maxLag = Math.min(size - 1, Math.floor(sampleRate / minHz));+ const minLag = Math.max(1, Math.floor(sampleRate / maxHz));+ if (maxLag <= minLag) return null;++ // NSDF[τ] = 2·Σ x[j]x[j+τ] / Σ (x[j]² + x[j+τ]²). The shrinking window+ // (j+τ < size) tapers long lags slightly, which is fine — we only need the+ // first strong peak, not absolute amplitudes.+ const nsdf = new Float32Array(maxLag + 1);+ for (let tau = minLag; tau <= maxLag; tau++) {+ let acf = 0;+ let denom = 0;+ for (let j = 0; j + tau < size; j++) {+ acf += frame[j] * frame[j + tau];+ denom += frame[j] * frame[j] + frame[j + tau] * frame[j + tau];+ }+ nsdf[tau] = denom > 0 ? (2 * acf) / denom : 0;+ }++ // Key-maximum picking: the highest point of each positive hump. We skip any+ // positive plateau at the very start (the tail of the τ=0 central lobe) so a+ // sub-period correlation can't masquerade as the fundamental, then take the+ // max within each subsequent hump.+ const peaks = [];+ let tau = minLag;+ while (tau <= maxLag && nsdf[tau] > 0) tau++; // descend out of the central lobe+ while (tau <= maxLag) {+ if (nsdf[tau] > 0) {+ let best = tau;+ while (tau <= maxLag && nsdf[tau] > 0) {+ if (nsdf[tau] > nsdf[best]) best = tau;+ tau++;+ }+ peaks.push(best);+ } else {+ tau++;+ }+ }+ if (!peaks.length) return null;++ // Clarity is the tallest hump. Below the floor we treat the frame as noise.+ let globalMax = 0;+ for (const p of peaks) if (nsdf[p] > globalMax) globalMax = nsdf[p];+ if (globalMax < clarityFloor) return null;++ // Pick the FIRST hump that reaches 90% of the tallest, not the global max —+ // this is the MPM trick that keeps an octave-down sub-harmonic (which can be+ // marginally taller) from winning over the true fundamental.+ const chosen = peaks.find((p) => nsdf[p] >= 0.9 * globalMax);+ if (chosen == null) return null;++ // Parabolic interpolation around the chosen lag for sub-sample period+ // precision — without it the pitch quantizes to integer-lag steps, which is+ // tens of cents of error at higher frequencies.+ const x0 = chosen > 0 ? nsdf[chosen - 1] : nsdf[chosen];+ const x1 = nsdf[chosen];+ const x2 = chosen < maxLag ? nsdf[chosen + 1] : nsdf[chosen];+ const curve = x0 - 2 * x1 + x2;+ const shift = curve !== 0 ? (0.5 * (x0 - x2)) / curve : 0;+ const period = chosen + shift;+ if (period <= 0) return null;++ return { hz: sampleRate / period, clarity: globalMax };+};++// === Live tracker ======================================================++// Median of a short numeric array (odd or even length). Used to smooth the+// per-frame pitch — the median kills the lone octave-jump outliers that raw+// frame-by-frame vocal detection produces, where a mean would smear them 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;+};++// Drive a live pitch readout off a Web Audio `AnalyserNode`. Pulls time-domain+// frames on a rAF (or interval) loop, runs `detectFrequency`, smooths the result+// (median window to drop octave jumps, then an EMA to settle the needle), and+// emits `{ hz, note, cents, clarity }` through `onUpdate`. While the frame is+// silent / unclear it emits nulls so the UI can show "no pitch" rather than+// freezing on the last note.+//+// Returns `{ stop }`. `stop()` cancels the loop — call it on stop/unmount so no+// rAF or timer dangles (the deferred-work teardown rule in CLAUDE.md). The loop+// body is wrapped so a throw inside an animation-frame callback (which has no+// Express `next(err)` to bubble to) can't crash the tab.+export const createPitchTracker = (analyser, opts = {}) => {+ const {+ onUpdate,+ a4 = 440,+ minHz = 70,+ maxHz = 1200,+ clarityThreshold = 0.9,+ medianWindow = 5,+ emaAlpha = 0.25,+ intervalMs = null, // when set, use setInterval instead of requestAnimationFrame+ } = opts;++ const sampleRate = analyser?.context?.sampleRate || 44100;+ const frame = new Float32Array(analyser?.fftSize || 2048);+ const recent = []; // recent clear-frame Hz for the median window+ let emaHz = null;+ let running = true;+ let rafId = null;+ let timerId = null;++ const schedule = () => {+ if (!running) return;+ if (intervalMs != null) timerId = setTimeout(tick, intervalMs);+ else if (typeof requestAnimationFrame === 'function') rafId = requestAnimationFrame(tick);+ else timerId = setTimeout(tick, 1000 / 60);+ };++ const tick = () => {+ if (!running) return;+ try {+ analyser.getFloatTimeDomainData(frame);+ const res = detectFrequency(frame, { sampleRate, minHz, maxHz });+ if (res && res.clarity >= clarityThreshold) {+ recent.push(res.hz);+ if (recent.length > medianWindow) recent.shift();+ const med = median(recent);+ emaHz = emaHz == null ? med : emaAlpha * med + (1 - emaAlpha) * emaHz;+ const note = frequencyToNote(emaHz, { a4 });+ onUpdate?.({ hz: emaHz, note, cents: note?.cents ?? null, clarity: res.clarity });+ } else {+ // Lost the pitch — reset the smoother so a new note doesn't ramp in from+ // the stale one, and report the gap.+ recent.length = 0;+ emaHz = null;+ onUpdate?.({ hz: null, note: null, cents: null, clarity: res?.clarity ?? 0 });+ }+ } catch (err) {+ console.error(`❌ pitch tracker frame failed: ${err.message}`);+ }+ schedule();+ };++ schedule();++ return {+ stop: () => {+ running = false;+ if (rafId != null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(rafId);+ if (timerId != null) clearTimeout(timerId);+ rafId = null;+ timerId = null;+ },+ };+};diff --git a/client/src/lib/pitchDetect.test.js b/client/src/lib/pitchDetect.test.jsnew file mode 100644index 0000000000..b44f8937bd--- /dev/null+++ b/client/src/lib/pitchDetect.test.js@@ -0,0 +1,180 @@+import { describe, it, expect } from 'vitest';+import {+ detectFrequency,+ frequencyToNote,+ noteToFrequency,+ createPitchTracker,+} from './pitchDetect.js';++const SAMPLE_RATE = 44100;++// Fill a Float32 frame with a pure sine of `hz` at the given amplitude.+const sine = (hz, { sampleRate = SAMPLE_RATE, length = 4096, amplitude = 0.5 } = {}) => {+ const buf = new Float32Array(length);+ for (let i = 0; i < length; i++) buf[i] = amplitude * Math.sin((2 * Math.PI * hz * i) / sampleRate);+ return buf;+};++// Deterministic pseudo-random white noise (seeded LCG so the test never flakes).+const noise = ({ length = 4096, amplitude = 0.5, seed = 12345 } = {}) => {+ const buf = new Float32Array(length);+ let s = seed >>> 0;+ for (let i = 0; i < length; i++) {+ s = (1664525 * s + 1013904223) >>> 0;+ buf[i] = ((s / 0xffffffff) * 2 - 1) * amplitude;+ }+ return buf;+};++describe('frequencyToNote', () => {+ it('maps concert pitches to the right letter + octave + step', () => {+ expect(frequencyToNote(440)).toMatchObject({ letter: 'A', accidental: '', octave: 4 });+ expect(frequencyToNote(261.63)).toMatchObject({ letter: 'C', octave: 4, step: 0 });+ expect(frequencyToNote(523.25)).toMatchObject({ letter: 'C', octave: 5, step: 7 });+ expect(frequencyToNote(130.81)).toMatchObject({ letter: 'C', octave: 3, step: -7 });+ });++ it('reports a sharp pitch class with a sharp accidental', () => {+ // F#4 ≈ 369.99 Hz+ expect(frequencyToNote(369.99)).toMatchObject({ letter: 'F', accidental: '#', octave: 4 });+ });++ it('aligns step with scoreNotation (A4 = step 5, treble top space)', () => {+ expect(frequencyToNote(440).step).toBe(5);+ });++ it('cents are zero at a note center and signed (sharp positive, flat negative)', () => {+ expect(frequencyToNote(440).cents).toBe(0);+ // 20 cents sharp of A4 → positive; 20 cents flat → negative.+ expect(frequencyToNote(440 * Math.pow(2, 20 / 1200)).cents).toBeGreaterThan(0);+ expect(frequencyToNote(440 * Math.pow(2, -20 / 1200)).cents).toBeLessThan(0);+ expect(Math.abs(frequencyToNote(450).cents)).toBeLessThanOrEqual(50);+ });++ it('honors a non-440 a4 reference', () => {+ expect(frequencyToNote(432, { a4: 432 })).toMatchObject({ letter: 'A', octave: 4, cents: 0 });+ // 440 read against a 432 reference is sharp of A4.+ expect(frequencyToNote(440, { a4: 432 })).toMatchObject({ letter: 'A', octave: 4 });+ expect(frequencyToNote(440, { a4: 432 }).cents).toBeGreaterThan(0);+ });++ it('returns null for non-positive / non-finite input', () => {+ expect(frequencyToNote(0)).toBeNull();+ expect(frequencyToNote(-100)).toBeNull();+ expect(frequencyToNote(NaN)).toBeNull();+ });+});++describe('noteToFrequency', () => {+ it('returns the standard frequency of common notes', () => {+ expect(noteToFrequency({ letter: 'A', accidental: '', octave: 4 })).toBeCloseTo(440, 5);+ expect(noteToFrequency({ letter: 'C', octave: 4 })).toBeCloseTo(261.6256, 2);+ expect(noteToFrequency({ letter: 'A', octave: 5 })).toBeCloseTo(880, 5);+ });++ it('applies accidentals', () => {+ expect(noteToFrequency({ letter: 'F', accidental: '#', octave: 4 })).toBeCloseTo(369.994, 2);+ expect(noteToFrequency({ letter: 'B', accidental: 'b', octave: 3 })).toBeCloseTo(233.082, 2);+ });++ it('honors a non-440 a4 reference', () => {+ expect(noteToFrequency({ letter: 'A', octave: 4 }, { a4: 432 })).toBeCloseTo(432, 5);+ });++ it('returns null for an unrecognizable note', () => {+ expect(noteToFrequency(null)).toBeNull();+ expect(noteToFrequency({ letter: 'H', octave: 4 })).toBeNull();+ expect(noteToFrequency({ letter: 'C' })).toBeNull();+ });++ it('round-trips through frequencyToNote within a cent of tolerance', () => {+ for (const hz of [261.63, 440, 587.33, 450, 333.2]) {+ const note = frequencyToNote(hz);+ // Reconstruct: note center × the detune the detector reported.+ const recon = noteToFrequency(note) * Math.pow(2, note.cents / 1200);+ expect(recon).toBeCloseTo(hz, 0); // within ~0.5 cent (cents are integer-rounded)+ }+ });+});++describe('detectFrequency', () => {+ it('recovers the fundamental of a pure sine across the vocal range', () => {+ for (const hz of [130.81, 261.63, 440, 587.33, 880]) {+ const res = detectFrequency(sine(hz), { sampleRate: SAMPLE_RATE });+ expect(res).not.toBeNull();+ expect(res.hz).toBeCloseTo(hz, 0); // within ~1 Hz+ expect(res.clarity).toBeGreaterThan(0.5);+ }+ });++ it('detected sine → correct note + octave', () => {+ const res = detectFrequency(sine(440), { sampleRate: SAMPLE_RATE });+ expect(frequencyToNote(res.hz)).toMatchObject({ letter: 'A', octave: 4 });+ const c4 = detectFrequency(sine(261.63), { sampleRate: SAMPLE_RATE });+ expect(frequencyToNote(c4.hz)).toMatchObject({ letter: 'C', octave: 4 });+ });++ it('cents sign survives detection (slightly sharp → positive, flat → negative)', () => {+ const sharp = detectFrequency(sine(440 * Math.pow(2, 30 / 1200)), { sampleRate: SAMPLE_RATE });+ const flat = detectFrequency(sine(440 * Math.pow(2, -30 / 1200)), { sampleRate: SAMPLE_RATE });+ expect(frequencyToNote(sharp.hz)).toMatchObject({ letter: 'A', octave: 4 });+ expect(frequencyToNote(sharp.hz).cents).toBeGreaterThan(0);+ expect(frequencyToNote(flat.hz).cents).toBeLessThan(0);+ });++ it('returns null for silence', () => {+ expect(detectFrequency(new Float32Array(4096), { sampleRate: SAMPLE_RATE })).toBeNull();+ });++ it('returns null for white noise (clarity gate)', () => {+ expect(detectFrequency(noise(), { sampleRate: SAMPLE_RATE })).toBeNull();+ });++ it('returns null for an empty / tiny frame', () => {+ expect(detectFrequency(new Float32Array(0))).toBeNull();+ expect(detectFrequency(new Float32Array(1))).toBeNull();+ });+});++describe('createPitchTracker', () => {+ // Minimal fake AnalyserNode: fills the frame with a fixed sine each pull.+ const fakeAnalyser = (hz) => ({+ fftSize: 4096,+ context: { sampleRate: SAMPLE_RATE },+ getFloatTimeDomainData: (out) => {+ for (let i = 0; i < out.length; i++) out[i] = 0.5 * Math.sin((2 * Math.PI * hz * i) / SAMPLE_RATE);+ },+ });++ it('emits a smoothed note for a steady tone and stops cleanly', async () => {+ const updates = [];+ const tracker = createPitchTracker(fakeAnalyser(440), {+ intervalMs: 1, // drive off a timer so the test doesn't depend on rAF+ onUpdate: (u) => updates.push(u),+ });+ await new Promise((r) => setTimeout(r, 50));+ tracker.stop();+ const before = updates.length;+ expect(before).toBeGreaterThan(0);+ const last = updates[updates.length - 1];+ expect(last.note).toMatchObject({ letter: 'A', octave: 4 });+ expect(last.clarity).toBeGreaterThan(0.5);+ // No further callbacks after stop().+ await new Promise((r) => setTimeout(r, 20));+ expect(updates.length).toBe(before);+ });++ it('emits nulls when the frame is silent', async () => {+ const silent = {+ fftSize: 2048,+ context: { sampleRate: SAMPLE_RATE },+ getFloatTimeDomainData: (out) => out.fill(0),+ };+ const updates = [];+ const tracker = createPitchTracker(silent, { intervalMs: 1, onUpdate: (u) => updates.push(u) });+ await new Promise((r) => setTimeout(r, 30));+ tracker.stop();+ expect(updates.length).toBeGreaterThan(0);+ expect(updates[updates.length - 1]).toMatchObject({ hz: null, note: null });+ });+});