@voicenter-team/opensips-js 1.0.93 → 1.0.94
Sign up to get free protection for your applications and to get access to all the features.
package/dist/opensips-js.umd.js
CHANGED
@@ -155,4 +155,4 @@ a=accept-types:text/plain text/html
|
|
155
155
|
a=path:${s.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
|
156
156
|
`),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new ro(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:_=>{this.onTransportError(),console.log(_)},onAuthenticated:_=>{this._request=_},onReceiveResponse:_=>{this._receiveInviteResponse(_),console.log("dialog af",this._dialog),_.status_code===200&&(_.parseSDP(!0),this._status=Ie.STATUS_CONFIRMED,this.target_addr=_.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ie.STATUS_INVITE_SENT}terminate(s={}){console.log("terminate",this);const i=s.cause||F.causes.BYE,l=$e.cloneArray(s.extraHeaders),o=s.body;let _,e=s.status_code,p=s.reason_phrase;if(this._status===Ie.STATUS_TERMINATED)throw new xs.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ie.STATUS_NULL:case Ie.STATUS_INVITE_SENT:case Ie.STATUS_1XX_RECEIVED:if(e&&(e<200||e>=700))throw new TypeError(`Invalid status_code: ${e}`);e&&(p=p||F.REASON_PHRASE[e]||"",_=`SIP ;cause=${e} ;text="${p}"`),this._status===Ie.STATUS_NULL||this._status===Ie.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=_):this._status===Ie.STATUS_1XX_RECEIVED&&this._request.cancel(_),this._status=Ie.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,F.causes.CANCELED);break;case Ie.STATUS_WAITING_FOR_ANSWER:case Ie.STATUS_ANSWERED:if(e=e||480,console.log("REPLY 480"),e<300||e>=700)throw new TypeError(`Invalid status_code: ${e}`);this._request.reply(e,p,l,o),console.log("failed 2"),this._failed("local",null,F.causes.REJECTED);break;case Ie.STATUS_WAITING_FOR_ACK:case Ie.STATUS_CONFIRMED:if(p=s.reason_phrase||F.REASON_PHRASE[e]||"",e&&(e<200||e>=700))throw new TypeError(`Invalid status_code: ${e}`);if(e&&l.push(`Reason: SIP ;cause=${e}; text="${p}"`),this._status===Ie.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==jt.C.STATUS_TERMINATED){const g=this._dialog;this.receiveRequest=({method:n})=>{n===F.ACK&&(this.sendRequest(F.BYE,{extraHeaders:l,body:o}),g.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===jt.C.STATUS_TERMINATED&&(this.sendRequest(F.BYE,{extraHeaders:l,body:o}),g.terminate())}),this._ended("local",null,i),this._dialog=g,this._ua.newDialog(g)}else console.log("here it is"),this.sendRequest(F.BYE,{extraHeaders:l,body:o}),this._ended("local",null,i)}}sendRequest(s,i){return this._dialog.sendRequest(s,i)}authenticate(s){this.status="auth";let i=new Jn("");i.method="AUTH",i.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),i.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),s&&i.addHeader("Authorization",s.toString());let l=i.toString();console.log(l);let o=[];for(var _=0;_<l.length;_++)o.push(l.charCodeAt(_).toString(16));console.log(o),this._connection.send(i.toString())}onmessage(s){console.log("onmessage",s);const i=new Jn(s.data);if(this.status==="auth"&&i.code===401){const l=this.parseAuth(i.getHeader("WWW-Authenticate")),o=new wm(this.credentials);o.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},l,$e.createRandomToken(12)),this.authenticate(o)}this.status==="auth"&&i.code===200&&this._direction==="outgoing"?(this.my_addr.push(i.getHeader("To-Path")),this.my_addr.push(i.getHeader("Use-Path")),this.status="active",this.inviteParty(i)):this.status==="auth"&&i.code===200&&this._direction==="incoming"?(this.my_addr.push(i.getHeader("To-Path")),this.my_addr.push(i.getHeader("Use-Path")),this.status="active",this.acceptParty(i),this.emit("confirmed")):i.method==="SEND"&&(this._sendOk(i),this._sendReport(i),i.direction="incoming",this.emit("newMessage",i),this._msgHistory.push(i),this.emit("msgHistoryUpdate",this._msgHistory),console.log("======================================================================")),i.code===480&&this._close()}onclose(){console.log("close")}onopen(){const s=new RTCPeerConnection({iceServers:[]});s.createDataChannel(""),s.createOffer().then(s.setLocalDescription.bind(s)),s.onicecandidate=i=>{if(!i||!i.candidate||!i.candidate.candidate)return;const l=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,o=i.candidate.candidate.match(l);this.my_ip=o&&o[1],s.onicecandidate=()=>{},this.authenticate(null)}}onerror(s){console.log(s)}_receiveInviteResponse(s){if(console.log("resp0000000000000",s),this._dialog&&s.status_code>=200&&s.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===s.call_id&&this._dialog.id.local_tag===s.from_tag&&this._dialog.id.remote_tag===s.to_tag){this.sendRequest(F.ACK);return}else{const i=new oo(this,s,"UAC");if(i.error!==void 0){console.log(i.error);return}this.sendRequest(F.ACK),this.sendRequest(F.BYE);return}if(this._is_canceled){s.status_code>=100&&s.status_code<200?this._request.cancel(this._cancel_reason):s.status_code>=200&&s.status_code<299&&this._acceptAndTerminate(s);return}if(!(this._status!==Ie.STATUS_INVITE_SENT&&this._status!==Ie.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(s.status_code):this._status=Ie.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(s.status_code):{if(!s.to_tag){console.log("1xx response received without to tag");break}if(s.hasHeader("contact")&&!this._createDialog(s,"UAC",!0))break;if(this._status=Ie.STATUS_1XX_RECEIVED,!s.body){this._progress("remote",s);break}const i={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",i);const l=new RTCSessionDescription({type:"answer",sdp:i.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>this._progress("remote",s)).catch(o=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)});break}case/^2[0-9]{2}$/.test(s.status_code):{if(console.log("maybe here???"),this._status=Ie.STATUS_CONFIRMED,!s.body){this._acceptAndTerminate(s,400,F.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",s,F.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(s,"UAC"))break;const i={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",i),new RTCSessionDescription({type:"answer",sdp:i.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(l=>this._connection.setLocalDescription(l)).catch(l=>{this._acceptAndTerminate(s,500,l.toString()),console.log("failed 4"),this._failed("local",s,F.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(s),this._accepted("remote",s),this.sendRequest(F.ACK),this._confirmed("local",null)});break}default:{const i=$e.sipErrorCause(s.status_code);console.log("failed 5"),this._failed("remote",s,i)}}}sendMSRP(s){const i=new Jn("");i.method="SEND",i.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),i.addHeader("From-Path",`${this.my_addr[0]}`),i.addHeader("Message-ID",$e.createRandomToken(10)),i.addHeader("Byte-Range","1-25/25"),i.addHeader("Content-Type","text/plain"),i.addHeader("Success-Report","yes"),i.addHeader("Failure-Report","yes"),i.body=s;let l=i.toString();console.log(l);let o=[];for(var _=0;_<l.length;_++)o.push(l.charCodeAt(_).toString(16));console.log(o),this._connection.send(i.toString()),i.direction="outgoing",this.emit("newMessage",i),this._msgHistory.push(i),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(s){let i=s.ident,l=s.getHeader("Message-ID"),o=new Jn("");o.method="200 OK",o.addHeader("To-Path",`${this.my_addr[1]}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",l),o.ident=i;let _=o.toString();console.log(_);let e=[];for(var p=0;p<_.length;p++)e.push(_.charCodeAt(p).toString(16));console.log(e),this._connection.send(o.toString())}_sendReport(s){let i=s.ident,l=s.getHeader("Message-ID"),o=new Jn("");o.method="REPORT",o.addHeader("To-Path",`${s.getHeader("From-Path")}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",l),o.addHeader("Byte-Range","1-25/25"),o.addHeader("Status","000 200 OK"),o.ident=i;let _=o.toString();console.log(_);let e=[];for(var p=0;p<_.length;p++)e.push(_.charCodeAt(p).toString(16));console.log(e),this._connection.send(o.toString())}parseAuth(s){const i={},l=s.replace("Digest","").split(",");for(const o of l){const _=o.trim().split("=");i[_[0]]=_[1].match('^"(.+)"$')[1]}return i}init_incoming(s,i){let l;const o=s.hasHeader("Content-Type")?s.getHeader("Content-Type").toLowerCase():void 0;if(s.body&&o!=="application/sdp"){s.reply(415);return}if(this._status=Ie.STATUS_INVITE_RECEIVED,this._from_tag=s.from_tag,this._id=s.call_id+this._from_tag,this._request=s,this._contact=this._ua.contact.toString(),s.hasHeader("expires")&&(l=s.getHeader("expires")*1e3),s.to_tag=$e.newTag(),!this._createDialog(s,"UAS",!0)){s.reply(500,"Missing Contact header field");return}s.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ie.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{s.reply(408),console.log("failed 6"),this._failed("local",null,F.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ie.STATUS_WAITING_FOR_ANSWER&&(s.reply(487),console.log("failed 7"),this._failed("system",null,F.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from,i&&i(this),s.parseSDP(!0),this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",s),this._status!==Ie.STATUS_TERMINATED&&(s.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(s,i,l){this.emit("_failed",{originator:s,message:i||null,cause:l}),this._close(),this.emit("failed",{originator:s,message:i||null,cause:l})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ie.STATUS_TERMINATED){if(this._status=Ie.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(s){console.log("close() | error closing the RTCPeerConnection: %o",s)}for(const s in this._timers)Object.prototype.hasOwnProperty.call(this._timers,s)&&clearTimeout(this._timers[s]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const s in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,s)&&(this._earlyDialogs[s].terminate(),delete this._earlyDialogs[s]);for(const s in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,s)&&delete this._referSubscribers[s];this._ua.destroyMSRPSession(this)}}_createDialog(s,i,l){const o=i==="UAS"?s.to_tag:s.from_tag,_=i==="UAS"?s.from_tag:s.to_tag,e=s.call_id+o+_;let p=this._earlyDialogs[e];if(l)return p?!0:(p=new oo(this,s,i,oo.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",s,F.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[e]=p,!0));{if(this._from_tag=s.from_tag,this._to_tag=s.to_tag,p)return p.update(s,i),this._dialog=p,delete this._earlyDialogs[e],!0;const g=new oo(this,s,i);return g.error?(console.log("failed 9"),this._failed("remote",s,F.causes.INTERNAL_ERROR),!1):(this._dialog=g,!0)}}_newMSRPSession(s,i){this._ua.newMSRPSession(this,{originator:s,session:this,request:i})}_progress(s,i){this.emit("progress",{originator:s,response:i||null})}isEnded(){switch(this._status){case Ie.STATUS_CANCELED:case Ie.STATUS_TERMINATED:return!0;default:return!1}}_accepted(s,i){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:s,response:i||null})}_confirmed(s,i){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:s,ack:i||null})}_ended(s,i,l){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:s,message:i||null,cause:l})}_handleSessionTimersInIncomingResponse(s){if(!this._sessionTimers.enabled)return;let i;s.session_expires&&s.session_expires>=F.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=s.session_expires,i=s.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,i="uac"),this._sessionTimers.refresher=i==="uac",this._runSessionTimer()}receiveRequest(s){if(console.log("receiveRequest()"),s.method===F.CANCEL)(this._status===Ie.STATUS_WAITING_FOR_ANSWER||this._status===Ie.STATUS_ANSWERED)&&(this._status=Ie.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",s,F.causes.CANCELED));else switch(s.method){case F.ACK:if(this._status!==Ie.STATUS_WAITING_FOR_ACK)return;if(this._status=Ie.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!s.body){this.terminate({cause:F.causes.MISSING_SDP,status_code:400});break}const i={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",i);const l=new RTCSessionDescription({type:"answer",sdp:i.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",s)}).catch(o=>{this.terminate({cause:F.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)})}else this._is_confirmed||this._confirmed("remote",s);break;case F.BYE:this._status===Ie.STATUS_CONFIRMED||this._status===Ie.STATUS_WAITING_FOR_ACK?(s.reply(200),this._ended("remote",s,F.causes.BYE)):this._status===Ie.STATUS_INVITE_RECEIVED||this._status===Ie.STATUS_WAITING_FOR_ANSWER?(s.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",s,F.causes.BYE)):s.reply(403,"Wrong Status");break;case F.INVITE:this._status===Ie.STATUS_CONFIRMED?s.hasHeader("replaces")?this._receiveReplaces(s):this._receiveReinvite(s):s.reply(403,"Wrong Status");break;case F.INFO:this._status===Ie.STATUS_1XX_RECEIVED||this._status===Ie.STATUS_WAITING_FOR_ANSWER||this._status===Ie.STATUS_ANSWERED||this._status===Ie.STATUS_WAITING_FOR_ACK||this._status===Ie.STATUS_CONFIRMED?(s.hasHeader("Content-Type")?s.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new cu(this).init_incoming(s):s.reply(415):s.reply(403,"Wrong Status");break;case F.UPDATE:this._status===Ie.STATUS_CONFIRMED?this._receiveUpdate(s):s.reply(403,"Wrong Status");break;case F.REFER:this._status===Ie.STATUS_CONFIRMED?this._receiveRefer(s):s.reply(403,"Wrong Status");break;case F.NOTIFY:this._status===Ie.STATUS_CONFIRMED?this._receiveNotify(s):s.reply(403,"Wrong Status");break;default:s.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ie.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:F.causes.CONNECTION_ERROR,cause:F.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ie.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:F.causes.REQUEST_TIMEOUT,cause:F.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ie.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:F.causes.DIALOG_ERROR,cause:F.causes.DIALOG_ERROR})}}var gT=Wt();const Ou=ke(gT),Eo=new eo("Parser"),TT=(c,s)=>{let i,l,o=c.indexOf(`\r
|
157
157
|
`);if(o===-1){Eo.warn("parseMessage() | no CRLF found, not a SIP message");return}const _=c.substring(0,o);let e=Ou.parse(_,"Request_Response");if(e===-1){Eo.warn(`parseMessage() | error parsing first line of SIP message: "${_}"`);return}else e.status_code?(i=new un.IncomingResponse,i.status_code=e.status_code,i.reason_phrase=e.reason_phrase):(i=new un.IncomingRequest(s),i.method=e.method,i.ruri=e.uri);i.data=c;let p=o+2;for(;;){if(o=vT(c,p),o===-2){l=p+2;break}else if(o===-1){Eo.warn("parseMessage() | malformed message");return}if(e=ET(i,c,p,o),e!==!0){Eo.warn("parseMessage() |",e.error);return}p=o+2}if(i.hasHeader("content-length")){const g=i.getHeader("content-length");i.body=c.substr(l,g)}else i.body=c.substring(l);return i};function vT(c,s){let i=s,l=0,o=0;if(c.substring(i,i+2).match(/(^\r\n)/))return-2;for(;l===0;){if(o=c.indexOf(`\r
|
158
|
-
`,i),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?i=o+2:l=o}return l}function ET(c,s,i,l){let o;const _=s.indexOf(":",i),e=s.substring(i,_).trim(),p=s.substring(_+1,l).trim();switch(e.toLowerCase()){case"via":case"v":c.addHeader("via",p),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",p),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",p),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=Ou.parse(p,"Record_Route"),o===-1)o=void 0;else for(const g of o)c.addHeader("record-route",p.substring(g.possition,g.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=g.parsed;break;case"call-id":case"i":c.setHeader("call-id",p),o=c.parseHeader("call-id"),o&&(c.call_id=p);break;case"contact":case"m":if(o=Ou.parse(p,"Contact"),o===-1)o=void 0;else for(const g of o)c.addHeader("contact",p.substring(g.possition,g.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=g.parsed;break;case"content-length":case"l":c.setHeader("content-length",p),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",p),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",p),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof un.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",p),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",p),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",p),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",p),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",p),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",p),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",p),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(e,p),o=0}return o===void 0?{error:`error parsing header "${e}"`}:!0}const ST={parseMessage:TT},Yr=new eo("Registrator"),So=10;class yT{constructor(s,i){this._reg_id=1,this._ua=s,this._transport=i,this._registrar=s.configuration.registrar_server,this._expires=s.configuration.register_expires,this._call_id=vs.createRandomToken(22),this._cseq=0,this._to_uri=s.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const l=this._contact.indexOf(">");if(l!==-1){const o=this._contact.slice(0,l)+this._contact.slice(l+1,this._contact.length);this._contact=o}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(s){Array.isArray(s)||(s=[]),this._extraHeaders=s.slice()}setExtraContactParams(s){s instanceof Object||(s={}),this._extraContactParams="";for(const i in s)if(Object.prototype.hasOwnProperty.call(s,i)){const l=s[i];this._extraContactParams+=`;${i}`,l&&(this._extraContactParams+=`=${l}`)}}setExtraContactUriParams(s){s instanceof Object||(s={}),this._extraContactParams="";for(const i in s)if(Object.prototype.hasOwnProperty.call(s,i)){const l=s[i];this._extraContactParams+=`;${i}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){Yr.debug("Register request in progress...");return}const s=this._extraHeaders.slice();s.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),s.push(`Expires: ${this._expires}`);const i=new bt.OutgoingRequest(F.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},s),l=new ro(this._ua,i,{onRequestTimeout:()=>{this._registrationFailure(null,F.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,F.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:o=>{if(o.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):{if(this._registering=!1,!o.hasHeader("Contact")){Yr.debug("no Contact header in response to REGISTER, response ignored");break}const _=o.headers.Contact.reduce((n,v)=>n.concat(v.parsed),[]);let e=_.find(n=>this._sipInstance===n.getParam("+sip.instance")&&this._reg_id===parseInt(n.getParam("reg-id")));if(e||(e=_.find(n=>n.uri.user===this._ua.contact.uri.user)),!e){Yr.debug("no Contact header pointing to us, response ignored");break}let p=e.getParam("expires");!p&&o.hasHeader("expires")&&(p=o.getHeader("expires")),p||(p=this._expires),p=Number(p),p<So&&(p=So);const g=p>64?p*1e3/2+Math.floor((p/2-32)*1e3*Math.random()):p*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},g),e.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=e.getParam("temp-gruu").replace(/"/g,"")),e.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=e.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:o}));break}case/^423$/.test(o.status_code):{o.hasHeader("min-expires")?(this._expires=Number(o.getHeader("min-expires")),this._expires<So&&(this._expires=So),this.register()):(Yr.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(o,F.causes.SIP_FAILURE_CODE));break}default:{const _=vs.sipErrorCause(o.status_code);this._registrationFailure(o,_)}}}});this._registering=!0,l.send()}unregister(s={}){if(!this._registered){Yr.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const i=this._extraHeaders.slice();s.all?i.push(`Contact: *${this._extraContactParams}`):i.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),i.push("Expires: 0");const l=new bt.OutgoingRequest(F.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},i);new ro(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,F.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,F.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:_=>{switch(!0){case/^1[0-9]{2}$/.test(_.status_code):break;case/^2[0-9]{2}$/.test(_.status_code):this._unregistered(_);break;default:{const e=vs.sipErrorCause(_.status_code);this._unregistered(_,e)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(s,i){this._registering=!1,this._ua.registrationFailed({response:s||null,cause:i}),this._registered&&(this._registered=!1,this._ua.unregistered({response:s||null,cause:i}))}_unregistered(s,i){this._registering=!1,this._registered=!1,this._ua.unregistered({response:s||null,cause:i||null})}}const _t=console,$s={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},AT=uT;class CT extends AT{constructor(s){super(s),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this._registrator=new yT(this)}call(s,i){return super.call(s,i)}joinVideoCall(s,i,l){_t.debug("call()");const o=new vo(this);return o.connect(s,i,l),o}_loadConfig(s){try{Kr.load(this._configuration,s)}catch(o){throw o}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=vs.newUUID()),this._configuration.jssip_id=vs.createRandomToken(5);const i=this._configuration.uri.clone();i.user=null,this._configuration.hostport_params=i.toString().replace(/^sip:/i,"");try{this._transport=new Mg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=RT.bind(this),this._transport.onconnect=IT.bind(this),this._transport.ondisconnect=bT.bind(this),this._transport.ondata=wT.bind(this)}catch(o){throw _t.warn(o),new xs.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const o=this._configuration.uri.clone();o.user=null,o.clearParams(),o.clearHeaders(),this._configuration.registrar_server=o}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Yn("sip",vs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(o={}){const _=o.anonymous||null,e=o.outbound||null;let p="<";return _?p+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":p+=this.pub_gruu||this.uri.toString(),e&&(_?!this.temp_gruu:!this.pub_gruu)&&(p+=";ob"),p+=">",p}};const l=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const o in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,o)&&(l.indexOf(o)!==-1?Object.defineProperty(this._configuration,o,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,o,{writable:!1,configurable:!1}));_t.debug("configuration parameters after validation:");for(const o in this._configuration)if(Object.prototype.hasOwnProperty.call(Kr.settings,o))switch(o){case"uri":case"registrar_server":_t.debug(`- ${o}: ${this._configuration[o]}`);break;case"password":case"ha1":case"authorization_jwt":_t.debug(`- ${o}: NOT SHOWN`);break;default:_t.debug(`- ${o}: ${JSON.stringify(this._configuration[o])}`)}}newMSRPSession(s,i){s.on("msgHistoryUpdate",l=>{console.log(l)}),this._msrp_sessions[s.id]=s,this.emit("newMSRPSession",i)}newJanusSession(s,i){this._janus_sessions[s.id]=s,this.emit("newJanusSession",i)}destroyMSRPSession(s){delete this._msrp_sessions[s.id]}destroyJanusSession(s){delete this._janus_sessions[s.id]}receiveRequest(s){var _,e,p,g;const i=s.method;if(console.log("-----------"),s.ruri.user!==this._configuration.uri.user&&s.ruri.user!==this._contact.uri.user){_t.debug("Request-URI does not point to us"),s.method!==xe.ACK&&s.reply_sl(404);return}if(s.ruri.scheme===xe.SIPS){s.reply_sl(416);return}if(jt.checkTransaction(this,s))return;if(i===xe.INVITE?new jt.InviteServerTransaction(this,this._transport,s):i!==xe.ACK&&i!==xe.CANCEL&&new jt.NonInviteServerTransaction(this,this._transport,s),i===xe.OPTIONS){if(this.listeners("newOptions").length===0){s.reply(200);return}new yf.Options(this).init_incoming(s)}else if(i===xe.MESSAGE){if(this.listeners("newMessage").length===0){s.reply(405);return}new yf.Message(this).init_incoming(s)}else if(i===xe.INVITE&&!s.to_tag&&this.listeners("newRTCSession").length===0){s.reply(405);return}let l,o;if(s.to_tag)if(l=this._findDialog(s.call_id,s.from_tag,s.to_tag),l)l.receiveRequest(s);else if(i===xe.NOTIFY)if(o=this._findSession(s),o)o.receiveRequest(s);else{if(s.body)try{const n=JSON.parse(s.body)||{};(e=(_=n.plugindata)==null?void 0:_.data)!=null&&e.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(n),(g=(p=n.plugindata)==null?void 0:p.data)!=null&&g.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(n.plugindata.data.unpublished)}catch(n){console.error(n)}s.reply(200)}else i!==xe.ACK&&s.reply(481);else switch(i){case xe.INVITE:if(window.RTCPeerConnection)if(s.hasHeader("replaces")){const n=s.replaces;l=this._findDialog(n.call_id,n.from_tag,n.to_tag),l?(o=l.owner,o.isEnded()?s.reply(603):o.receiveRequest(s)):s.reply(481)}else s.body.search(/MSRP/ig)>-1?(o=new wu(this),o.init_incoming(s)):s.body.search(/JANUS/ig)>-1||(o=new vg(this),o.init_incoming(s));else _t.warn("INVITE received but WebRTC is not supported"),s.reply(488);break;case xe.BYE:s.reply(481);break;case xe.CANCEL:o=this._findSession(s),o?o.receiveRequest(s):_t.debug("received CANCEL request for a non existent session");break;case xe.ACK:break;case xe.NOTIFY:this.emit("sipEvent",{event:s.event,request:s}),s.reply(200);break;default:s.reply(405);break}}startMSRP(s,i){_t.debug("startMSRP()",i);const l=new wu(this);return l.connect(s),l}startJanus(s,i){_t.debug("startJanus()",i);const l=new wu(this);return l.connect(s),l}terminateMSRPSessions(s){_t.debug("terminateSessions()");for(const i in this._msrp_sessions)this._msrp_sessions[i].isEnded()||this._msrp_sessions[i].terminate(s)}terminateJanusSessions(s){_t.debug("terminateSessions()");for(const i in this._janus_sessions)this._janus_sessions[i].isEnded()||this._janus_sessions[i].terminate(s)}stop(){if(_t.debug("stop()"),this._dynConfiguration={},this._status===$s.STATUS_USER_CLOSED){_t.debug("UA already closed");return}this._registrator.close();const s=Object.keys(this._sessions).length;for(const l in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,l)){_t.debug(`closing session ${l}`);try{this._sessions[l].terminate()}catch(o){console.error(o)}}for(const l in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,l)){_t.debug(`closing session ${l}`);try{this._msrp_sessions[l].terminate()}catch(o){console.error(o)}}for(const l in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,l)){_t.debug(`closing session ${l}`);try{this._janus_sessions[l].terminate()}catch(o){console.error(o)}}for(const l in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,l))try{this._applicants[l].close()}catch(o){console.error(o)}this._status=$s.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function RT(c){this.emit("connecting",c)}function IT(c){this._status!==$s.STATUS_USER_CLOSED&&(this._status=$s.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function bT(c){const s=["nict","ict","nist","ist"];for(const i of s)for(const l in this._transactions[i])Object.prototype.hasOwnProperty.call(this._transactions[i],l)&&this._transactions[i][l].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==$s.STATUS_USER_CLOSED&&(this._status=$s.STATUS_NOT_READY,this._error=$s.NETWORK_ERROR)}function wT(c){console.log("onTransportData",c);const s=c.transport;let i=c.message;if(i=ST.parseMessage(i,this),!i){console.log("if 1 return");return}if(this._status===$s.STATUS_USER_CLOSED&&i instanceof un.IncomingRequest){console.log("if 2 return");return}if(!zg(i,this,s)){console.log("if 3 return");return}if(console.log("onTransportData message",i),console.log("onTransportData instanceof",i instanceof un.IncomingRequest),i instanceof un.IncomingRequest)i.transport=s,console.log("onTransportData receiveRequest"),this.receiveRequest(i);else if(i instanceof un.IncomingResponse){let l;switch(i.method){case xe.INVITE:l=this._transactions.ict[i.via_branch],l&&l.receiveResponse(i);break;case xe.ACK:break;default:l=this._transactions.nict[i.via_branch],l&&l.receiveResponse(i);break}}}const OT=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer"],DT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function T_(c){const s={};return OT.forEach(i=>{c[i]!==void 0&&(s[i]=c[i])}),s.localHold=c._localHold,s}function v_(c){const s={};return DT.forEach(i=>{c[i]!==void 0&&(s[i]=c[i])}),s}function E_(c,s){const i=new AudioContext,l=i.createMediaStreamSource(c),o=i.createMediaStreamDestination(),_=i.createGain();return l.connect(_),_.connect(o),_.gain.value=s,o.stream}function NT(c,s,i,l){const o=document.createElement("audio");o.id=s._id,o.className="audioTag",o.srcObject=c,S_()||(o.setSinkId(i),o.volume=l),o.play(),s.audioTag=o}function UT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function S_(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const PT=ut,xT=Wt(),Pt=new PT("WebSocketInterface");var MT=class{constructor(s){Pt.debug('new() [url:"%s"]',s),this._url=s,this._sip_uri=null,this._via_transport=null,this._ws=null;const i=xT.parse(s,"absoluteURI");if(i===-1)throw Pt.warn(`invalid WebSocket URI: ${s}`),new TypeError(`Invalid argument: ${s}`);if(i.scheme!=="wss"&&i.scheme!=="ws")throw Pt.warn(`invalid WebSocket URI scheme: ${i.scheme}`),new TypeError(`Invalid argument: ${s}`);this._sip_uri=`sip:${i.host}${i.port?`:${i.port}`:""};transport=ws`,this._via_transport=i.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(s){this._via_transport=s.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Pt.debug("connect()"),this.isConnected()){Pt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Pt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Pt.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(s){this._onError(s)}}disconnect(){Pt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(s){return Pt.debug("send()"),this.isConnected()?(this._ws.send(s),!0):(Pt.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Pt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:s,code:i,reason:l}){Pt.debug(`WebSocket ${this._url} closed`),s===!1&&Pt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!s,i,l)}_onMessage({data:s}){Pt.debug("received WebSocket message"),this.ondata(s)}_onError(s){Pt.warn(`WebSocket ${this._url} error: `,s)}};const Du=pl,kT=xe,LT=Ts,$T=Tt(),HT=p_,FT=ps(),jT=Xa(),qT=Wt(),VT=MT;Hn("JsSIP")("version %s",Du.version);var BT={C:kT,Exceptions:LT,Utils:$T,UA:HT,URI:FT,NameAddrHeader:jT,WebSocketInterface:VT,Grammar:qT,debug:Hn,get name(){return Du.title},get version(){return Du.version}};const GT=ke(BT);function Nu(c){return c<10?`0${c}`:`${c}`}function WT(c){let s=c.hours||0,i=c.minutes||0,l=c.seconds||0;l++,l===60&&(l=0,i++,i===60&&(i=0,s++));const o=`${Nu(s)}:${Nu(i)}:${Nu(l)}`;return{seconds:l,minutes:i,hours:s,formatted:o}}var At={};At.forEach=async(c,s,i)=>{const l=[];for(let o=0;o<c.length;o++)if(o in c){const _=Promise.resolve(c[o]).then(e=>s.call(i||globalThis,e,o,c));l.push(_)}await Promise.all(l)},At.forEachSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)l in c&&await s.call(i||globalThis,await c[l],l,c)},At.map=async(c,s,i)=>{const l=[];for(let o=0;o<c.length;o++)o in c&&(l[o]=Promise.resolve(c[o]).then(_=>s.call(i||globalThis,_,o,c)));return Promise.all(l)},At.mapSeries=async(c,s,i)=>{const l=[];for(let o=0;o<c.length;o++)o in c&&(l[o]=await s.call(i||globalThis,await c[o],o,c));return l},At.find=(c,s,i)=>new Promise((l,o)=>{if(c.length===0)return l();let _=1;for(let e=0;e<c.length;e++){const p=g=>{g?l(c[e]):_===c.length&&l(),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(o)}}),At.findSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(await s.call(i||globalThis,await c[l],l,c))return c[l]},At.findIndex=(c,s,i)=>new Promise((l,o)=>{if(c.length===0)return l(-1);let _=1;for(let e=0;e<c.length;e++){const p=g=>{g?l(e):_===c.length&&l(-1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(o)}}),At.findIndexSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(await s.call(i||globalThis,await c[l],l,c))return l},At.some=(c,s,i)=>new Promise((l,o)=>{if(c.length===0)return l(!1);let _=1;for(let e=0;e<c.length;e++){if(!(e in c)){_++;continue}const p=g=>{g?l(!0):_===c.length&&l(!1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(o)}}),At.someSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(l in c&&await s.call(i||globalThis,await c[l],l,c))return!0;return!1},At.every=(c,s,i)=>new Promise((l,o)=>{if(c.length===0)return l(!0);let _=1;for(let e=0;e<c.length;e++){if(!(e in c)){_++;continue}const p=g=>{g?_===c.length&&l(!0):l(!1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(o)}}),At.everySeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(l in c&&!await s.call(i||globalThis,await c[l],l,c))return!1;return!0},At.filter=(c,s,i)=>new Promise(async(l,o)=>{const _=[];for(let p=0;p<c.length;p++)p in c&&(_[p]=Promise.resolve(c[p]).then(g=>s.call(i||globalThis,g,p,c)).catch(o));const e=[];for(let p=0;p<_.length;p++)await _[p]&&e.push(await c[p]);l(e)}),At.filterSeries=async(c,s,i)=>{const l=[];for(let o=0;o<c.length;o++)o in c&&await s.call(i||globalThis,await c[o],o,c)&&l.push(await c[o]);return l},At.reduce=async(c,s,i)=>{if(c.length===0&&i===void 0)throw TypeError("Reduce of empty array with no initial value");let l,o;for(i!==void 0?(o=i,l=0):(o=c[0],l=1),l;l<c.length;l++)l in c&&(o=await s(await o,await c[l],l,c));return o};var y_={};(function(c){const s=At;Object.keys(s).forEach(i=>{const l=i.charAt(0).toUpperCase()+i.slice(1);c[`async${l}`]=async function(...o){return s[i](this,...o)}})})(y_);var KT=Object.assign(At,{instanceMethods:y_});const dn=new AudioContext,Yt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var YT={exports:{}};(function(c){var s=function(i){var l=Object.prototype,o=l.hasOwnProperty,_=Object.defineProperty||function(N,z,re){N[z]=re.value},e,p=typeof Symbol=="function"?Symbol:{},g=p.iterator||"@@iterator",n=p.asyncIterator||"@@asyncIterator",v=p.toStringTag||"@@toStringTag";function S(N,z,re){return Object.defineProperty(N,z,{value:re,enumerable:!0,configurable:!0,writable:!0}),N[z]}try{S({},"")}catch{S=function(z,re,oe){return z[re]=oe}}function m(N,z,re,oe){var Te=z&&z.prototype instanceof ae?z:ae,De=Object.create(Te.prototype),Ce=new U(oe||[]);return _(De,"_invoke",{value:j(N,re,Ce)}),De}i.wrap=m;function C(N,z,re){try{return{type:"normal",arg:N.call(z,re)}}catch(oe){return{type:"throw",arg:oe}}}var A="suspendedStart",R="suspendedYield",I="executing",V="completed",W={};function ae(){}function x(){}function $(){}var Re={};S(Re,g,function(){return this});var be=Object.getPrototypeOf,H=be&&be(be(se([])));H&&H!==l&&o.call(H,g)&&(Re=H);var D=$.prototype=ae.prototype=Object.create(Re);x.prototype=$,_(D,"constructor",{value:$,configurable:!0}),_($,"constructor",{value:x,configurable:!0}),x.displayName=S($,v,"GeneratorFunction");function L(N){["next","throw","return"].forEach(function(z){S(N,z,function(re){return this._invoke(z,re)})})}i.isGeneratorFunction=function(N){var z=typeof N=="function"&&N.constructor;return z?z===x||(z.displayName||z.name)==="GeneratorFunction":!1},i.mark=function(N){return Object.setPrototypeOf?Object.setPrototypeOf(N,$):(N.__proto__=$,S(N,v,"GeneratorFunction")),N.prototype=Object.create(D),N},i.awrap=function(N){return{__await:N}};function q(N,z){function re(De,Ce,He,we){var Se=C(N[De],N,Ce);if(Se.type==="throw")we(Se.arg);else{var at=Se.arg,Ue=at.value;return Ue&&typeof Ue=="object"&&o.call(Ue,"__await")?z.resolve(Ue.__await).then(function(le){re("next",le,He,we)},function(le){re("throw",le,He,we)}):z.resolve(Ue).then(function(le){at.value=le,He(at)},function(le){return re("throw",le,He,we)})}}var oe;function Te(De,Ce){function He(){return new z(function(we,Se){re(De,Ce,we,Se)})}return oe=oe?oe.then(He,He):He()}_(this,"_invoke",{value:Te})}L(q.prototype),S(q.prototype,n,function(){return this}),i.AsyncIterator=q,i.async=function(N,z,re,oe,Te){Te===void 0&&(Te=Promise);var De=new q(m(N,z,re,oe),Te);return i.isGeneratorFunction(z)?De:De.next().then(function(Ce){return Ce.done?Ce.value:De.next()})};function j(N,z,re){var oe=A;return function(De,Ce){if(oe===I)throw new Error("Generator is already running");if(oe===V){if(De==="throw")throw Ce;return Dt()}for(re.method=De,re.arg=Ce;;){var He=re.delegate;if(He){var we=B(He,re);if(we){if(we===W)continue;return we}}if(re.method==="next")re.sent=re._sent=re.arg;else if(re.method==="throw"){if(oe===A)throw oe=V,re.arg;re.dispatchException(re.arg)}else re.method==="return"&&re.abrupt("return",re.arg);oe=I;var Se=C(N,z,re);if(Se.type==="normal"){if(oe=re.done?V:R,Se.arg===W)continue;return{value:Se.arg,done:re.done}}else Se.type==="throw"&&(oe=V,re.method="throw",re.arg=Se.arg)}}}function B(N,z){var re=z.method,oe=N.iterator[re];if(oe===e)return z.delegate=null,re==="throw"&&N.iterator.return&&(z.method="return",z.arg=e,B(N,z),z.method==="throw")||re!=="return"&&(z.method="throw",z.arg=new TypeError("The iterator does not provide a '"+re+"' method")),W;var Te=C(oe,N.iterator,z.arg);if(Te.type==="throw")return z.method="throw",z.arg=Te.arg,z.delegate=null,W;var De=Te.arg;if(!De)return z.method="throw",z.arg=new TypeError("iterator result is not an object"),z.delegate=null,W;if(De.done)z[N.resultName]=De.value,z.next=N.nextLoc,z.method!=="return"&&(z.method="next",z.arg=e);else return De;return z.delegate=null,W}L(D),S(D,v,"Generator"),S(D,g,function(){return this}),S(D,"toString",function(){return"[object Generator]"});function Q(N){var z={tryLoc:N[0]};1 in N&&(z.catchLoc=N[1]),2 in N&&(z.finallyLoc=N[2],z.afterLoc=N[3]),this.tryEntries.push(z)}function Z(N){var z=N.completion||{};z.type="normal",delete z.arg,N.completion=z}function U(N){this.tryEntries=[{tryLoc:"root"}],N.forEach(Q,this),this.reset(!0)}i.keys=function(N){var z=Object(N),re=[];for(var oe in z)re.push(oe);return re.reverse(),function Te(){for(;re.length;){var De=re.pop();if(De in z)return Te.value=De,Te.done=!1,Te}return Te.done=!0,Te}};function se(N){if(N){var z=N[g];if(z)return z.call(N);if(typeof N.next=="function")return N;if(!isNaN(N.length)){var re=-1,oe=function Te(){for(;++re<N.length;)if(o.call(N,re))return Te.value=N[re],Te.done=!1,Te;return Te.value=e,Te.done=!0,Te};return oe.next=oe}}return{next:Dt}}i.values=se;function Dt(){return{value:e,done:!0}}return U.prototype={constructor:U,reset:function(N){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(Z),!N)for(var z in this)z.charAt(0)==="t"&&o.call(this,z)&&!isNaN(+z.slice(1))&&(this[z]=e)},stop:function(){this.done=!0;var N=this.tryEntries[0],z=N.completion;if(z.type==="throw")throw z.arg;return this.rval},dispatchException:function(N){if(this.done)throw N;var z=this;function re(we,Se){return De.type="throw",De.arg=N,z.next=we,Se&&(z.method="next",z.arg=e),!!Se}for(var oe=this.tryEntries.length-1;oe>=0;--oe){var Te=this.tryEntries[oe],De=Te.completion;if(Te.tryLoc==="root")return re("end");if(Te.tryLoc<=this.prev){var Ce=o.call(Te,"catchLoc"),He=o.call(Te,"finallyLoc");if(Ce&&He){if(this.prev<Te.catchLoc)return re(Te.catchLoc,!0);if(this.prev<Te.finallyLoc)return re(Te.finallyLoc)}else if(Ce){if(this.prev<Te.catchLoc)return re(Te.catchLoc,!0)}else if(He){if(this.prev<Te.finallyLoc)return re(Te.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(N,z){for(var re=this.tryEntries.length-1;re>=0;--re){var oe=this.tryEntries[re];if(oe.tryLoc<=this.prev&&o.call(oe,"finallyLoc")&&this.prev<oe.finallyLoc){var Te=oe;break}}Te&&(N==="break"||N==="continue")&&Te.tryLoc<=z&&z<=Te.finallyLoc&&(Te=null);var De=Te?Te.completion:{};return De.type=N,De.arg=z,Te?(this.method="next",this.next=Te.finallyLoc,W):this.complete(De)},complete:function(N,z){if(N.type==="throw")throw N.arg;return N.type==="break"||N.type==="continue"?this.next=N.arg:N.type==="return"?(this.rval=this.arg=N.arg,this.method="return",this.next="end"):N.type==="normal"&&z&&(this.next=z),W},finish:function(N){for(var z=this.tryEntries.length-1;z>=0;--z){var re=this.tryEntries[z];if(re.finallyLoc===N)return this.complete(re.completion,re.afterLoc),Z(re),W}},catch:function(N){for(var z=this.tryEntries.length-1;z>=0;--z){var re=this.tryEntries[z];if(re.tryLoc===N){var oe=re.completion;if(oe.type==="throw"){var Te=oe.arg;Z(re)}return Te}}throw new Error("illegal catch attempt")},delegateYield:function(N,z,re){return this.delegate={iterator:se(N),resultName:z,nextLoc:re},this.method==="next"&&(this.arg=e),W}},i}(c.exports);try{regeneratorRuntime=s}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=s:Function("r","regeneratorRuntime = r")(s)}})(YT);var A_={exports:{}};(function(c){(function(s,i){c.exports?c.exports=i():s.log=i()})(Bt,function(){var s=function(){},i="undefined",l=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function _(R,I){var V=R[I];if(typeof V.bind=="function")return V.bind(R);try{return Function.prototype.bind.call(V,R)}catch{return function(){return Function.prototype.apply.apply(V,[R,arguments])}}}function e(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(R){return R==="debug"&&(R="log"),typeof console===i?!1:R==="trace"&&l?e:console[R]!==void 0?_(console,R):console.log!==void 0?_(console,"log"):s}function g(R,I){for(var V=0;V<o.length;V++){var W=o[V];this[W]=V<R?s:this.methodFactory(W,R,I)}this.log=this.debug}function n(R,I,V){return function(){typeof console!==i&&(g.call(this,I,V),this[R].apply(this,arguments))}}function v(R,I,V){return p(R)||n.apply(this,arguments)}function S(R,I,V){var W=this,ae;I=I??"WARN";var x="loglevel";typeof R=="string"?x+=":"+R:typeof R=="symbol"&&(x=void 0);function $(D){var L=(o[D]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=L;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+L+";"}catch{}}}function Re(){var D;if(!(typeof window===i||!x)){try{D=window.localStorage[x]}catch{}if(typeof D===i)try{var L=window.document.cookie,q=L.indexOf(encodeURIComponent(x)+"=");q!==-1&&(D=/^([^;]+)/.exec(L.slice(q))[1])}catch{}return W.levels[D]===void 0&&(D=void 0),D}}function be(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x);return}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}W.name=R,W.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},W.methodFactory=V||v,W.getLevel=function(){return ae},W.setLevel=function(D,L){if(typeof D=="string"&&W.levels[D.toUpperCase()]!==void 0&&(D=W.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=W.levels.SILENT){if(ae=D,L!==!1&&$(D),g.call(W,D,R),typeof console===i&&D<W.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},W.setDefaultLevel=function(D){I=D,Re()||W.setLevel(D,!1)},W.resetLevel=function(){W.setLevel(I,!1),be()},W.enableAll=function(D){W.setLevel(W.levels.TRACE,D)},W.disableAll=function(D){W.setLevel(W.levels.SILENT,D)};var H=Re();H==null&&(H=I),W.setLevel(H,!1)}var m=new S,C={};m.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var V=C[I];return V||(V=C[I]=new S(I,m.getLevel(),m.methodFactory)),V};var A=typeof window!==i?window.log:void 0;return m.noConflict=function(){return typeof window!==i&&window.log===m&&(window.log=A),m},m.getLoggers=function(){return C},m.default=m,m})})(A_);var wt=A_.exports;const Es=()=>`${new Date().toISOString()} | metrics`,Ss=(c,s,i)=>`${c} | ${s} | ${i}`;wt.setDefaultLevel(wt.levels.TRACE);const JT=c=>{wt.info(Ss(Es(),"log ",`set log level to ${c?"verbose":"info"}`)),wt.setLevel(c?wt.levels.TRACE:wt.levels.INFO)},zT=c=>{const s=[...Object.keys(wt.levels)];s.includes(c)?(wt.info(Ss(Es(),"log ",`update log level to ${c.toLowerCase()}`)),wt.setLevel(c)):wt.warn(Ss(Es(),"log ","Incorrect log level please choose one of "),s)},Le=(c,s,i)=>{i?wt.debug(Ss(Es(),c,s),i):wt.debug(Ss(Es(),c,s))},Uu=(c,s)=>{wt.info(Ss(Es(),c,s))},pn=(c,s)=>{wt.info(Ss(Es(),c,s))},yo=(c,s)=>{wt.warn(Ss(Es(),c,s))},zn=(c,s)=>{wt.error(Ss(Es(),c,s))};function XT(c){return Math.floor(Math.random()*c).toString()}function C_(c,s){let i=s;return c.forEach(l=>{i=i.replace(l,"")}),i}function QT(c,s){let i="";for(let l=0;l<s;l+=1)i+=c[XT(c.length)];return i}function ZT({length:c=20,useLetters:s=!0,useNumbers:i=!0,includeSymbols:l=[],excludeSymbols:o=[]}={}){let _="abcdefghijklmnopqrstuvwxyz",e="0123456789",p=[],g=[],n=[];return s&&(o.length&&(_=C_(o,_)),g=_.split("")),i&&(o.length&&(e=C_(o,e)),n=e.split("")),p=[...g,...n,...l],QT(p,c)}var ev=ZT;const Jr=ke(ev),tv=()=>"WebRTCMetrics",sv=()=>"5.0.3",Ve={INBOUND:"inbound",OUTBOUND:"outbound"},ys={IDLE:"idle",RUNNING:"running",MUTED:"muted"},zr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},nv=()=>({...{delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}}),R_={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:Ve.INBOUND},I_={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:Ve.OUTBOUND},b_={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:Ve.INBOUND},w_={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:Ve.OUTBOUND},rv=c=>{const s={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const i={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(l=>{i.audio[l]={...c.audio[l]}}),Object.keys(c.video).forEach(l=>{i.video[l]={...c.video[l]}}),i}return{...s,audio:{},video:{},data:{...s.data},network:{...s.network},experimental:{...s.experimental}}},iv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Jr()}`,cid:`c-${Jr()}`,uid:`u-${Jr()}`,record:!1,ticket:!0},Jt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},K={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},M={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Xr={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Pu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ie={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},xu="config ",lv=(c,s={},i)=>{const l={...i,...s};return s.pname||yo(xu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${i.pname}'`),s.cid||yo(xu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${i.cid}'`),s.uid||yo(xu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${i.uid}'`),l.pc=c,l},ov=(c={})=>{const s={...iv,...c};return s.name=tv(),s.version=sv(),s},Qr=(c,s,i,l=!1,o)=>{let _=c.map(e=>{if(!i)return e[s];if(!o)return e[s][i];const p=e[s][o];return p?p[i]:null});return _=_.filter(e=>l?Number.isFinite(e)&&e>0:Number.isFinite(e)),_.length===0?[]:_},Hs=c=>c.reduce((s,i)=>s+i,0)/c.length,av=()=>`probe-${Jr()}`,uv=()=>`coltr-${Jr()}`,O_=c=>new Promise(s=>setTimeout(s,c)),Mu=(c,s,i)=>{s?c.call(s,i):c(i)},Xe=(c,s,i,l)=>{const o=Qr(c,s,i,!0,l);if(o.length===0)return null;const _=o.reduce((n,v)=>n+v,0)/o.length;return _===0?null:o.map(n=>Math.abs(_-n)).reduce((n,v)=>n+v,0)/o.length*100/_},st=(c,s,i,l=!1,o)=>{const _=Qr(c,s,i,l,o);return _.length===0?null:_.reduce((e,p)=>e+p,0)/_.length},mn=(c,s,i)=>Qr(c,s,i).reduce((o,_)=>o+_,0),Qe=(c,s,i,l)=>{const o=Qr(c,s,i,!0,l);return o.length===0?null:Math.min(...o)},Ze=(c,s,i,l)=>{const o=Qr(c,s,i,!1,l);return o.length===0?null:Math.max(...o)},Ct=(c,s,i,l)=>{const o=c.slice().pop();if(!o)return null;if(!i)return o[s];if(!l)return o[s][i];const _=o[s][l];return _?_[i]:null},cv=c=>c.slice().pop(),ht=(c,s,i)=>{if(!s)return null;const l={};let o=s[M.AUDIO][c];o||(o=i===Ve.INBOUND?{...R_}:{...I_}),l[M.AUDIO]=o;let _=s[M.VIDEO][c];return _||(_=i===Ve.INBOUND?{...b_}:{...w_}),l[M.VIDEO]=_,l},Zr="exporter ",fv="2.0",D_=(c,s,i)=>{if(!c||c.length===0)return 0;const l=c[c.length-1];if(!l)return 0;const o=l[s][i];if(o){const _=o.total_rtt_ms_out,e=o.total_rtt_measure_out;return!e||!_?st(c,s,"delta_rtt_ms_out",!1,i):Number(_/e)}return null},_v=(c,s)=>{if(!c||c.length===0)return 0;const i=c[c.length-1];if(!i)return 0;const l=i[s].total_rtt_connectivity_ms,o=i[s].total_rtt_connectivity_measure;return!o||!l?st(c,s,"delta_rtt_connectivity_ms"):Number(l/o)},hv=c=>Ct(c,"network","local_candidate_type")!=="relay"?`direct/${Ct(c,"network","local_candidate_protocol")}`:`turn/${Ct(c,"network","local_candidate_relay_protocol")}`,dv=c=>{const s=Ct(c,"network","remote_candidate_type"),i=Ct(c,"network","remote_candidate_protocol");return s!=="relay"?`direct/${i}`:`turn/${i}`};class pv{constructor(s){this._start=null,this._end=null,this._cfg=s,this._referenceReport=null,this._reports=[],this._events=[]}start(){Uu(Zr,"start() - start exporter...");const s=new Date;return this._start=s.toJSON(),s}stop(){Uu(Zr,"stop() - stop exporter...");const s=new Date;return this._end=s.toJSON(),s}saveReferenceReport(s){this._referenceReport=s}getReferenceReport(){return this._referenceReport}addReport(s){this._cfg.ticket&&(Le(Zr,`addReport() - add report to exporter at ${s.timestamp}`),this._reports.push(s))}addCustomEvent(s){this._events.push(s)}reset(){Uu(Zr,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Le(Zr,"ticket() - generate ticket");const s=Ct(this._reports,"audio","total_packets_lost_in"),i=Ct(this._reports,"audio","total_packets_in"),l=Ct(this._reports,"video","total_packets_lost_in"),o=Ct(this._reports,"video","total_packets_in"),_={},e=cv(this._reports);return e&&(Object.keys(e[M.AUDIO]).forEach(p=>{const g=e[M.AUDIO][p];if(_[g.ssrc]={type:M.AUDIO,direction:g.direction},g.direction===Ve.INBOUND){const n={avg:st(this._reports,M.AUDIO,"delta_jitter_ms_in",!1,p),min:Qe(this._reports,M.AUDIO,"delta_jitter_ms_in",p),max:Ze(this._reports,M.AUDIO,"delta_jitter_ms_in",p),volatility:Xe(this._reports,M.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.AUDIO,"delta_kbs_in",!1,p),min:Qe(this._reports,M.AUDIO,"delta_kbs_in",p),max:Ze(this._reports,M.AUDIO,"delta_kbs_in",p),volatility:Xe(this._reports,M.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.AUDIO,"delta_KBytes_in",!1,p),min:Qe(this._reports,M.AUDIO,"delta_KBytes_in",p),max:Ze(this._reports,M.AUDIO,"delta_KBytes_in",p),volatility:Xe(this._reports,M.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={emodel:{avg:st(this._reports,M.AUDIO,"mos_emodel_in",!1,p),min:Qe(this._reports,M.AUDIO,"mos_emodel_in",p),max:Ze(this._reports,M.AUDIO,"mos_emodel_in",p),volatility:Xe(this._reports,M.AUDIO,"mos_emodel_in",p)},effective:{avg:st(this._reports,M.AUDIO,"mos_in",!1,p),min:Qe(this._reports,M.AUDIO,"mos_in",p),max:Ze(this._reports,M.AUDIO,"mos_in",p),volatility:Xe(this._reports,M.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},C=Ct(this._reports,M.AUDIO,"total_packets_lost_in",p),A=Ct(this._reports,M.AUDIO,"total_packets_in",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].mos=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R}else{const n={avg:st(this._reports,M.AUDIO,"delta_jitter_ms_out",!1,p),min:Qe(this._reports,M.AUDIO,"delta_jitter_ms_out",p),max:Ze(this._reports,M.AUDIO,"delta_jitter_ms_out",p),volatility:Xe(this._reports,M.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.AUDIO,"delta_kbs_out",!1,p),min:Qe(this._reports,M.AUDIO,"delta_kbs_out",p),max:Ze(this._reports,M.AUDIO,"delta_kbs_out",p),volatility:Xe(this._reports,M.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.AUDIO,"delta_KBytes_out",!1,p),min:Qe(this._reports,M.AUDIO,"delta_KBytes_out",p),max:Ze(this._reports,M.AUDIO,"delta_KBytes_out",p),volatility:Xe(this._reports,M.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},m={avg:D_(this._reports,M.AUDIO,p),min:Qe(this._reports,M.AUDIO,"delta_rtt_ms_out",p),max:Ze(this._reports,M.AUDIO,"delta_rtt_ms_out",p),volatility:Xe(this._reports,M.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=Ct(this._reports,M.AUDIO,"total_packets_lost_out",p),A=Ct(this._reports,M.AUDIO,"total_packets_out",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:st(this._reports,M.AUDIO,"mos_emodel_out",!1,p),min:Qe(this._reports,M.AUDIO,"mos_emodel_out",p),max:Ze(this._reports,M.AUDIO,"mos_emodel_out",p),volatility:Xe(this._reports,M.AUDIO,"mos_emodel_out",p)},effective:{avg:st(this._reports,M.AUDIO,"mos_out",!1,p),min:Qe(this._reports,M.AUDIO,"mos_out",p),max:Ze(this._reports,M.AUDIO,"mos_out",p),volatility:Xe(this._reports,M.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};_[p].jitter=n,_[p].rtt=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R,_[p].mos=I}}),Object.keys(e[M.VIDEO]).forEach(p=>{const g=e[M.VIDEO][p];if(_[p]={type:M.VIDEO,direction:g.direction},g.direction===Ve.INBOUND){const n={avg:st(this._reports,M.VIDEO,"delta_jitter_ms_in",!1,p),min:Qe(this._reports,M.VIDEO,"delta_jitter_ms_in",p),max:Ze(this._reports,M.VIDEO,"delta_jitter_ms_in",p),volatility:Xe(this._reports,M.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.VIDEO,"delta_kbs_in",!1,p),min:Qe(this._reports,M.VIDEO,"delta_kbs_in",p),max:Ze(this._reports,M.VIDEO,"delta_kbs_in",p),volatility:Xe(this._reports,M.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.VIDEO,"delta_KBytes_in",!1,p),min:Qe(this._reports,M.VIDEO,"delta_KBytes_in",p),max:Ze(this._reports,M.VIDEO,"delta_KBytes_in",p),volatility:Xe(this._reports,M.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m=Ct(this._reports,M.VIDEO,"total_packets_lost_in",p),C=Ct(this._reports,M.VIDEO,"total_packets_in",p),A={lost:m,avg:Math.round((m/(m+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].traffic=S,_[p].bitrate=v,_[p].loss=A}else{const n={avg:st(this._reports,M.VIDEO,"delta_jitter_ms_out",!1,p),min:Qe(this._reports,M.VIDEO,"delta_jitter_ms_out",p),max:Ze(this._reports,M.VIDEO,"delta_jitter_ms_out",p),volatility:Xe(this._reports,M.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.VIDEO,"delta_kbs_out",!1,p),min:Qe(this._reports,M.VIDEO,"delta_kbs_out",p),max:Ze(this._reports,M.VIDEO,"delta_kbs_out",p),volatility:Xe(this._reports,M.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.VIDEO,"delta_KBytes_out",!1,p),min:Qe(this._reports,M.VIDEO,"delta_KBytes_out",p),max:Ze(this._reports,M.VIDEO,"delta_KBytes_out",p),volatility:Xe(this._reports,M.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={avg:D_(this._reports,M.VIDEO,p),min:Qe(this._reports,M.VIDEO,"delta_rtt_ms_out",p),max:Ze(this._reports,M.VIDEO,"delta_rtt_ms_out",p),volatility:Xe(this._reports,M.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=Ct(this._reports,M.VIDEO,"total_packets_lost_out",p),A=Ct(this._reports,M.VIDEO,"total_packets_out",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].rtt=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R}})),{version:fv,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:_,data:{rtt:{avg:_v(this._reports,"data"),min:Qe(this._reports,"data","delta_rtt_connectivity_ms"),max:Ze(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Xe(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((s/(s+i)*100||0)*100)/100}},video:{in:{avg:Math.round((l/(l+o)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:st(this._reports,"data","delta_kbs_in"),min:Qe(this._reports,"data","delta_kbs_in"),max:Ze(this._reports,"data","delta_kbs_in"),volatility:Xe(this._reports,"data","delta_kbs_in")},out:{avg:st(this._reports,"data","delta_kbs_out"),min:Qe(this._reports,"data","delta_kbs_out"),max:Ze(this._reports,"data","delta_kbs_out"),volatility:Xe(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:st(this._reports,"data","delta_KBytes_in"),min:Qe(this._reports,"data","delta_KBytes_in"),max:Ze(this._reports,"data","delta_KBytes_in"),volatility:Xe(this._reports,"data","delta_KBytes_in")},out:{avg:st(this._reports,"data","delta_KBytes_out"),min:Qe(this._reports,"data","delta_KBytes_out"),max:Ze(this._reports,"data","delta_KBytes_out"),volatility:Xe(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:hv(this._reports),remoteConnection:dv(this._reports)}}}}updateConfig(s){this._cfg=s}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const s=this._reports.slice();return s.pop(),s.pop()||null}getReportsNumber(){return this._reports.length}}const Fs="extractor ",N_=(c,s,i,l)=>{let o=!1;const _=l[s].total_rtt_ms_out,e=l[s].total_rtt_measure_out,p=i?i[s].total_rtt_ms_out:0,g=i?i[s].total_rtt_measure_out:0,n={rtt:null,totalRTT:_,totalRTTMeasurements:e};if(c[K.TIMESTAMP]===l[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(o=!0,Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-g===e))return n;const v=1e3*Number(c[K.ROUND_TRIP_TIME]);let S=_+v,m=e+1;return o&&(S=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-p,m=Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-g),{rtt:v,totalRTT:S,totalRTTMeasurements:m}},mv=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:l[s].total_rtt_connectivity_ms,totalRTTMeasurements:l[s].total_rtt_connectivity_measure};const o=1e3*Number(c[K.CURRENT_ROUND_TRIP_TIME]);let _=l[s].total_rtt_connectivity_ms+o,e=l[s].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME)&&(_=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-(i?i[s].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,K.RESPONSES_RECEIVED)&&(e=Number(c[K.RESPONSES_RECEIVED])-(i?i[s].total_rtt_connectivity_measure:0)),{rtt:o,totalRTT:_,totalRTTMeasurements:e}},Ao=(c,s,i)=>c[K.TIMESTAMP]===i[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.JITTER)?null:1e3*(Number(c[K.JITTER])||0),gv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:s[M.VIDEO].delta_ms_decode_frame_in,frames_decoded:s[M.VIDEO].total_frames_decoded_in,total_decode_time:s[M.VIDEO].total_time_decoded_in};const i=c[K.FRAMES_DECODED],l=c[K.TOTAL_DECODE_TIME],o=l-s[M.VIDEO].total_time_decoded_in,_=i-s[M.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:_>0?o*1e3/_:0,frames_decoded:i,total_decode_time:l}},Tv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:s[M.VIDEO].delta_ms_encode_frame_out,frames_encoded:s[M.VIDEO].total_frames_encoded_out,total_encode_time:s[M.VIDEO].total_time_encoded_out};const i=c[K.FRAMES_ENCODED],l=c[K.TOTAL_ENCODE_TIME],o=l-s[M.VIDEO].total_time_encoded_out,_=i-s[M.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:_>0&&o?o*1e3/_:0,frames_encoded:i,total_encode_time:l}},U_=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_SENT))return{packetsSent:i[s].total_packets_out,packetsLost:i[s].total_packets_lost_out,bytesSent:i[s].total_KBytes_out};const o=Number(c[K.PACKETS_SENT])||0-(l?l[s].total_packets_out:0),_=o-i[s].total_packets_out,e=Number(c[K.BYTES_SENT])/1024-(l?l[s].total_KBytes_out:0),p=e-i[s].total_KBytes_out,g=c[K.TIMESTAMP]||Date.now(),n=l?l.timestamp:null;let v=i.timestamp;!v&&n&&(v=n);const S=v?g-v:0,m=S>0?p*.008*1024/S*1e3:0;return{packetsSent:o,deltaPacketsSent:_,KBytesSent:e,deltaKBytesSent:p,kbsSent:m}},P_=(c,s,i,l)=>{let o=i[s].total_packets_lost_out,_=0,e=0;return Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)&&(o=Number(c[K.PACKETS_LOST])||0-(l?l[s].total_packets_lost_out:0),_=o-i[s].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,K.FRACTION_LOST)&&(e=Number(100*c[K.FRACTION_LOST])),{packetsLost:o,deltaPacketsLost:_,fractionLost:e}},x_=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_RECEIVED))return{percent_packets_lost:i[s].percent_packets_lost_in,packetsReceived:i[s].total_packets_in,packetsLost:i[s].total_packets_lost_in,bytesReceived:i[s].total_KBytes_in};const o=Number(c[K.PACKETS_RECEIVED])||0-(l?l[s].total_packets_in:0),_=Number(c[K.PACKETS_LOST])||0-(l?l[s].total_packets_lost_in:0),e=_-i[s].total_packets_lost_in,p=o-i[s].total_packets_in,g=o!==i[s].total_packets_in?e*100/(e+p):0,n=Number(c[K.BYTES_RECEIVED])/1024-(l?l[s].total_KBytes_in:0),v=n-i[s].total_KBytes_in,S=c[K.TIMESTAMP]||Date.now(),m=l?l.timestamp:null;let C=i.timestamp;!C&&m&&(C=m);const A=C?S-C:0,R=A>0?v*.008*1024/A*1e3:0;return{percentPacketsLost:g,packetsReceived:o,deltaPacketsReceived:p,packetsLost:_,deltaPacketsLost:e,KBytesReceived:n,deltaKBytesReceived:v,kbsReceived:R}},vv=c=>c[K.CANDIDATE_TYPE]!=="relay"?"":c[K.RELAY_PROTOCOL]||"",Ev=c=>{if(!Object.prototype.hasOwnProperty.call(c,K.NETWORK_TYPE))return Xr.WIFI;switch(c[K.NETWORK_TYPE]){case Pu.ETHERNET:return Xr.ETHERNET;case Pu.CELLULAR_4G:return Xr.CELLULAR_4G;case Pu.WIFI:return Xr.WIFI;default:return Xr.CELLULAR}},M_=c=>!Object.prototype.hasOwnProperty.call(c,K.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,K.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[K.FRAME_WIDTH]||null,height:c[K.FRAME_HEIGHT]||null,framerate:c[K.FRAMES_PER_SECOND]},Sv=c=>{const s=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_REASON)?c[K.QUALITY_LIMITATION_REASON]:null,i=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[K.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,l=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_DURATIONS)?c[K.QUALITY_LIMITATION_DURATIONS]:null;return l&&Object.keys(l).forEach(o=>{l[o]>1e3&&(l[o]=Number(l[o]/1e3))}),{reason:s,durations:l,resolutionChanges:i}},yv=(c,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:s.total_pli_sent_in,nackCount:s.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(i?i[M.VIDEO].total_pli_sent_in:0),o=(c[K.NACK]||0)-(i?i[M.VIDEO].total_nack_sent_in:0);return{pliCount:l,nackCount:o,deltaPliCount:l-s[M.VIDEO].total_pli_sent_in,deltaNackCount:o-s[M.VIDEO].total_nack_sent_in}},Av=(c,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:s.total_pli_received_out,nackCount:s.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(i?i[M.VIDEO].total_pli_received_out:0),o=(c[K.NACK]||0)-(i?i[M.VIDEO].total_nack_received_out:0);return{pliCount:l,nackCount:o,deltaPliCount:l-s[M.VIDEO].total_pli_received_out,deltaNackCount:o-s[M.VIDEO].total_nack_received_out}},Cv=c=>({channels:c[K.CHANNELS]||null,clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null,sdp_fmtp_line:c[K.SDP_FMTP_LINE]||null}),Rv=c=>({clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null}),Iv=(c,s,i)=>{const l=(c[K.BYTES_RECEIVED]||0)/1024-(i?i.data.total_KBytes_in:0),o=(c[K.BYTES_SENT]||0)/1024-(i?i.data.total_KBytes_out:0),_=c[K.TIMESTAMP]||Date.now(),e=l-s.data.total_KBytes_in,p=o-s.data.total_KBytes_out,g=i?i.timestamp:null;let n=s.timestamp;!n&&g&&(n=g);const v=n?_-n:0,S=v>0?e*.008*1024/v*1e3:0,m=v>0?p*.008*1024/v*1e3:0;return{total_KBytes_received:l,total_KBytes_sent:o,delta_KBytes_received:e,delta_KBytes_sent:p,kbs_speed_received:S,kbs_speed_sent:m}},bv=c=>{const s=c[K.AVAILABLE_INCOMING_BITRATE]/1024||0,i=c[K.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:s,kbs_outgoing_bandwidth:i}},wv=(c,s,i,l)=>{if(!c)return[];switch(c[K.TYPE]){case Jt.CANDIDATE_PAIR:let o=!1;if(c[K.NOMINATED]&&c[K.STATE]===M.SUCCEEDED&&(o=!0,Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c),K.SELECTED in c&&!c[K.SELECTED]&&(o=!1)),o){const e=c[K.LOCAL_CANDIDATE_ID],p=c[K.REMOTE_CANDIDATE_ID],g=Iv(c,s,l),n=bv(c),v=mv(c,"data",l,s);return[{type:ie.NETWORK,value:{local_candidate_id:e}},{type:ie.NETWORK,value:{remote_candidate_id:p}},{type:ie.DATA,value:{total_KBytes_in:g.total_KBytes_received}},{type:ie.DATA,value:{total_KBytes_out:g.total_KBytes_sent}},{type:ie.DATA,value:{delta_KBytes_in:g.delta_KBytes_received}},{type:ie.DATA,value:{delta_KBytes_out:g.delta_KBytes_sent}},{type:ie.DATA,value:{delta_kbs_in:g.kbs_speed_received}},{type:ie.DATA,value:{delta_kbs_out:g.kbs_speed_sent}},{type:ie.DATA,value:{delta_kbs_bandwidth_in:n.kbs_incoming_bandwidth}},{type:ie.DATA,value:{delta_kbs_bandwidth_out:n.kbs_outgoing_bandwidth}},{type:ie.DATA,value:{delta_rtt_connectivity_ms:v.rtt}},{type:ie.DATA,value:{total_rtt_connectivity_ms:v.totalRTT}},{type:ie.DATA,value:{total_rtt_connectivity_measure:v.totalRTTMeasurements}}]}break;case Jt.LOCAL_CANDIDATE:if(c[K.ID]===s.network.local_candidate_id)return[{type:ie.NETWORK,value:{infrastructure:Ev(c)}},{type:ie.NETWORK,value:{local_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{local_candidate_protocol:c[K.PROTOCOL]||""}},{type:ie.NETWORK,value:{local_candidate_relay_protocol:vv(c)}}];break;case Jt.REMOTE_CANDIDATE:if(c[K.ID]===s.network.remote_candidate_id)return[{type:ie.NETWORK,value:{remote_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{remote_candidate_protocol:c[K.PROTOCOL]||""}}];break;case Jt.INBOUND_RTP:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=ht(e,s,Ve.INBOUND);p&&(p.timestamp=s.timestamp);const g=ht(e,l,Ve.INBOUND);if(g&&(g.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const n=x_(c,M.AUDIO,p,g),v=Ao(c,M.AUDIO,p),S=c[K.CODEC_ID]||"";return[{ssrc:e,type:ie.AUDIO,value:{codec_id_in:S}},{ssrc:e,type:ie.AUDIO,value:{total_packets_in:n.packetsReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_in:n.deltaPacketsReceived}},{ssrc:e,type:ie.AUDIO,value:{total_packets_lost_in:n.packetsLost}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_lost_in:n.deltaPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{percent_packets_lost_in:n.percentPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{total_KBytes_in:n.KBytesReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_KBytes_in:n.deltaKBytesReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_kbs_in:n.kbsReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_jitter_ms_in:v}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const n=gv(c,p),v=x_(c,M.VIDEO,p,g),S=Ao(c,M.VIDEO,p),m=c[K.DECODER_IMPLEMENTATION]||null,C=c[K.CODEC_ID]||null,A=M_(c),R=yv(c,p,g);return[{ssrc:e,type:ie.VIDEO,value:{codec_id_in:C}},{ssrc:e,type:ie.VIDEO,value:{total_packets_in:v.packetsReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_in:v.deltaPacketsReceived}},{ssrc:e,type:ie.VIDEO,value:{total_packets_lost_in:v.packetsLost}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_lost_in:v.deltaPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{percent_packets_lost_in:v.percentPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{total_KBytes_in:v.KBytesReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_KBytes_in:v.deltaKBytesReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_kbs_in:v.kbsReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_jitter_ms_in:S}},{ssrc:e,type:ie.VIDEO,value:{decoder_in:m}},{ssrc:e,type:ie.VIDEO,value:{delta_ms_decode_frame_in:n.delta_ms_decode_frame}},{ssrc:e,type:ie.VIDEO,value:{total_frames_decoded_in:n.frames_decoded}},{ssrc:e,type:ie.VIDEO,value:{total_time_decoded_in:n.total_decode_time}},{ssrc:e,type:ie.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:e,type:ie.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:e,type:ie.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:e,type:ie.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:e,type:ie.VIDEO,value:{size_in:A}}]}break}case Jt.OUTBOUND_RTP:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=ht(e,s,Ve.OUTBOUND);p&&(p.timestamp=s.timestamp);const g=ht(e,l,Ve.OUTBOUND);if(g&&(g.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const n=c[K.CODEC_ID]||null,v=U_(c,M.AUDIO,p,g);return[{ssrc:e,type:ie.AUDIO,value:{codec_id_out:n}},{ssrc:e,type:ie.AUDIO,value:{total_packets_out:v.packetsSent}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_out:v.deltaPacketsSent}},{ssrc:e,type:ie.AUDIO,value:{total_KBytes_out:v.KBytesSent}},{ssrc:e,type:ie.AUDIO,value:{delta_KBytes_out:v.deltaKBytesSent}},{ssrc:e,type:ie.AUDIO,value:{delta_kbs_out:v.kbsSent}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const n=c[K.ENCODER_IMPLEMENTATION]||null,v=c[K.CODEC_ID]||null,S=Tv(c,p),m=M_(c),C=Sv(c),A=Av(c,p,g),R=U_(c,M.VIDEO,p,g);return[{ssrc:e,type:ie.VIDEO,value:{codec_id_out:v}},{ssrc:e,type:ie.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:e,type:ie.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:e,type:ie.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:e,type:ie.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:e,type:ie.VIDEO,value:{encoder_out:n}},{ssrc:e,type:ie.VIDEO,value:{delta_ms_encode_frame_out:S.delta_ms_encode_frame}},{ssrc:e,type:ie.VIDEO,value:{total_frames_encoded_out:S.frames_encoded}},{ssrc:e,type:ie.VIDEO,value:{total_time_encoded_out:S.total_encode_time}},{ssrc:e,type:ie.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:e,type:ie.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:e,type:ie.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:e,type:ie.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:e,type:ie.VIDEO,value:{size_out:m}},{ssrc:e,type:ie.VIDEO,value:{limitation_out:C}}]}break}case Jt.MEDIA_SOURCE:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);break}case Jt.TRACK:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);break}case Jt.CODEC:const _=[];return Object.keys(s[M.AUDIO]).forEach(e=>{const p=s[M.AUDIO][e];if(p.codec_id_in===c[K.ID]||p.codec_id_out===c[K.ID]){Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const g=Cv(c);c[K.ID]===p.codec_id_in?_.push({ssrc:p.ssrc,type:ie.AUDIO,value:{codec_in:g}}):_.push({ssrc:p.ssrc,type:ie.AUDIO,value:{codec_out:g}})}}),Object.keys(s[M.VIDEO]).forEach(e=>{const p=s[M.VIDEO][e];if(p.codec_id_in===c[K.ID]||p.codec_id_out===c[K.ID]){Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const g=Rv(c);c[K.ID]===p.codec_id_in?_.push({ssrc:p.ssrc,type:ie.VIDEO,value:{codec_in:g}}):_.push({ssrc:p.ssrc,type:ie.VIDEO,value:{codec_out:g}})}}),_;case Jt.REMOTE_INBOUND_RTP:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=ht(e,s,Ve.OUTBOUND),g=ht(e,l,Ve.OUTBOUND);if(c[K.KIND]===M.AUDIO){const n=N_(c,M.AUDIO,g,p),v=Ao(c,M.AUDIO,p),S=P_(c,M.AUDIO,p,g);return[{ssrc:e,type:ie.AUDIO,value:{delta_rtt_ms_out:n.rtt}},{ssrc:e,type:ie.AUDIO,value:{total_rtt_ms_out:n.totalRTT}},{ssrc:e,type:ie.AUDIO,value:{total_rtt_measure_out:n.totalRTTMeasurements}},{ssrc:e,type:ie.AUDIO,value:{delta_jitter_ms_out:v}},{ssrc:e,type:ie.AUDIO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:e,type:ie.AUDIO,value:{total_packets_lost_out:S.packetsLost}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_lost_out:S.deltaPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{percent_packets_lost_out:S.fractionLost}}]}if(c[K.KIND]===M.VIDEO){const n=N_(c,M.VIDEO,g,p),v=Ao(c,M.VIDEO,p),S=P_(c,M.VIDEO,p,g);return[{ssrc:e,type:ie.VIDEO,value:{delta_rtt_ms_out:n.rtt}},{ssrc:e,type:ie.VIDEO,value:{total_rtt_ms_out:n.totalRTT}},{ssrc:e,type:ie.VIDEO,value:{total_rtt_measure_out:n.totalRTTMeasurements}},{ssrc:e,type:ie.VIDEO,value:{delta_jitter_ms_out:v}},{ssrc:e,type:ie.VIDEO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:e,type:ie.VIDEO,value:{total_packets_lost_out:S.packetsLost}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_lost_out:S.deltaPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{percent_packets_lost_out:S.fractionLost}}]}break}}return[]},Co=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Ov=(c,s=M.AUDIO,i,l,o)=>{const _=ht(o,c,Ve.INBOUND),e=ht(o,i,Ve.INBOUND),p=ht(o,l,Ve.INBOUND),g=[],n=[],v=_[s].percent_packets_lost_in,S=_[s].delta_jitter_ms_in,m=e&&e[s].delta_jitter_ms_in||null,C=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=i&&i.data.delta_rtt_connectivity_ms||null,I=l&&l.data.delta_rtt_connectivity_ms||null;A&&g.push(A),R&&g.push(R),I&&g.push(I),S&&n.push(S),i&&m&&n.push(m),l&&C&&n.push(C);const V=g.length>0?Hs(g):100,W=n.length>0?Hs(n):10,ae=93.2-v,x=.18*ae*ae-27.9*ae+1126.62,$=(V+W)/2,Re=$-177.3<0?0:1,be=.024*$+.11*($-177.3)*Re,H=x-be;return Co(H)},Dv=(c,s=M.AUDIO,i,l,o)=>{const _=ht(o,c,Ve.OUTBOUND),e=ht(o,i,Ve.OUTBOUND),p=ht(o,l,Ve.OUTBOUND),g=[],n=[],v=_[s].percent_packets_lost_out,S=_[s].delta_rtt_ms_out,m=e&&e[s].delta_rtt_ms_out||null,C=p&&p[s].delta_rtt_ms_out||null,A=_[s].delta_jitter_ms_out,R=e&&e[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,W=i&&i.data.delta_rtt_connectivity_ms||null,ae=l&&l.data.delta_rtt_connectivity_ms||null;S?g.push(S):V&&g.push(V),m?g.push(m):W&&g.push(W),C?g.push(C):ae&&g.push(ae),A&&n.push(A),i&&R&&n.push(R),l&&I&&n.push(I);const x=g.length>0?Hs(g):100,$=n.length>0?Hs(n):10,Re=93.2-v,be=.18*Re*Re-27.9*Re+1126.62,H=(x+$)/2,D=H-177.3<0?0:1,L=.024*H+.11*(H-177.3)*D,q=be-L;return Co(q)},Nv=(c,s=M.AUDIO,i,l,o)=>{const _=ht(o,c,Ve.INBOUND),e=ht(o,i,Ve.INBOUND),p=ht(o,l,Ve.INBOUND),g=[],n=[],v=_[s].percent_packets_lost_in/100,S=_[s].delta_jitter_ms_in,m=e&&e[s].delta_jitter_ms_in||null,C=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=i&&i.data.delta_rtt_connectivity_ms||null,I=l&&l.data.delta_rtt_connectivity_ms||null;A&&g.push(A),R&&g.push(R),I&&g.push(I),S&&n.push(S),e&&m&&n.push(m),p&&C&&n.push(C);const V=g.length>0?Hs(g):100,W=n.length>0?Hs(n):10,ae=0,x=19.8,$=29.7,Re=30,be=(V+W)/2+Re,H=be-177.3<0?0:1,D=.024*be+.11*(be-177.3)*H,q=93.2-(ae+x*Math.log(1+$*v)+D);return Co(q)},Uv=(c,s=M.AUDIO,i,l,o)=>{const _=ht(o,c,Ve.OUTBOUND),e=ht(o,i,Ve.OUTBOUND),p=ht(o,l,Ve.OUTBOUND),g=[],n=[],v=_[s].percent_packets_lost_out/100,S=_[s].delta_rtt_ms_out,m=e&&e[s].delta_rtt_ms_out||null,C=p&&p[s].delta_rtt_ms_out||null,A=_[s].delta_jitter_ms_out,R=e&&e[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,W=i&&i.data.delta_rtt_connectivity_ms||null,ae=l&&l.data.delta_rtt_connectivity_ms||null;S?g.push(S):V&&g.push(V),m?g.push(m):W&&g.push(W),C?g.push(C):ae&&g.push(ae),A&&n.push(A),e&&R&&n.push(R),p&&I&&n.push(I);const x=g.length>0?Hs(g):100,$=n.length>0?Hs(n):10,Re=0,be=19.8,H=29.7,D=30,L=(x+$)/2+D,q=L-177.3<0?0:1,j=.024*L+.11*(L-177.3)*q,Q=93.2-(Re+be*Math.log(1+H*v)+j);return Co(Q)};class Pv{constructor(s,i){this._callbacks={onreport:null,onticket:null},this._id=uv(),this._moduleName=this._id,this._probeId=i,this._config=s,this._exporter=new pv(s),this._state=ys.IDLE,this.registerToPCEvents(),pn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(s,i,l,o){const _=(g,n)=>g===M.AUDIO?n===Jt.INBOUND_RTP?{...R_}:{...I_}:n===Jt.INBOUND_RTP?{...b_}:{...w_},e=rv(i);e.pname=this._config.pname,e.call_id=this._config.cid,e.user_id=this._config.uid,e.count=i?i.count+1:1;let p=null;return s.forEach(g=>{!p&&g.timestamp&&(p=g.timestamp),wv(g,e,e.pname,o).forEach(v=>{if(v.value&&v.type)if(v.ssrc){let S=e[v.type][v.ssrc];S||(S=_(v.type,g.type),S.ssrc=v.ssrc,e[v.type][v.ssrc]=S),Object.keys(v.value).forEach(m=>{S[m]=v.value[m]})}else Object.keys(v.value).forEach(S=>{e[v.type][S]=v.value[S]})})}),e.timestamp=p,Object.keys(e[M.AUDIO]).forEach(g=>{const n=e[M.AUDIO][g];n.direction===Ve.INBOUND?(n.mos_emodel_in=Ov(e,M.AUDIO,i,l,n.ssrc),n.mos_in=Nv(e,M.AUDIO,i,l,n.ssrc)):(n.mos_emodel_out=Dv(e,M.AUDIO,i,l,n.ssrc),n.mos_out=Uv(e,M.AUDIO,i,l,n.ssrc))}),e}async takeReferenceStats(){return new Promise((s,i)=>{const l=Date.now();setTimeout(async()=>{try{const o=Date.now()-l,_=Date.now(),e=await this._config.pc.getStats(),p=this.analyze(e,null,null,null),g=Date.now();p.experimental.time_to_measure_ms=g-_,p.experimental.time_to_wait_ms=o,this._exporter.saveReferenceReport(p),Le(this._moduleName,`got reference report for probe ${this._probeId}`),s()}catch(o){i(o)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ys.RUNNING||!this._config.pc)return Le(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const s=Date.now(),i=await this._config.pc.getStats(),l=this.analyze(i,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),o=Date.now();return l.experimental.time_to_measure_ms=o-s,this._exporter.addReport(l),Le(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(l),l}catch(s){return zn(this._moduleName,`got error ${s}`),null}}async start(){Le(this._moduleName,"starting"),this.state=ys.RUNNING,this._startedTime=this._exporter.start(),Le(this._moduleName,"started")}async mute(){this.state=ys.MUTED,Le(this._moduleName,"muted")}async unmute(){this.state=ys.RUNNING,Le(this._moduleName,"unmuted")}async stop(s){if(Le(this._moduleName,`stopping${s?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ys.IDLE,this._config.ticket){const{ticket:i}=this._exporter;this.fireOnTicket(i)}this._exporter.reset(),Le(this._moduleName,"stopped")}registerCallback(s,i,l){s in this._callbacks?(this._callbacks[s]={callback:i,context:l},Le(this._moduleName,`registered callback '${s}'`)):zn(this._moduleName,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],Le(this._moduleName,`unregistered callback '${s}'`)):zn(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReport(s){this._callbacks.onreport&&Mu(this._callbacks.onreport.callback,this._callbacks.onreport.context,s)}fireOnTicket(s){this._callbacks.onticket&&Mu(this._callbacks.onticket.callback,this._callbacks.onticket.context,s)}updateConfig(s){this._config=s,this._exporter.updateConfig(s)}get state(){return this._state}set state(s){this._state=s,Le(this._moduleName,`state changed to ${s}`)}addCustomEvent(s,i,l,o){this._exporter.addCustomEvent({at:typeof s=="object"?s.toJSON():s,category:i,name:l,description:o})}async registerToPCEvents(){const{pc:s}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const i=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${i.length} devices found`,"Media Devices state")}catch{zn(this._moduleName,"can't get devices")}},s){s.oniceconnectionstatechange=()=>{const l=s.iceConnectionState;l===zr.CONNECTED||l===zr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===zr.DISCONNECTED||l===zr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===zr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},s.onicegatheringstatechange=()=>{const l=s.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",l,"ICE gathering state")},s.ontrack=l=>{this.addCustomEvent(new Date().toJSON(),"call",`${l.track.kind}track`,"MediaStreamTrack received")},s.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const i=s.getReceivers();if(i&&i.length>0){const l=i[0],{transport:o}=l;if(o){const{iceTransport:_}=o;_&&(_.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class xv{constructor(s){this._id=s.pname&&s.pname.substr(0,12).padEnd(12," ")||av(),this._moduleName=this._id,pn(this._moduleName,"probe created"),this._config=s,this._collector=new Pv(this._config,this._id)}set onreport(s){s?this._collector.registerCallback("onreport",s):this._collector.unregisterCallback("onreport")}set onticket(s){s?this._collector.registerCallback("onticket",s):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(s){this._collector.state=s}addCustomEvent(s,i,l,o=new Date().toJSON()){this._collector.addCustomEvent(o,i,s,l)}get isRunning(){return this._collector.state===ys.RUNNING}get isIdle(){return this._collector.state===ys.IDLE}updateUserId(s){this._config.uid=s,this._collector.updateConfig(this._config)}updateCallId(s){this._config.cid=s,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){yo(this._moduleName,"probe is already running");return}this._collector.start()}stop(s=!1){this.isRunning&&this._collector.stop(s)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Ot="engine ";class Mv{constructor(s){this._config=s,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},pn(Ot,`configured for probing every ${this._config.refreshEvery}ms`),pn(Ot,`configured for starting after ${this._config.startAfter}ms`),pn(Ot,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Le(Ot,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(s=>s.isRunning)}get isIdle(){return this._probes.every(s=>s.isIdle)}addNewProbe(s,i){if(!s)throw new Error("undefined peer connection");const l=lv(s,i,this._config),o=new xv(l);return this._probes.push(o),Le(Ot,`${this._probes.length} probes registered`),o}removeExistingProbe(s){if(!s)throw new Error("undefined probe");s.state===ys.RUNNING&&s.stop(),this._probes=this._probes.filter(i=>s.id!==i.id)}async start(){const s=()=>{this._probes.forEach(_=>_.start())},i=async()=>Promise.all(this._probes.map(_=>_.takeReferenceStats())),l=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,o=async()=>{const _=nv(),e=this._probes.filter(p=>p.isRunning);for(const p of e){const g=await p.collectStats();g&&_.probes.push(g),Le(Ot,`got probe ${p.id}`),await O_(0)}return _.delta_time_to_measure_probes_ms=mn(_.probes,"experimental","time_to_measure_ms"),_.delta_KBytes_in=mn(_.probes,"data","delta_KBytes_in"),_.delta_KBytes_out=mn(_.probes,"data","delta_KBytes_out"),_.delta_kbs_in=mn(_.probes,"data","delta_kbs_in"),_.delta_kbs_out=mn(_.probes,"data","delta_kbs_out"),_.total_time_decoded_in=mn(_.probes,"video","total_time_decoded_in"),_.total_time_encoded_out=mn(_.probes,"video","total_time_encoded_out"),_};for(Le(Ot,"starting to collect"),s(),Le(Ot,"generating reference reports..."),await i(),Le(Ot,"reference reports generated"),this._startedTime=Date.now();l();)if(Le(Ot,`wait ${this._config.refreshEvery}ms before collecting`),await O_(this._config.refreshEvery),l()){Le(Ot,"collecting...");const _=Date.now(),e=await o(),p=Date.now();e.delta_time_consumed_to_measure_ms=p-_,this.fireOnReports(e),Le(Ot,"collected")}Le(Ot,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(s){const i=l=>{this._probes.forEach(o=>{o.stop(l)})};pn(Ot,"stop collecting"),i(s)}registerCallback(s,i,l){s in this._callbacks?(this._callbacks[s]={callback:i,context:l},Le(Ot,`registered callback '${s}'`)):zn(Ot,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],Le(this._moduleName,`unregistered callback '${s}'`)):zn(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReports(s){this._callbacks.onresult&&s.probes.length>0&&Mu(this._callbacks.onresult.callback,this._callbacks.onresult.context,s)}}const kv="interface ";class Lv{constructor(s){this._config=ov(s),pn(kv,`welcome to ${this._config.name} version ${this._config.version}`),JT(this._config.verbose||!1),this._engine=new Mv(this._config)}setupLogLevel(s){zT(s)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(s,i){return this._engine.addNewProbe(s,i)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(s){this._engine.removeExistingProbe(s)}set onresult(s){s?this._engine.registerCallback("onresult",s):this._engine.unregisterCallback("onresult")}}function $v(c,s){return Object.keys(c).filter(i=>s.includes(i)).reduce((i,l)=>{const o=l;return{...i,[o]:c[o]}},{})}const Hv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class Fv{constructor(s){this.intervals={},this.emitInterval=s.emitInterval||200,this.onChangeFunction=s.onChangeFunction}start(s,i){s&&s.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(s,i))}stop(s){this.clearVolumeInterval(s)}clearVolumeInterval(s){console.log("clearVolumeInterval",s),clearInterval(this.intervals[s]),delete this.intervals[s]}clearAllIntervals(){Object.keys(this.intervals).forEach(s=>{clearInterval(this.intervals[s])}),this.intervals={}}beginCalculation(s,i){this.clearVolumeInterval(i);const l=dn.createAnalyser(),o=dn.createMediaStreamSource(s),_=dn.createScriptProcessor(2048,1,1);l.smoothingTimeConstant=.8,l.fftSize=1024,o.connect(l),l.connect(_),_.connect(dn.destination),this.intervals[i]=setInterval(()=>{const e=new Uint8Array(l.frequencyBinCount);l.getByteFrequencyData(e);let p=0;const g=e.length;for(let v=0;v<g;v++)p+=e[v];const n=p/g;this.onChangeFunction(i,n)},this.emitInterval)}}const Ro={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},jv=0;class qv{constructor(s){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=s,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new Fv({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(s){this.currentActiveRoomIdValue=s,this.context.emit("currentActiveRoomChanged",s)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(s){this.isCallAddingInProgress=s,this.context.emit("callAddingInProgressChanged",s)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(s=>s.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(s=>s.kind==="audiooutput")}get getUserMediaConstraints(){return S_()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(s){this.availableMediaDevices=s,this.context.emit("changeAvailableDeviceList",s)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}async initializeMediaDevices(){const s=localStorage.getItem(Ro.SELECTED_INPUT_DEVICE)||"default",i=localStorage.getItem(Ro.SELECTED_OUTPUT_DEVICE)||"default";try{const l=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),o=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(o),await this.setMicrophone(s),await this.setSpeaker(i),navigator.mediaDevices.addEventListener("devicechange",async()=>{const _=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(_)}),l.getTracks().forEach(_=>_.stop())}catch(l){console.error(l)}}setCallTime(s){const i={...s};delete i.callId,this.callTime={...this.callTime,[s.callId]:i},this.context.emit("changeCallTime",this.callTime)}removeCallTime(s){const i={...this.callTime};delete i[s],this.callTime={...i},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(s,i){this.timeIntervals={...this.timeIntervals,[s]:i}}removeTimeInterval(s){const i={...this.timeIntervals};i[s]&&(clearInterval(i[s]),delete i[s],this.timeIntervals={...i})}stopCallTimer(s){this.removeTimeInterval(s),this.removeCallTime(s)}emitVolumeChange(s,i){this.context.emit("changeCallVolume",{callId:s,volume:i})}setMetricsConfig(s){this.metricConfig={...this.metricConfig,...s}}sendDTMF(s,i){if(!/^[A-D0-9]+$/g.test(i))throw new Error("Not allowed character in DTMF input");this.extendedCalls[s].sendDTMF(i)}setIsMuted(s){this.muted=s,this.context.emit("changeIsMuted",s)}processMute(s){const i=this.currentActiveRoomId;this.setIsMuted(s),this.initialStreamValue.getTracks().forEach(l=>l.enabled=!s),this.roomReconfigure(i)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:s,toHold:i,automatic:l}){const o=this.extendedCalls[s];o._automaticHold=l??!1,await new Promise(p=>{const g=()=>{p()};i?o.hold({},g):o.unhold({},g)}),this.updateCall(o);const e=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(i?s!==p._id:!0));e.length>1&&await this.doConference(e)}holdCall(s,i=!1){return this.processHold({callId:s,automatic:i,toHold:!0})}unholdCall(s){return this.processHold({callId:s,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(s=>s.direction==="outgoing"&&s.status===jv).forEach(s=>this.terminateCall(s._id))}answerCall(s){const i=this.extendedCalls[s];this.cancelAllOutgoingUnanswered(),i.answer(this.sipOptions),this.updateCall(i),this.setActiveRoom(i.roomId),i.connection.addEventListener("track",l=>{this.triggerAddStream(l,i)})}async moveCall(s,i){this.updateCallStatus({callId:s,isMoving:!0}),await this.processRoomChange({callId:s,roomId:i}),this.updateCallStatus({callId:s,isMoving:!1})}updateCall(s){this.activeCalls[s._id]=T_(s),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(s){const l={...this.activeRooms[s.roomId],...s};this.activeRooms={...this.activeRooms,[s.roomId]:{...l}},this.context.emit("updateRoom",{room:l,roomList:this.activeRooms})}hasAutoAnswerHeaders(s){const i=/answer-after=0/,o=s.request.getHeader("Call-Info");return o&&i.test(o)}addCall(s,i=!0){this.activeCalls={...this.activeCalls,[s._id]:T_(s)},this.extendedCalls[s._id]=s,i&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(s){this.callStatus={...this.callStatus,[s]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(s){const l={...{...this.callStatus[s.callId]}};s.isMoving!==void 0&&(l.isMoving=s.isMoving),s.isTransferring!==void 0&&(l.isTransferring=s.isTransferring),s.isMerging!==void 0&&(l.isMerging=s.isMerging),this.callStatus={...this.callStatus,[s.callId]:{...l}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(s){const i={...this.callStatus};delete i[s],this.callStatus={...i},this.context.emit("changeCallStatus",this.callStatus)}addRoom(s){this.activeRooms={...this.activeRooms,[s.roomId]:s},this.context.emit("addRoom",{room:s,roomList:this.activeRooms})}getActiveStream(){const s=E_(this.initialStreamValue,this.microphoneInputLevel*2);return s.getTracks().forEach(i=>i.enabled=!this.isMuted),this.setActiveStream(s),s}async setMicrophone(s){if(!this.getInputDeviceList.find(({deviceId:l})=>l===s)||(this.setSelectedInputDevice(s),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const i=Object.values(this.extendedCalls).filter(l=>l.roomId===this.currentActiveRoomId);i.length===1?Object.values(i).forEach(async l=>{const o=this.getActiveStream();l.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.updateCall(l)}):await this.doConference(i)}setActiveStream(s){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(s,"origin"),this.activeStreamValue=s,this.context.emit("changeActiveStream",s)}async setSpeaker(s){if(!this.getOutputDeviceList.find(({deviceId:o})=>o===s))return;this.setSelectedOutputDevice(s);const i=Object.values(this.extendedCalls);if(i.length===0)return;const l=i.filter(o=>o.roomId===this.currentActiveRoomId);l.length===1?i.forEach(o=>{var _;(_=o.audioTag)==null||_.setSinkId(s),this.updateCall(o)}):await this.doConference(l)}removeRoom(s){const i={...this.activeRooms},l={...i[s]};delete i[s],this.activeRooms={...i},this.context.emit("removeRoom",{room:l,roomList:this.activeRooms})}deleteRoomIfEmpty(s){s!==void 0&&Object.values(this.extendedCalls).filter(i=>i.roomId===s).length===0&&(this.removeRoom(s),this.currentActiveRoomId===s&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(s){this.muted?s.mute({audio:!0}):s.unmute({audio:!0})}async roomReconfigure(s){var l;if(s===void 0)return;const i=Object.values(this.extendedCalls).filter(o=>o.roomId===s);if(this.currentActiveRoomId===s?i.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):i.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),i.length===0)this.deleteRoomIfEmpty(s);else if(i.length===1&&this.currentActiveRoomId!==s)i[0].isOnHold().local||await this.holdCall(i[0].id,!0);else if(i.length===1&&this.currentActiveRoomId===s){if(i[0].isOnHold().local&&i[0]._automaticHold&&await this.unholdCall(i[0].id),i[0].connection&&((l=i[0].connection)!=null&&l.getSenders()[0])){const o=this.getActiveStream();await i[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(i[0])}}else i.length>1&&await this.doConference(i)}async doConference(s){const i=[];s.forEach(l=>{l!=null&&l.connection.getReceivers().forEach(o=>{i.push(o.track)})}),await KT.forEach(s,async l=>{var e;if(l==null)return;const o=new MediaStream,_=dn.createMediaStreamDestination();if(l.connection.getReceivers().forEach(p=>{i.forEach(g=>{o.addTrack(p.track),p.track.id!==g.id&&dn.createMediaStreamSource(new MediaStream([g])).connect(_)})}),s[0].roomId===this.currentActiveRoomId){const p=this.getActiveStream();dn.createMediaStreamSource(p).connect(_)}(e=l.connection)!=null&&e.getSenders()[0]&&(await l.connection.getSenders()[0].replaceTrack(_.stream.getTracks()[0]),this.muteReconfigure(l))})}processCallerMute(s,i){const l=this.extendedCalls[s];l&&l.connection.getReceivers().length&&(l.localMuted=i,l.connection.getReceivers().forEach(o=>{o.track.enabled=!i}),this.updateCall(l))}muteCaller(s){this.processCallerMute(s,!0)}unmuteCaller(s){this.processCallerMute(s,!1)}terminateCall(s){const i=this.extendedCalls[s];i._status!==8&&i.terminate()}transferCall(s,i){if(i.toString().length===0)return new Error("Target must be passed");const l=this.extendedCalls[s];if(!l._is_confirmed&&!l._is_canceled){const o=`sip:${i}@${this.context.sipDomain}`;l.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${o}`]});return}this.updateCallStatus({callId:s,isTransferring:!0}),l.refer(`sip:${i}@${this.context.sipDomain}`),this.updateCall(l)}mergeCall(s){const i=Object.values(this.extendedCalls).filter(_=>_.roomId===s);if(i.length!==2)return;const l=i[0],o=i[1];!l||!o||(this.updateCallStatus({callId:l._id,isMerging:!0}),this.updateCallStatus({callId:o._id,isMerging:!0}),l.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(l))}mergeCallByIds(s,i){const l=Object.values(this.extendedCalls).find(_=>_._id===s),o=Object.values(this.extendedCalls).find(_=>_._id===i);if(!l||!o)throw new Error("Call ID is not provided");this.updateCallStatus({callId:s,isMerging:!0}),this.updateCallStatus({callId:i,isMerging:!0}),l.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(l)}setDND(s){this.isDNDEnabled=s,this.context.emit("changeIsDND",s)}startCallTimer(s){this.removeTimeInterval(s);const i={callId:s,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(i);const l=setInterval(()=>{const o={...this.callTime[s]},_=WT(o);this.setCallTime({callId:s,..._})},1e3);this.setTimeInterval(s,l)}async setActiveRoom(s){const i=this.currentActiveRoomId;s!==i&&(this.currentActiveRoomId=s,await this.roomReconfigure(i),await this.roomReconfigure(s))}getNewRoomId(){const s=Object.keys(this.activeRooms);return s.length===0?1:parseInt(s.sort()[s.length-1])+1}async setupCall(s){var n,v;const i=s.session;if(this.getActiveCalls[i.id]!==void 0)return;const o=this.getNewRoomId(),_={started:new Date,incomingInProgress:!1,roomId:o};i.direction==="incoming"?(this.context.logger.log("New incoming call from",(v=(n=i._remote_identity)==null?void 0:n._uri)==null?void 0:v._user),_.incomingInProgress=!0,this.context.subscribe(Yt.CALL_CONFIRMED,S=>{i.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.startCallTimer(i.id))}),this.context.subscribe(Yt.CALL_FAILED,S=>{i.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.deleteRoomIfEmpty(o))})):i.direction==="outgoing"&&(i.once("confirmed",()=>{this.startCallTimer(i.id)}),this.startCallTimer(i.id));const e=i,p=this.hasAutoAnswerHeaders(s),g=e.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);e.roomId=o,e.localMuted=!1,e.autoAnswer=g,g?this.addCall(e,!1):this.addCall(e),this.addCallStatus(i.id),this.addRoom(_),g&&this.answerCall(e._id)}removeCall(s){const i={...this.activeCalls};delete i[s],this.activeCalls={...i};const l={...this.extendedCalls};delete l[s],this.extendedCalls={...l},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(s){var o;const i=this.extendedCalls[s._id];this.stopVUMeter("origin"),(o=i.connection)==null||o.getSenders().forEach(_=>{_.track.stop()});const l=i.roomId;this.removeCall(s._id),this.roomReconfigure(l)}async newRTCSessionCallback(s){const i=s.session;if(this.isDND){i.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Yt.NEW_CALL,session:i,event:s}),i.on("ended",l=>{var _,e,p;this.stopVUMeter(i.id),this.context.logger.log("Session ended for",(e=(_=i._remote_identity)==null?void 0:_._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Yt.CALL_ENDED,session:i,event:l});const o=this.getActiveCalls[i.id];o&&this.activeCallListRemove(o),this.stopCallTimer(i.id),this.removeCallStatus(i.id),this.removeCallMetrics(i.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(g=>g.stop()),this.initialStreamValue=null)}),i.on("progress",l=>{var o,_;this.context.logger.log("Session in progress for",(_=(o=i._remote_identity)==null?void 0:o._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Yt.CALL_PROGRESS,session:i,event:l})}),i.on("failed",l=>{var _,e,p;this.stopVUMeter(i.id),this.context.logger.log("Session failed for",(e=(_=i._remote_identity)==null?void 0:_._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Yt.CALL_FAILED,session:i,event:l}),i.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const o=this.getActiveCalls[i.id];o&&this.activeCallListRemove(o),this.stopCallTimer(i.id),this.removeCallStatus(i.id),this.removeCallMetrics(i.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(g=>g.stop()),this.initialStreamValue=null)}),i.on("confirmed",l=>{var o,_;this.context.logger.log("Session confirmed for",(_=(o=i._remote_identity)==null?void 0:o._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Yt.CALL_CONFIRMED,session:i,event:l}),this.updateCall(i),i.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(s),i.direction==="outgoing"){const l=this.getActiveCalls[i.id].roomId;this.setActiveRoom(l)}}setMuteWhenJoin(s){this.muteWhenJoinEnabled=s,this.context.emit("changeMuteWhenJoin",s)}setMicrophoneSensitivity(s){if(s<0||s>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=s,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(s){this.speakerVolumeValue=s,Object.values(this.extendedCalls).forEach(i=>{i.audioTag&&(i.audioTag.volume=s,this.updateCall(i))})}setAutoAnswer(s){this.isAutoAnswer=s}setSelectedInputDevice(s){localStorage.setItem(Ro.SELECTED_INPUT_DEVICE,s),this.selectedMediaDevices.input=s,this.context.emit("changeActiveInputMediaDevice",s)}setSelectedOutputDevice(s){localStorage.setItem(Ro.SELECTED_OUTPUT_DEVICE,s),this.selectedMediaDevices.output=s,this.context.emit("changeActiveOutputMediaDevice",s)}setCallMetrics(s){const i={...s};delete i.callId,this.callMetrics={...this.callMetrics,[s.callId]:i},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(s){const i={...this.callMetrics};delete i[s],this.callMetrics={...i},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(s){const i=new Lv(this.metricConfig),l=i.createProbe(s.connection,{cid:s._id}),o=[];let _;l.onreport=e=>{Object.entries(e.audio).forEach(([n,v])=>{v.direction==="inbound"&&!o.includes(n)&&(o.push(n),_=n)});const p=e.audio[_];if(!p)return;const g=$v(p,Hv);g.callId=s._id,this.setCallMetrics(g)},this.context.subscribe(Yt.CALL_ENDED,e=>{e._id===s._id&&i.stopAllProbes()}),i.startAllProbes()}setupVUMeter(s,i){this.VUMeter.start(s,i)}stopVUMeter(s){this.VUMeter.stop(s)}async setupStream(){const s=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(i=>i.stop()),this.initialStreamValue=null),this.initialStreamValue=s}async triggerAddStream(s,i){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const l=E_(this.initialStreamValue,this.microphoneInputLevel*2),o=this.isMuted||this.muteWhenJoin;l.getTracks().forEach(e=>e.enabled=!o),this.setActiveStream(l),await i.connection.getSenders()[0].replaceTrack(l.getTracks()[0]);const _=new MediaStream([s.track]);NT(_,i,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(_,i._id),this.getCallQuality(i),this.updateCall(i)}initCall(s,i){if(s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`);const l=this.context.call(`sip:${s}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=l.id,i&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:l.id,roomId:this.currentActiveRoomId}),l.connection.addEventListener("track",o=>{this.triggerAddStream(o,l)})}async processRoomChange({callId:s,roomId:i}){const l=this.extendedCalls[s].roomId;this.extendedCalls[s].roomId=i;const o=this.extendedCalls[s];return this.updateCall(o),await this.setActiveRoom(i),Promise.all([this.roomReconfigure(l),this.roomReconfigure(i)]).then(()=>{this.deleteRoomIfEmpty(l),this.deleteRoomIfEmpty(i)})}}class Vv{constructor(s){this.context=s}get sipOptions(){return{...this.context.options.sipOptions}}initCall(s,i){if(s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${s}@${this.context.sipDomain}`,i,this.sipOptions)}stop(s={}){this.context.terminateJanusSessions(s)}}class Bv{constructor(s){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=s,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(s){const i=this.extendedMessages[s];this.updateMSRPSession(i)}updateMSRPSession(s){this.activeMessages[s._id]=v_(s),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(s){this.activeMessages={...this.activeMessages,[s._id]:v_(s)},this.extendedMessages[s._id]=s,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(s,i){const l=this.msrpHistory[i.id]||[];l.push(s),this.msrpHistory={...this.msrpHistory,[i.id]:[...l]},this.context.emit("newMSRPMessage",{message:s,session:i})}messageTerminate(s){const i=this.extendedMessages[s];i._status!==8&&i.terminate()}addMessageSession(s){if(!s._id||this.getActiveMessages[s._id]!==void 0)return;const l=s;this.addMMSRPSession(l)}triggerMSRPListener({listenerType:s,session:i,event:l}){const o=this.context.listenersList[s];!o||!o.length||o.forEach(_=>{_(i,l)})}removeMMSRPSession(s){const i={...this.activeMessages};delete i[s],this.activeMessages={...i};const l={...this.extendedMessages};delete l[s],this.extendedMessages={...l},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(s){this.removeMMSRPSession(s._id)}newMSRPSessionCallback(s){const i=s.session;i.on("ended",l=>{this.triggerMSRPListener({listenerType:Yt.CALL_ENDED,session:i,event:l});const o=this.getActiveMessages[i.id];this.activeMessageListRemove(o)}),i.on("failed",l=>{this.triggerMSRPListener({listenerType:Yt.CALL_FAILED,session:i,event:l});const o=this.getActiveMessages[i.id];this.activeMessageListRemove(o)}),i.on("confirmed",l=>{this.triggerMSRPListener({listenerType:Yt.CALL_CONFIRMED,session:i,event:l}),this.updateMSRPSession(i)}),i.on("newMessage",l=>{this.addMSRPMessage(l,i)}),this.addMessageSession(i)}setIsMSRPInitializing(s){this.isMSRPInitializingValue=s,this.context.emit("isMSRPInitializingChanged",s)}initMSRP(s,i,l){if(s.length===0)return console.error("Target must be a valid string");const o=this.context.startMSRP(s,l);o.on("active",()=>{this.addMessageSession(o),o.sendMSRP(i),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(s,i){const l=this.extendedMessages[s];if(!l)throw new Error(`MSRP session with id ${s} doesn't exist!`);l.sendMSRP(i)}}const ku={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Gv extends CT{constructor(s,i){if(!s.modules.length)throw new Error("options.modules should include at least 1 module");const l={...s.configuration,sockets:s.socketInterfaces.map(o=>new GT.WebSocketInterface(o))};super(l),this.initialized=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],s.pnExtraHeaders&&Object.keys(s.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(s.pnExtraHeaders),this.options=s,this.modules=s.modules,i&&UT(i)&&(this.logger=i)}on(s,i){return super.on(s,i)}off(s,i){return super.off(s,i)}emit(s,i){return super.emit(s,i)}get sipDomain(){return this.options.sipDomain}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(ku.AUDIO)&&(this.audio=new qv(this)),this.modules.includes(ku.MSRP)&&(this.msrp=new Bv(this)),this.modules.includes(ku.VIDEO)&&(this.video=new Vv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}subscribe(s,i){const o=!this.listenersList[s]||!this.listenersList[s].length?[i]:[...this.listenersList[s],i];this.listenersList={...this.listenersList,[s]:o}}removeIListener(s){const i={...this.listenersList};delete i[s],this.listenersList={...i}}triggerListener({listenerType:s,session:i,event:l}){const o=this.listenersList[s];!o||!o.length||o.forEach(_=>{_(i,l)})}setInitialized(s){this.initialized=s,this.emit("ready",s)}}return Gv});
|
158
|
+
`,i),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?i=o+2:l=o}return l}function ET(c,s,i,l){let o;const _=s.indexOf(":",i),e=s.substring(i,_).trim(),p=s.substring(_+1,l).trim();switch(e.toLowerCase()){case"via":case"v":c.addHeader("via",p),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",p),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",p),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=Ou.parse(p,"Record_Route"),o===-1)o=void 0;else for(const g of o)c.addHeader("record-route",p.substring(g.possition,g.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=g.parsed;break;case"call-id":case"i":c.setHeader("call-id",p),o=c.parseHeader("call-id"),o&&(c.call_id=p);break;case"contact":case"m":if(o=Ou.parse(p,"Contact"),o===-1)o=void 0;else for(const g of o)c.addHeader("contact",p.substring(g.possition,g.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=g.parsed;break;case"content-length":case"l":c.setHeader("content-length",p),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",p),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",p),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof un.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",p),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",p),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",p),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",p),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",p),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",p),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",p),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(e,p),o=0}return o===void 0?{error:`error parsing header "${e}"`}:!0}const ST={parseMessage:TT},Yr=new eo("Registrator"),So=10;class yT{constructor(s,i){this._reg_id=1,this._ua=s,this._transport=i,this._registrar=s.configuration.registrar_server,this._expires=s.configuration.register_expires,this._call_id=vs.createRandomToken(22),this._cseq=0,this._to_uri=s.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const l=this._contact.indexOf(">");if(l!==-1){const o=this._contact.slice(0,l)+this._contact.slice(l+1,this._contact.length);this._contact=o}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(s){Array.isArray(s)||(s=[]),this._extraHeaders=s.slice()}setExtraContactParams(s){s instanceof Object||(s={}),this._extraContactParams="";for(const i in s)if(Object.prototype.hasOwnProperty.call(s,i)){const l=s[i];this._extraContactParams+=`;${i}`,l&&(this._extraContactParams+=`=${l}`)}}setExtraContactUriParams(s){s instanceof Object||(s={}),this._extraContactParams="";for(const i in s)if(Object.prototype.hasOwnProperty.call(s,i)){const l=s[i];this._extraContactParams+=`;${i}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){Yr.debug("Register request in progress...");return}const s=this._extraHeaders.slice();s.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),s.push(`Expires: ${this._expires}`);const i=new bt.OutgoingRequest(F.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},s),l=new ro(this._ua,i,{onRequestTimeout:()=>{this._registrationFailure(null,F.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,F.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:o=>{if(o.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):{if(this._registering=!1,!o.hasHeader("Contact")){Yr.debug("no Contact header in response to REGISTER, response ignored");break}const _=o.headers.Contact.reduce((n,v)=>n.concat(v.parsed),[]);let e=_.find(n=>this._sipInstance===n.getParam("+sip.instance")&&this._reg_id===parseInt(n.getParam("reg-id")));if(e||(e=_.find(n=>n.uri.user===this._ua.contact.uri.user)),!e){Yr.debug("no Contact header pointing to us, response ignored");break}let p=e.getParam("expires");!p&&o.hasHeader("expires")&&(p=o.getHeader("expires")),p||(p=this._expires),p=Number(p),p<So&&(p=So);const g=p>64?p*1e3/2+Math.floor((p/2-32)*1e3*Math.random()):p*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},g),e.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=e.getParam("temp-gruu").replace(/"/g,"")),e.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=e.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:o}));break}case/^423$/.test(o.status_code):{o.hasHeader("min-expires")?(this._expires=Number(o.getHeader("min-expires")),this._expires<So&&(this._expires=So),this.register()):(Yr.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(o,F.causes.SIP_FAILURE_CODE));break}default:{const _=vs.sipErrorCause(o.status_code);this._registrationFailure(o,_)}}}});this._registering=!0,l.send()}unregister(s={}){if(!this._registered){Yr.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const i=this._extraHeaders.slice();s.all?i.push(`Contact: *${this._extraContactParams}`):i.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),i.push("Expires: 0");const l=new bt.OutgoingRequest(F.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},i);new ro(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,F.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,F.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:_=>{switch(!0){case/^1[0-9]{2}$/.test(_.status_code):break;case/^2[0-9]{2}$/.test(_.status_code):this._unregistered(_);break;default:{const e=vs.sipErrorCause(_.status_code);this._unregistered(_,e)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(s,i){this._registering=!1,this._ua.registrationFailed({response:s||null,cause:i}),this._registered&&(this._registered=!1,this._ua.unregistered({response:s||null,cause:i}))}_unregistered(s,i){this._registering=!1,this._registered=!1,this._ua.unregistered({response:s||null,cause:i||null})}}const _t=console,$s={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},AT=uT;class CT extends AT{constructor(s){super(s),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this._registrator=new yT(this)}call(s,i){return super.call(s,i)}joinVideoCall(s,i,l){_t.debug("call()");const o=new vo(this);return o.connect(s,i,l),o}_loadConfig(s){try{Kr.load(this._configuration,s)}catch(o){throw o}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=vs.newUUID()),this._configuration.jssip_id=vs.createRandomToken(5);const i=this._configuration.uri.clone();i.user=null,this._configuration.hostport_params=i.toString().replace(/^sip:/i,"");try{this._transport=new Mg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=RT.bind(this),this._transport.onconnect=IT.bind(this),this._transport.ondisconnect=bT.bind(this),this._transport.ondata=wT.bind(this)}catch(o){throw _t.warn(o),new xs.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const o=this._configuration.uri.clone();o.user=null,o.clearParams(),o.clearHeaders(),this._configuration.registrar_server=o}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Yn("sip",vs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(o={}){const _=o.anonymous||null,e=o.outbound||null;let p="<";return _?p+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":p+=this.pub_gruu||this.uri.toString(),e&&(_?!this.temp_gruu:!this.pub_gruu)&&(p+=";ob"),p+=">",p}};const l=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const o in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,o)&&(l.indexOf(o)!==-1?Object.defineProperty(this._configuration,o,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,o,{writable:!1,configurable:!1}));_t.debug("configuration parameters after validation:");for(const o in this._configuration)if(Object.prototype.hasOwnProperty.call(Kr.settings,o))switch(o){case"uri":case"registrar_server":_t.debug(`- ${o}: ${this._configuration[o]}`);break;case"password":case"ha1":case"authorization_jwt":_t.debug(`- ${o}: NOT SHOWN`);break;default:_t.debug(`- ${o}: ${JSON.stringify(this._configuration[o])}`)}}newMSRPSession(s,i){s.on("msgHistoryUpdate",l=>{console.log(l)}),this._msrp_sessions[s.id]=s,this.emit("newMSRPSession",i)}newJanusSession(s,i){this._janus_sessions[s.id]=s,this.emit("newJanusSession",i)}destroyMSRPSession(s){delete this._msrp_sessions[s.id]}destroyJanusSession(s){delete this._janus_sessions[s.id]}receiveRequest(s){var _,e,p,g;const i=s.method;if(console.log("-----------"),s.ruri.user!==this._configuration.uri.user&&s.ruri.user!==this._contact.uri.user){_t.debug("Request-URI does not point to us"),s.method!==xe.ACK&&s.reply_sl(404);return}if(s.ruri.scheme===xe.SIPS){s.reply_sl(416);return}if(jt.checkTransaction(this,s))return;if(i===xe.INVITE?new jt.InviteServerTransaction(this,this._transport,s):i!==xe.ACK&&i!==xe.CANCEL&&new jt.NonInviteServerTransaction(this,this._transport,s),i===xe.OPTIONS){if(this.listeners("newOptions").length===0){s.reply(200);return}new yf.Options(this).init_incoming(s)}else if(i===xe.MESSAGE){if(this.listeners("newMessage").length===0){s.reply(405);return}new yf.Message(this).init_incoming(s)}else if(i===xe.INVITE&&!s.to_tag&&this.listeners("newRTCSession").length===0){s.reply(405);return}let l,o;if(s.to_tag)if(l=this._findDialog(s.call_id,s.from_tag,s.to_tag),l)l.receiveRequest(s);else if(i===xe.NOTIFY)if(o=this._findSession(s),o)o.receiveRequest(s);else{if(s.body)try{const n=JSON.parse(s.body)||{};(e=(_=n.plugindata)==null?void 0:_.data)!=null&&e.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(n),(g=(p=n.plugindata)==null?void 0:p.data)!=null&&g.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(n.plugindata.data.unpublished)}catch(n){console.error(n)}s.reply(200)}else i!==xe.ACK&&s.reply(481);else switch(i){case xe.INVITE:if(window.RTCPeerConnection)if(s.hasHeader("replaces")){const n=s.replaces;l=this._findDialog(n.call_id,n.from_tag,n.to_tag),l?(o=l.owner,o.isEnded()?s.reply(603):o.receiveRequest(s)):s.reply(481)}else s.body.search(/MSRP/ig)>-1?(o=new wu(this),o.init_incoming(s)):s.body.search(/JANUS/ig)>-1||(o=new vg(this),o.init_incoming(s));else _t.warn("INVITE received but WebRTC is not supported"),s.reply(488);break;case xe.BYE:s.reply(481);break;case xe.CANCEL:o=this._findSession(s),o?o.receiveRequest(s):_t.debug("received CANCEL request for a non existent session");break;case xe.ACK:break;case xe.NOTIFY:this.emit("sipEvent",{event:s.event,request:s}),s.reply(200);break;default:s.reply(405);break}}startMSRP(s,i){_t.debug("startMSRP()",i);const l=new wu(this);return l.connect(s),l}startJanus(s,i){_t.debug("startJanus()",i);const l=new wu(this);return l.connect(s),l}terminateMSRPSessions(s){_t.debug("terminateSessions()");for(const i in this._msrp_sessions)this._msrp_sessions[i].isEnded()||this._msrp_sessions[i].terminate(s)}terminateJanusSessions(s){_t.debug("terminateSessions()");for(const i in this._janus_sessions)this._janus_sessions[i].isEnded()||this._janus_sessions[i].terminate(s)}stop(){if(_t.debug("stop()"),this._dynConfiguration={},this._status===$s.STATUS_USER_CLOSED){_t.debug("UA already closed");return}this._registrator.close();const s=Object.keys(this._sessions).length;for(const l in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,l)){_t.debug(`closing session ${l}`);try{this._sessions[l].terminate()}catch(o){console.error(o)}}for(const l in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,l)){_t.debug(`closing session ${l}`);try{this._msrp_sessions[l].terminate()}catch(o){console.error(o)}}for(const l in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,l)){_t.debug(`closing session ${l}`);try{this._janus_sessions[l].terminate()}catch(o){console.error(o)}}for(const l in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,l))try{this._applicants[l].close()}catch(o){console.error(o)}this._status=$s.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function RT(c){this.emit("connecting",c)}function IT(c){this._status!==$s.STATUS_USER_CLOSED&&(this._status=$s.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function bT(c){const s=["nict","ict","nist","ist"];for(const i of s)for(const l in this._transactions[i])Object.prototype.hasOwnProperty.call(this._transactions[i],l)&&this._transactions[i][l].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==$s.STATUS_USER_CLOSED&&(this._status=$s.STATUS_NOT_READY,this._error=$s.NETWORK_ERROR)}function wT(c){console.log("onTransportData",c);const s=c.transport;let i=c.message;if(i=ST.parseMessage(i,this),!i){console.log("if 1 return");return}if(this._status===$s.STATUS_USER_CLOSED&&i instanceof un.IncomingRequest){console.log("if 2 return");return}if(!zg(i,this,s)){console.log("if 3 return");return}if(console.log("onTransportData message",i),console.log("onTransportData instanceof",i instanceof un.IncomingRequest),i instanceof un.IncomingRequest)i.transport=s,console.log("onTransportData receiveRequest"),this.receiveRequest(i);else if(i instanceof un.IncomingResponse){let l;switch(i.method){case xe.INVITE:l=this._transactions.ict[i.via_branch],l&&l.receiveResponse(i);break;case xe.ACK:break;default:l=this._transactions.nict[i.via_branch],l&&l.receiveResponse(i);break}}}const OT=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer"],DT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function T_(c){const s={};return OT.forEach(i=>{c[i]!==void 0&&(s[i]=c[i])}),s.localHold=c._localHold,s}function v_(c){const s={};return DT.forEach(i=>{c[i]!==void 0&&(s[i]=c[i])}),s}function E_(c,s){const i=new AudioContext,l=i.createMediaStreamSource(c),o=i.createMediaStreamDestination(),_=i.createGain();return l.connect(_),_.connect(o),_.gain.value=s,o.stream}function NT(c,s,i,l){const o=document.createElement("audio");o.id=s._id,o.className="audioTag",o.srcObject=c,S_()||(o.setSinkId(i),o.volume=l),o.play(),s.audioTag=o}function UT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function S_(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const PT=ut,xT=Wt(),Pt=new PT("WebSocketInterface");var MT=class{constructor(s){Pt.debug('new() [url:"%s"]',s),this._url=s,this._sip_uri=null,this._via_transport=null,this._ws=null;const i=xT.parse(s,"absoluteURI");if(i===-1)throw Pt.warn(`invalid WebSocket URI: ${s}`),new TypeError(`Invalid argument: ${s}`);if(i.scheme!=="wss"&&i.scheme!=="ws")throw Pt.warn(`invalid WebSocket URI scheme: ${i.scheme}`),new TypeError(`Invalid argument: ${s}`);this._sip_uri=`sip:${i.host}${i.port?`:${i.port}`:""};transport=ws`,this._via_transport=i.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(s){this._via_transport=s.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Pt.debug("connect()"),this.isConnected()){Pt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Pt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Pt.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(s){this._onError(s)}}disconnect(){Pt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(s){return Pt.debug("send()"),this.isConnected()?(this._ws.send(s),!0):(Pt.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Pt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:s,code:i,reason:l}){Pt.debug(`WebSocket ${this._url} closed`),s===!1&&Pt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!s,i,l)}_onMessage({data:s}){Pt.debug("received WebSocket message"),this.ondata(s)}_onError(s){Pt.warn(`WebSocket ${this._url} error: `,s)}};const Du=pl,kT=xe,LT=Ts,$T=Tt(),HT=p_,FT=ps(),jT=Xa(),qT=Wt(),VT=MT;Hn("JsSIP")("version %s",Du.version);var BT={C:kT,Exceptions:LT,Utils:$T,UA:HT,URI:FT,NameAddrHeader:jT,WebSocketInterface:VT,Grammar:qT,debug:Hn,get name(){return Du.title},get version(){return Du.version}};const GT=ke(BT);function Nu(c){return c<10?`0${c}`:`${c}`}function WT(c){let s=c.hours||0,i=c.minutes||0,l=c.seconds||0;l++,l===60&&(l=0,i++,i===60&&(i=0,s++));const o=`${Nu(s)}:${Nu(i)}:${Nu(l)}`;return{seconds:l,minutes:i,hours:s,formatted:o}}var At={};At.forEach=async(c,s,i)=>{const l=[];for(let o=0;o<c.length;o++)if(o in c){const _=Promise.resolve(c[o]).then(e=>s.call(i||globalThis,e,o,c));l.push(_)}await Promise.all(l)},At.forEachSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)l in c&&await s.call(i||globalThis,await c[l],l,c)},At.map=async(c,s,i)=>{const l=[];for(let o=0;o<c.length;o++)o in c&&(l[o]=Promise.resolve(c[o]).then(_=>s.call(i||globalThis,_,o,c)));return Promise.all(l)},At.mapSeries=async(c,s,i)=>{const l=[];for(let o=0;o<c.length;o++)o in c&&(l[o]=await s.call(i||globalThis,await c[o],o,c));return l},At.find=(c,s,i)=>new Promise((l,o)=>{if(c.length===0)return l();let _=1;for(let e=0;e<c.length;e++){const p=g=>{g?l(c[e]):_===c.length&&l(),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(o)}}),At.findSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(await s.call(i||globalThis,await c[l],l,c))return c[l]},At.findIndex=(c,s,i)=>new Promise((l,o)=>{if(c.length===0)return l(-1);let _=1;for(let e=0;e<c.length;e++){const p=g=>{g?l(e):_===c.length&&l(-1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(o)}}),At.findIndexSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(await s.call(i||globalThis,await c[l],l,c))return l},At.some=(c,s,i)=>new Promise((l,o)=>{if(c.length===0)return l(!1);let _=1;for(let e=0;e<c.length;e++){if(!(e in c)){_++;continue}const p=g=>{g?l(!0):_===c.length&&l(!1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(o)}}),At.someSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(l in c&&await s.call(i||globalThis,await c[l],l,c))return!0;return!1},At.every=(c,s,i)=>new Promise((l,o)=>{if(c.length===0)return l(!0);let _=1;for(let e=0;e<c.length;e++){if(!(e in c)){_++;continue}const p=g=>{g?_===c.length&&l(!0):l(!1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(o)}}),At.everySeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(l in c&&!await s.call(i||globalThis,await c[l],l,c))return!1;return!0},At.filter=(c,s,i)=>new Promise(async(l,o)=>{const _=[];for(let p=0;p<c.length;p++)p in c&&(_[p]=Promise.resolve(c[p]).then(g=>s.call(i||globalThis,g,p,c)).catch(o));const e=[];for(let p=0;p<_.length;p++)await _[p]&&e.push(await c[p]);l(e)}),At.filterSeries=async(c,s,i)=>{const l=[];for(let o=0;o<c.length;o++)o in c&&await s.call(i||globalThis,await c[o],o,c)&&l.push(await c[o]);return l},At.reduce=async(c,s,i)=>{if(c.length===0&&i===void 0)throw TypeError("Reduce of empty array with no initial value");let l,o;for(i!==void 0?(o=i,l=0):(o=c[0],l=1),l;l<c.length;l++)l in c&&(o=await s(await o,await c[l],l,c));return o};var y_={};(function(c){const s=At;Object.keys(s).forEach(i=>{const l=i.charAt(0).toUpperCase()+i.slice(1);c[`async${l}`]=async function(...o){return s[i](this,...o)}})})(y_);var KT=Object.assign(At,{instanceMethods:y_});const dn=new AudioContext,Yt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var YT={exports:{}};(function(c){var s=function(i){var l=Object.prototype,o=l.hasOwnProperty,_=Object.defineProperty||function(N,z,re){N[z]=re.value},e,p=typeof Symbol=="function"?Symbol:{},g=p.iterator||"@@iterator",n=p.asyncIterator||"@@asyncIterator",v=p.toStringTag||"@@toStringTag";function S(N,z,re){return Object.defineProperty(N,z,{value:re,enumerable:!0,configurable:!0,writable:!0}),N[z]}try{S({},"")}catch{S=function(z,re,oe){return z[re]=oe}}function m(N,z,re,oe){var Te=z&&z.prototype instanceof ae?z:ae,De=Object.create(Te.prototype),Ce=new U(oe||[]);return _(De,"_invoke",{value:j(N,re,Ce)}),De}i.wrap=m;function C(N,z,re){try{return{type:"normal",arg:N.call(z,re)}}catch(oe){return{type:"throw",arg:oe}}}var A="suspendedStart",R="suspendedYield",I="executing",V="completed",W={};function ae(){}function x(){}function $(){}var Re={};S(Re,g,function(){return this});var be=Object.getPrototypeOf,H=be&&be(be(se([])));H&&H!==l&&o.call(H,g)&&(Re=H);var D=$.prototype=ae.prototype=Object.create(Re);x.prototype=$,_(D,"constructor",{value:$,configurable:!0}),_($,"constructor",{value:x,configurable:!0}),x.displayName=S($,v,"GeneratorFunction");function L(N){["next","throw","return"].forEach(function(z){S(N,z,function(re){return this._invoke(z,re)})})}i.isGeneratorFunction=function(N){var z=typeof N=="function"&&N.constructor;return z?z===x||(z.displayName||z.name)==="GeneratorFunction":!1},i.mark=function(N){return Object.setPrototypeOf?Object.setPrototypeOf(N,$):(N.__proto__=$,S(N,v,"GeneratorFunction")),N.prototype=Object.create(D),N},i.awrap=function(N){return{__await:N}};function q(N,z){function re(De,Ce,He,we){var Se=C(N[De],N,Ce);if(Se.type==="throw")we(Se.arg);else{var at=Se.arg,Ue=at.value;return Ue&&typeof Ue=="object"&&o.call(Ue,"__await")?z.resolve(Ue.__await).then(function(le){re("next",le,He,we)},function(le){re("throw",le,He,we)}):z.resolve(Ue).then(function(le){at.value=le,He(at)},function(le){return re("throw",le,He,we)})}}var oe;function Te(De,Ce){function He(){return new z(function(we,Se){re(De,Ce,we,Se)})}return oe=oe?oe.then(He,He):He()}_(this,"_invoke",{value:Te})}L(q.prototype),S(q.prototype,n,function(){return this}),i.AsyncIterator=q,i.async=function(N,z,re,oe,Te){Te===void 0&&(Te=Promise);var De=new q(m(N,z,re,oe),Te);return i.isGeneratorFunction(z)?De:De.next().then(function(Ce){return Ce.done?Ce.value:De.next()})};function j(N,z,re){var oe=A;return function(De,Ce){if(oe===I)throw new Error("Generator is already running");if(oe===V){if(De==="throw")throw Ce;return Dt()}for(re.method=De,re.arg=Ce;;){var He=re.delegate;if(He){var we=B(He,re);if(we){if(we===W)continue;return we}}if(re.method==="next")re.sent=re._sent=re.arg;else if(re.method==="throw"){if(oe===A)throw oe=V,re.arg;re.dispatchException(re.arg)}else re.method==="return"&&re.abrupt("return",re.arg);oe=I;var Se=C(N,z,re);if(Se.type==="normal"){if(oe=re.done?V:R,Se.arg===W)continue;return{value:Se.arg,done:re.done}}else Se.type==="throw"&&(oe=V,re.method="throw",re.arg=Se.arg)}}}function B(N,z){var re=z.method,oe=N.iterator[re];if(oe===e)return z.delegate=null,re==="throw"&&N.iterator.return&&(z.method="return",z.arg=e,B(N,z),z.method==="throw")||re!=="return"&&(z.method="throw",z.arg=new TypeError("The iterator does not provide a '"+re+"' method")),W;var Te=C(oe,N.iterator,z.arg);if(Te.type==="throw")return z.method="throw",z.arg=Te.arg,z.delegate=null,W;var De=Te.arg;if(!De)return z.method="throw",z.arg=new TypeError("iterator result is not an object"),z.delegate=null,W;if(De.done)z[N.resultName]=De.value,z.next=N.nextLoc,z.method!=="return"&&(z.method="next",z.arg=e);else return De;return z.delegate=null,W}L(D),S(D,v,"Generator"),S(D,g,function(){return this}),S(D,"toString",function(){return"[object Generator]"});function Q(N){var z={tryLoc:N[0]};1 in N&&(z.catchLoc=N[1]),2 in N&&(z.finallyLoc=N[2],z.afterLoc=N[3]),this.tryEntries.push(z)}function Z(N){var z=N.completion||{};z.type="normal",delete z.arg,N.completion=z}function U(N){this.tryEntries=[{tryLoc:"root"}],N.forEach(Q,this),this.reset(!0)}i.keys=function(N){var z=Object(N),re=[];for(var oe in z)re.push(oe);return re.reverse(),function Te(){for(;re.length;){var De=re.pop();if(De in z)return Te.value=De,Te.done=!1,Te}return Te.done=!0,Te}};function se(N){if(N){var z=N[g];if(z)return z.call(N);if(typeof N.next=="function")return N;if(!isNaN(N.length)){var re=-1,oe=function Te(){for(;++re<N.length;)if(o.call(N,re))return Te.value=N[re],Te.done=!1,Te;return Te.value=e,Te.done=!0,Te};return oe.next=oe}}return{next:Dt}}i.values=se;function Dt(){return{value:e,done:!0}}return U.prototype={constructor:U,reset:function(N){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(Z),!N)for(var z in this)z.charAt(0)==="t"&&o.call(this,z)&&!isNaN(+z.slice(1))&&(this[z]=e)},stop:function(){this.done=!0;var N=this.tryEntries[0],z=N.completion;if(z.type==="throw")throw z.arg;return this.rval},dispatchException:function(N){if(this.done)throw N;var z=this;function re(we,Se){return De.type="throw",De.arg=N,z.next=we,Se&&(z.method="next",z.arg=e),!!Se}for(var oe=this.tryEntries.length-1;oe>=0;--oe){var Te=this.tryEntries[oe],De=Te.completion;if(Te.tryLoc==="root")return re("end");if(Te.tryLoc<=this.prev){var Ce=o.call(Te,"catchLoc"),He=o.call(Te,"finallyLoc");if(Ce&&He){if(this.prev<Te.catchLoc)return re(Te.catchLoc,!0);if(this.prev<Te.finallyLoc)return re(Te.finallyLoc)}else if(Ce){if(this.prev<Te.catchLoc)return re(Te.catchLoc,!0)}else if(He){if(this.prev<Te.finallyLoc)return re(Te.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(N,z){for(var re=this.tryEntries.length-1;re>=0;--re){var oe=this.tryEntries[re];if(oe.tryLoc<=this.prev&&o.call(oe,"finallyLoc")&&this.prev<oe.finallyLoc){var Te=oe;break}}Te&&(N==="break"||N==="continue")&&Te.tryLoc<=z&&z<=Te.finallyLoc&&(Te=null);var De=Te?Te.completion:{};return De.type=N,De.arg=z,Te?(this.method="next",this.next=Te.finallyLoc,W):this.complete(De)},complete:function(N,z){if(N.type==="throw")throw N.arg;return N.type==="break"||N.type==="continue"?this.next=N.arg:N.type==="return"?(this.rval=this.arg=N.arg,this.method="return",this.next="end"):N.type==="normal"&&z&&(this.next=z),W},finish:function(N){for(var z=this.tryEntries.length-1;z>=0;--z){var re=this.tryEntries[z];if(re.finallyLoc===N)return this.complete(re.completion,re.afterLoc),Z(re),W}},catch:function(N){for(var z=this.tryEntries.length-1;z>=0;--z){var re=this.tryEntries[z];if(re.tryLoc===N){var oe=re.completion;if(oe.type==="throw"){var Te=oe.arg;Z(re)}return Te}}throw new Error("illegal catch attempt")},delegateYield:function(N,z,re){return this.delegate={iterator:se(N),resultName:z,nextLoc:re},this.method==="next"&&(this.arg=e),W}},i}(c.exports);try{regeneratorRuntime=s}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=s:Function("r","regeneratorRuntime = r")(s)}})(YT);var A_={exports:{}};(function(c){(function(s,i){c.exports?c.exports=i():s.log=i()})(Bt,function(){var s=function(){},i="undefined",l=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function _(R,I){var V=R[I];if(typeof V.bind=="function")return V.bind(R);try{return Function.prototype.bind.call(V,R)}catch{return function(){return Function.prototype.apply.apply(V,[R,arguments])}}}function e(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(R){return R==="debug"&&(R="log"),typeof console===i?!1:R==="trace"&&l?e:console[R]!==void 0?_(console,R):console.log!==void 0?_(console,"log"):s}function g(R,I){for(var V=0;V<o.length;V++){var W=o[V];this[W]=V<R?s:this.methodFactory(W,R,I)}this.log=this.debug}function n(R,I,V){return function(){typeof console!==i&&(g.call(this,I,V),this[R].apply(this,arguments))}}function v(R,I,V){return p(R)||n.apply(this,arguments)}function S(R,I,V){var W=this,ae;I=I??"WARN";var x="loglevel";typeof R=="string"?x+=":"+R:typeof R=="symbol"&&(x=void 0);function $(D){var L=(o[D]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=L;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+L+";"}catch{}}}function Re(){var D;if(!(typeof window===i||!x)){try{D=window.localStorage[x]}catch{}if(typeof D===i)try{var L=window.document.cookie,q=L.indexOf(encodeURIComponent(x)+"=");q!==-1&&(D=/^([^;]+)/.exec(L.slice(q))[1])}catch{}return W.levels[D]===void 0&&(D=void 0),D}}function be(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x);return}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}W.name=R,W.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},W.methodFactory=V||v,W.getLevel=function(){return ae},W.setLevel=function(D,L){if(typeof D=="string"&&W.levels[D.toUpperCase()]!==void 0&&(D=W.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=W.levels.SILENT){if(ae=D,L!==!1&&$(D),g.call(W,D,R),typeof console===i&&D<W.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},W.setDefaultLevel=function(D){I=D,Re()||W.setLevel(D,!1)},W.resetLevel=function(){W.setLevel(I,!1),be()},W.enableAll=function(D){W.setLevel(W.levels.TRACE,D)},W.disableAll=function(D){W.setLevel(W.levels.SILENT,D)};var H=Re();H==null&&(H=I),W.setLevel(H,!1)}var m=new S,C={};m.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var V=C[I];return V||(V=C[I]=new S(I,m.getLevel(),m.methodFactory)),V};var A=typeof window!==i?window.log:void 0;return m.noConflict=function(){return typeof window!==i&&window.log===m&&(window.log=A),m},m.getLoggers=function(){return C},m.default=m,m})})(A_);var wt=A_.exports;const Es=()=>`${new Date().toISOString()} | metrics`,Ss=(c,s,i)=>`${c} | ${s} | ${i}`;wt.setDefaultLevel(wt.levels.TRACE);const JT=c=>{wt.info(Ss(Es(),"log ",`set log level to ${c?"verbose":"info"}`)),wt.setLevel(c?wt.levels.TRACE:wt.levels.INFO)},zT=c=>{const s=[...Object.keys(wt.levels)];s.includes(c)?(wt.info(Ss(Es(),"log ",`update log level to ${c.toLowerCase()}`)),wt.setLevel(c)):wt.warn(Ss(Es(),"log ","Incorrect log level please choose one of "),s)},Le=(c,s,i)=>{i?wt.debug(Ss(Es(),c,s),i):wt.debug(Ss(Es(),c,s))},Uu=(c,s)=>{wt.info(Ss(Es(),c,s))},pn=(c,s)=>{wt.info(Ss(Es(),c,s))},yo=(c,s)=>{wt.warn(Ss(Es(),c,s))},zn=(c,s)=>{wt.error(Ss(Es(),c,s))};function XT(c){return Math.floor(Math.random()*c).toString()}function C_(c,s){let i=s;return c.forEach(l=>{i=i.replace(l,"")}),i}function QT(c,s){let i="";for(let l=0;l<s;l+=1)i+=c[XT(c.length)];return i}function ZT({length:c=20,useLetters:s=!0,useNumbers:i=!0,includeSymbols:l=[],excludeSymbols:o=[]}={}){let _="abcdefghijklmnopqrstuvwxyz",e="0123456789",p=[],g=[],n=[];return s&&(o.length&&(_=C_(o,_)),g=_.split("")),i&&(o.length&&(e=C_(o,e)),n=e.split("")),p=[...g,...n,...l],QT(p,c)}var ev=ZT;const Jr=ke(ev),tv=()=>"WebRTCMetrics",sv=()=>"5.0.3",Ve={INBOUND:"inbound",OUTBOUND:"outbound"},ys={IDLE:"idle",RUNNING:"running",MUTED:"muted"},zr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},nv=()=>({...{delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}}),R_={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:Ve.INBOUND},I_={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:Ve.OUTBOUND},b_={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:Ve.INBOUND},w_={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:Ve.OUTBOUND},rv=c=>{const s={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const i={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(l=>{i.audio[l]={...c.audio[l]}}),Object.keys(c.video).forEach(l=>{i.video[l]={...c.video[l]}}),i}return{...s,audio:{},video:{},data:{...s.data},network:{...s.network},experimental:{...s.experimental}}},iv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Jr()}`,cid:`c-${Jr()}`,uid:`u-${Jr()}`,record:!1,ticket:!0},Jt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},K={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},M={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Xr={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Pu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ie={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},xu="config ",lv=(c,s={},i)=>{const l={...i,...s};return s.pname||yo(xu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${i.pname}'`),s.cid||yo(xu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${i.cid}'`),s.uid||yo(xu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${i.uid}'`),l.pc=c,l},ov=(c={})=>{const s={...iv,...c};return s.name=tv(),s.version=sv(),s},Qr=(c,s,i,l=!1,o)=>{let _=c.map(e=>{if(!i)return e[s];if(!o)return e[s][i];const p=e[s][o];return p?p[i]:null});return _=_.filter(e=>l?Number.isFinite(e)&&e>0:Number.isFinite(e)),_.length===0?[]:_},Hs=c=>c.reduce((s,i)=>s+i,0)/c.length,av=()=>`probe-${Jr()}`,uv=()=>`coltr-${Jr()}`,O_=c=>new Promise(s=>setTimeout(s,c)),Mu=(c,s,i)=>{s?c.call(s,i):c(i)},Xe=(c,s,i,l)=>{const o=Qr(c,s,i,!0,l);if(o.length===0)return null;const _=o.reduce((n,v)=>n+v,0)/o.length;return _===0?null:o.map(n=>Math.abs(_-n)).reduce((n,v)=>n+v,0)/o.length*100/_},st=(c,s,i,l=!1,o)=>{const _=Qr(c,s,i,l,o);return _.length===0?null:_.reduce((e,p)=>e+p,0)/_.length},mn=(c,s,i)=>Qr(c,s,i).reduce((o,_)=>o+_,0),Qe=(c,s,i,l)=>{const o=Qr(c,s,i,!0,l);return o.length===0?null:Math.min(...o)},Ze=(c,s,i,l)=>{const o=Qr(c,s,i,!1,l);return o.length===0?null:Math.max(...o)},Ct=(c,s,i,l)=>{const o=c.slice().pop();if(!o)return null;if(!i)return o[s];if(!l)return o[s][i];const _=o[s][l];return _?_[i]:null},cv=c=>c.slice().pop(),ht=(c,s,i)=>{if(!s)return null;const l={};let o=s[M.AUDIO][c];o||(o=i===Ve.INBOUND?{...R_}:{...I_}),l[M.AUDIO]=o;let _=s[M.VIDEO][c];return _||(_=i===Ve.INBOUND?{...b_}:{...w_}),l[M.VIDEO]=_,l},Zr="exporter ",fv="2.0",D_=(c,s,i)=>{if(!c||c.length===0)return 0;const l=c[c.length-1];if(!l)return 0;const o=l[s][i];if(o){const _=o.total_rtt_ms_out,e=o.total_rtt_measure_out;return!e||!_?st(c,s,"delta_rtt_ms_out",!1,i):Number(_/e)}return null},_v=(c,s)=>{if(!c||c.length===0)return 0;const i=c[c.length-1];if(!i)return 0;const l=i[s].total_rtt_connectivity_ms,o=i[s].total_rtt_connectivity_measure;return!o||!l?st(c,s,"delta_rtt_connectivity_ms"):Number(l/o)},hv=c=>Ct(c,"network","local_candidate_type")!=="relay"?`direct/${Ct(c,"network","local_candidate_protocol")}`:`turn/${Ct(c,"network","local_candidate_relay_protocol")}`,dv=c=>{const s=Ct(c,"network","remote_candidate_type"),i=Ct(c,"network","remote_candidate_protocol");return s!=="relay"?`direct/${i}`:`turn/${i}`};class pv{constructor(s){this._start=null,this._end=null,this._cfg=s,this._referenceReport=null,this._reports=[],this._events=[]}start(){Uu(Zr,"start() - start exporter...");const s=new Date;return this._start=s.toJSON(),s}stop(){Uu(Zr,"stop() - stop exporter...");const s=new Date;return this._end=s.toJSON(),s}saveReferenceReport(s){this._referenceReport=s}getReferenceReport(){return this._referenceReport}addReport(s){this._cfg.ticket&&(Le(Zr,`addReport() - add report to exporter at ${s.timestamp}`),this._reports.push(s))}addCustomEvent(s){this._events.push(s)}reset(){Uu(Zr,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Le(Zr,"ticket() - generate ticket");const s=Ct(this._reports,"audio","total_packets_lost_in"),i=Ct(this._reports,"audio","total_packets_in"),l=Ct(this._reports,"video","total_packets_lost_in"),o=Ct(this._reports,"video","total_packets_in"),_={},e=cv(this._reports);return e&&(Object.keys(e[M.AUDIO]).forEach(p=>{const g=e[M.AUDIO][p];if(_[g.ssrc]={type:M.AUDIO,direction:g.direction},g.direction===Ve.INBOUND){const n={avg:st(this._reports,M.AUDIO,"delta_jitter_ms_in",!1,p),min:Qe(this._reports,M.AUDIO,"delta_jitter_ms_in",p),max:Ze(this._reports,M.AUDIO,"delta_jitter_ms_in",p),volatility:Xe(this._reports,M.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.AUDIO,"delta_kbs_in",!1,p),min:Qe(this._reports,M.AUDIO,"delta_kbs_in",p),max:Ze(this._reports,M.AUDIO,"delta_kbs_in",p),volatility:Xe(this._reports,M.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.AUDIO,"delta_KBytes_in",!1,p),min:Qe(this._reports,M.AUDIO,"delta_KBytes_in",p),max:Ze(this._reports,M.AUDIO,"delta_KBytes_in",p),volatility:Xe(this._reports,M.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={emodel:{avg:st(this._reports,M.AUDIO,"mos_emodel_in",!1,p),min:Qe(this._reports,M.AUDIO,"mos_emodel_in",p),max:Ze(this._reports,M.AUDIO,"mos_emodel_in",p),volatility:Xe(this._reports,M.AUDIO,"mos_emodel_in",p)},effective:{avg:st(this._reports,M.AUDIO,"mos_in",!1,p),min:Qe(this._reports,M.AUDIO,"mos_in",p),max:Ze(this._reports,M.AUDIO,"mos_in",p),volatility:Xe(this._reports,M.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},C=Ct(this._reports,M.AUDIO,"total_packets_lost_in",p),A=Ct(this._reports,M.AUDIO,"total_packets_in",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].mos=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R}else{const n={avg:st(this._reports,M.AUDIO,"delta_jitter_ms_out",!1,p),min:Qe(this._reports,M.AUDIO,"delta_jitter_ms_out",p),max:Ze(this._reports,M.AUDIO,"delta_jitter_ms_out",p),volatility:Xe(this._reports,M.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.AUDIO,"delta_kbs_out",!1,p),min:Qe(this._reports,M.AUDIO,"delta_kbs_out",p),max:Ze(this._reports,M.AUDIO,"delta_kbs_out",p),volatility:Xe(this._reports,M.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.AUDIO,"delta_KBytes_out",!1,p),min:Qe(this._reports,M.AUDIO,"delta_KBytes_out",p),max:Ze(this._reports,M.AUDIO,"delta_KBytes_out",p),volatility:Xe(this._reports,M.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},m={avg:D_(this._reports,M.AUDIO,p),min:Qe(this._reports,M.AUDIO,"delta_rtt_ms_out",p),max:Ze(this._reports,M.AUDIO,"delta_rtt_ms_out",p),volatility:Xe(this._reports,M.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=Ct(this._reports,M.AUDIO,"total_packets_lost_out",p),A=Ct(this._reports,M.AUDIO,"total_packets_out",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:st(this._reports,M.AUDIO,"mos_emodel_out",!1,p),min:Qe(this._reports,M.AUDIO,"mos_emodel_out",p),max:Ze(this._reports,M.AUDIO,"mos_emodel_out",p),volatility:Xe(this._reports,M.AUDIO,"mos_emodel_out",p)},effective:{avg:st(this._reports,M.AUDIO,"mos_out",!1,p),min:Qe(this._reports,M.AUDIO,"mos_out",p),max:Ze(this._reports,M.AUDIO,"mos_out",p),volatility:Xe(this._reports,M.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};_[p].jitter=n,_[p].rtt=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R,_[p].mos=I}}),Object.keys(e[M.VIDEO]).forEach(p=>{const g=e[M.VIDEO][p];if(_[p]={type:M.VIDEO,direction:g.direction},g.direction===Ve.INBOUND){const n={avg:st(this._reports,M.VIDEO,"delta_jitter_ms_in",!1,p),min:Qe(this._reports,M.VIDEO,"delta_jitter_ms_in",p),max:Ze(this._reports,M.VIDEO,"delta_jitter_ms_in",p),volatility:Xe(this._reports,M.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.VIDEO,"delta_kbs_in",!1,p),min:Qe(this._reports,M.VIDEO,"delta_kbs_in",p),max:Ze(this._reports,M.VIDEO,"delta_kbs_in",p),volatility:Xe(this._reports,M.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.VIDEO,"delta_KBytes_in",!1,p),min:Qe(this._reports,M.VIDEO,"delta_KBytes_in",p),max:Ze(this._reports,M.VIDEO,"delta_KBytes_in",p),volatility:Xe(this._reports,M.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m=Ct(this._reports,M.VIDEO,"total_packets_lost_in",p),C=Ct(this._reports,M.VIDEO,"total_packets_in",p),A={lost:m,avg:Math.round((m/(m+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].traffic=S,_[p].bitrate=v,_[p].loss=A}else{const n={avg:st(this._reports,M.VIDEO,"delta_jitter_ms_out",!1,p),min:Qe(this._reports,M.VIDEO,"delta_jitter_ms_out",p),max:Ze(this._reports,M.VIDEO,"delta_jitter_ms_out",p),volatility:Xe(this._reports,M.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.VIDEO,"delta_kbs_out",!1,p),min:Qe(this._reports,M.VIDEO,"delta_kbs_out",p),max:Ze(this._reports,M.VIDEO,"delta_kbs_out",p),volatility:Xe(this._reports,M.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.VIDEO,"delta_KBytes_out",!1,p),min:Qe(this._reports,M.VIDEO,"delta_KBytes_out",p),max:Ze(this._reports,M.VIDEO,"delta_KBytes_out",p),volatility:Xe(this._reports,M.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={avg:D_(this._reports,M.VIDEO,p),min:Qe(this._reports,M.VIDEO,"delta_rtt_ms_out",p),max:Ze(this._reports,M.VIDEO,"delta_rtt_ms_out",p),volatility:Xe(this._reports,M.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=Ct(this._reports,M.VIDEO,"total_packets_lost_out",p),A=Ct(this._reports,M.VIDEO,"total_packets_out",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].rtt=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R}})),{version:fv,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:_,data:{rtt:{avg:_v(this._reports,"data"),min:Qe(this._reports,"data","delta_rtt_connectivity_ms"),max:Ze(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Xe(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((s/(s+i)*100||0)*100)/100}},video:{in:{avg:Math.round((l/(l+o)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:st(this._reports,"data","delta_kbs_in"),min:Qe(this._reports,"data","delta_kbs_in"),max:Ze(this._reports,"data","delta_kbs_in"),volatility:Xe(this._reports,"data","delta_kbs_in")},out:{avg:st(this._reports,"data","delta_kbs_out"),min:Qe(this._reports,"data","delta_kbs_out"),max:Ze(this._reports,"data","delta_kbs_out"),volatility:Xe(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:st(this._reports,"data","delta_KBytes_in"),min:Qe(this._reports,"data","delta_KBytes_in"),max:Ze(this._reports,"data","delta_KBytes_in"),volatility:Xe(this._reports,"data","delta_KBytes_in")},out:{avg:st(this._reports,"data","delta_KBytes_out"),min:Qe(this._reports,"data","delta_KBytes_out"),max:Ze(this._reports,"data","delta_KBytes_out"),volatility:Xe(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:hv(this._reports),remoteConnection:dv(this._reports)}}}}updateConfig(s){this._cfg=s}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const s=this._reports.slice();return s.pop(),s.pop()||null}getReportsNumber(){return this._reports.length}}const Fs="extractor ",N_=(c,s,i,l)=>{let o=!1;const _=l[s].total_rtt_ms_out,e=l[s].total_rtt_measure_out,p=i?i[s].total_rtt_ms_out:0,g=i?i[s].total_rtt_measure_out:0,n={rtt:null,totalRTT:_,totalRTTMeasurements:e};if(c[K.TIMESTAMP]===l[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(o=!0,Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-g===e))return n;const v=1e3*Number(c[K.ROUND_TRIP_TIME]);let S=_+v,m=e+1;return o&&(S=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-p,m=Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-g),{rtt:v,totalRTT:S,totalRTTMeasurements:m}},mv=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:l[s].total_rtt_connectivity_ms,totalRTTMeasurements:l[s].total_rtt_connectivity_measure};const o=1e3*Number(c[K.CURRENT_ROUND_TRIP_TIME]);let _=l[s].total_rtt_connectivity_ms+o,e=l[s].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME)&&(_=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-(i?i[s].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,K.RESPONSES_RECEIVED)&&(e=Number(c[K.RESPONSES_RECEIVED])-(i?i[s].total_rtt_connectivity_measure:0)),{rtt:o,totalRTT:_,totalRTTMeasurements:e}},Ao=(c,s,i)=>c[K.TIMESTAMP]===i[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.JITTER)?null:1e3*(Number(c[K.JITTER])||0),gv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:s[M.VIDEO].delta_ms_decode_frame_in,frames_decoded:s[M.VIDEO].total_frames_decoded_in,total_decode_time:s[M.VIDEO].total_time_decoded_in};const i=c[K.FRAMES_DECODED],l=c[K.TOTAL_DECODE_TIME],o=l-s[M.VIDEO].total_time_decoded_in,_=i-s[M.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:_>0?o*1e3/_:0,frames_decoded:i,total_decode_time:l}},Tv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:s[M.VIDEO].delta_ms_encode_frame_out,frames_encoded:s[M.VIDEO].total_frames_encoded_out,total_encode_time:s[M.VIDEO].total_time_encoded_out};const i=c[K.FRAMES_ENCODED],l=c[K.TOTAL_ENCODE_TIME],o=l-s[M.VIDEO].total_time_encoded_out,_=i-s[M.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:_>0&&o?o*1e3/_:0,frames_encoded:i,total_encode_time:l}},U_=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_SENT))return{packetsSent:i[s].total_packets_out,packetsLost:i[s].total_packets_lost_out,bytesSent:i[s].total_KBytes_out};const o=Number(c[K.PACKETS_SENT])||0-(l?l[s].total_packets_out:0),_=o-i[s].total_packets_out,e=Number(c[K.BYTES_SENT])/1024-(l?l[s].total_KBytes_out:0),p=e-i[s].total_KBytes_out,g=c[K.TIMESTAMP]||Date.now(),n=l?l.timestamp:null;let v=i.timestamp;!v&&n&&(v=n);const S=v?g-v:0,m=S>0?p*.008*1024/S*1e3:0;return{packetsSent:o,deltaPacketsSent:_,KBytesSent:e,deltaKBytesSent:p,kbsSent:m}},P_=(c,s,i,l)=>{let o=i[s].total_packets_lost_out,_=0,e=0;return Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)&&(o=Number(c[K.PACKETS_LOST])||0-(l?l[s].total_packets_lost_out:0),_=o-i[s].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,K.FRACTION_LOST)&&(e=Number(100*c[K.FRACTION_LOST])),{packetsLost:o,deltaPacketsLost:_,fractionLost:e}},x_=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_RECEIVED))return{percent_packets_lost:i[s].percent_packets_lost_in,packetsReceived:i[s].total_packets_in,packetsLost:i[s].total_packets_lost_in,bytesReceived:i[s].total_KBytes_in};const o=Number(c[K.PACKETS_RECEIVED])||0-(l?l[s].total_packets_in:0),_=Number(c[K.PACKETS_LOST])||0-(l?l[s].total_packets_lost_in:0),e=_-i[s].total_packets_lost_in,p=o-i[s].total_packets_in,g=o!==i[s].total_packets_in?e*100/(e+p):0,n=Number(c[K.BYTES_RECEIVED])/1024-(l?l[s].total_KBytes_in:0),v=n-i[s].total_KBytes_in,S=c[K.TIMESTAMP]||Date.now(),m=l?l.timestamp:null;let C=i.timestamp;!C&&m&&(C=m);const A=C?S-C:0,R=A>0?v*.008*1024/A*1e3:0;return{percentPacketsLost:g,packetsReceived:o,deltaPacketsReceived:p,packetsLost:_,deltaPacketsLost:e,KBytesReceived:n,deltaKBytesReceived:v,kbsReceived:R}},vv=c=>c[K.CANDIDATE_TYPE]!=="relay"?"":c[K.RELAY_PROTOCOL]||"",Ev=c=>{if(!Object.prototype.hasOwnProperty.call(c,K.NETWORK_TYPE))return Xr.WIFI;switch(c[K.NETWORK_TYPE]){case Pu.ETHERNET:return Xr.ETHERNET;case Pu.CELLULAR_4G:return Xr.CELLULAR_4G;case Pu.WIFI:return Xr.WIFI;default:return Xr.CELLULAR}},M_=c=>!Object.prototype.hasOwnProperty.call(c,K.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,K.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[K.FRAME_WIDTH]||null,height:c[K.FRAME_HEIGHT]||null,framerate:c[K.FRAMES_PER_SECOND]},Sv=c=>{const s=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_REASON)?c[K.QUALITY_LIMITATION_REASON]:null,i=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[K.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,l=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_DURATIONS)?c[K.QUALITY_LIMITATION_DURATIONS]:null;return l&&Object.keys(l).forEach(o=>{l[o]>1e3&&(l[o]=Number(l[o]/1e3))}),{reason:s,durations:l,resolutionChanges:i}},yv=(c,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:s.total_pli_sent_in,nackCount:s.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(i?i[M.VIDEO].total_pli_sent_in:0),o=(c[K.NACK]||0)-(i?i[M.VIDEO].total_nack_sent_in:0);return{pliCount:l,nackCount:o,deltaPliCount:l-s[M.VIDEO].total_pli_sent_in,deltaNackCount:o-s[M.VIDEO].total_nack_sent_in}},Av=(c,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:s.total_pli_received_out,nackCount:s.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(i?i[M.VIDEO].total_pli_received_out:0),o=(c[K.NACK]||0)-(i?i[M.VIDEO].total_nack_received_out:0);return{pliCount:l,nackCount:o,deltaPliCount:l-s[M.VIDEO].total_pli_received_out,deltaNackCount:o-s[M.VIDEO].total_nack_received_out}},Cv=c=>({channels:c[K.CHANNELS]||null,clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null,sdp_fmtp_line:c[K.SDP_FMTP_LINE]||null}),Rv=c=>({clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null}),Iv=(c,s,i)=>{const l=(c[K.BYTES_RECEIVED]||0)/1024-(i?i.data.total_KBytes_in:0),o=(c[K.BYTES_SENT]||0)/1024-(i?i.data.total_KBytes_out:0),_=c[K.TIMESTAMP]||Date.now(),e=l-s.data.total_KBytes_in,p=o-s.data.total_KBytes_out,g=i?i.timestamp:null;let n=s.timestamp;!n&&g&&(n=g);const v=n?_-n:0,S=v>0?e*.008*1024/v*1e3:0,m=v>0?p*.008*1024/v*1e3:0;return{total_KBytes_received:l,total_KBytes_sent:o,delta_KBytes_received:e,delta_KBytes_sent:p,kbs_speed_received:S,kbs_speed_sent:m}},bv=c=>{const s=c[K.AVAILABLE_INCOMING_BITRATE]/1024||0,i=c[K.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:s,kbs_outgoing_bandwidth:i}},wv=(c,s,i,l)=>{if(!c)return[];switch(c[K.TYPE]){case Jt.CANDIDATE_PAIR:let o=!1;if(c[K.NOMINATED]&&c[K.STATE]===M.SUCCEEDED&&(o=!0,Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c),K.SELECTED in c&&!c[K.SELECTED]&&(o=!1)),o){const e=c[K.LOCAL_CANDIDATE_ID],p=c[K.REMOTE_CANDIDATE_ID],g=Iv(c,s,l),n=bv(c),v=mv(c,"data",l,s);return[{type:ie.NETWORK,value:{local_candidate_id:e}},{type:ie.NETWORK,value:{remote_candidate_id:p}},{type:ie.DATA,value:{total_KBytes_in:g.total_KBytes_received}},{type:ie.DATA,value:{total_KBytes_out:g.total_KBytes_sent}},{type:ie.DATA,value:{delta_KBytes_in:g.delta_KBytes_received}},{type:ie.DATA,value:{delta_KBytes_out:g.delta_KBytes_sent}},{type:ie.DATA,value:{delta_kbs_in:g.kbs_speed_received}},{type:ie.DATA,value:{delta_kbs_out:g.kbs_speed_sent}},{type:ie.DATA,value:{delta_kbs_bandwidth_in:n.kbs_incoming_bandwidth}},{type:ie.DATA,value:{delta_kbs_bandwidth_out:n.kbs_outgoing_bandwidth}},{type:ie.DATA,value:{delta_rtt_connectivity_ms:v.rtt}},{type:ie.DATA,value:{total_rtt_connectivity_ms:v.totalRTT}},{type:ie.DATA,value:{total_rtt_connectivity_measure:v.totalRTTMeasurements}}]}break;case Jt.LOCAL_CANDIDATE:if(c[K.ID]===s.network.local_candidate_id)return[{type:ie.NETWORK,value:{infrastructure:Ev(c)}},{type:ie.NETWORK,value:{local_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{local_candidate_protocol:c[K.PROTOCOL]||""}},{type:ie.NETWORK,value:{local_candidate_relay_protocol:vv(c)}}];break;case Jt.REMOTE_CANDIDATE:if(c[K.ID]===s.network.remote_candidate_id)return[{type:ie.NETWORK,value:{remote_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{remote_candidate_protocol:c[K.PROTOCOL]||""}}];break;case Jt.INBOUND_RTP:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=ht(e,s,Ve.INBOUND);p&&(p.timestamp=s.timestamp);const g=ht(e,l,Ve.INBOUND);if(g&&(g.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const n=x_(c,M.AUDIO,p,g),v=Ao(c,M.AUDIO,p),S=c[K.CODEC_ID]||"";return[{ssrc:e,type:ie.AUDIO,value:{codec_id_in:S}},{ssrc:e,type:ie.AUDIO,value:{total_packets_in:n.packetsReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_in:n.deltaPacketsReceived}},{ssrc:e,type:ie.AUDIO,value:{total_packets_lost_in:n.packetsLost}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_lost_in:n.deltaPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{percent_packets_lost_in:n.percentPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{total_KBytes_in:n.KBytesReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_KBytes_in:n.deltaKBytesReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_kbs_in:n.kbsReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_jitter_ms_in:v}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const n=gv(c,p),v=x_(c,M.VIDEO,p,g),S=Ao(c,M.VIDEO,p),m=c[K.DECODER_IMPLEMENTATION]||null,C=c[K.CODEC_ID]||null,A=M_(c),R=yv(c,p,g);return[{ssrc:e,type:ie.VIDEO,value:{codec_id_in:C}},{ssrc:e,type:ie.VIDEO,value:{total_packets_in:v.packetsReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_in:v.deltaPacketsReceived}},{ssrc:e,type:ie.VIDEO,value:{total_packets_lost_in:v.packetsLost}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_lost_in:v.deltaPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{percent_packets_lost_in:v.percentPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{total_KBytes_in:v.KBytesReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_KBytes_in:v.deltaKBytesReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_kbs_in:v.kbsReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_jitter_ms_in:S}},{ssrc:e,type:ie.VIDEO,value:{decoder_in:m}},{ssrc:e,type:ie.VIDEO,value:{delta_ms_decode_frame_in:n.delta_ms_decode_frame}},{ssrc:e,type:ie.VIDEO,value:{total_frames_decoded_in:n.frames_decoded}},{ssrc:e,type:ie.VIDEO,value:{total_time_decoded_in:n.total_decode_time}},{ssrc:e,type:ie.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:e,type:ie.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:e,type:ie.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:e,type:ie.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:e,type:ie.VIDEO,value:{size_in:A}}]}break}case Jt.OUTBOUND_RTP:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=ht(e,s,Ve.OUTBOUND);p&&(p.timestamp=s.timestamp);const g=ht(e,l,Ve.OUTBOUND);if(g&&(g.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const n=c[K.CODEC_ID]||null,v=U_(c,M.AUDIO,p,g);return[{ssrc:e,type:ie.AUDIO,value:{codec_id_out:n}},{ssrc:e,type:ie.AUDIO,value:{total_packets_out:v.packetsSent}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_out:v.deltaPacketsSent}},{ssrc:e,type:ie.AUDIO,value:{total_KBytes_out:v.KBytesSent}},{ssrc:e,type:ie.AUDIO,value:{delta_KBytes_out:v.deltaKBytesSent}},{ssrc:e,type:ie.AUDIO,value:{delta_kbs_out:v.kbsSent}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const n=c[K.ENCODER_IMPLEMENTATION]||null,v=c[K.CODEC_ID]||null,S=Tv(c,p),m=M_(c),C=Sv(c),A=Av(c,p,g),R=U_(c,M.VIDEO,p,g);return[{ssrc:e,type:ie.VIDEO,value:{codec_id_out:v}},{ssrc:e,type:ie.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:e,type:ie.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:e,type:ie.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:e,type:ie.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:e,type:ie.VIDEO,value:{encoder_out:n}},{ssrc:e,type:ie.VIDEO,value:{delta_ms_encode_frame_out:S.delta_ms_encode_frame}},{ssrc:e,type:ie.VIDEO,value:{total_frames_encoded_out:S.frames_encoded}},{ssrc:e,type:ie.VIDEO,value:{total_time_encoded_out:S.total_encode_time}},{ssrc:e,type:ie.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:e,type:ie.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:e,type:ie.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:e,type:ie.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:e,type:ie.VIDEO,value:{size_out:m}},{ssrc:e,type:ie.VIDEO,value:{limitation_out:C}}]}break}case Jt.MEDIA_SOURCE:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);break}case Jt.TRACK:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);break}case Jt.CODEC:const _=[];return Object.keys(s[M.AUDIO]).forEach(e=>{const p=s[M.AUDIO][e];if(p.codec_id_in===c[K.ID]||p.codec_id_out===c[K.ID]){Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const g=Cv(c);c[K.ID]===p.codec_id_in?_.push({ssrc:p.ssrc,type:ie.AUDIO,value:{codec_in:g}}):_.push({ssrc:p.ssrc,type:ie.AUDIO,value:{codec_out:g}})}}),Object.keys(s[M.VIDEO]).forEach(e=>{const p=s[M.VIDEO][e];if(p.codec_id_in===c[K.ID]||p.codec_id_out===c[K.ID]){Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const g=Rv(c);c[K.ID]===p.codec_id_in?_.push({ssrc:p.ssrc,type:ie.VIDEO,value:{codec_in:g}}):_.push({ssrc:p.ssrc,type:ie.VIDEO,value:{codec_out:g}})}}),_;case Jt.REMOTE_INBOUND_RTP:{Le(Fs,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=ht(e,s,Ve.OUTBOUND),g=ht(e,l,Ve.OUTBOUND);if(c[K.KIND]===M.AUDIO){const n=N_(c,M.AUDIO,g,p),v=Ao(c,M.AUDIO,p),S=P_(c,M.AUDIO,p,g);return[{ssrc:e,type:ie.AUDIO,value:{delta_rtt_ms_out:n.rtt}},{ssrc:e,type:ie.AUDIO,value:{total_rtt_ms_out:n.totalRTT}},{ssrc:e,type:ie.AUDIO,value:{total_rtt_measure_out:n.totalRTTMeasurements}},{ssrc:e,type:ie.AUDIO,value:{delta_jitter_ms_out:v}},{ssrc:e,type:ie.AUDIO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:e,type:ie.AUDIO,value:{total_packets_lost_out:S.packetsLost}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_lost_out:S.deltaPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{percent_packets_lost_out:S.fractionLost}}]}if(c[K.KIND]===M.VIDEO){const n=N_(c,M.VIDEO,g,p),v=Ao(c,M.VIDEO,p),S=P_(c,M.VIDEO,p,g);return[{ssrc:e,type:ie.VIDEO,value:{delta_rtt_ms_out:n.rtt}},{ssrc:e,type:ie.VIDEO,value:{total_rtt_ms_out:n.totalRTT}},{ssrc:e,type:ie.VIDEO,value:{total_rtt_measure_out:n.totalRTTMeasurements}},{ssrc:e,type:ie.VIDEO,value:{delta_jitter_ms_out:v}},{ssrc:e,type:ie.VIDEO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:e,type:ie.VIDEO,value:{total_packets_lost_out:S.packetsLost}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_lost_out:S.deltaPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{percent_packets_lost_out:S.fractionLost}}]}break}}return[]},Co=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Ov=(c,s=M.AUDIO,i,l,o)=>{const _=ht(o,c,Ve.INBOUND),e=ht(o,i,Ve.INBOUND),p=ht(o,l,Ve.INBOUND),g=[],n=[],v=_[s].percent_packets_lost_in,S=_[s].delta_jitter_ms_in,m=e&&e[s].delta_jitter_ms_in||null,C=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=i&&i.data.delta_rtt_connectivity_ms||null,I=l&&l.data.delta_rtt_connectivity_ms||null;A&&g.push(A),R&&g.push(R),I&&g.push(I),S&&n.push(S),i&&m&&n.push(m),l&&C&&n.push(C);const V=g.length>0?Hs(g):100,W=n.length>0?Hs(n):10,ae=93.2-v,x=.18*ae*ae-27.9*ae+1126.62,$=(V+W)/2,Re=$-177.3<0?0:1,be=.024*$+.11*($-177.3)*Re,H=x-be;return Co(H)},Dv=(c,s=M.AUDIO,i,l,o)=>{const _=ht(o,c,Ve.OUTBOUND),e=ht(o,i,Ve.OUTBOUND),p=ht(o,l,Ve.OUTBOUND),g=[],n=[],v=_[s].percent_packets_lost_out,S=_[s].delta_rtt_ms_out,m=e&&e[s].delta_rtt_ms_out||null,C=p&&p[s].delta_rtt_ms_out||null,A=_[s].delta_jitter_ms_out,R=e&&e[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,W=i&&i.data.delta_rtt_connectivity_ms||null,ae=l&&l.data.delta_rtt_connectivity_ms||null;S?g.push(S):V&&g.push(V),m?g.push(m):W&&g.push(W),C?g.push(C):ae&&g.push(ae),A&&n.push(A),i&&R&&n.push(R),l&&I&&n.push(I);const x=g.length>0?Hs(g):100,$=n.length>0?Hs(n):10,Re=93.2-v,be=.18*Re*Re-27.9*Re+1126.62,H=(x+$)/2,D=H-177.3<0?0:1,L=.024*H+.11*(H-177.3)*D,q=be-L;return Co(q)},Nv=(c,s=M.AUDIO,i,l,o)=>{const _=ht(o,c,Ve.INBOUND),e=ht(o,i,Ve.INBOUND),p=ht(o,l,Ve.INBOUND),g=[],n=[],v=_[s].percent_packets_lost_in/100,S=_[s].delta_jitter_ms_in,m=e&&e[s].delta_jitter_ms_in||null,C=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=i&&i.data.delta_rtt_connectivity_ms||null,I=l&&l.data.delta_rtt_connectivity_ms||null;A&&g.push(A),R&&g.push(R),I&&g.push(I),S&&n.push(S),e&&m&&n.push(m),p&&C&&n.push(C);const V=g.length>0?Hs(g):100,W=n.length>0?Hs(n):10,ae=0,x=19.8,$=29.7,Re=30,be=(V+W)/2+Re,H=be-177.3<0?0:1,D=.024*be+.11*(be-177.3)*H,q=93.2-(ae+x*Math.log(1+$*v)+D);return Co(q)},Uv=(c,s=M.AUDIO,i,l,o)=>{const _=ht(o,c,Ve.OUTBOUND),e=ht(o,i,Ve.OUTBOUND),p=ht(o,l,Ve.OUTBOUND),g=[],n=[],v=_[s].percent_packets_lost_out/100,S=_[s].delta_rtt_ms_out,m=e&&e[s].delta_rtt_ms_out||null,C=p&&p[s].delta_rtt_ms_out||null,A=_[s].delta_jitter_ms_out,R=e&&e[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,W=i&&i.data.delta_rtt_connectivity_ms||null,ae=l&&l.data.delta_rtt_connectivity_ms||null;S?g.push(S):V&&g.push(V),m?g.push(m):W&&g.push(W),C?g.push(C):ae&&g.push(ae),A&&n.push(A),e&&R&&n.push(R),p&&I&&n.push(I);const x=g.length>0?Hs(g):100,$=n.length>0?Hs(n):10,Re=0,be=19.8,H=29.7,D=30,L=(x+$)/2+D,q=L-177.3<0?0:1,j=.024*L+.11*(L-177.3)*q,Q=93.2-(Re+be*Math.log(1+H*v)+j);return Co(Q)};class Pv{constructor(s,i){this._callbacks={onreport:null,onticket:null},this._id=uv(),this._moduleName=this._id,this._probeId=i,this._config=s,this._exporter=new pv(s),this._state=ys.IDLE,this.registerToPCEvents(),pn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(s,i,l,o){const _=(g,n)=>g===M.AUDIO?n===Jt.INBOUND_RTP?{...R_}:{...I_}:n===Jt.INBOUND_RTP?{...b_}:{...w_},e=rv(i);e.pname=this._config.pname,e.call_id=this._config.cid,e.user_id=this._config.uid,e.count=i?i.count+1:1;let p=null;return s.forEach(g=>{!p&&g.timestamp&&(p=g.timestamp),wv(g,e,e.pname,o).forEach(v=>{if(v.value&&v.type)if(v.ssrc){let S=e[v.type][v.ssrc];S||(S=_(v.type,g.type),S.ssrc=v.ssrc,e[v.type][v.ssrc]=S),Object.keys(v.value).forEach(m=>{S[m]=v.value[m]})}else Object.keys(v.value).forEach(S=>{e[v.type][S]=v.value[S]})})}),e.timestamp=p,Object.keys(e[M.AUDIO]).forEach(g=>{const n=e[M.AUDIO][g];n.direction===Ve.INBOUND?(n.mos_emodel_in=Ov(e,M.AUDIO,i,l,n.ssrc),n.mos_in=Nv(e,M.AUDIO,i,l,n.ssrc)):(n.mos_emodel_out=Dv(e,M.AUDIO,i,l,n.ssrc),n.mos_out=Uv(e,M.AUDIO,i,l,n.ssrc))}),e}async takeReferenceStats(){return new Promise((s,i)=>{const l=Date.now();setTimeout(async()=>{try{const o=Date.now()-l,_=Date.now(),e=await this._config.pc.getStats(),p=this.analyze(e,null,null,null),g=Date.now();p.experimental.time_to_measure_ms=g-_,p.experimental.time_to_wait_ms=o,this._exporter.saveReferenceReport(p),Le(this._moduleName,`got reference report for probe ${this._probeId}`),s()}catch(o){i(o)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ys.RUNNING||!this._config.pc)return Le(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const s=Date.now(),i=await this._config.pc.getStats(),l=this.analyze(i,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),o=Date.now();return l.experimental.time_to_measure_ms=o-s,this._exporter.addReport(l),Le(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(l),l}catch(s){return zn(this._moduleName,`got error ${s}`),null}}async start(){Le(this._moduleName,"starting"),this.state=ys.RUNNING,this._startedTime=this._exporter.start(),Le(this._moduleName,"started")}async mute(){this.state=ys.MUTED,Le(this._moduleName,"muted")}async unmute(){this.state=ys.RUNNING,Le(this._moduleName,"unmuted")}async stop(s){if(Le(this._moduleName,`stopping${s?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ys.IDLE,this._config.ticket){const{ticket:i}=this._exporter;this.fireOnTicket(i)}this._exporter.reset(),Le(this._moduleName,"stopped")}registerCallback(s,i,l){s in this._callbacks?(this._callbacks[s]={callback:i,context:l},Le(this._moduleName,`registered callback '${s}'`)):zn(this._moduleName,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],Le(this._moduleName,`unregistered callback '${s}'`)):zn(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReport(s){this._callbacks.onreport&&Mu(this._callbacks.onreport.callback,this._callbacks.onreport.context,s)}fireOnTicket(s){this._callbacks.onticket&&Mu(this._callbacks.onticket.callback,this._callbacks.onticket.context,s)}updateConfig(s){this._config=s,this._exporter.updateConfig(s)}get state(){return this._state}set state(s){this._state=s,Le(this._moduleName,`state changed to ${s}`)}addCustomEvent(s,i,l,o){this._exporter.addCustomEvent({at:typeof s=="object"?s.toJSON():s,category:i,name:l,description:o})}async registerToPCEvents(){const{pc:s}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const i=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${i.length} devices found`,"Media Devices state")}catch{zn(this._moduleName,"can't get devices")}},s){s.oniceconnectionstatechange=()=>{const l=s.iceConnectionState;l===zr.CONNECTED||l===zr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===zr.DISCONNECTED||l===zr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===zr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},s.onicegatheringstatechange=()=>{const l=s.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",l,"ICE gathering state")},s.ontrack=l=>{this.addCustomEvent(new Date().toJSON(),"call",`${l.track.kind}track`,"MediaStreamTrack received")},s.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const i=s.getReceivers();if(i&&i.length>0){const l=i[0],{transport:o}=l;if(o){const{iceTransport:_}=o;_&&(_.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class xv{constructor(s){this._id=s.pname&&s.pname.substr(0,12).padEnd(12," ")||av(),this._moduleName=this._id,pn(this._moduleName,"probe created"),this._config=s,this._collector=new Pv(this._config,this._id)}set onreport(s){s?this._collector.registerCallback("onreport",s):this._collector.unregisterCallback("onreport")}set onticket(s){s?this._collector.registerCallback("onticket",s):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(s){this._collector.state=s}addCustomEvent(s,i,l,o=new Date().toJSON()){this._collector.addCustomEvent(o,i,s,l)}get isRunning(){return this._collector.state===ys.RUNNING}get isIdle(){return this._collector.state===ys.IDLE}updateUserId(s){this._config.uid=s,this._collector.updateConfig(this._config)}updateCallId(s){this._config.cid=s,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){yo(this._moduleName,"probe is already running");return}this._collector.start()}stop(s=!1){this.isRunning&&this._collector.stop(s)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Ot="engine ";class Mv{constructor(s){this._config=s,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},pn(Ot,`configured for probing every ${this._config.refreshEvery}ms`),pn(Ot,`configured for starting after ${this._config.startAfter}ms`),pn(Ot,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Le(Ot,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(s=>s.isRunning)}get isIdle(){return this._probes.every(s=>s.isIdle)}addNewProbe(s,i){if(!s)throw new Error("undefined peer connection");const l=lv(s,i,this._config),o=new xv(l);return this._probes.push(o),Le(Ot,`${this._probes.length} probes registered`),o}removeExistingProbe(s){if(!s)throw new Error("undefined probe");s.state===ys.RUNNING&&s.stop(),this._probes=this._probes.filter(i=>s.id!==i.id)}async start(){const s=()=>{this._probes.forEach(_=>_.start())},i=async()=>Promise.all(this._probes.map(_=>_.takeReferenceStats())),l=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,o=async()=>{const _=nv(),e=this._probes.filter(p=>p.isRunning);for(const p of e){const g=await p.collectStats();g&&_.probes.push(g),Le(Ot,`got probe ${p.id}`),await O_(0)}return _.delta_time_to_measure_probes_ms=mn(_.probes,"experimental","time_to_measure_ms"),_.delta_KBytes_in=mn(_.probes,"data","delta_KBytes_in"),_.delta_KBytes_out=mn(_.probes,"data","delta_KBytes_out"),_.delta_kbs_in=mn(_.probes,"data","delta_kbs_in"),_.delta_kbs_out=mn(_.probes,"data","delta_kbs_out"),_.total_time_decoded_in=mn(_.probes,"video","total_time_decoded_in"),_.total_time_encoded_out=mn(_.probes,"video","total_time_encoded_out"),_};for(Le(Ot,"starting to collect"),s(),Le(Ot,"generating reference reports..."),await i(),Le(Ot,"reference reports generated"),this._startedTime=Date.now();l();)if(Le(Ot,`wait ${this._config.refreshEvery}ms before collecting`),await O_(this._config.refreshEvery),l()){Le(Ot,"collecting...");const _=Date.now(),e=await o(),p=Date.now();e.delta_time_consumed_to_measure_ms=p-_,this.fireOnReports(e),Le(Ot,"collected")}Le(Ot,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(s){const i=l=>{this._probes.forEach(o=>{o.stop(l)})};pn(Ot,"stop collecting"),i(s)}registerCallback(s,i,l){s in this._callbacks?(this._callbacks[s]={callback:i,context:l},Le(Ot,`registered callback '${s}'`)):zn(Ot,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],Le(this._moduleName,`unregistered callback '${s}'`)):zn(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReports(s){this._callbacks.onresult&&s.probes.length>0&&Mu(this._callbacks.onresult.callback,this._callbacks.onresult.context,s)}}const kv="interface ";class Lv{constructor(s){this._config=ov(s),pn(kv,`welcome to ${this._config.name} version ${this._config.version}`),JT(this._config.verbose||!1),this._engine=new Mv(this._config)}setupLogLevel(s){zT(s)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(s,i){return this._engine.addNewProbe(s,i)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(s){this._engine.removeExistingProbe(s)}set onresult(s){s?this._engine.registerCallback("onresult",s):this._engine.unregisterCallback("onresult")}}function $v(c,s){return Object.keys(c).filter(i=>s.includes(i)).reduce((i,l)=>{const o=l;return{...i,[o]:c[o]}},{})}const Hv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class Fv{constructor(s){this.intervals={},this.emitInterval=s.emitInterval||200,this.onChangeFunction=s.onChangeFunction}start(s,i){s&&s.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(s,i))}stop(s){this.clearVolumeInterval(s)}clearVolumeInterval(s){console.log("clearVolumeInterval",s),clearInterval(this.intervals[s]),delete this.intervals[s]}clearAllIntervals(){Object.keys(this.intervals).forEach(s=>{clearInterval(this.intervals[s])}),this.intervals={}}beginCalculation(s,i){this.clearVolumeInterval(i);const l=dn.createAnalyser(),o=dn.createMediaStreamSource(s),_=dn.createScriptProcessor(2048,1,1);l.smoothingTimeConstant=.8,l.fftSize=1024,o.connect(l),l.connect(_),_.connect(dn.destination),this.intervals[i]=setInterval(()=>{const e=new Uint8Array(l.frequencyBinCount);l.getByteFrequencyData(e);let p=0;const g=e.length;for(let v=0;v<g;v++)p+=e[v];const n=p/g;this.onChangeFunction(i,n)},this.emitInterval)}}const Ro={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},jv=0;class qv{constructor(s){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=s,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new Fv({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(s){this.currentActiveRoomIdValue=s,this.context.emit("currentActiveRoomChanged",s)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(s){this.isCallAddingInProgress=s,this.context.emit("callAddingInProgressChanged",s)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(s=>s.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(s=>s.kind==="audiooutput")}get getUserMediaConstraints(){return S_()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(s){this.availableMediaDevices=s,this.context.emit("changeAvailableDeviceList",s)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}async initializeMediaDevices(){const s=localStorage.getItem(Ro.SELECTED_INPUT_DEVICE)||"default",i=localStorage.getItem(Ro.SELECTED_OUTPUT_DEVICE)||"default";try{const l=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),o=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(o),await this.setMicrophone(s),await this.setSpeaker(i),navigator.mediaDevices.addEventListener("devicechange",async()=>{const _=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(_)}),l.getTracks().forEach(_=>_.stop())}catch(l){console.error(l)}}setCallTime(s){const i={...s};delete i.callId,this.callTime={...this.callTime,[s.callId]:i},this.context.emit("changeCallTime",this.callTime)}removeCallTime(s){const i={...this.callTime};delete i[s],this.callTime={...i},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(s,i){this.timeIntervals={...this.timeIntervals,[s]:i}}removeTimeInterval(s){const i={...this.timeIntervals};i[s]&&(clearInterval(i[s]),delete i[s],this.timeIntervals={...i})}stopCallTimer(s){this.removeTimeInterval(s),this.removeCallTime(s)}emitVolumeChange(s,i){this.context.emit("changeCallVolume",{callId:s,volume:i})}setMetricsConfig(s){this.metricConfig={...this.metricConfig,...s}}sendDTMF(s,i){if(!/^[A-D0-9]+$/g.test(i))throw new Error("Not allowed character in DTMF input");this.extendedCalls[s].sendDTMF(i)}setIsMuted(s){this.muted=s,this.context.emit("changeIsMuted",s)}processMute(s){const i=this.currentActiveRoomId;this.setIsMuted(s),this.initialStreamValue.getTracks().forEach(l=>l.enabled=!s),this.roomReconfigure(i)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:s,toHold:i,automatic:l}){const o=this.extendedCalls[s];o._automaticHold=l??!1,await new Promise(p=>{const g=()=>{p()};i?o.hold({},g):o.unhold({},g)}),this.updateCall(o);const e=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(i?s!==p._id:!0));e.length>1&&await this.doConference(e)}holdCall(s,i=!1){return this.processHold({callId:s,automatic:i,toHold:!0})}unholdCall(s){return this.processHold({callId:s,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(s=>s.direction==="outgoing"&&s.status===jv).forEach(s=>this.terminateCall(s._id))}answerCall(s){const i=this.extendedCalls[s];this.cancelAllOutgoingUnanswered(),i.answer(this.sipOptions),this.updateCall(i),this.setActiveRoom(i.roomId),i.connection.addEventListener("track",l=>{this.triggerAddStream(l,i)})}async moveCall(s,i){this.updateCallStatus({callId:s,isMoving:!0}),await this.processRoomChange({callId:s,roomId:i}),this.updateCallStatus({callId:s,isMoving:!1})}updateCall(s){this.activeCalls[s._id]=T_(s),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(s){const l={...this.activeRooms[s.roomId],...s};this.activeRooms={...this.activeRooms,[s.roomId]:{...l}},this.context.emit("updateRoom",{room:l,roomList:this.activeRooms})}hasAutoAnswerHeaders(s){const i=/answer-after=0/,o=s.request.getHeader("Call-Info");return o&&i.test(o)}addCall(s,i=!0){this.activeCalls={...this.activeCalls,[s._id]:T_(s)},this.extendedCalls[s._id]=s,i&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(s){this.callStatus={...this.callStatus,[s]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(s){const l={...{...this.callStatus[s.callId]}};s.isMoving!==void 0&&(l.isMoving=s.isMoving),s.isTransferring!==void 0&&(l.isTransferring=s.isTransferring),s.isMerging!==void 0&&(l.isMerging=s.isMerging),this.callStatus={...this.callStatus,[s.callId]:{...l}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(s){const i={...this.callStatus};delete i[s],this.callStatus={...i},this.context.emit("changeCallStatus",this.callStatus)}addRoom(s){this.activeRooms={...this.activeRooms,[s.roomId]:s},this.context.emit("addRoom",{room:s,roomList:this.activeRooms})}getActiveStream(){const s=E_(this.initialStreamValue,this.microphoneInputLevel*2);return s.getTracks().forEach(i=>i.enabled=!this.isMuted),this.setActiveStream(s),s}async setMicrophone(s){if(!this.getInputDeviceList.find(({deviceId:l})=>l===s)||(this.setSelectedInputDevice(s),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const i=Object.values(this.extendedCalls).filter(l=>l.roomId===this.currentActiveRoomId);i.length===1?Object.values(i).forEach(async l=>{const o=this.getActiveStream();l.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.updateCall(l)}):await this.doConference(i)}setActiveStream(s){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(s,"origin"),this.activeStreamValue=s,this.context.emit("changeActiveStream",s)}async setSpeaker(s){if(!this.getOutputDeviceList.find(({deviceId:o})=>o===s))return;this.setSelectedOutputDevice(s);const i=Object.values(this.extendedCalls);if(i.length===0)return;const l=i.filter(o=>o.roomId===this.currentActiveRoomId);l.length===1?i.forEach(o=>{var _;(_=o.audioTag)==null||_.setSinkId(s),this.updateCall(o)}):await this.doConference(l)}removeRoom(s){const i={...this.activeRooms},l={...i[s]};delete i[s],this.activeRooms={...i},this.context.emit("removeRoom",{room:l,roomList:this.activeRooms})}deleteRoomIfEmpty(s){s!==void 0&&Object.values(this.extendedCalls).filter(i=>i.roomId===s).length===0&&(this.removeRoom(s),this.currentActiveRoomId===s&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(s){this.muted?s.mute({audio:!0}):s.unmute({audio:!0})}async roomReconfigure(s){var l;if(s===void 0)return;const i=Object.values(this.extendedCalls).filter(o=>o.roomId===s);if(this.currentActiveRoomId===s?i.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):i.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),i.length===0)this.deleteRoomIfEmpty(s);else if(i.length===1&&this.currentActiveRoomId!==s)i[0].isOnHold().local||await this.holdCall(i[0].id,!0);else if(i.length===1&&this.currentActiveRoomId===s){if(i[0].isOnHold().local&&i[0]._automaticHold&&await this.unholdCall(i[0].id),i[0].connection&&((l=i[0].connection)!=null&&l.getSenders()[0])){const o=this.getActiveStream();await i[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(i[0])}}else i.length>1&&await this.doConference(i)}async doConference(s){const i=[];s.forEach(l=>{l!=null&&l.connection.getReceivers().forEach(o=>{i.push(o.track)})}),await KT.forEach(s,async l=>{var e;if(l==null)return;const o=new MediaStream,_=dn.createMediaStreamDestination();if(l.connection.getReceivers().forEach(p=>{i.forEach(g=>{o.addTrack(p.track),p.track.id!==g.id&&dn.createMediaStreamSource(new MediaStream([g])).connect(_)})}),s[0].roomId===this.currentActiveRoomId){const p=this.getActiveStream();dn.createMediaStreamSource(p).connect(_)}(e=l.connection)!=null&&e.getSenders()[0]&&(await l.connection.getSenders()[0].replaceTrack(_.stream.getTracks()[0]),this.muteReconfigure(l))})}processCallerMute(s,i){const l=this.extendedCalls[s];l&&l.connection.getReceivers().length&&(l.localMuted=i,l.connection.getReceivers().forEach(o=>{o.track.enabled=!i}),this.updateCall(l))}muteCaller(s){this.processCallerMute(s,!0)}unmuteCaller(s){this.processCallerMute(s,!1)}terminateCall(s){const i=this.extendedCalls[s];i._status!==8&&i.terminate()}transferCall(s,i){if(i.toString().length===0)return new Error("Target must be passed");const l=this.extendedCalls[s];if(!l._is_confirmed&&!l._is_canceled){const o=`sip:${i}@${this.context.sipDomain}`;l.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${o}`]});return}this.updateCallStatus({callId:s,isTransferring:!0}),l.refer(`sip:${i}@${this.context.sipDomain}`),this.updateCall(l)}mergeCall(s){const i=Object.values(this.extendedCalls).filter(_=>_.roomId===s);if(i.length!==2)return;const l=i[0],o=i[1];!l||!o||(this.updateCallStatus({callId:l._id,isMerging:!0}),this.updateCallStatus({callId:o._id,isMerging:!0}),l.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(l))}mergeCallByIds(s,i){const l=Object.values(this.extendedCalls).find(_=>_._id===s),o=Object.values(this.extendedCalls).find(_=>_._id===i);if(!l||!o)throw new Error("Call ID is not provided");this.updateCallStatus({callId:s,isMerging:!0}),this.updateCallStatus({callId:i,isMerging:!0}),l.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(l)}setDND(s){this.isDNDEnabled=s,this.context.emit("changeIsDND",s)}startCallTimer(s){this.removeTimeInterval(s);const i={callId:s,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(i);const l=setInterval(()=>{const o={...this.callTime[s]},_=WT(o);this.setCallTime({callId:s,..._})},1e3);this.setTimeInterval(s,l)}async setActiveRoom(s){const i=this.currentActiveRoomId;s!==i&&(this.currentActiveRoomId=s,await this.roomReconfigure(i),await this.roomReconfigure(s))}getNewRoomId(){const s=Object.keys(this.activeRooms);return s.length===0?1:parseInt(s.sort()[s.length-1])+1}async setupCall(s){var n,v;const i=s.session;if(this.getActiveCalls[i.id]!==void 0)return;const o=this.getNewRoomId(),_={started:new Date,incomingInProgress:!1,roomId:o};i.direction==="incoming"?(this.context.logger.log("New incoming call from",(v=(n=i._remote_identity)==null?void 0:n._uri)==null?void 0:v._user),_.incomingInProgress=!0,this.context.subscribe(Yt.CALL_CONFIRMED,S=>{i.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.startCallTimer(i.id))}),this.context.subscribe(Yt.CALL_FAILED,S=>{i.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.deleteRoomIfEmpty(o))})):i.direction==="outgoing"&&(i.once("confirmed",()=>{this.startCallTimer(i.id)}),this.startCallTimer(i.id));const e=i,p=this.hasAutoAnswerHeaders(s),g=e.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);e.roomId=o,e.localMuted=!1,e.autoAnswer=g,g?this.addCall(e,!1):this.addCall(e),this.addCallStatus(i.id),this.addRoom(_),g&&this.answerCall(e._id)}removeCall(s){const i={...this.activeCalls};delete i[s],this.activeCalls={...i};const l={...this.extendedCalls};delete l[s],this.extendedCalls={...l},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(s){var o;const i=this.extendedCalls[s._id];this.stopVUMeter("origin"),(o=i.connection)==null||o.getSenders().forEach(_=>{_.track.stop()});const l=i.roomId;this.removeCall(s._id),this.roomReconfigure(l)}async newRTCSessionCallback(s){const i=s.session;if(this.isDND){i.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Yt.NEW_CALL,session:i,event:s}),i.on("ended",l=>{var _,e,p;this.stopVUMeter(i.id),this.context.logger.log("Session ended for",(e=(_=i._remote_identity)==null?void 0:_._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Yt.CALL_ENDED,session:i,event:l});const o=this.getActiveCalls[i.id];o&&this.activeCallListRemove(o),this.stopCallTimer(i.id),this.removeCallStatus(i.id),this.removeCallMetrics(i.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(g=>g.stop()),this.initialStreamValue=null)}),i.on("progress",l=>{var o,_;this.context.logger.log("Session in progress for",(_=(o=i._remote_identity)==null?void 0:o._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Yt.CALL_PROGRESS,session:i,event:l})}),i.on("failed",l=>{var _,e,p;this.stopVUMeter(i.id),this.context.logger.log("Session failed for",(e=(_=i._remote_identity)==null?void 0:_._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Yt.CALL_FAILED,session:i,event:l}),i.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const o=this.getActiveCalls[i.id];o&&this.activeCallListRemove(o),this.stopCallTimer(i.id),this.removeCallStatus(i.id),this.removeCallMetrics(i.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(g=>g.stop()),this.initialStreamValue=null)}),i.on("confirmed",l=>{var o,_;this.context.logger.log("Session confirmed for",(_=(o=i._remote_identity)==null?void 0:o._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Yt.CALL_CONFIRMED,session:i,event:l}),this.updateCall(i),i.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(s),i.direction==="outgoing"){const l=this.getActiveCalls[i.id].roomId;this.setActiveRoom(l)}}setMuteWhenJoin(s){this.muteWhenJoinEnabled=s,this.context.emit("changeMuteWhenJoin",s)}setMicrophoneSensitivity(s){if(s<0||s>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=s,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(s){this.speakerVolumeValue=s,Object.values(this.extendedCalls).forEach(i=>{i.audioTag&&(i.audioTag.volume=s,this.updateCall(i))})}setAutoAnswer(s){this.isAutoAnswer=s}setSelectedInputDevice(s){localStorage.setItem(Ro.SELECTED_INPUT_DEVICE,s),this.selectedMediaDevices.input=s,this.context.emit("changeActiveInputMediaDevice",s)}setSelectedOutputDevice(s){localStorage.setItem(Ro.SELECTED_OUTPUT_DEVICE,s),this.selectedMediaDevices.output=s,this.context.emit("changeActiveOutputMediaDevice",s)}setCallMetrics(s){const i={...s};delete i.callId,this.callMetrics={...this.callMetrics,[s.callId]:i},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(s){const i={...this.callMetrics};delete i[s],this.callMetrics={...i},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(s){const i=new Lv(this.metricConfig),l=i.createProbe(s.connection,{cid:s._id}),o=[];let _;l.onreport=e=>{Object.entries(e.audio).forEach(([n,v])=>{v.direction==="inbound"&&!o.includes(n)&&(o.push(n),_=n)});const p=e.audio[_];if(!p)return;const g=$v(p,Hv);g.callId=s._id,this.setCallMetrics(g)},this.context.subscribe(Yt.CALL_ENDED,e=>{e._id===s._id&&i.stopAllProbes()}),i.startAllProbes()}setupVUMeter(s,i){this.VUMeter.start(s,i)}stopVUMeter(s){this.VUMeter.stop(s)}async setupStream(){const s=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(i=>i.stop()),this.initialStreamValue=null),this.initialStreamValue=s}async triggerAddStream(s,i){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const l=E_(this.initialStreamValue,this.microphoneInputLevel*2),o=this.isMuted||this.muteWhenJoin;l.getTracks().forEach(e=>e.enabled=!o),this.setActiveStream(l),await i.connection.getSenders()[0].replaceTrack(l.getTracks()[0]);const _=new MediaStream([s.track]);NT(_,i,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(_,i._id),this.getCallQuality(i),this.updateCall(i)}initCall(s,i){if(s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`);const l=this.context.call(`sip:${s}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=l.id,i&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:l.id,roomId:this.currentActiveRoomId}),l.connection.addEventListener("track",o=>{this.triggerAddStream(o,l)})}async processRoomChange({callId:s,roomId:i}){const l=this.extendedCalls[s].roomId;this.extendedCalls[s].roomId=i;const o=this.extendedCalls[s];return this.updateCall(o),await this.setActiveRoom(i),Promise.all([this.roomReconfigure(l),this.roomReconfigure(i)]).then(()=>{this.deleteRoomIfEmpty(l),this.deleteRoomIfEmpty(i)})}}class Vv{constructor(s){this.context=s}get sipOptions(){return{...this.context.options.sipOptions}}initCall(s,i){if(s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${s}@${this.context.sipDomain}`,i,this.sipOptions)}stop(s={}){this.context.terminateJanusSessions(s)}}class Bv{constructor(s){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=s,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(s){const i=this.extendedMessages[s];this.updateMSRPSession(i)}updateMSRPSession(s){this.activeMessages[s._id]=v_(s),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(s){this.activeMessages={...this.activeMessages,[s._id]:v_(s)},this.extendedMessages[s._id]=s,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(s,i){const l=this.msrpHistory[i.id]||[];l.push(s),this.msrpHistory={...this.msrpHistory,[i.id]:[...l]},this.context.emit("newMSRPMessage",{message:s,session:i})}messageTerminate(s){const i=this.extendedMessages[s];i._status!==8&&i.terminate()}addMessageSession(s){if(!s._id||this.getActiveMessages[s._id]!==void 0)return;const l=s;this.addMMSRPSession(l)}triggerMSRPListener({listenerType:s,session:i,event:l}){const o=this.context.listenersList[s];!o||!o.length||o.forEach(_=>{_(i,l)})}removeMMSRPSession(s){const i={...this.activeMessages};delete i[s],this.activeMessages={...i};const l={...this.extendedMessages};delete l[s],this.extendedMessages={...l},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(s){this.removeMMSRPSession(s._id)}newMSRPSessionCallback(s){const i=s.session;i.on("ended",l=>{this.triggerMSRPListener({listenerType:Yt.CALL_ENDED,session:i,event:l});const o=this.getActiveMessages[i.id];this.activeMessageListRemove(o)}),i.on("failed",l=>{this.triggerMSRPListener({listenerType:Yt.CALL_FAILED,session:i,event:l});const o=this.getActiveMessages[i.id];this.activeMessageListRemove(o)}),i.on("confirmed",l=>{this.triggerMSRPListener({listenerType:Yt.CALL_CONFIRMED,session:i,event:l}),this.updateMSRPSession(i)}),i.on("newMessage",l=>{this.addMSRPMessage(l,i)}),this.addMessageSession(i)}setIsMSRPInitializing(s){this.isMSRPInitializingValue=s,this.context.emit("isMSRPInitializingChanged",s)}initMSRP(s,i,l){if(s.length===0)return console.error("Target must be a valid string");const o=this.context.startMSRP(s,l);o.on("active",()=>{this.addMessageSession(o),o.sendMSRP(i),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(s,i){const l=this.extendedMessages[s];if(!l)throw new Error(`MSRP session with id ${s} doesn't exist!`);l.sendMSRP(i)}}const ku={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Gv extends CT{constructor(s,i){if(!s.modules.length)throw new Error("options.modules should include at least 1 module");const l={...s.configuration,sockets:s.socketInterfaces.map(o=>new GT.WebSocketInterface(o))};super(l),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],s.pnExtraHeaders&&Object.keys(s.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(s.pnExtraHeaders),this.options=s,this.modules=s.modules,i&&UT(i)&&(this.logger=i)}on(s,i){return super.on(s,i)}off(s,i){return super.off(s,i)}emit(s,i){return super.emit(s,i)}get sipDomain(){return this.options.sipDomain}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(ku.AUDIO)&&(this.audio=new qv(this)),this.modules.includes(ku.MSRP)&&(this.msrp=new Bv(this)),this.modules.includes(ku.VIDEO)&&(this.video=new Vv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),this.setConnected(!1),setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}subscribe(s,i){const o=!this.listenersList[s]||!this.listenersList[s].length?[i]:[...this.listenersList[s],i];this.listenersList={...this.listenersList,[s]:o}}removeIListener(s){const i={...this.listenersList};delete i[s],this.listenersList={...i}}triggerListener({listenerType:s,session:i,event:l}){const o=this.listenersList[s];!o||!o.length||o.forEach(_=>{_(i,l)})}setInitialized(s){this.initialized=s,this.emit("ready",s)}setConnected(s){this.connected=s,this.emit("connection",s)}}return Gv});
|