speaker-calibration 2.2.48 → 2.2.50

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