speaker-calibration 2.2.42 → 2.2.44

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