@ac-kit/media-piano-audio 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/LICENSE +28 -0
  3. package/README.md +246 -2
  4. package/dist/acoustics/_assert-piano-pitch.d.ts +6 -0
  5. package/dist/acoustics/_assert-piano-pitch.d.ts.map +1 -0
  6. package/dist/acoustics/_assert-piano-pitch.js +12 -0
  7. package/dist/acoustics/_assert-piano-pitch.js.map +1 -0
  8. package/dist/acoustics/piano-partials.d.ts +27 -0
  9. package/dist/acoustics/piano-partials.d.ts.map +1 -0
  10. package/dist/acoustics/piano-partials.js +60 -0
  11. package/dist/acoustics/piano-partials.js.map +1 -0
  12. package/dist/calibrate/estimate-input-latency.d.ts +41 -0
  13. package/dist/calibrate/estimate-input-latency.d.ts.map +1 -0
  14. package/dist/calibrate/estimate-input-latency.js +58 -0
  15. package/dist/calibrate/estimate-input-latency.js.map +1 -0
  16. package/dist/index.d.ts +8 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +8 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/synthesize/synthesize-piano.d.ts +97 -0
  21. package/dist/synthesize/synthesize-piano.d.ts.map +1 -0
  22. package/dist/synthesize/synthesize-piano.js +132 -0
  23. package/dist/synthesize/synthesize-piano.js.map +1 -0
  24. package/dist/synthesize/synthesize-tick.d.ts +39 -0
  25. package/dist/synthesize/synthesize-tick.d.ts.map +1 -0
  26. package/dist/synthesize/synthesize-tick.js +64 -0
  27. package/dist/synthesize/synthesize-tick.js.map +1 -0
  28. package/dist/verify/_onset-detector.d.ts +58 -0
  29. package/dist/verify/_onset-detector.d.ts.map +1 -0
  30. package/dist/verify/_onset-detector.js +206 -0
  31. package/dist/verify/_onset-detector.js.map +1 -0
  32. package/dist/verify/_templates.d.ts +37 -0
  33. package/dist/verify/_templates.d.ts.map +1 -0
  34. package/dist/verify/_templates.js +113 -0
  35. package/dist/verify/_templates.js.map +1 -0
  36. package/dist/verify/piano-chord-verifier.d.ts +204 -0
  37. package/dist/verify/piano-chord-verifier.d.ts.map +1 -0
  38. package/dist/verify/piano-chord-verifier.js +938 -0
  39. package/dist/verify/piano-chord-verifier.js.map +1 -0
  40. package/dist/verify/tuning.d.ts +126 -0
  41. package/dist/verify/tuning.d.ts.map +1 -0
  42. package/dist/verify/tuning.js +133 -0
  43. package/dist/verify/tuning.js.map +1 -0
  44. package/dist/verify/types.d.ts +74 -0
  45. package/dist/verify/types.d.ts.map +1 -0
  46. package/dist/verify/types.js +2 -0
  47. package/dist/verify/types.js.map +1 -0
  48. package/package.json +71 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,63 @@
1
+ # @ac-kit/media-piano-audio
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 065cf8d: Synthetic signals for tests, demonstrations and loopback tones, deterministic for given arguments. `synthesizePiano(notes, { sampleRate, durationMs, referenceHz?, noise?, seed? })` sounds each `{ pitch, time, release?, level? }` note as the stretched partials of `pianoPartialPitches` under an attack and a pitch-dependent decay, a released note dying away in about 50 ms, plus seeded uniform white noise of the given RMS. `chordNotes(pitches, time, { spread?, level?, direction? })` gives the notes of a chord struck together or spread from the lowest or highest key, and refuses any pitch, level or resulting time that `synthesizePiano` would reject. `synthesizeTick({ sampleRate, band, durationMs, level?, seed? })` is a burst of noise confined to a band under a Hann envelope, its peak at `level`. Each throws `RangeError` on an option or note out of range. `@ac-kit/math-random` becomes a runtime dependency.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [065cf8d]
12
+ - Updated dependencies [065cf8d]
13
+ - Updated dependencies [065cf8d]
14
+ - Updated dependencies [065cf8d]
15
+ - Updated dependencies [065cf8d]
16
+ - Updated dependencies [065cf8d]
17
+ - @ac-kit/core@0.11.0
18
+ - @ac-kit/math-random@0.3.0
19
+ - @ac-kit/math-signal@0.3.0
20
+ - @ac-kit/math-stats@0.4.0
21
+ - @ac-kit/math-linear@0.2.1
22
+ - @ac-kit/model-music@0.8.1
23
+
24
+ ## 0.1.0
25
+
26
+ ### Minor Changes
27
+
28
+ - 5152230: New package: `PianoChordVerifier` checks microphone input against an expected
29
+ piano chord and reports heard, missing and wrong notes with latency-corrected
30
+ onset times. Use `expect(id, pitches, { fromTime })` to schedule a chord on
31
+ that same clock. The verifier accepts arbitrary input block lengths, runs in an
32
+ AudioWorklet and can calibrate background noise into a structured-cloneable
33
+ `NoiseProfile`. Use `validatePianoVerifierTuning` to check a tuning loaded from
34
+ JSON against `PianoVerifierTuning`. The package also exports
35
+ `estimateInputLatency`, `pianoInharmonicity` and `pianoPartialPitches`.
36
+
37
+ ### Patch Changes
38
+
39
+ - Updated dependencies [2a0fe74]
40
+ - Updated dependencies [5152230]
41
+ - Updated dependencies [2a0fe74]
42
+ - Updated dependencies [5152230]
43
+ - Updated dependencies [5152230]
44
+ - Updated dependencies [2a0fe74]
45
+ - Updated dependencies [2a0fe74]
46
+ - Updated dependencies [5152230]
47
+ - Updated dependencies [5152230]
48
+ - Updated dependencies [5152230]
49
+ - Updated dependencies [5152230]
50
+ - Updated dependencies [5152230]
51
+ - Updated dependencies [5152230]
52
+ - Updated dependencies [5152230]
53
+ - Updated dependencies [5152230]
54
+ - Updated dependencies [5152230]
55
+ - Updated dependencies [5152230]
56
+ - Updated dependencies [5152230]
57
+ - Updated dependencies [5152230]
58
+ - Updated dependencies [5152230]
59
+ - @ac-kit/core@0.10.0
60
+ - @ac-kit/math-linear@0.2.0
61
+ - @ac-kit/math-signal@0.2.0
62
+ - @ac-kit/math-stats@0.3.0
63
+ - @ac-kit/model-music@0.8.0
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2024-2026 Anthony Champagne and contributors
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,247 @@
1
- # Temporary Holding Version
1
+ # @ac-kit/media-piano-audio
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Piano audio analysis. First content: score-informed chord verification — tell
4
+ it which chord is due, feed it the microphone, and for every key press it
5
+ reports which expected notes it heard, which it did not, and which other notes
6
+ sounded. It verifies what a score asks for; it does not transcribe. Beside
7
+ it, a synthetic piano and a band-limited tick, for tests, demonstrations and the
8
+ tones a page plays to measure its own loopback.
9
+
10
+ ```ts
11
+ import { PianoChordVerifier } from "@ac-kit/media-piano-audio";
12
+
13
+ const verifier = new PianoChordVerifier({ sampleRate: 48_000 });
14
+ verifier.calibrateNoise(1000); // the player keeps silent for a second
15
+ verifier.expect(1, [60, 64, 67]); // C major is due
16
+
17
+ // For each block of microphone samples, as an AudioWorklet delivers them:
18
+ for (const verdict of verifier.process(block)) {
19
+ verdict.expectationId; // 1
20
+ verdict.heard; // [60, 64, 67]
21
+ verdict.missing; // []
22
+ verdict.wrong; // []
23
+ verdict.onsetTime; // seconds since the stream started, latency taken off
24
+ }
25
+ ```
26
+
27
+ ## What it exposes
28
+
29
+ - `PianoChordVerifier` — the streaming verifier.
30
+ - `new PianoChordVerifier({ sampleRate, windowMs?, latencyMs?, referenceHz?, tuning?, noiseProfile? })`:
31
+ `sampleRate` 22 050–96 000 Hz; `windowMs` 30–120, default 90, the length
32
+ of audio compared before and after a press (longer catches more wrong and
33
+ missing notes and answers later); `latencyMs` the finite, non-negative input latency taken off
34
+ every onset time; `referenceHz` the frequency of A4, 392–494, default 440.
35
+ - `process(block)` takes a `Float32Array` of any length and returns the
36
+ verdicts decided during it — a shared frozen empty array when there are
37
+ none.
38
+ - `expect(id, pitches, { fromTime }?)` schedules a chord: MIDI keys 21–108,
39
+ `[]` for a rest. The latest change at or before the corrected `onsetTime`
40
+ wins. Calls for the same time replace one another.
41
+ - `calibrateNoise(durationMs = 1000)`, `calibrating`, `noiseProfile()`:
42
+ measure background noise while the player keeps silent. A second
43
+ `calibrateNoise()` call starts the measurement over. Poll `calibrating`
44
+ after `process()` to see when it ends.
45
+ - `latencyMs` can be set at any time but must be finite and non-negative.
46
+ Set it before scheduling rhythm practice: changes affect unconfirmed
47
+ onsets and do not bring back discarded expectation history. `reset()`
48
+ restarts time at 0 and keeps the noise profile, latency and current
49
+ expectation, but discards future changes.
50
+ - `ChordVerdict` — `{ source, expectationId, expected, heard, missing, wrong,
51
+ onsetTime, onsetFrame, decidedFrame }`.
52
+ - `NoiseProfile` — `{ version, sampleRate, windowMs, grid, bandNoise, newEnergyNoise,
53
+ levelDb }`, a plain object `structuredClone` and `postMessage` carry. A
54
+ profile with a different sample rate, analysis window or frequency grid is
55
+ refused with a `RangeError`. Of the tuning fields, only those that change
56
+ the frequency grid invalidate a stored profile.
57
+ - `estimateInputLatency(dueTimes, onsetTimes, { maxOffsetMs, minPairs })` — the
58
+ median offset between the presses of a count-in and the onsets detected, or
59
+ `null` with too few pairs.
60
+ - `PianoVerifierTuning`, `DEFAULT_PIANO_VERIFIER_TUNING`,
61
+ `validatePianoVerifierTuning` — every constant of the algorithm as versioned
62
+ JSON data, so a tuning for another piano or microphone ships as a file.
63
+ - `pianoInharmonicity(pitch)`, `pianoPartialPitches(pitch, count,
64
+ inharmonicity?, out?)` — where a piano string's partials sound.
65
+ - `synthesizePiano(notes, { sampleRate, durationMs, referenceHz?, noise?,
66
+ seed? })` — a piano-like signal from the same partial model, with seeded
67
+ uniform white noise; `chordNotes(pitches, time, { spread?, level?,
68
+ direction? })` makes the notes of a chord, struck together or spread.
69
+ - `synthesizeTick({ sampleRate, band, durationMs, level?, seed? })` — a short
70
+ burst of noise confined to a band under a Hann envelope, a click kept out of
71
+ the bands the verifier listens to.
72
+
73
+ ## Synthetic piano and tick
74
+
75
+ The synthetic piano is the verifier's own model of a piano: each note's
76
+ stretched partials (`pianoPartialPitches`, up to 20, none within 500 Hz of the
77
+ Nyquist frequency) at amplitude `level / h`, a 3 ms attack and an exponential
78
+ decay faster towards the treble and the upper partials; a note with a
79
+ `release` dies away in about 50 ms. It is not a realistic piano: test the
80
+ verifier's accuracy on rendered SoundFont clips. Note times are seconds on the
81
+ signal's clock, like `onsetTime`; the signal's length is `durationMs`. The same
82
+ arguments always give the same samples.
83
+
84
+ ```ts
85
+ import {
86
+ chordNotes,
87
+ PianoChordVerifier,
88
+ synthesizePiano,
89
+ synthesizeTick,
90
+ } from "@ac-kit/media-piano-audio";
91
+
92
+ const signal = synthesizePiano(chordNotes([60, 64, 67], 0.5, { spread: 0.01 }), {
93
+ sampleRate: 48_000,
94
+ durationMs: 1500,
95
+ noise: 1e-4,
96
+ });
97
+ const verifier = new PianoChordVerifier({ sampleRate: 48_000 });
98
+ verifier.expect(1, [60, 64, 67]);
99
+ const verdicts = verifier.process(signal);
100
+
101
+ const tick = synthesizeTick({ sampleRate: 48_000, band: [12_000, 16_000], durationMs: 15 });
102
+ ```
103
+
104
+ ## The contract
105
+
106
+ - **Judge timing from `onsetTime`, not from when the verdict arrives.** A
107
+ verdict comes about the window plus 40 ms after the press (130 ms at the
108
+ default 90 ms); `onsetTime` is the press itself, typically within 5 ms after
109
+ calibration.
110
+ - **Not every press yields a verdict.** A missed onset (a soft note right after
111
+ a loud one, the lowest octave, a noisy room) yields nothing; a press whose new
112
+ energy is too weak against what was already ringing is dropped rather than
113
+ guessed. A press is also dropped if the next press cuts its analysis window
114
+ too short. A repeated miss simply makes the player play again.
115
+ - **`wrong` is a hint, not a fault.** It is precise (few false alarms) but
116
+ catches about two wrong notes in three; a wrong note on a partial of an
117
+ expected one (an octave, a twelfth) is rarely reported, and neither is a
118
+ missing octave doubling.
119
+ - **Only expected notes that were heard become free** for the next 1.5 s, so a
120
+ sustained chord does not count as wrong at the next press, and a wrong note
121
+ played again is reported again.
122
+ - **`source` is `"onset"` today.** More sources are planned (a re-check at the
123
+ due time, an early onset event); a `switch` over `source` must keep a
124
+ `default` branch.
125
+ - Durations are in milliseconds and sizes derive from the sampling rate; the
126
+ input is processed in 128-sample hops whatever the block length, so the
127
+ verdicts do not depend on how the input is cut.
128
+
129
+ ## Stream clock and rhythm practice
130
+
131
+ Time starts at the first sample fed to `process()` (or after `reset()`) and
132
+ advances only with samples you feed in. With continuous input, record the
133
+ AudioWorklet's `currentTime` at the first processed block as the origin.
134
+ Convert an AudioContext due time with `fromTime = dueTime - origin`, and map a
135
+ verdict back with `origin + verdict.onsetTime`. The verdict already has the
136
+ input latency subtracted; do not subtract it again.
137
+
138
+ A disconnected input usually has no channel to feed. Skipping those blocks
139
+ pauses the verifier clock, even if AudioContext time continues. Either feed
140
+ silence for the missing blocks (using a reused buffer), or `reset()` and take
141
+ a new origin when input resumes.
142
+
143
+ Send the next chord **before the earliest press you accept**. Set `fromTime`
144
+ to the start of that acceptance window, not the nominal beat, if an early
145
+ press should count for the next chord. For example, for a beat at stream time
146
+ 1 s that accepts presses up to 30 ms early, send
147
+ `verifier.expect(2, [62], { fromTime: 0.97 })` ahead of time. Without `fromTime`,
148
+ the change starts at the latency-corrected time of the next input frame.
149
+ A past `fromTime` within the onset confirmation window can still affect an
150
+ unconfirmed press, but cannot change a confirmed one. `expect()` rejects times
151
+ older than that window or new changes when the preallocated schedule is full.
152
+
153
+ ## Calibrating and loading tuning
154
+
155
+ Start noise calibration while the player keeps silent. Check for completion
156
+ immediately after feeding each block:
157
+
158
+ ```ts
159
+ verifier.calibrateNoise(); // call again to restart the measurement
160
+
161
+ function feedCalibrationBlock(block: Float32Array) {
162
+ const wasCalibrating = verifier.calibrating;
163
+ verifier.process(block);
164
+ if (wasCalibrating && !verifier.calibrating) {
165
+ return verifier.noiseProfile();
166
+ }
167
+ return null;
168
+ }
169
+ ```
170
+
171
+ During the latency count-in, `expect()` the note the player should play on
172
+ each beat, then collect verdict `onsetTime` values for `estimateInputLatency`.
173
+ Without an expectation, a correctly played note can appear in `wrong`.
174
+
175
+ To load a tuning file that overrides defaults, merge its parsed JSON and
176
+ validate the result before constructing the verifier. Extra fields are rejected.
177
+
178
+ ```ts
179
+ import {
180
+ DEFAULT_PIANO_VERIFIER_TUNING,
181
+ PianoChordVerifier,
182
+ validatePianoVerifierTuning,
183
+ } from "@ac-kit/media-piano-audio";
184
+
185
+ const json = await (await fetch("/piano-tuning.json")).json();
186
+ const tuning = { ...DEFAULT_PIANO_VERIFIER_TUNING, ...json };
187
+ validatePianoVerifierTuning(tuning);
188
+ const verifier = new PianoChordVerifier({ sampleRate: 48_000, tuning });
189
+ ```
190
+
191
+ ## In an AudioWorklet
192
+
193
+ The package has no Node.js API and no module-level side effect: bundle it into
194
+ the worklet module and construct the verifier **inside** the
195
+ `AudioWorkletProcessor` (construction takes about 5 ms and allocates the
196
+ templates, so do it in the constructor, not per block). `process` is
197
+ synchronous and, in steady state, allocates only for a verdict. The analysis of
198
+ a press is spread over about ten blocks: p99.9 under 0.1 ms, max under 0.15 ms on an otherwise
199
+ idle machine.
200
+
201
+ ```ts
202
+ class VerifierProcessor extends AudioWorkletProcessor {
203
+ verifier = new PianoChordVerifier({ sampleRate });
204
+ constructor() {
205
+ super();
206
+ this.port.onmessage = ({ data }) =>
207
+ this.verifier.expect(data.id, data.pitches, { fromTime: data.fromTime });
208
+ }
209
+ process(inputs: Float32Array[][]) {
210
+ const channel = inputs[0]?.[0];
211
+ if (!channel) return true;
212
+ for (const verdict of this.verifier.process(channel)) {
213
+ this.port.postMessage(verdict);
214
+ }
215
+ return true;
216
+ }
217
+ }
218
+ ```
219
+
220
+ ## What stays with the caller
221
+
222
+ - Choosing the expected chord as the score advances, and which verdict answers
223
+ which due note: pair the first verdict whose `onsetTime` is near the due time.
224
+ - Accumulating heard notes across presses in a wait mode, and the timing windows
225
+ of a rhythm mode (the measurement error is about 5–14 ms at p95).
226
+ - Running the calibrations: a second of silence (`calibrateNoise`), then a
227
+ count-in whose presses go to `estimateInputLatency`; storing the
228
+ `NoiseProfile` and the latency per device and piano.
229
+ - Microphone capture, channel selection, gain, and the `AudioWorklet` glue.
230
+
231
+ Portable: no Node.js built-ins.
232
+
233
+ See the
234
+ [generated API docs](https://anthochamp.pages.grenadine.io/node-essentials/api/media-piano-audio/)
235
+ for the full reference.
236
+
237
+ ## Further reading
238
+
239
+ - S. Böck, G. Widmer, _Maximum filter vibrato suppression for onset
240
+ detection_, DAFx 2013 (SuperFlux).
241
+ - S. Dixon, _Onset detection revisited_, DAFx 2006.
242
+ - D. D. Lee, H. S. Seung, _Algorithms for non-negative matrix factorization_,
243
+ NIPS 2001; T. Virtanen, _Monaural sound source separation by nonnegative
244
+ matrix factorization with temporal continuity and sparseness criteria_, IEEE
245
+ TASLP 15(3), 2007.
246
+ - F. Rigaud, B. David, L. Daudet, _A parametric model and estimation techniques
247
+ for the inharmonicity and tuning of the piano_, JASA 133(5), 2013.
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Throws a `RangeError` unless `pitch` is a finite MIDI pitch on the piano,
3
+ * 21–108.
4
+ */
5
+ export declare function assertPianoPitch(pitch: number): void;
6
+ //# sourceMappingURL=_assert-piano-pitch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_assert-piano-pitch.d.ts","sourceRoot":"","sources":["../../src/acoustics/_assert-piano-pitch.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CASpD"}
@@ -0,0 +1,12 @@
1
+ import { PIANO_PITCHES } from "@ac-kit/model-music";
2
+ /**
3
+ * Throws a `RangeError` unless `pitch` is a finite MIDI pitch on the piano,
4
+ * 21–108.
5
+ */
6
+ export function assertPianoPitch(pitch) {
7
+ if (!(pitch >= PIANO_PITCHES.lowest && pitch <= PIANO_PITCHES.highest) ||
8
+ !Number.isFinite(pitch)) {
9
+ throw new RangeError(`pitch must be within the piano's ${PIANO_PITCHES.lowest}–${PIANO_PITCHES.highest}, got ${pitch}`);
10
+ }
11
+ }
12
+ //# sourceMappingURL=_assert-piano-pitch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_assert-piano-pitch.js","sourceRoot":"","sources":["../../src/acoustics/_assert-piano-pitch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAa;IAC7C,IACC,CAAC,CAAC,KAAK,IAAI,aAAa,CAAC,MAAM,IAAI,KAAK,IAAI,aAAa,CAAC,OAAO,CAAC;QAClE,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EACtB,CAAC;QACF,MAAM,IAAI,UAAU,CACnB,oCAAoC,aAAa,CAAC,MAAM,IAAI,aAAa,CAAC,OAAO,SAAS,KAAK,EAAE,CACjG,CAAC;IACH,CAAC;AACF,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The inharmonicity coefficient `B` of a typical piano string at `pitch`: its
3
+ * partial `h` sounds at `h · f0 · √(1 + B·h²)`. A generic curve, lowest about
4
+ * C3 and rising towards both ends of the keyboard; a given instrument may
5
+ * differ by a factor of two or more.
6
+ *
7
+ * @param pitch - MIDI pitch within the piano's range, 21–108; fractional values
8
+ * are allowed.
9
+ * @throws {RangeError} If `pitch` is outside 21–108.
10
+ */
11
+ export declare function pianoInharmonicity(pitch: number): number;
12
+ /**
13
+ * The pitches (fractional MIDI) of the first `count` partials of a piano note,
14
+ * stretched by inharmonicity: partial `h` (from 1) is at `pitch + 12 · log₂(h ·
15
+ * √(1 + B·h²))`.
16
+ *
17
+ * @param pitch - MIDI pitch of the fundamental, 21–108.
18
+ * @param count - Number of partials, a positive integer.
19
+ * @param inharmonicity - `B`; default {@link pianoInharmonicity}`(pitch)`. 0
20
+ * gives the harmonic series.
21
+ * @param out - Written instead of allocating; must hold exactly `count` values.
22
+ * @returns `out`, or a new array.
23
+ * @throws {RangeError} On a pitch out of range, a bad count, a negative or
24
+ * non-finite `inharmonicity` or an `out` of the wrong length.
25
+ */
26
+ export declare function pianoPartialPitches(pitch: number, count: number, inharmonicity?: number, out?: Float64Array): Float64Array;
27
+ //# sourceMappingURL=piano-partials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"piano-partials.d.ts","sourceRoot":"","sources":["../../src/acoustics/piano-partials.ts"],"names":[],"mappings":"AAaA;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOxD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mBAAmB,CAClC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,aAAa,GAAE,MAAkC,EACjD,GAAG,CAAC,EAAE,YAAY,GAChB,YAAY,CAsBd"}
@@ -0,0 +1,60 @@
1
+ import { assertPianoPitch } from "./_assert-piano-pitch.js";
2
+ // The inharmonicity curve is two straight lines in log10(B) meeting at C3
3
+ // (pitch 48), where B is lowest: 1e-4 there, rising by 0.028 decades per
4
+ // semitone towards the treble (≈ 1.6e-2 at C8) and by 0.012 towards the bass
5
+ // (≈ 1.4e-3 at A0). Set by hand in the keylight microphone spike, shaped after
6
+ // the measurements of Young (1952) and Rigaud, David & Daudet (2013); it was not
7
+ // fitted to a recording. See CONTRIBUTING.md.
8
+ const INHARMONICITY_MINIMUM_PITCH_ = 48;
9
+ const INHARMONICITY_MINIMUM_LOG10_ = -4;
10
+ const INHARMONICITY_TREBLE_SLOPE_ = 0.028;
11
+ const INHARMONICITY_BASS_SLOPE_ = 0.012;
12
+ /**
13
+ * The inharmonicity coefficient `B` of a typical piano string at `pitch`: its
14
+ * partial `h` sounds at `h · f0 · √(1 + B·h²)`. A generic curve, lowest about
15
+ * C3 and rising towards both ends of the keyboard; a given instrument may
16
+ * differ by a factor of two or more.
17
+ *
18
+ * @param pitch - MIDI pitch within the piano's range, 21–108; fractional values
19
+ * are allowed.
20
+ * @throws {RangeError} If `pitch` is outside 21–108.
21
+ */
22
+ export function pianoInharmonicity(pitch) {
23
+ assertPianoPitch(pitch);
24
+ const distance = pitch - INHARMONICITY_MINIMUM_PITCH_;
25
+ const slope = distance >= 0 ? INHARMONICITY_TREBLE_SLOPE_ : -INHARMONICITY_BASS_SLOPE_;
26
+ return 10 ** (INHARMONICITY_MINIMUM_LOG10_ + distance * slope);
27
+ }
28
+ /**
29
+ * The pitches (fractional MIDI) of the first `count` partials of a piano note,
30
+ * stretched by inharmonicity: partial `h` (from 1) is at `pitch + 12 · log₂(h ·
31
+ * √(1 + B·h²))`.
32
+ *
33
+ * @param pitch - MIDI pitch of the fundamental, 21–108.
34
+ * @param count - Number of partials, a positive integer.
35
+ * @param inharmonicity - `B`; default {@link pianoInharmonicity}`(pitch)`. 0
36
+ * gives the harmonic series.
37
+ * @param out - Written instead of allocating; must hold exactly `count` values.
38
+ * @returns `out`, or a new array.
39
+ * @throws {RangeError} On a pitch out of range, a bad count, a negative or
40
+ * non-finite `inharmonicity` or an `out` of the wrong length.
41
+ */
42
+ export function pianoPartialPitches(pitch, count, inharmonicity = pianoInharmonicity(pitch), out) {
43
+ assertPianoPitch(pitch);
44
+ if (!Number.isSafeInteger(count) || count < 1) {
45
+ throw new RangeError(`count must be a positive integer, got ${count}`);
46
+ }
47
+ if (!(inharmonicity >= 0) || !Number.isFinite(inharmonicity)) {
48
+ throw new RangeError(`inharmonicity must be finite and non-negative, got ${inharmonicity}`);
49
+ }
50
+ if (out !== undefined && out.length !== count) {
51
+ throw new RangeError(`out must hold exactly ${count} values, got ${out.length}`);
52
+ }
53
+ const partials = out ?? new Float64Array(count);
54
+ for (let h = 1; h <= count; h++) {
55
+ partials[h - 1] =
56
+ pitch + 12 * Math.log2(h * Math.sqrt(1 + inharmonicity * h * h));
57
+ }
58
+ return partials;
59
+ }
60
+ //# sourceMappingURL=piano-partials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"piano-partials.js","sourceRoot":"","sources":["../../src/acoustics/piano-partials.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAE5D,0EAA0E;AAC1E,yEAAyE;AACzE,6EAA6E;AAC7E,+EAA+E;AAC/E,iFAAiF;AACjF,8CAA8C;AAC9C,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,4BAA4B,GAAG,CAAC,CAAC,CAAC;AACxC,MAAM,2BAA2B,GAAG,KAAK,CAAC;AAC1C,MAAM,yBAAyB,GAAG,KAAK,CAAC;AAExC;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAa;IAC/C,gBAAgB,CA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AAG,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,aAAa,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC"}
@@ -0,0 +1,41 @@
1
+ /** Options of {@link estimateInputLatency}. */
2
+ export interface EstimateInputLatencyOptions {
3
+ /**
4
+ * Furthest an onset may be from its due time to be paired with it, ms.
5
+ * Default 150.
6
+ */
7
+ readonly maxOffsetMs?: number;
8
+ /** Fewest pairs that give an estimate, a positive integer. Default 4. */
9
+ readonly minPairs?: number;
10
+ }
11
+ /** Result of {@link estimateInputLatency}. */
12
+ export interface InputLatencyEstimate {
13
+ /** Median of onset − due time, ms: the latency to set. */
14
+ readonly latencyMs: number;
15
+ /**
16
+ * Median absolute deviation of the offsets, ms: how steady the player and
17
+ * detector were.
18
+ */
19
+ readonly spreadMs: number;
20
+ /** Number of due times paired with an onset. */
21
+ readonly pairs: number;
22
+ }
23
+ /**
24
+ * The input latency of a device and piano, from a count-in: the player presses
25
+ * keys at `dueTimes` and the detector reports `onsetTimes`. Each due time is
26
+ * paired with the nearest onset within `maxOffsetMs` not already taken, and the
27
+ * latency is the median offset — robust to a few early or late presses and to
28
+ * spurious onsets.
29
+ *
30
+ * Both lists are in seconds on the same clock, in any order. Onsets from a
31
+ * {@link PianoChordVerifier} already have its `latencyMs` taken off, so the new
32
+ * latency is that value plus the result.
33
+ *
34
+ * Time complexity: O(d·o) for d due times and o onsets.
35
+ *
36
+ * @returns The estimate, or `null` with fewer than `minPairs` pairs.
37
+ * @throws {RangeError} On a non-finite time, a `maxOffsetMs` that is not
38
+ * positive or a `minPairs` that is not a positive integer.
39
+ */
40
+ export declare function estimateInputLatency(dueTimes: readonly number[], onsetTimes: readonly number[], options?: EstimateInputLatencyOptions): InputLatencyEstimate | null;
41
+ //# sourceMappingURL=estimate-input-latency.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"estimate-input-latency.d.ts","sourceRoot":"","sources":["../../src/calibrate/estimate-input-latency.ts"],"names":[],"mappings":"AAEA,+CAA+C;AAC/C,MAAM,WAAW,2BAA2B;IAC3C;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,yEAAyE;IACzE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,8CAA8C;AAC9C,MAAM,WAAW,oBAAoB;IACpC,0DAA0D;IAC1D,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,gDAAgD;IAChD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,oBAAoB,CACnC,QAAQ,EAAE,SAAS,MAAM,EAAE,EAC3B,UAAU,EAAE,SAAS,MAAM,EAAE,EAC7B,OAAO,GAAE,2BAAgC,GACvC,oBAAoB,GAAG,IAAI,CAyC7B"}
@@ -0,0 +1,58 @@
1
+ import { median, medianAbsoluteDeviation } from "@ac-kit/math-stats";
2
+ /**
3
+ * The input latency of a device and piano, from a count-in: the player presses
4
+ * keys at `dueTimes` and the detector reports `onsetTimes`. Each due time is
5
+ * paired with the nearest onset within `maxOffsetMs` not already taken, and the
6
+ * latency is the median offset — robust to a few early or late presses and to
7
+ * spurious onsets.
8
+ *
9
+ * Both lists are in seconds on the same clock, in any order. Onsets from a
10
+ * {@link PianoChordVerifier} already have its `latencyMs` taken off, so the new
11
+ * latency is that value plus the result.
12
+ *
13
+ * Time complexity: O(d·o) for d due times and o onsets.
14
+ *
15
+ * @returns The estimate, or `null` with fewer than `minPairs` pairs.
16
+ * @throws {RangeError} On a non-finite time, a `maxOffsetMs` that is not
17
+ * positive or a `minPairs` that is not a positive integer.
18
+ */
19
+ export function estimateInputLatency(dueTimes, onsetTimes, options = {}) {
20
+ const { maxOffsetMs = 150, minPairs = 4 } = options;
21
+ if (!(maxOffsetMs > 0) || !Number.isFinite(maxOffsetMs)) {
22
+ throw new RangeError(`maxOffsetMs must be positive, got ${maxOffsetMs}`);
23
+ }
24
+ if (!Number.isSafeInteger(minPairs) || minPairs < 1) {
25
+ throw new RangeError(`minPairs must be a positive integer, got ${minPairs}`);
26
+ }
27
+ for (const time of [...dueTimes, ...onsetTimes]) {
28
+ if (!Number.isFinite(time)) {
29
+ throw new RangeError(`times must be finite, got ${time}`);
30
+ }
31
+ }
32
+ const taken = new Uint8Array(onsetTimes.length);
33
+ const offsets = [];
34
+ for (const due of dueTimes) {
35
+ let best = -1;
36
+ let bestDistance = maxOffsetMs / 1000;
37
+ for (let index = 0; index < onsetTimes.length; index++) {
38
+ const distance = Math.abs(onsetTimes[index] - due);
39
+ if (taken[index] === 0 && distance <= bestDistance) {
40
+ best = index;
41
+ bestDistance = distance;
42
+ }
43
+ }
44
+ if (best >= 0) {
45
+ taken[best] = 1;
46
+ offsets.push((onsetTimes[best] - due) * 1000);
47
+ }
48
+ }
49
+ if (offsets.length < minPairs)
50
+ return null;
51
+ const latencyMs = median(offsets);
52
+ return {
53
+ latencyMs,
54
+ spreadMs: medianAbsoluteDeviation(offsets, latencyMs),
55
+ pairs: offsets.length,
56
+ };
57
+ }
58
+ //# sourceMappingURL=estimate-input-latency.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"estimate-input-latency.js","sourceRoot":"","sources":["../../src/calibrate/estimate-input-latency.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AA0BrE;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,oBAAoB,CACnC,QAA2B,EAC3B,UAA6B,EAC7B,OAAO,GAAgC,EAAE;IAEzC,MAAM,EAAE,WAAW,GAAG,GAAG,EAAE,QAAQ,GAAG,CAAC,EAAE,GAAG,OAAO,CAAC;IACpD,IAAI,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC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GAAG,CAAC,CAAC;YAChB,OAAO,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,IAAI,CAAE,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;QAChD,CAAC;IACF,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,GAAG,QAAQ;QAAE,OAAO,IAAI,CAAC;IAE3C,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IAClC,OAAO;QACN,SAAS;QACT,QAAQ,EAAE,uBAAuB,CAAC,OAAO,EAAE,SAAS,CAAC;QACrD,KAAK,EAAE,OAAO,CAAC,MAAM;KACrB,CAAC;AACH,CAAC"}
@@ -0,0 +1,8 @@
1
+ export * from "./acoustics/piano-partials.js";
2
+ export * from "./calibrate/estimate-input-latency.js";
3
+ export * from "./verify/piano-chord-verifier.js";
4
+ export * from "./verify/tuning.js";
5
+ export * from "./verify/types.js";
6
+ export * from "./synthesize/synthesize-piano.js";
7
+ export * from "./synthesize/synthesize-tick.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,uCAAuC,CAAC;AACtD,cAAc,kCAAkC,CAAC;AACjD,cAAc,oBAAoB,CAAC;AACnC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kCAAkC,CAAC;AACjD,cAAc,iCAAiC,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export * from "./acoustics/piano-partials.js";
2
+ export * from "./calibrate/estimate-input-latency.js";
3
+ export * from "./verify/piano-chord-verifier.js";
4
+ export * from "./verify/tuning.js";
5
+ export * from "./verify/types.js";
6
+ export * from "./synthesize/synthesize-piano.js";
7
+ export * from "./synthesize/synthesize-tick.js";
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,uCAAuC,CAAC;AACtD,cAAc,kCAAkC,CAAC;AACjD,cAAc,oBAAoB,CAAC;AACnC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kCAAkC,CAAC;AACjD,cAAc,iCAAiC,CAAC"}