@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.
- package/CHANGELOG.md +42 -0
- package/LICENSE +28 -0
- package/README.md +206 -2
- package/dist/acoustics/piano-partials.d.ts +27 -0
- package/dist/acoustics/piano-partials.d.ts.map +1 -0
- package/dist/acoustics/piano-partials.js +66 -0
- package/dist/acoustics/piano-partials.js.map +1 -0
- package/dist/calibrate/estimate-input-latency.d.ts +41 -0
- package/dist/calibrate/estimate-input-latency.d.ts.map +1 -0
- package/dist/calibrate/estimate-input-latency.js +58 -0
- package/dist/calibrate/estimate-input-latency.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/verify/_onset-detector.d.ts +58 -0
- package/dist/verify/_onset-detector.d.ts.map +1 -0
- package/dist/verify/_onset-detector.js +206 -0
- package/dist/verify/_onset-detector.js.map +1 -0
- package/dist/verify/_templates.d.ts +37 -0
- package/dist/verify/_templates.d.ts.map +1 -0
- package/dist/verify/_templates.js +113 -0
- package/dist/verify/_templates.js.map +1 -0
- package/dist/verify/piano-chord-verifier.d.ts +204 -0
- package/dist/verify/piano-chord-verifier.d.ts.map +1 -0
- package/dist/verify/piano-chord-verifier.js +938 -0
- package/dist/verify/piano-chord-verifier.js.map +1 -0
- package/dist/verify/tuning.d.ts +126 -0
- package/dist/verify/tuning.d.ts.map +1 -0
- package/dist/verify/tuning.js +133 -0
- package/dist/verify/tuning.js.map +1 -0
- package/dist/verify/types.d.ts +74 -0
- package/dist/verify/types.d.ts.map +1 -0
- package/dist/verify/types.js +2 -0
- package/dist/verify/types.js.map +1 -0
- package/package.json +70 -3
|
@@ -0,0 +1,938 @@
|
|
|
1
|
+
import { KlActivations } from "@ac-kit/math-linear";
|
|
2
|
+
import { createLogFrequencyMap, createRealFft, hannWindowInto, magnitudeSpectrumInto, } from "@ac-kit/math-signal";
|
|
3
|
+
import { frequencyPitch, pitchFrequency, PIANO_PITCHES, } from "@ac-kit/model-music";
|
|
4
|
+
import { HOP, OnsetDetector } from "./_onset-detector.js";
|
|
5
|
+
import { bandTemplateCount, buildTemplates, KEY_COUNT, keyPartials, } from "./_templates.js";
|
|
6
|
+
import { DEFAULT_PIANO_VERIFIER_TUNING, validatePianoVerifierTuning, } from "./tuning.js";
|
|
7
|
+
const EMPTY_ = Object.freeze([]);
|
|
8
|
+
const NO_PITCHES_ = Object.freeze([]);
|
|
9
|
+
const NO_BANDS_ = new Int32Array(0);
|
|
10
|
+
// Drop cut-short windows below this minimum (256 samples at 48 kHz in the
|
|
11
|
+
// spike). A cut window ends this long before the onset that cut it.
|
|
12
|
+
const MIN_ANALYSIS_MS_ = 5.3;
|
|
13
|
+
const CUT_MARGIN_MS_ = 2;
|
|
14
|
+
// Template sets exist for every window length in steps of this many ms from
|
|
15
|
+
// the shortest, so a window cut short by the next onset finds its own.
|
|
16
|
+
const TEMPLATE_STEP_MS_ = 5;
|
|
17
|
+
const SHORTEST_TEMPLATE_MS_ = 10;
|
|
18
|
+
// Floors keeping ratios defined.
|
|
19
|
+
const RATIO_FLOOR_ = 1e-12;
|
|
20
|
+
const LEVEL_FLOOR_DB_ = -200;
|
|
21
|
+
// Decision requests waiting while another is analysed; onsets are at least
|
|
22
|
+
// `minInterOnsetMs` apart and an analysis takes a few hops, so one is the
|
|
23
|
+
// usual depth.
|
|
24
|
+
const QUEUE_CAPACITY_ = 4;
|
|
25
|
+
// More band templates than this would only slow the activations down.
|
|
26
|
+
const MAX_BAND_TEMPLATES_ = 256;
|
|
27
|
+
// Phases of the analysis job, one per hop.
|
|
28
|
+
const IDLE_ = 0;
|
|
29
|
+
const AFTER_SPECTRUM_ = 1;
|
|
30
|
+
const BEFORE_SPECTRUM_ = 2;
|
|
31
|
+
const ITERATE_ = 3;
|
|
32
|
+
function newRequest_() {
|
|
33
|
+
return {
|
|
34
|
+
id: null,
|
|
35
|
+
expected: NO_PITCHES_,
|
|
36
|
+
onset: 0,
|
|
37
|
+
latencyMs: 0,
|
|
38
|
+
anchor: 0,
|
|
39
|
+
end: 0,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function checkRange_(name, value, minimum, maximum) {
|
|
43
|
+
if (!(value >= minimum && value <= maximum)) {
|
|
44
|
+
throw new RangeError(`${name} must be in [${minimum}, ${maximum}], got ${value}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Score-informed chord verification from a microphone: tell it which chord is
|
|
49
|
+
* due, feed it the audio, and it reports, for each key press it detects, which
|
|
50
|
+
* expected notes it heard, which it did not, and which other notes sounded. It
|
|
51
|
+
* verifies; it does not transcribe.
|
|
52
|
+
*
|
|
53
|
+
* Streaming and synchronous, for an `AudioWorkletProcessor`: {@link process}
|
|
54
|
+
* takes blocks of any length and works in 128-sample hops. In steady state it
|
|
55
|
+
* creates objects only for a verdict, and the analysis of a press is spread
|
|
56
|
+
* over several hops so no block carries all of it.
|
|
57
|
+
*
|
|
58
|
+
* Per press: an onset found by spectral flux (over all bands and over the
|
|
59
|
+
* expected notes' bands), then the new energy — the spectrum of `windowMs`
|
|
60
|
+
* after the onset minus that of the same length before it, minus the noise —
|
|
61
|
+
* decomposed onto harmonic templates of the 88 keys by KL-NMF activations, in
|
|
62
|
+
* which expected notes and notes heard in the last 1.5 s are free and other
|
|
63
|
+
* notes pay a penalty. A press whose new energy is too weak against what was
|
|
64
|
+
* already sounding gives no verdict.
|
|
65
|
+
*
|
|
66
|
+
* Time 0 is the first sample processed, or the last {@link reset}.
|
|
67
|
+
*/
|
|
68
|
+
export class PianoChordVerifier {
|
|
69
|
+
/** Sampling rate of the input, Hz. */
|
|
70
|
+
sampleRate;
|
|
71
|
+
/** Analysis window, ms. */
|
|
72
|
+
windowMs;
|
|
73
|
+
/** Frequency of A4 the templates are tuned to, Hz. */
|
|
74
|
+
referenceHz;
|
|
75
|
+
/** The tuning in use, frozen. */
|
|
76
|
+
tuning;
|
|
77
|
+
latencyMs_;
|
|
78
|
+
onset_;
|
|
79
|
+
ring_;
|
|
80
|
+
mask_;
|
|
81
|
+
position_ = 0;
|
|
82
|
+
hopFill_ = 0;
|
|
83
|
+
fft_;
|
|
84
|
+
fftSize_;
|
|
85
|
+
fftInput_;
|
|
86
|
+
spectrum_;
|
|
87
|
+
magnitudes_;
|
|
88
|
+
map_;
|
|
89
|
+
bins_;
|
|
90
|
+
after_;
|
|
91
|
+
before_;
|
|
92
|
+
newEnergy_;
|
|
93
|
+
penalties_;
|
|
94
|
+
uniform_;
|
|
95
|
+
window_;
|
|
96
|
+
cutWindow_;
|
|
97
|
+
cutWindows_ = new Map();
|
|
98
|
+
cutWindowLength_ = 0;
|
|
99
|
+
grid_;
|
|
100
|
+
historyFrom_;
|
|
101
|
+
historyId_;
|
|
102
|
+
historyExpected_;
|
|
103
|
+
historyBands_;
|
|
104
|
+
bandsFrom_ = Number.NEGATIVE_INFINITY;
|
|
105
|
+
bandsUntil_ = Number.NEGATIVE_INFINITY;
|
|
106
|
+
historyCount_ = 0;
|
|
107
|
+
windowSamples_;
|
|
108
|
+
minAnalysis_;
|
|
109
|
+
cutMargin_;
|
|
110
|
+
guardAfter_;
|
|
111
|
+
guardBefore_;
|
|
112
|
+
mergeSamples_;
|
|
113
|
+
recentSamples_;
|
|
114
|
+
partials_;
|
|
115
|
+
templateSets_;
|
|
116
|
+
templateMaxMs_;
|
|
117
|
+
bandNoise_;
|
|
118
|
+
newEnergyNoise_;
|
|
119
|
+
profile_;
|
|
120
|
+
pendingActive_ = false;
|
|
121
|
+
pending_ = newRequest_();
|
|
122
|
+
pendingDue_ = 0;
|
|
123
|
+
queue_;
|
|
124
|
+
queueHead_ = 0;
|
|
125
|
+
queueLength_ = 0;
|
|
126
|
+
phase_ = IDLE_;
|
|
127
|
+
job_ = newRequest_();
|
|
128
|
+
jobLength_ = 0;
|
|
129
|
+
jobTotal_ = 0;
|
|
130
|
+
jobNoiseScale_ = 0;
|
|
131
|
+
jobIterations_ = 0;
|
|
132
|
+
jobSet_ = null;
|
|
133
|
+
allowed_ = new Uint8Array(KEY_COUNT);
|
|
134
|
+
recentUntil_ = new Float64Array(KEY_COUNT);
|
|
135
|
+
calibrating_ = false;
|
|
136
|
+
calibrationStart_ = 0;
|
|
137
|
+
calibrationEnd_ = 0;
|
|
138
|
+
calibrationNext_ = 0;
|
|
139
|
+
calibrationFrames_ = 0;
|
|
140
|
+
calibrationMeasures_ = 0;
|
|
141
|
+
calibrationSquares_ = 0;
|
|
142
|
+
calibrationBands_;
|
|
143
|
+
calibrationNewEnergy_;
|
|
144
|
+
/**
|
|
145
|
+
* @throws {RangeError} On an option out of range, an invalid tuning (naming
|
|
146
|
+
* the field) or a noise profile measured with another sampling rate, window
|
|
147
|
+
* or tuning.
|
|
148
|
+
*/
|
|
149
|
+
constructor(options) {
|
|
150
|
+
const { sampleRate, windowMs = 90, latencyMs = 0, referenceHz = 440, tuning: tuningOption, noiseProfile, } = options;
|
|
151
|
+
checkRange_("sampleRate", sampleRate, 22050, 96000);
|
|
152
|
+
checkRange_("windowMs", windowMs, 30, 120);
|
|
153
|
+
checkRange_("referenceHz", referenceHz, 392, 494);
|
|
154
|
+
if (!Number.isFinite(latencyMs) || latencyMs < 0) {
|
|
155
|
+
throw new RangeError(`latencyMs must be finite and non-negative, got ${latencyMs}`);
|
|
156
|
+
}
|
|
157
|
+
// Everything below reads this frozen copy, never the caller's object.
|
|
158
|
+
const source = tuningOption === undefined ? DEFAULT_PIANO_VERIFIER_TUNING : tuningOption;
|
|
159
|
+
validatePianoVerifierTuning(source);
|
|
160
|
+
const tuning = Object.freeze({ ...source });
|
|
161
|
+
this.sampleRate = sampleRate;
|
|
162
|
+
this.windowMs = windowMs;
|
|
163
|
+
this.referenceHz = referenceHz;
|
|
164
|
+
this.tuning = tuning;
|
|
165
|
+
this.latencyMs_ = latencyMs;
|
|
166
|
+
const samplesOf = (ms) => Math.round((ms * sampleRate) / 1000);
|
|
167
|
+
this.onset_ = new OnsetDetector(sampleRate, tuning);
|
|
168
|
+
this.windowSamples_ = samplesOf(windowMs);
|
|
169
|
+
this.minAnalysis_ = samplesOf(MIN_ANALYSIS_MS_);
|
|
170
|
+
this.cutMargin_ = samplesOf(CUT_MARGIN_MS_);
|
|
171
|
+
this.guardAfter_ = samplesOf(tuning.guardAfterMs);
|
|
172
|
+
this.guardBefore_ = samplesOf(tuning.guardBeforeMs);
|
|
173
|
+
this.mergeSamples_ = (tuning.mergeMs * sampleRate) / 1000;
|
|
174
|
+
this.recentSamples_ = samplesOf(tuning.recentMs);
|
|
175
|
+
// The longest window reaches a hop past its due time; the FFT holds it.
|
|
176
|
+
const nearest = 2 ** Math.round(Math.log2(samplesOf(tuning.analysisFftMs)));
|
|
177
|
+
const needed = 2 ** Math.ceil(Math.log2(this.windowSamples_ + HOP));
|
|
178
|
+
this.fftSize_ = Math.max(nearest, needed);
|
|
179
|
+
this.fft_ = createRealFft(this.fftSize_);
|
|
180
|
+
this.fftInput_ = new Float64Array(this.fftSize_);
|
|
181
|
+
this.spectrum_ = new Float64Array(this.fftSize_ + 2);
|
|
182
|
+
this.magnitudes_ = new Float64Array(this.fftSize_ / 2 + 1);
|
|
183
|
+
// The analysis grid stays at A4 = 440 Hz; templates move with referenceHz.
|
|
184
|
+
const nyquistPitch = frequencyPitch(sampleRate / 2) - 0.5 / tuning.binsPerSemitone;
|
|
185
|
+
const maxPitch = Math.min(tuning.analysisMaxPitch, nyquistPitch);
|
|
186
|
+
if (!(maxPitch > tuning.analysisMinPitch)) {
|
|
187
|
+
throw new RangeError(`tuning.analysisMinPitch ${tuning.analysisMinPitch} is above the Nyquist frequency of ${sampleRate} Hz`);
|
|
188
|
+
}
|
|
189
|
+
this.map_ = createLogFrequencyMap({
|
|
190
|
+
sampleRate,
|
|
191
|
+
fftSize: this.fftSize_,
|
|
192
|
+
minFrequency: pitchFrequency(tuning.analysisMinPitch),
|
|
193
|
+
maxFrequency: pitchFrequency(maxPitch),
|
|
194
|
+
bandsPerOctave: 12 * tuning.binsPerSemitone,
|
|
195
|
+
pooling: "max",
|
|
196
|
+
emptyBands: "interpolate",
|
|
197
|
+
});
|
|
198
|
+
this.bins_ = this.map_.bandCount;
|
|
199
|
+
this.after_ = new Float64Array(this.bins_);
|
|
200
|
+
this.before_ = new Float64Array(this.bins_);
|
|
201
|
+
this.newEnergy_ = new Float64Array(this.bins_);
|
|
202
|
+
const geometry = {
|
|
203
|
+
bins: this.bins_,
|
|
204
|
+
minPitch: tuning.analysisMinPitch,
|
|
205
|
+
maxPitch: tuning.analysisMinPitch + (this.bins_ - 1) / tuning.binsPerSemitone,
|
|
206
|
+
binsPerSemitone: tuning.binsPerSemitone,
|
|
207
|
+
maxPartials: tuning.maxPartials,
|
|
208
|
+
lobeWidth: tuning.lobeWidth,
|
|
209
|
+
bandStep: tuning.bandStep,
|
|
210
|
+
bandWidth: tuning.bandWidth,
|
|
211
|
+
referenceHz,
|
|
212
|
+
};
|
|
213
|
+
const bandTemplates = bandTemplateCount(geometry);
|
|
214
|
+
if (bandTemplates > MAX_BAND_TEMPLATES_) {
|
|
215
|
+
throw new RangeError(`tuning.bandStep ${tuning.bandStep} gives ${bandTemplates} band templates, more than ${MAX_BAND_TEMPLATES_}`);
|
|
216
|
+
}
|
|
217
|
+
this.partials_ = keyPartials(geometry);
|
|
218
|
+
this.templateMaxMs_ =
|
|
219
|
+
Math.round(windowMs / TEMPLATE_STEP_MS_) * TEMPLATE_STEP_MS_ +
|
|
220
|
+
TEMPLATE_STEP_MS_;
|
|
221
|
+
this.templateSets_ = [];
|
|
222
|
+
for (let ms = SHORTEST_TEMPLATE_MS_; ms <= this.templateMaxMs_; ms += TEMPLATE_STEP_MS_) {
|
|
223
|
+
const columns = buildTemplates(geometry, this.partials_, ms);
|
|
224
|
+
this.templateSets_.push({
|
|
225
|
+
dictionary: new KlActivations({
|
|
226
|
+
rows: this.bins_,
|
|
227
|
+
dictionary: columns,
|
|
228
|
+
}),
|
|
229
|
+
offsets: columns.columnOffsets,
|
|
230
|
+
rows: columns.rowIndices,
|
|
231
|
+
values: columns.values,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
const columns = this.templateSets_[0].offsets.length - 1;
|
|
235
|
+
this.penalties_ = new Float64Array(columns);
|
|
236
|
+
// Handed to every reset, so no double is passed to a fill per press.
|
|
237
|
+
this.uniform_ = new Float64Array(columns).fill(1 / columns);
|
|
238
|
+
// What must stay readable: the window before an onset, the onset's merge
|
|
239
|
+
// span and the window after it, a hop of lateness, and the hops an
|
|
240
|
+
// analysis waits in the queue and runs for.
|
|
241
|
+
const hopsPerJob = 3 + Math.ceil(tuning.iterations / tuning.iterationsPerHop);
|
|
242
|
+
const retained = Math.max(this.onset_.frameSize, this.onset_.confirmationDelaySamples + HOP) +
|
|
243
|
+
2 * this.windowSamples_ +
|
|
244
|
+
this.guardAfter_ +
|
|
245
|
+
this.guardBefore_ +
|
|
246
|
+
Math.ceil(this.mergeSamples_) +
|
|
247
|
+
this.minAnalysis_ +
|
|
248
|
+
(QUEUE_CAPACITY_ + 2) * hopsPerJob * HOP;
|
|
249
|
+
this.ring_ = new Float32Array(2 ** Math.ceil(Math.log2(retained)));
|
|
250
|
+
this.mask_ = this.ring_.length - 1;
|
|
251
|
+
this.queue_ = Array.from({ length: QUEUE_CAPACITY_ }, newRequest_);
|
|
252
|
+
this.grid_ = Object.freeze({
|
|
253
|
+
onsetFftSize: this.onset_.frameSize,
|
|
254
|
+
onsetMinHz: tuning.onsetMinHz,
|
|
255
|
+
onsetMaxHz: this.onset_.maxFrequency,
|
|
256
|
+
onsetBandsPerOctave: tuning.onsetBandsPerOctave,
|
|
257
|
+
analysisFftSize: this.fftSize_,
|
|
258
|
+
analysisMinHz: pitchFrequency(tuning.analysisMinPitch),
|
|
259
|
+
analysisMaxHz: pitchFrequency(maxPitch),
|
|
260
|
+
analysisBinsPerOctave: 12 * tuning.binsPerSemitone,
|
|
261
|
+
});
|
|
262
|
+
this.calibrationBands_ = new Float64Array(this.onset_.bandCount);
|
|
263
|
+
this.calibrationNewEnergy_ = new Float64Array(this.bins_);
|
|
264
|
+
if (noiseProfile === undefined) {
|
|
265
|
+
this.bandNoise_ = new Float64Array(this.onset_.bandCount).fill(this.onset_.fullScale * 10 ** (tuning.onsetFloorDb / 20));
|
|
266
|
+
this.newEnergyNoise_ = new Float64Array(this.bins_);
|
|
267
|
+
this.profile_ = null;
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
this.checkProfile_(noiseProfile);
|
|
271
|
+
this.bandNoise_ = Float64Array.from(noiseProfile.bandNoise);
|
|
272
|
+
this.newEnergyNoise_ = Float64Array.from(noiseProfile.newEnergyNoise);
|
|
273
|
+
this.profile_ = this.profileOf_(this.bandNoise_, this.newEnergyNoise_, noiseProfile.levelDb);
|
|
274
|
+
}
|
|
275
|
+
// Onsets are spaced by whole hops, so a cut length is a whole number
|
|
276
|
+
// of hops less the margins. Only lengths below the full window need views.
|
|
277
|
+
this.window_ = new Float64Array(this.windowSamples_);
|
|
278
|
+
hannWindowInto(this.window_, { midpoint: true });
|
|
279
|
+
this.cutWindow_ = new Float64Array(this.windowSamples_);
|
|
280
|
+
for (let length = Math.ceil((this.minAnalysis_ + this.cutMargin_ + this.guardAfter_) / HOP) *
|
|
281
|
+
HOP -
|
|
282
|
+
this.cutMargin_ -
|
|
283
|
+
this.guardAfter_; length < this.windowSamples_; length += HOP) {
|
|
284
|
+
this.cutWindows_.set(length, this.cutWindow_.subarray(0, length));
|
|
285
|
+
}
|
|
286
|
+
// Enough slots for a change per sample across the confirmation interval,
|
|
287
|
+
// its carry-in expectation and a future change.
|
|
288
|
+
const historyCapacity = this.onset_.confirmationDelaySamples + 2;
|
|
289
|
+
this.historyFrom_ = new Float64Array(historyCapacity);
|
|
290
|
+
this.historyId_ = Array.from({
|
|
291
|
+
length: historyCapacity,
|
|
292
|
+
}).fill(null);
|
|
293
|
+
this.historyExpected_ = Array.from({
|
|
294
|
+
length: historyCapacity,
|
|
295
|
+
}).fill(NO_PITCHES_);
|
|
296
|
+
this.historyBands_ = Array.from({
|
|
297
|
+
length: historyCapacity,
|
|
298
|
+
}).fill(NO_BANDS_);
|
|
299
|
+
this.restartHistory_(-1);
|
|
300
|
+
}
|
|
301
|
+
/** Input latency taken off every `onsetTime`, ms. */
|
|
302
|
+
get latencyMs() {
|
|
303
|
+
return this.latencyMs_;
|
|
304
|
+
}
|
|
305
|
+
/** @throws {RangeError} If negative or not finite. */
|
|
306
|
+
set latencyMs(value) {
|
|
307
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
308
|
+
throw new RangeError(`latencyMs must be finite and non-negative, got ${value}`);
|
|
309
|
+
}
|
|
310
|
+
this.latencyMs_ = value;
|
|
311
|
+
}
|
|
312
|
+
/** Whether a {@link calibrateNoise} is in progress; no verdict comes meanwhile. */
|
|
313
|
+
get calibrating() {
|
|
314
|
+
return this.calibrating_;
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Schedules a chord on the {@link ChordVerdict.onsetTime} clock. It applies at
|
|
318
|
+
* `fromTime` (inclusive) until the next scheduled change. The default is the
|
|
319
|
+
* latency-corrected time of the next input frame. Updates at the same time
|
|
320
|
+
* replace one another; already confirmed onsets are unchanged. Pitches are
|
|
321
|
+
* MIDI keys 21–108 in any order, or `[]` for a rest.
|
|
322
|
+
*
|
|
323
|
+
* @throws {RangeError} On invalid pitches, a non-finite id or time, a time
|
|
324
|
+
* older than the confirmation window, or a full schedule.
|
|
325
|
+
*/
|
|
326
|
+
expect(id, pitches, options) {
|
|
327
|
+
if (!Number.isFinite(id)) {
|
|
328
|
+
throw new RangeError(`id must be finite, got ${id}`);
|
|
329
|
+
}
|
|
330
|
+
for (const pitch of pitches) {
|
|
331
|
+
if (!Number.isInteger(pitch) ||
|
|
332
|
+
pitch < PIANO_PITCHES.lowest ||
|
|
333
|
+
pitch > PIANO_PITCHES.highest) {
|
|
334
|
+
throw new RangeError(`pitches must be integers in ${PIANO_PITCHES.lowest}–${PIANO_PITCHES.highest}, got ${pitch}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
const oldest = (this.position_ - this.onset_.confirmationDelaySamples) /
|
|
338
|
+
this.sampleRate -
|
|
339
|
+
this.latencyMs_ / 1000;
|
|
340
|
+
const fromTime = options?.fromTime;
|
|
341
|
+
const from = fromTime === undefined
|
|
342
|
+
? this.position_ / this.sampleRate - this.latencyMs_ / 1000
|
|
343
|
+
: fromTime;
|
|
344
|
+
if (!Number.isFinite(from) || from < oldest) {
|
|
345
|
+
throw new RangeError("fromTime must be finite and within or after the onset confirmation window");
|
|
346
|
+
}
|
|
347
|
+
const first = Math.max(0, this.expectationIndexAt_(oldest));
|
|
348
|
+
const previous = this.expectationIndexAt_(from);
|
|
349
|
+
const replace = previous >= 0 && this.historyFrom_[previous] === from;
|
|
350
|
+
if (!replace && this.historyCount_ - first === this.historyFrom_.length) {
|
|
351
|
+
throw new RangeError("Expectation schedule is full");
|
|
352
|
+
}
|
|
353
|
+
const sorted = Object.freeze([...new Set(pitches)].sort((left, right) => left - right));
|
|
354
|
+
const bands = this.onset_.expectedBands(sorted, this.referenceHz);
|
|
355
|
+
this.recordExpectation_(first, previous + (replace ? 0 : 1), replace, from, id, sorted, bands);
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Measures the background noise over the next `durationMs` of input, during
|
|
359
|
+
* which the player must keep silent, and uses it from then on. Pending
|
|
360
|
+
* verdicts are dropped; none comes until it ends. Calling again restarts the
|
|
361
|
+
* measurement. Check {@link calibrating} after {@link process} to detect
|
|
362
|
+
* completion.
|
|
363
|
+
*
|
|
364
|
+
* @param durationMs - At least twice the window plus 10 ms; default 1000.
|
|
365
|
+
* @throws {RangeError} If `durationMs` is too short or not finite.
|
|
366
|
+
*/
|
|
367
|
+
calibrateNoise(durationMs = 1000) {
|
|
368
|
+
const minimum = 2 * this.windowMs + 10;
|
|
369
|
+
if (!(durationMs >= minimum) || !Number.isFinite(durationMs)) {
|
|
370
|
+
throw new RangeError(`durationMs must be at least ${minimum} ms (twice the window and 10 ms), got ${durationMs}`);
|
|
371
|
+
}
|
|
372
|
+
this.dropAnalyses_();
|
|
373
|
+
this.calibrating_ = true;
|
|
374
|
+
this.calibrationStart_ = this.position_;
|
|
375
|
+
this.calibrationEnd_ =
|
|
376
|
+
this.position_ + Math.round((durationMs * this.sampleRate) / 1000);
|
|
377
|
+
this.calibrationNext_ = this.position_ + 2 * this.windowSamples_;
|
|
378
|
+
this.calibrationFrames_ = 0;
|
|
379
|
+
this.calibrationMeasures_ = 0;
|
|
380
|
+
this.calibrationSquares_ = 0;
|
|
381
|
+
this.calibrationBands_.fill(0);
|
|
382
|
+
this.calibrationNewEnergy_.fill(0);
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* The noise profile in use — from the last completed calibration or the
|
|
386
|
+
* constructor — as a new object, or `null` when there is none.
|
|
387
|
+
*/
|
|
388
|
+
noiseProfile() {
|
|
389
|
+
const profile = this.profile_;
|
|
390
|
+
return profile === null
|
|
391
|
+
? null
|
|
392
|
+
: this.profileOf_(Float64Array.from(profile.bandNoise), Float64Array.from(profile.newEnergyNoise), profile.levelDb);
|
|
393
|
+
}
|
|
394
|
+
profileOf_(bandNoise, newEnergyNoise, levelDb) {
|
|
395
|
+
return {
|
|
396
|
+
version: 1,
|
|
397
|
+
sampleRate: this.sampleRate,
|
|
398
|
+
windowMs: this.windowMs,
|
|
399
|
+
grid: { ...this.grid_ },
|
|
400
|
+
bandNoise,
|
|
401
|
+
newEnergyNoise,
|
|
402
|
+
levelDb,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
/** Keeps the current expectation, discarding all scheduled changes. */
|
|
406
|
+
restartHistory_(current) {
|
|
407
|
+
this.historyFrom_[0] = Number.NEGATIVE_INFINITY;
|
|
408
|
+
this.historyId_[0] = current < 0 ? null : this.historyId_[current];
|
|
409
|
+
this.historyExpected_[0] =
|
|
410
|
+
current < 0 ? NO_PITCHES_ : this.historyExpected_[current];
|
|
411
|
+
this.historyBands_[0] =
|
|
412
|
+
current < 0 ? NO_BANDS_ : this.historyBands_[current];
|
|
413
|
+
this.historyExpected_.fill(NO_PITCHES_, 1);
|
|
414
|
+
this.historyBands_.fill(NO_BANDS_, 1);
|
|
415
|
+
this.historyCount_ = 1;
|
|
416
|
+
this.bandsUntil_ = Number.NEGATIVE_INFINITY;
|
|
417
|
+
}
|
|
418
|
+
recordExpectation_(first, slot, replace, from, id, pitches, bands) {
|
|
419
|
+
// Keep the change in force at the cutoff and all later changes, in time
|
|
420
|
+
// order. Insertions can arrive out of order, but never move past the cutoff.
|
|
421
|
+
const count = this.historyCount_;
|
|
422
|
+
const index = slot - first;
|
|
423
|
+
if (first > 0) {
|
|
424
|
+
this.historyFrom_.copyWithin(0, first, count);
|
|
425
|
+
this.historyId_.copyWithin(0, first, count);
|
|
426
|
+
this.historyExpected_.copyWithin(0, first, count);
|
|
427
|
+
this.historyBands_.copyWithin(0, first, count);
|
|
428
|
+
}
|
|
429
|
+
if (!replace && slot < count) {
|
|
430
|
+
this.historyFrom_.copyWithin(index + 1, index, count - first);
|
|
431
|
+
this.historyId_.copyWithin(index + 1, index, count - first);
|
|
432
|
+
this.historyExpected_.copyWithin(index + 1, index, count - first);
|
|
433
|
+
this.historyBands_.copyWithin(index + 1, index, count - first);
|
|
434
|
+
}
|
|
435
|
+
this.historyFrom_[index] = from;
|
|
436
|
+
this.historyId_[index] = id;
|
|
437
|
+
this.historyExpected_[index] = pitches;
|
|
438
|
+
this.historyBands_[index] = bands;
|
|
439
|
+
this.historyCount_ = count - first + (replace ? 0 : 1);
|
|
440
|
+
this.historyExpected_.fill(NO_PITCHES_, this.historyCount_, count);
|
|
441
|
+
this.historyBands_.fill(NO_BANDS_, this.historyCount_, count);
|
|
442
|
+
this.bandsUntil_ = Number.NEGATIVE_INFINITY;
|
|
443
|
+
}
|
|
444
|
+
/** Last change at or before the timestamp, or −1 if none is retained. */
|
|
445
|
+
expectationIndexAt_(timestamp, inFrames = false) {
|
|
446
|
+
// The hot path passes an integer frame instead of boxing a time in seconds.
|
|
447
|
+
const time = inFrames
|
|
448
|
+
? timestamp / this.sampleRate - this.latencyMs_ / 1000
|
|
449
|
+
: timestamp;
|
|
450
|
+
let low = 0;
|
|
451
|
+
let high = this.historyCount_;
|
|
452
|
+
while (low < high) {
|
|
453
|
+
const middle = (low + high) >>> 1;
|
|
454
|
+
if (this.historyFrom_[middle] <= time)
|
|
455
|
+
low = middle + 1;
|
|
456
|
+
else
|
|
457
|
+
high = middle;
|
|
458
|
+
}
|
|
459
|
+
return low - 1;
|
|
460
|
+
}
|
|
461
|
+
/** Copies the expectation and latency in force when the onset is confirmed. */
|
|
462
|
+
expectationAt_(request, frame) {
|
|
463
|
+
const latency = this.latencyMs_;
|
|
464
|
+
const slot = this.expectationIndexAt_(frame, true);
|
|
465
|
+
request.id = slot < 0 ? null : this.historyId_[slot];
|
|
466
|
+
request.expected = slot < 0 ? NO_PITCHES_ : this.historyExpected_[slot];
|
|
467
|
+
request.latencyMs = latency;
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Restarts time at 0 and forgets the audio, pending onsets, analyses,
|
|
471
|
+
* recently heard notes and any calibration in progress. Keeps the noise
|
|
472
|
+
* profile, the latency and the current expectation, not scheduled changes.
|
|
473
|
+
*/
|
|
474
|
+
reset() {
|
|
475
|
+
const current = this.expectationIndexAt_(this.position_, true);
|
|
476
|
+
this.ring_.fill(0);
|
|
477
|
+
this.position_ = 0;
|
|
478
|
+
this.hopFill_ = 0;
|
|
479
|
+
this.onset_.reset();
|
|
480
|
+
this.dropAnalyses_();
|
|
481
|
+
this.recentUntil_.fill(0);
|
|
482
|
+
this.calibrating_ = false;
|
|
483
|
+
this.restartHistory_(current);
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Feeds the next samples of the input, mono, in [−1, 1] — an
|
|
487
|
+
* `AudioWorkletProcessor`'s input channel as it comes, of any length.
|
|
488
|
+
*
|
|
489
|
+
* @returns The verdicts decided during this block, in order; a shared frozen
|
|
490
|
+
* empty array when there are none.
|
|
491
|
+
*/
|
|
492
|
+
process(block) {
|
|
493
|
+
let verdicts = null;
|
|
494
|
+
const ring = this.ring_;
|
|
495
|
+
const mask = this.mask_;
|
|
496
|
+
let offset = 0;
|
|
497
|
+
while (offset < block.length) {
|
|
498
|
+
let take = Math.min(HOP - this.hopFill_, block.length - offset);
|
|
499
|
+
const position = this.position_;
|
|
500
|
+
if (this.calibrating_) {
|
|
501
|
+
// Stop at the end of the calibration, even within a hop.
|
|
502
|
+
take = Math.min(take, this.calibrationEnd_ - position);
|
|
503
|
+
let squares = 0;
|
|
504
|
+
for (let i = 0; i < take; i++) {
|
|
505
|
+
const sample = block[offset + i];
|
|
506
|
+
ring[(position + i) & mask] = sample;
|
|
507
|
+
squares += sample * sample;
|
|
508
|
+
}
|
|
509
|
+
this.calibrationSquares_ += squares;
|
|
510
|
+
}
|
|
511
|
+
else {
|
|
512
|
+
for (let i = 0; i < take; i++) {
|
|
513
|
+
ring[(position + i) & mask] = block[offset + i];
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
this.position_ += take;
|
|
517
|
+
this.hopFill_ += take;
|
|
518
|
+
offset += take;
|
|
519
|
+
if (this.hopFill_ === HOP) {
|
|
520
|
+
this.hopFill_ = 0;
|
|
521
|
+
const verdict = this.hop_();
|
|
522
|
+
if (verdict !== null) {
|
|
523
|
+
verdicts ??= [];
|
|
524
|
+
verdicts.push(verdict);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (this.calibrating_ && this.position_ >= this.calibrationEnd_) {
|
|
528
|
+
this.finishCalibration_();
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return verdicts ?? EMPTY_;
|
|
532
|
+
}
|
|
533
|
+
checkProfile_(profile) {
|
|
534
|
+
if (profile.version !== 1) {
|
|
535
|
+
throw new RangeError(`noiseProfile.version must be 1, got ${String(profile.version)}`);
|
|
536
|
+
}
|
|
537
|
+
if (profile.sampleRate !== this.sampleRate) {
|
|
538
|
+
throw new RangeError(`noiseProfile was measured at ${profile.sampleRate} Hz, not ${this.sampleRate} Hz`);
|
|
539
|
+
}
|
|
540
|
+
if (profile.windowMs !== this.windowMs) {
|
|
541
|
+
throw new RangeError(`noiseProfile was measured with a ${profile.windowMs} ms window, not ${this.windowMs} ms`);
|
|
542
|
+
}
|
|
543
|
+
const grid = profile.grid;
|
|
544
|
+
if (typeof grid !== "object" || grid === null) {
|
|
545
|
+
throw new RangeError("noiseProfile.grid is missing");
|
|
546
|
+
}
|
|
547
|
+
for (const [key, value] of Object.entries(this.grid_)) {
|
|
548
|
+
const measured = grid[key];
|
|
549
|
+
if (measured !== value) {
|
|
550
|
+
throw new RangeError(`noiseProfile was measured on another analysis grid: grid.${key} is ${String(measured)}, not ${value}`);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const checkArray = (name, values, length) => {
|
|
554
|
+
if (!(values instanceof Float64Array) || values.length !== length) {
|
|
555
|
+
throw new RangeError(`noiseProfile.${name} must be a Float64Array of ${length} values; it was measured with another tuning`);
|
|
556
|
+
}
|
|
557
|
+
for (const value of values) {
|
|
558
|
+
if (!(value >= 0) || !Number.isFinite(value)) {
|
|
559
|
+
throw new RangeError(`noiseProfile.${name} must hold finite non-negative values`);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
checkArray("bandNoise", profile.bandNoise, this.onset_.bandCount);
|
|
564
|
+
checkArray("newEnergyNoise", profile.newEnergyNoise, this.bins_);
|
|
565
|
+
for (const value of profile.bandNoise) {
|
|
566
|
+
if (value === 0) {
|
|
567
|
+
throw new RangeError("noiseProfile.bandNoise must be positive");
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
if (typeof profile.levelDb !== "number" || Number.isNaN(profile.levelDb)) {
|
|
571
|
+
throw new RangeError("noiseProfile.levelDb must be a number");
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
dropAnalyses_() {
|
|
575
|
+
this.pendingActive_ = false;
|
|
576
|
+
this.queueLength_ = 0;
|
|
577
|
+
this.queueHead_ = 0;
|
|
578
|
+
this.phase_ = IDLE_;
|
|
579
|
+
this.jobSet_ = null;
|
|
580
|
+
}
|
|
581
|
+
/** One 128-sample hop: onset detection, then one step of analysis. */
|
|
582
|
+
hop_() {
|
|
583
|
+
const position = this.position_;
|
|
584
|
+
const centre = position - this.onset_.frameSize / 2;
|
|
585
|
+
const centreTime = centre / this.sampleRate - this.latencyMs_ / 1000;
|
|
586
|
+
if (centreTime < this.bandsFrom_ || centreTime >= this.bandsUntil_) {
|
|
587
|
+
const slot = this.expectationIndexAt_(centre, true);
|
|
588
|
+
this.bandsFrom_ =
|
|
589
|
+
slot < 0 ? Number.NEGATIVE_INFINITY : this.historyFrom_[slot];
|
|
590
|
+
this.bandsUntil_ =
|
|
591
|
+
slot + 1 < this.historyCount_
|
|
592
|
+
? this.historyFrom_[slot + 1]
|
|
593
|
+
: Number.POSITIVE_INFINITY;
|
|
594
|
+
this.onset_.setExpectedBands(slot < 0 ? NO_BANDS_ : this.historyBands_[slot]);
|
|
595
|
+
}
|
|
596
|
+
const onset = this.onset_.analyse(this.ring_, this.mask_, position, this.bandNoise_);
|
|
597
|
+
if (this.calibrating_) {
|
|
598
|
+
this.calibrationHop_(position);
|
|
599
|
+
return null;
|
|
600
|
+
}
|
|
601
|
+
if (onset >= 0) {
|
|
602
|
+
const replaced = this.onset_.replaced;
|
|
603
|
+
const pending = this.pending_;
|
|
604
|
+
if (this.pendingActive_ && replaced) {
|
|
605
|
+
pending.onset = onset;
|
|
606
|
+
pending.anchor = onset;
|
|
607
|
+
this.expectationAt_(pending, onset);
|
|
608
|
+
this.pendingDue_ = this.dueOf_(onset);
|
|
609
|
+
}
|
|
610
|
+
else if (this.pendingActive_ &&
|
|
611
|
+
onset - pending.onset <= this.mergeSamples_) {
|
|
612
|
+
pending.anchor = onset;
|
|
613
|
+
this.pendingDue_ = Math.max(this.pendingDue_, this.dueOf_(onset));
|
|
614
|
+
}
|
|
615
|
+
else {
|
|
616
|
+
if (this.pendingActive_) {
|
|
617
|
+
// A later, separate press cuts the window short.
|
|
618
|
+
this.enqueue_(pending, Math.min(this.pendingDue_, onset - this.cutMargin_));
|
|
619
|
+
}
|
|
620
|
+
this.pendingActive_ = true;
|
|
621
|
+
// The onset is confirmed a few hops after it happened; the
|
|
622
|
+
// expectation may have changed in between.
|
|
623
|
+
this.expectationAt_(pending, onset);
|
|
624
|
+
pending.onset = onset;
|
|
625
|
+
pending.anchor = onset;
|
|
626
|
+
this.pendingDue_ = this.dueOf_(onset);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
if (this.pendingActive_ && position >= this.pendingDue_) {
|
|
630
|
+
this.enqueue_(this.pending_, this.pendingDue_);
|
|
631
|
+
}
|
|
632
|
+
return this.step_();
|
|
633
|
+
}
|
|
634
|
+
dueOf_(anchor) {
|
|
635
|
+
return anchor + this.guardAfter_ + this.windowSamples_;
|
|
636
|
+
}
|
|
637
|
+
enqueue_(request, end) {
|
|
638
|
+
this.pendingActive_ = false;
|
|
639
|
+
if (end - (request.anchor + this.guardAfter_) < this.minAnalysis_)
|
|
640
|
+
return;
|
|
641
|
+
if (this.queueLength_ === QUEUE_CAPACITY_) {
|
|
642
|
+
// Never reached with a tuning whose onsets are further apart than an
|
|
643
|
+
// analysis lasts; the oldest request is the one dropped.
|
|
644
|
+
this.queueHead_ = (this.queueHead_ + 1) % QUEUE_CAPACITY_;
|
|
645
|
+
this.queueLength_--;
|
|
646
|
+
}
|
|
647
|
+
const slot = this.queue_[(this.queueHead_ + this.queueLength_) % QUEUE_CAPACITY_];
|
|
648
|
+
slot.id = request.id;
|
|
649
|
+
slot.expected = request.expected;
|
|
650
|
+
slot.onset = request.onset;
|
|
651
|
+
slot.latencyMs = request.latencyMs;
|
|
652
|
+
slot.anchor = request.anchor;
|
|
653
|
+
slot.end = end;
|
|
654
|
+
this.queueLength_++;
|
|
655
|
+
}
|
|
656
|
+
calibrationHop_(position) {
|
|
657
|
+
// Only frames and windows wholly inside the calibration count.
|
|
658
|
+
if (position - this.onset_.frameSize >= this.calibrationStart_) {
|
|
659
|
+
const bands = this.onset_.bands;
|
|
660
|
+
for (let band = 0; band < bands.length; band++) {
|
|
661
|
+
this.calibrationBands_[band] += bands[band];
|
|
662
|
+
}
|
|
663
|
+
this.calibrationFrames_++;
|
|
664
|
+
}
|
|
665
|
+
if (position >= this.calibrationNext_ && position <= this.calibrationEnd_) {
|
|
666
|
+
// The noise's own new energy: the window just past against the one
|
|
667
|
+
// before, both spectra in this hop so the calibration can end on time.
|
|
668
|
+
this.jobLength_ = this.windowSamples_;
|
|
669
|
+
this.logSpectrum_(position - this.windowSamples_, this.after_);
|
|
670
|
+
this.logSpectrum_(position - 2 * this.windowSamples_, this.before_);
|
|
671
|
+
for (let bin = 0; bin < this.bins_; bin++) {
|
|
672
|
+
this.calibrationNewEnergy_[bin] += Math.max(0, this.after_[bin] - this.before_[bin]);
|
|
673
|
+
}
|
|
674
|
+
this.calibrationMeasures_++;
|
|
675
|
+
this.calibrationNext_ = position + this.windowSamples_;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
finishCalibration_() {
|
|
679
|
+
const floor = this.onset_.fullScale * 10 ** (this.tuning.onsetFloorDb / 20);
|
|
680
|
+
const bandNoise = new Float64Array(this.onset_.bandCount);
|
|
681
|
+
for (let band = 0; band < bandNoise.length; band++) {
|
|
682
|
+
bandNoise[band] = Math.max(floor, this.calibrationBands_[band] / Math.max(1, this.calibrationFrames_));
|
|
683
|
+
}
|
|
684
|
+
const newEnergyNoise = new Float64Array(this.bins_);
|
|
685
|
+
if (this.calibrationMeasures_ > 0) {
|
|
686
|
+
for (let bin = 0; bin < this.bins_; bin++) {
|
|
687
|
+
newEnergyNoise[bin] =
|
|
688
|
+
this.calibrationNewEnergy_[bin] / this.calibrationMeasures_;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
const meanSquare = this.calibrationSquares_ /
|
|
692
|
+
Math.max(1, this.calibrationEnd_ - this.calibrationStart_);
|
|
693
|
+
this.bandNoise_ = bandNoise;
|
|
694
|
+
this.newEnergyNoise_ = newEnergyNoise;
|
|
695
|
+
this.profile_ = this.profileOf_(bandNoise, newEnergyNoise, Math.max(LEVEL_FLOOR_DB_, 10 * Math.log10(meanSquare)));
|
|
696
|
+
this.calibrating_ = false;
|
|
697
|
+
}
|
|
698
|
+
/** Runs one phase of the analysis in progress, or starts the next. */
|
|
699
|
+
step_() {
|
|
700
|
+
if (this.phase_ === IDLE_) {
|
|
701
|
+
if (this.queueLength_ === 0)
|
|
702
|
+
return null;
|
|
703
|
+
const next = this.queue_[this.queueHead_];
|
|
704
|
+
const job = this.job_;
|
|
705
|
+
job.id = next.id;
|
|
706
|
+
job.expected = next.expected;
|
|
707
|
+
job.onset = next.onset;
|
|
708
|
+
job.latencyMs = next.latencyMs;
|
|
709
|
+
job.anchor = next.anchor;
|
|
710
|
+
job.end = next.end;
|
|
711
|
+
next.expected = NO_PITCHES_;
|
|
712
|
+
this.queueHead_ = (this.queueHead_ + 1) % QUEUE_CAPACITY_;
|
|
713
|
+
this.queueLength_--;
|
|
714
|
+
this.jobLength_ = job.end - (job.anchor + this.guardAfter_);
|
|
715
|
+
this.phase_ = AFTER_SPECTRUM_;
|
|
716
|
+
}
|
|
717
|
+
const job = this.job_;
|
|
718
|
+
switch (this.phase_) {
|
|
719
|
+
case AFTER_SPECTRUM_: {
|
|
720
|
+
this.logSpectrum_(job.anchor + this.guardAfter_, this.after_);
|
|
721
|
+
this.phase_ = BEFORE_SPECTRUM_;
|
|
722
|
+
return null;
|
|
723
|
+
}
|
|
724
|
+
case BEFORE_SPECTRUM_: {
|
|
725
|
+
this.logSpectrum_(job.onset - this.guardBefore_ - this.jobLength_, this.before_);
|
|
726
|
+
this.prepare_();
|
|
727
|
+
if (this.jobTotal_ <= 0) {
|
|
728
|
+
this.phase_ = IDLE_;
|
|
729
|
+
return this.finish_();
|
|
730
|
+
}
|
|
731
|
+
this.phase_ = ITERATE_;
|
|
732
|
+
return null;
|
|
733
|
+
}
|
|
734
|
+
default: {
|
|
735
|
+
return this.iterate_();
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
/** One hop's share of the activation updates; the verdict after the last. */
|
|
740
|
+
iterate_() {
|
|
741
|
+
const count = Math.min(this.tuning.iterationsPerHop, this.tuning.iterations - this.jobIterations_);
|
|
742
|
+
this.jobSet_.dictionary.iterate(count);
|
|
743
|
+
this.jobIterations_ += count;
|
|
744
|
+
if (this.jobIterations_ < this.tuning.iterations)
|
|
745
|
+
return null;
|
|
746
|
+
this.phase_ = IDLE_;
|
|
747
|
+
return this.finish_();
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Windowed log-frequency magnitude spectrum of `jobLength_` samples from
|
|
751
|
+
* `start`.
|
|
752
|
+
*/
|
|
753
|
+
logSpectrum_(start, out) {
|
|
754
|
+
const length = this.jobLength_;
|
|
755
|
+
// Negative frames are zero-padded, not read from the ring.
|
|
756
|
+
if (start + length > this.position_ ||
|
|
757
|
+
Math.max(0, start) < this.position_ - this.ring_.length) {
|
|
758
|
+
throw new Error("Analysis window falls outside the retained audio");
|
|
759
|
+
}
|
|
760
|
+
let window = this.window_;
|
|
761
|
+
if (length !== window.length) {
|
|
762
|
+
const cut = this.cutWindows_.get(length);
|
|
763
|
+
if (cut === undefined) {
|
|
764
|
+
throw new Error("Analysis window length was not preallocated");
|
|
765
|
+
}
|
|
766
|
+
if (this.cutWindowLength_ !== length) {
|
|
767
|
+
hannWindowInto(cut, { midpoint: true });
|
|
768
|
+
this.cutWindowLength_ = length;
|
|
769
|
+
}
|
|
770
|
+
window = cut;
|
|
771
|
+
}
|
|
772
|
+
const input = this.fftInput_;
|
|
773
|
+
const ring = this.ring_;
|
|
774
|
+
const mask = this.mask_;
|
|
775
|
+
for (let i = 0; i < length; i++) {
|
|
776
|
+
// Before time 0 the stream is silent.
|
|
777
|
+
input[i] = start + i >= 0 ? ring[(start + i) & mask] * window[i] : 0;
|
|
778
|
+
}
|
|
779
|
+
input.fill(0, length);
|
|
780
|
+
this.fft_.forwardInto(this.spectrum_, input);
|
|
781
|
+
magnitudeSpectrumInto(this.magnitudes_, this.spectrum_);
|
|
782
|
+
this.map_.applyInto(out, this.magnitudes_);
|
|
783
|
+
}
|
|
784
|
+
/** New energy, allowed notes and penalties; loads the activations. */
|
|
785
|
+
prepare_() {
|
|
786
|
+
const tuning = this.tuning;
|
|
787
|
+
const job = this.job_;
|
|
788
|
+
const length = this.jobLength_;
|
|
789
|
+
const lengthMs = (length / this.sampleRate) * 1000;
|
|
790
|
+
const setIndex = Math.min(this.templateSets_.length - 1, Math.max(0, Math.round(lengthMs / TEMPLATE_STEP_MS_) -
|
|
791
|
+
SHORTEST_TEMPLATE_MS_ / TEMPLATE_STEP_MS_));
|
|
792
|
+
const set = this.templateSets_[setIndex];
|
|
793
|
+
this.jobSet_ = set;
|
|
794
|
+
const noiseScale = tuning.noiseFactor * Math.sqrt(length / this.windowSamples_);
|
|
795
|
+
this.jobNoiseScale_ = noiseScale;
|
|
796
|
+
const newEnergy = this.newEnergy_;
|
|
797
|
+
let total = 0;
|
|
798
|
+
for (let bin = 0; bin < this.bins_; bin++) {
|
|
799
|
+
const value = Math.max(0, this.after_[bin] -
|
|
800
|
+
this.before_[bin] -
|
|
801
|
+
noiseScale * this.newEnergyNoise_[bin]);
|
|
802
|
+
newEnergy[bin] = value;
|
|
803
|
+
total += value;
|
|
804
|
+
}
|
|
805
|
+
this.jobTotal_ = total;
|
|
806
|
+
this.jobIterations_ = 0;
|
|
807
|
+
const now = this.position_;
|
|
808
|
+
const allowed = this.allowed_;
|
|
809
|
+
allowed.fill(0);
|
|
810
|
+
for (let key = 0; key < KEY_COUNT; key++) {
|
|
811
|
+
if (this.recentUntil_[key] > now)
|
|
812
|
+
allowed[key] = 1;
|
|
813
|
+
}
|
|
814
|
+
const expected = job.expected;
|
|
815
|
+
for (let index = 0; index < expected.length; index++) {
|
|
816
|
+
allowed[expected[index] - PIANO_PITCHES.lowest] = 1;
|
|
817
|
+
}
|
|
818
|
+
const lowest = expected.length > 0 ? expected[0] : PIANO_PITCHES.lowest;
|
|
819
|
+
const highest = expected.length > 0
|
|
820
|
+
? expected[expected.length - 1]
|
|
821
|
+
: PIANO_PITCHES.highest;
|
|
822
|
+
const penalties = this.penalties_;
|
|
823
|
+
penalties.fill(0);
|
|
824
|
+
const { offsets, counts } = this.partials_;
|
|
825
|
+
const maxPartials = tuning.maxPartials;
|
|
826
|
+
for (let key = 0; key < KEY_COUNT; key++) {
|
|
827
|
+
if (allowed[key] === 1)
|
|
828
|
+
continue;
|
|
829
|
+
const pitch = PIANO_PITCHES.lowest + key;
|
|
830
|
+
// Does a partial of an allowed note fall on this one?
|
|
831
|
+
let coincides = false;
|
|
832
|
+
for (let other = 0; other < KEY_COUNT && !coincides; other++) {
|
|
833
|
+
if (allowed[other] !== 1)
|
|
834
|
+
continue;
|
|
835
|
+
const distance = pitch - (PIANO_PITCHES.lowest + other);
|
|
836
|
+
for (let h = 0; h < counts[other]; h++) {
|
|
837
|
+
if (Math.abs(offsets[other * maxPartials + h] - distance) <
|
|
838
|
+
tuning.overlapSemitones) {
|
|
839
|
+
coincides = true;
|
|
840
|
+
break;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
// A wrong note is usually within a hand's reach of the chord.
|
|
845
|
+
const far = pitch < lowest - tuning.farSemitones ||
|
|
846
|
+
pitch > highest + tuning.farSemitones;
|
|
847
|
+
penalties[key] =
|
|
848
|
+
(coincides ? tuning.overlapPenalty : tuning.penalty) *
|
|
849
|
+
(far ? tuning.farFactor : 1);
|
|
850
|
+
}
|
|
851
|
+
if (total > 0) {
|
|
852
|
+
for (let bin = 0; bin < this.bins_; bin++)
|
|
853
|
+
newEnergy[bin] /= total;
|
|
854
|
+
set.dictionary.reset(newEnergy, penalties, this.uniform_);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
/** The gate and the verdict, from the activations. */
|
|
858
|
+
finish_() {
|
|
859
|
+
const tuning = this.tuning;
|
|
860
|
+
const job = this.job_;
|
|
861
|
+
const total = this.jobTotal_;
|
|
862
|
+
const set = this.jobSet_;
|
|
863
|
+
this.jobSet_ = null;
|
|
864
|
+
if (total <= 0)
|
|
865
|
+
return null;
|
|
866
|
+
const activations = set.dictionary.activations;
|
|
867
|
+
const { offsets, rows, values } = set;
|
|
868
|
+
const noiseScale = this.jobNoiseScale_;
|
|
869
|
+
// Gate: a note's new level against what already sounded at its partials.
|
|
870
|
+
// Fluctuations of ringing notes stay well below 1; a press, even soft
|
|
871
|
+
// under a loud chord, shows at its own partials.
|
|
872
|
+
let gateRatio = 0;
|
|
873
|
+
let strongest = 0;
|
|
874
|
+
for (let key = 0; key < KEY_COUNT; key++) {
|
|
875
|
+
const activation = activations[key];
|
|
876
|
+
if (activation > strongest)
|
|
877
|
+
strongest = activation;
|
|
878
|
+
if (activation < tuning.heardAbsolute)
|
|
879
|
+
continue;
|
|
880
|
+
let numerator = 0;
|
|
881
|
+
let denominator = RATIO_FLOOR_;
|
|
882
|
+
for (let entry = offsets[key]; entry < offsets[key + 1]; entry++) {
|
|
883
|
+
const bin = rows[entry];
|
|
884
|
+
const weight = values[entry];
|
|
885
|
+
numerator += activation * total * weight * weight;
|
|
886
|
+
denominator +=
|
|
887
|
+
weight *
|
|
888
|
+
(this.before_[bin] + noiseScale * this.newEnergyNoise_[bin]);
|
|
889
|
+
}
|
|
890
|
+
gateRatio = Math.max(gateRatio, numerator / denominator);
|
|
891
|
+
}
|
|
892
|
+
if (gateRatio < tuning.gate)
|
|
893
|
+
return null;
|
|
894
|
+
const heard = [];
|
|
895
|
+
const missing = [];
|
|
896
|
+
for (let index = 0; index < job.expected.length; index++) {
|
|
897
|
+
const pitch = job.expected[index];
|
|
898
|
+
const activation = activations[pitch - PIANO_PITCHES.lowest];
|
|
899
|
+
if (activation >= tuning.heardRelative * strongest &&
|
|
900
|
+
activation >= tuning.heardAbsolute) {
|
|
901
|
+
heard.push(pitch);
|
|
902
|
+
}
|
|
903
|
+
else {
|
|
904
|
+
missing.push(pitch);
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
const wrong = [];
|
|
908
|
+
for (let key = 0; key < KEY_COUNT; key++) {
|
|
909
|
+
if (this.allowed_[key] === 1)
|
|
910
|
+
continue;
|
|
911
|
+
const activation = activations[key];
|
|
912
|
+
if (activation >= tuning.wrongRelative * strongest &&
|
|
913
|
+
activation >= tuning.wrongAbsolute) {
|
|
914
|
+
wrong.push(PIANO_PITCHES.lowest + key);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
// Only notes that were expected and heard become free for a while: a
|
|
918
|
+
// wrong note played again is reported again.
|
|
919
|
+
const now = this.position_;
|
|
920
|
+
for (let index = 0; index < heard.length; index++) {
|
|
921
|
+
const pitch = heard[index];
|
|
922
|
+
this.recentUntil_[pitch - PIANO_PITCHES.lowest] =
|
|
923
|
+
now + this.recentSamples_;
|
|
924
|
+
}
|
|
925
|
+
return Object.freeze({
|
|
926
|
+
source: "onset",
|
|
927
|
+
expectationId: job.id,
|
|
928
|
+
expected: job.expected,
|
|
929
|
+
heard: Object.freeze(heard),
|
|
930
|
+
missing: Object.freeze(missing),
|
|
931
|
+
wrong: Object.freeze(wrong),
|
|
932
|
+
onsetTime: job.onset / this.sampleRate - job.latencyMs / 1000,
|
|
933
|
+
onsetFrame: job.onset,
|
|
934
|
+
decidedFrame: now,
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
//# sourceMappingURL=piano-chord-verifier.js.map
|