@ac-kit/media-piano-audio 0.2.0 → 0.3.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 (39) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/README.md +20 -6
  3. package/dist/acoustics/_assert-piano-pitch.d.ts.map +1 -1
  4. package/dist/acoustics/_assert-piano-pitch.js +2 -1
  5. package/dist/acoustics/_assert-piano-pitch.js.map +1 -1
  6. package/dist/acoustics/_partial-pitch.d.ts +7 -0
  7. package/dist/acoustics/_partial-pitch.d.ts.map +1 -0
  8. package/dist/acoustics/_partial-pitch.js +9 -0
  9. package/dist/acoustics/_partial-pitch.js.map +1 -0
  10. package/dist/acoustics/piano-partials.d.ts.map +1 -1
  11. package/dist/acoustics/piano-partials.js +5 -4
  12. package/dist/acoustics/piano-partials.js.map +1 -1
  13. package/dist/calibrate/estimate-input-latency.d.ts.map +1 -1
  14. package/dist/calibrate/estimate-input-latency.js +6 -4
  15. package/dist/calibrate/estimate-input-latency.js.map +1 -1
  16. package/dist/synthesize/synthesize-piano.d.ts.map +1 -1
  17. package/dist/synthesize/synthesize-piano.js +2 -1
  18. package/dist/synthesize/synthesize-piano.js.map +1 -1
  19. package/dist/synthesize/synthesize-tick.d.ts.map +1 -1
  20. package/dist/synthesize/synthesize-tick.js +5 -4
  21. package/dist/synthesize/synthesize-tick.js.map +1 -1
  22. package/dist/verify/_onset-detector.d.ts.map +1 -1
  23. package/dist/verify/_onset-detector.js +6 -3
  24. package/dist/verify/_onset-detector.js.map +1 -1
  25. package/dist/verify/_templates.d.ts +6 -0
  26. package/dist/verify/_templates.d.ts.map +1 -1
  27. package/dist/verify/_templates.js +20 -9
  28. package/dist/verify/_templates.js.map +1 -1
  29. package/dist/verify/piano-chord-verifier.d.ts +80 -3
  30. package/dist/verify/piano-chord-verifier.d.ts.map +1 -1
  31. package/dist/verify/piano-chord-verifier.js +384 -82
  32. package/dist/verify/piano-chord-verifier.js.map +1 -1
  33. package/dist/verify/tuning.d.ts +27 -3
  34. package/dist/verify/tuning.d.ts.map +1 -1
  35. package/dist/verify/tuning.js +19 -2
  36. package/dist/verify/tuning.js.map +1 -1
  37. package/dist/verify/types.d.ts +9 -4
  38. package/dist/verify/types.d.ts.map +1 -1
  39. package/package.json +11 -10
@@ -1,8 +1,11 @@
1
+ import { describeValue } from "@ac-kit/core";
1
2
  import { KlActivations } from "@ac-kit/math-linear";
2
3
  import { createLogFrequencyMap, createRealFft, hannWindowInto, magnitudeSpectrumInto, } from "@ac-kit/math-signal";
3
4
  import { frequencyPitch, pitchFrequency, PIANO_PITCHES, } from "@ac-kit/model-music";
5
+ import { stretchedPartialPitch } from "../acoustics/_partial-pitch.js";
6
+ import { pianoInharmonicity } from "../acoustics/piano-partials.js";
4
7
  import { HOP, OnsetDetector } from "./_onset-detector.js";
5
- import { bandTemplateCount, buildTemplates, KEY_COUNT, keyPartials, } from "./_templates.js";
8
+ import { bandTemplateCount, buildTemplates, KEY_COUNT, keyPartials, partialAmplitude, } from "./_templates.js";
6
9
  import { DEFAULT_PIANO_VERIFIER_TUNING, validatePianoVerifierTuning, } from "./tuning.js";
7
10
  const EMPTY_ = Object.freeze([]);
8
11
  const NO_PITCHES_ = Object.freeze([]);
@@ -24,6 +27,10 @@ const LEVEL_FLOOR_DB_ = -200;
24
27
  const QUEUE_CAPACITY_ = 4;
25
28
  // More band templates than this would only slow the activations down.
26
29
  const MAX_BAND_TEMPLATES_ = 256;
30
+ // How late a recheck may be asked for, after its frame.
31
+ const RECHECK_LOOKBACK_MS_ = 500;
32
+ // Expectations a recheck can name: the latest ones given to `expect`.
33
+ const RECENT_EXPECTATIONS_ = 16;
27
34
  // Phases of the analysis job, one per hop.
28
35
  const IDLE_ = 0;
29
36
  const AFTER_SPECTRUM_ = 1;
@@ -31,6 +38,7 @@ const BEFORE_SPECTRUM_ = 2;
31
38
  const ITERATE_ = 3;
32
39
  function newRequest_() {
33
40
  return {
41
+ source: "onset",
34
42
  id: null,
35
43
  expected: NO_PITCHES_,
36
44
  onset: 0,
@@ -39,9 +47,18 @@ function newRequest_() {
39
47
  end: 0,
40
48
  };
41
49
  }
50
+ function copyRequest_(target, source) {
51
+ target.source = source.source;
52
+ target.id = source.id;
53
+ target.expected = source.expected;
54
+ target.onset = source.onset;
55
+ target.latencyMs = source.latencyMs;
56
+ target.anchor = source.anchor;
57
+ target.end = source.end;
58
+ }
42
59
  function checkRange_(name, value, minimum, maximum) {
43
60
  if (!(value >= minimum && value <= maximum)) {
44
- throw new RangeError(`${name} must be in [${minimum}, ${maximum}], got ${value}`);
61
+ throw new RangeError(`${name} must be in [${minimum}, ${maximum}], got ${describeValue(value)}`);
45
62
  }
46
63
  }
47
64
  /**
@@ -61,7 +78,14 @@ function checkRange_(name, value, minimum, maximum) {
61
78
  * decomposed onto harmonic templates of the 88 keys by KL-NMF activations, in
62
79
  * which expected notes and notes heard in the last 1.5 s are free and other
63
80
  * notes pay a penalty. A press whose new energy is too weak against what was
64
- * already sounding gives no verdict.
81
+ * already sounding gives no verdict. A heard note that shares partials with
82
+ * another heard note — an octave, a twelfth — must then show the energy of its
83
+ * own against its single-note template: at its own partials when its
84
+ * fundamental is its own, or, when its fundamental lies on a lower note's
85
+ * partial, as an excess of that note's partials over its template.
86
+ *
87
+ * Where no onset was found, {@link recheck} judges a chord at the time it was
88
+ * due.
65
89
  *
66
90
  * Time 0 is the first sample processed, or the last {@link reset}.
67
91
  */
@@ -72,7 +96,7 @@ export class PianoChordVerifier {
72
96
  windowMs;
73
97
  /** Frequency of A4 the templates are tuned to, Hz. */
74
98
  referenceHz;
75
- /** The tuning in use, frozen. */
99
+ /** The tuning in use, its absent fields filled with the defaults, frozen. */
76
100
  tuning;
77
101
  latencyMs_;
78
102
  onset_;
@@ -132,6 +156,15 @@ export class PianoChordVerifier {
132
156
  jobSet_ = null;
133
157
  allowed_ = new Uint8Array(KEY_COUNT);
134
158
  recentUntil_ = new Float64Array(KEY_COUNT);
159
+ recheckInitial_;
160
+ shift_;
161
+ inharmonicity_ = Float64Array.from({ length: KEY_COUNT }, (_, key) => pianoInharmonicity(PIANO_PITCHES.lowest + key));
162
+ rechecks_;
163
+ recheckCount_ = 0;
164
+ recheckLookback_;
165
+ recentIds_ = new Float64Array(RECENT_EXPECTATIONS_);
166
+ recentPitches_ = Array.from({ length: RECENT_EXPECTATIONS_ }).fill(null);
167
+ recentNext_ = 0;
135
168
  calibrating_ = false;
136
169
  calibrationStart_ = 0;
137
170
  calibrationEnd_ = 0;
@@ -152,12 +185,15 @@ export class PianoChordVerifier {
152
185
  checkRange_("windowMs", windowMs, 30, 120);
153
186
  checkRange_("referenceHz", referenceHz, 392, 494);
154
187
  if (!Number.isFinite(latencyMs) || latencyMs < 0) {
155
- throw new RangeError(`latencyMs must be finite and non-negative, got ${latencyMs}`);
188
+ throw new RangeError(`latencyMs must be finite and non-negative, got ${describeValue(latencyMs)}`);
156
189
  }
157
190
  // Everything below reads this frozen copy, never the caller's object.
158
- const source = tuningOption === undefined ? DEFAULT_PIANO_VERIFIER_TUNING : tuningOption;
191
+ const source = tuningOption ?? DEFAULT_PIANO_VERIFIER_TUNING;
159
192
  validatePianoVerifierTuning(source);
160
- const tuning = Object.freeze({ ...source });
193
+ const tuning = Object.freeze({
194
+ ...DEFAULT_PIANO_VERIFIER_TUNING,
195
+ ...source,
196
+ });
161
197
  this.sampleRate = sampleRate;
162
198
  this.windowMs = windowMs;
163
199
  this.referenceHz = referenceHz;
@@ -235,20 +271,29 @@ export class PianoChordVerifier {
235
271
  this.penalties_ = new Float64Array(columns);
236
272
  // Handed to every reset, so no double is passed to a fill per press.
237
273
  this.uniform_ = new Float64Array(columns).fill(1 / columns);
274
+ this.recheckInitial_ = new Float64Array(columns);
275
+ this.shift_ = 12 * Math.log2(referenceHz / 440);
238
276
  // 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.
277
+ // span and the window after it, a hop of lateness, the hops an analysis
278
+ // waits in the queue and runs for, and how late a recheck may come.
241
279
  const hopsPerJob = 3 + Math.ceil(tuning.iterations / tuning.iterationsPerHop);
280
+ const queueWait = (QUEUE_CAPACITY_ + 2) * hopsPerJob * HOP;
281
+ const recheckLookback = samplesOf(RECHECK_LOOKBACK_MS_);
242
282
  const retained = Math.max(this.onset_.frameSize, this.onset_.confirmationDelaySamples + HOP) +
243
283
  2 * this.windowSamples_ +
244
284
  this.guardAfter_ +
245
285
  this.guardBefore_ +
246
286
  Math.ceil(this.mergeSamples_) +
247
287
  this.minAnalysis_ +
248
- (QUEUE_CAPACITY_ + 2) * hopsPerJob * HOP;
288
+ queueWait +
289
+ recheckLookback;
249
290
  this.ring_ = new Float32Array(2 ** Math.ceil(Math.log2(retained)));
250
291
  this.mask_ = this.ring_.length - 1;
251
292
  this.queue_ = Array.from({ length: QUEUE_CAPACITY_ }, newRequest_);
293
+ this.rechecks_ = Array.from({ length: QUEUE_CAPACITY_ }, newRequest_);
294
+ // The ring holds this much more than a recheck's window before, and the
295
+ // wait in the queue, need.
296
+ this.recheckLookback_ = recheckLookback;
252
297
  this.grid_ = Object.freeze({
253
298
  onsetFftSize: this.onset_.frameSize,
254
299
  onsetMinHz: tuning.onsetMinHz,
@@ -305,7 +350,7 @@ export class PianoChordVerifier {
305
350
  /** @throws {RangeError} If negative or not finite. */
306
351
  set latencyMs(value) {
307
352
  if (!Number.isFinite(value) || value < 0) {
308
- throw new RangeError(`latencyMs must be finite and non-negative, got ${value}`);
353
+ throw new RangeError(`latencyMs must be finite and non-negative, got ${describeValue(value)}`);
309
354
  }
310
355
  this.latencyMs_ = value;
311
356
  }
@@ -325,22 +370,20 @@ export class PianoChordVerifier {
325
370
  */
326
371
  expect(id, pitches, options) {
327
372
  if (!Number.isFinite(id)) {
328
- throw new RangeError(`id must be finite, got ${id}`);
373
+ throw new RangeError(`id must be finite, got ${describeValue(id)}`);
329
374
  }
330
375
  for (const pitch of pitches) {
331
376
  if (!Number.isInteger(pitch) ||
332
377
  pitch < PIANO_PITCHES.lowest ||
333
378
  pitch > PIANO_PITCHES.highest) {
334
- throw new RangeError(`pitches must be integers in ${PIANO_PITCHES.lowest}–${PIANO_PITCHES.highest}, got ${pitch}`);
379
+ throw new RangeError(`pitches must be integers in ${PIANO_PITCHES.lowest}–${PIANO_PITCHES.highest}, got ${describeValue(pitch)}`);
335
380
  }
336
381
  }
337
382
  const oldest = (this.position_ - this.onset_.confirmationDelaySamples) /
338
383
  this.sampleRate -
339
384
  this.latencyMs_ / 1000;
340
385
  const fromTime = options?.fromTime;
341
- const from = fromTime === undefined
342
- ? this.position_ / this.sampleRate - this.latencyMs_ / 1000
343
- : fromTime;
386
+ const from = fromTime ?? this.position_ / this.sampleRate - this.latencyMs_ / 1000;
344
387
  if (!Number.isFinite(from) || from < oldest) {
345
388
  throw new RangeError("fromTime must be finite and within or after the onset confirmation window");
346
389
  }
@@ -353,6 +396,83 @@ export class PianoChordVerifier {
353
396
  const sorted = Object.freeze([...new Set(pitches)].sort((left, right) => left - right));
354
397
  const bands = this.onset_.expectedBands(sorted, this.referenceHz);
355
398
  this.recordExpectation_(first, previous + (replace ? 0 : 1), replace, from, id, sorted, bands);
399
+ this.recentIds_[this.recentNext_] = id;
400
+ this.recentPitches_[this.recentNext_] = sorted;
401
+ this.recentNext_ = (this.recentNext_ + 1) % RECENT_EXPECTATIONS_;
402
+ }
403
+ /**
404
+ * Judges expectation `id` at `frame` where no onset was found — a soft note
405
+ * right after a loud one, a note in the lowest octave — against the expected
406
+ * notes only: the window after `frame` against the one before it, as for an
407
+ * onset, with every other note left out and no gate on the whole press. A
408
+ * later {@link process} returns the verdict, with `source: "recheck"`; its
409
+ * `wrong` is empty, and an expected note is heard only when its own new level
410
+ * passes the gate. Ignored while {@link calibrating}.
411
+ *
412
+ * @param id - One of the last 16 ids given to {@link expect}; its latest
413
+ * pitches are judged.
414
+ * @param frame - The sample frame the chord was due at, on the
415
+ * {@link ChordVerdict.onsetFrame} clock: `Math.round((dueTime + latencyMs / 1000) *
416
+ * sampleRate)` for a due time on the `onsetTime` clock. At most half a
417
+ * second before the last frame processed; a later frame waits for its
418
+ * window.
419
+ * @throws {RangeError} On an id not among the recent expectations, a frame
420
+ * that is not a non-negative integer or is too old, or more than four
421
+ * rechecks waiting for their window.
422
+ */
423
+ recheck(id, frame) {
424
+ let pitches = null;
425
+ for (let back = 1; back <= RECENT_EXPECTATIONS_; back++) {
426
+ const slot = (this.recentNext_ - back + RECENT_EXPECTATIONS_) % RECENT_EXPECTATIONS_;
427
+ if (this.recentPitches_[slot] !== null && this.recentIds_[slot] === id) {
428
+ pitches = this.recentPitches_[slot];
429
+ break;
430
+ }
431
+ }
432
+ if (pitches === null) {
433
+ throw new RangeError(`id ${describeValue(id)} is not among the last ${RECENT_EXPECTATIONS_} expectations`);
434
+ }
435
+ if (!Number.isSafeInteger(frame) ||
436
+ frame < 0 ||
437
+ frame < this.position_ - this.recheckLookback_) {
438
+ throw new RangeError(`frame must be a non-negative integer no older than ${RECHECK_LOOKBACK_MS_} ms, got ${describeValue(frame)}`);
439
+ }
440
+ if (this.calibrating_) {
441
+ return;
442
+ }
443
+ if (this.recheckCount_ === this.rechecks_.length) {
444
+ throw new RangeError(`At most ${this.rechecks_.length} rechecks may wait for their window`);
445
+ }
446
+ const request = this.rechecks_[this.recheckCount_];
447
+ request.source = "recheck";
448
+ request.id = id;
449
+ request.expected = pitches;
450
+ request.onset = frame;
451
+ request.anchor = frame;
452
+ request.latencyMs = this.latencyMs_;
453
+ request.end = this.dueOf_(frame);
454
+ this.recheckCount_++;
455
+ }
456
+ /** Moves the rechecks whose window is complete to the analysis queue. */
457
+ releaseRechecks_() {
458
+ let kept = 0;
459
+ for (let index = 0; index < this.recheckCount_; index++) {
460
+ const request = this.rechecks_[index];
461
+ if (request.end <= this.position_) {
462
+ this.enqueue_(request, request.end);
463
+ request.expected = NO_PITCHES_;
464
+ }
465
+ else {
466
+ if (kept !== index) {
467
+ // Swap, so the slots stay preallocated.
468
+ const slot = this.rechecks_[kept];
469
+ this.rechecks_[kept] = request;
470
+ this.rechecks_[index] = slot;
471
+ }
472
+ kept++;
473
+ }
474
+ }
475
+ this.recheckCount_ = kept;
356
476
  }
357
477
  /**
358
478
  * Measures the background noise over the next `durationMs` of input, during
@@ -367,7 +487,7 @@ export class PianoChordVerifier {
367
487
  calibrateNoise(durationMs = 1000) {
368
488
  const minimum = 2 * this.windowMs + 10;
369
489
  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}`);
490
+ throw new RangeError(`durationMs must be at least ${minimum} ms (twice the window and 10 ms), got ${describeValue(durationMs)}`);
371
491
  }
372
492
  this.dropAnalyses_();
373
493
  this.calibrating_ = true;
@@ -451,10 +571,12 @@ export class PianoChordVerifier {
451
571
  let high = this.historyCount_;
452
572
  while (low < high) {
453
573
  const middle = (low + high) >>> 1;
454
- if (this.historyFrom_[middle] <= time)
574
+ if (this.historyFrom_[middle] <= time) {
455
575
  low = middle + 1;
456
- else
576
+ }
577
+ else {
457
578
  high = middle;
579
+ }
458
580
  }
459
581
  return low - 1;
460
582
  }
@@ -532,7 +654,7 @@ export class PianoChordVerifier {
532
654
  }
533
655
  checkProfile_(profile) {
534
656
  if (profile.version !== 1) {
535
- throw new RangeError(`noiseProfile.version must be 1, got ${String(profile.version)}`);
657
+ throw new RangeError(`noiseProfile.version must be 1, got ${describeValue(profile.version)}`);
536
658
  }
537
659
  if (profile.sampleRate !== this.sampleRate) {
538
660
  throw new RangeError(`noiseProfile was measured at ${profile.sampleRate} Hz, not ${this.sampleRate} Hz`);
@@ -547,7 +669,7 @@ export class PianoChordVerifier {
547
669
  for (const [key, value] of Object.entries(this.grid_)) {
548
670
  const measured = grid[key];
549
671
  if (measured !== value) {
550
- throw new RangeError(`noiseProfile was measured on another analysis grid: grid.${key} is ${String(measured)}, not ${value}`);
672
+ throw new RangeError(`noiseProfile was measured on another analysis grid: grid.${key} is ${describeValue(measured)}, not ${value}`);
551
673
  }
552
674
  }
553
675
  const checkArray = (name, values, length) => {
@@ -575,6 +697,7 @@ export class PianoChordVerifier {
575
697
  this.pendingActive_ = false;
576
698
  this.queueLength_ = 0;
577
699
  this.queueHead_ = 0;
700
+ this.recheckCount_ = 0;
578
701
  this.phase_ = IDLE_;
579
702
  this.jobSet_ = null;
580
703
  }
@@ -627,17 +750,21 @@ export class PianoChordVerifier {
627
750
  }
628
751
  }
629
752
  if (this.pendingActive_ && position >= this.pendingDue_) {
753
+ this.pendingActive_ = false;
630
754
  this.enqueue_(this.pending_, this.pendingDue_);
631
755
  }
756
+ if (this.recheckCount_ > 0) {
757
+ this.releaseRechecks_();
758
+ }
632
759
  return this.step_();
633
760
  }
634
761
  dueOf_(anchor) {
635
762
  return anchor + this.guardAfter_ + this.windowSamples_;
636
763
  }
637
764
  enqueue_(request, end) {
638
- this.pendingActive_ = false;
639
- if (end - (request.anchor + this.guardAfter_) < this.minAnalysis_)
765
+ if (end - (request.anchor + this.guardAfter_) < this.minAnalysis_) {
640
766
  return;
767
+ }
641
768
  if (this.queueLength_ === QUEUE_CAPACITY_) {
642
769
  // Never reached with a tuning whose onsets are further apart than an
643
770
  // analysis lasts; the oldest request is the one dropped.
@@ -645,11 +772,7 @@ export class PianoChordVerifier {
645
772
  this.queueLength_--;
646
773
  }
647
774
  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;
775
+ copyRequest_(slot, request);
653
776
  slot.end = end;
654
777
  this.queueLength_++;
655
778
  }
@@ -698,16 +821,12 @@ export class PianoChordVerifier {
698
821
  /** Runs one phase of the analysis in progress, or starts the next. */
699
822
  step_() {
700
823
  if (this.phase_ === IDLE_) {
701
- if (this.queueLength_ === 0)
824
+ if (this.queueLength_ === 0) {
702
825
  return null;
826
+ }
703
827
  const next = this.queue_[this.queueHead_];
704
828
  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;
829
+ copyRequest_(job, next);
711
830
  next.expected = NO_PITCHES_;
712
831
  this.queueHead_ = (this.queueHead_ + 1) % QUEUE_CAPACITY_;
713
832
  this.queueLength_--;
@@ -741,8 +860,9 @@ export class PianoChordVerifier {
741
860
  const count = Math.min(this.tuning.iterationsPerHop, this.tuning.iterations - this.jobIterations_);
742
861
  this.jobSet_.dictionary.iterate(count);
743
862
  this.jobIterations_ += count;
744
- if (this.jobIterations_ < this.tuning.iterations)
863
+ if (this.jobIterations_ < this.tuning.iterations) {
745
864
  return null;
865
+ }
746
866
  this.phase_ = IDLE_;
747
867
  return this.finish_();
748
868
  }
@@ -808,8 +928,9 @@ export class PianoChordVerifier {
808
928
  const allowed = this.allowed_;
809
929
  allowed.fill(0);
810
930
  for (let key = 0; key < KEY_COUNT; key++) {
811
- if (this.recentUntil_[key] > now)
931
+ if (this.recentUntil_[key] > now) {
812
932
  allowed[key] = 1;
933
+ }
813
934
  }
814
935
  const expected = job.expected;
815
936
  for (let index = 0; index < expected.length; index++) {
@@ -824,14 +945,16 @@ export class PianoChordVerifier {
824
945
  const { offsets, counts } = this.partials_;
825
946
  const maxPartials = tuning.maxPartials;
826
947
  for (let key = 0; key < KEY_COUNT; key++) {
827
- if (allowed[key] === 1)
948
+ if (allowed[key] === 1) {
828
949
  continue;
950
+ }
829
951
  const pitch = PIANO_PITCHES.lowest + key;
830
952
  // Does a partial of an allowed note fall on this one?
831
953
  let coincides = false;
832
954
  for (let other = 0; other < KEY_COUNT && !coincides; other++) {
833
- if (allowed[other] !== 1)
955
+ if (allowed[other] !== 1) {
834
956
  continue;
957
+ }
835
958
  const distance = pitch - (PIANO_PITCHES.lowest + other);
836
959
  for (let h = 0; h < counts[other]; h++) {
837
960
  if (Math.abs(offsets[other * maxPartials + h] - distance) <
@@ -849,55 +972,88 @@ export class PianoChordVerifier {
849
972
  (far ? tuning.farFactor : 1);
850
973
  }
851
974
  if (total > 0) {
852
- for (let bin = 0; bin < this.bins_; bin++)
975
+ for (let bin = 0; bin < this.bins_; bin++) {
853
976
  newEnergy[bin] /= total;
854
- set.dictionary.reset(newEnergy, penalties, this.uniform_);
977
+ }
978
+ if (job.source === "recheck") {
979
+ // Only the expected notes and the band templates may explain the
980
+ // new energy: the others start, and so stay, at zero.
981
+ const initial = this.recheckInitial_;
982
+ const columns = initial.length;
983
+ const share = 1 / (columns - KEY_COUNT + expected.length);
984
+ initial.fill(0, 0, KEY_COUNT);
985
+ initial.fill(share, KEY_COUNT);
986
+ for (let index = 0; index < expected.length; index++) {
987
+ initial[expected[index] - PIANO_PITCHES.lowest] = share;
988
+ }
989
+ set.dictionary.reset(newEnergy, penalties, initial);
990
+ }
991
+ else {
992
+ set.dictionary.reset(newEnergy, penalties, this.uniform_);
993
+ }
994
+ }
995
+ }
996
+ /**
997
+ * A note's new level against what already sounded at its partials.
998
+ * Fluctuations of ringing notes stay well below 1; a press, even soft under a
999
+ * loud chord, shows at its own partials.
1000
+ */
1001
+ gateRatio_(set, key, activation) {
1002
+ const { offsets, rows, values } = set;
1003
+ const total = this.jobTotal_;
1004
+ const noiseScale = this.jobNoiseScale_;
1005
+ let numerator = 0;
1006
+ let denominator = RATIO_FLOOR_;
1007
+ for (let entry = offsets[key]; entry < offsets[key + 1]; entry++) {
1008
+ const bin = rows[entry];
1009
+ const weight = values[entry];
1010
+ numerator += activation * total * weight * weight;
1011
+ denominator +=
1012
+ weight * (this.before_[bin] + noiseScale * this.newEnergyNoise_[bin]);
855
1013
  }
1014
+ return numerator / denominator;
856
1015
  }
857
1016
  /** The gate and the verdict, from the activations. */
858
1017
  finish_() {
859
1018
  const tuning = this.tuning;
860
1019
  const job = this.job_;
1020
+ const recheck = job.source === "recheck";
861
1021
  const total = this.jobTotal_;
862
1022
  const set = this.jobSet_;
863
1023
  this.jobSet_ = null;
864
- if (total <= 0)
865
- return null;
1024
+ if (total <= 0) {
1025
+ // Nothing new: no press, or for a recheck, none of the expected notes.
1026
+ return recheck
1027
+ ? this.verdict_(NO_PITCHES_, job.expected, NO_PITCHES_)
1028
+ : null;
1029
+ }
866
1030
  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
1031
  let strongest = 0;
874
1032
  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;
1033
+ strongest = Math.max(strongest, activations[key]);
1034
+ }
1035
+ if (!recheck) {
1036
+ let gateRatio = 0;
1037
+ for (let key = 0; key < KEY_COUNT; key++) {
1038
+ const activation = activations[key];
1039
+ if (activation >= tuning.heardAbsolute) {
1040
+ gateRatio = Math.max(gateRatio, this.gateRatio_(set, key, activation));
1041
+ }
1042
+ }
1043
+ if (gateRatio < tuning.gate) {
1044
+ return null;
1045
+ }
1046
+ }
894
1047
  const heard = [];
895
1048
  const missing = [];
896
1049
  for (let index = 0; index < job.expected.length; index++) {
897
1050
  const pitch = job.expected[index];
898
- const activation = activations[pitch - PIANO_PITCHES.lowest];
1051
+ const key = pitch - PIANO_PITCHES.lowest;
1052
+ const activation = activations[key];
899
1053
  if (activation >= tuning.heardRelative * strongest &&
900
- activation >= tuning.heardAbsolute) {
1054
+ activation >= tuning.heardAbsolute &&
1055
+ // A recheck has no press to gate: each note passes on its own.
1056
+ (!recheck || this.gateRatio_(set, key, activation) >= tuning.gate)) {
901
1057
  heard.push(pitch);
902
1058
  }
903
1059
  else {
@@ -905,15 +1061,31 @@ export class PianoChordVerifier {
905
1061
  }
906
1062
  }
907
1063
  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);
1064
+ if (!recheck) {
1065
+ for (let key = 0; key < KEY_COUNT; key++) {
1066
+ if (this.allowed_[key] === 1) {
1067
+ continue;
1068
+ }
1069
+ const activation = activations[key];
1070
+ if (activation >= tuning.wrongRelative * strongest &&
1071
+ activation >= tuning.wrongAbsolute) {
1072
+ wrong.push(PIANO_PITCHES.lowest + key);
1073
+ }
915
1074
  }
916
1075
  }
1076
+ // Every heard note is judged against the same sounding set, so the order
1077
+ // of the tests does not matter.
1078
+ const sounding = heard.length + wrong.length > 1 ? [...heard, ...wrong] : null;
1079
+ if (sounding !== null) {
1080
+ for (let index = heard.length - 1; index >= 0; index--) {
1081
+ const pitch = heard[index];
1082
+ if (!this.hasOwnEnergy_(pitch, sounding)) {
1083
+ heard.splice(index, 1);
1084
+ missing.push(pitch);
1085
+ }
1086
+ }
1087
+ missing.sort((left, right) => left - right);
1088
+ }
917
1089
  // Only notes that were expected and heard become free for a while: a
918
1090
  // wrong note played again is reported again.
919
1091
  const now = this.position_;
@@ -922,17 +1094,147 @@ export class PianoChordVerifier {
922
1094
  this.recentUntil_[pitch - PIANO_PITCHES.lowest] =
923
1095
  now + this.recentSamples_;
924
1096
  }
1097
+ return this.verdict_(heard, missing, wrong);
1098
+ }
1099
+ verdict_(heard, missing, wrong) {
1100
+ const job = this.job_;
925
1101
  return Object.freeze({
926
- source: "onset",
1102
+ source: job.source,
927
1103
  expectationId: job.id,
928
1104
  expected: job.expected,
929
- heard: Object.freeze(heard),
930
- missing: Object.freeze(missing),
931
- wrong: Object.freeze(wrong),
1105
+ heard: Object.isFrozen(heard) ? heard : Object.freeze(heard),
1106
+ missing: Object.isFrozen(missing) ? missing : Object.freeze(missing),
1107
+ wrong: Object.isFrozen(wrong) ? wrong : Object.freeze(wrong),
932
1108
  onsetTime: job.onset / this.sampleRate - job.latencyMs / 1000,
933
1109
  onsetFrame: job.onset,
934
- decidedFrame: now,
1110
+ decidedFrame: this.position_,
935
1111
  });
936
1112
  }
1113
+ /** Partial `h` (from 1) of `pitch`, in semitones on the template grid. */
1114
+ partialPitch_(pitch, h) {
1115
+ return (pitch +
1116
+ this.partials_.offsets[(pitch - PIANO_PITCHES.lowest) * this.tuning.maxPartials + h - 1]);
1117
+ }
1118
+ /**
1119
+ * The partial of `pitch` that lies within the overlap distance of `at`, its
1120
+ * number from 1, or 0: any partial, not only the template's first
1121
+ * `maxPartials`, since a string has them all.
1122
+ */
1123
+ partialOn_(at, pitch) {
1124
+ const inharmonicity = this.inharmonicity_[pitch - PIANO_PITCHES.lowest];
1125
+ const limit = this.tuning.overlapSemitones;
1126
+ // The harmonic number nearest `at`; stretching moves it by at most one.
1127
+ const nearest = Math.round(2 ** ((at - pitch) / 12));
1128
+ for (let h = Math.max(1, nearest - 1); h <= nearest + 1; h++) {
1129
+ if (Math.abs(stretchedPartialPitch(pitch, h, inharmonicity) - at) < limit) {
1130
+ return h;
1131
+ }
1132
+ }
1133
+ return 0;
1134
+ }
1135
+ /** Whether a partial of a sounding note other than `except…` lies on `at`. */
1136
+ liesOnOther_(at, sounding, except, alsoExcept) {
1137
+ for (const other of sounding) {
1138
+ if (other !== except &&
1139
+ other !== alsoExcept &&
1140
+ this.partialOn_(at, other) > 0) {
1141
+ return true;
1142
+ }
1143
+ }
1144
+ return false;
1145
+ }
1146
+ /** Peak new energy (normalised) within a bin of a partial at `at`. */
1147
+ partialEnergy_(at) {
1148
+ const tuning = this.tuning;
1149
+ const centre = Math.round((at + this.shift_ - tuning.analysisMinPitch) * tuning.binsPerSemitone);
1150
+ let peak = 0;
1151
+ for (let bin = Math.max(0, centre - 1); bin <= Math.min(this.bins_ - 1, centre + 1); bin++) {
1152
+ peak = Math.max(peak, this.newEnergy_[bin]);
1153
+ }
1154
+ return peak;
1155
+ }
1156
+ /**
1157
+ * The doubling check of a heard note against the other `sounding` notes. A
1158
+ * note none of whose first `doublingPartials` partials another sounding note
1159
+ * shares passes. Otherwise its partials are measured in the new energy and
1160
+ * divided by its single-note template's amplitudes:
1161
+ *
1162
+ * - With its fundamental its own, the level of its own partials must reach
1163
+ * `doublingOwnShare` of the shared ones' — a missing lower note of an
1164
+ * octave shows its upper note's energy at its even partials and next to
1165
+ * none at its fundamental;
1166
+ * - With its fundamental on a lower note's partial (an octave, a twelfth above
1167
+ * it): on one of those lower notes, the partials that are the note's must
1168
+ * exceed the lower note's others by `doublingExcess`, or the lower note's
1169
+ * own timbre explains them.
1170
+ *
1171
+ * A partial is shared when any partial of another sounding note lies within
1172
+ * `overlapSemitones` of it, however high, as a string has them all.
1173
+ */
1174
+ hasOwnEnergy_(pitch, sounding) {
1175
+ const tuning = this.tuning;
1176
+ const key = pitch - PIANO_PITCHES.lowest;
1177
+ const partials = Math.min(tuning.doublingPartials, this.partials_.counts[key]);
1178
+ let ownEnergy = 0;
1179
+ let ownTemplate = 0;
1180
+ let sharedEnergy = 0;
1181
+ let sharedTemplate = 0;
1182
+ let fundamentalShared = false;
1183
+ for (let h = 1; h <= partials; h++) {
1184
+ const at = this.partialPitch_(pitch, h);
1185
+ const energy = this.partialEnergy_(at);
1186
+ const amplitude = partialAmplitude(pitch, h);
1187
+ if (this.liesOnOther_(at, sounding, pitch, pitch)) {
1188
+ sharedEnergy += energy;
1189
+ sharedTemplate += amplitude;
1190
+ fundamentalShared ||= h === 1;
1191
+ }
1192
+ else {
1193
+ ownEnergy += energy;
1194
+ ownTemplate += amplitude;
1195
+ }
1196
+ }
1197
+ if (sharedTemplate === 0) {
1198
+ return true;
1199
+ }
1200
+ if (!fundamentalShared) {
1201
+ return (ownEnergy / ownTemplate >=
1202
+ tuning.doublingOwnShare * (sharedEnergy / sharedTemplate));
1203
+ }
1204
+ const fundamental = this.partialPitch_(pitch, 1);
1205
+ let judged = false;
1206
+ for (const lower of sounding) {
1207
+ if (lower >= pitch || this.partialOn_(fundamental, lower) === 0) {
1208
+ continue;
1209
+ }
1210
+ const lowerKey = lower - PIANO_PITCHES.lowest;
1211
+ const lowerPartials = Math.min(2 * tuning.doublingPartials, this.partials_.counts[lowerKey]);
1212
+ let onEnergy = 0;
1213
+ let onTemplate = 0;
1214
+ let offEnergy = 0;
1215
+ let offTemplate = 0;
1216
+ for (let h = 1; h <= lowerPartials; h++) {
1217
+ const at = this.partialPitch_(lower, h);
1218
+ const amplitude = partialAmplitude(lower, h);
1219
+ if (this.partialOn_(at, pitch) > 0) {
1220
+ onEnergy += this.partialEnergy_(at);
1221
+ onTemplate += amplitude;
1222
+ }
1223
+ else if (!this.liesOnOther_(at, sounding, lower, pitch)) {
1224
+ offEnergy += this.partialEnergy_(at);
1225
+ offTemplate += amplitude;
1226
+ }
1227
+ }
1228
+ if (onTemplate === 0 || offTemplate === 0) {
1229
+ continue;
1230
+ }
1231
+ judged = true;
1232
+ if (onEnergy / onTemplate >=
1233
+ tuning.doublingExcess * (offEnergy / offTemplate)) {
1234
+ return true;
1235
+ }
1236
+ }
1237
+ return !judged;
1238
+ }
937
1239
  }
938
1240
  //# sourceMappingURL=piano-chord-verifier.js.map