speaker-calibration 2.2.220 → 2.2.221

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