speaker-calibration 2.2.98 → 2.2.100

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