speaker-calibration 2.2.22 → 2.2.24

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