speaker-calibration 2.2.215 → 2.2.217

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