speaker-calibration 2.2.210 → 2.2.211

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