speaker-calibration 2.2.67 → 2.2.68

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