speaker-calibration 2.2.256 → 2.2.258

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