opensips-js-vue 0.1.21 → 0.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/library/index.d.ts +7 -1
- package/library/super.mjs +12 -3
- package/library/super.mjs.map +1 -1
- package/library/super.umd.js +1 -1
- package/library/super.umd.js.map +1 -1
- package/package.json +2 -2
package/library/super.umd.js
CHANGED
|
@@ -155,7 +155,7 @@ a=accept-types:text/plain text/html
|
|
|
155
155
|
a=path:${n.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._from_tag||(this._from_tag=this._request.from._parameters.tag),this._id=this._request.call_id+this._from_tag,new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:c=>{this.onTransportError(),console.log(c)},onAuthenticated:c=>{this._request=c},onReceiveResponse:c=>{this._receiveInviteResponse(c),c.status_code===200&&(c.parseSDP(!0),this._status=dt.STATUS_CONFIRMED,this.target_addr=c.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=dt.STATUS_INVITE_SENT}terminate(n={}){const r=n.cause||oe.causes.BYE,a=kt.cloneArray(n.extraHeaders),c=n.body;let e,_=n.status_code,g=n.reason_phrase;if(this._status===dt.STATUS_TERMINATED)throw new di.InvalidStateError(this._status);switch(this.status="terminated",this._status){case dt.STATUS_NULL:case dt.STATUS_INVITE_SENT:case dt.STATUS_1XX_RECEIVED:if(_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);_&&(g=g||oe.REASON_PHRASE[_]||"",e=`SIP ;cause=${_} ;text="${g}"`),this._status===dt.STATUS_NULL||this._status===dt.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===dt.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=dt.STATUS_CANCELED,this._failed("local",null,oe.causes.CANCELED);break;case dt.STATUS_WAITING_FOR_ANSWER:case dt.STATUS_ANSWERED:if(_=_||480,_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);this._request.reply(_,g,a,c),this._failed("local",null,oe.causes.REJECTED);break;case dt.STATUS_WAITING_FOR_ACK:case dt.STATUS_CONFIRMED:if(g=n.reason_phrase||oe.REASON_PHRASE[_]||"",_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);if(_&&a.push(`Reason: SIP ;cause=${_}; text="${g}"`),this._status===dt.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ir.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:A})=>{A===oe.ACK&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ir.C.STATUS_TERMINATED&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate())}),this._ended("local",null,r),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),this._ended("local",null,r)}}sendRequest(n,r){return this._dialog.sendRequest(n,r)}authenticate(n){this.status="auth";let r=new ro("");r.method="AUTH",r.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),r.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),n&&r.addHeader("Authorization",n.toString());let a=r.toString(),c=[];for(var e=0;e<a.length;e++)c.push(a.charCodeAt(e).toString(16));this._connection.send(r.toString())}onmessage(n){const r=new ro(n.data);if(this.status==="auth"&&r.code===401){const a=this.parseAuth(r.getHeader("WWW-Authenticate")),c=new $E(this.credentials);c.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},a,kt.createRandomToken(12)),this.authenticate(c)}this.status==="auth"&&r.code===200&&this._direction==="outgoing"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.inviteParty(r)):this.status==="auth"&&r.code===200&&this._direction==="incoming"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.acceptParty(r),this.emit("confirmed")):r.method==="SEND"&&(this._sendOk(r),this._sendReport(r),r.direction="incoming",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)),r.code===480&&this._close()}onclose(){console.log("close")}onopen(){const n=new RTCPeerConnection({iceServers:[]});n.createDataChannel(""),n.createOffer().then(n.setLocalDescription.bind(n)),n.onicecandidate=r=>{if(!r||!r.candidate||!r.candidate.candidate)return;const a=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,c=r.candidate.candidate.match(a);this.my_ip=c&&c[1],n.onicecandidate=()=>{},this.authenticate(null)}}onerror(n){console.log(n)}_receiveInviteResponse(n){if(console.log("resp0000000000000",n),this._dialog&&n.status_code>=200&&n.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.sendRequest(oe.ACK);return}else{const r=new Ru(this,n,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(oe.ACK),this.sendRequest(oe.BYE);return}if(this._is_canceled){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==dt.STATUS_INVITE_SENT&&this._status!==dt.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(n.status_code):this._status=dt.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){console.log("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=dt.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",n)).catch(c=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("maybe here???"),this._status=dt.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,oe.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",n,oe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r),new RTCSessionDescription({type:"answer",sdp:r.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(n,500,a.toString()),console.log("failed 4"),this._failed("local",n,oe.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(oe.ACK),this._confirmed("local",null)});break}default:{const r=kt.sipErrorCause(n.status_code);console.log("failed 5"),this._failed("remote",n,r)}}}sendMSRP(n){const r=new ro("");let a="";this.my_addr[1]&&(a=this.my_addr[1]),this.target_addr[1]&&(a+=" "+this.target_addr[1]),this.target_addr[0]&&(a+=" "+this.target_addr[0]),r.method="SEND",r.addHeader("To-Path",a),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",kt.createRandomToken(10)),r.addHeader("Byte-Range","1-25/25"),r.addHeader("Content-Type","text/plain"),r.addHeader("Success-Report","yes"),r.addHeader("Failure-Report","yes"),r.body=n;let c=r.toString();console.log(c);let e=[];for(var _=0;_<c.length;_++)e.push(c.charCodeAt(_).toString(16));console.log(e),this._connection.send(r.toString()),r.direction="outgoing",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(n){let r=n.ident,a=n.getHeader("Message-ID"),c=new ro("");c.method="200 OK",c.addHeader("To-Path",`${this.my_addr[1]}`),c.addHeader("From-Path",`${this.my_addr[0]}`),c.addHeader("Message-ID",a),c.ident=r;let e=c.toString();console.log(e);let _=[];for(var g=0;g<e.length;g++)_.push(e.charCodeAt(g).toString(16));console.log(_),this._connection.send(c.toString())}_sendReport(n){let r=n.ident,a=n.getHeader("Message-ID"),c=new ro("");c.method="REPORT",c.addHeader("To-Path",`${n.getHeader("From-Path")}`),c.addHeader("From-Path",`${this.my_addr[0]}`),c.addHeader("Message-ID",a),c.addHeader("Byte-Range","1-25/25"),c.addHeader("Status","000 200 OK"),c.ident=r;let e=c.toString();console.log(e);let _=[];for(var g=0;g<e.length;g++)_.push(e.charCodeAt(g).toString(16));console.log(_),this._connection.send(c.toString())}parseAuth(n){const r={},a=n.replace("Digest","").split(",");for(const c of a){const e=c.trim().split("=");r[e[0]]=e[1].match('^"(.+)"$')[1]}return r}init_incoming(n,r){let a;const c=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&c!=="application/sdp"){n.reply(415);return}if(this._status=dt.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(a=n.getHeader("expires")*1e3),n.to_tag=kt.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=dt.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),console.log("failed 6"),this._failed("local",null,oe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===dt.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),console.log("failed 7"),this._failed("system",null,oe.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),n.parseSDP(!0),this.target_addr=n.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",n),this._status!==dt.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(n,r,a){this.emit("_failed",{originator:n,message:r||null,cause:a}),this._close(),this.emit("failed",{originator:n,message:r||null,cause:a})}_close(){if(console.log("CLOSE SESSION"),this._status!==dt.STATUS_TERMINATED){if(this._status=dt.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){console.log("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyMSRPSession(this)}}_createDialog(n,r,a){const c=r==="UAS"?n.to_tag:n.from_tag,e=r==="UAS"?n.from_tag:n.to_tag,_=n.call_id+c+e;let g=this._earlyDialogs[_];if(a)return g?!0:(g=new Ru(this,n,r,Ru.C.STATUS_EARLY),g.error?(console.log("failed 8"),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[_]=g,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,g)return g.update(n,r),this._dialog=g,delete this._earlyDialogs[_],!0;const d=new Ru(this,n,r);return d.error?(console.log("failed 9"),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_newMSRPSession(n,r){this._ua.newMSRPSession(this,{originator:n,session:this,request:r})}_progress(n,r){this.emit("progress",{originator:n,response:r||null})}isEnded(){switch(this._status){case dt.STATUS_CANCELED:case dt.STATUS_TERMINATED:return!0;default:return!1}}_accepted(n,r){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,a){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:a})}_runKeepAliveTimer(){if(!this._sessionTimers||!this._sessionTimers.enabled||this._sessionTimers.running)return;if(this._sessionTimers.currentExpires||(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires||30),!this._sessionTimers.refresher){console.log("Not the refresher; waiting for remote keep-alive");return}const n=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.timer=setTimeout(()=>{if(this._connection.readyState===WebSocket.OPEN)try{this._sendKeepAlive(),console.log("Session timer: sending MSRP keep-alive")}catch(r){console.error("Failed to send keep-alive:",r)}this._sessionTimers.running=!1,this._runKeepAliveTimer()},n*1e3*.5)}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runKeepAliveTimer()}receiveRequest(n){if(console.log("receiveRequest()"),n.method===oe.CANCEL)(this._status===dt.STATUS_WAITING_FOR_ANSWER||this._status===dt.STATUS_ANSWERED)&&(this._status=dt.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",n,oe.causes.CANCELED));else switch(n.method){case oe.ACK:if(this._status!==dt.STATUS_WAITING_FOR_ACK)return;if(this._status=dt.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:oe.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(c=>{this.terminate({cause:oe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})}else this._is_confirmed||this._confirmed("remote",n);break;case oe.BYE:this._status===dt.STATUS_CONFIRMED||this._status===dt.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,oe.causes.BYE)):this._status===dt.STATUS_INVITE_RECEIVED||this._status===dt.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,oe.causes.BYE)):n.reply(403,"Wrong Status");break;case oe.INVITE:this._status===dt.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case oe.INFO:this._status===dt.STATUS_1XX_RECEIVED||this._status===dt.STATUS_WAITING_FOR_ANSWER||this._status===dt.STATUS_ANSWERED||this._status===dt.STATUS_WAITING_FOR_ACK||this._status===dt.STATUS_CONFIRMED?(n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new pd(this).init_incoming(n):n.reply(415):n.reply(403,"Wrong Status");break;case oe.UPDATE:this._status===dt.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case oe.REFER:this._status===dt.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case oe.NOTIFY:this._status===dt.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.CONNECTION_ERROR,cause:oe.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:oe.causes.REQUEST_TIMEOUT,cause:oe.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.DIALOG_ERROR,cause:oe.causes.DIALOG_ERROR})}}var yA=Hr();const kd=Qt(yA),Hu=new wu("Parser"),vA=(o,n)=>{let r,a,c=o.indexOf(`\r
|
|
157
157
|
`);if(c===-1){Hu.warn("parseMessage() | no CRLF found, not a SIP message");return}const e=o.substring(0,c);let _=kd.parse(e,"Request_Response");if(_===-1){Hu.warn(`parseMessage() | error parsing first line of SIP message: "${e}"`);return}else _.status_code?(r=new Za.IncomingResponse,r.status_code=_.status_code,r.reason_phrase=_.reason_phrase):(r=new Za.IncomingRequest(n),r.method=_.method,r.ruri=_.uri);r.data=o;let g=c+2;for(;;){if(c=TA(o,g),c===-2){a=g+2;break}else if(c===-1){Hu.warn("parseMessage() | malformed message");return}if(_=bA(r,o,g,c),_!==!0){Hu.warn("parseMessage() |",_.error);return}g=c+2}if(r.hasHeader("content-length")){const d=r.getHeader("content-length");r.body=o.substr(a,d)}else r.body=o.substring(a);return r};function TA(o,n){let r=n,a=0,c=0;if(o.substring(r,r+2).match(/(^\r\n)/))return-2;for(;a===0;){if(c=o.indexOf(`\r
|
|
158
|
-
`,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function bA(o,n,r,a){let c;const e=n.indexOf(":",r),_=n.substring(r,e).trim(),g=n.substring(e+1,a).trim();switch(_.toLowerCase()){case"via":case"v":o.addHeader("via",g),o.getHeaders("via").length===1?(c=o.parseHeader("Via"),c&&(o.via=c,o.via_branch=c.branch)):c=0;break;case"from":case"f":o.setHeader("from",g),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",g),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=kd.parse(g,"Record_Route"),c===-1)c=void 0;else for(const d of c)o.addHeader("record-route",g.substring(d.possition,d.offset)),o.headers["Record-Route"][o.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":o.setHeader("call-id",g),c=o.parseHeader("call-id"),c&&(o.call_id=g);break;case"contact":case"m":if(c=kd.parse(g,"Contact"),c===-1)c=void 0;else for(const d of c)o.addHeader("contact",g.substring(d.possition,d.offset)),o.headers.Contact[o.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":o.setHeader("content-length",g),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",g),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",g),c=o.parseHeader("cseq"),c&&(o.cseq=c.value),o instanceof Za.IncomingResponse&&(o.method=c.method);break;case"max-forwards":o.setHeader("max-forwards",g),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",g),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",g),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",g),c=o.parseHeader("session-expires"),c&&(o.session_expires=c.expires,o.session_expires_refresher=c.refresher);break;case"refer-to":case"r":o.setHeader("refer-to",g),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",g),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",g),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(_,g),c=0}return c===void 0?{error:`error parsing header "${_}"`}:!0}const wA={parseMessage:vA},_l=new wu("Registrator"),zu=10;class SA{constructor(n,r){this._reg_id=1,this._ua=n,this._transport=r,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=qs.createRandomToken(22),this._cseq=0,this._to_uri=n.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const c=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=c}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(n){Array.isArray(n)||(n=[]),this._extraHeaders=n.slice()}setExtraContactParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){_l.debug("Register request in progress...");return}const n=this._extraHeaders.slice();n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),n.push(`Expires: ${this._expires}`);const r=new On.OutgoingRequest(oe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n),a=new sl(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,oe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,oe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{if(c.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):{if(this._registering=!1,!c.hasHeader("Contact")){_l.debug("no Contact header in response to REGISTER, response ignored");break}const e=c.headers.Contact.reduce((A,S)=>A.concat(S.parsed),[]);let _=e.find(A=>this._sipInstance===A.getParam("+sip.instance")&&this._reg_id===parseInt(A.getParam("reg-id")));if(_||(_=e.find(A=>A.uri.user===this._ua.contact.uri.user)),!_){_l.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let g=_.getParam("expires");!g&&c.hasHeader("expires")&&(g=c.getHeader("expires")),g||(g=this._expires),g=Number(g),g<zu&&(g=zu);const d=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):Math.floor(g*1e3/2);this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),_.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=_.getParam("temp-gruu").replace(/"/g,"")),_.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=_.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:c}));break}case/^423$/.test(c.status_code):{c.hasHeader("min-expires")?(this._expires=Number(c.getHeader("min-expires")),this._expires<zu&&(this._expires=zu),this.register()):(_l.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(c,oe.causes.SIP_FAILURE_CODE));break}default:{const e=qs.sipErrorCause(c.status_code);this._registrationFailure(c,e)}}}});this._registering=!0,a.send()}unregister(n={}){if(!this._registered){_l.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();n.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),r.push("Expires: 0");const a=new On.OutgoingRequest(oe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new sl(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,oe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,oe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{switch(!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):this._unregistered(c);break;default:{const e=qs.sipErrorCause(c.status_code);this._unregistered(c,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(n,r){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:r}))}_unregistered(n,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:r||null})}}const un=console,fi={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},EA=cA;class CA extends EA{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new SA(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(n,r){return super.call(n,r)}joinVideoCall(n,r,a){un.debug("call()");const c=new qu(this);return c.configureMedia({audio:!0,video:!0}),c.connect(n,r,a),c}startScreenShare(){un.debug("startScreenShare()");for(const n in this._janus_sessions)this._janus_sessions[n].connectScreenShare()}changeMediaConstraints(n){for(const r in this._janus_sessions)this._janus_sessions[r].changeMediaConstraints(n)}startBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].connectBlur()}stopBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].stopBlur()}_loadConfig(n){try{pl.load(this._configuration,n)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=qs.newUUID());let r;typeof window<"u"&&typeof window.document<"u"?r=window?.navigator.userAgent:typeof self<"u"&&self.navigator&&(r=self.navigator.userAgent),r+=" "+bt.USER_AGENT,this._configuration.user_agent=n.overrideUserAgent&&typeof n.overrideUserAgent=="function"?n.overrideUserAgent(r):r,n.onTransportCallback&&typeof n.onTransportCallback=="function"&&(this.onTransportCallback=n.onTransportCallback),this._configuration.jssip_id=qs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new UC(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=AA.bind(this),this._transport.onconnect=IA.bind(this),this._transport.ondisconnect=RA.bind(this),this._transport.ondata=$A.bind(this)}catch(e){throw un.warn(e),new di.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 e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ba("sip",qs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){const _=e.anonymous||null,g=e.outbound||null;let d="<";return _?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),g&&(_?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",d}};const c=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(c.indexOf(e)!==-1?Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}));un.debug("configuration parameters after validation:");for(const e in this._configuration)if(Object.prototype.hasOwnProperty.call(pl.settings,e))switch(e){case"uri":case"registrar_server":un.debug(`- ${e}: ${this._configuration[e]}`);break;case"password":case"ha1":case"authorization_jwt":un.debug(`- ${e}: NOT SHOWN`);break;default:un.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}newMSRPSession(n,r){n.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.newStreamPlugins.forEach(a=>{a.setSession(n)}),this.processStreamPlugins.forEach(a=>{a.setSession(n)}),this.emit("newJanusSession",r)}kill(){}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(n){var r,a,c,e;const _=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){un.debug("Request-URI does not point to us"),n.method!==bt.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===bt.SIPS){n.reply_sl(416);return}if(Ir.checkTransaction(this,n))return;if(_===bt.INVITE?new Ir.InviteServerTransaction(this,this._transport,n):_!==bt.ACK&&_!==bt.CANCEL&&new Ir.NonInviteServerTransaction(this,this._transport,n),_===bt.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const A=Date.now(),S=this.lastOptionsTimestamp>A-35e3,R=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>A;S&&R&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){n.reply(200);return}new b_.Options(this).init_incoming(n)}else if(_===bt.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new b_.Message(this).init_incoming(n)}else if(_===bt.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let g,d;if(n.to_tag)if(g=this._findDialog(n.call_id,n.from_tag,n.to_tag),g)g.receiveRequest(n);else if(_===bt.NOTIFY)if(d=this._findSession(n),d)d.receiveRequest(n);else{if(n.body)try{const A=JSON.parse(n.body)||{};(a=(r=A.plugindata)==null?void 0:r.data)!=null&&a.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(A),(e=(c=A.plugindata)==null?void 0:c.data)!=null&&e.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(A.plugindata.data.unpublished)}catch(A){console.error(A)}n.reply(200)}else _!==bt.ACK&&n.reply(481);else switch(_){case bt.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const A=n.replaces;g=this._findDialog(A.call_id,A.from_tag,A.to_tag),g?(d=g.owner,d.isEnded()?n.reply(603):d.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(d=new Od(this),d.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(d=new TC(this),d.init_incoming(n));else un.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case bt.BYE:n.reply(481);break;case bt.CANCEL:d=this._findSession(n),d?d.receiveRequest(n):un.debug("received CANCEL request for a non existent session");break;case bt.ACK:break;case bt.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){un.debug("startMSRP()",r);const a=new Od(this);return a.connect(n),a}startJanus(n,r){un.debug("startJanus()",r);const a=new Od(this);return a.connect(n),a}terminateMSRPSessions(n){un.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){un.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}enableJanusAudio(n){un.debug("enableJanusAudio()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startAudio():this._janus_sessions[r].stopAudio())}enableJanusVideo(n){un.debug("enableJanusVideo()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startVideo():this._janus_sessions[r].stopVideo())}terminateAllSessions(){for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){un.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch(r){console.error(r)}}}stop(n=!0){if(un.debug("stop()"),this._dynConfiguration={},this._status===fi.STATUS_USER_CLOSED){un.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;n&&this.terminateAllSessions();for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){un.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){un.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(c){console.error(c)}this._status=fi.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&&r===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function AA(o){this.emit("connecting",o)}function IA(o){this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function RA(o){const n=["nict","ict","nist","ist"];for(const r of n)for(const a in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],a)&&this._transactions[r][a].onTransportError();this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_NOT_READY,this._error=fi.NETWORK_ERROR)}function $A(o){const n=o.transport;let r=o.message;const a=r;if(r=wA.parseMessage(r,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(r,a),!!r&&!(this._status===fi.STATUS_USER_CLOSED&&r instanceof Za.IncomingRequest)&&JC(r,this,n)){if(r instanceof Za.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Za.IncomingResponse){let c;switch(r.method){case bt.INVITE:c=this._transactions.ict[r.via_branch],c&&c.receiveResponse(r);break;case bt.ACK:break;default:c=this._transactions.nict[r.via_branch],c&&c.receiveResponse(r);break}}}}const xA=["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","putOnHoldTimestamp"],OA=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function yf(o){const n={};return xA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n.localHold=o._localHold,n}function vf(o){const n={};return OA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n}async function Dd(o,n,r){const a=o.createMediaStreamSource(n),c=o.createMediaStreamDestination(),e=o.createGain();return a.connect(e),e.connect(c),e.gain.value=r,c.stream}function kA(o,n,r,a){if(Tf())return;const c=document.createElement("audio");c.id=n._id,c.className="audioTag",c.srcObject=o,c.setSinkId(r),c.volume=a,c.play(),n.audioTag=c}function DA(o){if(o&&typeof o.log=="function"&&typeof o.warn=="function"&&typeof o.error=="function")return!0}function Tf(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const NA=mn,MA=Hr(),Jn=new NA("WebSocketInterface");var UA=class{constructor(o){Jn.debug('new() [url:"%s"]',o),this._url=o,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=MA.parse(o,"absoluteURI");if(n===-1)throw Jn.warn(`invalid WebSocket URI: ${o}`),new TypeError(`Invalid argument: ${o}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Jn.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${o}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(o){this._via_transport=o.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Jn.debug("connect()"),this.isConnected()){Jn.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Jn.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Jn.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(o){this._onError(o)}}disconnect(){Jn.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(o){return Jn.debug("send()"),this.isConnected()?(this._ws.send(o),!0):(Jn.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(){Jn.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:o,code:n,reason:r}){Jn.debug(`WebSocket ${this._url} closed`),o===!1&&Jn.debug("WebSocket abrupt disconnection"),this.ondisconnect(!o,n,r)}_onMessage({data:o}){Jn.debug("received WebSocket message"),this.ondata(o)}_onError(o){Jn.warn(`WebSocket ${this._url} error: `,o)}};const Nd=Pl,PA=bt,LA=Ls,qA=$n(),HA=ff,zA=Ms(),FA=ed(),BA=Hr(),VA=UA;Wa("JsSIP")("version %s",Nd.version);var jA={C:PA,Exceptions:LA,Utils:qA,UA:HA,URI:zA,NameAddrHeader:FA,WebSocketInterface:VA,Grammar:BA,debug:Wa,get name(){return Nd.title},get version(){return Nd.version}};const GA=Qt(jA);function Md(o){return o<10?`0${o}`:`${o}`}function WA(o){let n=o.hours||0,r=o.minutes||0,a=o.seconds||0;a++,a===60&&(a=0,r++,r===60&&(r=0,n++));const c=`${Md(n)}:${Md(r)}:${Md(a)}`;return{seconds:a,minutes:r,hours:n,formatted:c}}function KA(o){let n=0;for(let r=0;r<o.length;r++)n+=o[r]*o[r];return Math.sqrt(n/o.length)}async function YA(o,n,r=150){const a=n.createMediaStreamSource(o),c=n.createDelay();c.delayTime.value=r/1e3;const e=n.createGain();e.gain.value=0;const _=n.createMediaStreamDestination();return a.connect(c).connect(e).connect(_),{stream:_.stream,setSpeaking:g=>{e.gain.value=g?1:0}}}var Mn={};Mn.forEach=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)if(c in o){const e=Promise.resolve(o[c]).then(_=>n.call(r||globalThis,_,c,o));a.push(e)}await Promise.all(a)},Mn.forEachSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)a in o&&await n.call(r||globalThis,await o[a],a,o)},Mn.map=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=Promise.resolve(o[c]).then(e=>n.call(r||globalThis,e,c,o)));return Promise.all(a)},Mn.mapSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=await n.call(r||globalThis,await o[c],c,o));return a},Mn.find=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a();let e=1;for(let _=0;_<o.length;_++){const g=d=>{d?a(o[_]):e===o.length&&a(),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.findSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return o[a]},Mn.findIndex=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(-1);let e=1;for(let _=0;_<o.length;_++){const g=d=>{d?a(_):e===o.length&&a(-1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.findIndexSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return a},Mn.some=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!1);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const g=d=>{d?a(!0):e===o.length&&a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.someSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&await n.call(r||globalThis,await o[a],a,o))return!0;return!1},Mn.every=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!0);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const g=d=>{d?e===o.length&&a(!0):a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.everySeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&!await n.call(r||globalThis,await o[a],a,o))return!1;return!0},Mn.filter=(o,n,r)=>new Promise(async(a,c)=>{const e=[];for(let g=0;g<o.length;g++)g in o&&(e[g]=Promise.resolve(o[g]).then(d=>n.call(r||globalThis,d,g,o)).catch(c));const _=[];for(let g=0;g<e.length;g++)await e[g]&&_.push(await o[g]);a(_)}),Mn.filterSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&await n.call(r||globalThis,await o[c],c,o)&&a.push(await o[c]);return a},Mn.reduce=async(o,n,r)=>{if(o.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let a,c;for(r!==void 0?(c=r,a=0):(c=o[0],a=1),a;a<o.length;a++)a in o&&(c=await n(await c,await o[a],a,o));return c};var bf={};(function(o){const n=Mn;Object.keys(n).forEach(r=>{const a=r.charAt(0).toUpperCase()+r.slice(1);o[`async${a}`]=async function(...c){return n[r](this,...c)}})})(bf);var XA=Object.assign(Mn,{instanceMethods:bf});const Br={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},JA={TRYING:100,RINGING:180,SESSION_PROGRESS:183,OK:200,MOVED_TEMPORARILY:302,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,REQUEST_TIMEOUT:408,BUSY_HERE:486,REQUEST_TERMINATED:487,INTERNAL_SERVER_ERROR:500,SERVICE_UNAVAILABLE:503,BUSY_EVERYWHERE:600,DECLINE:603};var QA={exports:{}};(function(o){var n=function(r){var a=Object.prototype,c=a.hasOwnProperty,e=Object.defineProperty||function(Ae,fe,se){Ae[fe]=se.value},_,g=typeof Symbol=="function"?Symbol:{},d=g.iterator||"@@iterator",A=g.asyncIterator||"@@asyncIterator",S=g.toStringTag||"@@toStringTag";function R(Ae,fe,se){return Object.defineProperty(Ae,fe,{value:se,enumerable:!0,configurable:!0,writable:!0}),Ae[fe]}try{R({},"")}catch{R=function(Ae,fe,se){return Ae[fe]=se}}function N(Ae,fe,se,st){var We=fe&&fe.prototype instanceof De?fe:De,ht=Object.create(We.prototype),It=new Se(st||[]);return e(ht,"_invoke",{value:ue(Ae,se,It)}),ht}r.wrap=N;function H(Ae,fe,se){try{return{type:"normal",arg:Ae.call(fe,se)}}catch(st){return{type:"throw",arg:st}}}var W="suspendedStart",G="suspendedYield",K="executing",ae="completed",ee={};function De(){}function X(){}function re(){}var be={};R(be,d,function(){return this});var Ne=Object.getPrototypeOf,Q=Ne&&Ne(Ne($e([])));Q&&Q!==a&&c.call(Q,d)&&(be=Q);var ce=re.prototype=De.prototype=Object.create(be);X.prototype=re,e(ce,"constructor",{value:re,configurable:!0}),e(re,"constructor",{value:X,configurable:!0}),X.displayName=R(re,S,"GeneratorFunction");function me(Ae){["next","throw","return"].forEach(function(fe){R(Ae,fe,function(se){return this._invoke(fe,se)})})}r.isGeneratorFunction=function(Ae){var fe=typeof Ae=="function"&&Ae.constructor;return fe?fe===X||(fe.displayName||fe.name)==="GeneratorFunction":!1},r.mark=function(Ae){return Object.setPrototypeOf?Object.setPrototypeOf(Ae,re):(Ae.__proto__=re,R(Ae,S,"GeneratorFunction")),Ae.prototype=Object.create(ce),Ae},r.awrap=function(Ae){return{__await:Ae}};function _e(Ae,fe){function se(ht,It,qe,Ue){var wt=H(Ae[ht],Ae,It);if(wt.type==="throw")Ue(wt.arg);else{var Yt=wt.arg,Xe=Yt.value;return Xe&&typeof Xe=="object"&&c.call(Xe,"__await")?fe.resolve(Xe.__await).then(function(Je){se("next",Je,qe,Ue)},function(Je){se("throw",Je,qe,Ue)}):fe.resolve(Xe).then(function(Je){Yt.value=Je,qe(Yt)},function(Je){return se("throw",Je,qe,Ue)})}}var st;function We(ht,It){function qe(){return new fe(function(Ue,wt){se(ht,It,Ue,wt)})}return st=st?st.then(qe,qe):qe()}e(this,"_invoke",{value:We})}me(_e.prototype),R(_e.prototype,A,function(){return this}),r.AsyncIterator=_e,r.async=function(Ae,fe,se,st,We){We===void 0&&(We=Promise);var ht=new _e(N(Ae,fe,se,st),We);return r.isGeneratorFunction(fe)?ht:ht.next().then(function(It){return It.done?It.value:ht.next()})};function ue(Ae,fe,se){var st=W;return function(We,ht){if(st===K)throw new Error("Generator is already running");if(st===ae){if(We==="throw")throw ht;return zt()}for(se.method=We,se.arg=ht;;){var It=se.delegate;if(It){var qe=ye(It,se);if(qe){if(qe===ee)continue;return qe}}if(se.method==="next")se.sent=se._sent=se.arg;else if(se.method==="throw"){if(st===W)throw st=ae,se.arg;se.dispatchException(se.arg)}else se.method==="return"&&se.abrupt("return",se.arg);st=K;var Ue=H(Ae,fe,se);if(Ue.type==="normal"){if(st=se.done?ae:G,Ue.arg===ee)continue;return{value:Ue.arg,done:se.done}}else Ue.type==="throw"&&(st=ae,se.method="throw",se.arg=Ue.arg)}}}function ye(Ae,fe){var se=fe.method,st=Ae.iterator[se];if(st===_)return fe.delegate=null,se==="throw"&&Ae.iterator.return&&(fe.method="return",fe.arg=_,ye(Ae,fe),fe.method==="throw")||se!=="return"&&(fe.method="throw",fe.arg=new TypeError("The iterator does not provide a '"+se+"' method")),ee;var We=H(st,Ae.iterator,fe.arg);if(We.type==="throw")return fe.method="throw",fe.arg=We.arg,fe.delegate=null,ee;var ht=We.arg;if(!ht)return fe.method="throw",fe.arg=new TypeError("iterator result is not an object"),fe.delegate=null,ee;if(ht.done)fe[Ae.resultName]=ht.value,fe.next=Ae.nextLoc,fe.method!=="return"&&(fe.method="next",fe.arg=_);else return ht;return fe.delegate=null,ee}me(ce),R(ce,S,"Generator"),R(ce,d,function(){return this}),R(ce,"toString",function(){return"[object Generator]"});function Re(Ae){var fe={tryLoc:Ae[0]};1 in Ae&&(fe.catchLoc=Ae[1]),2 in Ae&&(fe.finallyLoc=Ae[2],fe.afterLoc=Ae[3]),this.tryEntries.push(fe)}function J(Ae){var fe=Ae.completion||{};fe.type="normal",delete fe.arg,Ae.completion=fe}function Se(Ae){this.tryEntries=[{tryLoc:"root"}],Ae.forEach(Re,this),this.reset(!0)}r.keys=function(Ae){var fe=Object(Ae),se=[];for(var st in fe)se.push(st);return se.reverse(),function We(){for(;se.length;){var ht=se.pop();if(ht in fe)return We.value=ht,We.done=!1,We}return We.done=!0,We}};function $e(Ae){if(Ae){var fe=Ae[d];if(fe)return fe.call(Ae);if(typeof Ae.next=="function")return Ae;if(!isNaN(Ae.length)){var se=-1,st=function We(){for(;++se<Ae.length;)if(c.call(Ae,se))return We.value=Ae[se],We.done=!1,We;return We.value=_,We.done=!0,We};return st.next=st}}return{next:zt}}r.values=$e;function zt(){return{value:_,done:!0}}return Se.prototype={constructor:Se,reset:function(Ae){if(this.prev=0,this.next=0,this.sent=this._sent=_,this.done=!1,this.delegate=null,this.method="next",this.arg=_,this.tryEntries.forEach(J),!Ae)for(var fe in this)fe.charAt(0)==="t"&&c.call(this,fe)&&!isNaN(+fe.slice(1))&&(this[fe]=_)},stop:function(){this.done=!0;var Ae=this.tryEntries[0],fe=Ae.completion;if(fe.type==="throw")throw fe.arg;return this.rval},dispatchException:function(Ae){if(this.done)throw Ae;var fe=this;function se(Ue,wt){return ht.type="throw",ht.arg=Ae,fe.next=Ue,wt&&(fe.method="next",fe.arg=_),!!wt}for(var st=this.tryEntries.length-1;st>=0;--st){var We=this.tryEntries[st],ht=We.completion;if(We.tryLoc==="root")return se("end");if(We.tryLoc<=this.prev){var It=c.call(We,"catchLoc"),qe=c.call(We,"finallyLoc");if(It&&qe){if(this.prev<We.catchLoc)return se(We.catchLoc,!0);if(this.prev<We.finallyLoc)return se(We.finallyLoc)}else if(It){if(this.prev<We.catchLoc)return se(We.catchLoc,!0)}else if(qe){if(this.prev<We.finallyLoc)return se(We.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Ae,fe){for(var se=this.tryEntries.length-1;se>=0;--se){var st=this.tryEntries[se];if(st.tryLoc<=this.prev&&c.call(st,"finallyLoc")&&this.prev<st.finallyLoc){var We=st;break}}We&&(Ae==="break"||Ae==="continue")&&We.tryLoc<=fe&&fe<=We.finallyLoc&&(We=null);var ht=We?We.completion:{};return ht.type=Ae,ht.arg=fe,We?(this.method="next",this.next=We.finallyLoc,ee):this.complete(ht)},complete:function(Ae,fe){if(Ae.type==="throw")throw Ae.arg;return Ae.type==="break"||Ae.type==="continue"?this.next=Ae.arg:Ae.type==="return"?(this.rval=this.arg=Ae.arg,this.method="return",this.next="end"):Ae.type==="normal"&&fe&&(this.next=fe),ee},finish:function(Ae){for(var fe=this.tryEntries.length-1;fe>=0;--fe){var se=this.tryEntries[fe];if(se.finallyLoc===Ae)return this.complete(se.completion,se.afterLoc),J(se),ee}},catch:function(Ae){for(var fe=this.tryEntries.length-1;fe>=0;--fe){var se=this.tryEntries[fe];if(se.tryLoc===Ae){var st=se.completion;if(st.type==="throw"){var We=st.arg;J(se)}return We}}throw new Error("illegal catch attempt")},delegateYield:function(Ae,fe,se){return this.delegate={iterator:$e(Ae),resultName:fe,nextLoc:se},this.method==="next"&&(this.arg=_),ee}},r}(o.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(QA);var wf={exports:{}};(function(o){(function(n,r){o.exports?o.exports=r():n.log=r()})(Sb,function(){var n=function(){},r="undefined",a=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),c=["trace","debug","info","warn","error"];function e(G,K){var ae=G[K];if(typeof ae.bind=="function")return ae.bind(G);try{return Function.prototype.bind.call(ae,G)}catch{return function(){return Function.prototype.apply.apply(ae,[G,arguments])}}}function _(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function g(G){return G==="debug"&&(G="log"),typeof console===r?!1:G==="trace"&&a?_:console[G]!==void 0?e(console,G):console.log!==void 0?e(console,"log"):n}function d(G,K){for(var ae=0;ae<c.length;ae++){var ee=c[ae];this[ee]=ae<G?n:this.methodFactory(ee,G,K)}this.log=this.debug}function A(G,K,ae){return function(){typeof console!==r&&(d.call(this,K,ae),this[G].apply(this,arguments))}}function S(G,K,ae){return g(G)||A.apply(this,arguments)}function R(G,K,ae){var ee=this,De;K=K??"WARN";var X="loglevel";typeof G=="string"?X+=":"+G:typeof G=="symbol"&&(X=void 0);function re(ce){var me=(c[ce]||"silent").toUpperCase();if(!(typeof window===r||!X)){try{window.localStorage[X]=me;return}catch{}try{window.document.cookie=encodeURIComponent(X)+"="+me+";"}catch{}}}function be(){var ce;if(!(typeof window===r||!X)){try{ce=window.localStorage[X]}catch{}if(typeof ce===r)try{var me=window.document.cookie,_e=me.indexOf(encodeURIComponent(X)+"=");_e!==-1&&(ce=/^([^;]+)/.exec(me.slice(_e))[1])}catch{}return ee.levels[ce]===void 0&&(ce=void 0),ce}}function Ne(){if(!(typeof window===r||!X)){try{window.localStorage.removeItem(X);return}catch{}try{window.document.cookie=encodeURIComponent(X)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}ee.name=G,ee.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},ee.methodFactory=ae||S,ee.getLevel=function(){return De},ee.setLevel=function(ce,me){if(typeof ce=="string"&&ee.levels[ce.toUpperCase()]!==void 0&&(ce=ee.levels[ce.toUpperCase()]),typeof ce=="number"&&ce>=0&&ce<=ee.levels.SILENT){if(De=ce,me!==!1&&re(ce),d.call(ee,ce,G),typeof console===r&&ce<ee.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+ce},ee.setDefaultLevel=function(ce){K=ce,be()||ee.setLevel(ce,!1)},ee.resetLevel=function(){ee.setLevel(K,!1),Ne()},ee.enableAll=function(ce){ee.setLevel(ee.levels.TRACE,ce)},ee.disableAll=function(ce){ee.setLevel(ee.levels.SILENT,ce)};var Q=be();Q==null&&(Q=K),ee.setLevel(Q,!1)}var N=new R,H={};N.getLogger=function(G){if(typeof G!="symbol"&&typeof G!="string"||G==="")throw new TypeError("You must supply a name when creating a logger.");var K=H[G];return K||(K=H[G]=new R(G,N.getLevel(),N.methodFactory)),K};var W=typeof window!==r?window.log:void 0;return N.noConflict=function(){return typeof window!==r&&window.log===N&&(window.log=W),N},N.getLoggers=function(){return H},N.default=N,N})})(wf);var Vn=wf.exports;const Hs=()=>`${new Date().toISOString()} | metrics`,zs=(o,n,r)=>`${o} | ${n} | ${r}`;Vn.setDefaultLevel(Vn.levels.TRACE);const ZA=o=>{Vn.info(zs(Hs(),"log ",`set log level to ${o?"verbose":"info"}`)),Vn.setLevel(o?Vn.levels.TRACE:Vn.levels.INFO)},e1=o=>{const n=[...Object.keys(Vn.levels)];n.includes(o)?(Vn.info(zs(Hs(),"log ",`update log level to ${o.toLowerCase()}`)),Vn.setLevel(o)):Vn.warn(zs(Hs(),"log ","Incorrect log level please choose one of "),n)},Rt=(o,n,r)=>{r?Vn.debug(zs(Hs(),o,n),r):Vn.debug(zs(Hs(),o,n))},Ud=(o,n)=>{Vn.info(zs(Hs(),o,n))},wa=(o,n)=>{Vn.info(zs(Hs(),o,n))},Fu=(o,n)=>{Vn.warn(zs(Hs(),o,n))},so=(o,n)=>{Vn.error(zs(Hs(),o,n))};function t1(o){return Math.floor(Math.random()*o).toString()}function Sf(o,n){let r=n;return o.forEach(a=>{r=r.replace(a,"")}),r}function n1(o,n){let r="";for(let a=0;a<n;a+=1)r+=o[t1(o.length)];return r}function r1({length:o=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:a=[],excludeSymbols:c=[]}={}){let e="abcdefghijklmnopqrstuvwxyz",_="0123456789",g=[],d=[],A=[];return n&&(c.length&&(e=Sf(c,e)),d=e.split("")),r&&(c.length&&(_=Sf(c,_)),A=_.split("")),g=[...d,...A,...a],n1(g,o)}var s1=r1;const fl=Qt(s1),i1=()=>"WebRTCMetrics",a1=()=>"5.0.3",Ht={INBOUND:"inbound",OUTBOUND:"outbound"},Fs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ml={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},o1=()=>({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:[]}),Ef={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:Ht.INBOUND},Cf={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:Ht.OUTBOUND},Af={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:Ht.INBOUND},If={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:Ht.OUTBOUND},l1=o=>{const n={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(o){const r={...o,audio:{},video:{},data:{...o.data},network:{...o.network},experimental:{...o.experimental}};return Object.keys(o.audio).forEach(a=>{r.audio[a]={...o.audio[a]}}),Object.keys(o.video).forEach(a=>{r.video[a]={...o.video[a]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},u1={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${fl()}`,cid:`c-${fl()}`,uid:`u-${fl()}`,record:!1,ticket:!0},Vr={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"},ge={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"},ie={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},gl={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Pd={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Me={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Ld="config ",c1=(o,n={},r)=>{const a={...r,...n};return n.pname||Fu(Ld,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||Fu(Ld,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||Fu(Ld,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),a.pc=o,a},d1=(o={})=>{const n={...u1,...o};return n.name=i1(),n.version=a1(),n},yl=(o,n,r,a=!1,c)=>{let e=o.map(_=>{if(!r)return _[n];if(!c)return _[n][r];const g=_[n][c];return g?g[r]:null});return e=e.filter(_=>a?Number.isFinite(_)&&_>0:Number.isFinite(_)),e.length===0?[]:e},mi=o=>o.reduce((n,r)=>n+r,0)/o.length,h1=()=>`probe-${fl()}`,p1=()=>`coltr-${fl()}`,Rf=o=>new Promise(n=>setTimeout(n,o)),qd=(o,n,r)=>{n?o.call(n,r):o(r)},Zt=(o,n,r,a)=>{const c=yl(o,n,r,!0,a);if(c.length===0)return null;const e=c.reduce((_,g)=>_+g,0)/c.length;return e===0?null:c.map(_=>Math.abs(e-_)).reduce((_,g)=>_+g,0)/c.length*100/e},nn=(o,n,r,a=!1,c)=>{const e=yl(o,n,r,a,c);return e.length===0?null:e.reduce((_,g)=>_+g,0)/e.length},Sa=(o,n,r)=>yl(o,n,r).reduce((a,c)=>a+c,0),en=(o,n,r,a)=>{const c=yl(o,n,r,!0,a);return c.length===0?null:Math.min(...c)},tn=(o,n,r,a)=>{const c=yl(o,n,r,!1,a);return c.length===0?null:Math.max(...c)},Un=(o,n,r,a)=>{const c=o.slice().pop();if(!c)return null;if(!r)return c[n];if(!a)return c[n][r];const e=c[n][a];return e?e[r]:null},_1=o=>o.slice().pop(),wn=(o,n,r)=>{if(!n)return null;const a={};let c=n[ie.AUDIO][o];c||(c=r===Ht.INBOUND?{...Ef}:{...Cf}),a[ie.AUDIO]=c;let e=n[ie.VIDEO][o];return e||(e=r===Ht.INBOUND?{...Af}:{...If}),a[ie.VIDEO]=e,a},vl="exporter ",f1="2.0",$f=(o,n,r)=>{if(!o||o.length===0)return 0;const a=o[o.length-1];if(!a)return 0;const c=a[n][r];if(c){const e=c.total_rtt_ms_out,_=c.total_rtt_measure_out;return!_||!e?nn(o,n,"delta_rtt_ms_out",!1,r):Number(e/_)}return null},m1=(o,n)=>{if(!o||o.length===0)return 0;const r=o[o.length-1];if(!r)return 0;const a=r[n].total_rtt_connectivity_ms,c=r[n].total_rtt_connectivity_measure;return!c||!a?nn(o,n,"delta_rtt_connectivity_ms"):Number(a/c)},g1=o=>Un(o,"network","local_candidate_type")!=="relay"?`direct/${Un(o,"network","local_candidate_protocol")}`:`turn/${Un(o,"network","local_candidate_relay_protocol")}`,y1=o=>{const n=Un(o,"network","remote_candidate_type"),r=Un(o,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class v1{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ud(vl,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){Ud(vl,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Rt(vl,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){Ud(vl,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Rt(vl,"ticket() - generate ticket");const n=Un(this._reports,"audio","total_packets_lost_in"),r=Un(this._reports,"audio","total_packets_in"),a=Un(this._reports,"video","total_packets_lost_in"),c=Un(this._reports,"video","total_packets_in"),e={},_=_1(this._reports);return _&&(Object.keys(_[ie.AUDIO]).forEach(g=>{const d=_[ie.AUDIO][g];if(e[d.ssrc]={type:ie.AUDIO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_kbs_in",g),max:tn(this._reports,ie.AUDIO,"delta_kbs_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_KBytes_in",g),max:tn(this._reports,ie.AUDIO,"delta_KBytes_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_in",!1,g),min:en(this._reports,ie.AUDIO,"mos_emodel_in",g),max:tn(this._reports,ie.AUDIO,"mos_emodel_in",g),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_in",g)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_in",!1,g),min:en(this._reports,ie.AUDIO,"mos_in",g),max:tn(this._reports,ie.AUDIO,"mos_in",g),volatility:Zt(this._reports,ie.AUDIO,"mos_in",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_in",g),W=Un(this._reports,ie.AUDIO,"total_packets_in",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].mos=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G}else{const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_kbs_out",g),max:tn(this._reports,ie.AUDIO,"delta_kbs_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_KBytes_out",g),max:tn(this._reports,ie.AUDIO,"delta_KBytes_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},N={avg:$f(this._reports,ie.AUDIO,g),min:en(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),max:tn(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_out",g),W=Un(this._reports,ie.AUDIO,"total_packets_out",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},K={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_out",!1,g),min:en(this._reports,ie.AUDIO,"mos_emodel_out",g),max:tn(this._reports,ie.AUDIO,"mos_emodel_out",g),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_out",g)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_out",!1,g),min:en(this._reports,ie.AUDIO,"mos_out",g),max:tn(this._reports,ie.AUDIO,"mos_out",g),volatility:Zt(this._reports,ie.AUDIO,"mos_out",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[g].jitter=A,e[g].rtt=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G,e[g].mos=K}}),Object.keys(_[ie.VIDEO]).forEach(g=>{const d=_[ie.VIDEO][g];if(e[g]={type:ie.VIDEO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_kbs_in",g),max:tn(this._reports,ie.VIDEO,"delta_kbs_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_KBytes_in",g),max:tn(this._reports,ie.VIDEO,"delta_KBytes_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N=Un(this._reports,ie.VIDEO,"total_packets_lost_in",g),H=Un(this._reports,ie.VIDEO,"total_packets_in",g),W={lost:N,avg:Math.round((N/(N+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].traffic=R,e[g].bitrate=S,e[g].loss=W}else{const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_kbs_out",g),max:tn(this._reports,ie.VIDEO,"delta_kbs_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_KBytes_out",g),max:tn(this._reports,ie.VIDEO,"delta_KBytes_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={avg:$f(this._reports,ie.VIDEO,g),min:en(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),max:tn(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.VIDEO,"total_packets_lost_out",g),W=Un(this._reports,ie.VIDEO,"total_packets_out",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].rtt=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G}})),{version:f1,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:e,data:{rtt:{avg:m1(this._reports,"data"),min:en(this._reports,"data","delta_rtt_connectivity_ms"),max:tn(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Zt(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+r)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+c)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:nn(this._reports,"data","delta_kbs_in"),min:en(this._reports,"data","delta_kbs_in"),max:tn(this._reports,"data","delta_kbs_in"),volatility:Zt(this._reports,"data","delta_kbs_in")},out:{avg:nn(this._reports,"data","delta_kbs_out"),min:en(this._reports,"data","delta_kbs_out"),max:tn(this._reports,"data","delta_kbs_out"),volatility:Zt(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:nn(this._reports,"data","delta_KBytes_in"),min:en(this._reports,"data","delta_KBytes_in"),max:tn(this._reports,"data","delta_KBytes_in"),volatility:Zt(this._reports,"data","delta_KBytes_in")},out:{avg:nn(this._reports,"data","delta_KBytes_out"),min:en(this._reports,"data","delta_KBytes_out"),max:tn(this._reports,"data","delta_KBytes_out"),volatility:Zt(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:g1(this._reports),remoteConnection:y1(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const gi="extractor ",xf=(o,n,r,a)=>{let c=!1;const e=a[n].total_rtt_ms_out,_=a[n].total_rtt_measure_out,g=r?r[n].total_rtt_ms_out:0,d=r?r[n].total_rtt_measure_out:0,A={rtt:null,totalRTT:e,totalRTTMeasurements:_};if(o[ge.TIMESTAMP]===a[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ge.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(c=!0,Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===_))return A;const S=1e3*Number(o[ge.ROUND_TRIP_TIME]);let R=e+S,N=_+1;return c&&(R=1e3*Number(o[ge.TOTAL_ROUND_TRIP_TIME])-g,N=Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:S,totalRTT:R,totalRTTMeasurements:N}},T1=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[n].total_rtt_connectivity_ms,totalRTTMeasurements:a[n].total_rtt_connectivity_measure};const c=1e3*Number(o[ge.CURRENT_ROUND_TRIP_TIME]);let e=a[n].total_rtt_connectivity_ms+c,_=a[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ROUND_TRIP_TIME)&&(e=1e3*Number(o[ge.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(o,ge.RESPONSES_RECEIVED)&&(_=Number(o[ge.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:c,totalRTT:e,totalRTTMeasurements:_}},Bu=(o,n,r)=>o[ge.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ge.JITTER)?null:1e3*(Number(o[ge.JITTER])||0),b1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(o,ge.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[ie.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[ie.VIDEO].total_frames_decoded_in,total_decode_time:n[ie.VIDEO].total_time_decoded_in};const r=o[ge.FRAMES_DECODED],a=o[ge.TOTAL_DECODE_TIME],c=a-n[ie.VIDEO].total_time_decoded_in,e=r-n[ie.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:e>0?c*1e3/e:0,frames_decoded:r,total_decode_time:a}},w1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[ie.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[ie.VIDEO].total_frames_encoded_out,total_encode_time:n[ie.VIDEO].total_time_encoded_out};const r=o[ge.FRAMES_ENCODED],a=o[ge.TOTAL_ENCODE_TIME],c=a-n[ie.VIDEO].total_time_encoded_out,e=r-n[ie.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:e>0&&c?c*1e3/e:0,frames_encoded:r,total_encode_time:a}},Of=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(o,ge.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const c=Number(o[ge.PACKETS_SENT])||0-(a?a[n].total_packets_out:0),e=c-r[n].total_packets_out,_=Number(o[ge.BYTES_SENT])/1024-(a?a[n].total_KBytes_out:0),g=_-r[n].total_KBytes_out,d=o[ge.TIMESTAMP]||Date.now(),A=a?a.timestamp:null;let S=r.timestamp;!S&&A&&(S=A);const R=S?d-S:0,N=R>0?g*.008*1024/R*1e3:0;return{packetsSent:c,deltaPacketsSent:e,KBytesSent:_,deltaKBytesSent:g,kbsSent:N}},kf=(o,n,r,a)=>{let c=r[n].total_packets_lost_out,e=0,_=0;return Object.prototype.hasOwnProperty.call(o,ge.PACKETS_LOST)&&(c=Number(o[ge.PACKETS_LOST])||0-(a?a[n].total_packets_lost_out:0),e=c-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(o,ge.FRACTION_LOST)&&(_=Number(100*o[ge.FRACTION_LOST])),{packetsLost:c,deltaPacketsLost:e,fractionLost:_}},Df=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(o,ge.BYTES_RECEIVED))return{percent_packets_lost:r[n].percent_packets_lost_in,packetsReceived:r[n].total_packets_in,packetsLost:r[n].total_packets_lost_in,bytesReceived:r[n].total_KBytes_in};const c=Number(o[ge.PACKETS_RECEIVED])||0-(a?a[n].total_packets_in:0),e=Number(o[ge.PACKETS_LOST])||0-(a?a[n].total_packets_lost_in:0),_=e-r[n].total_packets_lost_in,g=c-r[n].total_packets_in,d=c!==r[n].total_packets_in?_*100/(_+g):0,A=Number(o[ge.BYTES_RECEIVED])/1024-(a?a[n].total_KBytes_in:0),S=A-r[n].total_KBytes_in,R=o[ge.TIMESTAMP]||Date.now(),N=a?a.timestamp:null;let H=r.timestamp;!H&&N&&(H=N);const W=H?R-H:0,G=W>0?S*.008*1024/W*1e3:0;return{percentPacketsLost:d,packetsReceived:c,deltaPacketsReceived:g,packetsLost:e,deltaPacketsLost:_,KBytesReceived:A,deltaKBytesReceived:S,kbsReceived:G}},S1=o=>o[ge.CANDIDATE_TYPE]!=="relay"?"":o[ge.RELAY_PROTOCOL]||"",E1=o=>{if(!Object.prototype.hasOwnProperty.call(o,ge.NETWORK_TYPE))return gl.WIFI;switch(o[ge.NETWORK_TYPE]){case Pd.ETHERNET:return gl.ETHERNET;case Pd.CELLULAR_4G:return gl.CELLULAR_4G;case Pd.WIFI:return gl.WIFI;default:return gl.CELLULAR}},Nf=o=>!Object.prototype.hasOwnProperty.call(o,ge.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(o,ge.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:o[ge.FRAME_WIDTH]||null,height:o[ge.FRAME_HEIGHT]||null,framerate:o[ge.FRAMES_PER_SECOND]},C1=o=>{const n=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_REASON)?o[ge.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_RESOLUTION_CHANGES)?o[ge.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_DURATIONS)?o[ge.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(c=>{a[c]>1e3&&(a[c]=Number(a[c]/1e3))}),{reason:n,durations:a,resolutionChanges:r}},A1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PLI)||!Object.prototype.hasOwnProperty.call(o,ge.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(o[ge.PLI]||0)-(r?r[ie.VIDEO].total_pli_sent_in:0),c=(o[ge.NACK]||0)-(r?r[ie.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ie.VIDEO].total_pli_sent_in,deltaNackCount:c-n[ie.VIDEO].total_nack_sent_in}},I1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PLI)||!Object.prototype.hasOwnProperty.call(o,ge.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(o[ge.PLI]||0)-(r?r[ie.VIDEO].total_pli_received_out:0),c=(o[ge.NACK]||0)-(r?r[ie.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ie.VIDEO].total_pli_received_out,deltaNackCount:c-n[ie.VIDEO].total_nack_received_out}},R1=o=>({channels:o[ge.CHANNELS]||null,clock_rate:o[ge.CLOCK_RATE]||null,mime_type:o[ge.MIME_TYPE]||null,sdp_fmtp_line:o[ge.SDP_FMTP_LINE]||null}),$1=o=>({clock_rate:o[ge.CLOCK_RATE]||null,mime_type:o[ge.MIME_TYPE]||null}),x1=(o,n,r)=>{const a=(o[ge.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),c=(o[ge.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),e=o[ge.TIMESTAMP]||Date.now(),_=a-n.data.total_KBytes_in,g=c-n.data.total_KBytes_out,d=r?r.timestamp:null;let A=n.timestamp;!A&&d&&(A=d);const S=A?e-A:0,R=S>0?_*.008*1024/S*1e3:0,N=S>0?g*.008*1024/S*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:c,delta_KBytes_received:_,delta_KBytes_sent:g,kbs_speed_received:R,kbs_speed_sent:N}},O1=o=>{const n=o[ge.AVAILABLE_INCOMING_BITRATE]/1024||0,r=o[ge.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},k1=(o,n,r,a)=>{if(!o)return[];switch(o[ge.TYPE]){case Vr.CANDIDATE_PAIR:let c=!1;if(o[ge.NOMINATED]&&o[ge.STATE]===ie.SUCCEEDED&&(c=!0,Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o),ge.SELECTED in o&&!o[ge.SELECTED]&&(c=!1)),c){const _=o[ge.LOCAL_CANDIDATE_ID],g=o[ge.REMOTE_CANDIDATE_ID],d=x1(o,n,a),A=O1(o),S=T1(o,"data",a,n);return[{type:Me.NETWORK,value:{local_candidate_id:_}},{type:Me.NETWORK,value:{remote_candidate_id:g}},{type:Me.DATA,value:{total_KBytes_in:d.total_KBytes_received}},{type:Me.DATA,value:{total_KBytes_out:d.total_KBytes_sent}},{type:Me.DATA,value:{delta_KBytes_in:d.delta_KBytes_received}},{type:Me.DATA,value:{delta_KBytes_out:d.delta_KBytes_sent}},{type:Me.DATA,value:{delta_kbs_in:d.kbs_speed_received}},{type:Me.DATA,value:{delta_kbs_out:d.kbs_speed_sent}},{type:Me.DATA,value:{delta_kbs_bandwidth_in:A.kbs_incoming_bandwidth}},{type:Me.DATA,value:{delta_kbs_bandwidth_out:A.kbs_outgoing_bandwidth}},{type:Me.DATA,value:{delta_rtt_connectivity_ms:S.rtt}},{type:Me.DATA,value:{total_rtt_connectivity_ms:S.totalRTT}},{type:Me.DATA,value:{total_rtt_connectivity_measure:S.totalRTTMeasurements}}]}break;case Vr.LOCAL_CANDIDATE:if(o[ge.ID]===n.network.local_candidate_id)return[{type:Me.NETWORK,value:{infrastructure:E1(o)}},{type:Me.NETWORK,value:{local_candidate_type:o[ge.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{local_candidate_protocol:o[ge.PROTOCOL]||""}},{type:Me.NETWORK,value:{local_candidate_relay_protocol:S1(o)}}];break;case Vr.REMOTE_CANDIDATE:if(o[ge.ID]===n.network.remote_candidate_id)return[{type:Me.NETWORK,value:{remote_candidate_type:o[ge.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{remote_candidate_protocol:o[ge.PROTOCOL]||""}}];break;case Vr.INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const _=o[ge.SSRC],g=wn(_,n,Ht.INBOUND);g&&(g.timestamp=n.timestamp);const d=wn(_,a,Ht.INBOUND);if(d&&(d.timestamp=a.timestamp),o[ge.MEDIA_TYPE]===ie.AUDIO){const A=Df(o,ie.AUDIO,g,d),S=Bu(o,ie.AUDIO,g),R=o[ge.CODEC_ID]||"";return[{ssrc:_,type:Me.AUDIO,value:{codec_id_in:R}},{ssrc:_,type:Me.AUDIO,value:{total_packets_in:A.packetsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_in:A.deltaPacketsReceived}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_in:A.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_in:A.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_in:A.percentPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_in:A.KBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_in:A.deltaKBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_in:A.kbsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_in:S}}]}if(o[ge.MEDIA_TYPE]===ie.VIDEO){const A=b1(o,g),S=Df(o,ie.VIDEO,g,d),R=Bu(o,ie.VIDEO,g),N=o[ge.DECODER_IMPLEMENTATION]||null,H=o[ge.CODEC_ID]||null,W=Nf(o),G=A1(o,g,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_in:H}},{ssrc:_,type:Me.VIDEO,value:{total_packets_in:S.packetsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_in:S.deltaPacketsReceived}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_in:S.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_in:S.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_in:S.percentPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_in:S.KBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_in:S.deltaKBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_in:S.kbsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_in:R}},{ssrc:_,type:Me.VIDEO,value:{decoder_in:N}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_decode_frame_in:A.delta_ms_decode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_decoded_in:A.frames_decoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_decoded_in:A.total_decode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_sent_in:G.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_sent_in:G.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_sent_in:G.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_sent_in:G.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_in:W}}]}break}case Vr.OUTBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const _=o[ge.SSRC],g=wn(_,n,Ht.OUTBOUND);g&&(g.timestamp=n.timestamp);const d=wn(_,a,Ht.OUTBOUND);if(d&&(d.timestamp=a.timestamp),o[ge.MEDIA_TYPE]===ie.AUDIO){const A=o[ge.CODEC_ID]||null,S=Of(o,ie.AUDIO,g,d);return[{ssrc:_,type:Me.AUDIO,value:{codec_id_out:A}},{ssrc:_,type:Me.AUDIO,value:{total_packets_out:S.packetsSent}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_out:S.deltaPacketsSent}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_out:S.KBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_out:S.deltaKBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_out:S.kbsSent}}]}if(o[ge.MEDIA_TYPE]===ie.VIDEO){const A=o[ge.ENCODER_IMPLEMENTATION]||null,S=o[ge.CODEC_ID]||null,R=w1(o,g),N=Nf(o),H=C1(o),W=I1(o,g,d),G=Of(o,ie.VIDEO,g,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_out:S}},{ssrc:_,type:Me.VIDEO,value:{total_packets_out:G.packetsSent}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_out:G.deltaPacketsSent}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_out:G.KBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_out:G.deltaKBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_out:G.kbsSent}},{ssrc:_,type:Me.VIDEO,value:{encoder_out:A}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_encode_frame_out:R.delta_ms_encode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_encoded_out:R.frames_encoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_encoded_out:R.total_encode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_received_out:W.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_received_out:W.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_received_out:W.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_received_out:W.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_out:N}},{ssrc:_,type:Me.VIDEO,value:{limitation_out:H}}]}break}case Vr.MEDIA_SOURCE:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);break}case Vr.TRACK:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);break}case Vr.CODEC:const e=[];return Object.keys(n[ie.AUDIO]).forEach(_=>{const g=n[ie.AUDIO][_];if(g.codec_id_in===o[ge.ID]||g.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=R1(o);o[ge.ID]===g.codec_id_in?e.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_in:d}}):e.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_out:d}})}}),Object.keys(n[ie.VIDEO]).forEach(_=>{const g=n[ie.VIDEO][_];if(g.codec_id_in===o[ge.ID]||g.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=$1(o);o[ge.ID]===g.codec_id_in?e.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_in:d}}):e.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_out:d}})}}),e;case Vr.REMOTE_INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const _=o[ge.SSRC],g=wn(_,n,Ht.OUTBOUND),d=wn(_,a,Ht.OUTBOUND);if(o[ge.KIND]===ie.AUDIO){const A=xf(o,ie.AUDIO,d,g),S=Bu(o,ie.AUDIO,g),R=kf(o,ie.AUDIO,g,d);return[{ssrc:_,type:Me.AUDIO,value:{delta_rtt_ms_out:A.rtt}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_ms_out:A.totalRTT}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_measure_out:A.totalRTTMeasurements}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.AUDIO,value:{timestamp_out:o[ge.TIMESTAMP]}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_out:R.fractionLost}}]}if(o[ge.KIND]===ie.VIDEO){const A=xf(o,ie.VIDEO,d,g),S=Bu(o,ie.VIDEO,g),R=kf(o,ie.VIDEO,g,d);return[{ssrc:_,type:Me.VIDEO,value:{delta_rtt_ms_out:A.rtt}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_ms_out:A.totalRTT}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_measure_out:A.totalRTTMeasurements}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.VIDEO,value:{timestamp_out:o[ge.TIMESTAMP]}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_out:R.fractionLost}}]}break}}return[]},Vu=o=>o<0?1:o>100?4.5:1+.035*o+7/1e6*o*(o-60)*(100-o),D1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.INBOUND),_=wn(c,r,Ht.INBOUND),g=wn(c,a,Ht.INBOUND),d=[],A=[],S=e[n].percent_packets_lost_in,R=e[n].delta_jitter_ms_in,N=_&&_[n].delta_jitter_ms_in||null,H=g&&g[n].delta_jitter_ms_in||null,W=o.data.delta_rtt_connectivity_ms,G=r&&r.data.delta_rtt_connectivity_ms||null,K=a&&a.data.delta_rtt_connectivity_ms||null;W&&d.push(W),G&&d.push(G),K&&d.push(K),R&&A.push(R),r&&N&&A.push(N),a&&H&&A.push(H);const ae=d.length>0?mi(d):100,ee=A.length>0?mi(A):10,De=93.2-S,X=.18*De*De-27.9*De+1126.62,re=(ae+ee)/2,be=re-177.3<0?0:1,Ne=.024*re+.11*(re-177.3)*be,Q=X-Ne;return Vu(Q)},N1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.OUTBOUND),_=wn(c,r,Ht.OUTBOUND),g=wn(c,a,Ht.OUTBOUND),d=[],A=[],S=e[n].percent_packets_lost_out,R=e[n].delta_rtt_ms_out,N=_&&_[n].delta_rtt_ms_out||null,H=g&&g[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=g&&g[n].delta_jitter_ms_out||null,ae=o.data.delta_rtt_connectivity_ms,ee=r&&r.data.delta_rtt_connectivity_ms||null,De=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):ae&&d.push(ae),N?d.push(N):ee&&d.push(ee),H?d.push(H):De&&d.push(De),W&&A.push(W),r&&G&&A.push(G),a&&K&&A.push(K);const X=d.length>0?mi(d):100,re=A.length>0?mi(A):10,be=93.2-S,Ne=.18*be*be-27.9*be+1126.62,Q=(X+re)/2,ce=Q-177.3<0?0:1,me=.024*Q+.11*(Q-177.3)*ce,_e=Ne-me;return Vu(_e)},M1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.INBOUND),_=wn(c,r,Ht.INBOUND),g=wn(c,a,Ht.INBOUND),d=[],A=[],S=e[n].percent_packets_lost_in/100,R=e[n].delta_jitter_ms_in,N=_&&_[n].delta_jitter_ms_in||null,H=g&&g[n].delta_jitter_ms_in||null,W=o.data.delta_rtt_connectivity_ms,G=r&&r.data.delta_rtt_connectivity_ms||null,K=a&&a.data.delta_rtt_connectivity_ms||null;W&&d.push(W),G&&d.push(G),K&&d.push(K),R&&A.push(R),_&&N&&A.push(N),g&&H&&A.push(H);const ae=d.length>0?mi(d):100,ee=A.length>0?mi(A):10,De=0,X=19.8,re=29.7,be=30,Ne=(ae+ee)/2+be,Q=Ne-177.3<0?0:1,ce=.024*Ne+.11*(Ne-177.3)*Q,me=93.2-(De+X*Math.log(1+re*S)+ce);return Vu(me)},U1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.OUTBOUND),_=wn(c,r,Ht.OUTBOUND),g=wn(c,a,Ht.OUTBOUND),d=[],A=[],S=e[n].percent_packets_lost_out/100,R=e[n].delta_rtt_ms_out,N=_&&_[n].delta_rtt_ms_out||null,H=g&&g[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=g&&g[n].delta_jitter_ms_out||null,ae=o.data.delta_rtt_connectivity_ms,ee=r&&r.data.delta_rtt_connectivity_ms||null,De=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):ae&&d.push(ae),N?d.push(N):ee&&d.push(ee),H?d.push(H):De&&d.push(De),W&&A.push(W),_&&G&&A.push(G),g&&K&&A.push(K);const X=d.length>0?mi(d):100,re=A.length>0?mi(A):10,be=0,Ne=19.8,Q=29.7,ce=30,me=(X+re)/2+ce,_e=me-177.3<0?0:1,ue=.024*me+.11*(me-177.3)*_e,ye=93.2-(be+Ne*Math.log(1+Q*S)+ue);return Vu(ye)};class P1{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=p1(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new v1(n),this._state=Fs.IDLE,this.registerToPCEvents(),wa(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,a,c){const e=(d,A)=>d===ie.AUDIO?A===Vr.INBOUND_RTP?{...Ef}:{...Cf}:A===Vr.INBOUND_RTP?{...Af}:{...If},_=l1(r);_.pname=this._config.pname,_.call_id=this._config.cid,_.user_id=this._config.uid,_.count=r?r.count+1:1;let g=null;return n.forEach(d=>{!g&&d.timestamp&&(g=d.timestamp),k1(d,_,_.pname,c).forEach(A=>{if(A.value&&A.type)if(A.ssrc){let S=_[A.type][A.ssrc];S||(S=e(A.type,d.type),S.ssrc=A.ssrc,_[A.type][A.ssrc]=S),Object.keys(A.value).forEach(R=>{S[R]=A.value[R]})}else Object.keys(A.value).forEach(S=>{_[A.type][S]=A.value[S]})})}),_.timestamp=g,Object.keys(_[ie.AUDIO]).forEach(d=>{const A=_[ie.AUDIO][d];A.direction===Ht.INBOUND?(A.mos_emodel_in=D1(_,ie.AUDIO,r,a,A.ssrc),A.mos_in=M1(_,ie.AUDIO,r,a,A.ssrc)):(A.mos_emodel_out=N1(_,ie.AUDIO,r,a,A.ssrc),A.mos_out=U1(_,ie.AUDIO,r,a,A.ssrc))}),_}async takeReferenceStats(){return new Promise((n,r)=>{const a=Date.now();setTimeout(async()=>{try{const c=Date.now()-a,e=Date.now(),_=await this._config.pc.getStats(),g=this.analyze(_,null,null,null),d=Date.now();g.experimental.time_to_measure_ms=d-e,g.experimental.time_to_wait_ms=c,this._exporter.saveReferenceReport(g),Rt(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(c){r(c)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Fs.RUNNING||!this._config.pc)return Rt(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),a=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),c=Date.now();return a.experimental.time_to_measure_ms=c-n,this._exporter.addReport(a),Rt(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(n){return so(this._moduleName,`got error ${n}`),null}}async start(){Rt(this._moduleName,"starting"),this.state=Fs.RUNNING,this._startedTime=this._exporter.start(),Rt(this._moduleName,"started")}async mute(){this.state=Fs.MUTED,Rt(this._moduleName,"muted")}async unmute(){this.state=Fs.RUNNING,Rt(this._moduleName,"unmuted")}async stop(n){if(Rt(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Fs.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Rt(this._moduleName,"stopped")}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(this._moduleName,`registered callback '${n}'`)):so(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&qd(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&qd(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Rt(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,a,c){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:a,description:c})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{so(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const a=n.iceConnectionState;a===ml.CONNECTED||a===ml.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.DISCONNECTED||a===ml.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const a=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},n.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=n.getReceivers();if(r&&r.length>0){const a=r[0],{transport:c}=a;if(c){const{iceTransport:e}=c;e&&(e.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class L1{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||h1(),this._moduleName=this._id,wa(this._moduleName,"probe created"),this._config=n,this._collector=new P1(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):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(n){this._collector.state=n}addCustomEvent(n,r,a,c=new Date().toJSON()){this._collector.addCustomEvent(c,r,n,a)}get isRunning(){return this._collector.state===Fs.RUNNING}get isIdle(){return this._collector.state===Fs.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Fu(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const jn="engine ";class q1{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},wa(jn,`configured for probing every ${this._config.refreshEvery}ms`),wa(jn,`configured for starting after ${this._config.startAfter}ms`),wa(jn,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Rt(jn,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,r){if(!n)throw new Error("undefined peer connection");const a=c1(n,r,this._config),c=new L1(a);return this._probes.push(c),Rt(jn,`${this._probes.length} probes registered`),c}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===Fs.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(e=>e.start())},r=async()=>Promise.all(this._probes.map(e=>e.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,c=async()=>{const e=o1(),_=this._probes.filter(g=>g.isRunning);for(const g of _){const d=await g.collectStats();d&&e.probes.push(d),Rt(jn,`got probe ${g.id}`),await Rf(0)}return e.delta_time_to_measure_probes_ms=Sa(e.probes,"experimental","time_to_measure_ms"),e.delta_KBytes_in=Sa(e.probes,"data","delta_KBytes_in"),e.delta_KBytes_out=Sa(e.probes,"data","delta_KBytes_out"),e.delta_kbs_in=Sa(e.probes,"data","delta_kbs_in"),e.delta_kbs_out=Sa(e.probes,"data","delta_kbs_out"),e.total_time_decoded_in=Sa(e.probes,"video","total_time_decoded_in"),e.total_time_encoded_out=Sa(e.probes,"video","total_time_encoded_out"),e};for(Rt(jn,"starting to collect"),n(),Rt(jn,"generating reference reports..."),await r(),Rt(jn,"reference reports generated"),this._startedTime=Date.now();a();)if(Rt(jn,`wait ${this._config.refreshEvery}ms before collecting`),await Rf(this._config.refreshEvery),a()){Rt(jn,"collecting...");const e=Date.now(),_=await c(),g=Date.now();_.delta_time_consumed_to_measure_ms=g-e,this.fireOnReports(_),Rt(jn,"collected")}Rt(jn,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=a=>{this._probes.forEach(c=>{c.stop(a)})};wa(jn,"stop collecting"),r(n)}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(jn,`registered callback '${n}'`)):so(jn,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&qd(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const H1="interface ";class z1{constructor(n){this._config=d1(n),wa(H1,`welcome to ${this._config.name} version ${this._config.version}`),ZA(this._config.verbose||!1),this._engine=new q1(this._config)}setupLogLevel(n){e1(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,r){return this._engine.addNewProbe(n,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function F1(o,n){return Object.keys(o).filter(r=>n.includes(r)).reduce((r,a)=>{const c=a;return{...r,[c]:o[c]}},{})}const B1=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],V1={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class j1{constructor(n){this.intervals={},this.analysers={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}async start(n,r,a){r&&r.getTracks().length&&await this.beginCalculation(n,r,a)}stop(n){this.clearVolumeInterval(n),this.analysers[n]&&typeof this.analysers[n].disconnect=="function"&&(this.analysers[n].disconnect(),delete this.analysers[n])}clearVolumeInterval(n){this.intervals[n]&&(clearInterval(this.intervals[n]),delete this.intervals[n])}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{this.stop(n)}),this.intervals={},this.analysers={}}async beginCalculation(n,r,a){this.clearVolumeInterval(a);const c=n.createAnalyser(),e=n.createMediaStreamSource(r);c.smoothingTimeConstant=.8,c.fftSize=1024,e.connect(c),this.analysers[a]=c,this.intervals[a]=setInterval(()=>{const _=new Uint8Array(c.frequencyBinCount);c.getByteFrequencyData(_);let g=0;const d=_.length;for(let S=0;S<d;S++)g+=_[S];const A=g/d;this.onChangeFunction(a,A)},this.emitInterval)}}class G1{constructor(){this.resumePromise=null,this.context=new AudioContext}async getContext(){return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{throw this.resumePromise=null,n})),await this.resumePromise),this.context}}const ju={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},W1=0;class K1{constructor(n){var r;this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.isCallWaitingEnabled=!0,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.conferenceNodes={},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.vadSessions={},this.vadSessionsState={},this.vadIntervals={},this.vadMrsIntervals={},this.managedAudioContext=new G1,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new j1({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices(),this.processVADConfiguration(((r=this.context.options.configuration)==null?void 0:r.noiseReductionOptions)||{}),this.setupVADInstance()}setVADConfiguration(n){if(!this.MicVAD)throw new Error("VAD module is not provided in the initial configuration");const r=Object.keys(n);for(const a of r)this.noiseReduction[a]=n[a];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,r;const a=(r=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:r.vadModule;a&&a.MicVAD?(this.MicVAD=a.MicVAD,console.log("✅ VAD module loaded successfully")):this.noiseReduction.mode!=="disabled"&&(console.warn("⚠️ Noise reduction is enabled but VAD module is not provided. To use VAD features, please install @ricky0123/vad-web and pass it via configuration.noiseReductionOptions.vadModule option."),this.noiseReduction.mode="disabled")}processVADConfiguration(n){this.noiseReduction={mode:n.mode||"disabled",checkEveryMs:n.checkEveryMs||500,noiseCheckInterval:n.noiseCheckInterval||2e3,noiseThreshold:n.noiseThreshold||.004,vadConfig:n.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}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 hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(n=>!n.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return Tf()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(ju.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(ju.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),c=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(c),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}),a.getTracks().forEach(e=>e.stop())}catch(a){console.error(a)}}async cleanupConferenceNodes(n){const r=this.conferenceNodes[n];if(!r)return;let a=0;r.sources.forEach((_,g)=>{try{_.disconnect(),a++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting source ${g}:`,d)}});let c=0;r.destinations.forEach((_,g)=>{try{_.disconnect(),c++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${g}:`,d)}});let e=0;r.gains.forEach((_,g)=>{try{_.disconnect(),e++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${g}:`,d)}}),delete this.conferenceNodes[n]}setCallTime(n){const r={...n};delete r.callId,this.callTime={...this.callTime,[n.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const r={...this.callTime};delete r[n],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,r){this.timeIntervals={...this.timeIntervals,[n]:r}}removeTimeInterval(n){const r={...this.timeIntervals};r[n]&&(clearInterval(r[n]),delete r[n],this.timeIntervals={...r})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,r){this.context.emit("changeCallVolume",{callId:n,volume:r})}getNoiseReductionMode(){return this.noiseReduction.mode}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9*#]+$/g.test(r))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[n].sendDTMF(r)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const r=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:a}){const c=this.extendedCalls[n];if(!c)return;c._automaticHold=a??!1;const e=new Promise((_,g)=>{const d=setTimeout(()=>{g(new Error("Hold operation timeout"))},5e3),A=()=>{clearTimeout(d),c.putOnHoldTimestamp=r?Date.now():void 0,_()},S=R=>{clearTimeout(d),g(R)};try{r?(this.stopSessionVad(c._id),c.hold({},A)):c.unhold({},A)}catch(R){S(R)}});try{await e,this.updateCall(c);const _=Object.values(this.extendedCalls).filter(g=>g.roomId===c.roomId&&(r?n!==g._id:!0));_.length>1&&await this.doConference(_)}catch(_){throw console.error("Hold operation failed:",_),_}}holdCall(n,r=!1){return this.processHold({callId:n,automatic:r,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===W1).forEach(n=>this.terminateCall(n._id))}answerCall(n){const r=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",a=>{this.triggerAddStream(a,r)})}async moveCall(n,r){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:r}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=yf(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const r={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...r}},this.context.emit("updateRoom",{room:r,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const r=/answer-after=0/,a=n.request.getHeader("Call-Info");return a&&r.test(a)}addCall(n,r=!0){this.activeCalls={...this.activeCalls,[n._id]:yf(n)},this.extendedCalls[n._id]=n,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const r={...this.callStatus[n.callId]};n.isMoving!==void 0&&(r.isMoving=n.isMoving),n.isTransferring!==void 0&&(r.isTransferring=n.isTransferring),n.isMerging!==void 0&&(r.isMerging=n.isMerging),n.isTransferred!==void 0&&(r.isTransferred=n.isTransferred),this.callStatus={...this.callStatus,[n.callId]:{...r}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const r={...this.callStatus};delete r[n],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}async setupActiveStream(){const n=await Dd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n)}async getActiveStream(){const n=await Dd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:a})=>a===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async a=>{await this.setupActiveStream();const c=this.activeStream;a.connection.getSenders()[0].replaceTrack(c.getTracks()[0]),this.updateCall(a)}):await this.doConference(r)}async setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:c})=>c===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const a=r.filter(c=>c.roomId===this.currentActiveRoomId);a.length===1?r.forEach(c=>{var e;(e=c.audioTag)==null||e.setSinkId(n),this.updateCall(c)}):await this.doConference(a)}removeRoom(n){const r={...this.activeRooms},a={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}startNoiseMonitor({sessionId:n,stream:r,onNoiseDetected:a,onNoiseStop:c}){const e=new AudioContext,_=e.createMediaStreamSource(r.clone()),g=e.createAnalyser();g.fftSize=1024;const d=new Float32Array(g.fftSize);_.connect(g);const A=[];this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),this.vadIntervals[n]=null),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),this.vadMrsIntervals[n]=null),this.vadMrsIntervals[n]=setInterval(()=>{g.getFloatTimeDomainData(d);const S=KA(d);A.push(S);const R=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);A.length>R&&A.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[n]=setInterval(()=>{if(A.length===0)return;const S=A.reduce((H,W)=>H+W,0)/A.length,R=this.vadSessionsState[n],N=S>this.noiseReduction.noiseThreshold;R.isSpeaking||(N&&R.currentMode==="clean"?(R.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!0}),a()):!N&&R.currentMode==="noisy"&&(R.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!1}),c()))},this.noiseReduction.noiseCheckInterval)}async processVAD(n,r){const a=r.clone();this.stopSessionVad(n._id),this.vadSessionsState[n._id]={currentMode:"clean",isSpeaking:!1};const c=await this.managedAudioContext.getContext(),e=await YA(a,c,150);let _=!1;const g=await this.MicVAD.new({getStream:()=>new Promise(d=>d(a)),...V1,...this.noiseReduction.vadConfig,baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",onFrameProcessed:()=>{if(!_){if(_=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){n.connection.getSenders()[0]&&n.connection.getSenders()[0].replaceTrack(e.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:n._id,stream:a,onNoiseDetected:async()=>{var d;console.log("Replace track with Vad Controlled"),await((d=n.connection.getSenders()[0])==null?void 0:d.replaceTrack(e.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const d=n.connection.getSenders()[0];d&&d.track&&d.transport&&d.transport.state!=="closed"&&d.transport.state!=="failed"&&(console.log("Replace track with Original"),await d.replaceTrack(a.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var d;console.log("🎤 Speech started"),e.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((d=n.connection.getSenders()[0])==null||d.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!0},onSpeechEnd:()=>{var d;console.log("🛑 Speech end"),e.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((d=n.connection.getSenders()[0])==null||d.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!1}});this.vadSessions[n._id]&&(this.vadSessions[n._id].pause(),delete this.vadSessions[n._id]),this.vadSessions[n._id]=g,g.start()}stopSessionVad(n){this.vadSessions[n]&&(this.vadSessions[n].pause(),delete this.vadSessions[n]),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]),this.vadSessionsState[n]&&delete this.vadSessionsState[n]}async roomReconfigure(n){var r;if(n===void 0)return;const a=Object.values(this.extendedCalls).filter(e=>e.roomId===n),c=this.currentActiveRoomId===n;if(a.forEach((e,_)=>{if(e.audioTag){e.connection.getReceivers().forEach(d=>{d.track.enabled=!e.localMuted}),c&&this.muteReconfigure(e);const g=!c;e.audioTag.muted=g,this.updateCall(e)}}),a.length===0){this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n),this.deleteRoomIfEmpty(n);return}if(a.length===1&&!c){const e=a[0];e.isOnHold().local||await this.holdCall(e._id,!0),this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}if(a.length===1&&c){const e=a[0];e.isOnHold().local&&e._automaticHold&&await this.unholdCall(e._id);const _=(((r=e.connection)==null?void 0:r.getSenders())||[])[0];if(e.connection&&_)try{await this.setupActiveStream();const g=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(a[0],g);const d=g.getTracks();await _.replaceTrack(d[0]),this.muteReconfigure(e)}catch(g){console.error(g)}this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}a.length>1&&await this.doConference(a)}async doConference(n){if(n.length===0)return;const r=n[0].roomId,a=this.currentActiveRoomId===r;if(n.find(g=>g.roomId!==r))return;const c=await this.managedAudioContext.getContext();if(c.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${c.state}`);return}await this.cleanupConferenceNodes(r),this.conferenceNodes[r]={sources:new Map,destinations:new Map,gains:new Map};const e=this.conferenceNodes[r],_=new Map;n.forEach((g,d)=>{g&&g.connection&&g.connection.getReceivers().forEach((A,S)=>{var R,N,H;A.track.enabled=!g.localMuted;const W=(R=A.track)==null?void 0:R.id;(N=A.track)==null||N.readyState,(H=A.track)==null||H.kind;const G=`${g._id}-${W}`;A.track&&A.track.readyState==="live"&&_.set(G,A.track)})}),await this.setupActiveStream(),await XA.forEach(n,async(g,d)=>{if(!g||!g.connection)return;const A=c.createMediaStreamDestination();e.destinations.set(g._id,A);let S=0;if(_.forEach((H,W)=>{if(!W.startsWith(g._id))try{const G=c.createMediaStreamSource(new MediaStream([H])),K=c.createGain(),ae=`${g._id}-${W}`;G.connect(K),K.connect(A),e.sources.set(ae,G),e.gains.set(ae,K),S++}catch(G){console.error(G)}}),a&&this.activeStreamValue)try{const H=this.activeStream,W=c.createMediaStreamSource(H),G=c.createGain(),K=`${g._id}-local`;W.connect(G),G.connect(A),e.sources.set(K,W),e.gains.set(K,G)}catch(H){console.error(H)}else a&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${g._id}`);const R=g.connection.getSenders()[0],N=A.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(g,A.stream),R&&N[0])try{await R.replaceTrack(N[0]),this.muteReconfigure(g)}catch(H){console.error(H)}})}processCallerMute(n,r){const a=this.extendedCalls[n];a&&a.connection.getReceivers().length&&(a.localMuted=r,a.connection.getReceivers().forEach(c=>{c.track.enabled=!r}),this.updateCall(a))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status===4?r.terminate({status_code:603,reason_phrase:"Decline"}):r._status!==8&&r.terminate()}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[n];if(!a._is_confirmed&&!a._is_canceled){const c=`sip:${r}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${c}`]});return}this.updateCallStatus({callId:n,isTransferring:!0,isTransferred:!1}),a.refer(`sip:${r}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(a)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(e=>e.roomId===n);if(r.length!==2)return;const a=r[0],c=r[1];!a||!c||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:c._id,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a))}mergeCallByIds(n,r){const a=Object.values(this.extendedCalls).find(e=>e._id===n),c=Object.values(this.extendedCalls).find(e=>e._id===r);if(!a||!c)throw new Error("Call ID is not provided");this.updateCallStatus({callId:n,isMerging:!0}),this.updateCallStatus({callId:r,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a)}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}setCallWaiting(n){this.isCallWaitingEnabled=n,this.context.emit("changeIsCallWaiting",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const a=setInterval(()=>{const c={...this.callTime[n]},e=WA(c);this.setCallTime({callId:n,...e})},1e3);this.setTimeInterval(n,a)}async setActiveRoom(n){const r=this.currentActiveRoomId;n!==r&&(this.currentActiveRoomId=n,await this.roomReconfigure(r),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var r,a;const c=n.session;if(this.getActiveCalls[c.id]!==void 0)return;const e=this.getNewRoomId(),_={started:new Date,incomingInProgress:!1,roomId:e};if(c.direction==="incoming")this.context.logger.log("New incoming call from",(a=(r=c._remote_identity)==null?void 0:r._uri)==null?void 0:a._user),_.incomingInProgress=!0,this.context.subscribe(Br.CALL_CONFIRMED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.startCallTimer(c.id))}),this.context.subscribe(Br.CALL_FAILED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.deleteRoomIfEmpty(e))});else if(c.direction==="outgoing"){const S=R=>{R.response&&R.response.status_code===JA.SESSION_PROGRESS&&(this.startCallTimer(c.id),c.off("progress",S))};c.on("progress",S),c.once("confirmed",()=>{this.startCallTimer(c.id)})}const g=c,d=this.hasAutoAnswerHeaders(n),A=g.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);g.roomId=e,g.localMuted=!1,g.autoAnswer=A,A?this.addCall(g,!1):this.addCall(g),this.addCallStatus(c.id),this.addRoom(_),A&&this.answerCall(g._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const a={...this.extendedCalls};delete a[n],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];if(!r)return;this.stopVUMeter("origin"),this.stopVUMeter(n._id);const a=r.roomId;this.removeCall(n._id),this.roomReconfigure(a).then(()=>{}).catch(c=>{console.error("Error reconfiguring room after call removal:",c)})}shouldTerminateNewSession(n){if(n.session.direction==="outgoing")return!1;const r=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||r}async newRTCSessionCallback(n){const r=n.session;if(this.shouldTerminateNewSession(n)){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}this.context.triggerListener({listenerType:Br.NEW_CALL,session:r,event:n}),r.on("ended",c=>{var e,_,g;if(this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_ENDED,session:r,event:c}),r.connection){const A=r.connection.connectionState;(A==="closed"||A==="disconnected")&&this.context.emit("connectionStateChange",A)}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(A=>A.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("progress",c=>{var e,_;this.context.logger.log("Session in progress for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_PROGRESS,session:r,event:c})}),r.on("failed",c=>{var e,_,g;if(this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_FAILED,session:r,event:c}),r.connection){const A=r.connection.connectionState;(A==="closed"||A==="disconnected")&&this.context.emit("connectionStateChange",A)}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(A=>A.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("confirmed",c=>{var e,_;this.context.logger.log("Session confirmed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_CONFIRMED,session:r,event:c}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)});const a=c=>{c&&c.addEventListener("connectionstatechange",e=>{this.context.emit("connectionStateChange",c.connectionState)})};if(r.connection&&a(r.connection),r.on("peerconnection",({peerconnection:c})=>{a(c)}),await this.setupCall(n),r.direction==="outgoing"){const c=this.getActiveCalls[r.id].roomId;await this.setActiveRoom(c)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=n,this.updateCall(r))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(ju.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(ju.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const r={...n};delete r.callId,this.callMetrics={...this.callMetrics,[n.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const r={...this.callMetrics};delete r[n],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const r=new z1(this.metricConfig),a=r.createProbe(n.connection,{cid:n._id}),c=[];let e;a.onreport=_=>{Object.entries(_.audio).forEach(([A,S])=>{S.direction==="inbound"&&!c.includes(A)&&(c.push(A),e=A)});const g=_.audio[e];if(!g)return;const d=F1(g,B1);d.callId=n._id,this.setCallMetrics(d)},this.context.subscribe(Br.CALL_ENDED,_=>{_._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}async setupVUMeter(n,r){await this.VUMeter.start(await this.managedAudioContext.getContext(),n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){try{const n=Date.now(),r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((a,c)=>{a.stop()}),this.initialStreamValue=null),this.initialStreamValue=r}catch(n){throw n}}async triggerAddStream(n,r){const a=this.muteWhenJoin||this.isMuted;this.setIsMuted(a),this.initialStreamValue||await this.setupStream();const c=await this.managedAudioContext.getContext(),e=await Dd(c,this.initialStreamValue,this.microphoneInputLevel*2),_=this.isMuted||this.muteWhenJoin;e.getTracks().forEach(A=>{A.enabled=!_}),await this.setActiveStream(e),await r.connection.getSenders()[0].replaceTrack(e.getTracks()[0]);const g=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(A=>A.audioTag&&A.audioTag.id===r._id)&&kA(g,r,this.selectedOutputDevice,this.speakerVolume);const d=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!d),await this.setupVUMeter(g,r._id),this.getCallQuality(r),this.updateCall(r),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r,e)}initCall(n,r,a=!1){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const c=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=c.id,r&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:c.id,roomId:this.currentActiveRoomId}),a)){const e=Object.values(this.extendedCalls).filter(_=>_.roomId===this.currentActiveRoomId&&_._id!==c.id);for(const _ of e)this.holdCall(_._id,!0)}c.connection.addEventListener("track",e=>{this.triggerAddStream(e,c)})}async processRoomChange({callId:n,roomId:r}){const a=this.extendedCalls[n];if(!a)return;const c=a.roomId;a.roomId=r,this.updateCall(a),await this.roomReconfigure(c),await this.roomReconfigure(r)}}class Y1{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n,r){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,r,this.sipOptions)}stop(n={}){this.context.terminateJanusSessions(n)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(n){this.context.changeMediaConstraints(n)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class X1{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const r=this.extendedMessages[n];this.updateMSRPSession(r)}updateMSRPSession(n){this.activeMessages[n._id]=vf(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:vf(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const a=this.msrpHistory[r.id]||[];a.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...a]},this.context.emit("newMSRPMessage",{message:n,session:r})}messageTerminate(n){const r=this.extendedMessages[n];r._status!==8&&r.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const r=n;this.addMMSRPSession(r)}triggerMSRPListener({listenerType:n,session:r,event:a}){const c=this.context.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const a={...this.extendedMessages};delete a[n],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){n.session._id||(n.session._id=n.request.call_id+n.request.from._parameters.tag);const r=n.session;r.on("ended",a=>{this.triggerMSRPListener({listenerType:Br.CALL_ENDED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("failed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_FAILED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_CONFIRMED,session:r,event:a}),this.updateMSRPSession(r)}),r.on("newMessage",a=>{this.addMSRPMessage(a,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,a){if(n.length===0)return console.error("Target must be a valid string");const c=this.context.startMSRP(n,a);c.on("active",()=>{this.addMessageSession(c),c.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const a=this.extendedMessages[n];if(!a)throw new Error(`MSRP session with id ${n} doesn't exist!`);a.sendMSRP(r)}}const Gu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Mf{constructor(n){this.opensips=null,this.session=null,this.name=null,this.name=n}setOpensips(n){this.opensips=n}setSession(n){this.session=n}kill(){this.opensips.kill(this.name)}}class J1 extends Mf{constructor(n,r){super(n),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=r}connect(n={}){this.opaqueId=this.session.generateOpaqueId();const r=kt.cloneArray(n.extraHeaders),a={from_tag:this.session._from_tag};n.fromUserName&&(a.from_uri=new ba("sip",n.fromUserName,this.session._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(a.from_display_name=n.fromDisplayName),r.push(`Contact: ${this.session._contact}`),r.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&r.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new On.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,r),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let n;this._connection.onicecandidate=r=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||r.candidate&&(this._candidates.push(r.candidate),clearTimeout(n),n=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(n){n.forEach(r=>{this._connection.addTrack(r)})}async _sendInitialRequest(){const n=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const r={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(r),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},c=JSON.stringify(a);this._request.body=c,n.send()}_receiveInviteResponse(n){if(this._publisherSubscribeSent||!n.body)return;const r=JSON.parse(n.body);this.handleId=r.data.id;const a={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},c=[this.session.getPTypeHeader(ir.PUBLISHER)];this.session.sendRequest(oe.SUBSCRIBE,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{var _,g,d,A;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((g=(_=S.plugindata)==null?void 0:_.data)==null?void 0:g.videoroom)==="joined"&&this.session.myFeedList.push(S.plugindata.data.id),(A=(d=S.plugindata)==null?void 0:d.data)!=null&&A.publishers&&this.session.receivePublishers(S)}catch(S){console.error(S)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(n){const r=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handleId,session_id:this.session.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...n},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...r]},c=["Content-Type: application/json",this.session.getPTypeHeader(ir.ICE)];this.session.sendRequest(oe.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{this._configureSent=!0;const _=e.data.split(`\r
|
|
158
|
+
`,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function bA(o,n,r,a){let c;const e=n.indexOf(":",r),_=n.substring(r,e).trim(),g=n.substring(e+1,a).trim();switch(_.toLowerCase()){case"via":case"v":o.addHeader("via",g),o.getHeaders("via").length===1?(c=o.parseHeader("Via"),c&&(o.via=c,o.via_branch=c.branch)):c=0;break;case"from":case"f":o.setHeader("from",g),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",g),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=kd.parse(g,"Record_Route"),c===-1)c=void 0;else for(const d of c)o.addHeader("record-route",g.substring(d.possition,d.offset)),o.headers["Record-Route"][o.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":o.setHeader("call-id",g),c=o.parseHeader("call-id"),c&&(o.call_id=g);break;case"contact":case"m":if(c=kd.parse(g,"Contact"),c===-1)c=void 0;else for(const d of c)o.addHeader("contact",g.substring(d.possition,d.offset)),o.headers.Contact[o.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":o.setHeader("content-length",g),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",g),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",g),c=o.parseHeader("cseq"),c&&(o.cseq=c.value),o instanceof Za.IncomingResponse&&(o.method=c.method);break;case"max-forwards":o.setHeader("max-forwards",g),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",g),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",g),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",g),c=o.parseHeader("session-expires"),c&&(o.session_expires=c.expires,o.session_expires_refresher=c.refresher);break;case"refer-to":case"r":o.setHeader("refer-to",g),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",g),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",g),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(_,g),c=0}return c===void 0?{error:`error parsing header "${_}"`}:!0}const wA={parseMessage:vA},_l=new wu("Registrator"),zu=10;class SA{constructor(n,r){this._reg_id=1,this._ua=n,this._transport=r,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=qs.createRandomToken(22),this._cseq=0,this._to_uri=n.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const c=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=c}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(n){Array.isArray(n)||(n=[]),this._extraHeaders=n.slice()}setExtraContactParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){_l.debug("Register request in progress...");return}const n=this._extraHeaders.slice();n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),n.push(`Expires: ${this._expires}`);const r=new On.OutgoingRequest(oe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n),a=new sl(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,oe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,oe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{if(c.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):{if(this._registering=!1,!c.hasHeader("Contact")){_l.debug("no Contact header in response to REGISTER, response ignored");break}const e=c.headers.Contact.reduce((A,S)=>A.concat(S.parsed),[]);let _=e.find(A=>this._sipInstance===A.getParam("+sip.instance")&&this._reg_id===parseInt(A.getParam("reg-id")));if(_||(_=e.find(A=>A.uri.user===this._ua.contact.uri.user)),!_){_l.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let g=_.getParam("expires");!g&&c.hasHeader("expires")&&(g=c.getHeader("expires")),g||(g=this._expires),g=Number(g),g<zu&&(g=zu);const d=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):Math.floor(g*1e3/2);this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),_.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=_.getParam("temp-gruu").replace(/"/g,"")),_.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=_.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:c}));break}case/^423$/.test(c.status_code):{c.hasHeader("min-expires")?(this._expires=Number(c.getHeader("min-expires")),this._expires<zu&&(this._expires=zu),this.register()):(_l.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(c,oe.causes.SIP_FAILURE_CODE));break}default:{const e=qs.sipErrorCause(c.status_code);this._registrationFailure(c,e)}}}});this._registering=!0,a.send()}unregister(n={}){if(!this._registered){_l.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();n.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),r.push("Expires: 0");const a=new On.OutgoingRequest(oe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new sl(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,oe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,oe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{switch(!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):this._unregistered(c);break;default:{const e=qs.sipErrorCause(c.status_code);this._unregistered(c,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(n,r){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:r}))}_unregistered(n,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:r||null})}}const un=console,fi={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},EA=cA;class CA extends EA{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new SA(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(n,r){return super.call(n,r)}joinVideoCall(n,r,a){un.debug("call()");const c=new qu(this);return c.configureMedia({audio:!0,video:!0}),c.connect(n,r,a),c}startScreenShare(){un.debug("startScreenShare()");for(const n in this._janus_sessions)this._janus_sessions[n].connectScreenShare()}changeMediaConstraints(n){for(const r in this._janus_sessions)this._janus_sessions[r].changeMediaConstraints(n)}startBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].connectBlur()}stopBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].stopBlur()}_loadConfig(n){try{pl.load(this._configuration,n)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=qs.newUUID());let r;typeof window<"u"&&typeof window.document<"u"?r=window?.navigator.userAgent:typeof self<"u"&&self.navigator&&(r=self.navigator.userAgent),r+=" "+bt.USER_AGENT,this._configuration.user_agent=n.overrideUserAgent&&typeof n.overrideUserAgent=="function"?n.overrideUserAgent(r):r,n.onTransportCallback&&typeof n.onTransportCallback=="function"&&(this.onTransportCallback=n.onTransportCallback),this._configuration.jssip_id=qs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new UC(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=AA.bind(this),this._transport.onconnect=IA.bind(this),this._transport.ondisconnect=RA.bind(this),this._transport.ondata=$A.bind(this)}catch(e){throw un.warn(e),new di.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 e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ba("sip",qs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){const _=e.anonymous||null,g=e.outbound||null;let d="<";return _?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),g&&(_?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",d}};const c=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(c.indexOf(e)!==-1?Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}));un.debug("configuration parameters after validation:");for(const e in this._configuration)if(Object.prototype.hasOwnProperty.call(pl.settings,e))switch(e){case"uri":case"registrar_server":un.debug(`- ${e}: ${this._configuration[e]}`);break;case"password":case"ha1":case"authorization_jwt":un.debug(`- ${e}: NOT SHOWN`);break;default:un.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}newMSRPSession(n,r){n.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.newStreamPlugins.forEach(a=>{a.setSession(n)}),this.processStreamPlugins.forEach(a=>{a.setSession(n)}),this.emit("newJanusSession",r)}kill(){}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(n){var r,a,c,e;const _=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){un.debug("Request-URI does not point to us"),n.method!==bt.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===bt.SIPS){n.reply_sl(416);return}if(Ir.checkTransaction(this,n))return;if(_===bt.INVITE?new Ir.InviteServerTransaction(this,this._transport,n):_!==bt.ACK&&_!==bt.CANCEL&&new Ir.NonInviteServerTransaction(this,this._transport,n),_===bt.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const A=Date.now(),S=this.lastOptionsTimestamp>A-35e3,R=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>A;S&&R&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){n.reply(200);return}new b_.Options(this).init_incoming(n)}else if(_===bt.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new b_.Message(this).init_incoming(n)}else if(_===bt.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let g,d;if(n.to_tag)if(g=this._findDialog(n.call_id,n.from_tag,n.to_tag),g)g.receiveRequest(n);else if(_===bt.NOTIFY)if(d=this._findSession(n),d)d.receiveRequest(n);else{if(n.body)try{const A=JSON.parse(n.body)||{};(a=(r=A.plugindata)==null?void 0:r.data)!=null&&a.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(A),(e=(c=A.plugindata)==null?void 0:c.data)!=null&&e.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(A.plugindata.data.unpublished)}catch(A){console.error(A)}n.reply(200)}else _!==bt.ACK&&n.reply(481);else switch(_){case bt.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const A=n.replaces;g=this._findDialog(A.call_id,A.from_tag,A.to_tag),g?(d=g.owner,d.isEnded()?n.reply(603):d.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(d=new Od(this),d.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(d=new TC(this),d.init_incoming(n));else un.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case bt.BYE:n.reply(481);break;case bt.CANCEL:d=this._findSession(n),d?d.receiveRequest(n):un.debug("received CANCEL request for a non existent session");break;case bt.ACK:break;case bt.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){un.debug("startMSRP()",r);const a=new Od(this);return a.connect(n),a}startJanus(n,r){un.debug("startJanus()",r);const a=new Od(this);return a.connect(n),a}terminateMSRPSessions(n){un.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){un.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}enableJanusAudio(n){un.debug("enableJanusAudio()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startAudio():this._janus_sessions[r].stopAudio())}enableJanusVideo(n){un.debug("enableJanusVideo()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startVideo():this._janus_sessions[r].stopVideo())}terminateAllSessions(){for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){un.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch(r){console.error(r)}}}stop(n=!0){if(un.debug("stop()"),this._dynConfiguration={},this._status===fi.STATUS_USER_CLOSED){un.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;n&&this.terminateAllSessions();for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){un.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){un.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(c){console.error(c)}this._status=fi.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&&r===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function AA(o){this.emit("connecting",o)}function IA(o){this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function RA(o){const n=["nict","ict","nist","ist"];for(const r of n)for(const a in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],a)&&this._transactions[r][a].onTransportError();this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_NOT_READY,this._error=fi.NETWORK_ERROR)}function $A(o){const n=o.transport;let r=o.message;const a=r;if(r=wA.parseMessage(r,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(r,a),!!r&&!(this._status===fi.STATUS_USER_CLOSED&&r instanceof Za.IncomingRequest)&&JC(r,this,n)){if(r instanceof Za.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Za.IncomingResponse){let c;switch(r.method){case bt.INVITE:c=this._transactions.ict[r.via_branch],c&&c.receiveResponse(r);break;case bt.ACK:break;default:c=this._transactions.nict[r.via_branch],c&&c.receiveResponse(r);break}}}}const xA=["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","putOnHoldTimestamp"],OA=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function yf(o){const n={};return xA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n.localHold=o._localHold,n}function vf(o){const n={};return OA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n}async function Dd(o,n,r){const a=o.createMediaStreamSource(n),c=o.createMediaStreamDestination(),e=o.createGain();return a.connect(e),e.connect(c),e.gain.value=r,c.stream}function kA(o,n,r,a){if(Tf())return;const c=document.createElement("audio");c.id=n._id,c.className="audioTag",c.srcObject=o,c.setSinkId(r),c.volume=a,c.play(),n.audioTag=c}function DA(o){if(o&&typeof o.log=="function"&&typeof o.warn=="function"&&typeof o.error=="function")return!0}function Tf(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const NA=mn,MA=Hr(),Jn=new NA("WebSocketInterface");var UA=class{constructor(o){Jn.debug('new() [url:"%s"]',o),this._url=o,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=MA.parse(o,"absoluteURI");if(n===-1)throw Jn.warn(`invalid WebSocket URI: ${o}`),new TypeError(`Invalid argument: ${o}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Jn.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${o}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(o){this._via_transport=o.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Jn.debug("connect()"),this.isConnected()){Jn.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Jn.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Jn.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(o){this._onError(o)}}disconnect(){Jn.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(o){return Jn.debug("send()"),this.isConnected()?(this._ws.send(o),!0):(Jn.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(){Jn.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:o,code:n,reason:r}){Jn.debug(`WebSocket ${this._url} closed`),o===!1&&Jn.debug("WebSocket abrupt disconnection"),this.ondisconnect(!o,n,r)}_onMessage({data:o}){Jn.debug("received WebSocket message"),this.ondata(o)}_onError(o){Jn.warn(`WebSocket ${this._url} error: `,o)}};const Nd=Pl,PA=bt,LA=Ls,qA=$n(),HA=ff,zA=Ms(),FA=ed(),BA=Hr(),VA=UA;Wa("JsSIP")("version %s",Nd.version);var jA={C:PA,Exceptions:LA,Utils:qA,UA:HA,URI:zA,NameAddrHeader:FA,WebSocketInterface:VA,Grammar:BA,debug:Wa,get name(){return Nd.title},get version(){return Nd.version}};const GA=Qt(jA);function Md(o){return o<10?`0${o}`:`${o}`}function WA(o){let n=o.hours||0,r=o.minutes||0,a=o.seconds||0;a++,a===60&&(a=0,r++,r===60&&(r=0,n++));const c=`${Md(n)}:${Md(r)}:${Md(a)}`;return{seconds:a,minutes:r,hours:n,formatted:c}}function KA(o){let n=0;for(let r=0;r<o.length;r++)n+=o[r]*o[r];return Math.sqrt(n/o.length)}async function YA(o,n,r=150){const a=n.createMediaStreamSource(o),c=n.createDelay();c.delayTime.value=r/1e3;const e=n.createGain();e.gain.value=0;const _=n.createMediaStreamDestination();return a.connect(c).connect(e).connect(_),{stream:_.stream,setSpeaking:g=>{e.gain.value=g?1:0}}}var Mn={};Mn.forEach=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)if(c in o){const e=Promise.resolve(o[c]).then(_=>n.call(r||globalThis,_,c,o));a.push(e)}await Promise.all(a)},Mn.forEachSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)a in o&&await n.call(r||globalThis,await o[a],a,o)},Mn.map=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=Promise.resolve(o[c]).then(e=>n.call(r||globalThis,e,c,o)));return Promise.all(a)},Mn.mapSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=await n.call(r||globalThis,await o[c],c,o));return a},Mn.find=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a();let e=1;for(let _=0;_<o.length;_++){const g=d=>{d?a(o[_]):e===o.length&&a(),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.findSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return o[a]},Mn.findIndex=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(-1);let e=1;for(let _=0;_<o.length;_++){const g=d=>{d?a(_):e===o.length&&a(-1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.findIndexSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return a},Mn.some=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!1);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const g=d=>{d?a(!0):e===o.length&&a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.someSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&await n.call(r||globalThis,await o[a],a,o))return!0;return!1},Mn.every=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!0);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const g=d=>{d?e===o.length&&a(!0):a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.everySeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&!await n.call(r||globalThis,await o[a],a,o))return!1;return!0},Mn.filter=(o,n,r)=>new Promise(async(a,c)=>{const e=[];for(let g=0;g<o.length;g++)g in o&&(e[g]=Promise.resolve(o[g]).then(d=>n.call(r||globalThis,d,g,o)).catch(c));const _=[];for(let g=0;g<e.length;g++)await e[g]&&_.push(await o[g]);a(_)}),Mn.filterSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&await n.call(r||globalThis,await o[c],c,o)&&a.push(await o[c]);return a},Mn.reduce=async(o,n,r)=>{if(o.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let a,c;for(r!==void 0?(c=r,a=0):(c=o[0],a=1),a;a<o.length;a++)a in o&&(c=await n(await c,await o[a],a,o));return c};var bf={};(function(o){const n=Mn;Object.keys(n).forEach(r=>{const a=r.charAt(0).toUpperCase()+r.slice(1);o[`async${a}`]=async function(...c){return n[r](this,...c)}})})(bf);var XA=Object.assign(Mn,{instanceMethods:bf});const Br={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},JA={TRYING:100,RINGING:180,SESSION_PROGRESS:183,OK:200,MOVED_TEMPORARILY:302,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,REQUEST_TIMEOUT:408,BUSY_HERE:486,REQUEST_TERMINATED:487,INTERNAL_SERVER_ERROR:500,SERVICE_UNAVAILABLE:503,BUSY_EVERYWHERE:600,DECLINE:603};var QA={exports:{}};(function(o){var n=function(r){var a=Object.prototype,c=a.hasOwnProperty,e=Object.defineProperty||function(Ae,fe,se){Ae[fe]=se.value},_,g=typeof Symbol=="function"?Symbol:{},d=g.iterator||"@@iterator",A=g.asyncIterator||"@@asyncIterator",S=g.toStringTag||"@@toStringTag";function R(Ae,fe,se){return Object.defineProperty(Ae,fe,{value:se,enumerable:!0,configurable:!0,writable:!0}),Ae[fe]}try{R({},"")}catch{R=function(Ae,fe,se){return Ae[fe]=se}}function N(Ae,fe,se,st){var We=fe&&fe.prototype instanceof De?fe:De,ht=Object.create(We.prototype),It=new Se(st||[]);return e(ht,"_invoke",{value:ue(Ae,se,It)}),ht}r.wrap=N;function H(Ae,fe,se){try{return{type:"normal",arg:Ae.call(fe,se)}}catch(st){return{type:"throw",arg:st}}}var W="suspendedStart",G="suspendedYield",K="executing",ae="completed",ee={};function De(){}function X(){}function re(){}var be={};R(be,d,function(){return this});var Ne=Object.getPrototypeOf,Q=Ne&&Ne(Ne($e([])));Q&&Q!==a&&c.call(Q,d)&&(be=Q);var ce=re.prototype=De.prototype=Object.create(be);X.prototype=re,e(ce,"constructor",{value:re,configurable:!0}),e(re,"constructor",{value:X,configurable:!0}),X.displayName=R(re,S,"GeneratorFunction");function me(Ae){["next","throw","return"].forEach(function(fe){R(Ae,fe,function(se){return this._invoke(fe,se)})})}r.isGeneratorFunction=function(Ae){var fe=typeof Ae=="function"&&Ae.constructor;return fe?fe===X||(fe.displayName||fe.name)==="GeneratorFunction":!1},r.mark=function(Ae){return Object.setPrototypeOf?Object.setPrototypeOf(Ae,re):(Ae.__proto__=re,R(Ae,S,"GeneratorFunction")),Ae.prototype=Object.create(ce),Ae},r.awrap=function(Ae){return{__await:Ae}};function _e(Ae,fe){function se(ht,It,qe,Ue){var wt=H(Ae[ht],Ae,It);if(wt.type==="throw")Ue(wt.arg);else{var Yt=wt.arg,Xe=Yt.value;return Xe&&typeof Xe=="object"&&c.call(Xe,"__await")?fe.resolve(Xe.__await).then(function(Je){se("next",Je,qe,Ue)},function(Je){se("throw",Je,qe,Ue)}):fe.resolve(Xe).then(function(Je){Yt.value=Je,qe(Yt)},function(Je){return se("throw",Je,qe,Ue)})}}var st;function We(ht,It){function qe(){return new fe(function(Ue,wt){se(ht,It,Ue,wt)})}return st=st?st.then(qe,qe):qe()}e(this,"_invoke",{value:We})}me(_e.prototype),R(_e.prototype,A,function(){return this}),r.AsyncIterator=_e,r.async=function(Ae,fe,se,st,We){We===void 0&&(We=Promise);var ht=new _e(N(Ae,fe,se,st),We);return r.isGeneratorFunction(fe)?ht:ht.next().then(function(It){return It.done?It.value:ht.next()})};function ue(Ae,fe,se){var st=W;return function(We,ht){if(st===K)throw new Error("Generator is already running");if(st===ae){if(We==="throw")throw ht;return zt()}for(se.method=We,se.arg=ht;;){var It=se.delegate;if(It){var qe=ye(It,se);if(qe){if(qe===ee)continue;return qe}}if(se.method==="next")se.sent=se._sent=se.arg;else if(se.method==="throw"){if(st===W)throw st=ae,se.arg;se.dispatchException(se.arg)}else se.method==="return"&&se.abrupt("return",se.arg);st=K;var Ue=H(Ae,fe,se);if(Ue.type==="normal"){if(st=se.done?ae:G,Ue.arg===ee)continue;return{value:Ue.arg,done:se.done}}else Ue.type==="throw"&&(st=ae,se.method="throw",se.arg=Ue.arg)}}}function ye(Ae,fe){var se=fe.method,st=Ae.iterator[se];if(st===_)return fe.delegate=null,se==="throw"&&Ae.iterator.return&&(fe.method="return",fe.arg=_,ye(Ae,fe),fe.method==="throw")||se!=="return"&&(fe.method="throw",fe.arg=new TypeError("The iterator does not provide a '"+se+"' method")),ee;var We=H(st,Ae.iterator,fe.arg);if(We.type==="throw")return fe.method="throw",fe.arg=We.arg,fe.delegate=null,ee;var ht=We.arg;if(!ht)return fe.method="throw",fe.arg=new TypeError("iterator result is not an object"),fe.delegate=null,ee;if(ht.done)fe[Ae.resultName]=ht.value,fe.next=Ae.nextLoc,fe.method!=="return"&&(fe.method="next",fe.arg=_);else return ht;return fe.delegate=null,ee}me(ce),R(ce,S,"Generator"),R(ce,d,function(){return this}),R(ce,"toString",function(){return"[object Generator]"});function Re(Ae){var fe={tryLoc:Ae[0]};1 in Ae&&(fe.catchLoc=Ae[1]),2 in Ae&&(fe.finallyLoc=Ae[2],fe.afterLoc=Ae[3]),this.tryEntries.push(fe)}function J(Ae){var fe=Ae.completion||{};fe.type="normal",delete fe.arg,Ae.completion=fe}function Se(Ae){this.tryEntries=[{tryLoc:"root"}],Ae.forEach(Re,this),this.reset(!0)}r.keys=function(Ae){var fe=Object(Ae),se=[];for(var st in fe)se.push(st);return se.reverse(),function We(){for(;se.length;){var ht=se.pop();if(ht in fe)return We.value=ht,We.done=!1,We}return We.done=!0,We}};function $e(Ae){if(Ae){var fe=Ae[d];if(fe)return fe.call(Ae);if(typeof Ae.next=="function")return Ae;if(!isNaN(Ae.length)){var se=-1,st=function We(){for(;++se<Ae.length;)if(c.call(Ae,se))return We.value=Ae[se],We.done=!1,We;return We.value=_,We.done=!0,We};return st.next=st}}return{next:zt}}r.values=$e;function zt(){return{value:_,done:!0}}return Se.prototype={constructor:Se,reset:function(Ae){if(this.prev=0,this.next=0,this.sent=this._sent=_,this.done=!1,this.delegate=null,this.method="next",this.arg=_,this.tryEntries.forEach(J),!Ae)for(var fe in this)fe.charAt(0)==="t"&&c.call(this,fe)&&!isNaN(+fe.slice(1))&&(this[fe]=_)},stop:function(){this.done=!0;var Ae=this.tryEntries[0],fe=Ae.completion;if(fe.type==="throw")throw fe.arg;return this.rval},dispatchException:function(Ae){if(this.done)throw Ae;var fe=this;function se(Ue,wt){return ht.type="throw",ht.arg=Ae,fe.next=Ue,wt&&(fe.method="next",fe.arg=_),!!wt}for(var st=this.tryEntries.length-1;st>=0;--st){var We=this.tryEntries[st],ht=We.completion;if(We.tryLoc==="root")return se("end");if(We.tryLoc<=this.prev){var It=c.call(We,"catchLoc"),qe=c.call(We,"finallyLoc");if(It&&qe){if(this.prev<We.catchLoc)return se(We.catchLoc,!0);if(this.prev<We.finallyLoc)return se(We.finallyLoc)}else if(It){if(this.prev<We.catchLoc)return se(We.catchLoc,!0)}else if(qe){if(this.prev<We.finallyLoc)return se(We.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Ae,fe){for(var se=this.tryEntries.length-1;se>=0;--se){var st=this.tryEntries[se];if(st.tryLoc<=this.prev&&c.call(st,"finallyLoc")&&this.prev<st.finallyLoc){var We=st;break}}We&&(Ae==="break"||Ae==="continue")&&We.tryLoc<=fe&&fe<=We.finallyLoc&&(We=null);var ht=We?We.completion:{};return ht.type=Ae,ht.arg=fe,We?(this.method="next",this.next=We.finallyLoc,ee):this.complete(ht)},complete:function(Ae,fe){if(Ae.type==="throw")throw Ae.arg;return Ae.type==="break"||Ae.type==="continue"?this.next=Ae.arg:Ae.type==="return"?(this.rval=this.arg=Ae.arg,this.method="return",this.next="end"):Ae.type==="normal"&&fe&&(this.next=fe),ee},finish:function(Ae){for(var fe=this.tryEntries.length-1;fe>=0;--fe){var se=this.tryEntries[fe];if(se.finallyLoc===Ae)return this.complete(se.completion,se.afterLoc),J(se),ee}},catch:function(Ae){for(var fe=this.tryEntries.length-1;fe>=0;--fe){var se=this.tryEntries[fe];if(se.tryLoc===Ae){var st=se.completion;if(st.type==="throw"){var We=st.arg;J(se)}return We}}throw new Error("illegal catch attempt")},delegateYield:function(Ae,fe,se){return this.delegate={iterator:$e(Ae),resultName:fe,nextLoc:se},this.method==="next"&&(this.arg=_),ee}},r}(o.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(QA);var wf={exports:{}};(function(o){(function(n,r){o.exports?o.exports=r():n.log=r()})(Sb,function(){var n=function(){},r="undefined",a=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),c=["trace","debug","info","warn","error"];function e(G,K){var ae=G[K];if(typeof ae.bind=="function")return ae.bind(G);try{return Function.prototype.bind.call(ae,G)}catch{return function(){return Function.prototype.apply.apply(ae,[G,arguments])}}}function _(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function g(G){return G==="debug"&&(G="log"),typeof console===r?!1:G==="trace"&&a?_:console[G]!==void 0?e(console,G):console.log!==void 0?e(console,"log"):n}function d(G,K){for(var ae=0;ae<c.length;ae++){var ee=c[ae];this[ee]=ae<G?n:this.methodFactory(ee,G,K)}this.log=this.debug}function A(G,K,ae){return function(){typeof console!==r&&(d.call(this,K,ae),this[G].apply(this,arguments))}}function S(G,K,ae){return g(G)||A.apply(this,arguments)}function R(G,K,ae){var ee=this,De;K=K??"WARN";var X="loglevel";typeof G=="string"?X+=":"+G:typeof G=="symbol"&&(X=void 0);function re(ce){var me=(c[ce]||"silent").toUpperCase();if(!(typeof window===r||!X)){try{window.localStorage[X]=me;return}catch{}try{window.document.cookie=encodeURIComponent(X)+"="+me+";"}catch{}}}function be(){var ce;if(!(typeof window===r||!X)){try{ce=window.localStorage[X]}catch{}if(typeof ce===r)try{var me=window.document.cookie,_e=me.indexOf(encodeURIComponent(X)+"=");_e!==-1&&(ce=/^([^;]+)/.exec(me.slice(_e))[1])}catch{}return ee.levels[ce]===void 0&&(ce=void 0),ce}}function Ne(){if(!(typeof window===r||!X)){try{window.localStorage.removeItem(X);return}catch{}try{window.document.cookie=encodeURIComponent(X)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}ee.name=G,ee.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},ee.methodFactory=ae||S,ee.getLevel=function(){return De},ee.setLevel=function(ce,me){if(typeof ce=="string"&&ee.levels[ce.toUpperCase()]!==void 0&&(ce=ee.levels[ce.toUpperCase()]),typeof ce=="number"&&ce>=0&&ce<=ee.levels.SILENT){if(De=ce,me!==!1&&re(ce),d.call(ee,ce,G),typeof console===r&&ce<ee.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+ce},ee.setDefaultLevel=function(ce){K=ce,be()||ee.setLevel(ce,!1)},ee.resetLevel=function(){ee.setLevel(K,!1),Ne()},ee.enableAll=function(ce){ee.setLevel(ee.levels.TRACE,ce)},ee.disableAll=function(ce){ee.setLevel(ee.levels.SILENT,ce)};var Q=be();Q==null&&(Q=K),ee.setLevel(Q,!1)}var N=new R,H={};N.getLogger=function(G){if(typeof G!="symbol"&&typeof G!="string"||G==="")throw new TypeError("You must supply a name when creating a logger.");var K=H[G];return K||(K=H[G]=new R(G,N.getLevel(),N.methodFactory)),K};var W=typeof window!==r?window.log:void 0;return N.noConflict=function(){return typeof window!==r&&window.log===N&&(window.log=W),N},N.getLoggers=function(){return H},N.default=N,N})})(wf);var Vn=wf.exports;const Hs=()=>`${new Date().toISOString()} | metrics`,zs=(o,n,r)=>`${o} | ${n} | ${r}`;Vn.setDefaultLevel(Vn.levels.TRACE);const ZA=o=>{Vn.info(zs(Hs(),"log ",`set log level to ${o?"verbose":"info"}`)),Vn.setLevel(o?Vn.levels.TRACE:Vn.levels.INFO)},e1=o=>{const n=[...Object.keys(Vn.levels)];n.includes(o)?(Vn.info(zs(Hs(),"log ",`update log level to ${o.toLowerCase()}`)),Vn.setLevel(o)):Vn.warn(zs(Hs(),"log ","Incorrect log level please choose one of "),n)},Rt=(o,n,r)=>{r?Vn.debug(zs(Hs(),o,n),r):Vn.debug(zs(Hs(),o,n))},Ud=(o,n)=>{Vn.info(zs(Hs(),o,n))},wa=(o,n)=>{Vn.info(zs(Hs(),o,n))},Fu=(o,n)=>{Vn.warn(zs(Hs(),o,n))},so=(o,n)=>{Vn.error(zs(Hs(),o,n))};function t1(o){return Math.floor(Math.random()*o).toString()}function Sf(o,n){let r=n;return o.forEach(a=>{r=r.replace(a,"")}),r}function n1(o,n){let r="";for(let a=0;a<n;a+=1)r+=o[t1(o.length)];return r}function r1({length:o=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:a=[],excludeSymbols:c=[]}={}){let e="abcdefghijklmnopqrstuvwxyz",_="0123456789",g=[],d=[],A=[];return n&&(c.length&&(e=Sf(c,e)),d=e.split("")),r&&(c.length&&(_=Sf(c,_)),A=_.split("")),g=[...d,...A,...a],n1(g,o)}var s1=r1;const fl=Qt(s1),i1=()=>"WebRTCMetrics",a1=()=>"5.0.3",Ht={INBOUND:"inbound",OUTBOUND:"outbound"},Fs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ml={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},o1=()=>({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:[]}),Ef={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:Ht.INBOUND},Cf={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:Ht.OUTBOUND},Af={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:Ht.INBOUND},If={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:Ht.OUTBOUND},l1=o=>{const n={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(o){const r={...o,audio:{},video:{},data:{...o.data},network:{...o.network},experimental:{...o.experimental}};return Object.keys(o.audio).forEach(a=>{r.audio[a]={...o.audio[a]}}),Object.keys(o.video).forEach(a=>{r.video[a]={...o.video[a]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},u1={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${fl()}`,cid:`c-${fl()}`,uid:`u-${fl()}`,record:!1,ticket:!0},Vr={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"},ge={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"},ie={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},gl={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Pd={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Me={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Ld="config ",c1=(o,n={},r)=>{const a={...r,...n};return n.pname||Fu(Ld,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||Fu(Ld,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||Fu(Ld,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),a.pc=o,a},d1=(o={})=>{const n={...u1,...o};return n.name=i1(),n.version=a1(),n},yl=(o,n,r,a=!1,c)=>{let e=o.map(_=>{if(!r)return _[n];if(!c)return _[n][r];const g=_[n][c];return g?g[r]:null});return e=e.filter(_=>a?Number.isFinite(_)&&_>0:Number.isFinite(_)),e.length===0?[]:e},mi=o=>o.reduce((n,r)=>n+r,0)/o.length,h1=()=>`probe-${fl()}`,p1=()=>`coltr-${fl()}`,Rf=o=>new Promise(n=>setTimeout(n,o)),qd=(o,n,r)=>{n?o.call(n,r):o(r)},Zt=(o,n,r,a)=>{const c=yl(o,n,r,!0,a);if(c.length===0)return null;const e=c.reduce((_,g)=>_+g,0)/c.length;return e===0?null:c.map(_=>Math.abs(e-_)).reduce((_,g)=>_+g,0)/c.length*100/e},nn=(o,n,r,a=!1,c)=>{const e=yl(o,n,r,a,c);return e.length===0?null:e.reduce((_,g)=>_+g,0)/e.length},Sa=(o,n,r)=>yl(o,n,r).reduce((a,c)=>a+c,0),en=(o,n,r,a)=>{const c=yl(o,n,r,!0,a);return c.length===0?null:Math.min(...c)},tn=(o,n,r,a)=>{const c=yl(o,n,r,!1,a);return c.length===0?null:Math.max(...c)},Un=(o,n,r,a)=>{const c=o.slice().pop();if(!c)return null;if(!r)return c[n];if(!a)return c[n][r];const e=c[n][a];return e?e[r]:null},_1=o=>o.slice().pop(),wn=(o,n,r)=>{if(!n)return null;const a={};let c=n[ie.AUDIO][o];c||(c=r===Ht.INBOUND?{...Ef}:{...Cf}),a[ie.AUDIO]=c;let e=n[ie.VIDEO][o];return e||(e=r===Ht.INBOUND?{...Af}:{...If}),a[ie.VIDEO]=e,a},vl="exporter ",f1="2.0",$f=(o,n,r)=>{if(!o||o.length===0)return 0;const a=o[o.length-1];if(!a)return 0;const c=a[n][r];if(c){const e=c.total_rtt_ms_out,_=c.total_rtt_measure_out;return!_||!e?nn(o,n,"delta_rtt_ms_out",!1,r):Number(e/_)}return null},m1=(o,n)=>{if(!o||o.length===0)return 0;const r=o[o.length-1];if(!r)return 0;const a=r[n].total_rtt_connectivity_ms,c=r[n].total_rtt_connectivity_measure;return!c||!a?nn(o,n,"delta_rtt_connectivity_ms"):Number(a/c)},g1=o=>Un(o,"network","local_candidate_type")!=="relay"?`direct/${Un(o,"network","local_candidate_protocol")}`:`turn/${Un(o,"network","local_candidate_relay_protocol")}`,y1=o=>{const n=Un(o,"network","remote_candidate_type"),r=Un(o,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class v1{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ud(vl,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){Ud(vl,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Rt(vl,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){Ud(vl,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Rt(vl,"ticket() - generate ticket");const n=Un(this._reports,"audio","total_packets_lost_in"),r=Un(this._reports,"audio","total_packets_in"),a=Un(this._reports,"video","total_packets_lost_in"),c=Un(this._reports,"video","total_packets_in"),e={},_=_1(this._reports);return _&&(Object.keys(_[ie.AUDIO]).forEach(g=>{const d=_[ie.AUDIO][g];if(e[d.ssrc]={type:ie.AUDIO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_kbs_in",g),max:tn(this._reports,ie.AUDIO,"delta_kbs_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_KBytes_in",g),max:tn(this._reports,ie.AUDIO,"delta_KBytes_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_in",!1,g),min:en(this._reports,ie.AUDIO,"mos_emodel_in",g),max:tn(this._reports,ie.AUDIO,"mos_emodel_in",g),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_in",g)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_in",!1,g),min:en(this._reports,ie.AUDIO,"mos_in",g),max:tn(this._reports,ie.AUDIO,"mos_in",g),volatility:Zt(this._reports,ie.AUDIO,"mos_in",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_in",g),W=Un(this._reports,ie.AUDIO,"total_packets_in",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].mos=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G}else{const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_kbs_out",g),max:tn(this._reports,ie.AUDIO,"delta_kbs_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_KBytes_out",g),max:tn(this._reports,ie.AUDIO,"delta_KBytes_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},N={avg:$f(this._reports,ie.AUDIO,g),min:en(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),max:tn(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_out",g),W=Un(this._reports,ie.AUDIO,"total_packets_out",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},K={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_out",!1,g),min:en(this._reports,ie.AUDIO,"mos_emodel_out",g),max:tn(this._reports,ie.AUDIO,"mos_emodel_out",g),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_out",g)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_out",!1,g),min:en(this._reports,ie.AUDIO,"mos_out",g),max:tn(this._reports,ie.AUDIO,"mos_out",g),volatility:Zt(this._reports,ie.AUDIO,"mos_out",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[g].jitter=A,e[g].rtt=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G,e[g].mos=K}}),Object.keys(_[ie.VIDEO]).forEach(g=>{const d=_[ie.VIDEO][g];if(e[g]={type:ie.VIDEO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_kbs_in",g),max:tn(this._reports,ie.VIDEO,"delta_kbs_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_KBytes_in",g),max:tn(this._reports,ie.VIDEO,"delta_KBytes_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N=Un(this._reports,ie.VIDEO,"total_packets_lost_in",g),H=Un(this._reports,ie.VIDEO,"total_packets_in",g),W={lost:N,avg:Math.round((N/(N+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].traffic=R,e[g].bitrate=S,e[g].loss=W}else{const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_kbs_out",g),max:tn(this._reports,ie.VIDEO,"delta_kbs_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_KBytes_out",g),max:tn(this._reports,ie.VIDEO,"delta_KBytes_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={avg:$f(this._reports,ie.VIDEO,g),min:en(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),max:tn(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.VIDEO,"total_packets_lost_out",g),W=Un(this._reports,ie.VIDEO,"total_packets_out",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].rtt=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G}})),{version:f1,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:e,data:{rtt:{avg:m1(this._reports,"data"),min:en(this._reports,"data","delta_rtt_connectivity_ms"),max:tn(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Zt(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+r)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+c)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:nn(this._reports,"data","delta_kbs_in"),min:en(this._reports,"data","delta_kbs_in"),max:tn(this._reports,"data","delta_kbs_in"),volatility:Zt(this._reports,"data","delta_kbs_in")},out:{avg:nn(this._reports,"data","delta_kbs_out"),min:en(this._reports,"data","delta_kbs_out"),max:tn(this._reports,"data","delta_kbs_out"),volatility:Zt(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:nn(this._reports,"data","delta_KBytes_in"),min:en(this._reports,"data","delta_KBytes_in"),max:tn(this._reports,"data","delta_KBytes_in"),volatility:Zt(this._reports,"data","delta_KBytes_in")},out:{avg:nn(this._reports,"data","delta_KBytes_out"),min:en(this._reports,"data","delta_KBytes_out"),max:tn(this._reports,"data","delta_KBytes_out"),volatility:Zt(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:g1(this._reports),remoteConnection:y1(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const gi="extractor ",xf=(o,n,r,a)=>{let c=!1;const e=a[n].total_rtt_ms_out,_=a[n].total_rtt_measure_out,g=r?r[n].total_rtt_ms_out:0,d=r?r[n].total_rtt_measure_out:0,A={rtt:null,totalRTT:e,totalRTTMeasurements:_};if(o[ge.TIMESTAMP]===a[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ge.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(c=!0,Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===_))return A;const S=1e3*Number(o[ge.ROUND_TRIP_TIME]);let R=e+S,N=_+1;return c&&(R=1e3*Number(o[ge.TOTAL_ROUND_TRIP_TIME])-g,N=Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:S,totalRTT:R,totalRTTMeasurements:N}},T1=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[n].total_rtt_connectivity_ms,totalRTTMeasurements:a[n].total_rtt_connectivity_measure};const c=1e3*Number(o[ge.CURRENT_ROUND_TRIP_TIME]);let e=a[n].total_rtt_connectivity_ms+c,_=a[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ROUND_TRIP_TIME)&&(e=1e3*Number(o[ge.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(o,ge.RESPONSES_RECEIVED)&&(_=Number(o[ge.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:c,totalRTT:e,totalRTTMeasurements:_}},Bu=(o,n,r)=>o[ge.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ge.JITTER)?null:1e3*(Number(o[ge.JITTER])||0),b1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(o,ge.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[ie.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[ie.VIDEO].total_frames_decoded_in,total_decode_time:n[ie.VIDEO].total_time_decoded_in};const r=o[ge.FRAMES_DECODED],a=o[ge.TOTAL_DECODE_TIME],c=a-n[ie.VIDEO].total_time_decoded_in,e=r-n[ie.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:e>0?c*1e3/e:0,frames_decoded:r,total_decode_time:a}},w1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[ie.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[ie.VIDEO].total_frames_encoded_out,total_encode_time:n[ie.VIDEO].total_time_encoded_out};const r=o[ge.FRAMES_ENCODED],a=o[ge.TOTAL_ENCODE_TIME],c=a-n[ie.VIDEO].total_time_encoded_out,e=r-n[ie.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:e>0&&c?c*1e3/e:0,frames_encoded:r,total_encode_time:a}},Of=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(o,ge.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const c=Number(o[ge.PACKETS_SENT])||0-(a?a[n].total_packets_out:0),e=c-r[n].total_packets_out,_=Number(o[ge.BYTES_SENT])/1024-(a?a[n].total_KBytes_out:0),g=_-r[n].total_KBytes_out,d=o[ge.TIMESTAMP]||Date.now(),A=a?a.timestamp:null;let S=r.timestamp;!S&&A&&(S=A);const R=S?d-S:0,N=R>0?g*.008*1024/R*1e3:0;return{packetsSent:c,deltaPacketsSent:e,KBytesSent:_,deltaKBytesSent:g,kbsSent:N}},kf=(o,n,r,a)=>{let c=r[n].total_packets_lost_out,e=0,_=0;return Object.prototype.hasOwnProperty.call(o,ge.PACKETS_LOST)&&(c=Number(o[ge.PACKETS_LOST])||0-(a?a[n].total_packets_lost_out:0),e=c-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(o,ge.FRACTION_LOST)&&(_=Number(100*o[ge.FRACTION_LOST])),{packetsLost:c,deltaPacketsLost:e,fractionLost:_}},Df=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(o,ge.BYTES_RECEIVED))return{percent_packets_lost:r[n].percent_packets_lost_in,packetsReceived:r[n].total_packets_in,packetsLost:r[n].total_packets_lost_in,bytesReceived:r[n].total_KBytes_in};const c=Number(o[ge.PACKETS_RECEIVED])||0-(a?a[n].total_packets_in:0),e=Number(o[ge.PACKETS_LOST])||0-(a?a[n].total_packets_lost_in:0),_=e-r[n].total_packets_lost_in,g=c-r[n].total_packets_in,d=c!==r[n].total_packets_in?_*100/(_+g):0,A=Number(o[ge.BYTES_RECEIVED])/1024-(a?a[n].total_KBytes_in:0),S=A-r[n].total_KBytes_in,R=o[ge.TIMESTAMP]||Date.now(),N=a?a.timestamp:null;let H=r.timestamp;!H&&N&&(H=N);const W=H?R-H:0,G=W>0?S*.008*1024/W*1e3:0;return{percentPacketsLost:d,packetsReceived:c,deltaPacketsReceived:g,packetsLost:e,deltaPacketsLost:_,KBytesReceived:A,deltaKBytesReceived:S,kbsReceived:G}},S1=o=>o[ge.CANDIDATE_TYPE]!=="relay"?"":o[ge.RELAY_PROTOCOL]||"",E1=o=>{if(!Object.prototype.hasOwnProperty.call(o,ge.NETWORK_TYPE))return gl.WIFI;switch(o[ge.NETWORK_TYPE]){case Pd.ETHERNET:return gl.ETHERNET;case Pd.CELLULAR_4G:return gl.CELLULAR_4G;case Pd.WIFI:return gl.WIFI;default:return gl.CELLULAR}},Nf=o=>!Object.prototype.hasOwnProperty.call(o,ge.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(o,ge.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:o[ge.FRAME_WIDTH]||null,height:o[ge.FRAME_HEIGHT]||null,framerate:o[ge.FRAMES_PER_SECOND]},C1=o=>{const n=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_REASON)?o[ge.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_RESOLUTION_CHANGES)?o[ge.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_DURATIONS)?o[ge.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(c=>{a[c]>1e3&&(a[c]=Number(a[c]/1e3))}),{reason:n,durations:a,resolutionChanges:r}},A1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PLI)||!Object.prototype.hasOwnProperty.call(o,ge.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(o[ge.PLI]||0)-(r?r[ie.VIDEO].total_pli_sent_in:0),c=(o[ge.NACK]||0)-(r?r[ie.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ie.VIDEO].total_pli_sent_in,deltaNackCount:c-n[ie.VIDEO].total_nack_sent_in}},I1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PLI)||!Object.prototype.hasOwnProperty.call(o,ge.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(o[ge.PLI]||0)-(r?r[ie.VIDEO].total_pli_received_out:0),c=(o[ge.NACK]||0)-(r?r[ie.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ie.VIDEO].total_pli_received_out,deltaNackCount:c-n[ie.VIDEO].total_nack_received_out}},R1=o=>({channels:o[ge.CHANNELS]||null,clock_rate:o[ge.CLOCK_RATE]||null,mime_type:o[ge.MIME_TYPE]||null,sdp_fmtp_line:o[ge.SDP_FMTP_LINE]||null}),$1=o=>({clock_rate:o[ge.CLOCK_RATE]||null,mime_type:o[ge.MIME_TYPE]||null}),x1=(o,n,r)=>{const a=(o[ge.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),c=(o[ge.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),e=o[ge.TIMESTAMP]||Date.now(),_=a-n.data.total_KBytes_in,g=c-n.data.total_KBytes_out,d=r?r.timestamp:null;let A=n.timestamp;!A&&d&&(A=d);const S=A?e-A:0,R=S>0?_*.008*1024/S*1e3:0,N=S>0?g*.008*1024/S*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:c,delta_KBytes_received:_,delta_KBytes_sent:g,kbs_speed_received:R,kbs_speed_sent:N}},O1=o=>{const n=o[ge.AVAILABLE_INCOMING_BITRATE]/1024||0,r=o[ge.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},k1=(o,n,r,a)=>{if(!o)return[];switch(o[ge.TYPE]){case Vr.CANDIDATE_PAIR:let c=!1;if(o[ge.NOMINATED]&&o[ge.STATE]===ie.SUCCEEDED&&(c=!0,Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o),ge.SELECTED in o&&!o[ge.SELECTED]&&(c=!1)),c){const _=o[ge.LOCAL_CANDIDATE_ID],g=o[ge.REMOTE_CANDIDATE_ID],d=x1(o,n,a),A=O1(o),S=T1(o,"data",a,n);return[{type:Me.NETWORK,value:{local_candidate_id:_}},{type:Me.NETWORK,value:{remote_candidate_id:g}},{type:Me.DATA,value:{total_KBytes_in:d.total_KBytes_received}},{type:Me.DATA,value:{total_KBytes_out:d.total_KBytes_sent}},{type:Me.DATA,value:{delta_KBytes_in:d.delta_KBytes_received}},{type:Me.DATA,value:{delta_KBytes_out:d.delta_KBytes_sent}},{type:Me.DATA,value:{delta_kbs_in:d.kbs_speed_received}},{type:Me.DATA,value:{delta_kbs_out:d.kbs_speed_sent}},{type:Me.DATA,value:{delta_kbs_bandwidth_in:A.kbs_incoming_bandwidth}},{type:Me.DATA,value:{delta_kbs_bandwidth_out:A.kbs_outgoing_bandwidth}},{type:Me.DATA,value:{delta_rtt_connectivity_ms:S.rtt}},{type:Me.DATA,value:{total_rtt_connectivity_ms:S.totalRTT}},{type:Me.DATA,value:{total_rtt_connectivity_measure:S.totalRTTMeasurements}}]}break;case Vr.LOCAL_CANDIDATE:if(o[ge.ID]===n.network.local_candidate_id)return[{type:Me.NETWORK,value:{infrastructure:E1(o)}},{type:Me.NETWORK,value:{local_candidate_type:o[ge.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{local_candidate_protocol:o[ge.PROTOCOL]||""}},{type:Me.NETWORK,value:{local_candidate_relay_protocol:S1(o)}}];break;case Vr.REMOTE_CANDIDATE:if(o[ge.ID]===n.network.remote_candidate_id)return[{type:Me.NETWORK,value:{remote_candidate_type:o[ge.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{remote_candidate_protocol:o[ge.PROTOCOL]||""}}];break;case Vr.INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const _=o[ge.SSRC],g=wn(_,n,Ht.INBOUND);g&&(g.timestamp=n.timestamp);const d=wn(_,a,Ht.INBOUND);if(d&&(d.timestamp=a.timestamp),o[ge.MEDIA_TYPE]===ie.AUDIO){const A=Df(o,ie.AUDIO,g,d),S=Bu(o,ie.AUDIO,g),R=o[ge.CODEC_ID]||"";return[{ssrc:_,type:Me.AUDIO,value:{codec_id_in:R}},{ssrc:_,type:Me.AUDIO,value:{total_packets_in:A.packetsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_in:A.deltaPacketsReceived}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_in:A.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_in:A.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_in:A.percentPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_in:A.KBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_in:A.deltaKBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_in:A.kbsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_in:S}}]}if(o[ge.MEDIA_TYPE]===ie.VIDEO){const A=b1(o,g),S=Df(o,ie.VIDEO,g,d),R=Bu(o,ie.VIDEO,g),N=o[ge.DECODER_IMPLEMENTATION]||null,H=o[ge.CODEC_ID]||null,W=Nf(o),G=A1(o,g,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_in:H}},{ssrc:_,type:Me.VIDEO,value:{total_packets_in:S.packetsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_in:S.deltaPacketsReceived}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_in:S.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_in:S.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_in:S.percentPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_in:S.KBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_in:S.deltaKBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_in:S.kbsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_in:R}},{ssrc:_,type:Me.VIDEO,value:{decoder_in:N}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_decode_frame_in:A.delta_ms_decode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_decoded_in:A.frames_decoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_decoded_in:A.total_decode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_sent_in:G.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_sent_in:G.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_sent_in:G.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_sent_in:G.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_in:W}}]}break}case Vr.OUTBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const _=o[ge.SSRC],g=wn(_,n,Ht.OUTBOUND);g&&(g.timestamp=n.timestamp);const d=wn(_,a,Ht.OUTBOUND);if(d&&(d.timestamp=a.timestamp),o[ge.MEDIA_TYPE]===ie.AUDIO){const A=o[ge.CODEC_ID]||null,S=Of(o,ie.AUDIO,g,d);return[{ssrc:_,type:Me.AUDIO,value:{codec_id_out:A}},{ssrc:_,type:Me.AUDIO,value:{total_packets_out:S.packetsSent}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_out:S.deltaPacketsSent}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_out:S.KBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_out:S.deltaKBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_out:S.kbsSent}}]}if(o[ge.MEDIA_TYPE]===ie.VIDEO){const A=o[ge.ENCODER_IMPLEMENTATION]||null,S=o[ge.CODEC_ID]||null,R=w1(o,g),N=Nf(o),H=C1(o),W=I1(o,g,d),G=Of(o,ie.VIDEO,g,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_out:S}},{ssrc:_,type:Me.VIDEO,value:{total_packets_out:G.packetsSent}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_out:G.deltaPacketsSent}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_out:G.KBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_out:G.deltaKBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_out:G.kbsSent}},{ssrc:_,type:Me.VIDEO,value:{encoder_out:A}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_encode_frame_out:R.delta_ms_encode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_encoded_out:R.frames_encoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_encoded_out:R.total_encode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_received_out:W.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_received_out:W.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_received_out:W.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_received_out:W.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_out:N}},{ssrc:_,type:Me.VIDEO,value:{limitation_out:H}}]}break}case Vr.MEDIA_SOURCE:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);break}case Vr.TRACK:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);break}case Vr.CODEC:const e=[];return Object.keys(n[ie.AUDIO]).forEach(_=>{const g=n[ie.AUDIO][_];if(g.codec_id_in===o[ge.ID]||g.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=R1(o);o[ge.ID]===g.codec_id_in?e.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_in:d}}):e.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_out:d}})}}),Object.keys(n[ie.VIDEO]).forEach(_=>{const g=n[ie.VIDEO][_];if(g.codec_id_in===o[ge.ID]||g.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=$1(o);o[ge.ID]===g.codec_id_in?e.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_in:d}}):e.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_out:d}})}}),e;case Vr.REMOTE_INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const _=o[ge.SSRC],g=wn(_,n,Ht.OUTBOUND),d=wn(_,a,Ht.OUTBOUND);if(o[ge.KIND]===ie.AUDIO){const A=xf(o,ie.AUDIO,d,g),S=Bu(o,ie.AUDIO,g),R=kf(o,ie.AUDIO,g,d);return[{ssrc:_,type:Me.AUDIO,value:{delta_rtt_ms_out:A.rtt}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_ms_out:A.totalRTT}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_measure_out:A.totalRTTMeasurements}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.AUDIO,value:{timestamp_out:o[ge.TIMESTAMP]}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_out:R.fractionLost}}]}if(o[ge.KIND]===ie.VIDEO){const A=xf(o,ie.VIDEO,d,g),S=Bu(o,ie.VIDEO,g),R=kf(o,ie.VIDEO,g,d);return[{ssrc:_,type:Me.VIDEO,value:{delta_rtt_ms_out:A.rtt}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_ms_out:A.totalRTT}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_measure_out:A.totalRTTMeasurements}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.VIDEO,value:{timestamp_out:o[ge.TIMESTAMP]}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_out:R.fractionLost}}]}break}}return[]},Vu=o=>o<0?1:o>100?4.5:1+.035*o+7/1e6*o*(o-60)*(100-o),D1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.INBOUND),_=wn(c,r,Ht.INBOUND),g=wn(c,a,Ht.INBOUND),d=[],A=[],S=e[n].percent_packets_lost_in,R=e[n].delta_jitter_ms_in,N=_&&_[n].delta_jitter_ms_in||null,H=g&&g[n].delta_jitter_ms_in||null,W=o.data.delta_rtt_connectivity_ms,G=r&&r.data.delta_rtt_connectivity_ms||null,K=a&&a.data.delta_rtt_connectivity_ms||null;W&&d.push(W),G&&d.push(G),K&&d.push(K),R&&A.push(R),r&&N&&A.push(N),a&&H&&A.push(H);const ae=d.length>0?mi(d):100,ee=A.length>0?mi(A):10,De=93.2-S,X=.18*De*De-27.9*De+1126.62,re=(ae+ee)/2,be=re-177.3<0?0:1,Ne=.024*re+.11*(re-177.3)*be,Q=X-Ne;return Vu(Q)},N1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.OUTBOUND),_=wn(c,r,Ht.OUTBOUND),g=wn(c,a,Ht.OUTBOUND),d=[],A=[],S=e[n].percent_packets_lost_out,R=e[n].delta_rtt_ms_out,N=_&&_[n].delta_rtt_ms_out||null,H=g&&g[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=g&&g[n].delta_jitter_ms_out||null,ae=o.data.delta_rtt_connectivity_ms,ee=r&&r.data.delta_rtt_connectivity_ms||null,De=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):ae&&d.push(ae),N?d.push(N):ee&&d.push(ee),H?d.push(H):De&&d.push(De),W&&A.push(W),r&&G&&A.push(G),a&&K&&A.push(K);const X=d.length>0?mi(d):100,re=A.length>0?mi(A):10,be=93.2-S,Ne=.18*be*be-27.9*be+1126.62,Q=(X+re)/2,ce=Q-177.3<0?0:1,me=.024*Q+.11*(Q-177.3)*ce,_e=Ne-me;return Vu(_e)},M1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.INBOUND),_=wn(c,r,Ht.INBOUND),g=wn(c,a,Ht.INBOUND),d=[],A=[],S=e[n].percent_packets_lost_in/100,R=e[n].delta_jitter_ms_in,N=_&&_[n].delta_jitter_ms_in||null,H=g&&g[n].delta_jitter_ms_in||null,W=o.data.delta_rtt_connectivity_ms,G=r&&r.data.delta_rtt_connectivity_ms||null,K=a&&a.data.delta_rtt_connectivity_ms||null;W&&d.push(W),G&&d.push(G),K&&d.push(K),R&&A.push(R),_&&N&&A.push(N),g&&H&&A.push(H);const ae=d.length>0?mi(d):100,ee=A.length>0?mi(A):10,De=0,X=19.8,re=29.7,be=30,Ne=(ae+ee)/2+be,Q=Ne-177.3<0?0:1,ce=.024*Ne+.11*(Ne-177.3)*Q,me=93.2-(De+X*Math.log(1+re*S)+ce);return Vu(me)},U1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.OUTBOUND),_=wn(c,r,Ht.OUTBOUND),g=wn(c,a,Ht.OUTBOUND),d=[],A=[],S=e[n].percent_packets_lost_out/100,R=e[n].delta_rtt_ms_out,N=_&&_[n].delta_rtt_ms_out||null,H=g&&g[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=g&&g[n].delta_jitter_ms_out||null,ae=o.data.delta_rtt_connectivity_ms,ee=r&&r.data.delta_rtt_connectivity_ms||null,De=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):ae&&d.push(ae),N?d.push(N):ee&&d.push(ee),H?d.push(H):De&&d.push(De),W&&A.push(W),_&&G&&A.push(G),g&&K&&A.push(K);const X=d.length>0?mi(d):100,re=A.length>0?mi(A):10,be=0,Ne=19.8,Q=29.7,ce=30,me=(X+re)/2+ce,_e=me-177.3<0?0:1,ue=.024*me+.11*(me-177.3)*_e,ye=93.2-(be+Ne*Math.log(1+Q*S)+ue);return Vu(ye)};class P1{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=p1(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new v1(n),this._state=Fs.IDLE,this.registerToPCEvents(),wa(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,a,c){const e=(d,A)=>d===ie.AUDIO?A===Vr.INBOUND_RTP?{...Ef}:{...Cf}:A===Vr.INBOUND_RTP?{...Af}:{...If},_=l1(r);_.pname=this._config.pname,_.call_id=this._config.cid,_.user_id=this._config.uid,_.count=r?r.count+1:1;let g=null;return n.forEach(d=>{!g&&d.timestamp&&(g=d.timestamp),k1(d,_,_.pname,c).forEach(A=>{if(A.value&&A.type)if(A.ssrc){let S=_[A.type][A.ssrc];S||(S=e(A.type,d.type),S.ssrc=A.ssrc,_[A.type][A.ssrc]=S),Object.keys(A.value).forEach(R=>{S[R]=A.value[R]})}else Object.keys(A.value).forEach(S=>{_[A.type][S]=A.value[S]})})}),_.timestamp=g,Object.keys(_[ie.AUDIO]).forEach(d=>{const A=_[ie.AUDIO][d];A.direction===Ht.INBOUND?(A.mos_emodel_in=D1(_,ie.AUDIO,r,a,A.ssrc),A.mos_in=M1(_,ie.AUDIO,r,a,A.ssrc)):(A.mos_emodel_out=N1(_,ie.AUDIO,r,a,A.ssrc),A.mos_out=U1(_,ie.AUDIO,r,a,A.ssrc))}),_}async takeReferenceStats(){return new Promise((n,r)=>{const a=Date.now();setTimeout(async()=>{try{const c=Date.now()-a,e=Date.now(),_=await this._config.pc.getStats(),g=this.analyze(_,null,null,null),d=Date.now();g.experimental.time_to_measure_ms=d-e,g.experimental.time_to_wait_ms=c,this._exporter.saveReferenceReport(g),Rt(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(c){r(c)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Fs.RUNNING||!this._config.pc)return Rt(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),a=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),c=Date.now();return a.experimental.time_to_measure_ms=c-n,this._exporter.addReport(a),Rt(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(n){return so(this._moduleName,`got error ${n}`),null}}async start(){Rt(this._moduleName,"starting"),this.state=Fs.RUNNING,this._startedTime=this._exporter.start(),Rt(this._moduleName,"started")}async mute(){this.state=Fs.MUTED,Rt(this._moduleName,"muted")}async unmute(){this.state=Fs.RUNNING,Rt(this._moduleName,"unmuted")}async stop(n){if(Rt(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Fs.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Rt(this._moduleName,"stopped")}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(this._moduleName,`registered callback '${n}'`)):so(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&qd(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&qd(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Rt(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,a,c){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:a,description:c})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{so(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const a=n.iceConnectionState;a===ml.CONNECTED||a===ml.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.DISCONNECTED||a===ml.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const a=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},n.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=n.getReceivers();if(r&&r.length>0){const a=r[0],{transport:c}=a;if(c){const{iceTransport:e}=c;e&&(e.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class L1{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||h1(),this._moduleName=this._id,wa(this._moduleName,"probe created"),this._config=n,this._collector=new P1(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):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(n){this._collector.state=n}addCustomEvent(n,r,a,c=new Date().toJSON()){this._collector.addCustomEvent(c,r,n,a)}get isRunning(){return this._collector.state===Fs.RUNNING}get isIdle(){return this._collector.state===Fs.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Fu(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const jn="engine ";class q1{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},wa(jn,`configured for probing every ${this._config.refreshEvery}ms`),wa(jn,`configured for starting after ${this._config.startAfter}ms`),wa(jn,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Rt(jn,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,r){if(!n)throw new Error("undefined peer connection");const a=c1(n,r,this._config),c=new L1(a);return this._probes.push(c),Rt(jn,`${this._probes.length} probes registered`),c}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===Fs.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(e=>e.start())},r=async()=>Promise.all(this._probes.map(e=>e.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,c=async()=>{const e=o1(),_=this._probes.filter(g=>g.isRunning);for(const g of _){const d=await g.collectStats();d&&e.probes.push(d),Rt(jn,`got probe ${g.id}`),await Rf(0)}return e.delta_time_to_measure_probes_ms=Sa(e.probes,"experimental","time_to_measure_ms"),e.delta_KBytes_in=Sa(e.probes,"data","delta_KBytes_in"),e.delta_KBytes_out=Sa(e.probes,"data","delta_KBytes_out"),e.delta_kbs_in=Sa(e.probes,"data","delta_kbs_in"),e.delta_kbs_out=Sa(e.probes,"data","delta_kbs_out"),e.total_time_decoded_in=Sa(e.probes,"video","total_time_decoded_in"),e.total_time_encoded_out=Sa(e.probes,"video","total_time_encoded_out"),e};for(Rt(jn,"starting to collect"),n(),Rt(jn,"generating reference reports..."),await r(),Rt(jn,"reference reports generated"),this._startedTime=Date.now();a();)if(Rt(jn,`wait ${this._config.refreshEvery}ms before collecting`),await Rf(this._config.refreshEvery),a()){Rt(jn,"collecting...");const e=Date.now(),_=await c(),g=Date.now();_.delta_time_consumed_to_measure_ms=g-e,this.fireOnReports(_),Rt(jn,"collected")}Rt(jn,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=a=>{this._probes.forEach(c=>{c.stop(a)})};wa(jn,"stop collecting"),r(n)}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(jn,`registered callback '${n}'`)):so(jn,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&qd(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const H1="interface ";class z1{constructor(n){this._config=d1(n),wa(H1,`welcome to ${this._config.name} version ${this._config.version}`),ZA(this._config.verbose||!1),this._engine=new q1(this._config)}setupLogLevel(n){e1(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,r){return this._engine.addNewProbe(n,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function F1(o,n){return Object.keys(o).filter(r=>n.includes(r)).reduce((r,a)=>{const c=a;return{...r,[c]:o[c]}},{})}const B1=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],V1={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class j1{constructor(n){this.intervals={},this.analysers={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}async start(n,r,a){r&&r.getTracks().length&&await this.beginCalculation(n,r,a)}stop(n){this.clearVolumeInterval(n),this.analysers[n]&&typeof this.analysers[n].disconnect=="function"&&(this.analysers[n].disconnect(),delete this.analysers[n])}clearVolumeInterval(n){this.intervals[n]&&(clearInterval(this.intervals[n]),delete this.intervals[n])}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{this.stop(n)}),this.intervals={},this.analysers={}}async beginCalculation(n,r,a){this.clearVolumeInterval(a);const c=n.createAnalyser(),e=n.createMediaStreamSource(r);c.smoothingTimeConstant=.8,c.fftSize=1024,e.connect(c),this.analysers[a]=c,this.intervals[a]=setInterval(()=>{const _=new Uint8Array(c.frequencyBinCount);c.getByteFrequencyData(_);let g=0;const d=_.length;for(let S=0;S<d;S++)g+=_[S];const A=g/d;this.onChangeFunction(a,A)},this.emitInterval)}}class G1{constructor(){this.resumePromise=null,this.context=new AudioContext}async getContext(){return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{throw this.resumePromise=null,n})),await this.resumePromise),this.context}}const ju={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},W1=0;class K1{constructor(n){var r;this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.isCallWaitingEnabled=!0,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.conferenceNodes={},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.vadSessions={},this.vadSessionsState={},this.vadIntervals={},this.vadMrsIntervals={},this.managedAudioContext=new G1,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new j1({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices(),this.processVADConfiguration(((r=this.context.options.configuration)==null?void 0:r.noiseReductionOptions)||{}),this.setupVADInstance()}setVADConfiguration(n){if(!this.MicVAD)throw new Error("VAD module is not provided in the initial configuration");const r=Object.keys(n);for(const a of r)this.noiseReduction[a]=n[a];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,r;const a=(r=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:r.vadModule;a&&a.MicVAD?(this.MicVAD=a.MicVAD,console.log("✅ VAD module loaded successfully")):this.noiseReduction.mode!=="disabled"&&(console.warn("⚠️ Noise reduction is enabled but VAD module is not provided. To use VAD features, please install @ricky0123/vad-web and pass it via configuration.noiseReductionOptions.vadModule option."),this.noiseReduction.mode="disabled")}processVADConfiguration(n){this.noiseReduction={mode:n.mode||"disabled",checkEveryMs:n.checkEveryMs||500,noiseCheckInterval:n.noiseCheckInterval||2e3,noiseThreshold:n.noiseThreshold||.004,vadConfig:n.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}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 hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(n=>!n.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return Tf()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(ju.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(ju.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),c=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(c),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}),a.getTracks().forEach(e=>e.stop())}catch(a){console.error(a)}}async cleanupConferenceNodes(n){const r=this.conferenceNodes[n];if(!r)return;let a=0;r.sources.forEach((_,g)=>{try{_.disconnect(),a++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting source ${g}:`,d)}});let c=0;r.destinations.forEach((_,g)=>{try{_.disconnect(),c++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${g}:`,d)}});let e=0;r.gains.forEach((_,g)=>{try{_.disconnect(),e++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${g}:`,d)}}),delete this.conferenceNodes[n]}setCallTime(n){const r={...n};delete r.callId,this.callTime={...this.callTime,[n.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const r={...this.callTime};delete r[n],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,r){this.timeIntervals={...this.timeIntervals,[n]:r}}removeTimeInterval(n){const r={...this.timeIntervals};r[n]&&(clearInterval(r[n]),delete r[n],this.timeIntervals={...r})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,r){this.context.emit("changeCallVolume",{callId:n,volume:r})}getNoiseReductionMode(){return this.noiseReduction.mode}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9*#]+$/g.test(r))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[n].sendDTMF(r)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const r=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:a}){const c=this.extendedCalls[n];if(!c)return;c._automaticHold=a??!1;const e=new Promise((_,g)=>{const d=setTimeout(()=>{g(new Error("Hold operation timeout"))},5e3),A=()=>{clearTimeout(d),c.putOnHoldTimestamp=r?Date.now():void 0,_()},S=R=>{clearTimeout(d),g(R)};try{r?(this.stopSessionVad(c._id),c.hold({},A)):c.unhold({},A)}catch(R){S(R)}});try{await e,this.updateCall(c);const _=Object.values(this.extendedCalls).filter(g=>g.roomId===c.roomId&&(r?n!==g._id:!0));_.length>1&&await this.doConference(_)}catch(_){throw console.error("Hold operation failed:",_),_}}holdCall(n,r=!1){return this.processHold({callId:n,automatic:r,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===W1).forEach(n=>this.terminateCall(n._id))}answerCall(n){const r=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",a=>{this.triggerAddStream(a,r)})}async moveCall(n,r){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:r}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=yf(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const r={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...r}},this.context.emit("updateRoom",{room:r,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const r=/answer-after=0/,a=n.request.getHeader("Call-Info");return a&&r.test(a)}addCall(n,r=!0){this.activeCalls={...this.activeCalls,[n._id]:yf(n)},this.extendedCalls[n._id]=n,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const r={...this.callStatus[n.callId]};n.isMoving!==void 0&&(r.isMoving=n.isMoving),n.isTransferring!==void 0&&(r.isTransferring=n.isTransferring),n.isMerging!==void 0&&(r.isMerging=n.isMerging),n.isTransferred!==void 0&&(r.isTransferred=n.isTransferred),this.callStatus={...this.callStatus,[n.callId]:{...r}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const r={...this.callStatus};delete r[n],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}async setupActiveStream(){const n=await Dd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n)}async getActiveStream(){const n=await Dd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:a})=>a===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async a=>{await this.setupActiveStream();const c=this.activeStream;a.connection.getSenders()[0].replaceTrack(c.getTracks()[0]),this.updateCall(a)}):await this.doConference(r)}async setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:c})=>c===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const a=r.filter(c=>c.roomId===this.currentActiveRoomId);a.length===1?r.forEach(c=>{var e;(e=c.audioTag)==null||e.setSinkId(n),this.updateCall(c)}):await this.doConference(a)}removeRoom(n){const r={...this.activeRooms},a={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}startNoiseMonitor({sessionId:n,stream:r,onNoiseDetected:a,onNoiseStop:c}){const e=new AudioContext,_=e.createMediaStreamSource(r.clone()),g=e.createAnalyser();g.fftSize=1024;const d=new Float32Array(g.fftSize);_.connect(g);const A=[];this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),this.vadIntervals[n]=null),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),this.vadMrsIntervals[n]=null),this.vadMrsIntervals[n]=setInterval(()=>{g.getFloatTimeDomainData(d);const S=KA(d);A.push(S);const R=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);A.length>R&&A.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[n]=setInterval(()=>{if(A.length===0)return;const S=A.reduce((H,W)=>H+W,0)/A.length,R=this.vadSessionsState[n],N=S>this.noiseReduction.noiseThreshold;R.isSpeaking||(N&&R.currentMode==="clean"?(R.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!0}),a()):!N&&R.currentMode==="noisy"&&(R.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!1}),c()))},this.noiseReduction.noiseCheckInterval)}async processVAD(n,r){const a=r.clone();this.stopSessionVad(n._id),this.vadSessionsState[n._id]={currentMode:"clean",isSpeaking:!1};const c=await this.managedAudioContext.getContext(),e=await YA(a,c,150);let _=!1;const g=await this.MicVAD.new({getStream:()=>new Promise(d=>d(a)),...V1,...this.noiseReduction.vadConfig,baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",onFrameProcessed:()=>{if(!_){if(_=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){n.connection.getSenders()[0]&&n.connection.getSenders()[0].replaceTrack(e.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:n._id,stream:a,onNoiseDetected:async()=>{var d;console.log("Replace track with Vad Controlled"),await((d=n.connection.getSenders()[0])==null?void 0:d.replaceTrack(e.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const d=n.connection.getSenders()[0];d&&d.track&&d.transport&&d.transport.state!=="closed"&&d.transport.state!=="failed"&&(console.log("Replace track with Original"),await d.replaceTrack(a.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var d;console.log("🎤 Speech started"),e.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((d=n.connection.getSenders()[0])==null||d.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!0},onSpeechEnd:()=>{var d;console.log("🛑 Speech end"),e.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((d=n.connection.getSenders()[0])==null||d.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!1}});this.vadSessions[n._id]&&(this.vadSessions[n._id].pause(),delete this.vadSessions[n._id]),this.vadSessions[n._id]=g,g.start()}stopSessionVad(n){this.vadSessions[n]&&(this.vadSessions[n].pause(),delete this.vadSessions[n]),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]),this.vadSessionsState[n]&&delete this.vadSessionsState[n]}async roomReconfigure(n){var r;if(n===void 0)return;const a=Object.values(this.extendedCalls).filter(e=>e.roomId===n),c=this.currentActiveRoomId===n;if(a.forEach((e,_)=>{if(e.audioTag){e.connection.getReceivers().forEach(d=>{d.track.enabled=!e.localMuted}),c&&this.muteReconfigure(e);const g=!c;e.audioTag.muted=g,this.updateCall(e)}}),a.length===0){this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n),this.deleteRoomIfEmpty(n);return}if(a.length===1&&!c){const e=a[0];e.isOnHold().local||await this.holdCall(e._id,!0),this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}if(a.length===1&&c){const e=a[0];e.isOnHold().local&&e._automaticHold&&await this.unholdCall(e._id);const _=(((r=e.connection)==null?void 0:r.getSenders())||[])[0];if(e.connection&&_)try{await this.setupActiveStream();const g=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(a[0],g);const d=g.getTracks();await _.replaceTrack(d[0]),this.muteReconfigure(e)}catch(g){console.error(g)}this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}a.length>1&&await this.doConference(a)}async doConference(n){if(n.length===0)return;const r=n[0].roomId,a=this.currentActiveRoomId===r;if(n.find(g=>g.roomId!==r))return;const c=await this.managedAudioContext.getContext();if(c.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${c.state}`);return}await this.cleanupConferenceNodes(r),this.conferenceNodes[r]={sources:new Map,destinations:new Map,gains:new Map};const e=this.conferenceNodes[r],_=new Map;n.forEach((g,d)=>{g&&g.connection&&g.connection.getReceivers().forEach((A,S)=>{var R,N,H;A.track.enabled=!g.localMuted;const W=(R=A.track)==null?void 0:R.id;(N=A.track)==null||N.readyState,(H=A.track)==null||H.kind;const G=`${g._id}-${W}`;A.track&&A.track.readyState==="live"&&_.set(G,A.track)})}),await this.setupActiveStream(),await XA.forEach(n,async(g,d)=>{if(!g||!g.connection)return;const A=c.createMediaStreamDestination();e.destinations.set(g._id,A);let S=0;if(_.forEach((H,W)=>{if(!W.startsWith(g._id))try{const G=c.createMediaStreamSource(new MediaStream([H])),K=c.createGain(),ae=`${g._id}-${W}`;G.connect(K),K.connect(A),e.sources.set(ae,G),e.gains.set(ae,K),S++}catch(G){console.error(G)}}),a&&this.activeStreamValue)try{const H=this.activeStream,W=c.createMediaStreamSource(H),G=c.createGain(),K=`${g._id}-local`;W.connect(G),G.connect(A),e.sources.set(K,W),e.gains.set(K,G)}catch(H){console.error(H)}else a&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${g._id}`);const R=g.connection.getSenders()[0],N=A.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(g,A.stream),R&&N[0])try{await R.replaceTrack(N[0]),this.muteReconfigure(g)}catch(H){console.error(H)}})}processCallerMute(n,r){const a=this.extendedCalls[n];a&&a.connection.getReceivers().length&&(a.localMuted=r,a.connection.getReceivers().forEach(c=>{c.track.enabled=!r}),this.updateCall(a))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status===4?r.terminate({status_code:603,reason_phrase:"Decline"}):r._status!==8&&r.terminate()}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[n];if(!a._is_confirmed&&!a._is_canceled){const c=`sip:${r}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${c}`]});return}this.updateCallStatus({callId:n,isTransferring:!0,isTransferred:!1}),a.refer(`sip:${r}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(a)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(e=>e.roomId===n);if(r.length!==2)return;const a=r[0],c=r[1];!a||!c||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:c._id,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a))}mergeCallByIds(n,r){const a=Object.values(this.extendedCalls).find(e=>e._id===n),c=Object.values(this.extendedCalls).find(e=>e._id===r);if(!a||!c)throw new Error("Call ID is not provided");this.updateCallStatus({callId:n,isMerging:!0}),this.updateCallStatus({callId:r,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a)}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}setCallWaiting(n){this.isCallWaitingEnabled=n,this.context.emit("changeIsCallWaiting",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const a=setInterval(()=>{const c={...this.callTime[n]},e=WA(c);this.setCallTime({callId:n,...e})},1e3);this.setTimeInterval(n,a)}async setActiveRoom(n){const r=this.currentActiveRoomId;n!==r&&(this.currentActiveRoomId=n,await this.roomReconfigure(r),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var r,a;const c=n.session;if(this.getActiveCalls[c.id]!==void 0)return;const e=this.getNewRoomId(),_={started:new Date,incomingInProgress:!1,roomId:e};if(c.direction==="incoming")this.context.logger.log("New incoming call from",(a=(r=c._remote_identity)==null?void 0:r._uri)==null?void 0:a._user),_.incomingInProgress=!0,this.context.subscribe(Br.CALL_CONFIRMED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.startCallTimer(c.id))}),this.context.subscribe(Br.CALL_FAILED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.deleteRoomIfEmpty(e))});else if(c.direction==="outgoing"){const S=R=>{R.response&&R.response.status_code===JA.SESSION_PROGRESS&&(this.startCallTimer(c.id),c.off("progress",S))};c.on("progress",S),c.once("confirmed",()=>{this.startCallTimer(c.id)})}const g=c,d=this.hasAutoAnswerHeaders(n),A=g.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);g.roomId=e,g.localMuted=!1,g.autoAnswer=A,A?this.addCall(g,!1):this.addCall(g),this.addCallStatus(c.id),this.addRoom(_),A&&this.answerCall(g._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const a={...this.extendedCalls};delete a[n],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];if(!r)return;this.stopVUMeter("origin"),this.stopVUMeter(n._id);const a=r.roomId;this.removeCall(n._id),this.roomReconfigure(a).then(()=>{}).catch(c=>{console.error("Error reconfiguring room after call removal:",c)})}shouldTerminateNewSession(n){if(n.session.direction==="outgoing")return!1;const r=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||r}async newRTCSessionCallback(n){const r=n.session;if(this.shouldTerminateNewSession(n)){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}this.context.triggerListener({listenerType:Br.NEW_CALL,session:r,event:n}),r.on("ended",c=>{var e,_,g;if(this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_ENDED,session:r,event:c}),r.connection){const A=r.connection.connectionState;(A==="closed"||A==="disconnected")&&this.context.emit("connectionStateChange",{session:r,connectionState:A})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(A=>A.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("progress",c=>{var e,_;this.context.logger.log("Session in progress for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_PROGRESS,session:r,event:c})}),r.on("failed",c=>{var e,_,g;if(this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_FAILED,session:r,event:c}),r.connection){const A=r.connection.connectionState;(A==="closed"||A==="disconnected")&&this.context.emit("connectionStateChange",{session:r,connectionState:A})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(A=>A.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("confirmed",c=>{var e,_;this.context.logger.log("Session confirmed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_CONFIRMED,session:r,event:c}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)});const a=c=>{c&&c.addEventListener("connectionstatechange",e=>{this.context.emit("connectionStateChange",{session:r,connectionState:c.connectionState})})};if(r.connection&&a(r.connection),r.on("peerconnection",({peerconnection:c})=>{a(c)}),await this.setupCall(n),r.direction==="outgoing"){const c=this.getActiveCalls[r.id].roomId;await this.setActiveRoom(c)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=n,this.updateCall(r))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(ju.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(ju.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const r={...n};delete r.callId,this.callMetrics={...this.callMetrics,[n.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const r={...this.callMetrics};delete r[n],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const r=new z1(this.metricConfig),a=r.createProbe(n.connection,{cid:n._id}),c=[];let e;a.onreport=_=>{Object.entries(_.audio).forEach(([A,S])=>{S.direction==="inbound"&&!c.includes(A)&&(c.push(A),e=A)});const g=_.audio[e];if(!g)return;const d=F1(g,B1);d.callId=n._id,this.setCallMetrics(d)},this.context.subscribe(Br.CALL_ENDED,_=>{_._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}async setupVUMeter(n,r){await this.VUMeter.start(await this.managedAudioContext.getContext(),n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){try{const n=Date.now(),r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((a,c)=>{a.stop()}),this.initialStreamValue=null),this.initialStreamValue=r}catch(n){throw n}}async triggerAddStream(n,r){const a=this.muteWhenJoin||this.isMuted;this.setIsMuted(a),this.initialStreamValue||await this.setupStream();const c=await this.managedAudioContext.getContext(),e=await Dd(c,this.initialStreamValue,this.microphoneInputLevel*2),_=this.isMuted||this.muteWhenJoin;e.getTracks().forEach(A=>{A.enabled=!_}),await this.setActiveStream(e),await r.connection.getSenders()[0].replaceTrack(e.getTracks()[0]);const g=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(A=>A.audioTag&&A.audioTag.id===r._id)&&kA(g,r,this.selectedOutputDevice,this.speakerVolume);const d=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!d),await this.setupVUMeter(g,r._id),this.getCallQuality(r),this.updateCall(r),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r,e)}initCall(n,r,a=!1){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const c=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=c.id,r&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:c.id,roomId:this.currentActiveRoomId}),a)){const e=Object.values(this.extendedCalls).filter(_=>_.roomId===this.currentActiveRoomId&&_._id!==c.id);for(const _ of e)this.holdCall(_._id,!0)}c.connection.addEventListener("track",e=>{this.triggerAddStream(e,c)})}async processRoomChange({callId:n,roomId:r}){const a=this.extendedCalls[n];if(!a)return;const c=a.roomId;a.roomId=r,this.updateCall(a),await this.roomReconfigure(c),await this.roomReconfigure(r)}}class Y1{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n,r){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,r,this.sipOptions)}stop(n={}){this.context.terminateJanusSessions(n)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(n){this.context.changeMediaConstraints(n)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class X1{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const r=this.extendedMessages[n];this.updateMSRPSession(r)}updateMSRPSession(n){this.activeMessages[n._id]=vf(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:vf(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const a=this.msrpHistory[r.id]||[];a.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...a]},this.context.emit("newMSRPMessage",{message:n,session:r})}messageTerminate(n){const r=this.extendedMessages[n];r._status!==8&&r.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const r=n;this.addMMSRPSession(r)}triggerMSRPListener({listenerType:n,session:r,event:a}){const c=this.context.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const a={...this.extendedMessages};delete a[n],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){n.session._id||(n.session._id=n.request.call_id+n.request.from._parameters.tag);const r=n.session;r.on("ended",a=>{this.triggerMSRPListener({listenerType:Br.CALL_ENDED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("failed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_FAILED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_CONFIRMED,session:r,event:a}),this.updateMSRPSession(r)}),r.on("newMessage",a=>{this.addMSRPMessage(a,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,a){if(n.length===0)return console.error("Target must be a valid string");const c=this.context.startMSRP(n,a);c.on("active",()=>{this.addMessageSession(c),c.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const a=this.extendedMessages[n];if(!a)throw new Error(`MSRP session with id ${n} doesn't exist!`);a.sendMSRP(r)}}const Gu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Mf{constructor(n){this.opensips=null,this.session=null,this.name=null,this.name=n}setOpensips(n){this.opensips=n}setSession(n){this.session=n}kill(){this.opensips.kill(this.name)}}class J1 extends Mf{constructor(n,r){super(n),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=r}connect(n={}){this.opaqueId=this.session.generateOpaqueId();const r=kt.cloneArray(n.extraHeaders),a={from_tag:this.session._from_tag};n.fromUserName&&(a.from_uri=new ba("sip",n.fromUserName,this.session._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(a.from_display_name=n.fromDisplayName),r.push(`Contact: ${this.session._contact}`),r.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&r.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new On.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,r),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let n;this._connection.onicecandidate=r=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||r.candidate&&(this._candidates.push(r.candidate),clearTimeout(n),n=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(n){n.forEach(r=>{this._connection.addTrack(r)})}async _sendInitialRequest(){const n=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const r={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(r),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},c=JSON.stringify(a);this._request.body=c,n.send()}_receiveInviteResponse(n){if(this._publisherSubscribeSent||!n.body)return;const r=JSON.parse(n.body);this.handleId=r.data.id;const a={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},c=[this.session.getPTypeHeader(ir.PUBLISHER)];this.session.sendRequest(oe.SUBSCRIBE,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{var _,g,d,A;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((g=(_=S.plugindata)==null?void 0:_.data)==null?void 0:g.videoroom)==="joined"&&this.session.myFeedList.push(S.plugindata.data.id),(A=(d=S.plugindata)==null?void 0:d.data)!=null&&A.publishers&&this.session.receivePublishers(S)}catch(S){console.error(S)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(n){const r=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handleId,session_id:this.session.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...n},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...r]},c=["Content-Type: application/json",this.session.getPTypeHeader(ir.ICE)];this.session.sendRequest(oe.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{this._configureSent=!0;const _=e.data.split(`\r
|
|
159
159
|
`),g=_[_.length-1],d=JSON.parse(g);await this._connection.setRemoteDescription(d.jsep),this._candidates=[]}}})}_sendDetach(){const n={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},r=[this.session.getPTypeHeader(ir.DETACH)];this.session.sendRequest(oe.INFO,{extraHeaders:r,body:JSON.stringify(n)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const n=this._connection.getSenders();n.forEach(r=>{const a=r.track;a&&a.stop()}),n.forEach(r=>{this._connection.removeTrack(r)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Q1 extends Mf{constructor(n,r,a={}){super(n),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=r}start(n){return n}stop(){throw new Error("stop method is not implemented")}async process(n){if(this.immediate){const r=await this.start(n);return this.running=!0,r}return n}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class Z1 extends CA{constructor(n,r){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const a={...n.configuration,sockets:n.socketInterfaces.map(c=>new GA.WebSocketInterface(c))};super(a),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.activeConnection=!1,this.waitingForSessionHangup=!1,this.waitingForSessionTimeout=null,this.reconnectionAttemptsLimit=1/0,this.reconnectionAttemptsCounter=0,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],n.pnExtraHeaders&&Object.keys(n.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(n.pnExtraHeaders),this.options=n,this.modules=n.modules,n.configuration.reconnectionAttemptsLimit&&(this.reconnectionAttemptsLimit=n.configuration.reconnectionAttemptsLimit),r&&DA(r)&&(this.logger=r)}isWaitingForSessionHangup(){return this.waitingForSessionHangup}stopSessionAfterWaiting(){this.setInitialized(!1),this.waitingForSessionHangup=!1,clearTimeout(this.waitingForSessionTimeout),this.waitingForSessionTimeout=null,this.activeConnection&&this.reconnect()}get hasActiveSessions(){return this.modules.includes(Gu.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(n,r){return super.on(n,r)}off(n,r){return super.off(n,r)}emit(n,r){return super.emit(n,r)}get sipDomain(){return this.options.sipDomain}use(n){if(this.newStreamPlugins.find(r=>r.name===n.name)||this.processStreamPlugins.find(r=>r.name===n.name))throw new Error(`Plugin with name ${n.name} already exists`);if(n instanceof J1)n.setOpensips(this),this.newStreamPlugins.push(n);else if(n instanceof Q1)n.setOpensips(this),this.processStreamPlugins.push(n);else throw new Error("Wrong plugin instance")}getPlugin(n){return this.newStreamPlugins.find(r=>r.name===n)||this.processStreamPlugins.find(r=>r.name===n)}reconnect(){if(this.reconnectionAttemptsCounter<this.reconnectionAttemptsLimit){const n=5e3*Math.pow(2,this.reconnectionAttemptsCounter);this.reconnectionAttemptsCounter++,setTimeout(this.start.bind(this),n)}else this.emit("reconnectionAttemptsLimitReached",void 0)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Gu.AUDIO)&&(this.audio=new K1(this)),this.modules.includes(Gu.MSRP)&&(this.msrp=new X1(this)),this.modules.includes(Gu.VIDEO)&&(this.video=new Y1(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.setReconnecting(!1),this.activeConnection=!0,this.waitingForSessionHangup=!1,this.reconnectionAttemptsCounter=0}),this.on(this.disconnectedEventName,()=>{this.setConnected(!1),!this.isReconnecting&&(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.hasActiveSessions?(this.waitingForSessionHangup=!0,this.stop(!1),this.waitingForSessionTimeout=setTimeout(()=>{this.terminateAllSessions(),this.setInitialized(!1),this.waitingForSessionHangup=!1,this.activeConnection&&this.reconnect()},12e5)):(this.stop(),this.setInitialized(!1),this.activeConnection&&this.reconnect()))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(n,r){const a=!this.listenersList[n]||!this.listenersList[n].length?[r]:[...this.listenersList[n],r];this.listenersList={...this.listenersList,[n]:a}}removeIListener(n){const r={...this.listenersList};delete r[n],this.listenersList={...r}}triggerListener({listenerType:n,session:r,event:a}){const c=this.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}setConnected(n){this.connected=n,this.emit("connection",n)}setReconnecting(n){this.isReconnecting=n,this.emit("reconnecting",n)}}var Gn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function eI(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var Hd={},Tl={};Object.defineProperty(Tl,"__esModule",{value:!0}),Tl.baseAssetPath=void 0;const Uf=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let Pf="/";Uf&&(Pf=Uf.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),Tl.baseAssetPath=Pf;var io={};Object.defineProperty(io,"__esModule",{value:!0}),io.defaultModelFetcher=void 0;const tI=o=>fetch(o).then(n=>n.arrayBuffer());io.defaultModelFetcher=tI;var us={},ao={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.log=o.LOG_PREFIX=void 0,o.LOG_PREFIX="[VAD]";const n=["error","debug","warn"];function r(c){return(...e)=>{console[c](o.LOG_PREFIX,...e)}}const a=n.reduce((c,e)=>(c[e]=r(e),c),{});o.log=a})(ao);var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.Message=void 0;var Lf;(function(o){o.AudioFrame="AUDIO_FRAME",o.SpeechStart="SPEECH_START",o.VADMisfire="VAD_MISFIRE",o.SpeechEnd="SPEECH_END",o.SpeechStop="SPEECH_STOP",o.SpeechRealStart="SPEECH_REAL_START",o.FrameProcessed="FRAME_PROCESSED"})(Lf||(Ea.Message=Lf={})),Object.defineProperty(us,"__esModule",{value:!0}),us.FrameProcessor=us.validateOptions=us.defaultFrameProcessorOptions=void 0;const bl=ao,Ca=Ea;us.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function nI(o){(o.positiveSpeechThreshold<0||o.positiveSpeechThreshold>1)&&bl.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(o.negativeSpeechThreshold<0||o.negativeSpeechThreshold>o.positiveSpeechThreshold)&&bl.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),o.preSpeechPadMs<0&&bl.log.error("preSpeechPadMs should be positive"),o.redemptionMs<0&&bl.log.error("redemptionMs should be positive"),o.minSpeechMs<0&&bl.log.error("minSpeechMs should be positive")}us.validateOptions=nI;const qf=o=>{const n=o.reduce((a,c)=>(a.push(a.at(-1)+c.length),a),[0]),r=new Float32Array(n.at(-1));return o.forEach((a,c)=>{const e=n[c];r.set(a,e)}),r};class rI{constructor(n,r,a,c){this.modelProcessFunc=n,this.modelResetFunc=r,this.options=a,this.msPerFrame=c,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=e=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(e):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=e=>{const _=this.audioBuffer;this.audioBuffer=[];const g=this.speaking;if(this.reset(),g)if(_.reduce((A,S)=>S.isSpeech?A+1:A,0)>=this.minSpeechFrames){const A=qf(_.map(S=>S.frame));e({msg:Ca.Message.SpeechEnd,audio:A})}else e({msg:Ca.Message.VADMisfire});return{}},this.process=async(e,_)=>{if(!this.active)return;const g=await this.modelProcessFunc(e),d=g.isSpeech>=this.options.positiveSpeechThreshold;if(_({probs:g,msg:Ca.Message.FrameProcessed,frame:e}),this.audioBuffer.push({frame:e,isSpeech:d}),d&&(this.speechFrameCount++,this.redemptionCounter=0),d&&!this.speaking&&(this.speaking=!0,_({msg:Ca.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,_({msg:Ca.Message.SpeechRealStart})),g.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const A=this.audioBuffer;if(this.audioBuffer=[],A.reduce((R,N)=>N.isSpeech?R+1:R,0)>=this.minSpeechFrames){const R=qf(A.map(N=>N.frame));_({msg:Ca.Message.SpeechEnd,audio:R})}else _({msg:Ca.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[],this.redemptionFrames=Math.floor(a.redemptionMs/this.msPerFrame),this.preSpeechPadFrames=Math.floor(a.preSpeechPadMs/this.msPerFrame),this.minSpeechFrames=Math.floor(a.minSpeechMs/this.msPerFrame),this.reset()}}us.FrameProcessor=rI;var Hf={};function oo(o){throw new Error('Could not dynamically require "'+o+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var zf={exports:{}};/*!
|
|
160
160
|
* ONNX Runtime Web v1.23.2
|
|
161
161
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|