UNPKG

@twilio/voice-sdk

Version:
1 lines 300 kB
(function(root){var bundle=function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){"use strict";var call=require("./twilio/call.js");var device=require("./twilio/device.js");var log=require("./twilio/log.js");var preflight=require("./twilio/preflight/preflight.js");var index=require("./twilio/errors/index.js");Object.defineProperty(exports,"Call",{enumerable:true,get:function(){return call.default}});Object.defineProperty(exports,"Device",{enumerable:true,get:function(){return device.default}});exports.Logger=log.Logger;Object.defineProperty(exports,"PreflightTest",{enumerable:true,get:function(){return preflight.PreflightTest}});exports.TwilioError=index},{"./twilio/call.js":9,"./twilio/device.js":12,"./twilio/errors/index.js":15,"./twilio/log.js":18,"./twilio/preflight/preflight.js":20}],2:[function(require,module,exports){"use strict";var tslib=require("tslib");var deferred=require("./deferred.js");var AsyncQueue=function(){function AsyncQueue(){this._operations=[]}AsyncQueue.prototype.enqueue=function(callback){var hasPending=!!this._operations.length;var deferred$1=new deferred.default;this._operations.push({deferred:deferred$1,callback:callback});if(!hasPending){this._processQueue()}return deferred$1.promise};AsyncQueue.prototype._processQueue=function(){return tslib.__awaiter(this,void 0,void 0,function(){var _a,deferred,callback,result,error,hasResolved,e_1;return tslib.__generator(this,function(_b){switch(_b.label){case 0:if(!this._operations.length)return[3,5];_a=this._operations[0],deferred=_a.deferred,callback=_a.callback;result=void 0;error=void 0;hasResolved=void 0;_b.label=1;case 1:_b.trys.push([1,3,,4]);return[4,callback()];case 2:result=_b.sent();hasResolved=true;return[3,4];case 3:e_1=_b.sent();error=e_1;return[3,4];case 4:this._operations.shift();if(hasResolved){deferred.resolve(result)}else{deferred.reject(error)}return[3,0];case 5:return[2]}})})};return AsyncQueue}();exports.AsyncQueue=AsyncQueue},{"./deferred.js":11,tslib:41}],3:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var tslib=require("tslib");var events=require("events");var device=require("./device.js");var index=require("./errors/index.js");var log=require("./log.js");var outputdevicecollection=require("./outputdevicecollection.js");var mediadeviceinfo=require("./shims/mediadeviceinfo.js");var util=require("./util.js");var kindAliases={audioinput:"Audio Input",audiooutput:"Audio Output"};var AudioHelper=function(_super){tslib.__extends(AudioHelper,_super);function AudioHelper(onActiveOutputsChanged,onActiveInputChanged,options){var _a;var _this=_super.call(this)||this;_this.availableInputDevices=new Map;_this.availableOutputDevices=new Map;_this._audioConstraints=null;_this._defaultInputDeviceStream=null;_this._enabledSounds=(_a={},_a[device.default.SoundName.Disconnect]=true,_a[device.default.SoundName.Incoming]=true,_a[device.default.SoundName.Outgoing]=true,_a);_this._inputDevice=null;_this._inputDevicePromise=null;_this._isPollingInputVolume=false;_this._log=new log.default("AudioHelper");_this._localProcessedStream=null;_this._remoteProcessedStream=null;_this._selectedInputDeviceStream=null;_this._unknownDeviceIndexes={audioinput:{},audiooutput:{}};_this._updateAvailableDevices=function(){if(!_this._mediaDevices||!_this._enumerateDevices){return Promise.reject("Enumeration not supported")}return _this._enumerateDevices().then(function(devices){_this._updateDevices(devices.filter(function(d){return d.kind==="audiooutput"}),_this.availableOutputDevices,_this._removeLostOutput);_this._updateDevices(devices.filter(function(d){return d.kind==="audioinput"}),_this.availableInputDevices,_this._removeLostInput);var defaultDevice=_this.availableOutputDevices.get("default")||Array.from(_this.availableOutputDevices.values())[0];[_this.speakerDevices,_this.ringtoneDevices].forEach(function(outputDevices){if(!outputDevices.get().size&&_this.availableOutputDevices.size&&_this.isOutputSelectionSupported){outputDevices.set(defaultDevice.deviceId).catch(function(reason){_this._log.warn("Unable to set audio output devices. ".concat(reason))})}})})};_this._removeLostInput=function(lostDevice){if(!_this.inputDevice||_this.inputDevice.deviceId!==lostDevice.deviceId){return false}_this._destroyLocalProcessedStream();_this._replaceStream(null);_this._inputDevice=null;_this._maybeStopPollingVolume();var defaultDevice=_this.availableInputDevices.get("default")||Array.from(_this.availableInputDevices.values())[0];if(defaultDevice){_this.setInputDevice(defaultDevice.deviceId)}return true};_this._removeLostOutput=function(lostDevice){var wasSpeakerLost=_this.speakerDevices.delete(lostDevice);var wasRingtoneLost=_this.ringtoneDevices.delete(lostDevice);return wasSpeakerLost||wasRingtoneLost};options=Object.assign({AudioContext:typeof AudioContext!=="undefined"&&AudioContext,setSinkId:typeof HTMLAudioElement!=="undefined"&&HTMLAudioElement.prototype.setSinkId},options);_this._beforeSetInputDevice=options.beforeSetInputDevice||function(){return Promise.resolve()};_this._updateUserOptions(options);_this._audioProcessorEventObserver=options.audioProcessorEventObserver;_this._mediaDevices=options.mediaDevices||navigator.mediaDevices;_this._onActiveInputChanged=onActiveInputChanged;_this._enumerateDevices=typeof options.enumerateDevices==="function"?options.enumerateDevices:_this._mediaDevices&&_this._mediaDevices.enumerateDevices.bind(_this._mediaDevices);var isAudioContextSupported=!!(options.AudioContext||options.audioContext);var isEnumerationSupported=!!_this._enumerateDevices;if(options.enabledSounds){_this._enabledSounds=options.enabledSounds}var isSetSinkSupported=typeof options.setSinkId==="function";_this.isOutputSelectionSupported=isEnumerationSupported&&isSetSinkSupported;_this.isVolumeSupported=isAudioContextSupported;if(_this.isVolumeSupported){_this._audioContext=options.audioContext||options.AudioContext&&new options.AudioContext;if(_this._audioContext){_this._inputVolumeAnalyser=_this._audioContext.createAnalyser();_this._inputVolumeAnalyser.fftSize=32;_this._inputVolumeAnalyser.smoothingTimeConstant=.3}}_this.ringtoneDevices=new outputdevicecollection.default("ringtone",_this.availableOutputDevices,onActiveOutputsChanged,_this.isOutputSelectionSupported);_this.speakerDevices=new outputdevicecollection.default("speaker",_this.availableOutputDevices,onActiveOutputsChanged,_this.isOutputSelectionSupported);_this.addListener("newListener",function(eventName){if(eventName==="inputVolume"){_this._maybeStartPollingVolume()}});_this.addListener("removeListener",function(eventName){if(eventName==="inputVolume"){_this._maybeStopPollingVolume()}});_this.once("newListener",function(){if(!_this.isOutputSelectionSupported){_this._log.warn("Warning: This browser does not support audio output selection.")}if(!_this.isVolumeSupported){_this._log.warn("Warning: This browser does not support Twilio's volume indicator feature.")}});if(isEnumerationSupported){_this._initializeEnumeration()}if(navigator&&navigator.permissions&&typeof navigator.permissions.query==="function"){navigator.permissions.query({name:"microphone"}).then(function(microphonePermissionStatus){if(microphonePermissionStatus.state!=="granted"){var handleStateChange=function(){_this._updateAvailableDevices();_this._stopMicrophonePermissionListener()};microphonePermissionStatus.addEventListener("change",handleStateChange);_this._microphonePermissionStatus=microphonePermissionStatus;_this._onMicrophonePermissionStatusChanged=handleStateChange}}).catch(function(reason){return _this._log.warn("Warning: unable to listen for microphone permission changes. ".concat(reason))})}else{_this._log.warn("Warning: current browser does not support permissions API.")}return _this}Object.defineProperty(AudioHelper.prototype,"audioConstraints",{get:function(){return this._audioConstraints},enumerable:false,configurable:true});Object.defineProperty(AudioHelper.prototype,"inputDevice",{get:function(){return this._inputDevice},enumerable:false,configurable:true});Object.defineProperty(AudioHelper.prototype,"inputStream",{get:function(){return this._localProcessedStream||this._selectedInputDeviceStream},enumerable:false,configurable:true});Object.defineProperty(AudioHelper.prototype,"processedStream",{get:function(){this._log.warn("AudioHelper#processedStream is deprecated. Please use AudioHelper#localProcessedStream instead.");return this._localProcessedStream},enumerable:false,configurable:true});Object.defineProperty(AudioHelper.prototype,"localProcessedStream",{get:function(){return this._localProcessedStream},enumerable:false,configurable:true});Object.defineProperty(AudioHelper.prototype,"remoteProcessedStream",{get:function(){return this._remoteProcessedStream},enumerable:false,configurable:true});AudioHelper.prototype._destroy=function(){this._stopDefaultInputDeviceStream();this._stopSelectedInputDeviceStream();this._destroyLocalProcessedStream();this._destroyRemoteProcessedStream();this._maybeStopPollingVolume();this.removeAllListeners();this._stopMicrophonePermissionListener();this._unbind()};AudioHelper.prototype._destroyRemoteProcessedStream=function(){if(this._remoteProcessor&&this._remoteProcessedStream){this._log.info("destroying remote processed stream");var remoteProcessedStream=this._remoteProcessedStream;this._remoteProcessedStream.getTracks().forEach(function(track){return track.stop()});this._remoteProcessedStream=null;this._remoteProcessor.destroyProcessedStream(remoteProcessedStream);this._audioProcessorEventObserver.emit("destroy",true)}};AudioHelper.prototype._getInputDevicePromise=function(){return this._inputDevicePromise};AudioHelper.prototype._getAudioProcessorEventObserver=function(){return this._audioProcessorEventObserver};AudioHelper.prototype._maybeCreateRemoteProcessedStream=function(stream){var _this=this;if(this._remoteProcessor){this._log.info("Creating remote processed stream");return this._remoteProcessor.createProcessedStream(stream).then(function(processedStream){_this._remoteProcessedStream=processedStream;_this._audioProcessorEventObserver.emit("create",true);return _this._remoteProcessedStream})}return Promise.resolve(stream)};AudioHelper.prototype._maybeStartPollingVolume=function(){var _this=this;if(!this.isVolumeSupported||!this.inputStream){return}this._updateVolumeSource();if(this._isPollingInputVolume||!this._inputVolumeAnalyser){return}var bufferLength=this._inputVolumeAnalyser.frequencyBinCount;var buffer=new Uint8Array(bufferLength);this._isPollingInputVolume=true;var emitVolume=function(){if(!_this._isPollingInputVolume){return}if(_this._inputVolumeAnalyser){_this._inputVolumeAnalyser.getByteFrequencyData(buffer);var inputVolume=util.average(buffer);_this.emit("inputVolume",inputVolume/255)}requestAnimationFrame(emitVolume)};requestAnimationFrame(emitVolume)};AudioHelper.prototype._maybeStopPollingVolume=function(){if(!this.isVolumeSupported){return}if(!this._isPollingInputVolume||this.inputStream&&this.listenerCount("inputVolume")){return}if(this._inputVolumeSource){this._inputVolumeSource.disconnect();delete this._inputVolumeSource}this._isPollingInputVolume=false};AudioHelper.prototype._openDefaultDeviceWithConstraints=function(constraints){var _this=this;this._log.info("Opening default device with constraints",constraints);return this._getUserMedia(constraints).then(function(stream){_this._log.info("Opened default device. Updating available devices.");_this._updateAvailableDevices().catch(function(error){_this._log.warn("Unable to updateAvailableDevices after gUM call",error)});_this._defaultInputDeviceStream=stream;return _this._maybeCreateLocalProcessedStream(stream)})};AudioHelper.prototype._stopDefaultInputDeviceStream=function(){if(this._defaultInputDeviceStream){this._log.info("stopping default device stream");this._defaultInputDeviceStream.getTracks().forEach(function(track){return track.stop()});this._defaultInputDeviceStream=null;this._destroyLocalProcessedStream()}};AudioHelper.prototype._unbind=function(){var _a;if((_a=this._mediaDevices)===null||_a===void 0?void 0:_a.removeEventListener){this._mediaDevices.removeEventListener("devicechange",this._updateAvailableDevices)}};AudioHelper.prototype._updateUserOptions=function(options){if(typeof options.enumerateDevices==="function"){this._enumerateDevices=options.enumerateDevices}if(typeof options.getUserMedia==="function"){this._getUserMedia=options.getUserMedia}};AudioHelper.prototype.addProcessor=function(processor,isRemote){if(isRemote===void 0){isRemote=false}this._log.debug(".addProcessor");if(this._localProcessor&&!isRemote){throw new index.NotSupportedError("Can only have one Local AudioProcessor at a time.")}if(this._remoteProcessor&&isRemote){throw new index.NotSupportedError("Can only have one Remote AudioProcessor at a time.")}if(typeof processor!=="object"||processor===null){throw new index.InvalidArgumentError("Missing AudioProcessor argument.")}if(typeof processor.createProcessedStream!=="function"){throw new index.InvalidArgumentError("Missing createProcessedStream() method.")}if(typeof processor.destroyProcessedStream!=="function"){throw new index.InvalidArgumentError("Missing destroyProcessedStream() method.")}if(isRemote){this._remoteProcessor=processor;this._audioProcessorEventObserver.emit("add",true);return Promise.resolve()}else{this._localProcessor=processor;this._audioProcessorEventObserver.emit("add",false);return this._restartInputStreams()}};AudioHelper.prototype.disconnect=function(doEnable){this._log.debug(".disconnect",doEnable);return this._maybeEnableSound(device.default.SoundName.Disconnect,doEnable)};AudioHelper.prototype.incoming=function(doEnable){this._log.debug(".incoming",doEnable);return this._maybeEnableSound(device.default.SoundName.Incoming,doEnable)};AudioHelper.prototype.outgoing=function(doEnable){this._log.debug(".outgoing",doEnable);return this._maybeEnableSound(device.default.SoundName.Outgoing,doEnable)};AudioHelper.prototype.removeProcessor=function(processor,isRemote){if(isRemote===void 0){isRemote=false}this._log.debug(".removeProcessor");if(typeof processor!=="object"||processor===null){throw new index.InvalidArgumentError("Missing AudioProcessor argument.")}if(this._localProcessor!==processor&&!isRemote){throw new index.InvalidArgumentError("Cannot remove a Local AudioProcessor that has not been previously added.")}if(this._remoteProcessor!==processor&&isRemote){throw new index.InvalidArgumentError("Cannot remove a Remote AudioProcessor that has not been previously added.")}if(isRemote){this._destroyRemoteProcessedStream();this._remoteProcessor=null;this._audioProcessorEventObserver.emit("remove",true);return Promise.resolve()}else{this._destroyLocalProcessedStream();this._localProcessor=null;this._audioProcessorEventObserver.emit("remove",false);return this._restartInputStreams()}};AudioHelper.prototype.setAudioConstraints=function(audioConstraints){this._log.debug(".setAudioConstraints",audioConstraints);this._audioConstraints=Object.assign({},audioConstraints);delete this._audioConstraints.deviceId;return this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,true):Promise.resolve()};AudioHelper.prototype.setInputDevice=function(deviceId){this._log.debug(".setInputDevice",deviceId);return this._setInputDevice(deviceId,false)};AudioHelper.prototype.unsetAudioConstraints=function(){this._log.debug(".unsetAudioConstraints");this._audioConstraints=null;return this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,true):Promise.resolve()};AudioHelper.prototype.unsetInputDevice=function(){var _this=this;this._log.debug(".unsetInputDevice",this.inputDevice);if(!this.inputDevice){return Promise.resolve()}this._destroyLocalProcessedStream();return this._onActiveInputChanged(null).then(function(){_this._replaceStream(null);_this._inputDevice=null;_this._maybeStopPollingVolume()})};AudioHelper.prototype._destroyLocalProcessedStream=function(){if(this._localProcessor&&this._localProcessedStream){this._log.info("destroying local processed stream");var localProcessedStream=this._localProcessedStream;this._localProcessedStream.getTracks().forEach(function(track){return track.stop()});this._localProcessedStream=null;this._localProcessor.destroyProcessedStream(localProcessedStream);this._audioProcessorEventObserver.emit("destroy",false)}};AudioHelper.prototype._getUnknownDeviceIndex=function(mediaDeviceInfo){var id=mediaDeviceInfo.deviceId;var kind=mediaDeviceInfo.kind;var index=this._unknownDeviceIndexes[kind][id];if(!index){index=Object.keys(this._unknownDeviceIndexes[kind]).length+1;this._unknownDeviceIndexes[kind][id]=index}return index};AudioHelper.prototype._initializeEnumeration=function(){var _this=this;if(!this._mediaDevices||!this._enumerateDevices){throw new index.NotSupportedError("Enumeration is not supported")}if(this._mediaDevices.addEventListener){this._mediaDevices.addEventListener("devicechange",this._updateAvailableDevices)}this._updateAvailableDevices().then(function(){if(!_this.isOutputSelectionSupported){return}Promise.all([_this.speakerDevices.set("default"),_this.ringtoneDevices.set("default")]).catch(function(reason){_this._log.warn("Warning: Unable to set audio output devices. ".concat(reason))})})};AudioHelper.prototype._maybeCreateLocalProcessedStream=function(stream){var _this=this;if(this._localProcessor){this._log.info("Creating local processed stream");return this._localProcessor.createProcessedStream(stream).then(function(processedStream){_this._localProcessedStream=processedStream;_this._audioProcessorEventObserver.emit("create",false);return _this._localProcessedStream})}return Promise.resolve(stream)};AudioHelper.prototype._maybeEnableSound=function(soundName,doEnable){if(typeof doEnable!=="undefined"){this._enabledSounds[soundName]=doEnable}return this._enabledSounds[soundName]};AudioHelper.prototype._replaceStream=function(stream){this._log.info("Replacing with new stream.");if(this._selectedInputDeviceStream){this._log.info("Old stream detected. Stopping tracks.");this._stopSelectedInputDeviceStream()}this._selectedInputDeviceStream=stream};AudioHelper.prototype._restartInputStreams=function(){if(this.inputDevice&&this._selectedInputDeviceStream){this._log.info("Restarting selected input device");return this._setInputDevice(this.inputDevice.deviceId,true)}if(this._defaultInputDeviceStream){var defaultDevice=this.availableInputDevices.get("default")||Array.from(this.availableInputDevices.values())[0];this._log.info("Restarting default input device, now becoming selected.");return this._setInputDevice(defaultDevice.deviceId,true)}return Promise.resolve()};AudioHelper.prototype._setInputDevice=function(deviceId,forceGetUserMedia){return tslib.__awaiter(this,void 0,void 0,function(){var setInputDevice;var _this=this;return tslib.__generator(this,function(_a){setInputDevice=function(){return tslib.__awaiter(_this,void 0,void 0,function(){var device,constraints;var _this=this;return tslib.__generator(this,function(_a){switch(_a.label){case 0:return[4,this._beforeSetInputDevice()];case 1:_a.sent();if(typeof deviceId!=="string"){return[2,Promise.reject(new index.InvalidArgumentError("Must specify the device to set"))]}device=this.availableInputDevices.get(deviceId);if(!device){return[2,Promise.reject(new index.InvalidArgumentError("Device not found: ".concat(deviceId)))]}this._log.info("Setting input device. ID: "+deviceId);if(this._inputDevice&&this._inputDevice.deviceId===deviceId&&this._selectedInputDeviceStream){if(!forceGetUserMedia){return[2,Promise.resolve()]}this._log.info("Same track detected on setInputDevice, stopping old tracks.");this._stopSelectedInputDeviceStream()}this._stopDefaultInputDeviceStream();constraints={audio:Object.assign({deviceId:{exact:deviceId}},this.audioConstraints)};this._log.info("setInputDevice: getting new tracks.");return[2,this._getUserMedia(constraints).then(function(originalStream){_this._destroyLocalProcessedStream();return _this._maybeCreateLocalProcessedStream(originalStream).then(function(newStream){_this._log.info("setInputDevice: invoking _onActiveInputChanged.");return _this._onActiveInputChanged(newStream).then(function(){_this._replaceStream(originalStream);_this._inputDevice=device;_this._maybeStartPollingVolume()})})})]}})})};return[2,this._inputDevicePromise=setInputDevice().finally(function(){_this._inputDevicePromise=null})]})})};AudioHelper.prototype._stopMicrophonePermissionListener=function(){var _a;if((_a=this._microphonePermissionStatus)===null||_a===void 0?void 0:_a.removeEventListener){this._microphonePermissionStatus.removeEventListener("change",this._onMicrophonePermissionStatusChanged)}};AudioHelper.prototype._stopSelectedInputDeviceStream=function(){if(this._selectedInputDeviceStream){this._log.info("Stopping selected device stream");this._selectedInputDeviceStream.getTracks().forEach(function(track){return track.stop()})}};AudioHelper.prototype._updateDevices=function(updatedDevices,availableDevices,removeLostDevice){var _this=this;var updatedDeviceIds=updatedDevices.map(function(d){return d.deviceId});var knownDeviceIds=Array.from(availableDevices.values()).map(function(d){return d.deviceId});var lostActiveDevices=[];var lostDeviceIds=util.difference(knownDeviceIds,updatedDeviceIds);lostDeviceIds.forEach(function(lostDeviceId){var lostDevice=availableDevices.get(lostDeviceId);if(lostDevice){availableDevices.delete(lostDeviceId);if(removeLostDevice(lostDevice)){lostActiveDevices.push(lostDevice)}}});var deviceChanged=false;updatedDevices.forEach(function(newDevice){var existingDevice=availableDevices.get(newDevice.deviceId);var newMediaDeviceInfo=_this._wrapMediaDeviceInfo(newDevice);if(!existingDevice||existingDevice.label!==newMediaDeviceInfo.label){availableDevices.set(newDevice.deviceId,newMediaDeviceInfo);deviceChanged=true}});if(deviceChanged||lostDeviceIds.length){var defaultId_1="default";var isInputDeviceSet=this.inputDevice&&this.inputDevice.deviceId===defaultId_1;var isDefaultDeviceSet=this._defaultInputDeviceStream&&this.availableInputDevices.get(defaultId_1);if(isInputDeviceSet||isDefaultDeviceSet){this._log.warn("Calling getUserMedia after device change to ensure that the tracks of the active device (default) have not gone stale.");setTimeout(function(){_this._setInputDevice(defaultId_1,true)},0)}this._log.debug("#deviceChange",lostActiveDevices);this.emit("deviceChange",lostActiveDevices)}};AudioHelper.prototype._updateVolumeSource=function(){if(!this.inputStream||!this._audioContext||!this._inputVolumeAnalyser){return}if(this._inputVolumeSource){this._inputVolumeSource.disconnect()}try{this._inputVolumeSource=this._audioContext.createMediaStreamSource(this.inputStream);this._inputVolumeSource.connect(this._inputVolumeAnalyser)}catch(ex){this._log.warn("Unable to update volume source",ex);delete this._inputVolumeSource}};AudioHelper.prototype._wrapMediaDeviceInfo=function(mediaDeviceInfo){var options={deviceId:mediaDeviceInfo.deviceId,groupId:mediaDeviceInfo.groupId,kind:mediaDeviceInfo.kind,label:mediaDeviceInfo.label};if(!options.label){if(options.deviceId==="default"){options.label="Default"}else{var index=this._getUnknownDeviceIndex(mediaDeviceInfo);options.label="Unknown ".concat(kindAliases[options.kind]," Device ").concat(index)}}return new mediadeviceinfo.default(options)};return AudioHelper}(events.EventEmitter);(function(AudioHelper){})(AudioHelper||(AudioHelper={}));var AudioHelper$1=AudioHelper;exports.default=AudioHelper$1},{"./device.js":12,"./errors/index.js":15,"./log.js":18,"./outputdevicecollection.js":19,"./shims/mediadeviceinfo.js":33,"./util.js":37,events:39,tslib:41}],4:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var tslib=require("tslib");var deferred=require("./deferred.js");var eventtarget=require("./eventtarget.js");var AudioPlayer=function(_super){tslib.__extends(AudioPlayer,_super);function AudioPlayer(audioContext,srcOrOptions,options){if(srcOrOptions===void 0){srcOrOptions={}}if(options===void 0){options={}}var _this=_super.call(this)||this;_this._audioNode=null;_this._loop=false;_this._pendingPlayDeferreds=[];_this._sinkId="default";_this._src="";if(typeof srcOrOptions!=="string"){options=srcOrOptions}_this._audioContext=audioContext;_this._audioElement=new(options.AudioFactory||Audio);_this._bufferPromise=_this._createPlayDeferred().promise;_this._destination=_this._audioContext.destination;_this._gainNode=_this._audioContext.createGain();_this._gainNode.connect(_this._destination);_this._XMLHttpRequest=options.XMLHttpRequestFactory||XMLHttpRequest;_this.addEventListener("canplaythrough",function(){_this._resolvePlayDeferreds()});if(typeof srcOrOptions==="string"){_this.src=srcOrOptions}return _this}Object.defineProperty(AudioPlayer.prototype,"destination",{get:function(){return this._destination},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"loop",{get:function(){return this._loop},set:function(shouldLoop){var self=this;function pauseAfterPlaythrough(){self._audioNode.removeEventListener("ended",pauseAfterPlaythrough);self.pause()}if(!shouldLoop&&this.loop&&!this.paused){this._audioNode.addEventListener("ended",pauseAfterPlaythrough)}this._loop=shouldLoop},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"muted",{get:function(){return this._gainNode.gain.value===0},set:function(shouldBeMuted){this._gainNode.gain.value=shouldBeMuted?0:1},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"paused",{get:function(){return this._audioNode===null},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"src",{get:function(){return this._src},set:function(src){this._load(src)},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"srcObject",{get:function(){return this._audioElement.srcObject},set:function(srcObject){this._audioElement.srcObject=srcObject},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"sinkId",{get:function(){return this._sinkId},enumerable:false,configurable:true});AudioPlayer.prototype.load=function(){this._load(this._src)};AudioPlayer.prototype.pause=function(){if(this.paused){return}this._audioElement.pause();this._audioNode.stop();this._audioNode.disconnect(this._gainNode);this._audioNode=null;this._rejectPlayDeferreds(new Error("The play() request was interrupted by a call to pause()."))};AudioPlayer.prototype.play=function(){return tslib.__awaiter(this,void 0,void 0,function(){var buffer;var _this=this;return tslib.__generator(this,function(_a){switch(_a.label){case 0:if(!!this.paused)return[3,2];return[4,this._bufferPromise];case 1:_a.sent();if(!this.paused){return[2]}throw new Error("The play() request was interrupted by a call to pause().");case 2:this._audioNode=this._audioContext.createBufferSource();this._audioNode.loop=this.loop;this._audioNode.addEventListener("ended",function(){if(_this._audioNode&&_this._audioNode.loop){return}_this.dispatchEvent("ended")});return[4,this._bufferPromise];case 3:buffer=_a.sent();if(this.paused){throw new Error("The play() request was interrupted by a call to pause().")}this._audioNode.buffer=buffer;this._audioNode.connect(this._gainNode);this._audioNode.start();if(this._audioElement.srcObject){return[2,this._audioElement.play()]}return[2]}})})};AudioPlayer.prototype.setSinkId=function(sinkId){return tslib.__awaiter(this,void 0,void 0,function(){return tslib.__generator(this,function(_a){switch(_a.label){case 0:if(typeof this._audioElement.setSinkId!=="function"){throw new Error("This browser does not support setSinkId.")}if(sinkId===this.sinkId){return[2]}if(sinkId==="default"){if(!this.paused){this._gainNode.disconnect(this._destination)}this._audioElement.srcObject=null;this._destination=this._audioContext.destination;this._gainNode.connect(this._destination);this._sinkId=sinkId;return[2]}return[4,this._audioElement.setSinkId(sinkId)];case 1:_a.sent();if(this._audioElement.srcObject){return[2]}this._gainNode.disconnect(this._audioContext.destination);this._destination=this._audioContext.createMediaStreamDestination();this._audioElement.srcObject=this._destination.stream;this._sinkId=sinkId;this._gainNode.connect(this._destination);return[2]}})})};AudioPlayer.prototype._createPlayDeferred=function(){var deferred$1=new deferred.default;this._pendingPlayDeferreds.push(deferred$1);return deferred$1};AudioPlayer.prototype._load=function(src){var _this=this;if(this._src&&this._src!==src){this.pause()}this._src=src;this._bufferPromise=new Promise(function(resolve,reject){return tslib.__awaiter(_this,void 0,void 0,function(){var buffer;return tslib.__generator(this,function(_a){switch(_a.label){case 0:if(!src){return[2,this._createPlayDeferred().promise]}return[4,bufferSound(this._audioContext,this._XMLHttpRequest,src)];case 1:buffer=_a.sent();this.dispatchEvent("canplaythrough");resolve(buffer);return[2]}})})})};AudioPlayer.prototype._rejectPlayDeferreds=function(reason){var deferreds=this._pendingPlayDeferreds;deferreds.splice(0,deferreds.length).forEach(function(_a){var reject=_a.reject;return reject(reason)})};AudioPlayer.prototype._resolvePlayDeferreds=function(result){var deferreds=this._pendingPlayDeferreds;deferreds.splice(0,deferreds.length).forEach(function(_a){var resolve=_a.resolve;return resolve(result)})};return AudioPlayer}(eventtarget.default);function bufferSound(context,RequestFactory,src){return tslib.__awaiter(this,void 0,void 0,function(){var request,event;return tslib.__generator(this,function(_a){switch(_a.label){case 0:request=new RequestFactory;request.open("GET",src,true);request.responseType="arraybuffer";return[4,new Promise(function(resolve){request.addEventListener("load",resolve);request.send()})];case 1:event=_a.sent();try{return[2,context.decodeAudioData(event.target.response)]}catch(e){return[2,new Promise(function(resolve){context.decodeAudioData(event.target.response,resolve)})]}return[2]}})})}exports.default=AudioPlayer},{"./deferred.js":5,"./eventtarget.js":6,tslib:41}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var Deferred=function(){function Deferred(){var _this=this;this.promise=new Promise(function(resolve,reject){_this._resolve=resolve;_this._reject=reject})}Object.defineProperty(Deferred.prototype,"reject",{get:function(){return this._reject},enumerable:false,configurable:true});Object.defineProperty(Deferred.prototype,"resolve",{get:function(){return this._resolve},enumerable:false,configurable:true});return Deferred}();exports.default=Deferred},{}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var tslib=require("tslib");var events=require("events");var EventTarget=function(){function EventTarget(){this._eventEmitter=new events.EventEmitter}EventTarget.prototype.addEventListener=function(name,handler){return this._eventEmitter.addListener(name,handler)};EventTarget.prototype.dispatchEvent=function(name){var _a;var args=[];for(var _i=1;_i<arguments.length;_i++){args[_i-1]=arguments[_i]}return(_a=this._eventEmitter).emit.apply(_a,tslib.__spreadArray([name],args,false))};EventTarget.prototype.removeEventListener=function(name,handler){return this._eventEmitter.removeListener(name,handler)};return EventTarget}();exports.default=EventTarget},{events:39,tslib:41}],7:[function(require,module,exports){"use strict";var tslib=require("tslib");var events=require("events");var log=require("./log.js");var AudioProcessorEventObserver=function(_super){tslib.__extends(AudioProcessorEventObserver,_super);function AudioProcessorEventObserver(){var _this=_super.call(this)||this;_this._log=new log.default("AudioProcessorEventObserver");_this._log.info("Creating AudioProcessorEventObserver instance");_this.on("enabled",function(isRemote){return _this._reEmitEvent("enabled",isRemote)});_this.on("add",function(isRemote){return _this._reEmitEvent("add",isRemote)});_this.on("remove",function(isRemote){return _this._reEmitEvent("remove",isRemote)});_this.on("create",function(isRemote){return _this._reEmitEvent("create-processed-stream",isRemote)});_this.on("destroy",function(isRemote){return _this._reEmitEvent("destroy-processed-stream",isRemote)});return _this}AudioProcessorEventObserver.prototype.destroy=function(){this.removeAllListeners()};AudioProcessorEventObserver.prototype._reEmitEvent=function(name,isRemote){this._log.info("".concat(isRemote?"Remote":"Local"," AudioProcessor:").concat(name));this.emit("event",{name:name,group:"audio-processor",isRemote:isRemote})};return AudioProcessorEventObserver}(events.EventEmitter);exports.AudioProcessorEventObserver=AudioProcessorEventObserver},{"./log.js":18,events:39,tslib:41}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var tslib=require("tslib");var events=require("events");var Backoff=function(_super){tslib.__extends(Backoff,_super);function Backoff(options){var _this=_super.call(this)||this;Object.defineProperties(_this,{_attempts:{value:0,writable:true},_duration:{enumerable:false,get:function(){var ms=this._min*Math.pow(this._factor,this._attempts);if(this._jitter){var rand=Math.random();var deviation=Math.floor(rand*this._jitter*ms);ms=(Math.floor(rand*10)&1)===0?ms-deviation:ms+deviation}return Math.min(ms,this._max)|0}},_factor:{value:options.factor||2},_jitter:{value:options.jitter>0&&options.jitter<=1?options.jitter:0},_max:{value:options.max||1e4},_min:{value:options.min||100},_timeoutID:{value:null,writable:true}});return _this}Backoff.prototype.backoff=function(){var _this=this;var duration=this._duration;if(this._timeoutID){clearTimeout(this._timeoutID);this._timeoutID=null}this.emit("backoff",this._attempts,duration);this._timeoutID=setTimeout(function(){_this.emit("ready",_this._attempts,duration);_this._attempts++},duration)};Backoff.prototype.reset=function(){this._attempts=0;if(this._timeoutID){clearTimeout(this._timeoutID);this._timeoutID=null}};return Backoff}(events.EventEmitter);exports.default=Backoff},{events:39,tslib:41}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var tslib=require("tslib");var events=require("events");var backoff=require("./backoff.js");var device=require("./device.js");var index=require("./errors/index.js");var log=require("./log.js");var peerconnection=require("./rtc/peerconnection.js");require("./rtc/rtcpc.js");var icecandidate=require("./rtc/icecandidate.js");var sdp=require("./rtc/sdp.js");var sid=require("./sid.js");var statsMonitor=require("./statsMonitor.js");var util=require("./util.js");var constants=require("./constants.js");var generated=require("./errors/generated.js");var BACKOFF_CONFIG={factor:1.1,jitter:.5,max:3e4,min:1};var DTMF_INTER_TONE_GAP=70;var DTMF_PAUSE_DURATION=500;var DTMF_TONE_DURATION=160;var METRICS_BATCH_SIZE=10;var METRICS_DELAY=5e3;var MEDIA_DISCONNECT_ERROR={disconnect:true,info:{code:31003,message:"Connection with Twilio was interrupted.",twilioError:new generated.MediaErrors.ConnectionError}};var MULTIPLE_THRESHOLD_WARNING_NAMES={packetsLostFraction:{max:"packet-loss",maxAverage:"packets-lost-fraction"}};var WARNING_NAMES={audioInputLevel:"audio-input-level",audioOutputLevel:"audio-output-level",bytesReceived:"bytes-received",bytesSent:"bytes-sent",jitter:"jitter",mos:"mos",rtt:"rtt"};var WARNING_PREFIXES={max:"high-",maxAverage:"high-",maxDuration:"constant-",min:"low-",minStandardDeviation:"constant-"};exports.default=function(_super){tslib.__extends(Call,_super);function Call(config,options){var _this=_super.call(this)||this;_this.parameters={};_this._inputVolumeStreak=0;_this._isAnswered=false;_this._isCancelled=false;_this._isRejected=false;_this._latestInputVolume=0;_this._latestOutputVolume=0;_this._log=new log.default("Call");_this._mediaStatus=Call.State.Pending;_this._messages=new Map;_this._metricsSamples=[];_this._options={MediaHandler:peerconnection.default,MediaStream:null,enableImprovedSignalingErrorPrecision:false,offerSdp:null,shouldPlayDisconnect:function(){return true},voiceEventSidGenerator:sid.generateVoiceEventSid};_this._outputVolumeStreak=0;_this._shouldSendHangup=true;_this._signalingStatus=Call.State.Pending;_this._soundcache=new Map;_this._status=Call.State.Pending;_this._wasConnected=false;_this.toString=function(){return"[Twilio.Call instance]"};_this._emitWarning=function(groupPrefix,warningName,threshold,value,wasCleared,warningData){var groupSuffix=wasCleared?"-cleared":"-raised";var groupName="".concat(groupPrefix,"warning").concat(groupSuffix);if(warningName==="constant-audio-input-level"&&_this.isMuted()){return}var level=wasCleared?"info":"warning";if(warningName==="constant-audio-output-level"){level="info"}var payloadData={threshold:threshold};if(value){if(value instanceof Array){payloadData.values=value.map(function(val){if(typeof val==="number"){return Math.round(val*100)/100}return value})}else{payloadData.value=value}}_this._publisher.post(level,groupName,warningName,{data:payloadData},_this);if(warningName!=="constant-audio-output-level"){var emitName=wasCleared?"warning-cleared":"warning";_this._log.debug("#".concat(emitName),warningName);_this.emit(emitName,warningName,warningData&&!wasCleared?warningData:null)}};_this._onAck=function(payload){var acktype=payload.acktype,callsid=payload.callsid,voiceeventsid=payload.voiceeventsid;if(_this.parameters.CallSid!==callsid){_this._log.warn("Received ack from a different callsid: ".concat(callsid));return}if(acktype==="message"){_this._onMessageSent(voiceeventsid)}};_this._onAnswer=function(payload){if(typeof payload.reconnect==="string"){_this._signalingReconnectToken=payload.reconnect}if(_this._isAnswered&&_this._status!==Call.State.Reconnecting){return}_this._setCallSid(payload);_this._isAnswered=true;_this._maybeTransitionToOpen()};_this._onCancel=function(payload){var callsid=payload.callsid;if(_this.parameters.CallSid===callsid){_this._isCancelled=true;_this._publisher.info("connection","cancel",null,_this);_this._cleanupEventListeners();_this._mediaHandler.close();_this._status=Call.State.Closed;_this._log.debug("#cancel");_this.emit("cancel");_this._pstream.removeListener("cancel",_this._onCancel)}};_this._onConnected=function(){_this._log.info("Received connected from pstream");if(_this._signalingReconnectToken&&_this._mediaHandler.version){_this._pstream.reconnect(_this._mediaHandler.version.getSDP(),_this.parameters.CallSid,_this._signalingReconnectToken)}};_this._onHangup=function(payload){if(_this.status()===Call.State.Closed){return}if(payload.callsid&&(_this.parameters.CallSid||_this.outboundConnectionId)){if(payload.callsid!==_this.parameters.CallSid&&payload.callsid!==_this.outboundConnectionId){return}}else if(payload.callsid){return}_this._log.info("Received HANGUP from gateway");if(payload.error){var code=payload.error.code;var errorConstructor=index.getPreciseSignalingErrorByCode(_this._options.enableImprovedSignalingErrorPrecision,code);var error=typeof errorConstructor!=="undefined"?new errorConstructor(payload.error.message):new generated.GeneralErrors.ConnectionError("Error sent from gateway in HANGUP",payload.error);_this._log.error("Received an error from the gateway:",error);_this._log.debug("#error",error);_this.emit("error",error)}_this._shouldSendHangup=false;_this._publisher.info("connection","disconnected-by-remote",null,_this);_this._disconnect(null,true);_this._cleanupEventListeners()};_this._onMediaFailure=function(type){var _a=Call.MediaFailure,ConnectionDisconnected=_a.ConnectionDisconnected,ConnectionFailed=_a.ConnectionFailed,IceGatheringFailed=_a.IceGatheringFailed,LowBytes=_a.LowBytes;var isEndOfIceCycle=type===ConnectionFailed||type===IceGatheringFailed;if(!util.isChrome(window,window.navigator)&&type===ConnectionFailed){return _this._mediaHandler.onerror(MEDIA_DISCONNECT_ERROR)}if(_this._mediaStatus===Call.State.Reconnecting){if(isEndOfIceCycle){if(Date.now()-_this._mediaReconnectStartTime>BACKOFF_CONFIG.max){_this._log.warn("Exceeded max ICE retries");return _this._mediaHandler.onerror(MEDIA_DISCONNECT_ERROR)}try{_this._mediaReconnectBackoff.backoff()}catch(error){if(!(error.message&&error.message==="Backoff in progress.")){throw error}}}return}var pc=_this._mediaHandler.version.pc;var isIceDisconnected=pc&&pc.iceConnectionState==="disconnected";var hasLowBytesWarning=_this._monitor.hasActiveWarning("bytesSent","min")||_this._monitor.hasActiveWarning("bytesReceived","min");if(type===LowBytes&&isIceDisconnected||type===ConnectionDisconnected&&hasLowBytesWarning||isEndOfIceCycle){var mediaReconnectionError=new generated.MediaErrors.ConnectionError("Media connection failed.");_this._log.warn("ICE Connection disconnected.");_this._publisher.warn("connection","error",mediaReconnectionError,_this);_this._publisher.info("connection","reconnecting",null,_this);_this._mediaReconnectStartTime=Date.now();_this._status=Call.State.Reconnecting;_this._mediaStatus=Call.State.Reconnecting;_this._mediaReconnectBackoff.reset();_this._mediaReconnectBackoff.backoff();_this._log.debug("#reconnecting");_this.emit("reconnecting",mediaReconnectionError)}};_this._onMediaReconnected=function(){if(_this._mediaStatus!==Call.State.Reconnecting){return}_this._log.info("ICE Connection reestablished.");_this._mediaStatus=Call.State.Open;if(_this._signalingStatus===Call.State.Open){_this._publisher.info("connection","reconnected",null,_this);_this._log.debug("#reconnected");_this.emit("reconnected");_this._status=Call.State.Open}};_this._onMessageReceived=function(payload){var callsid=payload.callsid,content=payload.content,contenttype=payload.contenttype,messagetype=payload.messagetype,voiceeventsid=payload.voiceeventsid;if(_this.parameters.CallSid!==callsid){_this._log.warn("Received a message from a different callsid: ".concat(callsid));return}var data={content:content,contentType:contenttype,messageType:messagetype,voiceEventSid:voiceeventsid};_this._publisher.info("call-message",messagetype,{content_type:contenttype,event_type:"received",voice_event_sid:voiceeventsid},_this);_this._log.debug("#messageReceived",JSON.stringify(data));_this.emit("messageReceived",data)};_this._onMessageSent=function(voiceEventSid){if(!_this._messages.has(voiceEventSid)){_this._log.warn("Received a messageSent with a voiceEventSid that doesn't exists: ".concat(voiceEventSid));return}var message=_this._messages.get(voiceEventSid);_this._messages.delete(voiceEventSid);_this._publisher.info("call-message",message===null||message===void 0?void 0:message.messageType,{content_type:message===null||message===void 0?void 0:message.contentType,event_type:"sent",voice_event_sid:voiceEventSid},_this);_this._log.debug("#messageSent",JSON.stringify(message));_this.emit("messageSent",message)};_this._onRinging=function(payload){_this._setCallSid(payload);if(_this._status!==Call.State.Connecting&&_this._status!==Call.State.Ringing){return}var hasEarlyMedia=!!payload.sdp;_this._status=Call.State.Ringing;_this._publisher.info("connection","outgoing-ringing",{hasEarlyMedia:hasEarlyMedia},_this);_this._log.debug("#ringing");_this.emit("ringing",hasEarlyMedia)};_this._onRTCSample=function(sample){var callMetrics=tslib.__assign(tslib.__assign({},sample),{inputVolume:_this._latestInputVolume,outputVolume:_this._latestOutputVolume});_this._codec=callMetrics.codecName;_this._metricsSamples.push(callMetrics);if(_this._metricsSamples.length>=METRICS_BATCH_SIZE){_this._publishMetrics()}_this.emit("sample",sample)};_this._onSignalingError=function(payload){var callsid=payload.callsid,voiceeventsid=payload.voiceeventsid,error=payload.error;if(_this.parameters.CallSid!==callsid){_this._log.warn("Received an error from a different callsid: ".concat(callsid));return}if(voiceeventsid&&_this._messages.has(voiceeventsid)){_this._messages.delete(voiceeventsid);_this._log.warn("Received an error while sending a message.",payload);_this._publisher.error("call-message","error",{code:error.code,message:error.message,voice_event_sid:voiceeventsid},_this);var twilioError=void 0;var errorConstructor=index.getPreciseSignalingErrorByCode(!!_this._options.enableImprovedSignalingErrorPrecision,error.code);if(typeof errorConstructor!=="undefined"){twilioError=new errorConstructor(error)}if(!twilioError){_this._log.error("Unknown Call Message Error: ",error);twilioError=new generated.GeneralErrors.UnknownError(error.message,error)}_this._log.debug("#error",error,twilioError);_this.emit("error",twilioError)}};_this._onSignalingReconnected=function(){if(_this._signalingStatus!==Call.State.Reconnecting){return}_this._log.info("Signaling Connection reestablished.");_this._signalingStatus=Call.State.Open;if(_this._mediaStatus===Call.State.Open){_this._publisher.info("connection","reconnected",null,_this);_this._log.debug("#reconnected");_this.emit("reconnected");_this._status=Call.State.Open}};_this._onTransportClose=function(){_this._log.error("Received transportClose from pstream");_this._log.debug("#transportClose");_this.emit("transportClose");if(_this._signalingReconnectToken){_this._status=Call.State.Reconnecting;_this._signalingStatus=Call.State.Reconnecting;_this._publisher.info("connection","reconnecting",null,_this);_this._log.debug("#reconnecting");_this.emit("reconnecting",new generated.SignalingErrors.ConnectionDisconnected)}else{_this._status=Call.State.Closed;_this._signalingStatus=Call.State.Closed}};_this._reemitWarning=function(warningData,wasCleared){var groupPrefix=/^audio/.test(warningData.name)?"audio-level-":"network-quality-";var warningPrefix=WARNING_PREFIXES[warningData.threshold.name];var warningName;if(warningData.name in MULTIPLE_THRESHOLD_WARNING_NAMES){warningName=MULTIPLE_THRESHOLD_WARNING_NAMES[warningData.name][warningData.threshold.name]}else if(warningData.name in WARNING_NAMES){warningName=WARNING_NAMES[warningData.name]}var warning=warningPrefix+warningName;_this._emitWarning(groupPrefix,warning,warningData.threshold.value,warningData.values||warningData.value,wasCleared,warningData)};_this._reemitWarningCleared=function(warningData){_this._reemitWarning(warningData,true)};_this._soundcache=config.soundcache;if(typeof config.onIgnore==="function"){_this._onIgnore=config.onIgnore}var message=options&&options.twimlParams||{};_this.customParameters=new Map(Object.entries(message).map(function(_a){var key=_a[0],val=_a[1];return[key,String(val)]}));Object.assign(_this._options,options);if(_this._options.callParameters){_this.parameters=_this._options.callParameters}if(_this._options.reconnectToken){_this._signalingReconnectToken=_this._options.reconnectToken}_this._voiceEventSidGenerator=_this._options.voiceEventSidGenerator||sid.generateVoiceEventSid;_this._direction=_this.parameters.CallSid&&!_this._options.reconnectCallSid?Call.CallDirection.Incoming:Call.CallDirection.Outgoing;if(_this.parameters){_this.callerInfo=_this.parameters.StirStatus?{isVerified:_this.parameters.StirStatus==="TN-Validation-Passed-A"}:null}else{_this.callerInfo=null}_this._mediaReconnectBackoff=new backoff.default(BACKOFF_CONFIG);_this._mediaReconnectBackoff.on("ready",function(){return _this._mediaHandler.iceRestart()});_this.outboundConnectionId=generateTempCallSid();var publisher=_this._publisher=config.publisher;if(_this._direction===Call.CallDirection.Incoming){publisher.info("connection","incoming",null,_this)}else{publisher.info("connection","outgoing",{preflight:_this._options.preflight,reconnect:!!_this._options.reconnectCallSid},_this)}var monitor=_this._monitor=new(_this._options.StatsMonitor||statsMonitor.default);monitor.on("sample",_this._onRTCSample);monitor.disableWarnings();setTimeout(function(){return monitor.enableWarnings()},METRICS_DELAY);monitor.on("warning",function(data,wasCleared){if(data.name==="bytesSent"||data.name==="bytesReceived"){_this._onMediaFailure(Call.MediaFailure.LowBytes)}_this._reemitWarning(data,wasCleared)});monitor.on("warning-cleared",function(data){_this._reemitWarningCleared(data)});_this._mediaHandler=new _this._options.MediaHandler(config.audioHelper,config.pstream,{MediaStream:_this._options.MediaStream,RTCPeerConnection:_this._options.RTCPeerConnection,codecPreferences:_this._options.codecPreferences,dscp:_this._options.dscp,forceAggressiveIceNomination:_this._options.forceAggressiveIceNomination,maxAverageBitrate:_this._options.maxAverageBitrate});_this.on("volume",function(inputVolume,outputVolume){_this._inputVolumeStreak=_this._checkVolume(inputVolume,_this._inputVolumeStreak,_this._latestInputVolume,"input");_this._outputVolumeStreak=_this._checkVolume(outputVolume,_this._outputVolumeStreak,_this._latestOutputVolume,"output");_this._latestInputVolume=inputVolume;_this._latestOutputVolume=outputVolume});_this._mediaHandler.onaudio=function(remoteAudio){_this._log.debug("#audio");_this.emit("audio",remoteAudio)};_this._mediaHandler.onvolume=function(inputVolume,outputVolume,internalInputVolume,internalOutputVolume){monitor.addVolumes(internalInputVolume/255*32767,internalOutputVolume/255*32767);_this.emit("volume",inputVolume,outputVolume)};_this._mediaHandler.ondtlstransportstatechange=function(state){var level=state==="failed"?"error":"debug";_this._publisher.post(level,"dtls-transport-state",state,null,_this)};_this._mediaHandler.onpcconnectionstatechange=function(state){var level="debug";var dtlsTransport=_this._mediaHandler.getRTCDtlsTra