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

fix([issue-2109]): stabilize live PitchTuner with clarity hysteresis, hold window, and sticky note label

Adam Eivy9895b4fbc0a0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c5d8c6fe8c..bfa50219ae 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## Songs
+
+- **[issue-2109] The live vocal Tuner now locks onto the note you're singing instead of flickering.** Holding a steady note used to make the readout strobe — the note label flipped between neighbors, the needle lurched, and the display dropped to "—" on every breath or consonant. The tuner now holds a stable reading through brief dropouts (dimming while it coasts), only blanks after a real pause, keeps one note label while your pitch wanders up to ~60¢ around it, and re-locks promptly when you actually change notes — so a held note shows one label with a gently moving needle.
+
## Media
- **[issue-2036] Sketch & Annotation Canvas (phase 2): re-render an image guided by your annotations.** The annotate page (`/media/annotate/:mediaKey`) gained a "Re-render" action: draw over a generated image, then feed your markup back through local img2img so the marks reshape the render. A confirmation dialog names the exact local model it will run (no surprise AI calls) and lets you add an optional prompt and tune how much to change before it starts; the new render is queued and appears in Media History. Requires a local FLUX img2img runner — the action explains when one isn't available. Phase 3 (blank-canvas storyboard) remains open on #2036.
diff --git a/client/src/components/songs/PitchTuner.jsx b/client/src/components/songs/PitchTuner.jsx
index 94de53c72f..46039932a8 100644
--- a/client/src/components/songs/PitchTuner.jsx
+++ b/client/src/components/songs/PitchTuner.jsx
@@ -51,8 +51,11 @@ const noteLabel = (note) => {
};
export default function PitchTuner({ stream = null, a4 = 440 }) {
- // `reading` is the latest tracker frame: { note, cents } (nulls when no pitch).
- const [reading, setReading] = useState({ note: null, cents: null });
+ // `reading` is the latest tracker frame: { note, cents, held } (nulls when no
+ // pitch). `held` is true while the tracker is coasting on the last stable
+ // reading through a brief dropout — we dim the readout so a held frame reads as
+ // "still that note" rather than a fresh detection.
+ const [reading, setReading] = useState({ note: null, cents: null, held: false });
const [standaloneOn, setStandaloneOn] = useState(false);
const trackerRef = useRef(null); // active pitch tracker { stop }
const analyserRef = useRef(null); // active { close } stream-analyser graph
@@ -68,7 +71,7 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
const teardownTracker = useCallback(() => {
if (trackerRef.current) { trackerRef.current.stop(); trackerRef.current = null; }
if (analyserRef.current) { analyserRef.current.close(); analyserRef.current = null; }
- setReading({ note: null, cents: null });
+ setReading({ note: null, cents: null, held: false });
}, []);
// Attach the tuner to a stream. Returns nothing; teardownTracker() detaches.
@@ -79,9 +82,14 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
analyserRef.current = graph;
trackerRef.current = createPitchTracker(graph.analyser, {
a4,
+ // Cap the readout to ~12Hz (the lib's acquire/hold hysteresis, release
+ // window, and sticky note label all use their defaults) so the note/cents
+ // don't strobe at the 60fps frame rate; the tracker's smoothed value keeps
+ // the needle motion fluid between emits.
+ updateHz: 12,
onUpdate: (u) => {
if (!mountedRef.current) return; // navigation-away guard
- setReading({ note: u.note, cents: u.cents });
+ setReading({ note: u.note, cents: u.cents, held: !!u.held });
},
});
}, [a4, teardownTracker]);
@@ -145,11 +153,16 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
const active = Boolean(stream) || standaloneOn;
const quality = tuningQuality(reading.cents);
- // Needle position 0–100% across the bar; 50% is dead-center (in tune).
- const clamped = Number.isFinite(reading.cents)
+ // Needle position 0–100% across the bar; 50% is dead-center (in tune). The
+ // tracker's sticky note label reports cents relative to the held note, so a
+ // wandering pitch can read past ±50¢ — clamp so the needle stays on the bar and
+ // the displayed number stays within a semitone.
+ const displayCents = Number.isFinite(reading.cents)
? Math.max(-CENTS_SPAN, Math.min(CENTS_SPAN, reading.cents))
: 0;
- const needlePct = 50 + (clamped / CENTS_SPAN) * 50;
+ const needlePct = 50 + (displayCents / CENTS_SPAN) * 50;
+ // Dim the readout while coasting on a held reading through a brief dropout.
+ const heldDim = reading.held ? 'opacity-60' : '';
return (
<div className="bg-port-card border border-port-border rounded-lg p-3">
@@ -182,13 +195,13 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
</div>
{/* Note + cents readout */}
- <div className="flex items-end justify-center gap-3 mt-3" aria-live="polite">
+ <div className={`flex items-end justify-center gap-3 mt-3 transition-opacity ${heldDim}`} aria-live="polite">
<span className={`text-4xl font-bold tabular-nums leading-none ${LEVEL_TONE[quality.level]}`}>
{noteLabel(reading.note)}
</span>
<span className={`text-sm pb-1 ${LEVEL_TONE[quality.level]}`}>
{Number.isFinite(reading.cents) && reading.note
- ? `${reading.cents > 0 ? '+' : ''}${reading.cents}¢ · ${quality.label}`
+ ? `${displayCents > 0 ? '+' : ''}${displayCents}¢ · ${quality.label}`
: active ? 'Listening…' : 'Idle'}
</span>
</div>
diff --git a/client/src/hooks/useColorMatch.js b/client/src/hooks/useColorMatch.js
index 20886fe9dd..aa803d15ba 100644
--- a/client/src/hooks/useColorMatch.js
+++ b/client/src/hooks/useColorMatch.js
@@ -206,7 +206,12 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =
trackerRef.current = createPitchTracker(graph.analyser, {
a4,
// Keep hz + clarity — grade() reads hz for scoring and samples both
- // (plus cents-from-target) into the persisted tuner trace.
+ // (plus cents-from-target) into the persisted tuner trace. Grading wants
+ // the raw signal, so opt out of the tuner-readout hysteresis: a single
+ // clarity gate (no acquire/hold split) and an immediate null on an unclear
+ // frame (no release-window hold) rather than coasting on a stale pitch.
+ holdClarity: 0.9,
+ releaseFrames: 0,
onUpdate: (u) => { pitchRef.current = { hz: u.hz, clarity: u.clarity ?? null }; },
});
diff --git a/client/src/hooks/useSingToScore.js b/client/src/hooks/useSingToScore.js
index cb320a437b..4b62206ba6 100644
--- a/client/src/hooks/useSingToScore.js
+++ b/client/src/hooks/useSingToScore.js
@@ -116,6 +116,13 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
// relative to beat 1 of the bar.
trackerRef.current = createPitchTracker(graph.analyser, {
intervalMs: FRAME_INTERVAL_MS,
+ // Transcription wants the raw per-frame track: a single clarity gate (no
+ // acquire/hold hysteresis) and an immediate null on an unclear frame (no
+ // release-window hold), so a dropout is a real gap the segmenter can see
+ // rather than a stale held pitch. The tuner's hysteresis defaults are for
+ // the live readout, not the captured signal.
+ holdClarity: 0.9,
+ releaseFrames: 0,
onUpdate: (u) => {
if (!capturingRef.current) return;
const tMs = nowMs() - captureStartRef.current;
diff --git a/client/src/lib/pitchDetect.js b/client/src/lib/pitchDetect.js
index b925e96978..832e8cffe4 100644
--- a/client/src/lib/pitchDetect.js
+++ b/client/src/lib/pitchDetect.js
@@ -210,9 +210,36 @@ const median = (values) => {
// 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.
+// emits `{ hz, note, cents, clarity, held }` through `onUpdate`.
+//
+// Raw frame-by-frame vocal detection is jittery — vibrato, consonants, and
+// breath dips routinely drop NSDF clarity below a strict gate for a frame or two
+// while the note itself is perfectly steady. Without smoothing the readout
+// strobes: the label flickers, the needle lurches, and the display blanks
+// mid-note. Four knobs tame that, all configurable so the raw behavior stays
+// available to callers (sing-to-score, color-match) that want every frame:
+//
+// - **Acquire/hold hysteresis** (`acquireClarity` / `holdClarity`). We require a
+// strong frame (≥ `acquireClarity`) to START believing a pitch, but only a
+// weaker one (≥ `holdClarity`) to KEEP believing it — so a mid-note clarity
+// dip still feeds the smoother instead of tearing it down. Below `holdClarity`
+// a frame counts as "unclear".
+// - **Release window** (`releaseMs` / `releaseFrames`). A short run of unclear
+// frames keeps emitting the last smoothed reading (flagged `held: true`) rather
+// than blanking on the first bad frame; only once the window elapses do we emit
+// nulls and reset the smoother (so a new note doesn't ramp from the stale EMA).
+// - **Sticky note label** (`stickyCents`). The note label stays put until the
+// smoothed pitch drifts more than ±`stickyCents` from that note's center —
+// singing ~50¢ between C and C♯ no longer flaps the label C↔C♯. Cents are
+// reported relative to the held note (so they pass through ±50 continuously
+// instead of snapping sign); a clean semitone step blows past the band and
+// re-derives within a few frames.
+// - **Emit throttle** (`updateHz`). Cap the callback rate (e.g. the tuner's
+// ~12Hz) so integer-cents redraws don't read as vibration; a material change
+// (note flip, held⇄live) still emits immediately. `null` = emit every frame.
+//
+// Back-compat: a legacy `clarityThreshold` is honored as the `acquireClarity`
+// fallback.
//
// 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
@@ -224,20 +251,91 @@ export const createPitchTracker = (analyser, opts = {}) => {
a4 = 440,
minHz = 70,
maxHz = 1200,
- clarityThreshold = 0.9,
+ clarityThreshold, // legacy single-threshold → acquireClarity fallback
+ acquireClarity = clarityThreshold ?? 0.9,
+ holdClarity = 0.6,
medianWindow = 5,
emaAlpha = 0.25,
- intervalMs = null, // when set, use setInterval instead of requestAnimationFrame
+ stickyCents = 60,
+ releaseMs = 250,
+ releaseFrames = null, // wins over releaseMs when given (frame-exact)
+ updateHz = null, // emit throttle in Hz; null = every frame
+ intervalMs = null, // when set, use setTimeout 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;
+
+ // Resolve the release window into a frame count. A frame is `intervalMs` (when
+ // the loop is timer-driven) or ~16.7 ms (rAF at 60fps); `releaseFrames` wins
+ // when given so tests can pin an exact count independent of the loop rate.
+ const frameMs = intervalMs != null ? intervalMs : 1000 / 60;
+ const holdFrames = releaseFrames != null
+ ? Math.max(0, releaseFrames)
+ : Math.max(0, Math.round(releaseMs / frameMs));
+ const minEmitMs = updateHz != null && updateHz > 0 ? 1000 / updateHz : 0;
+
+ const recent = []; // recent clear-frame Hz for the median window
+ let emaHz = null; // smoothed pitch
+ let acquired = false; // do we currently hold a believed pitch?
+ let unclearRun = 0; // consecutive unclear frames since the last clear one
+ let stickyNote = null; // the note label we're holding across the ±stickyCents band
+ let lastEmitted = null; // last reading handed to onUpdate (throttle bookkeeping)
+ let lastEmitMs = null;
let running = true;
let rafId = null;
let timerId = null;
+ const clockMs = () => (typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now());
+
+ // Note identity for throttle material-change detection (a null note is '∅').
+ const noteId = (note) => (note ? `${note.letter}${note.accidental}${note.octave}` : '∅');
+
+ // Pick the note label for a smoothed pitch, keeping the current label sticky
+ // until the pitch drifts more than ±stickyCents from that note's center. A
+ // clean semitone step (100¢) blows past the band and re-derives.
+ const resolveNote = (hz) => {
+ const fresh = frequencyToNote(hz, { a4 });
+ if (!fresh) return stickyNote;
+ if (!stickyNote) { stickyNote = fresh; return stickyNote; }
+ const centerHz = noteToFrequency(stickyNote, { a4 });
+ const drift = centerHz ? Math.abs(1200 * Math.log2(hz / centerHz)) : Infinity;
+ if (drift > stickyCents) stickyNote = fresh;
+ return stickyNote;
+ };
+
+ // Cents of `hz` relative to a HELD note's center (may exceed ±50 while sticky).
+ const centsFromHeld = (hz, note) => {
+ const centerHz = noteToFrequency(note, { a4 });
+ return centerHz ? Math.round(1200 * Math.log2(hz / centerHz)) : null;
+ };
+
+ const emit = (reading) => {
+ // Throttle: within a note, emit at most `updateHz`/sec; a material change
+ // (note flip, held⇄live) always emits so the UI never lags a real transition.
+ // `updateHz == null` (minEmitMs 0) disables the throttle — every frame emits.
+ if (minEmitMs > 0 && lastEmitted) {
+ const material = noteId(reading.note) !== noteId(lastEmitted.note) || reading.held !== lastEmitted.held;
+ if (!material && lastEmitMs != null && clockMs() - lastEmitMs < minEmitMs) return;
+ }
+ lastEmitted = reading;
+ lastEmitMs = clockMs();
+ onUpdate?.(reading);
+ };
+
+ const emitLive = (hz, clarity, held) => {
+ const note = resolveNote(hz);
+ emit({ hz, note, cents: note ? centsFromHeld(hz, note) : null, clarity, held });
+ };
+
+ const reset = () => {
+ recent.length = 0;
+ emaHz = null;
+ acquired = false;
+ unclearRun = 0;
+ stickyNote = null;
+ };
+
const schedule = () => {
if (!running) return;
if (intervalMs != null) timerId = setTimeout(tick, intervalMs);
@@ -250,19 +348,30 @@ export const createPitchTracker = (analyser, opts = {}) => {
try {
analyser.getFloatTimeDomainData(frame);
const res = detectFrequency(frame, { sampleRate, minHz, maxHz });
- if (res && res.clarity >= clarityThreshold) {
+ const clarity = res?.clarity ?? 0;
+ // Acquire high, hold low: once we believe a pitch a frame merely above the
+ // hold floor still updates the smoother; only from silence do we require the
+ // stricter acquire floor.
+ const clear = !!res && clarity >= (acquired ? holdClarity : acquireClarity);
+
+ if (clear) {
+ acquired = true;
+ unclearRun = 0;
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 });
+ emitLive(emaHz, clarity, false);
+ } else if (acquired && unclearRun < holdFrames && emaHz != null) {
+ // Brief dropout (consonant, breath, vibrato dip) — keep showing the last
+ // stable reading for up to the release window instead of blanking.
+ unclearRun += 1;
+ emitLive(emaHz, clarity, true);
} 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 });
+ // Truly lost the pitch — reset so a new note doesn't ramp in from the
+ // stale EMA, and report the gap.
+ reset();
+ emit({ hz: null, note: null, cents: null, clarity, held: false });
}
} catch (err) {
console.error(`❌ pitch tracker frame failed: ${err.message}`);
diff --git a/client/src/lib/pitchDetect.test.js b/client/src/lib/pitchDetect.test.js
index 93489d5ba4..e80ed9511f 100644
--- a/client/src/lib/pitchDetect.test.js
+++ b/client/src/lib/pitchDetect.test.js
@@ -209,3 +209,152 @@ describe('createPitchTracker', () => {
expect(updates[updates.length - 1]).toMatchObject({ hz: null, note: null });
});
});
+
+describe('createPitchTracker — hysteresis, hold, and sticky label', () => {
+ // Frame fillers for a scripted analyser: each produces a specific signal so we
+ // can drive clarity and pitch frame-by-frame. With the emit throttle OFF (the
+ // default), the tracker emits exactly one update per tick and consumes exactly
+ // one filler per tick — so `updates[k]` corresponds to `fillers[k]`, giving a
+ // deterministic sequence regardless of wall-clock timing.
+ const fillSine = (hz, amplitude = 0.5) => (out) => {
+ for (let i = 0; i < out.length; i++) out[i] = amplitude * Math.sin((2 * Math.PI * hz * i) / SAMPLE_RATE);
+ };
+ const fillSilence = () => (out) => out.fill(0);
+ // A sine buried in seeded noise — clarity ≈ 0.81 at noiseAmp 0.3 (measured):
+ // above holdClarity (0.6) but below acquireClarity (0.9), i.e. a "hold-band"
+ // frame. Deterministic (fixed seed) so it never flakes.
+ const fillMix = (hz, noiseAmp = 0.3, seed = 999) => (out) => {
+ let s = seed >>> 0;
+ for (let i = 0; i < out.length; i++) {
+ s = (1664525 * s + 1013904223) >>> 0;
+ out[i] = 0.5 * Math.sin((2 * Math.PI * hz * i) / SAMPLE_RATE) + ((s / 0xffffffff) * 2 - 1) * noiseAmp;
+ }
+ };
+
+ // Analyser that plays a scripted list of frame fillers in order, repeating the
+ // LAST one once the script is exhausted (so the loop keeps running in a stable
+ // terminal state while we wait for enough ticks to fire).
+ const scriptedAnalyser = (fillers, { fftSize = 4096 } = {}) => {
+ let i = 0;
+ return {
+ fftSize,
+ context: { sampleRate: SAMPLE_RATE },
+ getFloatTimeDomainData: (out) => {
+ fillers[Math.min(i, fillers.length - 1)](out);
+ i += 1;
+ },
+ };
+ };
+
+ // Concert frequencies used below.
+ const A4 = 440;
+ const AS4 = 440 * Math.pow(2, 1 / 12); // A♯4, a clean semitone up
+ const A4_PLUS_55 = 440 * Math.pow(2, 55 / 1200); // +55¢ of A4 (inside the sticky band)
+
+ const runScript = async (fillers, opts, ms = 90) => {
+ const updates = [];
+ const tracker = createPitchTracker(scriptedAnalyser(fillers), {
+ intervalMs: 1,
+ onUpdate: (u) => updates.push(u),
+ ...opts,
+ });
+ await new Promise((r) => setTimeout(r, ms));
+ tracker.stop();
+ return updates;
+ };
+
+ it('a single interleaved unclear frame is HELD, not nulled — the smoother survives it', async () => {
+ // Acquire + settle on A4 (6 clear frames), one dropout frame, then A4 again.
+ const script = [...Array(6).fill(fillSine(A4)), fillSilence(), ...Array(6).fill(fillSine(A4))];
+ const updates = await runScript(script, { releaseFrames: 3 });
+ // The display never blanked: every frame kept a note.
+ expect(updates.every((u) => u.note !== null)).toBe(true);
+ // The dropout frame was emitted as a HELD reading on the same note.
+ const held = updates.filter((u) => u.held);
+ expect(held.length).toBeGreaterThanOrEqual(1);
+ expect(held.every((u) => u.note?.letter === 'A' && u.note?.octave === 4)).toBe(true);
+ });
+
+ it('hold-band frames update an acquired pitch but never acquire from silence', async () => {
+ // From silence: a run of hold-band frames (clarity ~0.81 < acquire 0.9) must
+ // NOT acquire — the readout stays blank.
+ const fromSilence = await runScript(Array(12).fill(fillMix(A4)), {});
+ expect(fromSilence.length).toBeGreaterThan(0);
+ expect(fromSilence.every((u) => u.note === null)).toBe(true);
+
+ // Once acquired on clear frames, a hold-band frame keeps updating (it is
+ // clear-enough to HOLD, so it is emitted live — not as a held/coasting frame).
+ const afterAcquire = await runScript(
+ [...Array(6).fill(fillSine(A4)), ...Array(6).fill(fillMix(A4))],
+ {},
+ );
+ const holdBandLive = afterAcquire.filter(
+ (u) => u.note?.letter === 'A' && !u.held && u.clarity >= 0.6 && u.clarity < 0.9,
+ );
+ expect(holdBandLive.length).toBeGreaterThanOrEqual(1);
+ });
+
+ it('emits nulls only after the release window of consecutive unclear frames', async () => {
+ const RELEASE = 4;
+ const script = [...Array(6).fill(fillSine(A4)), ...Array(20).fill(fillSilence())];
+ const updates = await runScript(script, { releaseFrames: RELEASE });
+ const firstNull = updates.findIndex((u) => u.note === null);
+ // A null eventually arrives, but only after acquisition + the release window.
+ expect(firstNull).toBeGreaterThanOrEqual(6 + RELEASE);
+ // The RELEASE frames just before the first null are all HELD on A4…
+ const window = updates.slice(firstNull - RELEASE, firstNull);
+ expect(window.length).toBe(RELEASE);
+ expect(window.every((u) => u.held && u.note?.letter === 'A')).toBe(true);
+ // …and the frame before the window was a live (non-held) A4 reading.
+ expect(updates[firstNull - RELEASE - 1]).toMatchObject({ held: false });
+ expect(updates[firstNull - RELEASE - 1].note?.letter).toBe('A');
+ });
+
+ it('keeps one sticky label while the pitch wanders ±55¢, reporting cents past ±50', async () => {
+ // Settle on A4, then sustain +55¢ — inside the ±60¢ sticky band, so the label
+ // must stay A4 while cents (relative to the held note) climb past +50.
+ const script = [...Array(6).fill(fillSine(A4)), ...Array(12).fill(fillSine(A4_PLUS_55))];
+ const updates = await runScript(script, {});
+ const voiced = updates.filter((u) => u.note !== null);
+ expect(voiced.length).toBeGreaterThan(0);
+ expect(voiced.every((u) => u.note.letter === 'A' && u.note.accidental === '' && u.note.octave === 4)).toBe(true);
+ // Cents are relative to the HELD note, so they exceed the ±50 semitone edge.
+ expect(voiced.some((u) => u.cents > 50)).toBe(true);
+ });
+
+ it('switches the label within a few frames on a clean semitone step', async () => {
+ // Settle on A4, then step cleanly up to A♯4 (+100¢) — well past the sticky
+ // band, so the label re-derives.
+ const ACQUIRE = 6;
+ const script = [...Array(ACQUIRE).fill(fillSine(A4)), ...Array(20).fill(fillSine(AS4))];
+ const updates = await runScript(script, {}, 120);
+ // The final voiced reading is A♯4.
+ const voiced = updates.filter((u) => u.note !== null);
+ const last = voiced[voiced.length - 1];
+ expect(last.note).toMatchObject({ letter: 'A', accidental: '#', octave: 4 });
+ // …and it switched promptly — within a few frames of the step, not stuck on A4.
+ const firstSharp = updates.findIndex((u) => u.note?.accidental === '#');
+ expect(firstSharp).toBeGreaterThanOrEqual(ACQUIRE);
+ expect(firstSharp - ACQUIRE).toBeLessThanOrEqual(12);
+ });
+
+ it('throttles emits to ~updateHz for a steady tone (vs every frame unthrottled)', async () => {
+ const steady = () => ({
+ 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 * A4 * i) / SAMPLE_RATE); },
+ });
+ const unthrottled = [];
+ const throttled = [];
+ const t1 = createPitchTracker(steady(), { intervalMs: 1, onUpdate: (u) => unthrottled.push(u) });
+ const t2 = createPitchTracker(steady(), { intervalMs: 1, updateHz: 12, onUpdate: (u) => throttled.push(u) });
+ await new Promise((r) => setTimeout(r, 120));
+ t1.stop();
+ t2.stop();
+ // A steady note has no material change after acquisition, so the throttle caps
+ // the ~12Hz stream far below the per-frame (~1kHz here) unthrottled stream.
+ expect(throttled.length).toBeGreaterThanOrEqual(1);
+ expect(unthrottled.length).toBeGreaterThan(throttled.length);
+ expect(throttled.length).toBeLessThanOrEqual(6);
+ });
+});