speaker-calibration 2.2.86 → 2.2.87

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