speaker-calibration 2.2.70 → 2.2.72

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 (119) 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/fetch-languages-sheets.js +77 -77
  31. package/dist/example/i18n.js +35846 -35846
  32. package/dist/example/index.html +47 -47
  33. package/dist/example/listener.html +62 -62
  34. package/dist/example/listener.js +282 -282
  35. package/dist/example/server.js +51 -51
  36. package/dist/example/speaker.html +145 -145
  37. package/dist/example/speakerUI.js +272 -272
  38. package/dist/example/styles.css +92 -92
  39. package/dist/main.js +17 -17
  40. package/dist/mlsGen.js +6814 -6814
  41. package/dist/mlsGen.wasm +0 -0
  42. package/dist/package-lock.json +1018 -1018
  43. package/dist/package.json +18 -18
  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 +69 -69
  93. package/src/config/firebase.js +25 -25
  94. package/src/index.html +21 -21
  95. package/src/main.js +23 -23
  96. package/src/myEventEmitter.js +83 -83
  97. package/src/peer-connection/audioPeer.js +151 -151
  98. package/src/peer-connection/listener.js +310 -306
  99. package/src/peer-connection/peerErrors.js +25 -25
  100. package/src/peer-connection/speaker.js +473 -473
  101. package/src/server/PythonServerAPI.js +587 -587
  102. package/src/tasks/audioCalibrator.js +308 -308
  103. package/src/tasks/audioRecorder.js +281 -281
  104. package/src/tasks/combination/combination.js +2088 -2088
  105. package/src/tasks/combination/mlsGen/mlsGen.cpp +98 -98
  106. package/src/tasks/combination/mlsGen/mlsGen.hpp +303 -303
  107. package/src/tasks/combination/mlsGen/mlsGenInterface.js +131 -131
  108. package/src/tasks/combination/mlsGen/mlsGenTest.cpp +180 -180
  109. package/src/tasks/impulse-response/impulseResponse.js +610 -610
  110. package/src/tasks/impulse-response/mlsGen/mlsGen.cpp +98 -98
  111. package/src/tasks/impulse-response/mlsGen/mlsGen.hpp +303 -303
  112. package/src/tasks/impulse-response/mlsGen/mlsGenInterface.js +131 -131
  113. package/src/tasks/impulse-response/mlsGen/mlsGenTest.cpp +180 -180
  114. package/src/tasks/volume/volume.cpp +2 -2
  115. package/src/tasks/volume/volume.hpp +22 -22
  116. package/src/tasks/volume/volume.js +279 -279
  117. package/src/utils.js +88 -88
  118. package/webpack.config.js +37 -37
  119. package/makefile +0 -74
@@ -1,473 +1,473 @@
1
- import QRCode from 'qrcode';
2
- import AudioPeer from './audioPeer';
3
- import {sleep} from '../utils';
4
- import {
5
- UnsupportedDeviceError,
6
- MissingSpeakerIdError,
7
- CalibrationTimedOutError,
8
- } from './peerErrors';
9
-
10
- import database from '../config/firebase';
11
- import {ref, set, get, child} from 'firebase/database';
12
- import {phrases} from '../../dist/example/i18n';
13
-
14
- /**
15
- * @class Handles the speaker's side of the connection. Responsible for initiating the connection,
16
- * rendering the QRCode, and answering the call.
17
- * @augments AudioPeer
18
- */
19
- class Speaker extends AudioPeer {
20
- /**
21
- * Takes the url of the current site and a target element where html elements will be appended.
22
- *
23
- * @param params - See type definition for initParameters.
24
- * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.
25
- * @param CalibratorInstance
26
- * @example
27
- */
28
- constructor(params, CalibratorInstance) {
29
- super(params);
30
- this.language = params?.language ?? 'en-US';
31
- this.siteUrl += '/listener?';
32
- this.ac = CalibratorInstance;
33
- this.result = null;
34
- this.debug = params?.debug ?? false;
35
- this.isSmartPhone = params?.isSmartPhone ?? false;
36
- this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;
37
- this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;
38
- this.instructionDisplayId = params?.instructionDisplayId ?? '';
39
- this.timeToCalibrateDisplay = params?.timeToCalibrateId ?? '';
40
- this.soundMessageId = params?.soundMessageId ?? '';
41
- this.titleDisplayId = params?.titleDisplayId ?? '';
42
- this.timeToCalibrate = params?.timeToCalibrate ?? 10;
43
-
44
- /* Set up callbacks that handle any events related to our peer object. */
45
- this.peer.on('open', this.#onPeerOpen);
46
- this.peer.on('connection', this.#onPeerConnection);
47
- this.peer.on('close', this.#onPeerClose);
48
- this.peer.on('disconnected', this.#onPeerDisconnected);
49
- this.peer.on('error', this.#onPeerError);
50
- }
51
-
52
- static getMicrophoneNamesFromDatabase = async () => {
53
- const dbRef = ref(database);
54
- const snapshot = await get(child(dbRef, 'Microphone'));
55
- if (snapshot.exists()) {
56
- return Object.keys(snapshot.val());
57
- }
58
- return null;
59
- };
60
-
61
- static doesMicrophoneExist = async (speakerID, OEM) => {
62
- const dbRef = ref(database);
63
- const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}`));
64
- if (snapshot.exists()) {
65
- return true;
66
- }
67
- return false;
68
- };
69
-
70
- /**
71
- * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.
72
- *
73
- * @param params - The parameters to be passed to the peer object.
74
- * @param Calibrator - The class that defines the calibration process.
75
- * @param CalibratorInstance
76
- * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).
77
- * @public
78
- * @example
79
- */
80
- static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {
81
- window.speaker = new Speaker(params, CalibratorInstance);
82
- const {speaker} = window;
83
-
84
- // wrap the calibration process in a promise so we can await it
85
- return new Promise((resolve, reject) => {
86
- // when a call is received
87
- speaker.peer.on('call', async call => {
88
- // Answer the call (one way)
89
-
90
- call.answer();
91
- speaker.#removeUIElems();
92
- speaker.#showSpinner();
93
- speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
94
- // when we start receiving audio
95
- call.on('stream', async stream => {
96
- window.localStream = stream;
97
- window.localAudio.srcObject = stream;
98
- window.localAudio.autoplay = false;
99
-
100
- // if the sinkSamplingRate is not set sleep
101
- while (!speaker.ac.sampleRatesSet()) {
102
- console.log('SinkSamplingRate is undefined, sleeping');
103
- await sleep(1);
104
- }
105
- // resolve when we have a result
106
- speaker.result = await speaker.ac.startCalibration(
107
- stream,
108
- params.gainValues,
109
- params.ICalib,
110
- params.knownIR,
111
- params.microphoneName,
112
- params.calibrateSoundCheck,
113
- params.isSmartPhone,
114
- params.calibrateSoundBurstDb,
115
- params.calibrateSoundBurstRepeats,
116
- params.calibrateSoundBurstSec,
117
- params.calibrateSoundBurstsWarmup,
118
- params.calibrateSoundHz,
119
- params.calibrateSoundIIRSec,
120
- params.calibrateSound1000HzPreSec,
121
- params.calibrateSound1000HzSec,
122
- params.calibrateSound1000HzPostSec,
123
- params.calibrateSoundBackgroundSecs,
124
- params.micManufacturer,
125
- params.micSerialNumber,
126
- params.micModelNumber,
127
- params.micModelName
128
- );
129
- speaker.#removeUIElems();
130
- resolve(speaker.result);
131
- });
132
- // if we do not receive a result within the timeout, reject
133
- setTimeout(() => {
134
- reject(
135
- new CalibrationTimedOutError(
136
- `Calibration failed to produce a result after ${
137
- timeOut / 1000
138
- } seconds. Please try again.`
139
- )
140
- );
141
- }, timeOut);
142
- });
143
- });
144
- };
145
-
146
- static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {
147
- window.speaker = new Speaker(params, CalibratorInstance);
148
- const {speaker} = window;
149
-
150
- // wrap the calibration process in a promise so we can await it
151
- return new Promise((resolve, reject) => {
152
- // when a call is received
153
- speaker.peer.on('call', async call => {
154
- // Answer the call (one way)
155
- call.answer();
156
- speaker.#removeUIElems();
157
- speaker.#showSpinner();
158
- speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
159
- // when we start receiving audio
160
- call.on('stream', async stream => {
161
- window.localStream = stream;
162
- window.localAudio.srcObject = stream;
163
- window.localAudio.autoplay = false;
164
-
165
- // if the sinkSamplingRate is not set sleep
166
- while (!speaker.ac.sampleRatesSet()) {
167
- console.log('SinkSamplingRate is undefined, sleeping');
168
- await sleep(1);
169
- }
170
- // resolve when we have a result
171
- speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);
172
- speaker.#removeUIElems();
173
- resolve(speaker.result);
174
- });
175
- // if we do not receive a result within the timeout, reject
176
- setTimeout(() => {
177
- reject(
178
- new CalibrationTimedOutError(
179
- `Calibration failed to produce a result after ${
180
- timeOut / 1000
181
- } seconds. Please try again.`
182
- )
183
- );
184
- }, timeOut);
185
- });
186
- });
187
- };
188
-
189
- /**
190
- * Called after the peer conncection has been opened.
191
- * Generates a QR code for the connection and displays it.
192
- *
193
- * @private
194
- * @example
195
- */
196
- #showQRCode = () => {
197
- // Get query string, the URL parameters to specify a Listener
198
- const queryStringParameters = {
199
- speakerPeerId: this.peer.id,
200
- isSmartPhone: this.isSmartPhone,
201
- calibrateSoundHz: this.calibrateSoundHz,
202
- calibrateSoundSamplingDesiredBits: this.calibrateSoundSamplingDesiredBits,
203
- lang: this.language,
204
- };
205
- const queryString = this.queryStringFromObject(queryStringParameters);
206
- const uri = this.siteUrl + queryString;
207
- if (this.isSmartPhone) {
208
- // Display QR code for the participant to scan
209
- const qrCanvas = document.createElement('canvas');
210
- qrCanvas.setAttribute('id', 'qrCanvas');
211
- console.log(uri);
212
- QRCode.toCanvas(qrCanvas, uri, error => {
213
- if (error) console.error(error);
214
- });
215
- document.getElementById(this.targetElement).appendChild(qrCanvas);
216
- } else {
217
- // show the link to the user
218
- // If specified HTML Id is available, show QR code there
219
- if (document.getElementById(this.targetElement)) {
220
- // const linkTag = document.createElement('a');
221
- // linkTag.setAttribute('href', uri);
222
- // linkTag.innerHTML = 'Click here to start the calibration';
223
- // linkTag.target = '_blank';
224
- // document.getElementById(this.targetElement).appendChild(linkTag);
225
- // document.getElementById(this.targetElement).appendChild(qrCanvas);
226
-
227
- const proceedButton = document.createElement('button');
228
- proceedButton.setAttribute('id', 'calibrationProceedButton');
229
- proceedButton.setAttribute('class', 'btn btn-success');
230
- proceedButton.innerHTML = 'Proceed';
231
- proceedButton.onclick = () => {
232
- // open the link in a new tab
233
- window.open(uri, '_blank');
234
- // remove the button
235
- document.getElementById('calibrationProceedButton').remove();
236
- };
237
- document.getElementById(this.targetElement).appendChild(proceedButton);
238
- }
239
- }
240
- // or just print it to console
241
- console.log('TEST: Peer reachable at: ', uri);
242
- };
243
-
244
- #showSpinner = () => {
245
- const spinner = document.createElement('div');
246
- spinner.className = 'spinner-border ml-auto';
247
- spinner.role = 'status';
248
- spinner.ariaHidden = 'true';
249
- document.getElementById(this.targetElement).appendChild(spinner);
250
-
251
- // clear instructionDisplay
252
- const soundMessage = document.getElementById(this.soundMessageId);
253
- soundMessage.innerHTML = '';
254
- soundMessage.style.display = 'none';
255
- const instructionDisplay = document.getElementById(this.instructionDisplayId);
256
- const background = document.getElementById('background'); // todo: get background id from params
257
- if (instructionDisplay) {
258
- instructionDisplay.innerHTML = '';
259
- instructionDisplay.style.whiteSpace = 'nowrap';
260
- instructionDisplay.style.fontWeight = 'bold';
261
- instructionDisplay.style.width = 'fit-content';
262
- instructionDisplay.innerHTML = phrases.RC_soundRecording[this.language];
263
- let fontSize = 100;
264
- instructionDisplay.style.fontSize = fontSize + 'px';
265
- while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
266
- fontSize--;
267
- instructionDisplay.style.fontSize = fontSize + 'px';
268
- }
269
- // const p = document.createElement('p');
270
- // // font size
271
- // p.style.fontSize = '1.1rem';
272
- // p.style.fontWeight = 'normal';
273
- // p.style.paddingTop = '20px';
274
- // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
275
- // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
276
- // instructionDisplay.appendChild(p);
277
- }
278
-
279
- const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
280
- if (timeToCalibrateDisplay) {
281
- const timeToCalibrateText = phrases.RC_howLongToCalibrate[this.language];
282
- timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
283
- timeToCalibrateDisplay.style.fontWeight = 'normal';
284
- timeToCalibrateDisplay.style.fontSize = '1rem';
285
- // timeToCalibrateDisplay.style.paddingTop = '20px';
286
- }
287
-
288
- // Update title - titleDisplayId
289
- const titleDisplay = document.getElementById(this.titleDisplayId);
290
- if (titleDisplay) {
291
- // replace 5 with 6
292
- titleDisplay.innerHTML = this.isSmartPhone
293
- ? titleDisplay.innerHTML.replace('2', '3')
294
- : titleDisplay.innerHTML.replace('4', '5');
295
- }
296
- };
297
-
298
- #removeUIElems = () => {
299
- const parent = document.getElementById(this.targetElement);
300
- while (parent.firstChild) {
301
- parent.firstChild.remove();
302
- }
303
- };
304
-
305
- /**
306
- * Called when the peer connection is opened.
307
- * Saves the peer id and calls the QR code generator.
308
- *
309
- * @param peerId - The peer id of the peer connection.
310
- * @param id
311
- * @private
312
- * @example
313
- */
314
- #onPeerOpen = id => {
315
- // Workaround for peer.reconnect deleting previous id
316
- if (id === null) {
317
- console.error('Received null id from peer open');
318
- this.peer.id = this.lastPeerId;
319
- } else {
320
- this.lastPeerId = this.peer.id;
321
- }
322
-
323
- if (id !== this.peer.id) {
324
- console.warn('DEBUG Check you assumption that id === this.peer.id');
325
- }
326
-
327
- this.#showQRCode();
328
- };
329
-
330
- /**
331
- * Called when the peer connection is established.
332
- * Enforces a single connection.
333
- *
334
- * @param connection - The connection object.
335
- * @private
336
- * @example
337
- */
338
- #onPeerConnection = connection => {
339
- // Allow only a single connection
340
- if (this.conn && this.conn.open) {
341
- connection.on('open', () => {
342
- connection.send('Already connected to another client');
343
- setTimeout(() => {
344
- connection.close();
345
- }, 500);
346
- });
347
- return;
348
- }
349
-
350
- this.conn = connection;
351
- console.log('Connected to: ', this.conn.peer);
352
- this.#ready();
353
- };
354
-
355
- /**
356
- * Called when the peer connection is closed.
357
- *
358
- * @private
359
- * @example
360
- */
361
- #onPeerClose = () => {
362
- this.conn = null;
363
- console.log('Connection destroyed');
364
- };
365
-
366
- /**
367
- * Called when the peer connection is disconnected.
368
- * Attempts to reconnect.
369
- *
370
- * @private
371
- * @example
372
- */
373
- #onPeerDisconnected = () => {
374
- console.log('Connection lost. Please reconnect');
375
-
376
- // Workaround for peer.reconnect deleting previous id
377
- this.peer.id = this.lastPeerId;
378
- // eslint-disable-next-line no-underscore-dangle
379
- this.peer._lastServerId = this.lastPeerId;
380
- this.peer.reconnect();
381
- };
382
-
383
- /**
384
- * Called when the peer connection encounters an error.
385
- *
386
- * @param error
387
- * @private
388
- * @example
389
- */
390
- #onPeerError = error => {
391
- // TODO: check if this function is needed or not
392
- console.error(error);
393
- };
394
-
395
- /**
396
- * Called when data is received from the peer connection.
397
- *
398
- * @param data
399
- * @private
400
- * @example
401
- */
402
- #onIncomingData = data => {
403
- // enforce object type
404
- if (
405
- !Object.prototype.hasOwnProperty.call(data, 'name') ||
406
- !Object.prototype.hasOwnProperty.call(data, 'payload')
407
- ) {
408
- console.error('Received malformed data: ', data);
409
- return;
410
- }
411
-
412
- switch (data.name) {
413
- case 'samplingRate':
414
- this.ac.setSamplingRates(data.payload);
415
- break;
416
- case 'sampleSize':
417
- this.ac.setSampleSize(data.payload);
418
- break;
419
- case 'deviceType':
420
- this.ac.setDeviceType(data.payload);
421
- break;
422
- case 'deviceName':
423
- this.ac.setDeviceName(data.payload);
424
- break;
425
- case 'deviceInfo':
426
- this.ac.setDeviceInfo(data.payload);
427
- console.log('Received device info from listener: ', data.payload);
428
- break;
429
- case UnsupportedDeviceError.name:
430
- case MissingSpeakerIdError.name:
431
- throw data.payload;
432
- break;
433
- default:
434
- break;
435
- }
436
- };
437
-
438
- /**
439
- * Called when the peer connection is #ready.
440
- *
441
- * @private
442
- * @example
443
- */
444
- #ready = () => {
445
- // Perform callback with data
446
- this.conn.on('data', this.#onIncomingData);
447
- this.conn.on('close', () => {
448
- console.log('Connection reset<br>Awaiting connection...');
449
- this.conn = null;
450
- });
451
- };
452
-
453
- /** .
454
- * .
455
- * .
456
- * Debug method for downloading the recorded audio
457
- *
458
- * @public
459
- * @example
460
- */
461
- downloadData = () => {
462
- this.ac.downloadData();
463
- };
464
- }
465
-
466
- /*
467
- Referenced links:
468
- https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
469
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
470
- https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
471
- */
472
-
473
- export default Speaker;
1
+ import QRCode from 'qrcode';
2
+ import AudioPeer from './audioPeer';
3
+ import {sleep} from '../utils';
4
+ import {
5
+ UnsupportedDeviceError,
6
+ MissingSpeakerIdError,
7
+ CalibrationTimedOutError,
8
+ } from './peerErrors';
9
+
10
+ import database from '../config/firebase';
11
+ import {ref, set, get, child} from 'firebase/database';
12
+ import {phrases} from '../../dist/example/i18n';
13
+
14
+ /**
15
+ * @class Handles the speaker's side of the connection. Responsible for initiating the connection,
16
+ * rendering the QRCode, and answering the call.
17
+ * @augments AudioPeer
18
+ */
19
+ class Speaker extends AudioPeer {
20
+ /**
21
+ * Takes the url of the current site and a target element where html elements will be appended.
22
+ *
23
+ * @param params - See type definition for initParameters.
24
+ * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.
25
+ * @param CalibratorInstance
26
+ * @example
27
+ */
28
+ constructor(params, CalibratorInstance) {
29
+ super(params);
30
+ this.language = params?.language ?? 'en-US';
31
+ this.siteUrl += '/listener?';
32
+ this.ac = CalibratorInstance;
33
+ this.result = null;
34
+ this.debug = params?.debug ?? false;
35
+ this.isSmartPhone = params?.isSmartPhone ?? false;
36
+ this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;
37
+ this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;
38
+ this.instructionDisplayId = params?.instructionDisplayId ?? '';
39
+ this.timeToCalibrateDisplay = params?.timeToCalibrateId ?? '';
40
+ this.soundMessageId = params?.soundMessageId ?? '';
41
+ this.titleDisplayId = params?.titleDisplayId ?? '';
42
+ this.timeToCalibrate = params?.timeToCalibrate ?? 10;
43
+
44
+ /* Set up callbacks that handle any events related to our peer object. */
45
+ this.peer.on('open', this.#onPeerOpen);
46
+ this.peer.on('connection', this.#onPeerConnection);
47
+ this.peer.on('close', this.#onPeerClose);
48
+ this.peer.on('disconnected', this.#onPeerDisconnected);
49
+ this.peer.on('error', this.#onPeerError);
50
+ }
51
+
52
+ static getMicrophoneNamesFromDatabase = async () => {
53
+ const dbRef = ref(database);
54
+ const snapshot = await get(child(dbRef, 'Microphone'));
55
+ if (snapshot.exists()) {
56
+ return Object.keys(snapshot.val());
57
+ }
58
+ return null;
59
+ };
60
+
61
+ static doesMicrophoneExist = async (speakerID, OEM) => {
62
+ const dbRef = ref(database);
63
+ const snapshot = await get(child(dbRef, `Microphone2/${OEM}/${speakerID}`));
64
+ if (snapshot.exists()) {
65
+ return true;
66
+ }
67
+ return false;
68
+ };
69
+
70
+ /**
71
+ * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.
72
+ *
73
+ * @param params - The parameters to be passed to the peer object.
74
+ * @param Calibrator - The class that defines the calibration process.
75
+ * @param CalibratorInstance
76
+ * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).
77
+ * @public
78
+ * @example
79
+ */
80
+ static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {
81
+ window.speaker = new Speaker(params, CalibratorInstance);
82
+ const {speaker} = window;
83
+
84
+ // wrap the calibration process in a promise so we can await it
85
+ return new Promise((resolve, reject) => {
86
+ // when a call is received
87
+ speaker.peer.on('call', async call => {
88
+ // Answer the call (one way)
89
+
90
+ call.answer();
91
+ speaker.#removeUIElems();
92
+ speaker.#showSpinner();
93
+ speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
94
+ // when we start receiving audio
95
+ call.on('stream', async stream => {
96
+ window.localStream = stream;
97
+ window.localAudio.srcObject = stream;
98
+ window.localAudio.autoplay = false;
99
+
100
+ // if the sinkSamplingRate is not set sleep
101
+ while (!speaker.ac.sampleRatesSet()) {
102
+ console.log('SinkSamplingRate is undefined, sleeping');
103
+ await sleep(1);
104
+ }
105
+ // resolve when we have a result
106
+ speaker.result = await speaker.ac.startCalibration(
107
+ stream,
108
+ params.gainValues,
109
+ params.ICalib,
110
+ params.knownIR,
111
+ params.microphoneName,
112
+ params.calibrateSoundCheck,
113
+ params.isSmartPhone,
114
+ params.calibrateSoundBurstDb,
115
+ params.calibrateSoundBurstRepeats,
116
+ params.calibrateSoundBurstSec,
117
+ params.calibrateSoundBurstsWarmup,
118
+ params.calibrateSoundHz,
119
+ params.calibrateSoundIIRSec,
120
+ params.calibrateSound1000HzPreSec,
121
+ params.calibrateSound1000HzSec,
122
+ params.calibrateSound1000HzPostSec,
123
+ params.calibrateSoundBackgroundSecs,
124
+ params.micManufacturer,
125
+ params.micSerialNumber,
126
+ params.micModelNumber,
127
+ params.micModelName
128
+ );
129
+ speaker.#removeUIElems();
130
+ resolve(speaker.result);
131
+ });
132
+ // if we do not receive a result within the timeout, reject
133
+ setTimeout(() => {
134
+ reject(
135
+ new CalibrationTimedOutError(
136
+ `Calibration failed to produce a result after ${
137
+ timeOut / 1000
138
+ } seconds. Please try again.`
139
+ )
140
+ );
141
+ }, timeOut);
142
+ });
143
+ });
144
+ };
145
+
146
+ static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {
147
+ window.speaker = new Speaker(params, CalibratorInstance);
148
+ const {speaker} = window;
149
+
150
+ // wrap the calibration process in a promise so we can await it
151
+ return new Promise((resolve, reject) => {
152
+ // when a call is received
153
+ speaker.peer.on('call', async call => {
154
+ // Answer the call (one way)
155
+ call.answer();
156
+ speaker.#removeUIElems();
157
+ speaker.#showSpinner();
158
+ speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
159
+ // when we start receiving audio
160
+ call.on('stream', async stream => {
161
+ window.localStream = stream;
162
+ window.localAudio.srcObject = stream;
163
+ window.localAudio.autoplay = false;
164
+
165
+ // if the sinkSamplingRate is not set sleep
166
+ while (!speaker.ac.sampleRatesSet()) {
167
+ console.log('SinkSamplingRate is undefined, sleeping');
168
+ await sleep(1);
169
+ }
170
+ // resolve when we have a result
171
+ speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);
172
+ speaker.#removeUIElems();
173
+ resolve(speaker.result);
174
+ });
175
+ // if we do not receive a result within the timeout, reject
176
+ setTimeout(() => {
177
+ reject(
178
+ new CalibrationTimedOutError(
179
+ `Calibration failed to produce a result after ${
180
+ timeOut / 1000
181
+ } seconds. Please try again.`
182
+ )
183
+ );
184
+ }, timeOut);
185
+ });
186
+ });
187
+ };
188
+
189
+ /**
190
+ * Called after the peer conncection has been opened.
191
+ * Generates a QR code for the connection and displays it.
192
+ *
193
+ * @private
194
+ * @example
195
+ */
196
+ #showQRCode = () => {
197
+ // Get query string, the URL parameters to specify a Listener
198
+ const queryStringParameters = {
199
+ speakerPeerId: this.peer.id,
200
+ isSmartPhone: this.isSmartPhone,
201
+ calibrateSoundHz: this.calibrateSoundHz,
202
+ calibrateSoundSamplingDesiredBits: this.calibrateSoundSamplingDesiredBits,
203
+ lang: this.language,
204
+ };
205
+ const queryString = this.queryStringFromObject(queryStringParameters);
206
+ const uri = this.siteUrl + queryString;
207
+ if (this.isSmartPhone) {
208
+ // Display QR code for the participant to scan
209
+ const qrCanvas = document.createElement('canvas');
210
+ qrCanvas.setAttribute('id', 'qrCanvas');
211
+ console.log(uri);
212
+ QRCode.toCanvas(qrCanvas, uri, error => {
213
+ if (error) console.error(error);
214
+ });
215
+ document.getElementById(this.targetElement).appendChild(qrCanvas);
216
+ } else {
217
+ // show the link to the user
218
+ // If specified HTML Id is available, show QR code there
219
+ if (document.getElementById(this.targetElement)) {
220
+ // const linkTag = document.createElement('a');
221
+ // linkTag.setAttribute('href', uri);
222
+ // linkTag.innerHTML = 'Click here to start the calibration';
223
+ // linkTag.target = '_blank';
224
+ // document.getElementById(this.targetElement).appendChild(linkTag);
225
+ // document.getElementById(this.targetElement).appendChild(qrCanvas);
226
+
227
+ const proceedButton = document.createElement('button');
228
+ proceedButton.setAttribute('id', 'calibrationProceedButton');
229
+ proceedButton.setAttribute('class', 'btn btn-success');
230
+ proceedButton.innerHTML = 'Proceed';
231
+ proceedButton.onclick = () => {
232
+ // open the link in a new tab
233
+ window.open(uri, '_blank');
234
+ // remove the button
235
+ document.getElementById('calibrationProceedButton').remove();
236
+ };
237
+ document.getElementById(this.targetElement).appendChild(proceedButton);
238
+ }
239
+ }
240
+ // or just print it to console
241
+ console.log('TEST: Peer reachable at: ', uri);
242
+ };
243
+
244
+ #showSpinner = () => {
245
+ const spinner = document.createElement('div');
246
+ spinner.className = 'spinner-border ml-auto';
247
+ spinner.role = 'status';
248
+ spinner.ariaHidden = 'true';
249
+ document.getElementById(this.targetElement).appendChild(spinner);
250
+
251
+ // clear instructionDisplay
252
+ const soundMessage = document.getElementById(this.soundMessageId);
253
+ soundMessage.innerHTML = '';
254
+ soundMessage.style.display = 'none';
255
+ const instructionDisplay = document.getElementById(this.instructionDisplayId);
256
+ const background = document.getElementById('background'); // todo: get background id from params
257
+ if (instructionDisplay) {
258
+ instructionDisplay.innerHTML = '';
259
+ instructionDisplay.style.whiteSpace = 'nowrap';
260
+ instructionDisplay.style.fontWeight = 'bold';
261
+ instructionDisplay.style.width = 'fit-content';
262
+ instructionDisplay.innerHTML = phrases.RC_soundRecording[this.language];
263
+ let fontSize = 100;
264
+ instructionDisplay.style.fontSize = fontSize + 'px';
265
+ while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {
266
+ fontSize--;
267
+ instructionDisplay.style.fontSize = fontSize + 'px';
268
+ }
269
+ // const p = document.createElement('p');
270
+ // // font size
271
+ // p.style.fontSize = '1.1rem';
272
+ // p.style.fontWeight = 'normal';
273
+ // p.style.paddingTop = '20px';
274
+ // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];
275
+ // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
276
+ // instructionDisplay.appendChild(p);
277
+ }
278
+
279
+ const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);
280
+ if (timeToCalibrateDisplay) {
281
+ const timeToCalibrateText = phrases.RC_howLongToCalibrate[this.language];
282
+ timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);
283
+ timeToCalibrateDisplay.style.fontWeight = 'normal';
284
+ timeToCalibrateDisplay.style.fontSize = '1rem';
285
+ // timeToCalibrateDisplay.style.paddingTop = '20px';
286
+ }
287
+
288
+ // Update title - titleDisplayId
289
+ const titleDisplay = document.getElementById(this.titleDisplayId);
290
+ if (titleDisplay) {
291
+ // replace 5 with 6
292
+ titleDisplay.innerHTML = this.isSmartPhone
293
+ ? titleDisplay.innerHTML.replace('2', '3')
294
+ : titleDisplay.innerHTML.replace('4', '5');
295
+ }
296
+ };
297
+
298
+ #removeUIElems = () => {
299
+ const parent = document.getElementById(this.targetElement);
300
+ while (parent.firstChild) {
301
+ parent.firstChild.remove();
302
+ }
303
+ };
304
+
305
+ /**
306
+ * Called when the peer connection is opened.
307
+ * Saves the peer id and calls the QR code generator.
308
+ *
309
+ * @param peerId - The peer id of the peer connection.
310
+ * @param id
311
+ * @private
312
+ * @example
313
+ */
314
+ #onPeerOpen = id => {
315
+ // Workaround for peer.reconnect deleting previous id
316
+ if (id === null) {
317
+ console.error('Received null id from peer open');
318
+ this.peer.id = this.lastPeerId;
319
+ } else {
320
+ this.lastPeerId = this.peer.id;
321
+ }
322
+
323
+ if (id !== this.peer.id) {
324
+ console.warn('DEBUG Check you assumption that id === this.peer.id');
325
+ }
326
+
327
+ this.#showQRCode();
328
+ };
329
+
330
+ /**
331
+ * Called when the peer connection is established.
332
+ * Enforces a single connection.
333
+ *
334
+ * @param connection - The connection object.
335
+ * @private
336
+ * @example
337
+ */
338
+ #onPeerConnection = connection => {
339
+ // Allow only a single connection
340
+ if (this.conn && this.conn.open) {
341
+ connection.on('open', () => {
342
+ connection.send('Already connected to another client');
343
+ setTimeout(() => {
344
+ connection.close();
345
+ }, 500);
346
+ });
347
+ return;
348
+ }
349
+
350
+ this.conn = connection;
351
+ console.log('Connected to: ', this.conn.peer);
352
+ this.#ready();
353
+ };
354
+
355
+ /**
356
+ * Called when the peer connection is closed.
357
+ *
358
+ * @private
359
+ * @example
360
+ */
361
+ #onPeerClose = () => {
362
+ this.conn = null;
363
+ console.log('Connection destroyed');
364
+ };
365
+
366
+ /**
367
+ * Called when the peer connection is disconnected.
368
+ * Attempts to reconnect.
369
+ *
370
+ * @private
371
+ * @example
372
+ */
373
+ #onPeerDisconnected = () => {
374
+ console.log('Connection lost. Please reconnect');
375
+
376
+ // Workaround for peer.reconnect deleting previous id
377
+ this.peer.id = this.lastPeerId;
378
+ // eslint-disable-next-line no-underscore-dangle
379
+ this.peer._lastServerId = this.lastPeerId;
380
+ this.peer.reconnect();
381
+ };
382
+
383
+ /**
384
+ * Called when the peer connection encounters an error.
385
+ *
386
+ * @param error
387
+ * @private
388
+ * @example
389
+ */
390
+ #onPeerError = error => {
391
+ // TODO: check if this function is needed or not
392
+ console.error(error);
393
+ };
394
+
395
+ /**
396
+ * Called when data is received from the peer connection.
397
+ *
398
+ * @param data
399
+ * @private
400
+ * @example
401
+ */
402
+ #onIncomingData = data => {
403
+ // enforce object type
404
+ if (
405
+ !Object.prototype.hasOwnProperty.call(data, 'name') ||
406
+ !Object.prototype.hasOwnProperty.call(data, 'payload')
407
+ ) {
408
+ console.error('Received malformed data: ', data);
409
+ return;
410
+ }
411
+
412
+ switch (data.name) {
413
+ case 'samplingRate':
414
+ this.ac.setSamplingRates(data.payload);
415
+ break;
416
+ case 'sampleSize':
417
+ this.ac.setSampleSize(data.payload);
418
+ break;
419
+ case 'deviceType':
420
+ this.ac.setDeviceType(data.payload);
421
+ break;
422
+ case 'deviceName':
423
+ this.ac.setDeviceName(data.payload);
424
+ break;
425
+ case 'deviceInfo':
426
+ this.ac.setDeviceInfo(data.payload);
427
+ console.log('Received device info from listener: ', data.payload);
428
+ break;
429
+ case UnsupportedDeviceError.name:
430
+ case MissingSpeakerIdError.name:
431
+ throw data.payload;
432
+ break;
433
+ default:
434
+ break;
435
+ }
436
+ };
437
+
438
+ /**
439
+ * Called when the peer connection is #ready.
440
+ *
441
+ * @private
442
+ * @example
443
+ */
444
+ #ready = () => {
445
+ // Perform callback with data
446
+ this.conn.on('data', this.#onIncomingData);
447
+ this.conn.on('close', () => {
448
+ console.log('Connection reset<br>Awaiting connection...');
449
+ this.conn = null;
450
+ });
451
+ };
452
+
453
+ /** .
454
+ * .
455
+ * .
456
+ * Debug method for downloading the recorded audio
457
+ *
458
+ * @public
459
+ * @example
460
+ */
461
+ downloadData = () => {
462
+ this.ac.downloadData();
463
+ };
464
+ }
465
+
466
+ /*
467
+ Referenced links:
468
+ https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676
469
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
470
+ https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]
471
+ */
472
+
473
+ export default Speaker;