speaker-calibration 2.2.212 → 2.2.214

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/.github/workflows/update-phrases.yml +37 -0
  4. package/.prettierignore +69 -69
  5. package/.prettierrc +14 -14
  6. package/LICENSE +20 -20
  7. package/README.md +133 -133
  8. package/__mocks__/fileMock.js +1 -1
  9. package/__mocks__/styleMock.js +1 -1
  10. package/babel.config.js +3 -3
  11. package/coverage/clover.xml +71 -71
  12. package/coverage/coverage-final.json +224 -224
  13. package/coverage/lcov-report/PythonServerInterface.js.html +265 -265
  14. package/coverage/lcov-report/base.css +354 -354
  15. package/coverage/lcov-report/block-navigation.js +82 -82
  16. package/coverage/lcov-report/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/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 +3459 -0
  44. package/dist/main.js +2420 -207
  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/makefile +74 -0
  112. package/netlify.toml +26 -26
  113. package/package.json +78 -73
  114. package/src/config/firebase.js +26 -26
  115. package/src/index.html +21 -21
  116. package/{dist/example → src/listener-app}/listener.js +153 -152
  117. package/src/main.js +23 -23
  118. package/src/myEventEmitter.js +83 -83
  119. package/src/peer-connection/audioPeer.js +183 -183
  120. package/src/peer-connection/listener.js +366 -367
  121. package/src/peer-connection/peerErrors.js +25 -25
  122. package/src/peer-connection/speaker.js +743 -738
  123. package/src/powerCheck.js +98 -98
  124. package/src/server/PythonServerAPI.js +869 -869
  125. package/src/tasks/audioCalibrator.js +351 -351
  126. package/src/tasks/audioRecorder.js +315 -315
  127. package/src/tasks/combination/combination.js +3160 -3031
  128. package/src/tasks/combination/mlsGen/mlsGen.cpp +98 -98
  129. package/src/tasks/combination/mlsGen/mlsGen.hpp +303 -303
  130. package/src/tasks/combination/mlsGen/mlsGenInterface.js +131 -131
  131. package/src/tasks/combination/mlsGen/mlsGenTest.cpp +180 -180
  132. package/src/tasks/impulse-response/impulseResponse.js +610 -610
  133. package/src/tasks/impulse-response/mlsGen/mlsGen.cpp +98 -98
  134. package/src/tasks/impulse-response/mlsGen/mlsGen.hpp +303 -303
  135. package/src/tasks/impulse-response/mlsGen/mlsGenInterface.js +131 -131
  136. package/src/tasks/impulse-response/mlsGen/mlsGenTest.cpp +180 -180
  137. package/src/tasks/volume/volume.cpp +2 -2
  138. package/src/tasks/volume/volume.hpp +22 -22
  139. package/src/tasks/volume/volume.js +279 -279
  140. package/src/utils.js +205 -205
  141. package/webpack.config.js +64 -37
  142. package/.gitignore +0 -81
@@ -1,738 +1,743 @@
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
+ 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
+ checkConnection.addEventListener('click', function (event) {
351
+ console.log('clicked');
352
+ event.preventDefault(); // Prevent the default link action
353
+ createAndShowPopup(lang, this.phrases);
354
+ });
355
+ explanation.querySelector('a#check-connection').replaceWith(checkConnection);
356
+ })
357
+ .catch(error => {
358
+ console.error('Error:', error.message); // Handle errors
359
+ });
360
+
361
+ const qrImage = new Image(400, 400);
362
+ qrImage.setAttribute('id', 'compatibilityCheckQRImage');
363
+ qrImage.style.zIndex = Infinity;
364
+ qrImage.style.width = 400;
365
+ qrImage.style.height = 400;
366
+ qrImage.style.aspectRatio = 1;
367
+ qrImage.src = qrCanvas.toDataURL();
368
+ qrImage.style.maxHeight = '150px';
369
+ qrImage.style.maxWidth = '150px';
370
+
371
+ this.qrImage = qrImage;
372
+
373
+ const container = document.createElement('div');
374
+ container.style.display = 'flex';
375
+ container.style.justifyContent = 'space-between';
376
+ container.style.alignItems = 'top';
377
+ container.id = 'skipQRContainer';
378
+ container.appendChild(qrImage);
379
+ container.appendChild(explanation);
380
+ container.appendChild(this.buttonsContainer);
381
+ const qrContainer = document.createElement('div');
382
+ qrContainer.appendChild(container);
383
+
384
+ document.getElementById(this.targetElement).appendChild(qrContainer);
385
+ } else {
386
+ // show the link to the user
387
+ // If specified HTML Id is available, show QR code there
388
+ if (document.getElementById(this.targetElement)) {
389
+ // const linkTag = document.createElement('a');
390
+ // linkTag.setAttribute('href', uri);
391
+ // linkTag.innerHTML = 'Click here to start the calibration';
392
+ // linkTag.target = '_blank';
393
+ // document.getElementById(this.targetElement).appendChild(linkTag);
394
+ // document.getElementById(this.targetElement).appendChild(qrCanvas);
395
+
396
+ const proceedButton = document.createElement('button');
397
+ proceedButton.setAttribute('id', 'calibrationProceedButton');
398
+ proceedButton.setAttribute('class', 'btn btn-success');
399
+ proceedButton.innerHTML = this.phrases.T_proceed[this.language];
400
+ proceedButton.onclick = () => {
401
+ // open the link in a new tab
402
+ window.open(this.uri, '_blank');
403
+ // remove the button
404
+ document.getElementById('calibrationProceedButton').remove();
405
+ };
406
+ document.getElementById(this.targetElement).appendChild(proceedButton);
407
+ }
408
+ }
409
+ // or just print it to console
410
+ console.log('TEST: Peer reachable at: ', this.uri);
411
+ };
412
+
413
+ #showSpinner = () => {
414
+ const spinner = document.createElement('div');
415
+ spinner.className = 'spinner-border ml-auto';
416
+ spinner.role = 'status';
417
+ spinner.ariaHidden = 'true';
418
+ spinner.style.marginTop = '0.8rem';
419
+ document.getElementById(this.targetElement).appendChild(spinner);
420
+
421
+ // clear instructionDisplay
422
+ const soundMessage = document.getElementById(this.soundMessageId);
423
+ soundMessage.innerHTML = '';
424
+ soundMessage.style.display = 'none';
425
+ const instructionDisplay = document.getElementById(this.instructionDisplayId);
426
+ const background = document.getElementById('background'); // todo: get background id from params
427
+ const subtitle = document.getElementById(this.soundSubtitleId);
428
+ if (subtitle) {
429
+ subtitle.innerHTML = '';
430
+ }
431
+ if (instructionDisplay) {
432
+ instructionDisplay.innerHTML = '';
433
+ instructionDisplay.style.whiteSpace = 'nowrap';
434
+ instructionDisplay.style.fontWeight = 'bold';
435
+ instructionDisplay.style.width = 'fit-content';
436
+ instructionDisplay.innerHTML = this.phrases.RC_soundRecording[this.language];
437
+ let fontSize = 100;
438
+ instructionDisplay.style.fontSize = fontSize + 'px';
439
+ while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
440
+ fontSize--;
441
+ instructionDisplay.style.fontSize = fontSize + 'px';
442
+ }
443
+ // const p = document.createElement('p');
444
+ // // font size
445
+ // p.style.fontSize = '1.1rem';
446
+ // p.style.fontWeight = 'normal';
447
+ // p.style.paddingTop = '20px';
448
+ // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
449
+ // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
450
+ // instructionDisplay.appendChild(p);
451
+ }
452
+
453
+ const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
454
+ if (timeToCalibrateDisplay) {
455
+ const timeToCalibrateText = this.phrases.RC_howLongToCalibrate[this.language];
456
+ timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
457
+ timeToCalibrateDisplay.style.fontWeight = 'normal';
458
+ timeToCalibrateDisplay.style.fontSize = '1rem';
459
+ // timeToCalibrateDisplay.style.paddingTop = '20px';
460
+ }
461
+
462
+ // Update title - titleDisplayId
463
+ const titleDisplay = document.getElementById(this.titleDisplayId);
464
+ if (titleDisplay) {
465
+ // if (this.isParticipant) {
466
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
467
+ // } else if (this.isSmartPhone) {
468
+ // if (this.isLoudspeakerCalibration) {
469
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
470
+ // } else {
471
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
472
+ // }
473
+ // } else {
474
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
475
+ // }
476
+ if (this.isLoudspeakerCalibration) {
477
+ if (this.isParticipant) {
478
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
479
+ } else if (this.isSmartPhone) {
480
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
481
+ } else {
482
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('4', '5');
483
+ }
484
+ } else {
485
+ if (this.isSmartPhone) {
486
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
487
+ } else {
488
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
489
+ }
490
+ }
491
+ }
492
+ };
493
+
494
+ #removeUIElems = () => {
495
+ const parent = document.getElementById(this.targetElement);
496
+ while (parent.firstChild) {
497
+ parent.firstChild.remove();
498
+ }
499
+ };
500
+
501
+ /**
502
+ * Called when the peer connection is opened.
503
+ * Saves the peer id and calls the QR code generator.
504
+ *
505
+ * @param peerId - The peer id of the peer connection.
506
+ * @param id
507
+ * @private
508
+ * @example
509
+ */
510
+ #onPeerOpen = id => {
511
+ // Workaround for peer.reconnect deleting previous id
512
+ if (id === null) {
513
+ console.error('Received null id from peer open');
514
+ this.peer.id = this.lastPeerId;
515
+ } else {
516
+ this.lastPeerId = this.peer.id;
517
+ }
518
+
519
+ if (id !== this.peer.id) {
520
+ console.warn('DEBUG Check you assumption that id === this.peer.id');
521
+ }
522
+
523
+ this.#showQRCode();
524
+ };
525
+
526
+ /**
527
+ * Called when the peer connection is established.
528
+ * Enforces a single connection.
529
+ *
530
+ * @param connection - The connection object.
531
+ * @private
532
+ * @example
533
+ */
534
+ #onPeerConnection = connection => {
535
+ // Allow only a single connection
536
+ if (this.conn && this.conn.open) {
537
+ connection.on('open', () => {
538
+ connection.send('Already connected to another client');
539
+ setTimeout(() => {
540
+ connection.close();
541
+ }, 500);
542
+ });
543
+ return;
544
+ }
545
+
546
+ this.conn = connection;
547
+ console.log('Connected to: ', this.conn.peer);
548
+ this.#ready();
549
+ };
550
+
551
+ /**
552
+ * Called when the peer connection is closed.
553
+ *
554
+ * @private
555
+ * @example
556
+ */
557
+ onPeerClose = () => {
558
+ this.conn = null;
559
+ console.log('Connection destroyed');
560
+ };
561
+
562
+ static closeConnection = () => {
563
+ this.conn = null;
564
+ console.log('Connection destroyed');
565
+ };
566
+
567
+ /**
568
+ * Called when the peer connection is disconnected.
569
+ * Attempts to reconnect.
570
+ *
571
+ * @private
572
+ * @example
573
+ */
574
+ #onPeerDisconnected = () => {
575
+ console.log('Connection lost. Please reconnect');
576
+
577
+ // Workaround for peer.reconnect deleting previous id
578
+ this.peer.id = this.lastPeerId;
579
+ // eslint-disable-next-line no-underscore-dangle
580
+ this.peer._lastServerId = this.lastPeerId;
581
+ this.peer.reconnect();
582
+ };
583
+
584
+ /**
585
+ * Called when the peer connection encounters an error.
586
+ *
587
+ * @param error
588
+ * @private
589
+ * @example
590
+ */
591
+ #onPeerError = error => {
592
+ // TODO: check if this function is needed or not
593
+ console.error(error);
594
+ };
595
+
596
+ /**
597
+ * Called when data is received from the peer connection.
598
+ *
599
+ * @param data
600
+ * @private
601
+ * @example
602
+ */
603
+ #onIncomingData = data => {
604
+ // enforce object type
605
+ if (
606
+ !Object.prototype.hasOwnProperty.call(data, 'name') ||
607
+ !Object.prototype.hasOwnProperty.call(data, 'payload')
608
+ ) {
609
+ console.error('Received malformed data: ', data);
610
+ return;
611
+ }
612
+
613
+ switch (data.name) {
614
+ case 'samplingRate':
615
+ this.ac.setSamplingRates(data.payload);
616
+ break;
617
+ case 'sampleSize':
618
+ this.ac.setSampleSize(data.payload);
619
+ break;
620
+ case 'deviceType':
621
+ this.ac.setDeviceType(data.payload);
622
+ break;
623
+ case 'deviceName':
624
+ this.ac.setDeviceName(data.payload);
625
+ break;
626
+ case 'flags':
627
+ //this.ac.setDeviceName(data.payload);
628
+ console.log('FLAGS');
629
+ console.log(data.payload);
630
+ this.ac.setFlags(data.payload);
631
+ break;
632
+ case 'deviceInfo':
633
+ this.ac.setDeviceInfo(data.payload);
634
+ console.log('Received device info from listener: ', data.payload);
635
+ break;
636
+ case UnsupportedDeviceError.name:
637
+ case MissingSpeakerIdError.name:
638
+ throw data.payload;
639
+ break;
640
+ default:
641
+ break;
642
+ }
643
+ };
644
+
645
+ /**
646
+ * Called when the peer connection is #ready.
647
+ *
648
+ * @private
649
+ * @example
650
+ */
651
+ #ready = () => {
652
+ // Perform callback with data
653
+ this.conn.on('data', this.#onIncomingData);
654
+ this.conn.on('close', () => {
655
+ console.log('Connection reset<br>Awaiting connection...');
656
+ this.conn = null;
657
+ });
658
+ };
659
+
660
+ /** .
661
+ * .
662
+ * .
663
+ * Debug method for downloading the recorded audio
664
+ *
665
+ * @public
666
+ * @example
667
+ */
668
+ downloadData = () => {
669
+ this.ac.downloadData();
670
+ };
671
+
672
+ repeatCalibration = async (params, stream, CalibratorInstance) => {
673
+ this.ac = CalibratorInstance;
674
+ this.#removeUIElems();
675
+ this.#showSpinner();
676
+
677
+ console.log('This is a repeat');
678
+ // wrap the calibration process in a promise so we can await it
679
+ return new Promise(async (resolve, reject) => {
680
+ const result = await this.ac.startCalibration(
681
+ stream,
682
+ params.gainValues,
683
+ params.ICalib,
684
+ params.knownIR,
685
+ params.microphoneName,
686
+ params.calibrateSoundCheck,
687
+ params.isSmartPhone,
688
+ params.calibrateSoundBurstDb,
689
+ params.calibrateSoundBurstFilteredExtraDb,
690
+ params.calibrateSoundBurstLevelReTBool,
691
+ params.calibrateSoundBurstUses1000HzGainBool,
692
+ params.calibrateSoundBurstRepeats,
693
+ params.calibrateSoundBurstSec,
694
+ params._calibrateSoundBurstPreSec,
695
+ params._calibrateSoundBurstPostSec,
696
+ params.calibrateSoundHz,
697
+ params.calibrateSoundIRSec,
698
+ params.calibrateSoundIIRSec,
699
+ params.calibrateSoundIIRPhase,
700
+ params.calibrateSound1000HzPreSec,
701
+ params.calibrateSound1000HzSec,
702
+ params.calibrateSound1000HzPostSec,
703
+ params.calibrateSoundBackgroundSecs,
704
+ params.calibrateSoundSmoothOctaves,
705
+ params.calibrateSoundSmoothMinBandwidthHz,
706
+ params.calibrateSoundPowerBinDesiredSec,
707
+ params.calibrateSoundPowerDbSDToleratedDb,
708
+ params.calibrateSoundTaperSec,
709
+ params.micManufacturer,
710
+ params.micSerialNumber,
711
+ params.micModelNumber,
712
+ params.micModelName,
713
+ params.calibrateMicrophonesBool,
714
+ params.authorEmails,
715
+ params.webAudioDeviceNames,
716
+ params.IDsToSaveInSoundProfileLibrary,
717
+ params.restartButton,
718
+ params.reminder,
719
+ params.calibrateSoundLimit,
720
+ params.calibrateSoundBurstNormalizeBy1000HzGainBool,
721
+ params.calibrateSoundBurstScalarDB,
722
+ params.calibrateSound1000HzMaxSD_dB,
723
+ params._calibrateSoundBurstMaxSD_dB,
724
+ params.calibrateSoundSamplingDesiredBits,
725
+ params.language,
726
+ params.loudspeakerModelName,
727
+ params.phrases,
728
+ params.soundSubtitleId
729
+ );
730
+ this.#removeUIElems();
731
+ resolve(result);
732
+ });
733
+ };
734
+ }
735
+
736
+ /*
737
+ Referenced links:
738
+ https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
739
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
740
+ https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
741
+ */
742
+
743
+ export default Speaker;