speaker-calibration 2.2.62 → 2.2.64

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