speaker-calibration 2.2.28 → 2.2.29

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