speaker-calibration 2.2.82 → 2.2.84

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 +35846 -35846
  32. package/dist/example/index.html +47 -47
  33. package/dist/example/listener.html +62 -62
  34. package/dist/example/listener.js +95 -95
  35. package/dist/example/server.js +51 -51
  36. package/dist/example/speaker.html +145 -145
  37. package/dist/example/speakerUI.js +273 -273
  38. package/dist/example/styles.css +92 -92
  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 +26 -26
  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 +310 -310
  99. package/src/peer-connection/peerErrors.js +25 -25
  100. package/src/peer-connection/speaker.js +454 -453
  101. package/src/server/PythonServerAPI.js +595 -591
  102. package/src/tasks/audioCalibrator.js +308 -308
  103. package/src/tasks/audioRecorder.js +281 -281
  104. package/src/tasks/combination/combination.js +2156 -2168
  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 +88 -88
  118. package/webpack.config.js +37 -37
  119. package/makefile +0 -74
@@ -1,453 +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 {phrases} from '../../dist/example/i18n';
11
-
12
- /**
13
- * @class Handles the speaker's side of the connection. Responsible for initiating the connection,
14
- * rendering the QRCode, and answering the call.
15
- * @augments AudioPeer
16
- */
17
- class Speaker extends AudioPeer {
18
- /**
19
- * Takes the url of the current site and a target element where html elements will be appended.
20
- *
21
- * @param params - See type definition for initParameters.
22
- * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.
23
- * @param CalibratorInstance
24
- * @example
25
- */
26
- constructor(params, CalibratorInstance) {
27
- super(params);
28
- this.language = params?.language ?? 'en-US';
29
- this.siteUrl += '/listener?';
30
- this.ac = CalibratorInstance;
31
- this.result = null;
32
- this.debug = params?.debug ?? false;
33
- this.isSmartPhone = params?.isSmartPhone ?? false;
34
- this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;
35
- this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;
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
- * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.
51
- *
52
- * @param params - The parameters to be passed to the peer object.
53
- * @param Calibrator - The class that defines the calibration process.
54
- * @param CalibratorInstance
55
- * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).
56
- * @public
57
- * @example
58
- */
59
- static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {
60
- window.speaker = new Speaker(params, CalibratorInstance);
61
- const {speaker} = window;
62
-
63
- // wrap the calibration process in a promise so we can await it
64
- return new Promise((resolve, reject) => {
65
- // when a call is received
66
- speaker.peer.on('call', async call => {
67
- // Answer the call (one way)
68
-
69
- call.answer();
70
- speaker.#removeUIElems();
71
- speaker.#showSpinner();
72
- speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
73
- // when we start receiving audio
74
- call.on('stream', async stream => {
75
- window.localStream = stream;
76
- window.localAudio.srcObject = stream;
77
- window.localAudio.autoplay = false;
78
-
79
- // if the sinkSamplingRate is not set sleep
80
- while (!speaker.ac.sampleRatesSet()) {
81
- console.log('SinkSamplingRate is undefined, sleeping');
82
- await sleep(1);
83
- }
84
- // resolve when we have a result
85
- speaker.result = await speaker.ac.startCalibration(
86
- stream,
87
- params.gainValues,
88
- params.ICalib,
89
- params.knownIR,
90
- params.microphoneName,
91
- params.calibrateSoundCheck,
92
- params.isSmartPhone,
93
- params.calibrateSoundBurstDb,
94
- params.calibrateSoundBurstRepeats,
95
- params.calibrateSoundBurstSec,
96
- params.calibrateSoundBurstsWarmup,
97
- params.calibrateSoundHz,
98
- params.calibrateSoundIRSec,
99
- params.calibrateSoundIIRSec,
100
- params.calibrateSound1000HzPreSec,
101
- params.calibrateSound1000HzSec,
102
- params.calibrateSound1000HzPostSec,
103
- params.calibrateSoundBackgroundSecs,
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
- calibrateSoundSamplingDesiredBits: this.calibrateSoundSamplingDesiredBits,
183
- lang: this.language,
184
- };
185
- const queryString = this.queryStringFromObject(queryStringParameters);
186
- const uri = this.siteUrl + queryString;
187
- if (this.isSmartPhone) {
188
- // Display QR code for the participant to scan
189
- const qrCanvas = document.createElement('canvas');
190
- qrCanvas.setAttribute('id', 'qrCanvas');
191
- console.log(uri);
192
- QRCode.toCanvas(qrCanvas, uri, error => {
193
- if (error) console.error(error);
194
- });
195
- document.getElementById(this.targetElement).appendChild(qrCanvas);
196
- } else {
197
- // show the link to the user
198
- // If specified HTML Id is available, show QR code there
199
- if (document.getElementById(this.targetElement)) {
200
- // const linkTag = document.createElement('a');
201
- // linkTag.setAttribute('href', uri);
202
- // linkTag.innerHTML = 'Click here to start the calibration';
203
- // linkTag.target = '_blank';
204
- // document.getElementById(this.targetElement).appendChild(linkTag);
205
- // document.getElementById(this.targetElement).appendChild(qrCanvas);
206
-
207
- const proceedButton = document.createElement('button');
208
- proceedButton.setAttribute('id', 'calibrationProceedButton');
209
- proceedButton.setAttribute('class', 'btn btn-success');
210
- proceedButton.innerHTML = 'Proceed';
211
- proceedButton.onclick = () => {
212
- // open the link in a new tab
213
- window.open(uri, '_blank');
214
- // remove the button
215
- document.getElementById('calibrationProceedButton').remove();
216
- };
217
- document.getElementById(this.targetElement).appendChild(proceedButton);
218
- }
219
- }
220
- // or just print it to console
221
- console.log('TEST: Peer reachable at: ', uri);
222
- };
223
-
224
- #showSpinner = () => {
225
- const spinner = document.createElement('div');
226
- spinner.className = 'spinner-border ml-auto';
227
- spinner.role = 'status';
228
- spinner.ariaHidden = 'true';
229
- document.getElementById(this.targetElement).appendChild(spinner);
230
-
231
- // clear instructionDisplay
232
- const soundMessage = document.getElementById(this.soundMessageId);
233
- soundMessage.innerHTML = '';
234
- soundMessage.style.display = 'none';
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[this.language];
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
- const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
260
- if (timeToCalibrateDisplay) {
261
- const timeToCalibrateText = phrases.RC_howLongToCalibrate[this.language];
262
- timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
263
- timeToCalibrateDisplay.style.fontWeight = 'normal';
264
- timeToCalibrateDisplay.style.fontSize = '1rem';
265
- // timeToCalibrateDisplay.style.paddingTop = '20px';
266
- }
267
-
268
- // Update title - titleDisplayId
269
- const titleDisplay = document.getElementById(this.titleDisplayId);
270
- if (titleDisplay) {
271
- // replace 5 with 6
272
- titleDisplay.innerHTML = this.isSmartPhone
273
- ? titleDisplay.innerHTML.replace('2', '3')
274
- : titleDisplay.innerHTML.replace('4', '5');
275
- }
276
- };
277
-
278
- #removeUIElems = () => {
279
- const parent = document.getElementById(this.targetElement);
280
- while (parent.firstChild) {
281
- parent.firstChild.remove();
282
- }
283
- };
284
-
285
- /**
286
- * Called when the peer connection is opened.
287
- * Saves the peer id and calls the QR code generator.
288
- *
289
- * @param peerId - The peer id of the peer connection.
290
- * @param id
291
- * @private
292
- * @example
293
- */
294
- #onPeerOpen = id => {
295
- // Workaround for peer.reconnect deleting previous id
296
- if (id === null) {
297
- console.error('Received null id from peer open');
298
- this.peer.id = this.lastPeerId;
299
- } else {
300
- this.lastPeerId = this.peer.id;
301
- }
302
-
303
- if (id !== this.peer.id) {
304
- console.warn('DEBUG Check you assumption that id === this.peer.id');
305
- }
306
-
307
- this.#showQRCode();
308
- };
309
-
310
- /**
311
- * Called when the peer connection is established.
312
- * Enforces a single connection.
313
- *
314
- * @param connection - The connection object.
315
- * @private
316
- * @example
317
- */
318
- #onPeerConnection = connection => {
319
- // Allow only a single connection
320
- if (this.conn && this.conn.open) {
321
- connection.on('open', () => {
322
- connection.send('Already connected to another client');
323
- setTimeout(() => {
324
- connection.close();
325
- }, 500);
326
- });
327
- return;
328
- }
329
-
330
- this.conn = connection;
331
- console.log('Connected to: ', this.conn.peer);
332
- this.#ready();
333
- };
334
-
335
- /**
336
- * Called when the peer connection is closed.
337
- *
338
- * @private
339
- * @example
340
- */
341
- #onPeerClose = () => {
342
- this.conn = null;
343
- console.log('Connection destroyed');
344
- };
345
-
346
- /**
347
- * Called when the peer connection is disconnected.
348
- * Attempts to reconnect.
349
- *
350
- * @private
351
- * @example
352
- */
353
- #onPeerDisconnected = () => {
354
- console.log('Connection lost. Please reconnect');
355
-
356
- // Workaround for peer.reconnect deleting previous id
357
- this.peer.id = this.lastPeerId;
358
- // eslint-disable-next-line no-underscore-dangle
359
- this.peer._lastServerId = this.lastPeerId;
360
- this.peer.reconnect();
361
- };
362
-
363
- /**
364
- * Called when the peer connection encounters an error.
365
- *
366
- * @param error
367
- * @private
368
- * @example
369
- */
370
- #onPeerError = error => {
371
- // TODO: check if this function is needed or not
372
- console.error(error);
373
- };
374
-
375
- /**
376
- * Called when data is received from the peer connection.
377
- *
378
- * @param data
379
- * @private
380
- * @example
381
- */
382
- #onIncomingData = data => {
383
- // enforce object type
384
- if (
385
- !Object.prototype.hasOwnProperty.call(data, 'name') ||
386
- !Object.prototype.hasOwnProperty.call(data, 'payload')
387
- ) {
388
- console.error('Received malformed data: ', data);
389
- return;
390
- }
391
-
392
- switch (data.name) {
393
- case 'samplingRate':
394
- this.ac.setSamplingRates(data.payload);
395
- break;
396
- case 'sampleSize':
397
- this.ac.setSampleSize(data.payload);
398
- break;
399
- case 'deviceType':
400
- this.ac.setDeviceType(data.payload);
401
- break;
402
- case 'deviceName':
403
- this.ac.setDeviceName(data.payload);
404
- break;
405
- case 'deviceInfo':
406
- this.ac.setDeviceInfo(data.payload);
407
- console.log('Received device info from listener: ', data.payload);
408
- break;
409
- case UnsupportedDeviceError.name:
410
- case MissingSpeakerIdError.name:
411
- throw data.payload;
412
- break;
413
- default:
414
- break;
415
- }
416
- };
417
-
418
- /**
419
- * Called when the peer connection is #ready.
420
- *
421
- * @private
422
- * @example
423
- */
424
- #ready = () => {
425
- // Perform callback with data
426
- this.conn.on('data', this.#onIncomingData);
427
- this.conn.on('close', () => {
428
- console.log('Connection reset<br>Awaiting connection...');
429
- this.conn = null;
430
- });
431
- };
432
-
433
- /** .
434
- * .
435
- * .
436
- * Debug method for downloading the recorded audio
437
- *
438
- * @public
439
- * @example
440
- */
441
- downloadData = () => {
442
- this.ac.downloadData();
443
- };
444
- }
445
-
446
- /*
447
- Referenced links:
448
- https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
449
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
450
- https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
451
- */
452
-
453
- 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 {phrases} from '../../dist/example/i18n';
11
+
12
+ /**
13
+ * @class Handles the speaker's side of the connection. Responsible for initiating the connection,
14
+ * rendering the QRCode, and answering the call.
15
+ * @augments AudioPeer
16
+ */
17
+ class Speaker extends AudioPeer {
18
+ /**
19
+ * Takes the url of the current site and a target element where html elements will be appended.
20
+ *
21
+ * @param params - See type definition for initParameters.
22
+ * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.
23
+ * @param CalibratorInstance
24
+ * @example
25
+ */
26
+ constructor(params, CalibratorInstance) {
27
+ super(params);
28
+ this.language = params?.language ?? 'en-US';
29
+ this.siteUrl += '/listener?';
30
+ this.ac = CalibratorInstance;
31
+ this.result = null;
32
+ this.debug = params?.debug ?? false;
33
+ this.isSmartPhone = params?.isSmartPhone ?? false;
34
+ this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;
35
+ this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;
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
+ * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.
51
+ *
52
+ * @param params - The parameters to be passed to the peer object.
53
+ * @param Calibrator - The class that defines the calibration process.
54
+ * @param CalibratorInstance
55
+ * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).
56
+ * @public
57
+ * @example
58
+ */
59
+ static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {
60
+ window.speaker = new Speaker(params, CalibratorInstance);
61
+ const {speaker} = window;
62
+
63
+ // wrap the calibration process in a promise so we can await it
64
+ return new Promise((resolve, reject) => {
65
+ // when a call is received
66
+ speaker.peer.on('call', async call => {
67
+ // Answer the call (one way)
68
+
69
+ call.answer();
70
+ speaker.#removeUIElems();
71
+ speaker.#showSpinner();
72
+ speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
73
+ // when we start receiving audio
74
+ call.on('stream', async stream => {
75
+ window.localStream = stream;
76
+ window.localAudio.srcObject = stream;
77
+ window.localAudio.autoplay = false;
78
+
79
+ // if the sinkSamplingRate is not set sleep
80
+ while (!speaker.ac.sampleRatesSet()) {
81
+ console.log('SinkSamplingRate is undefined, sleeping');
82
+ await sleep(1);
83
+ }
84
+ // resolve when we have a result
85
+ speaker.result = await speaker.ac.startCalibration(
86
+ stream,
87
+ params.gainValues,
88
+ params.ICalib,
89
+ params.knownIR,
90
+ params.microphoneName,
91
+ params.calibrateSoundCheck,
92
+ params.isSmartPhone,
93
+ params.calibrateSoundBurstDb,
94
+ params.calibrateSoundBurstRepeats,
95
+ params.calibrateSoundBurstSec,
96
+ params.calibrateSoundBurstsWarmup,
97
+ params.calibrateSoundHz,
98
+ params.calibrateSoundIRSec,
99
+ params.calibrateSoundIIRSec,
100
+ params.calibrateSound1000HzPreSec,
101
+ params.calibrateSound1000HzSec,
102
+ params.calibrateSound1000HzPostSec,
103
+ params.calibrateSoundBackgroundSecs,
104
+ params.calibrateSoundSmoothOctaves,
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
+ calibrateSoundSamplingDesiredBits: this.calibrateSoundSamplingDesiredBits,
184
+ lang: this.language,
185
+ };
186
+ const queryString = this.queryStringFromObject(queryStringParameters);
187
+ const uri = this.siteUrl + queryString;
188
+ if (this.isSmartPhone) {
189
+ // Display QR code for the participant to scan
190
+ const qrCanvas = document.createElement('canvas');
191
+ qrCanvas.setAttribute('id', 'qrCanvas');
192
+ console.log(uri);
193
+ QRCode.toCanvas(qrCanvas, uri, error => {
194
+ if (error) console.error(error);
195
+ });
196
+ document.getElementById(this.targetElement).appendChild(qrCanvas);
197
+ } else {
198
+ // show the link to the user
199
+ // If specified HTML Id is available, show QR code there
200
+ if (document.getElementById(this.targetElement)) {
201
+ // const linkTag = document.createElement('a');
202
+ // linkTag.setAttribute('href', uri);
203
+ // linkTag.innerHTML = 'Click here to start the calibration';
204
+ // linkTag.target = '_blank';
205
+ // document.getElementById(this.targetElement).appendChild(linkTag);
206
+ // document.getElementById(this.targetElement).appendChild(qrCanvas);
207
+
208
+ const proceedButton = document.createElement('button');
209
+ proceedButton.setAttribute('id', 'calibrationProceedButton');
210
+ proceedButton.setAttribute('class', 'btn btn-success');
211
+ proceedButton.innerHTML = 'Proceed';
212
+ proceedButton.onclick = () => {
213
+ // open the link in a new tab
214
+ window.open(uri, '_blank');
215
+ // remove the button
216
+ document.getElementById('calibrationProceedButton').remove();
217
+ };
218
+ document.getElementById(this.targetElement).appendChild(proceedButton);
219
+ }
220
+ }
221
+ // or just print it to console
222
+ console.log('TEST: Peer reachable at: ', uri);
223
+ };
224
+
225
+ #showSpinner = () => {
226
+ const spinner = document.createElement('div');
227
+ spinner.className = 'spinner-border ml-auto';
228
+ spinner.role = 'status';
229
+ spinner.ariaHidden = 'true';
230
+ document.getElementById(this.targetElement).appendChild(spinner);
231
+
232
+ // clear instructionDisplay
233
+ const soundMessage = document.getElementById(this.soundMessageId);
234
+ soundMessage.innerHTML = '';
235
+ soundMessage.style.display = 'none';
236
+ const instructionDisplay = document.getElementById(this.instructionDisplayId);
237
+ const background = document.getElementById('background'); // todo: get background id from params
238
+ if (instructionDisplay) {
239
+ instructionDisplay.innerHTML = '';
240
+ instructionDisplay.style.whiteSpace = 'nowrap';
241
+ instructionDisplay.style.fontWeight = 'bold';
242
+ instructionDisplay.style.width = 'fit-content';
243
+ instructionDisplay.innerHTML = phrases.RC_soundRecording[this.language];
244
+ let fontSize = 100;
245
+ instructionDisplay.style.fontSize = fontSize + 'px';
246
+ while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
247
+ fontSize--;
248
+ instructionDisplay.style.fontSize = fontSize + 'px';
249
+ }
250
+ // const p = document.createElement('p');
251
+ // // font size
252
+ // p.style.fontSize = '1.1rem';
253
+ // p.style.fontWeight = 'normal';
254
+ // p.style.paddingTop = '20px';
255
+ // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
256
+ // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
257
+ // instructionDisplay.appendChild(p);
258
+ }
259
+
260
+ const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
261
+ if (timeToCalibrateDisplay) {
262
+ const timeToCalibrateText = phrases.RC_howLongToCalibrate[this.language];
263
+ timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
264
+ timeToCalibrateDisplay.style.fontWeight = 'normal';
265
+ timeToCalibrateDisplay.style.fontSize = '1rem';
266
+ // timeToCalibrateDisplay.style.paddingTop = '20px';
267
+ }
268
+
269
+ // Update title - titleDisplayId
270
+ const titleDisplay = document.getElementById(this.titleDisplayId);
271
+ if (titleDisplay) {
272
+ // replace 5 with 6
273
+ titleDisplay.innerHTML = this.isSmartPhone
274
+ ? titleDisplay.innerHTML.replace('2', '3')
275
+ : titleDisplay.innerHTML.replace('4', '5');
276
+ }
277
+ };
278
+
279
+ #removeUIElems = () => {
280
+ const parent = document.getElementById(this.targetElement);
281
+ while (parent.firstChild) {
282
+ parent.firstChild.remove();
283
+ }
284
+ };
285
+
286
+ /**
287
+ * Called when the peer connection is opened.
288
+ * Saves the peer id and calls the QR code generator.
289
+ *
290
+ * @param peerId - The peer id of the peer connection.
291
+ * @param id
292
+ * @private
293
+ * @example
294
+ */
295
+ #onPeerOpen = id => {
296
+ // Workaround for peer.reconnect deleting previous id
297
+ if (id === null) {
298
+ console.error('Received null id from peer open');
299
+ this.peer.id = this.lastPeerId;
300
+ } else {
301
+ this.lastPeerId = this.peer.id;
302
+ }
303
+
304
+ if (id !== this.peer.id) {
305
+ console.warn('DEBUG Check you assumption that id === this.peer.id');
306
+ }
307
+
308
+ this.#showQRCode();
309
+ };
310
+
311
+ /**
312
+ * Called when the peer connection is established.
313
+ * Enforces a single connection.
314
+ *
315
+ * @param connection - The connection object.
316
+ * @private
317
+ * @example
318
+ */
319
+ #onPeerConnection = connection => {
320
+ // Allow only a single connection
321
+ if (this.conn && this.conn.open) {
322
+ connection.on('open', () => {
323
+ connection.send('Already connected to another client');
324
+ setTimeout(() => {
325
+ connection.close();
326
+ }, 500);
327
+ });
328
+ return;
329
+ }
330
+
331
+ this.conn = connection;
332
+ console.log('Connected to: ', this.conn.peer);
333
+ this.#ready();
334
+ };
335
+
336
+ /**
337
+ * Called when the peer connection is closed.
338
+ *
339
+ * @private
340
+ * @example
341
+ */
342
+ #onPeerClose = () => {
343
+ this.conn = null;
344
+ console.log('Connection destroyed');
345
+ };
346
+
347
+ /**
348
+ * Called when the peer connection is disconnected.
349
+ * Attempts to reconnect.
350
+ *
351
+ * @private
352
+ * @example
353
+ */
354
+ #onPeerDisconnected = () => {
355
+ console.log('Connection lost. Please reconnect');
356
+
357
+ // Workaround for peer.reconnect deleting previous id
358
+ this.peer.id = this.lastPeerId;
359
+ // eslint-disable-next-line no-underscore-dangle
360
+ this.peer._lastServerId = this.lastPeerId;
361
+ this.peer.reconnect();
362
+ };
363
+
364
+ /**
365
+ * Called when the peer connection encounters an error.
366
+ *
367
+ * @param error
368
+ * @private
369
+ * @example
370
+ */
371
+ #onPeerError = error => {
372
+ // TODO: check if this function is needed or not
373
+ console.error(error);
374
+ };
375
+
376
+ /**
377
+ * Called when data is received from the peer connection.
378
+ *
379
+ * @param data
380
+ * @private
381
+ * @example
382
+ */
383
+ #onIncomingData = data => {
384
+ // enforce object type
385
+ if (
386
+ !Object.prototype.hasOwnProperty.call(data, 'name') ||
387
+ !Object.prototype.hasOwnProperty.call(data, 'payload')
388
+ ) {
389
+ console.error('Received malformed data: ', data);
390
+ return;
391
+ }
392
+
393
+ switch (data.name) {
394
+ case 'samplingRate':
395
+ this.ac.setSamplingRates(data.payload);
396
+ break;
397
+ case 'sampleSize':
398
+ this.ac.setSampleSize(data.payload);
399
+ break;
400
+ case 'deviceType':
401
+ this.ac.setDeviceType(data.payload);
402
+ break;
403
+ case 'deviceName':
404
+ this.ac.setDeviceName(data.payload);
405
+ break;
406
+ case 'deviceInfo':
407
+ this.ac.setDeviceInfo(data.payload);
408
+ console.log('Received device info from listener: ', data.payload);
409
+ break;
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;