@ac-kit/media-piano-audio 0.0.0-stage → 0.1.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 (36) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/LICENSE +28 -0
  3. package/README.md +206 -2
  4. package/dist/acoustics/piano-partials.d.ts +27 -0
  5. package/dist/acoustics/piano-partials.d.ts.map +1 -0
  6. package/dist/acoustics/piano-partials.js +66 -0
  7. package/dist/acoustics/piano-partials.js.map +1 -0
  8. package/dist/calibrate/estimate-input-latency.d.ts +41 -0
  9. package/dist/calibrate/estimate-input-latency.d.ts.map +1 -0
  10. package/dist/calibrate/estimate-input-latency.js +58 -0
  11. package/dist/calibrate/estimate-input-latency.js.map +1 -0
  12. package/dist/index.d.ts +6 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +6 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/verify/_onset-detector.d.ts +58 -0
  17. package/dist/verify/_onset-detector.d.ts.map +1 -0
  18. package/dist/verify/_onset-detector.js +206 -0
  19. package/dist/verify/_onset-detector.js.map +1 -0
  20. package/dist/verify/_templates.d.ts +37 -0
  21. package/dist/verify/_templates.d.ts.map +1 -0
  22. package/dist/verify/_templates.js +113 -0
  23. package/dist/verify/_templates.js.map +1 -0
  24. package/dist/verify/piano-chord-verifier.d.ts +204 -0
  25. package/dist/verify/piano-chord-verifier.d.ts.map +1 -0
  26. package/dist/verify/piano-chord-verifier.js +938 -0
  27. package/dist/verify/piano-chord-verifier.js.map +1 -0
  28. package/dist/verify/tuning.d.ts +126 -0
  29. package/dist/verify/tuning.d.ts.map +1 -0
  30. package/dist/verify/tuning.js +133 -0
  31. package/dist/verify/tuning.js.map +1 -0
  32. package/dist/verify/types.d.ts +74 -0
  33. package/dist/verify/types.d.ts.map +1 -0
  34. package/dist/verify/types.js +2 -0
  35. package/dist/verify/types.js.map +1 -0
  36. package/package.json +70 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,42 @@
1
+ # @ac-kit/media-piano-audio
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5152230: New package: `PianoChordVerifier` checks microphone input against an expected
8
+ piano chord and reports heard, missing and wrong notes with latency-corrected
9
+ onset times. Use `expect(id, pitches, { fromTime })` to schedule a chord on
10
+ that same clock. The verifier accepts arbitrary input block lengths, runs in an
11
+ AudioWorklet and can calibrate background noise into a structured-cloneable
12
+ `NoiseProfile`. Use `validatePianoVerifierTuning` to check a tuning loaded from
13
+ JSON against `PianoVerifierTuning`. The package also exports
14
+ `estimateInputLatency`, `pianoInharmonicity` and `pianoPartialPitches`.
15
+
16
+ ### Patch Changes
17
+
18
+ - Updated dependencies [2a0fe74]
19
+ - Updated dependencies [5152230]
20
+ - Updated dependencies [2a0fe74]
21
+ - Updated dependencies [5152230]
22
+ - Updated dependencies [5152230]
23
+ - Updated dependencies [2a0fe74]
24
+ - Updated dependencies [2a0fe74]
25
+ - Updated dependencies [5152230]
26
+ - Updated dependencies [5152230]
27
+ - Updated dependencies [5152230]
28
+ - Updated dependencies [5152230]
29
+ - Updated dependencies [5152230]
30
+ - Updated dependencies [5152230]
31
+ - Updated dependencies [5152230]
32
+ - Updated dependencies [5152230]
33
+ - Updated dependencies [5152230]
34
+ - Updated dependencies [5152230]
35
+ - Updated dependencies [5152230]
36
+ - Updated dependencies [5152230]
37
+ - Updated dependencies [5152230]
38
+ - @ac-kit/core@0.10.0
39
+ - @ac-kit/math-linear@0.2.0
40
+ - @ac-kit/math-signal@0.2.0
41
+ - @ac-kit/math-stats@0.3.0
42
+ - @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,207 @@
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.
7
+
8
+ ```ts
9
+ import { PianoChordVerifier } from "@ac-kit/media-piano-audio";
10
+
11
+ const verifier = new PianoChordVerifier({ sampleRate: 48_000 });
12
+ verifier.calibrateNoise(1000); // the player keeps silent for a second
13
+ verifier.expect(1, [60, 64, 67]); // C major is due
14
+
15
+ // For each block of microphone samples, as an AudioWorklet delivers them:
16
+ for (const verdict of verifier.process(block)) {
17
+ verdict.expectationId; // 1
18
+ verdict.heard; // [60, 64, 67]
19
+ verdict.missing; // []
20
+ verdict.wrong; // []
21
+ verdict.onsetTime; // seconds since the stream started, latency taken off
22
+ }
23
+ ```
24
+
25
+ ## What it exposes
26
+
27
+ - `PianoChordVerifier` — the streaming verifier.
28
+ - `new PianoChordVerifier({ sampleRate, windowMs?, latencyMs?, referenceHz?, tuning?, noiseProfile? })`:
29
+ `sampleRate` 22 050–96 000 Hz; `windowMs` 30–120, default 90, the length
30
+ of audio compared before and after a press (longer catches more wrong and
31
+ missing notes and answers later); `latencyMs` the finite, non-negative input latency taken off
32
+ every onset time; `referenceHz` the frequency of A4, 392–494, default 440.
33
+ - `process(block)` takes a `Float32Array` of any length and returns the
34
+ verdicts decided during it — a shared frozen empty array when there are
35
+ none.
36
+ - `expect(id, pitches, { fromTime }?)` schedules a chord: MIDI keys 21–108,
37
+ `[]` for a rest. The latest change at or before the corrected `onsetTime`
38
+ wins. Calls for the same time replace one another.
39
+ - `calibrateNoise(durationMs = 1000)`, `calibrating`, `noiseProfile()`:
40
+ measure background noise while the player keeps silent. A second
41
+ `calibrateNoise()` call starts the measurement over. Poll `calibrating`
42
+ after `process()` to see when it ends.
43
+ - `latencyMs` can be set at any time but must be finite and non-negative.
44
+ Set it before scheduling rhythm practice: changes affect unconfirmed
45
+ onsets and do not bring back discarded expectation history. `reset()`
46
+ restarts time at 0 and keeps the noise profile, latency and current
47
+ expectation, but discards future changes.
48
+ - `ChordVerdict` — `{ source, expectationId, expected, heard, missing, wrong,
49
+ onsetTime, onsetFrame, decidedFrame }`.
50
+ - `NoiseProfile` — `{ version, sampleRate, windowMs, grid, bandNoise, newEnergyNoise,
51
+ levelDb }`, a plain object `structuredClone` and `postMessage` carry. A
52
+ profile with a different sample rate, analysis window or frequency grid is
53
+ refused with a `RangeError`. Of the tuning fields, only those that change
54
+ the frequency grid invalidate a stored profile.
55
+ - `estimateInputLatency(dueTimes, onsetTimes, { maxOffsetMs, minPairs })` — the
56
+ median offset between the presses of a count-in and the onsets detected, or
57
+ `null` with too few pairs.
58
+ - `PianoVerifierTuning`, `DEFAULT_PIANO_VERIFIER_TUNING`,
59
+ `validatePianoVerifierTuning` — every constant of the algorithm as versioned
60
+ JSON data, so a tuning for another piano or microphone ships as a file.
61
+ - `pianoInharmonicity(pitch)`, `pianoPartialPitches(pitch, count,
62
+ inharmonicity?, out?)` — where a piano string's partials sound.
63
+
64
+ ## The contract
65
+
66
+ - **Judge timing from `onsetTime`, not from when the verdict arrives.** A
67
+ verdict comes about the window plus 40 ms after the press (130 ms at the
68
+ default 90 ms); `onsetTime` is the press itself, typically within 5 ms after
69
+ calibration.
70
+ - **Not every press yields a verdict.** A missed onset (a soft note right after
71
+ a loud one, the lowest octave, a noisy room) yields nothing; a press whose new
72
+ energy is too weak against what was already ringing is dropped rather than
73
+ guessed. A press is also dropped if the next press cuts its analysis window
74
+ too short. A repeated miss simply makes the player play again.
75
+ - **`wrong` is a hint, not a fault.** It is precise (few false alarms) but
76
+ catches about two wrong notes in three; a wrong note on a partial of an
77
+ expected one (an octave, a twelfth) is rarely reported, and neither is a
78
+ missing octave doubling.
79
+ - **Only expected notes that were heard become free** for the next 1.5 s, so a
80
+ sustained chord does not count as wrong at the next press, and a wrong note
81
+ played again is reported again.
82
+ - **`source` is `"onset"` today.** More sources are planned (a re-check at the
83
+ due time, an early onset event); a `switch` over `source` must keep a
84
+ `default` branch.
85
+ - Durations are in milliseconds and sizes derive from the sampling rate; the
86
+ input is processed in 128-sample hops whatever the block length, so the
87
+ verdicts do not depend on how the input is cut.
88
+
89
+ ## Stream clock and rhythm practice
90
+
91
+ Time starts at the first sample fed to `process()` (or after `reset()`) and
92
+ advances only with samples you feed in. With continuous input, record the
93
+ AudioWorklet's `currentTime` at the first processed block as the origin.
94
+ Convert an AudioContext due time with `fromTime = dueTime - origin`, and map a
95
+ verdict back with `origin + verdict.onsetTime`. The verdict already has the
96
+ input latency subtracted; do not subtract it again.
97
+
98
+ A disconnected input usually has no channel to feed. Skipping those blocks
99
+ pauses the verifier clock, even if AudioContext time continues. Either feed
100
+ silence for the missing blocks (using a reused buffer), or `reset()` and take
101
+ a new origin when input resumes.
102
+
103
+ Send the next chord **before the earliest press you accept**. Set `fromTime`
104
+ to the start of that acceptance window, not the nominal beat, if an early
105
+ press should count for the next chord. For example, for a beat at stream time
106
+ 1 s that accepts presses up to 30 ms early, send
107
+ `verifier.expect(2, [62], { fromTime: 0.97 })` ahead of time. Without `fromTime`,
108
+ the change starts at the latency-corrected time of the next input frame.
109
+ A past `fromTime` within the onset confirmation window can still affect an
110
+ unconfirmed press, but cannot change a confirmed one. `expect()` rejects times
111
+ older than that window or new changes when the preallocated schedule is full.
112
+
113
+ ## Calibrating and loading tuning
114
+
115
+ Start noise calibration while the player keeps silent. Check for completion
116
+ immediately after feeding each block:
117
+
118
+ ```ts
119
+ verifier.calibrateNoise(); // call again to restart the measurement
120
+
121
+ function feedCalibrationBlock(block: Float32Array) {
122
+ const wasCalibrating = verifier.calibrating;
123
+ verifier.process(block);
124
+ if (wasCalibrating && !verifier.calibrating) {
125
+ return verifier.noiseProfile();
126
+ }
127
+ return null;
128
+ }
129
+ ```
130
+
131
+ During the latency count-in, `expect()` the note the player should play on
132
+ each beat, then collect verdict `onsetTime` values for `estimateInputLatency`.
133
+ Without an expectation, a correctly played note can appear in `wrong`.
134
+
135
+ To load a tuning file that overrides defaults, merge its parsed JSON and
136
+ validate the result before constructing the verifier. Extra fields are rejected.
137
+
138
+ ```ts
139
+ import {
140
+ DEFAULT_PIANO_VERIFIER_TUNING,
141
+ PianoChordVerifier,
142
+ validatePianoVerifierTuning,
143
+ } from "@ac-kit/media-piano-audio";
144
+
145
+ const json = await (await fetch("/piano-tuning.json")).json();
146
+ const tuning = { ...DEFAULT_PIANO_VERIFIER_TUNING, ...json };
147
+ validatePianoVerifierTuning(tuning);
148
+ const verifier = new PianoChordVerifier({ sampleRate: 48_000, tuning });
149
+ ```
150
+
151
+ ## In an AudioWorklet
152
+
153
+ The package has no Node.js API and no module-level side effect: bundle it into
154
+ the worklet module and construct the verifier **inside** the
155
+ `AudioWorkletProcessor` (construction takes about 5 ms and allocates the
156
+ templates, so do it in the constructor, not per block). `process` is
157
+ synchronous and, in steady state, allocates only for a verdict. The analysis of
158
+ a press is spread over about ten blocks: p99.9 under 0.1 ms, max under 0.15 ms on an otherwise
159
+ idle machine.
160
+
161
+ ```ts
162
+ class VerifierProcessor extends AudioWorkletProcessor {
163
+ verifier = new PianoChordVerifier({ sampleRate });
164
+ constructor() {
165
+ super();
166
+ this.port.onmessage = ({ data }) =>
167
+ this.verifier.expect(data.id, data.pitches, { fromTime: data.fromTime });
168
+ }
169
+ process(inputs: Float32Array[][]) {
170
+ const channel = inputs[0]?.[0];
171
+ if (!channel) return true;
172
+ for (const verdict of this.verifier.process(channel)) {
173
+ this.port.postMessage(verdict);
174
+ }
175
+ return true;
176
+ }
177
+ }
178
+ ```
179
+
180
+ ## What stays with the caller
181
+
182
+ - Choosing the expected chord as the score advances, and which verdict answers
183
+ which due note: pair the first verdict whose `onsetTime` is near the due time.
184
+ - Accumulating heard notes across presses in a wait mode, and the timing windows
185
+ of a rhythm mode (the measurement error is about 5–14 ms at p95).
186
+ - Running the calibrations: a second of silence (`calibrateNoise`), then a
187
+ count-in whose presses go to `estimateInputLatency`; storing the
188
+ `NoiseProfile` and the latency per device and piano.
189
+ - Microphone capture, channel selection, gain, and the `AudioWorklet` glue.
190
+
191
+ Portable: no Node.js built-ins.
192
+
193
+ See the
194
+ [generated API docs](https://anthochamp.pages.grenadine.io/node-essentials/api/media-piano-audio/)
195
+ for the full reference.
196
+
197
+ ## Further reading
198
+
199
+ - S. Böck, G. Widmer, _Maximum filter vibrato suppression for onset
200
+ detection_, DAFx 2013 (SuperFlux).
201
+ - S. Dixon, _Onset detection revisited_, DAFx 2006.
202
+ - D. D. Lee, H. S. Seung, _Algorithms for non-negative matrix factorization_,
203
+ NIPS 2001; T. Virtanen, _Monaural sound source separation by nonnegative
204
+ matrix factorization with temporal continuity and sparseness criteria_, IEEE
205
+ TASLP 15(3), 2007.
206
+ - F. Rigaud, B. David, L. Daudet, _A parametric model and estimation techniques
207
+ for the inharmonicity and tuning of the piano_, JASA 133(5), 2013.
@@ -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":"AAwBA;;;;;;;;;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,66 @@
1
+ import { PIANO_PITCHES } from "@ac-kit/model-music";
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
+ function assertPianoPitch_(pitch) {
13
+ if (!(pitch >= PIANO_PITCHES.lowest && pitch <= PIANO_PITCHES.highest) ||
14
+ !Number.isFinite(pitch)) {
15
+ throw new RangeError(`pitch must be within the piano's ${PIANO_PITCHES.lowest}–${PIANO_PITCHES.highest}, got ${pitch}`);
16
+ }
17
+ }
18
+ /**
19
+ * The inharmonicity coefficient `B` of a typical piano string at `pitch`: its
20
+ * partial `h` sounds at `h · f0 · √(1 + B·h²)`. A generic curve, lowest about
21
+ * C3 and rising towards both ends of the keyboard; a given instrument may
22
+ * differ by a factor of two or more.
23
+ *
24
+ * @param pitch - MIDI pitch within the piano's range, 21–108; fractional values
25
+ * are allowed.
26
+ * @throws {RangeError} If `pitch` is outside 21–108.
27
+ */
28
+ export function pianoInharmonicity(pitch) {
29
+ assertPianoPitch_(pitch);
30
+ const distance = pitch - INHARMONICITY_MINIMUM_PITCH_;
31
+ const slope = distance >= 0 ? INHARMONICITY_TREBLE_SLOPE_ : -INHARMONICITY_BASS_SLOPE_;
32
+ return 10 ** (INHARMONICITY_MINIMUM_LOG10_ + distance * slope);
33
+ }
34
+ /**
35
+ * The pitches (fractional MIDI) of the first `count` partials of a piano note,
36
+ * stretched by inharmonicity: partial `h` (from 1) is at `pitch + 12 · log₂(h ·
37
+ * √(1 + B·h²))`.
38
+ *
39
+ * @param pitch - MIDI pitch of the fundamental, 21–108.
40
+ * @param count - Number of partials, a positive integer.
41
+ * @param inharmonicity - `B`; default {@link pianoInharmonicity}`(pitch)`. 0
42
+ * gives the harmonic series.
43
+ * @param out - Written instead of allocating; must hold exactly `count` values.
44
+ * @returns `out`, or a new array.
45
+ * @throws {RangeError} On a pitch out of range, a bad count, a negative or
46
+ * non-finite `inharmonicity` or an `out` of the wrong length.
47
+ */
48
+ export function pianoPartialPitches(pitch, count, inharmonicity = pianoInharmonicity(pitch), out) {
49
+ assertPianoPitch_(pitch);
50
+ if (!Number.isSafeInteger(count) || count < 1) {
51
+ throw new RangeError(`count must be a positive integer, got ${count}`);
52
+ }
53
+ if (!(inharmonicity >= 0) || !Number.isFinite(inharmonicity)) {
54
+ throw new RangeError(`inharmonicity must be finite and non-negative, got ${inharmonicity}`);
55
+ }
56
+ if (out !== undefined && out.length !== count) {
57
+ throw new RangeError(`out must hold exactly ${count} values, got ${out.length}`);
58
+ }
59
+ const partials = out ?? new Float64Array(count);
60
+ for (let h = 1; h <= count; h++) {
61
+ partials[h - 1] =
62
+ pitch + 12 * Math.log2(h * Math.sqrt(1 + inharmonicity * h * h));
63
+ }
64
+ return partials;
65
+ }
66
+ //# 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,aAAa,EA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,yCAAyC,KAAK,EAAE,CAAC,CAAC;IACxE,CAAC;IACD,IAAI,CAAC,CAAC,aAAa,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;QAC9D,MAAM,IAAI,UAAU,CACnB,sDAAsD,aAAa,EAAE,CACrE,CAAC;IACH,CAAC;IACD,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,CAAC,MAAM,KAAK,KAAK,EAAE,CAAC;QAC/C,MAAM,IAAI,UAAU,CACnB,yBAAyB,KAAK,gBAAgB,GAAG,CAAC,MAAM,EAAE,CAC1D,CAAC;IACH,CAAC;IAED,MAAM,QAAQ,GAAG,GAAG,IAAI,IAAI,YAAY,CAAC,KAAK,CAAC,CAAC;IAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;QACjC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC;YACd,KAAK,GAAG,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,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,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;QACzD,MAAM,IAAI,UAAU,CAAC,qCAAqC,WAAW,EAAE,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,IAAI,QAAQ,GAAG,CAAC,EAAE,CAAC;QACrD,MAAM,IAAI,UAAU,CACnB,4CAA4C,QAAQ,EAAE,CACtD,CAAC;IACH,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,CAAC,GAAG,QAAQ,EAAE,GAAG,UAAU,CAAC,EAAE,CAAC;QACjD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5B,MAAM,IAAI,UAAU,CAAC,6BAA6B,IAAI,EAAE,CAAC,CAAC;QAC3D,CAAC;IACF,CAAC;IAED,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAChD,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,KAAK,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC5B,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC;QACd,IAAI,YAAY,GAAG,WAAW,GAAG,IAAI,CAAC;QACtC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;YACxD,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,CAAE,GAAG,GAAG,CAAC,CAAC;YACpD,IAAI,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,QAAQ,IAAI,YAAY,EAAE,CAAC;gBACpD,IAAI,GAAG,KAAK,CAAC;gBACb,YAAY,GAAG,QAAQ,CAAC;YACzB,CAAC;QACF,CAAC;QACD,IAAI,IAAI,IAAI,CAAC,EAAE,CAAC;YACf,KAAK,CAAC,IAAI,CAAC,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,6 @@
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
+ //# 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"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
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
+ //# 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"}
@@ -0,0 +1,58 @@
1
+ import type { PianoVerifierTuning } from "./tuning.js";
2
+ /** Samples between two frames: the AudioWorklet render quantum. */
3
+ export declare const HOP = 128;
4
+ /** Frames of `HOP` samples nearest to `ms`, at least `minimum`. */
5
+ export declare function framesOf(ms: number, sampleRate: number, minimum: number): number;
6
+ /**
7
+ * Streaming onset detection, one frame per hop: log-compressed, noise-relative
8
+ * band magnitudes, SuperFlux over all bands and over the expected notes' bands,
9
+ * adaptive-threshold peak picking, then the rise, minimum-interval and
10
+ * replacement rules.
11
+ */
12
+ export declare class OnsetDetector {
13
+ readonly frameSize: number;
14
+ /** Samples from the reported onset (frame centre) to its confirmation. */
15
+ readonly confirmationDelaySamples: number;
16
+ readonly bandCount: number;
17
+ /** Highest frequency of the onset bands, Hz, after the Nyquist clamp. */
18
+ readonly maxFrequency: number;
19
+ /** Band magnitudes of the latest frame, before compression. */
20
+ readonly bands: Float64Array;
21
+ private readonly sampleRate_;
22
+ private readonly tuning_;
23
+ private readonly fft_;
24
+ private readonly window_;
25
+ private readonly input_;
26
+ private readonly spectrum_;
27
+ private readonly magnitudes_;
28
+ private readonly map_;
29
+ private readonly history_;
30
+ private readonly picker_;
31
+ private readonly fluxLag_;
32
+ private readonly lookahead_;
33
+ private readonly positions_;
34
+ private readonly energies_;
35
+ private readonly novelties_;
36
+ private readonly fluxes_;
37
+ private readonly minInterOnset_;
38
+ private readonly merge_;
39
+ private expectedBands_;
40
+ private frame_;
41
+ private lastOnset_;
42
+ private lastNovelty_;
43
+ /** Whether the latest onset replaces its precursor rather than adding one. */
44
+ replaced: boolean;
45
+ constructor(sampleRate: number, tuning: PianoVerifierTuning);
46
+ /** Magnitude of a full-scale sine in one band: the unit of `bandNoise`. */
47
+ get fullScale(): number;
48
+ /** The bands of the first `expectedPartials` partials of `pitches`. */
49
+ expectedBands(pitches: readonly number[], referenceHz: number): Int32Array;
50
+ setExpectedBands(bands: Int32Array): void;
51
+ /**
52
+ * Analyses the frame ending at `position` and returns the sample position of
53
+ * a confirmed onset, or −1.
54
+ */
55
+ analyse(ring: Float32Array, mask: number, position: number, bandNoise: Float64Array): number;
56
+ reset(): void;
57
+ }
58
+ //# sourceMappingURL=_onset-detector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_onset-detector.d.ts","sourceRoot":"","sources":["../../src/verify/_onset-detector.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEvD,mEAAmE;AACnE,eAAO,MAAM,GAAG,MAAM,CAAC;AAUvB,mEAAmE;AACnE,wBAAgB,QAAQ,CACvB,EAAE,EAAE,MAAM,EACV,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,GACb,MAAM,CAER;AAED;;;;;GAKG;AACH,qBAAa,aAAa;IACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,0EAA0E;IAC1E,QAAQ,CAA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