speaker-calibration 2.2.270 → 2.2.272

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