speaker-calibration 2.2.217 → 2.2.218

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 +28705 -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 +99 -99
  43. package/dist/listener.js +13 -13
  44. package/dist/main.js +12 -12
  45. package/dist/main.js.LICENSE.txt +0 -0
  46. package/dist/mlsGen.js +6814 -6814
  47. package/dist/mlsGen.wasm +0 -0
  48. package/dist/package-lock.json +1018 -1018
  49. package/dist/package.json +18 -18
  50. package/doc/AudioCalibrator.html +417 -417
  51. package/doc/AudioPeer.html +251 -251
  52. package/doc/AudioRecorder.html +195 -195
  53. package/doc/ImpulseResponse.html +215 -215
  54. package/doc/Listener.html +308 -308
  55. package/doc/MlsGenInterface.html +226 -226
  56. package/doc/MyEventEmitter.html +274 -274
  57. package/doc/PythonServerAPI.html +109 -109
  58. package/doc/Speaker-Calibration-UML-Diagram.png +0 -0
  59. package/doc/Speaker.html +276 -276
  60. package/doc/Takes%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +128 -128
  61. package/doc/Takes%20the%20url%20of%20the%20current%20site%0Aand%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +138 -138
  62. package/doc/Takes%20the%20url%20of%20the%20current%20site%20and%20a%20target%20element%20where%20html%20elements%20will%20be%20appended..html +137 -137
  63. package/doc/Volume.html +88 -88
  64. package/doc/audioCalibrator.js.html +179 -179
  65. package/doc/audioPeer.js.html +175 -175
  66. package/doc/audioRecorder.js.html +163 -163
  67. package/doc/creates%20a%20new%20AudioRecorder%20instance.%20%0ASets%20up%20the%20audio%20context%20and%20file%20reader..html +114 -114
  68. package/doc/fonts/OpenSans-Bold-webfont.eot +0 -0
  69. package/doc/fonts/OpenSans-Bold-webfont.svg +1829 -1829
  70. package/doc/fonts/OpenSans-Bold-webfont.woff +0 -0
  71. package/doc/fonts/OpenSans-BoldItalic-webfont.eot +0 -0
  72. package/doc/fonts/OpenSans-BoldItalic-webfont.svg +1829 -1829
  73. package/doc/fonts/OpenSans-BoldItalic-webfont.woff +0 -0
  74. package/doc/fonts/OpenSans-Italic-webfont.eot +0 -0
  75. package/doc/fonts/OpenSans-Italic-webfont.svg +1829 -1829
  76. package/doc/fonts/OpenSans-Italic-webfont.woff +0 -0
  77. package/doc/fonts/OpenSans-Light-webfont.eot +0 -0
  78. package/doc/fonts/OpenSans-Light-webfont.svg +1830 -1830
  79. package/doc/fonts/OpenSans-Light-webfont.woff +0 -0
  80. package/doc/fonts/OpenSans-LightItalic-webfont.eot +0 -0
  81. package/doc/fonts/OpenSans-LightItalic-webfont.svg +1834 -1834
  82. package/doc/fonts/OpenSans-LightItalic-webfont.woff +0 -0
  83. package/doc/fonts/OpenSans-Regular-webfont.eot +0 -0
  84. package/doc/fonts/OpenSans-Regular-webfont.svg +1830 -1830
  85. package/doc/fonts/OpenSans-Regular-webfont.woff +0 -0
  86. package/doc/global.html +308 -308
  87. package/doc/index.html +58 -58
  88. package/doc/listener.js.html +170 -170
  89. package/doc/mlsGen_mlsGenInterface.js.html +117 -117
  90. package/doc/myEventEmitter.js.html +124 -124
  91. package/doc/peer-connection_audioPeer.js.html +188 -188
  92. package/doc/peer-connection_listener.js.html +311 -311
  93. package/doc/peer-connection_speaker.js.html +381 -381
  94. package/doc/sc-activity-diagram.png +0 -0
  95. package/doc/scripts/linenumber.js +25 -25
  96. package/doc/scripts/prettify/Apache-License-2.0.txt +202 -202
  97. package/doc/scripts/prettify/lang-css.js +24 -24
  98. package/doc/scripts/prettify/prettify.js +640 -640
  99. package/doc/server_PythonServerAPI.js.html +160 -160
  100. package/doc/speaker.js.html +248 -248
  101. package/doc/styles/jsdoc-default.css +371 -371
  102. package/doc/styles/prettify-jsdoc.css +111 -111
  103. package/doc/styles/prettify-tomorrow.css +163 -163
  104. package/doc/tasks_audioCalibrator.js.html +207 -207
  105. package/doc/tasks_audioRecorder.js.html +190 -190
  106. package/doc/tasks_impulse-response_impulseResponse.js.html +442 -442
  107. package/doc/tasks_impulse-response_mlsGen_mlsGenInterface.js.html +175 -175
  108. package/doc/tasks_volume_volume.js.html +185 -185
  109. package/doc/utils.js.html +105 -105
  110. package/jest.config.js +173 -173
  111. package/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 +153 -153
  117. package/src/main.js +23 -23
  118. package/src/myEventEmitter.js +83 -83
  119. package/src/peer-connection/audioPeer.js +183 -183
  120. package/src/peer-connection/listener.js +369 -369
  121. package/src/peer-connection/peerErrors.js +25 -25
  122. package/src/peer-connection/speaker.js +767 -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 +3160 -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,767 @@
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
+
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 = this.uri;
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 language = this.language;
374
+ const phrases = this.phrases;
375
+ const checkConnection = document.createElement('a');
376
+ checkConnection.id = 'check-connection';
377
+ checkConnection.href = '#';
378
+ checkConnection.innerHTML = "check the phone's internet connection";
379
+ checkConnection.addEventListener('click', function (event) {
380
+ event.preventDefault();
381
+ createAndShowPopup(language, phrases);
382
+ });
383
+ explanation.querySelector('a#check-connection').replaceWith(checkConnection);
384
+ textColumn.appendChild(explanation);
385
+
386
+ // Column 3: Buttons
387
+ const buttonColumn = document.createElement('div');
388
+ buttonColumn.style.display = 'flex';
389
+ buttonColumn.style.flexDirection = 'column';
390
+ buttonColumn.style.gap = '10px';
391
+ buttonColumn.style.flex = '0 0 auto';
392
+ buttonColumn.style.alignItems = 'flex-end';
393
+ buttonColumn.appendChild(this.buttonsContainer);
394
+
395
+ // Assemble the columns
396
+ container.appendChild(qrColumn);
397
+ container.appendChild(textColumn);
398
+ container.appendChild(buttonColumn);
399
+
400
+ document.getElementById(this.targetElement).appendChild(container);
401
+ } else {
402
+ // show the link to the user
403
+ // If specified HTML Id is available, show QR code there
404
+ if (document.getElementById(this.targetElement)) {
405
+ // const linkTag = document.createElement('a');
406
+ // linkTag.setAttribute('href', uri);
407
+ // linkTag.innerHTML = 'Click here to start the calibration';
408
+ // linkTag.target = '_blank';
409
+ // document.getElementById(this.targetElement).appendChild(linkTag);
410
+ // document.getElementById(this.targetElement).appendChild(qrCanvas);
411
+
412
+ const proceedButton = document.createElement('button');
413
+ proceedButton.setAttribute('id', 'calibrationProceedButton');
414
+ proceedButton.setAttribute('class', 'btn btn-success');
415
+ proceedButton.innerHTML = this.phrases.T_proceed[this.language];
416
+ proceedButton.onclick = () => {
417
+ // open the link in a new tab
418
+ window.open(this.uri, '_blank');
419
+ // remove the button
420
+ document.getElementById('calibrationProceedButton').remove();
421
+ };
422
+ document.getElementById(this.targetElement).appendChild(proceedButton);
423
+ }
424
+ }
425
+ // or just print it to console
426
+ console.log('TEST: Peer reachable at: ', this.uri);
427
+ };
428
+
429
+ #showSpinner = () => {
430
+ const spinner = document.createElement('div');
431
+ spinner.className = 'spinner-border ml-auto';
432
+ spinner.role = 'status';
433
+ spinner.ariaHidden = 'true';
434
+ spinner.style.marginTop = '0.8rem';
435
+ document.getElementById(this.targetElement).appendChild(spinner);
436
+
437
+ // clear instructionDisplay
438
+ const soundMessage = document.getElementById(this.soundMessageId);
439
+ soundMessage.innerHTML = '';
440
+ soundMessage.style.display = 'none';
441
+ const instructionDisplay = document.getElementById(this.instructionDisplayId);
442
+ const background = document.getElementById('background'); // todo: get background id from params
443
+ const subtitle = document.getElementById(this.soundSubtitleId);
444
+ if (subtitle) {
445
+ subtitle.innerHTML = '';
446
+ }
447
+ if (instructionDisplay) {
448
+ instructionDisplay.innerHTML = '';
449
+ instructionDisplay.style.whiteSpace = 'nowrap';
450
+ instructionDisplay.style.fontWeight = 'bold';
451
+ instructionDisplay.style.width = 'fit-content';
452
+ instructionDisplay.innerHTML = this.phrases.RC_soundRecording[this.language];
453
+ let fontSize = 100;
454
+ instructionDisplay.style.fontSize = fontSize + 'px';
455
+ while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
456
+ fontSize--;
457
+ instructionDisplay.style.fontSize = fontSize + 'px';
458
+ }
459
+ // const p = document.createElement('p');
460
+ // // font size
461
+ // p.style.fontSize = '1.1rem';
462
+ // p.style.fontWeight = 'normal';
463
+ // p.style.paddingTop = '20px';
464
+ // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
465
+ // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
466
+ // instructionDisplay.appendChild(p);
467
+ }
468
+
469
+ const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
470
+ if (timeToCalibrateDisplay) {
471
+ const timeToCalibrateText = this.phrases.RC_howLongToCalibrate[this.language];
472
+ timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
473
+ timeToCalibrateDisplay.style.fontWeight = 'normal';
474
+ timeToCalibrateDisplay.style.fontSize = '1rem';
475
+ // timeToCalibrateDisplay.style.paddingTop = '20px';
476
+ }
477
+
478
+ // Update title - titleDisplayId
479
+ const titleDisplay = document.getElementById(this.titleDisplayId);
480
+ if (titleDisplay) {
481
+ // if (this.isParticipant) {
482
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
483
+ // } else if (this.isSmartPhone) {
484
+ // if (this.isLoudspeakerCalibration) {
485
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
486
+ // } else {
487
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
488
+ // }
489
+ // } else {
490
+ // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
491
+ // }
492
+ if (this.isLoudspeakerCalibration) {
493
+ if (this.isParticipant) {
494
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
495
+ } else if (this.isSmartPhone) {
496
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');
497
+ } else {
498
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('4', '5');
499
+ }
500
+ } else {
501
+ if (this.isSmartPhone) {
502
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');
503
+ } else {
504
+ titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');
505
+ }
506
+ }
507
+ }
508
+ };
509
+
510
+ #removeUIElems = () => {
511
+ const parent = document.getElementById(this.targetElement);
512
+ while (parent.firstChild) {
513
+ parent.firstChild.remove();
514
+ }
515
+ };
516
+
517
+ /**
518
+ * Called when the peer connection is opened.
519
+ * Saves the peer id and calls the QR code generator.
520
+ *
521
+ * @param peerId - The peer id of the peer connection.
522
+ * @param id
523
+ * @private
524
+ * @example
525
+ */
526
+ #onPeerOpen = id => {
527
+ // Workaround for peer.reconnect deleting previous id
528
+ try {
529
+ if (id === null) {
530
+ console.error('Received null id from peer open');
531
+ this.peer.id = this.lastPeerId;
532
+ } else {
533
+ this.lastPeerId = this.peer.id;
534
+ }
535
+
536
+ if (id !== this.peer.id) {
537
+ console.warn('DEBUG Check you assumption that id === this.peer.id');
538
+ }
539
+ } catch (error) {
540
+ console.error('Error in #onPeerOpen: ', error);
541
+ }
542
+
543
+ this.#showQRCode();
544
+ };
545
+
546
+ /**
547
+ * Called when the peer connection is established.
548
+ * Enforces a single connection.
549
+ *
550
+ * @param connection - The connection object.
551
+ * @private
552
+ * @example
553
+ */
554
+ #onPeerConnection = connection => {
555
+ // Allow only a single connection
556
+ if (this.conn && this.conn.open) {
557
+ connection.on('open', () => {
558
+ connection.send('Already connected to another client');
559
+ setTimeout(() => {
560
+ connection.close();
561
+ }, 500);
562
+ });
563
+ return;
564
+ }
565
+
566
+ this.conn = connection;
567
+ console.log('Connected to: ', this.conn.peer);
568
+ this.#ready();
569
+ };
570
+
571
+ /**
572
+ * Called when the peer connection is closed.
573
+ *
574
+ * @private
575
+ * @example
576
+ */
577
+ onPeerClose = () => {
578
+ this.conn = null;
579
+ console.log('Connection destroyed');
580
+ };
581
+
582
+ static closeConnection = () => {
583
+ this.conn = null;
584
+ console.log('Connection destroyed');
585
+ };
586
+
587
+ /**
588
+ * Called when the peer connection is disconnected.
589
+ * Attempts to reconnect.
590
+ *
591
+ * @private
592
+ * @example
593
+ */
594
+ #onPeerDisconnected = () => {
595
+ console.log('Connection lost. Please reconnect');
596
+
597
+ try {
598
+ // Workaround for peer.reconnect deleting previous id
599
+ this.peer.id = this.lastPeerId;
600
+ // eslint-disable-next-line no-underscore-dangle
601
+ this.peer._lastServerId = this.lastPeerId;
602
+ this.peer.reconnect();
603
+ } catch (error) {
604
+ console.error('Error in #onPeerDisconnected: ', error);
605
+ }
606
+ };
607
+
608
+ /**
609
+ * Called when the peer connection encounters an error.
610
+ *
611
+ * @param error
612
+ * @private
613
+ * @example
614
+ */
615
+ #onPeerError = error => {
616
+ // TODO: check if this function is needed or not
617
+ console.error(error);
618
+ };
619
+
620
+ /**
621
+ * Called when data is received from the peer connection.
622
+ *
623
+ * @param data
624
+ * @private
625
+ * @example
626
+ */
627
+ #onIncomingData = data => {
628
+ // enforce object type
629
+ if (
630
+ !Object.prototype.hasOwnProperty.call(data, 'name') ||
631
+ !Object.prototype.hasOwnProperty.call(data, 'payload')
632
+ ) {
633
+ console.error('Received malformed data: ', data);
634
+ return;
635
+ }
636
+
637
+ switch (data.name) {
638
+ case 'samplingRate':
639
+ this.ac.setSamplingRates(data.payload);
640
+ break;
641
+ case 'sampleSize':
642
+ this.ac.setSampleSize(data.payload);
643
+ break;
644
+ case 'deviceType':
645
+ this.ac.setDeviceType(data.payload);
646
+ break;
647
+ case 'deviceName':
648
+ this.ac.setDeviceName(data.payload);
649
+ break;
650
+ case 'flags':
651
+ //this.ac.setDeviceName(data.payload);
652
+ console.log('FLAGS');
653
+ console.log(data.payload);
654
+ this.ac.setFlags(data.payload);
655
+ break;
656
+ case 'deviceInfo':
657
+ this.ac.setDeviceInfo(data.payload);
658
+ console.log('Received device info from listener: ', data.payload);
659
+ break;
660
+ case UnsupportedDeviceError.name:
661
+ case MissingSpeakerIdError.name:
662
+ throw data.payload;
663
+ break;
664
+ default:
665
+ break;
666
+ }
667
+ };
668
+
669
+ /**
670
+ * Called when the peer connection is #ready.
671
+ *
672
+ * @private
673
+ * @example
674
+ */
675
+ #ready = () => {
676
+ // Perform callback with data
677
+ this.conn.on('data', this.#onIncomingData);
678
+ this.conn.on('close', () => {
679
+ console.log('Connection reset<br>Awaiting connection...');
680
+ this.conn = null;
681
+ });
682
+ };
683
+
684
+ /** .
685
+ * .
686
+ * .
687
+ * Debug method for downloading the recorded audio
688
+ *
689
+ * @public
690
+ * @example
691
+ */
692
+ downloadData = () => {
693
+ this.ac.downloadData();
694
+ };
695
+
696
+ repeatCalibration = async (params, stream, CalibratorInstance) => {
697
+ this.ac = CalibratorInstance;
698
+ this.#removeUIElems();
699
+ this.#showSpinner();
700
+
701
+ console.log('This is a repeat');
702
+ // wrap the calibration process in a promise so we can await it
703
+ return new Promise(async (resolve, reject) => {
704
+ const result = await this.ac.startCalibration(
705
+ stream,
706
+ params.gainValues,
707
+ params.ICalib,
708
+ params.knownIR,
709
+ params.microphoneName,
710
+ params.calibrateSoundCheck,
711
+ params.isSmartPhone,
712
+ params.calibrateSoundBurstDb,
713
+ params.calibrateSoundBurstFilteredExtraDb,
714
+ params.calibrateSoundBurstLevelReTBool,
715
+ params.calibrateSoundBurstUses1000HzGainBool,
716
+ params.calibrateSoundBurstRepeats,
717
+ params.calibrateSoundBurstSec,
718
+ params._calibrateSoundBurstPreSec,
719
+ params._calibrateSoundBurstPostSec,
720
+ params.calibrateSoundHz,
721
+ params.calibrateSoundIRSec,
722
+ params.calibrateSoundIIRSec,
723
+ params.calibrateSoundIIRPhase,
724
+ params.calibrateSound1000HzPreSec,
725
+ params.calibrateSound1000HzSec,
726
+ params.calibrateSound1000HzPostSec,
727
+ params.calibrateSoundBackgroundSecs,
728
+ params.calibrateSoundSmoothOctaves,
729
+ params.calibrateSoundSmoothMinBandwidthHz,
730
+ params.calibrateSoundPowerBinDesiredSec,
731
+ params.calibrateSoundPowerDbSDToleratedDb,
732
+ params.calibrateSoundTaperSec,
733
+ params.micManufacturer,
734
+ params.micSerialNumber,
735
+ params.micModelNumber,
736
+ params.micModelName,
737
+ params.calibrateMicrophonesBool,
738
+ params.authorEmails,
739
+ params.webAudioDeviceNames,
740
+ params.IDsToSaveInSoundProfileLibrary,
741
+ params.restartButton,
742
+ params.reminder,
743
+ params.calibrateSoundLimit,
744
+ params.calibrateSoundBurstNormalizeBy1000HzGainBool,
745
+ params.calibrateSoundBurstScalarDB,
746
+ params.calibrateSound1000HzMaxSD_dB,
747
+ params._calibrateSoundBurstMaxSD_dB,
748
+ params.calibrateSoundSamplingDesiredBits,
749
+ params.language,
750
+ params.loudspeakerModelName,
751
+ params.phrases,
752
+ params.soundSubtitleId
753
+ );
754
+ this.#removeUIElems();
755
+ resolve(result);
756
+ });
757
+ };
758
+ }
759
+
760
+ /*
761
+ Referenced links:
762
+ https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
763
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
764
+ https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
765
+ */
766
+
767
+ export default Speaker;