speaker-calibration 2.2.87 → 2.2.89

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