speaker-calibration 2.2.114 → 2.2.116

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