speaker-calibration 2.2.33 → 2.2.35

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