speaker-calibration 2.2.200 → 2.2.202

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 (141) 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/favicon.png +0 -0
  17. package/coverage/lcov-report/index.html +123 -123
  18. package/coverage/lcov-report/prettify.css +101 -101
  19. package/coverage/lcov-report/prettify.js +937 -937
  20. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  21. package/coverage/lcov-report/sorter.js +189 -189
  22. package/coverage/lcov-report/src/index.html +121 -121
  23. package/coverage/lcov-report/src/server/PythonServerInterface.js.html +268 -268
  24. package/coverage/lcov-report/src/server/index.html +123 -123
  25. package/coverage/lcov-report/src/tasks/audioCalibrator.js.html +499 -499
  26. package/coverage/lcov-report/src/tasks/audioRecorder.js.html +412 -412
  27. package/coverage/lcov-report/src/tasks/index.html +143 -143
  28. package/coverage/lcov-report/src/tasks/volume/index.html +123 -123
  29. package/coverage/lcov-report/src/tasks/volume/volume.js.html +409 -409
  30. package/coverage/lcov-report/src/utils.js.html +172 -172
  31. package/coverage/lcov.info +91 -91
  32. package/dist/Procfile +0 -0
  33. package/dist/example/NoSleep.min.js +1 -1
  34. package/dist/example/credentials.json.gpg +0 -0
  35. package/dist/example/fetch-languages-sheets.js +77 -77
  36. package/dist/example/i18n.js +27366 -27366
  37. package/dist/example/index.html +47 -47
  38. package/dist/example/listener.html +79 -79
  39. package/dist/example/listener.js +149 -149
  40. package/dist/example/server.js +51 -51
  41. package/dist/example/speaker.html +145 -145
  42. package/dist/example/speakerUI.js +273 -273
  43. package/dist/example/styles.css +99 -99
  44. package/dist/main.js +1234 -1234
  45. package/dist/main.js.LICENSE.txt +0 -0
  46. package/dist/mlsGen.js +6814 -6814
  47. package/dist/mlsGen.wasm +0 -0
  48. package/dist/package-lock.json +1018 -1018
  49. package/dist/package.json +18 -18
  50. package/doc/AudioCalibrator.html +417 -417
  51. package/doc/AudioPeer.html +251 -251
  52. package/doc/AudioRecorder.html +195 -195
  53. package/doc/ImpulseResponse.html +215 -215
  54. package/doc/Listener.html +308 -308
  55. package/doc/MlsGenInterface.html +226 -226
  56. package/doc/MyEventEmitter.html +274 -274
  57. package/doc/PythonServerAPI.html +109 -109
  58. package/doc/Speaker-Calibration-UML-Diagram.png +0 -0
  59. package/doc/Speaker.html +276 -276
  60. package/doc/Takes%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +128 -128
  61. package/doc/Takes%20the%20url%20of%20the%20current%20site%0Aand%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +138 -138
  62. package/doc/Takes%20the%20url%20of%20the%20current%20site%20and%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +137 -137
  63. package/doc/Volume.html +88 -88
  64. package/doc/audioCalibrator.js.html +179 -179
  65. package/doc/audioPeer.js.html +175 -175
  66. package/doc/audioRecorder.js.html +163 -163
  67. package/doc/creates%20a%20new%20AudioRecorder%20instance.%20%0ASets%20up%20the%20audio%20context%20and%20file%20reader..html +114 -114
  68. package/doc/fonts/OpenSans-Bold-webfont.eot +0 -0
  69. package/doc/fonts/OpenSans-Bold-webfont.svg +1829 -1829
  70. package/doc/fonts/OpenSans-Bold-webfont.woff +0 -0
  71. package/doc/fonts/OpenSans-BoldItalic-webfont.eot +0 -0
  72. package/doc/fonts/OpenSans-BoldItalic-webfont.svg +1829 -1829
  73. package/doc/fonts/OpenSans-BoldItalic-webfont.woff +0 -0
  74. package/doc/fonts/OpenSans-Italic-webfont.eot +0 -0
  75. package/doc/fonts/OpenSans-Italic-webfont.svg +1829 -1829
  76. package/doc/fonts/OpenSans-Italic-webfont.woff +0 -0
  77. package/doc/fonts/OpenSans-Light-webfont.eot +0 -0
  78. package/doc/fonts/OpenSans-Light-webfont.svg +1830 -1830
  79. package/doc/fonts/OpenSans-Light-webfont.woff +0 -0
  80. package/doc/fonts/OpenSans-LightItalic-webfont.eot +0 -0
  81. package/doc/fonts/OpenSans-LightItalic-webfont.svg +1834 -1834
  82. package/doc/fonts/OpenSans-LightItalic-webfont.woff +0 -0
  83. package/doc/fonts/OpenSans-Regular-webfont.eot +0 -0
  84. package/doc/fonts/OpenSans-Regular-webfont.svg +1830 -1830
  85. package/doc/fonts/OpenSans-Regular-webfont.woff +0 -0
  86. package/doc/global.html +308 -308
  87. package/doc/index.html +58 -58
  88. package/doc/listener.js.html +170 -170
  89. package/doc/mlsGen_mlsGenInterface.js.html +117 -117
  90. package/doc/myEventEmitter.js.html +124 -124
  91. package/doc/peer-connection_audioPeer.js.html +188 -188
  92. package/doc/peer-connection_listener.js.html +311 -311
  93. package/doc/peer-connection_speaker.js.html +381 -381
  94. package/doc/sc-activity-diagram.png +0 -0
  95. package/doc/scripts/linenumber.js +25 -25
  96. package/doc/scripts/prettify/Apache-License-2.0.txt +202 -202
  97. package/doc/scripts/prettify/lang-css.js +24 -24
  98. package/doc/scripts/prettify/prettify.js +640 -640
  99. package/doc/server_PythonServerAPI.js.html +160 -160
  100. package/doc/speaker.js.html +248 -248
  101. package/doc/styles/jsdoc-default.css +371 -371
  102. package/doc/styles/prettify-jsdoc.css +111 -111
  103. package/doc/styles/prettify-tomorrow.css +163 -163
  104. package/doc/tasks_audioCalibrator.js.html +207 -207
  105. package/doc/tasks_audioRecorder.js.html +190 -190
  106. package/doc/tasks_impulse-response_impulseResponse.js.html +442 -442
  107. package/doc/tasks_impulse-response_mlsGen_mlsGenInterface.js.html +175 -175
  108. package/doc/tasks_volume_volume.js.html +185 -185
  109. package/doc/utils.js.html +105 -105
  110. package/jest.config.js +173 -173
  111. package/netlify.toml +26 -26
  112. package/package.json +73 -73
  113. package/src/config/firebase.js +26 -26
  114. package/src/index.html +21 -21
  115. package/src/main.js +23 -23
  116. package/src/myEventEmitter.js +83 -83
  117. package/src/peer-connection/audioPeer.js +178 -178
  118. package/src/peer-connection/listener.js +340 -340
  119. package/src/peer-connection/peerErrors.js +25 -25
  120. package/src/peer-connection/speaker.js +731 -731
  121. package/src/powerCheck.js +98 -98
  122. package/src/server/PythonServerAPI.js +869 -869
  123. package/src/tasks/audioCalibrator.js +336 -335
  124. package/src/tasks/audioRecorder.js +315 -315
  125. package/src/tasks/combination/combination.js +2996 -2968
  126. package/src/tasks/combination/mlsGen/mlsGen.cpp +98 -98
  127. package/src/tasks/combination/mlsGen/mlsGen.hpp +303 -303
  128. package/src/tasks/combination/mlsGen/mlsGenInterface.js +131 -131
  129. package/src/tasks/combination/mlsGen/mlsGenTest.cpp +180 -180
  130. package/src/tasks/impulse-response/impulseResponse.js +610 -610
  131. package/src/tasks/impulse-response/mlsGen/mlsGen.cpp +98 -98
  132. package/src/tasks/impulse-response/mlsGen/mlsGen.hpp +303 -303
  133. package/src/tasks/impulse-response/mlsGen/mlsGenInterface.js +131 -131
  134. package/src/tasks/impulse-response/mlsGen/mlsGenTest.cpp +180 -180
  135. package/src/tasks/volume/volume.cpp +2 -2
  136. package/src/tasks/volume/volume.hpp +22 -22
  137. package/src/tasks/volume/volume.js +279 -279
  138. package/src/utils.js +205 -205
  139. package/webpack.config.js +37 -37
  140. package/.github/workflows/update-phrases.yml +0 -37
  141. package/makefile +0 -74
@@ -1,731 +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
- 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;
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;