speaker-calibration 2.2.33 → 2.2.35

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 +437 -436
  101. package/src/server/PythonServerAPI.js +468 -468
  102. package/src/tasks/audioCalibrator.js +304 -304
  103. package/src/tasks/audioRecorder.js +267 -267
  104. package/src/tasks/combination/combination.js +1495 -1492
  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,436 +1,437 @@
1
- import QRCode from 'qrcode';
2
- import AudioPeer from './audioPeer';
3
- import {sleep} from '../utils';
4
- import {
5
- UnsupportedDeviceError,
6
- MissingSpeakerIdError,
7
- CalibrationTimedOutError,
8
- } from './peerErrors';
9
-
10
- import database from '../config/firebase';
11
- import {ref, set, get, child} from 'firebase/database';
12
- import {phrases} from '../../dist/example/i18n';
13
-
14
- /**
15
- * @class Handles the speaker's side of the connection. Responsible for initiating the connection,
16
- * rendering the QRCode, and answering the call.
17
- * @augments AudioPeer
18
- */
19
- class Speaker extends AudioPeer {
20
- /**
21
- * Takes the url of the current site and a target element where html elements will be appended.
22
- *
23
- * @param params - See type definition for initParameters.
24
- * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.
25
- * @param CalibratorInstance
26
- * @example
27
- */
28
- constructor(params, CalibratorInstance) {
29
- super(params);
30
- this.siteUrl += '/listener?';
31
- this.ac = CalibratorInstance;
32
- this.result = null;
33
- this.debug = params?.debug ?? false;
34
- this.isSmartPhone = params?.isSmartPhone ?? false;
35
- this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;
36
- this.instructionDisplayId = params?.instructionDisplayId ?? '';
37
- this.titleDisplayId = params?.titleDisplayId ?? '';
38
- this.timeToCalibrate = params?.timeToCalibrate ?? 10;
39
-
40
- /* Set up callbacks that handle any events related to our peer object. */
41
- this.peer.on('open', this.#onPeerOpen);
42
- this.peer.on('connection', this.#onPeerConnection);
43
- this.peer.on('close', this.#onPeerClose);
44
- this.peer.on('disconnected', this.#onPeerDisconnected);
45
- this.peer.on('error', this.#onPeerError);
46
- }
47
-
48
- static getMicrophoneNamesFromDatabase = async () => {
49
- const dbRef = ref(database);
50
- const snapshot = await get(child(dbRef, 'Microphone'));
51
- if (snapshot.exists()) {
52
- return Object.keys(snapshot.val());
53
- }
54
- return null;
55
- };
56
-
57
- /**
58
- * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.
59
- *
60
- * @param params - The parameters to be passed to the peer object.
61
- * @param Calibrator - The class that defines the calibration process.
62
- * @param CalibratorInstance
63
- * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).
64
- * @public
65
- * @example
66
- */
67
- static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {
68
- window.speaker = new Speaker(params, CalibratorInstance);
69
- const {speaker} = window;
70
-
71
- // wrap the calibration process in a promise so we can await it
72
- return new Promise((resolve, reject) => {
73
- // when a call is received
74
- speaker.peer.on('call', async call => {
75
- // Answer the call (one way)
76
- call.answer();
77
- speaker.#removeUIElems();
78
- speaker.#showSpinner();
79
- speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
80
- // when we start receiving audio
81
- call.on('stream', async stream => {
82
- window.localStream = stream;
83
- window.localAudio.srcObject = stream;
84
- window.localAudio.autoplay = false;
85
-
86
- // if the sinkSamplingRate is not set sleep
87
- while (!speaker.ac.sampleRatesSet()) {
88
- console.log('SinkSamplingRate is undefined, sleeping');
89
- await sleep(1);
90
- }
91
- // resolve when we have a result
92
- speaker.result = await speaker.ac.startCalibration(
93
- stream,
94
- params.gainValues,
95
- params.ICalib,
96
- params.knownIR,
97
- params.microphoneName,
98
- params.calibrateSoundCheck,
99
- params.isSmartPhone,
100
- params.calibrateSoundBurstRepeats,
101
- params.calibrateSoundBurstSec,
102
- params.calibrateSoundBurstsWarmup,
103
- params.calibrateSoundHz,
104
- params.calibrateSoundIIRSec,
105
- params.calibrateSound1000HzSec,
106
- params.micManufacturer,
107
- params.micSerialNumber,
108
- params.micModelNumber,
109
- params.micModelName
110
- );
111
- speaker.#removeUIElems();
112
- resolve(speaker.result);
113
- });
114
- // if we do not receive a result within the timeout, reject
115
- setTimeout(() => {
116
- reject(
117
- new CalibrationTimedOutError(
118
- `Calibration failed to produce a result after ${
119
- timeOut / 1000
120
- } seconds. Please try again.`
121
- )
122
- );
123
- }, timeOut);
124
- });
125
- });
126
- };
127
-
128
- static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {
129
- window.speaker = new Speaker(params, CalibratorInstance);
130
- const {speaker} = window;
131
-
132
- // wrap the calibration process in a promise so we can await it
133
- return new Promise((resolve, reject) => {
134
- // when a call is received
135
- speaker.peer.on('call', async call => {
136
- // Answer the call (one way)
137
- call.answer();
138
- speaker.#removeUIElems();
139
- speaker.#showSpinner();
140
- speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
141
- // when we start receiving audio
142
- call.on('stream', async stream => {
143
- window.localStream = stream;
144
- window.localAudio.srcObject = stream;
145
- window.localAudio.autoplay = false;
146
-
147
- // if the sinkSamplingRate is not set sleep
148
- while (!speaker.ac.sampleRatesSet()) {
149
- console.log('SinkSamplingRate is undefined, sleeping');
150
- await sleep(1);
151
- }
152
- // resolve when we have a result
153
- speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);
154
- speaker.#removeUIElems();
155
- resolve(speaker.result);
156
- });
157
- // if we do not receive a result within the timeout, reject
158
- setTimeout(() => {
159
- reject(
160
- new CalibrationTimedOutError(
161
- `Calibration failed to produce a result after ${
162
- timeOut / 1000
163
- } seconds. Please try again.`
164
- )
165
- );
166
- }, timeOut);
167
- });
168
- });
169
- };
170
-
171
- /**
172
- * Called after the peer conncection has been opened.
173
- * Generates a QR code for the connection and displays it.
174
- *
175
- * @private
176
- * @example
177
- */
178
- #showQRCode = () => {
179
- // Get query string, the URL parameters to specify a Listener
180
- const queryStringParameters = {
181
- speakerPeerId: this.peer.id,
182
- isSmartPhone: this.isSmartPhone,
183
- calibrateSoundHz: this.calibrateSoundHz,
184
- };
185
- const queryString = this.queryStringFromObject(queryStringParameters);
186
- const uri = this.siteUrl + queryString;
187
- if (this.isSmartPhone) {
188
- // Display QR code for the participant to scan
189
- const qrCanvas = document.createElement('canvas');
190
- qrCanvas.setAttribute('id', 'qrCanvas');
191
- console.log(uri);
192
- QRCode.toCanvas(qrCanvas, uri, error => {
193
- if (error) console.error(error);
194
- });
195
- document.getElementById(this.targetElement).appendChild(qrCanvas);
196
- } else {
197
- // show the link to the user
198
- // If specified HTML Id is available, show QR code there
199
- if (document.getElementById(this.targetElement)) {
200
- // const linkTag = document.createElement('a');
201
- // linkTag.setAttribute('href', uri);
202
- // linkTag.innerHTML = 'Click here to start the calibration';
203
- // linkTag.target = '_blank';
204
- // document.getElementById(this.targetElement).appendChild(linkTag);
205
- // document.getElementById(this.targetElement).appendChild(qrCanvas);
206
-
207
- const proceedButton = document.createElement('button');
208
- proceedButton.setAttribute('id', 'calibrationProceedButton');
209
- proceedButton.setAttribute('class', 'btn btn-success');
210
- proceedButton.innerHTML = 'Proceed';
211
- proceedButton.onclick = () => {
212
- // open the link in a new tab
213
- window.open(uri, '_blank');
214
- // remove the button
215
- document.getElementById('calibrationProceedButton').remove();
216
- };
217
- document.getElementById(this.targetElement).appendChild(proceedButton);
218
- }
219
- }
220
- // or just print it to console
221
- console.log('TEST: Peer reachable at: ', uri);
222
- };
223
-
224
- #showSpinner = () => {
225
- const spinner = document.createElement('div');
226
- spinner.className = 'spinner-border ml-auto';
227
- spinner.role = 'status';
228
- spinner.ariaHidden = 'true';
229
- document.getElementById(this.targetElement).appendChild(spinner);
230
-
231
- // clear instructionDisplay
232
- const instructionDisplay = document.getElementById(this.instructionDisplayId);
233
- const background = document.getElementById('background'); // todo: get background id from params
234
- if (instructionDisplay) {
235
- instructionDisplay.innerHTML = '';
236
- instructionDisplay.style.whiteSpace = 'nowrap';
237
- instructionDisplay.style.fontWeight = 'bold';
238
- instructionDisplay.style.width = 'fit-content';
239
- instructionDisplay.innerHTML = phrases.RC_soundRecording['en-US'];
240
- let fontSize = 100;
241
- instructionDisplay.style.fontSize = fontSize + 'px';
242
- while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
243
- fontSize--;
244
- instructionDisplay.style.fontSize = fontSize + 'px';
245
- }
246
- const p = document.createElement('p');
247
- // font size
248
- p.style.fontSize = '1.1rem';
249
- p.style.fontWeight = 'normal';
250
- p.style.paddingTop = '20px';
251
- const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
252
- p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
253
- instructionDisplay.appendChild(p);
254
- }
255
-
256
- // Update title - titleDisplayId
257
- const titleDisplay = document.getElementById(this.titleDisplayId);
258
- if (titleDisplay) {
259
- // replace 2 with 3
260
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('2', '3');
261
- // replace 1 with 3
262
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('1', '3');
263
- }
264
- };
265
-
266
- #removeUIElems = () => {
267
- const parent = document.getElementById(this.targetElement);
268
- while (parent.firstChild) {
269
- parent.firstChild.remove();
270
- }
271
- };
272
-
273
- /**
274
- * Called when the peer connection is opened.
275
- * Saves the peer id and calls the QR code generator.
276
- *
277
- * @param peerId - The peer id of the peer connection.
278
- * @param id
279
- * @private
280
- * @example
281
- */
282
- #onPeerOpen = id => {
283
- // Workaround for peer.reconnect deleting previous id
284
- if (id === null) {
285
- console.error('Received null id from peer open');
286
- this.peer.id = this.lastPeerId;
287
- } else {
288
- this.lastPeerId = this.peer.id;
289
- }
290
-
291
- if (id !== this.peer.id) {
292
- console.warn('DEBUG Check you assumption that id === this.peer.id');
293
- }
294
-
295
- this.#showQRCode();
296
- };
297
-
298
- /**
299
- * Called when the peer connection is established.
300
- * Enforces a single connection.
301
- *
302
- * @param connection - The connection object.
303
- * @private
304
- * @example
305
- */
306
- #onPeerConnection = connection => {
307
- // Allow only a single connection
308
- if (this.conn && this.conn.open) {
309
- connection.on('open', () => {
310
- connection.send('Already connected to another client');
311
- setTimeout(() => {
312
- connection.close();
313
- }, 500);
314
- });
315
- return;
316
- }
317
-
318
- this.conn = connection;
319
- console.log('Connected to: ', this.conn.peer);
320
- this.#ready();
321
- };
322
-
323
- /**
324
- * Called when the peer connection is closed.
325
- *
326
- * @private
327
- * @example
328
- */
329
- #onPeerClose = () => {
330
- this.conn = null;
331
- console.log('Connection destroyed');
332
- };
333
-
334
- /**
335
- * Called when the peer connection is disconnected.
336
- * Attempts to reconnect.
337
- *
338
- * @private
339
- * @example
340
- */
341
- #onPeerDisconnected = () => {
342
- console.log('Connection lost. Please reconnect');
343
-
344
- // Workaround for peer.reconnect deleting previous id
345
- this.peer.id = this.lastPeerId;
346
- // eslint-disable-next-line no-underscore-dangle
347
- this.peer._lastServerId = this.lastPeerId;
348
- this.peer.reconnect();
349
- };
350
-
351
- /**
352
- * Called when the peer connection encounters an error.
353
- *
354
- * @param error
355
- * @private
356
- * @example
357
- */
358
- #onPeerError = error => {
359
- // TODO: check if this function is needed or not
360
- console.error(error);
361
- };
362
-
363
- /**
364
- * Called when data is received from the peer connection.
365
- *
366
- * @param data
367
- * @private
368
- * @example
369
- */
370
- #onIncomingData = data => {
371
- // enforce object type
372
- if (
373
- !Object.prototype.hasOwnProperty.call(data, 'name') ||
374
- !Object.prototype.hasOwnProperty.call(data, 'payload')
375
- ) {
376
- console.error('Received malformed data: ', data);
377
- return;
378
- }
379
-
380
- switch (data.name) {
381
- case 'samplingRate':
382
- this.ac.setSamplingRates(data.payload);
383
- break;
384
- case 'deviceType':
385
- this.ac.setDeviceType(data.payload);
386
- break;
387
- case 'deviceName':
388
- this.ac.setDeviceName(data.payload);
389
- break;
390
- case 'deviceInfo':
391
- this.ac.setDeviceInfo(data.payload);
392
- case UnsupportedDeviceError.name:
393
- case MissingSpeakerIdError.name:
394
- throw data.payload;
395
- break;
396
- default:
397
- break;
398
- }
399
- };
400
-
401
- /**
402
- * Called when the peer connection is #ready.
403
- *
404
- * @private
405
- * @example
406
- */
407
- #ready = () => {
408
- // Perform callback with data
409
- this.conn.on('data', this.#onIncomingData);
410
- this.conn.on('close', () => {
411
- console.log('Connection reset<br>Awaiting connection...');
412
- this.conn = null;
413
- });
414
- };
415
-
416
- /** .
417
- * .
418
- * .
419
- * Debug method for downloading the recorded audio
420
- *
421
- * @public
422
- * @example
423
- */
424
- downloadData = () => {
425
- this.ac.downloadData();
426
- };
427
- }
428
-
429
- /*
430
- Referenced links:
431
- https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
432
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
433
- https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
434
- */
435
-
436
- export default Speaker;
1
+ import QRCode from 'qrcode';
2
+ import AudioPeer from './audioPeer';
3
+ import {sleep} from '../utils';
4
+ import {
5
+ UnsupportedDeviceError,
6
+ MissingSpeakerIdError,
7
+ CalibrationTimedOutError,
8
+ } from './peerErrors';
9
+
10
+ import database from '../config/firebase';
11
+ import {ref, set, get, child} from 'firebase/database';
12
+ import {phrases} from '../../dist/example/i18n';
13
+
14
+ /**
15
+ * @class Handles the speaker's side of the connection. Responsible for initiating the connection,
16
+ * rendering the QRCode, and answering the call.
17
+ * @augments AudioPeer
18
+ */
19
+ class Speaker extends AudioPeer {
20
+ /**
21
+ * Takes the url of the current site and a target element where html elements will be appended.
22
+ *
23
+ * @param params - See type definition for initParameters.
24
+ * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.
25
+ * @param CalibratorInstance
26
+ * @example
27
+ */
28
+ constructor(params, CalibratorInstance) {
29
+ super(params);
30
+ this.siteUrl += '/listener?';
31
+ this.ac = CalibratorInstance;
32
+ this.result = null;
33
+ this.debug = params?.debug ?? false;
34
+ this.isSmartPhone = params?.isSmartPhone ?? false;
35
+ this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;
36
+ this.instructionDisplayId = params?.instructionDisplayId ?? '';
37
+ this.titleDisplayId = params?.titleDisplayId ?? '';
38
+ this.timeToCalibrate = params?.timeToCalibrate ?? 10;
39
+
40
+ /* Set up callbacks that handle any events related to our peer object. */
41
+ this.peer.on('open', this.#onPeerOpen);
42
+ this.peer.on('connection', this.#onPeerConnection);
43
+ this.peer.on('close', this.#onPeerClose);
44
+ this.peer.on('disconnected', this.#onPeerDisconnected);
45
+ this.peer.on('error', this.#onPeerError);
46
+ }
47
+
48
+ static getMicrophoneNamesFromDatabase = async () => {
49
+ const dbRef = ref(database);
50
+ const snapshot = await get(child(dbRef, 'Microphone'));
51
+ if (snapshot.exists()) {
52
+ return Object.keys(snapshot.val());
53
+ }
54
+ return null;
55
+ };
56
+
57
+ /**
58
+ * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.
59
+ *
60
+ * @param params - The parameters to be passed to the peer object.
61
+ * @param Calibrator - The class that defines the calibration process.
62
+ * @param CalibratorInstance
63
+ * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).
64
+ * @public
65
+ * @example
66
+ */
67
+ static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {
68
+ window.speaker = new Speaker(params, CalibratorInstance);
69
+ const {speaker} = window;
70
+
71
+ // wrap the calibration process in a promise so we can await it
72
+ return new Promise((resolve, reject) => {
73
+ // when a call is received
74
+ speaker.peer.on('call', async call => {
75
+ // Answer the call (one way)
76
+ call.answer();
77
+ speaker.#removeUIElems();
78
+ speaker.#showSpinner();
79
+ speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
80
+ // when we start receiving audio
81
+ call.on('stream', async stream => {
82
+ window.localStream = stream;
83
+ window.localAudio.srcObject = stream;
84
+ window.localAudio.autoplay = false;
85
+
86
+ // if the sinkSamplingRate is not set sleep
87
+ while (!speaker.ac.sampleRatesSet()) {
88
+ console.log('SinkSamplingRate is undefined, sleeping');
89
+ await sleep(1);
90
+ }
91
+ // resolve when we have a result
92
+ speaker.result = await speaker.ac.startCalibration(
93
+ stream,
94
+ params.gainValues,
95
+ params.ICalib,
96
+ params.knownIR,
97
+ params.microphoneName,
98
+ params.calibrateSoundCheck,
99
+ params.isSmartPhone,
100
+ params.calibrateSoundBurstRepeats,
101
+ params.calibrateSoundBurstSec,
102
+ params.calibrateSoundBurstsWarmup,
103
+ params.calibrateSoundHz,
104
+ params.calibrateSoundIIRSec,
105
+ params.calibrateSound1000HzSec,
106
+ params.calibrateSoundBackgroundSecs,
107
+ params.micManufacturer,
108
+ params.micSerialNumber,
109
+ params.micModelNumber,
110
+ params.micModelName
111
+ );
112
+ speaker.#removeUIElems();
113
+ resolve(speaker.result);
114
+ });
115
+ // if we do not receive a result within the timeout, reject
116
+ setTimeout(() => {
117
+ reject(
118
+ new CalibrationTimedOutError(
119
+ `Calibration failed to produce a result after ${
120
+ timeOut / 1000
121
+ } seconds. Please try again.`
122
+ )
123
+ );
124
+ }, timeOut);
125
+ });
126
+ });
127
+ };
128
+
129
+ static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {
130
+ window.speaker = new Speaker(params, CalibratorInstance);
131
+ const {speaker} = window;
132
+
133
+ // wrap the calibration process in a promise so we can await it
134
+ return new Promise((resolve, reject) => {
135
+ // when a call is received
136
+ speaker.peer.on('call', async call => {
137
+ // Answer the call (one way)
138
+ call.answer();
139
+ speaker.#removeUIElems();
140
+ speaker.#showSpinner();
141
+ speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
142
+ // when we start receiving audio
143
+ call.on('stream', async stream => {
144
+ window.localStream = stream;
145
+ window.localAudio.srcObject = stream;
146
+ window.localAudio.autoplay = false;
147
+
148
+ // if the sinkSamplingRate is not set sleep
149
+ while (!speaker.ac.sampleRatesSet()) {
150
+ console.log('SinkSamplingRate is undefined, sleeping');
151
+ await sleep(1);
152
+ }
153
+ // resolve when we have a result
154
+ speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);
155
+ speaker.#removeUIElems();
156
+ resolve(speaker.result);
157
+ });
158
+ // if we do not receive a result within the timeout, reject
159
+ setTimeout(() => {
160
+ reject(
161
+ new CalibrationTimedOutError(
162
+ `Calibration failed to produce a result after ${
163
+ timeOut / 1000
164
+ } seconds. Please try again.`
165
+ )
166
+ );
167
+ }, timeOut);
168
+ });
169
+ });
170
+ };
171
+
172
+ /**
173
+ * Called after the peer conncection has been opened.
174
+ * Generates a QR code for the connection and displays it.
175
+ *
176
+ * @private
177
+ * @example
178
+ */
179
+ #showQRCode = () => {
180
+ // Get query string, the URL parameters to specify a Listener
181
+ const queryStringParameters = {
182
+ speakerPeerId: this.peer.id,
183
+ isSmartPhone: this.isSmartPhone,
184
+ calibrateSoundHz: this.calibrateSoundHz,
185
+ };
186
+ const queryString = this.queryStringFromObject(queryStringParameters);
187
+ const uri = this.siteUrl + queryString;
188
+ if (this.isSmartPhone) {
189
+ // Display QR code for the participant to scan
190
+ const qrCanvas = document.createElement('canvas');
191
+ qrCanvas.setAttribute('id', 'qrCanvas');
192
+ console.log(uri);
193
+ QRCode.toCanvas(qrCanvas, uri, error => {
194
+ if (error) console.error(error);
195
+ });
196
+ document.getElementById(this.targetElement).appendChild(qrCanvas);
197
+ } else {
198
+ // show the link to the user
199
+ // If specified HTML Id is available, show QR code there
200
+ if (document.getElementById(this.targetElement)) {
201
+ // const linkTag = document.createElement('a');
202
+ // linkTag.setAttribute('href', uri);
203
+ // linkTag.innerHTML = 'Click here to start the calibration';
204
+ // linkTag.target = '_blank';
205
+ // document.getElementById(this.targetElement).appendChild(linkTag);
206
+ // document.getElementById(this.targetElement).appendChild(qrCanvas);
207
+
208
+ const proceedButton = document.createElement('button');
209
+ proceedButton.setAttribute('id', 'calibrationProceedButton');
210
+ proceedButton.setAttribute('class', 'btn btn-success');
211
+ proceedButton.innerHTML = 'Proceed';
212
+ proceedButton.onclick = () => {
213
+ // open the link in a new tab
214
+ window.open(uri, '_blank');
215
+ // remove the button
216
+ document.getElementById('calibrationProceedButton').remove();
217
+ };
218
+ document.getElementById(this.targetElement).appendChild(proceedButton);
219
+ }
220
+ }
221
+ // or just print it to console
222
+ console.log('TEST: Peer reachable at: ', uri);
223
+ };
224
+
225
+ #showSpinner = () => {
226
+ const spinner = document.createElement('div');
227
+ spinner.className = 'spinner-border ml-auto';
228
+ spinner.role = 'status';
229
+ spinner.ariaHidden = 'true';
230
+ document.getElementById(this.targetElement).appendChild(spinner);
231
+
232
+ // clear instructionDisplay
233
+ const instructionDisplay = document.getElementById(this.instructionDisplayId);
234
+ const background = document.getElementById('background'); // todo: get background id from params
235
+ if (instructionDisplay) {
236
+ instructionDisplay.innerHTML = '';
237
+ instructionDisplay.style.whiteSpace = 'nowrap';
238
+ instructionDisplay.style.fontWeight = 'bold';
239
+ instructionDisplay.style.width = 'fit-content';
240
+ instructionDisplay.innerHTML = phrases.RC_soundRecording['en-US'];
241
+ let fontSize = 100;
242
+ instructionDisplay.style.fontSize = fontSize + 'px';
243
+ while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
244
+ fontSize--;
245
+ instructionDisplay.style.fontSize = fontSize + 'px';
246
+ }
247
+ const p = document.createElement('p');
248
+ // font size
249
+ p.style.fontSize = '1.1rem';
250
+ p.style.fontWeight = 'normal';
251
+ p.style.paddingTop = '20px';
252
+ const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
253
+ p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
254
+ instructionDisplay.appendChild(p);
255
+ }
256
+
257
+ // Update title - titleDisplayId
258
+ const titleDisplay = document.getElementById(this.titleDisplayId);
259
+ if (titleDisplay) {
260
+ // replace 2 with 3
261
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('2', '3');
262
+ // replace 1 with 3
263
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('1', '3');
264
+ }
265
+ };
266
+
267
+ #removeUIElems = () => {
268
+ const parent = document.getElementById(this.targetElement);
269
+ while (parent.firstChild) {
270
+ parent.firstChild.remove();
271
+ }
272
+ };
273
+
274
+ /**
275
+ * Called when the peer connection is opened.
276
+ * Saves the peer id and calls the QR code generator.
277
+ *
278
+ * @param peerId - The peer id of the peer connection.
279
+ * @param id
280
+ * @private
281
+ * @example
282
+ */
283
+ #onPeerOpen = id => {
284
+ // Workaround for peer.reconnect deleting previous id
285
+ if (id === null) {
286
+ console.error('Received null id from peer open');
287
+ this.peer.id = this.lastPeerId;
288
+ } else {
289
+ this.lastPeerId = this.peer.id;
290
+ }
291
+
292
+ if (id !== this.peer.id) {
293
+ console.warn('DEBUG Check you assumption that id === this.peer.id');
294
+ }
295
+
296
+ this.#showQRCode();
297
+ };
298
+
299
+ /**
300
+ * Called when the peer connection is established.
301
+ * Enforces a single connection.
302
+ *
303
+ * @param connection - The connection object.
304
+ * @private
305
+ * @example
306
+ */
307
+ #onPeerConnection = connection => {
308
+ // Allow only a single connection
309
+ if (this.conn && this.conn.open) {
310
+ connection.on('open', () => {
311
+ connection.send('Already connected to another client');
312
+ setTimeout(() => {
313
+ connection.close();
314
+ }, 500);
315
+ });
316
+ return;
317
+ }
318
+
319
+ this.conn = connection;
320
+ console.log('Connected to: ', this.conn.peer);
321
+ this.#ready();
322
+ };
323
+
324
+ /**
325
+ * Called when the peer connection is closed.
326
+ *
327
+ * @private
328
+ * @example
329
+ */
330
+ #onPeerClose = () => {
331
+ this.conn = null;
332
+ console.log('Connection destroyed');
333
+ };
334
+
335
+ /**
336
+ * Called when the peer connection is disconnected.
337
+ * Attempts to reconnect.
338
+ *
339
+ * @private
340
+ * @example
341
+ */
342
+ #onPeerDisconnected = () => {
343
+ console.log('Connection lost. Please reconnect');
344
+
345
+ // Workaround for peer.reconnect deleting previous id
346
+ this.peer.id = this.lastPeerId;
347
+ // eslint-disable-next-line no-underscore-dangle
348
+ this.peer._lastServerId = this.lastPeerId;
349
+ this.peer.reconnect();
350
+ };
351
+
352
+ /**
353
+ * Called when the peer connection encounters an error.
354
+ *
355
+ * @param error
356
+ * @private
357
+ * @example
358
+ */
359
+ #onPeerError = error => {
360
+ // TODO: check if this function is needed or not
361
+ console.error(error);
362
+ };
363
+
364
+ /**
365
+ * Called when data is received from the peer connection.
366
+ *
367
+ * @param data
368
+ * @private
369
+ * @example
370
+ */
371
+ #onIncomingData = data => {
372
+ // enforce object type
373
+ if (
374
+ !Object.prototype.hasOwnProperty.call(data, 'name') ||
375
+ !Object.prototype.hasOwnProperty.call(data, 'payload')
376
+ ) {
377
+ console.error('Received malformed data: ', data);
378
+ return;
379
+ }
380
+
381
+ switch (data.name) {
382
+ case 'samplingRate':
383
+ this.ac.setSamplingRates(data.payload);
384
+ break;
385
+ case 'deviceType':
386
+ this.ac.setDeviceType(data.payload);
387
+ break;
388
+ case 'deviceName':
389
+ this.ac.setDeviceName(data.payload);
390
+ break;
391
+ case 'deviceInfo':
392
+ this.ac.setDeviceInfo(data.payload);
393
+ case UnsupportedDeviceError.name:
394
+ case MissingSpeakerIdError.name:
395
+ throw data.payload;
396
+ break;
397
+ default:
398
+ break;
399
+ }
400
+ };
401
+
402
+ /**
403
+ * Called when the peer connection is #ready.
404
+ *
405
+ * @private
406
+ * @example
407
+ */
408
+ #ready = () => {
409
+ // Perform callback with data
410
+ this.conn.on('data', this.#onIncomingData);
411
+ this.conn.on('close', () => {
412
+ console.log('Connection reset<br>Awaiting connection...');
413
+ this.conn = null;
414
+ });
415
+ };
416
+
417
+ /** .
418
+ * .
419
+ * .
420
+ * Debug method for downloading the recorded audio
421
+ *
422
+ * @public
423
+ * @example
424
+ */
425
+ downloadData = () => {
426
+ this.ac.downloadData();
427
+ };
428
+ }
429
+
430
+ /*
431
+ Referenced links:
432
+ https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
433
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
434
+ https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
435
+ */
436
+
437
+ export default Speaker;