speaker-calibration 2.2.187 → 2.2.189

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 (121) 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/NoSleep.min.js +1 -1
  31. package/dist/example/fetch-languages-sheets.js +77 -77
  32. package/dist/example/i18n.js +26951 -26513
  33. package/dist/example/index.html +47 -47
  34. package/dist/example/listener.html +79 -79
  35. package/dist/example/listener.js +149 -149
  36. package/dist/example/server.js +51 -51
  37. package/dist/example/speaker.html +145 -145
  38. package/dist/example/speakerUI.js +273 -273
  39. package/dist/example/styles.css +99 -99
  40. package/dist/main.js +17 -17
  41. package/dist/mlsGen.js +6814 -6814
  42. package/dist/mlsGen.wasm +0 -0
  43. package/dist/package-lock.json +1018 -1018
  44. package/dist/package.json +18 -18
  45. package/doc/AudioCalibrator.html +417 -417
  46. package/doc/AudioPeer.html +251 -251
  47. package/doc/AudioRecorder.html +195 -195
  48. package/doc/ImpulseResponse.html +215 -215
  49. package/doc/Listener.html +308 -308
  50. package/doc/MlsGenInterface.html +226 -226
  51. package/doc/MyEventEmitter.html +274 -274
  52. package/doc/PythonServerAPI.html +109 -109
  53. package/doc/Speaker.html +276 -276
  54. package/doc/Takes%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +128 -128
  55. package/doc/Takes%20the%20url%20of%20the%20current%20site%0Aand%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +138 -138
  56. package/doc/Takes%20the%20url%20of%20the%20current%20site%20and%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +137 -137
  57. package/doc/Volume.html +88 -88
  58. package/doc/audioCalibrator.js.html +179 -179
  59. package/doc/audioPeer.js.html +175 -175
  60. package/doc/audioRecorder.js.html +163 -163
  61. package/doc/creates%20a%20new%20AudioRecorder%20instance.%20%0ASets%20up%20the%20audio%20context%20and%20file%20reader..html +114 -114
  62. package/doc/fonts/OpenSans-Bold-webfont.svg +1829 -1829
  63. package/doc/fonts/OpenSans-BoldItalic-webfont.svg +1829 -1829
  64. package/doc/fonts/OpenSans-Italic-webfont.svg +1829 -1829
  65. package/doc/fonts/OpenSans-Light-webfont.svg +1830 -1830
  66. package/doc/fonts/OpenSans-LightItalic-webfont.svg +1834 -1834
  67. package/doc/fonts/OpenSans-Regular-webfont.svg +1830 -1830
  68. package/doc/global.html +308 -308
  69. package/doc/index.html +58 -58
  70. package/doc/listener.js.html +170 -170
  71. package/doc/mlsGen_mlsGenInterface.js.html +117 -117
  72. package/doc/myEventEmitter.js.html +124 -124
  73. package/doc/peer-connection_audioPeer.js.html +188 -188
  74. package/doc/peer-connection_listener.js.html +311 -311
  75. package/doc/peer-connection_speaker.js.html +381 -381
  76. package/doc/scripts/linenumber.js +25 -25
  77. package/doc/scripts/prettify/Apache-License-2.0.txt +202 -202
  78. package/doc/scripts/prettify/lang-css.js +24 -24
  79. package/doc/scripts/prettify/prettify.js +640 -640
  80. package/doc/server_PythonServerAPI.js.html +160 -160
  81. package/doc/speaker.js.html +248 -248
  82. package/doc/styles/jsdoc-default.css +371 -371
  83. package/doc/styles/prettify-jsdoc.css +111 -111
  84. package/doc/styles/prettify-tomorrow.css +163 -163
  85. package/doc/tasks_audioCalibrator.js.html +207 -207
  86. package/doc/tasks_audioRecorder.js.html +190 -190
  87. package/doc/tasks_impulse-response_impulseResponse.js.html +442 -442
  88. package/doc/tasks_impulse-response_mlsGen_mlsGenInterface.js.html +175 -175
  89. package/doc/tasks_volume_volume.js.html +185 -185
  90. package/doc/utils.js.html +105 -105
  91. package/jest.config.js +173 -173
  92. package/netlify.toml +26 -26
  93. package/package.json +72 -72
  94. package/src/config/firebase.js +26 -26
  95. package/src/index.html +21 -21
  96. package/src/main.js +23 -23
  97. package/src/myEventEmitter.js +83 -83
  98. package/src/peer-connection/audioPeer.js +178 -178
  99. package/src/peer-connection/listener.js +340 -340
  100. package/src/peer-connection/peerErrors.js +25 -25
  101. package/src/peer-connection/speaker.js +722 -716
  102. package/src/server/PythonServerAPI.js +826 -830
  103. package/src/tasks/audioCalibrator.js +332 -323
  104. package/src/tasks/audioRecorder.js +315 -315
  105. package/src/tasks/combination/combination.js +2994 -2970
  106. package/src/tasks/combination/mlsGen/mlsGen.cpp +98 -98
  107. package/src/tasks/combination/mlsGen/mlsGen.hpp +303 -303
  108. package/src/tasks/combination/mlsGen/mlsGenInterface.js +131 -131
  109. package/src/tasks/combination/mlsGen/mlsGenTest.cpp +180 -180
  110. package/src/tasks/impulse-response/impulseResponse.js +610 -610
  111. package/src/tasks/impulse-response/mlsGen/mlsGen.cpp +98 -98
  112. package/src/tasks/impulse-response/mlsGen/mlsGen.hpp +303 -303
  113. package/src/tasks/impulse-response/mlsGen/mlsGenInterface.js +131 -131
  114. package/src/tasks/impulse-response/mlsGen/mlsGenTest.cpp +180 -180
  115. package/src/tasks/volume/volume.cpp +2 -2
  116. package/src/tasks/volume/volume.hpp +22 -22
  117. package/src/tasks/volume/volume.js +279 -279
  118. package/src/utils.js +205 -205
  119. package/webpack.config.js +37 -37
  120. package/.github/workflows/update-phrases.yml +0 -37
  121. package/makefile +0 -74
@@ -1,716 +1,722 @@
1
- import QRCode from 'qrcode';
2
- import AudioPeer from './audioPeer';
3
- import {sleep, formatLineBreak, createAndShowPopup} 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
- this.isParticipant = params?.isParticipant ?? false;
43
- this.isLoudspeakerCalibration = params?.isLoudspeakerCalibration ?? false;
44
- this.buttonsContainer = params?.buttonsContainer ?? document.createElement('div');
45
-
46
- /* Set up callbacks that handle any events related to our peer object. */
47
- }
48
-
49
- uri = '';
50
- qrImage;
51
- shortURL;
52
-
53
- initPeer = async () => {
54
- const id = await this.generateTimeBasedPeerID();
55
- this.peer = new Peer(id, {
56
- secure: true,
57
- host: 'easyeyes-peer-server.herokuapp.com',
58
- port: 443,
59
- config: {
60
- iceServers: [
61
- {
62
- urls: 'stun:stun.relay.metered.ca:80',
63
- },
64
- {
65
- urls: 'turn:global.relay.metered.ca:80',
66
- username: 'de884cfc34189cdf1a5dd616',
67
- credential: 'IcOpouU9/TYBmpHU',
68
- },
69
- {
70
- urls: 'turn:global.relay.metered.ca:80?transport=tcp',
71
- username: 'de884cfc34189cdf1a5dd616',
72
- credential: 'IcOpouU9/TYBmpHU',
73
- },
74
- {
75
- urls: 'turn:global.relay.metered.ca:443',
76
- username: 'de884cfc34189cdf1a5dd616',
77
- credential: 'IcOpouU9/TYBmpHU',
78
- },
79
- {
80
- urls: 'turns:global.relay.metered.ca:443?transport=tcp',
81
- username: 'de884cfc34189cdf1a5dd616',
82
- credential: 'IcOpouU9/TYBmpHU',
83
- },
84
- ],
85
- },
86
- });
87
- this.peer.on('open', this.#onPeerOpen);
88
- this.peer.on('connection', this.#onPeerConnection);
89
- this.peer.on('close', this.onPeerClose);
90
- this.peer.on('disconnected', this.#onPeerDisconnected);
91
- this.peer.on('error', this.#onPeerError);
92
- };
93
- generateTimeBasedPeerID = async () => {
94
- const now = new Date().getTime();
95
- const randomBuffer = new Uint8Array(10);
96
- crypto.getRandomValues(randomBuffer);
97
- const randomPart = Array.from(randomBuffer)
98
- .map(b => b.toString(36))
99
- .join('');
100
- const toHash = `${now}-${randomPart}`;
101
- const encoder = new TextEncoder();
102
- const data = encoder.encode(toHash);
103
- const hash = await crypto.subtle.digest('SHA-256', data);
104
- const hashArray = Array.from(new Uint8Array(hash)); // Convert buffer to byte array
105
- const hashString = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
106
- const shortHash = hashString.substring(0, 12); // Use more of the hash for a longer ID
107
- // return shortHash; // Consider converting this to Base62
108
- return this.encodeBase62(parseInt(shortHash, 16));
109
- };
110
-
111
- encodeBase62 = num => {
112
- const base = 36;
113
- const characters = '0123456789abcdefghijklmnopqrstuvwxyz';
114
- let result = '';
115
- while (num > 0) {
116
- result = characters[num % base] + result;
117
- num = Math.floor(num / base);
118
- }
119
- return result;
120
- };
121
-
122
- /**
123
- * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.
124
- *
125
- * @param params - The parameters to be passed to the peer object.
126
- * @param Calibrator - The class that defines the calibration process.
127
- * @param CalibratorInstance
128
- * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).
129
- * @public
130
- * @example
131
- */
132
- static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {
133
- window.speaker = new Speaker(params, CalibratorInstance);
134
- const {speaker} = window;
135
- await speaker.initPeer();
136
- // wrap the calibration process in a promise so we can await it
137
- return new Promise((resolve, reject) => {
138
- // when a call is received
139
- speaker.peer.on('call', async call => {
140
- // Answer the call (one way)
141
-
142
- call.answer();
143
- speaker.#removeUIElems();
144
- speaker.#showSpinner();
145
- speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
146
- // when we start receiving audio
147
- call.on('stream', async stream => {
148
- window.localStream = stream;
149
- window.localAudio.srcObject = stream;
150
- window.localAudio.autoplay = false;
151
-
152
- // if the sinkSamplingRate is not set sleep
153
- while (!speaker.ac.sampleRatesSet()) {
154
- console.log('SinkSamplingRate is undefined, sleeping');
155
- await sleep(1);
156
- }
157
-
158
- if (params.displayUpdate) {
159
- params.displayUpdate.style.display = '';
160
- }
161
-
162
- // resolve when we have a result
163
- speaker.result = await speaker.ac.startCalibration(
164
- stream,
165
- params.gainValues,
166
- params.ICalib,
167
- params.knownIR,
168
- params.microphoneName,
169
- params.calibrateSoundCheck,
170
- params.isSmartPhone,
171
- params.calibrateSoundBurstDb,
172
- params.calibrateSoundBurstFilteredExtraDb,
173
- params.calibrateSoundBurstLevelReTBool,
174
- params.calibrateSoundBurstUses1000HzGainBool,
175
- params.calibrateSoundBurstRepeats,
176
- params.calibrateSoundBurstSec,
177
- params.calibrateSoundBurstsWarmup,
178
- params.calibrateSoundHz,
179
- params.calibrateSoundIRSec,
180
- params.calibrateSoundIIRSec,
181
- params.calibrateSoundIIRPhase,
182
- params.calibrateSound1000HzPreSec,
183
- params.calibrateSound1000HzSec,
184
- params.calibrateSound1000HzPostSec,
185
- params.calibrateSoundBackgroundSecs,
186
- params.calibrateSoundSmoothOctaves,
187
- params.calibrateSoundSmoothMinBandwidthHz,
188
- params.calibrateSoundPowerBinDesiredSec,
189
- params.calibrateSoundPowerDbSDToleratedDb,
190
- params.calibrateSoundTaperSec,
191
- params.micManufacturer,
192
- params.micSerialNumber,
193
- params.micModelNumber,
194
- params.micModelName,
195
- params.calibrateMicrophonesBool,
196
- params.authorEmails,
197
- params.webAudioDeviceNames,
198
- params.IDsToSaveInSoundProfileLibrary,
199
- params.restartButton,
200
- params.reminder,
201
- params.calibrateSoundLimit,
202
- params.calibrateSoundBurstNormalizeBy1000HzGainBool,
203
- params.calibrateSoundBurstScalarDB
204
- );
205
- speaker.#removeUIElems();
206
- resolve(speaker.result);
207
- });
208
- // if we do not receive a result within the timeout, reject
209
- setTimeout(() => {
210
- reject(
211
- new CalibrationTimedOutError(
212
- `Calibration failed to produce a result after ${
213
- timeOut / 1000
214
- } seconds. Please try again.`
215
- )
216
- );
217
- }, timeOut);
218
- });
219
- });
220
- };
221
-
222
- static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {
223
- window.speaker = new Speaker(params, CalibratorInstance);
224
- const {speaker} = window;
225
- speaker.initPeer();
226
- // wrap the calibration process in a promise so we can await it
227
- return new Promise((resolve, reject) => {
228
- // when a call is received
229
- speaker.peer.on('call', async call => {
230
- // Answer the call (one way)
231
- call.answer();
232
- speaker.#removeUIElems();
233
- speaker.#showSpinner();
234
- speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
235
- // when we start receiving audio
236
- call.on('stream', async stream => {
237
- window.localStream = stream;
238
- window.localAudio.srcObject = stream;
239
- window.localAudio.autoplay = false;
240
-
241
- // if the sinkSamplingRate is not set sleep
242
- while (!speaker.ac.sampleRatesSet()) {
243
- console.log('SinkSamplingRate is undefined, sleeping');
244
- await sleep(1);
245
- }
246
- // resolve when we have a result
247
- speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);
248
- speaker.#removeUIElems();
249
- resolve(speaker.result);
250
- });
251
- // if we do not receive a result within the timeout, reject
252
- setTimeout(() => {
253
- reject(
254
- new CalibrationTimedOutError(
255
- `Calibration failed to produce a result after ${
256
- timeOut / 1000
257
- } seconds. Please try again.`
258
- )
259
- );
260
- }, timeOut);
261
- });
262
- });
263
- };
264
-
265
- /**
266
- * Called after the peer conncection has been opened.
267
- * Generates a QR code for the connection and displays it.
268
- *
269
- * @private
270
- * @example
271
- */
272
-
273
- #showQRCode = async () => {
274
- // Get query string, the URL parameters to specify a Listener
275
- const queryStringParameters = {
276
- speakerPeerId: this.peer.id,
277
- sp: this.isSmartPhone,
278
- hz: this.calibrateSoundHz,
279
- bits: this.calibrateSoundSamplingDesiredBits,
280
- lang: this.language,
281
- };
282
- const queryString = this.queryStringFromObject(queryStringParameters);
283
- this.uri = this.siteUrl + queryString;
284
- if (this.isSmartPhone) {
285
- // if (true) { // test smartphone QR
286
- // Display QR code for the participant to scan
287
- const qrCanvas = document.createElement('canvas');
288
- qrCanvas.setAttribute('id', 'qrCanvas');
289
- QRCode.toCanvas(qrCanvas, this.uri, error => {
290
- if (error) console.error(error);
291
- });
292
- const explanation = document.createElement('h2');
293
- explanation.id = 'skipQRExplanation';
294
- explanation.style = `
295
- user-select: text;
296
- margin-top: 9px;
297
- font-size: 1.1rem;
298
- `;
299
- // Define the URL and options for the request
300
- const url = 'https://api.short.io/links/public';
301
- const options = {
302
- method: 'POST',
303
- headers: {
304
- Accept: 'application/json',
305
- 'Content-Type': 'application/json',
306
- Authorization: 'pk_fysLKGj3legZz4XZ',
307
- },
308
- body: JSON.stringify({
309
- domain: 'listeners.link', // Ensure this domain is valid for your account
310
- originalURL: this.uri,
311
- }),
312
- };
313
-
314
- // Make the request using fetch
315
- await fetch(url, options)
316
- .then(response => {
317
- if (!response.ok) {
318
- throw new Error(`HTTP error! Status: ${response.status}`);
319
- }
320
- return response.json(); // Parse the JSON response
321
- })
322
- .then(data => {
323
- explanation.innerHTML = formatLineBreak(
324
- phrases.RC_skipQR_ExplanationWithoutPreferNot[this.language]
325
- .replace('xxx', `<b style="user-select: text">${data.shortURL}</b>`)
326
- .replace('XXX', `<b style="user-select: text">${data.shortURL}</b>`),
327
- phrases.RC_checkInternetConnection[this.language]
328
- );
329
- const checkConnection = document.createElement('a');
330
- checkConnection.id = 'check-connection';
331
- checkConnection.href = '#';
332
- checkConnection.innerHTML = "check the phone's internet connection";
333
- const lang = this.language;
334
- checkConnection.addEventListener('click', function (event) {
335
- console.log('clicked');
336
- event.preventDefault(); // Prevent the default link action
337
- createAndShowPopup(lang);
338
- });
339
- explanation.querySelector('a#check-connection').replaceWith(checkConnection);
340
- })
341
- .catch(error => {
342
- console.error('Error:', error.message); // Handle errors
343
- });
344
-
345
- const qrImage = new Image(400, 400);
346
- qrImage.setAttribute('id', 'compatibilityCheckQRImage');
347
- qrImage.style.zIndex = Infinity;
348
- qrImage.style.width = 400;
349
- qrImage.style.height = 400;
350
- qrImage.style.aspectRatio = 1;
351
- qrImage.src = qrCanvas.toDataURL();
352
- qrImage.style.maxHeight = '150px';
353
- qrImage.style.maxWidth = '150px';
354
-
355
- this.qrImage = qrImage;
356
-
357
- const container = document.createElement('div');
358
- container.style.display = 'flex';
359
- container.style.justifyContent = 'space-between';
360
- container.style.alignItems = 'top';
361
- container.id = 'skipQRContainer';
362
- container.appendChild(qrImage);
363
- container.appendChild(explanation);
364
- container.appendChild(this.buttonsContainer);
365
- const qrContainer = document.createElement('div');
366
- qrContainer.appendChild(container);
367
-
368
- document.getElementById(this.targetElement).appendChild(qrContainer);
369
- } else {
370
- // show the link to the user
371
- // If specified HTML Id is available, show QR code there
372
- if (document.getElementById(this.targetElement)) {
373
- // const linkTag = document.createElement('a');
374
- // linkTag.setAttribute('href', uri);
375
- // linkTag.innerHTML = 'Click here to start the calibration';
376
- // linkTag.target = '_blank';
377
- // document.getElementById(this.targetElement).appendChild(linkTag);
378
- // document.getElementById(this.targetElement).appendChild(qrCanvas);
379
-
380
- const proceedButton = document.createElement('button');
381
- proceedButton.setAttribute('id', 'calibrationProceedButton');
382
- proceedButton.setAttribute('class', 'btn btn-success');
383
- proceedButton.innerHTML = phrases.T_proceed[this.language];
384
- proceedButton.onclick = () => {
385
- // open the link in a new tab
386
- window.open(this.uri, '_blank');
387
- // remove the button
388
- document.getElementById('calibrationProceedButton').remove();
389
- };
390
- document.getElementById(this.targetElement).appendChild(proceedButton);
391
- }
392
- }
393
- // or just print it to console
394
- console.log('TEST: Peer reachable at: ', this.uri);
395
- };
396
-
397
- #showSpinner = () => {
398
- const spinner = document.createElement('div');
399
- spinner.className = 'spinner-border ml-auto';
400
- spinner.role = 'status';
401
- spinner.ariaHidden = 'true';
402
- document.getElementById(this.targetElement).appendChild(spinner);
403
-
404
- // clear instructionDisplay
405
- const soundMessage = document.getElementById(this.soundMessageId);
406
- soundMessage.innerHTML = '';
407
- soundMessage.style.display = 'none';
408
- const instructionDisplay = document.getElementById(this.instructionDisplayId);
409
- const background = document.getElementById('background'); // todo: get background id from params
410
- const subtitle = document.getElementById(this.soundSubtitleId);
411
- if (subtitle) {
412
- subtitle.innerHTML = '';
413
- }
414
- if (instructionDisplay) {
415
- instructionDisplay.innerHTML = '';
416
- instructionDisplay.style.whiteSpace = 'nowrap';
417
- instructionDisplay.style.fontWeight = 'bold';
418
- instructionDisplay.style.width = 'fit-content';
419
- instructionDisplay.innerHTML = phrases.RC_soundRecording[this.language];
420
- let fontSize = 100;
421
- instructionDisplay.style.fontSize = fontSize + 'px';
422
- while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
423
- fontSize--;
424
- instructionDisplay.style.fontSize = fontSize + 'px';
425
- }
426
- // const p = document.createElement('p');
427
- // // font size
428
- // p.style.fontSize = '1.1rem';
429
- // p.style.fontWeight = 'normal';
430
- // p.style.paddingTop = '20px';
431
- // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
432
- // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
433
- // instructionDisplay.appendChild(p);
434
- }
435
-
436
- const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
437
- if (timeToCalibrateDisplay) {
438
- const timeToCalibrateText = phrases.RC_howLongToCalibrate[this.language];
439
- timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
440
- timeToCalibrateDisplay.style.fontWeight = 'normal';
441
- timeToCalibrateDisplay.style.fontSize = '1rem';
442
- // timeToCalibrateDisplay.style.paddingTop = '20px';
443
- }
444
-
445
- // Update title - titleDisplayId
446
- const titleDisplay = document.getElementById(this.titleDisplayId);
447
- if (titleDisplay) {
448
- // if (this.isParticipant) {
449
- // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
450
- // } else if (this.isSmartPhone) {
451
- // if (this.isLoudspeakerCalibration) {
452
- // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
453
- // } else {
454
- // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
455
- // }
456
- // } else {
457
- // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
458
- // }
459
- if (this.isLoudspeakerCalibration) {
460
- if (this.isParticipant) {
461
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
462
- } else if (this.isSmartPhone) {
463
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
464
- } else {
465
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
466
- }
467
- } else {
468
- if (this.isSmartPhone) {
469
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
470
- } else {
471
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('4', '5');
472
- }
473
- }
474
- }
475
- };
476
-
477
- #removeUIElems = () => {
478
- const parent = document.getElementById(this.targetElement);
479
- while (parent.firstChild) {
480
- parent.firstChild.remove();
481
- }
482
- };
483
-
484
- /**
485
- * Called when the peer connection is opened.
486
- * Saves the peer id and calls the QR code generator.
487
- *
488
- * @param peerId - The peer id of the peer connection.
489
- * @param id
490
- * @private
491
- * @example
492
- */
493
- #onPeerOpen = id => {
494
- // Workaround for peer.reconnect deleting previous id
495
- if (id === null) {
496
- console.error('Received null id from peer open');
497
- this.peer.id = this.lastPeerId;
498
- } else {
499
- this.lastPeerId = this.peer.id;
500
- }
501
-
502
- if (id !== this.peer.id) {
503
- console.warn('DEBUG Check you assumption that id === this.peer.id');
504
- }
505
-
506
- this.#showQRCode();
507
- };
508
-
509
- /**
510
- * Called when the peer connection is established.
511
- * Enforces a single connection.
512
- *
513
- * @param connection - The connection object.
514
- * @private
515
- * @example
516
- */
517
- #onPeerConnection = connection => {
518
- // Allow only a single connection
519
- if (this.conn && this.conn.open) {
520
- connection.on('open', () => {
521
- connection.send('Already connected to another client');
522
- setTimeout(() => {
523
- connection.close();
524
- }, 500);
525
- });
526
- return;
527
- }
528
-
529
- this.conn = connection;
530
- console.log('Connected to: ', this.conn.peer);
531
- this.#ready();
532
- };
533
-
534
- /**
535
- * Called when the peer connection is closed.
536
- *
537
- * @private
538
- * @example
539
- */
540
- onPeerClose = () => {
541
- this.conn = null;
542
- console.log('Connection destroyed');
543
- };
544
-
545
- static closeConnection = () => {
546
- this.conn = null;
547
- console.log('Connection destroyed');
548
- };
549
-
550
- /**
551
- * Called when the peer connection is disconnected.
552
- * Attempts to reconnect.
553
- *
554
- * @private
555
- * @example
556
- */
557
- #onPeerDisconnected = () => {
558
- console.log('Connection lost. Please reconnect');
559
-
560
- // Workaround for peer.reconnect deleting previous id
561
- this.peer.id = this.lastPeerId;
562
- // eslint-disable-next-line no-underscore-dangle
563
- this.peer._lastServerId = this.lastPeerId;
564
- this.peer.reconnect();
565
- };
566
-
567
- /**
568
- * Called when the peer connection encounters an error.
569
- *
570
- * @param error
571
- * @private
572
- * @example
573
- */
574
- #onPeerError = error => {
575
- // TODO: check if this function is needed or not
576
- console.error(error);
577
- };
578
-
579
- /**
580
- * Called when data is received from the peer connection.
581
- *
582
- * @param data
583
- * @private
584
- * @example
585
- */
586
- #onIncomingData = data => {
587
- // enforce object type
588
- if (
589
- !Object.prototype.hasOwnProperty.call(data, 'name') ||
590
- !Object.prototype.hasOwnProperty.call(data, 'payload')
591
- ) {
592
- console.error('Received malformed data: ', data);
593
- return;
594
- }
595
-
596
- switch (data.name) {
597
- case 'samplingRate':
598
- this.ac.setSamplingRates(data.payload);
599
- break;
600
- case 'sampleSize':
601
- this.ac.setSampleSize(data.payload);
602
- break;
603
- case 'deviceType':
604
- this.ac.setDeviceType(data.payload);
605
- break;
606
- case 'deviceName':
607
- this.ac.setDeviceName(data.payload);
608
- break;
609
- case 'flags':
610
- //this.ac.setDeviceName(data.payload);
611
- console.log('FLAGS');
612
- console.log(data.payload);
613
- this.ac.setFlags(data.payload);
614
- break;
615
- case 'deviceInfo':
616
- this.ac.setDeviceInfo(data.payload);
617
- console.log('Received device info from listener: ', data.payload);
618
- break;
619
- case UnsupportedDeviceError.name:
620
- case MissingSpeakerIdError.name:
621
- throw data.payload;
622
- break;
623
- default:
624
- break;
625
- }
626
- };
627
-
628
- /**
629
- * Called when the peer connection is #ready.
630
- *
631
- * @private
632
- * @example
633
- */
634
- #ready = () => {
635
- // Perform callback with data
636
- this.conn.on('data', this.#onIncomingData);
637
- this.conn.on('close', () => {
638
- console.log('Connection reset<br>Awaiting connection...');
639
- this.conn = null;
640
- });
641
- };
642
-
643
- /** .
644
- * .
645
- * .
646
- * Debug method for downloading the recorded audio
647
- *
648
- * @public
649
- * @example
650
- */
651
- downloadData = () => {
652
- this.ac.downloadData();
653
- };
654
-
655
- repeatCalibration = async (params, stream, CalibratorInstance) => {
656
- this.ac = CalibratorInstance;
657
- this.#removeUIElems();
658
- this.#showSpinner();
659
-
660
- console.log('This is a repeat');
661
- // wrap the calibration process in a promise so we can await it
662
- return new Promise(async (resolve, reject) => {
663
- const result = await this.ac.startCalibration(
664
- stream,
665
- params.gainValues,
666
- params.ICalib,
667
- params.knownIR,
668
- params.microphoneName,
669
- params.calibrateSoundCheck,
670
- params.isSmartPhone,
671
- params.calibrateSoundBurstDb,
672
- params.calibrateSoundBurstFilteredExtraDb,
673
- params.calibrateSoundBurstLevelReTBool,
674
- params.calibrateSoundBurstUses1000HzGainBool,
675
- params.calibrateSoundBurstRepeats,
676
- params.calibrateSoundBurstSec,
677
- params.calibrateSoundBurstsWarmup,
678
- params.calibrateSoundHz,
679
- params.calibrateSoundIRSec,
680
- params.calibrateSoundIIRSec,
681
- params.calibrateSoundIIRPhase,
682
- params.calibrateSound1000HzPreSec,
683
- params.calibrateSound1000HzSec,
684
- params.calibrateSound1000HzPostSec,
685
- params.calibrateSoundBackgroundSecs,
686
- params.calibrateSoundSmoothOctaves,
687
- params.calibrateSoundSmoothMinBandwidthHz,
688
- params.calibrateSoundPowerBinDesiredSec,
689
- params.calibrateSoundPowerDbSDToleratedDb,
690
- params.calibrateSoundTaperSec,
691
- params.micManufacturer,
692
- params.micSerialNumber,
693
- params.micModelNumber,
694
- params.micModelName,
695
- params.calibrateMicrophonesBool,
696
- params.authorEmails,
697
- params.webAudioDeviceNames,
698
- params.IDsToSaveInSoundProfileLibrary,
699
- params.restartButton,
700
- params.reminder,
701
- params.calibrateSoundLimit
702
- );
703
- this.#removeUIElems();
704
- resolve(result);
705
- });
706
- };
707
- }
708
-
709
- /*
710
- Referenced links:
711
- https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
712
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
713
- https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
714
- */
715
-
716
- export default Speaker;
1
+ import QRCode from 'qrcode';
2
+ import AudioPeer from './audioPeer';
3
+ import {sleep, formatLineBreak, createAndShowPopup} 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
+ this.isParticipant = params?.isParticipant ?? false;
43
+ this.isLoudspeakerCalibration = params?.isLoudspeakerCalibration ?? false;
44
+ this.buttonsContainer = params?.buttonsContainer ?? document.createElement('div');
45
+
46
+ /* Set up callbacks that handle any events related to our peer object. */
47
+ }
48
+
49
+ uri = '';
50
+ qrImage;
51
+ shortURL;
52
+
53
+ initPeer = async () => {
54
+ const id = await this.generateTimeBasedPeerID();
55
+ this.peer = new Peer(id, {
56
+ secure: true,
57
+ host: 'easyeyes-peer-server.herokuapp.com',
58
+ port: 443,
59
+ config: {
60
+ iceServers: [
61
+ {
62
+ urls: 'stun:stun.relay.metered.ca:80',
63
+ },
64
+ {
65
+ urls: 'turn:global.relay.metered.ca:80',
66
+ username: 'de884cfc34189cdf1a5dd616',
67
+ credential: 'IcOpouU9/TYBmpHU',
68
+ },
69
+ {
70
+ urls: 'turn:global.relay.metered.ca:80?transport=tcp',
71
+ username: 'de884cfc34189cdf1a5dd616',
72
+ credential: 'IcOpouU9/TYBmpHU',
73
+ },
74
+ {
75
+ urls: 'turn:global.relay.metered.ca:443',
76
+ username: 'de884cfc34189cdf1a5dd616',
77
+ credential: 'IcOpouU9/TYBmpHU',
78
+ },
79
+ {
80
+ urls: 'turns:global.relay.metered.ca:443?transport=tcp',
81
+ username: 'de884cfc34189cdf1a5dd616',
82
+ credential: 'IcOpouU9/TYBmpHU',
83
+ },
84
+ ],
85
+ },
86
+ });
87
+ this.peer.on('open', this.#onPeerOpen);
88
+ this.peer.on('connection', this.#onPeerConnection);
89
+ this.peer.on('close', this.onPeerClose);
90
+ this.peer.on('disconnected', this.#onPeerDisconnected);
91
+ this.peer.on('error', this.#onPeerError);
92
+ };
93
+ generateTimeBasedPeerID = async () => {
94
+ const now = new Date().getTime();
95
+ const randomBuffer = new Uint8Array(10);
96
+ crypto.getRandomValues(randomBuffer);
97
+ const randomPart = Array.from(randomBuffer)
98
+ .map(b => b.toString(36))
99
+ .join('');
100
+ const toHash = `${now}-${randomPart}`;
101
+ const encoder = new TextEncoder();
102
+ const data = encoder.encode(toHash);
103
+ const hash = await crypto.subtle.digest('SHA-256', data);
104
+ const hashArray = Array.from(new Uint8Array(hash)); // Convert buffer to byte array
105
+ const hashString = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
106
+ const shortHash = hashString.substring(0, 12); // Use more of the hash for a longer ID
107
+ // return shortHash; // Consider converting this to Base62
108
+ return this.encodeBase62(parseInt(shortHash, 16));
109
+ };
110
+
111
+ encodeBase62 = num => {
112
+ const base = 36;
113
+ const characters = '0123456789abcdefghijklmnopqrstuvwxyz';
114
+ let result = '';
115
+ while (num > 0) {
116
+ result = characters[num % base] + result;
117
+ num = Math.floor(num / base);
118
+ }
119
+ return result;
120
+ };
121
+
122
+ /**
123
+ * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.
124
+ *
125
+ * @param params - The parameters to be passed to the peer object.
126
+ * @param Calibrator - The class that defines the calibration process.
127
+ * @param CalibratorInstance
128
+ * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).
129
+ * @public
130
+ * @example
131
+ */
132
+ static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {
133
+ window.speaker = new Speaker(params, CalibratorInstance);
134
+ const {speaker} = window;
135
+ await speaker.initPeer();
136
+ // wrap the calibration process in a promise so we can await it
137
+ return new Promise((resolve, reject) => {
138
+ // when a call is received
139
+ speaker.peer.on('call', async call => {
140
+ // Answer the call (one way)
141
+
142
+ call.answer();
143
+ speaker.#removeUIElems();
144
+ speaker.#showSpinner();
145
+ speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
146
+ // when we start receiving audio
147
+ call.on('stream', async stream => {
148
+ window.localStream = stream;
149
+ window.localAudio.srcObject = stream;
150
+ window.localAudio.autoplay = false;
151
+
152
+ // if the sinkSamplingRate is not set sleep
153
+ while (!speaker.ac.sampleRatesSet()) {
154
+ console.log('SinkSamplingRate is undefined, sleeping');
155
+ await sleep(1);
156
+ }
157
+
158
+ if (params.displayUpdate) {
159
+ params.displayUpdate.style.display = '';
160
+ }
161
+
162
+ // resolve when we have a result
163
+ speaker.result = await speaker.ac.startCalibration(
164
+ stream,
165
+ params.gainValues,
166
+ params.ICalib,
167
+ params.knownIR,
168
+ params.microphoneName,
169
+ params.calibrateSoundCheck,
170
+ params.isSmartPhone,
171
+ params.calibrateSoundBurstDb,
172
+ params.calibrateSoundBurstFilteredExtraDb,
173
+ params.calibrateSoundBurstLevelReTBool,
174
+ params.calibrateSoundBurstUses1000HzGainBool,
175
+ params.calibrateSoundBurstRepeats,
176
+ params.calibrateSoundBurstSec,
177
+ params.calibrateSoundBurstsWarmup,
178
+ params.calibrateSoundHz,
179
+ params.calibrateSoundIRSec,
180
+ params.calibrateSoundIIRSec,
181
+ params.calibrateSoundIIRPhase,
182
+ params.calibrateSound1000HzPreSec,
183
+ params.calibrateSound1000HzSec,
184
+ params.calibrateSound1000HzPostSec,
185
+ params.calibrateSoundBackgroundSecs,
186
+ params.calibrateSoundSmoothOctaves,
187
+ params.calibrateSoundSmoothMinBandwidthHz,
188
+ params.calibrateSoundPowerBinDesiredSec,
189
+ params.calibrateSoundPowerDbSDToleratedDb,
190
+ params.calibrateSoundTaperSec,
191
+ params.micManufacturer,
192
+ params.micSerialNumber,
193
+ params.micModelNumber,
194
+ params.micModelName,
195
+ params.calibrateMicrophonesBool,
196
+ params.authorEmails,
197
+ params.webAudioDeviceNames,
198
+ params.IDsToSaveInSoundProfileLibrary,
199
+ params.restartButton,
200
+ params.reminder,
201
+ params.calibrateSoundLimit,
202
+ params.calibrateSoundBurstNormalizeBy1000HzGainBool,
203
+ params.calibrateSoundBurstScalarDB,
204
+ params.calibrateSound1000HzMaxSD_dB,
205
+ params._calibrateSoundBurstMaxSD_dB
206
+ );
207
+ speaker.#removeUIElems();
208
+ resolve(speaker.result);
209
+ });
210
+ // if we do not receive a result within the timeout, reject
211
+ setTimeout(() => {
212
+ reject(
213
+ new CalibrationTimedOutError(
214
+ `Calibration failed to produce a result after ${
215
+ timeOut / 1000
216
+ } seconds. Please try again.`
217
+ )
218
+ );
219
+ }, timeOut);
220
+ });
221
+ });
222
+ };
223
+
224
+ static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {
225
+ window.speaker = new Speaker(params, CalibratorInstance);
226
+ const {speaker} = window;
227
+ speaker.initPeer();
228
+ // wrap the calibration process in a promise so we can await it
229
+ return new Promise((resolve, reject) => {
230
+ // when a call is received
231
+ speaker.peer.on('call', async call => {
232
+ // Answer the call (one way)
233
+ call.answer();
234
+ speaker.#removeUIElems();
235
+ speaker.#showSpinner();
236
+ speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
237
+ // when we start receiving audio
238
+ call.on('stream', async stream => {
239
+ window.localStream = stream;
240
+ window.localAudio.srcObject = stream;
241
+ window.localAudio.autoplay = false;
242
+
243
+ // if the sinkSamplingRate is not set sleep
244
+ while (!speaker.ac.sampleRatesSet()) {
245
+ console.log('SinkSamplingRate is undefined, sleeping');
246
+ await sleep(1);
247
+ }
248
+ // resolve when we have a result
249
+ speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);
250
+ speaker.#removeUIElems();
251
+ resolve(speaker.result);
252
+ });
253
+ // if we do not receive a result within the timeout, reject
254
+ setTimeout(() => {
255
+ reject(
256
+ new CalibrationTimedOutError(
257
+ `Calibration failed to produce a result after ${
258
+ timeOut / 1000
259
+ } seconds. Please try again.`
260
+ )
261
+ );
262
+ }, timeOut);
263
+ });
264
+ });
265
+ };
266
+
267
+ /**
268
+ * Called after the peer conncection has been opened.
269
+ * Generates a QR code for the connection and displays it.
270
+ *
271
+ * @private
272
+ * @example
273
+ */
274
+
275
+ #showQRCode = async () => {
276
+ // Get query string, the URL parameters to specify a Listener
277
+ const queryStringParameters = {
278
+ speakerPeerId: this.peer.id,
279
+ sp: this.isSmartPhone,
280
+ hz: this.calibrateSoundHz,
281
+ bits: this.calibrateSoundSamplingDesiredBits,
282
+ lang: this.language,
283
+ };
284
+ const queryString = this.queryStringFromObject(queryStringParameters);
285
+ this.uri = this.siteUrl + queryString;
286
+ if (this.isSmartPhone) {
287
+ // if (true) { // test smartphone QR
288
+ // Display QR code for the participant to scan
289
+ const qrCanvas = document.createElement('canvas');
290
+ qrCanvas.setAttribute('id', 'qrCanvas');
291
+ QRCode.toCanvas(qrCanvas, this.uri, error => {
292
+ if (error) console.error(error);
293
+ });
294
+ const explanation = document.createElement('h2');
295
+ explanation.id = 'skipQRExplanation';
296
+ explanation.style = `
297
+ user-select: text;
298
+ margin-top: 9px;
299
+ font-size: 1.1rem;
300
+ `;
301
+ // Define the URL and options for the request
302
+ const url = 'https://api.short.io/links/public';
303
+ const options = {
304
+ method: 'POST',
305
+ headers: {
306
+ Accept: 'application/json',
307
+ 'Content-Type': 'application/json',
308
+ Authorization: 'pk_fysLKGj3legZz4XZ',
309
+ },
310
+ body: JSON.stringify({
311
+ domain: 'listeners.link', // Ensure this domain is valid for your account
312
+ originalURL: this.uri,
313
+ }),
314
+ };
315
+
316
+ // Make the request using fetch
317
+ await fetch(url, options)
318
+ .then(response => {
319
+ if (!response.ok) {
320
+ throw new Error(`HTTP error! Status: ${response.status}`);
321
+ }
322
+ return response.json(); // Parse the JSON response
323
+ })
324
+ .then(data => {
325
+ explanation.innerHTML = formatLineBreak(
326
+ phrases.RC_skipQR_ExplanationWithoutPreferNot[this.language]
327
+ .replace('xxx', `<b style="user-select: text">${data.shortURL}</b>`)
328
+ .replace('XXX', `<b style="user-select: text">${data.shortURL}</b>`),
329
+ phrases.RC_checkInternetConnection[this.language]
330
+ );
331
+ const checkConnection = document.createElement('a');
332
+ checkConnection.id = 'check-connection';
333
+ checkConnection.href = '#';
334
+ checkConnection.innerHTML = "check the phone's internet connection";
335
+ const lang = this.language;
336
+ checkConnection.addEventListener('click', function (event) {
337
+ console.log('clicked');
338
+ event.preventDefault(); // Prevent the default link action
339
+ createAndShowPopup(lang);
340
+ });
341
+ explanation.querySelector('a#check-connection').replaceWith(checkConnection);
342
+ })
343
+ .catch(error => {
344
+ console.error('Error:', error.message); // Handle errors
345
+ });
346
+
347
+ const qrImage = new Image(400, 400);
348
+ qrImage.setAttribute('id', 'compatibilityCheckQRImage');
349
+ qrImage.style.zIndex = Infinity;
350
+ qrImage.style.width = 400;
351
+ qrImage.style.height = 400;
352
+ qrImage.style.aspectRatio = 1;
353
+ qrImage.src = qrCanvas.toDataURL();
354
+ qrImage.style.maxHeight = '150px';
355
+ qrImage.style.maxWidth = '150px';
356
+
357
+ this.qrImage = qrImage;
358
+
359
+ const container = document.createElement('div');
360
+ container.style.display = 'flex';
361
+ container.style.justifyContent = 'space-between';
362
+ container.style.alignItems = 'top';
363
+ container.id = 'skipQRContainer';
364
+ container.appendChild(qrImage);
365
+ container.appendChild(explanation);
366
+ container.appendChild(this.buttonsContainer);
367
+ const qrContainer = document.createElement('div');
368
+ qrContainer.appendChild(container);
369
+
370
+ document.getElementById(this.targetElement).appendChild(qrContainer);
371
+ } else {
372
+ // show the link to the user
373
+ // If specified HTML Id is available, show QR code there
374
+ if (document.getElementById(this.targetElement)) {
375
+ // const linkTag = document.createElement('a');
376
+ // linkTag.setAttribute('href', uri);
377
+ // linkTag.innerHTML = 'Click here to start the calibration';
378
+ // linkTag.target = '_blank';
379
+ // document.getElementById(this.targetElement).appendChild(linkTag);
380
+ // document.getElementById(this.targetElement).appendChild(qrCanvas);
381
+
382
+ const proceedButton = document.createElement('button');
383
+ proceedButton.setAttribute('id', 'calibrationProceedButton');
384
+ proceedButton.setAttribute('class', 'btn btn-success');
385
+ proceedButton.innerHTML = phrases.T_proceed[this.language];
386
+ proceedButton.onclick = () => {
387
+ // open the link in a new tab
388
+ window.open(this.uri, '_blank');
389
+ // remove the button
390
+ document.getElementById('calibrationProceedButton').remove();
391
+ };
392
+ document.getElementById(this.targetElement).appendChild(proceedButton);
393
+ }
394
+ }
395
+ // or just print it to console
396
+ console.log('TEST: Peer reachable at: ', this.uri);
397
+ };
398
+
399
+ #showSpinner = () => {
400
+ const spinner = document.createElement('div');
401
+ spinner.className = 'spinner-border ml-auto';
402
+ spinner.role = 'status';
403
+ spinner.ariaHidden = 'true';
404
+ document.getElementById(this.targetElement).appendChild(spinner);
405
+
406
+ // clear instructionDisplay
407
+ const soundMessage = document.getElementById(this.soundMessageId);
408
+ soundMessage.innerHTML = '';
409
+ soundMessage.style.display = 'none';
410
+ const instructionDisplay = document.getElementById(this.instructionDisplayId);
411
+ const background = document.getElementById('background'); // todo: get background id from params
412
+ const subtitle = document.getElementById(this.soundSubtitleId);
413
+ if (subtitle) {
414
+ subtitle.innerHTML = '';
415
+ }
416
+ if (instructionDisplay) {
417
+ instructionDisplay.innerHTML = '';
418
+ instructionDisplay.style.whiteSpace = 'nowrap';
419
+ instructionDisplay.style.fontWeight = 'bold';
420
+ instructionDisplay.style.width = 'fit-content';
421
+ instructionDisplay.innerHTML = phrases.RC_soundRecording[this.language];
422
+ let fontSize = 100;
423
+ instructionDisplay.style.fontSize = fontSize + 'px';
424
+ while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
425
+ fontSize--;
426
+ instructionDisplay.style.fontSize = fontSize + 'px';
427
+ }
428
+ // const p = document.createElement('p');
429
+ // // font size
430
+ // p.style.fontSize = '1.1rem';
431
+ // p.style.fontWeight = 'normal';
432
+ // p.style.paddingTop = '20px';
433
+ // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
434
+ // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
435
+ // instructionDisplay.appendChild(p);
436
+ }
437
+
438
+ const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
439
+ if (timeToCalibrateDisplay) {
440
+ const timeToCalibrateText = phrases.RC_howLongToCalibrate[this.language];
441
+ timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
442
+ timeToCalibrateDisplay.style.fontWeight = 'normal';
443
+ timeToCalibrateDisplay.style.fontSize = '1rem';
444
+ // timeToCalibrateDisplay.style.paddingTop = '20px';
445
+ }
446
+
447
+ // Update title - titleDisplayId
448
+ const titleDisplay = document.getElementById(this.titleDisplayId);
449
+ if (titleDisplay) {
450
+ // if (this.isParticipant) {
451
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
452
+ // } else if (this.isSmartPhone) {
453
+ // if (this.isLoudspeakerCalibration) {
454
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
455
+ // } else {
456
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
457
+ // }
458
+ // } else {
459
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
460
+ // }
461
+ if (this.isLoudspeakerCalibration) {
462
+ if (this.isParticipant) {
463
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
464
+ } else if (this.isSmartPhone) {
465
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
466
+ } else {
467
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
468
+ }
469
+ } else {
470
+ if (this.isSmartPhone) {
471
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
472
+ } else {
473
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('4', '5');
474
+ }
475
+ }
476
+ }
477
+ };
478
+
479
+ #removeUIElems = () => {
480
+ const parent = document.getElementById(this.targetElement);
481
+ while (parent.firstChild) {
482
+ parent.firstChild.remove();
483
+ }
484
+ };
485
+
486
+ /**
487
+ * Called when the peer connection is opened.
488
+ * Saves the peer id and calls the QR code generator.
489
+ *
490
+ * @param peerId - The peer id of the peer connection.
491
+ * @param id
492
+ * @private
493
+ * @example
494
+ */
495
+ #onPeerOpen = id => {
496
+ // Workaround for peer.reconnect deleting previous id
497
+ if (id === null) {
498
+ console.error('Received null id from peer open');
499
+ this.peer.id = this.lastPeerId;
500
+ } else {
501
+ this.lastPeerId = this.peer.id;
502
+ }
503
+
504
+ if (id !== this.peer.id) {
505
+ console.warn('DEBUG Check you assumption that id === this.peer.id');
506
+ }
507
+
508
+ this.#showQRCode();
509
+ };
510
+
511
+ /**
512
+ * Called when the peer connection is established.
513
+ * Enforces a single connection.
514
+ *
515
+ * @param connection - The connection object.
516
+ * @private
517
+ * @example
518
+ */
519
+ #onPeerConnection = connection => {
520
+ // Allow only a single connection
521
+ if (this.conn && this.conn.open) {
522
+ connection.on('open', () => {
523
+ connection.send('Already connected to another client');
524
+ setTimeout(() => {
525
+ connection.close();
526
+ }, 500);
527
+ });
528
+ return;
529
+ }
530
+
531
+ this.conn = connection;
532
+ console.log('Connected to: ', this.conn.peer);
533
+ this.#ready();
534
+ };
535
+
536
+ /**
537
+ * Called when the peer connection is closed.
538
+ *
539
+ * @private
540
+ * @example
541
+ */
542
+ onPeerClose = () => {
543
+ this.conn = null;
544
+ console.log('Connection destroyed');
545
+ };
546
+
547
+ static closeConnection = () => {
548
+ this.conn = null;
549
+ console.log('Connection destroyed');
550
+ };
551
+
552
+ /**
553
+ * Called when the peer connection is disconnected.
554
+ * Attempts to reconnect.
555
+ *
556
+ * @private
557
+ * @example
558
+ */
559
+ #onPeerDisconnected = () => {
560
+ console.log('Connection lost. Please reconnect');
561
+
562
+ // Workaround for peer.reconnect deleting previous id
563
+ this.peer.id = this.lastPeerId;
564
+ // eslint-disable-next-line no-underscore-dangle
565
+ this.peer._lastServerId = this.lastPeerId;
566
+ this.peer.reconnect();
567
+ };
568
+
569
+ /**
570
+ * Called when the peer connection encounters an error.
571
+ *
572
+ * @param error
573
+ * @private
574
+ * @example
575
+ */
576
+ #onPeerError = error => {
577
+ // TODO: check if this function is needed or not
578
+ console.error(error);
579
+ };
580
+
581
+ /**
582
+ * Called when data is received from the peer connection.
583
+ *
584
+ * @param data
585
+ * @private
586
+ * @example
587
+ */
588
+ #onIncomingData = data => {
589
+ // enforce object type
590
+ if (
591
+ !Object.prototype.hasOwnProperty.call(data, 'name') ||
592
+ !Object.prototype.hasOwnProperty.call(data, 'payload')
593
+ ) {
594
+ console.error('Received malformed data: ', data);
595
+ return;
596
+ }
597
+
598
+ switch (data.name) {
599
+ case 'samplingRate':
600
+ this.ac.setSamplingRates(data.payload);
601
+ break;
602
+ case 'sampleSize':
603
+ this.ac.setSampleSize(data.payload);
604
+ break;
605
+ case 'deviceType':
606
+ this.ac.setDeviceType(data.payload);
607
+ break;
608
+ case 'deviceName':
609
+ this.ac.setDeviceName(data.payload);
610
+ break;
611
+ case 'flags':
612
+ //this.ac.setDeviceName(data.payload);
613
+ console.log('FLAGS');
614
+ console.log(data.payload);
615
+ this.ac.setFlags(data.payload);
616
+ break;
617
+ case 'deviceInfo':
618
+ this.ac.setDeviceInfo(data.payload);
619
+ console.log('Received device info from listener: ', data.payload);
620
+ break;
621
+ case UnsupportedDeviceError.name:
622
+ case MissingSpeakerIdError.name:
623
+ throw data.payload;
624
+ break;
625
+ default:
626
+ break;
627
+ }
628
+ };
629
+
630
+ /**
631
+ * Called when the peer connection is #ready.
632
+ *
633
+ * @private
634
+ * @example
635
+ */
636
+ #ready = () => {
637
+ // Perform callback with data
638
+ this.conn.on('data', this.#onIncomingData);
639
+ this.conn.on('close', () => {
640
+ console.log('Connection reset<br>Awaiting connection...');
641
+ this.conn = null;
642
+ });
643
+ };
644
+
645
+ /** .
646
+ * .
647
+ * .
648
+ * Debug method for downloading the recorded audio
649
+ *
650
+ * @public
651
+ * @example
652
+ */
653
+ downloadData = () => {
654
+ this.ac.downloadData();
655
+ };
656
+
657
+ repeatCalibration = async (params, stream, CalibratorInstance) => {
658
+ this.ac = CalibratorInstance;
659
+ this.#removeUIElems();
660
+ this.#showSpinner();
661
+
662
+ console.log('This is a repeat');
663
+ // wrap the calibration process in a promise so we can await it
664
+ return new Promise(async (resolve, reject) => {
665
+ const result = await this.ac.startCalibration(
666
+ stream,
667
+ params.gainValues,
668
+ params.ICalib,
669
+ params.knownIR,
670
+ params.microphoneName,
671
+ params.calibrateSoundCheck,
672
+ params.isSmartPhone,
673
+ params.calibrateSoundBurstDb,
674
+ params.calibrateSoundBurstFilteredExtraDb,
675
+ params.calibrateSoundBurstLevelReTBool,
676
+ params.calibrateSoundBurstUses1000HzGainBool,
677
+ params.calibrateSoundBurstRepeats,
678
+ params.calibrateSoundBurstSec,
679
+ params.calibrateSoundBurstsWarmup,
680
+ params.calibrateSoundHz,
681
+ params.calibrateSoundIRSec,
682
+ params.calibrateSoundIIRSec,
683
+ params.calibrateSoundIIRPhase,
684
+ params.calibrateSound1000HzPreSec,
685
+ params.calibrateSound1000HzSec,
686
+ params.calibrateSound1000HzPostSec,
687
+ params.calibrateSoundBackgroundSecs,
688
+ params.calibrateSoundSmoothOctaves,
689
+ params.calibrateSoundSmoothMinBandwidthHz,
690
+ params.calibrateSoundPowerBinDesiredSec,
691
+ params.calibrateSoundPowerDbSDToleratedDb,
692
+ params.calibrateSoundTaperSec,
693
+ params.micManufacturer,
694
+ params.micSerialNumber,
695
+ params.micModelNumber,
696
+ params.micModelName,
697
+ params.calibrateMicrophonesBool,
698
+ params.authorEmails,
699
+ params.webAudioDeviceNames,
700
+ params.IDsToSaveInSoundProfileLibrary,
701
+ params.restartButton,
702
+ params.reminder,
703
+ params.calibrateSoundLimit,
704
+ params.calibrateSoundBurstNormalizeBy1000HzGainBool,
705
+ params.calibrateSoundBurstScalarDB,
706
+ params.calibrateSound1000HzMaxSD_dB,
707
+ params._calibrateSoundBurstMaxSD_dB
708
+ );
709
+ this.#removeUIElems();
710
+ resolve(result);
711
+ });
712
+ };
713
+ }
714
+
715
+ /*
716
+ Referenced links:
717
+ https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
718
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
719
+ https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
720
+ */
721
+
722
+ export default Speaker;