speaker-calibration 2.2.37 → 2.2.38

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 (119) hide show
  1. package/.eslintignore +71 -71
  2. package/.eslintrc.json +40 -40
  3. package/.prettierignore +69 -69
  4. package/.prettierrc +14 -14
  5. package/LICENSE +20 -20
  6. package/README.md +133 -133
  7. package/__mocks__/fileMock.js +1 -1
  8. package/__mocks__/styleMock.js +1 -1
  9. package/babel.config.js +3 -3
  10. package/coverage/clover.xml +71 -71
  11. package/coverage/coverage-final.json +224 -224
  12. package/coverage/lcov-report/PythonServerInterface.js.html +265 -265
  13. package/coverage/lcov-report/base.css +354 -354
  14. package/coverage/lcov-report/block-navigation.js +82 -82
  15. package/coverage/lcov-report/index.html +123 -123
  16. package/coverage/lcov-report/prettify.css +101 -101
  17. package/coverage/lcov-report/prettify.js +937 -937
  18. package/coverage/lcov-report/sorter.js +189 -189
  19. package/coverage/lcov-report/src/index.html +121 -121
  20. package/coverage/lcov-report/src/server/PythonServerInterface.js.html +268 -268
  21. package/coverage/lcov-report/src/server/index.html +123 -123
  22. package/coverage/lcov-report/src/tasks/audioCalibrator.js.html +499 -499
  23. package/coverage/lcov-report/src/tasks/audioRecorder.js.html +412 -412
  24. package/coverage/lcov-report/src/tasks/index.html +143 -143
  25. package/coverage/lcov-report/src/tasks/volume/index.html +123 -123
  26. package/coverage/lcov-report/src/tasks/volume/volume.js.html +409 -409
  27. package/coverage/lcov-report/src/utils.js.html +172 -172
  28. package/coverage/lcov.info +91 -91
  29. package/dist/example/fetch-languages-sheets.js +77 -77
  30. package/dist/example/i18n.js +6822 -6822
  31. package/dist/example/index.html +47 -47
  32. package/dist/example/listener.html +61 -61
  33. package/dist/example/listener.js +97 -97
  34. package/dist/example/server.js +51 -51
  35. package/dist/example/speaker.html +138 -138
  36. package/dist/example/speakerUI.js +269 -269
  37. package/dist/example/styles.css +63 -63
  38. package/dist/main.js +17 -17
  39. package/dist/mlsGen.js +6814 -6814
  40. package/dist/mlsGen.wasm +0 -0
  41. package/dist/package-lock.json +1018 -1018
  42. package/dist/package.json +18 -18
  43. package/doc/AudioCalibrator.html +417 -417
  44. package/doc/AudioPeer.html +251 -251
  45. package/doc/AudioRecorder.html +195 -195
  46. package/doc/ImpulseResponse.html +215 -215
  47. package/doc/Listener.html +308 -308
  48. package/doc/MlsGenInterface.html +226 -226
  49. package/doc/MyEventEmitter.html +274 -274
  50. package/doc/PythonServerAPI.html +109 -109
  51. package/doc/Speaker.html +276 -276
  52. package/doc/Takes%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +128 -128
  53. package/doc/Takes%20the%20url%20of%20the%20current%20site%0Aand%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +138 -138
  54. package/doc/Takes%20the%20url%20of%20the%20current%20site%20and%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +137 -137
  55. package/doc/Volume.html +88 -88
  56. package/doc/audioCalibrator.js.html +179 -179
  57. package/doc/audioPeer.js.html +175 -175
  58. package/doc/audioRecorder.js.html +163 -163
  59. package/doc/creates%20a%20new%20AudioRecorder%20instance.%20%0ASets%20up%20the%20audio%20context%20and%20file%20reader..html +114 -114
  60. package/doc/fonts/OpenSans-Bold-webfont.svg +1829 -1829
  61. package/doc/fonts/OpenSans-BoldItalic-webfont.svg +1829 -1829
  62. package/doc/fonts/OpenSans-Italic-webfont.svg +1829 -1829
  63. package/doc/fonts/OpenSans-Light-webfont.svg +1830 -1830
  64. package/doc/fonts/OpenSans-LightItalic-webfont.svg +1834 -1834
  65. package/doc/fonts/OpenSans-Regular-webfont.svg +1830 -1830
  66. package/doc/global.html +308 -308
  67. package/doc/index.html +58 -58
  68. package/doc/listener.js.html +170 -170
  69. package/doc/mlsGen_mlsGenInterface.js.html +117 -117
  70. package/doc/myEventEmitter.js.html +124 -124
  71. package/doc/peer-connection_audioPeer.js.html +188 -188
  72. package/doc/peer-connection_listener.js.html +311 -311
  73. package/doc/peer-connection_speaker.js.html +381 -381
  74. package/doc/scripts/linenumber.js +25 -25
  75. package/doc/scripts/prettify/Apache-License-2.0.txt +202 -202
  76. package/doc/scripts/prettify/lang-css.js +24 -24
  77. package/doc/scripts/prettify/prettify.js +640 -640
  78. package/doc/server_PythonServerAPI.js.html +160 -160
  79. package/doc/speaker.js.html +248 -248
  80. package/doc/styles/jsdoc-default.css +371 -371
  81. package/doc/styles/prettify-jsdoc.css +111 -111
  82. package/doc/styles/prettify-tomorrow.css +163 -163
  83. package/doc/tasks_audioCalibrator.js.html +207 -207
  84. package/doc/tasks_audioRecorder.js.html +190 -190
  85. package/doc/tasks_impulse-response_impulseResponse.js.html +442 -442
  86. package/doc/tasks_impulse-response_mlsGen_mlsGenInterface.js.html +175 -175
  87. package/doc/tasks_volume_volume.js.html +185 -185
  88. package/doc/utils.js.html +105 -105
  89. package/jest.config.js +173 -173
  90. package/makefile +74 -0
  91. package/netlify.toml +26 -26
  92. package/package.json +69 -69
  93. package/src/config/firebase.js +25 -25
  94. package/src/index.html +21 -21
  95. package/src/main.js +23 -23
  96. package/src/myEventEmitter.js +83 -83
  97. package/src/peer-connection/audioPeer.js +151 -151
  98. package/src/peer-connection/listener.js +288 -288
  99. package/src/peer-connection/peerErrors.js +25 -25
  100. package/src/peer-connection/speaker.js +442 -439
  101. package/src/server/PythonServerAPI.js +468 -468
  102. package/src/tasks/audioCalibrator.js +304 -304
  103. package/src/tasks/audioRecorder.js +277 -267
  104. package/src/tasks/combination/combination.js +1769 -1509
  105. package/src/tasks/combination/mlsGen/mlsGen.cpp +98 -98
  106. package/src/tasks/combination/mlsGen/mlsGen.hpp +303 -303
  107. package/src/tasks/combination/mlsGen/mlsGenInterface.js +131 -131
  108. package/src/tasks/combination/mlsGen/mlsGenTest.cpp +180 -180
  109. package/src/tasks/impulse-response/impulseResponse.js +610 -610
  110. package/src/tasks/impulse-response/mlsGen/mlsGen.cpp +98 -98
  111. package/src/tasks/impulse-response/mlsGen/mlsGen.hpp +303 -303
  112. package/src/tasks/impulse-response/mlsGen/mlsGenInterface.js +131 -131
  113. package/src/tasks/impulse-response/mlsGen/mlsGenTest.cpp +180 -180
  114. package/src/tasks/volume/volume.cpp +2 -2
  115. package/src/tasks/volume/volume.hpp +22 -22
  116. package/src/tasks/volume/volume.js +279 -279
  117. package/src/utils.js +55 -55
  118. package/webpack.config.js +37 -37
  119. package/.gitignore +0 -81
@@ -1,1509 +1,1769 @@
1
- import AudioCalibrator from '../audioCalibrator';
2
-
3
- import {sleep, csvToArray, saveToCSV} from '../../utils';
4
- import database from '../../config/firebase';
5
- import {ref, set, get, child} from 'firebase/database';
6
-
7
- /**
8
- *
9
- */
10
- class Combination extends AudioCalibrator {
11
- /**
12
- * Default constructor. Creates an instance with any number of paramters passed or the default parameters defined here.
13
- *
14
- * @param {Object<boolean, number, number, number>} calibratorParams - paramter object
15
- * @param {boolean} [calibratorParams.download = false] - boolean flag to download captures
16
- * @param {number} [calibratorParams.mlsOrder = 18] - order of the MLS to be generated
17
- * @param {number} [calibratorParams.numCaptures = 5] - number of captures to perform
18
- * @param {number} [calibratorParams.numMLSPerCapture = 4] - number of bursts of MLS per capture
19
- */
20
- constructor({
21
- download = false,
22
- mlsOrder = 18,
23
- numCaptures = 3,
24
- numMLSPerCapture = 4,
25
- lowHz = 20,
26
- highHz = 10000,
27
- }) {
28
- super(numCaptures, numMLSPerCapture);
29
- this.#mlsOrder = parseInt(mlsOrder, 10);
30
- this.#P = 2 ** mlsOrder - 1;
31
- this.#download = download;
32
- this.#mls = [];
33
- this.#lowHz = lowHz;
34
- this.#highHz = highHz;
35
- }
36
-
37
- /** @private */
38
- stepNum = 0;
39
-
40
- /** @private */
41
- totalSteps = 25;
42
-
43
- /** @private */
44
- #download;
45
-
46
- /** @private */
47
- #mlsGenInterface;
48
-
49
- /** @private */
50
- #mlsBufferView;
51
-
52
- /** @private */
53
- componentInvertedImpulseResponse = null;
54
-
55
- /** @private */
56
- systemInvertedImpulseResponse = null;
57
-
58
- //averaged and subtracted ir returned from calibration used to calculated iir
59
- /** @private */
60
- ir = null;
61
-
62
- /** @private */
63
- impulseResponses = [];
64
-
65
- /** @private */
66
- #mlsOrder;
67
-
68
- /** @private */
69
- #lowHz;
70
-
71
- /** @private */
72
- #highHz;
73
-
74
- /** @private */
75
- #mls;
76
-
77
- /** @private */
78
- #P;
79
-
80
- /** @private */
81
- #audioContext;
82
-
83
- /** @private */
84
- TAPER_SECS = 5;
85
-
86
- /** @private */
87
- offsetGainNode;
88
-
89
- /** @private */
90
- componentConvolution;
91
-
92
- /** @private */
93
- systemConvolution;
94
-
95
- ////////////////////////volume
96
- /** @private */
97
- #CALIBRATION_TONE_FREQUENCY = 1000; // Hz
98
-
99
- /** @private */
100
- #CALIBRATION_TONE_TYPE = 'sine';
101
-
102
- CALIBRATION_TONE_DURATION = 5; // seconds
103
- calibrateSound1000HzPreSec = 3.5;
104
- calibrateSound1000HzSec = 1.0;
105
- calibrateSound1000HzPostSec = 0.5;
106
-
107
-
108
- /** @private */
109
- outDBSPL = null;
110
- THD = null;
111
- outDBSPL1000 = null;
112
-
113
- /** @private */
114
- TAPER_SECS = 0.01; // seconds
115
-
116
- /** @private */
117
- status_denominator = 8;
118
-
119
- /** @private */
120
- status_numerator = 0;
121
-
122
- /** @private */
123
- percent_complete = 0;
124
-
125
- /** @private */
126
- status = ``;
127
-
128
- /**@private */
129
- status_literal = `<div style="display: flex; justify-content: center;"><div style="width: 200px; height: 20px; border: 2px solid #000; border-radius: 10px;"><div style="width: ${this.percent_complete}%; height: 100%; background-color: #00aaff; border-radius: 8px;"></div></div></div>`;
130
-
131
- /**@private */
132
- componentIR = null;
133
-
134
- /**@private */
135
- oldComponentIR = null;
136
-
137
- /**@private */
138
- systemIR = null;
139
-
140
- /**@private */
141
- _calibrateSoundCheck = '';
142
-
143
- deviceType = null;
144
-
145
- deviceName = null;
146
-
147
- deviceInfo = null;
148
-
149
- desired_time_per_mls = 0;
150
-
151
- num_mls_to_skip = 0;
152
-
153
- desired_sampling_rate = 0;
154
-
155
- #currentConvolution = [];
156
-
157
- mode = 'unfiltered';
158
-
159
- sourceNode;
160
-
161
- autocorrelations = [];
162
-
163
- iirLength = 0;
164
-
165
- componentInvertedImpulseResponseNoBandpass = [];
166
-
167
- systemInvertedImpulseResponseNoBandpass = [];
168
-
169
- _calibrateSoundBackgroundSecs;
170
-
171
- background_noise = {};
172
-
173
- numSuccessfulBackgroundCaptured;
174
-
175
- /**generate string template that gets reevaluated as variable increases */
176
- generateTemplate = () => {
177
- if (this.percent_complete > 100) {
178
- this.percent_complete = 100;
179
- }
180
- const template = `<div style="display: flex; justify-content: center;"><div style="width: 800px; height: 20px; border: 2px solid #000; border-radius: 10px;"><div style="width: ${this.percent_complete}%; height: 100%; background-color: #00aaff; border-radius: 8px;"></div></div></div>`;
181
- return template;
182
- };
183
-
184
- /** increment numerator and percent for status bar */
185
- incrementStatusBar = () => {
186
- this.status_numerator += 1;
187
- this.percent_complete = (this.status_numerator / this.status_denominator) * 100;
188
- };
189
-
190
- setDeviceType = deviceType => {
191
- this.deviceType = deviceType;
192
- };
193
-
194
- setDeviceName = deviceName => {
195
- this.deviceName = deviceName;
196
- };
197
-
198
- setDeviceInfo = deviceInfo => {
199
- this.deviceInfo = deviceInfo;
200
- };
201
-
202
- /** .
203
- * .
204
- * .
205
- * Sends all the computed impulse responses to the backend server for processing
206
- *
207
- * @returns sets the resulting inverted impulse response to the class property
208
- * @example
209
- */
210
- sendSystemImpulseResponsesToServerForProcessing = async () => {
211
- const computedIRs = await Promise.all(this.impulseResponses);
212
- const filteredComputedIRs = computedIRs.filter(element => {
213
- return element != undefined;
214
- }); //log any errors that are found in this step
215
- const mls = this.#mls;
216
- const lowHz = this.#lowHz; //gain of 1 below cutoff, need gain of 0
217
- const highHz = this.#highHz; //check error for anything other than 10 kHz
218
- const iirLength = this.iirLength;
219
- const num_periods = this.numMLSPerCapture + this.num_mls_to_skip;
220
- this.stepNum += 1;
221
- console.log('send impulse responses to server: ' + this.stepNum);
222
- this.status =
223
- `All Hz Calibration: computing the IIR...`.toString() + this.generateTemplate().toString();
224
- this.emit('update', {message: this.status});
225
- return this.pyServerAPI
226
- .getSystemInverseImpulseResponseWithRetry({
227
- payload: filteredComputedIRs.slice(0, this.numCaptures),
228
- mls,
229
- lowHz,
230
- highHz,
231
- iirLength,
232
- num_periods,
233
- sampleRate: this.sourceSamplingRate || 96000,
234
- })
235
- .then(res => {
236
- console.log(res);
237
- this.stepNum += 1;
238
- console.log('got impulse response ' + this.stepNum);
239
- this.incrementStatusBar();
240
- this.status =
241
- `All Hz Calibration: done computing the IIR...`.toString() +
242
- this.generateTemplate().toString();
243
- this.emit('update', {message: this.status});
244
- this.systemInvertedImpulseResponse = res['iir'];
245
- this.systemIR = res['ir'];
246
- this.systemConvolution = res['convolution'];
247
- this.systemInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];
248
- })
249
- .catch(err => {
250
- console.error(err);
251
- });
252
- };
253
-
254
- /** .
255
- * .
256
- * .
257
- * Sends all the computed impulse responses to the backend server for processing
258
- *
259
- * @returns sets the resulting inverted impulse response to the class property
260
- * @example
261
- */
262
- sendComponentImpulseResponsesToServerForProcessing = async () => {
263
- const computedIRs = await Promise.all(this.impulseResponses);
264
- const filteredComputedIRs = computedIRs.filter(element => {
265
- return element != undefined;
266
- });
267
- const componentIRGains = this.componentIR['Gain'];
268
- const componentIRFreqs = this.componentIR['Freq'];
269
- const mls = this.#mls;
270
- const lowHz = this.#lowHz;
271
- const iirLength = this.iirLength;
272
- const num_periods = this.numMLSPerCapture + this.num_mls_to_skip;
273
- const highHz = this.#highHz;
274
- this.stepNum += 1;
275
- console.log('send impulse responses to server: ' + this.stepNum);
276
- this.status =
277
- `All Hz Calibration: computing the IIR...`.toString() + this.generateTemplate().toString();
278
- this.emit('update', {message: this.status});
279
- return this.pyServerAPI
280
- .getComponentInverseImpulseResponseWithRetry({
281
- payload: filteredComputedIRs.slice(0, this.numCaptures),
282
- mls,
283
- lowHz,
284
- highHz,
285
- iirLength,
286
- componentIRGains,
287
- componentIRFreqs,
288
- num_periods,
289
- sampleRate: this.sourceSamplingRate || 96000,
290
- })
291
- .then(res => {
292
- console.log(res);
293
- this.stepNum += 1;
294
- console.log('got impulse response ' + this.stepNum);
295
- this.incrementStatusBar();
296
- this.status =
297
- `All Hz Calibration: done computing the IIR...`.toString() +
298
- this.generateTemplate().toString();
299
- this.emit('update', {message: this.status});
300
- this.componentInvertedImpulseResponse = res['iir'];
301
- this.componentIR['Gain'] = res['ir'];
302
- this.componentIR['Freq'] = res['frequencies'];
303
- this.componentConvolution = res['convolution'];
304
- this.componentInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];
305
- })
306
- .catch(err => {
307
- // this.emit('InvertedImpulseResponse', {res: false});
308
- console.error(err);
309
- });
310
- };
311
-
312
- sendBackgroundRecording = () => {
313
- const allSignals = this.getAllBackgroundRecordings();
314
- const numSignals = allSignals.length;
315
- const background_rec_whole = allSignals[numSignals-1];
316
- const fraction = .5/(this._calibrateSoundBackgroundSecs + .5);
317
- // Calculate the starting index for slicing the array
318
- const startIndex = Math.round(fraction * background_rec_whole.length);
319
- // Slice the array from the calculated start index to the end of the array
320
- const background_rec = background_rec_whole.slice(startIndex);
321
- console.log('Sending background recording to server for processing');
322
- this.pyServerAPI
323
- .getBackgroundNoisePSDWithRetry({
324
- background_rec,
325
- sampleRate: this.sourceSamplingRate || 96000,
326
- })
327
- .then(res => {
328
- if (this.numSuccessfulBackgroundCaptured < 1) {
329
- this.numSuccessfulBackgroundCaptured += 1;
330
- //storing all background data in background_psd object
331
- this.background_noise['x_background'] = res['x_background'];
332
- this.background_noise['y_background'] = res['y_background'];
333
- this.background_noise['recording'] = background_rec;
334
- }
335
- })
336
- .catch(err => {
337
- console.error(err);
338
- });
339
- }
340
-
341
- /** .
342
- * .
343
- * .
344
- * Sends the recorded signal, or a given csv string of a signal, to the back end server for processing
345
- *
346
- * @param {<array>String} signalCsv - Optional csv string of a previously recorded signal, if given, this signal will be processed
347
- * @example
348
- */
349
- sendRecordingToServerForProcessing = signalCsv => {
350
- const allSignals = this.getAllUnfilteredRecordedSignals();
351
- console.log(
352
- 'Obtaining last all hz unfiltered recording from #allHzUnfilteredRecordings to send to server for processing'
353
- );
354
- const numSignals = allSignals.length;
355
- const mls = this.#mls;
356
- const payload =
357
- signalCsv && signalCsv.length > 0 ? csvToArray(signalCsv) : allSignals[numSignals - 1];
358
- console.log('sending rec');
359
- this.stepNum += 1;
360
- console.log('send rec ' + this.stepNum);
361
- this.status =
362
- `All Hz Calibration Step: computing the IR of the last recording...`.toString() +
363
- this.generateTemplate().toString();
364
- this.emit('update', {message: this.status});
365
- this.impulseResponses.push(
366
- this.pyServerAPI
367
- .getImpulseResponse({
368
- sampleRate: this.sourceSamplingRate || 96000,
369
- payload,
370
- mls,
371
- P: this.#P, //get rid of this
372
- numPeriods: this.numMLSPerCapture,
373
- })
374
- .then(res => {
375
- if (this.numSuccessfulCaptured < this.numCaptures) {
376
- this.numSuccessfulCaptured += 1;
377
- console.log('num succ capt: ' + this.numSuccessfulCaptured);
378
- this.stepNum += 1;
379
- console.log('got impulse response ' + this.stepNum);
380
- this.incrementStatusBar();
381
- this.status =
382
- `All Hz Calibration: ${this.numSuccessfulCaptured}/${this.numCaptures} IRs computed...`.toString() +
383
- this.generateTemplate().toString();
384
- this.emit('update', {
385
- message: this.status,
386
- });
387
- this.autocorrelations.push(res['autocorrelation']);
388
- return res['ir'];
389
- }
390
- })
391
- .catch(err => {
392
- console.error(err);
393
- })
394
- );
395
- };
396
-
397
- /**
398
- * Passed to the calibration steps function, awaits the desired amount of seconds to capture the desired number
399
- * of MLS periods defined in the constructor.
400
- *
401
- * @example
402
- */
403
- #awaitDesiredMLSLength = async () => {
404
- // seconds per MLS = P / SR
405
- // await N * P / SR
406
- this.stepNum += 1;
407
- console.log('await desired length ' + this.stepNum);
408
- this.status =
409
- `All Hz Calibration: sampling the calibration signal...`.toString() +
410
- `\niteration ${this.stepNum}` +
411
- this.generateTemplate();
412
- this.emit('update', {
413
- message: this.status,
414
- });
415
- let time_to_wait = 0;
416
- if (this.mode === 'unfiltered') {
417
- time_to_wait = (this.#mls.length / this.sourceSamplingRate) * this.numMLSPerCapture;
418
- time_to_wait = time_to_wait * 1.1;
419
- } else if (this.mode === 'filtered') {
420
- time_to_wait =
421
- (this.#currentConvolution.length / this.sourceSamplingRate) *
422
- (this.numMLSPerCapture / (this.num_mls_to_skip + this.numMLSPerCapture));
423
- } else {
424
- throw new Error('Mode broke in awaitDesiredMLSLength');
425
- }
426
-
427
- await sleep(time_to_wait);
428
- };
429
-
430
- /**
431
- * Passed to the background noise recording function, awaits the desired amount of seconds to capture the desired number
432
- * of seconds of background noise
433
- *
434
- * @example
435
- */
436
- #awaitBackgroundNoiseRecording = async () => {
437
- console.log('Waiting ' + this._calibrateSoundBackgroundSecs + " second(s) to record background noise");
438
- let time_to_wait = this._calibrateSoundBackgroundSecs + .5;
439
- await sleep(time_to_wait);
440
- };
441
-
442
-
443
- /** .
444
- * .
445
- * .
446
- * Passed to the calibration steps function, awaits the onset of the signal to ensure a steady state
447
- *
448
- * @example
449
- */
450
- #awaitSignalOnset = async () => {
451
- this.stepNum += 1;
452
- console.log('await signal onset ' + this.stepNum);
453
- this.status =
454
- `All Hz Calibration: waiting for the signal to stabilize...`.toString() +
455
- this.generateTemplate();
456
- this.emit('update', {
457
- message: this.status,
458
- });
459
- let number_of_bursts_to_skip = this.num_mls_to_skip;
460
- let time_to_sleep = 0;
461
- if (this.mode === 'unfiltered') {
462
- time_to_sleep = (this.#mls.length / this.sourceSamplingRate) * number_of_bursts_to_skip;
463
- } else if (this.mode === 'filtered') {
464
- console.log(this.#currentConvolution.length);
465
- time_to_sleep =
466
- (this.#currentConvolution.length / this.sourceSamplingRate) *
467
- (number_of_bursts_to_skip / (number_of_bursts_to_skip + this.numMLSPerCapture));
468
- } else {
469
- throw new Error('Mode broke in awaitSignalOnset');
470
- }
471
- await sleep(time_to_sleep);
472
- };
473
-
474
- /**
475
- * Called immediately after a recording is captured. Used to process the resulting signal
476
- * whether by sending the result to a server or by computing a result locally.
477
- *
478
- * @example
479
- */
480
- #afterMLSRecord = () => {
481
- console.log('after record');
482
- this.sendRecordingToServerForProcessing();
483
- };
484
-
485
- #afterMLSwIIRRecord = () => {
486
- if (this.numSuccessfulCaptured < 1) {
487
- this.numSuccessfulCaptured += 1;
488
- this.stepNum += 1;
489
- this.incrementStatusBar();
490
- console.log('after mls w iir record for some reason add numSucc capt ' + this.stepNum);
491
- this.status =
492
- `All Hz Calibration: ${this.numSuccessfulCaptured} recording of convolved MLS captured`.toString() +
493
- this.generateTemplate().toString();
494
- this.emit('update', {
495
- message: this.status,
496
- });
497
- }
498
- };
499
-
500
- /** .
501
- * .
502
- * .
503
- * Created an S Curver Buffer to taper the signal onset
504
- *
505
- * @param {*} length
506
- * @param {*} phase
507
- * @returns
508
- * @example
509
- */
510
- static createSCurveBuffer = (length, phase) => {
511
- const curve = new Float32Array(length);
512
- let i;
513
- for (i = 0; i < length; i += 1) {
514
- // scale the curve to be between 0-1
515
- curve[i] = Math.sin((Math.PI * i) / length - phase) / 2 + 0.5;
516
- }
517
- return curve;
518
- };
519
-
520
- static createInverseSCurveBuffer = (length, phase) => {
521
- const curve = new Float32Array(length);
522
- let i;
523
- let j = length - 1;
524
- for (i = 0; i < length; i += 1) {
525
- // scale the curve to be between 0-1
526
- curve[i] = Math.sin((Math.PI * j) / length - phase) / 2 + 0.5;
527
- j -= 1;
528
- }
529
- return curve;
530
- };
531
-
532
- /**
533
- * Construct a Calibration Node with the calibration parameters.
534
- *
535
- * @param dataBuffer
536
- * @private
537
- * @example
538
- */
539
- #createCalibrationNodeFromBuffer = dataBuffer => {
540
- console.log('databuffer');
541
- console.log(dataBuffer);
542
- if (!this.sourceAudioContext) {
543
- this.makeNewSourceAudioContext();
544
- }
545
-
546
- const buffer = this.sourceAudioContext.createBuffer(
547
- 1, // number of channels
548
- dataBuffer.length,
549
- this.sourceAudioContext.sampleRate // sample rate
550
- );
551
-
552
- const data = buffer.getChannelData(0); // get data
553
- // fill the buffer with our data
554
- try {
555
- for (let i = 0; i < dataBuffer.length; i += 1) {
556
- data[i] = dataBuffer[i] * 0.33;
557
- }
558
- } catch (error) {
559
- console.error(error);
560
- }
561
-
562
- this.sourceNode = this.sourceAudioContext.createBufferSource();
563
-
564
- this.sourceNode.buffer = buffer;
565
- if (this.mode === 'filtered') {
566
- this.sourceNode.loop = false;
567
- } else {
568
- this.sourceNode.loop = true;
569
- }
570
-
571
- this.sourceNode.connect(this.sourceAudioContext.destination);
572
-
573
- this.addCalibrationNode(this.sourceNode);
574
- };
575
-
576
- /**
577
- * Given a data buffer, creates the required calibration node
578
- *
579
- * @param {*} dataBufferArray
580
- * @example
581
- */
582
- #setCalibrationNodesFromBuffer = (dataBufferArray = [this.#mlsBufferView]) => {
583
- if (dataBufferArray.length === 1) {
584
- this.#createCalibrationNodeFromBuffer(dataBufferArray[0]);
585
- } else {
586
- throw new Error('The length of the data buffer array must be 1');
587
- }
588
- };
589
-
590
- /**
591
- * Creates an audio context and plays it for a few seconds.
592
- *
593
- * @private
594
- * @returns - Resolves when the audio is done playing.
595
- * @example
596
- */
597
- #playCalibrationAudio = () => {
598
- this.calibrationNodes[0].start(0);
599
- this.status = ``;
600
- if (this.mode === 'unfiltered') {
601
- this.#mls = this.calibrationNodes[0].buffer.getChannelData(0);
602
- console.log('play calibration audio ' + this.stepNum);
603
- this.status =
604
- `All Hz Calibration: playing the calibration tone...`.toString() +
605
- this.generateTemplate().toString();
606
- } else if (this.mode === 'filtered') {
607
- console.log('play convolved audio ' + this.stepNum);
608
- this.status =
609
- `All Hz Calibration: playing the convolved calibration tone...`.toString() +
610
- this.generateTemplate().toString();
611
- } else {
612
- throw new Error('Mode is incorrect');
613
- }
614
- this.emit('update', {message: this.status});
615
- this.stepNum += 1;
616
- console.log('sink sampling rate');
617
- console.log(this.sinkSamplingRate);
618
- console.log('source sampling rate');
619
- console.log(this.sourceSamplingRate);
620
- };
621
-
622
- /** .
623
- * .
624
- * .
625
- * Stops the audio with tapered offset
626
- *
627
- * @example
628
- */
629
- #stopCalibrationAudio = () => {
630
- this.calibrationNodes[0].stop(0);
631
- this.calibrationNodes = [];
632
- this.sourceNode.disconnect();
633
- this.stepNum += 1;
634
- console.log('stop calibration audio ' + this.stepNum);
635
- this.status =
636
- `All Hz Calibration: stopping the calibration tone...`.toString() +
637
- this.generateTemplate().toString();
638
- this.emit('update', {message: this.status});
639
- };
640
-
641
- playMLSwithIIR = async (stream, iir) => {
642
- let checkRec = false;
643
- this.mode = 'filtered';
644
- console.log('play mls with iir');
645
- this.invertedImpulseResponse = iir;
646
-
647
- await this.calibrationSteps(
648
- stream,
649
- this.#playCalibrationAudio, // play audio func (required)
650
- this.#createCalibrationNodeFromBuffer(this.#currentConvolution), // before play func
651
- this.#awaitSignalOnset, // before record
652
- () => this.numSuccessfulCaptured < 1,
653
- this.#awaitDesiredMLSLength, // during record
654
- this.#afterMLSwIIRRecord, // after record
655
- this.mode,
656
- checkRec
657
- );
658
- };
659
-
660
- /**
661
- * Public method to start the calibration process. Objects intialized from webassembly allocate new memory
662
- * and must be manually freed. This function is responsible for intializing the MlsGenInterface,
663
- * and wrapping the calibration steps with a garbage collection safe gaurd.
664
- *
665
- * @public
666
- * @param stream - The stream of audio from the Listener.
667
- * @example
668
- */
669
- startCalibrationImpulseResponse = async stream => {
670
- let desired_time = this.desired_time_per_mls;
671
- let checkRec = 'allhz';
672
-
673
- console.log('MLS sequence should be of length: ' + this.sourceSamplingRate * desired_time);
674
-
675
- length = this.sourceSamplingRate * desired_time;
676
- //get mls here
677
- await this.pyServerAPI
678
- .getMLSWithRetry(length)
679
- .then(res => {
680
- console.log(res);
681
- this.#mlsBufferView = res['mls'];
682
- })
683
- .catch(err => {
684
- // this.emit('InvertedImpulseResponse', {res: false});
685
- console.error(err);
686
- });
687
- this.numSuccessfulBackgroundCaptured = 0;
688
- if (this._calibrateSoundBackgroundSecs > 0){
689
- this.mode='background';
690
- this.status =
691
- `All Hz Calibration: sampling the background noise...`.toString() + this.generateTemplate().toString();
692
- this.emit('update', {message: this.status});
693
- await this.recordBackground(
694
- stream, //stream
695
- () => this.numSuccessfulBackgroundCaptured < 1, //loop condition
696
- this.#awaitBackgroundNoiseRecording, //sleep to record
697
- this.sendBackgroundRecording, //send to get PSD
698
- this.mode,
699
- checkRec
700
- )
701
- this.incrementStatusBar();
702
- }
703
- this.mode='unfiltered';
704
- this.numSuccessfulCaptured = 0;
705
-
706
- await this.calibrationSteps(
707
- stream,
708
- this.#playCalibrationAudio, // play audio func (required)
709
- this.#createCalibrationNodeFromBuffer(this.#mlsBufferView), // before play func
710
- this.#awaitSignalOnset, // before record
711
- () => this.numSuccessfulCaptured < this.numCaptures, // loop while true
712
- this.#awaitDesiredMLSLength, // during record
713
- this.#afterMLSRecord, // after record
714
- this.mode,
715
- checkRec
716
- ),
717
- this.#stopCalibrationAudio();
718
- checkRec = false;
719
-
720
- // at this stage we've captured all the required signals,
721
- // and have received IRs for each one
722
- // so let's send all the IRs to the server to be converted to a single IIR
723
- await this.sendSystemImpulseResponsesToServerForProcessing();
724
- await this.sendComponentImpulseResponsesToServerForProcessing();
725
-
726
- this.numSuccessfulCaptured = 0;
727
-
728
- let iir_ir_and_plots;
729
- if (this._calibrateSoundCheck != 'none') {
730
- if (this._calibrateSoundCheck != 'system') {
731
- this.#currentConvolution = this.componentConvolution;
732
- } else {
733
- this.#currentConvolution = this.systemConvolution;
734
- }
735
- await this.playMLSwithIIR(stream, this.invertedImpulseResponse);
736
- this.#stopCalibrationAudio();
737
- this.sourceAudioContext.close();
738
- let conv_recs = this.getAllFilteredRecordedSignals();
739
- let recs = this.getAllUnfilteredRecordedSignals();
740
- console.log(
741
- 'Obtaining unfiltered recording from #allHzUnfilteredRecordings to calculate PSD'
742
- );
743
- console.log('Obtaining filtered recording from #allHzFilteredRecordings to calculate PSD');
744
- let unconv_rec = recs[0];
745
- let conv_rec = conv_recs[0];
746
- if (this._calibrateSoundCheck != 'system') {
747
- let knownGain = this.oldComponentIR.Gain;
748
- let knownFreq = this.oldComponentIR.Freq;
749
- let sampleRate = this.sourceSamplingRate || 96000;
750
- let unconv_results = await this.pyServerAPI
751
- .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)
752
- .then(res => {
753
- this.incrementStatusBar();
754
- this.status =
755
- `All Hz Calibration: done computing the PSD graphs...`.toString() +
756
- this.generateTemplate().toString();
757
- this.emit('update', {message: this.status});
758
- return res;
759
- })
760
- .catch(err => {
761
- console.error(err);
762
- });
763
-
764
- let conv_results = await this.pyServerAPI
765
- .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)
766
- .then(res => {
767
- this.incrementStatusBar();
768
- this.status =
769
- `All Hz Calibration: done computing the PSD graphs...`.toString() +
770
- this.generateTemplate().toString();
771
- this.emit('update', {message: this.status});
772
- return res;
773
- })
774
- .catch(err => {
775
- console.error(err);
776
- });
777
- unconv_rec = this.componentInvertedImpulseResponseNoBandpass;
778
- conv_rec = this.componentInvertedImpulseResponse;
779
- let component_iir_psd = await this.pyServerAPI
780
- .getPSDWithRetry({
781
- unconv_rec,
782
- conv_rec,
783
- sampleRate: this.sourceSamplingRate || 96000,
784
- })
785
- .then(res => {
786
- this.incrementStatusBar();
787
- this.status =
788
- `All Hz Calibration: done computing the PSD graphs...`.toString() +
789
- this.generateTemplate().toString();
790
- this.emit('update', {message: this.status});
791
- return res;
792
- })
793
- .catch(err => {
794
- console.error(err);
795
- });
796
- unconv_rec = this.systemInvertedImpulseResponseNoBandpass;
797
- conv_rec = this.systemInvertedImpulseResponse;
798
- let system_iir_psd = await this.pyServerAPI
799
- .getPSDWithRetry({
800
- unconv_rec,
801
- conv_rec,
802
- sampleRate: this.sourceSamplingRate || 96000,
803
- })
804
- .then(res => {
805
- this.incrementStatusBar();
806
- this.status =
807
- `All Hz Calibration: done computing the PSD graphs...`.toString() +
808
- this.generateTemplate().toString();
809
- this.emit('update', {message: this.status});
810
- return res;
811
- })
812
- .catch(err => {
813
- console.error(err);
814
- });
815
- iir_ir_and_plots = {
816
- systemIIR: this.systemInvertedImpulseResponse,
817
- componentIIR: this.componentInvertedImpulseResponse,
818
- x_unconv: unconv_results['x'],
819
- y_unconv: unconv_results['y'],
820
- x_conv: conv_results['x'],
821
- y_conv: conv_results['y'],
822
- componentIR: this.componentIR,
823
- systemIR: this.systemIR,
824
- x_system_iir: system_iir_psd['x_conv'],
825
- y_system_iir: system_iir_psd['y_conv'],
826
- x_system_iir_no_bandpass: system_iir_psd['x_unconv'],
827
- y_system_iir_no_bandpass: system_iir_psd['y_unconv'],
828
- x_component_iir: component_iir_psd['x_conv'],
829
- y_component_iir: component_iir_psd['y_conv'],
830
- x_component_iir_no_bandpass: component_iir_psd['x_unconv'],
831
- y_component_iir_no_bandpass: component_iir_psd['y_unconv'],
832
- unconv_rec: recs[0],
833
- conv_rec: conv_recs[0],
834
- mls: this.#mls,
835
- componentConvolution: this.componentConvolution,
836
- systemConvolution: this.systemConvolution,
837
- autocorrelations:this.autocorrelations,
838
- impulseResponses: []
839
- };
840
- } else {
841
- let results = await this.pyServerAPI
842
- .getPSDWithRetry({
843
- unconv_rec,
844
- conv_rec,
845
- sampleRate: this.sourceSamplingRate || 96000,
846
- })
847
- .then(res => {
848
- this.incrementStatusBar();
849
- this.status =
850
- `All Hz Calibration: done computing the PSD graphs...`.toString() +
851
- this.generateTemplate().toString();
852
- this.emit('update', {message: this.status});
853
- return res;
854
- })
855
- .catch(err => {
856
- console.error(err);
857
- });
858
-
859
- //iir w/ and without bandpass psd
860
- unconv_rec = this.componentInvertedImpulseResponseNoBandpass;
861
- conv_rec = this.componentInvertedImpulseResponse;
862
- let component_iir_psd = await this.pyServerAPI
863
- .getPSDWithRetry({
864
- unconv_rec,
865
- conv_rec,
866
- sampleRate: this.sourceSamplingRate || 96000,
867
- })
868
- .then(res => {
869
- this.incrementStatusBar();
870
- this.status =
871
- `All Hz Calibration: done computing the PSD graphs...`.toString() +
872
- this.generateTemplate().toString();
873
- this.emit('update', {message: this.status});
874
- return res;
875
- })
876
- .catch(err => {
877
- console.error(err);
878
- });
879
- unconv_rec = this.systemInvertedImpulseResponseNoBandpass;
880
- conv_rec = this.systemInvertedImpulseResponse;
881
- let system_iir_psd = await this.pyServerAPI
882
- .getPSDWithRetry({
883
- unconv_rec,
884
- conv_rec,
885
- sampleRate: this.sourceSamplingRate || 96000,
886
- })
887
- .then(res => {
888
- this.incrementStatusBar();
889
- this.status =
890
- `All Hz Calibration: done computing the PSD graphs...`.toString() +
891
- this.generateTemplate().toString();
892
- this.emit('update', {message: this.status});
893
- return res;
894
- })
895
- .catch(err => {
896
- console.error(err);
897
- });
898
-
899
- iir_ir_and_plots = {
900
- systemIIR: this.systemInvertedImpulseResponse,
901
- componentIIR: this.componentInvertedImpulseResponse,
902
- x_unconv: results['x_unconv'],
903
- y_unconv: results['y_unconv'],
904
- x_conv: results['x_conv'],
905
- y_conv: results['y_conv'],
906
- componentIR: this.componentIR,
907
- systemIR: this.systemIR,
908
- x_system_iir: system_iir_psd['x_conv'],
909
- y_system_iir: system_iir_psd['y_conv'],
910
- x_system_iir_no_bandpass: system_iir_psd['x_unconv'],
911
- y_system_iir_no_bandpass: system_iir_psd['y_unconv'],
912
- x_component_iir: component_iir_psd['x_conv'],
913
- y_component_iir: component_iir_psd['y_conv'],
914
- x_component_iir_no_bandpass: component_iir_psd['x_unconv'],
915
- y_component_iir_no_bandpass: component_iir_psd['y_unconv'],
916
- unconv_rec: recs[0],
917
- conv_rec: conv_recs[0],
918
- mls: this.#mls,
919
- componentConvolution: this.componentConvolution,
920
- systemConvolution: this.systemConvolution,
921
- autocorrelations:this.autocorrelations,
922
- impulseResponses: []
923
- };
924
- }
925
- await Promise.all(this.impulseResponses).then(res => {
926
- for (let i = 0; i < res.length; i++) {
927
- if (res[i] != undefined) {
928
- iir_ir_and_plots['impulseResponses'].push(res[i])
929
- }
930
- }
931
- });
932
-
933
- if (this.#download) {
934
- this.downloadSingleUnfilteredRecording();
935
- this.downloadSingleFilteredRecording();
936
- saveToCSV(this.#mls, 'MLS.csv');
937
- saveToCSV(this.componentConvolution, 'python_component_convolution_mls_iir.csv');
938
- saveToCSV(this.systemConvolution, 'python_system_convolution_mls_iir.csv');
939
- saveToCSV(this.componentInvertedImpulseResponse, 'componentIIR.csv');
940
- saveToCSV(this.systemInvertedImpulseResponse, 'systemIIR.csv');
941
- for (let i = 0; i < this.autocorrelations.length; i++) {
942
- saveToCSV(this.autocorrelations[i], `autocorrelation_${i}`);
943
- }
944
- const computedIRagain = await Promise.all(this.impulseResponses).then(res => {
945
- for (let i = 0; i < res.length; i++) {
946
- if (res[i] != undefined) {
947
- saveToCSV(res[i], `IR_${i}`);
948
- }
949
- }
950
- });
951
- }
952
- } else {
953
- let unconv_rec = this.componentInvertedImpulseResponseNoBandpass;
954
- let conv_rec = this.componentInvertedImpulseResponse;
955
- let component_iir_psd = await this.pyServerAPI
956
- .getPSDWithRetry({
957
- unconv_rec,
958
- conv_rec,
959
- sampleRate: this.sourceSamplingRate || 96000,
960
- })
961
- .then(res => {
962
- this.incrementStatusBar();
963
- this.status =
964
- `All Hz Calibration: done computing the PSD graphs...`.toString() +
965
- this.generateTemplate().toString();
966
- this.emit('update', {message: this.status});
967
- return res;
968
- })
969
- .catch(err => {
970
- console.error(err);
971
- });
972
- unconv_rec = this.systemInvertedImpulseResponseNoBandpass;
973
- conv_rec = this.systemInvertedImpulseResponse;
974
- let system_iir_psd = await this.pyServerAPI
975
- .getPSDWithRetry({
976
- unconv_rec,
977
- conv_rec,
978
- sampleRate: this.sourceSamplingRate || 96000,
979
- })
980
- .then(res => {
981
- this.incrementStatusBar();
982
- this.status =
983
- `All Hz Calibration: done computing the PSD graphs...`.toString() +
984
- this.generateTemplate().toString();
985
- this.emit('update', {message: this.status});
986
- return res;
987
- })
988
- .catch(err => {
989
- console.error(err);
990
- });
991
- iir_ir_and_plots = {
992
- systemIIR: this.systemInvertedImpulseResponse,
993
- componentIIR: this.componentInvertedImpulseResponse,
994
- x_unconv: [],
995
- y_unconv: [],
996
- x_conv: [],
997
- y_conv: [],
998
- componentIR: this.componentIR,
999
- systemIR: this.systemIR,
1000
- x_system_iir: system_iir_psd['x_conv'],
1001
- y_system_iir: system_iir_psd['y_conv'],
1002
- x_system_iir_no_bandpass: system_iir_psd['x_unconv'],
1003
- y_system_iir_no_bandpass: system_iir_psd['y_unconv'],
1004
- x_component_iir: component_iir_psd['x_conv'],
1005
- y_component_iir: component_iir_psd['y_conv'],
1006
- x_component_iir_no_bandpass: component_iir_psd['x_unconv'],
1007
- y_component_iir_no_bandpass: component_iir_psd['y_unconv'],
1008
- unconv_rec: recs[0],
1009
- conv_rec: conv_recs[0],
1010
- mls: this.#mls,
1011
- componentConvolution: this.componentConvolution,
1012
- systemConvolution: this.systemConvolution,
1013
- autocorrelations:this.autocorrelations,
1014
- impulseResponses: []
1015
- };
1016
- await Promise.all(this.impulseResponses).then(res => {
1017
- for (let i = 0; i < res.length; i++) {
1018
- if (res[i] != undefined) {
1019
- iir_ir_and_plots['impulseResponses'].push(res[i])
1020
- }
1021
- }
1022
- });
1023
-
1024
- if (this.#download) {
1025
- saveToCSV(this.#mls, 'MLS.csv');
1026
- saveToCSV(this.componentConvolution, 'python_component_convolution_mls_iir.csv');
1027
- saveToCSV(this.systemConvolution, 'python_system_convolution_mls_iir.csv');
1028
- saveToCSV(this.componentInvertedImpulseResponse, 'componentIIR.csv');
1029
- saveToCSV(this.systemInvertedImpulseResponse, 'systemIIR.csv');
1030
- for (let i = 0; i < this.autocorrelations.length; i++) {
1031
- saveToCSV(this.autocorrelations[i], `autocorrelation_${i}`);
1032
- }
1033
- const computedIRagain = await Promise.all(this.impulseResponses).then(res => {
1034
- for (let i = 0; i < res.length; i++) {
1035
- if (res[i] != undefined) {
1036
- saveToCSV(res[i], `IR_${i}`);
1037
- }
1038
- }
1039
- });
1040
- }
1041
- }
1042
-
1043
- this.percent_complete = 100;
1044
-
1045
- this.status = `All Hz Calibration: Finished`.toString() + this.generateTemplate().toString();
1046
- this.emit('update', {message: this.status});
1047
-
1048
- //here after calibration we have the component calibration (either loudspeaker or microphone) in the same form as the componentIR
1049
- //that was used to calibrate
1050
-
1051
- return iir_ir_and_plots;
1052
- };
1053
-
1054
- //////////////////////volume
1055
-
1056
- handleIncomingData = data => {
1057
- console.log('Received data: ', data);
1058
- if (data.type === 'soundGainDBSPL') {
1059
- this.soundGainDBSPL = data.value;
1060
- } else {
1061
- throw new Error(`Unknown data type: ${data.type}`);
1062
- }
1063
- };
1064
- createSCurveBuffer = (onSetBool = true) => {
1065
- const curve = new Float32Array(this.TAPER_SECS * this.sourceSamplingRate + 1);
1066
- const frequency = 1 / (4 * this.TAPER_SECS);
1067
- let j = 0;
1068
- for (let i = 0; i < this.TAPER_SECS * this.sourceSamplingRate + 1; i += 1) {
1069
- const phase = 2 * Math.PI * frequency * j;
1070
- const onsetTaper = Math.pow(Math.sin(phase), 2);
1071
- const offsetTaper = Math.pow(Math.cos(phase), 2);
1072
- curve[i] = onSetBool ? onsetTaper : offsetTaper;
1073
- j += 1 / this.sourceSamplingRate;
1074
- }
1075
- return curve;
1076
- };
1077
-
1078
- #getTruncatedSignal = (left = 3.5, right = 4.5) => {
1079
- const start = Math.floor(left * this.sourceSamplingRate);
1080
- const end = Math.floor(right * this.sourceSamplingRate);
1081
- const result = Array.from(this.getLastVolumeRecordedSignal().slice(start, end));
1082
- console.log(
1083
- 'Obtaining last 1000 hz recording from #allVolumeRecordings to send for processing'
1084
- );
1085
- /**
1086
- * function to check that capture was properly made
1087
- * @param {*} list
1088
- */
1089
- const checkResult = list => {
1090
- const setItem = new Set(list);
1091
- if (setItem.size === 1 && setItem.has(0)) {
1092
- console.warn(
1093
- 'The last capture failed, all recorded signal is zero',
1094
- this.getAllVolumeRecordedSignals()
1095
- );
1096
- }
1097
- if (setItem.size === 0) {
1098
- console.warn('The last capture failed, no recorded signal');
1099
- }
1100
- };
1101
- checkResult(result);
1102
- return result;
1103
- };
1104
-
1105
- /**
1106
- *
1107
- *
1108
- Construct a calibration Node with the calibration parameters and given gain value
1109
- * @param {*} gainValue
1110
- * */
1111
- #createCalibrationToneWithGainValue = gainValue => {
1112
- const audioContext = this.makeNewSourceAudioContext();
1113
- const oscilator = audioContext.createOscillator();
1114
- const gainNode = audioContext.createGain();
1115
- const taperGainNode = audioContext.createGain();
1116
- const offsetGainNode = audioContext.createGain();
1117
- const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;
1118
-
1119
- oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;
1120
- oscilator.type = this.#CALIBRATION_TONE_TYPE;
1121
- gainNode.gain.value = gainValue;
1122
-
1123
- oscilator.connect(gainNode);
1124
- gainNode.connect(taperGainNode);
1125
- const onsetCurve = this.createSCurveBuffer();
1126
- taperGainNode.gain.setValueCurveAtTime(onsetCurve, 0, this.TAPER_SECS);
1127
- taperGainNode.connect(offsetGainNode);
1128
- const offsetCurve = this.createSCurveBuffer(false);
1129
- offsetGainNode.gain.setValueCurveAtTime(
1130
- offsetCurve,
1131
- totalDuration - this.TAPER_SECS,
1132
- this.TAPER_SECS
1133
- );
1134
- offsetGainNode.connect(audioContext.destination);
1135
-
1136
- this.addCalibrationNode(oscilator);
1137
- };
1138
-
1139
- /**
1140
- * Construct a Calibration Node with the calibration parameters.
1141
- *
1142
- * @private
1143
- * @example
1144
- */
1145
- #createCalibrationNode = () => {
1146
- const audioContext = this.makeNewSourceAudioContext();
1147
- const oscilator = audioContext.createOscillator();
1148
- const gainNode = audioContext.createGain();
1149
-
1150
- oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;
1151
- oscilator.type = this.#CALIBRATION_TONE_TYPE;
1152
- gainNode.gain.value = 0.04;
1153
-
1154
- oscilator.connect(gainNode);
1155
- gainNode.connect(audioContext.destination);
1156
-
1157
- this.addCalibrationNode(oscilator);
1158
- };
1159
-
1160
- #playCalibrationAudioVolume = async () => {
1161
- const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;
1162
-
1163
- this.calibrationNodes[0].start(0);
1164
- this.calibrationNodes[0].stop(totalDuration);
1165
- console.log(`Playing a buffer of ${this.CALIBRATION_TONE_DURATION} seconds of audio`);
1166
- console.log(`Waiting a total of ${totalDuration} seconds`);
1167
- await sleep(totalDuration);
1168
- };
1169
-
1170
- #sendToServerForProcessing = (lCalib) => {
1171
- console.log('Sending data to server');
1172
- let left = this.calibrateSound1000HzPreSec
1173
- let right = this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec
1174
- this.pyServerAPI
1175
- .getVolumeCalibration({
1176
- sampleRate: this.sourceSamplingRate,
1177
- payload: this.#getTruncatedSignal(left,right),
1178
- lCalib: lCalib,
1179
- })
1180
- .then(res => {
1181
- if (this.outDBSPL === null) {
1182
- this.incrementStatusBar();
1183
- this.outDBSPL = res['outDbSPL'];
1184
- this.outDBSPL1000 = res['outDbSPL1000'];
1185
- this.THD = res['thd'];
1186
- }
1187
- })
1188
- .catch(err => {
1189
- console.warn(err);
1190
- });
1191
- };
1192
-
1193
- startCalibrationVolume = async (stream, gainValues, lCalib, componentGainDBSPL) => {
1194
- const trialIterations = gainValues.length;
1195
- this.status_denominator += trialIterations;
1196
- const thdValues = [];
1197
- const inDBValues = [];
1198
- let inDB = 0;
1199
- const outDBSPLValues = [];
1200
- const outDBSPL1000Values = [];
1201
- let checkRec = false;
1202
-
1203
- // do one calibration that will be discarded
1204
- const soundLevelToDiscard = -60;
1205
- const gainToDiscard = Math.pow(10, soundLevelToDiscard / 20);
1206
- this.status =
1207
- `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`.toString() +
1208
- this.generateTemplate().toString();
1209
- //this.emit('update', {message: `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`});
1210
- this.emit('update', {message: this.status});
1211
-
1212
- do {
1213
- // eslint-disable-next-line no-await-in-loop
1214
- await this.volumeCalibrationSteps(
1215
- stream,
1216
- this.#playCalibrationAudioVolume,
1217
- this.#createCalibrationToneWithGainValue,
1218
- this.#sendToServerForProcessing,
1219
- gainToDiscard,
1220
- lCalib, //todo make this a class parameter
1221
- checkRec
1222
- );
1223
- } while (this.outDBSPL === null);
1224
- //reset the values
1225
- //this.incrementStatusBar();
1226
-
1227
- this.outDBSPL = null;
1228
- this.outDBSPL = null;
1229
- this.outDBSPL1000 = null;
1230
- this.THD = null;
1231
-
1232
- // run the calibration at different gain values provided by the user
1233
- for (let i = 0; i < trialIterations; i++) {
1234
- //convert gain to DB and add to inDB
1235
- if (i == trialIterations - 1) {
1236
- checkRec = 'loudest';
1237
- }
1238
- inDB = Math.log10(gainValues[i]) * 20;
1239
- // precision to 1 decimal place
1240
- inDB = Math.round(inDB * 10) / 10;
1241
- inDBValues.push(inDB);
1242
- console.log('next update');
1243
- this.status =
1244
- `1000 Hz Calibration: Sound Level ${inDB} dB`.toString() +
1245
- this.generateTemplate().toString();
1246
- this.emit('update', {message: this.status});
1247
- do {
1248
- // eslint-disable-next-line no-await-in-loop
1249
- await this.volumeCalibrationSteps(
1250
- stream,
1251
- this.#playCalibrationAudioVolume,
1252
- this.#createCalibrationToneWithGainValue,
1253
- this.#sendToServerForProcessing,
1254
- gainValues[i],
1255
- lCalib, //todo make this a class parameter
1256
- checkRec
1257
- );
1258
- } while (this.outDBSPL === null);
1259
- outDBSPL1000Values.push(this.outDBSPL1000);
1260
- thdValues.push(this.THD);
1261
- outDBSPLValues.push(this.outDBSPL);
1262
-
1263
- this.outDBSPL = null;
1264
- this.outDBSPL1000 = null;
1265
- this.THD = null;
1266
- }
1267
-
1268
- // get the volume calibration parameters from the server
1269
- const parameters = await this.pyServerAPI
1270
- .getVolumeCalibrationParameters({
1271
- inDBValues: inDBValues,
1272
- outDBSPLValues: outDBSPL1000Values,
1273
- lCalib: lCalib,
1274
- componentGainDBSPL,
1275
- })
1276
- .then(res => {
1277
- this.incrementStatusBar();
1278
- return res;
1279
- });
1280
- const result = {
1281
- parameters: parameters,
1282
- inDBValues: inDBValues,
1283
- outDBSPLValues: outDBSPLValues,
1284
- outDBSPL1000Values: outDBSPL1000Values,
1285
- thdValues: thdValues,
1286
- };
1287
-
1288
- return result;
1289
- };
1290
-
1291
- // function to write frq and gain to firebase database given speakerID
1292
- writeFrqGain = async (speakerID, frq, gain, OEM) => {
1293
- // freq and gain are too large to take samples 1 in every 100 samples
1294
-
1295
- const sampledFrq = [];
1296
- const sampledGain = [];
1297
- for (let i = 0; i < frq.length; i += 100) {
1298
- sampledFrq.push(frq[i]);
1299
- sampledGain.push(gain[i]);
1300
- }
1301
-
1302
- const data = {Freq: sampledFrq, Gain: sampledGain};
1303
-
1304
- await set(ref(database, `Microphone2/${OEM}/${speakerID}/linear`), data);
1305
- };
1306
-
1307
- // Function to Read frq and gain from firebase database given speakerID
1308
- // returns an array of frq and gain if speakerID exists, returns null otherwise
1309
-
1310
- readFrqGain = async (speakerID, OEM) => {
1311
- const dbRef = ref(database);
1312
- const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}/linear`));
1313
- if (snapshot.exists()) {
1314
- return snapshot.val();
1315
- }
1316
- return null;
1317
- };
1318
-
1319
- readGainat1000Hz = async (speakerID, OEM) => {
1320
- const dbRef = ref(database);
1321
- const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}/Gain1000`));
1322
- if (snapshot.exists()) {
1323
- return snapshot.val();
1324
- }
1325
- return null;
1326
- };
1327
-
1328
- writeGainat1000Hz = async (speakerID, gain, OEM) => {
1329
- const data = {Gain: gain};
1330
- await set(ref(database, `Microphone2/${OEM}/${speakerID}/Gain1000`), gain);
1331
- };
1332
-
1333
- writeIsSmartPhone = async (speakerID, isSmartPhone, OEM) => {
1334
- const data = {isSmartPhone: isSmartPhone};
1335
- await set(ref(database, `Microphone2/${OEM}/${speakerID}/isSmartPhone`), isSmartPhone);
1336
- };
1337
-
1338
- doesMicrophoneExist = async (speakerID, OEM) => {
1339
- const dbRef = ref(database);
1340
- const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}`));
1341
- if (snapshot.exists()) {
1342
- return true;
1343
- }
1344
- return false;
1345
- };
1346
-
1347
- addMicrophoneInfo = async (speakerID, OEM, micInfo) => {
1348
- // add to database if /info does not exist
1349
- const dbRef = ref(database);
1350
- const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}/info`));
1351
- if (!snapshot.exists()) {
1352
- await set(ref(database, `Microphone2/${OEM}/${speakerID}/info`), micInfo);
1353
- }
1354
- };
1355
-
1356
- convertToDB = gain => {
1357
- return Math.log10(gain) * 20;
1358
- };
1359
-
1360
- // Function to perform linear interpolation between two points
1361
- interpolate(x, x0, y0, x1, y1) {
1362
- return y0 + ((x - x0) * (y1 - y0)) / (x1 - x0);
1363
- }
1364
-
1365
- findGainatFrequency = (frequencies, gains, targetFrequency) => {
1366
- // Find the index of the first frequency in the array greater than the target frequency
1367
- let index = 0;
1368
- while (index < frequencies.length && frequencies[index] < targetFrequency) {
1369
- index++;
1370
- }
1371
-
1372
- // Handle cases when the target frequency is outside the range of the given data
1373
- if (index === 0) {
1374
- return gains[0];
1375
- } else if (index === frequencies.length) {
1376
- return gains[gains.length - 1];
1377
- } else {
1378
- // Interpolate the gain based on the surrounding frequencies
1379
- const x0 = frequencies[index - 1];
1380
- const y0 = gains[index - 1];
1381
- const x1 = frequencies[index];
1382
- const y1 = gains[index];
1383
- return this.interpolate(targetFrequency, x0, y0, x1, y1);
1384
- }
1385
- };
1386
-
1387
- // Example of how to use the writeFrqGain and readFrqGain functions
1388
- // writeFrqGain('speaker1', [1, 2, 3], [4, 5, 6]);
1389
- // Speaker1 is the speakerID you want to write to in the database
1390
- // readFrqGain('MiniDSPUMIK_1').then(data => console.log(data));
1391
- // MiniDSPUMIK_1 is the speakerID with some Data in the database
1392
- //adding gainDBSPL
1393
- startCalibration = async (
1394
- stream,
1395
- gainValues,
1396
- lCalib = 104.92978421490648,
1397
- componentIR = null,
1398
- microphoneName = 'MiniDSP-UMIK1-711-4754-vertical',
1399
- _calibrateSoundCheck = 'goal', //GOAL PASSed in by default
1400
- isSmartPhone = false,
1401
- _calibrateSoundBurstRepeats = 4,
1402
- _calibrateSoundBurstSec = 1,
1403
- _calibrateSoundBurstsWarmup = 1,
1404
- _calibrateSoundHz = 48000,
1405
- _calibrateSoundIIRSec = 0.2,
1406
- calibrateSound1000HzPreSec = 3.5,
1407
- calibrateSound1000HzSec = 1.0,
1408
- calibrateSound1000HzPostSec = 0.5,
1409
- _calibrateSoundBackgroundSecs = 0,
1410
- micManufacturer = '',
1411
- micSerialNumber = '',
1412
- micModelNumber = '',
1413
- micModelName = ''
1414
- ) => {
1415
- this.CALIBRATION_TONE_DURATION =
1416
- calibrateSound1000HzPreSec + calibrateSound1000HzSec + calibrateSound1000HzPostSec;
1417
- this.calibrateSound1000HzPreSec = calibrateSound1000HzPreSec;
1418
- this.calibrateSound1000HzSec = calibrateSound1000HzSec;
1419
- this.calibrateSound1000HzPostSec = calibrateSound1000HzPostSec;
1420
- this.iirLength = Math.floor(_calibrateSoundIIRSec * this.sourceSamplingRate);
1421
- console.log('device info:', this.deviceInfo);
1422
- this.numMLSPerCapture = _calibrateSoundBurstRepeats;
1423
- this.desired_time_per_mls = _calibrateSoundBurstSec;
1424
- this.num_mls_to_skip = _calibrateSoundBurstsWarmup;
1425
- this.desired_sampling_rate = _calibrateSoundHz;
1426
- this._calibrateSoundBackgroundSecs = _calibrateSoundBackgroundSecs;
1427
-
1428
- //feed calibration goal here
1429
- this._calibrateSoundCheck = _calibrateSoundCheck;
1430
- //check if a componentIR was given to the system, if it isn't check for the microphone. using dummy data here bc we need to
1431
- //check the db based on the microphone currently connected
1432
-
1433
- //new lCalib found at top of calibration files *1000hz, make sure to correct
1434
- //based on zeroing of 1000hz, search for "*1000Hz"
1435
- const ID = isSmartPhone ? micModelNumber : micSerialNumber;
1436
- const OEM = isSmartPhone ? this.deviceInfo.OEM : micManufacturer;
1437
- // const ID = "711-4754";
1438
- // const OEM = "MiniDSP";
1439
- const micInfo = {
1440
- micModelName: isSmartPhone ? micModelName : microphoneName,
1441
- OEM: OEM,
1442
- ID: ID,
1443
- HardwareName: isSmartPhone ? this.deviceInfo.hardwarename : microphoneName,
1444
- hardwareFamily: isSmartPhone ? this.deviceInfo.hardwarefamily : microphoneName,
1445
- HardwareModel: isSmartPhone ? this.deviceInfo.hardwaremodel : microphoneName,
1446
- PlatformName: isSmartPhone ? this.deviceInfo.platformname : 'N/A',
1447
- PlatformVersion: isSmartPhone ? this.deviceInfo.platformversion : 'N/A',
1448
- DeviceType: isSmartPhone ? this.deviceInfo.devicetype : 'N/A',
1449
- };
1450
- this.addMicrophoneInfo(ID, OEM, micInfo);
1451
- if (componentIR == null) {
1452
- //mode 'ir'
1453
- //global variable this.componentIR must be set
1454
- this.componentIR = await this.readFrqGain(ID, OEM).then(data => {
1455
- return data;
1456
- });
1457
-
1458
- lCalib = await this.readGainat1000Hz(ID, OEM);
1459
- micInfo['gainDBSPL'] = lCalib;
1460
- // this.componentGainDBSPL = this.convertToDB(lCalib);
1461
- this.componentGainDBSPL = lCalib;
1462
- //TODO: if this call to database is unknown, cannot perform experiment => return false
1463
- if (this.componentIR == null) {
1464
- this.status =
1465
- `Microphone (${OEM},${ID}) is not found in the database. Please add it to the database.`.toString();
1466
- this.emit('update', {message: this.status});
1467
- return false;
1468
- }
1469
- } else {
1470
- this.componentIR = componentIR;
1471
- lCalib = this.findGainatFrequency(this.componentIR.Freq, this.componentIR.Gain, 1000);
1472
- // this.componentGainDBSPL = this.convertToDB(lCalib);
1473
- this.componentGainDBSPL = lCalib;
1474
- await this.writeIsSmartPhone(ID, isSmartPhone, OEM);
1475
- }
1476
-
1477
- this.oldComponentIR = this.componentIR;
1478
-
1479
- let volumeResults = await this.startCalibrationVolume(
1480
- stream,
1481
- gainValues,
1482
- lCalib,
1483
- this.componentGainDBSPL
1484
- );
1485
-
1486
- let impulseResponseResults = await this.startCalibrationImpulseResponse(stream);
1487
- impulseResponseResults['background_noise'] = this.background_noise;
1488
- if (componentIR != null) {
1489
- //insert Freq and Gain from this.componentIR into db
1490
- await this.writeFrqGain(
1491
- ID,
1492
- impulseResponseResults.componentIR.Freq,
1493
- impulseResponseResults.componentIR.Gain,
1494
- OEM
1495
- );
1496
- micInfo['gainDBSPL'] = impulseResponseResults.parameters.gainDBSPL;
1497
- await this.writeGainat1000Hz(ID, micInfo['gainDBSPL'], OEM);
1498
- }
1499
-
1500
- const total_results = {...volumeResults, ...impulseResponseResults};
1501
-
1502
- total_results['micInfo'] = micInfo;
1503
- console.log('total results');
1504
- console.log(total_results);
1505
- return total_results;
1506
- };
1507
- }
1508
-
1509
- export default Combination;
1
+ import AudioCalibrator from '../audioCalibrator';
2
+
3
+ import {sleep, csvToArray, saveToCSV} from '../../utils';
4
+ import database from '../../config/firebase';
5
+ import {ref, set, get, child} from 'firebase/database';
6
+
7
+ /**
8
+ *
9
+ */
10
+ class Combination extends AudioCalibrator {
11
+ /**
12
+ * Default constructor. Creates an instance with any number of paramters passed or the default parameters defined here.
13
+ *
14
+ * @param {Object<boolean, number, number, number>} calibratorParams - paramter object
15
+ * @param {boolean} [calibratorParams.download = false] - boolean flag to download captures
16
+ * @param {number} [calibratorParams.mlsOrder = 18] - order of the MLS to be generated
17
+ * @param {number} [calibratorParams.numCaptures = 5] - number of captures to perform
18
+ * @param {number} [calibratorParams.numMLSPerCapture = 4] - number of bursts of MLS per capture
19
+ */
20
+ constructor({
21
+ download = false,
22
+ mlsOrder = 18,
23
+ numCaptures = 3,
24
+ numMLSPerCapture = 4,
25
+ lowHz = 20,
26
+ highHz = 10000,
27
+ }) {
28
+ super(numCaptures, numMLSPerCapture);
29
+ this.#mlsOrder = parseInt(mlsOrder, 10);
30
+ this.#P = 2 ** mlsOrder - 1;
31
+ this.#download = download;
32
+ this.#mls = [];
33
+ this.#lowHz = lowHz;
34
+ this.#highHz = highHz;
35
+ }
36
+
37
+ /** @private */
38
+ stepNum = 0;
39
+
40
+ /** @private */
41
+ totalSteps = 25;
42
+
43
+ /** @private */
44
+ #download;
45
+
46
+ /** @private */
47
+ #mlsGenInterface;
48
+
49
+ /** @private */
50
+ #mlsBufferView;
51
+
52
+ /** @private */
53
+ componentInvertedImpulseResponse = null;
54
+
55
+ /** @private */
56
+ systemInvertedImpulseResponse = null;
57
+
58
+ //averaged and subtracted ir returned from calibration used to calculated iir
59
+ /** @private */
60
+ ir = null;
61
+
62
+ /** @private */
63
+ impulseResponses = [];
64
+
65
+ /** @private */
66
+ #mlsOrder;
67
+
68
+ /** @private */
69
+ #lowHz;
70
+
71
+ /** @private */
72
+ #highHz;
73
+
74
+ /** @private */
75
+ #mls;
76
+
77
+ /** @private */
78
+ #P;
79
+
80
+ /** @private */
81
+ #audioContext;
82
+
83
+ /** @private */
84
+ TAPER_SECS = 5;
85
+
86
+ /** @private */
87
+ offsetGainNode;
88
+
89
+ /** @private */
90
+ componentConvolution;
91
+
92
+ /** @private */
93
+ systemConvolution;
94
+
95
+ ////////////////////////volume
96
+ /** @private */
97
+ #CALIBRATION_TONE_FREQUENCY = 1000; // Hz
98
+
99
+ /** @private */
100
+ #CALIBRATION_TONE_TYPE = 'sine';
101
+
102
+ CALIBRATION_TONE_DURATION = 5; // seconds
103
+ calibrateSound1000HzPreSec = 3.5;
104
+ calibrateSound1000HzSec = 1.0;
105
+ calibrateSound1000HzPostSec = 0.5;
106
+
107
+
108
+ /** @private */
109
+ outDBSPL = null;
110
+ THD = null;
111
+ outDBSPL1000 = null;
112
+
113
+ /** @private */
114
+ TAPER_SECS = 0.01; // seconds
115
+
116
+ /** @private */
117
+ status_denominator = 8;
118
+
119
+ /** @private */
120
+ status_numerator = 0;
121
+
122
+ /** @private */
123
+ percent_complete = 0;
124
+
125
+ /** @private */
126
+ status = ``;
127
+
128
+ /**@private */
129
+ status_literal = `<div style="display: flex; justify-content: center;"><div style="width: 200px; height: 20px; border: 2px solid #000; border-radius: 10px;"><div style="width: ${this.percent_complete}%; height: 100%; background-color: #00aaff; border-radius: 8px;"></div></div></div>`;
130
+
131
+ /**@private */
132
+ componentIR = null;
133
+
134
+ /**@private */
135
+ oldComponentIR = null;
136
+
137
+ /**@private */
138
+ systemIR = null;
139
+
140
+ /**@private */
141
+ _calibrateSoundCheck = '';
142
+
143
+ deviceType = null;
144
+
145
+ deviceName = null;
146
+
147
+ deviceInfo = null;
148
+
149
+ desired_time_per_mls = 0;
150
+
151
+ num_mls_to_skip = 0;
152
+
153
+ desired_sampling_rate = 0;
154
+
155
+ #currentConvolution = [];
156
+
157
+ mode = 'unfiltered';
158
+
159
+ sourceNode;
160
+
161
+ autocorrelations = [];
162
+
163
+ iirLength = 0;
164
+
165
+ componentInvertedImpulseResponseNoBandpass = [];
166
+
167
+ systemInvertedImpulseResponseNoBandpass = [];
168
+
169
+ _calibrateSoundBackgroundSecs;
170
+
171
+ background_noise = {};
172
+
173
+ numSuccessfulBackgroundCaptured;
174
+
175
+ /**generate string template that gets reevaluated as variable increases */
176
+ generateTemplate = () => {
177
+ if (this.percent_complete > 100) {
178
+ this.percent_complete = 100;
179
+ }
180
+ const template = `<div style="display: flex; justify-content: center;"><div style="width: 800px; height: 20px; border: 2px solid #000; border-radius: 10px;"><div style="width: ${this.percent_complete}%; height: 100%; background-color: #00aaff; border-radius: 8px;"></div></div></div>`;
181
+ return template;
182
+ };
183
+
184
+ /** increment numerator and percent for status bar */
185
+ incrementStatusBar = () => {
186
+ this.status_numerator += 1;
187
+ this.percent_complete = (this.status_numerator / this.status_denominator) * 100;
188
+ };
189
+
190
+ setDeviceType = deviceType => {
191
+ this.deviceType = deviceType;
192
+ };
193
+
194
+ setDeviceName = deviceName => {
195
+ this.deviceName = deviceName;
196
+ };
197
+
198
+ setDeviceInfo = deviceInfo => {
199
+ this.deviceInfo = deviceInfo;
200
+ };
201
+
202
+ /** .
203
+ * .
204
+ * .
205
+ * Sends all the computed impulse responses to the backend server for processing
206
+ *
207
+ * @returns sets the resulting inverted impulse response to the class property
208
+ * @example
209
+ */
210
+ sendSystemImpulseResponsesToServerForProcessing = async () => {
211
+ const computedIRs = await Promise.all(this.impulseResponses);
212
+ const filteredComputedIRs = computedIRs.filter(element => {
213
+ return element != undefined;
214
+ }); //log any errors that are found in this step
215
+ const mls = this.#mls;
216
+ const lowHz = this.#lowHz; //gain of 1 below cutoff, need gain of 0
217
+ const highHz = this.#highHz; //check error for anything other than 10 kHz
218
+ const iirLength = this.iirLength;
219
+ const num_periods = this.numMLSPerCapture + this.num_mls_to_skip;
220
+ this.stepNum += 1;
221
+ console.log('send impulse responses to server: ' + this.stepNum);
222
+ this.status =
223
+ `All Hz Calibration: computing the IIR...`.toString() + this.generateTemplate().toString();
224
+ this.emit('update', {message: this.status});
225
+ return this.pyServerAPI
226
+ .getSystemInverseImpulseResponseWithRetry({
227
+ payload: filteredComputedIRs.slice(0, this.numCaptures),
228
+ mls,
229
+ lowHz,
230
+ highHz,
231
+ iirLength,
232
+ num_periods,
233
+ sampleRate: this.sourceSamplingRate || 96000,
234
+ })
235
+ .then(res => {
236
+ console.log(res);
237
+ this.stepNum += 1;
238
+ console.log('got impulse response ' + this.stepNum);
239
+ this.incrementStatusBar();
240
+ this.status =
241
+ `All Hz Calibration: done computing the IIR...`.toString() +
242
+ this.generateTemplate().toString();
243
+ this.emit('update', {message: this.status});
244
+ this.systemInvertedImpulseResponse = res['iir'];
245
+ this.systemIR = res['ir'];
246
+ this.systemConvolution = res['convolution'];
247
+ this.systemInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];
248
+ })
249
+ .catch(err => {
250
+ console.error(err);
251
+ });
252
+ };
253
+
254
+ /** .
255
+ * .
256
+ * .
257
+ * Sends all the computed impulse responses to the backend server for processing
258
+ *
259
+ * @returns sets the resulting inverted impulse response to the class property
260
+ * @example
261
+ */
262
+ sendComponentImpulseResponsesToServerForProcessing = async () => {
263
+ const computedIRs = await Promise.all(this.impulseResponses);
264
+ const filteredComputedIRs = computedIRs.filter(element => {
265
+ return element != undefined;
266
+ });
267
+ const componentIRGains = this.componentIR['Gain'];
268
+ const componentIRFreqs = this.componentIR['Freq'];
269
+ const mls = this.#mls;
270
+ const lowHz = this.#lowHz;
271
+ const iirLength = this.iirLength;
272
+ const num_periods = this.numMLSPerCapture + this.num_mls_to_skip;
273
+ const highHz = this.#highHz;
274
+ this.stepNum += 1;
275
+ console.log('send impulse responses to server: ' + this.stepNum);
276
+ this.status =
277
+ `All Hz Calibration: computing the IIR...`.toString() + this.generateTemplate().toString();
278
+ this.emit('update', {message: this.status});
279
+ return this.pyServerAPI
280
+ .getComponentInverseImpulseResponseWithRetry({
281
+ payload: filteredComputedIRs.slice(0, this.numCaptures),
282
+ mls,
283
+ lowHz,
284
+ highHz,
285
+ iirLength,
286
+ componentIRGains,
287
+ componentIRFreqs,
288
+ num_periods,
289
+ sampleRate: this.sourceSamplingRate || 96000,
290
+ })
291
+ .then(res => {
292
+ console.log(res);
293
+ this.stepNum += 1;
294
+ console.log('got impulse response ' + this.stepNum);
295
+ this.incrementStatusBar();
296
+ this.status =
297
+ `All Hz Calibration: done computing the IIR...`.toString() +
298
+ this.generateTemplate().toString();
299
+ this.emit('update', {message: this.status});
300
+ this.componentInvertedImpulseResponse = res['iir'];
301
+ this.componentIR['Gain'] = res['ir'];
302
+ this.componentIR['Freq'] = res['frequencies'];
303
+ this.componentConvolution = res['convolution'];
304
+ this.componentInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];
305
+ })
306
+ .catch(err => {
307
+ // this.emit('InvertedImpulseResponse', {res: false});
308
+ console.error(err);
309
+ });
310
+ };
311
+
312
+ sendBackgroundRecording = () => {
313
+ const allSignals = this.getAllBackgroundRecordings();
314
+ const numSignals = allSignals.length;
315
+ const background_rec_whole = allSignals[numSignals-1];
316
+ const fraction = .5/(this._calibrateSoundBackgroundSecs + .5);
317
+ // Calculate the starting index for slicing the array
318
+ const startIndex = Math.round(fraction * background_rec_whole.length);
319
+ // Slice the array from the calculated start index to the end of the array
320
+ const background_rec = background_rec_whole.slice(startIndex);
321
+ console.log('Sending background recording to server for processing');
322
+ this.pyServerAPI
323
+ .getBackgroundNoisePSDWithRetry({
324
+ background_rec,
325
+ sampleRate: this.sourceSamplingRate || 96000,
326
+ })
327
+ .then(res => {
328
+ if (this.numSuccessfulBackgroundCaptured < 1) {
329
+ this.numSuccessfulBackgroundCaptured += 1;
330
+ //storing all background data in background_psd object
331
+ this.background_noise['x_background'] = res['x_background'];
332
+ this.background_noise['y_background'] = res['y_background'];
333
+ this.background_noise['recording'] = background_rec;
334
+ }
335
+ })
336
+ .catch(err => {
337
+ console.error(err);
338
+ });
339
+ }
340
+
341
+ /** .
342
+ * .
343
+ * .
344
+ * Sends the recorded signal, or a given csv string of a signal, to the back end server for processing
345
+ *
346
+ * @param {<array>String} signalCsv - Optional csv string of a previously recorded signal, if given, this signal will be processed
347
+ * @example
348
+ */
349
+ sendRecordingToServerForProcessing = signalCsv => {
350
+ const allSignals = this.getAllUnfilteredRecordedSignals();
351
+ console.log(
352
+ 'Obtaining last all hz unfiltered recording from #allHzUnfilteredRecordings to send to server for processing'
353
+ );
354
+ const numSignals = allSignals.length;
355
+ const mls = this.#mls;
356
+ const payload =
357
+ signalCsv && signalCsv.length > 0 ? csvToArray(signalCsv) : allSignals[numSignals - 1];
358
+ console.log('sending rec');
359
+ this.stepNum += 1;
360
+ console.log('send rec ' + this.stepNum);
361
+ this.status =
362
+ `All Hz Calibration Step: computing the IR of the last recording...`.toString() +
363
+ this.generateTemplate().toString();
364
+ this.emit('update', {message: this.status});
365
+ this.impulseResponses.push(
366
+ this.pyServerAPI
367
+ .getImpulseResponse({
368
+ sampleRate: this.sourceSamplingRate || 96000,
369
+ payload,
370
+ mls,
371
+ P: this.#P, //get rid of this
372
+ numPeriods: this.numMLSPerCapture,
373
+ })
374
+ .then(res => {
375
+ if (this.numSuccessfulCaptured < this.numCaptures) {
376
+ this.numSuccessfulCaptured += 1;
377
+ console.log('num succ capt: ' + this.numSuccessfulCaptured);
378
+ this.stepNum += 1;
379
+ console.log('got impulse response ' + this.stepNum);
380
+ this.incrementStatusBar();
381
+ this.status =
382
+ `All Hz Calibration: ${this.numSuccessfulCaptured}/${this.numCaptures} IRs computed...`.toString() +
383
+ this.generateTemplate().toString();
384
+ this.emit('update', {
385
+ message: this.status,
386
+ });
387
+ this.autocorrelations.push(res['autocorrelation']);
388
+ return res['ir'];
389
+ }
390
+ })
391
+ .catch(err => {
392
+ console.error(err);
393
+ })
394
+ );
395
+ };
396
+
397
+ /**
398
+ * Passed to the calibration steps function, awaits the desired amount of seconds to capture the desired number
399
+ * of MLS periods defined in the constructor.
400
+ *
401
+ * @example
402
+ */
403
+ #awaitDesiredMLSLength = async () => {
404
+ // seconds per MLS = P / SR
405
+ // await N * P / SR
406
+ this.stepNum += 1;
407
+ console.log('await desired length ' + this.stepNum);
408
+ this.status =
409
+ `All Hz Calibration: sampling the calibration signal...`.toString() +
410
+ `\niteration ${this.stepNum}` +
411
+ this.generateTemplate();
412
+ this.emit('update', {
413
+ message: this.status,
414
+ });
415
+ let time_to_wait = 0;
416
+ if (this.mode === 'unfiltered') {
417
+ time_to_wait = (this.#mls.length / this.sourceSamplingRate) * this.numMLSPerCapture;
418
+ time_to_wait = time_to_wait * 1.1;
419
+ } else if (this.mode === 'filtered') {
420
+ time_to_wait =
421
+ (this.#currentConvolution.length / this.sourceSamplingRate) *
422
+ (this.numMLSPerCapture / (this.num_mls_to_skip + this.numMLSPerCapture));
423
+ } else {
424
+ throw new Error('Mode broke in awaitDesiredMLSLength');
425
+ }
426
+
427
+ await sleep(time_to_wait);
428
+ };
429
+
430
+ /**
431
+ * Passed to the background noise recording function, awaits the desired amount of seconds to capture the desired number
432
+ * of seconds of background noise
433
+ *
434
+ * @example
435
+ */
436
+ #awaitBackgroundNoiseRecording = async () => {
437
+ console.log('Waiting ' + this._calibrateSoundBackgroundSecs + " second(s) to record background noise");
438
+ let time_to_wait = this._calibrateSoundBackgroundSecs + .5;
439
+ await sleep(time_to_wait);
440
+ };
441
+
442
+
443
+ /** .
444
+ * .
445
+ * .
446
+ * Passed to the calibration steps function, awaits the onset of the signal to ensure a steady state
447
+ *
448
+ * @example
449
+ */
450
+ #awaitSignalOnset = async () => {
451
+ this.stepNum += 1;
452
+ console.log('await signal onset ' + this.stepNum);
453
+ this.status =
454
+ `All Hz Calibration: waiting for the signal to stabilize...`.toString() +
455
+ this.generateTemplate();
456
+ this.emit('update', {
457
+ message: this.status,
458
+ });
459
+ let number_of_bursts_to_skip = this.num_mls_to_skip;
460
+ let time_to_sleep = 0;
461
+ if (this.mode === 'unfiltered') {
462
+ time_to_sleep = (this.#mls.length / this.sourceSamplingRate) * number_of_bursts_to_skip;
463
+ } else if (this.mode === 'filtered') {
464
+ console.log(this.#currentConvolution.length);
465
+ time_to_sleep =
466
+ (this.#currentConvolution.length / this.sourceSamplingRate) *
467
+ (number_of_bursts_to_skip / (number_of_bursts_to_skip + this.numMLSPerCapture));
468
+ } else {
469
+ throw new Error('Mode broke in awaitSignalOnset');
470
+ }
471
+ await sleep(time_to_sleep);
472
+ };
473
+
474
+ /**
475
+ * Called immediately after a recording is captured. Used to process the resulting signal
476
+ * whether by sending the result to a server or by computing a result locally.
477
+ *
478
+ * @example
479
+ */
480
+ #afterMLSRecord = () => {
481
+ console.log('after record');
482
+ this.sendRecordingToServerForProcessing();
483
+ };
484
+
485
+ #afterMLSwIIRRecord = () => {
486
+ if (this.numSuccessfulCaptured < 1) {
487
+ this.numSuccessfulCaptured += 1;
488
+ this.stepNum += 1;
489
+ this.incrementStatusBar();
490
+ console.log('after mls w iir record for some reason add numSucc capt ' + this.stepNum);
491
+ this.status =
492
+ `All Hz Calibration: ${this.numSuccessfulCaptured} recording of convolved MLS captured`.toString() +
493
+ this.generateTemplate().toString();
494
+ this.emit('update', {
495
+ message: this.status,
496
+ });
497
+ }
498
+ };
499
+
500
+ /** .
501
+ * .
502
+ * .
503
+ * Created an S Curver Buffer to taper the signal onset
504
+ *
505
+ * @param {*} length
506
+ * @param {*} phase
507
+ * @returns
508
+ * @example
509
+ */
510
+ static createSCurveBuffer = (length, phase) => {
511
+ const curve = new Float32Array(length);
512
+ let i;
513
+ for (i = 0; i < length; i += 1) {
514
+ // scale the curve to be between 0-1
515
+ curve[i] = Math.sin((Math.PI * i) / length - phase) / 2 + 0.5;
516
+ }
517
+ return curve;
518
+ };
519
+
520
+ static createInverseSCurveBuffer = (length, phase) => {
521
+ const curve = new Float32Array(length);
522
+ let i;
523
+ let j = length - 1;
524
+ for (i = 0; i < length; i += 1) {
525
+ // scale the curve to be between 0-1
526
+ curve[i] = Math.sin((Math.PI * j) / length - phase) / 2 + 0.5;
527
+ j -= 1;
528
+ }
529
+ return curve;
530
+ };
531
+
532
+ /**
533
+ * Construct a Calibration Node with the calibration parameters.
534
+ *
535
+ * @param dataBuffer
536
+ * @private
537
+ * @example
538
+ */
539
+ #createCalibrationNodeFromBuffer = dataBuffer => {
540
+ console.log('databuffer');
541
+ console.log(dataBuffer);
542
+ if (!this.sourceAudioContext) {
543
+ this.makeNewSourceAudioContext();
544
+ }
545
+
546
+ const buffer = this.sourceAudioContext.createBuffer(
547
+ 1, // number of channels
548
+ dataBuffer.length,
549
+ this.sourceAudioContext.sampleRate // sample rate
550
+ );
551
+
552
+ const data = buffer.getChannelData(0); // get data
553
+ // fill the buffer with our data
554
+ try {
555
+ for (let i = 0; i < dataBuffer.length; i += 1) {
556
+ data[i] = dataBuffer[i] * 0.33;
557
+ }
558
+ } catch (error) {
559
+ console.error(error);
560
+ }
561
+
562
+ this.sourceNode = this.sourceAudioContext.createBufferSource();
563
+
564
+ this.sourceNode.buffer = buffer;
565
+ if (this.mode === 'filtered') {
566
+ this.sourceNode.loop = false;
567
+ } else {
568
+ this.sourceNode.loop = true;
569
+ }
570
+
571
+ this.sourceNode.connect(this.sourceAudioContext.destination);
572
+
573
+ this.addCalibrationNode(this.sourceNode);
574
+ };
575
+
576
+ /**
577
+ * Given a data buffer, creates the required calibration node
578
+ *
579
+ * @param {*} dataBufferArray
580
+ * @example
581
+ */
582
+ #setCalibrationNodesFromBuffer = (dataBufferArray = [this.#mlsBufferView]) => {
583
+ if (dataBufferArray.length === 1) {
584
+ this.#createCalibrationNodeFromBuffer(dataBufferArray[0]);
585
+ } else {
586
+ throw new Error('The length of the data buffer array must be 1');
587
+ }
588
+ };
589
+
590
+ /**
591
+ * Creates an audio context and plays it for a few seconds.
592
+ *
593
+ * @private
594
+ * @returns - Resolves when the audio is done playing.
595
+ * @example
596
+ */
597
+ #playCalibrationAudio = () => {
598
+ this.calibrationNodes[0].start(0);
599
+ this.status = ``;
600
+ if (this.mode === 'unfiltered') {
601
+ this.#mls = this.calibrationNodes[0].buffer.getChannelData(0);
602
+ console.log('play calibration audio ' + this.stepNum);
603
+ this.status =
604
+ `All Hz Calibration: playing the calibration tone...`.toString() +
605
+ this.generateTemplate().toString();
606
+ } else if (this.mode === 'filtered') {
607
+ console.log('play convolved audio ' + this.stepNum);
608
+ this.status =
609
+ `All Hz Calibration: playing the convolved calibration tone...`.toString() +
610
+ this.generateTemplate().toString();
611
+ } else {
612
+ throw new Error('Mode is incorrect');
613
+ }
614
+ this.emit('update', {message: this.status});
615
+ this.stepNum += 1;
616
+ console.log('sink sampling rate');
617
+ console.log(this.sinkSamplingRate);
618
+ console.log('source sampling rate');
619
+ console.log(this.sourceSamplingRate);
620
+ };
621
+
622
+ /** .
623
+ * .
624
+ * .
625
+ * Stops the audio with tapered offset
626
+ *
627
+ * @example
628
+ */
629
+ #stopCalibrationAudio = () => {
630
+ this.calibrationNodes[0].stop(0);
631
+ this.calibrationNodes = [];
632
+ this.sourceNode.disconnect();
633
+ this.stepNum += 1;
634
+ console.log('stop calibration audio ' + this.stepNum);
635
+ this.status =
636
+ `All Hz Calibration: stopping the calibration tone...`.toString() +
637
+ this.generateTemplate().toString();
638
+ this.emit('update', {message: this.status});
639
+ };
640
+
641
+ playMLSwithIIR = async (stream, convolution) => {
642
+ let checkRec = false;
643
+ this.mode = 'filtered';
644
+ console.log('play mls with iir');
645
+ //this.invertedImpulseResponse = iir;
646
+
647
+ await this.calibrationSteps(
648
+ stream,
649
+ this.#playCalibrationAudio, // play audio func (required)
650
+ this.#createCalibrationNodeFromBuffer(convolution), // before play func
651
+ this.#awaitSignalOnset, // before record
652
+ () => this.numSuccessfulCaptured < 1,
653
+ this.#awaitDesiredMLSLength, // during record
654
+ this.#afterMLSwIIRRecord, // after record
655
+ this.mode,
656
+ checkRec
657
+ );
658
+ };
659
+
660
+ bothSoundCheck = async (stream) => {
661
+ let iir_ir_and_plots;
662
+ this.#currentConvolution = this.componentConvolution;
663
+ await this.playMLSwithIIR(stream, this.#currentConvolution);
664
+ this.#stopCalibrationAudio();
665
+ let component_conv_recs = this.getAllFilteredRecordedSignals();
666
+ let return_component_conv_rec = component_conv_recs[0];
667
+ this.clearAllFilteredRecordedSignals();
668
+ this.#currentConvolution = this.systemConvolution;
669
+ await this.playMLSwithIIR(stream, this.#currentConvolution);
670
+ this.#stopCalibrationAudio();
671
+ let system_conv_recs = this.getAllFilteredRecordedSignals();
672
+ let return_system_conv_rec = system_conv_recs[0];
673
+ this.sourceAudioContext.close();
674
+ let recs = this.getAllUnfilteredRecordedSignals();
675
+ let unconv_rec = recs[0];
676
+ let return_unconv_rec= unconv_rec;
677
+ let conv_rec = component_conv_recs[0];
678
+
679
+ //psd of component
680
+ let knownGain = this.oldComponentIR.Gain;
681
+ let knownFreq = this.oldComponentIR.Freq;
682
+ let sampleRate = this.sourceSamplingRate || 96000;
683
+ let component_unconv_rec_psd = await this.pyServerAPI
684
+ .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)
685
+ .then(res => {
686
+ this.incrementStatusBar();
687
+ this.status =
688
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
689
+ this.generateTemplate().toString();
690
+ this.emit('update', {message: this.status});
691
+ return res;
692
+ })
693
+ .catch(err => {
694
+ console.error(err);
695
+ });
696
+
697
+ let component_conv_rec_psd = await this.pyServerAPI
698
+ .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)
699
+ .then(res => {
700
+ this.incrementStatusBar();
701
+ this.status =
702
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
703
+ this.generateTemplate().toString();
704
+ this.emit('update', {message: this.status});
705
+ return res;
706
+ })
707
+ .catch(err => {
708
+ console.error(err);
709
+ });
710
+
711
+ conv_rec = system_conv_recs[0];
712
+ //psd of system
713
+ let system_recs_psd = await this.pyServerAPI
714
+ .getPSDWithRetry({
715
+ unconv_rec,
716
+ conv_rec,
717
+ sampleRate: this.sourceSamplingRate || 96000,
718
+ })
719
+ .then(res => {
720
+ this.incrementStatusBar();
721
+ this.status =
722
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
723
+ this.generateTemplate().toString();
724
+ this.emit('update', {message: this.status});
725
+ return res;
726
+ })
727
+ .catch(err => {
728
+ console.error(err);
729
+ });
730
+
731
+ //iir w/ and without bandpass psd. done
732
+ unconv_rec = this.componentInvertedImpulseResponseNoBandpass;
733
+ conv_rec = this.componentInvertedImpulseResponse;
734
+ let component_iir_psd = await this.pyServerAPI
735
+ .getPSDWithRetry({
736
+ unconv_rec,
737
+ conv_rec,
738
+ sampleRate: this.sourceSamplingRate || 96000,
739
+ })
740
+ .then(res => {
741
+ this.incrementStatusBar();
742
+ this.status =
743
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
744
+ this.generateTemplate().toString();
745
+ this.emit('update', {message: this.status});
746
+ return res;
747
+ })
748
+ .catch(err => {
749
+ console.error(err);
750
+ });
751
+ unconv_rec = this.systemInvertedImpulseResponseNoBandpass;
752
+ conv_rec = this.systemInvertedImpulseResponse;
753
+ let system_iir_psd = await this.pyServerAPI
754
+ .getPSDWithRetry({
755
+ unconv_rec,
756
+ conv_rec,
757
+ sampleRate: this.sourceSamplingRate || 96000,
758
+ })
759
+ .then(res => {
760
+ this.incrementStatusBar();
761
+ this.status =
762
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
763
+ this.generateTemplate().toString();
764
+ this.emit('update', {message: this.status});
765
+ return res;
766
+ })
767
+ .catch(err => {
768
+ console.error(err);
769
+ });
770
+
771
+ iir_ir_and_plots = {
772
+ filtered_recording:{
773
+ component: return_component_conv_rec,
774
+ system: return_system_conv_rec
775
+ },
776
+ unfiltered_recording: this.getAllUnfilteredRecordedSignals()[0],
777
+ system: {
778
+ iir: this.systemInvertedImpulseResponse,
779
+ ir: this.systemIR,
780
+ iir_psd: {
781
+ y: system_iir_psd['y_conv'],
782
+ x: system_iir_psd['x_conv'],
783
+ y_no_bandpass: system_iir_psd['y_unconv'],
784
+ x_no_bandpass: system_iir_psd['x_unconv']
785
+ },
786
+ convolution: this.systemConvolution,
787
+ psd: {
788
+ unconv: {
789
+ x: system_recs_psd['x_unconv'],
790
+ y: system_recs_psd['y_unconv']
791
+ },
792
+ conv: {
793
+ x: system_recs_psd['x_unconv'],
794
+ y: system_recs_psd['y_unconv']
795
+ }
796
+ }
797
+ },
798
+ component: {
799
+ iir: this.componentInvertedImpulseResponse,
800
+ ir: this.componentIR,
801
+ iir_psd: {
802
+ y: component_iir_psd['y_conv'],
803
+ x: component_iir_psd['x_conv'],
804
+ y_no_bandpass: component_iir_psd['y_unconv'],
805
+ x_no_bandpass: component_iir_psd['x_unconv']
806
+ },
807
+ convolution: this.componentConvolution,
808
+ psd: {
809
+ unconv: {
810
+ x: component_unconv_rec_psd['x'],
811
+ y: component_unconv_rec_psd['y']
812
+ },
813
+ conv: {
814
+ x: component_conv_rec_psd['x'],
815
+ y: component_conv_rec_psd['y']
816
+ }
817
+ }
818
+ },
819
+ mls: this.#mls,
820
+ autocorrelations: this.autocorrelations,
821
+ impulseResponses: []
822
+ };
823
+
824
+ return iir_ir_and_plots;
825
+
826
+ }
827
+
828
+ singleSoundCheck = async (stream) => {
829
+ let iir_ir_and_plots;
830
+ if (this._calibrateSoundCheck != 'system') {
831
+ this.#currentConvolution = this.componentConvolution;
832
+ } else {
833
+ this.#currentConvolution = this.systemConvolution;
834
+ }
835
+ await this.playMLSwithIIR(stream, this.#currentConvolution);
836
+ this.#stopCalibrationAudio();
837
+ this.sourceAudioContext.close();
838
+ let conv_recs = this.getAllFilteredRecordedSignals();
839
+ let recs = this.getAllUnfilteredRecordedSignals();
840
+ console.log(
841
+ 'Obtaining unfiltered recording from #allHzUnfilteredRecordings to calculate PSD'
842
+ );
843
+ console.log('Obtaining filtered recording from #allHzFilteredRecordings to calculate PSD');
844
+ let unconv_rec = recs[0];
845
+ let return_unconv_rec = unconv_rec;
846
+ let conv_rec = conv_recs[0];
847
+ let return_conv_rec = conv_rec;
848
+ if (this._calibrateSoundCheck != 'system') {
849
+ let knownGain = this.oldComponentIR.Gain;
850
+ let knownFreq = this.oldComponentIR.Freq;
851
+ let sampleRate = this.sourceSamplingRate || 96000;
852
+ let unconv_results = await this.pyServerAPI
853
+ .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)
854
+ .then(res => {
855
+ this.incrementStatusBar();
856
+ this.status =
857
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
858
+ this.generateTemplate().toString();
859
+ this.emit('update', {message: this.status});
860
+ return res;
861
+ })
862
+ .catch(err => {
863
+ console.error(err);
864
+ });
865
+
866
+ let conv_results = await this.pyServerAPI
867
+ .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)
868
+ .then(res => {
869
+ this.incrementStatusBar();
870
+ this.status =
871
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
872
+ this.generateTemplate().toString();
873
+ this.emit('update', {message: this.status});
874
+ return res;
875
+ })
876
+ .catch(err => {
877
+ console.error(err);
878
+ });
879
+ unconv_rec = this.componentInvertedImpulseResponseNoBandpass;
880
+ conv_rec = this.componentInvertedImpulseResponse;
881
+ let component_iir_psd = await this.pyServerAPI
882
+ .getPSDWithRetry({
883
+ unconv_rec,
884
+ conv_rec,
885
+ sampleRate: this.sourceSamplingRate || 96000,
886
+ })
887
+ .then(res => {
888
+ this.incrementStatusBar();
889
+ this.status =
890
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
891
+ this.generateTemplate().toString();
892
+ this.emit('update', {message: this.status});
893
+ return res;
894
+ })
895
+ .catch(err => {
896
+ console.error(err);
897
+ });
898
+ unconv_rec = this.systemInvertedImpulseResponseNoBandpass;
899
+ conv_rec = this.systemInvertedImpulseResponse;
900
+ let system_iir_psd = await this.pyServerAPI
901
+ .getPSDWithRetry({
902
+ unconv_rec,
903
+ conv_rec,
904
+ sampleRate: this.sourceSamplingRate || 96000,
905
+ })
906
+ .then(res => {
907
+ this.incrementStatusBar();
908
+ this.status =
909
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
910
+ this.generateTemplate().toString();
911
+ this.emit('update', {message: this.status});
912
+ return res;
913
+ })
914
+ .catch(err => {
915
+ console.error(err);
916
+ });
917
+
918
+ iir_ir_and_plots = {
919
+ unfiltered_recording: return_unconv_rec,
920
+ filtered_recording: return_conv_rec,
921
+ system: {
922
+ iir: this.systemInvertedImpulseResponse,
923
+ ir: this.systemIR,
924
+ iir_psd: {
925
+ y: system_iir_psd['y_conv'],
926
+ x: system_iir_psd['y_conv'],
927
+ y_no_bandpass: system_iir_psd['y_unconv'],
928
+ x_no_bandpass: system_iir_psd['x_unconv'],
929
+ },
930
+ filtered_recording: [],
931
+ convolution: this.systemConvolution,
932
+ psd: {
933
+ unconv: {
934
+ x: [],
935
+ y: []
936
+ },
937
+ conv: {
938
+ x: [],
939
+ y: []
940
+ }
941
+ }
942
+ },
943
+ component: {
944
+ iir: this.componentInvertedImpulseResponse,
945
+ ir: this.componentIR,
946
+ iir_psd: {
947
+ y: component_iir_psd['y_conv'],
948
+ x: component_iir_psd['x_conv'],
949
+ y_no_bandpass: component_iir_psd['y_unconv'],
950
+ x_no_bandpass: component_iir_psd['x_unconv']
951
+ },
952
+ convolution: this.componentConvolution,
953
+ psd: {
954
+ unconv: {
955
+ x: unconv_results['x'],
956
+ y: unconv_results['y']
957
+ },
958
+ conv: {
959
+ x: conv_results['x'],
960
+ y: conv_results['y']
961
+ }
962
+ }
963
+ },
964
+ mls: this.#mls,
965
+ autocorrelations: this.autocorrelations,
966
+ impulseResponses: []
967
+ };
968
+ } else {
969
+ let results = await this.pyServerAPI
970
+ .getPSDWithRetry({
971
+ unconv_rec,
972
+ conv_rec,
973
+ sampleRate: this.sourceSamplingRate || 96000,
974
+ })
975
+ .then(res => {
976
+ this.incrementStatusBar();
977
+ this.status =
978
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
979
+ this.generateTemplate().toString();
980
+ this.emit('update', {message: this.status});
981
+ return res;
982
+ })
983
+ .catch(err => {
984
+ console.error(err);
985
+ });
986
+
987
+ //iir w/ and without bandpass psd
988
+ unconv_rec = this.componentInvertedImpulseResponseNoBandpass;
989
+ conv_rec = this.componentInvertedImpulseResponse;
990
+ let component_iir_psd = await this.pyServerAPI
991
+ .getPSDWithRetry({
992
+ unconv_rec,
993
+ conv_rec,
994
+ sampleRate: this.sourceSamplingRate || 96000,
995
+ })
996
+ .then(res => {
997
+ this.incrementStatusBar();
998
+ this.status =
999
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
1000
+ this.generateTemplate().toString();
1001
+ this.emit('update', {message: this.status});
1002
+ return res;
1003
+ })
1004
+ .catch(err => {
1005
+ console.error(err);
1006
+ });
1007
+ unconv_rec = this.systemInvertedImpulseResponseNoBandpass;
1008
+ conv_rec = this.systemInvertedImpulseResponse;
1009
+ let system_iir_psd = await this.pyServerAPI
1010
+ .getPSDWithRetry({
1011
+ unconv_rec,
1012
+ conv_rec,
1013
+ sampleRate: this.sourceSamplingRate || 96000,
1014
+ })
1015
+ .then(res => {
1016
+ this.incrementStatusBar();
1017
+ this.status =
1018
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
1019
+ this.generateTemplate().toString();
1020
+ this.emit('update', {message: this.status});
1021
+ return res;
1022
+ })
1023
+ .catch(err => {
1024
+ console.error(err);
1025
+ });
1026
+
1027
+ iir_ir_and_plots = {
1028
+ unfiltered_recording: return_unconv_rec,
1029
+ filtered_recording: return_conv_rec,
1030
+ system: {
1031
+ iir: this.systemInvertedImpulseResponse,
1032
+ ir: this.systemIR,
1033
+ iir_psd: {
1034
+ y: system_iir_psd['y_conv'],
1035
+ x: system_iir_psd['y_conv'],
1036
+ y_no_bandpass: system_iir_psd['y_unconv'],
1037
+ x_no_bandpass: system_iir_psd['x_unconv'],
1038
+ },
1039
+ filtered_recording: [],
1040
+ convolution: this.systemConvolution,
1041
+ psd: {
1042
+ unconv: {
1043
+ x: results['x_unconv'],
1044
+ y: results['y_unconv']
1045
+ },
1046
+ conv: {
1047
+ x: results['x_conv'],
1048
+ y: results['y_conv'],
1049
+ }
1050
+ }
1051
+ },
1052
+ component: {
1053
+ iir: this.componentInvertedImpulseResponse,
1054
+ ir: this.componentIR,
1055
+ iir_psd: {
1056
+ y: component_iir_psd['y_conv'],
1057
+ x: component_iir_psd['x_conv'],
1058
+ y_no_bandpass: component_iir_psd['y_unconv'],
1059
+ x_no_bandpass: component_iir_psd['x_unconv']
1060
+ },
1061
+ convolution: this.componentConvolution,
1062
+ psd: {
1063
+ unconv: {
1064
+ x: [],
1065
+ y: []
1066
+ },
1067
+ conv: {
1068
+ x: [],
1069
+ y: []
1070
+ }
1071
+ }
1072
+ },
1073
+ mls: this.#mls,
1074
+ autocorrelations: this.autocorrelations,
1075
+ impulseResponses: []
1076
+ };
1077
+ }
1078
+ await Promise.all(this.impulseResponses).then(res => {
1079
+ for (let i = 0; i < res.length; i++) {
1080
+ if (res[i] != undefined) {
1081
+ iir_ir_and_plots['impulseResponses'].push(res[i])
1082
+ }
1083
+ }
1084
+ });
1085
+
1086
+ if (this.#download) {
1087
+ this.downloadSingleUnfilteredRecording();
1088
+ this.downloadSingleFilteredRecording();
1089
+ saveToCSV(this.#mls, 'MLS.csv');
1090
+ saveToCSV(this.componentConvolution, 'python_component_convolution_mls_iir.csv');
1091
+ saveToCSV(this.systemConvolution, 'python_system_convolution_mls_iir.csv');
1092
+ saveToCSV(this.componentInvertedImpulseResponse, 'componentIIR.csv');
1093
+ saveToCSV(this.systemInvertedImpulseResponse, 'systemIIR.csv');
1094
+ for (let i = 0; i < this.autocorrelations.length; i++) {
1095
+ saveToCSV(this.autocorrelations[i], `autocorrelation_${i}`);
1096
+ }
1097
+ const computedIRagain = await Promise.all(this.impulseResponses).then(res => {
1098
+ for (let i = 0; i < res.length; i++) {
1099
+ if (res[i] != undefined) {
1100
+ saveToCSV(res[i], `IR_${i}`);
1101
+ }
1102
+ }
1103
+ });
1104
+ }
1105
+
1106
+ return iir_ir_and_plots;
1107
+ }
1108
+
1109
+ /**
1110
+ * Public method to start the calibration process. Objects intialized from webassembly allocate new memory
1111
+ * and must be manually freed. This function is responsible for intializing the MlsGenInterface,
1112
+ * and wrapping the calibration steps with a garbage collection safe gaurd.
1113
+ *
1114
+ * @public
1115
+ * @param stream - The stream of audio from the Listener.
1116
+ * @example
1117
+ */
1118
+ startCalibrationImpulseResponse = async stream => {
1119
+ let desired_time = this.desired_time_per_mls;
1120
+ let checkRec = 'allhz';
1121
+
1122
+ console.log('MLS sequence should be of length: ' + this.sourceSamplingRate * desired_time);
1123
+
1124
+ length = this.sourceSamplingRate * desired_time;
1125
+ //get mls here
1126
+ await this.pyServerAPI
1127
+ .getMLSWithRetry(length)
1128
+ .then(res => {
1129
+ console.log(res);
1130
+ this.#mlsBufferView = res['mls'];
1131
+ })
1132
+ .catch(err => {
1133
+ // this.emit('InvertedImpulseResponse', {res: false});
1134
+ console.error(err);
1135
+ });
1136
+ this.numSuccessfulBackgroundCaptured = 0;
1137
+ if (this._calibrateSoundBackgroundSecs > 0){
1138
+ this.mode='background';
1139
+ this.status =
1140
+ `All Hz Calibration: sampling the background noise...`.toString() + this.generateTemplate().toString();
1141
+ this.emit('update', {message: this.status});
1142
+ await this.recordBackground(
1143
+ stream, //stream
1144
+ () => this.numSuccessfulBackgroundCaptured < 1, //loop condition
1145
+ this.#awaitBackgroundNoiseRecording, //sleep to record
1146
+ this.sendBackgroundRecording, //send to get PSD
1147
+ this.mode,
1148
+ checkRec
1149
+ )
1150
+ this.incrementStatusBar();
1151
+ }
1152
+ this.mode='unfiltered';
1153
+ this.numSuccessfulCaptured = 0;
1154
+
1155
+ await this.calibrationSteps(
1156
+ stream,
1157
+ this.#playCalibrationAudio, // play audio func (required)
1158
+ this.#createCalibrationNodeFromBuffer(this.#mlsBufferView), // before play func
1159
+ this.#awaitSignalOnset, // before record
1160
+ () => this.numSuccessfulCaptured < this.numCaptures, // loop while true
1161
+ this.#awaitDesiredMLSLength, // during record
1162
+ this.#afterMLSRecord, // after record
1163
+ this.mode,
1164
+ checkRec
1165
+ ),
1166
+ this.#stopCalibrationAudio();
1167
+ checkRec = false;
1168
+
1169
+ // at this stage we've captured all the required signals,
1170
+ // and have received IRs for each one
1171
+ // so let's send all the IRs to the server to be converted to a single IIR
1172
+ await this.sendSystemImpulseResponsesToServerForProcessing();
1173
+ await this.sendComponentImpulseResponsesToServerForProcessing();
1174
+
1175
+ this.numSuccessfulCaptured = 0;
1176
+
1177
+ let iir_ir_and_plots;
1178
+ if (this._calibrateSoundCheck != 'none') {
1179
+ //do single check
1180
+ if (this._calibrateSoundCheck == 'goal' || this._calibrateSoundCheck == 'system'){
1181
+ iir_ir_and_plots = await this.singleSoundCheck(stream);
1182
+ } else{//both
1183
+ iir_ir_and_plots = await this.bothSoundCheck(stream);
1184
+ }
1185
+
1186
+ } else {
1187
+ let unconv_rec = this.componentInvertedImpulseResponseNoBandpass;
1188
+ let conv_rec = this.componentInvertedImpulseResponse;
1189
+ let component_iir_psd = await this.pyServerAPI
1190
+ .getPSDWithRetry({
1191
+ unconv_rec,
1192
+ conv_rec,
1193
+ sampleRate: this.sourceSamplingRate || 96000,
1194
+ })
1195
+ .then(res => {
1196
+ this.incrementStatusBar();
1197
+ this.status =
1198
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
1199
+ this.generateTemplate().toString();
1200
+ this.emit('update', {message: this.status});
1201
+ return res;
1202
+ })
1203
+ .catch(err => {
1204
+ console.error(err);
1205
+ });
1206
+ unconv_rec = this.systemInvertedImpulseResponseNoBandpass;
1207
+ conv_rec = this.systemInvertedImpulseResponse;
1208
+ let system_iir_psd = await this.pyServerAPI
1209
+ .getPSDWithRetry({
1210
+ unconv_rec,
1211
+ conv_rec,
1212
+ sampleRate: this.sourceSamplingRate || 96000,
1213
+ })
1214
+ .then(res => {
1215
+ this.incrementStatusBar();
1216
+ this.status =
1217
+ `All Hz Calibration: done computing the PSD graphs...`.toString() +
1218
+ this.generateTemplate().toString();
1219
+ this.emit('update', {message: this.status});
1220
+ return res;
1221
+ })
1222
+ .catch(err => {
1223
+ console.error(err);
1224
+ });
1225
+
1226
+ iir_ir_and_plots = {
1227
+ unfiltered_recording: return_unconv_rec,
1228
+ filtered_recording: return_conv_rec,
1229
+ system: {
1230
+ iir: this.systemInvertedImpulseResponse,
1231
+ ir: this.systemIR,
1232
+ iir_psd: {
1233
+ y: system_iir_psd['y_conv'],
1234
+ x: system_iir_psd['y_conv'],
1235
+ y_no_bandpass: system_iir_psd['y_unconv'],
1236
+ x_no_bandpass: system_iir_psd['x_unconv'],
1237
+ },
1238
+ filtered_recording: [],
1239
+ convolution: this.systemConvolution,
1240
+ psd: {
1241
+ unconv: {
1242
+ x: [],
1243
+ y: []
1244
+ },
1245
+ conv: {
1246
+ x: [],
1247
+ y: [],
1248
+ }
1249
+ }
1250
+ },
1251
+ component: {
1252
+ iir: this.componentInvertedImpulseResponse,
1253
+ ir: this.componentIR,
1254
+ iir_psd: {
1255
+ y: component_iir_psd['y_conv'],
1256
+ x: component_iir_psd['x_conv'],
1257
+ y_no_bandpass: component_iir_psd['y_unconv'],
1258
+ x_no_bandpass: component_iir_psd['x_unconv']
1259
+ },
1260
+ convolution: this.componentConvolution,
1261
+ psd: {
1262
+ unconv: {
1263
+ x: [],
1264
+ y: []
1265
+ },
1266
+ conv: {
1267
+ x: [],
1268
+ y: []
1269
+ }
1270
+ }
1271
+ },
1272
+ mls: this.#mls,
1273
+ autocorrelations: this.autocorrelations,
1274
+ impulseResponses: []
1275
+ };
1276
+ await Promise.all(this.impulseResponses).then(res => {
1277
+ for (let i = 0; i < res.length; i++) {
1278
+ if (res[i] != undefined) {
1279
+ iir_ir_and_plots['impulseResponses'].push(res[i])
1280
+ }
1281
+ }
1282
+ });
1283
+
1284
+ if (this.#download) {
1285
+ saveToCSV(this.#mls, 'MLS.csv');
1286
+ saveToCSV(this.componentConvolution, 'python_component_convolution_mls_iir.csv');
1287
+ saveToCSV(this.systemConvolution, 'python_system_convolution_mls_iir.csv');
1288
+ saveToCSV(this.componentInvertedImpulseResponse, 'componentIIR.csv');
1289
+ saveToCSV(this.systemInvertedImpulseResponse, 'systemIIR.csv');
1290
+ for (let i = 0; i < this.autocorrelations.length; i++) {
1291
+ saveToCSV(this.autocorrelations[i], `autocorrelation_${i}`);
1292
+ }
1293
+ const computedIRagain = await Promise.all(this.impulseResponses).then(res => {
1294
+ for (let i = 0; i < res.length; i++) {
1295
+ if (res[i] != undefined) {
1296
+ saveToCSV(res[i], `IR_${i}`);
1297
+ }
1298
+ }
1299
+ });
1300
+ }
1301
+ }
1302
+
1303
+ this.percent_complete = 100;
1304
+
1305
+ this.status = `All Hz Calibration: Finished`.toString() + this.generateTemplate().toString();
1306
+ this.emit('update', {message: this.status});
1307
+
1308
+ //here after calibration we have the component calibration (either loudspeaker or microphone) in the same form as the componentIR
1309
+ //that was used to calibrate
1310
+
1311
+ return iir_ir_and_plots;
1312
+ };
1313
+
1314
+ //////////////////////volume
1315
+
1316
+ handleIncomingData = data => {
1317
+ console.log('Received data: ', data);
1318
+ if (data.type === 'soundGainDBSPL') {
1319
+ this.soundGainDBSPL = data.value;
1320
+ } else {
1321
+ throw new Error(`Unknown data type: ${data.type}`);
1322
+ }
1323
+ };
1324
+ createSCurveBuffer = (onSetBool = true) => {
1325
+ const curve = new Float32Array(this.TAPER_SECS * this.sourceSamplingRate + 1);
1326
+ const frequency = 1 / (4 * this.TAPER_SECS);
1327
+ let j = 0;
1328
+ for (let i = 0; i < this.TAPER_SECS * this.sourceSamplingRate + 1; i += 1) {
1329
+ const phase = 2 * Math.PI * frequency * j;
1330
+ const onsetTaper = Math.pow(Math.sin(phase), 2);
1331
+ const offsetTaper = Math.pow(Math.cos(phase), 2);
1332
+ curve[i] = onSetBool ? onsetTaper : offsetTaper;
1333
+ j += 1 / this.sourceSamplingRate;
1334
+ }
1335
+ return curve;
1336
+ };
1337
+
1338
+ #getTruncatedSignal = (left = 3.5, right = 4.5) => {
1339
+ const start = Math.floor(left * this.sourceSamplingRate);
1340
+ const end = Math.floor(right * this.sourceSamplingRate);
1341
+ const result = Array.from(this.getLastVolumeRecordedSignal().slice(start, end));
1342
+ console.log(
1343
+ 'Obtaining last 1000 hz recording from #allVolumeRecordings to send for processing'
1344
+ );
1345
+ /**
1346
+ * function to check that capture was properly made
1347
+ * @param {*} list
1348
+ */
1349
+ const checkResult = list => {
1350
+ const setItem = new Set(list);
1351
+ if (setItem.size === 1 && setItem.has(0)) {
1352
+ console.warn(
1353
+ 'The last capture failed, all recorded signal is zero',
1354
+ this.getAllVolumeRecordedSignals()
1355
+ );
1356
+ }
1357
+ if (setItem.size === 0) {
1358
+ console.warn('The last capture failed, no recorded signal');
1359
+ }
1360
+ };
1361
+ checkResult(result);
1362
+ return result;
1363
+ };
1364
+
1365
+ /**
1366
+ *
1367
+ *
1368
+ Construct a calibration Node with the calibration parameters and given gain value
1369
+ * @param {*} gainValue
1370
+ * */
1371
+ #createCalibrationToneWithGainValue = gainValue => {
1372
+ const audioContext = this.makeNewSourceAudioContext();
1373
+ const oscilator = audioContext.createOscillator();
1374
+ const gainNode = audioContext.createGain();
1375
+ const taperGainNode = audioContext.createGain();
1376
+ const offsetGainNode = audioContext.createGain();
1377
+ const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;
1378
+
1379
+ oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;
1380
+ oscilator.type = this.#CALIBRATION_TONE_TYPE;
1381
+ gainNode.gain.value = gainValue;
1382
+
1383
+ oscilator.connect(gainNode);
1384
+ gainNode.connect(taperGainNode);
1385
+ const onsetCurve = this.createSCurveBuffer();
1386
+ taperGainNode.gain.setValueCurveAtTime(onsetCurve, 0, this.TAPER_SECS);
1387
+ taperGainNode.connect(offsetGainNode);
1388
+ const offsetCurve = this.createSCurveBuffer(false);
1389
+ offsetGainNode.gain.setValueCurveAtTime(
1390
+ offsetCurve,
1391
+ totalDuration - this.TAPER_SECS,
1392
+ this.TAPER_SECS
1393
+ );
1394
+ offsetGainNode.connect(audioContext.destination);
1395
+
1396
+ this.addCalibrationNode(oscilator);
1397
+ };
1398
+
1399
+ /**
1400
+ * Construct a Calibration Node with the calibration parameters.
1401
+ *
1402
+ * @private
1403
+ * @example
1404
+ */
1405
+ #createCalibrationNode = () => {
1406
+ const audioContext = this.makeNewSourceAudioContext();
1407
+ const oscilator = audioContext.createOscillator();
1408
+ const gainNode = audioContext.createGain();
1409
+
1410
+ oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;
1411
+ oscilator.type = this.#CALIBRATION_TONE_TYPE;
1412
+ gainNode.gain.value = 0.04;
1413
+
1414
+ oscilator.connect(gainNode);
1415
+ gainNode.connect(audioContext.destination);
1416
+
1417
+ this.addCalibrationNode(oscilator);
1418
+ };
1419
+
1420
+ #playCalibrationAudioVolume = async () => {
1421
+ const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;
1422
+
1423
+ this.calibrationNodes[0].start(0);
1424
+ this.calibrationNodes[0].stop(totalDuration);
1425
+ console.log(`Playing a buffer of ${this.CALIBRATION_TONE_DURATION} seconds of audio`);
1426
+ console.log(`Waiting a total of ${totalDuration} seconds`);
1427
+ await sleep(totalDuration);
1428
+ };
1429
+
1430
+ #sendToServerForProcessing = (lCalib) => {
1431
+ console.log('Sending data to server');
1432
+ let left = this.calibrateSound1000HzPreSec
1433
+ let right = this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec
1434
+ this.pyServerAPI
1435
+ .getVolumeCalibration({
1436
+ sampleRate: this.sourceSamplingRate,
1437
+ payload: this.#getTruncatedSignal(left,right),
1438
+ lCalib: lCalib,
1439
+ })
1440
+ .then(res => {
1441
+ if (this.outDBSPL === null) {
1442
+ this.incrementStatusBar();
1443
+ this.outDBSPL = res['outDbSPL'];
1444
+ this.outDBSPL1000 = res['outDbSPL1000'];
1445
+ this.THD = res['thd'];
1446
+ }
1447
+ })
1448
+ .catch(err => {
1449
+ console.warn(err);
1450
+ });
1451
+ };
1452
+
1453
+ startCalibrationVolume = async (stream, gainValues, lCalib, componentGainDBSPL) => {
1454
+ const trialIterations = gainValues.length;
1455
+ this.status_denominator += trialIterations;
1456
+ const thdValues = [];
1457
+ const inDBValues = [];
1458
+ let inDB = 0;
1459
+ const outDBSPLValues = [];
1460
+ const outDBSPL1000Values = [];
1461
+ let checkRec = false;
1462
+
1463
+ // do one calibration that will be discarded
1464
+ const soundLevelToDiscard = -60;
1465
+ const gainToDiscard = Math.pow(10, soundLevelToDiscard / 20);
1466
+ this.status =
1467
+ `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`.toString() +
1468
+ this.generateTemplate().toString();
1469
+ //this.emit('update', {message: `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`});
1470
+ this.emit('update', {message: this.status});
1471
+
1472
+ do {
1473
+ // eslint-disable-next-line no-await-in-loop
1474
+ await this.volumeCalibrationSteps(
1475
+ stream,
1476
+ this.#playCalibrationAudioVolume,
1477
+ this.#createCalibrationToneWithGainValue,
1478
+ this.#sendToServerForProcessing,
1479
+ gainToDiscard,
1480
+ lCalib, //todo make this a class parameter
1481
+ checkRec
1482
+ );
1483
+ } while (this.outDBSPL === null);
1484
+ //reset the values
1485
+ //this.incrementStatusBar();
1486
+
1487
+ this.outDBSPL = null;
1488
+ this.outDBSPL = null;
1489
+ this.outDBSPL1000 = null;
1490
+ this.THD = null;
1491
+
1492
+ // run the calibration at different gain values provided by the user
1493
+ for (let i = 0; i < trialIterations; i++) {
1494
+ //convert gain to DB and add to inDB
1495
+ if (i == trialIterations - 1) {
1496
+ checkRec = 'loudest';
1497
+ }
1498
+ inDB = Math.log10(gainValues[i]) * 20;
1499
+ // precision to 1 decimal place
1500
+ inDB = Math.round(inDB * 10) / 10;
1501
+ inDBValues.push(inDB);
1502
+ console.log('next update');
1503
+ this.status =
1504
+ `1000 Hz Calibration: Sound Level ${inDB} dB`.toString() +
1505
+ this.generateTemplate().toString();
1506
+ this.emit('update', {message: this.status});
1507
+ do {
1508
+ // eslint-disable-next-line no-await-in-loop
1509
+ await this.volumeCalibrationSteps(
1510
+ stream,
1511
+ this.#playCalibrationAudioVolume,
1512
+ this.#createCalibrationToneWithGainValue,
1513
+ this.#sendToServerForProcessing,
1514
+ gainValues[i],
1515
+ lCalib, //todo make this a class parameter
1516
+ checkRec
1517
+ );
1518
+ } while (this.outDBSPL === null);
1519
+ outDBSPL1000Values.push(this.outDBSPL1000);
1520
+ thdValues.push(this.THD);
1521
+ outDBSPLValues.push(this.outDBSPL);
1522
+
1523
+ this.outDBSPL = null;
1524
+ this.outDBSPL1000 = null;
1525
+ this.THD = null;
1526
+ }
1527
+
1528
+ // get the volume calibration parameters from the server
1529
+ const parameters = await this.pyServerAPI
1530
+ .getVolumeCalibrationParameters({
1531
+ inDBValues: inDBValues,
1532
+ outDBSPLValues: outDBSPL1000Values,
1533
+ lCalib: lCalib,
1534
+ componentGainDBSPL,
1535
+ })
1536
+ .then(res => {
1537
+ this.incrementStatusBar();
1538
+ return res;
1539
+ });
1540
+ const result = {
1541
+ parameters: parameters,
1542
+ inDBValues: inDBValues,
1543
+ outDBSPLValues: outDBSPLValues,
1544
+ outDBSPL1000Values: outDBSPL1000Values,
1545
+ thdValues: thdValues,
1546
+ };
1547
+
1548
+ return result;
1549
+ };
1550
+
1551
+ // function to write frq and gain to firebase database given speakerID
1552
+ writeFrqGain = async (speakerID, frq, gain, OEM) => {
1553
+ // freq and gain are too large to take samples 1 in every 100 samples
1554
+
1555
+ const sampledFrq = [];
1556
+ const sampledGain = [];
1557
+ for (let i = 0; i < frq.length; i += 100) {
1558
+ sampledFrq.push(frq[i]);
1559
+ sampledGain.push(gain[i]);
1560
+ }
1561
+
1562
+ const data = {Freq: sampledFrq, Gain: sampledGain};
1563
+
1564
+ await set(ref(database, `Microphone2/${OEM}/${speakerID}/linear`), data);
1565
+ };
1566
+
1567
+ // Function to Read frq and gain from firebase database given speakerID
1568
+ // returns an array of frq and gain if speakerID exists, returns null otherwise
1569
+
1570
+ readFrqGain = async (speakerID, OEM) => {
1571
+ const dbRef = ref(database);
1572
+ const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}/linear`));
1573
+ if (snapshot.exists()) {
1574
+ return snapshot.val();
1575
+ }
1576
+ return null;
1577
+ };
1578
+
1579
+ readGainat1000Hz = async (speakerID, OEM) => {
1580
+ const dbRef = ref(database);
1581
+ const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}/Gain1000`));
1582
+ if (snapshot.exists()) {
1583
+ return snapshot.val();
1584
+ }
1585
+ return null;
1586
+ };
1587
+
1588
+ writeGainat1000Hz = async (speakerID, gain, OEM) => {
1589
+ const data = {Gain: gain};
1590
+ await set(ref(database, `Microphone2/${OEM}/${speakerID}/Gain1000`), gain);
1591
+ };
1592
+
1593
+ writeIsSmartPhone = async (speakerID, isSmartPhone, OEM) => {
1594
+ const data = {isSmartPhone: isSmartPhone};
1595
+ await set(ref(database, `Microphone2/${OEM}/${speakerID}/isSmartPhone`), isSmartPhone);
1596
+ };
1597
+
1598
+ doesMicrophoneExist = async (speakerID, OEM) => {
1599
+ const dbRef = ref(database);
1600
+ const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}`));
1601
+ if (snapshot.exists()) {
1602
+ return true;
1603
+ }
1604
+ return false;
1605
+ };
1606
+
1607
+ addMicrophoneInfo = async (speakerID, OEM, micInfo) => {
1608
+ // add to database if /info does not exist
1609
+ const dbRef = ref(database);
1610
+ const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}/info`));
1611
+ if (!snapshot.exists()) {
1612
+ await set(ref(database, `Microphone2/${OEM}/${speakerID}/info`), micInfo);
1613
+ }
1614
+ };
1615
+
1616
+ convertToDB = gain => {
1617
+ return Math.log10(gain) * 20;
1618
+ };
1619
+
1620
+ // Function to perform linear interpolation between two points
1621
+ interpolate(x, x0, y0, x1, y1) {
1622
+ return y0 + ((x - x0) * (y1 - y0)) / (x1 - x0);
1623
+ }
1624
+
1625
+ findGainatFrequency = (frequencies, gains, targetFrequency) => {
1626
+ // Find the index of the first frequency in the array greater than the target frequency
1627
+ let index = 0;
1628
+ while (index < frequencies.length && frequencies[index] < targetFrequency) {
1629
+ index++;
1630
+ }
1631
+
1632
+ // Handle cases when the target frequency is outside the range of the given data
1633
+ if (index === 0) {
1634
+ return gains[0];
1635
+ } else if (index === frequencies.length) {
1636
+ return gains[gains.length - 1];
1637
+ } else {
1638
+ // Interpolate the gain based on the surrounding frequencies
1639
+ const x0 = frequencies[index - 1];
1640
+ const y0 = gains[index - 1];
1641
+ const x1 = frequencies[index];
1642
+ const y1 = gains[index];
1643
+ return this.interpolate(targetFrequency, x0, y0, x1, y1);
1644
+ }
1645
+ };
1646
+
1647
+ // Example of how to use the writeFrqGain and readFrqGain functions
1648
+ // writeFrqGain('speaker1', [1, 2, 3], [4, 5, 6]);
1649
+ // Speaker1 is the speakerID you want to write to in the database
1650
+ // readFrqGain('MiniDSPUMIK_1').then(data => console.log(data));
1651
+ // MiniDSPUMIK_1 is the speakerID with some Data in the database
1652
+ //adding gainDBSPL
1653
+ startCalibration = async (
1654
+ stream,
1655
+ gainValues,
1656
+ lCalib = 104.92978421490648,
1657
+ componentIR = null,
1658
+ microphoneName = 'MiniDSP-UMIK1-711-4754-vertical',
1659
+ _calibrateSoundCheck = 'goal', //GOAL PASSed in by default
1660
+ isSmartPhone = false,
1661
+ _calibrateSoundBurstRepeats = 4,
1662
+ _calibrateSoundBurstSec = 1,
1663
+ _calibrateSoundBurstsWarmup = 1,
1664
+ _calibrateSoundHz = 48000,
1665
+ _calibrateSoundIIRSec = 0.2,
1666
+ calibrateSound1000HzPreSec = 3.5,
1667
+ calibrateSound1000HzSec = 1.0,
1668
+ calibrateSound1000HzPostSec = 0.5,
1669
+ _calibrateSoundBackgroundSecs = 0,
1670
+ micManufacturer = '',
1671
+ micSerialNumber = '',
1672
+ micModelNumber = '',
1673
+ micModelName = ''
1674
+ ) => {
1675
+ this.CALIBRATION_TONE_DURATION =
1676
+ calibrateSound1000HzPreSec + calibrateSound1000HzSec + calibrateSound1000HzPostSec;
1677
+ this.calibrateSound1000HzPreSec = calibrateSound1000HzPreSec;
1678
+ this.calibrateSound1000HzSec = calibrateSound1000HzSec;
1679
+ this.calibrateSound1000HzPostSec = calibrateSound1000HzPostSec;
1680
+ this.iirLength = Math.floor(_calibrateSoundIIRSec * this.sourceSamplingRate);
1681
+ console.log('device info:', this.deviceInfo);
1682
+ this.numMLSPerCapture = _calibrateSoundBurstRepeats;
1683
+ this.desired_time_per_mls = _calibrateSoundBurstSec;
1684
+ this.num_mls_to_skip = _calibrateSoundBurstsWarmup;
1685
+ this.desired_sampling_rate = _calibrateSoundHz;
1686
+ this._calibrateSoundBackgroundSecs = _calibrateSoundBackgroundSecs;
1687
+
1688
+ //feed calibration goal here
1689
+ this._calibrateSoundCheck = _calibrateSoundCheck;
1690
+ //check if a componentIR was given to the system, if it isn't check for the microphone. using dummy data here bc we need to
1691
+ //check the db based on the microphone currently connected
1692
+
1693
+ //new lCalib found at top of calibration files *1000hz, make sure to correct
1694
+ //based on zeroing of 1000hz, search for "*1000Hz"
1695
+ const ID = isSmartPhone ? micModelNumber : micSerialNumber;
1696
+ const OEM = isSmartPhone ? this.deviceInfo.OEM : micManufacturer;
1697
+ // const ID = "711-4754";
1698
+ // const OEM = "MiniDSP";
1699
+ const micInfo = {
1700
+ micModelName: isSmartPhone ? micModelName : microphoneName,
1701
+ OEM: OEM,
1702
+ ID: ID,
1703
+ HardwareName: isSmartPhone ? this.deviceInfo.hardwarename : microphoneName,
1704
+ hardwareFamily: isSmartPhone ? this.deviceInfo.hardwarefamily : microphoneName,
1705
+ HardwareModel: isSmartPhone ? this.deviceInfo.hardwaremodel : microphoneName,
1706
+ PlatformName: isSmartPhone ? this.deviceInfo.platformname : 'N/A',
1707
+ PlatformVersion: isSmartPhone ? this.deviceInfo.platformversion : 'N/A',
1708
+ DeviceType: isSmartPhone ? this.deviceInfo.devicetype : 'N/A',
1709
+ };
1710
+ this.addMicrophoneInfo(ID, OEM, micInfo);
1711
+ if (componentIR == null) {
1712
+ //mode 'ir'
1713
+ //global variable this.componentIR must be set
1714
+ this.componentIR = await this.readFrqGain(ID, OEM).then(data => {
1715
+ return data;
1716
+ });
1717
+
1718
+ lCalib = await this.readGainat1000Hz(ID, OEM);
1719
+ micInfo['gainDBSPL'] = lCalib;
1720
+ // this.componentGainDBSPL = this.convertToDB(lCalib);
1721
+ this.componentGainDBSPL = lCalib;
1722
+ //TODO: if this call to database is unknown, cannot perform experiment => return false
1723
+ if (this.componentIR == null) {
1724
+ this.status =
1725
+ `Microphone (${OEM},${ID}) is not found in the database. Please add it to the database.`.toString();
1726
+ this.emit('update', {message: this.status});
1727
+ return false;
1728
+ }
1729
+ } else {
1730
+ this.componentIR = componentIR;
1731
+ lCalib = this.findGainatFrequency(this.componentIR.Freq, this.componentIR.Gain, 1000);
1732
+ // this.componentGainDBSPL = this.convertToDB(lCalib);
1733
+ this.componentGainDBSPL = lCalib;
1734
+ await this.writeIsSmartPhone(ID, isSmartPhone, OEM);
1735
+ }
1736
+
1737
+ this.oldComponentIR = this.componentIR;
1738
+
1739
+ let volumeResults = await this.startCalibrationVolume(
1740
+ stream,
1741
+ gainValues,
1742
+ lCalib,
1743
+ this.componentGainDBSPL
1744
+ );
1745
+
1746
+ let impulseResponseResults = await this.startCalibrationImpulseResponse(stream);
1747
+ impulseResponseResults['background_noise'] = this.background_noise;
1748
+ if (componentIR != null) {
1749
+ //insert Freq and Gain from this.componentIR into db
1750
+ await this.writeFrqGain(
1751
+ ID,
1752
+ impulseResponseResults.componentIR.Freq,
1753
+ impulseResponseResults.componentIR.Gain,
1754
+ OEM
1755
+ );
1756
+ micInfo['gainDBSPL'] = impulseResponseResults.parameters.gainDBSPL;
1757
+ await this.writeGainat1000Hz(ID, micInfo['gainDBSPL'], OEM);
1758
+ }
1759
+
1760
+ const total_results = {...volumeResults, ...impulseResponseResults};
1761
+
1762
+ total_results['micInfo'] = micInfo;
1763
+ console.log('total results');
1764
+ console.log(total_results);
1765
+ return total_results;
1766
+ };
1767
+ }
1768
+
1769
+ export default Combination;