@ac-kit/media-piano-audio 0.2.1 → 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.
@@ -2,8 +2,10 @@ import { describeValue } from "@ac-kit/core";
2
2
  import { KlActivations } from "@ac-kit/math-linear";
3
3
  import { createLogFrequencyMap, createRealFft, hannWindowInto, magnitudeSpectrumInto, } from "@ac-kit/math-signal";
4
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";
5
7
  import { HOP, OnsetDetector } from "./_onset-detector.js";
6
- import { bandTemplateCount, buildTemplates, KEY_COUNT, keyPartials, } from "./_templates.js";
8
+ import { bandTemplateCount, buildTemplates, KEY_COUNT, keyPartials, partialAmplitude, } from "./_templates.js";
7
9
  import { DEFAULT_PIANO_VERIFIER_TUNING, validatePianoVerifierTuning, } from "./tuning.js";
8
10
  const EMPTY_ = Object.freeze([]);
9
11
  const NO_PITCHES_ = Object.freeze([]);
@@ -25,6 +27,10 @@ const LEVEL_FLOOR_DB_ = -200;
25
27
  const QUEUE_CAPACITY_ = 4;
26
28
  // More band templates than this would only slow the activations down.
27
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;
28
34
  // Phases of the analysis job, one per hop.
29
35
  const IDLE_ = 0;
30
36
  const AFTER_SPECTRUM_ = 1;
@@ -32,6 +38,7 @@ const BEFORE_SPECTRUM_ = 2;
32
38
  const ITERATE_ = 3;
33
39
  function newRequest_() {
34
40
  return {
41
+ source: "onset",
35
42
  id: null,
36
43
  expected: NO_PITCHES_,
37
44
  onset: 0,
@@ -40,6 +47,15 @@ function newRequest_() {
40
47
  end: 0,
41
48
  };
42
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
+ }
43
59
  function checkRange_(name, value, minimum, maximum) {
44
60
  if (!(value >= minimum && value <= maximum)) {
45
61
  throw new RangeError(`${name} must be in [${minimum}, ${maximum}], got ${describeValue(value)}`);
@@ -62,7 +78,14 @@ function checkRange_(name, value, minimum, maximum) {
62
78
  * decomposed onto harmonic templates of the 88 keys by KL-NMF activations, in
63
79
  * which expected notes and notes heard in the last 1.5 s are free and other
64
80
  * notes pay a penalty. A press whose new energy is too weak against what was
65
- * 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.
66
89
  *
67
90
  * Time 0 is the first sample processed, or the last {@link reset}.
68
91
  */
@@ -73,7 +96,7 @@ export class PianoChordVerifier {
73
96
  windowMs;
74
97
  /** Frequency of A4 the templates are tuned to, Hz. */
75
98
  referenceHz;
76
- /** The tuning in use, frozen. */
99
+ /** The tuning in use, its absent fields filled with the defaults, frozen. */
77
100
  tuning;
78
101
  latencyMs_;
79
102
  onset_;
@@ -133,6 +156,15 @@ export class PianoChordVerifier {
133
156
  jobSet_ = null;
134
157
  allowed_ = new Uint8Array(KEY_COUNT);
135
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;
136
168
  calibrating_ = false;
137
169
  calibrationStart_ = 0;
138
170
  calibrationEnd_ = 0;
@@ -156,9 +188,12 @@ export class PianoChordVerifier {
156
188
  throw new RangeError(`latencyMs must be finite and non-negative, got ${describeValue(latencyMs)}`);
157
189
  }
158
190
  // Everything below reads this frozen copy, never the caller's object.
159
- const source = tuningOption === undefined ? DEFAULT_PIANO_VERIFIER_TUNING : tuningOption;
191
+ const source = tuningOption ?? DEFAULT_PIANO_VERIFIER_TUNING;
160
192
  validatePianoVerifierTuning(source);
161
- const tuning = Object.freeze({ ...source });
193
+ const tuning = Object.freeze({
194
+ ...DEFAULT_PIANO_VERIFIER_TUNING,
195
+ ...source,
196
+ });
162
197
  this.sampleRate = sampleRate;
163
198
  this.windowMs = windowMs;
164
199
  this.referenceHz = referenceHz;
@@ -236,20 +271,29 @@ export class PianoChordVerifier {
236
271
  this.penalties_ = new Float64Array(columns);
237
272
  // Handed to every reset, so no double is passed to a fill per press.
238
273
  this.uniform_ = new Float64Array(columns).fill(1 / columns);
274
+ this.recheckInitial_ = new Float64Array(columns);
275
+ this.shift_ = 12 * Math.log2(referenceHz / 440);
239
276
  // What must stay readable: the window before an onset, the onset's merge
240
- // span and the window after it, a hop of lateness, and the hops an
241
- // 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.
242
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_);
243
282
  const retained = Math.max(this.onset_.frameSize, this.onset_.confirmationDelaySamples + HOP) +
244
283
  2 * this.windowSamples_ +
245
284
  this.guardAfter_ +
246
285
  this.guardBefore_ +
247
286
  Math.ceil(this.mergeSamples_) +
248
287
  this.minAnalysis_ +
249
- (QUEUE_CAPACITY_ + 2) * hopsPerJob * HOP;
288
+ queueWait +
289
+ recheckLookback;
250
290
  this.ring_ = new Float32Array(2 ** Math.ceil(Math.log2(retained)));
251
291
  this.mask_ = this.ring_.length - 1;
252
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;
253
297
  this.grid_ = Object.freeze({
254
298
  onsetFftSize: this.onset_.frameSize,
255
299
  onsetMinHz: tuning.onsetMinHz,
@@ -339,9 +383,7 @@ export class PianoChordVerifier {
339
383
  this.sampleRate -
340
384
  this.latencyMs_ / 1000;
341
385
  const fromTime = options?.fromTime;
342
- const from = fromTime === undefined
343
- ? this.position_ / this.sampleRate - this.latencyMs_ / 1000
344
- : fromTime;
386
+ const from = fromTime ?? this.position_ / this.sampleRate - this.latencyMs_ / 1000;
345
387
  if (!Number.isFinite(from) || from < oldest) {
346
388
  throw new RangeError("fromTime must be finite and within or after the onset confirmation window");
347
389
  }
@@ -354,6 +396,83 @@ export class PianoChordVerifier {
354
396
  const sorted = Object.freeze([...new Set(pitches)].sort((left, right) => left - right));
355
397
  const bands = this.onset_.expectedBands(sorted, this.referenceHz);
356
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;
357
476
  }
358
477
  /**
359
478
  * Measures the background noise over the next `durationMs` of input, during
@@ -452,10 +571,12 @@ export class PianoChordVerifier {
452
571
  let high = this.historyCount_;
453
572
  while (low < high) {
454
573
  const middle = (low + high) >>> 1;
455
- if (this.historyFrom_[middle] <= time)
574
+ if (this.historyFrom_[middle] <= time) {
456
575
  low = middle + 1;
457
- else
576
+ }
577
+ else {
458
578
  high = middle;
579
+ }
459
580
  }
460
581
  return low - 1;
461
582
  }
@@ -576,6 +697,7 @@ export class PianoChordVerifier {
576
697
  this.pendingActive_ = false;
577
698
  this.queueLength_ = 0;
578
699
  this.queueHead_ = 0;
700
+ this.recheckCount_ = 0;
579
701
  this.phase_ = IDLE_;
580
702
  this.jobSet_ = null;
581
703
  }
@@ -628,17 +750,21 @@ export class PianoChordVerifier {
628
750
  }
629
751
  }
630
752
  if (this.pendingActive_ && position >= this.pendingDue_) {
753
+ this.pendingActive_ = false;
631
754
  this.enqueue_(this.pending_, this.pendingDue_);
632
755
  }
756
+ if (this.recheckCount_ > 0) {
757
+ this.releaseRechecks_();
758
+ }
633
759
  return this.step_();
634
760
  }
635
761
  dueOf_(anchor) {
636
762
  return anchor + this.guardAfter_ + this.windowSamples_;
637
763
  }
638
764
  enqueue_(request, end) {
639
- this.pendingActive_ = false;
640
- if (end - (request.anchor + this.guardAfter_) < this.minAnalysis_)
765
+ if (end - (request.anchor + this.guardAfter_) < this.minAnalysis_) {
641
766
  return;
767
+ }
642
768
  if (this.queueLength_ === QUEUE_CAPACITY_) {
643
769
  // Never reached with a tuning whose onsets are further apart than an
644
770
  // analysis lasts; the oldest request is the one dropped.
@@ -646,11 +772,7 @@ export class PianoChordVerifier {
646
772
  this.queueLength_--;
647
773
  }
648
774
  const slot = this.queue_[(this.queueHead_ + this.queueLength_) % QUEUE_CAPACITY_];
649
- slot.id = request.id;
650
- slot.expected = request.expected;
651
- slot.onset = request.onset;
652
- slot.latencyMs = request.latencyMs;
653
- slot.anchor = request.anchor;
775
+ copyRequest_(slot, request);
654
776
  slot.end = end;
655
777
  this.queueLength_++;
656
778
  }
@@ -699,16 +821,12 @@ export class PianoChordVerifier {
699
821
  /** Runs one phase of the analysis in progress, or starts the next. */
700
822
  step_() {
701
823
  if (this.phase_ === IDLE_) {
702
- if (this.queueLength_ === 0)
824
+ if (this.queueLength_ === 0) {
703
825
  return null;
826
+ }
704
827
  const next = this.queue_[this.queueHead_];
705
828
  const job = this.job_;
706
- job.id = next.id;
707
- job.expected = next.expected;
708
- job.onset = next.onset;
709
- job.latencyMs = next.latencyMs;
710
- job.anchor = next.anchor;
711
- job.end = next.end;
829
+ copyRequest_(job, next);
712
830
  next.expected = NO_PITCHES_;
713
831
  this.queueHead_ = (this.queueHead_ + 1) % QUEUE_CAPACITY_;
714
832
  this.queueLength_--;
@@ -742,8 +860,9 @@ export class PianoChordVerifier {
742
860
  const count = Math.min(this.tuning.iterationsPerHop, this.tuning.iterations - this.jobIterations_);
743
861
  this.jobSet_.dictionary.iterate(count);
744
862
  this.jobIterations_ += count;
745
- if (this.jobIterations_ < this.tuning.iterations)
863
+ if (this.jobIterations_ < this.tuning.iterations) {
746
864
  return null;
865
+ }
747
866
  this.phase_ = IDLE_;
748
867
  return this.finish_();
749
868
  }
@@ -809,8 +928,9 @@ export class PianoChordVerifier {
809
928
  const allowed = this.allowed_;
810
929
  allowed.fill(0);
811
930
  for (let key = 0; key < KEY_COUNT; key++) {
812
- if (this.recentUntil_[key] > now)
931
+ if (this.recentUntil_[key] > now) {
813
932
  allowed[key] = 1;
933
+ }
814
934
  }
815
935
  const expected = job.expected;
816
936
  for (let index = 0; index < expected.length; index++) {
@@ -825,14 +945,16 @@ export class PianoChordVerifier {
825
945
  const { offsets, counts } = this.partials_;
826
946
  const maxPartials = tuning.maxPartials;
827
947
  for (let key = 0; key < KEY_COUNT; key++) {
828
- if (allowed[key] === 1)
948
+ if (allowed[key] === 1) {
829
949
  continue;
950
+ }
830
951
  const pitch = PIANO_PITCHES.lowest + key;
831
952
  // Does a partial of an allowed note fall on this one?
832
953
  let coincides = false;
833
954
  for (let other = 0; other < KEY_COUNT && !coincides; other++) {
834
- if (allowed[other] !== 1)
955
+ if (allowed[other] !== 1) {
835
956
  continue;
957
+ }
836
958
  const distance = pitch - (PIANO_PITCHES.lowest + other);
837
959
  for (let h = 0; h < counts[other]; h++) {
838
960
  if (Math.abs(offsets[other * maxPartials + h] - distance) <
@@ -850,55 +972,88 @@ export class PianoChordVerifier {
850
972
  (far ? tuning.farFactor : 1);
851
973
  }
852
974
  if (total > 0) {
853
- for (let bin = 0; bin < this.bins_; bin++)
975
+ for (let bin = 0; bin < this.bins_; bin++) {
854
976
  newEnergy[bin] /= total;
855
- 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]);
856
1013
  }
1014
+ return numerator / denominator;
857
1015
  }
858
1016
  /** The gate and the verdict, from the activations. */
859
1017
  finish_() {
860
1018
  const tuning = this.tuning;
861
1019
  const job = this.job_;
1020
+ const recheck = job.source === "recheck";
862
1021
  const total = this.jobTotal_;
863
1022
  const set = this.jobSet_;
864
1023
  this.jobSet_ = null;
865
- if (total <= 0)
866
- 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
+ }
867
1030
  const activations = set.dictionary.activations;
868
- const { offsets, rows, values } = set;
869
- const noiseScale = this.jobNoiseScale_;
870
- // Gate: a note's new level against what already sounded at its partials.
871
- // Fluctuations of ringing notes stay well below 1; a press, even soft
872
- // under a loud chord, shows at its own partials.
873
- let gateRatio = 0;
874
1031
  let strongest = 0;
875
1032
  for (let key = 0; key < KEY_COUNT; key++) {
876
- const activation = activations[key];
877
- if (activation > strongest)
878
- strongest = activation;
879
- if (activation < tuning.heardAbsolute)
880
- continue;
881
- let numerator = 0;
882
- let denominator = RATIO_FLOOR_;
883
- for (let entry = offsets[key]; entry < offsets[key + 1]; entry++) {
884
- const bin = rows[entry];
885
- const weight = values[entry];
886
- numerator += activation * total * weight * weight;
887
- denominator +=
888
- weight *
889
- (this.before_[bin] + noiseScale * this.newEnergyNoise_[bin]);
890
- }
891
- gateRatio = Math.max(gateRatio, numerator / denominator);
892
- }
893
- if (gateRatio < tuning.gate)
894
- 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
+ }
895
1047
  const heard = [];
896
1048
  const missing = [];
897
1049
  for (let index = 0; index < job.expected.length; index++) {
898
1050
  const pitch = job.expected[index];
899
- const activation = activations[pitch - PIANO_PITCHES.lowest];
1051
+ const key = pitch - PIANO_PITCHES.lowest;
1052
+ const activation = activations[key];
900
1053
  if (activation >= tuning.heardRelative * strongest &&
901
- 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)) {
902
1057
  heard.push(pitch);
903
1058
  }
904
1059
  else {
@@ -906,15 +1061,31 @@ export class PianoChordVerifier {
906
1061
  }
907
1062
  }
908
1063
  const wrong = [];
909
- for (let key = 0; key < KEY_COUNT; key++) {
910
- if (this.allowed_[key] === 1)
911
- continue;
912
- const activation = activations[key];
913
- if (activation >= tuning.wrongRelative * strongest &&
914
- activation >= tuning.wrongAbsolute) {
915
- 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
+ }
916
1074
  }
917
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
+ }
918
1089
  // Only notes that were expected and heard become free for a while: a
919
1090
  // wrong note played again is reported again.
920
1091
  const now = this.position_;
@@ -923,17 +1094,147 @@ export class PianoChordVerifier {
923
1094
  this.recentUntil_[pitch - PIANO_PITCHES.lowest] =
924
1095
  now + this.recentSamples_;
925
1096
  }
1097
+ return this.verdict_(heard, missing, wrong);
1098
+ }
1099
+ verdict_(heard, missing, wrong) {
1100
+ const job = this.job_;
926
1101
  return Object.freeze({
927
- source: "onset",
1102
+ source: job.source,
928
1103
  expectationId: job.id,
929
1104
  expected: job.expected,
930
- heard: Object.freeze(heard),
931
- missing: Object.freeze(missing),
932
- 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),
933
1108
  onsetTime: job.onset / this.sampleRate - job.latencyMs / 1000,
934
1109
  onsetFrame: job.onset,
935
- decidedFrame: now,
1110
+ decidedFrame: this.position_,
936
1111
  });
937
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
+ }
938
1239
  }
939
1240
  //# sourceMappingURL=piano-chord-verifier.js.map