speaker-calibration 2.2.81 → 2.2.82

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