speaker-calibration 2.2.188 → 2.2.190

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 +26990 -26859
  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 +724 -718
  102. package/src/server/PythonServerAPI.js +835 -830
  103. package/src/tasks/audioCalibrator.js +332 -323
  104. package/src/tasks/audioRecorder.js +315 -315
  105. package/src/tasks/combination/combination.js +2999 -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,718 +1,724 @@
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
- params.calibrateSoundBurstNormalizeBy1000HzGainBool,
703
- params.calibrateSoundBurstScalarDB
704
- );
705
- this.#removeUIElems();
706
- resolve(result);
707
- });
708
- };
709
- }
710
-
711
- /*
712
- Referenced links:
713
- https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
714
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
715
- https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
716
- */
717
-
718
- 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
+ );
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;