speaker-calibration 2.2.37 → 2.2.38

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