speaker-calibration 2.2.105 → 2.2.106

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