speaker-calibration 2.2.14 → 2.2.15

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