speaker-calibration 2.2.56 → 2.2.57
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 +3 -3
- package/package.json +1 -1
- package/src/tasks/combination/combination.js +11 -18
- package/src/utils.js +34 -1
package/dist/main.js
CHANGED
|
@@ -807,7 +807,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var qrco
|
|
|
807
807
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
808
808
|
|
|
809
809
|
"use strict";
|
|
810
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n\n/**\n *\n */\nclass PythonServerAPI {\n static PYTHON_SERVER_URL = 'https://easyeyes-python-flask-server.herokuapp.com';\n\n static TEST_SERVER_URL = 'http://127.0.0.1:5000';\n // static PYTHON_SERVER_URL ='http://127.0.0.1:5000';\n\n /** @private */\n MAX_RETRY_COUNT = 3;\n /** @private */\n RETRY_DELAY_MS = 1000;\n /**\n * @param data- -\n * g = inverted impulse response, when convolved with the impulse\n * reponse, they cancel out.\n * @param data.payload\n * @param data.sampleRate\n * @param data.P\n * @param data-.payload\n * @param data-.sampleRate\n * @param data-.P\n * @returns\n * @example\n */\n getImpulseResponse = async ({mls, payload, sampleRate, P, numPeriods}) => {\n const task = 'impulse-response';\n let res = null;\n\n console.log({payload});\n\n const data = JSON.stringify({\n task,\n payload,\n 'sample-rate': sampleRate,\n mls,\n P,\n numPeriods,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n return res.data[task];\n };\n\n getMLS = async ({length,calibrateSoundBurstDb}) => {\n const task = 'mls';\n let res = null;\n\n const data = JSON.stringify({\n task,\n length: length,\n calibrateSoundBurstDb: calibrateSoundBurstDb\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n getMLSWithRetry = async ({length,calibrateSoundBurstDb}) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getMLS({length,calibrateSoundBurstDb});\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(`Failed to get MLS after ${this.MAX_RETRY_COUNT} attempts.`);\n }\n };\n\n getPSD = async ({unconv_rec, conv_rec, sampleRate}) => {\n const task = 'psd';\n let res = null;\n\n const data = JSON.stringify({\n task,\n unconv_rec,\n conv_rec,\n sampleRate,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n return res.data[task];\n };\n\n getBackgroundNoisePSD = async ({background_rec, sampleRate}) => {\n const task = 'background-psd';\n let res = null;\n\n const data = JSON.stringify({\n task,\n background_rec,\n sampleRate,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n return res.data[task];\n };\n\n getBackgroundNoisePSDWithRetry = async ({background_rec, sampleRate}) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getBackgroundNoisePSD({background_rec, sampleRate});\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(`Failed to get PSD after ${this.MAX_RETRY_COUNT} attempts.`);\n }\n };\n\n getSubtractedPSD = async (rec, knownGains, knownFrequencies, sampleRate) => {\n const task = 'subtracted-psd';\n let res = null;\n\n const data = JSON.stringify({\n task,\n rec,\n knownGains,\n knownFrequencies,\n sampleRate,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n return res.data[task];\n };\n\n getSubtractedPSDWithRetry = async (rec, knownGains, knownFrequencies, sampleRate) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getSubtractedPSD(rec, knownGains, knownFrequencies, sampleRate);\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(`Failed to get PSD after ${this.MAX_RETRY_COUNT} attempts.`);\n }\n };\n\n getPSDWithRetry = async ({unconv_rec, conv_rec, sampleRate}) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getPSD({unconv_rec, conv_rec, sampleRate});\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(`Failed to get PSD after ${this.MAX_RETRY_COUNT} attempts.`);\n }\n };\n\n getComponentInverseImpulseResponse = async ({\n payload,\n mls,\n lowHz,\n highHz,\n componentIRGains,\n iirLength,\n componentIRFreqs,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n }) => {\n const task = 'component-inverse-impulse-response';\n let res = null;\n\n console.log({payload});\n\n const data = JSON.stringify({\n task,\n payload,\n mls,\n lowHz,\n highHz,\n iirLength,\n componentIRGains,\n componentIRFreqs,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n getSystemInverseImpulseResponse = async ({\n payload,\n mls,\n lowHz,\n highHz,\n iirLength,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n }) => {\n const task = 'system-inverse-impulse-response';\n let res = null;\n\n console.log({payload});\n\n const data = JSON.stringify({\n task,\n payload,\n mls,\n lowHz,\n iirLength,\n highHz,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n\n getMLSPSD = async ({mls, sampleRate}) => {\n const task = 'mls-psd';\n let res = null;\n\n const data = JSON.stringify({\n task,\n mls,\n sampleRate,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n\n getMLSPSDWithRetry = async ({mls, sampleRate}) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getMLSPSD({mls, sampleRate});\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(\n `Failed to get inverse impulse response after ${this.MAX_RETRY_COUNT} attempts.`\n );\n }\n };\n\n getComponentInverseImpulseResponseWithRetry = async ({\n payload,\n mls,\n lowHz,\n highHz,\n componentIRGains,\n iirLength,\n componentIRFreqs,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n }) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getComponentInverseImpulseResponse({\n payload,\n mls,\n lowHz,\n highHz,\n componentIRGains,\n iirLength,\n componentIRFreqs,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n });\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(\n `Failed to get inverse impulse response after ${this.MAX_RETRY_COUNT} attempts.`\n );\n }\n };\n\n getSystemInverseImpulseResponseWithRetry = async ({\n payload,\n mls,\n lowHz,\n highHz,\n iirLength,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n }) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getSystemInverseImpulseResponse({\n payload,\n mls,\n lowHz,\n highHz,\n iirLength,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n });\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(\n `Failed to get inverse impulse response after ${this.MAX_RETRY_COUNT} attempts.`\n );\n }\n };\n\n getVolumeCalibration = async ({payload, sampleRate, lCalib}) => {\n const task = 'volume';\n let res = null;\n\n console.log({payload});\n\n const data = JSON.stringify({\n task,\n payload,\n 'sample-rate': sampleRate,\n lCalib,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n\n getVolumeCalibrationParameters = async ({\n inDBValues,\n outDBSPLValues,\n lCalib,\n componentGainDBSPL,\n }) => {\n const task = 'volume-parameters';\n let res = null;\n\n const data = JSON.stringify({\n task,\n inDBValues,\n outDBSPLValues,\n lCalib,\n componentGainDBSPL,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL, //server\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n console.log(res.data[task]);\n })\n .catch(error => {\n throw error;\n });\n\n // console.log(res.data[task]);\n //below is an example of res.data[task]\n //{\n // R: 16.56981076554259,\n // RMSError: 1.9289162528535229\n // T: -47.79799120884434,\n // W: 61.0485247483732,\n // backgroundDBSPL: 43.88233142069752,\n // gainDBSPL: -128.24742161208985\n //}\n return res.data[task];\n };\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (PythonServerAPI);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/server/PythonServerAPI.js?");
|
|
810
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n\n/**\n *\n */\nclass PythonServerAPI {\n // static PYTHON_SERVER_URL = 'https://easyeyes-python-flask-server.herokuapp.com';\n\n static TEST_SERVER_URL = 'http://127.0.0.1:5000';\n static PYTHON_SERVER_URL ='http://127.0.0.1:5000';\n\n /** @private */\n MAX_RETRY_COUNT = 3;\n /** @private */\n RETRY_DELAY_MS = 1000;\n /**\n * @param data- -\n * g = inverted impulse response, when convolved with the impulse\n * reponse, they cancel out.\n * @param data.payload\n * @param data.sampleRate\n * @param data.P\n * @param data-.payload\n * @param data-.sampleRate\n * @param data-.P\n * @returns\n * @example\n */\n getImpulseResponse = async ({mls, payload, sampleRate, P, numPeriods}) => {\n const task = 'impulse-response';\n let res = null;\n\n console.log({payload});\n\n const data = JSON.stringify({\n task,\n payload,\n 'sample-rate': sampleRate,\n mls,\n P,\n numPeriods,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n return res.data[task];\n };\n\n getMLS = async ({length,calibrateSoundBurstDb}) => {\n const task = 'mls';\n let res = null;\n\n const data = JSON.stringify({\n task,\n length: length,\n calibrateSoundBurstDb: calibrateSoundBurstDb\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n getMLSWithRetry = async ({length,calibrateSoundBurstDb}) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getMLS({length,calibrateSoundBurstDb});\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(`Failed to get MLS after ${this.MAX_RETRY_COUNT} attempts.`);\n }\n };\n\n getPSD = async ({unconv_rec, conv_rec, sampleRate}) => {\n const task = 'psd';\n let res = null;\n\n const data = JSON.stringify({\n task,\n unconv_rec,\n conv_rec,\n sampleRate,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n return res.data[task];\n };\n\n getBackgroundNoisePSD = async ({background_rec, sampleRate}) => {\n const task = 'background-psd';\n let res = null;\n\n const data = JSON.stringify({\n task,\n background_rec,\n sampleRate,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n return res.data[task];\n };\n\n getBackgroundNoisePSDWithRetry = async ({background_rec, sampleRate}) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getBackgroundNoisePSD({background_rec, sampleRate});\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(`Failed to get PSD after ${this.MAX_RETRY_COUNT} attempts.`);\n }\n };\n\n getSubtractedPSD = async (rec, knownGains, knownFrequencies, sampleRate) => {\n const task = 'subtracted-psd';\n let res = null;\n\n const data = JSON.stringify({\n task,\n rec,\n knownGains,\n knownFrequencies,\n sampleRate,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n return res.data[task];\n };\n\n getSubtractedPSDWithRetry = async (rec, knownGains, knownFrequencies, sampleRate) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getSubtractedPSD(rec, knownGains, knownFrequencies, sampleRate);\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(`Failed to get PSD after ${this.MAX_RETRY_COUNT} attempts.`);\n }\n };\n\n getPSDWithRetry = async ({unconv_rec, conv_rec, sampleRate}) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getPSD({unconv_rec, conv_rec, sampleRate});\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(`Failed to get PSD after ${this.MAX_RETRY_COUNT} attempts.`);\n }\n };\n\n getComponentInverseImpulseResponse = async ({\n payload,\n mls,\n lowHz,\n highHz,\n componentIRGains,\n iirLength,\n componentIRFreqs,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n }) => {\n const task = 'component-inverse-impulse-response';\n let res = null;\n\n console.log({payload});\n\n const data = JSON.stringify({\n task,\n payload,\n mls,\n lowHz,\n highHz,\n iirLength,\n componentIRGains,\n componentIRFreqs,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n getSystemInverseImpulseResponse = async ({\n payload,\n mls,\n lowHz,\n highHz,\n iirLength,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n }) => {\n const task = 'system-inverse-impulse-response';\n let res = null;\n\n console.log({payload});\n\n const data = JSON.stringify({\n task,\n payload,\n mls,\n lowHz,\n iirLength,\n highHz,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n\n getMLSPSD = async ({mls, sampleRate}) => {\n const task = 'mls-psd';\n let res = null;\n\n const data = JSON.stringify({\n task,\n mls,\n sampleRate,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n\n getMLSPSDWithRetry = async ({mls, sampleRate}) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getMLSPSD({mls, sampleRate});\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(\n `Failed to get inverse impulse response after ${this.MAX_RETRY_COUNT} attempts.`\n );\n }\n };\n\n getComponentInverseImpulseResponseWithRetry = async ({\n payload,\n mls,\n lowHz,\n highHz,\n componentIRGains,\n iirLength,\n componentIRFreqs,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n }) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getComponentInverseImpulseResponse({\n payload,\n mls,\n lowHz,\n highHz,\n componentIRGains,\n iirLength,\n componentIRFreqs,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n });\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(\n `Failed to get inverse impulse response after ${this.MAX_RETRY_COUNT} attempts.`\n );\n }\n };\n\n getSystemInverseImpulseResponseWithRetry = async ({\n payload,\n mls,\n lowHz,\n highHz,\n iirLength,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n }) => {\n let retryCount = 0;\n let response = null;\n\n while (retryCount < this.MAX_RETRY_COUNT) {\n try {\n response = await this.getSystemInverseImpulseResponse({\n payload,\n mls,\n lowHz,\n highHz,\n iirLength,\n num_periods,\n sampleRate,\n calibrateSoundBurstDb\n });\n // If the request is successful, break out of the loop\n break;\n } catch (error) {\n console.error(`Error occurred. Retrying... (${retryCount + 1}/${this.MAX_RETRY_COUNT})`);\n retryCount++;\n await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY_MS));\n }\n }\n\n if (response) {\n return response;\n } else {\n throw new Error(\n `Failed to get inverse impulse response after ${this.MAX_RETRY_COUNT} attempts.`\n );\n }\n };\n\n getVolumeCalibration = async ({payload, sampleRate, lCalib}) => {\n const task = 'volume';\n let res = null;\n\n console.log({payload});\n\n const data = JSON.stringify({\n task,\n payload,\n 'sample-rate': sampleRate,\n lCalib,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL,\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n })\n .catch(error => {\n throw error;\n });\n\n return res.data[task];\n };\n\n getVolumeCalibrationParameters = async ({\n inDBValues,\n outDBSPLValues,\n lCalib,\n componentGainDBSPL,\n }) => {\n const task = 'volume-parameters';\n let res = null;\n\n const data = JSON.stringify({\n task,\n inDBValues,\n outDBSPLValues,\n lCalib,\n componentGainDBSPL,\n });\n\n await axios__WEBPACK_IMPORTED_MODULE_0___default()({\n method: 'post',\n baseURL: PythonServerAPI.PYTHON_SERVER_URL, //server\n url: `/task/${task}`,\n headers: {\n 'Content-Type': 'application/json',\n },\n data,\n })\n .then(response => {\n res = response;\n console.log(res.data[task]);\n })\n .catch(error => {\n throw error;\n });\n\n // console.log(res.data[task]);\n //below is an example of res.data[task]\n //{\n // R: 16.56981076554259,\n // RMSError: 1.9289162528535229\n // T: -47.79799120884434,\n // W: 61.0485247483732,\n // backgroundDBSPL: 43.88233142069752,\n // gainDBSPL: -128.24742161208985\n //}\n return res.data[task];\n };\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (PythonServerAPI);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/server/PythonServerAPI.js?");
|
|
811
811
|
|
|
812
812
|
/***/ }),
|
|
813
813
|
|
|
@@ -840,7 +840,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _myE
|
|
|
840
840
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
841
841
|
|
|
842
842
|
"use strict";
|
|
843
|
-
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 _config_firebase__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../config/firebase */ \"./src/config/firebase.js\");\n/* harmony import */ var firebase_database__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! firebase/database */ \"./node_modules/firebase/database/dist/esm/index.esm.js\");\n\n\n\n\n\n\n/**\n *\n */\nclass Combination extends _audioCalibrator__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\n /**\n * Default constructor. Creates an instance with any number of paramters passed or the default parameters defined here.\n *\n * @param {Object<boolean, number, number, number>} calibratorParams - paramter object\n * @param {boolean} [calibratorParams.download = false] - boolean flag to download captures\n * @param {number} [calibratorParams.mlsOrder = 18] - order of the MLS to be generated\n * @param {number} [calibratorParams.numCaptures = 5] - number of captures to perform\n * @param {number} [calibratorParams.numMLSPerCapture = 2] - number of bursts of MLS per capture\n */\n constructor({\n download = false,\n mlsOrder = 18,\n numCaptures = 3,\n numMLSPerCapture = 2,\n lowHz = 20,\n highHz = 10000,\n }) {\n super(numCaptures, numMLSPerCapture);\n this.#mlsOrder = parseInt(mlsOrder, 10);\n this.#P = 2 ** mlsOrder - 1;\n this.#download = download;\n this.#mls = [];\n this.#lowHz = lowHz;\n this.#highHz = highHz;\n }\n\n /** @private */\n stepNum = 0;\n\n /** @private */\n totalSteps = 25;\n\n /** @private */\n #download;\n\n /** @private */\n #mlsGenInterface;\n\n /** @private */\n #mlsBufferView;\n\n /** @private */\n componentInvertedImpulseResponse = null;\n\n /** @private */\n systemInvertedImpulseResponse = null;\n\n //averaged and subtracted ir returned from calibration used to calculated iir\n /** @private */\n ir = null;\n\n /** @private */\n impulseResponses = [];\n\n /** @private */\n #mlsOrder;\n\n /** @private */\n #lowHz;\n\n /** @private */\n #highHz;\n\n /** @private */\n #mls;\n\n /** @private */\n #P;\n\n /** @private */\n #audioContext;\n\n /** @private */\n TAPER_SECS = 5;\n\n /** @private */\n offsetGainNode;\n\n /** @private */\n componentConvolution;\n\n /** @private */\n systemConvolution;\n\n ////////////////////////volume\n /** @private */\n #CALIBRATION_TONE_FREQUENCY = 1000; // Hz\n\n /** @private */\n #CALIBRATION_TONE_TYPE = 'sine';\n\n CALIBRATION_TONE_DURATION = 5; // seconds\n calibrateSound1000HzPreSec = 3.5;\n calibrateSound1000HzSec = 1.0;\n calibrateSound1000HzPostSec = 0.5;\n\n /** @private */\n outDBSPL = null;\n THD = null;\n outDBSPL1000 = null;\n\n /** @private */\n TAPER_SECS = 0.01; // seconds\n\n /** @private */\n status_denominator = 8;\n\n /** @private */\n status_numerator = 0;\n\n /** @private */\n percent_complete = 0;\n\n /** @private */\n status = ``;\n\n /**@private */\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>`;\n\n /**@private */\n componentIR = null;\n\n /**@private */\n oldComponentIR = null;\n\n /**@private */\n systemIR = null;\n\n /**@private */\n _calibrateSoundCheck = '';\n\n deviceType = null;\n\n deviceName = null;\n\n deviceInfo = null;\n\n desired_time_per_mls = 0;\n\n num_mls_to_skip = 0;\n\n desired_sampling_rate = 0;\n\n #currentConvolution = [];\n\n mode = 'unfiltered';\n\n sourceNode;\n\n autocorrelations = [];\n\n iirLength = 0;\n\n componentInvertedImpulseResponseNoBandpass = [];\n\n systemInvertedImpulseResponseNoBandpass = [];\n\n _calibrateSoundBackgroundSecs;\n\n background_noise = {};\n\n numSuccessfulBackgroundCaptured;\n\n _calibrateSoundBurstDb;\n\n filteredMLSRange = {\n component: {\n Min: null,\n Max: null,\n },\n system: {\n Min: null,\n Max: null,\n },\n };\n\n /**generate string template that gets reevaluated as variable increases */\n generateTemplate = () => {\n if (this.percent_complete > 100) {\n this.percent_complete = 100;\n }\n const template = `<div style=\"display: flex; justify-content: center; margin-top:12px;\"><div style=\"width: 800px; 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>`;\n return template;\n };\n\n /** increment numerator and percent for status bar */\n incrementStatusBar = () => {\n this.status_numerator += 1;\n this.percent_complete = (this.status_numerator / this.status_denominator) * 100;\n };\n\n setDeviceType = deviceType => {\n this.deviceType = deviceType;\n };\n\n setDeviceName = deviceName => {\n this.deviceName = deviceName;\n };\n\n setDeviceInfo = deviceInfo => {\n this.deviceInfo = deviceInfo;\n };\n\n /** .\n * .\n * .\n * Sends all the computed impulse responses to the backend server for processing\n *\n * @returns sets the resulting inverted impulse response to the class property\n * @example\n */\n sendSystemImpulseResponsesToServerForProcessing = async () => {\n const computedIRs = await Promise.all(this.impulseResponses);\n const filteredComputedIRs = computedIRs.filter(element => {\n return element != undefined;\n }); //log any errors that are found in this step\n const mls = this.#mls;\n const lowHz = this.#lowHz; //gain of 1 below cutoff, need gain of 0\n const highHz = this.#highHz; //check error for anything other than 10 kHz\n const iirLength = this.iirLength;\n const num_periods = this.numMLSPerCapture + this.num_mls_to_skip;\n this.stepNum += 1;\n console.log('send impulse responses to server: ' + this.stepNum);\n this.status =\n `All Hz Calibration: computing the IIR...`.toString() + this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return this.pyServerAPI\n .getSystemInverseImpulseResponseWithRetry({\n payload: filteredComputedIRs.slice(0, this.numCaptures),\n mls,\n lowHz,\n highHz,\n iirLength,\n num_periods,\n sampleRate: this.sourceSamplingRate || 96000,\n calibrateSoundBurstDb: this._calibrateSoundBurstDb,\n })\n .then(res => {\n console.log(res);\n this.stepNum += 1;\n console.log('got impulse response ' + this.stepNum);\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the IIR...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n this.systemInvertedImpulseResponse = res['iir'];\n this.systemIR = res['ir'];\n this.systemConvolution = res['convolution'];\n this.systemInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];\n })\n .catch(err => {\n console.error(err);\n });\n };\n\n /** .\n * .\n * .\n * Sends all the computed impulse responses to the backend server for processing\n *\n * @returns sets the resulting inverted impulse response to the class property\n * @example\n */\n sendComponentImpulseResponsesToServerForProcessing = async () => {\n const computedIRs = await Promise.all(this.impulseResponses);\n const filteredComputedIRs = computedIRs.filter(element => {\n return element != undefined;\n });\n const componentIRGains = this.componentIR['Gain'];\n const componentIRFreqs = this.componentIR['Freq'];\n const mls = this.#mls;\n const lowHz = this.#lowHz;\n const iirLength = this.iirLength;\n const num_periods = this.numMLSPerCapture + this.num_mls_to_skip;\n const highHz = this.#highHz;\n this.stepNum += 1;\n console.log('send impulse responses to server: ' + this.stepNum);\n this.status =\n `All Hz Calibration: computing the IIR...`.toString() + this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return this.pyServerAPI\n .getComponentInverseImpulseResponseWithRetry({\n payload: filteredComputedIRs.slice(0, this.numCaptures),\n mls,\n lowHz,\n highHz,\n iirLength,\n componentIRGains,\n componentIRFreqs,\n num_periods,\n sampleRate: this.sourceSamplingRate || 96000,\n calibrateSoundBurstDb: this._calibrateSoundBurstDb,\n })\n .then(res => {\n console.log(res);\n this.stepNum += 1;\n console.log('got impulse response ' + this.stepNum);\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the IIR...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n this.componentInvertedImpulseResponse = res['iir'];\n this.componentIR['Gain'] = res['ir'];\n this.componentIR['Freq'] = res['frequencies'];\n this.componentConvolution = res['convolution'];\n this.componentInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];\n })\n .catch(err => {\n // this.emit('InvertedImpulseResponse', {res: false});\n console.error(err);\n });\n };\n\n sendBackgroundRecording = () => {\n const allSignals = this.getAllBackgroundRecordings();\n const numSignals = allSignals.length;\n const background_rec_whole = allSignals[numSignals - 1];\n const fraction = 0.5 / (this._calibrateSoundBackgroundSecs + 0.5);\n // Calculate the starting index for slicing the array\n const startIndex = Math.round(fraction * background_rec_whole.length);\n // Slice the array from the calculated start index to the end of the array\n const background_rec = background_rec_whole.slice(startIndex);\n console.log('Sending background recording to server for processing');\n this.pyServerAPI\n .getBackgroundNoisePSDWithRetry({\n background_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n if (this.numSuccessfulBackgroundCaptured < 1) {\n this.numSuccessfulBackgroundCaptured += 1;\n //storing all background data in background_psd object\n this.background_noise['x_background'] = res['x_background'];\n this.background_noise['y_background'] = res['y_background'];\n this.background_noise['recording'] = background_rec;\n }\n })\n .catch(err => {\n console.error(err);\n });\n };\n\n /** .\n * .\n * .\n * Sends the recorded signal, or a given csv string of a signal, to the back end server for processing\n *\n * @param {<array>String} signalCsv - Optional csv string of a previously recorded signal, if given, this signal will be processed\n * @example\n */\n sendRecordingToServerForProcessing = signalCsv => {\n const allSignals = this.getAllUnfilteredRecordedSignals();\n console.log(\n 'Obtaining last all hz unfiltered recording from #allHzUnfilteredRecordings to send to server for processing'\n );\n const numSignals = allSignals.length;\n const mls = this.#mlsBufferView;\n const payload =\n signalCsv && signalCsv.length > 0 ? (0,_utils__WEBPACK_IMPORTED_MODULE_1__.csvToArray)(signalCsv) : allSignals[numSignals - 1];\n console.log('sending rec');\n this.stepNum += 1;\n console.log('send rec ' + this.stepNum);\n this.status =\n `All Hz Calibration Step: computing the IR of the last recording...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n this.impulseResponses.push(\n this.pyServerAPI\n .getImpulseResponse({\n sampleRate: this.sourceSamplingRate || 96000,\n payload,\n mls,\n P: this.#P, //get rid of this\n numPeriods: this.numMLSPerCapture,\n })\n .then(res => {\n if (this.numSuccessfulCaptured < this.numCaptures) {\n this.numSuccessfulCaptured += 1;\n console.log('num succ capt: ' + this.numSuccessfulCaptured);\n this.stepNum += 1;\n console.log('got impulse response ' + this.stepNum);\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: ${this.numSuccessfulCaptured}/${this.numCaptures} IRs computed...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {\n message: this.status,\n });\n this.autocorrelations.push(res['autocorrelation']);\n return res['ir'];\n }\n })\n .catch(err => {\n console.error(err);\n })\n );\n };\n\n /**\n * Passed to the calibration steps function, awaits the desired amount of seconds to capture the desired number\n * of MLS periods defined in the constructor.\n *\n * @example\n */\n #awaitDesiredMLSLength = async () => {\n // seconds per MLS = P / SR\n // await N * P / SR\n this.stepNum += 1;\n console.log('await desired length ' + this.stepNum);\n this.status =\n `All Hz Calibration: sampling the calibration signal...`.toString() +\n `\\niteration ${this.stepNum}` +\n this.generateTemplate();\n this.emit('update', {\n message: this.status,\n });\n let time_to_wait = 0;\n if (this.mode === 'unfiltered') {\n //unfiltered\n time_to_wait = (this.#mls.length / this.sourceSamplingRate) * this.numMLSPerCapture;\n time_to_wait = time_to_wait * 1.1;\n } else if (this.mode === 'filtered') {\n //filtered\n // time_to_wait =\n // (this.#currentConvolution.length / this.sourceSamplingRate) *\n // (this.numMLSPerCapture / (this.num_mls_to_skip + this.numMLSPerCapture));\n time_to_wait =\n (this.#currentConvolution.length / this.sourceSamplingRate) * this.numMLSPerCapture;\n time_to_wait = time_to_wait * 1.1;\n } else {\n throw new Error('Mode broke in awaitDesiredMLSLength');\n }\n\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_wait);\n };\n\n /**\n * Passed to the background noise recording function, awaits the desired amount of seconds to capture the desired number\n * of seconds of background noise\n *\n * @example\n */\n #awaitBackgroundNoiseRecording = async () => {\n console.log(\n 'Waiting ' + this._calibrateSoundBackgroundSecs + ' second(s) to record background noise'\n );\n let time_to_wait = this._calibrateSoundBackgroundSecs + 0.5;\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_wait);\n };\n\n /** .\n * .\n * .\n * Passed to the calibration steps function, awaits the onset of the signal to ensure a steady state\n *\n * @example\n */\n #awaitSignalOnset = async () => {\n this.stepNum += 1;\n console.log('await signal onset ' + this.stepNum);\n this.status =\n `All Hz Calibration: waiting for the signal to stabilize...`.toString() +\n this.generateTemplate();\n this.emit('update', {\n message: this.status,\n });\n let number_of_bursts_to_skip = this.num_mls_to_skip;\n let time_to_sleep = 0;\n if (this.mode === 'unfiltered') {\n time_to_sleep = (this.#mls.length / this.sourceSamplingRate) * number_of_bursts_to_skip;\n } else if (this.mode === 'filtered') {\n console.log(this.#currentConvolution.length);\n // time_to_sleep =\n // (this.#currentConvolution.length / this.sourceSamplingRate) *\n // (number_of_bursts_to_skip / (number_of_bursts_to_skip + this.numMLSPerCapture));\n time_to_sleep =\n (this.#currentConvolution.length / this.sourceSamplingRate) * number_of_bursts_to_skip;\n } else {\n throw new Error('Mode broke in awaitSignalOnset');\n }\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_sleep);\n };\n\n /**\n * Called immediately after a recording is captured. Used to process the resulting signal\n * whether by sending the result to a server or by computing a result locally.\n *\n * @example\n */\n #afterMLSRecord = () => {\n console.log('after record');\n this.sendRecordingToServerForProcessing();\n };\n\n #afterMLSwIIRRecord = () => {\n if (this.numSuccessfulCaptured < 1) {\n this.numSuccessfulCaptured += 1;\n this.stepNum += 1;\n this.incrementStatusBar();\n console.log('after mls w iir record for some reason add numSucc capt ' + this.stepNum);\n this.status =\n `All Hz Calibration: ${this.numSuccessfulCaptured} recording of convolved MLS captured`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {\n message: this.status,\n });\n }\n };\n\n /** .\n * .\n * .\n * Created an S Curver Buffer to taper the signal onset\n *\n * @param {*} length\n * @param {*} phase\n * @returns\n * @example\n */\n static createSCurveBuffer = (length, phase) => {\n const curve = new Float32Array(length);\n let i;\n for (i = 0; i < length; i += 1) {\n // scale the curve to be between 0-1\n curve[i] = Math.sin((Math.PI * i) / length - phase) / 2 + 0.5;\n }\n return curve;\n };\n\n static createInverseSCurveBuffer = (length, phase) => {\n const curve = new Float32Array(length);\n let i;\n let j = length - 1;\n for (i = 0; i < length; i += 1) {\n // scale the curve to be between 0-1\n curve[i] = Math.sin((Math.PI * j) / length - phase) / 2 + 0.5;\n j -= 1;\n }\n return curve;\n };\n\n /**\n * Construct a Calibration Node with the calibration parameters.\n *\n * @param dataBuffer\n * @private\n * @example\n */\n #createCalibrationNodeFromBuffer = dataBuffer => {\n console.log('length databuffer');\n console.log(dataBuffer.length);\n if (!this.sourceAudioContext) {\n this.makeNewSourceAudioContext();\n }\n\n const buffer = this.sourceAudioContext.createBuffer(\n 1, // number of channels\n dataBuffer.length,\n this.sourceAudioContext.sampleRate // sample rate\n );\n\n const data = buffer.getChannelData(0); // get data\n if (this.mode === 'filtered') {\n console.log('check max and min of convolution');\n } else {\n console.log('check max and min of mls');\n }\n\n console.log('Max:', Math.min(...dataBuffer));\n console.log('Min:', Math.max(...dataBuffer));\n // fill the buffer with our data\n try {\n for (let i = 0; i < dataBuffer.length; i += 1) {\n data[i] = dataBuffer[i];\n }\n } catch (error) {\n console.error(error);\n }\n\n this.sourceNode = this.sourceAudioContext.createBufferSource();\n\n this.sourceNode.buffer = buffer;\n\n if (this.mode === 'filtered') {\n //used to not loop filtered\n this.sourceNode.loop = true;\n } else {\n this.sourceNode.loop = true;\n }\n\n this.sourceNode.connect(this.sourceAudioContext.destination);\n\n this.addCalibrationNode(this.sourceNode);\n };\n\n /**\n * Given a data buffer, creates the required calibration node\n *\n * @param {*} dataBufferArray\n * @example\n */\n #setCalibrationNodesFromBuffer = (dataBufferArray = [this.#mlsBufferView]) => {\n if (dataBufferArray.length === 1) {\n this.#createCalibrationNodeFromBuffer(dataBufferArray[0]);\n } else {\n throw new Error('The length of the data buffer array must be 1');\n }\n };\n\n /**\n * Creates an audio context and plays it for a few seconds.\n *\n * @private\n * @returns - Resolves when the audio is done playing.\n * @example\n */\n #playCalibrationAudio = () => {\n this.calibrationNodes[0].start(0);\n this.status = ``;\n if (this.mode === 'unfiltered') {\n console.log('mls', this.#mls); // before multiplied by calibrateSoundBurstDb\n console.log('mls buffer view', this.#mlsBufferView); // after multiplied by calibrateSoundBurstDb\n console.log('play calibration audio ' + this.stepNum);\n this.status =\n `All Hz Calibration: playing the calibration tone...`.toString() +\n this.generateTemplate().toString();\n } else if (this.mode === 'filtered') {\n console.log('play convolved audio ' + this.stepNum);\n this.status =\n `All Hz Calibration: playing the convolved calibration tone...`.toString() +\n this.generateTemplate().toString();\n } else {\n throw new Error('Mode is incorrect');\n }\n this.emit('update', {message: this.status});\n this.stepNum += 1;\n console.log('sink sampling rate');\n console.log(this.sinkSamplingRate);\n console.log('source sampling rate');\n console.log(this.sourceSamplingRate);\n };\n\n /** .\n * .\n * .\n * Stops the audio with tapered offset\n *\n * @example\n */\n #stopCalibrationAudio = () => {\n this.calibrationNodes[0].stop(0);\n this.calibrationNodes = [];\n this.sourceNode.disconnect();\n this.stepNum += 1;\n console.log('stop calibration audio ' + this.stepNum);\n this.status =\n `All Hz Calibration: stopping the calibration tone...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n };\n\n playMLSwithIIR = async (stream, convolution) => {\n let checkRec = false;\n this.mode = 'filtered';\n console.log('play mls with iir');\n //this.invertedImpulseResponse = iir\n\n await this.calibrationSteps(\n stream,\n this.#playCalibrationAudio, // play audio func (required)\n this.#createCalibrationNodeFromBuffer(convolution), // before play func\n this.#awaitSignalOnset, // before record\n () => this.numSuccessfulCaptured < 1,\n this.#awaitDesiredMLSLength, // during record\n this.#afterMLSwIIRRecord, // after record\n this.mode,\n checkRec\n );\n };\n\n bothSoundCheck = async stream => {\n let iir_ir_and_plots;\n this.#currentConvolution = this.componentConvolution;\n this.filteredMLSRange.component.Min = Math.min(...this.#currentConvolution);\n this.filteredMLSRange.component.Max = Math.max(...this.#currentConvolution);\n await this.playMLSwithIIR(stream, this.#currentConvolution);\n this.#stopCalibrationAudio();\n let component_conv_recs = this.getAllFilteredRecordedSignals();\n let return_component_conv_rec = component_conv_recs[0];\n this.clearAllFilteredRecordedSignals();\n this.#currentConvolution = this.systemConvolution;\n this.filteredMLSRange.system.Min = Math.min(...this.#currentConvolution);\n this.filteredMLSRange.system.Max = Math.max(...this.#currentConvolution);\n await this.playMLSwithIIR(stream, this.#currentConvolution);\n this.#stopCalibrationAudio();\n let system_conv_recs = this.getAllFilteredRecordedSignals();\n let return_system_conv_rec = system_conv_recs[0];\n this.sourceAudioContext.close();\n let recs = this.getAllUnfilteredRecordedSignals();\n let unconv_rec = recs[0];\n let return_unconv_rec = unconv_rec;\n let conv_rec = component_conv_recs[0];\n\n //psd of component\n let knownGain = this.oldComponentIR.Gain;\n let knownFreq = this.oldComponentIR.Freq;\n let sampleRate = this.sourceSamplingRate || 96000;\n let component_unconv_rec_psd = await this.pyServerAPI\n .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let component_conv_rec_psd = await this.pyServerAPI\n .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n conv_rec = system_conv_recs[0];\n //psd of system\n let system_recs_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n //iir w/ and without bandpass psd. done\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\n conv_rec = this.componentInvertedImpulseResponse;\n let component_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\n conv_rec = this.systemInvertedImpulseResponse;\n let system_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({mls: this.#mlsBufferView, sampleRate: this.sourceSamplingRate || 96000})\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let system_filtered_mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.systemConvolution,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let component_filtered_mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.componentConvolution,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n iir_ir_and_plots = {\n filtered_recording: {\n component: return_component_conv_rec,\n system: return_system_conv_rec,\n },\n unfiltered_recording: this.getAllUnfilteredRecordedSignals()[0],\n system: {\n iir: this.systemInvertedImpulseResponse,\n ir: this.systemIR,\n iir_psd: {\n y: system_iir_psd['y_conv'],\n x: system_iir_psd['x_conv'],\n y_no_bandpass: system_iir_psd['y_unconv'],\n x_no_bandpass: system_iir_psd['x_unconv'],\n },\n filtered_mls_psd: {\n x: system_filtered_mls_psd['x_mls'],\n y: system_filtered_mls_psd['y_mls'],\n },\n convolution: this.systemConvolution,\n psd: {\n unconv: {\n x: system_recs_psd['x_unconv'],\n y: system_recs_psd['y_unconv'],\n },\n conv: {\n x: system_recs_psd['x_conv'],\n y: system_recs_psd['y_conv'],\n },\n },\n },\n component: {\n iir: this.componentInvertedImpulseResponse,\n ir: this.componentIR,\n iir_psd: {\n y: component_iir_psd['y_conv'],\n x: component_iir_psd['x_conv'],\n y_no_bandpass: component_iir_psd['y_unconv'],\n x_no_bandpass: component_iir_psd['x_unconv'],\n },\n filtered_mls_psd: {\n x: component_filtered_mls_psd['x_mls'],\n y: component_filtered_mls_psd['y_mls'],\n },\n convolution: this.componentConvolution,\n psd: {\n unconv: {\n x: component_unconv_rec_psd['x'],\n y: component_unconv_rec_psd['y'],\n },\n conv: {\n x: component_conv_rec_psd['x'],\n y: component_conv_rec_psd['y'],\n },\n },\n },\n mls: this.#mlsBufferView,\n mls_psd: {\n x: mls_psd['x_mls'],\n y: mls_psd['y_mls'],\n },\n autocorrelations: this.autocorrelations,\n impulseResponses: [],\n };\n\n return iir_ir_and_plots;\n };\n\n singleSoundCheck = async stream => {\n let iir_ir_and_plots;\n if (this._calibrateSoundCheck != 'system') {\n this.#currentConvolution = this.componentConvolution;\n this.filteredMLSRange.component.Min = Math.min(...this.#currentConvolution);\n this.filteredMLSRange.component.Max = Math.max(...this.#currentConvolution);\n } else {\n this.#currentConvolution = this.systemConvolution;\n this.filteredMLSRange.system.Min = Math.min(...this.#currentConvolution);\n this.filteredMLSRange.system.Max = Math.max(...this.#currentConvolution);\n }\n await this.playMLSwithIIR(stream, this.#currentConvolution);\n this.#stopCalibrationAudio();\n this.sourceAudioContext.close();\n let conv_recs = this.getAllFilteredRecordedSignals();\n let recs = this.getAllUnfilteredRecordedSignals();\n console.log('Obtaining unfiltered recording from #allHzUnfilteredRecordings to calculate PSD');\n console.log('Obtaining filtered recording from #allHzFilteredRecordings to calculate PSD');\n let unconv_rec = recs[0];\n let return_unconv_rec = unconv_rec;\n let conv_rec = conv_recs[0];\n let return_conv_rec = conv_rec;\n if (this._calibrateSoundCheck != 'system') {\n let knownGain = this.oldComponentIR.Gain;\n let knownFreq = this.oldComponentIR.Freq;\n let sampleRate = this.sourceSamplingRate || 96000;\n let unconv_results = await this.pyServerAPI\n .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let conv_results = await this.pyServerAPI\n .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\n conv_rec = this.componentInvertedImpulseResponse;\n let component_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\n conv_rec = this.systemInvertedImpulseResponse;\n let system_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.#mlsBufferView,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let filtered_mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.componentConvolution,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n iir_ir_and_plots = {\n unfiltered_recording: return_unconv_rec,\n filtered_recording: return_conv_rec,\n system: {\n iir: this.systemInvertedImpulseResponse,\n ir: this.systemIR,\n iir_psd: {\n y: system_iir_psd['y_conv'],\n x: system_iir_psd['y_conv'],\n y_no_bandpass: system_iir_psd['y_unconv'],\n x_no_bandpass: system_iir_psd['x_unconv'],\n },\n filtered_recording: [],\n filtered_mls_psd: {},\n convolution: this.systemConvolution,\n psd: {\n unconv: {\n x: [],\n y: [],\n },\n conv: {\n x: [],\n y: [],\n },\n },\n },\n component: {\n iir: this.componentInvertedImpulseResponse,\n ir: this.componentIR,\n iir_psd: {\n y: component_iir_psd['y_conv'],\n x: component_iir_psd['x_conv'],\n y_no_bandpass: component_iir_psd['y_unconv'],\n x_no_bandpass: component_iir_psd['x_unconv'],\n },\n filtered_mls_psd: {\n x: filtered_mls_psd['x_mls'],\n y: filtered_mls_psd['y_mls'],\n },\n convolution: this.componentConvolution,\n psd: {\n unconv: {\n x: unconv_results['x'],\n y: unconv_results['y'],\n },\n conv: {\n x: conv_results['x'],\n y: conv_results['y'],\n },\n },\n },\n mls: this.#mlsBufferView,\n mls_psd: {\n x: mls_psd['x_mls'],\n y: mls_psd['y_mls'],\n },\n autocorrelations: this.autocorrelations,\n impulseResponses: [],\n };\n } else {\n let results = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n //iir w/ and without bandpass psd\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\n conv_rec = this.componentInvertedImpulseResponse;\n let component_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\n conv_rec = this.systemInvertedImpulseResponse;\n let system_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.#mlsBufferView,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let filtered_mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.systemConvolution,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n iir_ir_and_plots = {\n unfiltered_recording: return_unconv_rec,\n filtered_recording: return_conv_rec,\n system: {\n iir: this.systemInvertedImpulseResponse,\n ir: this.systemIR,\n iir_psd: {\n y: system_iir_psd['y_conv'],\n x: system_iir_psd['y_conv'],\n y_no_bandpass: system_iir_psd['y_unconv'],\n x_no_bandpass: system_iir_psd['x_unconv'],\n },\n filtered_recording: [],\n filtered_mls_psd: {\n x: filtered_mls_psd['x_mls'],\n y: filtered_mls_psd['y_mls'],\n },\n convolution: this.systemConvolution,\n psd: {\n unconv: {\n x: results['x_unconv'],\n y: results['y_unconv'],\n },\n conv: {\n x: results['x_conv'],\n y: results['y_conv'],\n },\n },\n },\n component: {\n iir: this.componentInvertedImpulseResponse,\n ir: this.componentIR,\n iir_psd: {\n y: component_iir_psd['y_conv'],\n x: component_iir_psd['x_conv'],\n y_no_bandpass: component_iir_psd['y_unconv'],\n x_no_bandpass: component_iir_psd['x_unconv'],\n },\n filtered_mls_psd: {},\n convolution: this.componentConvolution,\n psd: {\n unconv: {\n x: [],\n y: [],\n },\n conv: {\n x: [],\n y: [],\n },\n },\n },\n mls: this.#mlsBufferView,\n mls_psd: {\n x: mls_psd['x_mls'],\n y: mls_psd['y_mls'],\n },\n autocorrelations: this.autocorrelations,\n impulseResponses: [],\n };\n }\n await Promise.all(this.impulseResponses).then(res => {\n for (let i = 0; i < res.length; i++) {\n if (res[i] != undefined) {\n iir_ir_and_plots['impulseResponses'].push(res[i]);\n }\n }\n });\n\n if (this.#download) {\n this.downloadSingleUnfilteredRecording();\n this.downloadSingleFilteredRecording();\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.#mls, 'MLS.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentConvolution, 'python_component_convolution_mls_iir.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemConvolution, 'python_system_convolution_mls_iir.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentInvertedImpulseResponse, 'componentIIR.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemInvertedImpulseResponse, 'systemIIR.csv');\n for (let i = 0; i < this.autocorrelations.length; i++) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.autocorrelations[i], `autocorrelation_${i}`);\n }\n const computedIRagain = await Promise.all(this.impulseResponses).then(res => {\n for (let i = 0; i < res.length; i++) {\n if (res[i] != undefined) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(res[i], `IR_${i}`);\n }\n }\n });\n }\n\n return iir_ir_and_plots;\n };\n\n /**\n * Public method to start the calibration process. Objects intialized from webassembly allocate new memory\n * and must be manually freed. This function is responsible for intializing the MlsGenInterface,\n * and wrapping the calibration steps with a garbage collection safe gaurd.\n *\n * @public\n * @param stream - The stream of audio from the Listener.\n * @example\n */\n startCalibrationImpulseResponse = async stream => {\n let desired_time = this.desired_time_per_mls;\n let checkRec = 'allhz';\n\n console.log('MLS sequence should be of length: ' + this.sourceSamplingRate * desired_time);\n\n length = this.sourceSamplingRate * desired_time;\n //get mls here\n const calibrateSoundBurstDb = this._calibrateSoundBurstDb;\n await this.pyServerAPI\n .getMLSWithRetry({length, calibrateSoundBurstDb})\n .then(res => {\n console.log(res);\n this.#mlsBufferView = res['mls'];\n this.#mls = res['unscaledMLS'];\n })\n .catch(err => {\n // this.emit('InvertedImpulseResponse', {res: false});\n console.error(err);\n });\n this.numSuccessfulBackgroundCaptured = 0;\n if (this._calibrateSoundBackgroundSecs > 0) {\n this.mode = 'background';\n this.status =\n `All Hz Calibration: sampling the background noise...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n await this.recordBackground(\n stream, //stream\n () => this.numSuccessfulBackgroundCaptured < 1, //loop condition\n this.#awaitBackgroundNoiseRecording, //sleep to record\n this.sendBackgroundRecording, //send to get PSD\n this.mode,\n checkRec\n );\n this.incrementStatusBar();\n }\n this.mode = 'unfiltered';\n this.numSuccessfulCaptured = 0;\n\n await this.calibrationSteps(\n stream,\n this.#playCalibrationAudio, // play audio func (required)\n this.#createCalibrationNodeFromBuffer(this.#mlsBufferView), // before play func\n this.#awaitSignalOnset, // before record\n () => this.numSuccessfulCaptured < this.numCaptures, // loop while true\n this.#awaitDesiredMLSLength, // during record\n this.#afterMLSRecord, // after record\n this.mode,\n checkRec\n ),\n this.#stopCalibrationAudio();\n checkRec = false;\n\n // at this stage we've captured all the required signals,\n // and have received IRs for each one\n // so let's send all the IRs to the server to be converted to a single IIR\n await this.sendSystemImpulseResponsesToServerForProcessing();\n await this.sendComponentImpulseResponsesToServerForProcessing();\n\n this.numSuccessfulCaptured = 0;\n\n let iir_ir_and_plots;\n if (this._calibrateSoundCheck != 'none') {\n //do single check\n if (this._calibrateSoundCheck == 'goal' || this._calibrateSoundCheck == 'system') {\n iir_ir_and_plots = await this.singleSoundCheck(stream);\n } else {\n //both\n iir_ir_and_plots = await this.bothSoundCheck(stream);\n }\n } else {\n let unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\n let conv_rec = this.componentInvertedImpulseResponse;\n let component_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\n conv_rec = this.systemInvertedImpulseResponse;\n let system_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n iir_ir_and_plots = {\n unfiltered_recording: return_unconv_rec,\n filtered_recording: return_conv_rec,\n system: {\n iir: this.systemInvertedImpulseResponse,\n ir: this.systemIR,\n iir_psd: {\n y: system_iir_psd['y_conv'],\n x: system_iir_psd['y_conv'],\n y_no_bandpass: system_iir_psd['y_unconv'],\n x_no_bandpass: system_iir_psd['x_unconv'],\n },\n filtered_recording: [],\n convolution: this.systemConvolution,\n psd: {\n unconv: {\n x: [],\n y: [],\n },\n conv: {\n x: [],\n y: [],\n },\n },\n },\n component: {\n iir: this.componentInvertedImpulseResponse,\n ir: this.componentIR,\n iir_psd: {\n y: component_iir_psd['y_conv'],\n x: component_iir_psd['x_conv'],\n y_no_bandpass: component_iir_psd['y_unconv'],\n x_no_bandpass: component_iir_psd['x_unconv'],\n },\n convolution: this.componentConvolution,\n psd: {\n unconv: {\n x: [],\n y: [],\n },\n conv: {\n x: [],\n y: [],\n },\n },\n },\n mls: this.#mlsBufferView,\n autocorrelations: this.autocorrelations,\n impulseResponses: [],\n };\n await Promise.all(this.impulseResponses).then(res => {\n for (let i = 0; i < res.length; i++) {\n if (res[i] != undefined) {\n iir_ir_and_plots['impulseResponses'].push(res[i]);\n }\n }\n });\n\n if (this.#download) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.#mls, 'MLS.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentConvolution, 'python_component_convolution_mls_iir.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemConvolution, 'python_system_convolution_mls_iir.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentInvertedImpulseResponse, 'componentIIR.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemInvertedImpulseResponse, 'systemIIR.csv');\n for (let i = 0; i < this.autocorrelations.length; i++) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.autocorrelations[i], `autocorrelation_${i}`);\n }\n const computedIRagain = await Promise.all(this.impulseResponses).then(res => {\n for (let i = 0; i < res.length; i++) {\n if (res[i] != undefined) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(res[i], `IR_${i}`);\n }\n }\n });\n }\n }\n\n this.percent_complete = 100;\n\n this.status = `All Hz Calibration: Finished`.toString() + this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n\n //here after calibration we have the component calibration (either loudspeaker or microphone) in the same form as the componentIR\n //that was used to calibrate\n\n return iir_ir_and_plots;\n };\n\n //////////////////////volume\n\n handleIncomingData = data => {\n console.log('Received data: ', data);\n if (data.type === 'soundGainDBSPL') {\n this.soundGainDBSPL = data.value;\n } else {\n throw new Error(`Unknown data type: ${data.type}`);\n }\n };\n createSCurveBuffer = (onSetBool = true) => {\n const curve = new Float32Array(this.TAPER_SECS * this.sourceSamplingRate + 1);\n const frequency = 1 / (4 * this.TAPER_SECS);\n let j = 0;\n for (let i = 0; i < this.TAPER_SECS * this.sourceSamplingRate + 1; i += 1) {\n const phase = 2 * Math.PI * frequency * j;\n const onsetTaper = Math.pow(Math.sin(phase), 2);\n const offsetTaper = Math.pow(Math.cos(phase), 2);\n curve[i] = onSetBool ? onsetTaper : offsetTaper;\n j += 1 / this.sourceSamplingRate;\n }\n return curve;\n };\n\n #getTruncatedSignal = (left = 3.5, right = 4.5) => {\n const start = Math.floor(left * this.sourceSamplingRate);\n const end = Math.floor(right * this.sourceSamplingRate);\n const result = Array.from(this.getLastVolumeRecordedSignal().slice(start, end));\n console.log(\n 'Obtaining last 1000 hz recording from #allVolumeRecordings to send for processing'\n );\n /**\n * function to check that capture was properly made\n * @param {*} list\n */\n const checkResult = list => {\n const setItem = new Set(list);\n if (setItem.size === 1 && setItem.has(0)) {\n console.warn(\n 'The last capture failed, all recorded signal is zero',\n this.getAllVolumeRecordedSignals()\n );\n }\n if (setItem.size === 0) {\n console.warn('The last capture failed, no recorded signal');\n }\n };\n checkResult(result);\n return result;\n };\n\n /** \n * \n * \n Construct a calibration Node with the calibration parameters and given gain value\n * @param {*} gainValue\n * */\n #createCalibrationToneWithGainValue = gainValue => {\n const audioContext = this.makeNewSourceAudioContext();\n const oscilator = audioContext.createOscillator();\n const gainNode = audioContext.createGain();\n const taperGainNode = audioContext.createGain();\n const offsetGainNode = audioContext.createGain();\n const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;\n\n oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;\n oscilator.type = this.#CALIBRATION_TONE_TYPE;\n gainNode.gain.value = gainValue;\n\n oscilator.connect(gainNode);\n gainNode.connect(taperGainNode);\n const onsetCurve = this.createSCurveBuffer();\n taperGainNode.gain.setValueCurveAtTime(onsetCurve, 0, this.TAPER_SECS);\n taperGainNode.connect(offsetGainNode);\n const offsetCurve = this.createSCurveBuffer(false);\n offsetGainNode.gain.setValueCurveAtTime(\n offsetCurve,\n totalDuration - this.TAPER_SECS,\n this.TAPER_SECS\n );\n offsetGainNode.connect(audioContext.destination);\n\n this.addCalibrationNode(oscilator);\n };\n\n /**\n * Construct a Calibration Node with the calibration parameters.\n *\n * @private\n * @example\n */\n #createCalibrationNode = () => {\n const audioContext = this.makeNewSourceAudioContext();\n const oscilator = audioContext.createOscillator();\n const gainNode = audioContext.createGain();\n\n oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;\n oscilator.type = this.#CALIBRATION_TONE_TYPE;\n gainNode.gain.value = 0.04;\n\n oscilator.connect(gainNode);\n gainNode.connect(audioContext.destination);\n\n this.addCalibrationNode(oscilator);\n };\n\n #playCalibrationAudioVolume = async () => {\n const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;\n\n this.calibrationNodes[0].start(0);\n this.calibrationNodes[0].stop(totalDuration);\n console.log(`Playing a buffer of ${this.CALIBRATION_TONE_DURATION} seconds of audio`);\n console.log(`Waiting a total of ${totalDuration} seconds`);\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(totalDuration);\n };\n\n #sendToServerForProcessing = lCalib => {\n console.log('Sending data to server');\n let left = this.calibrateSound1000HzPreSec;\n let right = this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec;\n this.pyServerAPI\n .getVolumeCalibration({\n sampleRate: this.sourceSamplingRate,\n payload: this.#getTruncatedSignal(left, right),\n lCalib: lCalib,\n })\n .then(res => {\n if (this.outDBSPL === null) {\n this.incrementStatusBar();\n this.outDBSPL = res['outDbSPL'];\n this.outDBSPL1000 = res['outDbSPL1000'];\n this.THD = res['thd'];\n }\n })\n .catch(err => {\n console.warn(err);\n });\n };\n\n startCalibrationVolume = async (stream, gainValues, lCalib, componentGainDBSPL) => {\n const trialIterations = gainValues.length;\n this.status_denominator += trialIterations;\n const thdValues = [];\n const inDBValues = [];\n let inDB = 0;\n const outDBSPLValues = [];\n const outDBSPL1000Values = [];\n let checkRec = false;\n\n // do one calibration that will be discarded\n const soundLevelToDiscard = -60;\n const gainToDiscard = Math.pow(10, soundLevelToDiscard / 20);\n this.status =\n `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`.toString() +\n this.generateTemplate().toString();\n //this.emit('update', {message: `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`});\n this.emit('update', {message: this.status});\n\n do {\n // eslint-disable-next-line no-await-in-loop\n await this.volumeCalibrationSteps(\n stream,\n this.#playCalibrationAudioVolume,\n this.#createCalibrationToneWithGainValue,\n this.#sendToServerForProcessing,\n gainToDiscard,\n lCalib, //todo make this a class parameter\n checkRec\n );\n } while (this.outDBSPL === null);\n //reset the values\n //this.incrementStatusBar();\n\n this.outDBSPL = null;\n this.outDBSPL = null;\n this.outDBSPL1000 = null;\n this.THD = null;\n\n // run the calibration at different gain values provided by the user\n for (let i = 0; i < trialIterations; i++) {\n //convert gain to DB and add to inDB\n if (i == trialIterations - 1) {\n checkRec = 'loudest';\n }\n inDB = Math.log10(gainValues[i]) * 20;\n // precision to 1 decimal place\n inDB = Math.round(inDB * 10) / 10;\n inDBValues.push(inDB);\n console.log('next update');\n this.status =\n `1000 Hz Calibration: Sound Level ${inDB} dB`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n do {\n // eslint-disable-next-line no-await-in-loop\n await this.volumeCalibrationSteps(\n stream,\n this.#playCalibrationAudioVolume,\n this.#createCalibrationToneWithGainValue,\n this.#sendToServerForProcessing,\n gainValues[i],\n lCalib, //todo make this a class parameter\n checkRec\n );\n } while (this.outDBSPL === null);\n outDBSPL1000Values.push(this.outDBSPL1000);\n thdValues.push(this.THD);\n outDBSPLValues.push(this.outDBSPL);\n\n this.outDBSPL = null;\n this.outDBSPL1000 = null;\n this.THD = null;\n }\n\n // get the volume calibration parameters from the server\n const parameters = await this.pyServerAPI\n .getVolumeCalibrationParameters({\n inDBValues: inDBValues,\n outDBSPLValues: outDBSPL1000Values,\n lCalib: lCalib,\n componentGainDBSPL,\n })\n .then(res => {\n this.incrementStatusBar();\n return res;\n });\n const result = {\n parameters: parameters,\n inDBValues: inDBValues,\n outDBSPLValues: outDBSPLValues,\n outDBSPL1000Values: outDBSPL1000Values,\n thdValues: thdValues,\n };\n\n return result;\n };\n\n // function to write frq and gain to firebase database given speakerID\n writeFrqGain = async (speakerID, frq, gain, OEM) => {\n // freq and gain are too large to take samples 1 in every 100 samples\n\n const sampledFrq = [];\n const sampledGain = [];\n for (let i = 0; i < frq.length; i += 100) {\n sampledFrq.push(frq[i]);\n sampledGain.push(gain[i]);\n }\n\n const data = {Freq: sampledFrq, Gain: sampledGain};\n\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"], `Microphone2/${OEM}/${speakerID}/linear`), data);\n };\n\n // Function to Read frq and gain from firebase database given speakerID\n // returns an array of frq and gain if speakerID exists, returns null otherwise\n\n readFrqGain = async (speakerID, OEM) => {\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/linear`));\n if (snapshot.exists()) {\n return snapshot.val();\n }\n return null;\n };\n\n readGainat1000Hz = async (speakerID, OEM) => {\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/Gain1000`));\n if (snapshot.exists()) {\n return snapshot.val();\n }\n return null;\n };\n\n writeGainat1000Hz = async (speakerID, gain, OEM) => {\n const data = {Gain: gain};\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"], `Microphone2/${OEM}/${speakerID}/Gain1000`), gain);\n };\n\n writeIsSmartPhone = async (speakerID, isSmartPhone, OEM) => {\n const data = {isSmartPhone: isSmartPhone};\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"], `Microphone2/${OEM}/${speakerID}/isSmartPhone`), isSmartPhone);\n };\n\n doesMicrophoneExist = async (speakerID, OEM) => {\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.child)(dbRef, `Microphone2/${OEM}/${speakerID}`));\n if (snapshot.exists()) {\n return true;\n }\n return false;\n };\n\n addMicrophoneInfo = async (speakerID, OEM, micInfo) => {\n // add to database if /info does not exist\n // if there is \"undefined\" in the micInfo, change it to null\n JSON.parse(JSON.stringify(micInfo));\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/info`));\n if (!snapshot.exists()) {\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"], `Microphone2/${OEM}/${speakerID}/info`), micInfo);\n }\n };\n\n convertToDB = gain => {\n return Math.log10(gain) * 20;\n };\n\n // Function to perform linear interpolation between two points\n interpolate(x, x0, y0, x1, y1) {\n return y0 + ((x - x0) * (y1 - y0)) / (x1 - x0);\n }\n\n findGainatFrequency = (frequencies, gains, targetFrequency) => {\n // Find the index of the first frequency in the array greater than the target frequency\n let index = 0;\n while (index < frequencies.length && frequencies[index] < targetFrequency) {\n index++;\n }\n\n // Handle cases when the target frequency is outside the range of the given data\n if (index === 0) {\n return gains[0];\n } else if (index === frequencies.length) {\n return gains[gains.length - 1];\n } else {\n // Interpolate the gain based on the surrounding frequencies\n const x0 = frequencies[index - 1];\n const y0 = gains[index - 1];\n const x1 = frequencies[index];\n const y1 = gains[index];\n return this.interpolate(targetFrequency, x0, y0, x1, y1);\n }\n };\n\n // Example of how to use the writeFrqGain and readFrqGain functions\n // writeFrqGain('speaker1', [1, 2, 3], [4, 5, 6]);\n // Speaker1 is the speakerID you want to write to in the database\n // readFrqGain('MiniDSPUMIK_1').then(data => console.log(data));\n // MiniDSPUMIK_1 is the speakerID with some Data in the database\n //adding gainDBSPL\n startCalibration = async (\n stream,\n gainValues,\n lCalib = 104.92978421490648,\n componentIR = null,\n microphoneName = 'MiniDSP-UMIK1-711-4754-vertical',\n _calibrateSoundCheck = 'goal', //GOAL PASSed in by default\n isSmartPhone = false,\n _calibrateSoundBurstDb = 0.33,\n _calibrateSoundBurstRepeats = 2,\n _calibrateSoundBurstSec = 1,\n _calibrateSoundBurstsWarmup = 1,\n _calibrateSoundHz = 48000,\n _calibrateSoundIIRSec = 0.2,\n calibrateSound1000HzPreSec = 3.5,\n calibrateSound1000HzSec = 1.0,\n calibrateSound1000HzPostSec = 0.5,\n _calibrateSoundBackgroundSecs = 0,\n micManufacturer = '',\n micSerialNumber = '',\n micModelNumber = '',\n micModelName = ''\n ) => {\n this._calibrateSoundBurstDb = _calibrateSoundBurstDb;\n this.CALIBRATION_TONE_DURATION =\n calibrateSound1000HzPreSec + calibrateSound1000HzSec + calibrateSound1000HzPostSec;\n this.calibrateSound1000HzPreSec = calibrateSound1000HzPreSec;\n this.calibrateSound1000HzSec = calibrateSound1000HzSec;\n this.calibrateSound1000HzPostSec = calibrateSound1000HzPostSec;\n this.iirLength = Math.floor(_calibrateSoundIIRSec * this.sourceSamplingRate);\n console.log('device info:', this.deviceInfo);\n this.numMLSPerCapture = _calibrateSoundBurstRepeats;\n this.desired_time_per_mls = _calibrateSoundBurstSec;\n this.num_mls_to_skip = _calibrateSoundBurstsWarmup;\n this.desired_sampling_rate = _calibrateSoundHz;\n this._calibrateSoundBackgroundSecs = _calibrateSoundBackgroundSecs;\n\n //feed calibration goal here\n this._calibrateSoundCheck = _calibrateSoundCheck;\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\n //check the db based on the microphone currently connected\n\n //new lCalib found at top of calibration files *1000hz, make sure to correct\n //based on zeroing of 1000hz, search for \"*1000Hz\"\n const ID = isSmartPhone ? micModelNumber : micSerialNumber;\n const OEM = isSmartPhone ? this.deviceInfo.OEM : micManufacturer;\n // const ID = \"711-4754\";\n // const OEM = \"MiniDSP\";\n const micInfo = {\n micModelName: isSmartPhone ? micModelName : microphoneName,\n OEM: OEM,\n ID: ID,\n HardwareName: isSmartPhone ? this.deviceInfo.hardwarename : microphoneName,\n hardwareFamily: isSmartPhone ? this.deviceInfo.hardwarefamily : microphoneName,\n HardwareModel: isSmartPhone ? this.deviceInfo.hardwaremodel : microphoneName,\n PlatformName: isSmartPhone ? this.deviceInfo.platformname : 'N/A',\n PlatformVersion: isSmartPhone ? this.deviceInfo.platformversion : 'N/A',\n DeviceType: isSmartPhone ? this.deviceInfo.devicetype : 'N/A',\n };\n this.addMicrophoneInfo(ID, OEM, micInfo);\n if (componentIR == null) {\n //mode 'ir'\n //global variable this.componentIR must be set\n this.componentIR = await this.readFrqGain(ID, OEM).then(data => {\n return data;\n });\n\n lCalib = await this.readGainat1000Hz(ID, OEM);\n micInfo['gainDBSPL'] = lCalib;\n // this.componentGainDBSPL = this.convertToDB(lCalib);\n this.componentGainDBSPL = lCalib;\n //TODO: if this call to database is unknown, cannot perform experiment => return false\n if (this.componentIR == null) {\n this.status =\n `Microphone (${OEM},${ID}) is not found in the database. Please add it to the database.`.toString();\n this.emit('update', {message: this.status});\n return false;\n }\n } else {\n this.componentIR = componentIR;\n lCalib = this.findGainatFrequency(this.componentIR.Freq, this.componentIR.Gain, 1000);\n // this.componentGainDBSPL = this.convertToDB(lCalib);\n this.componentGainDBSPL = lCalib;\n await this.writeIsSmartPhone(ID, isSmartPhone, OEM);\n }\n\n this.oldComponentIR = this.componentIR;\n\n let volumeResults = await this.startCalibrationVolume(\n stream,\n gainValues,\n lCalib,\n this.componentGainDBSPL\n );\n\n let impulseResponseResults = await this.startCalibrationImpulseResponse(stream);\n impulseResponseResults['background_noise'] = this.background_noise;\n if (componentIR != null) {\n //insert Freq and Gain from this.componentIR into db\n await this.writeFrqGain(\n ID,\n impulseResponseResults.componentIR.Freq,\n impulseResponseResults.componentIR.Gain,\n OEM\n );\n micInfo['gainDBSPL'] = impulseResponseResults.parameters.gainDBSPL;\n await this.writeGainat1000Hz(ID, micInfo['gainDBSPL'], OEM);\n }\n\n const total_results = {...volumeResults, ...impulseResponseResults};\n total_results['filteredMLSRange'] = this.filteredMLSRange;\n total_results['micInfo'] = micInfo;\n console.log('total results');\n console.log(total_results);\n return total_results;\n };\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (Combination);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/tasks/combination/combination.js?");
|
|
843
|
+
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 _config_firebase__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../config/firebase */ \"./src/config/firebase.js\");\n/* harmony import */ var firebase_database__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! firebase/database */ \"./node_modules/firebase/database/dist/esm/index.esm.js\");\n\n\n\n\n\n\n/**\n *\n */\nclass Combination extends _audioCalibrator__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\n /**\n * Default constructor. Creates an instance with any number of paramters passed or the default parameters defined here.\n *\n * @param {Object<boolean, number, number, number>} calibratorParams - paramter object\n * @param {boolean} [calibratorParams.download = false] - boolean flag to download captures\n * @param {number} [calibratorParams.mlsOrder = 18] - order of the MLS to be generated\n * @param {number} [calibratorParams.numCaptures = 5] - number of captures to perform\n * @param {number} [calibratorParams.numMLSPerCapture = 2] - number of bursts of MLS per capture\n */\n constructor({\n download = false,\n mlsOrder = 18,\n numCaptures = 3,\n numMLSPerCapture = 2,\n lowHz = 20,\n highHz = 10000,\n }) {\n super(numCaptures, numMLSPerCapture);\n this.#mlsOrder = parseInt(mlsOrder, 10);\n this.#P = 2 ** mlsOrder - 1;\n this.#download = download;\n this.#mls = [];\n this.#lowHz = lowHz;\n this.#highHz = highHz;\n }\n\n /** @private */\n stepNum = 0;\n\n /** @private */\n totalSteps = 25;\n\n /** @private */\n #download;\n\n /** @private */\n #mlsGenInterface;\n\n /** @private */\n #mlsBufferView;\n\n /** @private */\n componentInvertedImpulseResponse = null;\n\n /** @private */\n systemInvertedImpulseResponse = null;\n\n //averaged and subtracted ir returned from calibration used to calculated iir\n /** @private */\n ir = null;\n\n /** @private */\n impulseResponses = [];\n\n /** @private */\n #mlsOrder;\n\n /** @private */\n #lowHz;\n\n /** @private */\n #highHz;\n\n /** @private */\n #mls;\n\n /** @private */\n #P;\n\n /** @private */\n #audioContext;\n\n /** @private */\n TAPER_SECS = 5;\n\n /** @private */\n offsetGainNode;\n\n /** @private */\n componentConvolution;\n\n /** @private */\n systemConvolution;\n\n ////////////////////////volume\n /** @private */\n #CALIBRATION_TONE_FREQUENCY = 1000; // Hz\n\n /** @private */\n #CALIBRATION_TONE_TYPE = 'sine';\n\n CALIBRATION_TONE_DURATION = 5; // seconds\n calibrateSound1000HzPreSec = 3.5;\n calibrateSound1000HzSec = 1.0;\n calibrateSound1000HzPostSec = 0.5;\n\n /** @private */\n outDBSPL = null;\n THD = null;\n outDBSPL1000 = null;\n\n /** @private */\n TAPER_SECS = 0.01; // seconds\n\n /** @private */\n status_denominator = 8;\n\n /** @private */\n status_numerator = 0;\n\n /** @private */\n percent_complete = 0;\n\n /** @private */\n status = ``;\n\n /**@private */\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>`;\n\n /**@private */\n componentIR = null;\n\n /**@private */\n oldComponentIR = null;\n\n /**@private */\n systemIR = null;\n\n /**@private */\n _calibrateSoundCheck = '';\n\n deviceType = null;\n\n deviceName = null;\n\n deviceInfo = null;\n\n desired_time_per_mls = 0;\n\n num_mls_to_skip = 0;\n\n desired_sampling_rate = 0;\n\n #currentConvolution = [];\n\n mode = 'unfiltered';\n\n sourceNode;\n\n autocorrelations = [];\n\n iirLength = 0;\n\n componentInvertedImpulseResponseNoBandpass = [];\n\n systemInvertedImpulseResponseNoBandpass = [];\n\n _calibrateSoundBackgroundSecs;\n\n background_noise = {};\n\n numSuccessfulBackgroundCaptured;\n\n _calibrateSoundBurstDb;\n\n filteredMLSRange = {\n component: {\n Min: null,\n Max: null,\n },\n system: {\n Min: null,\n Max: null,\n },\n };\n\n /**generate string template that gets reevaluated as variable increases */\n generateTemplate = () => {\n if (this.percent_complete > 100) {\n this.percent_complete = 100;\n }\n const template = `<div style=\"display: flex; justify-content: center; margin-top:12px;\"><div style=\"width: 800px; 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>`;\n return template;\n };\n\n /** increment numerator and percent for status bar */\n incrementStatusBar = () => {\n this.status_numerator += 1;\n this.percent_complete = (this.status_numerator / this.status_denominator) * 100;\n };\n\n setDeviceType = deviceType => {\n this.deviceType = deviceType;\n };\n\n setDeviceName = deviceName => {\n this.deviceName = deviceName;\n };\n\n setDeviceInfo = deviceInfo => {\n this.deviceInfo = deviceInfo;\n };\n\n /** .\n * .\n * .\n * Sends all the computed impulse responses to the backend server for processing\n *\n * @returns sets the resulting inverted impulse response to the class property\n * @example\n */\n sendSystemImpulseResponsesToServerForProcessing = async () => {\n const computedIRs = await Promise.all(this.impulseResponses);\n const filteredComputedIRs = computedIRs.filter(element => {\n return element != undefined;\n }); //log any errors that are found in this step\n const mls = this.#mls;\n const lowHz = this.#lowHz; //gain of 1 below cutoff, need gain of 0\n const highHz = this.#highHz; //check error for anything other than 10 kHz\n const iirLength = this.iirLength;\n const num_periods = this.numMLSPerCapture + this.num_mls_to_skip;\n this.stepNum += 1;\n console.log('send impulse responses to server: ' + this.stepNum);\n this.status =\n `All Hz Calibration: computing the IIR...`.toString() + this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return this.pyServerAPI\n .getSystemInverseImpulseResponseWithRetry({\n payload: filteredComputedIRs.slice(0, this.numCaptures),\n mls,\n lowHz,\n highHz,\n iirLength,\n num_periods,\n sampleRate: this.sourceSamplingRate || 96000,\n calibrateSoundBurstDb: this._calibrateSoundBurstDb,\n })\n .then(res => {\n console.log(res);\n this.stepNum += 1;\n console.log('got impulse response ' + this.stepNum);\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the IIR...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n this.systemInvertedImpulseResponse = res['iir'];\n this.systemIR = res['ir'];\n this.systemConvolution = res['convolution'];\n this.systemInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];\n })\n .catch(err => {\n console.error(err);\n });\n };\n\n /** .\n * .\n * .\n * Sends all the computed impulse responses to the backend server for processing\n *\n * @returns sets the resulting inverted impulse response to the class property\n * @example\n */\n sendComponentImpulseResponsesToServerForProcessing = async () => {\n const computedIRs = await Promise.all(this.impulseResponses);\n const filteredComputedIRs = computedIRs.filter(element => {\n return element != undefined;\n });\n const componentIRGains = this.componentIR['Gain'];\n const componentIRFreqs = this.componentIR['Freq'];\n const mls = this.#mls;\n const lowHz = this.#lowHz;\n const iirLength = this.iirLength;\n const num_periods = this.numMLSPerCapture + this.num_mls_to_skip;\n const highHz = this.#highHz;\n this.stepNum += 1;\n console.log('send impulse responses to server: ' + this.stepNum);\n this.status =\n `All Hz Calibration: computing the IIR...`.toString() + this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return this.pyServerAPI\n .getComponentInverseImpulseResponseWithRetry({\n payload: filteredComputedIRs.slice(0, this.numCaptures),\n mls,\n lowHz,\n highHz,\n iirLength,\n componentIRGains,\n componentIRFreqs,\n num_periods,\n sampleRate: this.sourceSamplingRate || 96000,\n calibrateSoundBurstDb: this._calibrateSoundBurstDb,\n })\n .then(res => {\n console.log(res);\n this.stepNum += 1;\n console.log('got impulse response ' + this.stepNum);\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the IIR...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n this.componentInvertedImpulseResponse = res['iir'];\n this.componentIR['Gain'] = res['ir'];\n this.componentIR['Freq'] = res['frequencies'];\n this.componentConvolution = res['convolution'];\n this.componentInvertedImpulseResponseNoBandpass = res['iirNoBandpass'];\n })\n .catch(err => {\n // this.emit('InvertedImpulseResponse', {res: false});\n console.error(err);\n });\n };\n\n sendBackgroundRecording = () => {\n const allSignals = this.getAllBackgroundRecordings();\n const numSignals = allSignals.length;\n const background_rec_whole = allSignals[numSignals - 1];\n const fraction = 0.5 / (this._calibrateSoundBackgroundSecs + 0.5);\n // Calculate the starting index for slicing the array\n const startIndex = Math.round(fraction * background_rec_whole.length);\n // Slice the array from the calculated start index to the end of the array\n const background_rec = background_rec_whole.slice(startIndex);\n console.log('Sending background recording to server for processing');\n this.pyServerAPI\n .getBackgroundNoisePSDWithRetry({\n background_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n if (this.numSuccessfulBackgroundCaptured < 1) {\n this.numSuccessfulBackgroundCaptured += 1;\n //storing all background data in background_psd object\n this.background_noise['x_background'] = res['x_background'];\n this.background_noise['y_background'] = res['y_background'];\n this.background_noise['recording'] = background_rec;\n }\n })\n .catch(err => {\n console.error(err);\n });\n };\n\n /** .\n * .\n * .\n * Sends the recorded signal, or a given csv string of a signal, to the back end server for processing\n *\n * @param {<array>String} signalCsv - Optional csv string of a previously recorded signal, if given, this signal will be processed\n * @example\n */\n sendRecordingToServerForProcessing = signalCsv => {\n const allSignals = this.getAllUnfilteredRecordedSignals();\n console.log(\n 'Obtaining last all hz unfiltered recording from #allHzUnfilteredRecordings to send to server for processing'\n );\n const numSignals = allSignals.length;\n const mls = this.#mlsBufferView;\n const payload =\n signalCsv && signalCsv.length > 0 ? (0,_utils__WEBPACK_IMPORTED_MODULE_1__.csvToArray)(signalCsv) : allSignals[numSignals - 1];\n console.log('sending rec');\n this.stepNum += 1;\n console.log('send rec ' + this.stepNum);\n this.status =\n `All Hz Calibration Step: computing the IR of the last recording...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n this.impulseResponses.push(\n this.pyServerAPI\n .getImpulseResponse({\n sampleRate: this.sourceSamplingRate || 96000,\n payload,\n mls,\n P: this.#P, //get rid of this\n numPeriods: this.numMLSPerCapture,\n })\n .then(res => {\n if (this.numSuccessfulCaptured < this.numCaptures) {\n this.numSuccessfulCaptured += 1;\n console.log('num succ capt: ' + this.numSuccessfulCaptured);\n this.stepNum += 1;\n console.log('got impulse response ' + this.stepNum);\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: ${this.numSuccessfulCaptured}/${this.numCaptures} IRs computed...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {\n message: this.status,\n });\n this.autocorrelations.push(res['autocorrelation']);\n return res['ir'];\n }\n })\n .catch(err => {\n console.error(err);\n })\n );\n };\n\n /**\n * Passed to the calibration steps function, awaits the desired amount of seconds to capture the desired number\n * of MLS periods defined in the constructor.\n *\n * @example\n */\n #awaitDesiredMLSLength = async () => {\n // seconds per MLS = P / SR\n // await N * P / SR\n this.stepNum += 1;\n console.log('await desired length ' + this.stepNum);\n this.status =\n `All Hz Calibration: sampling the calibration signal...`.toString() +\n `\\niteration ${this.stepNum}` +\n this.generateTemplate();\n this.emit('update', {\n message: this.status,\n });\n let time_to_wait = 0;\n if (this.mode === 'unfiltered') {\n //unfiltered\n time_to_wait = (this.#mls.length / this.sourceSamplingRate) * this.numMLSPerCapture;\n time_to_wait = time_to_wait * 1.1;\n } else if (this.mode === 'filtered') {\n //filtered\n // time_to_wait =\n // (this.#currentConvolution.length / this.sourceSamplingRate) *\n // (this.numMLSPerCapture / (this.num_mls_to_skip + this.numMLSPerCapture));\n time_to_wait =\n (this.#currentConvolution.length / this.sourceSamplingRate) * this.numMLSPerCapture;\n time_to_wait = time_to_wait * 1.1;\n } else {\n throw new Error('Mode broke in awaitDesiredMLSLength');\n }\n\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_wait);\n };\n\n /**\n * Passed to the background noise recording function, awaits the desired amount of seconds to capture the desired number\n * of seconds of background noise\n *\n * @example\n */\n #awaitBackgroundNoiseRecording = async () => {\n console.log(\n 'Waiting ' + this._calibrateSoundBackgroundSecs + ' second(s) to record background noise'\n );\n let time_to_wait = this._calibrateSoundBackgroundSecs + 0.5;\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_wait);\n };\n\n /** .\n * .\n * .\n * Passed to the calibration steps function, awaits the onset of the signal to ensure a steady state\n *\n * @example\n */\n #awaitSignalOnset = async () => {\n this.stepNum += 1;\n console.log('await signal onset ' + this.stepNum);\n this.status =\n `All Hz Calibration: waiting for the signal to stabilize...`.toString() +\n this.generateTemplate();\n this.emit('update', {\n message: this.status,\n });\n let number_of_bursts_to_skip = this.num_mls_to_skip;\n let time_to_sleep = 0;\n if (this.mode === 'unfiltered') {\n time_to_sleep = (this.#mls.length / this.sourceSamplingRate) * number_of_bursts_to_skip;\n } else if (this.mode === 'filtered') {\n console.log(this.#currentConvolution.length);\n // time_to_sleep =\n // (this.#currentConvolution.length / this.sourceSamplingRate) *\n // (number_of_bursts_to_skip / (number_of_bursts_to_skip + this.numMLSPerCapture));\n time_to_sleep =\n (this.#currentConvolution.length / this.sourceSamplingRate) * number_of_bursts_to_skip;\n } else {\n throw new Error('Mode broke in awaitSignalOnset');\n }\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(time_to_sleep);\n };\n\n /**\n * Called immediately after a recording is captured. Used to process the resulting signal\n * whether by sending the result to a server or by computing a result locally.\n *\n * @example\n */\n #afterMLSRecord = () => {\n console.log('after record');\n this.sendRecordingToServerForProcessing();\n };\n\n #afterMLSwIIRRecord = () => {\n if (this.numSuccessfulCaptured < 1) {\n this.numSuccessfulCaptured += 1;\n this.stepNum += 1;\n this.incrementStatusBar();\n console.log('after mls w iir record for some reason add numSucc capt ' + this.stepNum);\n this.status =\n `All Hz Calibration: ${this.numSuccessfulCaptured} recording of convolved MLS captured`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {\n message: this.status,\n });\n }\n };\n\n /** .\n * .\n * .\n * Created an S Curver Buffer to taper the signal onset\n *\n * @param {*} length\n * @param {*} phase\n * @returns\n * @example\n */\n static createSCurveBuffer = (length, phase) => {\n const curve = new Float32Array(length);\n let i;\n for (i = 0; i < length; i += 1) {\n // scale the curve to be between 0-1\n curve[i] = Math.sin((Math.PI * i) / length - phase) / 2 + 0.5;\n }\n return curve;\n };\n\n static createInverseSCurveBuffer = (length, phase) => {\n const curve = new Float32Array(length);\n let i;\n let j = length - 1;\n for (i = 0; i < length; i += 1) {\n // scale the curve to be between 0-1\n curve[i] = Math.sin((Math.PI * j) / length - phase) / 2 + 0.5;\n j -= 1;\n }\n return curve;\n };\n\n /**\n * Construct a Calibration Node with the calibration parameters.\n *\n * @param dataBuffer\n * @private\n * @example\n */\n #createCalibrationNodeFromBuffer = dataBuffer => {\n console.log('length databuffer');\n console.log(dataBuffer.length);\n if (!this.sourceAudioContext) {\n this.makeNewSourceAudioContext();\n }\n\n const buffer = this.sourceAudioContext.createBuffer(\n 1, // number of channels\n dataBuffer.length,\n this.sourceAudioContext.sampleRate // sample rate\n );\n\n const data = buffer.getChannelData(0); // get data\n if (this.mode === 'filtered') {\n console.log('check max and min of convolution');\n } else {\n console.log('check max and min of mls');\n }\n\n // fill the buffer with our data\n try {\n for (let i = 0; i < dataBuffer.length; i += 1) {\n data[i] = dataBuffer[i];\n }\n } catch (error) {\n console.error(error);\n }\n\n this.sourceNode = this.sourceAudioContext.createBufferSource();\n\n this.sourceNode.buffer = buffer;\n\n if (this.mode === 'filtered') {\n //used to not loop filtered\n this.sourceNode.loop = true;\n } else {\n this.sourceNode.loop = true;\n }\n\n this.sourceNode.connect(this.sourceAudioContext.destination);\n\n this.addCalibrationNode(this.sourceNode);\n };\n\n /**\n * Given a data buffer, creates the required calibration node\n *\n * @param {*} dataBufferArray\n * @example\n */\n #setCalibrationNodesFromBuffer = (dataBufferArray = [this.#mlsBufferView]) => {\n if (dataBufferArray.length === 1) {\n this.#createCalibrationNodeFromBuffer(dataBufferArray[0]);\n } else {\n throw new Error('The length of the data buffer array must be 1');\n }\n };\n\n /**\n * Creates an audio context and plays it for a few seconds.\n *\n * @private\n * @returns - Resolves when the audio is done playing.\n * @example\n */\n #playCalibrationAudio = () => {\n this.calibrationNodes[0].start(0);\n this.status = ``;\n if (this.mode === 'unfiltered') {\n console.log('mls', this.#mls); // before multiplied by calibrateSoundBurstDb\n console.log('mls buffer view', this.#mlsBufferView); // after multiplied by calibrateSoundBurstDb\n console.log('play calibration audio ' + this.stepNum);\n this.status =\n `All Hz Calibration: playing the calibration tone...`.toString() +\n this.generateTemplate().toString();\n } else if (this.mode === 'filtered') {\n console.log('play convolved audio ' + this.stepNum);\n this.status =\n `All Hz Calibration: playing the convolved calibration tone...`.toString() +\n this.generateTemplate().toString();\n } else {\n throw new Error('Mode is incorrect');\n }\n this.emit('update', {message: this.status});\n this.stepNum += 1;\n console.log('sink sampling rate');\n console.log(this.sinkSamplingRate);\n console.log('source sampling rate');\n console.log(this.sourceSamplingRate);\n };\n\n /** .\n * .\n * .\n * Stops the audio with tapered offset\n *\n * @example\n */\n #stopCalibrationAudio = () => {\n this.calibrationNodes[0].stop(0);\n this.calibrationNodes = [];\n this.sourceNode.disconnect();\n this.stepNum += 1;\n console.log('stop calibration audio ' + this.stepNum);\n this.status =\n `All Hz Calibration: stopping the calibration tone...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n };\n\n playMLSwithIIR = async (stream, convolution) => {\n let checkRec = false;\n this.mode = 'filtered';\n console.log('play mls with iir');\n //this.invertedImpulseResponse = iir\n\n await this.calibrationSteps(\n stream,\n this.#playCalibrationAudio, // play audio func (required)\n this.#createCalibrationNodeFromBuffer(convolution), // before play func\n this.#awaitSignalOnset, // before record\n () => this.numSuccessfulCaptured < 1,\n this.#awaitDesiredMLSLength, // during record\n this.#afterMLSwIIRRecord, // after record\n this.mode,\n checkRec\n );\n };\n\n bothSoundCheck = async stream => {\n let iir_ir_and_plots;\n this.#currentConvolution = this.componentConvolution;\n this.filteredMLSRange.component.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\n this.filteredMLSRange.component.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\n await this.playMLSwithIIR(stream, this.#currentConvolution);\n this.#stopCalibrationAudio();\n let component_conv_recs = this.getAllFilteredRecordedSignals();\n let return_component_conv_rec = component_conv_recs[0];\n this.clearAllFilteredRecordedSignals();\n this.#currentConvolution = this.systemConvolution;\n this.filteredMLSRange.system.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\n this.filteredMLSRange.system.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\n await this.playMLSwithIIR(stream, this.#currentConvolution);\n this.#stopCalibrationAudio();\n let system_conv_recs = this.getAllFilteredRecordedSignals();\n let return_system_conv_rec = system_conv_recs[0];\n this.sourceAudioContext.close();\n let recs = this.getAllUnfilteredRecordedSignals();\n let unconv_rec = recs[0];\n let return_unconv_rec = unconv_rec;\n let conv_rec = component_conv_recs[0];\n\n //psd of component\n let knownGain = this.oldComponentIR.Gain;\n let knownFreq = this.oldComponentIR.Freq;\n let sampleRate = this.sourceSamplingRate || 96000;\n let component_unconv_rec_psd = await this.pyServerAPI\n .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let component_conv_rec_psd = await this.pyServerAPI\n .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n conv_rec = system_conv_recs[0];\n //psd of system\n let system_recs_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n //iir w/ and without bandpass psd. done\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\n conv_rec = this.componentInvertedImpulseResponse;\n let component_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\n conv_rec = this.systemInvertedImpulseResponse;\n let system_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({mls: this.#mlsBufferView, sampleRate: this.sourceSamplingRate || 96000})\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let system_filtered_mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.systemConvolution,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let component_filtered_mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.componentConvolution,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n iir_ir_and_plots = {\n filtered_recording: {\n component: return_component_conv_rec,\n system: return_system_conv_rec,\n },\n unfiltered_recording: this.getAllUnfilteredRecordedSignals()[0],\n system: {\n iir: this.systemInvertedImpulseResponse,\n ir: this.systemIR,\n iir_psd: {\n y: system_iir_psd['y_conv'],\n x: system_iir_psd['x_conv'],\n y_no_bandpass: system_iir_psd['y_unconv'],\n x_no_bandpass: system_iir_psd['x_unconv'],\n },\n filtered_mls_psd: {\n x: system_filtered_mls_psd['x_mls'],\n y: system_filtered_mls_psd['y_mls'],\n },\n convolution: this.systemConvolution,\n psd: {\n unconv: {\n x: system_recs_psd['x_unconv'],\n y: system_recs_psd['y_unconv'],\n },\n conv: {\n x: system_recs_psd['x_conv'],\n y: system_recs_psd['y_conv'],\n },\n },\n },\n component: {\n iir: this.componentInvertedImpulseResponse,\n ir: this.componentIR,\n iir_psd: {\n y: component_iir_psd['y_conv'],\n x: component_iir_psd['x_conv'],\n y_no_bandpass: component_iir_psd['y_unconv'],\n x_no_bandpass: component_iir_psd['x_unconv'],\n },\n filtered_mls_psd: {\n x: component_filtered_mls_psd['x_mls'],\n y: component_filtered_mls_psd['y_mls'],\n },\n convolution: this.componentConvolution,\n psd: {\n unconv: {\n x: component_unconv_rec_psd['x'],\n y: component_unconv_rec_psd['y'],\n },\n conv: {\n x: component_conv_rec_psd['x'],\n y: component_conv_rec_psd['y'],\n },\n },\n },\n mls: this.#mlsBufferView,\n mls_psd: {\n x: mls_psd['x_mls'],\n y: mls_psd['y_mls'],\n },\n autocorrelations: this.autocorrelations,\n impulseResponses: [],\n };\n\n return iir_ir_and_plots;\n };\n\n singleSoundCheck = async stream => {\n let iir_ir_and_plots;\n if (this._calibrateSoundCheck != 'system') {\n this.#currentConvolution = this.componentConvolution;\n this.filteredMLSRange.component.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\n this.filteredMLSRange.component.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\n } else {\n this.#currentConvolution = this.systemConvolution;\n this.filteredMLSRange.system.Min = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMinValue)(this.#currentConvolution);\n this.filteredMLSRange.system.Max = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.findMaxValue)(this.#currentConvolution);\n }\n await this.playMLSwithIIR(stream, this.#currentConvolution);\n this.#stopCalibrationAudio();\n this.sourceAudioContext.close();\n let conv_recs = this.getAllFilteredRecordedSignals();\n let recs = this.getAllUnfilteredRecordedSignals();\n console.log('Obtaining unfiltered recording from #allHzUnfilteredRecordings to calculate PSD');\n console.log('Obtaining filtered recording from #allHzFilteredRecordings to calculate PSD');\n let unconv_rec = recs[0];\n let return_unconv_rec = unconv_rec;\n let conv_rec = conv_recs[0];\n let return_conv_rec = conv_rec;\n if (this._calibrateSoundCheck != 'system') {\n let knownGain = this.oldComponentIR.Gain;\n let knownFreq = this.oldComponentIR.Freq;\n let sampleRate = this.sourceSamplingRate || 96000;\n let unconv_results = await this.pyServerAPI\n .getSubtractedPSDWithRetry(unconv_rec, knownGain, knownFreq, sampleRate)\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let conv_results = await this.pyServerAPI\n .getSubtractedPSDWithRetry(conv_rec, knownGain, knownFreq, sampleRate)\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\n conv_rec = this.componentInvertedImpulseResponse;\n let component_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\n conv_rec = this.systemInvertedImpulseResponse;\n let system_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.#mlsBufferView,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let filtered_mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.componentConvolution,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n iir_ir_and_plots = {\n unfiltered_recording: return_unconv_rec,\n filtered_recording: return_conv_rec,\n system: {\n iir: this.systemInvertedImpulseResponse,\n ir: this.systemIR,\n iir_psd: {\n y: system_iir_psd['y_conv'],\n x: system_iir_psd['y_conv'],\n y_no_bandpass: system_iir_psd['y_unconv'],\n x_no_bandpass: system_iir_psd['x_unconv'],\n },\n filtered_recording: [],\n filtered_mls_psd: {},\n convolution: this.systemConvolution,\n psd: {\n unconv: {\n x: [],\n y: [],\n },\n conv: {\n x: [],\n y: [],\n },\n },\n },\n component: {\n iir: this.componentInvertedImpulseResponse,\n ir: this.componentIR,\n iir_psd: {\n y: component_iir_psd['y_conv'],\n x: component_iir_psd['x_conv'],\n y_no_bandpass: component_iir_psd['y_unconv'],\n x_no_bandpass: component_iir_psd['x_unconv'],\n },\n filtered_mls_psd: {\n x: filtered_mls_psd['x_mls'],\n y: filtered_mls_psd['y_mls'],\n },\n convolution: this.componentConvolution,\n psd: {\n unconv: {\n x: unconv_results['x'],\n y: unconv_results['y'],\n },\n conv: {\n x: conv_results['x'],\n y: conv_results['y'],\n },\n },\n },\n mls: this.#mlsBufferView,\n mls_psd: {\n x: mls_psd['x_mls'],\n y: mls_psd['y_mls'],\n },\n autocorrelations: this.autocorrelations,\n impulseResponses: [],\n };\n } else {\n let results = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n //iir w/ and without bandpass psd\n unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\n conv_rec = this.componentInvertedImpulseResponse;\n let component_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\n conv_rec = this.systemInvertedImpulseResponse;\n let system_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.#mlsBufferView,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n let filtered_mls_psd = await this.pyServerAPI\n .getMLSPSDWithRetry({\n mls: this.systemConvolution,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n iir_ir_and_plots = {\n unfiltered_recording: return_unconv_rec,\n filtered_recording: return_conv_rec,\n system: {\n iir: this.systemInvertedImpulseResponse,\n ir: this.systemIR,\n iir_psd: {\n y: system_iir_psd['y_conv'],\n x: system_iir_psd['y_conv'],\n y_no_bandpass: system_iir_psd['y_unconv'],\n x_no_bandpass: system_iir_psd['x_unconv'],\n },\n filtered_recording: [],\n filtered_mls_psd: {\n x: filtered_mls_psd['x_mls'],\n y: filtered_mls_psd['y_mls'],\n },\n convolution: this.systemConvolution,\n psd: {\n unconv: {\n x: results['x_unconv'],\n y: results['y_unconv'],\n },\n conv: {\n x: results['x_conv'],\n y: results['y_conv'],\n },\n },\n },\n component: {\n iir: this.componentInvertedImpulseResponse,\n ir: this.componentIR,\n iir_psd: {\n y: component_iir_psd['y_conv'],\n x: component_iir_psd['x_conv'],\n y_no_bandpass: component_iir_psd['y_unconv'],\n x_no_bandpass: component_iir_psd['x_unconv'],\n },\n filtered_mls_psd: {},\n convolution: this.componentConvolution,\n psd: {\n unconv: {\n x: [],\n y: [],\n },\n conv: {\n x: [],\n y: [],\n },\n },\n },\n mls: this.#mlsBufferView,\n mls_psd: {\n x: mls_psd['x_mls'],\n y: mls_psd['y_mls'],\n },\n autocorrelations: this.autocorrelations,\n impulseResponses: [],\n };\n }\n await Promise.all(this.impulseResponses).then(res => {\n for (let i = 0; i < res.length; i++) {\n if (res[i] != undefined) {\n iir_ir_and_plots['impulseResponses'].push(res[i]);\n }\n }\n });\n\n if (this.#download) {\n this.downloadSingleUnfilteredRecording();\n this.downloadSingleFilteredRecording();\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.#mls, 'MLS.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentConvolution, 'python_component_convolution_mls_iir.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemConvolution, 'python_system_convolution_mls_iir.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentInvertedImpulseResponse, 'componentIIR.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemInvertedImpulseResponse, 'systemIIR.csv');\n for (let i = 0; i < this.autocorrelations.length; i++) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.autocorrelations[i], `autocorrelation_${i}`);\n }\n const computedIRagain = await Promise.all(this.impulseResponses).then(res => {\n for (let i = 0; i < res.length; i++) {\n if (res[i] != undefined) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(res[i], `IR_${i}`);\n }\n }\n });\n }\n\n return iir_ir_and_plots;\n };\n\n /**\n * Public method to start the calibration process. Objects intialized from webassembly allocate new memory\n * and must be manually freed. This function is responsible for intializing the MlsGenInterface,\n * and wrapping the calibration steps with a garbage collection safe gaurd.\n *\n * @public\n * @param stream - The stream of audio from the Listener.\n * @example\n */\n startCalibrationImpulseResponse = async stream => {\n let desired_time = this.desired_time_per_mls;\n let checkRec = 'allhz';\n\n console.log('MLS sequence should be of length: ' + this.sourceSamplingRate * desired_time);\n\n length = this.sourceSamplingRate * desired_time;\n //get mls here\n const calibrateSoundBurstDb = this._calibrateSoundBurstDb;\n await this.pyServerAPI\n .getMLSWithRetry({length, calibrateSoundBurstDb})\n .then(res => {\n console.log(res);\n this.#mlsBufferView = res['mls'];\n this.#mls = res['unscaledMLS'];\n })\n .catch(err => {\n // this.emit('InvertedImpulseResponse', {res: false});\n console.error(err);\n });\n this.numSuccessfulBackgroundCaptured = 0;\n if (this._calibrateSoundBackgroundSecs > 0) {\n this.mode = 'background';\n this.status =\n `All Hz Calibration: sampling the background noise...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n await this.recordBackground(\n stream, //stream\n () => this.numSuccessfulBackgroundCaptured < 1, //loop condition\n this.#awaitBackgroundNoiseRecording, //sleep to record\n this.sendBackgroundRecording, //send to get PSD\n this.mode,\n checkRec\n );\n this.incrementStatusBar();\n }\n this.mode = 'unfiltered';\n this.numSuccessfulCaptured = 0;\n\n await this.calibrationSteps(\n stream,\n this.#playCalibrationAudio, // play audio func (required)\n this.#createCalibrationNodeFromBuffer(this.#mlsBufferView), // before play func\n this.#awaitSignalOnset, // before record\n () => this.numSuccessfulCaptured < this.numCaptures, // loop while true\n this.#awaitDesiredMLSLength, // during record\n this.#afterMLSRecord, // after record\n this.mode,\n checkRec\n ),\n this.#stopCalibrationAudio();\n checkRec = false;\n\n // at this stage we've captured all the required signals,\n // and have received IRs for each one\n // so let's send all the IRs to the server to be converted to a single IIR\n await this.sendSystemImpulseResponsesToServerForProcessing();\n await this.sendComponentImpulseResponsesToServerForProcessing();\n\n this.numSuccessfulCaptured = 0;\n\n let iir_ir_and_plots;\n if (this._calibrateSoundCheck != 'none') {\n //do single check\n if (this._calibrateSoundCheck == 'goal' || this._calibrateSoundCheck == 'system') {\n iir_ir_and_plots = await this.singleSoundCheck(stream);\n } else {\n //both\n iir_ir_and_plots = await this.bothSoundCheck(stream);\n }\n } else {\n let unconv_rec = this.componentInvertedImpulseResponseNoBandpass;\n let conv_rec = this.componentInvertedImpulseResponse;\n let component_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n unconv_rec = this.systemInvertedImpulseResponseNoBandpass;\n conv_rec = this.systemInvertedImpulseResponse;\n let system_iir_psd = await this.pyServerAPI\n .getPSDWithRetry({\n unconv_rec,\n conv_rec,\n sampleRate: this.sourceSamplingRate || 96000,\n })\n .then(res => {\n this.incrementStatusBar();\n this.status =\n `All Hz Calibration: done computing the PSD graphs...`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n return res;\n })\n .catch(err => {\n console.error(err);\n });\n\n iir_ir_and_plots = {\n unfiltered_recording: return_unconv_rec,\n filtered_recording: return_conv_rec,\n system: {\n iir: this.systemInvertedImpulseResponse,\n ir: this.systemIR,\n iir_psd: {\n y: system_iir_psd['y_conv'],\n x: system_iir_psd['y_conv'],\n y_no_bandpass: system_iir_psd['y_unconv'],\n x_no_bandpass: system_iir_psd['x_unconv'],\n },\n filtered_recording: [],\n convolution: this.systemConvolution,\n psd: {\n unconv: {\n x: [],\n y: [],\n },\n conv: {\n x: [],\n y: [],\n },\n },\n },\n component: {\n iir: this.componentInvertedImpulseResponse,\n ir: this.componentIR,\n iir_psd: {\n y: component_iir_psd['y_conv'],\n x: component_iir_psd['x_conv'],\n y_no_bandpass: component_iir_psd['y_unconv'],\n x_no_bandpass: component_iir_psd['x_unconv'],\n },\n convolution: this.componentConvolution,\n psd: {\n unconv: {\n x: [],\n y: [],\n },\n conv: {\n x: [],\n y: [],\n },\n },\n },\n mls: this.#mlsBufferView,\n autocorrelations: this.autocorrelations,\n impulseResponses: [],\n };\n await Promise.all(this.impulseResponses).then(res => {\n for (let i = 0; i < res.length; i++) {\n if (res[i] != undefined) {\n iir_ir_and_plots['impulseResponses'].push(res[i]);\n }\n }\n });\n\n if (this.#download) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.#mls, 'MLS.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentConvolution, 'python_component_convolution_mls_iir.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemConvolution, 'python_system_convolution_mls_iir.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.componentInvertedImpulseResponse, 'componentIIR.csv');\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.systemInvertedImpulseResponse, 'systemIIR.csv');\n for (let i = 0; i < this.autocorrelations.length; i++) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(this.autocorrelations[i], `autocorrelation_${i}`);\n }\n const computedIRagain = await Promise.all(this.impulseResponses).then(res => {\n for (let i = 0; i < res.length; i++) {\n if (res[i] != undefined) {\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToCSV)(res[i], `IR_${i}`);\n }\n }\n });\n }\n }\n\n this.percent_complete = 100;\n\n this.status = `All Hz Calibration: Finished`.toString() + this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n\n //here after calibration we have the component calibration (either loudspeaker or microphone) in the same form as the componentIR\n //that was used to calibrate\n (0,_utils__WEBPACK_IMPORTED_MODULE_1__.saveToJSON)(iir_ir_and_plots);\n return iir_ir_and_plots;\n };\n\n //////////////////////volume\n\n handleIncomingData = data => {\n console.log('Received data: ', data);\n if (data.type === 'soundGainDBSPL') {\n this.soundGainDBSPL = data.value;\n } else {\n throw new Error(`Unknown data type: ${data.type}`);\n }\n };\n createSCurveBuffer = (onSetBool = true) => {\n const curve = new Float32Array(this.TAPER_SECS * this.sourceSamplingRate + 1);\n const frequency = 1 / (4 * this.TAPER_SECS);\n let j = 0;\n for (let i = 0; i < this.TAPER_SECS * this.sourceSamplingRate + 1; i += 1) {\n const phase = 2 * Math.PI * frequency * j;\n const onsetTaper = Math.pow(Math.sin(phase), 2);\n const offsetTaper = Math.pow(Math.cos(phase), 2);\n curve[i] = onSetBool ? onsetTaper : offsetTaper;\n j += 1 / this.sourceSamplingRate;\n }\n return curve;\n };\n\n #getTruncatedSignal = (left = 3.5, right = 4.5) => {\n const start = Math.floor(left * this.sourceSamplingRate);\n const end = Math.floor(right * this.sourceSamplingRate);\n const result = Array.from(this.getLastVolumeRecordedSignal().slice(start, end));\n console.log(\n 'Obtaining last 1000 hz recording from #allVolumeRecordings to send for processing'\n );\n /**\n * function to check that capture was properly made\n * @param {*} list\n */\n const checkResult = list => {\n const setItem = new Set(list);\n if (setItem.size === 1 && setItem.has(0)) {\n console.warn(\n 'The last capture failed, all recorded signal is zero',\n this.getAllVolumeRecordedSignals()\n );\n }\n if (setItem.size === 0) {\n console.warn('The last capture failed, no recorded signal');\n }\n };\n checkResult(result);\n return result;\n };\n\n /** \n * \n * \n Construct a calibration Node with the calibration parameters and given gain value\n * @param {*} gainValue\n * */\n #createCalibrationToneWithGainValue = gainValue => {\n const audioContext = this.makeNewSourceAudioContext();\n const oscilator = audioContext.createOscillator();\n const gainNode = audioContext.createGain();\n const taperGainNode = audioContext.createGain();\n const offsetGainNode = audioContext.createGain();\n const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;\n\n oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;\n oscilator.type = this.#CALIBRATION_TONE_TYPE;\n gainNode.gain.value = gainValue;\n\n oscilator.connect(gainNode);\n gainNode.connect(taperGainNode);\n const onsetCurve = this.createSCurveBuffer();\n taperGainNode.gain.setValueCurveAtTime(onsetCurve, 0, this.TAPER_SECS);\n taperGainNode.connect(offsetGainNode);\n const offsetCurve = this.createSCurveBuffer(false);\n offsetGainNode.gain.setValueCurveAtTime(\n offsetCurve,\n totalDuration - this.TAPER_SECS,\n this.TAPER_SECS\n );\n offsetGainNode.connect(audioContext.destination);\n\n this.addCalibrationNode(oscilator);\n };\n\n /**\n * Construct a Calibration Node with the calibration parameters.\n *\n * @private\n * @example\n */\n #createCalibrationNode = () => {\n const audioContext = this.makeNewSourceAudioContext();\n const oscilator = audioContext.createOscillator();\n const gainNode = audioContext.createGain();\n\n oscilator.frequency.value = this.#CALIBRATION_TONE_FREQUENCY;\n oscilator.type = this.#CALIBRATION_TONE_TYPE;\n gainNode.gain.value = 0.04;\n\n oscilator.connect(gainNode);\n gainNode.connect(audioContext.destination);\n\n this.addCalibrationNode(oscilator);\n };\n\n #playCalibrationAudioVolume = async () => {\n const totalDuration = this.CALIBRATION_TONE_DURATION * 1.2;\n\n this.calibrationNodes[0].start(0);\n this.calibrationNodes[0].stop(totalDuration);\n console.log(`Playing a buffer of ${this.CALIBRATION_TONE_DURATION} seconds of audio`);\n console.log(`Waiting a total of ${totalDuration} seconds`);\n await (0,_utils__WEBPACK_IMPORTED_MODULE_1__.sleep)(totalDuration);\n };\n\n #sendToServerForProcessing = lCalib => {\n console.log('Sending data to server');\n let left = this.calibrateSound1000HzPreSec;\n let right = this.calibrateSound1000HzPreSec + this.calibrateSound1000HzSec;\n this.pyServerAPI\n .getVolumeCalibration({\n sampleRate: this.sourceSamplingRate,\n payload: this.#getTruncatedSignal(left, right),\n lCalib: lCalib,\n })\n .then(res => {\n if (this.outDBSPL === null) {\n this.incrementStatusBar();\n this.outDBSPL = res['outDbSPL'];\n this.outDBSPL1000 = res['outDbSPL1000'];\n this.THD = res['thd'];\n }\n })\n .catch(err => {\n console.warn(err);\n });\n };\n\n startCalibrationVolume = async (stream, gainValues, lCalib, componentGainDBSPL) => {\n const trialIterations = gainValues.length;\n this.status_denominator += trialIterations;\n const thdValues = [];\n const inDBValues = [];\n let inDB = 0;\n const outDBSPLValues = [];\n const outDBSPL1000Values = [];\n let checkRec = false;\n\n // do one calibration that will be discarded\n const soundLevelToDiscard = -60;\n const gainToDiscard = Math.pow(10, soundLevelToDiscard / 20);\n this.status =\n `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`.toString() +\n this.generateTemplate().toString();\n //this.emit('update', {message: `1000 Hz Calibration: Sound Level ${soundLevelToDiscard} dB`});\n this.emit('update', {message: this.status});\n\n do {\n // eslint-disable-next-line no-await-in-loop\n await this.volumeCalibrationSteps(\n stream,\n this.#playCalibrationAudioVolume,\n this.#createCalibrationToneWithGainValue,\n this.#sendToServerForProcessing,\n gainToDiscard,\n lCalib, //todo make this a class parameter\n checkRec\n );\n } while (this.outDBSPL === null);\n //reset the values\n //this.incrementStatusBar();\n\n this.outDBSPL = null;\n this.outDBSPL = null;\n this.outDBSPL1000 = null;\n this.THD = null;\n\n // run the calibration at different gain values provided by the user\n for (let i = 0; i < trialIterations; i++) {\n //convert gain to DB and add to inDB\n if (i == trialIterations - 1) {\n checkRec = 'loudest';\n }\n inDB = Math.log10(gainValues[i]) * 20;\n // precision to 1 decimal place\n inDB = Math.round(inDB * 10) / 10;\n inDBValues.push(inDB);\n console.log('next update');\n this.status =\n `1000 Hz Calibration: Sound Level ${inDB} dB`.toString() +\n this.generateTemplate().toString();\n this.emit('update', {message: this.status});\n do {\n // eslint-disable-next-line no-await-in-loop\n await this.volumeCalibrationSteps(\n stream,\n this.#playCalibrationAudioVolume,\n this.#createCalibrationToneWithGainValue,\n this.#sendToServerForProcessing,\n gainValues[i],\n lCalib, //todo make this a class parameter\n checkRec\n );\n } while (this.outDBSPL === null);\n outDBSPL1000Values.push(this.outDBSPL1000);\n thdValues.push(this.THD);\n outDBSPLValues.push(this.outDBSPL);\n\n this.outDBSPL = null;\n this.outDBSPL1000 = null;\n this.THD = null;\n }\n\n // get the volume calibration parameters from the server\n const parameters = await this.pyServerAPI\n .getVolumeCalibrationParameters({\n inDBValues: inDBValues,\n outDBSPLValues: outDBSPL1000Values,\n lCalib: lCalib,\n componentGainDBSPL,\n })\n .then(res => {\n this.incrementStatusBar();\n return res;\n });\n const result = {\n parameters: parameters,\n inDBValues: inDBValues,\n outDBSPLValues: outDBSPLValues,\n outDBSPL1000Values: outDBSPL1000Values,\n thdValues: thdValues,\n };\n\n return result;\n };\n\n // function to write frq and gain to firebase database given speakerID\n writeFrqGain = async (speakerID, frq, gain, OEM) => {\n // freq and gain are too large to take samples 1 in every 100 samples\n\n const sampledFrq = [];\n const sampledGain = [];\n for (let i = 0; i < frq.length; i += 100) {\n sampledFrq.push(frq[i]);\n sampledGain.push(gain[i]);\n }\n\n const data = {Freq: sampledFrq, Gain: sampledGain};\n\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"], `Microphone2/${OEM}/${speakerID}/linear`), data);\n };\n\n // Function to Read frq and gain from firebase database given speakerID\n // returns an array of frq and gain if speakerID exists, returns null otherwise\n\n readFrqGain = async (speakerID, OEM) => {\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/linear`));\n if (snapshot.exists()) {\n return snapshot.val();\n }\n return null;\n };\n\n readGainat1000Hz = async (speakerID, OEM) => {\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/Gain1000`));\n if (snapshot.exists()) {\n return snapshot.val();\n }\n return null;\n };\n\n writeGainat1000Hz = async (speakerID, gain, OEM) => {\n const data = {Gain: gain};\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"], `Microphone2/${OEM}/${speakerID}/Gain1000`), gain);\n };\n\n writeIsSmartPhone = async (speakerID, isSmartPhone, OEM) => {\n const data = {isSmartPhone: isSmartPhone};\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"], `Microphone2/${OEM}/${speakerID}/isSmartPhone`), isSmartPhone);\n };\n\n doesMicrophoneExist = async (speakerID, OEM) => {\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.child)(dbRef, `Microphone2/${OEM}/${speakerID}`));\n if (snapshot.exists()) {\n return true;\n }\n return false;\n };\n\n addMicrophoneInfo = async (speakerID, OEM, micInfo) => {\n // add to database if /info does not exist\n // if there is \"undefined\" in the micInfo, change it to null\n JSON.parse(JSON.stringify(micInfo));\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.child)(dbRef, `Microphone2/${OEM}/${speakerID}/info`));\n if (!snapshot.exists()) {\n await (0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.set)((0,firebase_database__WEBPACK_IMPORTED_MODULE_3__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_2__[\"default\"], `Microphone2/${OEM}/${speakerID}/info`), micInfo);\n }\n };\n\n convertToDB = gain => {\n return Math.log10(gain) * 20;\n };\n\n // Function to perform linear interpolation between two points\n interpolate(x, x0, y0, x1, y1) {\n return y0 + ((x - x0) * (y1 - y0)) / (x1 - x0);\n }\n\n findGainatFrequency = (frequencies, gains, targetFrequency) => {\n // Find the index of the first frequency in the array greater than the target frequency\n let index = 0;\n while (index < frequencies.length && frequencies[index] < targetFrequency) {\n index++;\n }\n\n // Handle cases when the target frequency is outside the range of the given data\n if (index === 0) {\n return gains[0];\n } else if (index === frequencies.length) {\n return gains[gains.length - 1];\n } else {\n // Interpolate the gain based on the surrounding frequencies\n const x0 = frequencies[index - 1];\n const y0 = gains[index - 1];\n const x1 = frequencies[index];\n const y1 = gains[index];\n return this.interpolate(targetFrequency, x0, y0, x1, y1);\n }\n };\n\n // Example of how to use the writeFrqGain and readFrqGain functions\n // writeFrqGain('speaker1', [1, 2, 3], [4, 5, 6]);\n // Speaker1 is the speakerID you want to write to in the database\n // readFrqGain('MiniDSPUMIK_1').then(data => console.log(data));\n // MiniDSPUMIK_1 is the speakerID with some Data in the database\n //adding gainDBSPL\n startCalibration = async (\n stream,\n gainValues,\n lCalib = 104.92978421490648,\n componentIR = null,\n microphoneName = 'MiniDSP-UMIK1-711-4754-vertical',\n _calibrateSoundCheck = 'both', //GOAL PASSed in by default\n isSmartPhone = false,\n _calibrateSoundBurstDb = 0.04,\n _calibrateSoundBurstRepeats = 3,\n _calibrateSoundBurstSec = 1,\n _calibrateSoundBurstsWarmup = 1,\n _calibrateSoundHz = 48000,\n _calibrateSoundIIRSec = 0.2,\n calibrateSound1000HzPreSec = 3.5,\n calibrateSound1000HzSec = 1.0,\n calibrateSound1000HzPostSec = 0.5,\n _calibrateSoundBackgroundSecs = 0,\n micManufacturer = '',\n micSerialNumber = '',\n micModelNumber = '',\n micModelName = ''\n ) => {\n this._calibrateSoundBurstDb = _calibrateSoundBurstDb;\n this.CALIBRATION_TONE_DURATION =\n calibrateSound1000HzPreSec + calibrateSound1000HzSec + calibrateSound1000HzPostSec;\n this.calibrateSound1000HzPreSec = calibrateSound1000HzPreSec;\n this.calibrateSound1000HzSec = calibrateSound1000HzSec;\n this.calibrateSound1000HzPostSec = calibrateSound1000HzPostSec;\n this.iirLength = Math.floor(_calibrateSoundIIRSec * this.sourceSamplingRate);\n console.log('device info:', this.deviceInfo);\n this.numMLSPerCapture = _calibrateSoundBurstRepeats;\n console.log(this.numMLSPerCapture);\n this.desired_time_per_mls = _calibrateSoundBurstSec;\n this.num_mls_to_skip = _calibrateSoundBurstsWarmup;\n this.desired_sampling_rate = _calibrateSoundHz;\n this._calibrateSoundBackgroundSecs = _calibrateSoundBackgroundSecs;\n\n //feed calibration goal here\n this._calibrateSoundCheck = _calibrateSoundCheck;\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\n //check the db based on the microphone currently connected\n\n //new lCalib found at top of calibration files *1000hz, make sure to correct\n //based on zeroing of 1000hz, search for \"*1000Hz\"\n // const ID = isSmartPhone ? micModelNumber : micSerialNumber;\n // const OEM = isSmartPhone ? this.deviceInfo.OEM : micManufacturer;\n const ID = \"711-4754\";\n const OEM = \"MiniDSP\";\n const micInfo = {\n micModelName: isSmartPhone ? micModelName : microphoneName,\n OEM: OEM,\n ID: ID,\n HardwareName: isSmartPhone ? this.deviceInfo.hardwarename : microphoneName,\n hardwareFamily: isSmartPhone ? this.deviceInfo.hardwarefamily : microphoneName,\n HardwareModel: isSmartPhone ? this.deviceInfo.hardwaremodel : microphoneName,\n PlatformName: isSmartPhone ? this.deviceInfo.platformname : 'N/A',\n PlatformVersion: isSmartPhone ? this.deviceInfo.platformversion : 'N/A',\n DeviceType: isSmartPhone ? this.deviceInfo.devicetype : 'N/A',\n };\n this.addMicrophoneInfo(ID, OEM, micInfo);\n if (componentIR == null) {\n //mode 'ir'\n //global variable this.componentIR must be set\n this.componentIR = await this.readFrqGain(ID, OEM).then(data => {\n return data;\n });\n\n lCalib = await this.readGainat1000Hz(ID, OEM);\n micInfo['gainDBSPL'] = lCalib;\n // this.componentGainDBSPL = this.convertToDB(lCalib);\n this.componentGainDBSPL = lCalib;\n //TODO: if this call to database is unknown, cannot perform experiment => return false\n if (this.componentIR == null) {\n this.status =\n `Microphone (${OEM},${ID}) is not found in the database. Please add it to the database.`.toString();\n this.emit('update', {message: this.status});\n return false;\n }\n } else {\n this.componentIR = componentIR;\n lCalib = this.findGainatFrequency(this.componentIR.Freq, this.componentIR.Gain, 1000);\n // this.componentGainDBSPL = this.convertToDB(lCalib);\n this.componentGainDBSPL = lCalib;\n await this.writeIsSmartPhone(ID, isSmartPhone, OEM);\n }\n\n this.oldComponentIR = this.componentIR;\n\n let volumeResults = await this.startCalibrationVolume(\n stream,\n gainValues,\n lCalib,\n this.componentGainDBSPL\n );\n\n let impulseResponseResults = await this.startCalibrationImpulseResponse(stream);\n impulseResponseResults['background_noise'] = this.background_noise;\n if (componentIR != null) {\n //insert Freq and Gain from this.componentIR into db\n await this.writeFrqGain(\n ID,\n impulseResponseResults.componentIR.Freq,\n impulseResponseResults.componentIR.Gain,\n OEM\n );\n micInfo['gainDBSPL'] = impulseResponseResults.parameters.gainDBSPL;\n await this.writeGainat1000Hz(ID, micInfo['gainDBSPL'], OEM);\n }\n\n const total_results = {...volumeResults, ...impulseResponseResults};\n total_results['filteredMLSRange'] = this.filteredMLSRange;\n total_results['micInfo'] = micInfo;\n console.log('total results');\n console.log(total_results);\n return total_results;\n };\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (Combination);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/tasks/combination/combination.js?");
|
|
844
844
|
|
|
845
845
|
/***/ }),
|
|
846
846
|
|
|
@@ -884,7 +884,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _aud
|
|
|
884
884
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
885
885
|
|
|
886
886
|
"use strict";
|
|
887
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"sleep\": function() { return /* binding */ sleep; },\n/* harmony export */ \"saveToCSV\": function() { return /* binding */ saveToCSV; },\n/* harmony export */ \"csvToArray\": function() { return /* binding */ csvToArray; }\n/* harmony export */ });\n/** .\n * .\n * .\n * Utlity function to pause execution for a given time\n *\n * @param {number} seconds\n * @returns {Promise}\n * @example\n */\nconst sleep = seconds =>\n new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n\n/** .\n * .\n * .\n * Uiltity function to create and save a CSV file from a buffer\n *\n * @param {*} data\n * @param {*} filename\n * @example\n */\nconst saveToCSV = (data, filename = 'recordedMLSignal.csv') => {\n // console.log(data)\n let csvContent = 'data:text/csv;charset=utf-8,';\n\n data.forEach((val, idx) => {\n csvContent += `${idx},${val}\\r\\n`;\n });\n const encodedUri = encodeURI(csvContent);\n const link = document.createElement('a');\n link.setAttribute('href', encodedUri);\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n};\n\n/** .\n * .\n * .\n * Utility function to create a buffer from a CSV file\n *\n * @param {*} csvString\n * @param {*} delimiter\n * @returns\n * @example\n */\nconst csvToArray = (csvString, delimiter = ',') =>\n csvString\n .trim()\n .split('\\n')\n .map(row => parseFloat(row.trim().split(delimiter)[1]));\n\n\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/utils.js?");
|
|
887
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"sleep\": function() { return /* binding */ sleep; },\n/* harmony export */ \"saveToCSV\": function() { return /* binding */ saveToCSV; },\n/* harmony export */ \"saveToJSON\": function() { return /* binding */ saveToJSON; },\n/* harmony export */ \"csvToArray\": function() { return /* binding */ csvToArray; },\n/* harmony export */ \"findMinValue\": function() { return /* binding */ findMinValue; },\n/* harmony export */ \"findMaxValue\": function() { return /* binding */ findMaxValue; }\n/* harmony export */ });\n/** .\n * .\n * .\n * Utlity function to pause execution for a given time\n *\n * @param {number} seconds\n * @returns {Promise}\n * @example\n */\nconst sleep = seconds =>\n new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n\n/** .\n * .\n * .\n * Uiltity function to create and save a CSV file from a buffer\n *\n * @param {*} data\n * @param {*} filename\n * @example\n */\nconst saveToCSV = (data, filename = 'recordedMLSignal.csv') => {\n // console.log(data)\n let csvContent = 'data:text/csv;charset=utf-8,';\n\n data.forEach((val, idx) => {\n csvContent += `${idx},${val}\\r\\n`;\n });\n const encodedUri = encodeURI(csvContent);\n const link = document.createElement('a');\n link.setAttribute('href', encodedUri);\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n};\n\nconst saveToJSON = (data, filename = 'recordedMLSignal.json') => {\n const jsonData = JSON.stringify(data, null, 2);\n const blob = new Blob([jsonData], { type: 'application/json' });\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.setAttribute('href', url);\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n URL.revokeObjectURL(url);\n};\n\n\n/** .\n * .\n * .\n * Utility function to create a buffer from a CSV file\n *\n * @param {*} csvString\n * @param {*} delimiter\n * @returns\n * @example\n */\nconst csvToArray = (csvString, delimiter = ',') =>\n csvString\n .trim()\n .split('\\n')\n .map(row => parseFloat(row.trim().split(delimiter)[1]));\n\nconst findMinValue = (array) => {\n let minValue = array[0];\n for (let i = 1; i < array.length; i++) {\n if (array[i] < minValue) {\n minValue = array[i];\n }\n }\n return minValue;\n};\n\nconst findMaxValue = (array) => {\n let maxValue = array[0];\n for (let i = 1; i < array.length; i++) {\n if (array[i] > maxValue) {\n maxValue = array[i];\n }\n }\n return maxValue;\n};\n\n\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/utils.js?");
|
|
888
888
|
|
|
889
889
|
/***/ }),
|
|
890
890
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import AudioCalibrator from '../audioCalibrator';
|
|
2
2
|
|
|
3
|
-
import {sleep, csvToArray, saveToCSV} from '../../utils';
|
|
3
|
+
import {sleep, csvToArray, saveToCSV, saveToJSON,findMinValue,findMaxValue} from '../../utils';
|
|
4
4
|
import database from '../../config/firebase';
|
|
5
5
|
import {ref, set, get, child} from 'firebase/database';
|
|
6
6
|
|
|
@@ -572,14 +572,7 @@ class Combination extends AudioCalibrator {
|
|
|
572
572
|
);
|
|
573
573
|
|
|
574
574
|
const data = buffer.getChannelData(0); // get data
|
|
575
|
-
if (this.mode === 'filtered') {
|
|
576
|
-
console.log('check max and min of convolution');
|
|
577
|
-
} else {
|
|
578
|
-
console.log('check max and min of mls');
|
|
579
|
-
}
|
|
580
575
|
|
|
581
|
-
console.log('Max:', Math.min(...dataBuffer));
|
|
582
|
-
console.log('Min:', Math.max(...dataBuffer));
|
|
583
576
|
// fill the buffer with our data
|
|
584
577
|
try {
|
|
585
578
|
for (let i = 0; i < dataBuffer.length; i += 1) {
|
|
@@ -693,16 +686,16 @@ class Combination extends AudioCalibrator {
|
|
|
693
686
|
bothSoundCheck = async stream => {
|
|
694
687
|
let iir_ir_and_plots;
|
|
695
688
|
this.#currentConvolution = this.componentConvolution;
|
|
696
|
-
this.filteredMLSRange.component.Min =
|
|
697
|
-
this.filteredMLSRange.component.Max =
|
|
689
|
+
this.filteredMLSRange.component.Min = findMinValue(this.#currentConvolution);
|
|
690
|
+
this.filteredMLSRange.component.Max = findMaxValue(this.#currentConvolution);
|
|
698
691
|
await this.playMLSwithIIR(stream, this.#currentConvolution);
|
|
699
692
|
this.#stopCalibrationAudio();
|
|
700
693
|
let component_conv_recs = this.getAllFilteredRecordedSignals();
|
|
701
694
|
let return_component_conv_rec = component_conv_recs[0];
|
|
702
695
|
this.clearAllFilteredRecordedSignals();
|
|
703
696
|
this.#currentConvolution = this.systemConvolution;
|
|
704
|
-
this.filteredMLSRange.system.Min =
|
|
705
|
-
this.filteredMLSRange.system.Max =
|
|
697
|
+
this.filteredMLSRange.system.Min = findMinValue(this.#currentConvolution);
|
|
698
|
+
this.filteredMLSRange.system.Max = findMaxValue(this.#currentConvolution);
|
|
706
699
|
await this.playMLSwithIIR(stream, this.#currentConvolution);
|
|
707
700
|
this.#stopCalibrationAudio();
|
|
708
701
|
let system_conv_recs = this.getAllFilteredRecordedSignals();
|
|
@@ -925,12 +918,12 @@ class Combination extends AudioCalibrator {
|
|
|
925
918
|
let iir_ir_and_plots;
|
|
926
919
|
if (this._calibrateSoundCheck != 'system') {
|
|
927
920
|
this.#currentConvolution = this.componentConvolution;
|
|
928
|
-
this.filteredMLSRange.component.Min =
|
|
929
|
-
this.filteredMLSRange.component.Max =
|
|
921
|
+
this.filteredMLSRange.component.Min = findMinValue(this.#currentConvolution);
|
|
922
|
+
this.filteredMLSRange.component.Max = findMaxValue(this.#currentConvolution);
|
|
930
923
|
} else {
|
|
931
924
|
this.#currentConvolution = this.systemConvolution;
|
|
932
|
-
this.filteredMLSRange.system.Min =
|
|
933
|
-
this.filteredMLSRange.system.Max =
|
|
925
|
+
this.filteredMLSRange.system.Min = findMinValue(this.#currentConvolution);
|
|
926
|
+
this.filteredMLSRange.system.Max = findMaxValue(this.#currentConvolution);
|
|
934
927
|
}
|
|
935
928
|
await this.playMLSwithIIR(stream, this.#currentConvolution);
|
|
936
929
|
this.#stopCalibrationAudio();
|
|
@@ -1494,7 +1487,7 @@ class Combination extends AudioCalibrator {
|
|
|
1494
1487
|
|
|
1495
1488
|
//here after calibration we have the component calibration (either loudspeaker or microphone) in the same form as the componentIR
|
|
1496
1489
|
//that was used to calibrate
|
|
1497
|
-
|
|
1490
|
+
// saveToJSON(iir_ir_and_plots);
|
|
1498
1491
|
return iir_ir_and_plots;
|
|
1499
1492
|
};
|
|
1500
1493
|
|
|
@@ -1848,7 +1841,7 @@ class Combination extends AudioCalibrator {
|
|
|
1848
1841
|
_calibrateSoundCheck = 'goal', //GOAL PASSed in by default
|
|
1849
1842
|
isSmartPhone = false,
|
|
1850
1843
|
_calibrateSoundBurstDb = 0.33,
|
|
1851
|
-
_calibrateSoundBurstRepeats =
|
|
1844
|
+
_calibrateSoundBurstRepeats = 3,
|
|
1852
1845
|
_calibrateSoundBurstSec = 1,
|
|
1853
1846
|
_calibrateSoundBurstsWarmup = 1,
|
|
1854
1847
|
_calibrateSoundHz = 48000,
|
package/src/utils.js
CHANGED
|
@@ -36,6 +36,19 @@ const saveToCSV = (data, filename = 'recordedMLSignal.csv') => {
|
|
|
36
36
|
link.click();
|
|
37
37
|
};
|
|
38
38
|
|
|
39
|
+
const saveToJSON = (data, filename = 'recordedMLSignal.json') => {
|
|
40
|
+
const jsonData = JSON.stringify(data, null, 2);
|
|
41
|
+
const blob = new Blob([jsonData], { type: 'application/json' });
|
|
42
|
+
const url = URL.createObjectURL(blob);
|
|
43
|
+
const link = document.createElement('a');
|
|
44
|
+
link.setAttribute('href', url);
|
|
45
|
+
link.setAttribute('download', filename);
|
|
46
|
+
document.body.appendChild(link);
|
|
47
|
+
link.click();
|
|
48
|
+
URL.revokeObjectURL(url);
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
|
|
39
52
|
/** .
|
|
40
53
|
* .
|
|
41
54
|
* .
|
|
@@ -52,4 +65,24 @@ const csvToArray = (csvString, delimiter = ',') =>
|
|
|
52
65
|
.split('\n')
|
|
53
66
|
.map(row => parseFloat(row.trim().split(delimiter)[1]));
|
|
54
67
|
|
|
55
|
-
|
|
68
|
+
const findMinValue = (array) => {
|
|
69
|
+
let minValue = array[0];
|
|
70
|
+
for (let i = 1; i < array.length; i++) {
|
|
71
|
+
if (array[i] < minValue) {
|
|
72
|
+
minValue = array[i];
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return minValue;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const findMaxValue = (array) => {
|
|
79
|
+
let maxValue = array[0];
|
|
80
|
+
for (let i = 1; i < array.length; i++) {
|
|
81
|
+
if (array[i] > maxValue) {
|
|
82
|
+
maxValue = array[i];
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return maxValue;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
export {sleep, saveToCSV, saveToJSON, csvToArray,findMinValue,findMaxValue};
|