speaker-calibration 2.2.83 → 2.2.85

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