speaker-calibration 2.2.50 → 2.2.52

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