speaker-calibration 2.2.70 → 2.2.72

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