speaker-calibration 2.2.217 → 2.2.219

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