speaker-calibration 2.2.207 → 2.2.209

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.
package/dist/main.js CHANGED
@@ -424,7 +424,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/**\r\n * A simple event emit
424
424
  /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
425
425
 
426
426
  "use strict";
427
- eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var peerjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! peerjs */ \"./node_modules/peerjs/dist/peerjs.min.js\");\n/* harmony import */ var peerjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(peerjs__WEBPACK_IMPORTED_MODULE_0__);\n\r\n\r\n// TODO: this was already here before, but appears to be unused\r\nconst pressFeedbackURI =\r\n 'data:audio/mpeg;base64,//uQZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAALAAATlgAXFxcXFxcXFxcuLi4uLi4uLi5FRUVFRUVFRUVdXV1dXV1dXV10dHR0dHR0dHSLi4uLi4uLi4uioqKioqKioqK6urq6urq6urrR0dHR0dHR0dHo6Ojo6Ojo6Oj///////////8AAAA5TEFNRTMuMTAwAaoAAAAALgYAABSAJAZbTgAAgAAAE5YfafL/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//uQZAAAA0YVyhVvQAAAAA0goAABGfWdITn6gAgAADSDAAAAAEWjAwMwMDMFBzCQsw8PMPCwUDgkNMpNzXEoSUTP3s6nJPd4z28k62JNdIwIUHj3nvynRempMmLAo/tff9/3IchyHIch/IxY3SUmG86enD4Pg+fgmfEAIQQcsP+oH//E7/+Ud/1HP/B9AAABMCFFFAAAwDgCyMCVAgQcBQmARAHw0AOGAUgFJgUoL8YKsEvqzGA1APJQAIGBNgDpoBRvQYb6EIGhIkmJg1QA0aH0H4GDBgJ4G55UBpM1AGgUG0wAgOBIUAYJGoGFQ4AkHitxzRSocGMwDYYCwJAWAICgBD8jhwlEqBNsMiAkCBpQY2FxpG61opmucDLrjKi6Fmk5oK9PWVh1DNFM2IaRH/q8mTQgTF4sk0bnv//zEuqRMjYycuuj///5wxZzIvLSMTUxYyZL////86ZBqh4D+QUIABcwBQBLMCmAeTA4wJowO8E2DAeYwQ8CWMDLBHDB1QpIxscoSMwBQJj/WZBA3O4mFMHIAGzAKAVgwmcG8OIV//uSZCIN9VQ4wgd/gAAAAA0g4AABD+S/Di5+qgAAADSAAAAEEzcNTC4yM0m41SLDHAJLSggBKwtKRwb6+IBi4ctbepDskh2KmAgA16NTNrON66ptO40mNa9ayZHVx7zmGPHktZb7vP9xLn4fr+9jeO//8P+z39///9T/////t+d6vf1+c6fP9Hv5cxg4aA4TgkGIYmLbYHGAxaCjHwlM0lwBC4zGwzVG+MFnGoTY8sn0w1MSHA09vAM8ssDCSYAykIABmeCI4AKDMDIRfGbFAjWE8h+BfIEfBoFCTQJUcA5ZIrQDjzQ+gWzxsjDLtE4s46kxjHZZom2SXfyj6uadvNvb0ee/3dX//01YAVKw/FoW3hDrwUDTAwDMVigy8rTYaRNKug2tzzBwxnAx/DOuMhFECAOxWsDO6kAwkdQFH0BiwIgYlAwCgdAwiZBBI1kCC5JcWwCQWMQ/JQnkVFkOVN8oku8yDkjbMiry+2rrLvW/MvT53q/yv+n2///dywQL8DRgOgsrBBi0LGcngZrCZgYxGEAoZ+IplUdGJ1ifHVRh5v/7kmRMDPOhJ0MTn6qAAAANIAAAARDEiQhOf0pAAAA0gAAABAdCcEnCwmbqA1JhbIFwYKEAUGAXgOJo45oXAyjT0MinMgXM2UNoNGyYeLN0ENORMgQC5EYAJlr4Z3L3lgaHG5VO0lWX1q92J3t9sWM+bu9/fe8/VT/L+zq9v+zr9/+//8r71SAAAA9tq0AA1hzXXdxmzgPWzJyU20wh4EDDUSzWI4x4rgMGBd+IImDoAiEBAMCJn2HpqAlRpDIZhbxxp2ASQcGVRJG6RC4xmaZHiYlYPKGGdEGJjIoa4YtICXGHRhGJg2QMkYJADRGfCMTZE5+4ze1gMF1k163DfQrNgh83G3zIYoMdC4wEOwcrzMxMMam0AlYxkKzOgqMDhUuUBgYIQOWiEgwYHAogAwXBAYHAKAVVm0ZW2J1Wno9taaAzuOSF34AjMUjdBOy+pjbpKCil9TG/hOWRkUkxad2pAAAGFlrIADgyUqh1syPqzGQRoUAEDDoFgKMDw7MVA2NJ1sKHaMVghBwfGAgOgJR0migMTBUODDQezBI5jGNQzXD/+5JkjYD20jDN67/kngAADSAAAAEXjN0dTv9SAAAANIAAAASwgEb7HKvHZpiFAM0Bgs8wPYBNNi8MMfMIKRGRlOETOErM6wMGpBTQHTjJEQaKEBoKmlLXGizd5Ax5W2Byh0X6R9YRJ2rQFSKzgZDB0DQDKJHDr/MoZRDsaleN+vVhpoVqzczvZYx+Hdbx1/MuWOZb///Vr1YX93I/6P9KAWAQE8pFZWkOCuFAO0EEAThJ4OYwBQMHIJgUUVrHHRwaURUkZ4YX6MYvO6EDvpgTJY6aVeR7mGcgzBgfQE2YCuA5H9adJQKBCAhAqA53/aS/bk0T1zjIhpmcjVumpqS/ZZ1v6TuOXxF1+49x5d5Knl/Luvw7ua/8P/DdWT+dOkhD5zhvqb0db/93/5AQAQsF3glyO4MAysKti2BGAAdE0L31C4EMAhEAgAu28hgMOFHwEgaYACAFHpko0GM0ia2Yx0/wmKECIhpq5poYK2CTmAQAMhgAQBKYAoARFUAhUQbKhIMAxAFG3eFpLns4drJbaY9+pDVDPZ/QKtLHKNCpsTA6//uSZIEE9GAuRhNfzIAAAA0gAAABEnjLFK588sAAADSAAAAEdTXMSKxfop3DPM5RNbal/EvU7p6/Ie/t93Z1v6OqEAzmEmBoIQcGTCwGMCghPwvOQgUwEbKMZBgNAwOPZioUiMIl/ACXRGoREDB0clmTLApMiq4x2azRlmMM7NijivBEQxUIGvMGdAsjAxgHcDSxgRZANSYAOAgYs0FXAnwaIl43xAcuEVEogHIiFKRHEuREzUfFfSOoEgRyTk8Isema00Fl0gzqujqL/ZT3Krfoq7r1H/AvWzp/yXv/3f/oA0GjFwIZS19BgKAsiCDxuUBAMZ8D6zIZAIFMChweF7GFbQAITYoiSSSvMRBoUJ5l4RGVzOa2hhmAr6mbNSaYcYlxgqAvmAaCEYDAE6yBgAFIpAsGADyaXw+/MSnONGVBjhuNW+/dbYnEQqJJNwIgainmo0TB3Ofkus/yHs5P3dnW/+ryf+QqTEFNRTMuMTAwqqqqqqqqqqqqAABjBgrdYuwIwHSioNCCFkYbBZpMaoVDIRMDhB326ByJkJgYuGdC4P/7kmSwDPT4N0MLn6SAAAANIAAAARDIpRJOePLAAAA0gAAABDAGIA0YOGJhoVGKx+YbQxu2mmHbCT5rII6wYW2ASgYFJDgHYBAIpMARM6WcpEFALUjnWoXbkbwf8AGkx+2FugJGw/l2gIK+vverzfFet8Re/kur09f/f/u6f/1GySAhOMFigxOOnJAAdLIIqmTCCa9ahACTDANMqFMLAIQjQw0EVbjH4aOuN8OAgFCBn0sS0GpU0IAjUJ3MCoPaDTTB4AwnIE7MGrBCjAcgE836g5kUx6AtCKkjKElvKarxnFzLOlKRocalMtnabKM6hpYW5TSrdLe1Kop3e+ZWtymHt445fv9Vfyy/Hn5Xv///v1bXt4M9Z7+o729b+K/4b6pMQU1FMy4xMDCqqqqqqqqqqqoAArJ2QY8DbERAFjDyZMdBUwYDwIEDHduP9KsmPhhMKGHR0ZzTg0NTB4kGhkYqgZ2MZGQRUYNHoGXBgA4HWYEoBbGCNgvJhVgV8ZJaR2GsQJb5g5gRMYD+BQmAhADQNAVRoA4EQAOXUBwAkYBsAVr/+5Jk0w/0GynDE59coAAADSAAAAEULMkADn9SAAAANIAAAATsdabY4ta/VUMV5DuqzWuVs3pSSLmoKyJqFQGpUi+IAy2PdQm57ZU/m8oR6dDu/KvzehHpx5O/KkuvNN/o39SX9fblC3lusxd7wMr2zmhS+YLExsQBmRRQGKE6HITacxM2hgy8ATH50NVDsxSlQMPDL4bNJAg7HUAIBQcOjCRbMBtAdDAAACkwB4EWMCzCGTGll+U7EVMUMoPCSjDHgWcwaECqP+mza0I1QpATkY0Sm3lwsB0q0C3xd6GWuF4jEAeiqacWb5bdVxJbap8YzlnZWta3hLq34RaGf5hj3/pZ3HveY/3ku7/5a/7Wf//9/92aGoPcO9Z3nep/9H+mTEFNRTMuMTAwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqgBOZ2IMSwdMDATGQhDC4ZXKRj8wGMxub0k5717G//uSZPaO9axfvJOfPEAAAA0gAAABFsja3g5/cEAAADSAAAAELQSBSmZKFYVCYsIjBA1MCgYxWdDkBzMRAEwgQDIIBMgFIzWQTUjgPK3c02lpDWsiqM0Ih0w6QzjB4BzMDcD4wFgEzAfAeQQs8TcsNydp+n5wlq8UapFM2auMpwfZrv475ll25Y5ll3mtzMuwCWO8Ocqe/lndv+j/b1f6/9QATU2x0wCPIAYTCoUHAxhIYX2MXBDC24mvTCAedLotPVa09tEZwuBrSZmkoXXBgkY2SmmPBjQkpGrwfaYZQGhQDcPACJNPw90xLlijCVZWUifsophFk7ww7v7fGk6gE/vB+l0VNkSFwo0bYXJC6gyQQEiwvlDzbHAhHpZLIQbJ1UxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUASWNHVvyNdkdcuCnNLhmA8HuRIHbo/1AhfJ9JZVctla8gMQwpDT96eCGcDAGg8qCCIBce3D8P35RGMZXL8gcmxBByacE9hDD09hNohydtFshlp7EeIe9aMiMe/P/7kmTNjPTPJLaLvPDwAAANIAAAAQ/obuBt+FJAAAA0gAAABEchD3bEIchgekEBmZYRmyPAM3j4DJ8fhgfmeIjtD4HTwPAiPgNGB+BAAjtCABG8AwMvgwAEo5cSIfzt69YYDMdo9RxSsKtgIcom1PMylIK9rWkMkKzctAIIkqXCTqLYAoUrBCJrAlHzJipaMuaPvWraLnsMj6ExUtGUZ0ZRnJ7Q6PrnS7VrsC55kSlRyTYjonPkkybMT2AyVMrbMrYly661bq13Fz0K2JlbEdH1zk9ocnsB09CcutLYmj71p7Q6PWDI+hMXWjJ06Mozk9odH0BkfQmLrRlGdE6M5JrhKJzZKPoSSephKVHJlGcmLhkZXJJ9CYnrRkqSmMZybKpMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqr/+5Jk7QT0dTc4kxw0ogAADSAAAAEZOaLm5+WQSAAANIAAAASqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqglFJEIRoPjA2MDYyViqViCJxDHghjyPQ4ioUiYKw4EMzYZXAooDEE1y2zRpTu00acWUWWcacaUWYeWcacJAhYgWJFCRQGIFiBZZRZRZlw7s7PG////s7M7Ozs7M5xpRZR5RRpxZRZh5RRZRbRC1NP///9PKqqq4NNNNRKqJXTTTTVVVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uSZIIP9BFGHYksMlIAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ==';\r\n\r\n/**\r\n * @typedef initParameters - Parameters for initializing the AudioPeer\r\n * @type {object}\r\n * @property {string} targetElementId - Target element where new elements will be appended.\r\n * @property {string} siteUrl: The url of the current site.\r\n */\r\nconst initParameters = {\r\n targetElementId: null,\r\n siteUrl: null,\r\n};\r\n\r\n/**\r\n * @class The first layer of abstraction on the PeerJS library.\r\n * It meant to be extended by the two seperate client classes, Speaker and Listener.\r\n * It implements the shared methods and properties of both classes.\r\n */\r\nclass AudioPeer {\r\n /**\r\n * Creates an instance of AudioPeer\r\n * Takes the url of the current site and a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @param param\r\n * @example\r\n */\r\n constructor(param = initParameters) {\r\n // PeerJS\r\n /* Create the Peer object for our end of the connection. */\r\n this.peer = new (peerjs__WEBPACK_IMPORTED_MODULE_0___default())({\r\n secure: true,\r\n host: 'easyeyes-peer-server.herokuapp.com',\r\n port: 443,\r\n config: {\r\n iceServers: [\r\n {\r\n urls: 'stun:stun.relay.metered.ca:80',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:80',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:80?transport=tcp',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:443',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turns:global.relay.metered.ca:443?transport=tcp',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n ],\r\n },\r\n });\r\n this.conn = null;\r\n this.lastPeerId = null;\r\n\r\n // Display information to HTML elem with given id\r\n this.targetElement = param.targetElementId;\r\n\r\n this.siteUrl = param.siteUrl;\r\n this.debug = false;\r\n // Store for all incoming data\r\n this.dataStore = [];\r\n\r\n // Create and play sounds using this audio context\r\n this.sourceAudioContext = new (window.AudioContext ||\r\n window.webkitAudioContext ||\r\n window.audioContext)();\r\n }\r\n\r\n /** .\r\n * .\r\n * .\r\n * Helper method to display information to DOM element\r\n *\r\n * @param {string} message\r\n * @param {boolean} append\r\n * @example\r\n */\r\n displayUpdate = (message, append = true) => {\r\n // If the specified elem exists, update that elem\r\n if (document.getElementById(this.targetElement)) {\r\n const displayElement = document.getElementById(this.targetElement);\r\n if (append) {\r\n displayElement.innerText += `\\n${message}`;\r\n } else {\r\n displayElement.innerText = message;\r\n }\r\n } else {\r\n console.log('MESSAGE: ', message);\r\n }\r\n };\r\n\r\n /**\r\n * Callback method for when a peer connection is lost\r\n * saves the last peer id, last server id, and attempts to reconnect.\r\n *\r\n * @example\r\n */\r\n onPeerDisconnected = () => {\r\n this.displayUpdate('Connection lost. Please reconnect');\r\n\r\n // Workaround for peer.reconnect deleting previous id\r\n this.peer.id = this.lastPeerId;\r\n // eslint-disable-next-line no-underscore-dangle\r\n this.peer._lastServerId = this.lastPeerId;\r\n this.peer.reconnect();\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Callback method that cleans up after peer connection is closed\r\n *\r\n * @example\r\n */\r\n onPeerClose = () => {\r\n this.displayUpdate('Connection closed');\r\n this.conn = null;\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Helper method for when an error occurs\r\n *\r\n * @param {*} err\r\n * @example\r\n */\r\n onPeerError = err => {\r\n this.displayUpdate(err);\r\n console.log(`${err}`);\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Helper method that converts url paramters to an object\r\n *\r\n * @returns {object}\r\n * @example\r\n */\r\n parseURLSearchParams = () =>\r\n // SOURCE: chickens, https://stackoverflow.com/questions/8648892/how-to-convert-url-parameters-to-a-javascript-object\r\n // eslint-disable-next-line no-restricted-globals\r\n Object.fromEntries(new URLSearchParams(location.search));\r\n\r\n /** .\r\n * .\r\n * .\r\n * Helper method that converts an object to a query string\r\n *\r\n * @param {object} params\r\n * @returns {string}\r\n * @example\r\n */\r\n queryStringFromObject = params =>\r\n Object.keys(params)\r\n .map(key => `${key}=${params[key]}`)\r\n .join('&');\r\n\r\n static keypressFeedbackSound = pressFeedbackURI;\r\n}\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (AudioPeer);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/audioPeer.js?");
427
+ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var peerjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! peerjs */ \"./node_modules/peerjs/dist/peerjs.min.js\");\n/* harmony import */ var peerjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(peerjs__WEBPACK_IMPORTED_MODULE_0__);\n\r\n\r\n// TODO: this was already here before, but appears to be unused\r\nconst pressFeedbackURI =\r\n 'data:audio/mpeg;base64,//uQZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAALAAATlgAXFxcXFxcXFxcuLi4uLi4uLi5FRUVFRUVFRUVdXV1dXV1dXV10dHR0dHR0dHSLi4uLi4uLi4uioqKioqKioqK6urq6urq6urrR0dHR0dHR0dHo6Ojo6Ojo6Oj///////////8AAAA5TEFNRTMuMTAwAaoAAAAALgYAABSAJAZbTgAAgAAAE5YfafL/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//uQZAAAA0YVyhVvQAAAAA0goAABGfWdITn6gAgAADSDAAAAAEWjAwMwMDMFBzCQsw8PMPCwUDgkNMpNzXEoSUTP3s6nJPd4z28k62JNdIwIUHj3nvynRempMmLAo/tff9/3IchyHIch/IxY3SUmG86enD4Pg+fgmfEAIQQcsP+oH//E7/+Ud/1HP/B9AAABMCFFFAAAwDgCyMCVAgQcBQmARAHw0AOGAUgFJgUoL8YKsEvqzGA1APJQAIGBNgDpoBRvQYb6EIGhIkmJg1QA0aH0H4GDBgJ4G55UBpM1AGgUG0wAgOBIUAYJGoGFQ4AkHitxzRSocGMwDYYCwJAWAICgBD8jhwlEqBNsMiAkCBpQY2FxpG61opmucDLrjKi6Fmk5oK9PWVh1DNFM2IaRH/q8mTQgTF4sk0bnv//zEuqRMjYycuuj///5wxZzIvLSMTUxYyZL////86ZBqh4D+QUIABcwBQBLMCmAeTA4wJowO8E2DAeYwQ8CWMDLBHDB1QpIxscoSMwBQJj/WZBA3O4mFMHIAGzAKAVgwmcG8OIV//uSZCIN9VQ4wgd/gAAAAA0g4AABD+S/Di5+qgAAADSAAAAEEzcNTC4yM0m41SLDHAJLSggBKwtKRwb6+IBi4ctbepDskh2KmAgA16NTNrON66ptO40mNa9ayZHVx7zmGPHktZb7vP9xLn4fr+9jeO//8P+z39///9T/////t+d6vf1+c6fP9Hv5cxg4aA4TgkGIYmLbYHGAxaCjHwlM0lwBC4zGwzVG+MFnGoTY8sn0w1MSHA09vAM8ssDCSYAykIABmeCI4AKDMDIRfGbFAjWE8h+BfIEfBoFCTQJUcA5ZIrQDjzQ+gWzxsjDLtE4s46kxjHZZom2SXfyj6uadvNvb0ee/3dX//01YAVKw/FoW3hDrwUDTAwDMVigy8rTYaRNKug2tzzBwxnAx/DOuMhFECAOxWsDO6kAwkdQFH0BiwIgYlAwCgdAwiZBBI1kCC5JcWwCQWMQ/JQnkVFkOVN8oku8yDkjbMiry+2rrLvW/MvT53q/yv+n2///dywQL8DRgOgsrBBi0LGcngZrCZgYxGEAoZ+IplUdGJ1ifHVRh5v/7kmRMDPOhJ0MTn6qAAAANIAAAARDEiQhOf0pAAAA0gAAABAdCcEnCwmbqA1JhbIFwYKEAUGAXgOJo45oXAyjT0MinMgXM2UNoNGyYeLN0ENORMgQC5EYAJlr4Z3L3lgaHG5VO0lWX1q92J3t9sWM+bu9/fe8/VT/L+zq9v+zr9/+//8r71SAAAA9tq0AA1hzXXdxmzgPWzJyU20wh4EDDUSzWI4x4rgMGBd+IImDoAiEBAMCJn2HpqAlRpDIZhbxxp2ASQcGVRJG6RC4xmaZHiYlYPKGGdEGJjIoa4YtICXGHRhGJg2QMkYJADRGfCMTZE5+4ze1gMF1k163DfQrNgh83G3zIYoMdC4wEOwcrzMxMMam0AlYxkKzOgqMDhUuUBgYIQOWiEgwYHAogAwXBAYHAKAVVm0ZW2J1Wno9taaAzuOSF34AjMUjdBOy+pjbpKCil9TG/hOWRkUkxad2pAAAGFlrIADgyUqh1syPqzGQRoUAEDDoFgKMDw7MVA2NJ1sKHaMVghBwfGAgOgJR0migMTBUODDQezBI5jGNQzXD/+5JkjYD20jDN67/kngAADSAAAAEXjN0dTv9SAAAANIAAAASwgEb7HKvHZpiFAM0Bgs8wPYBNNi8MMfMIKRGRlOETOErM6wMGpBTQHTjJEQaKEBoKmlLXGizd5Ax5W2Byh0X6R9YRJ2rQFSKzgZDB0DQDKJHDr/MoZRDsaleN+vVhpoVqzczvZYx+Hdbx1/MuWOZb///Vr1YX93I/6P9KAWAQE8pFZWkOCuFAO0EEAThJ4OYwBQMHIJgUUVrHHRwaURUkZ4YX6MYvO6EDvpgTJY6aVeR7mGcgzBgfQE2YCuA5H9adJQKBCAhAqA53/aS/bk0T1zjIhpmcjVumpqS/ZZ1v6TuOXxF1+49x5d5Knl/Luvw7ua/8P/DdWT+dOkhD5zhvqb0db/93/5AQAQsF3glyO4MAysKti2BGAAdE0L31C4EMAhEAgAu28hgMOFHwEgaYACAFHpko0GM0ia2Yx0/wmKECIhpq5poYK2CTmAQAMhgAQBKYAoARFUAhUQbKhIMAxAFG3eFpLns4drJbaY9+pDVDPZ/QKtLHKNCpsTA6//uSZIEE9GAuRhNfzIAAAA0gAAABEnjLFK588sAAADSAAAAEdTXMSKxfop3DPM5RNbal/EvU7p6/Ie/t93Z1v6OqEAzmEmBoIQcGTCwGMCghPwvOQgUwEbKMZBgNAwOPZioUiMIl/ACXRGoREDB0clmTLApMiq4x2azRlmMM7NijivBEQxUIGvMGdAsjAxgHcDSxgRZANSYAOAgYs0FXAnwaIl43xAcuEVEogHIiFKRHEuREzUfFfSOoEgRyTk8Isema00Fl0gzqujqL/ZT3Krfoq7r1H/AvWzp/yXv/3f/oA0GjFwIZS19BgKAsiCDxuUBAMZ8D6zIZAIFMChweF7GFbQAITYoiSSSvMRBoUJ5l4RGVzOa2hhmAr6mbNSaYcYlxgqAvmAaCEYDAE6yBgAFIpAsGADyaXw+/MSnONGVBjhuNW+/dbYnEQqJJNwIgainmo0TB3Ofkus/yHs5P3dnW/+ryf+QqTEFNRTMuMTAwqqqqqqqqqqqqAABjBgrdYuwIwHSioNCCFkYbBZpMaoVDIRMDhB326ByJkJgYuGdC4P/7kmSwDPT4N0MLn6SAAAANIAAAARDIpRJOePLAAAA0gAAABDAGIA0YOGJhoVGKx+YbQxu2mmHbCT5rII6wYW2ASgYFJDgHYBAIpMARM6WcpEFALUjnWoXbkbwf8AGkx+2FugJGw/l2gIK+vverzfFet8Re/kur09f/f/u6f/1GySAhOMFigxOOnJAAdLIIqmTCCa9ahACTDANMqFMLAIQjQw0EVbjH4aOuN8OAgFCBn0sS0GpU0IAjUJ3MCoPaDTTB4AwnIE7MGrBCjAcgE836g5kUx6AtCKkjKElvKarxnFzLOlKRocalMtnabKM6hpYW5TSrdLe1Kop3e+ZWtymHt445fv9Vfyy/Hn5Xv///v1bXt4M9Z7+o729b+K/4b6pMQU1FMy4xMDCqqqqqqqqqqqoAArJ2QY8DbERAFjDyZMdBUwYDwIEDHduP9KsmPhhMKGHR0ZzTg0NTB4kGhkYqgZ2MZGQRUYNHoGXBgA4HWYEoBbGCNgvJhVgV8ZJaR2GsQJb5g5gRMYD+BQmAhADQNAVRoA4EQAOXUBwAkYBsAVr/+5Jk0w/0GynDE59coAAADSAAAAEULMkADn9SAAAANIAAAATsdabY4ta/VUMV5DuqzWuVs3pSSLmoKyJqFQGpUi+IAy2PdQm57ZU/m8oR6dDu/KvzehHpx5O/KkuvNN/o39SX9fblC3lusxd7wMr2zmhS+YLExsQBmRRQGKE6HITacxM2hgy8ATH50NVDsxSlQMPDL4bNJAg7HUAIBQcOjCRbMBtAdDAAACkwB4EWMCzCGTGll+U7EVMUMoPCSjDHgWcwaECqP+mza0I1QpATkY0Sm3lwsB0q0C3xd6GWuF4jEAeiqacWb5bdVxJbap8YzlnZWta3hLq34RaGf5hj3/pZ3HveY/3ku7/5a/7Wf//9/92aGoPcO9Z3nep/9H+mTEFNRTMuMTAwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqgBOZ2IMSwdMDATGQhDC4ZXKRj8wGMxub0k5717G//uSZPaO9axfvJOfPEAAAA0gAAABFsja3g5/cEAAADSAAAAELQSBSmZKFYVCYsIjBA1MCgYxWdDkBzMRAEwgQDIIBMgFIzWQTUjgPK3c02lpDWsiqM0Ih0w6QzjB4BzMDcD4wFgEzAfAeQQs8TcsNydp+n5wlq8UapFM2auMpwfZrv475ll25Y5ll3mtzMuwCWO8Ocqe/lndv+j/b1f6/9QATU2x0wCPIAYTCoUHAxhIYX2MXBDC24mvTCAedLotPVa09tEZwuBrSZmkoXXBgkY2SmmPBjQkpGrwfaYZQGhQDcPACJNPw90xLlijCVZWUifsophFk7ww7v7fGk6gE/vB+l0VNkSFwo0bYXJC6gyQQEiwvlDzbHAhHpZLIQbJ1UxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUASWNHVvyNdkdcuCnNLhmA8HuRIHbo/1AhfJ9JZVctla8gMQwpDT96eCGcDAGg8qCCIBce3D8P35RGMZXL8gcmxBByacE9hDD09hNohydtFshlp7EeIe9aMiMe/P/7kmTNjPTPJLaLvPDwAAANIAAAAQ/obuBt+FJAAAA0gAAABEchD3bEIchgekEBmZYRmyPAM3j4DJ8fhgfmeIjtD4HTwPAiPgNGB+BAAjtCABG8AwMvgwAEo5cSIfzt69YYDMdo9RxSsKtgIcom1PMylIK9rWkMkKzctAIIkqXCTqLYAoUrBCJrAlHzJipaMuaPvWraLnsMj6ExUtGUZ0ZRnJ7Q6PrnS7VrsC55kSlRyTYjonPkkybMT2AyVMrbMrYly661bq13Fz0K2JlbEdH1zk9ocnsB09CcutLYmj71p7Q6PWDI+hMXWjJ06Mozk9odH0BkfQmLrRlGdE6M5JrhKJzZKPoSSephKVHJlGcmLhkZXJJ9CYnrRkqSmMZybKpMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqr/+5Jk7QT0dTc4kxw0ogAADSAAAAEZOaLm5+WQSAAANIAAAASqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqglFJEIRoPjA2MDYyViqViCJxDHghjyPQ4ioUiYKw4EMzYZXAooDEE1y2zRpTu00acWUWWcacaUWYeWcacJAhYgWJFCRQGIFiBZZRZRZlw7s7PG////s7M7Ozs7M5xpRZR5RRpxZRZh5RRZRbRC1NP///9PKqqq4NNNNRKqJXTTTTVVVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uSZIIP9BFGHYksMlIAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ==';\r\n\r\n/**\r\n * @typedef initParameters - Parameters for initializing the AudioPeer\r\n * @type {object}\r\n * @property {string} targetElementId - Target element where new elements will be appended.\r\n * @property {string} siteUrl: The url of the current site.\r\n */\r\nconst initParameters = {\r\n targetElementId: null,\r\n siteUrl: null,\r\n};\r\n\r\n/**\r\n * @class The first layer of abstraction on the PeerJS library.\r\n * It meant to be extended by the two seperate client classes, Speaker and Listener.\r\n * It implements the shared methods and properties of both classes.\r\n */\r\nclass AudioPeer {\r\n /**\r\n * Creates an instance of AudioPeer\r\n * Takes the url of the current site and a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @param param\r\n * @example\r\n */\r\n constructor(param = initParameters) {\r\n // PeerJS\r\n /* Create the Peer object for our end of the connection. */\r\n this.peer = new (peerjs__WEBPACK_IMPORTED_MODULE_0___default())({\r\n secure: true,\r\n host: 'easyeyes-peer-server.herokuapp.com',\r\n port: 443,\r\n config: {\r\n iceServers: [\r\n {\r\n urls: 'stun:stun.relay.metered.ca:80',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:80',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:80?transport=tcp',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:443',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turns:global.relay.metered.ca:443?transport=tcp',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n ],\r\n },\r\n });\r\n this.conn = null;\r\n this.lastPeerId = null;\r\n\r\n // Display information to HTML elem with given id\r\n this.targetElement = param.targetElementId;\r\n\r\n this.siteUrl = param.siteUrl;\r\n this.debug = false;\r\n // Store for all incoming data\r\n this.dataStore = [];\r\n\r\n // Create and play sounds using this audio context\r\n this.sourceAudioContext = new (window.AudioContext ||\r\n window.webkitAudioContext ||\r\n window.audioContext)();\r\n }\r\n\r\n /** .\r\n * .\r\n * .\r\n * Helper method to display information to DOM element\r\n *\r\n * @param {string} message\r\n * @param {boolean} append\r\n * @example\r\n */\r\n displayUpdate = (message, append = true) => {\r\n // If the specified elem exists, update that elem\r\n if (document.getElementById(this.targetElement)) {\r\n const displayElement = document.getElementById(this.targetElement);\r\n if (append) {\r\n displayElement.innerText += `\\n${message}`;\r\n } else {\r\n displayElement.innerText = message;\r\n }\r\n } else {\r\n console.log('MESSAGE: ', message);\r\n }\r\n };\r\n\r\n /**\r\n * Callback method for when a peer connection is lost\r\n * saves the last peer id, last server id, and attempts to reconnect.\r\n *\r\n * @example\r\n */\r\n onPeerDisconnected = () => {\r\n this.displayUpdate('Connection lost. Please reconnect');\r\n\r\n // Workaround for peer.reconnect deleting previous id\r\n try {\r\n this.peer.id = this.lastPeerId;\r\n // eslint-disable-next-line no-underscore-dangle\r\n this.peer._lastServerId = this.lastPeerId;\r\n this.peer.reconnect();\r\n } catch(e) {\r\n console.log(e);\r\n }\r\n \r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Callback method that cleans up after peer connection is closed\r\n *\r\n * @example\r\n */\r\n onPeerClose = () => {\r\n this.displayUpdate('Connection closed');\r\n this.conn = null;\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Helper method for when an error occurs\r\n *\r\n * @param {*} err\r\n * @example\r\n */\r\n onPeerError = err => {\r\n this.displayUpdate(err);\r\n console.log(`${err}`);\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Helper method that converts url paramters to an object\r\n *\r\n * @returns {object}\r\n * @example\r\n */\r\n parseURLSearchParams = () =>\r\n // SOURCE: chickens, https://stackoverflow.com/questions/8648892/how-to-convert-url-parameters-to-a-javascript-object\r\n // eslint-disable-next-line no-restricted-globals\r\n Object.fromEntries(new URLSearchParams(location.search));\r\n\r\n /** .\r\n * .\r\n * .\r\n * Helper method that converts an object to a query string\r\n *\r\n * @param {object} params\r\n * @returns {string}\r\n * @example\r\n */\r\n queryStringFromObject = params =>\r\n Object.keys(params)\r\n .map(key => `${key}=${params[key]}`)\r\n .join('&');\r\n\r\n static keypressFeedbackSound = pressFeedbackURI;\r\n}\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (AudioPeer);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/audioPeer.js?");
428
428
 
429
429
  /***/ }),
430
430
 
@@ -435,7 +435,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var peer
435
435
  /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
436
436
 
437
437
  "use strict";
438
- eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _audioPeer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./audioPeer */ \"./src/peer-connection/audioPeer.js\");\n/* harmony import */ var _peerErrors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./peerErrors */ \"./src/peer-connection/peerErrors.js\");\n\r\n\r\n\r\n\r\n/**\r\n * @class Handles the listener's side of the connection. Responsible for getting access to user's microphone,\r\n * and initiating a call to the Speaker.\r\n * @augments AudioPeer\r\n */\r\nclass Listener extends _audioPeer__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\r\n /**\r\n * Takes a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @example\r\n */\r\n constructor(params) {\r\n super(params);\r\n this.microphoneFromAPI = params.microphoneFromAPI ? params.microphoneFromAPI : '';\r\n this.microphoneDeviceId = params.microphoneDeviceId ? params.microphoneDeviceId : '';\r\n // this.deviceInfoFromUser = params.deviceInfoFromUser\r\n // ? params.deviceInfoFromUser\r\n // : {modelNumber: '', modelName: ''};\r\n this.startTime = Date.now();\r\n this.receiverPeerId = null;\r\n\r\n const urlParameters = this.parseURLSearchParams();\r\n this.calibrateSoundHz =\r\n // previous calibrateSoundHz\r\n urlParameters.hz !== null && urlParameters.hz !== undefined ? urlParameters.hz : 48000;\r\n this.calibrateSoundSamplingDesiredBits =\r\n // previous calibrateSoundSamplingDesiredBits\r\n urlParameters.bits !== null && urlParameters.bits !== undefined ? urlParameters.bits : 24;\r\n this.speakerPeerId = urlParameters.speakerPeerId;\r\n\r\n this.peer.on('open', this.onPeerOpen);\r\n this.peer.on('connection', this.onPeerConnection);\r\n this.peer.on('disconnected', this.onPeerDisconnected);\r\n this.peer.on('close', this.onPeerClose);\r\n this.peer.on('error', this.onPeerError);\r\n }\r\n\r\n onPeerOpen = id => {\r\n this.displayUpdate('Listener - onPeerOpen');\r\n // Workaround for peer.reconnect deleting previous id\r\n\r\n if (id === null) {\r\n this.displayUpdate('Received null id from peer open');\r\n this.peer.id = this.lastPeerId;\r\n } else {\r\n this.lastPeerId = this.peer.id;\r\n }\r\n\r\n this.join();\r\n };\r\n\r\n onPeerConnection = connection => {\r\n this.displayUpdate('Listener - onPeerConnection');\r\n // Disallow incoming connections\r\n connection.on('open', () => {\r\n connection.send('Sender does not accept incoming connections');\r\n setTimeout(() => {\r\n connection.close();\r\n }, 500);\r\n });\r\n };\r\n\r\n onConnData = data => {\r\n this.displayUpdate('Listener - onConnData');\r\n const hasSpeakerID = Object.prototype.hasOwnProperty.call(data, 'speakerPeerId');\r\n if (!hasSpeakerID) {\r\n this.displayUpdate('Error in parsing data received! Must set \"speakerPeerId\" property');\r\n throw new _peerErrors__WEBPACK_IMPORTED_MODULE_1__.MissingSpeakerIdError('Must set \"speakerPeerId\" property');\r\n } else {\r\n // this.conn.close();\r\n this.displayUpdate(this.speakerPeerId);\r\n this.speakerPeerId = data.speakerPeerId;\r\n const newParams = {\r\n speakerPeerId: this.speakerPeerId,\r\n };\r\n /*\r\n FUTURE does this limit usable environments?\r\n ie does this work if internet is lost after initial page load?\r\n */\r\n window.location.search = this.queryStringFromObject(newParams); // Redirect to correctly constructed keypad page\r\n }\r\n };\r\n\r\n join = async () => {\r\n this.displayUpdate('Listener - join');\r\n /**\r\n * Create the connection between the two Peers.\r\n *\r\n * Sets up callbacks that handle any events related to the\r\n * connection and data received on it.\r\n */\r\n // Close old connection\r\n if (this.conn) {\r\n this.displayUpdate('Closing old connection');\r\n this.conn.close();\r\n }\r\n\r\n // Create connection to destination peer specified by the query param\r\n this.displayUpdate(`Creating connection to: ${this.speakerPeerId}`);\r\n this.conn = this.peer.connect(this.speakerPeerId, {\r\n reliable: true,\r\n });\r\n\r\n this.displayUpdate('Created connection');\r\n this.conn.on('open', async () => {\r\n this.displayUpdate('Listener - conn open');\r\n await this.getDeviceInfo();\r\n // this.sendSamplingRate();\r\n await this.openAudioStream();\r\n });\r\n\r\n // Handle incoming data (messages only since this is the signal sender)\r\n this.conn.on('data', this.onConnData);\r\n this.conn.on('close', () => {\r\n console.log('Connection closed');\r\n });\r\n };\r\n\r\n getMobileOS = () => {\r\n const ua = navigator.userAgent;\r\n if (/android/i.test(ua)) {\r\n return 'Android';\r\n }\r\n if (\r\n /iPad|iPhone|iPod/.test(ua) ||\r\n ((navigator?.userAgentData?.platform || navigator?.platform) === 'MacIntel' &&\r\n navigator.maxTouchPoints > 1)\r\n ) {\r\n return 'iOS';\r\n }\r\n return 'Other';\r\n };\r\n\r\n sendSamplingRate = sampleRate => {\r\n this.displayUpdate('Listener - sendSamplingRate');\r\n this.conn.send({\r\n name: 'samplingRate',\r\n payload: sampleRate,\r\n });\r\n };\r\n\r\n sendSampleSize = sampleSize => {\r\n this.displayUpdate('Listener - sendSampleSize');\r\n this.conn.send({\r\n name: 'sampleSize',\r\n payload: sampleSize,\r\n });\r\n };\r\n\r\n sendFlags = flags => {\r\n this.displayUpdate('Listener - sendFlags');\r\n this.conn.send({\r\n name: 'flags',\r\n payload: flags,\r\n });\r\n };\r\n\r\n getDeviceInfo = async () => {\r\n try {\r\n const deviceInfo = {};\r\n fod.complete(function (data) {\r\n deviceInfo['IsMobile'] = data.device['ismobile'];\r\n deviceInfo['HardwareName'] = data.device['hardwarename'];\r\n deviceInfo['HardwareFamily'] = data.device['hardwarefamily'];\r\n deviceInfo['HardwareModel'] = data.device['hardwaremodel'];\r\n deviceInfo['OEM'] = data.device['oem'];\r\n deviceInfo['HardwareModelVariants'] = data.device['hardwaremodelvariants'];\r\n deviceInfo['DeviceId'] = data.device['deviceid'];\r\n deviceInfo['PlatformName'] = data.device['platformname'];\r\n deviceInfo['PlatformVersion'] = data.device['platformversion'];\r\n deviceInfo['DeviceType'] = data.device['devicetype'];\r\n // deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\r\n });\r\n // deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\r\n deviceInfo['microphoneFromAPI'] = this.microphoneFromAPI;\r\n deviceInfo['microphoneDeviceId'] = this.microphoneDeviceId;\r\n deviceInfo['screenWidth'] = window.screen.width;\r\n deviceInfo['screenHeight'] = window.screen.height;\r\n console.log('deviceInfo Inside getDeviceInfo: ', deviceInfo);\r\n this.conn.send({\r\n name: 'deviceInfo',\r\n payload: deviceInfo,\r\n });\r\n return deviceInfo;\r\n } catch (error) {\r\n console.error('Error fetching or executing script:', error.message);\r\n return null;\r\n }\r\n };\r\n\r\n applyHQTrackConstraints = async stream => {\r\n // Contraint the incoming audio to the sampling rate we want\r\n stream.getAudioTracks().forEach(track => {\r\n console.log(track, track.enabled);\r\n });\r\n const track = stream.getAudioTracks()[0];\r\n console.log(track);\r\n const capabilities = track.getCapabilities();\r\n\r\n this.displayUpdate(\r\n `Listener Track Capabilities - ${JSON.stringify(capabilities, undefined, 2)}`\r\n );\r\n\r\n const constraints = track.getConstraints();\r\n\r\n if (capabilities.echoCancellation) {\r\n constraints.echoCancellation = false;\r\n }\r\n\r\n if (capabilities.sampleRate) {\r\n constraints.sampleRate = this.calibrateSoundHz;\r\n }\r\n\r\n if (capabilities.sampleSize) {\r\n constraints.sampleSize = this.calibrateSoundSamplingDesiredBits;\r\n }\r\n\r\n if (capabilities.channelCount) {\r\n constraints.channelCount = 1;\r\n }\r\n\r\n this.displayUpdate(`Listener Track Constraints - ${JSON.stringify(constraints, undefined, 2)}`);\r\n\r\n // await the promise\r\n try {\r\n await track.applyConstraints(constraints);\r\n } catch (err) {\r\n console.error(err);\r\n this.displayUpdate(`Error applying constraints to track: ${err}`);\r\n }\r\n\r\n const settings = track.getSettings();\r\n this.displayUpdate(`Listener Track Settings - ${JSON.stringify(settings, undefined, 2)}`);\r\n return settings;\r\n };\r\n\r\n getMediaDevicesAudioContraints = async () => {\r\n const availableConstraints = navigator.mediaDevices.getSupportedConstraints();\r\n\r\n const contraints = {\r\n // ...(availableConstraints.echoCancellation && availableConstraints.echoCancellation == true\r\n // ? {echoCancellation: {exact: false}}\r\n // : {}),\r\n // ...(availableConstraints.sampleRate && availableConstraints.sampleRate == true\r\n // ? {sampleRate: {ideal: this.calibrateSoundHz}}\r\n // : {}),\r\n // ...(availableConstraints.sampleSize && availableConstraints.sampleSize == true\r\n // ? {sampleSize: {ideal: this.calibrateSoundSamplingDesiredBits}}\r\n // : {}),\r\n // ...(availableConstraints.channelCount && availableConstraints.channelCount == true\r\n // ? {channelCount: {exact: 1}}\r\n // : {}),\r\n echoCancellation: false,\r\n channelCount: 1,\r\n };\r\n\r\n if (this.microphoneDeviceId !== '') {\r\n contraints.deviceId = {exact: await this.getDeviceIdByLabel(this.microphoneDeviceId)};\r\n }\r\n\r\n console.log(contraints);\r\n\r\n return contraints;\r\n };\r\n getDeviceIdByLabel = async targetLabel => {\r\n try {\r\n //get permission to use audio first. (Returns empty labels on some computers if not done first)\r\n await navigator.mediaDevices.getUserMedia({audio: true});\r\n // Enumerate available media devices\r\n const devices = await navigator.mediaDevices.enumerateDevices();\r\n\r\n // Find the device with the matching label\r\n const matchingDevice = devices.find(\r\n device => device.kind === 'audioinput' && device.label === targetLabel\r\n );\r\n\r\n if (matchingDevice) {\r\n return matchingDevice.deviceId; // Return the deviceId if found\r\n } else {\r\n throw new Error(`No audio input device found with label: \"${targetLabel}\"`);\r\n }\r\n } catch (error) {\r\n console.error('Error finding device ID:', error);\r\n return null;\r\n }\r\n };\r\n\r\n openAudioStream = async () => {\r\n this.displayUpdate('Listener - openAudioStream');\r\n const mobileOS = this.getMobileOS();\r\n if (false) {}\r\n const constraints = await this.getMediaDevicesAudioContraints();\r\n console.log('Constraints right before getUserMedia:', constraints);\r\n navigator.mediaDevices\r\n .getUserMedia({\r\n audio: constraints,\r\n video: false,\r\n //audio: {echoCancellation: false, noiseSuppression: false, autoGainControl: false, deviceId: {exact: await this.getDeviceIdByLabel(this.microphoneDeviceId) }},\r\n })\r\n .then(stream => {\r\n this.displayUpdate(\r\n `Listener Track settings before applied constraints - ${JSON.stringify(\r\n stream.getAudioTracks()[0].getSettings(),\r\n undefined,\r\n 2\r\n )}`\r\n );\r\n this.applyHQTrackConstraints(stream)\r\n .then(settings => {\r\n console.log(settings);\r\n this.sendSamplingRate(settings.sampleRate);\r\n let sampleSize = settings.sampleSize;\r\n if (!sampleSize) {\r\n sampleSize = this.calibrateSoundSamplingDesiredBits;\r\n }\r\n this.sendSampleSize(sampleSize);\r\n this.sendFlags({\r\n autoGainControl: settings.autoGainControl,\r\n noiseSuppression: settings.noiseSuppression,\r\n echoCancellation: settings.echoCancellation,\r\n });\r\n this.peer.call(this.speakerPeerId, stream); // one-way call\r\n this.displayUpdate('Listener - openAudioStream');\r\n })\r\n .catch(err => {\r\n console.log(err);\r\n this.displayUpdate(\r\n `Listener - Error in applyHQTrackConstraints - ${JSON.stringify(err, undefined, 2)}`\r\n );\r\n });\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n if (err.name === 'OverconstrainedError') {\r\n const constraint = err.constraint;\r\n const message = `The constraint \"${constraint}\" cannot be satisfied by the selected microphone. Please adjust your calibration settings or choose a different microphone.`;\r\n\r\n this.displayUpdate(`Listener - OverconstrainedError: ${message}`);\r\n console.error(message);\r\n\r\n alert(`Overconstrained Error: ${message}`);\r\n }\r\n this.displayUpdate(\r\n `Listener - Error in getUserMedia - ${JSON.stringify(err, undefined, 2)}`\r\n );\r\n });\r\n };\r\n}\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Listener);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/listener.js?");
438
+ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _audioPeer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./audioPeer */ \"./src/peer-connection/audioPeer.js\");\n/* harmony import */ var _peerErrors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./peerErrors */ \"./src/peer-connection/peerErrors.js\");\n\r\n\r\n\r\n\r\n/**\r\n * @class Handles the listener's side of the connection. Responsible for getting access to user's microphone,\r\n * and initiating a call to the Speaker.\r\n * @augments AudioPeer\r\n */\r\nclass Listener extends _audioPeer__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\r\n /**\r\n * Takes a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @example\r\n */\r\n constructor(params) {\r\n super(params);\r\n this.microphoneFromAPI = params.microphoneFromAPI ? params.microphoneFromAPI : '';\r\n this.microphoneDeviceId = params.microphoneDeviceId ? params.microphoneDeviceId : '';\r\n // this.deviceInfoFromUser = params.deviceInfoFromUser\r\n // ? params.deviceInfoFromUser\r\n // : {modelNumber: '', modelName: ''};\r\n this.startTime = Date.now();\r\n this.receiverPeerId = null;\r\n\r\n const urlParameters = this.parseURLSearchParams();\r\n this.calibrateSoundHz =\r\n // previous calibrateSoundHz\r\n urlParameters.hz !== null && urlParameters.hz !== undefined ? urlParameters.hz : 48000;\r\n this.calibrateSoundSamplingDesiredBits =\r\n // previous calibrateSoundSamplingDesiredBits\r\n urlParameters.bits !== null && urlParameters.bits !== undefined ? urlParameters.bits : 24;\r\n this.speakerPeerId = urlParameters.speakerPeerId;\r\n\r\n this.peer.on('open', this.onPeerOpen);\r\n this.peer.on('connection', this.onPeerConnection);\r\n this.peer.on('disconnected', this.onPeerDisconnected);\r\n this.peer.on('close', this.onPeerClose);\r\n this.peer.on('error', this.onPeerError);\r\n }\r\n\r\n onPeerOpen = id => {\r\n this.displayUpdate('Listener - onPeerOpen');\r\n // Workaround for peer.reconnect deleting previous id\r\n\r\n if (id === null) {\r\n this.displayUpdate('Received null id from peer open');\r\n this.peer.id = this.lastPeerId;\r\n } else {\r\n this.lastPeerId = this.peer.id;\r\n }\r\n\r\n this.join();\r\n };\r\n\r\n onPeerConnection = connection => {\r\n this.displayUpdate('Listener - onPeerConnection');\r\n // Disallow incoming connections\r\n connection.on('open', () => {\r\n connection.send('Sender does not accept incoming connections');\r\n setTimeout(() => {\r\n connection.close();\r\n }, 500);\r\n });\r\n };\r\n\r\n onConnData = data => {\r\n this.displayUpdate('Listener - onConnData');\r\n const hasSpeakerID = Object.prototype.hasOwnProperty.call(data, 'speakerPeerId');\r\n if (!hasSpeakerID) {\r\n this.displayUpdate('Error in parsing data received! Must set \"speakerPeerId\" property');\r\n throw new _peerErrors__WEBPACK_IMPORTED_MODULE_1__.MissingSpeakerIdError('Must set \"speakerPeerId\" property');\r\n } else {\r\n // this.conn.close();\r\n this.displayUpdate(this.speakerPeerId);\r\n this.speakerPeerId = data.speakerPeerId;\r\n const newParams = {\r\n speakerPeerId: this.speakerPeerId,\r\n };\r\n /*\r\n FUTURE does this limit usable environments?\r\n ie does this work if internet is lost after initial page load?\r\n */\r\n window.location.search = this.queryStringFromObject(newParams); // Redirect to correctly constructed keypad page\r\n }\r\n };\r\n\r\n join = async () => {\r\n this.displayUpdate('Listener - join');\r\n /**\r\n * Create the connection between the two Peers.\r\n *\r\n * Sets up callbacks that handle any events related to the\r\n * connection and data received on it.\r\n */\r\n // Close old connection\r\n if (this.conn) {\r\n this.displayUpdate('Closing old connection');\r\n this.conn.close();\r\n }\r\n\r\n // Create connection to destination peer specified by the query param\r\n this.displayUpdate(`Creating connection to: ${this.speakerPeerId}`);\r\n this.conn = this.peer.connect(this.speakerPeerId, {\r\n reliable: true,\r\n });\r\n\r\n this.displayUpdate('Created connection');\r\n this.conn.on('open', async () => {\r\n this.displayUpdate('Listener - conn open');\r\n await this.getDeviceInfo();\r\n // this.sendSamplingRate();\r\n await this.openAudioStream();\r\n });\r\n\r\n // Handle incoming data (messages only since this is the signal sender)\r\n this.conn.on('data', this.onConnData);\r\n this.conn.on('close', () => {\r\n console.log('Connection closed');\r\n });\r\n };\r\n\r\n getMobileOS = () => {\r\n const ua = navigator.userAgent;\r\n if (/android/i.test(ua)) {\r\n return 'Android';\r\n }\r\n if (\r\n /iPad|iPhone|iPod/.test(ua) ||\r\n ((navigator?.userAgentData?.platform || navigator?.platform) === 'MacIntel' &&\r\n navigator.maxTouchPoints > 1)\r\n ) {\r\n return 'iOS';\r\n }\r\n return 'Other';\r\n };\r\n\r\n sendSamplingRate = sampleRate => {\r\n this.displayUpdate('Listener - sendSamplingRate');\r\n this.conn.send({\r\n name: 'samplingRate',\r\n payload: sampleRate,\r\n });\r\n };\r\n\r\n sendSampleSize = sampleSize => {\r\n this.displayUpdate('Listener - sendSampleSize');\r\n this.conn.send({\r\n name: 'sampleSize',\r\n payload: sampleSize,\r\n });\r\n };\r\n\r\n sendFlags = flags => {\r\n this.displayUpdate('Listener - sendFlags');\r\n this.conn.send({\r\n name: 'flags',\r\n payload: flags,\r\n });\r\n };\r\n\r\n getDeviceInfo = async () => {\r\n try {\r\n const deviceInfo = {};\r\n fod.complete(function (data) {\r\n deviceInfo['IsMobile'] = data.device['ismobile'];\r\n deviceInfo['HardwareName'] = data.device['hardwarename'];\r\n deviceInfo['HardwareFamily'] = data.device['hardwarefamily'];\r\n deviceInfo['HardwareModel'] = data.device['hardwaremodel'];\r\n deviceInfo['OEM'] = data.device['oem'];\r\n deviceInfo['HardwareModelVariants'] = data.device['hardwaremodelvariants'];\r\n deviceInfo['DeviceId'] = data.device['deviceid'];\r\n deviceInfo['PlatformName'] = data.device['platformname'];\r\n deviceInfo['PlatformVersion'] = data.device['platformversion'];\r\n deviceInfo['DeviceType'] = data.device['devicetype'];\r\n // deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\r\n });\r\n // deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\r\n deviceInfo['microphoneFromAPI'] = this.microphoneFromAPI;\r\n deviceInfo['microphoneDeviceId'] = this.microphoneDeviceId;\r\n deviceInfo['screenWidth'] = window.screen.width;\r\n deviceInfo['screenHeight'] = window.screen.height;\r\n console.log('deviceInfo Inside getDeviceInfo: ', deviceInfo);\r\n this.conn.send({\r\n name: 'deviceInfo',\r\n payload: deviceInfo,\r\n });\r\n return deviceInfo;\r\n } catch (error) {\r\n console.error('Error fetching or executing script:', error.message);\r\n return null;\r\n }\r\n };\r\n\r\n applyHQTrackConstraints = async stream => {\r\n // Contraint the incoming audio to the sampling rate we want\r\n stream.getAudioTracks().forEach(track => {\r\n console.log(track, track.enabled);\r\n });\r\n const track = stream.getAudioTracks()[0];\r\n console.log(track);\r\n const capabilities = track.getCapabilities();\r\n\r\n this.displayUpdate(\r\n `Listener Track Capabilities - ${JSON.stringify(capabilities, undefined, 2)}`\r\n );\r\n\r\n const constraints = track.getConstraints();\r\n\r\n if (capabilities.echoCancellation) {\r\n constraints.echoCancellation = false;\r\n }\r\n\r\n if (capabilities.sampleRate) {\r\n constraints.sampleRate = this.calibrateSoundHz;\r\n }\r\n\r\n if (capabilities.sampleSize) {\r\n constraints.sampleSize = this.calibrateSoundSamplingDesiredBits;\r\n }\r\n\r\n if (capabilities.channelCount) {\r\n constraints.channelCount = 1;\r\n }\r\n\r\n this.displayUpdate(`Listener Track Constraints - ${JSON.stringify(constraints, undefined, 2)}`);\r\n\r\n // await the promise\r\n try {\r\n await track.applyConstraints(constraints);\r\n } catch (err) {\r\n console.error(err);\r\n this.displayUpdate(`Error applying constraints to track: ${err}`);\r\n }\r\n\r\n const settings = track.getSettings();\r\n this.displayUpdate(`Listener Track Settings - ${JSON.stringify(settings, undefined, 2)}`);\r\n return settings;\r\n };\r\n\r\n getMediaDevicesAudioContraints = async () => {\r\n const availableConstraints = navigator.mediaDevices.getSupportedConstraints();\r\n\r\n const contraints = {\r\n // ...(availableConstraints.echoCancellation && availableConstraints.echoCancellation == true\r\n // ? {echoCancellation: {exact: false}}\r\n // : {}),\r\n // ...(availableConstraints.sampleRate && availableConstraints.sampleRate == true\r\n // ? {sampleRate: {ideal: this.calibrateSoundHz}}\r\n // : {}),\r\n // ...(availableConstraints.sampleSize && availableConstraints.sampleSize == true\r\n // ? {sampleSize: {ideal: this.calibrateSoundSamplingDesiredBits}}\r\n // : {}),\r\n // ...(availableConstraints.channelCount && availableConstraints.channelCount == true\r\n // ? {channelCount: {exact: 1}}\r\n // : {}),\r\n autoGainControl: false,\r\n noiseSuppression: false,\r\n echoCancellation: false,\r\n channelCount: 1,\r\n };\r\n\r\n if (this.microphoneDeviceId !== '') {\r\n contraints.deviceId = {exact: await this.getDeviceIdByLabel(this.microphoneDeviceId)};\r\n }\r\n\r\n console.log(contraints);\r\n\r\n return contraints;\r\n };\r\n getDeviceIdByLabel = async targetLabel => {\r\n try {\r\n //get permission to use audio first. (Returns empty labels on some computers if not done first)\r\n await navigator.mediaDevices.getUserMedia({audio: true});\r\n // Enumerate available media devices\r\n const devices = await navigator.mediaDevices.enumerateDevices();\r\n\r\n // Find the device with the matching label\r\n const matchingDevice = devices.find(\r\n device => device.kind === 'audioinput' && device.label === targetLabel\r\n );\r\n\r\n if (matchingDevice) {\r\n return matchingDevice.deviceId; // Return the deviceId if found\r\n } else {\r\n throw new Error(`No audio input device found with label: \"${targetLabel}\"`);\r\n }\r\n } catch (error) {\r\n console.error('Error finding device ID:', error);\r\n return null;\r\n }\r\n };\r\n\r\n openAudioStream = async () => {\r\n this.displayUpdate('Listener - openAudioStream');\r\n const mobileOS = this.getMobileOS();\r\n if (false) {}\r\n const constraints = await this.getMediaDevicesAudioContraints();\r\n console.log('Constraints right before getUserMedia:', constraints);\r\n navigator.mediaDevices\r\n .getUserMedia({\r\n audio: constraints,\r\n video: false,\r\n //audio: {echoCancellation: false, noiseSuppression: false, autoGainControl: false, deviceId: {exact: await this.getDeviceIdByLabel(this.microphoneDeviceId) }},\r\n })\r\n .then(stream => {\r\n this.displayUpdate(\r\n `Listener Track settings before applied constraints - ${JSON.stringify(\r\n stream.getAudioTracks()[0].getSettings(),\r\n undefined,\r\n 2\r\n )}`\r\n );\r\n this.applyHQTrackConstraints(stream)\r\n .then(settings => {\r\n console.log(settings);\r\n this.sendSamplingRate(settings.sampleRate);\r\n let sampleSize = settings.sampleSize;\r\n if (!sampleSize) {\r\n sampleSize = this.calibrateSoundSamplingDesiredBits;\r\n }\r\n this.sendSampleSize(sampleSize);\r\n this.sendFlags({\r\n autoGainControl: settings.autoGainControl,\r\n noiseSuppression: settings.noiseSuppression,\r\n echoCancellation: settings.echoCancellation,\r\n });\r\n this.peer.call(this.speakerPeerId, stream); // one-way call\r\n this.displayUpdate('Listener - openAudioStream');\r\n })\r\n .catch(err => {\r\n console.log(err);\r\n this.displayUpdate(\r\n `Listener - Error in applyHQTrackConstraints - ${JSON.stringify(err, undefined, 2)}`\r\n );\r\n });\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n if (err.name === 'OverconstrainedError') {\r\n const constraint = err.constraint;\r\n const message = `The constraint \"${constraint}\" cannot be satisfied by the selected microphone. Please adjust your calibration settings or choose a different microphone.`;\r\n\r\n this.displayUpdate(`Listener - OverconstrainedError: ${message}`);\r\n console.error(message);\r\n\r\n alert(`Overconstrained Error: ${message}`);\r\n }\r\n this.displayUpdate(\r\n `Listener - Error in getUserMedia - ${JSON.stringify(err, undefined, 2)}`\r\n );\r\n });\r\n };\r\n}\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Listener);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/listener.js?");
439
439
 
440
440
  /***/ }),
441
441
 
@@ -457,7 +457,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac
457
457
  /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
458
458
 
459
459
  "use strict";
460
- eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var qrcode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! qrcode */ \"./node_modules/qrcode/lib/browser.js\");\n/* harmony import */ var _audioPeer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./audioPeer */ \"./src/peer-connection/audioPeer.js\");\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ \"./src/utils.js\");\n/* harmony import */ var _peerErrors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./peerErrors */ \"./src/peer-connection/peerErrors.js\");\n\r\n\r\n\r\n\r\n\r\n//import {phrases} from '../../dist/example/i18n';\r\n\r\n/**\r\n * @class Handles the speaker's side of the connection. Responsible for initiating the connection,\r\n * rendering the QRCode, and answering the call.\r\n * @augments AudioPeer\r\n */\r\nclass Speaker extends _audioPeer__WEBPACK_IMPORTED_MODULE_1__[\"default\"] {\r\n /**\r\n * Takes the url of the current site and a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.\r\n * @param CalibratorInstance\r\n * @example\r\n */\r\n constructor(params, CalibratorInstance) {\r\n super(params);\r\n this.language = params?.language ?? 'en-US';\r\n this.siteUrl += '/listener?';\r\n this.ac = CalibratorInstance;\r\n this.result = null;\r\n this.debug = params?.debug ?? false;\r\n this.isSmartPhone = params?.isSmartPhone ?? false;\r\n this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;\r\n this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;\r\n this.instructionDisplayId = params?.instructionDisplayId ?? '';\r\n this.soundSubtitleId = params?.soundSubtitleId ?? '';\r\n this.timeToCalibrateDisplay = params?.timeToCalibrateId ?? '';\r\n this.soundMessageId = params?.soundMessageId ?? '';\r\n this.titleDisplayId = params?.titleDisplayId ?? '';\r\n this.timeToCalibrate = params?.timeToCalibrate ?? 10;\r\n this.isParticipant = params?.isParticipant ?? false;\r\n this.isLoudspeakerCalibration = params?.isLoudspeakerCalibration ?? false;\r\n this.deviceId = params?.micrpohoneIdFromWebAudioApi ?? '';\r\n this.buttonsContainer = params?.buttonsContainer ?? document.createElement('div');\r\n this.phrases = params?. phrases ?? {};\r\n\r\n /* Set up callbacks that handle any events related to our peer object. */\r\n }\r\n\r\n uri = '';\r\n qrImage;\r\n shortURL;\r\n\r\n initPeer = async () => {\r\n const id = await this.generateTimeBasedPeerID();\r\n this.peer = new Peer(id, {\r\n secure: true,\r\n host: 'easyeyes-peer-server.herokuapp.com',\r\n port: 443,\r\n config: {\r\n iceServers: [\r\n {\r\n urls: 'stun:stun.relay.metered.ca:80',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:80',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:80?transport=tcp',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:443',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turns:global.relay.metered.ca:443?transport=tcp',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n ],\r\n },\r\n });\r\n this.peer.on('open', this.#onPeerOpen);\r\n this.peer.on('connection', this.#onPeerConnection);\r\n this.peer.on('close', this.onPeerClose);\r\n this.peer.on('disconnected', this.#onPeerDisconnected);\r\n this.peer.on('error', this.#onPeerError);\r\n };\r\n generateTimeBasedPeerID = async () => {\r\n const now = new Date().getTime();\r\n const randomBuffer = new Uint8Array(10);\r\n crypto.getRandomValues(randomBuffer);\r\n const randomPart = Array.from(randomBuffer)\r\n .map(b => b.toString(36))\r\n .join('');\r\n const toHash = `${now}-${randomPart}`;\r\n const encoder = new TextEncoder();\r\n const data = encoder.encode(toHash);\r\n const hash = await crypto.subtle.digest('SHA-256', data);\r\n const hashArray = Array.from(new Uint8Array(hash)); // Convert buffer to byte array\r\n const hashString = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\r\n const shortHash = hashString.substring(0, 12); // Use more of the hash for a longer ID\r\n // return shortHash; // Consider converting this to Base62\r\n return this.encodeBase62(parseInt(shortHash, 16));\r\n };\r\n\r\n encodeBase62 = num => {\r\n const base = 36;\r\n const characters = '0123456789abcdefghijklmnopqrstuvwxyz';\r\n let result = '';\r\n while (num > 0) {\r\n result = characters[num % base] + result;\r\n num = Math.floor(num / base);\r\n }\r\n return result;\r\n };\r\n\r\n /**\r\n * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.\r\n *\r\n * @param params - The parameters to be passed to the peer object.\r\n * @param Calibrator - The class that defines the calibration process.\r\n * @param CalibratorInstance\r\n * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).\r\n * @public\r\n * @example\r\n */\r\n static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {\r\n window.speaker = new Speaker(params, CalibratorInstance);\r\n const {speaker} = window;\r\n await speaker.initPeer();\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise((resolve, reject) => {\r\n // when a call is received\r\n speaker.peer.on('call', async call => {\r\n // Answer the call (one way)\r\n\r\n call.answer();\r\n speaker.#removeUIElems();\r\n speaker.#showSpinner();\r\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\r\n // when we start receiving audio\r\n call.on('stream', async stream => {\r\n window.localStream = stream;\r\n window.localAudio.srcObject = stream;\r\n window.localAudio.autoplay = false;\r\n\r\n // if the sinkSamplingRate is not set sleep\r\n while (!speaker.ac.sampleRatesSet()) {\r\n console.log('SinkSamplingRate is undefined, sleeping');\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\r\n }\r\n\r\n if (params.displayUpdate) {\r\n params.displayUpdate.style.display = '';\r\n }\r\n\r\n // resolve when we have a result\r\n speaker.result = await speaker.ac.startCalibration(\r\n stream,\r\n params.gainValues,\r\n params.ICalib,\r\n params.knownIR,\r\n params.microphoneName,\r\n params.calibrateSoundCheck,\r\n params.isSmartPhone,\r\n params.calibrateSoundBurstDb,\r\n params.calibrateSoundBurstFilteredExtraDb,\r\n params.calibrateSoundBurstLevelReTBool,\r\n params.calibrateSoundBurstUses1000HzGainBool,\r\n params.calibrateSoundBurstRepeats,\r\n params.calibrateSoundBurstSec,\r\n params._calibrateSoundBurstPreSec,\r\n params._calibrateSoundBurstPostSec,\r\n params.calibrateSoundHz,\r\n params.calibrateSoundIRSec,\r\n params.calibrateSoundIIRSec,\r\n params.calibrateSoundIIRPhase,\r\n params.calibrateSound1000HzPreSec,\r\n params.calibrateSound1000HzSec,\r\n params.calibrateSound1000HzPostSec,\r\n params.calibrateSoundBackgroundSecs,\r\n params.calibrateSoundSmoothOctaves,\r\n params.calibrateSoundSmoothMinBandwidthHz,\r\n params.calibrateSoundPowerBinDesiredSec,\r\n params.calibrateSoundPowerDbSDToleratedDb,\r\n params.calibrateSoundTaperSec,\r\n params.micManufacturer,\r\n params.micSerialNumber,\r\n params.micModelNumber,\r\n params.micModelName,\r\n params.calibrateMicrophonesBool,\r\n params.authorEmails,\r\n params.webAudioDeviceNames,\r\n params.IDsToSaveInSoundProfileLibrary,\r\n params.restartButton,\r\n params.reminder,\r\n params.calibrateSoundLimit,\r\n params.calibrateSoundBurstNormalizeBy1000HzGainBool,\r\n params.calibrateSoundBurstScalarDB,\r\n params.calibrateSound1000HzMaxSD_dB,\r\n params._calibrateSoundBurstMaxSD_dB,\r\n params.calibrateSoundSamplingDesiredBits,\r\n params.language,\r\n params.loudspeakerModelName,\r\n params.phrases,\r\n );\r\n speaker.#removeUIElems();\r\n resolve(speaker.result);\r\n });\r\n // if we do not receive a result within the timeout, reject\r\n setTimeout(() => {\r\n reject(\r\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\r\n `Calibration failed to produce a result after ${\r\n timeOut / 1000\r\n } seconds. Please try again.`\r\n )\r\n );\r\n }, timeOut);\r\n });\r\n });\r\n };\r\n\r\n static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {\r\n window.speaker = new Speaker(params, CalibratorInstance);\r\n const {speaker} = window;\r\n speaker.initPeer();\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise((resolve, reject) => {\r\n // when a call is received\r\n speaker.peer.on('call', async call => {\r\n // Answer the call (one way)\r\n call.answer();\r\n speaker.#removeUIElems();\r\n speaker.#showSpinner();\r\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\r\n // when we start receiving audio\r\n call.on('stream', async stream => {\r\n window.localStream = stream;\r\n window.localAudio.srcObject = stream;\r\n window.localAudio.autoplay = false;\r\n\r\n // if the sinkSamplingRate is not set sleep\r\n while (!speaker.ac.sampleRatesSet()) {\r\n console.log('SinkSamplingRate is undefined, sleeping');\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\r\n }\r\n // resolve when we have a result\r\n speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);\r\n speaker.#removeUIElems();\r\n resolve(speaker.result);\r\n });\r\n // if we do not receive a result within the timeout, reject\r\n setTimeout(() => {\r\n reject(\r\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\r\n `Calibration failed to produce a result after ${\r\n timeOut / 1000\r\n } seconds. Please try again.`\r\n )\r\n );\r\n }, timeOut);\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Called after the peer conncection has been opened.\r\n * Generates a QR code for the connection and displays it.\r\n *\r\n * @private\r\n * @example\r\n */\r\n\r\n #showQRCode = async () => {\r\n // Get query string, the URL parameters to specify a Listener\r\n const queryStringParameters = {\r\n speakerPeerId: this.peer.id,\r\n sp: this.isSmartPhone,\r\n hz: this.calibrateSoundHz,\r\n bits: this.calibrateSoundSamplingDesiredBits,\r\n lang: this.language,\r\n deviceId: this.deviceId\r\n };\r\n const queryString = this.queryStringFromObject(queryStringParameters);\r\n this.uri = this.siteUrl + queryString;\r\n if (this.isSmartPhone) {\r\n // if (true) { // test smartphone QR\r\n // Display QR code for the participant to scan\r\n const qrCanvas = document.createElement('canvas');\r\n qrCanvas.setAttribute('id', 'qrCanvas');\r\n qrcode__WEBPACK_IMPORTED_MODULE_0__.toCanvas(qrCanvas, this.uri, error => {\r\n if (error) console.error(error);\r\n });\r\n const explanation = document.createElement('h2');\r\n explanation.id = 'skipQRExplanation';\r\n explanation.style = `\r\n user-select: text;\r\n margin-top: 9px;\r\n font-size: 1.1rem;\r\n `;\r\n // Define the URL and options for the request\r\n const url = 'https://api.short.io/links/public';\r\n const options = {\r\n method: 'POST',\r\n headers: {\r\n Accept: 'application/json',\r\n 'Content-Type': 'application/json',\r\n Authorization: 'pk_fysLKGj3legZz4XZ',\r\n },\r\n body: JSON.stringify({\r\n domain: 'listeners.link', // Ensure this domain is valid for your account\r\n originalURL: this.uri,\r\n }),\r\n };\r\n\r\n // Make the request using fetch\r\n await fetch(url, options)\r\n .then(response => {\r\n if (!response.ok) {\r\n throw new Error(`HTTP error! Status: ${response.status}`);\r\n }\r\n return response.json(); // Parse the JSON response\r\n })\r\n .then(data => {\r\n explanation.innerHTML = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.formatLineBreak)(\r\n this.phrases.RC_skipQR_ExplanationWithoutPreferNot[this.language]\r\n .replace('xxx', `<b style=\"user-select: text\">${data.shortURL}</b>`)\r\n .replace('XXX', `<b style=\"user-select: text\">${data.shortURL}</b>`),\r\n this.phrases.RC_checkInternetConnection[this.language]\r\n );\r\n const checkConnection = document.createElement('a');\r\n checkConnection.id = 'check-connection';\r\n checkConnection.href = '#';\r\n checkConnection.innerHTML = \"check the phone's internet connection\";\r\n const lang = this.language;\r\n checkConnection.addEventListener('click', function (event) {\r\n console.log('clicked');\r\n event.preventDefault(); // Prevent the default link action\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_2__.createAndShowPopup)(lang, this.phrases);\r\n });\r\n explanation.querySelector('a#check-connection').replaceWith(checkConnection);\r\n })\r\n .catch(error => {\r\n console.error('Error:', error.message); // Handle errors\r\n });\r\n\r\n const qrImage = new Image(400, 400);\r\n qrImage.setAttribute('id', 'compatibilityCheckQRImage');\r\n qrImage.style.zIndex = Infinity;\r\n qrImage.style.width = 400;\r\n qrImage.style.height = 400;\r\n qrImage.style.aspectRatio = 1;\r\n qrImage.src = qrCanvas.toDataURL();\r\n qrImage.style.maxHeight = '150px';\r\n qrImage.style.maxWidth = '150px';\r\n\r\n this.qrImage = qrImage;\r\n\r\n const container = document.createElement('div');\r\n container.style.display = 'flex';\r\n container.style.justifyContent = 'space-between';\r\n container.style.alignItems = 'top';\r\n container.id = 'skipQRContainer';\r\n container.appendChild(qrImage);\r\n container.appendChild(explanation);\r\n container.appendChild(this.buttonsContainer);\r\n const qrContainer = document.createElement('div');\r\n qrContainer.appendChild(container);\r\n\r\n document.getElementById(this.targetElement).appendChild(qrContainer);\r\n } else {\r\n // show the link to the user\r\n // If specified HTML Id is available, show QR code there\r\n if (document.getElementById(this.targetElement)) {\r\n // const linkTag = document.createElement('a');\r\n // linkTag.setAttribute('href', uri);\r\n // linkTag.innerHTML = 'Click here to start the calibration';\r\n // linkTag.target = '_blank';\r\n // document.getElementById(this.targetElement).appendChild(linkTag);\r\n // document.getElementById(this.targetElement).appendChild(qrCanvas);\r\n\r\n const proceedButton = document.createElement('button');\r\n proceedButton.setAttribute('id', 'calibrationProceedButton');\r\n proceedButton.setAttribute('class', 'btn btn-success');\r\n proceedButton.innerHTML = this.phrases.T_proceed[this.language];\r\n proceedButton.onclick = () => {\r\n // open the link in a new tab\r\n window.open(this.uri, '_blank');\r\n // remove the button\r\n document.getElementById('calibrationProceedButton').remove();\r\n };\r\n document.getElementById(this.targetElement).appendChild(proceedButton);\r\n }\r\n }\r\n // or just print it to console\r\n console.log('TEST: Peer reachable at: ', this.uri);\r\n };\r\n\r\n #showSpinner = () => {\r\n const spinner = document.createElement('div');\r\n spinner.className = 'spinner-border ml-auto';\r\n spinner.role = 'status';\r\n spinner.ariaHidden = 'true';\r\n spinner.style.marginTop = '0.8rem';\r\n document.getElementById(this.targetElement).appendChild(spinner);\r\n\r\n // clear instructionDisplay\r\n const soundMessage = document.getElementById(this.soundMessageId);\r\n soundMessage.innerHTML = '';\r\n soundMessage.style.display = 'none';\r\n const instructionDisplay = document.getElementById(this.instructionDisplayId);\r\n const background = document.getElementById('background'); // todo: get background id from params\r\n const subtitle = document.getElementById(this.soundSubtitleId);\r\n if (subtitle) {\r\n subtitle.innerHTML = '';\r\n }\r\n if (instructionDisplay) {\r\n instructionDisplay.innerHTML = '';\r\n instructionDisplay.style.whiteSpace = 'nowrap';\r\n instructionDisplay.style.fontWeight = 'bold';\r\n instructionDisplay.style.width = 'fit-content';\r\n instructionDisplay.innerHTML = this.phrases.RC_soundRecording[this.language];\r\n let fontSize = 100;\r\n instructionDisplay.style.fontSize = fontSize + 'px';\r\n while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {\r\n fontSize--;\r\n instructionDisplay.style.fontSize = fontSize + 'px';\r\n }\r\n // const p = document.createElement('p');\r\n // // font size\r\n // p.style.fontSize = '1.1rem';\r\n // p.style.fontWeight = 'normal';\r\n // p.style.paddingTop = '20px';\r\n // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];\r\n // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\r\n // instructionDisplay.appendChild(p);\r\n }\r\n\r\n const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);\r\n if (timeToCalibrateDisplay) {\r\n const timeToCalibrateText = this.phrases.RC_howLongToCalibrate[this.language];\r\n timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\r\n timeToCalibrateDisplay.style.fontWeight = 'normal';\r\n timeToCalibrateDisplay.style.fontSize = '1rem';\r\n // timeToCalibrateDisplay.style.paddingTop = '20px';\r\n }\r\n\r\n // Update title - titleDisplayId\r\n const titleDisplay = document.getElementById(this.titleDisplayId);\r\n if (titleDisplay) {\r\n // if (this.isParticipant) {\r\n // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');\r\n // } else if (this.isSmartPhone) {\r\n // if (this.isLoudspeakerCalibration) {\r\n // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');\r\n // } else {\r\n // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');\r\n // }\r\n // } else {\r\n // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');\r\n // }\r\n if (this.isLoudspeakerCalibration) {\r\n if (this.isParticipant) {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');\r\n } else if (this.isSmartPhone) {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');\r\n } else {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('4', '5');\r\n }\r\n } else {\r\n if (this.isSmartPhone) {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');\r\n } else {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');\r\n }\r\n }\r\n }\r\n };\r\n\r\n #removeUIElems = () => {\r\n const parent = document.getElementById(this.targetElement);\r\n while (parent.firstChild) {\r\n parent.firstChild.remove();\r\n }\r\n };\r\n\r\n /**\r\n * Called when the peer connection is opened.\r\n * Saves the peer id and calls the QR code generator.\r\n *\r\n * @param peerId - The peer id of the peer connection.\r\n * @param id\r\n * @private\r\n * @example\r\n */\r\n #onPeerOpen = id => {\r\n // Workaround for peer.reconnect deleting previous id\r\n if (id === null) {\r\n console.error('Received null id from peer open');\r\n this.peer.id = this.lastPeerId;\r\n } else {\r\n this.lastPeerId = this.peer.id;\r\n }\r\n\r\n if (id !== this.peer.id) {\r\n console.warn('DEBUG Check you assumption that id === this.peer.id');\r\n }\r\n\r\n this.#showQRCode();\r\n };\r\n\r\n /**\r\n * Called when the peer connection is established.\r\n * Enforces a single connection.\r\n *\r\n * @param connection - The connection object.\r\n * @private\r\n * @example\r\n */\r\n #onPeerConnection = connection => {\r\n // Allow only a single connection\r\n if (this.conn && this.conn.open) {\r\n connection.on('open', () => {\r\n connection.send('Already connected to another client');\r\n setTimeout(() => {\r\n connection.close();\r\n }, 500);\r\n });\r\n return;\r\n }\r\n\r\n this.conn = connection;\r\n console.log('Connected to: ', this.conn.peer);\r\n this.#ready();\r\n };\r\n\r\n /**\r\n * Called when the peer connection is closed.\r\n *\r\n * @private\r\n * @example\r\n */\r\n onPeerClose = () => {\r\n this.conn = null;\r\n console.log('Connection destroyed');\r\n };\r\n\r\n static closeConnection = () => {\r\n this.conn = null;\r\n console.log('Connection destroyed');\r\n };\r\n\r\n /**\r\n * Called when the peer connection is disconnected.\r\n * Attempts to reconnect.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #onPeerDisconnected = () => {\r\n console.log('Connection lost. Please reconnect');\r\n\r\n // Workaround for peer.reconnect deleting previous id\r\n this.peer.id = this.lastPeerId;\r\n // eslint-disable-next-line no-underscore-dangle\r\n this.peer._lastServerId = this.lastPeerId;\r\n this.peer.reconnect();\r\n };\r\n\r\n /**\r\n * Called when the peer connection encounters an error.\r\n *\r\n * @param error\r\n * @private\r\n * @example\r\n */\r\n #onPeerError = error => {\r\n // TODO: check if this function is needed or not\r\n console.error(error);\r\n };\r\n\r\n /**\r\n * Called when data is received from the peer connection.\r\n *\r\n * @param data\r\n * @private\r\n * @example\r\n */\r\n #onIncomingData = data => {\r\n // enforce object type\r\n if (\r\n !Object.prototype.hasOwnProperty.call(data, 'name') ||\r\n !Object.prototype.hasOwnProperty.call(data, 'payload')\r\n ) {\r\n console.error('Received malformed data: ', data);\r\n return;\r\n }\r\n\r\n switch (data.name) {\r\n case 'samplingRate':\r\n this.ac.setSamplingRates(data.payload);\r\n break;\r\n case 'sampleSize':\r\n this.ac.setSampleSize(data.payload);\r\n break;\r\n case 'deviceType':\r\n this.ac.setDeviceType(data.payload);\r\n break;\r\n case 'deviceName':\r\n this.ac.setDeviceName(data.payload);\r\n break;\r\n case 'flags':\r\n //this.ac.setDeviceName(data.payload);\r\n console.log('FLAGS');\r\n console.log(data.payload);\r\n this.ac.setFlags(data.payload);\r\n break;\r\n case 'deviceInfo':\r\n this.ac.setDeviceInfo(data.payload);\r\n console.log('Received device info from listener: ', data.payload);\r\n break;\r\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.UnsupportedDeviceError.name:\r\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.MissingSpeakerIdError.name:\r\n throw data.payload;\r\n break;\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Called when the peer connection is #ready.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #ready = () => {\r\n // Perform callback with data\r\n this.conn.on('data', this.#onIncomingData);\r\n this.conn.on('close', () => {\r\n console.log('Connection reset<br>Awaiting connection...');\r\n this.conn = null;\r\n });\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Debug method for downloading the recorded audio\r\n *\r\n * @public\r\n * @example\r\n */\r\n downloadData = () => {\r\n this.ac.downloadData();\r\n };\r\n\r\n repeatCalibration = async (params, stream, CalibratorInstance) => {\r\n this.ac = CalibratorInstance;\r\n this.#removeUIElems();\r\n this.#showSpinner();\r\n\r\n console.log('This is a repeat');\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise(async (resolve, reject) => {\r\n const result = await this.ac.startCalibration(\r\n stream,\r\n params.gainValues,\r\n params.ICalib,\r\n params.knownIR,\r\n params.microphoneName,\r\n params.calibrateSoundCheck,\r\n params.isSmartPhone,\r\n params.calibrateSoundBurstDb,\r\n params.calibrateSoundBurstFilteredExtraDb,\r\n params.calibrateSoundBurstLevelReTBool,\r\n params.calibrateSoundBurstUses1000HzGainBool,\r\n params.calibrateSoundBurstRepeats,\r\n params.calibrateSoundBurstSec,\r\n params._calibrateSoundBurstPreSec,\r\n params._calibrateSoundBurstPostSec,\r\n params.calibrateSoundHz,\r\n params.calibrateSoundIRSec,\r\n params.calibrateSoundIIRSec,\r\n params.calibrateSoundIIRPhase,\r\n params.calibrateSound1000HzPreSec,\r\n params.calibrateSound1000HzSec,\r\n params.calibrateSound1000HzPostSec,\r\n params.calibrateSoundBackgroundSecs,\r\n params.calibrateSoundSmoothOctaves,\r\n params.calibrateSoundSmoothMinBandwidthHz,\r\n params.calibrateSoundPowerBinDesiredSec,\r\n params.calibrateSoundPowerDbSDToleratedDb,\r\n params.calibrateSoundTaperSec,\r\n params.micManufacturer,\r\n params.micSerialNumber,\r\n params.micModelNumber,\r\n params.micModelName,\r\n params.calibrateMicrophonesBool,\r\n params.authorEmails,\r\n params.webAudioDeviceNames,\r\n params.IDsToSaveInSoundProfileLibrary,\r\n params.restartButton,\r\n params.reminder,\r\n params.calibrateSoundLimit,\r\n params.calibrateSoundBurstNormalizeBy1000HzGainBool,\r\n params.calibrateSoundBurstScalarDB,\r\n params.calibrateSound1000HzMaxSD_dB,\r\n params._calibrateSoundBurstMaxSD_dB,\r\n params.calibrateSoundSamplingDesiredBits,\r\n params.language,\r\n params.loudspeakerModelName,\r\n params.phrases,\r\n );\r\n this.#removeUIElems();\r\n resolve(result);\r\n });\r\n };\r\n}\r\n\r\n/* \r\nReferenced links:\r\nhttps://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676\r\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\r\nhttps://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]\r\n*/\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Speaker);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/speaker.js?");
460
+ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var qrcode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! qrcode */ \"./node_modules/qrcode/lib/browser.js\");\n/* harmony import */ var _audioPeer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./audioPeer */ \"./src/peer-connection/audioPeer.js\");\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ \"./src/utils.js\");\n/* harmony import */ var _peerErrors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./peerErrors */ \"./src/peer-connection/peerErrors.js\");\n\r\n\r\n\r\n\r\n\r\n//import {phrases} from '../../dist/example/i18n';\r\n\r\n/**\r\n * @class Handles the speaker's side of the connection. Responsible for initiating the connection,\r\n * rendering the QRCode, and answering the call.\r\n * @augments AudioPeer\r\n */\r\nclass Speaker extends _audioPeer__WEBPACK_IMPORTED_MODULE_1__[\"default\"] {\r\n /**\r\n * Takes the url of the current site and a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.\r\n * @param CalibratorInstance\r\n * @example\r\n */\r\n constructor(params, CalibratorInstance) {\r\n super(params);\r\n this.language = params?.language ?? 'en-US';\r\n this.siteUrl += '/listener?';\r\n this.ac = CalibratorInstance;\r\n this.result = null;\r\n this.debug = params?.debug ?? false;\r\n this.isSmartPhone = params?.isSmartPhone ?? false;\r\n this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;\r\n this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;\r\n this.instructionDisplayId = params?.instructionDisplayId ?? '';\r\n this.soundSubtitleId = params?.soundSubtitleId ?? '';\r\n this.timeToCalibrateDisplay = params?.timeToCalibrateId ?? '';\r\n this.soundMessageId = params?.soundMessageId ?? '';\r\n this.titleDisplayId = params?.titleDisplayId ?? '';\r\n this.timeToCalibrate = params?.timeToCalibrate ?? 10;\r\n this.isParticipant = params?.isParticipant ?? false;\r\n this.isLoudspeakerCalibration = params?.isLoudspeakerCalibration ?? false;\r\n this.deviceId = params?.micrpohoneIdFromWebAudioApi ?? '';\r\n this.buttonsContainer = params?.buttonsContainer ?? document.createElement('div');\r\n this.phrases = params?. phrases ?? {};\r\n\r\n /* Set up callbacks that handle any events related to our peer object. */\r\n }\r\n\r\n uri = '';\r\n qrImage;\r\n shortURL;\r\n\r\n initPeer = async () => {\r\n const id = await this.generateTimeBasedPeerID();\r\n this.peer = new Peer(id, {\r\n secure: true,\r\n host: 'easyeyes-peer-server.herokuapp.com',\r\n port: 443,\r\n config: {\r\n iceServers: [\r\n {\r\n urls: 'stun:stun.relay.metered.ca:80',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:80',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:80?transport=tcp',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turn:global.relay.metered.ca:443',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n {\r\n urls: 'turns:global.relay.metered.ca:443?transport=tcp',\r\n username: 'de884cfc34189cdf1a5dd616',\r\n credential: 'IcOpouU9/TYBmpHU',\r\n },\r\n ],\r\n },\r\n });\r\n this.peer.on('open', this.#onPeerOpen);\r\n this.peer.on('connection', this.#onPeerConnection);\r\n this.peer.on('close', this.onPeerClose);\r\n this.peer.on('disconnected', this.#onPeerDisconnected);\r\n this.peer.on('error', this.#onPeerError);\r\n };\r\n generateTimeBasedPeerID = async () => {\r\n const now = new Date().getTime();\r\n const randomBuffer = new Uint8Array(10);\r\n crypto.getRandomValues(randomBuffer);\r\n const randomPart = Array.from(randomBuffer)\r\n .map(b => b.toString(36))\r\n .join('');\r\n const toHash = `${now}-${randomPart}`;\r\n const encoder = new TextEncoder();\r\n const data = encoder.encode(toHash);\r\n const hash = await crypto.subtle.digest('SHA-256', data);\r\n const hashArray = Array.from(new Uint8Array(hash)); // Convert buffer to byte array\r\n const hashString = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\r\n const shortHash = hashString.substring(0, 12); // Use more of the hash for a longer ID\r\n // return shortHash; // Consider converting this to Base62\r\n return this.encodeBase62(parseInt(shortHash, 16));\r\n };\r\n\r\n encodeBase62 = num => {\r\n const base = 36;\r\n const characters = '0123456789abcdefghijklmnopqrstuvwxyz';\r\n let result = '';\r\n while (num > 0) {\r\n result = characters[num % base] + result;\r\n num = Math.floor(num / base);\r\n }\r\n return result;\r\n };\r\n\r\n /**\r\n * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.\r\n *\r\n * @param params - The parameters to be passed to the peer object.\r\n * @param Calibrator - The class that defines the calibration process.\r\n * @param CalibratorInstance\r\n * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).\r\n * @public\r\n * @example\r\n */\r\n static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {\r\n window.speaker = new Speaker(params, CalibratorInstance);\r\n const {speaker} = window;\r\n await speaker.initPeer();\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise((resolve, reject) => {\r\n // when a call is received\r\n speaker.peer.on('call', async call => {\r\n // Answer the call (one way)\r\n\r\n call.answer();\r\n speaker.#removeUIElems();\r\n speaker.#showSpinner();\r\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\r\n // when we start receiving audio\r\n call.on('stream', async stream => {\r\n window.localStream = stream;\r\n window.localAudio.srcObject = stream;\r\n window.localAudio.autoplay = false;\r\n\r\n // if the sinkSamplingRate is not set sleep\r\n while (!speaker.ac.sampleRatesSet()) {\r\n console.log('SinkSamplingRate is undefined, sleeping');\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\r\n }\r\n\r\n if (params.displayUpdate) {\r\n params.displayUpdate.style.display = '';\r\n }\r\n\r\n // resolve when we have a result\r\n speaker.result = await speaker.ac.startCalibration(\r\n stream,\r\n params.gainValues,\r\n params.ICalib,\r\n params.knownIR,\r\n params.microphoneName,\r\n params.calibrateSoundCheck,\r\n params.isSmartPhone,\r\n params.calibrateSoundBurstDb,\r\n params.calibrateSoundBurstFilteredExtraDb,\r\n params.calibrateSoundBurstLevelReTBool,\r\n params.calibrateSoundBurstUses1000HzGainBool,\r\n params.calibrateSoundBurstRepeats,\r\n params.calibrateSoundBurstSec,\r\n params._calibrateSoundBurstPreSec,\r\n params._calibrateSoundBurstPostSec,\r\n params.calibrateSoundHz,\r\n params.calibrateSoundIRSec,\r\n params.calibrateSoundIIRSec,\r\n params.calibrateSoundIIRPhase,\r\n params.calibrateSound1000HzPreSec,\r\n params.calibrateSound1000HzSec,\r\n params.calibrateSound1000HzPostSec,\r\n params.calibrateSoundBackgroundSecs,\r\n params.calibrateSoundSmoothOctaves,\r\n params.calibrateSoundSmoothMinBandwidthHz,\r\n params.calibrateSoundPowerBinDesiredSec,\r\n params.calibrateSoundPowerDbSDToleratedDb,\r\n params.calibrateSoundTaperSec,\r\n params.micManufacturer,\r\n params.micSerialNumber,\r\n params.micModelNumber,\r\n params.micModelName,\r\n params.calibrateMicrophonesBool,\r\n params.authorEmails,\r\n params.webAudioDeviceNames,\r\n params.IDsToSaveInSoundProfileLibrary,\r\n params.restartButton,\r\n params.reminder,\r\n params.calibrateSoundLimit,\r\n params.calibrateSoundBurstNormalizeBy1000HzGainBool,\r\n params.calibrateSoundBurstScalarDB,\r\n params.calibrateSound1000HzMaxSD_dB,\r\n params._calibrateSoundBurstMaxSD_dB,\r\n params.calibrateSoundSamplingDesiredBits,\r\n params.language,\r\n params.loudspeakerModelName,\r\n params.phrases,\r\n params.soundSubtitleId,\r\n );\r\n speaker.#removeUIElems();\r\n resolve(speaker.result);\r\n });\r\n // if we do not receive a result within the timeout, reject\r\n setTimeout(() => {\r\n reject(\r\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\r\n `Calibration failed to produce a result after ${\r\n timeOut / 1000\r\n } seconds. Please try again.`\r\n )\r\n );\r\n }, timeOut);\r\n });\r\n });\r\n };\r\n\r\n static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {\r\n window.speaker = new Speaker(params, CalibratorInstance);\r\n const {speaker} = window;\r\n speaker.initPeer();\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise((resolve, reject) => {\r\n // when a call is received\r\n speaker.peer.on('call', async call => {\r\n // Answer the call (one way)\r\n call.answer();\r\n speaker.#removeUIElems();\r\n speaker.#showSpinner();\r\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\r\n // when we start receiving audio\r\n call.on('stream', async stream => {\r\n window.localStream = stream;\r\n window.localAudio.srcObject = stream;\r\n window.localAudio.autoplay = false;\r\n\r\n // if the sinkSamplingRate is not set sleep\r\n while (!speaker.ac.sampleRatesSet()) {\r\n console.log('SinkSamplingRate is undefined, sleeping');\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\r\n }\r\n // resolve when we have a result\r\n speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);\r\n speaker.#removeUIElems();\r\n resolve(speaker.result);\r\n });\r\n // if we do not receive a result within the timeout, reject\r\n setTimeout(() => {\r\n reject(\r\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\r\n `Calibration failed to produce a result after ${\r\n timeOut / 1000\r\n } seconds. Please try again.`\r\n )\r\n );\r\n }, timeOut);\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Called after the peer conncection has been opened.\r\n * Generates a QR code for the connection and displays it.\r\n *\r\n * @private\r\n * @example\r\n */\r\n\r\n #showQRCode = async () => {\r\n // Get query string, the URL parameters to specify a Listener\r\n const queryStringParameters = {\r\n speakerPeerId: this.peer.id,\r\n sp: this.isSmartPhone,\r\n hz: this.calibrateSoundHz,\r\n bits: this.calibrateSoundSamplingDesiredBits,\r\n lang: this.language,\r\n deviceId: this.deviceId\r\n };\r\n const queryString = this.queryStringFromObject(queryStringParameters);\r\n this.uri = this.siteUrl + queryString;\r\n if (this.isSmartPhone) {\r\n // if (true) { // test smartphone QR\r\n // Display QR code for the participant to scan\r\n const qrCanvas = document.createElement('canvas');\r\n qrCanvas.setAttribute('id', 'qrCanvas');\r\n qrcode__WEBPACK_IMPORTED_MODULE_0__.toCanvas(qrCanvas, this.uri, error => {\r\n if (error) console.error(error);\r\n });\r\n const explanation = document.createElement('h2');\r\n explanation.id = 'skipQRExplanation';\r\n explanation.style = `\r\n user-select: text;\r\n margin-top: 9px;\r\n font-size: 1.1rem;\r\n `;\r\n // Define the URL and options for the request\r\n const url = 'https://api.short.io/links/public';\r\n const options = {\r\n method: 'POST',\r\n headers: {\r\n Accept: 'application/json',\r\n 'Content-Type': 'application/json',\r\n Authorization: 'pk_fysLKGj3legZz4XZ',\r\n },\r\n body: JSON.stringify({\r\n domain: 'listeners.link', // Ensure this domain is valid for your account\r\n originalURL: this.uri,\r\n }),\r\n };\r\n\r\n // Make the request using fetch\r\n await fetch(url, options)\r\n .then(response => {\r\n if (!response.ok) {\r\n throw new Error(`HTTP error! Status: ${response.status}`);\r\n }\r\n return response.json(); // Parse the JSON response\r\n })\r\n .then(data => {\r\n explanation.innerHTML = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.formatLineBreak)(\r\n this.phrases.RC_skipQR_ExplanationWithoutPreferNot[this.language]\r\n .replace('xxx', `<b style=\"user-select: text\">${data.shortURL}</b>`)\r\n .replace('XXX', `<b style=\"user-select: text\">${data.shortURL}</b>`),\r\n this.phrases.RC_checkInternetConnection[this.language]\r\n );\r\n const checkConnection = document.createElement('a');\r\n checkConnection.id = 'check-connection';\r\n checkConnection.href = '#';\r\n checkConnection.innerHTML = \"check the phone's internet connection\";\r\n const lang = this.language;\r\n checkConnection.addEventListener('click', function (event) {\r\n console.log('clicked');\r\n event.preventDefault(); // Prevent the default link action\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_2__.createAndShowPopup)(lang, this.phrases);\r\n });\r\n explanation.querySelector('a#check-connection').replaceWith(checkConnection);\r\n })\r\n .catch(error => {\r\n console.error('Error:', error.message); // Handle errors\r\n });\r\n\r\n const qrImage = new Image(400, 400);\r\n qrImage.setAttribute('id', 'compatibilityCheckQRImage');\r\n qrImage.style.zIndex = Infinity;\r\n qrImage.style.width = 400;\r\n qrImage.style.height = 400;\r\n qrImage.style.aspectRatio = 1;\r\n qrImage.src = qrCanvas.toDataURL();\r\n qrImage.style.maxHeight = '150px';\r\n qrImage.style.maxWidth = '150px';\r\n\r\n this.qrImage = qrImage;\r\n\r\n const container = document.createElement('div');\r\n container.style.display = 'flex';\r\n container.style.justifyContent = 'space-between';\r\n container.style.alignItems = 'top';\r\n container.id = 'skipQRContainer';\r\n container.appendChild(qrImage);\r\n container.appendChild(explanation);\r\n container.appendChild(this.buttonsContainer);\r\n const qrContainer = document.createElement('div');\r\n qrContainer.appendChild(container);\r\n\r\n document.getElementById(this.targetElement).appendChild(qrContainer);\r\n } else {\r\n // show the link to the user\r\n // If specified HTML Id is available, show QR code there\r\n if (document.getElementById(this.targetElement)) {\r\n // const linkTag = document.createElement('a');\r\n // linkTag.setAttribute('href', uri);\r\n // linkTag.innerHTML = 'Click here to start the calibration';\r\n // linkTag.target = '_blank';\r\n // document.getElementById(this.targetElement).appendChild(linkTag);\r\n // document.getElementById(this.targetElement).appendChild(qrCanvas);\r\n\r\n const proceedButton = document.createElement('button');\r\n proceedButton.setAttribute('id', 'calibrationProceedButton');\r\n proceedButton.setAttribute('class', 'btn btn-success');\r\n proceedButton.innerHTML = this.phrases.T_proceed[this.language];\r\n proceedButton.onclick = () => {\r\n // open the link in a new tab\r\n window.open(this.uri, '_blank');\r\n // remove the button\r\n document.getElementById('calibrationProceedButton').remove();\r\n };\r\n document.getElementById(this.targetElement).appendChild(proceedButton);\r\n }\r\n }\r\n // or just print it to console\r\n console.log('TEST: Peer reachable at: ', this.uri);\r\n };\r\n\r\n #showSpinner = () => {\r\n const spinner = document.createElement('div');\r\n spinner.className = 'spinner-border ml-auto';\r\n spinner.role = 'status';\r\n spinner.ariaHidden = 'true';\r\n spinner.style.marginTop = '0.8rem';\r\n document.getElementById(this.targetElement).appendChild(spinner);\r\n\r\n // clear instructionDisplay\r\n const soundMessage = document.getElementById(this.soundMessageId);\r\n soundMessage.innerHTML = '';\r\n soundMessage.style.display = 'none';\r\n const instructionDisplay = document.getElementById(this.instructionDisplayId);\r\n const background = document.getElementById('background'); // todo: get background id from params\r\n const subtitle = document.getElementById(this.soundSubtitleId);\r\n if (subtitle) {\r\n subtitle.innerHTML = '';\r\n }\r\n if (instructionDisplay) {\r\n instructionDisplay.innerHTML = '';\r\n instructionDisplay.style.whiteSpace = 'nowrap';\r\n instructionDisplay.style.fontWeight = 'bold';\r\n instructionDisplay.style.width = 'fit-content';\r\n instructionDisplay.innerHTML = this.phrases.RC_soundRecording[this.language];\r\n let fontSize = 100;\r\n instructionDisplay.style.fontSize = fontSize + 'px';\r\n while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {\r\n fontSize--;\r\n instructionDisplay.style.fontSize = fontSize + 'px';\r\n }\r\n // const p = document.createElement('p');\r\n // // font size\r\n // p.style.fontSize = '1.1rem';\r\n // p.style.fontWeight = 'normal';\r\n // p.style.paddingTop = '20px';\r\n // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];\r\n // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\r\n // instructionDisplay.appendChild(p);\r\n }\r\n\r\n const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);\r\n if (timeToCalibrateDisplay) {\r\n const timeToCalibrateText = this.phrases.RC_howLongToCalibrate[this.language];\r\n timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\r\n timeToCalibrateDisplay.style.fontWeight = 'normal';\r\n timeToCalibrateDisplay.style.fontSize = '1rem';\r\n // timeToCalibrateDisplay.style.paddingTop = '20px';\r\n }\r\n\r\n // Update title - titleDisplayId\r\n const titleDisplay = document.getElementById(this.titleDisplayId);\r\n if (titleDisplay) {\r\n // if (this.isParticipant) {\r\n // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');\r\n // } else if (this.isSmartPhone) {\r\n // if (this.isLoudspeakerCalibration) {\r\n // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');\r\n // } else {\r\n // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');\r\n // }\r\n // } else {\r\n // titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');\r\n // }\r\n if (this.isLoudspeakerCalibration) {\r\n if (this.isParticipant) {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');\r\n } else if (this.isSmartPhone) {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('6', '7');\r\n } else {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('4', '5');\r\n }\r\n } else {\r\n if (this.isSmartPhone) {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');\r\n } else {\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('3', '4');\r\n }\r\n }\r\n }\r\n };\r\n\r\n #removeUIElems = () => {\r\n const parent = document.getElementById(this.targetElement);\r\n while (parent.firstChild) {\r\n parent.firstChild.remove();\r\n }\r\n };\r\n\r\n /**\r\n * Called when the peer connection is opened.\r\n * Saves the peer id and calls the QR code generator.\r\n *\r\n * @param peerId - The peer id of the peer connection.\r\n * @param id\r\n * @private\r\n * @example\r\n */\r\n #onPeerOpen = id => {\r\n // Workaround for peer.reconnect deleting previous id\r\n if (id === null) {\r\n console.error('Received null id from peer open');\r\n this.peer.id = this.lastPeerId;\r\n } else {\r\n this.lastPeerId = this.peer.id;\r\n }\r\n\r\n if (id !== this.peer.id) {\r\n console.warn('DEBUG Check you assumption that id === this.peer.id');\r\n }\r\n\r\n this.#showQRCode();\r\n };\r\n\r\n /**\r\n * Called when the peer connection is established.\r\n * Enforces a single connection.\r\n *\r\n * @param connection - The connection object.\r\n * @private\r\n * @example\r\n */\r\n #onPeerConnection = connection => {\r\n // Allow only a single connection\r\n if (this.conn && this.conn.open) {\r\n connection.on('open', () => {\r\n connection.send('Already connected to another client');\r\n setTimeout(() => {\r\n connection.close();\r\n }, 500);\r\n });\r\n return;\r\n }\r\n\r\n this.conn = connection;\r\n console.log('Connected to: ', this.conn.peer);\r\n this.#ready();\r\n };\r\n\r\n /**\r\n * Called when the peer connection is closed.\r\n *\r\n * @private\r\n * @example\r\n */\r\n onPeerClose = () => {\r\n this.conn = null;\r\n console.log('Connection destroyed');\r\n };\r\n\r\n static closeConnection = () => {\r\n this.conn = null;\r\n console.log('Connection destroyed');\r\n };\r\n\r\n /**\r\n * Called when the peer connection is disconnected.\r\n * Attempts to reconnect.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #onPeerDisconnected = () => {\r\n console.log('Connection lost. Please reconnect');\r\n\r\n // Workaround for peer.reconnect deleting previous id\r\n this.peer.id = this.lastPeerId;\r\n // eslint-disable-next-line no-underscore-dangle\r\n this.peer._lastServerId = this.lastPeerId;\r\n this.peer.reconnect();\r\n };\r\n\r\n /**\r\n * Called when the peer connection encounters an error.\r\n *\r\n * @param error\r\n * @private\r\n * @example\r\n */\r\n #onPeerError = error => {\r\n // TODO: check if this function is needed or not\r\n console.error(error);\r\n };\r\n\r\n /**\r\n * Called when data is received from the peer connection.\r\n *\r\n * @param data\r\n * @private\r\n * @example\r\n */\r\n #onIncomingData = data => {\r\n // enforce object type\r\n if (\r\n !Object.prototype.hasOwnProperty.call(data, 'name') ||\r\n !Object.prototype.hasOwnProperty.call(data, 'payload')\r\n ) {\r\n console.error('Received malformed data: ', data);\r\n return;\r\n }\r\n\r\n switch (data.name) {\r\n case 'samplingRate':\r\n this.ac.setSamplingRates(data.payload);\r\n break;\r\n case 'sampleSize':\r\n this.ac.setSampleSize(data.payload);\r\n break;\r\n case 'deviceType':\r\n this.ac.setDeviceType(data.payload);\r\n break;\r\n case 'deviceName':\r\n this.ac.setDeviceName(data.payload);\r\n break;\r\n case 'flags':\r\n //this.ac.setDeviceName(data.payload);\r\n console.log('FLAGS');\r\n console.log(data.payload);\r\n this.ac.setFlags(data.payload);\r\n break;\r\n case 'deviceInfo':\r\n this.ac.setDeviceInfo(data.payload);\r\n console.log('Received device info from listener: ', data.payload);\r\n break;\r\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.UnsupportedDeviceError.name:\r\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.MissingSpeakerIdError.name:\r\n throw data.payload;\r\n break;\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Called when the peer connection is #ready.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #ready = () => {\r\n // Perform callback with data\r\n this.conn.on('data', this.#onIncomingData);\r\n this.conn.on('close', () => {\r\n console.log('Connection reset<br>Awaiting connection...');\r\n this.conn = null;\r\n });\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Debug method for downloading the recorded audio\r\n *\r\n * @public\r\n * @example\r\n */\r\n downloadData = () => {\r\n this.ac.downloadData();\r\n };\r\n\r\n repeatCalibration = async (params, stream, CalibratorInstance) => {\r\n this.ac = CalibratorInstance;\r\n this.#removeUIElems();\r\n this.#showSpinner();\r\n\r\n console.log('This is a repeat');\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise(async (resolve, reject) => {\r\n const result = await this.ac.startCalibration(\r\n stream,\r\n params.gainValues,\r\n params.ICalib,\r\n params.knownIR,\r\n params.microphoneName,\r\n params.calibrateSoundCheck,\r\n params.isSmartPhone,\r\n params.calibrateSoundBurstDb,\r\n params.calibrateSoundBurstFilteredExtraDb,\r\n params.calibrateSoundBurstLevelReTBool,\r\n params.calibrateSoundBurstUses1000HzGainBool,\r\n params.calibrateSoundBurstRepeats,\r\n params.calibrateSoundBurstSec,\r\n params._calibrateSoundBurstPreSec,\r\n params._calibrateSoundBurstPostSec,\r\n params.calibrateSoundHz,\r\n params.calibrateSoundIRSec,\r\n params.calibrateSoundIIRSec,\r\n params.calibrateSoundIIRPhase,\r\n params.calibrateSound1000HzPreSec,\r\n params.calibrateSound1000HzSec,\r\n params.calibrateSound1000HzPostSec,\r\n params.calibrateSoundBackgroundSecs,\r\n params.calibrateSoundSmoothOctaves,\r\n params.calibrateSoundSmoothMinBandwidthHz,\r\n params.calibrateSoundPowerBinDesiredSec,\r\n params.calibrateSoundPowerDbSDToleratedDb,\r\n params.calibrateSoundTaperSec,\r\n params.micManufacturer,\r\n params.micSerialNumber,\r\n params.micModelNumber,\r\n params.micModelName,\r\n params.calibrateMicrophonesBool,\r\n params.authorEmails,\r\n params.webAudioDeviceNames,\r\n params.IDsToSaveInSoundProfileLibrary,\r\n params.restartButton,\r\n params.reminder,\r\n params.calibrateSoundLimit,\r\n params.calibrateSoundBurstNormalizeBy1000HzGainBool,\r\n params.calibrateSoundBurstScalarDB,\r\n params.calibrateSound1000HzMaxSD_dB,\r\n params._calibrateSoundBurstMaxSD_dB,\r\n params.calibrateSoundSamplingDesiredBits,\r\n params.language,\r\n params.loudspeakerModelName,\r\n params.phrases,\r\n params.soundSubtitleId,\r\n );\r\n this.#removeUIElems();\r\n resolve(result);\r\n });\r\n };\r\n}\r\n\r\n/* \r\nReferenced links:\r\nhttps://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676\r\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\r\nhttps://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]\r\n*/\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Speaker);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/speaker.js?");
461
461
 
462
462
  /***/ }),
463
463
 
@@ -512,7 +512,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _myE
512
512
  /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
513
513
 
514
514
  "use strict";
515
- eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _audioCalibrator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../audioCalibrator */ \"./src/tasks/audioCalibrator.js\");\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils */ \"./src/utils.js\");\n/* harmony import */ var _powerCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../powerCheck */ \"./src/powerCheck.js\");\n/* harmony import */ var _config_firebase__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../config/firebase */ \"./src/config/firebase.js\");\n/* harmony import */ var firebase_database__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! firebase/database */ \"./node_modules/firebase/database/dist/esm/index.esm.js\");\n/* harmony import */ var firebase_firestore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! firebase/firestore */ \"./node_modules/firebase/firestore/dist/esm/index.esm.js\");\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n//import { phrases } from '../../../dist/example/i18n';\r\n\r\n/**\r\n *\r\n */\r\nclass Combination extends _audioCalibrator__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\r\n /**\r\n * Default constructor. Creates an instance with any number of paramters passed or the default parameters defined here.\r\n *\r\n * @param {Object<boolean, number, number, number>} calibratorParams - paramter object\r\n * @param {boolean} [calibratorParams.download = false] - boolean flag to download captures\r\n * @param {number} [calibratorParams.mlsOrder = 18] - order of the MLS to be generated\r\n * @param {number} [calibratorParams.numCaptures = 5] - number of captures to perform\r\n * @param {number} [calibratorParams.numMLSPerCapture = 2] - number of bursts of MLS per capture\r\n */\r\n constructor({\r\n download = false,\r\n mlsOrder = 18,\r\n numCaptures = 3,\r\n numMLSPerCapture = 2,\r\n lowHz = 20,\r\n highHz = 10000,\r\n }) {\r\n super(numCaptures, numMLSPerCapture);\r\n this.#mlsOrder = parseInt(mlsOrder, 10);\r\n this.#P = 2 ** mlsOrder - 1;\r\n this.#download = download;\r\n this.#mls = [];\r\n this.#lowHz = lowHz;\r\n this.#highHz = highHz;\r\n }\r\n\r\n /** @private */\r\n stepNum = 0;\r\n\r\n /** @private */\r\n totalSteps = 25;\r\n\r\n /** @private */\r\n #download;\r\n\r\n /** @private */\r\n #mlsGenInterface;\r\n\r\n /** @private */\r\n #mlsBufferView;\r\n\r\n /** @private */\r\n componentInvertedImpulseResponse = null;\r\n\r\n /** @private */\r\n systemInvertedImpulseResponse = null;\r\n\r\n //averaged and subtracted ir returned from calibration used to calculated iir\r\n /** @private */\r\n ir = null;\r\n\r\n /** @private */\r\n impulseResponses = [];\r\n\r\n /** @private */\r\n #mlsOrder;\r\n\r\n /** @private */\r\n #lowHz;\r\n\r\n /** @private */\r\n #highHz;\r\n\r\n /** @private */\r\n #mls;\r\n\r\n /** @private */\r\n #P;\r\n\r\n /** @private */\r\n #audioContext;\r\n\r\n /** @private */\r\n offsetGainNode;\r\n\r\n /** @private */\r\n componentConvolution;\r\n\r\n /** @private */\r\n componentConvolutionNoBandpass;\r\n\r\n /** @private */\r\n componentIROrigin = {\r\n Freq: [],\r\n Gain: [],\r\n };\r\n\r\n /** @private */\r\n systemConvolution;\r\n\r\n /** @private */\r\n systemConvolutionNoBandpass;\r\n\r\n ////////////////////////volume\r\n /** @private */\r\n #CALIBRATION_TONE_FREQUENCY = 1000; // Hz\r\n\r\n /** @private */\r\n #CALIBRATION_TONE_TYPE = 'sine';\r\n\r\n CALIBRATION_TONE_DURATION = 5; // seconds\r\n calibrateSound1000HzPreSec = 3.5;\r\n calibrateSound1000HzSec = 1.0;\r\n calibrateSound1000HzPostSec = 0.5;\r\n\r\n /** @private */\r\n outDBSPL = null;\r\n THD = null;\r\n outDBSPL1000 = null;\r\n\r\n /** @private */\r\n TAPER_SECS = 0.01; // seconds\r\n\r\n /** @private */\r\n status_denominator = 8;\r\n\r\n /** @private */\r\n status_numerator = 0;\r\n\r\n /** @private */\r\n percent_complete = 0;\r\n\r\n /** @private */\r\n status = ``;\r\n\r\n /**@private */\r\n status_literal = `<div style=\"display: flex; justify-content: center;\"><div style=\"width: 200px; height: 20px; border: 2px solid #000; border-radius: 10px;\"><div style=\"width: ${this.percent_complete}%; height: 100%; background-color: #00aaff; border-radius: 8px;\"></div></div></div>`;\r\n\r\n /**@private */\r\n componentIR = null;\r\n\r\n /**@private */\r\n oldComponentIR = null;\r\n\r\n /**@private */\r\n systemIR = null;\r\n\r\n /**@private */\r\n _calibrateSoundCheck = '';\r\n\r\n deviceType = null;\r\n\r\n deviceName = null;\r\n\r\n deviceInfo = null;\r\n\r\n desired_time_per_mls = 0;\r\n\r\n num_mls_to_skip = 0;\r\n\r\n desired_sampling_rate = 0;\r\n\r\n #currentConvolution = [];\r\n\r\n mode = 'unfiltered';\r\n\r\n sourceNode;\r\n\r\n autocorrelations = [];\r\n\r\n iirLength = 0;\r\n\r\n irLength = 0;\r\n\r\n calibrateSoundIIRPhase = 'linear';\r\n\r\n componentInvertedImpulseResponseNoBandpass = [];\r\n\r\n componentIRInTimeDomain = [];\r\n\r\n systemInvertedImpulseResponseNoBandpass = [];\r\n\r\n _calibrateSoundBackgroundSecs;\r\n\r\n _calibrateSoundSmoothOctaves;\r\n\r\n background_noise = {};\r\n\r\n numSuccessfulBackgroundCaptured;\r\n\r\n _calibrateSoundBurstDb;\r\n\r\n _calibrateSoundBurstFilteredExtraDb;\r\n\r\n _calibrateSoundBurstLevelReTBool;\r\n\r\n SDofFilteredRange = {\r\n mls: undefined,\r\n component: undefined,\r\n system: undefined,\r\n };\r\n\r\n transducerType = 'Loudspeaker';\r\n\r\n componentIRPhase = [];\r\n\r\n systemIRPhase = [];\r\n\r\n webAudioDeviceNames = {loudspeaker: '', microphone: '', loudspeakerText: '', microphoneText: ''};\r\n\r\n waveforms = {\r\n volume: {},\r\n };\r\n\r\n recordingChecks = {\r\n volume: {},\r\n unfiltered: [],\r\n system: [],\r\n component: [],\r\n warnings:[]\r\n };\r\n\r\n inDB;\r\n\r\n soundCheck = '';\r\n\r\n filteredMLSRange = {\r\n component: {\r\n Min: null,\r\n Max: null,\r\n },\r\n system: {\r\n Min: null,\r\n Max: null,\r\n },\r\n };\r\n\r\n /** @private */\r\n timeStamp = [];\r\n\r\n restartCalibration = false;\r\n\r\n calibrateSoundLimit = 1;\r\n\r\n filteredMLSAttenuation = {\r\n component: 1,\r\n system: 1,\r\n maxAbsSystem: 1,\r\n maxAbsComponent: 1,\r\n };\r\n\r\n //parameter result from volume calibration\r\n T = 0;\r\n //gainDBSPL result from volume calibration\r\n gainDBSPL = 0;\r\n //not always just using _calibrateSoundBurstDb for MLS so created a new parameter\r\n power_dB = 0;\r\n\r\n //system\r\n systemAttenuatorGainDB = 0;\r\n systemFMaxHz = 0;\r\n\r\n //component\r\n componentAttentuatorGainDB = 0;\r\n componentFMaxHz = 0;\r\n\r\n dL_n;\r\n L_new_n;\r\n fs2;\r\n icapture = 0;\r\n\r\n /**generate string template that gets reevaluated as variable increases */\r\n generateTemplate = (status) => {\r\n if (this.isCalibrating) {\r\n return '';\r\n }\r\n if (this.percent_complete > 100) {\r\n this.percent_complete = 100;\r\n }\r\n let MLSsd = '';\r\n let componentSD = '';\r\n let systemSD = '';\r\n let flags = '';\r\n const reportWebAudioNames = `<strong>${this.webAudioDeviceNames.loudspeakerText} </strong> <strong>${this.webAudioDeviceNames.microphoneText} </strong>`;\r\n const samplingParamText = this.phrases.RC_SamplingHzBits[this.language].replace('111', this.sourceSamplingRate).replace('222',this.sinkSamplingRate).replace('333', this.calibrateSoundSamplingDesiredBits);\r\n const reportParameters = `${samplingParamText}`;\r\n if (this.flags) {\r\n flags = `<br> autoGainControl: ${this.flags.autoGainControl}; \r\n echoCancellation: ${this.flags.echoCancellation};\r\n noiseSuppression: ${this.flags.noiseSuppression}`;\r\n }\r\n if (this.SDofFilteredRange['mls']) {\r\n MLSsd = `<br> Recorded MLS power SD: ${this.SDofFilteredRange['mls']} dB`;\r\n }\r\n if (this.SDofFilteredRange['system']) {\r\n systemSD = `<br> Loudspeaker+Microphone correction SD: ${this.SDofFilteredRange['system']} dB`;\r\n }\r\n if (this.SDofFilteredRange['component']) {\r\n componentSD = `<br> ${this.transducerType} correction SD: ${this.SDofFilteredRange['component']} dB`;\r\n }\r\n const template = `<div style=\"display: flex; justify-content: flex-start; margin-top: 0.4rem;\"><div style=\"width: 100%; height: 20px; border: 2px solid #000; border-radius: 10px;\"><div style=\"width: ${this.percent_complete}%; height: 100%; background-color: #00aaff; border-radius: 8px;\"></div></div></div>`;\r\n return `\r\n ${reportWebAudioNames}\r\n ${reportParameters} \r\n ${MLSsd}\r\n ${systemSD}\r\n ${componentSD}\r\n ${flags}\r\n <br>${status}\r\n ${template }`;\r\n };\r\n\r\n /** increment numerator and percent for status bar */\r\n incrementStatusBar = () => {\r\n this.status_numerator += 1;\r\n this.percent_complete = (this.status_numerator / this.status_denominator) * 100;\r\n };\r\n\r\n setDeviceType = deviceType => {\r\n this.deviceType = deviceType;\r\n };\r\n\r\n setDeviceName = deviceName => {\r\n this.deviceName = deviceName;\r\n };\r\n\r\n setDeviceInfo = deviceInfo => {\r\n this.deviceInfo = deviceInfo;\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Sends all the computed impulse responses to the backend server for processing\r\n *\r\n * @returns sets the resulting inverted impulse response to the class property\r\n * @example\r\n */\r\n sendSystemImpulseResponsesToServerForProcessing = async () => {\r\n this.addTimeStamp('Compute system IIR');\r\n const computedIRs = await Promise.all(this.impulseResponses);\r\n const filteredComputedIRs = computedIRs.filter(element => {\r\n return element != undefined;\r\n }); //log any errors that are found in this step\r\n console.log('filteredComputedIRs', filteredComputedIRs);\r\n const mls = this.#mls[this.icapture];\r\n const lowHz = this.#lowHz; //gain of 1 below cutoff, need gain of 0\r\n const highHz = this.#highHz; //check error for anything other than 10 kHz\r\n const iirLength = this.iirLength;\r\n this.stepNum += 1;\r\n console.log('send impulse responses to server: ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: computing the IIR...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return await this.pyServerAPI\r\n .getSystemInverseImpulseResponseWithRetry({\r\n payload: filteredComputedIRs.slice(0, this.numCaptures),\r\n mls,\r\n lowHz,\r\n highHz,\r\n iirLength,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n mlsAmplitude: Math.pow(10, this.power_dB / 20),\r\n calibrateSoundBurstFilteredExtraDb: this._calibrateSoundBurstFilteredExtraDb,\r\n calibrateSoundIIRPhase: this.calibrateSoundIIRPhase,\r\n })\r\n .then(async res => {\r\n this.stepNum += 1;\r\n console.log('got impulse response ' + this.stepNum);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the IIR...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n this.systemInvertedImpulseResponse = res['iir'];\r\n this.systemIR = res['ir'];\r\n this.systemInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];\r\n this.systemAttenuatorGainDB = res['attenuatorGain_dB'];\r\n this.systemFMaxHz = res['fMaxHz'];\r\n await this.pyServerAPI.checkMemory();\r\n await this.pyServerAPI\r\n .getConvolution({\r\n mls,\r\n inverse_response: this.systemInvertedImpulseResponse,\r\n inverse_response_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n attenuatorGain_dB: this.systemAttenuatorGainDB,\r\n mls_amplitude: Math.pow(10, this.power_dB / 20),\r\n })\r\n .then(result => {\r\n console.log(result);\r\n this.systemConvolution = result['convolution'];\r\n this.systemConvolutionNoBandpass = result['convolution_no_bandpass'];\r\n });\r\n\r\n // attenuate the system convolution if the amplitude is greater than this.calibrateSoundLimit\r\n // find max of absolute value of system convolution\r\n\r\n const max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.systemConvolution);\r\n this.filteredMLSAttenuation.system =\r\n this.systemConvolution.reduce((a, b) => a + b ** 2, 0) / this.systemConvolution.length;\r\n this.filteredMLSAttenuation.maxAbsSystem = max;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Sends all the computed impulse responses to the backend server for processing\r\n *\r\n * @returns sets the resulting inverted impulse response to the class property\r\n * @example\r\n */\r\n sendComponentImpulseResponsesToServerForProcessing = async () => {\r\n this.addTimeStamp('Compute component IIR');\r\n const computedIRs = await Promise.all(this.impulseResponses);\r\n const filteredComputedIRs = computedIRs.filter(element => {\r\n return element != undefined;\r\n });\r\n let componentIRGains = this.componentIR['Gain'];\r\n const componentIRFreqs = this.componentIR['Freq'];\r\n //normalize the component IR gains\r\n componentIRGains = componentIRGains.map(value => {\r\n return value + this._calibrateSoundBurstScalarDB - this._calibrateSoundBurstDb;\r\n });\r\n if (this._calibrateSoundBurstNormalizeBy1000HzGainBool) {\r\n const sineGainAt1000Hz_dB = this.gainDBSPL;\r\n componentIRGains = componentIRGains.map(value => {\r\n return value - sineGainAt1000Hz_dB;\r\n });\r\n }\r\n const mls = this.#mls[this.icapture];\r\n const lowHz = this.#lowHz;\r\n const iirLength = this.iirLength;\r\n const irLength = this.irLength;\r\n const highHz = this.#highHz;\r\n this.stepNum += 1;\r\n console.log('send impulse responses to server: ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: computing the IIR...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n console.log()\r\n return this.pyServerAPI\r\n .getComponentInverseImpulseResponseWithRetry({\r\n payload: filteredComputedIRs.slice(0, this.numCaptures),\r\n mls,\r\n lowHz,\r\n highHz,\r\n iirLength,\r\n componentIRGains,\r\n componentIRFreqs,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n mlsAmplitude: Math.pow(10, this.power_dB / 20),\r\n irLength,\r\n calibrateSoundSmoothOctaves: this._calibrateSoundSmoothOctaves,\r\n calibrateSoundSmoothMinBandwidthHz: this._calibrateSoundSmoothMinBandwidthHz,\r\n calibrateSoundBurstFilteredExtraDb: this._calibrateSoundBurstFilteredExtraDb,\r\n calibrateSoundIIRPhase: this.calibrateSoundIIRPhase,\r\n })\r\n .then(async res => {\r\n this.stepNum += 1;\r\n console.log('got impulse response ' + this.stepNum);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the IIR...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n this.componentInvertedImpulseResponse = res['iir'];\r\n this.componentInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];\r\n this.componentIR['Gain'] = res['ir'];\r\n this.componentIR['Freq'] = res['frequencies'];\r\n this.componentIRPhase = res['component_angle'];\r\n this.systemIRPhase = res['system_angle'];\r\n this.componentIROrigin['Freq'] = res['frequencies'];\r\n this.componentIROrigin['Gain'] = res['irOrigin'];\r\n this.componentIRInTimeDomain = res['irTime'];\r\n this.componentAttenuatorGainDB = res['attenuatorGain_dB'];\r\n this.componentFMaxHz = res['fMaxHz'];\r\n await this.pyServerAPI.checkMemory();\r\n await this.pyServerAPI\r\n .getConvolution({\r\n mls,\r\n inverse_response: this.componentInvertedImpulseResponse,\r\n inverse_response_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n attenuatorGain_dB: this.componentAttenuatorGainDB,\r\n mls_amplitude: Math.pow(10, this.power_dB / 20),\r\n })\r\n .then(result => {\r\n console.log(result);\r\n this.componentConvolution = result['convolution'];\r\n this.componentConvolutionNoBandpass = result['convolution_no_bandpass'];\r\n });\r\n // attenuate the component convolution if the amplitude is greater than this.calibrateSoundLimit\r\n // find max of absolute value of component convolution\r\n const max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.componentConvolution);\r\n // if (max > this.calibrateSoundLimit) {\r\n // const gain = this.calibrateSoundLimit / max;\r\n // // apply gain to component convolution\r\n // this.componentConvolution = this.componentConvolution.map(value => value * gain);\r\n // this.filteredMLSAttenuation.component = gain;\r\n // }\r\n this.filteredMLSAttenuation.component =\r\n this.componentConvolution.reduce((a, b) => a + b ** 2, 0) /\r\n this.componentConvolution.length;\r\n this.filteredMLSAttenuation.maxAbsComponent = max;\r\n })\r\n .catch(err => {\r\n // this.emit('InvertedImpulseResponse', {res: false});\r\n console.error(err);\r\n });\r\n };\r\n\r\n sendBackgroundRecording = () => {\r\n const allSignals = this.getAllBackgroundRecordings();\r\n const numSignals = allSignals.length;\r\n const background_rec_whole = allSignals[numSignals - 1];\r\n const fraction = 0.5 / (this._calibrateSoundBackgroundSecs + 0.5);\r\n // Calculate the starting index for slicing the array\r\n const startIndex = Math.round(fraction * background_rec_whole.length);\r\n // Slice the array from the calculated start index to the end of the array\r\n const background_rec = background_rec_whole.slice(startIndex);\r\n console.log('Sending background recording to server for processing');\r\n this.addTimeStamp('Compute background PSD');\r\n this.pyServerAPI\r\n .getBackgroundNoisePSDWithRetry({\r\n background_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n if (this.numSuccessfulBackgroundCaptured < 1) {\r\n this.numSuccessfulBackgroundCaptured += 1;\r\n //storing all background data in background_psd object\r\n this.background_noise['x_background'] = res['x_background'];\r\n this.background_noise['y_background'] = res['y_background'];\r\n this.background_noise['recording'] = background_rec;\r\n }\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Sends the recorded signal, or a given csv string of a signal, to the back end server for processing\r\n *\r\n * @param {<array>String} signalCsv - Optional csv string of a previously recorded signal, if given, this signal will be processed\r\n * @example\r\n */\r\n sendRecordingToServerForProcessing = async signalCsv => {\r\n const allSignals = this.getAllUnfilteredRecordedSignals();\r\n console.log(\r\n 'Obtaining last all hz unfiltered recording from #allHzUnfilteredRecordings to send to server for processing'\r\n );\r\n const numSignals = allSignals.length;\r\n const mls = this.#mlsBufferView[this.icapture];\r\n const payload =\r\n signalCsv && signalCsv.length > 0 ? (0,_utils__WEBPACK_IMPORTED_MODULE_1__.csvToArray)(signalCsv) : allSignals[numSignals - 1];\r\n console.log('sending rec');\r\n this.stepNum += 1;\r\n console.log('send rec ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration Step: computing the IR of the last recording...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n if (this.isCalibrating) return null;\r\n await this.pyServerAPI\r\n .allHzPowerCheck({\r\n payload,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n binDesiredSec: this._calibrateSoundPowerBinDesiredSec,\r\n burstSec: this.desired_time_per_mls,\r\n repeats: this.numMLSPerCapture - this.num_mls_to_skip,\r\n warmUp: this.num_mls_to_skip \r\n })\r\n .then(async result => {\r\n if (result) {\r\n if (result['sd'] > this._calibrateSoundBurstMaxSD_dB && \r\n this.numSuccessfulCaptured == 0) {\r\n console.log('SD: ' + result['sd'] + ', greater than _calibrateSoundBurstMaxSD_dB: ' + this._calibrateSoundBurstMaxSD_dB);\r\n this.recordingChecks['unfiltered'].push(result);\r\n this.clearLastUnfilteredRecordedSignals();\r\n this.numSuccessfulCaptured +=1;\r\n } else {\r\n if (result['sd'] <= this._calibrateSoundBurstMaxSD_dB) {\r\n console.log('SD: ' + result['sd'] + ', less than _calibrateSoundBurstMaxSD_dB: ' + this._calibrateSoundBurstMaxSD_dB);\r\n } else {\r\n console.log('SD: ' + result['sd'] + ', greater than _calibrateSoundBurstMaxSD_dB: ' + this._calibrateSoundBurstMaxSD_dB);\r\n this.recordingChecks['warnings'].push(`All Hz. Re-recorded ${this.inDB} dB because SD ${result['sd']} > ${this._calibrateSoundBurstMaxSD_dB} dB`);\r\n this.status = this.generateTemplate(`All Hz: Re-recording at ${this.inDB} dB because SD ${result['sd']} > ${this._calibrateSoundBurstMaxSD_dB} dB`.toString()).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n }\r\n if (this.numSuccessfulCaptured == 1) {\r\n console.log('pop last unfiltered mls volume check');\r\n this.recordingChecks['unfiltered'].pop();\r\n }\r\n this.recordingChecks['unfiltered'].push(result);\r\n // let start = new Date().getTime() / 1000;\r\n // const payloadT = tf.tensor1d(payload);\r\n // payloadT.print();\r\n // const xfft = payloadT.rfft(); // tf.spe\r\n // xfft.array().then(array => {\r\n // console.log(\"fft:\", array);\r\n // let setItem = new Set(array);\r\n // console.log(\"all zero\", setItem.size === 1 && setItem.has(0));\r\n // });\r\n // console.log(\"dimention:\", xfft.shape);\r\n // let end = new Date().getTime() / 1000;\r\n // console.log(\"Time taken:\", end - start, \"seconds\");\r\n console.log('start calculate impulse response');\r\n const usedPeriodStart = this.num_mls_to_skip * this.sourceSamplingRate;\r\n const payload_skipped_warmUp = payload.slice(usedPeriodStart);\r\n await this.pyServerAPI\r\n .getAutocorrelation({\r\n mls:mls,\r\n payload: payload_skipped_warmUp,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n numPeriods: this.numMLSPerCapture - this.num_mls_to_skip,\r\n })\r\n .then(async res => {\r\n this.autocorrelations.push(res['autocorrelation']);\r\n this.fs2 = res['fs2'];\r\n this.L_new_n = res['L_new_n'];\r\n this.dL_n = res['dL_n'];\r\n this.impulseResponses.push(\r\n await this.pyServerAPI\r\n .getImpulseResponse({\r\n mls,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n numPeriods: this.numMLSPerCapture - this.num_mls_to_skip,\r\n sig: payload_skipped_warmUp,\r\n fs2: this.fs2,\r\n L_new_n: this.L_new_n,\r\n dL_n: this.dL_n,\r\n })\r\n .then(res => {\r\n this.numSuccessfulCaptured += 2;\r\n this.stepNum += 1;\r\n console.log('got impulse response ' + this.stepNum);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: ${this.numSuccessfulCaptured}/${this.numCaptures} IRs computed...`.toString()).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n return res['ir'];\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n })\r\n );\r\n });\r\n }\r\n console.log('number of unfiltered recording checks:' + this.recordingChecks['unfiltered'].length);\r\n }\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n };\r\n\r\n /**\r\n * Passed to the calibration steps function, awaits the desired amount of seconds to capture the desired number\r\n * of MLS periods defined in the constructor.\r\n *\r\n * @example\r\n */\r\n #awaitDesiredMLSLength = async () => {\r\n // seconds per MLS = P / SR\r\n // await N * P / SR\r\n this.stepNum += 1;\r\n console.log('await desired length ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: sampling the calibration signal...`.toString() +\r\n `\\niteration ${this.stepNum}`);\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n let time_to_wait = 0;\r\n if (this.mode === 'unfiltered') {\r\n //unfiltered\r\n time_to_wait = (this.#mls[0].length / this.sourceSamplingRate) * this.numMLSPerCapture;\r\n time_to_wait = time_to_wait + this._calibrateSoundBurstPostSec;\r\n } else if (this.mode === 'filtered') {\r\n //filtered\r\n // time_to_wait =\r\n // (this.#currentConvolution.length / this.sourceSamplingRate) *\r\n // (this.numMLSPerCapture / (this.num_mls_to_skip + this.numMLSPerCapture));\r\n time_to_wait =\r\n (this.#currentConvolution.length / this.sourceSamplingRate) * this.numMLSPerCapture;\r\n time_to_wait = time_to_wait + this._calibrateSoundBurstPostSec;\r\n } else {\r\n throw new Error('Mode broke in awaitDesiredMLSLength');\r\n }\r\n\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_wait);\r\n };\r\n\r\n /**\r\n * Passed to the background noise recording function, awaits the desired amount of seconds to capture the desired number\r\n * of seconds of background noise\r\n *\r\n * @example\r\n */\r\n #awaitBackgroundNoiseRecording = async () => {\r\n console.log(\r\n 'Waiting ' + this._calibrateSoundBackgroundSecs + ' second(s) to record background noise'\r\n );\r\n let time_to_wait = this._calibrateSoundBackgroundSecs + 0.5;\r\n this.addTimeStamp(`Record ${time_to_wait.toFixed(1)} s of background.`)\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_wait);\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Passed to the calibration steps function, awaits the onset of the signal to ensure a steady state\r\n *\r\n * @example\r\n */\r\n #awaitSignalOnset = async () => {\r\n this.stepNum += 1;\r\n console.log('await signal onset ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: waiting for the signal to stabilize...`.toString());\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n let number_of_bursts_to_skip = 0;\r\n let time_to_sleep = 0;\r\n if (this.mode === 'unfiltered') {\r\n time_to_sleep = (this.#mls[0].length / this.sourceSamplingRate) * number_of_bursts_to_skip;\r\n } else if (this.mode === 'filtered') {\r\n console.log(this.#currentConvolution.length);\r\n // time_to_sleep =\r\n // (this.#currentConvolution.length / this.sourceSamplingRate) *\r\n // (number_of_bursts_to_skip / (number_of_bursts_to_skip + this.numMLSPerCapture));\r\n time_to_sleep =\r\n (this.#currentConvolution.length / this.sourceSamplingRate) * number_of_bursts_to_skip;\r\n } else {\r\n throw new Error('Mode broke in awaitSignalOnset');\r\n }\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_sleep);\r\n };\r\n\r\n /**\r\n * Called immediately after a recording is captured. Used to process the resulting signal\r\n * whether by sending the result to a server or by computing a result locally.\r\n *\r\n * @example\r\n */\r\n #afterMLSRecord = async () => {\r\n console.log('after record');\r\n this.addTimeStamp(`Send unfiltered MLS to the server`);\r\n await this.sendRecordingToServerForProcessing();\r\n };\r\n\r\n #afterMLSwIIRRecord = async () => {\r\n await this.checkPowerVariation();\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Created an S Curver Buffer to taper the signal onset\r\n *\r\n * @param {*} onSetBool\r\n * @returns\r\n * @example\r\n */\r\n createSCurveBuffer = (onSetBool = true) => {\r\n const curve = new Float32Array(this.TAPER_SECS * this.sourceSamplingRate + 1);\r\n const frequency = 1 / (4 * this.TAPER_SECS);\r\n let j = 0;\r\n for (let i = 0; i < this.TAPER_SECS * this.sourceSamplingRate + 1; i += 1) {\r\n const phase = 2 * Math.PI * frequency * j;\r\n const onsetTaper = Math.pow(Math.sin(phase), 2);\r\n const offsetTaper = Math.pow(Math.cos(phase), 2);\r\n curve[i] = onSetBool ? onsetTaper : offsetTaper;\r\n j += 1 / this.sourceSamplingRate;\r\n }\r\n return curve;\r\n };\r\n\r\n static createInverseSCurveBuffer = (length, phase) => {\r\n const curve = new Float32Array(length);\r\n let i;\r\n let j = length - 1;\r\n for (i = 0; i < length; i += 1) {\r\n // scale the curve to be between 0-1\r\n curve[i] = Math.sin((Math.PI * j) / length - phase) / 2 + 0.5;\r\n j -= 1;\r\n }\r\n return curve;\r\n };\r\n\r\n /**\r\n * Construct a Calibration Node with the calibration parameters.\r\n *\r\n * @param dataBuffer\r\n * @private\r\n * @example\r\n */\r\n #createCalibrationNodeFromBuffer = dataBuffer => {\r\n console.log('length databuffer');\r\n console.log(dataBuffer.length);\r\n if (!this.sourceAudioContext) {\r\n this.makeNewSourceAudioContext();\r\n }\r\n\r\n const buffer = this.sourceAudioContext.createBuffer(\r\n 1, // number of channels\r\n dataBuffer.length,\r\n this.sourceAudioContext.sampleRate // sample rate\r\n );\r\n\r\n const data = buffer.getChannelData(0); // get data\r\n\r\n // fill the buffer with our data\r\n try {\r\n for (let i = 0; i < dataBuffer.length; i += 1) {\r\n data[i] = dataBuffer[i];\r\n }\r\n } catch (error) {\r\n console.error(error);\r\n }\r\n\r\n this.sourceNode = this.sourceAudioContext.createBufferSource();\r\n\r\n this.sourceNode.buffer = buffer;\r\n\r\n if (this.mode === 'filtered') {\r\n //used to not loop filtered\r\n this.sourceNode.loop = true;\r\n } else {\r\n this.sourceNode.loop = true;\r\n }\r\n\r\n this.sourceNode.connect(this.sourceAudioContext.destination);\r\n\r\n this.addCalibrationNode(this.sourceNode);\r\n };\r\n\r\n /**\r\n * Given a data buffer, creates the required calibration node\r\n *\r\n * @param {*} dataBufferArray\r\n * @example\r\n */\r\n #setCalibrationNodesFromBuffer = (dataBufferArray = [this.#mlsBufferView[this.icapture]]) => {\r\n if (dataBufferArray.length === 1) {\r\n this.#createCalibrationNodeFromBuffer(dataBufferArray[0]);\r\n } else {\r\n throw new Error('The length of the data buffer array must be 1');\r\n }\r\n };\r\n\r\n /**\r\n * Creates an audio context and plays it for a few seconds.\r\n *\r\n * @private\r\n * @returns - Resolves when the audio is done playing.\r\n * @example\r\n */\r\n #playCalibrationAudio = () => {\r\n this.calibrationNodes[0].start(0);\r\n this.status = ``;\r\n if (this.mode === 'unfiltered') {\r\n console.log('play calibration audio ' + this.stepNum);\r\n\r\n const pre = this._calibrateSoundBurstPreSec; \r\n const repeats = this._calibrateSoundBurstRepeats; \r\n const burst = this._calibrateSoundBurstSec; \r\n const post = this._calibrateSoundBurstPostSec; \r\n const total_dur = pre + repeats * burst + post;\r\n this.addTimeStamp(\r\n `Record ${total_dur.toFixed(1)} s of MLS ver. ${this.icapture}, unfiltered. ` +\r\n `(${pre.toFixed(1)} s pre + ${repeats}×${burst.toFixed(1)} s used + ${post.toFixed(1)} s post).`\r\n );\r\n this.status = this.generateTemplate(`All Hz Calibration: playing the calibration tone...`.toString()).toString();\r\n } else if (this.mode === 'filtered') {\r\n console.log('play convolved audio ' + this.stepNum);\r\n this.status = this.generateTemplate().toString( `All Hz Calibration: playing the convolved calibration tone...`.toString());\r\n } else {\r\n throw new Error('Mode is incorrect');\r\n }\r\n this.emit('update', {message: this.status});\r\n this.stepNum += 1;\r\n console.log('sink sampling rate');\r\n console.log(this.sinkSamplingRate);\r\n console.log('source sampling rate');\r\n console.log(this.sourceSamplingRate);\r\n console.log('sample size');\r\n console.log(this.sampleSize);\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Stops the audio with tapered offset\r\n *\r\n * @example\r\n */\r\n stopCalibrationAudio = () => {\r\n if (this.calibrationNodes.length === 0) {\r\n return;\r\n }\r\n this.calibrationNodes[0].stop(0);\r\n this.calibrationNodes = [];\r\n if (this.sourceNode) this.sourceNode.disconnect();\r\n this.stepNum += 1;\r\n console.log('stop calibration audio ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: stopping the calibration tone...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n };\r\n\r\n playMLSwithIIR = async (stream, convolution) => {\r\n let checkRec = false;\r\n this.mode = 'filtered';\r\n console.log('play mls with iir');\r\n //this.invertedImpulseResponse = iir\r\n\r\n await this.calibrationSteps(\r\n stream,\r\n this.#playCalibrationAudio, // play audio func (required)\r\n this.#createCalibrationNodeFromBuffer(convolution), // before play func\r\n this.#awaitSignalOnset, // before record\r\n () => this.numSuccessfulCaptured < 2,\r\n this.#awaitDesiredMLSLength, // during record\r\n this.#afterMLSwIIRRecord, // after record\r\n this.mode,\r\n checkRec\r\n );\r\n };\r\n\r\n bothSoundCheck = async stream => {\r\n let iir_ir_and_plots;\r\n this.#currentConvolution = this.componentConvolution;\r\n this.filteredMLSRange.component.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\r\n this.filteredMLSRange.component.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\r\n const pre = this._calibrateSoundBurstPreSec; \r\n const repeats = this._calibrateSoundBurstRepeats; \r\n const burst = this._calibrateSoundBurstSec; \r\n const post = this._calibrateSoundBurstPostSec; \r\n const total_dur = pre + repeats * burst + post;\r\n this.soundCheck = 'component';\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with ${this.soundCheck} IIR.”`)\r\n \r\n if (this.isCalibrating) return null;\r\n await this.playMLSwithIIR(stream, this.#currentConvolution);\r\n this.stopCalibrationAudio();\r\n let component_conv_recs = this.getAllFilteredRecordedSignals();\r\n\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttentuatorGainDB / 20);\r\n component_conv_recs = component_conv_recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n\r\n let return_component_conv_rec = component_conv_recs[component_conv_recs.length - 1];\r\n this.clearAllFilteredRecordedSignals();\r\n\r\n this.numSuccessfulCaptured = 0;\r\n this.#currentConvolution = this.systemConvolution;\r\n this.filteredMLSRange.system.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\r\n this.filteredMLSRange.system.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\r\n this.soundCheck = 'system';\r\n\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with ${this.soundCheck} IIR.”`)\r\n\r\n\r\n if (this.isCalibrating) return null;\r\n await this.playMLSwithIIR(stream, this.#currentConvolution);\r\n\r\n this.stopCalibrationAudio();\r\n\r\n let system_conv_recs = this.getAllFilteredRecordedSignals();\r\n\r\n if (this.systemAttenuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.systemAttenuatorGainDB / 20);\r\n system_conv_recs = system_conv_recs.map(rec => {\r\n return rec.map(value => value / linearScaleAttenuation);\r\n });\r\n }\r\n\r\n let return_system_conv_rec = system_conv_recs[system_conv_recs.length - 1];\r\n // await this.checkPowerVariation(return_system_conv_rec);\r\n\r\n this.clearAllFilteredRecordedSignals();\r\n\r\n this.sourceAudioContext.close();\r\n let recs = this.getAllUnfilteredRecordedSignals();\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttentuatorGainDB / 20);\r\n recs = recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n let unconv_rec = recs[0];\r\n let return_unconv_rec = unconv_rec;\r\n let conv_rec = component_conv_recs[component_conv_recs.length - 1];\r\n\r\n //psd of component\r\n let knownGain = this.oldComponentIR.Gain;\r\n let knownFreq = this.oldComponentIR.Freq;\r\n let sampleRate = this.sourceSamplingRate || 96000;\r\n this.addTimeStamp('Compute PSD of MLS recording');\r\n if (this.isCalibrating) return null;\r\n let component_unconv_rec_psd = await this.pyServerAPI\r\n .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered recording (component)');\r\n if (this.isCalibrating) return null;\r\n let component_conv_rec_psd = await this.pyServerAPI\r\n .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)\r\n .then(res => {\r\n let interpolatedGain = res.x.map((freq, index) => {\r\n let i = 0;\r\n while (i < knownFreq.length && knownFreq[i] < freq) {\r\n i++;\r\n }\r\n if (i === 0 || i === knownFreq.length) {\r\n return knownGain[i];\r\n }\r\n return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.interpolate)(freq, knownFreq[i - 1], knownFreq[i], knownGain[i - 1], knownGain[i]);\r\n });\r\n\r\n let correctedGain = res.y.map(\r\n (gain, index) => 10 * Math.log10(gain) - interpolatedGain[index]\r\n );\r\n\r\n let filtered_psd = correctedGain.filter(\r\n (value, index) => res.x[index] >= this.#lowHz && res.x[index] <= this.componentFMaxHz\r\n );\r\n\r\n this.SDofFilteredRange['component'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(filtered_psd);\r\n this.incrementStatusBar();\r\n this.status =this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n conv_rec = system_conv_recs[system_conv_recs.length - 1];\r\n //psd of system\r\n this.addTimeStamp('Compute PSD of filtered recording (system) and unfiltered recording');\r\n if (this.isCalibrating) return null;\r\n let system_recs_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n let filtered_psd = res.y_conv\r\n .filter(\r\n (value, index) => res.x_conv[index] >= this.#lowHz && res.x_conv[index] <= this.#highHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n\r\n let mls_psd = res.y_unconv\r\n .filter(\r\n (value, index) =>\r\n res.x_unconv[index] >= this.#lowHz && res.x_conv[index] <= this.#highHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n\r\n this.SDofFilteredRange['mls'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(mls_psd);\r\n console.log('mls_psd', this.SDofFilteredRange['mls']);\r\n this.SDofFilteredRange['system'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(filtered_psd);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n //iir w/ and without bandpass psd. done\r\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.componentInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of component IIR and component IIR no band pass');\r\n if (this.isCalibrating) return null;\r\n let component_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.systemInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of system IIR and system IIR no band pass');\r\n if (this.isCalibrating) return null;\r\n let system_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString() ).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of MLS sequence');\r\n if (this.isCalibrating) return null;\r\n let mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.#mlsBufferView[0],\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered MLS (system)');\r\n if (this.isCalibrating) return null;\r\n let system_filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.systemConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString() ).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let system_no_bandpass_filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.systemConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status =this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered MLS (component)');\r\n if (this.isCalibrating) return null;\r\n let component_filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.componentConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString() ).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let component_no_bandpass_filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.componentConvolutionNoBandpass,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString() ).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let gainValue = this.getGainDBSPL();\r\n\r\n iir_ir_and_plots = {\r\n filtered_recording: {\r\n component: return_component_conv_rec,\r\n system: return_system_conv_rec,\r\n },\r\n unfiltered_recording: this.getAllUnfilteredRecordedSignals()[0],\r\n system: {\r\n iir: this.systemInvertedImpulseResponse,\r\n iir_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n ir: this.systemIR,\r\n iir_psd: {\r\n y: system_iir_psd['y_conv'],\r\n x: system_iir_psd['x_conv'],\r\n y_no_bandpass: system_iir_psd['y_unconv'],\r\n x_no_bandpass: system_iir_psd['x_unconv'],\r\n },\r\n filtered_mls_psd: {\r\n x: system_filtered_mls_psd['x_mls'],\r\n y: system_filtered_mls_psd['y_mls'],\r\n },\r\n filtered_no_bandpass_mls_psd: {\r\n x: system_no_bandpass_filtered_mls_psd['x_mls'],\r\n y: system_no_bandpass_filtered_mls_psd['y_mls'],\r\n },\r\n convolution: this.systemConvolution,\r\n convolutionNoBandpass: this.systemConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: system_recs_psd['x_unconv'],\r\n y: system_recs_psd['y_unconv'],\r\n },\r\n conv: {\r\n x: system_recs_psd['x_conv'],\r\n y: system_recs_psd['y_conv'],\r\n },\r\n },\r\n },\r\n component: {\r\n iir: this.componentInvertedImpulseResponse,\r\n iir_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n ir: this.componentIR,\r\n ir_origin: this.componentIROrigin,\r\n ir_in_time_domain: this.componentIRInTimeDomain,\r\n iir_psd: {\r\n y: component_iir_psd['y_conv'],\r\n x: component_iir_psd['x_conv'],\r\n y_no_bandpass: component_iir_psd['y_unconv'],\r\n x_no_bandpass: component_iir_psd['x_unconv'],\r\n },\r\n filtered_mls_psd: {\r\n x: component_filtered_mls_psd['x_mls'],\r\n y: component_filtered_mls_psd['y_mls'],\r\n },\r\n filtered_no_bandpass_mls_psd: {\r\n x: component_no_bandpass_filtered_mls_psd['x_mls'],\r\n y: component_no_bandpass_filtered_mls_psd['y_mls'],\r\n },\r\n convolution: this.componentConvolution,\r\n convolutionNoBandpass: this.componentConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: component_unconv_rec_psd['x'],\r\n y: component_unconv_rec_psd['y'],\r\n },\r\n conv: {\r\n x: component_conv_rec_psd['x'],\r\n y: component_conv_rec_psd['y'],\r\n },\r\n },\r\n gainDBSPL: gainValue,\r\n },\r\n mls: this.#mlsBufferView,\r\n mls_psd: {\r\n x: mls_psd['x_mls'],\r\n y: mls_psd['y_mls'],\r\n },\r\n autocorrelations: this.autocorrelations,\r\n impulseResponses: [],\r\n };\r\n\r\n return iir_ir_and_plots;\r\n };\r\n\r\n singleSoundCheck = async stream => {\r\n let iir_ir_and_plots;\r\n const pre = this._calibrateSoundBurstPreSec; \r\n const repeats = this._calibrateSoundBurstRepeats; \r\n const burst = this._calibrateSoundBurstSec; \r\n const post = this._calibrateSoundBurstPostSec; \r\n const total_dur = pre + repeats * burst + post;\r\n if (this._calibrateSoundCheck != 'system') {\r\n this.#currentConvolution = this.componentConvolution;\r\n this.filteredMLSRange.component.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\r\n this.filteredMLSRange.component.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\r\n this.soundCheck = 'component';\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with ${this.soundCheck} IIR.`)\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with speaker or microphone IIR.`);\r\n if (this.isCalibrating) return null;\r\n await this.playMLSwithIIR(stream, this.#currentConvolution);\r\n this.stopCalibrationAudio();\r\n } else {\r\n this.#currentConvolution = this.systemConvolution;\r\n this.filteredMLSRange.system.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\r\n this.filteredMLSRange.system.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\r\n this.soundCheck = 'system';\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with ${this.soundCheck} IIR.`)\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with speaker or microphone IIR.`);\r\n if (this.isCalibrating) return null;\r\n await this.playMLSwithIIR(stream, this.#currentConvolution);\r\n this.stopCalibrationAudio();\r\n }\r\n let conv_recs = this.getAllFilteredRecordedSignals();\r\n if (this._calibrateSoundCheck == 'goal') {\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttentuatorGainDB / 20);\r\n conv_recs = conv_recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n } else if (this._calibrateSoundCheck == 'system') {\r\n if (this.systemAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.systemAttentuatorGainDB / 20);\r\n conv_recs = conv_recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n }\r\n\r\n //remove the filteredMLSAttenuation from the recorded signals\r\n // conv_recs = conv_recs.map(rec => {\r\n // if (this.soundCheck === 'component') {\r\n // return rec.map(value => value / this.filteredMLSAttenuation.component);\r\n // }\r\n // return rec.map(value => value / this.filteredMLSAttenuation.system);\r\n // });\r\n\r\n let recs = this.getAllUnfilteredRecordedSignals();\r\n if (this._calibrateSoundCheck == 'goal') {\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttentuatorGainDB / 20);\r\n recs = recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n } else if (this._calibrateSoundCheck == 'system') {\r\n if (this.systemAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.systemAttentuatorGainDB / 20);\r\n recs = recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n }\r\n this.clearAllFilteredRecordedSignals();\r\n console.log('Obtaining unfiltered recording from #allHzUnfilteredRecordings to calculate PSD');\r\n console.log('Obtaining filtered recording from #allHzFilteredRecordings to calculate PSD');\r\n let unconv_rec = recs[0];\r\n let return_unconv_rec = unconv_rec;\r\n let conv_rec = conv_recs[conv_recs.length - 1];\r\n let return_conv_rec = conv_rec;\r\n this.sourceAudioContext.close();\r\n if (this._calibrateSoundCheck != 'system') {\r\n let knownGain = this.oldComponentIR.Gain;\r\n let knownFreq = this.oldComponentIR.Freq;\r\n let sampleRate = this.sourceSamplingRate || 96000;\r\n this.addTimeStamp('Compute PSD of MLS recording');\r\n if (this.isCalibrating) return null;\r\n let unconv_results = await this.pyServerAPI\r\n .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)\r\n .then(res => {\r\n console.log(res);\r\n let mls_psd = res.y\r\n .filter(\r\n (value, index) => res.x[index] >= this.#lowHz && res.x[index] <= this.systemFMaxHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n this.SDofFilteredRange['mls'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(mls_psd);\r\n console.log('mls sd', this.SDofFilteredRange['mls']);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD recording of filtered recording (component)');\r\n if (this.isCalibrating) return null;\r\n let conv_results = await this.pyServerAPI\r\n .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)\r\n .then(res => {\r\n let interpolatedGain = res.x.map((freq, index) => {\r\n let i = 0;\r\n while (i < knownFreq.length && knownFreq[i] < freq) {\r\n i++;\r\n }\r\n if (i === 0 || i === knownFreq.length) {\r\n return knownGain[i];\r\n }\r\n return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.interpolate)(\r\n freq,\r\n knownFreq[i - 1],\r\n knownFreq[i],\r\n knownGain[i - 1],\r\n knownGain[i]\r\n );\r\n });\r\n\r\n let correctedGain = res.y.map(\r\n (gain, index) => 10 * Math.log10(gain) - interpolatedGain[index]\r\n );\r\n let filtered_psd = correctedGain.filter(\r\n (value, index) => res.x[index] >= this.#lowHz && res.x[index] <= this.#highHz\r\n );\r\n\r\n this.SDofFilteredRange['component'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(filtered_psd);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.componentInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of component IIR and component IIR no bandpass');\r\n if (this.isCalibrating) return null;\r\n let component_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.systemInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of system IIR and system IIR no bandpass');\r\n if (this.isCalibrating) return null;\r\n let system_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of MLS sequence');\r\n if (this.isCalibrating) return null;\r\n let mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.#mlsBufferView[this.icapture],\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered MLS (component)');\r\n if (this.isCalibrating) return null;\r\n let filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.componentConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let filtered_no_bandpass_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.componentConvolutionNoBandpass,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let gainValue = this.getGainDBSPL();\r\n iir_ir_and_plots = {\r\n unfiltered_recording: return_unconv_rec,\r\n filtered_recording: return_conv_rec,\r\n system: {\r\n iir: this.systemInvertedImpulseResponse,\r\n iir_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n ir: this.systemIR,\r\n iir_psd: {\r\n y: system_iir_psd['y_conv'],\r\n x: system_iir_psd['y_conv'],\r\n y_no_bandpass: system_iir_psd['y_unconv'],\r\n x_no_bandpass: system_iir_psd['x_unconv'],\r\n },\r\n filtered_recording: [],\r\n filtered_mls_psd: {},\r\n filtered_no_bandpass_mls_psd: {},\r\n convolution: this.systemConvolution,\r\n convolutionNoBandpass: this.systemConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: [],\r\n y: [],\r\n },\r\n conv: {\r\n x: [],\r\n y: [],\r\n },\r\n },\r\n },\r\n component: {\r\n iir: this.componentInvertedImpulseResponse,\r\n iir_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n ir: this.componentIR,\r\n ir_origin: this.componentIROrigin,\r\n ir_in_time_domain: this.componentIRInTimeDomain,\r\n iir_psd: {\r\n y: component_iir_psd['y_conv'],\r\n x: component_iir_psd['x_conv'],\r\n y_no_bandpass: component_iir_psd['y_unconv'],\r\n x_no_bandpass: component_iir_psd['x_unconv'],\r\n },\r\n filtered_mls_psd: {\r\n x: filtered_mls_psd['x_mls'],\r\n y: filtered_mls_psd['y_mls'],\r\n },\r\n filtered_no_bandpass_mls_psd: {\r\n x: filtered_no_bandpass_mls_psd['x_mls'],\r\n y: filtered_no_bandpass_mls_psd['y_mls'],\r\n },\r\n convolution: this.componentConvolution,\r\n convolutionNoBandpass: this.componentConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: unconv_results['x'],\r\n y: unconv_results['y'],\r\n },\r\n conv: {\r\n x: conv_results['x'],\r\n y: conv_results['y'],\r\n },\r\n },\r\n gainDBSPL: gainValue,\r\n },\r\n mls: this.#mlsBufferView,\r\n mls_psd: {\r\n x: mls_psd['x_mls'],\r\n y: mls_psd['y_mls'],\r\n },\r\n autocorrelations: this.autocorrelations,\r\n impulseResponses: [],\r\n };\r\n } else {\r\n this.addTimeStamp('Compute PSD of filtered recording (system) and unfiltered recording');\r\n if (this.isCalibrating) return null;\r\n let results = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n let filtered_psd = res.y_conv\r\n .filter(\r\n (value, index) =>\r\n res.x_conv[index] >= this.#lowHz && res.x_conv[index] <= this.systemFMaxHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n\r\n let mls_psd = res.y_unconv\r\n .filter(\r\n (value, index) =>\r\n res.x_unconv[index] >= this.#lowHz && res.x_conv[index] <= this.systemFMaxHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n this.SDofFilteredRange['mls'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(mls_psd);\r\n this.SDofFilteredRange['system'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(filtered_psd);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n //iir w/ and without bandpass psd\r\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.componentInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of component IIR and component IIR no band pass');\r\n if (this.isCalibrating) return null;\r\n let component_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.systemInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of system IIR and system IIR no band pass');\r\n if (this.isCalibrating) return null;\r\n let system_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate( `All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of MLS sequence');\r\n if (this.isCalibrating) return null;\r\n let mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.#mlsBufferView[this.icapture],\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered MLS (system)');\r\n if (this.isCalibrating) return null;\r\n let filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.systemConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let filtered_no_bandpass_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.systemConvolutionNoBandpass,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let gainValue = this.getGainDBSPL();\r\n iir_ir_and_plots = {\r\n unfiltered_recording: return_unconv_rec,\r\n filtered_recording: return_conv_rec,\r\n system: {\r\n iir: this.systemInvertedImpulseResponse,\r\n iir_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n ir: this.systemIR,\r\n iir_psd: {\r\n y: system_iir_psd['y_conv'],\r\n x: system_iir_psd['y_conv'],\r\n y_no_bandpass: system_iir_psd['y_unconv'],\r\n x_no_bandpass: system_iir_psd['x_unconv'],\r\n },\r\n filtered_recording: [],\r\n filtered_mls_psd: {\r\n x: filtered_mls_psd['x_mls'],\r\n y: filtered_mls_psd['y_mls'],\r\n },\r\n filtered_no_bandpass_mls_psd: {\r\n x: filtered_no_bandpass_mls_psd['x_mls'],\r\n y: filtered_no_bandpass_mls_psd['y_mls'],\r\n },\r\n convolution: this.systemConvolution,\r\n convolutionNoBandpass: this.systemConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: results['x_unconv'],\r\n y: results['y_unconv'],\r\n },\r\n conv: {\r\n x: results['x_conv'],\r\n y: results['y_conv'],\r\n },\r\n },\r\n },\r\n component: {\r\n iir: this.componentInvertedImpulseResponse,\r\n iir_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n ir: this.componentIR,\r\n ir_origin: this.componentIROrigin,\r\n ir_in_time_domain: this.componentIRInTimeDomain,\r\n iir_psd: {\r\n y: component_iir_psd['y_conv'],\r\n x: component_iir_psd['x_conv'],\r\n y_no_bandpass: component_iir_psd['y_unconv'],\r\n x_no_bandpass: component_iir_psd['x_unconv'],\r\n },\r\n filtered_mls_psd: {},\r\n filtered_no_bandpass_mls_psd: {},\r\n convolution: this.componentConvolution,\r\n convolutionNoBandpass: this.componentConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: [],\r\n y: [],\r\n },\r\n conv: {\r\n x: [],\r\n y: [],\r\n },\r\n },\r\n gainDBSPL: gainValue,\r\n },\r\n mls: this.#mlsBufferView,\r\n mls_psd: {\r\n x: mls_psd['x_mls'],\r\n y: mls_psd['y_mls'],\r\n },\r\n autocorrelations: this.autocorrelations,\r\n impulseResponses: [],\r\n };\r\n }\r\n if (this.isCalibrating) return null;\r\n await Promise.all(this.impulseResponses).then(res => {\r\n for (let i = 0; i < res.length; i++) {\r\n if (res[i] != undefined) {\r\n iir_ir_and_plots['impulseResponses'].push(res[i]);\r\n }\r\n }\r\n });\r\n\r\n if (this.#download) {\r\n this.downloadSingleUnfilteredRecording();\r\n this.downloadSingleFilteredRecording();\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.#mls, 'MLS.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentConvolution, 'python_component_convolution_mls_iir.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemConvolution, 'python_system_convolution_mls_iir.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentInvertedImpulseResponse, 'componentIIR.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemInvertedImpulseResponse, 'systemIIR.csv');\r\n for (let i = 0; i < this.autocorrelations.length; i++) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.autocorrelations[i], `autocorrelation_${i}`);\r\n }\r\n const computedIRagain = await Promise.all(this.impulseResponses).then(res => {\r\n for (let i = 0; i < res.length; i++) {\r\n if (res[i] != undefined) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(res[i], `IR_${i}`);\r\n }\r\n }\r\n });\r\n }\r\n\r\n return iir_ir_and_plots;\r\n };\r\n\r\n /**\r\n * Public method to start the calibration process. Objects intialized from webassembly allocate new memory\r\n * and must be manually freed. This function is responsible for intializing the MlsGenInterface,\r\n * and wrapping the calibration steps with a garbage collection safe gaurd.\r\n *\r\n * @public\r\n * @param stream - The stream of audio from the Listener.\r\n * @example\r\n */\r\n startCalibrationImpulseResponse = async stream => {\r\n console.log('JS used memory:', performance.memory.usedJSHeapSize / 1024 / 1024, 'mb');\r\n let desired_time = this.desired_time_per_mls;\r\n let checkRec = 'allhz';\r\n\r\n console.log('MLS sequence should be of length: ' + this.sourceSamplingRate * desired_time);\r\n\r\n length = this.sourceSamplingRate * desired_time;\r\n //get mls here\r\n // const calibrateSoundBurstDb = Math.pow(10, this._calibrateSoundBurstDb / 20);\r\n\r\n this.power_dB = 0;\r\n\r\n if (!this._calibrateSoundBurstLevelReTBool) {\r\n this.power_dB = this._calibrateSoundBurstDb;\r\n } else {\r\n this.power_dB = this._calibrateSoundBurstDb + (this.T - this.gainDBSPL);\r\n }\r\n\r\n const amplitude = Math.pow(10, this.power_dB / 20);\r\n //MLSpower = Math.pow(10,this.power_dB/20);\r\n this.addTimeStamp('Compute MLS sequence');\r\n if (this.isCalibrating) return null;\r\n await this.pyServerAPI\r\n .getMLSWithRetry({\r\n length,\r\n amplitude,\r\n calibrateSoundBurstMLSVersions: this.numCaptures,\r\n })\r\n .then(res => {\r\n console.log(res);\r\n this.#mlsBufferView = res['mls'];\r\n this.#mls = res['unscaledMLS'];\r\n })\r\n .catch(err => {\r\n // this.emit('InvertedImpulseResponse', {res: false});\r\n console.error(err);\r\n });\r\n this.numSuccessfulBackgroundCaptured = 0;\r\n if (this._calibrateSoundBackgroundSecs > 0) {\r\n this.mode = 'background';\r\n this.status = this.generateTemplate(`All Hz Calibration: sampling the background noise...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n if (this.isCalibrating) return null;\r\n await this.recordBackground(\r\n stream, //stream\r\n () => this.numSuccessfulBackgroundCaptured < 1, //loop condition\r\n this.#awaitBackgroundNoiseRecording, //sleep to record\r\n this.sendBackgroundRecording, //send to get PSD\r\n this.mode,\r\n checkRec\r\n );\r\n this.incrementStatusBar();\r\n }\r\n this.mode = 'unfiltered';\r\n this.numSuccessfulCaptured = 0;\r\n\r\n if (this.isCalibrating) return null;\r\n for (var i = 0; i < this.numCaptures; i++) {\r\n this.icapture = i;\r\n await this.calibrationSteps(\r\n stream,\r\n this.#playCalibrationAudio, // play audio func (required)\r\n this.#createCalibrationNodeFromBuffer(this.#mlsBufferView[this.icapture]), // before play func\r\n this.#awaitSignalOnset, // before record\r\n () => this.numSuccessfulCaptured < 2, // loop while true\r\n this.#awaitDesiredMLSLength, // during record\r\n this.#afterMLSRecord, // after record\r\n this.mode,\r\n checkRec\r\n );\r\n this.stopCalibrationAudio();\r\n }\r\n checkRec = false;\r\n\r\n // at this stage we've captured all the required signals,\r\n // and have received IRs for each one\r\n // so let's send all the IRs to the server to be converted to a single IIR\r\n if (this.isCalibrating) return null;\r\n await this.sendSystemImpulseResponsesToServerForProcessing();\r\n await this.pyServerAPI.checkMemory();\r\n if (this.isCalibrating) return null;\r\n await this.sendComponentImpulseResponsesToServerForProcessing();\r\n\r\n this.numSuccessfulCaptured = 0;\r\n\r\n let iir_ir_and_plots;\r\n if (this._calibrateSoundCheck != 'none') {\r\n //do single check\r\n if (this._calibrateSoundCheck == 'goal' || this._calibrateSoundCheck == 'system') {\r\n if (this.isCalibrating) return null;\r\n iir_ir_and_plots = await this.singleSoundCheck(stream);\r\n if (this.isCalibrating) return null;\r\n } else {\r\n //both\r\n if (this.isCalibrating) return null;\r\n iir_ir_and_plots = await this.bothSoundCheck(stream);\r\n if (this.isCalibrating) return null;\r\n }\r\n } else {\r\n let unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\r\n let conv_rec = this.componentInvertedImpulseResponse;\r\n if (this.isCalibrating) return null;\r\n let component_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.systemInvertedImpulseResponse;\r\n if (this.isCalibrating) return null;\r\n let system_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let gainValue = this.getGainDBSPL();\r\n iir_ir_and_plots = {\r\n unfiltered_recording: return_unconv_rec,\r\n filtered_recording: return_conv_rec,\r\n system: {\r\n iir: this.systemInvertedImpulseResponse,\r\n iir_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n ir: this.systemIR,\r\n iir_psd: {\r\n y: system_iir_psd['y_conv'],\r\n x: system_iir_psd['y_conv'],\r\n y_no_bandpass: system_iir_psd['y_unconv'],\r\n x_no_bandpass: system_iir_psd['x_unconv'],\r\n },\r\n filtered_recording: [],\r\n convolution: this.systemConvolution,\r\n convolutionNoBandpass: this.systemConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: [],\r\n y: [],\r\n },\r\n conv: {\r\n x: [],\r\n y: [],\r\n },\r\n },\r\n },\r\n component: {\r\n iir: this.componentInvertedImpulseResponse,\r\n iir_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n ir: this.componentIR,\r\n ir_in_time_domain: this.componentIRInTimeDomain,\r\n iir_psd: {\r\n y: component_iir_psd['y_conv'],\r\n x: component_iir_psd['x_conv'],\r\n y_no_bandpass: component_iir_psd['y_unconv'],\r\n x_no_bandpass: component_iir_psd['x_unconv'],\r\n },\r\n convolution: this.componentConvolution,\r\n convolutionNoBandpass: this.componentConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: [],\r\n y: [],\r\n },\r\n conv: {\r\n x: [],\r\n y: [],\r\n },\r\n },\r\n gainDBSPL: gainValue,\r\n },\r\n mls: this.#mlsBufferView,\r\n autocorrelations: this.autocorrelations,\r\n impulseResponses: [],\r\n };\r\n if (this.isCalibrating) return null;\r\n await Promise.all(this.impulseResponses).then(res => {\r\n for (let i = 0; i < res.length; i++) {\r\n if (res[i] != undefined) {\r\n iir_ir_and_plots['impulseResponses'].push(res[i]);\r\n }\r\n }\r\n });\r\n\r\n if (this.#download) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.#mls, 'MLS.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentConvolution, 'python_component_convolution_mls_iir.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemConvolution, 'python_system_convolution_mls_iir.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentInvertedImpulseResponse, 'componentIIR.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemInvertedImpulseResponse, 'systemIIR.csv');\r\n for (let i = 0; i < this.autocorrelations.length; i++) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.autocorrelations[i], `autocorrelation_${i}`);\r\n }\r\n const computedIRagain = await Promise.all(this.impulseResponses).then(res => {\r\n for (let i = 0; i < res.length; i++) {\r\n if (res[i] != undefined) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(res[i], `IR_${i}`);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (this.isCalibrating) return null;\r\n this.percent_complete = 100;\r\n this.status = this.generateTemplate(`All Hz Calibration: Finished`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n\r\n //here after calibration we have the component calibration (either loudspeaker or microphone) in the same form as the componentIR\r\n //that was used to calibrate\r\n // saveToJSON(iir_ir_and_plots);\r\n return iir_ir_and_plots;\r\n };\r\n\r\n //////////////////////volume\r\n\r\n handleIncomingData = data => {\r\n console.log('Received data: ', data);\r\n if (data.type === 'soundGainDBSPL') {\r\n this.soundGainDBSPL = data.value;\r\n } else {\r\n throw new Error(`Unknown data type: ${data.type}`);\r\n }\r\n };\r\n\r\n #getTruncatedSignal = (left = 3.5, right = 4.5) => {\r\n const start = Math.floor(left * this.sourceSamplingRate);\r\n const end = Math.floor(right * this.sourceSamplingRate);\r\n const result = Array.from(this.getLastVolumeRecordedSignal().slice(start, end));\r\n console.log(\r\n 'Obtaining last 1000 hz recording from #allVolumeRecordings to send for processing'\r\n );\r\n /**\r\n * function to check that capture was properly made\r\n * @param {*} list\r\n */\r\n const checkResult = list => {\r\n const setItem = new Set(list);\r\n if (setItem.size === 1 && setItem.has(0)) {\r\n console.warn(\r\n 'The last capture failed, all recorded signal is zero',\r\n this.getAllVolumeRecordedSignals()\r\n );\r\n this.stopCalibrationAudio();\r\n this.isCalibrating = true;\r\n // restartButton.style.display = 'none';\r\n this.emit('update', {message: 'Connection failed, hit restart button to reconnect'});\r\n }\r\n if (setItem.size === 0) {\r\n console.warn('The last capture failed, no recorded signal');\r\n this.stopCalibrationAudio();\r\n this.isCalibrating = true;\r\n // restartButton.style.display = 'none';\r\n this.emit('update', {message: 'Connection failed, hit restart button to reconnect'});\r\n }\r\n };\r\n checkResult(result);\r\n return result;\r\n };\r\n\r\n /** \r\n * \r\n * \r\n Construct a calibration Node with the calibration parameters and given gain value\r\n * @param {*} gainValue\r\n * */\r\n #createCalibrationToneWithGainValue = gainValue => {\r\n const audioContext = this.makeNewSourceAudioContext();\r\n const oscilator = audioContext.createOscillator();\r\n const gainNode = audioContext.createGain();\r\n const taperGainNode = audioContext.createGain();\r\n const offsetGainNode = audioContext.createGain();\r\n const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;\r\n\r\n oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;\r\n oscilator.type = this.#CALIBRATION_TONE_TYPE;\r\n gainNode.gain.value = gainValue;\r\n\r\n oscilator.connect(gainNode);\r\n gainNode.connect(taperGainNode);\r\n const onsetCurve = this.createSCurveBuffer();\r\n taperGainNode.gain.setValueCurveAtTime(onsetCurve, 0, this.TAPER_SECS);\r\n taperGainNode.connect(offsetGainNode);\r\n const offsetCurve = this.createSCurveBuffer(false);\r\n offsetGainNode.gain.setValueCurveAtTime(\r\n offsetCurve,\r\n totalDuration - this.TAPER_SECS,\r\n this.TAPER_SECS\r\n );\r\n offsetGainNode.connect(audioContext.destination);\r\n\r\n const gainValuesOverTime = [];\r\n const sampleRate = this.#CALIBRATION_TONE_FREQUENCY; // Number of samples per second\r\n const interval = 1 / sampleRate; // Time between samples\r\n\r\n for (let t = 0; t <= totalDuration; t += interval) {\r\n let gainValueAtTime = gainValue;\r\n\r\n // Apply the onset curve\r\n if (t < this.TAPER_SECS) {\r\n const onsetIndex = Math.floor((t / this.TAPER_SECS) * onsetCurve.length);\r\n gainValueAtTime *= onsetCurve[onsetIndex];\r\n }\r\n\r\n // Apply the offset curve\r\n if (t > totalDuration - this.TAPER_SECS) {\r\n const offsetTime = t - (totalDuration - this.TAPER_SECS);\r\n const offsetIndex = Math.floor((offsetTime / this.TAPER_SECS) * offsetCurve.length);\r\n gainValueAtTime *= offsetCurve[offsetIndex];\r\n }\r\n\r\n gainValuesOverTime.push(gainValueAtTime);\r\n }\r\n\r\n this.waveforms['volume'][this.inDB] = gainValuesOverTime;\r\n\r\n this.addCalibrationNode(oscilator);\r\n };\r\n\r\n /**\r\n * Construct a Calibration Node with the calibration parameters.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #createCalibrationNode = () => {\r\n const audioContext = this.makeNewSourceAudioContext();\r\n const oscilator = audioContext.createOscillator();\r\n const gainNode = audioContext.createGain();\r\n\r\n oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;\r\n oscilator.type = this.#CALIBRATION_TONE_TYPE;\r\n gainNode.gain.value = 0.04;\r\n\r\n oscilator.connect(gainNode);\r\n gainNode.connect(audioContext.destination);\r\n\r\n this.addCalibrationNode(oscilator);\r\n };\r\n\r\n #playCalibrationAudioVolume = async () => {\r\n if (this.numCalibratingRoundsCompleted==1) {\r\n this.recordingChecks['warnings'].push(`1000Hz. Re-recorded ${this.inDB} dB because SD ${(this.recordingChecks['volume'][this.inDB]['sd'])} > ${this.calibrateSound1000HzMaxSD_dB} dB`);\r\n const currentStatus = `1000 Hz: Re-recording at ${this.inDB} dB because SD \r\n ${this.recordingChecks['volume'][this.inDB]['sd']} > \r\n ${this.calibrateSound1000HzMaxSD_dB} dB`.toString();\r\n this.status = this.generateTemplate(currentStatus).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n }\r\n const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;\r\n\r\n this.calibrationNodes[0].start(0);\r\n this.calibrationNodes[0].stop(totalDuration);\r\n console.log(`Playing a buffer of ${this.CALIBRATION_TONE_DURATION} seconds of audio`);\r\n console.log(`Waiting a total of ${totalDuration} seconds`);\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(totalDuration);\r\n };\r\n\r\n stopCalibrationAudioVolume = () => {\r\n if (this.calibrationNodes.length > 0) {\r\n this.calibrationNodes[0].stop();\r\n }\r\n };\r\n\r\n #sendToServerForProcessing = async lCalib => {\r\n console.log('Sending data to server');\r\n const total_dur = this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec + this.calibrateSound1000HzPostSec;\r\n this.addTimeStamp(\r\n \"1000 Hz: recorded at \" + this.inDB + \r\n \" dB (\" + this.calibrateSound1000HzPreSec.toFixed(1) + \r\n \" s pre + \" + this.calibrateSound1000HzSec.toFixed(1) + \r\n \" s used + \" + this.calibrateSound1000HzPostSec.toFixed(1) + \r\n \" s post)\"\r\n );\r\n let left = this.calibrateSound1000HzPreSec;\r\n let right = this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec;\r\n if (this.isCalibrating) return null;\r\n this.pyServerAPI\r\n .getVolumeCalibration({\r\n sampleRate: this.sourceSamplingRate,\r\n payload: this.#getTruncatedSignal(left, right),\r\n lCalib: lCalib,\r\n })\r\n .then(res => {\r\n if (this.outDBSPL === null) {\r\n this.incrementStatusBar();\r\n this.outDBSPL = res['outDbSPL'];\r\n this.outDBSPL1000 = res['outDbSPL1000'];\r\n this.THD = res['thd'];\r\n }\r\n })\r\n .catch(err => {\r\n console.warn(err);\r\n });\r\n const rec = this.getLastVolumeRecordedSignal();\r\n console.log('pre period power: ', (0,_powerCheck__WEBPACK_IMPORTED_MODULE_2__.getPower)(rec.slice(0,this.calibrateSound1000HzPreSec * this.sourceSamplingRate)).toFixed(1));\r\n console.log('pre period power: ', \r\n (0,_powerCheck__WEBPACK_IMPORTED_MODULE_2__.getPower)(rec.slice(\r\n this.calibrateSound1000HzPreSec * this.sourceSamplingRate,\r\n (this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec)* this.sourceSamplingRate)).toFixed(1));\r\n console.log('pre period power: ', (0,_powerCheck__WEBPACK_IMPORTED_MODULE_2__.getPower)(rec.slice(\r\n (this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec)* this.sourceSamplingRate)).toFixed(1));\r\n const res = (0,_powerCheck__WEBPACK_IMPORTED_MODULE_2__.volumePowerCheck)(\r\n rec,\r\n this.sourceSamplingRate || 96000,\r\n this.calibrateSound1000HzPreSec,\r\n this.calibrateSound1000HzSec, \r\n this._calibrateSoundPowerBinDesiredSec);\r\n console.log(res);\r\n this.recordingChecks['volume'][this.inDB] = res;\r\n };\r\n\r\n startCalibrationVolume = async (stream, gainValues, lCalib, componentGainDBSPL) => {\r\n if (this.isCalibrating) return null;\r\n const trialIterations = gainValues.length;\r\n this.status_denominator += trialIterations;\r\n const thdValues = [];\r\n const inDBValues = [];\r\n let inDB = 0;\r\n const outDBSPLValues = [];\r\n const outDBSPL1000Values = [];\r\n let checkRec = 'loudest';\r\n // do one calibration that will be discarded\r\n const soundLevelToDiscard = -60;\r\n const gainToDiscard = Math.pow(10, soundLevelToDiscard / 20);\r\n this.inDB = soundLevelToDiscard;\r\n this.status = this.generateTemplate(`1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`.toString()).toString();\r\n //this.emit('update', {message: `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`});\r\n this.emit('update', {message: this.status});\r\n this.startTime = new Date().getTime();\r\n\r\n do {\r\n console.log('while loop');\r\n if (this.isCalibrating) {\r\n console.log('restart calibration');\r\n return null;\r\n }\r\n // eslint-disable-next-line no-await-in-loop\r\n await this.volumeCalibrationSteps(\r\n stream,\r\n this.#playCalibrationAudioVolume,\r\n this.#createCalibrationToneWithGainValue,\r\n this.#sendToServerForProcessing,\r\n gainToDiscard,\r\n lCalib, //todo make this a class parameter\r\n checkRec,\r\n () => {return this.recordingChecks['volume'][this.inDB]['sd']},\r\n this.calibrateSound1000HzMaxSD_dB\r\n );\r\n } while (this.outDBSPL === null);\r\n //reset the values\r\n //this.incrementStatusBar();\r\n\r\n this.outDBSPL = null;\r\n this.outDBSPL = null;\r\n this.outDBSPL1000 = null;\r\n this.THD = null;\r\n\r\n // run the calibration at different gain values provided by the user\r\n for (let i = 0; i < trialIterations; i++) {\r\n //convert gain to DB and add to inDB\r\n if (i == trialIterations - 1) {\r\n checkRec = 'loudest';\r\n }\r\n inDB = Math.log10(gainValues[i]) * 20;\r\n // precision to 1 decimal place\r\n inDB = Math.round(inDB * 10) / 10;\r\n this.inDB = inDB;\r\n inDBValues.push(inDB);\r\n console.log('next update');\r\n this.status = this.generateTemplate(`1000 Hz Calibration: Sound Level ${inDB} dB`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n do {\r\n if (this.isCalibrating) {\r\n console.log('restart calibration');\r\n return null;\r\n }\r\n // eslint-disable-next-line no-await-in-loop\r\n await this.volumeCalibrationSteps(\r\n stream,\r\n this.#playCalibrationAudioVolume,\r\n this.#createCalibrationToneWithGainValue,\r\n this.#sendToServerForProcessing,\r\n gainValues[i],\r\n lCalib, //todo make this a class parameter\r\n checkRec,\r\n () => {return this.recordingChecks?.['volume']?.[this.inDB]?.['sd'] || 0},\r\n this.calibrateSound1000HzMaxSD_dB\r\n );\r\n } while (this.outDBSPL === null);\r\n outDBSPL1000Values.push(this.outDBSPL1000);\r\n thdValues.push(this.THD);\r\n outDBSPLValues.push(this.outDBSPL);\r\n\r\n this.outDBSPL = null;\r\n this.outDBSPL1000 = null;\r\n this.THD = null;\r\n }\r\n if (this.isCalibrating) return null;\r\n // get the volume calibration parameters from the server\r\n this.addTimeStamp('Compute sound calibration parameters');\r\n\r\n const parameters = await this.pyServerAPI\r\n .getVolumeCalibrationParameters({\r\n inDBValues: inDBValues,\r\n outDBSPLValues: outDBSPL1000Values,\r\n lCalib: lCalib,\r\n componentGainDBSPL,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n return res;\r\n });\r\n if (this.isCalibrating) return null;\r\n const result = {\r\n parameters: parameters,\r\n inDBValues: inDBValues,\r\n outDBSPLValues: outDBSPLValues,\r\n outDBSPL1000Values: outDBSPL1000Values,\r\n thdValues: thdValues,\r\n };\r\n\r\n return result;\r\n };\r\n\r\n writeFrqGainToFirestore = async (speakerID, frq, gain, OEM, documentID) => {\r\n // freq and gain are too large to take samples 1 in every 100 samples\r\n // const sampledFrq = [];\r\n // const sampledGain = [];\r\n // for (let i = 0; i < frq.length; i += 100) {\r\n // sampledFrq.push(frq[i]);\r\n // sampledGain.push(gain[i]);\r\n // }\r\n\r\n const data = {Freq: frq, Gain: gain};\r\n\r\n const docRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.doc)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones', documentID);\r\n await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.updateDoc)(docRef, {\r\n linear: data,\r\n });\r\n\r\n // divide frq and gain into smaller chunks and write to firestore one chunk at a time\r\n // use arrayUnion to append to the array\r\n // const chunkSize = 600;\r\n // const chunkedFrq = [];\r\n // const chunkedGain = [];\r\n // for (let i = 0; i < frq.length; i += chunkSize) {\r\n // chunkedFrq.push(frq.slice(i, i + chunkSize));\r\n // chunkedGain.push(gain.slice(i, i + chunkSize));\r\n // }\r\n // const docRef = doc(database, 'Microphones', documentID);\r\n // for (let i = 0; i < chunkedFrq.length; i++) {\r\n // await updateDoc(docRef, {\r\n // linear: {\r\n // Freq: arrayUnion(...chunkedFrq[i]),\r\n // Gain: arrayUnion(...chunkedGain[i]),\r\n // },\r\n // });\r\n // }\r\n };\r\n // function to write frq and gain to firebase database given speakerID\r\n writeFrqGain = async (speakerID, frq, gain, OEM) => {\r\n // freq and gain are too large to take samples 1 in every 100 samples\r\n\r\n const sampledFrq = [];\r\n const sampledGain = [];\r\n for (let i = 0; i < frq.length; i += 100) {\r\n sampledFrq.push(frq[i]);\r\n sampledGain.push(gain[i]);\r\n }\r\n\r\n const data = {Freq: sampledFrq, Gain: sampledGain};\r\n\r\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], `Microphone2/${OEM}/${speakerID}/linear`), data);\r\n };\r\n\r\n // Function to Read frq and gain from firebase database given speakerID\r\n // returns an array of frq and gain if speakerID exists, returns null otherwise\r\n readFrqGainFromFirestore = async (speakerID, OEM, isDefault) => {\r\n const collectionRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.collection)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones');\r\n const q = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.query)(\r\n collectionRef,\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('ID', '==', speakerID),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('lowercaseOEM', '==', OEM),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('isDefault', '==', isDefault)\r\n );\r\n const querySnapshot = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.getDocs)(q);\r\n // if exists return the linear field of the first document\r\n if (querySnapshot.size > 0) {\r\n const timestamp = new firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.Timestamp(\r\n querySnapshot.docs[0].data().createDate.seconds,\r\n querySnapshot.docs[0].data().createDate.nanoseconds\r\n );\r\n return {\r\n ir: querySnapshot.docs[0].data().linear,\r\n createDate: timestamp.toDate(),\r\n jsonFileName: querySnapshot.docs[0].data().jsonFileName,\r\n };\r\n }\r\n return null;\r\n };\r\n readFrqGain = async (speakerID, OEM) => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/linear`));\r\n if (snapshot.exists()) {\r\n return snapshot.val();\r\n }\r\n return null;\r\n };\r\n readGainat1000HzFromFirestore = async (speakerID, OEM, isDefault) => {\r\n const collectionRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.collection)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones');\r\n const q = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.query)(\r\n collectionRef,\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('ID', '==', speakerID),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('lowercaseOEM', '==', OEM),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('isDefault', '==', isDefault)\r\n );\r\n const querySnapshot = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.getDocs)(q);\r\n // if exists return the Gain1000 field of the first document\r\n if (querySnapshot.size > 0) {\r\n return querySnapshot.docs[0].data().Gain1000;\r\n }\r\n return null;\r\n };\r\n\r\n readGainat1000Hz = async (speakerID, OEM) => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/Gain1000`));\r\n if (snapshot.exists()) {\r\n return snapshot.val();\r\n }\r\n return null;\r\n };\r\n\r\n writeGainat1000HzToFirestore = async (speakerID, gain, OEM, documentID) => {\r\n const docRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.doc)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones', documentID);\r\n await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.updateDoc)(docRef, {\r\n Gain1000: gain,\r\n });\r\n };\r\n\r\n writeGainat1000Hz = async (speakerID, gain, OEM) => {\r\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], `Microphone2/${OEM}/${speakerID}/Gain1000`), gain);\r\n };\r\n\r\n writeIsSmartPhoneToFirestore = async (speakerID, isSmartPhone, OEM) => {\r\n const collectionRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.collection)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones');\r\n const q = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.query)(\r\n collectionRef,\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('ID', '==', speakerID),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('lowercaseOEM', '==', OEM),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('isDefault', '==', true)\r\n );\r\n const querySnapshot = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.getDocs)(q);\r\n if (querySnapshot.size > 0) {\r\n const docRef = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.addDoc)(collectionRef, {isSmartPhone: isSmartPhone, isDefault: false});\r\n return docRef.id;\r\n } else {\r\n const docRef = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.addDoc)(collectionRef, {isSmartPhone: isSmartPhone, isDefault: true});\r\n return docRef.id;\r\n }\r\n };\r\n\r\n writeIsSmartPhone = async (speakerID, isSmartPhone, OEM) => {\r\n const data = {isSmartPhone: isSmartPhone};\r\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], `Microphone2/${OEM}/${speakerID}/isSmartPhone`), isSmartPhone);\r\n };\r\n\r\n writeMicrophoneInfoToFirestore = async (speakerID, micInfo, OEM, documentID) => {\r\n const docRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.doc)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones', documentID);\r\n await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.setDoc)(docRef, micInfo, {merge: true});\r\n };\r\n\r\n doesMicrophoneExistInFirestore = async (speakerID, OEM, documentID) => {\r\n const docRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.doc)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphone', OEM, speakerID, documentID);\r\n const docSnap = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.getDoc)(docRef);\r\n if (docSnap.exists()) {\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n doesMicrophoneExist = async (speakerID, OEM) => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.child)(dbRef, `Microphone2/${OEM}/${speakerID}`));\r\n if (snapshot.exists()) {\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n addMicrophoneInfo = async (speakerID, OEM, micInfo) => {\r\n // add to database if /info does not exist\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/info`));\r\n if (!snapshot.exists()) {\r\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], `Microphone2/${OEM}/${speakerID}/info`), micInfo);\r\n }\r\n };\r\n\r\n convertToDB = gain => {\r\n return Math.log10(gain) * 20;\r\n };\r\n\r\n // Function to perform linear interpolation between two points\r\n interpolate(x, x0, y0, x1, y1) {\r\n return y0 + ((x - x0) * (y1 - y0)) / (x1 - x0);\r\n }\r\n\r\n findGainatFrequency = (frequencies, gains, targetFrequency) => {\r\n // Find the index of the first frequency in the array greater than the target frequency\r\n let index = 0;\r\n while (index < frequencies.length && frequencies[index] < targetFrequency) {\r\n index++;\r\n }\r\n\r\n // Handle cases when the target frequency is outside the range of the given data\r\n if (index === 0) {\r\n return gains[0];\r\n } else if (index === frequencies.length) {\r\n return gains[gains.length - 1];\r\n } else {\r\n // Interpolate the gain based on the surrounding frequencies\r\n const x0 = frequencies[index - 1];\r\n const y0 = gains[index - 1];\r\n const x1 = frequencies[index];\r\n const y1 = gains[index];\r\n return this.interpolate(targetFrequency, x0, y0, x1, y1);\r\n }\r\n };\r\n\r\n checkPowerVariation = async () => {\r\n let recordings = this.getAllFilteredRecordedSignals();\r\n // remove filteredMLSAttenuation from the recordings\r\n\r\n // recordings = recordings.map(recording => {\r\n // if (this.soundCheck == 'component') {\r\n // return recording.map(value => value / this.filteredMLSAttenuation.component);\r\n // }\r\n // return recording.map(value => value / this.filteredMLSAttenuation.system);\r\n // });\r\n\r\n const rec = recordings[recordings.length - 1];\r\n\r\n await this.pyServerAPI\r\n .allHzPowerCheck({\r\n payload: rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n binDesiredSec: this._calibrateSoundPowerBinDesiredSec,\r\n burstSec: this.desired_time_per_mls,\r\n repeats: this.numMLSPerCapture - this.num_mls_to_skip ,\r\n warmUp: this.num_mls_to_skip \r\n })\r\n .then(result => {\r\n if (result) {\r\n if (result['sd'] > this._calibrateSoundBurstMaxSD_dB && this.numSuccessfulCaptured == 0) {\r\n console.log('filtered recording sd too high');\r\n this.recordingChecks['warnings'].push(`All Hz. Re-recorded ${this.inDB} because SD ${result['sd']} > ${this._calibrateSoundBurstMaxSD_dB} dB`);\r\n this.status = this.generateTemplate(`All Hz: Re-recording at ${this.inDB} dB because SD ${result['sd']} > ${this._calibrateSoundBurstMaxSD_dB} dB`.toString()).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n // numSuccessfulCaptured no longer to count number of successful capture but count attemps\r\n // is sd below _calibrateSoundBurstMaxSD_dB then count two attemps\r\n // else count one attemp\r\n this.numSuccessfulCaptured += 1;\r\n } else {\r\n this.recordingChecks[this.soundCheck].push(result);\r\n // Now we do at most 2 attempts if sd > _calibrateSoundBurstMaxSD_dB\r\n // Second attempt is the final\r\n if (this.numSuccessfulCaptured < 2) {\r\n this.numSuccessfulCaptured += 2;\r\n this.stepNum += 1;\r\n this.incrementStatusBar();\r\n console.log(\r\n 'after mls w iir record for some reason add numSucc capt ' + this.stepNum\r\n );\r\n this.status = this.generateTemplate(`All Hz Calibration: ${this.numSuccessfulCaptured} recording of convolved MLS captured`.toString()).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n }\r\n }\r\n }\r\n });\r\n };\r\n\r\n getGainDBSPL = () => {\r\n var freqIndex = this.componentIR.Freq.indexOf(1000);\r\n\r\n // If freqIndex is not -1 (meaning 1000 is found in the freq array)\r\n if (freqIndex !== -1) {\r\n // Get the corresponding gain value using the index\r\n var gainValue = this.componentIR.Gain[freqIndex];\r\n return gainValue;\r\n } else {\r\n console.log('Freq 1000 not found in the array.');\r\n return null;\r\n }\r\n };\r\n // Example of how to use the writeFrqGain and readFrqGain functions\r\n // writeFrqGain('speaker1', [1, 2, 3], [4, 5, 6]);\r\n // Speaker1 is the speakerID you want to write to in the database\r\n // readFrqGain('MiniDSPUMIK_1').then(data => console.log(data));\r\n // MiniDSPUMIK_1 is the speakerID with some Data in the database\r\n //adding gainDBSPL\r\n startCalibration = async (\r\n stream,\r\n gainValues,\r\n lCalib = 104.92978421490648,\r\n componentIR = null,\r\n microphoneName = 'MiniDSP-UMIK1-711-4754-vertical',\r\n _calibrateSoundCheck = 'goal', //GOAL PASSed in by default\r\n isSmartPhone = false,\r\n _calibrateSoundBurstDb = -18,\r\n _calibrateSoundBurstFilteredExtraDb = 6,\r\n _calibrateSoundBurstLevelReTBool = false,\r\n _calibrateSoundBurstUses1000HzGainBool = false,\r\n _calibrateSoundBurstRepeats = 3,\r\n _calibrateSoundBurstSec = 1,\r\n _calibrateSoundBurstPreSec = 1,\r\n _calibrateSoundBurstPostSec = 1,\r\n _calibrateSoundHz = 48000,\r\n _calibrateSoundIRSec = 0.2,\r\n _calibrateSoundIIRSec = 0.2,\r\n _calibrateSoundIIRPhase = 'linear',\r\n calibrateSound1000HzPreSec = 0.5,\r\n calibrateSound1000HzSec = 0.5,\r\n calibrateSound1000HzPostSec = 0.5,\r\n _calibrateSoundBackgroundSecs = 0,\r\n _calibrateSoundSmoothOctaves = 0.33,\r\n _calibrateSoundSmoothMinBandwidthHz = 200,\r\n _calibrateSoundPowerBinDesiredSec = 0.2,\r\n _calibrateSoundPowerDbSDToleratedDb = 1,\r\n _calibrateSoundTaperSec = 0.01,\r\n micManufacturer = '',\r\n micSerialNumber = '',\r\n micModelNumber = '',\r\n micModelName = '',\r\n calibrateMicrophonesBool,\r\n authorEmails,\r\n webAudioDeviceNames = {\r\n loudspeaker: 'loudspeaker',\r\n microphone: 'microphone',\r\n microphoneText: 'xxx XXX',\r\n },\r\n userIDs,\r\n restartButton,\r\n reminder,\r\n calibrateSoundLimit,\r\n _calibrateSoundBurstNormalizeBy1000HzGainBool = false,\r\n _calibrateSoundBurstScalarDB = 71,\r\n calibrateSound1000HzMaxSD_dB = 4,\r\n _calibrateSoundBurstMaxSD_dB = 4,\r\n calibrateSoundSamplingDesiredBits = 24,\r\n language,\r\n loudspeakerModelName='',\r\n phrases,\r\n\r\n ) => {\r\n this._calibrateSoundBurstPreSec = _calibrateSoundBurstPreSec;\r\n this._calibrateSoundBurstRepeats = _calibrateSoundBurstRepeats;\r\n this._calibrateSoundBurstSec = _calibrateSoundBurstSec;\r\n this.micModelName = micModelName;\r\n this.loudspeakerModelName = loudspeakerModelName;\r\n this.language = language;\r\n this.TAPER_SECS = _calibrateSoundTaperSec;\r\n this.calibrateSoundLimit = calibrateSoundLimit;\r\n this._calibrateSoundBurstDb = _calibrateSoundBurstDb;\r\n this._calibrateSoundBurstFilteredExtraDb = _calibrateSoundBurstFilteredExtraDb;\r\n this._calibrateSoundBurstLevelReTBool = _calibrateSoundBurstLevelReTBool;\r\n this.CALIBRATION_TONE_DURATION =\r\n calibrateSound1000HzPreSec + calibrateSound1000HzSec + calibrateSound1000HzPostSec;\r\n this.calibrateSound1000HzPreSec = calibrateSound1000HzPreSec;\r\n this.calibrateSound1000HzSec = calibrateSound1000HzSec;\r\n this.calibrateSound1000HzPostSec = calibrateSound1000HzPostSec;\r\n this.iirLength = Math.floor(_calibrateSoundIIRSec * this.sourceSamplingRate);\r\n this.irLength = Math.floor(_calibrateSoundIRSec * this.sourceSamplingRate);\r\n this.calibrateSoundIIRPhase = _calibrateSoundIIRPhase;\r\n this.num_mls_to_skip = Math.ceil(_calibrateSoundBurstPreSec / _calibrateSoundBurstSec);\r\n this._calibrateSoundBurstPostSec = _calibrateSoundBurstPostSec;\r\n this.numMLSPerCapture = _calibrateSoundBurstRepeats + this.num_mls_to_skip;\r\n this.desired_time_per_mls = _calibrateSoundBurstSec;\r\n this.desired_sampling_rate = _calibrateSoundHz;\r\n this._calibrateSoundBackgroundSecs = _calibrateSoundBackgroundSecs;\r\n this._calibrateSoundSmoothOctaves = _calibrateSoundSmoothOctaves;\r\n this._calibrateSoundSmoothMinBandwidthHz = _calibrateSoundSmoothMinBandwidthHz;\r\n this._calibrateSoundPowerBinDesiredSec = _calibrateSoundPowerBinDesiredSec;\r\n this._calibrateSoundBurstUses1000HzGainBool = _calibrateSoundBurstUses1000HzGainBool;\r\n this._calibrateSoundPowerDbSDToleratedDb = _calibrateSoundPowerDbSDToleratedDb;\r\n this._calibrateSoundBurstNormalizeBy1000HzGainBool =\r\n _calibrateSoundBurstNormalizeBy1000HzGainBool;\r\n this._calibrateSoundBurstScalarDB = _calibrateSoundBurstScalarDB;\r\n this.webAudioDeviceNames = webAudioDeviceNames;\r\n this.calibrateSoundSamplingDesiredBits = calibrateSoundSamplingDesiredBits;\r\n this.phrases = phrases;\r\n if (isSmartPhone) {\r\n const leftQuote = \"\\u201C\"; // “\r\n const rightQuote = \"\\u201D\"; // ”\r\n this.webAudioDeviceNames.microphone = this.deviceInfo.microphoneFromAPI;\r\n const quotedWebAudioMic = leftQuote + this.webAudioDeviceNames.microphone + rightQuote;\r\n const combinedMicText = this.micModelName + \" \" + quotedWebAudioMic;\r\n webAudioDeviceNames.microphoneText = this.phrases.RC_nameMicrophone[this.language]\r\n .replace(\"“xxx”\", combinedMicText)\r\n .replace(\"“XXX”\", combinedMicText);\r\n }\r\n // this.webAudioDeviceNames.microphoneText = this.webAudioDeviceNames.microphoneText\r\n // .replace('xxx', this.webAudioDeviceNames.microphone)\r\n // .replace('XXX', this.webAudioDeviceNames.microphone);\r\n //feed calibration goal here\r\n this._calibrateSoundCheck = _calibrateSoundCheck;\r\n this.calibrateSound1000HzMaxSD_dB = calibrateSound1000HzMaxSD_dB;\r\n this._calibrateSoundBurstMaxSD_dB = _calibrateSoundBurstMaxSD_dB;\r\n //check if a componentIR was given to the system, if it isn't check for the microphone. using dummy data here bc we need to\r\n //check the db based on the microphone currently connected\r\n\r\n //new lCalib found at top of calibration files *1000hz, make sure to correct\r\n //based on zeroing of 1000hz, search for \"*1000Hz\"\r\n const ID = isSmartPhone ? micModelNumber : micSerialNumber;\r\n const OEM = isSmartPhone\r\n ? micModelName === 'UMIK-1' || micModelName === 'UMIK-2'\r\n ? 'minidsp'\r\n : this.deviceInfo.OEM.toLowerCase().split(' ').join('')\r\n : micManufacturer.toLowerCase().split(' ').join('');\r\n // const ID = \"712-5669\";\r\n // const OEM = \"minidsp\";\r\n const micInfo = {\r\n micModelName: isSmartPhone ? micModelName : microphoneName,\r\n OEM: isSmartPhone\r\n ? micModelName === 'UMIK-1' || micModelName === 'UMIK-2'\r\n ? 'miniDSP'\r\n : this.deviceInfo.OEM\r\n : micManufacturer,\r\n ID: ID,\r\n createDate: new Date(),\r\n DateText: (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getCurrentTimeString)(),\r\n HardwareName: isSmartPhone ? this.deviceInfo.hardwarename : microphoneName,\r\n hardwareFamily: isSmartPhone ? this.deviceInfo.hardwarefamily : microphoneName,\r\n HardwareModel: isSmartPhone ? this.deviceInfo.hardwaremodel : microphoneName,\r\n PlatformName: isSmartPhone ? this.deviceInfo.platformname : 'N/A',\r\n PlatformVersion: isSmartPhone ? this.deviceInfo.platformversion : 'N/A',\r\n DeviceType: isSmartPhone ? this.deviceInfo.devicetype : 'N/A',\r\n ID_from_51Degrees: isSmartPhone ? this.deviceInfo.DeviceId : 'N/A',\r\n calibrateMicrophonesBool: calibrateMicrophonesBool,\r\n screenHeight: this.deviceInfo.screenHeight,\r\n screenWidth: this.deviceInfo.screenWidth,\r\n webAudioDeviceNames: {\r\n loudspeaker: this.webAudioDeviceNames.loudspeaker,\r\n microphone: this.webAudioDeviceNames.microphone,\r\n },\r\n userIDs: userIDs,\r\n lowercaseOEM: OEM.toLowerCase().split(' ').join(''),\r\n };\r\n if (calibrateMicrophonesBool) {\r\n micInfo['authorEmails'] = authorEmails;\r\n }\r\n // if undefined in micInfo, set to empty string\r\n for (const [key, value] of Object.entries(micInfo)) {\r\n if (value === undefined) {\r\n micInfo[key] = '';\r\n }\r\n }\r\n\r\n // this.writeMicrophoneInfoToFirestore(ID, micInfo, OEM, 'default');\r\n // this.addMicrophoneInfo(ID, OEM, micInfo);\r\n if (componentIR == null) {\r\n //mode 'ir'\r\n //global variable this.componentIR must be set\r\n await this.readFrqGainFromFirestore(ID, OEM, true).then(data => {\r\n if (data !== null) {\r\n this.componentIR = data.ir;\r\n micInfo['parentTimestamp'] = data.createDate ? data.createDate : new Date();\r\n micInfo['parentFilenameJSON'] = data.jsonFileName ? data.jsonFileName : '';\r\n }\r\n });\r\n\r\n // await this.readFrqGain(ID, OEM).then(data => {\r\n // return data;\r\n // });\r\n\r\n // lCalib = await this.readGainat1000Hz(ID, OEM);\r\n lCalib = await this.readGainat1000HzFromFirestore(ID, OEM, true);\r\n micInfo['gainDBSPL'] = lCalib;\r\n // this.componentGainDBSPL = this.convertToDB(lCalib);\r\n this.componentGainDBSPL = lCalib;\r\n //TODO: if this call to database is unknown, cannot perform experiment => return false\r\n if (this.componentIR == null) {\r\n this.status =\r\n `Microphone (${OEM},${ID}) is not found in the database. Please add it to the database.`.toString();\r\n this.emit('update', {message: this.status});\r\n return false;\r\n }\r\n } else {\r\n this.transducerType = 'Microphone';\r\n this.componentIR = componentIR;\r\n lCalib = this.findGainatFrequency(this.componentIR.Freq, this.componentIR.Gain, 1000);\r\n // this.componentGainDBSPL = this.convertToDB(lCalib);\r\n this.componentGainDBSPL = lCalib;\r\n // await this.writeIsSmartPhone(ID, isSmartPhone, OEM);\r\n }\r\n\r\n this.oldComponentIR = JSON.parse(JSON.stringify(this.componentIR));\r\n\r\n return await new Promise(async (resolve, reject) => {\r\n // add event listner to params.restartButton to resolve the promise with a string: 'restart'\r\n\r\n if (reminder) {\r\n reminder.style.display = '';\r\n }\r\n if (restartButton) {\r\n restartButton.style.display = '';\r\n restartButton.addEventListener('click', () => {\r\n this.stopCalibrationAudio();\r\n this.isCalibrating = true;\r\n restartButton.style.display = 'none';\r\n if (reminder) {\r\n reminder.style.display = 'none';\r\n }\r\n this.emit('update', {message: 'Restarting calibration...'});\r\n resolve('restart');\r\n });\r\n }\r\n await this.pyServerAPI.checkMemory();\r\n // calibrate volume\r\n\r\n let volumeResults = await this.startCalibrationVolume(\r\n stream,\r\n gainValues,\r\n lCalib,\r\n this.componentGainDBSPL\r\n );\r\n if (!volumeResults) return;\r\n this.T = volumeResults['parameters']['T'];\r\n this.gainDBSPL = volumeResults['parameters']['gainDBSPL'];\r\n\r\n // end calibrate volume\r\n\r\n let impulseResponseResults = await this.startCalibrationImpulseResponse(stream);\r\n if (!impulseResponseResults) return;\r\n impulseResponseResults['background_noise'] = this.background_noise;\r\n impulseResponseResults['system']['background_noise'] = this.background_noise;\r\n impulseResponseResults['component']['background_noise'] = this.background_noise;\r\n\r\n //attenuate system background noise\r\n if (this.systemAttenuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.systemAttenuatorGainDB / 20);\r\n let linearScalePowerAttenuation = Math.pow(10, this.systemAttenuatorGainDB / 10);\r\n impulseResponseResults['system']['background_noise']['recording'] = impulseResponseResults[\r\n 'background_noise'\r\n ]['recording'].map(value => value / linearScaleAttenuation);\r\n impulseResponseResults['system']['background_noise']['x_background'] =\r\n impulseResponseResults['background_noise']['x_background'];\r\n impulseResponseResults['system']['background_noise']['y_background'] =\r\n impulseResponseResults['background_noise']['y_background'].map(\r\n value => value / linearScalePowerAttenuation\r\n );\r\n }\r\n //attenuate component background noise\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttenuatorGainDB / 20);\r\n let linearScalePowerAttenuation = Math.pow(10, this.componentAttenuatorGainDB / 10);\r\n impulseResponseResults['component']['background_noise']['recording'] =\r\n impulseResponseResults['background_noise']['recording'].map(\r\n value => value / linearScaleAttenuation\r\n );\r\n impulseResponseResults['component']['background_noise']['x_background'] =\r\n impulseResponseResults['background_noise']['x_background'];\r\n impulseResponseResults['component']['background_noise']['y_background'] =\r\n impulseResponseResults['background_noise']['y_background'].map(\r\n value => value / linearScalePowerAttenuation\r\n );\r\n }\r\n impulseResponseResults['system']['attenuatorGainDB'] = this.systemAttenuatorGainDB;\r\n impulseResponseResults['component']['attenuatorGainDB'] = this.componentAttenuatorGainDB;\r\n impulseResponseResults['system']['fMaxHz'] = this.systemFMaxHz;\r\n impulseResponseResults['component']['fMaxHz'] = this.componentFMaxHz;\r\n impulseResponseResults['L_new_n'] = this.L_new_n;\r\n impulseResponseResults['fs2'] = this.fs2;\r\n\r\n if (componentIR != null) {\r\n // I corrected microphone/loudpeaker IR scale in easyeyes,\r\n // but since we write microphone IR to firestore here\r\n // we need to correct microphone IR here\r\n let correctGain =\r\n Math.round((volumeResults.parameters.gainDBSPL - this.componentGainDBSPL) * 10) / 10;\r\n\r\n let IrFreq = impulseResponseResults?.component.ir.Freq.map(freq => Math.round(freq));\r\n let IrGain = impulseResponseResults?.component?.ir.Gain;\r\n const IrGainAt1000Hz = IrGain[IrFreq.findIndex(freq => freq === 1000)];\r\n const difference = Math.round(10 * (IrGainAt1000Hz - correctGain)) / 10;\r\n IrGain = IrGain.map(gain => gain - difference);\r\n micInfo['mls'] = Number(this.SDofFilteredRange['mls']);\r\n micInfo['systemCorrectionSD'] = Number(this.SDofFilteredRange['system']);\r\n micInfo['componentCorrectionSD'] = Number(this.SDofFilteredRange['component']);\r\n console.log(typeof micInfo['componentCorrectionSD']);\r\n // const id = await this.writeIsSmartPhoneToFirestore(ID, isSmartPhone, OEM);\r\n // await this.writeMicrophoneInfoToFirestore(ID, micInfo, OEM, id);\r\n // await this.writeFrqGainToFirestore(ID, IrFreq, IrGain, OEM, id);\r\n // micInfo['gainDBSPL'] = impulseResponseResults.component.gainDBSPL;\r\n // await this.writeGainat1000HzToFirestore(ID, micInfo['gainDBSPL'], OEM, id);\r\n // await this.writeGainat1000Hz(ID, micInfo['gainDBSPL'], OEM);\r\n }\r\n const total_results = {...volumeResults, ...impulseResponseResults};\r\n total_results['filteredMLSRange'] = this.filteredMLSRange;\r\n total_results['filteredMLSAttenuation'] = this.filteredMLSAttenuation;\r\n total_results['micInfo'] = micInfo;\r\n total_results['audioInfo'] = {};\r\n total_results['audioInfo']['sinkSampleRate'] = this.sinkSamplingRate;\r\n total_results['audioInfo']['sourceSampleRate'] = this.sourceSamplingRate;\r\n total_results['audioInfo']['bitsPerSample'] = this.sampleSize;\r\n const timeStampresult = [...this.timeStamp].join('\\n');\r\n total_results['timeStamps'] = timeStampresult;\r\n total_results['recordingChecks'] = this.recordingChecks;\r\n total_results['waveforms'] = this.waveforms;\r\n total_results['component']['phase'] = this.componentIRPhase;\r\n total_results['system']['phase'] = this.systemIRPhase;\r\n total_results['qualityMetrics'] = this.SDofFilteredRange;\r\n total_results['flags'] = this.flags;\r\n console.log('total results');\r\n console.log(total_results);\r\n console.log('Time Stamps');\r\n console.log(timeStampresult);\r\n\r\n resolve(total_results);\r\n });\r\n };\r\n}\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Combination);\n\n//# sourceURL=webpack://speakerCalibrator/./src/tasks/combination/combination.js?");
515
+ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _audioCalibrator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../audioCalibrator */ \"./src/tasks/audioCalibrator.js\");\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils */ \"./src/utils.js\");\n/* harmony import */ var _powerCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../powerCheck */ \"./src/powerCheck.js\");\n/* harmony import */ var _config_firebase__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../config/firebase */ \"./src/config/firebase.js\");\n/* harmony import */ var firebase_database__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! firebase/database */ \"./node_modules/firebase/database/dist/esm/index.esm.js\");\n/* harmony import */ var firebase_firestore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! firebase/firestore */ \"./node_modules/firebase/firestore/dist/esm/index.esm.js\");\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n//import { phrases } from '../../../dist/example/i18n';\r\n\r\n/**\r\n *\r\n */\r\nclass Combination extends _audioCalibrator__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\r\n /**\r\n * Default constructor. Creates an instance with any number of paramters passed or the default parameters defined here.\r\n *\r\n * @param {Object<boolean, number, number, number>} calibratorParams - paramter object\r\n * @param {boolean} [calibratorParams.download = false] - boolean flag to download captures\r\n * @param {number} [calibratorParams.mlsOrder = 18] - order of the MLS to be generated\r\n * @param {number} [calibratorParams.numCaptures = 5] - number of captures to perform\r\n * @param {number} [calibratorParams.numMLSPerCapture = 2] - number of bursts of MLS per capture\r\n */\r\n constructor({\r\n download = false,\r\n mlsOrder = 18,\r\n numCaptures = 3,\r\n numMLSPerCapture = 2,\r\n lowHz = 20,\r\n highHz = 10000,\r\n }) {\r\n super(numCaptures, numMLSPerCapture);\r\n this.#mlsOrder = parseInt(mlsOrder, 10);\r\n this.#P = 2 ** mlsOrder - 1;\r\n this.#download = download;\r\n this.#mls = [];\r\n this.#lowHz = lowHz;\r\n this.#highHz = highHz;\r\n }\r\n\r\n /** @private */\r\n stepNum = 0;\r\n\r\n /** @private */\r\n totalSteps = 25;\r\n\r\n /** @private */\r\n #download;\r\n\r\n /** @private */\r\n #mlsGenInterface;\r\n\r\n /** @private */\r\n #mlsBufferView;\r\n\r\n /** @private */\r\n componentInvertedImpulseResponse = null;\r\n\r\n /** @private */\r\n systemInvertedImpulseResponse = null;\r\n\r\n //averaged and subtracted ir returned from calibration used to calculated iir\r\n /** @private */\r\n ir = null;\r\n\r\n /** @private */\r\n impulseResponses = [];\r\n\r\n /** @private */\r\n #mlsOrder;\r\n\r\n /** @private */\r\n #lowHz;\r\n\r\n /** @private */\r\n #highHz;\r\n\r\n /** @private */\r\n #mls;\r\n\r\n /** @private */\r\n #P;\r\n\r\n /** @private */\r\n #audioContext;\r\n\r\n /** @private */\r\n offsetGainNode;\r\n\r\n /** @private */\r\n componentConvolution;\r\n\r\n /** @private */\r\n componentConvolutionNoBandpass;\r\n\r\n /** @private */\r\n componentIROrigin = {\r\n Freq: [],\r\n Gain: [],\r\n };\r\n\r\n /** @private */\r\n systemConvolution;\r\n\r\n /** @private */\r\n systemConvolutionNoBandpass;\r\n\r\n ////////////////////////volume\r\n /** @private */\r\n #CALIBRATION_TONE_FREQUENCY = 1000; // Hz\r\n\r\n /** @private */\r\n #CALIBRATION_TONE_TYPE = 'sine';\r\n\r\n CALIBRATION_TONE_DURATION = 5; // seconds\r\n calibrateSound1000HzPreSec = 3.5;\r\n calibrateSound1000HzSec = 1.0;\r\n calibrateSound1000HzPostSec = 0.5;\r\n\r\n /** @private */\r\n outDBSPL = null;\r\n THD = null;\r\n outDBSPL1000 = null;\r\n\r\n /** @private */\r\n TAPER_SECS = 0.01; // seconds\r\n\r\n /** @private */\r\n status_denominator = 8;\r\n\r\n /** @private */\r\n status_numerator = 0;\r\n\r\n /** @private */\r\n percent_complete = 0;\r\n\r\n /** @private */\r\n status = ``;\r\n\r\n /**@private */\r\n status_literal = `<div style=\"display: flex; justify-content: center;\"><div style=\"width: 200px; height: 20px; border: 2px solid #000; border-radius: 10px;\"><div style=\"width: ${this.percent_complete}%; height: 100%; background-color: #00aaff; border-radius: 8px;\"></div></div></div>`;\r\n\r\n /**@private */\r\n componentIR = null;\r\n\r\n /**@private */\r\n oldComponentIR = null;\r\n\r\n /**@private */\r\n systemIR = null;\r\n\r\n /**@private */\r\n _calibrateSoundCheck = '';\r\n\r\n deviceType = null;\r\n\r\n deviceName = null;\r\n\r\n deviceInfo = null;\r\n\r\n desired_time_per_mls = 0;\r\n\r\n num_mls_to_skip = 0;\r\n\r\n desired_sampling_rate = 0;\r\n\r\n #currentConvolution = [];\r\n\r\n mode = 'unfiltered';\r\n\r\n sourceNode;\r\n\r\n autocorrelations = [];\r\n\r\n iirLength = 0;\r\n\r\n irLength = 0;\r\n\r\n calibrateSoundIIRPhase = 'linear';\r\n\r\n componentInvertedImpulseResponseNoBandpass = [];\r\n\r\n componentIRInTimeDomain = [];\r\n\r\n systemInvertedImpulseResponseNoBandpass = [];\r\n\r\n _calibrateSoundBackgroundSecs;\r\n\r\n _calibrateSoundSmoothOctaves;\r\n\r\n background_noise = {};\r\n\r\n numSuccessfulBackgroundCaptured;\r\n\r\n _calibrateSoundBurstDb;\r\n\r\n _calibrateSoundBurstFilteredExtraDb;\r\n\r\n _calibrateSoundBurstLevelReTBool;\r\n\r\n SDofFilteredRange = {\r\n mls: undefined,\r\n component: undefined,\r\n system: undefined,\r\n };\r\n\r\n transducerType = 'Loudspeaker';\r\n\r\n componentIRPhase = [];\r\n\r\n systemIRPhase = [];\r\n\r\n webAudioDeviceNames = {loudspeaker: '', microphone: '', loudspeakerText: '', microphoneText: ''};\r\n\r\n waveforms = {\r\n volume: {},\r\n };\r\n\r\n recordingChecks = {\r\n volume: {},\r\n unfiltered: [],\r\n system: [],\r\n component: [],\r\n warnings:[]\r\n };\r\n\r\n inDB;\r\n\r\n soundCheck = '';\r\n\r\n filteredMLSRange = {\r\n component: {\r\n Min: null,\r\n Max: null,\r\n },\r\n system: {\r\n Min: null,\r\n Max: null,\r\n },\r\n };\r\n\r\n /** @private */\r\n timeStamp = [];\r\n\r\n restartCalibration = false;\r\n\r\n calibrateSoundLimit = 1;\r\n\r\n filteredMLSAttenuation = {\r\n component: 1,\r\n system: 1,\r\n maxAbsSystem: 1,\r\n maxAbsComponent: 1,\r\n };\r\n\r\n //parameter result from volume calibration\r\n T = 0;\r\n //gainDBSPL result from volume calibration\r\n gainDBSPL = 0;\r\n //not always just using _calibrateSoundBurstDb for MLS so created a new parameter\r\n power_dB = 0;\r\n\r\n //system\r\n systemAttenuatorGainDB = 0;\r\n systemFMaxHz = 0;\r\n\r\n //component\r\n componentAttentuatorGainDB = 0;\r\n componentFMaxHz = 0;\r\n\r\n dL_n;\r\n L_new_n;\r\n fs2;\r\n icapture = 0;\r\n\r\n /**generate string template that gets reevaluated as variable increases */\r\n generateTemplate = (status) => {\r\n if (this.isCalibrating) {\r\n return '';\r\n }\r\n if (this.percent_complete > 100) {\r\n this.percent_complete = 100;\r\n }\r\n let MLSsd = '';\r\n let componentSD = '';\r\n let systemSD = '';\r\n let flags = '';\r\n const soundSubtitle = document.getElementById(this.soundSubtitleId);\r\n if(soundSubtitle)\r\n {\r\n const reportWebAudioNames = `${this.webAudioDeviceNames.loudspeakerText}<br/> ${this.webAudioDeviceNames.microphoneText}`;\r\n soundSubtitle.innerHTML = reportWebAudioNames;\r\n }\r\n \r\n const samplingParamText = this.phrases.RC_SamplingHzBits[this.language].replace('111', this.sourceSamplingRate).replace('222',this.sinkSamplingRate).replace('333', this.calibrateSoundSamplingDesiredBits);\r\n const reportParameters = `${samplingParamText}`;\r\n if (this.flags) {\r\n flags = `<br> autoGainControl: ${this.flags.autoGainControl}; \r\n echoCancellation: ${this.flags.echoCancellation};\r\n noiseSuppression: ${this.flags.noiseSuppression}`;\r\n }\r\n if (this.SDofFilteredRange['mls']) {\r\n MLSsd = `<br> Recorded MLS power SD: ${this.SDofFilteredRange['mls']} dB`;\r\n }\r\n if (this.SDofFilteredRange['system']) {\r\n systemSD = `<br> Loudspeaker+Microphone correction SD: ${this.SDofFilteredRange['system']} dB`;\r\n }\r\n if (this.SDofFilteredRange['component']) {\r\n componentSD = `<br> ${this.transducerType} correction SD: ${this.SDofFilteredRange['component']} dB`;\r\n }\r\n const template = `<div style=\"display: flex; justify-content: flex-start; margin-top: 0.4rem;\"><div style=\"width: 100%; height: 20px; border: 2px solid #000; border-radius: 10px;\"><div style=\"width: ${this.percent_complete}%; height: 100%; background-color: #00aaff; border-radius: 8px;\"></div></div></div>`;\r\n return `\r\n ${reportParameters} \r\n ${MLSsd}\r\n ${systemSD}\r\n ${componentSD}\r\n ${flags}\r\n <br>${status}\r\n ${template }`;\r\n };\r\n\r\n /** increment numerator and percent for status bar */\r\n incrementStatusBar = () => {\r\n this.status_numerator += 1;\r\n this.percent_complete = (this.status_numerator / this.status_denominator) * 100;\r\n };\r\n\r\n setDeviceType = deviceType => {\r\n this.deviceType = deviceType;\r\n };\r\n\r\n setDeviceName = deviceName => {\r\n this.deviceName = deviceName;\r\n };\r\n\r\n setDeviceInfo = deviceInfo => {\r\n this.deviceInfo = deviceInfo;\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Sends all the computed impulse responses to the backend server for processing\r\n *\r\n * @returns sets the resulting inverted impulse response to the class property\r\n * @example\r\n */\r\n sendSystemImpulseResponsesToServerForProcessing = async () => {\r\n this.addTimeStamp('Compute system IIR');\r\n const computedIRs = await Promise.all(this.impulseResponses);\r\n const filteredComputedIRs = computedIRs.filter(element => {\r\n return element != undefined;\r\n }); //log any errors that are found in this step\r\n console.log('filteredComputedIRs', filteredComputedIRs);\r\n const mls = this.#mls[this.icapture];\r\n const lowHz = this.#lowHz; //gain of 1 below cutoff, need gain of 0\r\n const highHz = this.#highHz; //check error for anything other than 10 kHz\r\n const iirLength = this.iirLength;\r\n this.stepNum += 1;\r\n console.log('send impulse responses to server: ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: computing the IIR...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return await this.pyServerAPI\r\n .getSystemInverseImpulseResponseWithRetry({\r\n payload: filteredComputedIRs.slice(0, this.numCaptures),\r\n mls,\r\n lowHz,\r\n highHz,\r\n iirLength,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n mlsAmplitude: Math.pow(10, this.power_dB / 20),\r\n calibrateSoundBurstFilteredExtraDb: this._calibrateSoundBurstFilteredExtraDb,\r\n calibrateSoundIIRPhase: this.calibrateSoundIIRPhase,\r\n })\r\n .then(async res => {\r\n this.stepNum += 1;\r\n console.log('got impulse response ' + this.stepNum);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the IIR...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n this.systemInvertedImpulseResponse = res['iir'];\r\n this.systemIR = res['ir'];\r\n this.systemInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];\r\n this.systemAttenuatorGainDB = res['attenuatorGain_dB'];\r\n this.systemFMaxHz = res['fMaxHz'];\r\n await this.pyServerAPI.checkMemory();\r\n await this.pyServerAPI\r\n .getConvolution({\r\n mls,\r\n inverse_response: this.systemInvertedImpulseResponse,\r\n inverse_response_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n attenuatorGain_dB: this.systemAttenuatorGainDB,\r\n mls_amplitude: Math.pow(10, this.power_dB / 20),\r\n })\r\n .then(result => {\r\n console.log(result);\r\n this.systemConvolution = result['convolution'];\r\n this.systemConvolutionNoBandpass = result['convolution_no_bandpass'];\r\n });\r\n\r\n // attenuate the system convolution if the amplitude is greater than this.calibrateSoundLimit\r\n // find max of absolute value of system convolution\r\n\r\n const max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.systemConvolution);\r\n this.filteredMLSAttenuation.system =\r\n this.systemConvolution.reduce((a, b) => a + b ** 2, 0) / this.systemConvolution.length;\r\n this.filteredMLSAttenuation.maxAbsSystem = max;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Sends all the computed impulse responses to the backend server for processing\r\n *\r\n * @returns sets the resulting inverted impulse response to the class property\r\n * @example\r\n */\r\n sendComponentImpulseResponsesToServerForProcessing = async () => {\r\n this.addTimeStamp('Compute component IIR');\r\n const computedIRs = await Promise.all(this.impulseResponses);\r\n const filteredComputedIRs = computedIRs.filter(element => {\r\n return element != undefined;\r\n });\r\n let componentIRGains = this.componentIR['Gain'];\r\n const componentIRFreqs = this.componentIR['Freq'];\r\n //normalize the component IR gains\r\n componentIRGains = componentIRGains.map(value => {\r\n return value + this._calibrateSoundBurstScalarDB - this._calibrateSoundBurstDb;\r\n });\r\n if (this._calibrateSoundBurstNormalizeBy1000HzGainBool) {\r\n const sineGainAt1000Hz_dB = this.gainDBSPL;\r\n componentIRGains = componentIRGains.map(value => {\r\n return value - sineGainAt1000Hz_dB;\r\n });\r\n }\r\n const mls = this.#mls[this.icapture];\r\n const lowHz = this.#lowHz;\r\n const iirLength = this.iirLength;\r\n const irLength = this.irLength;\r\n const highHz = this.#highHz;\r\n this.stepNum += 1;\r\n console.log('send impulse responses to server: ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: computing the IIR...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n console.log()\r\n return this.pyServerAPI\r\n .getComponentInverseImpulseResponseWithRetry({\r\n payload: filteredComputedIRs.slice(0, this.numCaptures),\r\n mls,\r\n lowHz,\r\n highHz,\r\n iirLength,\r\n componentIRGains,\r\n componentIRFreqs,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n mlsAmplitude: Math.pow(10, this.power_dB / 20),\r\n irLength,\r\n calibrateSoundSmoothOctaves: this._calibrateSoundSmoothOctaves,\r\n calibrateSoundSmoothMinBandwidthHz: this._calibrateSoundSmoothMinBandwidthHz,\r\n calibrateSoundBurstFilteredExtraDb: this._calibrateSoundBurstFilteredExtraDb,\r\n calibrateSoundIIRPhase: this.calibrateSoundIIRPhase,\r\n })\r\n .then(async res => {\r\n this.stepNum += 1;\r\n console.log('got impulse response ' + this.stepNum);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the IIR...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n this.componentInvertedImpulseResponse = res['iir'];\r\n this.componentInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];\r\n this.componentIR['Gain'] = res['ir'];\r\n this.componentIR['Freq'] = res['frequencies'];\r\n this.componentIRPhase = res['component_angle'];\r\n this.systemIRPhase = res['system_angle'];\r\n this.componentIROrigin['Freq'] = res['frequencies'];\r\n this.componentIROrigin['Gain'] = res['irOrigin'];\r\n this.componentIRInTimeDomain = res['irTime'];\r\n this.componentAttenuatorGainDB = res['attenuatorGain_dB'];\r\n this.componentFMaxHz = res['fMaxHz'];\r\n await this.pyServerAPI.checkMemory();\r\n await this.pyServerAPI\r\n .getConvolution({\r\n mls,\r\n inverse_response: this.componentInvertedImpulseResponse,\r\n inverse_response_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n attenuatorGain_dB: this.componentAttenuatorGainDB,\r\n mls_amplitude: Math.pow(10, this.power_dB / 20),\r\n })\r\n .then(result => {\r\n console.log(result);\r\n this.componentConvolution = result['convolution'];\r\n this.componentConvolutionNoBandpass = result['convolution_no_bandpass'];\r\n });\r\n // attenuate the component convolution if the amplitude is greater than this.calibrateSoundLimit\r\n // find max of absolute value of component convolution\r\n const max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.componentConvolution);\r\n // if (max > this.calibrateSoundLimit) {\r\n // const gain = this.calibrateSoundLimit / max;\r\n // // apply gain to component convolution\r\n // this.componentConvolution = this.componentConvolution.map(value => value * gain);\r\n // this.filteredMLSAttenuation.component = gain;\r\n // }\r\n this.filteredMLSAttenuation.component =\r\n this.componentConvolution.reduce((a, b) => a + b ** 2, 0) /\r\n this.componentConvolution.length;\r\n this.filteredMLSAttenuation.maxAbsComponent = max;\r\n })\r\n .catch(err => {\r\n // this.emit('InvertedImpulseResponse', {res: false});\r\n console.error(err);\r\n });\r\n };\r\n\r\n sendBackgroundRecording = () => {\r\n const allSignals = this.getAllBackgroundRecordings();\r\n const numSignals = allSignals.length;\r\n const background_rec_whole = allSignals[numSignals - 1];\r\n const fraction = 0.5 / (this._calibrateSoundBackgroundSecs + 0.5);\r\n // Calculate the starting index for slicing the array\r\n const startIndex = Math.round(fraction * background_rec_whole.length);\r\n // Slice the array from the calculated start index to the end of the array\r\n const background_rec = background_rec_whole.slice(startIndex);\r\n console.log('Sending background recording to server for processing');\r\n this.addTimeStamp('Compute background PSD');\r\n this.pyServerAPI\r\n .getBackgroundNoisePSDWithRetry({\r\n background_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n if (this.numSuccessfulBackgroundCaptured < 1) {\r\n this.numSuccessfulBackgroundCaptured += 1;\r\n //storing all background data in background_psd object\r\n this.background_noise['x_background'] = res['x_background'];\r\n this.background_noise['y_background'] = res['y_background'];\r\n this.background_noise['recording'] = background_rec;\r\n }\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Sends the recorded signal, or a given csv string of a signal, to the back end server for processing\r\n *\r\n * @param {<array>String} signalCsv - Optional csv string of a previously recorded signal, if given, this signal will be processed\r\n * @example\r\n */\r\n sendRecordingToServerForProcessing = async signalCsv => {\r\n const allSignals = this.getAllUnfilteredRecordedSignals();\r\n console.log(\r\n 'Obtaining last all hz unfiltered recording from #allHzUnfilteredRecordings to send to server for processing'\r\n );\r\n const numSignals = allSignals.length;\r\n const mls = this.#mlsBufferView[this.icapture];\r\n const payload =\r\n signalCsv && signalCsv.length > 0 ? (0,_utils__WEBPACK_IMPORTED_MODULE_1__.csvToArray)(signalCsv) : allSignals[numSignals - 1];\r\n console.log('sending rec');\r\n this.stepNum += 1;\r\n console.log('send rec ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration Step: computing the IR of the last recording...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n if (this.isCalibrating) return null;\r\n await this.pyServerAPI\r\n .allHzPowerCheck({\r\n payload,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n binDesiredSec: this._calibrateSoundPowerBinDesiredSec,\r\n burstSec: this.desired_time_per_mls,\r\n repeats: this.numMLSPerCapture - this.num_mls_to_skip,\r\n warmUp: this.num_mls_to_skip \r\n })\r\n .then(async result => {\r\n if (result) {\r\n if (result['sd'] > this._calibrateSoundBurstMaxSD_dB && \r\n this.numSuccessfulCaptured == 0) {\r\n console.log('SD: ' + result['sd'] + ', greater than _calibrateSoundBurstMaxSD_dB: ' + this._calibrateSoundBurstMaxSD_dB);\r\n this.recordingChecks['unfiltered'].push(result);\r\n this.clearLastUnfilteredRecordedSignals();\r\n this.numSuccessfulCaptured +=1;\r\n } else {\r\n if (result['sd'] <= this._calibrateSoundBurstMaxSD_dB) {\r\n console.log('SD: ' + result['sd'] + ', less than _calibrateSoundBurstMaxSD_dB: ' + this._calibrateSoundBurstMaxSD_dB);\r\n } else {\r\n console.log('SD: ' + result['sd'] + ', greater than _calibrateSoundBurstMaxSD_dB: ' + this._calibrateSoundBurstMaxSD_dB);\r\n this.recordingChecks['warnings'].push(`All Hz. Re-recorded ${this.inDB} dB because SD ${result['sd']} > ${this._calibrateSoundBurstMaxSD_dB} dB`);\r\n this.status = this.generateTemplate(`All Hz: Re-recording at ${this.inDB} dB because SD ${result['sd']} > ${this._calibrateSoundBurstMaxSD_dB} dB`.toString()).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n }\r\n if (this.numSuccessfulCaptured == 1) {\r\n console.log('pop last unfiltered mls volume check');\r\n this.recordingChecks['unfiltered'].pop();\r\n }\r\n this.recordingChecks['unfiltered'].push(result);\r\n // let start = new Date().getTime() / 1000;\r\n // const payloadT = tf.tensor1d(payload);\r\n // payloadT.print();\r\n // const xfft = payloadT.rfft(); // tf.spe\r\n // xfft.array().then(array => {\r\n // console.log(\"fft:\", array);\r\n // let setItem = new Set(array);\r\n // console.log(\"all zero\", setItem.size === 1 && setItem.has(0));\r\n // });\r\n // console.log(\"dimention:\", xfft.shape);\r\n // let end = new Date().getTime() / 1000;\r\n // console.log(\"Time taken:\", end - start, \"seconds\");\r\n console.log('start calculate impulse response');\r\n const usedPeriodStart = this.num_mls_to_skip * this.sourceSamplingRate;\r\n const payload_skipped_warmUp = payload.slice(usedPeriodStart);\r\n await this.pyServerAPI\r\n .getAutocorrelation({\r\n mls:mls,\r\n payload: payload_skipped_warmUp,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n numPeriods: this.numMLSPerCapture - this.num_mls_to_skip,\r\n })\r\n .then(async res => {\r\n this.autocorrelations.push(res['autocorrelation']);\r\n this.fs2 = res['fs2'];\r\n this.L_new_n = res['L_new_n'];\r\n this.dL_n = res['dL_n'];\r\n this.impulseResponses.push(\r\n await this.pyServerAPI\r\n .getImpulseResponse({\r\n mls,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n numPeriods: this.numMLSPerCapture - this.num_mls_to_skip,\r\n sig: payload_skipped_warmUp,\r\n fs2: this.fs2,\r\n L_new_n: this.L_new_n,\r\n dL_n: this.dL_n,\r\n })\r\n .then(res => {\r\n this.numSuccessfulCaptured += 2;\r\n this.stepNum += 1;\r\n console.log('got impulse response ' + this.stepNum);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: ${this.numSuccessfulCaptured}/${this.numCaptures} IRs computed...`.toString()).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n return res['ir'];\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n })\r\n );\r\n });\r\n }\r\n console.log('number of unfiltered recording checks:' + this.recordingChecks['unfiltered'].length);\r\n }\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n };\r\n\r\n /**\r\n * Passed to the calibration steps function, awaits the desired amount of seconds to capture the desired number\r\n * of MLS periods defined in the constructor.\r\n *\r\n * @example\r\n */\r\n #awaitDesiredMLSLength = async () => {\r\n // seconds per MLS = P / SR\r\n // await N * P / SR\r\n this.stepNum += 1;\r\n console.log('await desired length ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: sampling the calibration signal...`.toString() +\r\n `\\niteration ${this.stepNum}`);\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n let time_to_wait = 0;\r\n if (this.mode === 'unfiltered') {\r\n //unfiltered\r\n time_to_wait = (this.#mls[0].length / this.sourceSamplingRate) * this.numMLSPerCapture;\r\n time_to_wait = time_to_wait + this._calibrateSoundBurstPostSec;\r\n } else if (this.mode === 'filtered') {\r\n //filtered\r\n // time_to_wait =\r\n // (this.#currentConvolution.length / this.sourceSamplingRate) *\r\n // (this.numMLSPerCapture / (this.num_mls_to_skip + this.numMLSPerCapture));\r\n time_to_wait =\r\n (this.#currentConvolution.length / this.sourceSamplingRate) * this.numMLSPerCapture;\r\n time_to_wait = time_to_wait + this._calibrateSoundBurstPostSec;\r\n } else {\r\n throw new Error('Mode broke in awaitDesiredMLSLength');\r\n }\r\n\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_wait);\r\n };\r\n\r\n /**\r\n * Passed to the background noise recording function, awaits the desired amount of seconds to capture the desired number\r\n * of seconds of background noise\r\n *\r\n * @example\r\n */\r\n #awaitBackgroundNoiseRecording = async () => {\r\n console.log(\r\n 'Waiting ' + this._calibrateSoundBackgroundSecs + ' second(s) to record background noise'\r\n );\r\n let time_to_wait = this._calibrateSoundBackgroundSecs + 0.5;\r\n this.addTimeStamp(`Record ${time_to_wait.toFixed(1)} s of background.`)\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_wait);\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Passed to the calibration steps function, awaits the onset of the signal to ensure a steady state\r\n *\r\n * @example\r\n */\r\n #awaitSignalOnset = async () => {\r\n this.stepNum += 1;\r\n console.log('await signal onset ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: waiting for the signal to stabilize...`.toString());\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n let number_of_bursts_to_skip = 0;\r\n let time_to_sleep = 0;\r\n if (this.mode === 'unfiltered') {\r\n time_to_sleep = (this.#mls[0].length / this.sourceSamplingRate) * number_of_bursts_to_skip;\r\n } else if (this.mode === 'filtered') {\r\n console.log(this.#currentConvolution.length);\r\n // time_to_sleep =\r\n // (this.#currentConvolution.length / this.sourceSamplingRate) *\r\n // (number_of_bursts_to_skip / (number_of_bursts_to_skip + this.numMLSPerCapture));\r\n time_to_sleep =\r\n (this.#currentConvolution.length / this.sourceSamplingRate) * number_of_bursts_to_skip;\r\n } else {\r\n throw new Error('Mode broke in awaitSignalOnset');\r\n }\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_sleep);\r\n };\r\n\r\n /**\r\n * Called immediately after a recording is captured. Used to process the resulting signal\r\n * whether by sending the result to a server or by computing a result locally.\r\n *\r\n * @example\r\n */\r\n #afterMLSRecord = async () => {\r\n console.log('after record');\r\n this.addTimeStamp(`Send unfiltered MLS to the server`);\r\n await this.sendRecordingToServerForProcessing();\r\n };\r\n\r\n #afterMLSwIIRRecord = async () => {\r\n await this.checkPowerVariation();\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Created an S Curver Buffer to taper the signal onset\r\n *\r\n * @param {*} onSetBool\r\n * @returns\r\n * @example\r\n */\r\n createSCurveBuffer = (onSetBool = true) => {\r\n const curve = new Float32Array(this.TAPER_SECS * this.sourceSamplingRate + 1);\r\n const frequency = 1 / (4 * this.TAPER_SECS);\r\n let j = 0;\r\n for (let i = 0; i < this.TAPER_SECS * this.sourceSamplingRate + 1; i += 1) {\r\n const phase = 2 * Math.PI * frequency * j;\r\n const onsetTaper = Math.pow(Math.sin(phase), 2);\r\n const offsetTaper = Math.pow(Math.cos(phase), 2);\r\n curve[i] = onSetBool ? onsetTaper : offsetTaper;\r\n j += 1 / this.sourceSamplingRate;\r\n }\r\n return curve;\r\n };\r\n\r\n static createInverseSCurveBuffer = (length, phase) => {\r\n const curve = new Float32Array(length);\r\n let i;\r\n let j = length - 1;\r\n for (i = 0; i < length; i += 1) {\r\n // scale the curve to be between 0-1\r\n curve[i] = Math.sin((Math.PI * j) / length - phase) / 2 + 0.5;\r\n j -= 1;\r\n }\r\n return curve;\r\n };\r\n\r\n /**\r\n * Construct a Calibration Node with the calibration parameters.\r\n *\r\n * @param dataBuffer\r\n * @private\r\n * @example\r\n */\r\n #createCalibrationNodeFromBuffer = dataBuffer => {\r\n console.log('length databuffer');\r\n console.log(dataBuffer.length);\r\n if (!this.sourceAudioContext) {\r\n this.makeNewSourceAudioContext();\r\n }\r\n\r\n const buffer = this.sourceAudioContext.createBuffer(\r\n 1, // number of channels\r\n dataBuffer.length,\r\n this.sourceAudioContext.sampleRate // sample rate\r\n );\r\n\r\n const data = buffer.getChannelData(0); // get data\r\n\r\n // fill the buffer with our data\r\n try {\r\n for (let i = 0; i < dataBuffer.length; i += 1) {\r\n data[i] = dataBuffer[i];\r\n }\r\n } catch (error) {\r\n console.error(error);\r\n }\r\n\r\n this.sourceNode = this.sourceAudioContext.createBufferSource();\r\n\r\n this.sourceNode.buffer = buffer;\r\n\r\n if (this.mode === 'filtered') {\r\n //used to not loop filtered\r\n this.sourceNode.loop = true;\r\n } else {\r\n this.sourceNode.loop = true;\r\n }\r\n\r\n this.sourceNode.connect(this.sourceAudioContext.destination);\r\n\r\n this.addCalibrationNode(this.sourceNode);\r\n };\r\n\r\n /**\r\n * Given a data buffer, creates the required calibration node\r\n *\r\n * @param {*} dataBufferArray\r\n * @example\r\n */\r\n #setCalibrationNodesFromBuffer = (dataBufferArray = [this.#mlsBufferView[this.icapture]]) => {\r\n if (dataBufferArray.length === 1) {\r\n this.#createCalibrationNodeFromBuffer(dataBufferArray[0]);\r\n } else {\r\n throw new Error('The length of the data buffer array must be 1');\r\n }\r\n };\r\n\r\n /**\r\n * Creates an audio context and plays it for a few seconds.\r\n *\r\n * @private\r\n * @returns - Resolves when the audio is done playing.\r\n * @example\r\n */\r\n #playCalibrationAudio = () => {\r\n this.calibrationNodes[0].start(0);\r\n this.status = ``;\r\n if (this.mode === 'unfiltered') {\r\n console.log('play calibration audio ' + this.stepNum);\r\n\r\n const pre = this._calibrateSoundBurstPreSec; \r\n const repeats = this._calibrateSoundBurstRepeats; \r\n const burst = this._calibrateSoundBurstSec; \r\n const post = this._calibrateSoundBurstPostSec; \r\n const total_dur = pre + repeats * burst + post;\r\n this.addTimeStamp(\r\n `Record ${total_dur.toFixed(1)} s of MLS ver. ${this.icapture}, unfiltered. ` +\r\n `(${pre.toFixed(1)} s pre + ${repeats}×${burst.toFixed(1)} s used + ${post.toFixed(1)} s post).`\r\n );\r\n this.status = this.generateTemplate(`All Hz Calibration: playing the calibration tone...`.toString()).toString();\r\n } else if (this.mode === 'filtered') {\r\n console.log('play convolved audio ' + this.stepNum);\r\n this.status = this.generateTemplate().toString( `All Hz Calibration: playing the convolved calibration tone...`.toString());\r\n } else {\r\n throw new Error('Mode is incorrect');\r\n }\r\n this.emit('update', {message: this.status});\r\n this.stepNum += 1;\r\n console.log('sink sampling rate');\r\n console.log(this.sinkSamplingRate);\r\n console.log('source sampling rate');\r\n console.log(this.sourceSamplingRate);\r\n console.log('sample size');\r\n console.log(this.sampleSize);\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Stops the audio with tapered offset\r\n *\r\n * @example\r\n */\r\n stopCalibrationAudio = () => {\r\n if (this.calibrationNodes.length === 0) {\r\n return;\r\n }\r\n this.calibrationNodes[0].stop(0);\r\n this.calibrationNodes = [];\r\n if (this.sourceNode) this.sourceNode.disconnect();\r\n this.stepNum += 1;\r\n console.log('stop calibration audio ' + this.stepNum);\r\n this.status = this.generateTemplate(`All Hz Calibration: stopping the calibration tone...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n };\r\n\r\n playMLSwithIIR = async (stream, convolution) => {\r\n let checkRec = false;\r\n this.mode = 'filtered';\r\n console.log('play mls with iir');\r\n //this.invertedImpulseResponse = iir\r\n\r\n await this.calibrationSteps(\r\n stream,\r\n this.#playCalibrationAudio, // play audio func (required)\r\n this.#createCalibrationNodeFromBuffer(convolution), // before play func\r\n this.#awaitSignalOnset, // before record\r\n () => this.numSuccessfulCaptured < 2,\r\n this.#awaitDesiredMLSLength, // during record\r\n this.#afterMLSwIIRRecord, // after record\r\n this.mode,\r\n checkRec\r\n );\r\n };\r\n\r\n bothSoundCheck = async stream => {\r\n let iir_ir_and_plots;\r\n this.#currentConvolution = this.componentConvolution;\r\n this.filteredMLSRange.component.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\r\n this.filteredMLSRange.component.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\r\n const pre = this._calibrateSoundBurstPreSec; \r\n const repeats = this._calibrateSoundBurstRepeats; \r\n const burst = this._calibrateSoundBurstSec; \r\n const post = this._calibrateSoundBurstPostSec; \r\n const total_dur = pre + repeats * burst + post;\r\n this.soundCheck = 'component';\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with ${this.soundCheck} IIR.”`)\r\n \r\n if (this.isCalibrating) return null;\r\n await this.playMLSwithIIR(stream, this.#currentConvolution);\r\n this.stopCalibrationAudio();\r\n let component_conv_recs = this.getAllFilteredRecordedSignals();\r\n\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttentuatorGainDB / 20);\r\n component_conv_recs = component_conv_recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n\r\n let return_component_conv_rec = component_conv_recs[component_conv_recs.length - 1];\r\n this.clearAllFilteredRecordedSignals();\r\n\r\n this.numSuccessfulCaptured = 0;\r\n this.#currentConvolution = this.systemConvolution;\r\n this.filteredMLSRange.system.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\r\n this.filteredMLSRange.system.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\r\n this.soundCheck = 'system';\r\n\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with ${this.soundCheck} IIR.”`)\r\n\r\n\r\n if (this.isCalibrating) return null;\r\n await this.playMLSwithIIR(stream, this.#currentConvolution);\r\n\r\n this.stopCalibrationAudio();\r\n\r\n let system_conv_recs = this.getAllFilteredRecordedSignals();\r\n\r\n if (this.systemAttenuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.systemAttenuatorGainDB / 20);\r\n system_conv_recs = system_conv_recs.map(rec => {\r\n return rec.map(value => value / linearScaleAttenuation);\r\n });\r\n }\r\n\r\n let return_system_conv_rec = system_conv_recs[system_conv_recs.length - 1];\r\n // await this.checkPowerVariation(return_system_conv_rec);\r\n\r\n this.clearAllFilteredRecordedSignals();\r\n\r\n this.sourceAudioContext.close();\r\n let recs = this.getAllUnfilteredRecordedSignals();\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttentuatorGainDB / 20);\r\n recs = recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n let unconv_rec = recs[0];\r\n let return_unconv_rec = unconv_rec;\r\n let conv_rec = component_conv_recs[component_conv_recs.length - 1];\r\n\r\n //psd of component\r\n let knownGain = this.oldComponentIR.Gain;\r\n let knownFreq = this.oldComponentIR.Freq;\r\n let sampleRate = this.sourceSamplingRate || 96000;\r\n this.addTimeStamp('Compute PSD of MLS recording');\r\n if (this.isCalibrating) return null;\r\n let component_unconv_rec_psd = await this.pyServerAPI\r\n .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered recording (component)');\r\n if (this.isCalibrating) return null;\r\n let component_conv_rec_psd = await this.pyServerAPI\r\n .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)\r\n .then(res => {\r\n let interpolatedGain = res.x.map((freq, index) => {\r\n let i = 0;\r\n while (i < knownFreq.length && knownFreq[i] < freq) {\r\n i++;\r\n }\r\n if (i === 0 || i === knownFreq.length) {\r\n return knownGain[i];\r\n }\r\n return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.interpolate)(freq, knownFreq[i - 1], knownFreq[i], knownGain[i - 1], knownGain[i]);\r\n });\r\n\r\n let correctedGain = res.y.map(\r\n (gain, index) => 10 * Math.log10(gain) - interpolatedGain[index]\r\n );\r\n\r\n let filtered_psd = correctedGain.filter(\r\n (value, index) => res.x[index] >= this.#lowHz && res.x[index] <= this.componentFMaxHz\r\n );\r\n\r\n this.SDofFilteredRange['component'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(filtered_psd);\r\n this.incrementStatusBar();\r\n this.status =this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n conv_rec = system_conv_recs[system_conv_recs.length - 1];\r\n //psd of system\r\n this.addTimeStamp('Compute PSD of filtered recording (system) and unfiltered recording');\r\n if (this.isCalibrating) return null;\r\n let system_recs_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n let filtered_psd = res.y_conv\r\n .filter(\r\n (value, index) => res.x_conv[index] >= this.#lowHz && res.x_conv[index] <= this.#highHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n\r\n let mls_psd = res.y_unconv\r\n .filter(\r\n (value, index) =>\r\n res.x_unconv[index] >= this.#lowHz && res.x_conv[index] <= this.#highHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n\r\n this.SDofFilteredRange['mls'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(mls_psd);\r\n console.log('mls_psd', this.SDofFilteredRange['mls']);\r\n this.SDofFilteredRange['system'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(filtered_psd);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n //iir w/ and without bandpass psd. done\r\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.componentInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of component IIR and component IIR no band pass');\r\n if (this.isCalibrating) return null;\r\n let component_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.systemInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of system IIR and system IIR no band pass');\r\n if (this.isCalibrating) return null;\r\n let system_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString() ).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of MLS sequence');\r\n if (this.isCalibrating) return null;\r\n let mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.#mlsBufferView[0],\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered MLS (system)');\r\n if (this.isCalibrating) return null;\r\n let system_filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.systemConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString() ).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let system_no_bandpass_filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.systemConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status =this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered MLS (component)');\r\n if (this.isCalibrating) return null;\r\n let component_filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.componentConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString() ).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let component_no_bandpass_filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.componentConvolutionNoBandpass,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString() ).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let gainValue = this.getGainDBSPL();\r\n\r\n iir_ir_and_plots = {\r\n filtered_recording: {\r\n component: return_component_conv_rec,\r\n system: return_system_conv_rec,\r\n },\r\n unfiltered_recording: this.getAllUnfilteredRecordedSignals()[0],\r\n system: {\r\n iir: this.systemInvertedImpulseResponse,\r\n iir_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n ir: this.systemIR,\r\n iir_psd: {\r\n y: system_iir_psd['y_conv'],\r\n x: system_iir_psd['x_conv'],\r\n y_no_bandpass: system_iir_psd['y_unconv'],\r\n x_no_bandpass: system_iir_psd['x_unconv'],\r\n },\r\n filtered_mls_psd: {\r\n x: system_filtered_mls_psd['x_mls'],\r\n y: system_filtered_mls_psd['y_mls'],\r\n },\r\n filtered_no_bandpass_mls_psd: {\r\n x: system_no_bandpass_filtered_mls_psd['x_mls'],\r\n y: system_no_bandpass_filtered_mls_psd['y_mls'],\r\n },\r\n convolution: this.systemConvolution,\r\n convolutionNoBandpass: this.systemConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: system_recs_psd['x_unconv'],\r\n y: system_recs_psd['y_unconv'],\r\n },\r\n conv: {\r\n x: system_recs_psd['x_conv'],\r\n y: system_recs_psd['y_conv'],\r\n },\r\n },\r\n },\r\n component: {\r\n iir: this.componentInvertedImpulseResponse,\r\n iir_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n ir: this.componentIR,\r\n ir_origin: this.componentIROrigin,\r\n ir_in_time_domain: this.componentIRInTimeDomain,\r\n iir_psd: {\r\n y: component_iir_psd['y_conv'],\r\n x: component_iir_psd['x_conv'],\r\n y_no_bandpass: component_iir_psd['y_unconv'],\r\n x_no_bandpass: component_iir_psd['x_unconv'],\r\n },\r\n filtered_mls_psd: {\r\n x: component_filtered_mls_psd['x_mls'],\r\n y: component_filtered_mls_psd['y_mls'],\r\n },\r\n filtered_no_bandpass_mls_psd: {\r\n x: component_no_bandpass_filtered_mls_psd['x_mls'],\r\n y: component_no_bandpass_filtered_mls_psd['y_mls'],\r\n },\r\n convolution: this.componentConvolution,\r\n convolutionNoBandpass: this.componentConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: component_unconv_rec_psd['x'],\r\n y: component_unconv_rec_psd['y'],\r\n },\r\n conv: {\r\n x: component_conv_rec_psd['x'],\r\n y: component_conv_rec_psd['y'],\r\n },\r\n },\r\n gainDBSPL: gainValue,\r\n },\r\n mls: this.#mlsBufferView,\r\n mls_psd: {\r\n x: mls_psd['x_mls'],\r\n y: mls_psd['y_mls'],\r\n },\r\n autocorrelations: this.autocorrelations,\r\n impulseResponses: [],\r\n };\r\n\r\n return iir_ir_and_plots;\r\n };\r\n\r\n singleSoundCheck = async stream => {\r\n let iir_ir_and_plots;\r\n const pre = this._calibrateSoundBurstPreSec; \r\n const repeats = this._calibrateSoundBurstRepeats; \r\n const burst = this._calibrateSoundBurstSec; \r\n const post = this._calibrateSoundBurstPostSec; \r\n const total_dur = pre + repeats * burst + post;\r\n if (this._calibrateSoundCheck != 'system') {\r\n this.#currentConvolution = this.componentConvolution;\r\n this.filteredMLSRange.component.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\r\n this.filteredMLSRange.component.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\r\n this.soundCheck = 'component';\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with ${this.soundCheck} IIR.`)\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with speaker or microphone IIR.`);\r\n if (this.isCalibrating) return null;\r\n await this.playMLSwithIIR(stream, this.#currentConvolution);\r\n this.stopCalibrationAudio();\r\n } else {\r\n this.#currentConvolution = this.systemConvolution;\r\n this.filteredMLSRange.system.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\r\n this.filteredMLSRange.system.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\r\n this.soundCheck = 'system';\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with ${this.soundCheck} IIR.`)\r\n this.addTimeStamp(`Record ${total_dur} s of MLS with speaker or microphone IIR.`);\r\n if (this.isCalibrating) return null;\r\n await this.playMLSwithIIR(stream, this.#currentConvolution);\r\n this.stopCalibrationAudio();\r\n }\r\n let conv_recs = this.getAllFilteredRecordedSignals();\r\n if (this._calibrateSoundCheck == 'goal') {\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttentuatorGainDB / 20);\r\n conv_recs = conv_recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n } else if (this._calibrateSoundCheck == 'system') {\r\n if (this.systemAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.systemAttentuatorGainDB / 20);\r\n conv_recs = conv_recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n }\r\n\r\n //remove the filteredMLSAttenuation from the recorded signals\r\n // conv_recs = conv_recs.map(rec => {\r\n // if (this.soundCheck === 'component') {\r\n // return rec.map(value => value / this.filteredMLSAttenuation.component);\r\n // }\r\n // return rec.map(value => value / this.filteredMLSAttenuation.system);\r\n // });\r\n\r\n let recs = this.getAllUnfilteredRecordedSignals();\r\n if (this._calibrateSoundCheck == 'goal') {\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttentuatorGainDB / 20);\r\n recs = recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n } else if (this._calibrateSoundCheck == 'system') {\r\n if (this.systemAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.systemAttentuatorGainDB / 20);\r\n recs = recs.map(rec => {\r\n return rec.map(value => value / this.linearScaleAttenuation);\r\n });\r\n }\r\n }\r\n this.clearAllFilteredRecordedSignals();\r\n console.log('Obtaining unfiltered recording from #allHzUnfilteredRecordings to calculate PSD');\r\n console.log('Obtaining filtered recording from #allHzFilteredRecordings to calculate PSD');\r\n let unconv_rec = recs[0];\r\n let return_unconv_rec = unconv_rec;\r\n let conv_rec = conv_recs[conv_recs.length - 1];\r\n let return_conv_rec = conv_rec;\r\n this.sourceAudioContext.close();\r\n if (this._calibrateSoundCheck != 'system') {\r\n let knownGain = this.oldComponentIR.Gain;\r\n let knownFreq = this.oldComponentIR.Freq;\r\n let sampleRate = this.sourceSamplingRate || 96000;\r\n this.addTimeStamp('Compute PSD of MLS recording');\r\n if (this.isCalibrating) return null;\r\n let unconv_results = await this.pyServerAPI\r\n .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)\r\n .then(res => {\r\n console.log(res);\r\n let mls_psd = res.y\r\n .filter(\r\n (value, index) => res.x[index] >= this.#lowHz && res.x[index] <= this.systemFMaxHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n this.SDofFilteredRange['mls'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(mls_psd);\r\n console.log('mls sd', this.SDofFilteredRange['mls']);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD recording of filtered recording (component)');\r\n if (this.isCalibrating) return null;\r\n let conv_results = await this.pyServerAPI\r\n .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)\r\n .then(res => {\r\n let interpolatedGain = res.x.map((freq, index) => {\r\n let i = 0;\r\n while (i < knownFreq.length && knownFreq[i] < freq) {\r\n i++;\r\n }\r\n if (i === 0 || i === knownFreq.length) {\r\n return knownGain[i];\r\n }\r\n return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.interpolate)(\r\n freq,\r\n knownFreq[i - 1],\r\n knownFreq[i],\r\n knownGain[i - 1],\r\n knownGain[i]\r\n );\r\n });\r\n\r\n let correctedGain = res.y.map(\r\n (gain, index) => 10 * Math.log10(gain) - interpolatedGain[index]\r\n );\r\n let filtered_psd = correctedGain.filter(\r\n (value, index) => res.x[index] >= this.#lowHz && res.x[index] <= this.#highHz\r\n );\r\n\r\n this.SDofFilteredRange['component'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(filtered_psd);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.componentInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of component IIR and component IIR no bandpass');\r\n if (this.isCalibrating) return null;\r\n let component_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.systemInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of system IIR and system IIR no bandpass');\r\n if (this.isCalibrating) return null;\r\n let system_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of MLS sequence');\r\n if (this.isCalibrating) return null;\r\n let mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.#mlsBufferView[this.icapture],\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered MLS (component)');\r\n if (this.isCalibrating) return null;\r\n let filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.componentConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let filtered_no_bandpass_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.componentConvolutionNoBandpass,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let gainValue = this.getGainDBSPL();\r\n iir_ir_and_plots = {\r\n unfiltered_recording: return_unconv_rec,\r\n filtered_recording: return_conv_rec,\r\n system: {\r\n iir: this.systemInvertedImpulseResponse,\r\n iir_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n ir: this.systemIR,\r\n iir_psd: {\r\n y: system_iir_psd['y_conv'],\r\n x: system_iir_psd['y_conv'],\r\n y_no_bandpass: system_iir_psd['y_unconv'],\r\n x_no_bandpass: system_iir_psd['x_unconv'],\r\n },\r\n filtered_recording: [],\r\n filtered_mls_psd: {},\r\n filtered_no_bandpass_mls_psd: {},\r\n convolution: this.systemConvolution,\r\n convolutionNoBandpass: this.systemConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: [],\r\n y: [],\r\n },\r\n conv: {\r\n x: [],\r\n y: [],\r\n },\r\n },\r\n },\r\n component: {\r\n iir: this.componentInvertedImpulseResponse,\r\n iir_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n ir: this.componentIR,\r\n ir_origin: this.componentIROrigin,\r\n ir_in_time_domain: this.componentIRInTimeDomain,\r\n iir_psd: {\r\n y: component_iir_psd['y_conv'],\r\n x: component_iir_psd['x_conv'],\r\n y_no_bandpass: component_iir_psd['y_unconv'],\r\n x_no_bandpass: component_iir_psd['x_unconv'],\r\n },\r\n filtered_mls_psd: {\r\n x: filtered_mls_psd['x_mls'],\r\n y: filtered_mls_psd['y_mls'],\r\n },\r\n filtered_no_bandpass_mls_psd: {\r\n x: filtered_no_bandpass_mls_psd['x_mls'],\r\n y: filtered_no_bandpass_mls_psd['y_mls'],\r\n },\r\n convolution: this.componentConvolution,\r\n convolutionNoBandpass: this.componentConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: unconv_results['x'],\r\n y: unconv_results['y'],\r\n },\r\n conv: {\r\n x: conv_results['x'],\r\n y: conv_results['y'],\r\n },\r\n },\r\n gainDBSPL: gainValue,\r\n },\r\n mls: this.#mlsBufferView,\r\n mls_psd: {\r\n x: mls_psd['x_mls'],\r\n y: mls_psd['y_mls'],\r\n },\r\n autocorrelations: this.autocorrelations,\r\n impulseResponses: [],\r\n };\r\n } else {\r\n this.addTimeStamp('Compute PSD of filtered recording (system) and unfiltered recording');\r\n if (this.isCalibrating) return null;\r\n let results = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n let filtered_psd = res.y_conv\r\n .filter(\r\n (value, index) =>\r\n res.x_conv[index] >= this.#lowHz && res.x_conv[index] <= this.systemFMaxHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n\r\n let mls_psd = res.y_unconv\r\n .filter(\r\n (value, index) =>\r\n res.x_unconv[index] >= this.#lowHz && res.x_conv[index] <= this.systemFMaxHz\r\n )\r\n .map(value => 10 * Math.log10(value));\r\n this.SDofFilteredRange['mls'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(mls_psd);\r\n this.SDofFilteredRange['system'] = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.standardDeviation)(filtered_psd);\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n //iir w/ and without bandpass psd\r\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.componentInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of component IIR and component IIR no band pass');\r\n if (this.isCalibrating) return null;\r\n let component_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.systemInvertedImpulseResponse;\r\n this.addTimeStamp('Compute PSD of system IIR and system IIR no band pass');\r\n if (this.isCalibrating) return null;\r\n let system_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate( `All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of MLS sequence');\r\n if (this.isCalibrating) return null;\r\n let mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.#mlsBufferView[this.icapture],\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n this.addTimeStamp('Compute PSD of filtered MLS (system)');\r\n if (this.isCalibrating) return null;\r\n let filtered_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.systemConvolution,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let filtered_no_bandpass_mls_psd = await this.pyServerAPI\r\n .getMLSPSDWithRetry({\r\n mls: this.systemConvolutionNoBandpass,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let gainValue = this.getGainDBSPL();\r\n iir_ir_and_plots = {\r\n unfiltered_recording: return_unconv_rec,\r\n filtered_recording: return_conv_rec,\r\n system: {\r\n iir: this.systemInvertedImpulseResponse,\r\n iir_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n ir: this.systemIR,\r\n iir_psd: {\r\n y: system_iir_psd['y_conv'],\r\n x: system_iir_psd['y_conv'],\r\n y_no_bandpass: system_iir_psd['y_unconv'],\r\n x_no_bandpass: system_iir_psd['x_unconv'],\r\n },\r\n filtered_recording: [],\r\n filtered_mls_psd: {\r\n x: filtered_mls_psd['x_mls'],\r\n y: filtered_mls_psd['y_mls'],\r\n },\r\n filtered_no_bandpass_mls_psd: {\r\n x: filtered_no_bandpass_mls_psd['x_mls'],\r\n y: filtered_no_bandpass_mls_psd['y_mls'],\r\n },\r\n convolution: this.systemConvolution,\r\n convolutionNoBandpass: this.systemConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: results['x_unconv'],\r\n y: results['y_unconv'],\r\n },\r\n conv: {\r\n x: results['x_conv'],\r\n y: results['y_conv'],\r\n },\r\n },\r\n },\r\n component: {\r\n iir: this.componentInvertedImpulseResponse,\r\n iir_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n ir: this.componentIR,\r\n ir_origin: this.componentIROrigin,\r\n ir_in_time_domain: this.componentIRInTimeDomain,\r\n iir_psd: {\r\n y: component_iir_psd['y_conv'],\r\n x: component_iir_psd['x_conv'],\r\n y_no_bandpass: component_iir_psd['y_unconv'],\r\n x_no_bandpass: component_iir_psd['x_unconv'],\r\n },\r\n filtered_mls_psd: {},\r\n filtered_no_bandpass_mls_psd: {},\r\n convolution: this.componentConvolution,\r\n convolutionNoBandpass: this.componentConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: [],\r\n y: [],\r\n },\r\n conv: {\r\n x: [],\r\n y: [],\r\n },\r\n },\r\n gainDBSPL: gainValue,\r\n },\r\n mls: this.#mlsBufferView,\r\n mls_psd: {\r\n x: mls_psd['x_mls'],\r\n y: mls_psd['y_mls'],\r\n },\r\n autocorrelations: this.autocorrelations,\r\n impulseResponses: [],\r\n };\r\n }\r\n if (this.isCalibrating) return null;\r\n await Promise.all(this.impulseResponses).then(res => {\r\n for (let i = 0; i < res.length; i++) {\r\n if (res[i] != undefined) {\r\n iir_ir_and_plots['impulseResponses'].push(res[i]);\r\n }\r\n }\r\n });\r\n\r\n if (this.#download) {\r\n this.downloadSingleUnfilteredRecording();\r\n this.downloadSingleFilteredRecording();\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.#mls, 'MLS.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentConvolution, 'python_component_convolution_mls_iir.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemConvolution, 'python_system_convolution_mls_iir.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentInvertedImpulseResponse, 'componentIIR.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemInvertedImpulseResponse, 'systemIIR.csv');\r\n for (let i = 0; i < this.autocorrelations.length; i++) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.autocorrelations[i], `autocorrelation_${i}`);\r\n }\r\n const computedIRagain = await Promise.all(this.impulseResponses).then(res => {\r\n for (let i = 0; i < res.length; i++) {\r\n if (res[i] != undefined) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(res[i], `IR_${i}`);\r\n }\r\n }\r\n });\r\n }\r\n\r\n return iir_ir_and_plots;\r\n };\r\n\r\n /**\r\n * Public method to start the calibration process. Objects intialized from webassembly allocate new memory\r\n * and must be manually freed. This function is responsible for intializing the MlsGenInterface,\r\n * and wrapping the calibration steps with a garbage collection safe gaurd.\r\n *\r\n * @public\r\n * @param stream - The stream of audio from the Listener.\r\n * @example\r\n */\r\n startCalibrationImpulseResponse = async stream => {\r\n console.log('JS used memory:', performance.memory.usedJSHeapSize / 1024 / 1024, 'mb');\r\n let desired_time = this.desired_time_per_mls;\r\n let checkRec = 'allhz';\r\n\r\n console.log('MLS sequence should be of length: ' + this.sourceSamplingRate * desired_time);\r\n\r\n length = this.sourceSamplingRate * desired_time;\r\n //get mls here\r\n // const calibrateSoundBurstDb = Math.pow(10, this._calibrateSoundBurstDb / 20);\r\n\r\n this.power_dB = 0;\r\n\r\n if (!this._calibrateSoundBurstLevelReTBool) {\r\n this.power_dB = this._calibrateSoundBurstDb;\r\n } else {\r\n this.power_dB = this._calibrateSoundBurstDb + (this.T - this.gainDBSPL);\r\n }\r\n\r\n const amplitude = Math.pow(10, this.power_dB / 20);\r\n //MLSpower = Math.pow(10,this.power_dB/20);\r\n this.addTimeStamp('Compute MLS sequence');\r\n if (this.isCalibrating) return null;\r\n await this.pyServerAPI\r\n .getMLSWithRetry({\r\n length,\r\n amplitude,\r\n calibrateSoundBurstMLSVersions: this.numCaptures,\r\n })\r\n .then(res => {\r\n console.log(res);\r\n this.#mlsBufferView = res['mls'];\r\n this.#mls = res['unscaledMLS'];\r\n })\r\n .catch(err => {\r\n // this.emit('InvertedImpulseResponse', {res: false});\r\n console.error(err);\r\n });\r\n this.numSuccessfulBackgroundCaptured = 0;\r\n if (this._calibrateSoundBackgroundSecs > 0) {\r\n this.mode = 'background';\r\n this.status = this.generateTemplate(`All Hz Calibration: sampling the background noise...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n if (this.isCalibrating) return null;\r\n await this.recordBackground(\r\n stream, //stream\r\n () => this.numSuccessfulBackgroundCaptured < 1, //loop condition\r\n this.#awaitBackgroundNoiseRecording, //sleep to record\r\n this.sendBackgroundRecording, //send to get PSD\r\n this.mode,\r\n checkRec\r\n );\r\n this.incrementStatusBar();\r\n }\r\n this.mode = 'unfiltered';\r\n this.numSuccessfulCaptured = 0;\r\n\r\n if (this.isCalibrating) return null;\r\n for (var i = 0; i < this.numCaptures; i++) {\r\n this.icapture = i;\r\n await this.calibrationSteps(\r\n stream,\r\n this.#playCalibrationAudio, // play audio func (required)\r\n this.#createCalibrationNodeFromBuffer(this.#mlsBufferView[this.icapture]), // before play func\r\n this.#awaitSignalOnset, // before record\r\n () => this.numSuccessfulCaptured < 2, // loop while true\r\n this.#awaitDesiredMLSLength, // during record\r\n this.#afterMLSRecord, // after record\r\n this.mode,\r\n checkRec\r\n );\r\n this.stopCalibrationAudio();\r\n }\r\n checkRec = false;\r\n\r\n // at this stage we've captured all the required signals,\r\n // and have received IRs for each one\r\n // so let's send all the IRs to the server to be converted to a single IIR\r\n if (this.isCalibrating) return null;\r\n await this.sendSystemImpulseResponsesToServerForProcessing();\r\n await this.pyServerAPI.checkMemory();\r\n if (this.isCalibrating) return null;\r\n await this.sendComponentImpulseResponsesToServerForProcessing();\r\n\r\n this.numSuccessfulCaptured = 0;\r\n\r\n let iir_ir_and_plots;\r\n if (this._calibrateSoundCheck != 'none') {\r\n //do single check\r\n if (this._calibrateSoundCheck == 'goal' || this._calibrateSoundCheck == 'system') {\r\n if (this.isCalibrating) return null;\r\n iir_ir_and_plots = await this.singleSoundCheck(stream);\r\n if (this.isCalibrating) return null;\r\n } else {\r\n //both\r\n if (this.isCalibrating) return null;\r\n iir_ir_and_plots = await this.bothSoundCheck(stream);\r\n if (this.isCalibrating) return null;\r\n }\r\n } else {\r\n let unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\r\n let conv_rec = this.componentInvertedImpulseResponse;\r\n if (this.isCalibrating) return null;\r\n let component_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\r\n conv_rec = this.systemInvertedImpulseResponse;\r\n if (this.isCalibrating) return null;\r\n let system_iir_psd = await this.pyServerAPI\r\n .getPSDWithRetry({\r\n unconv_rec,\r\n conv_rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n this.status = this.generateTemplate(`All Hz Calibration: done computing the PSD graphs...`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n return res;\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n });\r\n\r\n let gainValue = this.getGainDBSPL();\r\n iir_ir_and_plots = {\r\n unfiltered_recording: return_unconv_rec,\r\n filtered_recording: return_conv_rec,\r\n system: {\r\n iir: this.systemInvertedImpulseResponse,\r\n iir_no_bandpass: this.systemInvertedImpulseResponseNoBandpass,\r\n ir: this.systemIR,\r\n iir_psd: {\r\n y: system_iir_psd['y_conv'],\r\n x: system_iir_psd['y_conv'],\r\n y_no_bandpass: system_iir_psd['y_unconv'],\r\n x_no_bandpass: system_iir_psd['x_unconv'],\r\n },\r\n filtered_recording: [],\r\n convolution: this.systemConvolution,\r\n convolutionNoBandpass: this.systemConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: [],\r\n y: [],\r\n },\r\n conv: {\r\n x: [],\r\n y: [],\r\n },\r\n },\r\n },\r\n component: {\r\n iir: this.componentInvertedImpulseResponse,\r\n iir_no_bandpass: this.componentInvertedImpulseResponseNoBandpass,\r\n ir: this.componentIR,\r\n ir_in_time_domain: this.componentIRInTimeDomain,\r\n iir_psd: {\r\n y: component_iir_psd['y_conv'],\r\n x: component_iir_psd['x_conv'],\r\n y_no_bandpass: component_iir_psd['y_unconv'],\r\n x_no_bandpass: component_iir_psd['x_unconv'],\r\n },\r\n convolution: this.componentConvolution,\r\n convolutionNoBandpass: this.componentConvolutionNoBandpass,\r\n psd: {\r\n unconv: {\r\n x: [],\r\n y: [],\r\n },\r\n conv: {\r\n x: [],\r\n y: [],\r\n },\r\n },\r\n gainDBSPL: gainValue,\r\n },\r\n mls: this.#mlsBufferView,\r\n autocorrelations: this.autocorrelations,\r\n impulseResponses: [],\r\n };\r\n if (this.isCalibrating) return null;\r\n await Promise.all(this.impulseResponses).then(res => {\r\n for (let i = 0; i < res.length; i++) {\r\n if (res[i] != undefined) {\r\n iir_ir_and_plots['impulseResponses'].push(res[i]);\r\n }\r\n }\r\n });\r\n\r\n if (this.#download) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.#mls, 'MLS.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentConvolution, 'python_component_convolution_mls_iir.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemConvolution, 'python_system_convolution_mls_iir.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentInvertedImpulseResponse, 'componentIIR.csv');\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemInvertedImpulseResponse, 'systemIIR.csv');\r\n for (let i = 0; i < this.autocorrelations.length; i++) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.autocorrelations[i], `autocorrelation_${i}`);\r\n }\r\n const computedIRagain = await Promise.all(this.impulseResponses).then(res => {\r\n for (let i = 0; i < res.length; i++) {\r\n if (res[i] != undefined) {\r\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(res[i], `IR_${i}`);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (this.isCalibrating) return null;\r\n this.percent_complete = 100;\r\n this.status = this.generateTemplate(`All Hz Calibration: Finished`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n\r\n //here after calibration we have the component calibration (either loudspeaker or microphone) in the same form as the componentIR\r\n //that was used to calibrate\r\n // saveToJSON(iir_ir_and_plots);\r\n return iir_ir_and_plots;\r\n };\r\n\r\n //////////////////////volume\r\n\r\n handleIncomingData = data => {\r\n console.log('Received data: ', data);\r\n if (data.type === 'soundGainDBSPL') {\r\n this.soundGainDBSPL = data.value;\r\n } else {\r\n throw new Error(`Unknown data type: ${data.type}`);\r\n }\r\n };\r\n\r\n #getTruncatedSignal = (left = 3.5, right = 4.5) => {\r\n const start = Math.floor(left * this.sourceSamplingRate);\r\n const end = Math.floor(right * this.sourceSamplingRate);\r\n const result = Array.from(this.getLastVolumeRecordedSignal().slice(start, end));\r\n console.log(\r\n 'Obtaining last 1000 hz recording from #allVolumeRecordings to send for processing'\r\n );\r\n /**\r\n * function to check that capture was properly made\r\n * @param {*} list\r\n */\r\n const checkResult = list => {\r\n const setItem = new Set(list);\r\n if (setItem.size === 1 && setItem.has(0)) {\r\n console.warn(\r\n 'The last capture failed, all recorded signal is zero',\r\n this.getAllVolumeRecordedSignals()\r\n );\r\n this.stopCalibrationAudio();\r\n this.isCalibrating = true;\r\n // restartButton.style.display = 'none';\r\n this.emit('update', {message: 'Connection failed, hit restart button to reconnect'});\r\n }\r\n if (setItem.size === 0) {\r\n console.warn('The last capture failed, no recorded signal');\r\n this.stopCalibrationAudio();\r\n this.isCalibrating = true;\r\n // restartButton.style.display = 'none';\r\n this.emit('update', {message: 'Connection failed, hit restart button to reconnect'});\r\n }\r\n };\r\n checkResult(result);\r\n return result;\r\n };\r\n\r\n /** \r\n * \r\n * \r\n Construct a calibration Node with the calibration parameters and given gain value\r\n * @param {*} gainValue\r\n * */\r\n #createCalibrationToneWithGainValue = gainValue => {\r\n const audioContext = this.makeNewSourceAudioContext();\r\n const oscilator = audioContext.createOscillator();\r\n const gainNode = audioContext.createGain();\r\n const taperGainNode = audioContext.createGain();\r\n const offsetGainNode = audioContext.createGain();\r\n const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;\r\n\r\n oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;\r\n oscilator.type = this.#CALIBRATION_TONE_TYPE;\r\n gainNode.gain.value = gainValue;\r\n\r\n oscilator.connect(gainNode);\r\n gainNode.connect(taperGainNode);\r\n const onsetCurve = this.createSCurveBuffer();\r\n taperGainNode.gain.setValueCurveAtTime(onsetCurve, 0, this.TAPER_SECS);\r\n taperGainNode.connect(offsetGainNode);\r\n const offsetCurve = this.createSCurveBuffer(false);\r\n offsetGainNode.gain.setValueCurveAtTime(\r\n offsetCurve,\r\n totalDuration - this.TAPER_SECS,\r\n this.TAPER_SECS\r\n );\r\n offsetGainNode.connect(audioContext.destination);\r\n\r\n const gainValuesOverTime = [];\r\n const sampleRate = this.#CALIBRATION_TONE_FREQUENCY; // Number of samples per second\r\n const interval = 1 / sampleRate; // Time between samples\r\n\r\n for (let t = 0; t <= totalDuration; t += interval) {\r\n let gainValueAtTime = gainValue;\r\n\r\n // Apply the onset curve\r\n if (t < this.TAPER_SECS) {\r\n const onsetIndex = Math.floor((t / this.TAPER_SECS) * onsetCurve.length);\r\n gainValueAtTime *= onsetCurve[onsetIndex];\r\n }\r\n\r\n // Apply the offset curve\r\n if (t > totalDuration - this.TAPER_SECS) {\r\n const offsetTime = t - (totalDuration - this.TAPER_SECS);\r\n const offsetIndex = Math.floor((offsetTime / this.TAPER_SECS) * offsetCurve.length);\r\n gainValueAtTime *= offsetCurve[offsetIndex];\r\n }\r\n\r\n gainValuesOverTime.push(gainValueAtTime);\r\n }\r\n\r\n this.waveforms['volume'][this.inDB] = gainValuesOverTime;\r\n\r\n this.addCalibrationNode(oscilator);\r\n };\r\n\r\n /**\r\n * Construct a Calibration Node with the calibration parameters.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #createCalibrationNode = () => {\r\n const audioContext = this.makeNewSourceAudioContext();\r\n const oscilator = audioContext.createOscillator();\r\n const gainNode = audioContext.createGain();\r\n\r\n oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;\r\n oscilator.type = this.#CALIBRATION_TONE_TYPE;\r\n gainNode.gain.value = 0.04;\r\n\r\n oscilator.connect(gainNode);\r\n gainNode.connect(audioContext.destination);\r\n\r\n this.addCalibrationNode(oscilator);\r\n };\r\n\r\n #playCalibrationAudioVolume = async () => {\r\n if (this.numCalibratingRoundsCompleted==1) {\r\n this.recordingChecks['warnings'].push(`1000Hz. Re-recorded ${this.inDB} dB because SD ${(this.recordingChecks['volume'][this.inDB]['sd'])} > ${this.calibrateSound1000HzMaxSD_dB} dB`);\r\n const currentStatus = `1000 Hz: Re-recording at ${this.inDB} dB because SD \r\n ${this.recordingChecks['volume'][this.inDB]['sd']} > \r\n ${this.calibrateSound1000HzMaxSD_dB} dB`.toString();\r\n this.status = this.generateTemplate(currentStatus).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n }\r\n const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;\r\n\r\n this.calibrationNodes[0].start(0);\r\n this.calibrationNodes[0].stop(totalDuration);\r\n console.log(`Playing a buffer of ${this.CALIBRATION_TONE_DURATION} seconds of audio`);\r\n console.log(`Waiting a total of ${totalDuration} seconds`);\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(totalDuration);\r\n };\r\n\r\n stopCalibrationAudioVolume = () => {\r\n if (this.calibrationNodes.length > 0) {\r\n this.calibrationNodes[0].stop();\r\n }\r\n };\r\n\r\n #sendToServerForProcessing = async lCalib => {\r\n console.log('Sending data to server');\r\n const total_dur = this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec + this.calibrateSound1000HzPostSec;\r\n this.addTimeStamp(\r\n \"1000 Hz: recorded at \" + this.inDB + \r\n \" dB (\" + this.calibrateSound1000HzPreSec.toFixed(1) + \r\n \" s pre + \" + this.calibrateSound1000HzSec.toFixed(1) + \r\n \" s used + \" + this.calibrateSound1000HzPostSec.toFixed(1) + \r\n \" s post)\"\r\n );\r\n let left = this.calibrateSound1000HzPreSec;\r\n let right = this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec;\r\n if (this.isCalibrating) return null;\r\n this.pyServerAPI\r\n .getVolumeCalibration({\r\n sampleRate: this.sourceSamplingRate,\r\n payload: this.#getTruncatedSignal(left, right),\r\n lCalib: lCalib,\r\n })\r\n .then(res => {\r\n if (this.outDBSPL === null) {\r\n this.incrementStatusBar();\r\n this.outDBSPL = res['outDbSPL'];\r\n this.outDBSPL1000 = res['outDbSPL1000'];\r\n this.THD = res['thd'];\r\n }\r\n })\r\n .catch(err => {\r\n console.warn(err);\r\n });\r\n const rec = this.getLastVolumeRecordedSignal();\r\n console.log('pre period power: ', (0,_powerCheck__WEBPACK_IMPORTED_MODULE_2__.getPower)(rec.slice(0,this.calibrateSound1000HzPreSec * this.sourceSamplingRate)).toFixed(1));\r\n console.log('pre period power: ', \r\n (0,_powerCheck__WEBPACK_IMPORTED_MODULE_2__.getPower)(rec.slice(\r\n this.calibrateSound1000HzPreSec * this.sourceSamplingRate,\r\n (this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec)* this.sourceSamplingRate)).toFixed(1));\r\n console.log('pre period power: ', (0,_powerCheck__WEBPACK_IMPORTED_MODULE_2__.getPower)(rec.slice(\r\n (this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec)* this.sourceSamplingRate)).toFixed(1));\r\n const res = (0,_powerCheck__WEBPACK_IMPORTED_MODULE_2__.volumePowerCheck)(\r\n rec,\r\n this.sourceSamplingRate || 96000,\r\n this.calibrateSound1000HzPreSec,\r\n this.calibrateSound1000HzSec, \r\n this._calibrateSoundPowerBinDesiredSec);\r\n console.log(res);\r\n this.recordingChecks['volume'][this.inDB] = res;\r\n };\r\n\r\n startCalibrationVolume = async (stream, gainValues, lCalib, componentGainDBSPL) => {\r\n if (this.isCalibrating) return null;\r\n const trialIterations = gainValues.length;\r\n this.status_denominator += trialIterations;\r\n const thdValues = [];\r\n const inDBValues = [];\r\n let inDB = 0;\r\n const outDBSPLValues = [];\r\n const outDBSPL1000Values = [];\r\n let checkRec = 'loudest';\r\n // do one calibration that will be discarded\r\n const soundLevelToDiscard = -60;\r\n const gainToDiscard = Math.pow(10, soundLevelToDiscard / 20);\r\n this.inDB = soundLevelToDiscard;\r\n this.status = this.generateTemplate(`1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`.toString()).toString();\r\n //this.emit('update', {message: `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`});\r\n this.emit('update', {message: this.status});\r\n this.startTime = new Date().getTime();\r\n\r\n do {\r\n console.log('while loop');\r\n if (this.isCalibrating) {\r\n console.log('restart calibration');\r\n return null;\r\n }\r\n // eslint-disable-next-line no-await-in-loop\r\n await this.volumeCalibrationSteps(\r\n stream,\r\n this.#playCalibrationAudioVolume,\r\n this.#createCalibrationToneWithGainValue,\r\n this.#sendToServerForProcessing,\r\n gainToDiscard,\r\n lCalib, //todo make this a class parameter\r\n checkRec,\r\n () => {return this.recordingChecks['volume'][this.inDB]['sd']},\r\n this.calibrateSound1000HzMaxSD_dB\r\n );\r\n } while (this.outDBSPL === null);\r\n //reset the values\r\n //this.incrementStatusBar();\r\n\r\n this.outDBSPL = null;\r\n this.outDBSPL = null;\r\n this.outDBSPL1000 = null;\r\n this.THD = null;\r\n\r\n // run the calibration at different gain values provided by the user\r\n for (let i = 0; i < trialIterations; i++) {\r\n //convert gain to DB and add to inDB\r\n if (i == trialIterations - 1) {\r\n checkRec = 'loudest';\r\n }\r\n inDB = Math.log10(gainValues[i]) * 20;\r\n // precision to 1 decimal place\r\n inDB = Math.round(inDB * 10) / 10;\r\n this.inDB = inDB;\r\n inDBValues.push(inDB);\r\n console.log('next update');\r\n this.status = this.generateTemplate(`1000 Hz Calibration: Sound Level ${inDB} dB`.toString()).toString();\r\n this.emit('update', {message: this.status});\r\n do {\r\n if (this.isCalibrating) {\r\n console.log('restart calibration');\r\n return null;\r\n }\r\n // eslint-disable-next-line no-await-in-loop\r\n await this.volumeCalibrationSteps(\r\n stream,\r\n this.#playCalibrationAudioVolume,\r\n this.#createCalibrationToneWithGainValue,\r\n this.#sendToServerForProcessing,\r\n gainValues[i],\r\n lCalib, //todo make this a class parameter\r\n checkRec,\r\n () => {return this.recordingChecks?.['volume']?.[this.inDB]?.['sd'] || 0},\r\n this.calibrateSound1000HzMaxSD_dB\r\n );\r\n } while (this.outDBSPL === null);\r\n outDBSPL1000Values.push(this.outDBSPL1000);\r\n thdValues.push(this.THD);\r\n outDBSPLValues.push(this.outDBSPL);\r\n\r\n this.outDBSPL = null;\r\n this.outDBSPL1000 = null;\r\n this.THD = null;\r\n }\r\n if (this.isCalibrating) return null;\r\n // get the volume calibration parameters from the server\r\n this.addTimeStamp('Compute sound calibration parameters');\r\n\r\n const parameters = await this.pyServerAPI\r\n .getVolumeCalibrationParameters({\r\n inDBValues: inDBValues,\r\n outDBSPLValues: outDBSPL1000Values,\r\n lCalib: lCalib,\r\n componentGainDBSPL,\r\n })\r\n .then(res => {\r\n this.incrementStatusBar();\r\n return res;\r\n });\r\n if (this.isCalibrating) return null;\r\n const result = {\r\n parameters: parameters,\r\n inDBValues: inDBValues,\r\n outDBSPLValues: outDBSPLValues,\r\n outDBSPL1000Values: outDBSPL1000Values,\r\n thdValues: thdValues,\r\n };\r\n\r\n return result;\r\n };\r\n\r\n writeFrqGainToFirestore = async (speakerID, frq, gain, OEM, documentID) => {\r\n // freq and gain are too large to take samples 1 in every 100 samples\r\n // const sampledFrq = [];\r\n // const sampledGain = [];\r\n // for (let i = 0; i < frq.length; i += 100) {\r\n // sampledFrq.push(frq[i]);\r\n // sampledGain.push(gain[i]);\r\n // }\r\n\r\n const data = {Freq: frq, Gain: gain};\r\n\r\n const docRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.doc)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones', documentID);\r\n await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.updateDoc)(docRef, {\r\n linear: data,\r\n });\r\n\r\n // divide frq and gain into smaller chunks and write to firestore one chunk at a time\r\n // use arrayUnion to append to the array\r\n // const chunkSize = 600;\r\n // const chunkedFrq = [];\r\n // const chunkedGain = [];\r\n // for (let i = 0; i < frq.length; i += chunkSize) {\r\n // chunkedFrq.push(frq.slice(i, i + chunkSize));\r\n // chunkedGain.push(gain.slice(i, i + chunkSize));\r\n // }\r\n // const docRef = doc(database, 'Microphones', documentID);\r\n // for (let i = 0; i < chunkedFrq.length; i++) {\r\n // await updateDoc(docRef, {\r\n // linear: {\r\n // Freq: arrayUnion(...chunkedFrq[i]),\r\n // Gain: arrayUnion(...chunkedGain[i]),\r\n // },\r\n // });\r\n // }\r\n };\r\n // function to write frq and gain to firebase database given speakerID\r\n writeFrqGain = async (speakerID, frq, gain, OEM) => {\r\n // freq and gain are too large to take samples 1 in every 100 samples\r\n\r\n const sampledFrq = [];\r\n const sampledGain = [];\r\n for (let i = 0; i < frq.length; i += 100) {\r\n sampledFrq.push(frq[i]);\r\n sampledGain.push(gain[i]);\r\n }\r\n\r\n const data = {Freq: sampledFrq, Gain: sampledGain};\r\n\r\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], `Microphone2/${OEM}/${speakerID}/linear`), data);\r\n };\r\n\r\n // Function to Read frq and gain from firebase database given speakerID\r\n // returns an array of frq and gain if speakerID exists, returns null otherwise\r\n readFrqGainFromFirestore = async (speakerID, OEM, isDefault) => {\r\n const collectionRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.collection)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones');\r\n const q = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.query)(\r\n collectionRef,\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('ID', '==', speakerID),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('lowercaseOEM', '==', OEM),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('isDefault', '==', isDefault)\r\n );\r\n const querySnapshot = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.getDocs)(q);\r\n // if exists return the linear field of the first document\r\n if (querySnapshot.size > 0) {\r\n const timestamp = new firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.Timestamp(\r\n querySnapshot.docs[0].data().createDate.seconds,\r\n querySnapshot.docs[0].data().createDate.nanoseconds\r\n );\r\n return {\r\n ir: querySnapshot.docs[0].data().linear,\r\n createDate: timestamp.toDate(),\r\n jsonFileName: querySnapshot.docs[0].data().jsonFileName,\r\n };\r\n }\r\n return null;\r\n };\r\n readFrqGain = async (speakerID, OEM) => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/linear`));\r\n if (snapshot.exists()) {\r\n return snapshot.val();\r\n }\r\n return null;\r\n };\r\n readGainat1000HzFromFirestore = async (speakerID, OEM, isDefault) => {\r\n const collectionRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.collection)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones');\r\n const q = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.query)(\r\n collectionRef,\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('ID', '==', speakerID),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('lowercaseOEM', '==', OEM),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('isDefault', '==', isDefault)\r\n );\r\n const querySnapshot = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.getDocs)(q);\r\n // if exists return the Gain1000 field of the first document\r\n if (querySnapshot.size > 0) {\r\n return querySnapshot.docs[0].data().Gain1000;\r\n }\r\n return null;\r\n };\r\n\r\n readGainat1000Hz = async (speakerID, OEM) => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/Gain1000`));\r\n if (snapshot.exists()) {\r\n return snapshot.val();\r\n }\r\n return null;\r\n };\r\n\r\n writeGainat1000HzToFirestore = async (speakerID, gain, OEM, documentID) => {\r\n const docRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.doc)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones', documentID);\r\n await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.updateDoc)(docRef, {\r\n Gain1000: gain,\r\n });\r\n };\r\n\r\n writeGainat1000Hz = async (speakerID, gain, OEM) => {\r\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], `Microphone2/${OEM}/${speakerID}/Gain1000`), gain);\r\n };\r\n\r\n writeIsSmartPhoneToFirestore = async (speakerID, isSmartPhone, OEM) => {\r\n const collectionRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.collection)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones');\r\n const q = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.query)(\r\n collectionRef,\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('ID', '==', speakerID),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('lowercaseOEM', '==', OEM),\r\n (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.where)('isDefault', '==', true)\r\n );\r\n const querySnapshot = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.getDocs)(q);\r\n if (querySnapshot.size > 0) {\r\n const docRef = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.addDoc)(collectionRef, {isSmartPhone: isSmartPhone, isDefault: false});\r\n return docRef.id;\r\n } else {\r\n const docRef = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.addDoc)(collectionRef, {isSmartPhone: isSmartPhone, isDefault: true});\r\n return docRef.id;\r\n }\r\n };\r\n\r\n writeIsSmartPhone = async (speakerID, isSmartPhone, OEM) => {\r\n const data = {isSmartPhone: isSmartPhone};\r\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], `Microphone2/${OEM}/${speakerID}/isSmartPhone`), isSmartPhone);\r\n };\r\n\r\n writeMicrophoneInfoToFirestore = async (speakerID, micInfo, OEM, documentID) => {\r\n const docRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.doc)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphones', documentID);\r\n await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.setDoc)(docRef, micInfo, {merge: true});\r\n };\r\n\r\n doesMicrophoneExistInFirestore = async (speakerID, OEM, documentID) => {\r\n const docRef = (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.doc)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], 'Microphone', OEM, speakerID, documentID);\r\n const docSnap = await (0,firebase_firestore__WEBPACK_IMPORTED_MODULE_5__.getDoc)(docRef);\r\n if (docSnap.exists()) {\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n doesMicrophoneExist = async (speakerID, OEM) => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.child)(dbRef, `Microphone2/${OEM}/${speakerID}`));\r\n if (snapshot.exists()) {\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n addMicrophoneInfo = async (speakerID, OEM, micInfo) => {\r\n // add to database if /info does not exist\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/info`));\r\n if (!snapshot.exists()) {\r\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_4__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_3__[\"default\"], `Microphone2/${OEM}/${speakerID}/info`), micInfo);\r\n }\r\n };\r\n\r\n convertToDB = gain => {\r\n return Math.log10(gain) * 20;\r\n };\r\n\r\n // Function to perform linear interpolation between two points\r\n interpolate(x, x0, y0, x1, y1) {\r\n return y0 + ((x - x0) * (y1 - y0)) / (x1 - x0);\r\n }\r\n\r\n findGainatFrequency = (frequencies, gains, targetFrequency) => {\r\n // Find the index of the first frequency in the array greater than the target frequency\r\n let index = 0;\r\n while (index < frequencies.length && frequencies[index] < targetFrequency) {\r\n index++;\r\n }\r\n\r\n // Handle cases when the target frequency is outside the range of the given data\r\n if (index === 0) {\r\n return gains[0];\r\n } else if (index === frequencies.length) {\r\n return gains[gains.length - 1];\r\n } else {\r\n // Interpolate the gain based on the surrounding frequencies\r\n const x0 = frequencies[index - 1];\r\n const y0 = gains[index - 1];\r\n const x1 = frequencies[index];\r\n const y1 = gains[index];\r\n return this.interpolate(targetFrequency, x0, y0, x1, y1);\r\n }\r\n };\r\n\r\n checkPowerVariation = async () => {\r\n let recordings = this.getAllFilteredRecordedSignals();\r\n // remove filteredMLSAttenuation from the recordings\r\n\r\n // recordings = recordings.map(recording => {\r\n // if (this.soundCheck == 'component') {\r\n // return recording.map(value => value / this.filteredMLSAttenuation.component);\r\n // }\r\n // return recording.map(value => value / this.filteredMLSAttenuation.system);\r\n // });\r\n\r\n const rec = recordings[recordings.length - 1];\r\n\r\n await this.pyServerAPI\r\n .allHzPowerCheck({\r\n payload: rec,\r\n sampleRate: this.sourceSamplingRate || 96000,\r\n binDesiredSec: this._calibrateSoundPowerBinDesiredSec,\r\n burstSec: this.desired_time_per_mls,\r\n repeats: this.numMLSPerCapture - this.num_mls_to_skip ,\r\n warmUp: this.num_mls_to_skip \r\n })\r\n .then(result => {\r\n if (result) {\r\n if (result['sd'] > this._calibrateSoundBurstMaxSD_dB && this.numSuccessfulCaptured == 0) {\r\n console.log('filtered recording sd too high');\r\n this.recordingChecks['warnings'].push(`All Hz. Re-recorded ${this.inDB} because SD ${result['sd']} > ${this._calibrateSoundBurstMaxSD_dB} dB`);\r\n this.status = this.generateTemplate(`All Hz: Re-recording at ${this.inDB} dB because SD ${result['sd']} > ${this._calibrateSoundBurstMaxSD_dB} dB`.toString()).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n // numSuccessfulCaptured no longer to count number of successful capture but count attemps\r\n // is sd below _calibrateSoundBurstMaxSD_dB then count two attemps\r\n // else count one attemp\r\n this.numSuccessfulCaptured += 1;\r\n } else {\r\n this.recordingChecks[this.soundCheck].push(result);\r\n // Now we do at most 2 attempts if sd > _calibrateSoundBurstMaxSD_dB\r\n // Second attempt is the final\r\n if (this.numSuccessfulCaptured < 2) {\r\n this.numSuccessfulCaptured += 2;\r\n this.stepNum += 1;\r\n this.incrementStatusBar();\r\n console.log(\r\n 'after mls w iir record for some reason add numSucc capt ' + this.stepNum\r\n );\r\n this.status = this.generateTemplate(`All Hz Calibration: ${this.numSuccessfulCaptured} recording of convolved MLS captured`.toString()).toString();\r\n this.emit('update', {\r\n message: this.status,\r\n });\r\n }\r\n }\r\n }\r\n });\r\n };\r\n\r\n getGainDBSPL = () => {\r\n var freqIndex = this.componentIR.Freq.indexOf(1000);\r\n\r\n // If freqIndex is not -1 (meaning 1000 is found in the freq array)\r\n if (freqIndex !== -1) {\r\n // Get the corresponding gain value using the index\r\n var gainValue = this.componentIR.Gain[freqIndex];\r\n return gainValue;\r\n } else {\r\n console.log('Freq 1000 not found in the array.');\r\n return null;\r\n }\r\n };\r\n // Example of how to use the writeFrqGain and readFrqGain functions\r\n // writeFrqGain('speaker1', [1, 2, 3], [4, 5, 6]);\r\n // Speaker1 is the speakerID you want to write to in the database\r\n // readFrqGain('MiniDSPUMIK_1').then(data => console.log(data));\r\n // MiniDSPUMIK_1 is the speakerID with some Data in the database\r\n //adding gainDBSPL\r\n startCalibration = async (\r\n stream,\r\n gainValues,\r\n lCalib = 104.92978421490648,\r\n componentIR = null,\r\n microphoneName = 'MiniDSP-UMIK1-711-4754-vertical',\r\n _calibrateSoundCheck = 'goal', //GOAL PASSed in by default\r\n isSmartPhone = false,\r\n _calibrateSoundBurstDb = -18,\r\n _calibrateSoundBurstFilteredExtraDb = 6,\r\n _calibrateSoundBurstLevelReTBool = false,\r\n _calibrateSoundBurstUses1000HzGainBool = false,\r\n _calibrateSoundBurstRepeats = 3,\r\n _calibrateSoundBurstSec = 1,\r\n _calibrateSoundBurstPreSec = 1,\r\n _calibrateSoundBurstPostSec = 1,\r\n _calibrateSoundHz = 48000,\r\n _calibrateSoundIRSec = 0.2,\r\n _calibrateSoundIIRSec = 0.2,\r\n _calibrateSoundIIRPhase = 'linear',\r\n calibrateSound1000HzPreSec = 0.5,\r\n calibrateSound1000HzSec = 0.5,\r\n calibrateSound1000HzPostSec = 0.5,\r\n _calibrateSoundBackgroundSecs = 0,\r\n _calibrateSoundSmoothOctaves = 0.33,\r\n _calibrateSoundSmoothMinBandwidthHz = 200,\r\n _calibrateSoundPowerBinDesiredSec = 0.2,\r\n _calibrateSoundPowerDbSDToleratedDb = 1,\r\n _calibrateSoundTaperSec = 0.01,\r\n micManufacturer = '',\r\n micSerialNumber = '',\r\n micModelNumber = '',\r\n micModelName = '',\r\n calibrateMicrophonesBool,\r\n authorEmails,\r\n webAudioDeviceNames = {\r\n loudspeaker: 'loudspeaker',\r\n microphone: 'microphone',\r\n microphoneText: 'xxx XXX',\r\n },\r\n userIDs,\r\n restartButton,\r\n reminder,\r\n calibrateSoundLimit,\r\n _calibrateSoundBurstNormalizeBy1000HzGainBool = false,\r\n _calibrateSoundBurstScalarDB = 71,\r\n calibrateSound1000HzMaxSD_dB = 4,\r\n _calibrateSoundBurstMaxSD_dB = 4,\r\n calibrateSoundSamplingDesiredBits = 24,\r\n language,\r\n loudspeakerModelName='',\r\n phrases,\r\n soundSubtitleId,\r\n\r\n ) => {\r\n this._calibrateSoundBurstPreSec = _calibrateSoundBurstPreSec;\r\n this._calibrateSoundBurstRepeats = _calibrateSoundBurstRepeats;\r\n this._calibrateSoundBurstSec = _calibrateSoundBurstSec;\r\n this.micModelName = micModelName;\r\n this.loudspeakerModelName = loudspeakerModelName;\r\n this.language = language;\r\n this.TAPER_SECS = _calibrateSoundTaperSec;\r\n this.calibrateSoundLimit = calibrateSoundLimit;\r\n this._calibrateSoundBurstDb = _calibrateSoundBurstDb;\r\n this._calibrateSoundBurstFilteredExtraDb = _calibrateSoundBurstFilteredExtraDb;\r\n this._calibrateSoundBurstLevelReTBool = _calibrateSoundBurstLevelReTBool;\r\n this.CALIBRATION_TONE_DURATION =\r\n calibrateSound1000HzPreSec + calibrateSound1000HzSec + calibrateSound1000HzPostSec;\r\n this.calibrateSound1000HzPreSec = calibrateSound1000HzPreSec;\r\n this.calibrateSound1000HzSec = calibrateSound1000HzSec;\r\n this.calibrateSound1000HzPostSec = calibrateSound1000HzPostSec;\r\n this.iirLength = Math.floor(_calibrateSoundIIRSec * this.sourceSamplingRate);\r\n this.irLength = Math.floor(_calibrateSoundIRSec * this.sourceSamplingRate);\r\n this.calibrateSoundIIRPhase = _calibrateSoundIIRPhase;\r\n this.num_mls_to_skip = Math.ceil(_calibrateSoundBurstPreSec / _calibrateSoundBurstSec);\r\n this._calibrateSoundBurstPostSec = _calibrateSoundBurstPostSec;\r\n this.numMLSPerCapture = _calibrateSoundBurstRepeats + this.num_mls_to_skip;\r\n this.desired_time_per_mls = _calibrateSoundBurstSec;\r\n this.desired_sampling_rate = _calibrateSoundHz;\r\n this._calibrateSoundBackgroundSecs = _calibrateSoundBackgroundSecs;\r\n this._calibrateSoundSmoothOctaves = _calibrateSoundSmoothOctaves;\r\n this._calibrateSoundSmoothMinBandwidthHz = _calibrateSoundSmoothMinBandwidthHz;\r\n this._calibrateSoundPowerBinDesiredSec = _calibrateSoundPowerBinDesiredSec;\r\n this._calibrateSoundBurstUses1000HzGainBool = _calibrateSoundBurstUses1000HzGainBool;\r\n this._calibrateSoundPowerDbSDToleratedDb = _calibrateSoundPowerDbSDToleratedDb;\r\n this._calibrateSoundBurstNormalizeBy1000HzGainBool =\r\n _calibrateSoundBurstNormalizeBy1000HzGainBool;\r\n this._calibrateSoundBurstScalarDB = _calibrateSoundBurstScalarDB;\r\n this.webAudioDeviceNames = webAudioDeviceNames;\r\n this.calibrateSoundSamplingDesiredBits = calibrateSoundSamplingDesiredBits;\r\n this.phrases = phrases;\r\n this.soundSubtitleId = soundSubtitleId;\r\n if (isSmartPhone) {\r\n const leftQuote = \"\\u201C\"; // “\r\n const rightQuote = \"\\u201D\"; // ”\r\n this.webAudioDeviceNames.microphone = this.deviceInfo.microphoneFromAPI;\r\n const quotedWebAudioMic = leftQuote + this.webAudioDeviceNames.microphone + rightQuote;\r\n const combinedMicText = this.micModelName + \" \" + quotedWebAudioMic;\r\n webAudioDeviceNames.microphoneText = this.phrases.RC_nameMicrophone[this.language]\r\n .replace(\"“xxx”\", combinedMicText)\r\n .replace(\"“XXX”\", combinedMicText);\r\n }\r\n // this.webAudioDeviceNames.microphoneText = this.webAudioDeviceNames.microphoneText\r\n // .replace('xxx', this.webAudioDeviceNames.microphone)\r\n // .replace('XXX', this.webAudioDeviceNames.microphone);\r\n //feed calibration goal here\r\n this._calibrateSoundCheck = _calibrateSoundCheck;\r\n this.calibrateSound1000HzMaxSD_dB = calibrateSound1000HzMaxSD_dB;\r\n this._calibrateSoundBurstMaxSD_dB = _calibrateSoundBurstMaxSD_dB;\r\n //check if a componentIR was given to the system, if it isn't check for the microphone. using dummy data here bc we need to\r\n //check the db based on the microphone currently connected\r\n\r\n //new lCalib found at top of calibration files *1000hz, make sure to correct\r\n //based on zeroing of 1000hz, search for \"*1000Hz\"\r\n const ID = isSmartPhone ? micModelNumber : micSerialNumber;\r\n const OEM = isSmartPhone\r\n ? micModelName === 'UMIK-1' || micModelName === 'UMIK-2'\r\n ? 'minidsp'\r\n : this.deviceInfo.OEM.toLowerCase().split(' ').join('')\r\n : micManufacturer.toLowerCase().split(' ').join('');\r\n // const ID = \"712-5669\";\r\n // const OEM = \"minidsp\";\r\n const micInfo = {\r\n micModelName: isSmartPhone ? micModelName : microphoneName,\r\n OEM: isSmartPhone\r\n ? micModelName === 'UMIK-1' || micModelName === 'UMIK-2'\r\n ? 'miniDSP'\r\n : this.deviceInfo.OEM\r\n : micManufacturer,\r\n ID: ID,\r\n createDate: new Date(),\r\n DateText: (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getCurrentTimeString)(),\r\n HardwareName: isSmartPhone ? this.deviceInfo.hardwarename : microphoneName,\r\n hardwareFamily: isSmartPhone ? this.deviceInfo.hardwarefamily : microphoneName,\r\n HardwareModel: isSmartPhone ? this.deviceInfo.hardwaremodel : microphoneName,\r\n PlatformName: isSmartPhone ? this.deviceInfo.platformname : 'N/A',\r\n PlatformVersion: isSmartPhone ? this.deviceInfo.platformversion : 'N/A',\r\n DeviceType: isSmartPhone ? this.deviceInfo.devicetype : 'N/A',\r\n ID_from_51Degrees: isSmartPhone ? this.deviceInfo.DeviceId : 'N/A',\r\n calibrateMicrophonesBool: calibrateMicrophonesBool,\r\n screenHeight: this.deviceInfo.screenHeight,\r\n screenWidth: this.deviceInfo.screenWidth,\r\n webAudioDeviceNames: {\r\n loudspeaker: this.webAudioDeviceNames.loudspeaker,\r\n microphone: this.webAudioDeviceNames.microphone,\r\n },\r\n userIDs: userIDs,\r\n lowercaseOEM: OEM.toLowerCase().split(' ').join(''),\r\n };\r\n if (calibrateMicrophonesBool) {\r\n micInfo['authorEmails'] = authorEmails;\r\n }\r\n // if undefined in micInfo, set to empty string\r\n for (const [key, value] of Object.entries(micInfo)) {\r\n if (value === undefined) {\r\n micInfo[key] = '';\r\n }\r\n }\r\n\r\n // this.writeMicrophoneInfoToFirestore(ID, micInfo, OEM, 'default');\r\n // this.addMicrophoneInfo(ID, OEM, micInfo);\r\n if (componentIR == null) {\r\n //mode 'ir'\r\n //global variable this.componentIR must be set\r\n await this.readFrqGainFromFirestore(ID, OEM, true).then(data => {\r\n if (data !== null) {\r\n this.componentIR = data.ir;\r\n micInfo['parentTimestamp'] = data.createDate ? data.createDate : new Date();\r\n micInfo['parentFilenameJSON'] = data.jsonFileName ? data.jsonFileName : '';\r\n }\r\n });\r\n\r\n // await this.readFrqGain(ID, OEM).then(data => {\r\n // return data;\r\n // });\r\n\r\n // lCalib = await this.readGainat1000Hz(ID, OEM);\r\n lCalib = await this.readGainat1000HzFromFirestore(ID, OEM, true);\r\n micInfo['gainDBSPL'] = lCalib;\r\n // this.componentGainDBSPL = this.convertToDB(lCalib);\r\n this.componentGainDBSPL = lCalib;\r\n //TODO: if this call to database is unknown, cannot perform experiment => return false\r\n if (this.componentIR == null) {\r\n this.status =\r\n `Microphone (${OEM},${ID}) is not found in the database. Please add it to the database.`.toString();\r\n this.emit('update', {message: this.status});\r\n return false;\r\n }\r\n } else {\r\n this.transducerType = 'Microphone';\r\n this.componentIR = componentIR;\r\n lCalib = this.findGainatFrequency(this.componentIR.Freq, this.componentIR.Gain, 1000);\r\n // this.componentGainDBSPL = this.convertToDB(lCalib);\r\n this.componentGainDBSPL = lCalib;\r\n // await this.writeIsSmartPhone(ID, isSmartPhone, OEM);\r\n }\r\n\r\n this.oldComponentIR = JSON.parse(JSON.stringify(this.componentIR));\r\n\r\n return await new Promise(async (resolve, reject) => {\r\n // add event listner to params.restartButton to resolve the promise with a string: 'restart'\r\n\r\n if (reminder) {\r\n reminder.style.display = '';\r\n }\r\n if (restartButton) {\r\n restartButton.style.display = '';\r\n restartButton.addEventListener('click', () => {\r\n this.stopCalibrationAudio();\r\n this.isCalibrating = true;\r\n restartButton.style.display = 'none';\r\n if (reminder) {\r\n reminder.style.display = 'none';\r\n }\r\n this.emit('update', {message: 'Restarting calibration...'});\r\n resolve('restart');\r\n });\r\n }\r\n await this.pyServerAPI.checkMemory();\r\n // calibrate volume\r\n\r\n let volumeResults = await this.startCalibrationVolume(\r\n stream,\r\n gainValues,\r\n lCalib,\r\n this.componentGainDBSPL\r\n );\r\n if (!volumeResults) return;\r\n this.T = volumeResults['parameters']['T'];\r\n this.gainDBSPL = volumeResults['parameters']['gainDBSPL'];\r\n\r\n // end calibrate volume\r\n\r\n let impulseResponseResults = await this.startCalibrationImpulseResponse(stream);\r\n if (!impulseResponseResults) return;\r\n impulseResponseResults['background_noise'] = this.background_noise;\r\n impulseResponseResults['system']['background_noise'] = this.background_noise;\r\n impulseResponseResults['component']['background_noise'] = this.background_noise;\r\n\r\n //attenuate system background noise\r\n if (this.systemAttenuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.systemAttenuatorGainDB / 20);\r\n let linearScalePowerAttenuation = Math.pow(10, this.systemAttenuatorGainDB / 10);\r\n impulseResponseResults['system']['background_noise']['recording'] = impulseResponseResults[\r\n 'background_noise'\r\n ]['recording'].map(value => value / linearScaleAttenuation);\r\n impulseResponseResults['system']['background_noise']['x_background'] =\r\n impulseResponseResults['background_noise']['x_background'];\r\n impulseResponseResults['system']['background_noise']['y_background'] =\r\n impulseResponseResults['background_noise']['y_background'].map(\r\n value => value / linearScalePowerAttenuation\r\n );\r\n }\r\n //attenuate component background noise\r\n if (this.componentAttentuatorGainDB != 0) {\r\n let linearScaleAttenuation = Math.pow(10, this.componentAttenuatorGainDB / 20);\r\n let linearScalePowerAttenuation = Math.pow(10, this.componentAttenuatorGainDB / 10);\r\n impulseResponseResults['component']['background_noise']['recording'] =\r\n impulseResponseResults['background_noise']['recording'].map(\r\n value => value / linearScaleAttenuation\r\n );\r\n impulseResponseResults['component']['background_noise']['x_background'] =\r\n impulseResponseResults['background_noise']['x_background'];\r\n impulseResponseResults['component']['background_noise']['y_background'] =\r\n impulseResponseResults['background_noise']['y_background'].map(\r\n value => value / linearScalePowerAttenuation\r\n );\r\n }\r\n impulseResponseResults['system']['attenuatorGainDB'] = this.systemAttenuatorGainDB;\r\n impulseResponseResults['component']['attenuatorGainDB'] = this.componentAttenuatorGainDB;\r\n impulseResponseResults['system']['fMaxHz'] = this.systemFMaxHz;\r\n impulseResponseResults['component']['fMaxHz'] = this.componentFMaxHz;\r\n impulseResponseResults['L_new_n'] = this.L_new_n;\r\n impulseResponseResults['fs2'] = this.fs2;\r\n\r\n if (componentIR != null) {\r\n // I corrected microphone/loudpeaker IR scale in easyeyes,\r\n // but since we write microphone IR to firestore here\r\n // we need to correct microphone IR here\r\n let correctGain =\r\n Math.round((volumeResults.parameters.gainDBSPL - this.componentGainDBSPL) * 10) / 10;\r\n\r\n let IrFreq = impulseResponseResults?.component.ir.Freq.map(freq => Math.round(freq));\r\n let IrGain = impulseResponseResults?.component?.ir.Gain;\r\n const IrGainAt1000Hz = IrGain[IrFreq.findIndex(freq => freq === 1000)];\r\n const difference = Math.round(10 * (IrGainAt1000Hz - correctGain)) / 10;\r\n IrGain = IrGain.map(gain => gain - difference);\r\n micInfo['mls'] = Number(this.SDofFilteredRange['mls']);\r\n micInfo['systemCorrectionSD'] = Number(this.SDofFilteredRange['system']);\r\n micInfo['componentCorrectionSD'] = Number(this.SDofFilteredRange['component']);\r\n console.log(typeof micInfo['componentCorrectionSD']);\r\n // const id = await this.writeIsSmartPhoneToFirestore(ID, isSmartPhone, OEM);\r\n // await this.writeMicrophoneInfoToFirestore(ID, micInfo, OEM, id);\r\n // await this.writeFrqGainToFirestore(ID, IrFreq, IrGain, OEM, id);\r\n // micInfo['gainDBSPL'] = impulseResponseResults.component.gainDBSPL;\r\n // await this.writeGainat1000HzToFirestore(ID, micInfo['gainDBSPL'], OEM, id);\r\n // await this.writeGainat1000Hz(ID, micInfo['gainDBSPL'], OEM);\r\n }\r\n const total_results = {...volumeResults, ...impulseResponseResults};\r\n total_results['filteredMLSRange'] = this.filteredMLSRange;\r\n total_results['filteredMLSAttenuation'] = this.filteredMLSAttenuation;\r\n total_results['micInfo'] = micInfo;\r\n total_results['audioInfo'] = {};\r\n total_results['audioInfo']['sinkSampleRate'] = this.sinkSamplingRate;\r\n total_results['audioInfo']['sourceSampleRate'] = this.sourceSamplingRate;\r\n total_results['audioInfo']['bitsPerSample'] = this.sampleSize;\r\n const timeStampresult = [...this.timeStamp].join('\\n');\r\n total_results['timeStamps'] = timeStampresult;\r\n total_results['recordingChecks'] = this.recordingChecks;\r\n total_results['waveforms'] = this.waveforms;\r\n total_results['component']['phase'] = this.componentIRPhase;\r\n total_results['system']['phase'] = this.systemIRPhase;\r\n total_results['qualityMetrics'] = this.SDofFilteredRange;\r\n total_results['flags'] = this.flags;\r\n console.log('total results');\r\n console.log(total_results);\r\n console.log('Time Stamps');\r\n console.log(timeStampresult);\r\n\r\n resolve(total_results);\r\n });\r\n };\r\n}\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Combination);\n\n//# sourceURL=webpack://speakerCalibrator/./src/tasks/combination/combination.js?");
516
516
 
517
517
  /***/ }),
518
518
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "speaker-calibration",
3
- "version": "2.2.207",
3
+ "version": "2.2.209",
4
4
  "description": "Speaker calibration library for auditory testing",
5
5
  "main": "dist/main.js",
6
6
  "directories": {
@@ -114,10 +114,15 @@ class AudioPeer {
114
114
  this.displayUpdate('Connection lost. Please reconnect');
115
115
 
116
116
  // Workaround for peer.reconnect deleting previous id
117
- this.peer.id = this.lastPeerId;
117
+ try {
118
+ this.peer.id = this.lastPeerId;
118
119
  // eslint-disable-next-line no-underscore-dangle
119
120
  this.peer._lastServerId = this.lastPeerId;
120
121
  this.peer.reconnect();
122
+ } catch(e) {
123
+ console.log(e);
124
+ }
125
+
121
126
  };
122
127
 
123
128
  /** .
@@ -255,6 +255,8 @@ class Listener extends AudioPeer {
255
255
  // ...(availableConstraints.channelCount && availableConstraints.channelCount == true
256
256
  // ? {channelCount: {exact: 1}}
257
257
  // : {}),
258
+ autoGainControl: false,
259
+ noiseSuppression: false,
258
260
  echoCancellation: false,
259
261
  channelCount: 1,
260
262
  };
@@ -210,6 +210,7 @@ class Speaker extends AudioPeer {
210
210
  params.language,
211
211
  params.loudspeakerModelName,
212
212
  params.phrases,
213
+ params.soundSubtitleId,
213
214
  );
214
215
  speaker.#removeUIElems();
215
216
  resolve(speaker.result);
@@ -719,6 +720,7 @@ class Speaker extends AudioPeer {
719
720
  params.language,
720
721
  params.loudspeakerModelName,
721
722
  params.phrases,
723
+ params.soundSubtitleId,
722
724
  );
723
725
  this.#removeUIElems();
724
726
  resolve(result);
@@ -311,7 +311,13 @@ class Combination extends AudioCalibrator {
311
311
  let componentSD = '';
312
312
  let systemSD = '';
313
313
  let flags = '';
314
- const reportWebAudioNames = `<strong>${this.webAudioDeviceNames.loudspeakerText} </strong> <strong>${this.webAudioDeviceNames.microphoneText} </strong>`;
314
+ const soundSubtitle = document.getElementById(this.soundSubtitleId);
315
+ if(soundSubtitle)
316
+ {
317
+ const reportWebAudioNames = `${this.webAudioDeviceNames.loudspeakerText}<br/> ${this.webAudioDeviceNames.microphoneText}`;
318
+ soundSubtitle.innerHTML = reportWebAudioNames;
319
+ }
320
+
315
321
  const samplingParamText = this.phrases.RC_SamplingHzBits[this.language].replace('111', this.sourceSamplingRate).replace('222',this.sinkSamplingRate).replace('333', this.calibrateSoundSamplingDesiredBits);
316
322
  const reportParameters = `${samplingParamText}`;
317
323
  if (this.flags) {
@@ -330,7 +336,6 @@ class Combination extends AudioCalibrator {
330
336
  }
331
337
  const template = `<div style="display: flex; justify-content: flex-start; margin-top: 0.4rem;"><div style="width: 100%; height: 20px; border: 2px solid #000; border-radius: 10px;"><div style="width: ${this.percent_complete}%; height: 100%; background-color: #00aaff; border-radius: 8px;"></div></div></div>`;
332
338
  return `
333
- ${reportWebAudioNames}
334
339
  ${reportParameters}
335
340
  ${MLSsd}
336
341
  ${systemSD}
@@ -2736,6 +2741,7 @@ class Combination extends AudioCalibrator {
2736
2741
  language,
2737
2742
  loudspeakerModelName='',
2738
2743
  phrases,
2744
+ soundSubtitleId,
2739
2745
 
2740
2746
  ) => {
2741
2747
  this._calibrateSoundBurstPreSec = _calibrateSoundBurstPreSec;
@@ -2774,6 +2780,7 @@ class Combination extends AudioCalibrator {
2774
2780
  this.webAudioDeviceNames = webAudioDeviceNames;
2775
2781
  this.calibrateSoundSamplingDesiredBits = calibrateSoundSamplingDesiredBits;
2776
2782
  this.phrases = phrases;
2783
+ this.soundSubtitleId = soundSubtitleId;
2777
2784
  if (isSmartPhone) {
2778
2785
  const leftQuote = "\u201C"; // “
2779
2786
  const rightQuote = "\u201D"; // ”