@flashphoner/websdk 2.0.268 → 2.0.271

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.
@@ -9,4 +9,4 @@
9
9
  * @license MIT License
10
10
  * @preserve
11
11
  */
12
- var KalmanFilter=function(){function KalmanFilter(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},_ref$R=_ref.R,R=void 0===_ref$R?1:_ref$R,_ref$Q=_ref.Q,Q=void 0===_ref$Q?1:_ref$Q,_ref$A=_ref.A,A=void 0===_ref$A?1:_ref$A,_ref$B=_ref.B,B=void 0===_ref$B?0:_ref$B,_ref$C=_ref.C,C=void 0===_ref$C?1:_ref$C;_classCallCheck(this,KalmanFilter),this.R=R,this.Q=Q,this.A=A,this.C=C,this.B=B,this.cov=NaN,this.x=NaN}var Constructor,protoProps,staticProps;return Constructor=KalmanFilter,(protoProps=[{key:"filter",value:function(z){var u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(isNaN(this.x))this.x=1/this.C*z,this.cov=1/this.C*this.Q*(1/this.C);else{var predX=this.predict(u),predCov=this.uncertainty(),K=predCov*this.C*(1/(this.C*predCov*this.C+this.Q));this.x=predX+K*(z-this.C*predX),this.cov=predCov-K*this.C*predCov}return this.x}},{key:"predict",value:function(){var u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return this.A*this.x+this.B*u}},{key:"uncertainty",value:function(){return this.A*this.cov*this.A+this.R}},{key:"lastMeasurement",value:function(){return this.x}},{key:"setMeasurementNoise",value:function(noise){this.Q=noise}},{key:"setProcessNoise",value:function(noise){this.R=noise}}])&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),KalmanFilter}();module.exports=KalmanFilter},{}],3:[function(require,module,exports){var cachedSetTimeout,cachedClearTimeout,process=module.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var currentQueue,queue=[],draining=!1,queueIndex=-1;function cleanUpNextTick(){draining&&currentQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,function(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(name){return[]},process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],4:[function(require,module,exports){(function(setImmediate){(function(){function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}!function(root){var setTimeoutFunc=setTimeout;function noop(){}function Promise(fn){if(!(this instanceof Promise))throw new TypeError("Promises must be constructed via new");if("function"!=typeof fn)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],doResolve(fn,this)}function handle(self,deferred){for(;3===self._state;)self=self._value;0!==self._state?(self._handled=!0,Promise._immediateFn((function(){var cb=1===self._state?deferred.onFulfilled:deferred.onRejected;if(null!==cb){var ret;try{ret=cb(self._value)}catch(e){return void reject(deferred.promise,e)}resolve(deferred.promise,ret)}else(1===self._state?resolve:reject)(deferred.promise,self._value)}))):self._deferreds.push(deferred)}function resolve(self,newValue){try{if(newValue===self)throw new TypeError("A promise cannot be resolved with itself.");if(newValue&&("object"===_typeof(newValue)||"function"==typeof newValue)){var then=newValue.then;if(newValue instanceof Promise)return self._state=3,self._value=newValue,void finale(self);if("function"==typeof then)return void doResolve((fn=then,thisArg=newValue,function(){fn.apply(thisArg,arguments)}),self)}self._state=1,self._value=newValue,finale(self)}catch(e){reject(self,e)}var fn,thisArg}function reject(self,newValue){self._state=2,self._value=newValue,finale(self)}function finale(self){2===self._state&&0===self._deferreds.length&&Promise._immediateFn((function(){self._handled||Promise._unhandledRejectionFn(self._value)}));for(var i=0,len=self._deferreds.length;i<len;i++)handle(self,self._deferreds[i]);self._deferreds=null}function Handler(onFulfilled,onRejected,promise){this.onFulfilled="function"==typeof onFulfilled?onFulfilled:null,this.onRejected="function"==typeof onRejected?onRejected:null,this.promise=promise}function doResolve(fn,self){var done=!1;try{fn((function(value){done||(done=!0,resolve(self,value))}),(function(reason){done||(done=!0,reject(self,reason))}))}catch(ex){if(done)return;done=!0,reject(self,ex)}}Promise.prototype.catch=function(onRejected){return this.then(null,onRejected)},Promise.prototype.then=function(onFulfilled,onRejected){var prom=new this.constructor(noop);return handle(this,new Handler(onFulfilled,onRejected,prom)),prom},Promise.all=function(arr){return new Promise((function(resolve,reject){if(!arr||"undefined"==typeof arr.length)throw new TypeError("Promise.all accepts an array");var args=Array.prototype.slice.call(arr);if(0===args.length)return resolve([]);var remaining=args.length;function res(i,val){try{if(val&&("object"===_typeof(val)||"function"==typeof val)){var then=val.then;if("function"==typeof then)return void then.call(val,(function(val){res(i,val)}),reject)}args[i]=val,0==--remaining&&resolve(args)}catch(ex){reject(ex)}}for(var i=0;i<args.length;i++)res(i,args[i])}))},Promise.resolve=function(value){return value&&"object"===_typeof(value)&&value.constructor===Promise?value:new Promise((function(resolve){resolve(value)}))},Promise.reject=function(value){return new Promise((function(resolve,reject){reject(value)}))},Promise.race=function(values){return new Promise((function(resolve,reject){for(var i=0,len=values.length;i<len;i++)values[i].then(resolve,reject)}))},Promise._immediateFn="function"==typeof setImmediate&&function(fn){setImmediate(fn)}||function(fn){setTimeoutFunc(fn,0)},Promise._unhandledRejectionFn=function(err){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",err)},Promise._setImmediateFn=function(fn){Promise._immediateFn=fn},Promise._setUnhandledRejectionFn=function(fn){Promise._unhandledRejectionFn=fn},"undefined"!=typeof module&&module.exports?module.exports=Promise:root.Promise||(root.Promise=Promise)}(this)}).call(this)}).call(this,require("timers").setImmediate)},{timers:7}],5:[function(require,module,exports){"use strict";var SDPUtils=require("sdp");function writeMediaSection(transceiver,caps,type,stream,dtlsRole){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":dtlsRole||"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var trackId=transceiver.rtpSender._initialTrackId||transceiver.rtpSender.track.id;transceiver.rtpSender._initialTrackId=trackId;var msid="msid:"+(stream?stream.id:"-")+" "+trackId+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp}function getCommonCapabilities(localCapabilities,remoteCapabilities){var commonCapabilities={codecs:[],headerExtensions:[],fecMechanisms:[]},findCodecByPayloadType=function(pt,codecs){pt=parseInt(pt,10);for(var i=0;i<codecs.length;i++)if(codecs[i].payloadType===pt||codecs[i].preferredPayloadType===pt)return codecs[i]},rtxCapabilityMatches=function(lRtx,rRtx,lCodecs,rCodecs){var lCodec=findCodecByPayloadType(lRtx.parameters.apt,lCodecs),rCodec=findCodecByPayloadType(rRtx.parameters.apt,rCodecs);return lCodec&&rCodec&&lCodec.name.toLowerCase()===rCodec.name.toLowerCase()};return localCapabilities.codecs.forEach((function(lCodec){for(var i=0;i<remoteCapabilities.codecs.length;i++){var rCodec=remoteCapabilities.codecs[i];if(lCodec.name.toLowerCase()===rCodec.name.toLowerCase()&&lCodec.clockRate===rCodec.clockRate){if("rtx"===lCodec.name.toLowerCase()&&lCodec.parameters&&rCodec.parameters.apt&&!rtxCapabilityMatches(lCodec,rCodec,localCapabilities.codecs,remoteCapabilities.codecs))continue;(rCodec=JSON.parse(JSON.stringify(rCodec))).numChannels=Math.min(lCodec.numChannels,rCodec.numChannels),commonCapabilities.codecs.push(rCodec),rCodec.rtcpFeedback=rCodec.rtcpFeedback.filter((function(fb){for(var j=0;j<lCodec.rtcpFeedback.length;j++)if(lCodec.rtcpFeedback[j].type===fb.type&&lCodec.rtcpFeedback[j].parameter===fb.parameter)return!0;return!1}));break}}})),localCapabilities.headerExtensions.forEach((function(lHeaderExtension){for(var i=0;i<remoteCapabilities.headerExtensions.length;i++){var rHeaderExtension=remoteCapabilities.headerExtensions[i];if(lHeaderExtension.uri===rHeaderExtension.uri){commonCapabilities.headerExtensions.push(rHeaderExtension);break}}})),commonCapabilities}function isActionAllowedInSignalingState(action,type,signalingState){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[type][action].indexOf(signalingState)}function maybeAddCandidate(iceTransport,candidate){var alreadyAdded=iceTransport.getRemoteCandidates().find((function(remoteCandidate){return candidate.foundation===remoteCandidate.foundation&&candidate.ip===remoteCandidate.ip&&candidate.port===remoteCandidate.port&&candidate.priority===remoteCandidate.priority&&candidate.protocol===remoteCandidate.protocol&&candidate.type===remoteCandidate.type}));return alreadyAdded||iceTransport.addRemoteCandidate(candidate),!alreadyAdded}function makeError(name,description){var e=new Error(description);return e.name=name,e.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[name],e}module.exports=function(window,edgeVersion){function addTrackToStreamAndFireEvent(track,stream){stream.addTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("addtrack",{track:track}))}function fireAddTrack(pc,track,receiver,streams){var trackEvent=new Event("track");trackEvent.track=track,trackEvent.receiver=receiver,trackEvent.transceiver={receiver:receiver},trackEvent.streams=streams,window.setTimeout((function(){pc._dispatchEvent("track",trackEvent)}))}var RTCPeerConnection=function(config){var pc=this,_eventTarget=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(method){pc[method]=_eventTarget[method].bind(_eventTarget)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",config=JSON.parse(JSON.stringify(config||{})),this.usingBundle="max-bundle"===config.bundlePolicy,"negotiate"===config.rtcpMuxPolicy)throw makeError("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(config.rtcpMuxPolicy||(config.rtcpMuxPolicy="require"),config.iceTransportPolicy){case"all":case"relay":break;default:config.iceTransportPolicy="all"}switch(config.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:config.bundlePolicy="balanced"}if(config.iceServers=function(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter((function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter((function(url){return 0===url.indexOf("turn:")&&-1!==url.indexOf("transport=udp")&&-1===url.indexOf("turn:[")&&!hasTurn?(hasTurn=!0,!0):0===url.indexOf("stun:")&&edgeVersion>=14393&&-1===url.indexOf("?transport=udp")})),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}}))}(config.iceServers||[],edgeVersion),this._iceGatherers=[],config.iceCandidatePoolSize)for(var i=config.iceCandidatePoolSize;i>0;i--)this._iceGatherers.push(new window.RTCIceGatherer({iceServers:config.iceServers,gatherPolicy:config.iceTransportPolicy}));else config.iceCandidatePoolSize=0;this._config=config,this.transceivers=[],this._sdpSessionId=SDPUtils.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(RTCPeerConnection.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(RTCPeerConnection.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),RTCPeerConnection.prototype.onicecandidate=null,RTCPeerConnection.prototype.onaddstream=null,RTCPeerConnection.prototype.ontrack=null,RTCPeerConnection.prototype.onremovestream=null,RTCPeerConnection.prototype.onsignalingstatechange=null,RTCPeerConnection.prototype.oniceconnectionstatechange=null,RTCPeerConnection.prototype.onconnectionstatechange=null,RTCPeerConnection.prototype.onicegatheringstatechange=null,RTCPeerConnection.prototype.onnegotiationneeded=null,RTCPeerConnection.prototype.ondatachannel=null,RTCPeerConnection.prototype._dispatchEvent=function(name,event){this._isClosed||(this.dispatchEvent(event),"function"==typeof this["on"+name]&&this["on"+name](event))},RTCPeerConnection.prototype._emitGatheringStateChange=function(){var event=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",event)},RTCPeerConnection.prototype.getConfiguration=function(){return this._config},RTCPeerConnection.prototype.getLocalStreams=function(){return this.localStreams},RTCPeerConnection.prototype.getRemoteStreams=function(){return this.remoteStreams},RTCPeerConnection.prototype._createTransceiver=function(kind,doNotAdd){var hasBundleTransport=this.transceivers.length>0,transceiver={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:kind,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&hasBundleTransport)transceiver.iceTransport=this.transceivers[0].iceTransport,transceiver.dtlsTransport=this.transceivers[0].dtlsTransport;else{var transports=this._createIceAndDtlsTransports();transceiver.iceTransport=transports.iceTransport,transceiver.dtlsTransport=transports.dtlsTransport}return doNotAdd||this.transceivers.push(transceiver),transceiver},RTCPeerConnection.prototype.addTrack=function(track,stream){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var transceiver;if(this.transceivers.find((function(s){return s.track===track})))throw makeError("InvalidAccessError","Track already exists.");for(var i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==track.kind||(transceiver=this.transceivers[i]);return transceiver||(transceiver=this._createTransceiver(track.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(stream)&&this.localStreams.push(stream),transceiver.track=track,transceiver.stream=stream,transceiver.rtpSender=new window.RTCRtpSender(track,transceiver.dtlsTransport),transceiver.rtpSender},RTCPeerConnection.prototype.addStream=function(stream){var pc=this;if(edgeVersion>=15025)stream.getTracks().forEach((function(track){pc.addTrack(track,stream)}));else{var clonedStream=stream.clone();stream.getTracks().forEach((function(track,idx){var clonedTrack=clonedStream.getTracks()[idx];track.addEventListener("enabled",(function(event){clonedTrack.enabled=event.enabled}))})),clonedStream.getTracks().forEach((function(track){pc.addTrack(track,clonedStream)}))}},RTCPeerConnection.prototype.removeTrack=function(sender){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(sender instanceof window.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var transceiver=this.transceivers.find((function(t){return t.rtpSender===sender}));if(!transceiver)throw makeError("InvalidAccessError","Sender was not created by this connection.");var stream=transceiver.stream;transceiver.rtpSender.stop(),transceiver.rtpSender=null,transceiver.track=null,transceiver.stream=null,-1===this.transceivers.map((function(t){return t.stream})).indexOf(stream)&&this.localStreams.indexOf(stream)>-1&&this.localStreams.splice(this.localStreams.indexOf(stream),1),this._maybeFireNegotiationNeeded()},RTCPeerConnection.prototype.removeStream=function(stream){var pc=this;stream.getTracks().forEach((function(track){var sender=pc.getSenders().find((function(s){return s.track===track}));sender&&pc.removeTrack(sender)}))},RTCPeerConnection.prototype.getSenders=function(){return this.transceivers.filter((function(transceiver){return!!transceiver.rtpSender})).map((function(transceiver){return transceiver.rtpSender}))},RTCPeerConnection.prototype.getReceivers=function(){return this.transceivers.filter((function(transceiver){return!!transceiver.rtpReceiver})).map((function(transceiver){return transceiver.rtpReceiver}))},RTCPeerConnection.prototype._createIceGatherer=function(sdpMLineIndex,usingBundle){var pc=this;if(usingBundle&&sdpMLineIndex>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var iceGatherer=new window.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(iceGatherer,"state",{value:"new",writable:!0}),this.transceivers[sdpMLineIndex].bufferedCandidateEvents=[],this.transceivers[sdpMLineIndex].bufferCandidates=function(event){var end=!event.candidate||0===Object.keys(event.candidate).length;iceGatherer.state=end?"completed":"gathering",null!==pc.transceivers[sdpMLineIndex].bufferedCandidateEvents&&pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event)},iceGatherer.addEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer},RTCPeerConnection.prototype._gather=function(mid,sdpMLineIndex){var pc=this,iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;if(!iceGatherer.onlocalcandidate){var bufferedCandidateEvents=this.transceivers[sdpMLineIndex].bufferedCandidateEvents;this.transceivers[sdpMLineIndex].bufferedCandidateEvents=null,iceGatherer.removeEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer.onlocalcandidate=function(evt){if(!(pc.usingBundle&&sdpMLineIndex>0)){var event=new Event("icecandidate");event.candidate={sdpMid:mid,sdpMLineIndex:sdpMLineIndex};var cand=evt.candidate,end=!cand||0===Object.keys(cand).length;if(end)"new"!==iceGatherer.state&&"gathering"!==iceGatherer.state||(iceGatherer.state="completed");else{"new"===iceGatherer.state&&(iceGatherer.state="gathering"),cand.component=1,cand.ufrag=iceGatherer.getLocalParameters().usernameFragment;var serializedCandidate=SDPUtils.writeCandidate(cand);event.candidate=Object.assign(event.candidate,SDPUtils.parseCandidate(serializedCandidate)),event.candidate.candidate=serializedCandidate,event.candidate.toJSON=function(){return{candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex,usernameFragment:event.candidate.usernameFragment}}}var sections=SDPUtils.getMediaSections(pc._localDescription.sdp);sections[event.candidate.sdpMLineIndex]+=end?"a=end-of-candidates\r\n":"a="+event.candidate.candidate+"\r\n",pc._localDescription.sdp=SDPUtils.getDescription(pc._localDescription.sdp)+sections.join("");var complete=pc.transceivers.every((function(transceiver){return transceiver.iceGatherer&&"completed"===transceiver.iceGatherer.state}));"gathering"!==pc.iceGatheringState&&(pc.iceGatheringState="gathering",pc._emitGatheringStateChange()),end||pc._dispatchEvent("icecandidate",event),complete&&(pc._dispatchEvent("icecandidate",new Event("icecandidate")),pc.iceGatheringState="complete",pc._emitGatheringStateChange())}},window.setTimeout((function(){bufferedCandidateEvents.forEach((function(e){iceGatherer.onlocalcandidate(e)}))}),0)}},RTCPeerConnection.prototype._createIceAndDtlsTransports=function(){var pc=this,iceTransport=new window.RTCIceTransport(null);iceTransport.onicestatechange=function(){pc._updateIceConnectionState(),pc._updateConnectionState()};var dtlsTransport=new window.RTCDtlsTransport(iceTransport);return dtlsTransport.ondtlsstatechange=function(){pc._updateConnectionState()},dtlsTransport.onerror=function(){Object.defineProperty(dtlsTransport,"state",{value:"failed",writable:!0}),pc._updateConnectionState()},{iceTransport:iceTransport,dtlsTransport:dtlsTransport}},RTCPeerConnection.prototype._disposeIceAndDtlsTransports=function(sdpMLineIndex){var iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;iceGatherer&&(delete iceGatherer.onlocalcandidate,delete this.transceivers[sdpMLineIndex].iceGatherer);var iceTransport=this.transceivers[sdpMLineIndex].iceTransport;iceTransport&&(delete iceTransport.onicestatechange,delete this.transceivers[sdpMLineIndex].iceTransport);var dtlsTransport=this.transceivers[sdpMLineIndex].dtlsTransport;dtlsTransport&&(delete dtlsTransport.ondtlsstatechange,delete dtlsTransport.onerror,delete this.transceivers[sdpMLineIndex].dtlsTransport)},RTCPeerConnection.prototype._transceive=function(transceiver,send,recv){var params=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);send&&transceiver.rtpSender&&(params.encodings=transceiver.sendEncodingParameters,params.rtcp={cname:SDPUtils.localCName,compound:transceiver.rtcpParameters.compound},transceiver.recvEncodingParameters.length&&(params.rtcp.ssrc=transceiver.recvEncodingParameters[0].ssrc),transceiver.rtpSender.send(params)),recv&&transceiver.rtpReceiver&&params.codecs.length>0&&("video"===transceiver.kind&&transceiver.recvEncodingParameters&&edgeVersion<15019&&transceiver.recvEncodingParameters.forEach((function(p){delete p.rtx})),transceiver.recvEncodingParameters.length?params.encodings=transceiver.recvEncodingParameters:params.encodings=[{}],params.rtcp={compound:transceiver.rtcpParameters.compound},transceiver.rtcpParameters.cname&&(params.rtcp.cname=transceiver.rtcpParameters.cname),transceiver.sendEncodingParameters.length&&(params.rtcp.ssrc=transceiver.sendEncodingParameters[0].ssrc),transceiver.rtpReceiver.receive(params))},RTCPeerConnection.prototype.setLocalDescription=function(description){var sections,sessionpart,pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setLocalDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set local "+description.type+" in state "+pc.signalingState));if("offer"===description.type)sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),sections.forEach((function(mediaSection,sdpMLineIndex){var caps=SDPUtils.parseRtpParameters(mediaSection);pc.transceivers[sdpMLineIndex].localCapabilities=caps})),pc.transceivers.forEach((function(transceiver,sdpMLineIndex){pc._gather(transceiver.mid,sdpMLineIndex)}));else if("answer"===description.type){sections=SDPUtils.splitSections(pc._remoteDescription.sdp),sessionpart=sections.shift();var isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0;sections.forEach((function(mediaSection,sdpMLineIndex){var transceiver=pc.transceivers[sdpMLineIndex],iceGatherer=transceiver.iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,localCapabilities=transceiver.localCapabilities,remoteCapabilities=transceiver.remoteCapabilities;if(!(SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length)&&!transceiver.rejected){var remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart);isIceLite&&(remoteDtlsParameters.role="server"),pc.usingBundle&&0!==sdpMLineIndex||(pc._gather(transceiver.mid,sdpMLineIndex),"new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,isIceLite?"controlling":"controlled"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters));var params=getCommonCapabilities(localCapabilities,remoteCapabilities);pc._transceive(transceiver,params.codecs.length>0,!1)}}))}return pc._localDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-local-offer"):pc._updateSignalingState("stable"),Promise.resolve()},RTCPeerConnection.prototype.setRemoteDescription=function(description){var pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setRemoteDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set remote "+description.type+" in state "+pc.signalingState));var streams={};pc.remoteStreams.forEach((function(stream){streams[stream.id]=stream}));var receiverList=[],sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0,usingBundle=SDPUtils.matchPrefix(sessionpart,"a=group:BUNDLE ").length>0;pc.usingBundle=usingBundle;var iceOptions=SDPUtils.matchPrefix(sessionpart,"a=ice-options:")[0];return pc.canTrickleIceCandidates=!!iceOptions&&iceOptions.substr(14).split(" ").indexOf("trickle")>=0,sections.forEach((function(mediaSection,sdpMLineIndex){var lines=SDPUtils.splitLines(mediaSection),kind=SDPUtils.getKind(mediaSection),rejected=SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length,protocol=lines[0].substr(2).split(" ")[2],direction=SDPUtils.getDirection(mediaSection,sessionpart),remoteMsid=SDPUtils.parseMsid(mediaSection),mid=SDPUtils.getMid(mediaSection)||SDPUtils.generateIdentifier();if(rejected||"application"===kind&&("DTLS/SCTP"===protocol||"UDP/DTLS/SCTP"===protocol))pc.transceivers[sdpMLineIndex]={mid:mid,kind:kind,protocol:protocol,rejected:!0};else{var transceiver,iceGatherer,iceTransport,dtlsTransport,rtpReceiver,sendEncodingParameters,recvEncodingParameters,localCapabilities,track;!rejected&&pc.transceivers[sdpMLineIndex]&&pc.transceivers[sdpMLineIndex].rejected&&(pc.transceivers[sdpMLineIndex]=pc._createTransceiver(kind,!0));var remoteIceParameters,remoteDtlsParameters,remoteCapabilities=SDPUtils.parseRtpParameters(mediaSection);rejected||(remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),(remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart)).role="client"),recvEncodingParameters=SDPUtils.parseRtpEncodingParameters(mediaSection);var rtcpParameters=SDPUtils.parseRtcpParameters(mediaSection),isComplete=SDPUtils.matchPrefix(mediaSection,"a=end-of-candidates",sessionpart).length>0,cands=SDPUtils.matchPrefix(mediaSection,"a=candidate:").map((function(cand){return SDPUtils.parseCandidate(cand)})).filter((function(cand){return 1===cand.component}));if(("offer"===description.type||"answer"===description.type)&&!rejected&&usingBundle&&sdpMLineIndex>0&&pc.transceivers[sdpMLineIndex]&&(pc._disposeIceAndDtlsTransports(sdpMLineIndex),pc.transceivers[sdpMLineIndex].iceGatherer=pc.transceivers[0].iceGatherer,pc.transceivers[sdpMLineIndex].iceTransport=pc.transceivers[0].iceTransport,pc.transceivers[sdpMLineIndex].dtlsTransport=pc.transceivers[0].dtlsTransport,pc.transceivers[sdpMLineIndex].rtpSender&&pc.transceivers[sdpMLineIndex].rtpSender.setTransport(pc.transceivers[0].dtlsTransport),pc.transceivers[sdpMLineIndex].rtpReceiver&&pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(pc.transceivers[0].dtlsTransport)),"offer"!==description.type||rejected){if("answer"===description.type&&!rejected){iceGatherer=(transceiver=pc.transceivers[sdpMLineIndex]).iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,rtpReceiver=transceiver.rtpReceiver,sendEncodingParameters=transceiver.sendEncodingParameters,localCapabilities=transceiver.localCapabilities,pc.transceivers[sdpMLineIndex].recvEncodingParameters=recvEncodingParameters,pc.transceivers[sdpMLineIndex].remoteCapabilities=remoteCapabilities,pc.transceivers[sdpMLineIndex].rtcpParameters=rtcpParameters,cands.length&&"new"===iceTransport.state&&(!isIceLite&&!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach((function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})):iceTransport.setRemoteCandidates(cands)),usingBundle&&0!==sdpMLineIndex||("new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,"controlling"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters)),!getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities).codecs.filter((function(c){return"rtx"===c.name.toLowerCase()})).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,pc._transceive(transceiver,"sendrecv"===direction||"recvonly"===direction,"sendrecv"===direction||"sendonly"===direction),!rtpReceiver||"sendrecv"!==direction&&"sendonly"!==direction?delete transceiver.rtpReceiver:(track=rtpReceiver.track,remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams[remoteMsid.stream]),receiverList.push([track,rtpReceiver,streams[remoteMsid.stream]])):(streams.default||(streams.default=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams.default),receiverList.push([track,rtpReceiver,streams.default])))}}else{(transceiver=pc.transceivers[sdpMLineIndex]||pc._createTransceiver(kind)).mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,usingBundle)),cands.length&&"new"===transceiver.iceTransport.state&&(!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach((function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})):transceiver.iceTransport.setRemoteCandidates(cands)),localCapabilities=window.RTCRtpReceiver.getCapabilities(kind),edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter((function(codec){return"rtx"!==codec.name}))),sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+2)}];var stream,isNewTrack=!1;if("sendrecv"===direction||"sendonly"===direction){if(isNewTrack=!transceiver.rtpReceiver,rtpReceiver=transceiver.rtpReceiver||new window.RTCRtpReceiver(transceiver.dtlsTransport,kind),isNewTrack)track=rtpReceiver.track,remoteMsid&&"-"===remoteMsid.stream||(remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream,Object.defineProperty(streams[remoteMsid.stream],"id",{get:function(){return remoteMsid.stream}})),Object.defineProperty(track,"id",{get:function(){return remoteMsid.track}}),stream=streams[remoteMsid.stream]):(streams.default||(streams.default=new window.MediaStream),stream=streams.default)),stream&&(addTrackToStreamAndFireEvent(track,stream),transceiver.associatedRemoteMediaStreams.push(stream)),receiverList.push([track,rtpReceiver,stream])}else transceiver.rtpReceiver&&transceiver.rtpReceiver.track&&(transceiver.associatedRemoteMediaStreams.forEach((function(s){var nativeTrack=s.getTracks().find((function(t){return t.id===transceiver.rtpReceiver.track.id}));nativeTrack&&function(track,stream){stream.removeTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("removetrack",{track:track}))}(nativeTrack,s)})),transceiver.associatedRemoteMediaStreams=[]);transceiver.localCapabilities=localCapabilities,transceiver.remoteCapabilities=remoteCapabilities,transceiver.rtpReceiver=rtpReceiver,transceiver.rtcpParameters=rtcpParameters,transceiver.sendEncodingParameters=sendEncodingParameters,transceiver.recvEncodingParameters=recvEncodingParameters,pc._transceive(pc.transceivers[sdpMLineIndex],!1,isNewTrack)}}})),void 0===pc._dtlsRole&&(pc._dtlsRole="offer"===description.type?"active":"passive"),pc._remoteDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-remote-offer"):pc._updateSignalingState("stable"),Object.keys(streams).forEach((function(sid){var stream=streams[sid];if(stream.getTracks().length){if(-1===pc.remoteStreams.indexOf(stream)){pc.remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,window.setTimeout((function(){pc._dispatchEvent("addstream",event)}))}receiverList.forEach((function(item){var track=item[0],receiver=item[1];stream.id===item[2].id&&fireAddTrack(pc,track,receiver,[stream])}))}})),receiverList.forEach((function(item){item[2]||fireAddTrack(pc,item[0],item[1],[])})),window.setTimeout((function(){pc&&pc.transceivers&&pc.transceivers.forEach((function(transceiver){transceiver.iceTransport&&"new"===transceiver.iceTransport.state&&transceiver.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),transceiver.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},RTCPeerConnection.prototype.close=function(){this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&transceiver.iceTransport.stop(),transceiver.dtlsTransport&&transceiver.dtlsTransport.stop(),transceiver.rtpSender&&transceiver.rtpSender.stop(),transceiver.rtpReceiver&&transceiver.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},RTCPeerConnection.prototype._updateSignalingState=function(newState){this.signalingState=newState;var event=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",event)},RTCPeerConnection.prototype._maybeFireNegotiationNeeded=function(){var pc=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,window.setTimeout((function(){if(pc.needNegotiation){pc.needNegotiation=!1;var event=new Event("negotiationneeded");pc._dispatchEvent("negotiationneeded",event)}}),0))},RTCPeerConnection.prototype._updateIceConnectionState=function(){var newState,states={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&!transceiver.rejected&&states[transceiver.iceTransport.state]++})),newState="new",states.failed>0?newState="failed":states.checking>0?newState="checking":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0?newState="connected":states.completed>0&&(newState="completed"),newState!==this.iceConnectionState){this.iceConnectionState=newState;var event=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",event)}},RTCPeerConnection.prototype._updateConnectionState=function(){var newState,states={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&transceiver.dtlsTransport&&!transceiver.rejected&&(states[transceiver.iceTransport.state]++,states[transceiver.dtlsTransport.state]++)})),states.connected+=states.completed,newState="new",states.failed>0?newState="failed":states.connecting>0?newState="connecting":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0&&(newState="connected"),newState!==this.connectionState){this.connectionState=newState;var event=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",event)}},RTCPeerConnection.prototype.createOffer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createOffer after close"));var numAudioTracks=pc.transceivers.filter((function(t){return"audio"===t.kind})).length,numVideoTracks=pc.transceivers.filter((function(t){return"video"===t.kind})).length,offerOptions=arguments[0];if(offerOptions){if(offerOptions.mandatory||offerOptions.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==offerOptions.offerToReceiveAudio&&(numAudioTracks=!0===offerOptions.offerToReceiveAudio?1:!1===offerOptions.offerToReceiveAudio?0:offerOptions.offerToReceiveAudio),void 0!==offerOptions.offerToReceiveVideo&&(numVideoTracks=!0===offerOptions.offerToReceiveVideo?1:!1===offerOptions.offerToReceiveVideo?0:offerOptions.offerToReceiveVideo)}for(pc.transceivers.forEach((function(transceiver){"audio"===transceiver.kind?--numAudioTracks<0&&(transceiver.wantReceive=!1):"video"===transceiver.kind&&--numVideoTracks<0&&(transceiver.wantReceive=!1)}));numAudioTracks>0||numVideoTracks>0;)numAudioTracks>0&&(pc._createTransceiver("audio"),numAudioTracks--),numVideoTracks>0&&(pc._createTransceiver("video"),numVideoTracks--);var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.transceivers.forEach((function(transceiver,sdpMLineIndex){var track=transceiver.track,kind=transceiver.kind,mid=transceiver.mid||SDPUtils.generateIdentifier();transceiver.mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,pc.usingBundle));var localCapabilities=window.RTCRtpSender.getCapabilities(kind);edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter((function(codec){return"rtx"!==codec.name}))),localCapabilities.codecs.forEach((function(codec){"H264"===codec.name&&void 0===codec.parameters["level-asymmetry-allowed"]&&(codec.parameters["level-asymmetry-allowed"]="1"),transceiver.remoteCapabilities&&transceiver.remoteCapabilities.codecs&&transceiver.remoteCapabilities.codecs.forEach((function(remoteCodec){codec.name.toLowerCase()===remoteCodec.name.toLowerCase()&&codec.clockRate===remoteCodec.clockRate&&(codec.preferredPayloadType=remoteCodec.payloadType)}))})),localCapabilities.headerExtensions.forEach((function(hdrExt){(transceiver.remoteCapabilities&&transceiver.remoteCapabilities.headerExtensions||[]).forEach((function(rHdrExt){hdrExt.uri===rHdrExt.uri&&(hdrExt.id=rHdrExt.id)}))}));var sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+1)}];track&&edgeVersion>=15019&&"video"===kind&&!sendEncodingParameters[0].rtx&&(sendEncodingParameters[0].rtx={ssrc:sendEncodingParameters[0].ssrc+1}),transceiver.wantReceive&&(transceiver.rtpReceiver=new window.RTCRtpReceiver(transceiver.dtlsTransport,kind)),transceiver.localCapabilities=localCapabilities,transceiver.sendEncodingParameters=sendEncodingParameters})),"max-compat"!==pc._config.bundlePolicy&&(sdp+="a=group:BUNDLE "+pc.transceivers.map((function(t){return t.mid})).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n",pc.transceivers.forEach((function(transceiver,sdpMLineIndex){sdp+=writeMediaSection(transceiver,transceiver.localCapabilities,"offer",transceiver.stream,pc._dtlsRole),sdp+="a=rtcp-rsize\r\n",!transceiver.iceGatherer||"new"===pc.iceGatheringState||0!==sdpMLineIndex&&pc.usingBundle||(transceiver.iceGatherer.getLocalCandidates().forEach((function(cand){cand.component=1,sdp+="a="+SDPUtils.writeCandidate(cand)+"\r\n"})),"completed"===transceiver.iceGatherer.state&&(sdp+="a=end-of-candidates\r\n"))}));var desc=new window.RTCSessionDescription({type:"offer",sdp:sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.createAnswer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==pc.signalingState&&"have-local-pranswer"!==pc.signalingState)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer in signalingState "+pc.signalingState));var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.usingBundle&&(sdp+="a=group:BUNDLE "+pc.transceivers.map((function(t){return t.mid})).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n";var mediaSectionsInOffer=SDPUtils.getMediaSections(pc._remoteDescription.sdp).length;pc.transceivers.forEach((function(transceiver,sdpMLineIndex){if(!(sdpMLineIndex+1>mediaSectionsInOffer)){if(transceiver.rejected)return"application"===transceiver.kind?"DTLS/SCTP"===transceiver.protocol?sdp+="m=application 0 DTLS/SCTP 5000\r\n":sdp+="m=application 0 "+transceiver.protocol+" webrtc-datachannel\r\n":"audio"===transceiver.kind?sdp+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===transceiver.kind&&(sdp+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(sdp+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+transceiver.mid+"\r\n");var localTrack;if(transceiver.stream)"audio"===transceiver.kind?localTrack=transceiver.stream.getAudioTracks()[0]:"video"===transceiver.kind&&(localTrack=transceiver.stream.getVideoTracks()[0]),localTrack&&edgeVersion>=15019&&"video"===transceiver.kind&&!transceiver.sendEncodingParameters[0].rtx&&(transceiver.sendEncodingParameters[0].rtx={ssrc:transceiver.sendEncodingParameters[0].ssrc+1});var commonCapabilities=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);!commonCapabilities.codecs.filter((function(c){return"rtx"===c.name.toLowerCase()})).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,sdp+=writeMediaSection(transceiver,commonCapabilities,"answer",transceiver.stream,pc._dtlsRole),transceiver.rtcpParameters&&transceiver.rtcpParameters.reducedSize&&(sdp+="a=rtcp-rsize\r\n")}}));var desc=new window.RTCSessionDescription({type:"answer",sdp:sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.addIceCandidate=function(candidate){var sections,pc=this;return candidate&&void 0===candidate.sdpMLineIndex&&!candidate.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(resolve,reject){if(!pc._remoteDescription)return reject(makeError("InvalidStateError","Can not add ICE candidate without a remote description"));if(candidate&&""!==candidate.candidate){var sdpMLineIndex=candidate.sdpMLineIndex;if(candidate.sdpMid)for(var i=0;i<pc.transceivers.length;i++)if(pc.transceivers[i].mid===candidate.sdpMid){sdpMLineIndex=i;break}var transceiver=pc.transceivers[sdpMLineIndex];if(!transceiver)return reject(makeError("OperationError","Can not add ICE candidate"));if(transceiver.rejected)return resolve();var cand=Object.keys(candidate.candidate).length>0?SDPUtils.parseCandidate(candidate.candidate):{};if("tcp"===cand.protocol&&(0===cand.port||9===cand.port))return resolve();if(cand.component&&1!==cand.component)return resolve();if((0===sdpMLineIndex||sdpMLineIndex>0&&transceiver.iceTransport!==pc.transceivers[0].iceTransport)&&!maybeAddCandidate(transceiver.iceTransport,cand))return reject(makeError("OperationError","Can not add ICE candidate"));var candidateString=candidate.candidate.trim();0===candidateString.indexOf("a=")&&(candidateString=candidateString.substr(2)),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[sdpMLineIndex]+="a="+(cand.type?candidateString:"end-of-candidates")+"\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join("")}else for(var j=0;j<pc.transceivers.length&&(pc.transceivers[j].rejected||(pc.transceivers[j].iceTransport.addRemoteCandidate({}),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[j]+="a=end-of-candidates\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join(""),!pc.usingBundle));j++);resolve()}))},RTCPeerConnection.prototype.getStats=function(selector){if(selector&&selector instanceof window.MediaStreamTrack){var senderOrReceiver=null;if(this.transceivers.forEach((function(transceiver){transceiver.rtpSender&&transceiver.rtpSender.track===selector?senderOrReceiver=transceiver.rtpSender:transceiver.rtpReceiver&&transceiver.rtpReceiver.track===selector&&(senderOrReceiver=transceiver.rtpReceiver)})),!senderOrReceiver)throw makeError("InvalidAccessError","Invalid selector.");return senderOrReceiver.getStats()}var promises=[];return this.transceivers.forEach((function(transceiver){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(method){transceiver[method]&&promises.push(transceiver[method].getStats())}))})),Promise.all(promises).then((function(allStats){var results=new Map;return allStats.forEach((function(stats){stats.forEach((function(stat){results.set(stat.id,stat)}))})),results}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(ortcObjectName){var obj=window[ortcObjectName];if(obj&&obj.prototype&&obj.prototype.getStats){var nativeGetstats=obj.prototype.getStats;obj.prototype.getStats=function(){return nativeGetstats.apply(this).then((function(nativeStats){var mapStats=new Map;return Object.keys(nativeStats).forEach((function(id){var stat;nativeStats[id].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(stat=nativeStats[id]).type]||stat.type,mapStats.set(id,nativeStats[id])})),mapStats}))}}}));var methods=["createOffer","createAnswer"];return methods.forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[0]||"function"==typeof args[1]?nativeMethod.apply(this,[arguments[2]]).then((function(description){"function"==typeof args[0]&&args[0].apply(null,[description])}),(function(error){"function"==typeof args[1]&&args[1].apply(null,[error])})):nativeMethod.apply(this,arguments)}})),(methods=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]||"function"==typeof args[2]?nativeMethod.apply(this,arguments).then((function(){"function"==typeof args[1]&&args[1].apply(null)}),(function(error){"function"==typeof args[2]&&args[2].apply(null,[error])})):nativeMethod.apply(this,arguments)}})),["getStats"].forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]?nativeMethod.apply(this,arguments).then((function(){"function"==typeof args[1]&&args[1].apply(null)})):nativeMethod.apply(this,arguments)}})),RTCPeerConnection}},{sdp:6}],6:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var SDPUtils={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};SDPUtils.localCName=SDPUtils.generateIdentifier(),SDPUtils.splitLines=function(blob){return blob.trim().split("\n").map((function(line){return line.trim()}))},SDPUtils.splitSections=function(blob){return blob.split("\nm=").map((function(part,index){return(index>0?"m="+part:part).trim()+"\r\n"}))},SDPUtils.getDescription=function(blob){var sections=SDPUtils.splitSections(blob);return sections&&sections[0]},SDPUtils.getMediaSections=function(blob){var sections=SDPUtils.splitSections(blob);return sections.shift(),sections},SDPUtils.matchPrefix=function(blob,prefix){return SDPUtils.splitLines(blob).filter((function(line){return 0===line.indexOf(prefix)}))},SDPUtils.parseCandidate=function(line){for(var parts,candidate={foundation:(parts=0===line.indexOf("a=candidate:")?line.substring(12).split(" "):line.substring(10).split(" "))[0],component:parseInt(parts[1],10),protocol:parts[2].toLowerCase(),priority:parseInt(parts[3],10),ip:parts[4],address:parts[4],port:parseInt(parts[5],10),type:parts[7]},i=8;i<parts.length;i+=2)switch(parts[i]){case"raddr":candidate.relatedAddress=parts[i+1];break;case"rport":candidate.relatedPort=parseInt(parts[i+1],10);break;case"tcptype":candidate.tcpType=parts[i+1];break;case"ufrag":candidate.ufrag=parts[i+1],candidate.usernameFragment=parts[i+1];break;default:candidate[parts[i]]=parts[i+1]}return candidate},SDPUtils.writeCandidate=function(candidate){var sdp=[];sdp.push(candidate.foundation),sdp.push(candidate.component),sdp.push(candidate.protocol.toUpperCase()),sdp.push(candidate.priority),sdp.push(candidate.address||candidate.ip),sdp.push(candidate.port);var type=candidate.type;return sdp.push("typ"),sdp.push(type),"host"!==type&&candidate.relatedAddress&&candidate.relatedPort&&(sdp.push("raddr"),sdp.push(candidate.relatedAddress),sdp.push("rport"),sdp.push(candidate.relatedPort)),candidate.tcpType&&"tcp"===candidate.protocol.toLowerCase()&&(sdp.push("tcptype"),sdp.push(candidate.tcpType)),(candidate.usernameFragment||candidate.ufrag)&&(sdp.push("ufrag"),sdp.push(candidate.usernameFragment||candidate.ufrag)),"candidate:"+sdp.join(" ")},SDPUtils.parseIceOptions=function(line){return line.substr(14).split(" ")},SDPUtils.parseRtpMap=function(line){var parts=line.substr(9).split(" "),parsed={payloadType:parseInt(parts.shift(),10)};return parts=parts[0].split("/"),parsed.name=parts[0],parsed.clockRate=parseInt(parts[1],10),parsed.channels=3===parts.length?parseInt(parts[2],10):1,parsed.numChannels=parsed.channels,parsed},SDPUtils.writeRtpMap=function(codec){var pt=codec.payloadType;void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType);var channels=codec.channels||codec.numChannels||1;return"a=rtpmap:"+pt+" "+codec.name+"/"+codec.clockRate+(1!==channels?"/"+channels:"")+"\r\n"},SDPUtils.parseExtmap=function(line){var parts=line.substr(9).split(" ");return{id:parseInt(parts[0],10),direction:parts[0].indexOf("/")>0?parts[0].split("/")[1]:"sendrecv",uri:parts[1]}},SDPUtils.writeExtmap=function(headerExtension){return"a=extmap:"+(headerExtension.id||headerExtension.preferredId)+(headerExtension.direction&&"sendrecv"!==headerExtension.direction?"/"+headerExtension.direction:"")+" "+headerExtension.uri+"\r\n"},SDPUtils.parseFmtp=function(line){for(var kv,parsed={},parts=line.substr(line.indexOf(" ")+1).split(";"),j=0;j<parts.length;j++)parsed[(kv=parts[j].trim().split("="))[0].trim()]=kv[1];return parsed},SDPUtils.writeFmtp=function(codec){var line="",pt=codec.payloadType;if(void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.parameters&&Object.keys(codec.parameters).length){var params=[];Object.keys(codec.parameters).forEach((function(param){codec.parameters[param]?params.push(param+"="+codec.parameters[param]):params.push(param)})),line+="a=fmtp:"+pt+" "+params.join(";")+"\r\n"}return line},SDPUtils.parseRtcpFb=function(line){var parts=line.substr(line.indexOf(" ")+1).split(" ");return{type:parts.shift(),parameter:parts.join(" ")}},SDPUtils.writeRtcpFb=function(codec){var lines="",pt=codec.payloadType;return void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.rtcpFeedback&&codec.rtcpFeedback.length&&codec.rtcpFeedback.forEach((function(fb){lines+="a=rtcp-fb:"+pt+" "+fb.type+(fb.parameter&&fb.parameter.length?" "+fb.parameter:"")+"\r\n"})),lines},SDPUtils.parseSsrcMedia=function(line){var sp=line.indexOf(" "),parts={ssrc:parseInt(line.substr(7,sp-7),10)},colon=line.indexOf(":",sp);return colon>-1?(parts.attribute=line.substr(sp+1,colon-sp-1),parts.value=line.substr(colon+1)):parts.attribute=line.substr(sp+1),parts},SDPUtils.parseSsrcGroup=function(line){var parts=line.substr(13).split(" ");return{semantics:parts.shift(),ssrcs:parts.map((function(ssrc){return parseInt(ssrc,10)}))}},SDPUtils.getMid=function(mediaSection){var mid=SDPUtils.matchPrefix(mediaSection,"a=mid:")[0];if(mid)return mid.substr(6)},SDPUtils.parseFingerprint=function(line){var parts=line.substr(14).split(" ");return{algorithm:parts[0].toLowerCase(),value:parts[1]}},SDPUtils.getDtlsParameters=function(mediaSection,sessionpart){return{role:"auto",fingerprints:SDPUtils.matchPrefix(mediaSection+sessionpart,"a=fingerprint:").map(SDPUtils.parseFingerprint)}},SDPUtils.writeDtlsParameters=function(params,setupType){var sdp="a=setup:"+setupType+"\r\n";return params.fingerprints.forEach((function(fp){sdp+="a=fingerprint:"+fp.algorithm+" "+fp.value+"\r\n"})),sdp},SDPUtils.parseCryptoLine=function(line){var parts=line.substr(9).split(" ");return{tag:parseInt(parts[0],10),cryptoSuite:parts[1],keyParams:parts[2],sessionParams:parts.slice(3)}},SDPUtils.writeCryptoLine=function(parameters){return"a=crypto:"+parameters.tag+" "+parameters.cryptoSuite+" "+("object"===_typeof(parameters.keyParams)?SDPUtils.writeCryptoKeyParams(parameters.keyParams):parameters.keyParams)+(parameters.sessionParams?" "+parameters.sessionParams.join(" "):"")+"\r\n"},SDPUtils.parseCryptoKeyParams=function(keyParams){if(0!==keyParams.indexOf("inline:"))return null;var parts=keyParams.substr(7).split("|");return{keyMethod:"inline",keySalt:parts[0],lifeTime:parts[1],mkiValue:parts[2]?parts[2].split(":")[0]:void 0,mkiLength:parts[2]?parts[2].split(":")[1]:void 0}},SDPUtils.writeCryptoKeyParams=function(keyParams){return keyParams.keyMethod+":"+keyParams.keySalt+(keyParams.lifeTime?"|"+keyParams.lifeTime:"")+(keyParams.mkiValue&&keyParams.mkiLength?"|"+keyParams.mkiValue+":"+keyParams.mkiLength:"")},SDPUtils.getCryptoParameters=function(mediaSection,sessionpart){return SDPUtils.matchPrefix(mediaSection+sessionpart,"a=crypto:").map(SDPUtils.parseCryptoLine)},SDPUtils.getIceParameters=function(mediaSection,sessionpart){var ufrag=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-ufrag:")[0],pwd=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-pwd:")[0];return ufrag&&pwd?{usernameFragment:ufrag.substr(12),password:pwd.substr(10)}:null},SDPUtils.writeIceParameters=function(params){return"a=ice-ufrag:"+params.usernameFragment+"\r\na=ice-pwd:"+params.password+"\r\n"},SDPUtils.parseRtpParameters=function(mediaSection){for(var description={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},mline=SDPUtils.splitLines(mediaSection)[0].split(" "),i=3;i<mline.length;i++){var pt=mline[i],rtpmapline=SDPUtils.matchPrefix(mediaSection,"a=rtpmap:"+pt+" ")[0];if(rtpmapline){var codec=SDPUtils.parseRtpMap(rtpmapline),fmtps=SDPUtils.matchPrefix(mediaSection,"a=fmtp:"+pt+" ");switch(codec.parameters=fmtps.length?SDPUtils.parseFmtp(fmtps[0]):{},codec.rtcpFeedback=SDPUtils.matchPrefix(mediaSection,"a=rtcp-fb:"+pt+" ").map(SDPUtils.parseRtcpFb),description.codecs.push(codec),codec.name.toUpperCase()){case"RED":case"ULPFEC":description.fecMechanisms.push(codec.name.toUpperCase())}}}return SDPUtils.matchPrefix(mediaSection,"a=extmap:").forEach((function(line){description.headerExtensions.push(SDPUtils.parseExtmap(line))})),description},SDPUtils.writeRtpDescription=function(kind,caps){var sdp="";sdp+="m="+kind+" ",sdp+=caps.codecs.length>0?"9":"0",sdp+=" UDP/TLS/RTP/SAVPF ",sdp+=caps.codecs.map((function(codec){return void 0!==codec.preferredPayloadType?codec.preferredPayloadType:codec.payloadType})).join(" ")+"\r\n",sdp+="c=IN IP4 0.0.0.0\r\n",sdp+="a=rtcp:9 IN IP4 0.0.0.0\r\n",caps.codecs.forEach((function(codec){sdp+=SDPUtils.writeRtpMap(codec),sdp+=SDPUtils.writeFmtp(codec),sdp+=SDPUtils.writeRtcpFb(codec)}));var maxptime=0;return caps.codecs.forEach((function(codec){codec.maxptime>maxptime&&(maxptime=codec.maxptime)})),maxptime>0&&(sdp+="a=maxptime:"+maxptime+"\r\n"),sdp+="a=rtcp-mux\r\n",caps.headerExtensions&&caps.headerExtensions.forEach((function(extension){sdp+=SDPUtils.writeExtmap(extension)})),sdp},SDPUtils.parseRtpEncodingParameters=function(mediaSection){var secondarySsrc,encodingParameters=[],description=SDPUtils.parseRtpParameters(mediaSection),hasRed=-1!==description.fecMechanisms.indexOf("RED"),hasUlpfec=-1!==description.fecMechanisms.indexOf("ULPFEC"),ssrcs=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(parts){return"cname"===parts.attribute})),primarySsrc=ssrcs.length>0&&ssrcs[0].ssrc,flows=SDPUtils.matchPrefix(mediaSection,"a=ssrc-group:FID").map((function(line){return line.substr(17).split(" ").map((function(part){return parseInt(part,10)}))}));flows.length>0&&flows[0].length>1&&flows[0][0]===primarySsrc&&(secondarySsrc=flows[0][1]),description.codecs.forEach((function(codec){if("RTX"===codec.name.toUpperCase()&&codec.parameters.apt){var encParam={ssrc:primarySsrc,codecPayloadType:parseInt(codec.parameters.apt,10)};primarySsrc&&secondarySsrc&&(encParam.rtx={ssrc:secondarySsrc}),encodingParameters.push(encParam),hasRed&&((encParam=JSON.parse(JSON.stringify(encParam))).fec={ssrc:primarySsrc,mechanism:hasUlpfec?"red+ulpfec":"red"},encodingParameters.push(encParam))}})),0===encodingParameters.length&&primarySsrc&&encodingParameters.push({ssrc:primarySsrc});var bandwidth=SDPUtils.matchPrefix(mediaSection,"b=");return bandwidth.length&&(bandwidth=0===bandwidth[0].indexOf("b=TIAS:")?parseInt(bandwidth[0].substr(7),10):0===bandwidth[0].indexOf("b=AS:")?1e3*parseInt(bandwidth[0].substr(5),10)*.95-16e3:void 0,encodingParameters.forEach((function(params){params.maxBitrate=bandwidth}))),encodingParameters},SDPUtils.parseRtcpParameters=function(mediaSection){var rtcpParameters={},remoteSsrc=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(obj){return"cname"===obj.attribute}))[0];remoteSsrc&&(rtcpParameters.cname=remoteSsrc.value,rtcpParameters.ssrc=remoteSsrc.ssrc);var rsize=SDPUtils.matchPrefix(mediaSection,"a=rtcp-rsize");rtcpParameters.reducedSize=rsize.length>0,rtcpParameters.compound=0===rsize.length;var mux=SDPUtils.matchPrefix(mediaSection,"a=rtcp-mux");return rtcpParameters.mux=mux.length>0,rtcpParameters},SDPUtils.parseMsid=function(mediaSection){var parts,spec=SDPUtils.matchPrefix(mediaSection,"a=msid:");if(1===spec.length)return{stream:(parts=spec[0].substr(7).split(" "))[0],track:parts[1]};var planB=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(msidParts){return"msid"===msidParts.attribute}));return planB.length>0?{stream:(parts=planB[0].value.split(" "))[0],track:parts[1]}:void 0},SDPUtils.parseSctpDescription=function(mediaSection){var maxMessageSize,mline=SDPUtils.parseMLine(mediaSection),maxSizeLine=SDPUtils.matchPrefix(mediaSection,"a=max-message-size:");maxSizeLine.length>0&&(maxMessageSize=parseInt(maxSizeLine[0].substr(19),10)),isNaN(maxMessageSize)&&(maxMessageSize=65536);var sctpPort=SDPUtils.matchPrefix(mediaSection,"a=sctp-port:");if(sctpPort.length>0)return{port:parseInt(sctpPort[0].substr(12),10),protocol:mline.fmt,maxMessageSize:maxMessageSize};if(SDPUtils.matchPrefix(mediaSection,"a=sctpmap:").length>0){var parts=SDPUtils.matchPrefix(mediaSection,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(parts[0],10),protocol:parts[1],maxMessageSize:maxMessageSize}}},SDPUtils.writeSctpDescription=function(media,sctp){var output=[];return output="DTLS/SCTP"!==media.protocol?["m="+media.kind+" 9 "+media.protocol+" "+sctp.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+sctp.port+"\r\n"]:["m="+media.kind+" 9 "+media.protocol+" "+sctp.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+sctp.port+" "+sctp.protocol+" 65535\r\n"],void 0!==sctp.maxMessageSize&&output.push("a=max-message-size:"+sctp.maxMessageSize+"\r\n"),output.join("")},SDPUtils.generateSessionId=function(){return Math.random().toString().substr(2,21)},SDPUtils.writeSessionBoilerplate=function(sessId,sessVer,sessUser){var version=void 0!==sessVer?sessVer:2;return"v=0\r\no="+(sessUser||"thisisadapterortc")+" "+(sessId||SDPUtils.generateSessionId())+" "+version+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},SDPUtils.writeMediaSection=function(transceiver,caps,type,stream){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.direction?sdp+="a="+transceiver.direction+"\r\n":transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var msid="msid:"+stream.id+" "+transceiver.rtpSender.track.id+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp},SDPUtils.getDirection=function(mediaSection,sessionpart){for(var lines=SDPUtils.splitLines(mediaSection),i=0;i<lines.length;i++)switch(lines[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return lines[i].substr(2)}return sessionpart?SDPUtils.getDirection(sessionpart):"sendrecv"},SDPUtils.getKind=function(mediaSection){return SDPUtils.splitLines(mediaSection)[0].split(" ")[0].substr(2)},SDPUtils.isRejected=function(mediaSection){return"0"===mediaSection.split(" ",2)[1]},SDPUtils.parseMLine=function(mediaSection){var parts=SDPUtils.splitLines(mediaSection)[0].substr(2).split(" ");return{kind:parts[0],port:parseInt(parts[1],10),protocol:parts[2],fmt:parts.slice(3).join(" ")}},SDPUtils.parseOLine=function(mediaSection){var parts=SDPUtils.matchPrefix(mediaSection,"o=")[0].substr(2).split(" ");return{username:parts[0],sessionId:parts[1],sessionVersion:parseInt(parts[2],10),netType:parts[3],addressType:parts[4],address:parts[5]}},SDPUtils.isValidSDP=function(blob){if("string"!=typeof blob||0===blob.length)return!1;for(var lines=SDPUtils.splitLines(blob),i=0;i<lines.length;i++)if(lines[i].length<2||"="!==lines[i].charAt(1))return!1;return!0},"object"===("undefined"==typeof module?"undefined":_typeof(module))&&(module.exports=SDPUtils)},{}],7:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;msecs>=0&&(item._idleTimeoutId=setTimeout((function(){item._onTimeout&&item._onTimeout()}),msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick((function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))})),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":3,timers:7}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"v1",{enumerable:!0,get:function(){return _v.default}}),Object.defineProperty(exports,"v3",{enumerable:!0,get:function(){return _v2.default}}),Object.defineProperty(exports,"v4",{enumerable:!0,get:function(){return _v3.default}}),Object.defineProperty(exports,"v5",{enumerable:!0,get:function(){return _v4.default}}),Object.defineProperty(exports,"NIL",{enumerable:!0,get:function(){return _nil.default}}),Object.defineProperty(exports,"version",{enumerable:!0,get:function(){return _version.default}}),Object.defineProperty(exports,"validate",{enumerable:!0,get:function(){return _validate.default}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return _stringify.default}}),Object.defineProperty(exports,"parse",{enumerable:!0,get:function(){return _parse.default}});var _v=_interopRequireDefault(require("./v1.js")),_v2=_interopRequireDefault(require("./v3.js")),_v3=_interopRequireDefault(require("./v4.js")),_v4=_interopRequireDefault(require("./v5.js")),_nil=_interopRequireDefault(require("./nil.js")),_version=_interopRequireDefault(require("./version.js")),_validate=_interopRequireDefault(require("./validate.js")),_stringify=_interopRequireDefault(require("./stringify.js")),_parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}},{"./nil.js":10,"./parse.js":11,"./stringify.js":15,"./v1.js":16,"./v3.js":17,"./v4.js":19,"./v5.js":20,"./validate.js":21,"./version.js":22}],9:[function(require,module,exports){"use strict";function getOutputLength(inputLength8){return 14+(inputLength8+64>>>9<<4)+1}function safeAdd(x,y){var lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw}function md5cmn(q,a,b,x,s,t){return safeAdd((num=safeAdd(safeAdd(a,q),safeAdd(x,t)))<<(cnt=s)|num>>>32-cnt,b);var num,cnt}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t)}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t)}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t)}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _default=function(bytes){if("string"==typeof bytes){var msg=unescape(encodeURIComponent(bytes));bytes=new Uint8Array(msg.length);for(var i=0;i<msg.length;++i)bytes[i]=msg.charCodeAt(i)}return function(input){for(var output=[],length32=32*input.length,i=0;i<length32;i+=8){var x=input[i>>5]>>>i%32&255,hex=parseInt("0123456789abcdef".charAt(x>>>4&15)+"0123456789abcdef".charAt(15&x),16);output.push(hex)}return output}(function(x,len){x[len>>5]|=128<<len%32,x[getOutputLength(len)-1]=len;for(var a=1732584193,b=-271733879,c=-1732584194,d=271733878,i=0;i<x.length;i+=16){var olda=a,oldb=b,oldc=c,oldd=d;a=md5ff(a,b,c,d,x[i],7,-680876936),d=md5ff(d,a,b,c,x[i+1],12,-389564586),c=md5ff(c,d,a,b,x[i+2],17,606105819),b=md5ff(b,c,d,a,x[i+3],22,-1044525330),a=md5ff(a,b,c,d,x[i+4],7,-176418897),d=md5ff(d,a,b,c,x[i+5],12,1200080426),c=md5ff(c,d,a,b,x[i+6],17,-1473231341),b=md5ff(b,c,d,a,x[i+7],22,-45705983),a=md5ff(a,b,c,d,x[i+8],7,1770035416),d=md5ff(d,a,b,c,x[i+9],12,-1958414417),c=md5ff(c,d,a,b,x[i+10],17,-42063),b=md5ff(b,c,d,a,x[i+11],22,-1990404162),a=md5ff(a,b,c,d,x[i+12],7,1804603682),d=md5ff(d,a,b,c,x[i+13],12,-40341101),c=md5ff(c,d,a,b,x[i+14],17,-1502002290),b=md5ff(b,c,d,a,x[i+15],22,1236535329),a=md5gg(a,b,c,d,x[i+1],5,-165796510),d=md5gg(d,a,b,c,x[i+6],9,-1069501632),c=md5gg(c,d,a,b,x[i+11],14,643717713),b=md5gg(b,c,d,a,x[i],20,-373897302),a=md5gg(a,b,c,d,x[i+5],5,-701558691),d=md5gg(d,a,b,c,x[i+10],9,38016083),c=md5gg(c,d,a,b,x[i+15],14,-660478335),b=md5gg(b,c,d,a,x[i+4],20,-405537848),a=md5gg(a,b,c,d,x[i+9],5,568446438),d=md5gg(d,a,b,c,x[i+14],9,-1019803690),c=md5gg(c,d,a,b,x[i+3],14,-187363961),b=md5gg(b,c,d,a,x[i+8],20,1163531501),a=md5gg(a,b,c,d,x[i+13],5,-1444681467),d=md5gg(d,a,b,c,x[i+2],9,-51403784),c=md5gg(c,d,a,b,x[i+7],14,1735328473),b=md5gg(b,c,d,a,x[i+12],20,-1926607734),a=md5hh(a,b,c,d,x[i+5],4,-378558),d=md5hh(d,a,b,c,x[i+8],11,-2022574463),c=md5hh(c,d,a,b,x[i+11],16,1839030562),b=md5hh(b,c,d,a,x[i+14],23,-35309556),a=md5hh(a,b,c,d,x[i+1],4,-1530992060),d=md5hh(d,a,b,c,x[i+4],11,1272893353),c=md5hh(c,d,a,b,x[i+7],16,-155497632),b=md5hh(b,c,d,a,x[i+10],23,-1094730640),a=md5hh(a,b,c,d,x[i+13],4,681279174),d=md5hh(d,a,b,c,x[i],11,-358537222),c=md5hh(c,d,a,b,x[i+3],16,-722521979),b=md5hh(b,c,d,a,x[i+6],23,76029189),a=md5hh(a,b,c,d,x[i+9],4,-640364487),d=md5hh(d,a,b,c,x[i+12],11,-421815835),c=md5hh(c,d,a,b,x[i+15],16,530742520),b=md5hh(b,c,d,a,x[i+2],23,-995338651),a=md5ii(a,b,c,d,x[i],6,-198630844),d=md5ii(d,a,b,c,x[i+7],10,1126891415),c=md5ii(c,d,a,b,x[i+14],15,-1416354905),b=md5ii(b,c,d,a,x[i+5],21,-57434055),a=md5ii(a,b,c,d,x[i+12],6,1700485571),d=md5ii(d,a,b,c,x[i+3],10,-1894986606),c=md5ii(c,d,a,b,x[i+10],15,-1051523),b=md5ii(b,c,d,a,x[i+1],21,-2054922799),a=md5ii(a,b,c,d,x[i+8],6,1873313359),d=md5ii(d,a,b,c,x[i+15],10,-30611744),c=md5ii(c,d,a,b,x[i+6],15,-1560198380),b=md5ii(b,c,d,a,x[i+13],21,1309151649),a=md5ii(a,b,c,d,x[i+4],6,-145523070),d=md5ii(d,a,b,c,x[i+11],10,-1120210379),c=md5ii(c,d,a,b,x[i+2],15,718787259),b=md5ii(b,c,d,a,x[i+9],21,-343485551),a=safeAdd(a,olda),b=safeAdd(b,oldb),c=safeAdd(c,oldc),d=safeAdd(d,oldd)}return[a,b,c,d]}(function(input){if(0===input.length)return[];for(var length8=8*input.length,output=new Uint32Array(getOutputLength(length8)),i=0;i<length8;i+=8)output[i>>5]|=(255&input[i/8])<<i%32;return output}(bytes),8*bytes.length))};exports.default=_default},{}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default="00000000-0000-0000-0000-000000000000"},{}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){if(!(0,_validate.default)(uuid))throw TypeError("Invalid UUID");var v,arr=new Uint8Array(16);return arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24,arr[1]=v>>>16&255,arr[2]=v>>>8&255,arr[3]=255&v,arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8,arr[5]=255&v,arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8,arr[7]=255&v,arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8,arr[9]=255&v,arr[10]=(v=parseInt(uuid.slice(24,36),16))/1099511627776&255,arr[11]=v/4294967296&255,arr[12]=v>>>24&255,arr[13]=v>>>16&255,arr[14]=v>>>8&255,arr[15]=255&v,arr};exports.default=_default},{"./validate.js":21}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},{}],13:[function(require,module,exports){"use strict";var getRandomValues;Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(){if(!getRandomValues&&!(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)};var rnds8=new Uint8Array(16)},{}],14:[function(require,module,exports){"use strict";function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z}}function ROTL(x,n){return x<<n|x>>>32-n}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _default=function(bytes){var K=[1518500249,1859775393,2400959708,3395469782],H=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof bytes){var msg=unescape(encodeURIComponent(bytes));bytes=[];for(var i=0;i<msg.length;++i)bytes.push(msg.charCodeAt(i))}else Array.isArray(bytes)||(bytes=Array.prototype.slice.call(bytes));bytes.push(128);for(var l=bytes.length/4+2,N=Math.ceil(l/16),M=new Array(N),_i=0;_i<N;++_i){for(var arr=new Uint32Array(16),j=0;j<16;++j)arr[j]=bytes[64*_i+4*j]<<24|bytes[64*_i+4*j+1]<<16|bytes[64*_i+4*j+2]<<8|bytes[64*_i+4*j+3];M[_i]=arr}M[N-1][14]=8*(bytes.length-1)/Math.pow(2,32),M[N-1][14]=Math.floor(M[N-1][14]),M[N-1][15]=8*(bytes.length-1)&4294967295;for(var _i2=0;_i2<N;++_i2){for(var W=new Uint32Array(80),t=0;t<16;++t)W[t]=M[_i2][t];for(var _t=16;_t<80;++_t)W[_t]=ROTL(W[_t-3]^W[_t-8]^W[_t-14]^W[_t-16],1);for(var a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],_t2=0;_t2<80;++_t2){var s=Math.floor(_t2/20),T=ROTL(a,5)+f(s,b,c,d)+e+K[s]+W[_t2]>>>0;e=d,d=c,c=ROTL(b,30)>>>0,b=a,a=T}H[0]=H[0]+a>>>0,H[1]=H[1]+b>>>0,H[2]=H[2]+c>>>0,H[3]=H[3]+d>>>0,H[4]=H[4]+e>>>0}return[H[0]>>24&255,H[0]>>16&255,H[0]>>8&255,255&H[0],H[1]>>24&255,H[1]>>16&255,H[1]>>8&255,255&H[1],H[2]>>24&255,H[2]>>16&255,H[2]>>8&255,255&H[2],H[3]>>24&255,H[3]>>16&255,H[3]>>8&255,255&H[3],H[4]>>24&255,H[4]>>16&255,H[4]>>8&255,255&H[4]]};exports.default=_default},{}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};for(var byteToHex=[],i=0;i<256;++i)byteToHex.push((i+256).toString(16).substr(1));var _default=function(arr){var offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,uuid=(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();if(!(0,_validate.default)(uuid))throw TypeError("Stringified UUID is invalid");return uuid};exports.default=_default},{"./validate.js":21}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _nodeId,_clockseq,_rng=_interopRequireDefault(require("./rng.js")),_stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _lastMSecs=0,_lastNSecs=0;var _default=function(options,buf,offset){var i=buf&&offset||0,b=buf||new Array(16),node=(options=options||{}).node||_nodeId,clockseq=void 0!==options.clockseq?options.clockseq:_clockseq;if(null==node||null==clockseq){var seedBytes=options.random||(options.rng||_rng.default)();null==node&&(node=_nodeId=[1|seedBytes[0],seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]]),null==clockseq&&(clockseq=_clockseq=16383&(seedBytes[6]<<8|seedBytes[7]))}var msecs=void 0!==options.msecs?options.msecs:Date.now(),nsecs=void 0!==options.nsecs?options.nsecs:_lastNSecs+1,dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&void 0===options.clockseq&&(clockseq=clockseq+1&16383),(dt<0||msecs>_lastMSecs)&&void 0===options.nsecs&&(nsecs=0),nsecs>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_lastMSecs=msecs,_lastNSecs=nsecs,_clockseq=clockseq;var tl=(1e4*(268435455&(msecs+=122192928e5))+nsecs)%4294967296;b[i++]=tl>>>24&255,b[i++]=tl>>>16&255,b[i++]=tl>>>8&255,b[i++]=255&tl;var tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255,b[i++]=255&tmh,b[i++]=tmh>>>24&15|16,b[i++]=tmh>>>16&255,b[i++]=clockseq>>>8|128,b[i++]=255&clockseq;for(var n=0;n<6;++n)b[i+n]=node[n];return buf||(0,_stringify.default)(b)};exports.default=_default},{"./rng.js":13,"./stringify.js":15}],17:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js")),_md=_interopRequireDefault(require("./md5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=(0,_v.default)("v3",48,_md.default);exports.default=_default},{"./md5.js":9,"./v35.js":18}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(name,version,hashfunc){function generateUUID(value,namespace,buf,offset){if("string"==typeof value&&(value=function(str){str=unescape(encodeURIComponent(str));for(var bytes=[],i=0;i<str.length;++i)bytes.push(str.charCodeAt(i));return bytes}(value)),"string"==typeof namespace&&(namespace=(0,_parse.default)(namespace)),16!==namespace.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var bytes=new Uint8Array(16+value.length);if(bytes.set(namespace),bytes.set(value,namespace.length),(bytes=hashfunc(bytes))[6]=15&bytes[6]|version,bytes[8]=63&bytes[8]|128,buf){offset=offset||0;for(var i=0;i<16;++i)buf[offset+i]=bytes[i];return buf}return(0,_stringify.default)(bytes)}try{generateUUID.name=name}catch(err){}return generateUUID.DNS=DNS,generateUUID.URL=URL,generateUUID},exports.URL=exports.DNS=void 0;var _stringify=_interopRequireDefault(require("./stringify.js")),_parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";exports.DNS=DNS;var URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";exports.URL=URL},{"./parse.js":11,"./stringify.js":15}],19:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js")),_stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=function(options,buf,offset){var rnds=(options=options||{}).random||(options.rng||_rng.default)();if(rnds[6]=15&rnds[6]|64,rnds[8]=63&rnds[8]|128,buf){offset=offset||0;for(var i=0;i<16;++i)buf[offset+i]=rnds[i];return buf}return(0,_stringify.default)(rnds)};exports.default=_default},{"./rng.js":13,"./stringify.js":15}],20:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js")),_sha=_interopRequireDefault(require("./sha1.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=(0,_v.default)("v5",80,_sha.default);exports.default=_default},{"./sha1.js":14,"./v35.js":18}],21:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_regex=(obj=require("./regex.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){return"string"==typeof uuid&&_regex.default.test(uuid)};exports.default=_default},{"./regex.js":12}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){if(!(0,_validate.default)(uuid))throw TypeError("Invalid UUID");return parseInt(uuid.substr(14,1),16)};exports.default=_default},{"./validate.js":21}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var adapter=(0,require("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});exports.default=adapter},{"./adapter_factory.js":24}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adapterFactory=function(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},window=_ref.window,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},logging=utils.log,browserDetails=utils.detectBrowser(window),adapter={browserDetails:browserDetails,commonShim:commonShim,extractVersion:utils.extractVersion,disableLog:utils.disableLog,disableWarnings:utils.disableWarnings};switch(browserDetails.browser){case"chrome":if(!chromeShim||!chromeShim.shimPeerConnection||!options.shimChrome)return logging("Chrome shim is not included in this adapter release."),adapter;if(null===browserDetails.version)return logging("Chrome shim can not determine version, not shimming."),adapter;logging("adapter.js shimming chrome."),adapter.browserShim=chromeShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),chromeShim.shimGetUserMedia(window,browserDetails),chromeShim.shimMediaStream(window,browserDetails),chromeShim.shimPeerConnection(window,browserDetails),chromeShim.shimOnTrack(window,browserDetails),chromeShim.shimAddTrackRemoveTrack(window,browserDetails),chromeShim.shimGetSendersWithDtmf(window,browserDetails),chromeShim.shimGetStats(window,browserDetails),chromeShim.shimSenderReceiverGetStats(window,browserDetails),chromeShim.fixNegotiationNeeded(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;case"firefox":if(!firefoxShim||!firefoxShim.shimPeerConnection||!options.shimFirefox)return logging("Firefox shim is not included in this adapter release."),adapter;logging("adapter.js shimming firefox."),adapter.browserShim=firefoxShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),firefoxShim.shimGetUserMedia(window,browserDetails),firefoxShim.shimPeerConnection(window,browserDetails),firefoxShim.shimOnTrack(window,browserDetails),firefoxShim.shimRemoveStream(window,browserDetails),firefoxShim.shimSenderGetStats(window,browserDetails),firefoxShim.shimReceiverGetStats(window,browserDetails),firefoxShim.shimRTCDataChannel(window,browserDetails),firefoxShim.shimAddTransceiver(window,browserDetails),firefoxShim.shimGetParameters(window,browserDetails),firefoxShim.shimCreateOffer(window,browserDetails),firefoxShim.shimCreateAnswer(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"edge":if(!edgeShim||!edgeShim.shimPeerConnection||!options.shimEdge)return logging("MS edge shim is not included in this adapter release."),adapter;logging("adapter.js shimming edge."),adapter.browserShim=edgeShim,edgeShim.shimGetUserMedia(window,browserDetails),edgeShim.shimGetDisplayMedia(window,browserDetails),edgeShim.shimPeerConnection(window,browserDetails),edgeShim.shimReplaceTrack(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"safari":if(!safariShim||!options.shimSafari)return logging("Safari shim is not included in this adapter release."),adapter;logging("adapter.js shimming safari."),adapter.browserShim=safariShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),safariShim.shimRTCIceServerUrls(window,browserDetails),safariShim.shimCreateOfferLegacy(window,browserDetails),safariShim.shimCallbacksAPI(window,browserDetails),safariShim.shimLocalStreamsAPI(window,browserDetails),safariShim.shimRemoteStreamsAPI(window,browserDetails),safariShim.shimTrackEventTransceiver(window,browserDetails),safariShim.shimGetUserMedia(window,browserDetails),safariShim.shimAudioContext(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;default:logging("Unsupported browser!")}return adapter};var utils=_interopRequireWildcard(require("./utils")),chromeShim=_interopRequireWildcard(require("./chrome/chrome_shim")),edgeShim=_interopRequireWildcard(require("./edge/edge_shim")),firefoxShim=_interopRequireWildcard(require("./firefox/firefox_shim")),safariShim=_interopRequireWildcard(require("./safari/safari_shim")),commonShim=_interopRequireWildcard(require("./common_shim"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}},{"./chrome/chrome_shim":25,"./common_shim":28,"./edge/edge_shim":29,"./firefox/firefox_shim":33,"./safari/safari_shim":36,"./utils":37}],25:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimMediaStream=function(window){window.MediaStream=window.MediaStream||window.webkitMediaStream},exports.shimOnTrack=function(window){if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("ontrack"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(f){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=f)},enumerable:!0,configurable:!0});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var _this=this;return this._ontrackpoly||(this._ontrackpoly=function(e){e.stream.addEventListener("addtrack",(function(te){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===te.track.id})):{track:te.track};var event=new Event("track");event.track=te.track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)})),e.stream.getTracks().forEach((function(track){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===track.id})):{track:track};var event=new Event("track");event.track=track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)}))},this.addEventListener("addstream",this._ontrackpoly)),origSetRemoteDescription.apply(this,arguments)}}else utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}))},exports.shimGetSendersWithDtmf=function(window){if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("getSenders"in window.RTCPeerConnection.prototype)&&"createDTMFSender"in window.RTCPeerConnection.prototype){var shimSenderWithDtmf=function(pc,track){return{track:track,get dtmf(){return void 0===this._dtmf&&("audio"===track.kind?this._dtmf=pc.createDTMFSender(track):this._dtmf=null),this._dtmf},_pc:pc}};if(!window.RTCPeerConnection.prototype.getSenders){window.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){var sender=origAddTrack.apply(this,arguments);return sender||(sender=shimSenderWithDtmf(this,track),this._senders.push(sender)),sender};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){origRemoveTrack.apply(this,arguments);var idx=this._senders.indexOf(sender);-1!==idx&&this._senders.splice(idx,1)}}var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this2=this;this._senders=this._senders||[],origAddStream.apply(this,[stream]),stream.getTracks().forEach((function(track){_this2._senders.push(shimSenderWithDtmf(_this2,track))}))};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._senders=this._senders||[],origRemoveStream.apply(this,[stream]),stream.getTracks().forEach((function(track){var sender=_this3._senders.find((function(s){return s.track===track}));sender&&_this3._senders.splice(_this3._senders.indexOf(sender),1)}))}}else if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&"getSenders"in window.RTCPeerConnection.prototype&&"createDTMFSender"in window.RTCPeerConnection.prototype&&window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;window.RTCPeerConnection.prototype.getSenders=function(){var _this4=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this4})),senders},Object.defineProperty(window.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}},exports.shimGetStats=function(window){if(!window.RTCPeerConnection)return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _this5=this,_arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];if(arguments.length>0&&"function"==typeof selector)return origGetStats.apply(this,arguments);if(0===origGetStats.length&&(0===arguments.length||"function"!=typeof selector))return origGetStats.apply(this,[]);var fixChromeStats_=function(response){var standardReport={};return response.result().forEach((function(report){var standardStats={id:report.id,timestamp:report.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[report.type]||report.type};report.names().forEach((function(name){standardStats[name]=report.stat(name)})),standardReport[standardStats.id]=standardStats})),standardReport},makeMapStats=function(stats){return new Map(Object.keys(stats).map((function(key){return[key,stats[key]]})))};if(arguments.length>=2){var successCallbackWrapper_=function(response){onSucc(makeMapStats(fixChromeStats_(response)))};return origGetStats.apply(this,[successCallbackWrapper_,selector])}return new Promise((function(resolve,reject){origGetStats.apply(_this5,[function(response){resolve(makeMapStats(fixChromeStats_(response)))},reject])})).then(onSucc,onErr)}},exports.shimSenderReceiverGetStats=function(window){if(!("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&window.RTCRtpSender&&window.RTCRtpReceiver))return;if(!("getStats"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this6=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this6})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window.RTCRtpSender.prototype.getStats=function(){var sender=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,sender.track,!0)}))}}if(!("getStats"in window.RTCRtpReceiver.prototype)){var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this7=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this7})),receivers}),utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){var receiver=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,receiver.track,!1)}))}}if(!("getStats"in window.RTCRtpSender.prototype)||!("getStats"in window.RTCRtpReceiver.prototype))return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof window.MediaStreamTrack){var track=arguments[0],sender=void 0,receiver=void 0,err=void 0;return this.getSenders().forEach((function(s){s.track===track&&(sender?err=!0:sender=s)})),this.getReceivers().forEach((function(r){return r.track===track&&(receiver?err=!0:receiver=r),r.track===track})),err||sender&&receiver?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):sender?sender.getStats():receiver?receiver.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return origGetStats.apply(this,arguments)}},exports.shimAddTrackRemoveTrackWithNative=shimAddTrackRemoveTrackWithNative,exports.shimAddTrackRemoveTrack=function(window,browserDetails){if(!window.RTCPeerConnection)return;if(window.RTCPeerConnection.prototype.addTrack&&browserDetails.version>=65)return shimAddTrackRemoveTrackWithNative(window);var origGetLocalStreams=window.RTCPeerConnection.prototype.getLocalStreams;window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this11=this,nativeStreams=origGetLocalStreams.apply(this);return this._reverseStreams=this._reverseStreams||{},nativeStreams.map((function(stream){return _this11._reverseStreams[stream.id]}))};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this12=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},stream.getTracks().forEach((function(track){if(_this12.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[stream.id]){var newStream=new window.MediaStream(stream.getTracks());this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,stream=newStream}origAddStream.apply(this,[stream])};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;function replaceInternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(internalStream.id,"g"),externalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}function replaceExternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(externalStream.id,"g"),internalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}window.RTCPeerConnection.prototype.removeStream=function(stream){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},origRemoveStream.apply(this,[this._streams[stream.id]||stream]),delete this._reverseStreams[this._streams[stream.id]?this._streams[stream.id].id:stream.id],delete this._streams[stream.id]},window.RTCPeerConnection.prototype.addTrack=function(track,stream){var _this13=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var streams=[].slice.call(arguments,1);if(1!==streams.length||!streams[0].getTracks().find((function(t){return t===track})))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var alreadyExists=this.getSenders().find((function(s){return s.track===track}));if(alreadyExists)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var oldStream=this._streams[stream.id];if(oldStream)oldStream.addTrack(track),Promise.resolve().then((function(){_this13.dispatchEvent(new Event("negotiationneeded"))}));else{var newStream=new window.MediaStream([track]);this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,this.addStream(newStream)}return this.getSenders().find((function(s){return s.track===track}))},["createOffer","createAnswer"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){var _this14=this,args=arguments,isLegacyCall=arguments.length&&"function"==typeof arguments[0];return isLegacyCall?nativeMethod.apply(this,[function(description){var desc=replaceInternalStreamId(_this14,description);args[0].apply(null,[desc])},function(err){args[1]&&args[1].apply(null,err)},arguments[2]]):nativeMethod.apply(this,arguments).then((function(description){return replaceInternalStreamId(_this14,description)}))}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var origSetLocalDescription=window.RTCPeerConnection.prototype.setLocalDescription;window.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=replaceExternalStreamId(this,arguments[0]),origSetLocalDescription.apply(this,arguments)):origSetLocalDescription.apply(this,arguments)};var origLocalDescription=Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(window.RTCPeerConnection.prototype,"localDescription",{get:function(){var description=origLocalDescription.get.apply(this);return""===description.type?description:replaceInternalStreamId(this,description)}}),window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this15=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!sender._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(sender._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var stream=void 0;Object.keys(this._streams).forEach((function(streamid){_this15._streams[streamid].getTracks().find((function(track){return sender.track===track}))&&(stream=_this15._streams[streamid])})),stream&&(1===stream.getTracks().length?this.removeStream(this._reverseStreams[stream.id]):stream.removeTrack(sender.track),this.dispatchEvent(new Event("negotiationneeded")))}},exports.shimPeerConnection=function(window,browserDetails){!window.RTCPeerConnection&&window.webkitRTCPeerConnection&&(window.RTCPeerConnection=window.webkitRTCPeerConnection);if(!window.RTCPeerConnection)return;browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}))},exports.fixNegotiationNeeded=function(window,browserDetails){utils.wrapPeerConnectionEvent(window,"negotiationneeded",(function(e){var pc=e.target;if(!(browserDetails.version<72||pc.getConfiguration&&"plan-b"===pc.getConfiguration().sdpSemantics)||"stable"===pc.signalingState)return e}))};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js"));function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimAddTrackRemoveTrackWithNative(window){window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this8=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((function(streamId){return _this8._shimmedLocalStreams[streamId][0]}))};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){if(!stream)return origAddTrack.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var sender=origAddTrack.apply(this,arguments);return this._shimmedLocalStreams[stream.id]?-1===this._shimmedLocalStreams[stream.id].indexOf(sender)&&this._shimmedLocalStreams[stream.id].push(sender):this._shimmedLocalStreams[stream.id]=[stream,sender],sender};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this9=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},stream.getTracks().forEach((function(track){if(_this9.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")}));var existingSenders=this.getSenders();origAddStream.apply(this,arguments);var newSenders=this.getSenders().filter((function(newSender){return-1===existingSenders.indexOf(newSender)}));this._shimmedLocalStreams[stream.id]=[stream].concat(newSenders)};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[stream.id],origRemoveStream.apply(this,arguments)};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this10=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},sender&&Object.keys(this._shimmedLocalStreams).forEach((function(streamId){var idx=_this10._shimmedLocalStreams[streamId].indexOf(sender);-1!==idx&&_this10._shimmedLocalStreams[streamId].splice(idx,1),1===_this10._shimmedLocalStreams[streamId].length&&delete _this10._shimmedLocalStreams[streamId]})),origRemoveTrack.apply(this,arguments)}}},{"../utils.js":37,"./getdisplaymedia":26,"./getusermedia":27}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,getSourceId){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;if("function"!=typeof getSourceId)return void console.error("shimGetDisplayMedia: getSourceId argument is not a function");window.navigator.mediaDevices.getDisplayMedia=function(constraints){return getSourceId(constraints).then((function(sourceId){var widthSpecified=constraints.video&&constraints.video.width,heightSpecified=constraints.video&&constraints.video.height,frameRateSpecified=constraints.video&&constraints.video.frameRate;return constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:sourceId,maxFrameRate:frameRateSpecified||3}},widthSpecified&&(constraints.video.mandatory.maxWidth=widthSpecified),heightSpecified&&(constraints.video.mandatory.maxHeight=heightSpecified),window.navigator.mediaDevices.getUserMedia(constraints)}))}}},{}],27:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator;if(!navigator.mediaDevices)return;var constraintsToChrome_=function(c){if("object"!==("undefined"==typeof c?"undefined":_typeof(c))||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach((function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"===_typeof(c[key])?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname_=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname_("min",key)]=r.ideal,cc.optional.push(oc),(oc={})[oldname_("max",key)]=r.ideal,cc.optional.push(oc)):(oc[oldname_("",key)]=r.ideal,cc.optional.push(oc))}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_("",key)]=r.exact):["min","max"].forEach((function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_(mix,key)]=r[mix])}))}})),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc},shimConstraints_=function(constraints,func){if(browserDetails.version>=61)return func(constraints);if((constraints=JSON.parse(JSON.stringify(constraints)))&&"object"===_typeof(constraints.audio)){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])};remap((constraints=JSON.parse(JSON.stringify(constraints))).audio,"autoGainControl","googAutoGainControl"),remap(constraints.audio,"noiseSuppression","googNoiseSuppression"),constraints.audio=constraintsToChrome_(constraints.audio)}if(constraints&&"object"===_typeof(constraints.video)){var face=constraints.video.facingMode;face=face&&("object"===("undefined"==typeof face?"undefined":_typeof(face))?face:{ideal:face});var getSupportedFacingModeLies=browserDetails.version<66;if(face&&("user"===face.exact||"environment"===face.exact||"user"===face.ideal||"environment"===face.ideal)&&(!navigator.mediaDevices.getSupportedConstraints||!navigator.mediaDevices.getSupportedConstraints().facingMode||getSupportedFacingModeLies)){delete constraints.video.facingMode;var matches=void 0;if("environment"===face.exact||"environment"===face.ideal?matches=["back","rear"]:"user"!==face.exact&&"user"!==face.ideal||(matches=["front"]),matches)return navigator.mediaDevices.enumerateDevices().then((function(devices){var dev=(devices=devices.filter((function(d){return"videoinput"===d.kind}))).find((function(d){return matches.some((function(match){return d.label.toLowerCase().includes(match)}))}));return!dev&&devices.length&&matches.includes("back")&&(dev=devices[devices.length-1]),dev&&(constraints.video.deviceId=face.exact?{exact:dev.deviceId}:{ideal:dev.deviceId}),constraints.video=constraintsToChrome_(constraints.video),logging("chrome: "+JSON.stringify(constraints)),func(constraints)}))}constraints.video=constraintsToChrome_(constraints.video)}return logging("chrome: "+JSON.stringify(constraints)),func(constraints)},shimError_=function(e){return browserDetails.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(navigator.getUserMedia=function(constraints,onSuccess,onError){shimConstraints_(constraints,(function(c){navigator.webkitGetUserMedia(c,onSuccess,(function(e){onError&&onError(shimError_(e))}))}))}.bind(navigator),navigator.mediaDevices.getUserMedia){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(cs){return shimConstraints_(cs,(function(c){return origGetUserMedia(c).then((function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach((function(track){track.stop()})),new DOMException("","NotFoundError");return stream}),(function(e){return Promise.reject(shimError_(e))}))}))}}};var logging=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js")).log},{"../utils.js":37}],28:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimRTCIceCandidate=function(window){if(!window.RTCIceCandidate||window.RTCIceCandidate&&"foundation"in window.RTCIceCandidate.prototype)return;var NativeRTCIceCandidate=window.RTCIceCandidate;window.RTCIceCandidate=function(args){if("object"===("undefined"==typeof args?"undefined":_typeof(args))&&args.candidate&&0===args.candidate.indexOf("a=")&&((args=JSON.parse(JSON.stringify(args))).candidate=args.candidate.substr(2)),args.candidate&&args.candidate.length){var nativeCandidate=new NativeRTCIceCandidate(args),parsedCandidate=_sdp2.default.parseCandidate(args.candidate),augmentedCandidate=Object.assign(nativeCandidate,parsedCandidate);return augmentedCandidate.toJSON=function(){return{candidate:augmentedCandidate.candidate,sdpMid:augmentedCandidate.sdpMid,sdpMLineIndex:augmentedCandidate.sdpMLineIndex,usernameFragment:augmentedCandidate.usernameFragment}},augmentedCandidate}return new NativeRTCIceCandidate(args)},window.RTCIceCandidate.prototype=NativeRTCIceCandidate.prototype,utils.wrapPeerConnectionEvent(window,"icecandidate",(function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new window.RTCIceCandidate(e.candidate),writable:"false"}),e}))},exports.shimMaxMessageSize=function(window,browserDetails){if(!window.RTCPeerConnection)return;"sctp"in window.RTCPeerConnection.prototype||Object.defineProperty(window.RTCPeerConnection.prototype,"sctp",{get:function(){return"undefined"==typeof this._sctp?null:this._sctp}});var sctpInDescription=function(description){if(!description||!description.sdp)return!1;var sections=_sdp2.default.splitSections(description.sdp);return sections.shift(),sections.some((function(mediaSection){var mLine=_sdp2.default.parseMLine(mediaSection);return mLine&&"application"===mLine.kind&&-1!==mLine.protocol.indexOf("SCTP")}))},getRemoteFirefoxVersion=function(description){var match=description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===match||match.length<2)return-1;var version=parseInt(match[1],10);return version!=version?-1:version},getCanSendMaxMessageSize=function(remoteIsFirefox){var canSendMaxMessageSize=65536;return"firefox"===browserDetails.browser&&(canSendMaxMessageSize=browserDetails.version<57?-1===remoteIsFirefox?16384:2147483637:browserDetails.version<60?57===browserDetails.version?65535:65536:2147483637),canSendMaxMessageSize},getMaxMessageSize=function(description,remoteIsFirefox){var maxMessageSize=65536;"firefox"===browserDetails.browser&&57===browserDetails.version&&(maxMessageSize=65535);var match=_sdp2.default.matchPrefix(description.sdp,"a=max-message-size:");return match.length>0?maxMessageSize=parseInt(match[0].substr(19),10):"firefox"===browserDetails.browser&&-1!==remoteIsFirefox&&(maxMessageSize=2147483637),maxMessageSize},origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===browserDetails.browser&&browserDetails.version>=76){var _getConfiguration=this.getConfiguration(),sdpSemantics=_getConfiguration.sdpSemantics;"plan-b"===sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return"undefined"==typeof this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(sctpInDescription(arguments[0])){var isFirefox=getRemoteFirefoxVersion(arguments[0]),canSendMMS=getCanSendMaxMessageSize(isFirefox),remoteMMS=getMaxMessageSize(arguments[0],isFirefox),maxMessageSize=void 0;maxMessageSize=0===canSendMMS&&0===remoteMMS?Number.POSITIVE_INFINITY:0===canSendMMS||0===remoteMMS?Math.max(canSendMMS,remoteMMS):Math.min(canSendMMS,remoteMMS);var sctp={};Object.defineProperty(sctp,"maxMessageSize",{get:function(){return maxMessageSize}}),this._sctp=sctp}return origSetRemoteDescription.apply(this,arguments)}},exports.shimSendThrowTypeError=function(window){if(!window.RTCPeerConnection||!("createDataChannel"in window.RTCPeerConnection.prototype))return;function wrapDcSend(dc,pc){var origDataChannelSend=dc.send;dc.send=function(){var data=arguments[0],length=data.length||data.size||data.byteLength;if("open"===dc.readyState&&pc.sctp&&length>pc.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+pc.sctp.maxMessageSize+" bytes)");return origDataChannelSend.apply(dc,arguments)}}var origCreateDataChannel=window.RTCPeerConnection.prototype.createDataChannel;window.RTCPeerConnection.prototype.createDataChannel=function(){var dataChannel=origCreateDataChannel.apply(this,arguments);return wrapDcSend(dataChannel,this),dataChannel},utils.wrapPeerConnectionEvent(window,"datachannel",(function(e){return wrapDcSend(e.channel,e.target),e}))},exports.shimConnectionState=function(window){if(!window.RTCPeerConnection||"connectionState"in window.RTCPeerConnection.prototype)return;var proto=window.RTCPeerConnection.prototype;Object.defineProperty(proto,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(proto,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(cb){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),cb&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=cb)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((function(method){var origMethod=proto[method];proto[method]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var pc=e.target;if(pc._lastConnectionState!==pc.connectionState){pc._lastConnectionState=pc.connectionState;var newEvent=new Event("connectionstatechange",e);pc.dispatchEvent(newEvent)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),origMethod.apply(this,arguments)}}))},exports.removeExtmapAllowMixed=function(window,browserDetails){if(!window.RTCPeerConnection)return;if("chrome"===browserDetails.browser&&browserDetails.version>=71)return;if("safari"===browserDetails.browser&&browserDetails.version>=605)return;var nativeSRD=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(desc){if(desc&&desc.sdp&&-1!==desc.sdp.indexOf("\na=extmap-allow-mixed")){var sdp=desc.sdp.split("\n").filter((function(line){return"a=extmap-allow-mixed"!==line.trim()})).join("\n");window.RTCSessionDescription&&desc instanceof window.RTCSessionDescription?arguments[0]=new window.RTCSessionDescription({type:desc.type,sdp:sdp}):desc.sdp=sdp}return nativeSRD.apply(this,arguments)}},exports.shimAddIceCandidateNullOrEmpty=function(window,browserDetails){if(!window.RTCPeerConnection||!window.RTCPeerConnection.prototype)return;var nativeAddIceCandidate=window.RTCPeerConnection.prototype.addIceCandidate;if(!nativeAddIceCandidate||0===nativeAddIceCandidate.length)return;window.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===browserDetails.browser&&browserDetails.version<78||"firefox"===browserDetails.browser&&browserDetails.version<68||"safari"===browserDetails.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():nativeAddIceCandidate.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}};var obj,_sdp=require("sdp"),_sdp2=(obj=_sdp)&&obj.__esModule?obj:{default:obj},utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("./utils"))},{"./utils":37,sdp:6}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimPeerConnection=function(window,browserDetails){if(window.RTCIceGatherer&&(window.RTCIceCandidate||(window.RTCIceCandidate=function(args){return args}),window.RTCSessionDescription||(window.RTCSessionDescription=function(args){return args}),browserDetails.version<15025)){var origMSTEnabled=Object.getOwnPropertyDescriptor(window.MediaStreamTrack.prototype,"enabled");Object.defineProperty(window.MediaStreamTrack.prototype,"enabled",{set:function(value){origMSTEnabled.set.call(this,value);var ev=new Event("enabled");ev.enabled=value,this.dispatchEvent(ev)}})}window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)&&Object.defineProperty(window.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new window.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}});window.RTCDtmfSender&&!window.RTCDTMFSender&&(window.RTCDTMFSender=window.RTCDtmfSender);var RTCPeerConnectionShim=(0,_rtcpeerconnectionShim2.default)(window,browserDetails.version);window.RTCPeerConnection=function(config){return config&&config.iceServers&&(config.iceServers=(0,_filtericeservers.filterIceServers)(config.iceServers,browserDetails.version),utils.log("ICE servers after filtering:",config.iceServers)),new RTCPeerConnectionShim(config)},window.RTCPeerConnection.prototype=RTCPeerConnectionShim.prototype},exports.shimReplaceTrack=function(window){window.RTCRtpSender&&!("replaceTrack"in window.RTCRtpSender.prototype)&&(window.RTCRtpSender.prototype.replaceTrack=window.RTCRtpSender.prototype.setTrack)};var obj,utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils")),_filtericeservers=require("./filtericeservers"),_rtcpeerconnectionShim=require("rtcpeerconnection-shim"),_rtcpeerconnectionShim2=(obj=_rtcpeerconnectionShim)&&obj.__esModule?obj:{default:obj}},{"../utils":37,"./filtericeservers":30,"./getdisplaymedia":31,"./getusermedia":32,"rtcpeerconnection-shim":5}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.filterIceServers=function(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter((function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&utils.deprecated("RTCIceServer.url","RTCIceServer.urls");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter((function(url){if(0===url.indexOf("stun:"))return!1;var validTurn=url.startsWith("turn")&&!url.startsWith("turn:[")&&url.includes("transport=udp");return validTurn&&!hasTurn?(hasTurn=!0,!0):validTurn&&!hasTurn})),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}}))};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":37}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window){if(!("getDisplayMedia"in window.navigator))return;if(!window.navigator.mediaDevices)return;if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;window.navigator.mediaDevices.getDisplayMedia=window.navigator.getDisplayMedia.bind(window.navigator)}},{}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetUserMedia=function(window){var navigator=window&&window.navigator,origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(c){return origGetUserMedia(c).catch((function(e){return Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString:function(){return this.name}}}(e))}))}}},{}],33:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimOnTrack=function(window){"object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimPeerConnection=function(window,browserDetails){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection&&!window.mozRTCPeerConnection)return;!window.RTCPeerConnection&&window.mozRTCPeerConnection&&(window.RTCPeerConnection=window.mozRTCPeerConnection);browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var modernStatsTypes={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},nativeGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];return nativeGetStats.apply(this,[selector||null]).then((function(stats){if(browserDetails.version<53&&!onSucc)try{stats.forEach((function(stat){stat.type=modernStatsTypes[stat.type]||stat.type}))}catch(e){if("TypeError"!==e.name)throw e;stats.forEach((function(stat,i){stats.set(i,Object.assign({},stat,{type:modernStatsTypes[stat.type]||stat.type}))}))}return stats})).then(onSucc,onErr)}},exports.shimSenderGetStats=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpSender.prototype)return;var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender});window.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}},exports.shimReceiverGetStats=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpReceiver.prototype)return;var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this2=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this2})),receivers});utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}},exports.shimRemoveStream=function(window){if(!window.RTCPeerConnection||"removeStream"in window.RTCPeerConnection.prototype)return;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;utils.deprecated("removeStream","removeTrack"),this.getSenders().forEach((function(sender){sender.track&&stream.getTracks().includes(sender.track)&&_this3.removeTrack(sender)}))}},exports.shimRTCDataChannel=function(window){window.DataChannel&&!window.RTCDataChannel&&(window.RTCDataChannel=window.DataChannel)},exports.shimAddTransceiver=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origAddTransceiver=window.RTCPeerConnection.prototype.addTransceiver;origAddTransceiver&&(window.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var initParameters=arguments[1],shouldPerformCheck=initParameters&&"sendEncodings"in initParameters;shouldPerformCheck&&initParameters.sendEncodings.forEach((function(encodingParam){if("rid"in encodingParam){if(!/^[a-z0-9]{0,16}$/i.test(encodingParam.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in encodingParam&&!(parseFloat(encodingParam.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in encodingParam&&!(parseFloat(encodingParam.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));var transceiver=origAddTransceiver.apply(this,arguments);if(shouldPerformCheck){var sender=transceiver.sender,params=sender.getParameters();(!("encodings"in params)||1===params.encodings.length&&0===Object.keys(params.encodings[0]).length)&&(params.encodings=initParameters.sendEncodings,sender.sendEncodings=initParameters.sendEncodings,this.setParametersPromises.push(sender.setParameters(params).then((function(){delete sender.sendEncodings})).catch((function(){delete sender.sendEncodings}))))}return transceiver})},exports.shimGetParameters=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCRtpSender)return;var origGetParameters=window.RTCRtpSender.prototype.getParameters;origGetParameters&&(window.RTCRtpSender.prototype.getParameters=function(){var params=origGetParameters.apply(this,arguments);return"encodings"in params||(params.encodings=[].concat(this.sendEncodings||[{}])),params})},exports.shimCreateOffer=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(){var _this4=this,_arguments2=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateOffer.apply(_this4,_arguments2)})).finally((function(){_this4.setParametersPromises=[]})):origCreateOffer.apply(this,arguments)}},exports.shimCreateAnswer=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateAnswer=window.RTCPeerConnection.prototype.createAnswer;window.RTCPeerConnection.prototype.createAnswer=function(){var _this5=this,_arguments3=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateAnswer.apply(_this5,_arguments3)})).finally((function(){_this5.setParametersPromises=[]})):origCreateAnswer.apply(this,arguments)}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":37,"./getdisplaymedia":34,"./getusermedia":35}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,preferredMediaSource){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;window.navigator.mediaDevices.getDisplayMedia=function(constraints){if(!constraints||!constraints.video){var err=new DOMException("getDisplayMedia without video constraints is undefined");return err.name="NotFoundError",err.code=8,Promise.reject(err)}return!0===constraints.video?constraints.video={mediaSource:preferredMediaSource}:constraints.video.mediaSource=preferredMediaSource,window.navigator.mediaDevices.getUserMedia(constraints)}}},{}],35:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator,MediaStreamTrack=window&&window.MediaStreamTrack;if(navigator.getUserMedia=function(constraints,onSuccess,onError){utils.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),navigator.mediaDevices.getUserMedia(constraints).then(onSuccess,onError)},!(browserDetails.version>55&&"autoGainControl"in navigator.mediaDevices.getSupportedConstraints())){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])},nativeGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);if(navigator.mediaDevices.getUserMedia=function(c){return"object"===("undefined"==typeof c?"undefined":_typeof(c))&&"object"===_typeof(c.audio)&&(c=JSON.parse(JSON.stringify(c)),remap(c.audio,"autoGainControl","mozAutoGainControl"),remap(c.audio,"noiseSuppression","mozNoiseSuppression")),nativeGetUserMedia(c)},MediaStreamTrack&&MediaStreamTrack.prototype.getSettings){var nativeGetSettings=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){var obj=nativeGetSettings.apply(this,arguments);return remap(obj,"mozAutoGainControl","autoGainControl"),remap(obj,"mozNoiseSuppression","noiseSuppression"),obj}}if(MediaStreamTrack&&MediaStreamTrack.prototype.applyConstraints){var nativeApplyConstraints=MediaStreamTrack.prototype.applyConstraints;MediaStreamTrack.prototype.applyConstraints=function(c){return"audio"===this.kind&&"object"===("undefined"==typeof c?"undefined":_typeof(c))&&(c=JSON.parse(JSON.stringify(c)),remap(c,"autoGainControl","mozAutoGainControl"),remap(c,"noiseSuppression","mozNoiseSuppression")),nativeApplyConstraints.apply(this,[c])}}}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":37}],36:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimLocalStreamsAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getLocalStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams});if(!("addStream"in window.RTCPeerConnection.prototype)){var _addTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addStream=function(stream){var _this=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(stream)||this._localStreams.push(stream),stream.getAudioTracks().forEach((function(track){return _addTrack.call(_this,track,stream)})),stream.getVideoTracks().forEach((function(track){return _addTrack.call(_this,track,stream)}))},window.RTCPeerConnection.prototype.addTrack=function(track){for(var _this2=this,_len=arguments.length,streams=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)streams[_key-1]=arguments[_key];return streams&&streams.forEach((function(stream){_this2._localStreams?_this2._localStreams.includes(stream)||_this2._localStreams.push(stream):_this2._localStreams=[stream]})),_addTrack.apply(this,arguments)}}"removeStream"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._localStreams||(this._localStreams=[]);var index=this._localStreams.indexOf(stream);if(-1!==index){this._localStreams.splice(index,1);var tracks=stream.getTracks();this.getSenders().forEach((function(sender){tracks.includes(sender.track)&&_this3.removeTrack(sender)}))}})},exports.shimRemoteStreamsAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getRemoteStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]});if(!("onaddstream"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(f){var _this4=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(_this4._remoteStreams||(_this4._remoteStreams=[]),!_this4._remoteStreams.includes(stream)){_this4._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,_this4.dispatchEvent(event)}}))})}});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var pc=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(pc._remoteStreams||(pc._remoteStreams=[]),!(pc._remoteStreams.indexOf(stream)>=0)){pc._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,pc.dispatchEvent(event)}}))}),origSetRemoteDescription.apply(pc,arguments)}}},exports.shimCallbacksAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var prototype=window.RTCPeerConnection.prototype,origCreateOffer=prototype.createOffer,origCreateAnswer=prototype.createAnswer,setLocalDescription=prototype.setLocalDescription,setRemoteDescription=prototype.setRemoteDescription,addIceCandidate=prototype.addIceCandidate;prototype.createOffer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateOffer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.createAnswer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateAnswer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};var withCallback=function(description,successCallback,failureCallback){var promise=setLocalDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};prototype.setLocalDescription=withCallback,withCallback=function(description,successCallback,failureCallback){var promise=setRemoteDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.setRemoteDescription=withCallback,withCallback=function(candidate,successCallback,failureCallback){var promise=addIceCandidate.apply(this,[candidate]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.addIceCandidate=withCallback},exports.shimGetUserMedia=function(window){var navigator=window&&window.navigator;if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var mediaDevices=navigator.mediaDevices,_getUserMedia=mediaDevices.getUserMedia.bind(mediaDevices);navigator.mediaDevices.getUserMedia=function(constraints){return _getUserMedia(shimConstraints(constraints))}}!navigator.getUserMedia&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(navigator.getUserMedia=function(constraints,cb,errcb){navigator.mediaDevices.getUserMedia(constraints).then(cb,errcb)}.bind(navigator))},exports.shimConstraints=shimConstraints,exports.shimRTCIceServerUrls=function(window){if(!window.RTCPeerConnection)return;var OrigPeerConnection=window.RTCPeerConnection;window.RTCPeerConnection=function(pcConfig,pcConstraints){if(pcConfig&&pcConfig.iceServers){for(var newIceServers=[],i=0;i<pcConfig.iceServers.length;i++){var server=pcConfig.iceServers[i];!server.hasOwnProperty("urls")&&server.hasOwnProperty("url")?(utils.deprecated("RTCIceServer.url","RTCIceServer.urls"),(server=JSON.parse(JSON.stringify(server))).urls=server.url,delete server.url,newIceServers.push(server)):newIceServers.push(pcConfig.iceServers[i])}pcConfig.iceServers=newIceServers}return new OrigPeerConnection(pcConfig,pcConstraints)},window.RTCPeerConnection.prototype=OrigPeerConnection.prototype,"generateCertificate"in OrigPeerConnection&&Object.defineProperty(window.RTCPeerConnection,"generateCertificate",{get:function(){return OrigPeerConnection.generateCertificate}})},exports.shimTrackEventTransceiver=function(window){"object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimCreateOfferLegacy=function(window){var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(offerOptions){if(offerOptions){"undefined"!=typeof offerOptions.offerToReceiveAudio&&(offerOptions.offerToReceiveAudio=!!offerOptions.offerToReceiveAudio);var audioTransceiver=this.getTransceivers().find((function(transceiver){return"audio"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveAudio&&audioTransceiver?"sendrecv"===audioTransceiver.direction?audioTransceiver.setDirection?audioTransceiver.setDirection("sendonly"):audioTransceiver.direction="sendonly":"recvonly"===audioTransceiver.direction&&(audioTransceiver.setDirection?audioTransceiver.setDirection("inactive"):audioTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveAudio||audioTransceiver||this.addTransceiver("audio"),"undefined"!=typeof offerOptions.offerToReceiveVideo&&(offerOptions.offerToReceiveVideo=!!offerOptions.offerToReceiveVideo);var videoTransceiver=this.getTransceivers().find((function(transceiver){return"video"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveVideo&&videoTransceiver?"sendrecv"===videoTransceiver.direction?videoTransceiver.setDirection?videoTransceiver.setDirection("sendonly"):videoTransceiver.direction="sendonly":"recvonly"===videoTransceiver.direction&&(videoTransceiver.setDirection?videoTransceiver.setDirection("inactive"):videoTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveVideo||videoTransceiver||this.addTransceiver("video")}return origCreateOffer.apply(this,arguments)}},exports.shimAudioContext=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||window.AudioContext)return;window.AudioContext=window.webkitAudioContext};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"));function shimConstraints(constraints){return constraints&&void 0!==constraints.video?Object.assign({},constraints,{video:utils.compactObject(constraints.video)}):constraints}},{"../utils":37}],37:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.extractVersion=extractVersion,exports.wrapPeerConnectionEvent=function(window,eventNameToWrap,wrapper){if(!window.RTCPeerConnection)return;var proto=window.RTCPeerConnection.prototype,nativeAddEventListener=proto.addEventListener;proto.addEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap)return nativeAddEventListener.apply(this,arguments);var wrappedCallback=function(e){var modifiedEvent=wrapper(e);modifiedEvent&&(cb.handleEvent?cb.handleEvent(modifiedEvent):cb(modifiedEvent))};return this._eventMap=this._eventMap||{},this._eventMap[eventNameToWrap]||(this._eventMap[eventNameToWrap]=new Map),this._eventMap[eventNameToWrap].set(cb,wrappedCallback),nativeAddEventListener.apply(this,[nativeEventName,wrappedCallback])};var nativeRemoveEventListener=proto.removeEventListener;proto.removeEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap||!this._eventMap||!this._eventMap[eventNameToWrap])return nativeRemoveEventListener.apply(this,arguments);if(!this._eventMap[eventNameToWrap].has(cb))return nativeRemoveEventListener.apply(this,arguments);var unwrappedCb=this._eventMap[eventNameToWrap].get(cb);return this._eventMap[eventNameToWrap].delete(cb),0===this._eventMap[eventNameToWrap].size&&delete this._eventMap[eventNameToWrap],0===Object.keys(this._eventMap).length&&delete this._eventMap,nativeRemoveEventListener.apply(this,[nativeEventName,unwrappedCb])},Object.defineProperty(proto,"on"+eventNameToWrap,{get:function(){return this["_on"+eventNameToWrap]},set:function(cb){this["_on"+eventNameToWrap]&&(this.removeEventListener(eventNameToWrap,this["_on"+eventNameToWrap]),delete this["_on"+eventNameToWrap]),cb&&this.addEventListener(eventNameToWrap,this["_on"+eventNameToWrap]=cb)},enumerable:!0,configurable:!0})},exports.disableLog=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+("undefined"==typeof bool?"undefined":_typeof(bool))+". Please use a boolean.");return logDisabled_=bool,bool?"adapter.js logging disabled":"adapter.js logging enabled"},exports.disableWarnings=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+("undefined"==typeof bool?"undefined":_typeof(bool))+". Please use a boolean.");return deprecationWarnings_=!bool,"adapter.js deprecation warnings "+(bool?"disabled":"enabled")},exports.log=function(){if("object"===("undefined"==typeof window?"undefined":_typeof(window))){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},exports.deprecated=function(oldMethod,newMethod){if(!deprecationWarnings_)return;console.warn(oldMethod+" is deprecated, please use "+newMethod+" instead.")},exports.detectBrowser=function(window){var result={browser:null,version:null};if("undefined"==typeof window||!window.navigator)return result.browser="Not a browser.",result;var navigator=window.navigator;if(navigator.mozGetUserMedia)result.browser="firefox",result.version=extractVersion(navigator.userAgent,/Firefox\/(\d+)\./,1);else if(navigator.webkitGetUserMedia||!1===window.isSecureContext&&window.webkitRTCPeerConnection&&!window.RTCIceGatherer)result.browser="chrome",result.version=extractVersion(navigator.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/))result.browser="edge",result.version=extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!window.RTCPeerConnection||!navigator.userAgent.match(/AppleWebKit\/(\d+)\./))return result.browser="Not a supported browser.",result;result.browser="safari",result.version=extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1),result.supportsUnifiedPlan=window.RTCRtpTransceiver&&"currentDirection"in window.RTCRtpTransceiver.prototype}return result},exports.compactObject=function compactObject(data){if(!isObject(data))return data;return Object.keys(data).reduce((function(accumulator,key){var isObj=isObject(data[key]),value=isObj?compactObject(data[key]):data[key],isEmptyObject=isObj&&!Object.keys(value).length;return void 0===value||isEmptyObject?accumulator:Object.assign(accumulator,function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},key,value))}),{})},exports.walkStats=walkStats,exports.filterStats=function(result,track,outbound){var streamStatsType=outbound?"outbound-rtp":"inbound-rtp",filteredResult=new Map;if(null===track)return filteredResult;var trackStats=[];return result.forEach((function(value){"track"===value.type&&value.trackIdentifier===track.id&&trackStats.push(value)})),trackStats.forEach((function(trackStat){result.forEach((function(stats){stats.type===streamStatsType&&stats.trackId===trackStat.id&&walkStats(result,stats,filteredResult)}))})),filteredResult};var logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}function isObject(val){return"[object Object]"===Object.prototype.toString.call(val)}function walkStats(stats,base,resultSet){base&&!resultSet.has(base.id)&&(resultSet.set(base.id,base),Object.keys(base).forEach((function(name){name.endsWith("Id")?walkStats(stats,stats.get(base[name]),resultSet):name.endsWith("Ids")&&base[name].forEach((function(id){walkStats(stats,stats.get(id),resultSet)}))})))}},{}],38:[function(require,module,exports){"use strict";function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}function parseArch(arch){switch(arch){case"x86_64":case"x64":return["x86","64"];case"x86_32":case"x86":return["x86",""];case"armv6l":case"armv7l":case"armv8l":return[arch,""];case"aarch64":return["arm","64"];default:return["",""]}}function padVersion(ver){var minSegs=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3,parts=ver.split("."),len=parts.length;if(len<minSegs){for(var i=0,lenToPad=minSegs-len;i<lenToPad;i+=1)parts.push("0");return parts.join(".")}return ver}var NavigatorUAData=function(){return e=function NavigatorUAData(navigator){!function(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,NavigatorUAData),this._ch=function(navigator){var mobile,uaFullVersion,m,m2,userAgent=navigator.userAgent,platform="",platformVersion="",architecture="",bitness="",fullVersionList=[],platformInfo=userAgent,found=!1,versionInfo=userAgent.replace(/\(([^)]+)\)?/g,(function($0,$1){return found||(platformInfo=$1,found=!0),""})),items=versionInfo.match(/(\S+)\/(\S+)/g),webview=!1;if(mobile=-1!==userAgent.indexOf("Mobile"),null!==(m=/Windows NT (\d+(\.\d+)*)/.exec(platformInfo))){platform="Windows";var ver={6.1:"0.1",6.2:"0.2",6.3:"0.3","10.0":"10.0","11.0":"13.0"}[m[1]];ver&&(platformVersion=padVersion(ver,3)),null!==(m2=/\b(WOW64|Win64|x64)\b/.exec(platformInfo))&&(architecture="x86",bitness="64")}else null!==(m=/Android (\d+(\.\d+)*)/.exec(platformInfo))?(platform="Android",platformVersion=padVersion(m[1]),null!==(m2=/Linux (\w+)/.exec(navigator.platform))&&m2[1]&&(architecture=(m2=parseArch(m2[1]))[0],bitness=m2[1])):null!==(m=/(iPhone|iPod touch); CPU iPhone OS (\d+(_\d+)*)/.exec(platformInfo))||null!==(m=/(iPad); CPU OS (\d+(_\d+)*)/.exec(platformInfo))?(platform="iOS",platformVersion=padVersion(m[2].replace(/_/g,"."))):null!==(m=/Macintosh; (Intel|\w+) Mac OS X (\d+([_.]\d+)*)/.exec(platformInfo))?(platform="macOS",platformVersion=padVersion(m[2].replace(/_/g,"."))):null!==(m=/Linux/.exec(platformInfo))?(platform="Linux",platformVersion=""):null!==(m=/CrOS (\w+) (\d+(\.\d+)*)/.exec(platformInfo))&&(platform="Chrome OS",platformVersion=padVersion(m[2]),architecture=(m2=parseArch(m[1]))[0],bitness=m2[1]);if(platform||(platform="Unknown"),null!==(m=/Chrome\/(\d+(\.\d+)*)/.exec(versionInfo))&&"Google Inc."===navigator.vendor){if(fullVersionList.push({brand:"Chromium",version:padVersion(m[1],4)}),null!==(m2=/(Edge?)\/(\d+(\.\d+)*)/.exec(versionInfo))){var brand={Edge:"Microsoft Edge",Edg:"Microsoft Edge"}[m[1]];fullVersionList.push({brand:brand,version:padVersion(m2[2],4)})}else fullVersionList.push({brand:"Google Chrome",version:padVersion(m[1],4)});/\bwv\b/.exec(platformInfo)&&(webview=!0)}else if(null!==(m=/AppleWebKit\/(\d+(\.\d+)*)/.exec(versionInfo))&&"Apple Computer, Inc."===navigator.vendor){if(fullVersionList.push({brand:"WebKit",version:padVersion(m[1])}),"iOS"===platform&&null!=(m2=/(CriOS|EdgiOS|FxiOS|Version)\/(\d+(\.\d+)*)/.exec(versionInfo))){var _brand={CriOS:"Google Chrome",EdgiOS:"Microsoft Edge",FxiOS:"Mozilla Firefox",Version:"Apple Safari"}[m2[1]];fullVersionList.push({brand:_brand,version:padVersion(m2[2])}),-1===items.findIndex((function(s){return s.startsWith("Safari/")}))&&(webview=!0)}}else null!==(m=/Firefox\/(\d+(\.\d+)*)/.exec(versionInfo))?fullVersionList.push({brand:"Firefox",version:padVersion(m[1])}):fullVersionList.push({brand:" Not;A Brand",version:"99.0.0.0"});return uaFullVersion=fullVersionList.length>0?fullVersionList[fullVersionList.length-1]:"",{mobile:mobile,platform:platform,brands:fullVersionList.map((function(b){var pos=b.version.indexOf("."),version=-1===pos?b.version:b.version.slice(0,pos);return{brand:b.brand,version:version}})),platformVersion:platformVersion,architecture:architecture,bitness:bitness,model:"",uaFullVersion:uaFullVersion,fullVersionList:fullVersionList,webview:webview}}(navigator),Object.defineProperties(this,{_ch:{enumerable:!1}})},(r=[{key:"mobile",get:function(){return this._ch.mobile}},{key:"platform",get:function(){return this._ch.platform}},{key:"brands",get:function(){return this._ch.brands}},{key:"getHighEntropyValues",value:function(hints){var _this=this;return new Promise((function(resolve,reject){if(!Array.isArray(hints))throw new TypeError("argument hints is not an array");var hintSet=new Set(hints),data=_this._ch,obj={mobile:data.mobile,platform:data.platform,brands:data.brands};hintSet.has("architecture")&&(obj.architecture=data.architecture),hintSet.has("bitness")&&(obj.bitness=data.bitness),hintSet.has("model")&&(obj.model=data.model),hintSet.has("platformVersion")&&(obj.platformVersion=data.platformVersion),hintSet.has("uaFullVersion")&&(obj.uaFullVersion=data.uaFullVersion),hintSet.has("fullVersionList")&&(obj.fullVersionList=data.fullVersionList),resolve(obj)}))}},{key:"toJSON",value:function(){var data=this._ch;return{mobile:data.mobile,brands:data.brands}}}])&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,r,t}();function _getClientInfo(){return(_getClientInfo=_asyncToGenerator(_regenerator().m((function _callee(navigator,keys){var info,customUAData;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(info={},"https:"!==location.protocol){_context.n=4;break}if(keys||(keys=["brands","mobile","platform","platformVersion","architecture","bitness","model","fullVersionList"]),navigator.userAgentData){_context.n=2;break}return customUAData=new NavigatorUAData(navigator),_context.n=1,customUAData.getHighEntropyValues(keys);case 1:info=_context.v,_context.n=4;break;case 2:return _context.n=3,navigator.userAgentData.getHighEntropyValues(keys);case 3:info=_context.v;case 4:return _context.a(2,info)}}),_callee)})))).apply(this,arguments)}Object.defineProperty(NavigatorUAData.prototype,Symbol.toStringTag,{enumerable:!1,configurable:!0,writable:!1,value:"NavigatorUAData"}),module.exports={getClientInfo:function(_x,_x2){return _getClientInfo.apply(this,arguments)}}},{}],39:[function(require,module,exports){"use strict";var SESSION_STATUS=Object.freeze({CONNECTED:"CONNECTED",ESTABLISHED:"ESTABLISHED",DISCONNECTED:"DISCONNECTED",WARN:"WARN",FAILED:"FAILED",DEBUG:"DEBUG",APP_DATA:"APP_DATA",SEND_DATA_STATUS:"SEND_DATA_STATUS",PENDING:"PENDING",REGISTERED:"REGISTERED",UNREGISTERED:"UNREGISTERED",INCOMING_CALL:"INCOMING_CALL"}),STREAM_STATUS=Object.freeze({NEW:"NEW",PENDING:"PENDING",PUBLISHING:"PUBLISHING",PLAYING:"PLAYING",PAUSED:"PAUSED",UNPUBLISHED:"UNPUBLISHED",STOPPED:"STOPPED",FAILED:"FAILED",PLAYBACK_PROBLEM:"PLAYBACK_PROBLEM",RESIZE:"RESIZE",SNAPSHOT_COMPLETE:"SNAPSHOT_COMPLETE",NOT_ENOUGH_BANDWIDTH:"NOT_ENOUGH_BANDWIDTH"}),CALL_STATUS=Object.freeze({NEW:"NEW",RING:"RING",RING_MEDIA:"RING_MEDIA",HOLD:"HOLD",ESTABLISHED:"ESTABLISHED",FINISH:"FINISH",BUSY:"BUSY",SESSION_PROGRESS:"SESSION_PROGRESS",FAILED:"FAILED",PENDING:"PENDING",TRYING:"TRYING"}),STREAM_STATUS_INFO=Object.freeze({FAILED_BY_ICE_ERROR:"Failed by ICE error",FAILED_BY_ICE_TIMEOUT:"Failed by ICE timeout",FAILED_BY_KEEP_ALIVE:"Failed by ICE keep alive",FAILED_BY_DTLS_FINGERPRINT_ERROR:"Failed by DTLS fingerprint error",FAILED_BY_DTLS_ERROR:"Failed by DTLS error",FAILED_BY_HLS_WRITER_ERROR:"Failed by HLS writer error",FAILED_BY_RTMP_WRITER_ERROR:"Failed by RTMP writer error",FAILED_BY_RTP_ACTIVITY:"Failed by RTP activity",STOPPED_BY_SESSION_DISCONNECT:"Stopped by session disconnect",STOPPED_BY_REST_TERMINATE:"Stopped by rest /terminate",STOPPED_BY_PUBLISHER_STOP:"Stopped by publisher stop",STOPPED_BY_USER:"Stopped by user",FAILED_BY_ERROR:"Failed by error",FAILED_TO_ADD_STREAM_TO_PROXY:"Failed to add stream to proxy",DISTRIBUTOR_STOPPED:"Distributor stopped",PUBLISH_STREAM_IS_NOT_READY:"Publish stream is not ready",STREAM_NOT_FOUND:"Stream not found",STREAM_NAME_ALREADY_IN_USE:"Stream name is already in use",MEDIASESSION_ID_NULL:"MediaSessionId is null",MEDIASESSION_ID_ALREADY_IN_USE:"MediaSessionId is already in use",SESSION_NOT_READY:"Session not ready",SESSION_DOES_NOT_EXIST:"Session does not exist",RTSP_HAS_WRONG_FORMAT:"Rtsp has wrong format",FILE_HAS_WRONG_FORMAT:"File has wrong format",FAILED_TO_CONNECT_TO_RTSP_STREAM:"Failed to connect to rtsp stream",RTSP_STREAM_NOT_FOUND:"Rtsp stream not found",RTSPAGENT_SHUTDOWN:"RtspAgent shutdown",STREAM_FAILED:"Stream failed",NO_COMMON_CODECS:"No common codecs",BAD_URI:"Bad URI",GOT_EXCEPTION_WHILE_STREAMING_FILE:"Got exception while streaming file",REQUESTED_STREAM_SHUTDOWN:"Requested stream shutdown",FAILED_TO_READ_FILE:"Failed to read file",FILE_NOT_FOUND:"File not found",FAILED_TO_CONNECT_TO_ORIGIN_STREAM:"Failed to connect to origin stream",CDN_STREAM_NOT_FOUND:"CDN stream not found",FAILED_TO_GET_AGENT_STORAGE:"Failed to get agent storage",AGENT_SERVICING_ORIGIN_STREAM_IS_SHUTTING_DOWN:"Agent servicing origin stream is shutting down",TERMINATED_BY_KEEP_ALIVE:"Terminated by keep-alive",TRANSCODING_REQUIRED_BUT_DISABLED:"Transcoding required, but disabled",RESTRICTED_ACCESS:"Restricted access",NO_AVAILABLE_TRANSCODERS:"No available transcoders"}),CALL_STATUS_INFO=Object.freeze({NORMAL_CALL_CLEARING:"Normal call clearing",FAILED_BY_SESSION_CREATION:"Failed by session creation",FAILED_BY_ICE_ERROR:"Failed by ICE error",FAILED_BY_RTP_ACTIVITY:"Failed by RTP activity",FAILED_BY_RTMP_WRITER_ERROR:"Failed by RTMP writer error",FAILED_BY_DTLS_FINGERPRINT_ERROR:"Failed by DTLS fingerprint error",NO_COMMON_CODECS:"No common codecs",FAILED_BY_DTLS_ERROR:"Failed by DTLS error",FAILED_BY_ERROR:"Failed by error",FAILED_BY_REQUEST_TIMEOUT:"Failed by request timeout",TRANSCODING_REQUIRED_BUT_DISABLED:"Transcoding required, but disabled"}),ERROR_INFO=Object.freeze({NONE_OF_MEDIAPROVIDERS_AVAILABLE:"None of MediaProviders available",NONE_OF_PREFERRED_MEDIAPROVIDERS_AVAILABLE:"None of preferred MediaProviders available",FLASHPHONER_API_NOT_INITIALIZED:"Flashphoner API is not initialized",OPTIONS_URLSERVER_MUST_BE_PROVIDED:"options.urlServer must be provided",INVALID_SESSION_STATE:"Invalid session state",OPTIONS_MUST_BE_PROVIDED:"options must be provided",INVALID_CALL_STATE:"Invalid call state",EVENT_CANT_BE_NULL:"Event can't be null",CALLBACK_NEEDS_TO_BE_A_VALID_FUNCTION:"Callback needs to be a valid function",OPTIONS_NAME_MUST_BE_PROVIDED:"options.name must be provided",CAN_NOT_SWITCH_CAM:"Number of cams is less than 2 or camera is already used by other application",CAN_NOT_SWITCH_MIC:"Number of mics is less than 2 or microphone is already used by other application",CAN_NOT_SET_RESOLUTION:"Cannot switch a published stream resolution",CAN_NOT_GET_STATS:"Cannot get PeerConnection stats",LOCAL_ERROR:"Local error"}),MEDIA_DEVICE_KIND=Object.freeze({OUTPUT:"output",INPUT:"input",ALL:"all"}),TRANSPORT_TYPE=Object.freeze({UDP:"UDP",TCP:"TCP"}),CONNECTION_QUALITY=Object.freeze({PERFECT:"PERFECT",GOOD:"GOOD",BAD:"BAD",UNKNOWN:"UNKNOWN",UPDATE:"UPDATE"}),STREAM_EVENT_TYPE=Object.freeze({AUDIO_MUTED:"audioMuted",AUDIO_UNMUTED:"audioUnmuted",VIDEO_MUTED:"videoMuted",VIDEO_UNMUTED:"videoUnmuted",DATA:"data",SNAPSHOT_COMPLETED:"snapshotCompleted",SNAPSHOT_FAILED:"snapshotFailed",RESIZE:"resize",NOT_ENOUGH_BANDWIDTH:"notEnoughBandwidth"}),CONTENT_HINT_TYPE=Object.freeze({MOTION:"motion",DETAIL:"detail",TEXT:"text"});module.exports={SESSION_STATUS:SESSION_STATUS,STREAM_STATUS:STREAM_STATUS,CALL_STATUS:CALL_STATUS,STREAM_STATUS_INFO:STREAM_STATUS_INFO,CALL_STATUS_INFO:CALL_STATUS_INFO,ERROR_INFO:ERROR_INFO,MEDIA_DEVICE_KIND:MEDIA_DEVICE_KIND,TRANSPORT_TYPE:TRANSPORT_TYPE,CONNECTION_QUALITY:CONNECTION_QUALITY,STREAM_EVENT:"STREAM_EVENT",STREAM_EVENT_TYPE:STREAM_EVENT_TYPE,CONTENT_HINT_TYPE:CONTENT_HINT_TYPE}},{}],40:[function(require,module,exports){"use strict";function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var coreLogger,clientUAData,disableConnectionQualityCalculation,uuid_v1=require("uuid").v1,constants=require("./constants"),util=require("./util"),LoggerObject=require("./util").logger,clientInfo=require("./client-info"),StatsCollector=require("./stats-collector"),_Promise=require("promise-polyfill"),KalmanFilter=require("kalmanjs"),browserDetails=require("webrtc-adapter").default.browserDetails,loggerConf={push:!1,severity:"INFO"},isUsingTemasysPlugin=!1,SESSION_STATUS=constants.SESSION_STATUS,STREAM_EVENT=constants.STREAM_EVENT,STREAM_EVENT_TYPE=constants.STREAM_EVENT_TYPE,STREAM_STATUS=constants.STREAM_STATUS,CALL_STATUS=constants.CALL_STATUS,CONNECTION_QUALITY=constants.CONNECTION_QUALITY,ERROR_INFO=constants.ERROR_INFO,MediaProvider={},sessions={},initialized=!1,init=function(){var _ref=_asyncToGenerator(_regenerator().m((function _callee(options){var waitingTemasys,audioContext,webRtcProvider,enableGainNode,webRtcConf,mediaSourceMediaProvider,mseConf,websocketProvider,wsConf,_MediaProvider,p,newMediaProvider,i,pMP;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(initialized){_context.n=6;break}options||(options={}),coreLogger=createLogger(options.logger),waitingTemasys=!1;try{audioContext=new(window.AudioContext||window.webkitAudioContext)}catch(e){console.warn("Failed to create audio context")}if(disableConnectionQualityCalculation=options.disableConnectionQualityCalculation,(webRtcProvider=require("./webrtc-media-provider"))&&webRtcProvider.hasOwnProperty("available")&&webRtcProvider.available()?(MediaProvider.WebRTC=webRtcProvider,enableGainNode=!util.Browser.isSamsungBrowser()&&!util.Browser.isAndroidFirefox()&&options.createMicGainNode,webRtcConf={constraints:options.constraints||getDefaultMediaConstraints(),extensionId:options.screenSharingExtensionId,audioContext:audioContext,logger:coreLogger,createMicGainNode:enableGainNode},webRtcProvider.configure(webRtcConf)):(webRtcProvider=require("./temasys-media-provider"))&&webRtcProvider.hasOwnProperty("available")&&AdapterJS&&(waitingTemasys=!0,AdapterJS.webRTCReady((function(isUsingPlugin){if(isUsingTemasysPlugin=isUsingPlugin,isUsingPlugin||webRtcProvider.available()){MediaProvider.WebRTC=webRtcProvider;var webRtcConf={constraints:options.constraints||getDefaultMediaConstraints(),extensionId:options.screenSharingExtensionId,logger:coreLogger};webRtcProvider.configure(webRtcConf);var _MediaProvider={};for(var p in _MediaProvider.WebRTC=MediaProvider.WebRTC,MediaProvider)_MediaProvider[p]=MediaProvider[p];MediaProvider=_MediaProvider}options.mediaProvidersReadyCallback&&options.mediaProvidersReadyCallback(Object.keys(MediaProvider))}))),null,(mediaSourceMediaProvider=require("./media-source-media-provider"))&&mediaSourceMediaProvider.hasOwnProperty("available")&&mediaSourceMediaProvider.available()&&(MediaProvider.MSE=mediaSourceMediaProvider,mseConf={audioContext:audioContext,browserDetails:browserDetails.browser},mediaSourceMediaProvider.configure(mseConf)),(websocketProvider=require("./websocket-media-provider"))&&websocketProvider.hasOwnProperty("available")&&websocketProvider.available(audioContext)&&(MediaProvider.WSPlayer=websocketProvider,wsConf={receiverLocation:options.receiverLocation,decoderLocation:options.decoderLocation,audioContext:audioContext,logger:coreLogger},websocketProvider.configure(wsConf)),0!=getMediaProviders().length){_context.n=1;break}throw new Error("None of MediaProviders available");case 1:if(options.preferredMediaProvider)if(MediaProvider.hasOwnProperty(options.preferredMediaProvider)){if(getMediaProviders()[0]!=options.preferredMediaProvider){for(p in(_MediaProvider={})[options.preferredMediaProvider]=MediaProvider[options.preferredMediaProvider],MediaProvider)_MediaProvider[p]=MediaProvider[p];MediaProvider=_MediaProvider}}else corelogger.warn("core","Preferred media provider is not available.");case 2:if(!(options.preferredMediaProviders&&options.preferredMediaProviders.length>0)){_context.n=4;break}for(i in newMediaProvider={},options.preferredMediaProviders)options.preferredMediaProviders.hasOwnProperty(i)&&(pMP=options.preferredMediaProviders[i],MediaProvider.hasOwnProperty(pMP)&&(newMediaProvider[pMP]=MediaProvider[pMP]));if(!util.isEmptyObject(newMediaProvider)){_context.n=3;break}throw new Error("None of preferred MediaProviders available");case 3:MediaProvider=newMediaProvider;case 4:if(!waitingTemasys&&options.mediaProvidersReadyCallback&&options.mediaProvidersReadyCallback(Object.keys(MediaProvider)),coreLogger.info("core","Initialized"),initialized=!0,void 0!==options.collectClientInfo&&!options.collectClientInfo){_context.n=6;break}return _context.n=5,clientInfo.getClientInfo(window.navigator);case 5:clientUAData=_context.v,coreLogger.info("core","Client system data: "+JSON.stringify(clientUAData));case 6:return _context.a(2)}}),_callee)})));return function(_x){return _ref.apply(this,arguments)}}(),getMediaProviders=function(){return Object.keys(MediaProvider)},getDefaultMediaConstraints=function(){return"safari"==browserDetails.browser?{audio:!0,video:{width:{min:320,max:640},height:{min:180,max:360}}}:{audio:!0,video:{width:320,height:240}}};function getConstraintsProperty(constraints,property,defaultValue){if(!constraints||!property)return defaultValue;var res,properties=property.split(".");for(var prop in constraints)if(prop==properties[0])res=constraints[prop],properties.length>1&&(res=getConstraintsProperty(constraints[prop],properties[1],defaultValue));else if("object"===_typeof(constraints[prop]))for(var p in constraints[prop])p==property&&(res=constraints[prop][p]);return"boolean"==typeof res?res:res||defaultValue}var releaseLocalMedia=function(display,mediaProvider){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].releaseMedia(display)},getLoggerConf=function(loggerOptions){var conf=loggerOptions||loggerConf;return null!==loggerOptions&&(conf.enableLogs=!0),conf},createLogger=function(loggerOptions){var parentLogger=arguments.length>1&&void 0!==arguments[1]?arguments[1]:coreLogger,newLogger=parentLogger;if(void 0===newLogger||null!=loggerOptions){var loggerConf=getLoggerConf(loggerOptions);(newLogger=new LoggerObject).init(loggerConf.severity||"INFO",loggerConf.push||!1,loggerConf.customLogger,loggerConf.enableLogs)}return newLogger};module.exports={init:init,isUsingTemasys:function(){return isUsingTemasysPlugin},getMediaProviders:getMediaProviders,getMediaDevices:function(mediaProvider,labels,kind,deviceConstraints){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].listDevices(labels,kind,deviceConstraints)},getMediaAccess:function(constraints,display,mediaProvider,disableConstraintsNormalization){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].getMediaAccess(constraints,display,disableConstraintsNormalization)},releaseLocalMedia:releaseLocalMedia,getSessions:function(){return util.copyObjectToArray(sessions)},getSession:function(id){return sessions[id]},createSession:function(options){if(!initialized)throw new Error("Flashphoner API is not initialized");if(!options||!options.urlServer)throw new TypeError("options.urlServer must be provided");var connectionTimeout,cConfig,sipConfig,sessionLogger=createLogger(options.logger),logger=sessionLogger,id_=uuid_v1(),sessionStatus=SESSION_STATUS.PENDING,urlServer=options.urlServer,lbUrl=options.lbUrl,flashProto=options.flashProto||"rtmfp",flashPort=options.flashPort||1935,appKey=options.appKey||"defaultApp",mediaOptions=options.mediaOptions,keepAlive=options.keepAlive,timeout=options.timeout,sendClientInfo=void 0===options.sendClientInfo||options.sendClientInfo,wsPingSender=new function(interval){return this.interval=interval||0,this.intervalId=null,this.start=function(){this.interval>0&&(this.intervalId=setInterval((function(){send("ping",null)}),this.interval))},this.stop=function(){this.intervalId&&clearInterval(this.intervalId)},this}(options.pingInterval||0),wsPingReceiver=new function(receiveProbes,probesInterval){return this.maxPings=receiveProbes||0,this.interval=probesInterval||0,this.intervalId=null,this.pingsMissing=0,this.start=function(){if(this.maxPings>0&&this.interval>0){var receiver=this;this.intervalId=setInterval((function(){receiver.checkPingsReceived()}),this.interval)}},this.stop=function(){this.intervalId&&clearInterval(this.intervalId),this.pingsMissing=0},this.checkPingsReceived=function(){this.pingsMissing++,this.pingsMissing>=this.maxPings&&this.failure()},this.success=function(){this.pingsMissing=0},this.failure=function(){logger.info("core","Missing "+this.pingsMissing+" pings from server, connection seems to be down"),onSessionStatusChange(SESSION_STATUS.FAILED),wsConnection.close()},this}(options.receiveProbes||0,options.probesInterval||0);options.sipOptions&&(sipConfig={sipLogin:options.sipOptions.login,sipAuthenticationName:options.sipOptions.authenticationName,sipPassword:options.sipOptions.password,sipDomain:options.sipOptions.domain,sipOutboundProxy:options.sipOptions.outboundProxy,sipProxy:options.sipOptions.proxy,sipPort:options.sipOptions.port,sipRegisterRequired:options.sipOptions.registerRequired});var wsConnection,webRTCMetricsServerDescription,url,request,authToken=options.authToken,streams={},calls={},mediaConnections={},streamEventRefreshHandlers={},streamRefreshHandlers={},callRefreshHandlers={},session={},callbacks={};lbUrl?(url=lbUrl,(request=new XMLHttpRequest).open("GET",url,!0),request.timeout=5e3,request.ontimeout=function(){logger.warn("core","Timeout during geting url from balancer!"),createWS(urlServer)},request.error=function(){logger.warn("core","Error during geting url from balancer!"),createWS(urlServer)},request.onload=function(e){if(200==request.status&&4==request.readyState){var result=JSON.parse(request.responseText);urlServer=-1!==urlServer.indexOf("wss://")?"wss://"+result.server+":"+result.wss:"ws://"+result.server+":"+result.ws,flashPort=result.flash,logger.debug("core","Got url from load balancer "+result.server),createWS(urlServer)}},request.send()):createWS(urlServer);var remoteSdpCache={};function createWS(url){wsConnection=new WebSocket(url),null!=timeout&&timeout>0&&(connectionTimeout=setTimeout((function(){0==wsConnection.readyState&&(logger.warn("core","WS connection timeout"),wsConnection.close())}),timeout)),wsConnection.onerror=function(){onSessionStatusChange(SESSION_STATUS.FAILED)},wsConnection.onclose=function(){sessionStatus!==SESSION_STATUS.FAILED&&onSessionStatusChange(SESSION_STATUS.DISCONNECTED)},wsConnection.onopen=function(){onSessionStatusChange(SESSION_STATUS.CONNECTED),clearTimeout(connectionTimeout),cConfig={appKey:appKey,mediaProviders:Object.keys(MediaProvider),keepAlive:keepAlive,authToken:authToken,clientVersion:"2.0",clientOSVersion:window.navigator.appVersion,clientBrowserVersion:window.navigator.userAgent,msePacketizationVersion:2,custom:options.custom},sendClientInfo&&clientUAData&&(cConfig.clientInfo=clientUAData),sipConfig&&util.copyObjectPropsToAnotherObject(sipConfig,cConfig),send("connection",cConfig),logger.setConnection(wsConnection),wsPingSender.start(),wsPingReceiver.start()},wsConnection.onmessage=function(event){var data={};if(event.data instanceof Blob)data.message="binaryData";else var obj=(data=JSON.parse(event.data)).data[0];switch(data.message){case"ping":logger.debug("core","<<< ping"),send("pong",null),logger.debug("core",">>> pong");break;case"getUserData":authToken=obj.authToken,cConfig=obj,webRTCMetricsServerDescription=obj.webRTCMetricsServerDescription,onSessionStatusChange(SESSION_STATUS.ESTABLISHED,obj);break;case"setRemoteSDP":var mediaSessionId=data.data[0],sdp=data.data[1];streamRefreshHandlers[mediaSessionId]?streamRefreshHandlers[mediaSessionId](null,sdp):callRefreshHandlers[mediaSessionId]?callRefreshHandlers[mediaSessionId](null,sdp):(remoteSdpCache[mediaSessionId]=sdp,logger.info("core","Media not found, id "+mediaSessionId));break;case"notifyVideoFormat":case"notifyStreamStatusEvent":streamRefreshHandlers[obj.mediaSessionId]&&streamRefreshHandlers[obj.mediaSessionId](obj);break;case"notifyStreamEvent":streamEventRefreshHandlers[obj.mediaSessionId]&&streamEventRefreshHandlers[obj.mediaSessionId](obj);break;case"DataStatusEvent":restAppCommunicator.resolveData(obj);break;case"OnDataEvent":callbacks[SESSION_STATUS.APP_DATA]&&callbacks[SESSION_STATUS.APP_DATA](obj);break;case"fail":obj.apiMethod&&"StreamStatusEvent"==obj.apiMethod&&streamRefreshHandlers[obj.id]&&streamRefreshHandlers[obj.id](obj),callbacks[SESSION_STATUS.WARN]&&callbacks[SESSION_STATUS.WARN](obj);break;case"registered":onSessionStatusChange(SESSION_STATUS.REGISTERED);break;case"notifyAudioCodec":mediaSessionId=data.data[0];var codec=data.data[1];callRefreshHandlers[mediaSessionId]&&callRefreshHandlers[mediaSessionId](null,null,codec);break;case"notifyTransferEvent":callRefreshHandlers[obj.callId](null,null,null,obj);break;case"notifyTryingResponse":case"hold":case"ring":case"talk":case"finish":callRefreshHandlers[obj.callId]&&callRefreshHandlers[obj.callId](obj);break;case"notifyIncomingCall":callRefreshHandlers[obj.callId]&&logger.error("core","Call already exists, id "+obj.callId),callbacks[SESSION_STATUS.INCOMING_CALL]&&callbacks[SESSION_STATUS.INCOMING_CALL](createCall(obj));break;case"notifySessionDebugEvent":logger.info("core","Session debug status "+obj.status),callbacks[SESSION_STATUS.DEBUG]&&callbacks[SESSION_STATUS.DEBUG](obj);break;case"availableStream":var availableStream={};availableStream.mediaSessionId=obj.id,availableStream.available=obj.status,availableStream.reason=obj.info,streamRefreshHandlers[availableStream.mediaSessionId]&&streamRefreshHandlers[availableStream.mediaSessionId](availableStream);break;case"outboundVideoRate":case"inboundVideoRate":streamRefreshHandlers[obj.mediaSessionId]&&(obj.status=data.message,streamRefreshHandlers[obj.mediaSessionId](obj));break;case"webRTCMetricsDescriptionUpdate":if(obj.ids)obj.ids.forEach((function(id){streamRefreshHandlers[id]&&streamRefreshHandlers[id](obj)}));else{obj.compression&&(webRTCMetricsServerDescription.compression=obj.compression),obj.batchSize&&(webRTCMetricsServerDescription.batchSize=obj.batchSize),obj.sampling&&(webRTCMetricsServerDescription.sampling=obj.sampling),obj.types&&(webRTCMetricsServerDescription.types=obj.types),obj.collect&&(webRTCMetricsServerDescription.collect=obj.collect);for(var _i=0,_Object$entries=Object.entries(streamRefreshHandlers);_i<_Object$entries.length;_i++){var _Object$entries$_i=_slicedToArray(_Object$entries[_i],2);_Object$entries$_i[0];(0,_Object$entries$_i[1])(obj)}}break;default:logger.info("core","Unknown server message "+data.message)}logger.debug("core","Reset missing pings counter by "+data.message+" message"),wsPingReceiver.success()}}function send(message,data){wsConnection.readyState===WebSocket.OPEN&&wsConnection.send(JSON.stringify({message:message,data:[data]}))}function onSessionStatusChange(newStatus,obj){if((sessionStatus=newStatus)==SESSION_STATUS.DISCONNECTED||sessionStatus==SESSION_STATUS.FAILED){for(var prop in wsPingSender.stop(),wsPingReceiver.stop(),streamRefreshHandlers)streamRefreshHandlers.hasOwnProperty(prop)&&"function"==typeof streamRefreshHandlers[prop]&&streamRefreshHandlers[prop]({status:STREAM_STATUS.FAILED});delete sessions[id_]}callbacks[sessionStatus]&&callbacks[sessionStatus](session,obj)}var createCall=function(options){if(sessionStatus!==SESSION_STATUS.REGISTERED&&sessionStatus!==SESSION_STATUS.ESTABLISHED)throw new Error("Invalid session state "+sessionStatus);if(!options)throw new TypeError("options must be provided");var mediaConnection,info_,errorInfo_,audioOutputId,callLogger=createLogger(options.logger,sessionLogger),logger=callLogger,login="clickToCallApp"==appKey?"":cConfig.sipLogin,caller_=options.incoming?options.caller:login,callee_=options.callee,visibleName_=options.visibleName||login,id_=options.callId||uuid_v1(),mediaProvider=options.mediaProvider||getMediaProviders()[0],localDisplay=options.localVideoDisplay,remoteDisplay=options.remoteVideoDisplay;if(options.constraints)var constraints=options.constraints;if(options.disableConstraintsNormalization)var disableConstraintsNormalization=options.disableConstraintsNormalization;var audioProperty=getConstraintsProperty(constraints,"audio",void 0);"object"===_typeof(audioProperty)&&(audioOutputId=getConstraintsProperty(audioProperty,"outputId",0));var stripCodecs=options.stripCodecs||[],receiveAudio="undefined"==typeof options.receiveAudio||options.receiveAudio,receiveVideo="undefined"==typeof options.receiveVideo||options.receiveVideo,cacheLocalResources=options.cacheLocalResources,status_=CALL_STATUS.NEW,callbacks={},hasTransferredCall=!1,sdpHook=options.sdpHook,sipSDP=options.sipSDP,videoContentHint=(options.sipHeaders,options.videoContentHint),useControls=options.useControls,collectDeviceInfo=void 0===options.collectDeviceInfo||options.collectDeviceInfo,minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0),call={};callRefreshHandlers[id_]=function(callInfo,sdp,codec,transfer){if(transfer)return mediaConnections[id_]||(mediaConnections[id_]=mediaConnection),void("COMPLETED"==transfer.status&&delete mediaConnections[id_]);if(!mediaConnection&&0!=Object.keys(mediaConnections).length)for(var mc in mediaConnections)mediaConnection=mediaConnections[mc],hasTransferredCall=!0,delete mediaConnections[mc];if(codec)"Flash"==mediaProvider&&mediaConnection.changeAudioCodec(codec.name);else{if(sdp&&""!==sdp)return sdp=sdpHookHandler(sdp,sdpHook),sdp=util.setPublishingBitrate(sdp,mediaConnection,minBitrate,maxBitrate),void mediaConnection.setRemoteSdp(sdp,hasTransferredCall,id_).then((function(){}));var event=callInfo.status;status_=event,event!=CALL_STATUS.FAILED&&event!=CALL_STATUS.FINISH&&event!=CALL_STATUS.BUSY||(delete calls[id_],delete callRefreshHandlers[id_],0==Object.keys(calls).length&&mediaConnection&&mediaConnection.close(cacheLocalResources)),callbacks[event]&&callbacks[event](call)}};var hangup=function(){if(status_!=CALL_STATUS.NEW){if(status_==CALL_STATUS.PENDING)return cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider),callRefreshHandlers[id_]({status:CALL_STATUS.FAILED}),void(options.incoming&&send("hangup",{callId:id_}));send("hangup",{callId:id_}),mediaConnection&&mediaConnection.close(cacheLocalResources)}else callRefreshHandlers[id_]({status:CALL_STATUS.FAILED})};return call.call=function(){if(status_!==CALL_STATUS.NEW)throw new Error("Invalid call state");status_=CALL_STATUS.PENDING;MediaProvider[mediaProvider].getMediaAccess(constraints,localDisplay,disableConstraintsNormalization).then((function(){status_!=CALL_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,localDisplay:localDisplay,remoteDisplay:remoteDisplay,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,bidirectional:!0,login:login,constraints:constraints,connectionConfig:mediaOptions,audioOutputId:audioOutputId,videoContentHint:videoContentHint,useControls:useControls,logger:logger}).then((function(newConnection){return(mediaConnection=newConnection).createOffer({sendAudio:!0,sendVideo:!0,receiveAudio:receiveAudio,receiveVideo:receiveVideo,stripCodecs:stripCodecs})})).then((function(offer){var callData={callId:id_,incoming:!1,hasVideo:offer.hasVideo,hasAudio:offer.hasAudio,status:status_,mediaProvider:mediaProvider,sdp:offer.sdp,sipSDP:sipSDP,caller:login,callee:callee_,custom:options.custom,visibleName:visibleName_};collectDeviceInfo&&(callData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],localDisplay)),send("call",callData)})):cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider)})).catch((function(error){logger.error("core",error),status_=CALL_STATUS.FAILED,info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,callRefreshHandlers[id_]({status:CALL_STATUS.FAILED}),hangup()}))},call.answer=function(answerOptions){if(status_!==CALL_STATUS.NEW&&status_!==CALL_STATUS.RING)throw new Error("Invalid call state");var sdp;localDisplay=answerOptions.localVideoDisplay,remoteDisplay=answerOptions.remoteVideoDisplay,constraints=answerOptions.constraints||getDefaultMediaConstraints(),status_=CALL_STATUS.PENDING;var sdpHook=answerOptions.sdpHook,minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0);if(sipSDP=answerOptions.sipSDP,answerOptions.sipHeaders,!remoteSdpCache[id_])throw logger.error("core","No remote sdp available"),new Error("No remote sdp available");sdp=sdpHookHandler(remoteSdpCache[id_],sdpHook),sdp=util.setPublishingBitrate(sdp,null,minBitrate,maxBitrate),delete remoteSdpCache[id_],0==util.SDP.matchPrefix(sdp,"m=video").length&&(constraints.video=!1);var stripCodecs=answerOptions.stripCodecs||[];MediaProvider[mediaProvider].getMediaAccess(constraints,localDisplay,disableConstraintsNormalization).then((function(){status_!=CALL_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,localDisplay:localDisplay,remoteDisplay:remoteDisplay,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,bidirectional:!0,login:cConfig.sipLogin,constraints:constraints,connectionConfig:mediaOptions,audioOutputId:audioOutputId,useControls:useControls}).then((function(newConnection){return(mediaConnection=newConnection).setPublishingBitrate(minBitrate,maxBitrate),mediaConnection.setRemoteSdp(sdp)})).then((function(){return mediaConnection.createAnswer({receiveAudio:options.receiveAudio,receiveVideo:options.receiveVideo,stripCodecs:stripCodecs})})).then((function(sdp){if(status_!=CALL_STATUS.FINISH&&status_!=CALL_STATUS.FAILED){var callData={callId:id_,incoming:!0,hasVideo:!0,hasAudio:!0,status:status_,mediaProvider:mediaProvider,sdp:sdp,sipSDP:sipSDP,caller:cConfig.login,callee:callee_,custom:options.custom};collectDeviceInfo&&(callData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],localDisplay)),send("answer",callData)}else hangup()})):cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider)})).catch((function(error){logger.error("core",error),info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,status_=CALL_STATUS.FAILED,callRefreshHandlers[id_]({status:CALL_STATUS.FAILED})}))},call.hangup=hangup,call.id=function(){return id_},call.getInfo=function(){return info_},call.getErrorInfo=function(){return errorInfo_},call.status=function(){return status_},call.getStats=function(callbackFn,nativeStats){mediaConnection&&mediaConnection.getStats(callbackFn,nativeStats)},call.setAudioOutputId=function(id){if(audioOutputId=id,mediaConnection&&mediaConnection.setAudioOutputId)return mediaConnection.setAudioOutputId(id)},call.setVolume=function(volume){mediaConnection&&mediaConnection.setVolume(volume)},call.getVolume=function(){return mediaConnection?mediaConnection.getVolume():-1},call.muteAudio=function(){mediaConnection&&mediaConnection.muteAudio()},call.unmuteAudio=function(){mediaConnection&&mediaConnection.unmuteAudio()},call.isAudioMuted=function(){return!mediaConnection||mediaConnection.isAudioMuted()},call.muteVideo=function(){mediaConnection&&mediaConnection.muteVideo()},call.unmuteVideo=function(){mediaConnection&&mediaConnection.unmuteVideo()},call.isVideoMuted=function(){return!mediaConnection||mediaConnection.isVideoMuted()},call.caller=function(){return caller_},call.callee=function(){return callee_},call.visibleName=function(){return visibleName_},call.hold=function(){send("hold",{callId:id_})},call.holdForTransfer=function(){send("hold",{callId:id_,holdForTransfer:!0})},call.unhold=function(){send("unhold",{callId:id_})},call.sendDTMF=function(number,type){send("sendDtmf",{callId:id_,type:type||"RFC2833",dtmf:number})},call.transfer=function(target){send("transfer",{callId:id_,target:target})},call.on=function(event,callback){if(!event)throw new TypeError("Event can't be null");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,call},call.switchCam=function(deviceId){if(status_!==CALL_STATUS.ESTABLISHED&&!constraints.video&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchCam(deviceId)},call.switchMic=function(deviceId){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchMic(deviceId)},call.switchToScreen=function(source,woExtension){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchToScreen(source,woExtension)},call.switchToCam=function(){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");mediaConnection.switchToCam()},call.getLogger=function(){return callLogger},calls[id_]=call,call},restAppCommunicator=function(){var pending={},exports={sendData:function(data){return new _Promise((function(resolve,reject){var obj={operationId:uuid_v1(),payload:data};pending[obj.operationId]={FAILED:function(info){reject(info)},ACCEPTED:function(info){resolve(info)}},send("sendData",obj)}))},resolveData:function(data){if(pending[data.operationId]){var handler=pending[data.operationId];delete pending[data.operationId],delete data.operationId,handler[data.status](data)}}};return exports}(),sdpHookHandler=function(sdp,sdpHook){if(null!=sdpHook&&"function"==typeof sdpHook){var newSdp=sdpHook({sdpString:sdp});return null!=newSdp&&""!=newSdp?newSdp:sdp}return sdp},collectLocalMediaInfo=function(mediaProvider,display){var videoCams=[],mics=[];mediaProvider.videoCams&&mediaProvider.videoCams.forEach((function(device){videoCams.push({id:device.id,label:encodeURI(device.label),type:device.type})})),mediaProvider.mics&&mediaProvider.mics.forEach((function(device){mics.push({id:device.id,label:encodeURI(device.label),type:device.type})})),videoCams.length&&logger.info("core","Video inputs available: "+JSON.stringify(videoCams)),mics.length&&logger.info("core","Audio inputs available: "+JSON.stringify(mics));var localVideo,audioTracks=[],videoTracks=[];return mediaProvider.getCacheInstance&&(localVideo=mediaProvider.getCacheInstance(display)),!localVideo&&mediaProvider.getVideoElement&&(localVideo=mediaProvider.getVideoElement(display)),localVideo&&localVideo.srcObject&&(localVideo.srcObject.getAudioTracks().forEach((function(track){var device=track.label;"MediaStreamAudioDestinationNode"===device&&mediaProvider.getAudioSourceDevice&&(device=mediaProvider.getAudioSourceDevice()),audioTracks.push({trackId:track.id,device:encodeURI(device)})})),localVideo.srcObject.getVideoTracks().forEach((function(track){videoTracks.push({trackId:track.id,device:encodeURI(track.label)})}))),videoTracks.length&&logger.info("core","Video tracks captured: "+JSON.stringify(videoTracks)),audioTracks.length&&logger.info("core","Audio tracks captured: "+JSON.stringify(audioTracks)),{devices:{video:videoCams,audio:mics},tracks:{video:videoTracks,audio:audioTracks}}};return session.id=function(){return id_},session.status=function(){return sessionStatus},session.getServerUrl=function(){return urlServer},session.createStream=function(options){var availableCallbacks=[];if(sessionStatus!==SESSION_STATUS.ESTABLISHED)throw new Error("Invalid session state "+sessionStatus);if(!options)throw new TypeError("options must be provided");if(!options.name)throw new TypeError("options.name must be provided");var mediaConnection,streamLogger=createLogger(options.logger,sessionLogger),logger=streamLogger,clientKf=new KalmanFilter,serverKf=new KalmanFilter,id_=uuid_v1(),name_=options.name,mediaProvider=options.mediaProvider||getMediaProviders()[0],display=options.display;if(options.constraints&&0!=Object.keys(options.constraints).length)var constraints=options.constraints;if(options.disableConstraintsNormalization)var disableConstraintsNormalization=options.disableConstraintsNormalization;var receiveAudio,audioOutputId,receiveVideo,mediaConnectionConstraints=options.mediaConnectionConstraints,audioProperty=getConstraintsProperty(constraints,"audio",void 0);if("boolean"==typeof audioProperty)receiveAudio=audioProperty;else if("object"===_typeof(audioProperty)){receiveAudio=!0;var _stereo=getConstraintsProperty(audioProperty,"stereo",0),_bitrate=getConstraintsProperty(audioProperty,"bitrate",0),_fec=getConstraintsProperty(audioProperty,"fec",0);audioOutputId=getConstraintsProperty(audioProperty,"outputId",0);var _codecOptions="";_bitrate&&(_codecOptions+="maxaveragebitrate="+_bitrate+";"),_stereo&&(_codecOptions+="stereo=1;sprop-stereo=1;"),_fec&&(_codecOptions+="useinbandfec=1;")}else receiveAudio="undefined"==typeof options.receiveAudio||options.receiveAudio;var videoProperty=getConstraintsProperty(constraints,"video",void 0);receiveVideo="boolean"==typeof videoProperty?videoProperty:"object"===_typeof(videoProperty)||("undefined"==typeof options.receiveVideo||options.receiveVideo);var bitrate=getConstraintsProperty(constraints,"video.bitrate",0),minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0),quality=getConstraintsProperty(constraints,"video.quality",0);quality>100&&(quality=100);var info_,errorInfo_,audioState_,videoState_,connectionQuality,playWidth="undefined"!=typeof options.playWidth?options.playWidth:getConstraintsProperty(constraints,"video.width",0),playHeight="undefined"!=typeof options.playHeight?options.playHeight:getConstraintsProperty(constraints,"video.height",0),stripCodecs=options.stripCodecs||[],resolution={},published_=!1,record_=options.record||!1,recordFileName=null,cacheLocalResources=options.cacheLocalResources,status_=STREAM_STATUS.NEW,rtmpUrl=options.rtmpUrl,remoteBitrate=-1,networkBandwidth=-1,sdpHook=options.sdpHook,transportType=options.transport,cvoExtension=options.cvoExtension,remoteVideo=options.remoteVideo,callbacks={},playoutDelay=options.playoutDelay,useCanvasMediaStream=options.useCanvasMediaStream,videoContentHint=options.videoContentHint,unmutePlayOnStart=options.unmutePlayOnStart,useControls=options.useControls,collectDeviceInfo=void 0===options.collectDeviceInfo||options.collectDeviceInfo,videoBytes=0,statsCollector=null,stream={};streamEventRefreshHandlers[id_]=function(streamEvent){if(streamEvent.type==STREAM_EVENT_TYPE.NOT_ENOUGH_BANDWIDTH){var info=streamEvent.payload.info.split("/");remoteBitrate=info[0],networkBandwidth=info[1]}else streamEvent.type==STREAM_EVENT_TYPE.RESIZE&&(resolution.width=streamEvent.payload.streamerVideoWidth,resolution.height=streamEvent.payload.streamerVideoHeight);callbacks[STREAM_EVENT]&&callbacks[STREAM_EVENT](streamEvent)},streamRefreshHandlers[id_]=function(streamInfo,sdp){if(sdp&&""!==sdp){var _sdp=sdp;return _codecOptions&&(_sdp=util.SDP.writeFmtp(sdp,_codecOptions,"opus")),_sdp=sdpHookHandler(_sdp,sdpHook),_sdp=util.setPublishingBitrate(_sdp,mediaConnection,minBitrate,maxBitrate),void mediaConnection.setRemoteSdp(_sdp).then((function(){}))}if(void 0===streamInfo.available){var event=streamInfo.status;if("inboundVideoRate"!==event&&"outboundVideoRate"!==event){if(event===STREAM_EVENT)return streamInfo.mediaSessionId||(streamInfo.mediaSessionId=id_),void streamEventRefreshHandlers[id_](streamInfo);if(event===STREAM_STATUS.RESIZE)resolution.width=streamInfo.streamerVideoWidth,resolution.height=streamInfo.streamerVideoHeight;else if(event===STREAM_STATUS.SNAPSHOT_COMPLETE);else if(event===STREAM_STATUS.NOT_ENOUGH_BANDWIDTH){var info=streamInfo.info.split("/");remoteBitrate=info[0],networkBandwidth=info[1]}else status_=event;streamInfo.audioState&&(audioState_=streamInfo.audioState),streamInfo.videoState&&(videoState_=streamInfo.videoState),streamInfo.info&&(info_=streamInfo.info),event!==STREAM_STATUS.FAILED&&event!==STREAM_STATUS.STOPPED&&event!==STREAM_STATUS.UNPUBLISHED||(delete streams[id_],delete streamRefreshHandlers[id_],delete streamEventRefreshHandlers[id_],mediaConnection&&mediaConnection.close(cacheLocalResources),statsCollector&&(statsCollector.stop(),statsCollector=null)),record_&&"undefined"!=typeof streamInfo.recordName&&(recordFileName=streamInfo.recordName),event!==STREAM_STATUS.PUBLISHING&&event!==STREAM_STATUS.PLAYING||webRTCMetricsServerDescription&&!statsCollector&&(statsCollector=StatsCollector.StreamStatsCollector(webRTCMetricsServerDescription,id_,mediaConnection,wsConnection,logger)).start(),!streamInfo.status&&void 0!==streamInfo.collect&&statsCollector&&statsCollector.update(streamInfo),callbacks[event]&&callbacks[event](stream)}else detectConnectionQuality(event,streamInfo)}else{for(var i=0;i<availableCallbacks.length;i++)info_=streamInfo.reason,"true"==streamInfo.available?availableCallbacks[i].resolve(stream):availableCallbacks[i].reject(stream);availableCallbacks=[]}};var detectConnectionQuality=function(event,streamInfo){disableConnectionQualityCalculation||mediaConnection.getStats((function(stats){var bytesSentReceived=0;if(stats)if("outboundVideoRate"==event&&stats.inboundStream&&stats.inboundStream.video&&stats.inboundStream.video.bytesReceived>0)bytesSentReceived=stats.inboundStream.video.bytesReceived;else{if(!(stats.outboundStream&&stats.outboundStream.video&&stats.outboundStream.video.bytesSent>0))return;bytesSentReceived=stats.outboundStream.video.bytesSent}if(videoBytes){var currentVideoRate=8*(bytesSentReceived-videoBytes);if(0!=currentVideoRate){var currentQuality,clientFiltered=clientKf.filter(currentVideoRate),serverFiltered=serverKf.filter(streamInfo.videoRate),videoRateDifference=100*Math.abs((serverFiltered-clientFiltered)/((serverFiltered+clientFiltered)/2));currentQuality=serverFiltered<5e4||clientFiltered<5e4?videoRateDifference>150?CONNECTION_QUALITY.BAD:CONNECTION_QUALITY.PERFECT:videoRateDifference>50?CONNECTION_QUALITY.BAD:videoRateDifference>20?CONNECTION_QUALITY.GOOD:CONNECTION_QUALITY.PERFECT,callbacks[CONNECTION_QUALITY.UPDATE]&&(connectionQuality=currentQuality,callbacks[CONNECTION_QUALITY.UPDATE](connectionQuality,clientFiltered,serverFiltered)),videoBytes=bytesSentReceived}}else videoBytes=bytesSentReceived}))},isRemoteAudioMuted=function(){return!(!mediaConnection||"Flash"==mediaProvider)&&mediaConnection.isRemoteAudioMuted()},_stop=function(){if(logger.debug("core","Stop stream "+name_),statsCollector&&(statsCollector.stop(),statsCollector=null),status_!=STREAM_STATUS.NEW)return status_==STREAM_STATUS.PENDING?(logger.warn("core","Stopping stream before server response "+id_),void setTimeout(_stop,200)):void(status_!=STREAM_STATUS.FAILED?(send(published_?"unPublishStream":"stopStream",{mediaSessionId:id_,name:name_,published:published_,hasVideo:!0,hasAudio:!0,status:status_,record:!1}),mediaConnection&&mediaConnection.close(cacheLocalResources)):logger.warn("core","Stream status FAILED"));streamRefreshHandlers[id_]({status:STREAM_STATUS.FAILED})},published=function(){return published_};function sendStreamEvent(type,payload){send("sendStreamEvent",{mediaSessionId:id_,type:type,payload:payload})}var fireUnmuteEvent=function(){isRemoteAudioMuted()&&streamRefreshHandlers[id_]&&"function"==typeof streamRefreshHandlers[id_]&&streamRefreshHandlers[id_]({status:STREAM_EVENT,type:STREAM_EVENT_TYPE.UNMUTE_REQUIRED})},setZoom=function(){var _ref2=_asyncToGenerator(_regenerator().m((function _callee2(value){return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(!published()||!mediaConnection){_context2.n=2;break}return _context2.n=1,mediaConnection.setZoom(value);case 1:return _context2.a(2,_context2.v);case 2:throw new Error("This function available for publishing stream only");case 3:return _context2.a(2)}}),_callee2)})));return function(_x2){return _ref2.apply(this,arguments)}}();return stream.play=function(){if(logger.debug("core","Play stream "+name_),status_!==STREAM_STATUS.NEW)throw new Error("Invalid stream state "+status_);status_=STREAM_STATUS.PENDING,MediaProvider[mediaProvider].createConnection({id:id_,display:display,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,flashBufferTime:options.flashBufferTime||0,flashShowFullScreenButton:options.flashShowFullScreenButton||!1,connectionConfig:mediaOptions,connectionConstraints:mediaConnectionConstraints,audioOutputId:audioOutputId,remoteVideo:remoteVideo,playoutDelay:playoutDelay,unmutePlayOnStart:unmutePlayOnStart,useControls:useControls,logger:logger,unmuteRequiredEvent:fireUnmuteEvent},streamRefreshHandlers[id_]).then((function(newConnection){mediaConnection=newConnection;try{streamRefreshHandlers[id_]({status:status_})}catch(e){console.warn(e)}return mediaConnection.createOffer({receiveAudio:receiveAudio,receiveVideo:receiveVideo,stripCodecs:stripCodecs,stereo:_stereo})})).then((function(offer){logger.debug("core","Offer SDP:\n"+offer.sdp),send("playStream",{mediaSessionId:id_,name:name_,published:published_,hasVideo:!0,hasAudio:!0,status:status_,record:!1,width:playWidth,height:playHeight,mediaProvider:mediaProvider,sdp:offer.sdp,custom:options.custom,bitrate:bitrate,minBitrate:minBitrate,maxBitrate:maxBitrate,quality:quality,constraints:constraints,transport:transportType,cvoExtension:cvoExtension}),offer.player&&offer.player.play(id_)})).catch((function(error){throw error}))},stream.publish=function(){if(logger.debug("core","Publish stream "+name_),status_!==STREAM_STATUS.NEW)throw new Error("Invalid stream state "+status_);status_=STREAM_STATUS.PENDING,published_=!0;constraints&&constraints.video&&constraints.video.type&&constraints.video.type,MediaProvider[mediaProvider].getMediaAccess(constraints,display,disableConstraintsNormalization,useCanvasMediaStream).then((function(){status_!=STREAM_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,display:display,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,constraints:constraints,connectionConfig:mediaOptions,connectionConstraints:mediaConnectionConstraints,customStream:!(!constraints||!constraints.customStream)&&constraints.customStream,videoContentHint:videoContentHint,useControls:useControls,logger:logger}).then((function(newConnection){return(mediaConnection=newConnection).createOffer({stripCodecs:stripCodecs})})).then((function(offer){logger.debug("core","Offer SDP:\n"+offer.sdp);var publishStreamData={mediaSessionId:id_,name:name_,published:published_,hasVideo:offer.hasVideo,hasAudio:offer.hasAudio,status:status_,record:record_,mediaProvider:mediaProvider,sdp:offer.sdp,custom:options.custom,bitrate:bitrate,minBitrate:minBitrate,maxBitrate:maxBitrate,rtmpUrl:rtmpUrl,constraints:constraints,transport:transportType,cvoExtension:cvoExtension};collectDeviceInfo&&(publishStreamData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],display)),send("publishStream",publishStreamData)})):cacheLocalResources||releaseLocalMedia(display,mediaProvider)})).catch((function(error){logger.warn("core",error),info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,status_=STREAM_STATUS.FAILED,callbacks[status_]&&callbacks[status_](stream)}))},stream.stop=_stop,stream.id=function(){return id_},stream.status=function(){return status_},stream.name=function(){return name_},stream.published=published,stream.getRecordInfo=function(){return recordFileName},stream.getInfo=function(){return info_},stream.getErrorInfo=function(){return errorInfo_},stream.videoResolution=function(){if(published_)throw new Error("This function available only on playing stream");return resolution},stream.setAudioOutputId=function(id){if(audioOutputId=id,mediaConnection&&mediaConnection.setAudioOutputId)return mediaConnection.setAudioOutputId(id)},stream.setVolume=function(volume){mediaConnection&&mediaConnection.setVolume(volume)},stream.unmuteRemoteAudio=function(){mediaConnection&&"Flash"!=mediaProvider&&mediaConnection.unmuteRemoteAudio()},stream.muteRemoteAudio=function(){mediaConnection&&"Flash"!=mediaProvider&&mediaConnection.muteRemoteAudio()},stream.isRemoteAudioMuted=isRemoteAudioMuted,stream.setMicrophoneGain=function(volume){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");mediaConnection.setMicrophoneGain(volume)},stream.getVolume=function(){return mediaConnection?mediaConnection.getVolume():-1},stream.muteAudio=function(){mediaConnection&&(mediaConnection.muteAudio(),sendStreamEvent(STREAM_EVENT_TYPE.AUDIO_MUTED))},stream.unmuteAudio=function(){mediaConnection&&(mediaConnection.unmuteAudio(),sendStreamEvent(STREAM_EVENT_TYPE.AUDIO_UNMUTED))},stream.isAudioMuted=function(){return!mediaConnection||mediaConnection.isAudioMuted()},stream.muteVideo=function(){mediaConnection&&(mediaConnection.muteVideo(),sendStreamEvent(STREAM_EVENT_TYPE.VIDEO_MUTED))},stream.unmuteVideo=function(){mediaConnection&&(mediaConnection.unmuteVideo(),sendStreamEvent(STREAM_EVENT_TYPE.VIDEO_UNMUTED))},stream.isVideoMuted=function(){return!mediaConnection||mediaConnection.isVideoMuted()},stream.getStats=function(callbackFn,nativeStats){mediaConnection&&mediaConnection.getStats(callbackFn,nativeStats)},stream.snapshot=function(){if(logger.debug("core","Request snapshot, stream "+name_),status_!==STREAM_STATUS.NEW&&status_!==STREAM_STATUS.PLAYING&&status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");send("snapshot",{name:name_,mediaSessionId:id_})},stream.getAudioState=function(){return audioState_},stream.getVideoState=function(){return videoState_},stream.getNetworkBandwidth=function(){return networkBandwidth},stream.getRemoteBitrate=function(){return remoteBitrate},stream.fullScreen=function(){published()?logger.warn("core","Full screen is allowed only for played streams"):mediaConnection&&mediaConnection.fullScreen()},stream.on=function(event,callback){if(!event)throw new TypeError("Event can't be null");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,stream},stream.available=function(){return new _Promise((function(resolve,reject){send("availableStream",{mediaSessionId:id_,name:name_});var promise={};promise.resolve=resolve,promise.reject=reject,availableCallbacks.push(promise)}))},stream.switchCam=function(deviceId){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchCam(deviceId)},stream.switchMic=function(deviceId){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchMic(deviceId)},stream.switchToScreen=function(source,woExtension){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchToScreen(source,woExtension)},stream.switchToCam=function(){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");mediaConnection.switchToCam()},stream.sendData=function(payload){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");sendStreamEvent(STREAM_EVENT_TYPE.DATA,payload)},stream.getLogger=function(){return streamLogger},stream.updateVideoSettings=function(settings){if(published()&&mediaConnection)return mediaConnection.updateVideoSettings(settings);throw new Error("This function available for publishing stream only")},stream.updateVideoResolution=function(resolution){if(published()&&mediaConnection)return mediaConnection.updateVideoResolution(resolution);throw new Error("This function available for publishing stream only")},stream.getZoomCapabilities=function(){if(published()&&mediaConnection)return mediaConnection.getZoomCapabilities();throw new Error("This function available for publishing stream only")},stream.getZoom=function(){if(published()&&mediaConnection)return mediaConnection.getZoom();throw new Error("This function available for publishing stream only")},stream.setZoom=setZoom,streams[id_]=stream,stream},session.createCall=createCall,session.getStream=function(streamId){return streams[streamId]},session.getStreams=function(){return util.copyObjectToArray(streams)},session.sendData=restAppCommunicator.sendData,session.disconnect=function(){wsConnection&&wsConnection.close()},session.submitBugReport=function(reportObject){send("submitBugReport",reportObject)},session.startDebug=function(){logger.setPushLogs(!0),logger.setLevel("DEBUG"),send("sessionDebug",{command:"start"})},session.stopDebug=function(){logger.setLevel("INFO"),send("sessionDebug",{command:"stop"})},session.on=function(event,callback){if(!event)throw new Error("Event can't be null","TypeError");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,session},session.getLogger=function(){return sessionLogger},sessions[id_]=session,session},playFirstSound:function(noise){var mediaProvider=getMediaProviders()[0];MediaProvider[mediaProvider].playFirstSound(noise)},playFirstVideo:function(display,isLocal,src,useControls){for(var mp in MediaProvider)return MediaProvider[mp].playFirstVideo(display,isLocal,src,useControls)},getLogger:function(){if(initialized)return coreLogger;console.warn("Initialize API first.")},constants:constants,firefoxScreenSharingExtensionInstalled:!0,Browser:util.Browser}},{"./client-info":38,"./constants":39,"./media-source-media-provider":1,"./stats-collector":41,"./temasys-media-provider":1,"./util":42,"./webrtc-media-provider":43,"./websocket-media-provider":1,kalmanjs:2,"promise-polyfill":4,uuid:8,"webrtc-adapter":23}],41:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||_unsupportedIterableToArray(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function(){};return{s:F,n:function(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var util=require("./util"),LOG_PREFIX="stats-collector",CONNECTION_TYPE_WEBSOCKET="ws",CONNECTION_TYPE_HTTP="http",CONNECTION_STATUS_INIT=0,CONNECTION_STATUS_OK=200,CONNECTION_STATUS_BAD_REQUEST=400,CONNECTION_STATUS_INTERNAL_SERVER_ERROR=500,Connection=function(){var _send2,existingConnection=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,maxErrors=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3,connection={type:"",websocket:null,http:null,maxErrors:maxErrors,errorsCount:0,status:CONNECTION_STATUS_INIT,setUp:function(url){var headers=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,existingConnection=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;url.startsWith(CONNECTION_TYPE_WEBSOCKET)?connection.type=CONNECTION_TYPE_WEBSOCKET:url.startsWith(CONNECTION_TYPE_HTTP)?(connection.type=CONNECTION_TYPE_HTTP,connection.http=HttpConnection(url,headers)):existingConnection&&(connection.type=CONNECTION_TYPE_WEBSOCKET,connection.websocket=WebsocketConnection(existingConnection)),connection.errorsCount=0,connection.status=CONNECTION_STATUS_INIT},send:(_send2=_asyncToGenerator(_regenerator().m((function _callee0(message,data){var code,_t4;return _regenerator().w((function(_context0){for(;;)switch(_context0.n){case 0:code=CONNECTION_STATUS_BAD_REQUEST,_t4=connection.type,_context0.n=_t4===CONNECTION_TYPE_WEBSOCKET?1:_t4===CONNECTION_TYPE_HTTP?2:5;break;case 1:return connection.websocket&&(code=connection.websocket.send(message,data)),_context0.a(3,5);case 2:if(!connection.http){_context0.n=4;break}return _context0.n=3,connection.http.send(message,data);case 3:code=_context0.v;case 4:return _context0.a(3,5);case 5:connection.status=code,connection.status===CONNECTION_STATUS_OK?connection.errorsCount=0:"webRTCMetricsBatch"===message&&(connection.errorsCount++,connection.errorsCount<connection.maxErrors&&(connection.status=CONNECTION_STATUS_OK));case 6:return _context0.a(2)}}),_callee0)}))),function(_x5,_x6){return _send2.apply(this,arguments)})};return connection.setUp("",null,existingConnection),connection},WebsocketConnection=function(wsConnection){var connection={websocket:wsConnection,send:function(message,data){var code=CONNECTION_STATUS_BAD_REQUEST;return connection.websocket&&(connection.websocket.readyState===WebSocket.OPEN&&connection.websocket.send(JSON.stringify({message:message,data:[data]})),code=CONNECTION_STATUS_OK),code}};return connection},HttpConnection=function(url,headers){var _send3,connection={url:addSlash(url),headers:headers,send:(_send3=_asyncToGenerator(_regenerator().m((function _callee1(message,data){var code,httpHeaders,_i2,_Object$entries,_Object$entries$_i,header,value,response;return _regenerator().w((function(_context1){for(;;)switch(_context1.p=_context1.n){case 0:if(code=CONNECTION_STATUS_BAD_REQUEST,!connection.url){_context1.n=4;break}if(_context1.p=1,(httpHeaders=new Headers).append("Content-Type","application/json"),connection.headers)for(_i2=0,_Object$entries=Object.entries(connection.headers);_i2<_Object$entries.length;_i2++)_Object$entries$_i=_slicedToArray(_Object$entries[_i2],2),header=_Object$entries$_i[0],value=_Object$entries$_i[1],httpHeaders.append(header,value);return _context1.n=2,fetch(connection.url+message,{method:"POST",headers:httpHeaders,mode:"cors",body:JSON.stringify(data)});case 2:response=_context1.v,code=response.status,_context1.n=4;break;case 3:_context1.p=3,_context1.v,code=CONNECTION_STATUS_INTERNAL_SERVER_ERROR;case 4:return _context1.a(2,code)}}),_callee1,null,[[1,3]])}))),function(_x7,_x8){return _send3.apply(this,arguments)})};return connection},valueToString=function(value){var valueString="undefined";return value&&(valueString="object"===_typeof(value)?JSON.stringify(value):value.toString()),valueString},getLogger=function(logger){return logger&&void 0!==logger.info&&void 0!==logger.warn&&void 0!==logger.error&&void 0!==logger.debug?logger:{info:function(){},warn:function(){},error:function(){},debug:function(){}}},addSlash=function(value){var endpoint=value;return endpoint&&!endpoint.endsWith("/")&&(endpoint+="/"),endpoint};module.exports={StreamStatsCollector:function(description,id,mediaConnection,wsConnection,logger,maxErrors){var _sendMetrics,_collectMetrics,_send,_sendHeaders,_checkForCompression,_updateCompression,_updateHeaders,_update,_start,statCollector={description:description,id:id,mediaConnection:mediaConnection,connection:Connection(wsConnection,maxErrors),logger:getLogger(logger),headers:"",compression:"none",metricsBatch:null,timer:null,batchCount:0,timerBusy:!1,start:(_start=_asyncToGenerator(_regenerator().m((function _callee(){var error,authHeader;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(error="Can't collect WebRTC stats to send: ",statCollector.description.types){_context.n=1;break}throw new Error(error+"no report types defined");case 1:if(statCollector.description.sampling){_context.n=2;break}throw new Error(error+"no sampling interval defined");case 2:if(statCollector.description.batchSize){_context.n=3;break}throw new Error(error+"no metrics batch size defined");case 3:if(statCollector.mediaConnection){_context.n=4;break}throw new Error(error+"no media connection available");case 4:return statCollector.logger.debug(LOG_PREFIX,"RTCMetricsServerDescription: "+JSON.stringify(statCollector.description)),statCollector.description.ingestPoint&&(authHeader=null,statCollector.description.authorization&&(authHeader={Authorization:statCollector.description.authorization}),statCollector.connection.setUp(statCollector.description.ingestPoint,authHeader)),_context.n=5,statCollector.updateHeaders();case 5:return _context.n=6,statCollector.updateCompression();case 6:return _context.n=7,statCollector.sendHeaders();case 7:"on"===statCollector.description.collect&&statCollector.collect(!0);case 8:return _context.a(2)}}),_callee)}))),function(){return _start.apply(this,arguments)}),collect:function(enable){enable&&statCollector.connection.status===CONNECTION_STATUS_OK?statCollector.startTimer():statCollector.stopTimer()},stop:function(){statCollector.stopTimer(),statCollector.headers=""},update:(_update=_asyncToGenerator(_regenerator().m((function _callee2(description){var _t;return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(description){_context2.n=1;break}return statCollector.logger.error(LOG_PREFIX+"-"+statCollector.id,"Can't update WebRTC metrics sending: no parameters passed"),_context2.a(2);case 1:if(statCollector.logger.debug(LOG_PREFIX,"New RTCMetricsServerDescription: "+JSON.stringify(description)),!description.types&&!description.compression){_context2.n=6;break}if(statCollector.stop(),!description.types){_context2.n=2;break}return statCollector.description.types=description.types,_context2.n=2,statCollector.updateHeaders();case 2:if(!description.compression){_context2.n=3;break}return statCollector.description.compression=description.compression,_context2.n=3,statCollector.updateCompression();case 3:return _context2.n=4,statCollector.sendHeaders();case 4:if(statCollector.connection.status===CONNECTION_STATUS_OK){_context2.n=5;break}return _context2.a(2);case 5:_context2.n=7;break;case 6:statCollector.collect(!1);case 7:description.batchSize&&(statCollector.description.batchSize=description.batchSize),description.sampling&&(statCollector.description.sampling=description.sampling),description.collect&&(statCollector.description.collect=description.collect),_t=statCollector.description.collect,_context2.n="on"===_t?8:"off"===_t?9:10;break;case 8:return statCollector.collect(!0),_context2.a(3,10);case 9:return statCollector.collect(!1),_context2.a(3,10);case 10:return _context2.a(2)}}),_callee2)}))),function(_x){return _update.apply(this,arguments)}),updateHeaders:(_updateHeaders=_asyncToGenerator(_regenerator().m((function _callee3(){var stats,currentHeaders,headersChanged,newMetrics,_args3=arguments;return _regenerator().w((function(_context3){for(;;)switch(_context3.n){case 0:if(stats=_args3.length>0&&void 0!==_args3[0]?_args3[0]:null,currentHeaders="",headersChanged=!1,null!==stats){_context3.n=2;break}return _context3.n=1,statCollector.mediaConnection.getWebRTCStats();case 1:stats=_context3.v;case 2:return Object.keys(statCollector.description.types).forEach((function(type){var typeDescriptor=statCollector.description.types[type],metricsString="",contentFilters=null;typeDescriptor.metrics&&(metricsString=typeDescriptor.metrics),typeDescriptor.contains&&(contentFilters=typeDescriptor.contains),stats[type]?stats[type].forEach((function(report){if(statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,type+" report: "+JSON.stringify(report)),contentFilters){var filtersMatched=!0;for(var filter in contentFilters){statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,type+" filter by "+filter+": "+JSON.stringify(contentFilters[filter]));var filterMatched=!1;if(report[filter]){var _step,_iterator=_createForOfIteratorHelper(contentFilters[filter]);try{for(_iterator.s();!(_step=_iterator.n()).done;){var value=_step.value;if(statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,filter+": "+value+" <> "+report[filter]),report[filter]===value){filterMatched=!0;break}}}catch(err){_iterator.e(err)}finally{_iterator.f()}}if(filtersMatched=filtersMatched&&filterMatched,!filterMatched)break}filtersMatched&&(currentHeaders=statCollector.addHeaders(currentHeaders,report,metricsString))}else currentHeaders=statCollector.addHeaders(currentHeaders,report,metricsString)})):statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,"No report type found in RTC stats: '"+type+"'")})),currentHeaders!==statCollector.headers&&(headersChanged=!0,newMetrics=[],currentHeaders.split(",").forEach((function(header){-1===statCollector.headers.indexOf(header)&&newMetrics.push(header)})),newMetrics.length&&statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"RTC metrics to be collected: "+newMetrics.toString()),statCollector.headers=currentHeaders),_context3.a(2,headersChanged)}}),_callee3)}))),function(){return _updateHeaders.apply(this,arguments)}),addHeaders:function(currentHeaders,report,metricsString){metricsString&&metricsString.split(",").forEach((function(metric){for(var _i=0,_Object$keys=Object.keys(report);_i<_Object$keys.length;_i++){if(metric===_Object$keys[_i]){currentHeaders=util.addFieldToCsvString(currentHeaders,report.type+"."+report.id+"."+metric,",");break}}}));return currentHeaders},updateCompression:(_updateCompression=_asyncToGenerator(_regenerator().m((function _callee4(){return _regenerator().w((function(_context4){for(;;)switch(_context4.n){case 0:if(!statCollector.description.compression){_context4.n=3;break}if(!(statCollector.description.compression.indexOf("gzip")>=0)){_context4.n=2;break}return _context4.n=1,statCollector.checkForCompression("gzip");case 1:_context4.n=3;break;case 2:if(!(statCollector.description.compression.indexOf("deflate")>=0)){_context4.n=3;break}return _context4.n=3,statCollector.checkForCompression("deflate");case 3:return _context4.a(2)}}),_callee4)}))),function(){return _updateCompression.apply(this,arguments)}),checkForCompression:(_checkForCompression=_asyncToGenerator(_regenerator().m((function _callee5(compression){var _t2;return _regenerator().w((function(_context5){for(;;)switch(_context5.p=_context5.n){case 0:return _context5.p=0,_context5.n=1,util.compress(compression,"test",!1);case 1:statCollector.compression=compression,_context5.n=3;break;case 2:_context5.p=2,_t2=_context5.v,statCollector.logger.warn(LOG_PREFIX+"-"+statCollector.id,"Can't compress metrics data using "+compression+": "+_t2),statCollector.compression="none";case 3:return _context5.a(2)}}),_callee5,null,[[0,2]])}))),function(_x2){return _checkForCompression.apply(this,arguments)}),sendHeaders:(_sendHeaders=_asyncToGenerator(_regenerator().m((function _callee6(){var data;return _regenerator().w((function(_context6){for(;;)switch(_context6.n){case 0:return data={mediaSessionId:statCollector.id,compression:statCollector.compression,headers:statCollector.headers},_context6.n=1,statCollector.send("webRTCMetricsClientDescription",data);case 1:return _context6.a(2)}}),_callee6)}))),function(){return _sendHeaders.apply(this,arguments)}),send:(_send=_asyncToGenerator(_regenerator().m((function _callee7(message,data){return _regenerator().w((function(_context7){for(;;)switch(_context7.n){case 0:if(statCollector.connection.status!==CONNECTION_STATUS_INIT&&statCollector.connection.status!==CONNECTION_STATUS_OK){_context7.n=2;break}return statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,data),_context7.n=1,statCollector.connection.send(message,data);case 1:statCollector.connection.status!==CONNECTION_STATUS_OK&&(statCollector.logger.error(LOG_PREFIX+"-"+statCollector.id,"Error "+statCollector.connection.status+" sending RTC metrics to the server, stop sending"),statCollector.stop());case 2:return _context7.a(2)}}),_callee7)}))),function(_x3,_x4){return _send.apply(this,arguments)}),startTimer:function(){statCollector.timer||(statCollector.batchCount=statCollector.description.batchSize,statCollector.timer=setInterval(statCollector.collectMetrics,statCollector.description.sampling))},stopTimer:function(){statCollector.timer&&(clearInterval(statCollector.timer),statCollector.timer=null,statCollector.metricsBatch=null)},collectMetrics:(_collectMetrics=_asyncToGenerator(_regenerator().m((function _callee8(){var stats,metrics,lostMetrics,headersUpdated;return _regenerator().w((function(_context8){for(;;)switch(_context8.n){case 0:if(!statCollector.timer||statCollector.timerBusy){_context8.n=7;break}return statCollector.timerBusy=!0,_context8.n=1,statCollector.mediaConnection.getWebRTCStats();case 1:return stats=_context8.v,statCollector.startNewBatch(),metrics=[],lostMetrics=[],statCollector.headers?statCollector.headers.split(",").forEach((function(header){var components=header.split("."),descriptor={type:components[0],id:components[1],name:components[2]},value=null;if(stats[descriptor.type]){var _step2,_iterator2=_createForOfIteratorHelper(stats[descriptor.type]);try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var report=_step2.value;if(report.id===descriptor.id){value=report[descriptor.name];break}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}}null===value?lostMetrics.push(descriptor):metrics.push(value)})):statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"No RTC metrics to collect, trying to update metrics available list"),_context8.n=2,statCollector.updateHeaders(stats);case 2:if(headersUpdated=_context8.v,!lostMetrics.length){_context8.n=4;break}return statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"Missing metrics: "+JSON.stringify(lostMetrics)),_context8.n=3,statCollector.sendMetrics();case 3:statCollector.startNewBatch(metrics),_context8.n=5;break;case 4:if(!metrics.length){_context8.n=5;break}if(statCollector.metricsBatch.push(metrics),statCollector.batchCount--,0!==statCollector.batchCount&&!headersUpdated){_context8.n=5;break}return _context8.n=5,statCollector.sendMetrics();case 5:if(!headersUpdated){_context8.n=6;break}return statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"RTC metrics list has changed, sending a new metrics description"),_context8.n=6,statCollector.sendHeaders();case 6:statCollector.timerBusy=!1;case 7:return _context8.a(2)}}),_callee8)}))),function(){return _collectMetrics.apply(this,arguments)}),sendMetrics:(_sendMetrics=_asyncToGenerator(_regenerator().m((function _callee9(){var previous,metricsToSend,metricsData,i,metricsString,j,valueString,previousString,data,_t3;return _regenerator().w((function(_context9){for(;;)switch(_context9.p=_context9.n){case 0:for(metricsToSend=[],i=0;statCollector.metricsBatch&&i<statCollector.metricsBatch.length;i++){for(metricsString="",j=0;j<statCollector.metricsBatch[i].length;j++)valueString=valueToString(statCollector.metricsBatch[i][j]),previousString="",previous&&(previousString=valueToString(previous[j])),valueString===previousString&&(valueString=""),metricsString=util.addFieldToCsvString(metricsString,valueString,";"),j>0&&""===metricsString&&(metricsString=";");previous=statCollector.metricsBatch[i],metricsToSend.push(metricsString)}if("none"===statCollector.compression){_context9.n=5;break}return _context9.p=1,_context9.n=2,util.compress(statCollector.compression,JSON.stringify(metricsToSend),!0);case 2:metricsData=_context9.v,_context9.n=4;break;case 3:_context9.p=3,_t3=_context9.v,statCollector.logger.warn(LOG_PREFIX+"-"+statCollector.id,"Can't send metrics data using"+statCollector.compression+": "+_t3),metricsData=null;case 4:_context9.n=6;break;case 5:metricsData=metricsToSend;case 6:if(!metricsData){_context9.n=7;break}return data={mediaSessionId:statCollector.id,metrics:metricsData},_context9.n=7,statCollector.send("webRTCMetricsBatch",data);case 7:statCollector.cleanBatch();case 8:return _context9.a(2)}}),_callee9,null,[[1,3]])}))),function(){return _sendMetrics.apply(this,arguments)}),startNewBatch:function(metrics){statCollector.metricsBatch||(statCollector.metricsBatch=[],metrics&&statCollector.metricsBatch.push(metrics))},cleanBatch:function(){statCollector.metricsBatch&&(statCollector.metricsBatch=null,statCollector.batchCount=statCollector.description.batchSize)}};return statCollector}}},{"./util":42}],42:[function(require,module,exports){"use strict";function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function _toConsumableArray(r){return function(r){if(Array.isArray(r))return _arrayLikeToArray(r)}(r)||function(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}(r)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var Browser={isIE:function(){return!!document.documentMode},isFirefox:function(){return"undefined"!=typeof InstallTrigger},isChrome:function(){return!!window.chrome&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!/OPR/.test(navigator.userAgent)},isEdge:function(){return!this.isIE()&&!!window.StyleMedia},isOpera:function(){return!!window.opr&&!!opr.addons||!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isiOS:function(){return/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream},isSafari:function(){var userAgent=navigator.userAgent.toLowerCase();return/(safari|applewebkit)/i.test(userAgent)&&!userAgent.includes("chrome")&&!userAgent.includes("android")},isAndroid:function(){return navigator.userAgent.toLowerCase().indexOf("android")>-1},isSafariWebRTC:function(){return navigator.mediaDevices&&this.isSafari()},isSamsungBrowser:function(){return/SamsungBrowser/i.test(navigator.userAgent)},isAndroidFirefox:function(){return this.isAndroid()&&/Firefox/i.test(navigator.userAgent)},isChromiumEdge:function(){return/Chrome/i.test(navigator.userAgent)&&/Edg/i.test(navigator.userAgent)},version:function(){var version=navigator.userAgent.match(/version\/(\d+)/i);return version?version[1]:(this.isEdge()&&(version=/\brv[ :]+(\d+)/g.exec(navigator.userAgent)||[]),this.isOpera()&&(version=navigator.userAgent.match(/\b(OPR)\/(\d+)/)||[]),this.isChromiumEdge()&&(version=navigator.userAgent.match(/\b(Edg)\/(\d+)/)||[]),this.isSamsungBrowser()&&(version=navigator.userAgent.match(/\b(SamsungBrowser)\/(\d+)/)||[]),this.isChrome()&&(version=navigator.userAgent.match(/\b(Chrome)\/(\d+)/)||[]),this.isFirefox()&&(version=navigator.userAgent.match(/\b(Firefox)\/(\d+)/)||[]),version[2]||0)}},SDP={matchPrefix:function(sdp,prefix){return sdp.trim().split("\n").map((function(line){return line.trim()})).filter((function(line){return 0===line.indexOf(prefix)}))},writeFmtp:function(sdp,param,codec){var i,sdpArray=sdp.split("\n");for(i=0;i<sdpArray.length;i++)-1!=sdpArray[i].search(codec)&&0==sdpArray[i].indexOf("a=rtpmap")&&(sdpArray[i]+="\na=fmtp:"+sdpArray[i].match(/[0-9]+/)[0]+" "+param+"\r");var result="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(result+=sdpArray[i]+"\n");return result},setPublishingBitrate:function(sdp,minBitrate,maxBitrate){if(sdp&&(minBitrate||maxBitrate)){var i,matches,sdpArray=sdp.split("\n"),rtpmap=-1,codec="",bitrateString="";for(i=0;i<sdpArray.length;i++)sdpArray[i].startsWith("a=rtpmap")?(matches=sdpArray[i].match("a=rtpmap:(.+) (.+)/.*"))&&matches.length>2&&(rtpmap=parseInt(matches[1],10),codec=matches[2]):"H264"!==codec&&"VP8"!==codec||(sdpArray[i].startsWith("a=fmtp:"+rtpmap)?(bitrateString=this.getBitrateString(sdpArray[i],minBitrate,maxBitrate))&&(sdpArray[i]+=";"+bitrateString):(bitrateString=this.getBitrateString("",minBitrate,maxBitrate))&&(sdpArray[i]="a=fmtp:"+rtpmap+" "+bitrateString+"\r\n"+sdpArray[i]),codec="",rtpmap=-1);var newSDP="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(newSDP+=sdpArray[i]+"\n");return newSDP}return sdp},getBitrateString:function(string,minBitrate,maxBitrate){var bitrateString="";return minBitrate&&-1==string.indexOf("x-google-min-bitrate")&&(bitrateString+="x-google-min-bitrate="+minBitrate),maxBitrate&&-1==string.indexOf("x-google-max-bitrate")&&(bitrateString&&(bitrateString+=";"),bitrateString+="x-google-max-bitrate="+maxBitrate),bitrateString}},compress=function(){var n,_ref=(n=_regenerator().m((function _callee(compression,data,base64){var stream,compressedReadableStream,compressedResponse,blob,buffer,compressedBase64;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if("undefined"!=typeof CompressionStream){_context.n=1;break}throw new Error("Compression is not available");case 1:return stream="string"==typeof data?new Blob([data],{type:"text/plain"}).stream():data.stream(),compressedReadableStream=stream.pipeThrough(new CompressionStream(compression)),_context.n=2,new Response(compressedReadableStream);case 2:return compressedResponse=_context.v,_context.n=3,compressedResponse.blob();case 3:if(blob=_context.v,!base64){_context.n=5;break}return _context.n=4,blob.arrayBuffer();case 4:return buffer=_context.v,compressedBase64=btoa(String.fromCharCode.apply(String,_toConsumableArray(new Uint8Array(buffer)))),_context.a(2,compressedBase64);case 5:return _context.a(2,blob);case 6:return _context.a(2)}}),_callee)})),function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))});return function(_x,_x2,_x3){return _ref.apply(this,arguments)}}();module.exports={isEmptyObject:function(obj){for(var name in obj)return!1;return!0},copyObjectToArray:function(obj){var ret=[];for(var prop in obj)obj.hasOwnProperty(prop)&&ret.push(obj[prop]);return ret},copyObjectPropsToAnotherObject:function(src,dst){for(var prop in src)src.hasOwnProperty(prop)&&(dst[prop]=src[prop])},processRtcStatsReport:function(browser,report){var result={};if("chrome"==browser){var gotResult=!1;if(report.type&&"googCandidatePair"==report.type&&"true"==report.googActiveConnection&&(gotResult=!0),report.type&&"ssrc"==report.type&&(gotResult=!0),gotResult)for(var k in report)report.hasOwnProperty(k)&&(result[k]=report[k]);return result}if("firefox"==browser){if(report.type&&("outboundrtp"==report.type||"inboundrtp"==report.type)&&-1==report.id.indexOf("rtcp"))for(var k in result={},report)report.hasOwnProperty(k)&&(result[k]=report[k]);return result}return result},Browser:Browser,SDP:SDP,logger:function(){return{init:function(verbosity,enablePushLogs,customLogger,enableLogs){switch(verbosity.toUpperCase()){case"DEBUG":this.verbosity=3;break;case"INFO":this.verbosity=2;break;case"ERROR":this.verbosity=0;break;case"WARN":this.verbosity=1;break;case"TRACE":this.verbosity=4;break;default:this.verbosity=2}this.date=function(){return(new Date).toTimeString().split(" ")[0]},this.enablePushLogs=enablePushLogs;var delayedLogs=[];this.customLogger=customLogger,this.enableLogs=enableLogs,this.pushLogs=function(log){if(this.wsConnection&&this.enablePushLogs){if(delayedLogs.length)for(var i=0;i<delayedLogs.length;i++)this.wsConnection.send(JSON.stringify({message:"pushLogs",data:[{logs:delayedLogs[i]}]}));delayedLogs=[],this.wsConnection.send(JSON.stringify({message:"pushLogs",data:[{logs:log}]}))}else delayedLogs.push(log)}},info:function(src,text){if(this.enableLogs){var prefix=this.date()+" INFO "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=2&&(null!=this.customLogger?this.customLogger.info(text):console.log(prefix,text))}},debug:function(src,text){if(this.enableLogs){var prefix=this.date()+" DEBUG "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=3&&(null!=this.customLogger?this.customLogger.debug(text):console.log(prefix,text))}},trace:function(src,text){if(this.enableLogs){var prefix=this.date()+" TRACE "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=4&&(null!=this.customLogger?this.customLogger.trace(text):console.log(prefix,text))}},warn:function(src,text){if(this.enableLogs){var prefix=this.date()+" WARN "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=1&&(null!=this.customLogger?this.customLogger.warn(text):console.warn(prefix,text))}},error:function(src,text){if(this.enableLogs){var prefix=this.date()+" ERROR "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=0&&(null!=this.customLogger?this.customLogger.error(text):console.error(prefix,text))}},setEnableLogs:function(enableLogs){this.enableLogs=enableLogs},setCustomLogger:function(customLogger){this.customLogger=customLogger},setConnection:function(connection){this.wsConnection=connection},setPushLogs:function(pushLogs){this.enablePushLogs=pushLogs},setLevel:function(level){switch(level.toUpperCase()){case"DEBUG":this.verbosity=3;break;case"INFO":this.verbosity=2;break;case"ERROR":this.verbosity=0;break;case"WARN":this.verbosity=1;break;case"TRACE":this.verbosity=4;break;default:this.verbosity=2}}}},stripCodecs:function(sdp,codecs){if(!codecs.length)return sdp;for(var i,sdpArray=sdp.split("\n"),codecsArray=codecs.split(","),pt=[],p=0;p<codecsArray.length;p++)for(console.log("Searching for codec "+codecsArray[p]),i=0;i<sdpArray.length;i++)-1!=sdpArray[i].search(new RegExp(codecsArray[p],"i"))&&0==sdpArray[i].indexOf("a=rtpmap")&&(console.log(codecsArray[p]+" detected"),pt.push(sdpArray[i].match(/[0-9]+/)[0]),sdpArray[i]="");if(pt.length){for(p=0;p<pt.length;p++)for(i=0;i<sdpArray.length;i++)-1==sdpArray[i].search("a=fmtp:"+pt[p])&&-1==sdpArray[i].search("a=rtcp-fb:"+pt[p])||(sdpArray[i]="");for(i=0;i<sdpArray.length;i++)if(-1!=sdpArray[i].search("m=audio")||-1!=sdpArray[i].search("m=video")){for(var mLineSplitted=sdpArray[i].split(" "),newMLine="",m=0;m<mLineSplitted.length;m++)(-1==pt.indexOf(mLineSplitted[m].trim())||m<=2)&&(newMLine+=mLineSplitted[m],m<mLineSplitted.length-1&&(newMLine+=" "));sdpArray[i]=newMLine}}var result="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(result+=sdpArray[i]+"\n");return result},getCurrentCodecAndSampleRate:function(sdp,mediaType){for(var codecPt,rows=sdp.split("\n"),ret={},i=0;i<rows.length;i++){if(codecPt&&-1!=rows[i].indexOf("a=rtpmap:"+codecPt))return ret.name=rows[i].split(" ")[1].split("/")[0],ret.sampleRate=rows[i].split(" ")[1].split("/")[1],ret;-1!=rows[i].indexOf("m="+mediaType)&&(codecPt=rows[i].split(" ")[3].trim())}return ret.name="undefined",ret.sampleRate="undefined",ret},isPromise:function(object){return null!==object&&"object"===_typeof(object)&&"function"==typeof object.then&&"function"==typeof object.catch},setPublishingBitrate:function(sdp,mediaConnection,minBitrate,maxBitrate){return(minBitrate||maxBitrate)&&(sdp&&Browser.isChrome()||Browser.isSafariWebRTC()?sdp=SDP.setPublishingBitrate(sdp,minBitrate,maxBitrate):mediaConnection&&mediaConnection.setPublishingBitrate(minBitrate,maxBitrate)),sdp},addFieldToCsvString:function(csvString,field,delimiter){return""!==field&&field.indexOf(delimiter)>=0&&(field='"'+field+'"'),csvString=""===csvString?field:csvString+delimiter+field},compress:compress}},{}],43:[function(require,module,exports){function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||_unsupportedIterableToArray(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var extensionId,defaultConstraints,logger,audioContext,createMicGainNode,microphoneGain,browserDetails=require("webrtc-adapter").default.browserDetails,uuid_v1=require("uuid").v1,util=require("./util"),connections={},constants=require("./constants"),validBrowsers=["firefox","chrome","safari"],videoCams=[],mics=[],audioSourceDevice="",mixAudioTracks=function(stream1,stream2){var stream1Sound=audioContext.createMediaStreamSource(stream1),stream2Sound=audioContext.createMediaStreamSource(stream2),destination=audioContext.createMediaStreamDestination(),newStream=destination.stream;return stream1Sound.connect(destination),stream2Sound.connect(destination),newStream.getAudioTracks()[0]},loadCanvasVideo=function(display,stream,video){var vEl=video;if(vEl){if("CANVAS"!==vEl.tagName){var canvas=document.createElement("canvas");display.replaceChild(canvas,vEl),canvas.appendChild(vEl),vEl=canvas}}else!function(parent){var canvas=document.createElement("canvas");parent.appendChild(canvas)}(display),function(parent){var video=document.createElement("video");parent.appendChild(video)}(display.children[0]),vEl=display.children[0];vEl.id||(vEl.id=uuid_v1()+"-LOCAL_CACHED_VIDEO");var child=vEl.children[0];return child.srcObject=stream,child.muted=!0,child.onloadedmetadata=function(e){child.play(),vEl.width=child.videoWidth,vEl.height=child.videoHeight,function(canvas,videoWidth,videoHeight){if(!canvas.parentNode)return;var newSize,display=vEl.parentNode,parentSize={w:display.parentNode.clientWidth,h:display.parentNode.clientHeight};newSize=videoWidth&&videoHeight?downScaleToFitSize(videoWidth,videoHeight,parentSize.w,parentSize.h):downScaleToFitSize(canvas.videoWidth,canvas.videoHeight,parentSize.w,parentSize.h);display.style.width=newSize.w+"px",display.style.height=newSize.h+"px";var margin=0;parentSize.h-newSize.h>1&&(margin=Math.floor((parentSize.h-newSize.h)/2));function downScaleToFitSize(videoWidth,videoHeight,dstWidth,dstHeight){var newWidth,newHeight,videoRatio=videoWidth/videoHeight;return dstWidth/dstHeight>videoRatio?(newHeight=dstHeight,newWidth=Math.floor(videoRatio*dstHeight)):(newWidth=dstWidth,newHeight=Math.floor(dstWidth/videoRatio)),{w:newWidth,h:newHeight}}display.style.margin=margin+"px auto"}(vEl,child.videoWidth,child.videoHeight)},util.Browser.isFirefox()&&vEl.getContext("2d"),vEl.srcObject=vEl.captureStream(30),stream.getAudioTracks().length>0&&vEl.srcObject.addTrack(stream.getAudioTracks()[0]),vEl},loadVideo=function(display,stream,screenShare,requestAudioConstraints,resolve,constraints,useCanvas){var video;function resolveCallback(){requestAudioConstraints&&"chrome"==browserDetails.browser?(logger.info("webrtc","Request for audio stream"),navigator.getUserMedia({audio:requestAudioConstraints},(function(stream){if(logger.info("webrtc","Got audio stream, add it to video stream"),video.srcObject.getAudioTracks()[0]){var mixedTrack=mixAudioTracks(stream,video.srcObject),originalTrack=video.srcObject.getAudioTracks()[0];video.srcObject.removeTrack(originalTrack),video.srcObject.addTrack(mixedTrack)}else video.srcObject.addTrack(stream.getAudioTracks()[0]);resolve(display)}))):resolve(display)}video=useCanvas?loadCanvasVideo(display,stream,getCacheInstance(display)):function(display,stream,screenShare,constraints,video){var vEl=video;return vEl||(vEl=createVideoElement(),display.appendChild(vEl)),vEl.id||(vEl.id=uuid_v1()+"-LOCAL_CACHED_VIDEO"),vEl.srcObject=stream,vEl.onloadedmetadata=function(e){screenShare&&!screenCaptureSupportedBrowsers()&&setScreenResolution(vEl,stream,constraints),vEl.play()},vEl}(display,stream,screenShare,constraints,getCacheInstance(display)),createMicGainNode&&stream.getAudioTracks().length>0&&"chrome"==browserDetails.browser&&(audioContext.resume(),microphoneGain=createGainNode(stream)),constraints.systemSound&&"chrome"==browserDetails.browser?chrome.runtime.sendMessage(extensionId,{type:"isInstalled"},(function(response){response?chrome.runtime.sendMessage(extensionId,{type:"getSourceId"},(function(response){if(response.error)resolveCallback(),logger.error("webrtc",response.error);else if(response.systemSoundAccess){var constraints={audio:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId,echoCancellation:!0},optional:[]},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId},optional:[]}};navigator.getUserMedia(constraints,(function(audioStream){if(stream.getAudioTracks().length>0){var originalAudioTrack=stream.getAudioTracks()[0],mixedTrack=mixAudioTracks(stream,audioStream);stream.addTrack(mixedTrack),stream.removeTrack(originalAudioTrack)}else stream.addTrack(audioStream.getAudioTracks()[0]);resolveCallback()}),(function(reason){resolveCallback(),logger.error("webrtc",reason)}))}else resolveCallback(),logger.error("webrtc","System sound: access is denied by the user")})):resolveCallback()})):resolveCallback()},createGainNode=function(stream){var audioCtx=audioContext,source=audioCtx.createMediaStreamSource(stream),gainNode=audioCtx.createGain(),destination=audioCtx.createMediaStreamDestination(),outputStream=destination.stream;source.connect(gainNode),gainNode.connect(destination);var sourceAudioTrack=stream.getAudioTracks()[0];return audioSourceDevice=sourceAudioTrack.label,gainNode.sourceAudioTrack=sourceAudioTrack,gainNode.release=function(){this.sourceAudioTrack.stop(),this.disconnect()},stream.addTrack(outputStream.getAudioTracks()[0]),stream.removeTrack(sourceAudioTrack),gainNode},setScreenResolution=function(video,stream,constraints){var newHeight,newWidth,videoRatio;video.videoWidth>video.videoHeight?(videoRatio=video.videoWidth/video.videoHeight,newHeight=constraints.video.videoWidth/videoRatio,newWidth=constraints.video.videoWidth):(videoRatio=video.videoHeight/video.videoWidth,newWidth=constraints.video.videoHeight/videoRatio,newHeight=constraints.video.videoHeight),console.log("videoRatio === "+videoRatio),stream.getVideoTracks()[0].applyConstraints({height:newHeight,width:newWidth})},getScreenDeviceIdWoExtension=function(constraints){return new Promise((function(resolve,reject){var video={};constraints.video.frameRate.ideal&&(video.frameRate=constraints.video.frameRate.ideal),constraints.video.width&&(video.width=constraints.video.width),constraints.video.height&&(video.height=constraints.video.height),0===Object.keys(video).length&&(video=!0),resolve({video:video,audio:!0})}))},getScreenDeviceId=function(constraints){return new Promise((function(resolve,reject){var o={};window.chrome?chrome.runtime.sendMessage(extensionId,{type:"isInstalled"},(function(response){response?(o.maxWidth=constraints&&constraints.video&&constraints.video.width?constraints.video.width:320,o.maxHeight=constraints&&constraints.video&&constraints.video.height?constraints.video.height:240,o.maxFrameRate=constraints&&constraints.video&&constraints.video.frameRate&&constraints.video.frameRate.ideal?constraints.video.frameRate.ideal:30,o.chromeMediaSource="desktop",chrome.runtime.sendMessage(extensionId,{type:"getSourceId"},(function(response){if(response.error)reject(new Error("Screen access denied"));else{o.chromeMediaSourceId=response.sourceId;var result={mandatory:o,sourceId:response.sourceId};response.systemSoundAccess&&(result.audioMandatory={chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId,echoCancellation:!0}),resolve(result)}}))):reject(new Error("Screen sharing extension is not available"))})):(o.mediaSource=constraints.video.mediaSource,o.width={},o.height={},o.frameRate={min:constraints.video.frameRate.max,max:constraints.video.frameRate.max},o.videoWidth=constraints.video.width,o.videoHeight=constraints.video.height,resolve(o))}))},releaseMedia=function(display){var video=getCacheInstance(display);return!!video&&(removeVideoElement(video),!0)};function getCacheInstance(display){var i;if(display)for(i=0;i<display.children.length;i++)if(display.children[i]&&(-1!=display.children[i].id.indexOf("-LOCAL_CACHED_VIDEO")||-1!=display.children[i].id.indexOf("-REMOTE_CACHED_VIDEO")))return logger.info("webrtc","FOUND WEBRTC CACHED INSTANCE, id "+display.children[i].id),display.children[i]}function createVideoElement(){var useControls=arguments.length>0&&void 0!==arguments[0]&&arguments[0],video=document.createElement("video");return video.muted=!0,util.Browser.isSafariWebRTC()&&(video.setAttribute("playsinline",""),video.setAttribute("webkit-playsinline","")),useControls&&enableVideoControls(video),video}function removeVideoElement(video){if(video.srcObject){video.pause();for(var tracks=video.srcObject.getTracks(),i=0;i<tracks.length;i++)tracks[i].stop(),-1!=video.id.indexOf("-LOCAL_CACHED_VIDEO")&&"audio"==tracks[i].kind&&microphoneGain&&microphoneGain.release();if(video.srcObject=null,"CANVAS"===video.tagName)for(var _i=0;_i<video.children.length;_i++)removeVideoElement(video.children[_i])}}function enableVideoControls(video){video&&!video.controls&&video.setAttribute("controls","controls")}var listDevices=function(labels,kind,deviceConstraints){deviceConstraints||(deviceConstraints={audio:!0,video:!0}),kind?"all"==kind&&(kind=""):kind=constants.MEDIA_DEVICE_KIND.INPUT;var getList=function(devices){for(var list={audio:[],video:[]},micCount=0,outputCount=0,camCount=0,i=0;i<devices.length;i++){var device=devices[i],ret={id:device.deviceId,label:device.label};0===device.kind.indexOf("audio"+kind)&&"communications"!=device.deviceId?(ret.type="audioinput"==device.kind?"mic":"speaker","mic"==ret.type&&""==ret.label&&(ret.label="microphone"+ ++micCount),"speaker"==ret.type&&""==ret.label&&(ret.label="speaker"+ ++outputCount),list.audio.push(ret)):0===device.kind.indexOf("video"+kind)?(""==ret.label&&(ret.label="camera"+ ++camCount),ret.type="camera",list.video.push(ret)):logger.debug("webrtc","unknown device "+device.kind+" id "+device.deviceId)}return list};return new Promise((function(resolve,reject){navigator.mediaDevices.enumerateDevices().then((function(devices){if(labels){var constraints=function(devices){for(var constraints={},i=0;i<devices.length;i++){var device=devices[i];0===device.kind.indexOf("audio"+kind)&&deviceConstraints.audio?constraints.audio=!0:0===device.kind.indexOf("video"+kind)&&deviceConstraints.video?constraints.video=!0:logger.debug("webrtc","unknown device "+device.kind+" id "+device.deviceId)}return constraints}(devices);if(0===Object.keys(constraints).length)return void reject(new Error(kind+" media devices not found"));navigator.getUserMedia(constraints,(function(stream){navigator.mediaDevices.enumerateDevices().then((function(devicesWithLabels){resolve(getList(devicesWithLabels)),stream.getTracks().forEach((function(track){track.stop()}))}),reject)}),reject)}else resolve(getList(devices))}),reject)}))};var screenCaptureSupportedBrowsers=function(){return util.Browser.isChrome()||util.Browser.isSafari()};module.exports={createConnection:function(options){return new Promise((function(resolve,reject){options.logger&&(logger=options.logger);var id=options.id,connectionConfig=options.connectionConfig||{iceServers:[]},connectionConstraints=options.connectionConstraints||{};connectionConstraints.hasOwnProperty("optional")||(connectionConstraints.optional=[{DtlsSrtpKeyAgreement:!0}]),connectionConfig.bundlePolicy="max-compat";var localVideo,currentAudioTrack,currentVideoTrack,systemSoundTrack,connection=new RTCPeerConnection(connectionConfig,connectionConstraints),display=options.display,localDisplay=options.localDisplay,remoteDisplay=options.remoteDisplay,bidirectional=options.bidirectional,remoteVideo=options.remoteVideo,switchCamIndex=0,switchMicCount=0,customStream=options.customStream,constraints=options.constraints?options.constraints:{},screenShare=!1,playoutDelay=options.playoutDelay,videoContentHint=options.videoContentHint?options.videoContentHint:"motion",unmutePlayOnStart=void 0===options.unmutePlayOnStart||options.unmutePlayOnStart,useControls=options.useControls||!1,unmuteRequiredEvent=options.unmuteRequiredEvent?options.unmuteRequiredEvent:null,zoom=null;if(bidirectional)(localVideo=getCacheInstance(localDisplay))&&(localVideo.srcObject?(localVideo.id=id+"-local",setContentHint(localVideo.srcObject,videoContentHint),addStreamTracks(connection,localVideo.srcObject)):localVideo=null),(remoteVideo=getCacheInstance(remoteDisplay))||(remoteVideo=createVideoElement(useControls),remoteDisplay.appendChild(remoteVideo)),remoteVideo.id=id+"-remote",options.audioOutputId&&"undefined"!=typeof remoteVideo.setSinkId&&remoteVideo.setSinkId(options.audioOutputId),remoteVideo.style="border-radius: 1px";else if(remoteVideo)remoteVideo.id&&(id=remoteVideo.id);else{var cachedVideo=getCacheInstance(display);cachedVideo&&-1===cachedVideo.id.indexOf("-REMOTE_CACHED_VIDEO")&&cachedVideo.srcObject?((localVideo=cachedVideo).id=id,setContentHint(localVideo.srcObject,videoContentHint),addStreamTracks(connection,localVideo.srcObject)):(cachedVideo?remoteVideo=cachedVideo:(remoteVideo=createVideoElement(useControls),display.appendChild(remoteVideo)),remoteVideo.id=id,options.audioOutputId&&"undefined"!=typeof remoteVideo.setSinkId&&remoteVideo.setSinkId(options.audioOutputId),remoteVideo.style="border-radius: 1px")}if(localVideo){useControls&&enableVideoControls(localVideo);var videoTrack=localVideo.srcObject.getVideoTracks()[0];videoTrack&&videoCams.forEach((function(cam,index){videoTrack.label===cam.label&&(switchCamIndex=index)}));var audioTrack=localVideo.srcObject.getAudioTracks()[0];audioTrack&&mics.forEach((function(mic,index){audioTrack.label===mic.label&&(switchMicCount=index)}))}function setContentHint(stream,hint){stream.getVideoTracks().forEach((function(track){void 0===track.contentHint?logger.warn("webrtc","Track contentHint unsupported"):(logger.info("webrtc","Set video track contentHint to "+hint),track.contentHint=hint)}))}function addStreamTracks(pc,stream){stream.getTracks().forEach((function(track){pc.addTrack(track,stream)}))}remoteVideo&&useControls&&enableVideoControls(remoteVideo),connection.ontrack=function(event){remoteVideo&&(remoteVideo.srcObject=event.streams[0],remoteVideo.onloadedmetadata=function(e){remoteVideo&&remoteVideo.play().then((function(){unmutePlayOnStart?remoteVideo.muted=!1:fireUnmuteEvent()})).catch((function(e){validBrowsers.includes(browserDetails.browser)?(logger.info("webrtc","Autoplay detected! Trying to play a video with a muted sound..."),remoteVideo.muted=!0,remoteVideo.play(),fireUnmuteEvent()):logger.error("webrtc",e)}))}),void 0!==playoutDelay&&connection.getReceivers().forEach((function(track){void 0===track.playoutDelayHint&&logger.warn("webrtc","Playout delay unsupported"),track.playoutDelayHint=playoutDelay}))},connection.onremovestream=function(event){remoteVideo&&remoteVideo.pause()},connection.onsignalingstatechange=function(event){},connection.oniceconnectionstatechange=function(event){},connection.onicecandidate=function(event){null!=event.candidate&&logger.debug("webrtc","Added icecandidate: "+event.candidate.candidate)};var unmuteAudio=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0&&(localVideo.srcObject.getAudioTracks()[0].enabled=!0)},unmuteVideo=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0&&(localVideo.srcObject.getVideoTracks()[0].enabled=!0)},getStat=function(){var _ref=_asyncToGenerator(_regenerator().m((function _callee(callbackFn,nativeStats){var result,rawStat;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:return result={outboundStream:{},inboundStream:{},otherStats:[]},_context.n=1,getWebRTCStats();case 1:rawStat=_context.v,nativeStats?callbackFn(rawStat):(rawStat["candidate-pair"]&&rawStat["candidate-pair"].forEach((function(report){"succeeded"===report.state&&report.nominated&&(report.availableIncomingBitrate?result.otherStats.availableIncomingBitrate=report.availableIncomingBitrate:localVideo&&report.availableOutgoingBitrate&&(result.otherStats.availableOutgoingBitrate=report.availableOutgoingBitrate))})),rawStat["outbound-rtp"]&&rawStat["outbound-rtp"].forEach((function(report){fillStatObject(result.outboundStream,report,report.kind),"video"===report.kind&&getVideoSize(result.outboundStream[report.kind],report.type,report)})),rawStat["inbound-rtp"]&&rawStat["inbound-rtp"].forEach((function(report){fillStatObject(result.inboundStream,report,report.kind),"video"===report.kind&&getVideoSize(result.inboundStream.video,report.type,report)})),callbackFn(result));case 2:return _context.a(2)}}),_callee)})));return function(_x,_x2){return _ref.apply(this,arguments)}}(),getVideoSize=function(obj,type,report){var videoSize={};"outbound-rtp"===type?void 0!==localVideo&&null!=localVideo&&(videoSize=localVideo.srcObject.getVideoTracks()[0].getSettings()):"inbound-rtp"===type&&void 0!==remoteVideo&&null!=remoteVideo&&(videoSize.width=remoteVideo.videoWidth,videoSize.height=remoteVideo.videoHeight),void 0!==report.frameWidth?obj.width=report.frameWidth:void 0!==videoSize.width&&(obj.width=videoSize.width),void 0!==report.frameHeight?obj.height=report.frameHeight:void 0!==videoSize.height&&(obj.height=videoSize.height)},fillStatObject=function(obj,report,mediaType){obj[mediaType]={};var description=null!=connection.currentRemoteDescription?connection.currentRemoteDescription:connection.remoteDescription,sdp="";description&&description.sdp?sdp=description.sdp:logger.debug("webrtc","Can't parse current SDP to detect codec and sampleRate");var qualityLimitationDurations,codec=util.getCurrentCodecAndSampleRate(sdp,mediaType);obj[mediaType].codec=codec.name,obj[mediaType].codecRate=codec.sampleRate,Object.keys(report).forEach((function(key){(key.startsWith("bytes")||key.startsWith("packets")||-1!=key.indexOf("Count")||-1!=key.indexOf("audioLevel")||"framesPerSecond"===key||"qualityLimitationReason"===key)&&(obj[mediaType][key]=report[key]),"qualityLimitationDurations"===key&&(qualityLimitationDurations=report[key])})),qualityLimitationDurations&&(obj[mediaType].qualityLimitationDurations=qualityLimitationDurations[obj[mediaType].qualityLimitationReason])},processScreenStream=function(stream,resolve){connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){currentAudioTrack=localVideo.srcObject.getAudioTracks()[0],currentVideoTrack=localVideo.srcObject.getVideoTracks()[0];var newVideoTrack=stream.getVideoTracks()[0];newVideoTrack.enabled=currentVideoTrack.enabled,sender.replaceTrack(newVideoTrack),localVideo.srcObject=stream,stream.getAudioTracks()[0]?(systemSoundTrack=stream.getAudioTracks()[0],connection.getSenders().forEach((function(sender){if("video"!==sender.track.kind){var mixedTrack=mixAudioTracks(stream,new MediaStream([sender.track]));mixedTrack.enabled=currentAudioTrack.enabled,sender.replaceTrack(mixedTrack),localVideo.srcObject.removeTrack(stream.getAudioTracks()[0]),localVideo.srcObject.addTrack(mixedTrack),currentAudioTrack.enabled=!0}}))):localVideo.srcObject.addTrack(currentAudioTrack)}})),logger.info("webrtc","Switch to screen"),screenShare=!0,resolve()},updateVideoSettings=function(settings){return new Promise((function(resolve,reject){connection&&settings&&connection.getSenders().forEach((function(sender){if("video"==sender.track.kind){for(var parameters=sender.getParameters(),i=0;i<parameters.encodings.length;i++)settings.maxBitrate?parameters.encodings[i].maxBitrate=1e3*settings.maxBitrate:parameters.encodings[i].maxBitrate&&delete parameters.encodings[i].maxBitrate,settings.frameRate&&(parameters.encodings[i].maxFramerate=settings.frameRate),settings.scaleResolutionDownBy&&(parameters.encodings[i].scaleResolutionDownBy=settings.scaleResolutionDownBy);sender.setParameters(parameters).then((function(){logger.info("webrtc","Set video encoder parameters to "+JSON.stringify(parameters.encodings)),resolve(parameters.encodings)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}}))}))},fireUnmuteEvent=function(){unmuteRequiredEvent&&"function"==typeof unmuteRequiredEvent&&unmuteRequiredEvent()},setZoom=function(){var _ref2=_asyncToGenerator(_regenerator().m((function _callee2(value){var _localVideo$srcObject3,_localVideo$srcObject4,track;return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(!zoom){_context2.n=6;break}if(!(value>=zoom.min&&value<=zoom.max)){_context2.n=4;break}if(!localVideo||!localVideo.srcObject){_context2.n=2;break}return _localVideo$srcObject3=localVideo.srcObject.getVideoTracks(),_localVideo$srcObject4=_slicedToArray(_localVideo$srcObject3,1),track=_localVideo$srcObject4[0],_context2.n=1,track.applyConstraints({advanced:[{zoom:value}]});case 1:zoom.value=value,_context2.n=3;break;case 2:logger.warn("webrtc","Can't set zoom value: no local video");case 3:_context2.n=5;break;case 4:logger.info("webrtc","Zoom value "+value+"is out of range: "+zoom.min+"-"+zoom.max);case 5:_context2.n=7;break;case 6:logger.info("webrtc","Zoom is not supported or zoom capabilities unknown yet");case 7:return _context2.a(2)}}),_callee2)})));return function(_x3){return _ref2.apply(this,arguments)}}(),getWebRTCStats=function(){return new Promise((function(resolve,reject){var browser=browserDetails.browser;connection&&validBrowsers.includes(browser)?connection.getStats(null).then((function(stats){var statObject={};stats&&stats.forEach((function(report){report&&(void 0===statObject[report.type]&&(statObject[report.type]=[]),statObject[report.type].push(report))})),resolve(statObject)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)})):reject(constants.ERROR_INFO.CAN_NOT_GET_STATS)}))},exports={state:function(){return connection.signalingState},createOffer:function(options){return new Promise((function(resolve,reject){var hasAudio=!0,hasVideo=!0;localVideo?(localVideo.srcObject.getAudioTracks()[0]||(hasAudio=!1),localVideo.srcObject.getVideoTracks()[0]||(hasVideo=!1,options.receiveVideo=!1)):"safari"!=browserDetails.browser||connection.getTransceivers().length||(options.receiveAudio&&connection.addTransceiver("audio",{direction:"recvonly"}),options.receiveVideo&&connection.addTransceiver("video",{direction:"recvonly"}));var constraints={offerToReceiveAudio:options.receiveAudio?1:0,offerToReceiveVideo:options.receiveVideo?1:0};connection.createOffer(constraints).then((function(offer){options.stereo&&(offer.sdp=offer.sdp.replace("minptime=10","minptime=10;stereo=1;sprop-stereo=1")),connection.setLocalDescription(offer).then((function(){var o={};o.sdp=util.stripCodecs(offer.sdp,options.stripCodecs),o.hasAudio=hasAudio,o.hasVideo=hasVideo,resolve(o)}))}))}))},createAnswer:function(options){return new Promise((function(resolve,reject){connection.createAnswer().then((function(answer){connection.setLocalDescription(answer).then((function(){resolve(util.stripCodecs(answer.sdp,options.stripCodecs))}))}))}))},setRemoteSdp:function(sdp){return logger.debug("webrtc","setRemoteSDP:"),logger.debug("webrtc",sdp),new Promise((function(resolve,reject){var sdpType;sdpType="have-local-offer"==connection.signalingState?"answer":"offer";var rtcSdp=new RTCSessionDescription({type:sdpType,sdp:sdp});connection.setRemoteDescription(rtcSdp).then((function(){browserDetails.browser,resolve()})).catch((function(error){reject(error)}))}))},changeAudioCodec:function(codec){return!1},close:function(cacheCamera){remoteVideo&&(removeVideoElement(remoteVideo),options.remoteVideo||(remoteVideo.id=remoteVideo.id+"-REMOTE_CACHED_VIDEO"),remoteVideo=null),localVideo&&!getCacheInstance(localDisplay||display)&&cacheCamera?(localVideo.id=localVideo.id+"-LOCAL_CACHED_VIDEO",unmuteAudio(),unmuteVideo(),localVideo=null):localVideo&&(localVideo.id=localVideo.id+"-LOCAL_CACHED_VIDEO",removeVideoElement(localVideo),localVideo=null),"closed"!==connection.signalingState&&connection.close(),delete connections[id]},setAudioOutputId:function(id){if(remoteVideo){if("edge"==browserDetails.browser){var srcObject=remoteVideo.srcObject;remoteVideo.srcObject=null;var res=remoteVideo.setSinkId(id);return remoteVideo.srcObject=srcObject,res}return remoteVideo.setSinkId(id)}},setVolume:function(volume){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.volume=volume/100)},unmuteRemoteAudio:function(){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.muted=!1)},muteRemoteAudio:function(){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.muted=!0)},isRemoteAudioMuted:function(){return!(remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0)||remoteVideo.muted},setMicrophoneGain:function(volume){microphoneGain&&(microphoneGain.gain.value=volume/100)},getVolume:function(){return remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0?100*remoteVideo.volume:-1},muteAudio:function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0&&(localVideo.srcObject.getAudioTracks()[0].enabled=!1)}};exports.unmuteAudio=unmuteAudio,exports.isAudioMuted=function(){return!(localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0)||!localVideo.srcObject.getAudioTracks()[0].enabled},exports.muteVideo=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0&&(localVideo.srcObject.getVideoTracks()[0].enabled=!1)},exports.unmuteVideo=unmuteVideo,exports.isVideoMuted=function(){return!(localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0)||!localVideo.srcObject.getVideoTracks()[0].enabled},exports.getStats=getStat,exports.fullScreen=function(){var video=document.getElementById(id);if(video)if(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else if(video.requestFullscreen){var result=video.requestFullscreen();util.isPromise(result)&&result.catch((function(e){logger.debug("webrtc",e)}))}else if(video.msRequestFullscreen)video.msRequestFullscreen();else if(video.mozRequestFullScreen)video.mozRequestFullScreen();else if(video.webkitRequestFullscreen)video.webkitRequestFullscreen();else if(video.webkitEnterFullscreen){video.webkitEnterFullscreen();var needRestart=!1;video.addEventListener("pause",(function(){needRestart&&(video.play(),needRestart=!1)})),video.addEventListener("webkitendfullscreen",(function(){video.play(),needRestart=!0}))}},exports.switchCam=function(deviceId){return new Promise((function(resolve,reject){localVideo&&localVideo.srcObject&&videoCams.length>1&&!customStream&&!screenShare?connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){var cameraId;sender.track.stop(),"undefined"!=typeof deviceId?(videoCams.forEach((function(cam,index){deviceId===cam.id&&(switchCamIndex=index)})),cameraId=deviceId):(switchCamIndex=(switchCamIndex+1)%videoCams.length,cameraId=videoCams[switchCamIndex].id),cameraId||(logger.error("webrtc","Can't detect camera to switch to"),reject(constants.ERROR_INFO.CAN_NOT_SWITCH_CAM));var clonedConstraints=Object.assign({},constraints);clonedConstraints.video.deviceId={exact:cameraId},clonedConstraints.audio=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){var newVideoTrack=newStream.getVideoTracks()[0];newVideoTrack.enabled=localVideo.srcObject.getVideoTracks()[0].enabled;var audioTrack=localVideo.srcObject.getAudioTracks()[0];sender.replaceTrack(newVideoTrack),localVideo.srcObject=newStream,0==localVideo.srcObject.getAudioTracks().length&&audioTrack&&localVideo.srcObject.addTrack(audioTrack),logger.info("webrtc","Switch camera to "+cameraId),resolve(cameraId)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SWITCH_CAM)}))},exports.switchMic=function(deviceId){return new Promise((function(resolve,reject){localVideo&&localVideo.srcObject&&mics.length>1&&!customStream?connection.getSenders().forEach((function(sender){if("video"!==sender.track.kind){switchMicCount=(switchMicCount+1)%mics.length,sender.track.stop(),microphoneGain&&microphoneGain.release();var mic="undefined"!=typeof deviceId?deviceId:mics[switchMicCount].id,clonedConstraints=Object.assign({},constraints);clonedConstraints.audio.deviceId={exact:mic},clonedConstraints.video=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){if(microphoneGain){var currentGain=microphoneGain.gain.value;(microphoneGain=createGainNode(newStream)).gain.value=currentGain}var newAudioTrack=newStream.getAudioTracks()[0];newAudioTrack.enabled=localVideo.srcObject.getAudioTracks()[0].enabled,currentAudioTrack=newAudioTrack;var videoTrack=localVideo.srcObject.getVideoTracks()[0];if(systemSoundTrack){var mixedTrack=mixAudioTracks(new MediaStream([newAudioTrack]),new MediaStream([systemSoundTrack]));mixedTrack.enabled=newAudioTrack.enabled,sender.replaceTrack(mixedTrack),localVideo.srcObject=new MediaStream([mixedTrack])}else sender.replaceTrack(newAudioTrack),localVideo.srcObject=newStream;videoTrack&&localVideo.srcObject.addTrack(videoTrack),logger.info("webrtc","Switch mic to "+mic),resolve(mic)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SWITCH_MIC)}))},exports.switchToScreen=function(source,woExtension){return new Promise((function(resolve,reject){if(!screenShare){var clonedConstraints={video:Object.assign({},constraints.video),audio:Object.assign({},constraints.audio)};if("firefox"===browserDetails.browser&&(clonedConstraints.video.mediaSource=source),woExtension)return void getScreenDeviceIdWoExtension(clonedConstraints).then((function(screenSharingConstraints){navigator.mediaDevices.getDisplayMedia(screenSharingConstraints).then((function(stream){processScreenStream(stream,resolve)})).catch(reject)}));getScreenDeviceId(clonedConstraints).then((function(screenSharingConstraints){clonedConstraints.sourceId=screenSharingConstraints.sourceId,screenSharingConstraints.audioMandatory?clonedConstraints.audio={mandatory:screenSharingConstraints.audioMandatory,optional:[]}:delete clonedConstraints.audio,"firefox"==browserDetails.browser?clonedConstraints.video=screenSharingConstraints:"chrome"==browserDetails.browser&&(delete clonedConstraints.video,clonedConstraints.video={mandatory:screenSharingConstraints.mandatory}),navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(stream){processScreenStream(stream,resolve)})).catch((function(reason){logger.error(reason),reject(reason)}))})).catch((function(reason){logger.error(reason),reject(reason)}))}}))},exports.switchToCam=function(){screenShare&&connection.getSenders().forEach((function(sender){"audio"!==sender.track.kind&&(currentVideoTrack.enabled=sender.track.enabled,sender.track.stop(),localVideo.srcObject=new MediaStream([currentVideoTrack]),sender.replaceTrack(currentVideoTrack),currentAudioTrack&&connection.getSenders().forEach((function(sender){"video"!==sender.track.kind&&(systemSoundTrack&&(currentAudioTrack.enabled=sender.track.enabled,sender.track.stop(),systemSoundTrack.stop(),systemSoundTrack=null,sender.replaceTrack(currentAudioTrack)),localVideo.srcObject.addTrack(currentAudioTrack))})))})),logger.info("webrtc","Switch to cam"),screenShare=!1},exports.setPublishingBitrate=function(minBitrate,maxBitrate){updateVideoSettings({maxBitrate:maxBitrate})},exports.updateVideoSettings=updateVideoSettings,exports.updateVideoResolution=function(resolution){return new Promise((function(resolve,reject){connection&&localVideo&&localVideo.srcObject&&!customStream&&resolution?connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){sender.track.stop();var clonedConstraints=Object.assign({},constraints);resolution.width&&(clonedConstraints.video.width={ideal:resolution.width}),resolution.height&&(clonedConstraints.video.height={ideal:resolution.height}),clonedConstraints.audio=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){var newVideoTrack=newStream.getVideoTracks()[0];newVideoTrack.enabled=localVideo.srcObject.getVideoTracks()[0].enabled;var audioTrack=localVideo.srcObject.getAudioTracks()[0];sender.replaceTrack(newVideoTrack),localVideo.srcObject=newStream,0==localVideo.srcObject.getAudioTracks().length&&audioTrack&&localVideo.srcObject.addTrack(audioTrack),logger.info("webrtc","Set video constraints to "+JSON.stringify(clonedConstraints.video)),resolve(clonedConstraints.video)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SET_RESOLUTION)}))},exports.getZoomCapabilities=function(){if(localVideo&&localVideo.srcObject)if(constraints.video&&constraints.video.zoom){var track=_slicedToArray(localVideo.srcObject.getVideoTracks(),1)[0],capabilities=track.getCapabilities(),settings=track.getSettings();"zoom"in settings?zoom={min:capabilities.zoom.min,max:capabilities.zoom.max,step:capabilities.zoom.step,value:settings.zoom}:(logger.info("webrtc","Zoom is not supported by "+track.label),zoom=null)}else zoom=null;return zoom},exports.setZoom=setZoom,exports.getZoom=function(){return zoom?zoom.value:-1},exports.getWebRTCStats=getWebRTCStats,connections[id]=exports,resolve(exports)}))},getMediaAccess:function(constraints,display,disableConstraintsNormalization,useCanvas){return new Promise((function(resolve,reject){constraints||(constraints=defaultConstraints),disableConstraintsNormalization||(constraints=function(constraints){var customStream=constraints.customStream;if((constraints=JSON.parse(JSON.stringify(constraints))).customStream=customStream,constraints.video&&(!0===constraints.video&&(constraints.video={}),"object"===_typeof(constraints.video))){var width=constraints.video.width,height=constraints.video.height;if("safari"==browserDetails.browser?width&&height?"object"===_typeof(width)&&"object"===_typeof(height)||(constraints.video.width={min:width,max:width},constraints.video.height={min:height,max:height}):(constraints.video.width={min:320,max:640},constraints.video.height={min:180,max:360}):(isNaN(width)||0===width||isNaN(height)||0===height)&&(constraints.video.width=320,constraints.video.height=240),"chrome"===browserDetails.browser&&browserDetails.version>=134);else{var frameRate=constraints.video.frameRate&&0!=constraints.video.frameRate?constraints.video.frameRate:30;constraints.video.frameRate={ideal:frameRate}}}constraints.audio&&constraints.audio.stereo&&(constraints.audio.echoCancellation=!1,constraints.audio.googEchoCancellation=!1);return constraints}(constraints));var cacheInstance=getCacheInstance(display);if(cacheInstance&&cacheInstance.srcObject&&JSON.stringify(display.mediaTrackConstraints)==JSON.stringify(constraints)&&!constraints.customStream)resolve(display);else if(display.mediaTrackConstraints=constraints,releaseMedia(display),constraints.video||constraints.audio||constraints.customStream)if(constraints.video&&constraints.video.type&&"screen"==constraints.video.type){if(delete constraints.video.type,screenCaptureSupportedBrowsers()&&constraints.video.withoutExtension)return void getScreenDeviceIdWoExtension(constraints).then((function(screenSharingConstraints){!function(constraints,requestAudioConstraints){navigator.mediaDevices.getDisplayMedia(constraints).then((function(stream){loadVideo(display,stream,!0,requestAudioConstraints,resolve,constraints)})).catch(reject)}(screenSharingConstraints,constraints.audio)}));var requestAudioConstraints=null;getScreenDeviceId(constraints).then((function(screenSharingConstraints){for(var prop in constraints.sourceId=screenSharingConstraints.sourceId,requestAudioConstraints=constraints.audio,screenSharingConstraints.audioMandatory?constraints.audio={mandatory:screenSharingConstraints.audioMandatory,optional:[]}:window.chrome&&(constraints.audio=!1),delete screenSharingConstraints.audioMandatory,delete screenSharingConstraints.sourceId,screenSharingConstraints)screenSharingConstraints.hasOwnProperty(prop)&&(constraints.video[prop]=screenSharingConstraints[prop]);"chrome"==browserDetails.browser&&(delete constraints.video.frameRate,delete constraints.video.height,delete constraints.video.width,delete constraints.systemSound),getAccess(constraints,!0,requestAudioConstraints)}),reject)}else getAccess(constraints);else resolve(display);function getAccess(constraints,screenShare,requestAudioConstraints){if(logger.info("webrtc",constraints),constraints.customStream)if(constraints.audio||constraints.video){var normalizedConstraints={audio:!!constraints.audio&&constraints.audio,video:!!constraints.video&&constraints.video};navigator.getUserMedia(normalizedConstraints,(function(stream){stream.getTracks().forEach((function(track){constraints.customStream.addTrack(track)})),loadVideo(display,constraints.customStream,screenShare,requestAudioConstraints,resolve,constraints)}),reject)}else loadVideo(display,constraints.customStream,screenShare,requestAudioConstraints,resolve,constraints);else listDevices(!1).then((function(devices){devices.video.forEach((function(device){videoCams.find((function(cam){return device.id===cam.id}))||videoCams.push(device)})),devices.audio.forEach((function(device){mics.find((function(mic){return device.id===mic.id}))||mics.push(device)})),navigator.getUserMedia(constraints,(function(stream){loadVideo(display,stream,screenShare,requestAudioConstraints,resolve,constraints,useCanvas)}),reject)}),reject)}}))},releaseMedia:releaseMedia,listDevices:listDevices,playFirstSound:function(){if(audioContext){for(var buffer=audioContext.createBuffer(1,441,44100),output=buffer.getChannelData(0),i=0;i<output.length;i++)output[i]=0;var source=audioContext.createBufferSource();return source.buffer=buffer,source.connect(audioContext.destination),source.start?source.start(0):source.play?source.play(0):source.noteOn&&source.noteOn(0),!0}return!1},playFirstVideo:function(display,isLocal,src){var useControls=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new Promise((function(resolve,reject){if(!getCacheInstance(display)){var video=createVideoElement(useControls);if(video.muted=!0,video.id=uuid_v1()+(isLocal?"-LOCAL_CACHED_VIDEO":"-REMOTE_CACHED_VIDEO"),src)return video.src=src,void video.play().then((function(){display.appendChild(video),video.removeAttribute("src"),resolve()})).catch((function(){logger.info("webrtc","Autoplay detected! Trying to play a video with a muted sound..."),video.muted=!0,video.play().then((function(){display.appendChild(video),video.removeAttribute("src"),resolve()})),video.onsuspend=function(event){reject()}}))}resolve()}))},available:function(){return"getUserMedia"in navigator&&"RTCPeerConnection"in window},configure:function(configuration){extensionId=configuration.extensionId,defaultConstraints=configuration.constraints,audioContext=configuration.audioContext,logger=configuration.logger,createMicGainNode="undefined"==typeof configuration.createMicGainNode||configuration.createMicGainNode,logger.info("webrtc","Initialized")},videoCams:videoCams,mics:mics,getAudioSourceDevice:function(){return audioSourceDevice},getCacheInstance:getCacheInstance,getVideoElement:function getVideoElement(display){if(display){var _step,_iterator=function(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function(){};return{s:F,n:function(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}(display.children);try{for(_iterator.s();!(_step=_iterator.n()).done;){var child=_step.value;if("video"===child.tagName.toLowerCase())return child;var grandchild=getVideoElement(child);if(grandchild)return grandchild}}catch(err){_iterator.e(err)}finally{_iterator.f()}}return null}}},{"./constants":39,"./util":42,uuid:8,"webrtc-adapter":23}]},{},[40])(40)}));
12
+ var KalmanFilter=function(){function KalmanFilter(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},_ref$R=_ref.R,R=void 0===_ref$R?1:_ref$R,_ref$Q=_ref.Q,Q=void 0===_ref$Q?1:_ref$Q,_ref$A=_ref.A,A=void 0===_ref$A?1:_ref$A,_ref$B=_ref.B,B=void 0===_ref$B?0:_ref$B,_ref$C=_ref.C,C=void 0===_ref$C?1:_ref$C;_classCallCheck(this,KalmanFilter),this.R=R,this.Q=Q,this.A=A,this.C=C,this.B=B,this.cov=NaN,this.x=NaN}var Constructor,protoProps,staticProps;return Constructor=KalmanFilter,(protoProps=[{key:"filter",value:function(z){var u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(isNaN(this.x))this.x=1/this.C*z,this.cov=1/this.C*this.Q*(1/this.C);else{var predX=this.predict(u),predCov=this.uncertainty(),K=predCov*this.C*(1/(this.C*predCov*this.C+this.Q));this.x=predX+K*(z-this.C*predX),this.cov=predCov-K*this.C*predCov}return this.x}},{key:"predict",value:function(){var u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return this.A*this.x+this.B*u}},{key:"uncertainty",value:function(){return this.A*this.cov*this.A+this.R}},{key:"lastMeasurement",value:function(){return this.x}},{key:"setMeasurementNoise",value:function(noise){this.Q=noise}},{key:"setProcessNoise",value:function(noise){this.R=noise}}])&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),KalmanFilter}();module.exports=KalmanFilter},{}],3:[function(require,module,exports){var cachedSetTimeout,cachedClearTimeout,process=module.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var currentQueue,queue=[],draining=!1,queueIndex=-1;function cleanUpNextTick(){draining&&currentQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,function(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(name){return[]},process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],4:[function(require,module,exports){(function(setImmediate){(function(){function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}!function(root){var setTimeoutFunc=setTimeout;function noop(){}function Promise(fn){if(!(this instanceof Promise))throw new TypeError("Promises must be constructed via new");if("function"!=typeof fn)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],doResolve(fn,this)}function handle(self,deferred){for(;3===self._state;)self=self._value;0!==self._state?(self._handled=!0,Promise._immediateFn((function(){var cb=1===self._state?deferred.onFulfilled:deferred.onRejected;if(null!==cb){var ret;try{ret=cb(self._value)}catch(e){return void reject(deferred.promise,e)}resolve(deferred.promise,ret)}else(1===self._state?resolve:reject)(deferred.promise,self._value)}))):self._deferreds.push(deferred)}function resolve(self,newValue){try{if(newValue===self)throw new TypeError("A promise cannot be resolved with itself.");if(newValue&&("object"===_typeof(newValue)||"function"==typeof newValue)){var then=newValue.then;if(newValue instanceof Promise)return self._state=3,self._value=newValue,void finale(self);if("function"==typeof then)return void doResolve((fn=then,thisArg=newValue,function(){fn.apply(thisArg,arguments)}),self)}self._state=1,self._value=newValue,finale(self)}catch(e){reject(self,e)}var fn,thisArg}function reject(self,newValue){self._state=2,self._value=newValue,finale(self)}function finale(self){2===self._state&&0===self._deferreds.length&&Promise._immediateFn((function(){self._handled||Promise._unhandledRejectionFn(self._value)}));for(var i=0,len=self._deferreds.length;i<len;i++)handle(self,self._deferreds[i]);self._deferreds=null}function Handler(onFulfilled,onRejected,promise){this.onFulfilled="function"==typeof onFulfilled?onFulfilled:null,this.onRejected="function"==typeof onRejected?onRejected:null,this.promise=promise}function doResolve(fn,self){var done=!1;try{fn((function(value){done||(done=!0,resolve(self,value))}),(function(reason){done||(done=!0,reject(self,reason))}))}catch(ex){if(done)return;done=!0,reject(self,ex)}}Promise.prototype.catch=function(onRejected){return this.then(null,onRejected)},Promise.prototype.then=function(onFulfilled,onRejected){var prom=new this.constructor(noop);return handle(this,new Handler(onFulfilled,onRejected,prom)),prom},Promise.all=function(arr){return new Promise((function(resolve,reject){if(!arr||"undefined"==typeof arr.length)throw new TypeError("Promise.all accepts an array");var args=Array.prototype.slice.call(arr);if(0===args.length)return resolve([]);var remaining=args.length;function res(i,val){try{if(val&&("object"===_typeof(val)||"function"==typeof val)){var then=val.then;if("function"==typeof then)return void then.call(val,(function(val){res(i,val)}),reject)}args[i]=val,0==--remaining&&resolve(args)}catch(ex){reject(ex)}}for(var i=0;i<args.length;i++)res(i,args[i])}))},Promise.resolve=function(value){return value&&"object"===_typeof(value)&&value.constructor===Promise?value:new Promise((function(resolve){resolve(value)}))},Promise.reject=function(value){return new Promise((function(resolve,reject){reject(value)}))},Promise.race=function(values){return new Promise((function(resolve,reject){for(var i=0,len=values.length;i<len;i++)values[i].then(resolve,reject)}))},Promise._immediateFn="function"==typeof setImmediate&&function(fn){setImmediate(fn)}||function(fn){setTimeoutFunc(fn,0)},Promise._unhandledRejectionFn=function(err){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",err)},Promise._setImmediateFn=function(fn){Promise._immediateFn=fn},Promise._setUnhandledRejectionFn=function(fn){Promise._unhandledRejectionFn=fn},"undefined"!=typeof module&&module.exports?module.exports=Promise:root.Promise||(root.Promise=Promise)}(this)}).call(this)}).call(this,require("timers").setImmediate)},{timers:7}],5:[function(require,module,exports){"use strict";var SDPUtils=require("sdp");function writeMediaSection(transceiver,caps,type,stream,dtlsRole){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":dtlsRole||"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var trackId=transceiver.rtpSender._initialTrackId||transceiver.rtpSender.track.id;transceiver.rtpSender._initialTrackId=trackId;var msid="msid:"+(stream?stream.id:"-")+" "+trackId+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp}function getCommonCapabilities(localCapabilities,remoteCapabilities){var commonCapabilities={codecs:[],headerExtensions:[],fecMechanisms:[]},findCodecByPayloadType=function(pt,codecs){pt=parseInt(pt,10);for(var i=0;i<codecs.length;i++)if(codecs[i].payloadType===pt||codecs[i].preferredPayloadType===pt)return codecs[i]},rtxCapabilityMatches=function(lRtx,rRtx,lCodecs,rCodecs){var lCodec=findCodecByPayloadType(lRtx.parameters.apt,lCodecs),rCodec=findCodecByPayloadType(rRtx.parameters.apt,rCodecs);return lCodec&&rCodec&&lCodec.name.toLowerCase()===rCodec.name.toLowerCase()};return localCapabilities.codecs.forEach((function(lCodec){for(var i=0;i<remoteCapabilities.codecs.length;i++){var rCodec=remoteCapabilities.codecs[i];if(lCodec.name.toLowerCase()===rCodec.name.toLowerCase()&&lCodec.clockRate===rCodec.clockRate){if("rtx"===lCodec.name.toLowerCase()&&lCodec.parameters&&rCodec.parameters.apt&&!rtxCapabilityMatches(lCodec,rCodec,localCapabilities.codecs,remoteCapabilities.codecs))continue;(rCodec=JSON.parse(JSON.stringify(rCodec))).numChannels=Math.min(lCodec.numChannels,rCodec.numChannels),commonCapabilities.codecs.push(rCodec),rCodec.rtcpFeedback=rCodec.rtcpFeedback.filter((function(fb){for(var j=0;j<lCodec.rtcpFeedback.length;j++)if(lCodec.rtcpFeedback[j].type===fb.type&&lCodec.rtcpFeedback[j].parameter===fb.parameter)return!0;return!1}));break}}})),localCapabilities.headerExtensions.forEach((function(lHeaderExtension){for(var i=0;i<remoteCapabilities.headerExtensions.length;i++){var rHeaderExtension=remoteCapabilities.headerExtensions[i];if(lHeaderExtension.uri===rHeaderExtension.uri){commonCapabilities.headerExtensions.push(rHeaderExtension);break}}})),commonCapabilities}function isActionAllowedInSignalingState(action,type,signalingState){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[type][action].indexOf(signalingState)}function maybeAddCandidate(iceTransport,candidate){var alreadyAdded=iceTransport.getRemoteCandidates().find((function(remoteCandidate){return candidate.foundation===remoteCandidate.foundation&&candidate.ip===remoteCandidate.ip&&candidate.port===remoteCandidate.port&&candidate.priority===remoteCandidate.priority&&candidate.protocol===remoteCandidate.protocol&&candidate.type===remoteCandidate.type}));return alreadyAdded||iceTransport.addRemoteCandidate(candidate),!alreadyAdded}function makeError(name,description){var e=new Error(description);return e.name=name,e.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[name],e}module.exports=function(window,edgeVersion){function addTrackToStreamAndFireEvent(track,stream){stream.addTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("addtrack",{track:track}))}function fireAddTrack(pc,track,receiver,streams){var trackEvent=new Event("track");trackEvent.track=track,trackEvent.receiver=receiver,trackEvent.transceiver={receiver:receiver},trackEvent.streams=streams,window.setTimeout((function(){pc._dispatchEvent("track",trackEvent)}))}var RTCPeerConnection=function(config){var pc=this,_eventTarget=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(method){pc[method]=_eventTarget[method].bind(_eventTarget)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",config=JSON.parse(JSON.stringify(config||{})),this.usingBundle="max-bundle"===config.bundlePolicy,"negotiate"===config.rtcpMuxPolicy)throw makeError("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(config.rtcpMuxPolicy||(config.rtcpMuxPolicy="require"),config.iceTransportPolicy){case"all":case"relay":break;default:config.iceTransportPolicy="all"}switch(config.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:config.bundlePolicy="balanced"}if(config.iceServers=function(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter((function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter((function(url){return 0===url.indexOf("turn:")&&-1!==url.indexOf("transport=udp")&&-1===url.indexOf("turn:[")&&!hasTurn?(hasTurn=!0,!0):0===url.indexOf("stun:")&&edgeVersion>=14393&&-1===url.indexOf("?transport=udp")})),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}}))}(config.iceServers||[],edgeVersion),this._iceGatherers=[],config.iceCandidatePoolSize)for(var i=config.iceCandidatePoolSize;i>0;i--)this._iceGatherers.push(new window.RTCIceGatherer({iceServers:config.iceServers,gatherPolicy:config.iceTransportPolicy}));else config.iceCandidatePoolSize=0;this._config=config,this.transceivers=[],this._sdpSessionId=SDPUtils.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(RTCPeerConnection.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(RTCPeerConnection.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),RTCPeerConnection.prototype.onicecandidate=null,RTCPeerConnection.prototype.onaddstream=null,RTCPeerConnection.prototype.ontrack=null,RTCPeerConnection.prototype.onremovestream=null,RTCPeerConnection.prototype.onsignalingstatechange=null,RTCPeerConnection.prototype.oniceconnectionstatechange=null,RTCPeerConnection.prototype.onconnectionstatechange=null,RTCPeerConnection.prototype.onicegatheringstatechange=null,RTCPeerConnection.prototype.onnegotiationneeded=null,RTCPeerConnection.prototype.ondatachannel=null,RTCPeerConnection.prototype._dispatchEvent=function(name,event){this._isClosed||(this.dispatchEvent(event),"function"==typeof this["on"+name]&&this["on"+name](event))},RTCPeerConnection.prototype._emitGatheringStateChange=function(){var event=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",event)},RTCPeerConnection.prototype.getConfiguration=function(){return this._config},RTCPeerConnection.prototype.getLocalStreams=function(){return this.localStreams},RTCPeerConnection.prototype.getRemoteStreams=function(){return this.remoteStreams},RTCPeerConnection.prototype._createTransceiver=function(kind,doNotAdd){var hasBundleTransport=this.transceivers.length>0,transceiver={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:kind,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&hasBundleTransport)transceiver.iceTransport=this.transceivers[0].iceTransport,transceiver.dtlsTransport=this.transceivers[0].dtlsTransport;else{var transports=this._createIceAndDtlsTransports();transceiver.iceTransport=transports.iceTransport,transceiver.dtlsTransport=transports.dtlsTransport}return doNotAdd||this.transceivers.push(transceiver),transceiver},RTCPeerConnection.prototype.addTrack=function(track,stream){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var transceiver;if(this.transceivers.find((function(s){return s.track===track})))throw makeError("InvalidAccessError","Track already exists.");for(var i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==track.kind||(transceiver=this.transceivers[i]);return transceiver||(transceiver=this._createTransceiver(track.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(stream)&&this.localStreams.push(stream),transceiver.track=track,transceiver.stream=stream,transceiver.rtpSender=new window.RTCRtpSender(track,transceiver.dtlsTransport),transceiver.rtpSender},RTCPeerConnection.prototype.addStream=function(stream){var pc=this;if(edgeVersion>=15025)stream.getTracks().forEach((function(track){pc.addTrack(track,stream)}));else{var clonedStream=stream.clone();stream.getTracks().forEach((function(track,idx){var clonedTrack=clonedStream.getTracks()[idx];track.addEventListener("enabled",(function(event){clonedTrack.enabled=event.enabled}))})),clonedStream.getTracks().forEach((function(track){pc.addTrack(track,clonedStream)}))}},RTCPeerConnection.prototype.removeTrack=function(sender){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(sender instanceof window.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var transceiver=this.transceivers.find((function(t){return t.rtpSender===sender}));if(!transceiver)throw makeError("InvalidAccessError","Sender was not created by this connection.");var stream=transceiver.stream;transceiver.rtpSender.stop(),transceiver.rtpSender=null,transceiver.track=null,transceiver.stream=null,-1===this.transceivers.map((function(t){return t.stream})).indexOf(stream)&&this.localStreams.indexOf(stream)>-1&&this.localStreams.splice(this.localStreams.indexOf(stream),1),this._maybeFireNegotiationNeeded()},RTCPeerConnection.prototype.removeStream=function(stream){var pc=this;stream.getTracks().forEach((function(track){var sender=pc.getSenders().find((function(s){return s.track===track}));sender&&pc.removeTrack(sender)}))},RTCPeerConnection.prototype.getSenders=function(){return this.transceivers.filter((function(transceiver){return!!transceiver.rtpSender})).map((function(transceiver){return transceiver.rtpSender}))},RTCPeerConnection.prototype.getReceivers=function(){return this.transceivers.filter((function(transceiver){return!!transceiver.rtpReceiver})).map((function(transceiver){return transceiver.rtpReceiver}))},RTCPeerConnection.prototype._createIceGatherer=function(sdpMLineIndex,usingBundle){var pc=this;if(usingBundle&&sdpMLineIndex>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var iceGatherer=new window.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(iceGatherer,"state",{value:"new",writable:!0}),this.transceivers[sdpMLineIndex].bufferedCandidateEvents=[],this.transceivers[sdpMLineIndex].bufferCandidates=function(event){var end=!event.candidate||0===Object.keys(event.candidate).length;iceGatherer.state=end?"completed":"gathering",null!==pc.transceivers[sdpMLineIndex].bufferedCandidateEvents&&pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event)},iceGatherer.addEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer},RTCPeerConnection.prototype._gather=function(mid,sdpMLineIndex){var pc=this,iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;if(!iceGatherer.onlocalcandidate){var bufferedCandidateEvents=this.transceivers[sdpMLineIndex].bufferedCandidateEvents;this.transceivers[sdpMLineIndex].bufferedCandidateEvents=null,iceGatherer.removeEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer.onlocalcandidate=function(evt){if(!(pc.usingBundle&&sdpMLineIndex>0)){var event=new Event("icecandidate");event.candidate={sdpMid:mid,sdpMLineIndex:sdpMLineIndex};var cand=evt.candidate,end=!cand||0===Object.keys(cand).length;if(end)"new"!==iceGatherer.state&&"gathering"!==iceGatherer.state||(iceGatherer.state="completed");else{"new"===iceGatherer.state&&(iceGatherer.state="gathering"),cand.component=1,cand.ufrag=iceGatherer.getLocalParameters().usernameFragment;var serializedCandidate=SDPUtils.writeCandidate(cand);event.candidate=Object.assign(event.candidate,SDPUtils.parseCandidate(serializedCandidate)),event.candidate.candidate=serializedCandidate,event.candidate.toJSON=function(){return{candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex,usernameFragment:event.candidate.usernameFragment}}}var sections=SDPUtils.getMediaSections(pc._localDescription.sdp);sections[event.candidate.sdpMLineIndex]+=end?"a=end-of-candidates\r\n":"a="+event.candidate.candidate+"\r\n",pc._localDescription.sdp=SDPUtils.getDescription(pc._localDescription.sdp)+sections.join("");var complete=pc.transceivers.every((function(transceiver){return transceiver.iceGatherer&&"completed"===transceiver.iceGatherer.state}));"gathering"!==pc.iceGatheringState&&(pc.iceGatheringState="gathering",pc._emitGatheringStateChange()),end||pc._dispatchEvent("icecandidate",event),complete&&(pc._dispatchEvent("icecandidate",new Event("icecandidate")),pc.iceGatheringState="complete",pc._emitGatheringStateChange())}},window.setTimeout((function(){bufferedCandidateEvents.forEach((function(e){iceGatherer.onlocalcandidate(e)}))}),0)}},RTCPeerConnection.prototype._createIceAndDtlsTransports=function(){var pc=this,iceTransport=new window.RTCIceTransport(null);iceTransport.onicestatechange=function(){pc._updateIceConnectionState(),pc._updateConnectionState()};var dtlsTransport=new window.RTCDtlsTransport(iceTransport);return dtlsTransport.ondtlsstatechange=function(){pc._updateConnectionState()},dtlsTransport.onerror=function(){Object.defineProperty(dtlsTransport,"state",{value:"failed",writable:!0}),pc._updateConnectionState()},{iceTransport:iceTransport,dtlsTransport:dtlsTransport}},RTCPeerConnection.prototype._disposeIceAndDtlsTransports=function(sdpMLineIndex){var iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;iceGatherer&&(delete iceGatherer.onlocalcandidate,delete this.transceivers[sdpMLineIndex].iceGatherer);var iceTransport=this.transceivers[sdpMLineIndex].iceTransport;iceTransport&&(delete iceTransport.onicestatechange,delete this.transceivers[sdpMLineIndex].iceTransport);var dtlsTransport=this.transceivers[sdpMLineIndex].dtlsTransport;dtlsTransport&&(delete dtlsTransport.ondtlsstatechange,delete dtlsTransport.onerror,delete this.transceivers[sdpMLineIndex].dtlsTransport)},RTCPeerConnection.prototype._transceive=function(transceiver,send,recv){var params=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);send&&transceiver.rtpSender&&(params.encodings=transceiver.sendEncodingParameters,params.rtcp={cname:SDPUtils.localCName,compound:transceiver.rtcpParameters.compound},transceiver.recvEncodingParameters.length&&(params.rtcp.ssrc=transceiver.recvEncodingParameters[0].ssrc),transceiver.rtpSender.send(params)),recv&&transceiver.rtpReceiver&&params.codecs.length>0&&("video"===transceiver.kind&&transceiver.recvEncodingParameters&&edgeVersion<15019&&transceiver.recvEncodingParameters.forEach((function(p){delete p.rtx})),transceiver.recvEncodingParameters.length?params.encodings=transceiver.recvEncodingParameters:params.encodings=[{}],params.rtcp={compound:transceiver.rtcpParameters.compound},transceiver.rtcpParameters.cname&&(params.rtcp.cname=transceiver.rtcpParameters.cname),transceiver.sendEncodingParameters.length&&(params.rtcp.ssrc=transceiver.sendEncodingParameters[0].ssrc),transceiver.rtpReceiver.receive(params))},RTCPeerConnection.prototype.setLocalDescription=function(description){var sections,sessionpart,pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setLocalDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set local "+description.type+" in state "+pc.signalingState));if("offer"===description.type)sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),sections.forEach((function(mediaSection,sdpMLineIndex){var caps=SDPUtils.parseRtpParameters(mediaSection);pc.transceivers[sdpMLineIndex].localCapabilities=caps})),pc.transceivers.forEach((function(transceiver,sdpMLineIndex){pc._gather(transceiver.mid,sdpMLineIndex)}));else if("answer"===description.type){sections=SDPUtils.splitSections(pc._remoteDescription.sdp),sessionpart=sections.shift();var isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0;sections.forEach((function(mediaSection,sdpMLineIndex){var transceiver=pc.transceivers[sdpMLineIndex],iceGatherer=transceiver.iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,localCapabilities=transceiver.localCapabilities,remoteCapabilities=transceiver.remoteCapabilities;if(!(SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length)&&!transceiver.rejected){var remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart);isIceLite&&(remoteDtlsParameters.role="server"),pc.usingBundle&&0!==sdpMLineIndex||(pc._gather(transceiver.mid,sdpMLineIndex),"new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,isIceLite?"controlling":"controlled"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters));var params=getCommonCapabilities(localCapabilities,remoteCapabilities);pc._transceive(transceiver,params.codecs.length>0,!1)}}))}return pc._localDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-local-offer"):pc._updateSignalingState("stable"),Promise.resolve()},RTCPeerConnection.prototype.setRemoteDescription=function(description){var pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setRemoteDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set remote "+description.type+" in state "+pc.signalingState));var streams={};pc.remoteStreams.forEach((function(stream){streams[stream.id]=stream}));var receiverList=[],sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0,usingBundle=SDPUtils.matchPrefix(sessionpart,"a=group:BUNDLE ").length>0;pc.usingBundle=usingBundle;var iceOptions=SDPUtils.matchPrefix(sessionpart,"a=ice-options:")[0];return pc.canTrickleIceCandidates=!!iceOptions&&iceOptions.substr(14).split(" ").indexOf("trickle")>=0,sections.forEach((function(mediaSection,sdpMLineIndex){var lines=SDPUtils.splitLines(mediaSection),kind=SDPUtils.getKind(mediaSection),rejected=SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length,protocol=lines[0].substr(2).split(" ")[2],direction=SDPUtils.getDirection(mediaSection,sessionpart),remoteMsid=SDPUtils.parseMsid(mediaSection),mid=SDPUtils.getMid(mediaSection)||SDPUtils.generateIdentifier();if(rejected||"application"===kind&&("DTLS/SCTP"===protocol||"UDP/DTLS/SCTP"===protocol))pc.transceivers[sdpMLineIndex]={mid:mid,kind:kind,protocol:protocol,rejected:!0};else{var transceiver,iceGatherer,iceTransport,dtlsTransport,rtpReceiver,sendEncodingParameters,recvEncodingParameters,localCapabilities,track;!rejected&&pc.transceivers[sdpMLineIndex]&&pc.transceivers[sdpMLineIndex].rejected&&(pc.transceivers[sdpMLineIndex]=pc._createTransceiver(kind,!0));var remoteIceParameters,remoteDtlsParameters,remoteCapabilities=SDPUtils.parseRtpParameters(mediaSection);rejected||(remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),(remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart)).role="client"),recvEncodingParameters=SDPUtils.parseRtpEncodingParameters(mediaSection);var rtcpParameters=SDPUtils.parseRtcpParameters(mediaSection),isComplete=SDPUtils.matchPrefix(mediaSection,"a=end-of-candidates",sessionpart).length>0,cands=SDPUtils.matchPrefix(mediaSection,"a=candidate:").map((function(cand){return SDPUtils.parseCandidate(cand)})).filter((function(cand){return 1===cand.component}));if(("offer"===description.type||"answer"===description.type)&&!rejected&&usingBundle&&sdpMLineIndex>0&&pc.transceivers[sdpMLineIndex]&&(pc._disposeIceAndDtlsTransports(sdpMLineIndex),pc.transceivers[sdpMLineIndex].iceGatherer=pc.transceivers[0].iceGatherer,pc.transceivers[sdpMLineIndex].iceTransport=pc.transceivers[0].iceTransport,pc.transceivers[sdpMLineIndex].dtlsTransport=pc.transceivers[0].dtlsTransport,pc.transceivers[sdpMLineIndex].rtpSender&&pc.transceivers[sdpMLineIndex].rtpSender.setTransport(pc.transceivers[0].dtlsTransport),pc.transceivers[sdpMLineIndex].rtpReceiver&&pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(pc.transceivers[0].dtlsTransport)),"offer"!==description.type||rejected){if("answer"===description.type&&!rejected){iceGatherer=(transceiver=pc.transceivers[sdpMLineIndex]).iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,rtpReceiver=transceiver.rtpReceiver,sendEncodingParameters=transceiver.sendEncodingParameters,localCapabilities=transceiver.localCapabilities,pc.transceivers[sdpMLineIndex].recvEncodingParameters=recvEncodingParameters,pc.transceivers[sdpMLineIndex].remoteCapabilities=remoteCapabilities,pc.transceivers[sdpMLineIndex].rtcpParameters=rtcpParameters,cands.length&&"new"===iceTransport.state&&(!isIceLite&&!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach((function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})):iceTransport.setRemoteCandidates(cands)),usingBundle&&0!==sdpMLineIndex||("new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,"controlling"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters)),!getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities).codecs.filter((function(c){return"rtx"===c.name.toLowerCase()})).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,pc._transceive(transceiver,"sendrecv"===direction||"recvonly"===direction,"sendrecv"===direction||"sendonly"===direction),!rtpReceiver||"sendrecv"!==direction&&"sendonly"!==direction?delete transceiver.rtpReceiver:(track=rtpReceiver.track,remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams[remoteMsid.stream]),receiverList.push([track,rtpReceiver,streams[remoteMsid.stream]])):(streams.default||(streams.default=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams.default),receiverList.push([track,rtpReceiver,streams.default])))}}else{(transceiver=pc.transceivers[sdpMLineIndex]||pc._createTransceiver(kind)).mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,usingBundle)),cands.length&&"new"===transceiver.iceTransport.state&&(!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach((function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})):transceiver.iceTransport.setRemoteCandidates(cands)),localCapabilities=window.RTCRtpReceiver.getCapabilities(kind),edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter((function(codec){return"rtx"!==codec.name}))),sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+2)}];var stream,isNewTrack=!1;if("sendrecv"===direction||"sendonly"===direction){if(isNewTrack=!transceiver.rtpReceiver,rtpReceiver=transceiver.rtpReceiver||new window.RTCRtpReceiver(transceiver.dtlsTransport,kind),isNewTrack)track=rtpReceiver.track,remoteMsid&&"-"===remoteMsid.stream||(remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream,Object.defineProperty(streams[remoteMsid.stream],"id",{get:function(){return remoteMsid.stream}})),Object.defineProperty(track,"id",{get:function(){return remoteMsid.track}}),stream=streams[remoteMsid.stream]):(streams.default||(streams.default=new window.MediaStream),stream=streams.default)),stream&&(addTrackToStreamAndFireEvent(track,stream),transceiver.associatedRemoteMediaStreams.push(stream)),receiverList.push([track,rtpReceiver,stream])}else transceiver.rtpReceiver&&transceiver.rtpReceiver.track&&(transceiver.associatedRemoteMediaStreams.forEach((function(s){var nativeTrack=s.getTracks().find((function(t){return t.id===transceiver.rtpReceiver.track.id}));nativeTrack&&function(track,stream){stream.removeTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("removetrack",{track:track}))}(nativeTrack,s)})),transceiver.associatedRemoteMediaStreams=[]);transceiver.localCapabilities=localCapabilities,transceiver.remoteCapabilities=remoteCapabilities,transceiver.rtpReceiver=rtpReceiver,transceiver.rtcpParameters=rtcpParameters,transceiver.sendEncodingParameters=sendEncodingParameters,transceiver.recvEncodingParameters=recvEncodingParameters,pc._transceive(pc.transceivers[sdpMLineIndex],!1,isNewTrack)}}})),void 0===pc._dtlsRole&&(pc._dtlsRole="offer"===description.type?"active":"passive"),pc._remoteDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-remote-offer"):pc._updateSignalingState("stable"),Object.keys(streams).forEach((function(sid){var stream=streams[sid];if(stream.getTracks().length){if(-1===pc.remoteStreams.indexOf(stream)){pc.remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,window.setTimeout((function(){pc._dispatchEvent("addstream",event)}))}receiverList.forEach((function(item){var track=item[0],receiver=item[1];stream.id===item[2].id&&fireAddTrack(pc,track,receiver,[stream])}))}})),receiverList.forEach((function(item){item[2]||fireAddTrack(pc,item[0],item[1],[])})),window.setTimeout((function(){pc&&pc.transceivers&&pc.transceivers.forEach((function(transceiver){transceiver.iceTransport&&"new"===transceiver.iceTransport.state&&transceiver.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),transceiver.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},RTCPeerConnection.prototype.close=function(){this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&transceiver.iceTransport.stop(),transceiver.dtlsTransport&&transceiver.dtlsTransport.stop(),transceiver.rtpSender&&transceiver.rtpSender.stop(),transceiver.rtpReceiver&&transceiver.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},RTCPeerConnection.prototype._updateSignalingState=function(newState){this.signalingState=newState;var event=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",event)},RTCPeerConnection.prototype._maybeFireNegotiationNeeded=function(){var pc=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,window.setTimeout((function(){if(pc.needNegotiation){pc.needNegotiation=!1;var event=new Event("negotiationneeded");pc._dispatchEvent("negotiationneeded",event)}}),0))},RTCPeerConnection.prototype._updateIceConnectionState=function(){var newState,states={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&!transceiver.rejected&&states[transceiver.iceTransport.state]++})),newState="new",states.failed>0?newState="failed":states.checking>0?newState="checking":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0?newState="connected":states.completed>0&&(newState="completed"),newState!==this.iceConnectionState){this.iceConnectionState=newState;var event=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",event)}},RTCPeerConnection.prototype._updateConnectionState=function(){var newState,states={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&transceiver.dtlsTransport&&!transceiver.rejected&&(states[transceiver.iceTransport.state]++,states[transceiver.dtlsTransport.state]++)})),states.connected+=states.completed,newState="new",states.failed>0?newState="failed":states.connecting>0?newState="connecting":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0&&(newState="connected"),newState!==this.connectionState){this.connectionState=newState;var event=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",event)}},RTCPeerConnection.prototype.createOffer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createOffer after close"));var numAudioTracks=pc.transceivers.filter((function(t){return"audio"===t.kind})).length,numVideoTracks=pc.transceivers.filter((function(t){return"video"===t.kind})).length,offerOptions=arguments[0];if(offerOptions){if(offerOptions.mandatory||offerOptions.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==offerOptions.offerToReceiveAudio&&(numAudioTracks=!0===offerOptions.offerToReceiveAudio?1:!1===offerOptions.offerToReceiveAudio?0:offerOptions.offerToReceiveAudio),void 0!==offerOptions.offerToReceiveVideo&&(numVideoTracks=!0===offerOptions.offerToReceiveVideo?1:!1===offerOptions.offerToReceiveVideo?0:offerOptions.offerToReceiveVideo)}for(pc.transceivers.forEach((function(transceiver){"audio"===transceiver.kind?--numAudioTracks<0&&(transceiver.wantReceive=!1):"video"===transceiver.kind&&--numVideoTracks<0&&(transceiver.wantReceive=!1)}));numAudioTracks>0||numVideoTracks>0;)numAudioTracks>0&&(pc._createTransceiver("audio"),numAudioTracks--),numVideoTracks>0&&(pc._createTransceiver("video"),numVideoTracks--);var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.transceivers.forEach((function(transceiver,sdpMLineIndex){var track=transceiver.track,kind=transceiver.kind,mid=transceiver.mid||SDPUtils.generateIdentifier();transceiver.mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,pc.usingBundle));var localCapabilities=window.RTCRtpSender.getCapabilities(kind);edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter((function(codec){return"rtx"!==codec.name}))),localCapabilities.codecs.forEach((function(codec){"H264"===codec.name&&void 0===codec.parameters["level-asymmetry-allowed"]&&(codec.parameters["level-asymmetry-allowed"]="1"),transceiver.remoteCapabilities&&transceiver.remoteCapabilities.codecs&&transceiver.remoteCapabilities.codecs.forEach((function(remoteCodec){codec.name.toLowerCase()===remoteCodec.name.toLowerCase()&&codec.clockRate===remoteCodec.clockRate&&(codec.preferredPayloadType=remoteCodec.payloadType)}))})),localCapabilities.headerExtensions.forEach((function(hdrExt){(transceiver.remoteCapabilities&&transceiver.remoteCapabilities.headerExtensions||[]).forEach((function(rHdrExt){hdrExt.uri===rHdrExt.uri&&(hdrExt.id=rHdrExt.id)}))}));var sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+1)}];track&&edgeVersion>=15019&&"video"===kind&&!sendEncodingParameters[0].rtx&&(sendEncodingParameters[0].rtx={ssrc:sendEncodingParameters[0].ssrc+1}),transceiver.wantReceive&&(transceiver.rtpReceiver=new window.RTCRtpReceiver(transceiver.dtlsTransport,kind)),transceiver.localCapabilities=localCapabilities,transceiver.sendEncodingParameters=sendEncodingParameters})),"max-compat"!==pc._config.bundlePolicy&&(sdp+="a=group:BUNDLE "+pc.transceivers.map((function(t){return t.mid})).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n",pc.transceivers.forEach((function(transceiver,sdpMLineIndex){sdp+=writeMediaSection(transceiver,transceiver.localCapabilities,"offer",transceiver.stream,pc._dtlsRole),sdp+="a=rtcp-rsize\r\n",!transceiver.iceGatherer||"new"===pc.iceGatheringState||0!==sdpMLineIndex&&pc.usingBundle||(transceiver.iceGatherer.getLocalCandidates().forEach((function(cand){cand.component=1,sdp+="a="+SDPUtils.writeCandidate(cand)+"\r\n"})),"completed"===transceiver.iceGatherer.state&&(sdp+="a=end-of-candidates\r\n"))}));var desc=new window.RTCSessionDescription({type:"offer",sdp:sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.createAnswer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==pc.signalingState&&"have-local-pranswer"!==pc.signalingState)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer in signalingState "+pc.signalingState));var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.usingBundle&&(sdp+="a=group:BUNDLE "+pc.transceivers.map((function(t){return t.mid})).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n";var mediaSectionsInOffer=SDPUtils.getMediaSections(pc._remoteDescription.sdp).length;pc.transceivers.forEach((function(transceiver,sdpMLineIndex){if(!(sdpMLineIndex+1>mediaSectionsInOffer)){if(transceiver.rejected)return"application"===transceiver.kind?"DTLS/SCTP"===transceiver.protocol?sdp+="m=application 0 DTLS/SCTP 5000\r\n":sdp+="m=application 0 "+transceiver.protocol+" webrtc-datachannel\r\n":"audio"===transceiver.kind?sdp+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===transceiver.kind&&(sdp+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(sdp+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+transceiver.mid+"\r\n");var localTrack;if(transceiver.stream)"audio"===transceiver.kind?localTrack=transceiver.stream.getAudioTracks()[0]:"video"===transceiver.kind&&(localTrack=transceiver.stream.getVideoTracks()[0]),localTrack&&edgeVersion>=15019&&"video"===transceiver.kind&&!transceiver.sendEncodingParameters[0].rtx&&(transceiver.sendEncodingParameters[0].rtx={ssrc:transceiver.sendEncodingParameters[0].ssrc+1});var commonCapabilities=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);!commonCapabilities.codecs.filter((function(c){return"rtx"===c.name.toLowerCase()})).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,sdp+=writeMediaSection(transceiver,commonCapabilities,"answer",transceiver.stream,pc._dtlsRole),transceiver.rtcpParameters&&transceiver.rtcpParameters.reducedSize&&(sdp+="a=rtcp-rsize\r\n")}}));var desc=new window.RTCSessionDescription({type:"answer",sdp:sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.addIceCandidate=function(candidate){var sections,pc=this;return candidate&&void 0===candidate.sdpMLineIndex&&!candidate.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(resolve,reject){if(!pc._remoteDescription)return reject(makeError("InvalidStateError","Can not add ICE candidate without a remote description"));if(candidate&&""!==candidate.candidate){var sdpMLineIndex=candidate.sdpMLineIndex;if(candidate.sdpMid)for(var i=0;i<pc.transceivers.length;i++)if(pc.transceivers[i].mid===candidate.sdpMid){sdpMLineIndex=i;break}var transceiver=pc.transceivers[sdpMLineIndex];if(!transceiver)return reject(makeError("OperationError","Can not add ICE candidate"));if(transceiver.rejected)return resolve();var cand=Object.keys(candidate.candidate).length>0?SDPUtils.parseCandidate(candidate.candidate):{};if("tcp"===cand.protocol&&(0===cand.port||9===cand.port))return resolve();if(cand.component&&1!==cand.component)return resolve();if((0===sdpMLineIndex||sdpMLineIndex>0&&transceiver.iceTransport!==pc.transceivers[0].iceTransport)&&!maybeAddCandidate(transceiver.iceTransport,cand))return reject(makeError("OperationError","Can not add ICE candidate"));var candidateString=candidate.candidate.trim();0===candidateString.indexOf("a=")&&(candidateString=candidateString.substr(2)),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[sdpMLineIndex]+="a="+(cand.type?candidateString:"end-of-candidates")+"\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join("")}else for(var j=0;j<pc.transceivers.length&&(pc.transceivers[j].rejected||(pc.transceivers[j].iceTransport.addRemoteCandidate({}),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[j]+="a=end-of-candidates\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join(""),!pc.usingBundle));j++);resolve()}))},RTCPeerConnection.prototype.getStats=function(selector){if(selector&&selector instanceof window.MediaStreamTrack){var senderOrReceiver=null;if(this.transceivers.forEach((function(transceiver){transceiver.rtpSender&&transceiver.rtpSender.track===selector?senderOrReceiver=transceiver.rtpSender:transceiver.rtpReceiver&&transceiver.rtpReceiver.track===selector&&(senderOrReceiver=transceiver.rtpReceiver)})),!senderOrReceiver)throw makeError("InvalidAccessError","Invalid selector.");return senderOrReceiver.getStats()}var promises=[];return this.transceivers.forEach((function(transceiver){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(method){transceiver[method]&&promises.push(transceiver[method].getStats())}))})),Promise.all(promises).then((function(allStats){var results=new Map;return allStats.forEach((function(stats){stats.forEach((function(stat){results.set(stat.id,stat)}))})),results}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(ortcObjectName){var obj=window[ortcObjectName];if(obj&&obj.prototype&&obj.prototype.getStats){var nativeGetstats=obj.prototype.getStats;obj.prototype.getStats=function(){return nativeGetstats.apply(this).then((function(nativeStats){var mapStats=new Map;return Object.keys(nativeStats).forEach((function(id){var stat;nativeStats[id].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(stat=nativeStats[id]).type]||stat.type,mapStats.set(id,nativeStats[id])})),mapStats}))}}}));var methods=["createOffer","createAnswer"];return methods.forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[0]||"function"==typeof args[1]?nativeMethod.apply(this,[arguments[2]]).then((function(description){"function"==typeof args[0]&&args[0].apply(null,[description])}),(function(error){"function"==typeof args[1]&&args[1].apply(null,[error])})):nativeMethod.apply(this,arguments)}})),(methods=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]||"function"==typeof args[2]?nativeMethod.apply(this,arguments).then((function(){"function"==typeof args[1]&&args[1].apply(null)}),(function(error){"function"==typeof args[2]&&args[2].apply(null,[error])})):nativeMethod.apply(this,arguments)}})),["getStats"].forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]?nativeMethod.apply(this,arguments).then((function(){"function"==typeof args[1]&&args[1].apply(null)})):nativeMethod.apply(this,arguments)}})),RTCPeerConnection}},{sdp:6}],6:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var SDPUtils={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};SDPUtils.localCName=SDPUtils.generateIdentifier(),SDPUtils.splitLines=function(blob){return blob.trim().split("\n").map((function(line){return line.trim()}))},SDPUtils.splitSections=function(blob){return blob.split("\nm=").map((function(part,index){return(index>0?"m="+part:part).trim()+"\r\n"}))},SDPUtils.getDescription=function(blob){var sections=SDPUtils.splitSections(blob);return sections&&sections[0]},SDPUtils.getMediaSections=function(blob){var sections=SDPUtils.splitSections(blob);return sections.shift(),sections},SDPUtils.matchPrefix=function(blob,prefix){return SDPUtils.splitLines(blob).filter((function(line){return 0===line.indexOf(prefix)}))},SDPUtils.parseCandidate=function(line){for(var parts,candidate={foundation:(parts=0===line.indexOf("a=candidate:")?line.substring(12).split(" "):line.substring(10).split(" "))[0],component:parseInt(parts[1],10),protocol:parts[2].toLowerCase(),priority:parseInt(parts[3],10),ip:parts[4],address:parts[4],port:parseInt(parts[5],10),type:parts[7]},i=8;i<parts.length;i+=2)switch(parts[i]){case"raddr":candidate.relatedAddress=parts[i+1];break;case"rport":candidate.relatedPort=parseInt(parts[i+1],10);break;case"tcptype":candidate.tcpType=parts[i+1];break;case"ufrag":candidate.ufrag=parts[i+1],candidate.usernameFragment=parts[i+1];break;default:candidate[parts[i]]=parts[i+1]}return candidate},SDPUtils.writeCandidate=function(candidate){var sdp=[];sdp.push(candidate.foundation),sdp.push(candidate.component),sdp.push(candidate.protocol.toUpperCase()),sdp.push(candidate.priority),sdp.push(candidate.address||candidate.ip),sdp.push(candidate.port);var type=candidate.type;return sdp.push("typ"),sdp.push(type),"host"!==type&&candidate.relatedAddress&&candidate.relatedPort&&(sdp.push("raddr"),sdp.push(candidate.relatedAddress),sdp.push("rport"),sdp.push(candidate.relatedPort)),candidate.tcpType&&"tcp"===candidate.protocol.toLowerCase()&&(sdp.push("tcptype"),sdp.push(candidate.tcpType)),(candidate.usernameFragment||candidate.ufrag)&&(sdp.push("ufrag"),sdp.push(candidate.usernameFragment||candidate.ufrag)),"candidate:"+sdp.join(" ")},SDPUtils.parseIceOptions=function(line){return line.substr(14).split(" ")},SDPUtils.parseRtpMap=function(line){var parts=line.substr(9).split(" "),parsed={payloadType:parseInt(parts.shift(),10)};return parts=parts[0].split("/"),parsed.name=parts[0],parsed.clockRate=parseInt(parts[1],10),parsed.channels=3===parts.length?parseInt(parts[2],10):1,parsed.numChannels=parsed.channels,parsed},SDPUtils.writeRtpMap=function(codec){var pt=codec.payloadType;void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType);var channels=codec.channels||codec.numChannels||1;return"a=rtpmap:"+pt+" "+codec.name+"/"+codec.clockRate+(1!==channels?"/"+channels:"")+"\r\n"},SDPUtils.parseExtmap=function(line){var parts=line.substr(9).split(" ");return{id:parseInt(parts[0],10),direction:parts[0].indexOf("/")>0?parts[0].split("/")[1]:"sendrecv",uri:parts[1]}},SDPUtils.writeExtmap=function(headerExtension){return"a=extmap:"+(headerExtension.id||headerExtension.preferredId)+(headerExtension.direction&&"sendrecv"!==headerExtension.direction?"/"+headerExtension.direction:"")+" "+headerExtension.uri+"\r\n"},SDPUtils.parseFmtp=function(line){for(var kv,parsed={},parts=line.substr(line.indexOf(" ")+1).split(";"),j=0;j<parts.length;j++)parsed[(kv=parts[j].trim().split("="))[0].trim()]=kv[1];return parsed},SDPUtils.writeFmtp=function(codec){var line="",pt=codec.payloadType;if(void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.parameters&&Object.keys(codec.parameters).length){var params=[];Object.keys(codec.parameters).forEach((function(param){codec.parameters[param]?params.push(param+"="+codec.parameters[param]):params.push(param)})),line+="a=fmtp:"+pt+" "+params.join(";")+"\r\n"}return line},SDPUtils.parseRtcpFb=function(line){var parts=line.substr(line.indexOf(" ")+1).split(" ");return{type:parts.shift(),parameter:parts.join(" ")}},SDPUtils.writeRtcpFb=function(codec){var lines="",pt=codec.payloadType;return void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.rtcpFeedback&&codec.rtcpFeedback.length&&codec.rtcpFeedback.forEach((function(fb){lines+="a=rtcp-fb:"+pt+" "+fb.type+(fb.parameter&&fb.parameter.length?" "+fb.parameter:"")+"\r\n"})),lines},SDPUtils.parseSsrcMedia=function(line){var sp=line.indexOf(" "),parts={ssrc:parseInt(line.substr(7,sp-7),10)},colon=line.indexOf(":",sp);return colon>-1?(parts.attribute=line.substr(sp+1,colon-sp-1),parts.value=line.substr(colon+1)):parts.attribute=line.substr(sp+1),parts},SDPUtils.parseSsrcGroup=function(line){var parts=line.substr(13).split(" ");return{semantics:parts.shift(),ssrcs:parts.map((function(ssrc){return parseInt(ssrc,10)}))}},SDPUtils.getMid=function(mediaSection){var mid=SDPUtils.matchPrefix(mediaSection,"a=mid:")[0];if(mid)return mid.substr(6)},SDPUtils.parseFingerprint=function(line){var parts=line.substr(14).split(" ");return{algorithm:parts[0].toLowerCase(),value:parts[1]}},SDPUtils.getDtlsParameters=function(mediaSection,sessionpart){return{role:"auto",fingerprints:SDPUtils.matchPrefix(mediaSection+sessionpart,"a=fingerprint:").map(SDPUtils.parseFingerprint)}},SDPUtils.writeDtlsParameters=function(params,setupType){var sdp="a=setup:"+setupType+"\r\n";return params.fingerprints.forEach((function(fp){sdp+="a=fingerprint:"+fp.algorithm+" "+fp.value+"\r\n"})),sdp},SDPUtils.parseCryptoLine=function(line){var parts=line.substr(9).split(" ");return{tag:parseInt(parts[0],10),cryptoSuite:parts[1],keyParams:parts[2],sessionParams:parts.slice(3)}},SDPUtils.writeCryptoLine=function(parameters){return"a=crypto:"+parameters.tag+" "+parameters.cryptoSuite+" "+("object"===_typeof(parameters.keyParams)?SDPUtils.writeCryptoKeyParams(parameters.keyParams):parameters.keyParams)+(parameters.sessionParams?" "+parameters.sessionParams.join(" "):"")+"\r\n"},SDPUtils.parseCryptoKeyParams=function(keyParams){if(0!==keyParams.indexOf("inline:"))return null;var parts=keyParams.substr(7).split("|");return{keyMethod:"inline",keySalt:parts[0],lifeTime:parts[1],mkiValue:parts[2]?parts[2].split(":")[0]:void 0,mkiLength:parts[2]?parts[2].split(":")[1]:void 0}},SDPUtils.writeCryptoKeyParams=function(keyParams){return keyParams.keyMethod+":"+keyParams.keySalt+(keyParams.lifeTime?"|"+keyParams.lifeTime:"")+(keyParams.mkiValue&&keyParams.mkiLength?"|"+keyParams.mkiValue+":"+keyParams.mkiLength:"")},SDPUtils.getCryptoParameters=function(mediaSection,sessionpart){return SDPUtils.matchPrefix(mediaSection+sessionpart,"a=crypto:").map(SDPUtils.parseCryptoLine)},SDPUtils.getIceParameters=function(mediaSection,sessionpart){var ufrag=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-ufrag:")[0],pwd=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-pwd:")[0];return ufrag&&pwd?{usernameFragment:ufrag.substr(12),password:pwd.substr(10)}:null},SDPUtils.writeIceParameters=function(params){return"a=ice-ufrag:"+params.usernameFragment+"\r\na=ice-pwd:"+params.password+"\r\n"},SDPUtils.parseRtpParameters=function(mediaSection){for(var description={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},mline=SDPUtils.splitLines(mediaSection)[0].split(" "),i=3;i<mline.length;i++){var pt=mline[i],rtpmapline=SDPUtils.matchPrefix(mediaSection,"a=rtpmap:"+pt+" ")[0];if(rtpmapline){var codec=SDPUtils.parseRtpMap(rtpmapline),fmtps=SDPUtils.matchPrefix(mediaSection,"a=fmtp:"+pt+" ");switch(codec.parameters=fmtps.length?SDPUtils.parseFmtp(fmtps[0]):{},codec.rtcpFeedback=SDPUtils.matchPrefix(mediaSection,"a=rtcp-fb:"+pt+" ").map(SDPUtils.parseRtcpFb),description.codecs.push(codec),codec.name.toUpperCase()){case"RED":case"ULPFEC":description.fecMechanisms.push(codec.name.toUpperCase())}}}return SDPUtils.matchPrefix(mediaSection,"a=extmap:").forEach((function(line){description.headerExtensions.push(SDPUtils.parseExtmap(line))})),description},SDPUtils.writeRtpDescription=function(kind,caps){var sdp="";sdp+="m="+kind+" ",sdp+=caps.codecs.length>0?"9":"0",sdp+=" UDP/TLS/RTP/SAVPF ",sdp+=caps.codecs.map((function(codec){return void 0!==codec.preferredPayloadType?codec.preferredPayloadType:codec.payloadType})).join(" ")+"\r\n",sdp+="c=IN IP4 0.0.0.0\r\n",sdp+="a=rtcp:9 IN IP4 0.0.0.0\r\n",caps.codecs.forEach((function(codec){sdp+=SDPUtils.writeRtpMap(codec),sdp+=SDPUtils.writeFmtp(codec),sdp+=SDPUtils.writeRtcpFb(codec)}));var maxptime=0;return caps.codecs.forEach((function(codec){codec.maxptime>maxptime&&(maxptime=codec.maxptime)})),maxptime>0&&(sdp+="a=maxptime:"+maxptime+"\r\n"),sdp+="a=rtcp-mux\r\n",caps.headerExtensions&&caps.headerExtensions.forEach((function(extension){sdp+=SDPUtils.writeExtmap(extension)})),sdp},SDPUtils.parseRtpEncodingParameters=function(mediaSection){var secondarySsrc,encodingParameters=[],description=SDPUtils.parseRtpParameters(mediaSection),hasRed=-1!==description.fecMechanisms.indexOf("RED"),hasUlpfec=-1!==description.fecMechanisms.indexOf("ULPFEC"),ssrcs=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(parts){return"cname"===parts.attribute})),primarySsrc=ssrcs.length>0&&ssrcs[0].ssrc,flows=SDPUtils.matchPrefix(mediaSection,"a=ssrc-group:FID").map((function(line){return line.substr(17).split(" ").map((function(part){return parseInt(part,10)}))}));flows.length>0&&flows[0].length>1&&flows[0][0]===primarySsrc&&(secondarySsrc=flows[0][1]),description.codecs.forEach((function(codec){if("RTX"===codec.name.toUpperCase()&&codec.parameters.apt){var encParam={ssrc:primarySsrc,codecPayloadType:parseInt(codec.parameters.apt,10)};primarySsrc&&secondarySsrc&&(encParam.rtx={ssrc:secondarySsrc}),encodingParameters.push(encParam),hasRed&&((encParam=JSON.parse(JSON.stringify(encParam))).fec={ssrc:primarySsrc,mechanism:hasUlpfec?"red+ulpfec":"red"},encodingParameters.push(encParam))}})),0===encodingParameters.length&&primarySsrc&&encodingParameters.push({ssrc:primarySsrc});var bandwidth=SDPUtils.matchPrefix(mediaSection,"b=");return bandwidth.length&&(bandwidth=0===bandwidth[0].indexOf("b=TIAS:")?parseInt(bandwidth[0].substr(7),10):0===bandwidth[0].indexOf("b=AS:")?1e3*parseInt(bandwidth[0].substr(5),10)*.95-16e3:void 0,encodingParameters.forEach((function(params){params.maxBitrate=bandwidth}))),encodingParameters},SDPUtils.parseRtcpParameters=function(mediaSection){var rtcpParameters={},remoteSsrc=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(obj){return"cname"===obj.attribute}))[0];remoteSsrc&&(rtcpParameters.cname=remoteSsrc.value,rtcpParameters.ssrc=remoteSsrc.ssrc);var rsize=SDPUtils.matchPrefix(mediaSection,"a=rtcp-rsize");rtcpParameters.reducedSize=rsize.length>0,rtcpParameters.compound=0===rsize.length;var mux=SDPUtils.matchPrefix(mediaSection,"a=rtcp-mux");return rtcpParameters.mux=mux.length>0,rtcpParameters},SDPUtils.parseMsid=function(mediaSection){var parts,spec=SDPUtils.matchPrefix(mediaSection,"a=msid:");if(1===spec.length)return{stream:(parts=spec[0].substr(7).split(" "))[0],track:parts[1]};var planB=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(msidParts){return"msid"===msidParts.attribute}));return planB.length>0?{stream:(parts=planB[0].value.split(" "))[0],track:parts[1]}:void 0},SDPUtils.parseSctpDescription=function(mediaSection){var maxMessageSize,mline=SDPUtils.parseMLine(mediaSection),maxSizeLine=SDPUtils.matchPrefix(mediaSection,"a=max-message-size:");maxSizeLine.length>0&&(maxMessageSize=parseInt(maxSizeLine[0].substr(19),10)),isNaN(maxMessageSize)&&(maxMessageSize=65536);var sctpPort=SDPUtils.matchPrefix(mediaSection,"a=sctp-port:");if(sctpPort.length>0)return{port:parseInt(sctpPort[0].substr(12),10),protocol:mline.fmt,maxMessageSize:maxMessageSize};if(SDPUtils.matchPrefix(mediaSection,"a=sctpmap:").length>0){var parts=SDPUtils.matchPrefix(mediaSection,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(parts[0],10),protocol:parts[1],maxMessageSize:maxMessageSize}}},SDPUtils.writeSctpDescription=function(media,sctp){var output=[];return output="DTLS/SCTP"!==media.protocol?["m="+media.kind+" 9 "+media.protocol+" "+sctp.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+sctp.port+"\r\n"]:["m="+media.kind+" 9 "+media.protocol+" "+sctp.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+sctp.port+" "+sctp.protocol+" 65535\r\n"],void 0!==sctp.maxMessageSize&&output.push("a=max-message-size:"+sctp.maxMessageSize+"\r\n"),output.join("")},SDPUtils.generateSessionId=function(){return Math.random().toString().substr(2,21)},SDPUtils.writeSessionBoilerplate=function(sessId,sessVer,sessUser){var version=void 0!==sessVer?sessVer:2;return"v=0\r\no="+(sessUser||"thisisadapterortc")+" "+(sessId||SDPUtils.generateSessionId())+" "+version+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},SDPUtils.writeMediaSection=function(transceiver,caps,type,stream){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.direction?sdp+="a="+transceiver.direction+"\r\n":transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var msid="msid:"+stream.id+" "+transceiver.rtpSender.track.id+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp},SDPUtils.getDirection=function(mediaSection,sessionpart){for(var lines=SDPUtils.splitLines(mediaSection),i=0;i<lines.length;i++)switch(lines[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return lines[i].substr(2)}return sessionpart?SDPUtils.getDirection(sessionpart):"sendrecv"},SDPUtils.getKind=function(mediaSection){return SDPUtils.splitLines(mediaSection)[0].split(" ")[0].substr(2)},SDPUtils.isRejected=function(mediaSection){return"0"===mediaSection.split(" ",2)[1]},SDPUtils.parseMLine=function(mediaSection){var parts=SDPUtils.splitLines(mediaSection)[0].substr(2).split(" ");return{kind:parts[0],port:parseInt(parts[1],10),protocol:parts[2],fmt:parts.slice(3).join(" ")}},SDPUtils.parseOLine=function(mediaSection){var parts=SDPUtils.matchPrefix(mediaSection,"o=")[0].substr(2).split(" ");return{username:parts[0],sessionId:parts[1],sessionVersion:parseInt(parts[2],10),netType:parts[3],addressType:parts[4],address:parts[5]}},SDPUtils.isValidSDP=function(blob){if("string"!=typeof blob||0===blob.length)return!1;for(var lines=SDPUtils.splitLines(blob),i=0;i<lines.length;i++)if(lines[i].length<2||"="!==lines[i].charAt(1))return!1;return!0},"object"===("undefined"==typeof module?"undefined":_typeof(module))&&(module.exports=SDPUtils)},{}],7:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;msecs>=0&&(item._idleTimeoutId=setTimeout((function(){item._onTimeout&&item._onTimeout()}),msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick((function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))})),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":3,timers:7}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"v1",{enumerable:!0,get:function(){return _v.default}}),Object.defineProperty(exports,"v3",{enumerable:!0,get:function(){return _v2.default}}),Object.defineProperty(exports,"v4",{enumerable:!0,get:function(){return _v3.default}}),Object.defineProperty(exports,"v5",{enumerable:!0,get:function(){return _v4.default}}),Object.defineProperty(exports,"NIL",{enumerable:!0,get:function(){return _nil.default}}),Object.defineProperty(exports,"version",{enumerable:!0,get:function(){return _version.default}}),Object.defineProperty(exports,"validate",{enumerable:!0,get:function(){return _validate.default}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return _stringify.default}}),Object.defineProperty(exports,"parse",{enumerable:!0,get:function(){return _parse.default}});var _v=_interopRequireDefault(require("./v1.js")),_v2=_interopRequireDefault(require("./v3.js")),_v3=_interopRequireDefault(require("./v4.js")),_v4=_interopRequireDefault(require("./v5.js")),_nil=_interopRequireDefault(require("./nil.js")),_version=_interopRequireDefault(require("./version.js")),_validate=_interopRequireDefault(require("./validate.js")),_stringify=_interopRequireDefault(require("./stringify.js")),_parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}},{"./nil.js":10,"./parse.js":11,"./stringify.js":15,"./v1.js":16,"./v3.js":17,"./v4.js":19,"./v5.js":20,"./validate.js":21,"./version.js":22}],9:[function(require,module,exports){"use strict";function getOutputLength(inputLength8){return 14+(inputLength8+64>>>9<<4)+1}function safeAdd(x,y){var lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw}function md5cmn(q,a,b,x,s,t){return safeAdd((num=safeAdd(safeAdd(a,q),safeAdd(x,t)))<<(cnt=s)|num>>>32-cnt,b);var num,cnt}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t)}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t)}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t)}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _default=function(bytes){if("string"==typeof bytes){var msg=unescape(encodeURIComponent(bytes));bytes=new Uint8Array(msg.length);for(var i=0;i<msg.length;++i)bytes[i]=msg.charCodeAt(i)}return function(input){for(var output=[],length32=32*input.length,i=0;i<length32;i+=8){var x=input[i>>5]>>>i%32&255,hex=parseInt("0123456789abcdef".charAt(x>>>4&15)+"0123456789abcdef".charAt(15&x),16);output.push(hex)}return output}(function(x,len){x[len>>5]|=128<<len%32,x[getOutputLength(len)-1]=len;for(var a=1732584193,b=-271733879,c=-1732584194,d=271733878,i=0;i<x.length;i+=16){var olda=a,oldb=b,oldc=c,oldd=d;a=md5ff(a,b,c,d,x[i],7,-680876936),d=md5ff(d,a,b,c,x[i+1],12,-389564586),c=md5ff(c,d,a,b,x[i+2],17,606105819),b=md5ff(b,c,d,a,x[i+3],22,-1044525330),a=md5ff(a,b,c,d,x[i+4],7,-176418897),d=md5ff(d,a,b,c,x[i+5],12,1200080426),c=md5ff(c,d,a,b,x[i+6],17,-1473231341),b=md5ff(b,c,d,a,x[i+7],22,-45705983),a=md5ff(a,b,c,d,x[i+8],7,1770035416),d=md5ff(d,a,b,c,x[i+9],12,-1958414417),c=md5ff(c,d,a,b,x[i+10],17,-42063),b=md5ff(b,c,d,a,x[i+11],22,-1990404162),a=md5ff(a,b,c,d,x[i+12],7,1804603682),d=md5ff(d,a,b,c,x[i+13],12,-40341101),c=md5ff(c,d,a,b,x[i+14],17,-1502002290),b=md5ff(b,c,d,a,x[i+15],22,1236535329),a=md5gg(a,b,c,d,x[i+1],5,-165796510),d=md5gg(d,a,b,c,x[i+6],9,-1069501632),c=md5gg(c,d,a,b,x[i+11],14,643717713),b=md5gg(b,c,d,a,x[i],20,-373897302),a=md5gg(a,b,c,d,x[i+5],5,-701558691),d=md5gg(d,a,b,c,x[i+10],9,38016083),c=md5gg(c,d,a,b,x[i+15],14,-660478335),b=md5gg(b,c,d,a,x[i+4],20,-405537848),a=md5gg(a,b,c,d,x[i+9],5,568446438),d=md5gg(d,a,b,c,x[i+14],9,-1019803690),c=md5gg(c,d,a,b,x[i+3],14,-187363961),b=md5gg(b,c,d,a,x[i+8],20,1163531501),a=md5gg(a,b,c,d,x[i+13],5,-1444681467),d=md5gg(d,a,b,c,x[i+2],9,-51403784),c=md5gg(c,d,a,b,x[i+7],14,1735328473),b=md5gg(b,c,d,a,x[i+12],20,-1926607734),a=md5hh(a,b,c,d,x[i+5],4,-378558),d=md5hh(d,a,b,c,x[i+8],11,-2022574463),c=md5hh(c,d,a,b,x[i+11],16,1839030562),b=md5hh(b,c,d,a,x[i+14],23,-35309556),a=md5hh(a,b,c,d,x[i+1],4,-1530992060),d=md5hh(d,a,b,c,x[i+4],11,1272893353),c=md5hh(c,d,a,b,x[i+7],16,-155497632),b=md5hh(b,c,d,a,x[i+10],23,-1094730640),a=md5hh(a,b,c,d,x[i+13],4,681279174),d=md5hh(d,a,b,c,x[i],11,-358537222),c=md5hh(c,d,a,b,x[i+3],16,-722521979),b=md5hh(b,c,d,a,x[i+6],23,76029189),a=md5hh(a,b,c,d,x[i+9],4,-640364487),d=md5hh(d,a,b,c,x[i+12],11,-421815835),c=md5hh(c,d,a,b,x[i+15],16,530742520),b=md5hh(b,c,d,a,x[i+2],23,-995338651),a=md5ii(a,b,c,d,x[i],6,-198630844),d=md5ii(d,a,b,c,x[i+7],10,1126891415),c=md5ii(c,d,a,b,x[i+14],15,-1416354905),b=md5ii(b,c,d,a,x[i+5],21,-57434055),a=md5ii(a,b,c,d,x[i+12],6,1700485571),d=md5ii(d,a,b,c,x[i+3],10,-1894986606),c=md5ii(c,d,a,b,x[i+10],15,-1051523),b=md5ii(b,c,d,a,x[i+1],21,-2054922799),a=md5ii(a,b,c,d,x[i+8],6,1873313359),d=md5ii(d,a,b,c,x[i+15],10,-30611744),c=md5ii(c,d,a,b,x[i+6],15,-1560198380),b=md5ii(b,c,d,a,x[i+13],21,1309151649),a=md5ii(a,b,c,d,x[i+4],6,-145523070),d=md5ii(d,a,b,c,x[i+11],10,-1120210379),c=md5ii(c,d,a,b,x[i+2],15,718787259),b=md5ii(b,c,d,a,x[i+9],21,-343485551),a=safeAdd(a,olda),b=safeAdd(b,oldb),c=safeAdd(c,oldc),d=safeAdd(d,oldd)}return[a,b,c,d]}(function(input){if(0===input.length)return[];for(var length8=8*input.length,output=new Uint32Array(getOutputLength(length8)),i=0;i<length8;i+=8)output[i>>5]|=(255&input[i/8])<<i%32;return output}(bytes),8*bytes.length))};exports.default=_default},{}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default="00000000-0000-0000-0000-000000000000"},{}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){if(!(0,_validate.default)(uuid))throw TypeError("Invalid UUID");var v,arr=new Uint8Array(16);return arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24,arr[1]=v>>>16&255,arr[2]=v>>>8&255,arr[3]=255&v,arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8,arr[5]=255&v,arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8,arr[7]=255&v,arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8,arr[9]=255&v,arr[10]=(v=parseInt(uuid.slice(24,36),16))/1099511627776&255,arr[11]=v/4294967296&255,arr[12]=v>>>24&255,arr[13]=v>>>16&255,arr[14]=v>>>8&255,arr[15]=255&v,arr};exports.default=_default},{"./validate.js":21}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},{}],13:[function(require,module,exports){"use strict";var getRandomValues;Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(){if(!getRandomValues&&!(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)};var rnds8=new Uint8Array(16)},{}],14:[function(require,module,exports){"use strict";function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z}}function ROTL(x,n){return x<<n|x>>>32-n}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _default=function(bytes){var K=[1518500249,1859775393,2400959708,3395469782],H=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof bytes){var msg=unescape(encodeURIComponent(bytes));bytes=[];for(var i=0;i<msg.length;++i)bytes.push(msg.charCodeAt(i))}else Array.isArray(bytes)||(bytes=Array.prototype.slice.call(bytes));bytes.push(128);for(var l=bytes.length/4+2,N=Math.ceil(l/16),M=new Array(N),_i=0;_i<N;++_i){for(var arr=new Uint32Array(16),j=0;j<16;++j)arr[j]=bytes[64*_i+4*j]<<24|bytes[64*_i+4*j+1]<<16|bytes[64*_i+4*j+2]<<8|bytes[64*_i+4*j+3];M[_i]=arr}M[N-1][14]=8*(bytes.length-1)/Math.pow(2,32),M[N-1][14]=Math.floor(M[N-1][14]),M[N-1][15]=8*(bytes.length-1)&4294967295;for(var _i2=0;_i2<N;++_i2){for(var W=new Uint32Array(80),t=0;t<16;++t)W[t]=M[_i2][t];for(var _t=16;_t<80;++_t)W[_t]=ROTL(W[_t-3]^W[_t-8]^W[_t-14]^W[_t-16],1);for(var a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],_t2=0;_t2<80;++_t2){var s=Math.floor(_t2/20),T=ROTL(a,5)+f(s,b,c,d)+e+K[s]+W[_t2]>>>0;e=d,d=c,c=ROTL(b,30)>>>0,b=a,a=T}H[0]=H[0]+a>>>0,H[1]=H[1]+b>>>0,H[2]=H[2]+c>>>0,H[3]=H[3]+d>>>0,H[4]=H[4]+e>>>0}return[H[0]>>24&255,H[0]>>16&255,H[0]>>8&255,255&H[0],H[1]>>24&255,H[1]>>16&255,H[1]>>8&255,255&H[1],H[2]>>24&255,H[2]>>16&255,H[2]>>8&255,255&H[2],H[3]>>24&255,H[3]>>16&255,H[3]>>8&255,255&H[3],H[4]>>24&255,H[4]>>16&255,H[4]>>8&255,255&H[4]]};exports.default=_default},{}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};for(var byteToHex=[],i=0;i<256;++i)byteToHex.push((i+256).toString(16).substr(1));var _default=function(arr){var offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,uuid=(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();if(!(0,_validate.default)(uuid))throw TypeError("Stringified UUID is invalid");return uuid};exports.default=_default},{"./validate.js":21}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _nodeId,_clockseq,_rng=_interopRequireDefault(require("./rng.js")),_stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _lastMSecs=0,_lastNSecs=0;var _default=function(options,buf,offset){var i=buf&&offset||0,b=buf||new Array(16),node=(options=options||{}).node||_nodeId,clockseq=void 0!==options.clockseq?options.clockseq:_clockseq;if(null==node||null==clockseq){var seedBytes=options.random||(options.rng||_rng.default)();null==node&&(node=_nodeId=[1|seedBytes[0],seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]]),null==clockseq&&(clockseq=_clockseq=16383&(seedBytes[6]<<8|seedBytes[7]))}var msecs=void 0!==options.msecs?options.msecs:Date.now(),nsecs=void 0!==options.nsecs?options.nsecs:_lastNSecs+1,dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&void 0===options.clockseq&&(clockseq=clockseq+1&16383),(dt<0||msecs>_lastMSecs)&&void 0===options.nsecs&&(nsecs=0),nsecs>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_lastMSecs=msecs,_lastNSecs=nsecs,_clockseq=clockseq;var tl=(1e4*(268435455&(msecs+=122192928e5))+nsecs)%4294967296;b[i++]=tl>>>24&255,b[i++]=tl>>>16&255,b[i++]=tl>>>8&255,b[i++]=255&tl;var tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255,b[i++]=255&tmh,b[i++]=tmh>>>24&15|16,b[i++]=tmh>>>16&255,b[i++]=clockseq>>>8|128,b[i++]=255&clockseq;for(var n=0;n<6;++n)b[i+n]=node[n];return buf||(0,_stringify.default)(b)};exports.default=_default},{"./rng.js":13,"./stringify.js":15}],17:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js")),_md=_interopRequireDefault(require("./md5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=(0,_v.default)("v3",48,_md.default);exports.default=_default},{"./md5.js":9,"./v35.js":18}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(name,version,hashfunc){function generateUUID(value,namespace,buf,offset){if("string"==typeof value&&(value=function(str){str=unescape(encodeURIComponent(str));for(var bytes=[],i=0;i<str.length;++i)bytes.push(str.charCodeAt(i));return bytes}(value)),"string"==typeof namespace&&(namespace=(0,_parse.default)(namespace)),16!==namespace.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var bytes=new Uint8Array(16+value.length);if(bytes.set(namespace),bytes.set(value,namespace.length),(bytes=hashfunc(bytes))[6]=15&bytes[6]|version,bytes[8]=63&bytes[8]|128,buf){offset=offset||0;for(var i=0;i<16;++i)buf[offset+i]=bytes[i];return buf}return(0,_stringify.default)(bytes)}try{generateUUID.name=name}catch(err){}return generateUUID.DNS=DNS,generateUUID.URL=URL,generateUUID},exports.URL=exports.DNS=void 0;var _stringify=_interopRequireDefault(require("./stringify.js")),_parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";exports.DNS=DNS;var URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";exports.URL=URL},{"./parse.js":11,"./stringify.js":15}],19:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js")),_stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=function(options,buf,offset){var rnds=(options=options||{}).random||(options.rng||_rng.default)();if(rnds[6]=15&rnds[6]|64,rnds[8]=63&rnds[8]|128,buf){offset=offset||0;for(var i=0;i<16;++i)buf[offset+i]=rnds[i];return buf}return(0,_stringify.default)(rnds)};exports.default=_default},{"./rng.js":13,"./stringify.js":15}],20:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js")),_sha=_interopRequireDefault(require("./sha1.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=(0,_v.default)("v5",80,_sha.default);exports.default=_default},{"./sha1.js":14,"./v35.js":18}],21:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_regex=(obj=require("./regex.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){return"string"==typeof uuid&&_regex.default.test(uuid)};exports.default=_default},{"./regex.js":12}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){if(!(0,_validate.default)(uuid))throw TypeError("Invalid UUID");return parseInt(uuid.substr(14,1),16)};exports.default=_default},{"./validate.js":21}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var adapter=(0,require("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});exports.default=adapter},{"./adapter_factory.js":24}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adapterFactory=function(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},window=_ref.window,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},logging=utils.log,browserDetails=utils.detectBrowser(window),adapter={browserDetails:browserDetails,commonShim:commonShim,extractVersion:utils.extractVersion,disableLog:utils.disableLog,disableWarnings:utils.disableWarnings};switch(browserDetails.browser){case"chrome":if(!chromeShim||!chromeShim.shimPeerConnection||!options.shimChrome)return logging("Chrome shim is not included in this adapter release."),adapter;if(null===browserDetails.version)return logging("Chrome shim can not determine version, not shimming."),adapter;logging("adapter.js shimming chrome."),adapter.browserShim=chromeShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),chromeShim.shimGetUserMedia(window,browserDetails),chromeShim.shimMediaStream(window,browserDetails),chromeShim.shimPeerConnection(window,browserDetails),chromeShim.shimOnTrack(window,browserDetails),chromeShim.shimAddTrackRemoveTrack(window,browserDetails),chromeShim.shimGetSendersWithDtmf(window,browserDetails),chromeShim.shimGetStats(window,browserDetails),chromeShim.shimSenderReceiverGetStats(window,browserDetails),chromeShim.fixNegotiationNeeded(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;case"firefox":if(!firefoxShim||!firefoxShim.shimPeerConnection||!options.shimFirefox)return logging("Firefox shim is not included in this adapter release."),adapter;logging("adapter.js shimming firefox."),adapter.browserShim=firefoxShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),firefoxShim.shimGetUserMedia(window,browserDetails),firefoxShim.shimPeerConnection(window,browserDetails),firefoxShim.shimOnTrack(window,browserDetails),firefoxShim.shimRemoveStream(window,browserDetails),firefoxShim.shimSenderGetStats(window,browserDetails),firefoxShim.shimReceiverGetStats(window,browserDetails),firefoxShim.shimRTCDataChannel(window,browserDetails),firefoxShim.shimAddTransceiver(window,browserDetails),firefoxShim.shimGetParameters(window,browserDetails),firefoxShim.shimCreateOffer(window,browserDetails),firefoxShim.shimCreateAnswer(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"edge":if(!edgeShim||!edgeShim.shimPeerConnection||!options.shimEdge)return logging("MS edge shim is not included in this adapter release."),adapter;logging("adapter.js shimming edge."),adapter.browserShim=edgeShim,edgeShim.shimGetUserMedia(window,browserDetails),edgeShim.shimGetDisplayMedia(window,browserDetails),edgeShim.shimPeerConnection(window,browserDetails),edgeShim.shimReplaceTrack(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"safari":if(!safariShim||!options.shimSafari)return logging("Safari shim is not included in this adapter release."),adapter;logging("adapter.js shimming safari."),adapter.browserShim=safariShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),safariShim.shimRTCIceServerUrls(window,browserDetails),safariShim.shimCreateOfferLegacy(window,browserDetails),safariShim.shimCallbacksAPI(window,browserDetails),safariShim.shimLocalStreamsAPI(window,browserDetails),safariShim.shimRemoteStreamsAPI(window,browserDetails),safariShim.shimTrackEventTransceiver(window,browserDetails),safariShim.shimGetUserMedia(window,browserDetails),safariShim.shimAudioContext(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;default:logging("Unsupported browser!")}return adapter};var utils=_interopRequireWildcard(require("./utils")),chromeShim=_interopRequireWildcard(require("./chrome/chrome_shim")),edgeShim=_interopRequireWildcard(require("./edge/edge_shim")),firefoxShim=_interopRequireWildcard(require("./firefox/firefox_shim")),safariShim=_interopRequireWildcard(require("./safari/safari_shim")),commonShim=_interopRequireWildcard(require("./common_shim"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}},{"./chrome/chrome_shim":25,"./common_shim":28,"./edge/edge_shim":29,"./firefox/firefox_shim":33,"./safari/safari_shim":36,"./utils":37}],25:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimMediaStream=function(window){window.MediaStream=window.MediaStream||window.webkitMediaStream},exports.shimOnTrack=function(window){if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("ontrack"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(f){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=f)},enumerable:!0,configurable:!0});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var _this=this;return this._ontrackpoly||(this._ontrackpoly=function(e){e.stream.addEventListener("addtrack",(function(te){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===te.track.id})):{track:te.track};var event=new Event("track");event.track=te.track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)})),e.stream.getTracks().forEach((function(track){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===track.id})):{track:track};var event=new Event("track");event.track=track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)}))},this.addEventListener("addstream",this._ontrackpoly)),origSetRemoteDescription.apply(this,arguments)}}else utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}))},exports.shimGetSendersWithDtmf=function(window){if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("getSenders"in window.RTCPeerConnection.prototype)&&"createDTMFSender"in window.RTCPeerConnection.prototype){var shimSenderWithDtmf=function(pc,track){return{track:track,get dtmf(){return void 0===this._dtmf&&("audio"===track.kind?this._dtmf=pc.createDTMFSender(track):this._dtmf=null),this._dtmf},_pc:pc}};if(!window.RTCPeerConnection.prototype.getSenders){window.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){var sender=origAddTrack.apply(this,arguments);return sender||(sender=shimSenderWithDtmf(this,track),this._senders.push(sender)),sender};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){origRemoveTrack.apply(this,arguments);var idx=this._senders.indexOf(sender);-1!==idx&&this._senders.splice(idx,1)}}var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this2=this;this._senders=this._senders||[],origAddStream.apply(this,[stream]),stream.getTracks().forEach((function(track){_this2._senders.push(shimSenderWithDtmf(_this2,track))}))};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._senders=this._senders||[],origRemoveStream.apply(this,[stream]),stream.getTracks().forEach((function(track){var sender=_this3._senders.find((function(s){return s.track===track}));sender&&_this3._senders.splice(_this3._senders.indexOf(sender),1)}))}}else if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&"getSenders"in window.RTCPeerConnection.prototype&&"createDTMFSender"in window.RTCPeerConnection.prototype&&window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;window.RTCPeerConnection.prototype.getSenders=function(){var _this4=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this4})),senders},Object.defineProperty(window.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}},exports.shimGetStats=function(window){if(!window.RTCPeerConnection)return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _this5=this,_arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];if(arguments.length>0&&"function"==typeof selector)return origGetStats.apply(this,arguments);if(0===origGetStats.length&&(0===arguments.length||"function"!=typeof selector))return origGetStats.apply(this,[]);var fixChromeStats_=function(response){var standardReport={};return response.result().forEach((function(report){var standardStats={id:report.id,timestamp:report.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[report.type]||report.type};report.names().forEach((function(name){standardStats[name]=report.stat(name)})),standardReport[standardStats.id]=standardStats})),standardReport},makeMapStats=function(stats){return new Map(Object.keys(stats).map((function(key){return[key,stats[key]]})))};if(arguments.length>=2){var successCallbackWrapper_=function(response){onSucc(makeMapStats(fixChromeStats_(response)))};return origGetStats.apply(this,[successCallbackWrapper_,selector])}return new Promise((function(resolve,reject){origGetStats.apply(_this5,[function(response){resolve(makeMapStats(fixChromeStats_(response)))},reject])})).then(onSucc,onErr)}},exports.shimSenderReceiverGetStats=function(window){if(!("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&window.RTCRtpSender&&window.RTCRtpReceiver))return;if(!("getStats"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this6=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this6})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window.RTCRtpSender.prototype.getStats=function(){var sender=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,sender.track,!0)}))}}if(!("getStats"in window.RTCRtpReceiver.prototype)){var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this7=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this7})),receivers}),utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){var receiver=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,receiver.track,!1)}))}}if(!("getStats"in window.RTCRtpSender.prototype)||!("getStats"in window.RTCRtpReceiver.prototype))return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof window.MediaStreamTrack){var track=arguments[0],sender=void 0,receiver=void 0,err=void 0;return this.getSenders().forEach((function(s){s.track===track&&(sender?err=!0:sender=s)})),this.getReceivers().forEach((function(r){return r.track===track&&(receiver?err=!0:receiver=r),r.track===track})),err||sender&&receiver?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):sender?sender.getStats():receiver?receiver.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return origGetStats.apply(this,arguments)}},exports.shimAddTrackRemoveTrackWithNative=shimAddTrackRemoveTrackWithNative,exports.shimAddTrackRemoveTrack=function(window,browserDetails){if(!window.RTCPeerConnection)return;if(window.RTCPeerConnection.prototype.addTrack&&browserDetails.version>=65)return shimAddTrackRemoveTrackWithNative(window);var origGetLocalStreams=window.RTCPeerConnection.prototype.getLocalStreams;window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this11=this,nativeStreams=origGetLocalStreams.apply(this);return this._reverseStreams=this._reverseStreams||{},nativeStreams.map((function(stream){return _this11._reverseStreams[stream.id]}))};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this12=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},stream.getTracks().forEach((function(track){if(_this12.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[stream.id]){var newStream=new window.MediaStream(stream.getTracks());this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,stream=newStream}origAddStream.apply(this,[stream])};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;function replaceInternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(internalStream.id,"g"),externalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}function replaceExternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(externalStream.id,"g"),internalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}window.RTCPeerConnection.prototype.removeStream=function(stream){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},origRemoveStream.apply(this,[this._streams[stream.id]||stream]),delete this._reverseStreams[this._streams[stream.id]?this._streams[stream.id].id:stream.id],delete this._streams[stream.id]},window.RTCPeerConnection.prototype.addTrack=function(track,stream){var _this13=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var streams=[].slice.call(arguments,1);if(1!==streams.length||!streams[0].getTracks().find((function(t){return t===track})))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var alreadyExists=this.getSenders().find((function(s){return s.track===track}));if(alreadyExists)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var oldStream=this._streams[stream.id];if(oldStream)oldStream.addTrack(track),Promise.resolve().then((function(){_this13.dispatchEvent(new Event("negotiationneeded"))}));else{var newStream=new window.MediaStream([track]);this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,this.addStream(newStream)}return this.getSenders().find((function(s){return s.track===track}))},["createOffer","createAnswer"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){var _this14=this,args=arguments,isLegacyCall=arguments.length&&"function"==typeof arguments[0];return isLegacyCall?nativeMethod.apply(this,[function(description){var desc=replaceInternalStreamId(_this14,description);args[0].apply(null,[desc])},function(err){args[1]&&args[1].apply(null,err)},arguments[2]]):nativeMethod.apply(this,arguments).then((function(description){return replaceInternalStreamId(_this14,description)}))}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var origSetLocalDescription=window.RTCPeerConnection.prototype.setLocalDescription;window.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=replaceExternalStreamId(this,arguments[0]),origSetLocalDescription.apply(this,arguments)):origSetLocalDescription.apply(this,arguments)};var origLocalDescription=Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(window.RTCPeerConnection.prototype,"localDescription",{get:function(){var description=origLocalDescription.get.apply(this);return""===description.type?description:replaceInternalStreamId(this,description)}}),window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this15=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!sender._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(sender._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var stream=void 0;Object.keys(this._streams).forEach((function(streamid){_this15._streams[streamid].getTracks().find((function(track){return sender.track===track}))&&(stream=_this15._streams[streamid])})),stream&&(1===stream.getTracks().length?this.removeStream(this._reverseStreams[stream.id]):stream.removeTrack(sender.track),this.dispatchEvent(new Event("negotiationneeded")))}},exports.shimPeerConnection=function(window,browserDetails){!window.RTCPeerConnection&&window.webkitRTCPeerConnection&&(window.RTCPeerConnection=window.webkitRTCPeerConnection);if(!window.RTCPeerConnection)return;browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}))},exports.fixNegotiationNeeded=function(window,browserDetails){utils.wrapPeerConnectionEvent(window,"negotiationneeded",(function(e){var pc=e.target;if(!(browserDetails.version<72||pc.getConfiguration&&"plan-b"===pc.getConfiguration().sdpSemantics)||"stable"===pc.signalingState)return e}))};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js"));function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimAddTrackRemoveTrackWithNative(window){window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this8=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((function(streamId){return _this8._shimmedLocalStreams[streamId][0]}))};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){if(!stream)return origAddTrack.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var sender=origAddTrack.apply(this,arguments);return this._shimmedLocalStreams[stream.id]?-1===this._shimmedLocalStreams[stream.id].indexOf(sender)&&this._shimmedLocalStreams[stream.id].push(sender):this._shimmedLocalStreams[stream.id]=[stream,sender],sender};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this9=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},stream.getTracks().forEach((function(track){if(_this9.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")}));var existingSenders=this.getSenders();origAddStream.apply(this,arguments);var newSenders=this.getSenders().filter((function(newSender){return-1===existingSenders.indexOf(newSender)}));this._shimmedLocalStreams[stream.id]=[stream].concat(newSenders)};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[stream.id],origRemoveStream.apply(this,arguments)};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this10=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},sender&&Object.keys(this._shimmedLocalStreams).forEach((function(streamId){var idx=_this10._shimmedLocalStreams[streamId].indexOf(sender);-1!==idx&&_this10._shimmedLocalStreams[streamId].splice(idx,1),1===_this10._shimmedLocalStreams[streamId].length&&delete _this10._shimmedLocalStreams[streamId]})),origRemoveTrack.apply(this,arguments)}}},{"../utils.js":37,"./getdisplaymedia":26,"./getusermedia":27}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,getSourceId){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;if("function"!=typeof getSourceId)return void console.error("shimGetDisplayMedia: getSourceId argument is not a function");window.navigator.mediaDevices.getDisplayMedia=function(constraints){return getSourceId(constraints).then((function(sourceId){var widthSpecified=constraints.video&&constraints.video.width,heightSpecified=constraints.video&&constraints.video.height,frameRateSpecified=constraints.video&&constraints.video.frameRate;return constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:sourceId,maxFrameRate:frameRateSpecified||3}},widthSpecified&&(constraints.video.mandatory.maxWidth=widthSpecified),heightSpecified&&(constraints.video.mandatory.maxHeight=heightSpecified),window.navigator.mediaDevices.getUserMedia(constraints)}))}}},{}],27:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator;if(!navigator.mediaDevices)return;var constraintsToChrome_=function(c){if("object"!==("undefined"==typeof c?"undefined":_typeof(c))||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach((function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"===_typeof(c[key])?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname_=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname_("min",key)]=r.ideal,cc.optional.push(oc),(oc={})[oldname_("max",key)]=r.ideal,cc.optional.push(oc)):(oc[oldname_("",key)]=r.ideal,cc.optional.push(oc))}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_("",key)]=r.exact):["min","max"].forEach((function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_(mix,key)]=r[mix])}))}})),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc},shimConstraints_=function(constraints,func){if(browserDetails.version>=61)return func(constraints);if((constraints=JSON.parse(JSON.stringify(constraints)))&&"object"===_typeof(constraints.audio)){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])};remap((constraints=JSON.parse(JSON.stringify(constraints))).audio,"autoGainControl","googAutoGainControl"),remap(constraints.audio,"noiseSuppression","googNoiseSuppression"),constraints.audio=constraintsToChrome_(constraints.audio)}if(constraints&&"object"===_typeof(constraints.video)){var face=constraints.video.facingMode;face=face&&("object"===("undefined"==typeof face?"undefined":_typeof(face))?face:{ideal:face});var getSupportedFacingModeLies=browserDetails.version<66;if(face&&("user"===face.exact||"environment"===face.exact||"user"===face.ideal||"environment"===face.ideal)&&(!navigator.mediaDevices.getSupportedConstraints||!navigator.mediaDevices.getSupportedConstraints().facingMode||getSupportedFacingModeLies)){delete constraints.video.facingMode;var matches=void 0;if("environment"===face.exact||"environment"===face.ideal?matches=["back","rear"]:"user"!==face.exact&&"user"!==face.ideal||(matches=["front"]),matches)return navigator.mediaDevices.enumerateDevices().then((function(devices){var dev=(devices=devices.filter((function(d){return"videoinput"===d.kind}))).find((function(d){return matches.some((function(match){return d.label.toLowerCase().includes(match)}))}));return!dev&&devices.length&&matches.includes("back")&&(dev=devices[devices.length-1]),dev&&(constraints.video.deviceId=face.exact?{exact:dev.deviceId}:{ideal:dev.deviceId}),constraints.video=constraintsToChrome_(constraints.video),logging("chrome: "+JSON.stringify(constraints)),func(constraints)}))}constraints.video=constraintsToChrome_(constraints.video)}return logging("chrome: "+JSON.stringify(constraints)),func(constraints)},shimError_=function(e){return browserDetails.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(navigator.getUserMedia=function(constraints,onSuccess,onError){shimConstraints_(constraints,(function(c){navigator.webkitGetUserMedia(c,onSuccess,(function(e){onError&&onError(shimError_(e))}))}))}.bind(navigator),navigator.mediaDevices.getUserMedia){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(cs){return shimConstraints_(cs,(function(c){return origGetUserMedia(c).then((function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach((function(track){track.stop()})),new DOMException("","NotFoundError");return stream}),(function(e){return Promise.reject(shimError_(e))}))}))}}};var logging=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js")).log},{"../utils.js":37}],28:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimRTCIceCandidate=function(window){if(!window.RTCIceCandidate||window.RTCIceCandidate&&"foundation"in window.RTCIceCandidate.prototype)return;var NativeRTCIceCandidate=window.RTCIceCandidate;window.RTCIceCandidate=function(args){if("object"===("undefined"==typeof args?"undefined":_typeof(args))&&args.candidate&&0===args.candidate.indexOf("a=")&&((args=JSON.parse(JSON.stringify(args))).candidate=args.candidate.substr(2)),args.candidate&&args.candidate.length){var nativeCandidate=new NativeRTCIceCandidate(args),parsedCandidate=_sdp2.default.parseCandidate(args.candidate),augmentedCandidate=Object.assign(nativeCandidate,parsedCandidate);return augmentedCandidate.toJSON=function(){return{candidate:augmentedCandidate.candidate,sdpMid:augmentedCandidate.sdpMid,sdpMLineIndex:augmentedCandidate.sdpMLineIndex,usernameFragment:augmentedCandidate.usernameFragment}},augmentedCandidate}return new NativeRTCIceCandidate(args)},window.RTCIceCandidate.prototype=NativeRTCIceCandidate.prototype,utils.wrapPeerConnectionEvent(window,"icecandidate",(function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new window.RTCIceCandidate(e.candidate),writable:"false"}),e}))},exports.shimMaxMessageSize=function(window,browserDetails){if(!window.RTCPeerConnection)return;"sctp"in window.RTCPeerConnection.prototype||Object.defineProperty(window.RTCPeerConnection.prototype,"sctp",{get:function(){return"undefined"==typeof this._sctp?null:this._sctp}});var sctpInDescription=function(description){if(!description||!description.sdp)return!1;var sections=_sdp2.default.splitSections(description.sdp);return sections.shift(),sections.some((function(mediaSection){var mLine=_sdp2.default.parseMLine(mediaSection);return mLine&&"application"===mLine.kind&&-1!==mLine.protocol.indexOf("SCTP")}))},getRemoteFirefoxVersion=function(description){var match=description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===match||match.length<2)return-1;var version=parseInt(match[1],10);return version!=version?-1:version},getCanSendMaxMessageSize=function(remoteIsFirefox){var canSendMaxMessageSize=65536;return"firefox"===browserDetails.browser&&(canSendMaxMessageSize=browserDetails.version<57?-1===remoteIsFirefox?16384:2147483637:browserDetails.version<60?57===browserDetails.version?65535:65536:2147483637),canSendMaxMessageSize},getMaxMessageSize=function(description,remoteIsFirefox){var maxMessageSize=65536;"firefox"===browserDetails.browser&&57===browserDetails.version&&(maxMessageSize=65535);var match=_sdp2.default.matchPrefix(description.sdp,"a=max-message-size:");return match.length>0?maxMessageSize=parseInt(match[0].substr(19),10):"firefox"===browserDetails.browser&&-1!==remoteIsFirefox&&(maxMessageSize=2147483637),maxMessageSize},origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===browserDetails.browser&&browserDetails.version>=76){var _getConfiguration=this.getConfiguration(),sdpSemantics=_getConfiguration.sdpSemantics;"plan-b"===sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return"undefined"==typeof this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(sctpInDescription(arguments[0])){var isFirefox=getRemoteFirefoxVersion(arguments[0]),canSendMMS=getCanSendMaxMessageSize(isFirefox),remoteMMS=getMaxMessageSize(arguments[0],isFirefox),maxMessageSize=void 0;maxMessageSize=0===canSendMMS&&0===remoteMMS?Number.POSITIVE_INFINITY:0===canSendMMS||0===remoteMMS?Math.max(canSendMMS,remoteMMS):Math.min(canSendMMS,remoteMMS);var sctp={};Object.defineProperty(sctp,"maxMessageSize",{get:function(){return maxMessageSize}}),this._sctp=sctp}return origSetRemoteDescription.apply(this,arguments)}},exports.shimSendThrowTypeError=function(window){if(!window.RTCPeerConnection||!("createDataChannel"in window.RTCPeerConnection.prototype))return;function wrapDcSend(dc,pc){var origDataChannelSend=dc.send;dc.send=function(){var data=arguments[0],length=data.length||data.size||data.byteLength;if("open"===dc.readyState&&pc.sctp&&length>pc.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+pc.sctp.maxMessageSize+" bytes)");return origDataChannelSend.apply(dc,arguments)}}var origCreateDataChannel=window.RTCPeerConnection.prototype.createDataChannel;window.RTCPeerConnection.prototype.createDataChannel=function(){var dataChannel=origCreateDataChannel.apply(this,arguments);return wrapDcSend(dataChannel,this),dataChannel},utils.wrapPeerConnectionEvent(window,"datachannel",(function(e){return wrapDcSend(e.channel,e.target),e}))},exports.shimConnectionState=function(window){if(!window.RTCPeerConnection||"connectionState"in window.RTCPeerConnection.prototype)return;var proto=window.RTCPeerConnection.prototype;Object.defineProperty(proto,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(proto,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(cb){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),cb&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=cb)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((function(method){var origMethod=proto[method];proto[method]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var pc=e.target;if(pc._lastConnectionState!==pc.connectionState){pc._lastConnectionState=pc.connectionState;var newEvent=new Event("connectionstatechange",e);pc.dispatchEvent(newEvent)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),origMethod.apply(this,arguments)}}))},exports.removeExtmapAllowMixed=function(window,browserDetails){if(!window.RTCPeerConnection)return;if("chrome"===browserDetails.browser&&browserDetails.version>=71)return;if("safari"===browserDetails.browser&&browserDetails.version>=605)return;var nativeSRD=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(desc){if(desc&&desc.sdp&&-1!==desc.sdp.indexOf("\na=extmap-allow-mixed")){var sdp=desc.sdp.split("\n").filter((function(line){return"a=extmap-allow-mixed"!==line.trim()})).join("\n");window.RTCSessionDescription&&desc instanceof window.RTCSessionDescription?arguments[0]=new window.RTCSessionDescription({type:desc.type,sdp:sdp}):desc.sdp=sdp}return nativeSRD.apply(this,arguments)}},exports.shimAddIceCandidateNullOrEmpty=function(window,browserDetails){if(!window.RTCPeerConnection||!window.RTCPeerConnection.prototype)return;var nativeAddIceCandidate=window.RTCPeerConnection.prototype.addIceCandidate;if(!nativeAddIceCandidate||0===nativeAddIceCandidate.length)return;window.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===browserDetails.browser&&browserDetails.version<78||"firefox"===browserDetails.browser&&browserDetails.version<68||"safari"===browserDetails.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():nativeAddIceCandidate.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}};var obj,_sdp=require("sdp"),_sdp2=(obj=_sdp)&&obj.__esModule?obj:{default:obj},utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("./utils"))},{"./utils":37,sdp:6}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimPeerConnection=function(window,browserDetails){if(window.RTCIceGatherer&&(window.RTCIceCandidate||(window.RTCIceCandidate=function(args){return args}),window.RTCSessionDescription||(window.RTCSessionDescription=function(args){return args}),browserDetails.version<15025)){var origMSTEnabled=Object.getOwnPropertyDescriptor(window.MediaStreamTrack.prototype,"enabled");Object.defineProperty(window.MediaStreamTrack.prototype,"enabled",{set:function(value){origMSTEnabled.set.call(this,value);var ev=new Event("enabled");ev.enabled=value,this.dispatchEvent(ev)}})}window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)&&Object.defineProperty(window.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new window.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}});window.RTCDtmfSender&&!window.RTCDTMFSender&&(window.RTCDTMFSender=window.RTCDtmfSender);var RTCPeerConnectionShim=(0,_rtcpeerconnectionShim2.default)(window,browserDetails.version);window.RTCPeerConnection=function(config){return config&&config.iceServers&&(config.iceServers=(0,_filtericeservers.filterIceServers)(config.iceServers,browserDetails.version),utils.log("ICE servers after filtering:",config.iceServers)),new RTCPeerConnectionShim(config)},window.RTCPeerConnection.prototype=RTCPeerConnectionShim.prototype},exports.shimReplaceTrack=function(window){window.RTCRtpSender&&!("replaceTrack"in window.RTCRtpSender.prototype)&&(window.RTCRtpSender.prototype.replaceTrack=window.RTCRtpSender.prototype.setTrack)};var obj,utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils")),_filtericeservers=require("./filtericeservers"),_rtcpeerconnectionShim=require("rtcpeerconnection-shim"),_rtcpeerconnectionShim2=(obj=_rtcpeerconnectionShim)&&obj.__esModule?obj:{default:obj}},{"../utils":37,"./filtericeservers":30,"./getdisplaymedia":31,"./getusermedia":32,"rtcpeerconnection-shim":5}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.filterIceServers=function(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter((function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&utils.deprecated("RTCIceServer.url","RTCIceServer.urls");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter((function(url){if(0===url.indexOf("stun:"))return!1;var validTurn=url.startsWith("turn")&&!url.startsWith("turn:[")&&url.includes("transport=udp");return validTurn&&!hasTurn?(hasTurn=!0,!0):validTurn&&!hasTurn})),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}}))};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":37}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window){if(!("getDisplayMedia"in window.navigator))return;if(!window.navigator.mediaDevices)return;if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;window.navigator.mediaDevices.getDisplayMedia=window.navigator.getDisplayMedia.bind(window.navigator)}},{}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetUserMedia=function(window){var navigator=window&&window.navigator,origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(c){return origGetUserMedia(c).catch((function(e){return Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString:function(){return this.name}}}(e))}))}}},{}],33:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimOnTrack=function(window){"object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimPeerConnection=function(window,browserDetails){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection&&!window.mozRTCPeerConnection)return;!window.RTCPeerConnection&&window.mozRTCPeerConnection&&(window.RTCPeerConnection=window.mozRTCPeerConnection);browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var modernStatsTypes={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},nativeGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];return nativeGetStats.apply(this,[selector||null]).then((function(stats){if(browserDetails.version<53&&!onSucc)try{stats.forEach((function(stat){stat.type=modernStatsTypes[stat.type]||stat.type}))}catch(e){if("TypeError"!==e.name)throw e;stats.forEach((function(stat,i){stats.set(i,Object.assign({},stat,{type:modernStatsTypes[stat.type]||stat.type}))}))}return stats})).then(onSucc,onErr)}},exports.shimSenderGetStats=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpSender.prototype)return;var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender});window.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}},exports.shimReceiverGetStats=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpReceiver.prototype)return;var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this2=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this2})),receivers});utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}},exports.shimRemoveStream=function(window){if(!window.RTCPeerConnection||"removeStream"in window.RTCPeerConnection.prototype)return;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;utils.deprecated("removeStream","removeTrack"),this.getSenders().forEach((function(sender){sender.track&&stream.getTracks().includes(sender.track)&&_this3.removeTrack(sender)}))}},exports.shimRTCDataChannel=function(window){window.DataChannel&&!window.RTCDataChannel&&(window.RTCDataChannel=window.DataChannel)},exports.shimAddTransceiver=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origAddTransceiver=window.RTCPeerConnection.prototype.addTransceiver;origAddTransceiver&&(window.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var initParameters=arguments[1],shouldPerformCheck=initParameters&&"sendEncodings"in initParameters;shouldPerformCheck&&initParameters.sendEncodings.forEach((function(encodingParam){if("rid"in encodingParam){if(!/^[a-z0-9]{0,16}$/i.test(encodingParam.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in encodingParam&&!(parseFloat(encodingParam.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in encodingParam&&!(parseFloat(encodingParam.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));var transceiver=origAddTransceiver.apply(this,arguments);if(shouldPerformCheck){var sender=transceiver.sender,params=sender.getParameters();(!("encodings"in params)||1===params.encodings.length&&0===Object.keys(params.encodings[0]).length)&&(params.encodings=initParameters.sendEncodings,sender.sendEncodings=initParameters.sendEncodings,this.setParametersPromises.push(sender.setParameters(params).then((function(){delete sender.sendEncodings})).catch((function(){delete sender.sendEncodings}))))}return transceiver})},exports.shimGetParameters=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCRtpSender)return;var origGetParameters=window.RTCRtpSender.prototype.getParameters;origGetParameters&&(window.RTCRtpSender.prototype.getParameters=function(){var params=origGetParameters.apply(this,arguments);return"encodings"in params||(params.encodings=[].concat(this.sendEncodings||[{}])),params})},exports.shimCreateOffer=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(){var _this4=this,_arguments2=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateOffer.apply(_this4,_arguments2)})).finally((function(){_this4.setParametersPromises=[]})):origCreateOffer.apply(this,arguments)}},exports.shimCreateAnswer=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateAnswer=window.RTCPeerConnection.prototype.createAnswer;window.RTCPeerConnection.prototype.createAnswer=function(){var _this5=this,_arguments3=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateAnswer.apply(_this5,_arguments3)})).finally((function(){_this5.setParametersPromises=[]})):origCreateAnswer.apply(this,arguments)}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":37,"./getdisplaymedia":34,"./getusermedia":35}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,preferredMediaSource){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;window.navigator.mediaDevices.getDisplayMedia=function(constraints){if(!constraints||!constraints.video){var err=new DOMException("getDisplayMedia without video constraints is undefined");return err.name="NotFoundError",err.code=8,Promise.reject(err)}return!0===constraints.video?constraints.video={mediaSource:preferredMediaSource}:constraints.video.mediaSource=preferredMediaSource,window.navigator.mediaDevices.getUserMedia(constraints)}}},{}],35:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator,MediaStreamTrack=window&&window.MediaStreamTrack;if(navigator.getUserMedia=function(constraints,onSuccess,onError){utils.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),navigator.mediaDevices.getUserMedia(constraints).then(onSuccess,onError)},!(browserDetails.version>55&&"autoGainControl"in navigator.mediaDevices.getSupportedConstraints())){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])},nativeGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);if(navigator.mediaDevices.getUserMedia=function(c){return"object"===("undefined"==typeof c?"undefined":_typeof(c))&&"object"===_typeof(c.audio)&&(c=JSON.parse(JSON.stringify(c)),remap(c.audio,"autoGainControl","mozAutoGainControl"),remap(c.audio,"noiseSuppression","mozNoiseSuppression")),nativeGetUserMedia(c)},MediaStreamTrack&&MediaStreamTrack.prototype.getSettings){var nativeGetSettings=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){var obj=nativeGetSettings.apply(this,arguments);return remap(obj,"mozAutoGainControl","autoGainControl"),remap(obj,"mozNoiseSuppression","noiseSuppression"),obj}}if(MediaStreamTrack&&MediaStreamTrack.prototype.applyConstraints){var nativeApplyConstraints=MediaStreamTrack.prototype.applyConstraints;MediaStreamTrack.prototype.applyConstraints=function(c){return"audio"===this.kind&&"object"===("undefined"==typeof c?"undefined":_typeof(c))&&(c=JSON.parse(JSON.stringify(c)),remap(c,"autoGainControl","mozAutoGainControl"),remap(c,"noiseSuppression","mozNoiseSuppression")),nativeApplyConstraints.apply(this,[c])}}}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":37}],36:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimLocalStreamsAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getLocalStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams});if(!("addStream"in window.RTCPeerConnection.prototype)){var _addTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addStream=function(stream){var _this=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(stream)||this._localStreams.push(stream),stream.getAudioTracks().forEach((function(track){return _addTrack.call(_this,track,stream)})),stream.getVideoTracks().forEach((function(track){return _addTrack.call(_this,track,stream)}))},window.RTCPeerConnection.prototype.addTrack=function(track){for(var _this2=this,_len=arguments.length,streams=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)streams[_key-1]=arguments[_key];return streams&&streams.forEach((function(stream){_this2._localStreams?_this2._localStreams.includes(stream)||_this2._localStreams.push(stream):_this2._localStreams=[stream]})),_addTrack.apply(this,arguments)}}"removeStream"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._localStreams||(this._localStreams=[]);var index=this._localStreams.indexOf(stream);if(-1!==index){this._localStreams.splice(index,1);var tracks=stream.getTracks();this.getSenders().forEach((function(sender){tracks.includes(sender.track)&&_this3.removeTrack(sender)}))}})},exports.shimRemoteStreamsAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getRemoteStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]});if(!("onaddstream"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(f){var _this4=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(_this4._remoteStreams||(_this4._remoteStreams=[]),!_this4._remoteStreams.includes(stream)){_this4._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,_this4.dispatchEvent(event)}}))})}});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var pc=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(pc._remoteStreams||(pc._remoteStreams=[]),!(pc._remoteStreams.indexOf(stream)>=0)){pc._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,pc.dispatchEvent(event)}}))}),origSetRemoteDescription.apply(pc,arguments)}}},exports.shimCallbacksAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var prototype=window.RTCPeerConnection.prototype,origCreateOffer=prototype.createOffer,origCreateAnswer=prototype.createAnswer,setLocalDescription=prototype.setLocalDescription,setRemoteDescription=prototype.setRemoteDescription,addIceCandidate=prototype.addIceCandidate;prototype.createOffer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateOffer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.createAnswer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateAnswer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};var withCallback=function(description,successCallback,failureCallback){var promise=setLocalDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};prototype.setLocalDescription=withCallback,withCallback=function(description,successCallback,failureCallback){var promise=setRemoteDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.setRemoteDescription=withCallback,withCallback=function(candidate,successCallback,failureCallback){var promise=addIceCandidate.apply(this,[candidate]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.addIceCandidate=withCallback},exports.shimGetUserMedia=function(window){var navigator=window&&window.navigator;if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var mediaDevices=navigator.mediaDevices,_getUserMedia=mediaDevices.getUserMedia.bind(mediaDevices);navigator.mediaDevices.getUserMedia=function(constraints){return _getUserMedia(shimConstraints(constraints))}}!navigator.getUserMedia&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(navigator.getUserMedia=function(constraints,cb,errcb){navigator.mediaDevices.getUserMedia(constraints).then(cb,errcb)}.bind(navigator))},exports.shimConstraints=shimConstraints,exports.shimRTCIceServerUrls=function(window){if(!window.RTCPeerConnection)return;var OrigPeerConnection=window.RTCPeerConnection;window.RTCPeerConnection=function(pcConfig,pcConstraints){if(pcConfig&&pcConfig.iceServers){for(var newIceServers=[],i=0;i<pcConfig.iceServers.length;i++){var server=pcConfig.iceServers[i];!server.hasOwnProperty("urls")&&server.hasOwnProperty("url")?(utils.deprecated("RTCIceServer.url","RTCIceServer.urls"),(server=JSON.parse(JSON.stringify(server))).urls=server.url,delete server.url,newIceServers.push(server)):newIceServers.push(pcConfig.iceServers[i])}pcConfig.iceServers=newIceServers}return new OrigPeerConnection(pcConfig,pcConstraints)},window.RTCPeerConnection.prototype=OrigPeerConnection.prototype,"generateCertificate"in OrigPeerConnection&&Object.defineProperty(window.RTCPeerConnection,"generateCertificate",{get:function(){return OrigPeerConnection.generateCertificate}})},exports.shimTrackEventTransceiver=function(window){"object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimCreateOfferLegacy=function(window){var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(offerOptions){if(offerOptions){"undefined"!=typeof offerOptions.offerToReceiveAudio&&(offerOptions.offerToReceiveAudio=!!offerOptions.offerToReceiveAudio);var audioTransceiver=this.getTransceivers().find((function(transceiver){return"audio"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveAudio&&audioTransceiver?"sendrecv"===audioTransceiver.direction?audioTransceiver.setDirection?audioTransceiver.setDirection("sendonly"):audioTransceiver.direction="sendonly":"recvonly"===audioTransceiver.direction&&(audioTransceiver.setDirection?audioTransceiver.setDirection("inactive"):audioTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveAudio||audioTransceiver||this.addTransceiver("audio"),"undefined"!=typeof offerOptions.offerToReceiveVideo&&(offerOptions.offerToReceiveVideo=!!offerOptions.offerToReceiveVideo);var videoTransceiver=this.getTransceivers().find((function(transceiver){return"video"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveVideo&&videoTransceiver?"sendrecv"===videoTransceiver.direction?videoTransceiver.setDirection?videoTransceiver.setDirection("sendonly"):videoTransceiver.direction="sendonly":"recvonly"===videoTransceiver.direction&&(videoTransceiver.setDirection?videoTransceiver.setDirection("inactive"):videoTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveVideo||videoTransceiver||this.addTransceiver("video")}return origCreateOffer.apply(this,arguments)}},exports.shimAudioContext=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||window.AudioContext)return;window.AudioContext=window.webkitAudioContext};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"));function shimConstraints(constraints){return constraints&&void 0!==constraints.video?Object.assign({},constraints,{video:utils.compactObject(constraints.video)}):constraints}},{"../utils":37}],37:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.extractVersion=extractVersion,exports.wrapPeerConnectionEvent=function(window,eventNameToWrap,wrapper){if(!window.RTCPeerConnection)return;var proto=window.RTCPeerConnection.prototype,nativeAddEventListener=proto.addEventListener;proto.addEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap)return nativeAddEventListener.apply(this,arguments);var wrappedCallback=function(e){var modifiedEvent=wrapper(e);modifiedEvent&&(cb.handleEvent?cb.handleEvent(modifiedEvent):cb(modifiedEvent))};return this._eventMap=this._eventMap||{},this._eventMap[eventNameToWrap]||(this._eventMap[eventNameToWrap]=new Map),this._eventMap[eventNameToWrap].set(cb,wrappedCallback),nativeAddEventListener.apply(this,[nativeEventName,wrappedCallback])};var nativeRemoveEventListener=proto.removeEventListener;proto.removeEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap||!this._eventMap||!this._eventMap[eventNameToWrap])return nativeRemoveEventListener.apply(this,arguments);if(!this._eventMap[eventNameToWrap].has(cb))return nativeRemoveEventListener.apply(this,arguments);var unwrappedCb=this._eventMap[eventNameToWrap].get(cb);return this._eventMap[eventNameToWrap].delete(cb),0===this._eventMap[eventNameToWrap].size&&delete this._eventMap[eventNameToWrap],0===Object.keys(this._eventMap).length&&delete this._eventMap,nativeRemoveEventListener.apply(this,[nativeEventName,unwrappedCb])},Object.defineProperty(proto,"on"+eventNameToWrap,{get:function(){return this["_on"+eventNameToWrap]},set:function(cb){this["_on"+eventNameToWrap]&&(this.removeEventListener(eventNameToWrap,this["_on"+eventNameToWrap]),delete this["_on"+eventNameToWrap]),cb&&this.addEventListener(eventNameToWrap,this["_on"+eventNameToWrap]=cb)},enumerable:!0,configurable:!0})},exports.disableLog=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+("undefined"==typeof bool?"undefined":_typeof(bool))+". Please use a boolean.");return logDisabled_=bool,bool?"adapter.js logging disabled":"adapter.js logging enabled"},exports.disableWarnings=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+("undefined"==typeof bool?"undefined":_typeof(bool))+". Please use a boolean.");return deprecationWarnings_=!bool,"adapter.js deprecation warnings "+(bool?"disabled":"enabled")},exports.log=function(){if("object"===("undefined"==typeof window?"undefined":_typeof(window))){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},exports.deprecated=function(oldMethod,newMethod){if(!deprecationWarnings_)return;console.warn(oldMethod+" is deprecated, please use "+newMethod+" instead.")},exports.detectBrowser=function(window){var result={browser:null,version:null};if("undefined"==typeof window||!window.navigator)return result.browser="Not a browser.",result;var navigator=window.navigator;if(navigator.mozGetUserMedia)result.browser="firefox",result.version=extractVersion(navigator.userAgent,/Firefox\/(\d+)\./,1);else if(navigator.webkitGetUserMedia||!1===window.isSecureContext&&window.webkitRTCPeerConnection&&!window.RTCIceGatherer)result.browser="chrome",result.version=extractVersion(navigator.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/))result.browser="edge",result.version=extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!window.RTCPeerConnection||!navigator.userAgent.match(/AppleWebKit\/(\d+)\./))return result.browser="Not a supported browser.",result;result.browser="safari",result.version=extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1),result.supportsUnifiedPlan=window.RTCRtpTransceiver&&"currentDirection"in window.RTCRtpTransceiver.prototype}return result},exports.compactObject=function compactObject(data){if(!isObject(data))return data;return Object.keys(data).reduce((function(accumulator,key){var isObj=isObject(data[key]),value=isObj?compactObject(data[key]):data[key],isEmptyObject=isObj&&!Object.keys(value).length;return void 0===value||isEmptyObject?accumulator:Object.assign(accumulator,function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},key,value))}),{})},exports.walkStats=walkStats,exports.filterStats=function(result,track,outbound){var streamStatsType=outbound?"outbound-rtp":"inbound-rtp",filteredResult=new Map;if(null===track)return filteredResult;var trackStats=[];return result.forEach((function(value){"track"===value.type&&value.trackIdentifier===track.id&&trackStats.push(value)})),trackStats.forEach((function(trackStat){result.forEach((function(stats){stats.type===streamStatsType&&stats.trackId===trackStat.id&&walkStats(result,stats,filteredResult)}))})),filteredResult};var logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}function isObject(val){return"[object Object]"===Object.prototype.toString.call(val)}function walkStats(stats,base,resultSet){base&&!resultSet.has(base.id)&&(resultSet.set(base.id,base),Object.keys(base).forEach((function(name){name.endsWith("Id")?walkStats(stats,stats.get(base[name]),resultSet):name.endsWith("Ids")&&base[name].forEach((function(id){walkStats(stats,stats.get(id),resultSet)}))})))}},{}],38:[function(require,module,exports){"use strict";function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}function parseArch(arch){switch(arch){case"x86_64":case"x64":return["x86","64"];case"x86_32":case"x86":return["x86",""];case"armv6l":case"armv7l":case"armv8l":return[arch,""];case"aarch64":return["arm","64"];default:return["",""]}}function padVersion(ver){var minSegs=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3,parts=ver.split("."),len=parts.length;if(len<minSegs){for(var i=0,lenToPad=minSegs-len;i<lenToPad;i+=1)parts.push("0");return parts.join(".")}return ver}var NavigatorUAData=function(){return e=function NavigatorUAData(navigator){!function(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,NavigatorUAData),this._ch=function(navigator){var mobile,uaFullVersion,m,m2,userAgent=navigator.userAgent,platform="",platformVersion="",architecture="",bitness="",fullVersionList=[],platformInfo=userAgent,found=!1,versionInfo=userAgent.replace(/\(([^)]+)\)?/g,(function($0,$1){return found||(platformInfo=$1,found=!0),""})),items=versionInfo.match(/(\S+)\/(\S+)/g),webview=!1;if(mobile=-1!==userAgent.indexOf("Mobile"),null!==(m=/Windows NT (\d+(\.\d+)*)/.exec(platformInfo))){platform="Windows";var ver={6.1:"0.1",6.2:"0.2",6.3:"0.3","10.0":"10.0","11.0":"13.0"}[m[1]];ver&&(platformVersion=padVersion(ver,3)),null!==(m2=/\b(WOW64|Win64|x64)\b/.exec(platformInfo))&&(architecture="x86",bitness="64")}else null!==(m=/Android (\d+(\.\d+)*)/.exec(platformInfo))?(platform="Android",platformVersion=padVersion(m[1]),null!==(m2=/Linux (\w+)/.exec(navigator.platform))&&m2[1]&&(architecture=(m2=parseArch(m2[1]))[0],bitness=m2[1])):null!==(m=/(iPhone|iPod touch); CPU iPhone OS (\d+(_\d+)*)/.exec(platformInfo))||null!==(m=/(iPad); CPU OS (\d+(_\d+)*)/.exec(platformInfo))?(platform="iOS",platformVersion=padVersion(m[2].replace(/_/g,"."))):null!==(m=/Macintosh; (Intel|\w+) Mac OS X (\d+([_.]\d+)*)/.exec(platformInfo))?(platform="macOS",platformVersion=padVersion(m[2].replace(/_/g,"."))):null!==(m=/Linux/.exec(platformInfo))?(platform="Linux",platformVersion=""):null!==(m=/CrOS (\w+) (\d+(\.\d+)*)/.exec(platformInfo))&&(platform="Chrome OS",platformVersion=padVersion(m[2]),architecture=(m2=parseArch(m[1]))[0],bitness=m2[1]);if(platform||(platform="Unknown"),null!==(m=/Chrome\/(\d+(\.\d+)*)/.exec(versionInfo))&&"Google Inc."===navigator.vendor){if(fullVersionList.push({brand:"Chromium",version:padVersion(m[1],4)}),null!==(m2=/(Edge?)\/(\d+(\.\d+)*)/.exec(versionInfo))){var brand={Edge:"Microsoft Edge",Edg:"Microsoft Edge"}[m[1]];fullVersionList.push({brand:brand,version:padVersion(m2[2],4)})}else fullVersionList.push({brand:"Google Chrome",version:padVersion(m[1],4)});/\bwv\b/.exec(platformInfo)&&(webview=!0)}else if(null!==(m=/AppleWebKit\/(\d+(\.\d+)*)/.exec(versionInfo))&&"Apple Computer, Inc."===navigator.vendor){if(fullVersionList.push({brand:"WebKit",version:padVersion(m[1])}),"iOS"===platform&&null!=(m2=/(CriOS|EdgiOS|FxiOS|Version)\/(\d+(\.\d+)*)/.exec(versionInfo))){var _brand={CriOS:"Google Chrome",EdgiOS:"Microsoft Edge",FxiOS:"Mozilla Firefox",Version:"Apple Safari"}[m2[1]];fullVersionList.push({brand:_brand,version:padVersion(m2[2])}),-1===items.findIndex((function(s){return s.startsWith("Safari/")}))&&(webview=!0)}}else null!==(m=/Firefox\/(\d+(\.\d+)*)/.exec(versionInfo))?fullVersionList.push({brand:"Firefox",version:padVersion(m[1])}):fullVersionList.push({brand:" Not;A Brand",version:"99.0.0.0"});return uaFullVersion=fullVersionList.length>0?fullVersionList[fullVersionList.length-1]:"",{mobile:mobile,platform:platform,brands:fullVersionList.map((function(b){var pos=b.version.indexOf("."),version=-1===pos?b.version:b.version.slice(0,pos);return{brand:b.brand,version:version}})),platformVersion:platformVersion,architecture:architecture,bitness:bitness,model:"",uaFullVersion:uaFullVersion,fullVersionList:fullVersionList,webview:webview}}(navigator),Object.defineProperties(this,{_ch:{enumerable:!1}})},(r=[{key:"mobile",get:function(){return this._ch.mobile}},{key:"platform",get:function(){return this._ch.platform}},{key:"brands",get:function(){return this._ch.brands}},{key:"getHighEntropyValues",value:function(hints){var _this=this;return new Promise((function(resolve,reject){if(!Array.isArray(hints))throw new TypeError("argument hints is not an array");var hintSet=new Set(hints),data=_this._ch,obj={mobile:data.mobile,platform:data.platform,brands:data.brands};hintSet.has("architecture")&&(obj.architecture=data.architecture),hintSet.has("bitness")&&(obj.bitness=data.bitness),hintSet.has("model")&&(obj.model=data.model),hintSet.has("platformVersion")&&(obj.platformVersion=data.platformVersion),hintSet.has("uaFullVersion")&&(obj.uaFullVersion=data.uaFullVersion),hintSet.has("fullVersionList")&&(obj.fullVersionList=data.fullVersionList),resolve(obj)}))}},{key:"toJSON",value:function(){var data=this._ch;return{mobile:data.mobile,brands:data.brands}}}])&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,r,t}();function _getClientInfo(){return(_getClientInfo=_asyncToGenerator(_regenerator().m((function _callee(navigator,keys){var info,customUAData;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(info={},"https:"!==location.protocol){_context.n=4;break}if(keys||(keys=["brands","mobile","platform","platformVersion","architecture","bitness","model","fullVersionList"]),navigator.userAgentData){_context.n=2;break}return customUAData=new NavigatorUAData(navigator),_context.n=1,customUAData.getHighEntropyValues(keys);case 1:info=_context.v,_context.n=4;break;case 2:return _context.n=3,navigator.userAgentData.getHighEntropyValues(keys);case 3:info=_context.v;case 4:return _context.a(2,info)}}),_callee)})))).apply(this,arguments)}Object.defineProperty(NavigatorUAData.prototype,Symbol.toStringTag,{enumerable:!1,configurable:!0,writable:!1,value:"NavigatorUAData"}),module.exports={getClientInfo:function(_x,_x2){return _getClientInfo.apply(this,arguments)}}},{}],39:[function(require,module,exports){"use strict";var SESSION_STATUS=Object.freeze({CONNECTED:"CONNECTED",ESTABLISHED:"ESTABLISHED",DISCONNECTED:"DISCONNECTED",WARN:"WARN",FAILED:"FAILED",DEBUG:"DEBUG",APP_DATA:"APP_DATA",SEND_DATA_STATUS:"SEND_DATA_STATUS",PENDING:"PENDING",REGISTERED:"REGISTERED",UNREGISTERED:"UNREGISTERED",INCOMING_CALL:"INCOMING_CALL"}),STREAM_STATUS=Object.freeze({NEW:"NEW",PENDING:"PENDING",PUBLISHING:"PUBLISHING",PLAYING:"PLAYING",PAUSED:"PAUSED",UNPUBLISHED:"UNPUBLISHED",STOPPED:"STOPPED",FAILED:"FAILED",PLAYBACK_PROBLEM:"PLAYBACK_PROBLEM",RESIZE:"RESIZE",SNAPSHOT_COMPLETE:"SNAPSHOT_COMPLETE",NOT_ENOUGH_BANDWIDTH:"NOT_ENOUGH_BANDWIDTH"}),CALL_STATUS=Object.freeze({NEW:"NEW",RING:"RING",RING_MEDIA:"RING_MEDIA",HOLD:"HOLD",ESTABLISHED:"ESTABLISHED",FINISH:"FINISH",BUSY:"BUSY",SESSION_PROGRESS:"SESSION_PROGRESS",FAILED:"FAILED",PENDING:"PENDING",TRYING:"TRYING"}),STREAM_STATUS_INFO=Object.freeze({FAILED_BY_ICE_ERROR:"Failed by ICE error",FAILED_BY_ICE_TIMEOUT:"Failed by ICE timeout",FAILED_BY_KEEP_ALIVE:"Failed by ICE keep alive",FAILED_BY_DTLS_FINGERPRINT_ERROR:"Failed by DTLS fingerprint error",FAILED_BY_DTLS_ERROR:"Failed by DTLS error",FAILED_BY_HLS_WRITER_ERROR:"Failed by HLS writer error",FAILED_BY_RTMP_WRITER_ERROR:"Failed by RTMP writer error",FAILED_BY_RTP_ACTIVITY:"Failed by RTP activity",STOPPED_BY_SESSION_DISCONNECT:"Stopped by session disconnect",STOPPED_BY_REST_TERMINATE:"Stopped by rest /terminate",STOPPED_BY_PUBLISHER_STOP:"Stopped by publisher stop",STOPPED_BY_USER:"Stopped by user",FAILED_BY_ERROR:"Failed by error",FAILED_TO_ADD_STREAM_TO_PROXY:"Failed to add stream to proxy",DISTRIBUTOR_STOPPED:"Distributor stopped",PUBLISH_STREAM_IS_NOT_READY:"Publish stream is not ready",STREAM_NOT_FOUND:"Stream not found",STREAM_NAME_ALREADY_IN_USE:"Stream name is already in use",MEDIASESSION_ID_NULL:"MediaSessionId is null",MEDIASESSION_ID_ALREADY_IN_USE:"MediaSessionId is already in use",SESSION_NOT_READY:"Session not ready",SESSION_DOES_NOT_EXIST:"Session does not exist",RTSP_HAS_WRONG_FORMAT:"Rtsp has wrong format",FILE_HAS_WRONG_FORMAT:"File has wrong format",FAILED_TO_CONNECT_TO_RTSP_STREAM:"Failed to connect to rtsp stream",RTSP_STREAM_NOT_FOUND:"Rtsp stream not found",RTSPAGENT_SHUTDOWN:"RtspAgent shutdown",STREAM_FAILED:"Stream failed",NO_COMMON_CODECS:"No common codecs",BAD_URI:"Bad URI",GOT_EXCEPTION_WHILE_STREAMING_FILE:"Got exception while streaming file",REQUESTED_STREAM_SHUTDOWN:"Requested stream shutdown",FAILED_TO_READ_FILE:"Failed to read file",FILE_NOT_FOUND:"File not found",FAILED_TO_CONNECT_TO_ORIGIN_STREAM:"Failed to connect to origin stream",CDN_STREAM_NOT_FOUND:"CDN stream not found",FAILED_TO_GET_AGENT_STORAGE:"Failed to get agent storage",AGENT_SERVICING_ORIGIN_STREAM_IS_SHUTTING_DOWN:"Agent servicing origin stream is shutting down",TERMINATED_BY_KEEP_ALIVE:"Terminated by keep-alive",TRANSCODING_REQUIRED_BUT_DISABLED:"Transcoding required, but disabled",RESTRICTED_ACCESS:"Restricted access",NO_AVAILABLE_TRANSCODERS:"No available transcoders"}),CALL_STATUS_INFO=Object.freeze({NORMAL_CALL_CLEARING:"Normal call clearing",FAILED_BY_SESSION_CREATION:"Failed by session creation",FAILED_BY_ICE_ERROR:"Failed by ICE error",FAILED_BY_RTP_ACTIVITY:"Failed by RTP activity",FAILED_BY_RTMP_WRITER_ERROR:"Failed by RTMP writer error",FAILED_BY_DTLS_FINGERPRINT_ERROR:"Failed by DTLS fingerprint error",NO_COMMON_CODECS:"No common codecs",FAILED_BY_DTLS_ERROR:"Failed by DTLS error",FAILED_BY_ERROR:"Failed by error",FAILED_BY_REQUEST_TIMEOUT:"Failed by request timeout",TRANSCODING_REQUIRED_BUT_DISABLED:"Transcoding required, but disabled"}),ERROR_INFO=Object.freeze({NONE_OF_MEDIAPROVIDERS_AVAILABLE:"None of MediaProviders available",NONE_OF_PREFERRED_MEDIAPROVIDERS_AVAILABLE:"None of preferred MediaProviders available",FLASHPHONER_API_NOT_INITIALIZED:"Flashphoner API is not initialized",OPTIONS_URLSERVER_MUST_BE_PROVIDED:"options.urlServer must be provided",INVALID_SESSION_STATE:"Invalid session state",OPTIONS_MUST_BE_PROVIDED:"options must be provided",INVALID_CALL_STATE:"Invalid call state",EVENT_CANT_BE_NULL:"Event can't be null",CALLBACK_NEEDS_TO_BE_A_VALID_FUNCTION:"Callback needs to be a valid function",OPTIONS_NAME_MUST_BE_PROVIDED:"options.name must be provided",CAN_NOT_SWITCH_CAM:"Number of cams is less than 2 or camera is already used by other application",CAN_NOT_SWITCH_MIC:"Number of mics is less than 2 or microphone is already used by other application",CAN_NOT_SET_RESOLUTION:"Cannot switch a published stream resolution",CAN_NOT_GET_STATS:"Cannot get PeerConnection stats",LOCAL_ERROR:"Local error"}),MEDIA_DEVICE_KIND=Object.freeze({OUTPUT:"output",INPUT:"input",ALL:"all"}),TRANSPORT_TYPE=Object.freeze({UDP:"UDP",TCP:"TCP"}),CONNECTION_QUALITY=Object.freeze({PERFECT:"PERFECT",GOOD:"GOOD",BAD:"BAD",UNKNOWN:"UNKNOWN",UPDATE:"UPDATE"}),STREAM_EVENT_TYPE=Object.freeze({AUDIO_MUTED:"audioMuted",AUDIO_UNMUTED:"audioUnmuted",VIDEO_MUTED:"videoMuted",VIDEO_UNMUTED:"videoUnmuted",DATA:"data",SNAPSHOT_COMPLETED:"snapshotCompleted",SNAPSHOT_FAILED:"snapshotFailed",RESIZE:"resize",NOT_ENOUGH_BANDWIDTH:"notEnoughBandwidth"}),CONTENT_HINT_TYPE=Object.freeze({MOTION:"motion",DETAIL:"detail",TEXT:"text"});module.exports={SESSION_STATUS:SESSION_STATUS,STREAM_STATUS:STREAM_STATUS,CALL_STATUS:CALL_STATUS,STREAM_STATUS_INFO:STREAM_STATUS_INFO,CALL_STATUS_INFO:CALL_STATUS_INFO,ERROR_INFO:ERROR_INFO,MEDIA_DEVICE_KIND:MEDIA_DEVICE_KIND,TRANSPORT_TYPE:TRANSPORT_TYPE,CONNECTION_QUALITY:CONNECTION_QUALITY,STREAM_EVENT:"STREAM_EVENT",STREAM_EVENT_TYPE:STREAM_EVENT_TYPE,CONTENT_HINT_TYPE:CONTENT_HINT_TYPE}},{}],40:[function(require,module,exports){"use strict";function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var coreLogger,clientUAData,disableConnectionQualityCalculation,uuid_v1=require("uuid").v1,constants=require("./constants"),util=require("./util"),LoggerObject=require("./util").logger,clientInfo=require("./client-info"),StatsCollector=require("./stats-collector"),_Promise=require("promise-polyfill"),KalmanFilter=require("kalmanjs"),browserDetails=require("webrtc-adapter").default.browserDetails,loggerConf={push:!1,severity:"INFO"},isUsingTemasysPlugin=!1,SESSION_STATUS=constants.SESSION_STATUS,STREAM_EVENT=constants.STREAM_EVENT,STREAM_EVENT_TYPE=constants.STREAM_EVENT_TYPE,STREAM_STATUS=constants.STREAM_STATUS,CALL_STATUS=constants.CALL_STATUS,CONNECTION_QUALITY=constants.CONNECTION_QUALITY,ERROR_INFO=constants.ERROR_INFO,MediaProvider={},sessions={},initialized=!1,init=function(){var _ref=_asyncToGenerator(_regenerator().m((function _callee(options){var waitingTemasys,audioContext,webRtcProvider,enableGainNode,webRtcConf,mediaSourceMediaProvider,mseConf,websocketProvider,wsConf,_MediaProvider,p,newMediaProvider,i,pMP;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(initialized){_context.n=6;break}options||(options={}),coreLogger=createLogger(options.logger),waitingTemasys=!1;try{audioContext=new(window.AudioContext||window.webkitAudioContext)}catch(e){console.warn("Failed to create audio context")}if(disableConnectionQualityCalculation=options.disableConnectionQualityCalculation,(webRtcProvider=require("./webrtc-media-provider"))&&webRtcProvider.hasOwnProperty("available")&&webRtcProvider.available()?(MediaProvider.WebRTC=webRtcProvider,enableGainNode=!util.Browser.isSamsungBrowser()&&!util.Browser.isAndroidFirefox()&&options.createMicGainNode,webRtcConf={constraints:options.constraints||getDefaultMediaConstraints(),extensionId:options.screenSharingExtensionId,audioContext:audioContext,logger:coreLogger,createMicGainNode:enableGainNode},webRtcProvider.configure(webRtcConf)):(webRtcProvider=require("./temasys-media-provider"))&&webRtcProvider.hasOwnProperty("available")&&AdapterJS&&(waitingTemasys=!0,AdapterJS.webRTCReady((function(isUsingPlugin){if(isUsingTemasysPlugin=isUsingPlugin,isUsingPlugin||webRtcProvider.available()){MediaProvider.WebRTC=webRtcProvider;var webRtcConf={constraints:options.constraints||getDefaultMediaConstraints(),extensionId:options.screenSharingExtensionId,logger:coreLogger};webRtcProvider.configure(webRtcConf);var _MediaProvider={};for(var p in _MediaProvider.WebRTC=MediaProvider.WebRTC,MediaProvider)_MediaProvider[p]=MediaProvider[p];MediaProvider=_MediaProvider}options.mediaProvidersReadyCallback&&options.mediaProvidersReadyCallback(Object.keys(MediaProvider))}))),null,(mediaSourceMediaProvider=require("./media-source-media-provider"))&&mediaSourceMediaProvider.hasOwnProperty("available")&&mediaSourceMediaProvider.available()&&(MediaProvider.MSE=mediaSourceMediaProvider,mseConf={audioContext:audioContext,browserDetails:browserDetails.browser},mediaSourceMediaProvider.configure(mseConf)),(websocketProvider=require("./websocket-media-provider"))&&websocketProvider.hasOwnProperty("available")&&websocketProvider.available(audioContext)&&(MediaProvider.WSPlayer=websocketProvider,wsConf={receiverLocation:options.receiverLocation,decoderLocation:options.decoderLocation,audioContext:audioContext,logger:coreLogger},websocketProvider.configure(wsConf)),0!=getMediaProviders().length){_context.n=1;break}throw new Error("None of MediaProviders available");case 1:if(options.preferredMediaProvider)if(MediaProvider.hasOwnProperty(options.preferredMediaProvider)){if(getMediaProviders()[0]!=options.preferredMediaProvider){for(p in(_MediaProvider={})[options.preferredMediaProvider]=MediaProvider[options.preferredMediaProvider],MediaProvider)_MediaProvider[p]=MediaProvider[p];MediaProvider=_MediaProvider}}else corelogger.warn("core","Preferred media provider is not available.");case 2:if(!(options.preferredMediaProviders&&options.preferredMediaProviders.length>0)){_context.n=4;break}for(i in newMediaProvider={},options.preferredMediaProviders)options.preferredMediaProviders.hasOwnProperty(i)&&(pMP=options.preferredMediaProviders[i],MediaProvider.hasOwnProperty(pMP)&&(newMediaProvider[pMP]=MediaProvider[pMP]));if(!util.isEmptyObject(newMediaProvider)){_context.n=3;break}throw new Error("None of preferred MediaProviders available");case 3:MediaProvider=newMediaProvider;case 4:if(!waitingTemasys&&options.mediaProvidersReadyCallback&&options.mediaProvidersReadyCallback(Object.keys(MediaProvider)),coreLogger.info("core","Initialized"),initialized=!0,void 0!==options.collectClientInfo&&!options.collectClientInfo){_context.n=6;break}return _context.n=5,clientInfo.getClientInfo(window.navigator);case 5:clientUAData=_context.v,coreLogger.info("core","Client system data: "+JSON.stringify(clientUAData));case 6:return _context.a(2)}}),_callee)})));return function(_x){return _ref.apply(this,arguments)}}(),getMediaProviders=function(){return Object.keys(MediaProvider)},getDefaultMediaConstraints=function(){return"safari"==browserDetails.browser?{audio:!0,video:{width:{min:320,max:640},height:{min:180,max:360}}}:{audio:!0,video:{width:320,height:240}}};function getConstraintsProperty(constraints,property,defaultValue){if(!constraints||!property)return defaultValue;var res,properties=property.split(".");for(var prop in constraints)if(prop==properties[0])res=constraints[prop],properties.length>1&&(res=getConstraintsProperty(constraints[prop],properties[1],defaultValue));else if("object"===_typeof(constraints[prop]))for(var p in constraints[prop])p==property&&(res=constraints[prop][p]);return"boolean"==typeof res?res:res||defaultValue}var releaseLocalMedia=function(display,mediaProvider){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].releaseMedia(display)},getLoggerConf=function(loggerOptions){var conf=loggerOptions||loggerConf;return null!==loggerOptions&&(conf.enableLogs=!0),conf},createLogger=function(loggerOptions){var parentLogger=arguments.length>1&&void 0!==arguments[1]?arguments[1]:coreLogger,newLogger=parentLogger;if(void 0===newLogger||null!=loggerOptions){var loggerConf=getLoggerConf(loggerOptions);(newLogger=new LoggerObject).init(loggerConf.severity||"INFO",loggerConf.push||!1,loggerConf.customLogger,loggerConf.enableLogs)}return newLogger};module.exports={init:init,isUsingTemasys:function(){return isUsingTemasysPlugin},getMediaProviders:getMediaProviders,getMediaDevices:function(mediaProvider,labels,kind,deviceConstraints){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].listDevices(labels,kind,deviceConstraints)},getMediaAccess:function(constraints,display,mediaProvider,disableConstraintsNormalization){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].getMediaAccess(constraints,display,disableConstraintsNormalization)},releaseLocalMedia:releaseLocalMedia,getSessions:function(){return util.copyObjectToArray(sessions)},getSession:function(id){return sessions[id]},createSession:function(options){if(!initialized)throw new Error("Flashphoner API is not initialized");if(!options||!options.urlServer)throw new TypeError("options.urlServer must be provided");var connectionTimeout,cConfig,sipConfig,sessionLogger=createLogger(options.logger),logger=sessionLogger,id_=uuid_v1(),sessionStatus=SESSION_STATUS.PENDING,urlServer=options.urlServer,lbUrl=options.lbUrl,flashProto=options.flashProto||"rtmfp",flashPort=options.flashPort||1935,appKey=options.appKey||"defaultApp",mediaOptions=options.mediaOptions,keepAlive=options.keepAlive,timeout=options.timeout,sendClientInfo=void 0===options.sendClientInfo||options.sendClientInfo,wsPingSender=new function(interval){return this.interval=interval||0,this.intervalId=null,this.start=function(){this.interval>0&&(this.intervalId=setInterval((function(){send("ping",null)}),this.interval))},this.stop=function(){this.intervalId&&clearInterval(this.intervalId)},this}(options.pingInterval||0),wsPingReceiver=new function(receiveProbes,probesInterval){return this.maxPings=receiveProbes||0,this.interval=probesInterval||0,this.intervalId=null,this.pingsMissing=0,this.start=function(){if(this.maxPings>0&&this.interval>0){var receiver=this;this.intervalId=setInterval((function(){receiver.checkPingsReceived()}),this.interval)}},this.stop=function(){this.intervalId&&clearInterval(this.intervalId),this.pingsMissing=0},this.checkPingsReceived=function(){this.pingsMissing++,this.pingsMissing>=this.maxPings&&this.failure()},this.success=function(){this.pingsMissing=0},this.failure=function(){logger.info("core","Missing "+this.pingsMissing+" pings from server, connection seems to be down"),onSessionStatusChange(SESSION_STATUS.FAILED),wsConnection.close()},this}(options.receiveProbes||0,options.probesInterval||0);options.sipOptions&&(sipConfig={sipLogin:options.sipOptions.login,sipAuthenticationName:options.sipOptions.authenticationName,sipPassword:options.sipOptions.password,sipDomain:options.sipOptions.domain,sipOutboundProxy:options.sipOptions.outboundProxy,sipProxy:options.sipOptions.proxy,sipPort:options.sipOptions.port,sipRegisterRequired:options.sipOptions.registerRequired});var wsConnection,webRTCMetricsServerDescription,url,request,authToken=options.authToken,streams={},calls={},mediaConnections={},streamEventRefreshHandlers={},streamRefreshHandlers={},callRefreshHandlers={},session={},callbacks={};lbUrl?(url=lbUrl,(request=new XMLHttpRequest).open("GET",url,!0),request.timeout=5e3,request.ontimeout=function(){logger.warn("core","Timeout during geting url from balancer!"),createWS(urlServer)},request.error=function(){logger.warn("core","Error during geting url from balancer!"),createWS(urlServer)},request.onload=function(e){if(200==request.status&&4==request.readyState){var result=JSON.parse(request.responseText);urlServer=-1!==urlServer.indexOf("wss://")?"wss://"+result.server+":"+result.wss:"ws://"+result.server+":"+result.ws,flashPort=result.flash,logger.debug("core","Got url from load balancer "+result.server),createWS(urlServer)}},request.send()):createWS(urlServer);var remoteSdpCache={};function createWS(url){wsConnection=new WebSocket(url),null!=timeout&&timeout>0&&(connectionTimeout=setTimeout((function(){0==wsConnection.readyState&&(logger.warn("core","WS connection timeout"),wsConnection.close())}),timeout)),wsConnection.onerror=function(){onSessionStatusChange(SESSION_STATUS.FAILED)},wsConnection.onclose=function(){sessionStatus!==SESSION_STATUS.FAILED&&onSessionStatusChange(SESSION_STATUS.DISCONNECTED)},wsConnection.onopen=function(){onSessionStatusChange(SESSION_STATUS.CONNECTED),clearTimeout(connectionTimeout),cConfig={appKey:appKey,mediaProviders:Object.keys(MediaProvider),keepAlive:keepAlive,authToken:authToken,clientVersion:"2.0",clientOSVersion:window.navigator.appVersion,clientBrowserVersion:window.navigator.userAgent,msePacketizationVersion:2,custom:options.custom},sendClientInfo&&clientUAData&&(cConfig.clientInfo=clientUAData),sipConfig&&util.copyObjectPropsToAnotherObject(sipConfig,cConfig),send("connection",cConfig),logger.setConnection(wsConnection),wsPingSender.start(),wsPingReceiver.start()},wsConnection.onmessage=function(event){var data={};if(event.data instanceof Blob)data.message="binaryData";else var obj=(data=JSON.parse(event.data)).data[0];switch(data.message){case"ping":logger.debug("core","<<< ping"),send("pong",null),logger.debug("core",">>> pong");break;case"getUserData":authToken=obj.authToken,cConfig=obj,webRTCMetricsServerDescription=obj.webRTCMetricsServerDescription,onSessionStatusChange(SESSION_STATUS.ESTABLISHED,obj);break;case"setRemoteSDP":var mediaSessionId=data.data[0],sdp=data.data[1];streamRefreshHandlers[mediaSessionId]?streamRefreshHandlers[mediaSessionId](null,sdp):callRefreshHandlers[mediaSessionId]?callRefreshHandlers[mediaSessionId](null,sdp):(remoteSdpCache[mediaSessionId]=sdp,logger.info("core","Media not found, id "+mediaSessionId));break;case"notifyVideoFormat":case"notifyStreamStatusEvent":streamRefreshHandlers[obj.mediaSessionId]&&streamRefreshHandlers[obj.mediaSessionId](obj);break;case"notifyStreamEvent":streamEventRefreshHandlers[obj.mediaSessionId]&&streamEventRefreshHandlers[obj.mediaSessionId](obj);break;case"DataStatusEvent":restAppCommunicator.resolveData(obj);break;case"OnDataEvent":callbacks[SESSION_STATUS.APP_DATA]&&callbacks[SESSION_STATUS.APP_DATA](obj);break;case"fail":obj.apiMethod&&"StreamStatusEvent"==obj.apiMethod&&streamRefreshHandlers[obj.id]&&streamRefreshHandlers[obj.id](obj),callbacks[SESSION_STATUS.WARN]&&callbacks[SESSION_STATUS.WARN](obj);break;case"registered":onSessionStatusChange(SESSION_STATUS.REGISTERED);break;case"notifyAudioCodec":mediaSessionId=data.data[0];var codec=data.data[1];callRefreshHandlers[mediaSessionId]&&callRefreshHandlers[mediaSessionId](null,null,codec);break;case"notifyTransferEvent":callRefreshHandlers[obj.callId](null,null,null,obj);break;case"notifyTryingResponse":case"hold":case"ring":case"talk":case"finish":callRefreshHandlers[obj.callId]&&callRefreshHandlers[obj.callId](obj);break;case"notifyIncomingCall":callRefreshHandlers[obj.callId]&&logger.error("core","Call already exists, id "+obj.callId),callbacks[SESSION_STATUS.INCOMING_CALL]&&callbacks[SESSION_STATUS.INCOMING_CALL](createCall(obj));break;case"notifySessionDebugEvent":logger.info("core","Session debug status "+obj.status),callbacks[SESSION_STATUS.DEBUG]&&callbacks[SESSION_STATUS.DEBUG](obj);break;case"availableStream":var availableStream={};availableStream.mediaSessionId=obj.id,availableStream.available=obj.status,availableStream.reason=obj.info,streamRefreshHandlers[availableStream.mediaSessionId]&&streamRefreshHandlers[availableStream.mediaSessionId](availableStream);break;case"outboundVideoRate":case"inboundVideoRate":streamRefreshHandlers[obj.mediaSessionId]&&(obj.status=data.message,streamRefreshHandlers[obj.mediaSessionId](obj));break;case"webRTCMetricsDescriptionUpdate":if(obj.ids)obj.ids.forEach((function(id){streamRefreshHandlers[id]&&streamRefreshHandlers[id](obj)}));else{obj.compression&&(webRTCMetricsServerDescription.compression=obj.compression),obj.batchSize&&(webRTCMetricsServerDescription.batchSize=obj.batchSize),obj.sampling&&(webRTCMetricsServerDescription.sampling=obj.sampling),obj.types&&(webRTCMetricsServerDescription.types=obj.types),obj.collect&&(webRTCMetricsServerDescription.collect=obj.collect);for(var _i=0,_Object$entries=Object.entries(streamRefreshHandlers);_i<_Object$entries.length;_i++){var _Object$entries$_i=_slicedToArray(_Object$entries[_i],2);_Object$entries$_i[0];(0,_Object$entries$_i[1])(obj)}}break;default:logger.info("core","Unknown server message "+data.message)}logger.debug("core","Reset missing pings counter by "+data.message+" message"),wsPingReceiver.success()}}function send(message,data){wsConnection.readyState===WebSocket.OPEN&&wsConnection.send(JSON.stringify({message:message,data:[data]}))}function onSessionStatusChange(newStatus,obj){if((sessionStatus=newStatus)==SESSION_STATUS.DISCONNECTED||sessionStatus==SESSION_STATUS.FAILED){for(var prop in wsPingSender.stop(),wsPingReceiver.stop(),streamRefreshHandlers)streamRefreshHandlers.hasOwnProperty(prop)&&"function"==typeof streamRefreshHandlers[prop]&&streamRefreshHandlers[prop]({status:STREAM_STATUS.FAILED});delete sessions[id_]}callbacks[sessionStatus]&&callbacks[sessionStatus](session,obj)}var createCall=function(options){if(sessionStatus!==SESSION_STATUS.REGISTERED&&sessionStatus!==SESSION_STATUS.ESTABLISHED)throw new Error("Invalid session state "+sessionStatus);if(!options)throw new TypeError("options must be provided");var mediaConnection,info_,errorInfo_,audioOutputId,callLogger=createLogger(options.logger,sessionLogger),logger=callLogger,login="clickToCallApp"==appKey?"":cConfig.sipLogin,caller_=options.incoming?options.caller:login,callee_=options.callee,visibleName_=options.visibleName||login,id_=options.callId||uuid_v1(),mediaProvider=options.mediaProvider||getMediaProviders()[0],localDisplay=options.localVideoDisplay,remoteDisplay=options.remoteVideoDisplay;if(options.constraints)var constraints=options.constraints;if(options.disableConstraintsNormalization)var disableConstraintsNormalization=options.disableConstraintsNormalization;var audioProperty=getConstraintsProperty(constraints,"audio",void 0);"object"===_typeof(audioProperty)&&(audioOutputId=getConstraintsProperty(audioProperty,"outputId",0));var stripCodecs=options.stripCodecs||[],receiveAudio="undefined"==typeof options.receiveAudio||options.receiveAudio,receiveVideo="undefined"==typeof options.receiveVideo||options.receiveVideo,cacheLocalResources=options.cacheLocalResources,status_=CALL_STATUS.NEW,callbacks={},hasTransferredCall=!1,sdpHook=options.sdpHook,sipSDP=options.sipSDP,videoContentHint=(options.sipHeaders,options.videoContentHint),useControls=options.useControls,collectDeviceInfo=void 0===options.collectDeviceInfo||options.collectDeviceInfo,minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0),call={};callRefreshHandlers[id_]=function(callInfo,sdp,codec,transfer){if(transfer)return mediaConnections[id_]||(mediaConnections[id_]=mediaConnection),void("COMPLETED"==transfer.status&&delete mediaConnections[id_]);if(!mediaConnection&&0!=Object.keys(mediaConnections).length)for(var mc in mediaConnections)mediaConnection=mediaConnections[mc],hasTransferredCall=!0,delete mediaConnections[mc];if(codec)"Flash"==mediaProvider&&mediaConnection.changeAudioCodec(codec.name);else{if(sdp&&""!==sdp)return sdp=sdpHookHandler(sdp,sdpHook),sdp=util.setPublishingBitrate(sdp,mediaConnection,minBitrate,maxBitrate),void mediaConnection.setRemoteSdp(sdp,hasTransferredCall,id_).then((function(){}));var event=callInfo.status;status_=event,event!=CALL_STATUS.FAILED&&event!=CALL_STATUS.FINISH&&event!=CALL_STATUS.BUSY||(delete calls[id_],delete callRefreshHandlers[id_],0==Object.keys(calls).length&&mediaConnection&&mediaConnection.close(cacheLocalResources)),callbacks[event]&&callbacks[event](call)}};var hangup=function(){if(status_!=CALL_STATUS.NEW){if(status_==CALL_STATUS.PENDING)return cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider),callRefreshHandlers[id_]({status:CALL_STATUS.FAILED}),void(options.incoming&&send("hangup",{callId:id_}));send("hangup",{callId:id_}),mediaConnection&&mediaConnection.close(cacheLocalResources)}else callRefreshHandlers[id_]({status:CALL_STATUS.FAILED})};return call.call=function(){if(status_!==CALL_STATUS.NEW)throw new Error("Invalid call state");status_=CALL_STATUS.PENDING;MediaProvider[mediaProvider].getMediaAccess(constraints,localDisplay,disableConstraintsNormalization).then((function(){status_!=CALL_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,localDisplay:localDisplay,remoteDisplay:remoteDisplay,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,bidirectional:!0,login:login,constraints:constraints,connectionConfig:mediaOptions,audioOutputId:audioOutputId,videoContentHint:videoContentHint,useControls:useControls,logger:logger}).then((function(newConnection){return(mediaConnection=newConnection).createOffer({sendAudio:!0,sendVideo:!0,receiveAudio:receiveAudio,receiveVideo:receiveVideo,stripCodecs:stripCodecs})})).then((function(offer){var callData={callId:id_,incoming:!1,hasVideo:offer.hasVideo,hasAudio:offer.hasAudio,status:status_,mediaProvider:mediaProvider,sdp:offer.sdp,sipSDP:sipSDP,caller:login,callee:callee_,custom:options.custom,visibleName:visibleName_};collectDeviceInfo&&(callData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],localDisplay)),send("call",callData)})):cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider)})).catch((function(error){logger.error("core",error),status_=CALL_STATUS.FAILED,info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,callRefreshHandlers[id_]({status:CALL_STATUS.FAILED}),hangup()}))},call.answer=function(answerOptions){if(status_!==CALL_STATUS.NEW&&status_!==CALL_STATUS.RING)throw new Error("Invalid call state");var sdp;localDisplay=answerOptions.localVideoDisplay,remoteDisplay=answerOptions.remoteVideoDisplay,constraints=answerOptions.constraints||getDefaultMediaConstraints(),status_=CALL_STATUS.PENDING;var sdpHook=answerOptions.sdpHook,minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0);if(sipSDP=answerOptions.sipSDP,answerOptions.sipHeaders,!remoteSdpCache[id_])throw logger.error("core","No remote sdp available"),new Error("No remote sdp available");sdp=sdpHookHandler(remoteSdpCache[id_],sdpHook),sdp=util.setPublishingBitrate(sdp,null,minBitrate,maxBitrate),delete remoteSdpCache[id_],0==util.SDP.matchPrefix(sdp,"m=video").length&&(constraints.video=!1);var stripCodecs=answerOptions.stripCodecs||[];MediaProvider[mediaProvider].getMediaAccess(constraints,localDisplay,disableConstraintsNormalization).then((function(){status_!=CALL_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,localDisplay:localDisplay,remoteDisplay:remoteDisplay,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,bidirectional:!0,login:cConfig.sipLogin,constraints:constraints,connectionConfig:mediaOptions,audioOutputId:audioOutputId,useControls:useControls}).then((function(newConnection){return(mediaConnection=newConnection).setPublishingBitrate(minBitrate,maxBitrate),mediaConnection.setRemoteSdp(sdp)})).then((function(){return mediaConnection.createAnswer({receiveAudio:options.receiveAudio,receiveVideo:options.receiveVideo,stripCodecs:stripCodecs})})).then((function(sdp){if(status_!=CALL_STATUS.FINISH&&status_!=CALL_STATUS.FAILED){var callData={callId:id_,incoming:!0,hasVideo:!0,hasAudio:!0,status:status_,mediaProvider:mediaProvider,sdp:sdp,sipSDP:sipSDP,caller:cConfig.login,callee:callee_,custom:options.custom};collectDeviceInfo&&(callData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],localDisplay)),send("answer",callData)}else hangup()})):cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider)})).catch((function(error){logger.error("core",error),info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,status_=CALL_STATUS.FAILED,callRefreshHandlers[id_]({status:CALL_STATUS.FAILED})}))},call.hangup=hangup,call.id=function(){return id_},call.getInfo=function(){return info_},call.getErrorInfo=function(){return errorInfo_},call.status=function(){return status_},call.getStats=function(callbackFn,nativeStats){mediaConnection&&mediaConnection.getStats(callbackFn,nativeStats)},call.setAudioOutputId=function(id){if(audioOutputId=id,mediaConnection&&mediaConnection.setAudioOutputId)return mediaConnection.setAudioOutputId(id)},call.setVolume=function(volume){mediaConnection&&mediaConnection.setVolume(volume)},call.getVolume=function(){return mediaConnection?mediaConnection.getVolume():-1},call.muteAudio=function(){mediaConnection&&mediaConnection.muteAudio()},call.unmuteAudio=function(){mediaConnection&&mediaConnection.unmuteAudio()},call.isAudioMuted=function(){return!mediaConnection||mediaConnection.isAudioMuted()},call.muteVideo=function(){mediaConnection&&mediaConnection.muteVideo()},call.unmuteVideo=function(){mediaConnection&&mediaConnection.unmuteVideo()},call.isVideoMuted=function(){return!mediaConnection||mediaConnection.isVideoMuted()},call.caller=function(){return caller_},call.callee=function(){return callee_},call.visibleName=function(){return visibleName_},call.hold=function(){send("hold",{callId:id_})},call.holdForTransfer=function(){send("hold",{callId:id_,holdForTransfer:!0})},call.unhold=function(){send("unhold",{callId:id_})},call.sendDTMF=function(number,type){send("sendDtmf",{callId:id_,type:type||"RFC2833",dtmf:number})},call.transfer=function(target){send("transfer",{callId:id_,target:target})},call.on=function(event,callback){if(!event)throw new TypeError("Event can't be null");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,call},call.switchCam=function(deviceId){if(status_!==CALL_STATUS.ESTABLISHED&&!constraints.video&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchCam(deviceId)},call.switchMic=function(deviceId){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchMic(deviceId)},call.switchToScreen=function(source,woExtension){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchToScreen(source,woExtension)},call.switchToCam=function(){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");mediaConnection.switchToCam()},call.getLogger=function(){return callLogger},calls[id_]=call,call},restAppCommunicator=function(){var pending={},exports={sendData:function(data){return new _Promise((function(resolve,reject){var obj={operationId:uuid_v1(),payload:data};pending[obj.operationId]={FAILED:function(info){reject(info)},ACCEPTED:function(info){resolve(info)}},send("sendData",obj)}))},resolveData:function(data){if(pending[data.operationId]){var handler=pending[data.operationId];delete pending[data.operationId],delete data.operationId,handler[data.status](data)}}};return exports}(),sdpHookHandler=function(sdp,sdpHook){if(null!=sdpHook&&"function"==typeof sdpHook){var newSdp=sdpHook({sdpString:sdp});return null!=newSdp&&""!=newSdp?newSdp:sdp}return sdp},collectLocalMediaInfo=function(mediaProvider,display){var videoCams=[],mics=[];mediaProvider.videoCams&&mediaProvider.videoCams.forEach((function(device){videoCams.push({id:device.id,label:encodeURI(device.label),type:device.type})})),mediaProvider.mics&&mediaProvider.mics.forEach((function(device){mics.push({id:device.id,label:encodeURI(device.label),type:device.type})})),videoCams.length&&logger.info("core","Video inputs available: "+JSON.stringify(videoCams)),mics.length&&logger.info("core","Audio inputs available: "+JSON.stringify(mics));var localVideo,audioTracks=[],videoTracks=[];return mediaProvider.getCacheInstance&&(localVideo=mediaProvider.getCacheInstance(display)),!localVideo&&mediaProvider.getVideoElement&&(localVideo=mediaProvider.getVideoElement(display)),localVideo&&localVideo.srcObject&&(localVideo.srcObject.getAudioTracks().forEach((function(track){var device=track.label;"MediaStreamAudioDestinationNode"===device&&mediaProvider.getAudioSourceDevice&&(device=mediaProvider.getAudioSourceDevice()),audioTracks.push({trackId:track.id,device:encodeURI(device)})})),localVideo.srcObject.getVideoTracks().forEach((function(track){videoTracks.push({trackId:track.id,device:encodeURI(track.label)})}))),videoTracks.length&&logger.info("core","Video tracks captured: "+JSON.stringify(videoTracks)),audioTracks.length&&logger.info("core","Audio tracks captured: "+JSON.stringify(audioTracks)),{devices:{video:videoCams,audio:mics},tracks:{video:videoTracks,audio:audioTracks}}};return session.id=function(){return id_},session.status=function(){return sessionStatus},session.getServerUrl=function(){return urlServer},session.createStream=function(options){var availableCallbacks=[];if(sessionStatus!==SESSION_STATUS.ESTABLISHED)throw new Error("Invalid session state "+sessionStatus);if(!options)throw new TypeError("options must be provided");if(!options.name)throw new TypeError("options.name must be provided");var mediaConnection,streamLogger=createLogger(options.logger,sessionLogger),logger=streamLogger,clientKf=new KalmanFilter,serverKf=new KalmanFilter,id_=uuid_v1(),name_=options.name,mediaProvider=options.mediaProvider||getMediaProviders()[0],display=options.display;if(options.constraints&&0!=Object.keys(options.constraints).length)var constraints=options.constraints;if(options.disableConstraintsNormalization)var disableConstraintsNormalization=options.disableConstraintsNormalization;var receiveAudio,audioOutputId,receiveVideo,mediaConnectionConstraints=options.mediaConnectionConstraints,audioProperty=getConstraintsProperty(constraints,"audio",void 0);if("boolean"==typeof audioProperty)receiveAudio=audioProperty;else if("object"===_typeof(audioProperty)){receiveAudio=!0;var _stereo=getConstraintsProperty(audioProperty,"stereo",0),_bitrate=getConstraintsProperty(audioProperty,"bitrate",0),_fec=getConstraintsProperty(audioProperty,"fec",0);audioOutputId=getConstraintsProperty(audioProperty,"outputId",0);var _codecOptions="";_bitrate&&(_codecOptions+="maxaveragebitrate="+_bitrate+";"),_stereo&&(_codecOptions+="stereo=1;sprop-stereo=1;"),_fec&&(_codecOptions+="useinbandfec=1;")}else receiveAudio="undefined"==typeof options.receiveAudio||options.receiveAudio;var videoProperty=getConstraintsProperty(constraints,"video",void 0);receiveVideo="boolean"==typeof videoProperty?videoProperty:"object"===_typeof(videoProperty)||("undefined"==typeof options.receiveVideo||options.receiveVideo);var bitrate=getConstraintsProperty(constraints,"video.bitrate",0),minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0),quality=getConstraintsProperty(constraints,"video.quality",0);quality>100&&(quality=100);var info_,errorInfo_,audioState_,videoState_,connectionQuality,playWidth="undefined"!=typeof options.playWidth?options.playWidth:getConstraintsProperty(constraints,"video.width",0),playHeight="undefined"!=typeof options.playHeight?options.playHeight:getConstraintsProperty(constraints,"video.height",0),stripCodecs=options.stripCodecs||[],resolution={},published_=!1,record_=options.record||!1,recordFileName=null,cacheLocalResources=options.cacheLocalResources,status_=STREAM_STATUS.NEW,rtmpUrl=options.rtmpUrl,remoteBitrate=-1,networkBandwidth=-1,sdpHook=options.sdpHook,transportType=options.transport,cvoExtension=options.cvoExtension,remoteVideo=options.remoteVideo,callbacks={},playoutDelay=options.playoutDelay,useCanvasMediaStream=options.useCanvasMediaStream,videoContentHint=options.videoContentHint,unmutePlayOnStart=options.unmutePlayOnStart,useControls=options.useControls,collectDeviceInfo=void 0===options.collectDeviceInfo||options.collectDeviceInfo,videoBytes=0,statsCollector=null,stream={};streamEventRefreshHandlers[id_]=function(streamEvent){if(streamEvent.type==STREAM_EVENT_TYPE.NOT_ENOUGH_BANDWIDTH){var info=streamEvent.payload.info.split("/");remoteBitrate=info[0],networkBandwidth=info[1]}else streamEvent.type==STREAM_EVENT_TYPE.RESIZE&&(resolution.width=streamEvent.payload.streamerVideoWidth,resolution.height=streamEvent.payload.streamerVideoHeight);callbacks[STREAM_EVENT]&&callbacks[STREAM_EVENT](streamEvent)},streamRefreshHandlers[id_]=function(streamInfo,sdp){if(sdp&&""!==sdp){var _sdp=sdp;return _codecOptions&&(_sdp=util.SDP.writeFmtp(sdp,_codecOptions,"opus")),_sdp=sdpHookHandler(_sdp,sdpHook),_sdp=util.setPublishingBitrate(_sdp,mediaConnection,minBitrate,maxBitrate),void mediaConnection.setRemoteSdp(_sdp).then((function(){}))}if(void 0===streamInfo.available){var event=streamInfo.status;if("inboundVideoRate"!==event&&"outboundVideoRate"!==event){if(event===STREAM_EVENT)return streamInfo.mediaSessionId||(streamInfo.mediaSessionId=id_),void streamEventRefreshHandlers[id_](streamInfo);if(event===STREAM_STATUS.RESIZE)resolution.width=streamInfo.streamerVideoWidth,resolution.height=streamInfo.streamerVideoHeight;else if(event===STREAM_STATUS.SNAPSHOT_COMPLETE);else if(event===STREAM_STATUS.NOT_ENOUGH_BANDWIDTH){var info=streamInfo.info.split("/");remoteBitrate=info[0],networkBandwidth=info[1]}else status_=event;streamInfo.audioState&&(audioState_=streamInfo.audioState),streamInfo.videoState&&(videoState_=streamInfo.videoState),streamInfo.info&&(info_=streamInfo.info),event!==STREAM_STATUS.FAILED&&event!==STREAM_STATUS.STOPPED&&event!==STREAM_STATUS.UNPUBLISHED||(delete streams[id_],delete streamRefreshHandlers[id_],delete streamEventRefreshHandlers[id_],mediaConnection&&mediaConnection.close(cacheLocalResources),statsCollector&&(statsCollector.stop(),statsCollector=null)),record_&&"undefined"!=typeof streamInfo.recordName&&(recordFileName=streamInfo.recordName),event!==STREAM_STATUS.PUBLISHING&&event!==STREAM_STATUS.PLAYING||webRTCMetricsServerDescription&&!statsCollector&&(statsCollector=StatsCollector.StreamStatsCollector(webRTCMetricsServerDescription,id_,mediaConnection,wsConnection,logger)).start(),!streamInfo.status&&void 0!==streamInfo.collect&&statsCollector&&statsCollector.update(streamInfo),callbacks[event]&&callbacks[event](stream)}else detectConnectionQuality(event,streamInfo)}else{for(var i=0;i<availableCallbacks.length;i++)info_=streamInfo.reason,"true"==streamInfo.available?availableCallbacks[i].resolve(stream):availableCallbacks[i].reject(stream);availableCallbacks=[]}};var detectConnectionQuality=function(event,streamInfo){disableConnectionQualityCalculation||mediaConnection.getStats((function(stats){var bytesSentReceived=0;if(stats)if("outboundVideoRate"==event&&stats.inboundStream&&stats.inboundStream.video&&stats.inboundStream.video.bytesReceived>0)bytesSentReceived=stats.inboundStream.video.bytesReceived;else{if(!(stats.outboundStream&&stats.outboundStream.video&&stats.outboundStream.video.bytesSent>0))return;bytesSentReceived=stats.outboundStream.video.bytesSent}if(videoBytes){var currentVideoRate=8*(bytesSentReceived-videoBytes);if(0!=currentVideoRate){var currentQuality,clientFiltered=clientKf.filter(currentVideoRate),serverFiltered=serverKf.filter(streamInfo.videoRate),videoRateDifference=100*Math.abs((serverFiltered-clientFiltered)/((serverFiltered+clientFiltered)/2));currentQuality=serverFiltered<5e4||clientFiltered<5e4?videoRateDifference>150?CONNECTION_QUALITY.BAD:CONNECTION_QUALITY.PERFECT:videoRateDifference>50?CONNECTION_QUALITY.BAD:videoRateDifference>20?CONNECTION_QUALITY.GOOD:CONNECTION_QUALITY.PERFECT,callbacks[CONNECTION_QUALITY.UPDATE]&&(connectionQuality=currentQuality,callbacks[CONNECTION_QUALITY.UPDATE](connectionQuality,clientFiltered,serverFiltered)),videoBytes=bytesSentReceived}}else videoBytes=bytesSentReceived}))},isRemoteAudioMuted=function(){return!(!mediaConnection||"Flash"==mediaProvider)&&mediaConnection.isRemoteAudioMuted()},_stop=function(){if(logger.debug("core","Stop stream "+name_),statsCollector&&(statsCollector.stop(),statsCollector=null),status_!=STREAM_STATUS.NEW)return status_==STREAM_STATUS.PENDING?(logger.warn("core","Stopping stream before server response "+id_),void setTimeout(_stop,200)):void(status_!=STREAM_STATUS.FAILED?(send(published_?"unPublishStream":"stopStream",{mediaSessionId:id_,name:name_,published:published_,hasVideo:!0,hasAudio:!0,status:status_,record:!1}),mediaConnection&&mediaConnection.close(cacheLocalResources)):logger.warn("core","Stream status FAILED"));streamRefreshHandlers[id_]({status:STREAM_STATUS.FAILED})},published=function(){return published_};function sendStreamEvent(type,payload){send("sendStreamEvent",{mediaSessionId:id_,type:type,payload:payload})}var fireUnmuteEvent=function(){isRemoteAudioMuted()&&streamRefreshHandlers[id_]&&"function"==typeof streamRefreshHandlers[id_]&&streamRefreshHandlers[id_]({status:STREAM_EVENT,type:STREAM_EVENT_TYPE.UNMUTE_REQUIRED})},setZoom=function(){var _ref2=_asyncToGenerator(_regenerator().m((function _callee2(value){return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(!published()||!mediaConnection){_context2.n=2;break}return _context2.n=1,mediaConnection.setZoom(value);case 1:return _context2.a(2,_context2.v);case 2:throw new Error("This function available for publishing stream only");case 3:return _context2.a(2)}}),_callee2)})));return function(_x2){return _ref2.apply(this,arguments)}}();return stream.play=function(){if(logger.debug("core","Play stream "+name_),status_!==STREAM_STATUS.NEW)throw new Error("Invalid stream state "+status_);status_=STREAM_STATUS.PENDING,MediaProvider[mediaProvider].createConnection({id:id_,display:display,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,flashBufferTime:options.flashBufferTime||0,flashShowFullScreenButton:options.flashShowFullScreenButton||!1,connectionConfig:mediaOptions,connectionConstraints:mediaConnectionConstraints,audioOutputId:audioOutputId,remoteVideo:remoteVideo,playoutDelay:playoutDelay,unmutePlayOnStart:unmutePlayOnStart,useControls:useControls,logger:logger,unmuteRequiredEvent:fireUnmuteEvent},streamRefreshHandlers[id_]).then((function(newConnection){mediaConnection=newConnection;try{streamRefreshHandlers[id_]({status:status_})}catch(e){console.warn(e)}return mediaConnection.createOffer({receiveAudio:receiveAudio,receiveVideo:receiveVideo,stripCodecs:stripCodecs,stereo:_stereo})})).then((function(offer){logger.debug("core","Offer SDP:\n"+offer.sdp),send("playStream",{mediaSessionId:id_,name:name_,published:published_,hasVideo:!0,hasAudio:!0,status:status_,record:!1,width:playWidth,height:playHeight,mediaProvider:mediaProvider,sdp:offer.sdp,custom:options.custom,bitrate:bitrate,minBitrate:minBitrate,maxBitrate:maxBitrate,quality:quality,constraints:constraints,transport:transportType,cvoExtension:cvoExtension}),offer.player&&offer.player.play(id_)})).catch((function(error){throw error}))},stream.publish=function(){if(logger.debug("core","Publish stream "+name_),status_!==STREAM_STATUS.NEW)throw new Error("Invalid stream state "+status_);status_=STREAM_STATUS.PENDING,published_=!0;constraints&&constraints.video&&constraints.video.type&&constraints.video.type,MediaProvider[mediaProvider].getMediaAccess(constraints,display,disableConstraintsNormalization,useCanvasMediaStream).then((function(){status_!=STREAM_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,display:display,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,constraints:constraints,connectionConfig:mediaOptions,connectionConstraints:mediaConnectionConstraints,customStream:!(!constraints||!constraints.customStream)&&constraints.customStream,videoContentHint:videoContentHint,useControls:useControls,logger:logger}).then((function(newConnection){return(mediaConnection=newConnection).createOffer({stripCodecs:stripCodecs})})).then((function(offer){logger.debug("core","Offer SDP:\n"+offer.sdp);var publishStreamData={mediaSessionId:id_,name:name_,published:published_,hasVideo:offer.hasVideo,hasAudio:offer.hasAudio,status:status_,record:record_,mediaProvider:mediaProvider,sdp:offer.sdp,custom:options.custom,bitrate:bitrate,minBitrate:minBitrate,maxBitrate:maxBitrate,rtmpUrl:rtmpUrl,constraints:constraints,transport:transportType,cvoExtension:cvoExtension};collectDeviceInfo&&(publishStreamData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],display)),send("publishStream",publishStreamData)})):cacheLocalResources||releaseLocalMedia(display,mediaProvider)})).catch((function(error){logger.warn("core",error),info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,status_=STREAM_STATUS.FAILED,callbacks[status_]&&callbacks[status_](stream)}))},stream.stop=_stop,stream.id=function(){return id_},stream.status=function(){return status_},stream.name=function(){return name_},stream.published=published,stream.getRecordInfo=function(){return recordFileName},stream.getInfo=function(){return info_},stream.getErrorInfo=function(){return errorInfo_},stream.videoResolution=function(){if(published_)throw new Error("This function available only on playing stream");return resolution},stream.setAudioOutputId=function(id){if(audioOutputId=id,mediaConnection&&mediaConnection.setAudioOutputId)return mediaConnection.setAudioOutputId(id)},stream.setVolume=function(volume){mediaConnection&&mediaConnection.setVolume(volume)},stream.unmuteRemoteAudio=function(){mediaConnection&&"Flash"!=mediaProvider&&mediaConnection.unmuteRemoteAudio()},stream.muteRemoteAudio=function(){mediaConnection&&"Flash"!=mediaProvider&&mediaConnection.muteRemoteAudio()},stream.isRemoteAudioMuted=isRemoteAudioMuted,stream.setMicrophoneGain=function(volume){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");mediaConnection.setMicrophoneGain(volume)},stream.getVolume=function(){return mediaConnection?mediaConnection.getVolume():-1},stream.muteAudio=function(){mediaConnection&&(mediaConnection.muteAudio(),sendStreamEvent(STREAM_EVENT_TYPE.AUDIO_MUTED))},stream.unmuteAudio=function(){mediaConnection&&(mediaConnection.unmuteAudio(),sendStreamEvent(STREAM_EVENT_TYPE.AUDIO_UNMUTED))},stream.isAudioMuted=function(){return!mediaConnection||mediaConnection.isAudioMuted()},stream.muteVideo=function(){mediaConnection&&(mediaConnection.muteVideo(),sendStreamEvent(STREAM_EVENT_TYPE.VIDEO_MUTED))},stream.unmuteVideo=function(){mediaConnection&&(mediaConnection.unmuteVideo(),sendStreamEvent(STREAM_EVENT_TYPE.VIDEO_UNMUTED))},stream.isVideoMuted=function(){return!mediaConnection||mediaConnection.isVideoMuted()},stream.getStats=function(callbackFn,nativeStats){mediaConnection&&mediaConnection.getStats(callbackFn,nativeStats)},stream.snapshot=function(){if(logger.debug("core","Request snapshot, stream "+name_),status_!==STREAM_STATUS.NEW&&status_!==STREAM_STATUS.PLAYING&&status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");send("snapshot",{name:name_,mediaSessionId:id_})},stream.getAudioState=function(){return audioState_},stream.getVideoState=function(){return videoState_},stream.getNetworkBandwidth=function(){return networkBandwidth},stream.getRemoteBitrate=function(){return remoteBitrate},stream.fullScreen=function(){published()?logger.warn("core","Full screen is allowed only for played streams"):mediaConnection&&mediaConnection.fullScreen()},stream.on=function(event,callback){if(!event)throw new TypeError("Event can't be null");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,stream},stream.available=function(){return new _Promise((function(resolve,reject){send("availableStream",{mediaSessionId:id_,name:name_});var promise={};promise.resolve=resolve,promise.reject=reject,availableCallbacks.push(promise)}))},stream.switchCam=function(deviceId){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchCam(deviceId)},stream.switchMic=function(deviceId){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchMic(deviceId)},stream.switchToScreen=function(source,woExtension){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchToScreen(source,woExtension)},stream.switchToCam=function(){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");mediaConnection.switchToCam()},stream.sendData=function(payload){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");sendStreamEvent(STREAM_EVENT_TYPE.DATA,payload)},stream.getLogger=function(){return streamLogger},stream.updateVideoSettings=function(settings){if(published()&&mediaConnection)return mediaConnection.updateVideoSettings(settings);throw new Error("This function available for publishing stream only")},stream.updateVideoResolution=function(resolution){if(published()&&mediaConnection)return mediaConnection.updateVideoResolution(resolution);throw new Error("This function available for publishing stream only")},stream.getZoomCapabilities=function(){if(published()&&mediaConnection)return mediaConnection.getZoomCapabilities();throw new Error("This function available for publishing stream only")},stream.getZoom=function(){if(published()&&mediaConnection)return mediaConnection.getZoom();throw new Error("This function available for publishing stream only")},stream.setZoom=setZoom,streams[id_]=stream,stream},session.createCall=createCall,session.getStream=function(streamId){return streams[streamId]},session.getStreams=function(){return util.copyObjectToArray(streams)},session.sendData=restAppCommunicator.sendData,session.disconnect=function(){wsConnection&&wsConnection.close()},session.submitBugReport=function(reportObject){send("submitBugReport",reportObject)},session.startDebug=function(){logger.setPushLogs(!0),logger.setLevel("DEBUG"),send("sessionDebug",{command:"start"})},session.stopDebug=function(){logger.setLevel("INFO"),send("sessionDebug",{command:"stop"})},session.on=function(event,callback){if(!event)throw new Error("Event can't be null","TypeError");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,session},session.getLogger=function(){return sessionLogger},sessions[id_]=session,session},playFirstSound:function(noise){var mediaProvider=getMediaProviders()[0];MediaProvider[mediaProvider].playFirstSound(noise)},playFirstVideo:function(display,isLocal,src,useControls){for(var mp in MediaProvider)return MediaProvider[mp].playFirstVideo(display,isLocal,src,useControls)},getLogger:function(){if(initialized)return coreLogger;console.warn("Initialize API first.")},constants:constants,firefoxScreenSharingExtensionInstalled:!0,Browser:util.Browser}},{"./client-info":38,"./constants":39,"./media-source-media-provider":1,"./stats-collector":41,"./temasys-media-provider":1,"./util":42,"./webrtc-media-provider":43,"./websocket-media-provider":1,kalmanjs:2,"promise-polyfill":4,uuid:8,"webrtc-adapter":23}],41:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||_unsupportedIterableToArray(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function(){};return{s:F,n:function(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var util=require("./util"),LOG_PREFIX="stats-collector",CONNECTION_TYPE_WEBSOCKET="ws",CONNECTION_TYPE_HTTP="http",CONNECTION_STATUS_INIT=0,CONNECTION_STATUS_OK=200,CONNECTION_STATUS_BAD_REQUEST=400,CONNECTION_STATUS_INTERNAL_SERVER_ERROR=500,Connection=function(){var _send2,existingConnection=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,maxErrors=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3,connection={type:"",websocket:null,http:null,maxErrors:maxErrors,errorsCount:0,status:CONNECTION_STATUS_INIT,setUp:function(url){var headers=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,existingConnection=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;url.startsWith(CONNECTION_TYPE_WEBSOCKET)?connection.type=CONNECTION_TYPE_WEBSOCKET:url.startsWith(CONNECTION_TYPE_HTTP)?(connection.type=CONNECTION_TYPE_HTTP,connection.http=HttpConnection(url,headers)):existingConnection&&(connection.type=CONNECTION_TYPE_WEBSOCKET,connection.websocket=WebsocketConnection(existingConnection)),connection.errorsCount=0,connection.status=CONNECTION_STATUS_INIT},send:(_send2=_asyncToGenerator(_regenerator().m((function _callee0(message,data){var code,_t4;return _regenerator().w((function(_context0){for(;;)switch(_context0.n){case 0:code=CONNECTION_STATUS_BAD_REQUEST,_t4=connection.type,_context0.n=_t4===CONNECTION_TYPE_WEBSOCKET?1:_t4===CONNECTION_TYPE_HTTP?2:5;break;case 1:return connection.websocket&&(code=connection.websocket.send(message,data)),_context0.a(3,5);case 2:if(!connection.http){_context0.n=4;break}return _context0.n=3,connection.http.send(message,data);case 3:code=_context0.v;case 4:return _context0.a(3,5);case 5:connection.status=code,connection.status===CONNECTION_STATUS_OK?connection.errorsCount=0:"webRTCMetricsBatch"===message&&(connection.errorsCount++,connection.errorsCount<connection.maxErrors&&(connection.status=CONNECTION_STATUS_OK));case 6:return _context0.a(2)}}),_callee0)}))),function(_x5,_x6){return _send2.apply(this,arguments)})};return connection.setUp("",null,existingConnection),connection},WebsocketConnection=function(wsConnection){var connection={websocket:wsConnection,send:function(message,data){var code=CONNECTION_STATUS_BAD_REQUEST;return connection.websocket&&(connection.websocket.readyState===WebSocket.OPEN&&connection.websocket.send(JSON.stringify({message:message,data:[data]})),code=CONNECTION_STATUS_OK),code}};return connection},HttpConnection=function(url,headers){var _send3,connection={url:addSlash(url),headers:headers,send:(_send3=_asyncToGenerator(_regenerator().m((function _callee1(message,data){var code,httpHeaders,_i2,_Object$entries,_Object$entries$_i,header,value,response;return _regenerator().w((function(_context1){for(;;)switch(_context1.p=_context1.n){case 0:if(code=CONNECTION_STATUS_BAD_REQUEST,!connection.url){_context1.n=4;break}if(_context1.p=1,(httpHeaders=new Headers).append("Content-Type","application/json"),connection.headers)for(_i2=0,_Object$entries=Object.entries(connection.headers);_i2<_Object$entries.length;_i2++)_Object$entries$_i=_slicedToArray(_Object$entries[_i2],2),header=_Object$entries$_i[0],value=_Object$entries$_i[1],httpHeaders.append(header,value);return _context1.n=2,fetch(connection.url+message,{method:"POST",headers:httpHeaders,mode:"cors",body:JSON.stringify(data)});case 2:response=_context1.v,code=response.status,_context1.n=4;break;case 3:_context1.p=3,_context1.v,code=CONNECTION_STATUS_INTERNAL_SERVER_ERROR;case 4:return _context1.a(2,code)}}),_callee1,null,[[1,3]])}))),function(_x7,_x8){return _send3.apply(this,arguments)})};return connection},valueToString=function(value){var valueString="undefined";return value&&(valueString="object"===_typeof(value)?JSON.stringify(value):value.toString()),valueString},getLogger=function(logger){return logger&&void 0!==logger.info&&void 0!==logger.warn&&void 0!==logger.error&&void 0!==logger.debug?logger:{info:function(){},warn:function(){},error:function(){},debug:function(){}}},addSlash=function(value){var endpoint=value;return endpoint&&!endpoint.endsWith("/")&&(endpoint+="/"),endpoint};module.exports={StreamStatsCollector:function(description,id,mediaConnection,wsConnection,logger,maxErrors){var _sendMetrics,_collectMetrics,_send,_sendHeaders,_checkForCompression,_updateCompression,_updateHeaders,_update,_start,statCollector={description:description,id:id,mediaConnection:mediaConnection,connection:Connection(wsConnection,maxErrors),logger:getLogger(logger),headers:"",compression:"none",metricsBatch:null,timer:null,batchCount:0,timerBusy:!1,start:(_start=_asyncToGenerator(_regenerator().m((function _callee(){var error,authHeader;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(error="Can't collect WebRTC stats to send: ",statCollector.description.types){_context.n=1;break}throw new Error(error+"no report types defined");case 1:if(statCollector.description.sampling){_context.n=2;break}throw new Error(error+"no sampling interval defined");case 2:if(statCollector.description.batchSize){_context.n=3;break}throw new Error(error+"no metrics batch size defined");case 3:if(statCollector.mediaConnection){_context.n=4;break}throw new Error(error+"no media connection available");case 4:return statCollector.logger.debug(LOG_PREFIX,"RTCMetricsServerDescription: "+JSON.stringify(statCollector.description)),statCollector.description.ingestPoint&&(authHeader=null,statCollector.description.authorization&&(authHeader={Authorization:statCollector.description.authorization}),statCollector.connection.setUp(statCollector.description.ingestPoint,authHeader)),_context.n=5,statCollector.updateHeaders();case 5:return _context.n=6,statCollector.updateCompression();case 6:return _context.n=7,statCollector.sendHeaders();case 7:"on"===statCollector.description.collect&&statCollector.collect(!0);case 8:return _context.a(2)}}),_callee)}))),function(){return _start.apply(this,arguments)}),collect:function(enable){enable&&statCollector.connection.status===CONNECTION_STATUS_OK?statCollector.startTimer():statCollector.stopTimer()},stop:function(){statCollector.stopTimer(),statCollector.headers=""},update:(_update=_asyncToGenerator(_regenerator().m((function _callee2(description){var _t;return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(description){_context2.n=1;break}return statCollector.logger.error(LOG_PREFIX+"-"+statCollector.id,"Can't update WebRTC metrics sending: no parameters passed"),_context2.a(2);case 1:if(statCollector.logger.debug(LOG_PREFIX,"New RTCMetricsServerDescription: "+JSON.stringify(description)),!description.types&&!description.compression){_context2.n=6;break}if(statCollector.stop(),!description.types){_context2.n=2;break}return statCollector.description.types=description.types,_context2.n=2,statCollector.updateHeaders();case 2:if(!description.compression){_context2.n=3;break}return statCollector.description.compression=description.compression,_context2.n=3,statCollector.updateCompression();case 3:return _context2.n=4,statCollector.sendHeaders();case 4:if(statCollector.connection.status===CONNECTION_STATUS_OK){_context2.n=5;break}return _context2.a(2);case 5:_context2.n=7;break;case 6:statCollector.collect(!1);case 7:description.batchSize&&(statCollector.description.batchSize=description.batchSize),description.sampling&&(statCollector.description.sampling=description.sampling),description.collect&&(statCollector.description.collect=description.collect),_t=statCollector.description.collect,_context2.n="on"===_t?8:"off"===_t?9:10;break;case 8:return statCollector.collect(!0),_context2.a(3,10);case 9:return statCollector.collect(!1),_context2.a(3,10);case 10:return _context2.a(2)}}),_callee2)}))),function(_x){return _update.apply(this,arguments)}),updateHeaders:(_updateHeaders=_asyncToGenerator(_regenerator().m((function _callee3(){var stats,currentHeaders,headersChanged,newMetrics,_args3=arguments;return _regenerator().w((function(_context3){for(;;)switch(_context3.n){case 0:if(stats=_args3.length>0&&void 0!==_args3[0]?_args3[0]:null,currentHeaders="",headersChanged=!1,null!==stats){_context3.n=2;break}return _context3.n=1,statCollector.mediaConnection.getWebRTCStats();case 1:stats=_context3.v;case 2:return Object.keys(statCollector.description.types).forEach((function(type){var typeDescriptor=statCollector.description.types[type],metricsString="",contentFilters=null;typeDescriptor.metrics&&(metricsString=typeDescriptor.metrics),typeDescriptor.contains&&(contentFilters=typeDescriptor.contains),stats[type]?stats[type].forEach((function(report){if(statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,type+" report: "+JSON.stringify(report)),contentFilters){var filtersMatched=!0;for(var filter in contentFilters){statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,type+" filter by "+filter+": "+JSON.stringify(contentFilters[filter]));var filterMatched=!1;if(report[filter]){var _step,_iterator=_createForOfIteratorHelper(contentFilters[filter]);try{for(_iterator.s();!(_step=_iterator.n()).done;){var value=_step.value;if(statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,filter+": "+value+" <> "+report[filter]),report[filter]===value){filterMatched=!0;break}}}catch(err){_iterator.e(err)}finally{_iterator.f()}}if(filtersMatched=filtersMatched&&filterMatched,!filterMatched)break}filtersMatched&&(currentHeaders=statCollector.addHeaders(currentHeaders,report,metricsString))}else currentHeaders=statCollector.addHeaders(currentHeaders,report,metricsString)})):statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,"No report type found in RTC stats: '"+type+"'")})),currentHeaders!==statCollector.headers&&(headersChanged=!0,newMetrics=[],currentHeaders.split(",").forEach((function(header){-1===statCollector.headers.indexOf(header)&&newMetrics.push(header)})),newMetrics.length&&statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"RTC metrics to be collected: "+newMetrics.toString()),statCollector.headers=currentHeaders),_context3.a(2,headersChanged)}}),_callee3)}))),function(){return _updateHeaders.apply(this,arguments)}),addHeaders:function(currentHeaders,report,metricsString){metricsString&&metricsString.split(",").forEach((function(metric){for(var _i=0,_Object$keys=Object.keys(report);_i<_Object$keys.length;_i++){var key=_Object$keys[_i];if(metric===key&&report[key]){currentHeaders=util.addFieldToCsvString(currentHeaders,report.type+"."+report.id+"."+metric,",");break}}}));return currentHeaders},updateCompression:(_updateCompression=_asyncToGenerator(_regenerator().m((function _callee4(){return _regenerator().w((function(_context4){for(;;)switch(_context4.n){case 0:if(!statCollector.description.compression){_context4.n=3;break}if(!(statCollector.description.compression.indexOf("gzip")>=0)){_context4.n=2;break}return _context4.n=1,statCollector.checkForCompression("gzip");case 1:_context4.n=3;break;case 2:if(!(statCollector.description.compression.indexOf("deflate")>=0)){_context4.n=3;break}return _context4.n=3,statCollector.checkForCompression("deflate");case 3:return _context4.a(2)}}),_callee4)}))),function(){return _updateCompression.apply(this,arguments)}),checkForCompression:(_checkForCompression=_asyncToGenerator(_regenerator().m((function _callee5(compression){var _t2;return _regenerator().w((function(_context5){for(;;)switch(_context5.p=_context5.n){case 0:return _context5.p=0,_context5.n=1,util.compress(compression,"test",!1);case 1:statCollector.compression=compression,_context5.n=3;break;case 2:_context5.p=2,_t2=_context5.v,statCollector.logger.warn(LOG_PREFIX+"-"+statCollector.id,"Can't compress metrics data using "+compression+": "+_t2),statCollector.compression="none";case 3:return _context5.a(2)}}),_callee5,null,[[0,2]])}))),function(_x2){return _checkForCompression.apply(this,arguments)}),sendHeaders:(_sendHeaders=_asyncToGenerator(_regenerator().m((function _callee6(){var data;return _regenerator().w((function(_context6){for(;;)switch(_context6.n){case 0:return data={mediaSessionId:statCollector.id,compression:statCollector.compression,headers:statCollector.headers},_context6.n=1,statCollector.send("webRTCMetricsClientDescription",data);case 1:return _context6.a(2)}}),_callee6)}))),function(){return _sendHeaders.apply(this,arguments)}),send:(_send=_asyncToGenerator(_regenerator().m((function _callee7(message,data){return _regenerator().w((function(_context7){for(;;)switch(_context7.n){case 0:if(statCollector.connection.status!==CONNECTION_STATUS_INIT&&statCollector.connection.status!==CONNECTION_STATUS_OK){_context7.n=2;break}return statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,data),_context7.n=1,statCollector.connection.send(message,data);case 1:statCollector.connection.status!==CONNECTION_STATUS_OK&&(statCollector.logger.error(LOG_PREFIX+"-"+statCollector.id,"Error "+statCollector.connection.status+" sending RTC metrics to the server, stop sending"),statCollector.stop());case 2:return _context7.a(2)}}),_callee7)}))),function(_x3,_x4){return _send.apply(this,arguments)}),startTimer:function(){statCollector.timer||(statCollector.batchCount=statCollector.description.batchSize,statCollector.timer=setInterval(statCollector.collectMetrics,statCollector.description.sampling))},stopTimer:function(){statCollector.timer&&(clearInterval(statCollector.timer),statCollector.timer=null,statCollector.metricsBatch=null)},collectMetrics:(_collectMetrics=_asyncToGenerator(_regenerator().m((function _callee8(){var stats,metrics,lostMetrics,headersUpdated;return _regenerator().w((function(_context8){for(;;)switch(_context8.n){case 0:if(!statCollector.timer||statCollector.timerBusy){_context8.n=7;break}return statCollector.timerBusy=!0,_context8.n=1,statCollector.mediaConnection.getWebRTCStats();case 1:return stats=_context8.v,statCollector.startNewBatch(),metrics=[],lostMetrics=[],statCollector.headers?statCollector.headers.split(",").forEach((function(header){var components=header.split("."),descriptor={type:components[0],id:components[1],name:components[2]},value=null;if(stats[descriptor.type]){var _step2,_iterator2=_createForOfIteratorHelper(stats[descriptor.type]);try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var report=_step2.value;if(report.id===descriptor.id){value=report[descriptor.name];break}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}}value?metrics.push(value):lostMetrics.push(descriptor)})):statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"No RTC metrics to collect, trying to update metrics available list"),_context8.n=2,statCollector.updateHeaders(stats);case 2:if(headersUpdated=_context8.v,!lostMetrics.length){_context8.n=4;break}return statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"Missing metrics: "+JSON.stringify(lostMetrics)),_context8.n=3,statCollector.sendMetrics();case 3:statCollector.startNewBatch(metrics),_context8.n=5;break;case 4:if(!metrics.length){_context8.n=5;break}if(statCollector.metricsBatch.push(metrics),statCollector.batchCount--,0!==statCollector.batchCount&&!headersUpdated){_context8.n=5;break}return _context8.n=5,statCollector.sendMetrics();case 5:if(!headersUpdated){_context8.n=6;break}return statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"RTC metrics list has changed, sending a new metrics description"),_context8.n=6,statCollector.sendHeaders();case 6:statCollector.timerBusy=!1;case 7:return _context8.a(2)}}),_callee8)}))),function(){return _collectMetrics.apply(this,arguments)}),sendMetrics:(_sendMetrics=_asyncToGenerator(_regenerator().m((function _callee9(){var previous,metricsToSend,metricsData,i,metricsString,j,valueString,previousString,data,_t3;return _regenerator().w((function(_context9){for(;;)switch(_context9.p=_context9.n){case 0:for(metricsToSend=[],i=0;statCollector.metricsBatch&&i<statCollector.metricsBatch.length;i++){for(metricsString="",j=0;j<statCollector.metricsBatch[i].length;j++)valueString=valueToString(statCollector.metricsBatch[i][j]),previousString="",previous&&(previousString=valueToString(previous[j])),valueString===previousString&&(valueString=""),metricsString=util.addFieldToCsvString(metricsString,valueString,";"),j>0&&""===metricsString&&(metricsString=";");previous=statCollector.metricsBatch[i],metricsToSend.push(metricsString)}if("none"===statCollector.compression){_context9.n=5;break}return _context9.p=1,_context9.n=2,util.compress(statCollector.compression,JSON.stringify(metricsToSend),!0);case 2:metricsData=_context9.v,_context9.n=4;break;case 3:_context9.p=3,_t3=_context9.v,statCollector.logger.warn(LOG_PREFIX+"-"+statCollector.id,"Can't send metrics data using"+statCollector.compression+": "+_t3),metricsData=null;case 4:_context9.n=6;break;case 5:metricsData=metricsToSend;case 6:if(!metricsData){_context9.n=7;break}return data={mediaSessionId:statCollector.id,metrics:metricsData},_context9.n=7,statCollector.send("webRTCMetricsBatch",data);case 7:statCollector.cleanBatch();case 8:return _context9.a(2)}}),_callee9,null,[[1,3]])}))),function(){return _sendMetrics.apply(this,arguments)}),startNewBatch:function(metrics){statCollector.metricsBatch||(statCollector.metricsBatch=[],metrics&&statCollector.metricsBatch.push(metrics))},cleanBatch:function(){statCollector.metricsBatch&&(statCollector.metricsBatch=null,statCollector.batchCount=statCollector.description.batchSize)}};return statCollector}}},{"./util":42}],42:[function(require,module,exports){"use strict";function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function _toConsumableArray(r){return function(r){if(Array.isArray(r))return _arrayLikeToArray(r)}(r)||function(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}(r)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var Browser={isIE:function(){return!!document.documentMode},isFirefox:function(){return"undefined"!=typeof InstallTrigger},isChrome:function(){return!!window.chrome&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!/OPR/.test(navigator.userAgent)},isEdge:function(){return!this.isIE()&&!!window.StyleMedia},isOpera:function(){return!!window.opr&&!!opr.addons||!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isiOS:function(){return/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream},isSafari:function(){var userAgent=navigator.userAgent.toLowerCase();return/(safari|applewebkit)/i.test(userAgent)&&!userAgent.includes("chrome")&&!userAgent.includes("android")},isAndroid:function(){return navigator.userAgent.toLowerCase().indexOf("android")>-1},isSafariWebRTC:function(){return navigator.mediaDevices&&this.isSafari()},isSamsungBrowser:function(){return/SamsungBrowser/i.test(navigator.userAgent)},isAndroidFirefox:function(){return this.isAndroid()&&/Firefox/i.test(navigator.userAgent)},isChromiumEdge:function(){return/Chrome/i.test(navigator.userAgent)&&/Edg/i.test(navigator.userAgent)},version:function(){var version=navigator.userAgent.match(/version\/(\d+)/i);return version?version[1]:(this.isEdge()&&(version=/\brv[ :]+(\d+)/g.exec(navigator.userAgent)||[]),this.isOpera()&&(version=navigator.userAgent.match(/\b(OPR)\/(\d+)/)||[]),this.isChromiumEdge()&&(version=navigator.userAgent.match(/\b(Edg)\/(\d+)/)||[]),this.isSamsungBrowser()&&(version=navigator.userAgent.match(/\b(SamsungBrowser)\/(\d+)/)||[]),this.isChrome()&&(version=navigator.userAgent.match(/\b(Chrome)\/(\d+)/)||[]),this.isFirefox()&&(version=navigator.userAgent.match(/\b(Firefox)\/(\d+)/)||[]),version[2]||0)}},SDP={matchPrefix:function(sdp,prefix){return sdp.trim().split("\n").map((function(line){return line.trim()})).filter((function(line){return 0===line.indexOf(prefix)}))},writeFmtp:function(sdp,param,codec){var i,sdpArray=sdp.split("\n");for(i=0;i<sdpArray.length;i++)-1!=sdpArray[i].search(codec)&&0==sdpArray[i].indexOf("a=rtpmap")&&(sdpArray[i]+="\na=fmtp:"+sdpArray[i].match(/[0-9]+/)[0]+" "+param+"\r");var result="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(result+=sdpArray[i]+"\n");return result},setPublishingBitrate:function(sdp,minBitrate,maxBitrate){if(sdp&&(minBitrate||maxBitrate)){var i,matches,sdpArray=sdp.split("\n"),rtpmap=-1,codec="",bitrateString="";for(i=0;i<sdpArray.length;i++)sdpArray[i].startsWith("a=rtpmap")?(matches=sdpArray[i].match("a=rtpmap:(.+) (.+)/.*"))&&matches.length>2&&(rtpmap=parseInt(matches[1],10),codec=matches[2]):"H264"!==codec&&"VP8"!==codec||(sdpArray[i].startsWith("a=fmtp:"+rtpmap)?(bitrateString=this.getBitrateString(sdpArray[i],minBitrate,maxBitrate))&&(sdpArray[i]+=";"+bitrateString):(bitrateString=this.getBitrateString("",minBitrate,maxBitrate))&&(sdpArray[i]="a=fmtp:"+rtpmap+" "+bitrateString+"\r\n"+sdpArray[i]),codec="",rtpmap=-1);var newSDP="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(newSDP+=sdpArray[i]+"\n");return newSDP}return sdp},getBitrateString:function(string,minBitrate,maxBitrate){var bitrateString="";return minBitrate&&-1==string.indexOf("x-google-min-bitrate")&&(bitrateString+="x-google-min-bitrate="+minBitrate),maxBitrate&&-1==string.indexOf("x-google-max-bitrate")&&(bitrateString&&(bitrateString+=";"),bitrateString+="x-google-max-bitrate="+maxBitrate),bitrateString}},compress=function(){var n,_ref=(n=_regenerator().m((function _callee(compression,data,base64){var stream,compressedReadableStream,compressedResponse,blob,buffer,compressedBase64;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if("undefined"!=typeof CompressionStream){_context.n=1;break}throw new Error("Compression is not available");case 1:return stream="string"==typeof data?new Blob([data],{type:"text/plain"}).stream():data.stream(),compressedReadableStream=stream.pipeThrough(new CompressionStream(compression)),_context.n=2,new Response(compressedReadableStream);case 2:return compressedResponse=_context.v,_context.n=3,compressedResponse.blob();case 3:if(blob=_context.v,!base64){_context.n=5;break}return _context.n=4,blob.arrayBuffer();case 4:return buffer=_context.v,compressedBase64=btoa(String.fromCharCode.apply(String,_toConsumableArray(new Uint8Array(buffer)))),_context.a(2,compressedBase64);case 5:return _context.a(2,blob);case 6:return _context.a(2)}}),_callee)})),function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))});return function(_x,_x2,_x3){return _ref.apply(this,arguments)}}();module.exports={isEmptyObject:function(obj){for(var name in obj)return!1;return!0},copyObjectToArray:function(obj){var ret=[];for(var prop in obj)obj.hasOwnProperty(prop)&&ret.push(obj[prop]);return ret},copyObjectPropsToAnotherObject:function(src,dst){for(var prop in src)src.hasOwnProperty(prop)&&(dst[prop]=src[prop])},processRtcStatsReport:function(browser,report){var result={};if("chrome"==browser){var gotResult=!1;if(report.type&&"googCandidatePair"==report.type&&"true"==report.googActiveConnection&&(gotResult=!0),report.type&&"ssrc"==report.type&&(gotResult=!0),gotResult)for(var k in report)report.hasOwnProperty(k)&&(result[k]=report[k]);return result}if("firefox"==browser){if(report.type&&("outboundrtp"==report.type||"inboundrtp"==report.type)&&-1==report.id.indexOf("rtcp"))for(var k in result={},report)report.hasOwnProperty(k)&&(result[k]=report[k]);return result}return result},Browser:Browser,SDP:SDP,logger:function(){return{init:function(verbosity,enablePushLogs,customLogger,enableLogs){switch(verbosity.toUpperCase()){case"DEBUG":this.verbosity=3;break;case"INFO":this.verbosity=2;break;case"ERROR":this.verbosity=0;break;case"WARN":this.verbosity=1;break;case"TRACE":this.verbosity=4;break;default:this.verbosity=2}this.date=function(){return(new Date).toTimeString().split(" ")[0]},this.enablePushLogs=enablePushLogs;var delayedLogs=[];this.customLogger=customLogger,this.enableLogs=enableLogs,this.pushLogs=function(log){if(this.wsConnection&&this.enablePushLogs){if(delayedLogs.length)for(var i=0;i<delayedLogs.length;i++)this.wsConnection.send(JSON.stringify({message:"pushLogs",data:[{logs:delayedLogs[i]}]}));delayedLogs=[],this.wsConnection.send(JSON.stringify({message:"pushLogs",data:[{logs:log}]}))}else delayedLogs.push(log)}},info:function(src,text){if(this.enableLogs){var prefix=this.date()+" INFO "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=2&&(null!=this.customLogger?this.customLogger.info(text):console.log(prefix,text))}},debug:function(src,text){if(this.enableLogs){var prefix=this.date()+" DEBUG "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=3&&(null!=this.customLogger?this.customLogger.debug(text):console.log(prefix,text))}},trace:function(src,text){if(this.enableLogs){var prefix=this.date()+" TRACE "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=4&&(null!=this.customLogger?this.customLogger.trace(text):console.log(prefix,text))}},warn:function(src,text){if(this.enableLogs){var prefix=this.date()+" WARN "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=1&&(null!=this.customLogger?this.customLogger.warn(text):console.warn(prefix,text))}},error:function(src,text){if(this.enableLogs){var prefix=this.date()+" ERROR "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=0&&(null!=this.customLogger?this.customLogger.error(text):console.error(prefix,text))}},setEnableLogs:function(enableLogs){this.enableLogs=enableLogs},setCustomLogger:function(customLogger){this.customLogger=customLogger},setConnection:function(connection){this.wsConnection=connection},setPushLogs:function(pushLogs){this.enablePushLogs=pushLogs},setLevel:function(level){switch(level.toUpperCase()){case"DEBUG":this.verbosity=3;break;case"INFO":this.verbosity=2;break;case"ERROR":this.verbosity=0;break;case"WARN":this.verbosity=1;break;case"TRACE":this.verbosity=4;break;default:this.verbosity=2}}}},stripCodecs:function(sdp,codecs){if(!codecs.length)return sdp;for(var i,sdpArray=sdp.split("\n"),codecsArray=codecs.split(","),pt=[],p=0;p<codecsArray.length;p++)for(console.log("Searching for codec "+codecsArray[p]),i=0;i<sdpArray.length;i++)-1!=sdpArray[i].search(new RegExp(codecsArray[p],"i"))&&0==sdpArray[i].indexOf("a=rtpmap")&&(console.log(codecsArray[p]+" detected"),pt.push(sdpArray[i].match(/[0-9]+/)[0]),sdpArray[i]="");if(pt.length){for(p=0;p<pt.length;p++)for(i=0;i<sdpArray.length;i++)-1==sdpArray[i].search("a=fmtp:"+pt[p])&&-1==sdpArray[i].search("a=rtcp-fb:"+pt[p])||(sdpArray[i]="");for(i=0;i<sdpArray.length;i++)if(-1!=sdpArray[i].search("m=audio")||-1!=sdpArray[i].search("m=video")){for(var mLineSplitted=sdpArray[i].split(" "),newMLine="",m=0;m<mLineSplitted.length;m++)(-1==pt.indexOf(mLineSplitted[m].trim())||m<=2)&&(newMLine+=mLineSplitted[m],m<mLineSplitted.length-1&&(newMLine+=" "));sdpArray[i]=newMLine}}var result="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(result+=sdpArray[i]+"\n");return result},getCurrentCodecAndSampleRate:function(sdp,mediaType){for(var codecPt,rows=sdp.split("\n"),ret={},i=0;i<rows.length;i++){if(codecPt&&-1!=rows[i].indexOf("a=rtpmap:"+codecPt))return ret.name=rows[i].split(" ")[1].split("/")[0],ret.sampleRate=rows[i].split(" ")[1].split("/")[1],ret;-1!=rows[i].indexOf("m="+mediaType)&&(codecPt=rows[i].split(" ")[3].trim())}return ret.name="undefined",ret.sampleRate="undefined",ret},isPromise:function(object){return null!==object&&"object"===_typeof(object)&&"function"==typeof object.then&&"function"==typeof object.catch},setPublishingBitrate:function(sdp,mediaConnection,minBitrate,maxBitrate){return(minBitrate||maxBitrate)&&(sdp&&Browser.isChrome()||Browser.isSafariWebRTC()?sdp=SDP.setPublishingBitrate(sdp,minBitrate,maxBitrate):mediaConnection&&mediaConnection.setPublishingBitrate(minBitrate,maxBitrate)),sdp},addFieldToCsvString:function(csvString,field,delimiter){return""!==field&&field.indexOf(delimiter)>=0&&(field='"'+field+'"'),csvString=""===csvString?field:csvString+delimiter+field},compress:compress}},{}],43:[function(require,module,exports){function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||_unsupportedIterableToArray(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var extensionId,defaultConstraints,logger,audioContext,createMicGainNode,microphoneGain,browserDetails=require("webrtc-adapter").default.browserDetails,uuid_v1=require("uuid").v1,util=require("./util"),connections={},constants=require("./constants"),validBrowsers=["firefox","chrome","safari"],videoCams=[],mics=[],audioSourceDevice="",mixAudioTracks=function(stream1,stream2){var stream1Sound=audioContext.createMediaStreamSource(stream1),stream2Sound=audioContext.createMediaStreamSource(stream2),destination=audioContext.createMediaStreamDestination(),newStream=destination.stream;return stream1Sound.connect(destination),stream2Sound.connect(destination),newStream.getAudioTracks()[0]},loadCanvasVideo=function(display,stream,video){var vEl=video;if(vEl){if("CANVAS"!==vEl.tagName){var canvas=document.createElement("canvas");display.replaceChild(canvas,vEl),canvas.appendChild(vEl),vEl=canvas}}else!function(parent){var canvas=document.createElement("canvas");parent.appendChild(canvas)}(display),function(parent){var video=document.createElement("video");parent.appendChild(video)}(display.children[0]),vEl=display.children[0];vEl.id||(vEl.id=uuid_v1()+"-LOCAL_CACHED_VIDEO");var child=vEl.children[0];return child.srcObject=stream,child.muted=!0,child.onloadedmetadata=function(e){child.play(),vEl.width=child.videoWidth,vEl.height=child.videoHeight,function(canvas,videoWidth,videoHeight){if(!canvas.parentNode)return;var newSize,display=vEl.parentNode,parentSize={w:display.parentNode.clientWidth,h:display.parentNode.clientHeight};newSize=videoWidth&&videoHeight?downScaleToFitSize(videoWidth,videoHeight,parentSize.w,parentSize.h):downScaleToFitSize(canvas.videoWidth,canvas.videoHeight,parentSize.w,parentSize.h);display.style.width=newSize.w+"px",display.style.height=newSize.h+"px";var margin=0;parentSize.h-newSize.h>1&&(margin=Math.floor((parentSize.h-newSize.h)/2));function downScaleToFitSize(videoWidth,videoHeight,dstWidth,dstHeight){var newWidth,newHeight,videoRatio=videoWidth/videoHeight;return dstWidth/dstHeight>videoRatio?(newHeight=dstHeight,newWidth=Math.floor(videoRatio*dstHeight)):(newWidth=dstWidth,newHeight=Math.floor(dstWidth/videoRatio)),{w:newWidth,h:newHeight}}display.style.margin=margin+"px auto"}(vEl,child.videoWidth,child.videoHeight)},util.Browser.isFirefox()&&vEl.getContext("2d"),vEl.srcObject=vEl.captureStream(30),stream.getAudioTracks().length>0&&vEl.srcObject.addTrack(stream.getAudioTracks()[0]),vEl},loadVideo=function(display,stream,screenShare,requestAudioConstraints,resolve,constraints,useCanvas){var video;function resolveCallback(){requestAudioConstraints&&"chrome"==browserDetails.browser?(logger.info("webrtc","Request for audio stream"),navigator.getUserMedia({audio:requestAudioConstraints},(function(stream){if(logger.info("webrtc","Got audio stream, add it to video stream"),video.srcObject.getAudioTracks()[0]){var mixedTrack=mixAudioTracks(stream,video.srcObject),originalTrack=video.srcObject.getAudioTracks()[0];video.srcObject.removeTrack(originalTrack),video.srcObject.addTrack(mixedTrack)}else video.srcObject.addTrack(stream.getAudioTracks()[0]);resolve(display)}))):resolve(display)}video=useCanvas?loadCanvasVideo(display,stream,getCacheInstance(display)):function(display,stream,screenShare,constraints,video){var vEl=video;return vEl||(vEl=createVideoElement(),display.appendChild(vEl)),vEl.id||(vEl.id=uuid_v1()+"-LOCAL_CACHED_VIDEO"),vEl.srcObject=stream,vEl.onloadedmetadata=function(e){screenShare&&!screenCaptureSupportedBrowsers()&&setScreenResolution(vEl,stream,constraints),vEl.play()},vEl}(display,stream,screenShare,constraints,getCacheInstance(display)),createMicGainNode&&stream.getAudioTracks().length>0&&"chrome"==browserDetails.browser&&(audioContext.resume(),microphoneGain=createGainNode(stream)),constraints.systemSound&&"chrome"==browserDetails.browser?chrome.runtime.sendMessage(extensionId,{type:"isInstalled"},(function(response){response?chrome.runtime.sendMessage(extensionId,{type:"getSourceId"},(function(response){if(response.error)resolveCallback(),logger.error("webrtc",response.error);else if(response.systemSoundAccess){var constraints={audio:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId,echoCancellation:!0},optional:[]},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId},optional:[]}};navigator.getUserMedia(constraints,(function(audioStream){if(stream.getAudioTracks().length>0){var originalAudioTrack=stream.getAudioTracks()[0],mixedTrack=mixAudioTracks(stream,audioStream);stream.addTrack(mixedTrack),stream.removeTrack(originalAudioTrack)}else stream.addTrack(audioStream.getAudioTracks()[0]);resolveCallback()}),(function(reason){resolveCallback(),logger.error("webrtc",reason)}))}else resolveCallback(),logger.error("webrtc","System sound: access is denied by the user")})):resolveCallback()})):resolveCallback()},createGainNode=function(stream){var audioCtx=audioContext,source=audioCtx.createMediaStreamSource(stream),gainNode=audioCtx.createGain(),destination=audioCtx.createMediaStreamDestination(),outputStream=destination.stream;source.connect(gainNode),gainNode.connect(destination);var sourceAudioTrack=stream.getAudioTracks()[0];return audioSourceDevice=sourceAudioTrack.label,gainNode.sourceAudioTrack=sourceAudioTrack,gainNode.release=function(){this.sourceAudioTrack.stop(),this.disconnect()},stream.addTrack(outputStream.getAudioTracks()[0]),stream.removeTrack(sourceAudioTrack),gainNode},setScreenResolution=function(video,stream,constraints){var newHeight,newWidth,videoRatio;video.videoWidth>video.videoHeight?(videoRatio=video.videoWidth/video.videoHeight,newHeight=constraints.video.videoWidth/videoRatio,newWidth=constraints.video.videoWidth):(videoRatio=video.videoHeight/video.videoWidth,newWidth=constraints.video.videoHeight/videoRatio,newHeight=constraints.video.videoHeight),console.log("videoRatio === "+videoRatio),stream.getVideoTracks()[0].applyConstraints({height:newHeight,width:newWidth})},getScreenDeviceIdWoExtension=function(constraints){return new Promise((function(resolve,reject){var video={};constraints.video.frameRate.ideal&&(video.frameRate=constraints.video.frameRate.ideal),constraints.video.width&&(video.width=constraints.video.width),constraints.video.height&&(video.height=constraints.video.height),0===Object.keys(video).length&&(video=!0),resolve({video:video,audio:!0})}))},getScreenDeviceId=function(constraints){return new Promise((function(resolve,reject){var o={};window.chrome?chrome.runtime.sendMessage(extensionId,{type:"isInstalled"},(function(response){response?(o.maxWidth=constraints&&constraints.video&&constraints.video.width?constraints.video.width:320,o.maxHeight=constraints&&constraints.video&&constraints.video.height?constraints.video.height:240,o.maxFrameRate=constraints&&constraints.video&&constraints.video.frameRate&&constraints.video.frameRate.ideal?constraints.video.frameRate.ideal:30,o.chromeMediaSource="desktop",chrome.runtime.sendMessage(extensionId,{type:"getSourceId"},(function(response){if(response.error)reject(new Error("Screen access denied"));else{o.chromeMediaSourceId=response.sourceId;var result={mandatory:o,sourceId:response.sourceId};response.systemSoundAccess&&(result.audioMandatory={chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId,echoCancellation:!0}),resolve(result)}}))):reject(new Error("Screen sharing extension is not available"))})):(o.mediaSource=constraints.video.mediaSource,o.width={},o.height={},o.frameRate={min:constraints.video.frameRate.max,max:constraints.video.frameRate.max},o.videoWidth=constraints.video.width,o.videoHeight=constraints.video.height,resolve(o))}))},releaseMedia=function(display){var video=getCacheInstance(display);return!!video&&(removeVideoElement(video),!0)};function getCacheInstance(display){var i;if(display)for(i=0;i<display.children.length;i++)if(display.children[i]&&(-1!=display.children[i].id.indexOf("-LOCAL_CACHED_VIDEO")||-1!=display.children[i].id.indexOf("-REMOTE_CACHED_VIDEO")))return logger.info("webrtc","FOUND WEBRTC CACHED INSTANCE, id "+display.children[i].id),display.children[i]}function createVideoElement(){var useControls=arguments.length>0&&void 0!==arguments[0]&&arguments[0],video=document.createElement("video");return video.muted=!0,util.Browser.isSafariWebRTC()&&(video.setAttribute("playsinline",""),video.setAttribute("webkit-playsinline","")),useControls&&enableVideoControls(video),video}function removeVideoElement(video){if(video.srcObject){video.pause();for(var tracks=video.srcObject.getTracks(),i=0;i<tracks.length;i++)tracks[i].stop(),-1!=video.id.indexOf("-LOCAL_CACHED_VIDEO")&&"audio"==tracks[i].kind&&microphoneGain&&microphoneGain.release();if(video.srcObject=null,"CANVAS"===video.tagName)for(var _i=0;_i<video.children.length;_i++)removeVideoElement(video.children[_i])}}function enableVideoControls(video){video&&!video.controls&&video.setAttribute("controls","controls")}var listDevices=function(labels,kind,deviceConstraints){deviceConstraints||(deviceConstraints={audio:!0,video:!0}),kind?"all"==kind&&(kind=""):kind=constants.MEDIA_DEVICE_KIND.INPUT;var getList=function(devices){for(var list={audio:[],video:[]},micCount=0,outputCount=0,camCount=0,i=0;i<devices.length;i++){var device=devices[i],ret={id:device.deviceId,label:device.label};0===device.kind.indexOf("audio"+kind)&&"communications"!=device.deviceId?(ret.type="audioinput"==device.kind?"mic":"speaker","mic"==ret.type&&""==ret.label&&(ret.label="microphone"+ ++micCount),"speaker"==ret.type&&""==ret.label&&(ret.label="speaker"+ ++outputCount),list.audio.push(ret)):0===device.kind.indexOf("video"+kind)?(""==ret.label&&(ret.label="camera"+ ++camCount),ret.type="camera",list.video.push(ret)):logger.debug("webrtc","unknown device "+device.kind+" id "+device.deviceId)}return list};return new Promise((function(resolve,reject){navigator.mediaDevices.enumerateDevices().then((function(devices){if(labels){var constraints=function(devices){for(var constraints={},i=0;i<devices.length;i++){var device=devices[i];0===device.kind.indexOf("audio"+kind)&&deviceConstraints.audio?constraints.audio=!0:0===device.kind.indexOf("video"+kind)&&deviceConstraints.video?constraints.video=!0:logger.debug("webrtc","unknown device "+device.kind+" id "+device.deviceId)}return constraints}(devices);if(0===Object.keys(constraints).length)return void reject(new Error(kind+" media devices not found"));navigator.getUserMedia(constraints,(function(stream){navigator.mediaDevices.enumerateDevices().then((function(devicesWithLabels){resolve(getList(devicesWithLabels)),stream.getTracks().forEach((function(track){track.stop()}))}),reject)}),reject)}else resolve(getList(devices))}),reject)}))};var screenCaptureSupportedBrowsers=function(){return util.Browser.isChrome()||util.Browser.isSafari()};module.exports={createConnection:function(options){return new Promise((function(resolve,reject){options.logger&&(logger=options.logger);var id=options.id,connectionConfig=options.connectionConfig||{iceServers:[]},connectionConstraints=options.connectionConstraints||{};connectionConstraints.hasOwnProperty("optional")||(connectionConstraints.optional=[{DtlsSrtpKeyAgreement:!0}]),connectionConfig.bundlePolicy="max-compat";var localVideo,currentAudioTrack,currentVideoTrack,systemSoundTrack,connection=new RTCPeerConnection(connectionConfig,connectionConstraints),display=options.display,localDisplay=options.localDisplay,remoteDisplay=options.remoteDisplay,bidirectional=options.bidirectional,remoteVideo=options.remoteVideo,switchCamIndex=0,switchMicCount=0,customStream=options.customStream,constraints=options.constraints?options.constraints:{},screenShare=!1,playoutDelay=options.playoutDelay,videoContentHint=options.videoContentHint?options.videoContentHint:"motion",unmutePlayOnStart=void 0===options.unmutePlayOnStart||options.unmutePlayOnStart,useControls=options.useControls||!1,unmuteRequiredEvent=options.unmuteRequiredEvent?options.unmuteRequiredEvent:null,zoom=null;if(bidirectional)(localVideo=getCacheInstance(localDisplay))&&(localVideo.srcObject?(localVideo.id=id+"-local",setContentHint(localVideo.srcObject,videoContentHint),addStreamTracks(connection,localVideo.srcObject)):localVideo=null),(remoteVideo=getCacheInstance(remoteDisplay))||(remoteVideo=createVideoElement(useControls),remoteDisplay.appendChild(remoteVideo)),remoteVideo.id=id+"-remote",options.audioOutputId&&"undefined"!=typeof remoteVideo.setSinkId&&remoteVideo.setSinkId(options.audioOutputId),remoteVideo.style="border-radius: 1px";else if(remoteVideo)remoteVideo.id&&(id=remoteVideo.id);else{var cachedVideo=getCacheInstance(display);cachedVideo&&-1===cachedVideo.id.indexOf("-REMOTE_CACHED_VIDEO")&&cachedVideo.srcObject?((localVideo=cachedVideo).id=id,setContentHint(localVideo.srcObject,videoContentHint),addStreamTracks(connection,localVideo.srcObject)):(cachedVideo?remoteVideo=cachedVideo:(remoteVideo=createVideoElement(useControls),display.appendChild(remoteVideo)),remoteVideo.id=id,options.audioOutputId&&"undefined"!=typeof remoteVideo.setSinkId&&remoteVideo.setSinkId(options.audioOutputId),remoteVideo.style="border-radius: 1px")}if(localVideo){useControls&&enableVideoControls(localVideo);var videoTrack=localVideo.srcObject.getVideoTracks()[0];videoTrack&&videoCams.forEach((function(cam,index){videoTrack.label===cam.label&&(switchCamIndex=index)}));var audioTrack=localVideo.srcObject.getAudioTracks()[0];audioTrack&&mics.forEach((function(mic,index){audioTrack.label===mic.label&&(switchMicCount=index)}))}function setContentHint(stream,hint){stream.getVideoTracks().forEach((function(track){void 0===track.contentHint?logger.warn("webrtc","Track contentHint unsupported"):(logger.info("webrtc","Set video track contentHint to "+hint),track.contentHint=hint)}))}function addStreamTracks(pc,stream){stream.getTracks().forEach((function(track){pc.addTrack(track,stream)}))}remoteVideo&&useControls&&enableVideoControls(remoteVideo),connection.ontrack=function(event){remoteVideo&&(remoteVideo.srcObject=event.streams[0],remoteVideo.onloadedmetadata=function(e){remoteVideo&&remoteVideo.play().then((function(){unmutePlayOnStart?remoteVideo.muted=!1:fireUnmuteEvent()})).catch((function(e){validBrowsers.includes(browserDetails.browser)?(logger.info("webrtc","Autoplay detected! Trying to play a video with a muted sound..."),remoteVideo.muted=!0,remoteVideo.play(),fireUnmuteEvent()):logger.error("webrtc",e)}))}),void 0!==playoutDelay&&connection.getReceivers().forEach((function(track){void 0===track.playoutDelayHint&&logger.warn("webrtc","Playout delay unsupported"),track.playoutDelayHint=playoutDelay}))},connection.onremovestream=function(event){remoteVideo&&remoteVideo.pause()},connection.onsignalingstatechange=function(event){},connection.oniceconnectionstatechange=function(event){},connection.onicecandidate=function(event){null!=event.candidate&&logger.debug("webrtc","Added icecandidate: "+event.candidate.candidate)};var unmuteAudio=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0&&(localVideo.srcObject.getAudioTracks()[0].enabled=!0)},unmuteVideo=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0&&(localVideo.srcObject.getVideoTracks()[0].enabled=!0)},getStat=function(){var _ref=_asyncToGenerator(_regenerator().m((function _callee(callbackFn,nativeStats){var result,rawStat;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:return result={outboundStream:{},inboundStream:{},otherStats:[]},_context.n=1,getWebRTCStats();case 1:rawStat=_context.v,nativeStats?callbackFn(rawStat):(rawStat["candidate-pair"]&&rawStat["candidate-pair"].forEach((function(report){"succeeded"===report.state&&report.nominated&&(report.availableIncomingBitrate?result.otherStats.availableIncomingBitrate=report.availableIncomingBitrate:localVideo&&report.availableOutgoingBitrate&&(result.otherStats.availableOutgoingBitrate=report.availableOutgoingBitrate))})),rawStat["outbound-rtp"]&&rawStat["outbound-rtp"].forEach((function(report){fillStatObject(result.outboundStream,report,report.kind),"video"===report.kind&&getVideoSize(result.outboundStream[report.kind],report.type,report)})),rawStat["inbound-rtp"]&&rawStat["inbound-rtp"].forEach((function(report){fillStatObject(result.inboundStream,report,report.kind),"video"===report.kind&&getVideoSize(result.inboundStream.video,report.type,report)})),callbackFn(result));case 2:return _context.a(2)}}),_callee)})));return function(_x,_x2){return _ref.apply(this,arguments)}}(),getVideoSize=function(obj,type,report){var videoSize={};"outbound-rtp"===type?void 0!==localVideo&&null!=localVideo&&(videoSize=localVideo.srcObject.getVideoTracks()[0].getSettings()):"inbound-rtp"===type&&void 0!==remoteVideo&&null!=remoteVideo&&(videoSize.width=remoteVideo.videoWidth,videoSize.height=remoteVideo.videoHeight),void 0!==report.frameWidth?obj.width=report.frameWidth:void 0!==videoSize.width&&(obj.width=videoSize.width),void 0!==report.frameHeight?obj.height=report.frameHeight:void 0!==videoSize.height&&(obj.height=videoSize.height)},fillStatObject=function(obj,report,mediaType){obj[mediaType]={};var description=null!=connection.currentRemoteDescription?connection.currentRemoteDescription:connection.remoteDescription,sdp="";description&&description.sdp?sdp=description.sdp:logger.debug("webrtc","Can't parse current SDP to detect codec and sampleRate");var qualityLimitationDurations,codec=util.getCurrentCodecAndSampleRate(sdp,mediaType);obj[mediaType].codec=codec.name,obj[mediaType].codecRate=codec.sampleRate,Object.keys(report).forEach((function(key){(key.startsWith("bytes")||key.startsWith("packets")||-1!=key.indexOf("Count")||-1!=key.indexOf("audioLevel")||"framesPerSecond"===key||"qualityLimitationReason"===key)&&(obj[mediaType][key]=report[key]),"qualityLimitationDurations"===key&&(qualityLimitationDurations=report[key])})),qualityLimitationDurations&&(obj[mediaType].qualityLimitationDurations=qualityLimitationDurations[obj[mediaType].qualityLimitationReason])},processScreenStream=function(stream,resolve){connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){currentAudioTrack=localVideo.srcObject.getAudioTracks()[0],currentVideoTrack=localVideo.srcObject.getVideoTracks()[0];var newVideoTrack=stream.getVideoTracks()[0];newVideoTrack.enabled=currentVideoTrack.enabled,sender.replaceTrack(newVideoTrack),localVideo.srcObject=stream,stream.getAudioTracks()[0]?(systemSoundTrack=stream.getAudioTracks()[0],connection.getSenders().forEach((function(sender){if("video"!==sender.track.kind){var mixedTrack=mixAudioTracks(stream,new MediaStream([sender.track]));mixedTrack.enabled=currentAudioTrack.enabled,sender.replaceTrack(mixedTrack),localVideo.srcObject.removeTrack(stream.getAudioTracks()[0]),localVideo.srcObject.addTrack(mixedTrack),currentAudioTrack.enabled=!0}}))):localVideo.srcObject.addTrack(currentAudioTrack)}})),logger.info("webrtc","Switch to screen"),screenShare=!0,resolve()},updateVideoSettings=function(settings){return new Promise((function(resolve,reject){connection&&settings&&connection.getSenders().forEach((function(sender){if("video"==sender.track.kind){for(var parameters=sender.getParameters(),i=0;i<parameters.encodings.length;i++)settings.maxBitrate?parameters.encodings[i].maxBitrate=1e3*settings.maxBitrate:parameters.encodings[i].maxBitrate&&delete parameters.encodings[i].maxBitrate,settings.frameRate&&(parameters.encodings[i].maxFramerate=settings.frameRate),settings.scaleResolutionDownBy&&(parameters.encodings[i].scaleResolutionDownBy=settings.scaleResolutionDownBy);sender.setParameters(parameters).then((function(){logger.info("webrtc","Set video encoder parameters to "+JSON.stringify(parameters.encodings)),resolve(parameters.encodings)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}}))}))},fireUnmuteEvent=function(){unmuteRequiredEvent&&"function"==typeof unmuteRequiredEvent&&unmuteRequiredEvent()},setZoom=function(){var _ref2=_asyncToGenerator(_regenerator().m((function _callee2(value){var _localVideo$srcObject3,_localVideo$srcObject4,track;return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(!zoom){_context2.n=6;break}if(!(value>=zoom.min&&value<=zoom.max)){_context2.n=4;break}if(!localVideo||!localVideo.srcObject){_context2.n=2;break}return _localVideo$srcObject3=localVideo.srcObject.getVideoTracks(),_localVideo$srcObject4=_slicedToArray(_localVideo$srcObject3,1),track=_localVideo$srcObject4[0],_context2.n=1,track.applyConstraints({advanced:[{zoom:value}]});case 1:zoom.value=value,_context2.n=3;break;case 2:logger.warn("webrtc","Can't set zoom value: no local video");case 3:_context2.n=5;break;case 4:logger.info("webrtc","Zoom value "+value+"is out of range: "+zoom.min+"-"+zoom.max);case 5:_context2.n=7;break;case 6:logger.info("webrtc","Zoom is not supported or zoom capabilities unknown yet");case 7:return _context2.a(2)}}),_callee2)})));return function(_x3){return _ref2.apply(this,arguments)}}(),getWebRTCStats=function(){return new Promise((function(resolve,reject){var browser=browserDetails.browser;connection&&validBrowsers.includes(browser)?connection.getStats(null).then((function(stats){var statObject={};stats&&stats.forEach((function(report){report&&(void 0===statObject[report.type]&&(statObject[report.type]=[]),statObject[report.type].push(report))})),resolve(statObject)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)})):reject(constants.ERROR_INFO.CAN_NOT_GET_STATS)}))},exports={state:function(){return connection.signalingState},createOffer:function(options){return new Promise((function(resolve,reject){var hasAudio=!0,hasVideo=!0;localVideo?(localVideo.srcObject.getAudioTracks()[0]||(hasAudio=!1),localVideo.srcObject.getVideoTracks()[0]||(hasVideo=!1,options.receiveVideo=!1)):"safari"!=browserDetails.browser||connection.getTransceivers().length||(options.receiveAudio&&connection.addTransceiver("audio",{direction:"recvonly"}),options.receiveVideo&&connection.addTransceiver("video",{direction:"recvonly"}));var constraints={offerToReceiveAudio:options.receiveAudio?1:0,offerToReceiveVideo:options.receiveVideo?1:0};connection.createOffer(constraints).then((function(offer){options.stereo&&(offer.sdp=offer.sdp.replace("minptime=10","minptime=10;stereo=1;sprop-stereo=1")),connection.setLocalDescription(offer).then((function(){var o={};o.sdp=util.stripCodecs(offer.sdp,options.stripCodecs),o.hasAudio=hasAudio,o.hasVideo=hasVideo,resolve(o)}))}))}))},createAnswer:function(options){return new Promise((function(resolve,reject){connection.createAnswer().then((function(answer){connection.setLocalDescription(answer).then((function(){resolve(util.stripCodecs(answer.sdp,options.stripCodecs))}))}))}))},setRemoteSdp:function(sdp){return logger.debug("webrtc","setRemoteSDP:"),logger.debug("webrtc",sdp),new Promise((function(resolve,reject){var sdpType;sdpType="have-local-offer"==connection.signalingState?"answer":"offer";var rtcSdp=new RTCSessionDescription({type:sdpType,sdp:sdp});connection.setRemoteDescription(rtcSdp).then((function(){browserDetails.browser,resolve()})).catch((function(error){reject(error)}))}))},changeAudioCodec:function(codec){return!1},close:function(cacheCamera){remoteVideo&&(removeVideoElement(remoteVideo),options.remoteVideo||(remoteVideo.id=remoteVideo.id+"-REMOTE_CACHED_VIDEO"),remoteVideo=null),localVideo&&!getCacheInstance(localDisplay||display)&&cacheCamera?(localVideo.id=localVideo.id+"-LOCAL_CACHED_VIDEO",unmuteAudio(),unmuteVideo(),localVideo=null):localVideo&&(localVideo.id=localVideo.id+"-LOCAL_CACHED_VIDEO",removeVideoElement(localVideo),localVideo=null),"closed"!==connection.signalingState&&connection.close(),delete connections[id]},setAudioOutputId:function(id){if(remoteVideo){if("edge"==browserDetails.browser){var srcObject=remoteVideo.srcObject;remoteVideo.srcObject=null;var res=remoteVideo.setSinkId(id);return remoteVideo.srcObject=srcObject,res}return remoteVideo.setSinkId(id)}},setVolume:function(volume){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.volume=volume/100)},unmuteRemoteAudio:function(){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.muted=!1)},muteRemoteAudio:function(){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.muted=!0)},isRemoteAudioMuted:function(){return!(remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0)||remoteVideo.muted},setMicrophoneGain:function(volume){microphoneGain&&(microphoneGain.gain.value=volume/100)},getVolume:function(){return remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0?100*remoteVideo.volume:-1},muteAudio:function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0&&(localVideo.srcObject.getAudioTracks()[0].enabled=!1)}};exports.unmuteAudio=unmuteAudio,exports.isAudioMuted=function(){return!(localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0)||!localVideo.srcObject.getAudioTracks()[0].enabled},exports.muteVideo=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0&&(localVideo.srcObject.getVideoTracks()[0].enabled=!1)},exports.unmuteVideo=unmuteVideo,exports.isVideoMuted=function(){return!(localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0)||!localVideo.srcObject.getVideoTracks()[0].enabled},exports.getStats=getStat,exports.fullScreen=function(){var video=document.getElementById(id);if(video)if(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else if(video.requestFullscreen){var result=video.requestFullscreen();util.isPromise(result)&&result.catch((function(e){logger.debug("webrtc",e)}))}else if(video.msRequestFullscreen)video.msRequestFullscreen();else if(video.mozRequestFullScreen)video.mozRequestFullScreen();else if(video.webkitRequestFullscreen)video.webkitRequestFullscreen();else if(video.webkitEnterFullscreen){video.webkitEnterFullscreen();var needRestart=!1;video.addEventListener("pause",(function(){needRestart&&(video.play(),needRestart=!1)})),video.addEventListener("webkitendfullscreen",(function(){video.play(),needRestart=!0}))}},exports.switchCam=function(deviceId){return new Promise((function(resolve,reject){localVideo&&localVideo.srcObject&&videoCams.length>1&&!customStream&&!screenShare?connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){var cameraId;sender.track.stop(),"undefined"!=typeof deviceId?(videoCams.forEach((function(cam,index){deviceId===cam.id&&(switchCamIndex=index)})),cameraId=deviceId):(switchCamIndex=(switchCamIndex+1)%videoCams.length,cameraId=videoCams[switchCamIndex].id),cameraId||(logger.error("webrtc","Can't detect camera to switch to"),reject(constants.ERROR_INFO.CAN_NOT_SWITCH_CAM));var clonedConstraints=Object.assign({},constraints);clonedConstraints.video.deviceId={exact:cameraId},clonedConstraints.audio=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){var newVideoTrack=newStream.getVideoTracks()[0];newVideoTrack.enabled=localVideo.srcObject.getVideoTracks()[0].enabled;var audioTrack=localVideo.srcObject.getAudioTracks()[0];sender.replaceTrack(newVideoTrack),localVideo.srcObject=newStream,0==localVideo.srcObject.getAudioTracks().length&&audioTrack&&localVideo.srcObject.addTrack(audioTrack),logger.info("webrtc","Switch camera to "+cameraId),resolve(cameraId)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SWITCH_CAM)}))},exports.switchMic=function(deviceId){return new Promise((function(resolve,reject){localVideo&&localVideo.srcObject&&mics.length>1&&!customStream?connection.getSenders().forEach((function(sender){if("video"!==sender.track.kind){switchMicCount=(switchMicCount+1)%mics.length,sender.track.stop(),microphoneGain&&microphoneGain.release();var mic="undefined"!=typeof deviceId?deviceId:mics[switchMicCount].id,clonedConstraints=Object.assign({},constraints);clonedConstraints.audio.deviceId={exact:mic},clonedConstraints.video=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){if(microphoneGain){var currentGain=microphoneGain.gain.value;(microphoneGain=createGainNode(newStream)).gain.value=currentGain}var newAudioTrack=newStream.getAudioTracks()[0];newAudioTrack.enabled=localVideo.srcObject.getAudioTracks()[0].enabled,currentAudioTrack=newAudioTrack;var videoTrack=localVideo.srcObject.getVideoTracks()[0];if(systemSoundTrack){var mixedTrack=mixAudioTracks(new MediaStream([newAudioTrack]),new MediaStream([systemSoundTrack]));mixedTrack.enabled=newAudioTrack.enabled,sender.replaceTrack(mixedTrack),localVideo.srcObject=new MediaStream([mixedTrack])}else sender.replaceTrack(newAudioTrack),localVideo.srcObject=newStream;videoTrack&&localVideo.srcObject.addTrack(videoTrack),logger.info("webrtc","Switch mic to "+mic),resolve(mic)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SWITCH_MIC)}))},exports.switchToScreen=function(source,woExtension){return new Promise((function(resolve,reject){if(!screenShare){var clonedConstraints={video:Object.assign({},constraints.video),audio:Object.assign({},constraints.audio)};if("firefox"===browserDetails.browser&&(clonedConstraints.video.mediaSource=source),woExtension)return void getScreenDeviceIdWoExtension(clonedConstraints).then((function(screenSharingConstraints){navigator.mediaDevices.getDisplayMedia(screenSharingConstraints).then((function(stream){processScreenStream(stream,resolve)})).catch(reject)}));getScreenDeviceId(clonedConstraints).then((function(screenSharingConstraints){clonedConstraints.sourceId=screenSharingConstraints.sourceId,screenSharingConstraints.audioMandatory?clonedConstraints.audio={mandatory:screenSharingConstraints.audioMandatory,optional:[]}:delete clonedConstraints.audio,"firefox"==browserDetails.browser?clonedConstraints.video=screenSharingConstraints:"chrome"==browserDetails.browser&&(delete clonedConstraints.video,clonedConstraints.video={mandatory:screenSharingConstraints.mandatory}),navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(stream){processScreenStream(stream,resolve)})).catch((function(reason){logger.error(reason),reject(reason)}))})).catch((function(reason){logger.error(reason),reject(reason)}))}}))},exports.switchToCam=function(){screenShare&&connection.getSenders().forEach((function(sender){"audio"!==sender.track.kind&&(currentVideoTrack.enabled=sender.track.enabled,sender.track.stop(),localVideo.srcObject=new MediaStream([currentVideoTrack]),sender.replaceTrack(currentVideoTrack),currentAudioTrack&&connection.getSenders().forEach((function(sender){"video"!==sender.track.kind&&(systemSoundTrack&&(currentAudioTrack.enabled=sender.track.enabled,sender.track.stop(),systemSoundTrack.stop(),systemSoundTrack=null,sender.replaceTrack(currentAudioTrack)),localVideo.srcObject.addTrack(currentAudioTrack))})))})),logger.info("webrtc","Switch to cam"),screenShare=!1},exports.setPublishingBitrate=function(minBitrate,maxBitrate){updateVideoSettings({maxBitrate:maxBitrate})},exports.updateVideoSettings=updateVideoSettings,exports.updateVideoResolution=function(resolution){return new Promise((function(resolve,reject){connection&&localVideo&&localVideo.srcObject&&!customStream&&resolution?connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){sender.track.stop();var clonedConstraints=Object.assign({},constraints);resolution.width&&(clonedConstraints.video.width={ideal:resolution.width}),resolution.height&&(clonedConstraints.video.height={ideal:resolution.height}),clonedConstraints.audio=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){var newVideoTrack=newStream.getVideoTracks()[0];newVideoTrack.enabled=localVideo.srcObject.getVideoTracks()[0].enabled;var audioTrack=localVideo.srcObject.getAudioTracks()[0];sender.replaceTrack(newVideoTrack),localVideo.srcObject=newStream,0==localVideo.srcObject.getAudioTracks().length&&audioTrack&&localVideo.srcObject.addTrack(audioTrack),logger.info("webrtc","Set video constraints to "+JSON.stringify(clonedConstraints.video)),resolve(clonedConstraints.video)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SET_RESOLUTION)}))},exports.getZoomCapabilities=function(){if(localVideo&&localVideo.srcObject)if(constraints.video&&constraints.video.zoom){var track=_slicedToArray(localVideo.srcObject.getVideoTracks(),1)[0],capabilities=track.getCapabilities(),settings=track.getSettings();"zoom"in settings?zoom={min:capabilities.zoom.min,max:capabilities.zoom.max,step:capabilities.zoom.step,value:settings.zoom}:(logger.info("webrtc","Zoom is not supported by "+track.label),zoom=null)}else zoom=null;return zoom},exports.setZoom=setZoom,exports.getZoom=function(){return zoom?zoom.value:-1},exports.getWebRTCStats=getWebRTCStats,connections[id]=exports,resolve(exports)}))},getMediaAccess:function(constraints,display,disableConstraintsNormalization,useCanvas){return new Promise((function(resolve,reject){constraints||(constraints=defaultConstraints),disableConstraintsNormalization||(constraints=function(constraints){var customStream=constraints.customStream;if((constraints=JSON.parse(JSON.stringify(constraints))).customStream=customStream,constraints.video&&(!0===constraints.video&&(constraints.video={}),"object"===_typeof(constraints.video))){var width=constraints.video.width,height=constraints.video.height;if("safari"==browserDetails.browser?width&&height?"object"===_typeof(width)&&"object"===_typeof(height)||(constraints.video.width={min:width,max:width},constraints.video.height={min:height,max:height}):(constraints.video.width={min:320,max:640},constraints.video.height={min:180,max:360}):(isNaN(width)||0===width||isNaN(height)||0===height)&&(constraints.video.width=320,constraints.video.height=240),"chrome"===browserDetails.browser&&browserDetails.version>=134);else{var frameRate=constraints.video.frameRate&&0!=constraints.video.frameRate?constraints.video.frameRate:30;constraints.video.frameRate={ideal:frameRate}}}constraints.audio&&constraints.audio.stereo&&(constraints.audio.echoCancellation=!1,constraints.audio.googEchoCancellation=!1);return constraints}(constraints));var cacheInstance=getCacheInstance(display);if(cacheInstance&&cacheInstance.srcObject&&JSON.stringify(display.mediaTrackConstraints)==JSON.stringify(constraints)&&!constraints.customStream)resolve(display);else if(display.mediaTrackConstraints=constraints,releaseMedia(display),constraints.video||constraints.audio||constraints.customStream)if(constraints.video&&constraints.video.type&&"screen"==constraints.video.type){if(delete constraints.video.type,screenCaptureSupportedBrowsers()&&constraints.video.withoutExtension)return void getScreenDeviceIdWoExtension(constraints).then((function(screenSharingConstraints){!function(constraints,requestAudioConstraints){navigator.mediaDevices.getDisplayMedia(constraints).then((function(stream){loadVideo(display,stream,!0,requestAudioConstraints,resolve,constraints)})).catch(reject)}(screenSharingConstraints,constraints.audio)}));var requestAudioConstraints=null;getScreenDeviceId(constraints).then((function(screenSharingConstraints){for(var prop in constraints.sourceId=screenSharingConstraints.sourceId,requestAudioConstraints=constraints.audio,screenSharingConstraints.audioMandatory?constraints.audio={mandatory:screenSharingConstraints.audioMandatory,optional:[]}:window.chrome&&(constraints.audio=!1),delete screenSharingConstraints.audioMandatory,delete screenSharingConstraints.sourceId,screenSharingConstraints)screenSharingConstraints.hasOwnProperty(prop)&&(constraints.video[prop]=screenSharingConstraints[prop]);"chrome"==browserDetails.browser&&(delete constraints.video.frameRate,delete constraints.video.height,delete constraints.video.width,delete constraints.systemSound),getAccess(constraints,!0,requestAudioConstraints)}),reject)}else getAccess(constraints);else resolve(display);function getAccess(constraints,screenShare,requestAudioConstraints){if(logger.info("webrtc",constraints),constraints.customStream)if(constraints.audio||constraints.video){var normalizedConstraints={audio:!!constraints.audio&&constraints.audio,video:!!constraints.video&&constraints.video};navigator.getUserMedia(normalizedConstraints,(function(stream){stream.getTracks().forEach((function(track){constraints.customStream.addTrack(track)})),loadVideo(display,constraints.customStream,screenShare,requestAudioConstraints,resolve,constraints)}),reject)}else loadVideo(display,constraints.customStream,screenShare,requestAudioConstraints,resolve,constraints);else listDevices(!1).then((function(devices){devices.video.forEach((function(device){videoCams.find((function(cam){return device.id===cam.id}))||videoCams.push(device)})),devices.audio.forEach((function(device){mics.find((function(mic){return device.id===mic.id}))||mics.push(device)})),navigator.getUserMedia(constraints,(function(stream){loadVideo(display,stream,screenShare,requestAudioConstraints,resolve,constraints,useCanvas)}),reject)}),reject)}}))},releaseMedia:releaseMedia,listDevices:listDevices,playFirstSound:function(){if(audioContext){for(var buffer=audioContext.createBuffer(1,441,44100),output=buffer.getChannelData(0),i=0;i<output.length;i++)output[i]=0;var source=audioContext.createBufferSource();return source.buffer=buffer,source.connect(audioContext.destination),source.start?source.start(0):source.play?source.play(0):source.noteOn&&source.noteOn(0),!0}return!1},playFirstVideo:function(display,isLocal,src){var useControls=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new Promise((function(resolve,reject){if(!getCacheInstance(display)){var video=createVideoElement(useControls);if(video.muted=!0,video.id=uuid_v1()+(isLocal?"-LOCAL_CACHED_VIDEO":"-REMOTE_CACHED_VIDEO"),src)return video.src=src,void video.play().then((function(){display.appendChild(video),video.removeAttribute("src"),resolve()})).catch((function(){logger.info("webrtc","Autoplay detected! Trying to play a video with a muted sound..."),video.muted=!0,video.play().then((function(){display.appendChild(video),video.removeAttribute("src"),resolve()})),video.onsuspend=function(event){reject()}}))}resolve()}))},available:function(){return"getUserMedia"in navigator&&"RTCPeerConnection"in window},configure:function(configuration){extensionId=configuration.extensionId,defaultConstraints=configuration.constraints,audioContext=configuration.audioContext,logger=configuration.logger,createMicGainNode="undefined"==typeof configuration.createMicGainNode||configuration.createMicGainNode,logger.info("webrtc","Initialized")},videoCams:videoCams,mics:mics,getAudioSourceDevice:function(){return audioSourceDevice},getCacheInstance:getCacheInstance,getVideoElement:function getVideoElement(display){if(display){var _step,_iterator=function(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function(){};return{s:F,n:function(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}(display.children);try{for(_iterator.s();!(_step=_iterator.n()).done;){var child=_step.value;if("video"===child.tagName.toLowerCase())return child;var grandchild=getVideoElement(child);if(grandchild)return grandchild}}catch(err){_iterator.e(err)}finally{_iterator.f()}}return null}}},{"./constants":39,"./util":42,uuid:8,"webrtc-adapter":23}]},{},[40])(40)}));