diff --git a/README.md b/README.md index 38ea95a..6696263 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ A chromatic instrument tuner that runs in the browser and on Android. It listens ## Features -- Real-time pitch detection using the [pitchy](https://github.com/ianprime0509/pitchy) library (McLeod Pitch Method) +- Pitch detection built for tuning strings: accurate to a fraction of a cent (pedal tuners are rated ±1 cent), in tune within ±3 cents, and not thrown off by the string you tuned before still ringing - Multiple instrument categories: guitar, bass, ukulele, and violin — each with tailored signal-processing parameters - Preset tunings (Standard, Drop D, Half Step Down, Open tunings, scordatura variants, and more) - Sequential string-by-string tuning flow — starts on the lowest/thickest string, confirms in tune, then auto-advances; tap any chip to jump to a specific string @@ -45,7 +45,6 @@ A chromatic instrument tuner that runs in the browser and on Android. It listens - [Vite](https://vitejs.dev/) - [Capacitor](https://capacitorjs.com/) for Android packaging - [vue-i18n](https://vue-i18n.intlify.dev/) for localisation -- [pitchy](https://github.com/ianprime0509/pitchy) for pitch detection - [Nunito](https://fonts.google.com/specimen/Nunito) (SIL Open Font License), bundled with the app - [Vitest](https://vitest.dev/) and [ESLint](https://eslint.org/), run on every pull request @@ -70,99 +69,53 @@ The large files are stored with [Git LFS](https://git-lfs.com/). Run `git lfs in ## Signal Processing Architecture -The audio pipeline runs at two rates: +The tuner always knows which string it is listening for, and every stage is aimed at it. -| Layer | Rate | Responsibility | -|---|---|---| -| Engine | ~60fps (16ms) | RMS gate, transient gate, pitchy, deliver `AudioFrame` | -| Presentation | ~30fps (33ms) | Write Vue reactive refs, update needle/ring/hint | +| Layer | Where | Rate | Responsibility | +|---|---|---|---| +| Capture | `useAudioCapture` | ~60fps (16ms) | Microphone, low-pass filter, noise gate, deliver `AudioFrame` | +| Detector | `src/tuner/detector.ts` | per frame | Pitch of the string to a fraction of a cent, its clarity, its share of the sound | +| Engine | `src/tuner/engine.ts` | per frame | Reading, needle, in tune, confirm, next string | +| Presentation | `useTuner` | ~30fps (33ms) | Write Vue reactive refs, update needle/ring/hint | -### Per-instrument configuration - -Each instrument category has its own profile in `INSTRUMENT_CONFIGS`. -The **decay gate** applies when string RMS drops below 0.04 (quiet tail). It must always be -≤ the normal clarity gate — decaying strings produce noisier signals, so the gate must be -*more* permissive, not stricter. - -| Instrument | FFT window | Stable time | Clarity gate | Decay gate | -|---|---|---|---|---| -| Bass | 8192 (~185ms) | 1500ms | 0.93 | 0.82 | -| Guitar | 2048 (~46ms) | 1100ms | 0.92 | 0.80 | -| Ukulele | 2048 | 800ms | 0.85 | 0.75 | -| Violin | 2048 | 600ms | 0.80 | 0.70 | - -### Signal chain (per tick) - -**Every tick (useAudioCapture):** -1. **RMS noise gate** — frames below 0.01 RMS are discarded (silence / room noise) -2. **Attack transient gate** — 80ms suppression window after a >3× RMS spike (pick attack) -3. **Low-pass filter** — always active as an audio graph node; cutoff = 3× locked string fundamental, clamped 280–2000Hz; updated per string -4. **Pitchy (primary)** — McLeod pitch detection on the primary FFT window -5. **Large-window fallback** — if primary clarity < 0.92, a secondary 8192-sample analyser is tried (guitar/ukulele/violin only; bass uses 8192 as primary) - -**Happy path — pitch passes frequency window and clarity gate (useTuner):** - -6. **Frequency window + clarity gate** — pitch must be within ±15% of the locked fundamental and above the instrument clarity threshold -7. **Median filter** — 22-frame rolling median (~350ms) removes transient octave errors -8. **Octave-fold correction** — if dividing by N=2–6 brings the pitch within 300¢ and improves by >400¢, use the folded value -9. **Pitch continuity gate** — discard if EMA would jump >500¢ in one tick -10. **EMA smoothing** — α=0.04 at 60fps ≈ 500ms settling time for the cents needle -11. **Hint + stability ring** — advances `stabilityProgress`; confirms the string after `stableMs` hold time - -**No-signal path — pitch fails step 6 (useTuner):** - -12. **Overtone fold-and-route** — if the pitch is a harmonic (N×2–6) of the locked fundamental, attempt to fold it down to the fundamental; if the folded pitch lands in the ±15% window, route it through the full stability pipeline (steps 7–11); otherwise just refresh the latch timer -13. **Coarse hint (wide window)** — active only before the string has ever entered the ±15% fine-tuning window; if pitch is within ±1 octave of the fundamental and passes the clarity gate, show a directional too-high/too-low hint without advancing stability. Suppressed if the pitch is a harmonic of an already-tuned string (sympathetic resonance) -14. **Latch-and-Fade** — display held for 500ms after the last valid frame; needle position preserved across the gap - -## Running Locally - -**Prerequisites:** Node.js 20.19+ or 22.12+ +### Capture (useAudioCapture) -```bash -# Install dependencies -npm install +1. **Raw microphone** — echo cancellation, noise suppression and automatic gain are turned off. They are tuned for speech: they fade out a sustained note as if it were noise and keep changing the level. +2. **Low-pass filter** — a Butterworth biquad at 3× the string (280–2000 Hz): the fundamental and the first harmonics pass, the upper harmonics that mislead period detection are damped. +3. **Noise gate** — a frame is analysed only above −60 dBFS and 6 dB above the room's own noise level, which the gate keeps learning from the unpitched frames. -# Start the dev server -npm run dev -``` +### Detector (per frame) -Open [http://localhost:5173/String-Tuner/](http://localhost:5173/String-Tuner/) in your browser. The app will ask for microphone permission on first use. +4. **Decimation** — the filtered input is averaged down to a rate that still gives ≥ 64 samples per period, so a 31 Hz bass B costs as little as a violin E. +5. **Coarse pitch: McLeod Pitch Method** — the normalised square difference function of a 60 ms (at least 4 periods) span, the same span at every lag, up to a fifth below the string, in double precision through one FFT pair; the first key maximum ≥ 0.9 of the highest, refined by parabolic interpolation. +6. **Fine pitch: phase measurement** — as a strobe tuner does: the phase advance of the fundamental and of the 2nd harmonic between two Hann-windowed frames of 12 periods. A period method reads a blend of everything that rings (with the previous string still sounding, the new one several cents flat); in these narrow bands a string a third or a fourth away hardly counts. Only this fine pitch is ever shown: in the first moments of a note, before both frames hold it, there is no reading at all. +7. **Fundamental share** — how much of the sound is at the pitch and its octave. B3 and E4 ringing together repeat at the period of E2 with no E2 in them: that phantom has none. +8. **Harmonic spread** — the cents between the pitch the fundamental gives and the one the 2nd harmonic gives: within a cent for a string read cleanly, wide when noise in the bands pulls each its own way. -```bash -# Run the tests (including a virtual instrument played through the whole audio chain) -npm test +### Engine (per frame) -# Check the code -npm run lint +9. **Clarity gate** — 0.85 to start a reading, 0.75 to carry one on through the tail of the note (violin: 0.80 / 0.70). Another string ringing as loud lowers the clarity of the whole sound without spoiling the narrow-band pitch, so a frame down to 0.55 still counts when its harmonics agree within a cent. +10. **Range** — up to a fifth either way reads as this string (direction to turn); a pitch an octave up (±300¢) is its 2nd harmonic. Anything else, a tuned string still ringing, or a phantom is ignored. +11. **Median of 5 readings** — a single wrong frame never shows. +12. **Needle smoothing** — 60 ms when steady, 25 ms while the pitch moves (a peg being turned); slower for readings whose harmonics disagree (noise). +13. **In tune** — within ±3 cents after at least 3 readings, staying in until ±4 cents (no flicker at the edge); confirmed after a hold time in tune. +14. **Latch-and-fade** — the reading stays 500 ms after the sound stops; the needle stays where it was. -# Build for production -npm run build - -# Preview the production build -npm run preview -``` - -## Android - -**Prerequisites:** Android Studio with the Android SDK installed. - -```bash -# Build the web assets and sync to the Android project -npm run build -npx cap sync android - -# Open in Android Studio -npx cap open android -``` - -The app declares the `RECORD_AUDIO` permission in `AndroidManifest.xml`, which Android requires for microphone access. The permission prompt will appear on first launch. - -**Min SDK:** Android 7.0 (API 24) — **Target SDK:** API 36 - -## License - -This project is licensed under the **MIT License** — you are free to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, provided that the original copyright notice and this permission notice are included in all copies or substantial portions of the software. +### Per-instrument configuration -See the [LICENSE](LICENSE) file for the full text. +| Instrument | Hold time in tune | Clarity to start | Clarity to carry on | +|---|---|---|---| +| Guitar | 1000ms | 0.85 | 0.75 | +| Bass | 1200ms | 0.85 | 0.75 | +| Ukulele | 700ms | 0.85 | 0.75 | +| Violin | 600ms | 0.80 | 0.70 | + +### Measured on the virtual instrument (`npm test`) + +| | | +|---|---| +| Error on a held note | < 0.03 cent on guitar; < 0.2 cent in a noisy room (< 0.5 on ukulele) | +| First reading after a pluck | 80–220 ms on guitar, already within half a cent; 0.15–0.36 s on bass | +| Needle behind a peg being turned | 130–220 ms | +| Previous string ringing 6 dB down | < 1 cent of error (a period method alone: 15–22 cents) | diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index a633983..0de1f2c 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -33,5 +33,7 @@ + + diff --git a/package-lock.json b/package-lock.json index 756c695..89ca735 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,6 @@ "@capacitor/android": "^8.3.1", "@capacitor/core": "^8.3.1", "@fontsource-variable/nunito": "^5.3.0", - "pitchy": "^4.1.0", "vue": "^3.5.32", "vue-i18n": "^11.4.0" }, @@ -4412,12 +4411,6 @@ } } }, - "node_modules/fft.js": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/fft.js/-/fft.js-4.0.4.tgz", - "integrity": "sha512-f9c00hphOgeQTlDyavwTtu6RiK8AIFjD6+jvXkNkpeQ7rirK3uFWVpalkoS4LAwbdX7mfZ8aoBfFVQX1Re/8aw==", - "license": "MIT" - }, "node_modules/file-entry-cache": { "version": "11.1.5", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", @@ -6587,15 +6580,6 @@ "node": ">=0.10.0" } }, - "node_modules/pitchy": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/pitchy/-/pitchy-4.1.0.tgz", - "integrity": "sha512-E8nQ8svBroGSMcc3qu2KvLHIuRYAIfrSkqDKWhjgj3WizseqWQXjQ+Q5t4g1CU73R5Euk+DAinyNFDK+KZw7zA==", - "license": "MIT", - "dependencies": { - "fft.js": "^4.0.4" - } - }, "node_modules/plist": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz", diff --git a/package.json b/package.json index b9f4372..68aefb3 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,6 @@ "@capacitor/android": "^8.3.1", "@capacitor/core": "^8.3.1", "@fontsource-variable/nunito": "^5.3.0", - "pitchy": "^4.1.0", "vue": "^3.5.32", "vue-i18n": "^11.4.0" }, diff --git a/src/composables/useAudioCapture.ts b/src/composables/useAudioCapture.ts index 19cbcdc..df4405a 100644 --- a/src/composables/useAudioCapture.ts +++ b/src/composables/useAudioCapture.ts @@ -2,68 +2,73 @@ * useAudioCapture — owns the Web Audio API lifecycle. * * Responsibilities: - * - Request microphone permission via getUserMedia - * - Create/destroy AudioContext, BiquadFilterNode, AnalyserNode(s), MediaStreamSource + * - Request the microphone, with the browser's voice processing (echo cancellation, noise + * suppression, automatic gain) turned off: tuned for speech, it fades out a sustained note + * as if it were noise and keeps changing the level + * - Create/destroy AudioContext, BiquadFilterNode, AnalyserNode, MediaStreamSource * - Run the requestAnimationFrame tick loop at ~60fps - * - Compute RMS, gate noise and attack transients, run pitchy, deliver AudioFrames + * - Gate silence against the room's own noise level, run the pitch detector, deliver one + * AudioFrame per tick * - * Knows nothing about tunings, cents, strings, or UI state. - * The FFT window size and LPF cutoff are controlled externally so callers - * can tune those parameters per-instrument without coupling to this module. + * Knows nothing about tunings, cents or UI state: only the frequency it should listen around + * (`setTarget`), which aims the low-pass filter and plans the analysis (src/tuner/detector.ts). */ -import { PitchDetector } from 'pitchy' import { readonly, ref } from 'vue' +import { + createPitchDetector, + lowPassCutoff, + MAX_RAW_LENGTH, + planAnalysis, + type AnalysisPlan, +} from '../tuner/detector' /** - * Default primary FFT window size when none is specified by the caller. - * 2048 samples at 44100Hz ≈ 46ms window — sufficient for guitar/ukulele/violin. - * Bass mode passes 8192 via startCapture options to get ~185ms (≈15 cycles of Low E). - */ -const FFT_SIZE = 2048 -/** - * Minimum ms between engine ticks — sets the Engine Layer frame rate. - * 16ms ≈ 60fps; fast enough to catch the onset of a pluck and react quickly - * to string changes. The Presentation Layer in useTuner throttles Vue writes - * independently to ~30fps so the UI stays fluid without Vue batching pressure. + * Minimum ms between ticks. 16ms ≈ 60fps: fast enough to follow a peg being turned. The + * engine throttles what the UI sees to ~30fps on its own. */ const TICK_INTERVAL_MS = 16 +/** Before the first string is known: the low E of a guitar */ +const DEFAULT_TARGET_HZ = 82.41 /** - * Default low-pass filter cutoff (Hz) — applied at session start. - * Attenuates harmonics before the signal reaches pitchy so it more reliably - * detects the fundamental. Kept at 300Hz as a conservative default; updated - * in real time via setLowPassCutoff() each time the locked string changes - * (cutoff = 3 × fundamental, clamped 280–2000Hz). - */ -const LPF_CUTOFF_HZ = 300 -/** - * Secondary FFT window size used as a clarity fallback for guitar/ukulele/violin. - * 8192 samples at 44100Hz ≈ 185ms window — gives pitchy ~15 cycles of Low E (82Hz) - * versus ~4 cycles for the standard 2048-sample window, dramatically improving - * fundamental-vs-harmonic discrimination on the thickest strings. - * Not created at all when the primary window is already this size (bass mode). - */ -const FFT_SIZE_LARGE = 8192 -/** Clarity threshold below which the engine tries the large-window detector */ -const LARGE_DETECTOR_CLARITY_THRESHOLD = 0.92 -/** - * RMS noise gate threshold (0–1 normalised amplitude). - * Frames quieter than this are silence/noise and skipped entirely. - * Typical guitar pluck RMS is 0.02–0.2; room noise < 0.008. + * Below this RMS (−60 dBFS) a frame is silence whatever the room. Low enough for an unplugged + * electric guitar or a far phone microphone; the detector's clarity tells noise apart above it. */ -const RMS_GATE = 0.01 +const MIN_GATE_RMS = 0.001 +/** A frame must be this much louder than the room's noise level (×2 = +6 dB) to be analysed */ +const GATE_OVER_NOISE = 2 +/** Frames less clear than this are noise, and teach the gate the room's level */ +const NOISE_CLARITY = 0.5 /** - * If RMS jumps by this factor in one tick, it's a pick/pluck attack transient. - * We suppress pitch readings for TRANSIENT_GATE_MS after detecting such a spike. + * The noise level follows quieter frames quickly and louder unpitched ones slowly (dB per + * tick): a pause between notes lowers it at once, a fan or traffic raises it over seconds. */ -const RMS_ONSET_RATIO = 3.0 -const TRANSIENT_GATE_MS = 80 +const NOISE_FALL_RATE = 0.25 +const NOISE_RISE_DB_PER_TICK = 0.05 export interface AudioFrame { + /** + * Pitch found, Hz, to a fraction of a cent; 0 when there is none: silence, noise, or the + * first moments of a note, before it can be measured precisely + */ pitch: number + /** 0–1: how clearly pitched the sound is (the NSDF peak); 0 with no pitch */ clarity: number + /** 0–1: share of the sound's energy at the pitch and its octave (see PitchEstimate) */ + fundamentalShare: number + /** Cents between the pitch on the fundamental and on the 2nd harmonic (see PitchEstimate) */ + harmonicSpread: number + /** RMS level of the filtered input analysed */ rms: number } +const SILENT = { pitch: 0, clarity: 0, fundamentalShare: 0, harmonicSpread: Infinity } + +function nextPowerOfTwo(n: number): number { + let p = 32 + while (p < n) p <<= 1 + return p +} + export function useAudioCapture() { const isCapturing = ref(false) const captureError = ref(null) @@ -73,119 +78,116 @@ export function useAudioCapture() { let lpf: BiquadFilterNode | null = null let stream: MediaStream | null = null let animationId: number | null = null - let detector: PitchDetector> | null = null - let inputBuffer: Float32Array | null = null + let input: Float32Array | null = null + let plan: AnalysisPlan | null = null + let targetHz = DEFAULT_TARGET_HZ let onTick: ((frame: AudioFrame) => void) | null = null let lastTickTime = 0 - /** RMS from the previous tick — used for onset (attack) detection */ - let prevRms = 0 - /** Timestamp (ms) when the last onset was detected — gate reads until expired */ - let transientGateUntil = 0 - /** Secondary large-window analyser/detector for bass-string clarity fallback */ - let analyserLarge: AnalyserNode | null = null - let detectorLarge: PitchDetector> | null = null - let inputBufferLarge: Float32Array | null = null + /** The room's noise level, dBFS */ + let noiseDb = 20 * Math.log10(MIN_GATE_RMS) + const detector = createPitchDetector() + + /** Size the analysis, the analyser and the filter for `targetHz` */ + function applyTarget() { + if (!audioCtx || !analyser || !lpf) return + plan = planAnalysis(targetHz, audioCtx.sampleRate) + const size = Math.min(MAX_RAW_LENGTH, nextPowerOfTwo(plan.rawLength)) + if (analyser.fftSize !== size || input?.length !== size) { + analyser.fftSize = size + input = new Float32Array(size) as Float32Array + } + lpf.frequency.value = lowPassCutoff(targetHz) + } + + function trackNoise(rms: number) { + const db = 20 * Math.log10(Math.max(rms, 1e-9)) + noiseDb += + db < noiseDb + ? (db - noiseDb) * NOISE_FALL_RATE + : Math.min(db - noiseDb, NOISE_RISE_DB_PER_TICK) + } function tick(timestamp: number) { - if (!analyser || !detector || !inputBuffer || !audioCtx) return + if (!analyser || !input || !plan) return animationId = requestAnimationFrame(tick) if (timestamp - lastTickTime < TICK_INTERVAL_MS) return lastTickTime = timestamp - analyser.getFloatTimeDomainData(inputBuffer) + analyser.getFloatTimeDomainData(input) - // ── RMS noise gate ────────────────────────────────────────────────────── - // Compute root-mean-square amplitude. Skip pitch detection entirely when - // the frame is too quiet — this filters out room noise and the silent - // gaps between plucks without waiting for pitchy to return low clarity. + // RMS of the samples about to be analysed (the newest ones) let sumSq = 0 - for (let i = 0; i < inputBuffer.length; i++) sumSq += inputBuffer[i] * inputBuffer[i] - const rms = Math.sqrt(sumSq / inputBuffer.length) - if (rms < RMS_GATE) { - prevRms = 0 // reset onset baseline during silence + const from = Math.max(0, input.length - plan.rawLength) + for (let i = from; i < input.length; i++) sumSq += input[i] * input[i] + const rms = Math.sqrt(sumSq / (input.length - from)) + + // Silence: below the absolute floor, or not clearly above the room's noise + const gate = Math.max(MIN_GATE_RMS, GATE_OVER_NOISE * 10 ** (noiseDb / 20)) + if (rms < gate) { + trackNoise(rms) + onTick?.({ ...SILENT, rms }) return } - // ── Attack transient gate ─────────────────────────────────────────────── - // A sudden RMS spike (pick/pluck attack) floods the buffer with wide-band - // noise. Detect it as a >3× jump in RMS from the previous frame, then - // suppress pitch readings for TRANSIENT_GATE_MS to let the string settle. - const now = performance.now() - if (prevRms > 0 && rms / prevRms > RMS_ONSET_RATIO) { - transientGateUntil = now + TRANSIENT_GATE_MS - } - prevRms = rms - if (now < transientGateUntil) return // inside attack window — skip pitchy - - let [pitch, clarity] = detector.findPitch(inputBuffer, audioCtx.sampleRate) - // ── Dual-detector: large-window fallback for bass strings ─────────────── - // The standard 2048-sample window covers ~46ms, giving pitchy only ~4 - // cycles of Low E (82Hz). The 8192-sample fallback covers ~185ms (~15 - // cycles), dramatically improving fundamental-vs-harmonic discrimination. - // Only runs when primary clarity is low, so there's no CPU cost in the - // normal (clearly-detected) case. - if ( - clarity < LARGE_DETECTOR_CLARITY_THRESHOLD && - analyserLarge && - detectorLarge && - inputBufferLarge - ) { - analyserLarge.getFloatTimeDomainData(inputBufferLarge) - const [pitchL, clarityL] = detectorLarge.findPitch(inputBufferLarge, audioCtx.sampleRate) - if (clarityL > clarity) { - pitch = pitchL - clarity = clarityL - } - } - onTick?.({ pitch, clarity, rms }) + const estimate = detector.analyze(input, plan) + if (!estimate || estimate.clarity < NOISE_CLARITY) trackNoise(rms) + onTick?.( + estimate + ? { + pitch: estimate.refined ? estimate.frequency : 0, + clarity: estimate.clarity, + fundamentalShare: estimate.fundamentalShare, + harmonicSpread: estimate.harmonicSpread, + rms, + } + : { ...SILENT, rms }, + ) } async function startCapture( tickCallback: (frame: AudioFrame) => void, - options?: { primaryFftSize?: number }, + options?: { targetHz?: number }, ): Promise { captureError.value = null onTick = tickCallback + if (options?.targetHz) targetHz = options.targetHz try { + // Created before the permission prompt, while the tap that started it still counts + // as a user gesture: Safari keeps an AudioContext created later suspended. + const ctx = new AudioContext({ latencyHint: 'interactive' }) + audioCtx = ctx stream = await navigator.mediaDevices.getUserMedia({ - audio: true, + audio: { + echoCancellation: false, + noiseSuppression: false, + autoGainControl: false, + channelCount: 1, + }, video: false, }) - audioCtx = new AudioContext() + if (ctx.state === 'suspended') void ctx.resume().catch(() => {}) // ── Low-pass filter ─────────────────────────────────────────────────── - // Inserted between the mic source and the analyser. Cuts harmonics above - // LPF_CUTOFF_HZ so pitchy only sees the fundamental frequency range of - // the instrument. Critical for low-E (82Hz) where mobile mics roll off - // the fundamental and pitchy would otherwise latch onto the 2nd harmonic. - lpf = audioCtx.createBiquadFilter() + // Between the microphone and the analyser, at 3× the string (setTarget): the + // fundamental and first harmonics pass, the upper harmonics that mislead period + // detection are damped, and the detector can decimate without aliasing. + lpf = ctx.createBiquadFilter() lpf.type = 'lowpass' - lpf.frequency.value = LPF_CUTOFF_HZ - lpf.Q.value = 0.7 // Butterworth-ish — flat passband, no resonance peak - - const primaryFftSize = options?.primaryFftSize ?? FFT_SIZE - analyser = audioCtx.createAnalyser() - analyser.fftSize = primaryFftSize - detector = PitchDetector.forFloat32Array(analyser.fftSize) - inputBuffer = new Float32Array(detector.inputLength) as Float32Array - const source = audioCtx.createMediaStreamSource(stream) + lpf.Q.value = Math.SQRT1_2 // Butterworth — flat passband, no resonance peak + + analyser = ctx.createAnalyser() + analyser.smoothingTimeConstant = 0 + const source = ctx.createMediaStreamSource(stream) source.connect(lpf) lpf.connect(analyser) - // ── Large-window analyser (bass-string fallback) ────────────────────── - // Skip when primary is already 8192+ (bass mode); the 4× larger window - // is only needed when the primary window is too short for the fundamental. - if (primaryFftSize < FFT_SIZE_LARGE) { - analyserLarge = audioCtx.createAnalyser() - analyserLarge.fftSize = FFT_SIZE_LARGE - detectorLarge = PitchDetector.forFloat32Array(analyserLarge.fftSize) - inputBufferLarge = new Float32Array(detectorLarge.inputLength) as Float32Array - lpf.connect(analyserLarge) - } + applyTarget() + isCapturing.value = true lastTickTime = 0 - prevRms = 0 - transientGateUntil = 0 + noiseDb = 20 * Math.log10(MIN_GATE_RMS) animationId = requestAnimationFrame(tick) } catch (e) { + stopCapture() + onTick = null captureError.value = e instanceof Error ? e.message : 'Microphone access denied' } } @@ -196,23 +198,22 @@ export function useAudioCapture() { animationId = null } stream?.getTracks().forEach((t) => t.stop()) - audioCtx?.close() + void audioCtx?.close().catch(() => {}) audioCtx = null analyser = null - analyserLarge = null lpf = null stream = null - detector = null - detectorLarge = null - inputBuffer = null - inputBufferLarge = null + input = null + plan = null onTick = null isCapturing.value = false } - /** Update the low-pass filter cutoff in real time — call when the locked string changes. */ - function setLowPassCutoff(hz: number) { - if (lpf) lpf.frequency.value = hz + /** Listen around `hz`: call when the string being tuned changes. */ + function setTarget(hz: number) { + if (!(hz > 0)) return + targetHz = hz + applyTarget() } return { @@ -220,6 +221,6 @@ export function useAudioCapture() { captureError: readonly(captureError), startCapture, stopCapture, - setLowPassCutoff, + setTarget, } } diff --git a/src/composables/useTuner.test.ts b/src/composables/useTuner.test.ts index c5f44d8..a3356bf 100644 --- a/src/composables/useTuner.test.ts +++ b/src/composables/useTuner.test.ts @@ -1,7 +1,8 @@ /** * The tuning engine, fed frame by frame. useAudioCapture is replaced by a stand-in that hands - * useTuner's tick callback to the test, so each frame (pitch, clarity, rms) is chosen here and - * time only moves when the test moves it (fake timers, performance.now included). + * useTuner's tick callback to the test, so each frame (pitch, clarity, share, spread, rms) is + * chosen here and time only moves when the test moves it (fake timers, performance.now + * included). */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { nextTick, ref } from 'vue' @@ -11,8 +12,8 @@ import { useTuner } from './useTuner' const capture = vi.hoisted(() => ({ onTick: null as ((frame: AudioFrame) => void) | null, - options: undefined as { primaryFftSize?: number } | undefined, - cutoffs: [] as number[], + options: undefined as { targetHz?: number } | undefined, + targets: [] as number[], starts: 0, stops: 0, })) @@ -25,10 +26,7 @@ vi.mock('./useAudioCapture', async () => { return { isCapturing: readonly(isCapturing), captureError: readonly(ref(null)), - async startCapture( - onTick: (frame: AudioFrame) => void, - options?: { primaryFftSize?: number }, - ) { + async startCapture(onTick: (frame: AudioFrame) => void, options?: { targetHz?: number }) { capture.onTick = onTick capture.options = options capture.starts++ @@ -39,8 +37,8 @@ vi.mock('./useAudioCapture', async () => { capture.stops++ isCapturing.value = false }, - setLowPassCutoff(hz: number) { - capture.cutoffs.push(hz) + setTarget(hz: number) { + capture.targets.push(hz) }, } }, @@ -51,13 +49,30 @@ const TICK_MS = 16 const preset = (id: string) => PRESET_TUNINGS.find((t) => t.id === id) as TuningPreset const GUITAR = preset('std6') const BASS = PRESET_TUNINGS.find((t) => t.category === 'bass') as TuningPreset - -/** A clean, loud frame at `hz` shifted by `cents`. */ -const note = (hz: number, cents = 0, clarity = 0.98, rms = 0.1): AudioFrame => ({ +const E2 = GUITAR.tuning[0].frequency +const A2 = GUITAR.tuning[1].frequency + +/** A clean, loud frame at `hz` shifted by `cents` (its fundamental and octave agree). */ +const note = ( + hz: number, + cents = 0, + clarity = 0.98, + { share = 0.6, spread = 0.2 }: { share?: number; spread?: number } = {}, +): AudioFrame => ({ pitch: hz * 2 ** (cents / 1200), clarity, - rms, + fundamentalShare: share, + harmonicSpread: spread, + rms: 0.1, }) +/** What the capture sends in silence */ +const SILENCE: AudioFrame = { + pitch: 0, + clarity: 0, + fundamentalShare: 0, + harmonicSpread: Infinity, + rms: 0.0005, +} /** Feed the same frame every 16 ms for `ms`, letting Vue's watchers run between ticks. */ async function feed(frame: AudioFrame, ms: number) { @@ -78,7 +93,7 @@ async function setup(tuning: TuningPreset = GUITAR) { beforeEach(() => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance', 'Date'] }) vi.spyOn(console, 'log').mockImplementation(() => {}) - Object.assign(capture, { onTick: null, options: undefined, cutoffs: [], starts: 0, stops: 0 }) + Object.assign(capture, { onTick: null, options: undefined, targets: [], starts: 0, stops: 0 }) }) afterEach(() => { @@ -87,27 +102,25 @@ afterEach(() => { }) describe('start', () => { - it('asks for a 2048-sample window for guitar and 8192 for bass', async () => { - await setup(GUITAR) - expect(capture.options?.primaryFftSize).toBe(2048) - await setup(BASS) - expect(capture.options?.primaryFftSize).toBe(8192) - }) - it('starts on the first (lowest) string, nothing tuned yet', async () => { const { tuner } = await setup() expect(tuner.isListening.value).toBe(true) expect(tuner.lockedStringIndex.value).toBe(0) expect(tuner.tunedStrings.value.size).toBe(0) }) + + it('aims the analysis at that string', async () => { + await setup(GUITAR) + expect(capture.options?.targetHz).toBeCloseTo(E2, 6) + await setup(BASS) + expect(capture.options?.targetHz).toBeCloseTo(BASS.tuning[0].frequency, 6) + }) }) describe('a string held in tune', () => { - const E2 = GUITAR.tuning[0].frequency - - it('fills the stability ring, then confirms the string after 1.1 s (guitar)', async () => { + it('fills the stability ring, then confirms the string after 1 s (guitar)', async () => { const { tuner } = await setup() - await feed(note(E2), 1000) + await feed(note(E2), 900) expect(tuner.tunedStrings.value.has(0)).toBe(false) expect(tuner.stabilityProgress.value).toBeGreaterThan(0.8) expect(tuner.hint.value).toBe('in-range') @@ -117,23 +130,47 @@ describe('a string held in tune', () => { expect(tuner.lockedStringIndex.value).toBe(1) }) - it('counts up to ±8 cents as in tune', async () => { + it('counts within ±3 cents as in tune', async () => { + const sharp = await setup() + await feed(note(E2, 2.5), 1200) + expect(sharp.tuner.tunedStrings.value.has(0)).toBe(true) + + const flat = await setup() + await feed(note(E2, -2.5), 1200) + expect(flat.tuner.tunedStrings.value.has(0)).toBe(true) + }) + + it('5 cents off is not in tune', async () => { const { tuner } = await setup() - await feed(note(E2, 7), 1200) - expect(tuner.tunedStrings.value.has(0)).toBe(true) + await feed(note(E2, 5), 3000) + expect(tuner.hint.value).toBe('too-high') + expect(tuner.tunedStrings.value.size).toBe(0) + }) + + it('does not flicker at the edge: once in tune, up to ±4 cents still is', async () => { + const { tuner } = await setup() + await feed(note(E2), 300) + await feed(note(E2, 3.6), 300) + expect(tuner.hint.value).toBe('in-range') + + await feed(note(E2, 4.6), 300) + expect(tuner.hint.value).toBe('too-high') }) - it('shows the frequency it hears, in Hz with one decimal', async () => { + it('shows the frequency it hears, in Hz with one decimal, and the cents on the needle', async () => { const { tuner } = await setup() await feed(note(E2), 100) expect(tuner.frequency.value).toBe(82.4) expect(tuner.cents.value).toBe(0) + + const fine = await setup() + await feed(note(E2, 1.37), 300) + expect(fine.tuner.needleCents.value).toBeCloseTo(1.37, 2) + expect(fine.tuner.cents.value).toBe(1) }) }) describe('a string out of tune', () => { - const E2 = GUITAR.tuning[0].frequency - it('30 cents sharp: says "tune down" and never confirms', async () => { const { tuner } = await setup() await feed(note(E2, 30), 3000) @@ -149,7 +186,7 @@ describe('a string out of tune', () => { expect(tuner.tunedStrings.value.size).toBe(0) }) - it('far off (a few semitones): coarse direction hint, no stability progress', async () => { + it('far off, up to a fifth: the direction to turn, no stability progress', async () => { const { tuner } = await setup() await feed(note(E2, -400), 500) expect(tuner.hint.value).toBe('too-low') @@ -157,10 +194,17 @@ describe('a string out of tune', () => { expect(tuner.stabilityProgress.value).toBe(0) const fresh = await setup() - await feed(note(E2, 500), 500) + await feed(note(E2, 650), 500) expect(fresh.tuner.hint.value).toBe('too-high') }) + it('beyond a fifth below is another note: nothing is shown', async () => { + const { tuner } = await setup() + await feed(note(E2, -900), 500) + expect(tuner.hint.value).toBeNull() + expect(tuner.frequency.value).toBeNull() + }) + it('confirms once the string is brought back into tune', async () => { const { tuner } = await setup() await feed(note(E2, 30), 1500) @@ -168,11 +212,19 @@ describe('a string out of tune', () => { await feed(note(E2), 2500) expect(tuner.tunedStrings.value.has(0)).toBe(true) }) + + it('a string that hovered just off needs its full second in tune once it comes in', async () => { + const { tuner } = await setup() + await feed(note(E2, 6), 2000) + await feed(note(E2), 600) + expect(tuner.tunedStrings.value.has(0)).toBe(false) + + await feed(note(E2), 600) + expect(tuner.tunedStrings.value.has(0)).toBe(true) + }) }) describe('noisy readings', () => { - const E2 = GUITAR.tuning[0].frequency - it('ignores frames below the clarity gate', async () => { const { tuner } = await setup() await feed(note(E2, 0, 0.5), 500) @@ -180,15 +232,56 @@ describe('noisy readings', () => { expect(tuner.hint.value).toBeNull() }) - it('accepts a less clear frame while the string is fading (quiet), not while it is loud', async () => { - // Guitar: clarity 0.92 normally, 0.80 when rms < 0.04 - const loud = await setup() - await feed(note(E2, 0, 0.85, 0.1), 300) - expect(loud.tuner.frequency.value).toBeNull() + it('a less clear, noisy frame carries on a reading, but cannot start one', async () => { + // Guitar: clarity 0.85 to start, 0.75 to carry on; noise sets the harmonics apart + const noisy = { spread: 6 } + const fresh = await setup() + await feed(note(E2, 0, 0.8, noisy), 300) + expect(fresh.tuner.frequency.value).toBeNull() + + const going = await setup() + await feed(note(E2, 0, 0.98), 200) + await feed(note(E2, 0, 0.8, noisy), 600) + expect(going.tuner.frequency.value).toBe(82.4) + }) + + it('another string ringing as loud: a less clear sound still reads if its harmonics agree', async () => { + const { tuner } = await setup() + await feed(note(E2, 1.5, 0.6, { spread: 0.4 }), 500) + expect(tuner.hint.value).toBe('in-range') + expect(tuner.needleCents.value).toBeCloseTo(1.5, 1) + + await feed(note(E2, 1.5, 0.6, { spread: 0.4 }), 800) + expect(tuner.tunedStrings.value.has(0)).toBe(true) + }) + + it('below 0.55 clarity nothing reads, however well the harmonics agree', async () => { + const { tuner } = await setup() + await feed(note(E2, 0, 0.5, { spread: 0.1 }), 1000) + expect(tuner.frequency.value).toBeNull() + }) + + it('the needle trusts readings less, and moves more slowly, when their harmonics disagree', async () => { + const agree = await setup() + await feed(note(E2), 300) + await feed(note(E2, 2.5, 0.98, { spread: 0.2 }), 200) + const agreeing = agree.tuner.needleCents.value as number + + const disagree = await setup() + await feed(note(E2), 300) + await feed(note(E2, 2.5, 0.98, { spread: 6 }), 200) + const disagreeing = disagree.tuner.needleCents.value as number + + expect(agreeing).toBeGreaterThan(2) + expect(disagreeing).toBeLessThan(1) + }) - const quiet = await setup() - await feed(note(E2, 0, 0.85, 0.02), 300) - expect(quiet.tuner.frequency.value).toBe(82.4) + it('one wild frame does not move the needle', async () => { + const { tuner } = await setup() + await feed(note(E2, 1), 400) + capture.onTick?.(note(E2, 45)) + await feed(note(E2, 1), 100) + expect(tuner.needleCents.value).toBeCloseTo(1, 1) }) it('reads the 2nd harmonic of the low string as its fundamental (octave fold)', async () => { @@ -201,13 +294,20 @@ describe('noisy readings', () => { expect(tuner.tunedStrings.value.has(0)).toBe(true) }) + it('ignores a pitch with nothing at its fundamental (other strings adding up to it)', async () => { + const { tuner } = await setup() + await feed(note(E2, -2, 0.99, { share: 0.001 }), 1500) + expect(tuner.hint.value).toBeNull() + expect(tuner.tunedStrings.value.size).toBe(0) + }) + it('keeps the reading through a 500 ms unclear tail, then clears it but leaves the needle', async () => { const { tuner } = await setup() await feed(note(E2, 5), 300) - await feed(note(E2, 0, 0.3, 0.02), 300) + await feed(note(E2, 0, 0.3), 300) expect(tuner.frequency.value).not.toBeNull() - await feed(note(E2, 0, 0.3, 0.02), 400) + await feed(note(E2, 0, 0.3), 400) expect(tuner.frequency.value).toBeNull() expect(tuner.hint.value).toBeNull() expect(tuner.stabilityProgress.value).toBe(0) @@ -215,28 +315,26 @@ describe('noisy readings', () => { }) }) -describe('silence (no frames at all: the capture gates them out)', () => { - const E2 = GUITAR.tuning[0].frequency - - it('blanks the reading 500 ms after the last frame, keeping the needle', async () => { +describe('silence', () => { + it('blanks the reading 500 ms after the last note, keeping the needle', async () => { const { tuner } = await setup() - await feed(note(E2, 4), 600) + await feed(note(E2, 2), 600) expect(tuner.hint.value).toBe('in-range') - await vi.advanceTimersByTimeAsync(450) + await feed(SILENCE, 450) expect(tuner.hint.value).toBe('in-range') - await vi.advanceTimersByTimeAsync(100) + await feed(SILENCE, 100) expect(tuner.hint.value).toBeNull() expect(tuner.frequency.value).toBeNull() expect(tuner.stabilityProgress.value).toBe(0) expect(tuner.needleCents.value).not.toBeNull() }) - it('shows the reading again with the next frame', async () => { + it('shows the reading again with the next note', async () => { const { tuner } = await setup() await feed(note(E2), 300) - await vi.advanceTimersByTimeAsync(800) + await feed(SILENCE, 800) expect(tuner.frequency.value).toBeNull() await feed(note(E2), 100) @@ -244,6 +342,26 @@ describe('silence (no frames at all: the capture gates them out)', () => { }) }) +describe('other strings', () => { + it('ignores a tuned string still ringing', async () => { + const { tuner } = await setup() + await feed(note(E2), 1200) + expect(tuner.lockedStringIndex.value).toBe(1) + + await feed(note(E2), 1000) // E2 rings on while the tuner waits for A2 + expect(tuner.hint.value).toBeNull() + expect(tuner.frequency.value).toBeNull() + }) + + it("shows an untuned string's note as it is, without confirming it", async () => { + const { tuner } = await setup() + await feed(note(A2), 1500) // A2 while waiting for E2: the player is on the wrong string + expect(tuner.hint.value).toBe('too-high') + expect(tuner.tunedStrings.value.size).toBe(0) + expect(tuner.lockedStringIndex.value).toBe(0) + }) +}) + describe('moving through the strings', () => { it('after the last string: "all in tune", then stops by itself 2 s later', async () => { const { tuner } = await setup() @@ -259,7 +377,7 @@ describe('moving through the strings', () => { it('choosing a tuned string un-marks it so it is checked again', async () => { const { tuner } = await setup() - await feed(note(GUITAR.tuning[0].frequency), 1200) + await feed(note(E2), 1200) expect(tuner.tunedStrings.value.has(0)).toBe(true) tuner.selectString(0) @@ -268,39 +386,54 @@ describe('moving through the strings', () => { expect(tuner.stabilityProgress.value).toBe(0) }) - it("ignores the next string's note while still on the current one", async () => { + it('choosing a string once all are in tune keeps listening for it', async () => { const { tuner } = await setup() - await feed(note(GUITAR.tuning[1].frequency), 1500) // A2 while waiting for E2 - expect(tuner.tunedStrings.value.size).toBe(0) - expect(tuner.lockedStringIndex.value).toBe(0) + for (const s of GUITAR.tuning) await feed(note(s.frequency), 1200) + tuner.selectString(2) + expect(tuner.allTuned.value).toBe(false) + + await vi.advanceTimersByTimeAsync(2500) + expect(tuner.isListening.value).toBe(true) + expect(tuner.lockedStringIndex.value).toBe(2) }) - it('sets the low-pass filter to 3× the string, between 280 and 2000 Hz', async () => { + it('aims the analysis at each string in turn', async () => { await setup() - expect(capture.cutoffs.at(-1)).toBe(280) // E2 × 3 = 247 → 280 - await feed(note(GUITAR.tuning[0].frequency), 1200) - expect(capture.cutoffs.at(-1)).toBeCloseTo(GUITAR.tuning[1].frequency * 3, 6) // A2 → 330 + for (const s of GUITAR.tuning) await feed(note(s.frequency), 1200) + expect(capture.targets.slice(-6)).toEqual(GUITAR.tuning.map((s) => s.frequency)) }) }) -describe('changing tuning while listening', () => { - it('restarts capture with the new window size when the instrument changes', async () => { +describe('changing tuning', () => { + it('while listening: carries on, from the first string of the new tuning', async () => { const { active, tuner } = await setup(GUITAR) + await feed(note(E2), 1200) active.value = BASS - await vi.advanceTimersByTimeAsync(0) await nextTick() - expect(capture.stops).toBe(1) - expect(capture.starts).toBe(2) - expect(capture.options?.primaryFftSize).toBe(8192) + expect(capture.stops).toBe(0) expect(tuner.isListening.value).toBe(true) + expect(tuner.lockedStringIndex.value).toBe(0) + expect(tuner.tunedStrings.value.size).toBe(0) + expect(capture.targets.at(-1)).toBeCloseTo(BASS.tuning[0].frequency, 6) }) - it('starts again from the first string within the same instrument', async () => { + it('with the new instrument settings (bass: 1.2 s in tune)', async () => { const { active, tuner } = await setup(GUITAR) - await feed(note(GUITAR.tuning[0].frequency), 1200) - active.value = preset('dropd') + active.value = BASS + await nextTick() + const E1 = BASS.tuning[0].frequency + await feed(note(E1), 1100) + expect(tuner.tunedStrings.value.size).toBe(0) + await feed(note(E1), 200) + expect(tuner.tunedStrings.value.has(0)).toBe(true) + }) + + it('while stopped: shows the first string of the new tuning', async () => { + const { active, tuner } = await setup(preset('bass_std5')) + await feed(note(preset('bass_std5').tuning[0].frequency), 1300) + tuner.stop() + active.value = GUITAR await nextTick() - expect(capture.stops).toBe(0) expect(tuner.lockedStringIndex.value).toBe(0) expect(tuner.tunedStrings.value.size).toBe(0) }) diff --git a/src/composables/useTuner.ts b/src/composables/useTuner.ts index 85d25fe..58f869a 100644 --- a/src/composables/useTuner.ts +++ b/src/composables/useTuner.ts @@ -2,13 +2,12 @@ * useTuner — connects the tuning engine (src/tuner/engine.ts) to the microphone and to Vue. * * Audio capture is delegated to useAudioCapture, the analysis to the engine; this composable - * feeds one to the other, mirrors the engine's state into read-only refs for the UI, steers - * the low-pass filter to the string being tuned, and stops on its own once every string is - * in tune. + * feeds one to the other, mirrors the engine's state into read-only refs for the UI, aims the + * capture at the string being tuned, and stops on its own once every string is in tune. */ import { readonly, ref, watch, type Ref } from 'vue' import type { TuningPreset } from '../data/tunings' -import { createTunerEngine, SIGNAL_HOLD_MS, type TunerHint } from '../tuner/engine' +import { createTunerEngine, type TunerHint } from '../tuner/engine' import { createSessionLog } from '../tuner/sessionLog' import { useAudioCapture, type AudioFrame } from './useAudioCapture' @@ -18,8 +17,7 @@ export type { TunerHint } const ALL_TUNED_RESET_MS = 2000 export function useTuner(activeTuning: Ref) { - const { isCapturing, captureError, startCapture, stopCapture, setLowPassCutoff } = - useAudioCapture() + const { isCapturing, captureError, startCapture, stopCapture, setTarget } = useAudioCapture() const log = createSessionLog() let allTunedResetTimer: ReturnType | null = null @@ -45,6 +43,9 @@ export function useTuner(activeTuning: Ref) { const needleCents = ref(null) const signalClarity = ref(0) + /** The frequency the capture is listening around */ + let aimedAt = 0 + function sync() { const d = engine.display frequency.value = d.frequency @@ -56,59 +57,35 @@ export function useTuner(activeTuning: Ref) { lockedStringIndex.value = engine.lockedStringIndex tunedStrings.value = engine.tunedStrings as Set allTuned.value = engine.allTuned + // Aim the capture at the string being tuned as soon as it changes, frame-exact + if (engine.targetFrequency !== aimedAt) { + aimedAt = engine.targetFrequency + setTarget(aimedAt) + } } - watch(activeTuning, async (newVal, oldVal) => { - engine.setTuning(newVal) - if (isCapturing.value) { - // Category change requires restarting audio to apply a new FFT size - if (newVal.category !== oldVal?.category) { - stop() - await start() - } else { - resetState() - } - } + // Another tuning: its first string, its instrument's settings; listening carries on + watch(activeTuning, (next) => { + engine.setTuning(next) + resetState() }) - watch(lockedStringIndex, updateLpf) - - function updateLpf() { - const tuningArr = activeTuning.value.tuning - const lockedFreq = tuningArr[Math.min(lockedStringIndex.value, tuningArr.length - 1)].frequency - setLowPassCutoff(Math.min(2000, Math.max(280, lockedFreq * 3))) - } - - function resetState() { - engine.reset() + function clearAllTunedTimer() { if (allTunedResetTimer !== null) { clearTimeout(allTunedResetTimer) allTunedResetTimer = null } - clearSilenceTimer() - sync() } - // Below its noise gate useAudioCapture sends no frames at all, so the engine's own - // latch-and-fade never runs in true silence. Blank the reading after the same hold time - // once frames stop coming; the engine's analysis state is left as it is. - let silenceTimer: ReturnType | null = null - function clearSilenceTimer() { - if (silenceTimer !== null) { - clearTimeout(silenceTimer) - silenceTimer = null - } + function resetState() { + engine.reset() + clearAllTunedTimer() + sync() } function processTick(frame: AudioFrame) { engine.process(frame, performance.now()) sync() - clearSilenceTimer() - silenceTimer = setTimeout(() => { - silenceTimer = null - engine.clearDisplay() - sync() - }, SIGNAL_HOLD_MS) } /** @@ -116,6 +93,7 @@ export function useTuner(activeTuning: Ref) { * If the string was already marked tuned, un-mark it so it gets re-checked. */ function selectString(index: number) { + clearAllTunedTimer() engine.selectString(index) sync() } @@ -128,12 +106,10 @@ export function useTuner(activeTuning: Ref) { `=== TUNER SESSION START === instrument=${activeTuning.value.category} tuning=${activeTuning.value.name}`, ) log.add( - `cfg: fftSize=${cfg.primaryFftSize} stableMs=${cfg.stableMs} clarityThreshold=${cfg.clarityThreshold} decayThreshold=${cfg.decayClarityThreshold}`, + `cfg: stableMs=${cfg.stableMs} clarityThreshold=${cfg.clarityThreshold} sustainClarity=${cfg.sustainClarity}`, ) resetState() - await startCapture(processTick, { primaryFftSize: cfg.primaryFftSize }) - // The LPF watcher fires before the audio graph exists; set it now for string 0. - updateLpf() + await startCapture(processTick, { targetHz: engine.targetFrequency }) } function stop() { @@ -141,7 +117,7 @@ export function useTuner(activeTuning: Ref) { const c = engine.counters log.add(`=== TUNER SESSION STOP ===`) log.add( - `ticks: total=${c.total} hasSignal=${c.hasSignal} coarseHint=${c.coarseHint} overtone=${c.overtone} silence=${c.silence} continuityRejected=${c.continuityRejected}`, + `ticks: total=${c.total} hasSignal=${c.hasSignal} octaveFolded=${c.octaveFolded} silence=${c.silence} unclear=${c.unclear} offRange=${c.offRange} ringing=${c.ringing} phantom=${c.phantom}`, ) log.add( `tunedStrings=${[...engine.tunedStrings].join(',') || 'none'} allTuned=${engine.allTuned}`, diff --git a/src/composables/virtualGuitar.test.ts b/src/composables/virtualGuitar.test.ts index 3375ced..1bc2b9b 100644 --- a/src/composables/virtualGuitar.test.ts +++ b/src/composables/virtualGuitar.test.ts @@ -1,13 +1,18 @@ /** * The whole audio chain with a virtual instrument instead of a microphone: the real - * useAudioCapture (RMS gate, attack gate, two pitchy windows), the real useTuner, and a fake + * useAudioCapture (noise gate, pitch detector), the real useTuner and tuning engine, and a fake * Web Audio API that plays synthetic plucked strings (see src/test/virtualInstrument.ts). * Nothing of the app is mocked except the browser. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ref } from 'vue' import { PRESET_TUNINGS, type TuningPreset } from '../data/tunings' -import { installFakeAudio, type PluckOptions, VirtualInstrument } from '../test/virtualInstrument' +import { + installFakeAudio, + type InstrumentOptions, + type PluckOptions, + VirtualInstrument, +} from '../test/virtualInstrument' import { useTuner } from './useTuner' const preset = (id: string) => PRESET_TUNINGS.find((t) => t.id === id) as TuningPreset @@ -19,6 +24,8 @@ interface Player { sound?: (stringIndex: number) => PluckOptions /** Give up after this many plucks in all */ maxPlucks?: number + /** The room and the sound card */ + instrument?: InstrumentOptions } /** @@ -26,13 +33,15 @@ interface Player { * the tuner moves on, then waits 0.4 s and plucks the next one. Earlier strings keep ringing. */ async function play(tuning: TuningPreset, player: Player = {}) { - const instrument = new VirtualInstrument() + const instrument = new VirtualInstrument(player.instrument) installFakeAudio(instrument) const tuner = useTuner(ref(tuning)) await tuner.start() const hints = new Map>() const plucksPerString = new Map() + /** The needle (cents) on each string the moment before it was confirmed */ + const confirmedAt = new Map() let plucks = 0 const started = performance.now() @@ -44,27 +53,56 @@ async function play(tuning: TuningPreset, player: Player = {}) { instrument.pluck(tuning.tuning[index].frequency * 2 ** (cents / 1200), player.sound?.(index)) plucks++ - for (let t = 0; t < 2500; t += 100) { - await vi.advanceTimersByTimeAsync(100) + let needle: number | null = null + for (let t = 0; t < 2500; t += 20) { + await vi.advanceTimersByTimeAsync(20) if (tuner.hint.value) { if (!hints.has(index)) hints.set(index, new Set()) hints.get(index)?.add(tuner.hint.value) } if (tuner.lockedStringIndex.value !== index || tuner.allTuned.value) { + if (needle !== null) confirmedAt.set(index, needle) await vi.advanceTimersByTimeAsync(400) break } + needle = tuner.needleCents.value } } return { tuner, + instrument, plucks, plucksPerString, hints, + confirmedAt, seconds: (performance.now() - started) / 1000, } } +/** Listen to string `index` alone: the needle every 20 ms for `ms` after plucking it `cents` off */ +async function listen( + tuning: TuningPreset, + index: number, + cents: number, + ms: number, + sound: PluckOptions = {}, + room: InstrumentOptions = {}, +) { + const instrument = new VirtualInstrument(room) + installFakeAudio(instrument) + const tuner = useTuner(ref(tuning)) + await tuner.start() + tuner.selectString(index) + instrument.pluck(tuning.tuning[index].frequency * 2 ** (cents / 1200), sound) + const needle: (number | null)[] = [] + for (let t = 0; t < ms; t += 20) { + await vi.advanceTimersByTimeAsync(20) + needle.push(tuner.needleCents.value) + } + vi.unstubAllGlobals() + return { tuner, needle } +} + beforeEach(() => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance', 'Date'] }) vi.spyOn(console, 'log').mockImplementation(() => {}) @@ -160,3 +198,121 @@ describe('a phone microphone that barely hears the low fundamentals', () => { expect(session.tuner.allTuned.value).toBe(true) }, 30_000) }) + +describe('accuracy', () => { + const guitar = preset('std6') + + it('reads every guitar string to a tenth of a cent, within a quarter second', async () => { + for (let index = 0; index < 6; index++) { + for (const cents of [-23.7, -6.2, 1.3, 14.9]) { + const { needle } = await listen(guitar, index, cents, 1000) + const label = `${guitar.tuning[index].note}${guitar.tuning[index].octave} ${cents}¢` + // Within a cent 250 ms after the pluck, within a tenth of a cent from 450 ms on + expect(Math.abs((needle[12] ?? NaN) - cents), label).toBeLessThan(1) + for (const v of needle.slice(22)) + expect(Math.abs((v ?? NaN) - cents), label).toBeLessThan(0.1) + } + } + }, 60_000) + + it('a string 5 cents sharp is never passed, even with the string below it still ringing', async () => { + // A period method alone reads the blend of the two strings several cents flat, and would + // pass a string that is really 5 cents sharp + const session = await play(guitar, { + cents: (string) => (string === 0 ? 0 : 5), + maxPlucks: 3, + }) + expect(session.tuner.tunedStrings.value.has(0)).toBe(true) + expect(session.tuner.tunedStrings.value.has(1)).toBe(false) + expect(session.hints.get(1)).toContain('too-high') + expect(session.hints.get(1)).not.toContain('in-range') + }, 30_000) + + it('every string is confirmed within a cent of its true pitch, earlier strings ringing on', async () => { + const session = await play(guitar, { cents: () => 1.5 }) + expect(session.tuner.allTuned.value).toBe(true) + for (let i = 0; i < 6; i++) { + expect(Math.abs((session.confirmedAt.get(i) ?? NaN) - 1.5), `string ${i + 1}`).toBeLessThan(1) + } + }, 30_000) + + it('reads a bass through a phone microphone that barely hears its fundamentals', async () => { + const bass = preset('bass_std5') + const phone = [0.056, 0.125, 0.167, 0.18, 0.17, 0.12, 0.1, 0.08] + for (let index = 0; index < bass.tuning.length; index++) { + const { needle } = await listen(bass, index, -12.4, 1600, { decay: 2, harmonics: phone }) + for (const v of needle.slice(40)) expect(Math.abs((v ?? NaN) + 12.4)).toBeLessThan(0.2) + } + }, 60_000) +}) + +describe('rooms, instruments and sound cards', () => { + it('an unplugged electric guitar, 30 dB quieter', async () => { + const session = await play(preset('std6'), { sound: () => ({ amplitude: 0.01 }) }) + expect(session.tuner.allTuned.value).toBe(true) + }, 30_000) + + it('a noisy room, the noise louder than the decaying strings', async () => { + const session = await play(preset('std6'), { + instrument: { noise: 0.06 }, + cents: () => 1, + }) + expect(session.tuner.allTuned.value).toBe(true) + for (let i = 0; i < 6; i++) { + expect(Math.abs((session.confirmedAt.get(i) ?? NaN) - 1), `string ${i + 1}`).toBeLessThan(1) + } + }, 30_000) + + it('a sound card at 44.1 kHz', async () => { + const session = await play(preset('std6'), { instrument: { sampleRate: 44100 } }) + expect(session.tuner.allTuned.value).toBe(true) + }, 30_000) + + it('stiff strings (inharmonic partials)', async () => { + const session = await play(preset('std6'), { + sound: () => ({ inharmonicity: 1e-4 }), + cents: () => 0, + }) + expect(session.tuner.allTuned.value).toBe(true) + for (let i = 0; i < 6; i++) { + expect(Math.abs(session.confirmedAt.get(i) ?? NaN), `string ${i + 1}`).toBeLessThan(1) + } + }, 30_000) +}) + +describe('other strings ringing', () => { + it('B and high E ringing make up no low E: choosing it, nothing is read until it is plucked', async () => { + const guitar = preset('std6') + const instrument = new VirtualInstrument() + installFakeAudio(instrument) + const tuner = useTuner(ref(guitar)) + await tuner.start() + instrument.pluck(guitar.tuning[4].frequency) + instrument.pluck(guitar.tuning[5].frequency) + tuner.selectString(0) + const hints = new Set() + for (let t = 0; t < 3000; t += 20) { + await vi.advanceTimersByTimeAsync(20) + hints.add(tuner.hint.value) + } + expect([...hints]).toEqual([null]) + expect(tuner.tunedStrings.value.size).toBe(0) + }, 30_000) +}) + +describe('turning a peg', () => { + it('the needle follows a string glided from 40 cents flat to 40 sharp, at most 250 ms behind', async () => { + const guitar = preset('std6') + for (let index = 0; index < 6; index++) { + const { needle } = await listen(guitar, index, -40, 2000, { centsPerSecond: 40, decay: 4 }) + needle.forEach((v, i) => { + const t = (i + 1) * 0.02 + if (t < 0.6) return + const lag = -40 + 40 * t - (v ?? NaN) + // At 40 ¢/s, 250 ms behind is 10 cents behind + expect(lag, `string ${index + 1} at ${t.toFixed(2)} s`).toBeLessThan(10) + expect(lag, `string ${index + 1} at ${t.toFixed(2)} s`).toBeGreaterThan(0) + }) + } + }, 60_000) +}) diff --git a/src/test/virtualInstrument.ts b/src/test/virtualInstrument.ts index ccfb2bf..6c89297 100644 --- a/src/test/virtualInstrument.ts +++ b/src/test/virtualInstrument.ts @@ -1,10 +1,12 @@ /** * A virtual instrument and a fake Web Audio API, for testing the real audio chain - * (useAudioCapture → pitchy → useTuner) without a microphone or an instrument. + * (useAudioCapture → the pitch detector → the tuning engine, through useTuner) without a + * microphone or an instrument. * - * The instrument is a sum of decaying harmonics per pluck, plus a little noise below the - * capture's RMS gate. The fake low-pass filter shapes each harmonic with the magnitude of a - * 2nd-order Butterworth at the cutoff useTuner sets, as the real BiquadFilterNode would. + * The instrument is a sum of decaying partials per pluck (optionally inharmonic, as stiff + * strings are, and optionally gliding, as while a peg is turned), plus the room's noise. The + * fake low-pass filter shapes each partial with the magnitude of a 2nd-order Butterworth at the + * cutoff the capture sets, as the real BiquadFilterNode would. * Time is the fake performance.now() of Vitest's timers. */ import { vi } from 'vitest' @@ -18,6 +20,17 @@ export interface PluckOptions { amplitude?: number /** Seconds until the note is stopped (a bow lifted, a string muted). Default: rings out */ duration?: number + /** Inharmonicity B of a stiff string: partial k sits at k·f·√(1 + B·k²). Default 0 */ + inharmonicity?: number + /** The pitch moves this many cents per second (a peg being turned). Default 0 */ + centsPerSecond?: number +} + +export interface InstrumentOptions { + /** Peak amplitude of the room's white noise, unfiltered. Default 0.004 (−59 dBFS RMS) */ + noise?: number + /** Default 48000 */ + sampleRate?: number } interface Sound { @@ -28,6 +41,8 @@ interface Sound { decay: number amplitude: number end: number + inharmonicity: number + centsPerSecond: number } /** Seconds a stopped note takes to fall to 1/e */ @@ -48,12 +63,31 @@ function prng(seed: number) { export const PLUCKED = [1, 1 / 2, 1 / 3, 1 / 4, 1 / 5, 1 / 6] export class VirtualInstrument { - readonly sampleRate = 48000 - /** Set by the fake BiquadFilterNode: useTuner moves it with the string being tuned */ + readonly sampleRate: number + readonly noise: number + /** Set by the fake BiquadFilterNode: the capture moves it with the string being tuned */ lowPassHz = 300 private sounds: Sound[] = [] private random = prng(42) + constructor(options: InstrumentOptions = {}) { + this.sampleRate = options.sampleRate ?? 48000 + this.noise = options.noise ?? 0.004 + } + + /** The frequency of `s` at time `t` (seconds) */ + private frequencyAt(s: Sound, t: number) { + return s.freq * 2 ** ((s.centsPerSecond * Math.max(0, t - s.start)) / 1200) + } + + /** Phase (radians, without the partial's own offset) of a partial at `ratio`× the note */ + private phaseAt(s: Sound, ratio: number, t: number) { + const elapsed = Math.max(0, t - s.start) + if (s.centsPerSecond === 0) return 2 * Math.PI * s.freq * ratio * elapsed + const k = (s.centsPerSecond * Math.LN2) / 1200 + return (2 * Math.PI * s.freq * ratio * (Math.exp(k * elapsed) - 1)) / k + } + pluck(freq: number, options: PluckOptions = {}) { const harmonics = options.harmonics ?? PLUCKED const start = performance.now() / 1000 @@ -65,9 +99,17 @@ export class VirtualInstrument { decay: options.decay ?? 1.2, amplitude: options.amplitude ?? 0.3, end: start + (options.duration ?? Infinity), + inharmonicity: options.inharmonicity ?? 0, + centsPerSecond: options.centsPerSecond ?? 0, }) } + /** Stop every note at once (all strings muted) */ + mute() { + const now = performance.now() / 1000 + for (const s of this.sounds) s.end = Math.min(s.end, now) + } + /** Envelope of `s` at time `t` (seconds): decay while it rings, a quick release once stopped. */ private envelope(s: Sound, t: number) { if (t < s.start) return 0 @@ -83,33 +125,35 @@ export class VirtualInstrument { const first = now - (n - 1) / sr this.sounds = this.sounds.filter((s) => this.envelope(s, now) > 1e-4 || now < s.start) - for (let i = 0; i < n; i++) buffer[i] = (this.random() - 0.5) * 0.004 + for (let i = 0; i < n; i++) buffer[i] = (this.random() - 0.5) * this.noise + const BLOCK = 64 for (const s of this.sounds) { const from = Math.max(0, Math.ceil((s.start - first) * sr)) if (from >= n) continue - const t0 = first + from / sr - // The envelope changes slowly: compute it every 64 samples and hold it in between - const env = new Float32Array(Math.ceil((n - from) / 64) + 1) - for (let j = 0; j < env.length; j++) env[j] = this.envelope(s, t0 + (j * 64) / sr) - for (let k = 0; k < s.gains.length; k++) { - const f = s.freq * (k + 1) - // Magnitude of a 2nd-order Butterworth low-pass at the filter's cutoff - const gain = s.gains[k] / Math.sqrt(1 + (f / this.lowPassHz) ** 4) - if (gain < 1e-4) continue - // Rotate a phasor instead of calling Math.sin for every sample - const w = (2 * Math.PI * f) / sr - const cw = Math.cos(w) - const sw = Math.sin(w) - const phase = 2 * Math.PI * f * (t0 - s.start) + s.phases[k] - let re = Math.cos(phase) - let im = Math.sin(phase) - for (let i = from; i < n; i++) { - buffer[i] += env[(i - from) >> 6] * gain * im - const r = re * cw - im * sw - im = re * sw + im * cw - re = r + const ratio = (k + 1) * Math.sqrt(1 + s.inharmonicity * (k + 1) ** 2) + // Envelope, filter gain and frequency change slowly: compute them every 64 samples + // and rotate a phasor in between instead of calling Math.sin for every sample + for (let b = from; b < n; b += BLOCK) { + const t = first + b / sr + const f = this.frequencyAt(s, t) * ratio + // Magnitude of a 2nd-order Butterworth low-pass at the filter's cutoff + const gain = (s.gains[k] * this.envelope(s, t)) / Math.sqrt(1 + (f / this.lowPassHz) ** 4) + if (gain < 1e-6) continue + const w = (2 * Math.PI * f) / sr + const cw = Math.cos(w) + const sw = Math.sin(w) + const phase = this.phaseAt(s, ratio, t) + s.phases[k] + let re = Math.cos(phase) + let im = Math.sin(phase) + const end = Math.min(n, b + BLOCK) + for (let i = b; i < end; i++) { + buffer[i] += gain * im + const r = re * cw - im * sw + im = re * sw + im * cw + re = r + } } } } diff --git a/src/tuner/detector.test.ts b/src/tuner/detector.test.ts new file mode 100644 index 0000000..03ff3ff --- /dev/null +++ b/src/tuner/detector.test.ts @@ -0,0 +1,305 @@ +/** + * The pitch detector on synthetic strings: plucked-string spectra through the capture's + * low-pass filter, with noise, inharmonicity, other strings ringing, and a microphone that + * barely hears the fundamental. + */ +import { describe, expect, it } from 'vitest' +import { PRESET_TUNINGS } from '../data/tunings' +import { + createPitchDetector, + lowPassCutoff, + MAX_RAW_LENGTH, + planAnalysis, + READ_RANGE_CENTS, + type AnalysisPlan, +} from './detector' +import { centsOff } from './pitch' + +/** Small deterministic PRNG (mulberry32) */ +function prng(seed: number) { + let a = seed >>> 0 + return () => { + a = (a + 0x6d2b79f5) >>> 0 + let t = a + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} +const random = prng(2024) +/** Roughly normal, unit variance */ +const gaussian = () => { + let sum = 0 + for (let i = 0; i < 6; i++) sum += random() + return (sum - 3) * Math.SQRT2 +} + +const PLUCKED = [1, 0.5, 0.33, 0.25, 0.2, 0.17] + +interface StringSound { + freq: number + /** Partial amplitudes, fundamental first */ + partials?: number[] + /** Inharmonicity B: partial k at k·f·√(1 + B·k²) */ + inharmonicity?: number + amplitude?: number +} + +/** `input` through a 2nd-order Butterworth low-pass at `cutoff`, as a BiquadFilterNode does */ +function lowPass(input: Float32Array, cutoff: number, sampleRate: number) { + const w0 = (2 * Math.PI * cutoff) / sampleRate + const alpha = Math.sin(w0) / Math.SQRT2 + const cos = Math.cos(w0) + const [b0, b1, b2] = [(1 - cos) / 2, 1 - cos, (1 - cos) / 2] + const [a0, a1, a2] = [1 + alpha, -2 * cos, 1 - alpha] + const out = new Float32Array(input.length) + let [x1, x2, y1, y2] = [0, 0, 0, 0] + for (let i = 0; i < input.length; i++) { + const y = (b0 * input[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2) / a0 + ;[x2, x1, y2, y1] = [x1, input[i], y1, y] + out[i] = y + } + return out +} + +/** + * `length` samples of strings at `sampleRate`, each partial shaped by the low-pass filter the + * capture puts in front of the detector for `targetHz`, plus white noise of RMS `noise` (or, + * with `filteredNoise`, of RMS `noise` after that filter, as a microphone's noise is). + */ +function render( + sounds: StringSound[], + targetHz: number, + { length = MAX_RAW_LENGTH, sampleRate = 48000, noise = 0, filteredNoise = false } = {}, +) { + const out = new Float32Array(length) + const cutoff = lowPassCutoff(targetHz) + for (const s of sounds) { + const partials = s.partials ?? PLUCKED + for (let k = 0; k < partials.length; k++) { + const n = k + 1 + const f = s.freq * n * Math.sqrt(1 + (s.inharmonicity ?? 0) * n * n) + const gain = ((s.amplitude ?? 0.1) * partials[k]) / Math.sqrt(1 + (f / cutoff) ** 4) + const phase = random() * 2 * Math.PI + const w = (2 * Math.PI * f) / sampleRate + for (let i = 0; i < length; i++) out[i] += gain * Math.sin(w * i + phase) + } + } + if (filteredNoise) { + const white = Float32Array.from({ length: length + 4096 }, gaussian) + const shaped = lowPass(white, cutoff, sampleRate).subarray(4096) + let power = 0 + for (const v of shaped) power += v * v + const gain = noise / Math.sqrt(power / length) + for (let i = 0; i < length; i++) out[i] += gain * shaped[i] + } else { + for (let i = 0; i < length; i++) out[i] += noise * gaussian() + } + return out +} + +const detector = createPitchDetector() +const analyze = (samples: Float32Array, plan: AnalysisPlan) => detector.analyze(samples, plan) + +/** Every distinct string frequency of every preset tuning */ +const STRINGS = [...new Set(PRESET_TUNINGS.flatMap((t) => t.tuning.map((s) => s.frequency)))].sort( + (a, b) => a - b, +) + +describe('planAnalysis', () => { + it.each([44100, 48000, 96000])('fits every string at %i Hz', (sampleRate) => { + for (const f of STRINGS) { + const plan = planAnalysis(f, sampleRate) + const period = plan.rate / f + // Enough samples per period for an exact interpolation, and no aliasing of the + // low-passed input + expect(period).toBeGreaterThanOrEqual(64) + expect(plan.rate).toBeGreaterThanOrEqual(8 * lowPassCutoff(f)) + // A fifth below the string is still within the longest lag + expect(plan.maxLag).toBeGreaterThan(period * 2 ** (READ_RANGE_CENTS / 1200)) + expect(plan.windowLength).toBeLessThanOrEqual(plan.analysedLength) + expect(plan.frameLength + plan.frameHop).toBeLessThanOrEqual(plan.analysedLength) + expect(plan.rawLength).toBeLessThanOrEqual(MAX_RAW_LENGTH) + } + }) + + it('listens to about 60–80 ms on a guitar string, longer on a low bass string', () => { + const ms = (f: number) => { + const plan = planAnalysis(f, 48000) + return (plan.windowLength / plan.rate) * 1000 + } + expect(ms(82.41)).toBeGreaterThan(60) + expect(ms(82.41)).toBeLessThan(90) + expect(ms(329.63)).toBeLessThan(70) + expect(ms(30.87)).toBeLessThan(200) + }) +}) + +describe('accuracy', () => { + it('reads every preset string within 0.05 cent on a clean string, detuned up to ±50 cents', () => { + for (const target of STRINGS) { + const plan = planAnalysis(target, 48000) + for (const detune of [-50, -17.3, 0, 8.6, 50]) { + const freq = target * 2 ** (detune / 1200) + const estimate = analyze(render([{ freq }], target, { noise: 0.0005 }), plan) + expect(estimate, `${target} Hz ${detune}¢`).not.toBeNull() + expect( + Math.abs(centsOff(estimate!.frequency, freq)), + `${target} Hz ${detune}¢`, + ).toBeLessThan(0.05) + expect(estimate!.clarity).toBeGreaterThan(0.95) + } + } + }) + + it('stays within 1.5 cents at 10 dB of signal-to-noise', () => { + for (const target of [41.2, 82.41, 110, 146.83, 196, 246.94, 329.63, 440, 659.25]) { + const plan = planAnalysis(target, 48000) + const errors: number[] = [] + for (let trial = 0; trial < 12; trial++) { + const freq = target * 2 ** ((random() - 0.5) / 12) + const estimate = analyze(render([{ freq }], target, { noise: 0.02 }), plan) + errors.push(Math.abs(centsOff(estimate!.frequency, freq))) + } + expect(Math.max(...errors), `${target} Hz`).toBeLessThan(1.5) + } + }) + + it('reads a stiff (inharmonic) string at its fundamental, within half a cent', () => { + // B = 1e-4: about a wound low E string; its 2nd partial is 0.35 cents sharp + for (const target of [82.41, 110, 146.83]) { + const estimate = analyze( + render([{ freq: target, inharmonicity: 1e-4 }], target), + planAnalysis(target, 48000), + ) + expect(Math.abs(centsOff(estimate!.frequency, target))).toBeLessThan(0.5) + } + }) + + it('reads the same at 44.1 kHz', () => { + const target = 82.41 + const estimate = analyze( + render([{ freq: target }], target, { sampleRate: 44100, noise: 0.002 }), + planAnalysis(target, 44100), + ) + expect(Math.abs(centsOff(estimate!.frequency, target))).toBeLessThan(0.1) + }) +}) + +describe('a microphone that barely hears the fundamental', () => { + it('still finds the string (or exactly its octave), with a good share of energy there', () => { + // A phone microphone on a bass: the fundamental 25 dB down, the 2nd harmonic 12 dB down + const phone = [0.056, 0.125, 0.167, 0.18, 0.17, 0.12, 0.1, 0.08] + for (const target of [30.87, 41.2, 55, 82.41]) { + const estimate = analyze( + render([{ freq: target, partials: phone }], target, { noise: 0.001 }), + planAnalysis(target, 48000), + ) + const cents = centsOff(estimate!.frequency, target) + const fromString = Math.min(Math.abs(cents), Math.abs(cents - 1200)) + expect(fromString, `${target} Hz`).toBeLessThan(0.2) + expect(estimate!.fundamentalShare, `${target} Hz`).toBeGreaterThan(0.1) + } + }) +}) + +describe('other strings ringing', () => { + // Each string of a standard guitar with the one below it (a fourth or a major third) still + // ringing 6 dB down. A period method alone reads 15–22 cents flat here. + const pairs: [below: number, string: number][] = [ + [82.41, 110], + [110, 146.83], + [146.83, 196], + [196, 246.94], + [246.94, 329.63], + ] + it.each(pairs)( + 'reads the string over the one below it (%f Hz ringing, %f Hz plucked)', + (below, string) => { + const estimate = analyze( + render( + [ + { freq: string, amplitude: 0.1 }, + { freq: below, amplitude: 0.05 }, + ], + string, + ), + planAnalysis(string, 48000), + ) + expect(Math.abs(centsOff(estimate!.frequency, string))).toBeLessThan(1) + }, + ) + + it.each(pairs)( + 'with the one below almost as loud (%f Hz), the sound is unclear but the harmonics of %f Hz agree', + (below, string) => { + const estimate = analyze( + render( + [ + { freq: string, amplitude: 0.1 }, + { freq: below, amplitude: 0.07 }, + ], + string, + ), + planAnalysis(string, 48000), + ) + expect(estimate!.clarity).toBeLessThan(0.75) + expect(estimate!.refined).toBe(true) + expect(estimate!.harmonicSpread).toBeLessThan(1.5) + expect(Math.abs(centsOff(estimate!.frequency, string))).toBeLessThan(1) + }, + ) + + it('noise sets the harmonics apart', () => { + // In-band noise moves the phase of each harmonic its own way: here the microphone's noise, + // through the low-pass filter, half as strong as the string (6 dB of SNR) + const spreads: number[] = [] + for (let trial = 0; trial < 12; trial++) { + const estimate = analyze( + render([{ freq: 196 }], 196, { noise: 0.045, filteredNoise: true }), + planAnalysis(196, 48000), + ) + if (estimate?.refined) spreads.push(estimate.harmonicSpread) + } + spreads.sort((a, b) => a - b) + expect(spreads[spreads.length >> 1]).toBeGreaterThan(1.5) + }) + + it('gives no share to a phantom fundamental made up by two other strings', () => { + // B3 and E4 repeat together every period of E2 (they are its 3rd and 4th harmonics) + const E2 = 82.41 + const estimate = analyze( + render( + [ + { freq: 246.94, partials: [1, 0.5, 0.33] }, + { freq: 329.63, partials: [1, 0.5, 0.33] }, + ], + E2, + ), + planAnalysis(E2, 48000), + ) + // The period method finds an E2, as clear as a real one… + expect(Math.abs(centsOff(estimate!.frequency, E2))).toBeLessThan(10) + expect(estimate!.clarity).toBeGreaterThan(0.95) + // …but there is nothing at E2 or its octave + expect(estimate!.fundamentalShare).toBeLessThan(0.01) + }) +}) + +describe('no pitch', () => { + it('finds nothing in silence', () => { + expect(analyze(new Float32Array(MAX_RAW_LENGTH), planAnalysis(110, 48000))).toBeNull() + }) + + it('is unclear on noise alone', () => { + for (const target of [41.2, 110, 329.63]) { + const estimate = analyze(render([], target, { noise: 0.01 }), planAnalysis(target, 48000)) + expect(estimate?.clarity ?? 0).toBeLessThan(0.6) + } + }) + + it('needs the samples the plan asks for', () => { + const plan = planAnalysis(82.41, 48000) + expect(analyze(new Float32Array(plan.rawLength - 1).fill(0.1), plan)).toBeNull() + }) +}) diff --git a/src/tuner/detector.ts b/src/tuner/detector.ts new file mode 100644 index 0000000..5679a48 --- /dev/null +++ b/src/tuner/detector.ts @@ -0,0 +1,402 @@ +/** + * The pitch detector: the McLeod Pitch Method (normalised square difference function, NSDF), + * aimed at one string at a time. Pure: no Vue, no Web Audio. + * + * Because the tuner always knows which string it is listening for, every analysis is planned + * around that string (`planAnalysis`): + * - Decimation. The input is already low-passed at a few times the string (`lowPassCutoff`), so + * it is averaged down to a rate that still gives ≥ 64 samples per period. Low strings cost + * as little as high ones, and the window can be long enough for a 31 Hz bass B. + * - Window. A reference span of max(60 ms, 4 periods) is correlated with itself at every lag + * up to the period of the lowest note read for the string (a fifth below it). Every lag uses + * the same number of samples, so the NSDF has none of the spurious peaks a shrinking overlap + * gives at long lags, and the newest samples come first so the reading is current. + * - Coarse pitch. The NSDF is computed in double precision through one FFT pair, and the chosen + * peak is refined by parabolic interpolation: a small fraction of a cent on a clean string. + * - Fine pitch. A period method reads a blend of everything that rings: with the previous + * string still sounding 12 dB down, it reads the new one 5–10 cents flat. So the coarse + * pitch is then measured again the way a strobe tuner does, narrow-band: the phase advance + * of the fundamental and of the 2nd harmonic between two Hann-windowed frames of 12 periods + * each. Other strings (a third or a fourth away) fall outside those narrow bands, and the + * reading stays within about a cent of the string's own pitch. + */ +import { FFT } from './fft' + +export interface PitchEstimate { + /** Fundamental frequency, Hz */ + frequency: number + /** 0–1: the NSDF at that period, how periodic (how clearly pitched) the sound is */ + clarity: number + /** + * 0–1: the share of the sound's energy at that frequency and its octave. A real string + * has a good part of its energy there, even through a phone microphone that hardly hears a + * bass fundamental (15% or more). Other strings ringing together can add up to a period with + * nothing at it: B3 and E4 together repeat at the period of E2, with no E2 in them. + */ + fundamentalShare: number + /** + * True when `frequency` is the fine (phase) measurement. False when only the coarse one was + * possible: in the first moments of a note, or when the two disagree. The tuner shows only + * fine pitches: with another string ringing, a coarse one can be several cents off. + */ + refined: boolean + /** + * Cents between the pitch measured on the fundamental and the one measured on the 2nd + * harmonic. A string read cleanly gives the same pitch on both (within a cent, or two on a + * stiff string); noise in the bands pulls each its own way. Unlike clarity, other strings + * ringing, outside these narrow bands, leave it small. + */ + harmonicSpread: number +} + +export interface AnalysisPlan { + /** Rate of the input, Hz */ + sampleRate: number + /** Input samples averaged into one analysed sample */ + decimation: number + /** Rate of the analysed samples, Hz */ + rate: number + /** Samples correlated at every lag */ + spanLength: number + /** Longest lag (period) searched, in analysed samples */ + maxLag: number + /** Samples the coarse (NSDF) analysis uses: the span plus the longest lag, plus one */ + windowLength: number + /** Samples in each of the two frames of the fine (phase) measurement */ + frameLength: number + /** How far apart the two frames are, in samples: the newer one ends with the newest sample */ + frameHop: number + /** Analysed samples in all: the longer of the two analyses */ + analysedLength: number + /** Input samples one analysis needs, the newest ones: analysedLength × decimation */ + rawLength: number +} + +/** How far below the string a pitch is still read as that string, flat (a fifth) */ +export const READ_RANGE_CENTS = 700 +/** Fewest analysed samples per period of the string, for an exact interpolation */ +const MIN_SAMPLES_PER_PERIOD = 64 +/** The analysed rate stays this far above the low-pass cutoff, so nothing folds back */ +const MIN_RATE_OVER_CUTOFF = 8 +const MAX_DECIMATION = 32 +/** The reference span lasts at least this long… */ +const SPAN_SECONDS = 0.06 +/** …and holds at least this many periods of the string */ +const SPAN_PERIODS = 4 +/** + * McLeod's k: the period is the first NSDF key maximum at least this high relative to the + * highest one. Lower picks harmonics more often, higher picks sub-octaves more often. + */ +const KEY_MAXIMUM_RATIO = 0.9 +/** + * Periods of the string in each frame of the fine measurement. A neighbouring string a fourth + * away is then 3 bins off, where the Hann window lets through −37 dB of it; a major third + * (2.5 bins) about −32 dB. + */ +const FRAME_PERIODS = 12 +/** …but a frame never lasts longer than this (the low strings of a bass) */ +const MAX_FRAME_SECONDS = 0.3 +/** The fine pitch replaces the coarse one only within this distance of it */ +const MAX_REFINEMENT_CENTS = 50 +/** + * The older frame must hold at least this share of the newer one's amplitude. Just after a + * pluck it is still partly silence: cut short, it lets in more of any other string ringing, + * and the first readings lean a few cents toward it. + */ +const MIN_FRAME_BALANCE = 0.8 +/** The analyser buffer can hold no more than this */ +export const MAX_RAW_LENGTH = 32768 + +/** + * Low-pass cutoff for a string: three times its frequency, so the fundamental and the first + * harmonics pass and the upper ones, which mislead period detection, are damped. Never below + * 280 Hz, so a bass string the microphone hardly hears still has harmonics to be read from. + */ +export function lowPassCutoff(targetHz: number): number { + return Math.min(2000, Math.max(280, 3 * targetHz)) +} + +/** The analysis for a string at `targetHz`, heard at `sampleRate` */ +export function planAnalysis(targetHz: number, sampleRate: number): AnalysisPlan { + const cutoff = lowPassCutoff(targetHz) + let decimation = 1 + while (decimation < MAX_DECIMATION) { + const rate = sampleRate / (decimation * 2) + if (rate < MIN_SAMPLES_PER_PERIOD * targetHz || rate < MIN_RATE_OVER_CUTOFF * cutoff) break + decimation *= 2 + } + const rate = sampleRate / decimation + const period = rate / targetHz + const maxLag = Math.ceil(period * 2 ** (READ_RANGE_CENTS / 1200)) + 2 + const spanLength = Math.ceil(Math.max(SPAN_SECONDS * rate, SPAN_PERIODS * period)) + const windowLength = spanLength + maxLag + 1 + // Two frames half overlapping; shortened if the analyser could not hold them + const maxAnalysed = Math.floor(MAX_RAW_LENGTH / decimation) + const frameLength = Math.max( + 16, + Math.min( + Math.round(FRAME_PERIODS * period), + Math.round(MAX_FRAME_SECONDS * rate), + Math.floor((maxAnalysed * 2) / 3), + ), + ) + const frameHop = Math.round(frameLength / 2) + const analysedLength = Math.min(maxAnalysed, Math.max(windowLength, frameLength + frameHop)) + return { + sampleRate, + decimation, + rate, + spanLength, + maxLag, + windowLength, + frameLength, + frameHop, + analysedLength, + rawLength: analysedLength * decimation, + } +} + +function nextPowerOfTwo(n: number): number { + let p = 1 + while (p < n) p <<= 1 + return p +} + +export interface PitchDetector { + /** + * The pitch of the newest `plan.rawLength` samples of `input`, or null when there is no + * period to find (silence, or only noise). + */ + analyze(input: Float32Array, plan: AnalysisPlan): PitchEstimate | null +} + +export function createPitchDetector(): PitchDetector { + let fft: FFT | null = null + // Analysed samples (newest first), FFT buffers, running energy, NSDF, Hann window + let x = new Float64Array(0) + let re = new Float64Array(0) + let im = new Float64Array(0) + let pr = new Float64Array(0) + let pi = new Float64Array(0) + let energy = new Float64Array(0) + let nsdf = new Float64Array(0) + let hann = new Float64Array(0) + const peaks: number[] = [] + + function allocate(plan: AnalysisPlan) { + const size = nextPowerOfTwo(plan.windowLength) + if (!fft || fft.size !== size) { + fft = new FFT(size) + re = new Float64Array(size) + im = new Float64Array(size) + pr = new Float64Array(size) + pi = new Float64Array(size) + } + if (x.length !== plan.analysedLength) x = new Float64Array(plan.analysedLength) + if (nsdf.length !== plan.windowLength) { + energy = new Float64Array(plan.windowLength + 1) + nsdf = new Float64Array(plan.windowLength) + } + if (hann.length !== plan.frameLength) { + const m = plan.frameLength + hann = new Float64Array(m) + for (let n = 0; n < m; n++) hann[n] = 0.5 - 0.5 * Math.cos((2 * Math.PI * (n + 0.5)) / m) + } + } + + /** Coarse pitch: the McLeod key maximum of the NSDF, interpolated */ + function coarsePitch(plan: AnalysisPlan): { frequency: number; clarity: number } | null { + const transform = fft as FFT + const size = transform.size + const { spanLength, maxLag, windowLength: length } = plan + + energy[0] = 0 + for (let i = 0; i < length; i++) energy[i + 1] = energy[i] + x[i] * x[i] + const spanEnergy = energy[spanLength] + if (!(spanEnergy > 0)) return null + + // Correlate the span with the whole window: one FFT of span + i·window splits into the + // two spectra, their cross-spectrum conj(S)·W goes back through one inverse FFT. Every + // index stays below the FFT size, so the circular correlation is the linear one. + for (let i = 0; i < size; i++) { + re[i] = i < spanLength ? x[i] : 0 + im[i] = i < length ? x[i] : 0 + } + transform.transform(re, im) + for (let k = 0; k < size; k++) { + const mirror = (size - k) & (size - 1) + const zr = re[k] + const zi = im[k] + const wr = re[mirror] + const wi = im[mirror] + const sr = (zr + wr) / 2 + const si = (zi - wi) / 2 + const xr = (zi + wi) / 2 + const xi = (wr - zr) / 2 + pr[k] = sr * xr + si * xi + pi[k] = sr * xi - si * xr + } + transform.transform(pr, pi, true) + + // NSDF: n(τ) = 2·Σ s[j]·x[j+τ] / Σ (s[j]² + x[j+τ]²), the same span at every lag + for (let lag = 0; lag <= maxLag + 1; lag++) { + const m = spanEnergy + energy[lag + spanLength] - energy[lag] + nsdf[lag] = m > 0 ? (2 * pr[lag]) / size / m : 0 + } + + // Key maxima: the highest point of each positive lobe after the one around lag 0 + let lag = 1 + while (lag <= maxLag && nsdf[lag] > 0) lag++ + peaks.length = 0 + let best = -Infinity + let bestLag = -1 + let highest = -Infinity + for (; lag <= maxLag; lag++) { + const v = nsdf[lag] + if (v > 0) { + if (v > best) { + best = v + bestLag = lag + } + } else if (bestLag >= 0) { + peaks.push(bestLag) + if (best > highest) highest = best + best = -Infinity + bestLag = -1 + } + } + // A lobe still open at the longest lag counts only if it peaked inside the range + if (bestLag >= 0 && bestLag < maxLag) { + peaks.push(bestLag) + if (best > highest) highest = best + } + if (peaks.length === 0) return null + + const chosen = peaks.find((p) => nsdf[p] >= KEY_MAXIMUM_RATIO * highest) as number + + // Parabolic interpolation through the peak and its neighbours + const y0 = nsdf[chosen - 1] + const y1 = nsdf[chosen] + const y2 = nsdf[chosen + 1] + const curvature = y0 - 2 * y1 + y2 + const shift = curvature < 0 ? (0.5 * (y0 - y2)) / curvature : 0 + const clarity = Math.min(1, Math.max(0, y1 - 0.25 * (y0 - y2) * shift)) + return { frequency: plan.rate / (chosen + shift), clarity } + } + + let demodRe = 0 + let demodIm = 0 + /** Σ hann[n]·x[offset+n]·e^(iωn): with x newest first, the phase of the frame at `offset` */ + function demodulate(offset: number, omega: number) { + const c = Math.cos(omega) + const s = Math.sin(omega) + let pRe = 1 + let pIm = 0 + let sumRe = 0 + let sumIm = 0 + for (let n = 0; n < hann.length; n++) { + const v = hann[n] * x[offset + n] + sumRe += v * pRe + sumIm += v * pIm + const t = pRe * c - pIm * s + pIm = pRe * s + pIm * c + pRe = t + } + demodRe = sumRe + demodIm = sumIm + } + + interface Harmonics { + /** Fine pitch near the coarse one, or null (see measureHarmonics) */ + fine: number | null + /** Share of the newer frame's energy at the pitch and its octave */ + share: number + /** Cents between the pitch the fundamental gives and the one the 2nd harmonic gives */ + spread: number + } + + /** + * The fundamental and the 2nd harmonic of `coarse` in the two frames. Fine pitch: the phase + * advance from the older frame to the newer one, averaged by strength; null when the older + * frame is still too quiet (an attack) or nothing rings near `coarse`. + */ + function measureHarmonics(coarse: number, plan: AnalysisPlan): Harmonics { + const hop = plan.frameHop + const frame = hann.length + let frameEnergy = 0 + for (let n = 0; n < frame; n++) frameEnergy += (hann[n] * x[n]) ** 2 + let sum = 0 + let weights = 0 + let power = 0 + let fineValid = true + let fromFundamental = 0 + let fromOctave = 0 + for (let harmonic = 1; harmonic <= 2; harmonic++) { + const omega = (2 * Math.PI * coarse * harmonic) / plan.rate + if (omega > 0.8 * Math.PI) break + demodulate(0, omega) + const newRe = demodRe + const newIm = demodIm + demodulate(hop, omega) + const oldRe = demodRe + const oldIm = demodIm + const newMag = Math.hypot(newRe, newIm) + const oldMag = Math.hypot(oldRe, oldIm) + // A sinusoid of amplitude A gives |X|² = A²M²/16 and Σ(w·x)² = 3A²M/16: share = A² / Σ A² + power += newMag * newMag + if (harmonic === 1 && oldMag < MIN_FRAME_BALANCE * newMag) fineValid = false + // arg(new · conj(old)) is ω·hop, give or take whole turns: take the turn nearest the + // coarse pitch + const advance = Math.atan2(newIm * oldRe - newRe * oldIm, newRe * oldRe + newIm * oldIm) + const turns = Math.round((omega * hop - advance) / (2 * Math.PI)) + const measured = (advance + 2 * Math.PI * turns) / hop + const weight = newMag * oldMag + const pitch = (measured * plan.rate) / (2 * Math.PI * harmonic) + if (harmonic === 1) fromFundamental = pitch + else fromOctave = pitch + sum += pitch * weight + weights += weight + } + const share = frameEnergy > 0 ? Math.min(1, (3 * power) / (frame * frameEnergy)) : 0 + const spread = + fromFundamental > 0 && fromOctave > 0 + ? Math.abs(1200 * Math.log2(fromOctave / fromFundamental)) + : Infinity + if (!fineValid || !(weights > 0)) return { fine: null, share, spread } + const fine = sum / weights + const close = Math.abs(1200 * Math.log2(fine / coarse)) <= MAX_REFINEMENT_CENTS + return { fine: close ? fine : null, share, spread } + } + + function analyze(input: Float32Array, plan: AnalysisPlan): PitchEstimate | null { + if (input.length < plan.rawLength) return null + allocate(plan) + + // Average every `decimation` input samples into one, newest first, and remove the mean + const { decimation, analysedLength } = plan + const end = input.length + let mean = 0 + for (let i = 0; i < analysedLength; i++) { + const stop = end - i * decimation + let sum = 0 + for (let j = stop - decimation; j < stop; j++) sum += input[j] + x[i] = sum / decimation + mean += x[i] + } + mean /= analysedLength + for (let i = 0; i < analysedLength; i++) x[i] -= mean + + const coarse = coarsePitch(plan) + if (!coarse) return null + const { fine, share, spread } = measureHarmonics(coarse.frequency, plan) + return { + frequency: fine ?? coarse.frequency, + clarity: coarse.clarity, + fundamentalShare: share, + refined: fine !== null, + harmonicSpread: spread, + } + } + + return { analyze } +} diff --git a/src/tuner/engine.ts b/src/tuner/engine.ts index a9c919b..29e02d3 100644 --- a/src/tuner/engine.ts +++ b/src/tuner/engine.ts @@ -2,43 +2,89 @@ * The tuning engine — a sequential string tuner, with no Vue and no audio APIs. * * Flow: - * 1. Start on string 0. Stay focused on it until confirmed in tune. - * 2. Once in tune, auto-advance to the next untuned string. - * 3. The user can pick any string to jump to it (resets its progress). - * 4. When all strings are confirmed tuned, report it (onAllTuned). + * 1. Start on string 0. Stay on it until it is confirmed in tune. + * 2. Once in tune, move on to the next string not yet tuned. + * 3. The user can pick any string to jump to it (a tuned one is checked again). + * 4. When every string is confirmed, report it (onAllTuned). * - * No auto-string detection: the engine only ever listens for the locked string. - * It is fed one AudioFrame per tick (~60 fps) with the time of the tick, and keeps the values - * the UI shows in `display`, written at most every DISPLAY_INTERVAL_MS (~30 fps). + * It is fed one AudioFrame per tick (~60 fps) with the time of the tick: the pitch the detector + * found (src/tuner/detector.ts) and how clear it was. Each frame becomes a reading, in cents + * from the string being tuned, or nothing: + * - Clarity: cfg.clarityThreshold to start a reading, cfg.sustainClarity to carry one on + * through the quieter tail of the note. Another string ringing as loud lowers the clarity of + * the whole sound without spoiling the narrow-band measurement: a less clear frame still + * counts when its fundamental and 2nd harmonic give the same pitch. + * - Range: up to a fifth either way reads as this string, so a string far off still gets its + * "tune up / tune down". A pitch an octave up (±300¢) is its 2nd harmonic, read as the + * string. Anything else is another note, and is ignored. + * - Other strings: a pitch far from this string but on one already tuned is that string still + * ringing, and is ignored. So is a pitch with almost nothing at its fundamental and octave: + * strings ringing together whose sum repeats at this string's period (B3 and E4 make an E2). + * Readings pass a 5-reading median (one wrong frame never shows) and a smoother that follows a + * peg being turned at once and holds the needle steady otherwise, trusting readings more the + * better their harmonics agree (noise pulls each its own way). The string is in tune within + * ±ACCEPT_CENTS (and stays so until it drifts past ±RELEASE_CENTS, so the colour does not + * flicker at the edge), and is confirmed after cfg.stableMs in tune. The values the UI shows are + * kept in `display`, written at most every DISPLAY_INTERVAL_MS (~30 fps). */ import type { AudioFrame } from '../composables/useAudioCapture' import type { TuningPreset } from '../data/tunings' +import { READ_RANGE_CENTS } from './detector' import { instrumentConfig, type InstrumentConfig } from './instruments' -import { centsBetween, foldTowardTarget, isHarmonicOf, median } from './pitch' +import { centsOff, frequencyAt, median } from './pitch' import type { SessionLog } from './sessionLog' -/** Cents window considered "in tune" (±8¢ is comfortable for guitar) */ -export const ACCEPT_CENTS = 8 -/** Cents above ACCEPT_CENTS before we consider resetting stability (hysteresis) */ -const STABILITY_RESET_CENTS = 20 -/** How long (ms) pitch must remain outside before stability progress resets */ +/** + * In tune: within ±3 cents (it was ±8, wide enough for two strings to beat audibly against each + * other). The reading itself is good to a fraction of a cent: this is the player's tolerance, + * not the tuner's error. + */ +export const ACCEPT_CENTS = 3 +/** Once in tune, the reading may drift this far before it counts as off again */ +const RELEASE_CENTS = 4 +/** A pitch this close to an octave above the string is its 2nd harmonic */ +const OCTAVE_FOLD_CENTS = 300 +/** Readings within this of the string are always its own, whatever else rings */ +const NEAR_TARGET_CENTS = 100 +/** A pitch this close to a tuned string (or its octave) is that string still ringing */ +const RINGING_MATCH_CENTS = 40 +/** + * Least share of the sound's energy at the pitch and its octave for it to be a string of its + * own. A string through a phone microphone that barely hears it has 15% or more there; a + * phantom pitch made up by other strings, next to nothing. + */ +const MIN_FUNDAMENTAL_SHARE = 0.05 +/** + * A frame below the clarity gate still counts when its fundamental and 2nd harmonic agree + * within this (cents): the sound is a blend, the narrow-band measurement is not + */ +const CONSISTENT_SPREAD_CENTS = 1 +/** …but not below this clarity: the string must still be a good part of what is heard */ +const BLEND_MIN_CLARITY = 0.55 +/** Harmonics this far apart (cents) halve the trust in a reading */ +const HALF_TRUST_SPREAD_CENTS = 2 +/** Readings in the median filter (~80 ms) */ +const MEDIAN_SIZE = 5 +/** + * Readings a note needs before it can count as in tune: its very first one, taken while the + * attack still fills the window, can be a couple of cents off + */ +const MIN_READINGS_IN_TUNE = 3 +/** Needle smoothing time constants (ms) for a steady note, and for a note on the move */ +const SMOOTH_STEADY_MS = 60 +const SMOOTH_MOVING_MS = 25 +/** A median this far (cents) from the needle means the note is moving */ +const MOVING_CENTS = 3 +/** Readings closer together than this (ms) belong to one note: the sustain gate applies */ +const TRACKING_GAP_MS = 150 +/** How long (ms) the last reading stays on screen after the sound becomes unclear or stops */ +const SIGNAL_HOLD_MS = 500 +/** How long (ms) the string may stay off before the stability ring empties */ const STABILITY_RESET_MS = 150 /** Minimum ms between writes of the display values (~30fps) */ const DISPLAY_INTERVAL_MS = 33 -/** EMA smoothing factor — 0.04 at 60fps ≈ 500ms settling time */ -const CENTS_EMA_ALPHA = 0.04 -/** RMS below which the SNR is too poor — apply tighter (decay) clarity gate */ -const LOW_RMS_THRESHOLD = 0.04 -/** Rolling median buffer size (22 × 16ms ≈ 350ms history) */ -const PITCH_BUFFER_SIZE = 22 -/** Max cents jump between EMA and incoming pitch before discarding as noise */ -const PITCH_CONTINUITY_CENTS = 500 -/** Wide hint window (±1 octave) — shows too-high/too-low even when heavily out of tune */ -const HINT_WINDOW_CENTS = 1200 -/** How long (ms) to hold the 'in-range' hint after pitch drifts slightly out */ -const HINT_GRACE_MS = 250 -/** How long (ms) to keep display alive after the last valid signal frame */ -export const SIGNAL_HOLD_MS = 500 +/** Longest tick (ms) counted towards the stability time: longer gaps are a stalled page */ +const MAX_TICK_MS = 100 /** Logging interval (ms) — throttles log lines to ~2/s */ const LOG_INTERVAL_MS = 500 @@ -46,31 +92,44 @@ export type TunerHint = 'too-high' | 'too-low' | 'in-range' | null /** What the UI shows */ export interface TunerDisplay { + /** The string's frequency as heard, Hz, one decimal */ frequency: number | null + /** Cents from the string, rounded */ cents: number | null hint: TunerHint /** 0–1: progress toward confirming current string as in tune */ stabilityProgress: number /** Float cents for needle — holds last position on signal loss */ needleCents: number | null - /** pitchy clarity (0–1) — drives needle opacity in the UI */ + /** Clarity (0–1) of the last reading — drives needle opacity in the UI */ signalClarity: number } /** Ticks by outcome, for the session report */ export interface TickCounters { total: number + /** Frames read as this string */ hasSignal: number - coarseHint: number - overtone: number + /** …of which an octave up, folded down */ + octaveFolded: number + /** No pitch at all (silence, noise, a note just starting) */ silence: number - continuityRejected: number + /** A pitch, too unclear to trust */ + unclear: number + /** Another note, beyond a fifth from the string */ + offRange: number + /** A tuned string still ringing */ + ringing: number + /** A period with nothing at its fundamental: other strings ringing together */ + phantom: number } export interface TunerEngine { readonly display: Readonly /** 0-based index into the tuning — the string currently being tuned */ readonly lockedStringIndex: number + /** Frequency (Hz) of the string currently being tuned */ + readonly targetFrequency: number /** Indices of strings confirmed tuned (a new Set on every change) */ readonly tunedStrings: ReadonlySet readonly allTuned: boolean @@ -80,49 +139,11 @@ export interface TunerEngine { process(frame: AudioFrame, now: number): void /** Jump to a string; if it was confirmed, un-mark it so it gets checked again */ selectString(index: number): void - /** Use another tuning: its instrument's settings and frequency windows (state is kept) */ + /** Use another tuning, with its instrument's settings, from its first string */ setTuning(tuning: TuningPreset): void /** Back to the first string, nothing tuned */ reset(): void resetCounters(): void - /** - * Blank the reading as the latch-and-fade does (the needle keeps its place). Only what is - * shown changes: the engine never reads `display`, so its analysis is not affected. - */ - clearDisplay(): void -} - -/** How a pitch that made it through the gates is taken in (see `acceptPitch`) */ -interface AcceptOptions { - /** Show this frame's pitch as the frequency instead of the median one */ - showFramePitch: boolean - /** Count and log the frames the continuity gate drops */ - reportRejects: boolean - /** Restart the stability timer when the pitch stays STABILITY_RESET_CENTS off */ - resetStabilityWhenOff: boolean - /** Appended to the confirmation log line */ - via: string -} - -/** A frame inside the ±15% window of the locked string */ -const DIRECT: AcceptOptions = { - showFramePitch: false, - reportRejects: true, - resetStabilityWhenOff: true, - via: '', -} - -/** - * A harmonic folded down into the window. It differs from DIRECT in three ways, kept as the - * engine always had them: the frequency shown is the folded frame's, a rejected jump is - * dropped silently, and staying off by more than STABILITY_RESET_CENTS does not restart the - * stability timer. - */ -const FOLDED_OVERTONE: AcceptOptions = { - showFramePitch: true, - reportRejects: false, - resetStabilityWhenOff: false, - via: ' (via overtone fold)', } export function createTunerEngine( @@ -146,71 +167,52 @@ export function createTunerEngine( const counters: TickCounters = { total: 0, hasSignal: 0, - coarseHint: 0, - overtone: 0, + octaveFolded: 0, silence: 0, - continuityRejected: 0, - } - - // --- Per-string state (written every tick at ~60fps) --- - let stableStartTime: number | null = null - let smoothedCents: number | null = null - let advancing = false - let minFreq = 0 - let maxFreq = 0 - let hintMinFreq = 0 - let hintMaxFreq = 0 - /** True once the pitch has entered the ±15% acceptance window for the current string. - * Disables the wide coarse-hint path so it cannot flicker back mid-tune. */ - let hasEnteredFineWindow = false - let pitchHistory: number[] = [] - let outOfRangeStart: number | null = null - let inRangeGraceUntil = 0 - let lastGoodSignalTime = 0 - let lastDisplayTime = 0 - let lastLogTime = 0 - - // --- Frequency window (updated whenever the locked string or the tuning changes) --- - // Accepts only pitches within ±15% of the locked fundamental. - // ±15% is tight enough to reject adjacent open strings - // (e.g. B3 at 247Hz is 33% below E4 at 330Hz) while still - // covering a guitar that is severely out of tune. - function cacheFreqBounds() { - const idx = Math.min(lockedStringIndex, tuning.tuning.length - 1) - const lockedFreq = tuning.tuning[idx].frequency - minFreq = lockedFreq * 0.85 - maxFreq = lockedFreq * 1.15 - // ±1 octave — wide window for coarse hint when string is heavily out of tune - hintMinFreq = lockedFreq * 2 ** (-HINT_WINDOW_CENTS / 1200) - hintMaxFreq = lockedFreq * 2 ** (HINT_WINDOW_CENTS / 1200) + unclear: 0, + offRange: 0, + ringing: 0, + phantom: 0, } - cacheFreqBounds() - function lockString(index: number) { - lockedStringIndex = index - cacheFreqBounds() + // --- Per-string state --- + /** The last readings, in cents, for the median */ + let recent: number[] = [] + /** The needle, in cents; null until the first reading of a note */ + let smoothed: number | null = null + let inTune = false + /** Time (ms) in tune so far; the string is confirmed at cfg.stableMs */ + let inTuneMs = 0 + /** Since when the reading has been off, while it is */ + let offSince: number | null = null + let lastReadingTime: number | null = null + // --- Timing --- + let lastTick: number | null = null + let lastDisplayTime = -Infinity + let lastLogTime = -Infinity + + function target(): number { + return tuning.tuning[lockedStringIndex].frequency } function resetStringProgress() { - stableStartTime = null - display.stabilityProgress = 0 - advancing = false - smoothedCents = null - hasEnteredFineWindow = false - pitchHistory = [] - outOfRangeStart = null - inRangeGraceUntil = 0 - lastGoodSignalTime = 0 - lastDisplayTime = 0 + recent = [] + smoothed = null + inTune = false + inTuneMs = 0 + offSince = null + lastReadingTime = null + lastDisplayTime = -Infinity display.frequency = null display.cents = null display.hint = null + display.stabilityProgress = 0 display.needleCents = null display.signalClarity = 0 } function reset() { - lockString(0) + lockedStringIndex = 0 tunedStrings = new Set() allTuned = false resetStringProgress() @@ -221,13 +223,12 @@ export function createTunerEngine( for (let offset = 1; offset <= count; offset++) { const next = (fromIndex + offset) % count if (!tunedStrings.has(next)) { - lockString(next) + lockedStringIndex = next resetStringProgress() return } } - // All strings tuned. Keep advancing=true so no further tick can re-enter the - // confirmation block. + // Every string is in tune: the display keeps the last reading, full ring and all allTuned = true onAllTuned() } @@ -238,251 +239,175 @@ export function createTunerEngine( next.delete(index) tunedStrings = next } - lockString(index) + allTuned = false + lockedStringIndex = index resetStringProgress() } - /** The hint while off the in-tune window: still 'in-range' during the grace period */ - function offHint(now: number, displayCents: number): TunerHint { - return now < inRangeGraceUntil ? 'in-range' : displayCents > 0 ? 'too-high' : 'too-low' + /** Is `pitch` (far from the string being tuned) a tuned string, or its octave, ringing on? */ + function isTunedStringRinging(pitch: number): boolean { + for (const index of tunedStrings) { + if (index === lockedStringIndex) continue + const f = tuning.tuning[index].frequency + if ( + Math.abs(centsOff(pitch, f)) <= RINGING_MATCH_CENTS || + Math.abs(centsOff(pitch, 2 * f)) <= RINGING_MATCH_CENTS + ) { + return true + } + } + return false + } + + /** The frame as cents from the string being tuned, or null when it is not this string */ + function read( + { pitch, clarity, fundamentalShare, harmonicSpread }: AudioFrame, + now: number, + ): number | null { + if (!(pitch > 0)) { + counters.silence++ + return null + } + const tracking = lastReadingTime !== null && now - lastReadingTime <= TRACKING_GAP_MS + const clear = clarity >= (tracking ? cfg.sustainClarity : cfg.clarityThreshold) + const consistentBlend = + clarity >= BLEND_MIN_CLARITY && harmonicSpread <= CONSISTENT_SPREAD_CENTS + if (!clear && !consistentBlend) { + counters.unclear++ + return null + } + let cents = centsOff(pitch, target()) + if (Math.abs(cents) > READ_RANGE_CENTS) { + if (Math.abs(cents - 1200) > OCTAVE_FOLD_CENTS) { + counters.offRange++ + return null + } + cents -= 1200 + counters.octaveFolded++ + } + if (Math.abs(cents) > NEAR_TARGET_CENTS && isTunedStringRinging(pitch)) { + counters.ringing++ + return null + } + if (fundamentalShare < MIN_FUNDAMENTAL_SHARE) { + counters.phantom++ + return null + } + return cents } /** - * Take in a pitch inside the fine window: median filter, continuity gate, EMA, display, - * hint and stability ring, and confirmation of the string once it has been in tune for - * cfg.stableMs. + * 0.1–1: how far to trust a reading. Mostly how well its fundamental and 2nd harmonic agree + * (noise in the bands pulls them apart, other strings do not), a little its clarity. */ - function acceptPitch( - pitch: number, - clarity: number, - now: number, - isDisplayFrame: boolean, - options: AcceptOptions, - ) { - hasEnteredFineWindow = true - lastGoodSignalTime = now + function trustIn({ clarity, harmonicSpread }: AudioFrame): number { + const agreement = 1 / (1 + (harmonicSpread / HALF_TRUST_SPREAD_CENTS) ** 2) + const clearness = Math.min(1, Math.max(0, (clarity - 0.5) / 0.45)) + return Math.max(0.1, agreement * (0.5 + 0.5 * clearness)) + } - // --- Median filter --- - // Rolling buffer of the last PITCH_BUFFER_SIZE pitches. - // Median is more robust than mean against occasional octave-error spikes. - pitchHistory.push(pitch) - if (pitchHistory.length > PITCH_BUFFER_SIZE) pitchHistory.shift() - const medianPitch = median(pitchHistory) + function takeReading(cents: number, trust: number, now: number, tickMs: number) { + counters.hasSignal++ + // A note after a silence starts afresh; within one note, time runs from reading to reading + let dt = tickMs + if (lastReadingTime === null || now - lastReadingTime > SIGNAL_HOLD_MS) { + recent = [] + smoothed = null + } else if (now - lastReadingTime <= TRACKING_GAP_MS) { + dt = Math.min(MAX_TICK_MS, now - lastReadingTime) + } + lastReadingTime = now - // --- Octave-fold correction --- - // If pitchy latches onto an upper harmonic (e.g. 2nd harmonic of Low E), - // dividing by N=2..6 may bring it within 300c of the target. We prefer - // that folded value when it improves the match by >400c. - const lockedFreq = tuning.tuning[lockedStringIndex].frequency - const stablePitch = foldTowardTarget(medianPitch, lockedFreq) + recent.push(cents) + if (recent.length > MEDIAN_SIZE) recent.shift() + const filtered = median(recent) + if (smoothed === null) { + smoothed = filtered + } else { + const diff = filtered - smoothed + const timeConstant = + (Math.abs(diff) > MOVING_CENTS ? SMOOTH_MOVING_MS : SMOOTH_STEADY_MS) / trust + smoothed += diff * (1 - Math.exp(-dt / timeConstant)) + } - // --- Pitch continuity gate --- - // Reject frames where the smoothed cents would jump by more than - // PITCH_CONTINUITY_CENTS in a single tick (transient noise or string change). - const rawCents = centsBetween(stablePitch, lockedFreq) - if (smoothedCents !== null && Math.abs(rawCents - smoothedCents) > PITCH_CONTINUITY_CENTS) { - if (options.reportRejects) { - counters.continuityRejected++ - log.add( - ` CONTINUITY_REJECTED jump=${Math.abs(rawCents - smoothedCents).toFixed( - 0, - )}¢ (limit=${PITCH_CONTINUITY_CENTS}¢)`, - ) - } - return + const off = Math.abs(smoothed) + inTune = recent.length >= MIN_READINGS_IN_TUNE && off <= (inTune ? RELEASE_CENTS : ACCEPT_CENTS) + if (inTune) { + offSince = null + inTuneMs += dt + } else { + if (offSince === null) offSince = now + if (now - offSince >= STABILITY_RESET_MS) inTuneMs = 0 } + } - // --- EMA smoothing --- - // Exponential moving average over the raw-cents readings. - // alpha=0.04 at 60fps gives ~500ms settling time — heavy enough - // to prevent needle jitter without hiding genuine pitch drift. - smoothedCents = - smoothedCents === null - ? rawCents - : smoothedCents + CENTS_EMA_ALPHA * (rawCents - smoothedCents) - const displayCents = Math.round(smoothedCents) + function showReading(clarity: number, now: number) { + if (smoothed === null) return + lastDisplayTime = now + display.frequency = Math.round(frequencyAt(smoothed, target()) * 10) / 10 + display.cents = Math.round(smoothed) || 0 + display.needleCents = smoothed + display.hint = inTune ? 'in-range' : smoothed > 0 ? 'too-high' : 'too-low' + display.stabilityProgress = Math.min(1, inTuneMs / cfg.stableMs) + display.signalClarity = clarity + } - // --- Display write (~30fps) --- - // Engine state (smoothedCents, stableStartTime) is updated every tick regardless. + /** No reading this tick: hold the last one for a while, then blank it (the needle stays) */ + function noReading(now: number, isDisplayFrame: boolean) { + if (lastReadingTime !== null && now - lastReadingTime < SIGNAL_HOLD_MS) return + lastReadingTime = null + recent = [] + smoothed = null + inTune = false + inTuneMs = 0 + offSince = null if (isDisplayFrame) { lastDisplayTime = now - display.frequency = Math.round((options.showFramePitch ? pitch : stablePitch) * 10) / 10 - display.cents = displayCents - display.needleCents = smoothedCents - display.signalClarity = clarity + display.frequency = null + display.cents = null + display.hint = null + display.stabilityProgress = 0 + display.signalClarity = 0 } + } - // --- Hint + stability ring --- - // stableStartTime tracks when the pitch first entered the ACCEPT_CENTS - // window. cfg.stableMs varies by instrument (600ms violin – 1500ms bass). - // advanceToNextUntuned() is called exactly once per string via `advancing`. - if (Math.abs(displayCents) <= ACCEPT_CENTS) { - outOfRangeStart = null - if (stableStartTime === null) stableStartTime = now - const elapsed = now - stableStartTime - if (isDisplayFrame) { - display.hint = 'in-range' - inRangeGraceUntil = now + HINT_GRACE_MS - display.stabilityProgress = Math.min(1, elapsed / cfg.stableMs) - } - if (elapsed >= cfg.stableMs && !advancing) { - advancing = true - log.add( - `STRING_CONFIRMED str=${lockedStringIndex} after ${elapsed.toFixed(0)}ms${options.via}`, - ) - const completedIdx = lockedStringIndex - const next = new Set(tunedStrings) - next.add(completedIdx) - tunedStrings = next - advanceToNextUntuned(completedIdx) - } - } else { - if (isDisplayFrame) display.hint = offHint(now, displayCents) - if (!options.resetStabilityWhenOff) return - if (Math.abs(displayCents) > STABILITY_RESET_CENTS) { - if (outOfRangeStart === null) outOfRangeStart = now - if (now - outOfRangeStart >= STABILITY_RESET_MS) { - stableStartTime = null - outOfRangeStart = null - if (isDisplayFrame) display.stabilityProgress = 0 - } - } else { - outOfRangeStart = null - } - } + function confirmString() { + const index = lockedStringIndex + log.add( + `STRING_CONFIRMED str=${index} at ${(smoothed ?? 0).toFixed(2)}¢ after ${inTuneMs.toFixed(0)}ms in tune`, + ) + tunedStrings = new Set(tunedStrings).add(index) + advanceToNextUntuned(index) } - function process({ pitch, clarity, rms }: AudioFrame, now: number) { + function process(frame: AudioFrame, now: number) { + if (allTuned) return + const tickMs = lastTick === null ? 0 : Math.min(MAX_TICK_MS, Math.max(0, now - lastTick)) + lastTick = now + counters.total++ const isDisplayFrame = now - lastDisplayTime >= DISPLAY_INTERVAL_MS - const isLogFrame = now - lastLogTime >= LOG_INTERVAL_MS - const lockedFreq = tuning.tuning[lockedStringIndex].frequency - // Dual clarity gate: tighter when RMS is low (decaying string has worse SNR). - // Both thresholds come from the instrument's settings so bass/guitar/ukulele/violin - // each use appropriate values for their sustain characteristics. - const clarityGate = rms < LOW_RMS_THRESHOLD ? cfg.decayClarityThreshold : cfg.clarityThreshold - // Frequency window rejects pitches outside ±15% of the locked fundamental, - // blocking harmonics of other strings that fall outside this narrow band. - const hasSignal = clarity > clarityGate && pitch >= minFreq && pitch <= maxFreq + const cents = read(frame, now) + if (cents === null) noReading(now, isDisplayFrame) + else { + takeReading(cents, trustIn(frame), now, tickMs) + if (isDisplayFrame || (inTune && inTuneMs >= cfg.stableMs)) showReading(frame.clarity, now) + } - counters.total++ - if (isLogFrame) { + if (now - lastLogTime >= LOG_INTERVAL_MS) { lastLogTime = now - const stringName = tuning.tuning[lockedStringIndex].note + const s = tuning.tuning[lockedStringIndex] log.add( - `t=${(now / 1000).toFixed(2)}s str=${stringName}(${lockedFreq.toFixed(1)}Hz)` + - ` pitch=${pitch.toFixed(1)}Hz clarity=${clarity.toFixed( - 3, - )} rms=${rms.toFixed(4)} gate=${clarityGate.toFixed(3)}` + - ` window=[${minFreq.toFixed(1)}-${maxFreq.toFixed(1)}]` + - ` hintWindow=[${hintMinFreq.toFixed(1)}-${hintMaxFreq.toFixed(1)}]` + - ` hasSignal=${hasSignal}` + - ` fineEntered=${hasEnteredFineWindow}` + - ` clarityOk=${clarity > clarityGate}` + - ` inFine=${pitch >= minFreq && pitch <= maxFreq}` + - ` inHint=${pitch >= hintMinFreq && pitch <= hintMaxFreq}`, + `t=${(now / 1000).toFixed(2)}s str=${s.note}${s.octave}(${s.frequency.toFixed(1)}Hz)` + + ` pitch=${frame.pitch.toFixed(2)}Hz clarity=${frame.clarity.toFixed(3)}` + + ` share=${frame.fundamentalShare.toFixed(2)} spread=${frame.harmonicSpread.toFixed(1)}¢ rms=${frame.rms.toFixed(4)}` + + ` reading=${cents === null ? '-' : `${cents.toFixed(1)}¢`}` + + ` needle=${smoothed === null ? '-' : `${smoothed.toFixed(2)}¢`}` + + ` inTune=${inTune} progress=${(inTuneMs / cfg.stableMs).toFixed(2)}`, ) } - if (hasSignal) { - counters.hasSignal++ - acceptPitch(pitch, clarity, now, isDisplayFrame, DIRECT) - return - } - - // --- Overtone fold-and-route --- - // Pitchy sometimes returns a strong harmonic instead of the fundamental, - // especially on Low E/B at peak attack (rms high, 2× harmonic dominates). - // Fold the harmonic down to the fundamental and, if it lands in the fine window, - // take it in like a direct reading so it contributes to stability progress. - if (clarity > cfg.clarityThreshold && isHarmonicOf(pitch, lockedFreq)) { - counters.overtone++ - const foldedPitch = foldTowardTarget(pitch, lockedFreq) - if (foldedPitch >= minFreq && foldedPitch <= maxFreq) { - if (isLogFrame) - log.add( - ` OVERTONE_FOLDED pitch=${pitch.toFixed( - 1, - )}Hz → ${foldedPitch.toFixed(1)}Hz (in fine window)`, - ) - acceptPitch(foldedPitch, clarity, now, isDisplayFrame, FOLDED_OVERTONE) - } else { - // Folded pitch still outside fine window — just refresh the latch. - if (isLogFrame) - log.add( - ` OVERTONE_LATCH pitch=${pitch.toFixed(1)}Hz harmonic of ${lockedFreq.toFixed(1)}Hz`, - ) - lastGoodSignalTime = now - } - return - } - - // --- Coarse hint (heavily out of tune) --- - // Only active before the pitch has ever entered the ±15% fine-tuning window - // for this string. Once hasEnteredFineWindow is set, this path is disabled - // so it cannot flicker back on mid-tune if the pitch briefly dips outside - // the acceptance window. Resets when the string resets (selectString / advance). - // Suppress coarse hint if the pitch is a harmonic of an already-tuned string - // (sympathetic resonance from a recently confirmed string can produce a - // spurious too-high/too-low flash before the user plucks the next string). - const isSympathetic = [...tunedStrings].some((idx) => { - const f = tuning.tuning[idx].frequency - return isHarmonicOf(pitch, f) || isHarmonicOf(f, pitch) - }) - if ( - !hasEnteredFineWindow && - !isSympathetic && - clarity > cfg.clarityThreshold && - pitch >= hintMinFreq && - pitch <= hintMaxFreq - ) { - counters.coarseHint++ - lastGoodSignalTime = now - smoothedCents = null - pitchHistory = [] - stableStartTime = null - const rawCents = centsBetween(pitch, lockedFreq) - if (isLogFrame) - log.add( - ` COARSE_HINT pitch=${pitch.toFixed(1)}Hz cents=${ - rawCents > 0 ? '+' : '' - }${rawCents}¢ hint=${rawCents > 0 ? 'too-high' : 'too-low'}`, - ) - if (isDisplayFrame) { - lastDisplayTime = now - display.frequency = Math.round(pitch * 10) / 10 - display.cents = rawCents - display.needleCents = rawCents - display.hint = rawCents > 0 ? 'too-high' : 'too-low' - display.signalClarity = clarity - display.stabilityProgress = 0 - } - return - } - - // --- Latch-and-Fade --- - // Keep the display alive for SIGNAL_HOLD_MS after the last valid frame. - // This bridges the natural decay gap when a string fades to silence, - // preventing the needle from snapping to blank between plucks. - // needleCents is intentionally NOT cleared — needle holds its last position. - pitchHistory = [] - const held = now - lastGoodSignalTime < SIGNAL_HOLD_MS - if (!held) { - counters.silence++ - stableStartTime = null - outOfRangeStart = null - inRangeGraceUntil = 0 - if (isDisplayFrame) { - lastDisplayTime = now - display.frequency = null - display.cents = null - display.hint = null - display.stabilityProgress = 0 - display.signalClarity = 0 - } - } else if (isDisplayFrame && now < inRangeGraceUntil) { - display.hint = 'in-range' - } + if (inTune && inTuneMs >= cfg.stableMs) confirmString() } return { @@ -490,6 +415,9 @@ export function createTunerEngine( get lockedStringIndex() { return lockedStringIndex }, + get targetFrequency() { + return target() + }, get tunedStrings() { return tunedStrings }, @@ -505,18 +433,11 @@ export function createTunerEngine( setTuning(next) { tuning = next cfg = instrumentConfig(next.category) - cacheFreqBounds() + reset() }, reset, resetCounters() { for (const key of Object.keys(counters) as (keyof TickCounters)[]) counters[key] = 0 }, - clearDisplay() { - display.frequency = null - display.cents = null - display.hint = null - display.stabilityProgress = 0 - display.signalClarity = 0 - }, } } diff --git a/src/tuner/fft.test.ts b/src/tuner/fft.test.ts new file mode 100644 index 0000000..ab2ea3e --- /dev/null +++ b/src/tuner/fft.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest' +import { FFT } from './fft' + +/** The DFT by its definition, O(N²) */ +function naiveDft(re: number[], im: number[], inverse = false) { + const n = re.length + const sign = inverse ? 1 : -1 + const outRe: number[] = [] + const outIm: number[] = [] + for (let k = 0; k < n; k++) { + let sr = 0 + let si = 0 + for (let t = 0; t < n; t++) { + const a = (sign * 2 * Math.PI * k * t) / n + sr += re[t] * Math.cos(a) - im[t] * Math.sin(a) + si += re[t] * Math.sin(a) + im[t] * Math.cos(a) + } + outRe.push(sr) + outIm.push(si) + } + return { re: outRe, im: outIm } +} + +describe('FFT', () => { + it('matches the DFT definition, forward and inverse', () => { + for (const size of [2, 8, 64, 256]) { + const re = Array.from({ length: size }, (_, i) => Math.sin(i * 1.7) + 0.3 * Math.cos(i * 0.2)) + const im = Array.from({ length: size }, (_, i) => Math.cos(i * 0.9) - 0.5) + for (const inverse of [false, true]) { + const expected = naiveDft(re, im, inverse) + const r = Float64Array.from(re) + const i = Float64Array.from(im) + new FFT(size).transform(r, i, inverse) + for (let k = 0; k < size; k++) { + expect(r[k]).toBeCloseTo(expected.re[k], 9) + expect(i[k]).toBeCloseTo(expected.im[k], 9) + } + } + } + }) + + it('round-trips: inverse(forward(x)) / N = x', () => { + const size = 1024 + const re = Float64Array.from( + { length: size }, + (_, i) => Math.sin(i * 0.05) * Math.exp(-i / 500), + ) + const im = new Float64Array(size) + const r = re.slice() + const fft = new FFT(size) + fft.transform(r, im) + fft.transform(r, im, true) + for (let k = 0; k < size; k++) expect(r[k] / size).toBeCloseTo(re[k], 12) + }) + + it('refuses a size that is not a power of 2', () => { + expect(() => new FFT(48)).toThrow() + expect(() => new FFT(1)).toThrow() + }) +}) diff --git a/src/tuner/fft.ts b/src/tuner/fft.ts new file mode 100644 index 0000000..016730d --- /dev/null +++ b/src/tuner/fft.ts @@ -0,0 +1,70 @@ +/** + * An in-place radix-2 complex FFT on Float64Arrays, with its twiddle factors and bit-reversal + * table computed once per size. Pure: no Vue, no Web Audio. + */ +export class FFT { + readonly size: number + private readonly cos: Float64Array + private readonly sin: Float64Array + private readonly reversed: Uint32Array + + constructor(size: number) { + if (size < 2 || (size & (size - 1)) !== 0) { + throw new Error(`FFT size must be a power of 2, got ${size}`) + } + this.size = size + const half = size >> 1 + this.cos = new Float64Array(half) + this.sin = new Float64Array(half) + for (let i = 0; i < half; i++) { + this.cos[i] = Math.cos((2 * Math.PI * i) / size) + this.sin[i] = Math.sin((2 * Math.PI * i) / size) + } + const bits = Math.log2(size) + this.reversed = new Uint32Array(size) + for (let i = 0; i < size; i++) { + let r = 0 + for (let b = 0; b < bits; b++) r = (r << 1) | ((i >>> b) & 1) + this.reversed[i] = r + } + } + + /** + * Transform `re` + i·`im` in place: X[k] = Σ x[n]·e^(−2πikn/N), or with `inverse` the + * conjugate transform, unscaled (divide by `size` to invert). + */ + transform(re: Float64Array, im: Float64Array, inverse = false) { + const n = this.size + const reversed = this.reversed + for (let i = 0; i < n; i++) { + const j = reversed[i] + if (j > i) { + const tr = re[i] + re[i] = re[j] + re[j] = tr + const ti = im[i] + im[i] = im[j] + im[j] = ti + } + } + const sign = inverse ? 1 : -1 + for (let len = 2; len <= n; len <<= 1) { + const half = len >> 1 + const step = n / len + for (let start = 0; start < n; start += len) { + for (let k = 0; k < half; k++) { + const wr = this.cos[k * step] + const wi = sign * this.sin[k * step] + const a = start + k + const b = a + half + const tr = re[b] * wr - im[b] * wi + const ti = re[b] * wi + im[b] * wr + re[b] = re[a] - tr + im[b] = im[a] - ti + re[a] += tr + im[a] += ti + } + } + } + } +} diff --git a/src/tuner/instruments.ts b/src/tuner/instruments.ts index 969c5a3..3b8cce1 100644 --- a/src/tuner/instruments.ts +++ b/src/tuner/instruments.ts @@ -1,55 +1,35 @@ import type { InstrumentCategory } from '../data/tunings' -/** Per-instrument analysis configuration */ +/** Per-instrument settings of the tuning engine */ export interface InstrumentConfig { - /** Primary FFT window size — larger values improve low-freq fundamental detection */ - primaryFftSize: number - /** How long (ms) pitch must stay inside ACCEPT_CENTS to confirm the string */ + /** How long (ms) the string must stay in tune to be confirmed */ stableMs: number - /** Minimum pitchy clarity to accept a pitch reading */ + /** Clarity (0–1, how clearly pitched the sound is) a frame needs to start a reading */ clarityThreshold: number - /** Stricter clarity gate when the string RMS is decaying */ - decayClarityThreshold: number + /** + * Clarity a frame needs to carry on a reading already going: lower, for the quieter tail + * of a note, but never so low that the noise of its last moments moves the needle. + * Always ≤ clarityThreshold. + */ + sustainClarity: number } +/* + * Clarity is the height of the period peak of the NSDF: about S/(S+N) for a tone in noise. + * Pure room noise never reaches 0.45, a string at 0 dB SNR reads 0.5 with errors of tens of + * cents; 0.85 is about 8 dB of SNR, 0.75 about 5 dB. + * + * stableMs: a plucked steel string sustains for seconds, so a second in tune is quick and + * still proves the reading steady; nylon ukulele strings die away sooner, and a bowed violin + * string holds its pitch for as long as it is bowed. Bass strings settle more slowly after + * the attack. + */ export const INSTRUMENT_CONFIGS: Record = { - // decayClarityThreshold MUST always be <= clarityThreshold: - // decaying strings produce noisier signals (lower RMS → worse SNR), - // so the clarity gate must be more permissive when the string is quiet, - // not stricter. Inverted values cause valid quiet-tail frames to be - // rejected, fragmenting the stability timer and requiring many plucks. - // - // bass: 8192 FFT resolves E1(41Hz) cleanly; long sustain warrants - // 1500ms hold. Low strings have heavy overtone content so - // decay threshold is relaxed to match guitar's tuned value. - // guitar: confirmed via session logs — 0.80 decay threshold accepts - // quiet-tail frames at 0.83-0.91 while rejecting noise at ≤0.76. - // ukulele: nylon strings, short sustain; quiet tail is brief but noisy. - // violin: bowed, no sharp attack; clarity drops fast after bow lift. - bass: { - primaryFftSize: 8192, - stableMs: 1500, - clarityThreshold: 0.93, - decayClarityThreshold: 0.82, - }, - guitar: { - primaryFftSize: 2048, - stableMs: 1100, - clarityThreshold: 0.92, - decayClarityThreshold: 0.8, - }, - ukulele: { - primaryFftSize: 2048, - stableMs: 800, - clarityThreshold: 0.85, - decayClarityThreshold: 0.75, - }, - violin: { - primaryFftSize: 2048, - stableMs: 600, - clarityThreshold: 0.8, - decayClarityThreshold: 0.7, - }, + bass: { stableMs: 1200, clarityThreshold: 0.85, sustainClarity: 0.75 }, + guitar: { stableMs: 1000, clarityThreshold: 0.85, sustainClarity: 0.75 }, + ukulele: { stableMs: 700, clarityThreshold: 0.85, sustainClarity: 0.75 }, + // Bow noise lowers the clarity of a perfectly steady note + violin: { stableMs: 600, clarityThreshold: 0.8, sustainClarity: 0.7 }, } /** The configuration for `category`, guitar's for anything else (custom tunings, say). */ diff --git a/src/tuner/pitch.test.ts b/src/tuner/pitch.test.ts index 1a531ce..57620b0 100644 --- a/src/tuner/pitch.test.ts +++ b/src/tuner/pitch.test.ts @@ -1,39 +1,34 @@ import { describe, expect, it } from 'vitest' -import { centsBetween, foldTowardTarget, isHarmonicOf, median } from './pitch' +import { centsOff, frequencyAt, median } from './pitch' const E2 = 82.4069 -describe('centsBetween', () => { +describe('centsOff', () => { it('is 0 for the same frequency, ±1200 for an octave, ±100 for a semitone', () => { - expect(centsBetween(E2, E2)).toBe(0) - expect(centsBetween(E2 * 2, E2)).toBe(1200) - expect(centsBetween(E2 / 2, E2)).toBe(-1200) - expect(centsBetween(E2 * 2 ** (1 / 12), E2)).toBe(100) + expect(centsOff(E2, E2)).toBe(0) + expect(centsOff(E2 * 2, E2)).toBeCloseTo(1200, 9) + expect(centsOff(E2 / 2, E2)).toBeCloseTo(-1200, 9) + expect(centsOff(E2 * 2 ** (1 / 12), E2)).toBeCloseTo(100, 9) }) - it('rounds to the nearest cent', () => { - expect(centsBetween(E2 * 2 ** (7.4 / 1200), E2)).toBe(7) - expect(centsBetween(E2 * 2 ** (-7.6 / 1200), E2)).toBe(-8) + it('keeps fractions of a cent', () => { + expect(centsOff(E2 * 2 ** (0.25 / 1200), E2)).toBeCloseTo(0.25, 9) + expect(centsOff(E2 * 2 ** (-7.6 / 1200), E2)).toBeCloseTo(-7.6, 9) }) }) -describe('isHarmonicOf', () => { - it('recognises the 2nd to 6th harmonics, within 8%', () => { - for (const n of [2, 3, 4, 5, 6]) expect(isHarmonicOf(E2 * n, E2)).toBe(true) - expect(isHarmonicOf(E2 * 3 * 1.02, E2)).toBe(true) - }) - - it('does not count the fundamental, the 7th harmonic or notes in between', () => { - expect(isHarmonicOf(E2, E2)).toBe(false) - expect(isHarmonicOf(E2 * 7, E2)).toBe(false) - expect(isHarmonicOf(E2 * 2.5, E2)).toBe(false) +describe('frequencyAt', () => { + it('is the inverse of centsOff', () => { + for (const cents of [-700, -12.5, 0, 3, 1200]) { + expect(centsOff(frequencyAt(cents, E2), E2)).toBeCloseTo(cents, 9) + } }) }) describe('median', () => { - it('is the middle value, the upper middle one for an even count', () => { + it('is the middle value, the mean of the two middle ones for an even count', () => { expect(median([3, 1, 2])).toBe(2) - expect(median([4, 1, 3, 2])).toBe(3) + expect(median([4, 1, 3, 2])).toBe(2.5) }) it('ignores a single octave-error spike', () => { @@ -46,23 +41,3 @@ describe('median', () => { expect(input).toEqual([3, 1, 2]) }) }) - -describe('foldTowardTarget', () => { - it('brings a harmonic down to the fundamental', () => { - expect(foldTowardTarget(E2 * 2, E2)).toBeCloseTo(E2, 6) - expect(foldTowardTarget(E2 * 3, E2)).toBeCloseTo(E2, 6) - }) - - it('keeps a slightly sharp harmonic slightly sharp', () => { - const folded = foldTowardTarget(E2 * 2 * 2 ** (10 / 1200), E2) - expect(centsBetween(folded, E2)).toBe(10) - }) - - it('leaves a pitch near the target alone', () => { - expect(foldTowardTarget(E2 * 1.1, E2)).toBe(E2 * 1.1) - }) - - it('leaves a pitch that no division brings within 300 cents', () => { - expect(foldTowardTarget(E2 * 2.5, E2)).toBe(E2 * 2.5) - }) -}) diff --git a/src/tuner/pitch.ts b/src/tuner/pitch.ts index fcc42fc..132498e 100644 --- a/src/tuner/pitch.ts +++ b/src/tuner/pitch.ts @@ -1,43 +1,18 @@ /** Pure pitch arithmetic used by the tuning engine. No state, no Vue. */ -/** Cents from `targetFreq` to `freq`, rounded to the nearest cent. */ -export function centsBetween(freq: number, targetFreq: number): number { - return Math.round(1200 * Math.log2(freq / targetFreq)) +/** Cents from `targetFreq` to `freq` (positive: sharp), not rounded. */ +export function centsOff(freq: number, targetFreq: number): number { + return 1200 * Math.log2(freq / targetFreq) } -/** - * Returns true if `pitch` is approximately an integer harmonic (2×–6×) of - * `fundamentalFreq`. Tolerance ±8% covers natural intonation variance. - */ -export function isHarmonicOf(pitch: number, fundamentalFreq: number): boolean { - for (let n = 2; n <= 6; n++) { - if (Math.abs(pitch / fundamentalFreq - n) < 0.08) return true - } - return false +/** The frequency `cents` away from `targetFreq`. */ +export function frequencyAt(cents: number, targetFreq: number): number { + return targetFreq * 2 ** (cents / 1200) } -/** Median of `arr` (the upper one of the two middle values for an even length). */ -export function median(arr: number[]): number { +/** Median of `arr` (the mean of the two middle values for an even length). */ +export function median(arr: readonly number[]): number { const s = [...arr].sort((a, b) => a - b) - return s[Math.floor(s.length / 2)] -} - -/** - * Fold `pitch` toward `targetFreq` by dividing by N = 2..6. - * If dividing brings it within 300¢ AND improves the match by >400¢, - * return the folded value. Corrects pitchy latching onto upper harmonics. - */ -export function foldTowardTarget(pitch: number, targetFreq: number): number { - const rawCents = Math.abs(centsBetween(pitch, targetFreq)) - let best = pitch - let bestCents = rawCents - for (let n = 2; n <= 6; n++) { - const folded = pitch / n - const fc = Math.abs(centsBetween(folded, targetFreq)) - if (fc < bestCents && rawCents - fc > 400 && fc < 300) { - bestCents = fc - best = folded - } - } - return best + const mid = s.length >> 1 + return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2 }