speaker-calibration 2.2.253 → 2.2.255

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