speaker-calibration 2.2.13 → 2.2.15

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