speaker-calibration 2.2.198 → 2.2.199

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 (122) hide show
  1. package/.eslintignore +71 -71
  2. package/.eslintrc.json +40 -40
  3. package/.github/workflows/update-phrases.yml +37 -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 +27366 -27366
  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 +1234 -1234
  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/makefile +74 -0
  93. package/netlify.toml +26 -26
  94. package/package.json +73 -72
  95. package/src/config/firebase.js +26 -26
  96. package/src/index.html +21 -21
  97. package/src/main.js +23 -23
  98. package/src/myEventEmitter.js +83 -83
  99. package/src/peer-connection/audioPeer.js +178 -178
  100. package/src/peer-connection/listener.js +340 -340
  101. package/src/peer-connection/peerErrors.js +25 -25
  102. package/src/peer-connection/speaker.js +727 -724
  103. package/src/powerCheck.js +98 -98
  104. package/src/server/PythonServerAPI.js +869 -869
  105. package/src/tasks/audioCalibrator.js +335 -335
  106. package/src/tasks/audioRecorder.js +315 -315
  107. package/src/tasks/combination/combination.js +2963 -3033
  108. package/src/tasks/combination/mlsGen/mlsGen.cpp +98 -98
  109. package/src/tasks/combination/mlsGen/mlsGen.hpp +303 -303
  110. package/src/tasks/combination/mlsGen/mlsGenInterface.js +131 -131
  111. package/src/tasks/combination/mlsGen/mlsGenTest.cpp +180 -180
  112. package/src/tasks/impulse-response/impulseResponse.js +610 -610
  113. package/src/tasks/impulse-response/mlsGen/mlsGen.cpp +98 -98
  114. package/src/tasks/impulse-response/mlsGen/mlsGen.hpp +303 -303
  115. package/src/tasks/impulse-response/mlsGen/mlsGenInterface.js +131 -131
  116. package/src/tasks/impulse-response/mlsGen/mlsGenTest.cpp +180 -180
  117. package/src/tasks/volume/volume.cpp +2 -2
  118. package/src/tasks/volume/volume.hpp +22 -22
  119. package/src/tasks/volume/volume.js +279 -279
  120. package/src/utils.js +205 -205
  121. package/webpack.config.js +37 -37
  122. package/.gitignore +0 -81
@@ -1,724 +1,727 @@
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._calibrateSoundBurstPreSec,
178
- params._calibrateSoundBurstPostSec,
179
- params.calibrateSoundHz,
180
- params.calibrateSoundIRSec,
181
- params.calibrateSoundIIRSec,
182
- params.calibrateSoundIIRPhase,
183
- params.calibrateSound1000HzPreSec,
184
- params.calibrateSound1000HzSec,
185
- params.calibrateSound1000HzPostSec,
186
- params.calibrateSoundBackgroundSecs,
187
- params.calibrateSoundSmoothOctaves,
188
- params.calibrateSoundSmoothMinBandwidthHz,
189
- params.calibrateSoundPowerBinDesiredSec,
190
- params.calibrateSoundPowerDbSDToleratedDb,
191
- params.calibrateSoundTaperSec,
192
- params.micManufacturer,
193
- params.micSerialNumber,
194
- params.micModelNumber,
195
- params.micModelName,
196
- params.calibrateMicrophonesBool,
197
- params.authorEmails,
198
- params.webAudioDeviceNames,
199
- params.IDsToSaveInSoundProfileLibrary,
200
- params.restartButton,
201
- params.reminder,
202
- params.calibrateSoundLimit,
203
- params.calibrateSoundBurstNormalizeBy1000HzGainBool,
204
- params.calibrateSoundBurstScalarDB,
205
- params.calibrateSound1000HzMaxSD_dB,
206
- params._calibrateSoundBurstMaxSD_dB
207
- );
208
- speaker.#removeUIElems();
209
- resolve(speaker.result);
210
- });
211
- // if we do not receive a result within the timeout, reject
212
- setTimeout(() => {
213
- reject(
214
- new CalibrationTimedOutError(
215
- `Calibration failed to produce a result after ${
216
- timeOut / 1000
217
- } seconds. Please try again.`
218
- )
219
- );
220
- }, timeOut);
221
- });
222
- });
223
- };
224
-
225
- static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {
226
- window.speaker = new Speaker(params, CalibratorInstance);
227
- const {speaker} = window;
228
- speaker.initPeer();
229
- // wrap the calibration process in a promise so we can await it
230
- return new Promise((resolve, reject) => {
231
- // when a call is received
232
- speaker.peer.on('call', async call => {
233
- // Answer the call (one way)
234
- call.answer();
235
- speaker.#removeUIElems();
236
- speaker.#showSpinner();
237
- speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
238
- // when we start receiving audio
239
- call.on('stream', async stream => {
240
- window.localStream = stream;
241
- window.localAudio.srcObject = stream;
242
- window.localAudio.autoplay = false;
243
-
244
- // if the sinkSamplingRate is not set sleep
245
- while (!speaker.ac.sampleRatesSet()) {
246
- console.log('SinkSamplingRate is undefined, sleeping');
247
- await sleep(1);
248
- }
249
- // resolve when we have a result
250
- speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);
251
- speaker.#removeUIElems();
252
- resolve(speaker.result);
253
- });
254
- // if we do not receive a result within the timeout, reject
255
- setTimeout(() => {
256
- reject(
257
- new CalibrationTimedOutError(
258
- `Calibration failed to produce a result after ${
259
- timeOut / 1000
260
- } seconds. Please try again.`
261
- )
262
- );
263
- }, timeOut);
264
- });
265
- });
266
- };
267
-
268
- /**
269
- * Called after the peer conncection has been opened.
270
- * Generates a QR code for the connection and displays it.
271
- *
272
- * @private
273
- * @example
274
- */
275
-
276
- #showQRCode = async () => {
277
- // Get query string, the URL parameters to specify a Listener
278
- const queryStringParameters = {
279
- speakerPeerId: this.peer.id,
280
- sp: this.isSmartPhone,
281
- hz: this.calibrateSoundHz,
282
- bits: this.calibrateSoundSamplingDesiredBits,
283
- lang: this.language,
284
- };
285
- const queryString = this.queryStringFromObject(queryStringParameters);
286
- this.uri = this.siteUrl + queryString;
287
- if (this.isSmartPhone) {
288
- // if (true) { // test smartphone QR
289
- // Display QR code for the participant to scan
290
- const qrCanvas = document.createElement('canvas');
291
- qrCanvas.setAttribute('id', 'qrCanvas');
292
- QRCode.toCanvas(qrCanvas, this.uri, error => {
293
- if (error) console.error(error);
294
- });
295
- const explanation = document.createElement('h2');
296
- explanation.id = 'skipQRExplanation';
297
- explanation.style = `
298
- user-select: text;
299
- margin-top: 9px;
300
- font-size: 1.1rem;
301
- `;
302
- // Define the URL and options for the request
303
- const url = 'https://api.short.io/links/public';
304
- const options = {
305
- method: 'POST',
306
- headers: {
307
- Accept: 'application/json',
308
- 'Content-Type': 'application/json',
309
- Authorization: 'pk_fysLKGj3legZz4XZ',
310
- },
311
- body: JSON.stringify({
312
- domain: 'listeners.link', // Ensure this domain is valid for your account
313
- originalURL: this.uri,
314
- }),
315
- };
316
-
317
- // Make the request using fetch
318
- await fetch(url, options)
319
- .then(response => {
320
- if (!response.ok) {
321
- throw new Error(`HTTP error! Status: ${response.status}`);
322
- }
323
- return response.json(); // Parse the JSON response
324
- })
325
- .then(data => {
326
- explanation.innerHTML = formatLineBreak(
327
- phrases.RC_skipQR_ExplanationWithoutPreferNot[this.language]
328
- .replace('xxx', `<b style="user-select: text">${data.shortURL}</b>`)
329
- .replace('XXX', `<b style="user-select: text">${data.shortURL}</b>`),
330
- phrases.RC_checkInternetConnection[this.language]
331
- );
332
- const checkConnection = document.createElement('a');
333
- checkConnection.id = 'check-connection';
334
- checkConnection.href = '#';
335
- checkConnection.innerHTML = "check the phone's internet connection";
336
- const lang = this.language;
337
- checkConnection.addEventListener('click', function (event) {
338
- console.log('clicked');
339
- event.preventDefault(); // Prevent the default link action
340
- createAndShowPopup(lang);
341
- });
342
- explanation.querySelector('a#check-connection').replaceWith(checkConnection);
343
- })
344
- .catch(error => {
345
- console.error('Error:', error.message); // Handle errors
346
- });
347
-
348
- const qrImage = new Image(400, 400);
349
- qrImage.setAttribute('id', 'compatibilityCheckQRImage');
350
- qrImage.style.zIndex = Infinity;
351
- qrImage.style.width = 400;
352
- qrImage.style.height = 400;
353
- qrImage.style.aspectRatio = 1;
354
- qrImage.src = qrCanvas.toDataURL();
355
- qrImage.style.maxHeight = '150px';
356
- qrImage.style.maxWidth = '150px';
357
-
358
- this.qrImage = qrImage;
359
-
360
- const container = document.createElement('div');
361
- container.style.display = 'flex';
362
- container.style.justifyContent = 'space-between';
363
- container.style.alignItems = 'top';
364
- container.id = 'skipQRContainer';
365
- container.appendChild(qrImage);
366
- container.appendChild(explanation);
367
- container.appendChild(this.buttonsContainer);
368
- const qrContainer = document.createElement('div');
369
- qrContainer.appendChild(container);
370
-
371
- document.getElementById(this.targetElement).appendChild(qrContainer);
372
- } else {
373
- // show the link to the user
374
- // If specified HTML Id is available, show QR code there
375
- if (document.getElementById(this.targetElement)) {
376
- // const linkTag = document.createElement('a');
377
- // linkTag.setAttribute('href', uri);
378
- // linkTag.innerHTML = 'Click here to start the calibration';
379
- // linkTag.target = '_blank';
380
- // document.getElementById(this.targetElement).appendChild(linkTag);
381
- // document.getElementById(this.targetElement).appendChild(qrCanvas);
382
-
383
- const proceedButton = document.createElement('button');
384
- proceedButton.setAttribute('id', 'calibrationProceedButton');
385
- proceedButton.setAttribute('class', 'btn btn-success');
386
- proceedButton.innerHTML = phrases.T_proceed[this.language];
387
- proceedButton.onclick = () => {
388
- // open the link in a new tab
389
- window.open(this.uri, '_blank');
390
- // remove the button
391
- document.getElementById('calibrationProceedButton').remove();
392
- };
393
- document.getElementById(this.targetElement).appendChild(proceedButton);
394
- }
395
- }
396
- // or just print it to console
397
- console.log('TEST: Peer reachable at: ', this.uri);
398
- };
399
-
400
- #showSpinner = () => {
401
- const spinner = document.createElement('div');
402
- spinner.className = 'spinner-border ml-auto';
403
- spinner.role = 'status';
404
- spinner.ariaHidden = 'true';
405
- document.getElementById(this.targetElement).appendChild(spinner);
406
-
407
- // clear instructionDisplay
408
- const soundMessage = document.getElementById(this.soundMessageId);
409
- soundMessage.innerHTML = '';
410
- soundMessage.style.display = 'none';
411
- const instructionDisplay = document.getElementById(this.instructionDisplayId);
412
- const background = document.getElementById('background'); // todo: get background id from params
413
- const subtitle = document.getElementById(this.soundSubtitleId);
414
- if (subtitle) {
415
- subtitle.innerHTML = '';
416
- }
417
- if (instructionDisplay) {
418
- instructionDisplay.innerHTML = '';
419
- instructionDisplay.style.whiteSpace = 'nowrap';
420
- instructionDisplay.style.fontWeight = 'bold';
421
- instructionDisplay.style.width = 'fit-content';
422
- instructionDisplay.innerHTML = phrases.RC_soundRecording[this.language];
423
- let fontSize = 100;
424
- instructionDisplay.style.fontSize = fontSize + 'px';
425
- while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
426
- fontSize--;
427
- instructionDisplay.style.fontSize = fontSize + 'px';
428
- }
429
- // const p = document.createElement('p');
430
- // // font size
431
- // p.style.fontSize = '1.1rem';
432
- // p.style.fontWeight = 'normal';
433
- // p.style.paddingTop = '20px';
434
- // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
435
- // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
436
- // instructionDisplay.appendChild(p);
437
- }
438
-
439
- const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
440
- if (timeToCalibrateDisplay) {
441
- const timeToCalibrateText = phrases.RC_howLongToCalibrate[this.language];
442
- timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
443
- timeToCalibrateDisplay.style.fontWeight = 'normal';
444
- timeToCalibrateDisplay.style.fontSize = '1rem';
445
- // timeToCalibrateDisplay.style.paddingTop = '20px';
446
- }
447
-
448
- // Update title - titleDisplayId
449
- const titleDisplay = document.getElementById(this.titleDisplayId);
450
- if (titleDisplay) {
451
- // if (this.isParticipant) {
452
- // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
453
- // } else if (this.isSmartPhone) {
454
- // if (this.isLoudspeakerCalibration) {
455
- // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
456
- // } else {
457
- // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
458
- // }
459
- // } else {
460
- // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
461
- // }
462
- if (this.isLoudspeakerCalibration) {
463
- if (this.isParticipant) {
464
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
465
- } else if (this.isSmartPhone) {
466
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
467
- } else {
468
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
469
- }
470
- } else {
471
- if (this.isSmartPhone) {
472
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
473
- } else {
474
- titleDisplay.innerHTML = titleDisplay.innerHTML.replace('4', '5');
475
- }
476
- }
477
- }
478
- };
479
-
480
- #removeUIElems = () => {
481
- const parent = document.getElementById(this.targetElement);
482
- while (parent.firstChild) {
483
- parent.firstChild.remove();
484
- }
485
- };
486
-
487
- /**
488
- * Called when the peer connection is opened.
489
- * Saves the peer id and calls the QR code generator.
490
- *
491
- * @param peerId - The peer id of the peer connection.
492
- * @param id
493
- * @private
494
- * @example
495
- */
496
- #onPeerOpen = id => {
497
- // Workaround for peer.reconnect deleting previous id
498
- if (id === null) {
499
- console.error('Received null id from peer open');
500
- this.peer.id = this.lastPeerId;
501
- } else {
502
- this.lastPeerId = this.peer.id;
503
- }
504
-
505
- if (id !== this.peer.id) {
506
- console.warn('DEBUG Check you assumption that id === this.peer.id');
507
- }
508
-
509
- this.#showQRCode();
510
- };
511
-
512
- /**
513
- * Called when the peer connection is established.
514
- * Enforces a single connection.
515
- *
516
- * @param connection - The connection object.
517
- * @private
518
- * @example
519
- */
520
- #onPeerConnection = connection => {
521
- // Allow only a single connection
522
- if (this.conn && this.conn.open) {
523
- connection.on('open', () => {
524
- connection.send('Already connected to another client');
525
- setTimeout(() => {
526
- connection.close();
527
- }, 500);
528
- });
529
- return;
530
- }
531
-
532
- this.conn = connection;
533
- console.log('Connected to: ', this.conn.peer);
534
- this.#ready();
535
- };
536
-
537
- /**
538
- * Called when the peer connection is closed.
539
- *
540
- * @private
541
- * @example
542
- */
543
- onPeerClose = () => {
544
- this.conn = null;
545
- console.log('Connection destroyed');
546
- };
547
-
548
- static closeConnection = () => {
549
- this.conn = null;
550
- console.log('Connection destroyed');
551
- };
552
-
553
- /**
554
- * Called when the peer connection is disconnected.
555
- * Attempts to reconnect.
556
- *
557
- * @private
558
- * @example
559
- */
560
- #onPeerDisconnected = () => {
561
- console.log('Connection lost. Please reconnect');
562
-
563
- // Workaround for peer.reconnect deleting previous id
564
- this.peer.id = this.lastPeerId;
565
- // eslint-disable-next-line no-underscore-dangle
566
- this.peer._lastServerId = this.lastPeerId;
567
- this.peer.reconnect();
568
- };
569
-
570
- /**
571
- * Called when the peer connection encounters an error.
572
- *
573
- * @param error
574
- * @private
575
- * @example
576
- */
577
- #onPeerError = error => {
578
- // TODO: check if this function is needed or not
579
- console.error(error);
580
- };
581
-
582
- /**
583
- * Called when data is received from the peer connection.
584
- *
585
- * @param data
586
- * @private
587
- * @example
588
- */
589
- #onIncomingData = data => {
590
- // enforce object type
591
- if (
592
- !Object.prototype.hasOwnProperty.call(data, 'name') ||
593
- !Object.prototype.hasOwnProperty.call(data, 'payload')
594
- ) {
595
- console.error('Received malformed data: ', data);
596
- return;
597
- }
598
-
599
- switch (data.name) {
600
- case 'samplingRate':
601
- this.ac.setSamplingRates(data.payload);
602
- break;
603
- case 'sampleSize':
604
- this.ac.setSampleSize(data.payload);
605
- break;
606
- case 'deviceType':
607
- this.ac.setDeviceType(data.payload);
608
- break;
609
- case 'deviceName':
610
- this.ac.setDeviceName(data.payload);
611
- break;
612
- case 'flags':
613
- //this.ac.setDeviceName(data.payload);
614
- console.log('FLAGS');
615
- console.log(data.payload);
616
- this.ac.setFlags(data.payload);
617
- break;
618
- case 'deviceInfo':
619
- this.ac.setDeviceInfo(data.payload);
620
- console.log('Received device info from listener: ', data.payload);
621
- break;
622
- case UnsupportedDeviceError.name:
623
- case MissingSpeakerIdError.name:
624
- throw data.payload;
625
- break;
626
- default:
627
- break;
628
- }
629
- };
630
-
631
- /**
632
- * Called when the peer connection is #ready.
633
- *
634
- * @private
635
- * @example
636
- */
637
- #ready = () => {
638
- // Perform callback with data
639
- this.conn.on('data', this.#onIncomingData);
640
- this.conn.on('close', () => {
641
- console.log('Connection reset<br>Awaiting connection...');
642
- this.conn = null;
643
- });
644
- };
645
-
646
- /** .
647
- * .
648
- * .
649
- * Debug method for downloading the recorded audio
650
- *
651
- * @public
652
- * @example
653
- */
654
- downloadData = () => {
655
- this.ac.downloadData();
656
- };
657
-
658
- repeatCalibration = async (params, stream, CalibratorInstance) => {
659
- this.ac = CalibratorInstance;
660
- this.#removeUIElems();
661
- this.#showSpinner();
662
-
663
- console.log('This is a repeat');
664
- // wrap the calibration process in a promise so we can await it
665
- return new Promise(async (resolve, reject) => {
666
- const result = await this.ac.startCalibration(
667
- stream,
668
- params.gainValues,
669
- params.ICalib,
670
- params.knownIR,
671
- params.microphoneName,
672
- params.calibrateSoundCheck,
673
- params.isSmartPhone,
674
- params.calibrateSoundBurstDb,
675
- params.calibrateSoundBurstFilteredExtraDb,
676
- params.calibrateSoundBurstLevelReTBool,
677
- params.calibrateSoundBurstUses1000HzGainBool,
678
- params.calibrateSoundBurstRepeats,
679
- params.calibrateSoundBurstSec,
680
- params._calibrateSoundBurstPreSec,
681
- params._calibrateSoundBurstPostSec,
682
- params.calibrateSoundHz,
683
- params.calibrateSoundIRSec,
684
- params.calibrateSoundIIRSec,
685
- params.calibrateSoundIIRPhase,
686
- params.calibrateSound1000HzPreSec,
687
- params.calibrateSound1000HzSec,
688
- params.calibrateSound1000HzPostSec,
689
- params.calibrateSoundBackgroundSecs,
690
- params.calibrateSoundSmoothOctaves,
691
- params.calibrateSoundSmoothMinBandwidthHz,
692
- params.calibrateSoundPowerBinDesiredSec,
693
- params.calibrateSoundPowerDbSDToleratedDb,
694
- params.calibrateSoundTaperSec,
695
- params.micManufacturer,
696
- params.micSerialNumber,
697
- params.micModelNumber,
698
- params.micModelName,
699
- params.calibrateMicrophonesBool,
700
- params.authorEmails,
701
- params.webAudioDeviceNames,
702
- params.IDsToSaveInSoundProfileLibrary,
703
- params.restartButton,
704
- params.reminder,
705
- params.calibrateSoundLimit,
706
- params.calibrateSoundBurstNormalizeBy1000HzGainBool,
707
- params.calibrateSoundBurstScalarDB,
708
- params.calibrateSound1000HzMaxSD_dB,
709
- params._calibrateSoundBurstMaxSD_dB
710
- );
711
- this.#removeUIElems();
712
- resolve(result);
713
- });
714
- };
715
- }
716
-
717
- /*
718
- Referenced links:
719
- https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
720
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
721
- https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
722
- */
723
-
724
- 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._calibrateSoundBurstPreSec,
178
+ params._calibrateSoundBurstPostSec,
179
+ params.calibrateSoundHz,
180
+ params.calibrateSoundIRSec,
181
+ params.calibrateSoundIIRSec,
182
+ params.calibrateSoundIIRPhase,
183
+ params.calibrateSound1000HzPreSec,
184
+ params.calibrateSound1000HzSec,
185
+ params.calibrateSound1000HzPostSec,
186
+ params.calibrateSoundBackgroundSecs,
187
+ params.calibrateSoundSmoothOctaves,
188
+ params.calibrateSoundSmoothMinBandwidthHz,
189
+ params.calibrateSoundPowerBinDesiredSec,
190
+ params.calibrateSoundPowerDbSDToleratedDb,
191
+ params.calibrateSoundTaperSec,
192
+ params.micManufacturer,
193
+ params.micSerialNumber,
194
+ params.micModelNumber,
195
+ params.micModelName,
196
+ params.calibrateMicrophonesBool,
197
+ params.authorEmails,
198
+ params.webAudioDeviceNames,
199
+ params.IDsToSaveInSoundProfileLibrary,
200
+ params.restartButton,
201
+ params.reminder,
202
+ params.calibrateSoundLimit,
203
+ params.calibrateSoundBurstNormalizeBy1000HzGainBool,
204
+ params.calibrateSoundBurstScalarDB,
205
+ params.calibrateSound1000HzMaxSD_dB,
206
+ params._calibrateSoundBurstMaxSD_dB,
207
+ params.calibrateSoundSamplingDesiredBits,
208
+ params.language
209
+ );
210
+ speaker.#removeUIElems();
211
+ resolve(speaker.result);
212
+ });
213
+ // if we do not receive a result within the timeout, reject
214
+ setTimeout(() => {
215
+ reject(
216
+ new CalibrationTimedOutError(
217
+ `Calibration failed to produce a result after ${
218
+ timeOut / 1000
219
+ } seconds. Please try again.`
220
+ )
221
+ );
222
+ }, timeOut);
223
+ });
224
+ });
225
+ };
226
+
227
+ static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {
228
+ window.speaker = new Speaker(params, CalibratorInstance);
229
+ const {speaker} = window;
230
+ speaker.initPeer();
231
+ // wrap the calibration process in a promise so we can await it
232
+ return new Promise((resolve, reject) => {
233
+ // when a call is received
234
+ speaker.peer.on('call', async call => {
235
+ // Answer the call (one way)
236
+ call.answer();
237
+ speaker.#removeUIElems();
238
+ speaker.#showSpinner();
239
+ speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
240
+ // when we start receiving audio
241
+ call.on('stream', async stream => {
242
+ window.localStream = stream;
243
+ window.localAudio.srcObject = stream;
244
+ window.localAudio.autoplay = false;
245
+
246
+ // if the sinkSamplingRate is not set sleep
247
+ while (!speaker.ac.sampleRatesSet()) {
248
+ console.log('SinkSamplingRate is undefined, sleeping');
249
+ await sleep(1);
250
+ }
251
+ // resolve when we have a result
252
+ speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);
253
+ speaker.#removeUIElems();
254
+ resolve(speaker.result);
255
+ });
256
+ // if we do not receive a result within the timeout, reject
257
+ setTimeout(() => {
258
+ reject(
259
+ new CalibrationTimedOutError(
260
+ `Calibration failed to produce a result after ${
261
+ timeOut / 1000
262
+ } seconds. Please try again.`
263
+ )
264
+ );
265
+ }, timeOut);
266
+ });
267
+ });
268
+ };
269
+
270
+ /**
271
+ * Called after the peer conncection has been opened.
272
+ * Generates a QR code for the connection and displays it.
273
+ *
274
+ * @private
275
+ * @example
276
+ */
277
+
278
+ #showQRCode = async () => {
279
+ // Get query string, the URL parameters to specify a Listener
280
+ const queryStringParameters = {
281
+ speakerPeerId: this.peer.id,
282
+ sp: this.isSmartPhone,
283
+ hz: this.calibrateSoundHz,
284
+ bits: this.calibrateSoundSamplingDesiredBits,
285
+ lang: this.language,
286
+ };
287
+ const queryString = this.queryStringFromObject(queryStringParameters);
288
+ this.uri = this.siteUrl + queryString;
289
+ if (this.isSmartPhone) {
290
+ // if (true) { // test smartphone QR
291
+ // Display QR code for the participant to scan
292
+ const qrCanvas = document.createElement('canvas');
293
+ qrCanvas.setAttribute('id', 'qrCanvas');
294
+ QRCode.toCanvas(qrCanvas, this.uri, error => {
295
+ if (error) console.error(error);
296
+ });
297
+ const explanation = document.createElement('h2');
298
+ explanation.id = 'skipQRExplanation';
299
+ explanation.style = `
300
+ user-select: text;
301
+ margin-top: 9px;
302
+ font-size: 1.1rem;
303
+ `;
304
+ // Define the URL and options for the request
305
+ const url = 'https://api.short.io/links/public';
306
+ const options = {
307
+ method: 'POST',
308
+ headers: {
309
+ Accept: 'application/json',
310
+ 'Content-Type': 'application/json',
311
+ Authorization: 'pk_fysLKGj3legZz4XZ',
312
+ },
313
+ body: JSON.stringify({
314
+ domain: 'listeners.link', // Ensure this domain is valid for your account
315
+ originalURL: this.uri,
316
+ }),
317
+ };
318
+
319
+ // Make the request using fetch
320
+ await fetch(url, options)
321
+ .then(response => {
322
+ if (!response.ok) {
323
+ throw new Error(`HTTP error! Status: ${response.status}`);
324
+ }
325
+ return response.json(); // Parse the JSON response
326
+ })
327
+ .then(data => {
328
+ explanation.innerHTML = formatLineBreak(
329
+ phrases.RC_skipQR_ExplanationWithoutPreferNot[this.language]
330
+ .replace('xxx', `<b style="user-select: text">${data.shortURL}</b>`)
331
+ .replace('XXX', `<b style="user-select: text">${data.shortURL}</b>`),
332
+ phrases.RC_checkInternetConnection[this.language]
333
+ );
334
+ const checkConnection = document.createElement('a');
335
+ checkConnection.id = 'check-connection';
336
+ checkConnection.href = '#';
337
+ checkConnection.innerHTML = "check the phone's internet connection";
338
+ const lang = this.language;
339
+ checkConnection.addEventListener('click', function (event) {
340
+ console.log('clicked');
341
+ event.preventDefault(); // Prevent the default link action
342
+ createAndShowPopup(lang);
343
+ });
344
+ explanation.querySelector('a#check-connection').replaceWith(checkConnection);
345
+ })
346
+ .catch(error => {
347
+ console.error('Error:', error.message); // Handle errors
348
+ });
349
+
350
+ const qrImage = new Image(400, 400);
351
+ qrImage.setAttribute('id', 'compatibilityCheckQRImage');
352
+ qrImage.style.zIndex = Infinity;
353
+ qrImage.style.width = 400;
354
+ qrImage.style.height = 400;
355
+ qrImage.style.aspectRatio = 1;
356
+ qrImage.src = qrCanvas.toDataURL();
357
+ qrImage.style.maxHeight = '150px';
358
+ qrImage.style.maxWidth = '150px';
359
+
360
+ this.qrImage = qrImage;
361
+
362
+ const container = document.createElement('div');
363
+ container.style.display = 'flex';
364
+ container.style.justifyContent = 'space-between';
365
+ container.style.alignItems = 'top';
366
+ container.id = 'skipQRContainer';
367
+ container.appendChild(qrImage);
368
+ container.appendChild(explanation);
369
+ container.appendChild(this.buttonsContainer);
370
+ const qrContainer = document.createElement('div');
371
+ qrContainer.appendChild(container);
372
+
373
+ document.getElementById(this.targetElement).appendChild(qrContainer);
374
+ } else {
375
+ // show the link to the user
376
+ // If specified HTML Id is available, show QR code there
377
+ if (document.getElementById(this.targetElement)) {
378
+ // const linkTag = document.createElement('a');
379
+ // linkTag.setAttribute('href', uri);
380
+ // linkTag.innerHTML = 'Click here to start the calibration';
381
+ // linkTag.target = '_blank';
382
+ // document.getElementById(this.targetElement).appendChild(linkTag);
383
+ // document.getElementById(this.targetElement).appendChild(qrCanvas);
384
+
385
+ const proceedButton = document.createElement('button');
386
+ proceedButton.setAttribute('id', 'calibrationProceedButton');
387
+ proceedButton.setAttribute('class', 'btn btn-success');
388
+ proceedButton.innerHTML = phrases.T_proceed[this.language];
389
+ proceedButton.onclick = () => {
390
+ // open the link in a new tab
391
+ window.open(this.uri, '_blank');
392
+ // remove the button
393
+ document.getElementById('calibrationProceedButton').remove();
394
+ };
395
+ document.getElementById(this.targetElement).appendChild(proceedButton);
396
+ }
397
+ }
398
+ // or just print it to console
399
+ console.log('TEST: Peer reachable at: ', this.uri);
400
+ };
401
+
402
+ #showSpinner = () => {
403
+ const spinner = document.createElement('div');
404
+ spinner.className = 'spinner-border ml-auto';
405
+ spinner.role = 'status';
406
+ spinner.ariaHidden = 'true';
407
+ spinner.style.marginTop = '0.8rem';
408
+ document.getElementById(this.targetElement).appendChild(spinner);
409
+
410
+ // clear instructionDisplay
411
+ const soundMessage = document.getElementById(this.soundMessageId);
412
+ soundMessage.innerHTML = '';
413
+ soundMessage.style.display = 'none';
414
+ const instructionDisplay = document.getElementById(this.instructionDisplayId);
415
+ const background = document.getElementById('background'); // todo: get background id from params
416
+ const subtitle = document.getElementById(this.soundSubtitleId);
417
+ if (subtitle) {
418
+ subtitle.innerHTML = '';
419
+ }
420
+ if (instructionDisplay) {
421
+ instructionDisplay.innerHTML = '';
422
+ instructionDisplay.style.whiteSpace = 'nowrap';
423
+ instructionDisplay.style.fontWeight = 'bold';
424
+ instructionDisplay.style.width = 'fit-content';
425
+ instructionDisplay.innerHTML = phrases.RC_soundRecording[this.language];
426
+ let fontSize = 100;
427
+ instructionDisplay.style.fontSize = fontSize + 'px';
428
+ while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
429
+ fontSize--;
430
+ instructionDisplay.style.fontSize = fontSize + 'px';
431
+ }
432
+ // const p = document.createElement('p');
433
+ // // font size
434
+ // p.style.fontSize = '1.1rem';
435
+ // p.style.fontWeight = 'normal';
436
+ // p.style.paddingTop = '20px';
437
+ // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
438
+ // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
439
+ // instructionDisplay.appendChild(p);
440
+ }
441
+
442
+ const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
443
+ if (timeToCalibrateDisplay) {
444
+ const timeToCalibrateText = phrases.RC_howLongToCalibrate[this.language];
445
+ timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
446
+ timeToCalibrateDisplay.style.fontWeight = 'normal';
447
+ timeToCalibrateDisplay.style.fontSize = '1rem';
448
+ // timeToCalibrateDisplay.style.paddingTop = '20px';
449
+ }
450
+
451
+ // Update title - titleDisplayId
452
+ const titleDisplay = document.getElementById(this.titleDisplayId);
453
+ if (titleDisplay) {
454
+ // if (this.isParticipant) {
455
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
456
+ // } else if (this.isSmartPhone) {
457
+ // if (this.isLoudspeakerCalibration) {
458
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
459
+ // } else {
460
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
461
+ // }
462
+ // } else {
463
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
464
+ // }
465
+ if (this.isLoudspeakerCalibration) {
466
+ if (this.isParticipant) {
467
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
468
+ } else if (this.isSmartPhone) {
469
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
470
+ } else {
471
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
472
+ }
473
+ } else {
474
+ if (this.isSmartPhone) {
475
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
476
+ } else {
477
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('4', '5');
478
+ }
479
+ }
480
+ }
481
+ };
482
+
483
+ #removeUIElems = () => {
484
+ const parent = document.getElementById(this.targetElement);
485
+ while (parent.firstChild) {
486
+ parent.firstChild.remove();
487
+ }
488
+ };
489
+
490
+ /**
491
+ * Called when the peer connection is opened.
492
+ * Saves the peer id and calls the QR code generator.
493
+ *
494
+ * @param peerId - The peer id of the peer connection.
495
+ * @param id
496
+ * @private
497
+ * @example
498
+ */
499
+ #onPeerOpen = id => {
500
+ // Workaround for peer.reconnect deleting previous id
501
+ if (id === null) {
502
+ console.error('Received null id from peer open');
503
+ this.peer.id = this.lastPeerId;
504
+ } else {
505
+ this.lastPeerId = this.peer.id;
506
+ }
507
+
508
+ if (id !== this.peer.id) {
509
+ console.warn('DEBUG Check you assumption that id === this.peer.id');
510
+ }
511
+
512
+ this.#showQRCode();
513
+ };
514
+
515
+ /**
516
+ * Called when the peer connection is established.
517
+ * Enforces a single connection.
518
+ *
519
+ * @param connection - The connection object.
520
+ * @private
521
+ * @example
522
+ */
523
+ #onPeerConnection = connection => {
524
+ // Allow only a single connection
525
+ if (this.conn && this.conn.open) {
526
+ connection.on('open', () => {
527
+ connection.send('Already connected to another client');
528
+ setTimeout(() => {
529
+ connection.close();
530
+ }, 500);
531
+ });
532
+ return;
533
+ }
534
+
535
+ this.conn = connection;
536
+ console.log('Connected to: ', this.conn.peer);
537
+ this.#ready();
538
+ };
539
+
540
+ /**
541
+ * Called when the peer connection is closed.
542
+ *
543
+ * @private
544
+ * @example
545
+ */
546
+ onPeerClose = () => {
547
+ this.conn = null;
548
+ console.log('Connection destroyed');
549
+ };
550
+
551
+ static closeConnection = () => {
552
+ this.conn = null;
553
+ console.log('Connection destroyed');
554
+ };
555
+
556
+ /**
557
+ * Called when the peer connection is disconnected.
558
+ * Attempts to reconnect.
559
+ *
560
+ * @private
561
+ * @example
562
+ */
563
+ #onPeerDisconnected = () => {
564
+ console.log('Connection lost. Please reconnect');
565
+
566
+ // Workaround for peer.reconnect deleting previous id
567
+ this.peer.id = this.lastPeerId;
568
+ // eslint-disable-next-line no-underscore-dangle
569
+ this.peer._lastServerId = this.lastPeerId;
570
+ this.peer.reconnect();
571
+ };
572
+
573
+ /**
574
+ * Called when the peer connection encounters an error.
575
+ *
576
+ * @param error
577
+ * @private
578
+ * @example
579
+ */
580
+ #onPeerError = error => {
581
+ // TODO: check if this function is needed or not
582
+ console.error(error);
583
+ };
584
+
585
+ /**
586
+ * Called when data is received from the peer connection.
587
+ *
588
+ * @param data
589
+ * @private
590
+ * @example
591
+ */
592
+ #onIncomingData = data => {
593
+ // enforce object type
594
+ if (
595
+ !Object.prototype.hasOwnProperty.call(data, 'name') ||
596
+ !Object.prototype.hasOwnProperty.call(data, 'payload')
597
+ ) {
598
+ console.error('Received malformed data: ', data);
599
+ return;
600
+ }
601
+
602
+ switch (data.name) {
603
+ case 'samplingRate':
604
+ this.ac.setSamplingRates(data.payload);
605
+ break;
606
+ case 'sampleSize':
607
+ this.ac.setSampleSize(data.payload);
608
+ break;
609
+ case 'deviceType':
610
+ this.ac.setDeviceType(data.payload);
611
+ break;
612
+ case 'deviceName':
613
+ this.ac.setDeviceName(data.payload);
614
+ break;
615
+ case 'flags':
616
+ //this.ac.setDeviceName(data.payload);
617
+ console.log('FLAGS');
618
+ console.log(data.payload);
619
+ this.ac.setFlags(data.payload);
620
+ break;
621
+ case 'deviceInfo':
622
+ this.ac.setDeviceInfo(data.payload);
623
+ console.log('Received device info from listener: ', data.payload);
624
+ break;
625
+ case UnsupportedDeviceError.name:
626
+ case MissingSpeakerIdError.name:
627
+ throw data.payload;
628
+ break;
629
+ default:
630
+ break;
631
+ }
632
+ };
633
+
634
+ /**
635
+ * Called when the peer connection is #ready.
636
+ *
637
+ * @private
638
+ * @example
639
+ */
640
+ #ready = () => {
641
+ // Perform callback with data
642
+ this.conn.on('data', this.#onIncomingData);
643
+ this.conn.on('close', () => {
644
+ console.log('Connection reset<br>Awaiting connection...');
645
+ this.conn = null;
646
+ });
647
+ };
648
+
649
+ /** .
650
+ * .
651
+ * .
652
+ * Debug method for downloading the recorded audio
653
+ *
654
+ * @public
655
+ * @example
656
+ */
657
+ downloadData = () => {
658
+ this.ac.downloadData();
659
+ };
660
+
661
+ repeatCalibration = async (params, stream, CalibratorInstance) => {
662
+ this.ac = CalibratorInstance;
663
+ this.#removeUIElems();
664
+ this.#showSpinner();
665
+
666
+ console.log('This is a repeat');
667
+ // wrap the calibration process in a promise so we can await it
668
+ return new Promise(async (resolve, reject) => {
669
+ const result = await this.ac.startCalibration(
670
+ stream,
671
+ params.gainValues,
672
+ params.ICalib,
673
+ params.knownIR,
674
+ params.microphoneName,
675
+ params.calibrateSoundCheck,
676
+ params.isSmartPhone,
677
+ params.calibrateSoundBurstDb,
678
+ params.calibrateSoundBurstFilteredExtraDb,
679
+ params.calibrateSoundBurstLevelReTBool,
680
+ params.calibrateSoundBurstUses1000HzGainBool,
681
+ params.calibrateSoundBurstRepeats,
682
+ params.calibrateSoundBurstSec,
683
+ params._calibrateSoundBurstPreSec,
684
+ params._calibrateSoundBurstPostSec,
685
+ params.calibrateSoundHz,
686
+ params.calibrateSoundIRSec,
687
+ params.calibrateSoundIIRSec,
688
+ params.calibrateSoundIIRPhase,
689
+ params.calibrateSound1000HzPreSec,
690
+ params.calibrateSound1000HzSec,
691
+ params.calibrateSound1000HzPostSec,
692
+ params.calibrateSoundBackgroundSecs,
693
+ params.calibrateSoundSmoothOctaves,
694
+ params.calibrateSoundSmoothMinBandwidthHz,
695
+ params.calibrateSoundPowerBinDesiredSec,
696
+ params.calibrateSoundPowerDbSDToleratedDb,
697
+ params.calibrateSoundTaperSec,
698
+ params.micManufacturer,
699
+ params.micSerialNumber,
700
+ params.micModelNumber,
701
+ params.micModelName,
702
+ params.calibrateMicrophonesBool,
703
+ params.authorEmails,
704
+ params.webAudioDeviceNames,
705
+ params.IDsToSaveInSoundProfileLibrary,
706
+ params.restartButton,
707
+ params.reminder,
708
+ params.calibrateSoundLimit,
709
+ params.calibrateSoundBurstNormalizeBy1000HzGainBool,
710
+ params.calibrateSoundBurstScalarDB,
711
+ params.calibrateSound1000HzMaxSD_dB,
712
+ params._calibrateSoundBurstMaxSD_dB
713
+ );
714
+ this.#removeUIElems();
715
+ resolve(result);
716
+ });
717
+ };
718
+ }
719
+
720
+ /*
721
+ Referenced links:
722
+ https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
723
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
724
+ https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
725
+ */
726
+
727
+ export default Speaker;