speaker-calibration 2.2.50 → 2.2.52

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