speaker-calibration 2.2.97 → 2.2.98

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