speaker-calibration 2.2.198 → 2.2.200

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