speaker-calibration 2.2.77 → 2.2.79

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